]> Pileus Git - ~andy/gtk/blob - gtk/gtkbuilder.c
gtktreemodelfilter: fix small bug in prune level
[~andy/gtk] / gtk / gtkbuilder.c
1 /* GTK - The GIMP Toolkit
2  * Copyright (C) 1998-2002 James Henstridge <james@daa.com.au>
3  * Copyright (C) 2006-2007 Async Open Source,
4  *                         Johan Dahlin <jdahlin@async.com.br>,
5  *                         Henrique Romano <henrique@async.com.br>
6  *
7  * This library is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Library General Public
9  * License as published by the Free Software Foundation; either
10  * version 2 of the License, or (at your option) any later version.
11  *
12  * This library is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Library General Public License for more details.
16  *
17  * You should have received a copy of the GNU Library General Public
18  * License along with this library; if not, write to the
19  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
20  * Boston, MA 02111-1307, USA.
21  */
22
23 /**
24  * SECTION:gtkbuilder
25  * @Short_description: Build an interface from an XML UI definition
26  * @Title: GtkBuilder
27  *
28  * A GtkBuilder is an auxiliary object that reads textual descriptions
29  * of a user interface and instantiates the described objects. To pass a
30  * description to a GtkBuilder, call gtk_builder_add_from_file() or
31  * gtk_builder_add_from_string(). These functions can be called multiple
32  * times; the builder merges the content of all descriptions.
33  *
34  * A GtkBuilder holds a reference to all objects that it has constructed
35  * and drops these references when it is finalized. This finalization can
36  * cause the destruction of non-widget objects or widgets which are not
37  * contained in a toplevel window. For toplevel windows constructed by a
38  * builder, it is the responsibility of the user to call gtk_widget_destroy()
39  * to get rid of them and all the widgets they contain.
40  *
41  * The functions gtk_builder_get_object() and gtk_builder_get_objects()
42  * can be used to access the widgets in the interface by the names assigned
43  * to them inside the UI description. Toplevel windows returned by these
44  * functions will stay around until the user explicitly destroys them
45  * with gtk_widget_destroy(). Other widgets will either be part of a
46  * larger hierarchy constructed by the builder (in which case you should
47  * not have to worry about their lifecycle), or without a parent, in which
48  * case they have to be added to some container to make use of them.
49  * Non-widget objects need to be reffed with g_object_ref() to keep them
50  * beyond the lifespan of the builder.
51  *
52  * The function gtk_builder_connect_signals() and variants thereof can be
53  * used to connect handlers to the named signals in the description.
54  *
55  * <refsect2 id="BUILDER-UI">
56  * <title>GtkBuilder UI Definitions</title>
57  * <para>
58  * GtkBuilder parses textual descriptions of user interfaces which are specified
59  * in an XML format which can be roughly described by the DTD below. We refer to
60  * these descriptions as <firstterm>GtkBuilder UI definitions</firstterm> or
61  * just <firstterm>UI definitions</firstterm> if the context is clear. Do not
62  * confuse GtkBuilder UI Definitions with
63  * <link linkend="XML-UI">GtkUIManager UI Definitions</link>, which are more
64  * limited in scope.
65  * </para>
66  * <programlisting><![CDATA[
67  * <!ELEMENT interface (requires|object)* >
68  * <!ELEMENT object    (property|signal|child|ANY)* >
69  * <!ELEMENT property  PCDATA >
70  * <!ELEMENT signal    EMPTY >
71  * <!ELEMENT requires  EMPTY >
72  * <!ELEMENT child     (object|ANY*) >
73  *
74  * <!ATTLIST interface  domain              #IMPLIED >
75  * <!ATTLIST object     id                  #REQUIRED
76  *                      class               #REQUIRED
77  *                      type-func           #IMPLIED
78  *                      constructor         #IMPLIED >
79  * <!ATTLIST requires   lib                         #REQUIRED
80  *                      version                     #REQUIRED >
81  * <!ATTLIST property   name                #REQUIRED
82  *                      translatable        #IMPLIED
83  *                      comments               #IMPLIED
84  *                      context                #IMPLIED >
85  * <!ATTLIST signal     name                #REQUIRED
86  *                      handler             #REQUIRED
87  *                      after               #IMPLIED
88  *                      swapped             #IMPLIED
89  *                      object              #IMPLIED
90  *                      last_modification_time #IMPLIED >
91  * <!ATTLIST child      type                #IMPLIED
92  *                      internal-child      #IMPLIED >
93  * ]]></programlisting>
94  * <para>
95  * The toplevel element is &lt;interface&gt;. It optionally takes a "domain"
96  * attribute, which will make the builder look for translated strings using
97  * dgettext() in the domain specified. This can also be done by calling
98  * gtk_builder_set_translation_domain() on the builder. Objects are described by
99  * &lt;object&gt; elements, which can contain &lt;property&gt; elements to set
100  * properties, &lt;signal&gt; elements which connect signals to handlers, and
101  * &lt;child&gt; elements, which describe child objects (most often widgets
102  * inside a container, but also e.g. actions in an action group, or columns in a
103  * tree model). A &lt;child&gt; element contains an &lt;object&gt; element which
104  * describes the child object. The target toolkit version(s) are described by
105  * &lt;requires&gt; elements, the "lib" attribute specifies the widget library
106  * in question (currently the only supported value is "gtk+") and the "version"
107  * attribute specifies the target version in the form
108  * "&lt;major&gt;.&lt;minor&gt;". The builder will error out if the version
109  * requirements are not met.
110  *
111  * Typically, the specific kind of object represented by an &lt;object&gt;
112  * element is specified by the "class" attribute. If the type has not been
113  * loaded yet, GTK+ tries to find the <function>_get_type()</function> from the
114  * class name by applying heuristics. This works in most cases, but if
115  * necessary, it is possible to specify the name of the
116  * <function>_get_type()</function> explictly with the "type-func" attribute.
117  * As a special case, GtkBuilder allows to use an object that has been
118  * constructed by a #GtkUIManager in another part of the UI definition by
119  * specifying the id of the #GtkUIManager in the "constructor" attribute and the
120  * name of the object in the "id" attribute.
121  *
122  * Objects must be given a name with the "id" attribute, which allows the
123  * application to retrieve them from the builder with gtk_builder_get_object().
124  * An id is also necessary to use the object as property value in other parts of
125  * the UI definition.
126  * </para>
127  * <note><para>
128  * Prior to 2.20, GtkBuilder was setting the "name" property of constructed widgets to the
129  * "id" attribute. In GTK+ 2.20 or newer, you have to use gtk_buildable_get_name() instead
130  * of gtk_widget_get_name() to obtain the "id", or set the "name" property in your UI
131  * definition.
132  * </para></note>
133  * <para>
134  * Setting properties of objects is pretty straightforward with the
135  * &lt;property&gt; element: the "name" attribute specifies the name of the
136  * property, and the content of the element specifies the value. If the
137  * "translatable" attribute is set to a true value, GTK+ uses gettext() (or
138  * dgettext() if the builder has a translation domain set) to find a translation
139  * for the value. This happens before the value is parsed, so it can be used for
140  * properties of any type, but it is probably most useful for string properties.
141  * It is also possible to specify a context to disambiguate short strings, and
142  * comments which may help the translators.
143  *
144  * GtkBuilder can parse textual representations for the most common property
145  * types: characters, strings, integers, floating-point numbers, booleans
146  * (strings like "TRUE", "t", "yes", "y", "1" are interpreted as %TRUE, strings
147  * like "FALSE, "f", "no", "n", "0" are interpreted as %FALSE), enumerations
148  * (can be specified by their name, nick or integer value), flags (can be
149  * specified by their name, nick, integer value, optionally combined with "|",
150  * e.g. "GTK_VISIBLE|GTK_REALIZED")  and colors (in a format understood by
151  * gdk_color_parse()). Objects can be referred to by their name. Pixbufs can be
152  * specified as a filename of an image file to load. In general, GtkBuilder
153  * allows forward references to objects &mdash; an object doesn't have to be
154  * constructed before it can be referred to. The exception to this rule is that
155  * an object has to be constructed before it can be used as the value of a
156  * construct-only property.
157  *
158  * Signal handlers are set up with the &lt;signal&gt; element. The "name"
159  * attribute specifies the name of the signal, and the "handler" attribute
160  * specifies the function to connect to the signal. By default, GTK+ tries to
161  * find the handler using g_module_symbol(), but this can be changed by passing
162  * a custom #GtkBuilderConnectFunc to gtk_builder_connect_signals_full(). The
163  * remaining attributes, "after", "swapped" and "object", have the same meaning
164  * as the corresponding parameters of the g_signal_connect_object() or
165  * g_signal_connect_data() functions. A "last_modification_time" attribute
166  * is also allowed, but it does not have a meaning to the builder.
167  *
168  * Sometimes it is necessary to refer to widgets which have implicitly been
169  * constructed by GTK+ as part of a composite widget, to set properties on them
170  * or to add further children (e.g. the @vbox of a #GtkDialog). This can be
171  * achieved by setting the "internal-child" propery of the &lt;child&gt; element
172  * to a true value. Note that GtkBuilder still requires an &lt;object&gt;
173  * element for the internal child, even if it has already been constructed.
174  *
175  * A number of widgets have different places where a child can be added (e.g.
176  * tabs vs. page content in notebooks). This can be reflected in a UI definition
177  * by specifying the "type" attribute on a &lt;child&gt;. The possible values
178  * for the "type" attribute are described in the sections describing the
179  * widget-specific portions of UI definitions.
180  * </para>
181  * <example>
182  * <title>A GtkBuilder UI Definition</title>
183  * <programlisting><![CDATA[
184  * <interface>
185  *   <object class="GtkDialog" id="dialog1">
186  *     <child internal-child="vbox">
187  *       <object class="GtkVBox" id="vbox1">
188  *         <property name="border-width">10</property>
189  *         <child internal-child="action_area">
190  *           <object class="GtkHButtonBox" id="hbuttonbox1">
191  *             <property name="border-width">20</property>
192  *             <child>
193  *               <object class="GtkButton" id="ok_button">
194  *                 <property name="label">gtk-ok</property>
195  *                 <property name="use-stock">TRUE</property>
196  *                 <signal name="clicked" handler="ok_button_clicked"/>
197  *               </object>
198  *             </child>
199  *           </object>
200  *         </child>
201  *       </object>
202  *     </child>
203  *   </object>
204  * </interface>
205  * ]]></programlisting>
206  * </example>
207  * <para>
208  * Beyond this general structure, several object classes define their own XML
209  * DTD fragments for filling in the ANY placeholders in the DTD above. Note that
210  * a custom element in a &lt;child&gt; element gets parsed by the custom tag
211  * handler of the parent object, while a custom element in an &lt;object&gt;
212  * element gets parsed by the custom tag handler of the object.
213  *
214  * These XML fragments are explained in the documentation of the respective
215  * objects, see
216  * <link linkend="GtkWidget-BUILDER-UI">GtkWidget</link>,
217  * <link linkend="GtkLabel-BUILDER-UI">GtkLabel</link>,
218  * <link linkend="GtkWindow-BUILDER-UI">GtkWindow</link>,
219  * <link linkend="GtkContainer-BUILDER-UI">GtkContainer</link>,
220  * <link linkend="GtkDialog-BUILDER-UI">GtkDialog</link>,
221  * <link linkend="GtkCellLayout-BUILDER-UI">GtkCellLayout</link>,
222  * <link linkend="GtkColorSelectionDialog-BUILDER-UI">GtkColorSelectionDialog</link>,
223  * <link linkend="GtkFontSelectionDialog-BUILDER-UI">GtkFontSelectionDialog</link>,
224  * <link linkend="GtkExpander-BUILDER-UI">GtkExpander</link>,
225  * <link linkend="GtkFrame-BUILDER-UI">GtkFrame</link>,
226  * <link linkend="GtkListStore-BUILDER-UI">GtkListStore</link>,
227  * <link linkend="GtkTreeStore-BUILDER-UI">GtkTreeStore</link>,
228  * <link linkend="GtkNotebook-BUILDER-UI">GtkNotebook</link>,
229  * <link linkend="GtkSizeGroup-BUILDER-UI">GtkSizeGroup</link>,
230  * <link linkend="GtkTreeView-BUILDER-UI">GtkTreeView</link>,
231  * <link linkend="GtkUIManager-BUILDER-UI">GtkUIManager</link>,
232  * <link linkend="GtkActionGroup-BUILDER-UI">GtkActionGroup</link>.
233  * <link linkend="GtkMenuItem-BUILDER-UI">GtkMenuItem</link>,
234  * <link linkend="GtkMenuToolButton-BUILDER-UI">GtkMenuToolButton</link>,
235  * <link linkend="GtkAssistant-BUILDER-UI">GtkAssistant</link>,
236  * <link linkend="GtkScale-BUILDER-UI">GtkScale</link>,
237  * <link linkend="GtkComboBoxText-BUILDER-UI">GtkComboBoxText</link>,
238  * <link linkend="GtkRecentFilter-BUILDER-UI">GtkRecentFilter</link>,
239  * <link linkend="GtkFileFilter-BUILDER-UI">GtkFileFilter</link>,
240  * <link linkend="GtkTextTagTable-BUILDER-UI">GtkTextTagTable</link>.
241  * </para>
242  * </refsect2>
243  */
244
245 #include "config.h"
246 #include <errno.h> /* errno */
247 #include <stdlib.h>
248 #include <string.h> /* strlen */
249
250 #include "gtkbuilder.h"
251 #include "gtkbuildable.h"
252 #include "gtkbuilderprivate.h"
253 #include "gtkdebug.h"
254 #include "gtkmain.h"
255 #include "gtkintl.h"
256 #include "gtkprivate.h"
257 #include "gtktypebuiltins.h"
258 #include "gtkwindow.h"
259 #include "gtkicontheme.h"
260 #include "gtkstock.h"
261
262
263 static void gtk_builder_class_init     (GtkBuilderClass *klass);
264 static void gtk_builder_init           (GtkBuilder      *builder);
265 static void gtk_builder_finalize       (GObject         *object);
266 static void gtk_builder_set_property   (GObject         *object,
267                                         guint            prop_id,
268                                         const GValue    *value,
269                                         GParamSpec      *pspec);
270 static void gtk_builder_get_property   (GObject         *object,
271                                         guint            prop_id,
272                                         GValue          *value,
273                                         GParamSpec      *pspec);
274 static GType gtk_builder_real_get_type_from_name (GtkBuilder  *builder,
275                                                   const gchar *type_name);
276
277 enum {
278   PROP_0,
279   PROP_TRANSLATION_DOMAIN,
280 };
281
282 struct _GtkBuilderPrivate
283 {
284   gchar *domain;
285   GHashTable *objects;
286   GSList *delayed_properties;
287   GSList *signals;
288   gchar *filename;
289 };
290
291 G_DEFINE_TYPE (GtkBuilder, gtk_builder, G_TYPE_OBJECT)
292
293 static void
294 gtk_builder_class_init (GtkBuilderClass *klass)
295 {
296   GObjectClass *gobject_class;
297
298   gobject_class = G_OBJECT_CLASS (klass);
299
300   gobject_class->finalize = gtk_builder_finalize;
301   gobject_class->set_property = gtk_builder_set_property;
302   gobject_class->get_property = gtk_builder_get_property;
303
304   klass->get_type_from_name = gtk_builder_real_get_type_from_name;
305
306  /** 
307   * GtkBuilder:translation-domain:
308   *
309   * The translation domain used when translating property values that
310   * have been marked as translatable in interface descriptions.
311   * If the translation domain is %NULL, #GtkBuilder uses gettext(),
312   * otherwise g_dgettext().
313   *
314   * Since: 2.12
315   */
316   g_object_class_install_property (gobject_class,
317                                    PROP_TRANSLATION_DOMAIN,
318                                    g_param_spec_string ("translation-domain",
319                                                         P_("Translation Domain"),
320                                                         P_("The translation domain used by gettext"),
321                                                         NULL,
322                                                         GTK_PARAM_READWRITE));
323
324   g_type_class_add_private (gobject_class, sizeof (GtkBuilderPrivate));
325 }
326
327 static void
328 gtk_builder_init (GtkBuilder *builder)
329 {
330   builder->priv = G_TYPE_INSTANCE_GET_PRIVATE (builder, GTK_TYPE_BUILDER,
331                                                GtkBuilderPrivate);
332   builder->priv->domain = NULL;
333   builder->priv->objects = g_hash_table_new_full (g_str_hash, g_str_equal,
334                                                   g_free, g_object_unref);
335 }
336
337
338 /*
339  * GObject virtual methods
340  */
341
342 static void
343 gtk_builder_finalize (GObject *object)
344 {
345   GtkBuilderPrivate *priv = GTK_BUILDER (object)->priv;
346   
347   g_free (priv->domain);
348   g_free (priv->filename);
349   
350   g_hash_table_destroy (priv->objects);
351
352   g_slist_foreach (priv->signals, (GFunc) _free_signal_info, NULL);
353   g_slist_free (priv->signals);
354   
355   G_OBJECT_CLASS (gtk_builder_parent_class)->finalize (object);
356 }
357
358 static void
359 gtk_builder_set_property (GObject      *object,
360                           guint         prop_id,
361                           const GValue *value,
362                           GParamSpec   *pspec)
363 {
364   GtkBuilder *builder = GTK_BUILDER (object);
365
366   switch (prop_id)
367     {
368     case PROP_TRANSLATION_DOMAIN:
369       gtk_builder_set_translation_domain (builder, g_value_get_string (value));
370       break;
371     default:
372       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
373       break;
374     }
375 }
376
377 static void
378 gtk_builder_get_property (GObject    *object,
379                           guint       prop_id,
380                           GValue     *value,
381                           GParamSpec *pspec)
382 {
383   GtkBuilder *builder = GTK_BUILDER (object);
384
385   switch (prop_id)
386     {
387     case PROP_TRANSLATION_DOMAIN:
388       g_value_set_string (value, builder->priv->domain);
389       break;
390     default:
391       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
392       break;
393     }
394 }
395
396
397 /*
398  * Try to map a type name to a _get_type function
399  * and call it, eg:
400  *
401  * GtkWindow -> gtk_window_get_type
402  * GtkHBox -> gtk_hbox_get_type
403  * GtkUIManager -> gtk_ui_manager_get_type
404  *
405  */
406 static GType
407 _gtk_builder_resolve_type_lazily (const gchar *name)
408 {
409   static GModule *module = NULL;
410   GTypeGetFunc func;
411   GString *symbol_name = g_string_new ("");
412   char c, *symbol;
413   int i;
414   GType gtype = G_TYPE_INVALID;
415
416   if (!module)
417     module = g_module_open (NULL, 0);
418   
419   for (i = 0; name[i] != '\0'; i++)
420     {
421       c = name[i];
422       /* skip if uppercase, first or previous is uppercase */
423       if ((c == g_ascii_toupper (c) &&
424            i > 0 && name[i-1] != g_ascii_toupper (name[i-1])) ||
425           (i > 2 && name[i]   == g_ascii_toupper (name[i]) &&
426            name[i-1] == g_ascii_toupper (name[i-1]) &&
427            name[i-2] == g_ascii_toupper (name[i-2])))
428         g_string_append_c (symbol_name, '_');
429       g_string_append_c (symbol_name, g_ascii_tolower (c));
430     }
431   g_string_append (symbol_name, "_get_type");
432   
433   symbol = g_string_free (symbol_name, FALSE);
434
435   if (g_module_symbol (module, symbol, (gpointer)&func))
436     gtype = func ();
437   
438   g_free (symbol);
439
440   return gtype;
441 }
442
443 /*
444  * GtkBuilder virtual methods
445  */
446
447 static GType
448 gtk_builder_real_get_type_from_name (GtkBuilder  *builder, 
449                                      const gchar *type_name)
450 {
451   GType gtype;
452
453   gtype = g_type_from_name (type_name);
454   if (gtype != G_TYPE_INVALID)
455     return gtype;
456
457   return _gtk_builder_resolve_type_lazily (type_name);
458 }
459
460 typedef struct
461 {
462   gchar *object;
463   gchar *name;
464   gchar *value;
465 } DelayedProperty;
466
467 static void
468 gtk_builder_get_parameters (GtkBuilder  *builder,
469                             GType        object_type,
470                             const gchar *object_name,
471                             GSList      *properties,
472                             GArray      **parameters,
473                             GArray      **construct_parameters)
474 {
475   GSList *l;
476   GParamSpec *pspec;
477   GObjectClass *oclass;
478   DelayedProperty *property;
479   GError *error = NULL;
480   
481   oclass = g_type_class_ref (object_type);
482   g_assert (oclass != NULL);
483
484   *parameters = g_array_new (FALSE, FALSE, sizeof (GParameter));
485   *construct_parameters = g_array_new (FALSE, FALSE, sizeof (GParameter));
486
487   for (l = properties; l; l = l->next)
488     {
489       PropertyInfo *prop = (PropertyInfo*)l->data;
490       GParameter parameter = { NULL };
491
492       pspec = g_object_class_find_property (G_OBJECT_CLASS (oclass),
493                                             prop->name);
494       if (!pspec)
495         {
496           g_warning ("Unknown property: %s.%s",
497                      g_type_name (object_type), prop->name);
498           continue;
499         }
500
501       parameter.name = prop->name;
502
503       if (G_IS_PARAM_SPEC_OBJECT (pspec) &&
504           (G_PARAM_SPEC_VALUE_TYPE (pspec) != GDK_TYPE_PIXBUF))
505         {
506           GObject *object = gtk_builder_get_object (builder, prop->data);
507
508           if (object)
509             {
510               g_value_init (&parameter.value, G_OBJECT_TYPE (object));
511               g_value_set_object (&parameter.value, object);
512             }
513           else 
514             {
515               if (pspec->flags & G_PARAM_CONSTRUCT_ONLY)
516                 {
517                   g_warning ("Failed to get constuct only property "
518                              "%s of %s with value `%s'",
519                              prop->name, object_name, prop->data);
520                   continue;
521                 }
522               /* Delay setting property */
523               property = g_slice_new (DelayedProperty);
524               property->object = g_strdup (object_name);
525               property->name = g_strdup (prop->name);
526               property->value = g_strdup (prop->data);
527               builder->priv->delayed_properties =
528                 g_slist_prepend (builder->priv->delayed_properties, property);
529               continue;
530             }
531         }
532       else if (!gtk_builder_value_from_string (builder, pspec,
533                                                prop->data, &parameter.value, &error))
534         {
535           g_warning ("Failed to set property %s.%s to %s: %s",
536                      g_type_name (object_type), prop->name, prop->data,
537                      error->message);
538           g_error_free (error);
539           error = NULL;
540           continue;
541         }
542
543       if (pspec->flags & (G_PARAM_CONSTRUCT | G_PARAM_CONSTRUCT_ONLY))
544         g_array_append_val (*construct_parameters, parameter);
545       else
546         g_array_append_val (*parameters, parameter);
547     }
548
549   g_type_class_unref (oclass);
550 }
551
552 static GObject *
553 gtk_builder_get_internal_child (GtkBuilder  *builder,
554                                 ObjectInfo  *info,
555                                 const gchar *childname,
556                                 GError      **error)
557 {
558   GObject *obj = NULL;
559
560   while (!obj)
561     {
562       if (!info->parent)
563         break;
564
565       info = (ObjectInfo*)((ChildInfo*)info->parent)->parent;
566       if (!info)
567         break;
568
569       GTK_NOTE (BUILDER,
570                 g_print ("Trying to get internal child %s from %s\n",
571                          childname,
572                          gtk_buildable_get_name (GTK_BUILDABLE (info->object))));
573
574       if (GTK_IS_BUILDABLE (info->object))
575           obj = gtk_buildable_get_internal_child (GTK_BUILDABLE (info->object),
576                                                   builder,
577                                                   childname);
578     };
579
580   if (!obj)
581     {
582       g_set_error (error,
583                    GTK_BUILDER_ERROR,
584                    GTK_BUILDER_ERROR_INVALID_VALUE,
585                    "Unknown internal child: %s", childname);
586     }
587   return obj;
588 }
589
590 GObject *
591 _gtk_builder_construct (GtkBuilder *builder,
592                         ObjectInfo *info,
593                         GError **error)
594 {
595   GArray *parameters, *construct_parameters;
596   GType object_type;
597   GObject *obj;
598   int i;
599   GtkBuildableIface *iface;
600   gboolean custom_set_property;
601   GtkBuildable *buildable;
602
603   g_assert (info->class_name != NULL);
604   object_type = gtk_builder_get_type_from_name (builder, info->class_name);
605   if (object_type == G_TYPE_INVALID)
606     {
607       g_set_error (error,
608                    GTK_BUILDER_ERROR,
609                    GTK_BUILDER_ERROR_INVALID_VALUE,
610                    "Invalid object type `%s'",
611                    info->class_name);
612       return NULL;
613     }
614
615   gtk_builder_get_parameters (builder, object_type,
616                               info->id,
617                               info->properties,
618                               &parameters,
619                               &construct_parameters);
620
621   if (info->constructor)
622     {
623       GObject *constructor;
624
625       constructor = gtk_builder_get_object (builder, info->constructor);
626       if (constructor == NULL)
627         {
628           g_set_error (error,
629                        GTK_BUILDER_ERROR,
630                        GTK_BUILDER_ERROR_INVALID_VALUE,
631                        "Unknown object constructor for %s: %s",
632                        info->id,
633                        info->constructor);
634           g_array_free (parameters, TRUE);
635           g_array_free (construct_parameters, TRUE);
636           return NULL;
637         }
638       obj = gtk_buildable_construct_child (GTK_BUILDABLE (constructor),
639                                            builder,
640                                            info->id);
641       g_assert (obj != NULL);
642       if (construct_parameters->len)
643         g_warning ("Can't pass in construct-only parameters to %s", info->id);
644     }
645   else if (info->parent && ((ChildInfo*)info->parent)->internal_child != NULL)
646     {
647       gchar *childname = ((ChildInfo*)info->parent)->internal_child;
648       obj = gtk_builder_get_internal_child (builder, info, childname, error);
649       if (!obj)
650         {
651           g_array_free (parameters, TRUE);
652           g_array_free (construct_parameters, TRUE);
653           return NULL;
654         }
655       if (construct_parameters->len)
656         g_warning ("Can't pass in construct-only parameters to %s", childname);
657       g_object_ref (obj);
658     }
659   else
660     {
661       obj = g_object_newv (object_type,
662                            construct_parameters->len,
663                            (GParameter *)construct_parameters->data);
664
665       /* No matter what, make sure we have a reference.
666        *
667        * If it's an initially unowned object, sink it.
668        * If it's not initially unowned then we have the reference already.
669        *
670        * In the case that this is a window it will be sunk already and
671        * this is effectively a call to g_object_ref().  That's what
672        * we want.
673        */
674       if (G_IS_INITIALLY_UNOWNED (obj))
675         g_object_ref_sink (obj);
676
677       GTK_NOTE (BUILDER,
678                 g_print ("created %s of type %s\n", info->id, info->class_name));
679
680       for (i = 0; i < construct_parameters->len; i++)
681         {
682           GParameter *param = &g_array_index (construct_parameters,
683                                               GParameter, i);
684           g_value_unset (&param->value);
685         }
686     }
687   g_array_free (construct_parameters, TRUE);
688
689   custom_set_property = FALSE;
690   buildable = NULL;
691   iface = NULL;
692   if (GTK_IS_BUILDABLE (obj))
693     {
694       buildable = GTK_BUILDABLE (obj);
695       iface = GTK_BUILDABLE_GET_IFACE (obj);
696       if (iface->set_buildable_property)
697         custom_set_property = TRUE;
698     }
699
700   for (i = 0; i < parameters->len; i++)
701     {
702       GParameter *param = &g_array_index (parameters, GParameter, i);
703       if (custom_set_property)
704         iface->set_buildable_property (buildable, builder, param->name, &param->value);
705       else
706         g_object_set_property (obj, param->name, &param->value);
707
708 #if G_ENABLE_DEBUG
709       if (gtk_get_debug_flags () & GTK_DEBUG_BUILDER)
710         {
711           gchar *str = g_strdup_value_contents ((const GValue*)&param->value);
712           g_print ("set %s: %s = %s\n", info->id, param->name, str);
713           g_free (str);
714         }
715 #endif      
716       g_value_unset (&param->value);
717     }
718   g_array_free (parameters, TRUE);
719   
720   if (GTK_IS_BUILDABLE (obj))
721     gtk_buildable_set_name (buildable, info->id);
722   else
723     g_object_set_data_full (obj,
724                             "gtk-builder-name",
725                             g_strdup (info->id),
726                             g_free);
727
728   /* we already own a reference to obj.  put it in the hash table. */
729   g_hash_table_insert (builder->priv->objects, g_strdup (info->id), obj);
730   
731   return obj;
732 }
733
734
735 void
736 _gtk_builder_add (GtkBuilder *builder,
737                   ChildInfo  *child_info)
738 {
739   GObject *object;
740   GObject *parent;
741
742   /* Internal children are already added
743    * Also prevent us from being called twice.
744    */
745   if (!child_info ||
746       child_info->internal_child ||
747       child_info->added)
748     return;
749
750   object = child_info->object;
751   if (!object)
752     return;
753
754   if (!child_info->parent)
755     {
756       g_warning ("%s: Not adding, No parent",
757                  gtk_buildable_get_name (GTK_BUILDABLE (object)));
758       return;
759     }
760
761   g_assert (object != NULL);
762
763   parent = ((ObjectInfo*)child_info->parent)->object;
764   g_assert (GTK_IS_BUILDABLE (parent));
765
766   GTK_NOTE (BUILDER,
767             g_print ("adding %s to %s\n",
768                      gtk_buildable_get_name (GTK_BUILDABLE (object)),
769                      gtk_buildable_get_name (GTK_BUILDABLE (parent))));
770   
771   gtk_buildable_add_child (GTK_BUILDABLE (parent), builder, object,
772                            child_info->type);
773
774   child_info->added = TRUE;
775 }
776
777 void
778 _gtk_builder_add_signals (GtkBuilder *builder,
779                           GSList     *signals)
780 {
781   builder->priv->signals = g_slist_concat (builder->priv->signals,
782                                            g_slist_copy (signals));
783 }
784
785 static void
786 gtk_builder_apply_delayed_properties (GtkBuilder *builder)
787 {
788   GSList *l, *props;
789   DelayedProperty *property;
790   GObject *object;
791   GType object_type;
792   GObjectClass *oclass;
793   GParamSpec *pspec;
794
795   /* take the list over from the builder->priv.
796    *
797    * g_slist_reverse does not copy the list, so the list now
798    * belongs to us (and we free it at the end of this function).
799    */
800   props = g_slist_reverse (builder->priv->delayed_properties);
801   builder->priv->delayed_properties = NULL;
802
803   for (l = props; l; l = l->next)
804     {
805       property = (DelayedProperty*)l->data;
806       object = g_hash_table_lookup (builder->priv->objects, property->object);
807       g_assert (object != NULL);
808
809       object_type = G_OBJECT_TYPE (object);
810       g_assert (object_type != G_TYPE_INVALID);
811
812       oclass = g_type_class_ref (object_type);
813       g_assert (oclass != NULL);
814
815       pspec = g_object_class_find_property (G_OBJECT_CLASS (oclass),
816                                             property->name);
817       if (!pspec)
818         g_warning ("Unknown property: %s.%s", g_type_name (object_type),
819                    property->name);
820       else
821         {
822           GObject *obj;
823
824           obj = g_hash_table_lookup (builder->priv->objects, property->value);
825           if (!obj)
826             g_warning ("No object called: %s", property->value);
827           else
828             g_object_set (object, property->name, obj, NULL);
829         }
830       g_free (property->value);
831       g_free (property->object);
832       g_free (property->name);
833       g_slice_free (DelayedProperty, property);
834       g_type_class_unref (oclass);
835     }
836   g_slist_free (props);
837 }
838
839 void
840 _gtk_builder_finish (GtkBuilder *builder)
841 {
842   gtk_builder_apply_delayed_properties (builder);
843 }
844
845 /**
846  * gtk_builder_new:
847  *
848  * Creates a new builder object.
849  *
850  * Return value: a new #GtkBuilder object
851  *
852  * Since: 2.12
853  **/
854 GtkBuilder *
855 gtk_builder_new (void)
856 {
857   return g_object_new (GTK_TYPE_BUILDER, NULL);
858 }
859
860 /**
861  * gtk_builder_add_from_file:
862  * @builder: a #GtkBuilder
863  * @filename: the name of the file to parse
864  * @error: (allow-none): return location for an error, or %NULL
865  *
866  * Parses a file containing a <link linkend="BUILDER-UI">GtkBuilder 
867  * UI definition</link> and merges it with the current contents of @builder. 
868  * 
869  * Upon errors 0 will be returned and @error will be assigned a
870  * #GError from the #GTK_BUILDER_ERROR, #G_MARKUP_ERROR or #G_FILE_ERROR 
871  * domain.
872  *
873  * Returns: A positive value on success, 0 if an error occurred
874  *
875  * Since: 2.12
876  **/
877 guint
878 gtk_builder_add_from_file (GtkBuilder   *builder,
879                            const gchar  *filename,
880                            GError      **error)
881 {
882   gchar *buffer;
883   gsize length;
884   GError *tmp_error;
885
886   g_return_val_if_fail (GTK_IS_BUILDER (builder), 0);
887   g_return_val_if_fail (filename != NULL, 0);
888   g_return_val_if_fail (error == NULL || *error == NULL, 0);
889
890   tmp_error = NULL;
891
892   if (!g_file_get_contents (filename, &buffer, &length, &tmp_error))
893     {
894       g_propagate_error (error, tmp_error);
895       return 0;
896     }
897   
898   g_free (builder->priv->filename);
899   builder->priv->filename = g_strdup (filename);
900
901   _gtk_builder_parser_parse_buffer (builder, filename,
902                                     buffer, length,
903                                     NULL,
904                                     &tmp_error);
905
906   g_free (buffer);
907
908   if (tmp_error != NULL)
909     {
910       g_propagate_error (error, tmp_error);
911       return 0;
912     }
913
914   return 1;
915 }
916
917 /**
918  * gtk_builder_add_objects_from_file:
919  * @builder: a #GtkBuilder
920  * @filename: the name of the file to parse
921  * @object_ids: (array zero-terminated=1) (element-type utf8): nul-terminated array of objects to build
922  * @error: (allow-none): return location for an error, or %NULL
923  *
924  * Parses a file containing a <link linkend="BUILDER-UI">GtkBuilder 
925  * UI definition</link> building only the requested objects and merges
926  * them with the current contents of @builder. 
927  *
928  * Upon errors 0 will be returned and @error will be assigned a
929  * #GError from the #GTK_BUILDER_ERROR, #G_MARKUP_ERROR or #G_FILE_ERROR 
930  * domain.
931  *
932  * <note><para>
933  * If you are adding an object that depends on an object that is not 
934  * its child (for instance a #GtkTreeView that depends on its
935  * #GtkTreeModel), you have to explicitely list all of them in @object_ids. 
936  * </para></note>
937  *
938  * Returns: A positive value on success, 0 if an error occurred
939  *
940  * Since: 2.14
941  **/
942 guint
943 gtk_builder_add_objects_from_file (GtkBuilder   *builder,
944                                    const gchar  *filename,
945                                    gchar       **object_ids,
946                                    GError      **error)
947 {
948   gchar *buffer;
949   gsize length;
950   GError *tmp_error;
951
952   g_return_val_if_fail (GTK_IS_BUILDER (builder), 0);
953   g_return_val_if_fail (filename != NULL, 0);
954   g_return_val_if_fail (object_ids != NULL && object_ids[0] != NULL, 0);
955   g_return_val_if_fail (error == NULL || *error == NULL, 0);
956
957   tmp_error = NULL;
958
959   if (!g_file_get_contents (filename, &buffer, &length, &tmp_error))
960     {
961       g_propagate_error (error, tmp_error);
962       return 0;
963     }
964   
965   g_free (builder->priv->filename);
966   builder->priv->filename = g_strdup (filename);
967
968   _gtk_builder_parser_parse_buffer (builder, filename,
969                                     buffer, length,
970                                     object_ids,
971                                     &tmp_error);
972
973   g_free (buffer);
974
975   if (tmp_error != NULL)
976     {
977       g_propagate_error (error, tmp_error);
978       return 0;
979     }
980
981   return 1;
982 }
983
984 /**
985  * gtk_builder_add_from_string:
986  * @builder: a #GtkBuilder
987  * @buffer: the string to parse
988  * @length: the length of @buffer (may be -1 if @buffer is nul-terminated)
989  * @error: (allow-none): return location for an error, or %NULL
990  *
991  * Parses a string containing a <link linkend="BUILDER-UI">GtkBuilder 
992  * UI definition</link> and merges it with the current contents of @builder. 
993  *
994  * Upon errors 0 will be returned and @error will be assigned a
995  * #GError from the #GTK_BUILDER_ERROR or #G_MARKUP_ERROR domain.
996  *
997  * Returns: A positive value on success, 0 if an error occurred
998  *
999  * Since: 2.12
1000  **/
1001 guint
1002 gtk_builder_add_from_string (GtkBuilder   *builder,
1003                              const gchar  *buffer,
1004                              gsize         length,
1005                              GError      **error)
1006 {
1007   GError *tmp_error;
1008
1009   g_return_val_if_fail (GTK_IS_BUILDER (builder), 0);
1010   g_return_val_if_fail (buffer != NULL, 0);
1011   g_return_val_if_fail (error == NULL || *error == NULL, 0);
1012
1013   tmp_error = NULL;
1014
1015   g_free (builder->priv->filename);
1016   builder->priv->filename = g_strdup (".");
1017
1018   _gtk_builder_parser_parse_buffer (builder, "<input>",
1019                                     buffer, length,
1020                                     NULL,
1021                                     &tmp_error);
1022   if (tmp_error != NULL)
1023     {
1024       g_propagate_error (error, tmp_error);
1025       return 0;
1026     }
1027
1028   return 1;
1029 }
1030
1031 /**
1032  * gtk_builder_add_objects_from_string:
1033  * @builder: a #GtkBuilder
1034  * @buffer: the string to parse
1035  * @length: the length of @buffer (may be -1 if @buffer is nul-terminated)
1036  * @object_ids: (array zero-terminated=1) (element-type utf8): nul-terminated array of objects to build
1037  * @error: (allow-none): return location for an error, or %NULL
1038  *
1039  * Parses a string containing a <link linkend="BUILDER-UI">GtkBuilder 
1040  * UI definition</link> building only the requested objects and merges
1041  * them with the current contents of @builder. 
1042  *
1043  * Upon errors 0 will be returned and @error will be assigned a
1044  * #GError from the #GTK_BUILDER_ERROR or #G_MARKUP_ERROR domain.
1045  * 
1046  * <note><para>
1047  * If you are adding an object that depends on an object that is not 
1048  * its child (for instance a #GtkTreeView that depends on its
1049  * #GtkTreeModel), you have to explicitely list all of them in @object_ids. 
1050  * </para></note>
1051  *
1052  * Returns: A positive value on success, 0 if an error occurred
1053  *
1054  * Since: 2.14
1055  **/
1056 guint
1057 gtk_builder_add_objects_from_string (GtkBuilder   *builder,
1058                                      const gchar  *buffer,
1059                                      gsize         length,
1060                                      gchar       **object_ids,
1061                                      GError      **error)
1062 {
1063   GError *tmp_error;
1064
1065   g_return_val_if_fail (GTK_IS_BUILDER (builder), 0);
1066   g_return_val_if_fail (buffer != NULL, 0);
1067   g_return_val_if_fail (object_ids != NULL && object_ids[0] != NULL, 0);
1068   g_return_val_if_fail (error == NULL || *error == NULL, 0);
1069
1070   tmp_error = NULL;
1071
1072   g_free (builder->priv->filename);
1073   builder->priv->filename = g_strdup (".");
1074
1075   _gtk_builder_parser_parse_buffer (builder, "<input>",
1076                                     buffer, length,
1077                                     object_ids,
1078                                     &tmp_error);
1079
1080   if (tmp_error != NULL)
1081     {
1082       g_propagate_error (error, tmp_error);
1083       return 0;
1084     }
1085
1086   return 1;
1087 }
1088
1089 /**
1090  * gtk_builder_get_object:
1091  * @builder: a #GtkBuilder
1092  * @name: name of object to get
1093  *
1094  * Gets the object named @name. Note that this function does not
1095  * increment the reference count of the returned object. 
1096  *
1097  * Return value: (transfer none): the object named @name or %NULL if
1098  *    it could not be found in the object tree.
1099  *
1100  * Since: 2.12
1101  **/
1102 GObject *
1103 gtk_builder_get_object (GtkBuilder  *builder,
1104                         const gchar *name)
1105 {
1106   g_return_val_if_fail (GTK_IS_BUILDER (builder), NULL);
1107   g_return_val_if_fail (name != NULL, NULL);
1108
1109   return g_hash_table_lookup (builder->priv->objects, name);
1110 }
1111
1112 static void
1113 object_add_to_list (gchar    *object_id,
1114                     GObject  *object,
1115                     GSList  **list)
1116 {
1117   *list = g_slist_prepend (*list, object);
1118 }
1119
1120 /**
1121  * gtk_builder_get_objects:
1122  * @builder: a #GtkBuilder
1123  *
1124  * Gets all objects that have been constructed by @builder. Note that 
1125  * this function does not increment the reference counts of the returned
1126  * objects.
1127  *
1128  * Return value: (element-type GObject) (transfer container): a newly-allocated #GSList containing all the objects
1129  *   constructed by the #GtkBuilder instance. It should be freed by
1130  *   g_slist_free()
1131  *
1132  * Since: 2.12
1133  **/
1134 GSList *
1135 gtk_builder_get_objects (GtkBuilder *builder)
1136 {
1137   GSList *objects = NULL;
1138
1139   g_return_val_if_fail (GTK_IS_BUILDER (builder), NULL);
1140
1141   g_hash_table_foreach (builder->priv->objects, (GHFunc)object_add_to_list, &objects);
1142
1143   return g_slist_reverse (objects);
1144 }
1145
1146 /**
1147  * gtk_builder_set_translation_domain:
1148  * @builder: a #GtkBuilder
1149  * @domain: (allow-none): the translation domain or %NULL
1150  *
1151  * Sets the translation domain of @builder. 
1152  * See #GtkBuilder:translation-domain.
1153  *
1154  * Since: 2.12
1155  **/
1156 void
1157 gtk_builder_set_translation_domain (GtkBuilder  *builder,
1158                                     const gchar *domain)
1159 {
1160   gchar *new_domain;
1161     
1162   g_return_if_fail (GTK_IS_BUILDER (builder));
1163
1164   new_domain = g_strdup (domain);
1165   g_free (builder->priv->domain);
1166   builder->priv->domain = new_domain;
1167
1168   g_object_notify (G_OBJECT (builder), "translation-domain");
1169 }
1170
1171 /**
1172  * gtk_builder_get_translation_domain:
1173  * @builder: a #GtkBuilder
1174  *
1175  * Gets the translation domain of @builder.
1176  *
1177  * Return value: the translation domain. This string is owned
1178  * by the builder object and must not be modified or freed.
1179  *
1180  * Since: 2.12
1181  **/
1182 const gchar *
1183 gtk_builder_get_translation_domain (GtkBuilder *builder)
1184 {
1185   g_return_val_if_fail (GTK_IS_BUILDER (builder), NULL);
1186
1187   return builder->priv->domain;
1188 }
1189
1190 typedef struct {
1191   GModule *module;
1192   gpointer data;
1193 } connect_args;
1194
1195 static void
1196 gtk_builder_connect_signals_default (GtkBuilder    *builder,
1197                                      GObject       *object,
1198                                      const gchar   *signal_name,
1199                                      const gchar   *handler_name,
1200                                      GObject       *connect_object,
1201                                      GConnectFlags  flags,
1202                                      gpointer       user_data)
1203 {
1204   GCallback func;
1205   connect_args *args = (connect_args*)user_data;
1206   
1207   if (!g_module_symbol (args->module, handler_name, (gpointer)&func))
1208     {
1209       g_warning ("Could not find signal handler '%s'", handler_name);
1210       return;
1211     }
1212
1213   if (connect_object)
1214     g_signal_connect_object (object, signal_name, func, connect_object, flags);
1215   else
1216     g_signal_connect_data (object, signal_name, func, args->data, NULL, flags);
1217 }
1218
1219
1220 /**
1221  * gtk_builder_connect_signals:
1222  * @builder: a #GtkBuilder
1223  * @user_data: a pointer to a structure sent in as user data to all signals
1224  *
1225  * This method is a simpler variation of gtk_builder_connect_signals_full().
1226  * It uses #GModule's introspective features (by opening the module %NULL) 
1227  * to look at the application's symbol table. From here it tries to match
1228  * the signal handler names given in the interface description with
1229  * symbols in the application and connects the signals. Note that this
1230  * function can only be called once, subsequent calls will do nothing.
1231  * 
1232  * Note that this function will not work correctly if #GModule is not
1233  * supported on the platform.
1234  *
1235  * When compiling applications for Windows, you must declare signal callbacks
1236  * with #G_MODULE_EXPORT, or they will not be put in the symbol table.
1237  * On Linux and Unices, this is not necessary; applications should instead
1238  * be compiled with the -Wl,--export-dynamic CFLAGS, and linked against
1239  * gmodule-export-2.0.
1240  *
1241  * Since: 2.12
1242  **/
1243 void
1244 gtk_builder_connect_signals (GtkBuilder *builder,
1245                              gpointer    user_data)
1246 {
1247   connect_args *args;
1248   
1249   g_return_if_fail (GTK_IS_BUILDER (builder));
1250   
1251   if (!g_module_supported ())
1252     g_error ("gtk_builder_connect_signals() requires working GModule");
1253
1254   args = g_slice_new0 (connect_args);
1255   args->module = g_module_open (NULL, G_MODULE_BIND_LAZY);
1256   args->data = user_data;
1257   
1258   gtk_builder_connect_signals_full (builder,
1259                                     gtk_builder_connect_signals_default,
1260                                     args);
1261   g_module_close (args->module);
1262
1263   g_slice_free (connect_args, args);
1264 }
1265
1266 /**
1267  * GtkBuilderConnectFunc:
1268  * @builder: a #GtkBuilder
1269  * @object: object to connect a signal to
1270  * @signal_name: name of the signal
1271  * @handler_name: name of the handler
1272  * @connect_object: a #GObject, if non-%NULL, use g_signal_connect_object()
1273  * @flags: #GConnectFlags to use
1274  * @user_data: user data
1275  *
1276  * This is the signature of a function used to connect signals.  It is used
1277  * by the gtk_builder_connect_signals() and gtk_builder_connect_signals_full()
1278  * methods.  It is mainly intended for interpreted language bindings, but
1279  * could be useful where the programmer wants more control over the signal
1280  * connection process. Note that this function can only be called once,
1281  * subsequent calls will do nothing.
1282  *
1283  * Since: 2.12
1284  */
1285
1286 /**
1287  * gtk_builder_connect_signals_full:
1288  * @builder: a #GtkBuilder
1289  * @func: (scope call): the function used to connect the signals
1290  * @user_data: arbitrary data that will be passed to the connection function
1291  *
1292  * This function can be thought of the interpreted language binding
1293  * version of gtk_builder_connect_signals(), except that it does not
1294  * require GModule to function correctly.
1295  *
1296  * Since: 2.12
1297  */
1298 void
1299 gtk_builder_connect_signals_full (GtkBuilder            *builder,
1300                                   GtkBuilderConnectFunc  func,
1301                                   gpointer               user_data)
1302 {
1303   GSList *l;
1304   GObject *object;
1305   GObject *connect_object;
1306   
1307   g_return_if_fail (GTK_IS_BUILDER (builder));
1308   g_return_if_fail (func != NULL);
1309   
1310   if (!builder->priv->signals)
1311     return;
1312
1313   builder->priv->signals = g_slist_reverse (builder->priv->signals);
1314   for (l = builder->priv->signals; l; l = l->next)
1315     {
1316       SignalInfo *signal = (SignalInfo*)l->data;
1317
1318       g_assert (signal != NULL);
1319       g_assert (signal->name != NULL);
1320
1321       object = g_hash_table_lookup (builder->priv->objects,
1322                                     signal->object_name);
1323       g_assert (object != NULL);
1324
1325       connect_object = NULL;
1326       
1327       if (signal->connect_object_name)
1328         {
1329           connect_object = g_hash_table_lookup (builder->priv->objects,
1330                                                 signal->connect_object_name);
1331           if (!connect_object)
1332               g_warning ("Could not lookup object %s on signal %s of object %s",
1333                          signal->connect_object_name, signal->name,
1334                          signal->object_name);
1335         }
1336                                                   
1337       func (builder, object, signal->name, signal->handler, 
1338             connect_object, signal->flags, user_data);
1339     }
1340
1341   g_slist_foreach (builder->priv->signals, (GFunc)_free_signal_info, NULL);
1342   g_slist_free (builder->priv->signals);
1343   builder->priv->signals = NULL;
1344 }
1345
1346 /**
1347  * gtk_builder_value_from_string:
1348  * @builder: a #GtkBuilder
1349  * @pspec: the #GParamSpec for the property
1350  * @string: the string representation of the value
1351  * @value: (out): the #GValue to store the result in
1352  * @error: (allow-none): return location for an error, or %NULL
1353  *
1354  * This function demarshals a value from a string. This function
1355  * calls g_value_init() on the @value argument, so it need not be
1356  * initialised beforehand.
1357  *
1358  * This function can handle char, uchar, boolean, int, uint, long,
1359  * ulong, enum, flags, float, double, string, #GdkColor, #GdkRGBA and
1360  * #GtkAdjustment type values. Support for #GtkWidget type values is
1361  * still to come.
1362  *
1363  * Upon errors %FALSE will be returned and @error will be assigned a
1364  * #GError from the #GTK_BUILDER_ERROR domain.
1365  *
1366  * Returns: %TRUE on success
1367  *
1368  * Since: 2.12
1369  */
1370 gboolean
1371 gtk_builder_value_from_string (GtkBuilder   *builder,
1372                                GParamSpec   *pspec,
1373                                const gchar  *string,
1374                                GValue       *value,
1375                                GError      **error)
1376 {
1377   g_return_val_if_fail (GTK_IS_BUILDER (builder), FALSE);
1378   g_return_val_if_fail (G_IS_PARAM_SPEC (pspec), FALSE);
1379   g_return_val_if_fail (string != NULL, FALSE);
1380   g_return_val_if_fail (value != NULL, FALSE);
1381   g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1382
1383   /*
1384    * GParamSpecUnichar has the internal type G_TYPE_UINT,
1385    * so we cannot handle this in the switch, do it separately
1386    */
1387   if (G_IS_PARAM_SPEC_UNICHAR (pspec))
1388     {
1389       gunichar c;
1390       g_value_init (value, G_TYPE_UINT);
1391       c = g_utf8_get_char_validated (string, strlen (string));
1392       if (c > 0)
1393         g_value_set_uint (value, c);
1394       return TRUE;
1395     }
1396
1397   return gtk_builder_value_from_string_type (builder,
1398                                              G_PARAM_SPEC_VALUE_TYPE (pspec),
1399                                              string, value, error);
1400 }
1401
1402 /**
1403  * gtk_builder_value_from_string_type:
1404  * @builder: a #GtkBuilder
1405  * @type: the #GType of the value
1406  * @string: the string representation of the value
1407  * @value: (out): the #GValue to store the result in
1408  * @error: (allow-none): return location for an error, or %NULL
1409  *
1410  * Like gtk_builder_value_from_string(), this function demarshals 
1411  * a value from a string, but takes a #GType instead of #GParamSpec.
1412  * This function calls g_value_init() on the @value argument, so it 
1413  * need not be initialised beforehand.
1414  *
1415  * Upon errors %FALSE will be returned and @error will be assigned a
1416  * #GError from the #GTK_BUILDER_ERROR domain.
1417  *
1418  * Returns: %TRUE on success
1419  *
1420  * Since: 2.12
1421  */
1422 gboolean
1423 gtk_builder_value_from_string_type (GtkBuilder   *builder,
1424                                     GType         type,
1425                                     const gchar  *string,
1426                                     GValue       *value,
1427                                     GError      **error)
1428 {
1429   gboolean ret = TRUE;
1430
1431   g_return_val_if_fail (type != G_TYPE_INVALID, FALSE);
1432   g_return_val_if_fail (string != NULL, FALSE);
1433   g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1434
1435   g_value_init (value, type);
1436
1437   switch (G_TYPE_FUNDAMENTAL (type))
1438     {
1439     case G_TYPE_CHAR:
1440       g_value_set_char (value, string[0]);
1441       break;
1442     case G_TYPE_UCHAR:
1443       g_value_set_uchar (value, (guchar)string[0]);
1444       break;
1445     case G_TYPE_BOOLEAN:
1446       {
1447         gboolean b;
1448
1449         if (!_gtk_builder_boolean_from_string (string, &b, error))
1450           {
1451             ret = FALSE;
1452             break;
1453           }
1454         g_value_set_boolean (value, b);
1455         break;
1456       }
1457     case G_TYPE_INT:
1458     case G_TYPE_LONG:
1459       {
1460         long l;
1461         gchar *endptr = NULL;
1462         errno = 0;
1463         l = g_ascii_strtoll (string, &endptr, 0);
1464         if (errno || endptr == string)
1465           {
1466             g_set_error (error,
1467                          GTK_BUILDER_ERROR,
1468                          GTK_BUILDER_ERROR_INVALID_VALUE,
1469                          "Could not parse integer `%s'",
1470                          string);
1471             ret = FALSE;
1472             break;
1473           }
1474         if (G_VALUE_HOLDS_INT (value))
1475           g_value_set_int (value, l);
1476         else
1477           g_value_set_long (value, l);
1478         break;
1479       }
1480     case G_TYPE_UINT:
1481     case G_TYPE_ULONG:
1482       {
1483         gulong ul;
1484         gchar *endptr = NULL;
1485         errno = 0;
1486         ul = g_ascii_strtoull (string, &endptr, 0);
1487         if (errno || endptr == string)
1488           {
1489             g_set_error (error,
1490                          GTK_BUILDER_ERROR,
1491                          GTK_BUILDER_ERROR_INVALID_VALUE,
1492                          "Could not parse unsigned integer `%s'",
1493                          string);
1494             ret = FALSE;
1495             break;
1496           }
1497         if (G_VALUE_HOLDS_UINT (value))
1498           g_value_set_uint (value, ul);
1499         else 
1500           g_value_set_ulong (value, ul);
1501         break;
1502       }
1503     case G_TYPE_ENUM:
1504       {
1505         gint enum_value;
1506         if (!_gtk_builder_enum_from_string (type, string, &enum_value, error))
1507           {
1508             ret = FALSE;
1509             break;
1510           }
1511         g_value_set_enum (value, enum_value);
1512         break;
1513       }
1514     case G_TYPE_FLAGS:
1515       {
1516         guint flags_value;
1517
1518         if (!_gtk_builder_flags_from_string (type, string, &flags_value, error))
1519           {
1520             ret = FALSE;
1521             break;
1522           }
1523         g_value_set_flags (value, flags_value);
1524         break;
1525       }
1526     case G_TYPE_FLOAT:
1527     case G_TYPE_DOUBLE:
1528       {
1529         gdouble d;
1530         gchar *endptr = NULL;
1531         errno = 0;
1532         d = g_ascii_strtod (string, &endptr);
1533         if (errno || endptr == string)
1534           {
1535             g_set_error (error,
1536                          GTK_BUILDER_ERROR,
1537                          GTK_BUILDER_ERROR_INVALID_VALUE,
1538                          "Could not parse double `%s'",
1539                          string);
1540             ret = FALSE;
1541             break;
1542           }
1543         if (G_VALUE_HOLDS_FLOAT (value))
1544           g_value_set_float (value, d);
1545         else
1546           g_value_set_double (value, d);
1547         break;
1548       }
1549     case G_TYPE_STRING:
1550       g_value_set_string (value, string);
1551       break;
1552     case G_TYPE_BOXED:
1553       if (G_VALUE_HOLDS (value, GDK_TYPE_COLOR))
1554         {
1555           GdkColor color = { 0, };
1556
1557           if (gdk_color_parse (string, &color))
1558             g_value_set_boxed (value, &color);
1559           else
1560             {
1561               g_set_error (error,
1562                            GTK_BUILDER_ERROR,
1563                            GTK_BUILDER_ERROR_INVALID_VALUE,
1564                            "Could not parse color `%s'",
1565                            string);
1566               ret = FALSE;
1567             }
1568         }
1569       else if (G_VALUE_HOLDS (value, GDK_TYPE_RGBA))
1570         {
1571           GdkRGBA rgba = { 0 };
1572
1573           if (gdk_rgba_parse (&rgba, string))
1574             g_value_set_boxed (value, &rgba);
1575           else
1576             {
1577               g_set_error (error,
1578                            GTK_BUILDER_ERROR,
1579                            GTK_BUILDER_ERROR_INVALID_VALUE,
1580                            "Could not parse RGBA color '%s'",
1581                            string);
1582               ret = FALSE;
1583             }
1584         }
1585       else if (G_VALUE_HOLDS (value, G_TYPE_STRV))
1586         {
1587           gchar **vector = g_strsplit (string, "\n", 0);
1588           g_value_take_boxed (value, vector);
1589         }
1590       else
1591         {
1592           g_set_error (error,
1593                        GTK_BUILDER_ERROR,
1594                        GTK_BUILDER_ERROR_INVALID_VALUE,
1595                        "Could not parse '%s' as a %s",
1596                        string, G_VALUE_TYPE_NAME (value));
1597           ret = FALSE;
1598         }
1599       break;
1600     case G_TYPE_OBJECT:
1601       if (G_VALUE_HOLDS (value, GDK_TYPE_PIXBUF))
1602         {
1603           gchar *filename;
1604           GError *tmp_error = NULL;
1605           GdkPixbuf *pixbuf;
1606        
1607           if (gtk_builder_get_object (builder, string))
1608             {
1609               g_set_error (error,
1610                            GTK_BUILDER_ERROR,
1611                            GTK_BUILDER_ERROR_INVALID_VALUE,
1612                            "Could not load image '%s': "
1613                            " '%s' is already used as object id",
1614                            string, string);
1615               return FALSE;
1616             }
1617
1618           filename = _gtk_builder_get_absolute_filename (builder, string);
1619           pixbuf = gdk_pixbuf_new_from_file (filename, &tmp_error);
1620
1621           if (pixbuf == NULL)
1622             {
1623               GtkIconTheme *theme;
1624
1625               g_warning ("Could not load image '%s': %s", 
1626                          string, tmp_error->message);
1627               g_error_free (tmp_error);
1628
1629               /* fall back to a missing image */
1630               theme = gtk_icon_theme_get_default ();
1631               pixbuf = gtk_icon_theme_load_icon (theme, 
1632                                                  GTK_STOCK_MISSING_IMAGE,
1633                                                  16,
1634                                                  GTK_ICON_LOOKUP_USE_BUILTIN,
1635                                                  NULL);
1636             }
1637  
1638           if (pixbuf)
1639             {
1640               g_value_set_object (value, pixbuf);
1641               g_object_unref (G_OBJECT (pixbuf));
1642             }
1643
1644           g_free (filename);
1645
1646           ret = TRUE;
1647         }
1648       else
1649         ret = FALSE;
1650       break;
1651     default:
1652       ret = FALSE;
1653       break;
1654     }
1655  
1656   /* Catch unassigned error for object types as well as any unsupported types.
1657    * While parsing GtkBuilder; object types are deserialized
1658    * without calling gtk_builder_value_from_string_type().
1659    */
1660   if (!ret && error && *error == NULL) 
1661     g_set_error (error,
1662                  GTK_BUILDER_ERROR,
1663                  GTK_BUILDER_ERROR_INVALID_VALUE,
1664                  "Unsupported GType `%s'", g_type_name (type));
1665
1666   return ret;
1667 }
1668
1669 gboolean
1670 _gtk_builder_enum_from_string (GType         type, 
1671                                const gchar  *string,
1672                                gint         *enum_value,
1673                                GError      **error)
1674 {
1675   GEnumClass *eclass;
1676   GEnumValue *ev;
1677   gchar *endptr;
1678   gint value;
1679   gboolean ret;
1680   
1681   g_return_val_if_fail (G_TYPE_IS_ENUM (type), FALSE);
1682   g_return_val_if_fail (string != NULL, FALSE);
1683   
1684   ret = TRUE;
1685
1686   endptr = NULL;
1687   errno = 0;
1688   value = g_ascii_strtoull (string, &endptr, 0);
1689   if (errno == 0 && endptr != string) /* parsed a number */
1690     *enum_value = value;
1691   else
1692     {
1693       eclass = g_type_class_ref (type);
1694       ev = g_enum_get_value_by_name (eclass, string);
1695       if (!ev)
1696         ev = g_enum_get_value_by_nick (eclass, string);
1697
1698       if (ev)
1699         *enum_value = ev->value;
1700       else
1701         {
1702           g_set_error (error,
1703                        GTK_BUILDER_ERROR,
1704                        GTK_BUILDER_ERROR_INVALID_VALUE,
1705                        "Could not parse enum: `%s'",
1706                        string);
1707           ret = FALSE;
1708         }
1709       
1710       g_type_class_unref (eclass);
1711     }
1712   
1713   return ret;
1714 }
1715
1716 gboolean
1717 _gtk_builder_flags_from_string (GType         type, 
1718                                 const gchar  *string,
1719                                 guint        *flags_value,
1720                                 GError      **error)
1721 {
1722   GFlagsClass *fclass;
1723   gchar *endptr, *prevptr;
1724   guint i, j, value;
1725   gchar *flagstr;
1726   GFlagsValue *fv;
1727   const gchar *flag;
1728   gunichar ch;
1729   gboolean eos, ret;
1730
1731   g_return_val_if_fail (G_TYPE_IS_FLAGS (type), FALSE);
1732   g_return_val_if_fail (string != 0, FALSE);
1733
1734   ret = TRUE;
1735
1736   endptr = NULL;
1737   errno = 0;
1738   value = g_ascii_strtoull (string, &endptr, 0);
1739   if (errno == 0 && endptr != string) /* parsed a number */
1740     *flags_value = value;
1741   else
1742     {
1743       fclass = g_type_class_ref (type);
1744
1745       flagstr = g_strdup (string);
1746       for (value = i = j = 0; ; i++)
1747         {
1748           
1749           eos = flagstr[i] == '\0';
1750           
1751           if (!eos && flagstr[i] != '|')
1752             continue;
1753           
1754           flag = &flagstr[j];
1755           endptr = &flagstr[i];
1756           
1757           if (!eos)
1758             {
1759               flagstr[i++] = '\0';
1760               j = i;
1761             }
1762           
1763           /* trim spaces */
1764           for (;;)
1765             {
1766               ch = g_utf8_get_char (flag);
1767               if (!g_unichar_isspace (ch))
1768                 break;
1769               flag = g_utf8_next_char (flag);
1770             }
1771           
1772           while (endptr > flag)
1773             {
1774               prevptr = g_utf8_prev_char (endptr);
1775               ch = g_utf8_get_char (prevptr);
1776               if (!g_unichar_isspace (ch))
1777                 break;
1778               endptr = prevptr;
1779             }
1780           
1781           if (endptr > flag)
1782             {
1783               *endptr = '\0';
1784               fv = g_flags_get_value_by_name (fclass, flag);
1785               
1786               if (!fv)
1787                 fv = g_flags_get_value_by_nick (fclass, flag);
1788               
1789               if (fv)
1790                 value |= fv->value;
1791               else
1792                 {
1793                   g_set_error (error,
1794                                GTK_BUILDER_ERROR,
1795                                GTK_BUILDER_ERROR_INVALID_VALUE,
1796                                "Unknown flag: `%s'",
1797                                flag);
1798                   ret = FALSE;
1799                   break;
1800                 }
1801             }
1802           
1803           if (eos)
1804             {
1805               *flags_value = value;
1806               break;
1807             }
1808         }
1809       
1810       g_free (flagstr);
1811       
1812       g_type_class_unref (fclass);
1813     }
1814
1815   return ret;
1816 }
1817
1818 /**
1819  * gtk_builder_get_type_from_name:
1820  * @builder: a #GtkBuilder
1821  * @type_name: type name to lookup
1822  *
1823  * Looks up a type by name, using the virtual function that 
1824  * #GtkBuilder has for that purpose. This is mainly used when
1825  * implementing the #GtkBuildable interface on a type.
1826  *
1827  * Returns: the #GType found for @type_name or #G_TYPE_INVALID 
1828  *   if no type was found
1829  *
1830  * Since: 2.12
1831  */
1832 GType
1833 gtk_builder_get_type_from_name (GtkBuilder  *builder, 
1834                                 const gchar *type_name)
1835 {
1836   g_return_val_if_fail (GTK_IS_BUILDER (builder), G_TYPE_INVALID);
1837   g_return_val_if_fail (type_name != NULL, G_TYPE_INVALID);
1838
1839   return GTK_BUILDER_GET_CLASS (builder)->get_type_from_name (builder, type_name);
1840 }
1841
1842 GQuark
1843 gtk_builder_error_quark (void)
1844 {
1845   return g_quark_from_static_string ("gtk-builder-error-quark");
1846 }
1847
1848 gchar *
1849 _gtk_builder_get_absolute_filename (GtkBuilder *builder, const gchar *string)
1850 {
1851   gchar *filename;
1852   gchar *dirname = NULL;
1853   
1854   if (g_path_is_absolute (string))
1855     return g_strdup (string);
1856
1857   if (builder->priv->filename &&
1858       strcmp (builder->priv->filename, ".") != 0) 
1859     {
1860       dirname = g_path_get_dirname (builder->priv->filename);
1861
1862       if (strcmp (dirname, ".") == 0)
1863         {
1864           g_free (dirname);
1865           dirname = g_get_current_dir ();
1866         }
1867     }
1868   else
1869     dirname = g_get_current_dir ();
1870     
1871   filename = g_build_filename (dirname, string, NULL);
1872   g_free (dirname);
1873   
1874   return filename;
1875 }