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