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