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