No necessary to init qdata atomically
[platform/upstream/glib.git] / gobject / gobject.c
1 /* GObject - GLib Type, Object, Parameter and Signal Library
2  * Copyright (C) 1998-1999, 2000-2001 Tim Janik and Red Hat, Inc.
3  *
4  * This library is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Lesser General Public
6  * License as published by the Free Software Foundation; either
7  * version 2 of the License, or (at your option) any later version.
8  *
9  * This library is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * Lesser General Public License for more details.
13  *
14  * You should have received a copy of the GNU Lesser General
15  * Public License along with this library; if not, write to the
16  * Free Software Foundation, Inc., 59 Temple Place, Suite 330,
17  * Boston, MA 02111-1307, USA.
18  */
19
20 /*
21  * MT safe with regards to reference counting.
22  */
23
24 #include "config.h"
25
26 #include <string.h>
27 #include <signal.h>
28
29 #include "gobject.h"
30 #include "gtype-private.h"
31 #include "gvaluecollector.h"
32 #include "gsignal.h"
33 #include "gparamspecs.h"
34 #include "gvaluetypes.h"
35 #include "gobject_trace.h"
36
37 #include "gobjectnotifyqueue.c"
38
39 /**
40  * SECTION:objects
41  * @short_description: The base object type
42  * @see_also: #GParamSpecObject, g_param_spec_object()
43  * @title: The Base Object Type
44  *
45  * GObject is the fundamental type providing the common attributes and
46  * methods for all object types in GTK+, Pango and other libraries
47  * based on GObject.  The GObject class provides methods for object
48  * construction and destruction, property access methods, and signal
49  * support.  Signals are described in detail in <xref
50  * linkend="gobject-Signals"/>.
51  *
52  * <para id="floating-ref">
53  * #GInitiallyUnowned is derived from #GObject. The only difference between
54  * the two is that the initial reference of a #GInitiallyUnowned is flagged
55  * as a <firstterm>floating</firstterm> reference.
56  * This means that it is not specifically claimed to be "owned" by
57  * any code portion. The main motivation for providing floating references is
58  * C convenience. In particular, it allows code to be written as:
59  * |[
60  * container = create_container();
61  * container_add_child (container, create_child());
62  * ]|
63  * If <function>container_add_child()</function> will g_object_ref_sink() the
64  * passed in child, no reference of the newly created child is leaked.
65  * Without floating references, <function>container_add_child()</function>
66  * can only g_object_ref() the new child, so to implement this code without
67  * reference leaks, it would have to be written as:
68  * |[
69  * Child *child;
70  * container = create_container();
71  * child = create_child();
72  * container_add_child (container, child);
73  * g_object_unref (child);
74  * ]|
75  * The floating reference can be converted into
76  * an ordinary reference by calling g_object_ref_sink().
77  * For already sunken objects (objects that don't have a floating reference
78  * anymore), g_object_ref_sink() is equivalent to g_object_ref() and returns
79  * a new reference.
80  * Since floating references are useful almost exclusively for C convenience,
81  * language bindings that provide automated reference and memory ownership
82  * maintenance (such as smart pointers or garbage collection) therefore don't
83  * need to expose floating references in their API.
84  * </para>
85  *
86  * Some object implementations may need to save an objects floating state
87  * across certain code portions (an example is #GtkMenu), to achive this, the
88  * following sequence can be used:
89  *
90  * |[
91  * // save floating state
92  * gboolean was_floating = g_object_is_floating (object);
93  * g_object_ref_sink (object);
94  * // protected code portion
95  * ...;
96  * // restore floating state
97  * if (was_floating)
98  *   g_object_force_floating (object);
99  * g_obejct_unref (object); // release previously acquired reference
100  * ]|
101  */
102
103
104 /* --- macros --- */
105 #define PARAM_SPEC_PARAM_ID(pspec)              ((pspec)->param_id)
106 #define PARAM_SPEC_SET_PARAM_ID(pspec, id)      ((pspec)->param_id = (id))
107
108 #define OBJECT_HAS_TOGGLE_REF_FLAG 0x1
109 #define OBJECT_HAS_TOGGLE_REF(object) \
110     ((g_datalist_get_flags (&(object)->qdata) & OBJECT_HAS_TOGGLE_REF_FLAG) != 0)
111 #define OBJECT_FLOATING_FLAG 0x2
112
113 #define CLASS_HAS_PROPS_FLAG 0x1
114 #define CLASS_HAS_PROPS(class) \
115     ((class)->flags & CLASS_HAS_PROPS_FLAG)
116 #define CLASS_HAS_CUSTOM_CONSTRUCTOR(class) \
117     ((class)->constructor != g_object_constructor)
118 #define CLASS_HAS_CUSTOM_CONSTRUCTED(class) \
119     ((class)->constructed != g_object_constructed)
120
121 #define CLASS_HAS_DERIVED_CLASS_FLAG 0x2
122 #define CLASS_HAS_DERIVED_CLASS(class) \
123     ((class)->flags & CLASS_HAS_DERIVED_CLASS_FLAG)
124
125 /* --- signals --- */
126 enum {
127   NOTIFY,
128   LAST_SIGNAL
129 };
130
131
132 /* --- properties --- */
133 enum {
134   PROP_NONE
135 };
136
137
138 /* --- prototypes --- */
139 static void     g_object_base_class_init                (GObjectClass   *class);
140 static void     g_object_base_class_finalize            (GObjectClass   *class);
141 static void     g_object_do_class_init                  (GObjectClass   *class);
142 static void     g_object_init                           (GObject        *object,
143                                                          GObjectClass   *class);
144 static GObject* g_object_constructor                    (GType                  type,
145                                                          guint                  n_construct_properties,
146                                                          GObjectConstructParam *construct_params);
147 static void     g_object_constructed                    (GObject        *object);
148 static void     g_object_real_dispose                   (GObject        *object);
149 static void     g_object_finalize                       (GObject        *object);
150 static void     g_object_do_set_property                (GObject        *object,
151                                                          guint           property_id,
152                                                          const GValue   *value,
153                                                          GParamSpec     *pspec);
154 static void     g_object_do_get_property                (GObject        *object,
155                                                          guint           property_id,
156                                                          GValue         *value,
157                                                          GParamSpec     *pspec);
158 static void     g_value_object_init                     (GValue         *value);
159 static void     g_value_object_free_value               (GValue         *value);
160 static void     g_value_object_copy_value               (const GValue   *src_value,
161                                                          GValue         *dest_value);
162 static void     g_value_object_transform_value          (const GValue   *src_value,
163                                                          GValue         *dest_value);
164 static gpointer g_value_object_peek_pointer             (const GValue   *value);
165 static gchar*   g_value_object_collect_value            (GValue         *value,
166                                                          guint           n_collect_values,
167                                                          GTypeCValue    *collect_values,
168                                                          guint           collect_flags);
169 static gchar*   g_value_object_lcopy_value              (const GValue   *value,
170                                                          guint           n_collect_values,
171                                                          GTypeCValue    *collect_values,
172                                                          guint           collect_flags);
173 static void     g_object_dispatch_properties_changed    (GObject        *object,
174                                                          guint           n_pspecs,
175                                                          GParamSpec    **pspecs);
176 static inline void         object_get_property          (GObject        *object,
177                                                          GParamSpec     *pspec,
178                                                          GValue         *value);
179 static inline void         object_set_property          (GObject        *object,
180                                                          GParamSpec     *pspec,
181                                                          const GValue   *value,
182                                                          GObjectNotifyQueue *nqueue);
183 static guint               object_floating_flag_handler (GObject        *object,
184                                                          gint            job);
185
186 static void object_interface_check_properties           (gpointer        func_data,
187                                                          gpointer        g_iface);
188
189
190 /* --- variables --- */
191 G_LOCK_DEFINE_STATIC (closure_array_mutex);
192 G_LOCK_DEFINE_STATIC (weak_refs_mutex);
193 G_LOCK_DEFINE_STATIC (toggle_refs_mutex);
194 static GQuark               quark_closure_array = 0;
195 static GQuark               quark_weak_refs = 0;
196 static GQuark               quark_toggle_refs = 0;
197 static GParamSpecPool      *pspec_pool = NULL;
198 static GObjectNotifyContext property_notify_context = { 0, };
199 static gulong               gobject_signals[LAST_SIGNAL] = { 0, };
200 static guint (*floating_flag_handler) (GObject*, gint) = object_floating_flag_handler;
201 G_LOCK_DEFINE_STATIC (construction_mutex);
202 static GSList *construction_objects = NULL;
203
204 /* --- functions --- */
205 #ifdef  G_ENABLE_DEBUG
206 #define IF_DEBUG(debug_type)    if (_g_type_debug_flags & G_TYPE_DEBUG_ ## debug_type)
207 G_LOCK_DEFINE_STATIC     (debug_objects);
208 static volatile GObject *g_trap_object_ref = NULL;
209 static guint             debug_objects_count = 0;
210 static GHashTable       *debug_objects_ht = NULL;
211
212 static void
213 debug_objects_foreach (gpointer key,
214                        gpointer value,
215                        gpointer user_data)
216 {
217   GObject *object = value;
218
219   g_message ("[%p] stale %s\tref_count=%u",
220              object,
221              G_OBJECT_TYPE_NAME (object),
222              object->ref_count);
223 }
224
225 static void
226 debug_objects_atexit (void)
227 {
228   IF_DEBUG (OBJECTS)
229     {
230       G_LOCK (debug_objects);
231       g_message ("stale GObjects: %u", debug_objects_count);
232       g_hash_table_foreach (debug_objects_ht, debug_objects_foreach, NULL);
233       G_UNLOCK (debug_objects);
234     }
235 }
236 #endif  /* G_ENABLE_DEBUG */
237
238 void
239 _g_object_type_init (void)
240 {
241   static gboolean initialized = FALSE;
242   static const GTypeFundamentalInfo finfo = {
243     G_TYPE_FLAG_CLASSED | G_TYPE_FLAG_INSTANTIATABLE | G_TYPE_FLAG_DERIVABLE | G_TYPE_FLAG_DEEP_DERIVABLE,
244   };
245   static GTypeInfo info = {
246     sizeof (GObjectClass),
247     (GBaseInitFunc) g_object_base_class_init,
248     (GBaseFinalizeFunc) g_object_base_class_finalize,
249     (GClassInitFunc) g_object_do_class_init,
250     NULL        /* class_destroy */,
251     NULL        /* class_data */,
252     sizeof (GObject),
253     0           /* n_preallocs */,
254     (GInstanceInitFunc) g_object_init,
255     NULL,       /* value_table */
256   };
257   static const GTypeValueTable value_table = {
258     g_value_object_init,          /* value_init */
259     g_value_object_free_value,    /* value_free */
260     g_value_object_copy_value,    /* value_copy */
261     g_value_object_peek_pointer,  /* value_peek_pointer */
262     "p",                          /* collect_format */
263     g_value_object_collect_value, /* collect_value */
264     "p",                          /* lcopy_format */
265     g_value_object_lcopy_value,   /* lcopy_value */
266   };
267   GType type;
268   
269   g_return_if_fail (initialized == FALSE);
270   initialized = TRUE;
271   
272   /* G_TYPE_OBJECT
273    */
274   info.value_table = &value_table;
275   type = g_type_register_fundamental (G_TYPE_OBJECT, g_intern_static_string ("GObject"), &info, &finfo, 0);
276   g_assert (type == G_TYPE_OBJECT);
277   g_value_register_transform_func (G_TYPE_OBJECT, G_TYPE_OBJECT, g_value_object_transform_value);
278   
279 #ifdef  G_ENABLE_DEBUG
280   IF_DEBUG (OBJECTS)
281     {
282       debug_objects_ht = g_hash_table_new (g_direct_hash, NULL);
283       g_atexit (debug_objects_atexit);
284     }
285 #endif  /* G_ENABLE_DEBUG */
286 }
287
288 static void
289 g_object_base_class_init (GObjectClass *class)
290 {
291   GObjectClass *pclass = g_type_class_peek_parent (class);
292
293   /* Don't inherit HAS_DERIVED_CLASS flag from parent class */
294   class->flags &= ~CLASS_HAS_DERIVED_CLASS_FLAG;
295
296   if (pclass)
297     pclass->flags |= CLASS_HAS_DERIVED_CLASS_FLAG;
298
299   /* reset instance specific fields and methods that don't get inherited */
300   class->construct_properties = pclass ? g_slist_copy (pclass->construct_properties) : NULL;
301   class->get_property = NULL;
302   class->set_property = NULL;
303 }
304
305 static void
306 g_object_base_class_finalize (GObjectClass *class)
307 {
308   GList *list, *node;
309   
310   _g_signals_destroy (G_OBJECT_CLASS_TYPE (class));
311
312   g_slist_free (class->construct_properties);
313   class->construct_properties = NULL;
314   list = g_param_spec_pool_list_owned (pspec_pool, G_OBJECT_CLASS_TYPE (class));
315   for (node = list; node; node = node->next)
316     {
317       GParamSpec *pspec = node->data;
318       
319       g_param_spec_pool_remove (pspec_pool, pspec);
320       PARAM_SPEC_SET_PARAM_ID (pspec, 0);
321       g_param_spec_unref (pspec);
322     }
323   g_list_free (list);
324 }
325
326 static void
327 g_object_notify_dispatcher (GObject     *object,
328                             guint        n_pspecs,
329                             GParamSpec **pspecs)
330 {
331   G_OBJECT_GET_CLASS (object)->dispatch_properties_changed (object, n_pspecs, pspecs);
332 }
333
334 static void
335 g_object_do_class_init (GObjectClass *class)
336 {
337   /* read the comment about typedef struct CArray; on why not to change this quark */
338   quark_closure_array = g_quark_from_static_string ("GObject-closure-array");
339
340   quark_weak_refs = g_quark_from_static_string ("GObject-weak-references");
341   quark_toggle_refs = g_quark_from_static_string ("GObject-toggle-references");
342   pspec_pool = g_param_spec_pool_new (TRUE);
343   property_notify_context.quark_notify_queue = g_quark_from_static_string ("GObject-notify-queue");
344   property_notify_context.dispatcher = g_object_notify_dispatcher;
345
346   class->constructor = g_object_constructor;
347   class->constructed = g_object_constructed;
348   class->set_property = g_object_do_set_property;
349   class->get_property = g_object_do_get_property;
350   class->dispose = g_object_real_dispose;
351   class->finalize = g_object_finalize;
352   class->dispatch_properties_changed = g_object_dispatch_properties_changed;
353   class->notify = NULL;
354
355   /**
356    * GObject::notify:
357    * @gobject: the object which received the signal.
358    * @pspec: the #GParamSpec of the property which changed.
359    *
360    * The notify signal is emitted on an object when one of its
361    * properties has been changed. Note that getting this signal
362    * doesn't guarantee that the value of the property has actually
363    * changed, it may also be emitted when the setter for the property
364    * is called to reinstate the previous value.
365    *
366    * This signal is typically used to obtain change notification for a
367    * single property, by specifying the property name as a detail in the
368    * g_signal_connect() call, like this:
369    * |[
370    * g_signal_connect (text_view->buffer, "notify::paste-target-list",
371    *                   G_CALLBACK (gtk_text_view_target_list_notify),
372    *                   text_view)
373    * ]|
374    * It is important to note that you must use
375    * <link linkend="canonical-parameter-name">canonical</link> parameter names as
376    * detail strings for the notify signal.
377    */
378   gobject_signals[NOTIFY] =
379     g_signal_new (g_intern_static_string ("notify"),
380                   G_TYPE_FROM_CLASS (class),
381                   G_SIGNAL_RUN_FIRST | G_SIGNAL_NO_RECURSE | G_SIGNAL_DETAILED | G_SIGNAL_NO_HOOKS | G_SIGNAL_ACTION,
382                   G_STRUCT_OFFSET (GObjectClass, notify),
383                   NULL, NULL,
384                   g_cclosure_marshal_VOID__PARAM,
385                   G_TYPE_NONE,
386                   1, G_TYPE_PARAM);
387
388   /* Install a check function that we'll use to verify that classes that
389    * implement an interface implement all properties for that interface
390    */
391   g_type_add_interface_check (NULL, object_interface_check_properties);
392 }
393
394 static inline void
395 install_property_internal (GType       g_type,
396                            guint       property_id,
397                            GParamSpec *pspec)
398 {
399   if (g_param_spec_pool_lookup (pspec_pool, pspec->name, g_type, FALSE))
400     {
401       g_warning ("When installing property: type `%s' already has a property named `%s'",
402                  g_type_name (g_type),
403                  pspec->name);
404       return;
405     }
406
407   g_param_spec_ref (pspec);
408   g_param_spec_sink (pspec);
409   PARAM_SPEC_SET_PARAM_ID (pspec, property_id);
410   g_param_spec_pool_insert (pspec_pool, pspec, g_type);
411 }
412
413 /**
414  * g_object_class_install_property:
415  * @oclass: a #GObjectClass
416  * @property_id: the id for the new property
417  * @pspec: the #GParamSpec for the new property
418  *
419  * Installs a new property. This is usually done in the class initializer.
420  *
421  * Note that it is possible to redefine a property in a derived class,
422  * by installing a property with the same name. This can be useful at times,
423  * e.g. to change the range of allowed values or the default value.
424  */
425 void
426 g_object_class_install_property (GObjectClass *class,
427                                  guint         property_id,
428                                  GParamSpec   *pspec)
429 {
430   g_return_if_fail (G_IS_OBJECT_CLASS (class));
431   g_return_if_fail (G_IS_PARAM_SPEC (pspec));
432
433   if (CLASS_HAS_DERIVED_CLASS (class))
434     g_error ("Attempt to add property %s::%s to class after it was derived",
435              G_OBJECT_CLASS_NAME (class), pspec->name);
436
437   class->flags |= CLASS_HAS_PROPS_FLAG;
438
439   if (pspec->flags & G_PARAM_WRITABLE)
440     g_return_if_fail (class->set_property != NULL);
441   if (pspec->flags & G_PARAM_READABLE)
442     g_return_if_fail (class->get_property != NULL);
443   g_return_if_fail (property_id > 0);
444   g_return_if_fail (PARAM_SPEC_PARAM_ID (pspec) == 0);  /* paranoid */
445   if (pspec->flags & G_PARAM_CONSTRUCT)
446     g_return_if_fail ((pspec->flags & G_PARAM_CONSTRUCT_ONLY) == 0);
447   if (pspec->flags & (G_PARAM_CONSTRUCT | G_PARAM_CONSTRUCT_ONLY))
448     g_return_if_fail (pspec->flags & G_PARAM_WRITABLE);
449
450   install_property_internal (G_OBJECT_CLASS_TYPE (class), property_id, pspec);
451
452   if (pspec->flags & (G_PARAM_CONSTRUCT | G_PARAM_CONSTRUCT_ONLY))
453     class->construct_properties = g_slist_prepend (class->construct_properties, pspec);
454
455   /* for property overrides of construct properties, we have to get rid
456    * of the overidden inherited construct property
457    */
458   pspec = g_param_spec_pool_lookup (pspec_pool, pspec->name, g_type_parent (G_OBJECT_CLASS_TYPE (class)), TRUE);
459   if (pspec && pspec->flags & (G_PARAM_CONSTRUCT | G_PARAM_CONSTRUCT_ONLY))
460     class->construct_properties = g_slist_remove (class->construct_properties, pspec);
461 }
462
463 /**
464  * g_object_class_install_properties:
465  * @oclass: a #GObjectClass
466  * @n_pspecs: the length of the #GParamSpec<!-- -->s array
467  * @pspecs: (array length=n_pspecs): the #GParamSpec<!-- -->s array
468  *   defining the new properties
469  *
470  * Installs new properties from an array of #GParamSpec<!-- -->s. This is
471  * usually done in the class initializer.
472  *
473  * The property id of each property is the index of each #GParamSpec in
474  * the @pspecs array.
475  *
476  * The property id of 0 is treated specially by #GObject and it should not
477  * be used to store a #GParamSpec.
478  *
479  * This function should be used if you plan to use a static array of
480  * #GParamSpec<!-- -->s and g_object_notify_by_pspec(). For instance, this
481  * class initialization:
482  *
483  * |[
484  * enum {
485  *   PROP_0, PROP_FOO, PROP_BAR, N_PROPERTIES
486  * };
487  *
488  * static GParamSpec *obj_properties[N_PROPERTIES] = { NULL, };
489  *
490  * static void
491  * my_object_class_init (MyObjectClass *klass)
492  * {
493  *   GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
494  *
495  *   obj_properties[PROP_FOO] =
496  *     g_param_spec_int ("foo", "Foo", "Foo",
497  *                       -1, G_MAXINT,
498  *                       0,
499  *                       G_PARAM_READWRITE);
500  *
501  *   obj_properties[PROP_BAR] =
502  *     g_param_spec_string ("bar", "Bar", "Bar",
503  *                          NULL,
504  *                          G_PARAM_READWRITE);
505  *
506  *   gobject_class->set_property = my_object_set_property;
507  *   gobject_class->get_property = my_object_get_property;
508  *   g_object_class_install_properties (gobject_class,
509  *                                      N_PROPERTIES,
510  *                                      obj_properties);
511  * }
512  * ]|
513  *
514  * allows calling g_object_notify_by_pspec() to notify of property changes:
515  *
516  * |[
517  * void
518  * my_object_set_foo (MyObject *self, gint foo)
519  * {
520  *   if (self->foo != foo)
521  *     {
522  *       self->foo = foo;
523  *       g_object_notify_by_pspec (G_OBJECT (self), obj_properties[PROP_FOO]);
524  *     }
525  *  }
526  * ]|
527  *
528  * Since: 2.26
529  */
530 void
531 g_object_class_install_properties (GObjectClass  *oclass,
532                                    guint          n_pspecs,
533                                    GParamSpec   **pspecs)
534 {
535   GType oclass_type, parent_type;
536   gint i;
537
538   g_return_if_fail (G_IS_OBJECT_CLASS (oclass));
539   g_return_if_fail (n_pspecs > 1);
540   g_return_if_fail (pspecs[0] == NULL);
541
542   if (CLASS_HAS_DERIVED_CLASS (oclass))
543     g_error ("Attempt to add properties to %s after it was derived",
544              G_OBJECT_CLASS_NAME (oclass));
545
546   oclass_type = G_OBJECT_CLASS_TYPE (oclass);
547   parent_type = g_type_parent (oclass_type);
548
549   /* we skip the first element of the array as it would have a 0 prop_id */
550   for (i = 1; i < n_pspecs; i++)
551     {
552       GParamSpec *pspec = pspecs[i];
553
554       g_return_if_fail (pspec != NULL);
555
556       if (pspec->flags & G_PARAM_WRITABLE)
557         g_return_if_fail (oclass->set_property != NULL);
558       if (pspec->flags & G_PARAM_READABLE)
559         g_return_if_fail (oclass->get_property != NULL);
560       g_return_if_fail (PARAM_SPEC_PARAM_ID (pspec) == 0);      /* paranoid */
561       if (pspec->flags & G_PARAM_CONSTRUCT)
562         g_return_if_fail ((pspec->flags & G_PARAM_CONSTRUCT_ONLY) == 0);
563       if (pspec->flags & (G_PARAM_CONSTRUCT | G_PARAM_CONSTRUCT_ONLY))
564         g_return_if_fail (pspec->flags & G_PARAM_WRITABLE);
565
566       oclass->flags |= CLASS_HAS_PROPS_FLAG;
567       install_property_internal (oclass_type, i, pspec);
568
569       if (pspec->flags & (G_PARAM_CONSTRUCT | G_PARAM_CONSTRUCT_ONLY))
570         oclass->construct_properties = g_slist_prepend (oclass->construct_properties, pspec);
571
572       /* for property overrides of construct properties, we have to get rid
573        * of the overidden inherited construct property
574        */
575       pspec = g_param_spec_pool_lookup (pspec_pool, pspec->name, parent_type, TRUE);
576       if (pspec && pspec->flags & (G_PARAM_CONSTRUCT | G_PARAM_CONSTRUCT_ONLY))
577         oclass->construct_properties = g_slist_remove (oclass->construct_properties, pspec);
578     }
579 }
580
581 /**
582  * g_object_interface_install_property:
583  * @g_iface: any interface vtable for the interface, or the default
584  *  vtable for the interface.
585  * @pspec: the #GParamSpec for the new property
586  *
587  * Add a property to an interface; this is only useful for interfaces
588  * that are added to GObject-derived types. Adding a property to an
589  * interface forces all objects classes with that interface to have a
590  * compatible property. The compatible property could be a newly
591  * created #GParamSpec, but normally
592  * g_object_class_override_property() will be used so that the object
593  * class only needs to provide an implementation and inherits the
594  * property description, default value, bounds, and so forth from the
595  * interface property.
596  *
597  * This function is meant to be called from the interface's default
598  * vtable initialization function (the @class_init member of
599  * #GTypeInfo.) It must not be called after after @class_init has
600  * been called for any object types implementing this interface.
601  *
602  * Since: 2.4
603  */
604 void
605 g_object_interface_install_property (gpointer      g_iface,
606                                      GParamSpec   *pspec)
607 {
608   GTypeInterface *iface_class = g_iface;
609         
610   g_return_if_fail (G_TYPE_IS_INTERFACE (iface_class->g_type));
611   g_return_if_fail (G_IS_PARAM_SPEC (pspec));
612   g_return_if_fail (!G_IS_PARAM_SPEC_OVERRIDE (pspec)); /* paranoid */
613   g_return_if_fail (PARAM_SPEC_PARAM_ID (pspec) == 0);  /* paranoid */
614                     
615   install_property_internal (iface_class->g_type, 0, pspec);
616 }
617
618 /**
619  * g_object_class_find_property:
620  * @oclass: a #GObjectClass
621  * @property_name: the name of the property to look up
622  *
623  * Looks up the #GParamSpec for a property of a class.
624  *
625  * Returns: (transfer none): the #GParamSpec for the property, or
626  *          %NULL if the class doesn't have a property of that name
627  */
628 GParamSpec*
629 g_object_class_find_property (GObjectClass *class,
630                               const gchar  *property_name)
631 {
632   GParamSpec *pspec;
633   GParamSpec *redirect;
634         
635   g_return_val_if_fail (G_IS_OBJECT_CLASS (class), NULL);
636   g_return_val_if_fail (property_name != NULL, NULL);
637   
638   pspec = g_param_spec_pool_lookup (pspec_pool,
639                                     property_name,
640                                     G_OBJECT_CLASS_TYPE (class),
641                                     TRUE);
642   if (pspec)
643     {
644       redirect = g_param_spec_get_redirect_target (pspec);
645       if (redirect)
646         return redirect;
647       else
648         return pspec;
649     }
650   else
651     return NULL;
652 }
653
654 /**
655  * g_object_interface_find_property:
656  * @g_iface: any interface vtable for the interface, or the default
657  *  vtable for the interface
658  * @property_name: name of a property to lookup.
659  *
660  * Find the #GParamSpec with the given name for an
661  * interface. Generally, the interface vtable passed in as @g_iface
662  * will be the default vtable from g_type_default_interface_ref(), or,
663  * if you know the interface has already been loaded,
664  * g_type_default_interface_peek().
665  *
666  * Since: 2.4
667  *
668  * Returns: (transfer none): the #GParamSpec for the property of the
669  *          interface with the name @property_name, or %NULL if no
670  *          such property exists.
671  */
672 GParamSpec*
673 g_object_interface_find_property (gpointer      g_iface,
674                                   const gchar  *property_name)
675 {
676   GTypeInterface *iface_class = g_iface;
677         
678   g_return_val_if_fail (G_TYPE_IS_INTERFACE (iface_class->g_type), NULL);
679   g_return_val_if_fail (property_name != NULL, NULL);
680   
681   return g_param_spec_pool_lookup (pspec_pool,
682                                    property_name,
683                                    iface_class->g_type,
684                                    FALSE);
685 }
686
687 /**
688  * g_object_class_override_property:
689  * @oclass: a #GObjectClass
690  * @property_id: the new property ID
691  * @name: the name of a property registered in a parent class or
692  *  in an interface of this class.
693  *
694  * Registers @property_id as referring to a property with the
695  * name @name in a parent class or in an interface implemented
696  * by @oclass. This allows this class to <firstterm>override</firstterm>
697  * a property implementation in a parent class or to provide
698  * the implementation of a property from an interface.
699  *
700  * <note>
701  * Internally, overriding is implemented by creating a property of type
702  * #GParamSpecOverride; generally operations that query the properties of
703  * the object class, such as g_object_class_find_property() or
704  * g_object_class_list_properties() will return the overridden
705  * property. However, in one case, the @construct_properties argument of
706  * the @constructor virtual function, the #GParamSpecOverride is passed
707  * instead, so that the @param_id field of the #GParamSpec will be
708  * correct.  For virtually all uses, this makes no difference. If you
709  * need to get the overridden property, you can call
710  * g_param_spec_get_redirect_target().
711  * </note>
712  *
713  * Since: 2.4
714  */
715 void
716 g_object_class_override_property (GObjectClass *oclass,
717                                   guint         property_id,
718                                   const gchar  *name)
719 {
720   GParamSpec *overridden = NULL;
721   GParamSpec *new;
722   GType parent_type;
723   
724   g_return_if_fail (G_IS_OBJECT_CLASS (oclass));
725   g_return_if_fail (property_id > 0);
726   g_return_if_fail (name != NULL);
727
728   /* Find the overridden property; first check parent types
729    */
730   parent_type = g_type_parent (G_OBJECT_CLASS_TYPE (oclass));
731   if (parent_type != G_TYPE_NONE)
732     overridden = g_param_spec_pool_lookup (pspec_pool,
733                                            name,
734                                            parent_type,
735                                            TRUE);
736   if (!overridden)
737     {
738       GType *ifaces;
739       guint n_ifaces;
740       
741       /* Now check interfaces
742        */
743       ifaces = g_type_interfaces (G_OBJECT_CLASS_TYPE (oclass), &n_ifaces);
744       while (n_ifaces-- && !overridden)
745         {
746           overridden = g_param_spec_pool_lookup (pspec_pool,
747                                                  name,
748                                                  ifaces[n_ifaces],
749                                                  FALSE);
750         }
751       
752       g_free (ifaces);
753     }
754
755   if (!overridden)
756     {
757       g_warning ("%s: Can't find property to override for '%s::%s'",
758                  G_STRFUNC, G_OBJECT_CLASS_NAME (oclass), name);
759       return;
760     }
761
762   new = g_param_spec_override (name, overridden);
763   g_object_class_install_property (oclass, property_id, new);
764 }
765
766 /**
767  * g_object_class_list_properties:
768  * @oclass: a #GObjectClass
769  * @n_properties: (out): return location for the length of the returned array
770  *
771  * Get an array of #GParamSpec* for all properties of a class.
772  *
773  * Returns: (array length=n_properties) (transfer container): an array of
774  *          #GParamSpec* which should be freed after use
775  */
776 GParamSpec** /* free result */
777 g_object_class_list_properties (GObjectClass *class,
778                                 guint        *n_properties_p)
779 {
780   GParamSpec **pspecs;
781   guint n;
782
783   g_return_val_if_fail (G_IS_OBJECT_CLASS (class), NULL);
784
785   pspecs = g_param_spec_pool_list (pspec_pool,
786                                    G_OBJECT_CLASS_TYPE (class),
787                                    &n);
788   if (n_properties_p)
789     *n_properties_p = n;
790
791   return pspecs;
792 }
793
794 /**
795  * g_object_interface_list_properties:
796  * @g_iface: any interface vtable for the interface, or the default
797  *  vtable for the interface
798  * @n_properties_p: (out): location to store number of properties returned.
799  *
800  * Lists the properties of an interface.Generally, the interface
801  * vtable passed in as @g_iface will be the default vtable from
802  * g_type_default_interface_ref(), or, if you know the interface has
803  * already been loaded, g_type_default_interface_peek().
804  *
805  * Since: 2.4
806  *
807  * Returns: (array length=n_properties_p) (transfer container): a
808  *          pointer to an array of pointers to #GParamSpec
809  *          structures. The paramspecs are owned by GLib, but the
810  *          array should be freed with g_free() when you are done with
811  *          it.
812  */
813 GParamSpec**
814 g_object_interface_list_properties (gpointer      g_iface,
815                                     guint        *n_properties_p)
816 {
817   GTypeInterface *iface_class = g_iface;
818   GParamSpec **pspecs;
819   guint n;
820
821   g_return_val_if_fail (G_TYPE_IS_INTERFACE (iface_class->g_type), NULL);
822
823   pspecs = g_param_spec_pool_list (pspec_pool,
824                                    iface_class->g_type,
825                                    &n);
826   if (n_properties_p)
827     *n_properties_p = n;
828
829   return pspecs;
830 }
831
832 static void
833 g_object_init (GObject          *object,
834                GObjectClass     *class)
835 {
836   object->ref_count = 1;
837   object->qdata = NULL;
838
839   if (CLASS_HAS_PROPS (class))
840     {
841       /* freeze object's notification queue, g_object_newv() preserves pairedness */
842       g_object_notify_queue_freeze (object, &property_notify_context);
843     }
844
845   if (CLASS_HAS_CUSTOM_CONSTRUCTOR (class))
846     {
847       /* enter construction list for notify_queue_thaw() and to allow construct-only properties */
848       G_LOCK (construction_mutex);
849       construction_objects = g_slist_prepend (construction_objects, object);
850       G_UNLOCK (construction_mutex);
851     }
852
853 #ifdef  G_ENABLE_DEBUG
854   IF_DEBUG (OBJECTS)
855     {
856       G_LOCK (debug_objects);
857       debug_objects_count++;
858       g_hash_table_insert (debug_objects_ht, object, object);
859       G_UNLOCK (debug_objects);
860     }
861 #endif  /* G_ENABLE_DEBUG */
862 }
863
864 static void
865 g_object_do_set_property (GObject      *object,
866                           guint         property_id,
867                           const GValue *value,
868                           GParamSpec   *pspec)
869 {
870   switch (property_id)
871     {
872     default:
873       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec);
874       break;
875     }
876 }
877
878 static void
879 g_object_do_get_property (GObject     *object,
880                           guint        property_id,
881                           GValue      *value,
882                           GParamSpec  *pspec)
883 {
884   switch (property_id)
885     {
886     default:
887       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec);
888       break;
889     }
890 }
891
892 static void
893 g_object_real_dispose (GObject *object)
894 {
895   g_signal_handlers_destroy (object);
896   g_datalist_id_set_data (&object->qdata, quark_closure_array, NULL);
897   g_datalist_id_set_data (&object->qdata, quark_weak_refs, NULL);
898 }
899
900 static void
901 g_object_finalize (GObject *object)
902 {
903   g_datalist_clear (&object->qdata);
904   
905 #ifdef  G_ENABLE_DEBUG
906   IF_DEBUG (OBJECTS)
907     {
908       G_LOCK (debug_objects);
909       g_assert (g_hash_table_lookup (debug_objects_ht, object) == object);
910       g_hash_table_remove (debug_objects_ht, object);
911       debug_objects_count--;
912       G_UNLOCK (debug_objects);
913     }
914 #endif  /* G_ENABLE_DEBUG */
915 }
916
917
918 static void
919 g_object_dispatch_properties_changed (GObject     *object,
920                                       guint        n_pspecs,
921                                       GParamSpec **pspecs)
922 {
923   guint i;
924
925   for (i = 0; i < n_pspecs; i++)
926     g_signal_emit (object, gobject_signals[NOTIFY], g_quark_from_string (pspecs[i]->name), pspecs[i]);
927 }
928
929 /**
930  * g_object_run_dispose:
931  * @object: a #GObject
932  *
933  * Releases all references to other objects. This can be used to break
934  * reference cycles.
935  *
936  * This functions should only be called from object system implementations.
937  */
938 void
939 g_object_run_dispose (GObject *object)
940 {
941   g_return_if_fail (G_IS_OBJECT (object));
942   g_return_if_fail (object->ref_count > 0);
943
944   g_object_ref (object);
945   TRACE (GOBJECT_OBJECT_DISPOSE(object,G_TYPE_FROM_INSTANCE(object), 0));
946   G_OBJECT_GET_CLASS (object)->dispose (object);
947   TRACE (GOBJECT_OBJECT_DISPOSE_END(object,G_TYPE_FROM_INSTANCE(object), 0));
948   g_object_unref (object);
949 }
950
951 /**
952  * g_object_freeze_notify:
953  * @object: a #GObject
954  *
955  * Increases the freeze count on @object. If the freeze count is
956  * non-zero, the emission of "notify" signals on @object is
957  * stopped. The signals are queued until the freeze count is decreased
958  * to zero.
959  *
960  * This is necessary for accessors that modify multiple properties to prevent
961  * premature notification while the object is still being modified.
962  */
963 void
964 g_object_freeze_notify (GObject *object)
965 {
966   g_return_if_fail (G_IS_OBJECT (object));
967
968   if (g_atomic_int_get (&object->ref_count) == 0)
969     return;
970
971   g_object_ref (object);
972   g_object_notify_queue_freeze (object, &property_notify_context);
973   g_object_unref (object);
974 }
975
976 static inline void
977 g_object_notify_by_spec_internal (GObject    *object,
978                                   GParamSpec *pspec)
979 {
980   GObjectNotifyQueue *nqueue;
981
982   nqueue = g_object_notify_queue_freeze (object, &property_notify_context);
983   g_object_notify_queue_add (object, nqueue, pspec);
984   g_object_notify_queue_thaw (object, nqueue);
985 }
986
987 /**
988  * g_object_notify:
989  * @object: a #GObject
990  * @property_name: the name of a property installed on the class of @object.
991  *
992  * Emits a "notify" signal for the property @property_name on @object.
993  *
994  * When possible, eg. when signaling a property change from within the class
995  * that registered the property, you should use g_object_notify_by_pspec()
996  * instead.
997  */
998 void
999 g_object_notify (GObject     *object,
1000                  const gchar *property_name)
1001 {
1002   GParamSpec *pspec;
1003   
1004   g_return_if_fail (G_IS_OBJECT (object));
1005   g_return_if_fail (property_name != NULL);
1006   if (g_atomic_int_get (&object->ref_count) == 0)
1007     return;
1008   
1009   g_object_ref (object);
1010   /* We don't need to get the redirect target
1011    * (by, e.g. calling g_object_class_find_property())
1012    * because g_object_notify_queue_add() does that
1013    */
1014   pspec = g_param_spec_pool_lookup (pspec_pool,
1015                                     property_name,
1016                                     G_OBJECT_TYPE (object),
1017                                     TRUE);
1018
1019   if (!pspec)
1020     g_warning ("%s: object class `%s' has no property named `%s'",
1021                G_STRFUNC,
1022                G_OBJECT_TYPE_NAME (object),
1023                property_name);
1024   else
1025     g_object_notify_by_spec_internal (object, pspec);
1026   g_object_unref (object);
1027 }
1028
1029 /**
1030  * g_object_notify_by_pspec:
1031  * @object: a #GObject
1032  * @pspec: the #GParamSpec of a property installed on the class of @object.
1033  *
1034  * Emits a "notify" signal for the property specified by @pspec on @object.
1035  *
1036  * This function omits the property name lookup, hence it is faster than
1037  * g_object_notify().
1038  *
1039  * One way to avoid using g_object_notify() from within the
1040  * class that registered the properties, and using g_object_notify_by_pspec()
1041  * instead, is to store the GParamSpec used with
1042  * g_object_class_install_property() inside a static array, e.g.:
1043  *
1044  *|[
1045  *   enum
1046  *   {
1047  *     PROP_0,
1048  *     PROP_FOO,
1049  *     PROP_LAST
1050  *   };
1051  *
1052  *   static GParamSpec *properties[PROP_LAST];
1053  *
1054  *   static void
1055  *   my_object_class_init (MyObjectClass *klass)
1056  *   {
1057  *     properties[PROP_FOO] = g_param_spec_int ("foo", "Foo", "The foo",
1058  *                                              0, 100,
1059  *                                              50,
1060  *                                              G_PARAM_READWRITE);
1061  *     g_object_class_install_property (gobject_class,
1062  *                                      PROP_FOO,
1063  *                                      properties[PROP_FOO]);
1064  *   }
1065  * ]|
1066  *
1067  * and then notify a change on the "foo" property with:
1068  *
1069  * |[
1070  *   g_object_notify_by_pspec (self, properties[PROP_FOO]);
1071  * ]|
1072  *
1073  * Since: 2.26
1074  */
1075 void
1076 g_object_notify_by_pspec (GObject    *object,
1077                           GParamSpec *pspec)
1078 {
1079
1080   g_return_if_fail (G_IS_OBJECT (object));
1081   g_return_if_fail (G_IS_PARAM_SPEC (pspec));
1082
1083   g_object_ref (object);
1084   g_object_notify_by_spec_internal (object, pspec);
1085   g_object_unref (object);
1086 }
1087
1088 /**
1089  * g_object_thaw_notify:
1090  * @object: a #GObject
1091  *
1092  * Reverts the effect of a previous call to
1093  * g_object_freeze_notify(). The freeze count is decreased on @object
1094  * and when it reaches zero, all queued "notify" signals are emitted.
1095  *
1096  * It is an error to call this function when the freeze count is zero.
1097  */
1098 void
1099 g_object_thaw_notify (GObject *object)
1100 {
1101   GObjectNotifyQueue *nqueue;
1102   
1103   g_return_if_fail (G_IS_OBJECT (object));
1104   if (g_atomic_int_get (&object->ref_count) == 0)
1105     return;
1106   
1107   g_object_ref (object);
1108
1109   /* FIXME: Freezing is the only way to get at the notify queue.
1110    * So we freeze once and then thaw twice.
1111    */
1112   nqueue = g_object_notify_queue_freeze (object,  &property_notify_context);
1113   g_object_notify_queue_thaw (object, nqueue);
1114   g_object_notify_queue_thaw (object, nqueue);
1115
1116   g_object_unref (object);
1117 }
1118
1119 static inline void
1120 object_get_property (GObject     *object,
1121                      GParamSpec  *pspec,
1122                      GValue      *value)
1123 {
1124   GObjectClass *class = g_type_class_peek (pspec->owner_type);
1125   guint param_id = PARAM_SPEC_PARAM_ID (pspec);
1126   GParamSpec *redirect;
1127
1128   if (class == NULL)
1129     {
1130       g_warning ("'%s::%s' is not a valid property name; '%s' is not a GObject subtype",
1131                  g_type_name (pspec->owner_type), pspec->name, g_type_name (pspec->owner_type));
1132       return;
1133     }
1134
1135   redirect = g_param_spec_get_redirect_target (pspec);
1136   if (redirect)
1137     pspec = redirect;    
1138   
1139   class->get_property (object, param_id, value, pspec);
1140 }
1141
1142 static inline void
1143 object_set_property (GObject             *object,
1144                      GParamSpec          *pspec,
1145                      const GValue        *value,
1146                      GObjectNotifyQueue  *nqueue)
1147 {
1148   GValue tmp_value = { 0, };
1149   GObjectClass *class = g_type_class_peek (pspec->owner_type);
1150   guint param_id = PARAM_SPEC_PARAM_ID (pspec);
1151   GParamSpec *redirect;
1152   static gchar* enable_diagnostic = NULL;
1153
1154   if (class == NULL)
1155     {
1156       g_warning ("'%s::%s' is not a valid property name; '%s' is not a GObject subtype",
1157                  g_type_name (pspec->owner_type), pspec->name, g_type_name (pspec->owner_type));
1158       return;
1159     }
1160
1161   redirect = g_param_spec_get_redirect_target (pspec);
1162   if (redirect)
1163     pspec = redirect;
1164
1165   if (G_UNLIKELY (!enable_diagnostic))
1166     {
1167       enable_diagnostic = g_getenv ("G_ENABLE_DIAGNOSTIC");
1168       if (!enable_diagnostic)
1169         enable_diagnostic = "0";
1170     }
1171
1172   if (enable_diagnostic[0] == '1')
1173     {
1174       if (pspec->flags & G_PARAM_DEPRECATED)
1175         g_warning ("The property %s::%s is deprecated and shouldn't be used "
1176                    "anymore. It will be removed in a future version.",
1177                    G_OBJECT_TYPE_NAME (object), pspec->name);
1178     }
1179
1180   /* provide a copy to work from, convert (if necessary) and validate */
1181   g_value_init (&tmp_value, pspec->value_type);
1182   if (!g_value_transform (value, &tmp_value))
1183     g_warning ("unable to set property `%s' of type `%s' from value of type `%s'",
1184                pspec->name,
1185                g_type_name (pspec->value_type),
1186                G_VALUE_TYPE_NAME (value));
1187   else if (g_param_value_validate (pspec, &tmp_value) && !(pspec->flags & G_PARAM_LAX_VALIDATION))
1188     {
1189       gchar *contents = g_strdup_value_contents (value);
1190
1191       g_warning ("value \"%s\" of type `%s' is invalid or out of range for property `%s' of type `%s'",
1192                  contents,
1193                  G_VALUE_TYPE_NAME (value),
1194                  pspec->name,
1195                  g_type_name (pspec->value_type));
1196       g_free (contents);
1197     }
1198   else
1199     {
1200       class->set_property (object, param_id, &tmp_value, pspec);
1201       g_object_notify_queue_add (object, nqueue, pspec);
1202     }
1203   g_value_unset (&tmp_value);
1204 }
1205
1206 static void
1207 object_interface_check_properties (gpointer func_data,
1208                                    gpointer g_iface)
1209 {
1210   GTypeInterface *iface_class = g_iface;
1211   GObjectClass *class;
1212   GType iface_type = iface_class->g_type;
1213   GParamSpec **pspecs;
1214   guint n;
1215
1216   class = g_type_class_ref (iface_class->g_instance_type);
1217
1218   if (!G_IS_OBJECT_CLASS (class))
1219     return;
1220
1221   pspecs = g_param_spec_pool_list (pspec_pool, iface_type, &n);
1222
1223   while (n--)
1224     {
1225       GParamSpec *class_pspec = g_param_spec_pool_lookup (pspec_pool,
1226                                                           pspecs[n]->name,
1227                                                           G_OBJECT_CLASS_TYPE (class),
1228                                                           TRUE);
1229
1230       if (!class_pspec)
1231         {
1232           g_critical ("Object class %s doesn't implement property "
1233                       "'%s' from interface '%s'",
1234                       g_type_name (G_OBJECT_CLASS_TYPE (class)),
1235                       pspecs[n]->name,
1236                       g_type_name (iface_type));
1237
1238           continue;
1239         }
1240
1241       /* The implementation paramspec must have a less restrictive
1242        * type than the interface parameter spec for set() and a
1243        * more restrictive type for get(). We just require equality,
1244        * rather than doing something more complicated checking
1245        * the READABLE and WRITABLE flags. We also simplify here
1246        * by only checking the value type, not the G_PARAM_SPEC_TYPE.
1247        */
1248       if (class_pspec &&
1249           !g_type_is_a (pspecs[n]->value_type,
1250                         class_pspec->value_type))
1251         {
1252           g_critical ("Property '%s' on class '%s' has type '%s' "
1253                       "which is different from the type '%s', "
1254                       "of the property on interface '%s'\n",
1255                       pspecs[n]->name,
1256                       g_type_name (G_OBJECT_CLASS_TYPE (class)),
1257                       g_type_name (G_PARAM_SPEC_VALUE_TYPE (class_pspec)),
1258                       g_type_name (G_PARAM_SPEC_VALUE_TYPE (pspecs[n])),
1259                       g_type_name (iface_type));
1260         }
1261
1262 #define SUBSET(a,b,mask) (((a) & ~(b) & (mask)) == 0)
1263
1264       /* CONSTRUCT and CONSTRUCT_ONLY add restrictions.
1265        * READABLE and WRITABLE remove restrictions. The implementation
1266        * paramspec must have less restrictive flags.
1267        */
1268       if (class_pspec &&
1269           (!SUBSET (class_pspec->flags,
1270                     pspecs[n]->flags,
1271                     G_PARAM_CONSTRUCT | G_PARAM_CONSTRUCT_ONLY) ||
1272            !SUBSET (pspecs[n]->flags,
1273                     class_pspec->flags,
1274                     G_PARAM_READABLE | G_PARAM_WRITABLE)))
1275         {
1276           g_critical ("Flags for property '%s' on class '%s' "
1277                       "are not compatible with the property on"
1278                       "interface '%s'\n",
1279                       pspecs[n]->name,
1280                       g_type_name (G_OBJECT_CLASS_TYPE (class)),
1281                       g_type_name (iface_type));
1282         }
1283 #undef SUBSET
1284     }
1285
1286   g_free (pspecs);
1287
1288   g_type_class_unref (class);
1289 }
1290
1291 GType
1292 g_object_get_type (void)
1293 {
1294     return G_TYPE_OBJECT;
1295 }
1296
1297 /**
1298  * g_object_new: (skip)
1299  * @object_type: the type id of the #GObject subtype to instantiate
1300  * @first_property_name: the name of the first property
1301  * @...: the value of the first property, followed optionally by more
1302  *  name/value pairs, followed by %NULL
1303  *
1304  * Creates a new instance of a #GObject subtype and sets its properties.
1305  *
1306  * Construction parameters (see #G_PARAM_CONSTRUCT, #G_PARAM_CONSTRUCT_ONLY)
1307  * which are not explicitly specified are set to their default values.
1308  *
1309  * Returns: (transfer full): a new instance of @object_type
1310  */
1311 gpointer
1312 g_object_new (GType        object_type,
1313               const gchar *first_property_name,
1314               ...)
1315 {
1316   GObject *object;
1317   va_list var_args;
1318   
1319   g_return_val_if_fail (G_TYPE_IS_OBJECT (object_type), NULL);
1320   
1321   /* short circuit for calls supplying no properties */
1322   if (!first_property_name)
1323     return g_object_newv (object_type, 0, NULL);
1324
1325   va_start (var_args, first_property_name);
1326   object = g_object_new_valist (object_type, first_property_name, var_args);
1327   va_end (var_args);
1328   
1329   return object;
1330 }
1331
1332 static gboolean
1333 slist_maybe_remove (GSList       **slist,
1334                     gconstpointer  data)
1335 {
1336   GSList *last = NULL, *node = *slist;
1337   while (node)
1338     {
1339       if (node->data == data)
1340         {
1341           if (last)
1342             last->next = node->next;
1343           else
1344             *slist = node->next;
1345           g_slist_free_1 (node);
1346           return TRUE;
1347         }
1348       last = node;
1349       node = last->next;
1350     }
1351   return FALSE;
1352 }
1353
1354 static inline gboolean
1355 object_in_construction_list (GObject *object)
1356 {
1357   gboolean in_construction;
1358   G_LOCK (construction_mutex);
1359   in_construction = g_slist_find (construction_objects, object) != NULL;
1360   G_UNLOCK (construction_mutex);
1361   return in_construction;
1362 }
1363
1364 /**
1365  * g_object_newv:
1366  * @object_type: the type id of the #GObject subtype to instantiate
1367  * @n_parameters: the length of the @parameters array
1368  * @parameters: (array length=n_parameters): an array of #GParameter
1369  *
1370  * Creates a new instance of a #GObject subtype and sets its properties.
1371  *
1372  * Construction parameters (see #G_PARAM_CONSTRUCT, #G_PARAM_CONSTRUCT_ONLY)
1373  * which are not explicitly specified are set to their default values.
1374  *
1375  * Rename to: g_object_new
1376  * Returns: (type GObject.Object) (transfer full): a new instance of
1377  * @object_type
1378  */
1379 gpointer
1380 g_object_newv (GType       object_type,
1381                guint       n_parameters,
1382                GParameter *parameters)
1383 {
1384   GObjectConstructParam *cparams = NULL, *oparams;
1385   GObjectNotifyQueue *nqueue = NULL; /* shouldn't be initialized, just to silence compiler */
1386   GObject *object;
1387   GObjectClass *class, *unref_class = NULL;
1388   GSList *slist;
1389   guint n_total_cparams = 0, n_cparams = 0, n_oparams = 0, n_cvalues;
1390   GValue *cvalues;
1391   GList *clist = NULL;
1392   gboolean newly_constructed;
1393   guint i;
1394
1395   g_return_val_if_fail (G_TYPE_IS_OBJECT (object_type), NULL);
1396
1397   class = g_type_class_peek_static (object_type);
1398   if (!class)
1399     class = unref_class = g_type_class_ref (object_type);
1400   for (slist = class->construct_properties; slist; slist = slist->next)
1401     {
1402       clist = g_list_prepend (clist, slist->data);
1403       n_total_cparams += 1;
1404     }
1405
1406   if (n_parameters == 0 && n_total_cparams == 0)
1407     {
1408       /* This is a simple object with no construct properties, and
1409        * no properties are being set, so short circuit the parameter
1410        * handling. This speeds up simple object construction.
1411        */
1412       oparams = NULL;
1413       object = class->constructor (object_type, 0, NULL);
1414       goto did_construction;
1415     }
1416
1417   /* collect parameters, sort into construction and normal ones */
1418   oparams = g_new (GObjectConstructParam, n_parameters);
1419   cparams = g_new (GObjectConstructParam, n_total_cparams);
1420   for (i = 0; i < n_parameters; i++)
1421     {
1422       GValue *value = &parameters[i].value;
1423       GParamSpec *pspec = g_param_spec_pool_lookup (pspec_pool,
1424                                                     parameters[i].name,
1425                                                     object_type,
1426                                                     TRUE);
1427       if (!pspec)
1428         {
1429           g_warning ("%s: object class `%s' has no property named `%s'",
1430                      G_STRFUNC,
1431                      g_type_name (object_type),
1432                      parameters[i].name);
1433           continue;
1434         }
1435       if (!(pspec->flags & G_PARAM_WRITABLE))
1436         {
1437           g_warning ("%s: property `%s' of object class `%s' is not writable",
1438                      G_STRFUNC,
1439                      pspec->name,
1440                      g_type_name (object_type));
1441           continue;
1442         }
1443       if (pspec->flags & (G_PARAM_CONSTRUCT | G_PARAM_CONSTRUCT_ONLY))
1444         {
1445           GList *list = g_list_find (clist, pspec);
1446
1447           if (!list)
1448             {
1449               g_warning ("%s: construct property \"%s\" for object `%s' can't be set twice",
1450                          G_STRFUNC, pspec->name, g_type_name (object_type));
1451               continue;
1452             }
1453           cparams[n_cparams].pspec = pspec;
1454           cparams[n_cparams].value = value;
1455           n_cparams++;
1456           if (!list->prev)
1457             clist = list->next;
1458           else
1459             list->prev->next = list->next;
1460           if (list->next)
1461             list->next->prev = list->prev;
1462           g_list_free_1 (list);
1463         }
1464       else
1465         {
1466           oparams[n_oparams].pspec = pspec;
1467           oparams[n_oparams].value = value;
1468           n_oparams++;
1469         }
1470     }
1471
1472   /* set remaining construction properties to default values */
1473   n_cvalues = n_total_cparams - n_cparams;
1474   cvalues = g_new (GValue, n_cvalues);
1475   while (clist)
1476     {
1477       GList *tmp = clist->next;
1478       GParamSpec *pspec = clist->data;
1479       GValue *value = cvalues + n_total_cparams - n_cparams - 1;
1480
1481       value->g_type = 0;
1482       g_value_init (value, pspec->value_type);
1483       g_param_value_set_default (pspec, value);
1484
1485       cparams[n_cparams].pspec = pspec;
1486       cparams[n_cparams].value = value;
1487       n_cparams++;
1488
1489       g_list_free_1 (clist);
1490       clist = tmp;
1491     }
1492
1493   /* construct object from construction parameters */
1494   object = class->constructor (object_type, n_total_cparams, cparams);
1495   /* free construction values */
1496   g_free (cparams);
1497   while (n_cvalues--)
1498     g_value_unset (cvalues + n_cvalues);
1499   g_free (cvalues);
1500
1501  did_construction:
1502   if (CLASS_HAS_CUSTOM_CONSTRUCTOR (class))
1503     {
1504       /* adjust freeze_count according to g_object_init() and remaining properties */
1505       G_LOCK (construction_mutex);
1506       newly_constructed = slist_maybe_remove (&construction_objects, object);
1507       G_UNLOCK (construction_mutex);
1508     }
1509   else
1510     newly_constructed = TRUE;
1511
1512   if (CLASS_HAS_PROPS (class))
1513     {
1514       if (newly_constructed || n_oparams)
1515         nqueue = g_object_notify_queue_freeze (object, &property_notify_context);
1516       if (newly_constructed)
1517         g_object_notify_queue_thaw (object, nqueue);
1518     }
1519
1520   /* run 'constructed' handler if there is a custom one */
1521   if (newly_constructed && CLASS_HAS_CUSTOM_CONSTRUCTED (class))
1522     class->constructed (object);
1523
1524   /* set remaining properties */
1525   for (i = 0; i < n_oparams; i++)
1526     object_set_property (object, oparams[i].pspec, oparams[i].value, nqueue);
1527   g_free (oparams);
1528
1529   if (CLASS_HAS_PROPS (class))
1530     {
1531       /* release our own freeze count and handle notifications */
1532       if (newly_constructed || n_oparams)
1533         g_object_notify_queue_thaw (object, nqueue);
1534     }
1535
1536   if (unref_class)
1537     g_type_class_unref (unref_class);
1538
1539   return object;
1540 }
1541
1542 /**
1543  * g_object_new_valist: (skip)
1544  * @object_type: the type id of the #GObject subtype to instantiate
1545  * @first_property_name: the name of the first property
1546  * @var_args: the value of the first property, followed optionally by more
1547  *  name/value pairs, followed by %NULL
1548  *
1549  * Creates a new instance of a #GObject subtype and sets its properties.
1550  *
1551  * Construction parameters (see #G_PARAM_CONSTRUCT, #G_PARAM_CONSTRUCT_ONLY)
1552  * which are not explicitly specified are set to their default values.
1553  *
1554  * Returns: a new instance of @object_type
1555  */
1556 GObject*
1557 g_object_new_valist (GType        object_type,
1558                      const gchar *first_property_name,
1559                      va_list      var_args)
1560 {
1561   GObjectClass *class;
1562   GParameter *params;
1563   const gchar *name;
1564   GObject *object;
1565   guint n_params = 0, n_alloced_params = 16;
1566   
1567   g_return_val_if_fail (G_TYPE_IS_OBJECT (object_type), NULL);
1568
1569   if (!first_property_name)
1570     return g_object_newv (object_type, 0, NULL);
1571
1572   class = g_type_class_ref (object_type);
1573
1574   params = g_new0 (GParameter, n_alloced_params);
1575   name = first_property_name;
1576   while (name)
1577     {
1578       gchar *error = NULL;
1579       GParamSpec *pspec = g_param_spec_pool_lookup (pspec_pool,
1580                                                     name,
1581                                                     object_type,
1582                                                     TRUE);
1583       if (!pspec)
1584         {
1585           g_warning ("%s: object class `%s' has no property named `%s'",
1586                      G_STRFUNC,
1587                      g_type_name (object_type),
1588                      name);
1589           break;
1590         }
1591       if (n_params >= n_alloced_params)
1592         {
1593           n_alloced_params += 16;
1594           params = g_renew (GParameter, params, n_alloced_params);
1595           memset (params + n_params, 0, 16 * (sizeof *params));
1596         }
1597       params[n_params].name = name;
1598       G_VALUE_COLLECT_INIT (&params[n_params].value, pspec->value_type,
1599                             var_args, 0, &error);
1600       if (error)
1601         {
1602           g_warning ("%s: %s", G_STRFUNC, error);
1603           g_free (error);
1604           g_value_unset (&params[n_params].value);
1605           break;
1606         }
1607       n_params++;
1608       name = va_arg (var_args, gchar*);
1609     }
1610
1611   object = g_object_newv (object_type, n_params, params);
1612
1613   while (n_params--)
1614     g_value_unset (&params[n_params].value);
1615   g_free (params);
1616
1617   g_type_class_unref (class);
1618
1619   return object;
1620 }
1621
1622 static GObject*
1623 g_object_constructor (GType                  type,
1624                       guint                  n_construct_properties,
1625                       GObjectConstructParam *construct_params)
1626 {
1627   GObject *object;
1628
1629   /* create object */
1630   object = (GObject*) g_type_create_instance (type);
1631   
1632   /* set construction parameters */
1633   if (n_construct_properties)
1634     {
1635       GObjectNotifyQueue *nqueue = g_object_notify_queue_freeze (object, &property_notify_context);
1636       
1637       /* set construct properties */
1638       while (n_construct_properties--)
1639         {
1640           GValue *value = construct_params->value;
1641           GParamSpec *pspec = construct_params->pspec;
1642
1643           construct_params++;
1644           object_set_property (object, pspec, value, nqueue);
1645         }
1646       g_object_notify_queue_thaw (object, nqueue);
1647       /* the notification queue is still frozen from g_object_init(), so
1648        * we don't need to handle it here, g_object_newv() takes
1649        * care of that
1650        */
1651     }
1652
1653   return object;
1654 }
1655
1656 static void
1657 g_object_constructed (GObject *object)
1658 {
1659   /* empty default impl to allow unconditional upchaining */
1660 }
1661
1662 /**
1663  * g_object_set_valist: (skip)
1664  * @object: a #GObject
1665  * @first_property_name: name of the first property to set
1666  * @var_args: value for the first property, followed optionally by more
1667  *  name/value pairs, followed by %NULL
1668  *
1669  * Sets properties on an object.
1670  */
1671 void
1672 g_object_set_valist (GObject     *object,
1673                      const gchar *first_property_name,
1674                      va_list      var_args)
1675 {
1676   GObjectNotifyQueue *nqueue;
1677   const gchar *name;
1678   
1679   g_return_if_fail (G_IS_OBJECT (object));
1680   
1681   g_object_ref (object);
1682   nqueue = g_object_notify_queue_freeze (object, &property_notify_context);
1683   
1684   name = first_property_name;
1685   while (name)
1686     {
1687       GValue value = { 0, };
1688       GParamSpec *pspec;
1689       gchar *error = NULL;
1690       
1691       pspec = g_param_spec_pool_lookup (pspec_pool,
1692                                         name,
1693                                         G_OBJECT_TYPE (object),
1694                                         TRUE);
1695       if (!pspec)
1696         {
1697           g_warning ("%s: object class `%s' has no property named `%s'",
1698                      G_STRFUNC,
1699                      G_OBJECT_TYPE_NAME (object),
1700                      name);
1701           break;
1702         }
1703       if (!(pspec->flags & G_PARAM_WRITABLE))
1704         {
1705           g_warning ("%s: property `%s' of object class `%s' is not writable",
1706                      G_STRFUNC,
1707                      pspec->name,
1708                      G_OBJECT_TYPE_NAME (object));
1709           break;
1710         }
1711       if ((pspec->flags & G_PARAM_CONSTRUCT_ONLY) && !object_in_construction_list (object))
1712         {
1713           g_warning ("%s: construct property \"%s\" for object `%s' can't be set after construction",
1714                      G_STRFUNC, pspec->name, G_OBJECT_TYPE_NAME (object));
1715           break;
1716         }
1717
1718       G_VALUE_COLLECT_INIT (&value, pspec->value_type, var_args,
1719                             0, &error);
1720       if (error)
1721         {
1722           g_warning ("%s: %s", G_STRFUNC, error);
1723           g_free (error);
1724           g_value_unset (&value);
1725           break;
1726         }
1727       
1728       object_set_property (object, pspec, &value, nqueue);
1729       g_value_unset (&value);
1730       
1731       name = va_arg (var_args, gchar*);
1732     }
1733
1734   g_object_notify_queue_thaw (object, nqueue);
1735   g_object_unref (object);
1736 }
1737
1738 /**
1739  * g_object_get_valist: (skip)
1740  * @object: a #GObject
1741  * @first_property_name: name of the first property to get
1742  * @var_args: return location for the first property, followed optionally by more
1743  *  name/return location pairs, followed by %NULL
1744  *
1745  * Gets properties of an object.
1746  *
1747  * In general, a copy is made of the property contents and the caller
1748  * is responsible for freeing the memory in the appropriate manner for
1749  * the type, for instance by calling g_free() or g_object_unref().
1750  *
1751  * See g_object_get().
1752  */
1753 void
1754 g_object_get_valist (GObject     *object,
1755                      const gchar *first_property_name,
1756                      va_list      var_args)
1757 {
1758   const gchar *name;
1759   
1760   g_return_if_fail (G_IS_OBJECT (object));
1761   
1762   g_object_ref (object);
1763   
1764   name = first_property_name;
1765   
1766   while (name)
1767     {
1768       GValue value = { 0, };
1769       GParamSpec *pspec;
1770       gchar *error;
1771       
1772       pspec = g_param_spec_pool_lookup (pspec_pool,
1773                                         name,
1774                                         G_OBJECT_TYPE (object),
1775                                         TRUE);
1776       if (!pspec)
1777         {
1778           g_warning ("%s: object class `%s' has no property named `%s'",
1779                      G_STRFUNC,
1780                      G_OBJECT_TYPE_NAME (object),
1781                      name);
1782           break;
1783         }
1784       if (!(pspec->flags & G_PARAM_READABLE))
1785         {
1786           g_warning ("%s: property `%s' of object class `%s' is not readable",
1787                      G_STRFUNC,
1788                      pspec->name,
1789                      G_OBJECT_TYPE_NAME (object));
1790           break;
1791         }
1792       
1793       g_value_init (&value, pspec->value_type);
1794       
1795       object_get_property (object, pspec, &value);
1796       
1797       G_VALUE_LCOPY (&value, var_args, 0, &error);
1798       if (error)
1799         {
1800           g_warning ("%s: %s", G_STRFUNC, error);
1801           g_free (error);
1802           g_value_unset (&value);
1803           break;
1804         }
1805       
1806       g_value_unset (&value);
1807       
1808       name = va_arg (var_args, gchar*);
1809     }
1810   
1811   g_object_unref (object);
1812 }
1813
1814 /**
1815  * g_object_set: (skip)
1816  * @object: a #GObject
1817  * @first_property_name: name of the first property to set
1818  * @...: value for the first property, followed optionally by more
1819  *  name/value pairs, followed by %NULL
1820  *
1821  * Sets properties on an object.
1822  */
1823 void
1824 g_object_set (gpointer     _object,
1825               const gchar *first_property_name,
1826               ...)
1827 {
1828   GObject *object = _object;
1829   va_list var_args;
1830   
1831   g_return_if_fail (G_IS_OBJECT (object));
1832   
1833   va_start (var_args, first_property_name);
1834   g_object_set_valist (object, first_property_name, var_args);
1835   va_end (var_args);
1836 }
1837
1838 /**
1839  * g_object_get: (skip)
1840  * @object: a #GObject
1841  * @first_property_name: name of the first property to get
1842  * @...: return location for the first property, followed optionally by more
1843  *  name/return location pairs, followed by %NULL
1844  *
1845  * Gets properties of an object.
1846  *
1847  * In general, a copy is made of the property contents and the caller
1848  * is responsible for freeing the memory in the appropriate manner for
1849  * the type, for instance by calling g_free() or g_object_unref().
1850  *
1851  * <example>
1852  * <title>Using g_object_get(<!-- -->)</title>
1853  * An example of using g_object_get() to get the contents
1854  * of three properties - one of type #G_TYPE_INT,
1855  * one of type #G_TYPE_STRING, and one of type #G_TYPE_OBJECT:
1856  * <programlisting>
1857  *  gint intval;
1858  *  gchar *strval;
1859  *  GObject *objval;
1860  *
1861  *  g_object_get (my_object,
1862  *                "int-property", &intval,
1863  *                "str-property", &strval,
1864  *                "obj-property", &objval,
1865  *                NULL);
1866  *
1867  *  // Do something with intval, strval, objval
1868  *
1869  *  g_free (strval);
1870  *  g_object_unref (objval);
1871  * </programlisting>
1872  * </example>
1873  */
1874 void
1875 g_object_get (gpointer     _object,
1876               const gchar *first_property_name,
1877               ...)
1878 {
1879   GObject *object = _object;
1880   va_list var_args;
1881   
1882   g_return_if_fail (G_IS_OBJECT (object));
1883   
1884   va_start (var_args, first_property_name);
1885   g_object_get_valist (object, first_property_name, var_args);
1886   va_end (var_args);
1887 }
1888
1889 /**
1890  * g_object_set_property:
1891  * @object: a #GObject
1892  * @property_name: the name of the property to set
1893  * @value: the value
1894  *
1895  * Sets a property on an object.
1896  */
1897 void
1898 g_object_set_property (GObject      *object,
1899                        const gchar  *property_name,
1900                        const GValue *value)
1901 {
1902   GObjectNotifyQueue *nqueue;
1903   GParamSpec *pspec;
1904   
1905   g_return_if_fail (G_IS_OBJECT (object));
1906   g_return_if_fail (property_name != NULL);
1907   g_return_if_fail (G_IS_VALUE (value));
1908   
1909   g_object_ref (object);
1910   nqueue = g_object_notify_queue_freeze (object, &property_notify_context);
1911   
1912   pspec = g_param_spec_pool_lookup (pspec_pool,
1913                                     property_name,
1914                                     G_OBJECT_TYPE (object),
1915                                     TRUE);
1916   if (!pspec)
1917     g_warning ("%s: object class `%s' has no property named `%s'",
1918                G_STRFUNC,
1919                G_OBJECT_TYPE_NAME (object),
1920                property_name);
1921   else if (!(pspec->flags & G_PARAM_WRITABLE))
1922     g_warning ("%s: property `%s' of object class `%s' is not writable",
1923                G_STRFUNC,
1924                pspec->name,
1925                G_OBJECT_TYPE_NAME (object));
1926   else if ((pspec->flags & G_PARAM_CONSTRUCT_ONLY) && !object_in_construction_list (object))
1927     g_warning ("%s: construct property \"%s\" for object `%s' can't be set after construction",
1928                G_STRFUNC, pspec->name, G_OBJECT_TYPE_NAME (object));
1929   else
1930     object_set_property (object, pspec, value, nqueue);
1931   
1932   g_object_notify_queue_thaw (object, nqueue);
1933   g_object_unref (object);
1934 }
1935
1936 /**
1937  * g_object_get_property:
1938  * @object: a #GObject
1939  * @property_name: the name of the property to get
1940  * @value: return location for the property value
1941  *
1942  * Gets a property of an object. @value must have been initialized to the
1943  * expected type of the property (or a type to which the expected type can be
1944  * transformed) using g_value_init().
1945  *
1946  * In general, a copy is made of the property contents and the caller is
1947  * responsible for freeing the memory by calling g_value_unset().
1948  *
1949  * Note that g_object_get_property() is really intended for language
1950  * bindings, g_object_get() is much more convenient for C programming.
1951  */
1952 void
1953 g_object_get_property (GObject     *object,
1954                        const gchar *property_name,
1955                        GValue      *value)
1956 {
1957   GParamSpec *pspec;
1958   
1959   g_return_if_fail (G_IS_OBJECT (object));
1960   g_return_if_fail (property_name != NULL);
1961   g_return_if_fail (G_IS_VALUE (value));
1962   
1963   g_object_ref (object);
1964   
1965   pspec = g_param_spec_pool_lookup (pspec_pool,
1966                                     property_name,
1967                                     G_OBJECT_TYPE (object),
1968                                     TRUE);
1969   if (!pspec)
1970     g_warning ("%s: object class `%s' has no property named `%s'",
1971                G_STRFUNC,
1972                G_OBJECT_TYPE_NAME (object),
1973                property_name);
1974   else if (!(pspec->flags & G_PARAM_READABLE))
1975     g_warning ("%s: property `%s' of object class `%s' is not readable",
1976                G_STRFUNC,
1977                pspec->name,
1978                G_OBJECT_TYPE_NAME (object));
1979   else
1980     {
1981       GValue *prop_value, tmp_value = { 0, };
1982       
1983       /* auto-conversion of the callers value type
1984        */
1985       if (G_VALUE_TYPE (value) == pspec->value_type)
1986         {
1987           g_value_reset (value);
1988           prop_value = value;
1989         }
1990       else if (!g_value_type_transformable (pspec->value_type, G_VALUE_TYPE (value)))
1991         {
1992           g_warning ("%s: can't retrieve property `%s' of type `%s' as value of type `%s'",
1993                      G_STRFUNC, pspec->name,
1994                      g_type_name (pspec->value_type),
1995                      G_VALUE_TYPE_NAME (value));
1996           g_object_unref (object);
1997           return;
1998         }
1999       else
2000         {
2001           g_value_init (&tmp_value, pspec->value_type);
2002           prop_value = &tmp_value;
2003         }
2004       object_get_property (object, pspec, prop_value);
2005       if (prop_value != value)
2006         {
2007           g_value_transform (prop_value, value);
2008           g_value_unset (&tmp_value);
2009         }
2010     }
2011   
2012   g_object_unref (object);
2013 }
2014
2015 /**
2016  * g_object_connect: (skip)
2017  * @object: a #GObject
2018  * @signal_spec: the spec for the first signal
2019  * @...: #GCallback for the first signal, followed by data for the
2020  *       first signal, followed optionally by more signal
2021  *       spec/callback/data triples, followed by %NULL
2022  *
2023  * A convenience function to connect multiple signals at once.
2024  *
2025  * The signal specs expected by this function have the form
2026  * "modifier::signal_name", where modifier can be one of the following:
2027  * <variablelist>
2028  * <varlistentry>
2029  * <term>signal</term>
2030  * <listitem><para>
2031  * equivalent to <literal>g_signal_connect_data (..., NULL, 0)</literal>
2032  * </para></listitem>
2033  * </varlistentry>
2034  * <varlistentry>
2035  * <term>object_signal</term>
2036  * <term>object-signal</term>
2037  * <listitem><para>
2038  * equivalent to <literal>g_signal_connect_object (..., 0)</literal>
2039  * </para></listitem>
2040  * </varlistentry>
2041  * <varlistentry>
2042  * <term>swapped_signal</term>
2043  * <term>swapped-signal</term>
2044  * <listitem><para>
2045  * equivalent to <literal>g_signal_connect_data (..., NULL, G_CONNECT_SWAPPED)</literal>
2046  * </para></listitem>
2047  * </varlistentry>
2048  * <varlistentry>
2049  * <term>swapped_object_signal</term>
2050  * <term>swapped-object-signal</term>
2051  * <listitem><para>
2052  * equivalent to <literal>g_signal_connect_object (..., G_CONNECT_SWAPPED)</literal>
2053  * </para></listitem>
2054  * </varlistentry>
2055  * <varlistentry>
2056  * <term>signal_after</term>
2057  * <term>signal-after</term>
2058  * <listitem><para>
2059  * equivalent to <literal>g_signal_connect_data (..., NULL, G_CONNECT_AFTER)</literal>
2060  * </para></listitem>
2061  * </varlistentry>
2062  * <varlistentry>
2063  * <term>object_signal_after</term>
2064  * <term>object-signal-after</term>
2065  * <listitem><para>
2066  * equivalent to <literal>g_signal_connect_object (..., G_CONNECT_AFTER)</literal>
2067  * </para></listitem>
2068  * </varlistentry>
2069  * <varlistentry>
2070  * <term>swapped_signal_after</term>
2071  * <term>swapped-signal-after</term>
2072  * <listitem><para>
2073  * equivalent to <literal>g_signal_connect_data (..., NULL, G_CONNECT_SWAPPED | G_CONNECT_AFTER)</literal>
2074  * </para></listitem>
2075  * </varlistentry>
2076  * <varlistentry>
2077  * <term>swapped_object_signal_after</term>
2078  * <term>swapped-object-signal-after</term>
2079  * <listitem><para>
2080  * equivalent to <literal>g_signal_connect_object (..., G_CONNECT_SWAPPED | G_CONNECT_AFTER)</literal>
2081  * </para></listitem>
2082  * </varlistentry>
2083  * </variablelist>
2084  *
2085  * |[
2086  *   menu->toplevel = g_object_connect (g_object_new (GTK_TYPE_WINDOW,
2087  *                                                 "type", GTK_WINDOW_POPUP,
2088  *                                                 "child", menu,
2089  *                                                 NULL),
2090  *                                   "signal::event", gtk_menu_window_event, menu,
2091  *                                   "signal::size_request", gtk_menu_window_size_request, menu,
2092  *                                   "signal::destroy", gtk_widget_destroyed, &amp;menu-&gt;toplevel,
2093  *                                   NULL);
2094  * ]|
2095  *
2096  * Returns: (transfer none): @object
2097  */
2098 gpointer
2099 g_object_connect (gpointer     _object,
2100                   const gchar *signal_spec,
2101                   ...)
2102 {
2103   GObject *object = _object;
2104   va_list var_args;
2105
2106   g_return_val_if_fail (G_IS_OBJECT (object), NULL);
2107   g_return_val_if_fail (object->ref_count > 0, object);
2108
2109   va_start (var_args, signal_spec);
2110   while (signal_spec)
2111     {
2112       GCallback callback = va_arg (var_args, GCallback);
2113       gpointer data = va_arg (var_args, gpointer);
2114
2115       if (strncmp (signal_spec, "signal::", 8) == 0)
2116         g_signal_connect_data (object, signal_spec + 8,
2117                                callback, data, NULL,
2118                                0);
2119       else if (strncmp (signal_spec, "object_signal::", 15) == 0 ||
2120                strncmp (signal_spec, "object-signal::", 15) == 0)
2121         g_signal_connect_object (object, signal_spec + 15,
2122                                  callback, data,
2123                                  0);
2124       else if (strncmp (signal_spec, "swapped_signal::", 16) == 0 ||
2125                strncmp (signal_spec, "swapped-signal::", 16) == 0)
2126         g_signal_connect_data (object, signal_spec + 16,
2127                                callback, data, NULL,
2128                                G_CONNECT_SWAPPED);
2129       else if (strncmp (signal_spec, "swapped_object_signal::", 23) == 0 ||
2130                strncmp (signal_spec, "swapped-object-signal::", 23) == 0)
2131         g_signal_connect_object (object, signal_spec + 23,
2132                                  callback, data,
2133                                  G_CONNECT_SWAPPED);
2134       else if (strncmp (signal_spec, "signal_after::", 14) == 0 ||
2135                strncmp (signal_spec, "signal-after::", 14) == 0)
2136         g_signal_connect_data (object, signal_spec + 14,
2137                                callback, data, NULL,
2138                                G_CONNECT_AFTER);
2139       else if (strncmp (signal_spec, "object_signal_after::", 21) == 0 ||
2140                strncmp (signal_spec, "object-signal-after::", 21) == 0)
2141         g_signal_connect_object (object, signal_spec + 21,
2142                                  callback, data,
2143                                  G_CONNECT_AFTER);
2144       else if (strncmp (signal_spec, "swapped_signal_after::", 22) == 0 ||
2145                strncmp (signal_spec, "swapped-signal-after::", 22) == 0)
2146         g_signal_connect_data (object, signal_spec + 22,
2147                                callback, data, NULL,
2148                                G_CONNECT_SWAPPED | G_CONNECT_AFTER);
2149       else if (strncmp (signal_spec, "swapped_object_signal_after::", 29) == 0 ||
2150                strncmp (signal_spec, "swapped-object-signal-after::", 29) == 0)
2151         g_signal_connect_object (object, signal_spec + 29,
2152                                  callback, data,
2153                                  G_CONNECT_SWAPPED | G_CONNECT_AFTER);
2154       else
2155         {
2156           g_warning ("%s: invalid signal spec \"%s\"", G_STRFUNC, signal_spec);
2157           break;
2158         }
2159       signal_spec = va_arg (var_args, gchar*);
2160     }
2161   va_end (var_args);
2162
2163   return object;
2164 }
2165
2166 /**
2167  * g_object_disconnect: (skip)
2168  * @object: a #GObject
2169  * @signal_spec: the spec for the first signal
2170  * @...: #GCallback for the first signal, followed by data for the first signal,
2171  *  followed optionally by more signal spec/callback/data triples,
2172  *  followed by %NULL
2173  *
2174  * A convenience function to disconnect multiple signals at once.
2175  *
2176  * The signal specs expected by this function have the form
2177  * "any_signal", which means to disconnect any signal with matching
2178  * callback and data, or "any_signal::signal_name", which only
2179  * disconnects the signal named "signal_name".
2180  */
2181 void
2182 g_object_disconnect (gpointer     _object,
2183                      const gchar *signal_spec,
2184                      ...)
2185 {
2186   GObject *object = _object;
2187   va_list var_args;
2188
2189   g_return_if_fail (G_IS_OBJECT (object));
2190   g_return_if_fail (object->ref_count > 0);
2191
2192   va_start (var_args, signal_spec);
2193   while (signal_spec)
2194     {
2195       GCallback callback = va_arg (var_args, GCallback);
2196       gpointer data = va_arg (var_args, gpointer);
2197       guint sid = 0, detail = 0, mask = 0;
2198
2199       if (strncmp (signal_spec, "any_signal::", 12) == 0 ||
2200           strncmp (signal_spec, "any-signal::", 12) == 0)
2201         {
2202           signal_spec += 12;
2203           mask = G_SIGNAL_MATCH_ID | G_SIGNAL_MATCH_FUNC | G_SIGNAL_MATCH_DATA;
2204         }
2205       else if (strcmp (signal_spec, "any_signal") == 0 ||
2206                strcmp (signal_spec, "any-signal") == 0)
2207         {
2208           signal_spec += 10;
2209           mask = G_SIGNAL_MATCH_FUNC | G_SIGNAL_MATCH_DATA;
2210         }
2211       else
2212         {
2213           g_warning ("%s: invalid signal spec \"%s\"", G_STRFUNC, signal_spec);
2214           break;
2215         }
2216
2217       if ((mask & G_SIGNAL_MATCH_ID) &&
2218           !g_signal_parse_name (signal_spec, G_OBJECT_TYPE (object), &sid, &detail, FALSE))
2219         g_warning ("%s: invalid signal name \"%s\"", G_STRFUNC, signal_spec);
2220       else if (!g_signal_handlers_disconnect_matched (object, mask | (detail ? G_SIGNAL_MATCH_DETAIL : 0),
2221                                                       sid, detail,
2222                                                       NULL, (gpointer)callback, data))
2223         g_warning ("%s: signal handler %p(%p) is not connected", G_STRFUNC, callback, data);
2224       signal_spec = va_arg (var_args, gchar*);
2225     }
2226   va_end (var_args);
2227 }
2228
2229 typedef struct {
2230   GObject *object;
2231   guint n_weak_refs;
2232   struct {
2233     GWeakNotify notify;
2234     gpointer    data;
2235   } weak_refs[1];  /* flexible array */
2236 } WeakRefStack;
2237
2238 static void
2239 weak_refs_notify (gpointer data)
2240 {
2241   WeakRefStack *wstack = data;
2242   guint i;
2243
2244   for (i = 0; i < wstack->n_weak_refs; i++)
2245     wstack->weak_refs[i].notify (wstack->weak_refs[i].data, wstack->object);
2246   g_free (wstack);
2247 }
2248
2249 /**
2250  * g_object_weak_ref: (skip)
2251  * @object: #GObject to reference weakly
2252  * @notify: callback to invoke before the object is freed
2253  * @data: extra data to pass to notify
2254  *
2255  * Adds a weak reference callback to an object. Weak references are
2256  * used for notification when an object is finalized. They are called
2257  * "weak references" because they allow you to safely hold a pointer
2258  * to an object without calling g_object_ref() (g_object_ref() adds a
2259  * strong reference, that is, forces the object to stay alive).
2260  */
2261 void
2262 g_object_weak_ref (GObject    *object,
2263                    GWeakNotify notify,
2264                    gpointer    data)
2265 {
2266   WeakRefStack *wstack;
2267   guint i;
2268   
2269   g_return_if_fail (G_IS_OBJECT (object));
2270   g_return_if_fail (notify != NULL);
2271   g_return_if_fail (object->ref_count >= 1);
2272
2273   G_LOCK (weak_refs_mutex);
2274   wstack = g_datalist_id_remove_no_notify (&object->qdata, quark_weak_refs);
2275   if (wstack)
2276     {
2277       i = wstack->n_weak_refs++;
2278       wstack = g_realloc (wstack, sizeof (*wstack) + sizeof (wstack->weak_refs[0]) * i);
2279     }
2280   else
2281     {
2282       wstack = g_renew (WeakRefStack, NULL, 1);
2283       wstack->object = object;
2284       wstack->n_weak_refs = 1;
2285       i = 0;
2286     }
2287   wstack->weak_refs[i].notify = notify;
2288   wstack->weak_refs[i].data = data;
2289   g_datalist_id_set_data_full (&object->qdata, quark_weak_refs, wstack, weak_refs_notify);
2290   G_UNLOCK (weak_refs_mutex);
2291 }
2292
2293 /**
2294  * g_object_weak_unref: (skip)
2295  * @object: #GObject to remove a weak reference from
2296  * @notify: callback to search for
2297  * @data: data to search for
2298  *
2299  * Removes a weak reference callback to an object.
2300  */
2301 void
2302 g_object_weak_unref (GObject    *object,
2303                      GWeakNotify notify,
2304                      gpointer    data)
2305 {
2306   WeakRefStack *wstack;
2307   gboolean found_one = FALSE;
2308
2309   g_return_if_fail (G_IS_OBJECT (object));
2310   g_return_if_fail (notify != NULL);
2311
2312   G_LOCK (weak_refs_mutex);
2313   wstack = g_datalist_id_get_data (&object->qdata, quark_weak_refs);
2314   if (wstack)
2315     {
2316       guint i;
2317
2318       for (i = 0; i < wstack->n_weak_refs; i++)
2319         if (wstack->weak_refs[i].notify == notify &&
2320             wstack->weak_refs[i].data == data)
2321           {
2322             found_one = TRUE;
2323             wstack->n_weak_refs -= 1;
2324             if (i != wstack->n_weak_refs)
2325               wstack->weak_refs[i] = wstack->weak_refs[wstack->n_weak_refs];
2326
2327             break;
2328           }
2329     }
2330   G_UNLOCK (weak_refs_mutex);
2331   if (!found_one)
2332     g_warning ("%s: couldn't find weak ref %p(%p)", G_STRFUNC, notify, data);
2333 }
2334
2335 /**
2336  * g_object_add_weak_pointer: (skip)
2337  * @object: The object that should be weak referenced.
2338  * @weak_pointer_location: (inout): The memory address of a pointer.
2339  *
2340  * Adds a weak reference from weak_pointer to @object to indicate that
2341  * the pointer located at @weak_pointer_location is only valid during
2342  * the lifetime of @object. When the @object is finalized,
2343  * @weak_pointer will be set to %NULL.
2344  */
2345 void
2346 g_object_add_weak_pointer (GObject  *object, 
2347                            gpointer *weak_pointer_location)
2348 {
2349   g_return_if_fail (G_IS_OBJECT (object));
2350   g_return_if_fail (weak_pointer_location != NULL);
2351
2352   g_object_weak_ref (object, 
2353                      (GWeakNotify) g_nullify_pointer, 
2354                      weak_pointer_location);
2355 }
2356
2357 /**
2358  * g_object_remove_weak_pointer: (skip)
2359  * @object: The object that is weak referenced.
2360  * @weak_pointer_location: (inout): The memory address of a pointer.
2361  *
2362  * Removes a weak reference from @object that was previously added
2363  * using g_object_add_weak_pointer(). The @weak_pointer_location has
2364  * to match the one used with g_object_add_weak_pointer().
2365  */
2366 void
2367 g_object_remove_weak_pointer (GObject  *object, 
2368                               gpointer *weak_pointer_location)
2369 {
2370   g_return_if_fail (G_IS_OBJECT (object));
2371   g_return_if_fail (weak_pointer_location != NULL);
2372
2373   g_object_weak_unref (object, 
2374                        (GWeakNotify) g_nullify_pointer, 
2375                        weak_pointer_location);
2376 }
2377
2378 static guint
2379 object_floating_flag_handler (GObject        *object,
2380                               gint            job)
2381 {
2382   switch (job)
2383     {
2384       gpointer oldvalue;
2385     case +1:    /* force floating if possible */
2386       do
2387         oldvalue = g_atomic_pointer_get (&object->qdata);
2388       while (!g_atomic_pointer_compare_and_exchange ((void**) &object->qdata, oldvalue,
2389                                                      (gpointer) ((gsize) oldvalue | OBJECT_FLOATING_FLAG)));
2390       return (gsize) oldvalue & OBJECT_FLOATING_FLAG;
2391     case -1:    /* sink if possible */
2392       do
2393         oldvalue = g_atomic_pointer_get (&object->qdata);
2394       while (!g_atomic_pointer_compare_and_exchange ((void**) &object->qdata, oldvalue,
2395                                                      (gpointer) ((gsize) oldvalue & ~(gsize) OBJECT_FLOATING_FLAG)));
2396       return (gsize) oldvalue & OBJECT_FLOATING_FLAG;
2397     default:    /* check floating */
2398       return 0 != ((gsize) g_atomic_pointer_get (&object->qdata) & OBJECT_FLOATING_FLAG);
2399     }
2400 }
2401
2402 /**
2403  * g_object_is_floating:
2404  * @object: (type GObject.Object): a #GObject
2405  *
2406  * Checks whether @object has a <link linkend="floating-ref">floating</link>
2407  * reference.
2408  *
2409  * Since: 2.10
2410  *
2411  * Returns: %TRUE if @object has a floating reference
2412  */
2413 gboolean
2414 g_object_is_floating (gpointer _object)
2415 {
2416   GObject *object = _object;
2417   g_return_val_if_fail (G_IS_OBJECT (object), FALSE);
2418   return floating_flag_handler (object, 0);
2419 }
2420
2421 /**
2422  * g_object_ref_sink:
2423  * @object: (type GObject.Object): a #GObject
2424  *
2425  * Increase the reference count of @object, and possibly remove the
2426  * <link linkend="floating-ref">floating</link> reference, if @object
2427  * has a floating reference.
2428  *
2429  * In other words, if the object is floating, then this call "assumes
2430  * ownership" of the floating reference, converting it to a normal
2431  * reference by clearing the floating flag while leaving the reference
2432  * count unchanged.  If the object is not floating, then this call
2433  * adds a new normal reference increasing the reference count by one.
2434  *
2435  * Since: 2.10
2436  *
2437  * Returns: (type GObject.Object) (transfer none): @object
2438  */
2439 gpointer
2440 g_object_ref_sink (gpointer _object)
2441 {
2442   GObject *object = _object;
2443   gboolean was_floating;
2444   g_return_val_if_fail (G_IS_OBJECT (object), object);
2445   g_return_val_if_fail (object->ref_count >= 1, object);
2446   g_object_ref (object);
2447   was_floating = floating_flag_handler (object, -1);
2448   if (was_floating)
2449     g_object_unref (object);
2450   return object;
2451 }
2452
2453 /**
2454  * g_object_force_floating:
2455  * @object: a #GObject
2456  *
2457  * This function is intended for #GObject implementations to re-enforce a
2458  * <link linkend="floating-ref">floating</link> object reference.
2459  * Doing this is seldomly required: all
2460  * #GInitiallyUnowned<!-- -->s are created with a floating reference which
2461  * usually just needs to be sunken by calling g_object_ref_sink().
2462  *
2463  * Since: 2.10
2464  */
2465 void
2466 g_object_force_floating (GObject *object)
2467 {
2468   g_return_if_fail (G_IS_OBJECT (object));
2469   g_return_if_fail (object->ref_count >= 1);
2470
2471   floating_flag_handler (object, +1);
2472 }
2473
2474 typedef struct {
2475   GObject *object;
2476   guint n_toggle_refs;
2477   struct {
2478     GToggleNotify notify;
2479     gpointer    data;
2480   } toggle_refs[1];  /* flexible array */
2481 } ToggleRefStack;
2482
2483 static void
2484 toggle_refs_notify (GObject *object,
2485                     gboolean is_last_ref)
2486 {
2487   ToggleRefStack tstack, *tstackptr;
2488
2489   G_LOCK (toggle_refs_mutex);
2490   tstackptr = g_datalist_id_get_data (&object->qdata, quark_toggle_refs);
2491   tstack = *tstackptr;
2492   G_UNLOCK (toggle_refs_mutex);
2493
2494   /* Reentrancy here is not as tricky as it seems, because a toggle reference
2495    * will only be notified when there is exactly one of them.
2496    */
2497   g_assert (tstack.n_toggle_refs == 1);
2498   tstack.toggle_refs[0].notify (tstack.toggle_refs[0].data, tstack.object, is_last_ref);
2499 }
2500
2501 /**
2502  * g_object_add_toggle_ref: (skip)
2503  * @object: a #GObject
2504  * @notify: a function to call when this reference is the
2505  *  last reference to the object, or is no longer
2506  *  the last reference.
2507  * @data: data to pass to @notify
2508  *
2509  * Increases the reference count of the object by one and sets a
2510  * callback to be called when all other references to the object are
2511  * dropped, or when this is already the last reference to the object
2512  * and another reference is established.
2513  *
2514  * This functionality is intended for binding @object to a proxy
2515  * object managed by another memory manager. This is done with two
2516  * paired references: the strong reference added by
2517  * g_object_add_toggle_ref() and a reverse reference to the proxy
2518  * object which is either a strong reference or weak reference.
2519  *
2520  * The setup is that when there are no other references to @object,
2521  * only a weak reference is held in the reverse direction from @object
2522  * to the proxy object, but when there are other references held to
2523  * @object, a strong reference is held. The @notify callback is called
2524  * when the reference from @object to the proxy object should be
2525  * <firstterm>toggled</firstterm> from strong to weak (@is_last_ref
2526  * true) or weak to strong (@is_last_ref false).
2527  *
2528  * Since a (normal) reference must be held to the object before
2529  * calling g_object_toggle_ref(), the initial state of the reverse
2530  * link is always strong.
2531  *
2532  * Multiple toggle references may be added to the same gobject,
2533  * however if there are multiple toggle references to an object, none
2534  * of them will ever be notified until all but one are removed.  For
2535  * this reason, you should only ever use a toggle reference if there
2536  * is important state in the proxy object.
2537  *
2538  * Since: 2.8
2539  */
2540 void
2541 g_object_add_toggle_ref (GObject       *object,
2542                          GToggleNotify  notify,
2543                          gpointer       data)
2544 {
2545   ToggleRefStack *tstack;
2546   guint i;
2547   
2548   g_return_if_fail (G_IS_OBJECT (object));
2549   g_return_if_fail (notify != NULL);
2550   g_return_if_fail (object->ref_count >= 1);
2551
2552   g_object_ref (object);
2553
2554   G_LOCK (toggle_refs_mutex);
2555   tstack = g_datalist_id_remove_no_notify (&object->qdata, quark_toggle_refs);
2556   if (tstack)
2557     {
2558       i = tstack->n_toggle_refs++;
2559       /* allocate i = tstate->n_toggle_refs - 1 positions beyond the 1 declared
2560        * in tstate->toggle_refs */
2561       tstack = g_realloc (tstack, sizeof (*tstack) + sizeof (tstack->toggle_refs[0]) * i);
2562     }
2563   else
2564     {
2565       tstack = g_renew (ToggleRefStack, NULL, 1);
2566       tstack->object = object;
2567       tstack->n_toggle_refs = 1;
2568       i = 0;
2569     }
2570
2571   /* Set a flag for fast lookup after adding the first toggle reference */
2572   if (tstack->n_toggle_refs == 1)
2573     g_datalist_set_flags (&object->qdata, OBJECT_HAS_TOGGLE_REF_FLAG);
2574   
2575   tstack->toggle_refs[i].notify = notify;
2576   tstack->toggle_refs[i].data = data;
2577   g_datalist_id_set_data_full (&object->qdata, quark_toggle_refs, tstack,
2578                                (GDestroyNotify)g_free);
2579   G_UNLOCK (toggle_refs_mutex);
2580 }
2581
2582 /**
2583  * g_object_remove_toggle_ref: (skip)
2584  * @object: a #GObject
2585  * @notify: a function to call when this reference is the
2586  *  last reference to the object, or is no longer
2587  *  the last reference.
2588  * @data: data to pass to @notify
2589  *
2590  * Removes a reference added with g_object_add_toggle_ref(). The
2591  * reference count of the object is decreased by one.
2592  *
2593  * Since: 2.8
2594  */
2595 void
2596 g_object_remove_toggle_ref (GObject       *object,
2597                             GToggleNotify  notify,
2598                             gpointer       data)
2599 {
2600   ToggleRefStack *tstack;
2601   gboolean found_one = FALSE;
2602
2603   g_return_if_fail (G_IS_OBJECT (object));
2604   g_return_if_fail (notify != NULL);
2605
2606   G_LOCK (toggle_refs_mutex);
2607   tstack = g_datalist_id_get_data (&object->qdata, quark_toggle_refs);
2608   if (tstack)
2609     {
2610       guint i;
2611
2612       for (i = 0; i < tstack->n_toggle_refs; i++)
2613         if (tstack->toggle_refs[i].notify == notify &&
2614             tstack->toggle_refs[i].data == data)
2615           {
2616             found_one = TRUE;
2617             tstack->n_toggle_refs -= 1;
2618             if (i != tstack->n_toggle_refs)
2619               tstack->toggle_refs[i] = tstack->toggle_refs[tstack->n_toggle_refs];
2620
2621             if (tstack->n_toggle_refs == 0)
2622               g_datalist_unset_flags (&object->qdata, OBJECT_HAS_TOGGLE_REF_FLAG);
2623
2624             break;
2625           }
2626     }
2627   G_UNLOCK (toggle_refs_mutex);
2628
2629   if (found_one)
2630     g_object_unref (object);
2631   else
2632     g_warning ("%s: couldn't find toggle ref %p(%p)", G_STRFUNC, notify, data);
2633 }
2634
2635 /**
2636  * g_object_ref:
2637  * @object: (type GObject.Object): a #GObject
2638  *
2639  * Increases the reference count of @object.
2640  *
2641  * Returns: (type GObject.Object) (transfer none): the same @object
2642  */
2643 gpointer
2644 g_object_ref (gpointer _object)
2645 {
2646   GObject *object = _object;
2647   gint old_val;
2648
2649   g_return_val_if_fail (G_IS_OBJECT (object), NULL);
2650   g_return_val_if_fail (object->ref_count > 0, NULL);
2651   
2652 #ifdef  G_ENABLE_DEBUG
2653   if (g_trap_object_ref == object)
2654     G_BREAKPOINT ();
2655 #endif  /* G_ENABLE_DEBUG */
2656
2657
2658   old_val = g_atomic_int_add (&object->ref_count, 1);
2659
2660   if (old_val == 1 && OBJECT_HAS_TOGGLE_REF (object))
2661     toggle_refs_notify (object, FALSE);
2662
2663   TRACE (GOBJECT_OBJECT_REF(object,G_TYPE_FROM_INSTANCE(object),old_val));
2664
2665   return object;
2666 }
2667
2668 /**
2669  * g_object_unref:
2670  * @object: (type GObject.Object): a #GObject
2671  *
2672  * Decreases the reference count of @object. When its reference count
2673  * drops to 0, the object is finalized (i.e. its memory is freed).
2674  */
2675 void
2676 g_object_unref (gpointer _object)
2677 {
2678   GObject *object = _object;
2679   gint old_ref;
2680   
2681   g_return_if_fail (G_IS_OBJECT (object));
2682   g_return_if_fail (object->ref_count > 0);
2683   
2684 #ifdef  G_ENABLE_DEBUG
2685   if (g_trap_object_ref == object)
2686     G_BREAKPOINT ();
2687 #endif  /* G_ENABLE_DEBUG */
2688
2689   /* here we want to atomically do: if (ref_count>1) { ref_count--; return; } */
2690  retry_atomic_decrement1:
2691   old_ref = g_atomic_int_get (&object->ref_count);
2692   if (old_ref > 1)
2693     {
2694       /* valid if last 2 refs are owned by this call to unref and the toggle_ref */
2695       gboolean has_toggle_ref = OBJECT_HAS_TOGGLE_REF (object);
2696
2697       if (!g_atomic_int_compare_and_exchange ((int *)&object->ref_count, old_ref, old_ref - 1))
2698         goto retry_atomic_decrement1;
2699
2700       TRACE (GOBJECT_OBJECT_UNREF(object,G_TYPE_FROM_INSTANCE(object),old_ref));
2701
2702       /* if we went from 2->1 we need to notify toggle refs if any */
2703       if (old_ref == 2 && has_toggle_ref) /* The last ref being held in this case is owned by the toggle_ref */
2704         toggle_refs_notify (object, TRUE);
2705     }
2706   else
2707     {
2708       /* we are about tp remove the last reference */
2709       TRACE (GOBJECT_OBJECT_DISPOSE(object,G_TYPE_FROM_INSTANCE(object), 1));
2710       G_OBJECT_GET_CLASS (object)->dispose (object);
2711       TRACE (GOBJECT_OBJECT_DISPOSE_END(object,G_TYPE_FROM_INSTANCE(object), 1));
2712
2713       /* may have been re-referenced meanwhile */
2714     retry_atomic_decrement2:
2715       old_ref = g_atomic_int_get ((int *)&object->ref_count);
2716       if (old_ref > 1)
2717         {
2718           /* valid if last 2 refs are owned by this call to unref and the toggle_ref */
2719           gboolean has_toggle_ref = OBJECT_HAS_TOGGLE_REF (object);
2720
2721           if (!g_atomic_int_compare_and_exchange ((int *)&object->ref_count, old_ref, old_ref - 1))
2722             goto retry_atomic_decrement2;
2723
2724           TRACE (GOBJECT_OBJECT_UNREF(object,G_TYPE_FROM_INSTANCE(object),old_ref));
2725
2726           /* if we went from 2->1 we need to notify toggle refs if any */
2727           if (old_ref == 2 && has_toggle_ref) /* The last ref being held in this case is owned by the toggle_ref */
2728             toggle_refs_notify (object, TRUE);
2729
2730           return;
2731         }
2732
2733       /* we are still in the process of taking away the last ref */
2734       g_datalist_id_set_data (&object->qdata, quark_closure_array, NULL);
2735       g_signal_handlers_destroy (object);
2736       g_datalist_id_set_data (&object->qdata, quark_weak_refs, NULL);
2737       
2738       /* decrement the last reference */
2739       old_ref = g_atomic_int_add (&object->ref_count, -1);
2740
2741       TRACE (GOBJECT_OBJECT_UNREF(object,G_TYPE_FROM_INSTANCE(object),old_ref));
2742
2743       /* may have been re-referenced meanwhile */
2744       if (G_LIKELY (old_ref == 1))
2745         {
2746           TRACE (GOBJECT_OBJECT_FINALIZE(object,G_TYPE_FROM_INSTANCE(object)));
2747           G_OBJECT_GET_CLASS (object)->finalize (object);
2748
2749           TRACE (GOBJECT_OBJECT_FINALIZE_END(object,G_TYPE_FROM_INSTANCE(object)));
2750
2751 #ifdef  G_ENABLE_DEBUG
2752           IF_DEBUG (OBJECTS)
2753             {
2754               /* catch objects not chaining finalize handlers */
2755               G_LOCK (debug_objects);
2756               g_assert (g_hash_table_lookup (debug_objects_ht, object) == NULL);
2757               G_UNLOCK (debug_objects);
2758             }
2759 #endif  /* G_ENABLE_DEBUG */
2760           g_type_free_instance ((GTypeInstance*) object);
2761         }
2762     }
2763 }
2764
2765 /**
2766  * g_clear_object: (skip)
2767  * @object_ptr: a pointer to a #GObject reference
2768  *
2769  * Clears a reference to a #GObject.
2770  *
2771  * @object_ptr must not be %NULL.
2772  *
2773  * If the reference is %NULL then this function does nothing.
2774  * Otherwise, the reference count of the object is decreased and the
2775  * pointer is set to %NULL.
2776  *
2777  * This function is threadsafe and modifies the pointer atomically,
2778  * using memory barriers where needed.
2779  *
2780  * A macro is also included that allows this function to be used without
2781  * pointer casts.
2782  *
2783  * Since: 2.28
2784  **/
2785 #undef g_clear_object
2786 void
2787 g_clear_object (volatile GObject **object_ptr)
2788 {
2789   gpointer *ptr = (gpointer) object_ptr;
2790   gpointer old;
2791
2792   /* This is a little frustrating.
2793    * Would be nice to have an atomic exchange (with no compare).
2794    */
2795   do
2796     old = g_atomic_pointer_get (ptr);
2797   while G_UNLIKELY (!g_atomic_pointer_compare_and_exchange (ptr, old, NULL));
2798
2799   if (old)
2800     g_object_unref (old);
2801 }
2802
2803 /**
2804  * g_object_get_qdata:
2805  * @object: The GObject to get a stored user data pointer from
2806  * @quark: A #GQuark, naming the user data pointer
2807  * 
2808  * This function gets back user data pointers stored via
2809  * g_object_set_qdata().
2810  * 
2811  * Returns: (transfer none): The user data pointer set, or %NULL
2812  */
2813 gpointer
2814 g_object_get_qdata (GObject *object,
2815                     GQuark   quark)
2816 {
2817   g_return_val_if_fail (G_IS_OBJECT (object), NULL);
2818   
2819   return quark ? g_datalist_id_get_data (&object->qdata, quark) : NULL;
2820 }
2821
2822 /**
2823  * g_object_set_qdata: (skip)
2824  * @object: The GObject to set store a user data pointer
2825  * @quark: A #GQuark, naming the user data pointer
2826  * @data: An opaque user data pointer
2827  *
2828  * This sets an opaque, named pointer on an object.
2829  * The name is specified through a #GQuark (retrived e.g. via
2830  * g_quark_from_static_string()), and the pointer
2831  * can be gotten back from the @object with g_object_get_qdata()
2832  * until the @object is finalized.
2833  * Setting a previously set user data pointer, overrides (frees)
2834  * the old pointer set, using #NULL as pointer essentially
2835  * removes the data stored.
2836  */
2837 void
2838 g_object_set_qdata (GObject *object,
2839                     GQuark   quark,
2840                     gpointer data)
2841 {
2842   g_return_if_fail (G_IS_OBJECT (object));
2843   g_return_if_fail (quark > 0);
2844   
2845   g_datalist_id_set_data (&object->qdata, quark, data);
2846 }
2847
2848 /**
2849  * g_object_set_qdata_full: (skip)
2850  * @object: The GObject to set store a user data pointer
2851  * @quark: A #GQuark, naming the user data pointer
2852  * @data: An opaque user data pointer
2853  * @destroy: Function to invoke with @data as argument, when @data
2854  *           needs to be freed
2855  *
2856  * This function works like g_object_set_qdata(), but in addition,
2857  * a void (*destroy) (gpointer) function may be specified which is
2858  * called with @data as argument when the @object is finalized, or
2859  * the data is being overwritten by a call to g_object_set_qdata()
2860  * with the same @quark.
2861  */
2862 void
2863 g_object_set_qdata_full (GObject       *object,
2864                          GQuark         quark,
2865                          gpointer       data,
2866                          GDestroyNotify destroy)
2867 {
2868   g_return_if_fail (G_IS_OBJECT (object));
2869   g_return_if_fail (quark > 0);
2870   
2871   g_datalist_id_set_data_full (&object->qdata, quark, data,
2872                                data ? destroy : (GDestroyNotify) NULL);
2873 }
2874
2875 /**
2876  * g_object_steal_qdata:
2877  * @object: The GObject to get a stored user data pointer from
2878  * @quark: A #GQuark, naming the user data pointer
2879  *
2880  * This function gets back user data pointers stored via
2881  * g_object_set_qdata() and removes the @data from object
2882  * without invoking its destroy() function (if any was
2883  * set).
2884  * Usually, calling this function is only required to update
2885  * user data pointers with a destroy notifier, for example:
2886  * |[
2887  * void
2888  * object_add_to_user_list (GObject     *object,
2889  *                          const gchar *new_string)
2890  * {
2891  *   // the quark, naming the object data
2892  *   GQuark quark_string_list = g_quark_from_static_string ("my-string-list");
2893  *   // retrive the old string list
2894  *   GList *list = g_object_steal_qdata (object, quark_string_list);
2895  *
2896  *   // prepend new string
2897  *   list = g_list_prepend (list, g_strdup (new_string));
2898  *   // this changed 'list', so we need to set it again
2899  *   g_object_set_qdata_full (object, quark_string_list, list, free_string_list);
2900  * }
2901  * static void
2902  * free_string_list (gpointer data)
2903  * {
2904  *   GList *node, *list = data;
2905  *
2906  *   for (node = list; node; node = node->next)
2907  *     g_free (node->data);
2908  *   g_list_free (list);
2909  * }
2910  * ]|
2911  * Using g_object_get_qdata() in the above example, instead of
2912  * g_object_steal_qdata() would have left the destroy function set,
2913  * and thus the partial string list would have been freed upon
2914  * g_object_set_qdata_full().
2915  *
2916  * Returns: (transfer full): The user data pointer set, or %NULL
2917  */
2918 gpointer
2919 g_object_steal_qdata (GObject *object,
2920                       GQuark   quark)
2921 {
2922   g_return_val_if_fail (G_IS_OBJECT (object), NULL);
2923   g_return_val_if_fail (quark > 0, NULL);
2924   
2925   return g_datalist_id_remove_no_notify (&object->qdata, quark);
2926 }
2927
2928 /**
2929  * g_object_get_data:
2930  * @object: #GObject containing the associations
2931  * @key: name of the key for that association
2932  * 
2933  * Gets a named field from the objects table of associations (see g_object_set_data()).
2934  * 
2935  * Returns: (transfer none): the data if found, or %NULL if no such data exists.
2936  */
2937 gpointer
2938 g_object_get_data (GObject     *object,
2939                    const gchar *key)
2940 {
2941   g_return_val_if_fail (G_IS_OBJECT (object), NULL);
2942   g_return_val_if_fail (key != NULL, NULL);
2943
2944   return g_datalist_get_data (&object->qdata, key);
2945 }
2946
2947 /**
2948  * g_object_set_data:
2949  * @object: #GObject containing the associations.
2950  * @key: name of the key
2951  * @data: data to associate with that key
2952  *
2953  * Each object carries around a table of associations from
2954  * strings to pointers.  This function lets you set an association.
2955  *
2956  * If the object already had an association with that name,
2957  * the old association will be destroyed.
2958  */
2959 void
2960 g_object_set_data (GObject     *object,
2961                    const gchar *key,
2962                    gpointer     data)
2963 {
2964   g_return_if_fail (G_IS_OBJECT (object));
2965   g_return_if_fail (key != NULL);
2966
2967   g_datalist_id_set_data (&object->qdata, g_quark_from_string (key), data);
2968 }
2969
2970 /**
2971  * g_object_set_data_full: (skip)
2972  * @object: #GObject containing the associations
2973  * @key: name of the key
2974  * @data: data to associate with that key
2975  * @destroy: function to call when the association is destroyed
2976  *
2977  * Like g_object_set_data() except it adds notification
2978  * for when the association is destroyed, either by setting it
2979  * to a different value or when the object is destroyed.
2980  *
2981  * Note that the @destroy callback is not called if @data is %NULL.
2982  */
2983 void
2984 g_object_set_data_full (GObject       *object,
2985                         const gchar   *key,
2986                         gpointer       data,
2987                         GDestroyNotify destroy)
2988 {
2989   g_return_if_fail (G_IS_OBJECT (object));
2990   g_return_if_fail (key != NULL);
2991
2992   g_datalist_id_set_data_full (&object->qdata, g_quark_from_string (key), data,
2993                                data ? destroy : (GDestroyNotify) NULL);
2994 }
2995
2996 /**
2997  * g_object_steal_data:
2998  * @object: #GObject containing the associations
2999  * @key: name of the key
3000  *
3001  * Remove a specified datum from the object's data associations,
3002  * without invoking the association's destroy handler.
3003  *
3004  * Returns: (transfer full): the data if found, or %NULL if no such data exists.
3005  */
3006 gpointer
3007 g_object_steal_data (GObject     *object,
3008                      const gchar *key)
3009 {
3010   GQuark quark;
3011
3012   g_return_val_if_fail (G_IS_OBJECT (object), NULL);
3013   g_return_val_if_fail (key != NULL, NULL);
3014
3015   quark = g_quark_try_string (key);
3016
3017   return quark ? g_datalist_id_remove_no_notify (&object->qdata, quark) : NULL;
3018 }
3019
3020 static void
3021 g_value_object_init (GValue *value)
3022 {
3023   value->data[0].v_pointer = NULL;
3024 }
3025
3026 static void
3027 g_value_object_free_value (GValue *value)
3028 {
3029   if (value->data[0].v_pointer)
3030     g_object_unref (value->data[0].v_pointer);
3031 }
3032
3033 static void
3034 g_value_object_copy_value (const GValue *src_value,
3035                            GValue       *dest_value)
3036 {
3037   if (src_value->data[0].v_pointer)
3038     dest_value->data[0].v_pointer = g_object_ref (src_value->data[0].v_pointer);
3039   else
3040     dest_value->data[0].v_pointer = NULL;
3041 }
3042
3043 static void
3044 g_value_object_transform_value (const GValue *src_value,
3045                                 GValue       *dest_value)
3046 {
3047   if (src_value->data[0].v_pointer && g_type_is_a (G_OBJECT_TYPE (src_value->data[0].v_pointer), G_VALUE_TYPE (dest_value)))
3048     dest_value->data[0].v_pointer = g_object_ref (src_value->data[0].v_pointer);
3049   else
3050     dest_value->data[0].v_pointer = NULL;
3051 }
3052
3053 static gpointer
3054 g_value_object_peek_pointer (const GValue *value)
3055 {
3056   return value->data[0].v_pointer;
3057 }
3058
3059 static gchar*
3060 g_value_object_collect_value (GValue      *value,
3061                               guint        n_collect_values,
3062                               GTypeCValue *collect_values,
3063                               guint        collect_flags)
3064 {
3065   if (collect_values[0].v_pointer)
3066     {
3067       GObject *object = collect_values[0].v_pointer;
3068       
3069       if (object->g_type_instance.g_class == NULL)
3070         return g_strconcat ("invalid unclassed object pointer for value type `",
3071                             G_VALUE_TYPE_NAME (value),
3072                             "'",
3073                             NULL);
3074       else if (!g_value_type_compatible (G_OBJECT_TYPE (object), G_VALUE_TYPE (value)))
3075         return g_strconcat ("invalid object type `",
3076                             G_OBJECT_TYPE_NAME (object),
3077                             "' for value type `",
3078                             G_VALUE_TYPE_NAME (value),
3079                             "'",
3080                             NULL);
3081       /* never honour G_VALUE_NOCOPY_CONTENTS for ref-counted types */
3082       value->data[0].v_pointer = g_object_ref (object);
3083     }
3084   else
3085     value->data[0].v_pointer = NULL;
3086   
3087   return NULL;
3088 }
3089
3090 static gchar*
3091 g_value_object_lcopy_value (const GValue *value,
3092                             guint        n_collect_values,
3093                             GTypeCValue *collect_values,
3094                             guint        collect_flags)
3095 {
3096   GObject **object_p = collect_values[0].v_pointer;
3097   
3098   if (!object_p)
3099     return g_strdup_printf ("value location for `%s' passed as NULL", G_VALUE_TYPE_NAME (value));
3100
3101   if (!value->data[0].v_pointer)
3102     *object_p = NULL;
3103   else if (collect_flags & G_VALUE_NOCOPY_CONTENTS)
3104     *object_p = value->data[0].v_pointer;
3105   else
3106     *object_p = g_object_ref (value->data[0].v_pointer);
3107   
3108   return NULL;
3109 }
3110
3111 /**
3112  * g_value_set_object:
3113  * @value: a valid #GValue of %G_TYPE_OBJECT derived type
3114  * @v_object: (type GObject.Object): object value to be set
3115  *
3116  * Set the contents of a %G_TYPE_OBJECT derived #GValue to @v_object.
3117  *
3118  * g_value_set_object() increases the reference count of @v_object
3119  * (the #GValue holds a reference to @v_object).  If you do not wish
3120  * to increase the reference count of the object (i.e. you wish to
3121  * pass your current reference to the #GValue because you no longer
3122  * need it), use g_value_take_object() instead.
3123  *
3124  * It is important that your #GValue holds a reference to @v_object (either its
3125  * own, or one it has taken) to ensure that the object won't be destroyed while
3126  * the #GValue still exists).
3127  */
3128 void
3129 g_value_set_object (GValue   *value,
3130                     gpointer  v_object)
3131 {
3132   GObject *old;
3133         
3134   g_return_if_fail (G_VALUE_HOLDS_OBJECT (value));
3135
3136   old = value->data[0].v_pointer;
3137   
3138   if (v_object)
3139     {
3140       g_return_if_fail (G_IS_OBJECT (v_object));
3141       g_return_if_fail (g_value_type_compatible (G_OBJECT_TYPE (v_object), G_VALUE_TYPE (value)));
3142
3143       value->data[0].v_pointer = v_object;
3144       g_object_ref (value->data[0].v_pointer);
3145     }
3146   else
3147     value->data[0].v_pointer = NULL;
3148   
3149   if (old)
3150     g_object_unref (old);
3151 }
3152
3153 /**
3154  * g_value_set_object_take_ownership: (skip)
3155  * @value: a valid #GValue of %G_TYPE_OBJECT derived type
3156  * @v_object: object value to be set
3157  *
3158  * This is an internal function introduced mainly for C marshallers.
3159  *
3160  * Deprecated: 2.4: Use g_value_take_object() instead.
3161  */
3162 void
3163 g_value_set_object_take_ownership (GValue  *value,
3164                                    gpointer v_object)
3165 {
3166   g_value_take_object (value, v_object);
3167 }
3168
3169 /**
3170  * g_value_take_object: (skip)
3171  * @value: a valid #GValue of %G_TYPE_OBJECT derived type
3172  * @v_object: object value to be set
3173  *
3174  * Sets the contents of a %G_TYPE_OBJECT derived #GValue to @v_object
3175  * and takes over the ownership of the callers reference to @v_object;
3176  * the caller doesn't have to unref it any more (i.e. the reference
3177  * count of the object is not increased).
3178  *
3179  * If you want the #GValue to hold its own reference to @v_object, use
3180  * g_value_set_object() instead.
3181  *
3182  * Since: 2.4
3183  */
3184 void
3185 g_value_take_object (GValue  *value,
3186                      gpointer v_object)
3187 {
3188   g_return_if_fail (G_VALUE_HOLDS_OBJECT (value));
3189
3190   if (value->data[0].v_pointer)
3191     {
3192       g_object_unref (value->data[0].v_pointer);
3193       value->data[0].v_pointer = NULL;
3194     }
3195
3196   if (v_object)
3197     {
3198       g_return_if_fail (G_IS_OBJECT (v_object));
3199       g_return_if_fail (g_value_type_compatible (G_OBJECT_TYPE (v_object), G_VALUE_TYPE (value)));
3200
3201       value->data[0].v_pointer = v_object; /* we take over the reference count */
3202     }
3203 }
3204
3205 /**
3206  * g_value_get_object:
3207  * @value: a valid #GValue of %G_TYPE_OBJECT derived type
3208  * 
3209  * Get the contents of a %G_TYPE_OBJECT derived #GValue.
3210  * 
3211  * Returns: (type GObject.Object) (transfer none): object contents of @value
3212  */
3213 gpointer
3214 g_value_get_object (const GValue *value)
3215 {
3216   g_return_val_if_fail (G_VALUE_HOLDS_OBJECT (value), NULL);
3217   
3218   return value->data[0].v_pointer;
3219 }
3220
3221 /**
3222  * g_value_dup_object:
3223  * @value: a valid #GValue whose type is derived from %G_TYPE_OBJECT
3224  *
3225  * Get the contents of a %G_TYPE_OBJECT derived #GValue, increasing
3226  * its reference count. If the contents of the #GValue are %NULL, then
3227  * %NULL will be returned.
3228  *
3229  * Returns: (type GObject.Object) (transfer full): object content of @value,
3230  *          should be unreferenced when no longer needed.
3231  */
3232 gpointer
3233 g_value_dup_object (const GValue *value)
3234 {
3235   g_return_val_if_fail (G_VALUE_HOLDS_OBJECT (value), NULL);
3236   
3237   return value->data[0].v_pointer ? g_object_ref (value->data[0].v_pointer) : NULL;
3238 }
3239
3240 /**
3241  * g_signal_connect_object: (skip)
3242  * @instance: the instance to connect to.
3243  * @detailed_signal: a string of the form "signal-name::detail".
3244  * @c_handler: the #GCallback to connect.
3245  * @gobject: the object to pass as data to @c_handler.
3246  * @connect_flags: a combination of #GConnnectFlags.
3247  *
3248  * This is similar to g_signal_connect_data(), but uses a closure which
3249  * ensures that the @gobject stays alive during the call to @c_handler
3250  * by temporarily adding a reference count to @gobject.
3251  *
3252  * Note that there is a bug in GObject that makes this function
3253  * much less useful than it might seem otherwise. Once @gobject is
3254  * disposed, the callback will no longer be called, but, the signal
3255  * handler is <emphasis>not</emphasis> currently disconnected. If the
3256  * @instance is itself being freed at the same time than this doesn't
3257  * matter, since the signal will automatically be removed, but
3258  * if @instance persists, then the signal handler will leak. You
3259  * should not remove the signal yourself because in a future versions of
3260  * GObject, the handler <emphasis>will</emphasis> automatically
3261  * be disconnected.
3262  *
3263  * It's possible to work around this problem in a way that will
3264  * continue to work with future versions of GObject by checking
3265  * that the signal handler is still connected before disconnected it:
3266  * <informalexample><programlisting>
3267  *  if (g_signal_handler_is_connected (instance, id))
3268  *    g_signal_handler_disconnect (instance, id);
3269  * </programlisting></informalexample>
3270  *
3271  * Returns: the handler id.
3272  */
3273 gulong
3274 g_signal_connect_object (gpointer      instance,
3275                          const gchar  *detailed_signal,
3276                          GCallback     c_handler,
3277                          gpointer      gobject,
3278                          GConnectFlags connect_flags)
3279 {
3280   g_return_val_if_fail (G_TYPE_CHECK_INSTANCE (instance), 0);
3281   g_return_val_if_fail (detailed_signal != NULL, 0);
3282   g_return_val_if_fail (c_handler != NULL, 0);
3283
3284   if (gobject)
3285     {
3286       GClosure *closure;
3287
3288       g_return_val_if_fail (G_IS_OBJECT (gobject), 0);
3289
3290       closure = ((connect_flags & G_CONNECT_SWAPPED) ? g_cclosure_new_object_swap : g_cclosure_new_object) (c_handler, gobject);
3291
3292       return g_signal_connect_closure (instance, detailed_signal, closure, connect_flags & G_CONNECT_AFTER);
3293     }
3294   else
3295     return g_signal_connect_data (instance, detailed_signal, c_handler, NULL, NULL, connect_flags);
3296 }
3297
3298 typedef struct {
3299   GObject  *object;
3300   guint     n_closures;
3301   GClosure *closures[1]; /* flexible array */
3302 } CArray;
3303 /* don't change this structure without supplying an accessor for
3304  * watched closures, e.g.:
3305  * GSList* g_object_list_watched_closures (GObject *object)
3306  * {
3307  *   CArray *carray;
3308  *   g_return_val_if_fail (G_IS_OBJECT (object), NULL);
3309  *   carray = g_object_get_data (object, "GObject-closure-array");
3310  *   if (carray)
3311  *     {
3312  *       GSList *slist = NULL;
3313  *       guint i;
3314  *       for (i = 0; i < carray->n_closures; i++)
3315  *         slist = g_slist_prepend (slist, carray->closures[i]);
3316  *       return slist;
3317  *     }
3318  *   return NULL;
3319  * }
3320  */
3321
3322 static void
3323 object_remove_closure (gpointer  data,
3324                        GClosure *closure)
3325 {
3326   GObject *object = data;
3327   CArray *carray;
3328   guint i;
3329   
3330   G_LOCK (closure_array_mutex);
3331   carray = g_object_get_qdata (object, quark_closure_array);
3332   for (i = 0; i < carray->n_closures; i++)
3333     if (carray->closures[i] == closure)
3334       {
3335         carray->n_closures--;
3336         if (i < carray->n_closures)
3337           carray->closures[i] = carray->closures[carray->n_closures];
3338         G_UNLOCK (closure_array_mutex);
3339         return;
3340       }
3341   G_UNLOCK (closure_array_mutex);
3342   g_assert_not_reached ();
3343 }
3344
3345 static void
3346 destroy_closure_array (gpointer data)
3347 {
3348   CArray *carray = data;
3349   GObject *object = carray->object;
3350   guint i, n = carray->n_closures;
3351   
3352   for (i = 0; i < n; i++)
3353     {
3354       GClosure *closure = carray->closures[i];
3355       
3356       /* removing object_remove_closure() upfront is probably faster than
3357        * letting it fiddle with quark_closure_array which is empty anyways
3358        */
3359       g_closure_remove_invalidate_notifier (closure, object, object_remove_closure);
3360       g_closure_invalidate (closure);
3361     }
3362   g_free (carray);
3363 }
3364
3365 /**
3366  * g_object_watch_closure:
3367  * @object: GObject restricting lifetime of @closure
3368  * @closure: GClosure to watch
3369  *
3370  * This function essentially limits the life time of the @closure to
3371  * the life time of the object. That is, when the object is finalized,
3372  * the @closure is invalidated by calling g_closure_invalidate() on
3373  * it, in order to prevent invocations of the closure with a finalized
3374  * (nonexisting) object. Also, g_object_ref() and g_object_unref() are
3375  * added as marshal guards to the @closure, to ensure that an extra
3376  * reference count is held on @object during invocation of the
3377  * @closure.  Usually, this function will be called on closures that
3378  * use this @object as closure data.
3379  */
3380 void
3381 g_object_watch_closure (GObject  *object,
3382                         GClosure *closure)
3383 {
3384   CArray *carray;
3385   guint i;
3386   
3387   g_return_if_fail (G_IS_OBJECT (object));
3388   g_return_if_fail (closure != NULL);
3389   g_return_if_fail (closure->is_invalid == FALSE);
3390   g_return_if_fail (closure->in_marshal == FALSE);
3391   g_return_if_fail (object->ref_count > 0);     /* this doesn't work on finalizing objects */
3392   
3393   g_closure_add_invalidate_notifier (closure, object, object_remove_closure);
3394   g_closure_add_marshal_guards (closure,
3395                                 object, (GClosureNotify) g_object_ref,
3396                                 object, (GClosureNotify) g_object_unref);
3397   G_LOCK (closure_array_mutex);
3398   carray = g_datalist_id_remove_no_notify (&object->qdata, quark_closure_array);
3399   if (!carray)
3400     {
3401       carray = g_renew (CArray, NULL, 1);
3402       carray->object = object;
3403       carray->n_closures = 1;
3404       i = 0;
3405     }
3406   else
3407     {
3408       i = carray->n_closures++;
3409       carray = g_realloc (carray, sizeof (*carray) + sizeof (carray->closures[0]) * i);
3410     }
3411   carray->closures[i] = closure;
3412   g_datalist_id_set_data_full (&object->qdata, quark_closure_array, carray, destroy_closure_array);
3413   G_UNLOCK (closure_array_mutex);
3414 }
3415
3416 /**
3417  * g_closure_new_object:
3418  * @sizeof_closure: the size of the structure to allocate, must be at least
3419  *  <literal>sizeof (GClosure)</literal>
3420  * @object: a #GObject pointer to store in the @data field of the newly
3421  *  allocated #GClosure
3422  *
3423  * A variant of g_closure_new_simple() which stores @object in the
3424  * @data field of the closure and calls g_object_watch_closure() on
3425  * @object and the created closure. This function is mainly useful
3426  * when implementing new types of closures.
3427  *
3428  * Returns: (transfer full): a newly allocated #GClosure
3429  */
3430 GClosure*
3431 g_closure_new_object (guint    sizeof_closure,
3432                       GObject *object)
3433 {
3434   GClosure *closure;
3435
3436   g_return_val_if_fail (G_IS_OBJECT (object), NULL);
3437   g_return_val_if_fail (object->ref_count > 0, NULL);     /* this doesn't work on finalizing objects */
3438
3439   closure = g_closure_new_simple (sizeof_closure, object);
3440   g_object_watch_closure (object, closure);
3441
3442   return closure;
3443 }
3444
3445 /**
3446  * g_cclosure_new_object: (skip)
3447  * @callback_func: the function to invoke
3448  * @object: a #GObject pointer to pass to @callback_func
3449  *
3450  * A variant of g_cclosure_new() which uses @object as @user_data and
3451  * calls g_object_watch_closure() on @object and the created
3452  * closure. This function is useful when you have a callback closely
3453  * associated with a #GObject, and want the callback to no longer run
3454  * after the object is is freed.
3455  *
3456  * Returns: a new #GCClosure
3457  */
3458 GClosure*
3459 g_cclosure_new_object (GCallback callback_func,
3460                        GObject  *object)
3461 {
3462   GClosure *closure;
3463
3464   g_return_val_if_fail (G_IS_OBJECT (object), NULL);
3465   g_return_val_if_fail (object->ref_count > 0, NULL);     /* this doesn't work on finalizing objects */
3466   g_return_val_if_fail (callback_func != NULL, NULL);
3467
3468   closure = g_cclosure_new (callback_func, object, NULL);
3469   g_object_watch_closure (object, closure);
3470
3471   return closure;
3472 }
3473
3474 /**
3475  * g_cclosure_new_object_swap: (skip)
3476  * @callback_func: the function to invoke
3477  * @object: a #GObject pointer to pass to @callback_func
3478  *
3479  * A variant of g_cclosure_new_swap() which uses @object as @user_data
3480  * and calls g_object_watch_closure() on @object and the created
3481  * closure. This function is useful when you have a callback closely
3482  * associated with a #GObject, and want the callback to no longer run
3483  * after the object is is freed.
3484  *
3485  * Returns: a new #GCClosure
3486  */
3487 GClosure*
3488 g_cclosure_new_object_swap (GCallback callback_func,
3489                             GObject  *object)
3490 {
3491   GClosure *closure;
3492
3493   g_return_val_if_fail (G_IS_OBJECT (object), NULL);
3494   g_return_val_if_fail (object->ref_count > 0, NULL);     /* this doesn't work on finalizing objects */
3495   g_return_val_if_fail (callback_func != NULL, NULL);
3496
3497   closure = g_cclosure_new_swap (callback_func, object, NULL);
3498   g_object_watch_closure (object, closure);
3499
3500   return closure;
3501 }
3502
3503 gsize
3504 g_object_compat_control (gsize           what,
3505                          gpointer        data)
3506 {
3507   switch (what)
3508     {
3509       gpointer *pp;
3510     case 1:     /* floating base type */
3511       return G_TYPE_INITIALLY_UNOWNED;
3512     case 2:     /* FIXME: remove this once GLib/Gtk+ break ABI again */
3513       floating_flag_handler = (guint(*)(GObject*,gint)) data;
3514       return 1;
3515     case 3:     /* FIXME: remove this once GLib/Gtk+ break ABI again */
3516       pp = data;
3517       *pp = floating_flag_handler;
3518       return 1;
3519     default:
3520       return 0;
3521     }
3522 }
3523
3524 G_DEFINE_TYPE (GInitiallyUnowned, g_initially_unowned, G_TYPE_OBJECT);
3525
3526 static void
3527 g_initially_unowned_init (GInitiallyUnowned *object)
3528 {
3529   g_object_force_floating (object);
3530 }
3531
3532 static void
3533 g_initially_unowned_class_init (GInitiallyUnownedClass *klass)
3534 {
3535 }