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