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