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