1 /* GObject - GLib Type, Object, Parameter and Signal Library
2 * Copyright (C) 1998-1999, 2000-2001 Tim Janik and Red Hat, Inc.
4 * SPDX-License-Identifier: LGPL-2.1-or-later
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2.1 of the License, or (at your option) any later version.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General
17 * Public License along with this library; if not, see <http://www.gnu.org/licenses/>.
21 * MT safe with regards to reference counting.
29 #include "../glib/glib-private.h"
32 #include "gtype-private.h"
33 #include "gvaluecollector.h"
35 #include "gparamspecs.h"
36 #include "gvaluetypes.h"
37 #include "gobject_trace.h"
38 #include "gconstructor.h"
43 * @short_description: The base object type
44 * @see_also: #GParamSpecObject, g_param_spec_object()
46 * GObject is the fundamental type providing the common attributes and
47 * methods for all object types in GTK, Pango and other libraries
48 * based on GObject. The GObject class provides methods for object
49 * construction and destruction, property access methods, and signal
50 * support. Signals are described in detail [here][gobject-Signals].
52 * For a tutorial on implementing a new GObject class, see [How to define and
53 * implement a new GObject][howto-gobject]. For a list of naming conventions for
54 * GObjects and their methods, see the [GType conventions][gtype-conventions].
55 * For the high-level concepts behind GObject, read [Instantiatable classed types:
56 * Objects][gtype-instantiatable-classed].
58 * ## Floating references # {#floating-ref}
60 * **Note**: Floating references are a C convenience API and should not be
61 * used in modern GObject code. Language bindings in particular find the
62 * concept highly problematic, as floating references are not identifiable
63 * through annotations, and neither are deviations from the floating reference
64 * behavior, like types that inherit from #GInitiallyUnowned and still return
65 * a full reference from g_object_new().
67 * GInitiallyUnowned is derived from GObject. The only difference between
68 * the two is that the initial reference of a GInitiallyUnowned is flagged
69 * as a "floating" reference. This means that it is not specifically
70 * claimed to be "owned" by any code portion. The main motivation for
71 * providing floating references is C convenience. In particular, it
72 * allows code to be written as:
74 * |[<!-- language="C" -->
75 * container = create_container ();
76 * container_add_child (container, create_child());
79 * If container_add_child() calls g_object_ref_sink() on the passed-in child,
80 * no reference of the newly created child is leaked. Without floating
81 * references, container_add_child() can only g_object_ref() the new child,
82 * so to implement this code without reference leaks, it would have to be
85 * |[<!-- language="C" -->
87 * container = create_container ();
88 * child = create_child ();
89 * container_add_child (container, child);
90 * g_object_unref (child);
93 * The floating reference can be converted into an ordinary reference by
94 * calling g_object_ref_sink(). For already sunken objects (objects that
95 * don't have a floating reference anymore), g_object_ref_sink() is equivalent
96 * to g_object_ref() and returns a new reference.
98 * Since floating references are useful almost exclusively for C convenience,
99 * language bindings that provide automated reference and memory ownership
100 * maintenance (such as smart pointers or garbage collection) should not
101 * expose floating references in their API. The best practice for handling
102 * types that have initially floating references is to immediately sink those
103 * references after g_object_new() returns, by checking if the #GType
104 * inherits from #GInitiallyUnowned. For instance:
106 * |[<!-- language="C" -->
107 * GObject *res = g_object_new_with_properties (gtype,
112 * // or: if (g_type_is_a (gtype, G_TYPE_INITIALLY_UNOWNED))
113 * if (G_IS_INITIALLY_UNOWNED (res))
114 * g_object_ref_sink (res);
119 * Some object implementations may need to save an objects floating state
120 * across certain code portions (an example is #GtkMenu), to achieve this,
121 * the following sequence can be used:
123 * |[<!-- language="C" -->
124 * // save floating state
125 * gboolean was_floating = g_object_is_floating (object);
126 * g_object_ref_sink (object);
127 * // protected code portion
131 * // restore floating state
133 * g_object_force_floating (object);
135 * g_object_unref (object); // release previously acquired reference
140 #define PARAM_SPEC_PARAM_ID(pspec) ((pspec)->param_id)
141 #define PARAM_SPEC_SET_PARAM_ID(pspec, id) ((pspec)->param_id = (id))
143 #define OBJECT_HAS_TOGGLE_REF_FLAG 0x1
144 #define OBJECT_HAS_TOGGLE_REF(object) \
145 ((g_datalist_get_flags (&(object)->qdata) & OBJECT_HAS_TOGGLE_REF_FLAG) != 0)
146 #define OBJECT_FLOATING_FLAG 0x2
148 #define CLASS_HAS_PROPS_FLAG 0x1
149 #define CLASS_HAS_PROPS(class) \
150 ((class)->flags & CLASS_HAS_PROPS_FLAG)
151 #define CLASS_HAS_CUSTOM_CONSTRUCTOR(class) \
152 ((class)->constructor != g_object_constructor)
153 #define CLASS_HAS_CUSTOM_CONSTRUCTED(class) \
154 ((class)->constructed != g_object_constructed)
155 #define CLASS_HAS_NOTIFY(class) ((class)->notify != NULL)
156 #define CLASS_HAS_CUSTOM_DISPATCH(class) \
157 ((class)->dispatch_properties_changed != g_object_dispatch_properties_changed)
158 #define CLASS_NEEDS_NOTIFY(class) \
159 (CLASS_HAS_NOTIFY(class) || CLASS_HAS_CUSTOM_DISPATCH(class))
161 #define CLASS_HAS_DERIVED_CLASS_FLAG 0x2
162 #define CLASS_HAS_DERIVED_CLASS(class) \
163 ((class)->flags & CLASS_HAS_DERIVED_CLASS_FLAG)
165 /* --- signals --- */
172 /* --- properties --- */
177 #define OPTIONAL_FLAG_IN_CONSTRUCTION (1 << 0)
178 #define OPTIONAL_FLAG_HAS_SIGNAL_HANDLER (1 << 1) /* Set if object ever had a signal handler */
179 #define OPTIONAL_FLAG_HAS_NOTIFY_HANDLER (1 << 2) /* Same, specifically for "notify" */
181 #if SIZEOF_INT == 4 && GLIB_SIZEOF_VOID_P == 8
182 #define HAVE_OPTIONAL_FLAGS
187 GTypeInstance g_type_instance;
190 guint ref_count; /* (atomic) */
191 #ifdef HAVE_OPTIONAL_FLAGS
192 guint optional_flags; /* (atomic) */
197 G_STATIC_ASSERT(sizeof(GObject) == sizeof(GObjectReal));
198 G_STATIC_ASSERT(G_STRUCT_OFFSET(GObject, ref_count) == G_STRUCT_OFFSET(GObjectReal, ref_count));
199 G_STATIC_ASSERT(G_STRUCT_OFFSET(GObject, qdata) == G_STRUCT_OFFSET(GObjectReal, qdata));
202 /* --- prototypes --- */
203 static void g_object_base_class_init (GObjectClass *class);
204 static void g_object_base_class_finalize (GObjectClass *class);
205 static void g_object_do_class_init (GObjectClass *class);
206 static void g_object_init (GObject *object,
207 GObjectClass *class);
208 static GObject* g_object_constructor (GType type,
209 guint n_construct_properties,
210 GObjectConstructParam *construct_params);
211 static void g_object_constructed (GObject *object);
212 static void g_object_real_dispose (GObject *object);
213 static void g_object_finalize (GObject *object);
214 static void g_object_do_set_property (GObject *object,
218 static void g_object_do_get_property (GObject *object,
222 static void g_value_object_init (GValue *value);
223 static void g_value_object_free_value (GValue *value);
224 static void g_value_object_copy_value (const GValue *src_value,
226 static void g_value_object_transform_value (const GValue *src_value,
228 static gpointer g_value_object_peek_pointer (const GValue *value);
229 static gchar* g_value_object_collect_value (GValue *value,
230 guint n_collect_values,
231 GTypeCValue *collect_values,
232 guint collect_flags);
233 static gchar* g_value_object_lcopy_value (const GValue *value,
234 guint n_collect_values,
235 GTypeCValue *collect_values,
236 guint collect_flags);
237 static void g_object_dispatch_properties_changed (GObject *object,
239 GParamSpec **pspecs);
240 static guint object_floating_flag_handler (GObject *object,
243 static void object_interface_check_properties (gpointer check_data,
245 static void weak_locations_free_unlocked (GSList **weak_locations);
247 /* --- typedefs --- */
248 typedef struct _GObjectNotifyQueue GObjectNotifyQueue;
250 struct _GObjectNotifyQueue
254 guint16 freeze_count;
257 /* --- variables --- */
258 G_LOCK_DEFINE_STATIC (closure_array_mutex);
259 G_LOCK_DEFINE_STATIC (weak_refs_mutex);
260 G_LOCK_DEFINE_STATIC (toggle_refs_mutex);
261 static GQuark quark_closure_array = 0;
262 static GQuark quark_weak_refs = 0;
263 static GQuark quark_toggle_refs = 0;
264 static GQuark quark_notify_queue;
265 #ifndef HAVE_OPTIONAL_FLAGS
266 static GQuark quark_in_construction;
268 static GParamSpecPool *pspec_pool = NULL;
269 static gulong gobject_signals[LAST_SIGNAL] = { 0, };
270 static guint (*floating_flag_handler) (GObject*, gint) = object_floating_flag_handler;
271 /* qdata pointing to GSList<GWeakRef *>, protected by weak_locations_lock */
272 static GQuark quark_weak_locations = 0;
273 static GRWLock weak_locations_lock;
275 G_LOCK_DEFINE_STATIC(notify_lock);
277 /* --- functions --- */
279 g_object_notify_queue_free (gpointer data)
281 GObjectNotifyQueue *nqueue = data;
283 g_slist_free (nqueue->pspecs);
284 g_slice_free (GObjectNotifyQueue, nqueue);
287 static GObjectNotifyQueue*
288 g_object_notify_queue_freeze (GObject *object,
289 gboolean conditional)
291 GObjectNotifyQueue *nqueue;
294 nqueue = g_datalist_id_get_data (&object->qdata, quark_notify_queue);
299 G_UNLOCK(notify_lock);
303 nqueue = g_slice_new0 (GObjectNotifyQueue);
304 g_datalist_id_set_data_full (&object->qdata, quark_notify_queue,
305 nqueue, g_object_notify_queue_free);
308 if (nqueue->freeze_count >= 65535)
309 g_critical("Free queue for %s (%p) is larger than 65535,"
310 " called g_object_freeze_notify() too often."
311 " Forgot to call g_object_thaw_notify() or infinite loop",
312 G_OBJECT_TYPE_NAME (object), object);
314 nqueue->freeze_count++;
316 G_UNLOCK(notify_lock);
322 g_object_notify_queue_thaw (GObject *object,
323 GObjectNotifyQueue *nqueue)
325 GParamSpec *pspecs_mem[16], **pspecs, **free_me = NULL;
331 /* Just make sure we never get into some nasty race condition */
332 if (G_UNLIKELY (nqueue->freeze_count == 0))
334 G_UNLOCK (notify_lock);
335 g_critical ("%s: property-changed notification for %s(%p) is not frozen",
336 G_STRFUNC, G_OBJECT_TYPE_NAME (object), object);
340 nqueue->freeze_count--;
341 if (nqueue->freeze_count)
343 G_UNLOCK (notify_lock);
347 pspecs = nqueue->n_pspecs > 16 ? free_me = g_new (GParamSpec*, nqueue->n_pspecs) : pspecs_mem;
349 for (slist = nqueue->pspecs; slist; slist = slist->next)
351 pspecs[n_pspecs++] = slist->data;
353 g_datalist_id_set_data (&object->qdata, quark_notify_queue, NULL);
355 G_UNLOCK(notify_lock);
358 G_OBJECT_GET_CLASS (object)->dispatch_properties_changed (object, n_pspecs, pspecs);
363 g_object_notify_queue_add (GObject *object,
364 GObjectNotifyQueue *nqueue,
369 g_assert (nqueue->n_pspecs < 65535);
371 if (g_slist_find (nqueue->pspecs, pspec) == NULL)
373 nqueue->pspecs = g_slist_prepend (nqueue->pspecs, pspec);
377 G_UNLOCK(notify_lock);
380 #ifdef G_ENABLE_DEBUG
381 G_LOCK_DEFINE_STATIC (debug_objects);
382 static guint debug_objects_count = 0;
383 static GHashTable *debug_objects_ht = NULL;
386 debug_objects_foreach (gpointer key,
390 GObject *object = value;
392 g_message ("[%p] stale %s\tref_count=%u",
394 G_OBJECT_TYPE_NAME (object),
398 #ifdef G_HAS_CONSTRUCTORS
399 #ifdef G_DEFINE_DESTRUCTOR_NEEDS_PRAGMA
400 #pragma G_DEFINE_DESTRUCTOR_PRAGMA_ARGS(debug_objects_atexit)
402 G_DEFINE_DESTRUCTOR(debug_objects_atexit)
403 #endif /* G_HAS_CONSTRUCTORS */
406 debug_objects_atexit (void)
408 GOBJECT_IF_DEBUG (OBJECTS,
410 G_LOCK (debug_objects);
411 g_message ("stale GObjects: %u", debug_objects_count);
412 g_hash_table_foreach (debug_objects_ht, debug_objects_foreach, NULL);
413 G_UNLOCK (debug_objects);
416 #endif /* G_ENABLE_DEBUG */
419 _g_object_type_init (void)
421 static gboolean initialized = FALSE;
422 static const GTypeFundamentalInfo finfo = {
423 G_TYPE_FLAG_CLASSED | G_TYPE_FLAG_INSTANTIATABLE | G_TYPE_FLAG_DERIVABLE | G_TYPE_FLAG_DEEP_DERIVABLE,
426 sizeof (GObjectClass),
427 (GBaseInitFunc) g_object_base_class_init,
428 (GBaseFinalizeFunc) g_object_base_class_finalize,
429 (GClassInitFunc) g_object_do_class_init,
430 NULL /* class_destroy */,
431 NULL /* class_data */,
434 (GInstanceInitFunc) g_object_init,
435 NULL, /* value_table */
437 static const GTypeValueTable value_table = {
438 g_value_object_init, /* value_init */
439 g_value_object_free_value, /* value_free */
440 g_value_object_copy_value, /* value_copy */
441 g_value_object_peek_pointer, /* value_peek_pointer */
442 "p", /* collect_format */
443 g_value_object_collect_value, /* collect_value */
444 "p", /* lcopy_format */
445 g_value_object_lcopy_value, /* lcopy_value */
447 GType type G_GNUC_UNUSED /* when compiling with G_DISABLE_ASSERT */;
449 g_return_if_fail (initialized == FALSE);
454 info.value_table = &value_table;
455 type = g_type_register_fundamental (G_TYPE_OBJECT, g_intern_static_string ("GObject"), &info, &finfo, 0);
456 g_assert (type == G_TYPE_OBJECT);
457 g_value_register_transform_func (G_TYPE_OBJECT, G_TYPE_OBJECT, g_value_object_transform_value);
460 /* We cannot use GOBJECT_IF_DEBUG here because of the G_HAS_CONSTRUCTORS
461 * conditional in between, as the C spec leaves conditionals inside macro
462 * expansions as undefined behavior. Only GCC and Clang are known to work
463 * but compilation breaks on MSVC.
465 * See: https://bugzilla.gnome.org/show_bug.cgi?id=769504
467 if (_g_type_debug_flags & G_TYPE_DEBUG_OBJECTS) \
469 debug_objects_ht = g_hash_table_new (g_direct_hash, NULL);
470 # ifndef G_HAS_CONSTRUCTORS
471 g_atexit (debug_objects_atexit);
472 # endif /* G_HAS_CONSTRUCTORS */
474 #endif /* G_ENABLE_DEBUG */
478 g_object_base_class_init (GObjectClass *class)
480 GObjectClass *pclass = g_type_class_peek_parent (class);
482 /* Don't inherit HAS_DERIVED_CLASS flag from parent class */
483 class->flags &= ~CLASS_HAS_DERIVED_CLASS_FLAG;
486 pclass->flags |= CLASS_HAS_DERIVED_CLASS_FLAG;
488 /* reset instance specific fields and methods that don't get inherited */
489 class->construct_properties = pclass ? g_slist_copy (pclass->construct_properties) : NULL;
490 class->n_construct_properties = g_slist_length (class->construct_properties);
491 class->get_property = NULL;
492 class->set_property = NULL;
493 class->pspecs = NULL;
498 g_object_base_class_finalize (GObjectClass *class)
502 _g_signals_destroy (G_OBJECT_CLASS_TYPE (class));
504 g_slist_free (class->construct_properties);
505 class->construct_properties = NULL;
506 class->n_construct_properties = 0;
507 list = g_param_spec_pool_list_owned (pspec_pool, G_OBJECT_CLASS_TYPE (class));
508 for (node = list; node; node = node->next)
510 GParamSpec *pspec = node->data;
512 g_param_spec_pool_remove (pspec_pool, pspec);
513 PARAM_SPEC_SET_PARAM_ID (pspec, 0);
514 g_param_spec_unref (pspec);
520 g_object_do_class_init (GObjectClass *class)
522 /* read the comment about typedef struct CArray; on why not to change this quark */
523 quark_closure_array = g_quark_from_static_string ("GObject-closure-array");
525 quark_weak_refs = g_quark_from_static_string ("GObject-weak-references");
526 quark_weak_locations = g_quark_from_static_string ("GObject-weak-locations");
527 quark_toggle_refs = g_quark_from_static_string ("GObject-toggle-references");
528 quark_notify_queue = g_quark_from_static_string ("GObject-notify-queue");
529 #ifndef HAVE_OPTIONAL_FLAGS
530 quark_in_construction = g_quark_from_static_string ("GObject-in-construction");
532 pspec_pool = g_param_spec_pool_new (TRUE);
534 class->constructor = g_object_constructor;
535 class->constructed = g_object_constructed;
536 class->set_property = g_object_do_set_property;
537 class->get_property = g_object_do_get_property;
538 class->dispose = g_object_real_dispose;
539 class->finalize = g_object_finalize;
540 class->dispatch_properties_changed = g_object_dispatch_properties_changed;
541 class->notify = NULL;
545 * @gobject: the object which received the signal.
546 * @pspec: the #GParamSpec of the property which changed.
548 * The notify signal is emitted on an object when one of its properties has
549 * its value set through g_object_set_property(), g_object_set(), et al.
551 * Note that getting this signal doesn’t itself guarantee that the value of
552 * the property has actually changed. When it is emitted is determined by the
553 * derived GObject class. If the implementor did not create the property with
554 * %G_PARAM_EXPLICIT_NOTIFY, then any call to g_object_set_property() results
555 * in ::notify being emitted, even if the new value is the same as the old.
556 * If they did pass %G_PARAM_EXPLICIT_NOTIFY, then this signal is emitted only
557 * when they explicitly call g_object_notify() or g_object_notify_by_pspec(),
558 * and common practice is to do that only when the value has actually changed.
560 * This signal is typically used to obtain change notification for a
561 * single property, by specifying the property name as a detail in the
562 * g_signal_connect() call, like this:
564 * |[<!-- language="C" -->
565 * g_signal_connect (text_view->buffer, "notify::paste-target-list",
566 * G_CALLBACK (gtk_text_view_target_list_notify),
570 * It is important to note that you must use
571 * [canonical parameter names][canonical-parameter-names] as
572 * detail strings for the notify signal.
574 gobject_signals[NOTIFY] =
575 g_signal_new (g_intern_static_string ("notify"),
576 G_TYPE_FROM_CLASS (class),
577 G_SIGNAL_RUN_FIRST | G_SIGNAL_NO_RECURSE | G_SIGNAL_DETAILED | G_SIGNAL_NO_HOOKS | G_SIGNAL_ACTION,
578 G_STRUCT_OFFSET (GObjectClass, notify),
584 /* Install a check function that we'll use to verify that classes that
585 * implement an interface implement all properties for that interface
587 g_type_add_interface_check (NULL, object_interface_check_properties);
590 /* Sinks @pspec if it’s a floating ref. */
591 static inline gboolean
592 install_property_internal (GType g_type,
596 g_param_spec_ref_sink (pspec);
598 if (g_param_spec_pool_lookup (pspec_pool, pspec->name, g_type, FALSE))
600 g_critical ("When installing property: type '%s' already has a property named '%s'",
601 g_type_name (g_type),
603 g_param_spec_unref (pspec);
607 PARAM_SPEC_SET_PARAM_ID (pspec, property_id);
608 g_param_spec_pool_insert (pspec_pool, g_steal_pointer (&pspec), g_type);
613 validate_pspec_to_install (GParamSpec *pspec)
615 g_return_val_if_fail (G_IS_PARAM_SPEC (pspec), FALSE);
616 g_return_val_if_fail (PARAM_SPEC_PARAM_ID (pspec) == 0, FALSE); /* paranoid */
618 g_return_val_if_fail (pspec->flags & (G_PARAM_READABLE | G_PARAM_WRITABLE), FALSE);
620 if (pspec->flags & G_PARAM_CONSTRUCT)
621 g_return_val_if_fail ((pspec->flags & G_PARAM_CONSTRUCT_ONLY) == 0, FALSE);
623 if (pspec->flags & (G_PARAM_CONSTRUCT | G_PARAM_CONSTRUCT_ONLY))
624 g_return_val_if_fail (pspec->flags & G_PARAM_WRITABLE, FALSE);
629 /* Sinks @pspec if it’s a floating ref. */
631 validate_and_install_class_property (GObjectClass *class,
637 if (!validate_pspec_to_install (pspec))
639 g_param_spec_ref_sink (pspec);
640 g_param_spec_unref (pspec);
644 if (pspec->flags & G_PARAM_WRITABLE)
645 g_return_val_if_fail (class->set_property != NULL, FALSE);
646 if (pspec->flags & G_PARAM_READABLE)
647 g_return_val_if_fail (class->get_property != NULL, FALSE);
649 class->flags |= CLASS_HAS_PROPS_FLAG;
650 if (install_property_internal (oclass_type, property_id, pspec))
652 if (pspec->flags & (G_PARAM_CONSTRUCT | G_PARAM_CONSTRUCT_ONLY))
654 class->construct_properties = g_slist_append (class->construct_properties, pspec);
655 class->n_construct_properties += 1;
658 /* for property overrides of construct properties, we have to get rid
659 * of the overridden inherited construct property
661 pspec = g_param_spec_pool_lookup (pspec_pool, pspec->name, parent_type, TRUE);
662 if (pspec && pspec->flags & (G_PARAM_CONSTRUCT | G_PARAM_CONSTRUCT_ONLY))
664 class->construct_properties = g_slist_remove (class->construct_properties, pspec);
665 class->n_construct_properties -= 1;
675 * g_object_class_install_property:
676 * @oclass: a #GObjectClass
677 * @property_id: the id for the new property
678 * @pspec: the #GParamSpec for the new property
680 * Installs a new property.
682 * All properties should be installed during the class initializer. It
683 * is possible to install properties after that, but doing so is not
684 * recommend, and specifically, is not guaranteed to be thread-safe vs.
685 * use of properties on the same type on other threads.
687 * Note that it is possible to redefine a property in a derived class,
688 * by installing a property with the same name. This can be useful at times,
689 * e.g. to change the range of allowed values or the default value.
692 g_object_class_install_property (GObjectClass *class,
696 GType oclass_type, parent_type;
698 g_return_if_fail (G_IS_OBJECT_CLASS (class));
699 g_return_if_fail (property_id > 0);
701 oclass_type = G_OBJECT_CLASS_TYPE (class);
702 parent_type = g_type_parent (oclass_type);
704 if (CLASS_HAS_DERIVED_CLASS (class))
705 g_error ("Attempt to add property %s::%s to class after it was derived", G_OBJECT_CLASS_NAME (class), pspec->name);
707 (void) validate_and_install_class_property (class,
720 compare_pspec_entry (const void *a,
723 const PspecEntry *ae = a;
724 const PspecEntry *be = b;
726 return ae->name < be->name ? -1 : (ae->name > be->name ? 1 : 0);
729 /* This uses pointer comparisons with @property_name, so
730 * will only work with string literals. */
731 static inline GParamSpec *
732 find_pspec (GObjectClass *class,
733 const char *property_name)
735 const PspecEntry *pspecs = (const PspecEntry *)class->pspecs;
736 gsize n_pspecs = class->n_pspecs;
738 g_assert (n_pspecs <= G_MAXSSIZE);
740 /* The limit for choosing between linear and binary search is
743 * Both searches use pointer comparisons against @property_name.
744 * If this function is called with a non-static @property_name,
745 * it will fall through to the g_param_spec_pool_lookup() case.
746 * That’s OK; this is an opportunistic optimisation which relies
747 * on the fact that *most* (but not all) property lookups use
748 * static property names.
752 for (gsize i = 0; i < n_pspecs; i++)
754 if (pspecs[i].name == property_name)
755 return pspecs[i].pspec;
761 gssize upper = (int)class->n_pspecs - 1;
764 while (lower <= upper)
766 mid = (lower + upper) / 2;
768 if (property_name < pspecs[mid].name)
770 else if (property_name > pspecs[mid].name)
773 return pspecs[mid].pspec;
777 return g_param_spec_pool_lookup (pspec_pool,
779 ((GTypeClass *)class)->g_type,
784 * g_object_class_install_properties:
785 * @oclass: a #GObjectClass
786 * @n_pspecs: the length of the #GParamSpecs array
787 * @pspecs: (array length=n_pspecs): the #GParamSpecs array
788 * defining the new properties
790 * Installs new properties from an array of #GParamSpecs.
792 * All properties should be installed during the class initializer. It
793 * is possible to install properties after that, but doing so is not
794 * recommend, and specifically, is not guaranteed to be thread-safe vs.
795 * use of properties on the same type on other threads.
797 * The property id of each property is the index of each #GParamSpec in
800 * The property id of 0 is treated specially by #GObject and it should not
801 * be used to store a #GParamSpec.
803 * This function should be used if you plan to use a static array of
804 * #GParamSpecs and g_object_notify_by_pspec(). For instance, this
805 * class initialization:
807 * |[<!-- language="C" -->
812 * } MyObjectProperty;
814 * static GParamSpec *obj_properties[N_PROPERTIES] = { NULL, };
817 * my_object_class_init (MyObjectClass *klass)
819 * GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
821 * obj_properties[PROP_FOO] =
822 * g_param_spec_int ("foo", "Foo", "Foo",
825 * G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS);
827 * obj_properties[PROP_BAR] =
828 * g_param_spec_string ("bar", "Bar", "Bar",
830 * G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS);
832 * gobject_class->set_property = my_object_set_property;
833 * gobject_class->get_property = my_object_get_property;
834 * g_object_class_install_properties (gobject_class,
835 * G_N_ELEMENTS (obj_properties),
840 * allows calling g_object_notify_by_pspec() to notify of property changes:
842 * |[<!-- language="C" -->
844 * my_object_set_foo (MyObject *self, gint foo)
846 * if (self->foo != foo)
849 * g_object_notify_by_pspec (G_OBJECT (self), obj_properties[PROP_FOO]);
857 g_object_class_install_properties (GObjectClass *oclass,
861 GType oclass_type, parent_type;
864 g_return_if_fail (G_IS_OBJECT_CLASS (oclass));
865 g_return_if_fail (n_pspecs > 1);
866 g_return_if_fail (pspecs[0] == NULL);
868 if (CLASS_HAS_DERIVED_CLASS (oclass))
869 g_error ("Attempt to add properties to %s after it was derived",
870 G_OBJECT_CLASS_NAME (oclass));
872 oclass_type = G_OBJECT_CLASS_TYPE (oclass);
873 parent_type = g_type_parent (oclass_type);
875 /* we skip the first element of the array as it would have a 0 prop_id */
876 for (i = 1; i < n_pspecs; i++)
878 GParamSpec *pspec = pspecs[i];
880 if (!validate_and_install_class_property (oclass,
890 /* Save a copy of the pspec array inside the class struct. This
891 * makes it faster to look up pspecs for the class in future when
892 * acting on those properties.
894 * If a pspec is not in this cache array, calling code will fall
895 * back to using g_param_spec_pool_lookup(), so a pspec not being
896 * in this array is a (potential) performance problem but not a
897 * correctness problem. */
898 if (oclass->pspecs == NULL)
902 entries = g_new (PspecEntry, n_pspecs - 1);
904 for (i = 1; i < n_pspecs; i++)
906 entries[i - 1].name = pspecs[i]->name;
907 entries[i - 1].pspec = pspecs[i];
910 qsort (entries, n_pspecs - 1, sizeof (PspecEntry), compare_pspec_entry);
912 oclass->pspecs = entries;
913 oclass->n_pspecs = n_pspecs - 1;
918 * g_object_interface_install_property:
919 * @g_iface: (type GObject.TypeInterface): any interface vtable for the
920 * interface, or the default
921 * vtable for the interface.
922 * @pspec: the #GParamSpec for the new property
924 * Add a property to an interface; this is only useful for interfaces
925 * that are added to GObject-derived types. Adding a property to an
926 * interface forces all objects classes with that interface to have a
927 * compatible property. The compatible property could be a newly
928 * created #GParamSpec, but normally
929 * g_object_class_override_property() will be used so that the object
930 * class only needs to provide an implementation and inherits the
931 * property description, default value, bounds, and so forth from the
932 * interface property.
934 * This function is meant to be called from the interface's default
935 * vtable initialization function (the @class_init member of
936 * #GTypeInfo.) It must not be called after after @class_init has
937 * been called for any object types implementing this interface.
939 * If @pspec is a floating reference, it will be consumed.
944 g_object_interface_install_property (gpointer g_iface,
947 GTypeInterface *iface_class = g_iface;
949 g_return_if_fail (G_TYPE_IS_INTERFACE (iface_class->g_type));
950 g_return_if_fail (!G_IS_PARAM_SPEC_OVERRIDE (pspec)); /* paranoid */
952 if (!validate_pspec_to_install (pspec))
954 g_param_spec_ref_sink (pspec);
955 g_param_spec_unref (pspec);
959 (void) install_property_internal (iface_class->g_type, 0, pspec);
962 /* Inlined version of g_param_spec_get_redirect_target(), for speed */
964 param_spec_follow_override (GParamSpec **pspec)
966 if (((GTypeInstance *) (*pspec))->g_class->g_type == G_TYPE_PARAM_OVERRIDE)
967 *pspec = ((GParamSpecOverride *) (*pspec))->overridden;
971 * g_object_class_find_property:
972 * @oclass: a #GObjectClass
973 * @property_name: the name of the property to look up
975 * Looks up the #GParamSpec for a property of a class.
977 * Returns: (transfer none): the #GParamSpec for the property, or
978 * %NULL if the class doesn't have a property of that name
981 g_object_class_find_property (GObjectClass *class,
982 const gchar *property_name)
986 g_return_val_if_fail (G_IS_OBJECT_CLASS (class), NULL);
987 g_return_val_if_fail (property_name != NULL, NULL);
989 pspec = find_pspec (class, property_name);
992 param_spec_follow_override (&pspec);
998 * g_object_interface_find_property:
999 * @g_iface: (type GObject.TypeInterface): any interface vtable for the
1000 * interface, or the default vtable for the interface
1001 * @property_name: name of a property to look up.
1003 * Find the #GParamSpec with the given name for an
1004 * interface. Generally, the interface vtable passed in as @g_iface
1005 * will be the default vtable from g_type_default_interface_ref(), or,
1006 * if you know the interface has already been loaded,
1007 * g_type_default_interface_peek().
1011 * Returns: (transfer none): the #GParamSpec for the property of the
1012 * interface with the name @property_name, or %NULL if no
1013 * such property exists.
1016 g_object_interface_find_property (gpointer g_iface,
1017 const gchar *property_name)
1019 GTypeInterface *iface_class = g_iface;
1021 g_return_val_if_fail (G_TYPE_IS_INTERFACE (iface_class->g_type), NULL);
1022 g_return_val_if_fail (property_name != NULL, NULL);
1024 return g_param_spec_pool_lookup (pspec_pool,
1026 iface_class->g_type,
1031 * g_object_class_override_property:
1032 * @oclass: a #GObjectClass
1033 * @property_id: the new property ID
1034 * @name: the name of a property registered in a parent class or
1035 * in an interface of this class.
1037 * Registers @property_id as referring to a property with the name
1038 * @name in a parent class or in an interface implemented by @oclass.
1039 * This allows this class to "override" a property implementation in
1040 * a parent class or to provide the implementation of a property from
1043 * Internally, overriding is implemented by creating a property of type
1044 * #GParamSpecOverride; generally operations that query the properties of
1045 * the object class, such as g_object_class_find_property() or
1046 * g_object_class_list_properties() will return the overridden
1047 * property. However, in one case, the @construct_properties argument of
1048 * the @constructor virtual function, the #GParamSpecOverride is passed
1049 * instead, so that the @param_id field of the #GParamSpec will be
1050 * correct. For virtually all uses, this makes no difference. If you
1051 * need to get the overridden property, you can call
1052 * g_param_spec_get_redirect_target().
1057 g_object_class_override_property (GObjectClass *oclass,
1061 GParamSpec *overridden = NULL;
1065 g_return_if_fail (G_IS_OBJECT_CLASS (oclass));
1066 g_return_if_fail (property_id > 0);
1067 g_return_if_fail (name != NULL);
1069 /* Find the overridden property; first check parent types
1071 parent_type = g_type_parent (G_OBJECT_CLASS_TYPE (oclass));
1072 if (parent_type != G_TYPE_NONE)
1073 overridden = g_param_spec_pool_lookup (pspec_pool,
1082 /* Now check interfaces
1084 ifaces = g_type_interfaces (G_OBJECT_CLASS_TYPE (oclass), &n_ifaces);
1085 while (n_ifaces-- && !overridden)
1087 overridden = g_param_spec_pool_lookup (pspec_pool,
1098 g_critical ("%s: Can't find property to override for '%s::%s'",
1099 G_STRFUNC, G_OBJECT_CLASS_NAME (oclass), name);
1103 new = g_param_spec_override (name, overridden);
1104 g_object_class_install_property (oclass, property_id, new);
1108 * g_object_class_list_properties:
1109 * @oclass: a #GObjectClass
1110 * @n_properties: (out): return location for the length of the returned array
1112 * Get an array of #GParamSpec* for all properties of a class.
1114 * Returns: (array length=n_properties) (transfer container): an array of
1115 * #GParamSpec* which should be freed after use
1117 GParamSpec** /* free result */
1118 g_object_class_list_properties (GObjectClass *class,
1119 guint *n_properties_p)
1121 GParamSpec **pspecs;
1124 g_return_val_if_fail (G_IS_OBJECT_CLASS (class), NULL);
1126 pspecs = g_param_spec_pool_list (pspec_pool,
1127 G_OBJECT_CLASS_TYPE (class),
1130 *n_properties_p = n;
1136 * g_object_interface_list_properties:
1137 * @g_iface: (type GObject.TypeInterface): any interface vtable for the
1138 * interface, or the default vtable for the interface
1139 * @n_properties_p: (out): location to store number of properties returned.
1141 * Lists the properties of an interface.Generally, the interface
1142 * vtable passed in as @g_iface will be the default vtable from
1143 * g_type_default_interface_ref(), or, if you know the interface has
1144 * already been loaded, g_type_default_interface_peek().
1148 * Returns: (array length=n_properties_p) (transfer container): a
1149 * pointer to an array of pointers to #GParamSpec
1150 * structures. The paramspecs are owned by GLib, but the
1151 * array should be freed with g_free() when you are done with
1155 g_object_interface_list_properties (gpointer g_iface,
1156 guint *n_properties_p)
1158 GTypeInterface *iface_class = g_iface;
1159 GParamSpec **pspecs;
1162 g_return_val_if_fail (G_TYPE_IS_INTERFACE (iface_class->g_type), NULL);
1164 pspecs = g_param_spec_pool_list (pspec_pool,
1165 iface_class->g_type,
1168 *n_properties_p = n;
1174 object_get_optional_flags (GObject *object)
1176 #ifdef HAVE_OPTIONAL_FLAGS
1177 GObjectReal *real = (GObjectReal *)object;
1178 return (guint)g_atomic_int_get (&real->optional_flags);
1184 /* Variant of object_get_optional_flags for when
1185 * we know that we have exclusive access (during
1189 object_get_optional_flags_X (GObject *object)
1191 #ifdef HAVE_OPTIONAL_FLAGS
1192 GObjectReal *real = (GObjectReal *)object;
1193 return real->optional_flags;
1199 #ifdef HAVE_OPTIONAL_FLAGS
1201 object_set_optional_flags (GObject *object,
1204 GObjectReal *real = (GObjectReal *)object;
1205 g_atomic_int_or (&real->optional_flags, flags);
1208 /* Variant for when we have exclusive access
1209 * (during construction)
1212 object_set_optional_flags_X (GObject *object,
1215 GObjectReal *real = (GObjectReal *)object;
1216 real->optional_flags |= flags;
1219 /* Variant for when we have exclusive access
1220 * (during construction)
1223 object_unset_optional_flags_X (GObject *object,
1226 GObjectReal *real = (GObjectReal *)object;
1227 real->optional_flags &= ~flags;
1232 _g_object_has_signal_handler (GObject *object)
1234 #ifdef HAVE_OPTIONAL_FLAGS
1235 return (object_get_optional_flags (object) & OPTIONAL_FLAG_HAS_SIGNAL_HANDLER) != 0;
1241 static inline gboolean
1242 _g_object_has_notify_handler (GObject *object)
1244 #ifdef HAVE_OPTIONAL_FLAGS
1245 return CLASS_NEEDS_NOTIFY (G_OBJECT_GET_CLASS (object)) ||
1246 (object_get_optional_flags (object) & OPTIONAL_FLAG_HAS_NOTIFY_HANDLER) != 0;
1252 static inline gboolean
1253 _g_object_has_notify_handler_X (GObject *object)
1255 #ifdef HAVE_OPTIONAL_FLAGS
1256 return CLASS_NEEDS_NOTIFY (G_OBJECT_GET_CLASS (object)) ||
1257 (object_get_optional_flags_X (object) & OPTIONAL_FLAG_HAS_NOTIFY_HANDLER) != 0;
1264 _g_object_set_has_signal_handler (GObject *object,
1267 #ifdef HAVE_OPTIONAL_FLAGS
1268 guint flags = OPTIONAL_FLAG_HAS_SIGNAL_HANDLER;
1269 if (signal_id == gobject_signals[NOTIFY])
1270 flags |= OPTIONAL_FLAG_HAS_NOTIFY_HANDLER;
1271 object_set_optional_flags (object, flags);
1275 static inline gboolean
1276 object_in_construction (GObject *object)
1278 #ifdef HAVE_OPTIONAL_FLAGS
1279 return (object_get_optional_flags (object) & OPTIONAL_FLAG_IN_CONSTRUCTION) != 0;
1281 return g_datalist_id_get_data (&object->qdata, quark_in_construction) != NULL;
1286 set_object_in_construction (GObject *object)
1288 #ifdef HAVE_OPTIONAL_FLAGS
1289 object_set_optional_flags_X (object, OPTIONAL_FLAG_IN_CONSTRUCTION);
1291 g_datalist_id_set_data (&object->qdata, quark_in_construction, object);
1296 unset_object_in_construction (GObject *object)
1298 #ifdef HAVE_OPTIONAL_FLAGS
1299 object_unset_optional_flags_X (object, OPTIONAL_FLAG_IN_CONSTRUCTION);
1301 g_datalist_id_set_data (&object->qdata, quark_in_construction, NULL);
1306 g_object_init (GObject *object,
1307 GObjectClass *class)
1309 object->ref_count = 1;
1310 object->qdata = NULL;
1312 if (CLASS_HAS_PROPS (class) && CLASS_NEEDS_NOTIFY (class))
1314 /* freeze object's notification queue, g_object_new_internal() preserves pairedness */
1315 g_object_notify_queue_freeze (object, FALSE);
1318 /* mark object in-construction for notify_queue_thaw() and to allow construct-only properties */
1319 set_object_in_construction (object);
1321 GOBJECT_IF_DEBUG (OBJECTS,
1323 G_LOCK (debug_objects);
1324 debug_objects_count++;
1325 g_hash_table_add (debug_objects_ht, object);
1326 G_UNLOCK (debug_objects);
1331 g_object_do_set_property (GObject *object,
1333 const GValue *value,
1336 switch (property_id)
1339 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec);
1345 g_object_do_get_property (GObject *object,
1350 switch (property_id)
1353 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec);
1359 g_object_real_dispose (GObject *object)
1361 g_signal_handlers_destroy (object);
1362 g_datalist_id_set_data (&object->qdata, quark_closure_array, NULL);
1363 g_datalist_id_set_data (&object->qdata, quark_weak_refs, NULL);
1364 g_datalist_id_set_data (&object->qdata, quark_weak_locations, NULL);
1367 #ifdef G_ENABLE_DEBUG
1369 floating_check (GObject *object)
1371 static const char *g_enable_diagnostic = NULL;
1373 if (G_UNLIKELY (g_enable_diagnostic == NULL))
1375 g_enable_diagnostic = g_getenv ("G_ENABLE_DIAGNOSTIC");
1376 if (g_enable_diagnostic == NULL)
1377 g_enable_diagnostic = "0";
1380 if (g_enable_diagnostic[0] == '1')
1381 return g_object_is_floating (object);
1388 g_object_finalize (GObject *object)
1390 #ifdef G_ENABLE_DEBUG
1391 if (object_in_construction (object))
1393 g_critical ("object %s %p finalized while still in-construction",
1394 G_OBJECT_TYPE_NAME (object), object);
1397 if (floating_check (object))
1399 g_critical ("A floating object %s %p was finalized. This means that someone\n"
1400 "called g_object_unref() on an object that had only a floating\n"
1401 "reference; the initial floating reference is not owned by anyone\n"
1402 "and must be removed with g_object_ref_sink().",
1403 G_OBJECT_TYPE_NAME (object), object);
1407 g_datalist_clear (&object->qdata);
1409 GOBJECT_IF_DEBUG (OBJECTS,
1411 G_LOCK (debug_objects);
1412 g_assert (g_hash_table_contains (debug_objects_ht, object));
1413 g_hash_table_remove (debug_objects_ht, object);
1414 debug_objects_count--;
1415 G_UNLOCK (debug_objects);
1420 g_object_dispatch_properties_changed (GObject *object,
1422 GParamSpec **pspecs)
1426 for (i = 0; i < n_pspecs; i++)
1427 g_signal_emit (object, gobject_signals[NOTIFY], g_param_spec_get_name_quark (pspecs[i]), pspecs[i]);
1431 * g_object_run_dispose:
1432 * @object: a #GObject
1434 * Releases all references to other objects. This can be used to break
1437 * This function should only be called from object system implementations.
1440 g_object_run_dispose (GObject *object)
1442 g_return_if_fail (G_IS_OBJECT (object));
1443 g_return_if_fail (g_atomic_int_get (&object->ref_count) > 0);
1445 g_object_ref (object);
1446 TRACE (GOBJECT_OBJECT_DISPOSE(object,G_TYPE_FROM_INSTANCE(object), 0));
1447 G_OBJECT_GET_CLASS (object)->dispose (object);
1448 TRACE (GOBJECT_OBJECT_DISPOSE_END(object,G_TYPE_FROM_INSTANCE(object), 0));
1449 g_object_unref (object);
1453 * g_object_freeze_notify:
1454 * @object: a #GObject
1456 * Increases the freeze count on @object. If the freeze count is
1457 * non-zero, the emission of "notify" signals on @object is
1458 * stopped. The signals are queued until the freeze count is decreased
1459 * to zero. Duplicate notifications are squashed so that at most one
1460 * #GObject::notify signal is emitted for each property modified while the
1463 * This is necessary for accessors that modify multiple properties to prevent
1464 * premature notification while the object is still being modified.
1467 g_object_freeze_notify (GObject *object)
1469 g_return_if_fail (G_IS_OBJECT (object));
1471 #ifndef G_DISABLE_CHECKS
1472 if (G_UNLIKELY (g_atomic_int_get (&object->ref_count) == 0))
1474 g_critical ("Attempting to freeze the notification queue for object %s[%p]; "
1475 "Property notification does not work during instance finalization.",
1476 G_OBJECT_TYPE_NAME (object),
1482 g_object_ref (object);
1483 g_object_notify_queue_freeze (object, FALSE);
1484 g_object_unref (object);
1488 g_object_notify_by_spec_internal (GObject *object,
1491 #ifdef HAVE_OPTIONAL_FLAGS
1494 gboolean needs_notify;
1497 if (G_UNLIKELY (~pspec->flags & G_PARAM_READABLE))
1500 param_spec_follow_override (&pspec);
1502 #ifdef HAVE_OPTIONAL_FLAGS
1503 /* get all flags we need with a single atomic read */
1504 object_flags = object_get_optional_flags (object);
1505 needs_notify = ((object_flags & OPTIONAL_FLAG_HAS_NOTIFY_HANDLER) != 0) ||
1506 CLASS_NEEDS_NOTIFY (G_OBJECT_GET_CLASS (object));
1507 in_init = (object_flags & OPTIONAL_FLAG_IN_CONSTRUCTION) != 0;
1509 needs_notify = TRUE;
1510 in_init = object_in_construction (object);
1513 if (pspec != NULL && needs_notify)
1515 GObjectNotifyQueue *nqueue;
1516 gboolean need_thaw = TRUE;
1518 /* conditional freeze: only increase freeze count if already frozen */
1519 nqueue = g_object_notify_queue_freeze (object, TRUE);
1520 if (in_init && !nqueue)
1522 /* We did not freeze the queue in g_object_init, but
1523 * we gained a notify handler in instance init, so
1524 * now we need to freeze just-in-time
1526 nqueue = g_object_notify_queue_freeze (object, FALSE);
1532 /* we're frozen, so add to the queue and release our freeze */
1533 g_object_notify_queue_add (object, nqueue, pspec);
1535 g_object_notify_queue_thaw (object, nqueue);
1540 * Coverity doesn’t understand the paired ref/unref here and seems to
1541 * ignore the ref, thus reports every call to g_object_notify() as
1542 * causing a double-free. That’s incorrect, but I can’t get a model
1543 * file to work for avoiding the false positives, so instead comment
1544 * out the ref/unref when doing static analysis.
1546 #ifndef __COVERITY__
1547 g_object_ref (object);
1550 /* not frozen, so just dispatch the notification directly */
1551 G_OBJECT_GET_CLASS (object)
1552 ->dispatch_properties_changed (object, 1, &pspec);
1554 #ifndef __COVERITY__
1555 g_object_unref (object);
1563 * @object: a #GObject
1564 * @property_name: the name of a property installed on the class of @object.
1566 * Emits a "notify" signal for the property @property_name on @object.
1568 * When possible, eg. when signaling a property change from within the class
1569 * that registered the property, you should use g_object_notify_by_pspec()
1572 * Note that emission of the notify signal may be blocked with
1573 * g_object_freeze_notify(). In this case, the signal emissions are queued
1574 * and will be emitted (in reverse order) when g_object_thaw_notify() is
1578 g_object_notify (GObject *object,
1579 const gchar *property_name)
1583 g_return_if_fail (G_IS_OBJECT (object));
1584 g_return_if_fail (property_name != NULL);
1586 /* We don't need to get the redirect target
1587 * (by, e.g. calling g_object_class_find_property())
1588 * because g_object_notify_queue_add() does that
1590 pspec = g_param_spec_pool_lookup (pspec_pool,
1592 G_OBJECT_TYPE (object),
1596 g_critical ("%s: object class '%s' has no property named '%s'",
1598 G_OBJECT_TYPE_NAME (object),
1601 g_object_notify_by_spec_internal (object, pspec);
1605 * g_object_notify_by_pspec:
1606 * @object: a #GObject
1607 * @pspec: the #GParamSpec of a property installed on the class of @object.
1609 * Emits a "notify" signal for the property specified by @pspec on @object.
1611 * This function omits the property name lookup, hence it is faster than
1612 * g_object_notify().
1614 * One way to avoid using g_object_notify() from within the
1615 * class that registered the properties, and using g_object_notify_by_pspec()
1616 * instead, is to store the GParamSpec used with
1617 * g_object_class_install_property() inside a static array, e.g.:
1619 *|[<!-- language="C" -->
1624 * } MyObjectProperty;
1626 * static GParamSpec *properties[PROP_LAST];
1629 * my_object_class_init (MyObjectClass *klass)
1631 * properties[PROP_FOO] = g_param_spec_int ("foo", "Foo", "The foo",
1634 * G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS);
1635 * g_object_class_install_property (gobject_class,
1637 * properties[PROP_FOO]);
1641 * and then notify a change on the "foo" property with:
1643 * |[<!-- language="C" -->
1644 * g_object_notify_by_pspec (self, properties[PROP_FOO]);
1650 g_object_notify_by_pspec (GObject *object,
1654 g_return_if_fail (G_IS_OBJECT (object));
1655 g_return_if_fail (G_IS_PARAM_SPEC (pspec));
1657 g_object_notify_by_spec_internal (object, pspec);
1661 * g_object_thaw_notify:
1662 * @object: a #GObject
1664 * Reverts the effect of a previous call to
1665 * g_object_freeze_notify(). The freeze count is decreased on @object
1666 * and when it reaches zero, queued "notify" signals are emitted.
1668 * Duplicate notifications for each property are squashed so that at most one
1669 * #GObject::notify signal is emitted for each property, in the reverse order
1670 * in which they have been queued.
1672 * It is an error to call this function when the freeze count is zero.
1675 g_object_thaw_notify (GObject *object)
1677 GObjectNotifyQueue *nqueue;
1679 g_return_if_fail (G_IS_OBJECT (object));
1681 #ifndef G_DISABLE_CHECKS
1682 if (G_UNLIKELY (g_atomic_int_get (&object->ref_count) == 0))
1684 g_critical ("Attempting to thaw the notification queue for object %s[%p]; "
1685 "Property notification does not work during instance finalization.",
1686 G_OBJECT_TYPE_NAME (object),
1693 g_object_ref (object);
1695 /* FIXME: Freezing is the only way to get at the notify queue.
1696 * So we freeze once and then thaw twice.
1698 nqueue = g_object_notify_queue_freeze (object, FALSE);
1699 g_object_notify_queue_thaw (object, nqueue);
1700 g_object_notify_queue_thaw (object, nqueue);
1702 g_object_unref (object);
1706 maybe_issue_property_deprecation_warning (const GParamSpec *pspec)
1708 static GHashTable *already_warned_table;
1709 static const gchar *enable_diagnostic;
1710 static GMutex already_warned_lock;
1713 if (g_once_init_enter (&enable_diagnostic))
1715 const gchar *value = g_getenv ("G_ENABLE_DIAGNOSTIC");
1720 g_once_init_leave (&enable_diagnostic, value);
1723 if (enable_diagnostic[0] == '0')
1726 /* We hash only on property names: this means that we could end up in
1727 * a situation where we fail to emit a warning about a pair of
1728 * same-named deprecated properties used on two separate types.
1729 * That's pretty unlikely to occur, and even if it does, you'll still
1730 * have seen the warning for the first one...
1732 * Doing it this way lets us hash directly on the (interned) property
1735 g_mutex_lock (&already_warned_lock);
1737 if (already_warned_table == NULL)
1738 already_warned_table = g_hash_table_new (NULL, NULL);
1740 already = g_hash_table_contains (already_warned_table, (gpointer) pspec->name);
1742 g_hash_table_add (already_warned_table, (gpointer) pspec->name);
1744 g_mutex_unlock (&already_warned_lock);
1747 g_warning ("The property %s:%s is deprecated and shouldn't be used "
1748 "anymore. It will be removed in a future version.",
1749 g_type_name (pspec->owner_type), pspec->name);
1753 consider_issuing_property_deprecation_warning (const GParamSpec *pspec)
1755 if (G_UNLIKELY (pspec->flags & G_PARAM_DEPRECATED))
1756 maybe_issue_property_deprecation_warning (pspec);
1760 object_get_property (GObject *object,
1764 GTypeInstance *inst = (GTypeInstance *) object;
1765 GObjectClass *class;
1766 guint param_id = PARAM_SPEC_PARAM_ID (pspec);
1768 if (G_LIKELY (inst->g_class->g_type == pspec->owner_type))
1769 class = (GObjectClass *) inst->g_class;
1771 class = g_type_class_peek (pspec->owner_type);
1773 g_assert (class != NULL);
1775 param_spec_follow_override (&pspec);
1777 consider_issuing_property_deprecation_warning (pspec);
1779 class->get_property (object, param_id, value, pspec);
1783 object_set_property (GObject *object,
1785 const GValue *value,
1786 GObjectNotifyQueue *nqueue,
1787 gboolean user_specified)
1789 GTypeInstance *inst = (GTypeInstance *) object;
1790 GObjectClass *class;
1791 GParamSpecClass *pclass;
1792 guint param_id = PARAM_SPEC_PARAM_ID (pspec);
1794 if (G_LIKELY (inst->g_class->g_type == pspec->owner_type))
1795 class = (GObjectClass *) inst->g_class;
1797 class = g_type_class_peek (pspec->owner_type);
1799 g_assert (class != NULL);
1801 param_spec_follow_override (&pspec);
1804 consider_issuing_property_deprecation_warning (pspec);
1806 pclass = G_PARAM_SPEC_GET_CLASS (pspec);
1807 if (g_value_type_compatible (G_VALUE_TYPE (value), pspec->value_type) &&
1808 (pclass->value_validate == NULL ||
1809 (pclass->value_is_valid != NULL && pclass->value_is_valid (pspec, value))))
1811 class->set_property (object, param_id, value, pspec);
1815 /* provide a copy to work from, convert (if necessary) and validate */
1816 GValue tmp_value = G_VALUE_INIT;
1818 g_value_init (&tmp_value, pspec->value_type);
1820 if (!g_value_transform (value, &tmp_value))
1821 g_critical ("unable to set property '%s' of type '%s' from value of type '%s'",
1823 g_type_name (pspec->value_type),
1824 G_VALUE_TYPE_NAME (value));
1825 else if (g_param_value_validate (pspec, &tmp_value) && !(pspec->flags & G_PARAM_LAX_VALIDATION))
1827 gchar *contents = g_strdup_value_contents (value);
1829 g_critical ("value \"%s\" of type '%s' is invalid or out of range for property '%s' of type '%s'",
1831 G_VALUE_TYPE_NAME (value),
1833 g_type_name (pspec->value_type));
1838 class->set_property (object, param_id, &tmp_value, pspec);
1841 g_value_unset (&tmp_value);
1844 if ((pspec->flags & (G_PARAM_EXPLICIT_NOTIFY | G_PARAM_READABLE)) == G_PARAM_READABLE &&
1846 g_object_notify_queue_add (object, nqueue, pspec);
1850 object_interface_check_properties (gpointer check_data,
1853 GTypeInterface *iface_class = g_iface;
1854 GObjectClass *class;
1855 GType iface_type = iface_class->g_type;
1856 GParamSpec **pspecs;
1859 class = g_type_class_ref (iface_class->g_instance_type);
1864 if (!G_IS_OBJECT_CLASS (class))
1867 pspecs = g_param_spec_pool_list (pspec_pool, iface_type, &n);
1871 GParamSpec *class_pspec = g_param_spec_pool_lookup (pspec_pool,
1873 G_OBJECT_CLASS_TYPE (class),
1878 g_critical ("Object class %s doesn't implement property "
1879 "'%s' from interface '%s'",
1880 g_type_name (G_OBJECT_CLASS_TYPE (class)),
1882 g_type_name (iface_type));
1887 /* We do a number of checks on the properties of an interface to
1888 * make sure that all classes implementing the interface are
1889 * overriding the properties correctly.
1891 * We do the checks in order of importance so that we can give
1892 * more useful error messages first.
1894 * First, we check that the implementation doesn't remove the
1895 * basic functionality (readability, writability) advertised by
1896 * the interface. Next, we check that it doesn't introduce
1897 * additional restrictions (such as construct-only). Finally, we
1898 * make sure the types are compatible.
1901 #define SUBSET(a,b,mask) (((a) & ~(b) & (mask)) == 0)
1902 /* If the property on the interface is readable then the
1903 * implementation must be readable. If the interface is writable
1904 * then the implementation must be writable.
1906 if (!SUBSET (pspecs[n]->flags, class_pspec->flags, G_PARAM_READABLE | G_PARAM_WRITABLE))
1908 g_critical ("Flags for property '%s' on class '%s' remove functionality compared with the "
1909 "property on interface '%s'\n", pspecs[n]->name,
1910 g_type_name (G_OBJECT_CLASS_TYPE (class)), g_type_name (iface_type));
1914 /* If the property on the interface is writable then we need to
1915 * make sure the implementation doesn't introduce new restrictions
1916 * on that writability (ie: construct-only).
1918 * If the interface was not writable to begin with then we don't
1919 * really have any problems here because "writable at construct
1920 * time only" is still more permissive than "read only".
1922 if (pspecs[n]->flags & G_PARAM_WRITABLE)
1924 if (!SUBSET (class_pspec->flags, pspecs[n]->flags, G_PARAM_CONSTRUCT_ONLY))
1926 g_critical ("Flags for property '%s' on class '%s' introduce additional restrictions on "
1927 "writability compared with the property on interface '%s'\n", pspecs[n]->name,
1928 g_type_name (G_OBJECT_CLASS_TYPE (class)), g_type_name (iface_type));
1934 /* If the property on the interface is readable then we are
1935 * effectively advertising that reading the property will return a
1936 * value of a specific type. All implementations of the interface
1937 * need to return items of this type -- but may be more
1938 * restrictive. For example, it is legal to have:
1940 * GtkWidget *get_item();
1942 * that is implemented by a function that always returns a
1943 * GtkEntry. In short: readability implies that the
1944 * implementation value type must be equal or more restrictive.
1946 * Similarly, if the property on the interface is writable then
1947 * must be able to accept the property being set to any value of
1948 * that type, including subclasses. In this case, we may also be
1949 * less restrictive. For example, it is legal to have:
1951 * set_item (GtkEntry *);
1953 * that is implemented by a function that will actually work with
1954 * any GtkWidget. In short: writability implies that the
1955 * implementation value type must be equal or less restrictive.
1957 * In the case that the property is both readable and writable
1958 * then the only way that both of the above can be satisfied is
1959 * with a type that is exactly equal.
1961 switch (pspecs[n]->flags & (G_PARAM_READABLE | G_PARAM_WRITABLE))
1963 case G_PARAM_READABLE | G_PARAM_WRITABLE:
1964 /* class pspec value type must have exact equality with interface */
1965 if (pspecs[n]->value_type != class_pspec->value_type)
1966 g_critical ("Read/writable property '%s' on class '%s' has type '%s' which is not exactly equal to the "
1967 "type '%s' of the property on the interface '%s'\n", pspecs[n]->name,
1968 g_type_name (G_OBJECT_CLASS_TYPE (class)), g_type_name (G_PARAM_SPEC_VALUE_TYPE (class_pspec)),
1969 g_type_name (G_PARAM_SPEC_VALUE_TYPE (pspecs[n])), g_type_name (iface_type));
1972 case G_PARAM_READABLE:
1973 /* class pspec value type equal or more restrictive than interface */
1974 if (!g_type_is_a (class_pspec->value_type, pspecs[n]->value_type))
1975 g_critical ("Read-only property '%s' on class '%s' has type '%s' which is not equal to or more "
1976 "restrictive than the type '%s' of the property on the interface '%s'\n", pspecs[n]->name,
1977 g_type_name (G_OBJECT_CLASS_TYPE (class)), g_type_name (G_PARAM_SPEC_VALUE_TYPE (class_pspec)),
1978 g_type_name (G_PARAM_SPEC_VALUE_TYPE (pspecs[n])), g_type_name (iface_type));
1981 case G_PARAM_WRITABLE:
1982 /* class pspec value type equal or less restrictive than interface */
1983 if (!g_type_is_a (pspecs[n]->value_type, class_pspec->value_type))
1984 g_critical ("Write-only property '%s' on class '%s' has type '%s' which is not equal to or less "
1985 "restrictive than the type '%s' of the property on the interface '%s' \n", pspecs[n]->name,
1986 g_type_name (G_OBJECT_CLASS_TYPE (class)), g_type_name (G_PARAM_SPEC_VALUE_TYPE (class_pspec)),
1987 g_type_name (G_PARAM_SPEC_VALUE_TYPE (pspecs[n])), g_type_name (iface_type));
1991 g_assert_not_reached ();
1998 g_type_class_unref (class);
2002 g_object_get_type (void)
2004 return G_TYPE_OBJECT;
2008 * g_object_new: (skip)
2009 * @object_type: the type id of the #GObject subtype to instantiate
2010 * @first_property_name: the name of the first property
2011 * @...: the value of the first property, followed optionally by more
2012 * name/value pairs, followed by %NULL
2014 * Creates a new instance of a #GObject subtype and sets its properties.
2016 * Construction parameters (see %G_PARAM_CONSTRUCT, %G_PARAM_CONSTRUCT_ONLY)
2017 * which are not explicitly specified are set to their default values. Any
2018 * private data for the object is guaranteed to be initialized with zeros, as
2019 * per g_type_create_instance().
2021 * Note that in C, small integer types in variable argument lists are promoted
2022 * up to `gint` or `guint` as appropriate, and read back accordingly. `gint` is
2023 * 32 bits on every platform on which GLib is currently supported. This means that
2024 * you can use C expressions of type `gint` with g_object_new() and properties of
2025 * type `gint` or `guint` or smaller. Specifically, you can use integer literals
2026 * with these property types.
2028 * When using property types of `gint64` or `guint64`, you must ensure that the
2029 * value that you provide is 64 bit. This means that you should use a cast or
2030 * make use of the %G_GINT64_CONSTANT or %G_GUINT64_CONSTANT macros.
2032 * Similarly, `gfloat` is promoted to `gdouble`, so you must ensure that the value
2033 * you provide is a `gdouble`, even for a property of type `gfloat`.
2035 * Since GLib 2.72, all #GObjects are guaranteed to be aligned to at least the
2036 * alignment of the largest basic GLib type (typically this is `guint64` or
2037 * `gdouble`). If you need larger alignment for an element in a #GObject, you
2038 * should allocate it on the heap (aligned), or arrange for your #GObject to be
2039 * appropriately padded.
2041 * Returns: (transfer full) (type GObject.Object): a new instance of
2045 g_object_new (GType object_type,
2046 const gchar *first_property_name,
2052 /* short circuit for calls supplying no properties */
2053 if (!first_property_name)
2054 return g_object_new_with_properties (object_type, 0, NULL, NULL);
2056 va_start (var_args, first_property_name);
2057 object = g_object_new_valist (object_type, first_property_name, var_args);
2063 /* Check alignment. (See https://gitlab.gnome.org/GNOME/glib/-/issues/1231.)
2064 * This should never fail, since g_type_create_instance() uses g_slice_alloc0().
2065 * The GSlice allocator always aligns to the next power of 2 greater than the
2066 * allocation size. The allocation size for a GObject is
2067 * sizeof(GTypeInstance) + sizeof(guint) + sizeof(GData*)
2068 * which is 12B on 32-bit platforms, and larger on 64-bit systems. In both
2069 * cases, that’s larger than the 8B needed for a guint64 or gdouble.
2071 * If GSlice falls back to malloc(), it’s documented to return something
2072 * suitably aligned for any basic type. */
2073 static inline gboolean
2074 g_object_is_aligned (GObject *object)
2076 return ((((guintptr) (void *) object) %
2077 MAX (G_ALIGNOF (gdouble),
2078 MAX (G_ALIGNOF (guint64),
2079 MAX (G_ALIGNOF (gint),
2080 G_ALIGNOF (glong))))) == 0);
2084 g_object_new_with_custom_constructor (GObjectClass *class,
2085 GObjectConstructParam *params,
2088 GObjectNotifyQueue *nqueue = NULL;
2089 gboolean newly_constructed;
2090 GObjectConstructParam *cparams;
2091 gboolean free_cparams = FALSE;
2098 /* If we have ->constructed() then we have to do a lot more work.
2099 * It's possible that this is a singleton and it's also possible
2100 * that the user's constructor() will attempt to modify the values
2101 * that we pass in, so we'll need to allocate copies of them.
2102 * It's also possible that the user may attempt to call
2103 * g_object_set() from inside of their constructor, so we need to
2104 * add ourselves to a list of objects for which that is allowed
2105 * while their constructor() is running.
2108 /* Create the array of GObjectConstructParams for constructor(),
2109 * The 1024 here is an arbitrary, high limit that no sane code
2110 * will ever hit, just to avoid the possibility of stack overflow.
2112 if (G_LIKELY (class->n_construct_properties < 1024))
2114 cparams = g_newa0 (GObjectConstructParam, class->n_construct_properties);
2115 cvalues = g_newa0 (GValue, class->n_construct_properties);
2119 cparams = g_new0 (GObjectConstructParam, class->n_construct_properties);
2120 cvalues = g_new0 (GValue, class->n_construct_properties);
2121 free_cparams = TRUE;
2126 /* As above, we may find the value in the passed-in params list.
2128 * If we have the value passed in then we can use the GValue from
2129 * it directly because it is safe to modify. If we use the
2130 * default value from the class, we had better not pass that in
2131 * and risk it being modified, so we create a new one.
2133 for (node = class->construct_properties; node; node = node->next)
2140 value = NULL; /* to silence gcc... */
2142 for (j = 0; j < n_params; j++)
2143 if (params[j].pspec == pspec)
2145 consider_issuing_property_deprecation_warning (pspec);
2146 value = params[j].value;
2152 value = &cvalues[cvals_used++];
2153 g_value_init (value, pspec->value_type);
2154 g_param_value_set_default (pspec, value);
2157 cparams[i].pspec = pspec;
2158 cparams[i].value = value;
2162 /* construct object from construction parameters */
2163 object = class->constructor (class->g_type_class.g_type, class->n_construct_properties, cparams);
2164 /* free construction values */
2165 while (cvals_used--)
2166 g_value_unset (&cvalues[cvals_used]);
2174 /* There is code in the wild that relies on being able to return NULL
2175 * from its custom constructor. This was never a supported operation,
2176 * but since the code is already out there...
2180 g_critical ("Custom constructor for class %s returned NULL (which is invalid). "
2181 "Please use GInitable instead.", G_OBJECT_CLASS_NAME (class));
2185 if (!g_object_is_aligned (object))
2187 g_critical ("Custom constructor for class %s returned a non-aligned "
2188 "GObject (which is invalid since GLib 2.72). Assuming any "
2189 "code using this object doesn’t require it to be aligned. "
2190 "Please fix your constructor to align to the largest GLib "
2191 "basic type (typically gdouble or guint64).",
2192 G_OBJECT_CLASS_NAME (class));
2195 /* g_object_init() will have marked the object as being in-construction.
2196 * Check if the returned object still is so marked, or if this is an
2197 * already-existing singleton (in which case we should not do 'constructed').
2199 newly_constructed = object_in_construction (object);
2200 if (newly_constructed)
2201 unset_object_in_construction (object);
2203 if (CLASS_HAS_PROPS (class))
2205 if ((newly_constructed && _g_object_has_notify_handler_X (object)) ||
2206 _g_object_has_notify_handler (object))
2208 /* This may or may not have been setup in g_object_init().
2209 * If it hasn't, we do it now.
2211 nqueue = g_datalist_id_get_data (&object->qdata, quark_notify_queue);
2213 nqueue = g_object_notify_queue_freeze (object, FALSE);
2217 /* run 'constructed' handler if there is a custom one */
2218 if (newly_constructed && CLASS_HAS_CUSTOM_CONSTRUCTED (class))
2219 class->constructed (object);
2221 /* set remaining properties */
2222 for (i = 0; i < n_params; i++)
2223 if (!(params[i].pspec->flags & (G_PARAM_CONSTRUCT | G_PARAM_CONSTRUCT_ONLY)))
2224 object_set_property (object, params[i].pspec, params[i].value, nqueue, TRUE);
2226 /* If nqueue is non-NULL then we are frozen. Thaw it. */
2228 g_object_notify_queue_thaw (object, nqueue);
2234 g_object_new_internal (GObjectClass *class,
2235 GObjectConstructParam *params,
2238 GObjectNotifyQueue *nqueue = NULL;
2242 if G_UNLIKELY (CLASS_HAS_CUSTOM_CONSTRUCTOR (class))
2243 return g_object_new_with_custom_constructor (class, params, n_params);
2245 object = (GObject *) g_type_create_instance (class->g_type_class.g_type);
2247 g_assert (g_object_is_aligned (object));
2249 unset_object_in_construction (object);
2251 if (CLASS_HAS_PROPS (class))
2255 if (_g_object_has_notify_handler_X (object))
2257 /* This may or may not have been setup in g_object_init().
2258 * If it hasn't, we do it now.
2260 nqueue = g_datalist_id_get_data (&object->qdata, quark_notify_queue);
2262 nqueue = g_object_notify_queue_freeze (object, FALSE);
2265 /* We will set exactly n_construct_properties construct
2266 * properties, but they may come from either the class default
2267 * values or the passed-in parameter list.
2269 for (node = class->construct_properties; node; node = node->next)
2271 const GValue *value;
2274 gboolean user_specified = FALSE;
2277 value = NULL; /* to silence gcc... */
2279 for (j = 0; j < n_params; j++)
2280 if (params[j].pspec == pspec)
2282 value = params[j].value;
2283 user_specified = TRUE;
2288 value = g_param_spec_get_default_value (pspec);
2290 object_set_property (object, pspec, value, nqueue, user_specified);
2294 /* run 'constructed' handler if there is a custom one */
2295 if (CLASS_HAS_CUSTOM_CONSTRUCTED (class))
2296 class->constructed (object);
2298 /* Set remaining properties. The construct properties will
2299 * already have been taken, so set only the non-construct ones.
2301 for (i = 0; i < n_params; i++)
2302 if (!(params[i].pspec->flags & (G_PARAM_CONSTRUCT | G_PARAM_CONSTRUCT_ONLY)))
2303 object_set_property (object, params[i].pspec, params[i].value, nqueue, TRUE);
2306 g_object_notify_queue_thaw (object, nqueue);
2312 static inline gboolean
2313 g_object_new_is_valid_property (GType object_type,
2316 GObjectConstructParam *params,
2321 if (G_UNLIKELY (pspec == NULL))
2323 g_critical ("%s: object class '%s' has no property named '%s'",
2324 G_STRFUNC, g_type_name (object_type), name);
2328 if (G_UNLIKELY (~pspec->flags & G_PARAM_WRITABLE))
2330 g_critical ("%s: property '%s' of object class '%s' is not writable",
2331 G_STRFUNC, pspec->name, g_type_name (object_type));
2335 if (G_UNLIKELY (pspec->flags & (G_PARAM_CONSTRUCT | G_PARAM_CONSTRUCT_ONLY)))
2337 for (i = 0; i < n_params; i++)
2338 if (params[i].pspec == pspec)
2340 if (G_UNLIKELY (i != n_params))
2342 g_critical ("%s: property '%s' for type '%s' cannot be set twice",
2343 G_STRFUNC, name, g_type_name (object_type));
2352 * g_object_new_with_properties: (skip)
2353 * @object_type: the object type to instantiate
2354 * @n_properties: the number of properties
2355 * @names: (array length=n_properties): the names of each property to be set
2356 * @values: (array length=n_properties): the values of each property to be set
2358 * Creates a new instance of a #GObject subtype and sets its properties using
2359 * the provided arrays. Both arrays must have exactly @n_properties elements,
2360 * and the names and values correspond by index.
2362 * Construction parameters (see %G_PARAM_CONSTRUCT, %G_PARAM_CONSTRUCT_ONLY)
2363 * which are not explicitly specified are set to their default values.
2365 * Returns: (type GObject.Object) (transfer full): a new instance of
2371 g_object_new_with_properties (GType object_type,
2373 const char *names[],
2374 const GValue values[])
2376 GObjectClass *class, *unref_class = NULL;
2379 g_return_val_if_fail (G_TYPE_IS_OBJECT (object_type), NULL);
2381 /* Try to avoid thrashing the ref_count if we don't need to (since
2382 * it's a locked operation).
2384 class = g_type_class_peek_static (object_type);
2387 class = unref_class = g_type_class_ref (object_type);
2389 if (n_properties > 0)
2392 GObjectConstructParam *params;
2394 params = g_newa (GObjectConstructParam, n_properties);
2395 for (i = 0; i < n_properties; i++)
2397 GParamSpec *pspec = find_pspec (class, names[i]);
2399 if (!g_object_new_is_valid_property (object_type, pspec, names[i], params, count))
2401 params[count].pspec = pspec;
2402 params[count].value = (GValue *) &values[i];
2405 object = g_object_new_internal (class, params, count);
2408 object = g_object_new_internal (class, NULL, 0);
2410 if (unref_class != NULL)
2411 g_type_class_unref (unref_class);
2418 * @object_type: the type id of the #GObject subtype to instantiate
2419 * @n_parameters: the length of the @parameters array
2420 * @parameters: (array length=n_parameters): an array of #GParameter
2422 * Creates a new instance of a #GObject subtype and sets its properties.
2424 * Construction parameters (see %G_PARAM_CONSTRUCT, %G_PARAM_CONSTRUCT_ONLY)
2425 * which are not explicitly specified are set to their default values.
2427 * Returns: (type GObject.Object) (transfer full): a new instance of
2430 * Deprecated: 2.54: Use g_object_new_with_properties() instead.
2431 * deprecated. See #GParameter for more information.
2433 G_GNUC_BEGIN_IGNORE_DEPRECATIONS
2435 g_object_newv (GType object_type,
2437 GParameter *parameters)
2439 GObjectClass *class, *unref_class = NULL;
2442 g_return_val_if_fail (G_TYPE_IS_OBJECT (object_type), NULL);
2443 g_return_val_if_fail (n_parameters == 0 || parameters != NULL, NULL);
2445 /* Try to avoid thrashing the ref_count if we don't need to (since
2446 * it's a locked operation).
2448 class = g_type_class_peek_static (object_type);
2451 class = unref_class = g_type_class_ref (object_type);
2455 GObjectConstructParam *cparams;
2458 cparams = g_newa (GObjectConstructParam, n_parameters);
2461 for (i = 0; i < n_parameters; i++)
2463 GParamSpec *pspec = find_pspec (class, parameters[i].name);
2465 if (!g_object_new_is_valid_property (object_type, pspec, parameters[i].name, cparams, j))
2468 cparams[j].pspec = pspec;
2469 cparams[j].value = ¶meters[i].value;
2473 object = g_object_new_internal (class, cparams, j);
2476 /* Fast case: no properties passed in. */
2477 object = g_object_new_internal (class, NULL, 0);
2480 g_type_class_unref (unref_class);
2484 G_GNUC_END_IGNORE_DEPRECATIONS
2487 * g_object_new_valist: (skip)
2488 * @object_type: the type id of the #GObject subtype to instantiate
2489 * @first_property_name: the name of the first property
2490 * @var_args: the value of the first property, followed optionally by more
2491 * name/value pairs, followed by %NULL
2493 * Creates a new instance of a #GObject subtype and sets its properties.
2495 * Construction parameters (see %G_PARAM_CONSTRUCT, %G_PARAM_CONSTRUCT_ONLY)
2496 * which are not explicitly specified are set to their default values.
2498 * Returns: a new instance of @object_type
2501 g_object_new_valist (GType object_type,
2502 const gchar *first_property_name,
2505 GObjectClass *class, *unref_class = NULL;
2508 g_return_val_if_fail (G_TYPE_IS_OBJECT (object_type), NULL);
2510 /* Try to avoid thrashing the ref_count if we don't need to (since
2511 * it's a locked operation).
2513 class = g_type_class_peek_static (object_type);
2516 class = unref_class = g_type_class_ref (object_type);
2518 if (first_property_name)
2520 GObjectConstructParam params_stack[16];
2521 GValue values_stack[G_N_ELEMENTS (params_stack)];
2522 GTypeValueTable *vtabs_stack[G_N_ELEMENTS (params_stack)];
2524 GObjectConstructParam *params = params_stack;
2525 GValue *values = values_stack;
2526 GTypeValueTable **vtabs = vtabs_stack;
2528 guint n_params_alloc = G_N_ELEMENTS (params_stack);
2530 name = first_property_name;
2534 gchar *error = NULL;
2535 GParamSpec *pspec = find_pspec (class, name);
2537 if (!g_object_new_is_valid_property (object_type, pspec, name, params, n_params))
2540 if (G_UNLIKELY (n_params == n_params_alloc))
2544 if (n_params_alloc == G_N_ELEMENTS (params_stack))
2546 n_params_alloc = G_N_ELEMENTS (params_stack) * 2u;
2547 params = g_new (GObjectConstructParam, n_params_alloc);
2548 values = g_new (GValue, n_params_alloc);
2549 vtabs = g_new (GTypeValueTable *, n_params_alloc);
2550 memcpy (params, params_stack, sizeof (GObjectConstructParam) * n_params);
2551 memcpy (values, values_stack, sizeof (GValue) * n_params);
2552 memcpy (vtabs, vtabs_stack, sizeof (GTypeValueTable *) * n_params);
2556 n_params_alloc *= 2u;
2557 params = g_realloc (params, sizeof (GObjectConstructParam) * n_params_alloc);
2558 values = g_realloc (values, sizeof (GValue) * n_params_alloc);
2559 vtabs = g_realloc (vtabs, sizeof (GTypeValueTable *) * n_params_alloc);
2562 for (i = 0; i < n_params; i++)
2563 params[i].value = &values[i];
2566 params[n_params].pspec = pspec;
2567 params[n_params].value = &values[n_params];
2568 memset (&values[n_params], 0, sizeof (GValue));
2570 G_VALUE_COLLECT_INIT2 (&values[n_params], vtabs[n_params], pspec->value_type, var_args, G_VALUE_NOCOPY_CONTENTS, &error);
2574 g_critical ("%s: %s", G_STRFUNC, error);
2575 g_value_unset (&values[n_params]);
2582 while ((name = va_arg (var_args, const gchar *)));
2584 object = g_object_new_internal (class, params, n_params);
2588 /* We open-code g_value_unset() here to avoid the
2589 * cost of looking up the GTypeValueTable again.
2591 if (vtabs[n_params]->value_free)
2592 vtabs[n_params]->value_free (params[n_params].value);
2595 if (G_UNLIKELY (n_params_alloc != G_N_ELEMENTS (params_stack)))
2603 /* Fast case: no properties passed in. */
2604 object = g_object_new_internal (class, NULL, 0);
2607 g_type_class_unref (unref_class);
2613 g_object_constructor (GType type,
2614 guint n_construct_properties,
2615 GObjectConstructParam *construct_params)
2620 object = (GObject*) g_type_create_instance (type);
2622 /* set construction parameters */
2623 if (n_construct_properties)
2625 GObjectNotifyQueue *nqueue = g_object_notify_queue_freeze (object, FALSE);
2627 /* set construct properties */
2628 while (n_construct_properties--)
2630 GValue *value = construct_params->value;
2631 GParamSpec *pspec = construct_params->pspec;
2634 object_set_property (object, pspec, value, nqueue, TRUE);
2636 g_object_notify_queue_thaw (object, nqueue);
2637 /* the notification queue is still frozen from g_object_init(), so
2638 * we don't need to handle it here, g_object_newv() takes
2647 g_object_constructed (GObject *object)
2649 /* empty default impl to allow unconditional upchaining */
2652 static inline gboolean
2653 g_object_set_is_valid_property (GObject *object,
2655 const char *property_name)
2657 if (G_UNLIKELY (pspec == NULL))
2659 g_critical ("%s: object class '%s' has no property named '%s'",
2660 G_STRFUNC, G_OBJECT_TYPE_NAME (object), property_name);
2663 if (G_UNLIKELY (!(pspec->flags & G_PARAM_WRITABLE)))
2665 g_critical ("%s: property '%s' of object class '%s' is not writable",
2666 G_STRFUNC, pspec->name, G_OBJECT_TYPE_NAME (object));
2669 if (G_UNLIKELY (((pspec->flags & G_PARAM_CONSTRUCT_ONLY) && !object_in_construction (object))))
2671 g_critical ("%s: construct property \"%s\" for object '%s' can't be set after construction",
2672 G_STRFUNC, pspec->name, G_OBJECT_TYPE_NAME (object));
2679 * g_object_setv: (skip)
2680 * @object: a #GObject
2681 * @n_properties: the number of properties
2682 * @names: (array length=n_properties): the names of each property to be set
2683 * @values: (array length=n_properties): the values of each property to be set
2685 * Sets @n_properties properties for an @object.
2686 * Properties to be set will be taken from @values. All properties must be
2687 * valid. Warnings will be emitted and undefined behaviour may result if invalid
2688 * properties are passed in.
2693 g_object_setv (GObject *object,
2695 const gchar *names[],
2696 const GValue values[])
2699 GObjectNotifyQueue *nqueue = NULL;
2701 GObjectClass *class;
2703 g_return_if_fail (G_IS_OBJECT (object));
2705 if (n_properties == 0)
2708 g_object_ref (object);
2710 class = G_OBJECT_GET_CLASS (object);
2712 if (_g_object_has_notify_handler (object))
2713 nqueue = g_object_notify_queue_freeze (object, FALSE);
2715 for (i = 0; i < n_properties; i++)
2717 pspec = find_pspec (class, names[i]);
2719 if (!g_object_set_is_valid_property (object, pspec, names[i]))
2722 object_set_property (object, pspec, &values[i], nqueue, TRUE);
2726 g_object_notify_queue_thaw (object, nqueue);
2728 g_object_unref (object);
2732 * g_object_set_valist: (skip)
2733 * @object: a #GObject
2734 * @first_property_name: name of the first property to set
2735 * @var_args: value for the first property, followed optionally by more
2736 * name/value pairs, followed by %NULL
2738 * Sets properties on an object.
2741 g_object_set_valist (GObject *object,
2742 const gchar *first_property_name,
2745 GObjectNotifyQueue *nqueue = NULL;
2747 GObjectClass *class;
2749 g_return_if_fail (G_IS_OBJECT (object));
2751 g_object_ref (object);
2753 if (_g_object_has_notify_handler (object))
2754 nqueue = g_object_notify_queue_freeze (object, FALSE);
2756 class = G_OBJECT_GET_CLASS (object);
2758 name = first_property_name;
2761 GValue value = G_VALUE_INIT;
2763 gchar *error = NULL;
2764 GTypeValueTable *vtab;
2766 pspec = find_pspec (class, name);
2768 if (!g_object_set_is_valid_property (object, pspec, name))
2771 G_VALUE_COLLECT_INIT2 (&value, vtab, pspec->value_type, var_args, G_VALUE_NOCOPY_CONTENTS, &error);
2774 g_critical ("%s: %s", G_STRFUNC, error);
2776 g_value_unset (&value);
2780 object_set_property (object, pspec, &value, nqueue, TRUE);
2782 /* We open-code g_value_unset() here to avoid the
2783 * cost of looking up the GTypeValueTable again.
2785 if (vtab->value_free)
2786 vtab->value_free (&value);
2788 name = va_arg (var_args, gchar*);
2792 g_object_notify_queue_thaw (object, nqueue);
2794 g_object_unref (object);
2797 static inline gboolean
2798 g_object_get_is_valid_property (GObject *object,
2800 const char *property_name)
2802 if (G_UNLIKELY (pspec == NULL))
2804 g_critical ("%s: object class '%s' has no property named '%s'",
2805 G_STRFUNC, G_OBJECT_TYPE_NAME (object), property_name);
2808 if (G_UNLIKELY (!(pspec->flags & G_PARAM_READABLE)))
2810 g_critical ("%s: property '%s' of object class '%s' is not readable",
2811 G_STRFUNC, pspec->name, G_OBJECT_TYPE_NAME (object));
2819 * @object: a #GObject
2820 * @n_properties: the number of properties
2821 * @names: (array length=n_properties): the names of each property to get
2822 * @values: (array length=n_properties): the values of each property to get
2824 * Gets @n_properties properties for an @object.
2825 * Obtained properties will be set to @values. All properties must be valid.
2826 * Warnings will be emitted and undefined behaviour may result if invalid
2827 * properties are passed in.
2832 g_object_getv (GObject *object,
2834 const gchar *names[],
2839 GObjectClass *class;
2841 g_return_if_fail (G_IS_OBJECT (object));
2843 if (n_properties == 0)
2846 g_object_ref (object);
2848 class = G_OBJECT_GET_CLASS (object);
2850 memset (values, 0, n_properties * sizeof (GValue));
2852 for (i = 0; i < n_properties; i++)
2854 pspec = find_pspec (class, names[i]);
2856 if (!g_object_get_is_valid_property (object, pspec, names[i]))
2858 g_value_init (&values[i], pspec->value_type);
2859 object_get_property (object, pspec, &values[i]);
2861 g_object_unref (object);
2865 * g_object_get_valist: (skip)
2866 * @object: a #GObject
2867 * @first_property_name: name of the first property to get
2868 * @var_args: return location for the first property, followed optionally by more
2869 * name/return location pairs, followed by %NULL
2871 * Gets properties of an object.
2873 * In general, a copy is made of the property contents and the caller
2874 * is responsible for freeing the memory in the appropriate manner for
2875 * the type, for instance by calling g_free() or g_object_unref().
2877 * See g_object_get().
2880 g_object_get_valist (GObject *object,
2881 const gchar *first_property_name,
2885 GObjectClass *class;
2887 g_return_if_fail (G_IS_OBJECT (object));
2889 g_object_ref (object);
2891 class = G_OBJECT_GET_CLASS (object);
2893 name = first_property_name;
2897 GValue value = G_VALUE_INIT;
2901 pspec = find_pspec (class, name);
2903 if (!g_object_get_is_valid_property (object, pspec, name))
2906 g_value_init (&value, pspec->value_type);
2908 object_get_property (object, pspec, &value);
2910 G_VALUE_LCOPY (&value, var_args, 0, &error);
2913 g_critical ("%s: %s", G_STRFUNC, error);
2915 g_value_unset (&value);
2919 g_value_unset (&value);
2921 name = va_arg (var_args, gchar*);
2924 g_object_unref (object);
2928 * g_object_set: (skip)
2929 * @object: (type GObject.Object): a #GObject
2930 * @first_property_name: name of the first property to set
2931 * @...: value for the first property, followed optionally by more
2932 * name/value pairs, followed by %NULL
2934 * Sets properties on an object.
2936 * The same caveats about passing integer literals as varargs apply as with
2937 * g_object_new(). In particular, any integer literals set as the values for
2938 * properties of type #gint64 or #guint64 must be 64 bits wide, using the
2939 * %G_GINT64_CONSTANT or %G_GUINT64_CONSTANT macros.
2941 * Note that the "notify" signals are queued and only emitted (in
2942 * reverse order) after all properties have been set. See
2943 * g_object_freeze_notify().
2946 g_object_set (gpointer _object,
2947 const gchar *first_property_name,
2950 GObject *object = _object;
2953 g_return_if_fail (G_IS_OBJECT (object));
2955 va_start (var_args, first_property_name);
2956 g_object_set_valist (object, first_property_name, var_args);
2961 * g_object_get: (skip)
2962 * @object: (type GObject.Object): a #GObject
2963 * @first_property_name: name of the first property to get
2964 * @...: return location for the first property, followed optionally by more
2965 * name/return location pairs, followed by %NULL
2967 * Gets properties of an object.
2969 * In general, a copy is made of the property contents and the caller
2970 * is responsible for freeing the memory in the appropriate manner for
2971 * the type, for instance by calling g_free() or g_object_unref().
2973 * Here is an example of using g_object_get() to get the contents
2974 * of three properties: an integer, a string and an object:
2975 * |[<!-- language="C" -->
2977 * guint64 uint64val;
2981 * g_object_get (my_object,
2982 * "int-property", &intval,
2983 * "uint64-property", &uint64val,
2984 * "str-property", &strval,
2985 * "obj-property", &objval,
2988 * // Do something with intval, uint64val, strval, objval
2991 * g_object_unref (objval);
2995 g_object_get (gpointer _object,
2996 const gchar *first_property_name,
2999 GObject *object = _object;
3002 g_return_if_fail (G_IS_OBJECT (object));
3004 va_start (var_args, first_property_name);
3005 g_object_get_valist (object, first_property_name, var_args);
3010 * g_object_set_property:
3011 * @object: a #GObject
3012 * @property_name: the name of the property to set
3015 * Sets a property on an object.
3018 g_object_set_property (GObject *object,
3019 const gchar *property_name,
3020 const GValue *value)
3022 g_object_setv (object, 1, &property_name, value);
3026 * g_object_get_property:
3027 * @object: a #GObject
3028 * @property_name: the name of the property to get
3029 * @value: return location for the property value
3031 * Gets a property of an object.
3033 * The @value can be:
3035 * - an empty #GValue initialized by %G_VALUE_INIT, which will be
3036 * automatically initialized with the expected type of the property
3038 * - a #GValue initialized with the expected type of the property
3039 * - a #GValue initialized with a type to which the expected type
3040 * of the property can be transformed
3042 * In general, a copy is made of the property contents and the caller is
3043 * responsible for freeing the memory by calling g_value_unset().
3045 * Note that g_object_get_property() is really intended for language
3046 * bindings, g_object_get() is much more convenient for C programming.
3049 g_object_get_property (GObject *object,
3050 const gchar *property_name,
3055 g_return_if_fail (G_IS_OBJECT (object));
3056 g_return_if_fail (property_name != NULL);
3057 g_return_if_fail (value != NULL);
3059 g_object_ref (object);
3061 pspec = find_pspec (G_OBJECT_GET_CLASS (object), property_name);
3063 if (g_object_get_is_valid_property (object, pspec, property_name))
3065 GValue *prop_value, tmp_value = G_VALUE_INIT;
3067 if (G_VALUE_TYPE (value) == G_TYPE_INVALID)
3069 /* zero-initialized value */
3070 g_value_init (value, pspec->value_type);
3073 else if (G_VALUE_TYPE (value) == pspec->value_type)
3075 /* auto-conversion of the callers value type */
3076 g_value_reset (value);
3079 else if (!g_value_type_transformable (pspec->value_type, G_VALUE_TYPE (value)))
3081 g_critical ("%s: can't retrieve property '%s' of type '%s' as value of type '%s'",
3082 G_STRFUNC, pspec->name,
3083 g_type_name (pspec->value_type),
3084 G_VALUE_TYPE_NAME (value));
3085 g_object_unref (object);
3090 g_value_init (&tmp_value, pspec->value_type);
3091 prop_value = &tmp_value;
3093 object_get_property (object, pspec, prop_value);
3094 if (prop_value != value)
3096 g_value_transform (prop_value, value);
3097 g_value_unset (&tmp_value);
3101 g_object_unref (object);
3105 * g_object_connect: (skip)
3106 * @object: (type GObject.Object): a #GObject
3107 * @signal_spec: the spec for the first signal
3108 * @...: #GCallback for the first signal, followed by data for the
3109 * first signal, followed optionally by more signal
3110 * spec/callback/data triples, followed by %NULL
3112 * A convenience function to connect multiple signals at once.
3114 * The signal specs expected by this function have the form
3115 * "modifier::signal_name", where modifier can be one of the following:
3116 * - signal: equivalent to g_signal_connect_data (..., NULL, G_CONNECT_DEFAULT)
3117 * - object-signal, object_signal: equivalent to g_signal_connect_object (..., G_CONNECT_DEFAULT)
3118 * - swapped-signal, swapped_signal: equivalent to g_signal_connect_data (..., NULL, G_CONNECT_SWAPPED)
3119 * - swapped_object_signal, swapped-object-signal: equivalent to g_signal_connect_object (..., G_CONNECT_SWAPPED)
3120 * - signal_after, signal-after: equivalent to g_signal_connect_data (..., NULL, G_CONNECT_AFTER)
3121 * - object_signal_after, object-signal-after: equivalent to g_signal_connect_object (..., G_CONNECT_AFTER)
3122 * - swapped_signal_after, swapped-signal-after: equivalent to g_signal_connect_data (..., NULL, G_CONNECT_SWAPPED | G_CONNECT_AFTER)
3123 * - swapped_object_signal_after, swapped-object-signal-after: equivalent to g_signal_connect_object (..., G_CONNECT_SWAPPED | G_CONNECT_AFTER)
3125 * |[<!-- language="C" -->
3126 * menu->toplevel = g_object_connect (g_object_new (GTK_TYPE_WINDOW,
3127 * "type", GTK_WINDOW_POPUP,
3130 * "signal::event", gtk_menu_window_event, menu,
3131 * "signal::size_request", gtk_menu_window_size_request, menu,
3132 * "signal::destroy", gtk_widget_destroyed, &menu->toplevel,
3136 * Returns: (transfer none) (type GObject.Object): @object
3139 g_object_connect (gpointer _object,
3140 const gchar *signal_spec,
3143 GObject *object = _object;
3146 g_return_val_if_fail (G_IS_OBJECT (object), NULL);
3147 g_return_val_if_fail (object->ref_count > 0, object);
3149 va_start (var_args, signal_spec);
3152 GCallback callback = va_arg (var_args, GCallback);
3153 gpointer data = va_arg (var_args, gpointer);
3155 if (strncmp (signal_spec, "signal::", 8) == 0)
3156 g_signal_connect_data (object, signal_spec + 8,
3157 callback, data, NULL,
3159 else if (strncmp (signal_spec, "object_signal::", 15) == 0 ||
3160 strncmp (signal_spec, "object-signal::", 15) == 0)
3161 g_signal_connect_object (object, signal_spec + 15,
3164 else if (strncmp (signal_spec, "swapped_signal::", 16) == 0 ||
3165 strncmp (signal_spec, "swapped-signal::", 16) == 0)
3166 g_signal_connect_data (object, signal_spec + 16,
3167 callback, data, NULL,
3169 else if (strncmp (signal_spec, "swapped_object_signal::", 23) == 0 ||
3170 strncmp (signal_spec, "swapped-object-signal::", 23) == 0)
3171 g_signal_connect_object (object, signal_spec + 23,
3174 else if (strncmp (signal_spec, "signal_after::", 14) == 0 ||
3175 strncmp (signal_spec, "signal-after::", 14) == 0)
3176 g_signal_connect_data (object, signal_spec + 14,
3177 callback, data, NULL,
3179 else if (strncmp (signal_spec, "object_signal_after::", 21) == 0 ||
3180 strncmp (signal_spec, "object-signal-after::", 21) == 0)
3181 g_signal_connect_object (object, signal_spec + 21,
3184 else if (strncmp (signal_spec, "swapped_signal_after::", 22) == 0 ||
3185 strncmp (signal_spec, "swapped-signal-after::", 22) == 0)
3186 g_signal_connect_data (object, signal_spec + 22,
3187 callback, data, NULL,
3188 G_CONNECT_SWAPPED | G_CONNECT_AFTER);
3189 else if (strncmp (signal_spec, "swapped_object_signal_after::", 29) == 0 ||
3190 strncmp (signal_spec, "swapped-object-signal-after::", 29) == 0)
3191 g_signal_connect_object (object, signal_spec + 29,
3193 G_CONNECT_SWAPPED | G_CONNECT_AFTER);
3196 g_critical ("%s: invalid signal spec \"%s\"", G_STRFUNC, signal_spec);
3199 signal_spec = va_arg (var_args, gchar*);
3207 * g_object_disconnect: (skip)
3208 * @object: (type GObject.Object): a #GObject
3209 * @signal_spec: the spec for the first signal
3210 * @...: #GCallback for the first signal, followed by data for the first signal,
3211 * followed optionally by more signal spec/callback/data triples,
3214 * A convenience function to disconnect multiple signals at once.
3216 * The signal specs expected by this function have the form
3217 * "any_signal", which means to disconnect any signal with matching
3218 * callback and data, or "any_signal::signal_name", which only
3219 * disconnects the signal named "signal_name".
3222 g_object_disconnect (gpointer _object,
3223 const gchar *signal_spec,
3226 GObject *object = _object;
3229 g_return_if_fail (G_IS_OBJECT (object));
3230 g_return_if_fail (object->ref_count > 0);
3232 va_start (var_args, signal_spec);
3235 GCallback callback = va_arg (var_args, GCallback);
3236 gpointer data = va_arg (var_args, gpointer);
3237 guint sid = 0, detail = 0, mask = 0;
3239 if (strncmp (signal_spec, "any_signal::", 12) == 0 ||
3240 strncmp (signal_spec, "any-signal::", 12) == 0)
3243 mask = G_SIGNAL_MATCH_ID | G_SIGNAL_MATCH_FUNC | G_SIGNAL_MATCH_DATA;
3245 else if (strcmp (signal_spec, "any_signal") == 0 ||
3246 strcmp (signal_spec, "any-signal") == 0)
3249 mask = G_SIGNAL_MATCH_FUNC | G_SIGNAL_MATCH_DATA;
3253 g_critical ("%s: invalid signal spec \"%s\"", G_STRFUNC, signal_spec);
3257 if ((mask & G_SIGNAL_MATCH_ID) &&
3258 !g_signal_parse_name (signal_spec, G_OBJECT_TYPE (object), &sid, &detail, FALSE))
3259 g_critical ("%s: invalid signal name \"%s\"", G_STRFUNC, signal_spec);
3260 else if (!g_signal_handlers_disconnect_matched (object, mask | (detail ? G_SIGNAL_MATCH_DETAIL : 0),
3262 NULL, (gpointer)callback, data))
3263 g_critical ("%s: signal handler %p(%p) is not connected", G_STRFUNC, callback, data);
3264 signal_spec = va_arg (var_args, gchar*);
3275 } weak_refs[1]; /* flexible array */
3279 weak_refs_notify (gpointer data)
3281 WeakRefStack *wstack = data;
3284 for (i = 0; i < wstack->n_weak_refs; i++)
3285 wstack->weak_refs[i].notify (wstack->weak_refs[i].data, wstack->object);
3290 * g_object_weak_ref: (skip)
3291 * @object: #GObject to reference weakly
3292 * @notify: callback to invoke before the object is freed
3293 * @data: extra data to pass to notify
3295 * Adds a weak reference callback to an object. Weak references are
3296 * used for notification when an object is disposed. They are called
3297 * "weak references" because they allow you to safely hold a pointer
3298 * to an object without calling g_object_ref() (g_object_ref() adds a
3299 * strong reference, that is, forces the object to stay alive).
3301 * Note that the weak references created by this method are not
3302 * thread-safe: they cannot safely be used in one thread if the
3303 * object's last g_object_unref() might happen in another thread.
3304 * Use #GWeakRef if thread-safety is required.
3307 g_object_weak_ref (GObject *object,
3311 WeakRefStack *wstack;
3314 g_return_if_fail (G_IS_OBJECT (object));
3315 g_return_if_fail (notify != NULL);
3316 g_return_if_fail (g_atomic_int_get (&object->ref_count) >= 1);
3318 G_LOCK (weak_refs_mutex);
3319 wstack = g_datalist_id_remove_no_notify (&object->qdata, quark_weak_refs);
3322 i = wstack->n_weak_refs++;
3323 wstack = g_realloc (wstack, sizeof (*wstack) + sizeof (wstack->weak_refs[0]) * i);
3327 wstack = g_renew (WeakRefStack, NULL, 1);
3328 wstack->object = object;
3329 wstack->n_weak_refs = 1;
3332 wstack->weak_refs[i].notify = notify;
3333 wstack->weak_refs[i].data = data;
3334 g_datalist_id_set_data_full (&object->qdata, quark_weak_refs, wstack, weak_refs_notify);
3335 G_UNLOCK (weak_refs_mutex);
3339 * g_object_weak_unref: (skip)
3340 * @object: #GObject to remove a weak reference from
3341 * @notify: callback to search for
3342 * @data: data to search for
3344 * Removes a weak reference callback to an object.
3347 g_object_weak_unref (GObject *object,
3351 WeakRefStack *wstack;
3352 gboolean found_one = FALSE;
3354 g_return_if_fail (G_IS_OBJECT (object));
3355 g_return_if_fail (notify != NULL);
3357 G_LOCK (weak_refs_mutex);
3358 wstack = g_datalist_id_get_data (&object->qdata, quark_weak_refs);
3363 for (i = 0; i < wstack->n_weak_refs; i++)
3364 if (wstack->weak_refs[i].notify == notify &&
3365 wstack->weak_refs[i].data == data)
3368 wstack->n_weak_refs -= 1;
3369 if (i != wstack->n_weak_refs)
3370 wstack->weak_refs[i] = wstack->weak_refs[wstack->n_weak_refs];
3375 G_UNLOCK (weak_refs_mutex);
3377 g_critical ("%s: couldn't find weak ref %p(%p)", G_STRFUNC, notify, data);
3381 * g_object_add_weak_pointer: (skip)
3382 * @object: The object that should be weak referenced.
3383 * @weak_pointer_location: (inout) (not optional): The memory address
3386 * Adds a weak reference from weak_pointer to @object to indicate that
3387 * the pointer located at @weak_pointer_location is only valid during
3388 * the lifetime of @object. When the @object is finalized,
3389 * @weak_pointer will be set to %NULL.
3391 * Note that as with g_object_weak_ref(), the weak references created by
3392 * this method are not thread-safe: they cannot safely be used in one
3393 * thread if the object's last g_object_unref() might happen in another
3394 * thread. Use #GWeakRef if thread-safety is required.
3397 g_object_add_weak_pointer (GObject *object,
3398 gpointer *weak_pointer_location)
3400 g_return_if_fail (G_IS_OBJECT (object));
3401 g_return_if_fail (weak_pointer_location != NULL);
3403 g_object_weak_ref (object,
3404 (GWeakNotify) g_nullify_pointer,
3405 weak_pointer_location);
3409 * g_object_remove_weak_pointer: (skip)
3410 * @object: The object that is weak referenced.
3411 * @weak_pointer_location: (inout) (not optional): The memory address
3414 * Removes a weak reference from @object that was previously added
3415 * using g_object_add_weak_pointer(). The @weak_pointer_location has
3416 * to match the one used with g_object_add_weak_pointer().
3419 g_object_remove_weak_pointer (GObject *object,
3420 gpointer *weak_pointer_location)
3422 g_return_if_fail (G_IS_OBJECT (object));
3423 g_return_if_fail (weak_pointer_location != NULL);
3425 g_object_weak_unref (object,
3426 (GWeakNotify) g_nullify_pointer,
3427 weak_pointer_location);
3431 object_floating_flag_handler (GObject *object,
3437 case +1: /* force floating if possible */
3438 oldvalue = g_atomic_pointer_get (&object->qdata);
3439 while (!g_atomic_pointer_compare_and_exchange_full (
3440 (void**) &object->qdata, oldvalue,
3441 (void *) ((gsize) oldvalue | OBJECT_FLOATING_FLAG),
3444 return (gsize) oldvalue & OBJECT_FLOATING_FLAG;
3445 case -1: /* sink if possible */
3446 oldvalue = g_atomic_pointer_get (&object->qdata);
3447 while (!g_atomic_pointer_compare_and_exchange_full (
3448 (void**) &object->qdata, oldvalue,
3449 (void *) ((gsize) oldvalue & ~(gsize) OBJECT_FLOATING_FLAG),
3452 return (gsize) oldvalue & OBJECT_FLOATING_FLAG;
3453 default: /* check floating */
3454 return 0 != ((gsize) g_atomic_pointer_get (&object->qdata) & OBJECT_FLOATING_FLAG);
3459 * g_object_is_floating:
3460 * @object: (type GObject.Object): a #GObject
3462 * Checks whether @object has a [floating][floating-ref] reference.
3466 * Returns: %TRUE if @object has a floating reference
3469 g_object_is_floating (gpointer _object)
3471 GObject *object = _object;
3472 g_return_val_if_fail (G_IS_OBJECT (object), FALSE);
3473 return floating_flag_handler (object, 0);
3477 * g_object_ref_sink:
3478 * @object: (type GObject.Object): a #GObject
3480 * Increase the reference count of @object, and possibly remove the
3481 * [floating][floating-ref] reference, if @object has a floating reference.
3483 * In other words, if the object is floating, then this call "assumes
3484 * ownership" of the floating reference, converting it to a normal
3485 * reference by clearing the floating flag while leaving the reference
3486 * count unchanged. If the object is not floating, then this call
3487 * adds a new normal reference increasing the reference count by one.
3489 * Since GLib 2.56, the type of @object will be propagated to the return type
3490 * under the same conditions as for g_object_ref().
3494 * Returns: (type GObject.Object) (transfer none): @object
3497 (g_object_ref_sink) (gpointer _object)
3499 GObject *object = _object;
3500 gboolean was_floating;
3501 g_return_val_if_fail (G_IS_OBJECT (object), object);
3502 g_return_val_if_fail (g_atomic_int_get (&object->ref_count) >= 1, object);
3503 g_object_ref (object);
3504 was_floating = floating_flag_handler (object, -1);
3506 g_object_unref (object);
3511 * g_object_take_ref: (skip)
3512 * @object: (type GObject.Object): a #GObject
3514 * If @object is floating, sink it. Otherwise, do nothing.
3516 * In other words, this function will convert a floating reference (if
3517 * present) into a full reference.
3519 * Typically you want to use g_object_ref_sink() in order to
3520 * automatically do the correct thing with respect to floating or
3521 * non-floating references, but there is one specific scenario where
3522 * this function is helpful.
3524 * The situation where this function is helpful is when creating an API
3525 * that allows the user to provide a callback function that returns a
3526 * GObject. We certainly want to allow the user the flexibility to
3527 * return a non-floating reference from this callback (for the case
3528 * where the object that is being returned already exists).
3530 * At the same time, the API style of some popular GObject-based
3531 * libraries (such as Gtk) make it likely that for newly-created GObject
3532 * instances, the user can be saved some typing if they are allowed to
3533 * return a floating reference.
3535 * Using this function on the return value of the user's callback allows
3536 * the user to do whichever is more convenient for them. The caller will
3537 * alway receives exactly one full reference to the value: either the
3538 * one that was returned in the first place, or a floating reference
3539 * that has been converted to a full reference.
3541 * This function has an odd interaction when combined with
3542 * g_object_ref_sink() running at the same time in another thread on
3543 * the same #GObject instance. If g_object_ref_sink() runs first then
3544 * the result will be that the floating reference is converted to a hard
3545 * reference. If g_object_take_ref() runs first then the result will be
3546 * that the floating reference is converted to a hard reference and an
3547 * additional reference on top of that one is added. It is best to avoid
3552 * Returns: (type GObject.Object) (transfer full): @object
3555 g_object_take_ref (gpointer _object)
3557 GObject *object = _object;
3558 g_return_val_if_fail (G_IS_OBJECT (object), object);
3559 g_return_val_if_fail (g_atomic_int_get (&object->ref_count) >= 1, object);
3561 floating_flag_handler (object, -1);
3567 * g_object_force_floating:
3568 * @object: a #GObject
3570 * This function is intended for #GObject implementations to re-enforce
3571 * a [floating][floating-ref] object reference. Doing this is seldom
3572 * required: all #GInitiallyUnowneds are created with a floating reference
3573 * which usually just needs to be sunken by calling g_object_ref_sink().
3578 g_object_force_floating (GObject *object)
3580 g_return_if_fail (G_IS_OBJECT (object));
3581 g_return_if_fail (g_atomic_int_get (&object->ref_count) >= 1);
3583 floating_flag_handler (object, +1);
3588 guint n_toggle_refs;
3590 GToggleNotify notify;
3592 } toggle_refs[1]; /* flexible array */
3596 toggle_refs_notify (GObject *object,
3597 gboolean is_last_ref)
3599 ToggleRefStack tstack, *tstackptr;
3601 G_LOCK (toggle_refs_mutex);
3602 /* If another thread removed the toggle reference on the object, while
3603 * we were waiting here, there's nothing to notify.
3604 * So let's check again if the object has toggle reference and in case return.
3606 if (!OBJECT_HAS_TOGGLE_REF (object))
3608 G_UNLOCK (toggle_refs_mutex);
3612 tstackptr = g_datalist_id_get_data (&object->qdata, quark_toggle_refs);
3613 tstack = *tstackptr;
3614 G_UNLOCK (toggle_refs_mutex);
3616 /* Reentrancy here is not as tricky as it seems, because a toggle reference
3617 * will only be notified when there is exactly one of them.
3619 g_assert (tstack.n_toggle_refs == 1);
3620 tstack.toggle_refs[0].notify (tstack.toggle_refs[0].data, tstack.object, is_last_ref);
3624 * g_object_add_toggle_ref: (skip)
3625 * @object: a #GObject
3626 * @notify: a function to call when this reference is the
3627 * last reference to the object, or is no longer
3628 * the last reference.
3629 * @data: data to pass to @notify
3631 * Increases the reference count of the object by one and sets a
3632 * callback to be called when all other references to the object are
3633 * dropped, or when this is already the last reference to the object
3634 * and another reference is established.
3636 * This functionality is intended for binding @object to a proxy
3637 * object managed by another memory manager. This is done with two
3638 * paired references: the strong reference added by
3639 * g_object_add_toggle_ref() and a reverse reference to the proxy
3640 * object which is either a strong reference or weak reference.
3642 * The setup is that when there are no other references to @object,
3643 * only a weak reference is held in the reverse direction from @object
3644 * to the proxy object, but when there are other references held to
3645 * @object, a strong reference is held. The @notify callback is called
3646 * when the reference from @object to the proxy object should be
3647 * "toggled" from strong to weak (@is_last_ref true) or weak to strong
3648 * (@is_last_ref false).
3650 * Since a (normal) reference must be held to the object before
3651 * calling g_object_add_toggle_ref(), the initial state of the reverse
3652 * link is always strong.
3654 * Multiple toggle references may be added to the same gobject,
3655 * however if there are multiple toggle references to an object, none
3656 * of them will ever be notified until all but one are removed. For
3657 * this reason, you should only ever use a toggle reference if there
3658 * is important state in the proxy object.
3663 g_object_add_toggle_ref (GObject *object,
3664 GToggleNotify notify,
3667 ToggleRefStack *tstack;
3670 g_return_if_fail (G_IS_OBJECT (object));
3671 g_return_if_fail (notify != NULL);
3672 g_return_if_fail (g_atomic_int_get (&object->ref_count) >= 1);
3674 g_object_ref (object);
3676 G_LOCK (toggle_refs_mutex);
3677 tstack = g_datalist_id_remove_no_notify (&object->qdata, quark_toggle_refs);
3680 i = tstack->n_toggle_refs++;
3681 /* allocate i = tstate->n_toggle_refs - 1 positions beyond the 1 declared
3682 * in tstate->toggle_refs */
3683 tstack = g_realloc (tstack, sizeof (*tstack) + sizeof (tstack->toggle_refs[0]) * i);
3687 tstack = g_renew (ToggleRefStack, NULL, 1);
3688 tstack->object = object;
3689 tstack->n_toggle_refs = 1;
3693 /* Set a flag for fast lookup after adding the first toggle reference */
3694 if (tstack->n_toggle_refs == 1)
3695 g_datalist_set_flags (&object->qdata, OBJECT_HAS_TOGGLE_REF_FLAG);
3697 tstack->toggle_refs[i].notify = notify;
3698 tstack->toggle_refs[i].data = data;
3699 g_datalist_id_set_data_full (&object->qdata, quark_toggle_refs, tstack,
3700 (GDestroyNotify)g_free);
3701 G_UNLOCK (toggle_refs_mutex);
3705 * g_object_remove_toggle_ref: (skip)
3706 * @object: a #GObject
3707 * @notify: a function to call when this reference is the
3708 * last reference to the object, or is no longer
3709 * the last reference.
3710 * @data: (nullable): data to pass to @notify, or %NULL to
3711 * match any toggle refs with the @notify argument.
3713 * Removes a reference added with g_object_add_toggle_ref(). The
3714 * reference count of the object is decreased by one.
3719 g_object_remove_toggle_ref (GObject *object,
3720 GToggleNotify notify,
3723 ToggleRefStack *tstack;
3724 gboolean found_one = FALSE;
3726 g_return_if_fail (G_IS_OBJECT (object));
3727 g_return_if_fail (notify != NULL);
3729 G_LOCK (toggle_refs_mutex);
3730 tstack = g_datalist_id_get_data (&object->qdata, quark_toggle_refs);
3735 for (i = 0; i < tstack->n_toggle_refs; i++)
3736 if (tstack->toggle_refs[i].notify == notify &&
3737 (tstack->toggle_refs[i].data == data || data == NULL))
3740 tstack->n_toggle_refs -= 1;
3741 if (i != tstack->n_toggle_refs)
3742 tstack->toggle_refs[i] = tstack->toggle_refs[tstack->n_toggle_refs];
3744 if (tstack->n_toggle_refs == 0)
3745 g_datalist_unset_flags (&object->qdata, OBJECT_HAS_TOGGLE_REF_FLAG);
3750 G_UNLOCK (toggle_refs_mutex);
3753 g_object_unref (object);
3755 g_critical ("%s: couldn't find toggle ref %p(%p)", G_STRFUNC, notify, data);
3760 * @object: (type GObject.Object): a #GObject
3762 * Increases the reference count of @object.
3764 * Since GLib 2.56, if `GLIB_VERSION_MAX_ALLOWED` is 2.56 or greater, the type
3765 * of @object will be propagated to the return type (using the GCC typeof()
3766 * extension), so any casting the caller needs to do on the return type must be
3769 * Returns: (type GObject.Object) (transfer none): the same @object
3772 (g_object_ref) (gpointer _object)
3774 GObject *object = _object;
3776 gboolean object_already_finalized;
3778 g_return_val_if_fail (G_IS_OBJECT (object), NULL);
3780 old_val = g_atomic_int_add (&object->ref_count, 1);
3781 object_already_finalized = (old_val <= 0);
3782 g_return_val_if_fail (!object_already_finalized, NULL);
3784 if (old_val == 1 && OBJECT_HAS_TOGGLE_REF (object))
3785 toggle_refs_notify (object, FALSE);
3787 TRACE (GOBJECT_OBJECT_REF(object,G_TYPE_FROM_INSTANCE(object),old_val));
3794 * @object: (type GObject.Object): a #GObject
3796 * Decreases the reference count of @object. When its reference count
3797 * drops to 0, the object is finalized (i.e. its memory is freed).
3799 * If the pointer to the #GObject may be reused in future (for example, if it is
3800 * an instance variable of another object), it is recommended to clear the
3801 * pointer to %NULL rather than retain a dangling pointer to a potentially
3802 * invalid #GObject instance. Use g_clear_object() for this.
3805 g_object_unref (gpointer _object)
3807 GObject *object = _object;
3810 g_return_if_fail (G_IS_OBJECT (object));
3812 /* here we want to atomically do: if (ref_count>1) { ref_count--; return; } */
3813 old_ref = g_atomic_int_get (&object->ref_count);
3814 retry_atomic_decrement1:
3817 /* valid if last 2 refs are owned by this call to unref and the toggle_ref */
3819 if (!g_atomic_int_compare_and_exchange_full ((int *)&object->ref_count,
3820 old_ref, old_ref - 1,
3824 TRACE (GOBJECT_OBJECT_UNREF(object,G_TYPE_FROM_INSTANCE(object),old_ref));
3826 /* if we went from 2->1 we need to notify toggle refs if any */
3827 if (old_ref == 2 && OBJECT_HAS_TOGGLE_REF (object))
3829 /* The last ref being held in this case is owned by the toggle_ref */
3830 toggle_refs_notify (object, TRUE);
3837 GSList **weak_locations;
3838 GObjectNotifyQueue *nqueue;
3840 /* The only way that this object can live at this point is if
3841 * there are outstanding weak references already established
3842 * before we got here.
3844 * If there were not already weak references then no more can be
3845 * established at this time, because the other thread would have
3846 * to hold a strong ref in order to call
3847 * g_object_add_weak_pointer() and then we wouldn't be here.
3849 * Other GWeakRef's (weak locations) instead may still be added
3850 * before the object is finalized, but in such case we'll unset
3851 * them as part of the qdata removal.
3853 weak_locations = g_datalist_id_get_data (&object->qdata, quark_weak_locations);
3855 if (weak_locations != NULL)
3857 g_rw_lock_writer_lock (&weak_locations_lock);
3859 /* It is possible that one of the weak references beat us to
3860 * the lock. Make sure the refcount is still what we expected
3863 old_ref = g_atomic_int_get (&object->ref_count);
3866 g_rw_lock_writer_unlock (&weak_locations_lock);
3867 goto retry_atomic_decrement1;
3870 /* We got the lock first, so the object will definitely die
3871 * now. Clear out all the weak references, if they're still set.
3873 weak_locations = g_datalist_id_remove_no_notify (&object->qdata,
3874 quark_weak_locations);
3875 g_clear_pointer (&weak_locations, weak_locations_free_unlocked);
3877 g_rw_lock_writer_unlock (&weak_locations_lock);
3880 /* freeze the notification queue, so we don't accidentally emit
3881 * notifications during dispose() and finalize().
3883 * The notification queue stays frozen unless the instance acquires
3884 * a reference during dispose(), in which case we thaw it and
3885 * dispatch all the notifications. If the instance gets through
3886 * to finalize(), the notification queue gets automatically
3887 * drained when g_object_finalize() is reached and
3888 * the qdata is cleared.
3890 nqueue = g_object_notify_queue_freeze (object, FALSE);
3892 /* we are about to remove the last reference */
3893 TRACE (GOBJECT_OBJECT_DISPOSE(object,G_TYPE_FROM_INSTANCE(object), 1));
3894 G_OBJECT_GET_CLASS (object)->dispose (object);
3895 TRACE (GOBJECT_OBJECT_DISPOSE_END(object,G_TYPE_FROM_INSTANCE(object), 1));
3897 /* may have been re-referenced meanwhile */
3898 old_ref = g_atomic_int_get ((int *)&object->ref_count);
3902 /* valid if last 2 refs are owned by this call to unref and the toggle_ref */
3904 if (!g_atomic_int_compare_and_exchange_full ((int *)&object->ref_count,
3905 old_ref, old_ref - 1,
3909 TRACE (GOBJECT_OBJECT_UNREF (object, G_TYPE_FROM_INSTANCE (object), old_ref));
3911 /* emit all notifications that have been queued during dispose() */
3912 g_object_notify_queue_thaw (object, nqueue);
3914 /* if we went from 2->1 we need to notify toggle refs if any */
3915 if (old_ref == 2 && OBJECT_HAS_TOGGLE_REF (object) &&
3916 g_atomic_int_get ((int *)&object->ref_count) == 1)
3918 /* The last ref being held in this case is owned by the toggle_ref */
3919 toggle_refs_notify (object, TRUE);
3925 /* we are still in the process of taking away the last ref */
3926 g_datalist_id_set_data (&object->qdata, quark_closure_array, NULL);
3927 g_signal_handlers_destroy (object);
3928 g_datalist_id_set_data (&object->qdata, quark_weak_refs, NULL);
3929 g_datalist_id_set_data (&object->qdata, quark_weak_locations, NULL);
3931 /* decrement the last reference */
3932 old_ref = g_atomic_int_add (&object->ref_count, -1);
3933 g_return_if_fail (old_ref > 0);
3935 TRACE (GOBJECT_OBJECT_UNREF(object,G_TYPE_FROM_INSTANCE(object),old_ref));
3937 /* may have been re-referenced meanwhile */
3938 if (G_LIKELY (old_ref == 1))
3940 TRACE (GOBJECT_OBJECT_FINALIZE(object,G_TYPE_FROM_INSTANCE(object)));
3941 G_OBJECT_GET_CLASS (object)->finalize (object);
3942 TRACE (GOBJECT_OBJECT_FINALIZE_END(object,G_TYPE_FROM_INSTANCE(object)));
3944 GOBJECT_IF_DEBUG (OBJECTS,
3946 gboolean was_present;
3948 /* catch objects not chaining finalize handlers */
3949 G_LOCK (debug_objects);
3950 was_present = g_hash_table_remove (debug_objects_ht, object);
3951 G_UNLOCK (debug_objects);
3954 g_critical ("Object %p of type %s not finalized correctly.",
3955 object, G_OBJECT_TYPE_NAME (object));
3957 g_type_free_instance ((GTypeInstance*) object);
3961 /* The instance acquired a reference between dispose() and
3962 * finalize(), so we need to thaw the notification queue
3964 g_object_notify_queue_thaw (object, nqueue);
3970 * g_clear_object: (skip)
3971 * @object_ptr: a pointer to a #GObject reference
3973 * Clears a reference to a #GObject.
3975 * @object_ptr must not be %NULL.
3977 * If the reference is %NULL then this function does nothing.
3978 * Otherwise, the reference count of the object is decreased and the
3979 * pointer is set to %NULL.
3981 * A macro is also included that allows this function to be used without
3986 #undef g_clear_object
3988 g_clear_object (GObject **object_ptr)
3990 g_clear_pointer (object_ptr, g_object_unref);
3994 * g_object_get_qdata:
3995 * @object: The GObject to get a stored user data pointer from
3996 * @quark: A #GQuark, naming the user data pointer
3998 * This function gets back user data pointers stored via
3999 * g_object_set_qdata().
4001 * Returns: (transfer none) (nullable): The user data pointer set, or %NULL
4004 g_object_get_qdata (GObject *object,
4007 g_return_val_if_fail (G_IS_OBJECT (object), NULL);
4009 return quark ? g_datalist_id_get_data (&object->qdata, quark) : NULL;
4013 * g_object_set_qdata: (skip)
4014 * @object: The GObject to set store a user data pointer
4015 * @quark: A #GQuark, naming the user data pointer
4016 * @data: (nullable): An opaque user data pointer
4018 * This sets an opaque, named pointer on an object.
4019 * The name is specified through a #GQuark (retrieved e.g. via
4020 * g_quark_from_static_string()), and the pointer
4021 * can be gotten back from the @object with g_object_get_qdata()
4022 * until the @object is finalized.
4023 * Setting a previously set user data pointer, overrides (frees)
4024 * the old pointer set, using #NULL as pointer essentially
4025 * removes the data stored.
4028 g_object_set_qdata (GObject *object,
4032 g_return_if_fail (G_IS_OBJECT (object));
4033 g_return_if_fail (quark > 0);
4035 g_datalist_id_set_data (&object->qdata, quark, data);
4039 * g_object_dup_qdata: (skip)
4040 * @object: the #GObject to store user data on
4041 * @quark: a #GQuark, naming the user data pointer
4042 * @dup_func: (nullable): function to dup the value
4043 * @user_data: (nullable): passed as user_data to @dup_func
4045 * This is a variant of g_object_get_qdata() which returns
4046 * a 'duplicate' of the value. @dup_func defines the
4047 * meaning of 'duplicate' in this context, it could e.g.
4048 * take a reference on a ref-counted object.
4050 * If the @quark is not set on the object then @dup_func
4051 * will be called with a %NULL argument.
4053 * Note that @dup_func is called while user data of @object
4056 * This function can be useful to avoid races when multiple
4057 * threads are using object data on the same key on the same
4060 * Returns: the result of calling @dup_func on the value
4061 * associated with @quark on @object, or %NULL if not set.
4062 * If @dup_func is %NULL, the value is returned
4068 g_object_dup_qdata (GObject *object,
4070 GDuplicateFunc dup_func,
4073 g_return_val_if_fail (G_IS_OBJECT (object), NULL);
4074 g_return_val_if_fail (quark > 0, NULL);
4076 return g_datalist_id_dup_data (&object->qdata, quark, dup_func, user_data);
4080 * g_object_replace_qdata: (skip)
4081 * @object: the #GObject to store user data on
4082 * @quark: a #GQuark, naming the user data pointer
4083 * @oldval: (nullable): the old value to compare against
4084 * @newval: (nullable): the new value
4085 * @destroy: (nullable): a destroy notify for the new value
4086 * @old_destroy: (out) (optional): destroy notify for the existing value
4088 * Compares the user data for the key @quark on @object with
4089 * @oldval, and if they are the same, replaces @oldval with
4092 * This is like a typical atomic compare-and-exchange
4093 * operation, for user data on an object.
4095 * If the previous value was replaced then ownership of the
4096 * old value (@oldval) is passed to the caller, including
4097 * the registered destroy notify for it (passed out in @old_destroy).
4098 * It’s up to the caller to free this as needed, which may
4099 * or may not include using @old_destroy as sometimes replacement
4100 * should not destroy the object in the normal way.
4102 * Returns: %TRUE if the existing value for @quark was replaced
4103 * by @newval, %FALSE otherwise.
4108 g_object_replace_qdata (GObject *object,
4112 GDestroyNotify destroy,
4113 GDestroyNotify *old_destroy)
4115 g_return_val_if_fail (G_IS_OBJECT (object), FALSE);
4116 g_return_val_if_fail (quark > 0, FALSE);
4118 return g_datalist_id_replace_data (&object->qdata, quark,
4119 oldval, newval, destroy,
4124 * g_object_set_qdata_full: (skip)
4125 * @object: The GObject to set store a user data pointer
4126 * @quark: A #GQuark, naming the user data pointer
4127 * @data: (nullable): An opaque user data pointer
4128 * @destroy: (nullable): Function to invoke with @data as argument, when @data
4131 * This function works like g_object_set_qdata(), but in addition,
4132 * a void (*destroy) (gpointer) function may be specified which is
4133 * called with @data as argument when the @object is finalized, or
4134 * the data is being overwritten by a call to g_object_set_qdata()
4135 * with the same @quark.
4138 g_object_set_qdata_full (GObject *object,
4141 GDestroyNotify destroy)
4143 g_return_if_fail (G_IS_OBJECT (object));
4144 g_return_if_fail (quark > 0);
4146 g_datalist_id_set_data_full (&object->qdata, quark, data,
4147 data ? destroy : (GDestroyNotify) NULL);
4151 * g_object_steal_qdata:
4152 * @object: The GObject to get a stored user data pointer from
4153 * @quark: A #GQuark, naming the user data pointer
4155 * This function gets back user data pointers stored via
4156 * g_object_set_qdata() and removes the @data from object
4157 * without invoking its destroy() function (if any was
4159 * Usually, calling this function is only required to update
4160 * user data pointers with a destroy notifier, for example:
4161 * |[<!-- language="C" -->
4163 * object_add_to_user_list (GObject *object,
4164 * const gchar *new_string)
4166 * // the quark, naming the object data
4167 * GQuark quark_string_list = g_quark_from_static_string ("my-string-list");
4168 * // retrieve the old string list
4169 * GList *list = g_object_steal_qdata (object, quark_string_list);
4171 * // prepend new string
4172 * list = g_list_prepend (list, g_strdup (new_string));
4173 * // this changed 'list', so we need to set it again
4174 * g_object_set_qdata_full (object, quark_string_list, list, free_string_list);
4177 * free_string_list (gpointer data)
4179 * GList *node, *list = data;
4181 * for (node = list; node; node = node->next)
4182 * g_free (node->data);
4183 * g_list_free (list);
4186 * Using g_object_get_qdata() in the above example, instead of
4187 * g_object_steal_qdata() would have left the destroy function set,
4188 * and thus the partial string list would have been freed upon
4189 * g_object_set_qdata_full().
4191 * Returns: (transfer full) (nullable): The user data pointer set, or %NULL
4194 g_object_steal_qdata (GObject *object,
4197 g_return_val_if_fail (G_IS_OBJECT (object), NULL);
4198 g_return_val_if_fail (quark > 0, NULL);
4200 return g_datalist_id_remove_no_notify (&object->qdata, quark);
4204 * g_object_get_data:
4205 * @object: #GObject containing the associations
4206 * @key: name of the key for that association
4208 * Gets a named field from the objects table of associations (see g_object_set_data()).
4210 * Returns: (transfer none) (nullable): the data if found,
4211 * or %NULL if no such data exists.
4214 g_object_get_data (GObject *object,
4217 g_return_val_if_fail (G_IS_OBJECT (object), NULL);
4218 g_return_val_if_fail (key != NULL, NULL);
4220 return g_datalist_get_data (&object->qdata, key);
4224 * g_object_set_data:
4225 * @object: #GObject containing the associations.
4226 * @key: name of the key
4227 * @data: (nullable): data to associate with that key
4229 * Each object carries around a table of associations from
4230 * strings to pointers. This function lets you set an association.
4232 * If the object already had an association with that name,
4233 * the old association will be destroyed.
4235 * Internally, the @key is converted to a #GQuark using g_quark_from_string().
4236 * This means a copy of @key is kept permanently (even after @object has been
4237 * finalized) — so it is recommended to only use a small, bounded set of values
4238 * for @key in your program, to avoid the #GQuark storage growing unbounded.
4241 g_object_set_data (GObject *object,
4245 g_return_if_fail (G_IS_OBJECT (object));
4246 g_return_if_fail (key != NULL);
4248 g_datalist_id_set_data (&object->qdata, g_quark_from_string (key), data);
4252 * g_object_dup_data: (skip)
4253 * @object: the #GObject to store user data on
4254 * @key: a string, naming the user data pointer
4255 * @dup_func: (nullable): function to dup the value
4256 * @user_data: (nullable): passed as user_data to @dup_func
4258 * This is a variant of g_object_get_data() which returns
4259 * a 'duplicate' of the value. @dup_func defines the
4260 * meaning of 'duplicate' in this context, it could e.g.
4261 * take a reference on a ref-counted object.
4263 * If the @key is not set on the object then @dup_func
4264 * will be called with a %NULL argument.
4266 * Note that @dup_func is called while user data of @object
4269 * This function can be useful to avoid races when multiple
4270 * threads are using object data on the same key on the same
4273 * Returns: the result of calling @dup_func on the value
4274 * associated with @key on @object, or %NULL if not set.
4275 * If @dup_func is %NULL, the value is returned
4281 g_object_dup_data (GObject *object,
4283 GDuplicateFunc dup_func,
4286 g_return_val_if_fail (G_IS_OBJECT (object), NULL);
4287 g_return_val_if_fail (key != NULL, NULL);
4289 return g_datalist_id_dup_data (&object->qdata,
4290 g_quark_from_string (key),
4291 dup_func, user_data);
4295 * g_object_replace_data: (skip)
4296 * @object: the #GObject to store user data on
4297 * @key: a string, naming the user data pointer
4298 * @oldval: (nullable): the old value to compare against
4299 * @newval: (nullable): the new value
4300 * @destroy: (nullable): a destroy notify for the new value
4301 * @old_destroy: (out) (optional): destroy notify for the existing value
4303 * Compares the user data for the key @key on @object with
4304 * @oldval, and if they are the same, replaces @oldval with
4307 * This is like a typical atomic compare-and-exchange
4308 * operation, for user data on an object.
4310 * If the previous value was replaced then ownership of the
4311 * old value (@oldval) is passed to the caller, including
4312 * the registered destroy notify for it (passed out in @old_destroy).
4313 * It’s up to the caller to free this as needed, which may
4314 * or may not include using @old_destroy as sometimes replacement
4315 * should not destroy the object in the normal way.
4317 * See g_object_set_data() for guidance on using a small, bounded set of values
4320 * Returns: %TRUE if the existing value for @key was replaced
4321 * by @newval, %FALSE otherwise.
4326 g_object_replace_data (GObject *object,
4330 GDestroyNotify destroy,
4331 GDestroyNotify *old_destroy)
4333 g_return_val_if_fail (G_IS_OBJECT (object), FALSE);
4334 g_return_val_if_fail (key != NULL, FALSE);
4336 return g_datalist_id_replace_data (&object->qdata,
4337 g_quark_from_string (key),
4338 oldval, newval, destroy,
4343 * g_object_set_data_full: (skip)
4344 * @object: #GObject containing the associations
4345 * @key: name of the key
4346 * @data: (nullable): data to associate with that key
4347 * @destroy: (nullable): function to call when the association is destroyed
4349 * Like g_object_set_data() except it adds notification
4350 * for when the association is destroyed, either by setting it
4351 * to a different value or when the object is destroyed.
4353 * Note that the @destroy callback is not called if @data is %NULL.
4356 g_object_set_data_full (GObject *object,
4359 GDestroyNotify destroy)
4361 g_return_if_fail (G_IS_OBJECT (object));
4362 g_return_if_fail (key != NULL);
4364 g_datalist_id_set_data_full (&object->qdata, g_quark_from_string (key), data,
4365 data ? destroy : (GDestroyNotify) NULL);
4369 * g_object_steal_data:
4370 * @object: #GObject containing the associations
4371 * @key: name of the key
4373 * Remove a specified datum from the object's data associations,
4374 * without invoking the association's destroy handler.
4376 * Returns: (transfer full) (nullable): the data if found, or %NULL
4377 * if no such data exists.
4380 g_object_steal_data (GObject *object,
4385 g_return_val_if_fail (G_IS_OBJECT (object), NULL);
4386 g_return_val_if_fail (key != NULL, NULL);
4388 quark = g_quark_try_string (key);
4390 return quark ? g_datalist_id_remove_no_notify (&object->qdata, quark) : NULL;
4394 g_value_object_init (GValue *value)
4396 value->data[0].v_pointer = NULL;
4400 g_value_object_free_value (GValue *value)
4402 g_clear_object ((GObject**) &value->data[0].v_pointer);
4406 g_value_object_copy_value (const GValue *src_value,
4409 g_set_object ((GObject**) &dest_value->data[0].v_pointer,
4410 src_value->data[0].v_pointer);
4414 g_value_object_transform_value (const GValue *src_value,
4417 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)))
4418 dest_value->data[0].v_pointer = g_object_ref (src_value->data[0].v_pointer);
4420 dest_value->data[0].v_pointer = NULL;
4424 g_value_object_peek_pointer (const GValue *value)
4426 return value->data[0].v_pointer;
4430 g_value_object_collect_value (GValue *value,
4431 guint n_collect_values,
4432 GTypeCValue *collect_values,
4433 guint collect_flags)
4435 if (collect_values[0].v_pointer)
4437 GObject *object = collect_values[0].v_pointer;
4439 if (object->g_type_instance.g_class == NULL)
4440 return g_strconcat ("invalid unclassed object pointer for value type '",
4441 G_VALUE_TYPE_NAME (value),
4444 else if (!g_value_type_compatible (G_OBJECT_TYPE (object), G_VALUE_TYPE (value)))
4445 return g_strconcat ("invalid object type '",
4446 G_OBJECT_TYPE_NAME (object),
4447 "' for value type '",
4448 G_VALUE_TYPE_NAME (value),
4451 /* never honour G_VALUE_NOCOPY_CONTENTS for ref-counted types */
4452 value->data[0].v_pointer = g_object_ref (object);
4455 value->data[0].v_pointer = NULL;
4461 g_value_object_lcopy_value (const GValue *value,
4462 guint n_collect_values,
4463 GTypeCValue *collect_values,
4464 guint collect_flags)
4466 GObject **object_p = collect_values[0].v_pointer;
4468 g_return_val_if_fail (object_p != NULL, g_strdup_printf ("value location for '%s' passed as NULL", G_VALUE_TYPE_NAME (value)));
4470 if (!value->data[0].v_pointer)
4472 else if (collect_flags & G_VALUE_NOCOPY_CONTENTS)
4473 *object_p = value->data[0].v_pointer;
4475 *object_p = g_object_ref (value->data[0].v_pointer);
4481 * g_value_set_object:
4482 * @value: a valid #GValue of %G_TYPE_OBJECT derived type
4483 * @v_object: (type GObject.Object) (nullable): object value to be set
4485 * Set the contents of a %G_TYPE_OBJECT derived #GValue to @v_object.
4487 * g_value_set_object() increases the reference count of @v_object
4488 * (the #GValue holds a reference to @v_object). If you do not wish
4489 * to increase the reference count of the object (i.e. you wish to
4490 * pass your current reference to the #GValue because you no longer
4491 * need it), use g_value_take_object() instead.
4493 * It is important that your #GValue holds a reference to @v_object (either its
4494 * own, or one it has taken) to ensure that the object won't be destroyed while
4495 * the #GValue still exists).
4498 g_value_set_object (GValue *value,
4503 g_return_if_fail (G_VALUE_HOLDS_OBJECT (value));
4505 if G_UNLIKELY (value->data[0].v_pointer == v_object)
4508 old = g_steal_pointer (&value->data[0].v_pointer);
4512 g_return_if_fail (G_IS_OBJECT (v_object));
4513 g_return_if_fail (g_value_type_compatible (G_OBJECT_TYPE (v_object), G_VALUE_TYPE (value)));
4515 value->data[0].v_pointer = g_object_ref (v_object);
4518 g_clear_object (&old);
4522 * g_value_set_object_take_ownership: (skip)
4523 * @value: a valid #GValue of %G_TYPE_OBJECT derived type
4524 * @v_object: (nullable): object value to be set
4526 * This is an internal function introduced mainly for C marshallers.
4528 * Deprecated: 2.4: Use g_value_take_object() instead.
4531 g_value_set_object_take_ownership (GValue *value,
4534 g_value_take_object (value, v_object);
4538 * g_value_take_object: (skip)
4539 * @value: a valid #GValue of %G_TYPE_OBJECT derived type
4540 * @v_object: (nullable): object value to be set
4542 * Sets the contents of a %G_TYPE_OBJECT derived #GValue to @v_object
4543 * and takes over the ownership of the caller’s reference to @v_object;
4544 * the caller doesn’t have to unref it any more (i.e. the reference
4545 * count of the object is not increased).
4547 * If you want the #GValue to hold its own reference to @v_object, use
4548 * g_value_set_object() instead.
4553 g_value_take_object (GValue *value,
4556 g_return_if_fail (G_VALUE_HOLDS_OBJECT (value));
4558 g_clear_object ((GObject **) &value->data[0].v_pointer);
4562 g_return_if_fail (G_IS_OBJECT (v_object));
4563 g_return_if_fail (g_value_type_compatible (G_OBJECT_TYPE (v_object), G_VALUE_TYPE (value)));
4565 value->data[0].v_pointer = g_steal_pointer (&v_object);
4570 * g_value_get_object:
4571 * @value: a valid #GValue of %G_TYPE_OBJECT derived type
4573 * Get the contents of a %G_TYPE_OBJECT derived #GValue.
4575 * Returns: (type GObject.Object) (transfer none) (nullable): object contents of @value
4578 g_value_get_object (const GValue *value)
4580 g_return_val_if_fail (G_VALUE_HOLDS_OBJECT (value), NULL);
4582 return value->data[0].v_pointer;
4586 * g_value_dup_object:
4587 * @value: a valid #GValue whose type is derived from %G_TYPE_OBJECT
4589 * Get the contents of a %G_TYPE_OBJECT derived #GValue, increasing
4590 * its reference count. If the contents of the #GValue are %NULL, then
4591 * %NULL will be returned.
4593 * Returns: (type GObject.Object) (transfer full) (nullable): object content of @value,
4594 * should be unreferenced when no longer needed.
4597 g_value_dup_object (const GValue *value)
4599 g_return_val_if_fail (G_VALUE_HOLDS_OBJECT (value), NULL);
4601 return value->data[0].v_pointer ? g_object_ref (value->data[0].v_pointer) : NULL;
4605 * g_signal_connect_object: (skip)
4606 * @instance: (type GObject.TypeInstance): the instance to connect to.
4607 * @detailed_signal: a string of the form "signal-name::detail".
4608 * @c_handler: the #GCallback to connect.
4609 * @gobject: (type GObject.Object) (nullable): the object to pass as data
4611 * @connect_flags: a combination of #GConnectFlags.
4613 * This is similar to g_signal_connect_data(), but uses a closure which
4614 * ensures that the @gobject stays alive during the call to @c_handler
4615 * by temporarily adding a reference count to @gobject.
4617 * When the @gobject is destroyed the signal handler will be automatically
4618 * disconnected. Note that this is not currently threadsafe (ie:
4619 * emitting a signal while @gobject is being destroyed in another thread
4622 * Returns: the handler id.
4625 g_signal_connect_object (gpointer instance,
4626 const gchar *detailed_signal,
4627 GCallback c_handler,
4629 GConnectFlags connect_flags)
4631 g_return_val_if_fail (G_TYPE_CHECK_INSTANCE (instance), 0);
4632 g_return_val_if_fail (detailed_signal != NULL, 0);
4633 g_return_val_if_fail (c_handler != NULL, 0);
4639 g_return_val_if_fail (G_IS_OBJECT (gobject), 0);
4641 closure = ((connect_flags & G_CONNECT_SWAPPED) ? g_cclosure_new_object_swap : g_cclosure_new_object) (c_handler, gobject);
4643 return g_signal_connect_closure (instance, detailed_signal, closure, connect_flags & G_CONNECT_AFTER);
4646 return g_signal_connect_data (instance, detailed_signal, c_handler, NULL, NULL, connect_flags);
4652 GClosure *closures[1]; /* flexible array */
4654 /* don't change this structure without supplying an accessor for
4655 * watched closures, e.g.:
4656 * GSList* g_object_list_watched_closures (GObject *object)
4659 * g_return_val_if_fail (G_IS_OBJECT (object), NULL);
4660 * carray = g_object_get_data (object, "GObject-closure-array");
4663 * GSList *slist = NULL;
4665 * for (i = 0; i < carray->n_closures; i++)
4666 * slist = g_slist_prepend (slist, carray->closures[i]);
4674 object_remove_closure (gpointer data,
4677 GObject *object = data;
4681 G_LOCK (closure_array_mutex);
4682 carray = g_object_get_qdata (object, quark_closure_array);
4683 for (i = 0; i < carray->n_closures; i++)
4684 if (carray->closures[i] == closure)
4686 carray->n_closures--;
4687 if (i < carray->n_closures)
4688 carray->closures[i] = carray->closures[carray->n_closures];
4689 G_UNLOCK (closure_array_mutex);
4692 G_UNLOCK (closure_array_mutex);
4693 g_assert_not_reached ();
4697 destroy_closure_array (gpointer data)
4699 CArray *carray = data;
4700 GObject *object = carray->object;
4701 guint i, n = carray->n_closures;
4703 for (i = 0; i < n; i++)
4705 GClosure *closure = carray->closures[i];
4707 /* removing object_remove_closure() upfront is probably faster than
4708 * letting it fiddle with quark_closure_array which is empty anyways
4710 g_closure_remove_invalidate_notifier (closure, object, object_remove_closure);
4711 g_closure_invalidate (closure);
4717 * g_object_watch_closure:
4718 * @object: #GObject restricting lifetime of @closure
4719 * @closure: #GClosure to watch
4721 * This function essentially limits the life time of the @closure to
4722 * the life time of the object. That is, when the object is finalized,
4723 * the @closure is invalidated by calling g_closure_invalidate() on
4724 * it, in order to prevent invocations of the closure with a finalized
4725 * (nonexisting) object. Also, g_object_ref() and g_object_unref() are
4726 * added as marshal guards to the @closure, to ensure that an extra
4727 * reference count is held on @object during invocation of the
4728 * @closure. Usually, this function will be called on closures that
4729 * use this @object as closure data.
4732 g_object_watch_closure (GObject *object,
4738 g_return_if_fail (G_IS_OBJECT (object));
4739 g_return_if_fail (closure != NULL);
4740 g_return_if_fail (closure->is_invalid == FALSE);
4741 g_return_if_fail (closure->in_marshal == FALSE);
4742 g_return_if_fail (g_atomic_int_get (&object->ref_count) > 0); /* this doesn't work on finalizing objects */
4744 g_closure_add_invalidate_notifier (closure, object, object_remove_closure);
4745 g_closure_add_marshal_guards (closure,
4746 object, (GClosureNotify) g_object_ref,
4747 object, (GClosureNotify) g_object_unref);
4748 G_LOCK (closure_array_mutex);
4749 carray = g_datalist_id_remove_no_notify (&object->qdata, quark_closure_array);
4752 carray = g_renew (CArray, NULL, 1);
4753 carray->object = object;
4754 carray->n_closures = 1;
4759 i = carray->n_closures++;
4760 carray = g_realloc (carray, sizeof (*carray) + sizeof (carray->closures[0]) * i);
4762 carray->closures[i] = closure;
4763 g_datalist_id_set_data_full (&object->qdata, quark_closure_array, carray, destroy_closure_array);
4764 G_UNLOCK (closure_array_mutex);
4768 * g_closure_new_object:
4769 * @sizeof_closure: the size of the structure to allocate, must be at least
4770 * `sizeof (GClosure)`
4771 * @object: a #GObject pointer to store in the @data field of the newly
4772 * allocated #GClosure
4774 * A variant of g_closure_new_simple() which stores @object in the
4775 * @data field of the closure and calls g_object_watch_closure() on
4776 * @object and the created closure. This function is mainly useful
4777 * when implementing new types of closures.
4779 * Returns: (transfer floating): a newly allocated #GClosure
4782 g_closure_new_object (guint sizeof_closure,
4787 g_return_val_if_fail (G_IS_OBJECT (object), NULL);
4788 g_return_val_if_fail (g_atomic_int_get (&object->ref_count) > 0, NULL); /* this doesn't work on finalizing objects */
4790 closure = g_closure_new_simple (sizeof_closure, object);
4791 g_object_watch_closure (object, closure);
4797 * g_cclosure_new_object: (skip)
4798 * @callback_func: the function to invoke
4799 * @object: a #GObject pointer to pass to @callback_func
4801 * A variant of g_cclosure_new() which uses @object as @user_data and
4802 * calls g_object_watch_closure() on @object and the created
4803 * closure. This function is useful when you have a callback closely
4804 * associated with a #GObject, and want the callback to no longer run
4805 * after the object is is freed.
4807 * Returns: (transfer floating): a new #GCClosure
4810 g_cclosure_new_object (GCallback callback_func,
4815 g_return_val_if_fail (G_IS_OBJECT (object), NULL);
4816 g_return_val_if_fail (g_atomic_int_get (&object->ref_count) > 0, NULL); /* this doesn't work on finalizing objects */
4817 g_return_val_if_fail (callback_func != NULL, NULL);
4819 closure = g_cclosure_new (callback_func, object, NULL);
4820 g_object_watch_closure (object, closure);
4826 * g_cclosure_new_object_swap: (skip)
4827 * @callback_func: the function to invoke
4828 * @object: a #GObject pointer to pass to @callback_func
4830 * A variant of g_cclosure_new_swap() which uses @object as @user_data
4831 * and calls g_object_watch_closure() on @object and the created
4832 * closure. This function is useful when you have a callback closely
4833 * associated with a #GObject, and want the callback to no longer run
4834 * after the object is is freed.
4836 * Returns: (transfer floating): a new #GCClosure
4839 g_cclosure_new_object_swap (GCallback callback_func,
4844 g_return_val_if_fail (G_IS_OBJECT (object), NULL);
4845 g_return_val_if_fail (g_atomic_int_get (&object->ref_count) > 0, NULL); /* this doesn't work on finalizing objects */
4846 g_return_val_if_fail (callback_func != NULL, NULL);
4848 closure = g_cclosure_new_swap (callback_func, object, NULL);
4849 g_object_watch_closure (object, closure);
4855 g_object_compat_control (gsize what,
4861 case 1: /* floating base type */
4862 return (gsize) G_TYPE_INITIALLY_UNOWNED;
4863 case 2: /* FIXME: remove this once GLib/Gtk+ break ABI again */
4864 floating_flag_handler = (guint(*)(GObject*,gint)) data;
4866 case 3: /* FIXME: remove this once GLib/Gtk+ break ABI again */
4868 *pp = floating_flag_handler;
4875 G_DEFINE_TYPE (GInitiallyUnowned, g_initially_unowned, G_TYPE_OBJECT)
4878 g_initially_unowned_init (GInitiallyUnowned *object)
4880 g_object_force_floating (object);
4884 g_initially_unowned_class_init (GInitiallyUnownedClass *klass)
4891 * A structure containing a weak reference to a #GObject.
4893 * A `GWeakRef` can either be empty (i.e. point to %NULL), or point to an
4894 * object for as long as at least one "strong" reference to that object
4895 * exists. Before the object's #GObjectClass.dispose method is called,
4896 * every #GWeakRef associated with becomes empty (i.e. points to %NULL).
4898 * Like #GValue, #GWeakRef can be statically allocated, stack- or
4899 * heap-allocated, or embedded in larger structures.
4901 * Unlike g_object_weak_ref() and g_object_add_weak_pointer(), this weak
4902 * reference is thread-safe: converting a weak pointer to a reference is
4903 * atomic with respect to invalidation of weak pointers to destroyed
4906 * If the object's #GObjectClass.dispose method results in additional
4907 * references to the object being held (‘re-referencing’), any #GWeakRefs taken
4908 * before it was disposed will continue to point to %NULL. Any #GWeakRefs taken
4909 * during disposal and after re-referencing, or after disposal has returned due
4910 * to the re-referencing, will continue to point to the object until its refcount
4911 * goes back to zero, at which point they too will be invalidated.
4913 * It is invalid to take a #GWeakRef on an object during #GObjectClass.dispose
4914 * without first having or creating a strong reference to the object.
4918 * g_weak_ref_init: (skip)
4919 * @weak_ref: (inout): uninitialized or empty location for a weak
4921 * @object: (type GObject.Object) (nullable): a #GObject or %NULL
4923 * Initialise a non-statically-allocated #GWeakRef.
4925 * This function also calls g_weak_ref_set() with @object on the
4926 * freshly-initialised weak reference.
4928 * This function should always be matched with a call to
4929 * g_weak_ref_clear(). It is not necessary to use this function for a
4930 * #GWeakRef in static storage because it will already be
4931 * properly initialised. Just use g_weak_ref_set() directly.
4936 g_weak_ref_init (GWeakRef *weak_ref,
4939 weak_ref->priv.p = NULL;
4941 g_weak_ref_set (weak_ref, object);
4945 * g_weak_ref_clear: (skip)
4946 * @weak_ref: (inout): location of a weak reference, which
4949 * Frees resources associated with a non-statically-allocated #GWeakRef.
4950 * After this call, the #GWeakRef is left in an undefined state.
4952 * You should only call this on a #GWeakRef that previously had
4953 * g_weak_ref_init() called on it.
4958 g_weak_ref_clear (GWeakRef *weak_ref)
4960 g_weak_ref_set (weak_ref, NULL);
4963 weak_ref->priv.p = (void *) 0xccccccccu;
4967 * g_weak_ref_get: (skip)
4968 * @weak_ref: (inout): location of a weak reference to a #GObject
4970 * If @weak_ref is not empty, atomically acquire a strong
4971 * reference to the object it points to, and return that reference.
4973 * This function is needed because of the potential race between taking
4974 * the pointer value and g_object_ref() on it, if the object was losing
4975 * its last reference at the same time in a different thread.
4977 * The caller should release the resulting reference in the usual way,
4978 * by using g_object_unref().
4980 * Returns: (transfer full) (type GObject.Object): the object pointed to
4981 * by @weak_ref, or %NULL if it was empty
4986 g_weak_ref_get (GWeakRef *weak_ref)
4988 gpointer object_or_null;
4990 g_return_val_if_fail (weak_ref!= NULL, NULL);
4992 g_rw_lock_reader_lock (&weak_locations_lock);
4994 object_or_null = weak_ref->priv.p;
4996 if (object_or_null != NULL)
4997 g_object_ref (object_or_null);
4999 g_rw_lock_reader_unlock (&weak_locations_lock);
5001 return object_or_null;
5005 weak_locations_free_unlocked (GSList **weak_locations)
5007 if (*weak_locations)
5009 GSList *weak_location;
5011 for (weak_location = *weak_locations; weak_location;)
5013 GWeakRef *weak_ref_location = weak_location->data;
5015 weak_ref_location->priv.p = NULL;
5016 weak_location = g_slist_delete_link (weak_location, weak_location);
5020 g_free (weak_locations);
5024 weak_locations_free (gpointer data)
5026 GSList **weak_locations = data;
5028 g_rw_lock_writer_lock (&weak_locations_lock);
5029 weak_locations_free_unlocked (weak_locations);
5030 g_rw_lock_writer_unlock (&weak_locations_lock);
5034 * g_weak_ref_set: (skip)
5035 * @weak_ref: location for a weak reference
5036 * @object: (type GObject.Object) (nullable): a #GObject or %NULL
5038 * Change the object to which @weak_ref points, or set it to
5041 * You must own a strong reference on @object while calling this
5047 g_weak_ref_set (GWeakRef *weak_ref,
5050 GSList **weak_locations;
5051 GObject *new_object;
5052 GObject *old_object;
5054 g_return_if_fail (weak_ref != NULL);
5055 g_return_if_fail (object == NULL || G_IS_OBJECT (object));
5057 new_object = object;
5059 g_rw_lock_writer_lock (&weak_locations_lock);
5061 /* We use the extra level of indirection here so that if we have ever
5062 * had a weak pointer installed at any point in time on this object,
5063 * we can see that there is a non-NULL value associated with the
5064 * weak-pointer quark and know that this value will not change at any
5065 * point in the object's lifetime.
5067 * Both properties are important for reducing the amount of times we
5068 * need to acquire locks and for decreasing the duration of time the
5069 * lock is held while avoiding some rather tricky races.
5071 * Specifically: we can avoid having to do an extra unconditional lock
5072 * in g_object_unref() without worrying about some extremely tricky
5076 old_object = weak_ref->priv.p;
5077 if (new_object != old_object)
5079 weak_ref->priv.p = new_object;
5081 /* Remove the weak ref from the old object */
5082 if (old_object != NULL)
5084 weak_locations = g_datalist_id_get_data (&old_object->qdata, quark_weak_locations);
5085 if (weak_locations == NULL)
5087 #ifndef G_DISABLE_ASSERT
5088 gboolean in_weak_refs_notify =
5089 g_datalist_id_get_data (&old_object->qdata, quark_weak_refs) == NULL;
5090 g_assert (in_weak_refs_notify);
5091 #endif /* G_DISABLE_ASSERT */
5095 *weak_locations = g_slist_remove (*weak_locations, weak_ref);
5097 if (!*weak_locations)
5099 weak_locations_free_unlocked (weak_locations);
5100 g_datalist_id_remove_no_notify (&old_object->qdata, quark_weak_locations);
5105 /* Add the weak ref to the new object */
5106 if (new_object != NULL)
5108 weak_locations = g_datalist_id_get_data (&new_object->qdata, quark_weak_locations);
5110 if (weak_locations == NULL)
5112 weak_locations = g_new0 (GSList *, 1);
5113 g_datalist_id_set_data_full (&new_object->qdata, quark_weak_locations,
5114 weak_locations, weak_locations_free);
5117 *weak_locations = g_slist_prepend (*weak_locations, weak_ref);
5121 g_rw_lock_writer_unlock (&weak_locations_lock);