GObject: prevent installing properties after init
[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_critical ("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_critical ("Attempt to add properties %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 void
954 g_object_init (GObject          *object,
955                GObjectClass     *class)
956 {
957   object->ref_count = 1;
958   object->qdata = NULL;
959
960   if (CLASS_HAS_PROPS (class))
961     {
962       /* freeze object's notification queue, g_object_newv() preserves pairedness */
963       g_object_notify_queue_freeze (object, FALSE);
964     }
965
966   if (CLASS_HAS_CUSTOM_CONSTRUCTOR (class))
967     {
968       /* enter construction list for notify_queue_thaw() and to allow construct-only properties */
969       G_LOCK (construction_mutex);
970       construction_objects = g_slist_prepend (construction_objects, object);
971       G_UNLOCK (construction_mutex);
972     }
973
974 #ifdef  G_ENABLE_DEBUG
975   IF_DEBUG (OBJECTS)
976     {
977       G_LOCK (debug_objects);
978       debug_objects_count++;
979       g_hash_table_insert (debug_objects_ht, object, object);
980       G_UNLOCK (debug_objects);
981     }
982 #endif  /* G_ENABLE_DEBUG */
983 }
984
985 static void
986 g_object_do_set_property (GObject      *object,
987                           guint         property_id,
988                           const GValue *value,
989                           GParamSpec   *pspec)
990 {
991   switch (property_id)
992     {
993     default:
994       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec);
995       break;
996     }
997 }
998
999 static void
1000 g_object_do_get_property (GObject     *object,
1001                           guint        property_id,
1002                           GValue      *value,
1003                           GParamSpec  *pspec)
1004 {
1005   switch (property_id)
1006     {
1007     default:
1008       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec);
1009       break;
1010     }
1011 }
1012
1013 static void
1014 g_object_real_dispose (GObject *object)
1015 {
1016   g_signal_handlers_destroy (object);
1017   g_datalist_id_set_data (&object->qdata, quark_closure_array, NULL);
1018   g_datalist_id_set_data (&object->qdata, quark_weak_refs, NULL);
1019 }
1020
1021 static void
1022 g_object_finalize (GObject *object)
1023 {
1024   g_datalist_clear (&object->qdata);
1025   
1026 #ifdef  G_ENABLE_DEBUG
1027   IF_DEBUG (OBJECTS)
1028     {
1029       G_LOCK (debug_objects);
1030       g_assert (g_hash_table_lookup (debug_objects_ht, object) == object);
1031       g_hash_table_remove (debug_objects_ht, object);
1032       debug_objects_count--;
1033       G_UNLOCK (debug_objects);
1034     }
1035 #endif  /* G_ENABLE_DEBUG */
1036 }
1037
1038
1039 static void
1040 g_object_dispatch_properties_changed (GObject     *object,
1041                                       guint        n_pspecs,
1042                                       GParamSpec **pspecs)
1043 {
1044   guint i;
1045
1046   for (i = 0; i < n_pspecs; i++)
1047     g_signal_emit (object, gobject_signals[NOTIFY], g_quark_from_string (pspecs[i]->name), pspecs[i]);
1048 }
1049
1050 /**
1051  * g_object_run_dispose:
1052  * @object: a #GObject
1053  *
1054  * Releases all references to other objects. This can be used to break
1055  * reference cycles.
1056  *
1057  * This functions should only be called from object system implementations.
1058  */
1059 void
1060 g_object_run_dispose (GObject *object)
1061 {
1062   g_return_if_fail (G_IS_OBJECT (object));
1063   g_return_if_fail (object->ref_count > 0);
1064
1065   g_object_ref (object);
1066   TRACE (GOBJECT_OBJECT_DISPOSE(object,G_TYPE_FROM_INSTANCE(object), 0));
1067   G_OBJECT_GET_CLASS (object)->dispose (object);
1068   TRACE (GOBJECT_OBJECT_DISPOSE_END(object,G_TYPE_FROM_INSTANCE(object), 0));
1069   g_object_unref (object);
1070 }
1071
1072 /**
1073  * g_object_freeze_notify:
1074  * @object: a #GObject
1075  *
1076  * Increases the freeze count on @object. If the freeze count is
1077  * non-zero, the emission of "notify" signals on @object is
1078  * stopped. The signals are queued until the freeze count is decreased
1079  * to zero. Duplicate notifications are squashed so that at most one
1080  * #GObject::notify signal is emitted for each property modified while the
1081  * object is frozen.
1082  *
1083  * This is necessary for accessors that modify multiple properties to prevent
1084  * premature notification while the object is still being modified.
1085  */
1086 void
1087 g_object_freeze_notify (GObject *object)
1088 {
1089   g_return_if_fail (G_IS_OBJECT (object));
1090
1091   if (g_atomic_int_get (&object->ref_count) == 0)
1092     return;
1093
1094   g_object_ref (object);
1095   g_object_notify_queue_freeze (object, FALSE);
1096   g_object_unref (object);
1097 }
1098
1099 static GParamSpec *
1100 get_notify_pspec (GParamSpec *pspec)
1101 {
1102   GParamSpec *redirected;
1103
1104   /* we don't notify on non-READABLE parameters */
1105   if (~pspec->flags & G_PARAM_READABLE)
1106     return NULL;
1107
1108   /* if the paramspec is redirected, notify on the target */
1109   redirected = g_param_spec_get_redirect_target (pspec);
1110   if (redirected != NULL)
1111     return redirected;
1112
1113   /* else, notify normally */
1114   return pspec;
1115 }
1116
1117 static inline void
1118 g_object_notify_by_spec_internal (GObject    *object,
1119                                   GParamSpec *pspec)
1120 {
1121   GParamSpec *notify_pspec;
1122
1123   notify_pspec = get_notify_pspec (pspec);
1124
1125   if (notify_pspec != NULL)
1126     {
1127       GObjectNotifyQueue *nqueue;
1128
1129       /* conditional freeze: only increase freeze count if already frozen */
1130       nqueue = g_object_notify_queue_freeze (object, TRUE);
1131
1132       if (nqueue != NULL)
1133         {
1134           /* we're frozen, so add to the queue and release our freeze */
1135           g_object_notify_queue_add (object, nqueue, notify_pspec);
1136           g_object_notify_queue_thaw (object, nqueue);
1137         }
1138       else
1139         /* not frozen, so just dispatch the notification directly */
1140         G_OBJECT_GET_CLASS (object)
1141           ->dispatch_properties_changed (object, 1, &notify_pspec);
1142     }
1143 }
1144
1145 /**
1146  * g_object_notify:
1147  * @object: a #GObject
1148  * @property_name: the name of a property installed on the class of @object.
1149  *
1150  * Emits a "notify" signal for the property @property_name on @object.
1151  *
1152  * When possible, eg. when signaling a property change from within the class
1153  * that registered the property, you should use g_object_notify_by_pspec()
1154  * instead.
1155  */
1156 void
1157 g_object_notify (GObject     *object,
1158                  const gchar *property_name)
1159 {
1160   GParamSpec *pspec;
1161   
1162   g_return_if_fail (G_IS_OBJECT (object));
1163   g_return_if_fail (property_name != NULL);
1164   if (g_atomic_int_get (&object->ref_count) == 0)
1165     return;
1166   
1167   g_object_ref (object);
1168   /* We don't need to get the redirect target
1169    * (by, e.g. calling g_object_class_find_property())
1170    * because g_object_notify_queue_add() does that
1171    */
1172   pspec = g_param_spec_pool_lookup (pspec_pool,
1173                                     property_name,
1174                                     G_OBJECT_TYPE (object),
1175                                     TRUE);
1176
1177   if (!pspec)
1178     g_warning ("%s: object class '%s' has no property named '%s'",
1179                G_STRFUNC,
1180                G_OBJECT_TYPE_NAME (object),
1181                property_name);
1182   else
1183     g_object_notify_by_spec_internal (object, pspec);
1184   g_object_unref (object);
1185 }
1186
1187 /**
1188  * g_object_notify_by_pspec:
1189  * @object: a #GObject
1190  * @pspec: the #GParamSpec of a property installed on the class of @object.
1191  *
1192  * Emits a "notify" signal for the property specified by @pspec on @object.
1193  *
1194  * This function omits the property name lookup, hence it is faster than
1195  * g_object_notify().
1196  *
1197  * One way to avoid using g_object_notify() from within the
1198  * class that registered the properties, and using g_object_notify_by_pspec()
1199  * instead, is to store the GParamSpec used with
1200  * g_object_class_install_property() inside a static array, e.g.:
1201  *
1202  *|[
1203  *   enum
1204  *   {
1205  *     PROP_0,
1206  *     PROP_FOO,
1207  *     PROP_LAST
1208  *   };
1209  *
1210  *   static GParamSpec *properties[PROP_LAST];
1211  *
1212  *   static void
1213  *   my_object_class_init (MyObjectClass *klass)
1214  *   {
1215  *     properties[PROP_FOO] = g_param_spec_int ("foo", "Foo", "The foo",
1216  *                                              0, 100,
1217  *                                              50,
1218  *                                              G_PARAM_READWRITE);
1219  *     g_object_class_install_property (gobject_class,
1220  *                                      PROP_FOO,
1221  *                                      properties[PROP_FOO]);
1222  *   }
1223  * ]|
1224  *
1225  * and then notify a change on the "foo" property with:
1226  *
1227  * |[
1228  *   g_object_notify_by_pspec (self, properties[PROP_FOO]);
1229  * ]|
1230  *
1231  * Since: 2.26
1232  */
1233 void
1234 g_object_notify_by_pspec (GObject    *object,
1235                           GParamSpec *pspec)
1236 {
1237
1238   g_return_if_fail (G_IS_OBJECT (object));
1239   g_return_if_fail (G_IS_PARAM_SPEC (pspec));
1240
1241   g_object_ref (object);
1242   g_object_notify_by_spec_internal (object, pspec);
1243   g_object_unref (object);
1244 }
1245
1246 /**
1247  * g_object_thaw_notify:
1248  * @object: a #GObject
1249  *
1250  * Reverts the effect of a previous call to
1251  * g_object_freeze_notify(). The freeze count is decreased on @object
1252  * and when it reaches zero, queued "notify" signals are emitted.
1253  *
1254  * Duplicate notifications for each property are squashed so that at most one
1255  * #GObject::notify signal is emitted for each property.
1256  *
1257  * It is an error to call this function when the freeze count is zero.
1258  */
1259 void
1260 g_object_thaw_notify (GObject *object)
1261 {
1262   GObjectNotifyQueue *nqueue;
1263   
1264   g_return_if_fail (G_IS_OBJECT (object));
1265   if (g_atomic_int_get (&object->ref_count) == 0)
1266     return;
1267   
1268   g_object_ref (object);
1269
1270   /* FIXME: Freezing is the only way to get at the notify queue.
1271    * So we freeze once and then thaw twice.
1272    */
1273   nqueue = g_object_notify_queue_freeze (object, FALSE);
1274   g_object_notify_queue_thaw (object, nqueue);
1275   g_object_notify_queue_thaw (object, nqueue);
1276
1277   g_object_unref (object);
1278 }
1279
1280 static inline void
1281 object_get_property (GObject     *object,
1282                      GParamSpec  *pspec,
1283                      GValue      *value)
1284 {
1285   GObjectClass *class = g_type_class_peek (pspec->owner_type);
1286   guint param_id = PARAM_SPEC_PARAM_ID (pspec);
1287   GParamSpec *redirect;
1288
1289   if (class == NULL)
1290     {
1291       g_warning ("'%s::%s' is not a valid property name; '%s' is not a GObject subtype",
1292                  g_type_name (pspec->owner_type), pspec->name, g_type_name (pspec->owner_type));
1293       return;
1294     }
1295
1296   redirect = g_param_spec_get_redirect_target (pspec);
1297   if (redirect)
1298     pspec = redirect;    
1299   
1300   class->get_property (object, param_id, value, pspec);
1301 }
1302
1303 static inline void
1304 object_set_property (GObject             *object,
1305                      GParamSpec          *pspec,
1306                      const GValue        *value,
1307                      GObjectNotifyQueue  *nqueue)
1308 {
1309   GValue tmp_value = G_VALUE_INIT;
1310   GObjectClass *class = g_type_class_peek (pspec->owner_type);
1311   guint param_id = PARAM_SPEC_PARAM_ID (pspec);
1312   GParamSpec *redirect;
1313   static const gchar * enable_diagnostic = NULL;
1314
1315   if (class == NULL)
1316     {
1317       g_warning ("'%s::%s' is not a valid property name; '%s' is not a GObject subtype",
1318                  g_type_name (pspec->owner_type), pspec->name, g_type_name (pspec->owner_type));
1319       return;
1320     }
1321
1322   redirect = g_param_spec_get_redirect_target (pspec);
1323   if (redirect)
1324     pspec = redirect;
1325
1326   if (G_UNLIKELY (!enable_diagnostic))
1327     {
1328       enable_diagnostic = g_getenv ("G_ENABLE_DIAGNOSTIC");
1329       if (!enable_diagnostic)
1330         enable_diagnostic = "0";
1331     }
1332
1333   if (enable_diagnostic[0] == '1')
1334     {
1335       if (pspec->flags & G_PARAM_DEPRECATED)
1336         g_warning ("The property %s:%s is deprecated and shouldn't be used "
1337                    "anymore. It will be removed in a future version.",
1338                    G_OBJECT_TYPE_NAME (object), pspec->name);
1339     }
1340
1341   /* provide a copy to work from, convert (if necessary) and validate */
1342   g_value_init (&tmp_value, pspec->value_type);
1343   if (!g_value_transform (value, &tmp_value))
1344     g_warning ("unable to set property '%s' of type '%s' from value of type '%s'",
1345                pspec->name,
1346                g_type_name (pspec->value_type),
1347                G_VALUE_TYPE_NAME (value));
1348   else if (g_param_value_validate (pspec, &tmp_value) && !(pspec->flags & G_PARAM_LAX_VALIDATION))
1349     {
1350       gchar *contents = g_strdup_value_contents (value);
1351
1352       g_warning ("value \"%s\" of type '%s' is invalid or out of range for property '%s' of type '%s'",
1353                  contents,
1354                  G_VALUE_TYPE_NAME (value),
1355                  pspec->name,
1356                  g_type_name (pspec->value_type));
1357       g_free (contents);
1358     }
1359   else
1360     {
1361       GParamSpec *notify_pspec;
1362
1363       class->set_property (object, param_id, &tmp_value, pspec);
1364
1365       notify_pspec = get_notify_pspec (pspec);
1366
1367       if (notify_pspec != NULL)
1368         g_object_notify_queue_add (object, nqueue, notify_pspec);
1369     }
1370   g_value_unset (&tmp_value);
1371 }
1372
1373 static void
1374 object_interface_check_properties (gpointer check_data,
1375                                    gpointer g_iface)
1376 {
1377   GTypeInterface *iface_class = g_iface;
1378   GObjectClass *class;
1379   GType iface_type = iface_class->g_type;
1380   GParamSpec **pspecs;
1381   guint n;
1382
1383   class = g_type_class_ref (iface_class->g_instance_type);
1384
1385   if (!G_IS_OBJECT_CLASS (class))
1386     return;
1387
1388   pspecs = g_param_spec_pool_list (pspec_pool, iface_type, &n);
1389
1390   while (n--)
1391     {
1392       GParamSpec *class_pspec = g_param_spec_pool_lookup (pspec_pool,
1393                                                           pspecs[n]->name,
1394                                                           G_OBJECT_CLASS_TYPE (class),
1395                                                           TRUE);
1396
1397       if (!class_pspec)
1398         {
1399           g_critical ("Object class %s doesn't implement property "
1400                       "'%s' from interface '%s'",
1401                       g_type_name (G_OBJECT_CLASS_TYPE (class)),
1402                       pspecs[n]->name,
1403                       g_type_name (iface_type));
1404
1405           continue;
1406         }
1407
1408       /* We do a number of checks on the properties of an interface to
1409        * make sure that all classes implementing the interface are
1410        * overriding the properties in a sane way.
1411        *
1412        * We do the checks in order of importance so that we can give
1413        * more useful error messages first.
1414        *
1415        * First, we check that the implementation doesn't remove the
1416        * basic functionality (readability, writability) advertised by
1417        * the interface.  Next, we check that it doesn't introduce
1418        * additional restrictions (such as construct-only).  Finally, we
1419        * make sure the types are compatible.
1420        */
1421
1422 #define SUBSET(a,b,mask) (((a) & ~(b) & (mask)) == 0)
1423       /* If the property on the interface is readable then the
1424        * implementation must be readable.  If the interface is writable
1425        * then the implementation must be writable.
1426        */
1427       if (!SUBSET (pspecs[n]->flags, class_pspec->flags, G_PARAM_READABLE | G_PARAM_WRITABLE))
1428         {
1429           g_critical ("Flags for property '%s' on class '%s' remove functionality compared with the "
1430                       "property on interface '%s'\n", pspecs[n]->name,
1431                       g_type_name (G_OBJECT_CLASS_TYPE (class)), g_type_name (iface_type));
1432           continue;
1433         }
1434
1435       /* If the property on the interface is writable then we need to
1436        * make sure the implementation doesn't introduce new restrictions
1437        * on that writability (ie: construct-only).
1438        *
1439        * If the interface was not writable to begin with then we don't
1440        * really have any problems here because "writable at construct
1441        * type only" is still more permissive than "read only".
1442        */
1443       if (pspecs[n]->flags & G_PARAM_WRITABLE)
1444         {
1445           if (!SUBSET (class_pspec->flags, pspecs[n]->flags, G_PARAM_CONSTRUCT_ONLY))
1446             {
1447               g_critical ("Flags for property '%s' on class '%s' introduce additional restrictions on "
1448                           "writability compared with the property on interface '%s'\n", pspecs[n]->name,
1449                           g_type_name (G_OBJECT_CLASS_TYPE (class)), g_type_name (iface_type));
1450               continue;
1451             }
1452         }
1453 #undef SUBSET
1454
1455       /* If the property on the interface is readable then we are
1456        * effectively advertising that reading the property will return a
1457        * value of a specific type.  All implementations of the interface
1458        * need to return items of this type -- but may be more
1459        * restrictive.  For example, it is legal to have:
1460        *
1461        *   GtkWidget *get_item();
1462        *
1463        * that is implemented by a function that always returns a
1464        * GtkEntry.  In short: readability implies that the
1465        * implementation  value type must be equal or more restrictive.
1466        *
1467        * Similarly, if the property on the interface is writable then
1468        * must be able to accept the property being set to any value of
1469        * that type, including subclasses.  In this case, we may also be
1470        * less restrictive.  For example, it is legal to have:
1471        *
1472        *   set_item (GtkEntry *);
1473        *
1474        * that is implemented by a function that will actually work with
1475        * any GtkWidget.  In short: writability implies that the
1476        * implementation value type must be equal or less restrictive.
1477        *
1478        * In the case that the property is both readable and writable
1479        * then the only way that both of the above can be satisfied is
1480        * with a type that is exactly equal.
1481        */
1482       switch (pspecs[n]->flags & (G_PARAM_READABLE | G_PARAM_WRITABLE))
1483         {
1484         case G_PARAM_READABLE | G_PARAM_WRITABLE:
1485           /* class pspec value type must have exact equality with interface */
1486           if (pspecs[n]->value_type != class_pspec->value_type)
1487             g_critical ("Read/writable property '%s' on class '%s' has type '%s' which is not exactly equal to the "
1488                         "type '%s' of the property on the interface '%s'\n", pspecs[n]->name,
1489                         g_type_name (G_OBJECT_CLASS_TYPE (class)), g_type_name (G_PARAM_SPEC_VALUE_TYPE (class_pspec)),
1490                         g_type_name (G_PARAM_SPEC_VALUE_TYPE (pspecs[n])), g_type_name (iface_type));
1491           break;
1492
1493         case G_PARAM_READABLE:
1494           /* class pspec value type equal or more restrictive than interface */
1495           if (!g_type_is_a (class_pspec->value_type, pspecs[n]->value_type))
1496             g_critical ("Read-only property '%s' on class '%s' has type '%s' which is not equal to or more "
1497                         "restrictive than the type '%s' of the property on the interface '%s'\n", pspecs[n]->name,
1498                         g_type_name (G_OBJECT_CLASS_TYPE (class)), g_type_name (G_PARAM_SPEC_VALUE_TYPE (class_pspec)),
1499                         g_type_name (G_PARAM_SPEC_VALUE_TYPE (pspecs[n])), g_type_name (iface_type));
1500           break;
1501
1502         case G_PARAM_WRITABLE:
1503           /* class pspec value type equal or less restrictive than interface */
1504           if (!g_type_is_a (pspecs[n]->value_type, class_pspec->value_type))
1505             g_critical ("Write-only property '%s' on class '%s' has type '%s' which is not equal to or less "
1506                         "restrictive than the type '%s' of the property on the interface '%s' \n", pspecs[n]->name,
1507                         g_type_name (G_OBJECT_CLASS_TYPE (class)), g_type_name (G_PARAM_SPEC_VALUE_TYPE (class_pspec)),
1508                         g_type_name (G_PARAM_SPEC_VALUE_TYPE (pspecs[n])), g_type_name (iface_type));
1509           break;
1510
1511         default:
1512           g_assert_not_reached ();
1513         }
1514     }
1515
1516   g_free (pspecs);
1517
1518   g_type_class_unref (class);
1519 }
1520
1521 GType
1522 g_object_get_type (void)
1523 {
1524     return G_TYPE_OBJECT;
1525 }
1526
1527 /**
1528  * g_object_new: (skip)
1529  * @object_type: the type id of the #GObject subtype to instantiate
1530  * @first_property_name: the name of the first property
1531  * @...: the value of the first property, followed optionally by more
1532  *  name/value pairs, followed by %NULL
1533  *
1534  * Creates a new instance of a #GObject subtype and sets its properties.
1535  *
1536  * Construction parameters (see #G_PARAM_CONSTRUCT, #G_PARAM_CONSTRUCT_ONLY)
1537  * which are not explicitly specified are set to their default values.
1538  *
1539  * Returns: (transfer full): a new instance of @object_type
1540  */
1541 gpointer
1542 g_object_new (GType        object_type,
1543               const gchar *first_property_name,
1544               ...)
1545 {
1546   GObject *object;
1547   va_list var_args;
1548   
1549   g_return_val_if_fail (G_TYPE_IS_OBJECT (object_type), NULL);
1550   
1551   /* short circuit for calls supplying no properties */
1552   if (!first_property_name)
1553     return g_object_newv (object_type, 0, NULL);
1554
1555   va_start (var_args, first_property_name);
1556   object = g_object_new_valist (object_type, first_property_name, var_args);
1557   va_end (var_args);
1558   
1559   return object;
1560 }
1561
1562 static gboolean
1563 slist_maybe_remove (GSList       **slist,
1564                     gconstpointer  data)
1565 {
1566   GSList *last = NULL, *node = *slist;
1567   while (node)
1568     {
1569       if (node->data == data)
1570         {
1571           if (last)
1572             last->next = node->next;
1573           else
1574             *slist = node->next;
1575           g_slist_free_1 (node);
1576           return TRUE;
1577         }
1578       last = node;
1579       node = last->next;
1580     }
1581   return FALSE;
1582 }
1583
1584 static inline gboolean
1585 object_in_construction_list (GObject *object)
1586 {
1587   gboolean in_construction;
1588   G_LOCK (construction_mutex);
1589   in_construction = g_slist_find (construction_objects, object) != NULL;
1590   G_UNLOCK (construction_mutex);
1591   return in_construction;
1592 }
1593
1594 static gpointer
1595 g_object_new_with_custom_constructor (GObjectClass          *class,
1596                                       GObjectConstructParam *params,
1597                                       guint                  n_params)
1598 {
1599   GObjectNotifyQueue *nqueue = NULL;
1600   gboolean newly_constructed;
1601   GObjectConstructParam *cparams;
1602   GObject *object;
1603   GValue *cvalues;
1604   gint n_cparams;
1605   gint cvals_used;
1606   GSList *node;
1607   gint i;
1608
1609   /* If we have ->constructed() then we have to do a lot more work.
1610    * It's possible that this is a singleton and it's also possible
1611    * that the user's constructor() will attempt to modify the values
1612    * that we pass in, so we'll need to allocate copies of them.
1613    * It's also possible that the user may attempt to call
1614    * g_object_set() from inside of their constructor, so we need to
1615    * add ourselves to a list of objects for which that is allowed
1616    * while their constructor() is running.
1617    */
1618
1619   /* Create the array of GObjectConstructParams for constructor() */
1620   n_cparams = g_slist_length (class->construct_properties);
1621   cparams = g_new (GObjectConstructParam, n_cparams);
1622   cvalues = g_new0 (GValue, n_cparams);
1623   cvals_used = 0;
1624   i = 0;
1625
1626   /* As above, we may find the value in the passed-in params list.
1627    *
1628    * If we have the value passed in then we can use the GValue from
1629    * it directly because it is safe to modify.  If we use the
1630    * default value from the class, we had better not pass that in
1631    * and risk it being modified, so we create a new one.
1632    * */
1633   for (node = class->construct_properties; node; node = node->next)
1634     {
1635       GParamSpec *pspec;
1636       GValue *value;
1637       gint j;
1638
1639       pspec = node->data;
1640       value = NULL; /* to silence gcc... */
1641
1642       for (j = 0; j < n_params; j++)
1643         if (params[j].pspec == pspec)
1644           {
1645             value = params[j].value;
1646             break;
1647           }
1648
1649       if (j == n_params)
1650         {
1651           value = &cvalues[cvals_used++];
1652           g_value_init (value, pspec->value_type);
1653           g_param_value_set_default (pspec, value);
1654         }
1655
1656       cparams[i].pspec = pspec;
1657       cparams[i].value = value;
1658       i++;
1659     }
1660
1661   /* construct object from construction parameters */
1662   object = class->constructor (class->g_type_class.g_type, n_cparams, cparams);
1663   /* free construction values */
1664   g_free (cparams);
1665   while (cvals_used--)
1666     g_value_unset (&cvalues[cvals_used]);
1667   g_free (cvalues);
1668
1669   /* There is code in the wild that relies on being able to return NULL
1670    * from its custom constructor.  This was never a supported operation
1671    * and will leak memory, but since the code is already out there...
1672    */
1673   if (object == NULL)
1674     {
1675       g_critical ("Custom constructor for class %s returned NULL (which is invalid).  Unable to remove object "
1676                   "from construction_objects list, so memory was probably just leaked.  Please use GInitable "
1677                   "instead.", G_OBJECT_CLASS_NAME (class));
1678       return NULL;
1679     }
1680
1681   /* g_object_init() will have added us to the construction_objects
1682    * list.  Check if we're in it (and remove us) in order to find
1683    * out if we were newly-constructed or this is an already-existing
1684    * singleton (in which case we should not do 'constructed').
1685    */
1686   G_LOCK (construction_mutex);
1687   newly_constructed = slist_maybe_remove (&construction_objects, object);
1688   G_UNLOCK (construction_mutex);
1689
1690   if (CLASS_HAS_PROPS (class))
1691     {
1692       /* If this object was newly_constructed then g_object_init()
1693        * froze the queue.  We need to freeze it here in order to get
1694        * the handle so that we can thaw it below (otherwise it will
1695        * be frozen forever).
1696        *
1697        * We also want to do a freeze if we have any params to set,
1698        * even on a non-newly_constructed object.
1699        *
1700        * It's possible that we have the case of non-newly created
1701        * singleton and all of the passed-in params were construct
1702        * properties so n_params > 0 but we will actually set no
1703        * properties.  This is a pretty lame case to optimise, so
1704        * just ignore it and freeze anyway.
1705        */
1706       if (newly_constructed || n_params)
1707         nqueue = g_object_notify_queue_freeze (object, FALSE);
1708
1709       /* Remember: if it was newly_constructed then g_object_init()
1710        * already did a freeze, so we now have two.  Release one.
1711        */
1712       if (newly_constructed)
1713         g_object_notify_queue_thaw (object, nqueue);
1714     }
1715
1716   /* run 'constructed' handler if there is a custom one */
1717   if (newly_constructed && CLASS_HAS_CUSTOM_CONSTRUCTED (class))
1718     class->constructed (object);
1719
1720   /* set remaining properties */
1721   for (i = 0; i < n_params; i++)
1722     if (!(params[i].pspec->flags & (G_PARAM_CONSTRUCT | G_PARAM_CONSTRUCT_ONLY)))
1723       object_set_property (object, params[i].pspec, params[i].value, nqueue);
1724
1725   /* If nqueue is non-NULL then we are frozen.  Thaw it. */
1726   if (nqueue)
1727     g_object_notify_queue_thaw (object, nqueue);
1728
1729   return object;
1730 }
1731
1732 static gpointer
1733 g_object_new_internal (GObjectClass          *class,
1734                        GObjectConstructParam *params,
1735                        guint                  n_params)
1736 {
1737   GObjectNotifyQueue *nqueue = NULL;
1738   GObject *object;
1739
1740   if G_UNLIKELY (CLASS_HAS_CUSTOM_CONSTRUCTOR (class))
1741     return g_object_new_with_custom_constructor (class, params, n_params);
1742
1743   object = (GObject *) g_type_create_instance (class->g_type_class.g_type);
1744
1745   if (CLASS_HAS_PROPS (class))
1746     {
1747       GSList *node;
1748
1749       /* This will have been setup in g_object_init() */
1750       nqueue = g_datalist_id_get_data (&object->qdata, quark_notify_queue);
1751       g_assert (nqueue != NULL);
1752
1753       /* We will set exactly n_construct_properties construct
1754        * properties, but they may come from either the class default
1755        * values or the passed-in parameter list.
1756        */
1757       for (node = class->construct_properties; node; node = node->next)
1758         {
1759           const GValue *value;
1760           GParamSpec *pspec;
1761           gint j;
1762
1763           pspec = node->data;
1764           value = NULL; /* to silence gcc... */
1765
1766           for (j = 0; j < n_params; j++)
1767             if (params[j].pspec == pspec)
1768               {
1769                 value = params[j].value;
1770                 break;
1771               }
1772
1773           if (j == n_params)
1774             value = g_param_spec_get_default_value (pspec);
1775
1776           object_set_property (object, pspec, value, nqueue);
1777         }
1778     }
1779
1780   /* run 'constructed' handler if there is a custom one */
1781   if (CLASS_HAS_CUSTOM_CONSTRUCTED (class))
1782     class->constructed (object);
1783
1784   if (nqueue)
1785     {
1786       gint i;
1787
1788       /* Set remaining properties.  The construct properties will
1789        * already have been taken, so set only the non-construct
1790        * ones.
1791        */
1792       for (i = 0; i < n_params; i++)
1793         if (!(params[i].pspec->flags & (G_PARAM_CONSTRUCT | G_PARAM_CONSTRUCT_ONLY)))
1794           object_set_property (object, params[i].pspec, params[i].value, nqueue);
1795
1796       g_object_notify_queue_thaw (object, nqueue);
1797     }
1798
1799   return object;
1800 }
1801
1802 /**
1803  * g_object_newv:
1804  * @object_type: the type id of the #GObject subtype to instantiate
1805  * @n_parameters: the length of the @parameters array
1806  * @parameters: (array length=n_parameters): an array of #GParameter
1807  *
1808  * Creates a new instance of a #GObject subtype and sets its properties.
1809  *
1810  * Construction parameters (see #G_PARAM_CONSTRUCT, #G_PARAM_CONSTRUCT_ONLY)
1811  * which are not explicitly specified are set to their default values.
1812  *
1813  * Rename to: g_object_new
1814  * Returns: (type GObject.Object) (transfer full): a new instance of
1815  * @object_type
1816  */
1817 gpointer
1818 g_object_newv (GType       object_type,
1819                guint       n_parameters,
1820                GParameter *parameters)
1821 {
1822   GObjectClass *class, *unref_class = NULL;
1823   GObject *object;
1824
1825   g_return_val_if_fail (G_TYPE_IS_OBJECT (object_type), NULL);
1826   g_return_val_if_fail (n_parameters == 0 || parameters != NULL, NULL);
1827
1828   /* Try to avoid thrashing the ref_count if we don't need to (since
1829    * it's a locked operation).
1830    */
1831   class = g_type_class_peek_static (object_type);
1832
1833   if (!class)
1834     class = unref_class = g_type_class_ref (object_type);
1835
1836   if (n_parameters)
1837     {
1838       GObjectConstructParam *cparams;
1839       guint i, j;
1840
1841       cparams = g_newa (GObjectConstructParam, n_parameters);
1842       j = 0;
1843
1844       for (i = 0; i < n_parameters; i++)
1845         {
1846           GParamSpec *pspec;
1847           gint k;
1848
1849           pspec = g_param_spec_pool_lookup (pspec_pool, parameters[i].name, object_type, TRUE);
1850
1851           if G_UNLIKELY (!pspec)
1852             {
1853               g_critical ("%s: object class '%s' has no property named '%s'",
1854                           G_STRFUNC, g_type_name (object_type), parameters[i].name);
1855               continue;
1856             }
1857
1858           if G_UNLIKELY (~pspec->flags & G_PARAM_WRITABLE)
1859             {
1860               g_critical ("%s: property '%s' of object class '%s' is not writable",
1861                           G_STRFUNC, pspec->name, g_type_name (object_type));
1862               continue;
1863             }
1864
1865           if (pspec->flags & (G_PARAM_CONSTRUCT | G_PARAM_CONSTRUCT_ONLY))
1866             {
1867               for (k = 0; k < j; k++)
1868                 if (cparams[k].pspec == pspec)
1869                     break;
1870               if G_UNLIKELY (k != j)
1871                 {
1872                   g_critical ("%s: construct property '%s' for type '%s' cannot be set twice",
1873                               G_STRFUNC, parameters[i].name, g_type_name (object_type));
1874                   continue;
1875                 }
1876             }
1877
1878           cparams[j].pspec = pspec;
1879           cparams[j].value = &parameters[i].value;
1880           j++;
1881         }
1882
1883       object = g_object_new_internal (class, cparams, j);
1884     }
1885   else
1886     /* Fast case: no properties passed in. */
1887     object = g_object_new_internal (class, NULL, 0);
1888
1889   if (unref_class)
1890     g_type_class_unref (unref_class);
1891
1892   return object;
1893 }
1894
1895 /**
1896  * g_object_new_valist: (skip)
1897  * @object_type: the type id of the #GObject subtype to instantiate
1898  * @first_property_name: the name of the first property
1899  * @var_args: the value of the first property, followed optionally by more
1900  *  name/value pairs, followed by %NULL
1901  *
1902  * Creates a new instance of a #GObject subtype and sets its properties.
1903  *
1904  * Construction parameters (see #G_PARAM_CONSTRUCT, #G_PARAM_CONSTRUCT_ONLY)
1905  * which are not explicitly specified are set to their default values.
1906  *
1907  * Returns: a new instance of @object_type
1908  */
1909 GObject*
1910 g_object_new_valist (GType        object_type,
1911                      const gchar *first_property_name,
1912                      va_list      var_args)
1913 {
1914   GObjectClass *class, *unref_class = NULL;
1915   GObject *object;
1916
1917   g_return_val_if_fail (G_TYPE_IS_OBJECT (object_type), NULL);
1918
1919   /* Try to avoid thrashing the ref_count if we don't need to (since
1920    * it's a locked operation).
1921    */
1922   class = g_type_class_peek_static (object_type);
1923
1924   if (!class)
1925     class = unref_class = g_type_class_ref (object_type);
1926
1927   if (first_property_name)
1928     {
1929       GObjectConstructParam stack_params[16];
1930       GObjectConstructParam *params;
1931       const gchar *name;
1932       gint n_params = 0;
1933
1934       name = first_property_name;
1935       params = stack_params;
1936
1937       do
1938         {
1939           gchar *error = NULL;
1940           GParamSpec *pspec;
1941           gint i;
1942
1943           pspec = g_param_spec_pool_lookup (pspec_pool, name, object_type, TRUE);
1944
1945           if G_UNLIKELY (!pspec)
1946             {
1947               g_critical ("%s: object class '%s' has no property named '%s'",
1948                           G_STRFUNC, g_type_name (object_type), name);
1949               /* Can't continue because arg list will be out of sync. */
1950               break;
1951             }
1952
1953           if G_UNLIKELY (~pspec->flags & G_PARAM_WRITABLE)
1954             {
1955               g_critical ("%s: property '%s' of object class '%s' is not writable",
1956                           G_STRFUNC, pspec->name, g_type_name (object_type));
1957               break;
1958             }
1959
1960           if (pspec->flags & (G_PARAM_CONSTRUCT | G_PARAM_CONSTRUCT_ONLY))
1961             {
1962               for (i = 0; i < n_params; i++)
1963                 if (params[i].pspec == pspec)
1964                     break;
1965               if G_UNLIKELY (i != n_params)
1966                 {
1967                   g_critical ("%s: property '%s' for type '%s' cannot be set twice",
1968                               G_STRFUNC, name, g_type_name (object_type));
1969                   break;
1970                 }
1971             }
1972
1973           if (n_params == 16)
1974             {
1975               params = g_new (GObjectConstructParam, n_params + 1);
1976               memcpy (params, stack_params, sizeof stack_params);
1977             }
1978           else if (n_params > 16)
1979             params = g_renew (GObjectConstructParam, params, n_params + 1);
1980
1981           params[n_params].pspec = pspec;
1982           params[n_params].value = g_newa (GValue, 1);
1983           memset (params[n_params].value, 0, sizeof (GValue));
1984
1985           G_VALUE_COLLECT_INIT (params[n_params].value, pspec->value_type, var_args, 0, &error);
1986
1987           if (error)
1988             {
1989               g_critical ("%s: %s", G_STRFUNC, error);
1990               g_value_unset (params[n_params].value);
1991               g_free (error);
1992               break;
1993             }
1994
1995           n_params++;
1996         }
1997       while ((name = va_arg (var_args, const gchar *)));
1998
1999       object = g_object_new_internal (class, params, n_params);
2000
2001       while (n_params--)
2002         g_value_unset (params[n_params].value);
2003
2004       if (params != stack_params)
2005         g_free (params);
2006     }
2007   else
2008     /* Fast case: no properties passed in. */
2009     object = g_object_new_internal (class, NULL, 0);
2010
2011   if (unref_class)
2012     g_type_class_unref (unref_class);
2013
2014   return object;
2015 }
2016
2017 static GObject*
2018 g_object_constructor (GType                  type,
2019                       guint                  n_construct_properties,
2020                       GObjectConstructParam *construct_params)
2021 {
2022   GObject *object;
2023
2024   /* create object */
2025   object = (GObject*) g_type_create_instance (type);
2026   
2027   /* set construction parameters */
2028   if (n_construct_properties)
2029     {
2030       GObjectNotifyQueue *nqueue = g_object_notify_queue_freeze (object, FALSE);
2031       
2032       /* set construct properties */
2033       while (n_construct_properties--)
2034         {
2035           GValue *value = construct_params->value;
2036           GParamSpec *pspec = construct_params->pspec;
2037
2038           construct_params++;
2039           object_set_property (object, pspec, value, nqueue);
2040         }
2041       g_object_notify_queue_thaw (object, nqueue);
2042       /* the notification queue is still frozen from g_object_init(), so
2043        * we don't need to handle it here, g_object_newv() takes
2044        * care of that
2045        */
2046     }
2047
2048   return object;
2049 }
2050
2051 static void
2052 g_object_constructed (GObject *object)
2053 {
2054   /* empty default impl to allow unconditional upchaining */
2055 }
2056
2057 /**
2058  * g_object_set_valist: (skip)
2059  * @object: a #GObject
2060  * @first_property_name: name of the first property to set
2061  * @var_args: value for the first property, followed optionally by more
2062  *  name/value pairs, followed by %NULL
2063  *
2064  * Sets properties on an object.
2065  */
2066 void
2067 g_object_set_valist (GObject     *object,
2068                      const gchar *first_property_name,
2069                      va_list      var_args)
2070 {
2071   GObjectNotifyQueue *nqueue;
2072   const gchar *name;
2073   
2074   g_return_if_fail (G_IS_OBJECT (object));
2075   
2076   g_object_ref (object);
2077   nqueue = g_object_notify_queue_freeze (object, FALSE);
2078   
2079   name = first_property_name;
2080   while (name)
2081     {
2082       GValue value = G_VALUE_INIT;
2083       GParamSpec *pspec;
2084       gchar *error = NULL;
2085       
2086       pspec = g_param_spec_pool_lookup (pspec_pool,
2087                                         name,
2088                                         G_OBJECT_TYPE (object),
2089                                         TRUE);
2090       if (!pspec)
2091         {
2092           g_warning ("%s: object class '%s' has no property named '%s'",
2093                      G_STRFUNC,
2094                      G_OBJECT_TYPE_NAME (object),
2095                      name);
2096           break;
2097         }
2098       if (!(pspec->flags & G_PARAM_WRITABLE))
2099         {
2100           g_warning ("%s: property '%s' of object class '%s' is not writable",
2101                      G_STRFUNC,
2102                      pspec->name,
2103                      G_OBJECT_TYPE_NAME (object));
2104           break;
2105         }
2106       if ((pspec->flags & G_PARAM_CONSTRUCT_ONLY) && !object_in_construction_list (object))
2107         {
2108           g_warning ("%s: construct property \"%s\" for object '%s' can't be set after construction",
2109                      G_STRFUNC, pspec->name, G_OBJECT_TYPE_NAME (object));
2110           break;
2111         }
2112
2113       G_VALUE_COLLECT_INIT (&value, pspec->value_type, var_args,
2114                             0, &error);
2115       if (error)
2116         {
2117           g_warning ("%s: %s", G_STRFUNC, error);
2118           g_free (error);
2119           g_value_unset (&value);
2120           break;
2121         }
2122       
2123       object_set_property (object, pspec, &value, nqueue);
2124       g_value_unset (&value);
2125       
2126       name = va_arg (var_args, gchar*);
2127     }
2128
2129   g_object_notify_queue_thaw (object, nqueue);
2130   g_object_unref (object);
2131 }
2132
2133 /**
2134  * g_object_get_valist: (skip)
2135  * @object: a #GObject
2136  * @first_property_name: name of the first property to get
2137  * @var_args: return location for the first property, followed optionally by more
2138  *  name/return location pairs, followed by %NULL
2139  *
2140  * Gets properties of an object.
2141  *
2142  * In general, a copy is made of the property contents and the caller
2143  * is responsible for freeing the memory in the appropriate manner for
2144  * the type, for instance by calling g_free() or g_object_unref().
2145  *
2146  * See g_object_get().
2147  */
2148 void
2149 g_object_get_valist (GObject     *object,
2150                      const gchar *first_property_name,
2151                      va_list      var_args)
2152 {
2153   const gchar *name;
2154   
2155   g_return_if_fail (G_IS_OBJECT (object));
2156   
2157   g_object_ref (object);
2158   
2159   name = first_property_name;
2160   
2161   while (name)
2162     {
2163       GValue value = G_VALUE_INIT;
2164       GParamSpec *pspec;
2165       gchar *error;
2166       
2167       pspec = g_param_spec_pool_lookup (pspec_pool,
2168                                         name,
2169                                         G_OBJECT_TYPE (object),
2170                                         TRUE);
2171       if (!pspec)
2172         {
2173           g_warning ("%s: object class '%s' has no property named '%s'",
2174                      G_STRFUNC,
2175                      G_OBJECT_TYPE_NAME (object),
2176                      name);
2177           break;
2178         }
2179       if (!(pspec->flags & G_PARAM_READABLE))
2180         {
2181           g_warning ("%s: property '%s' of object class '%s' is not readable",
2182                      G_STRFUNC,
2183                      pspec->name,
2184                      G_OBJECT_TYPE_NAME (object));
2185           break;
2186         }
2187       
2188       g_value_init (&value, pspec->value_type);
2189       
2190       object_get_property (object, pspec, &value);
2191       
2192       G_VALUE_LCOPY (&value, var_args, 0, &error);
2193       if (error)
2194         {
2195           g_warning ("%s: %s", G_STRFUNC, error);
2196           g_free (error);
2197           g_value_unset (&value);
2198           break;
2199         }
2200       
2201       g_value_unset (&value);
2202       
2203       name = va_arg (var_args, gchar*);
2204     }
2205   
2206   g_object_unref (object);
2207 }
2208
2209 /**
2210  * g_object_set: (skip)
2211  * @object: a #GObject
2212  * @first_property_name: name of the first property to set
2213  * @...: value for the first property, followed optionally by more
2214  *  name/value pairs, followed by %NULL
2215  *
2216  * Sets properties on an object.
2217  */
2218 void
2219 g_object_set (gpointer     _object,
2220               const gchar *first_property_name,
2221               ...)
2222 {
2223   GObject *object = _object;
2224   va_list var_args;
2225   
2226   g_return_if_fail (G_IS_OBJECT (object));
2227   
2228   va_start (var_args, first_property_name);
2229   g_object_set_valist (object, first_property_name, var_args);
2230   va_end (var_args);
2231 }
2232
2233 /**
2234  * g_object_get: (skip)
2235  * @object: a #GObject
2236  * @first_property_name: name of the first property to get
2237  * @...: return location for the first property, followed optionally by more
2238  *  name/return location pairs, followed by %NULL
2239  *
2240  * Gets properties of an object.
2241  *
2242  * In general, a copy is made of the property contents and the caller
2243  * is responsible for freeing the memory in the appropriate manner for
2244  * the type, for instance by calling g_free() or g_object_unref().
2245  *
2246  * <example>
2247  * <title>Using g_object_get(<!-- -->)</title>
2248  * An example of using g_object_get() to get the contents
2249  * of three properties - one of type #G_TYPE_INT,
2250  * one of type #G_TYPE_STRING, and one of type #G_TYPE_OBJECT:
2251  * <programlisting>
2252  *  gint intval;
2253  *  gchar *strval;
2254  *  GObject *objval;
2255  *
2256  *  g_object_get (my_object,
2257  *                "int-property", &intval,
2258  *                "str-property", &strval,
2259  *                "obj-property", &objval,
2260  *                NULL);
2261  *
2262  *  // Do something with intval, strval, objval
2263  *
2264  *  g_free (strval);
2265  *  g_object_unref (objval);
2266  * </programlisting>
2267  * </example>
2268  */
2269 void
2270 g_object_get (gpointer     _object,
2271               const gchar *first_property_name,
2272               ...)
2273 {
2274   GObject *object = _object;
2275   va_list var_args;
2276   
2277   g_return_if_fail (G_IS_OBJECT (object));
2278   
2279   va_start (var_args, first_property_name);
2280   g_object_get_valist (object, first_property_name, var_args);
2281   va_end (var_args);
2282 }
2283
2284 /**
2285  * g_object_set_property:
2286  * @object: a #GObject
2287  * @property_name: the name of the property to set
2288  * @value: the value
2289  *
2290  * Sets a property on an object.
2291  */
2292 void
2293 g_object_set_property (GObject      *object,
2294                        const gchar  *property_name,
2295                        const GValue *value)
2296 {
2297   GObjectNotifyQueue *nqueue;
2298   GParamSpec *pspec;
2299   
2300   g_return_if_fail (G_IS_OBJECT (object));
2301   g_return_if_fail (property_name != NULL);
2302   g_return_if_fail (G_IS_VALUE (value));
2303   
2304   g_object_ref (object);
2305   nqueue = g_object_notify_queue_freeze (object, FALSE);
2306   
2307   pspec = g_param_spec_pool_lookup (pspec_pool,
2308                                     property_name,
2309                                     G_OBJECT_TYPE (object),
2310                                     TRUE);
2311   if (!pspec)
2312     g_warning ("%s: object class '%s' has no property named '%s'",
2313                G_STRFUNC,
2314                G_OBJECT_TYPE_NAME (object),
2315                property_name);
2316   else if (!(pspec->flags & G_PARAM_WRITABLE))
2317     g_warning ("%s: property '%s' of object class '%s' is not writable",
2318                G_STRFUNC,
2319                pspec->name,
2320                G_OBJECT_TYPE_NAME (object));
2321   else if ((pspec->flags & G_PARAM_CONSTRUCT_ONLY) && !object_in_construction_list (object))
2322     g_warning ("%s: construct property \"%s\" for object '%s' can't be set after construction",
2323                G_STRFUNC, pspec->name, G_OBJECT_TYPE_NAME (object));
2324   else
2325     object_set_property (object, pspec, value, nqueue);
2326   
2327   g_object_notify_queue_thaw (object, nqueue);
2328   g_object_unref (object);
2329 }
2330
2331 /**
2332  * g_object_get_property:
2333  * @object: a #GObject
2334  * @property_name: the name of the property to get
2335  * @value: return location for the property value
2336  *
2337  * Gets a property of an object. @value must have been initialized to the
2338  * expected type of the property (or a type to which the expected type can be
2339  * transformed) using g_value_init().
2340  *
2341  * In general, a copy is made of the property contents and the caller is
2342  * responsible for freeing the memory by calling g_value_unset().
2343  *
2344  * Note that g_object_get_property() is really intended for language
2345  * bindings, g_object_get() is much more convenient for C programming.
2346  */
2347 void
2348 g_object_get_property (GObject     *object,
2349                        const gchar *property_name,
2350                        GValue      *value)
2351 {
2352   GParamSpec *pspec;
2353   
2354   g_return_if_fail (G_IS_OBJECT (object));
2355   g_return_if_fail (property_name != NULL);
2356   g_return_if_fail (G_IS_VALUE (value));
2357   
2358   g_object_ref (object);
2359   
2360   pspec = g_param_spec_pool_lookup (pspec_pool,
2361                                     property_name,
2362                                     G_OBJECT_TYPE (object),
2363                                     TRUE);
2364   if (!pspec)
2365     g_warning ("%s: object class '%s' has no property named '%s'",
2366                G_STRFUNC,
2367                G_OBJECT_TYPE_NAME (object),
2368                property_name);
2369   else if (!(pspec->flags & G_PARAM_READABLE))
2370     g_warning ("%s: property '%s' of object class '%s' is not readable",
2371                G_STRFUNC,
2372                pspec->name,
2373                G_OBJECT_TYPE_NAME (object));
2374   else
2375     {
2376       GValue *prop_value, tmp_value = G_VALUE_INIT;
2377       
2378       /* auto-conversion of the callers value type
2379        */
2380       if (G_VALUE_TYPE (value) == pspec->value_type)
2381         {
2382           g_value_reset (value);
2383           prop_value = value;
2384         }
2385       else if (!g_value_type_transformable (pspec->value_type, G_VALUE_TYPE (value)))
2386         {
2387           g_warning ("%s: can't retrieve property '%s' of type '%s' as value of type '%s'",
2388                      G_STRFUNC, pspec->name,
2389                      g_type_name (pspec->value_type),
2390                      G_VALUE_TYPE_NAME (value));
2391           g_object_unref (object);
2392           return;
2393         }
2394       else
2395         {
2396           g_value_init (&tmp_value, pspec->value_type);
2397           prop_value = &tmp_value;
2398         }
2399       object_get_property (object, pspec, prop_value);
2400       if (prop_value != value)
2401         {
2402           g_value_transform (prop_value, value);
2403           g_value_unset (&tmp_value);
2404         }
2405     }
2406   
2407   g_object_unref (object);
2408 }
2409
2410 /**
2411  * g_object_connect: (skip)
2412  * @object: a #GObject
2413  * @signal_spec: the spec for the first signal
2414  * @...: #GCallback for the first signal, followed by data for the
2415  *       first signal, followed optionally by more signal
2416  *       spec/callback/data triples, followed by %NULL
2417  *
2418  * A convenience function to connect multiple signals at once.
2419  *
2420  * The signal specs expected by this function have the form
2421  * "modifier::signal_name", where modifier can be one of the following:
2422  * <variablelist>
2423  * <varlistentry>
2424  * <term>signal</term>
2425  * <listitem><para>
2426  * equivalent to <literal>g_signal_connect_data (..., NULL, 0)</literal>
2427  * </para></listitem>
2428  * </varlistentry>
2429  * <varlistentry>
2430  * <term>object_signal</term>
2431  * <term>object-signal</term>
2432  * <listitem><para>
2433  * equivalent to <literal>g_signal_connect_object (..., 0)</literal>
2434  * </para></listitem>
2435  * </varlistentry>
2436  * <varlistentry>
2437  * <term>swapped_signal</term>
2438  * <term>swapped-signal</term>
2439  * <listitem><para>
2440  * equivalent to <literal>g_signal_connect_data (..., NULL, G_CONNECT_SWAPPED)</literal>
2441  * </para></listitem>
2442  * </varlistentry>
2443  * <varlistentry>
2444  * <term>swapped_object_signal</term>
2445  * <term>swapped-object-signal</term>
2446  * <listitem><para>
2447  * equivalent to <literal>g_signal_connect_object (..., G_CONNECT_SWAPPED)</literal>
2448  * </para></listitem>
2449  * </varlistentry>
2450  * <varlistentry>
2451  * <term>signal_after</term>
2452  * <term>signal-after</term>
2453  * <listitem><para>
2454  * equivalent to <literal>g_signal_connect_data (..., NULL, G_CONNECT_AFTER)</literal>
2455  * </para></listitem>
2456  * </varlistentry>
2457  * <varlistentry>
2458  * <term>object_signal_after</term>
2459  * <term>object-signal-after</term>
2460  * <listitem><para>
2461  * equivalent to <literal>g_signal_connect_object (..., G_CONNECT_AFTER)</literal>
2462  * </para></listitem>
2463  * </varlistentry>
2464  * <varlistentry>
2465  * <term>swapped_signal_after</term>
2466  * <term>swapped-signal-after</term>
2467  * <listitem><para>
2468  * equivalent to <literal>g_signal_connect_data (..., NULL, G_CONNECT_SWAPPED | G_CONNECT_AFTER)</literal>
2469  * </para></listitem>
2470  * </varlistentry>
2471  * <varlistentry>
2472  * <term>swapped_object_signal_after</term>
2473  * <term>swapped-object-signal-after</term>
2474  * <listitem><para>
2475  * equivalent to <literal>g_signal_connect_object (..., G_CONNECT_SWAPPED | G_CONNECT_AFTER)</literal>
2476  * </para></listitem>
2477  * </varlistentry>
2478  * </variablelist>
2479  *
2480  * |[
2481  *   menu->toplevel = g_object_connect (g_object_new (GTK_TYPE_WINDOW,
2482  *                                                 "type", GTK_WINDOW_POPUP,
2483  *                                                 "child", menu,
2484  *                                                 NULL),
2485  *                                   "signal::event", gtk_menu_window_event, menu,
2486  *                                   "signal::size_request", gtk_menu_window_size_request, menu,
2487  *                                   "signal::destroy", gtk_widget_destroyed, &amp;menu-&gt;toplevel,
2488  *                                   NULL);
2489  * ]|
2490  *
2491  * Returns: (transfer none): @object
2492  */
2493 gpointer
2494 g_object_connect (gpointer     _object,
2495                   const gchar *signal_spec,
2496                   ...)
2497 {
2498   GObject *object = _object;
2499   va_list var_args;
2500
2501   g_return_val_if_fail (G_IS_OBJECT (object), NULL);
2502   g_return_val_if_fail (object->ref_count > 0, object);
2503
2504   va_start (var_args, signal_spec);
2505   while (signal_spec)
2506     {
2507       GCallback callback = va_arg (var_args, GCallback);
2508       gpointer data = va_arg (var_args, gpointer);
2509
2510       if (strncmp (signal_spec, "signal::", 8) == 0)
2511         g_signal_connect_data (object, signal_spec + 8,
2512                                callback, data, NULL,
2513                                0);
2514       else if (strncmp (signal_spec, "object_signal::", 15) == 0 ||
2515                strncmp (signal_spec, "object-signal::", 15) == 0)
2516         g_signal_connect_object (object, signal_spec + 15,
2517                                  callback, data,
2518                                  0);
2519       else if (strncmp (signal_spec, "swapped_signal::", 16) == 0 ||
2520                strncmp (signal_spec, "swapped-signal::", 16) == 0)
2521         g_signal_connect_data (object, signal_spec + 16,
2522                                callback, data, NULL,
2523                                G_CONNECT_SWAPPED);
2524       else if (strncmp (signal_spec, "swapped_object_signal::", 23) == 0 ||
2525                strncmp (signal_spec, "swapped-object-signal::", 23) == 0)
2526         g_signal_connect_object (object, signal_spec + 23,
2527                                  callback, data,
2528                                  G_CONNECT_SWAPPED);
2529       else if (strncmp (signal_spec, "signal_after::", 14) == 0 ||
2530                strncmp (signal_spec, "signal-after::", 14) == 0)
2531         g_signal_connect_data (object, signal_spec + 14,
2532                                callback, data, NULL,
2533                                G_CONNECT_AFTER);
2534       else if (strncmp (signal_spec, "object_signal_after::", 21) == 0 ||
2535                strncmp (signal_spec, "object-signal-after::", 21) == 0)
2536         g_signal_connect_object (object, signal_spec + 21,
2537                                  callback, data,
2538                                  G_CONNECT_AFTER);
2539       else if (strncmp (signal_spec, "swapped_signal_after::", 22) == 0 ||
2540                strncmp (signal_spec, "swapped-signal-after::", 22) == 0)
2541         g_signal_connect_data (object, signal_spec + 22,
2542                                callback, data, NULL,
2543                                G_CONNECT_SWAPPED | G_CONNECT_AFTER);
2544       else if (strncmp (signal_spec, "swapped_object_signal_after::", 29) == 0 ||
2545                strncmp (signal_spec, "swapped-object-signal-after::", 29) == 0)
2546         g_signal_connect_object (object, signal_spec + 29,
2547                                  callback, data,
2548                                  G_CONNECT_SWAPPED | G_CONNECT_AFTER);
2549       else
2550         {
2551           g_warning ("%s: invalid signal spec \"%s\"", G_STRFUNC, signal_spec);
2552           break;
2553         }
2554       signal_spec = va_arg (var_args, gchar*);
2555     }
2556   va_end (var_args);
2557
2558   return object;
2559 }
2560
2561 /**
2562  * g_object_disconnect: (skip)
2563  * @object: a #GObject
2564  * @signal_spec: the spec for the first signal
2565  * @...: #GCallback for the first signal, followed by data for the first signal,
2566  *  followed optionally by more signal spec/callback/data triples,
2567  *  followed by %NULL
2568  *
2569  * A convenience function to disconnect multiple signals at once.
2570  *
2571  * The signal specs expected by this function have the form
2572  * "any_signal", which means to disconnect any signal with matching
2573  * callback and data, or "any_signal::signal_name", which only
2574  * disconnects the signal named "signal_name".
2575  */
2576 void
2577 g_object_disconnect (gpointer     _object,
2578                      const gchar *signal_spec,
2579                      ...)
2580 {
2581   GObject *object = _object;
2582   va_list var_args;
2583
2584   g_return_if_fail (G_IS_OBJECT (object));
2585   g_return_if_fail (object->ref_count > 0);
2586
2587   va_start (var_args, signal_spec);
2588   while (signal_spec)
2589     {
2590       GCallback callback = va_arg (var_args, GCallback);
2591       gpointer data = va_arg (var_args, gpointer);
2592       guint sid = 0, detail = 0, mask = 0;
2593
2594       if (strncmp (signal_spec, "any_signal::", 12) == 0 ||
2595           strncmp (signal_spec, "any-signal::", 12) == 0)
2596         {
2597           signal_spec += 12;
2598           mask = G_SIGNAL_MATCH_ID | G_SIGNAL_MATCH_FUNC | G_SIGNAL_MATCH_DATA;
2599         }
2600       else if (strcmp (signal_spec, "any_signal") == 0 ||
2601                strcmp (signal_spec, "any-signal") == 0)
2602         {
2603           signal_spec += 10;
2604           mask = G_SIGNAL_MATCH_FUNC | G_SIGNAL_MATCH_DATA;
2605         }
2606       else
2607         {
2608           g_warning ("%s: invalid signal spec \"%s\"", G_STRFUNC, signal_spec);
2609           break;
2610         }
2611
2612       if ((mask & G_SIGNAL_MATCH_ID) &&
2613           !g_signal_parse_name (signal_spec, G_OBJECT_TYPE (object), &sid, &detail, FALSE))
2614         g_warning ("%s: invalid signal name \"%s\"", G_STRFUNC, signal_spec);
2615       else if (!g_signal_handlers_disconnect_matched (object, mask | (detail ? G_SIGNAL_MATCH_DETAIL : 0),
2616                                                       sid, detail,
2617                                                       NULL, (gpointer)callback, data))
2618         g_warning ("%s: signal handler %p(%p) is not connected", G_STRFUNC, callback, data);
2619       signal_spec = va_arg (var_args, gchar*);
2620     }
2621   va_end (var_args);
2622 }
2623
2624 typedef struct {
2625   GObject *object;
2626   guint n_weak_refs;
2627   struct {
2628     GWeakNotify notify;
2629     gpointer    data;
2630   } weak_refs[1];  /* flexible array */
2631 } WeakRefStack;
2632
2633 static void
2634 weak_refs_notify (gpointer data)
2635 {
2636   WeakRefStack *wstack = data;
2637   guint i;
2638
2639   for (i = 0; i < wstack->n_weak_refs; i++)
2640     wstack->weak_refs[i].notify (wstack->weak_refs[i].data, wstack->object);
2641   g_free (wstack);
2642 }
2643
2644 /**
2645  * g_object_weak_ref: (skip)
2646  * @object: #GObject to reference weakly
2647  * @notify: callback to invoke before the object is freed
2648  * @data: extra data to pass to notify
2649  *
2650  * Adds a weak reference callback to an object. Weak references are
2651  * used for notification when an object is finalized. They are called
2652  * "weak references" because they allow you to safely hold a pointer
2653  * to an object without calling g_object_ref() (g_object_ref() adds a
2654  * strong reference, that is, forces the object to stay alive).
2655  *
2656  * Note that the weak references created by this method are not
2657  * thread-safe: they cannot safely be used in one thread if the
2658  * object's last g_object_unref() might happen in another thread.
2659  * Use #GWeakRef if thread-safety is required.
2660  */
2661 void
2662 g_object_weak_ref (GObject    *object,
2663                    GWeakNotify notify,
2664                    gpointer    data)
2665 {
2666   WeakRefStack *wstack;
2667   guint i;
2668   
2669   g_return_if_fail (G_IS_OBJECT (object));
2670   g_return_if_fail (notify != NULL);
2671   g_return_if_fail (object->ref_count >= 1);
2672
2673   G_LOCK (weak_refs_mutex);
2674   wstack = g_datalist_id_remove_no_notify (&object->qdata, quark_weak_refs);
2675   if (wstack)
2676     {
2677       i = wstack->n_weak_refs++;
2678       wstack = g_realloc (wstack, sizeof (*wstack) + sizeof (wstack->weak_refs[0]) * i);
2679     }
2680   else
2681     {
2682       wstack = g_renew (WeakRefStack, NULL, 1);
2683       wstack->object = object;
2684       wstack->n_weak_refs = 1;
2685       i = 0;
2686     }
2687   wstack->weak_refs[i].notify = notify;
2688   wstack->weak_refs[i].data = data;
2689   g_datalist_id_set_data_full (&object->qdata, quark_weak_refs, wstack, weak_refs_notify);
2690   G_UNLOCK (weak_refs_mutex);
2691 }
2692
2693 /**
2694  * g_object_weak_unref: (skip)
2695  * @object: #GObject to remove a weak reference from
2696  * @notify: callback to search for
2697  * @data: data to search for
2698  *
2699  * Removes a weak reference callback to an object.
2700  */
2701 void
2702 g_object_weak_unref (GObject    *object,
2703                      GWeakNotify notify,
2704                      gpointer    data)
2705 {
2706   WeakRefStack *wstack;
2707   gboolean found_one = FALSE;
2708
2709   g_return_if_fail (G_IS_OBJECT (object));
2710   g_return_if_fail (notify != NULL);
2711
2712   G_LOCK (weak_refs_mutex);
2713   wstack = g_datalist_id_get_data (&object->qdata, quark_weak_refs);
2714   if (wstack)
2715     {
2716       guint i;
2717
2718       for (i = 0; i < wstack->n_weak_refs; i++)
2719         if (wstack->weak_refs[i].notify == notify &&
2720             wstack->weak_refs[i].data == data)
2721           {
2722             found_one = TRUE;
2723             wstack->n_weak_refs -= 1;
2724             if (i != wstack->n_weak_refs)
2725               wstack->weak_refs[i] = wstack->weak_refs[wstack->n_weak_refs];
2726
2727             break;
2728           }
2729     }
2730   G_UNLOCK (weak_refs_mutex);
2731   if (!found_one)
2732     g_warning ("%s: couldn't find weak ref %p(%p)", G_STRFUNC, notify, data);
2733 }
2734
2735 /**
2736  * g_object_add_weak_pointer: (skip)
2737  * @object: The object that should be weak referenced.
2738  * @weak_pointer_location: (inout): The memory address of a pointer.
2739  *
2740  * Adds a weak reference from weak_pointer to @object to indicate that
2741  * the pointer located at @weak_pointer_location is only valid during
2742  * the lifetime of @object. When the @object is finalized,
2743  * @weak_pointer will be set to %NULL.
2744  *
2745  * Note that as with g_object_weak_ref(), the weak references created by
2746  * this method are not thread-safe: they cannot safely be used in one
2747  * thread if the object's last g_object_unref() might happen in another
2748  * thread. Use #GWeakRef if thread-safety is required.
2749  */
2750 void
2751 g_object_add_weak_pointer (GObject  *object, 
2752                            gpointer *weak_pointer_location)
2753 {
2754   g_return_if_fail (G_IS_OBJECT (object));
2755   g_return_if_fail (weak_pointer_location != NULL);
2756
2757   g_object_weak_ref (object, 
2758                      (GWeakNotify) g_nullify_pointer, 
2759                      weak_pointer_location);
2760 }
2761
2762 /**
2763  * g_object_remove_weak_pointer: (skip)
2764  * @object: The object that is weak referenced.
2765  * @weak_pointer_location: (inout): The memory address of a pointer.
2766  *
2767  * Removes a weak reference from @object that was previously added
2768  * using g_object_add_weak_pointer(). The @weak_pointer_location has
2769  * to match the one used with g_object_add_weak_pointer().
2770  */
2771 void
2772 g_object_remove_weak_pointer (GObject  *object, 
2773                               gpointer *weak_pointer_location)
2774 {
2775   g_return_if_fail (G_IS_OBJECT (object));
2776   g_return_if_fail (weak_pointer_location != NULL);
2777
2778   g_object_weak_unref (object, 
2779                        (GWeakNotify) g_nullify_pointer, 
2780                        weak_pointer_location);
2781 }
2782
2783 static guint
2784 object_floating_flag_handler (GObject        *object,
2785                               gint            job)
2786 {
2787   switch (job)
2788     {
2789       gpointer oldvalue;
2790     case +1:    /* force floating if possible */
2791       do
2792         oldvalue = g_atomic_pointer_get (&object->qdata);
2793       while (!g_atomic_pointer_compare_and_exchange ((void**) &object->qdata, oldvalue,
2794                                                      (gpointer) ((gsize) oldvalue | OBJECT_FLOATING_FLAG)));
2795       return (gsize) oldvalue & OBJECT_FLOATING_FLAG;
2796     case -1:    /* sink if possible */
2797       do
2798         oldvalue = g_atomic_pointer_get (&object->qdata);
2799       while (!g_atomic_pointer_compare_and_exchange ((void**) &object->qdata, oldvalue,
2800                                                      (gpointer) ((gsize) oldvalue & ~(gsize) OBJECT_FLOATING_FLAG)));
2801       return (gsize) oldvalue & OBJECT_FLOATING_FLAG;
2802     default:    /* check floating */
2803       return 0 != ((gsize) g_atomic_pointer_get (&object->qdata) & OBJECT_FLOATING_FLAG);
2804     }
2805 }
2806
2807 /**
2808  * g_object_is_floating:
2809  * @object: (type GObject.Object): a #GObject
2810  *
2811  * Checks whether @object has a <link linkend="floating-ref">floating</link>
2812  * reference.
2813  *
2814  * Since: 2.10
2815  *
2816  * Returns: %TRUE if @object has a floating reference
2817  */
2818 gboolean
2819 g_object_is_floating (gpointer _object)
2820 {
2821   GObject *object = _object;
2822   g_return_val_if_fail (G_IS_OBJECT (object), FALSE);
2823   return floating_flag_handler (object, 0);
2824 }
2825
2826 /**
2827  * g_object_ref_sink:
2828  * @object: (type GObject.Object): a #GObject
2829  *
2830  * Increase the reference count of @object, and possibly remove the
2831  * <link linkend="floating-ref">floating</link> reference, if @object
2832  * has a floating reference.
2833  *
2834  * In other words, if the object is floating, then this call "assumes
2835  * ownership" of the floating reference, converting it to a normal
2836  * reference by clearing the floating flag while leaving the reference
2837  * count unchanged.  If the object is not floating, then this call
2838  * adds a new normal reference increasing the reference count by one.
2839  *
2840  * Since: 2.10
2841  *
2842  * Returns: (type GObject.Object) (transfer none): @object
2843  */
2844 gpointer
2845 g_object_ref_sink (gpointer _object)
2846 {
2847   GObject *object = _object;
2848   gboolean was_floating;
2849   g_return_val_if_fail (G_IS_OBJECT (object), object);
2850   g_return_val_if_fail (object->ref_count >= 1, object);
2851   g_object_ref (object);
2852   was_floating = floating_flag_handler (object, -1);
2853   if (was_floating)
2854     g_object_unref (object);
2855   return object;
2856 }
2857
2858 /**
2859  * g_object_force_floating:
2860  * @object: a #GObject
2861  *
2862  * This function is intended for #GObject implementations to re-enforce a
2863  * <link linkend="floating-ref">floating</link> object reference.
2864  * Doing this is seldom required: all
2865  * #GInitiallyUnowned<!-- -->s are created with a floating reference which
2866  * usually just needs to be sunken by calling g_object_ref_sink().
2867  *
2868  * Since: 2.10
2869  */
2870 void
2871 g_object_force_floating (GObject *object)
2872 {
2873   g_return_if_fail (G_IS_OBJECT (object));
2874   g_return_if_fail (object->ref_count >= 1);
2875
2876   floating_flag_handler (object, +1);
2877 }
2878
2879 typedef struct {
2880   GObject *object;
2881   guint n_toggle_refs;
2882   struct {
2883     GToggleNotify notify;
2884     gpointer    data;
2885   } toggle_refs[1];  /* flexible array */
2886 } ToggleRefStack;
2887
2888 static void
2889 toggle_refs_notify (GObject *object,
2890                     gboolean is_last_ref)
2891 {
2892   ToggleRefStack tstack, *tstackptr;
2893
2894   G_LOCK (toggle_refs_mutex);
2895   tstackptr = g_datalist_id_get_data (&object->qdata, quark_toggle_refs);
2896   tstack = *tstackptr;
2897   G_UNLOCK (toggle_refs_mutex);
2898
2899   /* Reentrancy here is not as tricky as it seems, because a toggle reference
2900    * will only be notified when there is exactly one of them.
2901    */
2902   g_assert (tstack.n_toggle_refs == 1);
2903   tstack.toggle_refs[0].notify (tstack.toggle_refs[0].data, tstack.object, is_last_ref);
2904 }
2905
2906 /**
2907  * g_object_add_toggle_ref: (skip)
2908  * @object: a #GObject
2909  * @notify: a function to call when this reference is the
2910  *  last reference to the object, or is no longer
2911  *  the last reference.
2912  * @data: data to pass to @notify
2913  *
2914  * Increases the reference count of the object by one and sets a
2915  * callback to be called when all other references to the object are
2916  * dropped, or when this is already the last reference to the object
2917  * and another reference is established.
2918  *
2919  * This functionality is intended for binding @object to a proxy
2920  * object managed by another memory manager. This is done with two
2921  * paired references: the strong reference added by
2922  * g_object_add_toggle_ref() and a reverse reference to the proxy
2923  * object which is either a strong reference or weak reference.
2924  *
2925  * The setup is that when there are no other references to @object,
2926  * only a weak reference is held in the reverse direction from @object
2927  * to the proxy object, but when there are other references held to
2928  * @object, a strong reference is held. The @notify callback is called
2929  * when the reference from @object to the proxy object should be
2930  * <firstterm>toggled</firstterm> from strong to weak (@is_last_ref
2931  * true) or weak to strong (@is_last_ref false).
2932  *
2933  * Since a (normal) reference must be held to the object before
2934  * calling g_object_add_toggle_ref(), the initial state of the reverse
2935  * link is always strong.
2936  *
2937  * Multiple toggle references may be added to the same gobject,
2938  * however if there are multiple toggle references to an object, none
2939  * of them will ever be notified until all but one are removed.  For
2940  * this reason, you should only ever use a toggle reference if there
2941  * is important state in the proxy object.
2942  *
2943  * Since: 2.8
2944  */
2945 void
2946 g_object_add_toggle_ref (GObject       *object,
2947                          GToggleNotify  notify,
2948                          gpointer       data)
2949 {
2950   ToggleRefStack *tstack;
2951   guint i;
2952   
2953   g_return_if_fail (G_IS_OBJECT (object));
2954   g_return_if_fail (notify != NULL);
2955   g_return_if_fail (object->ref_count >= 1);
2956
2957   g_object_ref (object);
2958
2959   G_LOCK (toggle_refs_mutex);
2960   tstack = g_datalist_id_remove_no_notify (&object->qdata, quark_toggle_refs);
2961   if (tstack)
2962     {
2963       i = tstack->n_toggle_refs++;
2964       /* allocate i = tstate->n_toggle_refs - 1 positions beyond the 1 declared
2965        * in tstate->toggle_refs */
2966       tstack = g_realloc (tstack, sizeof (*tstack) + sizeof (tstack->toggle_refs[0]) * i);
2967     }
2968   else
2969     {
2970       tstack = g_renew (ToggleRefStack, NULL, 1);
2971       tstack->object = object;
2972       tstack->n_toggle_refs = 1;
2973       i = 0;
2974     }
2975
2976   /* Set a flag for fast lookup after adding the first toggle reference */
2977   if (tstack->n_toggle_refs == 1)
2978     g_datalist_set_flags (&object->qdata, OBJECT_HAS_TOGGLE_REF_FLAG);
2979   
2980   tstack->toggle_refs[i].notify = notify;
2981   tstack->toggle_refs[i].data = data;
2982   g_datalist_id_set_data_full (&object->qdata, quark_toggle_refs, tstack,
2983                                (GDestroyNotify)g_free);
2984   G_UNLOCK (toggle_refs_mutex);
2985 }
2986
2987 /**
2988  * g_object_remove_toggle_ref: (skip)
2989  * @object: a #GObject
2990  * @notify: a function to call when this reference is the
2991  *  last reference to the object, or is no longer
2992  *  the last reference.
2993  * @data: data to pass to @notify
2994  *
2995  * Removes a reference added with g_object_add_toggle_ref(). The
2996  * reference count of the object is decreased by one.
2997  *
2998  * Since: 2.8
2999  */
3000 void
3001 g_object_remove_toggle_ref (GObject       *object,
3002                             GToggleNotify  notify,
3003                             gpointer       data)
3004 {
3005   ToggleRefStack *tstack;
3006   gboolean found_one = FALSE;
3007
3008   g_return_if_fail (G_IS_OBJECT (object));
3009   g_return_if_fail (notify != NULL);
3010
3011   G_LOCK (toggle_refs_mutex);
3012   tstack = g_datalist_id_get_data (&object->qdata, quark_toggle_refs);
3013   if (tstack)
3014     {
3015       guint i;
3016
3017       for (i = 0; i < tstack->n_toggle_refs; i++)
3018         if (tstack->toggle_refs[i].notify == notify &&
3019             tstack->toggle_refs[i].data == data)
3020           {
3021             found_one = TRUE;
3022             tstack->n_toggle_refs -= 1;
3023             if (i != tstack->n_toggle_refs)
3024               tstack->toggle_refs[i] = tstack->toggle_refs[tstack->n_toggle_refs];
3025
3026             if (tstack->n_toggle_refs == 0)
3027               g_datalist_unset_flags (&object->qdata, OBJECT_HAS_TOGGLE_REF_FLAG);
3028
3029             break;
3030           }
3031     }
3032   G_UNLOCK (toggle_refs_mutex);
3033
3034   if (found_one)
3035     g_object_unref (object);
3036   else
3037     g_warning ("%s: couldn't find toggle ref %p(%p)", G_STRFUNC, notify, data);
3038 }
3039
3040 /**
3041  * g_object_ref:
3042  * @object: (type GObject.Object): a #GObject
3043  *
3044  * Increases the reference count of @object.
3045  *
3046  * Returns: (type GObject.Object) (transfer none): the same @object
3047  */
3048 gpointer
3049 g_object_ref (gpointer _object)
3050 {
3051   GObject *object = _object;
3052   gint old_val;
3053
3054   g_return_val_if_fail (G_IS_OBJECT (object), NULL);
3055   g_return_val_if_fail (object->ref_count > 0, NULL);
3056   
3057 #ifdef  G_ENABLE_DEBUG
3058   if (g_trap_object_ref == object)
3059     G_BREAKPOINT ();
3060 #endif  /* G_ENABLE_DEBUG */
3061
3062
3063   old_val = g_atomic_int_add (&object->ref_count, 1);
3064
3065   if (old_val == 1 && OBJECT_HAS_TOGGLE_REF (object))
3066     toggle_refs_notify (object, FALSE);
3067
3068   TRACE (GOBJECT_OBJECT_REF(object,G_TYPE_FROM_INSTANCE(object),old_val));
3069
3070   return object;
3071 }
3072
3073 /**
3074  * g_object_unref:
3075  * @object: (type GObject.Object): a #GObject
3076  *
3077  * Decreases the reference count of @object. When its reference count
3078  * drops to 0, the object is finalized (i.e. its memory is freed).
3079  */
3080 void
3081 g_object_unref (gpointer _object)
3082 {
3083   GObject *object = _object;
3084   gint old_ref;
3085   
3086   g_return_if_fail (G_IS_OBJECT (object));
3087   g_return_if_fail (object->ref_count > 0);
3088   
3089 #ifdef  G_ENABLE_DEBUG
3090   if (g_trap_object_ref == object)
3091     G_BREAKPOINT ();
3092 #endif  /* G_ENABLE_DEBUG */
3093
3094   /* here we want to atomically do: if (ref_count>1) { ref_count--; return; } */
3095  retry_atomic_decrement1:
3096   old_ref = g_atomic_int_get (&object->ref_count);
3097   if (old_ref > 1)
3098     {
3099       /* valid if last 2 refs are owned by this call to unref and the toggle_ref */
3100       gboolean has_toggle_ref = OBJECT_HAS_TOGGLE_REF (object);
3101
3102       if (!g_atomic_int_compare_and_exchange ((int *)&object->ref_count, old_ref, old_ref - 1))
3103         goto retry_atomic_decrement1;
3104
3105       TRACE (GOBJECT_OBJECT_UNREF(object,G_TYPE_FROM_INSTANCE(object),old_ref));
3106
3107       /* if we went from 2->1 we need to notify toggle refs if any */
3108       if (old_ref == 2 && has_toggle_ref) /* The last ref being held in this case is owned by the toggle_ref */
3109         toggle_refs_notify (object, TRUE);
3110     }
3111   else
3112     {
3113       GSList **weak_locations;
3114
3115       /* The only way that this object can live at this point is if
3116        * there are outstanding weak references already established
3117        * before we got here.
3118        *
3119        * If there were not already weak references then no more can be
3120        * established at this time, because the other thread would have
3121        * to hold a strong ref in order to call
3122        * g_object_add_weak_pointer() and then we wouldn't be here.
3123        */
3124       weak_locations = g_datalist_id_get_data (&object->qdata, quark_weak_locations);
3125
3126       if (weak_locations != NULL)
3127         {
3128           g_rw_lock_writer_lock (&weak_locations_lock);
3129
3130           /* It is possible that one of the weak references beat us to
3131            * the lock. Make sure the refcount is still what we expected
3132            * it to be.
3133            */
3134           old_ref = g_atomic_int_get (&object->ref_count);
3135           if (old_ref != 1)
3136             {
3137               g_rw_lock_writer_unlock (&weak_locations_lock);
3138               goto retry_atomic_decrement1;
3139             }
3140
3141           /* We got the lock first, so the object will definitely die
3142            * now. Clear out all the weak references.
3143            */
3144           while (*weak_locations)
3145             {
3146               GWeakRef *weak_ref_location = (*weak_locations)->data;
3147
3148               weak_ref_location->priv.p = NULL;
3149               *weak_locations = g_slist_delete_link (*weak_locations, *weak_locations);
3150             }
3151
3152           g_rw_lock_writer_unlock (&weak_locations_lock);
3153         }
3154
3155       /* we are about to remove the last reference */
3156       TRACE (GOBJECT_OBJECT_DISPOSE(object,G_TYPE_FROM_INSTANCE(object), 1));
3157       G_OBJECT_GET_CLASS (object)->dispose (object);
3158       TRACE (GOBJECT_OBJECT_DISPOSE_END(object,G_TYPE_FROM_INSTANCE(object), 1));
3159
3160       /* may have been re-referenced meanwhile */
3161     retry_atomic_decrement2:
3162       old_ref = g_atomic_int_get ((int *)&object->ref_count);
3163       if (old_ref > 1)
3164         {
3165           /* valid if last 2 refs are owned by this call to unref and the toggle_ref */
3166           gboolean has_toggle_ref = OBJECT_HAS_TOGGLE_REF (object);
3167
3168           if (!g_atomic_int_compare_and_exchange ((int *)&object->ref_count, old_ref, old_ref - 1))
3169             goto retry_atomic_decrement2;
3170
3171           TRACE (GOBJECT_OBJECT_UNREF(object,G_TYPE_FROM_INSTANCE(object),old_ref));
3172
3173           /* if we went from 2->1 we need to notify toggle refs if any */
3174           if (old_ref == 2 && has_toggle_ref) /* The last ref being held in this case is owned by the toggle_ref */
3175             toggle_refs_notify (object, TRUE);
3176
3177           return;
3178         }
3179
3180       /* we are still in the process of taking away the last ref */
3181       g_datalist_id_set_data (&object->qdata, quark_closure_array, NULL);
3182       g_signal_handlers_destroy (object);
3183       g_datalist_id_set_data (&object->qdata, quark_weak_refs, NULL);
3184       
3185       /* decrement the last reference */
3186       old_ref = g_atomic_int_add (&object->ref_count, -1);
3187
3188       TRACE (GOBJECT_OBJECT_UNREF(object,G_TYPE_FROM_INSTANCE(object),old_ref));
3189
3190       /* may have been re-referenced meanwhile */
3191       if (G_LIKELY (old_ref == 1))
3192         {
3193           TRACE (GOBJECT_OBJECT_FINALIZE(object,G_TYPE_FROM_INSTANCE(object)));
3194           G_OBJECT_GET_CLASS (object)->finalize (object);
3195
3196           TRACE (GOBJECT_OBJECT_FINALIZE_END(object,G_TYPE_FROM_INSTANCE(object)));
3197
3198 #ifdef  G_ENABLE_DEBUG
3199           IF_DEBUG (OBJECTS)
3200             {
3201               /* catch objects not chaining finalize handlers */
3202               G_LOCK (debug_objects);
3203               g_assert (g_hash_table_lookup (debug_objects_ht, object) == NULL);
3204               G_UNLOCK (debug_objects);
3205             }
3206 #endif  /* G_ENABLE_DEBUG */
3207           g_type_free_instance ((GTypeInstance*) object);
3208         }
3209     }
3210 }
3211
3212 /**
3213  * g_clear_object: (skip)
3214  * @object_ptr: a pointer to a #GObject reference
3215  *
3216  * Clears a reference to a #GObject.
3217  *
3218  * @object_ptr must not be %NULL.
3219  *
3220  * If the reference is %NULL then this function does nothing.
3221  * Otherwise, the reference count of the object is decreased and the
3222  * pointer is set to %NULL.
3223  *
3224  * This function is threadsafe and modifies the pointer atomically,
3225  * using memory barriers where needed.
3226  *
3227  * A macro is also included that allows this function to be used without
3228  * pointer casts.
3229  *
3230  * Since: 2.28
3231  **/
3232 #undef g_clear_object
3233 void
3234 g_clear_object (volatile GObject **object_ptr)
3235 {
3236   g_clear_pointer (object_ptr, g_object_unref);
3237 }
3238
3239 /**
3240  * g_object_get_qdata:
3241  * @object: The GObject to get a stored user data pointer from
3242  * @quark: A #GQuark, naming the user data pointer
3243  * 
3244  * This function gets back user data pointers stored via
3245  * g_object_set_qdata().
3246  * 
3247  * Returns: (transfer none): The user data pointer set, or %NULL
3248  */
3249 gpointer
3250 g_object_get_qdata (GObject *object,
3251                     GQuark   quark)
3252 {
3253   g_return_val_if_fail (G_IS_OBJECT (object), NULL);
3254   
3255   return quark ? g_datalist_id_get_data (&object->qdata, quark) : NULL;
3256 }
3257
3258 /**
3259  * g_object_set_qdata: (skip)
3260  * @object: The GObject to set store a user data pointer
3261  * @quark: A #GQuark, naming the user data pointer
3262  * @data: An opaque user data pointer
3263  *
3264  * This sets an opaque, named pointer on an object.
3265  * The name is specified through a #GQuark (retrived e.g. via
3266  * g_quark_from_static_string()), and the pointer
3267  * can be gotten back from the @object with g_object_get_qdata()
3268  * until the @object is finalized.
3269  * Setting a previously set user data pointer, overrides (frees)
3270  * the old pointer set, using #NULL as pointer essentially
3271  * removes the data stored.
3272  */
3273 void
3274 g_object_set_qdata (GObject *object,
3275                     GQuark   quark,
3276                     gpointer data)
3277 {
3278   g_return_if_fail (G_IS_OBJECT (object));
3279   g_return_if_fail (quark > 0);
3280
3281   g_datalist_id_set_data (&object->qdata, quark, data);
3282 }
3283
3284 /**
3285  * g_object_dup_qdata:
3286  * @object: the #GObject to store user data on
3287  * @quark: a #GQuark, naming the user data pointer
3288  * @dup_func: (allow-none): function to dup the value
3289  * @user_data: (allow-none): passed as user_data to @dup_func
3290  *
3291  * This is a variant of g_object_get_qdata() which returns
3292  * a 'duplicate' of the value. @dup_func defines the
3293  * meaning of 'duplicate' in this context, it could e.g.
3294  * take a reference on a ref-counted object.
3295  *
3296  * If the @quark is not set on the object then @dup_func
3297  * will be called with a %NULL argument.
3298  *
3299  * Note that @dup_func is called while user data of @object
3300  * is locked.
3301  *
3302  * This function can be useful to avoid races when multiple
3303  * threads are using object data on the same key on the same
3304  * object.
3305  *
3306  * Returns: the result of calling @dup_func on the value
3307  *     associated with @quark on @object, or %NULL if not set.
3308  *     If @dup_func is %NULL, the value is returned
3309  *     unmodified.
3310  *
3311  * Since: 2.34
3312  */
3313 gpointer
3314 g_object_dup_qdata (GObject        *object,
3315                     GQuark          quark,
3316                     GDuplicateFunc   dup_func,
3317                     gpointer         user_data)
3318 {
3319   g_return_val_if_fail (G_IS_OBJECT (object), NULL);
3320   g_return_val_if_fail (quark > 0, NULL);
3321
3322   return g_datalist_id_dup_data (&object->qdata, quark, dup_func, user_data);
3323 }
3324
3325 /**
3326  * g_object_replace_qdata:
3327  * @object: the #GObject to store user data on
3328  * @quark: a #GQuark, naming the user data pointer
3329  * @oldval: (allow-none): the old value to compare against
3330  * @newval: (allow-none): the new value
3331  * @destroy: (allow-none): a destroy notify for the new value
3332  * @old_destroy: (allow-none): destroy notify for the existing value
3333  *
3334  * Compares the user data for the key @quark on @object with
3335  * @oldval, and if they are the same, replaces @oldval with
3336  * @newval.
3337  *
3338  * This is like a typical atomic compare-and-exchange
3339  * operation, for user data on an object.
3340  *
3341  * If the previous value was replaced then ownership of the
3342  * old value (@oldval) is passed to the caller, including
3343  * the registered destroy notify for it (passed out in @old_destroy).
3344  * Its up to the caller to free this as he wishes, which may
3345  * or may not include using @old_destroy as sometimes replacement
3346  * should not destroy the object in the normal way.
3347  *
3348  * Return: %TRUE if the existing value for @quark was replaced
3349  *  by @newval, %FALSE otherwise.
3350  *
3351  * Since: 2.34
3352  */
3353 gboolean
3354 g_object_replace_qdata (GObject        *object,
3355                         GQuark          quark,
3356                         gpointer        oldval,
3357                         gpointer        newval,
3358                         GDestroyNotify  destroy,
3359                         GDestroyNotify *old_destroy)
3360 {
3361   g_return_val_if_fail (G_IS_OBJECT (object), FALSE);
3362   g_return_val_if_fail (quark > 0, FALSE);
3363
3364   return g_datalist_id_replace_data (&object->qdata, quark,
3365                                      oldval, newval, destroy,
3366                                      old_destroy);
3367 }
3368
3369 /**
3370  * g_object_set_qdata_full: (skip)
3371  * @object: The GObject to set store a user data pointer
3372  * @quark: A #GQuark, naming the user data pointer
3373  * @data: An opaque user data pointer
3374  * @destroy: Function to invoke with @data as argument, when @data
3375  *           needs to be freed
3376  *
3377  * This function works like g_object_set_qdata(), but in addition,
3378  * a void (*destroy) (gpointer) function may be specified which is
3379  * called with @data as argument when the @object is finalized, or
3380  * the data is being overwritten by a call to g_object_set_qdata()
3381  * with the same @quark.
3382  */
3383 void
3384 g_object_set_qdata_full (GObject       *object,
3385                          GQuark         quark,
3386                          gpointer       data,
3387                          GDestroyNotify destroy)
3388 {
3389   g_return_if_fail (G_IS_OBJECT (object));
3390   g_return_if_fail (quark > 0);
3391   
3392   g_datalist_id_set_data_full (&object->qdata, quark, data,
3393                                data ? destroy : (GDestroyNotify) NULL);
3394 }
3395
3396 /**
3397  * g_object_steal_qdata:
3398  * @object: The GObject to get a stored user data pointer from
3399  * @quark: A #GQuark, naming the user data pointer
3400  *
3401  * This function gets back user data pointers stored via
3402  * g_object_set_qdata() and removes the @data from object
3403  * without invoking its destroy() function (if any was
3404  * set).
3405  * Usually, calling this function is only required to update
3406  * user data pointers with a destroy notifier, for example:
3407  * |[
3408  * void
3409  * object_add_to_user_list (GObject     *object,
3410  *                          const gchar *new_string)
3411  * {
3412  *   // the quark, naming the object data
3413  *   GQuark quark_string_list = g_quark_from_static_string ("my-string-list");
3414  *   // retrive the old string list
3415  *   GList *list = g_object_steal_qdata (object, quark_string_list);
3416  *
3417  *   // prepend new string
3418  *   list = g_list_prepend (list, g_strdup (new_string));
3419  *   // this changed 'list', so we need to set it again
3420  *   g_object_set_qdata_full (object, quark_string_list, list, free_string_list);
3421  * }
3422  * static void
3423  * free_string_list (gpointer data)
3424  * {
3425  *   GList *node, *list = data;
3426  *
3427  *   for (node = list; node; node = node->next)
3428  *     g_free (node->data);
3429  *   g_list_free (list);
3430  * }
3431  * ]|
3432  * Using g_object_get_qdata() in the above example, instead of
3433  * g_object_steal_qdata() would have left the destroy function set,
3434  * and thus the partial string list would have been freed upon
3435  * g_object_set_qdata_full().
3436  *
3437  * Returns: (transfer full): The user data pointer set, or %NULL
3438  */
3439 gpointer
3440 g_object_steal_qdata (GObject *object,
3441                       GQuark   quark)
3442 {
3443   g_return_val_if_fail (G_IS_OBJECT (object), NULL);
3444   g_return_val_if_fail (quark > 0, NULL);
3445   
3446   return g_datalist_id_remove_no_notify (&object->qdata, quark);
3447 }
3448
3449 /**
3450  * g_object_get_data:
3451  * @object: #GObject containing the associations
3452  * @key: name of the key for that association
3453  * 
3454  * Gets a named field from the objects table of associations (see g_object_set_data()).
3455  * 
3456  * Returns: (transfer none): the data if found, or %NULL if no such data exists.
3457  */
3458 gpointer
3459 g_object_get_data (GObject     *object,
3460                    const gchar *key)
3461 {
3462   g_return_val_if_fail (G_IS_OBJECT (object), NULL);
3463   g_return_val_if_fail (key != NULL, NULL);
3464
3465   return g_datalist_get_data (&object->qdata, key);
3466 }
3467
3468 /**
3469  * g_object_set_data:
3470  * @object: #GObject containing the associations.
3471  * @key: name of the key
3472  * @data: data to associate with that key
3473  *
3474  * Each object carries around a table of associations from
3475  * strings to pointers.  This function lets you set an association.
3476  *
3477  * If the object already had an association with that name,
3478  * the old association will be destroyed.
3479  */
3480 void
3481 g_object_set_data (GObject     *object,
3482                    const gchar *key,
3483                    gpointer     data)
3484 {
3485   g_return_if_fail (G_IS_OBJECT (object));
3486   g_return_if_fail (key != NULL);
3487
3488   g_datalist_id_set_data (&object->qdata, g_quark_from_string (key), data);
3489 }
3490
3491 /**
3492  * g_object_dup_data:
3493  * @object: the #GObject to store user data on
3494  * @key: a string, naming the user data pointer
3495  * @dup_func: (allow-none): function to dup the value
3496  * @user_data: (allow-none): passed as user_data to @dup_func
3497  *
3498  * This is a variant of g_object_get_data() which returns
3499  * a 'duplicate' of the value. @dup_func defines the
3500  * meaning of 'duplicate' in this context, it could e.g.
3501  * take a reference on a ref-counted object.
3502  *
3503  * If the @key is not set on the object then @dup_func
3504  * will be called with a %NULL argument.
3505  *
3506  * Note that @dup_func is called while user data of @object
3507  * is locked.
3508  *
3509  * This function can be useful to avoid races when multiple
3510  * threads are using object data on the same key on the same
3511  * object.
3512  *
3513  * Returns: the result of calling @dup_func on the value
3514  *     associated with @key on @object, or %NULL if not set.
3515  *     If @dup_func is %NULL, the value is returned
3516  *     unmodified.
3517  *
3518  * Since: 2.34
3519  */
3520 gpointer
3521 g_object_dup_data (GObject        *object,
3522                    const gchar    *key,
3523                    GDuplicateFunc   dup_func,
3524                    gpointer         user_data)
3525 {
3526   g_return_val_if_fail (G_IS_OBJECT (object), NULL);
3527   g_return_val_if_fail (key != NULL, NULL);
3528
3529   return g_datalist_id_dup_data (&object->qdata,
3530                                  g_quark_from_string (key),
3531                                  dup_func, user_data);
3532 }
3533
3534 /**
3535  * g_object_replace_data:
3536  * @object: the #GObject to store user data on
3537  * @key: a string, naming the user data pointer
3538  * @oldval: (allow-none): the old value to compare against
3539  * @newval: (allow-none): the new value
3540  * @destroy: (allow-none): a destroy notify for the new value
3541  * @old_destroy: (allow-none): destroy notify for the existing value
3542  *
3543  * Compares the user data for the key @key on @object with
3544  * @oldval, and if they are the same, replaces @oldval with
3545  * @newval.
3546  *
3547  * This is like a typical atomic compare-and-exchange
3548  * operation, for user data on an object.
3549  *
3550  * If the previous value was replaced then ownership of the
3551  * old value (@oldval) is passed to the caller, including
3552  * the registered destroy notify for it (passed out in @old_destroy).
3553  * Its up to the caller to free this as he wishes, which may
3554  * or may not include using @old_destroy as sometimes replacement
3555  * should not destroy the object in the normal way.
3556  *
3557  * Return: %TRUE if the existing value for @key was replaced
3558  *  by @newval, %FALSE otherwise.
3559  *
3560  * Since: 2.34
3561  */
3562 gboolean
3563 g_object_replace_data (GObject        *object,
3564                        const gchar    *key,
3565                        gpointer        oldval,
3566                        gpointer        newval,
3567                        GDestroyNotify  destroy,
3568                        GDestroyNotify *old_destroy)
3569 {
3570   g_return_val_if_fail (G_IS_OBJECT (object), FALSE);
3571   g_return_val_if_fail (key != NULL, FALSE);
3572
3573   return g_datalist_id_replace_data (&object->qdata,
3574                                      g_quark_from_string (key),
3575                                      oldval, newval, destroy,
3576                                      old_destroy);
3577 }
3578
3579 /**
3580  * g_object_set_data_full: (skip)
3581  * @object: #GObject containing the associations
3582  * @key: name of the key
3583  * @data: data to associate with that key
3584  * @destroy: function to call when the association is destroyed
3585  *
3586  * Like g_object_set_data() except it adds notification
3587  * for when the association is destroyed, either by setting it
3588  * to a different value or when the object is destroyed.
3589  *
3590  * Note that the @destroy callback is not called if @data is %NULL.
3591  */
3592 void
3593 g_object_set_data_full (GObject       *object,
3594                         const gchar   *key,
3595                         gpointer       data,
3596                         GDestroyNotify destroy)
3597 {
3598   g_return_if_fail (G_IS_OBJECT (object));
3599   g_return_if_fail (key != NULL);
3600
3601   g_datalist_id_set_data_full (&object->qdata, g_quark_from_string (key), data,
3602                                data ? destroy : (GDestroyNotify) NULL);
3603 }
3604
3605 /**
3606  * g_object_steal_data:
3607  * @object: #GObject containing the associations
3608  * @key: name of the key
3609  *
3610  * Remove a specified datum from the object's data associations,
3611  * without invoking the association's destroy handler.
3612  *
3613  * Returns: (transfer full): the data if found, or %NULL if no such data exists.
3614  */
3615 gpointer
3616 g_object_steal_data (GObject     *object,
3617                      const gchar *key)
3618 {
3619   GQuark quark;
3620
3621   g_return_val_if_fail (G_IS_OBJECT (object), NULL);
3622   g_return_val_if_fail (key != NULL, NULL);
3623
3624   quark = g_quark_try_string (key);
3625
3626   return quark ? g_datalist_id_remove_no_notify (&object->qdata, quark) : NULL;
3627 }
3628
3629 static void
3630 g_value_object_init (GValue *value)
3631 {
3632   value->data[0].v_pointer = NULL;
3633 }
3634
3635 static void
3636 g_value_object_free_value (GValue *value)
3637 {
3638   if (value->data[0].v_pointer)
3639     g_object_unref (value->data[0].v_pointer);
3640 }
3641
3642 static void
3643 g_value_object_copy_value (const GValue *src_value,
3644                            GValue       *dest_value)
3645 {
3646   if (src_value->data[0].v_pointer)
3647     dest_value->data[0].v_pointer = g_object_ref (src_value->data[0].v_pointer);
3648   else
3649     dest_value->data[0].v_pointer = NULL;
3650 }
3651
3652 static void
3653 g_value_object_transform_value (const GValue *src_value,
3654                                 GValue       *dest_value)
3655 {
3656   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)))
3657     dest_value->data[0].v_pointer = g_object_ref (src_value->data[0].v_pointer);
3658   else
3659     dest_value->data[0].v_pointer = NULL;
3660 }
3661
3662 static gpointer
3663 g_value_object_peek_pointer (const GValue *value)
3664 {
3665   return value->data[0].v_pointer;
3666 }
3667
3668 static gchar*
3669 g_value_object_collect_value (GValue      *value,
3670                               guint        n_collect_values,
3671                               GTypeCValue *collect_values,
3672                               guint        collect_flags)
3673 {
3674   if (collect_values[0].v_pointer)
3675     {
3676       GObject *object = collect_values[0].v_pointer;
3677       
3678       if (object->g_type_instance.g_class == NULL)
3679         return g_strconcat ("invalid unclassed object pointer for value type '",
3680                             G_VALUE_TYPE_NAME (value),
3681                             "'",
3682                             NULL);
3683       else if (!g_value_type_compatible (G_OBJECT_TYPE (object), G_VALUE_TYPE (value)))
3684         return g_strconcat ("invalid object type '",
3685                             G_OBJECT_TYPE_NAME (object),
3686                             "' for value type '",
3687                             G_VALUE_TYPE_NAME (value),
3688                             "'",
3689                             NULL);
3690       /* never honour G_VALUE_NOCOPY_CONTENTS for ref-counted types */
3691       value->data[0].v_pointer = g_object_ref (object);
3692     }
3693   else
3694     value->data[0].v_pointer = NULL;
3695   
3696   return NULL;
3697 }
3698
3699 static gchar*
3700 g_value_object_lcopy_value (const GValue *value,
3701                             guint        n_collect_values,
3702                             GTypeCValue *collect_values,
3703                             guint        collect_flags)
3704 {
3705   GObject **object_p = collect_values[0].v_pointer;
3706   
3707   if (!object_p)
3708     return g_strdup_printf ("value location for '%s' passed as NULL", G_VALUE_TYPE_NAME (value));
3709
3710   if (!value->data[0].v_pointer)
3711     *object_p = NULL;
3712   else if (collect_flags & G_VALUE_NOCOPY_CONTENTS)
3713     *object_p = value->data[0].v_pointer;
3714   else
3715     *object_p = g_object_ref (value->data[0].v_pointer);
3716   
3717   return NULL;
3718 }
3719
3720 /**
3721  * g_value_set_object:
3722  * @value: a valid #GValue of %G_TYPE_OBJECT derived type
3723  * @v_object: (type GObject.Object) (allow-none): object value to be set
3724  *
3725  * Set the contents of a %G_TYPE_OBJECT derived #GValue to @v_object.
3726  *
3727  * g_value_set_object() increases the reference count of @v_object
3728  * (the #GValue holds a reference to @v_object).  If you do not wish
3729  * to increase the reference count of the object (i.e. you wish to
3730  * pass your current reference to the #GValue because you no longer
3731  * need it), use g_value_take_object() instead.
3732  *
3733  * It is important that your #GValue holds a reference to @v_object (either its
3734  * own, or one it has taken) to ensure that the object won't be destroyed while
3735  * the #GValue still exists).
3736  */
3737 void
3738 g_value_set_object (GValue   *value,
3739                     gpointer  v_object)
3740 {
3741   GObject *old;
3742         
3743   g_return_if_fail (G_VALUE_HOLDS_OBJECT (value));
3744
3745   old = value->data[0].v_pointer;
3746   
3747   if (v_object)
3748     {
3749       g_return_if_fail (G_IS_OBJECT (v_object));
3750       g_return_if_fail (g_value_type_compatible (G_OBJECT_TYPE (v_object), G_VALUE_TYPE (value)));
3751
3752       value->data[0].v_pointer = v_object;
3753       g_object_ref (value->data[0].v_pointer);
3754     }
3755   else
3756     value->data[0].v_pointer = NULL;
3757   
3758   if (old)
3759     g_object_unref (old);
3760 }
3761
3762 /**
3763  * g_value_set_object_take_ownership: (skip)
3764  * @value: a valid #GValue of %G_TYPE_OBJECT derived type
3765  * @v_object: (allow-none): object value to be set
3766  *
3767  * This is an internal function introduced mainly for C marshallers.
3768  *
3769  * Deprecated: 2.4: Use g_value_take_object() instead.
3770  */
3771 void
3772 g_value_set_object_take_ownership (GValue  *value,
3773                                    gpointer v_object)
3774 {
3775   g_value_take_object (value, v_object);
3776 }
3777
3778 /**
3779  * g_value_take_object: (skip)
3780  * @value: a valid #GValue of %G_TYPE_OBJECT derived type
3781  * @v_object: (allow-none): object value to be set
3782  *
3783  * Sets the contents of a %G_TYPE_OBJECT derived #GValue to @v_object
3784  * and takes over the ownership of the callers reference to @v_object;
3785  * the caller doesn't have to unref it any more (i.e. the reference
3786  * count of the object is not increased).
3787  *
3788  * If you want the #GValue to hold its own reference to @v_object, use
3789  * g_value_set_object() instead.
3790  *
3791  * Since: 2.4
3792  */
3793 void
3794 g_value_take_object (GValue  *value,
3795                      gpointer v_object)
3796 {
3797   g_return_if_fail (G_VALUE_HOLDS_OBJECT (value));
3798
3799   if (value->data[0].v_pointer)
3800     {
3801       g_object_unref (value->data[0].v_pointer);
3802       value->data[0].v_pointer = NULL;
3803     }
3804
3805   if (v_object)
3806     {
3807       g_return_if_fail (G_IS_OBJECT (v_object));
3808       g_return_if_fail (g_value_type_compatible (G_OBJECT_TYPE (v_object), G_VALUE_TYPE (value)));
3809
3810       value->data[0].v_pointer = v_object; /* we take over the reference count */
3811     }
3812 }
3813
3814 /**
3815  * g_value_get_object:
3816  * @value: a valid #GValue of %G_TYPE_OBJECT derived type
3817  * 
3818  * Get the contents of a %G_TYPE_OBJECT derived #GValue.
3819  * 
3820  * Returns: (type GObject.Object) (transfer none): object contents of @value
3821  */
3822 gpointer
3823 g_value_get_object (const GValue *value)
3824 {
3825   g_return_val_if_fail (G_VALUE_HOLDS_OBJECT (value), NULL);
3826   
3827   return value->data[0].v_pointer;
3828 }
3829
3830 /**
3831  * g_value_dup_object:
3832  * @value: a valid #GValue whose type is derived from %G_TYPE_OBJECT
3833  *
3834  * Get the contents of a %G_TYPE_OBJECT derived #GValue, increasing
3835  * its reference count. If the contents of the #GValue are %NULL, then
3836  * %NULL will be returned.
3837  *
3838  * Returns: (type GObject.Object) (transfer full): object content of @value,
3839  *          should be unreferenced when no longer needed.
3840  */
3841 gpointer
3842 g_value_dup_object (const GValue *value)
3843 {
3844   g_return_val_if_fail (G_VALUE_HOLDS_OBJECT (value), NULL);
3845   
3846   return value->data[0].v_pointer ? g_object_ref (value->data[0].v_pointer) : NULL;
3847 }
3848
3849 /**
3850  * g_signal_connect_object: (skip)
3851  * @instance: the instance to connect to.
3852  * @detailed_signal: a string of the form "signal-name::detail".
3853  * @c_handler: the #GCallback to connect.
3854  * @gobject: the object to pass as data to @c_handler.
3855  * @connect_flags: a combination of #GConnectFlags.
3856  *
3857  * This is similar to g_signal_connect_data(), but uses a closure which
3858  * ensures that the @gobject stays alive during the call to @c_handler
3859  * by temporarily adding a reference count to @gobject.
3860  *
3861  * When the @gobject is destroyed the signal handler will be automatically
3862  * disconnected.  Note that this is not currently threadsafe (ie:
3863  * emitting a signal while @gobject is being destroyed in another thread
3864  * is not safe).
3865  *
3866  * Returns: the handler id.
3867  */
3868 gulong
3869 g_signal_connect_object (gpointer      instance,
3870                          const gchar  *detailed_signal,
3871                          GCallback     c_handler,
3872                          gpointer      gobject,
3873                          GConnectFlags connect_flags)
3874 {
3875   g_return_val_if_fail (G_TYPE_CHECK_INSTANCE (instance), 0);
3876   g_return_val_if_fail (detailed_signal != NULL, 0);
3877   g_return_val_if_fail (c_handler != NULL, 0);
3878
3879   if (gobject)
3880     {
3881       GClosure *closure;
3882
3883       g_return_val_if_fail (G_IS_OBJECT (gobject), 0);
3884
3885       closure = ((connect_flags & G_CONNECT_SWAPPED) ? g_cclosure_new_object_swap : g_cclosure_new_object) (c_handler, gobject);
3886
3887       return g_signal_connect_closure (instance, detailed_signal, closure, connect_flags & G_CONNECT_AFTER);
3888     }
3889   else
3890     return g_signal_connect_data (instance, detailed_signal, c_handler, NULL, NULL, connect_flags);
3891 }
3892
3893 typedef struct {
3894   GObject  *object;
3895   guint     n_closures;
3896   GClosure *closures[1]; /* flexible array */
3897 } CArray;
3898 /* don't change this structure without supplying an accessor for
3899  * watched closures, e.g.:
3900  * GSList* g_object_list_watched_closures (GObject *object)
3901  * {
3902  *   CArray *carray;
3903  *   g_return_val_if_fail (G_IS_OBJECT (object), NULL);
3904  *   carray = g_object_get_data (object, "GObject-closure-array");
3905  *   if (carray)
3906  *     {
3907  *       GSList *slist = NULL;
3908  *       guint i;
3909  *       for (i = 0; i < carray->n_closures; i++)
3910  *         slist = g_slist_prepend (slist, carray->closures[i]);
3911  *       return slist;
3912  *     }
3913  *   return NULL;
3914  * }
3915  */
3916
3917 static void
3918 object_remove_closure (gpointer  data,
3919                        GClosure *closure)
3920 {
3921   GObject *object = data;
3922   CArray *carray;
3923   guint i;
3924   
3925   G_LOCK (closure_array_mutex);
3926   carray = g_object_get_qdata (object, quark_closure_array);
3927   for (i = 0; i < carray->n_closures; i++)
3928     if (carray->closures[i] == closure)
3929       {
3930         carray->n_closures--;
3931         if (i < carray->n_closures)
3932           carray->closures[i] = carray->closures[carray->n_closures];
3933         G_UNLOCK (closure_array_mutex);
3934         return;
3935       }
3936   G_UNLOCK (closure_array_mutex);
3937   g_assert_not_reached ();
3938 }
3939
3940 static void
3941 destroy_closure_array (gpointer data)
3942 {
3943   CArray *carray = data;
3944   GObject *object = carray->object;
3945   guint i, n = carray->n_closures;
3946   
3947   for (i = 0; i < n; i++)
3948     {
3949       GClosure *closure = carray->closures[i];
3950       
3951       /* removing object_remove_closure() upfront is probably faster than
3952        * letting it fiddle with quark_closure_array which is empty anyways
3953        */
3954       g_closure_remove_invalidate_notifier (closure, object, object_remove_closure);
3955       g_closure_invalidate (closure);
3956     }
3957   g_free (carray);
3958 }
3959
3960 /**
3961  * g_object_watch_closure:
3962  * @object: GObject restricting lifetime of @closure
3963  * @closure: GClosure to watch
3964  *
3965  * This function essentially limits the life time of the @closure to
3966  * the life time of the object. That is, when the object is finalized,
3967  * the @closure is invalidated by calling g_closure_invalidate() on
3968  * it, in order to prevent invocations of the closure with a finalized
3969  * (nonexisting) object. Also, g_object_ref() and g_object_unref() are
3970  * added as marshal guards to the @closure, to ensure that an extra
3971  * reference count is held on @object during invocation of the
3972  * @closure.  Usually, this function will be called on closures that
3973  * use this @object as closure data.
3974  */
3975 void
3976 g_object_watch_closure (GObject  *object,
3977                         GClosure *closure)
3978 {
3979   CArray *carray;
3980   guint i;
3981   
3982   g_return_if_fail (G_IS_OBJECT (object));
3983   g_return_if_fail (closure != NULL);
3984   g_return_if_fail (closure->is_invalid == FALSE);
3985   g_return_if_fail (closure->in_marshal == FALSE);
3986   g_return_if_fail (object->ref_count > 0);     /* this doesn't work on finalizing objects */
3987   
3988   g_closure_add_invalidate_notifier (closure, object, object_remove_closure);
3989   g_closure_add_marshal_guards (closure,
3990                                 object, (GClosureNotify) g_object_ref,
3991                                 object, (GClosureNotify) g_object_unref);
3992   G_LOCK (closure_array_mutex);
3993   carray = g_datalist_id_remove_no_notify (&object->qdata, quark_closure_array);
3994   if (!carray)
3995     {
3996       carray = g_renew (CArray, NULL, 1);
3997       carray->object = object;
3998       carray->n_closures = 1;
3999       i = 0;
4000     }
4001   else
4002     {
4003       i = carray->n_closures++;
4004       carray = g_realloc (carray, sizeof (*carray) + sizeof (carray->closures[0]) * i);
4005     }
4006   carray->closures[i] = closure;
4007   g_datalist_id_set_data_full (&object->qdata, quark_closure_array, carray, destroy_closure_array);
4008   G_UNLOCK (closure_array_mutex);
4009 }
4010
4011 /**
4012  * g_closure_new_object:
4013  * @sizeof_closure: the size of the structure to allocate, must be at least
4014  *  <literal>sizeof (GClosure)</literal>
4015  * @object: a #GObject pointer to store in the @data field of the newly
4016  *  allocated #GClosure
4017  *
4018  * A variant of g_closure_new_simple() which stores @object in the
4019  * @data field of the closure and calls g_object_watch_closure() on
4020  * @object and the created closure. This function is mainly useful
4021  * when implementing new types of closures.
4022  *
4023  * Returns: (transfer full): a newly allocated #GClosure
4024  */
4025 GClosure*
4026 g_closure_new_object (guint    sizeof_closure,
4027                       GObject *object)
4028 {
4029   GClosure *closure;
4030
4031   g_return_val_if_fail (G_IS_OBJECT (object), NULL);
4032   g_return_val_if_fail (object->ref_count > 0, NULL);     /* this doesn't work on finalizing objects */
4033
4034   closure = g_closure_new_simple (sizeof_closure, object);
4035   g_object_watch_closure (object, closure);
4036
4037   return closure;
4038 }
4039
4040 /**
4041  * g_cclosure_new_object: (skip)
4042  * @callback_func: the function to invoke
4043  * @object: a #GObject pointer to pass to @callback_func
4044  *
4045  * A variant of g_cclosure_new() which uses @object as @user_data and
4046  * calls g_object_watch_closure() on @object and the created
4047  * closure. This function is useful when you have a callback closely
4048  * associated with a #GObject, and want the callback to no longer run
4049  * after the object is is freed.
4050  *
4051  * Returns: a new #GCClosure
4052  */
4053 GClosure*
4054 g_cclosure_new_object (GCallback callback_func,
4055                        GObject  *object)
4056 {
4057   GClosure *closure;
4058
4059   g_return_val_if_fail (G_IS_OBJECT (object), NULL);
4060   g_return_val_if_fail (object->ref_count > 0, NULL);     /* this doesn't work on finalizing objects */
4061   g_return_val_if_fail (callback_func != NULL, NULL);
4062
4063   closure = g_cclosure_new (callback_func, object, NULL);
4064   g_object_watch_closure (object, closure);
4065
4066   return closure;
4067 }
4068
4069 /**
4070  * g_cclosure_new_object_swap: (skip)
4071  * @callback_func: the function to invoke
4072  * @object: a #GObject pointer to pass to @callback_func
4073  *
4074  * A variant of g_cclosure_new_swap() which uses @object as @user_data
4075  * and calls g_object_watch_closure() on @object and the created
4076  * closure. This function is useful when you have a callback closely
4077  * associated with a #GObject, and want the callback to no longer run
4078  * after the object is is freed.
4079  *
4080  * Returns: a new #GCClosure
4081  */
4082 GClosure*
4083 g_cclosure_new_object_swap (GCallback callback_func,
4084                             GObject  *object)
4085 {
4086   GClosure *closure;
4087
4088   g_return_val_if_fail (G_IS_OBJECT (object), NULL);
4089   g_return_val_if_fail (object->ref_count > 0, NULL);     /* this doesn't work on finalizing objects */
4090   g_return_val_if_fail (callback_func != NULL, NULL);
4091
4092   closure = g_cclosure_new_swap (callback_func, object, NULL);
4093   g_object_watch_closure (object, closure);
4094
4095   return closure;
4096 }
4097
4098 gsize
4099 g_object_compat_control (gsize           what,
4100                          gpointer        data)
4101 {
4102   switch (what)
4103     {
4104       gpointer *pp;
4105     case 1:     /* floating base type */
4106       return G_TYPE_INITIALLY_UNOWNED;
4107     case 2:     /* FIXME: remove this once GLib/Gtk+ break ABI again */
4108       floating_flag_handler = (guint(*)(GObject*,gint)) data;
4109       return 1;
4110     case 3:     /* FIXME: remove this once GLib/Gtk+ break ABI again */
4111       pp = data;
4112       *pp = floating_flag_handler;
4113       return 1;
4114     default:
4115       return 0;
4116     }
4117 }
4118
4119 G_DEFINE_TYPE (GInitiallyUnowned, g_initially_unowned, G_TYPE_OBJECT);
4120
4121 static void
4122 g_initially_unowned_init (GInitiallyUnowned *object)
4123 {
4124   g_object_force_floating (object);
4125 }
4126
4127 static void
4128 g_initially_unowned_class_init (GInitiallyUnownedClass *klass)
4129 {
4130 }
4131
4132 /**
4133  * GWeakRef:
4134  *
4135  * A structure containing a weak reference to a #GObject.  It can either
4136  * be empty (i.e. point to %NULL), or point to an object for as long as
4137  * at least one "strong" reference to that object exists. Before the
4138  * object's #GObjectClass.dispose method is called, every #GWeakRef
4139  * associated with becomes empty (i.e. points to %NULL).
4140  *
4141  * Like #GValue, #GWeakRef can be statically allocated, stack- or
4142  * heap-allocated, or embedded in larger structures.
4143  *
4144  * Unlike g_object_weak_ref() and g_object_add_weak_pointer(), this weak
4145  * reference is thread-safe: converting a weak pointer to a reference is
4146  * atomic with respect to invalidation of weak pointers to destroyed
4147  * objects.
4148  *
4149  * If the object's #GObjectClass.dispose method results in additional
4150  * references to the object being held, any #GWeakRef<!-- -->s taken
4151  * before it was disposed will continue to point to %NULL.  If
4152  * #GWeakRef<!-- -->s are taken after the object is disposed and
4153  * re-referenced, they will continue to point to it until its refcount
4154  * goes back to zero, at which point they too will be invalidated.
4155  */
4156
4157 /**
4158  * g_weak_ref_init: (skip)
4159  * @weak_ref: (inout): uninitialized or empty location for a weak
4160  *    reference
4161  * @object: (allow-none): a #GObject or %NULL
4162  *
4163  * Initialise a non-statically-allocated #GWeakRef.
4164  *
4165  * This function also calls g_weak_ref_set() with @object on the
4166  * freshly-initialised weak reference.
4167  *
4168  * This function should always be matched with a call to
4169  * g_weak_ref_clear().  It is not necessary to use this function for a
4170  * #GWeakRef in static storage because it will already be
4171  * properly initialised.  Just use g_weak_ref_set() directly.
4172  *
4173  * Since: 2.32
4174  */
4175 void
4176 g_weak_ref_init (GWeakRef *weak_ref,
4177                  gpointer  object)
4178 {
4179   weak_ref->priv.p = NULL;
4180
4181   g_weak_ref_set (weak_ref, object);
4182 }
4183
4184 /**
4185  * g_weak_ref_clear: (skip)
4186  * @weak_ref: (inout): location of a weak reference, which
4187  *  may be empty
4188  *
4189  * Frees resources associated with a non-statically-allocated #GWeakRef.
4190  * After this call, the #GWeakRef is left in an undefined state.
4191  *
4192  * You should only call this on a #GWeakRef that previously had
4193  * g_weak_ref_init() called on it.
4194  *
4195  * Since: 2.32
4196  */
4197 void
4198 g_weak_ref_clear (GWeakRef *weak_ref)
4199 {
4200   g_weak_ref_set (weak_ref, NULL);
4201
4202   /* be unkind */
4203   weak_ref->priv.p = (void *) 0xccccccccu;
4204 }
4205
4206 /**
4207  * g_weak_ref_get: (skip)
4208  * @weak_ref: (inout): location of a weak reference to a #GObject
4209  *
4210  * If @weak_ref is not empty, atomically acquire a strong
4211  * reference to the object it points to, and return that reference.
4212  *
4213  * This function is needed because of the potential race between taking
4214  * the pointer value and g_object_ref() on it, if the object was losing
4215  * its last reference at the same time in a different thread.
4216  *
4217  * The caller should release the resulting reference in the usual way,
4218  * by using g_object_unref().
4219  *
4220  * Returns: (transfer full) (type GObject.Object): the object pointed to
4221  *     by @weak_ref, or %NULL if it was empty
4222  *
4223  * Since: 2.32
4224  */
4225 gpointer
4226 g_weak_ref_get (GWeakRef *weak_ref)
4227 {
4228   gpointer object_or_null;
4229
4230   g_return_val_if_fail (weak_ref!= NULL, NULL);
4231
4232   g_rw_lock_reader_lock (&weak_locations_lock);
4233
4234   object_or_null = weak_ref->priv.p;
4235
4236   if (object_or_null != NULL)
4237     g_object_ref (object_or_null);
4238
4239   g_rw_lock_reader_unlock (&weak_locations_lock);
4240
4241   return object_or_null;
4242 }
4243
4244 /**
4245  * g_weak_ref_set: (skip)
4246  * @weak_ref: location for a weak reference
4247  * @object: (allow-none): a #GObject or %NULL
4248  *
4249  * Change the object to which @weak_ref points, or set it to
4250  * %NULL.
4251  *
4252  * You must own a strong reference on @object while calling this
4253  * function.
4254  *
4255  * Since: 2.32
4256  */
4257 void
4258 g_weak_ref_set (GWeakRef *weak_ref,
4259                 gpointer  object)
4260 {
4261   GSList **weak_locations;
4262   GObject *new_object;
4263   GObject *old_object;
4264
4265   g_return_if_fail (weak_ref != NULL);
4266   g_return_if_fail (object == NULL || G_IS_OBJECT (object));
4267
4268   new_object = object;
4269
4270   g_rw_lock_writer_lock (&weak_locations_lock);
4271
4272   /* We use the extra level of indirection here so that if we have ever
4273    * had a weak pointer installed at any point in time on this object,
4274    * we can see that there is a non-NULL value associated with the
4275    * weak-pointer quark and know that this value will not change at any
4276    * point in the object's lifetime.
4277    *
4278    * Both properties are important for reducing the amount of times we
4279    * need to acquire locks and for decreasing the duration of time the
4280    * lock is held while avoiding some rather tricky races.
4281    *
4282    * Specifically: we can avoid having to do an extra unconditional lock
4283    * in g_object_unref() without worrying about some extremely tricky
4284    * races.
4285    */
4286
4287   old_object = weak_ref->priv.p;
4288   if (new_object != old_object)
4289     {
4290       weak_ref->priv.p = new_object;
4291
4292       /* Remove the weak ref from the old object */
4293       if (old_object != NULL)
4294         {
4295           weak_locations = g_datalist_id_get_data (&old_object->qdata, quark_weak_locations);
4296           /* for it to point to an object, the object must have had it added once */
4297           g_assert (weak_locations != NULL);
4298
4299           *weak_locations = g_slist_remove (*weak_locations, weak_ref);
4300         }
4301
4302       /* Add the weak ref to the new object */
4303       if (new_object != NULL)
4304         {
4305           weak_locations = g_datalist_id_get_data (&new_object->qdata, quark_weak_locations);
4306
4307           if (weak_locations == NULL)
4308             {
4309               weak_locations = g_new0 (GSList *, 1);
4310               g_datalist_id_set_data_full (&new_object->qdata, quark_weak_locations, weak_locations, g_free);
4311             }
4312
4313           *weak_locations = g_slist_prepend (*weak_locations, weak_ref);
4314         }
4315     }
4316
4317   g_rw_lock_writer_unlock (&weak_locations_lock);
4318 }