]> Pileus Git - ~andy/gtk/blob - gtk/gtkcssprovider.c
cssprovider: Fix names for first and last child pseudo class
[~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 "gtksymboliccolor.h"
33 #include "gtkstyleprovider.h"
34 #include "gtkstylecontextprivate.h"
35 #include "gtkstylepropertiesprivate.h"
36 #include "gtkstylepropertyprivate.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: Sans 20
145  * }
146  *
147  * /&ast; Theme a label named title-label &ast;/
148  * GtkLabel&num;title-label {
149  *     font: 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-shadows">
509  * <title>Text shadow</title>
510  * <para>
511  * A shadow list can be applied to text or symbolic icons, using the CSS3
512  * text-shadow syntax, as defined in
513  * <ulink url="http://www.w3.org/TR/css3-text/#text-shadow">the CSS3 specification</ulink>.
514  * </para>
515  * <para>
516  * A text shadow is specified using the syntax
517  * <literallayout>text-shadow: @horizontal_offset @vertical_offset [ @blur_radius ] @color</literallayout>
518  * The offset of the shadow is specified with the @horizontal_offset and @vertical_offset
519  * parameters. The optional blur radius is parsed, but it is currently not rendered by
520  * the GTK+ theming engine.
521  * </para>
522  * <para>
523  * To set multiple shadows on an element, you can specify a comma-separated list
524  * of shadow elements in the text-shadow property. Shadows are always rendered
525  * front-back, i.e. the first shadow specified is on top of the others. Shadows
526  * can thus overlay each other, but they can never overlay the text itself,
527  * which is always rendered on top of the shadow layer.
528  * </para>
529  * </refsect2>
530  * <refsect2>
531  * <title>Box shadow</title>
532  * <para>
533  * Themes can apply shadows on framed elements using the CSS3 box-shadow syntax,
534  * as defined in 
535  * <ulink url="http://www.w3.org/TR/css3-background/#the-box-shadow">the CSS3 specification</ulink>.
536  * </para>
537  * <para>
538  * A box shadow is specified using the syntax
539  * <literallayout>box-shadow: [ @inset ] @horizontal_offset @vertical_offset [ @blur_radius ] [ @spread ] @color</literallayout>
540  * A positive offset will draw a shadow that is offset to the right (down) of the box,
541  * a negative offset to the left (top). The optional spread parameter defines an additional
542  * distance to expand the shadow shape in all directions, by the specified radius.
543  * The optional blur radius parameter is parsed, but it is currently not rendered by
544  * the GTK+ theming engine.
545  * The inset parameter defines whether the drop shadow should be rendered inside or outside
546  * the box canvas. Only inset box-shadows are currently supported by the GTK+ theming engine,
547  * non-inset elements are currently ignored.
548  * </para>
549  * <para>
550  * To set multiple box-shadows on an element, you can specify a comma-separated list
551  * of shadow elements in the box-shadow property. Shadows are always rendered
552  * front-back, i.e. the first shadow specified is on top of the others, so they may
553  * overlap other boxes or other shadows.
554  * </para>
555  * </refsect2>
556  * <refsect2 id="gtkcssprovider-border-image">
557  * <title>Border images</title>
558  * <para>
559  * Images and gradients can also be used in slices for the purpose of creating
560  * scalable borders.
561  * For more information, see the CSS3 documentation for the border-image property,
562  * which can be found <ulink url="http://www.w3.org/TR/css3-background/#border-images">here</ulink>.
563  * </para>
564  * <inlinegraphic fileref="slices.png" format="PNG"/>
565  * <para>
566  * The parameters of the slicing process are controlled by
567  * four separate properties. Note that you can use the
568  * <literallayout>border-image</literallayout> shorthand property
569  * to set values for the three properties at the same time.
570  * </para>
571  * <para>
572  * <literallayout>border-image-source: url(@path)
573  * (or border-image-source: -gtk-gradient(...))</literallayout>:
574  * Specifies the source of the border image, and it can either
575  * be an URL or a gradient (see above).
576  * </para>
577  * <para>
578  * <literallayout>border-image-slice: @top @right @bottom @left</literallayout>
579  * The sizes specified by the @top, @right, @bottom and @left parameters
580  * are the offsets, in pixels, from the relevant edge where the image
581  * should be "cut off" to build the slices used for the rendering
582  * of the border.
583  * </para>
584  * <para>
585  * <literallayout>border-image-width: @top @right @bottom @left</literallayout>
586  * The sizes specified by the @top, @right, @bottom and @left parameters
587  * are inward distances from the border box edge, used to specify the
588  * rendered size of each slice determined by border-image-slice.
589  * If this property is not specified, the values of border-width will
590  * be used as a fallback.
591  * </para>
592  * <para>
593  * <literallayout>border-image-repeat: [stretch|repeat|round|space] ? 
594  * [stretch|repeat|round|space]</literallayout>
595  * Specifies how the image slices should be rendered in the area
596  * outlined by border-width.
597  * The default (stretch) is to resize the slice to fill in the whole 
598  * allocated area.
599  * If the value of this property is 'repeat', the image slice
600  * will be tiled to fill the area.
601  * If the value of this property is 'round', the image slice will
602  * be tiled to fill the area, and scaled to fit it exactly
603  * a whole number of times.
604  * If the value of this property is 'space', the image slice will
605  * be tiled to fill the area, and if it doesn't fit it exactly a whole
606  * number of times, the extra space is distributed as padding around 
607  * the slices.
608  * If two options are specified, the first one affects
609  * the horizontal behaviour and the second one the vertical behaviour.
610  * If only one option is specified, it affects both.
611  * </para>
612  * <example>
613  * <title>A border image</title>
614  * <inlinegraphic fileref="border1.png" format="PNG"/>
615  * <para>This border image was specified with
616  * <literallayout>url("gradient1.png") 10 10 10 10</literallayout>
617  * </para>
618  * </example>
619  * <example>
620  * <title>A repeating border image</title>
621  * <inlinegraphic fileref="border2.png" format="PNG"/>
622  * <para>This border image was specified with
623  * <literallayout>url("gradient1.png") 10 10 10 10 repeat</literallayout>
624  * </para>
625  * </example>
626  * <example>
627  * <title>A stretched border image</title>
628  * <inlinegraphic fileref="border3.png" format="PNG"/>
629  * <para>This border image was specified with
630  * <literallayout>url("gradient1.png") 10 10 10 10 stretch</literallayout>
631  * </para>
632  * </example>
633  * </refsect2>
634  * <refsect2 id="gtkcssprovider-transitions">
635  * <para>Styles can specify transitions that will be used to create a gradual
636  * change in the appearance when a widget state changes. The following
637  * syntax is used to specify transitions:
638  * <literallayout>@duration [s|ms] [linear|ease|ease-in|ease-out|ease-in-out] [loop]?</literallayout>
639  * The @duration is the amount of time that the animation will take for
640  * a complete cycle from start to end. If the loop option is given, the
641  * animation will be repated until the state changes again.
642  * The option after the duration determines the transition function from a
643  * small set of predefined functions.
644  * <figure><title>Linear transition</title>
645  * <graphic fileref="linear.png" format="PNG"/>
646  * </figure>
647  * <figure><title>Ease transition</title>
648  * <graphic fileref="ease.png" format="PNG"/>
649  * </figure>
650  * <figure><title>Ease-in-out transition</title>
651  * <graphic fileref="ease-in-out.png" format="PNG"/>
652  * </figure>
653  * <figure><title>Ease-in transition</title>
654  * <graphic fileref="ease-in.png" format="PNG"/>
655  * </figure>
656  * <figure><title>Ease-out transition</title>
657  * <graphic fileref="ease-out.png" format="PNG"/>
658  * </figure>
659  * </para>
660  * </refsect2>
661  * <refsect2 id="gtkcssprovider-properties">
662  * <title>Supported properties</title>
663  * <para>
664  * Properties are the part that differ the most to common CSS,
665  * not all properties are supported (some are planned to be
666  * supported eventually, some others are meaningless or don't
667  * map intuitively in a widget based environment).
668  * </para>
669  * <para>
670  * There is also a difference in shorthand properties, for
671  * example in common CSS it is fine to define a font through
672  * the different @font-family, @font-style, @font-size
673  * properties, meanwhile in GTK+'s CSS only the canonical
674  * @font property is supported.
675  * </para>
676  * <para>
677  * The currently supported properties are:
678  * </para>
679  * <informaltable>
680  *   <tgroup cols="4">
681  *     <thead>
682  *       <row>
683  *         <entry>Property name</entry>
684  *         <entry>Syntax</entry>
685  *         <entry>Maps to</entry>
686  *         <entry>Examples</entry>
687  *       </row>
688  *     </thead>
689  *     <tbody>
690  *       <row>
691  *         <entry>engine</entry>
692  *         <entry>engine-name</entry>
693  *         <entry>#GtkThemingEngine</entry>
694  *         <entry>engine: clearlooks;
695  *  engine: none; /&ast; use the default (i.e. builtin) engine) &ast;/ </entry>
696  *       </row>
697  *       <row>
698  *         <entry>background-color</entry>
699  *         <entry morerows="2">color (see above)</entry>
700  *         <entry morerows="7">#GdkRGBA</entry>
701  *         <entry morerows="7"><literallayout>background-color: &num;fff;
702  * color: &amp;color1;
703  * background-color: shade (&amp;color1, 0.5);
704  * color: mix (&amp;color1, &num;f0f, 0.8);</literallayout>
705  *         </entry>
706  *       </row>
707  *       <row>
708  *         <entry>color</entry>
709  *       </row>
710  *       <row>
711  *         <entry>border-top-color</entry>
712  *         <entry morerows="4">transparent|color (see above)</entry>
713  *       </row>
714  *       <row>
715  *         <entry>border-right-color</entry>
716  *       </row>
717  *       <row>
718  *         <entry>border-bottom-color</entry>
719  *       </row>
720  *       <row>
721  *         <entry>border-left-color</entry>
722  *       </row>
723  *       <row>
724  *         <entry>border-color</entry>
725  *         <entry>[transparent|color]{1,4}</entry>
726  *       </row>
727  *       <row>
728  *         <entry>font-family</entry>
729  *         <entry>@family [, @family]*</entry>
730  *         <entry>#gchararray</entry>
731  *         <entry>font-family: Sans, Arial;</entry>
732  *       </row>
733  *       <row>
734  *         <entry>font-style</entry>
735  *         <entry>[normal|oblique|italic]</entry>
736  *         <entry>#PANGO_TYPE_STYLE</entry>
737  *         <entry>font-style: italic;</entry>
738  *       </row>
739  *       <row>
740  *         <entry>font-variant</entry>
741  *         <entry>[normal|small-caps]</entry>
742  *         <entry>#PANGO_TYPE_VARIANT</entry>
743  *         <entry>font-variant: normal;</entry>
744  *       </row>
745  *       <row>
746  *         <entry>font-weight</entry>
747  *         <entry>[normal|bold|bolder|lighter|100|200|300|400|500|600|700|800|900]</entry>
748  *         <entry>#PANGO_TYPE_WEIGHT</entry>
749  *         <entry>font-weight: bold;</entry>
750  *       </row>
751  *       <row>
752  *         <entry>font-size</entry>
753  *         <entry>Font size in point</entry>
754  *         <entry>#gint</entry>
755  *         <entry>font-size: 13;</entry>
756  *       </row>
757  *       <row>
758  *         <entry>font</entry>
759  *         <entry>@family [@style] [@size]</entry>
760  *         <entry>#PangoFontDescription</entry>
761  *         <entry>font: Sans 15;</entry>
762  *       </row>
763  *       <row>
764  *         <entry>margin-top</entry>
765  *         <entry>integer</entry>
766  *         <entry>#gint</entry>
767  *         <entry>margin-top: 0;</entry>
768  *       </row>
769  *       <row>
770  *         <entry>margin-left</entry>
771  *         <entry>integer</entry>
772  *         <entry>#gint</entry>
773  *         <entry>margin-left: 1;</entry>
774  *       </row>
775  *       <row>
776  *         <entry>margin-bottom</entry>
777  *         <entry>integer</entry>
778  *         <entry>#gint</entry>
779  *         <entry>margin-bottom: 2;</entry>
780  *       </row>
781  *       <row>
782  *         <entry>margin-right</entry>
783  *         <entry>integer</entry>
784  *         <entry>#gint</entry>
785  *         <entry>margin-right: 4;</entry>
786  *       </row>
787  *       <row>
788  *         <entry>margin</entry>
789  *         <entry morerows="1"><literallayout>@width
790  * @vertical_width @horizontal_width
791  * @top_width @horizontal_width @bottom_width
792  * @top_width @right_width @bottom_width @left_width</literallayout>
793  *         </entry>
794  *         <entry morerows="1">#GtkBorder</entry>
795  *         <entry morerows="1"><literallayout>margin: 5;
796  * margin: 5 10;
797  * margin: 5 10 3;
798  * margin: 5 10 3 5;</literallayout>
799  *         </entry>
800  *       </row>
801  *       <row>
802  *         <entry>padding-top</entry>
803  *         <entry>integer</entry>
804  *         <entry>#gint</entry>
805  *         <entry>padding-top: 5;</entry>
806  *       </row>
807  *       <row>
808  *         <entry>padding-left</entry>
809  *         <entry>integer</entry>
810  *         <entry>#gint</entry>
811  *         <entry>padding-left: 5;</entry>
812  *       </row>
813  *       <row>
814  *         <entry>padding-bottom</entry>
815  *         <entry>integer</entry>
816  *         <entry>#gint</entry>
817  *         <entry>padding-bottom: 5;</entry>
818  *       </row>
819  *       <row>
820  *         <entry>padding-right</entry>
821  *         <entry>integer</entry>
822  *         <entry>#gint</entry>
823  *         <entry>padding-right: 5;</entry>
824  *       </row>
825  *       <row>
826  *         <entry>padding</entry>
827  *       </row>
828  *       <row>
829  *         <entry>background-image</entry>
830  *         <entry><literallayout>gradient (see above) or
831  * url(@path)</literallayout></entry>
832  *         <entry>#cairo_pattern_t</entry>
833  *         <entry><literallayout>-gtk-gradient (linear,
834  *                left top, right top,
835  *                from (&num;fff), to (&num;000));
836  * -gtk-gradient (linear, 0.0 0.5, 0.5 1.0,
837  *                from (&num;fff),
838  *                color-stop (0.5, &num;f00),
839  *                to (&num;000));
840  * -gtk-gradient (radial,
841  *                center center, 0.2,
842  *                center center, 0.8,
843  *                color-stop (0.0, &num;fff),
844  *                color-stop (1.0, &num;000));
845  * url ('background.png');</literallayout>
846  *         </entry>
847  *       </row>
848  *       <row>
849  *         <entry>border-top-width</entry>
850  *         <entry>integer</entry>
851  *         <entry>#gint</entry>
852  *         <entry>border-top-width: 5;</entry>
853  *       </row>
854  *       <row>
855  *         <entry>border-left-width</entry>
856  *         <entry>integer</entry>
857  *         <entry>#gint</entry>
858  *         <entry>border-left-width: 5;</entry>
859  *       </row>
860  *       <row>
861  *         <entry>border-bottom-width</entry>
862  *         <entry>integer</entry>
863  *         <entry>#gint</entry>
864  *         <entry>border-bottom-width: 5;</entry>
865  *       </row>
866  *       <row>
867  *         <entry>border-right-width</entry>
868  *         <entry>integer</entry>
869  *         <entry>#gint</entry>
870  *         <entry>border-right-width: 5;</entry>
871  *       </row>
872  *       <row>
873  *         <entry>border-width</entry>
874  *         <entry morerows="1">#GtkBorder</entry>
875  *         <entry morerows="1"><literallayout>border-width: 1;
876  * border-width: 1 2;
877  * border-width: 1 2 3;
878  * border-width: 1 2 3 5;</literallayout>
879  *         </entry>
880  *       </row>
881  *       <row>
882  *         <entry>border-radius</entry>
883  *         <entry>integer</entry>
884  *         <entry>#gint</entry>
885  *         <entry>border-radius: 5;</entry>
886  *       </row>
887  *       <row>
888  *         <entry>border-style</entry>
889  *         <entry>[none|solid|inset|outset]</entry>
890  *         <entry>#GtkBorderStyle</entry>
891  *         <entry>border-style: solid;</entry>
892  *       </row>
893  *       <row>
894  *         <entry>border-image</entry>
895  *         <entry><literallayout>border image (see above)</literallayout></entry>
896  *         <entry>internal use only</entry>
897  *         <entry><literallayout>border-image: url("/path/to/image.png") 3 4 3 4 stretch;
898  * border-image: url("/path/to/image.png") 3 4 4 3 repeat stretch;</literallayout>
899  *         </entry>
900  *       </row>
901  *       <row>
902  *         <entry>text-shadow</entry>
903  *         <entry>shadow list (see above)</entry>
904  *         <entry>#GtkTextShadow</entry>
905  *         <entry><literallayout>text-shadow: 1 1 0 blue, -4 -4 red;</literallayout></entry>
906  *       </row>
907  *       <row>
908  *         <entry>transition</entry>
909  *         <entry>transition (see above)</entry>
910  *         <entry>internal use only</entry>
911  *         <entry><literallayout>transition: 150ms ease-in-out;
912  * transition: 1s linear loop;</literallayout>
913  *         </entry>
914  *       </row>
915  *       <row>
916  *         <entry>gtk-key-bindings</entry>
917  *         <entry>binding set name list</entry>
918  *         <entry>internal use only</entry>
919  *         <entry><literallayout>gtk-bindings: binding1, binding2, ...;</literallayout>
920  *         </entry>
921  *       </row>
922  *     </tbody>
923  *   </tgroup>
924  * </informaltable>
925  * <para>
926  * GtkThemingEngines can register their own, engine-specific style properties
927  * with the function gtk_theming_engine_register_property(). These properties
928  * can be set in CSS like other properties, using a name of the form
929  * <literallayout>-<replaceable>namespace</replaceable>-<replaceable>name</replaceable></literallayout>, where <replaceable>namespace</replaceable> is typically
930  * the name of the theming engine, and <replaceable>name</replaceable> is the
931  * name of the property. Style properties that have been registered by widgets
932  * using gtk_widget_class_install_style_property() can also be set in this
933  * way, using the widget class name for <replaceable>namespace</replaceable>.
934  * </para>
935  * <example>
936  * <title>Using engine-specific style properties</title>
937  * <programlisting>
938  * * {
939  *     engine: clearlooks;
940  *     border-radius: 4;
941  *     -GtkPaned-handle-size: 6;
942  *     -clearlooks-colorize-scrollbar: false;
943  * }
944  * </programlisting>
945  * </example>
946  * </refsect2>
947  */
948
949 typedef struct GtkCssRuleset GtkCssRuleset;
950 typedef struct _GtkCssScanner GtkCssScanner;
951 typedef enum ParserScope ParserScope;
952 typedef enum ParserSymbol ParserSymbol;
953
954 struct GtkCssRuleset
955 {
956   GtkCssSelector *selector;
957   GHashTable *widget_style;
958   GHashTable *style;
959
960   guint has_inherit :1;
961 };
962
963 struct _GtkCssScanner
964 {
965   GtkCssProvider *provider;
966   GtkCssParser *parser;
967   GtkCssScanner *parent;
968   GFile *file;
969   GFile *base;
970   GSList *state;
971   GSList *cur_selectors;
972   GHashTable *cur_properties;
973 };
974
975 struct _GtkCssProviderPrivate
976 {
977   GScanner *scanner;
978
979   GHashTable *symbolic_colors;
980
981   GArray *rulesets;
982 };
983
984 enum ParserScope {
985   SCOPE_SELECTOR,
986   SCOPE_PSEUDO_CLASS,
987   SCOPE_NTH_CHILD,
988   SCOPE_DECLARATION,
989   SCOPE_VALUE,
990   SCOPE_BINDING_SET
991 };
992
993 /* Extend GtkStateType, since these
994  * values are also used as symbols
995  */
996 enum ParserSymbol {
997   /* Scope: pseudo-class */
998   SYMBOL_NTH_CHILD = GTK_STATE_FOCUSED + 1,
999   SYMBOL_FIRST_CHILD,
1000   SYMBOL_LAST_CHILD,
1001   SYMBOL_SORTED_CHILD,
1002
1003   /* Scope: nth-child */
1004   SYMBOL_NTH_CHILD_EVEN,
1005   SYMBOL_NTH_CHILD_ODD,
1006   SYMBOL_NTH_CHILD_FIRST,
1007   SYMBOL_NTH_CHILD_LAST
1008 };
1009
1010 enum {
1011   PARSING_ERROR,
1012   LAST_SIGNAL
1013 };
1014
1015 static guint css_provider_signals[LAST_SIGNAL] = { 0 };
1016
1017 static void gtk_css_provider_finalize (GObject *object);
1018 static void gtk_css_style_provider_iface_init (GtkStyleProviderIface *iface);
1019
1020 static gboolean
1021 gtk_css_provider_load_internal (GtkCssProvider *css_provider,
1022                                 GtkCssScanner  *scanner,
1023                                 GFile          *file,
1024                                 const char     *data,
1025                                 gsize           length,
1026                                 GError        **error);
1027
1028 GQuark
1029 gtk_css_provider_error_quark (void)
1030 {
1031   return g_quark_from_static_string ("gtk-css-provider-error-quark");
1032 }
1033
1034 G_DEFINE_TYPE_EXTENDED (GtkCssProvider, gtk_css_provider, G_TYPE_OBJECT, 0,
1035                         G_IMPLEMENT_INTERFACE (GTK_TYPE_STYLE_PROVIDER,
1036                                                gtk_css_style_provider_iface_init));
1037
1038 static void
1039 gtk_css_provider_parsing_error (GtkCssProvider  *provider,
1040                                 const gchar     *path,
1041                                 guint            line,
1042                                 guint            position,
1043                                 const GError *   error)
1044 {
1045   /* Only emit a warning when we have no error handlers. This is our
1046    * default handlers. And in this case erroneous CSS files are a bug
1047    * and should be fixed.
1048    * Note that these warnings can also be triggered by a broken theme
1049    * that people installed from some weird location on the internets.
1050    */
1051   if (!g_signal_has_handler_pending (provider,
1052                                      css_provider_signals[PARSING_ERROR],
1053                                      0,
1054                                      TRUE))
1055     {
1056       g_warning ("Theme parsing error: %s:%u:%u: %s", path ? path : "<unknown>", line, position, error->message);
1057     }
1058 }
1059
1060 static void
1061 gtk_css_provider_class_init (GtkCssProviderClass *klass)
1062 {
1063   GObjectClass *object_class = G_OBJECT_CLASS (klass);
1064
1065   /**
1066    * GtkCssProvider::parsing-error:
1067    * @provider: the provider that had a parsing error
1068    * @path: path to the parsed file or %NULL if the file cannot be
1069    *   identified or the data was not loaded from a file
1070    * @line: line in the file or data or 0 if unknown
1071    * @position: offset into the current line or 0 if unknown or the
1072    *   whole line is affected
1073    * @error: The parsing error
1074    *
1075    * Signals that a parsing error occured. the @path, @line and @position
1076    * describe the actual location of the error as accurately as possible.
1077    *
1078    * Parsing errors are never fatal, so the parsing will resume after
1079    * the error. Errors may however cause parts of the given
1080    * data or even all of it to not be parsed at all. So it is a useful idea
1081    * to check that the parsing succeeds by connecting to this signal.
1082    *
1083    * Note that this signal may be emitted at any time as the css provider
1084    * may opt to defer parsing parts or all of the input to a later time
1085    * than when a loading function was called.
1086    */
1087   css_provider_signals[PARSING_ERROR] =
1088     g_signal_new (I_("parsing-error"),
1089                   G_TYPE_FROM_CLASS (object_class),
1090                   G_SIGNAL_RUN_LAST,
1091                   G_STRUCT_OFFSET (GtkCssProviderClass, parsing_error),
1092                   NULL, NULL,
1093                   _gtk_marshal_VOID__STRING_UINT_UINT_BOXED,
1094                   G_TYPE_NONE, 4,
1095                   G_TYPE_STRING, G_TYPE_UINT, G_TYPE_UINT, G_TYPE_ERROR);
1096
1097   object_class->finalize = gtk_css_provider_finalize;
1098
1099   klass->parsing_error = gtk_css_provider_parsing_error;
1100
1101   g_type_class_add_private (object_class, sizeof (GtkCssProviderPrivate));
1102 }
1103
1104 static void
1105 gtk_css_provider_take_error_full (GtkCssProvider *provider,
1106                                   GFile          *file,
1107                                   guint           line,
1108                                   guint           position,
1109                                   GError         *error)
1110 {
1111   char *filename;
1112
1113   if (file)
1114     filename = g_file_get_path (file);
1115   else
1116     filename = NULL;
1117
1118   g_signal_emit (provider, css_provider_signals[PARSING_ERROR], 0,
1119                  filename, line, position, error);
1120
1121   g_free (filename);
1122   g_error_free (error);
1123 }
1124
1125 static void
1126 gtk_css_ruleset_init_copy (GtkCssRuleset       *new,
1127                            const GtkCssRuleset *ruleset,
1128                            GtkCssSelector      *selector)
1129 {
1130   memcpy (new, ruleset, sizeof (GtkCssRuleset));
1131
1132   new->selector = selector;
1133   if (new->widget_style)
1134     g_hash_table_ref (new->widget_style);
1135   if (new->style)
1136     g_hash_table_ref (new->style);
1137 }
1138
1139 static void
1140 gtk_css_ruleset_clear (GtkCssRuleset *ruleset)
1141 {
1142   if (ruleset->style)
1143     g_hash_table_unref (ruleset->style);
1144   if (ruleset->widget_style)
1145     g_hash_table_unref (ruleset->widget_style);
1146   if (ruleset->selector)
1147     _gtk_css_selector_free (ruleset->selector);
1148
1149   memset (ruleset, 0, sizeof (GtkCssRuleset));
1150 }
1151
1152 static void
1153 property_value_free (GValue *value)
1154 {
1155   if (G_IS_VALUE (value))
1156     g_value_unset (value);
1157
1158   g_slice_free (GValue, value);
1159 }
1160
1161 static void
1162 gtk_css_ruleset_add_style (GtkCssRuleset *ruleset,
1163                            char          *name,
1164                            GValue        *value)
1165 {
1166   if (ruleset->widget_style == NULL)
1167     ruleset->widget_style = g_hash_table_new_full (g_str_hash,
1168                                                    g_str_equal,
1169                                                    (GDestroyNotify) g_free,
1170                                                    (GDestroyNotify) property_value_free);
1171
1172   g_hash_table_insert (ruleset->widget_style, name, value);
1173 }
1174
1175 static void
1176 gtk_css_ruleset_add (GtkCssRuleset          *ruleset,
1177                      const GtkStyleProperty *prop,
1178                      GValue                 *value)
1179 {
1180   if (ruleset->style == NULL)
1181     ruleset->style = g_hash_table_new_full (g_direct_hash,
1182                                             g_direct_equal,
1183                                             NULL,
1184                                             (GDestroyNotify) property_value_free);
1185
1186   if (_gtk_style_property_is_shorthand (prop))
1187     {
1188       GParameter *parameters;
1189       guint i, n_parameters;
1190
1191       parameters = _gtk_style_property_unpack (prop, value, &n_parameters);
1192
1193       for (i = 0; i < n_parameters; i++)
1194         {
1195           const GtkStyleProperty *child;
1196           GValue *value;
1197
1198           child = _gtk_style_property_lookup (parameters[i].name);
1199           value = g_slice_dup (GValue, &parameters[i].value);
1200           gtk_css_ruleset_add (ruleset, child, value);
1201         }
1202       g_free (parameters);
1203       property_value_free (value);
1204       return;
1205     }
1206
1207   ruleset->has_inherit |= _gtk_style_property_is_inherit (prop);
1208   g_hash_table_insert (ruleset->style, (gpointer) prop, value);
1209 }
1210
1211 static gboolean
1212 gtk_css_ruleset_matches (GtkCssRuleset *ruleset,
1213                          GtkWidgetPath *path,
1214                          guint          length)
1215 {
1216   return _gtk_css_selector_matches (ruleset->selector, path, length);
1217 }
1218
1219 static void
1220 gtk_css_scanner_reset (GtkCssScanner *scanner)
1221 {
1222   g_slist_free (scanner->state);
1223   scanner->state = NULL;
1224
1225   g_slist_free_full (scanner->cur_selectors, (GDestroyNotify) _gtk_css_selector_free);
1226   scanner->cur_selectors = NULL;
1227
1228   if (scanner->cur_properties)
1229     g_hash_table_unref (scanner->cur_properties);
1230
1231   scanner ->cur_properties = g_hash_table_new_full (g_str_hash,
1232                                                     g_str_equal,
1233                                                     (GDestroyNotify) g_free,
1234                                                     (GDestroyNotify) property_value_free);
1235 }
1236
1237 static void
1238 gtk_css_scanner_destroy (GtkCssScanner *scanner)
1239 {
1240   gtk_css_scanner_reset (scanner);
1241
1242   g_object_unref (scanner->provider);
1243   if (scanner->file)
1244     g_object_unref (scanner->file);
1245   g_object_unref (scanner->base);
1246   g_hash_table_destroy (scanner->cur_properties);
1247   _gtk_css_parser_free (scanner->parser);
1248
1249   g_slice_free (GtkCssScanner, scanner);
1250 }
1251
1252 static void
1253 gtk_css_scanner_parser_error (GtkCssParser *parser,
1254                               const GError *error,
1255                               gpointer      user_data)
1256 {
1257   GtkCssScanner *scanner = user_data;
1258
1259   gtk_css_provider_take_error_full (scanner->provider,
1260                                     scanner->file,
1261                                     _gtk_css_parser_get_line (scanner->parser),
1262                                     _gtk_css_parser_get_position (scanner->parser),
1263                                     g_error_copy (error));
1264 }
1265
1266 static GtkCssScanner *
1267 gtk_css_scanner_new (GtkCssProvider *provider,
1268                      GtkCssScanner  *parent,
1269                      GFile          *file,
1270                      const gchar    *data,
1271                      gsize           length)
1272 {
1273   GtkCssScanner *scanner;
1274
1275   g_assert (data[length] == 0);
1276
1277   scanner = g_slice_new0 (GtkCssScanner);
1278
1279   g_object_ref (provider);
1280   scanner->provider = provider;
1281   scanner->parent = parent;
1282
1283   if (file)
1284     {
1285       scanner->file = g_object_ref (file);
1286       scanner->base = g_file_get_parent (file);
1287     }
1288   else
1289     {
1290       char *dir = g_get_current_dir ();
1291       scanner->base = g_file_new_for_path (dir);
1292       g_free (dir);
1293     }
1294
1295   scanner->cur_properties = g_hash_table_new_full (g_str_hash,
1296                                                    g_str_equal,
1297                                                    (GDestroyNotify) g_free,
1298                                                    (GDestroyNotify) property_value_free);
1299
1300   scanner->parser = _gtk_css_parser_new (data,
1301                                          gtk_css_scanner_parser_error,
1302                                          scanner);
1303
1304   return scanner;
1305 }
1306
1307 static GFile *
1308 gtk_css_scanner_get_base_url (GtkCssScanner *scanner)
1309 {
1310   return scanner->base;
1311 }
1312
1313 static gboolean
1314 gtk_css_scanner_would_recurse (GtkCssScanner *scanner,
1315                                GFile         *file)
1316 {
1317   while (scanner)
1318     {
1319       if (scanner->file && g_file_equal (scanner->file, file))
1320         return TRUE;
1321
1322       scanner = scanner->parent;
1323     }
1324
1325   return FALSE;
1326 }
1327
1328 static void
1329 gtk_css_provider_init (GtkCssProvider *css_provider)
1330 {
1331   GtkCssProviderPrivate *priv;
1332
1333   priv = css_provider->priv = G_TYPE_INSTANCE_GET_PRIVATE (css_provider,
1334                                                            GTK_TYPE_CSS_PROVIDER,
1335                                                            GtkCssProviderPrivate);
1336
1337   priv->rulesets = g_array_new (FALSE, FALSE, sizeof (GtkCssRuleset));
1338
1339   priv->symbolic_colors = g_hash_table_new_full (g_str_hash, g_str_equal,
1340                                                  (GDestroyNotify) g_free,
1341                                                  (GDestroyNotify) gtk_symbolic_color_unref);
1342 }
1343
1344 static void
1345 css_provider_dump_symbolic_colors (GtkCssProvider     *css_provider,
1346                                    GtkStyleProperties *props)
1347 {
1348   GtkCssProviderPrivate *priv;
1349   GHashTableIter iter;
1350   gpointer key, value;
1351
1352   priv = css_provider->priv;
1353   g_hash_table_iter_init (&iter, priv->symbolic_colors);
1354
1355   while (g_hash_table_iter_next (&iter, &key, &value))
1356     {
1357       const gchar *name;
1358       GtkSymbolicColor *color;
1359
1360       name = key;
1361       color = value;
1362
1363       gtk_style_properties_map_color (props, name, color);
1364     }
1365 }
1366
1367 static GtkStyleProperties *
1368 gtk_css_provider_get_style (GtkStyleProvider *provider,
1369                             GtkWidgetPath    *path)
1370 {
1371   GtkCssProvider *css_provider;
1372   GtkCssProviderPrivate *priv;
1373   GtkStyleProperties *props;
1374   guint i, l, length;
1375
1376   css_provider = GTK_CSS_PROVIDER (provider);
1377   priv = css_provider->priv;
1378   length = gtk_widget_path_length (path);
1379   props = gtk_style_properties_new ();
1380
1381   css_provider_dump_symbolic_colors (css_provider, props);
1382
1383   for (l = 1; l <= length; l++)
1384     {
1385       for (i = 0; i < priv->rulesets->len; i++)
1386         {
1387           GtkCssRuleset *ruleset;
1388           GHashTableIter iter;
1389           gpointer key, value;
1390
1391           ruleset = &g_array_index (priv->rulesets, GtkCssRuleset, i);
1392
1393           if (ruleset->style == NULL)
1394             continue;
1395
1396           if (l < length && (!ruleset->has_inherit || _gtk_css_selector_get_state_flags (ruleset->selector)))
1397             continue;
1398
1399           if (!gtk_css_ruleset_matches (ruleset, path, l))
1400             continue;
1401
1402           g_hash_table_iter_init (&iter, ruleset->style);
1403
1404           while (g_hash_table_iter_next (&iter, &key, &value))
1405             {
1406               GtkStyleProperty *prop = key;
1407
1408               if (l != length && !_gtk_style_property_is_inherit (prop))
1409                 continue;
1410
1411               _gtk_style_properties_set_property_by_property (props,
1412                                                               prop,
1413                                                               _gtk_css_selector_get_state_flags (ruleset->selector),
1414                                                               value);
1415             }
1416         }
1417     }
1418
1419   return props;
1420 }
1421
1422 static void
1423 gtk_css_provider_parser_error (GtkCssParser *parser,
1424                                const GError *error,
1425                                gpointer      user_data)
1426 {
1427   GtkCssProvider *provider = user_data;
1428
1429   gtk_css_provider_take_error_full (provider,
1430                                     NULL,
1431                                     _gtk_css_parser_get_line (parser),
1432                                     _gtk_css_parser_get_position (parser),
1433                                     g_error_copy (error));
1434 }
1435
1436 static gboolean
1437 gtk_css_provider_get_style_property (GtkStyleProvider *provider,
1438                                      GtkWidgetPath    *path,
1439                                      GtkStateFlags     state,
1440                                      GParamSpec       *pspec,
1441                                      GValue           *value)
1442 {
1443   GtkCssProvider *css_provider = GTK_CSS_PROVIDER (provider);
1444   GtkCssProviderPrivate *priv = css_provider->priv;
1445   const GValue *val;
1446   gboolean found = FALSE;
1447   gchar *prop_name;
1448   gint i;
1449
1450   prop_name = g_strdup_printf ("-%s-%s",
1451                                g_type_name (pspec->owner_type),
1452                                pspec->name);
1453
1454   for (i = priv->rulesets->len - 1; i >= 0; i--)
1455     {
1456       GtkCssRuleset *ruleset;
1457       GtkStateFlags selector_state;
1458
1459       ruleset = &g_array_index (priv->rulesets, GtkCssRuleset, i);
1460
1461       if (ruleset->widget_style == NULL)
1462         continue;
1463
1464       if (!gtk_css_ruleset_matches (ruleset, path, gtk_widget_path_length (path)))
1465         continue;
1466
1467       selector_state = _gtk_css_selector_get_state_flags (ruleset->selector);
1468       val = g_hash_table_lookup (ruleset->widget_style, prop_name);
1469
1470       if (val &&
1471           (selector_state == 0 ||
1472            selector_state == state ||
1473            ((selector_state & state) != 0 &&
1474             (selector_state & ~(state)) == 0)))
1475         {
1476           GtkCssParser *parser;
1477
1478           parser = _gtk_css_parser_new (g_value_get_string (val),
1479                                         gtk_css_provider_parser_error,
1480                                         provider);
1481
1482           found = _gtk_style_property_parse_value (NULL,
1483                                                    value,
1484                                                    parser,
1485                                                    NULL);
1486
1487           _gtk_css_parser_free (parser);
1488
1489           if (found)
1490             break;
1491         }
1492     }
1493
1494   g_free (prop_name);
1495
1496   return found;
1497 }
1498
1499 static void
1500 gtk_css_style_provider_iface_init (GtkStyleProviderIface *iface)
1501 {
1502   iface->get_style = gtk_css_provider_get_style;
1503   iface->get_style_property = gtk_css_provider_get_style_property;
1504 }
1505
1506 static void
1507 gtk_css_provider_finalize (GObject *object)
1508 {
1509   GtkCssProvider *css_provider;
1510   GtkCssProviderPrivate *priv;
1511   guint i;
1512
1513   css_provider = GTK_CSS_PROVIDER (object);
1514   priv = css_provider->priv;
1515
1516   for (i = 0; i < priv->rulesets->len; i++)
1517     gtk_css_ruleset_clear (&g_array_index (priv->rulesets, GtkCssRuleset, i));
1518
1519   g_array_free (priv->rulesets, TRUE);
1520
1521   if (priv->symbolic_colors)
1522     g_hash_table_destroy (priv->symbolic_colors);
1523
1524   G_OBJECT_CLASS (gtk_css_provider_parent_class)->finalize (object);
1525 }
1526
1527 /**
1528  * gtk_css_provider_new:
1529  *
1530  * Returns a newly created #GtkCssProvider.
1531  *
1532  * Returns: A new #GtkCssProvider
1533  **/
1534 GtkCssProvider *
1535 gtk_css_provider_new (void)
1536 {
1537   return g_object_new (GTK_TYPE_CSS_PROVIDER, NULL);
1538 }
1539
1540 static void
1541 gtk_css_provider_take_error (GtkCssProvider *provider,
1542                              GtkCssScanner  *scanner,
1543                              GError         *error)
1544 {
1545   gtk_css_provider_take_error_full (provider,
1546                                     scanner->file,
1547                                     _gtk_css_parser_get_line (scanner->parser),
1548                                     _gtk_css_parser_get_position (scanner->parser),
1549                                     error);
1550 }
1551
1552 static void
1553 gtk_css_provider_error_literal (GtkCssProvider *provider,
1554                                 GtkCssScanner  *scanner,
1555                                 GQuark          domain,
1556                                 gint            code,
1557                                 const char     *message)
1558 {
1559   gtk_css_provider_take_error (provider,
1560                                scanner,
1561                                g_error_new_literal (domain, code, message));
1562 }
1563
1564 static void
1565 gtk_css_provider_error (GtkCssProvider *provider,
1566                         GtkCssScanner  *scanner,
1567                         GQuark          domain,
1568                         gint            code,
1569                         const char     *format,
1570                         ...)  G_GNUC_PRINTF (5, 6);
1571 static void
1572 gtk_css_provider_error (GtkCssProvider *provider,
1573                         GtkCssScanner  *scanner,
1574                         GQuark          domain,
1575                         gint            code,
1576                         const char     *format,
1577                         ...)
1578 {
1579   GError *error;
1580   va_list args;
1581
1582   va_start (args, format);
1583   error = g_error_new_valist (domain, code, format, args);
1584   va_end (args);
1585
1586   gtk_css_provider_take_error (provider, scanner, error);
1587 }
1588
1589 static void
1590 gtk_css_provider_invalid_token (GtkCssProvider *provider,
1591                                 GtkCssScanner  *scanner,
1592                                 const char     *expected)
1593 {
1594   gtk_css_provider_error (provider,
1595                           scanner,
1596                           GTK_CSS_PROVIDER_ERROR,
1597                           GTK_CSS_PROVIDER_ERROR_SYNTAX,
1598                           "expected a valid %s", expected);
1599 }
1600
1601 static void 
1602 css_provider_commit (GtkCssProvider *css_provider,
1603                      GSList         *selectors,
1604                      GtkCssRuleset  *ruleset)
1605 {
1606   GtkCssProviderPrivate *priv;
1607   GSList *l;
1608
1609   priv = css_provider->priv;
1610
1611   if (ruleset->style == NULL && ruleset->widget_style == NULL)
1612     {
1613       g_slist_free_full (selectors, (GDestroyNotify) _gtk_css_selector_free);
1614       return;
1615     }
1616
1617   for (l = selectors; l; l = l->next)
1618     {
1619       GtkCssRuleset new;
1620
1621       gtk_css_ruleset_init_copy (&new, ruleset, l->data);
1622
1623       g_array_append_val (priv->rulesets, new);
1624     }
1625
1626   g_slist_free (selectors);
1627 }
1628
1629 static void
1630 gtk_css_provider_reset (GtkCssProvider *css_provider)
1631 {
1632   GtkCssProviderPrivate *priv;
1633   guint i;
1634
1635   priv = css_provider->priv;
1636
1637   g_hash_table_remove_all (priv->symbolic_colors);
1638
1639   for (i = 0; i < priv->rulesets->len; i++)
1640     gtk_css_ruleset_clear (&g_array_index (priv->rulesets, GtkCssRuleset, i));
1641   g_array_set_size (priv->rulesets, 0);
1642 }
1643
1644 static void
1645 gtk_css_provider_propagate_error (GtkCssProvider  *provider,
1646                                   const gchar     *path,
1647                                   guint            line,
1648                                   guint            position,
1649                                   const GError    *error,
1650                                   GError         **propagate_to)
1651 {
1652   /* don't fail for deprecations */
1653   if (g_error_matches (error, GTK_CSS_PROVIDER_ERROR, GTK_CSS_PROVIDER_ERROR_DEPRECATED))
1654     {
1655       g_warning ("Theme parsing error: %s:%u:%u: %s", path ? path : "<unknown>", line, position, error->message);
1656       return;
1657     }
1658
1659   /* we already set an error. And we'd like to keep the first one */
1660   if (*propagate_to)
1661     return;
1662
1663   *propagate_to = g_error_copy (error);
1664   g_prefix_error (propagate_to, "%s:%u:%u: ", path ? path : "<unknown>", line, position);
1665 }
1666
1667 static void
1668 parse_import (GtkCssScanner *scanner)
1669 {
1670   GFile *file;
1671   char *uri;
1672
1673   if (_gtk_css_parser_is_string (scanner->parser))
1674     uri = _gtk_css_parser_read_string (scanner->parser);
1675   else
1676     uri = _gtk_css_parser_read_uri (scanner->parser);
1677   if (uri == NULL)
1678     {
1679       _gtk_css_parser_resync (scanner->parser, TRUE, 0);
1680       return;
1681     }
1682
1683   file = g_file_resolve_relative_path (gtk_css_scanner_get_base_url (scanner), uri);
1684   g_free (uri);
1685
1686   if (gtk_css_scanner_would_recurse (scanner, file))
1687     {
1688        char *path = g_file_get_path (file);
1689        gtk_css_provider_error (scanner->provider,
1690                                scanner,
1691                                GTK_CSS_PROVIDER_ERROR,
1692                                GTK_CSS_PROVIDER_ERROR_IMPORT,
1693                                "Loading '%s' would recurse",
1694                                path);
1695        g_free (path);
1696     }
1697   else
1698     {
1699       gtk_css_provider_load_internal (scanner->provider,
1700                                       scanner,
1701                                       file,
1702                                       NULL, 0,
1703                                       NULL);
1704     }
1705
1706   if (!_gtk_css_parser_try (scanner->parser, ";", TRUE))
1707     {
1708       g_object_unref (file);
1709       gtk_css_provider_invalid_token (scanner->provider, scanner, "semicolon");
1710       _gtk_css_parser_resync (scanner->parser, TRUE, 0);
1711       return;
1712     }
1713
1714   g_object_unref (file);
1715 }
1716
1717 static void
1718 parse_color_definition (GtkCssScanner *scanner)
1719 {
1720   GtkSymbolicColor *symbolic;
1721   char *name;
1722
1723   name = _gtk_css_parser_try_name (scanner->parser, TRUE);
1724   if (name == NULL)
1725     {
1726       gtk_css_provider_error_literal (scanner->provider,
1727                                       scanner,
1728                                       GTK_CSS_PROVIDER_ERROR,
1729                                       GTK_CSS_PROVIDER_ERROR_SYNTAX,
1730                                       "Not a valid color name");
1731       _gtk_css_parser_resync (scanner->parser, TRUE, 0);
1732       return;
1733     }
1734
1735   symbolic = _gtk_css_parser_read_symbolic_color (scanner->parser);
1736   if (symbolic == NULL)
1737     {
1738       g_free (name);
1739       _gtk_css_parser_resync (scanner->parser, TRUE, 0);
1740       return;
1741     }
1742
1743   if (!_gtk_css_parser_try (scanner->parser, ";", TRUE))
1744     {
1745       g_free (name);
1746       gtk_symbolic_color_unref (symbolic);
1747       gtk_css_provider_error_literal (scanner->provider,
1748                                       scanner,
1749                                       GTK_CSS_PROVIDER_ERROR,
1750                                       GTK_CSS_PROVIDER_ERROR_SYNTAX,
1751                                       "Missing semicolon at end of color definition");
1752       _gtk_css_parser_resync (scanner->parser, TRUE, 0);
1753       return;
1754     }
1755
1756   g_hash_table_insert (scanner->provider->priv->symbolic_colors, name, symbolic);
1757 }
1758
1759 static void
1760 parse_binding_set (GtkCssScanner *scanner)
1761 {
1762   GtkBindingSet *binding_set;
1763   char *name;
1764
1765   name = _gtk_css_parser_try_ident (scanner->parser, TRUE);
1766   if (name == NULL)
1767     {
1768       gtk_css_provider_error_literal (scanner->provider,
1769                                       scanner,
1770                                       GTK_CSS_PROVIDER_ERROR,
1771                                       GTK_CSS_PROVIDER_ERROR_SYNTAX,
1772                                       "Expected name for binding set");
1773       _gtk_css_parser_resync (scanner->parser, TRUE, 0);
1774       goto skip_semicolon;
1775     }
1776
1777   binding_set = gtk_binding_set_find (name);
1778   if (!binding_set)
1779     {
1780       binding_set = gtk_binding_set_new (name);
1781       binding_set->parsed = TRUE;
1782     }
1783   g_free (name);
1784
1785   if (!_gtk_css_parser_try (scanner->parser, "{", TRUE))
1786     {
1787       gtk_css_provider_error_literal (scanner->provider,
1788                                       scanner,
1789                                       GTK_CSS_PROVIDER_ERROR,
1790                                       GTK_CSS_PROVIDER_ERROR_SYNTAX,
1791                                       "Expected '{' for binding set");
1792       _gtk_css_parser_resync (scanner->parser, TRUE, 0);
1793       goto skip_semicolon;
1794     }
1795
1796   while (!_gtk_css_parser_is_eof (scanner->parser) &&
1797          !_gtk_css_parser_begins_with (scanner->parser, '}'))
1798     {
1799       name = _gtk_css_parser_read_value (scanner->parser);
1800       if (name == NULL)
1801         {
1802           _gtk_css_parser_resync (scanner->parser, TRUE, '}');
1803           continue;
1804         }
1805
1806       if (gtk_binding_entry_add_signal_from_string (binding_set, name) != G_TOKEN_NONE)
1807         {
1808           gtk_css_provider_error_literal (scanner->provider,
1809                                           scanner,
1810                                           GTK_CSS_PROVIDER_ERROR,
1811                                           GTK_CSS_PROVIDER_ERROR_SYNTAX,
1812                                           "Failed to parse binding set.");
1813         }
1814
1815       g_free (name);
1816
1817       if (!_gtk_css_parser_try (scanner->parser, ";", TRUE))
1818         {
1819           if (!_gtk_css_parser_begins_with (scanner->parser, '}') &&
1820               !_gtk_css_parser_is_eof (scanner->parser))
1821             {
1822               gtk_css_provider_error_literal (scanner->provider,
1823                                               scanner,
1824                                               GTK_CSS_PROVIDER_ERROR,
1825                                               GTK_CSS_PROVIDER_ERROR_SYNTAX,
1826                                               "Expected semicolon");
1827               _gtk_css_parser_resync (scanner->parser, TRUE, '}');
1828             }
1829         }
1830     }
1831
1832   if (!_gtk_css_parser_try (scanner->parser, "}", TRUE))
1833     {
1834       gtk_css_provider_error_literal (scanner->provider,
1835                                       scanner,
1836                                       GTK_CSS_PROVIDER_ERROR,
1837                                       GTK_CSS_PROVIDER_ERROR_SYNTAX,
1838                                       "expected '}' after declarations");
1839       if (!_gtk_css_parser_is_eof (scanner->parser))
1840         _gtk_css_parser_resync (scanner->parser, FALSE, 0);
1841     }
1842
1843 skip_semicolon:
1844   if (_gtk_css_parser_begins_with (scanner->parser, ';'))
1845     {
1846       gtk_css_provider_error_literal (scanner->provider,
1847                                       scanner,
1848                                       GTK_CSS_PROVIDER_ERROR,
1849                                       GTK_CSS_PROVIDER_ERROR_DEPRECATED,
1850                                       "Nonstandard semicolon at end of binding set");
1851       _gtk_css_parser_try (scanner->parser, ";", TRUE);
1852     }
1853 }
1854
1855 static void
1856 parse_at_keyword (GtkCssScanner *scanner)
1857 {
1858   if (_gtk_css_parser_try (scanner->parser, "@import", TRUE))
1859     parse_import (scanner);
1860   else if (_gtk_css_parser_try (scanner->parser, "@define-color", TRUE))
1861     parse_color_definition (scanner);
1862   else if (_gtk_css_parser_try (scanner->parser, "@binding-set", TRUE))
1863     parse_binding_set (scanner);
1864   else
1865     {
1866       gtk_css_provider_error_literal (scanner->provider,
1867                                       scanner,
1868                                       GTK_CSS_PROVIDER_ERROR,
1869                                       GTK_CSS_PROVIDER_ERROR_SYNTAX,
1870                                       "unknown @ rule");
1871       _gtk_css_parser_resync (scanner->parser, TRUE, 0);
1872     }
1873 }
1874
1875 static gboolean
1876 parse_selector_class (GtkCssScanner *scanner, GArray *classes)
1877 {
1878   GQuark qname;
1879   char *name;
1880     
1881   name = _gtk_css_parser_try_name (scanner->parser, FALSE);
1882
1883   if (name == NULL)
1884     {
1885       gtk_css_provider_error_literal (scanner->provider,
1886                                       scanner,
1887                                       GTK_CSS_PROVIDER_ERROR,
1888                                       GTK_CSS_PROVIDER_ERROR_SYNTAX,
1889                                       "Expected a valid name for class");
1890       return FALSE;
1891     }
1892
1893   qname = g_quark_from_string (name);
1894   g_array_append_val (classes, qname);
1895   g_free (name);
1896   return TRUE;
1897 }
1898
1899 static gboolean
1900 parse_selector_name (GtkCssScanner *scanner, GArray *names)
1901 {
1902   GQuark qname;
1903   char *name;
1904     
1905   name = _gtk_css_parser_try_name (scanner->parser, FALSE);
1906
1907   if (name == NULL)
1908     {
1909       gtk_css_provider_error_literal (scanner->provider,
1910                                       scanner,
1911                                       GTK_CSS_PROVIDER_ERROR,
1912                                       GTK_CSS_PROVIDER_ERROR_SYNTAX,
1913                                       "Expected a valid name for id");
1914       return FALSE;
1915     }
1916
1917   qname = g_quark_from_string (name);
1918   g_array_append_val (names, qname);
1919   g_free (name);
1920   return TRUE;
1921 }
1922
1923 static gboolean
1924 parse_selector_pseudo_class (GtkCssScanner  *scanner,
1925                              GtkRegionFlags *region_to_modify,
1926                              GtkStateFlags  *state_to_modify)
1927 {
1928   struct {
1929     const char *name;
1930     GtkRegionFlags region_flag;
1931     GtkStateFlags state_flag;
1932   } pseudo_classes[] = {
1933     { "first-child",  GTK_REGION_FIRST, 0 },
1934     { "last-child",   GTK_REGION_LAST, 0 },
1935     { "sorted",       GTK_REGION_SORTED, 0 },
1936     { "active",       0, GTK_STATE_FLAG_ACTIVE },
1937     { "prelight",     0, GTK_STATE_FLAG_PRELIGHT },
1938     { "hover",        0, GTK_STATE_FLAG_PRELIGHT },
1939     { "selected",     0, GTK_STATE_FLAG_SELECTED },
1940     { "insensitive",  0, GTK_STATE_FLAG_INSENSITIVE },
1941     { "inconsistent", 0, GTK_STATE_FLAG_INCONSISTENT },
1942     { "focused",      0, GTK_STATE_FLAG_FOCUSED },
1943     { "focus",        0, GTK_STATE_FLAG_FOCUSED },
1944     { NULL, }
1945   }, nth_child_classes[] = {
1946     { "first",        GTK_REGION_FIRST, 0 },
1947     { "last",         GTK_REGION_LAST, 0 },
1948     { "even",         GTK_REGION_EVEN, 0 },
1949     { "odd",          GTK_REGION_ODD, 0 },
1950     { NULL, }
1951   }, *classes;
1952   guint i;
1953   char *name;
1954
1955   name = _gtk_css_parser_try_ident (scanner->parser, FALSE);
1956   if (name == NULL)
1957     {
1958       gtk_css_provider_error_literal (scanner->provider,
1959                                       scanner,
1960                                       GTK_CSS_PROVIDER_ERROR,
1961                                       GTK_CSS_PROVIDER_ERROR_SYNTAX,
1962                                       "Missing name of pseudo-class");
1963       return FALSE;
1964     }
1965
1966   if (_gtk_css_parser_try (scanner->parser, "(", TRUE))
1967     {
1968       char *function = name;
1969
1970       name = _gtk_css_parser_try_ident (scanner->parser, TRUE);
1971       if (!_gtk_css_parser_try (scanner->parser, ")", FALSE))
1972         {
1973           gtk_css_provider_error_literal (scanner->provider,
1974                                           scanner,
1975                                           GTK_CSS_PROVIDER_ERROR,
1976                                           GTK_CSS_PROVIDER_ERROR_SYNTAX,
1977                                           "Missing closing bracket for pseudo-class");
1978           return FALSE;
1979         }
1980
1981       if (g_ascii_strcasecmp (function, "nth-child") != 0)
1982         {
1983           gtk_css_provider_error (scanner->provider,
1984                                   scanner,
1985                                   GTK_CSS_PROVIDER_ERROR,
1986                                   GTK_CSS_PROVIDER_ERROR_UNKNOWN_VALUE,
1987                                   "Unknown pseudo-class '%s(%s)'", function, name ? name : "");
1988           g_free (function);
1989           g_free (name);
1990           return FALSE;
1991         }
1992       
1993       g_free (function);
1994     
1995       if (name == NULL)
1996         {
1997           gtk_css_provider_error (scanner->provider,
1998                                   scanner,
1999                                   GTK_CSS_PROVIDER_ERROR,
2000                                   GTK_CSS_PROVIDER_ERROR_UNKNOWN_VALUE,
2001                                   "nth-child() requires an argument");
2002           return FALSE;
2003         }
2004
2005       classes = nth_child_classes;
2006     }
2007   else
2008     classes = pseudo_classes;
2009
2010   for (i = 0; classes[i].name != NULL; i++)
2011     {
2012       if (g_ascii_strcasecmp (name, classes[i].name) == 0)
2013         {
2014           if ((*region_to_modify & classes[i].region_flag) ||
2015               (*state_to_modify & classes[i].state_flag))
2016             {
2017               if (classes == nth_child_classes)
2018                 gtk_css_provider_error (scanner->provider,
2019                                         scanner,
2020                                         GTK_CSS_PROVIDER_ERROR,
2021                                         GTK_CSS_PROVIDER_ERROR_SYNTAX,
2022                                         "Duplicate pseudo-class 'nth-child(%s)'", name);
2023               else
2024                 gtk_css_provider_error (scanner->provider,
2025                                         scanner,
2026                                         GTK_CSS_PROVIDER_ERROR,
2027                                         GTK_CSS_PROVIDER_ERROR_SYNTAX,
2028                                         "Duplicate pseudo-class '%s'", name);
2029             }
2030           *region_to_modify |= classes[i].region_flag;
2031           *state_to_modify |= classes[i].state_flag;
2032
2033           g_free (name);
2034           return TRUE;
2035         }
2036     }
2037
2038   if (classes == nth_child_classes)
2039     gtk_css_provider_error (scanner->provider,
2040                             scanner,
2041                             GTK_CSS_PROVIDER_ERROR,
2042                             GTK_CSS_PROVIDER_ERROR_UNKNOWN_VALUE,
2043                             "Unknown pseudo-class 'nth-child(%s)'", name);
2044   else
2045     gtk_css_provider_error (scanner->provider,
2046                             scanner,
2047                             GTK_CSS_PROVIDER_ERROR,
2048                             GTK_CSS_PROVIDER_ERROR_UNKNOWN_VALUE,
2049                             "Unknown pseudo-class '%s'", name);
2050   g_free (name);
2051   return FALSE;
2052 }
2053
2054 static gboolean
2055 parse_simple_selector (GtkCssScanner *scanner,
2056                        char **name,
2057                        GArray *ids,
2058                        GArray *classes,
2059                        GtkRegionFlags *pseudo_classes,
2060                        GtkStateFlags *state)
2061 {
2062   gboolean parsed_something;
2063   
2064   *name = _gtk_css_parser_try_ident (scanner->parser, FALSE);
2065   if (*name)
2066     parsed_something = TRUE;
2067   else
2068     parsed_something = _gtk_css_parser_try (scanner->parser, "*", FALSE);
2069
2070   do {
2071       if (_gtk_css_parser_try (scanner->parser, "#", FALSE))
2072         {
2073           if (!parse_selector_name (scanner, ids))
2074             return FALSE;
2075         }
2076       else if (_gtk_css_parser_try (scanner->parser, ".", FALSE))
2077         {
2078           if (!parse_selector_class (scanner, classes))
2079             return FALSE;
2080         }
2081       else if (_gtk_css_parser_try (scanner->parser, ":", FALSE))
2082         {
2083           if (!parse_selector_pseudo_class (scanner, pseudo_classes, state))
2084             return FALSE;
2085         }
2086       else if (!parsed_something)
2087         {
2088           gtk_css_provider_error_literal (scanner->provider,
2089                                           scanner,
2090                                           GTK_CSS_PROVIDER_ERROR,
2091                                           GTK_CSS_PROVIDER_ERROR_SYNTAX,
2092                                           "Expected a valid selector");
2093           return FALSE;
2094         }
2095       else
2096         break;
2097
2098       parsed_something = TRUE;
2099     }
2100   while (!_gtk_css_parser_is_eof (scanner->parser));
2101
2102   _gtk_css_parser_skip_whitespace (scanner->parser);
2103   return TRUE;
2104 }
2105
2106 static GtkCssSelector *
2107 parse_selector (GtkCssScanner *scanner)
2108 {
2109   GtkCssSelector *selector = NULL;
2110
2111   do {
2112       char *name = NULL;
2113       GArray *ids = g_array_new (TRUE, FALSE, sizeof (GQuark));
2114       GArray *classes = g_array_new (TRUE, FALSE, sizeof (GQuark));
2115       GtkRegionFlags pseudo_classes = 0;
2116       GtkStateFlags state = 0;
2117       GtkCssCombinator combine = GTK_CSS_COMBINE_DESCANDANT;
2118
2119       if (selector)
2120         {
2121           if (_gtk_css_parser_try (scanner->parser, ">", TRUE))
2122             combine = GTK_CSS_COMBINE_CHILD;
2123         }
2124
2125       if (!parse_simple_selector (scanner, &name, ids, classes, &pseudo_classes, &state))
2126         {
2127           g_array_free (ids, TRUE);
2128           g_array_free (classes, TRUE);
2129           if (selector)
2130             _gtk_css_selector_free (selector);
2131           return NULL;
2132         }
2133
2134       selector = _gtk_css_selector_new (selector,
2135                                         combine,
2136                                         name,
2137                                         (GQuark *) g_array_free (ids, ids->len == 0),
2138                                         (GQuark *) g_array_free (classes, classes->len == 0),
2139                                         pseudo_classes,
2140                                         state);
2141       g_free (name);
2142     }
2143   while (!_gtk_css_parser_is_eof (scanner->parser) &&
2144          !_gtk_css_parser_begins_with (scanner->parser, ',') &&
2145          !_gtk_css_parser_begins_with (scanner->parser, '{'));
2146
2147   return selector;
2148 }
2149
2150 static GSList *
2151 parse_selector_list (GtkCssScanner *scanner)
2152 {
2153   GSList *selectors = NULL;
2154
2155   do {
2156       GtkCssSelector *select = parse_selector (scanner);
2157
2158       if (select == NULL)
2159         {
2160           g_slist_free_full (selectors, (GDestroyNotify) _gtk_css_selector_free);
2161           _gtk_css_parser_resync (scanner->parser, FALSE, 0);
2162           return NULL;
2163         }
2164
2165       selectors = g_slist_prepend (selectors, select);
2166     }
2167   while (_gtk_css_parser_try (scanner->parser, ",", TRUE));
2168
2169   return selectors;
2170 }
2171
2172 static void
2173 parse_declaration (GtkCssScanner *scanner,
2174                    GtkCssRuleset *ruleset)
2175 {
2176   const GtkStyleProperty *property;
2177   char *name;
2178
2179   name = _gtk_css_parser_try_ident (scanner->parser, TRUE);
2180   if (name == NULL)
2181     goto check_for_semicolon;
2182
2183   property = _gtk_style_property_lookup (name);
2184   if (property == NULL && name[0] != '-')
2185     {
2186       gtk_css_provider_error (scanner->provider,
2187                               scanner,
2188                               GTK_CSS_PROVIDER_ERROR,
2189                               GTK_CSS_PROVIDER_ERROR_NAME,
2190                               "'%s' is not a valid property name",
2191                               name);
2192       _gtk_css_parser_resync (scanner->parser, TRUE, '}');
2193       g_free (name);
2194       return;
2195     }
2196
2197   if (!_gtk_css_parser_try (scanner->parser, ":", TRUE))
2198     {
2199       gtk_css_provider_invalid_token (scanner->provider, scanner, "':'");
2200       _gtk_css_parser_resync (scanner->parser, TRUE, '}');
2201       g_free (name);
2202       return;
2203     }
2204
2205   if (property)
2206     {
2207       GValue *val;
2208
2209       g_free (name);
2210
2211       val = g_slice_new0 (GValue);
2212       g_value_init (val, property->pspec->value_type);
2213
2214       if (_gtk_style_property_parse_value (property,
2215                                            val,
2216                                            scanner->parser,
2217                                            gtk_css_scanner_get_base_url (scanner)))
2218         {
2219           if (_gtk_css_parser_begins_with (scanner->parser, ';') ||
2220               _gtk_css_parser_begins_with (scanner->parser, '}') ||
2221               _gtk_css_parser_is_eof (scanner->parser))
2222             {
2223               gtk_css_ruleset_add (ruleset, property, val);
2224             }
2225           else
2226             {
2227               gtk_css_provider_error_literal (scanner->provider,
2228                                               scanner,
2229                                               GTK_CSS_PROVIDER_ERROR,
2230                                               GTK_CSS_PROVIDER_ERROR_SYNTAX,
2231                                               "Junk at end of value");
2232               _gtk_css_parser_resync (scanner->parser, TRUE, '}');
2233               g_value_unset (val);
2234               g_slice_free (GValue, val);
2235               return;
2236             }
2237         }
2238       else
2239         {
2240           g_value_unset (val);
2241           g_slice_free (GValue, val);
2242           _gtk_css_parser_resync (scanner->parser, TRUE, '}');
2243           return;
2244         }
2245     }
2246   else if (name[0] == '-')
2247     {
2248       char *value_str;
2249
2250       value_str = _gtk_css_parser_read_value (scanner->parser);
2251       if (value_str)
2252         {
2253           GValue *val;
2254
2255           val = g_slice_new0 (GValue);
2256           g_value_init (val, G_TYPE_STRING);
2257           g_value_take_string (val, value_str);
2258
2259           gtk_css_ruleset_add_style (ruleset, name, val);
2260         }
2261       else
2262         {
2263           _gtk_css_parser_resync (scanner->parser, TRUE, '}');
2264           return;
2265         }
2266     }
2267   else
2268     g_free (name);
2269
2270 check_for_semicolon:
2271   if (!_gtk_css_parser_try (scanner->parser, ";", TRUE))
2272     {
2273       if (!_gtk_css_parser_begins_with (scanner->parser, '}') &&
2274           !_gtk_css_parser_is_eof (scanner->parser))
2275         {
2276           gtk_css_provider_error_literal (scanner->provider,
2277                                           scanner,
2278                                           GTK_CSS_PROVIDER_ERROR,
2279                                           GTK_CSS_PROVIDER_ERROR_SYNTAX,
2280                                           "Expected semicolon");
2281           _gtk_css_parser_resync (scanner->parser, TRUE, '}');
2282         }
2283     }
2284 }
2285
2286 static void
2287 parse_declarations (GtkCssScanner *scanner,
2288                     GtkCssRuleset *ruleset)
2289 {
2290   while (!_gtk_css_parser_is_eof (scanner->parser) &&
2291          !_gtk_css_parser_begins_with (scanner->parser, '}'))
2292     {
2293       parse_declaration (scanner, ruleset);
2294     }
2295 }
2296
2297 static void
2298 parse_ruleset (GtkCssScanner *scanner)
2299 {
2300   GSList *selectors;
2301   GtkCssRuleset ruleset = { 0, };
2302
2303   selectors = parse_selector_list (scanner);
2304   if (selectors == NULL)
2305     return;
2306
2307   if (!_gtk_css_parser_try (scanner->parser, "{", TRUE))
2308     {
2309       gtk_css_provider_error_literal (scanner->provider,
2310                                       scanner,
2311                                       GTK_CSS_PROVIDER_ERROR,
2312                                       GTK_CSS_PROVIDER_ERROR_SYNTAX,
2313                                       "expected '{' after selectors");
2314       _gtk_css_parser_resync (scanner->parser, FALSE, 0);
2315       g_slist_free_full (selectors, (GDestroyNotify) _gtk_css_selector_free);
2316       return;
2317     }
2318
2319   parse_declarations (scanner, &ruleset);
2320
2321   if (!_gtk_css_parser_try (scanner->parser, "}", TRUE))
2322     {
2323       gtk_css_provider_error_literal (scanner->provider,
2324                                       scanner,
2325                                       GTK_CSS_PROVIDER_ERROR,
2326                                       GTK_CSS_PROVIDER_ERROR_SYNTAX,
2327                                       "expected '}' after declarations");
2328       if (!_gtk_css_parser_is_eof (scanner->parser))
2329         {
2330           _gtk_css_parser_resync (scanner->parser, FALSE, 0);
2331           g_slist_free_full (selectors, (GDestroyNotify) _gtk_css_selector_free);
2332           gtk_css_ruleset_clear (&ruleset);
2333           return;
2334         }
2335     }
2336
2337   css_provider_commit (scanner->provider, selectors, &ruleset);
2338   gtk_css_ruleset_clear (&ruleset);
2339 }
2340
2341 static void
2342 parse_statement (GtkCssScanner *scanner)
2343 {
2344   if (_gtk_css_parser_begins_with (scanner->parser, '@'))
2345     parse_at_keyword (scanner);
2346   else
2347     parse_ruleset (scanner);
2348 }
2349
2350 static void
2351 parse_stylesheet (GtkCssScanner *scanner)
2352 {
2353   _gtk_css_parser_skip_whitespace (scanner->parser);
2354
2355   while (!_gtk_css_parser_is_eof (scanner->parser))
2356     {
2357       if (_gtk_css_parser_try (scanner->parser, "<!--", TRUE) ||
2358           _gtk_css_parser_try (scanner->parser, "-->", TRUE))
2359         continue;
2360
2361       parse_statement (scanner);
2362     }
2363 }
2364
2365 static int
2366 gtk_css_provider_compare_rule (gconstpointer a_,
2367                                gconstpointer b_)
2368 {
2369   const GtkCssRuleset *a = (const GtkCssRuleset *) a_;
2370   const GtkCssRuleset *b = (const GtkCssRuleset *) b_;
2371   int compare;
2372
2373   compare = _gtk_css_selector_compare (a->selector, b->selector);
2374   if (compare != 0)
2375     return compare;
2376
2377   /* compare pointers in array to ensure a stable sort */
2378   if (a_ < b_)
2379     return -1;
2380
2381   if (a_ > b_)
2382     return 1;
2383
2384   return 0;
2385 }
2386
2387 static void
2388 gtk_css_provider_postprocess (GtkCssProvider *css_provider)
2389 {
2390   GtkCssProviderPrivate *priv = css_provider->priv;
2391
2392   g_array_sort (priv->rulesets, gtk_css_provider_compare_rule);
2393 }
2394
2395 static gboolean
2396 gtk_css_provider_load_internal (GtkCssProvider *css_provider,
2397                                 GtkCssScanner  *parent,
2398                                 GFile          *file,
2399                                 const char     *data,
2400                                 gsize           length,
2401                                 GError        **error)
2402 {
2403   GtkCssScanner *scanner;
2404   gulong error_handler;
2405   char *free_data = NULL;
2406
2407   if (error)
2408     error_handler = g_signal_connect (css_provider,
2409                                       "parsing-error",
2410                                       G_CALLBACK (gtk_css_provider_propagate_error),
2411                                       error);
2412   else
2413     error_handler = 0; /* silence gcc */
2414
2415   if (data == NULL)
2416     {
2417       GError *load_error = NULL;
2418
2419       if (g_file_load_contents (file, NULL,
2420                                 &free_data, &length,
2421                                 NULL, &load_error))
2422         {
2423           data = free_data;
2424         }
2425       else
2426         {
2427           if (parent)
2428             {
2429               gtk_css_provider_error (css_provider,
2430                                       parent,
2431                                       GTK_CSS_PROVIDER_ERROR,
2432                                       GTK_CSS_PROVIDER_ERROR_IMPORT,
2433                                       "Failed to import: %s",
2434                                       load_error->message);
2435               g_error_free (load_error);
2436             }
2437           else
2438             {
2439               gtk_css_provider_take_error_full (css_provider,
2440                                                 file,
2441                                                 0, 0,
2442                                                 load_error);
2443             }
2444         }
2445     }
2446
2447   if (data)
2448     {
2449       scanner = gtk_css_scanner_new (css_provider, parent, file, data, length);
2450
2451       parse_stylesheet (scanner);
2452
2453       gtk_css_scanner_destroy (scanner);
2454
2455       if (parent == NULL)
2456         gtk_css_provider_postprocess (css_provider);
2457     }
2458
2459   g_free (free_data);
2460
2461   if (error)
2462     {
2463       g_signal_handler_disconnect (css_provider, error_handler);
2464
2465       if (*error)
2466         {
2467           /* We clear all contents from the provider for backwards compat reasons */
2468           gtk_css_provider_reset (css_provider);
2469           return FALSE;
2470         }
2471     }
2472
2473   return TRUE;
2474 }
2475
2476 /**
2477  * gtk_css_provider_load_from_data:
2478  * @css_provider: a #GtkCssProvider
2479  * @data: (array length=length) (element-type guint8): CSS data loaded in memory
2480  * @length: the length of @data in bytes, or -1 for NUL terminated strings
2481  * @error: (out) (allow-none): return location for a #GError, or %NULL
2482  *
2483  * Loads @data into @css_provider, making it clear any previously loaded
2484  * information.
2485  *
2486  * Returns: %TRUE if the data could be loaded.
2487  **/
2488 gboolean
2489 gtk_css_provider_load_from_data (GtkCssProvider  *css_provider,
2490                                  const gchar     *data,
2491                                  gssize           length,
2492                                  GError         **error)
2493 {
2494   g_return_val_if_fail (GTK_IS_CSS_PROVIDER (css_provider), FALSE);
2495   g_return_val_if_fail (data != NULL, FALSE);
2496
2497   if (length < 0)
2498     length = strlen (data);
2499
2500   gtk_css_provider_reset (css_provider);
2501
2502   return gtk_css_provider_load_internal (css_provider, NULL, NULL, data, length, error);
2503 }
2504
2505 /**
2506  * gtk_css_provider_load_from_file:
2507  * @css_provider: a #GtkCssProvider
2508  * @file: #GFile pointing to a file to load
2509  * @error: (out) (allow-none): return location for a #GError, or %NULL
2510  *
2511  * Loads the data contained in @file into @css_provider, making it
2512  * clear any previously loaded information.
2513  *
2514  * Returns: %TRUE if the data could be loaded.
2515  **/
2516 gboolean
2517 gtk_css_provider_load_from_file (GtkCssProvider  *css_provider,
2518                                  GFile           *file,
2519                                  GError         **error)
2520 {
2521   g_return_val_if_fail (GTK_IS_CSS_PROVIDER (css_provider), FALSE);
2522   g_return_val_if_fail (G_IS_FILE (file), FALSE);
2523
2524   gtk_css_provider_reset (css_provider);
2525
2526   return gtk_css_provider_load_internal (css_provider, NULL, file, NULL, 0, error);
2527 }
2528
2529 /**
2530  * gtk_css_provider_load_from_path:
2531  * @css_provider: a #GtkCssProvider
2532  * @path: the path of a filename to load, in the GLib filename encoding
2533  * @error: (out) (allow-none): return location for a #GError, or %NULL
2534  *
2535  * Loads the data contained in @path into @css_provider, making it clear
2536  * any previously loaded information.
2537  *
2538  * Returns: %TRUE if the data could be loaded.
2539  **/
2540 gboolean
2541 gtk_css_provider_load_from_path (GtkCssProvider  *css_provider,
2542                                  const gchar     *path,
2543                                  GError         **error)
2544 {
2545   GFile *file;
2546   gboolean result;
2547
2548   g_return_val_if_fail (GTK_IS_CSS_PROVIDER (css_provider), FALSE);
2549   g_return_val_if_fail (path != NULL, FALSE);
2550
2551   file = g_file_new_for_path (path);
2552   
2553   result = gtk_css_provider_load_from_file (css_provider, file, error);
2554
2555   g_object_unref (file);
2556
2557   return result;
2558 }
2559
2560 /**
2561  * gtk_css_provider_get_default:
2562  *
2563  * Returns the provider containing the style settings used as a
2564  * fallback for all widgets.
2565  *
2566  * Returns: (transfer none): The provider used for fallback styling.
2567  *          This memory is owned by GTK+, and you must not free it.
2568  **/
2569 GtkCssProvider *
2570 gtk_css_provider_get_default (void)
2571 {
2572   static GtkCssProvider *provider;
2573
2574   if (G_UNLIKELY (!provider))
2575     {
2576       const gchar *str =
2577         "@define-color fg_color #000; \n"
2578         "@define-color bg_color #dcdad5; \n"
2579         "@define-color text_color #000; \n"
2580         "@define-color base_color #fff; \n"
2581         "@define-color selected_bg_color #4b6983; \n"
2582         "@define-color selected_fg_color #fff; \n"
2583         "@define-color tooltip_bg_color #eee1b3; \n"
2584         "@define-color tooltip_fg_color #000; \n"
2585         "@define-color placeholder_text_color #808080; \n"
2586         "\n"
2587         "@define-color info_fg_color rgb (181, 171, 156);\n"
2588         "@define-color info_bg_color rgb (252, 252, 189);\n"
2589         "@define-color warning_fg_color rgb (173, 120, 41);\n"
2590         "@define-color warning_bg_color rgb (250, 173, 61);\n"
2591         "@define-color question_fg_color rgb (97, 122, 214);\n"
2592         "@define-color question_bg_color rgb (138, 173, 212);\n"
2593         "@define-color error_fg_color rgb (166, 38, 38);\n"
2594         "@define-color error_bg_color rgb (237, 54, 54);\n"
2595         "\n"
2596         "* {\n"
2597         "  background-color: @bg_color;\n"
2598         "  color: @fg_color;\n"
2599         "  border-color: shade (@bg_color, 0.6);\n"
2600         "  padding: 2;\n"
2601         "  border-width: 0;\n"
2602         "}\n"
2603         "\n"
2604         "*:prelight {\n"
2605         "  background-color: shade (@bg_color, 1.05);\n"
2606         "  color: shade (@fg_color, 1.3);\n"
2607         "}\n"
2608         "\n"
2609         "*:selected {\n"
2610         "  background-color: @selected_bg_color;\n"
2611         "  color: @selected_fg_color;\n"
2612         "}\n"
2613         "\n"
2614         ".expander, GtkTreeView.view.expander {\n"
2615         "  color: #fff;\n"
2616         "}\n"
2617         "\n"
2618         ".expander:prelight,\n"
2619         "GtkTreeView.view.expander:selected:prelight {\n"
2620         "  color: @text_color;\n"
2621         "}\n"
2622         "\n"
2623         ".expander:active {\n"
2624         "  transition: 200ms linear;\n"
2625         "}\n"
2626         "\n"
2627         "*:insensitive {\n"
2628         "  border-color: shade (@bg_color, 0.7);\n"
2629         "  background-color: shade (@bg_color, 0.9);\n"
2630         "  color: shade (@bg_color, 0.7);\n"
2631         "}\n"
2632         "\n"
2633         ".view {\n"
2634         "  border-width: 0;\n"
2635         "  border-radius: 0;\n"
2636         "  background-color: @base_color;\n"
2637         "  color: @text_color;\n"
2638         "}\n"
2639         ".view:selected {\n"
2640         "  background-color: shade (@bg_color, 0.9);\n"
2641         "  color: @fg_color;\n"
2642         "}\n"
2643         "\n"
2644         ".view:selected:focused {\n"
2645         "  background-color: @selected_bg_color;\n"
2646         "  color: @selected_fg_color;\n"
2647         "}\n"
2648         "\n"
2649         ".view column:sorted row,\n"
2650         ".view column:sorted row:prelight {\n"
2651         "  background-color: shade (@bg_color, 0.85);\n"
2652         "}\n"
2653         "\n"
2654         ".view column:sorted row:nth-child(odd),\n"
2655         ".view column:sorted row:nth-child(odd):prelight {\n"
2656         "  background-color: shade (@bg_color, 0.8);\n"
2657         "}\n"
2658         "\n"
2659         ".view row,\n"
2660         ".view row:prelight {\n"
2661         "  background-color: @base_color;\n"
2662         "  color: @text_color;\n"
2663         "}\n"
2664         "\n"
2665         ".view row:nth-child(odd),\n"
2666         ".view row:nth-child(odd):prelight {\n"
2667         "  background-color: shade (@base_color, 0.93); \n"
2668         "}\n"
2669         "\n"
2670         ".view row:selected:focused {\n"
2671         "  background-color: @selected_bg_color;\n"
2672         "}\n"
2673         "\n"
2674         ".view row:selected {\n"
2675         "  background-color: darker (@bg_color);\n"
2676         "  color: @selected_fg_color;\n"
2677         "}\n"
2678         "\n"
2679         ".view.cell.trough,\n"
2680         ".view.cell.trough:hover,\n"
2681         ".view.cell.trough:selected,\n"
2682         ".view.cell.trough:selected:focused {\n"
2683         "  background-color: @bg_color;\n"
2684         "  color: @fg_color;\n"
2685         "}\n"
2686         "\n"
2687         ".view.cell.progressbar,\n"
2688         ".view.cell.progressbar:hover,\n"
2689         ".view.cell.progressbar:selected,\n"
2690         ".view.cell.progressbar:selected:focused {\n"
2691         "  background-color: @selected_bg_color;\n"
2692         "  color: @selected_fg_color;\n"
2693         "}\n"
2694         "\n"
2695         ".rubberband {\n"
2696         "  background-color: alpha (@fg_color, 0.25);\n"
2697         "  border-color: @fg_color;\n"
2698         "  border-style: solid;\n"
2699         "  border-width: 1;\n"
2700         "}\n"
2701         "\n"
2702         ".tooltip,\n"
2703         ".tooltip * {\n"
2704         "  background-color: @tooltip_bg_color; \n"
2705         "  color: @tooltip_fg_color; \n"
2706         "  border-color: @tooltip_fg_color; \n"
2707         "  border-width: 1;\n"
2708         "  border-style: solid;\n"
2709         "}\n"
2710         "\n"
2711         ".button,\n"
2712         ".slider {\n"
2713         "  border-style: outset; \n"
2714         "  border-width: 2; \n"
2715         "}\n"
2716         "\n"
2717         ".button:active {\n"
2718         "  background-color: shade (@bg_color, 0.7);\n"
2719         "  border-style: inset; \n"
2720         "}\n"
2721         "\n"
2722         ".button:prelight,\n"
2723         ".slider:prelight {\n"
2724         "  background-color: @selected_bg_color;\n"
2725         "  color: @selected_fg_color;\n"
2726         "  border-color: shade (@selected_bg_color, 0.7);\n"
2727         "}\n"
2728         "\n"
2729         ".trough {\n"
2730         "  background-color: darker (@bg_color);\n"
2731         "  border-style: inset;\n"
2732         "  border-width: 1;\n"
2733         "  padding: 0;\n"
2734         "}\n"
2735         "\n"
2736         ".entry {\n"
2737         "  border-style: inset;\n"
2738         "  border-width: 2;\n"
2739         "  background-color: @base_color;\n"
2740         "  color: @text_color;\n"
2741         "}\n"
2742         "\n"
2743         ".entry:insensitive {\n"
2744         "  background-color: shade (@base_color, 0.9);\n"
2745         "  color: shade (@base_color, 0.7);\n"
2746         "}\n"
2747         ".entry:active {\n"
2748         "  background-color: #c4c2bd;\n"
2749         "  color: #000;\n"
2750         "}\n"
2751         "\n"
2752         ".progressbar,\n"
2753         ".entry.progressbar, \n"
2754         ".cell.progressbar {\n"
2755         "  background-color: @selected_bg_color;\n"
2756         "  border-color: shade (@selected_bg_color, 0.7);\n"
2757         "  color: @selected_fg_color;\n"
2758         "  border-style: outset;\n"
2759         "  border-width: 1;\n"
2760         "}\n"
2761         "\n"
2762         "GtkCheckButton:hover,\n"
2763         "GtkCheckButton:selected,\n"
2764         "GtkRadioButton:hover,\n"
2765         "GtkRadioButton:selected {\n"
2766         "  background-color: shade (@bg_color, 1.05);\n"
2767         "}\n"
2768         "\n"
2769         ".check, .radio,"
2770         ".cell.check, .cell.radio,\n"
2771         ".cell.check:hover, .cell.radio:hover {\n"
2772         "  border-style: solid;\n"
2773         "  border-width: 1;\n"
2774         "  background-color: @base_color;\n"
2775         "  border-color: @fg_color;\n"
2776         "}\n"
2777         "\n"
2778         ".check:active, .radio:active,\n"
2779         ".check:hover, .radio:hover {\n"
2780         "  background-color: @base_color;\n"
2781         "  border-color: @fg_color;\n"
2782         "  color: @text_color;\n"
2783         "}\n"
2784         "\n"
2785         ".check:selected, .radio:selected {\n"
2786         "  background-color: darker (@bg_color);\n"
2787         "  color: @selected_fg_color;\n"
2788         "  border-color: @selected_fg_color;\n"
2789         "}\n"
2790         "\n"
2791         ".check:selected:focused, .radio:selected:focused {\n"
2792         "  background-color: @selected_bg_color;\n"
2793         "}\n"
2794         "\n"
2795         ".menuitem.check, .menuitem.radio {\n"
2796         "  color: @fg_color;\n"
2797         "  border-style: none;\n"
2798         "  border-width: 0;\n"
2799         "}\n"
2800         "\n"
2801         ".popup {\n"
2802         "  border-style: outset;\n"
2803         "  border-width: 1;\n"
2804         "}\n"
2805         "\n"
2806         ".viewport {\n"
2807         "  border-style: inset;\n"
2808         "  border-width: 2;\n"
2809         "}\n"
2810         "\n"
2811         ".notebook {\n"
2812         "  border-style: outset;\n"
2813         "  border-width: 1;\n"
2814         "}\n"
2815         "\n"
2816         ".frame {\n"
2817         "  border-style: inset;\n"
2818         "  border-width: 1;\n"
2819         "}\n"
2820         "\n"
2821         "GtkScrolledWindow.frame {\n"
2822         "  padding: 0;\n"
2823         "}\n"
2824         "\n"
2825         ".menu,\n"
2826         ".menubar,\n"
2827         ".toolbar {\n"
2828         "  border-style: outset;\n"
2829         "  border-width: 1;\n"
2830         "}\n"
2831         "\n"
2832         ".menu:hover,\n"
2833         ".menubar:hover,\n"
2834         ".menuitem:hover,\n"
2835         ".menuitem.check:hover,\n"
2836         ".menuitem.radio:hover {\n"
2837         "  background-color: @selected_bg_color;\n"
2838         "  color: @selected_fg_color;\n"
2839         "}\n"
2840         "\n"
2841         "GtkSpinButton.button {\n"
2842         "  border-width: 1;\n"
2843         "}\n"
2844         "\n"
2845         ".scale.slider:hover,\n"
2846         "GtkSpinButton.button:hover {\n"
2847         "  background-color: shade (@bg_color, 1.05);\n"
2848         "  border-color: shade (@bg_color, 0.8);\n"
2849         "}\n"
2850         "\n"
2851         "GtkSwitch.trough:active {\n"
2852         "  background-color: @selected_bg_color;\n"
2853         "  color: @selected_fg_color;\n"
2854         "}\n"
2855         "\n"
2856         "GtkToggleButton.button:inconsistent {\n"
2857         "  border-style: outset;\n"
2858         "  border-width: 1px;\n"
2859         "  background-color: shade (@bg_color, 0.9);\n"
2860         "  border-color: shade (@bg_color, 0.7);\n"
2861         "}\n"
2862         "\n"
2863         "GtkLabel:selected {\n"
2864         "  background-color: shade (@bg_color, 0.9);\n"
2865         "}\n"
2866         "\n"
2867         "GtkLabel:selected:focused {\n"
2868         "  background-color: @selected_bg_color;\n"
2869         "}\n"
2870         "\n"
2871         ".spinner:active {\n"
2872         "  transition: 750ms linear loop;\n"
2873         "}\n"
2874         "\n"
2875         ".info {\n"
2876         "  background-color: @info_bg_color;\n"
2877         "  color: @info_fg_color;\n"
2878         "}\n"
2879         "\n"
2880         ".warning {\n"
2881         "  background-color: @warning_bg_color;\n"
2882         "  color: @warning_fg_color;\n"
2883         "}\n"
2884         "\n"
2885         ".question {\n"
2886         "  background-color: @question_bg_color;\n"
2887         "  color: @question_fg_color;\n"
2888         "}\n"
2889         "\n"
2890         ".error {\n"
2891         "  background-color: @error_bg_color;\n"
2892         "  color: @error_fg_color;\n"
2893         "}\n"
2894         "\n"
2895         ".highlight {\n"
2896         "  background-color: @selected_bg_color;\n"
2897         "  color: @selected_fg_color;\n"
2898         "}\n"
2899         "\n"
2900         ".light-area-focus {\n"
2901         "  color: #000;\n"
2902         "}\n"
2903         "\n"
2904         ".dark-area-focus {\n"
2905         "  color: #fff;\n"
2906         "}\n"
2907         "GtkCalendar.view {\n"
2908         "  border-width: 1;\n"
2909         "  border-style: inset;\n"
2910         "  padding: 1;\n"
2911         "}\n"
2912         "\n"
2913         "GtkCalendar.view:inconsistent {\n"
2914         "  color: darker (@bg_color);\n"
2915         "}\n"
2916         "\n"
2917         "GtkCalendar.header {\n"
2918         "  background-color: @bg_color;\n"
2919         "  border-style: outset;\n"
2920         "  border-width: 2;\n"
2921         "}\n"
2922         "\n"
2923         "GtkCalendar.highlight {\n"
2924         "  border-width: 0;\n"
2925         "}\n"
2926         "\n"
2927         "GtkCalendar.button {\n"
2928         "  background-color: @bg_color;\n"
2929         "}\n"
2930         "\n"
2931         "GtkCalendar.button:hover {\n"
2932         "  background-color: lighter (@bg_color);\n"
2933         "  color: @fg_color;\n"
2934         "}\n"
2935         "\n"
2936         ".menu * {\n"
2937         "  border-width: 0;\n"
2938         "  padding: 2;\n"
2939         "}\n"
2940         "\n";
2941
2942       provider = gtk_css_provider_new ();
2943       if (!gtk_css_provider_load_from_data (provider, str, -1, NULL))
2944         {
2945           g_error ("Failed to load the internal default CSS.");
2946         }
2947     }
2948
2949   return provider;
2950 }
2951
2952 gchar *
2953 _gtk_css_provider_get_theme_dir (void)
2954 {
2955   const gchar *var;
2956   gchar *path;
2957
2958   var = g_getenv ("GTK_DATA_PREFIX");
2959
2960   if (var)
2961     path = g_build_filename (var, "share", "themes", NULL);
2962   else
2963     path = g_build_filename (GTK_DATA_PREFIX, "share", "themes", NULL);
2964
2965   return path;
2966 }
2967
2968 /**
2969  * gtk_css_provider_get_named:
2970  * @name: A theme name
2971  * @variant: (allow-none): variant to load, for example, "dark", or
2972  *     %NULL for the default
2973  *
2974  * Loads a theme from the usual theme paths
2975  *
2976  * Returns: (transfer none): a #GtkCssProvider with the theme loaded.
2977  *     This memory is owned by GTK+, and you must not free it.
2978  */
2979 GtkCssProvider *
2980 gtk_css_provider_get_named (const gchar *name,
2981                             const gchar *variant)
2982 {
2983   static GHashTable *themes = NULL;
2984   GtkCssProvider *provider;
2985   gchar *key;
2986
2987   if (G_UNLIKELY (!themes))
2988     themes = g_hash_table_new (g_str_hash, g_str_equal);
2989
2990   if (variant == NULL)
2991     key = (gchar *)name;
2992   else
2993     key = g_strconcat (name, "-", variant, NULL);
2994
2995   provider = g_hash_table_lookup (themes, key);
2996
2997   if (!provider)
2998     {
2999       const gchar *home_dir;
3000       gchar *subpath, *path = NULL;
3001
3002       if (variant)
3003         subpath = g_strdup_printf ("gtk-3.0" G_DIR_SEPARATOR_S "gtk-%s.css", variant);
3004       else
3005         subpath = g_strdup ("gtk-3.0" G_DIR_SEPARATOR_S "gtk.css");
3006
3007       /* First look in the users home directory
3008        */
3009       home_dir = g_get_home_dir ();
3010       if (home_dir)
3011         {
3012           path = g_build_filename (home_dir, ".themes", name, subpath, NULL);
3013
3014           if (!g_file_test (path, G_FILE_TEST_EXISTS))
3015             {
3016               g_free (path);
3017               path = NULL;
3018             }
3019         }
3020
3021       if (!path)
3022         {
3023           gchar *theme_dir;
3024
3025           theme_dir = _gtk_css_provider_get_theme_dir ();
3026           path = g_build_filename (theme_dir, name, subpath, NULL);
3027           g_free (theme_dir);
3028
3029           if (!g_file_test (path, G_FILE_TEST_EXISTS))
3030             {
3031               g_free (path);
3032               path = NULL;
3033             }
3034         }
3035
3036       g_free (subpath);
3037
3038       if (path)
3039         {
3040           provider = gtk_css_provider_new ();
3041
3042           if (!gtk_css_provider_load_from_path (provider, path, NULL))
3043             {
3044               g_object_unref (provider);
3045               provider = NULL;
3046             }
3047           else
3048             g_hash_table_insert (themes, g_strdup (key), provider);
3049
3050           g_free (path);
3051         }
3052     }
3053
3054   if (key != name)
3055     g_free (key);
3056
3057   return provider;
3058 }
3059
3060 static int
3061 compare_properties (gconstpointer a, gconstpointer b)
3062 {
3063   return strcmp (((const GtkStyleProperty *) a)->pspec->name,
3064                  ((const GtkStyleProperty *) b)->pspec->name);
3065 }
3066
3067 static void
3068 gtk_css_ruleset_print (const GtkCssRuleset *ruleset,
3069                        GString             *str)
3070 {
3071   GList *keys, *walk;
3072
3073   _gtk_css_selector_print (ruleset->selector, str);
3074
3075   g_string_append (str, " {\n");
3076
3077   if (ruleset->style)
3078     {
3079       keys = g_hash_table_get_keys (ruleset->style);
3080       /* so the output is identical for identical selector styles */
3081       keys = g_list_sort (keys, compare_properties);
3082
3083       for (walk = keys; walk; walk = walk->next)
3084         {
3085           GtkStyleProperty *prop = walk->data;
3086           const GValue *value = g_hash_table_lookup (ruleset->style, prop);
3087
3088           g_string_append (str, "  ");
3089           g_string_append (str, prop->pspec->name);
3090           g_string_append (str, ": ");
3091           _gtk_style_property_print_value (prop, value, str);
3092           g_string_append (str, ";\n");
3093         }
3094
3095       g_list_free (keys);
3096     }
3097
3098   if (ruleset->widget_style)
3099     {
3100       keys = g_hash_table_get_keys (ruleset->widget_style);
3101       /* so the output is identical for identical selector styles */
3102       keys = g_list_sort (keys, (GCompareFunc) strcmp);
3103
3104       for (walk = keys; walk; walk = walk->next)
3105         {
3106           const char *name = walk->data;
3107           const GValue *value = g_hash_table_lookup (ruleset->widget_style, (gpointer) name);
3108
3109           g_string_append (str, "  ");
3110           g_string_append (str, name);
3111           g_string_append (str, ": ");
3112           g_string_append (str, g_value_get_string (value));
3113           g_string_append (str, ";\n");
3114         }
3115
3116       g_list_free (keys);
3117     }
3118
3119   g_string_append (str, "}\n");
3120 }
3121
3122 static void
3123 gtk_css_provider_print_colors (GHashTable *colors,
3124                                GString    *str)
3125 {
3126   GList *keys, *walk;
3127   char *s;
3128
3129   keys = g_hash_table_get_keys (colors);
3130   /* so the output is identical for identical styles */
3131   keys = g_list_sort (keys, (GCompareFunc) strcmp);
3132
3133   for (walk = keys; walk; walk = walk->next)
3134     {
3135       const char *name = walk->data;
3136       GtkSymbolicColor *symbolic = g_hash_table_lookup (colors, (gpointer) name);
3137
3138       g_string_append (str, "@define-color ");
3139       g_string_append (str, name);
3140       g_string_append (str, " ");
3141       s = gtk_symbolic_color_to_string (symbolic);
3142       g_string_append (str, s);
3143       g_free (s);
3144       g_string_append (str, ";\n");
3145     }
3146
3147   g_list_free (keys);
3148 }
3149
3150 /**
3151  * gtk_css_provider_to_string:
3152  * @provider: the provider to write to a string
3153  *
3154  * Convertes the @provider into a string representation in CSS
3155  * format.
3156  * 
3157  * Using gtk_css_provider_load_from_data() with the return value
3158  * from this function on a new provider created with
3159  * gtk_css_provider_new() will basicallu create a duplicate of
3160  * this @provider.
3161  *
3162  * Returns: a new string representing the @provider.
3163  **/
3164 char *
3165 gtk_css_provider_to_string (GtkCssProvider *provider)
3166 {
3167   GtkCssProviderPrivate *priv;
3168   GString *str;
3169   guint i;
3170
3171   g_return_val_if_fail (GTK_IS_CSS_PROVIDER (provider), NULL);
3172
3173   priv = provider->priv;
3174
3175   str = g_string_new ("");
3176
3177   gtk_css_provider_print_colors (priv->symbolic_colors, str);
3178
3179   for (i = 0; i < priv->rulesets->len; i++)
3180     {
3181       if (i > 0)
3182         g_string_append (str, "\n");
3183       gtk_css_ruleset_print (&g_array_index (priv->rulesets, GtkCssRuleset, i), str);
3184     }
3185
3186   return g_string_free (str, FALSE);
3187 }
3188