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