1 /* -*- Mode: C; c-basic-offset: 4 -*-
2 * pygtk- Python bindings for the GTK toolkit.
3 * Copyright (C) 1998-2003 James Henstridge
5 * pygobject.c: wrapper for the GObject type.
7 * This library is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
12 * This library is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with this library; if not, see <http://www.gnu.org/licenses/>.
26 #include "pygobject-private.h"
27 #include "pyginterface.h"
28 #include "pygparamspec.h"
31 #include "pygi-value.h"
32 #include "pygi-type.h"
33 #include "pygi-property.h"
34 #include "pygi-signal-closure.h"
36 static void pygobject_dealloc(PyGObject *self);
37 static int pygobject_traverse(PyGObject *self, visitproc visit, void *arg);
38 static int pygobject_clear(PyGObject *self);
39 static PyObject * pyg_type_get_bases(GType gtype);
40 static inline int pygobject_clear(PyGObject *self);
41 static PyObject * pygobject_weak_ref_new(GObject *obj, PyObject *callback, PyObject *user_data);
42 static inline PyGObjectData * pyg_object_peek_inst_data(GObject *obj);
43 static void pygobject_inherit_slots(PyTypeObject *type, PyObject *bases,
44 gboolean check_for_present);
45 static void pygobject_find_slot_for(PyTypeObject *type, PyObject *bases, int slot_offset,
46 gboolean check_for_present);
47 GType PY_TYPE_OBJECT = 0;
48 GQuark pygobject_custom_key;
49 GQuark pygobject_class_key;
50 GQuark pygobject_class_init_key;
51 GQuark pygobject_wrapper_key;
52 GQuark pygobject_has_updated_constructor_key;
53 GQuark pygobject_instance_data_key;
55 /* Copied from glib. gobject uses hyphens in property names, but in Python
56 * we can only represent hyphens as underscores. Convert underscores to
57 * hyphens for glib compatibility. */
59 canonicalize_key (gchar *key)
63 for (p = key; *p != 0; p++)
68 (c < '0' || c > '9') &&
69 (c < 'A' || c > 'Z') &&
75 /* -------------- class <-> wrapper manipulation --------------- */
78 pygobject_data_free(PyGObjectData *data)
80 /* This function may be called after the python interpreter has already
81 * been shut down. If this happens, we cannot do any python calls, so just
83 PyGILState_STATE state;
84 PyThreadState *_save = NULL;
85 gboolean state_saved = FALSE;
87 GSList *closures, *tmp;
89 if (Py_IsInitialized()) {
91 state = pyglib_gil_state_ensure();
92 Py_DECREF(data->type);
93 /* We cannot use Py_BEGIN_ALLOW_THREADS here because this is inside
95 Py_UNBLOCK_THREADS; /* Modifies _save */
98 tmp = closures = data->closures;
100 data->closures = NULL;
104 GClosure *closure = tmp->data;
106 /* we get next item first, because the current link gets
107 * invalidated by pygobject_unwatch_closure */
109 g_closure_invalidate(closure);
112 if (data->closures != NULL)
113 g_warning("invalidated all closures, but data->closures != NULL !");
117 if (state_saved && Py_IsInitialized ()) {
118 Py_BLOCK_THREADS; /* Restores _save */
119 pyglib_gil_state_release(state);
123 static inline PyGObjectData *
124 pygobject_data_new(void)
127 data = g_new0(PyGObjectData, 1);
131 static inline PyGObjectData *
132 pygobject_get_inst_data(PyGObject *self)
134 PyGObjectData *inst_data;
136 if (G_UNLIKELY(!self->obj))
138 inst_data = g_object_get_qdata(self->obj, pygobject_instance_data_key);
139 if (inst_data == NULL)
141 inst_data = pygobject_data_new();
143 inst_data->type = Py_TYPE(self);
144 Py_INCREF((PyObject *) inst_data->type);
146 g_object_set_qdata_full(self->obj, pygobject_instance_data_key,
147 inst_data, (GDestroyNotify) pygobject_data_free);
153 PyTypeObject *PyGObject_MetaType = NULL;
159 * As Python handles reference counting for us, the "floating
160 * reference" code in GTK is not all that useful. In fact, it can
161 * cause leaks. This function should be called to remove the floating
162 * references on objects on construction.
165 pygobject_sink(GObject *obj)
167 /* The default behaviour for GInitiallyUnowned subclasses is to call ref_sink().
168 * - if the object is new and owned by someone else, its ref has been sunk and
169 * we need to keep the one from that someone and add our own "fresh ref"
170 * - if the object is not and owned by nobody, its ref is floating and we need
171 * to transform it into a regular ref.
173 if (G_IS_INITIALLY_UNOWNED(obj)) {
174 g_object_ref_sink(obj);
185 PYGLIB_DEFINE_TYPE("gi._gobject.GPropsIter", PyGPropsIter_Type, PyGPropsIter);
188 pyg_props_iter_dealloc(PyGPropsIter *self)
191 PyObject_Del((PyObject*) self);
195 pygobject_props_iter_next(PyGPropsIter *iter)
197 if (iter->index < iter->n_props)
198 return pyg_param_spec_new(iter->props[iter->index++]);
200 PyErr_SetNone(PyExc_StopIteration);
207 /* a reference to the object containing the properties */
208 PyGObject *pygobject;
213 PyGProps_dealloc(PyGProps* self)
217 PyObject_GC_UnTrack((PyObject*)self);
219 tmp = self->pygobject;
220 self->pygobject = NULL;
223 PyObject_GC_Del((PyObject*)self);
227 build_parameter_list(GObjectClass *class)
230 guint n_props = 0, i;
232 PyObject *props_list;
234 props = g_object_class_list_properties(class, &n_props);
235 props_list = PyList_New(n_props);
236 for (i = 0; i < n_props; i++) {
238 name = g_strdup(g_param_spec_get_name(props[i]));
239 /* hyphens cannot belong in identifiers */
240 g_strdelimit(name, "-", '_');
241 prop_str = PYGLIB_PyUnicode_FromString(name);
243 PyList_SetItem(props_list, i, prop_str);
254 PyGProps_getattro(PyGProps *self, PyObject *attr)
256 char *attr_name, *property_name;
260 attr_name = PYGLIB_PyUnicode_AsString(attr);
263 return PyObject_GenericGetAttr((PyObject *)self, attr);
266 class = g_type_class_ref(self->gtype);
268 /* g_object_class_find_property recurses through the class hierarchy,
269 * so the resulting pspec tells us the owner_type that owns the property
270 * we're dealing with. */
271 property_name = g_strdup(attr_name);
272 canonicalize_key(property_name);
273 pspec = g_object_class_find_property(class, property_name);
274 g_free(property_name);
275 g_type_class_unref(class);
278 return PyObject_GenericGetAttr((PyObject *)self, attr);
281 if (!self->pygobject) {
282 /* If we're doing it without an instance, return a GParamSpec */
283 return pyg_param_spec_new(pspec);
286 return pygi_get_property_value (self->pygobject, pspec);
290 set_property_from_pspec(GObject *obj,
294 GValue value = { 0, };
296 if (pspec->flags & G_PARAM_CONSTRUCT_ONLY) {
297 PyErr_Format(PyExc_TypeError,
298 "property '%s' can only be set in constructor",
303 if (!(pspec->flags & G_PARAM_WRITABLE)) {
304 PyErr_Format(PyExc_TypeError,
305 "property '%s' is not writable", pspec->name);
309 g_value_init(&value, G_PARAM_SPEC_VALUE_TYPE(pspec));
310 if (pyg_param_gvalue_from_pyobject(&value, pvalue, pspec) < 0) {
311 PyObject *pvalue_str = PyObject_Str(pvalue);
312 PyErr_Format(PyExc_TypeError,
313 "could not convert '%s' to type '%s' when setting property '%s.%s'",
314 PYGLIB_PyUnicode_AsString(pvalue_str),
315 g_type_name(G_PARAM_SPEC_VALUE_TYPE(pspec)),
316 G_OBJECT_TYPE_NAME(obj),
318 Py_DECREF(pvalue_str);
322 Py_BEGIN_ALLOW_THREADS;
323 g_object_set_property(obj, pspec->name, &value);
324 g_value_unset(&value);
325 Py_END_ALLOW_THREADS;
330 PYGLIB_DEFINE_TYPE("gi._gobject.GProps", PyGProps_Type, PyGProps);
333 PyGProps_setattro(PyGProps *self, PyObject *attr, PyObject *pvalue)
336 char *attr_name, *property_name;
340 if (pvalue == NULL) {
341 PyErr_SetString(PyExc_TypeError, "properties cannot be "
346 attr_name = PYGLIB_PyUnicode_AsString(attr);
349 return PyObject_GenericSetAttr((PyObject *)self, attr, pvalue);
352 if (!self->pygobject) {
353 PyErr_SetString(PyExc_TypeError,
354 "cannot set GOject properties without an instance");
358 obj = self->pygobject->obj;
360 property_name = g_strdup(attr_name);
361 canonicalize_key(property_name);
363 /* g_object_class_find_property recurses through the class hierarchy,
364 * so the resulting pspec tells us the owner_type that owns the property
365 * we're dealing with. */
366 pspec = g_object_class_find_property(G_OBJECT_GET_CLASS(obj),
368 g_free(property_name);
370 return PyObject_GenericSetAttr((PyObject *)self, attr, pvalue);
372 if (!pyg_gtype_is_custom (pspec->owner_type)) {
373 /* This GType is not implemented in Python: see if we can set the
374 * property via gi. */
375 ret = pygi_set_property_value (self->pygobject, pspec, pvalue);
378 else if (ret == -1 && PyErr_Occurred())
382 /* This GType is implemented in Python, or we failed to set it via gi:
383 * do a straightforward set. */
384 if (!set_property_from_pspec(obj, pspec, pvalue))
391 pygobject_props_traverse(PyGProps *self, visitproc visit, void *arg)
393 if (self->pygobject && visit((PyObject *) self->pygobject, arg) < 0)
399 pygobject_props_get_iter(PyGProps *self)
404 iter = PyObject_NEW(PyGPropsIter, &PyGPropsIter_Type);
405 class = g_type_class_ref(self->gtype);
406 iter->props = g_object_class_list_properties(class, &iter->n_props);
408 g_type_class_unref(class);
409 return (PyObject *) iter;
413 pygobject_props_dir(PyGProps *self)
418 class = g_type_class_ref (self->gtype);
419 ret = build_parameter_list (class);
420 g_type_class_unref (class);
425 static PyMethodDef pygobject_props_methods[] = {
426 { "__dir__", (PyCFunction)pygobject_props_dir, METH_NOARGS},
432 PyGProps_length(PyGProps *self)
438 class = g_type_class_ref(self->gtype);
439 props = g_object_class_list_properties(class, &n_props);
440 g_type_class_unref(class);
443 return (Py_ssize_t)n_props;
446 static PySequenceMethods _PyGProps_as_sequence = {
447 (lenfunc) PyGProps_length,
456 PYGLIB_DEFINE_TYPE("gi._gobject.GPropsDescr", PyGPropsDescr_Type, PyObject);
459 pyg_props_descr_descr_get(PyObject *self, PyObject *obj, PyObject *type)
463 gprops = PyObject_GC_New(PyGProps, &PyGProps_Type);
464 if (obj == NULL || obj == Py_None) {
465 gprops->pygobject = NULL;
466 gprops->gtype = pyg_type_from_object(type);
468 if (!PyObject_IsInstance(obj, (PyObject *) &PyGObject_Type)) {
469 PyErr_SetString(PyExc_TypeError, "cannot use GObject property"
470 " descriptor on non-GObject instances");
474 gprops->pygobject = (PyGObject *) obj;
475 gprops->gtype = pyg_type_from_object(obj);
477 return (PyObject *) gprops;
481 * pygobject_register_class:
482 * @dict: the module dictionary. A reference to the type will be stored here.
483 * @type_name: not used ?
484 * @gtype: the GType of the GObject subclass.
485 * @type: the Python type object for this wrapper.
486 * @static_bases: a tuple of Python type objects that are the bases of
489 * This function is used to register a Python type as the wrapper for
490 * a particular GObject subclass. It will also insert a reference to
491 * the wrapper class into the module dictionary passed as a reference,
492 * which simplifies initialisation.
495 pygobject_register_class(PyObject *dict, const gchar *type_name,
496 GType gtype, PyTypeObject *type,
497 PyObject *static_bases)
500 const char *class_name, *s;
501 PyObject *runtime_bases;
502 PyObject *bases_list, *bases, *mod_name;
505 class_name = type->tp_name;
506 s = strrchr(class_name, '.');
510 runtime_bases = pyg_type_get_bases(gtype);
512 PyTypeObject *py_parent_type = (PyTypeObject *) PyTuple_GET_ITEM(static_bases, 0);
513 bases_list = PySequence_List(static_bases);
514 /* we start at index 1 because we want to skip the primary
515 * base, otherwise we might get MRO conflict */
516 for (i = 1; i < PyTuple_GET_SIZE(runtime_bases); ++i)
518 PyObject *base = PyTuple_GET_ITEM(runtime_bases, i);
519 int contains = PySequence_Contains(bases_list, base);
522 else if (!contains) {
523 if (!PySequence_Contains(py_parent_type->tp_mro, base)) {
525 g_message("Adding missing base %s to type %s",
526 ((PyTypeObject *)base)->tp_name, type->tp_name);
528 PyList_Append(bases_list, base);
532 bases = PySequence_Tuple(bases_list);
533 Py_DECREF(bases_list);
534 Py_DECREF(runtime_bases);
536 bases = runtime_bases;
538 Py_TYPE(type) = PyGObject_MetaType;
539 type->tp_bases = bases;
540 if (G_LIKELY(bases)) {
541 type->tp_base = (PyTypeObject *)PyTuple_GetItem(bases, 0);
542 Py_INCREF(type->tp_base);
545 pygobject_inherit_slots(type, bases, TRUE);
547 if (PyType_Ready(type) < 0) {
548 g_warning ("couldn't make the type `%s' ready", type->tp_name);
552 /* Set type.__module__ to the name of the module,
553 * otherwise it'll default to 'gobject', see #376099
555 s = strrchr(type->tp_name, '.');
557 mod_name = PYGLIB_PyUnicode_FromStringAndSize(type->tp_name, (int)(s - type->tp_name));
558 PyDict_SetItemString(type->tp_dict, "__module__", mod_name);
563 o = pyg_type_wrapper_new(gtype);
564 PyDict_SetItemString(type->tp_dict, "__gtype__", o);
567 /* stash a pointer to the python class with the GType */
569 g_type_set_qdata(gtype, pygobject_class_key, type);
572 /* set up __doc__ descriptor on type */
573 PyDict_SetItemString(type->tp_dict, "__doc__",
574 pyg_object_descr_doc_get());
576 PyDict_SetItemString(dict, (char *)class_name, (PyObject *)type);
580 pyg_toggle_notify (gpointer data, GObject *object, gboolean is_last_ref)
583 PyGILState_STATE state;
585 state = pyglib_gil_state_ensure();
587 /* Avoid thread safety problems by using qdata for wrapper retrieval
588 * instead of the user data argument.
589 * See: https://bugzilla.gnome.org/show_bug.cgi?id=709223
591 self = (PyGObject *)g_object_get_qdata (object, pygobject_wrapper_key);
599 pyglib_gil_state_release(state);
602 /* Called when the inst_dict is first created; switches the
603 reference counting strategy to start using toggle ref to keep the
604 wrapper alive while the GObject lives. In contrast, while
605 inst_dict was NULL the python wrapper is allowed to die at
606 will and is recreated on demand. */
608 pygobject_switch_to_toggle_ref(PyGObject *self)
610 g_assert(self->obj->ref_count >= 1);
612 if (self->private_flags.flags & PYGOBJECT_USING_TOGGLE_REF)
613 return; /* already using toggle ref */
614 self->private_flags.flags |= PYGOBJECT_USING_TOGGLE_REF;
615 /* Note that add_toggle_ref will never immediately call back into
617 Py_INCREF((PyObject *) self);
618 g_object_add_toggle_ref(self->obj, pyg_toggle_notify, NULL);
619 g_object_unref(self->obj);
622 /* Called when an custom gobject is initalized via g_object_new instead of
623 its constructor. The next time the wrapper is access via
624 pygobject_new_full it will sink the floating reference instead of
625 adding a new reference and causing a leak */
628 pygobject_ref_float(PyGObject *self)
630 /* should only be floated once */
631 g_assert(!(self->private_flags.flags & PYGOBJECT_IS_FLOATING_REF));
633 self->private_flags.flags |= PYGOBJECT_IS_FLOATING_REF;
636 /* Called by gobject_new_full, if the floating flag is set remove it, otherwise
639 pygobject_ref_sink(PyGObject *self)
641 if (self->private_flags.flags & PYGOBJECT_IS_FLOATING_REF)
642 self->private_flags.flags &= ~PYGOBJECT_IS_FLOATING_REF;
644 Py_INCREF ( (PyObject *) self);
648 * pygobject_register_wrapper:
649 * @self: the wrapper instance
651 * In the constructor of PyGTK wrappers, this function should be
652 * called after setting the obj member. It will tie the wrapper
653 * instance to the GObject so that the same wrapper instance will
654 * always be used for this GObject instance.
657 pygobject_register_wrapper(PyObject *self)
661 g_return_if_fail(self != NULL);
662 g_return_if_fail(PyObject_TypeCheck(self, &PyGObject_Type));
664 gself = (PyGObject *)self;
666 g_assert(gself->obj->ref_count >= 1);
667 /* save wrapper pointer so we can access it later */
668 g_object_set_qdata_full(gself->obj, pygobject_wrapper_key, gself, NULL);
669 if (gself->inst_dict)
670 pygobject_switch_to_toggle_ref(gself);
674 pyg_type_get_bases(GType gtype)
676 GType *interfaces, parent_type, interface_type;
678 PyTypeObject *py_parent_type, *py_interface_type;
682 if (G_UNLIKELY(gtype == G_TYPE_OBJECT))
685 /* Lookup the parent type */
686 parent_type = g_type_parent(gtype);
687 py_parent_type = pygobject_lookup_class(parent_type);
688 interfaces = g_type_interfaces(gtype, &n_interfaces);
689 bases = PyTuple_New(n_interfaces + 1);
690 /* We will always put the parent at the first position in bases */
691 Py_INCREF(py_parent_type); /* PyTuple_SetItem steals a reference */
692 PyTuple_SetItem(bases, 0, (PyObject *) py_parent_type);
694 /* And traverse interfaces */
696 for (i = 0; i < n_interfaces; i++) {
697 interface_type = interfaces[i];
698 py_interface_type = pygobject_lookup_class(interface_type);
699 Py_INCREF(py_interface_type); /* PyTuple_SetItem steals a reference */
700 PyTuple_SetItem(bases, i + 1, (PyObject *) py_interface_type);
708 * pygobject_new_with_interfaces
709 * @gtype: the GType of the GObject subclass.
711 * Creates a new PyTypeObject from the given GType with interfaces attached in
714 * Returns: a PyTypeObject for the new type or NULL if it couldn't be created
716 static PyTypeObject *
717 pygobject_new_with_interfaces(GType gtype)
719 PyGILState_STATE state;
723 PyTypeObject *py_parent_type;
726 state = pyglib_gil_state_ensure();
728 bases = pyg_type_get_bases(gtype);
729 py_parent_type = (PyTypeObject *) PyTuple_GetItem(bases, 0);
733 o = pyg_type_wrapper_new(gtype);
734 PyDict_SetItemString(dict, "__gtype__", o);
737 /* set up __doc__ descriptor on type */
738 PyDict_SetItemString(dict, "__doc__", pyg_object_descr_doc_get());
740 /* Something special to point out that it's not accessible through
742 o = PYGLIB_PyUnicode_FromString ("__gi__");
743 PyDict_SetItemString (dict, "__module__", o);
746 type = (PyTypeObject*)PyObject_CallFunction((PyObject *) Py_TYPE(py_parent_type),
747 "sNN", g_type_name (gtype), bases, dict);
751 pyglib_gil_state_release(state);
755 /* Workaround python tp_(get|set)attr slot inheritance bug.
756 * Fixes bug #144135. */
757 if (!type->tp_getattr && py_parent_type->tp_getattr) {
758 type->tp_getattro = NULL;
759 type->tp_getattr = py_parent_type->tp_getattr;
761 if (!type->tp_setattr && py_parent_type->tp_setattr) {
762 type->tp_setattro = NULL;
763 type->tp_setattr = py_parent_type->tp_setattr;
765 /* override more python stupid hacks behind our back */
766 type->tp_dealloc = py_parent_type->tp_dealloc;
767 type->tp_alloc = py_parent_type->tp_alloc;
768 type->tp_free = py_parent_type->tp_free;
769 type->tp_traverse = py_parent_type->tp_traverse;
770 type->tp_clear = py_parent_type->tp_clear;
772 pygobject_inherit_slots(type, bases, FALSE);
774 if (PyType_Ready(type) < 0) {
775 g_warning ("couldn't make the type `%s' ready", type->tp_name);
776 pyglib_gil_state_release(state);
780 /* stash a pointer to the python class with the GType */
782 g_type_set_qdata(gtype, pygobject_class_key, type);
784 pyglib_gil_state_release(state);
789 /* Pick appropriate value for given slot (at slot_offset inside
790 * PyTypeObject structure). It must be a pointer, e.g. a pointer to a
791 * function. We use the following heuristic:
793 * - Scan all types listed as bases of the type.
794 * - If for exactly one base type slot value is non-NULL and
795 * different from that of 'object' and 'GObject', set current type
796 * slot into that value.
797 * - Otherwise (if there is more than one such base type or none at
798 * all) don't touch it and live with Python default.
800 * The intention here is to propagate slot from custom wrappers to
801 * wrappers created at runtime when appropriate. We prefer to be on
802 * the safe side, so if there is potential collision (more than one
803 * custom slot value), we discard custom overrides altogether.
805 * When registering type with pygobject_register_class(), i.e. a type
806 * that has been manually created (likely with Codegen help),
807 * `check_for_present' should be set to TRUE. In this case, the
808 * function will never overwrite any non-NULL slots already present in
809 * the type. If `check_for_present' is FALSE, such non-NULL slots are
810 * though to be set by Python interpreter and so will be overwritten
811 * if heuristic above says so.
814 pygobject_inherit_slots(PyTypeObject *type, PyObject *bases, gboolean check_for_present)
816 static int slot_offsets[] = { offsetof(PyTypeObject, tp_richcompare),
817 #if PY_VERSION_HEX < 0x03000000
818 offsetof(PyTypeObject, tp_compare),
820 offsetof(PyTypeObject, tp_richcompare),
821 offsetof(PyTypeObject, tp_hash),
822 offsetof(PyTypeObject, tp_iter),
823 offsetof(PyTypeObject, tp_repr),
824 offsetof(PyTypeObject, tp_str),
825 offsetof(PyTypeObject, tp_print) };
828 /* Happens when registering gobject.GObject itself, at least. */
832 for (i = 0; i < G_N_ELEMENTS(slot_offsets); ++i)
833 pygobject_find_slot_for(type, bases, slot_offsets[i], check_for_present);
837 pygobject_find_slot_for(PyTypeObject *type, PyObject *bases, int slot_offset,
838 gboolean check_for_present)
840 #define TYPE_SLOT(type) (* (void **) (((char *) (type)) + slot_offset))
842 void *found_slot = NULL;
843 int num_bases = PyTuple_Size(bases);
846 if (check_for_present && TYPE_SLOT(type) != NULL) {
847 /* We are requested to check if there is any custom slot value
848 * in this type already and there actually is. Don't
854 for (i = 0; i < num_bases; ++i) {
855 PyTypeObject *base_type = (PyTypeObject *) PyTuple_GetItem(bases, i);
856 void *slot = TYPE_SLOT(base_type);
860 if (slot == TYPE_SLOT(&PyGObject_Type) ||
861 slot == TYPE_SLOT(&PyBaseObject_Type))
864 if (found_slot != NULL && found_slot != slot) {
865 /* We have a conflict: more than one base use different
866 * custom slots. To be on the safe side, we bail out.
874 /* Only perform the final assignment if at least one base has a
875 * custom value. Otherwise just leave this type's slot untouched.
877 if (found_slot != NULL)
878 TYPE_SLOT(type) = found_slot;
884 * pygobject_lookup_class:
885 * @gtype: the GType of the GObject subclass.
887 * This function looks up the wrapper class used to represent
888 * instances of a GObject represented by @gtype. If no wrapper class
889 * or interface has been registered for the given GType, then a new
890 * type will be created.
892 * Returns: The wrapper class for the GObject or NULL if the
893 * GType has no registered type and a new type couldn't be created
896 pygobject_lookup_class(GType gtype)
898 PyTypeObject *py_type;
900 if (gtype == G_TYPE_INTERFACE)
901 return &PyGInterface_Type;
903 py_type = g_type_get_qdata(gtype, pygobject_class_key);
904 if (py_type == NULL) {
905 py_type = g_type_get_qdata(gtype, pyginterface_type_key);
908 py_type = (PyTypeObject *)pygi_type_import_by_g_type(gtype);
910 if (py_type == NULL) {
911 py_type = pygobject_new_with_interfaces(gtype);
912 g_type_set_qdata(gtype, pyginterface_type_key, py_type);
920 * pygobject_new_full:
921 * @obj: a GObject instance.
922 * @steal: whether to steal a ref from the GObject or add (sink) a new one.
923 * @g_class: the GObjectClass
925 * This function gets a reference to a wrapper for the given GObject
926 * instance. If a wrapper has already been created, a new reference
927 * to that wrapper will be returned. Otherwise, a wrapper instance
930 * Returns: a reference to the wrapper for the GObject.
933 pygobject_new_full(GObject *obj, gboolean steal, gpointer g_class)
941 /* If the GObject already has a PyObject wrapper stashed in its qdata, re-use it.
943 self = (PyGObject *)g_object_get_qdata(obj, pygobject_wrapper_key);
945 /* Note the use of "pygobject_ref_sink" here only deals with PyObject
946 * wrapper ref counts and has nothing to do with GObject.
948 pygobject_ref_sink(self);
950 /* If steal is true, we also want to decref the incoming GObjects which
951 * already have a Python wrapper because the wrapper is already holding a
955 g_object_unref (obj);
959 PyGObjectData *inst_data = pyg_object_peek_inst_data(obj);
962 tp = inst_data->type;
965 tp = pygobject_lookup_class(G_OBJECT_CLASS_TYPE(g_class));
967 tp = pygobject_lookup_class(G_OBJECT_TYPE(obj));
969 g_assert(tp != NULL);
971 /* need to bump type refcount if created with
972 pygobject_new_with_interfaces(). fixes bug #141042 */
973 if (tp->tp_flags & Py_TPFLAGS_HEAPTYPE)
975 self = PyObject_GC_New(PyGObject, tp);
978 self->inst_dict = NULL;
979 self->weakreflist = NULL;
980 self->private_flags.flags = 0;
983 /* If we are not stealing a ref or the object is floating,
984 * add a regular ref or sink the object. */
985 if (g_object_is_floating (obj))
986 self->private_flags.flags |= PYGOBJECT_GOBJECT_WAS_FLOATING;
987 if (!steal || self->private_flags.flags & PYGOBJECT_GOBJECT_WAS_FLOATING)
988 g_object_ref_sink (obj);
990 pygobject_register_wrapper((PyObject *)self);
991 PyObject_GC_Track((PyObject *)self);
994 return (PyObject *)self;
999 pygobject_new(GObject *obj)
1001 return pygobject_new_full(obj,
1007 pygobject_unwatch_closure(gpointer data, GClosure *closure)
1009 PyGObjectData *inst_data = data;
1011 inst_data->closures = g_slist_remove (inst_data->closures, closure);
1015 * pygobject_watch_closure:
1016 * @self: a GObject wrapper instance
1017 * @closure: a GClosure to watch
1019 * Adds a closure to the list of watched closures for the wrapper.
1020 * The closure must be one returned by pyg_closure_new(). When the
1021 * cycle GC traverses the wrapper instance, it will enumerate the
1022 * references to Python objects stored in watched closures. If the
1023 * cycle GC tells the wrapper to clear itself, the watched closures
1024 * will be invalidated.
1027 pygobject_watch_closure(PyObject *self, GClosure *closure)
1030 PyGObjectData *data;
1032 g_return_if_fail(self != NULL);
1033 g_return_if_fail(PyObject_TypeCheck(self, &PyGObject_Type));
1034 g_return_if_fail(closure != NULL);
1036 gself = (PyGObject *)self;
1037 data = pygobject_get_inst_data(gself);
1038 g_return_if_fail(g_slist_find(data->closures, closure) == NULL);
1039 data->closures = g_slist_prepend(data->closures, closure);
1040 g_closure_add_invalidate_notifier(closure, data, pygobject_unwatch_closure);
1044 /* -------------- PyGObject behaviour ----------------- */
1046 PYGLIB_DEFINE_TYPE("gi._gobject.GObject", PyGObject_Type, PyGObject);
1049 pygobject_dealloc(PyGObject *self)
1051 /* Untrack must be done first. This is because followup calls such as
1052 * ClearWeakRefs could call into Python and cause new allocations to
1053 * happen, which could in turn could trigger the garbage collector,
1054 * which would then get confused as it is tracking this half-deallocated
1056 PyObject_GC_UnTrack((PyObject *)self);
1058 PyObject_ClearWeakRefs((PyObject *)self);
1059 /* this forces inst_data->type to be updated, which could prove
1060 * important if a new wrapper has to be created and it is of a
1061 * unregistered type */
1062 pygobject_get_inst_data(self);
1063 pygobject_clear(self);
1064 /* the following causes problems with subclassed types */
1065 /* Py_TYPE(self)->tp_free((PyObject *)self); */
1066 PyObject_GC_Del(self);
1070 pygobject_richcompare(PyObject *self, PyObject *other, int op)
1074 isinst = PyObject_IsInstance(self, (PyObject*)&PyGObject_Type);
1078 Py_INCREF(Py_NotImplemented);
1079 return Py_NotImplemented;
1081 isinst = PyObject_IsInstance(other, (PyObject*)&PyGObject_Type);
1085 Py_INCREF(Py_NotImplemented);
1086 return Py_NotImplemented;
1089 return _pyglib_generic_ptr_richcompare(((PyGObject*)self)->obj,
1090 ((PyGObject*)other)->obj,
1095 pygobject_hash(PyGObject *self)
1097 return (long)self->obj;
1101 pygobject_repr(PyGObject *self)
1103 PyObject *module, *repr;
1104 gchar *module_str, *namespace;
1106 module = PyObject_GetAttrString ((PyObject *)self, "__module__");
1110 if (!PYGLIB_PyUnicode_Check (module)) {
1115 module_str = PYGLIB_PyUnicode_AsString (module);
1116 namespace = g_strrstr (module_str, ".");
1117 if (namespace == NULL) {
1118 namespace = module_str;
1123 repr = PYGLIB_PyUnicode_FromFormat ("<%s.%s object at %p (%s at %p)>",
1124 namespace, Py_TYPE (self)->tp_name, self,
1125 self->obj ? G_OBJECT_TYPE_NAME (self->obj) : "uninitialized",
1133 pygobject_traverse(PyGObject *self, visitproc visit, void *arg)
1137 PyGObjectData *data = pygobject_get_inst_data(self);
1139 if (self->inst_dict) ret = visit(self->inst_dict, arg);
1140 if (ret != 0) return ret;
1144 for (tmp = data->closures; tmp != NULL; tmp = tmp->next) {
1145 PyGClosure *closure = tmp->data;
1147 if (closure->callback) ret = visit(closure->callback, arg);
1148 if (ret != 0) return ret;
1150 if (closure->extra_args) ret = visit(closure->extra_args, arg);
1151 if (ret != 0) return ret;
1153 if (closure->swap_data) ret = visit(closure->swap_data, arg);
1154 if (ret != 0) return ret;
1161 pygobject_clear(PyGObject *self)
1164 g_object_set_qdata_full(self->obj, pygobject_wrapper_key, NULL, NULL);
1165 if (self->inst_dict) {
1166 g_object_remove_toggle_ref(self->obj, pyg_toggle_notify, NULL);
1167 self->private_flags.flags &= ~PYGOBJECT_USING_TOGGLE_REF;
1169 Py_BEGIN_ALLOW_THREADS;
1170 g_object_unref(self->obj);
1171 Py_END_ALLOW_THREADS;
1175 Py_CLEAR(self->inst_dict);
1180 pygobject_free(PyObject *op)
1182 PyObject_GC_Del(op);
1186 pygobject_prepare_construct_properties(GObjectClass *class, PyObject *kwargs,
1187 guint *n_params, GParameter **params)
1197 *params = g_new0(GParameter, PyDict_Size(kwargs));
1198 while (PyDict_Next(kwargs, &pos, &key, &value)) {
1200 GParameter *param = &(*params)[*n_params];
1201 const gchar *key_str = PYGLIB_PyUnicode_AsString(key);
1203 pspec = g_object_class_find_property(class, key_str);
1205 PyErr_Format(PyExc_TypeError,
1206 "gobject `%s' doesn't support property `%s'",
1207 G_OBJECT_CLASS_NAME(class), key_str);
1210 g_value_init(¶m->value, G_PARAM_SPEC_VALUE_TYPE(pspec));
1211 if (pyg_param_gvalue_from_pyobject(¶m->value, value, pspec) < 0) {
1212 PyErr_Format(PyExc_TypeError,
1213 "could not convert value for property `%s' from %s to %s",
1214 key_str, Py_TYPE(value)->tp_name,
1215 g_type_name(G_PARAM_SPEC_VALUE_TYPE(pspec)));
1218 param->name = g_strdup(key_str);
1225 /* ---------------- PyGObject methods ----------------- */
1228 pygobject_init(PyGObject *self, PyObject *args, PyObject *kwargs)
1231 guint n_params = 0, i;
1232 GParameter *params = NULL;
1233 GObjectClass *class;
1235 /* Only do GObject creation and property setting if the GObject hasn't
1236 * already been created. The case where self->obj already exists can occur
1237 * when C constructors are called directly (Gtk.Button.new_with_label)
1238 * and we are simply wrapping the result with a PyGObject.
1239 * In these cases we want to ignore any keyword arguments passed along
1240 * to __init__ and simply return.
1242 * See: https://bugzilla.gnome.org/show_bug.cgi?id=705810
1244 if (self->obj != NULL)
1247 if (!PyArg_ParseTuple(args, ":GObject.__init__", NULL))
1250 object_type = pyg_type_from_object((PyObject *)self);
1254 if (G_TYPE_IS_ABSTRACT(object_type)) {
1255 PyErr_Format(PyExc_TypeError, "cannot create instance of abstract "
1256 "(non-instantiable) type `%s'", g_type_name(object_type));
1260 if ((class = g_type_class_ref (object_type)) == NULL) {
1261 PyErr_SetString(PyExc_TypeError,
1262 "could not get a reference to type class");
1266 if (!pygobject_prepare_construct_properties (class, kwargs, &n_params, ¶ms))
1269 if (pygobject_constructv(self, n_params, params))
1270 PyErr_SetString(PyExc_RuntimeError, "could not create object");
1273 for (i = 0; i < n_params; i++) {
1274 g_free((gchar *) params[i].name);
1275 g_value_unset(¶ms[i].value);
1278 g_type_class_unref(class);
1280 return (self->obj) ? 0 : -1;
1283 #define CHECK_GOBJECT(self) \
1284 if (!G_IS_OBJECT(self->obj)) { \
1285 PyErr_Format(PyExc_TypeError, \
1286 "object at %p of type %s is not initialized", \
1287 self, Py_TYPE(self)->tp_name); \
1292 pygobject_get_property (PyGObject *self, PyObject *args)
1296 if (!PyArg_ParseTuple (args, "s:GObject.get_property", ¶m_name)) {
1300 CHECK_GOBJECT(self);
1302 return pygi_get_property_value_by_name (self, param_name);
1306 pygobject_get_properties(PyGObject *self, PyObject *args)
1311 if ((len = PyTuple_Size(args)) < 1) {
1312 PyErr_SetString(PyExc_TypeError, "requires at least one argument");
1316 tuple = PyTuple_New(len);
1317 for (i = 0; i < len; i++) {
1318 PyObject *py_property = PyTuple_GetItem(args, i);
1319 gchar *property_name;
1322 if (!PYGLIB_PyUnicode_Check(py_property)) {
1323 PyErr_SetString(PyExc_TypeError,
1324 "Expected string argument for property.");
1328 property_name = PYGLIB_PyUnicode_AsString(py_property);
1329 item = pygi_get_property_value_by_name (self, property_name);
1330 PyTuple_SetItem (tuple, i, item);
1341 pygobject_set_property(PyGObject *self, PyObject *args)
1348 if (!PyArg_ParseTuple(args, "sO:GObject.set_property", ¶m_name,
1352 CHECK_GOBJECT(self);
1354 pspec = g_object_class_find_property(G_OBJECT_GET_CLASS(self->obj),
1357 PyErr_Format(PyExc_TypeError,
1358 "object of type `%s' does not have property `%s'",
1359 g_type_name(G_OBJECT_TYPE(self->obj)), param_name);
1363 ret = pygi_set_property_value (self, pspec, pvalue);
1366 else if (PyErr_Occurred())
1369 if (!set_property_from_pspec(self->obj, pspec, pvalue))
1379 pygobject_set_properties(PyGObject *self, PyObject *args, PyObject *kwargs)
1381 GObjectClass *class;
1385 PyObject *result = NULL;
1387 CHECK_GOBJECT(self);
1389 class = G_OBJECT_GET_CLASS(self->obj);
1391 g_object_freeze_notify (G_OBJECT(self->obj));
1394 while (kwargs && PyDict_Next (kwargs, &pos, &key, &value)) {
1395 gchar *key_str = PYGLIB_PyUnicode_AsString(key);
1399 pspec = g_object_class_find_property(class, key_str);
1403 g_snprintf(buf, sizeof(buf),
1404 "object `%s' doesn't support property `%s'",
1405 g_type_name(G_OBJECT_TYPE(self->obj)), key_str);
1406 PyErr_SetString(PyExc_TypeError, buf);
1410 ret = pygi_set_property_value (self, pspec, value);
1412 /* Non-zero return code means that either an error occured ...*/
1413 if (PyErr_Occurred())
1416 /* ... or the property couldn't be found , so let's try the default
1418 if (!set_property_from_pspec(G_OBJECT(self->obj), pspec, value))
1426 g_object_thaw_notify (G_OBJECT(self->obj));
1431 /* custom closure for gobject bindings */
1433 pygbinding_closure_invalidate(gpointer data, GClosure *closure)
1435 PyGClosure *pc = (PyGClosure *)closure;
1436 PyGILState_STATE state;
1438 state = pyglib_gil_state_ensure();
1439 Py_XDECREF(pc->callback);
1440 Py_XDECREF(pc->extra_args);
1441 pyglib_gil_state_release(state);
1443 pc->callback = NULL;
1444 pc->extra_args = NULL;
1448 pygbinding_marshal (GClosure *closure,
1449 GValue *return_value,
1450 guint n_param_values,
1451 const GValue *param_values,
1452 gpointer invocation_hint,
1453 gpointer marshal_data)
1455 PyGILState_STATE state;
1456 PyGClosure *pc = (PyGClosure *)closure;
1457 PyObject *params, *ret;
1460 state = pyglib_gil_state_ensure();
1462 /* construct Python tuple for the parameter values */
1463 params = PyTuple_New(2);
1464 PyTuple_SetItem (params, 0, pyg_value_as_pyobject(¶m_values[0], FALSE));
1465 PyTuple_SetItem (params, 1, pyg_value_as_pyobject(¶m_values[1], FALSE));
1467 /* params passed to function may have extra arguments */
1468 if (pc->extra_args) {
1469 PyObject *tuple = params;
1470 params = PySequence_Concat(tuple, pc->extra_args);
1473 ret = PyObject_CallObject(pc->callback, params);
1477 } else if (ret == Py_None) {
1478 g_value_set_boolean (return_value, FALSE);
1482 out_value = g_value_get_boxed (¶m_values[2]);
1483 if (pyg_value_from_pyobject (out_value, ret) != 0) {
1484 PyErr_SetString (PyExc_ValueError, "can't convert value");
1486 g_value_set_boolean (return_value, FALSE);
1488 g_value_set_boolean (return_value, TRUE);
1495 pyglib_gil_state_release(state);
1499 pygbinding_closure_new (PyObject *callback, PyObject *extra_args)
1503 g_return_val_if_fail(callback != NULL, NULL);
1504 closure = g_closure_new_simple(sizeof(PyGClosure), NULL);
1505 g_closure_add_invalidate_notifier(closure, NULL, pygbinding_closure_invalidate);
1506 g_closure_set_marshal(closure, pygbinding_marshal);
1507 Py_INCREF(callback);
1508 ((PyGClosure *)closure)->callback = callback;
1509 if (extra_args && extra_args != Py_None) {
1510 Py_INCREF(extra_args);
1511 if (!PyTuple_Check(extra_args)) {
1512 PyObject *tmp = PyTuple_New(1);
1513 PyTuple_SetItem(tmp, 0, extra_args);
1516 ((PyGClosure *)closure)->extra_args = extra_args;
1522 pygobject_bind_property(PyGObject *self, PyObject *args)
1524 gchar *source_name, *target_name;
1525 gchar *source_canon, *target_canon;
1526 PyObject *target, *source_repr, *target_repr;
1527 PyObject *transform_to, *transform_from, *user_data = NULL;
1529 GBindingFlags flags = G_BINDING_DEFAULT;
1530 GClosure *to_closure = NULL, *from_closure = NULL;
1532 transform_from = NULL;
1533 transform_to = NULL;
1535 if (!PyArg_ParseTuple(args, "sOs|iOOO:GObject.bind_property",
1536 &source_name, &target, &target_name, &flags,
1537 &transform_to, &transform_from, &user_data))
1540 CHECK_GOBJECT(self);
1541 if (!PyObject_TypeCheck(target, &PyGObject_Type)) {
1542 PyErr_SetString(PyExc_TypeError, "Second argument must be a GObject");
1546 if (transform_to && transform_to != Py_None) {
1547 if (!PyCallable_Check (transform_to)) {
1548 PyErr_SetString (PyExc_TypeError,
1549 "transform_to must be callable or None");
1552 to_closure = pygbinding_closure_new (transform_to, user_data);
1555 if (transform_from && transform_from != Py_None) {
1556 if (!PyCallable_Check (transform_from)) {
1557 PyErr_SetString (PyExc_TypeError,
1558 "transform_from must be callable or None");
1561 from_closure = pygbinding_closure_new (transform_from, user_data);
1564 /* Canonicalize underscores to hyphens. Note the results must be freed. */
1565 source_canon = g_strdelimit(g_strdup(source_name), "_", '-');
1566 target_canon = g_strdelimit(g_strdup(target_name), "_", '-');
1568 binding = g_object_bind_property_with_closures (G_OBJECT(self->obj), source_canon,
1569 pygobject_get(target), target_canon,
1570 flags, to_closure, from_closure);
1571 g_free(source_canon);
1572 g_free(target_canon);
1573 source_canon = target_canon = NULL;
1575 if (binding == NULL) {
1576 source_repr = PyObject_Repr((PyObject*)self);
1577 target_repr = PyObject_Repr(target);
1578 PyErr_Format(PyExc_TypeError, "Cannot create binding from %s.%s to %s.%s",
1579 PYGLIB_PyUnicode_AsString(source_repr), source_name,
1580 PYGLIB_PyUnicode_AsString(target_repr), target_name);
1581 Py_DECREF(source_repr);
1582 Py_DECREF(target_repr);
1586 return pygobject_new (G_OBJECT (binding));
1590 connect_helper(PyGObject *self, gchar *name, PyObject *callback, PyObject *extra_args, PyObject *object, gboolean after)
1594 GClosure *closure = NULL;
1596 GSignalQuery query_info;
1598 if (!g_signal_parse_name(name, G_OBJECT_TYPE(self->obj),
1599 &sigid, &detail, TRUE)) {
1600 PyObject *repr = PyObject_Repr((PyObject*)self);
1601 PyErr_Format(PyExc_TypeError, "%s: unknown signal name: %s",
1602 PYGLIB_PyUnicode_AsString(repr),
1608 if (object && !PyObject_TypeCheck (object, &PyGObject_Type)) {
1609 if (PyErr_WarnEx (PyGIDeprecationWarning,
1610 "Using non GObject arguments for connect_object() is deprecated, use: "
1611 "connect_data(signal, callback, data, connect_flags=GObject.ConnectFlags.SWAPPED)",
1617 g_signal_query (sigid, &query_info);
1618 if (!pyg_gtype_is_custom (query_info.itype)) {
1619 /* The signal is implemented by a non-Python class, probably
1620 * something in the gi repository. */
1621 closure = pygi_signal_closure_new (self, query_info.itype,
1622 query_info.signal_name, callback,
1623 extra_args, object);
1627 /* The signal is either implemented at the Python level, or it comes
1628 * from a foreign class that we don't have introspection data for. */
1629 closure = pyg_closure_new (callback, extra_args, object);
1632 pygobject_watch_closure((PyObject *)self, closure);
1633 handlerid = g_signal_connect_closure_by_id(self->obj, sigid, detail,
1635 return PyLong_FromUnsignedLong(handlerid);
1639 pygobject_connect(PyGObject *self, PyObject *args)
1641 PyObject *first, *callback, *extra_args, *ret;
1645 len = PyTuple_Size(args);
1647 PyErr_SetString(PyExc_TypeError,
1648 "GObject.connect requires at least 2 arguments");
1651 first = PySequence_GetSlice(args, 0, 2);
1652 if (!PyArg_ParseTuple(first, "sO:GObject.connect", &name, &callback)) {
1657 if (!PyCallable_Check(callback)) {
1658 PyErr_SetString(PyExc_TypeError, "second argument must be callable");
1662 CHECK_GOBJECT(self);
1664 extra_args = PySequence_GetSlice(args, 2, len);
1665 if (extra_args == NULL)
1668 ret = connect_helper(self, name, callback, extra_args, NULL, FALSE);
1669 Py_DECREF(extra_args);
1674 pygobject_connect_after(PyGObject *self, PyObject *args)
1676 PyObject *first, *callback, *extra_args, *ret;
1680 len = PyTuple_Size(args);
1682 PyErr_SetString(PyExc_TypeError,
1683 "GObject.connect_after requires at least 2 arguments");
1686 first = PySequence_GetSlice(args, 0, 2);
1687 if (!PyArg_ParseTuple(first, "sO:GObject.connect_after",
1688 &name, &callback)) {
1693 if (!PyCallable_Check(callback)) {
1694 PyErr_SetString(PyExc_TypeError, "second argument must be callable");
1698 CHECK_GOBJECT(self);
1700 extra_args = PySequence_GetSlice(args, 2, len);
1701 if (extra_args == NULL)
1704 ret = connect_helper(self, name, callback, extra_args, NULL, TRUE);
1705 Py_DECREF(extra_args);
1710 pygobject_connect_object(PyGObject *self, PyObject *args)
1712 PyObject *first, *callback, *extra_args, *object, *ret;
1716 len = PyTuple_Size(args);
1718 PyErr_SetString(PyExc_TypeError,
1719 "GObject.connect_object requires at least 3 arguments");
1722 first = PySequence_GetSlice(args, 0, 3);
1723 if (!PyArg_ParseTuple(first, "sOO:GObject.connect_object",
1724 &name, &callback, &object)) {
1729 if (!PyCallable_Check(callback)) {
1730 PyErr_SetString(PyExc_TypeError, "second argument must be callable");
1734 CHECK_GOBJECT(self);
1736 extra_args = PySequence_GetSlice(args, 3, len);
1737 if (extra_args == NULL)
1740 ret = connect_helper(self, name, callback, extra_args, object, FALSE);
1741 Py_DECREF(extra_args);
1746 pygobject_connect_object_after(PyGObject *self, PyObject *args)
1748 PyObject *first, *callback, *extra_args, *object, *ret;
1752 len = PyTuple_Size(args);
1754 PyErr_SetString(PyExc_TypeError,
1755 "GObject.connect_object_after requires at least 3 arguments");
1758 first = PySequence_GetSlice(args, 0, 3);
1759 if (!PyArg_ParseTuple(first, "sOO:GObject.connect_object_after",
1760 &name, &callback, &object)) {
1765 if (!PyCallable_Check(callback)) {
1766 PyErr_SetString(PyExc_TypeError, "second argument must be callable");
1770 CHECK_GOBJECT(self);
1772 extra_args = PySequence_GetSlice(args, 3, len);
1773 if (extra_args == NULL)
1776 ret = connect_helper(self, name, callback, extra_args, object, TRUE);
1777 Py_DECREF(extra_args);
1782 pygobject_emit(PyGObject *self, PyObject *args)
1784 guint signal_id, i, j;
1787 PyObject *first, *py_ret, *repr = NULL;
1790 GValue *params, ret = { 0, };
1792 len = PyTuple_Size(args);
1794 PyErr_SetString(PyExc_TypeError,"GObject.emit needs at least one arg");
1797 first = PySequence_GetSlice(args, 0, 1);
1798 if (!PyArg_ParseTuple(first, "s:GObject.emit", &name)) {
1804 CHECK_GOBJECT(self);
1806 if (!g_signal_parse_name(name, G_OBJECT_TYPE(self->obj),
1807 &signal_id, &detail, TRUE)) {
1808 repr = PyObject_Repr((PyObject*)self);
1809 PyErr_Format(PyExc_TypeError, "%s: unknown signal name: %s",
1810 PYGLIB_PyUnicode_AsString(repr),
1815 g_signal_query(signal_id, &query);
1816 if (len != query.n_params + 1) {
1819 g_snprintf(buf, sizeof(buf),
1820 "%d parameters needed for signal %s; %ld given",
1821 query.n_params, name, (long int) (len - 1));
1822 PyErr_SetString(PyExc_TypeError, buf);
1826 params = g_new0(GValue, query.n_params + 1);
1827 g_value_init(¶ms[0], G_OBJECT_TYPE(self->obj));
1828 g_value_set_object(¶ms[0], G_OBJECT(self->obj));
1830 for (i = 0; i < query.n_params; i++)
1831 g_value_init(¶ms[i + 1],
1832 query.param_types[i] & ~G_SIGNAL_TYPE_STATIC_SCOPE);
1833 for (i = 0; i < query.n_params; i++) {
1834 PyObject *item = PyTuple_GetItem(args, i+1);
1836 if (pyg_value_from_pyobject(¶ms[i+1], item) < 0) {
1838 g_snprintf(buf, sizeof(buf),
1839 "could not convert type %s to %s required for parameter %d",
1840 Py_TYPE(item)->tp_name,
1841 G_VALUE_TYPE_NAME(¶ms[i+1]), i);
1842 PyErr_SetString(PyExc_TypeError, buf);
1844 for (j = 0; j <= i; j++)
1845 g_value_unset(¶ms[j]);
1852 if (query.return_type != G_TYPE_NONE)
1853 g_value_init(&ret, query.return_type & ~G_SIGNAL_TYPE_STATIC_SCOPE);
1855 g_signal_emitv(params, signal_id, detail, &ret);
1857 for (i = 0; i < query.n_params + 1; i++)
1858 g_value_unset(¶ms[i]);
1861 if ((query.return_type & ~G_SIGNAL_TYPE_STATIC_SCOPE) != G_TYPE_NONE) {
1862 py_ret = pyg_value_as_pyobject(&ret, TRUE);
1863 g_value_unset(&ret);
1873 pygobject_chain_from_overridden(PyGObject *self, PyObject *args)
1875 GSignalInvocationHint *ihint;
1881 GValue *params, ret = { 0, };
1883 CHECK_GOBJECT(self);
1885 ihint = g_signal_get_invocation_hint(self->obj);
1887 PyErr_SetString(PyExc_TypeError, "could not find signal invocation "
1888 "information for this object.");
1892 signal_id = ihint->signal_id;
1893 name = g_signal_name(signal_id);
1895 len = PyTuple_Size(args);
1896 if (signal_id == 0) {
1897 PyErr_SetString(PyExc_TypeError, "unknown signal name");
1900 g_signal_query(signal_id, &query);
1901 if (len != query.n_params) {
1904 g_snprintf(buf, sizeof(buf),
1905 "%d parameters needed for signal %s; %ld given",
1906 query.n_params, name, (long int) len);
1907 PyErr_SetString(PyExc_TypeError, buf);
1910 params = g_new0(GValue, query.n_params + 1);
1911 g_value_init(¶ms[0], G_OBJECT_TYPE(self->obj));
1912 g_value_set_object(¶ms[0], G_OBJECT(self->obj));
1914 for (i = 0; i < query.n_params; i++)
1915 g_value_init(¶ms[i + 1],
1916 query.param_types[i] & ~G_SIGNAL_TYPE_STATIC_SCOPE);
1917 for (i = 0; i < query.n_params; i++) {
1918 PyObject *item = PyTuple_GetItem(args, i);
1920 if (pyg_boxed_check(item, (query.param_types[i] & ~G_SIGNAL_TYPE_STATIC_SCOPE))) {
1921 g_value_set_static_boxed(¶ms[i+1], pyg_boxed_get(item, void));
1923 else if (pyg_value_from_pyobject(¶ms[i+1], item) < 0) {
1926 g_snprintf(buf, sizeof(buf),
1927 "could not convert type %s to %s required for parameter %d",
1928 Py_TYPE(item)->tp_name,
1929 g_type_name(G_VALUE_TYPE(¶ms[i+1])), i);
1930 PyErr_SetString(PyExc_TypeError, buf);
1931 for (i = 0; i < query.n_params + 1; i++)
1932 g_value_unset(¶ms[i]);
1937 if (query.return_type != G_TYPE_NONE)
1938 g_value_init(&ret, query.return_type & ~G_SIGNAL_TYPE_STATIC_SCOPE);
1939 g_signal_chain_from_overridden(params, &ret);
1940 for (i = 0; i < query.n_params + 1; i++)
1941 g_value_unset(¶ms[i]);
1943 if (query.return_type != G_TYPE_NONE) {
1944 py_ret = pyg_value_as_pyobject(&ret, TRUE);
1945 g_value_unset(&ret);
1955 pygobject_weak_ref(PyGObject *self, PyObject *args)
1958 PyObject *callback = NULL, *user_data = NULL;
1961 CHECK_GOBJECT(self);
1963 if ((len = PySequence_Length(args)) >= 1) {
1964 callback = PySequence_ITEM(args, 0);
1965 user_data = PySequence_GetSlice(args, 1, len);
1967 retval = pygobject_weak_ref_new(self->obj, callback, user_data);
1968 Py_XDECREF(callback);
1969 Py_XDECREF(user_data);
1975 pygobject_copy(PyGObject *self)
1977 PyErr_SetString(PyExc_TypeError,
1978 "GObject descendants' instances are non-copyable");
1983 pygobject_deepcopy(PyGObject *self, PyObject *args)
1985 PyErr_SetString(PyExc_TypeError,
1986 "GObject descendants' instances are non-copyable");
1992 pygobject_disconnect_by_func(PyGObject *self, PyObject *args)
1994 PyObject *pyfunc = NULL, *repr = NULL;
1995 GClosure *closure = NULL;
1998 CHECK_GOBJECT(self);
2000 if (!PyArg_ParseTuple(args, "O:GObject.disconnect_by_func", &pyfunc))
2003 if (!PyCallable_Check(pyfunc)) {
2004 PyErr_SetString(PyExc_TypeError, "first argument must be callable");
2008 closure = gclosure_from_pyfunc(self, pyfunc);
2010 repr = PyObject_Repr((PyObject*)pyfunc);
2011 PyErr_Format(PyExc_TypeError, "nothing connected to %s",
2012 PYGLIB_PyUnicode_AsString(repr));
2017 retval = g_signal_handlers_disconnect_matched(self->obj,
2018 G_SIGNAL_MATCH_CLOSURE,
2022 return PYGLIB_PyLong_FromLong(retval);
2026 pygobject_handler_block_by_func(PyGObject *self, PyObject *args)
2028 PyObject *pyfunc = NULL, *repr = NULL;
2029 GClosure *closure = NULL;
2032 CHECK_GOBJECT(self);
2034 if (!PyArg_ParseTuple(args, "O:GObject.handler_block_by_func", &pyfunc))
2037 if (!PyCallable_Check(pyfunc)) {
2038 PyErr_SetString(PyExc_TypeError, "first argument must be callable");
2042 closure = gclosure_from_pyfunc(self, pyfunc);
2044 repr = PyObject_Repr((PyObject*)pyfunc);
2045 PyErr_Format(PyExc_TypeError, "nothing connected to %s",
2046 PYGLIB_PyUnicode_AsString(repr));
2051 retval = g_signal_handlers_block_matched(self->obj,
2052 G_SIGNAL_MATCH_CLOSURE,
2056 return PYGLIB_PyLong_FromLong(retval);
2060 pygobject_handler_unblock_by_func(PyGObject *self, PyObject *args)
2062 PyObject *pyfunc = NULL, *repr = NULL;
2063 GClosure *closure = NULL;
2066 CHECK_GOBJECT(self);
2068 if (!PyArg_ParseTuple(args, "O:GObject.handler_unblock_by_func", &pyfunc))
2071 if (!PyCallable_Check(pyfunc)) {
2072 PyErr_SetString(PyExc_TypeError, "first argument must be callable");
2076 closure = gclosure_from_pyfunc(self, pyfunc);
2078 repr = PyObject_Repr((PyObject*)pyfunc);
2079 PyErr_Format(PyExc_TypeError, "nothing connected to %s",
2080 PYGLIB_PyUnicode_AsString(repr));
2085 retval = g_signal_handlers_unblock_matched(self->obj,
2086 G_SIGNAL_MATCH_CLOSURE,
2090 return PYGLIB_PyLong_FromLong(retval);
2094 static PyMethodDef pygobject_methods[] = {
2095 { "get_property", (PyCFunction)pygobject_get_property, METH_VARARGS },
2096 { "get_properties", (PyCFunction)pygobject_get_properties, METH_VARARGS },
2097 { "set_property", (PyCFunction)pygobject_set_property, METH_VARARGS },
2098 { "set_properties", (PyCFunction)pygobject_set_properties, METH_VARARGS|METH_KEYWORDS },
2099 { "bind_property", (PyCFunction)pygobject_bind_property, METH_VARARGS|METH_KEYWORDS },
2100 { "connect", (PyCFunction)pygobject_connect, METH_VARARGS },
2101 { "connect_after", (PyCFunction)pygobject_connect_after, METH_VARARGS },
2102 { "connect_object", (PyCFunction)pygobject_connect_object, METH_VARARGS },
2103 { "connect_object_after", (PyCFunction)pygobject_connect_object_after, METH_VARARGS },
2104 { "disconnect_by_func", (PyCFunction)pygobject_disconnect_by_func, METH_VARARGS },
2105 { "handler_block_by_func", (PyCFunction)pygobject_handler_block_by_func, METH_VARARGS },
2106 { "handler_unblock_by_func", (PyCFunction)pygobject_handler_unblock_by_func, METH_VARARGS },
2107 { "emit", (PyCFunction)pygobject_emit, METH_VARARGS },
2108 { "chain", (PyCFunction)pygobject_chain_from_overridden,METH_VARARGS },
2109 { "weak_ref", (PyCFunction)pygobject_weak_ref, METH_VARARGS },
2110 { "__copy__", (PyCFunction)pygobject_copy, METH_NOARGS },
2111 { "__deepcopy__", (PyCFunction)pygobject_deepcopy, METH_VARARGS },
2117 pygobject_get_dict(PyGObject *self, void *closure)
2119 if (self->inst_dict == NULL) {
2120 self->inst_dict = PyDict_New();
2121 if (self->inst_dict == NULL)
2123 if (G_LIKELY(self->obj))
2124 pygobject_switch_to_toggle_ref(self);
2126 Py_INCREF(self->inst_dict);
2127 return self->inst_dict;
2131 pygobject_get_refcount(PyGObject *self, void *closure)
2133 if (self->obj == NULL) {
2134 PyErr_Format(PyExc_TypeError, "GObject instance is not yet created");
2137 return PYGLIB_PyLong_FromLong(self->obj->ref_count);
2141 pygobject_get_pointer(PyGObject *self, void *closure)
2143 return PYGLIB_CPointer_WrapPointer (self->obj, NULL);
2147 pygobject_setattro(PyObject *self, PyObject *name, PyObject *value)
2150 PyGObject *gself = (PyGObject *) self;
2151 PyObject *inst_dict_before = gself->inst_dict;
2152 /* call parent type's setattro */
2153 res = PyGObject_Type.tp_base->tp_setattro(self, name, value);
2154 if (inst_dict_before == NULL && gself->inst_dict != NULL) {
2155 if (G_LIKELY(gself->obj))
2156 pygobject_switch_to_toggle_ref(gself);
2161 static PyGetSetDef pygobject_getsets[] = {
2162 { "__dict__", (getter)pygobject_get_dict, (setter)0 },
2163 { "__grefcount__", (getter)pygobject_get_refcount, (setter)0, },
2164 { "__gpointer__", (getter)pygobject_get_pointer, (setter)0, },
2168 /* ------------------------------------ */
2169 /* ****** GObject weak reference ****** */
2170 /* ------------------------------------ */
2176 PyObject *user_data;
2177 gboolean have_floating_ref;
2180 PYGLIB_DEFINE_TYPE("gi._gobject.GObjectWeakRef", PyGObjectWeakRef_Type, PyGObjectWeakRef);
2183 pygobject_weak_ref_traverse(PyGObjectWeakRef *self, visitproc visit, void *arg)
2185 if (self->callback && visit(self->callback, arg) < 0)
2187 if (self->user_data && visit(self->user_data, arg) < 0)
2193 pygobject_weak_ref_notify(PyGObjectWeakRef *self, GObject *dummy)
2196 if (self->callback) {
2198 PyGILState_STATE state = pyglib_gil_state_ensure();
2199 retval = PyObject_Call(self->callback, self->user_data, NULL);
2201 if (retval != Py_None)
2202 PyErr_Format(PyExc_TypeError,
2203 "GObject weak notify callback returned a value"
2204 " of type %s, should return None",
2205 Py_TYPE(retval)->tp_name);
2210 Py_CLEAR(self->callback);
2211 Py_CLEAR(self->user_data);
2212 if (self->have_floating_ref) {
2213 self->have_floating_ref = FALSE;
2214 Py_DECREF((PyObject *) self);
2216 pyglib_gil_state_release(state);
2221 pygobject_weak_ref_clear(PyGObjectWeakRef *self)
2223 Py_CLEAR(self->callback);
2224 Py_CLEAR(self->user_data);
2226 g_object_weak_unref(self->obj, (GWeakNotify) pygobject_weak_ref_notify, self);
2233 pygobject_weak_ref_dealloc(PyGObjectWeakRef *self)
2235 PyObject_GC_UnTrack((PyObject *)self);
2236 pygobject_weak_ref_clear(self);
2237 PyObject_GC_Del(self);
2241 pygobject_weak_ref_new(GObject *obj, PyObject *callback, PyObject *user_data)
2243 PyGObjectWeakRef *self;
2245 self = PyObject_GC_New(PyGObjectWeakRef, &PyGObjectWeakRef_Type);
2246 self->callback = callback;
2247 self->user_data = user_data;
2248 Py_XINCREF(self->callback);
2249 Py_XINCREF(self->user_data);
2251 g_object_weak_ref(self->obj, (GWeakNotify) pygobject_weak_ref_notify, self);
2252 if (callback != NULL) {
2253 /* when we have a callback, we should INCREF the weakref
2254 * object to make it stay alive even if it goes out of scope */
2255 self->have_floating_ref = TRUE;
2256 Py_INCREF((PyObject *) self);
2258 return (PyObject *) self;
2262 pygobject_weak_ref_unref(PyGObjectWeakRef *self, PyObject *args)
2265 PyErr_SetString(PyExc_ValueError, "weak ref already unreffed");
2268 g_object_weak_unref(self->obj, (GWeakNotify) pygobject_weak_ref_notify, self);
2270 if (self->have_floating_ref) {
2271 self->have_floating_ref = FALSE;
2278 static PyMethodDef pygobject_weak_ref_methods[] = {
2279 { "unref", (PyCFunction)pygobject_weak_ref_unref, METH_NOARGS},
2284 pygobject_weak_ref_call(PyGObjectWeakRef *self, PyObject *args, PyObject *kw)
2286 static char *argnames[] = {NULL};
2288 if (!PyArg_ParseTupleAndKeywords(args, kw, ":__call__", argnames))
2292 return pygobject_new(self->obj);
2300 pyobject_copy(gpointer boxed)
2302 PyObject *object = boxed;
2303 PyGILState_STATE state;
2305 state = pyglib_gil_state_ensure();
2307 pyglib_gil_state_release(state);
2312 pyobject_free(gpointer boxed)
2314 PyObject *object = boxed;
2315 PyGILState_STATE state;
2317 state = pyglib_gil_state_ensure();
2319 pyglib_gil_state_release(state);
2323 pygobject_object_register_types(PyObject *d)
2325 PyObject *o, *descr;
2327 pygobject_custom_key = g_quark_from_static_string("PyGObject::custom");
2328 pygobject_class_key = g_quark_from_static_string("PyGObject::class");
2329 pygobject_class_init_key = g_quark_from_static_string("PyGObject::class-init");
2330 pygobject_wrapper_key = g_quark_from_static_string("PyGObject::wrapper");
2331 pygobject_has_updated_constructor_key =
2332 g_quark_from_static_string("PyGObject::has-updated-constructor");
2333 pygobject_instance_data_key = g_quark_from_static_string("PyGObject::instance-data");
2336 if (!PY_TYPE_OBJECT)
2337 PY_TYPE_OBJECT = g_boxed_type_register_static("PyObject",
2340 PyGObject_Type.tp_dealloc = (destructor)pygobject_dealloc;
2341 PyGObject_Type.tp_richcompare = pygobject_richcompare;
2342 PyGObject_Type.tp_repr = (reprfunc)pygobject_repr;
2343 PyGObject_Type.tp_hash = (hashfunc)pygobject_hash;
2344 PyGObject_Type.tp_setattro = (setattrofunc)pygobject_setattro;
2345 PyGObject_Type.tp_flags = (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
2346 Py_TPFLAGS_HAVE_GC);
2347 PyGObject_Type.tp_traverse = (traverseproc)pygobject_traverse;
2348 PyGObject_Type.tp_clear = (inquiry)pygobject_clear;
2349 PyGObject_Type.tp_weaklistoffset = offsetof(PyGObject, weakreflist);
2350 PyGObject_Type.tp_methods = pygobject_methods;
2351 PyGObject_Type.tp_getset = pygobject_getsets;
2352 PyGObject_Type.tp_dictoffset = offsetof(PyGObject, inst_dict);
2353 PyGObject_Type.tp_init = (initproc)pygobject_init;
2354 PyGObject_Type.tp_free = (freefunc)pygobject_free;
2355 PyGObject_Type.tp_alloc = PyType_GenericAlloc;
2356 PyGObject_Type.tp_new = PyType_GenericNew;
2357 pygobject_register_class(d, "GObject", G_TYPE_OBJECT,
2358 &PyGObject_Type, NULL);
2359 PyDict_SetItemString(PyGObject_Type.tp_dict, "__gdoc__",
2360 pyg_object_descr_doc_get());
2363 PyGProps_Type.tp_dealloc = (destructor)PyGProps_dealloc;
2364 PyGProps_Type.tp_as_sequence = (PySequenceMethods*)&_PyGProps_as_sequence;
2365 PyGProps_Type.tp_getattro = (getattrofunc)PyGProps_getattro;
2366 PyGProps_Type.tp_setattro = (setattrofunc)PyGProps_setattro;
2367 PyGProps_Type.tp_flags = Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_GC;
2368 PyGProps_Type.tp_doc = "The properties of the GObject accessible as "
2369 "Python attributes.";
2370 PyGProps_Type.tp_traverse = (traverseproc)pygobject_props_traverse;
2371 PyGProps_Type.tp_iter = (getiterfunc)pygobject_props_get_iter;
2372 PyGProps_Type.tp_methods = pygobject_props_methods;
2373 if (PyType_Ready(&PyGProps_Type) < 0)
2377 PyGPropsDescr_Type.tp_flags = Py_TPFLAGS_DEFAULT;
2378 PyGPropsDescr_Type.tp_descr_get = pyg_props_descr_descr_get;
2379 if (PyType_Ready(&PyGPropsDescr_Type) < 0)
2381 descr = PyObject_New(PyObject, &PyGPropsDescr_Type);
2382 PyDict_SetItemString(PyGObject_Type.tp_dict, "props", descr);
2383 PyDict_SetItemString(PyGObject_Type.tp_dict, "__module__",
2384 o=PYGLIB_PyUnicode_FromString("gi._gobject._gobject"));
2388 PyGPropsIter_Type.tp_dealloc = (destructor)pyg_props_iter_dealloc;
2389 PyGPropsIter_Type.tp_flags = Py_TPFLAGS_DEFAULT;
2390 PyGPropsIter_Type.tp_doc = "GObject properties iterator";
2391 PyGPropsIter_Type.tp_iternext = (iternextfunc)pygobject_props_iter_next;
2392 if (PyType_Ready(&PyGPropsIter_Type) < 0)
2395 PyGObjectWeakRef_Type.tp_dealloc = (destructor)pygobject_weak_ref_dealloc;
2396 PyGObjectWeakRef_Type.tp_call = (ternaryfunc)pygobject_weak_ref_call;
2397 PyGObjectWeakRef_Type.tp_flags = Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_GC;
2398 PyGObjectWeakRef_Type.tp_doc = "A GObject weak reference";
2399 PyGObjectWeakRef_Type.tp_traverse = (traverseproc)pygobject_weak_ref_traverse;
2400 PyGObjectWeakRef_Type.tp_clear = (inquiry)pygobject_weak_ref_clear;
2401 PyGObjectWeakRef_Type.tp_methods = pygobject_weak_ref_methods;
2402 if (PyType_Ready(&PyGObjectWeakRef_Type) < 0)
2404 PyDict_SetItemString(d, "GObjectWeakRef", (PyObject *) &PyGObjectWeakRef_Type);