]> Pileus Git - ~andy/gtk/blob - gtk/gtkcssprovider.c
API: cssprovider: Change parsing-error signal
[~andy/gtk] / gtk / gtkcssprovider.c
1 /* GTK - The GIMP Toolkit
2  * Copyright (C) 2010 Carlos Garnacho <carlosg@gnome.org>
3  *
4  * This library is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Lesser General Public
6  * License as published by the Free Software Foundation; either
7  * version 2 of the License, or (at your option) any later version.
8  *
9  * This library is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * Lesser General Public License for more details.
13  *
14  * You should have received a copy of the GNU Lesser General Public
15  * License along with this library; if not, write to the
16  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
17  * Boston, MA 02111-1307, USA.
18  */
19
20 #include "config.h"
21
22 #include <string.h>
23 #include <stdlib.h>
24
25 #include <gdk-pixbuf/gdk-pixbuf.h>
26 #include <cairo-gobject.h>
27
28 #include "gtkcssproviderprivate.h"
29
30 #include "gtkcssparserprivate.h"
31 #include "gtkcsssectionprivate.h"
32 #include "gtkcssselectorprivate.h"
33 #include "gtksymboliccolor.h"
34 #include "gtkstyleprovider.h"
35 #include "gtkstylecontextprivate.h"
36 #include "gtkstylepropertiesprivate.h"
37 #include "gtkstylepropertyprivate.h"
38 #include "gtkbindings.h"
39 #include "gtkmarshalers.h"
40 #include "gtkprivate.h"
41 #include "gtkintl.h"
42
43 /**
44  * SECTION:gtkcssprovider
45  * @Short_description: CSS-like styling for widgets
46  * @Title: GtkCssProvider
47  * @See_also: #GtkStyleContext, #GtkStyleProvider
48  *
49  * GtkCssProvider is an object implementing the #GtkStyleProvider interface.
50  * It is able to parse <ulink url="http://www.w3.org/TR/CSS2">CSS</ulink>-like
51  * input in order to style widgets.
52  *
53  * <refsect2 id="gtkcssprovider-files">
54  * <title>Default files</title>
55  * <para>
56  * An application can cause GTK+ to parse a specific CSS style sheet by
57  * calling gtk_css_provider_load_from_file() and adding the provider with
58  * gtk_style_context_add_provider() or gtk_style_context_add_provider_for_screen().
59  * In addition, certain files will be read when GTK+ is initialized. First,
60  * the file <filename><envar>$XDG_CONFIG_HOME</envar>/gtk-3.0/gtk.css</filename>
61  * is loaded if it exists. Then, GTK+ tries to load
62  * <filename><envar>$HOME</envar>/.themes/<replaceable>theme-name</replaceable>/gtk-3.0/gtk.css</filename>,
63  * falling back to
64  * <filename><replaceable>datadir</replaceable>/share/themes/<replaceable>theme-name</replaceable>/gtk-3.0/gtk.css</filename>,
65  * where <replaceable>theme-name</replaceable> is the name of the current theme
66  * (see the #GtkSettings:gtk-theme-name setting) and <replaceable>datadir</replaceable>
67  * is the prefix configured when GTK+ was compiled, unless overridden by the
68  * <envar>GTK_DATA_PREFIX</envar> environment variable.
69  * </para>
70  * </refsect2>
71  * <refsect2 id="gtkcssprovider-stylesheets">
72  * <title>Style sheets</title>
73  * <para>
74  * The basic structure of the style sheets understood by this provider is
75  * a series of statements, which are either rule sets or '@-rules', separated
76  * by whitespace.
77  * </para>
78  * <para>
79  * A rule set consists of a selector and a declaration block, which is
80  * a series of declarations enclosed in curly braces ({ and }). The
81  * declarations are separated by semicolons (;). Multiple selectors can
82  * share the same declaration block, by putting all the separators in
83  * front of the block, separated by commas.
84  * </para>
85  * <example><title>A rule set with two selectors</title>
86  * <programlisting language="text">
87  * GtkButton, GtkEntry {
88  *     color: &num;ff00ea;
89  *     font: Comic Sans 12
90  * }
91  * </programlisting>
92  * </example>
93  * </refsect2>
94  * <refsect2 id="gtkcssprovider-selectors">
95  * <title>Selectors</title>
96  * <para>
97  * Selectors work very similar to the way they do in CSS, with widget class
98  * names taking the role of element names, and widget names taking the role
99  * of IDs. When used in a selector, widget names must be prefixed with a
100  * '&num;' character. The '*' character represents the so-called universal
101  * selector, which matches any widget.
102  * </para>
103  * <para>
104  * To express more complicated situations, selectors can be combined in
105  * various ways:
106  * <itemizedlist>
107  * <listitem><para>To require that a widget satisfies several conditions,
108  *   combine several selectors into one by concatenating them. E.g.
109  *   <literal>GtkButton&num;button1</literal> matches a GtkButton widget
110  *   with the name button1.</para></listitem>
111  * <listitem><para>To only match a widget when it occurs inside some other
112  *   widget, write the two selectors after each other, separated by whitespace.
113  *   E.g. <literal>GtkToolBar GtkButton</literal> matches GtkButton widgets
114  *   that occur inside a GtkToolBar.</para></listitem>
115  * <listitem><para>In the previous example, the GtkButton is matched even
116  *   if it occurs deeply nested inside the toolbar. To restrict the match
117  *   to direct children of the parent widget, insert a '>' character between
118  *   the two selectors. E.g. <literal>GtkNotebook > GtkLabel</literal> matches
119  *   GtkLabel widgets that are direct children of a GtkNotebook.</para></listitem>
120  * </itemizedlist>
121  * </para>
122  * <example>
123  * <title>Widget classes and names in selectors</title>
124  * <programlisting language="text">
125  * /&ast; Theme labels that are descendants of a window &ast;/
126  * GtkWindow GtkLabel {
127  *     background-color: &num;898989
128  * }
129  *
130  * /&ast; Theme notebooks, and anything that's within these &ast;/
131  * GtkNotebook {
132  *     background-color: &num;a939f0
133  * }
134  *
135  * /&ast; Theme combo boxes, and entries that
136  *  are direct children of a notebook &ast;/
137  * GtkComboBox,
138  * GtkNotebook > GtkEntry {
139  *     color: @fg_color;
140  *     background-color: &num;1209a2
141  * }
142  *
143  * /&ast; Theme any widget within a GtkBin &ast;/
144  * GtkBin * {
145  *     font: Sans 20
146  * }
147  *
148  * /&ast; Theme a label named title-label &ast;/
149  * GtkLabel&num;title-label {
150  *     font: Sans 15
151  * }
152  *
153  * /&ast; Theme any widget named main-entry &ast;/
154  * &num;main-entry {
155  *     background-color: &num;f0a810
156  * }
157  * </programlisting>
158  * </example>
159  * <para>
160  * Widgets may also define style classes, which can be used for matching.
161  * When used in a selector, style classes must be prefixed with a '.'
162  * character.
163  * </para>
164  * <para>
165  * Refer to the documentation of individual widgets to learn which
166  * style classes they define and see <xref linkend="gtkstylecontext-classes"/>
167  * for a list of all style classes used by GTK+ widgets.
168  * </para>
169  * <para>
170  * Note that there is some ambiguity in the selector syntax when it comes
171  * to differentiation widget class names from regions. GTK+ currently treats
172  * a string as a widget class name if it contains any uppercase characters
173  * (which should work for more widgets with names like GtkLabel).
174  * </para>
175  * <example>
176  * <title>Style classes in selectors</title>
177  * <programlisting language="text">
178  * /&ast; Theme all widgets defining the class entry &ast;/
179  * .entry {
180  *     color: &num;39f1f9;
181  * }
182  *
183  * /&ast; Theme spinbuttons' entry &ast;/
184  * GtkSpinButton.entry {
185  *     color: &num;900185
186  * }
187  * </programlisting>
188  * </example>
189  * <para>
190  * In complicated widgets like e.g. a GtkNotebook, it may be desirable
191  * to style different parts of the widget differently. To make this
192  * possible, container widgets may define regions, whose names
193  * may be used for matching in selectors.
194  * </para>
195  * <para>
196  * Some containers allow to further differentiate between regions by
197  * applying so-called pseudo-classes to the region. For example, the
198  * tab region in GtkNotebook allows to single out the first or last
199  * tab by using the :first-child or :last-child pseudo-class.
200  * When used in selectors, pseudo-classes must be prefixed with a
201  * ':' character.
202  * </para>
203  * <para>
204  * Refer to the documentation of individual widgets to learn which
205  * regions and pseudo-classes they define and see
206  * <xref linkend="gtkstylecontext-classes"/> for a list of all regions
207  * used by GTK+ widgets.
208  * </para>
209  * <example>
210  * <title>Regions in selectors</title>
211  * <programlisting language="text">
212  * /&ast; Theme any label within a notebook &ast;/
213  * GtkNotebook GtkLabel {
214  *     color: &num;f90192;
215  * }
216  *
217  * /&ast; Theme labels within notebook tabs &ast;/
218  * GtkNotebook tab GtkLabel {
219  *     color: &num;703910;
220  * }
221  *
222  * /&ast; Theme labels in the any first notebook
223  *  tab, both selectors are equivalent &ast;/
224  * GtkNotebook tab:nth-child(first) GtkLabel,
225  * GtkNotebook tab:first-child GtkLabel {
226  *     color: &num;89d012;
227  * }
228  * </programlisting>
229  * </example>
230  * <para>
231  * Another use of pseudo-classes is to match widgets depending on their
232  * state. This is conceptually similar to the :hover, :active or :focus
233  * pseudo-classes in CSS. The available pseudo-classes for widget states
234  * are :active, :prelight (or :hover), :insensitive, :selected, :focused
235  * and :inconsistent.
236  * </para>
237  * <example>
238  * <title>Styling specific widget states</title>
239  * <programlisting language="text">
240  * /&ast; Theme active (pressed) buttons &ast;/
241  * GtkButton:active {
242  *     background-color: &num;0274d9;
243  * }
244  *
245  * /&ast; Theme buttons with the mouse pointer on it,
246  *    both are equivalent &ast;/
247  * GtkButton:hover,
248  * GtkButton:prelight {
249  *     background-color: &num;3085a9;
250  * }
251  *
252  * /&ast; Theme insensitive widgets, both are equivalent &ast;/
253  * :insensitive,
254  * *:insensitive {
255  *     background-color: &num;320a91;
256  * }
257  *
258  * /&ast; Theme selection colors in entries &ast;/
259  * GtkEntry:selected {
260  *     background-color: &num;56f9a0;
261  * }
262  *
263  * /&ast; Theme focused labels &ast;/
264  * GtkLabel:focused {
265  *     background-color: &num;b4940f;
266  * }
267  *
268  * /&ast; Theme inconsistent checkbuttons &ast;/
269  * GtkCheckButton:inconsistent {
270  *     background-color: &num;20395a;
271  * }
272  * </programlisting>
273  * </example>
274  * <para>
275  * Widget state pseudoclasses may only apply to the last element
276  * in a selector.
277  * </para>
278  * <para>
279  * To determine the effective style for a widget, all the matching rule
280  * sets are merged. As in CSS, rules apply by specificity, so the rules
281  * whose selectors more closely match a widget path will take precedence
282  * over the others.
283  * </para>
284  * </refsect2>
285  * <refsect2 id="gtkcssprovider-rules">
286  * <title>&commat; Rules</title>
287  * <para>
288  * GTK+'s CSS supports the &commat;import rule, in order to load another
289  * CSS style sheet in addition to the currently parsed one.
290  * </para>
291  * <example>
292  * <title>Using the &commat;import rule</title>
293  * <programlisting language="text">
294  * &commat;import url ("path/to/common.css");
295  * </programlisting>
296  * </example>
297  * <para id="css-binding-set">
298  * In order to extend key bindings affecting different widgets, GTK+
299  * supports the &commat;binding-set rule to parse a set of bind/unbind
300  * directives, see #GtkBindingSet for the supported syntax. Note that
301  * the binding sets defined in this way must be associated with rule sets
302  * by setting the gtk-key-bindings style property.
303  * </para>
304  * <para>
305  * Customized key bindings are typically defined in a separate
306  * <filename>gtk-keys.css</filename> CSS file and GTK+ loads this file
307  * according to the current key theme, which is defined by the
308  * #GtkSettings:gtk-key-theme-name setting.
309  * </para>
310  * <example>
311  * <title>Using the &commat;binding rule</title>
312  * <programlisting language="text">
313  * &commat;binding-set binding-set1 {
314  *   bind "&lt;alt&gt;Left" { "move-cursor" (visual-positions, -3, 0) };
315  *   unbind "End";
316  * };
317  *
318  * &commat;binding-set binding-set2 {
319  *   bind "&lt;alt&gt;Right" { "move-cursor" (visual-positions, 3, 0) };
320  *   bind "&lt;alt&gt;KP_space" { "delete-from-cursor" (whitespace, 1)
321  *                          "insert-at-cursor" (" ") };
322  * };
323  *
324  * GtkEntry {
325  *   gtk-key-bindings: binding-set1, binding-set2;
326  * }
327  * </programlisting>
328  * </example>
329  * <para>
330  * GTK+ also supports an additional &commat;define-color rule, in order
331  * to define a color name which may be used instead of color numeric
332  * representations. Also see the #GtkSettings:gtk-color-scheme setting
333  * for a way to override the values of these named colors.
334  * </para>
335  * <example>
336  * <title>Defining colors</title>
337  * <programlisting language="text">
338  * &commat;define-color bg_color &num;f9a039;
339  *
340  * &ast; {
341  *     background-color: &commat;bg_color;
342  * }
343  * </programlisting>
344  * </example>
345  * </refsect2>
346  * <refsect2 id="gtkcssprovider-symbolic-colors">
347  * <title>Symbolic colors</title>
348  * <para>
349  * Besides being able to define color names, the CSS parser is also able
350  * to read different color expressions, which can also be nested, providing
351  * a rich language to define colors which are derived from a set of base
352  * colors.
353  * </para>
354  * <example>
355  * <title>Using symbolic colors</title>
356  * <programlisting language="text">
357  * &commat;define-color entry-color shade (&commat;bg_color, 0.7);
358  *
359  * GtkEntry {
360  *     background-color: @entry-color;
361  * }
362  *
363  * GtkEntry:focused {
364  *     background-color: mix (&commat;entry-color,
365  *                            shade (&num;fff, 0.5),
366  *                            0.8);
367  * }
368  * </programlisting>
369  * </example>
370  * <para>
371  *   The various ways to express colors in GTK+ CSS are:
372  * </para>
373  * <informaltable>
374  *   <tgroup cols="3">
375  *     <thead>
376  *       <row>
377  *         <entry>Syntax</entry>
378  *         <entry>Explanation</entry>
379  *         <entry>Examples</entry>
380  *       </row>
381  *     </thead>
382  *     <tbody>
383  *       <row>
384  *         <entry>rgb(@r, @g, @b)</entry>
385  *         <entry>An opaque color; @r, @g, @b can be either integers between
386  *                0 and 255 or percentages</entry>
387  *         <entry><literallayout>rgb(128, 10, 54)
388  * rgb(20%, 30%, 0%)</literallayout></entry>
389  *       </row>
390  *       <row>
391  *         <entry>rgba(@r, @g, @b, @a)</entry>
392  *         <entry>A translucent color; @r, @g, @b are as in the previous row,
393  *                @a is a floating point number between 0 and 1</entry>
394  *         <entry><literallayout>rgba(255, 255, 0, 0.5)</literallayout></entry>
395  *       </row>
396  *       <row>
397  *         <entry>&num;@xxyyzz</entry>
398  *         <entry>An opaque color; @xx, @yy, @zz are hexadecimal numbers
399  *                specifying @r, @g, @b variants with between 1 and 4
400  *                hexadecimal digits per component are allowed</entry>
401  *         <entry><literallayout>&num;ff12ab
402  * &num;f0c</literallayout></entry>
403  *       </row>
404  *       <row>
405  *         <entry>&commat;name</entry>
406  *         <entry>Reference to a color that has been defined with
407  *                &commat;define-color
408  *         </entry>
409  *         <entry>&commat;bg_color</entry>
410  *       </row>
411  *       <row>
412  *         <entry>mix(@color1, @color2, @f)</entry>
413  *         <entry>A linear combination of @color1 and @color2. @f is a
414  *                floating point number between 0 and 1.</entry>
415  *         <entry><literallayout>mix(&num;ff1e0a, &commat;bg_color, 0.8)</literallayout></entry>
416  *       </row>
417  *       <row>
418  *         <entry>shade(@color, @f)</entry>
419  *         <entry>A lighter or darker variant of @color. @f is a
420  *                floating point number.
421  *         </entry>
422  *         <entry>shade(&commat;fg_color, 0.5)</entry>
423  *       </row>
424  *       <row>
425  *         <entry>lighter(@color)</entry>
426  *         <entry>A lighter variant of @color</entry>
427  *       </row>
428  *       <row>
429  *         <entry>darker(@color)</entry>
430  *         <entry>A darker variant of @color</entry>
431  *       </row>
432  *     </tbody>
433  *   </tgroup>
434  * </informaltable>
435  * </refsect2>
436  * <refsect2 id="gtkcssprovider-gradients">
437  * <title>Gradients</title>
438  * <para>
439  * Linear or radial Gradients can be used as background images.
440  * </para>
441  * <para>
442  * A linear gradient along the line from (@start_x, @start_y) to
443  * (@end_x, @end_y) is specified using the syntax
444  * <literallayout>-gtk-gradient (linear,
445  *               @start_x @start_y, @end_x @end_y,
446  *               color-stop (@position, @color),
447  *               ...)</literallayout>
448  * where @start_x and @end_x can be either a floating point number between
449  * 0 and 1 or one of the special values 'left', 'right' or 'center', @start_y
450  * and @end_y can be either a floating point number between 0 and 1 or one
451  * of the special values 'top', 'bottom' or 'center', @position is a floating
452  * point number between 0 and 1 and @color is a color expression (see above).
453  * The color-stop can be repeated multiple times to add more than one color
454  * stop. 'from (@color)' and 'to (@color)' can be used as abbreviations for
455  * color stops with position 0 and 1, respectively.
456  * </para>
457  * <example>
458  * <title>A linear gradient</title>
459  * <inlinegraphic fileref="gradient1.png" format="PNG"/>
460  * <para>This gradient was specified with
461  * <literallayout>-gtk-gradient (linear,
462  *                left top, right bottom,
463  *                from(&commat;yellow), to(&commat;blue))</literallayout></para>
464  * </example>
465  * <example>
466  * <title>Another linear gradient</title>
467  * <inlinegraphic fileref="gradient2.png" format="PNG"/>
468  * <para>This gradient was specified with
469  * <literallayout>-gtk-gradient (linear,
470  *                0 0, 0 1,
471  *                color-stop(0, &commat;yellow),
472  *                color-stop(0.2, &commat;blue),
473  *                color-stop(1, &num;0f0))</literallayout></para>
474  * </example>
475  * <para>
476  * A radial gradient along the two circles defined by (@start_x, @start_y,
477  * @start_radius) and (@end_x, @end_y, @end_radius) is specified using the
478  * syntax
479  * <literallayout>-gtk-gradient (radial,
480  *                @start_x @start_y, @start_radius,
481  *                @end_x @end_y, @end_radius,
482  *                color-stop (@position, @color),
483  *                ...)</literallayout>
484  * where @start_radius and @end_radius are floating point numbers and
485  * the other parameters are as before.
486  * </para>
487  * <example>
488  * <title>A radial gradient</title>
489  * <inlinegraphic fileref="gradient3.png" format="PNG"/>
490  * <para>This gradient was specified with
491  * <literallayout>-gtk-gradient (radial,
492  *                center center, 0,
493  *                center center, 1,
494  *                from(&commat;yellow), to(&commat;green))</literallayout></para>
495  * </example>
496  * <example>
497  * <title>Another radial gradient</title>
498  * <inlinegraphic fileref="gradient4.png" format="PNG"/>
499  * <para>This gradient was specified with
500  * <literallayout>-gtk-gradient (radial,
501  *                0.4 0.4, 0.1,
502  *                0.6 0.6, 0.7,
503  *                color-stop (0, &num;f00),
504  *                color-stop (0.1, &num;a0f),
505  *                color-stop (0.2, &commat;yellow),
506  *                color-stop (1, &commat;green))</literallayout></para>
507  * </example>
508  * </refsect2>
509  * <refsect2 id="gtkcssprovider-shadows">
510  * <title>Text shadow</title>
511  * <para>
512  * A shadow list can be applied to text or symbolic icons, using the CSS3
513  * text-shadow syntax, as defined in
514  * <ulink url="http://www.w3.org/TR/css3-text/#text-shadow">the CSS3 specification</ulink>.
515  * </para>
516  * <para>
517  * A text shadow is specified using the syntax
518  * <literallayout>text-shadow: @horizontal_offset @vertical_offset [ @blur_radius ] @color</literallayout>
519  * The offset of the shadow is specified with the @horizontal_offset and @vertical_offset
520  * parameters. The optional blur radius is parsed, but it is currently not rendered by
521  * the GTK+ theming engine.
522  * </para>
523  * <para>
524  * To set multiple shadows on an element, you can specify a comma-separated list
525  * of shadow elements in the text-shadow property. Shadows are always rendered
526  * front-back, i.e. the first shadow specified is on top of the others. Shadows
527  * can thus overlay each other, but they can never overlay the text itself,
528  * which is always rendered on top of the shadow layer.
529  * </para>
530  * </refsect2>
531  * <refsect2>
532  * <title>Box shadow</title>
533  * <para>
534  * Themes can apply shadows on framed elements using the CSS3 box-shadow syntax,
535  * as defined in 
536  * <ulink url="http://www.w3.org/TR/css3-background/#the-box-shadow">the CSS3 specification</ulink>.
537  * </para>
538  * <para>
539  * A box shadow is specified using the syntax
540  * <literallayout>box-shadow: [ @inset ] @horizontal_offset @vertical_offset [ @blur_radius ] [ @spread ] @color</literallayout>
541  * A positive offset will draw a shadow that is offset to the right (down) of the box,
542  * a negative offset to the left (top). The optional spread parameter defines an additional
543  * distance to expand the shadow shape in all directions, by the specified radius.
544  * The optional blur radius parameter is parsed, but it is currently not rendered by
545  * the GTK+ theming engine.
546  * The inset parameter defines whether the drop shadow should be rendered inside or outside
547  * the box canvas. Only inset box-shadows are currently supported by the GTK+ theming engine,
548  * non-inset elements are currently ignored.
549  * </para>
550  * <para>
551  * To set multiple box-shadows on an element, you can specify a comma-separated list
552  * of shadow elements in the box-shadow property. Shadows are always rendered
553  * front-back, i.e. the first shadow specified is on top of the others, so they may
554  * overlap other boxes or other shadows.
555  * </para>
556  * </refsect2>
557  * <refsect2 id="gtkcssprovider-border-image">
558  * <title>Border images</title>
559  * <para>
560  * Images and gradients can also be used in slices for the purpose of creating
561  * scalable borders.
562  * For more information, see the CSS3 documentation for the border-image property,
563  * which can be found <ulink url="http://www.w3.org/TR/css3-background/#border-images">here</ulink>.
564  * </para>
565  * <inlinegraphic fileref="slices.png" format="PNG"/>
566  * <para>
567  * The parameters of the slicing process are controlled by
568  * four separate properties. Note that you can use the
569  * <literallayout>border-image</literallayout> shorthand property
570  * to set values for the three properties at the same time.
571  * </para>
572  * <para>
573  * <literallayout>border-image-source: url(@path)
574  * (or border-image-source: -gtk-gradient(...))</literallayout>:
575  * Specifies the source of the border image, and it can either
576  * be an URL or a gradient (see above).
577  * </para>
578  * <para>
579  * <literallayout>border-image-slice: @top @right @bottom @left</literallayout>
580  * The sizes specified by the @top, @right, @bottom and @left parameters
581  * are the offsets, in pixels, from the relevant edge where the image
582  * should be "cut off" to build the slices used for the rendering
583  * of the border.
584  * </para>
585  * <para>
586  * <literallayout>border-image-width: @top @right @bottom @left</literallayout>
587  * The sizes specified by the @top, @right, @bottom and @left parameters
588  * are inward distances from the border box edge, used to specify the
589  * rendered size of each slice determined by border-image-slice.
590  * If this property is not specified, the values of border-width will
591  * be used as a fallback.
592  * </para>
593  * <para>
594  * <literallayout>border-image-repeat: [stretch|repeat|round|space] ? 
595  * [stretch|repeat|round|space]</literallayout>
596  * Specifies how the image slices should be rendered in the area
597  * outlined by border-width.
598  * The default (stretch) is to resize the slice to fill in the whole 
599  * allocated area.
600  * If the value of this property is 'repeat', the image slice
601  * will be tiled to fill the area.
602  * If the value of this property is 'round', the image slice will
603  * be tiled to fill the area, and scaled to fit it exactly
604  * a whole number of times.
605  * If the value of this property is 'space', the image slice will
606  * be tiled to fill the area, and if it doesn't fit it exactly a whole
607  * number of times, the extra space is distributed as padding around 
608  * the slices.
609  * If two options are specified, the first one affects
610  * the horizontal behaviour and the second one the vertical behaviour.
611  * If only one option is specified, it affects both.
612  * </para>
613  * <example>
614  * <title>A border image</title>
615  * <inlinegraphic fileref="border1.png" format="PNG"/>
616  * <para>This border image was specified with
617  * <literallayout>url("gradient1.png") 10 10 10 10</literallayout>
618  * </para>
619  * </example>
620  * <example>
621  * <title>A repeating border image</title>
622  * <inlinegraphic fileref="border2.png" format="PNG"/>
623  * <para>This border image was specified with
624  * <literallayout>url("gradient1.png") 10 10 10 10 repeat</literallayout>
625  * </para>
626  * </example>
627  * <example>
628  * <title>A stretched border image</title>
629  * <inlinegraphic fileref="border3.png" format="PNG"/>
630  * <para>This border image was specified with
631  * <literallayout>url("gradient1.png") 10 10 10 10 stretch</literallayout>
632  * </para>
633  * </example>
634  * </refsect2>
635  * <refsect2 id="gtkcssprovider-transitions">
636  * <para>Styles can specify transitions that will be used to create a gradual
637  * change in the appearance when a widget state changes. The following
638  * syntax is used to specify transitions:
639  * <literallayout>@duration [s|ms] [linear|ease|ease-in|ease-out|ease-in-out] [loop]?</literallayout>
640  * The @duration is the amount of time that the animation will take for
641  * a complete cycle from start to end. If the loop option is given, the
642  * animation will be repated until the state changes again.
643  * The option after the duration determines the transition function from a
644  * small set of predefined functions.
645  * <figure><title>Linear transition</title>
646  * <graphic fileref="linear.png" format="PNG"/>
647  * </figure>
648  * <figure><title>Ease transition</title>
649  * <graphic fileref="ease.png" format="PNG"/>
650  * </figure>
651  * <figure><title>Ease-in-out transition</title>
652  * <graphic fileref="ease-in-out.png" format="PNG"/>
653  * </figure>
654  * <figure><title>Ease-in transition</title>
655  * <graphic fileref="ease-in.png" format="PNG"/>
656  * </figure>
657  * <figure><title>Ease-out transition</title>
658  * <graphic fileref="ease-out.png" format="PNG"/>
659  * </figure>
660  * </para>
661  * </refsect2>
662  * <refsect2 id="gtkcssprovider-properties">
663  * <title>Supported properties</title>
664  * <para>
665  * Properties are the part that differ the most to common CSS,
666  * not all properties are supported (some are planned to be
667  * supported eventually, some others are meaningless or don't
668  * map intuitively in a widget based environment).
669  * </para>
670  * <para>
671  * There is also a difference in shorthand properties, for
672  * example in common CSS it is fine to define a font through
673  * the different @font-family, @font-style, @font-size
674  * properties, meanwhile in GTK+'s CSS only the canonical
675  * @font property is supported.
676  * </para>
677  * <para>
678  * The currently supported properties are:
679  * </para>
680  * <informaltable>
681  *   <tgroup cols="4">
682  *     <thead>
683  *       <row>
684  *         <entry>Property name</entry>
685  *         <entry>Syntax</entry>
686  *         <entry>Maps to</entry>
687  *         <entry>Examples</entry>
688  *       </row>
689  *     </thead>
690  *     <tbody>
691  *       <row>
692  *         <entry>engine</entry>
693  *         <entry>engine-name</entry>
694  *         <entry>#GtkThemingEngine</entry>
695  *         <entry>engine: clearlooks;
696  *  engine: none; /&ast; use the default (i.e. builtin) engine) &ast;/ </entry>
697  *       </row>
698  *       <row>
699  *         <entry>background-color</entry>
700  *         <entry morerows="2">color (see above)</entry>
701  *         <entry morerows="7">#GdkRGBA</entry>
702  *         <entry morerows="7"><literallayout>background-color: &num;fff;
703  * color: &amp;color1;
704  * background-color: shade (&amp;color1, 0.5);
705  * color: mix (&amp;color1, &num;f0f, 0.8);</literallayout>
706  *         </entry>
707  *       </row>
708  *       <row>
709  *         <entry>color</entry>
710  *       </row>
711  *       <row>
712  *         <entry>border-top-color</entry>
713  *         <entry morerows="4">transparent|color (see above)</entry>
714  *       </row>
715  *       <row>
716  *         <entry>border-right-color</entry>
717  *       </row>
718  *       <row>
719  *         <entry>border-bottom-color</entry>
720  *       </row>
721  *       <row>
722  *         <entry>border-left-color</entry>
723  *       </row>
724  *       <row>
725  *         <entry>border-color</entry>
726  *         <entry>[transparent|color]{1,4}</entry>
727  *       </row>
728  *       <row>
729  *         <entry>font-family</entry>
730  *         <entry>@family [, @family]*</entry>
731  *         <entry>#gchararray</entry>
732  *         <entry>font-family: Sans, Arial;</entry>
733  *       </row>
734  *       <row>
735  *         <entry>font-style</entry>
736  *         <entry>[normal|oblique|italic]</entry>
737  *         <entry>#PANGO_TYPE_STYLE</entry>
738  *         <entry>font-style: italic;</entry>
739  *       </row>
740  *       <row>
741  *         <entry>font-variant</entry>
742  *         <entry>[normal|small-caps]</entry>
743  *         <entry>#PANGO_TYPE_VARIANT</entry>
744  *         <entry>font-variant: normal;</entry>
745  *       </row>
746  *       <row>
747  *         <entry>font-weight</entry>
748  *         <entry>[normal|bold|bolder|lighter|100|200|300|400|500|600|700|800|900]</entry>
749  *         <entry>#PANGO_TYPE_WEIGHT</entry>
750  *         <entry>font-weight: bold;</entry>
751  *       </row>
752  *       <row>
753  *         <entry>font-size</entry>
754  *         <entry>Font size in point</entry>
755  *         <entry>#gint</entry>
756  *         <entry>font-size: 13;</entry>
757  *       </row>
758  *       <row>
759  *         <entry>font</entry>
760  *         <entry>@family [@style] [@size]</entry>
761  *         <entry>#PangoFontDescription</entry>
762  *         <entry>font: Sans 15;</entry>
763  *       </row>
764  *       <row>
765  *         <entry>margin-top</entry>
766  *         <entry>integer</entry>
767  *         <entry>#gint</entry>
768  *         <entry>margin-top: 0;</entry>
769  *       </row>
770  *       <row>
771  *         <entry>margin-left</entry>
772  *         <entry>integer</entry>
773  *         <entry>#gint</entry>
774  *         <entry>margin-left: 1;</entry>
775  *       </row>
776  *       <row>
777  *         <entry>margin-bottom</entry>
778  *         <entry>integer</entry>
779  *         <entry>#gint</entry>
780  *         <entry>margin-bottom: 2;</entry>
781  *       </row>
782  *       <row>
783  *         <entry>margin-right</entry>
784  *         <entry>integer</entry>
785  *         <entry>#gint</entry>
786  *         <entry>margin-right: 4;</entry>
787  *       </row>
788  *       <row>
789  *         <entry>margin</entry>
790  *         <entry morerows="1"><literallayout>@width
791  * @vertical_width @horizontal_width
792  * @top_width @horizontal_width @bottom_width
793  * @top_width @right_width @bottom_width @left_width</literallayout>
794  *         </entry>
795  *         <entry morerows="1">#GtkBorder</entry>
796  *         <entry morerows="1"><literallayout>margin: 5;
797  * margin: 5 10;
798  * margin: 5 10 3;
799  * margin: 5 10 3 5;</literallayout>
800  *         </entry>
801  *       </row>
802  *       <row>
803  *         <entry>padding-top</entry>
804  *         <entry>integer</entry>
805  *         <entry>#gint</entry>
806  *         <entry>padding-top: 5;</entry>
807  *       </row>
808  *       <row>
809  *         <entry>padding-left</entry>
810  *         <entry>integer</entry>
811  *         <entry>#gint</entry>
812  *         <entry>padding-left: 5;</entry>
813  *       </row>
814  *       <row>
815  *         <entry>padding-bottom</entry>
816  *         <entry>integer</entry>
817  *         <entry>#gint</entry>
818  *         <entry>padding-bottom: 5;</entry>
819  *       </row>
820  *       <row>
821  *         <entry>padding-right</entry>
822  *         <entry>integer</entry>
823  *         <entry>#gint</entry>
824  *         <entry>padding-right: 5;</entry>
825  *       </row>
826  *       <row>
827  *         <entry>padding</entry>
828  *       </row>
829  *       <row>
830  *         <entry>background-image</entry>
831  *         <entry><literallayout>gradient (see above) or
832  * url(@path)</literallayout></entry>
833  *         <entry>#cairo_pattern_t</entry>
834  *         <entry><literallayout>-gtk-gradient (linear,
835  *                left top, right top,
836  *                from (&num;fff), to (&num;000));
837  * -gtk-gradient (linear, 0.0 0.5, 0.5 1.0,
838  *                from (&num;fff),
839  *                color-stop (0.5, &num;f00),
840  *                to (&num;000));
841  * -gtk-gradient (radial,
842  *                center center, 0.2,
843  *                center center, 0.8,
844  *                color-stop (0.0, &num;fff),
845  *                color-stop (1.0, &num;000));
846  * url ('background.png');</literallayout>
847  *         </entry>
848  *       </row>
849  *       <row>
850  *         <entry>border-top-width</entry>
851  *         <entry>integer</entry>
852  *         <entry>#gint</entry>
853  *         <entry>border-top-width: 5;</entry>
854  *       </row>
855  *       <row>
856  *         <entry>border-left-width</entry>
857  *         <entry>integer</entry>
858  *         <entry>#gint</entry>
859  *         <entry>border-left-width: 5;</entry>
860  *       </row>
861  *       <row>
862  *         <entry>border-bottom-width</entry>
863  *         <entry>integer</entry>
864  *         <entry>#gint</entry>
865  *         <entry>border-bottom-width: 5;</entry>
866  *       </row>
867  *       <row>
868  *         <entry>border-right-width</entry>
869  *         <entry>integer</entry>
870  *         <entry>#gint</entry>
871  *         <entry>border-right-width: 5;</entry>
872  *       </row>
873  *       <row>
874  *         <entry>border-width</entry>
875  *         <entry morerows="1">#GtkBorder</entry>
876  *         <entry morerows="1"><literallayout>border-width: 1;
877  * border-width: 1 2;
878  * border-width: 1 2 3;
879  * border-width: 1 2 3 5;</literallayout>
880  *         </entry>
881  *       </row>
882  *       <row>
883  *         <entry>border-radius</entry>
884  *         <entry>integer</entry>
885  *         <entry>#gint</entry>
886  *         <entry>border-radius: 5;</entry>
887  *       </row>
888  *       <row>
889  *         <entry>border-style</entry>
890  *         <entry>[none|solid|inset|outset]</entry>
891  *         <entry>#GtkBorderStyle</entry>
892  *         <entry>border-style: solid;</entry>
893  *       </row>
894  *       <row>
895  *         <entry>border-image</entry>
896  *         <entry><literallayout>border image (see above)</literallayout></entry>
897  *         <entry>internal use only</entry>
898  *         <entry><literallayout>border-image: url("/path/to/image.png") 3 4 3 4 stretch;
899  * border-image: url("/path/to/image.png") 3 4 4 3 repeat stretch;</literallayout>
900  *         </entry>
901  *       </row>
902  *       <row>
903  *         <entry>text-shadow</entry>
904  *         <entry>shadow list (see above)</entry>
905  *         <entry>#GtkTextShadow</entry>
906  *         <entry><literallayout>text-shadow: 1 1 0 blue, -4 -4 red;</literallayout></entry>
907  *       </row>
908  *       <row>
909  *         <entry>transition</entry>
910  *         <entry>transition (see above)</entry>
911  *         <entry>internal use only</entry>
912  *         <entry><literallayout>transition: 150ms ease-in-out;
913  * transition: 1s linear loop;</literallayout>
914  *         </entry>
915  *       </row>
916  *       <row>
917  *         <entry>gtk-key-bindings</entry>
918  *         <entry>binding set name list</entry>
919  *         <entry>internal use only</entry>
920  *         <entry><literallayout>gtk-bindings: binding1, binding2, ...;</literallayout>
921  *         </entry>
922  *       </row>
923  *     </tbody>
924  *   </tgroup>
925  * </informaltable>
926  * <para>
927  * GtkThemingEngines can register their own, engine-specific style properties
928  * with the function gtk_theming_engine_register_property(). These properties
929  * can be set in CSS like other properties, using a name of the form
930  * <literallayout>-<replaceable>namespace</replaceable>-<replaceable>name</replaceable></literallayout>, where <replaceable>namespace</replaceable> is typically
931  * the name of the theming engine, and <replaceable>name</replaceable> is the
932  * name of the property. Style properties that have been registered by widgets
933  * using gtk_widget_class_install_style_property() can also be set in this
934  * way, using the widget class name for <replaceable>namespace</replaceable>.
935  * </para>
936  * <example>
937  * <title>Using engine-specific style properties</title>
938  * <programlisting>
939  * * {
940  *     engine: clearlooks;
941  *     border-radius: 4;
942  *     -GtkPaned-handle-size: 6;
943  *     -clearlooks-colorize-scrollbar: false;
944  * }
945  * </programlisting>
946  * </example>
947  * </refsect2>
948  */
949
950 typedef struct GtkCssRuleset GtkCssRuleset;
951 typedef struct _GtkCssScanner GtkCssScanner;
952 typedef enum ParserScope ParserScope;
953 typedef enum ParserSymbol ParserSymbol;
954
955 struct GtkCssRuleset
956 {
957   GtkCssSelector *selector;
958   GHashTable *widget_style;
959   GHashTable *style;
960
961   guint has_inherit :1;
962 };
963
964 struct _GtkCssScanner
965 {
966   GtkCssProvider *provider;
967   GtkCssParser *parser;
968   GtkCssSection *section;
969   GtkCssScanner *parent;
970   GFile *file;
971   GFile *base;
972   GSList *state;
973 };
974
975 struct _GtkCssProviderPrivate
976 {
977   GScanner *scanner;
978
979   GHashTable *symbolic_colors;
980
981   GArray *rulesets;
982 };
983
984 enum ParserScope {
985   SCOPE_SELECTOR,
986   SCOPE_PSEUDO_CLASS,
987   SCOPE_NTH_CHILD,
988   SCOPE_DECLARATION,
989   SCOPE_VALUE,
990   SCOPE_BINDING_SET
991 };
992
993 /* Extend GtkStateType, since these
994  * values are also used as symbols
995  */
996 enum ParserSymbol {
997   /* Scope: pseudo-class */
998   SYMBOL_NTH_CHILD = GTK_STATE_FOCUSED + 1,
999   SYMBOL_FIRST_CHILD,
1000   SYMBOL_LAST_CHILD,
1001   SYMBOL_SORTED_CHILD,
1002
1003   /* Scope: nth-child */
1004   SYMBOL_NTH_CHILD_EVEN,
1005   SYMBOL_NTH_CHILD_ODD,
1006   SYMBOL_NTH_CHILD_FIRST,
1007   SYMBOL_NTH_CHILD_LAST
1008 };
1009
1010 enum {
1011   PARSING_ERROR,
1012   LAST_SIGNAL
1013 };
1014
1015 static guint css_provider_signals[LAST_SIGNAL] = { 0 };
1016
1017 static void gtk_css_provider_finalize (GObject *object);
1018 static void gtk_css_style_provider_iface_init (GtkStyleProviderIface *iface);
1019
1020 static gboolean
1021 gtk_css_provider_load_internal (GtkCssProvider *css_provider,
1022                                 GtkCssScanner  *scanner,
1023                                 GFile          *file,
1024                                 const char     *data,
1025                                 GError        **error);
1026
1027 GQuark
1028 gtk_css_provider_error_quark (void)
1029 {
1030   return g_quark_from_static_string ("gtk-css-provider-error-quark");
1031 }
1032
1033 G_DEFINE_TYPE_EXTENDED (GtkCssProvider, gtk_css_provider, G_TYPE_OBJECT, 0,
1034                         G_IMPLEMENT_INTERFACE (GTK_TYPE_STYLE_PROVIDER,
1035                                                gtk_css_style_provider_iface_init));
1036
1037 static void
1038 gtk_css_provider_parsing_error (GtkCssProvider  *provider,
1039                                 GtkCssSection   *section,
1040                                 const GError    *error)
1041 {
1042   /* Only emit a warning when we have no error handlers. This is our
1043    * default handlers. And in this case erroneous CSS files are a bug
1044    * and should be fixed.
1045    * Note that these warnings can also be triggered by a broken theme
1046    * that people installed from some weird location on the internets.
1047    */
1048   if (!g_signal_has_handler_pending (provider,
1049                                      css_provider_signals[PARSING_ERROR],
1050                                      0,
1051                                      TRUE))
1052     {
1053       GFileInfo *info;
1054       GFile *file;
1055       const char *path;
1056
1057       file = gtk_css_section_get_file (section);
1058       if (file)
1059         {
1060           GFileInfo *info = g_file_query_info (file, G_FILE_ATTRIBUTE_STANDARD_DISPLAY_NAME, 0, NULL, NULL);
1061
1062           if (info)
1063             path = g_file_info_get_display_name (info);
1064           else
1065             path = "<broken file>";
1066         }
1067       else
1068         {
1069           info = NULL;
1070           path = "<data>";
1071         }
1072
1073       g_warning ("Theme parsing error: %s:%u:%u: %s",
1074                  path,
1075                  gtk_css_section_get_end_line (section) + 1,
1076                  gtk_css_section_get_end_position (section),
1077                  error->message);
1078
1079       if (info)
1080         g_object_unref (info);
1081     }
1082 }
1083
1084 static void
1085 gtk_css_provider_class_init (GtkCssProviderClass *klass)
1086 {
1087   GObjectClass *object_class = G_OBJECT_CLASS (klass);
1088
1089   /**
1090    * GtkCssProvider::parsing-error:
1091    * @provider: the provider that had a parsing error
1092    * @section: section the error happened in
1093    * @error: The parsing error
1094    *
1095    * Signals that a parsing error occured. the @path, @line and @position
1096    * describe the actual location of the error as accurately as possible.
1097    *
1098    * Parsing errors are never fatal, so the parsing will resume after
1099    * the error. Errors may however cause parts of the given
1100    * data or even all of it to not be parsed at all. So it is a useful idea
1101    * to check that the parsing succeeds by connecting to this signal.
1102    *
1103    * Note that this signal may be emitted at any time as the css provider
1104    * may opt to defer parsing parts or all of the input to a later time
1105    * than when a loading function was called.
1106    */
1107   css_provider_signals[PARSING_ERROR] =
1108     g_signal_new (I_("parsing-error"),
1109                   G_TYPE_FROM_CLASS (object_class),
1110                   G_SIGNAL_RUN_LAST,
1111                   G_STRUCT_OFFSET (GtkCssProviderClass, parsing_error),
1112                   NULL, NULL,
1113                   _gtk_marshal_VOID__BOXED_BOXED,
1114                   G_TYPE_NONE, 2, GTK_TYPE_CSS_SECTION, G_TYPE_ERROR);
1115
1116   object_class->finalize = gtk_css_provider_finalize;
1117
1118   klass->parsing_error = gtk_css_provider_parsing_error;
1119
1120   g_type_class_add_private (object_class, sizeof (GtkCssProviderPrivate));
1121 }
1122
1123 static void
1124 gtk_css_ruleset_init_copy (GtkCssRuleset       *new,
1125                            const GtkCssRuleset *ruleset,
1126                            GtkCssSelector      *selector)
1127 {
1128   memcpy (new, ruleset, sizeof (GtkCssRuleset));
1129
1130   new->selector = selector;
1131   if (new->widget_style)
1132     g_hash_table_ref (new->widget_style);
1133   if (new->style)
1134     g_hash_table_ref (new->style);
1135 }
1136
1137 static void
1138 gtk_css_ruleset_clear (GtkCssRuleset *ruleset)
1139 {
1140   if (ruleset->style)
1141     g_hash_table_unref (ruleset->style);
1142   if (ruleset->widget_style)
1143     g_hash_table_unref (ruleset->widget_style);
1144   if (ruleset->selector)
1145     _gtk_css_selector_free (ruleset->selector);
1146
1147   memset (ruleset, 0, sizeof (GtkCssRuleset));
1148 }
1149
1150 typedef struct _PropertyValue PropertyValue;
1151 struct _PropertyValue {
1152   GtkCssSection *section;
1153   GValue         value;
1154 };
1155
1156 static PropertyValue *
1157 property_value_new (GtkCssSection *section)
1158 {
1159   PropertyValue *value;
1160
1161   value = g_slice_new0 (PropertyValue);
1162
1163   value->section = gtk_css_section_ref (section);
1164
1165   return value;
1166 }
1167
1168 static void
1169 property_value_free (PropertyValue *value)
1170 {
1171   if (G_IS_VALUE (&value->value))
1172     g_value_unset (&value->value);
1173
1174   gtk_css_section_unref (value->section);
1175
1176   g_slice_free (PropertyValue, value);
1177 }
1178
1179 static void
1180 gtk_css_ruleset_add_style (GtkCssRuleset *ruleset,
1181                            char          *name,
1182                            PropertyValue *value)
1183 {
1184   if (ruleset->widget_style == NULL)
1185     ruleset->widget_style = g_hash_table_new_full (g_str_hash,
1186                                                    g_str_equal,
1187                                                    (GDestroyNotify) g_free,
1188                                                    (GDestroyNotify) property_value_free);
1189
1190   g_hash_table_insert (ruleset->widget_style, name, value);
1191 }
1192
1193 static void
1194 gtk_css_ruleset_add (GtkCssRuleset          *ruleset,
1195                      const GtkStyleProperty *prop,
1196                      PropertyValue          *value)
1197 {
1198   if (ruleset->style == NULL)
1199     ruleset->style = g_hash_table_new_full (g_direct_hash,
1200                                             g_direct_equal,
1201                                             NULL,
1202                                             (GDestroyNotify) property_value_free);
1203
1204   if (_gtk_style_property_is_shorthand (prop))
1205     {
1206       GParameter *parameters;
1207       guint i, n_parameters;
1208
1209       parameters = _gtk_style_property_unpack (prop, &value->value, &n_parameters);
1210
1211       for (i = 0; i < n_parameters; i++)
1212         {
1213           const GtkStyleProperty *child;
1214           PropertyValue *val;
1215
1216           child = _gtk_style_property_lookup (parameters[i].name);
1217           val = property_value_new (value->section);
1218           memcpy (&val->value, &parameters[i].value, sizeof (GValue));
1219           gtk_css_ruleset_add (ruleset, child, val);
1220         }
1221       g_free (parameters);
1222       property_value_free (value);
1223       return;
1224     }
1225
1226   ruleset->has_inherit |= _gtk_style_property_is_inherit (prop);
1227   g_hash_table_insert (ruleset->style, (gpointer) prop, value);
1228 }
1229
1230 static gboolean
1231 gtk_css_ruleset_matches (GtkCssRuleset *ruleset,
1232                          GtkWidgetPath *path,
1233                          guint          length)
1234 {
1235   return _gtk_css_selector_matches (ruleset->selector, path, length);
1236 }
1237
1238 static void
1239 gtk_css_scanner_destroy (GtkCssScanner *scanner)
1240 {
1241   g_object_unref (scanner->provider);
1242   if (scanner->file)
1243     g_object_unref (scanner->file);
1244   g_object_unref (scanner->base);
1245   _gtk_css_parser_free (scanner->parser);
1246
1247   g_slice_free (GtkCssScanner, scanner);
1248 }
1249
1250 static void
1251 gtk_css_provider_emit_error (GtkCssProvider *provider,
1252                              GtkCssScanner  *scanner,
1253                              const GError   *error)
1254 {
1255   g_signal_emit (provider, css_provider_signals[PARSING_ERROR], 0,
1256                  scanner->section, error);
1257 }
1258
1259 static void
1260 gtk_css_scanner_parser_error (GtkCssParser *parser,
1261                               const GError *error,
1262                               gpointer      user_data)
1263 {
1264   GtkCssScanner *scanner = user_data;
1265
1266   gtk_css_provider_emit_error (scanner->provider,
1267                                scanner,
1268                                error);
1269 }
1270
1271 static GtkCssScanner *
1272 gtk_css_scanner_new (GtkCssProvider *provider,
1273                      GtkCssScanner  *parent,
1274                      GtkCssSection  *section,
1275                      GFile          *file,
1276                      const gchar    *text)
1277 {
1278   GtkCssScanner *scanner;
1279
1280   scanner = g_slice_new0 (GtkCssScanner);
1281
1282   g_object_ref (provider);
1283   scanner->provider = provider;
1284   scanner->parent = parent;
1285   if (section)
1286     scanner->section = gtk_css_section_ref (section);
1287
1288   if (file)
1289     {
1290       scanner->file = g_object_ref (file);
1291       scanner->base = g_file_get_parent (file);
1292     }
1293   else
1294     {
1295       char *dir = g_get_current_dir ();
1296       scanner->base = g_file_new_for_path (dir);
1297       g_free (dir);
1298     }
1299
1300   scanner->parser = _gtk_css_parser_new (text,
1301                                          gtk_css_scanner_parser_error,
1302                                          scanner);
1303
1304   return scanner;
1305 }
1306
1307 static GFile *
1308 gtk_css_scanner_get_base_url (GtkCssScanner *scanner)
1309 {
1310   return scanner->base;
1311 }
1312
1313 static gboolean
1314 gtk_css_scanner_would_recurse (GtkCssScanner *scanner,
1315                                GFile         *file)
1316 {
1317   while (scanner)
1318     {
1319       if (scanner->file && g_file_equal (scanner->file, file))
1320         return TRUE;
1321
1322       scanner = scanner->parent;
1323     }
1324
1325   return FALSE;
1326 }
1327
1328 static void
1329 gtk_css_scanner_push_section (GtkCssScanner     *scanner,
1330                               GtkCssSectionType  section_type)
1331 {
1332   GtkCssSection *section;
1333
1334   section = _gtk_css_section_new (scanner->section,
1335                                   section_type,
1336                                   scanner->parser,
1337                                   scanner->file);
1338
1339   if (scanner->section)
1340     gtk_css_section_unref (scanner->section);
1341   scanner->section = section;
1342 }
1343
1344 static void
1345 gtk_css_scanner_pop_section (GtkCssScanner *scanner,
1346                              GtkCssSectionType check_type)
1347 {
1348   GtkCssSection *parent;
1349   
1350   g_assert (gtk_css_section_get_section_type (scanner->section) == check_type);
1351
1352   parent = gtk_css_section_get_parent (scanner->section);
1353   if (parent)
1354     gtk_css_section_ref (parent);
1355
1356   _gtk_css_section_end (scanner->section);
1357   gtk_css_section_unref (scanner->section);
1358
1359   scanner->section = parent;
1360 }
1361
1362 static void
1363 gtk_css_provider_init (GtkCssProvider *css_provider)
1364 {
1365   GtkCssProviderPrivate *priv;
1366
1367   priv = css_provider->priv = G_TYPE_INSTANCE_GET_PRIVATE (css_provider,
1368                                                            GTK_TYPE_CSS_PROVIDER,
1369                                                            GtkCssProviderPrivate);
1370
1371   priv->rulesets = g_array_new (FALSE, FALSE, sizeof (GtkCssRuleset));
1372
1373   priv->symbolic_colors = g_hash_table_new_full (g_str_hash, g_str_equal,
1374                                                  (GDestroyNotify) g_free,
1375                                                  (GDestroyNotify) gtk_symbolic_color_unref);
1376 }
1377
1378 static void
1379 css_provider_dump_symbolic_colors (GtkCssProvider     *css_provider,
1380                                    GtkStyleProperties *props)
1381 {
1382   GtkCssProviderPrivate *priv;
1383   GHashTableIter iter;
1384   gpointer key, value;
1385
1386   priv = css_provider->priv;
1387   g_hash_table_iter_init (&iter, priv->symbolic_colors);
1388
1389   while (g_hash_table_iter_next (&iter, &key, &value))
1390     {
1391       const gchar *name;
1392       GtkSymbolicColor *color;
1393
1394       name = key;
1395       color = value;
1396
1397       gtk_style_properties_map_color (props, name, color);
1398     }
1399 }
1400
1401 static GtkStyleProperties *
1402 gtk_css_provider_get_style (GtkStyleProvider *provider,
1403                             GtkWidgetPath    *path)
1404 {
1405   GtkCssProvider *css_provider;
1406   GtkCssProviderPrivate *priv;
1407   GtkStyleProperties *props;
1408   guint i, l, length;
1409
1410   css_provider = GTK_CSS_PROVIDER (provider);
1411   priv = css_provider->priv;
1412   length = gtk_widget_path_length (path);
1413   props = gtk_style_properties_new ();
1414
1415   css_provider_dump_symbolic_colors (css_provider, props);
1416
1417   for (l = 1; l <= length; l++)
1418     {
1419       for (i = 0; i < priv->rulesets->len; i++)
1420         {
1421           GtkCssRuleset *ruleset;
1422           GHashTableIter iter;
1423           gpointer key, val;
1424
1425           ruleset = &g_array_index (priv->rulesets, GtkCssRuleset, i);
1426
1427           if (ruleset->style == NULL)
1428             continue;
1429
1430           if (l < length && (!ruleset->has_inherit || _gtk_css_selector_get_state_flags (ruleset->selector)))
1431             continue;
1432
1433           if (!gtk_css_ruleset_matches (ruleset, path, l))
1434             continue;
1435
1436           g_hash_table_iter_init (&iter, ruleset->style);
1437
1438           while (g_hash_table_iter_next (&iter, &key, &val))
1439             {
1440               GtkStyleProperty *prop = key;
1441               PropertyValue *value = val;
1442
1443               if (l != length && !_gtk_style_property_is_inherit (prop))
1444                 continue;
1445
1446               _gtk_style_properties_set_property_by_property (props,
1447                                                               prop,
1448                                                               _gtk_css_selector_get_state_flags (ruleset->selector),
1449                                                               &value->value);
1450             }
1451         }
1452     }
1453
1454   return props;
1455 }
1456
1457 static gboolean
1458 gtk_css_provider_get_style_property (GtkStyleProvider *provider,
1459                                      GtkWidgetPath    *path,
1460                                      GtkStateFlags     state,
1461                                      GParamSpec       *pspec,
1462                                      GValue           *value)
1463 {
1464   GtkCssProvider *css_provider = GTK_CSS_PROVIDER (provider);
1465   GtkCssProviderPrivate *priv = css_provider->priv;
1466   PropertyValue *val;
1467   gboolean found = FALSE;
1468   gchar *prop_name;
1469   gint i;
1470
1471   prop_name = g_strdup_printf ("-%s-%s",
1472                                g_type_name (pspec->owner_type),
1473                                pspec->name);
1474
1475   for (i = priv->rulesets->len - 1; i >= 0; i--)
1476     {
1477       GtkCssRuleset *ruleset;
1478       GtkStateFlags selector_state;
1479
1480       ruleset = &g_array_index (priv->rulesets, GtkCssRuleset, i);
1481
1482       if (ruleset->widget_style == NULL)
1483         continue;
1484
1485       if (!gtk_css_ruleset_matches (ruleset, path, gtk_widget_path_length (path)))
1486         continue;
1487
1488       selector_state = _gtk_css_selector_get_state_flags (ruleset->selector);
1489       val = g_hash_table_lookup (ruleset->widget_style, prop_name);
1490
1491       if (val &&
1492           (selector_state == 0 ||
1493            selector_state == state ||
1494            ((selector_state & state) != 0 &&
1495             (selector_state & ~(state)) == 0)))
1496         {
1497           GtkCssScanner *scanner;
1498
1499           scanner = gtk_css_scanner_new (css_provider,
1500                                          NULL,
1501                                          val->section,
1502                                          gtk_css_section_get_file (val->section),
1503                                          g_value_get_string (&val->value));
1504
1505           found = _gtk_style_property_parse_value (NULL,
1506                                                    value,
1507                                                    scanner->parser,
1508                                                    NULL);
1509
1510           gtk_css_scanner_destroy (scanner);
1511
1512           if (found)
1513             break;
1514         }
1515     }
1516
1517   g_free (prop_name);
1518
1519   return found;
1520 }
1521
1522 static void
1523 gtk_css_style_provider_iface_init (GtkStyleProviderIface *iface)
1524 {
1525   iface->get_style = gtk_css_provider_get_style;
1526   iface->get_style_property = gtk_css_provider_get_style_property;
1527 }
1528
1529 static void
1530 gtk_css_provider_finalize (GObject *object)
1531 {
1532   GtkCssProvider *css_provider;
1533   GtkCssProviderPrivate *priv;
1534   guint i;
1535
1536   css_provider = GTK_CSS_PROVIDER (object);
1537   priv = css_provider->priv;
1538
1539   for (i = 0; i < priv->rulesets->len; i++)
1540     gtk_css_ruleset_clear (&g_array_index (priv->rulesets, GtkCssRuleset, i));
1541
1542   g_array_free (priv->rulesets, TRUE);
1543
1544   if (priv->symbolic_colors)
1545     g_hash_table_destroy (priv->symbolic_colors);
1546
1547   G_OBJECT_CLASS (gtk_css_provider_parent_class)->finalize (object);
1548 }
1549
1550 /**
1551  * gtk_css_provider_new:
1552  *
1553  * Returns a newly created #GtkCssProvider.
1554  *
1555  * Returns: A new #GtkCssProvider
1556  **/
1557 GtkCssProvider *
1558 gtk_css_provider_new (void)
1559 {
1560   return g_object_new (GTK_TYPE_CSS_PROVIDER, NULL);
1561 }
1562
1563 static void
1564 gtk_css_provider_take_error (GtkCssProvider *provider,
1565                              GtkCssScanner  *scanner,
1566                              GError         *error)
1567 {
1568   gtk_css_provider_emit_error (scanner->provider,
1569                                scanner,
1570                                error);
1571
1572   g_error_free (error);
1573 }
1574
1575 static void
1576 gtk_css_provider_error_literal (GtkCssProvider *provider,
1577                                 GtkCssScanner  *scanner,
1578                                 GQuark          domain,
1579                                 gint            code,
1580                                 const char     *message)
1581 {
1582   gtk_css_provider_take_error (provider,
1583                                scanner,
1584                                g_error_new_literal (domain, code, message));
1585 }
1586
1587 static void
1588 gtk_css_provider_error (GtkCssProvider *provider,
1589                         GtkCssScanner  *scanner,
1590                         GQuark          domain,
1591                         gint            code,
1592                         const char     *format,
1593                         ...)  G_GNUC_PRINTF (5, 6);
1594 static void
1595 gtk_css_provider_error (GtkCssProvider *provider,
1596                         GtkCssScanner  *scanner,
1597                         GQuark          domain,
1598                         gint            code,
1599                         const char     *format,
1600                         ...)
1601 {
1602   GError *error;
1603   va_list args;
1604
1605   va_start (args, format);
1606   error = g_error_new_valist (domain, code, format, args);
1607   va_end (args);
1608
1609   gtk_css_provider_take_error (provider, scanner, error);
1610 }
1611
1612 static void
1613 gtk_css_provider_invalid_token (GtkCssProvider *provider,
1614                                 GtkCssScanner  *scanner,
1615                                 const char     *expected)
1616 {
1617   gtk_css_provider_error (provider,
1618                           scanner,
1619                           GTK_CSS_PROVIDER_ERROR,
1620                           GTK_CSS_PROVIDER_ERROR_SYNTAX,
1621                           "expected a valid %s", expected);
1622 }
1623
1624 static void 
1625 css_provider_commit (GtkCssProvider *css_provider,
1626                      GSList         *selectors,
1627                      GtkCssRuleset  *ruleset)
1628 {
1629   GtkCssProviderPrivate *priv;
1630   GSList *l;
1631
1632   priv = css_provider->priv;
1633
1634   if (ruleset->style == NULL && ruleset->widget_style == NULL)
1635     {
1636       g_slist_free_full (selectors, (GDestroyNotify) _gtk_css_selector_free);
1637       return;
1638     }
1639
1640   for (l = selectors; l; l = l->next)
1641     {
1642       GtkCssRuleset new;
1643
1644       gtk_css_ruleset_init_copy (&new, ruleset, l->data);
1645
1646       g_array_append_val (priv->rulesets, new);
1647     }
1648
1649   g_slist_free (selectors);
1650 }
1651
1652 static void
1653 gtk_css_provider_reset (GtkCssProvider *css_provider)
1654 {
1655   GtkCssProviderPrivate *priv;
1656   guint i;
1657
1658   priv = css_provider->priv;
1659
1660   g_hash_table_remove_all (priv->symbolic_colors);
1661
1662   for (i = 0; i < priv->rulesets->len; i++)
1663     gtk_css_ruleset_clear (&g_array_index (priv->rulesets, GtkCssRuleset, i));
1664   g_array_set_size (priv->rulesets, 0);
1665 }
1666
1667 static void
1668 gtk_css_provider_propagate_error (GtkCssProvider  *provider,
1669                                   const gchar     *path,
1670                                   guint            line,
1671                                   guint            position,
1672                                   const GError    *error,
1673                                   GError         **propagate_to)
1674 {
1675   /* don't fail for deprecations */
1676   if (g_error_matches (error, GTK_CSS_PROVIDER_ERROR, GTK_CSS_PROVIDER_ERROR_DEPRECATED))
1677     {
1678       g_warning ("Theme parsing error: %s:%u:%u: %s", path ? path : "<unknown>", line, position, error->message);
1679       return;
1680     }
1681
1682   /* we already set an error. And we'd like to keep the first one */
1683   if (*propagate_to)
1684     return;
1685
1686   *propagate_to = g_error_copy (error);
1687   g_prefix_error (propagate_to, "%s:%u:%u: ", path ? path : "<unknown>", line, position);
1688 }
1689
1690 static gboolean
1691 parse_import (GtkCssScanner *scanner)
1692 {
1693   GFile *file;
1694   char *uri;
1695
1696   gtk_css_scanner_push_section (scanner, GTK_CSS_SECTION_IMPORT);
1697
1698   if (!_gtk_css_parser_try (scanner->parser, "@import", TRUE))
1699     {
1700       gtk_css_scanner_pop_section (scanner, GTK_CSS_SECTION_IMPORT);
1701       return FALSE;
1702     }
1703
1704   if (_gtk_css_parser_is_string (scanner->parser))
1705     uri = _gtk_css_parser_read_string (scanner->parser);
1706   else
1707     uri = _gtk_css_parser_read_uri (scanner->parser);
1708
1709   if (uri == NULL)
1710     {
1711       _gtk_css_parser_resync (scanner->parser, TRUE, 0);
1712       gtk_css_scanner_pop_section (scanner, GTK_CSS_SECTION_IMPORT);
1713       return TRUE;
1714     }
1715
1716   file = g_file_resolve_relative_path (gtk_css_scanner_get_base_url (scanner), uri);
1717   g_free (uri);
1718
1719   if (gtk_css_scanner_would_recurse (scanner, file))
1720     {
1721        char *path = g_file_get_path (file);
1722        gtk_css_provider_error (scanner->provider,
1723                                scanner,
1724                                GTK_CSS_PROVIDER_ERROR,
1725                                GTK_CSS_PROVIDER_ERROR_IMPORT,
1726                                "Loading '%s' would recurse",
1727                                path);
1728        g_free (path);
1729     }
1730   else
1731     {
1732       gtk_css_provider_load_internal (scanner->provider,
1733                                       scanner,
1734                                       file,
1735                                       NULL,
1736                                       NULL);
1737     }
1738
1739   if (!_gtk_css_parser_try (scanner->parser, ";", TRUE))
1740     {
1741       gtk_css_provider_invalid_token (scanner->provider, scanner, "semicolon");
1742       _gtk_css_parser_resync (scanner->parser, TRUE, 0);
1743     }
1744
1745   g_object_unref (file);
1746
1747   gtk_css_scanner_pop_section (scanner, GTK_CSS_SECTION_IMPORT);
1748   return TRUE;
1749 }
1750
1751 static gboolean
1752 parse_color_definition (GtkCssScanner *scanner)
1753 {
1754   GtkSymbolicColor *symbolic;
1755   char *name;
1756
1757   gtk_css_scanner_push_section (scanner, GTK_CSS_SECTION_COLOR_DEFINITION);
1758
1759   if (!_gtk_css_parser_try (scanner->parser, "@define-color", TRUE))
1760     {
1761       gtk_css_scanner_pop_section (scanner, GTK_CSS_SECTION_COLOR_DEFINITION);
1762       return FALSE;
1763     }
1764
1765   name = _gtk_css_parser_try_name (scanner->parser, TRUE);
1766   if (name == NULL)
1767     {
1768       gtk_css_provider_error_literal (scanner->provider,
1769                                       scanner,
1770                                       GTK_CSS_PROVIDER_ERROR,
1771                                       GTK_CSS_PROVIDER_ERROR_SYNTAX,
1772                                       "Not a valid color name");
1773       _gtk_css_parser_resync (scanner->parser, TRUE, 0);
1774       gtk_css_scanner_pop_section (scanner, GTK_CSS_SECTION_COLOR_DEFINITION);
1775       return TRUE;
1776     }
1777
1778   symbolic = _gtk_css_parser_read_symbolic_color (scanner->parser);
1779   if (symbolic == NULL)
1780     {
1781       g_free (name);
1782       _gtk_css_parser_resync (scanner->parser, TRUE, 0);
1783       gtk_css_scanner_pop_section (scanner, GTK_CSS_SECTION_COLOR_DEFINITION);
1784       return TRUE;
1785     }
1786
1787   if (!_gtk_css_parser_try (scanner->parser, ";", TRUE))
1788     {
1789       g_free (name);
1790       gtk_symbolic_color_unref (symbolic);
1791       gtk_css_provider_error_literal (scanner->provider,
1792                                       scanner,
1793                                       GTK_CSS_PROVIDER_ERROR,
1794                                       GTK_CSS_PROVIDER_ERROR_SYNTAX,
1795                                       "Missing semicolon at end of color definition");
1796       _gtk_css_parser_resync (scanner->parser, TRUE, 0);
1797
1798       gtk_css_scanner_pop_section (scanner, GTK_CSS_SECTION_COLOR_DEFINITION);
1799       return TRUE;
1800     }
1801
1802   g_hash_table_insert (scanner->provider->priv->symbolic_colors, name, symbolic);
1803
1804   gtk_css_scanner_pop_section (scanner, GTK_CSS_SECTION_COLOR_DEFINITION);
1805   return TRUE;
1806 }
1807
1808 static gboolean
1809 parse_binding_set (GtkCssScanner *scanner)
1810 {
1811   GtkBindingSet *binding_set;
1812   char *name;
1813
1814   gtk_css_scanner_push_section (scanner, GTK_CSS_SECTION_BINDING_SET);
1815
1816   if (!_gtk_css_parser_try (scanner->parser, "@binding-set", TRUE))
1817     {
1818       gtk_css_scanner_pop_section (scanner, GTK_CSS_SECTION_BINDING_SET);
1819       return FALSE;
1820     }
1821
1822   name = _gtk_css_parser_try_ident (scanner->parser, TRUE);
1823   if (name == NULL)
1824     {
1825       gtk_css_provider_error_literal (scanner->provider,
1826                                       scanner,
1827                                       GTK_CSS_PROVIDER_ERROR,
1828                                       GTK_CSS_PROVIDER_ERROR_SYNTAX,
1829                                       "Expected name for binding set");
1830       _gtk_css_parser_resync (scanner->parser, TRUE, 0);
1831       goto skip_semicolon;
1832     }
1833
1834   binding_set = gtk_binding_set_find (name);
1835   if (!binding_set)
1836     {
1837       binding_set = gtk_binding_set_new (name);
1838       binding_set->parsed = TRUE;
1839     }
1840   g_free (name);
1841
1842   if (!_gtk_css_parser_try (scanner->parser, "{", TRUE))
1843     {
1844       gtk_css_provider_error_literal (scanner->provider,
1845                                       scanner,
1846                                       GTK_CSS_PROVIDER_ERROR,
1847                                       GTK_CSS_PROVIDER_ERROR_SYNTAX,
1848                                       "Expected '{' for binding set");
1849       _gtk_css_parser_resync (scanner->parser, TRUE, 0);
1850       goto skip_semicolon;
1851     }
1852
1853   while (!_gtk_css_parser_is_eof (scanner->parser) &&
1854          !_gtk_css_parser_begins_with (scanner->parser, '}'))
1855     {
1856       name = _gtk_css_parser_read_value (scanner->parser);
1857       if (name == NULL)
1858         {
1859           _gtk_css_parser_resync (scanner->parser, TRUE, '}');
1860           continue;
1861         }
1862
1863       if (gtk_binding_entry_add_signal_from_string (binding_set, name) != G_TOKEN_NONE)
1864         {
1865           gtk_css_provider_error_literal (scanner->provider,
1866                                           scanner,
1867                                           GTK_CSS_PROVIDER_ERROR,
1868                                           GTK_CSS_PROVIDER_ERROR_SYNTAX,
1869                                           "Failed to parse binding set.");
1870         }
1871
1872       g_free (name);
1873
1874       if (!_gtk_css_parser_try (scanner->parser, ";", TRUE))
1875         {
1876           if (!_gtk_css_parser_begins_with (scanner->parser, '}') &&
1877               !_gtk_css_parser_is_eof (scanner->parser))
1878             {
1879               gtk_css_provider_error_literal (scanner->provider,
1880                                               scanner,
1881                                               GTK_CSS_PROVIDER_ERROR,
1882                                               GTK_CSS_PROVIDER_ERROR_SYNTAX,
1883                                               "Expected semicolon");
1884               _gtk_css_parser_resync (scanner->parser, TRUE, '}');
1885             }
1886         }
1887     }
1888
1889   if (!_gtk_css_parser_try (scanner->parser, "}", TRUE))
1890     {
1891       gtk_css_provider_error_literal (scanner->provider,
1892                                       scanner,
1893                                       GTK_CSS_PROVIDER_ERROR,
1894                                       GTK_CSS_PROVIDER_ERROR_SYNTAX,
1895                                       "expected '}' after declarations");
1896       if (!_gtk_css_parser_is_eof (scanner->parser))
1897         _gtk_css_parser_resync (scanner->parser, FALSE, 0);
1898     }
1899
1900 skip_semicolon:
1901   if (_gtk_css_parser_begins_with (scanner->parser, ';'))
1902     {
1903       gtk_css_provider_error_literal (scanner->provider,
1904                                       scanner,
1905                                       GTK_CSS_PROVIDER_ERROR,
1906                                       GTK_CSS_PROVIDER_ERROR_DEPRECATED,
1907                                       "Nonstandard semicolon at end of binding set");
1908       _gtk_css_parser_try (scanner->parser, ";", TRUE);
1909     }
1910
1911   gtk_css_scanner_pop_section (scanner, GTK_CSS_SECTION_BINDING_SET);
1912
1913   return TRUE;
1914 }
1915
1916 static void
1917 parse_at_keyword (GtkCssScanner *scanner)
1918 {
1919   if (parse_import (scanner))
1920     return;
1921   if (parse_color_definition (scanner))
1922     return;
1923   if (parse_binding_set (scanner))
1924     return;
1925
1926   else
1927     {
1928       gtk_css_provider_error_literal (scanner->provider,
1929                                       scanner,
1930                                       GTK_CSS_PROVIDER_ERROR,
1931                                       GTK_CSS_PROVIDER_ERROR_SYNTAX,
1932                                       "unknown @ rule");
1933       _gtk_css_parser_resync (scanner->parser, TRUE, 0);
1934     }
1935 }
1936
1937 static gboolean
1938 parse_selector_class (GtkCssScanner *scanner, GArray *classes)
1939 {
1940   GQuark qname;
1941   char *name;
1942     
1943   name = _gtk_css_parser_try_name (scanner->parser, FALSE);
1944
1945   if (name == NULL)
1946     {
1947       gtk_css_provider_error_literal (scanner->provider,
1948                                       scanner,
1949                                       GTK_CSS_PROVIDER_ERROR,
1950                                       GTK_CSS_PROVIDER_ERROR_SYNTAX,
1951                                       "Expected a valid name for class");
1952       return FALSE;
1953     }
1954
1955   qname = g_quark_from_string (name);
1956   g_array_append_val (classes, qname);
1957   g_free (name);
1958   return TRUE;
1959 }
1960
1961 static gboolean
1962 parse_selector_name (GtkCssScanner *scanner, GArray *names)
1963 {
1964   GQuark qname;
1965   char *name;
1966     
1967   name = _gtk_css_parser_try_name (scanner->parser, FALSE);
1968
1969   if (name == NULL)
1970     {
1971       gtk_css_provider_error_literal (scanner->provider,
1972                                       scanner,
1973                                       GTK_CSS_PROVIDER_ERROR,
1974                                       GTK_CSS_PROVIDER_ERROR_SYNTAX,
1975                                       "Expected a valid name for id");
1976       return FALSE;
1977     }
1978
1979   qname = g_quark_from_string (name);
1980   g_array_append_val (names, qname);
1981   g_free (name);
1982   return TRUE;
1983 }
1984
1985 static gboolean
1986 parse_selector_pseudo_class (GtkCssScanner  *scanner,
1987                              GtkRegionFlags *region_to_modify,
1988                              GtkStateFlags  *state_to_modify)
1989 {
1990   struct {
1991     const char *name;
1992     GtkRegionFlags region_flag;
1993     GtkStateFlags state_flag;
1994   } pseudo_classes[] = {
1995     { "first-child",  GTK_REGION_FIRST, 0 },
1996     { "last-child",   GTK_REGION_LAST, 0 },
1997     { "sorted",       GTK_REGION_SORTED, 0 },
1998     { "active",       0, GTK_STATE_FLAG_ACTIVE },
1999     { "prelight",     0, GTK_STATE_FLAG_PRELIGHT },
2000     { "hover",        0, GTK_STATE_FLAG_PRELIGHT },
2001     { "selected",     0, GTK_STATE_FLAG_SELECTED },
2002     { "insensitive",  0, GTK_STATE_FLAG_INSENSITIVE },
2003     { "inconsistent", 0, GTK_STATE_FLAG_INCONSISTENT },
2004     { "focused",      0, GTK_STATE_FLAG_FOCUSED },
2005     { "focus",        0, GTK_STATE_FLAG_FOCUSED },
2006     { NULL, }
2007   }, nth_child_classes[] = {
2008     { "first",        GTK_REGION_FIRST, 0 },
2009     { "last",         GTK_REGION_LAST, 0 },
2010     { "even",         GTK_REGION_EVEN, 0 },
2011     { "odd",          GTK_REGION_ODD, 0 },
2012     { NULL, }
2013   }, *classes;
2014   guint i;
2015   char *name;
2016
2017   name = _gtk_css_parser_try_ident (scanner->parser, FALSE);
2018   if (name == NULL)
2019     {
2020       gtk_css_provider_error_literal (scanner->provider,
2021                                       scanner,
2022                                       GTK_CSS_PROVIDER_ERROR,
2023                                       GTK_CSS_PROVIDER_ERROR_SYNTAX,
2024                                       "Missing name of pseudo-class");
2025       return FALSE;
2026     }
2027
2028   if (_gtk_css_parser_try (scanner->parser, "(", TRUE))
2029     {
2030       char *function = name;
2031
2032       name = _gtk_css_parser_try_ident (scanner->parser, TRUE);
2033       if (!_gtk_css_parser_try (scanner->parser, ")", FALSE))
2034         {
2035           gtk_css_provider_error_literal (scanner->provider,
2036                                           scanner,
2037                                           GTK_CSS_PROVIDER_ERROR,
2038                                           GTK_CSS_PROVIDER_ERROR_SYNTAX,
2039                                           "Missing closing bracket for pseudo-class");
2040           return FALSE;
2041         }
2042
2043       if (g_ascii_strcasecmp (function, "nth-child") != 0)
2044         {
2045           gtk_css_provider_error (scanner->provider,
2046                                   scanner,
2047                                   GTK_CSS_PROVIDER_ERROR,
2048                                   GTK_CSS_PROVIDER_ERROR_UNKNOWN_VALUE,
2049                                   "Unknown pseudo-class '%s(%s)'", function, name ? name : "");
2050           g_free (function);
2051           g_free (name);
2052           return FALSE;
2053         }
2054       
2055       g_free (function);
2056     
2057       if (name == NULL)
2058         {
2059           gtk_css_provider_error (scanner->provider,
2060                                   scanner,
2061                                   GTK_CSS_PROVIDER_ERROR,
2062                                   GTK_CSS_PROVIDER_ERROR_UNKNOWN_VALUE,
2063                                   "nth-child() requires an argument");
2064           return FALSE;
2065         }
2066
2067       classes = nth_child_classes;
2068     }
2069   else
2070     classes = pseudo_classes;
2071
2072   for (i = 0; classes[i].name != NULL; i++)
2073     {
2074       if (g_ascii_strcasecmp (name, classes[i].name) == 0)
2075         {
2076           if ((*region_to_modify & classes[i].region_flag) ||
2077               (*state_to_modify & classes[i].state_flag))
2078             {
2079               if (classes == nth_child_classes)
2080                 gtk_css_provider_error (scanner->provider,
2081                                         scanner,
2082                                         GTK_CSS_PROVIDER_ERROR,
2083                                         GTK_CSS_PROVIDER_ERROR_SYNTAX,
2084                                         "Duplicate pseudo-class 'nth-child(%s)'", name);
2085               else
2086                 gtk_css_provider_error (scanner->provider,
2087                                         scanner,
2088                                         GTK_CSS_PROVIDER_ERROR,
2089                                         GTK_CSS_PROVIDER_ERROR_SYNTAX,
2090                                         "Duplicate pseudo-class '%s'", name);
2091             }
2092           *region_to_modify |= classes[i].region_flag;
2093           *state_to_modify |= classes[i].state_flag;
2094
2095           g_free (name);
2096           return TRUE;
2097         }
2098     }
2099
2100   if (classes == nth_child_classes)
2101     gtk_css_provider_error (scanner->provider,
2102                             scanner,
2103                             GTK_CSS_PROVIDER_ERROR,
2104                             GTK_CSS_PROVIDER_ERROR_UNKNOWN_VALUE,
2105                             "Unknown pseudo-class 'nth-child(%s)'", name);
2106   else
2107     gtk_css_provider_error (scanner->provider,
2108                             scanner,
2109                             GTK_CSS_PROVIDER_ERROR,
2110                             GTK_CSS_PROVIDER_ERROR_UNKNOWN_VALUE,
2111                             "Unknown pseudo-class '%s'", name);
2112   g_free (name);
2113   return FALSE;
2114 }
2115
2116 static gboolean
2117 parse_simple_selector (GtkCssScanner *scanner,
2118                        char **name,
2119                        GArray *ids,
2120                        GArray *classes,
2121                        GtkRegionFlags *pseudo_classes,
2122                        GtkStateFlags *state)
2123 {
2124   gboolean parsed_something;
2125   
2126   *name = _gtk_css_parser_try_ident (scanner->parser, FALSE);
2127   if (*name)
2128     parsed_something = TRUE;
2129   else
2130     parsed_something = _gtk_css_parser_try (scanner->parser, "*", FALSE);
2131
2132   do {
2133       if (_gtk_css_parser_try (scanner->parser, "#", FALSE))
2134         {
2135           if (!parse_selector_name (scanner, ids))
2136             return FALSE;
2137         }
2138       else if (_gtk_css_parser_try (scanner->parser, ".", FALSE))
2139         {
2140           if (!parse_selector_class (scanner, classes))
2141             return FALSE;
2142         }
2143       else if (_gtk_css_parser_try (scanner->parser, ":", FALSE))
2144         {
2145           if (!parse_selector_pseudo_class (scanner, pseudo_classes, state))
2146             return FALSE;
2147         }
2148       else if (!parsed_something)
2149         {
2150           gtk_css_provider_error_literal (scanner->provider,
2151                                           scanner,
2152                                           GTK_CSS_PROVIDER_ERROR,
2153                                           GTK_CSS_PROVIDER_ERROR_SYNTAX,
2154                                           "Expected a valid selector");
2155           return FALSE;
2156         }
2157       else
2158         break;
2159
2160       parsed_something = TRUE;
2161     }
2162   while (!_gtk_css_parser_is_eof (scanner->parser));
2163
2164   _gtk_css_parser_skip_whitespace (scanner->parser);
2165   return TRUE;
2166 }
2167
2168 static GtkCssSelector *
2169 parse_selector (GtkCssScanner *scanner)
2170 {
2171   GtkCssSelector *selector = NULL;
2172
2173   do {
2174       char *name = NULL;
2175       GArray *ids = g_array_new (TRUE, FALSE, sizeof (GQuark));
2176       GArray *classes = g_array_new (TRUE, FALSE, sizeof (GQuark));
2177       GtkRegionFlags pseudo_classes = 0;
2178       GtkStateFlags state = 0;
2179       GtkCssCombinator combine = GTK_CSS_COMBINE_DESCANDANT;
2180
2181       if (selector)
2182         {
2183           if (_gtk_css_parser_try (scanner->parser, ">", TRUE))
2184             combine = GTK_CSS_COMBINE_CHILD;
2185         }
2186
2187       if (!parse_simple_selector (scanner, &name, ids, classes, &pseudo_classes, &state))
2188         {
2189           g_array_free (ids, TRUE);
2190           g_array_free (classes, TRUE);
2191           if (selector)
2192             _gtk_css_selector_free (selector);
2193           return NULL;
2194         }
2195
2196       selector = _gtk_css_selector_new (selector,
2197                                         combine,
2198                                         name,
2199                                         (GQuark *) g_array_free (ids, ids->len == 0),
2200                                         (GQuark *) g_array_free (classes, classes->len == 0),
2201                                         pseudo_classes,
2202                                         state);
2203       g_free (name);
2204     }
2205   while (!_gtk_css_parser_is_eof (scanner->parser) &&
2206          !_gtk_css_parser_begins_with (scanner->parser, ',') &&
2207          !_gtk_css_parser_begins_with (scanner->parser, '{'));
2208
2209   return selector;
2210 }
2211
2212 static GSList *
2213 parse_selector_list (GtkCssScanner *scanner)
2214 {
2215   GSList *selectors = NULL;
2216
2217   gtk_css_scanner_push_section (scanner, GTK_CSS_SECTION_SELECTOR);
2218
2219   do {
2220       GtkCssSelector *select = parse_selector (scanner);
2221
2222       if (select == NULL)
2223         {
2224           g_slist_free_full (selectors, (GDestroyNotify) _gtk_css_selector_free);
2225           _gtk_css_parser_resync (scanner->parser, FALSE, 0);
2226           gtk_css_scanner_pop_section (scanner, GTK_CSS_SECTION_SELECTOR);
2227           return NULL;
2228         }
2229
2230       selectors = g_slist_prepend (selectors, select);
2231     }
2232   while (_gtk_css_parser_try (scanner->parser, ",", TRUE));
2233
2234   gtk_css_scanner_pop_section (scanner, GTK_CSS_SECTION_SELECTOR);
2235
2236   return selectors;
2237 }
2238
2239 static void
2240 parse_declaration (GtkCssScanner *scanner,
2241                    GtkCssRuleset *ruleset)
2242 {
2243   const GtkStyleProperty *property;
2244   char *name;
2245
2246   gtk_css_scanner_push_section (scanner, GTK_CSS_SECTION_DECLARATION);
2247
2248   name = _gtk_css_parser_try_ident (scanner->parser, TRUE);
2249   if (name == NULL)
2250     goto check_for_semicolon;
2251
2252   property = _gtk_style_property_lookup (name);
2253   if (property == NULL && name[0] != '-')
2254     {
2255       gtk_css_provider_error (scanner->provider,
2256                               scanner,
2257                               GTK_CSS_PROVIDER_ERROR,
2258                               GTK_CSS_PROVIDER_ERROR_NAME,
2259                               "'%s' is not a valid property name",
2260                               name);
2261       _gtk_css_parser_resync (scanner->parser, TRUE, '}');
2262       g_free (name);
2263       gtk_css_scanner_pop_section (scanner, GTK_CSS_SECTION_DECLARATION);
2264       return;
2265     }
2266
2267   if (!_gtk_css_parser_try (scanner->parser, ":", TRUE))
2268     {
2269       gtk_css_provider_invalid_token (scanner->provider, scanner, "':'");
2270       _gtk_css_parser_resync (scanner->parser, TRUE, '}');
2271       g_free (name);
2272       gtk_css_scanner_pop_section (scanner, GTK_CSS_SECTION_DECLARATION);
2273       return;
2274     }
2275
2276   if (property)
2277     {
2278       PropertyValue *val;
2279
2280       g_free (name);
2281
2282       gtk_css_scanner_push_section (scanner, GTK_CSS_SECTION_VALUE);
2283
2284       val = property_value_new (scanner->section);
2285       g_value_init (&val->value, property->pspec->value_type);
2286
2287       if (_gtk_style_property_parse_value (property,
2288                                            &val->value,
2289                                            scanner->parser,
2290                                            gtk_css_scanner_get_base_url (scanner)))
2291         {
2292           if (_gtk_css_parser_begins_with (scanner->parser, ';') ||
2293               _gtk_css_parser_begins_with (scanner->parser, '}') ||
2294               _gtk_css_parser_is_eof (scanner->parser))
2295             {
2296               gtk_css_ruleset_add (ruleset, property, val);
2297             }
2298           else
2299             {
2300               gtk_css_provider_error_literal (scanner->provider,
2301                                               scanner,
2302                                               GTK_CSS_PROVIDER_ERROR,
2303                                               GTK_CSS_PROVIDER_ERROR_SYNTAX,
2304                                               "Junk at end of value");
2305               _gtk_css_parser_resync (scanner->parser, TRUE, '}');
2306               property_value_free (val);
2307               gtk_css_scanner_pop_section (scanner, GTK_CSS_SECTION_VALUE);
2308               gtk_css_scanner_pop_section (scanner, GTK_CSS_SECTION_DECLARATION);
2309               return;
2310             }
2311         }
2312       else
2313         {
2314           property_value_free (val);
2315           _gtk_css_parser_resync (scanner->parser, TRUE, '}');
2316           gtk_css_scanner_pop_section (scanner, GTK_CSS_SECTION_VALUE);
2317           gtk_css_scanner_pop_section (scanner, GTK_CSS_SECTION_DECLARATION);
2318           return;
2319         }
2320       gtk_css_scanner_pop_section (scanner, GTK_CSS_SECTION_VALUE);
2321     }
2322   else if (name[0] == '-')
2323     {
2324       char *value_str;
2325
2326       gtk_css_scanner_push_section (scanner, GTK_CSS_SECTION_VALUE);
2327
2328       value_str = _gtk_css_parser_read_value (scanner->parser);
2329       if (value_str)
2330         {
2331           PropertyValue *val;
2332
2333           val = property_value_new (scanner->section);
2334           g_value_init (&val->value, G_TYPE_STRING);
2335           g_value_take_string (&val->value, value_str);
2336
2337           gtk_css_ruleset_add_style (ruleset, name, val);
2338         }
2339       else
2340         {
2341           _gtk_css_parser_resync (scanner->parser, TRUE, '}');
2342           gtk_css_scanner_pop_section (scanner, GTK_CSS_SECTION_VALUE);
2343           gtk_css_scanner_pop_section (scanner, GTK_CSS_SECTION_DECLARATION);
2344           return;
2345         }
2346
2347       gtk_css_scanner_pop_section (scanner, GTK_CSS_SECTION_VALUE);
2348     }
2349   else
2350     g_free (name);
2351
2352 check_for_semicolon:
2353   gtk_css_scanner_pop_section (scanner, GTK_CSS_SECTION_DECLARATION);
2354
2355   if (!_gtk_css_parser_try (scanner->parser, ";", TRUE))
2356     {
2357       if (!_gtk_css_parser_begins_with (scanner->parser, '}') &&
2358           !_gtk_css_parser_is_eof (scanner->parser))
2359         {
2360           gtk_css_provider_error_literal (scanner->provider,
2361                                           scanner,
2362                                           GTK_CSS_PROVIDER_ERROR,
2363                                           GTK_CSS_PROVIDER_ERROR_SYNTAX,
2364                                           "Expected semicolon");
2365           _gtk_css_parser_resync (scanner->parser, TRUE, '}');
2366         }
2367     }
2368 }
2369
2370 static void
2371 parse_declarations (GtkCssScanner *scanner,
2372                     GtkCssRuleset *ruleset)
2373 {
2374   while (!_gtk_css_parser_is_eof (scanner->parser) &&
2375          !_gtk_css_parser_begins_with (scanner->parser, '}'))
2376     {
2377       parse_declaration (scanner, ruleset);
2378     }
2379 }
2380
2381 static void
2382 parse_ruleset (GtkCssScanner *scanner)
2383 {
2384   GSList *selectors;
2385   GtkCssRuleset ruleset = { 0, };
2386
2387   gtk_css_scanner_push_section (scanner, GTK_CSS_SECTION_RULESET);
2388
2389   selectors = parse_selector_list (scanner);
2390   if (selectors == NULL)
2391     {
2392       gtk_css_scanner_pop_section (scanner, GTK_CSS_SECTION_RULESET);
2393       return;
2394     }
2395
2396   if (!_gtk_css_parser_try (scanner->parser, "{", TRUE))
2397     {
2398       gtk_css_provider_error_literal (scanner->provider,
2399                                       scanner,
2400                                       GTK_CSS_PROVIDER_ERROR,
2401                                       GTK_CSS_PROVIDER_ERROR_SYNTAX,
2402                                       "expected '{' after selectors");
2403       _gtk_css_parser_resync (scanner->parser, FALSE, 0);
2404       g_slist_free_full (selectors, (GDestroyNotify) _gtk_css_selector_free);
2405       gtk_css_scanner_pop_section (scanner, GTK_CSS_SECTION_RULESET);
2406       return;
2407     }
2408
2409   parse_declarations (scanner, &ruleset);
2410
2411   if (!_gtk_css_parser_try (scanner->parser, "}", TRUE))
2412     {
2413       gtk_css_provider_error_literal (scanner->provider,
2414                                       scanner,
2415                                       GTK_CSS_PROVIDER_ERROR,
2416                                       GTK_CSS_PROVIDER_ERROR_SYNTAX,
2417                                       "expected '}' after declarations");
2418       if (!_gtk_css_parser_is_eof (scanner->parser))
2419         {
2420           _gtk_css_parser_resync (scanner->parser, FALSE, 0);
2421           g_slist_free_full (selectors, (GDestroyNotify) _gtk_css_selector_free);
2422           gtk_css_ruleset_clear (&ruleset);
2423           gtk_css_scanner_pop_section (scanner, GTK_CSS_SECTION_RULESET);
2424         }
2425     }
2426
2427   css_provider_commit (scanner->provider, selectors, &ruleset);
2428   gtk_css_ruleset_clear (&ruleset);
2429   gtk_css_scanner_pop_section (scanner, GTK_CSS_SECTION_RULESET);
2430 }
2431
2432 static void
2433 parse_statement (GtkCssScanner *scanner)
2434 {
2435   if (_gtk_css_parser_begins_with (scanner->parser, '@'))
2436     parse_at_keyword (scanner);
2437   else
2438     parse_ruleset (scanner);
2439 }
2440
2441 static void
2442 parse_stylesheet (GtkCssScanner *scanner)
2443 {
2444   gtk_css_scanner_push_section (scanner, GTK_CSS_SECTION_DOCUMENT);
2445
2446   _gtk_css_parser_skip_whitespace (scanner->parser);
2447
2448   while (!_gtk_css_parser_is_eof (scanner->parser))
2449     {
2450       if (_gtk_css_parser_try (scanner->parser, "<!--", TRUE) ||
2451           _gtk_css_parser_try (scanner->parser, "-->", TRUE))
2452         continue;
2453
2454       parse_statement (scanner);
2455     }
2456
2457   gtk_css_scanner_pop_section (scanner, GTK_CSS_SECTION_DOCUMENT);
2458 }
2459
2460 static int
2461 gtk_css_provider_compare_rule (gconstpointer a_,
2462                                gconstpointer b_)
2463 {
2464   const GtkCssRuleset *a = (const GtkCssRuleset *) a_;
2465   const GtkCssRuleset *b = (const GtkCssRuleset *) b_;
2466   int compare;
2467
2468   compare = _gtk_css_selector_compare (a->selector, b->selector);
2469   if (compare != 0)
2470     return compare;
2471
2472   /* compare pointers in array to ensure a stable sort */
2473   if (a_ < b_)
2474     return -1;
2475
2476   if (a_ > b_)
2477     return 1;
2478
2479   return 0;
2480 }
2481
2482 static void
2483 gtk_css_provider_postprocess (GtkCssProvider *css_provider)
2484 {
2485   GtkCssProviderPrivate *priv = css_provider->priv;
2486
2487   g_array_sort (priv->rulesets, gtk_css_provider_compare_rule);
2488 }
2489
2490 static gboolean
2491 gtk_css_provider_load_internal (GtkCssProvider *css_provider,
2492                                 GtkCssScanner  *parent,
2493                                 GFile          *file,
2494                                 const char     *text,
2495                                 GError        **error)
2496 {
2497   GtkCssScanner *scanner;
2498   gulong error_handler;
2499   char *free_data = NULL;
2500
2501   if (error)
2502     error_handler = g_signal_connect (css_provider,
2503                                       "parsing-error",
2504                                       G_CALLBACK (gtk_css_provider_propagate_error),
2505                                       error);
2506   else
2507     error_handler = 0; /* silence gcc */
2508
2509   if (text == NULL)
2510     {
2511       GError *load_error = NULL;
2512
2513       if (g_file_load_contents (file, NULL,
2514                                 &free_data, NULL,
2515                                 NULL, &load_error))
2516         {
2517           text = free_data;
2518         }
2519       else
2520         {
2521           GtkCssSection *section;
2522           
2523           if (parent)
2524             section = gtk_css_section_ref (parent->section);
2525           else
2526             section = _gtk_css_section_new_for_file (GTK_CSS_SECTION_DOCUMENT, file);
2527
2528           gtk_css_provider_error (css_provider,
2529                                   parent,
2530                                   GTK_CSS_PROVIDER_ERROR,
2531                                   GTK_CSS_PROVIDER_ERROR_IMPORT,
2532                                   "Failed to import: %s",
2533                                   load_error->message);
2534
2535           gtk_css_section_unref (section);
2536         }
2537     }
2538
2539   if (text)
2540     {
2541       scanner = gtk_css_scanner_new (css_provider,
2542                                      parent,
2543                                      parent ? parent->section : NULL,
2544                                      file,
2545                                      text);
2546
2547       parse_stylesheet (scanner);
2548
2549       gtk_css_scanner_destroy (scanner);
2550
2551       if (parent == NULL)
2552         gtk_css_provider_postprocess (css_provider);
2553     }
2554
2555   g_free (free_data);
2556
2557   if (error)
2558     {
2559       g_signal_handler_disconnect (css_provider, error_handler);
2560
2561       if (*error)
2562         {
2563           /* We clear all contents from the provider for backwards compat reasons */
2564           gtk_css_provider_reset (css_provider);
2565           return FALSE;
2566         }
2567     }
2568
2569   return TRUE;
2570 }
2571
2572 /**
2573  * gtk_css_provider_load_from_data:
2574  * @css_provider: a #GtkCssProvider
2575  * @data: (array length=length) (element-type guint8): CSS data loaded in memory
2576  * @length: the length of @data in bytes, or -1 for NUL terminated strings. If
2577  *   @length is not -1, the code will assume it is not NUL terminated and will
2578  *   potentially do a copy.
2579  * @error: (out) (allow-none): return location for a #GError, or %NULL
2580  *
2581  * Loads @data into @css_provider, making it clear any previously loaded
2582  * information.
2583  *
2584  * Returns: %TRUE if the data could be loaded.
2585  **/
2586 gboolean
2587 gtk_css_provider_load_from_data (GtkCssProvider  *css_provider,
2588                                  const gchar     *data,
2589                                  gssize           length,
2590                                  GError         **error)
2591 {
2592   char *free_data;
2593   gboolean ret;
2594
2595   g_return_val_if_fail (GTK_IS_CSS_PROVIDER (css_provider), FALSE);
2596   g_return_val_if_fail (data != NULL, FALSE);
2597
2598   if (length < 0)
2599     {
2600       length = strlen (data);
2601       free_data = NULL;
2602     }
2603   else
2604     {
2605       free_data = g_strndup (data, length);
2606       data = free_data;
2607     }
2608
2609   gtk_css_provider_reset (css_provider);
2610
2611   ret = gtk_css_provider_load_internal (css_provider, NULL, NULL, data, error);
2612
2613   g_free (free_data);
2614
2615   return ret;
2616 }
2617
2618 /**
2619  * gtk_css_provider_load_from_file:
2620  * @css_provider: a #GtkCssProvider
2621  * @file: #GFile pointing to a file to load
2622  * @error: (out) (allow-none): return location for a #GError, or %NULL
2623  *
2624  * Loads the data contained in @file into @css_provider, making it
2625  * clear any previously loaded information.
2626  *
2627  * Returns: %TRUE if the data could be loaded.
2628  **/
2629 gboolean
2630 gtk_css_provider_load_from_file (GtkCssProvider  *css_provider,
2631                                  GFile           *file,
2632                                  GError         **error)
2633 {
2634   g_return_val_if_fail (GTK_IS_CSS_PROVIDER (css_provider), FALSE);
2635   g_return_val_if_fail (G_IS_FILE (file), FALSE);
2636
2637   gtk_css_provider_reset (css_provider);
2638
2639   return gtk_css_provider_load_internal (css_provider, NULL, file, NULL, error);
2640 }
2641
2642 /**
2643  * gtk_css_provider_load_from_path:
2644  * @css_provider: a #GtkCssProvider
2645  * @path: the path of a filename to load, in the GLib filename encoding
2646  * @error: (out) (allow-none): return location for a #GError, or %NULL
2647  *
2648  * Loads the data contained in @path into @css_provider, making it clear
2649  * any previously loaded information.
2650  *
2651  * Returns: %TRUE if the data could be loaded.
2652  **/
2653 gboolean
2654 gtk_css_provider_load_from_path (GtkCssProvider  *css_provider,
2655                                  const gchar     *path,
2656                                  GError         **error)
2657 {
2658   GFile *file;
2659   gboolean result;
2660
2661   g_return_val_if_fail (GTK_IS_CSS_PROVIDER (css_provider), FALSE);
2662   g_return_val_if_fail (path != NULL, FALSE);
2663
2664   file = g_file_new_for_path (path);
2665   
2666   result = gtk_css_provider_load_from_file (css_provider, file, error);
2667
2668   g_object_unref (file);
2669
2670   return result;
2671 }
2672
2673 /**
2674  * gtk_css_provider_get_default:
2675  *
2676  * Returns the provider containing the style settings used as a
2677  * fallback for all widgets.
2678  *
2679  * Returns: (transfer none): The provider used for fallback styling.
2680  *          This memory is owned by GTK+, and you must not free it.
2681  **/
2682 GtkCssProvider *
2683 gtk_css_provider_get_default (void)
2684 {
2685   static GtkCssProvider *provider;
2686
2687   if (G_UNLIKELY (!provider))
2688     {
2689       const gchar *str =
2690         "@define-color fg_color #000; \n"
2691         "@define-color bg_color #dcdad5; \n"
2692         "@define-color text_color #000; \n"
2693         "@define-color base_color #fff; \n"
2694         "@define-color selected_bg_color #4b6983; \n"
2695         "@define-color selected_fg_color #fff; \n"
2696         "@define-color tooltip_bg_color #eee1b3; \n"
2697         "@define-color tooltip_fg_color #000; \n"
2698         "@define-color placeholder_text_color #808080; \n"
2699         "\n"
2700         "@define-color info_fg_color rgb (181, 171, 156);\n"
2701         "@define-color info_bg_color rgb (252, 252, 189);\n"
2702         "@define-color warning_fg_color rgb (173, 120, 41);\n"
2703         "@define-color warning_bg_color rgb (250, 173, 61);\n"
2704         "@define-color question_fg_color rgb (97, 122, 214);\n"
2705         "@define-color question_bg_color rgb (138, 173, 212);\n"
2706         "@define-color error_fg_color rgb (166, 38, 38);\n"
2707         "@define-color error_bg_color rgb (237, 54, 54);\n"
2708         "\n"
2709         "* {\n"
2710         "  background-color: @bg_color;\n"
2711         "  color: @fg_color;\n"
2712         "  border-color: shade (@bg_color, 0.6);\n"
2713         "  padding: 2;\n"
2714         "  border-width: 0;\n"
2715         "}\n"
2716         "\n"
2717         "*:prelight {\n"
2718         "  background-color: shade (@bg_color, 1.05);\n"
2719         "  color: shade (@fg_color, 1.3);\n"
2720         "}\n"
2721         "\n"
2722         "*:selected {\n"
2723         "  background-color: @selected_bg_color;\n"
2724         "  color: @selected_fg_color;\n"
2725         "}\n"
2726         "\n"
2727         ".expander, GtkTreeView.view.expander {\n"
2728         "  color: #fff;\n"
2729         "}\n"
2730         "\n"
2731         ".expander:prelight,\n"
2732         "GtkTreeView.view.expander:selected:prelight {\n"
2733         "  color: @text_color;\n"
2734         "}\n"
2735         "\n"
2736         ".expander:active {\n"
2737         "  transition: 200ms linear;\n"
2738         "}\n"
2739         "\n"
2740         "*:insensitive {\n"
2741         "  border-color: shade (@bg_color, 0.7);\n"
2742         "  background-color: shade (@bg_color, 0.9);\n"
2743         "  color: shade (@bg_color, 0.7);\n"
2744         "}\n"
2745         "\n"
2746         ".view {\n"
2747         "  border-width: 0;\n"
2748         "  border-radius: 0;\n"
2749         "  background-color: @base_color;\n"
2750         "  color: @text_color;\n"
2751         "}\n"
2752         ".view:selected {\n"
2753         "  background-color: shade (@bg_color, 0.9);\n"
2754         "  color: @fg_color;\n"
2755         "}\n"
2756         "\n"
2757         ".view:selected:focused {\n"
2758         "  background-color: @selected_bg_color;\n"
2759         "  color: @selected_fg_color;\n"
2760         "}\n"
2761         "\n"
2762         ".view column:sorted row,\n"
2763         ".view column:sorted row:prelight {\n"
2764         "  background-color: shade (@bg_color, 0.85);\n"
2765         "}\n"
2766         "\n"
2767         ".view column:sorted row:nth-child(odd),\n"
2768         ".view column:sorted row:nth-child(odd):prelight {\n"
2769         "  background-color: shade (@bg_color, 0.8);\n"
2770         "}\n"
2771         "\n"
2772         ".view row,\n"
2773         ".view row:prelight {\n"
2774         "  background-color: @base_color;\n"
2775         "  color: @text_color;\n"
2776         "}\n"
2777         "\n"
2778         ".view row:nth-child(odd),\n"
2779         ".view row:nth-child(odd):prelight {\n"
2780         "  background-color: shade (@base_color, 0.93); \n"
2781         "}\n"
2782         "\n"
2783         ".view row:selected:focused {\n"
2784         "  background-color: @selected_bg_color;\n"
2785         "}\n"
2786         "\n"
2787         ".view row:selected {\n"
2788         "  background-color: darker (@bg_color);\n"
2789         "  color: @selected_fg_color;\n"
2790         "}\n"
2791         "\n"
2792         ".view.cell.trough,\n"
2793         ".view.cell.trough:hover,\n"
2794         ".view.cell.trough:selected,\n"
2795         ".view.cell.trough:selected:focused {\n"
2796         "  background-color: @bg_color;\n"
2797         "  color: @fg_color;\n"
2798         "}\n"
2799         "\n"
2800         ".view.cell.progressbar,\n"
2801         ".view.cell.progressbar:hover,\n"
2802         ".view.cell.progressbar:selected,\n"
2803         ".view.cell.progressbar:selected:focused {\n"
2804         "  background-color: @selected_bg_color;\n"
2805         "  color: @selected_fg_color;\n"
2806         "}\n"
2807         "\n"
2808         ".rubberband {\n"
2809         "  background-color: alpha (@fg_color, 0.25);\n"
2810         "  border-color: @fg_color;\n"
2811         "  border-style: solid;\n"
2812         "  border-width: 1;\n"
2813         "}\n"
2814         "\n"
2815         ".tooltip,\n"
2816         ".tooltip * {\n"
2817         "  background-color: @tooltip_bg_color; \n"
2818         "  color: @tooltip_fg_color; \n"
2819         "  border-color: @tooltip_fg_color; \n"
2820         "  border-width: 1;\n"
2821         "  border-style: solid;\n"
2822         "}\n"
2823         "\n"
2824         ".button,\n"
2825         ".slider {\n"
2826         "  border-style: outset; \n"
2827         "  border-width: 2; \n"
2828         "}\n"
2829         "\n"
2830         ".button:active {\n"
2831         "  background-color: shade (@bg_color, 0.7);\n"
2832         "  border-style: inset; \n"
2833         "}\n"
2834         "\n"
2835         ".button:prelight,\n"
2836         ".slider:prelight {\n"
2837         "  background-color: @selected_bg_color;\n"
2838         "  color: @selected_fg_color;\n"
2839         "  border-color: shade (@selected_bg_color, 0.7);\n"
2840         "}\n"
2841         "\n"
2842         ".trough {\n"
2843         "  background-color: darker (@bg_color);\n"
2844         "  border-style: inset;\n"
2845         "  border-width: 1;\n"
2846         "  padding: 0;\n"
2847         "}\n"
2848         "\n"
2849         ".entry {\n"
2850         "  border-style: inset;\n"
2851         "  border-width: 2;\n"
2852         "  background-color: @base_color;\n"
2853         "  color: @text_color;\n"
2854         "}\n"
2855         "\n"
2856         ".entry:insensitive {\n"
2857         "  background-color: shade (@base_color, 0.9);\n"
2858         "  color: shade (@base_color, 0.7);\n"
2859         "}\n"
2860         ".entry:active {\n"
2861         "  background-color: #c4c2bd;\n"
2862         "  color: #000;\n"
2863         "}\n"
2864         "\n"
2865         ".progressbar,\n"
2866         ".entry.progressbar, \n"
2867         ".cell.progressbar {\n"
2868         "  background-color: @selected_bg_color;\n"
2869         "  border-color: shade (@selected_bg_color, 0.7);\n"
2870         "  color: @selected_fg_color;\n"
2871         "  border-style: outset;\n"
2872         "  border-width: 1;\n"
2873         "}\n"
2874         "\n"
2875         "GtkCheckButton:hover,\n"
2876         "GtkCheckButton:selected,\n"
2877         "GtkRadioButton:hover,\n"
2878         "GtkRadioButton:selected {\n"
2879         "  background-color: shade (@bg_color, 1.05);\n"
2880         "}\n"
2881         "\n"
2882         ".check, .radio,"
2883         ".cell.check, .cell.radio,\n"
2884         ".cell.check:hover, .cell.radio:hover {\n"
2885         "  border-style: solid;\n"
2886         "  border-width: 1;\n"
2887         "  background-color: @base_color;\n"
2888         "  border-color: @fg_color;\n"
2889         "}\n"
2890         "\n"
2891         ".check:active, .radio:active,\n"
2892         ".check:hover, .radio:hover {\n"
2893         "  background-color: @base_color;\n"
2894         "  border-color: @fg_color;\n"
2895         "  color: @text_color;\n"
2896         "}\n"
2897         "\n"
2898         ".check:selected, .radio:selected {\n"
2899         "  background-color: darker (@bg_color);\n"
2900         "  color: @selected_fg_color;\n"
2901         "  border-color: @selected_fg_color;\n"
2902         "}\n"
2903         "\n"
2904         ".check:selected:focused, .radio:selected:focused {\n"
2905         "  background-color: @selected_bg_color;\n"
2906         "}\n"
2907         "\n"
2908         ".menuitem.check, .menuitem.radio {\n"
2909         "  color: @fg_color;\n"
2910         "  border-style: none;\n"
2911         "  border-width: 0;\n"
2912         "}\n"
2913         "\n"
2914         ".popup {\n"
2915         "  border-style: outset;\n"
2916         "  border-width: 1;\n"
2917         "}\n"
2918         "\n"
2919         ".viewport {\n"
2920         "  border-style: inset;\n"
2921         "  border-width: 2;\n"
2922         "}\n"
2923         "\n"
2924         ".notebook {\n"
2925         "  border-style: outset;\n"
2926         "  border-width: 1;\n"
2927         "}\n"
2928         "\n"
2929         ".frame {\n"
2930         "  border-style: inset;\n"
2931         "  border-width: 1;\n"
2932         "}\n"
2933         "\n"
2934         "GtkScrolledWindow.frame {\n"
2935         "  padding: 0;\n"
2936         "}\n"
2937         "\n"
2938         ".menu,\n"
2939         ".menubar,\n"
2940         ".toolbar {\n"
2941         "  border-style: outset;\n"
2942         "  border-width: 1;\n"
2943         "}\n"
2944         "\n"
2945         ".menu:hover,\n"
2946         ".menubar:hover,\n"
2947         ".menuitem:hover,\n"
2948         ".menuitem.check:hover,\n"
2949         ".menuitem.radio:hover {\n"
2950         "  background-color: @selected_bg_color;\n"
2951         "  color: @selected_fg_color;\n"
2952         "}\n"
2953         "\n"
2954         "GtkSpinButton.button {\n"
2955         "  border-width: 1;\n"
2956         "}\n"
2957         "\n"
2958         ".scale.slider:hover,\n"
2959         "GtkSpinButton.button:hover {\n"
2960         "  background-color: shade (@bg_color, 1.05);\n"
2961         "  border-color: shade (@bg_color, 0.8);\n"
2962         "}\n"
2963         "\n"
2964         "GtkSwitch.trough:active {\n"
2965         "  background-color: @selected_bg_color;\n"
2966         "  color: @selected_fg_color;\n"
2967         "}\n"
2968         "\n"
2969         "GtkToggleButton.button:inconsistent {\n"
2970         "  border-style: outset;\n"
2971         "  border-width: 1px;\n"
2972         "  background-color: shade (@bg_color, 0.9);\n"
2973         "  border-color: shade (@bg_color, 0.7);\n"
2974         "}\n"
2975         "\n"
2976         "GtkLabel:selected {\n"
2977         "  background-color: shade (@bg_color, 0.9);\n"
2978         "}\n"
2979         "\n"
2980         "GtkLabel:selected:focused {\n"
2981         "  background-color: @selected_bg_color;\n"
2982         "}\n"
2983         "\n"
2984         ".spinner:active {\n"
2985         "  transition: 750ms linear loop;\n"
2986         "}\n"
2987         "\n"
2988         ".info {\n"
2989         "  background-color: @info_bg_color;\n"
2990         "  color: @info_fg_color;\n"
2991         "}\n"
2992         "\n"
2993         ".warning {\n"
2994         "  background-color: @warning_bg_color;\n"
2995         "  color: @warning_fg_color;\n"
2996         "}\n"
2997         "\n"
2998         ".question {\n"
2999         "  background-color: @question_bg_color;\n"
3000         "  color: @question_fg_color;\n"
3001         "}\n"
3002         "\n"
3003         ".error {\n"
3004         "  background-color: @error_bg_color;\n"
3005         "  color: @error_fg_color;\n"
3006         "}\n"
3007         "\n"
3008         ".highlight {\n"
3009         "  background-color: @selected_bg_color;\n"
3010         "  color: @selected_fg_color;\n"
3011         "}\n"
3012         "\n"
3013         ".light-area-focus {\n"
3014         "  color: #000;\n"
3015         "}\n"
3016         "\n"
3017         ".dark-area-focus {\n"
3018         "  color: #fff;\n"
3019         "}\n"
3020         "GtkCalendar.view {\n"
3021         "  border-width: 1;\n"
3022         "  border-style: inset;\n"
3023         "  padding: 1;\n"
3024         "}\n"
3025         "\n"
3026         "GtkCalendar.view:inconsistent {\n"
3027         "  color: darker (@bg_color);\n"
3028         "}\n"
3029         "\n"
3030         "GtkCalendar.header {\n"
3031         "  background-color: @bg_color;\n"
3032         "  border-style: outset;\n"
3033         "  border-width: 2;\n"
3034         "}\n"
3035         "\n"
3036         "GtkCalendar.highlight {\n"
3037         "  border-width: 0;\n"
3038         "}\n"
3039         "\n"
3040         "GtkCalendar.button {\n"
3041         "  background-color: @bg_color;\n"
3042         "}\n"
3043         "\n"
3044         "GtkCalendar.button:hover {\n"
3045         "  background-color: lighter (@bg_color);\n"
3046         "  color: @fg_color;\n"
3047         "}\n"
3048         "\n"
3049         ".menu * {\n"
3050         "  border-width: 0;\n"
3051         "  padding: 2;\n"
3052         "}\n"
3053         "\n";
3054
3055       provider = gtk_css_provider_new ();
3056       if (!gtk_css_provider_load_from_data (provider, str, -1, NULL))
3057         {
3058           g_error ("Failed to load the internal default CSS.");
3059         }
3060     }
3061
3062   return provider;
3063 }
3064
3065 gchar *
3066 _gtk_css_provider_get_theme_dir (void)
3067 {
3068   const gchar *var;
3069   gchar *path;
3070
3071   var = g_getenv ("GTK_DATA_PREFIX");
3072
3073   if (var)
3074     path = g_build_filename (var, "share", "themes", NULL);
3075   else
3076     path = g_build_filename (GTK_DATA_PREFIX, "share", "themes", NULL);
3077
3078   return path;
3079 }
3080
3081 /**
3082  * gtk_css_provider_get_named:
3083  * @name: A theme name
3084  * @variant: (allow-none): variant to load, for example, "dark", or
3085  *     %NULL for the default
3086  *
3087  * Loads a theme from the usual theme paths
3088  *
3089  * Returns: (transfer none): a #GtkCssProvider with the theme loaded.
3090  *     This memory is owned by GTK+, and you must not free it.
3091  */
3092 GtkCssProvider *
3093 gtk_css_provider_get_named (const gchar *name,
3094                             const gchar *variant)
3095 {
3096   static GHashTable *themes = NULL;
3097   GtkCssProvider *provider;
3098   gchar *key;
3099
3100   if (G_UNLIKELY (!themes))
3101     themes = g_hash_table_new (g_str_hash, g_str_equal);
3102
3103   if (variant == NULL)
3104     key = (gchar *)name;
3105   else
3106     key = g_strconcat (name, "-", variant, NULL);
3107
3108   provider = g_hash_table_lookup (themes, key);
3109
3110   if (!provider)
3111     {
3112       const gchar *home_dir;
3113       gchar *subpath, *path = NULL;
3114
3115       if (variant)
3116         subpath = g_strdup_printf ("gtk-3.0" G_DIR_SEPARATOR_S "gtk-%s.css", variant);
3117       else
3118         subpath = g_strdup ("gtk-3.0" G_DIR_SEPARATOR_S "gtk.css");
3119
3120       /* First look in the users home directory
3121        */
3122       home_dir = g_get_home_dir ();
3123       if (home_dir)
3124         {
3125           path = g_build_filename (home_dir, ".themes", name, subpath, NULL);
3126
3127           if (!g_file_test (path, G_FILE_TEST_EXISTS))
3128             {
3129               g_free (path);
3130               path = NULL;
3131             }
3132         }
3133
3134       if (!path)
3135         {
3136           gchar *theme_dir;
3137
3138           theme_dir = _gtk_css_provider_get_theme_dir ();
3139           path = g_build_filename (theme_dir, name, subpath, NULL);
3140           g_free (theme_dir);
3141
3142           if (!g_file_test (path, G_FILE_TEST_EXISTS))
3143             {
3144               g_free (path);
3145               path = NULL;
3146             }
3147         }
3148
3149       g_free (subpath);
3150
3151       if (path)
3152         {
3153           provider = gtk_css_provider_new ();
3154
3155           if (!gtk_css_provider_load_from_path (provider, path, NULL))
3156             {
3157               g_object_unref (provider);
3158               provider = NULL;
3159             }
3160           else
3161             g_hash_table_insert (themes, g_strdup (key), provider);
3162
3163           g_free (path);
3164         }
3165     }
3166
3167   if (key != name)
3168     g_free (key);
3169
3170   return provider;
3171 }
3172
3173 static int
3174 compare_properties (gconstpointer a, gconstpointer b)
3175 {
3176   return strcmp (((const GtkStyleProperty *) a)->pspec->name,
3177                  ((const GtkStyleProperty *) b)->pspec->name);
3178 }
3179
3180 static void
3181 gtk_css_ruleset_print (const GtkCssRuleset *ruleset,
3182                        GString             *str)
3183 {
3184   GList *keys, *walk;
3185
3186   _gtk_css_selector_print (ruleset->selector, str);
3187
3188   g_string_append (str, " {\n");
3189
3190   if (ruleset->style)
3191     {
3192       keys = g_hash_table_get_keys (ruleset->style);
3193       /* so the output is identical for identical selector styles */
3194       keys = g_list_sort (keys, compare_properties);
3195
3196       for (walk = keys; walk; walk = walk->next)
3197         {
3198           GtkStyleProperty *prop = walk->data;
3199           const PropertyValue *value = g_hash_table_lookup (ruleset->style, prop);
3200
3201           g_string_append (str, "  ");
3202           g_string_append (str, prop->pspec->name);
3203           g_string_append (str, ": ");
3204           _gtk_style_property_print_value (prop, &value->value, str);
3205           g_string_append (str, ";\n");
3206         }
3207
3208       g_list_free (keys);
3209     }
3210
3211   if (ruleset->widget_style)
3212     {
3213       keys = g_hash_table_get_keys (ruleset->widget_style);
3214       /* so the output is identical for identical selector styles */
3215       keys = g_list_sort (keys, (GCompareFunc) strcmp);
3216
3217       for (walk = keys; walk; walk = walk->next)
3218         {
3219           const char *name = walk->data;
3220           const PropertyValue *value = g_hash_table_lookup (ruleset->widget_style, (gpointer) name);
3221
3222           g_string_append (str, "  ");
3223           g_string_append (str, name);
3224           g_string_append (str, ": ");
3225           g_string_append (str, g_value_get_string (&value->value));
3226           g_string_append (str, ";\n");
3227         }
3228
3229       g_list_free (keys);
3230     }
3231
3232   g_string_append (str, "}\n");
3233 }
3234
3235 static void
3236 gtk_css_provider_print_colors (GHashTable *colors,
3237                                GString    *str)
3238 {
3239   GList *keys, *walk;
3240   char *s;
3241
3242   keys = g_hash_table_get_keys (colors);
3243   /* so the output is identical for identical styles */
3244   keys = g_list_sort (keys, (GCompareFunc) strcmp);
3245
3246   for (walk = keys; walk; walk = walk->next)
3247     {
3248       const char *name = walk->data;
3249       GtkSymbolicColor *symbolic = g_hash_table_lookup (colors, (gpointer) name);
3250
3251       g_string_append (str, "@define-color ");
3252       g_string_append (str, name);
3253       g_string_append (str, " ");
3254       s = gtk_symbolic_color_to_string (symbolic);
3255       g_string_append (str, s);
3256       g_free (s);
3257       g_string_append (str, ";\n");
3258     }
3259
3260   g_list_free (keys);
3261 }
3262
3263 /**
3264  * gtk_css_provider_to_string:
3265  * @provider: the provider to write to a string
3266  *
3267  * Convertes the @provider into a string representation in CSS
3268  * format.
3269  * 
3270  * Using gtk_css_provider_load_from_data() with the return value
3271  * from this function on a new provider created with
3272  * gtk_css_provider_new() will basicallu create a duplicate of
3273  * this @provider.
3274  *
3275  * Returns: a new string representing the @provider.
3276  **/
3277 char *
3278 gtk_css_provider_to_string (GtkCssProvider *provider)
3279 {
3280   GtkCssProviderPrivate *priv;
3281   GString *str;
3282   guint i;
3283
3284   g_return_val_if_fail (GTK_IS_CSS_PROVIDER (provider), NULL);
3285
3286   priv = provider->priv;
3287
3288   str = g_string_new ("");
3289
3290   gtk_css_provider_print_colors (priv->symbolic_colors, str);
3291
3292   for (i = 0; i < priv->rulesets->len; i++)
3293     {
3294       if (i > 0)
3295         g_string_append (str, "\n");
3296       gtk_css_ruleset_print (&g_array_index (priv->rulesets, GtkCssRuleset, i), str);
3297     }
3298
3299   return g_string_free (str, FALSE);
3300 }
3301