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