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