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