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