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