]> Pileus Git - ~andy/gtk/blob - gtk/gtkcssprovider.c
cssprovider: Store current properties and selectors in scanner
[~andy/gtk] / gtk / gtkcssprovider.c
1 /* GTK - The GIMP Toolkit
2  * Copyright (C) 2010 Carlos Garnacho <carlosg@gnome.org>
3  *
4  * This library is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Lesser General Public
6  * License as published by the Free Software Foundation; either
7  * version 2 of the License, or (at your option) any later version.
8  *
9  * This library is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * Lesser General Public License for more details.
13  *
14  * You should have received a copy of the GNU Lesser General Public
15  * License along with this library; if not, 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   /* Current parser state */
805   GError *error;
806 };
807
808 enum ParserScope {
809   SCOPE_SELECTOR,
810   SCOPE_PSEUDO_CLASS,
811   SCOPE_NTH_CHILD,
812   SCOPE_DECLARATION,
813   SCOPE_VALUE,
814   SCOPE_BINDING_SET
815 };
816
817 /* Extend GtkStateType, since these
818  * values are also used as symbols
819  */
820 enum ParserSymbol {
821   /* Scope: pseudo-class */
822   SYMBOL_NTH_CHILD = GTK_STATE_FOCUSED + 1,
823   SYMBOL_FIRST_CHILD,
824   SYMBOL_LAST_CHILD,
825   SYMBOL_SORTED_CHILD,
826
827   /* Scope: nth-child */
828   SYMBOL_NTH_CHILD_EVEN,
829   SYMBOL_NTH_CHILD_ODD,
830   SYMBOL_NTH_CHILD_FIRST,
831   SYMBOL_NTH_CHILD_LAST
832 };
833
834 enum {
835   PARSING_ERROR,
836   LAST_SIGNAL
837 };
838
839 static guint css_provider_signals[LAST_SIGNAL] = { 0 };
840
841 static void gtk_css_provider_finalize (GObject *object);
842 static void gtk_css_style_provider_iface_init (GtkStyleProviderIface *iface);
843
844 static void scanner_apply_scope (GScanner    *scanner,
845                                  ParserScope  scope);
846 static void     css_provider_reset_parser (GtkCssProvider *css_provider);
847 static gboolean gtk_css_provider_load_from_path_internal (GtkCssProvider  *css_provider,
848                                                           const gchar     *path,
849                                                           gboolean         reset,
850                                                           GError         **error);
851 static void     gtk_css_provider_take_error (GtkCssProvider *provider,
852                                              GScanner       *scanner,
853                                              GError         *error);
854
855 GQuark
856 gtk_css_provider_error_quark (void)
857 {
858   return g_quark_from_static_string ("gtk-css-provider-error-quark");
859 }
860
861 G_DEFINE_TYPE_EXTENDED (GtkCssProvider, gtk_css_provider, G_TYPE_OBJECT, 0,
862                         G_IMPLEMENT_INTERFACE (GTK_TYPE_STYLE_PROVIDER,
863                                                gtk_css_style_provider_iface_init));
864
865 static void
866 gtk_css_provider_parsing_error (GtkCssProvider  *provider,
867                                 const gchar     *path,
868                                 guint            line,
869                                 guint            position,
870                                 const GError *   error)
871 {
872   GtkCssProviderPrivate *priv = provider->priv;
873
874   if (!priv->error)
875     {
876       priv->error = g_error_copy (error);
877       g_prefix_error (&priv->error, "%s:%u:%u: ", path ? path : "<unknown>", line, position);
878     }
879 }
880
881 static void
882 gtk_css_provider_class_init (GtkCssProviderClass *klass)
883 {
884   GObjectClass *object_class = G_OBJECT_CLASS (klass);
885
886   /**
887    * GtkCssProvider::parsing-error:
888    * @provider: the provider that had a parsing error
889    * @path: path to the parsed file or %NULL if the file cannot be
890    *   identified or the data was not loaded from a file
891    * @line: line in the file or data or 0 if unknown
892    * @position: offset into the current line or 0 if unknown or the
893    *   whole line is affected
894    * @error: The parsing error
895    *
896    * Signals that a parsing error occured. the @path, @line and @position
897    * describe the actual location of the error as accurately as possible.
898    *
899    * Parsing errors are never fatal, so the parsing will resume after
900    * the error. Errors may however cause parts of the given
901    * data or even all of it to not be parsed at all. So it is a useful idea
902    * to check that the parsing succeeds by connecting to this signal.
903    *
904    * Note that this signal may be emitted at any time as the css provider
905    * may opt to defer parsing parts or all of the input to a later time
906    * than when a loading function was called.
907    */
908   css_provider_signals[PARSING_ERROR] =
909     g_signal_new (I_("parsing-error"),
910                   G_TYPE_FROM_CLASS (object_class),
911                   G_SIGNAL_RUN_LAST,
912                   G_STRUCT_OFFSET (GtkCssProviderClass, parsing_error),
913                   NULL, NULL,
914                   _gtk_marshal_VOID__STRING_UINT_UINT_BOXED,
915                   G_TYPE_NONE, 4,
916                   G_TYPE_STRING, G_TYPE_UINT, G_TYPE_UINT, G_TYPE_ERROR);
917
918   object_class->finalize = gtk_css_provider_finalize;
919
920   klass->parsing_error = gtk_css_provider_parsing_error;
921
922   g_type_class_add_private (object_class, sizeof (GtkCssProviderPrivate));
923 }
924
925 static SelectorPath *
926 selector_path_new (void)
927 {
928   SelectorPath *path;
929
930   path = g_slice_new0 (SelectorPath);
931   path->ref_count = 1;
932
933   return path;
934 }
935
936 static SelectorPath *
937 selector_path_ref (SelectorPath *path)
938 {
939   path->ref_count++;
940   return path;
941 }
942
943 static void
944 selector_path_unref (SelectorPath *path)
945 {
946   path->ref_count--;
947
948   if (path->ref_count > 0)
949     return;
950
951   while (path->elements)
952     {
953       g_slice_free (SelectorElement, path->elements->data);
954       path->elements = g_slist_delete_link (path->elements, path->elements);
955     }
956
957   g_slice_free (SelectorPath, path);
958 }
959
960 static void
961 selector_path_prepend_type (SelectorPath *path,
962                             const gchar  *type_name)
963 {
964   SelectorElement *elem;
965   GType type;
966
967   elem = g_slice_new (SelectorElement);
968   elem->combinator = COMBINATOR_DESCENDANT;
969   type = g_type_from_name (type_name);
970
971   if (type == G_TYPE_INVALID)
972     {
973       elem->elem_type = SELECTOR_TYPE_NAME;
974       elem->name = g_quark_from_string (type_name);
975     }
976   else
977     {
978       elem->elem_type = SELECTOR_GTYPE;
979       elem->type = type;
980     }
981
982   path->elements = g_slist_prepend (path->elements, elem);
983 }
984
985 static void
986 selector_path_prepend_glob (SelectorPath *path)
987 {
988   SelectorElement *elem;
989
990   elem = g_slice_new (SelectorElement);
991   elem->elem_type = SELECTOR_GLOB;
992   elem->combinator = COMBINATOR_DESCENDANT;
993
994   path->elements = g_slist_prepend (path->elements, elem);
995 }
996
997 static void
998 selector_path_prepend_region (SelectorPath   *path,
999                               const gchar    *name,
1000                               GtkRegionFlags  flags)
1001 {
1002   SelectorElement *elem;
1003
1004   elem = g_slice_new (SelectorElement);
1005   elem->combinator = COMBINATOR_DESCENDANT;
1006   elem->elem_type = SELECTOR_REGION;
1007
1008   elem->region.name = g_quark_from_string (name);
1009   elem->region.flags = flags;
1010
1011   path->elements = g_slist_prepend (path->elements, elem);
1012 }
1013
1014 static void
1015 selector_path_prepend_name (SelectorPath *path,
1016                             const gchar  *name)
1017 {
1018   SelectorElement *elem;
1019
1020   elem = g_slice_new (SelectorElement);
1021   elem->combinator = COMBINATOR_DESCENDANT;
1022   elem->elem_type = SELECTOR_NAME;
1023
1024   elem->name = g_quark_from_string (name);
1025
1026   path->elements = g_slist_prepend (path->elements, elem);
1027 }
1028
1029 static void
1030 selector_path_prepend_class (SelectorPath *path,
1031                              const gchar  *name)
1032 {
1033   SelectorElement *elem;
1034
1035   elem = g_slice_new (SelectorElement);
1036   elem->combinator = COMBINATOR_DESCENDANT;
1037   elem->elem_type = SELECTOR_CLASS;
1038
1039   elem->name = g_quark_from_string (name);
1040
1041   path->elements = g_slist_prepend (path->elements, elem);
1042 }
1043
1044 static void
1045 selector_path_prepend_combinator (SelectorPath   *path,
1046                                   CombinatorType  combinator)
1047 {
1048   SelectorElement *elem;
1049
1050   g_assert (path->elements != NULL);
1051
1052   /* It is actually stored in the last element */
1053   elem = path->elements->data;
1054   elem->combinator = combinator;
1055 }
1056
1057 static gint
1058 selector_path_depth (SelectorPath *path)
1059 {
1060   return g_slist_length (path->elements);
1061 }
1062
1063 static SelectorStyleInfo *
1064 selector_style_info_new (SelectorPath *path)
1065 {
1066   SelectorStyleInfo *info;
1067
1068   info = g_slice_new0 (SelectorStyleInfo);
1069   info->path = selector_path_ref (path);
1070
1071   return info;
1072 }
1073
1074 static void
1075 selector_style_info_free (SelectorStyleInfo *info)
1076 {
1077   if (info->style)
1078     g_hash_table_unref (info->style);
1079
1080   if (info->path)
1081     selector_path_unref (info->path);
1082
1083   g_slice_free (SelectorStyleInfo, info);
1084 }
1085
1086 static void
1087 selector_style_info_set_style (SelectorStyleInfo *info,
1088                                GHashTable        *style)
1089 {
1090   if (info->style)
1091     g_hash_table_unref (info->style);
1092
1093   if (style)
1094     info->style = g_hash_table_ref (style);
1095   else
1096     info->style = NULL;
1097 }
1098
1099 static void
1100 property_value_free (GValue *value)
1101 {
1102   if (G_IS_VALUE (value))
1103     g_value_unset (value);
1104
1105   g_slice_free (GValue, value);
1106 }
1107
1108 static void
1109 gtk_css_scanner_reset (GScanner *scanner)
1110 {
1111   GtkCssScannerPrivate *priv = scanner->user_data;
1112
1113   g_slist_free (priv->state);
1114   priv->state = NULL;
1115
1116   g_slist_foreach (priv->cur_selectors, (GFunc) selector_path_unref, NULL);
1117   g_slist_free (priv->cur_selectors);
1118   priv->cur_selectors = NULL;
1119
1120   if (priv->cur_properties)
1121     g_hash_table_unref (priv->cur_properties);
1122
1123   priv->cur_properties = g_hash_table_new_full (g_str_hash,
1124                                                 g_str_equal,
1125                                                 (GDestroyNotify) g_free,
1126                                                 (GDestroyNotify) property_value_free);
1127
1128   scanner_apply_scope (scanner, SCOPE_SELECTOR);
1129 }
1130
1131 static void
1132 gtk_css_scanner_destroy (GScanner *scanner)
1133 {
1134   GtkCssScannerPrivate *priv = scanner->user_data;
1135
1136   gtk_css_scanner_reset (scanner);
1137
1138   g_hash_table_destroy (priv->cur_properties);
1139   g_slice_free (GtkCssScannerPrivate, priv);
1140   
1141   g_scanner_destroy (scanner);
1142 }
1143
1144 static GScanner *
1145 gtk_css_provider_create_scanner (GtkCssProvider *provider)
1146 {
1147   GtkCssScannerPrivate *priv;
1148   GScanner *scanner;
1149
1150   scanner = g_scanner_new (NULL);
1151
1152   priv = scanner->user_data = g_slice_new0 (GtkCssScannerPrivate);
1153
1154   priv->cur_properties = g_hash_table_new_full (g_str_hash,
1155                                                 g_str_equal,
1156                                                 (GDestroyNotify) g_free,
1157                                                 (GDestroyNotify) property_value_free);
1158
1159   g_scanner_scope_add_symbol (scanner, SCOPE_PSEUDO_CLASS, "active", GUINT_TO_POINTER (GTK_STATE_ACTIVE));
1160   g_scanner_scope_add_symbol (scanner, SCOPE_PSEUDO_CLASS, "prelight", GUINT_TO_POINTER (GTK_STATE_PRELIGHT));
1161   g_scanner_scope_add_symbol (scanner, SCOPE_PSEUDO_CLASS, "hover", GUINT_TO_POINTER (GTK_STATE_PRELIGHT));
1162   g_scanner_scope_add_symbol (scanner, SCOPE_PSEUDO_CLASS, "selected", GUINT_TO_POINTER (GTK_STATE_SELECTED));
1163   g_scanner_scope_add_symbol (scanner, SCOPE_PSEUDO_CLASS, "insensitive", GUINT_TO_POINTER (GTK_STATE_INSENSITIVE));
1164   g_scanner_scope_add_symbol (scanner, SCOPE_PSEUDO_CLASS, "inconsistent", GUINT_TO_POINTER (GTK_STATE_INCONSISTENT));
1165   g_scanner_scope_add_symbol (scanner, SCOPE_PSEUDO_CLASS, "focused", GUINT_TO_POINTER (GTK_STATE_FOCUSED));
1166   g_scanner_scope_add_symbol (scanner, SCOPE_PSEUDO_CLASS, "focus", GUINT_TO_POINTER (GTK_STATE_FOCUSED));
1167
1168   g_scanner_scope_add_symbol (scanner, SCOPE_PSEUDO_CLASS, "nth-child", GUINT_TO_POINTER (SYMBOL_NTH_CHILD));
1169   g_scanner_scope_add_symbol (scanner, SCOPE_PSEUDO_CLASS, "first-child", GUINT_TO_POINTER (SYMBOL_FIRST_CHILD));
1170   g_scanner_scope_add_symbol (scanner, SCOPE_PSEUDO_CLASS, "last-child", GUINT_TO_POINTER (SYMBOL_LAST_CHILD));
1171   g_scanner_scope_add_symbol (scanner, SCOPE_PSEUDO_CLASS, "sorted", GUINT_TO_POINTER (SYMBOL_SORTED_CHILD));
1172
1173   g_scanner_scope_add_symbol (scanner, SCOPE_NTH_CHILD, "even", GUINT_TO_POINTER (SYMBOL_NTH_CHILD_EVEN));
1174   g_scanner_scope_add_symbol (scanner, SCOPE_NTH_CHILD, "odd", GUINT_TO_POINTER (SYMBOL_NTH_CHILD_ODD));
1175   g_scanner_scope_add_symbol (scanner, SCOPE_NTH_CHILD, "first", GUINT_TO_POINTER (SYMBOL_NTH_CHILD_FIRST));
1176   g_scanner_scope_add_symbol (scanner, SCOPE_NTH_CHILD, "last", GUINT_TO_POINTER (SYMBOL_NTH_CHILD_LAST));
1177
1178   scanner_apply_scope (scanner, SCOPE_SELECTOR);
1179
1180   return scanner;
1181 }
1182
1183 static void
1184 gtk_css_provider_init (GtkCssProvider *css_provider)
1185 {
1186   GtkCssProviderPrivate *priv;
1187
1188   priv = css_provider->priv = G_TYPE_INSTANCE_GET_PRIVATE (css_provider,
1189                                                            GTK_TYPE_CSS_PROVIDER,
1190                                                            GtkCssProviderPrivate);
1191
1192   priv->selectors_info = g_ptr_array_new_with_free_func ((GDestroyNotify) selector_style_info_free);
1193   priv->scanner = gtk_css_provider_create_scanner (css_provider);
1194
1195   priv->symbolic_colors = g_hash_table_new_full (g_str_hash, g_str_equal,
1196                                                  (GDestroyNotify) g_free,
1197                                                  (GDestroyNotify) gtk_symbolic_color_unref);
1198 }
1199
1200 typedef struct ComparePathData ComparePathData;
1201
1202 struct ComparePathData
1203 {
1204   guint64 score;
1205   SelectorPath *path;
1206   GSList *iter;
1207 };
1208
1209 static gboolean
1210 compare_selector_element (GtkWidgetPath   *path,
1211                           guint            index,
1212                           SelectorElement *elem,
1213                           guint8          *score)
1214 {
1215   *score = 0;
1216
1217   if (elem->elem_type == SELECTOR_TYPE_NAME)
1218     {
1219       const gchar *type_name;
1220       GType resolved_type;
1221
1222       /* Resolve the type name */
1223       type_name = g_quark_to_string (elem->name);
1224       resolved_type = g_type_from_name (type_name);
1225
1226       if (resolved_type == G_TYPE_INVALID)
1227         {
1228           /* Type couldn't be resolved, so the selector
1229            * clearly doesn't affect the given widget path
1230            */
1231           return FALSE;
1232         }
1233
1234       elem->elem_type = SELECTOR_GTYPE;
1235       elem->type = resolved_type;
1236     }
1237
1238   if (elem->elem_type == SELECTOR_GTYPE)
1239     {
1240       GType type;
1241
1242       type = gtk_widget_path_iter_get_object_type (path, index);
1243
1244       if (!g_type_is_a (type, elem->type))
1245         return FALSE;
1246
1247       if (type == elem->type)
1248         *score |= 0xF;
1249       else
1250         {
1251           guint diff = g_type_depth (type) - g_type_depth (elem->type);
1252
1253           if (G_UNLIKELY (diff > 0xE))
1254             {
1255               g_warning ("Hierarchy is higher than expected.");
1256               diff = 0xE;
1257             }
1258           
1259           *score = 0XF - diff;
1260         }
1261
1262       return TRUE;
1263     }
1264   else if (elem->elem_type == SELECTOR_REGION)
1265     {
1266       GtkRegionFlags flags;
1267
1268       if (!gtk_widget_path_iter_has_qregion (path, index,
1269                                              elem->region.name,
1270                                              &flags))
1271         return FALSE;
1272
1273       if (elem->region.flags != 0 &&
1274           (flags & elem->region.flags) == 0)
1275         return FALSE;
1276
1277       *score = 0xF;
1278       return TRUE;
1279     }
1280   else if (elem->elem_type == SELECTOR_GLOB)
1281     {
1282       /* Treat as lowest matching type */
1283       *score = 1;
1284       return TRUE;
1285     }
1286   else if (elem->elem_type == SELECTOR_NAME)
1287     {
1288       if (!gtk_widget_path_iter_has_qname (path, index, elem->name))
1289         return FALSE;
1290
1291       *score = 0xF;
1292       return TRUE;
1293     }
1294   else if (elem->elem_type == SELECTOR_CLASS)
1295     {
1296       if (!gtk_widget_path_iter_has_qclass (path, index, elem->name))
1297         return FALSE;
1298
1299       *score = 0xF;
1300       return TRUE;
1301     }
1302
1303   return FALSE;
1304 }
1305
1306 static guint64
1307 compare_selector (GtkWidgetPath *path,
1308                   SelectorPath  *selector)
1309 {
1310   GSList *elements = selector->elements;
1311   gboolean match = TRUE, first = TRUE, first_match = FALSE;
1312   guint64 score = 0;
1313   gint i;
1314
1315   i = gtk_widget_path_length (path) - 1;
1316
1317   while (elements && match && i >= 0)
1318     {
1319       SelectorElement *elem;
1320       guint8 elem_score;
1321
1322       elem = elements->data;
1323
1324       match = compare_selector_element (path, i, elem, &elem_score);
1325
1326       if (match && first)
1327         first_match = TRUE;
1328
1329       /* Only move on to the next index if there is no match
1330        * with the current element (whether to continue or not
1331        * handled right after in the combinator check), or a
1332        * GType or glob has just been matched.
1333        *
1334        * Region and widget names do not trigger this because
1335        * the next element in the selector path could also be
1336        * related to the same index.
1337        */
1338       if (!match ||
1339           (elem->elem_type == SELECTOR_GTYPE ||
1340            elem->elem_type == SELECTOR_GLOB))
1341         i--;
1342
1343       if (!match &&
1344           elem->elem_type != SELECTOR_TYPE_NAME &&
1345           elem->combinator == COMBINATOR_DESCENDANT)
1346         {
1347           /* With descendant combinators there may
1348            * be intermediate chidren in the hierarchy
1349            */
1350           match = TRUE;
1351         }
1352       else if (match)
1353         elements = elements->next;
1354
1355       if (match)
1356         {
1357           /* Only 4 bits are actually used */
1358           score <<= 4;
1359           score |= elem_score;
1360         }
1361
1362       first = FALSE;
1363     }
1364
1365   /* If there are pending selector
1366    * elements to compare, it's not
1367    * a match.
1368    */
1369   if (elements)
1370     match = FALSE;
1371
1372   if (!match)
1373     score = 0;
1374   else if (first_match)
1375     {
1376       /* Assign more weight to these selectors
1377        * that matched right from the first element.
1378        */
1379       score <<= 4;
1380     }
1381
1382   return score;
1383 }
1384
1385 typedef struct StylePriorityInfo StylePriorityInfo;
1386
1387 struct StylePriorityInfo
1388 {
1389   guint64 score;
1390   GHashTable *style;
1391   GtkStateFlags state;
1392 };
1393
1394 static GArray *
1395 css_provider_get_selectors (GtkCssProvider *css_provider,
1396                             GtkWidgetPath  *path)
1397 {
1398   GtkCssProviderPrivate *priv;
1399   GArray *priority_info;
1400   guint i, j;
1401
1402   priv = css_provider->priv;
1403   priority_info = g_array_new (FALSE, FALSE, sizeof (StylePriorityInfo));
1404
1405   for (i = 0; i < priv->selectors_info->len; i++)
1406     {
1407       SelectorStyleInfo *info;
1408       StylePriorityInfo new;
1409       gboolean added = FALSE;
1410       guint64 score;
1411
1412       info = g_ptr_array_index (priv->selectors_info, i);
1413       score = compare_selector (path, info->path);
1414
1415       if (score <= 0)
1416         continue;
1417
1418       new.score = score;
1419       new.style = info->style;
1420       new.state = info->path->state;
1421
1422       for (j = 0; j < priority_info->len; j++)
1423         {
1424           StylePriorityInfo *cur;
1425
1426           cur = &g_array_index (priority_info, StylePriorityInfo, j);
1427
1428           if (cur->score > new.score)
1429             {
1430               g_array_insert_val (priority_info, j, new);
1431               added = TRUE;
1432               break;
1433             }
1434         }
1435
1436       if (!added)
1437         g_array_append_val (priority_info, new);
1438     }
1439
1440   return priority_info;
1441 }
1442
1443 static void
1444 css_provider_dump_symbolic_colors (GtkCssProvider     *css_provider,
1445                                    GtkStyleProperties *props)
1446 {
1447   GtkCssProviderPrivate *priv;
1448   GHashTableIter iter;
1449   gpointer key, value;
1450
1451   priv = css_provider->priv;
1452   g_hash_table_iter_init (&iter, priv->symbolic_colors);
1453
1454   while (g_hash_table_iter_next (&iter, &key, &value))
1455     {
1456       const gchar *name;
1457       GtkSymbolicColor *color;
1458
1459       name = key;
1460       color = value;
1461
1462       gtk_style_properties_map_color (props, name, color);
1463     }
1464 }
1465
1466 static GtkStyleProperties *
1467 gtk_css_provider_get_style (GtkStyleProvider *provider,
1468                             GtkWidgetPath    *path)
1469 {
1470   GtkCssProvider *css_provider;
1471   GtkStyleProperties *props;
1472   GArray *priority_info;
1473   guint i;
1474
1475   css_provider = GTK_CSS_PROVIDER (provider);
1476   props = gtk_style_properties_new ();
1477
1478   css_provider_dump_symbolic_colors (css_provider, props);
1479   priority_info = css_provider_get_selectors (css_provider, path);
1480
1481   for (i = 0; i < priority_info->len; i++)
1482     {
1483       StylePriorityInfo *info;
1484       GHashTableIter iter;
1485       gpointer key, value;
1486
1487       info = &g_array_index (priority_info, StylePriorityInfo, i);
1488       g_hash_table_iter_init (&iter, info->style);
1489
1490       while (g_hash_table_iter_next (&iter, &key, &value))
1491         {
1492           gchar *prop = key;
1493
1494           /* Properties starting with '-' may be both widget style properties
1495            * or custom properties from the theming engine, so check whether
1496            * the type is registered or not.
1497            */
1498           if (prop[0] == '-' &&
1499               !gtk_style_properties_lookup_property (prop, NULL, NULL))
1500             continue;
1501
1502           gtk_style_properties_set_property (props, key, info->state, value);
1503         }
1504     }
1505
1506   g_array_free (priority_info, TRUE);
1507
1508   return props;
1509 }
1510
1511 static gboolean
1512 gtk_css_provider_get_style_property (GtkStyleProvider *provider,
1513                                      GtkWidgetPath    *path,
1514                                      GtkStateFlags     state,
1515                                      GParamSpec       *pspec,
1516                                      GValue           *value)
1517 {
1518   GArray *priority_info;
1519   gboolean found = FALSE;
1520   gchar *prop_name;
1521   gint i;
1522
1523   prop_name = g_strdup_printf ("-%s-%s",
1524                                g_type_name (pspec->owner_type),
1525                                pspec->name);
1526
1527   priority_info = css_provider_get_selectors (GTK_CSS_PROVIDER (provider), path);
1528
1529   for (i = priority_info->len - 1; i >= 0; i--)
1530     {
1531       StylePriorityInfo *info;
1532       GValue *val;
1533
1534       info = &g_array_index (priority_info, StylePriorityInfo, i);
1535       val = g_hash_table_lookup (info->style, prop_name);
1536
1537       if (val &&
1538           (info->state == 0 ||
1539            info->state == state ||
1540            ((info->state & state) != 0 &&
1541             (info->state & ~(state)) == 0)))
1542         {
1543           GError *error = NULL;
1544
1545           found = _gtk_css_value_from_string (value,
1546                                               NULL,
1547                                               g_value_get_string (val),
1548                                               &error);
1549
1550           if (found)
1551             break;
1552           
1553           gtk_css_provider_take_error (GTK_CSS_PROVIDER (provider), NULL, error);
1554         }
1555     }
1556
1557   g_array_free (priority_info, TRUE);
1558   g_free (prop_name);
1559
1560   return found;
1561 }
1562
1563 static void
1564 gtk_css_style_provider_iface_init (GtkStyleProviderIface *iface)
1565 {
1566   iface->get_style = gtk_css_provider_get_style;
1567   iface->get_style_property = gtk_css_provider_get_style_property;
1568 }
1569
1570 static void
1571 gtk_css_provider_finalize (GObject *object)
1572 {
1573   GtkCssProvider *css_provider;
1574   GtkCssProviderPrivate *priv;
1575
1576   css_provider = GTK_CSS_PROVIDER (object);
1577   priv = css_provider->priv;
1578
1579   css_provider_reset_parser (css_provider);
1580
1581   gtk_css_scanner_destroy (priv->scanner);
1582
1583   g_ptr_array_free (priv->selectors_info, TRUE);
1584
1585   if (priv->symbolic_colors)
1586     g_hash_table_destroy (priv->symbolic_colors);
1587
1588   G_OBJECT_CLASS (gtk_css_provider_parent_class)->finalize (object);
1589 }
1590
1591 /**
1592  * gtk_css_provider_new:
1593  *
1594  * Returns a newly created #GtkCssProvider.
1595  *
1596  * Returns: A new #GtkCssProvider
1597  **/
1598 GtkCssProvider *
1599 gtk_css_provider_new (void)
1600 {
1601   return g_object_new (GTK_TYPE_CSS_PROVIDER, NULL);
1602 }
1603
1604 static void
1605 gtk_css_provider_take_error (GtkCssProvider *provider,
1606                              GScanner       *scanner,
1607                              GError         *error)
1608 {
1609   const char *filename;
1610   guint line, position;
1611
1612   if (scanner)
1613     {
1614       filename = scanner->input_name;
1615       line = scanner->line;
1616       position = scanner->position;
1617     }
1618   else
1619     {
1620       filename = NULL;
1621       line = 0;
1622       position = 0;
1623     }
1624
1625   g_signal_emit (provider, css_provider_signals[PARSING_ERROR], 0,
1626                  filename, line, position, error);
1627
1628   g_error_free (error);
1629 }
1630
1631 static void
1632 gtk_css_provider_error_literal (GtkCssProvider *provider,
1633                                 GScanner       *scanner,
1634                                 GQuark          domain,
1635                                 gint            code,
1636                                 const char     *message)
1637 {
1638   gtk_css_provider_take_error (provider,
1639                                scanner,
1640                                g_error_new_literal (domain, code, message));
1641 }
1642
1643 static void
1644 gtk_css_provider_error (GtkCssProvider *provider,
1645                         GScanner       *scanner,
1646                         GQuark          domain,
1647                         gint            code,
1648                         const char     *format,
1649                         ...)  G_GNUC_PRINTF (5, 6);
1650 static void
1651 gtk_css_provider_error (GtkCssProvider *provider,
1652                         GScanner       *scanner,
1653                         GQuark          domain,
1654                         gint            code,
1655                         const char     *format,
1656                         ...)
1657 {
1658   GError *error;
1659   va_list args;
1660
1661   va_start (args, format);
1662   error = g_error_new_valist (domain, code, format, args);
1663   va_end (args);
1664
1665   gtk_css_provider_take_error (provider, scanner, error);
1666 }
1667
1668 static void
1669 gtk_css_provider_invalid_token (GtkCssProvider *provider,
1670                                 GScanner       *scanner,
1671                                 const char     *expected)
1672 {
1673   gtk_css_provider_error (provider,
1674                           scanner,
1675                           GTK_CSS_PROVIDER_ERROR,
1676                           GTK_CSS_PROVIDER_ERROR_SYNTAX,
1677                           "expected a valid %s", expected);
1678 }
1679
1680 static void
1681 scanner_apply_scope (GScanner    *scanner,
1682                      ParserScope  scope)
1683 {
1684   g_scanner_set_scope (scanner, scope);
1685
1686   if (scope == SCOPE_VALUE)
1687     {
1688       scanner->config->cset_identifier_first = G_CSET_a_2_z G_CSET_A_2_Z G_CSET_DIGITS "@#-_";
1689       scanner->config->cset_identifier_nth = G_CSET_a_2_z G_CSET_A_2_Z G_CSET_DIGITS "@#-_ +(),.%\t\n'/\"";
1690       scanner->config->scan_identifier_1char = TRUE;
1691     }
1692   else if (scope == SCOPE_BINDING_SET)
1693     {
1694       scanner->config->cset_identifier_first = G_CSET_a_2_z G_CSET_A_2_Z G_CSET_DIGITS "@#-_";
1695       scanner->config->cset_identifier_nth = G_CSET_a_2_z G_CSET_A_2_Z G_CSET_DIGITS "@#-_ +(){}<>,.%\t\n'/\"";
1696       scanner->config->scan_identifier_1char = TRUE;
1697     }
1698   else if (scope == SCOPE_SELECTOR)
1699     {
1700       scanner->config->cset_identifier_first = G_CSET_a_2_z G_CSET_A_2_Z "*@";
1701       scanner->config->cset_identifier_nth = G_CSET_a_2_z G_CSET_A_2_Z G_CSET_DIGITS "-_#.";
1702       scanner->config->scan_identifier_1char = TRUE;
1703     }
1704   else if (scope == SCOPE_PSEUDO_CLASS ||
1705            scope == SCOPE_NTH_CHILD ||
1706            scope == SCOPE_DECLARATION)
1707     {
1708       scanner->config->cset_identifier_first = G_CSET_a_2_z G_CSET_A_2_Z "-_";
1709       scanner->config->cset_identifier_nth = G_CSET_a_2_z G_CSET_A_2_Z G_CSET_DIGITS "-_";
1710       scanner->config->scan_identifier_1char = FALSE;
1711     }
1712   else
1713     g_assert_not_reached ();
1714
1715   scanner->config->scan_float = FALSE;
1716   scanner->config->cpair_comment_single = NULL;
1717 }
1718
1719 static void
1720 gtk_css_scanner_push_scope (GScanner    *scanner,
1721                             ParserScope  scope)
1722 {
1723   GtkCssScannerPrivate *priv;
1724
1725   priv = scanner->user_data;
1726   priv->state = g_slist_prepend (priv->state, GUINT_TO_POINTER (scope));
1727
1728   scanner_apply_scope (scanner, scope);
1729 }
1730
1731 static void
1732 gtk_css_scanner_pop_scope (GScanner *scanner)
1733 {
1734   GtkCssScannerPrivate *priv;
1735   ParserScope scope = SCOPE_SELECTOR;
1736
1737   priv = scanner->user_data;
1738
1739   if (!priv->state)
1740     {
1741       g_warning ("Push/pop calls to parser scope aren't paired");
1742       scanner_apply_scope (scanner, SCOPE_SELECTOR);
1743       return;
1744     }
1745
1746   priv->state = g_slist_delete_link (priv->state, priv->state);
1747
1748   /* Fetch new scope */
1749   if (priv->state)
1750     scope = GPOINTER_TO_INT (priv->state->data);
1751
1752   scanner_apply_scope (scanner, scope);
1753 }
1754
1755 static void
1756 css_provider_reset_parser (GtkCssProvider *css_provider)
1757 {
1758   GtkCssProviderPrivate *priv;
1759
1760   priv = css_provider->priv;
1761
1762   gtk_css_scanner_reset (priv->scanner);
1763
1764   if (priv->error)
1765     g_error_free (priv->error);
1766   priv->error = NULL;
1767 }
1768
1769 static void
1770 css_provider_commit (GtkCssProvider *css_provider,
1771                      GScanner       *scanner)
1772 {
1773   GtkCssScannerPrivate *scanner_priv;
1774   GtkCssProviderPrivate *priv;
1775   GSList *l;
1776
1777   priv = css_provider->priv;
1778   scanner_priv = scanner->user_data;
1779
1780   l = scanner_priv->cur_selectors;
1781
1782   if (g_hash_table_size (scanner_priv->cur_properties) == 0)
1783     return;
1784
1785   while (l)
1786     {
1787       SelectorPath *path = l->data;
1788       SelectorStyleInfo *info;
1789
1790       info = selector_style_info_new (path);
1791       selector_style_info_set_style (info, scanner_priv->cur_properties);
1792
1793       g_ptr_array_add (priv->selectors_info, info);
1794       l = l->next;
1795     }
1796 }
1797
1798 static GTokenType
1799 parse_nth_child (GtkCssProvider *css_provider,
1800                  GScanner       *scanner,
1801                  GtkRegionFlags *flags)
1802 {
1803   ParserSymbol symbol;
1804
1805   g_scanner_get_next_token (scanner);
1806
1807   if (scanner->token != G_TOKEN_SYMBOL)
1808     return G_TOKEN_SYMBOL;
1809
1810   symbol = GPOINTER_TO_INT (scanner->value.v_symbol);
1811
1812   if (symbol == SYMBOL_NTH_CHILD)
1813     {
1814       g_scanner_get_next_token (scanner);
1815
1816       if (scanner->token != G_TOKEN_LEFT_PAREN)
1817         return G_TOKEN_LEFT_PAREN;
1818
1819       gtk_css_scanner_push_scope (scanner, SCOPE_NTH_CHILD);
1820       g_scanner_get_next_token (scanner);
1821
1822       if (scanner->token != G_TOKEN_SYMBOL)
1823         return G_TOKEN_SYMBOL;
1824
1825       symbol = GPOINTER_TO_INT (scanner->value.v_symbol);
1826
1827       switch (symbol)
1828         {
1829         case SYMBOL_NTH_CHILD_EVEN:
1830           *flags = GTK_REGION_EVEN;
1831           break;
1832         case SYMBOL_NTH_CHILD_ODD:
1833           *flags = GTK_REGION_ODD;
1834           break;
1835         case SYMBOL_NTH_CHILD_FIRST:
1836           *flags = GTK_REGION_FIRST;
1837           break;
1838         case SYMBOL_NTH_CHILD_LAST:
1839           *flags = GTK_REGION_LAST;
1840           break;
1841         default:
1842           break;
1843         }
1844
1845       g_scanner_get_next_token (scanner);
1846
1847       if (scanner->token != G_TOKEN_RIGHT_PAREN)
1848         return G_TOKEN_RIGHT_PAREN;
1849
1850       gtk_css_scanner_pop_scope (scanner);
1851     }
1852   else if (symbol == SYMBOL_FIRST_CHILD)
1853     *flags = GTK_REGION_FIRST;
1854   else if (symbol == SYMBOL_LAST_CHILD)
1855     *flags = GTK_REGION_LAST;
1856   else if (symbol == SYMBOL_SORTED_CHILD)
1857     *flags = GTK_REGION_SORTED;
1858   else
1859     {
1860       *flags = 0;
1861       return G_TOKEN_SYMBOL;
1862     }
1863
1864   return G_TOKEN_NONE;
1865 }
1866
1867 static GTokenType
1868 parse_pseudo_class (GtkCssProvider *css_provider,
1869                     GScanner       *scanner,
1870                     SelectorPath   *selector)
1871 {
1872   GtkStateType state;
1873
1874   g_scanner_get_next_token (scanner);
1875
1876   if (scanner->token != G_TOKEN_SYMBOL)
1877     return G_TOKEN_SYMBOL;
1878
1879   state = GPOINTER_TO_INT (scanner->value.v_symbol);
1880
1881   switch (state)
1882     {
1883     case GTK_STATE_ACTIVE:
1884       selector->state |= GTK_STATE_FLAG_ACTIVE;
1885       break;
1886     case GTK_STATE_PRELIGHT:
1887       selector->state |= GTK_STATE_FLAG_PRELIGHT;
1888       break;
1889     case GTK_STATE_SELECTED:
1890       selector->state |= GTK_STATE_FLAG_SELECTED;
1891       break;
1892     case GTK_STATE_INSENSITIVE:
1893       selector->state |= GTK_STATE_FLAG_INSENSITIVE;
1894       break;
1895     case GTK_STATE_INCONSISTENT:
1896       selector->state |= GTK_STATE_FLAG_INCONSISTENT;
1897       break;
1898     case GTK_STATE_FOCUSED:
1899       selector->state |= GTK_STATE_FLAG_FOCUSED;
1900       break;
1901     default:
1902       return G_TOKEN_SYMBOL;
1903     }
1904
1905   return G_TOKEN_NONE;
1906 }
1907
1908 /* Parses a number of concatenated classes */
1909 static void
1910 parse_classes (SelectorPath   *path,
1911                const gchar    *str)
1912 {
1913   gchar *pos;
1914
1915   if ((pos = strchr (str, '.')) != NULL)
1916     {
1917       /* Leave the last class to the call after the loop */
1918       while (pos)
1919         {
1920           *pos = '\0';
1921           selector_path_prepend_class (path, str);
1922
1923           str = pos + 1;
1924           pos = strchr (str, '.');
1925         }
1926     }
1927
1928   selector_path_prepend_class (path, str);
1929 }
1930
1931 static gboolean
1932 is_widget_class_name (const gchar *str)
1933 {
1934   /* Do a pretty lax check here, not all
1935    * widget class names contain only CamelCase
1936    * (gtkmm widgets don't), but at least part of
1937    * the name will be CamelCase, so check for
1938    * the first uppercase char
1939    */
1940   while (*str)
1941     {
1942       if (g_ascii_isupper (*str))
1943         return TRUE;
1944
1945       str++;
1946     }
1947
1948   return FALSE;
1949 }
1950
1951 static GTokenType
1952 parse_selector (GtkCssProvider  *css_provider,
1953                 GScanner        *scanner,
1954                 SelectorPath   **selector_out)
1955 {
1956   SelectorPath *path;
1957
1958   path = selector_path_new ();
1959   *selector_out = path;
1960
1961   if (scanner->token != ':' &&
1962       scanner->token != '#' &&
1963       scanner->token != '.' &&
1964       scanner->token != G_TOKEN_IDENTIFIER)
1965     return G_TOKEN_IDENTIFIER;
1966
1967   while (scanner->token == '#' ||
1968          scanner->token == '.' ||
1969          scanner->token == G_TOKEN_IDENTIFIER)
1970     {
1971       if (scanner->token == '#' ||
1972           scanner->token == '.')
1973         {
1974           gboolean is_class;
1975           gchar *pos;
1976
1977           is_class = (scanner->token == '.');
1978
1979           g_scanner_get_next_token (scanner);
1980
1981           if (scanner->token != G_TOKEN_IDENTIFIER)
1982             return G_TOKEN_IDENTIFIER;
1983
1984           selector_path_prepend_glob (path);
1985           selector_path_prepend_combinator (path, COMBINATOR_CHILD);
1986
1987           if (is_class)
1988             parse_classes (path, scanner->value.v_identifier);
1989           else
1990             {
1991               if ((pos = strchr (scanner->value.v_identifier, '.')) != NULL)
1992                 *pos = '\0';
1993
1994               selector_path_prepend_name (path, scanner->value.v_identifier);
1995
1996               /* Parse any remaining classes */
1997               if (pos)
1998                 parse_classes (path, pos + 1);
1999             }
2000         }
2001       else if (is_widget_class_name (scanner->value.v_identifier))
2002         {
2003           gchar *pos;
2004
2005           if ((pos = strchr (scanner->value.v_identifier, '#')) != NULL ||
2006               (pos = strchr (scanner->value.v_identifier, '.')) != NULL)
2007             {
2008               gchar *type_name, *name;
2009               gboolean is_class;
2010
2011               is_class = (*pos == '.');
2012
2013               /* Widget type and name/class put together */
2014               name = pos + 1;
2015               *pos = '\0';
2016               type_name = scanner->value.v_identifier;
2017
2018               selector_path_prepend_type (path, type_name);
2019
2020               /* This is only so there is a direct relationship
2021                * between widget type and its name.
2022                */
2023               selector_path_prepend_combinator (path, COMBINATOR_CHILD);
2024
2025               if (is_class)
2026                 parse_classes (path, name);
2027               else
2028                 {
2029                   if ((pos = strchr (name, '.')) != NULL)
2030                     *pos = '\0';
2031
2032                   selector_path_prepend_name (path, name);
2033
2034                   /* Parse any remaining classes */
2035                   if (pos)
2036                     parse_classes (path, pos + 1);
2037                 }
2038             }
2039           else
2040             selector_path_prepend_type (path, scanner->value.v_identifier);
2041         }
2042       else if (_gtk_style_context_check_region_name (scanner->value.v_identifier))
2043         {
2044           GtkRegionFlags flags = 0;
2045           gchar *region_name;
2046
2047           region_name = g_strdup (scanner->value.v_identifier);
2048
2049           if (g_scanner_peek_next_token (scanner) == ':')
2050             {
2051               ParserSymbol symbol;
2052
2053               g_scanner_get_next_token (scanner);
2054               gtk_css_scanner_push_scope (scanner, SCOPE_PSEUDO_CLASS);
2055
2056               /* Check for the next token being nth-child, parse in that
2057                * case, and fallback into common state parsing if not.
2058                */
2059               if (g_scanner_peek_next_token (scanner) != G_TOKEN_SYMBOL)
2060                 return G_TOKEN_SYMBOL;
2061
2062               symbol = GPOINTER_TO_INT (scanner->next_value.v_symbol);
2063
2064               if (symbol == SYMBOL_FIRST_CHILD ||
2065                   symbol == SYMBOL_LAST_CHILD ||
2066                   symbol == SYMBOL_NTH_CHILD ||
2067                   symbol == SYMBOL_SORTED_CHILD)
2068                 {
2069                   GTokenType token;
2070
2071                   if ((token = parse_nth_child (css_provider, scanner, &flags)) != G_TOKEN_NONE)
2072                     return token;
2073
2074                   gtk_css_scanner_pop_scope (scanner);
2075                 }
2076               else
2077                 {
2078                   gtk_css_scanner_pop_scope (scanner);
2079                   selector_path_prepend_region (path, region_name, 0);
2080                   g_free (region_name);
2081                   break;
2082                 }
2083             }
2084
2085           selector_path_prepend_region (path, region_name, flags);
2086           g_free (region_name);
2087         }
2088       else if (scanner->value.v_identifier[0] == '*')
2089         selector_path_prepend_glob (path);
2090       else
2091         return G_TOKEN_IDENTIFIER;
2092
2093       g_scanner_get_next_token (scanner);
2094
2095       if (scanner->token == '>')
2096         {
2097           selector_path_prepend_combinator (path, COMBINATOR_CHILD);
2098           g_scanner_get_next_token (scanner);
2099         }
2100     }
2101
2102   if (scanner->token == ':')
2103     {
2104       /* Add glob selector if path is empty */
2105       if (selector_path_depth (path) == 0)
2106         selector_path_prepend_glob (path);
2107
2108       gtk_css_scanner_push_scope (scanner, SCOPE_PSEUDO_CLASS);
2109
2110       while (scanner->token == ':')
2111         {
2112           GTokenType token;
2113
2114           if ((token = parse_pseudo_class (css_provider, scanner, path)) != G_TOKEN_NONE)
2115             return token;
2116
2117           g_scanner_get_next_token (scanner);
2118         }
2119
2120       gtk_css_scanner_pop_scope (scanner);
2121     }
2122
2123   return G_TOKEN_NONE;
2124 }
2125
2126 static void
2127 resolve_binding_sets (const gchar *value_str,
2128                       GValue      *value)
2129 {
2130   GPtrArray *array;
2131   gchar **bindings, **str;
2132
2133   bindings = g_strsplit (value_str, ",", -1);
2134   array = g_ptr_array_new ();
2135
2136   for (str = bindings; *str; str++)
2137     {
2138       GtkBindingSet *binding_set;
2139
2140       binding_set = gtk_binding_set_find (g_strstrip (*str));
2141
2142       if (!binding_set)
2143         continue;
2144
2145       g_ptr_array_add (array, binding_set);
2146     }
2147
2148   g_value_take_boxed (value, array);
2149   g_strfreev (bindings);
2150 }
2151
2152 static GTokenType
2153 parse_rule (GtkCssProvider  *css_provider,
2154             GScanner        *scanner)
2155 {
2156   GtkCssScannerPrivate *priv;
2157   GTokenType expected_token;
2158   SelectorPath *selector;
2159
2160   priv = scanner->user_data;
2161
2162   gtk_css_scanner_push_scope (scanner, SCOPE_SELECTOR);
2163
2164   /* Handle directives */
2165   if (scanner->token == G_TOKEN_IDENTIFIER &&
2166       scanner->value.v_identifier[0] == '@')
2167     {
2168       gchar *directive;
2169
2170       directive = &scanner->value.v_identifier[1];
2171
2172       if (strcmp (directive, "define-color") == 0)
2173         {
2174           GtkSymbolicColor *color;
2175           gchar *color_name, *color_str;
2176           GError *error = NULL;
2177
2178           /* Directive is a color mapping */
2179           g_scanner_get_next_token (scanner);
2180
2181           if (scanner->token != G_TOKEN_IDENTIFIER)
2182             {
2183               gtk_css_provider_invalid_token (css_provider, scanner, "Color name");
2184               return G_TOKEN_IDENTIFIER;
2185             }
2186
2187           color_name = g_strdup (scanner->value.v_identifier);
2188           gtk_css_scanner_push_scope (scanner, SCOPE_VALUE);
2189           g_scanner_get_next_token (scanner);
2190
2191           if (scanner->token != G_TOKEN_IDENTIFIER)
2192             {
2193               gtk_css_provider_invalid_token (css_provider, scanner, "Color definition");
2194               return G_TOKEN_IDENTIFIER;
2195             }
2196
2197           color_str = g_strstrip (scanner->value.v_identifier);
2198           color = _gtk_css_parse_symbolic_color (color_str, &error);
2199           if (!color)
2200             {
2201               gtk_css_provider_take_error (css_provider, scanner, error);
2202               return G_TOKEN_IDENTIFIER;
2203             }
2204
2205           g_hash_table_insert (css_provider->priv->symbolic_colors, color_name, color);
2206
2207           gtk_css_scanner_pop_scope (scanner);
2208           g_scanner_get_next_token (scanner);
2209
2210           if (scanner->token != ';')
2211             return ';';
2212
2213           return G_TOKEN_NONE;
2214         }
2215       else if (strcmp (directive, "import") == 0)
2216         {
2217           GScanner *new_scanner;
2218           gboolean loaded;
2219           gchar *path = NULL;
2220           GFile *base, *actual;
2221           char *dirname;
2222           GError *error = NULL;
2223
2224           gtk_css_scanner_push_scope (scanner, SCOPE_VALUE);
2225           g_scanner_get_next_token (scanner);
2226
2227           if (scanner->token == G_TOKEN_IDENTIFIER &&
2228               g_str_has_prefix (scanner->value.v_identifier, "url"))
2229             path = g_strstrip (scanner->value.v_identifier);
2230           else if (scanner->token == G_TOKEN_STRING)
2231             path = g_strstrip (scanner->value.v_string);
2232           else
2233             {
2234               gtk_css_provider_invalid_token (css_provider, scanner, "File URL");
2235               return G_TOKEN_IDENTIFIER;
2236             }
2237
2238           if (scanner->input_name)
2239             dirname = g_path_get_dirname (scanner->input_name);
2240           else
2241             dirname = g_get_current_dir ();
2242
2243           base = g_file_new_for_path (dirname);
2244           g_free (dirname);
2245
2246           actual = _gtk_css_parse_url (base, path, NULL, &error);
2247           g_object_unref (base);
2248
2249           if (actual == NULL)
2250             {
2251               gtk_css_provider_take_error (css_provider, scanner, error);
2252               return G_TOKEN_IDENTIFIER;
2253             }
2254
2255           gtk_css_scanner_pop_scope (scanner);
2256           g_scanner_get_next_token (scanner);
2257
2258           if (scanner->token != ';')
2259             {
2260               g_object_unref (actual);
2261               return ';';
2262             }
2263
2264           path = g_file_get_path (actual);
2265           g_object_unref (actual);
2266
2267           new_scanner = gtk_css_provider_create_scanner (css_provider);
2268           css_provider->priv->scanner = new_scanner;
2269
2270           /* FIXME: Avoid recursive importing */
2271           loaded = gtk_css_provider_load_from_path_internal (css_provider, path,
2272                                                              FALSE, NULL);
2273
2274           /* Restore previous state */
2275           css_provider_reset_parser (css_provider);
2276           gtk_css_scanner_destroy (new_scanner);
2277           css_provider->priv->scanner = scanner;
2278
2279           g_free (path);
2280
2281           if (!loaded)
2282             return G_TOKEN_IDENTIFIER;
2283           else
2284             return G_TOKEN_NONE;
2285         }
2286       else if (strcmp (directive, "binding-set") == 0)
2287         {
2288           GtkBindingSet *binding_set;
2289           gchar *binding_set_name;
2290
2291           g_scanner_get_next_token (scanner);
2292
2293           if (scanner->token != G_TOKEN_IDENTIFIER)
2294             {
2295               gtk_css_provider_invalid_token (css_provider, scanner, "Binding name");
2296               return G_TOKEN_IDENTIFIER;
2297             }
2298
2299           binding_set_name = scanner->value.v_identifier;
2300           binding_set = gtk_binding_set_find (binding_set_name);
2301
2302           if (!binding_set)
2303             {
2304               binding_set = gtk_binding_set_new (binding_set_name);
2305               binding_set->parsed = TRUE;
2306             }
2307
2308           g_scanner_get_next_token (scanner);
2309
2310           if (scanner->token != G_TOKEN_LEFT_CURLY)
2311             return G_TOKEN_LEFT_CURLY;
2312
2313           gtk_css_scanner_push_scope (scanner, SCOPE_BINDING_SET);
2314           g_scanner_get_next_token (scanner);
2315
2316           do
2317             {
2318               GTokenType ret;
2319
2320               if (scanner->token != G_TOKEN_IDENTIFIER)
2321                 {
2322                   gtk_css_provider_invalid_token (css_provider, scanner, "Binding definition");
2323                   return G_TOKEN_IDENTIFIER;
2324                 }
2325
2326               ret = gtk_binding_entry_add_signal_from_string (binding_set,
2327                                                               scanner->value.v_identifier);
2328               if (ret != G_TOKEN_NONE)
2329                 {
2330                   gtk_css_provider_invalid_token (css_provider, scanner, "Binding definition");
2331                   return ret;
2332                 }
2333
2334               g_scanner_get_next_token (scanner);
2335
2336               if (scanner->token != ';')
2337                 return ';';
2338
2339               g_scanner_get_next_token (scanner);
2340             }
2341           while (scanner->token != G_TOKEN_RIGHT_CURLY);
2342
2343           gtk_css_scanner_pop_scope (scanner);
2344           g_scanner_get_next_token (scanner);
2345
2346           return G_TOKEN_NONE;
2347         }
2348       else
2349         {
2350           gtk_css_provider_invalid_token (css_provider, scanner, "Directive");
2351           return G_TOKEN_IDENTIFIER;
2352         }
2353     }
2354
2355   expected_token = parse_selector (css_provider, scanner, &selector);
2356
2357   if (expected_token != G_TOKEN_NONE)
2358     {
2359       selector_path_unref (selector);
2360       gtk_css_provider_invalid_token (css_provider, scanner, "Selector");
2361       return expected_token;
2362     }
2363
2364   priv->cur_selectors = g_slist_prepend (priv->cur_selectors, selector);
2365
2366   while (scanner->token == ',')
2367     {
2368       g_scanner_get_next_token (scanner);
2369
2370       expected_token = parse_selector (css_provider, scanner, &selector);
2371
2372       if (expected_token != G_TOKEN_NONE)
2373         {
2374           selector_path_unref (selector);
2375           gtk_css_provider_invalid_token (css_provider, scanner, "Selector");
2376           return expected_token;
2377         }
2378
2379       priv->cur_selectors = g_slist_prepend (priv->cur_selectors, selector);
2380     }
2381
2382   gtk_css_scanner_pop_scope (scanner);
2383
2384   if (scanner->token != G_TOKEN_LEFT_CURLY)
2385     return G_TOKEN_LEFT_CURLY;
2386
2387   /* Declarations parsing */
2388   gtk_css_scanner_push_scope (scanner, SCOPE_DECLARATION);
2389
2390   g_scanner_get_next_token (scanner);
2391     
2392   while (scanner->token != G_TOKEN_RIGHT_CURLY &&
2393          !g_scanner_eof (scanner))
2394     {
2395       gchar *value_str = NULL;
2396       GtkStylePropertyParser parse_func = NULL;
2397       GParamSpec *pspec = NULL;;
2398       gchar *prop;
2399
2400       if (scanner->token == ';')
2401         {
2402           g_scanner_get_next_token (scanner);
2403           continue;
2404         }
2405
2406       if (scanner->token != G_TOKEN_IDENTIFIER)
2407         {
2408           gtk_css_provider_error_literal (css_provider,
2409                                           scanner,
2410                                           GTK_CSS_PROVIDER_ERROR,
2411                                           GTK_CSS_PROVIDER_ERROR_PROPERTY_NAME,
2412                                           "Expected a valid property name");
2413           goto find_end_of_declaration;
2414         }
2415
2416       prop = g_strdup (scanner->value.v_identifier);
2417
2418       if (!gtk_style_properties_lookup_property (prop, &parse_func, &pspec) &&
2419           prop[0] != '-')
2420         {
2421           gtk_css_provider_error (css_provider,
2422                                   scanner,
2423                                   GTK_CSS_PROVIDER_ERROR,
2424                                   GTK_CSS_PROVIDER_ERROR_PROPERTY_NAME,
2425                                   "'%s' is not a valid property name",
2426                                   prop);
2427           g_free (prop);
2428           goto find_end_of_declaration;
2429         }
2430
2431       g_scanner_get_next_token (scanner);
2432
2433       if (scanner->token != ':')
2434         {
2435           g_free (prop);
2436           gtk_css_provider_invalid_token (css_provider, scanner, "':'");
2437           goto find_end_of_declaration;
2438         }
2439
2440       gtk_css_scanner_push_scope (scanner, SCOPE_VALUE);
2441       g_scanner_get_next_token (scanner);
2442
2443       if (scanner->token != G_TOKEN_IDENTIFIER)
2444         {
2445           g_free (prop);
2446           /* the error value here is hacky. But strings should be used for
2447            * strings really, so a string is not a syntax error but a broken
2448            * value for everything that we support. */
2449           gtk_css_provider_error (css_provider,
2450                                   scanner,
2451                                   GTK_CSS_PROVIDER_ERROR,
2452                                   scanner->token == G_TOKEN_STRING ? GTK_CSS_PROVIDER_ERROR_PROPERTY_VALUE
2453                                                                    : GTK_CSS_PROVIDER_ERROR_SYNTAX,
2454                                   "Not a property value");
2455           gtk_css_scanner_pop_scope (scanner);
2456           goto find_end_of_declaration;
2457         }
2458
2459       value_str = scanner->value.v_identifier;
2460       g_strchomp (value_str);
2461
2462       gtk_css_scanner_pop_scope (scanner);
2463       g_scanner_peek_next_token (scanner);
2464
2465       if (scanner->next_token != ';' &&
2466           scanner->next_token != G_TOKEN_RIGHT_CURLY &&
2467           scanner->next_token != G_TOKEN_EOF)
2468         {
2469           gtk_css_provider_invalid_token (css_provider, scanner, "';'");
2470           g_free (prop);
2471           goto find_end_of_declaration;
2472         }
2473
2474       if (pspec)
2475         {
2476           GValue *val;
2477
2478           val = g_slice_new0 (GValue);
2479           g_value_init (val, pspec->value_type);
2480
2481           if (strcmp (value_str, "none") == 0)
2482             {
2483               /* Insert the default value, so it has an opportunity
2484                * to override other style providers when merged
2485                */
2486               g_param_value_set_default (pspec, val);
2487               g_hash_table_insert (priv->cur_properties, prop, val);
2488             }
2489           else if (strcmp (prop, "gtk-key-bindings") == 0)
2490             {
2491               /* Private property holding the binding sets */
2492               resolve_binding_sets (value_str, val);
2493               g_hash_table_insert (priv->cur_properties, prop, val);
2494             }
2495           else if (pspec->value_type == G_TYPE_STRING)
2496             {
2497               g_value_set_string (val, value_str);
2498               g_hash_table_insert (priv->cur_properties, prop, val);
2499             }
2500           else if (parse_func)
2501             {
2502               GError *error = NULL;
2503               
2504               if ((*parse_func) (value_str, val, &error))
2505                 g_hash_table_insert (priv->cur_properties, prop, val);
2506               else
2507                 gtk_css_provider_take_error (css_provider, scanner, error);
2508             }
2509           else
2510             {
2511               GError *error = NULL;
2512               GFile *base;
2513               char *dirname;
2514               gboolean success;
2515
2516               if (scanner->input_name)
2517                 dirname = g_path_get_dirname (scanner->input_name);
2518               else
2519                 dirname = g_get_current_dir ();
2520
2521               base = g_file_new_for_path (dirname);
2522               g_free (dirname);
2523
2524               success = _gtk_css_value_from_string (val,
2525                                                     base,
2526                                                     value_str,
2527                                                     &error);
2528
2529               g_object_unref (base);
2530
2531               if (success)
2532                 {
2533                   g_hash_table_insert (priv->cur_properties, prop, val);
2534                 }
2535               else
2536                 {
2537                   g_value_unset (val);
2538                   g_slice_free (GValue, val);
2539                   g_free (prop);
2540
2541                   gtk_css_provider_take_error (css_provider, scanner, error);
2542                 }
2543             }
2544         }
2545       else if (prop[0] == '-')
2546         {
2547           GValue *val;
2548
2549           val = g_slice_new0 (GValue);
2550           g_value_init (val, G_TYPE_STRING);
2551           g_value_set_string (val, value_str);
2552
2553           g_hash_table_insert (priv->cur_properties, prop, val);
2554         }
2555       else
2556         g_free (prop);
2557
2558       g_scanner_get_next_token (scanner);
2559
2560       if (g_scanner_eof (scanner))
2561         {
2562           gtk_css_provider_invalid_token (css_provider, scanner, "}");
2563           break;
2564         }
2565
2566 find_end_of_declaration:
2567       while (scanner->token != ';' &&
2568              scanner->token != G_TOKEN_RIGHT_CURLY &&
2569              !g_scanner_eof (scanner))
2570         g_scanner_get_next_token (scanner);
2571     }
2572
2573   gtk_css_scanner_pop_scope (scanner);
2574
2575   return G_TOKEN_NONE;
2576 }
2577
2578 static void
2579 gtk_css_provider_reset (GtkCssProvider *css_provider)
2580 {
2581   GtkCssProviderPrivate *priv;
2582
2583   priv = css_provider->priv;
2584
2585   if (priv->selectors_info->len > 0)
2586     g_ptr_array_remove_range (priv->selectors_info, 0, priv->selectors_info->len);
2587 }
2588
2589
2590 static gboolean
2591 parse_stylesheet (GtkCssProvider  *css_provider,
2592                   GScanner        *scanner,
2593                   GError         **error)
2594 {
2595   GtkCssProviderPrivate *priv;
2596   gboolean result;
2597
2598   result = TRUE;
2599
2600   priv = css_provider->priv;
2601   g_scanner_get_next_token (scanner);
2602
2603   while (!g_scanner_eof (scanner))
2604     {
2605       GTokenType expected_token;
2606
2607       css_provider_reset_parser (css_provider);
2608       expected_token = parse_rule (css_provider, scanner);
2609
2610       if (expected_token != G_TOKEN_NONE)
2611         {
2612           /* If a GError was passed in, propagate the error and bail out,
2613            * else report a warning and keep going
2614            */
2615           if (error != NULL)
2616             {
2617               result = FALSE;
2618               if (priv->error)
2619                 g_propagate_error (error, priv->error);
2620               else
2621                 g_set_error_literal (error,
2622                                      GTK_CSS_PROVIDER_ERROR,
2623                                      GTK_CSS_PROVIDER_ERROR_FAILED,
2624                                      "Error parsing stylesheet");
2625               break;
2626             }
2627           else
2628             {
2629               g_clear_error (&priv->error);
2630               priv->error = NULL;
2631             }
2632
2633           css_provider_reset_parser (css_provider);
2634
2635           while (!g_scanner_eof (scanner) &&
2636                  scanner->token != G_TOKEN_RIGHT_CURLY)
2637             g_scanner_get_next_token (scanner);
2638         }
2639       else
2640         css_provider_commit (css_provider, scanner);
2641
2642       g_scanner_get_next_token (scanner);
2643     }
2644
2645   return result;
2646 }
2647
2648 /**
2649  * gtk_css_provider_load_from_data:
2650  * @css_provider: a #GtkCssProvider
2651  * @data: CSS data loaded in memory
2652  * @length: the length of @data in bytes, or -1 for NUL terminated strings
2653  * @error: (out) (allow-none): return location for a #GError, or %NULL
2654  *
2655  * Loads @data into @css_provider, making it clear any previously loaded
2656  * information.
2657  *
2658  * Returns: %TRUE if the data could be loaded.
2659  **/
2660 gboolean
2661 gtk_css_provider_load_from_data (GtkCssProvider  *css_provider,
2662                                  const gchar     *data,
2663                                  gssize           length,
2664                                  GError         **error)
2665 {
2666   GtkCssProviderPrivate *priv;
2667
2668   g_return_val_if_fail (GTK_IS_CSS_PROVIDER (css_provider), FALSE);
2669   g_return_val_if_fail (data != NULL, FALSE);
2670
2671   priv = css_provider->priv;
2672
2673   if (length < 0)
2674     length = strlen (data);
2675
2676   gtk_css_provider_reset (css_provider);
2677
2678   priv->scanner->input_name = NULL;
2679   g_scanner_input_text (priv->scanner, data, (guint) length);
2680
2681   return parse_stylesheet (css_provider, priv->scanner, error);
2682 }
2683
2684 /**
2685  * gtk_css_provider_load_from_file:
2686  * @css_provider: a #GtkCssProvider
2687  * @file: #GFile pointing to a file to load
2688  * @error: (out) (allow-none): return location for a #GError, or %NULL
2689  *
2690  * Loads the data contained in @file into @css_provider, making it
2691  * clear any previously loaded information.
2692  *
2693  * Returns: %TRUE if the data could be loaded.
2694  **/
2695 gboolean
2696 gtk_css_provider_load_from_file (GtkCssProvider  *css_provider,
2697                                  GFile           *file,
2698                                  GError         **error)
2699 {
2700   GtkCssProviderPrivate *priv;
2701   GError *internal_error = NULL;
2702   char *path;
2703   gchar *data;
2704   gsize length;
2705   gboolean ret;
2706
2707   g_return_val_if_fail (GTK_IS_CSS_PROVIDER (css_provider), FALSE);
2708   g_return_val_if_fail (G_IS_FILE (file), FALSE);
2709
2710   priv = css_provider->priv;
2711
2712   if (!g_file_load_contents (file, NULL,
2713                              &data, &length,
2714                              NULL, &internal_error))
2715     {
2716       g_propagate_error (error, internal_error);
2717       return FALSE;
2718     }
2719
2720   gtk_css_provider_reset (css_provider);
2721
2722   path = g_file_get_path (file);
2723   priv->scanner->input_name = path;
2724   g_scanner_input_text (priv->scanner, data, (guint) length);
2725
2726   ret = parse_stylesheet (css_provider, priv->scanner, error);
2727
2728   g_free (path);
2729   priv->scanner->input_name = NULL;
2730   g_free (data);
2731
2732   return ret;
2733 }
2734
2735 static gboolean
2736 gtk_css_provider_load_from_path_internal (GtkCssProvider  *css_provider,
2737                                           const gchar     *path,
2738                                           gboolean         reset,
2739                                           GError         **error)
2740 {
2741   GtkCssProviderPrivate *priv;
2742   GError *internal_error = NULL;
2743   GMappedFile *mapped_file;
2744   const gchar *data;
2745   gsize length;
2746   gboolean ret;
2747
2748   priv = css_provider->priv;
2749
2750   mapped_file = g_mapped_file_new (path, FALSE, &internal_error);
2751
2752   if (internal_error)
2753     {
2754       g_propagate_error (error, internal_error);
2755       return FALSE;
2756     }
2757
2758   length = g_mapped_file_get_length (mapped_file);
2759   data = g_mapped_file_get_contents (mapped_file);
2760
2761   if (!data)
2762     data = "";
2763
2764   if (reset)
2765     gtk_css_provider_reset (css_provider);
2766
2767   priv->scanner->input_name = path;
2768   g_scanner_input_text (priv->scanner, data, (guint) length);
2769
2770   ret = parse_stylesheet (css_provider, priv->scanner, error);
2771
2772   priv->scanner->input_name = NULL;
2773
2774   g_mapped_file_unref (mapped_file);
2775
2776   return ret;
2777 }
2778
2779 /**
2780  * gtk_css_provider_load_from_path:
2781  * @css_provider: a #GtkCssProvider
2782  * @path: the path of a filename to load, in the GLib filename encoding
2783  * @error: (out) (allow-none): return location for a #GError, or %NULL
2784  *
2785  * Loads the data contained in @path into @css_provider, making it clear
2786  * any previously loaded information.
2787  *
2788  * Returns: %TRUE if the data could be loaded.
2789  **/
2790 gboolean
2791 gtk_css_provider_load_from_path (GtkCssProvider  *css_provider,
2792                                  const gchar     *path,
2793                                  GError         **error)
2794 {
2795   g_return_val_if_fail (GTK_IS_CSS_PROVIDER (css_provider), FALSE);
2796   g_return_val_if_fail (path != NULL, FALSE);
2797
2798   return gtk_css_provider_load_from_path_internal (css_provider, path,
2799                                                    TRUE, error);
2800 }
2801
2802 /**
2803  * gtk_css_provider_get_default:
2804  *
2805  * Returns the provider containing the style settings used as a
2806  * fallback for all widgets.
2807  *
2808  * Returns: (transfer none): The provider used for fallback styling.
2809  *          This memory is owned by GTK+, and you must not free it.
2810  **/
2811 GtkCssProvider *
2812 gtk_css_provider_get_default (void)
2813 {
2814   static GtkCssProvider *provider;
2815
2816   if (G_UNLIKELY (!provider))
2817     {
2818       const gchar *str =
2819         "@define-color fg_color #000; \n"
2820         "@define-color bg_color #dcdad5; \n"
2821         "@define-color text_color #000; \n"
2822         "@define-color base_color #fff; \n"
2823         "@define-color selected_bg_color #4b6983; \n"
2824         "@define-color selected_fg_color #fff; \n"
2825         "@define-color tooltip_bg_color #eee1b3; \n"
2826         "@define-color tooltip_fg_color #000; \n"
2827         "@define-color placeholder_text_color #808080; \n"
2828         "\n"
2829         "@define-color info_fg_color rgb (181, 171, 156);\n"
2830         "@define-color info_bg_color rgb (252, 252, 189);\n"
2831         "@define-color warning_fg_color rgb (173, 120, 41);\n"
2832         "@define-color warning_bg_color rgb (250, 173, 61);\n"
2833         "@define-color question_fg_color rgb (97, 122, 214);\n"
2834         "@define-color question_bg_color rgb (138, 173, 212);\n"
2835         "@define-color error_fg_color rgb (166, 38, 38);\n"
2836         "@define-color error_bg_color rgb (237, 54, 54);\n"
2837         "\n"
2838         "* {\n"
2839         "  background-color: @bg_color;\n"
2840         "  color: @fg_color;\n"
2841         "  border-color: shade (@bg_color, 0.6);\n"
2842         "  padding: 2;\n"
2843         "  border-width: 0;\n"
2844         "}\n"
2845         "\n"
2846         "*:prelight {\n"
2847         "  background-color: shade (@bg_color, 1.05);\n"
2848         "  color: shade (@fg_color, 1.3);\n"
2849         "}\n"
2850         "\n"
2851         "*:selected {\n"
2852         "  background-color: @selected_bg_color;\n"
2853         "  color: @selected_fg_color;\n"
2854         "}\n"
2855         "\n"
2856         ".expander, GtkTreeView.view.expander {\n"
2857         "  color: #fff;\n"
2858         "}\n"
2859         "\n"
2860         ".expander:prelight,\n"
2861         "GtkTreeView.view.expander:selected:prelight {\n"
2862         "  color: @text_color;\n"
2863         "}\n"
2864         "\n"
2865         ".expander:active {\n"
2866         "  transition: 200ms linear;\n"
2867         "}\n"
2868         "\n"
2869         "*:insensitive {\n"
2870         "  border-color: shade (@bg_color, 0.7);\n"
2871         "  background-color: shade (@bg_color, 0.9);\n"
2872         "  color: shade (@bg_color, 0.7);\n"
2873         "}\n"
2874         "\n"
2875         ".view {\n"
2876         "  border-width: 0;\n"
2877         "  border-radius: 0;\n"
2878         "  background-color: @base_color;\n"
2879         "  color: @text_color;\n"
2880         "}\n"
2881         ".view:selected {\n"
2882         "  background-color: shade (@bg_color, 0.9);\n"
2883         "  color: @fg_color;\n"
2884         "}\n"
2885         "\n"
2886         ".view:selected:focused {\n"
2887         "  background-color: @selected_bg_color;\n"
2888         "  color: @selected_fg_color;\n"
2889         "}\n"
2890         "\n"
2891         ".view column:sorted row,\n"
2892         ".view column:sorted row:prelight {\n"
2893         "  background-color: shade (@bg_color, 0.85);\n"
2894         "}\n"
2895         "\n"
2896         ".view column:sorted row:nth-child(odd),\n"
2897         ".view column:sorted row:nth-child(odd):prelight {\n"
2898         "  background-color: shade (@bg_color, 0.8);\n"
2899         "}\n"
2900         "\n"
2901         ".view row,\n"
2902         ".view row:prelight {\n"
2903         "  background-color: @base_color;\n"
2904         "  color: @text_color;\n"
2905         "}\n"
2906         "\n"
2907         ".view row:nth-child(odd),\n"
2908         ".view row:nth-child(odd):prelight {\n"
2909         "  background-color: shade (@base_color, 0.93); \n"
2910         "}\n"
2911         "\n"
2912         ".view row:selected:focused {\n"
2913         "  background-color: @selected_bg_color;\n"
2914         "}\n"
2915         "\n"
2916         ".view row:selected {\n"
2917         "  background-color: darker (@bg_color);\n"
2918         "  color: @selected_fg_color;\n"
2919         "}\n"
2920         "\n"
2921         ".view.cell.trough,\n"
2922         ".view.cell.trough:hover,\n"
2923         ".view.cell.trough:selected,\n"
2924         ".view.cell.trough:selected:focused {\n"
2925         "  background-color: @bg_color;\n"
2926         "  color: @fg_color;\n"
2927         "}\n"
2928         "\n"
2929         ".view.cell.progressbar,\n"
2930         ".view.cell.progressbar:hover,\n"
2931         ".view.cell.progressbar:selected,\n"
2932         ".view.cell.progressbar:selected:focused {\n"
2933         "  background-color: @selected_bg_color;\n"
2934         "  color: @selected_fg_color;\n"
2935         "}\n"
2936         "\n"
2937         ".rubberband {\n"
2938         "  background-color: alpha (@fg_color, 0.25);\n"
2939         "  border-color: @fg_color;\n"
2940         "  border-style: solid;\n"
2941         "  border-width: 1;\n"
2942         "}\n"
2943         "\n"
2944         ".tooltip {\n"
2945         "  background-color: @tooltip_bg_color; \n"
2946         "  color: @tooltip_fg_color; \n"
2947         "  border-color: @tooltip_fg_color; \n"
2948         "  border-width: 1;\n"
2949         "  border-style: solid;\n"
2950         "}\n"
2951         "\n"
2952         ".button,\n"
2953         ".slider {\n"
2954         "  border-style: outset; \n"
2955         "  border-width: 2; \n"
2956         "}\n"
2957         "\n"
2958         ".button:active {\n"
2959         "  background-color: shade (@bg_color, 0.7);\n"
2960         "  border-style: inset; \n"
2961         "}\n"
2962         "\n"
2963         ".button:prelight,\n"
2964         ".slider:prelight {\n"
2965         "  background-color: @selected_bg_color;\n"
2966         "  color: @selected_fg_color;\n"
2967         "  border-color: shade (@selected_bg_color, 0.7);\n"
2968         "}\n"
2969         "\n"
2970         ".trough {\n"
2971         "  background-color: darker (@bg_color);\n"
2972         "  border-style: inset;\n"
2973         "  border-width: 1;\n"
2974         "  padding: 0;\n"
2975         "}\n"
2976         "\n"
2977         ".entry {\n"
2978         "  border-style: inset;\n"
2979         "  border-width: 2;\n"
2980         "  background-color: @base_color;\n"
2981         "  color: @text_color;\n"
2982         "}\n"
2983         "\n"
2984         ".entry:insensitive {\n"
2985         "  background-color: shade (@base_color, 0.9);\n"
2986         "  color: shade (@base_color, 0.7);\n"
2987         "}\n"
2988         ".entry:active {\n"
2989         "  background-color: #c4c2bd;\n"
2990         "  color: #000;\n"
2991         "}\n"
2992         "\n"
2993         ".progressbar,\n"
2994         ".entry.progressbar, \n"
2995         ".cell.progressbar {\n"
2996         "  background-color: @selected_bg_color;\n"
2997         "  border-color: shade (@selected_bg_color, 0.7);\n"
2998         "  color: @selected_fg_color;\n"
2999         "  border-style: outset;\n"
3000         "  border-width: 1;\n"
3001         "}\n"
3002         "\n"
3003         "GtkCheckButton:hover,\n"
3004         "GtkCheckButton:selected,\n"
3005         "GtkRadioButton:hover,\n"
3006         "GtkRadioButton:selected {\n"
3007         "  background-color: shade (@bg_color, 1.05);\n"
3008         "}\n"
3009         "\n"
3010         ".check, .radio,"
3011         ".cell.check, .cell.radio,\n"
3012         ".cell.check:hover, .cell.radio:hover {\n"
3013         "  border-style: solid;\n"
3014         "  border-width: 1;\n"
3015         "  background-color: @base_color;\n"
3016         "  border-color: @fg_color;\n"
3017         "}\n"
3018         "\n"
3019         ".check:active, .radio:active,\n"
3020         ".check:hover, .radio:hover {\n"
3021         "  background-color: @base_color;\n"
3022         "  border-color: @fg_color;\n"
3023         "  color: @text_color;\n"
3024         "}\n"
3025         "\n"
3026         ".check:selected, .radio:selected {\n"
3027         "  background-color: darker (@bg_color);\n"
3028         "  color: @selected_fg_color;\n"
3029         "  border-color: @selected_fg_color;\n"
3030         "}\n"
3031         "\n"
3032         ".check:selected:focused, .radio:selected:focused {\n"
3033         "  background-color: @selected_bg_color;\n"
3034         "}\n"
3035         "\n"
3036         ".menu.check, .menu.radio {\n"
3037         "  color: @fg_color;\n"
3038         "  border-style: none;\n"
3039         "  border-width: 0;\n"
3040         "}\n"
3041         "\n"
3042         ".popup {\n"
3043         "  border-style: outset;\n"
3044         "  border-width: 1;\n"
3045         "}\n"
3046         "\n"
3047         ".viewport {\n"
3048         "  border-style: inset;\n"
3049         "  border-width: 2;\n"
3050         "}\n"
3051         "\n"
3052         ".notebook {\n"
3053         "  border-style: outset;\n"
3054         "  border-width: 1;\n"
3055         "}\n"
3056         "\n"
3057         ".frame {\n"
3058         "  border-style: inset;\n"
3059         "  border-width: 1;\n"
3060         "}\n"
3061         "\n"
3062         "GtkScrolledWindow.frame {\n"
3063         "  padding: 0;\n"
3064         "}\n"
3065         "\n"
3066         ".menu,\n"
3067         ".menubar,\n"
3068         ".toolbar {\n"
3069         "  border-style: outset;\n"
3070         "  border-width: 1;\n"
3071         "}\n"
3072         "\n"
3073         ".menu:hover,\n"
3074         ".menubar:hover,\n"
3075         ".menu.check:hover,\n"
3076         ".menu.radio:hover {\n"
3077         "  background-color: @selected_bg_color;\n"
3078         "  color: @selected_fg_color;\n"
3079         "}\n"
3080         "\n"
3081         "GtkSpinButton.button {\n"
3082         "  border-width: 1;\n"
3083         "}\n"
3084         "\n"
3085         ".scale.slider:hover,\n"
3086         "GtkSpinButton.button:hover {\n"
3087         "  background-color: shade (@bg_color, 1.05);\n"
3088         "  border-color: shade (@bg_color, 0.8);\n"
3089         "}\n"
3090         "\n"
3091         "GtkSwitch.trough:active {\n"
3092         "  background-color: @selected_bg_color;\n"
3093         "  color: @selected_fg_color;\n"
3094         "}\n"
3095         "\n"
3096         "GtkToggleButton.button:inconsistent {\n"
3097         "  border-style: outset;\n"
3098         "  border-width: 1px;\n"
3099         "  background-color: shade (@bg_color, 0.9);\n"
3100         "  border-color: shade (@bg_color, 0.7);\n"
3101         "}\n"
3102         "\n"
3103         "GtkLabel:selected {\n"
3104         "  background-color: shade (@bg_color, 0.9);\n"
3105         "}\n"
3106         "\n"
3107         "GtkLabel:selected:focused {\n"
3108         "  background-color: @selected_bg_color;\n"
3109         "}\n"
3110         "\n"
3111         ".spinner:active {\n"
3112         "  transition: 750ms linear loop;\n"
3113         "}\n"
3114         "\n"
3115         ".info {\n"
3116         "  background-color: @info_bg_color;\n"
3117         "  color: @info_fg_color;\n"
3118         "}\n"
3119         "\n"
3120         ".warning {\n"
3121         "  background-color: @warning_bg_color;\n"
3122         "  color: @warning_fg_color;\n"
3123         "}\n"
3124         "\n"
3125         ".question {\n"
3126         "  background-color: @question_bg_color;\n"
3127         "  color: @question_fg_color;\n"
3128         "}\n"
3129         "\n"
3130         ".error {\n"
3131         "  background-color: @error_bg_color;\n"
3132         "  color: @error_fg_color;\n"
3133         "}\n"
3134         "\n"
3135         ".highlight {\n"
3136         "  background-color: @selected_bg_color;\n"
3137         "  color: @selected_fg_color;\n"
3138         "}\n"
3139         "\n"
3140         ".light-area-focus {\n"
3141         "  color: #000;\n"
3142         "}\n"
3143         "\n"
3144         ".dark-area-focus {\n"
3145         "  color: #fff;\n"
3146         "}\n"
3147         "GtkCalendar.view {\n"
3148         "  border-width: 1;\n"
3149         "  border-style: inset;\n"
3150         "  padding: 1;\n"
3151         "}\n"
3152         "\n"
3153         "GtkCalendar.view:inconsistent {\n"
3154         "  color: darker (@bg_color);\n"
3155         "}\n"
3156         "\n"
3157         "GtkCalendar.header {\n"
3158         "  background-color: @bg_color;\n"
3159         "  border-style: outset;\n"
3160         "  border-width: 2;\n"
3161         "}\n"
3162         "\n"
3163         "GtkCalendar.highlight {\n"
3164         "  border-width: 0;\n"
3165         "}\n"
3166         "\n"
3167         "GtkCalendar.button {\n"
3168         "  background-color: @bg_color;\n"
3169         "}\n"
3170         "\n"
3171         "GtkCalendar.button:hover {\n"
3172         "  background-color: lighter (@bg_color);\n"
3173         "  color: @fg_color;\n"
3174         "}\n"
3175         "\n"
3176         ".menu * {\n"
3177         "  border-width: 0;\n"
3178         "  padding: 2;\n"
3179         "}\n"
3180         "\n";
3181
3182       provider = gtk_css_provider_new ();
3183       if (!gtk_css_provider_load_from_data (provider, str, -1, NULL))
3184         {
3185           g_error ("Failed to load the internal default CSS.");
3186         }
3187     }
3188
3189   return provider;
3190 }
3191
3192 gchar *
3193 _gtk_css_provider_get_theme_dir (void)
3194 {
3195   const gchar *var;
3196   gchar *path;
3197
3198   var = g_getenv ("GTK_DATA_PREFIX");
3199
3200   if (var)
3201     path = g_build_filename (var, "share", "themes", NULL);
3202   else
3203     path = g_build_filename (GTK_DATA_PREFIX, "share", "themes", NULL);
3204
3205   return path;
3206 }
3207
3208 /**
3209  * gtk_css_provider_get_named:
3210  * @name: A theme name
3211  * @variant: (allow-none): variant to load, for example, "dark", or
3212  *     %NULL for the default
3213  *
3214  * Loads a theme from the usual theme paths
3215  *
3216  * Returns: (transfer none): a #GtkCssProvider with the theme loaded.
3217  *     This memory is owned by GTK+, and you must not free it.
3218  */
3219 GtkCssProvider *
3220 gtk_css_provider_get_named (const gchar *name,
3221                             const gchar *variant)
3222 {
3223   static GHashTable *themes = NULL;
3224   GtkCssProvider *provider;
3225   gchar *key;
3226
3227   if (G_UNLIKELY (!themes))
3228     themes = g_hash_table_new (g_str_hash, g_str_equal);
3229
3230   if (variant == NULL)
3231     key = (gchar *)name;
3232   else
3233     key = g_strconcat (name, "-", variant, NULL);
3234
3235   provider = g_hash_table_lookup (themes, key);
3236
3237   if (!provider)
3238     {
3239       const gchar *home_dir;
3240       gchar *subpath, *path = NULL;
3241
3242       if (variant)
3243         subpath = g_strdup_printf ("gtk-3.0" G_DIR_SEPARATOR_S "gtk-%s.css", variant);
3244       else
3245         subpath = g_strdup ("gtk-3.0" G_DIR_SEPARATOR_S "gtk.css");
3246
3247       /* First look in the users home directory
3248        */
3249       home_dir = g_get_home_dir ();
3250       if (home_dir)
3251         {
3252           path = g_build_filename (home_dir, ".themes", name, subpath, NULL);
3253
3254           if (!g_file_test (path, G_FILE_TEST_EXISTS))
3255             {
3256               g_free (path);
3257               path = NULL;
3258             }
3259         }
3260
3261       if (!path)
3262         {
3263           gchar *theme_dir;
3264
3265           theme_dir = _gtk_css_provider_get_theme_dir ();
3266           path = g_build_filename (theme_dir, name, subpath, NULL);
3267           g_free (theme_dir);
3268
3269           if (!g_file_test (path, G_FILE_TEST_EXISTS))
3270             {
3271               g_free (path);
3272               path = NULL;
3273             }
3274         }
3275
3276       g_free (subpath);
3277
3278       if (path)
3279         {
3280           GError *error;
3281
3282           provider = gtk_css_provider_new ();
3283           error = NULL;
3284           if (!gtk_css_provider_load_from_path (provider, path, &error))
3285             {
3286               g_warning ("Could not load named theme \"%s\": %s", name, error->message);
3287               g_error_free (error);
3288
3289               g_object_unref (provider);
3290               provider = NULL;
3291             }
3292           else
3293             g_hash_table_insert (themes, g_strdup (key), provider);
3294
3295           g_free (path);
3296         }
3297     }
3298
3299   if (key != name)
3300     g_free (key);
3301
3302   return provider;
3303 }
3304
3305 static void
3306 selector_path_print (const SelectorPath *path,
3307                      GString *           str)
3308 {
3309   GSList *walk, *reverse;
3310
3311   reverse = g_slist_copy (path->elements);
3312   reverse = g_slist_reverse (reverse);
3313
3314   for (walk = reverse; walk; walk = walk->next)
3315     {
3316       SelectorElement *elem = walk->data;
3317
3318       switch (elem->elem_type)
3319         {
3320         case SELECTOR_TYPE_NAME:
3321         case SELECTOR_NAME:
3322           g_string_append (str, g_quark_to_string (elem->name));
3323           break;
3324         case SELECTOR_GTYPE:
3325           g_string_append (str, g_type_name (elem->type));
3326           break;
3327         case SELECTOR_REGION:
3328           g_string_append (str, g_quark_to_string (elem->region.name));
3329           if (elem->region.flags)
3330             {
3331               char * flag_names[] = {
3332                 "nth-child(even)",
3333                 "nth-child(odd)",
3334                 "first-child",
3335                 "last-child",
3336                 "sorted"
3337               };
3338               guint i;
3339
3340               for (i = 0; i < G_N_ELEMENTS (flag_names); i++)
3341                 {
3342                   if (elem->region.flags & (1 << i))
3343                     {
3344                       g_string_append_c (str, ':');
3345                       g_string_append (str, flag_names[i]);
3346                     }
3347                 }
3348             }
3349           break;
3350         case SELECTOR_CLASS:
3351           g_string_append_c (str, '.');
3352           g_string_append (str, g_quark_to_string (elem->name));
3353           break;
3354         case SELECTOR_GLOB:
3355           if (walk->next == NULL ||
3356               elem->combinator != COMBINATOR_CHILD ||
3357               ((SelectorElement *) walk->next->data)->elem_type != SELECTOR_CLASS)
3358             g_string_append (str, "*");
3359           break;
3360         default:
3361           g_assert_not_reached ();
3362         }
3363
3364       if (walk->next)
3365         {
3366           switch (elem->combinator)
3367             {
3368             case COMBINATOR_DESCENDANT:
3369               if (elem->elem_type != SELECTOR_CLASS ||
3370                   ((SelectorElement *) walk->next->data)->elem_type != SELECTOR_CLASS)
3371                 g_string_append_c (str, ' ');
3372               break;
3373             case COMBINATOR_CHILD:
3374               if (((SelectorElement *) walk->next->data)->elem_type != SELECTOR_CLASS)
3375                 g_string_append (str, " > ");
3376               break;
3377             default:
3378               g_assert_not_reached ();
3379             }
3380         }
3381         
3382     }
3383
3384   if (path->state)
3385     {
3386       char * state_names[] = {
3387         "active",
3388         "hover",
3389         "selected",
3390         "insensitive",
3391         "inconsistent",
3392         "focus"
3393       };
3394       guint i;
3395
3396       for (i = 0; i < G_N_ELEMENTS (state_names); i++)
3397         {
3398           if (path->state & (1 << i))
3399             {
3400               g_string_append_c (str, ':');
3401               g_string_append (str, state_names[i]);
3402             }
3403         }
3404     }
3405
3406   g_slist_free (reverse);
3407 }
3408
3409 static void
3410 selector_style_info_print (const SelectorStyleInfo *info,
3411                            GString                 *str)
3412 {
3413   GList *keys, *walk;
3414   char *s;
3415
3416   selector_path_print (info->path, str);
3417
3418   g_string_append (str, " {\n");
3419
3420   keys = g_hash_table_get_keys (info->style);
3421   /* so the output is identical for identical selector styles */
3422   keys = g_list_sort (keys, (GCompareFunc) strcmp);
3423
3424   for (walk = keys; walk; walk = walk->next)
3425     {
3426       const char *name = walk->data;
3427       const GValue *value = g_hash_table_lookup (info->style, (gpointer) name);
3428
3429       g_string_append (str, "  ");
3430       g_string_append (str, name);
3431       g_string_append (str, ": ");
3432       s = _gtk_css_value_to_string (value);
3433       g_string_append (str, s);
3434       g_free (s);
3435       g_string_append (str, ";\n");
3436     }
3437
3438   g_list_free (keys);
3439
3440   g_string_append (str, "}\n");
3441 }
3442
3443 static void
3444 gtk_css_provider_print_colors (GHashTable *colors,
3445                                GString    *str)
3446 {
3447   GList *keys, *walk;
3448   char *s;
3449
3450   keys = g_hash_table_get_keys (colors);
3451   /* so the output is identical for identical styles */
3452   keys = g_list_sort (keys, (GCompareFunc) strcmp);
3453
3454   for (walk = keys; walk; walk = walk->next)
3455     {
3456       const char *name = walk->data;
3457       GtkSymbolicColor *symbolic = g_hash_table_lookup (colors, (gpointer) name);
3458
3459       g_string_append (str, "@define-color ");
3460       g_string_append (str, name);
3461       g_string_append (str, " ");
3462       s = gtk_symbolic_color_to_string (symbolic);
3463       g_string_append (str, s);
3464       g_free (s);
3465       g_string_append (str, ";\n");
3466     }
3467
3468   g_list_free (keys);
3469 }
3470
3471 /**
3472  * gtk_css_provider_to_string:
3473  * @provider: the provider to write to a string
3474  *
3475  * Convertes the @provider into a string representation in CSS
3476  * format.
3477  * 
3478  * Using gtk_css_provider_load_from_data() with the return value
3479  * from this function on a new provider created with
3480  * gtk_css_provider_new() will basicallu create a duplicate of
3481  * this @provider.
3482  *
3483  * Returns: a new string representing the @provider.
3484  **/
3485 char *
3486 gtk_css_provider_to_string (GtkCssProvider *provider)
3487 {
3488   GtkCssProviderPrivate *priv;
3489   GString *str;
3490   guint i;
3491
3492   g_return_val_if_fail (GTK_IS_CSS_PROVIDER (provider), NULL);
3493
3494   priv = provider->priv;
3495
3496   str = g_string_new ("");
3497
3498   gtk_css_provider_print_colors (priv->symbolic_colors, str);
3499
3500   for (i = 0; i < priv->selectors_info->len; i++)
3501     {
3502       if (i > 0)
3503         g_string_append (str, "\n");
3504       selector_style_info_print (g_ptr_array_index (priv->selectors_info, i),
3505                                  str);
3506     }
3507
3508   return g_string_free (str, FALSE);
3509 }
3510