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