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