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