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