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