]> Pileus Git - ~andy/gtk/blob - gtk/gtkcssprovider.c
cssprovider: Remove unused members from scanner
[~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   GSList *state;
1003 };
1004
1005 struct _GtkCssProviderPrivate
1006 {
1007   GScanner *scanner;
1008
1009   GHashTable *symbolic_colors;
1010
1011   GArray *rulesets;
1012   GResource *resource;
1013 };
1014
1015 enum {
1016   PARSING_ERROR,
1017   LAST_SIGNAL
1018 };
1019
1020 static gboolean gtk_keep_css_sections = FALSE;
1021
1022 static guint css_provider_signals[LAST_SIGNAL] = { 0 };
1023
1024 static void gtk_css_provider_finalize (GObject *object);
1025 static void gtk_css_style_provider_iface_init (GtkStyleProviderIface *iface);
1026 static void gtk_css_style_provider_private_iface_init (GtkStyleProviderPrivateInterface *iface);
1027 static void widget_property_value_list_free (WidgetPropertyValue *head);
1028
1029 static gboolean
1030 gtk_css_provider_load_internal (GtkCssProvider *css_provider,
1031                                 GtkCssScanner  *scanner,
1032                                 GFile          *file,
1033                                 const char     *data,
1034                                 GError        **error);
1035
1036 GQuark
1037 gtk_css_provider_error_quark (void)
1038 {
1039   return g_quark_from_static_string ("gtk-css-provider-error-quark");
1040 }
1041
1042 G_DEFINE_TYPE_EXTENDED (GtkCssProvider, gtk_css_provider, G_TYPE_OBJECT, 0,
1043                         G_IMPLEMENT_INTERFACE (GTK_TYPE_STYLE_PROVIDER,
1044                                                gtk_css_style_provider_iface_init)
1045                         G_IMPLEMENT_INTERFACE (GTK_TYPE_STYLE_PROVIDER_PRIVATE,
1046                                                gtk_css_style_provider_private_iface_init));
1047
1048 static void
1049 gtk_css_provider_parsing_error (GtkCssProvider  *provider,
1050                                 GtkCssSection   *section,
1051                                 const GError    *error)
1052 {
1053   /* Only emit a warning when we have no error handlers. This is our
1054    * default handlers. And in this case erroneous CSS files are a bug
1055    * and should be fixed.
1056    * Note that these warnings can also be triggered by a broken theme
1057    * that people installed from some weird location on the internets.
1058    */
1059   if (!g_signal_has_handler_pending (provider,
1060                                      css_provider_signals[PARSING_ERROR],
1061                                      0,
1062                                      TRUE))
1063     {
1064       GFileInfo *info;
1065       GFile *file;
1066       const char *path;
1067
1068       file = gtk_css_section_get_file (section);
1069       if (file)
1070         {
1071           info = g_file_query_info (file, G_FILE_ATTRIBUTE_STANDARD_DISPLAY_NAME, 0, NULL, NULL);
1072
1073           if (info)
1074             path = g_file_info_get_display_name (info);
1075           else
1076             path = "<broken file>";
1077         }
1078       else
1079         {
1080           info = NULL;
1081           path = "<data>";
1082         }
1083
1084       g_warning ("Theme parsing error: %s:%u:%u: %s",
1085                  path,
1086                  gtk_css_section_get_end_line (section) + 1,
1087                  gtk_css_section_get_end_position (section),
1088                  error->message);
1089
1090       if (info)
1091         g_object_unref (info);
1092     }
1093 }
1094
1095 static void
1096 gtk_css_provider_class_init (GtkCssProviderClass *klass)
1097 {
1098   GObjectClass *object_class = G_OBJECT_CLASS (klass);
1099
1100   if (g_getenv ("GTK_CSS_DEBUG"))
1101     gtk_keep_css_sections = TRUE;
1102
1103   /**
1104    * GtkCssProvider::parsing-error:
1105    * @provider: the provider that had a parsing error
1106    * @section: section the error happened in
1107    * @error: The parsing error
1108    *
1109    * Signals that a parsing error occured. the @path, @line and @position
1110    * describe the actual location of the error as accurately as possible.
1111    *
1112    * Parsing errors are never fatal, so the parsing will resume after
1113    * the error. Errors may however cause parts of the given
1114    * data or even all of it to not be parsed at all. So it is a useful idea
1115    * to check that the parsing succeeds by connecting to this signal.
1116    *
1117    * Note that this signal may be emitted at any time as the css provider
1118    * may opt to defer parsing parts or all of the input to a later time
1119    * than when a loading function was called.
1120    */
1121   css_provider_signals[PARSING_ERROR] =
1122     g_signal_new (I_("parsing-error"),
1123                   G_TYPE_FROM_CLASS (object_class),
1124                   G_SIGNAL_RUN_LAST,
1125                   G_STRUCT_OFFSET (GtkCssProviderClass, parsing_error),
1126                   NULL, NULL,
1127                   _gtk_marshal_VOID__BOXED_BOXED,
1128                   G_TYPE_NONE, 2, GTK_TYPE_CSS_SECTION, G_TYPE_ERROR);
1129
1130   object_class->finalize = gtk_css_provider_finalize;
1131
1132   klass->parsing_error = gtk_css_provider_parsing_error;
1133
1134   g_type_class_add_private (object_class, sizeof (GtkCssProviderPrivate));
1135 }
1136
1137 static void
1138 gtk_css_ruleset_init_copy (GtkCssRuleset       *new,
1139                            GtkCssRuleset       *ruleset,
1140                            GtkCssSelector      *selector)
1141 {
1142   memcpy (new, ruleset, sizeof (GtkCssRuleset));
1143
1144   new->selector = selector;
1145   /* First copy takes over ownership */
1146   if (ruleset->owns_styles)
1147     ruleset->owns_styles = FALSE;
1148   if (ruleset->owns_widget_style)
1149     ruleset->owns_widget_style = FALSE;
1150   if (new->set_styles)
1151     new->set_styles = _gtk_bitmask_copy (new->set_styles);
1152 }
1153
1154 static void
1155 gtk_css_ruleset_clear (GtkCssRuleset *ruleset)
1156 {
1157   if (ruleset->owns_styles)
1158     {
1159       guint i;
1160
1161       for (i = 0; i < ruleset->n_styles; i++)
1162         {
1163           _gtk_css_value_unref (ruleset->styles[i].value);
1164           ruleset->styles[i].value = NULL;
1165           if (ruleset->styles[i].section)
1166             gtk_css_section_unref (ruleset->styles[i].section);
1167         }
1168       g_free (ruleset->styles);
1169     }
1170   if (ruleset->set_styles)
1171     _gtk_bitmask_free (ruleset->set_styles);
1172   if (ruleset->owns_widget_style)
1173     widget_property_value_list_free (ruleset->widget_style);
1174   if (ruleset->selector)
1175     _gtk_css_selector_free (ruleset->selector);
1176
1177   memset (ruleset, 0, sizeof (GtkCssRuleset));
1178 }
1179
1180 static WidgetPropertyValue *
1181 widget_property_value_new (char *name, GtkCssSection *section)
1182 {
1183   WidgetPropertyValue *value;
1184
1185   value = g_slice_new0 (WidgetPropertyValue);
1186
1187   value->name = name;
1188   if (gtk_keep_css_sections)
1189     value->section = gtk_css_section_ref (section);
1190
1191   return value;
1192 }
1193
1194 static void
1195 widget_property_value_free (WidgetPropertyValue *value)
1196 {
1197   g_free (value->value);
1198   g_free (value->name);
1199   if (value->section)
1200     gtk_css_section_unref (value->section);
1201
1202   g_slice_free (WidgetPropertyValue, value);
1203 }
1204
1205 static void
1206 widget_property_value_list_free (WidgetPropertyValue *head)
1207 {
1208   WidgetPropertyValue *l, *next;
1209   for (l = head; l != NULL; l = next)
1210     {
1211       next = l->next;
1212       widget_property_value_free (l);
1213     }
1214 }
1215
1216 static WidgetPropertyValue *
1217 widget_property_value_list_remove_name (WidgetPropertyValue *head, const char *name)
1218 {
1219   WidgetPropertyValue *l, **last;
1220
1221   last = &head;
1222
1223   for (l = head; l != NULL; l = l->next)
1224     {
1225       if (strcmp (l->name, name) == 0)
1226         {
1227           *last = l->next;
1228           widget_property_value_free (l);
1229           break;
1230         }
1231
1232       last = &l->next;
1233     }
1234
1235   return head;
1236 }
1237
1238 static void
1239 gtk_css_ruleset_add_style (GtkCssRuleset *ruleset,
1240                            char          *name,
1241                            WidgetPropertyValue *value)
1242 {
1243   value->next = widget_property_value_list_remove_name (ruleset->widget_style, name);
1244   ruleset->widget_style = value;
1245   ruleset->owns_widget_style = TRUE;
1246 }
1247
1248 static void
1249 gtk_css_ruleset_add (GtkCssRuleset       *ruleset,
1250                      GtkCssStyleProperty *property,
1251                      GtkCssValue         *value,
1252                      GtkCssSection       *section)
1253 {
1254   guint i;
1255
1256   g_return_if_fail (ruleset->owns_styles || ruleset->n_styles == 0);
1257
1258   if (ruleset->set_styles == NULL)
1259     ruleset->set_styles = _gtk_bitmask_new ();
1260
1261   ruleset->set_styles = _gtk_bitmask_set (ruleset->set_styles,
1262                                           _gtk_css_style_property_get_id (property),
1263                                           TRUE);
1264
1265   ruleset->owns_styles = TRUE;
1266
1267   for (i = 0; i < ruleset->n_styles; i++)
1268     {
1269       if (ruleset->styles[i].property == property)
1270         {
1271           _gtk_css_value_unref (ruleset->styles[i].value);
1272           ruleset->styles[i].value = NULL;
1273           if (ruleset->styles[i].section)
1274             gtk_css_section_unref (ruleset->styles[i].section);
1275           break;
1276         }
1277     }
1278   if (i == ruleset->n_styles)
1279     {
1280       ruleset->n_styles++;
1281       ruleset->styles = g_realloc (ruleset->styles, ruleset->n_styles * sizeof (PropertyValue));
1282       ruleset->styles[i].value = NULL;
1283       ruleset->styles[i].property = property;
1284     }
1285
1286   ruleset->styles[i].value = value;
1287   if (gtk_keep_css_sections)
1288     ruleset->styles[i].section = gtk_css_section_ref (section);
1289   else
1290     ruleset->styles[i].section = NULL;
1291 }
1292
1293 static gboolean
1294 gtk_css_ruleset_matches (GtkCssRuleset       *ruleset,
1295                          const GtkCssMatcher *matcher)
1296 {
1297   return _gtk_css_selector_matches (ruleset->selector, matcher);
1298 }
1299
1300 static GtkCssChange
1301 gtk_css_ruleset_get_change (GtkCssRuleset *ruleset)
1302 {
1303   return _gtk_css_selector_get_change (ruleset->selector);
1304 }
1305
1306 static void
1307 gtk_css_scanner_destroy (GtkCssScanner *scanner)
1308 {
1309   if (scanner->section)
1310     gtk_css_section_unref (scanner->section);
1311   g_object_unref (scanner->provider);
1312   _gtk_css_parser_free (scanner->parser);
1313
1314   g_slice_free (GtkCssScanner, scanner);
1315 }
1316
1317 static void
1318 gtk_css_provider_emit_error (GtkCssProvider *provider,
1319                              GtkCssScanner  *scanner,
1320                              const GError   *error)
1321 {
1322   g_signal_emit (provider, css_provider_signals[PARSING_ERROR], 0,
1323                  scanner != NULL ? scanner->section : NULL, error);
1324 }
1325
1326 static void
1327 gtk_css_scanner_parser_error (GtkCssParser *parser,
1328                               const GError *error,
1329                               gpointer      user_data)
1330 {
1331   GtkCssScanner *scanner = user_data;
1332
1333   gtk_css_provider_emit_error (scanner->provider,
1334                                scanner,
1335                                error);
1336 }
1337
1338 static GtkCssScanner *
1339 gtk_css_scanner_new (GtkCssProvider *provider,
1340                      GtkCssScanner  *parent,
1341                      GtkCssSection  *section,
1342                      GFile          *file,
1343                      const gchar    *text)
1344 {
1345   GtkCssScanner *scanner;
1346
1347   scanner = g_slice_new0 (GtkCssScanner);
1348
1349   g_object_ref (provider);
1350   scanner->provider = provider;
1351   scanner->parent = parent;
1352   if (section)
1353     scanner->section = gtk_css_section_ref (section);
1354
1355   scanner->parser = _gtk_css_parser_new (text,
1356                                          file,
1357                                          gtk_css_scanner_parser_error,
1358                                          scanner);
1359
1360   return scanner;
1361 }
1362
1363 static gboolean
1364 gtk_css_scanner_would_recurse (GtkCssScanner *scanner,
1365                                GFile         *file)
1366 {
1367   while (scanner)
1368     {
1369       GFile *parser_file = _gtk_css_parser_get_file (scanner->parser);
1370       if (parser_file && g_file_equal (parser_file, file))
1371         return TRUE;
1372
1373       scanner = scanner->parent;
1374     }
1375
1376   return FALSE;
1377 }
1378
1379 static void
1380 gtk_css_scanner_push_section (GtkCssScanner     *scanner,
1381                               GtkCssSectionType  section_type)
1382 {
1383   GtkCssSection *section;
1384
1385   section = _gtk_css_section_new (scanner->section,
1386                                   section_type,
1387                                   scanner->parser);
1388
1389   if (scanner->section)
1390     gtk_css_section_unref (scanner->section);
1391   scanner->section = section;
1392 }
1393
1394 static void
1395 gtk_css_scanner_pop_section (GtkCssScanner *scanner,
1396                              GtkCssSectionType check_type)
1397 {
1398   GtkCssSection *parent;
1399   
1400   g_assert (gtk_css_section_get_section_type (scanner->section) == check_type);
1401
1402   parent = gtk_css_section_get_parent (scanner->section);
1403   if (parent)
1404     gtk_css_section_ref (parent);
1405
1406   _gtk_css_section_end (scanner->section);
1407   gtk_css_section_unref (scanner->section);
1408
1409   scanner->section = parent;
1410 }
1411
1412 static void
1413 gtk_css_provider_init (GtkCssProvider *css_provider)
1414 {
1415   GtkCssProviderPrivate *priv;
1416
1417   priv = css_provider->priv = G_TYPE_INSTANCE_GET_PRIVATE (css_provider,
1418                                                            GTK_TYPE_CSS_PROVIDER,
1419                                                            GtkCssProviderPrivate);
1420
1421   priv->rulesets = g_array_new (FALSE, FALSE, sizeof (GtkCssRuleset));
1422
1423   priv->symbolic_colors = g_hash_table_new_full (g_str_hash, g_str_equal,
1424                                                  (GDestroyNotify) g_free,
1425                                                  (GDestroyNotify) gtk_symbolic_color_unref);
1426 }
1427
1428 static void
1429 css_provider_dump_symbolic_colors (GtkCssProvider     *css_provider,
1430                                    GtkStyleProperties *props)
1431 {
1432   GtkCssProviderPrivate *priv;
1433   GHashTableIter iter;
1434   gpointer key, value;
1435
1436   priv = css_provider->priv;
1437   g_hash_table_iter_init (&iter, priv->symbolic_colors);
1438
1439   while (g_hash_table_iter_next (&iter, &key, &value))
1440     {
1441       const gchar *name;
1442       GtkSymbolicColor *color;
1443
1444       name = key;
1445       color = value;
1446
1447       gtk_style_properties_map_color (props, name, color);
1448     }
1449 }
1450
1451 static GtkStyleProperties *
1452 gtk_css_provider_get_style (GtkStyleProvider *provider,
1453                             GtkWidgetPath    *path)
1454 {
1455   GtkCssMatcher matcher;
1456   GtkCssProvider *css_provider;
1457   GtkCssProviderPrivate *priv;
1458   GtkStyleProperties *props;
1459   guint i, j;
1460
1461   css_provider = GTK_CSS_PROVIDER (provider);
1462   priv = css_provider->priv;
1463   props = gtk_style_properties_new ();
1464
1465   css_provider_dump_symbolic_colors (css_provider, props);
1466   if (_gtk_css_matcher_init (&matcher, path, 0))
1467     {
1468       for (i = 0; i < priv->rulesets->len; i++)
1469         {
1470           GtkCssRuleset *ruleset;
1471
1472           ruleset = &g_array_index (priv->rulesets, GtkCssRuleset, i);
1473
1474           if (ruleset->styles == NULL)
1475             continue;
1476
1477           if (!gtk_css_ruleset_matches (ruleset, &matcher))
1478             continue;
1479
1480           for (j = 0; j < ruleset->n_styles; j++)
1481             _gtk_style_properties_set_property_by_property (props,
1482                                                             GTK_CSS_STYLE_PROPERTY (ruleset->styles[i].property),
1483                                                             _gtk_css_selector_get_state_flags (ruleset->selector),
1484                                                             ruleset->styles[i].value);
1485         }
1486     }
1487
1488   return props;
1489 }
1490
1491 static gboolean
1492 gtk_css_provider_get_style_property (GtkStyleProvider *provider,
1493                                      GtkWidgetPath    *path,
1494                                      GtkStateFlags     state,
1495                                      GParamSpec       *pspec,
1496                                      GValue           *value)
1497 {
1498   GtkCssProvider *css_provider = GTK_CSS_PROVIDER (provider);
1499   GtkCssProviderPrivate *priv = css_provider->priv;
1500   WidgetPropertyValue *val;
1501   GtkCssMatcher matcher;
1502   gboolean found = FALSE;
1503   gchar *prop_name;
1504   gint i;
1505
1506   if (!_gtk_css_matcher_init (&matcher, path, state))
1507     return FALSE;
1508
1509   prop_name = g_strdup_printf ("-%s-%s",
1510                                g_type_name (pspec->owner_type),
1511                                pspec->name);
1512
1513   for (i = priv->rulesets->len - 1; i >= 0; i--)
1514     {
1515       GtkCssRuleset *ruleset;
1516
1517       ruleset = &g_array_index (priv->rulesets, GtkCssRuleset, i);
1518
1519       if (ruleset->widget_style == NULL)
1520         continue;
1521
1522       if (!gtk_css_ruleset_matches (ruleset, &matcher))
1523         continue;
1524
1525       for (val = ruleset->widget_style; val != NULL; val = val->next)
1526         {
1527           if (strcmp (val->name, prop_name) == 0)
1528             {
1529               GtkCssScanner *scanner;
1530
1531               scanner = gtk_css_scanner_new (css_provider,
1532                                              NULL,
1533                                              val->section,
1534                                              val->section != NULL ? gtk_css_section_get_file (val->section) : NULL,
1535                                              val->value);
1536
1537               found = _gtk_css_style_parse_value (value,
1538                                                   scanner->parser);
1539
1540               gtk_css_scanner_destroy (scanner);
1541
1542               break;
1543             }
1544         }
1545
1546       if (found)
1547         break;
1548     }
1549
1550   g_free (prop_name);
1551
1552   return found;
1553 }
1554
1555 static void
1556 gtk_css_style_provider_iface_init (GtkStyleProviderIface *iface)
1557 {
1558   iface->get_style = gtk_css_provider_get_style;
1559   iface->get_style_property = gtk_css_provider_get_style_property;
1560 }
1561
1562 static GtkSymbolicColor *
1563 gtk_css_style_provider_get_color (GtkStyleProviderPrivate *provider,
1564                                   const char              *name)
1565 {
1566   GtkCssProvider *css_provider = GTK_CSS_PROVIDER (provider);
1567
1568   return g_hash_table_lookup (css_provider->priv->symbolic_colors, name);
1569 }
1570
1571 static void
1572 gtk_css_style_provider_lookup (GtkStyleProviderPrivate *provider,
1573                                const GtkCssMatcher     *matcher,
1574                                GtkCssLookup            *lookup)
1575 {
1576   GtkCssProvider *css_provider;
1577   GtkCssProviderPrivate *priv;
1578   int i;
1579   guint j;
1580
1581   css_provider = GTK_CSS_PROVIDER (provider);
1582   priv = css_provider->priv;
1583
1584   for (i = priv->rulesets->len - 1; i >= 0; i--)
1585     {
1586       GtkCssRuleset *ruleset;
1587
1588       ruleset = &g_array_index (priv->rulesets, GtkCssRuleset, i);
1589
1590       if (ruleset->styles == NULL)
1591         continue;
1592
1593       if (!_gtk_bitmask_intersects (_gtk_css_lookup_get_missing (lookup),
1594                                     ruleset->set_styles))
1595         continue;
1596
1597       if (!gtk_css_ruleset_matches (ruleset, matcher))
1598         continue;
1599
1600       for (j = 0; j < ruleset->n_styles; j++)
1601         {
1602           GtkCssStyleProperty *prop = ruleset->styles[j].property;
1603           guint id = _gtk_css_style_property_get_id (prop);
1604
1605           if (!_gtk_css_lookup_is_missing (lookup, id))
1606             continue;
1607
1608           _gtk_css_lookup_set (lookup,
1609                                id,
1610                                ruleset->styles[j].section,
1611                                ruleset->styles[j].value);
1612         }
1613     }
1614 }
1615
1616 static GtkCssChange
1617 gtk_css_style_provider_get_change (GtkStyleProviderPrivate *provider,
1618                                    const GtkCssMatcher     *matcher)
1619 {
1620   GtkCssProvider *css_provider;
1621   GtkCssProviderPrivate *priv;
1622   GtkCssChange change = 0;
1623   int i;
1624
1625   css_provider = GTK_CSS_PROVIDER (provider);
1626   priv = css_provider->priv;
1627
1628   for (i = priv->rulesets->len - 1; i >= 0; i--)
1629     {
1630       GtkCssRuleset *ruleset;
1631
1632       ruleset = &g_array_index (priv->rulesets, GtkCssRuleset, i);
1633
1634       if (ruleset->styles == NULL)
1635         continue;
1636
1637       if (!gtk_css_ruleset_matches (ruleset, matcher))
1638         continue;
1639
1640       change |= gtk_css_ruleset_get_change (ruleset);
1641     }
1642
1643   return change;
1644 }
1645
1646 static void
1647 gtk_css_style_provider_private_iface_init (GtkStyleProviderPrivateInterface *iface)
1648 {
1649   iface->get_color = gtk_css_style_provider_get_color;
1650   iface->lookup = gtk_css_style_provider_lookup;
1651   iface->get_change = gtk_css_style_provider_get_change;
1652 }
1653
1654 static void
1655 gtk_css_provider_finalize (GObject *object)
1656 {
1657   GtkCssProvider *css_provider;
1658   GtkCssProviderPrivate *priv;
1659   guint i;
1660
1661   css_provider = GTK_CSS_PROVIDER (object);
1662   priv = css_provider->priv;
1663
1664   for (i = 0; i < priv->rulesets->len; i++)
1665     gtk_css_ruleset_clear (&g_array_index (priv->rulesets, GtkCssRuleset, i));
1666
1667   g_array_free (priv->rulesets, TRUE);
1668
1669   if (priv->symbolic_colors)
1670     g_hash_table_destroy (priv->symbolic_colors);
1671
1672   if (priv->resource)
1673     {
1674       g_resources_unregister (priv->resource);
1675       g_resource_unref (priv->resource);
1676       priv->resource = NULL;
1677     }
1678
1679   G_OBJECT_CLASS (gtk_css_provider_parent_class)->finalize (object);
1680 }
1681
1682 /**
1683  * gtk_css_provider_new:
1684  *
1685  * Returns a newly created #GtkCssProvider.
1686  *
1687  * Returns: A new #GtkCssProvider
1688  **/
1689 GtkCssProvider *
1690 gtk_css_provider_new (void)
1691 {
1692   return g_object_new (GTK_TYPE_CSS_PROVIDER, NULL);
1693 }
1694
1695 static void
1696 gtk_css_provider_take_error (GtkCssProvider *provider,
1697                              GtkCssScanner  *scanner,
1698                              GError         *error)
1699 {
1700   gtk_css_provider_emit_error (provider,
1701                                scanner,
1702                                error);
1703
1704   g_error_free (error);
1705 }
1706
1707 static void
1708 gtk_css_provider_error_literal (GtkCssProvider *provider,
1709                                 GtkCssScanner  *scanner,
1710                                 GQuark          domain,
1711                                 gint            code,
1712                                 const char     *message)
1713 {
1714   gtk_css_provider_take_error (provider,
1715                                scanner,
1716                                g_error_new_literal (domain, code, message));
1717 }
1718
1719 static void
1720 gtk_css_provider_error (GtkCssProvider *provider,
1721                         GtkCssScanner  *scanner,
1722                         GQuark          domain,
1723                         gint            code,
1724                         const char     *format,
1725                         ...)  G_GNUC_PRINTF (5, 6);
1726 static void
1727 gtk_css_provider_error (GtkCssProvider *provider,
1728                         GtkCssScanner  *scanner,
1729                         GQuark          domain,
1730                         gint            code,
1731                         const char     *format,
1732                         ...)
1733 {
1734   GError *error;
1735   va_list args;
1736
1737   va_start (args, format);
1738   error = g_error_new_valist (domain, code, format, args);
1739   va_end (args);
1740
1741   gtk_css_provider_take_error (provider, scanner, error);
1742 }
1743
1744 static void
1745 gtk_css_provider_invalid_token (GtkCssProvider *provider,
1746                                 GtkCssScanner  *scanner,
1747                                 const char     *expected)
1748 {
1749   gtk_css_provider_error (provider,
1750                           scanner,
1751                           GTK_CSS_PROVIDER_ERROR,
1752                           GTK_CSS_PROVIDER_ERROR_SYNTAX,
1753                           "expected a valid %s", expected);
1754 }
1755
1756 static void 
1757 css_provider_commit (GtkCssProvider *css_provider,
1758                      GSList         *selectors,
1759                      GtkCssRuleset  *ruleset)
1760 {
1761   GtkCssProviderPrivate *priv;
1762   GSList *l;
1763
1764   priv = css_provider->priv;
1765
1766   if (ruleset->styles == NULL && ruleset->widget_style == NULL)
1767     {
1768       g_slist_free_full (selectors, (GDestroyNotify) _gtk_css_selector_free);
1769       return;
1770     }
1771
1772   for (l = selectors; l; l = l->next)
1773     {
1774       GtkCssRuleset new;
1775
1776       gtk_css_ruleset_init_copy (&new, ruleset, l->data);
1777
1778       g_array_append_val (priv->rulesets, new);
1779     }
1780
1781   g_slist_free (selectors);
1782 }
1783
1784 static void
1785 gtk_css_provider_reset (GtkCssProvider *css_provider)
1786 {
1787   GtkCssProviderPrivate *priv;
1788   guint i;
1789
1790   priv = css_provider->priv;
1791
1792   if (priv->resource)
1793     {
1794       g_resources_unregister (priv->resource);
1795       g_resource_unref (priv->resource);
1796       priv->resource = NULL;
1797     }
1798
1799   g_hash_table_remove_all (priv->symbolic_colors);
1800
1801   for (i = 0; i < priv->rulesets->len; i++)
1802     gtk_css_ruleset_clear (&g_array_index (priv->rulesets, GtkCssRuleset, i));
1803   g_array_set_size (priv->rulesets, 0);
1804 }
1805
1806 static void
1807 gtk_css_provider_propagate_error (GtkCssProvider  *provider,
1808                                   GtkCssSection   *section,
1809                                   const GError    *error,
1810                                   GError         **propagate_to)
1811 {
1812
1813   GFileInfo *info;
1814   GFile *file;
1815   const char *path;
1816
1817   file = gtk_css_section_get_file (section);
1818   if (file)
1819     {
1820       info = g_file_query_info (file,G_FILE_ATTRIBUTE_STANDARD_DISPLAY_NAME, 0, NULL, NULL);
1821
1822       if (info)
1823         path = g_file_info_get_display_name (info);
1824       else
1825         path = "<broken file>";
1826     }
1827   else
1828     {
1829       info = NULL;
1830       path = "<unknown>";
1831     }
1832
1833   /* don't fail for deprecations */
1834   if (g_error_matches (error, GTK_CSS_PROVIDER_ERROR, GTK_CSS_PROVIDER_ERROR_DEPRECATED))
1835     {
1836       g_warning ("Theme parsing error: %s:%u:%u: %s", path,
1837                  gtk_css_section_get_end_line (section) + 1,
1838                  gtk_css_section_get_end_position (section), error->message);
1839       return;
1840     }
1841
1842   /* we already set an error. And we'd like to keep the first one */
1843   if (*propagate_to)
1844     return;
1845
1846   *propagate_to = g_error_copy (error);
1847   g_prefix_error (propagate_to, "%s:%u:%u: ", path,
1848                   gtk_css_section_get_end_line (section) + 1,
1849                   gtk_css_section_get_end_position (section));
1850
1851   if (info)
1852     g_object_unref (info);
1853 }
1854
1855 static gboolean
1856 parse_import (GtkCssScanner *scanner)
1857 {
1858   GFile *file;
1859
1860   gtk_css_scanner_push_section (scanner, GTK_CSS_SECTION_IMPORT);
1861
1862   if (!_gtk_css_parser_try (scanner->parser, "@import", TRUE))
1863     {
1864       gtk_css_scanner_pop_section (scanner, GTK_CSS_SECTION_IMPORT);
1865       return FALSE;
1866     }
1867
1868   if (_gtk_css_parser_is_string (scanner->parser))
1869     {
1870       char *uri;
1871
1872       uri = _gtk_css_parser_read_string (scanner->parser);
1873       file = _gtk_css_parser_get_file_for_path (scanner->parser, uri);
1874       g_free (uri);
1875     }
1876   else
1877     {
1878       file = _gtk_css_parser_read_url (scanner->parser);
1879     }
1880
1881   if (file == NULL)
1882     {
1883       _gtk_css_parser_resync (scanner->parser, TRUE, 0);
1884       gtk_css_scanner_pop_section (scanner, GTK_CSS_SECTION_IMPORT);
1885       return TRUE;
1886     }
1887
1888   if (!_gtk_css_parser_try (scanner->parser, ";", FALSE))
1889     {
1890       gtk_css_provider_invalid_token (scanner->provider, scanner, "semicolon");
1891       _gtk_css_parser_resync (scanner->parser, TRUE, 0);
1892     }
1893   else if (gtk_css_scanner_would_recurse (scanner, file))
1894     {
1895        char *path = g_file_get_path (file);
1896        gtk_css_provider_error (scanner->provider,
1897                                scanner,
1898                                GTK_CSS_PROVIDER_ERROR,
1899                                GTK_CSS_PROVIDER_ERROR_IMPORT,
1900                                "Loading '%s' would recurse",
1901                                path);
1902        g_free (path);
1903     }
1904   else
1905     {
1906       gtk_css_provider_load_internal (scanner->provider,
1907                                       scanner,
1908                                       file,
1909                                       NULL,
1910                                       NULL);
1911     }
1912
1913   g_object_unref (file);
1914
1915   gtk_css_scanner_pop_section (scanner, GTK_CSS_SECTION_IMPORT);
1916   _gtk_css_parser_skip_whitespace (scanner->parser);
1917
1918   return TRUE;
1919 }
1920
1921 static gboolean
1922 parse_color_definition (GtkCssScanner *scanner)
1923 {
1924   GtkCssValue *symbolic;
1925   char *name;
1926
1927   gtk_css_scanner_push_section (scanner, GTK_CSS_SECTION_COLOR_DEFINITION);
1928
1929   if (!_gtk_css_parser_try (scanner->parser, "@define-color", TRUE))
1930     {
1931       gtk_css_scanner_pop_section (scanner, GTK_CSS_SECTION_COLOR_DEFINITION);
1932       return FALSE;
1933     }
1934
1935   name = _gtk_css_parser_try_name (scanner->parser, TRUE);
1936   if (name == NULL)
1937     {
1938       gtk_css_provider_error_literal (scanner->provider,
1939                                       scanner,
1940                                       GTK_CSS_PROVIDER_ERROR,
1941                                       GTK_CSS_PROVIDER_ERROR_SYNTAX,
1942                                       "Not a valid color name");
1943       _gtk_css_parser_resync (scanner->parser, TRUE, 0);
1944       gtk_css_scanner_pop_section (scanner, GTK_CSS_SECTION_COLOR_DEFINITION);
1945       return TRUE;
1946     }
1947
1948   symbolic = _gtk_css_symbolic_value_new (scanner->parser);
1949   if (symbolic == NULL)
1950     {
1951       g_free (name);
1952       _gtk_css_parser_resync (scanner->parser, TRUE, 0);
1953       gtk_css_scanner_pop_section (scanner, GTK_CSS_SECTION_COLOR_DEFINITION);
1954       return TRUE;
1955     }
1956
1957   if (!_gtk_css_parser_try (scanner->parser, ";", TRUE))
1958     {
1959       g_free (name);
1960       _gtk_css_value_unref (symbolic);
1961       gtk_css_provider_error_literal (scanner->provider,
1962                                       scanner,
1963                                       GTK_CSS_PROVIDER_ERROR,
1964                                       GTK_CSS_PROVIDER_ERROR_SYNTAX,
1965                                       "Missing semicolon at end of color definition");
1966       _gtk_css_parser_resync (scanner->parser, TRUE, 0);
1967
1968       gtk_css_scanner_pop_section (scanner, GTK_CSS_SECTION_COLOR_DEFINITION);
1969       return TRUE;
1970     }
1971
1972   g_hash_table_insert (scanner->provider->priv->symbolic_colors, name, symbolic);
1973
1974   gtk_css_scanner_pop_section (scanner, GTK_CSS_SECTION_COLOR_DEFINITION);
1975   return TRUE;
1976 }
1977
1978 static gboolean
1979 parse_binding_set (GtkCssScanner *scanner)
1980 {
1981   GtkBindingSet *binding_set;
1982   char *name;
1983
1984   gtk_css_scanner_push_section (scanner, GTK_CSS_SECTION_BINDING_SET);
1985
1986   if (!_gtk_css_parser_try (scanner->parser, "@binding-set", TRUE))
1987     {
1988       gtk_css_scanner_pop_section (scanner, GTK_CSS_SECTION_BINDING_SET);
1989       return FALSE;
1990     }
1991
1992   name = _gtk_css_parser_try_ident (scanner->parser, TRUE);
1993   if (name == NULL)
1994     {
1995       gtk_css_provider_error_literal (scanner->provider,
1996                                       scanner,
1997                                       GTK_CSS_PROVIDER_ERROR,
1998                                       GTK_CSS_PROVIDER_ERROR_SYNTAX,
1999                                       "Expected name for binding set");
2000       _gtk_css_parser_resync (scanner->parser, TRUE, 0);
2001       goto skip_semicolon;
2002     }
2003
2004   binding_set = gtk_binding_set_find (name);
2005   if (!binding_set)
2006     {
2007       binding_set = gtk_binding_set_new (name);
2008       binding_set->parsed = TRUE;
2009     }
2010   g_free (name);
2011
2012   if (!_gtk_css_parser_try (scanner->parser, "{", TRUE))
2013     {
2014       gtk_css_provider_error_literal (scanner->provider,
2015                                       scanner,
2016                                       GTK_CSS_PROVIDER_ERROR,
2017                                       GTK_CSS_PROVIDER_ERROR_SYNTAX,
2018                                       "Expected '{' for binding set");
2019       _gtk_css_parser_resync (scanner->parser, TRUE, 0);
2020       goto skip_semicolon;
2021     }
2022
2023   while (!_gtk_css_parser_is_eof (scanner->parser) &&
2024          !_gtk_css_parser_begins_with (scanner->parser, '}'))
2025     {
2026       name = _gtk_css_parser_read_value (scanner->parser);
2027       if (name == NULL)
2028         {
2029           _gtk_css_parser_resync (scanner->parser, TRUE, '}');
2030           continue;
2031         }
2032
2033       if (gtk_binding_entry_add_signal_from_string (binding_set, name) != G_TOKEN_NONE)
2034         {
2035           gtk_css_provider_error_literal (scanner->provider,
2036                                           scanner,
2037                                           GTK_CSS_PROVIDER_ERROR,
2038                                           GTK_CSS_PROVIDER_ERROR_SYNTAX,
2039                                           "Failed to parse binding set.");
2040         }
2041
2042       g_free (name);
2043
2044       if (!_gtk_css_parser_try (scanner->parser, ";", TRUE))
2045         {
2046           if (!_gtk_css_parser_begins_with (scanner->parser, '}') &&
2047               !_gtk_css_parser_is_eof (scanner->parser))
2048             {
2049               gtk_css_provider_error_literal (scanner->provider,
2050                                               scanner,
2051                                               GTK_CSS_PROVIDER_ERROR,
2052                                               GTK_CSS_PROVIDER_ERROR_SYNTAX,
2053                                               "Expected semicolon");
2054               _gtk_css_parser_resync (scanner->parser, TRUE, '}');
2055             }
2056         }
2057     }
2058
2059   if (!_gtk_css_parser_try (scanner->parser, "}", TRUE))
2060     {
2061       gtk_css_provider_error_literal (scanner->provider,
2062                                       scanner,
2063                                       GTK_CSS_PROVIDER_ERROR,
2064                                       GTK_CSS_PROVIDER_ERROR_SYNTAX,
2065                                       "expected '}' after declarations");
2066       if (!_gtk_css_parser_is_eof (scanner->parser))
2067         _gtk_css_parser_resync (scanner->parser, FALSE, 0);
2068     }
2069
2070 skip_semicolon:
2071   if (_gtk_css_parser_begins_with (scanner->parser, ';'))
2072     {
2073       gtk_css_provider_error_literal (scanner->provider,
2074                                       scanner,
2075                                       GTK_CSS_PROVIDER_ERROR,
2076                                       GTK_CSS_PROVIDER_ERROR_DEPRECATED,
2077                                       "Nonstandard semicolon at end of binding set");
2078       _gtk_css_parser_try (scanner->parser, ";", TRUE);
2079     }
2080
2081   gtk_css_scanner_pop_section (scanner, GTK_CSS_SECTION_BINDING_SET);
2082
2083   return TRUE;
2084 }
2085
2086 static void
2087 parse_at_keyword (GtkCssScanner *scanner)
2088 {
2089   if (parse_import (scanner))
2090     return;
2091   if (parse_color_definition (scanner))
2092     return;
2093   if (parse_binding_set (scanner))
2094     return;
2095
2096   else
2097     {
2098       gtk_css_provider_error_literal (scanner->provider,
2099                                       scanner,
2100                                       GTK_CSS_PROVIDER_ERROR,
2101                                       GTK_CSS_PROVIDER_ERROR_SYNTAX,
2102                                       "unknown @ rule");
2103       _gtk_css_parser_resync (scanner->parser, TRUE, 0);
2104     }
2105 }
2106
2107 static GSList *
2108 parse_selector_list (GtkCssScanner *scanner)
2109 {
2110   GSList *selectors = NULL;
2111
2112   gtk_css_scanner_push_section (scanner, GTK_CSS_SECTION_SELECTOR);
2113
2114   do {
2115       GtkCssSelector *select = _gtk_css_selector_parse (scanner->parser);
2116
2117       if (select == NULL)
2118         {
2119           g_slist_free_full (selectors, (GDestroyNotify) _gtk_css_selector_free);
2120           _gtk_css_parser_resync (scanner->parser, FALSE, 0);
2121           gtk_css_scanner_pop_section (scanner, GTK_CSS_SECTION_SELECTOR);
2122           return NULL;
2123         }
2124
2125       selectors = g_slist_prepend (selectors, select);
2126     }
2127   while (_gtk_css_parser_try (scanner->parser, ",", TRUE));
2128
2129   gtk_css_scanner_pop_section (scanner, GTK_CSS_SECTION_SELECTOR);
2130
2131   return selectors;
2132 }
2133
2134 static void
2135 parse_declaration (GtkCssScanner *scanner,
2136                    GtkCssRuleset *ruleset)
2137 {
2138   GtkStyleProperty *property;
2139   char *name;
2140
2141   gtk_css_scanner_push_section (scanner, GTK_CSS_SECTION_DECLARATION);
2142
2143   name = _gtk_css_parser_try_ident (scanner->parser, TRUE);
2144   if (name == NULL)
2145     goto check_for_semicolon;
2146
2147   property = _gtk_style_property_lookup (name);
2148   if (property == NULL && name[0] != '-')
2149     {
2150       gtk_css_provider_error (scanner->provider,
2151                               scanner,
2152                               GTK_CSS_PROVIDER_ERROR,
2153                               GTK_CSS_PROVIDER_ERROR_NAME,
2154                               "'%s' is not a valid property name",
2155                               name);
2156       _gtk_css_parser_resync (scanner->parser, TRUE, '}');
2157       g_free (name);
2158       gtk_css_scanner_pop_section (scanner, GTK_CSS_SECTION_DECLARATION);
2159       return;
2160     }
2161
2162   if (!_gtk_css_parser_try (scanner->parser, ":", TRUE))
2163     {
2164       gtk_css_provider_invalid_token (scanner->provider, scanner, "':'");
2165       _gtk_css_parser_resync (scanner->parser, TRUE, '}');
2166       g_free (name);
2167       gtk_css_scanner_pop_section (scanner, GTK_CSS_SECTION_DECLARATION);
2168       return;
2169     }
2170
2171   if (property)
2172     {
2173       GtkCssValue *value;
2174
2175       g_free (name);
2176
2177       gtk_css_scanner_push_section (scanner, GTK_CSS_SECTION_VALUE);
2178
2179       value = _gtk_style_property_parse_value (property,
2180                                                scanner->parser);
2181
2182       if (value == NULL)
2183         {
2184           _gtk_css_parser_resync (scanner->parser, TRUE, '}');
2185           gtk_css_scanner_pop_section (scanner, GTK_CSS_SECTION_VALUE);
2186           gtk_css_scanner_pop_section (scanner, GTK_CSS_SECTION_DECLARATION);
2187           return;
2188         }
2189
2190       if (!_gtk_css_parser_begins_with (scanner->parser, ';') &&
2191           !_gtk_css_parser_begins_with (scanner->parser, '}') &&
2192           !_gtk_css_parser_is_eof (scanner->parser))
2193         {
2194           gtk_css_provider_error_literal (scanner->provider,
2195                                           scanner,
2196                                           GTK_CSS_PROVIDER_ERROR,
2197                                           GTK_CSS_PROVIDER_ERROR_SYNTAX,
2198                                           "Junk at end of value");
2199           _gtk_css_parser_resync (scanner->parser, TRUE, '}');
2200           gtk_css_scanner_pop_section (scanner, GTK_CSS_SECTION_VALUE);
2201           gtk_css_scanner_pop_section (scanner, GTK_CSS_SECTION_DECLARATION);
2202           return;
2203         }
2204
2205       if (GTK_IS_CSS_SHORTHAND_PROPERTY (property))
2206         {
2207           GtkCssShorthandProperty *shorthand = GTK_CSS_SHORTHAND_PROPERTY (property);
2208           guint i;
2209
2210           for (i = 0; i < _gtk_css_shorthand_property_get_n_subproperties (shorthand); i++)
2211             {
2212               GtkCssStyleProperty *child = _gtk_css_shorthand_property_get_subproperty (shorthand, i);
2213               GtkCssValue *sub = _gtk_css_array_value_get_nth (value, i);
2214               
2215               gtk_css_ruleset_add (ruleset, child, _gtk_css_value_ref (sub), scanner->section);
2216             }
2217           
2218             _gtk_css_value_unref (value);
2219         }
2220       else if (GTK_IS_CSS_STYLE_PROPERTY (property))
2221         {
2222           gtk_css_ruleset_add (ruleset, GTK_CSS_STYLE_PROPERTY (property), value, scanner->section);
2223         }
2224       else
2225         {
2226           g_assert_not_reached ();
2227           _gtk_css_value_unref (value);
2228         }
2229
2230
2231       gtk_css_scanner_pop_section (scanner, GTK_CSS_SECTION_VALUE);
2232     }
2233   else if (name[0] == '-')
2234     {
2235       char *value_str;
2236
2237       gtk_css_scanner_push_section (scanner, GTK_CSS_SECTION_VALUE);
2238
2239       value_str = _gtk_css_parser_read_value (scanner->parser);
2240       if (value_str)
2241         {
2242           WidgetPropertyValue *val;
2243
2244           val = widget_property_value_new (name, scanner->section);
2245           val->value = value_str;
2246
2247           gtk_css_ruleset_add_style (ruleset, name, val);
2248         }
2249       else
2250         {
2251           _gtk_css_parser_resync (scanner->parser, TRUE, '}');
2252           gtk_css_scanner_pop_section (scanner, GTK_CSS_SECTION_VALUE);
2253           gtk_css_scanner_pop_section (scanner, GTK_CSS_SECTION_DECLARATION);
2254           return;
2255         }
2256
2257       gtk_css_scanner_pop_section (scanner, GTK_CSS_SECTION_VALUE);
2258     }
2259   else
2260     g_free (name);
2261
2262 check_for_semicolon:
2263   gtk_css_scanner_pop_section (scanner, GTK_CSS_SECTION_DECLARATION);
2264
2265   if (!_gtk_css_parser_try (scanner->parser, ";", TRUE))
2266     {
2267       if (!_gtk_css_parser_begins_with (scanner->parser, '}') &&
2268           !_gtk_css_parser_is_eof (scanner->parser))
2269         {
2270           gtk_css_provider_error_literal (scanner->provider,
2271                                           scanner,
2272                                           GTK_CSS_PROVIDER_ERROR,
2273                                           GTK_CSS_PROVIDER_ERROR_SYNTAX,
2274                                           "Expected semicolon");
2275           _gtk_css_parser_resync (scanner->parser, TRUE, '}');
2276         }
2277     }
2278 }
2279
2280 static void
2281 parse_declarations (GtkCssScanner *scanner,
2282                     GtkCssRuleset *ruleset)
2283 {
2284   while (!_gtk_css_parser_is_eof (scanner->parser) &&
2285          !_gtk_css_parser_begins_with (scanner->parser, '}'))
2286     {
2287       parse_declaration (scanner, ruleset);
2288     }
2289 }
2290
2291 static void
2292 parse_ruleset (GtkCssScanner *scanner)
2293 {
2294   GSList *selectors;
2295   GtkCssRuleset ruleset = { 0, };
2296
2297   gtk_css_scanner_push_section (scanner, GTK_CSS_SECTION_RULESET);
2298
2299   selectors = parse_selector_list (scanner);
2300   if (selectors == NULL)
2301     {
2302       gtk_css_scanner_pop_section (scanner, GTK_CSS_SECTION_RULESET);
2303       return;
2304     }
2305
2306   if (!_gtk_css_parser_try (scanner->parser, "{", TRUE))
2307     {
2308       gtk_css_provider_error_literal (scanner->provider,
2309                                       scanner,
2310                                       GTK_CSS_PROVIDER_ERROR,
2311                                       GTK_CSS_PROVIDER_ERROR_SYNTAX,
2312                                       "expected '{' after selectors");
2313       _gtk_css_parser_resync (scanner->parser, FALSE, 0);
2314       g_slist_free_full (selectors, (GDestroyNotify) _gtk_css_selector_free);
2315       gtk_css_scanner_pop_section (scanner, GTK_CSS_SECTION_RULESET);
2316       return;
2317     }
2318
2319   parse_declarations (scanner, &ruleset);
2320
2321   if (!_gtk_css_parser_try (scanner->parser, "}", TRUE))
2322     {
2323       gtk_css_provider_error_literal (scanner->provider,
2324                                       scanner,
2325                                       GTK_CSS_PROVIDER_ERROR,
2326                                       GTK_CSS_PROVIDER_ERROR_SYNTAX,
2327                                       "expected '}' after declarations");
2328       if (!_gtk_css_parser_is_eof (scanner->parser))
2329         {
2330           _gtk_css_parser_resync (scanner->parser, FALSE, 0);
2331           g_slist_free_full (selectors, (GDestroyNotify) _gtk_css_selector_free);
2332           gtk_css_ruleset_clear (&ruleset);
2333           gtk_css_scanner_pop_section (scanner, GTK_CSS_SECTION_RULESET);
2334         }
2335     }
2336
2337   css_provider_commit (scanner->provider, selectors, &ruleset);
2338   gtk_css_ruleset_clear (&ruleset);
2339   gtk_css_scanner_pop_section (scanner, GTK_CSS_SECTION_RULESET);
2340 }
2341
2342 static void
2343 parse_statement (GtkCssScanner *scanner)
2344 {
2345   if (_gtk_css_parser_begins_with (scanner->parser, '@'))
2346     parse_at_keyword (scanner);
2347   else
2348     parse_ruleset (scanner);
2349 }
2350
2351 static void
2352 parse_stylesheet (GtkCssScanner *scanner)
2353 {
2354   gtk_css_scanner_push_section (scanner, GTK_CSS_SECTION_DOCUMENT);
2355
2356   _gtk_css_parser_skip_whitespace (scanner->parser);
2357
2358   while (!_gtk_css_parser_is_eof (scanner->parser))
2359     {
2360       if (_gtk_css_parser_try (scanner->parser, "<!--", TRUE) ||
2361           _gtk_css_parser_try (scanner->parser, "-->", TRUE))
2362         continue;
2363
2364       parse_statement (scanner);
2365     }
2366
2367   gtk_css_scanner_pop_section (scanner, GTK_CSS_SECTION_DOCUMENT);
2368 }
2369
2370 static int
2371 gtk_css_provider_compare_rule (gconstpointer a_,
2372                                gconstpointer b_)
2373 {
2374   const GtkCssRuleset *a = (const GtkCssRuleset *) a_;
2375   const GtkCssRuleset *b = (const GtkCssRuleset *) b_;
2376   int compare;
2377
2378   compare = _gtk_css_selector_compare (a->selector, b->selector);
2379   if (compare != 0)
2380     return compare;
2381
2382   return 0;
2383 }
2384
2385 static void
2386 gtk_css_provider_postprocess (GtkCssProvider *css_provider)
2387 {
2388   GtkCssProviderPrivate *priv = css_provider->priv;
2389
2390   g_array_sort (priv->rulesets, gtk_css_provider_compare_rule);
2391 }
2392
2393 static gboolean
2394 gtk_css_provider_load_internal (GtkCssProvider *css_provider,
2395                                 GtkCssScanner  *parent,
2396                                 GFile          *file,
2397                                 const char     *text,
2398                                 GError        **error)
2399 {
2400   GtkCssScanner *scanner;
2401   gulong error_handler;
2402   char *free_data = NULL;
2403
2404   if (error)
2405     error_handler = g_signal_connect (css_provider,
2406                                       "parsing-error",
2407                                       G_CALLBACK (gtk_css_provider_propagate_error),
2408                                       error);
2409   else
2410     error_handler = 0; /* silence gcc */
2411
2412   if (text == NULL)
2413     {
2414       GError *load_error = NULL;
2415
2416       if (g_file_load_contents (file, NULL,
2417                                 &free_data, NULL,
2418                                 NULL, &load_error))
2419         {
2420           text = free_data;
2421         }
2422       else
2423         {
2424           GtkCssSection *section;
2425           
2426           if (parent)
2427             section = gtk_css_section_ref (parent->section);
2428           else
2429             section = _gtk_css_section_new_for_file (GTK_CSS_SECTION_DOCUMENT, file);
2430
2431           gtk_css_provider_error (css_provider,
2432                                   parent,
2433                                   GTK_CSS_PROVIDER_ERROR,
2434                                   GTK_CSS_PROVIDER_ERROR_IMPORT,
2435                                   "Failed to import: %s",
2436                                   load_error->message);
2437
2438           gtk_css_section_unref (section);
2439         }
2440     }
2441
2442   if (text)
2443     {
2444       scanner = gtk_css_scanner_new (css_provider,
2445                                      parent,
2446                                      parent ? parent->section : NULL,
2447                                      file,
2448                                      text);
2449
2450       parse_stylesheet (scanner);
2451
2452       gtk_css_scanner_destroy (scanner);
2453
2454       if (parent == NULL)
2455         gtk_css_provider_postprocess (css_provider);
2456     }
2457
2458   g_free (free_data);
2459
2460   if (error)
2461     {
2462       g_signal_handler_disconnect (css_provider, error_handler);
2463
2464       if (*error)
2465         {
2466           /* We clear all contents from the provider for backwards compat reasons */
2467           gtk_css_provider_reset (css_provider);
2468           return FALSE;
2469         }
2470     }
2471
2472   return TRUE;
2473 }
2474
2475 /**
2476  * gtk_css_provider_load_from_data:
2477  * @css_provider: a #GtkCssProvider
2478  * @data: (array length=length) (element-type guint8): CSS data loaded in memory
2479  * @length: the length of @data in bytes, or -1 for NUL terminated strings. If
2480  *   @length is not -1, the code will assume it is not NUL terminated and will
2481  *   potentially do a copy.
2482  * @error: (out) (allow-none): return location for a #GError, or %NULL
2483  *
2484  * Loads @data into @css_provider, making it clear any previously loaded
2485  * information.
2486  *
2487  * Returns: %TRUE if the data could be loaded.
2488  **/
2489 gboolean
2490 gtk_css_provider_load_from_data (GtkCssProvider  *css_provider,
2491                                  const gchar     *data,
2492                                  gssize           length,
2493                                  GError         **error)
2494 {
2495   char *free_data;
2496   gboolean ret;
2497
2498   g_return_val_if_fail (GTK_IS_CSS_PROVIDER (css_provider), FALSE);
2499   g_return_val_if_fail (data != NULL, FALSE);
2500
2501   if (length < 0)
2502     {
2503       length = strlen (data);
2504       free_data = NULL;
2505     }
2506   else
2507     {
2508       free_data = g_strndup (data, length);
2509       data = free_data;
2510     }
2511
2512   gtk_css_provider_reset (css_provider);
2513
2514   ret = gtk_css_provider_load_internal (css_provider, NULL, NULL, data, error);
2515
2516   g_free (free_data);
2517
2518   _gtk_style_provider_private_changed (GTK_STYLE_PROVIDER_PRIVATE (css_provider));
2519
2520   return ret;
2521 }
2522
2523 /**
2524  * gtk_css_provider_load_from_file:
2525  * @css_provider: a #GtkCssProvider
2526  * @file: #GFile pointing to a file to load
2527  * @error: (out) (allow-none): return location for a #GError, or %NULL
2528  *
2529  * Loads the data contained in @file into @css_provider, making it
2530  * clear any previously loaded information.
2531  *
2532  * Returns: %TRUE if the data could be loaded.
2533  **/
2534 gboolean
2535 gtk_css_provider_load_from_file (GtkCssProvider  *css_provider,
2536                                  GFile           *file,
2537                                  GError         **error)
2538 {
2539   gboolean success;
2540
2541   g_return_val_if_fail (GTK_IS_CSS_PROVIDER (css_provider), FALSE);
2542   g_return_val_if_fail (G_IS_FILE (file), FALSE);
2543
2544   gtk_css_provider_reset (css_provider);
2545
2546   success = gtk_css_provider_load_internal (css_provider, NULL, file, NULL, error);
2547
2548   _gtk_style_provider_private_changed (GTK_STYLE_PROVIDER_PRIVATE (css_provider));
2549
2550   return success;
2551 }
2552
2553 /**
2554  * gtk_css_provider_load_from_path:
2555  * @css_provider: a #GtkCssProvider
2556  * @path: the path of a filename to load, in the GLib filename encoding
2557  * @error: (out) (allow-none): return location for a #GError, or %NULL
2558  *
2559  * Loads the data contained in @path into @css_provider, making it clear
2560  * any previously loaded information.
2561  *
2562  * Returns: %TRUE if the data could be loaded.
2563  **/
2564 gboolean
2565 gtk_css_provider_load_from_path (GtkCssProvider  *css_provider,
2566                                  const gchar     *path,
2567                                  GError         **error)
2568 {
2569   GFile *file;
2570   gboolean result;
2571
2572   g_return_val_if_fail (GTK_IS_CSS_PROVIDER (css_provider), FALSE);
2573   g_return_val_if_fail (path != NULL, FALSE);
2574
2575   file = g_file_new_for_path (path);
2576   
2577   result = gtk_css_provider_load_from_file (css_provider, file, error);
2578
2579   g_object_unref (file);
2580
2581   return result;
2582 }
2583
2584 static gboolean
2585 _gtk_css_provider_load_from_resource (GtkCssProvider  *css_provider,
2586                                       const gchar     *resource_path)
2587 {
2588   GFile *file;
2589   char *uri, *escaped;
2590   gboolean result;
2591
2592   g_return_val_if_fail (GTK_IS_CSS_PROVIDER (css_provider), FALSE);
2593   g_return_val_if_fail (resource_path != NULL, FALSE);
2594
2595   escaped = g_uri_escape_string (resource_path,
2596                                  G_URI_RESERVED_CHARS_ALLOWED_IN_PATH, FALSE);
2597   uri = g_strconcat ("resource://", escaped, NULL);
2598   g_free (escaped);
2599
2600   file = g_file_new_for_uri (uri);
2601   g_free (uri);
2602
2603   result = gtk_css_provider_load_from_file (css_provider, file, NULL);
2604
2605   g_object_unref (file);
2606
2607   return result;
2608 }
2609
2610 /**
2611  * gtk_css_provider_get_default:
2612  *
2613  * Returns the provider containing the style settings used as a
2614  * fallback for all widgets.
2615  *
2616  * Returns: (transfer none): The provider used for fallback styling.
2617  *          This memory is owned by GTK+, and you must not free it.
2618  **/
2619 GtkCssProvider *
2620 gtk_css_provider_get_default (void)
2621 {
2622   static GtkCssProvider *provider;
2623
2624   if (G_UNLIKELY (!provider))
2625     {
2626       provider = gtk_css_provider_new ();
2627     }
2628
2629   return provider;
2630 }
2631
2632 gchar *
2633 _gtk_css_provider_get_theme_dir (void)
2634 {
2635   const gchar *var;
2636   gchar *path;
2637
2638   var = g_getenv ("GTK_DATA_PREFIX");
2639
2640   if (var)
2641     path = g_build_filename (var, "share", "themes", NULL);
2642   else
2643     path = g_build_filename (_gtk_get_data_prefix (), "share", "themes", NULL);
2644
2645   return path;
2646 }
2647
2648 /**
2649  * gtk_css_provider_get_named:
2650  * @name: A theme name
2651  * @variant: (allow-none): variant to load, for example, "dark", or
2652  *     %NULL for the default
2653  *
2654  * Loads a theme from the usual theme paths
2655  *
2656  * Returns: (transfer none): a #GtkCssProvider with the theme loaded.
2657  *     This memory is owned by GTK+, and you must not free it.
2658  */
2659 GtkCssProvider *
2660 gtk_css_provider_get_named (const gchar *name,
2661                             const gchar *variant)
2662 {
2663   static GHashTable *themes = NULL;
2664   GtkCssProvider *provider;
2665   gchar *key;
2666
2667   if (variant == NULL)
2668     key = (gchar *)name;
2669   else
2670     key = g_strconcat (name, "-", variant, NULL);
2671
2672   if (G_UNLIKELY (!themes))
2673     themes = g_hash_table_new (g_str_hash, g_str_equal);
2674
2675   provider = g_hash_table_lookup (themes, key);
2676
2677   if (!provider)
2678     {
2679       gchar *resource_path = NULL;
2680
2681       if (variant)
2682         resource_path = g_strdup_printf ("/org/gtk/libgtk/%s-%s.css", name, variant);
2683       else
2684         resource_path = g_strdup_printf ("/org/gtk/libgtk/%s.css", name);
2685
2686       if (g_resources_get_info (resource_path, 0, NULL, NULL, NULL))
2687         {
2688           provider = gtk_css_provider_new ();
2689           if (!_gtk_css_provider_load_from_resource (provider, resource_path))
2690             {
2691               g_object_unref (provider);
2692               provider = NULL;
2693             }
2694         }
2695       g_free (resource_path);
2696     }
2697
2698   if (!provider)
2699     {
2700       gchar *subpath, *path = NULL;
2701
2702       if (variant)
2703         subpath = g_strdup_printf ("gtk-3.0" G_DIR_SEPARATOR_S "gtk-%s.css", variant);
2704       else
2705         subpath = g_strdup ("gtk-3.0" G_DIR_SEPARATOR_S "gtk.css");
2706
2707       /* First look in the user's config directory
2708        */
2709       path = g_build_filename (g_get_user_data_dir (), "themes", name, subpath, NULL);
2710       if (!g_file_test (path, G_FILE_TEST_EXISTS))
2711         {
2712           g_free (path);
2713           path = NULL;
2714         }
2715
2716       /* Next look in the user's home directory
2717        */
2718       if (!path)
2719         {
2720           const gchar *home_dir;
2721
2722           home_dir = g_get_home_dir ();
2723           if (home_dir)
2724             {
2725               path = g_build_filename (home_dir, ".themes", name, subpath, NULL);
2726
2727               if (!g_file_test (path, G_FILE_TEST_EXISTS))
2728                 {
2729                   g_free (path);
2730                   path = NULL;
2731                 }
2732             }
2733         }
2734
2735       if (!path)
2736         {
2737           gchar *theme_dir;
2738
2739           theme_dir = _gtk_css_provider_get_theme_dir ();
2740           path = g_build_filename (theme_dir, name, subpath, NULL);
2741           g_free (theme_dir);
2742
2743           if (!g_file_test (path, G_FILE_TEST_EXISTS))
2744             {
2745               g_free (path);
2746               path = NULL;
2747             }
2748         }
2749
2750       g_free (subpath);
2751
2752       if (path)
2753         {
2754           char *dir, *resource_file;
2755           GResource *resource;
2756
2757           provider = gtk_css_provider_new ();
2758
2759           dir = g_path_get_dirname (path);
2760           resource_file = g_build_filename (dir, "gtk.gresource", NULL);
2761           resource = g_resource_load (resource_file, NULL);
2762           g_free (resource_file);
2763
2764           if (resource != NULL)
2765             g_resources_register (resource);
2766
2767           if (!gtk_css_provider_load_from_path (provider, path, NULL))
2768             {
2769               if (resource != NULL)
2770                 {
2771                   g_resources_unregister (resource);
2772                   g_resource_unref (resource);
2773                 }
2774               g_object_unref (provider);
2775               provider = NULL;
2776             }
2777           else
2778             {
2779               /* Only set this after load success, as load_from_path will clear it */
2780               provider->priv->resource = resource;
2781               g_hash_table_insert (themes, g_strdup (key), provider);
2782             }
2783
2784           g_free (path);
2785           g_free (dir);
2786         }
2787     }
2788
2789   if (key != name)
2790     g_free (key);
2791
2792   return provider;
2793 }
2794
2795 static int
2796 compare_properties (gconstpointer a, gconstpointer b, gpointer style)
2797 {
2798   const guint *ua = a;
2799   const guint *ub = b;
2800   PropertyValue *styles = style;
2801
2802   return strcmp (_gtk_style_property_get_name (GTK_STYLE_PROPERTY (styles[*ua].property)),
2803                  _gtk_style_property_get_name (GTK_STYLE_PROPERTY (styles[*ub].property)));
2804 }
2805
2806 static int
2807 compare_names (gconstpointer a, gconstpointer b)
2808 {
2809   const WidgetPropertyValue *aa = a;
2810   const WidgetPropertyValue *bb = b;
2811   return strcmp (aa->name, bb->name);
2812 }
2813
2814 static void
2815 gtk_css_ruleset_print (const GtkCssRuleset *ruleset,
2816                        GString             *str)
2817 {
2818   GList *values, *walk;
2819   WidgetPropertyValue *widget_value;
2820   guint i;
2821
2822   _gtk_css_selector_print (ruleset->selector, str);
2823
2824   g_string_append (str, " {\n");
2825
2826   if (ruleset->styles)
2827     {
2828       guint *sorted = g_new (guint, ruleset->n_styles);
2829
2830       for (i = 0; i < ruleset->n_styles; i++)
2831         sorted[i] = i;
2832
2833       /* so the output is identical for identical selector styles */
2834       g_qsort_with_data (sorted, ruleset->n_styles, sizeof (guint), compare_properties, ruleset->styles);
2835
2836       for (i = 0; i < ruleset->n_styles; i++)
2837         {
2838           PropertyValue *prop = &ruleset->styles[sorted[i]];
2839           g_string_append (str, "  ");
2840           g_string_append (str, _gtk_style_property_get_name (GTK_STYLE_PROPERTY (prop->property)));
2841           g_string_append (str, ": ");
2842           _gtk_css_style_property_print_value (prop->property, prop->value, str);
2843           g_string_append (str, ";\n");
2844         }
2845
2846       g_free (sorted);
2847     }
2848
2849   if (ruleset->widget_style)
2850     {
2851       values = NULL;
2852       for (widget_value = ruleset->widget_style; widget_value != NULL; widget_value = widget_value->next)
2853         values = g_list_prepend (values, widget_value);
2854
2855       /* so the output is identical for identical selector styles */
2856       values = g_list_sort (values, compare_names);
2857
2858       for (walk = values; walk; walk = walk->next)
2859         {
2860           widget_value = walk->data;
2861
2862           g_string_append (str, "  ");
2863           g_string_append (str, widget_value->name);
2864           g_string_append (str, ": ");
2865           g_string_append (str, widget_value->value);
2866           g_string_append (str, ";\n");
2867         }
2868
2869       g_list_free (values);
2870     }
2871
2872   g_string_append (str, "}\n");
2873 }
2874
2875 static void
2876 gtk_css_provider_print_colors (GHashTable *colors,
2877                                GString    *str)
2878 {
2879   GList *keys, *walk;
2880   char *s;
2881
2882   keys = g_hash_table_get_keys (colors);
2883   /* so the output is identical for identical styles */
2884   keys = g_list_sort (keys, (GCompareFunc) strcmp);
2885
2886   for (walk = keys; walk; walk = walk->next)
2887     {
2888       const char *name = walk->data;
2889       GtkSymbolicColor *symbolic = g_hash_table_lookup (colors, (gpointer) name);
2890
2891       g_string_append (str, "@define-color ");
2892       g_string_append (str, name);
2893       g_string_append (str, " ");
2894       s = gtk_symbolic_color_to_string (symbolic);
2895       g_string_append (str, s);
2896       g_free (s);
2897       g_string_append (str, ";\n");
2898     }
2899
2900   g_list_free (keys);
2901 }
2902
2903 /**
2904  * gtk_css_provider_to_string:
2905  * @provider: the provider to write to a string
2906  *
2907  * Convertes the @provider into a string representation in CSS
2908  * format.
2909  * 
2910  * Using gtk_css_provider_load_from_data() with the return value
2911  * from this function on a new provider created with
2912  * gtk_css_provider_new() will basicallu create a duplicate of
2913  * this @provider.
2914  *
2915  * Returns: a new string representing the @provider.
2916  *
2917  * Since: 3.2
2918  **/
2919 char *
2920 gtk_css_provider_to_string (GtkCssProvider *provider)
2921 {
2922   GtkCssProviderPrivate *priv;
2923   GString *str;
2924   guint i;
2925
2926   g_return_val_if_fail (GTK_IS_CSS_PROVIDER (provider), NULL);
2927
2928   priv = provider->priv;
2929
2930   str = g_string_new ("");
2931
2932   gtk_css_provider_print_colors (priv->symbolic_colors, str);
2933
2934   for (i = 0; i < priv->rulesets->len; i++)
2935     {
2936       if (str->len != 0)
2937         g_string_append (str, "\n");
2938       gtk_css_ruleset_print (&g_array_index (priv->rulesets, GtkCssRuleset, i), str);
2939     }
2940
2941   return g_string_free (str, FALSE);
2942 }
2943