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