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