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