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