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 <gdk-pixbuf/gdk-pixbuf.h>
26 #include <cairo-gobject.h>
28 #include "gtkanimationdescription.h"
29 #include "gtk9slice.h"
30 #include "gtkgradient.h"
31 #include "gtkthemingengine.h"
32 #include "gtkstyleprovider.h"
33 #include "gtkcssprovider.h"
34 #include "gtkstylecontextprivate.h"
35 #include "gtkprivate.h"
38 * SECTION:gtkcssprovider
39 * @Short_description: CSS-like styling for widgets
40 * @Title: GtkCssProvider
41 * @See_also: #GtkStyleContext, #GtkStyleProvider
43 * GtkCssProvider is an object implementing the #GtkStyleProvider interface.
44 * It is able to parse <ulink url="http://www.w3.org/TR/CSS2">CSS</ulink>-like
45 * input in order to style widgets.
47 * <refsect2 id="gtkcssprovider-files">
48 * <title>Default files</title>
50 * An application can cause GTK+ to parse a specific CSS style sheet by
51 * calling gtk_css_provider_load_from_file() and adding the provider with
52 * gtk_style_context_add_provider() or gtk_style_context_add_provider_for_screen().
53 * In addition, certain files will be read when GTK+ is initialized. First,
54 * the file <filename><envar>$XDG_CONFIG_HOME</envar>/gtk-3.0/gtk.css</filename>
55 * is loaded if it exists. Then, GTK+ tries to load
56 * <filename><envar>$HOME</envar>/.themes/<replaceable>theme-name</replaceable>/gtk-3.0/gtk.css</filename>,
58 * <filename><replaceable>datadir</replaceable>/share/themes/<replaceable>theme-name</replaceable>/gtk-3.0/gtk.css</filename>,
59 * where <replaceable>theme-name</replaceable> is the name of the current theme
60 * (see the #GtkSettings:gtk-theme-name setting) and <replaceable>datadir</replaceable>
61 * is the prefix configured when GTK+ was compiled, unless overridden by the
62 * <envar>GTK_DATA_PREFIX</envar> environment variable.
65 * <refsect2 id="gtkcssprovider-stylesheets">
66 * <title>Style sheets</title>
68 * The basic structure of the style sheets understood by this provider is
69 * a series of statements, which are either rule sets or '@-rules', separated
73 * A rule set consists of a selector and a declaration block, which is
74 * a series of declarations enclosed in curly braces ({ and }). The
75 * declarations are separated by semicolons (;). Multiple selectors can
76 * share the same declaration block, by putting all the separators in
77 * front of the block, separated by commas.
79 * <example><title>A rule set with two selectors</title>
80 * <programlisting language="text">
81 * GtkButton, GtkEntry {
88 * <refsect2 id="gtkcssprovider-selectors">
89 * <title>Selectors</title>
91 * Selectors work very similar to the way they do in CSS, with widget class
92 * names taking the role of element names, and widget names taking the role
93 * of IDs. When used in a selector, widget names must be prefixed with a
94 * '#' character. The '*' character represents the so-called universal
95 * selector, which matches any widget.
98 * To express more complicated situations, selectors can be combined in
101 * <listitem><para>To require that a widget satisfies several conditions,
102 * combine several selectors into one by concatenating them. E.g.
103 * <literal>GtkButton#button1</literal> matches a GtkButton widget
104 * with the name button1.</para></listitem>
105 * <listitem><para>To only match a widget when it occurs inside some other
106 * widget, write the two selectors after each other, separated by whitespace.
107 * E.g. <literal>GtkToolBar GtkButton</literal> matches GtkButton widgets
108 * that occur inside a GtkToolBar.</para></listitem>
109 * <listitem><para>In the previous example, the GtkButton is matched even
110 * if it occurs deeply nested inside the toolbar. To restrict the match
111 * to direct children of the parent widget, insert a '>' character between
112 * the two selectors. E.g. <literal>GtkNotebook > GtkLabel</literal> matches
113 * GtkLabel widgets that are direct children of a GtkNotebook.</para></listitem>
117 * <title>Widget classes and names in selectors</title>
118 * <programlisting language="text">
119 * /* Theme labels that are descendants of a window */
120 * GtkWindow GtkLabel {
121 * background-color: #898989
124 * /* Theme notebooks, and anything that's within these */
126 * background-color: #a939f0
129 * /* Theme combo boxes, and entries that
130 * are direct children of a notebook */
132 * GtkNotebook > GtkEntry {
134 * background-color: #1209a2
137 * /* Theme any widget within a GtkBin */
142 * /* Theme a label named title-label */
143 * GtkLabel#title-label {
147 * /* Theme any widget named main-entry */
149 * background-color: #f0a810
154 * Widgets may also define style classes, which can be used for matching.
155 * When used in a selector, style classes must be prefixed with a '.'
159 * Refer to the documentation of individual widgets to learn which
160 * style classes they define and see <xref linkend="gtkstylecontext-classes"/>
161 * for a list of all style classes used by GTK+ widgets.
164 * Note that there is some ambiguity in the selector syntax when it comes
165 * to differentiation widget class names from regions. GTK+ currently treats
166 * a string as a widget class name if it contains any uppercase characters
167 * (which should work for more widgets with names like GtkLabel).
170 * <title>Style classes in selectors</title>
171 * <programlisting language="text">
172 * /* Theme all widgets defining the class entry */
174 * color: #39f1f9;
177 * /* Theme spinbuttons' entry */
178 * GtkSpinButton.entry {
184 * In complicated widgets like e.g. a GtkNotebook, it may be desirable
185 * to style different parts of the widget differently. To make this
186 * possible, container widgets may define regions, whose names
187 * may be used for matching in selectors.
190 * Some containers allow to further differentiate between regions by
191 * applying so-called pseudo-classes to the region. For example, the
192 * tab region in GtkNotebook allows to single out the first or last
193 * tab by using the :first-child or :last-child pseudo-class.
194 * When used in selectors, pseudo-classes must be prefixed with a
198 * Refer to the documentation of individual widgets to learn which
199 * regions and pseudo-classes they define and see
200 * <xref linkend="gtkstylecontext-classes"/> for a list of all regions
201 * used by GTK+ widgets.
204 * <title>Regions in selectors</title>
205 * <programlisting language="text">
206 * /* Theme any label within a notebook */
207 * GtkNotebook GtkLabel {
208 * color: #f90192;
211 * /* Theme labels within notebook tabs */
212 * GtkNotebook tab GtkLabel {
213 * color: #703910;
216 * /* Theme labels in the any first notebook
217 * tab, both selectors are equivalent */
218 * GtkNotebook tab:nth-child(first) GtkLabel,
219 * GtkNotebook tab:first-child GtkLabel {
220 * color: #89d012;
225 * Another use of pseudo-classes is to match widgets depending on their
226 * state. This is conceptually similar to the :hover, :active or :focus
227 * pseudo-classes in CSS. The available pseudo-classes for widget states
228 * are :active, :prelight (or :hover), :insensitive, :selected, :focused
232 * <title>Styling specific widget states</title>
233 * <programlisting language="text">
234 * /* Theme active (pressed) buttons */
236 * background-color: #0274d9;
239 * /* Theme buttons with the mouse pointer on it,
240 * both are equivalent */
242 * GtkButton:prelight {
243 * background-color: #3085a9;
246 * /* Theme insensitive widgets, both are equivalent */
249 * background-color: #320a91;
252 * /* Theme selection colors in entries */
253 * GtkEntry:selected {
254 * background-color: #56f9a0;
257 * /* Theme focused labels */
259 * background-color: #b4940f;
262 * /* Theme inconsistent checkbuttons */
263 * GtkCheckButton:inconsistent {
264 * background-color: #20395a;
269 * Widget state pseudoclasses may only apply to the last element
273 * To determine the effective style for a widget, all the matching rule
274 * sets are merged. As in CSS, rules apply by specificity, so the rules
275 * whose selectors more closely match a widget path will take precedence
279 * <refsect2 id="gtkcssprovider-rules">
280 * <title>@ Rules</title>
282 * GTK+'s CSS supports the @import rule, in order to load another
283 * CSS style sheet in addition to the currently parsed one.
286 * <title>Using the @import rule</title>
287 * <programlisting language="text">
288 * @import url ("path/to/common.css");
292 * GTK+ also supports an additional @define-color rule, in order
293 * to define a color name which may be used instead of color numeric
294 * representations. Also see the #GtkSettings:gtk-color-scheme setting
295 * for a way to override the values of these named colors.
298 * <title>Defining colors</title>
299 * <programlisting language="text">
300 * @define-color bg_color #f9a039;
303 * background-color: @bg_color;
308 * <refsect2 id="gtkcssprovider-symbolic-colors">
309 * <title>Symbolic colors</title>
311 * Besides being able to define color names, the CSS parser is also able
312 * to read different color expressions, which can also be nested, providing
313 * a rich language to define colors which are derived from a set of base
317 * <title>Using symbolic colors</title>
318 * <programlisting language="text">
319 * @define-color entry-color shade (@bg_color, 0.7);
322 * background-color: @entry-color;
326 * background-color: mix (@entry-color,
327 * shade (#fff, 0.5),
333 * The various ways to express colors in GTK+ CSS are:
339 * <entry>Syntax</entry>
340 * <entry>Explanation</entry>
341 * <entry>Examples</entry>
346 * <entry>rgb(@r, @g, @b)</entry>
347 * <entry>An opaque color; @r, @g, @b can be either integers between
348 * 0 and 255 or percentages</entry>
349 * <entry><literallayout>rgb(128, 10, 54)
350 * rgb(20%, 30%, 0%)</literallayout></entry>
353 * <entry>rgba(@r, @g, @b, @a)</entry>
354 * <entry>A translucent color; @r, @g, @b are as in the previous row,
355 * @a is a floating point number between 0 and 1</entry>
356 * <entry><literallayout>rgba(255, 255, 0, 0.5)</literallayout></entry>
359 * <entry>#@xxyyzz</entry>
360 * <entry>An opaque color; @xx, @yy, @zz are hexadecimal numbers
361 * specifying @r, @g, @b variants with between 1 and 4
362 * hexadecimal digits per component are allowed</entry>
363 * <entry><literallayout>#ff12ab
364 * #f0c</literallayout></entry>
367 * <entry>@name</entry>
368 * <entry>Reference to a color that has been defined with
369 * @define-color
371 * <entry>@bg_color</entry>
374 * <entry>mix(@color1, @color2, @f)</entry>
375 * <entry>A linear combination of @color1 and @color2. @f is a
376 * floating point number between 0 and 1.</entry>
377 * <entry><literallayout>mix(#ff1e0a, @bg_color, 0.8)</literallayout></entry>
380 * <entry>shade(@color, @f)</entry>
381 * <entry>A lighter or darker variant of @color. @f is a
382 * floating point number.
384 * <entry>shade(@fg_color, 0.5)</entry>
387 * <entry>lighter(@color)</entry>
388 * <entry>A lighter variant of @color</entry>
391 * <entry>darker(@color)</entry>
392 * <entry>A darker variant of @color</entry>
398 * <refsect2 id="gtkcssprovider-gradients">
399 * <title>Gradients</title>
401 * Linear or radial Gradients can be used as background images.
404 * A linear gradient along the line from (@start_x, @start_y) to
405 * (@end_x, @end_y) is specified using the syntax
406 * <literallayout>-gtk-gradient (linear,
407 * @start_x @start_y, @end_x @end_y,
408 * color-stop (@position, @color),
409 * ...)</literallayout>
410 * where @start_x and @end_x can be either a floating point number between
411 * 0 and 1 or one of the special values 'left', 'right' or 'center', @start_y
412 * and @end_y can be either a floating point number between 0 and 1 or one
413 * of the special values 'top', 'bottom' or 'center', @position is a floating
414 * point number between 0 and 1 and @color is a color expression (see above).
415 * The color-stop can be repeated multiple times to add more than one color
416 * stop. 'from (@color)' and 'to (@color)' can be used as abbreviations for
417 * color stops with position 0 and 1, respectively.
420 * <title>A linear gradient</title>
421 * <inlinegraphic fileref="gradient1.png" format="PNG"/>
422 * <para>This gradient was specified with
423 * <literallayout>-gtk-gradient (linear,
424 * left top, right bottom,
425 * from(@yellow), to(@blue))</literallayout></para>
428 * <title>Another linear gradient</title>
429 * <inlinegraphic fileref="gradient2.png" format="PNG"/>
430 * <para>This gradient was specified with
431 * <literallayout>-gtk-gradient (linear,
433 * color-stop(0, @yellow),
434 * color-stop(0.2, @blue),
435 * color-stop(1, #0f0))</literallayout></para>
438 * A radial gradient along the two circles defined by (@start_x, @start_y,
439 * @start_radius) and (@end_x, @end_y, @end_radius) is specified using the
441 * <literallayout>-gtk-gradient (radial,
442 * @start_x @start_y, @start_radius,
443 * @end_x @end_y, @end_radius,
444 * color-stop (@position, @color),
445 * ...)</literallayout>
446 * where @start_radius and @end_radius are floating point numbers and
447 * the other parameters are as before.
450 * <title>A radial gradient</title>
451 * <inlinegraphic fileref="gradient3.png" format="PNG"/>
452 * <para>This gradient was specified with
453 * <literallayout>-gtk-gradient (radial,
456 * from(@yellow), to(@green))</literallayout></para>
459 * <title>Another radial gradient</title>
460 * <inlinegraphic fileref="gradient4.png" format="PNG"/>
461 * <para>This gradient was specified with
462 * <literallayout>-gtk-gradient (radial,
465 * color-stop (0, #f00),
466 * color-stop (0.1, #a0f),
467 * color-stop (0.2, @yellow),
468 * color-stop (1, @green))</literallayout></para>
471 * <refsect2 id="gtkcssprovider-slices">
472 * <title>Border images</title>
474 * Images can be used in 'slices' for the purpose of creating scalable
477 * <inlinegraphic fileref="slices.png" format="PNG"/>
479 * The syntax for specifying border images of this kind is:
480 * <literallayout>url(@path) @top @right @bottom @left [repeat|stretch]? [repeat|stretch]?</literallayout>
481 * The sizes of the 'cut off' portions are specified
482 * with the @top, @right, @bottom and @left parameters.
483 * The 'middle' sections can be repeated or stretched to create
484 * the desired effect, by adding the 'repeat' or 'stretch' options after
485 * the dimensions. If two options are specified, the first one affects
486 * the horizontal behaviour and the second one the vertical behaviour.
487 * If only one option is specified, it affects both.
490 * <title>A border image</title>
491 * <inlinegraphic fileref="border1.png" format="PNG"/>
492 * <para>This border image was specified with
493 * <literallayout>url("gradient1.png") 10 10 10 10</literallayout>
497 * <title>A repeating border image</title>
498 * <inlinegraphic fileref="border2.png" format="PNG"/>
499 * <para>This border image was specified with
500 * <literallayout>url("gradient1.png") 10 10 10 10 repeat</literallayout>
504 * <title>A stretched border image</title>
505 * <inlinegraphic fileref="border3.png" format="PNG"/>
506 * <para>This border image was specified with
507 * <literallayout>url("gradient1.png") 10 10 10 10 stretch</literallayout>
511 * <refsect2 id="gtkcssprovider-transitions">
512 * <para>Styles can specify transitions that will be used to create a gradual
513 * change in the appearance when a widget state changes. The following
514 * syntax is used to specify transitions:
515 * <literallayout>@duration [s|ms] [linear|ease|ease-in|ease-out|ease-in-out] [loop]?</literallayout>
516 * The @duration is the amount of time that the animation will take for
517 * a complete cycle from start to end. If the loop option is given, the
518 * animation will be repated until the state changes again.
519 * The option after the duration determines the transition function from a
520 * small set of predefined functions.
521 * <figure><title>Linear transition</title>
522 * <graphic fileref="linear.png" format="PNG"/>
524 * <figure><title>Ease transition</title>
525 * <graphic fileref="ease.png" format="PNG"/>
527 * <figure><title>Ease-in-out transition</title>
528 * <graphic fileref="ease-in-out.png" format="PNG"/>
530 * <figure><title>Ease-in transition</title>
531 * <graphic fileref="ease-in.png" format="PNG"/>
533 * <figure><title>Ease-out transition</title>
534 * <graphic fileref="ease-out.png" format="PNG"/>
538 * <refsect2 id="gtkcssprovider-properties">
539 * <title>Supported properties</title>
541 * Properties are the part that differ the most to common CSS,
542 * not all properties are supported (some are planned to be
543 * supported eventually, some others are meaningless or don't
544 * map intuitively in a widget based environment).
547 * There is also a difference in shorthand properties, for
548 * example in common CSS it is fine to define a font through
549 * the different @font-family, @font-style, @font-size
550 * properties, meanwhile in GTK+'s CSS only the canonical
551 * @font property is supported.
554 * The currently supported properties are:
560 * <entry>Property name</entry>
561 * <entry>Syntax</entry>
562 * <entry>Maps to</entry>
563 * <entry>Examples</entry>
568 * <entry>engine</entry>
569 * <entry>engine-name</entry>
570 * <entry>#GtkThemingEngine</entry>
571 * <entry>engine: clearlooks;
572 * engine: none; /* use the default (i.e. builtin) engine) */ </entry>
575 * <entry>background-color</entry>
576 * <entry morerows="2">color (see above)</entry>
577 * <entry morerows="2">#GdkRGBA</entry>
578 * <entry morerows="2"><literallayout>background-color: #fff;
579 * color: &color1;
580 * background-color: shade (&color1, 0.5);
581 * color: mix (&color1, #f0f, 0.8);</literallayout>
585 * <entry>color</entry>
588 * <entry>border-color</entry>
591 * <entry>font</entry>
592 * <entry>@family [@style] [@size]</entry>
593 * <entry>#PangoFontDescription</entry>
594 * <entry>font: Sans 15;</entry>
597 * <entry>margin</entry>
598 * <entry morerows="1"><literallayout>@width
599 * @vertical_width @horizontal_width
600 * @top_width @horizontal_width @bottom_width
601 * @top_width @right_width @bottom_width @left_width</literallayout>
603 * <entry morerows="1">#GtkBorder</entry>
604 * <entry morerows="1"><literallayout>margin: 5;
607 * margin: 5 10 3 5;</literallayout>
611 * <entry>padding</entry>
614 * <entry>background-image</entry>
615 * <entry><literallayout>gradient (see above) or
616 * url(@path)</literallayout></entry>
617 * <entry>#cairo_pattern_t</entry>
618 * <entry><literallayout>-gtk-gradient (linear,
619 * left top, right top,
620 * from (#fff), to (#000));
621 * -gtk-gradient (linear, 0.0 0.5, 0.5 1.0,
623 * color-stop (0.5, #f00),
625 * -gtk-gradient (radial,
626 * center center, 0.2,
627 * center center, 0.8,
628 * color-stop (0.0, #fff),
629 * color-stop (1.0, #000));
630 * url ('background.png');</literallayout>
634 * <entry>border-width</entry>
635 * <entry>integer</entry>
636 * <entry>#gint</entry>
637 * <entry>border-width: 5;</entry>
640 * <entry>border-radius</entry>
641 * <entry>integer</entry>
642 * <entry>#gint</entry>
643 * <entry>border-radius: 5;</entry>
646 * <entry>border-style</entry>
647 * <entry>[none|solid|inset|outset]</entry>
648 * <entry>#GtkBorderStyle</entry>
649 * <entry>border-style: solid;</entry>
652 * <entry>border-image</entry>
653 * <entry><literallayout>border image (see above)</literallayout></entry>
654 * <entry>internal use only</entry>
655 * <entry><literallayout>border-image: url("/path/to/image.png") 3 4 3 4 stretch;
656 * border-image: url("/path/to/image.png") 3 4 4 3 repeat stretch;</literallayout>
660 * <entry>transition</entry>
661 * <entry>transition (see above)</entry>
662 * <entry>internal use only</entry>
663 * <entry><literallayout>transition: 150ms ease-in-out;
664 * transition: 1s linear loop;</literallayout>
671 * GtkThemingEngines can register their own, engine-specific style properties
672 * with the function gtk_theming_engine_register_property(). These properties
673 * can be set in CSS like other properties, using a name of the form
674 * <literallayout>-<replaceable>namespace</replaceable>-<replaceable>name</replaceable></literallayout>, where <replaceable>namespace</replaceable> is typically
675 * the name of the theming engine, and <replaceable>name</replaceable> is the
676 * name of the property. Style properties that have been registered by widgets
677 * using gtk_widget_class_install_style_property() can also be set in this
678 * way, using the widget class name for <replaceable>namespace</replaceable>.
681 * <title>Using engine-specific style properties</title>
684 * engine: clearlooks;
686 * -GtkPaned-handle-size: 6;
687 * -clearlooks-colorize-scrollbar: false;
694 typedef struct GtkCssProviderPrivate GtkCssProviderPrivate;
695 typedef struct SelectorElement SelectorElement;
696 typedef struct SelectorPath SelectorPath;
697 typedef struct SelectorStyleInfo SelectorStyleInfo;
698 typedef enum SelectorElementType SelectorElementType;
699 typedef enum CombinatorType CombinatorType;
700 typedef enum ParserScope ParserScope;
701 typedef enum ParserSymbol ParserSymbol;
703 enum SelectorElementType {
712 enum CombinatorType {
713 COMBINATOR_DESCENDANT, /* No direct relation needed */
714 COMBINATOR_CHILD /* Direct child */
717 struct SelectorElement
719 SelectorElementType elem_type;
720 CombinatorType combinator;
730 GtkRegionFlags flags;
742 struct SelectorStyleInfo
748 struct GtkCssProviderPrivate
754 const gchar *value_pos;
756 GHashTable *symbolic_colors;
758 GPtrArray *selectors_info;
760 /* Current parser state */
762 GSList *cur_selectors;
763 GHashTable *cur_properties;
774 /* Extend GtkStateType, since these
775 * values are also used as symbols
778 /* Scope: pseudo-class */
779 SYMBOL_NTH_CHILD = GTK_STATE_FOCUSED + 1,
784 /* Scope: nth-child */
785 SYMBOL_NTH_CHILD_EVEN,
786 SYMBOL_NTH_CHILD_ODD,
787 SYMBOL_NTH_CHILD_FIRST,
788 SYMBOL_NTH_CHILD_LAST
791 static void gtk_css_provider_finalize (GObject *object);
792 static void gtk_css_style_provider_iface_init (GtkStyleProviderIface *iface);
794 static void scanner_apply_scope (GScanner *scanner,
796 static gboolean css_provider_parse_value (GtkCssProvider *css_provider,
797 const gchar *value_str,
800 static gboolean gtk_css_provider_load_from_path_internal (GtkCssProvider *css_provider,
806 gtk_css_provider_error_quark (void)
808 return g_quark_from_static_string ("gtk-css-provider-error-quark");
811 G_DEFINE_TYPE_EXTENDED (GtkCssProvider, gtk_css_provider, G_TYPE_OBJECT, 0,
812 G_IMPLEMENT_INTERFACE (GTK_TYPE_STYLE_PROVIDER,
813 gtk_css_style_provider_iface_init));
816 gtk_css_provider_class_init (GtkCssProviderClass *klass)
818 GObjectClass *object_class = G_OBJECT_CLASS (klass);
820 object_class->finalize = gtk_css_provider_finalize;
822 g_type_class_add_private (object_class, sizeof (GtkCssProviderPrivate));
825 static SelectorPath *
826 selector_path_new (void)
830 path = g_slice_new0 (SelectorPath);
836 static SelectorPath *
837 selector_path_ref (SelectorPath *path)
844 selector_path_unref (SelectorPath *path)
848 if (path->ref_count > 0)
851 while (path->elements)
853 g_slice_free (SelectorElement, path->elements->data);
854 path->elements = g_slist_delete_link (path->elements, path->elements);
857 g_slice_free (SelectorPath, path);
861 selector_path_prepend_type (SelectorPath *path,
862 const gchar *type_name)
864 SelectorElement *elem;
867 elem = g_slice_new (SelectorElement);
868 elem->combinator = COMBINATOR_DESCENDANT;
869 type = g_type_from_name (type_name);
871 if (type == G_TYPE_INVALID)
873 elem->elem_type = SELECTOR_TYPE_NAME;
874 elem->name = g_quark_from_string (type_name);
878 elem->elem_type = SELECTOR_GTYPE;
882 path->elements = g_slist_prepend (path->elements, elem);
886 selector_path_prepend_glob (SelectorPath *path)
888 SelectorElement *elem;
890 elem = g_slice_new (SelectorElement);
891 elem->elem_type = SELECTOR_GLOB;
892 elem->combinator = COMBINATOR_DESCENDANT;
894 path->elements = g_slist_prepend (path->elements, elem);
898 selector_path_prepend_region (SelectorPath *path,
900 GtkRegionFlags flags)
902 SelectorElement *elem;
904 elem = g_slice_new (SelectorElement);
905 elem->combinator = COMBINATOR_DESCENDANT;
906 elem->elem_type = SELECTOR_REGION;
908 elem->region.name = g_quark_from_string (name);
909 elem->region.flags = flags;
911 path->elements = g_slist_prepend (path->elements, elem);
915 selector_path_prepend_name (SelectorPath *path,
918 SelectorElement *elem;
920 elem = g_slice_new (SelectorElement);
921 elem->combinator = COMBINATOR_DESCENDANT;
922 elem->elem_type = SELECTOR_NAME;
924 elem->name = g_quark_from_string (name);
926 path->elements = g_slist_prepend (path->elements, elem);
930 selector_path_prepend_class (SelectorPath *path,
933 SelectorElement *elem;
935 elem = g_slice_new (SelectorElement);
936 elem->combinator = COMBINATOR_DESCENDANT;
937 elem->elem_type = SELECTOR_CLASS;
939 elem->name = g_quark_from_string (name);
941 path->elements = g_slist_prepend (path->elements, elem);
945 selector_path_prepend_combinator (SelectorPath *path,
946 CombinatorType combinator)
948 SelectorElement *elem;
950 g_assert (path->elements != NULL);
952 /* It is actually stored in the last element */
953 elem = path->elements->data;
954 elem->combinator = combinator;
958 selector_path_depth (SelectorPath *path)
960 return g_slist_length (path->elements);
963 static SelectorStyleInfo *
964 selector_style_info_new (SelectorPath *path)
966 SelectorStyleInfo *info;
968 info = g_slice_new0 (SelectorStyleInfo);
969 info->path = selector_path_ref (path);
975 selector_style_info_free (SelectorStyleInfo *info)
978 g_hash_table_unref (info->style);
981 selector_path_unref (info->path);
983 g_slice_free (SelectorStyleInfo, info);
987 selector_style_info_set_style (SelectorStyleInfo *info,
991 g_hash_table_unref (info->style);
994 info->style = g_hash_table_ref (style);
1000 create_scanner (void)
1004 scanner = g_scanner_new (NULL);
1006 g_scanner_scope_add_symbol (scanner, SCOPE_PSEUDO_CLASS, "active", GUINT_TO_POINTER (GTK_STATE_ACTIVE));
1007 g_scanner_scope_add_symbol (scanner, SCOPE_PSEUDO_CLASS, "prelight", GUINT_TO_POINTER (GTK_STATE_PRELIGHT));
1008 g_scanner_scope_add_symbol (scanner, SCOPE_PSEUDO_CLASS, "hover", GUINT_TO_POINTER (GTK_STATE_PRELIGHT));
1009 g_scanner_scope_add_symbol (scanner, SCOPE_PSEUDO_CLASS, "selected", GUINT_TO_POINTER (GTK_STATE_SELECTED));
1010 g_scanner_scope_add_symbol (scanner, SCOPE_PSEUDO_CLASS, "insensitive", GUINT_TO_POINTER (GTK_STATE_INSENSITIVE));
1011 g_scanner_scope_add_symbol (scanner, SCOPE_PSEUDO_CLASS, "inconsistent", GUINT_TO_POINTER (GTK_STATE_INCONSISTENT));
1012 g_scanner_scope_add_symbol (scanner, SCOPE_PSEUDO_CLASS, "focused", GUINT_TO_POINTER (GTK_STATE_FOCUSED));
1013 g_scanner_scope_add_symbol (scanner, SCOPE_PSEUDO_CLASS, "focus", GUINT_TO_POINTER (GTK_STATE_FOCUSED));
1015 g_scanner_scope_add_symbol (scanner, SCOPE_PSEUDO_CLASS, "nth-child", GUINT_TO_POINTER (SYMBOL_NTH_CHILD));
1016 g_scanner_scope_add_symbol (scanner, SCOPE_PSEUDO_CLASS, "first-child", GUINT_TO_POINTER (SYMBOL_FIRST_CHILD));
1017 g_scanner_scope_add_symbol (scanner, SCOPE_PSEUDO_CLASS, "last-child", GUINT_TO_POINTER (SYMBOL_LAST_CHILD));
1018 g_scanner_scope_add_symbol (scanner, SCOPE_PSEUDO_CLASS, "sorted", GUINT_TO_POINTER (SYMBOL_SORTED_CHILD));
1020 g_scanner_scope_add_symbol (scanner, SCOPE_NTH_CHILD, "even", GUINT_TO_POINTER (SYMBOL_NTH_CHILD_EVEN));
1021 g_scanner_scope_add_symbol (scanner, SCOPE_NTH_CHILD, "odd", GUINT_TO_POINTER (SYMBOL_NTH_CHILD_ODD));
1022 g_scanner_scope_add_symbol (scanner, SCOPE_NTH_CHILD, "first", GUINT_TO_POINTER (SYMBOL_NTH_CHILD_FIRST));
1023 g_scanner_scope_add_symbol (scanner, SCOPE_NTH_CHILD, "last", GUINT_TO_POINTER (SYMBOL_NTH_CHILD_LAST));
1025 scanner_apply_scope (scanner, SCOPE_SELECTOR);
1031 gtk_css_provider_init (GtkCssProvider *css_provider)
1033 GtkCssProviderPrivate *priv;
1035 priv = css_provider->priv = G_TYPE_INSTANCE_GET_PRIVATE (css_provider,
1036 GTK_TYPE_CSS_PROVIDER,
1037 GtkCssProviderPrivate);
1039 priv->selectors_info = g_ptr_array_new_with_free_func ((GDestroyNotify) selector_style_info_free);
1040 priv->scanner = create_scanner ();
1042 priv->symbolic_colors = g_hash_table_new_full (g_str_hash, g_str_equal,
1043 (GDestroyNotify) g_free,
1044 (GDestroyNotify) gtk_symbolic_color_unref);
1047 typedef struct ComparePathData ComparePathData;
1049 struct ComparePathData
1057 compare_selector_element (GtkWidgetPath *path,
1059 SelectorElement *elem,
1064 if (elem->elem_type == SELECTOR_TYPE_NAME)
1066 const gchar *type_name;
1067 GType resolved_type;
1069 /* Resolve the type name */
1070 type_name = g_quark_to_string (elem->name);
1071 resolved_type = g_type_from_name (type_name);
1073 if (resolved_type == G_TYPE_INVALID)
1075 /* Type couldn't be resolved, so the selector
1076 * clearly doesn't affect the given widget path
1081 elem->elem_type = SELECTOR_GTYPE;
1082 elem->type = resolved_type;
1085 if (elem->elem_type == SELECTOR_GTYPE)
1089 type = gtk_widget_path_iter_get_object_type (path, index);
1091 if (!g_type_is_a (type, elem->type))
1094 if (type == elem->type)
1098 GType parent = type;
1102 while ((parent = g_type_parent (parent)) != G_TYPE_INVALID)
1104 if (parent == elem->type)
1111 g_warning ("Hierarchy is higher than expected.");
1119 else if (elem->elem_type == SELECTOR_REGION)
1121 GtkRegionFlags flags;
1123 if (!gtk_widget_path_iter_has_qregion (path, index,
1128 if (elem->region.flags != 0 &&
1129 (flags & elem->region.flags) == 0)
1135 else if (elem->elem_type == SELECTOR_GLOB)
1137 /* Treat as lowest matching type */
1141 else if (elem->elem_type == SELECTOR_NAME)
1143 if (!gtk_widget_path_iter_has_qname (path, index, elem->name))
1149 else if (elem->elem_type == SELECTOR_CLASS)
1151 if (!gtk_widget_path_iter_has_qclass (path, index, elem->name))
1162 compare_selector (GtkWidgetPath *path,
1163 SelectorPath *selector)
1165 GSList *elements = selector->elements;
1166 gboolean match = TRUE, first = TRUE, first_match = FALSE;
1170 i = gtk_widget_path_length (path) - 1;
1172 while (elements && match && i >= 0)
1174 SelectorElement *elem;
1177 elem = elements->data;
1179 match = compare_selector_element (path, i, elem, &elem_score);
1184 /* Only move on to the next index if there is no match
1185 * with the current element (whether to continue or not
1186 * handled right after in the combinator check), or a
1187 * GType or glob has just been matched.
1189 * Region and widget names do not trigger this because
1190 * the next element in the selector path could also be
1191 * related to the same index.
1194 (elem->elem_type == SELECTOR_GTYPE ||
1195 elem->elem_type == SELECTOR_GLOB))
1199 elem->elem_type != SELECTOR_TYPE_NAME &&
1200 elem->combinator == COMBINATOR_DESCENDANT)
1202 /* With descendant combinators there may
1203 * be intermediate chidren in the hierarchy
1208 elements = elements->next;
1212 /* Only 4 bits are actually used */
1214 score |= elem_score;
1220 /* If there are pending selector
1221 * elements to compare, it's not
1229 else if (first_match)
1231 /* Assign more weight to these selectors
1232 * that matched right from the first element.
1240 typedef struct StylePriorityInfo StylePriorityInfo;
1242 struct StylePriorityInfo
1246 GtkStateFlags state;
1250 css_provider_get_selectors (GtkCssProvider *css_provider,
1251 GtkWidgetPath *path)
1253 GtkCssProviderPrivate *priv;
1254 GArray *priority_info;
1257 priv = css_provider->priv;
1258 priority_info = g_array_new (FALSE, FALSE, sizeof (StylePriorityInfo));
1260 for (i = 0; i < priv->selectors_info->len; i++)
1262 SelectorStyleInfo *info;
1263 StylePriorityInfo new;
1264 gboolean added = FALSE;
1267 info = g_ptr_array_index (priv->selectors_info, i);
1268 score = compare_selector (path, info->path);
1274 new.style = info->style;
1275 new.state = info->path->state;
1277 for (j = 0; j < priority_info->len; j++)
1279 StylePriorityInfo *cur;
1281 cur = &g_array_index (priority_info, StylePriorityInfo, j);
1283 if (cur->score > new.score)
1285 g_array_insert_val (priority_info, j, new);
1292 g_array_append_val (priority_info, new);
1295 return priority_info;
1299 css_provider_dump_symbolic_colors (GtkCssProvider *css_provider,
1300 GtkStyleProperties *props)
1302 GtkCssProviderPrivate *priv;
1303 GHashTableIter iter;
1304 gpointer key, value;
1306 priv = css_provider->priv;
1307 g_hash_table_iter_init (&iter, priv->symbolic_colors);
1309 while (g_hash_table_iter_next (&iter, &key, &value))
1312 GtkSymbolicColor *color;
1317 gtk_style_properties_map_color (props, name, color);
1321 static GtkStyleProperties *
1322 gtk_css_provider_get_style (GtkStyleProvider *provider,
1323 GtkWidgetPath *path)
1325 GtkCssProvider *css_provider;
1326 GtkStyleProperties *props;
1327 GArray *priority_info;
1330 css_provider = GTK_CSS_PROVIDER (provider);
1331 props = gtk_style_properties_new ();
1333 css_provider_dump_symbolic_colors (css_provider, props);
1334 priority_info = css_provider_get_selectors (css_provider, path);
1336 for (i = 0; i < priority_info->len; i++)
1338 StylePriorityInfo *info;
1339 GHashTableIter iter;
1340 gpointer key, value;
1342 info = &g_array_index (priority_info, StylePriorityInfo, i);
1343 g_hash_table_iter_init (&iter, info->style);
1345 while (g_hash_table_iter_next (&iter, &key, &value))
1349 /* Properties starting with '-' may be both widget style properties
1350 * or custom properties from the theming engine, so check whether
1351 * the type is registered or not.
1353 if (prop[0] == '-' &&
1354 !gtk_style_properties_lookup_property (prop, NULL, NULL))
1357 gtk_style_properties_set_property (props, key, info->state, value);
1361 g_array_free (priority_info, TRUE);
1367 gtk_css_provider_get_style_property (GtkStyleProvider *provider,
1368 GtkWidgetPath *path,
1369 GtkStateFlags state,
1373 GArray *priority_info;
1374 gboolean found = FALSE;
1378 prop_name = g_strdup_printf ("-%s-%s",
1379 g_type_name (pspec->owner_type),
1382 priority_info = css_provider_get_selectors (GTK_CSS_PROVIDER (provider), path);
1384 for (i = priority_info->len - 1; i >= 0; i--)
1386 StylePriorityInfo *info;
1389 info = &g_array_index (priority_info, StylePriorityInfo, i);
1390 val = g_hash_table_lookup (info->style, prop_name);
1393 (info->state == 0 ||
1394 info->state == state ||
1395 ((info->state & state) != 0 &&
1396 (info->state & ~(state)) == 0)))
1398 const gchar *val_str;
1400 val_str = g_value_get_string (val);
1403 css_provider_parse_value (GTK_CSS_PROVIDER (provider), val_str, value, NULL);
1408 g_array_free (priority_info, TRUE);
1415 gtk_css_style_provider_iface_init (GtkStyleProviderIface *iface)
1417 iface->get_style = gtk_css_provider_get_style;
1418 iface->get_style_property = gtk_css_provider_get_style_property;
1422 gtk_css_provider_finalize (GObject *object)
1424 GtkCssProvider *css_provider;
1425 GtkCssProviderPrivate *priv;
1427 css_provider = GTK_CSS_PROVIDER (object);
1428 priv = css_provider->priv;
1430 g_scanner_destroy (priv->scanner);
1431 g_free (priv->filename);
1433 g_ptr_array_free (priv->selectors_info, TRUE);
1435 g_slist_foreach (priv->cur_selectors, (GFunc) selector_path_unref, NULL);
1436 g_slist_free (priv->cur_selectors);
1438 if (priv->cur_properties)
1439 g_hash_table_unref (priv->cur_properties);
1440 if (priv->symbolic_colors)
1441 g_hash_table_destroy (priv->symbolic_colors);
1443 G_OBJECT_CLASS (gtk_css_provider_parent_class)->finalize (object);
1447 * gtk_css_provider_new:
1449 * Returns a newly created #GtkCssProvider.
1451 * Returns: A new #GtkCssProvider
1454 gtk_css_provider_new (void)
1456 return g_object_new (GTK_TYPE_CSS_PROVIDER, NULL);
1460 property_value_free (GValue *value)
1462 if (G_IS_VALUE (value))
1463 g_value_unset (value);
1465 g_slice_free (GValue, value);
1469 scanner_apply_scope (GScanner *scanner,
1472 g_scanner_set_scope (scanner, scope);
1474 if (scope == SCOPE_VALUE)
1476 scanner->config->cset_identifier_first = G_CSET_a_2_z G_CSET_A_2_Z G_CSET_DIGITS "@#-_";
1477 scanner->config->cset_identifier_nth = G_CSET_a_2_z G_CSET_A_2_Z G_CSET_DIGITS "@#-_ +(),.%\t\n'/\"";
1478 scanner->config->scan_identifier_1char = TRUE;
1480 else if (scope == SCOPE_SELECTOR)
1482 scanner->config->cset_identifier_first = G_CSET_a_2_z G_CSET_A_2_Z "*@";
1483 scanner->config->cset_identifier_nth = G_CSET_a_2_z G_CSET_A_2_Z G_CSET_DIGITS "-_#.";
1484 scanner->config->scan_identifier_1char = TRUE;
1486 else if (scope == SCOPE_PSEUDO_CLASS ||
1487 scope == SCOPE_NTH_CHILD ||
1488 scope == SCOPE_DECLARATION)
1490 scanner->config->cset_identifier_first = G_CSET_a_2_z G_CSET_A_2_Z "-_";
1491 scanner->config->cset_identifier_nth = G_CSET_a_2_z G_CSET_A_2_Z G_CSET_DIGITS "-_";
1492 scanner->config->scan_identifier_1char = FALSE;
1495 g_assert_not_reached ();
1497 scanner->config->scan_float = FALSE;
1498 scanner->config->cpair_comment_single = NULL;
1502 css_provider_push_scope (GtkCssProvider *css_provider,
1505 GtkCssProviderPrivate *priv;
1507 priv = css_provider->priv;
1508 priv->state = g_slist_prepend (priv->state, GUINT_TO_POINTER (scope));
1510 scanner_apply_scope (priv->scanner, scope);
1514 css_provider_pop_scope (GtkCssProvider *css_provider)
1516 GtkCssProviderPrivate *priv;
1517 ParserScope scope = SCOPE_SELECTOR;
1519 priv = css_provider->priv;
1523 g_warning ("Push/pop calls to parser scope aren't paired");
1524 scanner_apply_scope (priv->scanner, SCOPE_SELECTOR);
1525 return SCOPE_SELECTOR;
1528 priv->state = g_slist_delete_link (priv->state, priv->state);
1530 /* Fetch new scope */
1532 scope = GPOINTER_TO_INT (priv->state->data);
1534 scanner_apply_scope (priv->scanner, scope);
1540 css_provider_reset_parser (GtkCssProvider *css_provider)
1542 GtkCssProviderPrivate *priv;
1544 priv = css_provider->priv;
1546 g_slist_free (priv->state);
1549 scanner_apply_scope (priv->scanner, SCOPE_SELECTOR);
1550 priv->scanner->user_data = NULL;
1551 priv->value_pos = NULL;
1553 g_slist_foreach (priv->cur_selectors, (GFunc) selector_path_unref, NULL);
1554 g_slist_free (priv->cur_selectors);
1555 priv->cur_selectors = NULL;
1557 if (priv->cur_properties)
1558 g_hash_table_unref (priv->cur_properties);
1560 priv->cur_properties = g_hash_table_new_full (g_str_hash,
1562 (GDestroyNotify) g_free,
1563 (GDestroyNotify) property_value_free);
1567 css_provider_commit (GtkCssProvider *css_provider)
1569 GtkCssProviderPrivate *priv;
1572 priv = css_provider->priv;
1573 l = priv->cur_selectors;
1577 SelectorPath *path = l->data;
1578 SelectorStyleInfo *info;
1580 info = selector_style_info_new (path);
1581 selector_style_info_set_style (info, priv->cur_properties);
1583 g_ptr_array_add (priv->selectors_info, info);
1589 parse_nth_child (GtkCssProvider *css_provider,
1591 GtkRegionFlags *flags)
1593 ParserSymbol symbol;
1595 g_scanner_get_next_token (scanner);
1597 if (scanner->token != G_TOKEN_SYMBOL)
1598 return G_TOKEN_SYMBOL;
1600 symbol = GPOINTER_TO_INT (scanner->value.v_symbol);
1602 if (symbol == SYMBOL_NTH_CHILD)
1604 g_scanner_get_next_token (scanner);
1606 if (scanner->token != G_TOKEN_LEFT_PAREN)
1607 return G_TOKEN_LEFT_PAREN;
1609 css_provider_push_scope (css_provider, SCOPE_NTH_CHILD);
1610 g_scanner_get_next_token (scanner);
1612 if (scanner->token != G_TOKEN_SYMBOL)
1613 return G_TOKEN_SYMBOL;
1615 symbol = GPOINTER_TO_INT (scanner->value.v_symbol);
1619 case SYMBOL_NTH_CHILD_EVEN:
1620 *flags = GTK_REGION_EVEN;
1622 case SYMBOL_NTH_CHILD_ODD:
1623 *flags = GTK_REGION_ODD;
1625 case SYMBOL_NTH_CHILD_FIRST:
1626 *flags = GTK_REGION_FIRST;
1628 case SYMBOL_NTH_CHILD_LAST:
1629 *flags = GTK_REGION_LAST;
1635 g_scanner_get_next_token (scanner);
1637 if (scanner->token != G_TOKEN_RIGHT_PAREN)
1638 return G_TOKEN_RIGHT_PAREN;
1640 css_provider_pop_scope (css_provider);
1642 else if (symbol == SYMBOL_FIRST_CHILD)
1643 *flags = GTK_REGION_FIRST;
1644 else if (symbol == SYMBOL_LAST_CHILD)
1645 *flags = GTK_REGION_LAST;
1646 else if (symbol == SYMBOL_SORTED_CHILD)
1647 *flags = GTK_REGION_SORTED;
1651 return G_TOKEN_SYMBOL;
1654 return G_TOKEN_NONE;
1658 parse_pseudo_class (GtkCssProvider *css_provider,
1660 SelectorPath *selector)
1664 g_scanner_get_next_token (scanner);
1666 if (scanner->token != G_TOKEN_SYMBOL)
1667 return G_TOKEN_SYMBOL;
1669 state = GPOINTER_TO_INT (scanner->value.v_symbol);
1673 case GTK_STATE_ACTIVE:
1674 selector->state |= GTK_STATE_FLAG_ACTIVE;
1676 case GTK_STATE_PRELIGHT:
1677 selector->state |= GTK_STATE_FLAG_PRELIGHT;
1679 case GTK_STATE_SELECTED:
1680 selector->state |= GTK_STATE_FLAG_SELECTED;
1682 case GTK_STATE_INSENSITIVE:
1683 selector->state |= GTK_STATE_FLAG_INSENSITIVE;
1685 case GTK_STATE_INCONSISTENT:
1686 selector->state |= GTK_STATE_FLAG_INCONSISTENT;
1688 case GTK_STATE_FOCUSED:
1689 selector->state |= GTK_STATE_FLAG_FOCUSED;
1692 return G_TOKEN_SYMBOL;
1695 return G_TOKEN_NONE;
1698 /* Parses a number of concatenated classes */
1700 parse_classes (SelectorPath *path,
1705 if ((pos = strchr (str, '.')) != NULL)
1707 /* Leave the last class to the call after the loop */
1711 selector_path_prepend_class (path, str);
1714 pos = strchr (str, '.');
1718 selector_path_prepend_class (path, str);
1722 is_widget_class_name (const gchar *str)
1724 /* Do a pretty lax check here, not all
1725 * widget class names contain only CamelCase
1726 * (gtkmm widgets don't), but at least part of
1727 * the name will be CamelCase, so check for
1728 * the first uppercase char
1732 if (g_ascii_isupper (*str))
1742 parse_selector (GtkCssProvider *css_provider,
1744 SelectorPath **selector_out)
1748 path = selector_path_new ();
1749 *selector_out = path;
1751 if (scanner->token != ':' &&
1752 scanner->token != '#' &&
1753 scanner->token != '.' &&
1754 scanner->token != G_TOKEN_IDENTIFIER)
1755 return G_TOKEN_IDENTIFIER;
1757 while (scanner->token == '#' ||
1758 scanner->token == '.' ||
1759 scanner->token == G_TOKEN_IDENTIFIER)
1761 if (scanner->token == '#' ||
1762 scanner->token == '.')
1767 is_class = (scanner->token == '.');
1769 g_scanner_get_next_token (scanner);
1771 if (scanner->token != G_TOKEN_IDENTIFIER)
1772 return G_TOKEN_IDENTIFIER;
1774 selector_path_prepend_glob (path);
1775 selector_path_prepend_combinator (path, COMBINATOR_CHILD);
1778 parse_classes (path, scanner->value.v_identifier);
1781 if ((pos = strchr (scanner->value.v_identifier, '.')) != NULL)
1784 selector_path_prepend_name (path, scanner->value.v_identifier);
1786 /* Parse any remaining classes */
1788 parse_classes (path, pos + 1);
1791 else if (is_widget_class_name (scanner->value.v_identifier))
1795 if ((pos = strchr (scanner->value.v_identifier, '#')) != NULL ||
1796 (pos = strchr (scanner->value.v_identifier, '.')) != NULL)
1798 gchar *type_name, *name;
1801 is_class = (*pos == '.');
1803 /* Widget type and name/class put together */
1806 type_name = scanner->value.v_identifier;
1808 selector_path_prepend_type (path, type_name);
1810 /* This is only so there is a direct relationship
1811 * between widget type and its name.
1813 selector_path_prepend_combinator (path, COMBINATOR_CHILD);
1816 parse_classes (path, name);
1819 if ((pos = strchr (name, '.')) != NULL)
1822 selector_path_prepend_name (path, name);
1824 /* Parse any remaining classes */
1826 parse_classes (path, pos + 1);
1830 selector_path_prepend_type (path, scanner->value.v_identifier);
1832 else if (_gtk_style_context_check_region_name (scanner->value.v_identifier))
1834 GtkRegionFlags flags = 0;
1837 region_name = g_strdup (scanner->value.v_identifier);
1839 if (g_scanner_peek_next_token (scanner) == ':')
1841 ParserSymbol symbol;
1843 g_scanner_get_next_token (scanner);
1844 css_provider_push_scope (css_provider, SCOPE_PSEUDO_CLASS);
1846 /* Check for the next token being nth-child, parse in that
1847 * case, and fallback into common state parsing if not.
1849 if (g_scanner_peek_next_token (scanner) != G_TOKEN_SYMBOL)
1850 return G_TOKEN_SYMBOL;
1852 symbol = GPOINTER_TO_INT (scanner->next_value.v_symbol);
1854 if (symbol == SYMBOL_FIRST_CHILD ||
1855 symbol == SYMBOL_LAST_CHILD ||
1856 symbol == SYMBOL_NTH_CHILD ||
1857 symbol == SYMBOL_SORTED_CHILD)
1861 if ((token = parse_nth_child (css_provider, scanner, &flags)) != G_TOKEN_NONE)
1864 css_provider_pop_scope (css_provider);
1868 css_provider_pop_scope (css_provider);
1869 selector_path_prepend_region (path, region_name, 0);
1870 g_free (region_name);
1875 selector_path_prepend_region (path, region_name, flags);
1876 g_free (region_name);
1878 else if (scanner->value.v_identifier[0] == '*')
1879 selector_path_prepend_glob (path);
1881 return G_TOKEN_IDENTIFIER;
1883 g_scanner_get_next_token (scanner);
1885 if (scanner->token == '>')
1887 selector_path_prepend_combinator (path, COMBINATOR_CHILD);
1888 g_scanner_get_next_token (scanner);
1892 if (scanner->token == ':')
1894 /* Add glob selector if path is empty */
1895 if (selector_path_depth (path) == 0)
1896 selector_path_prepend_glob (path);
1898 css_provider_push_scope (css_provider, SCOPE_PSEUDO_CLASS);
1900 while (scanner->token == ':')
1904 if ((token = parse_pseudo_class (css_provider, scanner, path)) != G_TOKEN_NONE)
1907 g_scanner_get_next_token (scanner);
1910 css_provider_pop_scope (css_provider);
1913 return G_TOKEN_NONE;
1916 #define SKIP_SPACES(s) while (s[0] == ' ' || s[0] == '\t' || s[0] == '\n') s++;
1917 #define SKIP_SPACES_BACK(s) while (s[0] == ' ' || s[0] == '\t' || s[0] == '\n') s--;
1919 static GtkSymbolicColor *
1920 symbolic_color_parse_str (const gchar *string,
1923 GtkSymbolicColor *symbolic_color = NULL;
1926 str = (gchar *) string;
1937 while (*end == '-' || *end == '_' || g_ascii_isalpha (*end))
1940 name = g_strndup (str, end - str);
1941 symbolic_color = gtk_symbolic_color_new_name (name);
1944 *end_ptr = (gchar *) end;
1946 else if (g_str_has_prefix (str, "lighter") ||
1947 g_str_has_prefix (str, "darker"))
1949 GtkSymbolicColor *param_color;
1950 gboolean is_lighter = FALSE;
1952 is_lighter = g_str_has_prefix (str, "lighter");
1955 str += strlen ("lighter");
1957 str += strlen ("darker");
1963 *end_ptr = (gchar *) str;
1969 param_color = symbolic_color_parse_str (str, end_ptr);
1976 *end_ptr = (gchar *) str;
1980 gtk_symbolic_color_unref (param_color);
1985 symbolic_color = gtk_symbolic_color_new_shade (param_color, 1.3);
1987 symbolic_color = gtk_symbolic_color_new_shade (param_color, 0.7);
1989 gtk_symbolic_color_unref (param_color);
1992 else if (g_str_has_prefix (str, "shade") ||
1993 g_str_has_prefix (str, "alpha"))
1995 GtkSymbolicColor *param_color;
1996 gboolean is_shade = FALSE;
1999 is_shade = g_str_has_prefix (str, "shade");
2002 str += strlen ("shade");
2004 str += strlen ("alpha");
2010 *end_ptr = (gchar *) str;
2016 param_color = symbolic_color_parse_str (str, end_ptr);
2026 gtk_symbolic_color_unref (param_color);
2027 *end_ptr = (gchar *) str;
2033 factor = g_ascii_strtod (str, end_ptr);
2037 *end_ptr = (gchar *) str;
2041 gtk_symbolic_color_unref (param_color);
2046 symbolic_color = gtk_symbolic_color_new_shade (param_color, factor);
2048 symbolic_color = gtk_symbolic_color_new_alpha (param_color, factor);
2050 gtk_symbolic_color_unref (param_color);
2053 else if (g_str_has_prefix (str, "mix"))
2055 GtkSymbolicColor *color1, *color2;
2058 str += strlen ("mix");
2063 *end_ptr = (gchar *) str;
2069 color1 = symbolic_color_parse_str (str, end_ptr);
2079 gtk_symbolic_color_unref (color1);
2080 *end_ptr = (gchar *) str;
2086 color2 = symbolic_color_parse_str (str, end_ptr);
2088 if (!color2 || *end_ptr[0] != ',')
2090 gtk_symbolic_color_unref (color1);
2099 gtk_symbolic_color_unref (color1);
2100 gtk_symbolic_color_unref (color2);
2101 *end_ptr = (gchar *) str;
2107 factor = g_ascii_strtod (str, end_ptr);
2111 *end_ptr = (gchar *) str;
2115 gtk_symbolic_color_unref (color1);
2116 gtk_symbolic_color_unref (color2);
2120 symbolic_color = gtk_symbolic_color_new_mix (color1, color2, factor);
2121 gtk_symbolic_color_unref (color1);
2122 gtk_symbolic_color_unref (color2);
2135 /* Color in hex format */
2136 while (g_ascii_isxdigit (*end))
2139 else if (g_str_has_prefix (str, "rgb"))
2141 /* color in rgb/rgba format */
2142 while (*end != ')' && *end != '\0')
2151 while (*end != '\0' &&
2152 (g_ascii_isalnum (*end) || *end == ' '))
2156 color_str = g_strndup (str, end - str);
2157 *end_ptr = (gchar *) end;
2159 if (!gdk_rgba_parse (&color, color_str))
2165 symbolic_color = gtk_symbolic_color_new_literal (&color);
2169 return symbolic_color;
2172 static GtkSymbolicColor *
2173 symbolic_color_parse (const gchar *str,
2176 GtkSymbolicColor *color;
2179 color = symbolic_color_parse_str (str, &end);
2183 g_set_error_literal (error,
2184 GTK_CSS_PROVIDER_ERROR,
2185 GTK_CSS_PROVIDER_ERROR_FAILED,
2186 "Could not parse symbolic color");
2190 gtk_symbolic_color_unref (color);
2198 static GtkGradient *
2199 gradient_parse_str (const gchar *str,
2202 GtkGradient *gradient = NULL;
2207 if (g_str_has_prefix (str, "-gtk-gradient"))
2209 cairo_pattern_type_t type;
2211 str += strlen ("-gtk-gradient");
2216 *end_ptr = (gchar *) str;
2223 /* Parse gradient type */
2224 if (g_str_has_prefix (str, "linear"))
2226 type = CAIRO_PATTERN_TYPE_LINEAR;
2227 str += strlen ("linear");
2229 else if (g_str_has_prefix (str, "radial"))
2231 type = CAIRO_PATTERN_TYPE_RADIAL;
2232 str += strlen ("radial");
2236 *end_ptr = (gchar *) str;
2242 /* Parse start/stop position parameters */
2243 for (i = 0; i < 2; i++)
2247 *end_ptr = (gchar *) str;
2254 if (strncmp (str, "left", 4) == 0)
2257 str += strlen ("left");
2259 else if (strncmp (str, "right", 5) == 0)
2262 str += strlen ("right");
2264 else if (strncmp (str, "center", 6) == 0)
2266 coords[i * 3] = 0.5;
2267 str += strlen ("center");
2271 coords[i * 3] = g_ascii_strtod (str, &end);
2275 *end_ptr = (gchar *) str;
2284 if (strncmp (str, "top", 3) == 0)
2286 coords[(i * 3) + 1] = 0;
2287 str += strlen ("top");
2289 else if (strncmp (str, "bottom", 6) == 0)
2291 coords[(i * 3) + 1] = 1;
2292 str += strlen ("bottom");
2294 else if (strncmp (str, "center", 6) == 0)
2296 coords[(i * 3) + 1] = 0.5;
2297 str += strlen ("center");
2301 coords[(i * 3) + 1] = g_ascii_strtod (str, &end);
2305 *end_ptr = (gchar *) str;
2314 if (type == CAIRO_PATTERN_TYPE_RADIAL)
2319 *end_ptr = (gchar *) str;
2326 coords[(i * 3) + 2] = g_ascii_strtod (str, &end);
2333 if (type == CAIRO_PATTERN_TYPE_LINEAR)
2334 gradient = gtk_gradient_new_linear (coords[0], coords[1], coords[3], coords[4]);
2336 gradient = gtk_gradient_new_radial (coords[0], coords[1], coords[2],
2337 coords[3], coords[4], coords[5]);
2341 GtkSymbolicColor *color;
2346 *end_ptr = (gchar *) str;
2353 if (g_str_has_prefix (str, "from"))
2356 str += strlen ("from");
2361 *end_ptr = (gchar *) str;
2365 else if (g_str_has_prefix (str, "to"))
2368 str += strlen ("to");
2373 *end_ptr = (gchar *) str;
2377 else if (g_str_has_prefix (str, "color-stop"))
2379 str += strlen ("color-stop");
2384 *end_ptr = (gchar *) str;
2391 position = g_ascii_strtod (str, &end);
2398 *end_ptr = (gchar *) str;
2404 *end_ptr = (gchar *) str;
2411 color = symbolic_color_parse_str (str, &end);
2418 *end_ptr = (gchar *) str;
2427 gtk_gradient_add_color_stop (gradient, position, color);
2428 gtk_symbolic_color_unref (color);
2434 *end_ptr = (gchar *) str;
2441 *end_ptr = (gchar *) str;
2447 path_parse_str (GtkCssProvider *css_provider,
2453 const gchar *start, *end;
2456 if (g_str_has_prefix (str, "url"))
2458 str += strlen ("url");
2463 *end_ptr = (gchar *) str;
2467 chr = strchr (str, ')');
2470 *end_ptr = (gchar *) str;
2479 if (*str == '"' || *str == '\'')
2486 SKIP_SPACES_BACK (chr);
2488 if (*chr != *p || chr == p)
2490 *end_ptr = (gchar *)str;
2496 *end_ptr = (gchar *)str;
2500 path = g_strndup (str, chr - str);
2503 *end_ptr = (gchar *)end;
2507 path = g_strdup (str);
2508 *end_ptr = (gchar *)str + strlen (str);
2511 /* Always return an absolute path */
2512 if (!g_path_is_absolute (path))
2514 GtkCssProviderPrivate *priv;
2515 gchar *dirname, *full_path;
2517 priv = css_provider->priv;
2519 /* Use relative path to the current CSS file path, if any */
2521 dirname = g_path_get_dirname (priv->filename);
2523 dirname = g_get_current_dir ();
2525 full_path = g_build_filename (dirname, path, NULL);
2532 if (!g_file_test (path, G_FILE_TEST_EXISTS | G_FILE_TEST_IS_REGULAR))
2534 g_set_error (error, G_FILE_ERROR, G_FILE_ERROR_EXIST,
2535 "File doesn't exist: %s", path);
2538 *end_ptr = (gchar *)start;
2545 path_parse (GtkCssProvider *css_provider,
2552 path = path_parse_str (css_provider, str, &end, error);
2559 g_set_error_literal (error,
2560 GTK_CSS_PROVIDER_ERROR,
2561 GTK_CSS_PROVIDER_ERROR_FAILED,
2562 "Error parsing path");
2571 slice_parse_str (GtkCssProvider *css_provider,
2576 gdouble distance_top, distance_bottom;
2577 gdouble distance_left, distance_right;
2578 GtkSliceSideModifier mods[2];
2586 /* Parse image url */
2587 path = path_parse_str (css_provider, str, end_ptr, error);
2595 /* Parse top/left/bottom/right distances */
2596 distance_top = g_ascii_strtod (str, end_ptr);
2601 distance_right = g_ascii_strtod (str, end_ptr);
2606 distance_bottom = g_ascii_strtod (str, end_ptr);
2611 distance_left = g_ascii_strtod (str, end_ptr);
2616 while (*str && i < 2)
2618 if (g_str_has_prefix (str, "stretch"))
2620 str += strlen ("stretch");
2621 mods[i] = GTK_SLICE_STRETCH;
2623 else if (g_str_has_prefix (str, "repeat"))
2625 str += strlen ("repeat");
2626 mods[i] = GTK_SLICE_REPEAT;
2631 *end_ptr = (gchar *) str;
2639 *end_ptr = (gchar *) str;
2649 /* Fill in second modifier, same as the first */
2653 pixbuf = gdk_pixbuf_new_from_file (path, error);
2658 *end_ptr = (gchar *) str;
2662 slice = _gtk_9slice_new (pixbuf,
2663 distance_top, distance_bottom,
2664 distance_left, distance_right,
2666 g_object_unref (pixbuf);
2672 unit_parse_str (const gchar *str,
2678 unit = g_ascii_strtod (str, end_str);
2681 /* Now parse the unit type, if any. We
2682 * don't admit spaces between these.
2684 if (*str != ' ' && *str != '\0')
2686 while (**end_str != ' ' && **end_str != '\0')
2689 /* Only handle pixels at the moment */
2690 if (strncmp (str, "px", 2) != 0)
2694 type = g_strndup (str, *end_str - str);
2695 g_warning ("Unknown unit '%s', only pixel units are "
2696 "currently supported in CSS style", type);
2705 border_parse_str (const gchar *str,
2708 gdouble first, second, third, fourth;
2711 border = gtk_border_new ();
2714 if (!g_ascii_isdigit (*str) && *str != '-')
2717 first = unit_parse_str (str, end_str);
2721 if (!g_ascii_isdigit (*str) && *str != '-')
2723 border->left = border->right = border->top = border->bottom = (gint) first;
2724 *end_str = (gchar *) str;
2728 second = unit_parse_str (str, end_str);
2732 if (!g_ascii_isdigit (*str) && *str != '-')
2734 border->top = border->bottom = (gint) first;
2735 border->left = border->right = (gint) second;
2736 *end_str = (gchar *) str;
2740 third = unit_parse_str (str, end_str);
2744 if (!g_ascii_isdigit (*str) && *str != '-')
2746 border->top = (gint) first;
2747 border->left = border->right = (gint) second;
2748 border->bottom = (gint) third;
2749 *end_str = (gchar *) str;
2753 fourth = unit_parse_str (str, end_str);
2755 border->top = (gint) first;
2756 border->right = (gint) second;
2757 border->bottom = (gint) third;
2758 border->left = (gint) fourth;
2764 css_provider_parse_value (GtkCssProvider *css_provider,
2765 const gchar *value_str,
2769 GtkCssProviderPrivate *priv;
2771 gboolean parsed = TRUE;
2774 priv = css_provider->priv;
2775 type = G_VALUE_TYPE (value);
2777 if (type == GDK_TYPE_RGBA ||
2778 type == GDK_TYPE_COLOR)
2783 if (type == GDK_TYPE_RGBA &&
2784 gdk_rgba_parse (&rgba, value_str))
2785 g_value_set_boxed (value, &rgba);
2786 else if (type == GDK_TYPE_COLOR &&
2787 gdk_color_parse (value_str, &color))
2788 g_value_set_boxed (value, &color);
2791 GtkSymbolicColor *symbolic_color;
2793 symbolic_color = symbolic_color_parse_str (value_str, &end);
2797 g_value_unset (value);
2798 g_value_init (value, GTK_TYPE_SYMBOLIC_COLOR);
2799 g_value_take_boxed (value, symbolic_color);
2805 else if (type == PANGO_TYPE_FONT_DESCRIPTION)
2807 PangoFontDescription *font_desc;
2809 font_desc = pango_font_description_from_string (value_str);
2810 g_value_take_boxed (value, font_desc);
2812 else if (type == G_TYPE_BOOLEAN)
2814 if (value_str[0] == '1' ||
2815 g_ascii_strcasecmp (value_str, "true") == 0)
2816 g_value_set_boolean (value, TRUE);
2818 g_value_set_boolean (value, FALSE);
2820 else if (type == G_TYPE_INT)
2821 g_value_set_int (value, atoi (value_str));
2822 else if (type == G_TYPE_UINT)
2823 g_value_set_uint (value, (guint) atoi (value_str));
2824 else if (type == G_TYPE_DOUBLE)
2825 g_value_set_double (value, g_ascii_strtod (value_str, NULL));
2826 else if (type == G_TYPE_FLOAT)
2827 g_value_set_float (value, (gfloat) g_ascii_strtod (value_str, NULL));
2828 else if (type == GTK_TYPE_THEMING_ENGINE)
2830 GtkThemingEngine *engine;
2832 engine = gtk_theming_engine_load (value_str);
2834 g_value_set_object (value, engine);
2838 else if (type == GTK_TYPE_ANIMATION_DESCRIPTION)
2840 GtkAnimationDescription *desc;
2842 desc = _gtk_animation_description_from_string (value_str);
2845 g_value_take_boxed (value, desc);
2849 else if (type == GTK_TYPE_BORDER)
2853 border = border_parse_str (value_str, &end);
2854 g_value_take_boxed (value, border);
2856 else if (type == CAIRO_GOBJECT_TYPE_PATTERN)
2858 GtkGradient *gradient;
2860 gradient = gradient_parse_str (value_str, &end);
2864 g_value_unset (value);
2865 g_value_init (value, GTK_TYPE_GRADIENT);
2866 g_value_take_boxed (value, gradient);
2873 g_clear_error (error);
2874 path = path_parse_str (css_provider, value_str, &end, error);
2878 pixbuf = gdk_pixbuf_new_from_file (path, NULL);
2883 cairo_surface_t *surface;
2884 cairo_pattern_t *pattern;
2886 cairo_matrix_t matrix;
2888 surface = cairo_image_surface_create (CAIRO_FORMAT_ARGB32,
2889 gdk_pixbuf_get_width (pixbuf),
2890 gdk_pixbuf_get_height (pixbuf));
2891 cr = cairo_create (surface);
2892 gdk_cairo_set_source_pixbuf (cr, pixbuf, 0, 0);
2894 pattern = cairo_pattern_create_for_surface (surface);
2896 cairo_matrix_init_scale (&matrix,
2897 gdk_pixbuf_get_width (pixbuf),
2898 gdk_pixbuf_get_height (pixbuf));
2899 cairo_pattern_set_matrix (pattern, &matrix);
2901 cairo_surface_destroy (surface);
2903 g_object_unref (pixbuf);
2905 g_value_take_boxed (value, pattern);
2914 else if (G_TYPE_IS_ENUM (type))
2916 GEnumClass *enum_class;
2917 GEnumValue *enum_value;
2919 enum_class = g_type_class_ref (type);
2920 enum_value = g_enum_get_value_by_nick (enum_class, value_str);
2925 GTK_CSS_PROVIDER_ERROR,
2926 GTK_CSS_PROVIDER_ERROR_FAILED,
2927 "Unknown value '%s' for enum type '%s'",
2928 value_str, g_type_name (type));
2932 g_value_set_enum (value, enum_value->value);
2934 g_type_class_unref (enum_class);
2936 else if (G_TYPE_IS_FLAGS (type))
2938 GFlagsClass *flags_class;
2939 GFlagsValue *flag_value;
2943 flags_class = g_type_class_ref (type);
2945 /* Parse comma separated values */
2946 ptr = strchr (value_str, ',');
2948 while (ptr && parsed)
2955 flag_str = (gchar *) value_str;
2956 flag_value = g_flags_get_value_by_nick (flags_class,
2957 g_strstrip (flag_str));
2962 GTK_CSS_PROVIDER_ERROR,
2963 GTK_CSS_PROVIDER_ERROR_FAILED,
2964 "Unknown flag '%s' for type '%s'",
2965 value_str, g_type_name (type));
2969 flags |= flag_value->value;
2972 ptr = strchr (value_str, ',');
2975 /* Store last/only value */
2976 flag_value = g_flags_get_value_by_nick (flags_class, value_str);
2981 GTK_CSS_PROVIDER_ERROR,
2982 GTK_CSS_PROVIDER_ERROR_FAILED,
2983 "Unknown flag '%s' for type '%s'",
2984 value_str, g_type_name (type));
2988 flags |= flag_value->value;
2991 g_value_set_enum (value, flags);
2993 g_type_class_unref (flags_class);
2995 else if (type == GTK_TYPE_9SLICE)
2999 slice = slice_parse_str (css_provider, value_str, &end, error);
3002 g_value_take_boxed (value, slice);
3009 GTK_CSS_PROVIDER_ERROR,
3010 GTK_CSS_PROVIDER_ERROR_FAILED,
3011 "Cannot parse string '%s' for type %s",
3012 value_str, g_type_name (type));
3018 /* Set error position in the scanner
3019 * according to what we've parsed so far
3021 priv->value_pos += (end - value_str);
3023 if (error && !*error)
3024 g_set_error_literal (error,
3025 GTK_CSS_PROVIDER_ERROR,
3026 GTK_CSS_PROVIDER_ERROR_FAILED,
3027 "Failed to parse value");
3034 scanner_report_warning (GtkCssProvider *css_provider,
3035 GTokenType expected_token,
3038 GtkCssProviderPrivate *priv;
3039 const gchar *line_end, *line_start;
3040 const gchar *expected_str;
3041 gchar buf[2], *line, *str;
3044 priv = css_provider->priv;
3047 str = g_strdup (error->message);
3050 if (priv->scanner->user_data)
3051 expected_str = priv->scanner->user_data;
3054 switch (expected_token)
3056 case G_TOKEN_SYMBOL:
3057 expected_str = "Symbol";
3058 case G_TOKEN_IDENTIFIER:
3059 expected_str = "Identifier";
3061 buf[0] = expected_token;
3067 str = g_strdup_printf ("Parse error, expecting a %s '%s'",
3068 (expected_str != buf) ? "valid" : "",
3072 if (priv->value_pos)
3073 line_start = priv->value_pos - 1;
3075 line_start = priv->scanner->text - 1;
3077 while (*line_start != '\n' &&
3078 line_start != priv->buffer)
3081 if (*line_start == '\n')
3084 if (priv->value_pos)
3085 pos = priv->value_pos - line_start + 1;
3087 pos = priv->scanner->text - line_start - 1;
3089 line_end = strchr (line_start, '\n');
3092 line = g_strndup (line_start, (line_end - line_start));
3094 line = g_strdup (line_start);
3096 g_message ("CSS: %s\n"
3097 "%s, line %d, char %d:\n"
3100 str, priv->scanner->input_name,
3101 priv->scanner->line, priv->scanner->position,
3110 parse_rule (GtkCssProvider *css_provider,
3114 GtkCssProviderPrivate *priv;
3115 GTokenType expected_token;
3116 SelectorPath *selector;
3118 priv = css_provider->priv;
3120 css_provider_push_scope (css_provider, SCOPE_SELECTOR);
3122 /* Handle directives */
3123 if (scanner->token == G_TOKEN_IDENTIFIER &&
3124 scanner->value.v_identifier[0] == '@')
3128 directive = &scanner->value.v_identifier[1];
3130 if (strcmp (directive, "define-color") == 0)
3132 GtkSymbolicColor *color;
3133 gchar *color_name, *color_str;
3135 /* Directive is a color mapping */
3136 g_scanner_get_next_token (scanner);
3138 if (scanner->token != G_TOKEN_IDENTIFIER)
3140 scanner->user_data = "Color name";
3141 return G_TOKEN_IDENTIFIER;
3144 color_name = g_strdup (scanner->value.v_identifier);
3145 css_provider_push_scope (css_provider, SCOPE_VALUE);
3146 g_scanner_get_next_token (scanner);
3148 if (scanner->token != G_TOKEN_IDENTIFIER)
3150 scanner->user_data = "Color definition";
3151 return G_TOKEN_IDENTIFIER;
3154 color_str = g_strstrip (scanner->value.v_identifier);
3155 color = symbolic_color_parse (color_str, error);
3159 scanner->user_data = "Color definition";
3160 return G_TOKEN_IDENTIFIER;
3163 g_hash_table_insert (priv->symbolic_colors, color_name, color);
3165 css_provider_pop_scope (css_provider);
3166 g_scanner_get_next_token (scanner);
3168 if (scanner->token != ';')
3171 return G_TOKEN_NONE;
3173 else if (strcmp (directive, "import") == 0)
3175 GScanner *scanner_backup;
3176 GSList *state_backup;
3180 css_provider_push_scope (css_provider, SCOPE_VALUE);
3181 g_scanner_get_next_token (scanner);
3183 if (scanner->token == G_TOKEN_IDENTIFIER &&
3184 g_str_has_prefix (scanner->value.v_identifier, "url"))
3185 path = path_parse (css_provider,
3186 g_strstrip (scanner->value.v_identifier),
3188 else if (scanner->token == G_TOKEN_STRING)
3189 path = path_parse (css_provider,
3190 g_strstrip (scanner->value.v_string),
3195 scanner->user_data = "File URL";
3196 return G_TOKEN_IDENTIFIER;
3199 css_provider_pop_scope (css_provider);
3200 g_scanner_get_next_token (scanner);
3202 if (scanner->token != ';')
3208 /* Snapshot current parser state and scanner in order to restore after importing */
3209 state_backup = priv->state;
3210 scanner_backup = priv->scanner;
3213 priv->scanner = create_scanner ();
3215 /* FIXME: Avoid recursive importing */
3216 loaded = gtk_css_provider_load_from_path_internal (css_provider, path,
3219 /* Restore previous state */
3220 css_provider_reset_parser (css_provider);
3221 priv->state = state_backup;
3222 g_scanner_destroy (priv->scanner);
3223 priv->scanner = scanner_backup;
3229 scanner->user_data = "File URL";
3230 return G_TOKEN_IDENTIFIER;
3233 return G_TOKEN_NONE;
3237 scanner->user_data = "Directive";
3238 return G_TOKEN_IDENTIFIER;
3242 expected_token = parse_selector (css_provider, scanner, &selector);
3244 if (expected_token != G_TOKEN_NONE)
3246 selector_path_unref (selector);
3247 scanner->user_data = "Selector";
3248 return expected_token;
3251 priv->cur_selectors = g_slist_prepend (priv->cur_selectors, selector);
3253 while (scanner->token == ',')
3255 g_scanner_get_next_token (scanner);
3257 expected_token = parse_selector (css_provider, scanner, &selector);
3259 if (expected_token != G_TOKEN_NONE)
3261 selector_path_unref (selector);
3262 scanner->user_data = "Selector";
3263 return expected_token;
3266 priv->cur_selectors = g_slist_prepend (priv->cur_selectors, selector);
3269 css_provider_pop_scope (css_provider);
3271 if (scanner->token != G_TOKEN_LEFT_CURLY)
3272 return G_TOKEN_LEFT_CURLY;
3274 /* Declarations parsing */
3275 css_provider_push_scope (css_provider, SCOPE_DECLARATION);
3276 g_scanner_get_next_token (scanner);
3278 while (scanner->token == G_TOKEN_IDENTIFIER)
3280 gchar *value_str = NULL;
3281 GtkStylePropertyParser parse_func = NULL;
3285 prop = g_strdup (scanner->value.v_identifier);
3286 g_scanner_get_next_token (scanner);
3288 if (scanner->token != ':')
3294 priv->value_pos = priv->scanner->text;
3296 css_provider_push_scope (css_provider, SCOPE_VALUE);
3297 g_scanner_get_next_token (scanner);
3299 if (scanner->token != G_TOKEN_IDENTIFIER)
3302 scanner->user_data = "Property value";
3303 return G_TOKEN_IDENTIFIER;
3306 value_str = scanner->value.v_identifier;
3307 SKIP_SPACES (value_str);
3308 g_strchomp (value_str);
3310 if (gtk_style_properties_lookup_property (prop, &parse_func, &pspec))
3314 val = g_slice_new0 (GValue);
3315 g_value_init (val, pspec->value_type);
3317 if (strcmp (value_str, "none") == 0)
3319 /* Insert the default value, so it has an opportunity
3320 * to override other style providers when merged
3322 g_param_value_set_default (pspec, val);
3323 g_hash_table_insert (priv->cur_properties, prop, val);
3325 else if (pspec->value_type == G_TYPE_STRING)
3327 g_value_set_string (val, value_str);
3328 g_hash_table_insert (priv->cur_properties, prop, val);
3330 else if ((parse_func && (parse_func) (value_str, val, error)) ||
3331 (!parse_func && css_provider_parse_value (css_provider, value_str, val, error)))
3332 g_hash_table_insert (priv->cur_properties, prop, val);
3335 g_value_unset (val);
3336 g_slice_free (GValue, val);
3339 scanner->user_data = "Property value";
3340 return G_TOKEN_IDENTIFIER;
3343 else if (prop[0] == '-')
3347 val = g_slice_new0 (GValue);
3348 g_value_init (val, G_TYPE_STRING);
3349 g_value_set_string (val, value_str);
3351 g_hash_table_insert (priv->cur_properties, prop, val);
3356 css_provider_pop_scope (css_provider);
3357 g_scanner_get_next_token (scanner);
3359 if (scanner->token != ';')
3362 g_scanner_get_next_token (scanner);
3365 if (scanner->token != G_TOKEN_RIGHT_CURLY)
3366 return G_TOKEN_RIGHT_CURLY;
3368 css_provider_pop_scope (css_provider);
3370 return G_TOKEN_NONE;
3374 parse_stylesheet (GtkCssProvider *css_provider,
3377 GtkCssProviderPrivate *priv;
3382 priv = css_provider->priv;
3383 g_scanner_get_next_token (priv->scanner);
3385 while (!g_scanner_eof (priv->scanner))
3387 GTokenType expected_token;
3390 css_provider_reset_parser (css_provider);
3391 expected_token = parse_rule (css_provider, priv->scanner, &err);
3393 if (expected_token != G_TOKEN_NONE)
3395 /* If a GError was passed in, propagate the error and bail out,
3396 * else report a warning and keep going
3402 g_propagate_error (error, err);
3404 g_set_error_literal (error,
3405 GTK_CSS_PROVIDER_ERROR,
3406 GTK_CSS_PROVIDER_ERROR_FAILED,
3407 "Error parsing stylesheet");
3412 scanner_report_warning (css_provider, expected_token, err);
3413 g_clear_error (&err);
3416 while (!g_scanner_eof (priv->scanner) &&
3417 priv->scanner->token != G_TOKEN_RIGHT_CURLY)
3418 g_scanner_get_next_token (priv->scanner);
3421 css_provider_commit (css_provider);
3423 g_scanner_get_next_token (priv->scanner);
3430 * gtk_css_provider_load_from_data:
3431 * @css_provider: a #GtkCssProvider
3432 * @data: CSS data loaded in memory
3433 * @length: the length of @data in bytes, or -1 for NUL terminated strings
3434 * @error: (out) (allow-none): return location for a #GError, or %NULL
3436 * Loads @data into @css_provider, making it clear any previously loaded
3439 * Returns: %TRUE if the data could be loaded.
3442 gtk_css_provider_load_from_data (GtkCssProvider *css_provider,
3447 GtkCssProviderPrivate *priv;
3449 g_return_val_if_fail (GTK_IS_CSS_PROVIDER (css_provider), FALSE);
3450 g_return_val_if_fail (data != NULL, FALSE);
3452 priv = css_provider->priv;
3455 length = strlen (data);
3457 if (priv->selectors_info->len > 0)
3458 g_ptr_array_remove_range (priv->selectors_info, 0, priv->selectors_info->len);
3460 priv->scanner->input_name = "-";
3461 priv->buffer = data;
3462 g_scanner_input_text (priv->scanner, data, (guint) length);
3464 g_free (priv->filename);
3465 priv->filename = NULL;
3466 priv->buffer = NULL;
3468 return parse_stylesheet (css_provider, error);
3472 * gtk_css_provider_load_from_file:
3473 * @css_provider: a #GtkCssProvider
3474 * @file: #GFile pointing to a file to load
3475 * @error: (out) (allow-none): return location for a #GError, or %NULL
3477 * Loads the data contained in @file into @css_provider, making it
3478 * clear any previously loaded information.
3480 * Returns: %TRUE if the data could be loaded.
3483 gtk_css_provider_load_from_file (GtkCssProvider *css_provider,
3487 GtkCssProviderPrivate *priv;
3488 GError *internal_error = NULL;
3493 g_return_val_if_fail (GTK_IS_CSS_PROVIDER (css_provider), FALSE);
3494 g_return_val_if_fail (G_IS_FILE (file), FALSE);
3496 priv = css_provider->priv;
3498 if (!g_file_load_contents (file, NULL,
3500 NULL, &internal_error))
3502 g_propagate_error (error, internal_error);
3506 if (priv->selectors_info->len > 0)
3507 g_ptr_array_remove_range (priv->selectors_info, 0, priv->selectors_info->len);
3509 g_free (priv->filename);
3510 priv->filename = g_file_get_path (file);
3512 priv->scanner->input_name = priv->filename;
3513 priv->buffer = data;
3514 g_scanner_input_text (priv->scanner, data, (guint) length);
3516 ret = parse_stylesheet (css_provider, error);
3518 priv->buffer = NULL;
3525 gtk_css_provider_load_from_path_internal (GtkCssProvider *css_provider,
3530 GtkCssProviderPrivate *priv;
3531 GError *internal_error = NULL;
3532 GMappedFile *mapped_file;
3537 priv = css_provider->priv;
3539 mapped_file = g_mapped_file_new (path, FALSE, &internal_error);
3543 g_propagate_error (error, internal_error);
3547 length = g_mapped_file_get_length (mapped_file);
3548 data = g_mapped_file_get_contents (mapped_file);
3555 if (priv->selectors_info->len > 0)
3556 g_ptr_array_remove_range (priv->selectors_info, 0, priv->selectors_info->len);
3558 g_free (priv->filename);
3559 priv->filename = g_strdup (path);
3562 priv->scanner->input_name = priv->filename;
3563 priv->buffer = data;
3564 g_scanner_input_text (priv->scanner, data, (guint) length);
3566 ret = parse_stylesheet (css_provider, error);
3568 priv->buffer = NULL;
3569 g_mapped_file_unref (mapped_file);
3575 * gtk_css_provider_load_from_path:
3576 * @css_provider: a #GtkCssProvider
3577 * @path: the path of a filename to load, in the GLib filename encoding
3578 * @error: (out) (allow-none): return location for a #GError, or %NULL
3580 * Loads the data contained in @path into @css_provider, making it clear
3581 * any previously loaded information.
3583 * Returns: %TRUE if the data could be loaded.
3586 gtk_css_provider_load_from_path (GtkCssProvider *css_provider,
3590 g_return_val_if_fail (GTK_IS_CSS_PROVIDER (css_provider), FALSE);
3591 g_return_val_if_fail (path != NULL, FALSE);
3593 return gtk_css_provider_load_from_path_internal (css_provider, path,
3598 * gtk_css_provider_get_default:
3600 * Returns the provider containing the style settings used as a
3601 * fallback for all widgets.
3603 * Returns: (transfer none): The provider used for fallback styling.
3604 * This memory is owned by GTK+, and you must not free it.
3607 gtk_css_provider_get_default (void)
3609 static GtkCssProvider *provider;
3611 if (G_UNLIKELY (!provider))
3614 "@define-color fg_color #000; \n"
3615 "@define-color bg_color #dcdad5; \n"
3616 "@define-color text_color #000; \n"
3617 "@define-color base_color #fff; \n"
3618 "@define-color selected_bg_color #4b6983; \n"
3619 "@define-color selected_fg_color #fff; \n"
3620 "@define-color tooltip_bg_color #eee1b3; \n"
3621 "@define-color tooltip_fg_color #000; \n"
3623 "@define-color info_fg_color rgb (181, 171, 156);\n"
3624 "@define-color info_bg_color rgb (252, 252, 189);\n"
3625 "@define-color warning_fg_color rgb (173, 120, 41);\n"
3626 "@define-color warning_bg_color rgb (250, 173, 61);\n"
3627 "@define-color question_fg_color rgb (97, 122, 214);\n"
3628 "@define-color question_bg_color rgb (138, 173, 212);\n"
3629 "@define-color error_fg_color rgb (166, 38, 38);\n"
3630 "@define-color error_bg_color rgb (237, 54, 54);\n"
3633 "GtkTreeView > GtkButton {\n"
3634 " background-color: @bg_color;\n"
3635 " color: @fg_color;\n"
3636 " border-color: shade (@bg_color, 0.6);\n"
3638 " border-width: 0;\n"
3642 " background-color: shade (@bg_color, 1.05);\n"
3643 " color: shade (@fg_color, 1.3);\n"
3647 " background-color: @selected_bg_color;\n"
3648 " color: @selected_fg_color;\n"
3651 ".expander, .view.expander {\n"
3655 ".expander:prelight {\n"
3656 " color: @text_color;\n"
3659 ".expander:active {\n"
3660 " transition: 300ms linear;\n"
3664 " border-color: shade (@bg_color, 0.7);\n"
3665 " background-color: shade (@bg_color, 0.9);\n"
3666 " color: shade (@bg_color, 0.7);\n"
3669 "GtkTreeView, GtkIconView {\n"
3670 " background-color: @base_color;\n"
3671 " color: @text_color;\n"
3675 " background-color: @base_color;\n"
3676 " color: @text_color;\n"
3678 ".view:selected {\n"
3679 " background-color: shade (@bg_color, 0.9);\n"
3680 " color: @fg_color;\n"
3683 ".view:selected:focused {\n"
3684 " background-color: @selected_bg_color;\n"
3685 " color: @selected_fg_color;\n"
3688 "GtkTreeView > row {\n"
3689 " background-color: @base_color;\n"
3690 " color: @text_color;\n"
3693 "GtkTreeView > row:nth-child(odd) { \n"
3694 " background-color: shade (@base_color, 0.93); \n"
3698 " background-color: @tooltip_bg_color; \n"
3699 " color: @tooltip_fg_color; \n"
3700 " border-color: @tooltip_fg_color; \n"
3701 " border-width: 1;\n"
3702 " border-style: solid;\n"
3707 " border-style: outset; \n"
3708 " border-width: 2; \n"
3711 ".button:active {\n"
3712 " background-color: shade (@bg_color, 0.7);\n"
3713 " border-style: inset; \n"
3716 ".button:prelight,\n"
3717 ".slider:prelight {\n"
3718 " background-color: @selected_bg_color;\n"
3719 " color: @selected_fg_color;\n"
3720 " border-color: shade (@selected_bg_color, 0.7);\n"
3724 " border-style: inset;\n"
3725 " border-width: 1;\n"
3730 " border-style: inset;\n"
3731 " border-width: 2;\n"
3732 " background-color: @base_color;\n"
3733 " color: @text_color;\n"
3736 ".entry:insensitive {\n"
3737 " background-color: shade (@base_color, 0.9);\n"
3738 " color: shade (@base_color, 0.7);\n"
3741 " background-color: #c4c2bd;\n"
3746 ".entry.progressbar {\n"
3747 " background-color: @selected_bg_color;\n"
3748 " border-color: shade (@selected_bg_color, 0.7);\n"
3749 " color: @selected_fg_color;\n"
3750 " border-style: outset;\n"
3751 " border-width: 1;\n"
3754 "GtkCheckButton:hover,\n"
3755 "GtkCheckButton:selected,\n"
3756 "GtkRadioButton:hover,\n"
3757 "GtkRadioButton:selected {\n"
3758 " background-color: shade (@bg_color, 1.05);\n"
3761 ".check, .radio {\n"
3762 " border-style: solid;\n"
3763 " border-width: 1;\n"
3764 " background-color: @base_color;\n"
3765 " border-color: @fg_color;\n"
3768 ".check:active, .radio:active,\n"
3769 ".check:hover, .radio:hover {\n"
3770 " background-color: @base_color;\n"
3771 " border-color: @fg_color;\n"
3772 " color: @text_color;\n"
3775 ".check:selected, .radio:selected {\n"
3776 " background-color: @selected_bg_color;\n"
3777 " color: @selected_fg_color;\n"
3780 ".menu.check, .menu.radio {\n"
3781 " color: @fg_color;\n"
3782 " border-style: none;\n"
3783 " border-width: 0;\n"
3787 " border-style: outset;\n"
3788 " border-width: 1;\n"
3792 " border-style: inset;\n"
3793 " border-width: 2;\n"
3797 " border-style: outset;\n"
3798 " border-width: 1;\n"
3802 " border-style: inset;\n"
3803 " border-width: 1;\n"
3806 "GtkScrolledWindow.frame {\n"
3813 " border-style: outset;\n"
3814 " border-width: 1;\n"
3819 ".menu.check:hover,\n"
3820 ".menu.radio:hover {\n"
3821 " background-color: @selected_bg_color;\n"
3822 " color: @selected_fg_color;\n"
3825 "GtkSpinButton.button {\n"
3826 " border-width: 1;\n"
3829 ".scale.slider:hover,\n"
3830 "GtkSpinButton.button:hover {\n"
3831 " background-color: shade (@bg_color, 1.05);\n"
3832 " border-color: shade (@bg_color, 0.8);\n"
3835 "GtkToggleButton.button:inconsistent {\n"
3836 " border-style: outset;\n"
3837 " border-width: 1px;\n"
3838 " background-color: shade (@bg_color, 0.9);\n"
3839 " border-color: shade (@bg_color, 0.7);\n"
3842 "GtkLabel:selected {\n"
3843 " background-color: shade (@bg_color, 0.9);\n"
3844 " color: @fg_color;\n"
3847 "GtkLabel:selected:focused {\n"
3848 " background-color: @selected_bg_color;\n"
3849 " color: @selected_fg_color;\n"
3852 ".spinner:active {\n"
3853 " transition: 750ms linear loop;\n"
3857 " background-color: @info_bg_color;\n"
3858 " color: @info_fg_color;\n"
3862 " background-color: @warning_bg_color;\n"
3863 " color: @warning_fg_color;\n"
3867 " background-color: @question_bg_color;\n"
3868 " color: @question_fg_color;\n"
3872 " background-color: @error_bg_color;\n"
3873 " color: @error_fg_color;\n"
3877 " background-color: @selected_bg_color;\n"
3878 " color: @selected_fg_color;\n"
3881 ".light-area-focus {\n"
3885 ".dark-area-focus {\n"
3888 "GtkCalendar.view {\n"
3889 " border-width: 1;\n"
3890 " border-style: inset;\n"
3894 "GtkCalendar.view:inconsistent {\n"
3895 " color: darker (@bg_color);\n"
3898 "GtkCalendar.header {\n"
3899 " background-color: @bg_color;\n"
3900 " border-style: outset;\n"
3901 " border-width: 2;\n"
3904 "GtkCalendar.highlight {\n"
3905 " border-width: 0;\n"
3908 "GtkCalendar.button {\n"
3909 " background-color: @bg_color;\n"
3912 "GtkCalendar.button:hover {\n"
3913 " background-color: lighter (@bg_color);\n"
3914 " color: @fg_color;\n"
3918 " border-width: 1;\n"
3923 " border-width: 0;\n"
3928 provider = gtk_css_provider_new ();
3929 if (!gtk_css_provider_load_from_data (provider, str, -1, NULL))
3931 g_error ("Failed to load the internal default CSS.");
3939 css_provider_get_theme_dir (void)
3944 var = g_getenv ("GTK_DATA_PREFIX");
3947 path = g_build_filename (var, "share", "themes", NULL);
3949 path = g_build_filename (GTK_DATA_PREFIX, "share", "themes", NULL);
3955 * gtk_css_provider_get_named:
3956 * @name: A theme name
3957 * @variant: variant to load, for example, "dark", or %NULL for the default
3959 * Loads a theme from the usual theme paths
3961 * Returns: (transfer none): a #GtkCssProvider with the theme loaded.
3962 * This memory is owned by GTK+, and you must not free it.
3965 gtk_css_provider_get_named (const gchar *name,
3966 const gchar *variant)
3968 static GHashTable *themes = NULL;
3969 GtkCssProvider *provider;
3971 if (G_UNLIKELY (!themes))
3972 themes = g_hash_table_new (g_str_hash, g_str_equal);
3974 provider = g_hash_table_lookup (themes, name);
3978 const gchar *home_dir;
3979 gchar *subpath, *path = NULL;
3982 subpath = g_strdup_printf ("gtk-3.0" G_DIR_SEPARATOR_S "gtk-%s.css", variant);
3984 subpath = g_strdup ("gtk-3.0" G_DIR_SEPARATOR_S "gtk.css");
3986 /* First look in the users home directory
3988 home_dir = g_get_home_dir ();
3991 path = g_build_filename (home_dir, ".themes", name, subpath, NULL);
3993 if (!g_file_test (path, G_FILE_TEST_EXISTS))
4002 gchar *theme_dir = css_provider_get_theme_dir ();
4003 path = g_build_filename (theme_dir, name, subpath, NULL);
4006 if (!g_file_test (path, G_FILE_TEST_EXISTS))
4017 GError *error = NULL;
4019 provider = gtk_css_provider_new ();
4020 gtk_css_provider_load_from_path (provider, path, &error);
4024 g_warning ("Could not load named theme \"%s\": %s", name, error->message);
4025 g_error_free (error);
4027 g_object_unref (provider);
4031 g_hash_table_insert (themes, g_strdup (name), provider);