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