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