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