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