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