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