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