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