gtkbuilder.c 88.5 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
/**
 * SECTION:gtkbuilder
 * @Short_description: Build an interface from an XML UI definition
 * @Title: GtkBuilder
 *
 * A GtkBuilder is an auxiliary object that reads textual descriptions
27 28 29 30 31 32 33 34 35 36
 * of a user interface and instantiates the described objects. To create
 * a GtkBuilder from a user interface description, call
 * gtk_builder_new_from_file(), gtk_builder_new_from_resource() or
 * gtk_builder_new_from_string().
 *
 * In the (unusual) case that you want to add user interface
 * descriptions from multiple sources to the same GtkBuilder you can
 * call gtk_builder_new() to get an empty builder and populate it by
 * (multiple) calls to gtk_builder_add_from_file(),
 * gtk_builder_add_from_resource() or gtk_builder_add_from_string().
37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
 *
 * 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.
 *
59
 * # GtkBuilder UI Definitions # {#BUILDER-UI}
60 61 62
 *
 * GtkBuilder parses textual descriptions of user interfaces which are
 * specified in an XML format which can be roughly described by the
63 64
 * RELAX NG schema below. We refer to these descriptions as “GtkBuilder
 * UI definitions” or just “UI definitions” if the context is clear.
65
 * Do not confuse GtkBuilder UI Definitions with
66 67 68
 * [GtkUIManager UI Definitions][XML-UI], which are more limited in scope.
 * It is common to use `.ui` as the filename extension for files containing
 * GtkBuilder UI definitions.
69
 *
70
 * [RELAX NG Compact Syntax](https://git.gnome.org/browse/gtk+/tree/gtk/gtkbuilder.rnc)
71
 *
72 73 74 75 76 77 78 79 80 81 82 83 84 85
 * The toplevel element is <interface>. 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 <object> elements, which can contain
 * <property> elements to set properties, <signal> elements which
 * connect signals to handlers, and <child> 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 <child>
 * element contains an <object> element which describes the child object.
 * The target toolkit version(s) are described by <requires> 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 “<major>.<minor>”. The builder will error
86
 * out if the version requirements are not met.
87
 *
88 89 90 91 92 93 94 95 96 97
 * Typically, the specific kind of object represented by an <object>
 * element is specified by the “class” attribute. If the type has not
 * been loaded yet, GTK+ tries to find the 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 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.
98
 *
99
 * Objects may be given a name with the “id” attribute, which allows the
100
 * application to retrieve them from the builder with gtk_builder_get_object().
101 102 103 104
 * An id is also necessary to use the object as property value in other
 * parts of the UI definition. GTK+ reserves ids starting and ending
 * with ___ (3 underscores) for its own purposes.
 *
105
 * Setting properties of objects is pretty straightforward with the
106 107
 * <property> element: the “name” attribute specifies the name of the
 * property, and the content of the element specifies the value.
108
 * If the “translatable” attribute is set to a true value, GTK+ uses
109 110 111 112 113 114 115 116 117
 * 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,
118 119
 * booleans (strings like “TRUE”, “t”, “yes”, “y”, “1” are interpreted
 * as %TRUE, strings like “FALSE”, “f”, “no”, “n”, “0” are interpreted
120 121
 * as %FALSE), enumerations (can be specified by their name, nick or
 * integer value), flags (can be specified by their name, nick, integer
122
 * value, optionally combined with “|”, e.g. “GTK_VISIBLE|GTK_REALIZED”)
123 124 125 126 127 128 129 130 131 132 133 134
 * and colors (in a format understood by gdk_rgba_parse()).
 *
 * GVariants can be specified in the format understood by g_variant_parse(),
 * and pixbufs can be specified as a filename of an image file to load.
 *
 * Objects can be referred to by their name and by default refer to
 * objects declared in the local xml fragment and objects exposed via
 * gtk_builder_expose_object(). In general, GtkBuilder allows forward
 * references to objects — declared in the local xml; 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.
135
 *
136 137 138 139
 * It is also possible to bind a property value to another object's
 * property value using the attributes
 * "bind-source" to specify the source object of the binding,
 * "bind-property" to specify the source property and optionally
Matthias Clasen's avatar
Matthias Clasen committed
140
 * "bind-flags" to specify the binding flags
141 142
 * Internally builder implement this using GBinding objects.
 * For more information see g_object_bind_property()
Matthias Clasen's avatar
Matthias Clasen committed
143
 *
144 145 146 147 148
 * Signal handlers are set up with the <signal> 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
149 150
 * gtk_builder_connect_signals_full(). The remaining attributes, “after”,
 * “swapped” and “object”, have the same meaning as the corresponding
151
 * parameters of the g_signal_connect_object() or
152
 * g_signal_connect_data() functions. A “last_modification_time”
153 154 155 156 157 158
 * 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
159
 * a #GtkDialog). This can be achieved by setting the “internal-child”
160 161 162
 * propery of the <child> element to a true value. Note that GtkBuilder
 * still requires an <object> element for the internal child, even if it
 * has already been constructed.
163 164 165
 *
 * 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
166
 * a UI definition by specifying the “type” attribute on a <child>
167
 * The possible values for the “type” attribute are described in the
168 169
 * sections describing the widget-specific portions of UI definitions.
 *
170
 * # A GtkBuilder UI Definition
171
 *
172
 * |[
173 174 175
 * <interface>
 *   <object class="GtkDialog" id="dialog1">
 *     <child internal-child="vbox">
176
 *       <object class="GtkBox" id="vbox1">
177 178
 *         <property name="border-width">10</property>
 *         <child internal-child="action_area">
179
 *           <object class="GtkButtonBox" id="hbuttonbox1">
180 181 182 183 184 185 186 187 188 189 190 191 192 193
 *             <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>
194
 * ]|
195 196 197
 *
 * Beyond this general structure, several object classes define their
 * own XML DTD fragments for filling in the ANY placeholders in the DTD
198 199 200
 * above. Note that a custom element in a <child> element gets parsed by
 * the custom tag handler of the parent object, while a custom element in
 * an <object> element gets parsed by the custom tag handler of the object.
201 202 203 204
 *
 * These XML fragments are explained in the documentation of the
 * respective objects.
 *
205 206
 * Additionally, since 3.10 a special <template> tag has been added
 * to the format allowing one to define a widget class’s components.
207
 * See the [GtkWidget documentation][composite-templates] for details.
208 209
 */

210
#include "config.h"
211
#include <errno.h> /* errno */
212
#include <stdlib.h>
213 214 215 216 217
#include <string.h> /* strlen */

#include "gtkbuilder.h"
#include "gtkbuildable.h"
#include "gtkbuilderprivate.h"
218
#include "gtkdebug.h"
219 220 221 222
#include "gtkmain.h"
#include "gtkintl.h"
#include "gtkprivate.h"
#include "gtktypebuiltins.h"
223
#include "gtkwindow.h"
Matthias Clasen's avatar
Matthias Clasen committed
224
#include "gtkicontheme.h"
225
#include "gtktestutils.h"
226
#include "deprecated/gtkstock.h"
227

228 229 230 231 232 233 234 235 236 237 238 239

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
240 241
static GType gtk_builder_real_get_type_from_name (GtkBuilder  *builder,
                                                  const gchar *type_name);
242 243 244 245

enum {
  PROP_0,
  PROP_TRANSLATION_DOMAIN,
246
  LAST_PROP
247 248
};

249 250
static GParamSpec *builder_props[LAST_PROP];

251 252 253 254
struct _GtkBuilderPrivate
{
  gchar *domain;
  GHashTable *objects;
255
  GHashTable *callbacks;
256
  GSList *delayed_properties;
257
  GSList *signals;
258
  GSList *bindings;
259
  gchar *filename;
260
  gchar *resource_prefix;
261
  GType template_type;
262
  GtkApplication *application;
263 264
};

265
G_DEFINE_TYPE_WITH_PRIVATE (GtkBuilder, gtk_builder, G_TYPE_OBJECT)
266 267 268 269 270 271 272 273 274 275 276 277 278 279

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
280
 /**
Matthias Clasen's avatar
Matthias Clasen committed
281 282 283 284 285
  * 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(),
286
  * otherwise g_dgettext().
Matthias Clasen's avatar
Matthias Clasen committed
287 288 289
  *
  * Since: 2.12
  */
290 291 292 293 294 295 296 297
  builder_props[PROP_TRANSLATION_DOMAIN] =
      g_param_spec_string ("translation-domain",
                           P_("Translation Domain"),
                           P_("The translation domain used by gettext"),
                           NULL,
                           GTK_PARAM_READWRITE);

  g_object_class_install_properties (gobject_class, LAST_PROP, builder_props);
298 299 300 301 302
}

static void
gtk_builder_init (GtkBuilder *builder)
{
303
  builder->priv = gtk_builder_get_instance_private (builder);
304 305
  builder->priv->domain = NULL;
  builder->priv->objects = g_hash_table_new_full (g_str_hash, g_str_equal,
306
                                                  g_free, g_object_unref);
307 308 309 310 311 312 313 314 315 316
}


/*
 * GObject virtual methods
 */

static void
gtk_builder_finalize (GObject *object)
{
317
  GtkBuilderPrivate *priv = GTK_BUILDER (object)->priv;
318

319 320
  g_free (priv->domain);
  g_free (priv->filename);
321
  g_free (priv->resource_prefix);
322

323
  g_hash_table_destroy (priv->objects);
324 325
  if (priv->callbacks)
    g_hash_table_destroy (priv->callbacks);
326

Matthias Clasen's avatar
Matthias Clasen committed
327
  g_slist_free_full (priv->signals, (GDestroyNotify)_free_signal_info);
328

329
  G_OBJECT_CLASS (gtk_builder_parent_class)->finalize (object);
330 331 332 333 334 335 336 337 338 339 340 341 342 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
}

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
378 379 380
 * GWeatherLocation -> gweather_location_get_type
 *
 * Keep in sync with testsuite/gtk/typename.c !
381
 */
Matthias Clasen's avatar
Matthias Clasen committed
382 383
static gchar *
type_name_mangle (const gchar *name)
384 385
{
  GString *symbol_name = g_string_new ("");
386
  gint i;
387 388 389 390

  for (i = 0; name[i] != '\0'; i++)
    {
      /* skip if uppercase, first or previous is uppercase */
391 392 393 394 395
      if ((name[i] == g_ascii_toupper (name[i]) &&
           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])))
396
        g_string_append_c (symbol_name, '_');
Matthias Clasen's avatar
Matthias Clasen committed
397
      g_string_append_c (symbol_name, g_ascii_tolower (name[i]));
398 399
    }
  g_string_append (symbol_name, "_get_type");
Matthias Clasen's avatar
Matthias Clasen committed
400 401 402 403 404 405 406 407 408 409 410 411 412 413

  return g_string_free (symbol_name, FALSE);
}

static GType
_gtk_builder_resolve_type_lazily (const gchar *name)
{
  static GModule *module = NULL;
  GTypeGetFunc func;
  gchar *symbol;
  GType gtype = G_TYPE_INVALID;

  if (!module)
    module = g_module_open (NULL, 0);
Matthias Clasen's avatar
Matthias Clasen committed
414

Matthias Clasen's avatar
Matthias Clasen committed
415
  symbol = type_name_mangle (name);
416 417 418

  if (g_module_symbol (module, symbol, (gpointer)&func))
    gtype = func ();
Matthias Clasen's avatar
Matthias Clasen committed
419

420 421 422 423 424 425 426 427 428 429
  g_free (symbol);

  return gtype;
}

/*
 * GtkBuilder virtual methods
 */

static GType
Matthias Clasen's avatar
Matthias Clasen committed
430
gtk_builder_real_get_type_from_name (GtkBuilder  *builder,
Matthias Clasen's avatar
Matthias Clasen committed
431
                                     const gchar *type_name)
432 433 434
{
  GType gtype;

435
  gtype = g_type_from_name (type_name);
436 437 438
  if (gtype != G_TYPE_INVALID)
    return gtype;

439 440 441 442 443 444
  gtype = _gtk_builder_resolve_type_lazily (type_name);
  if (gtype != G_TYPE_INVALID)
    return gtype;

  gtk_test_register_all_types ();
  return g_type_from_name (type_name);
445 446 447 448 449
}

typedef struct
{
  gchar *object;
450
  GParamSpec *pspec;
451
  gchar *value;
452 453
  gint line;
  gint col;
454 455 456 457 458 459 460
} DelayedProperty;

static void
gtk_builder_get_parameters (GtkBuilder  *builder,
                            GType        object_type,
                            const gchar *object_name,
                            GSList      *properties,
Matthias Clasen's avatar
Matthias Clasen committed
461
                            GParamFlags  filter_flags,
462
                            GArray      **parameters,
463
                            GArray      **filtered_parameters)
464 465 466
{
  GSList *l;
  DelayedProperty *property;
467
  GError *error = NULL;
468

469 470 471 472
  if (parameters)
    *parameters = g_array_new (FALSE, FALSE, sizeof (GParameter));
  if (filtered_parameters)
    *filtered_parameters = g_array_new (FALSE, FALSE, sizeof (GParameter));
473 474 475 476 477 478

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

479
      parameter.name = prop->pspec->name;
480

481
      if (G_IS_PARAM_SPEC_OBJECT (prop->pspec) &&
482 483
          (G_PARAM_SPEC_VALUE_TYPE (prop->pspec) != GDK_TYPE_PIXBUF) &&
          (G_PARAM_SPEC_VALUE_TYPE (prop->pspec) != G_TYPE_FILE))
484
        {
485 486
          GObject *object = g_hash_table_lookup (builder->priv->objects,
                                                 prop->text->str);
487 488 489 490 491 492

          if (object)
            {
              g_value_init (&parameter.value, G_OBJECT_TYPE (object));
              g_value_set_object (&parameter.value, object);
            }
Matthias Clasen's avatar
Matthias Clasen committed
493
          else
494
            {
495
              if (prop->pspec->flags & G_PARAM_CONSTRUCT_ONLY)
496
                {
Matthias Clasen's avatar
Matthias Clasen committed
497
                  g_warning ("Failed to get construct only property "
498
                             "%s of %s with value '%s'",
499
                             prop->pspec->name, object_name, prop->text->str);
500 501
                  continue;
                }
502
              /* Delay setting property */
503
              property = g_slice_new (DelayedProperty);
504
              property->pspec = prop->pspec;
505
              property->object = g_strdup (object_name);
506
              property->value = g_strdup (prop->text->str);
507 508
              property->line = prop->line;
              property->col = prop->col;
509 510
              builder->priv->delayed_properties =
                g_slist_prepend (builder->priv->delayed_properties, property);
511 512 513
              continue;
            }
        }
514
      else if (prop->bound && (!prop->text || prop->text->len == 0))
515 516 517 518 519 520
        {
          /* Ignore properties with a binding and no value since they are
           * only there for to express the binding.
           */
          continue;
        }
521
      else if (!gtk_builder_value_from_string (builder, prop->pspec,
522
                                               prop->text->str, &parameter.value, &error))
523
        {
Matthias Clasen's avatar
Matthias Clasen committed
524
          g_warning ("Failed to set property %s.%s to %s: %s",
525
                     g_type_name (object_type), prop->pspec->name, prop->text->str,
Matthias Clasen's avatar
Matthias Clasen committed
526 527 528
                     error->message);
          g_error_free (error);
          error = NULL;
529 530 531
          continue;
        }

532
      if (prop->pspec->flags & filter_flags)
Matthias Clasen's avatar
Matthias Clasen committed
533 534 535 536
        {
          if (filtered_parameters)
            g_array_append_val (*filtered_parameters, parameter);
        }
537
      else
Matthias Clasen's avatar
Matthias Clasen committed
538 539 540 541
        {
          if (parameters)
            g_array_append_val (*parameters, parameter);
        }
542 543 544
    }
}

545 546 547 548 549 550 551 552 553
static const gchar *
object_get_name (GObject *object)
{
  if (GTK_IS_BUILDABLE (object))
    return gtk_buildable_get_name (GTK_BUILDABLE (object));
  else
    return g_object_get_data (object, "gtk-builder-name");
}

554
static GObject *
Matthias Clasen's avatar
Matthias Clasen committed
555 556 557 558
gtk_builder_get_internal_child (GtkBuilder   *builder,
                                ObjectInfo   *info,
                                const gchar  *childname,
                                GError      **error)
559 560 561 562 563 564 565 566 567 568 569 570 571
{
  GObject *obj = NULL;

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

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

      GTK_NOTE (BUILDER,
572 573
                g_message ("Trying to get internal child %s from %s",
                           childname, object_get_name (info->object)));
574 575 576 577 578 579 580 581

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

  if (!obj)
582 583
    {
      g_set_error (error,
Matthias Clasen's avatar
Matthias Clasen committed
584 585 586
                   GTK_BUILDER_ERROR,
                   GTK_BUILDER_ERROR_INVALID_VALUE,
                   "Unknown internal child: %s", childname);
587
    }
588 589 590
  return obj;
}

591
static inline void
Matthias Clasen's avatar
Matthias Clasen committed
592 593
object_set_name (GObject     *object,
                 const gchar *name)
594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609
{
  if (GTK_IS_BUILDABLE (object))
    gtk_buildable_set_name (GTK_BUILDABLE (object), name);
  else
    g_object_set_data_full (object, "gtk-builder-name", g_strdup (name), g_free);
}

void
_gtk_builder_add_object (GtkBuilder  *builder,
                         const gchar *id,
                         GObject     *object)
{
  object_set_name (object, id);
  g_hash_table_insert (builder->priv->objects, g_strdup (id), g_object_ref (object));
}

610
static void
611 612 613 614 615 616
gtk_builder_take_bindings (GtkBuilder *builder,
                           GObject    *target,
                           GSList     *bindings)
{
  GSList *l;

617
  for (l = bindings; l; l = l->next)
618 619 620 621 622 623 624 625
    {
      BindingInfo *info = l->data;
      info->target = target;
    }

  builder->priv->bindings = g_slist_concat (builder->priv->bindings, bindings);
}

626
GObject *
Matthias Clasen's avatar
Matthias Clasen committed
627 628 629
_gtk_builder_construct (GtkBuilder  *builder,
                        ObjectInfo  *info,
                        GError     **error)
630 631 632 633 634 635 636
{
  GArray *parameters, *construct_parameters;
  GObject *obj;
  int i;
  GtkBuildableIface *iface;
  gboolean custom_set_property;
  GtkBuildable *buildable;
637
  GParamFlags param_filter_flags;
638

639 640 641 642
  g_assert (info->type != G_TYPE_INVALID);

  if (builder->priv->template_type != 0 &&
      g_type_is_a (info->type, builder->priv->template_type))
643 644
    {
      g_set_error (error,
Matthias Clasen's avatar
Matthias Clasen committed
645 646
                   GTK_BUILDER_ERROR,
                   GTK_BUILDER_ERROR_OBJECT_TYPE_REFUSED,
647 648
                   "Refused to build object of type '%s' because it "
                   "conforms to the template type '%s', avoiding infinite recursion.",
Matthias Clasen's avatar
Matthias Clasen committed
649
                   g_type_name (info->type), g_type_name (builder->priv->template_type));
650 651
      return NULL;
    }
652

653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669
  /* If there is a manual constructor (like UIManager), or if this is a
   * reference to an internal child, then we filter out construct-only
   * and warn that they cannot be set.
   *
   * Otherwise if we are calling g_object_newv(), we want to pass
   * both G_PARAM_CONSTRUCT and G_PARAM_CONSTRUCT_ONLY to the
   * object's constructor.
   *
   * Passing all construct properties to g_object_newv() slightly
   * improves performance as the construct properties will only be set once.
   */
  if (info->constructor ||
      (info->parent && ((ChildInfo*)info->parent)->internal_child != NULL))
    param_filter_flags = G_PARAM_CONSTRUCT_ONLY;
  else
    param_filter_flags = G_PARAM_CONSTRUCT | G_PARAM_CONSTRUCT_ONLY;

670
  gtk_builder_get_parameters (builder, info->type,
671 672
                              info->id,
                              info->properties,
Matthias Clasen's avatar
Matthias Clasen committed
673
                              param_filter_flags,
674 675 676 677 678 679 680
                              &parameters,
                              &construct_parameters);

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

681
      constructor = g_hash_table_lookup (builder->priv->objects, info->constructor);
682
      if (constructor == NULL)
Matthias Clasen's avatar
Matthias Clasen committed
683 684 685 686 687 688 689 690 691 692 693
        {
          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;
        }
694 695 696 697 698 699 700 701 702 703
      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;
704 705
      obj = gtk_builder_get_internal_child (builder, info, childname, error);
      if (!obj)
Matthias Clasen's avatar
Matthias Clasen committed
706 707 708 709 710
        {
          g_array_free (parameters, TRUE);
          g_array_free (construct_parameters, TRUE);
          return NULL;
        }
711 712
      if (construct_parameters->len)
        g_warning ("Can't pass in construct-only parameters to %s", childname);
713
      g_object_ref (obj);
714 715 716
    }
  else
    {
717
G_GNUC_BEGIN_IGNORE_DEPRECATIONS
718
      obj = g_object_newv (info->type,
719 720
                           construct_parameters->len,
                           (GParameter *)construct_parameters->data);
721
G_GNUC_END_IGNORE_DEPRECATIONS
722

723 724 725 726 727 728 729 730 731 732 733 734
      /* 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);

735
      GTK_NOTE (BUILDER,
736
                g_message ("created %s of type %s", info->id, g_type_name (info->type)));
737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753

      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);
754
      if (iface->set_buildable_property)
755 756 757 758 759 760 761
        custom_set_property = TRUE;
    }

  for (i = 0; i < parameters->len; i++)
    {
      GParameter *param = &g_array_index (parameters, GParameter, i);
      if (custom_set_property)
762
        iface->set_buildable_property (buildable, builder, param->name, &param->value);
763 764 765 766
      else
        g_object_set_property (obj, param->name, &param->value);

#if G_ENABLE_DEBUG
767
      if (GTK_DEBUG_CHECK (BUILDER))
768 769
        {
          gchar *str = g_strdup_value_contents ((const GValue*)&param->value);
770
          g_message ("set %s: %s = %s", info->id, param->name, str);
771 772
          g_free (str);
        }
Matthias Clasen's avatar
Matthias Clasen committed
773
#endif
774 775 776 777
      g_value_unset (&param->value);
    }
  g_array_free (parameters, TRUE);

778 779 780
  if (info->bindings)
    gtk_builder_take_bindings (builder, obj, info->bindings);

781 782
  /* put it in the hash table. */
  _gtk_builder_add_object (builder, info->id, obj);
Matthias Clasen's avatar
Matthias Clasen committed
783 784

  /* we already own a reference to obj. */
785
  g_object_unref (obj);
Matthias Clasen's avatar
Matthias Clasen committed
786

787 788 789
  return obj;
}

790
void
Matthias Clasen's avatar
Matthias Clasen committed
791 792 793
_gtk_builder_apply_properties (GtkBuilder  *builder,
                               ObjectInfo  *info,
                               GError     **error)
794 795 796 797 798 799 800 801
{
  GArray *parameters;
  GtkBuildableIface *iface;
  GtkBuildable *buildable;
  gboolean custom_set_property;
  gint i;

  g_assert (info->object != NULL);
802
  g_assert (info->type != G_TYPE_INVALID);
803 804

  /* Fetch all properties that are not construct-only */
805
  gtk_builder_get_parameters (builder, info->type,
806 807
                              info->id,
                              info->properties,
Matthias Clasen's avatar
Matthias Clasen committed
808
                              G_PARAM_CONSTRUCT_ONLY,
809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830
                              &parameters, NULL);

  custom_set_property = FALSE;
  buildable = NULL;
  iface = NULL;
  if (GTK_IS_BUILDABLE (info->object))
    {
      buildable = GTK_BUILDABLE (info->object);
      iface = GTK_BUILDABLE_GET_IFACE (info->object);
      if (iface->set_buildable_property)
        custom_set_property = TRUE;
    }

  for (i = 0; i < parameters->len; i++)
    {
      GParameter *param = &g_array_index (parameters, GParameter, i);
      if (custom_set_property)
        iface->set_buildable_property (buildable, builder, param->name, &param->value);
      else
        g_object_set_property (info->object, param->name, &param->value);

#if G_ENABLE_DEBUG
831
      if (GTK_DEBUG_CHECK (BUILDER))
832 833
        {
          gchar *str = g_strdup_value_contents ((const GValue*)&param->value);
834
          g_message ("set %s: %s = %s", info->id, param->name, str);
835 836
          g_free (str);
        }
Matthias Clasen's avatar
Matthias Clasen committed
837
#endif
838 839 840 841 842
      g_value_unset (&param->value);
    }
  g_array_free (parameters, TRUE);
}

843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863
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)
    {
864
      g_warning ("%s: Not adding, No parent", object_get_name (object));
865 866 867 868 869 870 871 872 873
      return;
    }

  g_assert (object != NULL);

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

  GTK_NOTE (BUILDER,
874
            g_message ("adding %s to %s", object_get_name (object), object_get_name (parent)));
Matthias Clasen's avatar
Matthias Clasen committed
875

876
  gtk_buildable_add_child (GTK_BUILDABLE (parent), builder, object,
Matthias Clasen's avatar
Matthias Clasen committed
877
                           child_info->type);
878 879 880 881

  child_info->added = TRUE;
}

882 883
void
_gtk_builder_add_signals (GtkBuilder *builder,
Matthias Clasen's avatar
Matthias Clasen committed
884
                          GSList     *signals)
885 886 887 888 889
{
  builder->priv->signals = g_slist_concat (builder->priv->signals,
                                           g_slist_copy (signals));
}

890
static void
891
gtk_builder_apply_delayed_properties (GtkBuilder *builder)
892
{
893
  GSList *l, *props;
894

895 896 897 898 899 900 901 902
  /* 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;

903 904
  for (l = props; l; l = l->next)
    {
905 906 907
      DelayedProperty *property = l->data;
      GObject *object, *obj;

908 909 910
      object = g_hash_table_lookup (builder->priv->objects, property->object);
      g_assert (object != NULL);

911
      obj = _gtk_builder_lookup_object (builder, property->value, property->line, property->col);
912 913
      if (obj)
        g_object_set (object, property->pspec->name, obj, NULL);
914 915 916 917 918 919 920 921

      g_free (property->value);
      g_free (property->object);
      g_slice_free (DelayedProperty, property);
    }
  g_slist_free (props);
}

922
static inline void
Matthias Clasen's avatar
Matthias Clasen committed
923 924
free_binding_info (gpointer data,
                   gpointer user)
925 926
{
  BindingInfo *info = data;
927

928 929 930 931 932 933 934 935 936 937
  g_free (info->source);
  g_free (info->source_property);
  g_slice_free (BindingInfo, data);
}

static inline void
gtk_builder_create_bindings (GtkBuilder *builder)
{
  GSList *l;

938
  for (l = builder->priv->bindings; l; l = l->next)
939 940 941 942
    {
      BindingInfo *info = l->data;
      GObject *source;

943 944
      source = _gtk_builder_lookup_object (builder, info->source, info->line, info->col);
      if (source)
945
        g_object_bind_property (source, info->source_property,
946
                                info->target, info->target_pspec->name,
947 948 949 950 951 952 953 954 955
                                info->flags);

      free_binding_info (info, NULL);
    }

  g_slist_free (builder->priv->bindings);
  builder->priv->bindings = NULL;
}

956
void
957
_gtk_builder_finish (GtkBuilder *builder)
958
{
959
  gtk_builder_apply_delayed_properties (builder);
960
  gtk_builder_create_bindings (builder);
961 962 963 964 965
}

/**
 * gtk_builder_new:
 *
966 967
 * Creates a new empty builder object.
 *
968 969 970
 * This function is only useful if you intend to make multiple calls
 * to gtk_builder_add_from_file(), gtk_builder_add_from_resource()
 * or gtk_builder_add_from_string() in order to merge multiple UI
971
 * descriptions into a single builder.
972
 *
973 974 975
 * Most users will probably want to use gtk_builder_new_from_file(),
 * gtk_builder_new_from_resource() or gtk_builder_new_from_string().
 *
976
 * Returns: a new (empty) #GtkBuilder object
977 978 979 980 981 982 983 984 985 986 987 988 989
 *
 * 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
990
 * @error: (allow-none): return location for an error, or %NULL
991
 *
992 993
 * Parses a file containing a [GtkBuilder UI definition][BUILDER-UI]
 * and merges it with the current contents of @builder.
994 995
 *
 * Most users will probably want to use gtk_builder_new_from_file().
996
 *
997
 * If an error occurs, 0 will be returned and @error will be assigned a
Matthias Clasen's avatar
Matthias Clasen committed
998
 * #GError from the #GTK_BUILDER_ERROR, #G_MARKUP_ERROR or #G_FILE_ERROR
999 1000
 * domain.
 *
1001
 * It’s not really reasonable to attempt to handle failures of this
1002 1003
 * call. You should not use this function with untrusted files (ie:
 * files that are not part of your application). Broken #GtkBuilder
1004
 * files can easily crash your program, and it’s possible that memory
1005
 * was leaked leading up to the reported failure. The only reasonable
1006 1007
 * thing to do when an error is detected is to call g_error().
 *
1008 1009 1010 1011 1012 1013 1014 1015 1016
 * 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
1017
  gchar *buffer;
1018
  gsize length;
1019 1020 1021 1022
  GError *tmp_error;

  g_return_val_if_fail (GTK_IS_BUILDER (builder), 0);
  g_return_val_if_fail (filename != NULL, 0);
1023
  g_return_val_if_fail (error == NULL || *error == NULL, 0);
1024 1025 1026 1027 1028 1029 1030 1031

  tmp_error = NULL;

  if (!g_file_get_contents (filename, &buffer, &length, &tmp_error))
    {
      g_propagate_error (error, tmp_error);
      return 0;
    }
Matthias Clasen's avatar
Matthias Clasen committed
1032

1033
  g_free (builder->priv->filename);
1034
  g_free (builder->priv->resource_prefix);
1035
  builder->priv->filename = g_strdup (filename);
1036
  builder->priv->resource_prefix = NULL;
Matthias Clasen's avatar
Matthias Clasen committed
1037

1038 1039
  _gtk_builder_parser_parse_buffer (builder, filename,
                                    buffer, length,
1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057
                                    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
1058
 * @object_ids: (array zero-terminated=1) (element-type utf8): nul-terminated array of objects to build
1059
 * @error: (allow-none): return location for an error, or %NULL
1060
 *
1061 1062 1063
 * Parses a file containing a [GtkBuilder UI definition][BUILDER-UI]
 * building only the requested objects and merges
 * them with the current contents of @builder.
1064
 *
1065
 * Upon errors 0 will be returned and @error will be assigned a
Matthias Clasen's avatar
Matthias Clasen committed
1066
 * #GError from the #GTK_BUILDER_ERROR, #G_MARKUP_ERROR or #G_FILE_ERROR
1067 1068
 * domain.
 *
Matthias Clasen's avatar
Matthias Clasen committed
1069
 * If you are adding an object that depends on an object that is not
1070
 * its child (for instance a #GtkTreeView that depends on its
Matthias Clasen's avatar
Matthias Clasen committed
1071
 * #GtkTreeModel), you have to explicitly list all of them in @object_ids.
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
 *
 * 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;
    }
Matthias Clasen's avatar
Matthias Clasen committed
1099

1100
  g_free (builder->priv->filename);
1101
  g_free (builder->priv->resource_prefix);
1102
  builder->priv->filename = g_strdup (filename);
1103
  builder->priv->resource_prefix = NULL;
1104 1105 1106 1107

  _gtk_builder_parser_parse_buffer (builder, filename,
                                    buffer, length,
                                    object_ids,
1108 1109
                                    &tmp_error);

1110 1111
  g_free (buffer);

1112 1113 1114 1115 1116 1117 1118 1119 1120
  if (tmp_error != NULL)
    {
      g_propagate_error (error, tmp_error);
      return 0;
    }

  return 1;
}

1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131

/**
 * gtk_builder_extend_with_template:
 * @builder: a #GtkBuilder
 * @widget: the widget that is being extended
 * @template_type: the type that the template is for
 * @buffer: the string to parse
 * @length: the length of @buffer (may be -1 if @buffer is nul-terminated)
 * @error: (allow-none): return location for an error, or %NULL
 *
 * Main private entry point for building composite container
1132
 * components from template XML.
1133
 *
1134 1135
 * This is exported purely to let gtk-builder-tool validate
 * templates, applications have no need to call this function.
1136 1137
 *
 * Returns: A positive value on success, 0 if an error occurred
1138 1139
 */
guint
1140 1141 1142 1143 1144 1145
gtk_builder_extend_with_template (GtkBuilder   *builder,
                                  GtkWidget    *widget,
                                  GType         template_type,
                                  const gchar  *buffer,
                                  gsize         length,
                                  GError      **error)
1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177
{
  GError *tmp_error;

  g_return_val_if_fail (GTK_IS_BUILDER (builder), 0);
  g_return_val_if_fail (GTK_IS_WIDGET (widget), 0);
  g_return_val_if_fail (g_type_name (template_type) != NULL, 0);
  g_return_val_if_fail (g_type_is_a (G_OBJECT_TYPE (widget), template_type), 0);
  g_return_val_if_fail (buffer && buffer[0], 0);

  tmp_error = NULL;

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

  gtk_builder_expose_object (builder, g_type_name (template_type), G_OBJECT (widget));
  _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;
}

1178 1179 1180 1181 1182 1183
/**
 * 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
 *
1184 1185
 * Parses a resource file containing a [GtkBuilder UI definition][BUILDER-UI]
 * and merges it with the current contents of @builder.
1186
 *
1187 1188
 * Most users will probably want to use gtk_builder_new_from_resource().
 *
1189
 * If an error occurs, 0 will be returned and @error will be assigned a
1190 1191 1192
 * #GError from the #GTK_BUILDER_ERROR, #G_MARKUP_ERROR or #G_RESOURCE_ERROR
 * domain.
 *
1193
 * It’s not really reasonable to attempt to handle failures of this
1194 1195 1196
 * call.  The only reasonable thing to do when an error is detected is
 * to call g_error().
 *
1197 1198 1199 1200 1201 1202
 * Returns: A positive value on success, 0 if an error occurred
 *
 * Since: 3.4
 **/
guint
gtk_builder_add_from_resource (GtkBuilder   *builder,
Matthias Clasen's avatar
Matthias Clasen committed
1203 1204
                               const gchar  *resource_path,
                               GError      **error)
1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 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
{
  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
 *
1262 1263
 * Parses a resource file containing a [GtkBuilder UI definition][BUILDER-UI]
 * building only the requested objects and merges
1264 1265 1266 1267 1268 1269 1270 1271
 * 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.
 *
 * If you are adding an object that depends on an object that is not
 * its child (for instance a #GtkTreeView that depends on its
1272
 * #GtkTreeModel), you have to explicitly list all of them in @object_ids.
1273 1274 1275 1276 1277 1278 1279
 *
 * Returns: A positive value on success, 0 if an error occurred
 *
 * Since: 3.4
 **/
guint
gtk_builder_add_objects_from_resource (GtkBuilder   *builder,
Matthias Clasen's avatar
Matthias Clasen committed
1280 1281 1282
                                       const gchar  *resource_path,
                                       gchar       **object_ids,
                                       GError      **error)
1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332
{
  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;
}

1333 1334 1335 1336 1337
/**
 * 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)
1338
 * @error: (allow-none): return location for an error, or %NULL
1339
 *
1340 1341
 * Parses a string containing a [GtkBuilder UI definition][BUILDER-UI]
 * and merges it with the current contents of @builder.
1342
 *
1343 1344
 * Most users will probably want to use gtk_builder_new_from_string().
 *
1345
 * Upon errors 0 will be returned and @error will be assigned a
1346 1347
 * #GError from the #GTK_BUILDER_ERROR, #G_MARKUP_ERROR or
 * #G_VARIANT_PARSE_ERROR domain.
1348
 *
1349
 * It’s not really reasonable to attempt to handle failures of this
1350 1351 1352
 * call.  The only reasonable thing to do when an error is detected is
 * to call g_error().
 *
1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366
 * 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);
1367 1368 1369 1370 1371
  g_return_val_if_fail (error == NULL || *error == NULL, 0);

  tmp_error = NULL;

  g_free (builder->priv->filename);
1372
  g_free (builder->priv->resource_prefix);
1373
  builder->priv->filename = g_strdup (".");
1374
  builder->priv->resource_prefix = NULL;
1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393

  _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)
1394
 * @object_ids: (array zero-terminated=1) (element-type utf8): nul-terminated array of objects to build
1395
 * @error: (allow-none): return location for an error, or %NULL
1396
 *
1397 1398
 * Parses a string containing a [GtkBuilder UI definition][BUILDER-UI]
 * building only the requested objects and merges
Matthias Clasen's avatar
Matthias Clasen committed
1399
 * them with the current contents of @builder.
1400 1401 1402
 *
 * Upon errors 0 will be returned and @error will be assigned a
 * #GError from the #GTK_BUILDER_ERROR or #G_MARKUP_ERROR domain.
Matthias Clasen's avatar
Matthias Clasen committed
1403 1404
 *
 * If you are adding an object that depends on an object that is not
1405
 * its child (for instance a #GtkTreeView that depends on its
Matthias Clasen's avatar
Matthias Clasen committed
1406
 * #GtkTreeModel), you have to explicitly list all of them in @object_ids.
1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424
 *
 * 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);
1425 1426 1427

  tmp_error = NULL;

1428
  g_free (builder->priv->filename);
1429
  g_free (builder->priv->resource_prefix);
Matthias Clasen's avatar
Matthias Clasen committed
1430
  builder->priv->filename = g_strdup (".");
1431
  builder->priv->resource_prefix = NULL;
Matthias Clasen's avatar
Matthias Clasen committed
1432

1433 1434
  _gtk_builder_parser_parse_buffer (builder, "<input>",
                                    buffer, length,
1435
                                    object_ids,
1436
                                    &tmp_error);
1437

1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451
  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
1452
 * Gets the object named @name. Note that this function does not
Matthias Clasen's avatar
Matthias Clasen committed
1453
 * increment the reference count of the returned object.
Matthias Clasen's avatar
Matthias Clasen committed
1454
 *
1455
 * Returns: (nullable) (transfer none): the object named @name or %NULL if
1456
 *    it could not be found in the object tree.
1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473
 *
 * 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);
}

/**
 * gtk_builder_get_objects:
 * @builder: a #GtkBuilder
 *
Matthias Clasen's avatar
Matthias Clasen committed
1474
 * Gets all objects that have been constructed by @builder. Note that
Matthias Clasen's avatar
Matthias Clasen committed
1475 1476
 * this function does not increment the reference counts of the returned
 * objects.
Matthias Clasen's avatar
Matthias Clasen committed
1477
 *
1478
 * Returns: (element-type GObject) (transfer container): a newly-allocated #GSList containing all the objects
Matthias Clasen's avatar
Matthias Clasen committed
1479 1480
 *   constructed by the #GtkBuilder instance. It should be freed by
 *   g_slist_free()
1481 1482 1483 1484 1485 1486 1487
 *
 * Since: 2.12
 **/
GSList *
gtk_builder_get_objects (GtkBuilder *builder)
{
  GSList *objects = NULL;
1488 1489
  GObject *object;
  GHashTableIter iter;
1490 1491 1492

  g_return_val_if_fail (GTK_IS_BUILDER (builder), NULL);

1493 1494 1495
  g_hash_table_iter_init (&iter, builder->priv->objects);
  while (g_hash_table_iter_next (&iter, NULL, (gpointer *)&object))
    objects = g_slist_prepend (objects, object);
1496 1497 1498 1499 1500 1501 1502

  return g_slist_reverse (objects);
}

/**
 * gtk_builder_set_translation_domain:
 * @builder: a #GtkBuilder
1503
 * @domain: (allow-none): the translation domain or %NULL
1504
 *
Matthias Clasen's avatar
Matthias Clasen committed
1505
 * Sets the translation domain of @builder.
Matthias Clasen's avatar
Matthias Clasen committed
1506
 * See #GtkBuilder:translation-domain.
1507 1508 1509 1510 1511 1512 1513 1514
 *
 * Since: 2.12
 **/
void
gtk_builder_set_translation_domain (GtkBuilder  *builder,
                                    const gchar *domain)
{
  gchar *new_domain;
Matthias Clasen's avatar
Matthias Clasen committed
1515

1516 1517 1518 1519 1520 1521
  g_return_if_fail (GTK_IS_BUILDER (builder));

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

1522
  g_object_notify_by_pspec (G_OBJECT (builder), builder_props[PROP_TRANSLATION_DOMAIN]);
1523 1524 1525 1526 1527 1528
}

/**
 * gtk_builder_get_translation_domain:
 * @builder: a #GtkBuilder
 *
Matthias Clasen's avatar
Matthias Clasen committed
1529
 * Gets the translation domain of @builder.
Matthias Clasen's avatar
Matthias Clasen committed
1530
 *
1531
 * Returns: the translation domain. This string is owned
1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543
 * 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;
}

1544 1545 1546 1547 1548 1549 1550 1551
/**
 * gtk_builder_expose_object:
 * @builder: a #GtkBuilder
 * @name: the name of the object exposed to the builder
 * @object: the object to expose
 *
 * Add @object to the @builder object pool so it can be referenced just like any
 * other object built by builder.
Matthias Clasen's avatar
Matthias Clasen committed
1552
 *
1553 1554 1555 1556 1557 1558 1559 1560 1561
 * Since: 3.8
 **/
void
gtk_builder_expose_object (GtkBuilder    *builder,
                           const gchar   *name,
                           GObject       *object)
{
  g_return_if_fail (GTK_IS_BUILDER (builder));
  g_return_if_fail (name && name[0]);
1562
  g_return_if_fail (!g_hash_table_contains (builder->priv->objects, name));
1563 1564 1565 1566 1567 1568 1569 1570

  object_set_name (object, name);
  g_hash_table_insert (builder->priv->objects,
                       g_strdup (name),
                       g_object_ref (object));
}


1571 1572 1573
typedef struct {
  GModule *module;
  gpointer data;
Benjamin Otte's avatar
Benjamin Otte committed
1574
} ConnectArgs;
1575 1576 1577

static void
gtk_builder_connect_signals_default (GtkBuilder    *builder,
Matthias Clasen's avatar
Matthias Clasen committed
1578 1579 1580 1581 1582 1583
                                     GObject       *object,
                                     const gchar   *signal_name,
                                     const gchar   *handler_name,
                                     GObject       *connect_object,
                                     GConnectFlags  flags,
                                     gpointer       user_data)
1584 1585
{
  GCallback func;
Benjamin Otte's avatar
Benjamin Otte committed
1586
  ConnectArgs *args = (ConnectArgs*) user_data;
1587 1588 1589 1590

  func = gtk_builder_lookup_callback_symbol (builder, handler_name);

  if (!func)
1591
    {
1592 1593 1594 1595
      /* Only error out for missing GModule support if we've not
       * found the symbols explicitly added with gtk_builder_add_callback_symbol()
       */
      if (args->module == NULL)
Matthias Clasen's avatar
Matthias Clasen committed
1596 1597
        g_error ("gtk_builder_connect_signals() requires working GModule");

1598
      if (!g_module_symbol (args->module, handler_name, (gpointer)&func))
Matthias Clasen's avatar
Matthias Clasen committed
1599 1600 1601 1602
        {
          g_warning ("Could not find signal handler '%s'.  Did you compile with -rdynamic?", handler_name);
          return;
        }
1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614
    }

  if (connect_object)
    g_signal_connect_object (object, signal_name, func, connect_object, flags