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