1 /* GTK - The GIMP Toolkit
2 * Copyright (C) 2010 Carlos Garnacho <carlosg@gnome.org>
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.
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.
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.
25 #include <gtkstyleprovider.h>
26 #include <gdk-pixbuf/gdk-pixbuf.h>
27 #include <cairo-gobject.h>
29 #include "gtkanimationdescription.h"
30 #include "gtk9slice.h"
31 #include "gtkcssprovider.h"
34 * SECTION:gtkcssprovider
35 * @Short_description: CSS-like styling for widgets
36 * @Title: GtkCssProvider
37 * @See_also: #GtkStyleContext, #GtkStyleProvider
39 * GtkCssProvider is an object implementing the #GtkStyleProvider interface.
40 * It is able to parse <ulink url="http://www.w3.org/TR/CSS2">CSS</ulink>-like
41 * input in order to style widgets.
43 * <refsect2 id="gtkcssprovider-files">
44 * <title>Default files</title>
46 * An application can cause GTK+ to parse a specific CSS style sheet by
47 * calling gtk_css_provider_load_from_file() and adding the provider with
48 * gtk_style_context_add_provider() or gtk_style_context_add_provider_for_screen().
49 * In addition, certain files will be read when GTK+ is initialized. First,
50 * the file <filename><replaceable>XDG_CONFIG_HOME</replaceable>/gtk-3.0/gtk.css</filename>
51 * is loaded if it exists. Then, GTK+ tries to load
52 * <filename><replaceable>HOME</replaceable>/.themes/<replaceable>theme-name</replaceable>/gtk-3.0/gtk.css</filename>,
54 * <filename><replaceable>GTK_DATA_PREFIX</replaceable>/share/themes/<replaceable>theme-name</replaceable>/gtk-3.0/gtk.css</filename>,
55 * where <replaceable>theme-name</replaceable> is the name of the current theme
56 * (see the #GtkSettings:gtk-theme-name setting) and <replaceable>GTK_DATA_PREFIX</replaceable>
57 * is the prefix configured when GTK+ was compiled, unless overridden by the
58 * <envar>GTK_DATA_PREFIX</envar> environment variable.
61 * <refsect2 id="gtkcssprovider-stylesheets">
62 * <title>Style sheets</title>
64 * The basic structure of the style sheets understood by this provider is
65 * a series of statements, which are either rule sets or '@-rules', separated
69 * A rule set consists of a selector and a declaration block, which is
70 * a series of declarations enclosed in curly braces ({ and }). The
71 * declarations are separated by semicolons (;). Multiple selectors can
72 * share the same declaration block, by putting all the separators in
73 * front of the block, separated by commas.
75 * <example><title>A rule set with two selectors</title>
76 * <programlisting language="text">
77 * GtkButton, GtkEntry {
84 * <refsect2 id="gtkcssprovider-selectors">
85 * <title>Selectors</title>
87 * Selectors work very similar to the way they do in CSS, with widget class
88 * names taking the role of element names, and widget names taking the role
89 * of IDs. When used in a selector, widget names must be prefixed with a
90 * '#' character. The '*' character represents the so-called universal
91 * selector, which matches any widget.
94 * To express more complicated situations, selectors can be combined in
97 * <listitem><para>To require that a widget satisfies several conditions,
98 * combine several selectors into one by concatenating them. E.g.
99 * <literal>GtkButton#button1</literal> matches a GtkButton widget
100 * with the name button1.</para></listitem>
101 * <listitem><para>To only match a widget when it occurs inside some other
102 * widget, write the two selectors after each other, separated by whitespace.
103 * E.g. <literal>GtkToolBar GtkButton</literal> matches GtkButton widgets
104 * that occur inside a GtkToolBar.</para></listitem>
105 * <listitem><para>In the previous example, the GtkButton is matched even
106 * if it occurs deeply nested inside the toolbar. To restrict the match
107 * to direct children of the parent widget, insert a '>' character between
108 * the two selectors. E.g. <literal>GtkNotebook > GtkLabel</literal> matches
109 * GtkLabel widgets that are direct children of a GtkNotebook.</para></listitem>
113 * <title>Widget classes and names in selectors</title>
114 * <programlisting language="text">
115 * /* Theme labels that are descendants of a window */
116 * GtkWindow GtkLabel {
117 * background-color: #898989
120 * /* Theme notebooks, and anything that's within these */
122 * background-color: #a939f0
125 * /* Theme combo boxes, and entries that
126 * are direct children of a notebook */
128 * GtkNotebook > GtkEntry {
130 * background-color: #1209a2
133 * /* Theme any widget within a GtkBin */
138 * /* Theme a label named title-label */
139 * GtkLabel#title-label {
143 * /* Theme any widget named main-entry */
145 * background-color: #f0a810
150 * Widgets may also define style classes, which can be used for matching.
151 * When used in a selector, style classes must be prefixed with a '.'
155 * Refer to the documentation of individual widgets to learn which
156 * style classes they define and see <xref linkend="gtkstylecontext-classes"/>
157 * for a list of all style classes used by GTK+ widgets.
160 * <title>Style classes in selectors</title>
161 * <programlisting language="text">
162 * /* Theme all widgets defining the class entry */
164 * color: #39f1f9;
167 * /* Theme spinbuttons' entry */
168 * GtkSpinButton.entry {
174 * In complicated widgets like e.g. a GtkNotebook, it may be desirable
175 * to style different parts of the widget differently. To make this
176 * possible, container widgets may define regions, whose names
177 * may be used for matching in selectors.
180 * Some containers allow to further differentiate between regions by
181 * applying so-called pseudo-classes to the region. For example, the
182 * tab region in GtkNotebook allows to single out the first or last
183 * tab by using the :first-child or :last-child pseudo-class.
184 * When used in selectors, pseudo-classes must be prefixed with a
188 * Refer to the documentation of individual widgets to learn which
189 * regions and pseudo-classes they define and see
190 * <xref linkend="gtkstylecontext-classes"/> for a list of all regions
191 * used by GTK+ widgets.
194 * <title>Regions in selectors</title>
195 * <programlisting language="text">
196 * /* Theme any label within a notebook */
197 * GtkNotebook GtkLabel {
198 * color: #f90192;
201 * /* Theme labels within notebook tabs */
202 * GtkNotebook tab GtkLabel {
203 * color: #703910;
206 * /* Theme labels in the any first notebook
207 * tab, both selectors are equivalent */
208 * GtkNotebook tab:nth-child(first) GtkLabel,
209 * GtkNotebook tab:first-child GtkLabel {
210 * color: #89d012;
215 * Another use of pseudo-classes is to match widgets depending on their
216 * state. This is conceptually similar to the :hover, :active or :focus
217 * pseudo-classes in CSS. The available pseudo-classes for widget states
218 * are :active, :prelight (or :hover), :insensitive, :selected, :focused
222 * <title>Styling specific widget states</title>
223 * <programlisting language="text">
224 * /* Theme active (pressed) buttons */
226 * background-color: #0274d9;
229 * /* Theme buttons with the mouse pointer on it,
230 * both are equivalent */
232 * GtkButton:prelight {
233 * background-color: #3085a9;
236 * /* Theme insensitive widgets, both are equivalent */
239 * background-color: #320a91;
242 * /* Theme selection colors in entries */
243 * GtkEntry:selected {
244 * background-color: #56f9a0;
247 * /* Theme focused labels */
249 * background-color: #b4940f;
252 * /* Theme inconsistent checkbuttons */
253 * GtkCheckButton:inconsistent {
254 * background-color: #20395a;
259 * Widget state pseudoclasses may only apply to the last element
263 * To determine the effective style for a widget, all the matching rule
264 * sets are merged. As in CSS, rules apply by specificity, so the rules
265 * whose selectors more closely match a widget path will take precedence
269 * <refsect2 id="gtkcssprovider-rules">
270 * <title>@ Rules</title>
272 * GTK+'s CSS supports the @import rule, in order to load another
273 * CSS style sheet in addition to the currently parsed one.
276 * <title>Using the @import rule</title>
277 * <programlisting language="text">
278 * @import url ("path/to/common.css");
282 * GTK+ also supports an additional @define-color rule, in order
283 * to define a color name which may be used instead of color numeric
284 * representations. Also see the #GtkSettings:gtk-color-scheme setting
285 * for a way to override the values of these named colors.
288 * <title>Defining colors</title>
289 * <programlisting language="text">
290 * @define-color bg_color #f9a039;
293 * background-color: @bg_color;
298 * <refsect2 id="gtkcssprovider-symbolic-colors">
299 * <title>Symbolic colors</title>
301 * Besides being able to define color names, the CSS parser is also able
302 * to read different color expressions, which can also be nested, providing
303 * a rich language to define colors which are derived from a set of base
307 * <title>Using symbolic colors</title>
308 * <programlisting language="text">
309 * @define-color entry-color shade (@bg_color, 0.7);
312 * background-color: @entry-color;
316 * background-color: mix (@entry-color,
317 * shade (#fff, 0.5),
323 * The various ways to express colors in GTK+ CSS are:
329 * <entry>Syntax</entry>
330 * <entry>Explanation</entry>
331 * <entry>Examples</entry>
336 * <entry>rgb(@r, @g, @b)</entry>
337 * <entry>An opaque color; @r, @g, @b can be either integers between
338 * 0 and 255 or percentages</entry>
339 * <entry><literallayout>rgb(128, 10, 54)
340 * rgb(20%, 30%, 0%)</literallayout></entry>
343 * <entry>rgba(@r, @g, @b, @a)</entry>
344 * <entry>A translucent color; @r, @g, @b are as in the previous row,
345 * @a is a floating point number between 0 and 1</entry>
346 * <entry><literallayout>rgba(255, 255, 0, 0.5)</literallayout></entry>
349 * <entry>#@xxyyzz</entry>
350 * <entry>An opaque color; @xx, @yy, @zz are hexadecimal numbers
351 * specifying @r, @g, @b variants with between 1 and 4
352 * hexadecimal digits per component are allowed</entry>
353 * <entry><literallayout>#ff12ab
354 * #f0c</literallayout></entry>
357 * <entry>@name</entry>
358 * <entry>Reference to a color that has been defined with
359 * @define-color
361 * <entry>@bg_color</entry>
364 * <entry>mix(@color1, @color2, @f)</entry>
365 * <entry>A linear combination of @color1 and @color2. @f is a
366 * floating point number between 0 and 1.</entry>
367 * <entry><literallayout>mix(#ff1e0a, @bg_color, 0.8)</literallayout></entry>
370 * <entry>shade(@color, @f)</entry>
371 * <entry>A lighter or darker variant of @color. @f is a
372 * floating point number.
374 * <entry>shade(@fg_color, 0.5)</entry>
377 * <entry>lighter(@color)</entry>
378 * <entry>A lighter variant of @color</entry>
381 * <entry>darker(@color)</entry>
382 * <entry>A darker variant of @color</entry>
388 * <refsect2 id="gtkcssprovider-gradients">
389 * <title>Gradients</title>
391 * Linear or radial Gradients can be used as background images.
394 * A linear gradient along the line from (@start_x, @start_y) to
395 * (@end_x, @end_y) is specified using the syntax
396 * <literallayout>-gtk-gradient (linear,
397 * @start_x @start_y, @end_x @end_y,
398 * color-stop (@position, @color),
399 * ...)</literallayout>
400 * where @start_x and @end_x can be either a floating point number between
401 * 0 and 1 or one of the special values 'left', 'right' or 'center', @start_y
402 * and @end_y can be either a floating point number between 0 and 1 or one
403 * of the special values 'top', 'bottom' or 'center', @position is a floating
404 * point number between 0 and 1 and @color is a color expression (see above).
405 * The color-stop can be repeated multiple times to add more than one color
406 * stop. 'from (@color)' and 'to (@color)' can be used as abbreviations for
407 * color stops with position 0 and 1, respectively.
410 * <title>A linear gradient</title>
411 * <inlinegraphic fileref="gradient1.png" format="PNG"/>
412 * <para>This gradient was specified with
413 * <literallayout>-gtk-gradient (linear,
414 * left top, right bottom,
415 * from(@yellow), to(@blue))</literallayout></para>
418 * <title>Another linear gradient</title>
419 * <inlinegraphic fileref="gradient2.png" format="PNG"/>
420 * <para>This gradient was specified with
421 * <literallayout>-gtk-gradient (linear,
423 * color-stop(0, @yellow),
424 * color-stop(0.2, @blue),
425 * color-stop(1, #0f0))</literallayout></para>
428 * A radial gradient along the two circles defined by (@start_x, @start_y,
429 * @start_radius) and (@end_x, @end_y, @end_radius) is specified using the
431 * <literallayout>-gtk-gradient (radial,
432 * @start_x @start_y, @start_radius,
433 * @end_x @end_y, @end_radius,
434 * color-stop (@position, @color),
435 * ...)</literallayout>
436 * where @start_radius and @end_radius are floating point numbers and
437 * the other parameters are as before.
440 * <title>A radial gradient</title>
441 * <inlinegraphic fileref="gradient3.png" format="PNG"/>
442 * <para>This gradient was specified with
443 * <literallayout>-gtk-gradient (radial,
446 * from(@yellow), to(@green))</literallayout></para>
449 * <title>Another radial gradient</title>
450 * <inlinegraphic fileref="gradient4.png" format="PNG"/>
451 * <para>This gradient was specified with
452 * <literallayout>-gtk-gradient (radial,
455 * color-stop (0, #f00),
456 * color-stop (0.1, #a0f),
457 * color-stop (0.2, @yellow),
458 * color-stop (1, @green))</literallayout></para>
461 * <refsect2 id="gtkcssprovider-slices">
462 * <title>Border images</title>
464 * Images can be used in 'slices' for the purpose of creating scalable
467 * <inlinegraphic fileref="slices.png" format="PNG"/>
469 * The syntax for specifying border images of this kind is:
470 * <literallayout>url(@path) @top @right @bottom @left [repeat|stretch]? [repeat|stretch]?</literallayout>
471 * The sizes of the 'cut off' portions are specified
472 * with the @top, @right, @bottom and @left parameters.
473 * The 'middle' sections can be repeated or stretched to create
474 * the desired effect, by adding the 'repeat' or 'stretch' options after
475 * the dimensions. If two options are specified, the first one affects
476 * the horizontal behaviour and the second one the vertical behaviour.
477 * If only one option is specified, it affects both.
480 * <title>A border image</title>
481 * <inlinegraphic fileref="border1.png" format="PNG"/>
482 * <para>This border image was specified with
483 * <literallayout>url("gradient1.png") 10 10 10 10</literallayout>
487 * <title>A repeating border image</title>
488 * <inlinegraphic fileref="border2.png" format="PNG"/>
489 * <para>This border image was specified with
490 * <literallayout>url("gradient1.png") 10 10 10 10 repeat</literallayout>
494 * <title>A stretched border image</title>
495 * <inlinegraphic fileref="border3.png" format="PNG"/>
496 * <para>This border image was specified with
497 * <literallayout>url("gradient1.png") 10 10 10 10 stretch</literallayout>
501 * <refsect2 id="gtkcssprovider-transitions">
502 * <para>Styles can specify transitions that will be used to create a gradual
503 * change in the appearance when a widget state changes. The following
504 * syntax is used to specify transitions:
505 * <literallayout>@duration [s|ms] [linear|ease|ease-in|ease-out|ease-in-out] [loop]?</literallayout>
506 * The @duration is the amount of time that the animation will take for
507 * a complete cycle from start to end. If the loop option is given, the
508 * animation will be repated until the state changes again.
509 * The option after the duration determines the transition function from a
510 * small set of predefined functions.
511 * <figure><title>Linear transition</title>
512 * <graphic fileref="linear.png" format="PNG"/>
514 * <figure><title>Ease transition</title>
515 * <graphic fileref="ease.png" format="PNG"/>
517 * <figure><title>Ease-in-out transition</title>
518 * <graphic fileref="ease-in-out.png" format="PNG"/>
520 * <figure><title>Ease-in transition</title>
521 * <graphic fileref="ease-in.png" format="PNG"/>
523 * <figure><title>Ease-out transition</title>
524 * <graphic fileref="ease-out.png" format="PNG"/>
528 * <refsect2 id="gtkcssprovider-properties">
529 * <title>Supported properties</title>
531 * Properties are the part that differ the most to common CSS,
532 * not all properties are supported (some are planned to be
533 * supported eventually, some others are meaningless or don't
534 * map intuitively in a widget based environment).
537 * There is also a difference in shorthand properties, for
538 * example in common CSS it is fine to define a font through
539 * the different @font-family, @font-style, @font-size
540 * properties, meanwhile in GTK+'s CSS only the canonical
541 * @font property is supported.
544 * The currently supported properties are:
550 * <entry>Property name</entry>
551 * <entry>Syntax</entry>
552 * <entry>Maps to</entry>
553 * <entry>Examples</entry>
558 * <entry>engine</entry>
559 * <entry>engine-name</entry>
560 * <entry>#GtkThemingEngine</entry>
561 * <entry>engine: clearlooks;</entry>
564 * <entry>background-color</entry>
565 * <entry morerows="2">color (see above)</entry>
566 * <entry morerows="2">#GdkRGBA</entry>
567 * <entry morerows="2"><literallayout>background-color: #fff;
568 * color: &color1;
569 * background-color: shade (&color1, 0.5);
570 * color: mix (&color1, #f0f, 0.8);</literallayout>
574 * <entry>color</entry>
577 * <entry>border-color</entry>
580 * <entry>font</entry>
581 * <entry>@family [@style] [@size]</entry>
582 * <entry>#PangoFontDescription</entry>
583 * <entry>font: Sans 15;</entry>
586 * <entry>margin</entry>
587 * <entry morerows="1"><literallayout>@width
588 * @vertical_width @horizontal_width
589 * @top_width @horizontal_width @bottom_width
590 * @top_width @right_width @bottom_width @left_width</literallayout>
592 * <entry morerows="1">#GtkBorder</entry>
593 * <entry morerows="1"><literallayout>margin: 5;
596 * margin: 5 10 3 5;</literallayout>
600 * <entry>padding</entry>
603 * <entry>background-image</entry>
604 * <entry><literallayout>gradient (see above) or
605 * url(@path)</literallayout></entry>
606 * <entry>#cairo_pattern_t</entry>
607 * <entry><literallayout>-gtk-gradient (linear,
608 * left top, right top,
609 * from (#fff), to (#000));
610 * -gtk-gradient (linear, 0.0 0.5, 0.5 1.0,
612 * color-stop (0.5, #f00),
614 * -gtk-gradient (radial,
615 * center center, 0.2,
616 * center center, 0.8,
617 * color-stop (0.0, #fff),
618 * color-stop (1.0, #000));
619 * url ('background.png');</literallayout>
623 * <entry>border-width</entry>
624 * <entry>integer</entry>
625 * <entry>#gint</entry>
626 * <entry>border-width: 5;</entry>
629 * <entry>border-radius</entry>
630 * <entry>integer</entry>
631 * <entry>#gint</entry>
632 * <entry>border-radius: 5;</entry>
635 * <entry>border-style</entry>
636 * <entry>[none|solid|inset|outset]</entry>
637 * <entry>#GtkBorderStyle</entry>
638 * <entry>border-style: solid;</entry>
641 * <entry>border-image</entry>
642 * <entry><literallayout>border image (see above)</literallayout></entry>
643 * <entry>internal use only</entry>
644 * <entry><literallayout>border-image: url("/path/to/image.png") 3 4 3 4 stretch;
645 * border-image: url("/path/to/image.png") 3 4 4 3 repeat stretch;</literallayout>
649 * <entry>transition</entry>
650 * <entry>transition (see above)</entry>
651 * <entry>internal use only</entry>
652 * <entry><literallayout>transition: 150ms ease-in-out;
653 * transition: 1s linear loop;</literallayout>
660 * GtkThemingEngines can register their own, engine-specific style properties
661 * with the function gtk_theming_engine_register_property(). These properties
662 * can be set in CSS like other properties, using a name of the form
663 * <literallayout>-<replaceable>namespace</replaceable>-<replaceable>name</replaceable></literallayout>, where <replaceable>namespace</replaceable> is typically
664 * the name of the theming engine, and <replaceable>name</replaceable> is the
665 * name of the property. Style properties that have been registered by widgets
666 * using gtk_widget_class_install_style_property() can also be set in this
667 * way, using the widget class name for <replaceable>namespace</replaceable>.
670 * <title>Using engine-specific style properties</title>
673 * engine: clearlooks;
675 * -GtkPaned-handle-size: 6;
676 * -clearlooks-colorize-scrollbar: false;
683 typedef struct GtkCssProviderPrivate GtkCssProviderPrivate;
684 typedef struct SelectorElement SelectorElement;
685 typedef struct SelectorPath SelectorPath;
686 typedef struct SelectorStyleInfo SelectorStyleInfo;
687 typedef enum SelectorElementType SelectorElementType;
688 typedef enum CombinatorType CombinatorType;
689 typedef enum ParserScope ParserScope;
690 typedef enum ParserSymbol ParserSymbol;
692 enum SelectorElementType {
701 enum CombinatorType {
702 COMBINATOR_DESCENDANT, /* No direct relation needed */
703 COMBINATOR_CHILD /* Direct child */
706 struct SelectorElement
708 SelectorElementType elem_type;
709 CombinatorType combinator;
719 GtkRegionFlags flags;
731 struct SelectorStyleInfo
737 struct GtkCssProviderPrivate
743 const gchar *value_pos;
745 GHashTable *symbolic_colors;
747 GPtrArray *selectors_info;
749 /* Current parser state */
751 GSList *cur_selectors;
752 GHashTable *cur_properties;
763 /* Extend GtkStateType, since these
764 * values are also used as symbols
767 /* Scope: pseudo-class */
768 SYMBOL_NTH_CHILD = GTK_STATE_FOCUSED + 1,
773 /* Scope: nth-child */
774 SYMBOL_NTH_CHILD_EVEN,
775 SYMBOL_NTH_CHILD_ODD,
776 SYMBOL_NTH_CHILD_FIRST,
777 SYMBOL_NTH_CHILD_LAST
780 static void gtk_css_provider_finalize (GObject *object);
781 static void gtk_css_style_provider_iface_init (GtkStyleProviderIface *iface);
783 static void scanner_apply_scope (GScanner *scanner,
785 static gboolean css_provider_parse_value (GtkCssProvider *css_provider,
786 const gchar *value_str,
789 static gboolean gtk_css_provider_load_from_path_internal (GtkCssProvider *css_provider,
795 gtk_css_provider_error_quark (void)
797 return g_quark_from_static_string ("gtk-css-provider-error-quark");
800 G_DEFINE_TYPE_EXTENDED (GtkCssProvider, gtk_css_provider, G_TYPE_OBJECT, 0,
801 G_IMPLEMENT_INTERFACE (GTK_TYPE_STYLE_PROVIDER,
802 gtk_css_style_provider_iface_init));
805 gtk_css_provider_class_init (GtkCssProviderClass *klass)
807 GObjectClass *object_class = G_OBJECT_CLASS (klass);
809 object_class->finalize = gtk_css_provider_finalize;
811 g_type_class_add_private (object_class, sizeof (GtkCssProviderPrivate));
814 static SelectorPath *
815 selector_path_new (void)
819 path = g_slice_new0 (SelectorPath);
825 static SelectorPath *
826 selector_path_ref (SelectorPath *path)
833 selector_path_unref (SelectorPath *path)
837 if (path->ref_count > 0)
840 while (path->elements)
842 g_slice_free (SelectorElement, path->elements->data);
843 path->elements = g_slist_delete_link (path->elements, path->elements);
846 g_slice_free (SelectorPath, path);
850 selector_path_prepend_type (SelectorPath *path,
851 const gchar *type_name)
853 SelectorElement *elem;
856 elem = g_slice_new (SelectorElement);
857 elem->combinator = COMBINATOR_DESCENDANT;
858 type = g_type_from_name (type_name);
860 if (type == G_TYPE_INVALID)
862 elem->elem_type = SELECTOR_TYPE_NAME;
863 elem->name = g_quark_from_string (type_name);
867 elem->elem_type = SELECTOR_GTYPE;
871 path->elements = g_slist_prepend (path->elements, elem);
875 selector_path_prepend_glob (SelectorPath *path)
877 SelectorElement *elem;
879 elem = g_slice_new (SelectorElement);
880 elem->elem_type = SELECTOR_GLOB;
881 elem->combinator = COMBINATOR_DESCENDANT;
883 path->elements = g_slist_prepend (path->elements, elem);
887 selector_path_prepend_region (SelectorPath *path,
889 GtkRegionFlags flags)
891 SelectorElement *elem;
893 elem = g_slice_new (SelectorElement);
894 elem->combinator = COMBINATOR_DESCENDANT;
895 elem->elem_type = SELECTOR_REGION;
897 elem->region.name = g_quark_from_string (name);
898 elem->region.flags = flags;
900 path->elements = g_slist_prepend (path->elements, elem);
904 selector_path_prepend_name (SelectorPath *path,
907 SelectorElement *elem;
909 elem = g_slice_new (SelectorElement);
910 elem->combinator = COMBINATOR_DESCENDANT;
911 elem->elem_type = SELECTOR_NAME;
913 elem->name = g_quark_from_string (name);
915 path->elements = g_slist_prepend (path->elements, elem);
919 selector_path_prepend_class (SelectorPath *path,
922 SelectorElement *elem;
924 elem = g_slice_new (SelectorElement);
925 elem->combinator = COMBINATOR_DESCENDANT;
926 elem->elem_type = SELECTOR_CLASS;
928 elem->name = g_quark_from_string (name);
930 path->elements = g_slist_prepend (path->elements, elem);
934 selector_path_prepend_combinator (SelectorPath *path,
935 CombinatorType combinator)
937 SelectorElement *elem;
939 g_assert (path->elements != NULL);
941 /* It is actually stored in the last element */
942 elem = path->elements->data;
943 elem->combinator = combinator;
947 selector_path_depth (SelectorPath *path)
949 return g_slist_length (path->elements);
952 static SelectorStyleInfo *
953 selector_style_info_new (SelectorPath *path)
955 SelectorStyleInfo *info;
957 info = g_slice_new0 (SelectorStyleInfo);
958 info->path = selector_path_ref (path);
964 selector_style_info_free (SelectorStyleInfo *info)
967 g_hash_table_unref (info->style);
970 selector_path_unref (info->path);
974 selector_style_info_set_style (SelectorStyleInfo *info,
978 g_hash_table_unref (info->style);
981 info->style = g_hash_table_ref (style);
987 create_scanner (void)
991 scanner = g_scanner_new (NULL);
993 g_scanner_scope_add_symbol (scanner, SCOPE_PSEUDO_CLASS, "active", GUINT_TO_POINTER (GTK_STATE_ACTIVE));
994 g_scanner_scope_add_symbol (scanner, SCOPE_PSEUDO_CLASS, "prelight", GUINT_TO_POINTER (GTK_STATE_PRELIGHT));
995 g_scanner_scope_add_symbol (scanner, SCOPE_PSEUDO_CLASS, "hover", GUINT_TO_POINTER (GTK_STATE_PRELIGHT));
996 g_scanner_scope_add_symbol (scanner, SCOPE_PSEUDO_CLASS, "selected", GUINT_TO_POINTER (GTK_STATE_SELECTED));
997 g_scanner_scope_add_symbol (scanner, SCOPE_PSEUDO_CLASS, "insensitive", GUINT_TO_POINTER (GTK_STATE_INSENSITIVE));
998 g_scanner_scope_add_symbol (scanner, SCOPE_PSEUDO_CLASS, "inconsistent", GUINT_TO_POINTER (GTK_STATE_INCONSISTENT));
999 g_scanner_scope_add_symbol (scanner, SCOPE_PSEUDO_CLASS, "focused", GUINT_TO_POINTER (GTK_STATE_FOCUSED));
1000 g_scanner_scope_add_symbol (scanner, SCOPE_PSEUDO_CLASS, "focus", GUINT_TO_POINTER (GTK_STATE_FOCUSED));
1002 g_scanner_scope_add_symbol (scanner, SCOPE_PSEUDO_CLASS, "nth-child", GUINT_TO_POINTER (SYMBOL_NTH_CHILD));
1003 g_scanner_scope_add_symbol (scanner, SCOPE_PSEUDO_CLASS, "first-child", GUINT_TO_POINTER (SYMBOL_FIRST_CHILD));
1004 g_scanner_scope_add_symbol (scanner, SCOPE_PSEUDO_CLASS, "last-child", GUINT_TO_POINTER (SYMBOL_LAST_CHILD));
1005 g_scanner_scope_add_symbol (scanner, SCOPE_PSEUDO_CLASS, "sorted", GUINT_TO_POINTER (SYMBOL_SORTED_CHILD));
1007 g_scanner_scope_add_symbol (scanner, SCOPE_NTH_CHILD, "even", GUINT_TO_POINTER (SYMBOL_NTH_CHILD_EVEN));
1008 g_scanner_scope_add_symbol (scanner, SCOPE_NTH_CHILD, "odd", GUINT_TO_POINTER (SYMBOL_NTH_CHILD_ODD));
1009 g_scanner_scope_add_symbol (scanner, SCOPE_NTH_CHILD, "first", GUINT_TO_POINTER (SYMBOL_NTH_CHILD_FIRST));
1010 g_scanner_scope_add_symbol (scanner, SCOPE_NTH_CHILD, "last", GUINT_TO_POINTER (SYMBOL_NTH_CHILD_LAST));
1012 scanner_apply_scope (scanner, SCOPE_SELECTOR);
1018 gtk_css_provider_init (GtkCssProvider *css_provider)
1020 GtkCssProviderPrivate *priv;
1022 priv = css_provider->priv = G_TYPE_INSTANCE_GET_PRIVATE (css_provider,
1023 GTK_TYPE_CSS_PROVIDER,
1024 GtkCssProviderPrivate);
1026 priv->selectors_info = g_ptr_array_new_with_free_func ((GDestroyNotify) selector_style_info_free);
1027 priv->scanner = create_scanner ();
1029 priv->symbolic_colors = g_hash_table_new_full (g_str_hash, g_str_equal,
1030 (GDestroyNotify) g_free,
1031 (GDestroyNotify) gtk_symbolic_color_unref);
1034 typedef struct ComparePathData ComparePathData;
1036 struct ComparePathData
1044 compare_selector_element (GtkWidgetPath *path,
1046 SelectorElement *elem,
1051 if (elem->elem_type == SELECTOR_TYPE_NAME)
1053 const gchar *type_name;
1054 GType resolved_type;
1056 /* Resolve the type name */
1057 type_name = g_quark_to_string (elem->name);
1058 resolved_type = g_type_from_name (type_name);
1060 if (resolved_type == G_TYPE_INVALID)
1062 /* Type couldn't be resolved, so the selector
1063 * clearly doesn't affect the given widget path
1068 elem->elem_type = SELECTOR_GTYPE;
1069 elem->type = resolved_type;
1072 if (elem->elem_type == SELECTOR_GTYPE)
1076 type = gtk_widget_path_iter_get_object_type (path, index);
1078 if (!g_type_is_a (type, elem->type))
1081 if (type == elem->type)
1085 GType parent = type;
1089 while ((parent = g_type_parent (parent)) != G_TYPE_INVALID)
1091 if (parent == elem->type)
1098 g_warning ("Hierarchy is higher than expected.");
1106 else if (elem->elem_type == SELECTOR_REGION)
1108 GtkRegionFlags flags;
1110 if (!gtk_widget_path_iter_has_qregion (path, index,
1115 if (elem->region.flags != 0 &&
1116 (flags & elem->region.flags) == 0)
1122 else if (elem->elem_type == SELECTOR_GLOB)
1124 /* Treat as lowest matching type */
1128 else if (elem->elem_type == SELECTOR_NAME)
1130 if (!gtk_widget_path_iter_has_qname (path, index, elem->name))
1136 else if (elem->elem_type == SELECTOR_CLASS)
1138 if (!gtk_widget_path_iter_has_qclass (path, index, elem->name))
1149 compare_selector (GtkWidgetPath *path,
1150 SelectorPath *selector)
1152 GSList *elements = selector->elements;
1153 gboolean match = TRUE, first = TRUE, first_match = FALSE;
1157 i = gtk_widget_path_length (path) - 1;
1159 while (elements && match && i >= 0)
1161 SelectorElement *elem;
1164 elem = elements->data;
1166 match = compare_selector_element (path, i, elem, &elem_score);
1171 /* Only move on to the next index if there is no match
1172 * with the current element (whether to continue or not
1173 * handled right after in the combinator check), or a
1174 * GType or glob has just been matched.
1176 * Region and widget names do not trigger this because
1177 * the next element in the selector path could also be
1178 * related to the same index.
1181 (elem->elem_type == SELECTOR_GTYPE ||
1182 elem->elem_type == SELECTOR_GLOB))
1186 elem->elem_type != SELECTOR_TYPE_NAME &&
1187 elem->combinator == COMBINATOR_DESCENDANT)
1189 /* With descendant combinators there may
1190 * be intermediate chidren in the hierarchy
1195 elements = elements->next;
1199 /* Only 4 bits are actually used */
1201 score |= elem_score;
1207 /* If there are pending selector
1208 * elements to compare, it's not
1216 else if (first_match)
1218 /* Assign more weight to these selectors
1219 * that matched right from the first element.
1227 typedef struct StylePriorityInfo StylePriorityInfo;
1229 struct StylePriorityInfo
1233 GtkStateFlags state;
1237 css_provider_get_selectors (GtkCssProvider *css_provider,
1238 GtkWidgetPath *path)
1240 GtkCssProviderPrivate *priv;
1241 GArray *priority_info;
1244 priv = css_provider->priv;
1245 priority_info = g_array_new (FALSE, FALSE, sizeof (StylePriorityInfo));
1247 for (i = 0; i < priv->selectors_info->len; i++)
1249 SelectorStyleInfo *info;
1250 StylePriorityInfo new;
1251 gboolean added = FALSE;
1254 info = g_ptr_array_index (priv->selectors_info, i);
1255 score = compare_selector (path, info->path);
1261 new.style = info->style;
1262 new.state = info->path->state;
1264 for (j = 0; j < priority_info->len; j++)
1266 StylePriorityInfo *cur;
1268 cur = &g_array_index (priority_info, StylePriorityInfo, j);
1270 if (cur->score > new.score)
1272 g_array_insert_val (priority_info, j, new);
1279 g_array_append_val (priority_info, new);
1282 return priority_info;
1286 css_provider_dump_symbolic_colors (GtkCssProvider *css_provider,
1287 GtkStyleProperties *props)
1289 GtkCssProviderPrivate *priv;
1290 GHashTableIter iter;
1291 gpointer key, value;
1293 priv = css_provider->priv;
1294 g_hash_table_iter_init (&iter, priv->symbolic_colors);
1296 while (g_hash_table_iter_next (&iter, &key, &value))
1299 GtkSymbolicColor *color;
1304 gtk_style_properties_map_color (props, name, color);
1308 static GtkStyleProperties *
1309 gtk_css_provider_get_style (GtkStyleProvider *provider,
1310 GtkWidgetPath *path)
1312 GtkCssProvider *css_provider;
1313 GtkCssProviderPrivate *priv;
1314 GtkStyleProperties *props;
1315 GArray *priority_info;
1318 css_provider = GTK_CSS_PROVIDER (provider);
1319 props = gtk_style_properties_new ();
1320 priv = css_provider->priv;
1322 css_provider_dump_symbolic_colors (css_provider, props);
1323 priority_info = css_provider_get_selectors (css_provider, path);
1325 for (i = 0; i < priority_info->len; i++)
1327 StylePriorityInfo *info;
1328 GHashTableIter iter;
1329 gpointer key, value;
1331 info = &g_array_index (priority_info, StylePriorityInfo, i);
1332 g_hash_table_iter_init (&iter, info->style);
1334 while (g_hash_table_iter_next (&iter, &key, &value))
1338 /* Properties starting with '-' may be both widget style properties
1339 * or custom properties from the theming engine, so check whether
1340 * the type is registered or not.
1342 if (prop[0] == '-' &&
1343 !gtk_style_properties_lookup_property (prop, NULL, NULL))
1346 gtk_style_properties_set_property (props, key, info->state, value);
1350 g_array_free (priority_info, TRUE);
1356 gtk_css_provider_get_style_property (GtkStyleProvider *provider,
1357 GtkWidgetPath *path,
1358 GtkStateFlags state,
1362 GArray *priority_info;
1363 gboolean found = FALSE;
1367 prop_name = g_strdup_printf ("-%s-%s",
1368 g_type_name (pspec->owner_type),
1371 priority_info = css_provider_get_selectors (GTK_CSS_PROVIDER (provider), path);
1373 for (i = priority_info->len - 1; i >= 0; i--)
1375 StylePriorityInfo *info;
1378 info = &g_array_index (priority_info, StylePriorityInfo, i);
1379 val = g_hash_table_lookup (info->style, prop_name);
1382 (info->state == 0 ||
1383 info->state == state ||
1384 ((info->state & state) != 0 &&
1385 (info->state & ~(state)) == 0)))
1387 const gchar *val_str;
1389 val_str = g_value_get_string (val);
1392 css_provider_parse_value (GTK_CSS_PROVIDER (provider), val_str, value, NULL);
1397 g_array_free (priority_info, TRUE);
1404 gtk_css_style_provider_iface_init (GtkStyleProviderIface *iface)
1406 iface->get_style = gtk_css_provider_get_style;
1407 iface->get_style_property = gtk_css_provider_get_style_property;
1411 gtk_css_provider_finalize (GObject *object)
1413 GtkCssProvider *css_provider;
1414 GtkCssProviderPrivate *priv;
1416 css_provider = GTK_CSS_PROVIDER (object);
1417 priv = css_provider->priv;
1419 g_scanner_destroy (priv->scanner);
1420 g_free (priv->filename);
1422 g_ptr_array_free (priv->selectors_info, TRUE);
1424 g_slist_foreach (priv->cur_selectors, (GFunc) selector_path_unref, NULL);
1425 g_slist_free (priv->cur_selectors);
1427 if (priv->cur_properties)
1428 g_hash_table_unref (priv->cur_properties);
1429 if (priv->symbolic_colors)
1430 g_hash_table_destroy (priv->symbolic_colors);
1432 G_OBJECT_CLASS (gtk_css_provider_parent_class)->finalize (object);
1436 * gtk_css_provider_new:
1438 * Returns a newly created #GtkCssProvider.
1440 * Returns: A new #GtkCssProvider
1443 gtk_css_provider_new (void)
1445 return g_object_new (GTK_TYPE_CSS_PROVIDER, NULL);
1449 property_value_free (GValue *value)
1451 if (G_IS_VALUE (value))
1452 g_value_unset (value);
1454 g_slice_free (GValue, value);
1458 scanner_apply_scope (GScanner *scanner,
1461 g_scanner_set_scope (scanner, scope);
1463 if (scope == SCOPE_VALUE)
1465 scanner->config->cset_identifier_first = G_CSET_a_2_z G_CSET_A_2_Z G_CSET_DIGITS "@#-_";
1466 scanner->config->cset_identifier_nth = G_CSET_a_2_z G_CSET_A_2_Z G_CSET_DIGITS "@#-_ +(),.%\t\n'/\"";
1467 scanner->config->scan_identifier_1char = TRUE;
1469 else if (scope == SCOPE_SELECTOR)
1471 scanner->config->cset_identifier_first = G_CSET_a_2_z G_CSET_A_2_Z "*@";
1472 scanner->config->cset_identifier_nth = G_CSET_a_2_z G_CSET_A_2_Z G_CSET_DIGITS "-_#.";
1473 scanner->config->scan_identifier_1char = TRUE;
1475 else if (scope == SCOPE_PSEUDO_CLASS ||
1476 scope == SCOPE_NTH_CHILD ||
1477 scope == SCOPE_DECLARATION)
1479 scanner->config->cset_identifier_first = G_CSET_a_2_z G_CSET_A_2_Z "-_";
1480 scanner->config->cset_identifier_nth = G_CSET_a_2_z G_CSET_A_2_Z G_CSET_DIGITS "-_";
1481 scanner->config->scan_identifier_1char = FALSE;
1484 g_assert_not_reached ();
1486 scanner->config->scan_float = FALSE;
1487 scanner->config->cpair_comment_single = NULL;
1491 css_provider_push_scope (GtkCssProvider *css_provider,
1494 GtkCssProviderPrivate *priv;
1496 priv = css_provider->priv;
1497 priv->state = g_slist_prepend (priv->state, GUINT_TO_POINTER (scope));
1499 scanner_apply_scope (priv->scanner, scope);
1503 css_provider_pop_scope (GtkCssProvider *css_provider)
1505 GtkCssProviderPrivate *priv;
1506 ParserScope scope = SCOPE_SELECTOR;
1508 priv = css_provider->priv;
1512 g_warning ("Push/pop calls to parser scope aren't paired");
1513 scanner_apply_scope (priv->scanner, SCOPE_SELECTOR);
1514 return SCOPE_SELECTOR;
1517 priv->state = g_slist_delete_link (priv->state, priv->state);
1519 /* Fetch new scope */
1521 scope = GPOINTER_TO_INT (priv->state->data);
1523 scanner_apply_scope (priv->scanner, scope);
1529 css_provider_reset_parser (GtkCssProvider *css_provider)
1531 GtkCssProviderPrivate *priv;
1533 priv = css_provider->priv;
1535 g_slist_free (priv->state);
1538 scanner_apply_scope (priv->scanner, SCOPE_SELECTOR);
1539 priv->scanner->user_data = NULL;
1540 priv->value_pos = NULL;
1542 g_slist_foreach (priv->cur_selectors, (GFunc) selector_path_unref, NULL);
1543 g_slist_free (priv->cur_selectors);
1544 priv->cur_selectors = NULL;
1546 if (priv->cur_properties)
1547 g_hash_table_unref (priv->cur_properties);
1549 priv->cur_properties = g_hash_table_new_full (g_str_hash,
1551 (GDestroyNotify) g_free,
1552 (GDestroyNotify) property_value_free);
1556 css_provider_commit (GtkCssProvider *css_provider)
1558 GtkCssProviderPrivate *priv;
1561 priv = css_provider->priv;
1562 l = priv->cur_selectors;
1566 SelectorPath *path = l->data;
1567 SelectorStyleInfo *info;
1569 info = selector_style_info_new (path);
1570 selector_style_info_set_style (info, priv->cur_properties);
1572 g_ptr_array_add (priv->selectors_info, info);
1578 parse_nth_child (GtkCssProvider *css_provider,
1580 GtkRegionFlags *flags)
1582 ParserSymbol symbol;
1584 g_scanner_get_next_token (scanner);
1586 if (scanner->token != G_TOKEN_SYMBOL)
1587 return G_TOKEN_SYMBOL;
1589 symbol = GPOINTER_TO_INT (scanner->value.v_symbol);
1591 if (symbol == SYMBOL_NTH_CHILD)
1593 g_scanner_get_next_token (scanner);
1595 if (scanner->token != G_TOKEN_LEFT_PAREN)
1596 return G_TOKEN_LEFT_PAREN;
1598 css_provider_push_scope (css_provider, SCOPE_NTH_CHILD);
1599 g_scanner_get_next_token (scanner);
1601 if (scanner->token != G_TOKEN_SYMBOL)
1602 return G_TOKEN_SYMBOL;
1604 symbol = GPOINTER_TO_INT (scanner->value.v_symbol);
1608 case SYMBOL_NTH_CHILD_EVEN:
1609 *flags = GTK_REGION_EVEN;
1611 case SYMBOL_NTH_CHILD_ODD:
1612 *flags = GTK_REGION_ODD;
1614 case SYMBOL_NTH_CHILD_FIRST:
1615 *flags = GTK_REGION_FIRST;
1617 case SYMBOL_NTH_CHILD_LAST:
1618 *flags = GTK_REGION_LAST;
1624 g_scanner_get_next_token (scanner);
1626 if (scanner->token != G_TOKEN_RIGHT_PAREN)
1627 return G_TOKEN_RIGHT_PAREN;
1629 css_provider_pop_scope (css_provider);
1631 else if (symbol == SYMBOL_FIRST_CHILD)
1632 *flags = GTK_REGION_FIRST;
1633 else if (symbol == SYMBOL_LAST_CHILD)
1634 *flags = GTK_REGION_LAST;
1635 else if (symbol == SYMBOL_SORTED_CHILD)
1636 *flags = GTK_REGION_SORTED;
1640 return G_TOKEN_SYMBOL;
1643 return G_TOKEN_NONE;
1647 parse_pseudo_class (GtkCssProvider *css_provider,
1649 SelectorPath *selector)
1653 g_scanner_get_next_token (scanner);
1655 if (scanner->token != G_TOKEN_SYMBOL)
1656 return G_TOKEN_SYMBOL;
1658 state = GPOINTER_TO_INT (scanner->value.v_symbol);
1662 case GTK_STATE_ACTIVE:
1663 selector->state |= GTK_STATE_FLAG_ACTIVE;
1665 case GTK_STATE_PRELIGHT:
1666 selector->state |= GTK_STATE_FLAG_PRELIGHT;
1668 case GTK_STATE_SELECTED:
1669 selector->state |= GTK_STATE_FLAG_SELECTED;
1671 case GTK_STATE_INSENSITIVE:
1672 selector->state |= GTK_STATE_FLAG_INSENSITIVE;
1674 case GTK_STATE_INCONSISTENT:
1675 selector->state |= GTK_STATE_FLAG_INCONSISTENT;
1677 case GTK_STATE_FOCUSED:
1678 selector->state |= GTK_STATE_FLAG_FOCUSED;
1681 return G_TOKEN_SYMBOL;
1684 return G_TOKEN_NONE;
1687 /* Parses a number of concatenated classes */
1689 parse_classes (SelectorPath *path,
1694 if ((pos = strchr (str, '.')) != NULL)
1696 /* Leave the last class to the call after the loop */
1700 selector_path_prepend_class (path, str);
1703 pos = strchr (str, '.');
1707 selector_path_prepend_class (path, str);
1711 parse_selector (GtkCssProvider *css_provider,
1713 SelectorPath **selector_out)
1717 path = selector_path_new ();
1718 *selector_out = path;
1720 if (scanner->token != ':' &&
1721 scanner->token != '#' &&
1722 scanner->token != '.' &&
1723 scanner->token != G_TOKEN_IDENTIFIER)
1724 return G_TOKEN_IDENTIFIER;
1726 while (scanner->token == '#' ||
1727 scanner->token == '.' ||
1728 scanner->token == G_TOKEN_IDENTIFIER)
1730 if (scanner->token == '#' ||
1731 scanner->token == '.')
1736 is_class = (scanner->token == '.');
1738 g_scanner_get_next_token (scanner);
1740 if (scanner->token != G_TOKEN_IDENTIFIER)
1741 return G_TOKEN_IDENTIFIER;
1743 selector_path_prepend_glob (path);
1744 selector_path_prepend_combinator (path, COMBINATOR_CHILD);
1747 parse_classes (path, scanner->value.v_identifier);
1750 if ((pos = strchr (scanner->value.v_identifier, '.')) != NULL)
1753 selector_path_prepend_name (path, scanner->value.v_identifier);
1755 /* Parse any remaining classes */
1757 parse_classes (path, pos + 1);
1760 else if (g_ascii_isupper (scanner->value.v_identifier[0]))
1764 if ((pos = strchr (scanner->value.v_identifier, '#')) != NULL ||
1765 (pos = strchr (scanner->value.v_identifier, '.')) != NULL)
1767 gchar *type_name, *name;
1770 is_class = (*pos == '.');
1772 /* Widget type and name/class put together */
1775 type_name = scanner->value.v_identifier;
1777 selector_path_prepend_type (path, type_name);
1779 /* This is only so there is a direct relationship
1780 * between widget type and its name.
1782 selector_path_prepend_combinator (path, COMBINATOR_CHILD);
1785 parse_classes (path, name);
1788 if ((pos = strchr (name, '.')) != NULL)
1791 selector_path_prepend_name (path, name);
1793 /* Parse any remaining classes */
1795 parse_classes (path, pos + 1);
1799 selector_path_prepend_type (path, scanner->value.v_identifier);
1801 else if (g_ascii_islower (scanner->value.v_identifier[0]))
1803 GtkRegionFlags flags = 0;
1806 region_name = g_strdup (scanner->value.v_identifier);
1808 if (g_scanner_peek_next_token (scanner) == ':')
1810 ParserSymbol symbol;
1812 g_scanner_get_next_token (scanner);
1813 css_provider_push_scope (css_provider, SCOPE_PSEUDO_CLASS);
1815 /* Check for the next token being nth-child, parse in that
1816 * case, and fallback into common state parsing if not.
1818 if (g_scanner_peek_next_token (scanner) != G_TOKEN_SYMBOL)
1819 return G_TOKEN_SYMBOL;
1821 symbol = GPOINTER_TO_INT (scanner->next_value.v_symbol);
1823 if (symbol == SYMBOL_FIRST_CHILD ||
1824 symbol == SYMBOL_LAST_CHILD ||
1825 symbol == SYMBOL_NTH_CHILD ||
1826 symbol == SYMBOL_SORTED_CHILD)
1830 if ((token = parse_nth_child (css_provider, scanner, &flags)) != G_TOKEN_NONE)
1833 css_provider_pop_scope (css_provider);
1837 css_provider_pop_scope (css_provider);
1838 selector_path_prepend_region (path, region_name, 0);
1839 g_free (region_name);
1844 selector_path_prepend_region (path, region_name, flags);
1845 g_free (region_name);
1847 else if (scanner->value.v_identifier[0] == '*')
1848 selector_path_prepend_glob (path);
1850 return G_TOKEN_IDENTIFIER;
1852 g_scanner_get_next_token (scanner);
1854 if (scanner->token == '>')
1856 selector_path_prepend_combinator (path, COMBINATOR_CHILD);
1857 g_scanner_get_next_token (scanner);
1861 if (scanner->token == ':')
1863 /* Add glob selector if path is empty */
1864 if (selector_path_depth (path) == 0)
1865 selector_path_prepend_glob (path);
1867 css_provider_push_scope (css_provider, SCOPE_PSEUDO_CLASS);
1869 while (scanner->token == ':')
1873 if ((token = parse_pseudo_class (css_provider, scanner, path)) != G_TOKEN_NONE)
1876 g_scanner_get_next_token (scanner);
1879 css_provider_pop_scope (css_provider);
1882 return G_TOKEN_NONE;
1885 #define SKIP_SPACES(s) while (s[0] == ' ' || s[0] == '\t' || s[0] == '\n') s++;
1886 #define SKIP_SPACES_BACK(s) while (s[0] == ' ' || s[0] == '\t' || s[0] == '\n') s--;
1888 static GtkSymbolicColor *
1889 symbolic_color_parse_str (const gchar *string,
1892 GtkSymbolicColor *symbolic_color = NULL;
1895 str = (gchar *) string;
1906 while (*end == '-' || *end == '_' || g_ascii_isalpha (*end))
1909 name = g_strndup (str, end - str);
1910 symbolic_color = gtk_symbolic_color_new_name (name);
1913 *end_ptr = (gchar *) end;
1915 else if (g_str_has_prefix (str, "lighter") ||
1916 g_str_has_prefix (str, "darker"))
1918 GtkSymbolicColor *param_color;
1919 gboolean is_lighter = FALSE;
1921 is_lighter = g_str_has_prefix (str, "lighter");
1924 str += strlen ("lighter");
1926 str += strlen ("darker");
1932 *end_ptr = (gchar *) str;
1938 param_color = symbolic_color_parse_str (str, end_ptr);
1945 *end_ptr = (gchar *) str;
1949 gtk_symbolic_color_unref (param_color);
1954 symbolic_color = gtk_symbolic_color_new_shade (param_color, 1.3);
1956 symbolic_color = gtk_symbolic_color_new_shade (param_color, 0.7);
1958 gtk_symbolic_color_unref (param_color);
1961 else if (g_str_has_prefix (str, "shade") ||
1962 g_str_has_prefix (str, "alpha"))
1964 GtkSymbolicColor *param_color;
1965 gboolean is_shade = FALSE;
1968 is_shade = g_str_has_prefix (str, "shade");
1971 str += strlen ("shade");
1973 str += strlen ("alpha");
1979 *end_ptr = (gchar *) str;
1985 param_color = symbolic_color_parse_str (str, end_ptr);
1995 gtk_symbolic_color_unref (param_color);
1996 *end_ptr = (gchar *) str;
2002 factor = g_ascii_strtod (str, end_ptr);
2006 *end_ptr = (gchar *) str;
2010 gtk_symbolic_color_unref (param_color);
2015 symbolic_color = gtk_symbolic_color_new_shade (param_color, factor);
2017 symbolic_color = gtk_symbolic_color_new_alpha (param_color, factor);
2019 gtk_symbolic_color_unref (param_color);
2022 else if (g_str_has_prefix (str, "mix"))
2024 GtkSymbolicColor *color1, *color2;
2027 str += strlen ("mix");
2032 *end_ptr = (gchar *) str;
2038 color1 = symbolic_color_parse_str (str, end_ptr);
2048 gtk_symbolic_color_unref (color1);
2049 *end_ptr = (gchar *) str;
2055 color2 = symbolic_color_parse_str (str, end_ptr);
2057 if (!color2 || *end_ptr[0] != ',')
2059 gtk_symbolic_color_unref (color1);
2068 gtk_symbolic_color_unref (color1);
2069 gtk_symbolic_color_unref (color2);
2070 *end_ptr = (gchar *) str;
2076 factor = g_ascii_strtod (str, end_ptr);
2080 *end_ptr = (gchar *) str;
2084 gtk_symbolic_color_unref (color1);
2085 gtk_symbolic_color_unref (color2);
2089 symbolic_color = gtk_symbolic_color_new_mix (color1, color2, factor);
2090 gtk_symbolic_color_unref (color1);
2091 gtk_symbolic_color_unref (color2);
2104 /* Color in hex format */
2105 while (g_ascii_isxdigit (*end))
2108 else if (g_str_has_prefix (str, "rgb"))
2110 /* color in rgb/rgba format */
2111 while (*end != ')' && *end != '\0')
2119 /* color name? parse until first whitespace */
2120 while (*end != ' ' && *end != '\0')
2124 color_str = g_strndup (str, end - str);
2125 *end_ptr = (gchar *) end;
2127 if (!gdk_rgba_parse (&color, color_str))
2133 symbolic_color = gtk_symbolic_color_new_literal (&color);
2137 return symbolic_color;
2140 static GtkSymbolicColor *
2141 symbolic_color_parse (const gchar *str,
2144 GtkSymbolicColor *color;
2147 color = symbolic_color_parse_str (str, &end);
2151 g_set_error_literal (error,
2152 GTK_CSS_PROVIDER_ERROR,
2153 GTK_CSS_PROVIDER_ERROR_FAILED,
2154 "Could not parse symbolic color");
2158 gtk_symbolic_color_unref (color);
2166 static GtkGradient *
2167 gradient_parse_str (const gchar *str,
2170 GtkGradient *gradient = NULL;
2175 if (g_str_has_prefix (str, "-gtk-gradient"))
2177 cairo_pattern_type_t type;
2179 str += strlen ("-gtk-gradient");
2184 *end_ptr = (gchar *) str;
2191 /* Parse gradient type */
2192 if (g_str_has_prefix (str, "linear"))
2194 type = CAIRO_PATTERN_TYPE_LINEAR;
2195 str += strlen ("linear");
2197 else if (g_str_has_prefix (str, "radial"))
2199 type = CAIRO_PATTERN_TYPE_RADIAL;
2200 str += strlen ("radial");
2204 *end_ptr = (gchar *) str;
2210 /* Parse start/stop position parameters */
2211 for (i = 0; i < 2; i++)
2215 *end_ptr = (gchar *) str;
2222 if (strncmp (str, "left", 4) == 0)
2225 str += strlen ("left");
2227 else if (strncmp (str, "right", 5) == 0)
2230 str += strlen ("right");
2232 else if (strncmp (str, "center", 6) == 0)
2234 coords[i * 3] = 0.5;
2235 str += strlen ("center");
2239 coords[i * 3] = g_ascii_strtod (str, &end);
2243 *end_ptr = (gchar *) str;
2252 if (strncmp (str, "top", 3) == 0)
2254 coords[(i * 3) + 1] = 0;
2255 str += strlen ("top");
2257 else if (strncmp (str, "bottom", 6) == 0)
2259 coords[(i * 3) + 1] = 1;
2260 str += strlen ("bottom");
2262 else if (strncmp (str, "center", 6) == 0)
2264 coords[(i * 3) + 1] = 0.5;
2265 str += strlen ("center");
2269 coords[(i * 3) + 1] = g_ascii_strtod (str, &end);
2273 *end_ptr = (gchar *) str;
2282 if (type == CAIRO_PATTERN_TYPE_RADIAL)
2287 *end_ptr = (gchar *) str;
2294 coords[(i * 3) + 2] = g_ascii_strtod (str, &end);
2301 if (type == CAIRO_PATTERN_TYPE_LINEAR)
2302 gradient = gtk_gradient_new_linear (coords[0], coords[1], coords[3], coords[4]);
2304 gradient = gtk_gradient_new_radial (coords[0], coords[1], coords[2],
2305 coords[3], coords[4], coords[5]);
2309 GtkSymbolicColor *color;
2314 *end_ptr = (gchar *) str;
2321 if (g_str_has_prefix (str, "from"))
2324 str += strlen ("from");
2329 *end_ptr = (gchar *) str;
2333 else if (g_str_has_prefix (str, "to"))
2336 str += strlen ("to");
2341 *end_ptr = (gchar *) str;
2345 else if (g_str_has_prefix (str, "color-stop"))
2347 str += strlen ("color-stop");
2352 *end_ptr = (gchar *) str;
2359 position = g_ascii_strtod (str, &end);
2366 *end_ptr = (gchar *) str;
2372 *end_ptr = (gchar *) str;
2379 color = symbolic_color_parse_str (str, &end);
2386 *end_ptr = (gchar *) str;
2395 gtk_gradient_add_color_stop (gradient, position, color);
2396 gtk_symbolic_color_unref (color);
2402 *end_ptr = (gchar *) str;
2409 *end_ptr = (gchar *) str;
2415 path_parse_str (GtkCssProvider *css_provider,
2421 const gchar *start, *end;
2424 if (g_str_has_prefix (str, "url"))
2426 str += strlen ("url");
2431 *end_ptr = (gchar *) str;
2435 chr = strchr (str, ')');
2438 *end_ptr = (gchar *) str;
2447 if (*str == '"' || *str == '\'')
2454 SKIP_SPACES_BACK (chr);
2456 if (*chr != *p || chr == p)
2458 *end_ptr = (gchar *)str;
2464 *end_ptr = (gchar *)str;
2468 path = g_strndup (str, chr - str);
2471 *end_ptr = (gchar *)end;
2475 path = g_strdup (str);
2476 *end_ptr = (gchar *)str + strlen (str);
2479 /* Always return an absolute path */
2480 if (!g_path_is_absolute (path))
2482 GtkCssProviderPrivate *priv;
2483 gchar *dirname, *full_path;
2485 priv = css_provider->priv;
2487 /* Use relative path to the current CSS file path, if any */
2489 dirname = g_path_get_dirname (priv->filename);
2491 dirname = g_get_current_dir ();
2493 full_path = g_build_filename (dirname, path, NULL);
2500 if (!g_file_test (path, G_FILE_TEST_EXISTS | G_FILE_TEST_IS_REGULAR))
2502 g_set_error (error, G_FILE_ERROR, G_FILE_ERROR_EXIST,
2503 "File doesn't exist: %s", path);
2506 *end_ptr = (gchar *)start;
2513 path_parse (GtkCssProvider *css_provider,
2520 path = path_parse_str (css_provider, str, &end, error);
2527 g_set_error_literal (error,
2528 GTK_CSS_PROVIDER_ERROR,
2529 GTK_CSS_PROVIDER_ERROR_FAILED,
2530 "Error parsing path");
2539 slice_parse_str (GtkCssProvider *css_provider,
2544 gdouble distance_top, distance_bottom;
2545 gdouble distance_left, distance_right;
2546 GtkSliceSideModifier mods[2];
2554 /* Parse image url */
2555 path = path_parse_str (css_provider, str, end_ptr, error);
2563 /* Parse top/left/bottom/right distances */
2564 distance_top = g_ascii_strtod (str, end_ptr);
2569 distance_right = g_ascii_strtod (str, end_ptr);
2574 distance_bottom = g_ascii_strtod (str, end_ptr);
2579 distance_left = g_ascii_strtod (str, end_ptr);
2584 while (*str && i < 2)
2586 if (g_str_has_prefix (str, "stretch"))
2588 str += strlen ("stretch");
2589 mods[i] = GTK_SLICE_STRETCH;
2591 else if (g_str_has_prefix (str, "repeat"))
2593 str += strlen ("repeat");
2594 mods[i] = GTK_SLICE_REPEAT;
2599 *end_ptr = (gchar *) str;
2607 *end_ptr = (gchar *) str;
2617 /* Fill in second modifier, same as the first */
2621 pixbuf = gdk_pixbuf_new_from_file (path, error);
2626 *end_ptr = (gchar *) str;
2630 slice = _gtk_9slice_new (pixbuf,
2631 distance_top, distance_bottom,
2632 distance_left, distance_right,
2634 g_object_unref (pixbuf);
2640 unit_parse_str (const gchar *str,
2646 unit = g_ascii_strtod (str, end_str);
2649 /* Now parse the unit type, if any. We
2650 * don't admit spaces between these.
2652 if (*str != ' ' && *str != '\0')
2654 while (**end_str != ' ' && **end_str != '\0')
2657 /* Only handle pixels at the moment */
2658 if (strncmp (str, "px", 2) != 0)
2662 type = g_strndup (str, *end_str - str);
2663 g_warning ("Unknown unit '%s', only pixel units are "
2664 "currently supported in CSS style", type);
2673 border_parse_str (const gchar *str,
2676 gdouble first, second, third, fourth;
2679 border = gtk_border_new ();
2682 if (!g_ascii_isdigit (*str))
2685 first = unit_parse_str (str, end_str);
2689 if (!g_ascii_isdigit (*str))
2691 border->left = border->right = border->top = border->bottom = (gint) first;
2692 *end_str = (gchar *) str;
2696 second = unit_parse_str (str, end_str);
2700 if (!g_ascii_isdigit (*str))
2702 border->top = border->bottom = (gint) first;
2703 border->left = border->right = (gint) second;
2704 *end_str = (gchar *) str;
2708 third = unit_parse_str (str, end_str);
2712 if (!g_ascii_isdigit (*str))
2714 border->top = (gint) first;
2715 border->left = border->right = (gint) second;
2716 border->bottom = (gint) third;
2717 *end_str = (gchar *) str;
2721 fourth = unit_parse_str (str, end_str);
2723 border->top = (gint) first;
2724 border->right = (gint) second;
2725 border->bottom = (gint) third;
2726 border->left = (gint) fourth;
2732 css_provider_parse_value (GtkCssProvider *css_provider,
2733 const gchar *value_str,
2737 GtkCssProviderPrivate *priv;
2739 gboolean parsed = TRUE;
2742 priv = css_provider->priv;
2743 type = G_VALUE_TYPE (value);
2745 if (type == GDK_TYPE_RGBA ||
2746 type == GDK_TYPE_COLOR)
2751 if (type == GDK_TYPE_RGBA &&
2752 gdk_rgba_parse (&rgba, value_str))
2753 g_value_set_boxed (value, &rgba);
2754 else if (type == GDK_TYPE_COLOR &&
2755 gdk_color_parse (value_str, &color))
2756 g_value_set_boxed (value, &color);
2759 GtkSymbolicColor *symbolic_color;
2761 symbolic_color = symbolic_color_parse_str (value_str, &end);
2765 g_value_unset (value);
2766 g_value_init (value, GTK_TYPE_SYMBOLIC_COLOR);
2767 g_value_take_boxed (value, symbolic_color);
2773 else if (type == PANGO_TYPE_FONT_DESCRIPTION)
2775 PangoFontDescription *font_desc;
2777 font_desc = pango_font_description_from_string (value_str);
2778 g_value_take_boxed (value, font_desc);
2780 else if (type == G_TYPE_BOOLEAN)
2782 if (value_str[0] == '1' ||
2783 g_ascii_strcasecmp (value_str, "true") == 0)
2784 g_value_set_boolean (value, TRUE);
2786 g_value_set_boolean (value, FALSE);
2788 else if (type == G_TYPE_INT)
2789 g_value_set_int (value, atoi (value_str));
2790 else if (type == G_TYPE_UINT)
2791 g_value_set_uint (value, (guint) atoi (value_str));
2792 else if (type == G_TYPE_DOUBLE)
2793 g_value_set_double (value, g_ascii_strtod (value_str, NULL));
2794 else if (type == G_TYPE_FLOAT)
2795 g_value_set_float (value, (gfloat) g_ascii_strtod (value_str, NULL));
2796 else if (type == GTK_TYPE_THEMING_ENGINE)
2798 GtkThemingEngine *engine;
2800 engine = gtk_theming_engine_load (value_str);
2802 g_value_set_object (value, engine);
2806 else if (type == GTK_TYPE_ANIMATION_DESCRIPTION)
2808 GtkAnimationDescription *desc;
2810 desc = _gtk_animation_description_from_string (value_str);
2813 g_value_take_boxed (value, desc);
2817 else if (type == GTK_TYPE_BORDER)
2821 border = border_parse_str (value_str, &end);
2822 g_value_take_boxed (value, border);
2824 else if (type == CAIRO_GOBJECT_TYPE_PATTERN)
2826 GtkGradient *gradient;
2828 gradient = gradient_parse_str (value_str, &end);
2832 g_value_unset (value);
2833 g_value_init (value, GTK_TYPE_GRADIENT);
2834 g_value_take_boxed (value, gradient);
2841 g_clear_error (error);
2842 path = path_parse_str (css_provider, value_str, &end, error);
2846 pixbuf = gdk_pixbuf_new_from_file (path, NULL);
2851 cairo_surface_t *surface;
2852 cairo_pattern_t *pattern;
2854 cairo_matrix_t matrix;
2856 surface = cairo_image_surface_create (CAIRO_FORMAT_ARGB32,
2857 gdk_pixbuf_get_width (pixbuf),
2858 gdk_pixbuf_get_height (pixbuf));
2859 cr = cairo_create (surface);
2860 gdk_cairo_set_source_pixbuf (cr, pixbuf, 0, 0);
2862 pattern = cairo_pattern_create_for_surface (surface);
2864 cairo_matrix_init_scale (&matrix,
2865 gdk_pixbuf_get_width (pixbuf),
2866 gdk_pixbuf_get_height (pixbuf));
2867 cairo_pattern_set_matrix (pattern, &matrix);
2869 cairo_surface_destroy (surface);
2871 g_object_unref (pixbuf);
2873 g_value_take_boxed (value, pattern);
2882 else if (G_TYPE_IS_ENUM (type))
2884 GEnumClass *enum_class;
2885 GEnumValue *enum_value;
2887 enum_class = g_type_class_ref (type);
2888 enum_value = g_enum_get_value_by_nick (enum_class, value_str);
2893 GTK_CSS_PROVIDER_ERROR,
2894 GTK_CSS_PROVIDER_ERROR_FAILED,
2895 "Unknown value '%s' for enum type '%s'",
2896 value_str, g_type_name (type));
2900 g_value_set_enum (value, enum_value->value);
2902 g_type_class_unref (enum_class);
2904 else if (G_TYPE_IS_FLAGS (type))
2906 GFlagsClass *flags_class;
2907 GFlagsValue *flag_value;
2911 flags_class = g_type_class_ref (type);
2913 /* Parse comma separated values */
2914 ptr = strchr (value_str, ',');
2916 while (ptr && parsed)
2923 flag_str = (gchar *) value_str;
2924 flag_value = g_flags_get_value_by_nick (flags_class,
2925 g_strstrip (flag_str));
2930 GTK_CSS_PROVIDER_ERROR,
2931 GTK_CSS_PROVIDER_ERROR_FAILED,
2932 "Unknown flag '%s' for type '%s'",
2933 value_str, g_type_name (type));
2937 flags |= flag_value->value;
2940 ptr = strchr (value_str, ',');
2943 /* Store last/only value */
2944 flag_value = g_flags_get_value_by_nick (flags_class, value_str);
2949 GTK_CSS_PROVIDER_ERROR,
2950 GTK_CSS_PROVIDER_ERROR_FAILED,
2951 "Unknown flag '%s' for type '%s'",
2952 value_str, g_type_name (type));
2956 flags |= flag_value->value;
2959 g_value_set_enum (value, flags);
2961 g_type_class_unref (flags_class);
2963 else if (type == GTK_TYPE_9SLICE)
2967 slice = slice_parse_str (css_provider, value_str, &end, error);
2970 g_value_take_boxed (value, slice);
2977 GTK_CSS_PROVIDER_ERROR,
2978 GTK_CSS_PROVIDER_ERROR_FAILED,
2979 "Cannot parse string '%s' for type %s",
2980 value_str, g_type_name (type));
2986 /* Set error position in the scanner
2987 * according to what we've parsed so far
2989 priv->value_pos += (end - value_str);
2991 if (error && !*error)
2992 g_set_error_literal (error,
2993 GTK_CSS_PROVIDER_ERROR,
2994 GTK_CSS_PROVIDER_ERROR_FAILED,
2995 "Failed to parse value");
3002 scanner_report_warning (GtkCssProvider *css_provider,
3003 GTokenType expected_token,
3006 GtkCssProviderPrivate *priv;
3007 const gchar *line_end, *line_start;
3008 const gchar *expected_str;
3009 gchar buf[2], *line, *str;
3012 priv = css_provider->priv;
3015 str = g_strdup (error->message);
3018 if (priv->scanner->user_data)
3019 expected_str = priv->scanner->user_data;
3022 switch (expected_token)
3024 case G_TOKEN_SYMBOL:
3025 expected_str = "Symbol";
3026 case G_TOKEN_IDENTIFIER:
3027 expected_str = "Identifier";
3029 buf[0] = expected_token;
3035 str = g_strdup_printf ("Parse error, expecting a %s '%s'",
3036 (expected_str != buf) ? "valid" : "",
3040 if (priv->value_pos)
3041 line_start = priv->value_pos - 1;
3043 line_start = priv->scanner->text - 1;
3045 while (*line_start != '\n' &&
3046 line_start != priv->buffer)
3049 if (*line_start == '\n')
3052 if (priv->value_pos)
3053 pos = priv->value_pos - line_start + 1;
3055 pos = priv->scanner->text - line_start - 1;
3057 line_end = strchr (line_start, '\n');
3060 line = g_strndup (line_start, (line_end - line_start));
3062 line = g_strdup (line_start);
3064 g_message ("CSS: %s\n"
3065 "%s, line %d, char %d:\n"
3068 str, priv->scanner->input_name,
3069 priv->scanner->line, priv->scanner->position,
3078 parse_rule (GtkCssProvider *css_provider,
3082 GtkCssProviderPrivate *priv;
3083 GTokenType expected_token;
3084 SelectorPath *selector;
3086 priv = css_provider->priv;
3088 css_provider_push_scope (css_provider, SCOPE_SELECTOR);
3090 /* Handle directives */
3091 if (scanner->token == G_TOKEN_IDENTIFIER &&
3092 scanner->value.v_identifier[0] == '@')
3096 directive = &scanner->value.v_identifier[1];
3098 if (strcmp (directive, "define-color") == 0)
3100 GtkSymbolicColor *color;
3101 gchar *color_name, *color_str;
3103 /* Directive is a color mapping */
3104 g_scanner_get_next_token (scanner);
3106 if (scanner->token != G_TOKEN_IDENTIFIER)
3108 scanner->user_data = "Color name";
3109 return G_TOKEN_IDENTIFIER;
3112 color_name = g_strdup (scanner->value.v_identifier);
3113 css_provider_push_scope (css_provider, SCOPE_VALUE);
3114 g_scanner_get_next_token (scanner);
3116 if (scanner->token != G_TOKEN_IDENTIFIER)
3118 scanner->user_data = "Color definition";
3119 return G_TOKEN_IDENTIFIER;
3122 color_str = g_strstrip (scanner->value.v_identifier);
3123 color = symbolic_color_parse (color_str, error);
3127 scanner->user_data = "Color definition";
3128 return G_TOKEN_IDENTIFIER;
3131 g_hash_table_insert (priv->symbolic_colors, color_name, color);
3133 css_provider_pop_scope (css_provider);
3134 g_scanner_get_next_token (scanner);
3136 if (scanner->token != ';')
3139 return G_TOKEN_NONE;
3141 else if (strcmp (directive, "import") == 0)
3143 GScanner *scanner_backup;
3144 GSList *state_backup;
3148 css_provider_push_scope (css_provider, SCOPE_VALUE);
3149 g_scanner_get_next_token (scanner);
3151 if (scanner->token == G_TOKEN_IDENTIFIER &&
3152 g_str_has_prefix (scanner->value.v_identifier, "url"))
3153 path = path_parse (css_provider,
3154 g_strstrip (scanner->value.v_identifier),
3156 else if (scanner->token == G_TOKEN_STRING)
3157 path = path_parse (css_provider,
3158 g_strstrip (scanner->value.v_string),
3163 scanner->user_data = "File URL";
3164 return G_TOKEN_IDENTIFIER;
3167 css_provider_pop_scope (css_provider);
3168 g_scanner_get_next_token (scanner);
3170 if (scanner->token != ';')
3176 /* Snapshot current parser state and scanner in order to restore after importing */
3177 state_backup = priv->state;
3178 scanner_backup = priv->scanner;
3181 priv->scanner = create_scanner ();
3183 /* FIXME: Avoid recursive importing */
3184 loaded = gtk_css_provider_load_from_path_internal (css_provider, path,
3187 /* Restore previous state */
3188 css_provider_reset_parser (css_provider);
3189 priv->state = state_backup;
3190 g_scanner_destroy (priv->scanner);
3191 priv->scanner = scanner_backup;
3197 scanner->user_data = "File URL";
3198 return G_TOKEN_IDENTIFIER;
3201 return G_TOKEN_NONE;
3205 scanner->user_data = "Directive";
3206 return G_TOKEN_IDENTIFIER;
3210 expected_token = parse_selector (css_provider, scanner, &selector);
3212 if (expected_token != G_TOKEN_NONE)
3214 selector_path_unref (selector);
3215 scanner->user_data = "Selector";
3216 return expected_token;
3219 priv->cur_selectors = g_slist_prepend (priv->cur_selectors, selector);
3221 while (scanner->token == ',')
3223 g_scanner_get_next_token (scanner);
3225 expected_token = parse_selector (css_provider, scanner, &selector);
3227 if (expected_token != G_TOKEN_NONE)
3229 selector_path_unref (selector);
3230 scanner->user_data = "Selector";
3231 return expected_token;
3234 priv->cur_selectors = g_slist_prepend (priv->cur_selectors, selector);
3237 css_provider_pop_scope (css_provider);
3239 if (scanner->token != G_TOKEN_LEFT_CURLY)
3240 return G_TOKEN_LEFT_CURLY;
3242 /* Declarations parsing */
3243 css_provider_push_scope (css_provider, SCOPE_DECLARATION);
3244 g_scanner_get_next_token (scanner);
3246 while (scanner->token == G_TOKEN_IDENTIFIER)
3248 gchar *value_str = NULL;
3249 GtkStylePropertyParser parse_func = NULL;
3253 prop = g_strdup (scanner->value.v_identifier);
3254 g_scanner_get_next_token (scanner);
3256 if (scanner->token != ':')
3262 priv->value_pos = priv->scanner->text;
3264 css_provider_push_scope (css_provider, SCOPE_VALUE);
3265 g_scanner_get_next_token (scanner);
3267 if (scanner->token != G_TOKEN_IDENTIFIER)
3270 scanner->user_data = "Property value";
3271 return G_TOKEN_IDENTIFIER;
3274 value_str = scanner->value.v_identifier;
3275 SKIP_SPACES (value_str);
3276 g_strchomp (value_str);
3278 if (gtk_style_properties_lookup_property (prop, &parse_func, &pspec))
3282 val = g_slice_new0 (GValue);
3283 g_value_init (val, pspec->value_type);
3285 if (strcmp (value_str, "none") == 0)
3287 /* Insert the default value, so it has an opportunity
3288 * to override other style providers when merged
3290 g_param_value_set_default (pspec, val);
3291 g_hash_table_insert (priv->cur_properties, prop, val);
3293 else if (pspec->value_type == G_TYPE_STRING)
3295 g_value_set_string (val, value_str);
3296 g_hash_table_insert (priv->cur_properties, prop, val);
3298 else if ((parse_func && (parse_func) (value_str, val, error)) ||
3299 (!parse_func && css_provider_parse_value (css_provider, value_str, val, error)))
3300 g_hash_table_insert (priv->cur_properties, prop, val);
3303 g_value_unset (val);
3304 g_slice_free (GValue, val);
3307 scanner->user_data = "Property value";
3308 return G_TOKEN_IDENTIFIER;
3311 else if (prop[0] == '-' &&
3312 g_ascii_isupper (prop[1]))
3316 val = g_slice_new0 (GValue);
3317 g_value_init (val, G_TYPE_STRING);
3318 g_value_set_string (val, value_str);
3320 g_hash_table_insert (priv->cur_properties, prop, val);
3325 css_provider_pop_scope (css_provider);
3326 g_scanner_get_next_token (scanner);
3328 if (scanner->token != ';')
3331 g_scanner_get_next_token (scanner);
3334 if (scanner->token != G_TOKEN_RIGHT_CURLY)
3335 return G_TOKEN_RIGHT_CURLY;
3337 css_provider_pop_scope (css_provider);
3339 return G_TOKEN_NONE;
3343 parse_stylesheet (GtkCssProvider *css_provider,
3346 GtkCssProviderPrivate *priv;
3351 priv = css_provider->priv;
3352 g_scanner_get_next_token (priv->scanner);
3354 while (!g_scanner_eof (priv->scanner))
3356 GTokenType expected_token;
3359 css_provider_reset_parser (css_provider);
3360 expected_token = parse_rule (css_provider, priv->scanner, &err);
3362 if (expected_token != G_TOKEN_NONE)
3364 /* If a GError was passed in, propagate the error and bail out,
3365 * else report a warning and keep going
3371 g_propagate_error (error, err);
3373 g_set_error_literal (error,
3374 GTK_CSS_PROVIDER_ERROR,
3375 GTK_CSS_PROVIDER_ERROR_FAILED,
3376 "Error parsing stylesheet");
3381 scanner_report_warning (css_provider, expected_token, err);
3382 g_clear_error (&err);
3385 while (!g_scanner_eof (priv->scanner) &&
3386 priv->scanner->token != G_TOKEN_RIGHT_CURLY)
3387 g_scanner_get_next_token (priv->scanner);
3390 css_provider_commit (css_provider);
3392 g_scanner_get_next_token (priv->scanner);
3399 * gtk_css_provider_load_from_data:
3400 * @css_provider: a #GtkCssProvider
3401 * @data: CSS data loaded in memory
3402 * @length: the length of @data in bytes, or -1 for NUL terminated strings
3403 * @error: (out) (allow-none): return location for a #GError, or %NULL
3405 * Loads @data into @css_provider, making it clear any previously loaded
3408 * Returns: %TRUE if the data could be loaded.
3411 gtk_css_provider_load_from_data (GtkCssProvider *css_provider,
3416 GtkCssProviderPrivate *priv;
3418 g_return_val_if_fail (GTK_IS_CSS_PROVIDER (css_provider), FALSE);
3419 g_return_val_if_fail (data != NULL, FALSE);
3421 priv = css_provider->priv;
3424 length = strlen (data);
3426 if (priv->selectors_info->len > 0)
3427 g_ptr_array_remove_range (priv->selectors_info, 0, priv->selectors_info->len);
3429 priv->scanner->input_name = "-";
3430 priv->buffer = data;
3431 g_scanner_input_text (priv->scanner, data, (guint) length);
3433 g_free (priv->filename);
3434 priv->filename = NULL;
3435 priv->buffer = NULL;
3437 return parse_stylesheet (css_provider, error);
3441 * gtk_css_provider_load_from_file:
3442 * @css_provider: a #GtkCssProvider
3443 * @file: #GFile pointing to a file to load
3444 * @error: (out) (allow-none): return location for a #GError, or %NULL
3446 * Loads the data contained in @file into @css_provider, making it
3447 * clear any previously loaded information.
3449 * Returns: %TRUE if the data could be loaded.
3452 gtk_css_provider_load_from_file (GtkCssProvider *css_provider,
3456 GtkCssProviderPrivate *priv;
3457 GError *internal_error = NULL;
3462 g_return_val_if_fail (GTK_IS_CSS_PROVIDER (css_provider), FALSE);
3463 g_return_val_if_fail (G_IS_FILE (file), FALSE);
3465 priv = css_provider->priv;
3467 if (!g_file_load_contents (file, NULL,
3469 NULL, &internal_error))
3471 g_propagate_error (error, internal_error);
3475 if (priv->selectors_info->len > 0)
3476 g_ptr_array_remove_range (priv->selectors_info, 0, priv->selectors_info->len);
3478 g_free (priv->filename);
3479 priv->filename = g_file_get_path (file);
3481 priv->scanner->input_name = priv->filename;
3482 priv->buffer = data;
3483 g_scanner_input_text (priv->scanner, data, (guint) length);
3485 ret = parse_stylesheet (css_provider, error);
3487 priv->buffer = NULL;
3494 gtk_css_provider_load_from_path_internal (GtkCssProvider *css_provider,
3499 GtkCssProviderPrivate *priv;
3500 GError *internal_error = NULL;
3501 GMappedFile *mapped_file;
3506 priv = css_provider->priv;
3508 mapped_file = g_mapped_file_new (path, FALSE, &internal_error);
3512 g_propagate_error (error, internal_error);
3516 length = g_mapped_file_get_length (mapped_file);
3517 data = g_mapped_file_get_contents (mapped_file);
3524 if (priv->selectors_info->len > 0)
3525 g_ptr_array_remove_range (priv->selectors_info, 0, priv->selectors_info->len);
3527 g_free (priv->filename);
3528 priv->filename = g_strdup (path);
3531 priv->scanner->input_name = priv->filename;
3532 priv->buffer = data;
3533 g_scanner_input_text (priv->scanner, data, (guint) length);
3535 ret = parse_stylesheet (css_provider, error);
3537 priv->buffer = NULL;
3538 g_mapped_file_unref (mapped_file);
3544 * gtk_css_provider_load_from_path:
3545 * @css_provider: a #GtkCssProvider
3546 * @path: the path of a filename to load, in the GLib filename encoding
3547 * @error: (out) (allow-none): return location for a #GError, or %NULL
3549 * Loads the data contained in @path into @css_provider, making it clear
3550 * any previously loaded information.
3552 * Returns: %TRUE if the data could be loaded.
3555 gtk_css_provider_load_from_path (GtkCssProvider *css_provider,
3559 g_return_val_if_fail (GTK_IS_CSS_PROVIDER (css_provider), FALSE);
3560 g_return_val_if_fail (path != NULL, FALSE);
3562 return gtk_css_provider_load_from_path_internal (css_provider, path,
3567 * gtk_css_provider_get_default:
3569 * Returns the provider containing the style settings used as a
3570 * fallback for all widgets.
3572 * Returns: (transfer none): The provider used for fallback styling.
3573 * This memory is owned by GTK+, and you must not free it.
3576 gtk_css_provider_get_default (void)
3578 static GtkCssProvider *provider;
3580 if (G_UNLIKELY (!provider))
3583 "@define-color fg_color #000; \n"
3584 "@define-color bg_color #dcdad5; \n"
3585 "@define-color text_color #000; \n"
3586 "@define-color base_color #fff; \n"
3587 "@define-color selected_bg_color #4b6983; \n"
3588 "@define-color selected_fg_color #fff; \n"
3589 "@define-color tooltip_bg_color #eee1b3; \n"
3590 "@define-color tooltip_fg_color #000; \n"
3592 "@define-color info_fg_color rgb (181, 171, 156);\n"
3593 "@define-color info_bg_color rgb (252, 252, 189);\n"
3594 "@define-color warning_fg_color rgb (173, 120, 41);\n"
3595 "@define-color warning_bg_color rgb (250, 173, 61);\n"
3596 "@define-color question_fg_color rgb (97, 122, 214);\n"
3597 "@define-color question_bg_color rgb (138, 173, 212);\n"
3598 "@define-color error_fg_color rgb (166, 38, 38);\n"
3599 "@define-color error_bg_color rgb (237, 54, 54);\n"
3602 "GtkTreeView > GtkButton {\n"
3603 " background-color: @bg_color;\n"
3604 " color: @fg_color;\n"
3605 " border-color: shade (@bg_color, 0.6);\n"
3607 " border-width: 0;\n"
3611 " background-color: shade (@bg_color, 1.05);\n"
3612 " color: shade (@fg_color, 1.3);\n"
3616 " background-color: @selected_bg_color;\n"
3617 " color: @selected_fg_color;\n"
3624 ".expander:prelight {\n"
3625 " color: @text_color;\n"
3628 ".expander:active {\n"
3629 " transition: 300ms linear;\n"
3633 " border-color: shade (@bg_color, 0.7);\n"
3634 " background-color: shade (@bg_color, 0.9);\n"
3635 " color: shade (@bg_color, 0.7);\n"
3638 "GtkTreeView, GtkIconView, GtkTextView {\n"
3639 " background-color: @base_color;\n"
3640 " color: @text_color;\n"
3643 "GtkTreeView > row {\n"
3644 " background-color: @base_color;\n"
3645 " color: @text_color;\n"
3648 "GtkTreeView > row:nth-child(odd) { \n"
3649 " background-color: shade (@base_color, 0.93); \n"
3653 " background-color: @tooltip_bg_color; \n"
3654 " color: @tooltip_fg_color; \n"
3659 " border-style: outset; \n"
3660 " border-width: 2; \n"
3663 ".button:active {\n"
3664 " background-color: shade (@bg_color, 0.7);\n"
3665 " border-style: inset; \n"
3668 ".button:prelight,\n"
3669 ".slider:prelight {\n"
3670 " background-color: @selected_bg_color;\n"
3671 " color: @selected_fg_color;\n"
3672 " border-color: shade (@selected_bg_color, 0.7);\n"
3676 " border-style: inset;\n"
3677 " border-width: 1;\n"
3681 " border-style: inset;\n"
3682 " border-width: 2;\n"
3683 " background-color: @base_color;\n"
3684 " color: @text_color;\n"
3687 ".entry:insensitive {\n"
3688 " background-color: shade (@base_color, 0.9);\n"
3689 " color: shade (@base_color, 0.7);\n"
3692 " background-color: #c4c2bd;\n"
3696 ".progressbar:prelight,\n"
3697 ".entry.progressbar {\n"
3698 " background-color: @selected_bg_color;\n"
3699 " border-color: shade (@selected_bg_color, 0.7);\n"
3700 " color: @selected_fg_color;\n"
3703 "GtkCheckButton:hover,\n"
3704 "GtkCheckButton:selected,\n"
3705 "GtkRadioButton:hover,\n"
3706 "GtkRadioButton:selected {\n"
3707 " background-color: shade (@bg_color, 1.05);\n"
3711 ".check:active, .radio:active,\n"
3712 ".check:hover, .radio:hover {\n"
3713 " background-color: @base_color;\n"
3714 " border-color: @fg_color;\n"
3715 " color: @text_color;\n"
3716 " border-style: solid;\n"
3717 " border-width: 1;\n"
3720 ".check:selected, .radio:selected {\n"
3721 " background-color: @selected_bg_color;\n"
3722 " color: @selected_fg_color;\n"
3725 ".menu.check, .menu.radio {\n"
3726 " color: @fg_color;\n"
3730 " background-color: @selected_bg_color;\n"
3731 " border-style: none;\n"
3735 " border-style: outset;\n"
3736 " border-width: 1;\n"
3740 " border-style: inset;\n"
3741 " border-width: 2;\n"
3745 " border-style: outset;\n"
3746 " border-width: 1;\n"
3750 " border-style: inset;\n"
3751 " border-width: 1;\n"
3757 " border-style: outset;\n"
3758 " border-width: 1;\n"
3762 ".menubar:hover {\n"
3763 " background-color: @selected_bg_color;\n"
3764 " color: @selected_fg_color;\n"
3769 ".menu .check:active,\n"
3770 ".menu .radio:active {\n"
3771 " border-style: none;\n"
3774 "GtkSpinButton.button {\n"
3775 " border-width: 1;\n"
3778 ".scale.slider:hover,\n"
3779 "GtkSpinButton.button:hover {\n"
3780 " background-color: shade (@bg_color, 1.05);\n"
3781 " border-color: shade (@bg_color, 0.8);\n"
3784 "GtkToggleButton.button:inconsistent {\n"
3785 " border-style: outset;\n"
3786 " border-width: 1px;\n"
3787 " background-color: shade (@bg_color, 0.9);\n"
3788 " border-color: shade (@bg_color, 0.7);\n"
3791 "GtkLabel:selected {\n"
3792 " background-color: shade (@bg_color, 0.9);\n"
3793 " color: @fg_color;\n"
3796 "GtkLabel:selected:focused {\n"
3797 " background-color: @selected_bg_color;\n"
3798 " color: @selected_fg_color;\n"
3801 ".spinner:active {\n"
3802 " transition: 750ms linear loop;\n"
3806 " background-color: @info_bg_color;\n"
3807 " color: @info_fg_color;\n"
3811 " background-color: @warning_bg_color;\n"
3812 " color: @warning_fg_color;\n"
3816 " background-color: @question_bg_color;\n"
3817 " color: @question_fg_color;\n"
3821 " background-color: @error_bg_color;\n"
3822 " color: @error_fg_color;\n"
3826 provider = gtk_css_provider_new ();
3827 if (!gtk_css_provider_load_from_data (provider, str, -1, NULL))
3829 g_error ("Failed to load the internal default CSS.");
3837 css_provider_get_theme_dir (void)
3842 var = g_getenv ("GTK_DATA_PREFIX");
3845 path = g_build_filename (var, "share", "themes", NULL);
3847 path = g_build_filename (GTK_DATA_PREFIX, "share", "themes", NULL);
3853 * gtk_css_provider_get_named:
3854 * @name: A theme name
3855 * @variant: variant to load, for example, "dark", or %NULL for the default
3857 * Loads a theme from the usual theme paths
3859 * Returns: (transfer none): a #GtkCssProvider with the theme loaded.
3860 * This memory is owned by GTK+, and you must not free it.
3863 gtk_css_provider_get_named (const gchar *name,
3864 const gchar *variant)
3866 static GHashTable *themes = NULL;
3867 GtkCssProvider *provider;
3869 if (G_UNLIKELY (!themes))
3870 themes = g_hash_table_new (g_str_hash, g_str_equal);
3872 provider = g_hash_table_lookup (themes, name);
3876 const gchar *home_dir;
3877 gchar *subpath, *path = NULL;
3880 subpath = g_strdup_printf ("gtk-3.0" G_DIR_SEPARATOR_S "gtk-%s.css", variant);
3882 subpath = g_strdup ("gtk-3.0" G_DIR_SEPARATOR_S "gtk.css");
3884 /* First look in the users home directory
3886 home_dir = g_get_home_dir ();
3889 path = g_build_filename (home_dir, ".themes", name, subpath, NULL);
3891 if (!g_file_test (path, G_FILE_TEST_EXISTS))
3900 gchar *theme_dir = css_provider_get_theme_dir ();
3901 path = g_build_filename (theme_dir, name, subpath, NULL);
3904 if (!g_file_test (path, G_FILE_TEST_EXISTS))
3915 GError *error = NULL;
3917 provider = gtk_css_provider_new ();
3918 gtk_css_provider_load_from_path (provider, path, &error);
3922 g_warning ("Could not load named theme \"%s\": %s", name, error->message);
3923 g_error_free (error);
3925 g_object_unref (provider);
3929 g_hash_table_insert (themes, g_strdup (name), provider);