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