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