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