gtkcssprovider.c 82.3 KB
Newer Older
Carlos Garnacho's avatar
Carlos Garnacho committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
/* GTK - The GIMP Toolkit
 * Copyright (C) 2010 Carlos Garnacho <carlosg@gnome.org>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the
 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
 * Boston, MA 02111-1307, USA.
 */

#include "config.h"

#include <string.h>
#include <stdlib.h>
#include <gtk/gtk.h>
#include <gtkstyleprovider.h>
26
#include <gdk-pixbuf/gdk-pixbuf.h>
27
#include <cairo-gobject.h>
Carlos Garnacho's avatar
Carlos Garnacho committed
28

29
#include "gtkanimationdescription.h"
30
#include "gtk9slice.h"
Carlos Garnacho's avatar
Carlos Garnacho committed
31 32
#include "gtkcssprovider.h"

Carlos Garnacho's avatar
Carlos Garnacho committed
33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99
/**
 * SECTION:gtkcssprovider
 * @Short_description: CSS-like styling for widgets
 * @Title: GtkCssProvider
 * @See_also: #GtkStyleContext, #GtkStyleProvider
 *
 * #GtkCssProvider is an object implementing #GtkStyleProvider, it is able
 * to parse CSS-like input in order to style widgets.
 *
 * <refsect2 id="gtkcssprovider-selectors">
 * <title>Widget selectors</title>
 * <para>
 * Selectors work in a really similar way than in common CSS, widget object
 * names act as HTML tags:
 * </para>
 * <example>
 * <title>Widgets in selectors</title>
 * <programlisting>
 * /&ast; Theme labels that are descendants of a window &ast;/
 * GtkWindow GtkLabel {
 *     background-color: &num;898989;
 * }
 *
 * /&ast; Theme notebooks, and anything that's within these &ast;/
 * GtkNotebook {
 *     background-color: &num;a939f0;
 * }
 *
 * /&ast; Theme combo boxes, and entries that
 *  are direct children of a notebook &ast;/
 * GtkComboBox,
 * GtkNotebook > GtkEntry {
 *     background-color: &num;1209a2;
 * }
 *
 * /&ast; Theme any widget within a GtkBin &ast;/
 * GtkBin * {
 *     font-name: Sans 20;
 * }
 * </programlisting>
 * </example>
 * <para>
 * Widget names may be matched in CSS as well:
 * </para>
 * <example>
 * <title>Widget names in selectors</title>
 * <programlisting>
 * /&ast; Theme a label named title-label &ast;/
 * GtkLabel&num;title-label {
 *     font-name: Sans 15;
 * }
 *
 * /&ast; Theme any widget named main-entry &ast;/
 * &num;main-entry {
 *     background-color: &num;f0a810;
 * }
 * </programlisting>
 * </example>
 * <para>
 * Widgets may also define different classes, so these can be matched
 * in CSS:
 * </para>
 * <example>
 * <title>Widget names in selectors</title>
 * <programlisting>
 * /&ast; Theme all widgets defining the class entry &ast;/
 * .entry {
100
 *     color: &num;39f1f9;
Carlos Garnacho's avatar
Carlos Garnacho committed
101 102 103 104
 * }
 *
 * /&ast; Theme spinbuttons' entry &ast;/
 * GtkSpinButton.entry {
105
 *     color: &num;900185;
Carlos Garnacho's avatar
Carlos Garnacho committed
106 107 108 109 110 111 112 113 114 115 116 117 118 119
 * }
 * </programlisting>
 * </example>
 * <para>
 * Container widgets may define regions, these region names may be
 * referenced in CSS, it's also possible to apply :nth-child
 * pseudo-class information if the widget implementation provides
 * such data.
 * </para>
 * <example>
 * <title>Region names in containers</title>
 * <programlisting>
 * /&ast; Theme any label within a notebook &ast;/
 * GtkNotebook GtkLabel {
120
 *     color: &num;f90192;
Carlos Garnacho's avatar
Carlos Garnacho committed
121 122 123 124
 * }
 *
 * /&ast; Theme labels within notebook tabs &ast;/
 * GtkNotebook tab:nth-child GtkLabel {
125
 *     color: &num;703910;
Carlos Garnacho's avatar
Carlos Garnacho committed
126 127 128 129 130 131
 * }
 *
 * /&ast; Theme labels in the any first notebook
 *  tab, both selectors are equivalent &ast;/
 * GtkNotebook tab:nth-child(first) GtkLabel,
 * GtkNotebook tab:first-child GtkLabel {
132
 *     color: &num;89d012;
Carlos Garnacho's avatar
Carlos Garnacho committed
133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280
 * }
 * </programlisting>
 * </example>
 * <para>
 * Widget states may be matched as pseudoclasses.
 * Given the needed widget states differ from the
 * offered pseudoclasses in CSS, some are unsupported,
 * and some custom ones have been added.
 * </para>
 * <example>
 * <title>Styling specific widget states</title>
 * <programlisting>
 * /&ast; Theme active (pressed) buttons &ast;/
 * GtkButton:active {
 *     background-color: &num;0274d9;
 * }
 *
 * /&ast; Theme buttons with the mouse pointer on it &ast;/
 * GtkButton:hover,
 * GtkButton:prelight {
 *     background-color: &num;3085a9;
 * }
 *
 * /&ast; Theme insensitive widgets, both are equivalent &ast;/
 * :insensitive,
 * *:insensitive {
 *     background-color: &num;320a91;
 * }
 *
 * /&ast; Theme selection colors in entries &ast;/
 * GtkEntry:selected {
 *     background-color: &num;56f9a0;
 * }
 *
 * /&ast; Theme focused labels &ast;/
 * GtkLabel:focused {
 *     background-color: &num;b4940f;
 * }
 *
 * /&ast; Theme inconsistent checkbuttons &ast;/
 * GtkCheckButton:inconsistent {
 *     background-color: &num;20395a;
 * }
 * </programlisting>
 * </example>
 * <para>
 * Widget state pseudoclasses may only apply to the
 * last element in a selector.
 * </para>
 * <para>
 * All the mentioned elements may be combined to create
 * complex selectors that match specific widget paths.
 * As in CSS, rules apply by specificity, so the selectors
 * describing the best a widget path will take precedence
 * over the others.
 * </para>
 * </refsect2>
 * <refsect2 id="gtkcssprovider-rules">
 * <title>&commat; rules</title>
 * <para>
 * GTK+'s CSS supports the &commat;import rule, in order
 * to load another CSS file in addition to the currently
 * parsed one.
 * </para>
 * <example>
 * <title>Using the &commat;import rule</title>
 * <programlisting>
 * &commat;import url (path/to/common.css)
 * </programlisting>
 * </example>
 * <para>
 * GTK+ also supports an additional &commat;define-color
 * rule, in order to define a color name which may be used
 * instead of color numeric representations.
 * </para>
 * <example>
 * <title>Defining colors</title>
 * <programlisting>
 * &commat;define-color bg_color &num;f9a039;
 *
 * &ast; {
 *     background-color: &commat;bg_color;
 * }
 * </programlisting>
 * </example>
 * </refsect2>
 * <refsect2 id="gtkcssprovider-symbolic-colors">
 * <title>Symbolic colors</title>
 * <para>
 * Besides being able to define color names, the CSS
 * parser is also able to read different color modifiers,
 * which can also be nested, providing a rich language
 * to define colors starting from other colors.
 * </para>
 * <example>
 * <title>Using symbolic colors</title>
 * <programlisting>
 * &commat;define-color entry-color shade (&commat;bg_color, 0.7);
 *
 * GtkEntry {
 *     background-color: @entry-color;
 * }
 *
 * GtkEntry:focused {
 *     background-color: mix (&commat;entry-color,
 *                            shade (&num;fff, 0.5),
 *                            0.8);
 * }
 * </programlisting>
 * </example>
 * </refsect2>
 * <refsect2 id="gtkcssprovider-properties">
 * <title>Supported properties</title>
 * <para>
 * Properties are the part that differ the most to common CSS,
 * not all properties are supported (some are planned to be
 * supported eventually, some others are meaningless or don't
 * map intuitively in a widget based environment).
 * </para>
 * <para>
 * There is also a difference in shorthand properties, for
 * example in common CSS it is fine to define a font through
 * the different @font-family, @font-style, @font-size
 * properties, meanwhile in GTK+'s CSS only the canonical
 * @font property would be supported.
 * </para>
 * <para>
 * The currently supported properties are:
 * </para>
 * <informaltable>
 *   <tgroup cols="4">
 *     <thead>
 *       <row>
 *         <entry>Property name</entry>
 *         <entry>Syntax</entry>
 *         <entry>Maps to</entry>
 *         <entry>Examples</entry>
 *       </row>
 *     </thead>
 *     <tbody>
 *       <row>
 *         <entry>engine</entry>
 *         <entry><programlisting>engine-name</programlisting></entry>
 *         <entry>#GtkThemingEngine</entry>
 *         <entry><programlisting>engine: clearlooks;</programlisting></entry>
 *       </row>
 *       <row>
 *         <entry>background-color</entry>
281 282 283
 *         <entry morerows="1"><programlisting>color</programlisting></entry>
 *         <entry morerows="1">#GdkRGBA</entry>
 *         <entry morerows="1">
Carlos Garnacho's avatar
Carlos Garnacho committed
284 285
 *           <programlisting>
 * background-color: &num;fff;
286 287 288
 * color: @color-name;
 * background-color: shade (@color-name, 0.5);
 * color: mix (@color-name, &num;f0f, 0.8);</programlisting>
Carlos Garnacho's avatar
Carlos Garnacho committed
289 290 291
 *         </entry>
 *       </row>
 *       <row>
292
 *         <entry>color</entry>
Carlos Garnacho's avatar
Carlos Garnacho committed
293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341
 *       </row>
 *       <row>
 *         <entry>font</entry>
 *         <entry><programlisting>family [style] [size]</programlisting></entry>
 *         <entry>#PangoFontDescription</entry>
 *         <entry><programlisting>font: Sans 15;</programlisting></entry>
 *       </row>
 *       <row>
 *         <entry>margin</entry>
 *         <entry morerows="1">
 *           <programlisting>
 * width
 * vertical-width horizontal-width
 * top-width horizontal-width bottom-width
 * top-width right-width bottom-width left-width
 *           </programlisting>
 *         </entry>
 *         <entry morerows="1">#GtkBorder</entry>
 *         <entry morerows="1">
 *           <programlisting>
 * margin: 5;
 * margin: 5 10;
 * margin: 5 10 3;
 * margin: 5 10 3 5;</programlisting>
 *         </entry>
 *       </row>
 *       <row>
 *         <entry>padding</entry>
 *       </row>
 *       <row>
 *         <entry>background-image</entry>
 *         <entry>
 *           <programlisting>
 * -gtk-gradient (linear,
 *                starting-x-position starting-y-position,
 *                ending-x-position ending-y-position,
 *                [ [from|to] (color) |
 *                  color-stop (percentage, color) ] )
 *
 * -gtk-gradient (radial,
 *                starting-x-position starting-y-position, starting-radius,
 *                ending-x-position ending-y-position, ending-radius,
 *                [ [from|to] (color) |
 *                  color-stop (percentage, color) ]* )</programlisting>
 *         </entry>
 *         <entry>#cairo_pattern_t</entry>
 *         <entry>
 *           <programlisting>
 * -gtk-gradient (linear,
342
 *                left top, right top,
Carlos Garnacho's avatar
Carlos Garnacho committed
343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366
 *                from (&num;fff), to (&num;000));
 * -gtk-gradient (linear, 0.0 0.5, 0.5 1.0,
 *                from (&num;fff),
 *                color-stop (0.5, &num;f00),
 *                to (&num;000));
 * -gtk-gradient (radial,
 *                center center, 0.2,
 *                center center, 0.8,
 *                color-stop (0.0, &num;fff),
 *                color-stop (1.0, &num;000));</programlisting>
 *         </entry>
 *       </row>
 *       <row>
 *         <entry>border-image</entry>
 *         <entry><programlisting>url([path]) top-distance right-distance bottom-distance left-distance horizontal-option vertical-option</programlisting></entry>
 *         <entry></entry>
 *         <entry>
 *           <programlisting>
 * border-image: url (/path/to/image.png) 3 4 3 4 stretch;
 * border-image: url (/path/to/image.png) 3 4 4 3 repeat stretch;</programlisting>
 *         </entry>
 *       </row>
 *       <row>
 *         <entry>transition</entry>
367
 *         <entry><programlisting>duration [s|ms] [linear|ease|ease-in|ease-out|ease-in-out] [loop]?</programlisting></entry>
Carlos Garnacho's avatar
Carlos Garnacho committed
368 369 370 371
 *         <entry></entry>
 *         <entry>
 *           <programlisting>
 * transition: 150ms ease-in-out;
372
 * transition: 1s linear loop;</programlisting>
Carlos Garnacho's avatar
Carlos Garnacho committed
373 374 375 376 377 378 379 380
 *         </entry>
 *       </row>
 *     </tbody>
 *   </tgroup>
 * </informaltable>
 * </refsect2>
 */

Carlos Garnacho's avatar
Carlos Garnacho committed
381 382 383 384 385
typedef struct GtkCssProviderPrivate GtkCssProviderPrivate;
typedef struct SelectorElement SelectorElement;
typedef struct SelectorPath SelectorPath;
typedef struct SelectorStyleInfo SelectorStyleInfo;
typedef enum SelectorElementType SelectorElementType;
386
typedef enum CombinatorType CombinatorType;
Carlos Garnacho's avatar
Carlos Garnacho committed
387
typedef enum ParserScope ParserScope;
388
typedef enum ParserSymbol ParserSymbol;
Carlos Garnacho's avatar
Carlos Garnacho committed
389 390 391 392

enum SelectorElementType {
  SELECTOR_TYPE_NAME,
  SELECTOR_NAME,
393
  SELECTOR_GTYPE,
394
  SELECTOR_REGION,
395
  SELECTOR_CLASS,
396
  SELECTOR_GLOB
Carlos Garnacho's avatar
Carlos Garnacho committed
397 398
};

399 400 401 402 403
enum CombinatorType {
  COMBINATOR_DESCENDANT, /* No direct relation needed */
  COMBINATOR_CHILD       /* Direct child */
};

Carlos Garnacho's avatar
Carlos Garnacho committed
404 405 406
struct SelectorElement
{
  SelectorElementType elem_type;
407
  CombinatorType combinator;
Carlos Garnacho's avatar
Carlos Garnacho committed
408 409 410 411 412

  union
  {
    GQuark name;
    GType type;
413 414 415 416

    struct
    {
      GQuark name;
417
      GtkRegionFlags flags;
418
    } region;
Carlos Garnacho's avatar
Carlos Garnacho committed
419 420 421 422 423 424
  };
};

struct SelectorPath
{
  GSList *elements;
425
  GtkStateFlags state;
Carlos Garnacho's avatar
Carlos Garnacho committed
426 427 428 429 430 431 432 433 434 435 436 437
  guint ref_count;
};

struct SelectorStyleInfo
{
  SelectorPath *path;
  GHashTable *style;
};

struct GtkCssProviderPrivate
{
  GScanner *scanner;
438
  gchar *filename;
439

440 441
  GHashTable *symbolic_colors;

Carlos Garnacho's avatar
Carlos Garnacho committed
442 443 444 445 446 447 448 449 450 451
  GPtrArray *selectors_info;

  /* Current parser state */
  GSList *state;
  GSList *cur_selectors;
  GHashTable *cur_properties;
};

enum ParserScope {
  SCOPE_SELECTOR,
452
  SCOPE_PSEUDO_CLASS,
453
  SCOPE_NTH_CHILD,
Carlos Garnacho's avatar
Carlos Garnacho committed
454 455 456 457
  SCOPE_DECLARATION,
  SCOPE_VALUE
};

458 459 460 461 462
/* Extend GtkStateType, since these
 * values are also used as symbols
 */
enum ParserSymbol {
  /* Scope: pseudo-class */
Carlos Garnacho's avatar
Carlos Garnacho committed
463
  SYMBOL_NTH_CHILD = GTK_STATE_FOCUSED + 1,
464 465
  SYMBOL_FIRST_CHILD,
  SYMBOL_LAST_CHILD,
466
  SYMBOL_SORTED_CHILD,
467 468 469 470 471 472 473 474

  /* Scope: nth-child */
  SYMBOL_NTH_CHILD_EVEN,
  SYMBOL_NTH_CHILD_ODD,
  SYMBOL_NTH_CHILD_FIRST,
  SYMBOL_NTH_CHILD_LAST
};

Carlos Garnacho's avatar
Carlos Garnacho committed
475 476 477
static void gtk_css_provider_finalize (GObject *object);
static void gtk_css_style_provider_iface_init (GtkStyleProviderIface *iface);

478 479
static void scanner_apply_scope (GScanner    *scanner,
                                 ParserScope  scope);
480 481 482
static gboolean css_provider_parse_value (GtkCssProvider *css_provider,
                                          const gchar    *value_str,
                                          GValue         *value);
483 484 485 486 487
static gboolean gtk_css_provider_load_from_path_internal (GtkCssProvider  *css_provider,
                                                          const gchar     *path,
                                                          gboolean         reset,
                                                          GError         **error);

Carlos Garnacho's avatar
Carlos Garnacho committed
488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530

G_DEFINE_TYPE_EXTENDED (GtkCssProvider, gtk_css_provider, G_TYPE_OBJECT, 0,
                        G_IMPLEMENT_INTERFACE (GTK_TYPE_STYLE_PROVIDER,
                                               gtk_css_style_provider_iface_init));

static void
gtk_css_provider_class_init (GtkCssProviderClass *klass)
{
  GObjectClass *object_class = G_OBJECT_CLASS (klass);

  object_class->finalize = gtk_css_provider_finalize;

  g_type_class_add_private (object_class, sizeof (GtkCssProviderPrivate));
}

static SelectorPath *
selector_path_new (void)
{
  SelectorPath *path;

  path = g_slice_new0 (SelectorPath);
  path->ref_count = 1;

  return path;
}

static SelectorPath *
selector_path_ref (SelectorPath *path)
{
  path->ref_count++;
  return path;
}

static void
selector_path_unref (SelectorPath *path)
{
  path->ref_count--;

  if (path->ref_count > 0)
    return;

  while (path->elements)
    {
531
      g_slice_free (SelectorElement, path->elements->data);
Carlos Garnacho's avatar
Carlos Garnacho committed
532 533 534 535 536 537 538 539 540 541 542 543 544 545
      path->elements = g_slist_delete_link (path->elements, path->elements);
    }

  g_slice_free (SelectorPath, path);
}

static void
selector_path_prepend_type (SelectorPath *path,
                            const gchar  *type_name)
{
  SelectorElement *elem;
  GType type;

  elem = g_slice_new (SelectorElement);
546
  elem->combinator = COMBINATOR_DESCENDANT;
Carlos Garnacho's avatar
Carlos Garnacho committed
547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562
  type = g_type_from_name (type_name);

  if (type == G_TYPE_INVALID)
    {
      elem->elem_type = SELECTOR_TYPE_NAME;
      elem->name = g_quark_from_string (type_name);
    }
  else
    {
      elem->elem_type = SELECTOR_GTYPE;
      elem->type = type;
    }

  path->elements = g_slist_prepend (path->elements, elem);
}

563 564 565 566 567 568 569
static void
selector_path_prepend_glob (SelectorPath *path)
{
  SelectorElement *elem;

  elem = g_slice_new (SelectorElement);
  elem->elem_type = SELECTOR_GLOB;
570
  elem->combinator = COMBINATOR_DESCENDANT;
571 572 573 574

  path->elements = g_slist_prepend (path->elements, elem);
}

575
static void
576 577 578
selector_path_prepend_region (SelectorPath   *path,
                              const gchar    *name,
                              GtkRegionFlags  flags)
579 580 581 582 583 584 585 586 587 588 589 590 591
{
  SelectorElement *elem;

  elem = g_slice_new (SelectorElement);
  elem->combinator = COMBINATOR_DESCENDANT;
  elem->elem_type = SELECTOR_REGION;

  elem->region.name = g_quark_from_string (name);
  elem->region.flags = flags;

  path->elements = g_slist_prepend (path->elements, elem);
}

592 593 594 595 596 597 598 599 600 601 602 603 604 605 606
static void
selector_path_prepend_name (SelectorPath *path,
                            const gchar  *name)
{
  SelectorElement *elem;

  elem = g_slice_new (SelectorElement);
  elem->combinator = COMBINATOR_DESCENDANT;
  elem->elem_type = SELECTOR_NAME;

  elem->name = g_quark_from_string (name);

  path->elements = g_slist_prepend (path->elements, elem);
}

607 608 609 610 611 612 613 614 615 616 617 618 619 620 621
static void
selector_path_prepend_class (SelectorPath *path,
                             const gchar  *name)
{
  SelectorElement *elem;

  elem = g_slice_new (SelectorElement);
  elem->combinator = COMBINATOR_DESCENDANT;
  elem->elem_type = SELECTOR_CLASS;

  elem->name = g_quark_from_string (name);

  path->elements = g_slist_prepend (path->elements, elem);
}

622 623 624 625 626 627 628 629 630 631 632 633 634
static void
selector_path_prepend_combinator (SelectorPath   *path,
                                  CombinatorType  combinator)
{
  SelectorElement *elem;

  g_assert (path->elements != NULL);

  /* It is actually stored in the last element */
  elem = path->elements->data;
  elem->combinator = combinator;
}

635 636 637 638 639 640
static gint
selector_path_depth (SelectorPath *path)
{
  return g_slist_length (path->elements);
}

Carlos Garnacho's avatar
Carlos Garnacho committed
641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674
static SelectorStyleInfo *
selector_style_info_new (SelectorPath *path)
{
  SelectorStyleInfo *info;

  info = g_slice_new0 (SelectorStyleInfo);
  info->path = selector_path_ref (path);

  return info;
}

static void
selector_style_info_free (SelectorStyleInfo *info)
{
  if (info->style)
    g_hash_table_unref (info->style);

  if (info->path)
    selector_path_unref (info->path);
}

static void
selector_style_info_set_style (SelectorStyleInfo *info,
                               GHashTable        *style)
{
  if (info->style)
    g_hash_table_unref (info->style);

  if (style)
    info->style = g_hash_table_ref (style);
  else
    info->style = NULL;
}

675 676
static GScanner *
create_scanner (void)
Carlos Garnacho's avatar
Carlos Garnacho committed
677 678 679 680 681
{
  GScanner *scanner;

  scanner = g_scanner_new (NULL);

682 683 684 685 686
  g_scanner_scope_add_symbol (scanner, SCOPE_PSEUDO_CLASS, "active", GUINT_TO_POINTER (GTK_STATE_ACTIVE));
  g_scanner_scope_add_symbol (scanner, SCOPE_PSEUDO_CLASS, "prelight", GUINT_TO_POINTER (GTK_STATE_PRELIGHT));
  g_scanner_scope_add_symbol (scanner, SCOPE_PSEUDO_CLASS, "hover", GUINT_TO_POINTER (GTK_STATE_PRELIGHT));
  g_scanner_scope_add_symbol (scanner, SCOPE_PSEUDO_CLASS, "selected", GUINT_TO_POINTER (GTK_STATE_SELECTED));
  g_scanner_scope_add_symbol (scanner, SCOPE_PSEUDO_CLASS, "insensitive", GUINT_TO_POINTER (GTK_STATE_INSENSITIVE));
687 688
  g_scanner_scope_add_symbol (scanner, SCOPE_PSEUDO_CLASS, "inconsistent", GUINT_TO_POINTER (GTK_STATE_INCONSISTENT));
  g_scanner_scope_add_symbol (scanner, SCOPE_PSEUDO_CLASS, "focused", GUINT_TO_POINTER (GTK_STATE_FOCUSED));
689

690 691 692
  g_scanner_scope_add_symbol (scanner, SCOPE_PSEUDO_CLASS, "nth-child", GUINT_TO_POINTER (SYMBOL_NTH_CHILD));
  g_scanner_scope_add_symbol (scanner, SCOPE_PSEUDO_CLASS, "first-child", GUINT_TO_POINTER (SYMBOL_FIRST_CHILD));
  g_scanner_scope_add_symbol (scanner, SCOPE_PSEUDO_CLASS, "last-child", GUINT_TO_POINTER (SYMBOL_LAST_CHILD));
693
  g_scanner_scope_add_symbol (scanner, SCOPE_PSEUDO_CLASS, "sorted", GUINT_TO_POINTER (SYMBOL_SORTED_CHILD));
694 695 696 697 698 699

  g_scanner_scope_add_symbol (scanner, SCOPE_NTH_CHILD, "even", GUINT_TO_POINTER (SYMBOL_NTH_CHILD_EVEN));
  g_scanner_scope_add_symbol (scanner, SCOPE_NTH_CHILD, "odd", GUINT_TO_POINTER (SYMBOL_NTH_CHILD_ODD));
  g_scanner_scope_add_symbol (scanner, SCOPE_NTH_CHILD, "first", GUINT_TO_POINTER (SYMBOL_NTH_CHILD_FIRST));
  g_scanner_scope_add_symbol (scanner, SCOPE_NTH_CHILD, "last", GUINT_TO_POINTER (SYMBOL_NTH_CHILD_LAST));

700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715
  scanner_apply_scope (scanner, SCOPE_SELECTOR);

  return scanner;
}

static void
gtk_css_provider_init (GtkCssProvider *css_provider)
{
  GtkCssProviderPrivate *priv;

  priv = css_provider->priv = G_TYPE_INSTANCE_GET_PRIVATE (css_provider,
                                                           GTK_TYPE_CSS_PROVIDER,
                                                           GtkCssProviderPrivate);

  priv->selectors_info = g_ptr_array_new_with_free_func ((GDestroyNotify) selector_style_info_free);
  priv->scanner = create_scanner ();
716 717 718 719

  priv->symbolic_colors = g_hash_table_new_full (g_str_hash, g_str_equal,
                                                 (GDestroyNotify) g_free,
                                                 (GDestroyNotify) gtk_symbolic_color_unref);
Carlos Garnacho's avatar
Carlos Garnacho committed
720 721 722 723 724 725 726 727 728 729 730 731
}

typedef struct ComparePathData ComparePathData;

struct ComparePathData
{
  guint64 score;
  SelectorPath *path;
  GSList *iter;
};

static gboolean
732 733 734 735
compare_selector_element (GtkWidgetPath   *path,
                          guint            index,
                          SelectorElement *elem,
                          guint8          *score)
Carlos Garnacho's avatar
Carlos Garnacho committed
736
{
737
  *score = 0;
Carlos Garnacho's avatar
Carlos Garnacho committed
738 739 740 741 742 743 744 745 746 747 748 749 750 751 752

  if (elem->elem_type == SELECTOR_TYPE_NAME)
    {
      const gchar *type_name;
      GType resolved_type;

      /* Resolve the type name */
      type_name = g_quark_to_string (elem->name);
      resolved_type = g_type_from_name (type_name);

      if (resolved_type == G_TYPE_INVALID)
        {
          /* Type couldn't be resolved, so the selector
           * clearly doesn't affect the given widget path
           */
753
          return FALSE;
Carlos Garnacho's avatar
Carlos Garnacho committed
754 755 756 757 758 759 760 761
        }

      elem->elem_type = SELECTOR_GTYPE;
      elem->type = resolved_type;
    }

  if (elem->elem_type == SELECTOR_GTYPE)
    {
762 763
      GType type;

764
      type = gtk_widget_path_iter_get_widget_type (path, index);
765

Carlos Garnacho's avatar
Carlos Garnacho committed
766
      if (!g_type_is_a (type, elem->type))
767 768 769 770
        return FALSE;

      if (type == elem->type)
        *score |= 0xF;
Carlos Garnacho's avatar
Carlos Garnacho committed
771 772 773
      else
        {
          GType parent = type;
774 775

          *score = 0xE;
Carlos Garnacho's avatar
Carlos Garnacho committed
776 777 778 779 780 781

          while ((parent = g_type_parent (parent)) != G_TYPE_INVALID)
            {
              if (parent == elem->type)
                break;

782
              *score -= 1;
Carlos Garnacho's avatar
Carlos Garnacho committed
783

784
              if (*score == 1)
Carlos Garnacho's avatar
Carlos Garnacho committed
785 786 787 788 789 790
                {
                  g_warning ("Hierarchy is higher than expected.");
                  break;
                }
            }
        }
791 792

      return TRUE;
Carlos Garnacho's avatar
Carlos Garnacho committed
793
    }
794 795
  else if (elem->elem_type == SELECTOR_REGION)
    {
796
      GtkRegionFlags flags;
797

798 799 800
      if (!gtk_widget_path_iter_has_qregion (path, index,
                                             elem->region.name,
                                             &flags))
801 802 803 804 805 806 807 808 809
        return FALSE;

      if (elem->region.flags != 0 &&
          (flags & elem->region.flags) == 0)
        return FALSE;

      *score = 0xF;
      return TRUE;
    }
810 811 812
  else if (elem->elem_type == SELECTOR_GLOB)
    {
      /* Treat as lowest matching type */
813 814
      *score = 1;
      return TRUE;
815
    }
816 817
  else if (elem->elem_type == SELECTOR_NAME)
    {
818
      if (!gtk_widget_path_iter_has_qname (path, index, elem->name))
819 820 821 822 823
        return FALSE;

      *score = 0xF;
      return TRUE;
    }
824 825 826 827 828 829 830 831
  else if (elem->elem_type == SELECTOR_CLASS)
    {
      if (!gtk_widget_path_iter_has_qclass (path, index, elem->name))
        return FALSE;

      *score = 0xF;
      return TRUE;
    }
Carlos Garnacho's avatar
Carlos Garnacho committed
832

833
  return FALSE;
Carlos Garnacho's avatar
Carlos Garnacho committed
834 835 836 837 838 839
}

static guint64
compare_selector (GtkWidgetPath *path,
                  SelectorPath  *selector)
{
840 841 842
  GSList *elements = selector->elements;
  gboolean match = TRUE;
  guint64 score = 0;
843
  gint i;
Carlos Garnacho's avatar
Carlos Garnacho committed
844

845
  i = gtk_widget_path_length (path) - 1;
846

847
  while (elements && match && i >= 0)
848 849 850
    {
      SelectorElement *elem;
      guint8 elem_score;
Carlos Garnacho's avatar
Carlos Garnacho committed
851

852
      elem = elements->data;
Carlos Garnacho's avatar
Carlos Garnacho committed
853

854
      match = compare_selector_element (path, i, elem, &elem_score);
855 856 857 858 859 860 861 862 863 864 865 866 867

      /* Only move on to the next index if there is no match
       * with the current element (whether to continue or not
       * handled right after in the combinator check), or a
       * GType or glob has just been matched.
       *
       * Region and widget names do not trigger this because
       * the next element in the selector path could also be
       * related to the same index.
       */
      if (!match ||
          (elem->elem_type == SELECTOR_GTYPE ||
           elem->elem_type == SELECTOR_GLOB))
868
        i--;
869

870 871 872
      if (!match &&
          elem->elem_type != SELECTOR_TYPE_NAME &&
          elem->combinator == COMBINATOR_DESCENDANT)
873 874 875 876 877 878
        {
          /* With descendant combinators there may
           * be intermediate chidren in the hierarchy
           */
          match = TRUE;
        }
879
      else if (match)
880
        elements = elements->next;
881 882 883

      if (match)
        {
884
          /* Only 4 bits are actually used */
885 886 887
          score <<= 4;
          score |= elem_score;
        }
Carlos Garnacho's avatar
Carlos Garnacho committed
888 889
    }

890 891 892 893 894 895 896 897 898 899 900
  /* If there are pending selector
   * elements to compare, it's not
   * a match.
   */
  if (elements)
    match = FALSE;

  if (!match)
    score = 0;

  return score;
Carlos Garnacho's avatar
Carlos Garnacho committed
901 902 903 904 905 906 907 908
}

typedef struct StylePriorityInfo StylePriorityInfo;

struct StylePriorityInfo
{
  guint64 score;
  GHashTable *style;
909
  GtkStateFlags state;
Carlos Garnacho's avatar
Carlos Garnacho committed
910 911
};

912 913 914
static GArray *
css_provider_get_selectors (GtkCssProvider *css_provider,
                            GtkWidgetPath  *path)
Carlos Garnacho's avatar
Carlos Garnacho committed
915 916 917 918 919
{
  GtkCssProviderPrivate *priv;
  GArray *priority_info;
  guint i, j;

920
  priv = css_provider->priv;
Carlos Garnacho's avatar
Carlos Garnacho committed
921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937
  priority_info = g_array_new (FALSE, FALSE, sizeof (StylePriorityInfo));

  for (i = 0; i < priv->selectors_info->len; i++)
    {
      SelectorStyleInfo *info;
      StylePriorityInfo new;
      gboolean added = FALSE;
      guint64 score;

      info = g_ptr_array_index (priv->selectors_info, i);
      score = compare_selector (path, info->path);

      if (score <= 0)
        continue;

      new.score = score;
      new.style = info->style;
938
      new.state = info->path->state;
Carlos Garnacho's avatar
Carlos Garnacho committed
939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957

      for (j = 0; j < priority_info->len; j++)
        {
          StylePriorityInfo *cur;

          cur = &g_array_index (priority_info, StylePriorityInfo, j);

          if (cur->score > new.score)
            {
              g_array_insert_val (priority_info, j, new);
              added = TRUE;
              break;
            }
        }

      if (!added)
        g_array_append_val (priority_info, new);
    }

958 959 960
  return priority_info;
}

961
static void
962 963
css_provider_dump_symbolic_colors (GtkCssProvider     *css_provider,
                                   GtkStyleProperties *props)
964 965 966 967 968
{
  GtkCssProviderPrivate *priv;
  GHashTableIter iter;
  gpointer key, value;

969
  priv = css_provider->priv;
970 971 972 973 974 975 976 977 978 979
  g_hash_table_iter_init (&iter, priv->symbolic_colors);

  while (g_hash_table_iter_next (&iter, &key, &value))
    {
      const gchar *name;
      GtkSymbolicColor *color;

      name = key;
      color = value;

980
      gtk_style_properties_map_color (props, name, color);
981 982 983
    }
}

984
static GtkStyleProperties *
985 986 987
gtk_css_provider_get_style (GtkStyleProvider *provider,
                            GtkWidgetPath    *path)
{
988
  GtkCssProvider *css_provider;
989
  GtkCssProviderPrivate *priv;
990
  GtkStyleProperties *props;
991 992 993
  GArray *priority_info;
  guint i;

994
  css_provider = GTK_CSS_PROVIDER (provider);
995
  props = gtk_style_properties_new ();
996
  priv = css_provider->priv;
997

998
  css_provider_dump_symbolic_colors (css_provider, props);
999
  priority_info = css_provider_get_selectors (css_provider, path);
1000

Carlos Garnacho's avatar
Carlos Garnacho committed
1001 1002 1003 1004 1005 1006 1007 1008 1009 1010
  for (i = 0; i < priority_info->len; i++)
    {
      StylePriorityInfo *info;
      GHashTableIter iter;
      gpointer key, value;

      info = &g_array_index (priority_info, StylePriorityInfo, i);
      g_hash_table_iter_init (&iter, info->style);

      while (g_hash_table_iter_next (&iter, &key, &value))
1011
        {
1012 1013
          gchar *prop = key;

1014 1015 1016 1017 1018
          /* Properties starting with '-' may be both widget style properties
           * or custom properties from the theming engine, so check whether
           * the type is registered or not.
           */
          if (prop[0] == '-' &&
1019
              !gtk_style_properties_lookup_property (prop, NULL, NULL))
1020 1021
            continue;

1022
          gtk_style_properties_set_property (props, key, info->state, value);
1023
        }
Carlos Garnacho's avatar
Carlos Garnacho committed
1024 1025 1026 1027
    }

  g_array_free (priority_info, TRUE);

1028
  return props;
Carlos Garnacho's avatar
Carlos Garnacho committed
1029 1030
}

1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065
static gboolean
gtk_css_provider_get_style_property (GtkStyleProvider *provider,
                                     GtkWidgetPath    *path,
                                     const gchar      *property_name,
                                     GValue           *value)
{
  GArray *priority_info;
  gboolean found = FALSE;
  gchar *prop_name;
  GType path_type;
  gint i;

  path_type = gtk_widget_path_get_widget_type (path);

  prop_name = g_strdup_printf ("-%s-%s",
                               g_type_name (path_type),
                               property_name);

  priority_info = css_provider_get_selectors (GTK_CSS_PROVIDER (provider), path);

  for (i = priority_info->len - 1; i >= 0; i--)
    {
      StylePriorityInfo *info;
      GValue *val;

      info = &g_array_index (priority_info, StylePriorityInfo, i);
      val = g_hash_table_lookup (info->style, prop_name);

      if (val)
        {
          const gchar *val_str;

          val_str = g_value_get_string (val);
          found = TRUE;

1066
          css_provider_parse_value (GTK_CSS_PROVIDER (provider), val_str, value);
1067 1068 1069 1070 1071 1072 1073 1074 1075 1076
          break;
        }
    }

  g_array_free (priority_info, TRUE);
  g_free (prop_name);

  return found;
}

Carlos Garnacho's avatar
Carlos Garnacho committed
1077 1078 1079
static void
gtk_css_style_provider_iface_init (GtkStyleProviderIface *iface)
{
1080 1081
  iface->get_style = gtk_css_provider_get_style;
  iface->get_style_property = gtk_css_provider_get_style_property;
Carlos Garnacho's avatar
Carlos Garnacho committed
1082 1083 1084 1085 1086
}

static void
gtk_css_provider_finalize (GObject *object)
{
1087
  GtkCssProvider *css_provider;
Carlos Garnacho's avatar
Carlos Garnacho committed
1088 1089
  GtkCssProviderPrivate *priv;

1090 1091
  css_provider = GTK_CSS_PROVIDER (object);
  priv = css_provider->priv;
1092

Carlos Garnacho's avatar
Carlos Garnacho committed
1093
  g_scanner_destroy (priv->scanner);
1094
  g_free (priv->filename);
Carlos Garnacho's avatar
Carlos Garnacho committed
1095 1096 1097 1098 1099 1100 1101

  g_ptr_array_free (priv->selectors_info, TRUE);

  g_slist_foreach (priv->cur_selectors, (GFunc) selector_path_unref, NULL);
  g_slist_free (priv->cur_selectors);

  g_hash_table_unref (priv->cur_properties);
1102
  g_hash_table_destroy (priv->symbolic_colors);
Carlos Garnacho's avatar
Carlos Garnacho committed
1103 1104 1105 1106

  G_OBJECT_CLASS (gtk_css_provider_parent_class)->finalize (object);
}

Carlos Garnacho's avatar
Carlos Garnacho committed
1107 1108 1109 1110 1111 1112 1113
/**
 * gtk_css_provider_new:
 *
 * Returns a newly created #GtkCssProvider.
 *
 * Returns: A new #GtkCssProvider
 **/
Carlos Garnacho's avatar
Carlos Garnacho committed
1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129
GtkCssProvider *
gtk_css_provider_new (void)
{
  return g_object_new (GTK_TYPE_CSS_PROVIDER, NULL);
}

static void
property_value_free (GValue *value)
{
  if (G_IS_VALUE (value))
    g_value_unset (value);

  g_slice_free (GValue, value);
}

static void
1130 1131
scanner_apply_scope (GScanner    *scanner,
                     ParserScope  scope)
Carlos Garnacho's avatar
Carlos Garnacho committed
1132
{
1133
  g_scanner_set_scope (scanner, scope);
Carlos Garnacho's avatar
Carlos Garnacho committed
1134 1135 1136

  if (scope == SCOPE_VALUE)
    {
1137
      scanner->config->cset_identifier_first = G_CSET_a_2_z "@#-_0123456789" G_CSET_A_2_Z;
1138
      scanner->config->cset_identifier_nth = G_CSET_a_2_z "@#-_ 0123456789(),.\t\n" G_CSET_A_2_Z;
1139
      scanner->config->scan_identifier_1char = TRUE;
1140 1141 1142
    }
  else if (scope == SCOPE_SELECTOR)
    {
1143
      scanner->config->cset_identifier_first = G_CSET_a_2_z G_CSET_A_2_Z "*@";
1144
      scanner->config->cset_identifier_nth = G_CSET_a_2_z "-_#." G_CSET_A_2_Z;
1145
      scanner->config->scan_identifier_1char = TRUE;
Carlos Garnacho's avatar
Carlos Garnacho committed
1146
    }
1147 1148 1149
  else if (scope == SCOPE_PSEUDO_CLASS ||
           scope == SCOPE_NTH_CHILD ||
           scope == SCOPE_DECLARATION)
Carlos Garnacho's avatar
Carlos Garnacho committed
1150
    {
1151 1152 1153
      scanner->config->cset_identifier_first = G_CSET_a_2_z "-" G_CSET_A_2_Z;
      scanner->config->cset_identifier_nth = G_CSET_a_2_z "-" G_CSET_A_2_Z;
      scanner->config->scan_identifier_1char = FALSE;
Carlos Garnacho's avatar
Carlos Garnacho committed
1154
    }
1155 1156
  else
    g_assert_not_reached ();
Carlos Garnacho's avatar
Carlos Garnacho committed
1157

1158 1159
  scanner->config->scan_float = FALSE;
  scanner->config->cpair_comment_single = NULL;
Carlos Garnacho's avatar
Carlos Garnacho committed
1160 1161 1162 1163 1164 1165 1166 1167
}

static void
css_provider_push_scope (GtkCssProvider *css_provider,
                         ParserScope     scope)
{
  GtkCssProviderPrivate *priv;

1168
  priv = css_provider->priv;
Carlos Garnacho's avatar
Carlos Garnacho committed
1169 1170
  priv->state = g_slist_prepend (priv->state, GUINT_TO_POINTER (scope));

1171
  scanner_apply_scope (priv->scanner, scope);
Carlos Garnacho's avatar
Carlos Garnacho committed
1172 1173 1174 1175 1176 1177 1178 1179
}

static ParserScope
css_provider_pop_scope (GtkCssProvider *css_provider)
{
  GtkCssProviderPrivate *priv;
  ParserScope scope = SCOPE_SELECTOR;

1180
  priv = css_provider->priv;
Carlos Garnacho's avatar
Carlos Garnacho committed
1181 1182 1183 1184

  if (!priv->state)
    {
      g_warning ("Push/pop calls to parser scope aren't paired");
1185
      scanner_apply_scope (priv->scanner, SCOPE_SELECTOR);
Carlos Garnacho's avatar
Carlos Garnacho committed
1186 1187 1188 1189 1190 1191 1192 1193 1194
      return SCOPE_SELECTOR;
    }

  priv->state = g_slist_delete_link (priv->state, priv->state);

  /* Fetch new scope */
  if (priv->state)
    scope = GPOINTER_TO_INT (priv->state->data);

1195
  scanner_apply_scope (priv->scanner, scope);
Carlos Garnacho's avatar
Carlos Garnacho committed
1196 1197 1198 1199 1200 1201 1202 1203 1204

  return scope;
}

static void
css_provider_reset_parser (GtkCssProvider *css_provider)
{
  GtkCssProviderPrivate *priv;

1205
  priv = css_provider->priv;
Carlos Garnacho's avatar
Carlos Garnacho committed
1206 1207 1208 1209

  g_slist_free (priv->state);
  priv->state = NULL;

1210
  scanner_apply_scope (priv->scanner, SCOPE_SELECTOR);
Carlos Garnacho's avatar
Carlos Garnacho committed
1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230

  g_slist_foreach (priv->cur_selectors, (GFunc) selector_path_unref, NULL);
  g_slist_free (priv->cur_selectors);
  priv->cur_selectors = NULL;

  if (priv->cur_properties)
    g_hash_table_unref (priv->cur_properties);

  priv->cur_properties = g_hash_table_new_full (g_str_hash,
                                                g_str_equal,
                                                (GDestroyNotify) g_free,
                                                (GDestroyNotify) property_value_free);
}

static void
css_provider_commit (GtkCssProvider *css_provider)
{
  GtkCssProviderPrivate *priv;
  GSList *l;

1231
  priv = css_provider->priv;
Carlos Garnacho's avatar
Carlos Garnacho committed
1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246
  l = priv->cur_selectors;

  while (l)
    {
      SelectorPath *path = l->data;
      SelectorStyleInfo *info;

      info = selector_style_info_new (path);
      selector_style_info_set_style (info, priv->cur_properties);

      g_ptr_array_add (priv->selectors_info, info);
      l = l->next;
    }
}

1247
static GTokenType
1248 1249 1250
parse_nth_child (GtkCssProvider *css_provider,
                 GScanner       *scanner,
                 GtkRegionFlags *flags)
1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278
{
  ParserSymbol symbol;

  g_scanner_get_next_token (scanner);

  if (scanner->token != G_TOKEN_SYMBOL)
    return G_TOKEN_SYMBOL;

  symbol = GPOINTER_TO_INT (scanner->value.v_symbol);

  if (symbol == SYMBOL_NTH_CHILD)
    {
      g_scanner_get_next_token (scanner);

      if (scanner->token != G_TOKEN_LEFT_PAREN)
        return G_TOKEN_LEFT_PAREN;

      css_provider_push_scope (css_provider, SCOPE_NTH_CHILD);
      g_scanner_get_next_token (scanner);

      if (scanner->token != G_TOKEN_SYMBOL)
        return G_TOKEN_SYMBOL;

      symbol = GPOINTER_TO_INT (scanner->value.v_symbol);

      switch (symbol)
        {
        case SYMBOL_NTH_CHILD_EVEN:
1279
          *flags = GTK_REGION_EVEN;
1280 1281
          break;
        case SYMBOL_NTH_CHILD_ODD:
1282
          *flags = GTK_REGION_ODD;
1283 1284
          break;
        case SYMBOL_NTH_CHILD_FIRST:
1285
          *flags = GTK_REGION_FIRST;
1286 1287
          break;
        case SYMBOL_NTH_CHILD_LAST:
1288
          *flags = GTK_REGION_LAST;
1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301
          break;
        default:
          break;
        }

      g_scanner_get_next_token (scanner);

      if (scanner->token != G_TOKEN_RIGHT_PAREN)
        return G_TOKEN_RIGHT_PAREN;

      css_provider_pop_scope (css_provider);
    }
  else if (symbol == SYMBOL_FIRST_CHILD)
1302
    *flags = GTK_REGION_FIRST;
1303
  else if (symbol == SYMBOL_LAST_CHILD)
1304
    *flags = GTK_REGION_LAST;
1305 1306
  else if (symbol == SYMBOL_SORTED_CHILD)
    *flags = GTK_REGION_SORTED;
1307 1308
  else
    {
1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321
      *flags = 0;
      return G_TOKEN_SYMBOL;
    }

  return G_TOKEN_NONE;
}

static GTokenType
parse_pseudo_class (GtkCssProvider *css_provider,
                    GScanner       *scanner,
                    SelectorPath   *selector)
{
  GtkStateType state;
1322

1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351
  g_scanner_get_next_token (scanner);

  if (scanner->token != G_TOKEN_SYMBOL)
    return G_TOKEN_SYMBOL;

  state = GPOINTER_TO_INT (scanner->value.v_symbol);

  switch (state)
    {
    case GTK_STATE_ACTIVE:
      selector->state |= GTK_STATE_FLAG_ACTIVE;
      break;
    case GTK_STATE_PRELIGHT:
      selector->state |= GTK_STATE_FLAG_PRELIGHT;
      break;
    case GTK_STATE_SELECTED:
      selector->state |= GTK_STATE_FLAG_SELECTED;
      break;
    case GTK_STATE_INSENSITIVE:
      selector->state |= GTK_STATE_FLAG_INSENSITIVE;
      break;
    case GTK_STATE_INCONSISTENT:
      selector->state |= GTK_STATE_FLAG_INCONSISTENT;
      break;
    case GTK_STATE_FOCUSED:
      selector->state |= GTK_STATE_FLAG_FOCUSED;
      break;
    default:
      return G_TOKEN_SYMBOL;
1352
    }
1353 1354 1355 1356

  return G_TOKEN_NONE;
}

1357 1358 1359 1360 1361 1362 1363 1364 1365
/* Parses a number of concatenated classes */
static void
parse_classes (SelectorPath   *path,
               const gchar    *str)
{
  gchar *pos;

  if ((pos = strchr (str, '.')) != NULL)
    {
1366
      /* Leave the last class to the call after the loop */
1367 1368 1369 1370 1371 1372 1373 1374 1375
      while (pos)
        {
          *pos = '\0';
          selector_path_prepend_class (path, str);

          str = pos + 1;
          pos = strchr (str, '.');
        }
    }
1376 1377

  selector_path_prepend_class (path, str);
1378 1379
}

Carlos Garnacho's avatar
Carlos Garnacho committed
1380
static GTokenType
1381 1382 1383
parse_selector (GtkCssProvider  *css_provider,
                GScanner        *scanner,
                SelectorPath   **selector_out)
Carlos Garnacho's avatar
Carlos Garnacho committed
1384 1385 1386
{
  SelectorPath *path;

1387 1388
  path = selector_path_new ();
  *selector_out = path;
Carlos Garnacho's avatar
Carlos Garnacho committed
1389

1390
  if (scanner->token != ':' &&
1391
      scanner->token != '#' &&
1392
      scanner->token != '.' &&
1393
      scanner->token != G_TOKEN_IDENTIFIER)
Carlos Garnacho's avatar
Carlos Garnacho committed
1394 1395
    return G_TOKEN_IDENTIFIER;

1396
  while (scanner->token == '#' ||
1397
         scanner->token == '.' ||
1398
         scanner->token == G_TOKEN_IDENTIFIER)
Carlos Garnacho's avatar
Carlos Garnacho committed
1399
    {
1400 1401
      if (scanner->token == '#' ||
          scanner->token == '.')
1402
        {
1403
          gboolean is_class;
1404
          gchar *pos;
1405 1406 1407

          is_class = (scanner->token == '.');

1408 1409 1410 1411 1412
          g_scanner_get_next_token (scanner);

          if (scanner->token != G_TOKEN_IDENTIFIER)
            return G_TOKEN_IDENTIFIER;

1413 1414
          selector_path_prepend_glob (path);
          selector_path_prepend_combinator (path, COMBINATOR_CHILD);
1415 1416

          if (is_class)
1417
            parse_classes (path, scanner->value.v_identifier);
1418
          else
1419 1420 1421 1422 1423 1424 1425 1426 1427 1428
            {
              if ((pos = strchr (scanner->value.v_identifier, '.')) != NULL)
                *pos = '\0';

              selector_path_prepend_name (path, scanner->value.v_identifier);

              /* Parse any remaining classes */
              if (pos)
                parse_classes (path, pos + 1);
            }
1429 1430
        }
      else if (g_ascii_isupper (scanner->value.v_identifier[0]))
1431 1432 1433
        {
          gchar *pos;

1434 1435
          if ((pos = strchr (scanner->value.v_identifier, '#')) != NULL ||
              (pos = strchr (scanner->value.v_identifier, '.')) != NULL)
1436 1437
            {
              gchar *type_name, *name;
1438 1439 1440
              gboolean is_class;

              is_class = (*pos == '.');
1441

1442
              /* Widget type and name/class put together */
1443 1444 1445 1446 1447 1448 1449 1450 1451 1452
              name = pos + 1;
              *pos = '\0';
              type_name = scanner->value.v_identifier;

              selector_path_prepend_type (path, type_name);

              /* This is only so there is a direct relationship
               * between widget type and its name.
               */
              selector_path_prepend_combinator (path, COMBINATOR_CHILD);
1453 1454

              if (is_class)
1455
                parse_classes (path, name);
1456
              else
1457 1458 1459 1460 1461 1462 1463 1464 1465 1466
                {
                  if ((pos = strchr (name, '.')) != NULL)
                    *pos = '\0';

                  selector_path_prepend_name (path, name);

                  /* Parse any remaining classes */
                  if (pos)
                    parse_classes (path, pos + 1);
                }
1467 1468 1469 1470
            }
          else
            selector_path_prepend_type (path, scanner->value.v_identifier);
        }
1471 1472
      else if (g_ascii_islower (scanner->value.v_identifier[0]))
        {
1473
          GtkRegionFlags flags = 0;
1474 1475 1476
          gchar *region_name;

          region_name = g_strdup (scanner->value.v_identifier);
1477

1478
          if (g_scanner_peek_next_token (scanner) == ':')
1479
            {
1480
              ParserSymbol symbol;
1481

1482
              g_scanner_get_next_token (scanner);
1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494
              css_provider_push_scope (css_provider, SCOPE_PSEUDO_CLASS);

              /* Check for the next token being nth-child, parse in that
               * case, and fallback into common state parsing if not.
               */
              if (g_scanner_peek_next_token (scanner) != G_TOKEN_SYMBOL)
                return G_TOKEN_SYMBOL;

              symbol = GPOINTER_TO_INT (scanner->next_value.v_symbol);

              if (symbol == SYMBOL_FIRST_CHILD ||
                  symbol == SYMBOL_LAST_CHILD ||
1495 1496
                  symbol == SYMBOL_NTH_CHILD ||
                  symbol == SYMBOL_SORTED_CHILD)
1497 1498
                {
                  GTokenType token;
1499

1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511
                  if ((token = parse_nth_child (css_provider, scanner, &flags)) != G_TOKEN_NONE)
                    return token;

                  css_provider_pop_scope (css_provider);
                }
              else
                {
                  css_provider_pop_scope (css_provider);
                  selector_path_prepend_region (path, region_name, 0);
                  g_free (region_name);
                  break;
                }
1512
            }
1513 1514 1515

          selector_path_prepend_region (path, region_name, flags);
          g_free (region_name);
1516
        }
1517 1518 1519
      else if (scanner->value.v_identifier[0] == '*')
        selector_path_prepend_glob (path);
      else
1520
        return G_TOKEN_IDENTIFIER;
Carlos Garnacho's avatar
Carlos Garnacho committed
1521

1522
      g_scanner_get_next_token (scanner);
1523 1524 1525 1526 1527 1528

      if (scanner->token == '>')
        {
          selector_path_prepend_combinator (path, COMBINATOR_CHILD);
          g_scanner_get_next_token (scanner);
        }
Carlos Garnacho's avatar
Carlos Garnacho committed
1529 1530
    }

1531
  if (scanner->token == ':')
1532
    {
1533 1534 1535 1536
      /* Add glob selector if path is empty */
      if (selector_path_depth (path) == 0)
        selector_path_prepend_glob (path);

1537
      css_provider_push_scope (css_provider, SCOPE_PSEUDO_CLASS);
1538

1539
      while (scanner->token == ':')
1540
        {
1541 1542 1543 1544 1545 1546
          GTokenType token;

          if ((token = parse_pseudo_class (css_provider, scanner, path)) != G_TOKEN_NONE)
            return token;

          g_scanner_get_next_token (scanner);
1547
        }
1548

1549
      css_provider_pop_scope (css_provider);
1550 1551
    }

Carlos Garnacho's avatar
Carlos Garnacho committed
1552 1553 1554
  return G_TOKEN_NONE;
}

1555
#define SKIP_SPACES(s) while (s[0] == ' ' || s[0] == '\t' || s[0] == '\n') s++;
1556 1557 1558 1559 1560 1561 1562 1563 1564

static GtkSymbolicColor *
symbolic_color_parse_str (const gchar  *string,
			  gchar       **end_ptr)
{
  GtkSymbolicColor *symbolic_color = NULL;
  gchar *str;

  str = (gchar *) string;
1565
  *end_ptr = str;
1566

1567
  if (str[0] == '@')
1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584
    {
      const gchar *end;
      gchar *name;

      str++;
      end = str;

      while (*end == '-' || *end == '_' ||
             g_ascii_isalpha (*end))
        end++;

      name = g_strndup (str, end - str);
      symbolic_color = gtk_symbolic_color_new_name (name);
      g_free (name);

      *end_ptr = (gchar *) end;
    }
1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630
  else if (g_str_has_prefix (str, "lighter") ||
           g_str_has_prefix (str, "darker"))
    {
      GtkSymbolicColor *param_color;
      gboolean is_lighter = FALSE;

      is_lighter = g_str_has_prefix (str, "lighter");

      if (is_lighter)
        str += strlen ("lighter");
      else
        str += strlen ("darker");

      SKIP_SPACES (str);

      if (*str != '(')
        {
          *end_ptr = (gchar *) str;
          return NULL;
        }

      str++;
      SKIP_SPACES (str);
      param_color = symbolic_color_parse_str (str, end_ptr);

      if (!param_color)
        return NULL;

      str = *end_ptr;
      SKIP_SPACES (str);
      *end_ptr = (gchar *) str;

      if (*str != ')')
        {
          gtk_symbolic_color_unref (param_color);
          return NULL;
        }

      if (is_lighter)
        symbolic_color = gtk_symbolic_color_new_shade (param_color, 1.3);
      else
        symbolic_color = gtk_symbolic_color_new_shade (param_color, 0.7);

      gtk_symbolic_color_unref (param_color);
      (*end_ptr)++;
    }
1631 1632
  else if (g_str_has_prefix (str, "shade") ||
           g_str_has_prefix (str, "alpha"))
1633 1634
    {
      GtkSymbolicColor *param_color;
1635
      gboolean is_shade = FALSE;
1636 1637
      gdouble factor;

1638 1639 1640 1641 1642 1643
      is_shade = g_str_has_prefix (str, "shade");

      if (is_shade)
        str += strlen ("shade");
      else
        str += strlen ("alpha");
1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683

      SKIP_SPACES (str);

      if (*str != '(')
        {
          *end_ptr = (gchar *) str;
          return NULL;
        }

      str++;
      SKIP_SPACES (str);
      param_color = symbolic_color_parse_str (str, end_ptr);

      if (!param_color)
        return NULL;

      str = *end_ptr;
      SKIP_SPACES (str);

      if (str[0] != ',')
        {
          gtk_symbolic_color_unref (param_color);
          *end_ptr = (gchar *) str;
          return NULL;
        }

      str++;
      SKIP_SPACES (str);
      factor = g_ascii_strtod (str, end_ptr);

      str = *end_ptr;
      SKIP_SPACES (str);
      *end_ptr = (gchar *) str;

      if (str[0] != ')')
        {
          gtk_symbolic_color_unref (param_color);
          return NULL;
        }

1684 1685 1686 1687 1688
      if (is_shade)
        symbolic_color = gtk_symbolic_color_new_shade (param_color, factor);
      else
        symbolic_color = gtk_symbolic_color_new_alpha (param_color, factor);

Carlos Garnacho's avatar
Carlos Garnacho committed
1689
      gtk_symbolic_color_unref (param_color);
1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759
      (*end_ptr)++;
    }
  else if (g_str_has_prefix (str, "mix"))
    {
      GtkSymbolicColor *color1, *color2;
      gdouble factor;

      str += strlen ("mix");
      SKIP_SPACES (str);

      if (*str != '(')
        {
          *end_ptr = (gchar *) str;
          return NULL;
        }

      str++;
      SKIP_SPACES (str);
      color1 = symbolic_color_parse_str (str, end_ptr);

      if (!color1)
        return NULL;

      str = *end_ptr;
      SKIP_SPACES (str);

      if (str[0] != ',')
        {
          gtk_symbolic_color_unref (color1);
          *end_ptr = (gchar *) str;
          return NULL;
        }

      str++;
      SKIP_SPACES (str);
      color2 = symbolic_color_parse_str (str, end_ptr);

      if (!color2 || *end_ptr[0] != ',')
        {
          gtk_symbolic_color_unref (color1);
          return NULL;
        }

      str = *end_ptr;
      SKIP_SPACES (str);

      if (str[0] != ',')
        {
          gtk_symbolic_color_unref (color1);
          gtk_symbolic_color_unref (color2);
          *end_ptr = (gchar *) str;
          return NULL;
        }

      str++;
      SKIP_SPACES (str);
      factor = g_ascii_strtod (str, end_ptr);

      str = *end_ptr;
      SKIP_SPACES (str);
      *end_ptr = (gchar *) str;

      if (str[0] != ')')
	{
          gtk_symbolic_color_unref (color1);
          gtk_symbolic_color_unref (color2);
          return NULL;
        }

      symbolic_color = gtk_symbolic_color_new_mix (color1, color2, factor);
Carlos Garnacho's avatar
Carlos Garnacho committed
1760 1761
      gtk_symbolic_color_unref (color1);
      gtk_symbolic_color_unref (color2);
1762 1763
      (*end_ptr)++;
    }
1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805
  else
    {
      GdkRGBA color;
      gchar *color_str;
      const gchar *end;

      end = str + 1;

      if (str[0] == '#')
        {
          /* Color in hex format */
          while (g_ascii_isxdigit (*end))
            end++;
        }
      else if (g_str_has_prefix (str, "rgb"))
        {
          /* color in rgb/rgba format */
          while (*end != ')' && *end != '\0')
            end++;

          if (*end == ')')
            end++;
        }
      else
        {
          /* color name? parse until first whitespace */
          while (*end != ' ' && *end != '\0')
            end++;
        }

      color_str = g_strndup (str, end - str);
      *end_ptr = (gchar *) end;

      if (!gdk_rgba_parse (&color, color_str))
        {
          g_free (color_str);
          return NULL;
        }

      symbolic_color = gtk_symbolic_color_new_literal (&color);
      g_free (color_str);
    }
1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832

  return symbolic_color;
}

static GtkSymbolicColor *
symbolic_color_parse (const gchar *str)
{
  GtkSymbolicColor *color;
  gchar *end;

  color = symbolic_color_parse_str (str, &end);

  if (*end != '\0')
    {
      g_warning ("Error parsing symbolic color \"%s\", stopped at char %ld : '%c'",
                 str, end - str, *end);

      if (color)
        {
          gtk_symbolic_color_unref (color);
          color = NULL;
        }
    }

  return color;
}

1833 1834 1835 1836 1837
static GtkGradient *
gradient_parse_str (const gchar  *str,
                    gchar       **end_ptr)
{
  GtkGradient *gradient = NULL;
1838 1839 1840
  gdouble coords[6];
  gchar *end;
  guint i;
1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876

  if (g_str_has_prefix (str, "-gtk-gradient"))
    {
      cairo_pattern_type_t type;

      str += strlen ("-gtk-gradient");
      SKIP_SPACES (str);

      if (*str != '(')
        {
          *end_ptr = (gchar *) str;
          return NULL;
        }

      str++;
      SKIP_SPACES (str);

      /* Parse gradient type */
      if (g_str_has_prefix (str, "linear"))
        {
          type = CAIRO_PATTERN_TYPE_LINEAR;
          str += strlen ("linear");
        }
      else if (g_str_has_prefix (str, "radial"))
        {
          type = CAIRO_PATTERN_TYPE_RADIAL;
          str += strlen ("radial");
        }
      else
        {
          *end_ptr = (gchar *) str;
          return NULL;
        }

      SKIP_SPACES (str);

1877 1878
      /* Parse start/stop position parameters */
      for (i = 0; i < 2; i++)
1879
        {
1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933
          if (*str != ',')
            {
              *end_ptr = (gchar *) str;
              return NULL;
            }

          str++;
          SKIP_SPACES (str);

          if (strncmp (str, "left", 4) == 0)
            {
              coords[i * 3] = 0;
              str += strlen ("left");
            }
          else if (strncmp (str, "right", 5) == 0)
            {
              coords[i * 3] = 1;
              str += strlen ("right");
            }
          else if (strncmp (str, "center", 6) == 0)
            {
              coords[i * 3] = 0.5;
              str += strlen ("center");
            }
          else
            {
              coords[i * 3] = g_ascii_strtod (str, &end);
              str = end;
            }

          SKIP_SPACES (str);

          if (strncmp (str, "top", 3) == 0)
            {
              coords[(i * 3) + 1] = 0;
              str += strlen ("top");
            }
          else if (strncmp (str, "bottom", 6) == 0)
            {
              coords[(i * 3) + 1] = 1;
              str += strlen ("bottom");
            }
          else if (strncmp (str, "center", 6) == 0)
            {
              coords[(i * 3) + 1] = 0.5;
              str += strlen ("center");
            }
          else
            {
              coords[(i * 3) + 1] = g_ascii_strtod (str, &end);
              str = end;
            }

          SKIP_SPACES (str);
1934

1935
          if (type == CAIRO_PATTERN_TYPE_RADIAL)
1936
            {
1937
              /* Parse radius */
1938 1939 1940 1941 1942 1943 1944 1945 1946
              if (*str != ',')
                {
                  *end_ptr = (gchar *) str;
                  return NULL;
                }

              str++;
              SKIP_SPACES (str);

1947 1948
              coords[(i * 3) + 2] = g_ascii_strtod (str, &end);
              str = end;
1949 1950

              SKIP_SPACES (str);
1951 1952
            }
        }
1953

1954 1955 1956 1957 1958
      if (type == CAIRO_PATTERN_TYPE_LINEAR)
        gradient = gtk_gradient_new_linear (coords[0], coords[1], coords[3], coords[4]);
      else
        gradient = gtk_gradient_new_radial (coords[0], coords[1], coords[2],
                                            coords[3], coords[4], coords[5]);
1959

1960 1961 1962 1963 1964 1965 1966 1967 1968
      while (*str == ',')
        {
          GtkSymbolicColor *color;
          gdouble position;

          if (*str != ',')
            {
              *end_ptr = (gchar *) str;
              return gradient;
1969 1970
            }

1971 1972
          str++;
          SKIP_SPACES (str);
1973

1974
          if (g_str_has_prefix (str, "from"))
1975
            {
1976 1977 1978
              position = 0;
              str += strlen ("from");
              SKIP_SPACES (str);
1979

1980
              if (*str != '(')
1981 1982 1983 1984
                {
                  *end_ptr = (gchar *) str;
                  return gradient;
                }
1985 1986 1987 1988 1989
            }
          else if (g_str_has_prefix (str, "to"))
            {
              position = 1;
              str += strlen ("to");
1990 1991
              SKIP_SPACES (str);

1992
              if (*str != '(')