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