Docs: Don't use the note tag
[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 <function>container_add_child()</function> will g_object_ref_sink() the
61  * passed in child, no reference of the newly created child is leaked.
62  * Without floating references, <function>container_add_child()</function>
63  * can only g_object_ref() the new child, so to implement this code without
64  * reference leaks, it would have to be 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
73  * an ordinary reference by calling g_object_ref_sink().
74  * For already sunken objects (objects that don't have a floating reference
75  * anymore), g_object_ref_sink() is equivalent to g_object_ref() and returns
76  * a new reference.
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  * <example>
2231  * <title>Using g_object_get(<!-- -->)</title>
2232  * An example of using g_object_get() to get the contents
2233  * of three properties - one of type #G_TYPE_INT,
2234  * one of type #G_TYPE_STRING, and one of type #G_TYPE_OBJECT:
2235  * <programlisting>
2236  *  gint intval;
2237  *  gchar *strval;
2238  *  GObject *objval;
2239  *
2240  *  g_object_get (my_object,
2241  *                "int-property", &intval,
2242  *                "str-property", &strval,
2243  *                "obj-property", &objval,
2244  *                NULL);
2245  *
2246  *  // Do something with intval, strval, objval
2247  *
2248  *  g_free (strval);
2249  *  g_object_unref (objval);
2250  * </programlisting>
2251  * </example>
2252  */
2253 void
2254 g_object_get (gpointer     _object,
2255               const gchar *first_property_name,
2256               ...)
2257 {
2258   GObject *object = _object;
2259   va_list var_args;
2260   
2261   g_return_if_fail (G_IS_OBJECT (object));
2262   
2263   va_start (var_args, first_property_name);
2264   g_object_get_valist (object, first_property_name, var_args);
2265   va_end (var_args);
2266 }
2267
2268 /**
2269  * g_object_set_property:
2270  * @object: a #GObject
2271  * @property_name: the name of the property to set
2272  * @value: the value
2273  *
2274  * Sets a property on an object.
2275  */
2276 void
2277 g_object_set_property (GObject      *object,
2278                        const gchar  *property_name,
2279                        const GValue *value)
2280 {
2281   GObjectNotifyQueue *nqueue;
2282   GParamSpec *pspec;
2283   
2284   g_return_if_fail (G_IS_OBJECT (object));
2285   g_return_if_fail (property_name != NULL);
2286   g_return_if_fail (G_IS_VALUE (value));
2287   
2288   g_object_ref (object);
2289   nqueue = g_object_notify_queue_freeze (object, FALSE);
2290   
2291   pspec = g_param_spec_pool_lookup (pspec_pool,
2292                                     property_name,
2293                                     G_OBJECT_TYPE (object),
2294                                     TRUE);
2295   if (!pspec)
2296     g_warning ("%s: object class '%s' has no property named '%s'",
2297                G_STRFUNC,
2298                G_OBJECT_TYPE_NAME (object),
2299                property_name);
2300   else if (!(pspec->flags & G_PARAM_WRITABLE))
2301     g_warning ("%s: property '%s' of object class '%s' is not writable",
2302                G_STRFUNC,
2303                pspec->name,
2304                G_OBJECT_TYPE_NAME (object));
2305   else if ((pspec->flags & G_PARAM_CONSTRUCT_ONLY) && !object_in_construction (object))
2306     g_warning ("%s: construct property \"%s\" for object '%s' can't be set after construction",
2307                G_STRFUNC, pspec->name, G_OBJECT_TYPE_NAME (object));
2308   else
2309     object_set_property (object, pspec, value, nqueue);
2310   
2311   g_object_notify_queue_thaw (object, nqueue);
2312   g_object_unref (object);
2313 }
2314
2315 /**
2316  * g_object_get_property:
2317  * @object: a #GObject
2318  * @property_name: the name of the property to get
2319  * @value: return location for the property value
2320  *
2321  * Gets a property of an object. @value must have been initialized to the
2322  * expected type of the property (or a type to which the expected type can be
2323  * transformed) using g_value_init().
2324  *
2325  * In general, a copy is made of the property contents and the caller is
2326  * responsible for freeing the memory by calling g_value_unset().
2327  *
2328  * Note that g_object_get_property() is really intended for language
2329  * bindings, g_object_get() is much more convenient for C programming.
2330  */
2331 void
2332 g_object_get_property (GObject     *object,
2333                        const gchar *property_name,
2334                        GValue      *value)
2335 {
2336   GParamSpec *pspec;
2337   
2338   g_return_if_fail (G_IS_OBJECT (object));
2339   g_return_if_fail (property_name != NULL);
2340   g_return_if_fail (G_IS_VALUE (value));
2341   
2342   g_object_ref (object);
2343   
2344   pspec = g_param_spec_pool_lookup (pspec_pool,
2345                                     property_name,
2346                                     G_OBJECT_TYPE (object),
2347                                     TRUE);
2348   if (!pspec)
2349     g_warning ("%s: object class '%s' has no property named '%s'",
2350                G_STRFUNC,
2351                G_OBJECT_TYPE_NAME (object),
2352                property_name);
2353   else if (!(pspec->flags & G_PARAM_READABLE))
2354     g_warning ("%s: property '%s' of object class '%s' is not readable",
2355                G_STRFUNC,
2356                pspec->name,
2357                G_OBJECT_TYPE_NAME (object));
2358   else
2359     {
2360       GValue *prop_value, tmp_value = G_VALUE_INIT;
2361       
2362       /* auto-conversion of the callers value type
2363        */
2364       if (G_VALUE_TYPE (value) == pspec->value_type)
2365         {
2366           g_value_reset (value);
2367           prop_value = value;
2368         }
2369       else if (!g_value_type_transformable (pspec->value_type, G_VALUE_TYPE (value)))
2370         {
2371           g_warning ("%s: can't retrieve property '%s' of type '%s' as value of type '%s'",
2372                      G_STRFUNC, pspec->name,
2373                      g_type_name (pspec->value_type),
2374                      G_VALUE_TYPE_NAME (value));
2375           g_object_unref (object);
2376           return;
2377         }
2378       else
2379         {
2380           g_value_init (&tmp_value, pspec->value_type);
2381           prop_value = &tmp_value;
2382         }
2383       object_get_property (object, pspec, prop_value);
2384       if (prop_value != value)
2385         {
2386           g_value_transform (prop_value, value);
2387           g_value_unset (&tmp_value);
2388         }
2389     }
2390   
2391   g_object_unref (object);
2392 }
2393
2394 /**
2395  * g_object_connect: (skip)
2396  * @object: a #GObject
2397  * @signal_spec: the spec for the first signal
2398  * @...: #GCallback for the first signal, followed by data for the
2399  *       first signal, followed optionally by more signal
2400  *       spec/callback/data triples, followed by %NULL
2401  *
2402  * A convenience function to connect multiple signals at once.
2403  *
2404  * The signal specs expected by this function have the form
2405  * "modifier::signal_name", where modifier can be one of the following:
2406  * <variablelist>
2407  * <varlistentry>
2408  * <term>signal</term>
2409  * <listitem><para>
2410  * equivalent to <literal>g_signal_connect_data (..., NULL, 0)</literal>
2411  * </para></listitem>
2412  * </varlistentry>
2413  * <varlistentry>
2414  * <term>object_signal</term>
2415  * <term>object-signal</term>
2416  * <listitem><para>
2417  * equivalent to <literal>g_signal_connect_object (..., 0)</literal>
2418  * </para></listitem>
2419  * </varlistentry>
2420  * <varlistentry>
2421  * <term>swapped_signal</term>
2422  * <term>swapped-signal</term>
2423  * <listitem><para>
2424  * equivalent to <literal>g_signal_connect_data (..., NULL, G_CONNECT_SWAPPED)</literal>
2425  * </para></listitem>
2426  * </varlistentry>
2427  * <varlistentry>
2428  * <term>swapped_object_signal</term>
2429  * <term>swapped-object-signal</term>
2430  * <listitem><para>
2431  * equivalent to <literal>g_signal_connect_object (..., G_CONNECT_SWAPPED)</literal>
2432  * </para></listitem>
2433  * </varlistentry>
2434  * <varlistentry>
2435  * <term>signal_after</term>
2436  * <term>signal-after</term>
2437  * <listitem><para>
2438  * equivalent to <literal>g_signal_connect_data (..., NULL, G_CONNECT_AFTER)</literal>
2439  * </para></listitem>
2440  * </varlistentry>
2441  * <varlistentry>
2442  * <term>object_signal_after</term>
2443  * <term>object-signal-after</term>
2444  * <listitem><para>
2445  * equivalent to <literal>g_signal_connect_object (..., G_CONNECT_AFTER)</literal>
2446  * </para></listitem>
2447  * </varlistentry>
2448  * <varlistentry>
2449  * <term>swapped_signal_after</term>
2450  * <term>swapped-signal-after</term>
2451  * <listitem><para>
2452  * equivalent to <literal>g_signal_connect_data (..., NULL, G_CONNECT_SWAPPED | G_CONNECT_AFTER)</literal>
2453  * </para></listitem>
2454  * </varlistentry>
2455  * <varlistentry>
2456  * <term>swapped_object_signal_after</term>
2457  * <term>swapped-object-signal-after</term>
2458  * <listitem><para>
2459  * equivalent to <literal>g_signal_connect_object (..., G_CONNECT_SWAPPED | G_CONNECT_AFTER)</literal>
2460  * </para></listitem>
2461  * </varlistentry>
2462  * </variablelist>
2463  *
2464  * |[
2465  *   menu->toplevel = g_object_connect (g_object_new (GTK_TYPE_WINDOW,
2466  *                                                 "type", GTK_WINDOW_POPUP,
2467  *                                                 "child", menu,
2468  *                                                 NULL),
2469  *                                   "signal::event", gtk_menu_window_event, menu,
2470  *                                   "signal::size_request", gtk_menu_window_size_request, menu,
2471  *                                   "signal::destroy", gtk_widget_destroyed, &amp;menu-&gt;toplevel,
2472  *                                   NULL);
2473  * ]|
2474  *
2475  * Returns: (transfer none): @object
2476  */
2477 gpointer
2478 g_object_connect (gpointer     _object,
2479                   const gchar *signal_spec,
2480                   ...)
2481 {
2482   GObject *object = _object;
2483   va_list var_args;
2484
2485   g_return_val_if_fail (G_IS_OBJECT (object), NULL);
2486   g_return_val_if_fail (object->ref_count > 0, object);
2487
2488   va_start (var_args, signal_spec);
2489   while (signal_spec)
2490     {
2491       GCallback callback = va_arg (var_args, GCallback);
2492       gpointer data = va_arg (var_args, gpointer);
2493
2494       if (strncmp (signal_spec, "signal::", 8) == 0)
2495         g_signal_connect_data (object, signal_spec + 8,
2496                                callback, data, NULL,
2497                                0);
2498       else if (strncmp (signal_spec, "object_signal::", 15) == 0 ||
2499                strncmp (signal_spec, "object-signal::", 15) == 0)
2500         g_signal_connect_object (object, signal_spec + 15,
2501                                  callback, data,
2502                                  0);
2503       else if (strncmp (signal_spec, "swapped_signal::", 16) == 0 ||
2504                strncmp (signal_spec, "swapped-signal::", 16) == 0)
2505         g_signal_connect_data (object, signal_spec + 16,
2506                                callback, data, NULL,
2507                                G_CONNECT_SWAPPED);
2508       else if (strncmp (signal_spec, "swapped_object_signal::", 23) == 0 ||
2509                strncmp (signal_spec, "swapped-object-signal::", 23) == 0)
2510         g_signal_connect_object (object, signal_spec + 23,
2511                                  callback, data,
2512                                  G_CONNECT_SWAPPED);
2513       else if (strncmp (signal_spec, "signal_after::", 14) == 0 ||
2514                strncmp (signal_spec, "signal-after::", 14) == 0)
2515         g_signal_connect_data (object, signal_spec + 14,
2516                                callback, data, NULL,
2517                                G_CONNECT_AFTER);
2518       else if (strncmp (signal_spec, "object_signal_after::", 21) == 0 ||
2519                strncmp (signal_spec, "object-signal-after::", 21) == 0)
2520         g_signal_connect_object (object, signal_spec + 21,
2521                                  callback, data,
2522                                  G_CONNECT_AFTER);
2523       else if (strncmp (signal_spec, "swapped_signal_after::", 22) == 0 ||
2524                strncmp (signal_spec, "swapped-signal-after::", 22) == 0)
2525         g_signal_connect_data (object, signal_spec + 22,
2526                                callback, data, NULL,
2527                                G_CONNECT_SWAPPED | G_CONNECT_AFTER);
2528       else if (strncmp (signal_spec, "swapped_object_signal_after::", 29) == 0 ||
2529                strncmp (signal_spec, "swapped-object-signal-after::", 29) == 0)
2530         g_signal_connect_object (object, signal_spec + 29,
2531                                  callback, data,
2532                                  G_CONNECT_SWAPPED | G_CONNECT_AFTER);
2533       else
2534         {
2535           g_warning ("%s: invalid signal spec \"%s\"", G_STRFUNC, signal_spec);
2536           break;
2537         }
2538       signal_spec = va_arg (var_args, gchar*);
2539     }
2540   va_end (var_args);
2541
2542   return object;
2543 }
2544
2545 /**
2546  * g_object_disconnect: (skip)
2547  * @object: a #GObject
2548  * @signal_spec: the spec for the first signal
2549  * @...: #GCallback for the first signal, followed by data for the first signal,
2550  *  followed optionally by more signal spec/callback/data triples,
2551  *  followed by %NULL
2552  *
2553  * A convenience function to disconnect multiple signals at once.
2554  *
2555  * The signal specs expected by this function have the form
2556  * "any_signal", which means to disconnect any signal with matching
2557  * callback and data, or "any_signal::signal_name", which only
2558  * disconnects the signal named "signal_name".
2559  */
2560 void
2561 g_object_disconnect (gpointer     _object,
2562                      const gchar *signal_spec,
2563                      ...)
2564 {
2565   GObject *object = _object;
2566   va_list var_args;
2567
2568   g_return_if_fail (G_IS_OBJECT (object));
2569   g_return_if_fail (object->ref_count > 0);
2570
2571   va_start (var_args, signal_spec);
2572   while (signal_spec)
2573     {
2574       GCallback callback = va_arg (var_args, GCallback);
2575       gpointer data = va_arg (var_args, gpointer);
2576       guint sid = 0, detail = 0, mask = 0;
2577
2578       if (strncmp (signal_spec, "any_signal::", 12) == 0 ||
2579           strncmp (signal_spec, "any-signal::", 12) == 0)
2580         {
2581           signal_spec += 12;
2582           mask = G_SIGNAL_MATCH_ID | G_SIGNAL_MATCH_FUNC | G_SIGNAL_MATCH_DATA;
2583         }
2584       else if (strcmp (signal_spec, "any_signal") == 0 ||
2585                strcmp (signal_spec, "any-signal") == 0)
2586         {
2587           signal_spec += 10;
2588           mask = G_SIGNAL_MATCH_FUNC | G_SIGNAL_MATCH_DATA;
2589         }
2590       else
2591         {
2592           g_warning ("%s: invalid signal spec \"%s\"", G_STRFUNC, signal_spec);
2593           break;
2594         }
2595
2596       if ((mask & G_SIGNAL_MATCH_ID) &&
2597           !g_signal_parse_name (signal_spec, G_OBJECT_TYPE (object), &sid, &detail, FALSE))
2598         g_warning ("%s: invalid signal name \"%s\"", G_STRFUNC, signal_spec);
2599       else if (!g_signal_handlers_disconnect_matched (object, mask | (detail ? G_SIGNAL_MATCH_DETAIL : 0),
2600                                                       sid, detail,
2601                                                       NULL, (gpointer)callback, data))
2602         g_warning ("%s: signal handler %p(%p) is not connected", G_STRFUNC, callback, data);
2603       signal_spec = va_arg (var_args, gchar*);
2604     }
2605   va_end (var_args);
2606 }
2607
2608 typedef struct {
2609   GObject *object;
2610   guint n_weak_refs;
2611   struct {
2612     GWeakNotify notify;
2613     gpointer    data;
2614   } weak_refs[1];  /* flexible array */
2615 } WeakRefStack;
2616
2617 static void
2618 weak_refs_notify (gpointer data)
2619 {
2620   WeakRefStack *wstack = data;
2621   guint i;
2622
2623   for (i = 0; i < wstack->n_weak_refs; i++)
2624     wstack->weak_refs[i].notify (wstack->weak_refs[i].data, wstack->object);
2625   g_free (wstack);
2626 }
2627
2628 /**
2629  * g_object_weak_ref: (skip)
2630  * @object: #GObject to reference weakly
2631  * @notify: callback to invoke before the object is freed
2632  * @data: extra data to pass to notify
2633  *
2634  * Adds a weak reference callback to an object. Weak references are
2635  * used for notification when an object is finalized. They are called
2636  * "weak references" because they allow you to safely hold a pointer
2637  * to an object without calling g_object_ref() (g_object_ref() adds a
2638  * strong reference, that is, forces the object to stay alive).
2639  *
2640  * Note that the weak references created by this method are not
2641  * thread-safe: they cannot safely be used in one thread if the
2642  * object's last g_object_unref() might happen in another thread.
2643  * Use #GWeakRef if thread-safety is required.
2644  */
2645 void
2646 g_object_weak_ref (GObject    *object,
2647                    GWeakNotify notify,
2648                    gpointer    data)
2649 {
2650   WeakRefStack *wstack;
2651   guint i;
2652   
2653   g_return_if_fail (G_IS_OBJECT (object));
2654   g_return_if_fail (notify != NULL);
2655   g_return_if_fail (object->ref_count >= 1);
2656
2657   G_LOCK (weak_refs_mutex);
2658   wstack = g_datalist_id_remove_no_notify (&object->qdata, quark_weak_refs);
2659   if (wstack)
2660     {
2661       i = wstack->n_weak_refs++;
2662       wstack = g_realloc (wstack, sizeof (*wstack) + sizeof (wstack->weak_refs[0]) * i);
2663     }
2664   else
2665     {
2666       wstack = g_renew (WeakRefStack, NULL, 1);
2667       wstack->object = object;
2668       wstack->n_weak_refs = 1;
2669       i = 0;
2670     }
2671   wstack->weak_refs[i].notify = notify;
2672   wstack->weak_refs[i].data = data;
2673   g_datalist_id_set_data_full (&object->qdata, quark_weak_refs, wstack, weak_refs_notify);
2674   G_UNLOCK (weak_refs_mutex);
2675 }
2676
2677 /**
2678  * g_object_weak_unref: (skip)
2679  * @object: #GObject to remove a weak reference from
2680  * @notify: callback to search for
2681  * @data: data to search for
2682  *
2683  * Removes a weak reference callback to an object.
2684  */
2685 void
2686 g_object_weak_unref (GObject    *object,
2687                      GWeakNotify notify,
2688                      gpointer    data)
2689 {
2690   WeakRefStack *wstack;
2691   gboolean found_one = FALSE;
2692
2693   g_return_if_fail (G_IS_OBJECT (object));
2694   g_return_if_fail (notify != NULL);
2695
2696   G_LOCK (weak_refs_mutex);
2697   wstack = g_datalist_id_get_data (&object->qdata, quark_weak_refs);
2698   if (wstack)
2699     {
2700       guint i;
2701
2702       for (i = 0; i < wstack->n_weak_refs; i++)
2703         if (wstack->weak_refs[i].notify == notify &&
2704             wstack->weak_refs[i].data == data)
2705           {
2706             found_one = TRUE;
2707             wstack->n_weak_refs -= 1;
2708             if (i != wstack->n_weak_refs)
2709               wstack->weak_refs[i] = wstack->weak_refs[wstack->n_weak_refs];
2710
2711             break;
2712           }
2713     }
2714   G_UNLOCK (weak_refs_mutex);
2715   if (!found_one)
2716     g_warning ("%s: couldn't find weak ref %p(%p)", G_STRFUNC, notify, data);
2717 }
2718
2719 /**
2720  * g_object_add_weak_pointer: (skip)
2721  * @object: The object that should be weak referenced.
2722  * @weak_pointer_location: (inout): The memory address of a pointer.
2723  *
2724  * Adds a weak reference from weak_pointer to @object to indicate that
2725  * the pointer located at @weak_pointer_location is only valid during
2726  * the lifetime of @object. When the @object is finalized,
2727  * @weak_pointer will be set to %NULL.
2728  *
2729  * Note that as with g_object_weak_ref(), the weak references created by
2730  * this method are not thread-safe: they cannot safely be used in one
2731  * thread if the object's last g_object_unref() might happen in another
2732  * thread. Use #GWeakRef if thread-safety is required.
2733  */
2734 void
2735 g_object_add_weak_pointer (GObject  *object, 
2736                            gpointer *weak_pointer_location)
2737 {
2738   g_return_if_fail (G_IS_OBJECT (object));
2739   g_return_if_fail (weak_pointer_location != NULL);
2740
2741   g_object_weak_ref (object, 
2742                      (GWeakNotify) g_nullify_pointer, 
2743                      weak_pointer_location);
2744 }
2745
2746 /**
2747  * g_object_remove_weak_pointer: (skip)
2748  * @object: The object that is weak referenced.
2749  * @weak_pointer_location: (inout): The memory address of a pointer.
2750  *
2751  * Removes a weak reference from @object that was previously added
2752  * using g_object_add_weak_pointer(). The @weak_pointer_location has
2753  * to match the one used with g_object_add_weak_pointer().
2754  */
2755 void
2756 g_object_remove_weak_pointer (GObject  *object, 
2757                               gpointer *weak_pointer_location)
2758 {
2759   g_return_if_fail (G_IS_OBJECT (object));
2760   g_return_if_fail (weak_pointer_location != NULL);
2761
2762   g_object_weak_unref (object, 
2763                        (GWeakNotify) g_nullify_pointer, 
2764                        weak_pointer_location);
2765 }
2766
2767 static guint
2768 object_floating_flag_handler (GObject        *object,
2769                               gint            job)
2770 {
2771   switch (job)
2772     {
2773       gpointer oldvalue;
2774     case +1:    /* force floating if possible */
2775       do
2776         oldvalue = g_atomic_pointer_get (&object->qdata);
2777       while (!g_atomic_pointer_compare_and_exchange ((void**) &object->qdata, oldvalue,
2778                                                      (gpointer) ((gsize) oldvalue | OBJECT_FLOATING_FLAG)));
2779       return (gsize) oldvalue & OBJECT_FLOATING_FLAG;
2780     case -1:    /* sink if possible */
2781       do
2782         oldvalue = g_atomic_pointer_get (&object->qdata);
2783       while (!g_atomic_pointer_compare_and_exchange ((void**) &object->qdata, oldvalue,
2784                                                      (gpointer) ((gsize) oldvalue & ~(gsize) OBJECT_FLOATING_FLAG)));
2785       return (gsize) oldvalue & OBJECT_FLOATING_FLAG;
2786     default:    /* check floating */
2787       return 0 != ((gsize) g_atomic_pointer_get (&object->qdata) & OBJECT_FLOATING_FLAG);
2788     }
2789 }
2790
2791 /**
2792  * g_object_is_floating:
2793  * @object: (type GObject.Object): a #GObject
2794  *
2795  * Checks whether @object has a <link linkend="floating-ref">floating</link>
2796  * reference.
2797  *
2798  * Since: 2.10
2799  *
2800  * Returns: %TRUE if @object has a floating reference
2801  */
2802 gboolean
2803 g_object_is_floating (gpointer _object)
2804 {
2805   GObject *object = _object;
2806   g_return_val_if_fail (G_IS_OBJECT (object), FALSE);
2807   return floating_flag_handler (object, 0);
2808 }
2809
2810 /**
2811  * g_object_ref_sink:
2812  * @object: (type GObject.Object): a #GObject
2813  *
2814  * Increase the reference count of @object, and possibly remove the
2815  * <link linkend="floating-ref">floating</link> reference, if @object
2816  * has a floating reference.
2817  *
2818  * In other words, if the object is floating, then this call "assumes
2819  * ownership" of the floating reference, converting it to a normal
2820  * reference by clearing the floating flag while leaving the reference
2821  * count unchanged.  If the object is not floating, then this call
2822  * adds a new normal reference increasing the reference count by one.
2823  *
2824  * Since: 2.10
2825  *
2826  * Returns: (type GObject.Object) (transfer none): @object
2827  */
2828 gpointer
2829 g_object_ref_sink (gpointer _object)
2830 {
2831   GObject *object = _object;
2832   gboolean was_floating;
2833   g_return_val_if_fail (G_IS_OBJECT (object), object);
2834   g_return_val_if_fail (object->ref_count >= 1, object);
2835   g_object_ref (object);
2836   was_floating = floating_flag_handler (object, -1);
2837   if (was_floating)
2838     g_object_unref (object);
2839   return object;
2840 }
2841
2842 /**
2843  * g_object_force_floating:
2844  * @object: a #GObject
2845  *
2846  * This function is intended for #GObject implementations to re-enforce a
2847  * <link linkend="floating-ref">floating</link> object reference.
2848  * Doing this is seldom required: all
2849  * #GInitiallyUnowned<!-- -->s are created with a floating reference which
2850  * usually just needs to be sunken by calling g_object_ref_sink().
2851  *
2852  * Since: 2.10
2853  */
2854 void
2855 g_object_force_floating (GObject *object)
2856 {
2857   g_return_if_fail (G_IS_OBJECT (object));
2858   g_return_if_fail (object->ref_count >= 1);
2859
2860   floating_flag_handler (object, +1);
2861 }
2862
2863 typedef struct {
2864   GObject *object;
2865   guint n_toggle_refs;
2866   struct {
2867     GToggleNotify notify;
2868     gpointer    data;
2869   } toggle_refs[1];  /* flexible array */
2870 } ToggleRefStack;
2871
2872 static void
2873 toggle_refs_notify (GObject *object,
2874                     gboolean is_last_ref)
2875 {
2876   ToggleRefStack tstack, *tstackptr;
2877
2878   G_LOCK (toggle_refs_mutex);
2879   tstackptr = g_datalist_id_get_data (&object->qdata, quark_toggle_refs);
2880   tstack = *tstackptr;
2881   G_UNLOCK (toggle_refs_mutex);
2882
2883   /* Reentrancy here is not as tricky as it seems, because a toggle reference
2884    * will only be notified when there is exactly one of them.
2885    */
2886   g_assert (tstack.n_toggle_refs == 1);
2887   tstack.toggle_refs[0].notify (tstack.toggle_refs[0].data, tstack.object, is_last_ref);
2888 }
2889
2890 /**
2891  * g_object_add_toggle_ref: (skip)
2892  * @object: a #GObject
2893  * @notify: a function to call when this reference is the
2894  *  last reference to the object, or is no longer
2895  *  the last reference.
2896  * @data: data to pass to @notify
2897  *
2898  * Increases the reference count of the object by one and sets a
2899  * callback to be called when all other references to the object are
2900  * dropped, or when this is already the last reference to the object
2901  * and another reference is established.
2902  *
2903  * This functionality is intended for binding @object to a proxy
2904  * object managed by another memory manager. This is done with two
2905  * paired references: the strong reference added by
2906  * g_object_add_toggle_ref() and a reverse reference to the proxy
2907  * object which is either a strong reference or weak reference.
2908  *
2909  * The setup is that when there are no other references to @object,
2910  * only a weak reference is held in the reverse direction from @object
2911  * to the proxy object, but when there are other references held to
2912  * @object, a strong reference is held. The @notify callback is called
2913  * when the reference from @object to the proxy object should be
2914  * <firstterm>toggled</firstterm> from strong to weak (@is_last_ref
2915  * true) or weak to strong (@is_last_ref false).
2916  *
2917  * Since a (normal) reference must be held to the object before
2918  * calling g_object_add_toggle_ref(), the initial state of the reverse
2919  * link is always strong.
2920  *
2921  * Multiple toggle references may be added to the same gobject,
2922  * however if there are multiple toggle references to an object, none
2923  * of them will ever be notified until all but one are removed.  For
2924  * this reason, you should only ever use a toggle reference if there
2925  * is important state in the proxy object.
2926  *
2927  * Since: 2.8
2928  */
2929 void
2930 g_object_add_toggle_ref (GObject       *object,
2931                          GToggleNotify  notify,
2932                          gpointer       data)
2933 {
2934   ToggleRefStack *tstack;
2935   guint i;
2936   
2937   g_return_if_fail (G_IS_OBJECT (object));
2938   g_return_if_fail (notify != NULL);
2939   g_return_if_fail (object->ref_count >= 1);
2940
2941   g_object_ref (object);
2942
2943   G_LOCK (toggle_refs_mutex);
2944   tstack = g_datalist_id_remove_no_notify (&object->qdata, quark_toggle_refs);
2945   if (tstack)
2946     {
2947       i = tstack->n_toggle_refs++;
2948       /* allocate i = tstate->n_toggle_refs - 1 positions beyond the 1 declared
2949        * in tstate->toggle_refs */
2950       tstack = g_realloc (tstack, sizeof (*tstack) + sizeof (tstack->toggle_refs[0]) * i);
2951     }
2952   else
2953     {
2954       tstack = g_renew (ToggleRefStack, NULL, 1);
2955       tstack->object = object;
2956       tstack->n_toggle_refs = 1;
2957       i = 0;
2958     }
2959
2960   /* Set a flag for fast lookup after adding the first toggle reference */
2961   if (tstack->n_toggle_refs == 1)
2962     g_datalist_set_flags (&object->qdata, OBJECT_HAS_TOGGLE_REF_FLAG);
2963   
2964   tstack->toggle_refs[i].notify = notify;
2965   tstack->toggle_refs[i].data = data;
2966   g_datalist_id_set_data_full (&object->qdata, quark_toggle_refs, tstack,
2967                                (GDestroyNotify)g_free);
2968   G_UNLOCK (toggle_refs_mutex);
2969 }
2970
2971 /**
2972  * g_object_remove_toggle_ref: (skip)
2973  * @object: a #GObject
2974  * @notify: a function to call when this reference is the
2975  *  last reference to the object, or is no longer
2976  *  the last reference.
2977  * @data: data to pass to @notify
2978  *
2979  * Removes a reference added with g_object_add_toggle_ref(). The
2980  * reference count of the object is decreased by one.
2981  *
2982  * Since: 2.8
2983  */
2984 void
2985 g_object_remove_toggle_ref (GObject       *object,
2986                             GToggleNotify  notify,
2987                             gpointer       data)
2988 {
2989   ToggleRefStack *tstack;
2990   gboolean found_one = FALSE;
2991
2992   g_return_if_fail (G_IS_OBJECT (object));
2993   g_return_if_fail (notify != NULL);
2994
2995   G_LOCK (toggle_refs_mutex);
2996   tstack = g_datalist_id_get_data (&object->qdata, quark_toggle_refs);
2997   if (tstack)
2998     {
2999       guint i;
3000
3001       for (i = 0; i < tstack->n_toggle_refs; i++)
3002         if (tstack->toggle_refs[i].notify == notify &&
3003             tstack->toggle_refs[i].data == data)
3004           {
3005             found_one = TRUE;
3006             tstack->n_toggle_refs -= 1;
3007             if (i != tstack->n_toggle_refs)
3008               tstack->toggle_refs[i] = tstack->toggle_refs[tstack->n_toggle_refs];
3009
3010             if (tstack->n_toggle_refs == 0)
3011               g_datalist_unset_flags (&object->qdata, OBJECT_HAS_TOGGLE_REF_FLAG);
3012
3013             break;
3014           }
3015     }
3016   G_UNLOCK (toggle_refs_mutex);
3017
3018   if (found_one)
3019     g_object_unref (object);
3020   else
3021     g_warning ("%s: couldn't find toggle ref %p(%p)", G_STRFUNC, notify, data);
3022 }
3023
3024 /**
3025  * g_object_ref:
3026  * @object: (type GObject.Object): a #GObject
3027  *
3028  * Increases the reference count of @object.
3029  *
3030  * Returns: (type GObject.Object) (transfer none): the same @object
3031  */
3032 gpointer
3033 g_object_ref (gpointer _object)
3034 {
3035   GObject *object = _object;
3036   gint old_val;
3037
3038   g_return_val_if_fail (G_IS_OBJECT (object), NULL);
3039   g_return_val_if_fail (object->ref_count > 0, NULL);
3040   
3041   old_val = g_atomic_int_add (&object->ref_count, 1);
3042
3043   if (old_val == 1 && OBJECT_HAS_TOGGLE_REF (object))
3044     toggle_refs_notify (object, FALSE);
3045
3046   TRACE (GOBJECT_OBJECT_REF(object,G_TYPE_FROM_INSTANCE(object),old_val));
3047
3048   return object;
3049 }
3050
3051 /**
3052  * g_object_unref:
3053  * @object: (type GObject.Object): a #GObject
3054  *
3055  * Decreases the reference count of @object. When its reference count
3056  * drops to 0, the object is finalized (i.e. its memory is freed).
3057  */
3058 void
3059 g_object_unref (gpointer _object)
3060 {
3061   GObject *object = _object;
3062   gint old_ref;
3063   
3064   g_return_if_fail (G_IS_OBJECT (object));
3065   g_return_if_fail (object->ref_count > 0);
3066   
3067   /* here we want to atomically do: if (ref_count>1) { ref_count--; return; } */
3068  retry_atomic_decrement1:
3069   old_ref = g_atomic_int_get (&object->ref_count);
3070   if (old_ref > 1)
3071     {
3072       /* valid if last 2 refs are owned by this call to unref and the toggle_ref */
3073       gboolean has_toggle_ref = OBJECT_HAS_TOGGLE_REF (object);
3074
3075       if (!g_atomic_int_compare_and_exchange ((int *)&object->ref_count, old_ref, old_ref - 1))
3076         goto retry_atomic_decrement1;
3077
3078       TRACE (GOBJECT_OBJECT_UNREF(object,G_TYPE_FROM_INSTANCE(object),old_ref));
3079
3080       /* if we went from 2->1 we need to notify toggle refs if any */
3081       if (old_ref == 2 && has_toggle_ref) /* The last ref being held in this case is owned by the toggle_ref */
3082         toggle_refs_notify (object, TRUE);
3083     }
3084   else
3085     {
3086       GSList **weak_locations;
3087
3088       /* The only way that this object can live at this point is if
3089        * there are outstanding weak references already established
3090        * before we got here.
3091        *
3092        * If there were not already weak references then no more can be
3093        * established at this time, because the other thread would have
3094        * to hold a strong ref in order to call
3095        * g_object_add_weak_pointer() and then we wouldn't be here.
3096        */
3097       weak_locations = g_datalist_id_get_data (&object->qdata, quark_weak_locations);
3098
3099       if (weak_locations != NULL)
3100         {
3101           g_rw_lock_writer_lock (&weak_locations_lock);
3102
3103           /* It is possible that one of the weak references beat us to
3104            * the lock. Make sure the refcount is still what we expected
3105            * it to be.
3106            */
3107           old_ref = g_atomic_int_get (&object->ref_count);
3108           if (old_ref != 1)
3109             {
3110               g_rw_lock_writer_unlock (&weak_locations_lock);
3111               goto retry_atomic_decrement1;
3112             }
3113
3114           /* We got the lock first, so the object will definitely die
3115            * now. Clear out all the weak references.
3116            */
3117           while (*weak_locations)
3118             {
3119               GWeakRef *weak_ref_location = (*weak_locations)->data;
3120
3121               weak_ref_location->priv.p = NULL;
3122               *weak_locations = g_slist_delete_link (*weak_locations, *weak_locations);
3123             }
3124
3125           g_rw_lock_writer_unlock (&weak_locations_lock);
3126         }
3127
3128       /* we are about to remove the last reference */
3129       TRACE (GOBJECT_OBJECT_DISPOSE(object,G_TYPE_FROM_INSTANCE(object), 1));
3130       G_OBJECT_GET_CLASS (object)->dispose (object);
3131       TRACE (GOBJECT_OBJECT_DISPOSE_END(object,G_TYPE_FROM_INSTANCE(object), 1));
3132
3133       /* may have been re-referenced meanwhile */
3134     retry_atomic_decrement2:
3135       old_ref = g_atomic_int_get ((int *)&object->ref_count);
3136       if (old_ref > 1)
3137         {
3138           /* valid if last 2 refs are owned by this call to unref and the toggle_ref */
3139           gboolean has_toggle_ref = OBJECT_HAS_TOGGLE_REF (object);
3140
3141           if (!g_atomic_int_compare_and_exchange ((int *)&object->ref_count, old_ref, old_ref - 1))
3142             goto retry_atomic_decrement2;
3143
3144           TRACE (GOBJECT_OBJECT_UNREF(object,G_TYPE_FROM_INSTANCE(object),old_ref));
3145
3146           /* if we went from 2->1 we need to notify toggle refs if any */
3147           if (old_ref == 2 && has_toggle_ref) /* The last ref being held in this case is owned by the toggle_ref */
3148             toggle_refs_notify (object, TRUE);
3149
3150           return;
3151         }
3152
3153       /* we are still in the process of taking away the last ref */
3154       g_datalist_id_set_data (&object->qdata, quark_closure_array, NULL);
3155       g_signal_handlers_destroy (object);
3156       g_datalist_id_set_data (&object->qdata, quark_weak_refs, NULL);
3157       
3158       /* decrement the last reference */
3159       old_ref = g_atomic_int_add (&object->ref_count, -1);
3160
3161       TRACE (GOBJECT_OBJECT_UNREF(object,G_TYPE_FROM_INSTANCE(object),old_ref));
3162
3163       /* may have been re-referenced meanwhile */
3164       if (G_LIKELY (old_ref == 1))
3165         {
3166           TRACE (GOBJECT_OBJECT_FINALIZE(object,G_TYPE_FROM_INSTANCE(object)));
3167           G_OBJECT_GET_CLASS (object)->finalize (object);
3168
3169           TRACE (GOBJECT_OBJECT_FINALIZE_END(object,G_TYPE_FROM_INSTANCE(object)));
3170
3171 #ifdef  G_ENABLE_DEBUG
3172           IF_DEBUG (OBJECTS)
3173             {
3174               /* catch objects not chaining finalize handlers */
3175               G_LOCK (debug_objects);
3176               g_assert (g_hash_table_lookup (debug_objects_ht, object) == NULL);
3177               G_UNLOCK (debug_objects);
3178             }
3179 #endif  /* G_ENABLE_DEBUG */
3180           g_type_free_instance ((GTypeInstance*) object);
3181         }
3182     }
3183 }
3184
3185 /**
3186  * g_clear_object: (skip)
3187  * @object_ptr: a pointer to a #GObject reference
3188  *
3189  * Clears a reference to a #GObject.
3190  *
3191  * @object_ptr must not be %NULL.
3192  *
3193  * If the reference is %NULL then this function does nothing.
3194  * Otherwise, the reference count of the object is decreased and the
3195  * pointer is set to %NULL.
3196  *
3197  * This function is threadsafe and modifies the pointer atomically,
3198  * using memory barriers where needed.
3199  *
3200  * A macro is also included that allows this function to be used without
3201  * pointer casts.
3202  *
3203  * Since: 2.28
3204  **/
3205 #undef g_clear_object
3206 void
3207 g_clear_object (volatile GObject **object_ptr)
3208 {
3209   g_clear_pointer (object_ptr, g_object_unref);
3210 }
3211
3212 /**
3213  * g_object_get_qdata:
3214  * @object: The GObject to get a stored user data pointer from
3215  * @quark: A #GQuark, naming the user data pointer
3216  * 
3217  * This function gets back user data pointers stored via
3218  * g_object_set_qdata().
3219  * 
3220  * Returns: (transfer none): The user data pointer set, or %NULL
3221  */
3222 gpointer
3223 g_object_get_qdata (GObject *object,
3224                     GQuark   quark)
3225 {
3226   g_return_val_if_fail (G_IS_OBJECT (object), NULL);
3227   
3228   return quark ? g_datalist_id_get_data (&object->qdata, quark) : NULL;
3229 }
3230
3231 /**
3232  * g_object_set_qdata: (skip)
3233  * @object: The GObject to set store a user data pointer
3234  * @quark: A #GQuark, naming the user data pointer
3235  * @data: An opaque user data pointer
3236  *
3237  * This sets an opaque, named pointer on an object.
3238  * The name is specified through a #GQuark (retrived e.g. via
3239  * g_quark_from_static_string()), and the pointer
3240  * can be gotten back from the @object with g_object_get_qdata()
3241  * until the @object is finalized.
3242  * Setting a previously set user data pointer, overrides (frees)
3243  * the old pointer set, using #NULL as pointer essentially
3244  * removes the data stored.
3245  */
3246 void
3247 g_object_set_qdata (GObject *object,
3248                     GQuark   quark,
3249                     gpointer data)
3250 {
3251   g_return_if_fail (G_IS_OBJECT (object));
3252   g_return_if_fail (quark > 0);
3253
3254   g_datalist_id_set_data (&object->qdata, quark, data);
3255 }
3256
3257 /**
3258  * g_object_dup_qdata:
3259  * @object: the #GObject to store user data on
3260  * @quark: a #GQuark, naming the user data pointer
3261  * @dup_func: (allow-none): function to dup the value
3262  * @user_data: (allow-none): passed as user_data to @dup_func
3263  *
3264  * This is a variant of g_object_get_qdata() which returns
3265  * a 'duplicate' of the value. @dup_func defines the
3266  * meaning of 'duplicate' in this context, it could e.g.
3267  * take a reference on a ref-counted object.
3268  *
3269  * If the @quark is not set on the object then @dup_func
3270  * will be called with a %NULL argument.
3271  *
3272  * Note that @dup_func is called while user data of @object
3273  * is locked.
3274  *
3275  * This function can be useful to avoid races when multiple
3276  * threads are using object data on the same key on the same
3277  * object.
3278  *
3279  * Returns: the result of calling @dup_func on the value
3280  *     associated with @quark on @object, or %NULL if not set.
3281  *     If @dup_func is %NULL, the value is returned
3282  *     unmodified.
3283  *
3284  * Since: 2.34
3285  */
3286 gpointer
3287 g_object_dup_qdata (GObject        *object,
3288                     GQuark          quark,
3289                     GDuplicateFunc   dup_func,
3290                     gpointer         user_data)
3291 {
3292   g_return_val_if_fail (G_IS_OBJECT (object), NULL);
3293   g_return_val_if_fail (quark > 0, NULL);
3294
3295   return g_datalist_id_dup_data (&object->qdata, quark, dup_func, user_data);
3296 }
3297
3298 /**
3299  * g_object_replace_qdata:
3300  * @object: the #GObject to store user data on
3301  * @quark: a #GQuark, naming the user data pointer
3302  * @oldval: (allow-none): the old value to compare against
3303  * @newval: (allow-none): the new value
3304  * @destroy: (allow-none): a destroy notify for the new value
3305  * @old_destroy: (allow-none): destroy notify for the existing value
3306  *
3307  * Compares the user data for the key @quark on @object with
3308  * @oldval, and if they are the same, replaces @oldval with
3309  * @newval.
3310  *
3311  * This is like a typical atomic compare-and-exchange
3312  * operation, for user data on an object.
3313  *
3314  * If the previous value was replaced then ownership of the
3315  * old value (@oldval) is passed to the caller, including
3316  * the registered destroy notify for it (passed out in @old_destroy).
3317  * Its up to the caller to free this as he wishes, which may
3318  * or may not include using @old_destroy as sometimes replacement
3319  * should not destroy the object in the normal way.
3320  *
3321  * Return: %TRUE if the existing value for @quark was replaced
3322  *  by @newval, %FALSE otherwise.
3323  *
3324  * Since: 2.34
3325  */
3326 gboolean
3327 g_object_replace_qdata (GObject        *object,
3328                         GQuark          quark,
3329                         gpointer        oldval,
3330                         gpointer        newval,
3331                         GDestroyNotify  destroy,
3332                         GDestroyNotify *old_destroy)
3333 {
3334   g_return_val_if_fail (G_IS_OBJECT (object), FALSE);
3335   g_return_val_if_fail (quark > 0, FALSE);
3336
3337   return g_datalist_id_replace_data (&object->qdata, quark,
3338                                      oldval, newval, destroy,
3339                                      old_destroy);
3340 }
3341
3342 /**
3343  * g_object_set_qdata_full: (skip)
3344  * @object: The GObject to set store a user data pointer
3345  * @quark: A #GQuark, naming the user data pointer
3346  * @data: An opaque user data pointer
3347  * @destroy: Function to invoke with @data as argument, when @data
3348  *           needs to be freed
3349  *
3350  * This function works like g_object_set_qdata(), but in addition,
3351  * a void (*destroy) (gpointer) function may be specified which is
3352  * called with @data as argument when the @object is finalized, or
3353  * the data is being overwritten by a call to g_object_set_qdata()
3354  * with the same @quark.
3355  */
3356 void
3357 g_object_set_qdata_full (GObject       *object,
3358                          GQuark         quark,
3359                          gpointer       data,
3360                          GDestroyNotify destroy)
3361 {
3362   g_return_if_fail (G_IS_OBJECT (object));
3363   g_return_if_fail (quark > 0);
3364   
3365   g_datalist_id_set_data_full (&object->qdata, quark, data,
3366                                data ? destroy : (GDestroyNotify) NULL);
3367 }
3368
3369 /**
3370  * g_object_steal_qdata:
3371  * @object: The GObject to get a stored user data pointer from
3372  * @quark: A #GQuark, naming the user data pointer
3373  *
3374  * This function gets back user data pointers stored via
3375  * g_object_set_qdata() and removes the @data from object
3376  * without invoking its destroy() function (if any was
3377  * set).
3378  * Usually, calling this function is only required to update
3379  * user data pointers with a destroy notifier, for example:
3380  * |[
3381  * void
3382  * object_add_to_user_list (GObject     *object,
3383  *                          const gchar *new_string)
3384  * {
3385  *   // the quark, naming the object data
3386  *   GQuark quark_string_list = g_quark_from_static_string ("my-string-list");
3387  *   // retrive the old string list
3388  *   GList *list = g_object_steal_qdata (object, quark_string_list);
3389  *
3390  *   // prepend new string
3391  *   list = g_list_prepend (list, g_strdup (new_string));
3392  *   // this changed 'list', so we need to set it again
3393  *   g_object_set_qdata_full (object, quark_string_list, list, free_string_list);
3394  * }
3395  * static void
3396  * free_string_list (gpointer data)
3397  * {
3398  *   GList *node, *list = data;
3399  *
3400  *   for (node = list; node; node = node->next)
3401  *     g_free (node->data);
3402  *   g_list_free (list);
3403  * }
3404  * ]|
3405  * Using g_object_get_qdata() in the above example, instead of
3406  * g_object_steal_qdata() would have left the destroy function set,
3407  * and thus the partial string list would have been freed upon
3408  * g_object_set_qdata_full().
3409  *
3410  * Returns: (transfer full): The user data pointer set, or %NULL
3411  */
3412 gpointer
3413 g_object_steal_qdata (GObject *object,
3414                       GQuark   quark)
3415 {
3416   g_return_val_if_fail (G_IS_OBJECT (object), NULL);
3417   g_return_val_if_fail (quark > 0, NULL);
3418   
3419   return g_datalist_id_remove_no_notify (&object->qdata, quark);
3420 }
3421
3422 /**
3423  * g_object_get_data:
3424  * @object: #GObject containing the associations
3425  * @key: name of the key for that association
3426  * 
3427  * Gets a named field from the objects table of associations (see g_object_set_data()).
3428  * 
3429  * Returns: (transfer none): the data if found, or %NULL if no such data exists.
3430  */
3431 gpointer
3432 g_object_get_data (GObject     *object,
3433                    const gchar *key)
3434 {
3435   g_return_val_if_fail (G_IS_OBJECT (object), NULL);
3436   g_return_val_if_fail (key != NULL, NULL);
3437
3438   return g_datalist_get_data (&object->qdata, key);
3439 }
3440
3441 /**
3442  * g_object_set_data:
3443  * @object: #GObject containing the associations.
3444  * @key: name of the key
3445  * @data: data to associate with that key
3446  *
3447  * Each object carries around a table of associations from
3448  * strings to pointers.  This function lets you set an association.
3449  *
3450  * If the object already had an association with that name,
3451  * the old association will be destroyed.
3452  */
3453 void
3454 g_object_set_data (GObject     *object,
3455                    const gchar *key,
3456                    gpointer     data)
3457 {
3458   g_return_if_fail (G_IS_OBJECT (object));
3459   g_return_if_fail (key != NULL);
3460
3461   g_datalist_id_set_data (&object->qdata, g_quark_from_string (key), data);
3462 }
3463
3464 /**
3465  * g_object_dup_data:
3466  * @object: the #GObject to store user data on
3467  * @key: a string, naming the user data pointer
3468  * @dup_func: (allow-none): function to dup the value
3469  * @user_data: (allow-none): passed as user_data to @dup_func
3470  *
3471  * This is a variant of g_object_get_data() which returns
3472  * a 'duplicate' of the value. @dup_func defines the
3473  * meaning of 'duplicate' in this context, it could e.g.
3474  * take a reference on a ref-counted object.
3475  *
3476  * If the @key is not set on the object then @dup_func
3477  * will be called with a %NULL argument.
3478  *
3479  * Note that @dup_func is called while user data of @object
3480  * is locked.
3481  *
3482  * This function can be useful to avoid races when multiple
3483  * threads are using object data on the same key on the same
3484  * object.
3485  *
3486  * Returns: the result of calling @dup_func on the value
3487  *     associated with @key on @object, or %NULL if not set.
3488  *     If @dup_func is %NULL, the value is returned
3489  *     unmodified.
3490  *
3491  * Since: 2.34
3492  */
3493 gpointer
3494 g_object_dup_data (GObject        *object,
3495                    const gchar    *key,
3496                    GDuplicateFunc   dup_func,
3497                    gpointer         user_data)
3498 {
3499   g_return_val_if_fail (G_IS_OBJECT (object), NULL);
3500   g_return_val_if_fail (key != NULL, NULL);
3501
3502   return g_datalist_id_dup_data (&object->qdata,
3503                                  g_quark_from_string (key),
3504                                  dup_func, user_data);
3505 }
3506
3507 /**
3508  * g_object_replace_data:
3509  * @object: the #GObject to store user data on
3510  * @key: a string, naming the user data pointer
3511  * @oldval: (allow-none): the old value to compare against
3512  * @newval: (allow-none): the new value
3513  * @destroy: (allow-none): a destroy notify for the new value
3514  * @old_destroy: (allow-none): destroy notify for the existing value
3515  *
3516  * Compares the user data for the key @key on @object with
3517  * @oldval, and if they are the same, replaces @oldval with
3518  * @newval.
3519  *
3520  * This is like a typical atomic compare-and-exchange
3521  * operation, for user data on an object.
3522  *
3523  * If the previous value was replaced then ownership of the
3524  * old value (@oldval) is passed to the caller, including
3525  * the registered destroy notify for it (passed out in @old_destroy).
3526  * Its up to the caller to free this as he wishes, which may
3527  * or may not include using @old_destroy as sometimes replacement
3528  * should not destroy the object in the normal way.
3529  *
3530  * Return: %TRUE if the existing value for @key was replaced
3531  *  by @newval, %FALSE otherwise.
3532  *
3533  * Since: 2.34
3534  */
3535 gboolean
3536 g_object_replace_data (GObject        *object,
3537                        const gchar    *key,
3538                        gpointer        oldval,
3539                        gpointer        newval,
3540                        GDestroyNotify  destroy,
3541                        GDestroyNotify *old_destroy)
3542 {
3543   g_return_val_if_fail (G_IS_OBJECT (object), FALSE);
3544   g_return_val_if_fail (key != NULL, FALSE);
3545
3546   return g_datalist_id_replace_data (&object->qdata,
3547                                      g_quark_from_string (key),
3548                                      oldval, newval, destroy,
3549                                      old_destroy);
3550 }
3551
3552 /**
3553  * g_object_set_data_full: (skip)
3554  * @object: #GObject containing the associations
3555  * @key: name of the key
3556  * @data: data to associate with that key
3557  * @destroy: function to call when the association is destroyed
3558  *
3559  * Like g_object_set_data() except it adds notification
3560  * for when the association is destroyed, either by setting it
3561  * to a different value or when the object is destroyed.
3562  *
3563  * Note that the @destroy callback is not called if @data is %NULL.
3564  */
3565 void
3566 g_object_set_data_full (GObject       *object,
3567                         const gchar   *key,
3568                         gpointer       data,
3569                         GDestroyNotify destroy)
3570 {
3571   g_return_if_fail (G_IS_OBJECT (object));
3572   g_return_if_fail (key != NULL);
3573
3574   g_datalist_id_set_data_full (&object->qdata, g_quark_from_string (key), data,
3575                                data ? destroy : (GDestroyNotify) NULL);
3576 }
3577
3578 /**
3579  * g_object_steal_data:
3580  * @object: #GObject containing the associations
3581  * @key: name of the key
3582  *
3583  * Remove a specified datum from the object's data associations,
3584  * without invoking the association's destroy handler.
3585  *
3586  * Returns: (transfer full): the data if found, or %NULL if no such data exists.
3587  */
3588 gpointer
3589 g_object_steal_data (GObject     *object,
3590                      const gchar *key)
3591 {
3592   GQuark quark;
3593
3594   g_return_val_if_fail (G_IS_OBJECT (object), NULL);
3595   g_return_val_if_fail (key != NULL, NULL);
3596
3597   quark = g_quark_try_string (key);
3598
3599   return quark ? g_datalist_id_remove_no_notify (&object->qdata, quark) : NULL;
3600 }
3601
3602 static void
3603 g_value_object_init (GValue *value)
3604 {
3605   value->data[0].v_pointer = NULL;
3606 }
3607
3608 static void
3609 g_value_object_free_value (GValue *value)
3610 {
3611   if (value->data[0].v_pointer)
3612     g_object_unref (value->data[0].v_pointer);
3613 }
3614
3615 static void
3616 g_value_object_copy_value (const GValue *src_value,
3617                            GValue       *dest_value)
3618 {
3619   if (src_value->data[0].v_pointer)
3620     dest_value->data[0].v_pointer = g_object_ref (src_value->data[0].v_pointer);
3621   else
3622     dest_value->data[0].v_pointer = NULL;
3623 }
3624
3625 static void
3626 g_value_object_transform_value (const GValue *src_value,
3627                                 GValue       *dest_value)
3628 {
3629   if (src_value->data[0].v_pointer && g_type_is_a (G_OBJECT_TYPE (src_value->data[0].v_pointer), G_VALUE_TYPE (dest_value)))
3630     dest_value->data[0].v_pointer = g_object_ref (src_value->data[0].v_pointer);
3631   else
3632     dest_value->data[0].v_pointer = NULL;
3633 }
3634
3635 static gpointer
3636 g_value_object_peek_pointer (const GValue *value)
3637 {
3638   return value->data[0].v_pointer;
3639 }
3640
3641 static gchar*
3642 g_value_object_collect_value (GValue      *value,
3643                               guint        n_collect_values,
3644                               GTypeCValue *collect_values,
3645                               guint        collect_flags)
3646 {
3647   if (collect_values[0].v_pointer)
3648     {
3649       GObject *object = collect_values[0].v_pointer;
3650       
3651       if (object->g_type_instance.g_class == NULL)
3652         return g_strconcat ("invalid unclassed object pointer for value type '",
3653                             G_VALUE_TYPE_NAME (value),
3654                             "'",
3655                             NULL);
3656       else if (!g_value_type_compatible (G_OBJECT_TYPE (object), G_VALUE_TYPE (value)))
3657         return g_strconcat ("invalid object type '",
3658                             G_OBJECT_TYPE_NAME (object),
3659                             "' for value type '",
3660                             G_VALUE_TYPE_NAME (value),
3661                             "'",
3662                             NULL);
3663       /* never honour G_VALUE_NOCOPY_CONTENTS for ref-counted types */
3664       value->data[0].v_pointer = g_object_ref (object);
3665     }
3666   else
3667     value->data[0].v_pointer = NULL;
3668   
3669   return NULL;
3670 }
3671
3672 static gchar*
3673 g_value_object_lcopy_value (const GValue *value,
3674                             guint        n_collect_values,
3675                             GTypeCValue *collect_values,
3676                             guint        collect_flags)
3677 {
3678   GObject **object_p = collect_values[0].v_pointer;
3679   
3680   if (!object_p)
3681     return g_strdup_printf ("value location for '%s' passed as NULL", G_VALUE_TYPE_NAME (value));
3682
3683   if (!value->data[0].v_pointer)
3684     *object_p = NULL;
3685   else if (collect_flags & G_VALUE_NOCOPY_CONTENTS)
3686     *object_p = value->data[0].v_pointer;
3687   else
3688     *object_p = g_object_ref (value->data[0].v_pointer);
3689   
3690   return NULL;
3691 }
3692
3693 /**
3694  * g_value_set_object:
3695  * @value: a valid #GValue of %G_TYPE_OBJECT derived type
3696  * @v_object: (type GObject.Object) (allow-none): object value to be set
3697  *
3698  * Set the contents of a %G_TYPE_OBJECT derived #GValue to @v_object.
3699  *
3700  * g_value_set_object() increases the reference count of @v_object
3701  * (the #GValue holds a reference to @v_object).  If you do not wish
3702  * to increase the reference count of the object (i.e. you wish to
3703  * pass your current reference to the #GValue because you no longer
3704  * need it), use g_value_take_object() instead.
3705  *
3706  * It is important that your #GValue holds a reference to @v_object (either its
3707  * own, or one it has taken) to ensure that the object won't be destroyed while
3708  * the #GValue still exists).
3709  */
3710 void
3711 g_value_set_object (GValue   *value,
3712                     gpointer  v_object)
3713 {
3714   GObject *old;
3715         
3716   g_return_if_fail (G_VALUE_HOLDS_OBJECT (value));
3717
3718   old = value->data[0].v_pointer;
3719   
3720   if (v_object)
3721     {
3722       g_return_if_fail (G_IS_OBJECT (v_object));
3723       g_return_if_fail (g_value_type_compatible (G_OBJECT_TYPE (v_object), G_VALUE_TYPE (value)));
3724
3725       value->data[0].v_pointer = v_object;
3726       g_object_ref (value->data[0].v_pointer);
3727     }
3728   else
3729     value->data[0].v_pointer = NULL;
3730   
3731   if (old)
3732     g_object_unref (old);
3733 }
3734
3735 /**
3736  * g_value_set_object_take_ownership: (skip)
3737  * @value: a valid #GValue of %G_TYPE_OBJECT derived type
3738  * @v_object: (allow-none): object value to be set
3739  *
3740  * This is an internal function introduced mainly for C marshallers.
3741  *
3742  * Deprecated: 2.4: Use g_value_take_object() instead.
3743  */
3744 void
3745 g_value_set_object_take_ownership (GValue  *value,
3746                                    gpointer v_object)
3747 {
3748   g_value_take_object (value, v_object);
3749 }
3750
3751 /**
3752  * g_value_take_object: (skip)
3753  * @value: a valid #GValue of %G_TYPE_OBJECT derived type
3754  * @v_object: (allow-none): object value to be set
3755  *
3756  * Sets the contents of a %G_TYPE_OBJECT derived #GValue to @v_object
3757  * and takes over the ownership of the callers reference to @v_object;
3758  * the caller doesn't have to unref it any more (i.e. the reference
3759  * count of the object is not increased).
3760  *
3761  * If you want the #GValue to hold its own reference to @v_object, use
3762  * g_value_set_object() instead.
3763  *
3764  * Since: 2.4
3765  */
3766 void
3767 g_value_take_object (GValue  *value,
3768                      gpointer v_object)
3769 {
3770   g_return_if_fail (G_VALUE_HOLDS_OBJECT (value));
3771
3772   if (value->data[0].v_pointer)
3773     {
3774       g_object_unref (value->data[0].v_pointer);
3775       value->data[0].v_pointer = NULL;
3776     }
3777
3778   if (v_object)
3779     {
3780       g_return_if_fail (G_IS_OBJECT (v_object));
3781       g_return_if_fail (g_value_type_compatible (G_OBJECT_TYPE (v_object), G_VALUE_TYPE (value)));
3782
3783       value->data[0].v_pointer = v_object; /* we take over the reference count */
3784     }
3785 }
3786
3787 /**
3788  * g_value_get_object:
3789  * @value: a valid #GValue of %G_TYPE_OBJECT derived type
3790  * 
3791  * Get the contents of a %G_TYPE_OBJECT derived #GValue.
3792  * 
3793  * Returns: (type GObject.Object) (transfer none): object contents of @value
3794  */
3795 gpointer
3796 g_value_get_object (const GValue *value)
3797 {
3798   g_return_val_if_fail (G_VALUE_HOLDS_OBJECT (value), NULL);
3799   
3800   return value->data[0].v_pointer;
3801 }
3802
3803 /**
3804  * g_value_dup_object:
3805  * @value: a valid #GValue whose type is derived from %G_TYPE_OBJECT
3806  *
3807  * Get the contents of a %G_TYPE_OBJECT derived #GValue, increasing
3808  * its reference count. If the contents of the #GValue are %NULL, then
3809  * %NULL will be returned.
3810  *
3811  * Returns: (type GObject.Object) (transfer full): object content of @value,
3812  *          should be unreferenced when no longer needed.
3813  */
3814 gpointer
3815 g_value_dup_object (const GValue *value)
3816 {
3817   g_return_val_if_fail (G_VALUE_HOLDS_OBJECT (value), NULL);
3818   
3819   return value->data[0].v_pointer ? g_object_ref (value->data[0].v_pointer) : NULL;
3820 }
3821
3822 /**
3823  * g_signal_connect_object: (skip)
3824  * @instance: the instance to connect to.
3825  * @detailed_signal: a string of the form "signal-name::detail".
3826  * @c_handler: the #GCallback to connect.
3827  * @gobject: the object to pass as data to @c_handler.
3828  * @connect_flags: a combination of #GConnectFlags.
3829  *
3830  * This is similar to g_signal_connect_data(), but uses a closure which
3831  * ensures that the @gobject stays alive during the call to @c_handler
3832  * by temporarily adding a reference count to @gobject.
3833  *
3834  * When the @gobject is destroyed the signal handler will be automatically
3835  * disconnected.  Note that this is not currently threadsafe (ie:
3836  * emitting a signal while @gobject is being destroyed in another thread
3837  * is not safe).
3838  *
3839  * Returns: the handler id.
3840  */
3841 gulong
3842 g_signal_connect_object (gpointer      instance,
3843                          const gchar  *detailed_signal,
3844                          GCallback     c_handler,
3845                          gpointer      gobject,
3846                          GConnectFlags connect_flags)
3847 {
3848   g_return_val_if_fail (G_TYPE_CHECK_INSTANCE (instance), 0);
3849   g_return_val_if_fail (detailed_signal != NULL, 0);
3850   g_return_val_if_fail (c_handler != NULL, 0);
3851
3852   if (gobject)
3853     {
3854       GClosure *closure;
3855
3856       g_return_val_if_fail (G_IS_OBJECT (gobject), 0);
3857
3858       closure = ((connect_flags & G_CONNECT_SWAPPED) ? g_cclosure_new_object_swap : g_cclosure_new_object) (c_handler, gobject);
3859
3860       return g_signal_connect_closure (instance, detailed_signal, closure, connect_flags & G_CONNECT_AFTER);
3861     }
3862   else
3863     return g_signal_connect_data (instance, detailed_signal, c_handler, NULL, NULL, connect_flags);
3864 }
3865
3866 typedef struct {
3867   GObject  *object;
3868   guint     n_closures;
3869   GClosure *closures[1]; /* flexible array */
3870 } CArray;
3871 /* don't change this structure without supplying an accessor for
3872  * watched closures, e.g.:
3873  * GSList* g_object_list_watched_closures (GObject *object)
3874  * {
3875  *   CArray *carray;
3876  *   g_return_val_if_fail (G_IS_OBJECT (object), NULL);
3877  *   carray = g_object_get_data (object, "GObject-closure-array");
3878  *   if (carray)
3879  *     {
3880  *       GSList *slist = NULL;
3881  *       guint i;
3882  *       for (i = 0; i < carray->n_closures; i++)
3883  *         slist = g_slist_prepend (slist, carray->closures[i]);
3884  *       return slist;
3885  *     }
3886  *   return NULL;
3887  * }
3888  */
3889
3890 static void
3891 object_remove_closure (gpointer  data,
3892                        GClosure *closure)
3893 {
3894   GObject *object = data;
3895   CArray *carray;
3896   guint i;
3897   
3898   G_LOCK (closure_array_mutex);
3899   carray = g_object_get_qdata (object, quark_closure_array);
3900   for (i = 0; i < carray->n_closures; i++)
3901     if (carray->closures[i] == closure)
3902       {
3903         carray->n_closures--;
3904         if (i < carray->n_closures)
3905           carray->closures[i] = carray->closures[carray->n_closures];
3906         G_UNLOCK (closure_array_mutex);
3907         return;
3908       }
3909   G_UNLOCK (closure_array_mutex);
3910   g_assert_not_reached ();
3911 }
3912
3913 static void
3914 destroy_closure_array (gpointer data)
3915 {
3916   CArray *carray = data;
3917   GObject *object = carray->object;
3918   guint i, n = carray->n_closures;
3919   
3920   for (i = 0; i < n; i++)
3921     {
3922       GClosure *closure = carray->closures[i];
3923       
3924       /* removing object_remove_closure() upfront is probably faster than
3925        * letting it fiddle with quark_closure_array which is empty anyways
3926        */
3927       g_closure_remove_invalidate_notifier (closure, object, object_remove_closure);
3928       g_closure_invalidate (closure);
3929     }
3930   g_free (carray);
3931 }
3932
3933 /**
3934  * g_object_watch_closure:
3935  * @object: GObject restricting lifetime of @closure
3936  * @closure: GClosure to watch
3937  *
3938  * This function essentially limits the life time of the @closure to
3939  * the life time of the object. That is, when the object is finalized,
3940  * the @closure is invalidated by calling g_closure_invalidate() on
3941  * it, in order to prevent invocations of the closure with a finalized
3942  * (nonexisting) object. Also, g_object_ref() and g_object_unref() are
3943  * added as marshal guards to the @closure, to ensure that an extra
3944  * reference count is held on @object during invocation of the
3945  * @closure.  Usually, this function will be called on closures that
3946  * use this @object as closure data.
3947  */
3948 void
3949 g_object_watch_closure (GObject  *object,
3950                         GClosure *closure)
3951 {
3952   CArray *carray;
3953   guint i;
3954   
3955   g_return_if_fail (G_IS_OBJECT (object));
3956   g_return_if_fail (closure != NULL);
3957   g_return_if_fail (closure->is_invalid == FALSE);
3958   g_return_if_fail (closure->in_marshal == FALSE);
3959   g_return_if_fail (object->ref_count > 0);     /* this doesn't work on finalizing objects */
3960   
3961   g_closure_add_invalidate_notifier (closure, object, object_remove_closure);
3962   g_closure_add_marshal_guards (closure,
3963                                 object, (GClosureNotify) g_object_ref,
3964                                 object, (GClosureNotify) g_object_unref);
3965   G_LOCK (closure_array_mutex);
3966   carray = g_datalist_id_remove_no_notify (&object->qdata, quark_closure_array);
3967   if (!carray)
3968     {
3969       carray = g_renew (CArray, NULL, 1);
3970       carray->object = object;
3971       carray->n_closures = 1;
3972       i = 0;
3973     }
3974   else
3975     {
3976       i = carray->n_closures++;
3977       carray = g_realloc (carray, sizeof (*carray) + sizeof (carray->closures[0]) * i);
3978     }
3979   carray->closures[i] = closure;
3980   g_datalist_id_set_data_full (&object->qdata, quark_closure_array, carray, destroy_closure_array);
3981   G_UNLOCK (closure_array_mutex);
3982 }
3983
3984 /**
3985  * g_closure_new_object:
3986  * @sizeof_closure: the size of the structure to allocate, must be at least
3987  *  <literal>sizeof (GClosure)</literal>
3988  * @object: a #GObject pointer to store in the @data field of the newly
3989  *  allocated #GClosure
3990  *
3991  * A variant of g_closure_new_simple() which stores @object in the
3992  * @data field of the closure and calls g_object_watch_closure() on
3993  * @object and the created closure. This function is mainly useful
3994  * when implementing new types of closures.
3995  *
3996  * Returns: (transfer full): a newly allocated #GClosure
3997  */
3998 GClosure*
3999 g_closure_new_object (guint    sizeof_closure,
4000                       GObject *object)
4001 {
4002   GClosure *closure;
4003
4004   g_return_val_if_fail (G_IS_OBJECT (object), NULL);
4005   g_return_val_if_fail (object->ref_count > 0, NULL);     /* this doesn't work on finalizing objects */
4006
4007   closure = g_closure_new_simple (sizeof_closure, object);
4008   g_object_watch_closure (object, closure);
4009
4010   return closure;
4011 }
4012
4013 /**
4014  * g_cclosure_new_object: (skip)
4015  * @callback_func: the function to invoke
4016  * @object: a #GObject pointer to pass to @callback_func
4017  *
4018  * A variant of g_cclosure_new() which uses @object as @user_data and
4019  * calls g_object_watch_closure() on @object and the created
4020  * closure. This function is useful when you have a callback closely
4021  * associated with a #GObject, and want the callback to no longer run
4022  * after the object is is freed.
4023  *
4024  * Returns: a new #GCClosure
4025  */
4026 GClosure*
4027 g_cclosure_new_object (GCallback callback_func,
4028                        GObject  *object)
4029 {
4030   GClosure *closure;
4031
4032   g_return_val_if_fail (G_IS_OBJECT (object), NULL);
4033   g_return_val_if_fail (object->ref_count > 0, NULL);     /* this doesn't work on finalizing objects */
4034   g_return_val_if_fail (callback_func != NULL, NULL);
4035
4036   closure = g_cclosure_new (callback_func, object, NULL);
4037   g_object_watch_closure (object, closure);
4038
4039   return closure;
4040 }
4041
4042 /**
4043  * g_cclosure_new_object_swap: (skip)
4044  * @callback_func: the function to invoke
4045  * @object: a #GObject pointer to pass to @callback_func
4046  *
4047  * A variant of g_cclosure_new_swap() which uses @object as @user_data
4048  * and calls g_object_watch_closure() on @object and the created
4049  * closure. This function is useful when you have a callback closely
4050  * associated with a #GObject, and want the callback to no longer run
4051  * after the object is is freed.
4052  *
4053  * Returns: a new #GCClosure
4054  */
4055 GClosure*
4056 g_cclosure_new_object_swap (GCallback callback_func,
4057                             GObject  *object)
4058 {
4059   GClosure *closure;
4060
4061   g_return_val_if_fail (G_IS_OBJECT (object), NULL);
4062   g_return_val_if_fail (object->ref_count > 0, NULL);     /* this doesn't work on finalizing objects */
4063   g_return_val_if_fail (callback_func != NULL, NULL);
4064
4065   closure = g_cclosure_new_swap (callback_func, object, NULL);
4066   g_object_watch_closure (object, closure);
4067
4068   return closure;
4069 }
4070
4071 gsize
4072 g_object_compat_control (gsize           what,
4073                          gpointer        data)
4074 {
4075   switch (what)
4076     {
4077       gpointer *pp;
4078     case 1:     /* floating base type */
4079       return G_TYPE_INITIALLY_UNOWNED;
4080     case 2:     /* FIXME: remove this once GLib/Gtk+ break ABI again */
4081       floating_flag_handler = (guint(*)(GObject*,gint)) data;
4082       return 1;
4083     case 3:     /* FIXME: remove this once GLib/Gtk+ break ABI again */
4084       pp = data;
4085       *pp = floating_flag_handler;
4086       return 1;
4087     default:
4088       return 0;
4089     }
4090 }
4091
4092 G_DEFINE_TYPE (GInitiallyUnowned, g_initially_unowned, G_TYPE_OBJECT);
4093
4094 static void
4095 g_initially_unowned_init (GInitiallyUnowned *object)
4096 {
4097   g_object_force_floating (object);
4098 }
4099
4100 static void
4101 g_initially_unowned_class_init (GInitiallyUnownedClass *klass)
4102 {
4103 }
4104
4105 /**
4106  * GWeakRef:
4107  *
4108  * A structure containing a weak reference to a #GObject.  It can either
4109  * be empty (i.e. point to %NULL), or point to an object for as long as
4110  * at least one "strong" reference to that object exists. Before the
4111  * object's #GObjectClass.dispose method is called, every #GWeakRef
4112  * associated with becomes empty (i.e. points to %NULL).
4113  *
4114  * Like #GValue, #GWeakRef can be statically allocated, stack- or
4115  * heap-allocated, or embedded in larger structures.
4116  *
4117  * Unlike g_object_weak_ref() and g_object_add_weak_pointer(), this weak
4118  * reference is thread-safe: converting a weak pointer to a reference is
4119  * atomic with respect to invalidation of weak pointers to destroyed
4120  * objects.
4121  *
4122  * If the object's #GObjectClass.dispose method results in additional
4123  * references to the object being held, any #GWeakRef<!-- -->s taken
4124  * before it was disposed will continue to point to %NULL.  If
4125  * #GWeakRef<!-- -->s are taken after the object is disposed and
4126  * re-referenced, they will continue to point to it until its refcount
4127  * goes back to zero, at which point they too will be invalidated.
4128  */
4129
4130 /**
4131  * g_weak_ref_init: (skip)
4132  * @weak_ref: (inout): uninitialized or empty location for a weak
4133  *    reference
4134  * @object: (allow-none): a #GObject or %NULL
4135  *
4136  * Initialise a non-statically-allocated #GWeakRef.
4137  *
4138  * This function also calls g_weak_ref_set() with @object on the
4139  * freshly-initialised weak reference.
4140  *
4141  * This function should always be matched with a call to
4142  * g_weak_ref_clear().  It is not necessary to use this function for a
4143  * #GWeakRef in static storage because it will already be
4144  * properly initialised.  Just use g_weak_ref_set() directly.
4145  *
4146  * Since: 2.32
4147  */
4148 void
4149 g_weak_ref_init (GWeakRef *weak_ref,
4150                  gpointer  object)
4151 {
4152   weak_ref->priv.p = NULL;
4153
4154   g_weak_ref_set (weak_ref, object);
4155 }
4156
4157 /**
4158  * g_weak_ref_clear: (skip)
4159  * @weak_ref: (inout): location of a weak reference, which
4160  *  may be empty
4161  *
4162  * Frees resources associated with a non-statically-allocated #GWeakRef.
4163  * After this call, the #GWeakRef is left in an undefined state.
4164  *
4165  * You should only call this on a #GWeakRef that previously had
4166  * g_weak_ref_init() called on it.
4167  *
4168  * Since: 2.32
4169  */
4170 void
4171 g_weak_ref_clear (GWeakRef *weak_ref)
4172 {
4173   g_weak_ref_set (weak_ref, NULL);
4174
4175   /* be unkind */
4176   weak_ref->priv.p = (void *) 0xccccccccu;
4177 }
4178
4179 /**
4180  * g_weak_ref_get: (skip)
4181  * @weak_ref: (inout): location of a weak reference to a #GObject
4182  *
4183  * If @weak_ref is not empty, atomically acquire a strong
4184  * reference to the object it points to, and return that reference.
4185  *
4186  * This function is needed because of the potential race between taking
4187  * the pointer value and g_object_ref() on it, if the object was losing
4188  * its last reference at the same time in a different thread.
4189  *
4190  * The caller should release the resulting reference in the usual way,
4191  * by using g_object_unref().
4192  *
4193  * Returns: (transfer full) (type GObject.Object): the object pointed to
4194  *     by @weak_ref, or %NULL if it was empty
4195  *
4196  * Since: 2.32
4197  */
4198 gpointer
4199 g_weak_ref_get (GWeakRef *weak_ref)
4200 {
4201   gpointer object_or_null;
4202
4203   g_return_val_if_fail (weak_ref!= NULL, NULL);
4204
4205   g_rw_lock_reader_lock (&weak_locations_lock);
4206
4207   object_or_null = weak_ref->priv.p;
4208
4209   if (object_or_null != NULL)
4210     g_object_ref (object_or_null);
4211
4212   g_rw_lock_reader_unlock (&weak_locations_lock);
4213
4214   return object_or_null;
4215 }
4216
4217 /**
4218  * g_weak_ref_set: (skip)
4219  * @weak_ref: location for a weak reference
4220  * @object: (allow-none): a #GObject or %NULL
4221  *
4222  * Change the object to which @weak_ref points, or set it to
4223  * %NULL.
4224  *
4225  * You must own a strong reference on @object while calling this
4226  * function.
4227  *
4228  * Since: 2.32
4229  */
4230 void
4231 g_weak_ref_set (GWeakRef *weak_ref,
4232                 gpointer  object)
4233 {
4234   GSList **weak_locations;
4235   GObject *new_object;
4236   GObject *old_object;
4237
4238   g_return_if_fail (weak_ref != NULL);
4239   g_return_if_fail (object == NULL || G_IS_OBJECT (object));
4240
4241   new_object = object;
4242
4243   g_rw_lock_writer_lock (&weak_locations_lock);
4244
4245   /* We use the extra level of indirection here so that if we have ever
4246    * had a weak pointer installed at any point in time on this object,
4247    * we can see that there is a non-NULL value associated with the
4248    * weak-pointer quark and know that this value will not change at any
4249    * point in the object's lifetime.
4250    *
4251    * Both properties are important for reducing the amount of times we
4252    * need to acquire locks and for decreasing the duration of time the
4253    * lock is held while avoiding some rather tricky races.
4254    *
4255    * Specifically: we can avoid having to do an extra unconditional lock
4256    * in g_object_unref() without worrying about some extremely tricky
4257    * races.
4258    */
4259
4260   old_object = weak_ref->priv.p;
4261   if (new_object != old_object)
4262     {
4263       weak_ref->priv.p = new_object;
4264
4265       /* Remove the weak ref from the old object */
4266       if (old_object != NULL)
4267         {
4268           weak_locations = g_datalist_id_get_data (&old_object->qdata, quark_weak_locations);
4269           /* for it to point to an object, the object must have had it added once */
4270           g_assert (weak_locations != NULL);
4271
4272           *weak_locations = g_slist_remove (*weak_locations, weak_ref);
4273         }
4274
4275       /* Add the weak ref to the new object */
4276       if (new_object != NULL)
4277         {
4278           weak_locations = g_datalist_id_get_data (&new_object->qdata, quark_weak_locations);
4279
4280           if (weak_locations == NULL)
4281             {
4282               weak_locations = g_new0 (GSList *, 1);
4283               g_datalist_id_set_data_full (&new_object->qdata, quark_weak_locations, weak_locations, g_free);
4284             }
4285
4286           *weak_locations = g_slist_prepend (*weak_locations, weak_ref);
4287         }
4288     }
4289
4290   g_rw_lock_writer_unlock (&weak_locations_lock);
4291 }