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