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