gtkbuilderparser.c 39.6 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
/* gtkbuilderparser.c
 * Copyright (C) 2006-2007 Async Open Source,
 *                         Johan Dahlin <jdahlin@async.com.br>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library 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
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public
Javier Jardón's avatar
Javier Jardón committed
16
 * License along with this library. If not, see <http://www.gnu.org/licenses/>.
17 18
 */

19
#include "config.h"
20

21 22 23
#include <string.h>
#include <gmodule.h>

24
#include <gio/gio.h>
25 26 27 28
#include "gtkbuilderprivate.h"
#include "gtkbuilder.h"
#include "gtkbuildable.h"
#include "gtkdebug.h"
29
#include "gtkversion.h"
30
#include "gtktypebuiltins.h"
31
#include "gtkintl.h"
32

33

34 35
static void free_property_info (PropertyInfo *info);
static void free_object_info (ObjectInfo *info);
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 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134

static inline void
state_push (ParserData *data, gpointer info)
{
  data->stack = g_slist_prepend (data->stack, info);
}

static inline gpointer
state_peek (ParserData *data)
{
  if (!data->stack)
    return NULL;

  return data->stack->data;
}

static inline gpointer
state_pop (ParserData *data)
{
  gpointer old = NULL;

  if (!data->stack)
    return NULL;

  old = data->stack->data;
  data->stack = g_slist_delete_link (data->stack, data->stack);
  return old;
}
#define state_peek_info(data, st) ((st*)state_peek(data))
#define state_pop_info(data, st) ((st*)state_pop(data))

static void
error_missing_attribute (ParserData *data,
                         const gchar *tag,
                         const gchar *attribute,
                         GError **error)
{
  gint line_number, char_number;

  g_markup_parse_context_get_position (data->ctx,
                                       &line_number,
                                       &char_number);

  g_set_error (error,
               GTK_BUILDER_ERROR,
               GTK_BUILDER_ERROR_MISSING_ATTRIBUTE,
               "%s:%d:%d <%s> requires attribute \"%s\"",
               data->filename,
               line_number, char_number, tag, attribute);
}

static void
error_invalid_attribute (ParserData *data,
                         const gchar *tag,
                         const gchar *attribute,
                         GError **error)
{
  gint line_number, char_number;

  g_markup_parse_context_get_position (data->ctx,
                                       &line_number,
                                       &char_number);

  g_set_error (error,
               GTK_BUILDER_ERROR,
               GTK_BUILDER_ERROR_INVALID_ATTRIBUTE,
               "%s:%d:%d '%s' is not a valid attribute of <%s>",
               data->filename,
               line_number, char_number, attribute, tag);
}

static void
error_invalid_tag (ParserData *data,
		   const gchar *tag,
		   const gchar *expected,
		   GError **error)
{
  gint line_number, char_number;

  g_markup_parse_context_get_position (data->ctx,
                                       &line_number,
                                       &char_number);

  if (expected)
    g_set_error (error,
		 GTK_BUILDER_ERROR,
		 GTK_BUILDER_ERROR_INVALID_TAG,
		 "%s:%d:%d '%s' is not a valid tag here, expected a '%s' tag",
		 data->filename,
		 line_number, char_number, tag, expected);
  else
    g_set_error (error,
		 GTK_BUILDER_ERROR,
		 GTK_BUILDER_ERROR_INVALID_TAG,
		 "%s:%d:%d '%s' is not a valid tag here",
		 data->filename,
		 line_number, char_number, tag);
}

135
gboolean
136 137 138
_gtk_builder_boolean_from_string (const gchar  *string,
				  gboolean     *value,
				  GError      **error)
139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159
{
  gboolean retval = TRUE;
  int length;
  
  g_assert (string != NULL);
  length = strlen (string);
  
  if (length == 0)
    retval = FALSE;
  else if (length == 1)
    {
      gchar c = g_ascii_tolower (string[0]);
      if (c == 'y' || c == 't' || c == '1')
	*value = TRUE;
      else if (c == 'n' || c == 'f' || c == '0')
	*value = FALSE;
      else
	retval = FALSE;
    }
  else
    {
Matthias Clasen's avatar
Matthias Clasen committed
160
      gchar *lower = g_ascii_strdown (string, length);
161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180
      
      if (strcmp (lower, "yes") == 0 || strcmp (lower, "true") == 0)
	*value = TRUE;
      else if (strcmp (lower, "no") == 0 || strcmp (lower, "false") == 0)
	*value = FALSE;
      else
	retval = FALSE;
      g_free (lower);
    }
  
  if (!retval)
    g_set_error (error,
		 GTK_BUILDER_ERROR,
		 GTK_BUILDER_ERROR_INVALID_VALUE,
		 "could not parse boolean `%s'",
		 string);

  return retval;
}

181
static GObject *
182 183 184
builder_construct (ParserData  *data,
                   ObjectInfo  *object_info,
		   GError     **error)
185 186 187 188 189
{
  GObject *object;

  g_assert (object_info != NULL);

190
  if (object_info->object && object_info->applied_properties)
191 192 193 194
    return object_info->object;

  object_info->properties = g_slist_reverse (object_info->properties);

195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210
  if (object_info->object == NULL)
    {
      object = _gtk_builder_construct (data->builder, object_info, error);
      if (!object)
	return NULL;
    }
  else
    {
      /* We're building a template, the object is already set and
       * we just want to resolve the properties at the right time
       */
      object = object_info->object;
      _gtk_builder_apply_properties (data->builder, object_info, error);
    }

  object_info->applied_properties = TRUE;
211

212 213 214 215 216 217 218
  g_assert (G_IS_OBJECT (object));

  object_info->object = object;

  return object;
}

219
static GType
220 221 222 223 224 225 226 227 228
_get_type_by_symbol (const gchar* symbol)
{
  static GModule *module = NULL;
  GTypeGetFunc func;
  
  if (!module)
    module = g_module_open (NULL, 0);

  if (!g_module_symbol (module, symbol, (gpointer)&func))
229
    return G_TYPE_INVALID;
230
  
231
  return func ();
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 281 282 283 284 285 286 287 288 289 290
static void
parse_requires (ParserData   *data,
		const gchar  *element_name,
		const gchar **names,
		const gchar **values,
		GError      **error)
{
  RequiresInfo *req_info;
  const gchar  *library = NULL;
  const gchar  *version = NULL;
  gchar       **split;
  gint          i, version_major = 0, version_minor = 0;
  gint          line_number, char_number;

  g_markup_parse_context_get_position (data->ctx,
                                       &line_number,
                                       &char_number);

  for (i = 0; names[i] != NULL; i++)
    {
      if (strcmp (names[i], "lib") == 0)
        library = values[i];
      else if (strcmp (names[i], "version") == 0)
	version = values[i];
      else
	error_invalid_attribute (data, element_name, names[i], error);
    }

  if (!library || !version)
    {
      error_missing_attribute (data, element_name, 
			       version ? "lib" : "version", error);
      return;
    }

  if (!(split = g_strsplit (version, ".", 2)) || !split[0] || !split[1])
    {
      g_set_error (error,
		   GTK_BUILDER_ERROR,
		   GTK_BUILDER_ERROR_INVALID_VALUE,
		   "%s:%d:%d <%s> attribute has malformed value \"%s\"",
		   data->filename,
		   line_number, char_number, "version", version);
      return;
    }
  version_major = g_ascii_strtoll (split[0], NULL, 10);
  version_minor = g_ascii_strtoll (split[1], NULL, 10);
  g_strfreev (split);

  req_info = g_slice_new0 (RequiresInfo);
  req_info->library = g_strdup (library);
  req_info->major   = version_major;
  req_info->minor   = version_minor;
  state_push (data, req_info);
  req_info->tag.name = element_name;
}

291 292 293 294 295 296 297 298
static gboolean
is_requested_object (const gchar *object,
                     ParserData  *data)
{
  GSList *l;

  for (l = data->requested_objects; l; l = l->next)
    {
299
      if (g_strcmp0 (l->data, object) == 0)
300 301 302 303 304 305
        return TRUE;
    }

  return FALSE;
}

306
static void
307 308 309 310 311 312
parse_object (GMarkupParseContext  *context,
              ParserData           *data,
              const gchar          *element_name,
              const gchar         **names,
              const gchar         **values,
              GError              **error)
313 314 315
{
  ObjectInfo *object_info;
  ChildInfo* child_info;
316
  GType object_type = G_TYPE_INVALID;
317 318 319 320
  const gchar *object_id = NULL;
  const gchar *constructor = NULL;
  gchar *internal_id = NULL;
  gint i, line, line2;
321 322 323 324 325 326 327 328 329 330 331

  child_info = state_peek_info (data, ChildInfo);
  if (child_info && strcmp (child_info->tag.name, "object") == 0)
    {
      error_invalid_tag (data, element_name, NULL, error);
      return;
    }

  for (i = 0; names[i] != NULL; i++)
    {
      if (strcmp (names[i], "class") == 0)
332 333 334 335 336 337 338 339
        {
          object_type = gtk_builder_get_type_from_name (data->builder, values[i]);

          if (object_type == G_TYPE_INVALID)
            {
              g_markup_parse_context_get_position (context, &line, NULL);
              g_set_error (error, GTK_BUILDER_ERROR,
                           GTK_BUILDER_ERROR_INVALID_VALUE,
340
                           _("Invalid object type '%s' on line %d"),
341 342 343 344
                           values[i], line);
              return;
            }
        }
345
      else if (strcmp (names[i], "id") == 0)
346
        object_id = values[i];
347
      else if (strcmp (names[i], "constructor") == 0)
348
        constructor = values[i];
349 350
      else if (strcmp (names[i], "type-func") == 0)
        {
351 352 353 354 355
          /* Call the GType function, and return the GType, it's guaranteed afterwards
           * that g_type_from_name on the name will return our GType
           */
          object_type = _get_type_by_symbol (values[i]);
          if (object_type == G_TYPE_INVALID)
356
            {
357 358
              g_markup_parse_context_get_position (context, &line, NULL);
              g_set_error (error, GTK_BUILDER_ERROR,
359
                           GTK_BUILDER_ERROR_INVALID_TYPE_FUNCTION,
360 361
                           _("Invalid type function on line %d: '%s'"),
                           line, values[i]);
362 363 364
              return;
            }
        }
365 366
      else
	{
367
	  error_invalid_attribute (data, element_name, names[i], error);
368 369 370 371
	  return;
	}
    }

372
  if (object_type == G_TYPE_INVALID)
373 374 375 376 377 378 379
    {
      error_missing_attribute (data, element_name, "class", error);
      return;
    }

  if (!object_id)
    {
380 381
      internal_id = g_strdup_printf ("___object_%d___", ++data->object_counter);
      object_id = internal_id;
382 383
    }

384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399
  ++data->cur_object_level;

  /* check if we reached a requested object (if it is specified) */
  if (data->requested_objects && !data->inside_requested_object)
    {
      if (is_requested_object (object_id, data))
        {
          data->requested_object_level = data->cur_object_level;

          GTK_NOTE (BUILDER, g_print ("requested object \"%s\" found at level %d\n",
                                      object_id,
                                      data->requested_object_level));

          data->inside_requested_object = TRUE;
        }
      else
400
        {
401
          g_free (internal_id);
402 403
          return;
        }
404 405
    }

406
  object_info = g_slice_new0 (ObjectInfo);
407
  object_info->type = object_type;
408 409
  object_info->id = (internal_id) ? internal_id : g_strdup (object_id);
  object_info->constructor = g_strdup (constructor);
410 411 412 413 414
  state_push (data, object_info);
  object_info->tag.name = element_name;

  if (child_info)
    object_info->parent = (CommonInfo*)child_info;
415 416 417 418 419 420 421

  g_markup_parse_context_get_position (context, &line, NULL);
  line2 = GPOINTER_TO_INT (g_hash_table_lookup (data->object_ids, object_id));
  if (line2 != 0)
    {
      g_set_error (error, GTK_BUILDER_ERROR,
                   GTK_BUILDER_ERROR_DUPLICATE_ID,
422
                   _("Duplicate object ID '%s' on line %d (previously on line %d)"),
Matthias Clasen's avatar
Matthias Clasen committed
423
                   object_id, line, line2);
424 425 426
      return;
    }

427
  g_hash_table_insert (data->object_ids, g_strdup (object_id), GINT_TO_POINTER (line));
428 429
}

430 431 432 433 434 435 436 437 438 439
static void
parse_template (GMarkupParseContext  *context,
		ParserData           *data,
		const gchar          *element_name,
		const gchar         **names,
		const gchar         **values,
		GError              **error)
{
  ObjectInfo *object_info;
  int i;
440
  const gchar *object_class = NULL;
441
  const gchar *parent_class = NULL;
442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465
  gint line, line2;
  GType template_type = _gtk_builder_get_template_type (data->builder);
  GType parsed_type;

  if (template_type == 0)
    {
      g_set_error (error,
		   GTK_BUILDER_ERROR,
		   GTK_BUILDER_ERROR_UNHANDLED_TAG,
		   "Encountered template definition but not parsing a template.");
      return;
    }
  else if (state_peek (data) != NULL)
    {
      g_set_error (error,
		   GTK_BUILDER_ERROR,
		   GTK_BUILDER_ERROR_UNHANDLED_TAG,
		   "Encountered template definition that is not at the top level.");
      return;
    }

  for (i = 0; names[i] != NULL; i++)
    {
      if (strcmp (names[i], "class") == 0)
466
        object_class = values[i];
467
      else if (strcmp (names[i], "parent") == 0)
468
        parent_class = values[i];
469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492
      else
	{
	  error_invalid_attribute (data, element_name, names[i], error);
	  return;
	}
    }

  if (!object_class)
    {
      error_missing_attribute (data, element_name, "class", error);
      return;
    }

  parsed_type = g_type_from_name (object_class);
  if (template_type != parsed_type)
    {
      g_set_error (error,
		   GTK_BUILDER_ERROR,
		   GTK_BUILDER_ERROR_TEMPLATE_MISMATCH,
		   "Parsed template definition for type `%s', expected type `%s'.",
		   object_class, g_type_name (template_type));
      return;
    }

493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515
  if (parent_class)
    {
      GType parent_type = g_type_from_name (parent_class);
      GType expected_type = g_type_parent (parsed_type);

      if (parent_type == G_TYPE_INVALID)
        {
          g_set_error (error, GTK_BUILDER_ERROR,
                       GTK_BUILDER_ERROR_INVALID_VALUE,
                       "Invalid template parent type `%s'",
                       parent_class);
          return;
        }      
      if (parent_type != expected_type)
        {
          g_set_error (error, GTK_BUILDER_ERROR,
                       GTK_BUILDER_ERROR_TEMPLATE_MISMATCH,
                       "Template parent type `%s' does not match instance parent type `%s'.",
                       parent_class, g_type_name (expected_type));
          return;
        }
    }
  
516 517 518
  ++data->cur_object_level;

  object_info = g_slice_new0 (ObjectInfo);
519
  object_info->type = parsed_type;
520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539
  object_info->id = g_strdup (object_class);
  object_info->object = gtk_builder_get_object (data->builder, object_class);
  state_push (data, object_info);
  object_info->tag.name = element_name;

  g_markup_parse_context_get_position (context, &line, NULL);
  line2 = GPOINTER_TO_INT (g_hash_table_lookup (data->object_ids, object_class));
  if (line2 != 0)
    {
      g_set_error (error, GTK_BUILDER_ERROR,
                   GTK_BUILDER_ERROR_DUPLICATE_ID,
                   _("Duplicate object ID '%s' on line %d (previously on line %d)"),
                   object_class, line, line2);
      return;
    }

  g_hash_table_insert (data->object_ids, g_strdup (object_class), GINT_TO_POINTER (line));
}


540 541 542 543 544 545 546 547 548 549 550 551 552
static void
free_object_info (ObjectInfo *info)
{
  /* Do not free the signal items, which GtkBuilder takes ownership of */
  g_slist_free (info->signals);
  g_slist_foreach (info->properties,
                   (GFunc)free_property_info, NULL);
  g_slist_free (info->properties);
  g_free (info->constructor);
  g_free (info->id);
  g_slice_free (ObjectInfo, info);
}

553 554 555 556 557 558 559 560
static void
free_menu_info (MenuInfo *info)
{
  g_free (info->id);
  g_hash_table_unref (info->objects);
  g_slice_free (MenuInfo, info);
}

561 562 563 564 565 566 567 568 569 570 571 572 573
static void
parse_child (ParserData   *data,
             const gchar  *element_name,
             const gchar **names,
             const gchar **values,
             GError      **error)

{
  ObjectInfo* object_info;
  ChildInfo *child_info;
  guint i;

  object_info = state_peek_info (data, ObjectInfo);
574 575 576
  if (!object_info ||
      !(strcmp (object_info->tag.name, "object") == 0 ||
	strcmp (object_info->tag.name, "template") == 0))
577
    {
578
      error_invalid_tag (data, element_name, NULL, error);
579 580 581 582 583 584 585 586 587 588 589 590 591
      return;
    }
  
  child_info = g_slice_new0 (ChildInfo);
  state_push (data, child_info);
  child_info->tag.name = element_name;
  for (i = 0; names[i]; i++)
    {
      if (strcmp (names[i], "type") == 0)
        child_info->type = g_strdup (values[i]);
      else if (strcmp (names[i], "internal-child") == 0)
        child_info->internal_child = g_strdup (values[i]);
      else
592
	error_invalid_attribute (data, element_name, names[i], error);
593 594 595 596
    }

  child_info->parent = (CommonInfo*)object_info;

597
  object_info->object = builder_construct (data, object_info, error);
598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615
}

static void
free_child_info (ChildInfo *info)
{
  g_free (info->type);
  g_free (info->internal_child);
  g_slice_free (ChildInfo, info);
}

static void
parse_property (ParserData   *data,
                const gchar  *element_name,
                const gchar **names,
                const gchar **values,
                GError      **error)
{
  PropertyInfo *info;
616 617 618 619
  const gchar *context = NULL;
  const gchar *bind_source = NULL;
  const gchar *bind_property = NULL;
  GBindingFlags bind_flags = G_BINDING_DEFAULT;
620
  gboolean translatable = FALSE;
621
  ObjectInfo *object_info;
622 623
  GParamSpec *pspec = NULL;
  gint i;
624

625
  object_info = state_peek_info (data, ObjectInfo);
626 627 628
  if (!object_info || 
      !(strcmp (object_info->tag.name, "object") == 0 ||
	strcmp (object_info->tag.name, "template") == 0))
629
    {
630
      error_invalid_tag (data, element_name, NULL, error);
631 632
      return;
    }
633 634 635 636

  for (i = 0; names[i] != NULL; i++)
    {
      if (strcmp (names[i], "name") == 0)
637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656
        {
          GObjectClass *oclass = g_type_class_ref (object_info->type);
          gchar *name = g_strdelimit (g_strdup (values[i]), "_", '-');

          g_assert (oclass != NULL);
          pspec = g_object_class_find_property (oclass, name);
          g_type_class_unref (oclass);
          g_free (name);

          if (!pspec)
            {
              gint line;
              g_markup_parse_context_get_position (data->ctx, &line, NULL);
              g_set_error (error, GTK_BUILDER_ERROR,
                           GTK_BUILDER_ERROR_INVALID_PROPERTY,
                           _("Invalid property: %s.%s on line %d"),
                           g_type_name (object_info->type), values[i], line);
              return;
            }
        }
657
      else if (strcmp (names[i], "translatable") == 0)
658
	{
659 660
	  if (!_gtk_builder_boolean_from_string (values[i], &translatable,
						 error))
661 662
	    return;
	}
663 664 665 666 667 668
      else if (strcmp (names[i], "comments") == 0)
        {
          /* do nothing, comments are for translators */
        }
      else if (strcmp (names[i], "context") == 0) 
        {
669 670 671 672 673 674 675 676 677 678 679 680 681 682 683
          context = values[i];
        }
      else if (strcmp (names[i], "bind-source") == 0) 
        {
          bind_source = values[i];
        }
      else if (strcmp (names[i], "bind-property") == 0) 
        {
          bind_property = values[i];
        }
      else if (strcmp (names[i], "bind-flags") == 0) 
        {
          if (!_gtk_builder_flags_from_string (G_TYPE_BINDING_FLAGS, values[i],
                                               &bind_flags, error))
            return;
684
        }
685 686
      else
	{
687
	  error_invalid_attribute (data, element_name, names[i], error);
688 689 690 691
	  return;
	}
    }

692
  if (!pspec)
693 694 695 696 697
    {
      error_missing_attribute (data, element_name, "name", error);
      return;
    }

698 699 700 701
  if (bind_source && bind_property)
    {
      BindingInfo *binfo = g_slice_new0 (BindingInfo);

702
      binfo->target_pspec = pspec;
703 704 705 706 707 708 709 710 711 712 713 714 715 716
      binfo->source = g_strdup (bind_source);
      binfo->source_property = g_strdup (bind_property);
      binfo->flags = bind_flags;

      object_info->bindings = g_slist_prepend (object_info->bindings, binfo);
    }
  else if (bind_source || bind_property)
    {
      error_missing_attribute (data, element_name,
                               (bind_source) ? "bind-property" : "bind-source",
                               error);
      return;
    }

717
  info = g_slice_new0 (PropertyInfo);
718
  info->pspec = pspec;
719
  info->translatable = translatable;
720
  info->bound = (bind_source && bind_property);
721
  info->context = g_strdup (context);
722
  info->text = g_string_new ("");
723 724 725 726 727 728
  state_push (data, info);

  info->tag.name = element_name;
}

static void
729
free_property_info (PropertyInfo *info)
730 731
{
  g_free (info->data);
732 733
  g_free (info->context);
  /* info->text is already freed */
734 735 736 737 738 739 740 741 742 743 744
  g_slice_free (PropertyInfo, info);
}

static void
parse_signal (ParserData   *data,
              const gchar  *element_name,
              const gchar **names,
              const gchar **values,
              GError      **error)
{
  SignalInfo *info;
745 746
  const gchar *handler = NULL;
  const gchar *object = NULL;
747 748 749
  gboolean after = FALSE;
  gboolean swapped = FALSE;
  gboolean swapped_set = FALSE;
750
  ObjectInfo *object_info;
751 752 753
  guint  id = 0;
  GQuark detail = 0;
  gint i;
754

755
  object_info = state_peek_info (data, ObjectInfo);
756 757 758
  if (!object_info ||
      !(strcmp (object_info->tag.name, "object") == 0 ||
	strcmp (object_info->tag.name, "template") == 0))
759
    {
760
      error_invalid_tag (data, element_name, NULL, error);
761 762
      return;
    }
763 764 765 766

  for (i = 0; names[i] != NULL; i++)
    {
      if (strcmp (names[i], "name") == 0)
767 768 769 770 771 772 773 774
        {
          if (!g_signal_parse_name (values[i], object_info->type,
                                    &id, &detail, FALSE))
            {
              gint line;
              g_markup_parse_context_get_position (data->ctx, &line, NULL);
              g_set_error (error, GTK_BUILDER_ERROR,
                           GTK_BUILDER_ERROR_INVALID_SIGNAL,
775
                           _("Invalid signal '%s' for type '%s' on line %d"),
776 777 778 779
                           values[i], g_type_name (object_info->type), line);
              return;
            }
        }
780
      else if (strcmp (names[i], "handler") == 0)
781
        handler = values[i];
782
      else if (strcmp (names[i], "after") == 0)
783
	{
784
	  if (!_gtk_builder_boolean_from_string (values[i], &after, error))
785 786
	    return;
	}
787 788
      else if (strcmp (names[i], "swapped") == 0)
	{
789
	  if (!_gtk_builder_boolean_from_string (values[i], &swapped, error))
790
	    return;
791 792 793
	  swapped_set = TRUE;
	}
      else if (strcmp (names[i], "object") == 0)
794
        object = values[i];
795 796 797
      else if (strcmp (names[i], "last_modification_time") == 0)
	/* parse but ignore */
	;
798 799
      else
	{
800
	  error_invalid_attribute (data, element_name, names[i], error);
801 802 803 804
	  return;
	}
    }

805
  if (!id)
806 807 808 809 810 811 812 813 814 815 816 817 818 819 820
    {
      error_missing_attribute (data, element_name, "name", error);
      return;
    }
  else if (!handler)
    {
      error_missing_attribute (data, element_name, "handler", error);
      return;
    }

  /* Swapped defaults to FALSE except when object is set */
  if (object && !swapped_set)
    swapped = TRUE;
  
  info = g_slice_new0 (SignalInfo);
821 822
  info->id = id;
  info->detail = detail;
823
  info->handler = g_strdup (handler);
824 825 826 827
  if (after)
    info->flags |= G_CONNECT_AFTER;
  if (swapped)
    info->flags |= G_CONNECT_SWAPPED;
828
  info->connect_object_name = g_strdup (object);
829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844
  state_push (data, info);

  info->tag.name = element_name;
}

/* Called by GtkBuilder */
void
_free_signal_info (SignalInfo *info,
                   gpointer user_data)
{
  g_free (info->handler);
  g_free (info->connect_object_name);
  g_free (info->object_name);
  g_slice_free (SignalInfo, info);
}

845 846 847
static void
free_requires_info (RequiresInfo *info,
                    gpointer user_data)
848 849 850 851 852
{
  g_free (info->library);
  g_slice_free (RequiresInfo, info);
}

853 854 855 856 857 858 859 860 861 862 863
static void
parse_interface (ParserData   *data,
		 const gchar  *element_name,
		 const gchar **names,
		 const gchar **values,
		 GError      **error)
{
  int i;

  for (i = 0; names[i] != NULL; i++)
    {
864
      if (strcmp (names[i], "domain") == 0)
865
	{
866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882
	  if (data->domain)
	    {
	      if (strcmp (data->domain, values[i]) == 0)
		continue;
	      else
		g_warning ("%s: interface domain '%s' overrides "
			   "programically set domain '%s'",
			   data->filename,
			   values[i],
			   data->domain
			   );
	      
	      g_free (data->domain);
	    }
	  
 	  data->domain = g_strdup (values[i]);
	  gtk_builder_set_translation_domain (data->builder, data->domain);
883 884
	}
      else
885
	error_invalid_attribute (data, "interface", names[i], error);
886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979
    }
}

static SubParser *
create_subparser (GObject       *object,
		  GObject       *child,
		  const gchar   *element_name,
		  GMarkupParser *parser,
		  gpointer       user_data)
{
  SubParser *subparser;

  subparser = g_slice_new0 (SubParser);
  subparser->object = object;
  subparser->child = child;
  subparser->tagname = g_strdup (element_name);
  subparser->start = element_name;
  subparser->parser = g_memdup (parser, sizeof (GMarkupParser));
  subparser->data = user_data;

  return subparser;
}

static void
free_subparser (SubParser *subparser)
{
  g_free (subparser->tagname);
  g_slice_free (SubParser, subparser);
}

static gboolean
subparser_start (GMarkupParseContext *context,
		 const gchar         *element_name,
		 const gchar        **names,
		 const gchar        **values,
		 ParserData          *data,
		 GError             **error)
{
  SubParser *subparser = data->subparser;

  if (!subparser->start &&
      strcmp (element_name, subparser->tagname) == 0)
    subparser->start = element_name;

  if (subparser->start)
    {
      if (subparser->parser->start_element)
	subparser->parser->start_element (context,
					  element_name, names, values,
					  subparser->data, error);
      return FALSE;
    }
  return TRUE;
}

static void
subparser_end (GMarkupParseContext *context,
	       const gchar         *element_name,
	       ParserData          *data,
	       GError             **error)
{
  if (data->subparser->parser->end_element)
    data->subparser->parser->end_element (context, element_name,
					  data->subparser->data, error);
  
  if (!strcmp (data->subparser->start, element_name) == 0)
    return;
    
  gtk_buildable_custom_tag_end (GTK_BUILDABLE (data->subparser->object),
				data->builder,
				data->subparser->child,
				element_name,
				data->subparser->data);
  g_free (data->subparser->parser);
      
  if (GTK_BUILDABLE_GET_IFACE (data->subparser->object)->custom_finished)
    data->custom_finalizers = g_slist_prepend (data->custom_finalizers,
					       data->subparser);
  else
    free_subparser (data->subparser);
  
  data->subparser = NULL;
}

static gboolean
parse_custom (GMarkupParseContext *context,
	      const gchar         *element_name,
	      const gchar        **names,
	      const gchar        **values,
	      ParserData          *data,
	      GError             **error)
{
  CommonInfo* parent_info;
  GMarkupParser parser;
980
  gpointer subparser_data;
981 982 983 984 985 986 987
  GObject *object;
  GObject *child;

  parent_info = state_peek_info (data, CommonInfo);
  if (!parent_info)
    return FALSE;

988 989
  if (strcmp (parent_info->tag.name, "object") == 0 ||
      strcmp (parent_info->tag.name, "template") == 0)
990 991 992
    {
      ObjectInfo* object_info = (ObjectInfo*)parent_info;
      if (!object_info->object)
993
	{
994
	  object_info->properties = g_slist_reverse (object_info->properties);
995 996 997 998 999 1000
	  object_info->object = _gtk_builder_construct (data->builder,
							object_info,
							error);
	  if (!object_info->object)
	    return TRUE; /* A GError is already set */
	}
1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021
      g_assert (object_info->object);
      object = object_info->object;
      child = NULL;
    }
  else if (strcmp (parent_info->tag.name, "child") == 0)
    {
      ChildInfo* child_info = (ChildInfo*)parent_info;
      
      _gtk_builder_add (data->builder, child_info);
      
      object = ((ObjectInfo*)child_info->parent)->object;
      child  = child_info->object;
    }
  else
    return FALSE;

  if (!gtk_buildable_custom_tag_start (GTK_BUILDABLE (object),
				       data->builder,
				       child,
				       element_name,
				       &parser,
1022
				       &subparser_data))
1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044
    return FALSE;
      
  data->subparser = create_subparser (object, child, element_name,
				      &parser, subparser_data);
  
  if (parser.start_element)
    parser.start_element (context,
			  element_name, names, values,
			  subparser_data, error);
  return TRUE;
}

static void
start_element (GMarkupParseContext *context,
               const gchar         *element_name,
               const gchar        **names,
               const gchar        **values,
               gpointer             user_data,
               GError             **error)
{
  ParserData *data = (ParserData*)user_data;

1045
#ifdef G_ENABLE_DEBUG
1046
  if (gtk_get_debug_flags () & GTK_DEBUG_BUILDER)
1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066
    {
      GString *tags = g_string_new ("");
      int i;
      for (i = 0; names[i]; i++)
        g_string_append_printf (tags, "%s=\"%s\" ", names[i], values[i]);

      if (i)
        {
          g_string_insert_c (tags, 0, ' ');
          g_string_truncate (tags, tags->len - 1);
        }
      g_print ("<%s%s>\n", element_name, tags->str);
      g_string_free (tags, TRUE);
    }
#endif

  if (!data->last_element && strcmp (element_name, "interface") != 0)
    {
      g_set_error (error, GTK_BUILDER_ERROR, 
		   GTK_BUILDER_ERROR_UNHANDLED_TAG,
1067
		   _("Invalid root element: <%s>"),
1068 1069 1070 1071 1072 1073 1074 1075 1076
		   element_name);
      return;
    }
  data->last_element = element_name;

  if (data->subparser)
    if (!subparser_start (context, element_name, names, values,
			  data, error))
      return;
1077 1078 1079 1080

  if (strcmp (element_name, "requires") == 0)
    parse_requires (data, element_name, names, values, error);
  else if (strcmp (element_name, "object") == 0)
1081
    parse_object (context, data, element_name, names, values, error);
1082 1083
  else if (strcmp (element_name, "template") == 0)
    parse_template (context, data, element_name, names, values, error);
1084 1085 1086 1087 1088
  else if (data->requested_objects && !data->inside_requested_object)
    {
      /* If outside a requested object, simply ignore this tag */
      return;
    }
1089 1090 1091 1092 1093 1094 1095 1096
  else if (strcmp (element_name, "child") == 0)
    parse_child (data, element_name, names, values, error);
  else if (strcmp (element_name, "property") == 0)
    parse_property (data, element_name, names, values, error);
  else if (strcmp (element_name, "signal") == 0)
    parse_signal (data, element_name, names, values, error);
  else if (strcmp (element_name, "interface") == 0)
    parse_interface (data, element_name, names, values, error);
1097
  else if (strcmp (element_name, "menu") == 0)
1098
    _gtk_builder_menu_start (data, element_name, names, values, error);
1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109
  else if (strcmp (element_name, "placeholder") == 0)
    {
      /* placeholder has no special treatmeant, but it needs an
       * if clause to avoid an error below.
       */
    }
  else
    if (!parse_custom (context, element_name, names, values,
		       data, error))
      g_set_error (error, GTK_BUILDER_ERROR, 
		   GTK_BUILDER_ERROR_UNHANDLED_TAG,
1110
		   _("Unhandled tag: <%s>"),
1111 1112 1113
		   element_name);
}

1114
const gchar *
1115 1116 1117 1118
_gtk_builder_parser_translate (const gchar *domain,
			       const gchar *context,
			       const gchar *text)
{
1119
  const gchar *s;
1120 1121

  if (context)
1122
    s = g_dpgettext2 (domain, context, text);
1123
  else
1124
    s = g_dgettext (domain, text);
1125

1126
  return s;
1127 1128
}

1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145
/* Called for close tags </foo> */
static void
end_element (GMarkupParseContext *context,
             const gchar         *element_name,
             gpointer             user_data,
             GError             **error)
{
  ParserData *data = (ParserData*)user_data;

  GTK_NOTE (BUILDER, g_print ("</%s>\n", element_name));

  if (data->subparser && data->subparser->start)
    {
      subparser_end (context, element_name, data, error);
      return;
    }

1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160
  if (strcmp (element_name, "requires") == 0)
    {
      RequiresInfo *req_info = state_pop_info (data, RequiresInfo);

      /* TODO: Allow third party widget developers to check thier
       * required versions, possibly throw a signal allowing them
       * to check thier library versions here.
       */
      if (!strcmp (req_info->library, "gtk+"))
	{
	  if (!GTK_CHECK_VERSION (req_info->major, req_info->minor, 0))
	    g_set_error (error,
			 GTK_BUILDER_ERROR,
			 GTK_BUILDER_ERROR_VERSION_MISMATCH,
			 "%s: required %s version %d.%d, current version is %d.%d",
1161
			 data->filename, req_info->library,
1162 1163 1164
			 req_info->major, req_info->minor,
			 GTK_MAJOR_VERSION, GTK_MINOR_VERSION);
	}
1165
      free_requires_info (req_info, NULL);
1166
    }
1167 1168 1169 1170 1171 1172 1173 1174
  else if (strcmp (element_name, "interface") == 0)
    {
    }
  else if (data->requested_objects && !data->inside_requested_object)
    {
      /* If outside a requested object, simply ignore this tag */
      return;
    }
1175 1176 1177 1178
  else if (strcmp (element_name, "menu") == 0)
    {
      _gtk_builder_menu_end (data);
    }
1179 1180
  else if (strcmp (element_name, "object") == 0 ||
	   strcmp (element_name, "template") == 0)
1181 1182 1183 1184
    {
      ObjectInfo *object_info = state_pop_info (data, ObjectInfo);
      ChildInfo* child_info = state_peek_info (data, ChildInfo);

1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197
      if (data->requested_objects && data->inside_requested_object &&
          (data->cur_object_level == data->requested_object_level))
        {
          GTK_NOTE (BUILDER, g_print ("requested object end found at level %d\n",
                                      data->requested_object_level));

          data->inside_requested_object = FALSE;
        }

      --data->cur_object_level;

      g_assert (data->cur_object_level >= 0);

1198 1199 1200 1201 1202 1203
      object_info->object = builder_construct (data, object_info, error);
      if (!object_info->object)
	{
	  free_object_info (object_info);
	  return;
	}
1204 1205 1206 1207 1208 1209
      if (child_info)
        child_info->object = object_info->object;

      if (GTK_IS_BUILDABLE (object_info->object) &&
          GTK_BUILDABLE_GET_IFACE (object_info->object)->parser_finished)
        data->finalizers = g_slist_prepend (data->finalizers, object_info->object);
1210 1211
      _gtk_builder_add_signals (data->builder, object_info->signals);

1212 1213 1214 1215 1216 1217 1218 1219
      free_object_info (object_info);
    }
  else if (strcmp (element_name, "property") == 0)
    {
      PropertyInfo *prop_info = state_pop_info (data, PropertyInfo);
      CommonInfo *info = state_peek_info (data, CommonInfo);

      /* Normal properties */
1220 1221
      if (strcmp (info->tag.name, "object") == 0 ||
	  strcmp (info->tag.name, "template") == 0)
1222 1223
        {
          ObjectInfo *object_info = (ObjectInfo*)info;
1224 1225 1226

          if (prop_info->translatable && prop_info->text->len)
            {
1227 1228 1229 1230 1231 1232
              const gchar *translated;

              translated = _gtk_builder_parser_translate (data->domain,
                                                          prop_info->context,
                                                          prop_info->text->str);
              g_string_assign (prop_info->text, translated);
1233 1234
            }

1235 1236
          prop_info->data = g_string_free (prop_info->text, FALSE);

1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 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 1279 1280 1281
          object_info->properties =
            g_slist_prepend (object_info->properties, prop_info);
        }
      else
        g_assert_not_reached ();
    }
  else if (strcmp (element_name, "child") == 0)
    {
      ChildInfo *child_info = state_pop_info (data, ChildInfo);

      _gtk_builder_add (data->builder, child_info);

      free_child_info (child_info);
    }
  else if (strcmp (element_name, "signal") == 0)
    {
      SignalInfo *signal_info = state_pop_info (data, SignalInfo);
      ObjectInfo *object_info = (ObjectInfo*)state_peek_info (data, CommonInfo);
      signal_info->object_name = g_strdup (object_info->id);
      object_info->signals =
        g_slist_prepend (object_info->signals, signal_info);
    }
  else if (strcmp (element_name, "placeholder") == 0)
    {
    }
  else
    {
      g_assert_not_reached ();
    }
}

/* Called for character data */
/* text is not nul-terminated */
static void
text (GMarkupParseContext *context,
      const gchar         *text,
      gsize                text_len,
      gpointer             user_data,
      GError             **error)
{
  ParserData *data = (ParserData*)user_data;
  CommonInfo *info;

  if (data->subparser && data->subparser->start)
    {
1282 1283
      GError *tmp_error = NULL;
      
1284 1285
      if (data->subparser->parser->text)
        data->subparser->parser->text (context, text, text_len,
1286 1287 1288
                                       data->subparser->data, &tmp_error);
      if (tmp_error)
	g_propagate_error (error, tmp_error);
1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301
      return;
    }

  if (!data->stack)
    return;

  info = state_peek_info (data, CommonInfo);
  g_assert (info != NULL);

  if (strcmp (g_markup_parse_context_get_element (context), "property") == 0)
    {
      PropertyInfo *prop_info = (PropertyInfo*)info;

1302
      g_string_append_len (prop_info->text, text, text_len);
1303 1304 1305
    }
}

1306 1307 1308
static void
free_info (CommonInfo *info)
{
1309 1310
  if (strcmp (info->tag.name, "object") == 0 ||
      strcmp (info->tag.name, "template") == 0)
1311
    free_object_info ((ObjectInfo *)info);
1312
  else if (strcmp (info->tag.name, "child") == 0)
1313
    free_child_info ((ChildInfo *)info);
1314
  else if (strcmp (info->tag.name, "property") == 0)
1315
    free_property_info ((PropertyInfo *)info);
1316
  else if (strcmp (info->tag.name, "signal") == 0)
1317
    _free_signal_info ((SignalInfo *)info, NULL);
1318
  else if (strcmp (info->tag.name, "requires") == 0)
1319
    free_requires_info ((RequiresInfo *)info, NULL);
1320
  else if (strcmp (info->tag.name, "menu") == 0)
1321
    free_menu_info ((MenuInfo *)info);
1322
  else
1323 1324 1325
    g_assert_not_reached ();
}

1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337
static const GMarkupParser parser = {
  start_element,
  end_element,
  text,
  NULL,
};

void
_gtk_builder_parser_parse_buffer (GtkBuilder   *builder,
                                  const gchar  *filename,
                                  const gchar  *buffer,
                                  gsize         length,
1338
                                  gchar       **requested_objs,
1339 1340
                                  GError      **error)
{
1341
  const gchar* domain;
1342 1343 1344
  ParserData *data;
  GSList *l;
  
1345 1346 1347 1348 1349 1350 1351
  /* Store the original domain so that interface domain attribute can be
   * applied for the builder and the original domain can be restored after
   * parsing has finished. This allows subparsers to translate elements with
   * gtk_builder_get_translation_domain() without breaking the ABI or API
   */
  domain = gtk_builder_get_translation_domain (builder);

1352 1353 1354
  data = g_new0 (ParserData, 1);
  data->builder = builder;
  data->filename = filename;
1355
  data->domain = g_strdup (domain);
1356 1357
  data->object_ids = g_hash_table_new_full (g_str_hash, g_str_equal,
					    (GDestroyNotify)g_free, NULL);
1358

1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376
  data->requested_objects = NULL;
  if (requested_objs)
    {
      gint i;

      data->inside_requested_object = FALSE;
      for (i = 0; requested_objs[i]; ++i)
        {
          data->requested_objects = g_slist_prepend (data->requested_objects,
                                                     g_strdup (requested_objs[i]));	
        }
    }
  else
    {
      /* get all the objects */
      data->inside_requested_object = TRUE;
    }

1377 1378 1379
  data->ctx = g_markup_parse_context_new (&parser, 
                                          G_MARKUP_TREAT_CDATA_AS_TEXT, 
                                          data, NULL);
1380 1381 1382

  if (!g_markup_parse_context_parse (data->ctx, buffer, length, error))
    goto out;
1383

1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408
  _gtk_builder_finish (builder);

  /* Custom parser_finished */
  data->custom_finalizers = g_slist_reverse (data->custom_finalizers);
  for (l = data->custom_finalizers; l; l = l->next)
    {
      SubParser *sub = (SubParser*)l->data;
      
      gtk_buildable_custom_finished (GTK_BUILDABLE (sub->object),
                                     builder,
                                     sub->child,
                                     sub->tagname,
                                     sub->data);
    }
  
  /* Common parser_finished, for all created objects */
  data->finalizers = g_slist_reverse (data->finalizers);
  for (l = data->finalizers; l; l = l->next)
    {
      GtkBuildable *buildable = (GtkBuildable*)l->data;
      gtk_buildable_parser_finished (GTK_BUILDABLE (buildable), builder);
    }

 out:

1409
  g_slist_foreach (data->stack, (GFunc)free_info, NULL);
1410
  g_slist_free (data->stack);
1411
  g_slist_foreach (data->custom_finalizers, (GFunc)free_subparser, NULL);
1412 1413
  g_slist_free (data->custom_finalizers);
  g_slist_free (data->finalizers);
1414 1415
  g_slist_foreach (data->requested_objects, (GFunc) g_free, NULL);
  g_slist_free (data->requested_objects);
1416
  g_free (data->domain);
1417
  g_hash_table_destroy (data->object_ids);
1418
  g_markup_parse_context_free (data->ctx);
1419
  g_free (data);
1420 1421 1422

  /* restore the original domain */
  gtk_builder_set_translation_domain (builder, domain);
1423
}