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