gtkbuilder.c 63.8 KB
Newer Older
Cody Russell's avatar
Cody Russell committed
1
/* GTK - The GIMP Toolkit
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
 * Copyright (C) 1998-2002 James Henstridge <james@daa.com.au>
 * Copyright (C) 2006-2007 Async Open Source,
 *                         Johan Dahlin <jdahlin@async.com.br>,
 *                         Henrique Romano <henrique@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
18
 * License along with this library. If not, see <http://www.gnu.org/licenses/>.
19 20
 */

21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
/**
 * SECTION:gtkbuilder
 * @Short_description: Build an interface from an XML UI definition
 * @Title: GtkBuilder
 *
 * A GtkBuilder is an auxiliary object that reads textual descriptions
 * of a user interface and instantiates the described objects. To pass a
 * description to a GtkBuilder, call gtk_builder_add_from_file() or
 * gtk_builder_add_from_string(). These functions can be called multiple
 * times; the builder merges the content of all descriptions.
 *
 * A GtkBuilder holds a reference to all objects that it has constructed
 * and drops these references when it is finalized. This finalization can
 * cause the destruction of non-widget objects or widgets which are not
 * contained in a toplevel window. For toplevel windows constructed by a
 * builder, it is the responsibility of the user to call gtk_widget_destroy()
 * to get rid of them and all the widgets they contain.
 *
 * The functions gtk_builder_get_object() and gtk_builder_get_objects()
 * can be used to access the widgets in the interface by the names assigned
 * to them inside the UI description. Toplevel windows returned by these
 * functions will stay around until the user explicitly destroys them
 * with gtk_widget_destroy(). Other widgets will either be part of a
 * larger hierarchy constructed by the builder (in which case you should
 * not have to worry about their lifecycle), or without a parent, in which
 * case they have to be added to some container to make use of them.
 * Non-widget objects need to be reffed with g_object_ref() to keep them
 * beyond the lifespan of the builder.
 *
 * The function gtk_builder_connect_signals() and variants thereof can be
 * used to connect handlers to the named signals in the description.
 *
 * <refsect2 id="BUILDER-UI">
 * <title>GtkBuilder UI Definitions</title>
 * <para>
 * GtkBuilder parses textual descriptions of user interfaces which are specified
57 58 59
 * in an XML format which can be roughly described by the RELAX NG schema below.
 * We refer to these descriptions as <firstterm>GtkBuilder UI definitions</firstterm>
 * or just <firstterm>UI definitions</firstterm> if the context is clear. Do not
60 61 62 63
 * confuse GtkBuilder UI Definitions with
 * <link linkend="XML-UI">GtkUIManager UI Definitions</link>, which are more
 * limited in scope.
 * </para>
64 65 66 67 68
 * <programlisting>
 * <xi:include xmlns:xi="http://www.w3.org/2001/XInclude" parse="text" href="../../../../gtk/gtkbuilder.rnc">
 *   <xi:fallback>FIXME: MISSING XINCLUDE CONTENT</xi:fallback>
 * </xi:include>
 * </programlisting>
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 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
 * <para>
 * The toplevel element is &lt;interface&gt;. It optionally takes a "domain"
 * attribute, which will make the builder look for translated strings using
 * dgettext() in the domain specified. This can also be done by calling
 * gtk_builder_set_translation_domain() on the builder. Objects are described by
 * &lt;object&gt; elements, which can contain &lt;property&gt; elements to set
 * properties, &lt;signal&gt; elements which connect signals to handlers, and
 * &lt;child&gt; elements, which describe child objects (most often widgets
 * inside a container, but also e.g. actions in an action group, or columns in a
 * tree model). A &lt;child&gt; element contains an &lt;object&gt; element which
 * describes the child object. The target toolkit version(s) are described by
 * &lt;requires&gt; elements, the "lib" attribute specifies the widget library
 * in question (currently the only supported value is "gtk+") and the "version"
 * attribute specifies the target version in the form
 * "&lt;major&gt;.&lt;minor&gt;". The builder will error out if the version
 * requirements are not met.
 *
 * Typically, the specific kind of object represented by an &lt;object&gt;
 * element is specified by the "class" attribute. If the type has not been
 * loaded yet, GTK+ tries to find the <function>_get_type()</function> from the
 * class name by applying heuristics. This works in most cases, but if
 * necessary, it is possible to specify the name of the
 * <function>_get_type()</function> explictly with the "type-func" attribute.
 * As a special case, GtkBuilder allows to use an object that has been
 * constructed by a #GtkUIManager in another part of the UI definition by
 * specifying the id of the #GtkUIManager in the "constructor" attribute and the
 * name of the object in the "id" attribute.
 *
 * Objects must be given a name with the "id" attribute, which allows the
 * application to retrieve them from the builder with gtk_builder_get_object().
 * An id is also necessary to use the object as property value in other parts of
 * the UI definition.
 * </para>
 * <note><para>
 * Prior to 2.20, GtkBuilder was setting the "name" property of constructed widgets to the
 * "id" attribute. In GTK+ 2.20 or newer, you have to use gtk_buildable_get_name() instead
 * of gtk_widget_get_name() to obtain the "id", or set the "name" property in your UI
 * definition.
 * </para></note>
 * <para>
 * Setting properties of objects is pretty straightforward with the
 * &lt;property&gt; element: the "name" attribute specifies the name of the
 * property, and the content of the element specifies the value. If the
 * "translatable" attribute is set to a true value, GTK+ uses gettext() (or
 * dgettext() if the builder has a translation domain set) to find a translation
 * for the value. This happens before the value is parsed, so it can be used for
 * properties of any type, but it is probably most useful for string properties.
 * It is also possible to specify a context to disambiguate short strings, and
 * comments which may help the translators.
 *
 * GtkBuilder can parse textual representations for the most common property
 * types: characters, strings, integers, floating-point numbers, booleans
 * (strings like "TRUE", "t", "yes", "y", "1" are interpreted as %TRUE, strings
 * like "FALSE, "f", "no", "n", "0" are interpreted as %FALSE), enumerations
 * (can be specified by their name, nick or integer value), flags (can be
 * specified by their name, nick, integer value, optionally combined with "|",
 * e.g. "GTK_VISIBLE|GTK_REALIZED")  and colors (in a format understood by
 * gdk_color_parse()). Objects can be referred to by their name. Pixbufs can be
 * specified as a filename of an image file to load. In general, GtkBuilder
 * allows forward references to objects &mdash; an object doesn't have to be
 * constructed before it can be referred to. The exception to this rule is that
 * an object has to be constructed before it can be used as the value of a
 * construct-only property.
 *
 * Signal handlers are set up with the &lt;signal&gt; element. The "name"
 * attribute specifies the name of the signal, and the "handler" attribute
 * specifies the function to connect to the signal. By default, GTK+ tries to
 * find the handler using g_module_symbol(), but this can be changed by passing
 * a custom #GtkBuilderConnectFunc to gtk_builder_connect_signals_full(). The
 * remaining attributes, "after", "swapped" and "object", have the same meaning
 * as the corresponding parameters of the g_signal_connect_object() or
 * g_signal_connect_data() functions. A "last_modification_time" attribute
 * is also allowed, but it does not have a meaning to the builder.
 *
 * Sometimes it is necessary to refer to widgets which have implicitly been
 * constructed by GTK+ as part of a composite widget, to set properties on them
 * or to add further children (e.g. the @vbox of a #GtkDialog). This can be
 * achieved by setting the "internal-child" propery of the &lt;child&gt; element
 * to a true value. Note that GtkBuilder still requires an &lt;object&gt;
 * element for the internal child, even if it has already been constructed.
 *
 * A number of widgets have different places where a child can be added (e.g.
 * tabs vs. page content in notebooks). This can be reflected in a UI definition
 * by specifying the "type" attribute on a &lt;child&gt;. The possible values
 * for the "type" attribute are described in the sections describing the
 * widget-specific portions of UI definitions.
 * </para>
 * <example>
 * <title>A GtkBuilder UI Definition</title>
 * <programlisting><![CDATA[
 * <interface>
 *   <object class="GtkDialog" id="dialog1">
 *     <child internal-child="vbox">
 *       <object class="GtkVBox" id="vbox1">
 *         <property name="border-width">10</property>
 *         <child internal-child="action_area">
 *           <object class="GtkHButtonBox" id="hbuttonbox1">
 *             <property name="border-width">20</property>
 *             <child>
 *               <object class="GtkButton" id="ok_button">
 *                 <property name="label">gtk-ok</property>
 *                 <property name="use-stock">TRUE</property>
 *                 <signal name="clicked" handler="ok_button_clicked"/>
 *               </object>
 *             </child>
 *           </object>
 *         </child>
 *       </object>
 *     </child>
 *   </object>
 * </interface>
 * ]]></programlisting>
 * </example>
 * <para>
 * Beyond this general structure, several object classes define their own XML
 * DTD fragments for filling in the ANY placeholders in the DTD above. Note that
 * a custom element in a &lt;child&gt; element gets parsed by the custom tag
 * handler of the parent object, while a custom element in an &lt;object&gt;
 * element gets parsed by the custom tag handler of the object.
 *
 * These XML fragments are explained in the documentation of the respective
 * objects, see
 * <link linkend="GtkWidget-BUILDER-UI">GtkWidget</link>,
 * <link linkend="GtkLabel-BUILDER-UI">GtkLabel</link>,
 * <link linkend="GtkWindow-BUILDER-UI">GtkWindow</link>,
 * <link linkend="GtkContainer-BUILDER-UI">GtkContainer</link>,
 * <link linkend="GtkDialog-BUILDER-UI">GtkDialog</link>,
 * <link linkend="GtkCellLayout-BUILDER-UI">GtkCellLayout</link>,
 * <link linkend="GtkColorSelectionDialog-BUILDER-UI">GtkColorSelectionDialog</link>,
 * <link linkend="GtkFontSelectionDialog-BUILDER-UI">GtkFontSelectionDialog</link>,
 * <link linkend="GtkExpander-BUILDER-UI">GtkExpander</link>,
 * <link linkend="GtkFrame-BUILDER-UI">GtkFrame</link>,
 * <link linkend="GtkListStore-BUILDER-UI">GtkListStore</link>,
 * <link linkend="GtkTreeStore-BUILDER-UI">GtkTreeStore</link>,
 * <link linkend="GtkNotebook-BUILDER-UI">GtkNotebook</link>,
 * <link linkend="GtkSizeGroup-BUILDER-UI">GtkSizeGroup</link>,
 * <link linkend="GtkTreeView-BUILDER-UI">GtkTreeView</link>,
 * <link linkend="GtkUIManager-BUILDER-UI">GtkUIManager</link>,
 * <link linkend="GtkActionGroup-BUILDER-UI">GtkActionGroup</link>.
 * <link linkend="GtkMenuItem-BUILDER-UI">GtkMenuItem</link>,
209
 * <link linkend="GtkMenuToolButton-BUILDER-UI">GtkMenuToolButton</link>,
210
 * <link linkend="GtkAssistant-BUILDER-UI">GtkAssistant</link>,
211 212 213
 * <link linkend="GtkScale-BUILDER-UI">GtkScale</link>,
 * <link linkend="GtkComboBoxText-BUILDER-UI">GtkComboBoxText</link>,
 * <link linkend="GtkRecentFilter-BUILDER-UI">GtkRecentFilter</link>,
214
 * <link linkend="GtkFileFilter-BUILDER-UI">GtkFileFilter</link>,
215
 * <link linkend="GtkTextTagTable-BUILDER-UI">GtkTextTagTable</link>.
216 217
 * </para>
 * </refsect2>
Matthias Clasen's avatar
Matthias Clasen committed
218
 * <refsect2>
219 220 221 222 223 224 225
 * <title>Embedding other XML</title>
 * <para>
 * Apart from the language for UI descriptions that has been explained
 * in the previous section, GtkBuilder can also parse XML fragments
 * of <link linkend="gio-GMenu-Markup">GMenu markup</link>. The resulting
 * #GMenu object and its named submenus are available via
 * gtk_builder_get_object() like other constructed objects.
Matthias Clasen's avatar
Matthias Clasen committed
226 227
 * </para>
 * </refsect2>
228 229
 */

230
#include "config.h"
231
#include <errno.h> /* errno */
232
#include <stdlib.h>
233 234 235 236 237
#include <string.h> /* strlen */

#include "gtkbuilder.h"
#include "gtkbuildable.h"
#include "gtkbuilderprivate.h"
238
#include "gtkdebug.h"
239 240 241 242
#include "gtkmain.h"
#include "gtkintl.h"
#include "gtkprivate.h"
#include "gtktypebuiltins.h"
243
#include "gtkwindow.h"
Matthias Clasen's avatar
Matthias Clasen committed
244 245
#include "gtkicontheme.h"
#include "gtkstock.h"
246

247 248 249 250 251 252 253 254 255 256 257 258

static void gtk_builder_class_init     (GtkBuilderClass *klass);
static void gtk_builder_init           (GtkBuilder      *builder);
static void gtk_builder_finalize       (GObject         *object);
static void gtk_builder_set_property   (GObject         *object,
                                        guint            prop_id,
                                        const GValue    *value,
                                        GParamSpec      *pspec);
static void gtk_builder_get_property   (GObject         *object,
                                        guint            prop_id,
                                        GValue          *value,
                                        GParamSpec      *pspec);
Matthias Clasen's avatar
Matthias Clasen committed
259 260
static GType gtk_builder_real_get_type_from_name (GtkBuilder  *builder,
                                                  const gchar *type_name);
261 262 263 264 265 266 267 268 269 270

enum {
  PROP_0,
  PROP_TRANSLATION_DOMAIN,
};

struct _GtkBuilderPrivate
{
  gchar *domain;
  GHashTable *objects;
271
  GSList *delayed_properties;
272
  GSList *signals;
273
  gchar *filename;
274
  gchar *resource_prefix;
275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291
};

G_DEFINE_TYPE (GtkBuilder, gtk_builder, G_TYPE_OBJECT)

static void
gtk_builder_class_init (GtkBuilderClass *klass)
{
  GObjectClass *gobject_class;

  gobject_class = G_OBJECT_CLASS (klass);

  gobject_class->finalize = gtk_builder_finalize;
  gobject_class->set_property = gtk_builder_set_property;
  gobject_class->get_property = gtk_builder_get_property;

  klass->get_type_from_name = gtk_builder_real_get_type_from_name;

Matthias Clasen's avatar
Matthias Clasen committed
292 293 294 295 296 297
 /** 
  * GtkBuilder:translation-domain:
  *
  * The translation domain used when translating property values that
  * have been marked as translatable in interface descriptions.
  * If the translation domain is %NULL, #GtkBuilder uses gettext(),
298
  * otherwise g_dgettext().
Matthias Clasen's avatar
Matthias Clasen committed
299 300 301
  *
  * Since: 2.12
  */
302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319
  g_object_class_install_property (gobject_class,
                                   PROP_TRANSLATION_DOMAIN,
                                   g_param_spec_string ("translation-domain",
                                                        P_("Translation Domain"),
                                                        P_("The translation domain used by gettext"),
                                                        NULL,
                                                        GTK_PARAM_READWRITE));

  g_type_class_add_private (gobject_class, sizeof (GtkBuilderPrivate));
}

static void
gtk_builder_init (GtkBuilder *builder)
{
  builder->priv = G_TYPE_INSTANCE_GET_PRIVATE (builder, GTK_TYPE_BUILDER,
                                               GtkBuilderPrivate);
  builder->priv->domain = NULL;
  builder->priv->objects = g_hash_table_new_full (g_str_hash, g_str_equal,
320
                                                  g_free, g_object_unref);
321 322 323 324 325 326 327 328 329 330
}


/*
 * GObject virtual methods
 */

static void
gtk_builder_finalize (GObject *object)
{
331
  GtkBuilderPrivate *priv = GTK_BUILDER (object)->priv;
332
  
333 334
  g_free (priv->domain);
  g_free (priv->filename);
335
  g_free (priv->resource_prefix);
336 337 338 339 340 341 342
  
  g_hash_table_destroy (priv->objects);

  g_slist_foreach (priv->signals, (GFunc) _free_signal_info, NULL);
  g_slist_free (priv->signals);
  
  G_OBJECT_CLASS (gtk_builder_parent_class)->finalize (object);
343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409
}

static void
gtk_builder_set_property (GObject      *object,
                          guint         prop_id,
                          const GValue *value,
                          GParamSpec   *pspec)
{
  GtkBuilder *builder = GTK_BUILDER (object);

  switch (prop_id)
    {
    case PROP_TRANSLATION_DOMAIN:
      gtk_builder_set_translation_domain (builder, g_value_get_string (value));
      break;
    default:
      G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
      break;
    }
}

static void
gtk_builder_get_property (GObject    *object,
                          guint       prop_id,
                          GValue     *value,
                          GParamSpec *pspec)
{
  GtkBuilder *builder = GTK_BUILDER (object);

  switch (prop_id)
    {
    case PROP_TRANSLATION_DOMAIN:
      g_value_set_string (value, builder->priv->domain);
      break;
    default:
      G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
      break;
    }
}


/*
 * Try to map a type name to a _get_type function
 * and call it, eg:
 *
 * GtkWindow -> gtk_window_get_type
 * GtkHBox -> gtk_hbox_get_type
 * GtkUIManager -> gtk_ui_manager_get_type
 *
 */
static GType
_gtk_builder_resolve_type_lazily (const gchar *name)
{
  static GModule *module = NULL;
  GTypeGetFunc func;
  GString *symbol_name = g_string_new ("");
  char c, *symbol;
  int i;
  GType gtype = G_TYPE_INVALID;

  if (!module)
    module = g_module_open (NULL, 0);
  
  for (i = 0; name[i] != '\0'; i++)
    {
      c = name[i];
      /* skip if uppercase, first or previous is uppercase */
410 411 412 413 414
      if ((c == g_ascii_toupper (c) &&
           i > 0 && name[i-1] != g_ascii_toupper (name[i-1])) ||
          (i > 2 && name[i]   == g_ascii_toupper (name[i]) &&
           name[i-1] == g_ascii_toupper (name[i-1]) &&
           name[i-2] == g_ascii_toupper (name[i-2])))
415
        g_string_append_c (symbol_name, '_');
416
      g_string_append_c (symbol_name, g_ascii_tolower (c));
417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434
    }
  g_string_append (symbol_name, "_get_type");
  
  symbol = g_string_free (symbol_name, FALSE);

  if (g_module_symbol (module, symbol, (gpointer)&func))
    gtype = func ();
  
  g_free (symbol);

  return gtype;
}

/*
 * GtkBuilder virtual methods
 */

static GType
Matthias Clasen's avatar
Matthias Clasen committed
435 436
gtk_builder_real_get_type_from_name (GtkBuilder  *builder, 
                                     const gchar *type_name)
437 438 439
{
  GType gtype;

440
  gtype = g_type_from_name (type_name);
441 442 443
  if (gtype != G_TYPE_INVALID)
    return gtype;

444
  return _gtk_builder_resolve_type_lazily (type_name);
445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465
}

typedef struct
{
  gchar *object;
  gchar *name;
  gchar *value;
} DelayedProperty;

static void
gtk_builder_get_parameters (GtkBuilder  *builder,
                            GType        object_type,
                            const gchar *object_name,
                            GSList      *properties,
                            GArray      **parameters,
                            GArray      **construct_parameters)
{
  GSList *l;
  GParamSpec *pspec;
  GObjectClass *oclass;
  DelayedProperty *property;
466 467
  GError *error = NULL;
  
468 469 470 471 472 473 474 475 476 477 478 479 480 481 482
  oclass = g_type_class_ref (object_type);
  g_assert (oclass != NULL);

  *parameters = g_array_new (FALSE, FALSE, sizeof (GParameter));
  *construct_parameters = g_array_new (FALSE, FALSE, sizeof (GParameter));

  for (l = properties; l; l = l->next)
    {
      PropertyInfo *prop = (PropertyInfo*)l->data;
      GParameter parameter = { NULL };

      pspec = g_object_class_find_property (G_OBJECT_CLASS (oclass),
                                            prop->name);
      if (!pspec)
        {
483
          g_warning ("Unknown property: %s.%s",
484 485 486 487 488 489
                     g_type_name (object_type), prop->name);
          continue;
        }

      parameter.name = prop->name;

Matthias Clasen's avatar
Matthias Clasen committed
490 491
      if (G_IS_PARAM_SPEC_OBJECT (pspec) &&
          (G_PARAM_SPEC_VALUE_TYPE (pspec) != GDK_TYPE_PIXBUF))
492
        {
493 494 495 496 497 498 499 500
          GObject *object = gtk_builder_get_object (builder, prop->data);

          if (object)
            {
              g_value_init (&parameter.value, G_OBJECT_TYPE (object));
              g_value_set_object (&parameter.value, object);
            }
          else 
501
            {
502
              if (pspec->flags & G_PARAM_CONSTRUCT_ONLY)
503
                {
Matthias Clasen's avatar
Matthias Clasen committed
504 505
                  g_warning ("Failed to get constuct only property "
                             "%s of %s with value `%s'",
506 507 508
                             prop->name, object_name, prop->data);
                  continue;
                }
509
              /* Delay setting property */
510 511 512 513
              property = g_slice_new (DelayedProperty);
              property->object = g_strdup (object_name);
              property->name = g_strdup (prop->name);
              property->value = g_strdup (prop->data);
514 515
              builder->priv->delayed_properties =
                g_slist_prepend (builder->priv->delayed_properties, property);
516 517 518
              continue;
            }
        }
519 520
      else if (!gtk_builder_value_from_string (builder, pspec,
					       prop->data, &parameter.value, &error))
521
        {
Matthias Clasen's avatar
Matthias Clasen committed
522
          g_warning ("Failed to set property %s.%s to %s: %s",
523 524 525 526
                     g_type_name (object_type), prop->name, prop->data,
		     error->message);
	  g_error_free (error);
	  error = NULL;
527 528 529
          continue;
        }

530
      if (pspec->flags & (G_PARAM_CONSTRUCT | G_PARAM_CONSTRUCT_ONLY))
531 532 533 534 535 536 537 538 539 540 541
        g_array_append_val (*construct_parameters, parameter);
      else
        g_array_append_val (*parameters, parameter);
    }

  g_type_class_unref (oclass);
}

static GObject *
gtk_builder_get_internal_child (GtkBuilder  *builder,
                                ObjectInfo  *info,
542 543
                                const gchar *childname,
				GError      **error)
544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567
{
  GObject *obj = NULL;

  while (!obj)
    {
      if (!info->parent)
        break;

      info = (ObjectInfo*)((ChildInfo*)info->parent)->parent;
      if (!info)
        break;

      GTK_NOTE (BUILDER,
                g_print ("Trying to get internal child %s from %s\n",
                         childname,
                         gtk_buildable_get_name (GTK_BUILDABLE (info->object))));

      if (GTK_IS_BUILDABLE (info->object))
          obj = gtk_buildable_get_internal_child (GTK_BUILDABLE (info->object),
                                                  builder,
                                                  childname);
    };

  if (!obj)
568 569 570 571 572 573
    {
      g_set_error (error,
		   GTK_BUILDER_ERROR,
		   GTK_BUILDER_ERROR_INVALID_VALUE,
		   "Unknown internal child: %s", childname);
    }
574 575 576 577 578
  return obj;
}

GObject *
_gtk_builder_construct (GtkBuilder *builder,
579 580
                        ObjectInfo *info,
			GError **error)
581 582 583 584 585 586 587 588 589 590 591 592
{
  GArray *parameters, *construct_parameters;
  GType object_type;
  GObject *obj;
  int i;
  GtkBuildableIface *iface;
  gboolean custom_set_property;
  GtkBuildable *buildable;

  g_assert (info->class_name != NULL);
  object_type = gtk_builder_get_type_from_name (builder, info->class_name);
  if (object_type == G_TYPE_INVALID)
593 594 595 596 597 598 599 600
    {
      g_set_error (error,
		   GTK_BUILDER_ERROR,
		   GTK_BUILDER_ERROR_INVALID_VALUE,
		   "Invalid object type `%s'",
		   info->class_name);
      return NULL;
    }
601 602 603 604 605 606 607 608 609 610 611 612 613

  gtk_builder_get_parameters (builder, object_type,
                              info->id,
                              info->properties,
                              &parameters,
                              &construct_parameters);

  if (info->constructor)
    {
      GObject *constructor;

      constructor = gtk_builder_get_object (builder, info->constructor);
      if (constructor == NULL)
614 615 616 617 618 619 620 621 622 623 624
	{
	  g_set_error (error,
		       GTK_BUILDER_ERROR,
		       GTK_BUILDER_ERROR_INVALID_VALUE,
		       "Unknown object constructor for %s: %s",
		       info->id,
		       info->constructor);
	  g_array_free (parameters, TRUE);
	  g_array_free (construct_parameters, TRUE);
	  return NULL;
	}
625 626 627 628 629 630 631 632 633 634
      obj = gtk_buildable_construct_child (GTK_BUILDABLE (constructor),
                                           builder,
                                           info->id);
      g_assert (obj != NULL);
      if (construct_parameters->len)
        g_warning ("Can't pass in construct-only parameters to %s", info->id);
    }
  else if (info->parent && ((ChildInfo*)info->parent)->internal_child != NULL)
    {
      gchar *childname = ((ChildInfo*)info->parent)->internal_child;
635 636 637 638 639 640 641
      obj = gtk_builder_get_internal_child (builder, info, childname, error);
      if (!obj)
	{
	  g_array_free (parameters, TRUE);
	  g_array_free (construct_parameters, TRUE);
	  return NULL;
	}
642 643
      if (construct_parameters->len)
        g_warning ("Can't pass in construct-only parameters to %s", childname);
644
      g_object_ref (obj);
645 646 647 648 649 650 651
    }
  else
    {
      obj = g_object_newv (object_type,
                           construct_parameters->len,
                           (GParameter *)construct_parameters->data);

652 653 654 655 656 657 658 659 660 661 662 663
      /* No matter what, make sure we have a reference.
       *
       * If it's an initially unowned object, sink it.
       * If it's not initially unowned then we have the reference already.
       *
       * In the case that this is a window it will be sunk already and
       * this is effectively a call to g_object_ref().  That's what
       * we want.
       */
      if (G_IS_INITIALLY_UNOWNED (obj))
        g_object_ref_sink (obj);

664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682
      GTK_NOTE (BUILDER,
                g_print ("created %s of type %s\n", info->id, info->class_name));

      for (i = 0; i < construct_parameters->len; i++)
        {
          GParameter *param = &g_array_index (construct_parameters,
                                              GParameter, i);
          g_value_unset (&param->value);
        }
    }
  g_array_free (construct_parameters, TRUE);

  custom_set_property = FALSE;
  buildable = NULL;
  iface = NULL;
  if (GTK_IS_BUILDABLE (obj))
    {
      buildable = GTK_BUILDABLE (obj);
      iface = GTK_BUILDABLE_GET_IFACE (obj);
683
      if (iface->set_buildable_property)
684 685 686 687 688 689 690
        custom_set_property = TRUE;
    }

  for (i = 0; i < parameters->len; i++)
    {
      GParameter *param = &g_array_index (parameters, GParameter, i);
      if (custom_set_property)
691
        iface->set_buildable_property (buildable, builder, param->name, &param->value);
692 693 694 695
      else
        g_object_set_property (obj, param->name, &param->value);

#if G_ENABLE_DEBUG
696
      if (gtk_get_debug_flags () & GTK_DEBUG_BUILDER)
697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714
        {
          gchar *str = g_strdup_value_contents ((const GValue*)&param->value);
          g_print ("set %s: %s = %s\n", info->id, param->name, str);
          g_free (str);
        }
#endif      
      g_value_unset (&param->value);
    }
  g_array_free (parameters, TRUE);
  
  if (GTK_IS_BUILDABLE (obj))
    gtk_buildable_set_name (buildable, info->id);
  else
    g_object_set_data_full (obj,
                            "gtk-builder-name",
                            g_strdup (info->id),
                            g_free);

715
  /* we already own a reference to obj.  put it in the hash table. */
716 717 718 719 720
  g_hash_table_insert (builder->priv->objects, g_strdup (info->id), obj);
  
  return obj;
}

721 722 723 724 725 726 727
void
_gtk_builder_add_object (GtkBuilder  *builder,
                         const gchar *id,
                         GObject     *object)
{
  g_hash_table_insert (builder->priv->objects, g_strdup (id), g_object_ref (object));
}
728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749

void
_gtk_builder_add (GtkBuilder *builder,
                  ChildInfo  *child_info)
{
  GObject *object;
  GObject *parent;

  /* Internal children are already added
   * Also prevent us from being called twice.
   */
  if (!child_info ||
      child_info->internal_child ||
      child_info->added)
    return;

  object = child_info->object;
  if (!object)
    return;

  if (!child_info->parent)
    {
750
      g_warning ("%s: Not adding, No parent",
751 752 753 754 755 756 757 758 759 760 761 762 763 764
                 gtk_buildable_get_name (GTK_BUILDABLE (object)));
      return;
    }

  g_assert (object != NULL);

  parent = ((ObjectInfo*)child_info->parent)->object;
  g_assert (GTK_IS_BUILDABLE (parent));

  GTK_NOTE (BUILDER,
            g_print ("adding %s to %s\n",
                     gtk_buildable_get_name (GTK_BUILDABLE (object)),
                     gtk_buildable_get_name (GTK_BUILDABLE (parent))));
  
765 766
  gtk_buildable_add_child (GTK_BUILDABLE (parent), builder, object,
			   child_info->type);
767 768 769 770

  child_info->added = TRUE;
}

771 772 773 774 775 776 777 778
void
_gtk_builder_add_signals (GtkBuilder *builder,
			  GSList     *signals)
{
  builder->priv->signals = g_slist_concat (builder->priv->signals,
                                           g_slist_copy (signals));
}

779
static void
780
gtk_builder_apply_delayed_properties (GtkBuilder *builder)
781
{
782
  GSList *l, *props;
783 784 785 786 787 788
  DelayedProperty *property;
  GObject *object;
  GType object_type;
  GObjectClass *oclass;
  GParamSpec *pspec;

789 790 791 792 793 794 795 796
  /* take the list over from the builder->priv.
   *
   * g_slist_reverse does not copy the list, so the list now
   * belongs to us (and we free it at the end of this function).
   */
  props = g_slist_reverse (builder->priv->delayed_properties);
  builder->priv->delayed_properties = NULL;

797 798 799 800 801 802 803 804 805 806 807 808 809 810 811
  for (l = props; l; l = l->next)
    {
      property = (DelayedProperty*)l->data;
      object = g_hash_table_lookup (builder->priv->objects, property->object);
      g_assert (object != NULL);

      object_type = G_OBJECT_TYPE (object);
      g_assert (object_type != G_TYPE_INVALID);

      oclass = g_type_class_ref (object_type);
      g_assert (oclass != NULL);

      pspec = g_object_class_find_property (G_OBJECT_CLASS (oclass),
                                            property->name);
      if (!pspec)
812
        g_warning ("Unknown property: %s.%s", g_type_name (object_type),
813 814 815 816 817 818 819
                   property->name);
      else
        {
          GObject *obj;

          obj = g_hash_table_lookup (builder->priv->objects, property->value);
          if (!obj)
820
            g_warning ("No object called: %s", property->value);
821 822 823 824 825 826 827 828 829 830 831 832 833
          else
            g_object_set (object, property->name, obj, NULL);
        }
      g_free (property->value);
      g_free (property->object);
      g_free (property->name);
      g_slice_free (DelayedProperty, property);
      g_type_class_unref (oclass);
    }
  g_slist_free (props);
}

void
834
_gtk_builder_finish (GtkBuilder *builder)
835
{
836
  gtk_builder_apply_delayed_properties (builder);
837 838 839 840 841 842 843
}

/**
 * gtk_builder_new:
 *
 * Creates a new builder object.
 *
Matthias Clasen's avatar
Matthias Clasen committed
844
 * Return value: a new #GtkBuilder object
845 846 847 848 849 850 851 852 853 854 855 856 857
 *
 * Since: 2.12
 **/
GtkBuilder *
gtk_builder_new (void)
{
  return g_object_new (GTK_TYPE_BUILDER, NULL);
}

/**
 * gtk_builder_add_from_file:
 * @builder: a #GtkBuilder
 * @filename: the name of the file to parse
858
 * @error: (allow-none): return location for an error, or %NULL
859
 *
Matthias Clasen's avatar
Matthias Clasen committed
860
 * Parses a file containing a <link linkend="BUILDER-UI">GtkBuilder 
Matthias Clasen's avatar
Matthias Clasen committed
861
 * UI definition</link> and merges it with the current contents of @builder. 
862
 * 
863 864 865 866
 * Upon errors 0 will be returned and @error will be assigned a
 * #GError from the #GTK_BUILDER_ERROR, #G_MARKUP_ERROR or #G_FILE_ERROR 
 * domain.
 *
867 868 869 870 871 872 873 874 875
 * Returns: A positive value on success, 0 if an error occurred
 *
 * Since: 2.12
 **/
guint
gtk_builder_add_from_file (GtkBuilder   *builder,
                           const gchar  *filename,
                           GError      **error)
{
Matthias Clasen's avatar
Matthias Clasen committed
876
  gchar *buffer;
877
  gsize length;
878 879 880 881
  GError *tmp_error;

  g_return_val_if_fail (GTK_IS_BUILDER (builder), 0);
  g_return_val_if_fail (filename != NULL, 0);
882
  g_return_val_if_fail (error == NULL || *error == NULL, 0);
883 884 885 886 887 888 889 890 891

  tmp_error = NULL;

  if (!g_file_get_contents (filename, &buffer, &length, &tmp_error))
    {
      g_propagate_error (error, tmp_error);
      return 0;
    }
  
892
  g_free (builder->priv->filename);
893
  g_free (builder->priv->resource_prefix);
894
  builder->priv->filename = g_strdup (filename);
895
  builder->priv->resource_prefix = NULL;
Matthias Clasen's avatar
Matthias Clasen committed
896

897 898
  _gtk_builder_parser_parse_buffer (builder, filename,
                                    buffer, length,
899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916
                                    NULL,
                                    &tmp_error);

  g_free (buffer);

  if (tmp_error != NULL)
    {
      g_propagate_error (error, tmp_error);
      return 0;
    }

  return 1;
}

/**
 * gtk_builder_add_objects_from_file:
 * @builder: a #GtkBuilder
 * @filename: the name of the file to parse
917
 * @object_ids: (array zero-terminated=1) (element-type utf8): nul-terminated array of objects to build
918
 * @error: (allow-none): return location for an error, or %NULL
919 920 921 922 923
 *
 * Parses a file containing a <link linkend="BUILDER-UI">GtkBuilder 
 * UI definition</link> building only the requested objects and merges
 * them with the current contents of @builder. 
 *
924 925 926 927
 * Upon errors 0 will be returned and @error will be assigned a
 * #GError from the #GTK_BUILDER_ERROR, #G_MARKUP_ERROR or #G_FILE_ERROR 
 * domain.
 *
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
 * <note><para>
 * If you are adding an object that depends on an object that is not 
 * its child (for instance a #GtkTreeView that depends on its
 * #GtkTreeModel), you have to explicitely list all of them in @object_ids. 
 * </para></note>
 *
 * Returns: A positive value on success, 0 if an error occurred
 *
 * Since: 2.14
 **/
guint
gtk_builder_add_objects_from_file (GtkBuilder   *builder,
                                   const gchar  *filename,
                                   gchar       **object_ids,
                                   GError      **error)
{
  gchar *buffer;
  gsize length;
  GError *tmp_error;

  g_return_val_if_fail (GTK_IS_BUILDER (builder), 0);
  g_return_val_if_fail (filename != NULL, 0);
  g_return_val_if_fail (object_ids != NULL && object_ids[0] != NULL, 0);
  g_return_val_if_fail (error == NULL || *error == NULL, 0);

  tmp_error = NULL;

  if (!g_file_get_contents (filename, &buffer, &length, &tmp_error))
    {
      g_propagate_error (error, tmp_error);
      return 0;
    }
  
  g_free (builder->priv->filename);
962
  g_free (builder->priv->resource_prefix);
963
  builder->priv->filename = g_strdup (filename);
964
  builder->priv->resource_prefix = NULL;
965 966 967 968

  _gtk_builder_parser_parse_buffer (builder, filename,
                                    buffer, length,
                                    object_ids,
969 970
                                    &tmp_error);

971 972
  g_free (buffer);

973 974 975 976 977 978 979 980 981
  if (tmp_error != NULL)
    {
      g_propagate_error (error, tmp_error);
      return 0;
    }

  return 1;
}

982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 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 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132
/**
 * gtk_builder_add_from_resource:
 * @builder: a #GtkBuilder
 * @resource_path: the path of the resource file to parse
 * @error: (allow-none): return location for an error, or %NULL
 *
 * Parses a resource file containing a <link linkend="BUILDER-UI">GtkBuilder
 * UI definition</link> and merges it with the current contents of @builder.
 *
 * Upon errors 0 will be returned and @error will be assigned a
 * #GError from the #GTK_BUILDER_ERROR, #G_MARKUP_ERROR or #G_RESOURCE_ERROR
 * domain.
 *
 * Returns: A positive value on success, 0 if an error occurred
 *
 * Since: 3.4
 **/
guint
gtk_builder_add_from_resource (GtkBuilder   *builder,
			       const gchar  *resource_path,
			       GError      **error)
{
  GError *tmp_error;
  GBytes *data;
  char *filename_for_errors;
  char *slash;

  g_return_val_if_fail (GTK_IS_BUILDER (builder), 0);
  g_return_val_if_fail (resource_path != NULL, 0);
  g_return_val_if_fail (error == NULL || *error == NULL, 0);

  tmp_error = NULL;

  data = g_resources_lookup_data (resource_path, 0, &tmp_error);
  if (data == NULL)
    {
      g_propagate_error (error, tmp_error);
      return 0;
    }

  g_free (builder->priv->filename);
  g_free (builder->priv->resource_prefix);
  builder->priv->filename = g_strdup (".");

  slash = strrchr (resource_path, '/');
  if (slash != NULL)
    builder->priv->resource_prefix =
      g_strndup (resource_path, slash - resource_path + 1);
  else
    builder->priv->resource_prefix =
      g_strdup ("/");

  filename_for_errors = g_strconcat ("<resource>", resource_path, NULL);

  _gtk_builder_parser_parse_buffer (builder, filename_for_errors,
                                    g_bytes_get_data (data, NULL), g_bytes_get_size (data),
                                    NULL,
                                    &tmp_error);

  g_free (filename_for_errors);
  g_bytes_unref (data);

  if (tmp_error != NULL)
    {
      g_propagate_error (error, tmp_error);
      return 0;
    }

  return 1;
}

/**
 * gtk_builder_add_objects_from_resource:
 * @builder: a #GtkBuilder
 * @resource_path: the path of the resource file to parse
 * @object_ids: (array zero-terminated=1) (element-type utf8): nul-terminated array of objects to build
 * @error: (allow-none): return location for an error, or %NULL
 *
 * Parses a resource file containing a <link linkend="BUILDER-UI">GtkBuilder
 * UI definition</link> building only the requested objects and merges
 * them with the current contents of @builder.
 *
 * Upon errors 0 will be returned and @error will be assigned a
 * #GError from the #GTK_BUILDER_ERROR, #G_MARKUP_ERROR or #G_RESOURCE_ERROR
 * domain.
 *
 * <note><para>
 * If you are adding an object that depends on an object that is not
 * its child (for instance a #GtkTreeView that depends on its
 * #GtkTreeModel), you have to explicitely list all of them in @object_ids.
 * </para></note>
 *
 * Returns: A positive value on success, 0 if an error occurred
 *
 * Since: 3.4
 **/
guint
gtk_builder_add_objects_from_resource (GtkBuilder   *builder,
				       const gchar  *resource_path,
				       gchar       **object_ids,
				       GError      **error)
{
  GError *tmp_error;
  GBytes *data;
  char *filename_for_errors;
  char *slash;

  g_return_val_if_fail (GTK_IS_BUILDER (builder), 0);
  g_return_val_if_fail (resource_path != NULL, 0);
  g_return_val_if_fail (object_ids != NULL && object_ids[0] != NULL, 0);
  g_return_val_if_fail (error == NULL || *error == NULL, 0);

  tmp_error = NULL;

  data = g_resources_lookup_data (resource_path, 0, &tmp_error);
  if (data == NULL)
    {
      g_propagate_error (error, tmp_error);
      return 0;
    }

  g_free (builder->priv->filename);
  g_free (builder->priv->resource_prefix);
  builder->priv->filename = g_strdup (".");

  slash = strrchr (resource_path, '/');
  if (slash != NULL)
    builder->priv->resource_prefix =
      g_strndup (resource_path, slash - resource_path + 1);
  else
    builder->priv->resource_prefix =
      g_strdup ("/");

  filename_for_errors = g_strconcat ("<resource>", resource_path, NULL);

  _gtk_builder_parser_parse_buffer (builder, filename_for_errors,
                                    g_bytes_get_data (data, NULL), g_bytes_get_size (data),
                                    object_ids,
                                    &tmp_error);
  g_free (filename_for_errors);
  g_bytes_unref (data);

  if (tmp_error != NULL)
    {
      g_propagate_error (error, tmp_error);
      return 0;
    }

  return 1;
}

1133 1134 1135 1136 1137
/**
 * gtk_builder_add_from_string:
 * @builder: a #GtkBuilder
 * @buffer: the string to parse
 * @length: the length of @buffer (may be -1 if @buffer is nul-terminated)
1138
 * @error: (allow-none): return location for an error, or %NULL
1139
 *
Matthias Clasen's avatar
Matthias Clasen committed
1140 1141
 * Parses a string containing a <link linkend="BUILDER-UI">GtkBuilder 
 * UI definition</link> and merges it with the current contents of @builder. 
1142
 *
1143 1144 1145
 * Upon errors 0 will be returned and @error will be assigned a
 * #GError from the #GTK_BUILDER_ERROR or #G_MARKUP_ERROR domain.
 *
1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159
 * Returns: A positive value on success, 0 if an error occurred
 *
 * Since: 2.12
 **/
guint
gtk_builder_add_from_string (GtkBuilder   *builder,
                             const gchar  *buffer,
                             gsize         length,
                             GError      **error)
{
  GError *tmp_error;

  g_return_val_if_fail (GTK_IS_BUILDER (builder), 0);
  g_return_val_if_fail (buffer != NULL, 0);
1160 1161 1162 1163 1164
  g_return_val_if_fail (error == NULL || *error == NULL, 0);

  tmp_error = NULL;

  g_free (builder->priv->filename);
1165
  g_free (builder->priv->resource_prefix);
1166
  builder->priv->filename = g_strdup (".");
1167
  builder->priv->resource_prefix = NULL;
1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186

  _gtk_builder_parser_parse_buffer (builder, "<input>",
                                    buffer, length,
                                    NULL,
                                    &tmp_error);
  if (tmp_error != NULL)
    {
      g_propagate_error (error, tmp_error);
      return 0;
    }

  return 1;
}

/**
 * gtk_builder_add_objects_from_string:
 * @builder: a #GtkBuilder
 * @buffer: the string to parse
 * @length: the length of @buffer (may be -1 if @buffer is nul-terminated)
1187
 * @object_ids: (array zero-terminated=1) (element-type utf8): nul-terminated array of objects to build
1188
 * @error: (allow-none): return location for an error, or %NULL
1189 1190 1191 1192
 *
 * Parses a string containing a <link linkend="BUILDER-UI">GtkBuilder 
 * UI definition</link> building only the requested objects and merges
 * them with the current contents of @builder. 
1193 1194 1195
 *
 * Upon errors 0 will be returned and @error will be assigned a
 * #GError from the #GTK_BUILDER_ERROR or #G_MARKUP_ERROR domain.
1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219
 * 
 * <note><para>
 * If you are adding an object that depends on an object that is not 
 * its child (for instance a #GtkTreeView that depends on its
 * #GtkTreeModel), you have to explicitely list all of them in @object_ids. 
 * </para></note>
 *
 * Returns: A positive value on success, 0 if an error occurred
 *
 * Since: 2.14
 **/
guint
gtk_builder_add_objects_from_string (GtkBuilder   *builder,
                                     const gchar  *buffer,
                                     gsize         length,
                                     gchar       **object_ids,
                                     GError      **error)
{
  GError *tmp_error;

  g_return_val_if_fail (GTK_IS_BUILDER (builder), 0);
  g_return_val_if_fail (buffer != NULL, 0);
  g_return_val_if_fail (object_ids != NULL && object_ids[0] != NULL, 0);
  g_return_val_if_fail (error == NULL || *error == NULL, 0);
1220 1221 1222

  tmp_error = NULL;

1223
  g_free (builder->priv->filename);
1224
  g_free (builder->priv->resource_prefix);
Matthias Clasen's avatar
Matthias Clasen committed
1225
  builder->priv->filename = g_strdup (".");
1226
  builder->priv->resource_prefix = NULL;
Matthias Clasen's avatar
Matthias Clasen committed
1227

1228 1229
  _gtk_builder_parser_parse_buffer (builder, "<input>",
                                    buffer, length,
1230
                                    object_ids,
1231
                                    &tmp_error);
1232

1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246
  if (tmp_error != NULL)
    {
      g_propagate_error (error, tmp_error);
      return 0;
    }

  return 1;
}

/**
 * gtk_builder_get_object:
 * @builder: a #GtkBuilder
 * @name: name of object to get
 *
Matthias Clasen's avatar
Matthias Clasen committed
1247 1248
 * Gets the object named @name. Note that this function does not
 * increment the reference count of the returned object. 
Matthias Clasen's avatar
Matthias Clasen committed
1249
 *
1250 1251
 * Return value: (transfer none): the object named @name or %NULL if
 *    it could not be found in the object tree.
1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265
 *
 * Since: 2.12
 **/
GObject *
gtk_builder_get_object (GtkBuilder  *builder,
                        const gchar *name)
{
  g_return_val_if_fail (GTK_IS_BUILDER (builder), NULL);
  g_return_val_if_fail (name != NULL, NULL);

  return g_hash_table_lookup (builder->priv->objects, name);
}

static void
Matthias Clasen's avatar
Matthias Clasen committed
1266 1267 1268
object_add_to_list (gchar    *object_id,
                    GObject  *object,
                    GSList  **list)
1269 1270 1271 1272 1273 1274 1275 1276
{
  *list = g_slist_prepend (*list, object);
}

/**
 * gtk_builder_get_objects:
 * @builder: a #GtkBuilder
 *
Matthias Clasen's avatar
Matthias Clasen committed
1277 1278 1279
 * Gets all objects that have been constructed by @builder. Note that 
 * this function does not increment the reference counts of the returned
 * objects.
Matthias Clasen's avatar
Matthias Clasen committed
1280
 *
1281
 * Return value: (element-type GObject) (transfer container): a newly-allocated #GSList containing all the objects
Matthias Clasen's avatar
Matthias Clasen committed
1282 1283
 *   constructed by the #GtkBuilder instance. It should be freed by
 *   g_slist_free()
1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301
 *
 * Since: 2.12
 **/
GSList *
gtk_builder_get_objects (GtkBuilder *builder)
{
  GSList *objects = NULL;

  g_return_val_if_fail (GTK_IS_BUILDER (builder), NULL);

  g_hash_table_foreach (builder->priv->objects, (GHFunc)object_add_to_list, &objects);

  return g_slist_reverse (objects);
}

/**
 * gtk_builder_set_translation_domain:
 * @builder: a #GtkBuilder
1302
 * @domain: (allow-none): the translation domain or %NULL
1303
 *
Matthias Clasen's avatar
Matthias Clasen committed
1304 1305
 * Sets the translation domain of @builder. 
 * See #GtkBuilder:translation-domain.
1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327
 *
 * Since: 2.12
 **/
void
gtk_builder_set_translation_domain (GtkBuilder  *builder,
                                    const gchar *domain)
{
  gchar *new_domain;
    
  g_return_if_fail (GTK_IS_BUILDER (builder));

  new_domain = g_strdup (domain);
  g_free (builder->priv->domain);
  builder->priv->domain = new_domain;

  g_object_notify (G_OBJECT (builder), "translation-domain");
}

/**
 * gtk_builder_get_translation_domain:
 * @builder: a #GtkBuilder
 *
Matthias Clasen's avatar
Matthias Clasen committed
1328
 * Gets the translation domain of @builder.
Matthias Clasen's avatar
Matthias Clasen committed
1329 1330
 *
 * Return value: the translation domain. This string is owned
1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361
 * by the builder object and must not be modified or freed.
 *
 * Since: 2.12
 **/
const gchar *
gtk_builder_get_translation_domain (GtkBuilder *builder)
{
  g_return_val_if_fail (GTK_IS_BUILDER (builder), NULL);

  return builder->priv->domain;
}

typedef struct {
  GModule *module;
  gpointer data;
} connect_args;

static void
gtk_builder_connect_signals_default (GtkBuilder    *builder,
				     GObject       *object,
				     const gchar   *signal_name,
				     const gchar   *handler_name,
				     GObject       *connect_object,
				     GConnectFlags  flags,
				     gpointer       user_data)
{
  GCallback func;
  connect_args *args = (connect_args*)user_data;
  
  if (!g_module_symbol (args->module, handler_name, (gpointer)&func))
    {
Matthias Clasen's avatar
Matthias Clasen committed
1362
      g_warning ("Could not find signal handler '%s'", handler_name);
1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378
      return;
    }

  if (connect_object)
    g_signal_connect_object (object, signal_name, func, connect_object, flags);
  else
    g_signal_connect_data (object, signal_name, func, args->data, NULL, flags);
}


/**
 * gtk_builder_connect_signals:
 * @builder: a #GtkBuilder
 * @user_data: a pointer to a structure sent in as user data to all signals
 *
 * This method is a simpler variation of gtk_builder_connect_signals_full().
Matthias Clasen's avatar
Matthias Clasen committed
1379 1380
 * It uses #GModule's introspective features (by opening the module %NULL) 
 * to look at the application's symbol table. From here it tries to match
1381
 * the signal handler names given in the interface description with
1382 1383
 * symbols in the application and connects the signals. Note that this
 * function can only be called once, subsequent calls will do nothing.
1384 1385 1386 1387
 * 
 * Note that this function will not work correctly if #GModule is not
 * supported on the platform.
 *
1388 1389 1390 1391 1392 1393
 * When compiling applications for Windows, you must declare signal callbacks
 * with #G_MODULE_EXPORT, or they will not be put in the symbol table.
 * On Linux and Unices, this is not necessary; applications should instead
 * be compiled with the -Wl,--export-dynamic CFLAGS, and linked against
 * gmodule-export-2.0.
 *
1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404
 * Since: 2.12
 **/
void
gtk_builder_connect_signals (GtkBuilder *builder,
			     gpointer    user_data)
{
  connect_args *args;
  
  g_return_if_fail (GTK_IS_BUILDER (builder));
  
  if (!g_module_supported ())
Matthias Clasen's avatar
Matthias Clasen committed
1405
    g_error ("gtk_builder_connect_signals() requires working GModule");
1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421

  args = g_slice_new0 (connect_args);
  args->module = g_module_open (NULL, G_MODULE_BIND_LAZY);
  args->data = user_data;
  
  gtk_builder_connect_signals_full (builder,
                                    gtk_builder_connect_signals_default,
                                    args);
  g_module_close (args->module);

  g_slice_free (connect_args, args);
}

/**
 * GtkBuilderConnectFunc:
 * @builder: a #GtkBuilder
Matthias Clasen's avatar
Matthias Clasen committed
1422
 * @object: object to connect a signal to
1423 1424
 * @signal_name: name of the signal
 * @handler_name: name of the handler
Matthias Clasen's avatar
Matthias Clasen committed
1425
 * @connect_object: a #GObject, if non-%NULL, use g_signal_connect_object()
1426 1427 1428 1429 1430 1431 1432
 * @flags: #GConnectFlags to use
 * @user_data: user data
 *
 * This is the signature of a function used to connect signals.  It is used
 * by the gtk_builder_connect_signals() and gtk_builder_connect_signals_full()
 * methods.  It is mainly intended for interpreted language bindings, but
 * could be useful where the programmer wants more control over the signal
1433 1434
 * connection process. Note that this function can only be called once,
 * subsequent calls will do nothing.
1435 1436 1437 1438 1439 1440 1441
 *
 * Since: 2.12
 */

/**
 * gtk_builder_connect_signals_full:
 * @builder: a #GtkBuilder
1442
 * @func: (scope call): the function used to connect the signals
Matthias Clasen's avatar
Matthias Clasen committed
1443
 * @user_data: arbitrary data that will be passed to the connection function
1444 1445
 *
 * This function can be thought of the interpreted language binding
Matthias Clasen's avatar
Matthias Clasen committed
1446 1447
 * version of gtk_builder_connect_signals(), except that it does not
 * require GModule to function correctly.
1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484
 *
 * Since: 2.12
 */
void
gtk_builder_connect_signals_full (GtkBuilder            *builder,
                                  GtkBuilderConnectFunc  func,
                                  gpointer               user_data)
{
  GSList *l;
  GObject *object;
  GObject *connect_object;
  
  g_return_if_fail (GTK_IS_BUILDER (builder));
  g_return_if_fail (func != NULL);
  
  if (!builder->priv->signals)
    return;

  builder->priv->signals = g_slist_reverse (builder->priv->signals);
  for (l = builder->priv->signals; l; l = l->next)
    {
      SignalInfo *signal = (SignalInfo*)l->data;

      g_assert (signal != NULL);
      g_assert (signal->name != NULL);

      object = g_hash_table_lookup (builder->priv->objects,
				    signal->object_name);
      g_assert (object != NULL);

      connect_object = NULL;
      
      if (signal->connect_object_name)
	{
	  connect_object = g_hash_table_lookup (builder->priv->objects,
						signal->connect_object_name);
	  if (!connect_object)
Matthias Clasen's avatar
Matthias Clasen committed
1485
	      g_warning ("Could not lookup object %s on signal %s of object %s",
1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499
			 signal->connect_object_name, signal->name,
			 signal->object_name);
	}
						  
      func (builder, object, signal->name, signal->handler, 
	    connect_object, signal->flags, user_data);
    }

  g_slist_foreach (builder->priv->signals, (GFunc)_free_signal_info, NULL);
  g_slist_free (builder->priv->signals);
  builder->priv->signals = NULL;
}

/**
Matthias Clasen's avatar
Matthias Clasen committed
1500
 * gtk_builder_value_from_string:
1501
 * @builder: a #GtkBuilder
Matthias Clasen's avatar
Matthias Clasen committed
1502 1503
 * @pspec: the #GParamSpec for the property
 * @string: the string representation of the value
1504
 * @value: (out): the #GValue to store the result in
1505
 * @error: (allow-none): return location for an error, or %NULL
1506
 *
Matthias Clasen's avatar
Matthias Clasen committed
1507
 * This function demarshals a value from a string. This function
1508 1509 1510 1511
 * calls g_value_init() on the @value argument, so it need not be
 * initialised beforehand.
 *
 * This function can handle char, uchar, boolean, int, uint, long,
1512
 * ulong, enum, flags, float, double, string, #GdkColor, #GdkRGBA and
Matthias Clasen's avatar
Matthias Clasen committed
1513
 * #GtkAdjustment type values. Support for #GtkWidget type values is
1514 1515
 * still to come.
 *
1516 1517 1518
 * Upon errors %FALSE will be returned and @error will be assigned a
 * #GError from the #GTK_BUILDER_ERROR domain.
 *
Matthias Clasen's avatar
Matthias Clasen committed
1519
 * Returns: %TRUE on success
1520 1521 1522 1523
 *
 * Since: 2.12
 */
gboolean
1524 1525 1526 1527 1528
gtk_builder_value_from_string (GtkBuilder   *builder,
			       GParamSpec   *pspec,
                               const gchar  *string,
                               GValue       *value,
			       GError      **error)
1529
{
1530 1531 1532 1533 1534 1535
  g_return_val_if_fail (GTK_IS_BUILDER (builder), FALSE);
  g_return_val_if_fail (G_IS_PARAM_SPEC (pspec), FALSE);
  g_return_val_if_fail (string != NULL, FALSE);
  g_return_val_if_fail (value != NULL, FALSE);
  g_return_val_if_fail (error == NULL || *error == NULL, FALSE);

1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549
  /*
   * GParamSpecUnichar has the internal type G_TYPE_UINT,
   * so we cannot handle this in the switch, do it separately
   */
  if (G_IS_PARAM_SPEC_UNICHAR (pspec))
    {
      gunichar c;
      g_value_init (value, G_TYPE_UINT);
      c = g_utf8_get_char_validated (string, strlen (string));
      if (c > 0)
        g_value_set_uint (value, c);
      return TRUE;
    }

1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574
  /*
   * GParamSpecVariant can specify a GVariantType which can help with
   * parsing, so we need to take care of that here.
   */
  if (G_IS_PARAM_SPEC_VARIANT (pspec))
    {
      GParamSpecVariant *variant_pspec = G_PARAM_SPEC_VARIANT (pspec);
      const GVariantType *type;
      GVariant *variant;

      g_value_init (value, G_TYPE_VARIANT);

      /* The GVariant parser doesn't deal with indefinite types */
      if (g_variant_type_is_definite (variant_pspec->type))
        type = variant_pspec->type;
      else
        type = NULL;

      variant = g_variant_parse (type, string, NULL, NULL, error);
      if (variant == NULL)
        return FALSE;
      g_value_take_variant (value, variant);
      return TRUE;
    }

1575 1576 1577
  return gtk_builder_value_from_string_type (builder,
					     G_PARAM_SPEC_VALUE_TYPE (pspec),
                                             string, value, error);
1578 1579 1580
}

/**
Matthias Clasen's avatar
Matthias Clasen committed
1581
 * gtk_builder_value_from_string_type:
1582
 * @builder: a #GtkBuilder
Matthias Clasen's avatar
Matthias Clasen committed
1583 1584
 * @type: the #GType of the value
 * @string: the string representation of the value
1585
 * @value: (out): the #GValue to store the result in
1586
 * @error: (allow-none): return location for an error, or %NULL
1587
 *
Matthias Clasen's avatar
Matthias Clasen committed
1588 1589 1590 1591
 * Like gtk_builder_value_from_string(), this function demarshals 
 * a value from a string, but takes a #GType instead of #GParamSpec.
 * This function calls g_value_init() on the @value argument, so it 
 * need not be initialised beforehand.
1592
 *
1593 1594 1595
 * Upon errors %FALSE will be returned and @error will be assigned a
 * #GError from the #GTK_BUILDER_ERROR domain.
 *
Matthias Clasen's avatar
Matthias Clasen committed
1596
 * Returns: %TRUE on success
1597 1598 1599 1600
 *
 * Since: 2.12
 */
gboolean
1601 1602 1603 1604 1605
gtk_builder_value_from_string_type (GtkBuilder   *builder,
				    GType         type,
                                    const gchar  *string,
                                    GValue       *value,
				    GError      **error)
1606 1607 1608 1609 1610
{
  gboolean ret = TRUE;

  g_return_val_if_fail (type != G_TYPE_INVALID, FALSE);
  g_return_val_if_fail (string != NULL, FALSE);
1611
  g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1612 1613 1614 1615 1616 1617

  g_value_init (value, type);

  switch (G_TYPE_FUNDAMENTAL (type))
    {
    case G_TYPE_CHAR:
1618
      g_value_set_schar (value, string[0]);
1619 1620 1621 1622 1623 1624 1625 1626
      break;
    case G_TYPE_UCHAR:
      g_value_set_uchar (value, (guchar)string[0]);
      break;
    case G_TYPE_BOOLEAN:
      {
        gboolean b;

1627
	if (!_gtk_builder_boolean_from_string (string, &b, error))
1628 1629 1630
	  {
	    ret = FALSE;
	    break;
1631 1632 1633 1634 1635 1636 1637 1638
          }
        g_value_set_boolean (value, b);
        break;
      }
    case G_TYPE_INT:
    case G_TYPE_LONG:
      {
        long l;
1639
        gchar *endptr = NULL;
1640
        errno = 0;
1641
        l = g_ascii_strtoll (string, &endptr, 0);
1642 1643
        if (errno || endptr == string)
          {
1644 1645 1646
	    g_set_error (error,
			 GTK_BUILDER_ERROR,
			 GTK_BUILDER_ERROR_INVALID_VALUE,
Matthias Clasen's avatar
Matthias Clasen committed
1647
			 "Could not parse integer `%s'",
1648
			 string);
1649 1650 1651
            ret = FALSE;
            break;
          }
1652 1653 1654 1655 1656 1657 1658 1659 1660
        if (G_VALUE_HOLDS_INT (value))
          g_value_set_int (value, l);
        else
          g_value_set_long (value, l);
        break;
      }
    case G_TYPE_UINT:
    case G_TYPE_ULONG:
      {
1661
        gulong ul;
1662
        gchar *endptr = NULL;
1663
        errno = 0;
1664
        ul = g_ascii_strtoull (string, &endptr, 0);
1665
        if (errno || endptr == string)
1666
          {
1667 1668 1669
	    g_set_error (error,
			 GTK_BUILDER_ERROR,
			 GTK_BUILDER_ERROR_INVALID_VALUE,
Matthias Clasen's avatar
Matthias Clasen committed
1670
			 "Could not parse unsigned integer `%s'",
1671
			 string);
1672
            ret = FALSE;
1673 1674 1675
            break;
          }
        if (G_VALUE_HOLDS_UINT (value))
1676
          g_value_set_uint (value, ul);
1677
        else 
1678
          g_value_set_ulong (value, ul);
1679 1680 1681
        break;
      }
    case G_TYPE_ENUM:
1682 1683 1684 1685 1686 1687 1688 1689 1690 1691
      {
	gint enum_value;
	if (!_gtk_builder_enum_from_string (type, string, &enum_value, error))
	  {
	    ret = FALSE;
	    break;
          }
	g_value_set_enum (value, enum_value);
	break;
      }
1692
    case G_TYPE_FLAGS:
1693
      {
1694 1695
	guint flags_value;

1696 1697 1698 1699 1700 1701 1702 1703
	if (!_gtk_builder_flags_from_string (type, string, &flags_value, error))
	  {
	    ret = FALSE;
	    break;
          }
	g_value_set_flags (value, flags_value);
	break;
      }
1704 1705 1706
    case G_TYPE_FLOAT:
    case G_TYPE_DOUBLE:
      {
Matthias Clasen's avatar
Matthias Clasen committed
1707
        gdouble d;
1708
        gchar *endptr = NULL;
1709
        errno = 0;
1710 1711
        d = g_ascii_strtod (string, &endptr);
        if (errno || endptr == string)
1712
          {
1713 1714 1715
	    g_set_error (error,
			 GTK_BUILDER_ERROR,
			 GTK_BUILDER_ERROR_INVALID_VALUE,
Matthias Clasen's avatar
Matthias Clasen committed
1716
			 "Could not parse double `%s'",
1717
			 string);
1718
            ret = FALSE;
1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729
            break;
          }
        if (G_VALUE_HOLDS_FLOAT (value))
          g_value_set_float (value, d);
        else
          g_value_set_double (value, d);
        break;
      }
    case G_TYPE_STRING:
      g_value_set_string (value, string);
      break;
1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740
    case G_TYPE_VARIANT:
      {
        GVariant *variant;

        variant = g_variant_parse (NULL, string, NULL, NULL, error);
        if (value != NULL)
          g_value_take_variant (value, variant);
        else
          ret = FALSE;
      }
      break;
1741 1742 1743
    case G_TYPE_BOXED:
      if (G_VALUE_HOLDS (value, GDK_TYPE_COLOR))
        {
1744
          GdkColor color = { 0, };
1745

1746 1747
          if (gdk_color_parse (string, &color))
            g_value_set_boxed (value, &color);
1748 1749
          else
            {
1750 1751 1752
	      g_set_error (error,
			   GTK_BUILDER_ERROR,
			   GTK_BUILDER_ERROR_INVALID_VALUE,
Matthias Clasen's avatar
Matthias Clasen committed
1753
			   "Could not parse color `%s'",
1754
			   string);
1755 1756 1757
              ret = FALSE;
            }
        }
1758 1759 1760 1761
      else if (G_VALUE_HOLDS (value, GDK_TYPE_RGBA))
        {
          GdkRGBA rgba = { 0 };

1762
          if (gdk_rgba_parse (&rgba, string))
1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773
            g_value_set_boxed (value, &rgba);
          else
            {
              g_set_error (error,
                           GTK_BUILDER_ERROR,
                           GTK_BUILDER_ERROR_INVALID_VALUE,
                           "Could not parse RGBA color '%s'",
                           string);
              ret = FALSE;
            }
        }
1774 1775
      else if (G_VALUE_HOLDS (value, G_TYPE_STRV))
        {
Matthias Clasen's avatar
Matthias Clasen committed
1776
          gchar **vector = g_strsplit (string, "\n", 0);
1777 1778 1779
          g_value_take_boxed (value, vector);
        }
      else
Matthias Clasen's avatar
Matthias Clasen committed
1780 1781 1782 1783 1784 1785 1786 1787
        {
          g_set_error (error,
                       GTK_BUILDER_ERROR,
                       GTK_BUILDER_ERROR_INVALID_VALUE,
                       "Could not parse '%s' as a %s",
                       string, G_VALUE_TYPE_NAME (value));
          ret = FALSE;
        }
1788 1789
      break;
    case G_TYPE_OBJECT:
Matthias Clasen's avatar
Matthias Clasen committed
1790 1791 1792 1793
      if (G_VALUE_HOLDS (value, GDK_TYPE_PIXBUF))
        {
          gchar *filename;
          GError *tmp_error = NULL;
1794
          GdkPixbuf *pixbuf = NULL;
Matthias Clasen's avatar
Matthias Clasen committed
1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805
       
          if (gtk_builder_get_object (builder, string))
            {
              g_set_error (error,
                           GTK_BUILDER_ERROR,
                           GTK_BUILDER_ERROR_INVALID_VALUE,
                           "Could not load image '%s': "
                           " '%s' is already used as object id",
                           string, string);
              return FALSE;
            }
1806

1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821
	  filename = _gtk_builder_get_resource_path (builder, string);
	  if (filename != NULL)
	    {
	      GInputStream *stream = g_resources_open_stream (filename, 0, &tmp_error);
	      if (stream != NULL)
		{
		  pixbuf = gdk_pixbuf_new_from_stream (stream, NULL, &tmp_error);
		  g_object_unref (stream);
		}
	    }
	  else
	    {
	      filename = _gtk_builder_get_absolute_filename (builder, string);
	      pixbuf = gdk_pixbuf_new_from_file (filename, &tmp_error);
	    }
Matthias Clasen's avatar
Matthias Clasen committed
1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850

          if (pixbuf == NULL)
            {
              GtkIconTheme *theme;

              g_warning ("Could not load image '%s': %s", 
                         string, tmp_error->message);
              g_error_free (tmp_error);

              /* fall back to a missing image */
              theme = gtk_icon_theme_get_default ();
              pixbuf = gtk_icon_theme_load_icon (theme, 
                                                 GTK_STOCK_MISSING_IMAGE,
                                                 16,
                                                 GTK_ICON_LOOKUP_USE_BUILTIN,
                                                 NULL);
            }
 
          if (pixbuf)
            {
              g_value_set_object (value, pixbuf);
              g_object_unref (G_OBJECT (pixbuf));
            }

          g_free (filename);

          ret = TRUE;
        }
      else
Matthias Clasen's avatar
Matthias Clasen committed
1851
        ret = FALSE;
1852 1853 1854 1855 1856
      break;
    default:
      ret = FALSE;
      break;
    }
1857 1858 1859 1860 1861 1862 1863 1864 1865 1866
 
  /* Catch unassigned error for object types as well as any unsupported types.
   * While parsing GtkBuilder; object types are deserialized
   * without calling gtk_builder_value_from_string_type().
   */
  if (!ret && error && *error == NULL) 
    g_set_error (error,
		 GTK_BUILDER_ERROR,
		 GTK_BUILDER_ERROR_INVALID_VALUE,
		 "Unsupported GType `%s'", g_type_name (type));
1867 1868 1869 1870

  return ret;
}

1871
gboolean
1872 1873 1874 1875
_gtk_builder_enum_from_string (GType         type, 
                               const gchar  *string,
			       gint         *enum_value,
			       GError      **error)
1876 1877 1878 1879
{
  GEnumClass *eclass;
  GEnumValue *ev;
  gchar *endptr;
1880
  gint value;
1881
  gboolean ret;
1882
  
1883 1884
  g_return_val_if_fail (G_TYPE_IS_ENUM (type), FALSE);
  g_return_val_if_fail (string != NULL, FALSE);
1885
  
1886 1887
  ret = TRUE;

1888 1889 1890 1891
  endptr = NULL;
  errno = 0;
  value = g_ascii_strtoull (string, &endptr, 0);
  if (errno == 0 && endptr != string) /* parsed a number */
1892 1893 1894 1895 1896 1897 1898
    *enum_value = value;
  else
    {
      eclass = g_type_class_ref (type);
      ev = g_enum_get_value_by_name (eclass, string);
      if (!ev)
	ev = g_enum_get_value_by_nick (eclass, string);
1899

1900 1901 1902 1903 1904 1905 1906 1907 1908
      if (ev)
	*enum_value = ev->value;
      else
	{
	  g_set_error (error,
		       GTK_BUILDER_ERROR,
		       GTK_BUILDER_ERROR_INVALID_VALUE,
		       "Could not parse enum: `%s'",
		       string);
1909
	  ret = FALSE;
1910 1911 1912 1913 1914
	}
      
      g_type_class_unref (eclass);
    }
  
1915
  return ret;
1916 1917
}

1918 1919 1920
gboolean
_gtk_builder_flags_from_string (GType         type, 
                                const gchar  *string,
1921
				guint        *flags_value,
1922
				GError      **error)
1923 1924 1925
{
  GFlagsClass *fclass;
  gchar *endptr, *prevptr;
1926
  guint i, j, value;
Matthias Clasen's avatar
Matthias Clasen committed
1927
  gchar *flagstr;
1928
  GFlagsValue *fv;
Matthias Clasen's avatar
Matthias Clasen committed
1929
  const gchar *flag;
1930
  gunichar ch;
1931
  gboolean eos, ret;
1932

1933 1934
  g_return_val_if_fail (G_TYPE_IS_FLAGS (type), FALSE);
  g_return_val_if_fail (string != 0, FALSE);
1935

1936
  ret = TRUE;
1937 1938 1939 1940 1941

  endptr = NULL;
  errno = 0;
  value = g_ascii_strtoull (string, &endptr, 0);
  if (errno == 0 && endptr != string) /* parsed a number */
1942 1943
    *flags_value = value;
  else
1944
    {
1945
      fclass = g_type_class_ref (type);
1946

1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006