Debian Codegraph @

gi/pygobject-object.c

raw
1 /* -*- Mode: C; c-basic-offset: 4 -*-
2 * pygtk- Python bindings for the GTK toolkit.
3 * Copyright (C) 1998-2003 James Henstridge
4 *
5 * pygobject.c: wrapper for the GObject type.
6 *
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.
11 *
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.
16 *
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/>.
19 */
20
21 #include "pygobject-types.h"
22 #include "pygboxed.h"
23 #include "pygi-basictype.h"
24 #include "pygi-fundamental.h"
25 #include "pygi-property.h"
26 #include "pygi-signal-closure.h"
27 #include "pygi-type.h"
28 #include "pygi-util.h"
29 #include "pygi-value.h"
30 #include "pyginterface.h"
31 #include "pygobject-object.h"
32 #include "pygobject-props.h"
33
34 extern PyObject *PyGIDeprecationWarning;
35
36 static void pygobject_dealloc (PyGObject *self);
37 static int pygobject_traverse (PyGObject *self, visitproc visit, void *arg);
38 static PyObject *pyg_type_get_bases (GType gtype);
39 static int pygobject_clear (PyGObject *self);
40 static PyObject *pygobject_weak_ref_new (GObject *obj, PyObject *callback,
41 PyObject *user_data);
42 static void pygobject_inherit_slots (PyTypeObject *type, PyObject *bases,
43 gboolean check_for_present);
44 static void pygobject_find_slot_for (PyTypeObject *type, PyObject *bases,
45 int slot_offset,
46 gboolean check_for_present);
47
48 GType PY_TYPE_OBJECT = 0;
49 GQuark pygobject_custom_key;
50 GQuark pygobject_class_key;
51 GQuark pygobject_class_init_key;
52 GQuark pygobject_wrapper_key;
53 GQuark pygobject_instance_init_ref_count;
54 GQuark pygobject_instance_data_key;
55
56
57 static GClosure *
58 gclosure_from_pyfunc (PyGObject *object, PyObject *func)
59 {
60 GSList *l;
61 PyGObjectData *inst_data;
62 inst_data = pyg_object_peek_inst_data (object->obj);
63 if (inst_data) {
64 for (l = inst_data->closures; l; l = l->next) {
65 PyGClosure *pyclosure = l->data;
66 int res =
67 PyObject_RichCompareBool (pyclosure->callback, func, Py_EQ);
68 if (res == -1) {
69 PyErr_Clear (); /* Is there anything else to do? */
70 } else if (res) {
71 return (GClosure *)pyclosure;
72 }
73 }
74 }
75 return NULL;
76 }
77
78
79 /* -------------- class <-> wrapper manipulation --------------- */
80
81 static gboolean
82 pygobject_has_custom_do_dispose (PyObject *self)
83 {
84 PyTypeObject *type = Py_TYPE (self);
85 PyObject *mro;
86 PyObject *base_do_dispose;
87 Py_ssize_t i;
88
89 if (type == &PyGObject_Type) return FALSE;
90
91 mro = type->tp_mro;
92 if (mro == NULL) return FALSE;
93
94 base_do_dispose =
95 PyDict_GetItemString (PyGObject_Type.tp_dict, "do_dispose");
96
97 for (i = 0; i < PyTuple_GET_SIZE (mro); i++) {
98 PyTypeObject *mro_type = (PyTypeObject *)PyTuple_GET_ITEM (mro, i);
99 PyObject *do_dispose =
100 PyDict_GetItemString (mro_type->tp_dict, "do_dispose");
101
102 if (do_dispose != NULL) return do_dispose != base_do_dispose;
103 }
104
105 return FALSE;
106 }
107
108 static void
109 pygobject_data_free (PyGObjectData *data)
110 {
111 /* This function may be called after the python interpreter has already
112 * been shut down. If this happens, we cannot do any python calls, so just
113 * free the memory. */
114 PyGILState_STATE state = 0;
115 PyThreadState *_save = NULL;
116 gboolean state_saved;
117 GSList *closures, *tmp;
118
119 state_saved = Py_IsInitialized ();
120 if (state_saved) {
121 state = PyGILState_Ensure ();
122 Py_DECREF (data->type);
123 Py_CLEAR (data->inst_dict);
124 /* We cannot use Py_BEGIN_ALLOW_THREADS here because this is inside
125 * a branch. */
126 Py_UNBLOCK_THREADS; /* Modifies _save */
127 }
128
129 tmp = closures = data->closures;
130 #ifndef NDEBUG
131 data->closures = NULL;
132 data->type = NULL;
133 #endif
134 while (tmp) {
135 GClosure *closure = tmp->data;
136
137 /* we get next item first, because the current link gets
138 * invalidated by pygobject_unwatch_closure */
139 tmp = tmp->next;
140 g_closure_invalidate (closure);
141 }
142
143 if (data->closures != NULL)
144 g_warning ("invalidated all closures, but data->closures != NULL !");
145
146 g_free (data);
147
148 if (state_saved && Py_IsInitialized ()) {
149 Py_BLOCK_THREADS; /* Restores _save */
150 PyGILState_Release (state);
151 }
152 }
153
154 static inline PyGObjectData *
155 pygobject_get_inst_data (PyGObject *self)
156 {
157 PyGObjectData *inst_data;
158
159 if (G_UNLIKELY (!self->obj)) return NULL;
160 inst_data = g_object_get_qdata (self->obj, pygobject_instance_data_key);
161 if (inst_data == NULL) {
162 inst_data = g_new0 (PyGObjectData, 1);
163
164 inst_data->type = Py_TYPE (self);
165 Py_INCREF ((PyObject *)inst_data->type);
166
167
168 /* Add a marker so we know if we should create a new object
169 * to call `do_dispose` on. */
170 inst_data->call_do_dispose =
171 pygobject_has_custom_do_dispose ((PyObject *)self);
172
173 g_object_set_qdata_full (self->obj, pygobject_instance_data_key,
174 inst_data,
175 (GDestroyNotify)pygobject_data_free);
176 }
177 return inst_data;
178 }
179
180
181 PyTypeObject *PyGObject_MetaType = NULL;
182
183 /**
184 * pygobject_register_class:
185 * @dict: the module dictionary. A reference to the type will be stored here.
186 * @type_name: not used ?
187 * @gtype: the GType of the GObject subclass.
188 * @type: the Python type object for this wrapper.
189 * @static_bases: a tuple of Python type objects that are the bases of
190 * this type
191 *
192 * This function is used to register a Python type as the wrapper for
193 * a particular GObject subclass. It will also insert a reference to
194 * the wrapper class into the module dictionary passed as a reference,
195 * which simplifies initialisation.
196 */
197 void
198 pygobject_register_class (PyObject *dict, const gchar *type_name, GType gtype,
199 PyTypeObject *type, PyObject *static_bases)
200 {
201 PyObject *o;
202 const char *class_name, *s;
203 PyObject *runtime_bases;
204 PyObject *bases_list, *bases, *mod_name;
205 int i;
206
207 class_name = type->tp_name;
208 s = strrchr (class_name, '.');
209 if (s != NULL) class_name = s + 1;
210
211 runtime_bases = pyg_type_get_bases (gtype);
212 if (static_bases) {
213 PyTypeObject *py_parent_type =
214 (PyTypeObject *)PyTuple_GET_ITEM (static_bases, 0);
215 bases_list = PySequence_List (static_bases);
216 /* we start at index 1 because we want to skip the primary
217 * base, otherwise we might get MRO conflict */
218 for (i = 1; i < PyTuple_GET_SIZE (runtime_bases); ++i) {
219 PyObject *base = PyTuple_GET_ITEM (runtime_bases, i);
220 int contains = PySequence_Contains (bases_list, base);
221 if (contains < 0)
222 PyErr_Print ();
223 else if (!contains) {
224 if (!PySequence_Contains (py_parent_type->tp_mro, base)) {
225 #if 0
226 g_message("Adding missing base %s to type %s",
227 ((PyTypeObject *)base)->tp_name, type->tp_name);
228 #endif
229 PyList_Append (bases_list, base);
230 }
231 }
232 }
233 bases = PySequence_Tuple (bases_list);
234 Py_DECREF (bases_list);
235 Py_DECREF (runtime_bases);
236 } else
237 bases = runtime_bases;
238
239 Py_SET_TYPE (type, PyGObject_MetaType);
240 type->tp_bases = bases;
241 if (G_LIKELY (bases)) {
242 type->tp_base = (PyTypeObject *)PyTuple_GetItem (bases, 0);
243 Py_INCREF (type->tp_base);
244 }
245
246 pygobject_inherit_slots (type, bases, TRUE);
247
248 if (PyType_Ready (type) < 0) {
249 g_warning ("couldn't make the type `%s' ready", type->tp_name);
250 return;
251 }
252
253 /* Set type.__module__ to the name of the module,
254 * otherwise it'll default to 'gobject', see #376099
255 */
256 s = strrchr (type->tp_name, '.');
257 if (s != NULL) {
258 mod_name = PyUnicode_FromStringAndSize (type->tp_name,
259 (int)(s - type->tp_name));
260 PyDict_SetItemString (type->tp_dict, "__module__", mod_name);
261 Py_DECREF (mod_name);
262 }
263
264 if (gtype) {
265 o = pyg_type_wrapper_new (gtype);
266 PyDict_SetItemString (type->tp_dict, "__gtype__", o);
267 Py_DECREF (o);
268
269 /* stash a pointer to the python class with the GType */
270 Py_INCREF (type);
271 g_type_set_qdata (gtype, pygobject_class_key, type);
272 }
273
274 /* set up __doc__ descriptor on type */
275 PyDict_SetItemString (type->tp_dict, "__doc__",
276 pyg_object_descr_doc_get ());
277
278 PyDict_SetItemString (dict, (char *)class_name, (PyObject *)type);
279 }
280
281 /**
282 * pygobject_register_wrapper:
283 * @self: the wrapper instance
284 *
285 * In the constructor of PyGTK wrappers, this function should be
286 * called after setting the obj member. It will tie the wrapper
287 * instance to the GObject so that the same wrapper instance will
288 * always be used for this GObject instance.
289 */
290 void
291 pygobject_register_wrapper (PyObject *self)
292 {
293 PyObject *error_type, *error_value, *error_traceback;
294 gboolean have_error = !!PyErr_Occurred ();
295 PyGObject *gself;
296 PyGObjectData *inst_data;
297
298 g_return_if_fail (self != NULL);
299 g_return_if_fail (PyObject_TypeCheck (self, &PyGObject_Type));
300
301 if (have_error) PyErr_Fetch (&error_type, &error_value, &error_traceback);
302
303 gself = (PyGObject *)self;
304
305 g_assert (gself->obj->ref_count >= 1);
306
307 inst_data = pygobject_get_inst_data (gself);
308 g_assert (inst_data != NULL);
309
310 if (inst_data->inst_dict == NULL) {
311 PyObject *inst_dict = PyObject_GenericGetDict (self, NULL);
312 #ifdef PYPY_VERSION
313 inst_data->inst_dict = PyDict_Copy (inst_dict);
314 Py_DECREF (inst_dict);
315 PyObject_GenericSetDict (self, inst_data->inst_dict, NULL);
316 #else
317 inst_data->inst_dict = inst_dict;
318 #endif
319 } else {
320 PyObject_GenericSetDict (self, inst_data->inst_dict, NULL);
321 }
322
323 /* save wrapper pointer so we can access it later */
324 g_object_set_qdata_full (gself->obj, pygobject_wrapper_key, gself, NULL);
325
326 if (have_error) PyErr_Restore (error_type, error_value, error_traceback);
327 }
328
329 static PyObject *
330 pyg_type_get_bases (GType gtype)
331 {
332 GType *interfaces, parent_type, interface_type;
333 guint n_interfaces;
334 PyTypeObject *py_parent_type, *py_interface_type;
335 PyObject *bases;
336 guint i;
337
338 if (G_UNLIKELY (gtype == G_TYPE_OBJECT)) return NULL;
339
340 /* Lookup the parent type */
341 parent_type = g_type_parent (gtype);
342 py_parent_type = pygobject_lookup_class (parent_type);
343 interfaces = g_type_interfaces (gtype, &n_interfaces);
344 bases = PyTuple_New (n_interfaces + 1);
345 /* We will always put the parent at the first position in bases */
346 Py_INCREF (py_parent_type); /* PyTuple_SetItem steals a reference */
347 PyTuple_SetItem (bases, 0, (PyObject *)py_parent_type);
348
349 /* And traverse interfaces */
350 if (n_interfaces) {
351 for (i = 0; i < n_interfaces; i++) {
352 interface_type = interfaces[i];
353 py_interface_type = pygobject_lookup_class (interface_type);
354 Py_INCREF (
355 py_interface_type); /* PyTuple_SetItem steals a reference */
356 PyTuple_SetItem (bases, i + 1, (PyObject *)py_interface_type);
357 }
358 }
359 g_free (interfaces);
360 return bases;
361 }
362
363 /**
364 * pygobject_new_with_interfaces
365 * @gtype: the GType of the GObject subclass.
366 *
367 * Creates a new PyTypeObject from the given GType with interfaces attached in
368 * bases.
369 *
370 * Returns: a PyTypeObject for the new type or NULL if it couldn't be created
371 */
372 static PyTypeObject *
373 pygobject_new_with_interfaces (GType gtype)
374 {
375 PyGILState_STATE state;
376 PyObject *o;
377 PyTypeObject *type;
378 PyObject *dict;
379 PyTypeObject *py_parent_type;
380 PyObject *bases;
381
382 state = PyGILState_Ensure ();
383
384 bases = pyg_type_get_bases (gtype);
385 py_parent_type = (PyTypeObject *)PyTuple_GetItem (bases, 0);
386
387 dict = PyDict_New ();
388
389 o = pyg_type_wrapper_new (gtype);
390 PyDict_SetItemString (dict, "__gtype__", o);
391 Py_DECREF (o);
392
393 /* set up __doc__ descriptor on type */
394 PyDict_SetItemString (dict, "__doc__", pyg_object_descr_doc_get ());
395
396 /* Something special to point out that it's not accessible through
397 * gi.repository */
398 o = PyUnicode_FromString ("__gi__");
399 PyDict_SetItemString (dict, "__module__", o);
400 Py_DECREF (o);
401
402 type = (PyTypeObject *)PyObject_CallFunction (
403 (PyObject *)Py_TYPE (py_parent_type), "sNN", g_type_name (gtype),
404 bases, dict);
405
406 if (type == NULL) {
407 PyErr_Print ();
408 PyGILState_Release (state);
409 return NULL;
410 }
411
412 /* Workaround python tp_(get|set)attr slot inheritance bug.
413 * Fixes bug #144135. */
414 if (!type->tp_getattr && py_parent_type->tp_getattr) {
415 type->tp_getattro = NULL;
416 type->tp_getattr = py_parent_type->tp_getattr;
417 }
418 if (!type->tp_setattr && py_parent_type->tp_setattr) {
419 type->tp_setattro = NULL;
420 type->tp_setattr = py_parent_type->tp_setattr;
421 }
422 /* override more python stupid hacks behind our back */
423 type->tp_dealloc = py_parent_type->tp_dealloc;
424 type->tp_alloc = py_parent_type->tp_alloc;
425 type->tp_free = py_parent_type->tp_free;
426 type->tp_traverse = py_parent_type->tp_traverse;
427 type->tp_clear = py_parent_type->tp_clear;
428
429 pygobject_inherit_slots (type, bases, FALSE);
430
431 if (PyType_Ready (type) < 0) {
432 g_warning ("couldn't make the type `%s' ready", type->tp_name);
433 PyGILState_Release (state);
434 return NULL;
435 }
436
437 /* stash a pointer to the python class with the GType */
438 Py_INCREF (type);
439 g_type_set_qdata (gtype, pygobject_class_key, type);
440
441 PyGILState_Release (state);
442
443 return type;
444 }
445
446 /* Pick appropriate value for given slot (at slot_offset inside
447 * PyTypeObject structure). It must be a pointer, e.g. a pointer to a
448 * function. We use the following heuristic:
449 *
450 * - Scan all types listed as bases of the type.
451 * - If for exactly one base type slot value is non-NULL and
452 * different from that of 'object' and 'GObject', set current type
453 * slot into that value.
454 * - Otherwise (if there is more than one such base type or none at
455 * all) don't touch it and live with Python default.
456 *
457 * The intention here is to propagate slot from custom wrappers to
458 * wrappers created at runtime when appropriate. We prefer to be on
459 * the safe side, so if there is potential collision (more than one
460 * custom slot value), we discard custom overrides altogether.
461 *
462 * When registering type with pygobject_register_class(), i.e. a type
463 * that has been manually created (likely with Codegen help),
464 * `check_for_present' should be set to TRUE. In this case, the
465 * function will never overwrite any non-NULL slots already present in
466 * the type. If `check_for_present' is FALSE, such non-NULL slots are
467 * though to be set by Python interpreter and so will be overwritten
468 * if heuristic above says so.
469 */
470 static void
471 pygobject_inherit_slots (PyTypeObject *type, PyObject *bases,
472 gboolean check_for_present)
473 {
474 static int slot_offsets[] = {
475 offsetof (PyTypeObject, tp_richcompare),
476 offsetof (PyTypeObject, tp_richcompare),
477 offsetof (PyTypeObject, tp_hash),
478 offsetof (PyTypeObject, tp_iter),
479 offsetof (PyTypeObject, tp_repr),
480 offsetof (PyTypeObject, tp_str),
481 };
482 gsize i;
483
484 /* Happens when registering gobject.GObject itself, at least. */
485 if (!bases) return;
486
487 for (i = 0; i < G_N_ELEMENTS (slot_offsets); ++i)
488 pygobject_find_slot_for (type, bases, slot_offsets[i],
489 check_for_present);
490 }
491
492 static void
493 pygobject_find_slot_for (PyTypeObject *type, PyObject *bases, int slot_offset,
494 gboolean check_for_present)
495 {
496 #define TYPE_SLOT(type) (*(void **)(void *)(((char *)(type)) + slot_offset))
497
498 void *found_slot = NULL;
499 Py_ssize_t num_bases = PyTuple_Size (bases);
500 Py_ssize_t i;
501
502 if (check_for_present && TYPE_SLOT (type) != NULL) {
503 /* We are requested to check if there is any custom slot value
504 * in this type already and there actually is. Don't
505 * overwrite it.
506 */
507 return;
508 }
509
510 for (i = 0; i < num_bases; ++i) {
511 PyTypeObject *base_type = (PyTypeObject *)PyTuple_GetItem (bases, i);
512 void *slot = TYPE_SLOT (base_type);
513
514 if (slot == NULL) continue;
515 if (slot == TYPE_SLOT (&PyGObject_Type)
516 || slot == TYPE_SLOT (&PyBaseObject_Type))
517 continue;
518
519 if (found_slot != NULL && found_slot != slot) {
520 /* We have a conflict: more than one base use different
521 * custom slots. To be on the safe side, we bail out.
522 */
523 return;
524 }
525
526 found_slot = slot;
527 }
528
529 /* Only perform the final assignment if at least one base has a
530 * custom value. Otherwise just leave this type's slot untouched.
531 */
532 if (found_slot != NULL) TYPE_SLOT (type) = found_slot;
533
534 #undef TYPE_SLOT
535 }
536
537 /**
538 * pygobject_lookup_class:
539 * @gtype: the GType of the GObject subclass.
540 *
541 * This function looks up the wrapper class used to represent
542 * instances of a GObject represented by @gtype. If no wrapper class
543 * or interface has been registered for the given GType, then a new
544 * type will be created.
545 *
546 * Does not set an exception when NULL is returned.
547 *
548 * Returns: The wrapper class for the GObject or NULL if the
549 * GType has no registered type and a new type couldn't be created
550 */
551 PyTypeObject *
552 pygobject_lookup_class (GType gtype)
553 {
554 PyTypeObject *py_type;
555
556 if (gtype == G_TYPE_INTERFACE) return &PyGInterface_Type;
557
558 py_type = g_type_get_qdata (gtype, pygobject_class_key);
559 if (py_type == NULL) {
560 py_type = g_type_get_qdata (gtype, pyginterface_type_key);
561
562 if (py_type == NULL) {
563 py_type = (PyTypeObject *)pygi_type_import_by_g_type (gtype);
564 PyErr_Clear ();
565 }
566
567 if (py_type == NULL) {
568 py_type = pygobject_new_with_interfaces (gtype);
569 PyErr_Clear ();
570 g_type_set_qdata (gtype, pyginterface_type_key, py_type);
571 }
572 }
573
574 return py_type;
575 }
576
577 /**
578 * pygobject_new_full:
579 * @obj: a GObject instance.
580 * @steal: whether to steal a ref from the GObject or add (sink) a new one.
581 * @g_class: the GObjectClass
582 *
583 * This function gets a reference to a wrapper for the given GObject
584 * instance. If a wrapper has already been created, a new reference
585 * to that wrapper will be returned. Otherwise, a wrapper instance
586 * will be created.
587 *
588 * Returns: a reference to the wrapper for the GObject.
589 */
590 PyObject *
591 pygobject_new_full (GObject *obj, gboolean steal, gpointer g_class)
592 {
593 PyGObject *self;
594
595 if (obj == NULL) {
596 Py_RETURN_NONE;
597 }
598
599 /* If the GObject already has a PyObject wrapper stashed in its qdata, re-use it.
600 */
601 self = (PyGObject *)g_object_get_qdata (obj, pygobject_wrapper_key);
602 if (self != NULL) {
603 Py_INCREF ((PyObject *)self);
604
605 /* If steal is true, we also want to decref the incoming GObjects which
606 * already have a Python wrapper because the wrapper is already holding a
607 * strong reference.
608 */
609 if (steal) g_object_unref (obj);
610
611 } else {
612 /* create wrapper */
613 PyGObjectData *inst_data = pyg_object_peek_inst_data (obj);
614 PyTypeObject *tp;
615 if (inst_data)
616 tp = inst_data->type;
617 else {
618 if (g_class)
619 tp = pygobject_lookup_class (G_OBJECT_CLASS_TYPE (g_class));
620 else
621 tp = pygobject_lookup_class (G_OBJECT_TYPE (obj));
622 }
623 g_assert (tp != NULL);
624
625 /* need to bump type refcount if created with
626 pygobject_new_with_interfaces(). fixes bug #141042 */
627 if (tp->tp_flags & Py_TPFLAGS_HEAPTYPE) Py_INCREF (tp);
628 self = PyObject_GC_New (PyGObject, tp);
629 if (self == NULL) return NULL;
630
631 self->inst_dict = NULL;
632 self->weakreflist = NULL;
633 self->private_flags.flags = 0;
634 self->obj = obj;
635
636 /* If we are not stealing a ref or the object is floating,
637 * add a regular ref or sink the object. */
638 if (!steal || g_object_is_floating (obj)) g_object_ref_sink (obj);
639
640 pygobject_register_wrapper ((PyObject *)self);
641 PyObject_GC_Track ((PyObject *)self);
642 }
643
644 return (PyObject *)self;
645 }
646
647
648 PyObject *
649 pygobject_new (GObject *obj)
650 {
651 return pygobject_new_full (obj,
652 /*steal=*/FALSE, NULL);
653 }
654
655 static void
656 pygobject_unwatch_closure (gpointer data, GClosure *closure)
657 {
658 PyGObjectData *inst_data = data;
659
660 /* Despite no Python API is called the list inst_data->closures
661 * must be protected by GIL as it is used by GC in
662 * pygobject_traverse */
663 PyGILState_STATE state = PyGILState_Ensure ();
664 inst_data->closures = g_slist_remove (inst_data->closures, closure);
665 PyGILState_Release (state);
666 }
667
668 /**
669 * pygobject_watch_closure:
670 * @self: a GObject wrapper instance
671 * @closure: a GClosure to watch
672 *
673 * Adds a closure to the list of watched closures for the wrapper.
674 * The closure must be one returned by pyg_closure_new(). When the
675 * cycle GC traverses the wrapper instance, it will enumerate the
676 * references to Python objects stored in watched closures. If the
677 * cycle GC tells the wrapper to clear itself, the watched closures
678 * will be invalidated.
679 */
680 void
681 pygobject_watch_closure (PyObject *self, GClosure *closure)
682 {
683 PyGObject *gself;
684 PyGObjectData *data;
685
686 g_return_if_fail (self != NULL);
687 g_return_if_fail (PyObject_TypeCheck (self, &PyGObject_Type));
688 g_return_if_fail (closure != NULL);
689
690 gself = (PyGObject *)self;
691 data = pygobject_get_inst_data (gself);
692 g_return_if_fail (data != NULL);
693 g_return_if_fail (g_slist_find (data->closures, closure) == NULL);
694 data->closures = g_slist_prepend (data->closures, closure);
695 g_closure_add_invalidate_notifier (closure, data,
696 pygobject_unwatch_closure);
697 }
698
699 /* -------------- PyGObject behaviour ----------------- */
700
701 PYGI_DEFINE_TYPE ("gi._gi.GObject", PyGObject_Type, PyGObject);
702
703 static void
704 pygobject_dealloc (PyGObject *self)
705 {
706 /* Untrack must be done first. This is because followup calls such as
707 * ClearWeakRefs could call into Python and cause new allocations to
708 * happen, which could in turn could trigger the garbage collector,
709 * which would then get confused as it is tracking this half-deallocated
710 * object. */
711 PyObject_GC_UnTrack ((PyObject *)self);
712
713 if (self->weakreflist != NULL) PyObject_ClearWeakRefs ((PyObject *)self);
714
715 pygobject_clear (self);
716 /* the following causes problems with subclassed types */
717 /* Py_TYPE(self)->tp_free((PyObject *)self); */
718 PyObject_GC_Del (self);
719 }
720
721 static PyObject *
722 pygobject_richcompare (PyObject *self, PyObject *other, int op)
723 {
724 int isinst;
725
726 isinst = PyObject_IsInstance (self, (PyObject *)&PyGObject_Type);
727 if (isinst == -1) return NULL;
728 if (!isinst) {
729 Py_RETURN_NOTIMPLEMENTED;
730 }
731 isinst = PyObject_IsInstance (other, (PyObject *)&PyGObject_Type);
732 if (isinst == -1) return NULL;
733 if (!isinst) {
734 Py_RETURN_NOTIMPLEMENTED;
735 }
736
737 return pyg_ptr_richcompare (((PyGObject *)self)->obj,
738 ((PyGObject *)other)->obj, op);
739 }
740
741 static Py_hash_t
742 pygobject_hash (PyGObject *self)
743 {
744 return (Py_hash_t)(gintptr)(self->obj);
745 }
746
747 static PyObject *
748 pygobject_repr (PyGObject *self)
749 {
750 PyObject *module, *repr;
751 gchar *module_str, *namespace;
752
753 module = PyObject_GetAttrString ((PyObject *)self, "__module__");
754 if (module == NULL) return NULL;
755
756 if (!PyUnicode_Check (module)) {
757 Py_DECREF (module);
758 return NULL;
759 }
760
761 module_str = PyUnicode_AsUTF8 (module);
762 namespace = g_strrstr (module_str, ".");
763 if (namespace == NULL) {
764 namespace = module_str;
765 } else {
766 namespace += 1;
767 }
768
769 repr = PyUnicode_FromFormat (
770 "<%s.%s object at %p (%s at %p)>", namespace, Py_TYPE (self)->tp_name,
771 self, self->obj ? G_OBJECT_TYPE_NAME (self->obj) : "uninitialized",
772 self->obj);
773 Py_DECREF (module);
774 return repr;
775 }
776
777 static int
778 pygobject_traverse (PyGObject *self, visitproc visit, void *arg)
779 {
780 int ret = 0;
781 PyGObjectData *data = pyg_object_peek_inst_data (self->obj);
782
783 if (self->inst_dict) {
784 ret = visit (self->inst_dict, arg);
785 if (ret != 0) return ret;
786 }
787
788 /* Only let the GC track the closures when tp_clear() would free them.
789 * https://bugzilla.gnome.org/show_bug.cgi?id=731501
790 */
791 if (data && self->obj->ref_count == 1) {
792 if (data->inst_dict) ret = visit (data->inst_dict, arg);
793 if (ret != 0) return ret;
794
795 for (GSList *tmp = data->closures; tmp != NULL; tmp = tmp->next) {
796 PyGClosure *closure = tmp->data;
797
798 if (closure->callback) ret = visit (closure->callback, arg);
799 if (ret != 0) return ret;
800
801 if (closure->extra_args) ret = visit (closure->extra_args, arg);
802 if (ret != 0) return ret;
803
804 if (closure->swap_data) ret = visit (closure->swap_data, arg);
805 if (ret != 0) return ret;
806 }
807 }
808 return ret;
809 }
810
811 static int
812 pygobject_clear (PyGObject *self)
813 {
814 if (self->obj) {
815 PyGObjectData *inst_data = pygobject_get_inst_data (self);
816
817 /* The __class__ of the object may have changed. If so, update it. */
818 if (inst_data != NULL && inst_data->type != Py_TYPE (self)) {
819 Py_DECREF ((PyObject *)inst_data->type);
820 inst_data->type = Py_TYPE (self);
821 Py_INCREF ((PyObject *)inst_data->type);
822 }
823
824 g_object_set_qdata_full (self->obj, pygobject_wrapper_key, NULL, NULL);
825 Py_BEGIN_ALLOW_THREADS;
826 g_clear_pointer (&self->obj, g_object_unref);
827 Py_END_ALLOW_THREADS;
828 }
829 Py_CLEAR (self->inst_dict);
830 return 0;
831 }
832
833 #ifndef PYPY_VERSION
834 static void
835 pygobject_finalize (PyGObject *self)
836 {
837 PyGObjectData *data = pyg_object_peek_inst_data (self->obj);
838
839 /* We hold the last reference to the GObject.
840 * Call `do_dispose` before the object is cleared. */
841 if (data && data->call_do_dispose && self->obj->ref_count == 1) {
842 PyObject *error_type, *error_value, *error_traceback;
843 PyErr_Fetch (&error_type, &error_value, &error_traceback);
844
845 g_object_run_dispose (self->obj);
846
847 PyErr_Restore (error_type, error_value, error_traceback);
848 }
849 }
850 #endif
851
852 static void
853 pygobject_free (PyObject *op)
854 {
855 PyObject_GC_Del (op);
856 }
857
858 static gboolean
859 pygobject_prepare_construct_properties (
860 GObjectClass *class, PyObject *kwargs, guint *n_properties,
861 const char **names[], const GValue **values,
862 const PyGIArgumentFromPyCleanupData **cleanup_data)
863 {
864 *n_properties = 0;
865 *names = NULL;
866 *values = NULL;
867
868 if (kwargs) {
869 Py_ssize_t pos = 0;
870 PyObject *key;
871 PyObject *value;
872 Py_ssize_t len;
873
874 len = PyDict_Size (kwargs);
875 *names = g_new (const char *, len);
876 *values = g_new0 (GValue, len);
877 *cleanup_data = g_new0 (PyGIArgumentFromPyCleanupData, len);
878 while (PyDict_Next (kwargs, &pos, &key, &value)) {
879 GParamSpec *pspec;
880 GValue *gvalue = &(*values)[*n_properties];
881 PyGIArgumentFromPyCleanupData *arg_cleanup_data =
882 &(*cleanup_data)[*n_properties];
883
884 const gchar *key_str = PyUnicode_AsUTF8 (key);
885
886 pspec = g_object_class_find_property (class, key_str);
887 if (!pspec) {
888 PyErr_Format (PyExc_TypeError,
889 "gobject `%s' doesn't support property `%s'",
890 G_OBJECT_CLASS_NAME (class), key_str);
891 return FALSE;
892 }
893 g_value_init (gvalue, G_PARAM_SPEC_VALUE_TYPE (pspec));
894 if (pygi_set_gvalue_for_pspec (gvalue, pspec, value,
895 arg_cleanup_data)
896 < 0) {
897 if (!PyErr_Occurred ())
898 PyErr_Format (
899 PyExc_TypeError,
900 "could not convert value for property `%s' from %s to "
901 "%s",
902 key_str, Py_TYPE (value)->tp_name,
903 g_type_name (G_PARAM_SPEC_VALUE_TYPE (pspec)));
904 return FALSE;
905 }
906 (*names)[*n_properties] = g_strdup (key_str);
907 ++(*n_properties);
908 }
909 }
910 return TRUE;
911 }
912
913 /* ---------------- PyGObject methods ----------------- */
914
915 static int
916 pygobject_init (PyGObject *self, PyObject *args, PyObject *kwargs)
917 {
918 GType object_type;
919 guint n_properties = 0, i;
920 const GValue *values = NULL;
921 const PyGIArgumentFromPyCleanupData *cleanup_data = NULL;
922 const char **names = NULL;
923 GObjectClass *class;
924 GObject *obj;
925
926 /* Only do GObject creation and property setting if the GObject hasn't
927 * already been created. The case where self->obj already exists can occur
928 * when C constructors are called directly (Gtk.Button.new_with_label)
929 * and we are simply wrapping the result with a PyGObject.
930 * In these cases we want to ignore any keyword arguments passed along
931 * to __init__ and simply return.
932 *
933 * See: https://bugzilla.gnome.org/show_bug.cgi?id=705810
934 */
935 if (self->obj != NULL) return 0;
936
937 if (!PyArg_ParseTuple (args, ":GObject.__init__", NULL)) return -1;
938
939 object_type = pyg_type_from_object ((PyObject *)self);
940 if (!object_type) return -1;
941
942 if (G_TYPE_IS_ABSTRACT (object_type)) {
943 PyErr_Format (PyExc_TypeError,
944 "cannot create instance of abstract "
945 "(non-instantiable) type `%s'",
946 g_type_name (object_type));
947 return -1;
948 }
949
950 if ((class = g_type_class_ref (object_type)) == NULL) {
951 PyErr_SetString (PyExc_TypeError,
952 "could not get a reference to type class");
953 return -1;
954 }
955
956 if (!pygobject_prepare_construct_properties (
957 class, kwargs, &n_properties, &names, &values, &cleanup_data))
958 goto cleanup;
959
960 pygobject_init_wrapper_set ((PyObject *)self);
961 obj = g_object_new_with_properties (object_type, n_properties, names,
962 values);
963 pygobject_init_wrapper_set (NULL);
964
965 if (G_IS_INITIALLY_UNOWNED (obj)) {
966 g_object_ref_sink (obj);
967 }
968
969 self->obj = obj;
970 pygobject_register_wrapper ((PyObject *)self);
971
972 cleanup:
973 for (i = 0; i < n_properties; i++) {
974 pygi_argument_from_py_cleanup (&cleanup_data[i]);
975 g_free (names[i]);
976 g_value_unset (&values[i]);
977 }
978 g_free (names);
979 g_free (values);
980 g_free (cleanup_data);
981
982 g_type_class_unref (class);
983
984 if (PyErr_Occurred ()) return -1;
985
986 return (self->obj) ? 0 : -1;
987 }
988
989 #define CHECK_GOBJECT(self) \
990 if (!G_IS_OBJECT (self->obj)) { \
991 PyErr_Format (PyExc_TypeError, \
992 "object at %p of type %s is not initialized", self, \
993 Py_TYPE (self)->tp_name); \
994 return NULL; \
995 }
996
997 static PyObject *
998 pygobject_get_property (PyGObject *self, PyObject *args)
999 {
1000 gchar *param_name;
1001
1002 if (!PyArg_ParseTuple (args, "s:GObject.get_property", &param_name)) {
1003 return NULL;
1004 }
1005
1006 CHECK_GOBJECT (self);
1007
1008 return pygi_get_property_value_by_name (self, param_name);
1009 }
1010
1011 static PyObject *
1012 pygobject_get_properties (PyGObject *self, PyObject *args)
1013 {
1014 Py_ssize_t len, i;
1015 PyObject *tuple;
1016
1017 if ((len = PyTuple_Size (args)) < 1) {
1018 PyErr_SetString (PyExc_TypeError, "requires at least one argument");
1019 return NULL;
1020 }
1021
1022 tuple = PyTuple_New (len);
1023 for (i = 0; i < len; i++) {
1024 PyObject *py_property = PyTuple_GetItem (args, i);
1025 gchar *property_name;
1026 PyObject *item;
1027
1028 if (!PyUnicode_Check (py_property)) {
1029 PyErr_SetString (PyExc_TypeError,
1030 "Expected string argument for property.");
1031 goto fail;
1032 }
1033
1034 property_name = PyUnicode_AsUTF8 (py_property);
1035 item = pygi_get_property_value_by_name (self, property_name);
1036 PyTuple_SetItem (tuple, i, item);
1037 }
1038
1039 return tuple;
1040
1041 fail:
1042 Py_DECREF (tuple);
1043 return NULL;
1044 }
1045
1046 static PyObject *
1047 pygobject_set_property (PyGObject *self, PyObject *args)
1048 {
1049 gchar *param_name;
1050 GParamSpec *pspec;
1051 PyObject *pvalue;
1052
1053 if (!PyArg_ParseTuple (args, "sO:GObject.set_property", &param_name,
1054 &pvalue))
1055 return NULL;
1056
1057 CHECK_GOBJECT (self);
1058
1059 pspec = g_object_class_find_property (G_OBJECT_GET_CLASS (self->obj),
1060 param_name);
1061 if (!pspec) {
1062 PyErr_Format (PyExc_TypeError,
1063 "object of type `%s' does not have property `%s'",
1064 g_type_name (G_OBJECT_TYPE (self->obj)), param_name);
1065 return NULL;
1066 }
1067
1068 pygi_set_property_value (self, pspec, pvalue);
1069 if (PyErr_Occurred ()) return NULL;
1070
1071 Py_RETURN_NONE;
1072 }
1073
1074 static PyObject *
1075 pygobject_set_properties (PyGObject *self, PyObject *args, PyObject *kwargs)
1076 {
1077 GObjectClass *class;
1078 Py_ssize_t pos;
1079 PyObject *value;
1080 PyObject *key;
1081 PyObject *result = NULL;
1082
1083 CHECK_GOBJECT (self);
1084
1085 class = G_OBJECT_GET_CLASS (self->obj);
1086
1087 g_object_freeze_notify (G_OBJECT (self->obj));
1088 pos = 0;
1089
1090 while (kwargs && PyDict_Next (kwargs, &pos, &key, &value)) {
1091 gchar *key_str = PyUnicode_AsUTF8 (key);
1092 GParamSpec *pspec;
1093 int ret = -1;
1094
1095 pspec = g_object_class_find_property (class, key_str);
1096 if (!pspec) {
1097 gchar buf[512];
1098
1099 g_snprintf (buf, sizeof (buf),
1100 "object `%s' doesn't support property `%s'",
1101 g_type_name (G_OBJECT_TYPE (self->obj)), key_str);
1102 PyErr_SetString (PyExc_TypeError, buf);
1103 goto exit;
1104 }
1105
1106 ret = pygi_set_property_value (self, pspec, value);
1107 if (ret != 0) {
1108 /* Non-zero return code means that an error occurred */
1109 if (PyErr_Occurred ()) goto exit;
1110 }
1111 }
1112
1113 result = Py_None;
1114
1115 exit:
1116 g_object_thaw_notify (G_OBJECT (self->obj));
1117 return Py_XNewRef (result);
1118 }
1119
1120 /* custom closure for gobject bindings */
1121 static void
1122 pygbinding_closure_invalidate (gpointer data, GClosure *closure)
1123 {
1124 PyGClosure *pc = (PyGClosure *)closure;
1125 PyGILState_STATE state;
1126
1127 state = PyGILState_Ensure ();
1128 Py_XDECREF (pc->callback);
1129 Py_XDECREF (pc->extra_args);
1130 PyGILState_Release (state);
1131
1132 pc->callback = NULL;
1133 pc->extra_args = NULL;
1134 }
1135
1136 static void
1137 pygbinding_marshal (GClosure *closure, GValue *return_value,
1138 guint n_param_values, const GValue *param_values,
1139 gpointer invocation_hint, gpointer marshal_data)
1140 {
1141 PyGILState_STATE state;
1142 PyGClosure *pc = (PyGClosure *)closure;
1143 PyObject *params, *ret;
1144 GValue *out_value;
1145
1146 state = PyGILState_Ensure ();
1147
1148 /* construct Python tuple for the parameter values */
1149 params = PyTuple_New (2);
1150 PyTuple_SetItem (params, 0,
1151 pyg_value_to_pyobject (&param_values[0], FALSE));
1152 PyTuple_SetItem (params, 1,
1153 pyg_value_to_pyobject (&param_values[1], FALSE));
1154
1155 /* params passed to function may have extra arguments */
1156 if (pc->extra_args) {
1157 PyObject *tuple = params;
1158 params = PySequence_Concat (tuple, pc->extra_args);
1159 Py_DECREF (tuple);
1160 }
1161 ret = PyObject_CallObject (pc->callback, params);
1162 if (!ret) {
1163 PyErr_Print ();
1164 goto out;
1165 } else if (Py_IsNone (ret)) {
1166 g_value_set_boolean (return_value, FALSE);
1167 goto out;
1168 }
1169
1170 out_value = g_value_get_boxed (&param_values[2]);
1171 if (pyg_value_from_pyobject (out_value, ret) != 0) {
1172 PyErr_SetString (PyExc_ValueError, "can't convert value");
1173 PyErr_Print ();
1174 g_value_set_boolean (return_value, FALSE);
1175 } else {
1176 g_value_set_boolean (return_value, TRUE);
1177 }
1178
1179 Py_DECREF (ret);
1180
1181 out:
1182 Py_DECREF (params);
1183 PyGILState_Release (state);
1184 }
1185
1186 static GClosure *
1187 pygbinding_closure_new (PyObject *callback, PyObject *extra_args)
1188 {
1189 GClosure *closure;
1190
1191 g_return_val_if_fail (callback != NULL, NULL);
1192 closure = g_closure_new_simple (sizeof (PyGClosure), NULL);
1193 g_closure_add_invalidate_notifier (closure, NULL,
1194 pygbinding_closure_invalidate);
1195 g_closure_set_marshal (closure, pygbinding_marshal);
1196 Py_INCREF (callback);
1197 ((PyGClosure *)closure)->callback = callback;
1198 if (extra_args && !Py_IsNone (extra_args)) {
1199 Py_INCREF (extra_args);
1200 if (!PyTuple_Check (extra_args)) {
1201 PyObject *tmp = PyTuple_New (1);
1202 PyTuple_SetItem (tmp, 0, extra_args);
1203 extra_args = tmp;
1204 }
1205 ((PyGClosure *)closure)->extra_args = extra_args;
1206 }
1207 return closure;
1208 }
1209
1210 static PyObject *
1211 pygobject_bind_property (PyGObject *self, PyObject *args, PyObject *kwargs)
1212 {
1213 gchar *source_name, *target_name;
1214 gchar *source_canon, *target_canon;
1215 PyObject *target, *source_repr, *target_repr;
1216 PyObject *transform_to, *transform_from, *user_data = NULL;
1217 GBinding *binding;
1218 GBindingFlags flags = G_BINDING_DEFAULT;
1219 GClosure *to_closure = NULL, *from_closure = NULL;
1220
1221 transform_from = NULL;
1222 transform_to = NULL;
1223
1224 static char *kwlist[] = { "source_property", "target",
1225 "target_property", "flags",
1226 "transform_to", "transform_from",
1227 "user_data", NULL };
1228
1229 if (!PyArg_ParseTupleAndKeywords (
1230 args, kwargs, "sOs|iOOO:GObject.bind_property", kwlist,
1231 &source_name, &target, &target_name, &flags, &transform_to,
1232 &transform_from, &user_data))
1233 return NULL;
1234
1235 CHECK_GOBJECT (self);
1236 if (!PyObject_TypeCheck (target, &PyGObject_Type)) {
1237 PyErr_SetString (PyExc_TypeError, "Second argument must be a GObject");
1238 return NULL;
1239 }
1240
1241 if (transform_to && !Py_IsNone (transform_to)) {
1242 if (!PyCallable_Check (transform_to)) {
1243 PyErr_SetString (PyExc_TypeError,
1244 "transform_to must be callable or None");
1245 return NULL;
1246 }
1247 to_closure = pygbinding_closure_new (transform_to, user_data);
1248 }
1249
1250 if (transform_from && !Py_IsNone (transform_from)) {
1251 if (!PyCallable_Check (transform_from)) {
1252 PyErr_SetString (PyExc_TypeError,
1253 "transform_from must be callable or None");
1254 return NULL;
1255 }
1256 from_closure = pygbinding_closure_new (transform_from, user_data);
1257 }
1258
1259 /* Canonicalize underscores to hyphens. Note the results must be freed. */
1260 source_canon = g_strdelimit (g_strdup (source_name), "_", '-');
1261 target_canon = g_strdelimit (g_strdup (target_name), "_", '-');
1262
1263 binding = g_object_bind_property_with_closures (
1264 G_OBJECT (self->obj), source_canon, pygobject_get (target),
1265 target_canon, flags, to_closure, from_closure);
1266 g_free (source_canon);
1267 g_free (target_canon);
1268 source_canon = target_canon = NULL;
1269
1270 if (binding == NULL) {
1271 source_repr = PyObject_Repr ((PyObject *)self);
1272 target_repr = PyObject_Repr (target);
1273 PyErr_Format (PyExc_TypeError,
1274 "Cannot create binding from %s.%s to %s.%s",
1275 PyUnicode_AsUTF8 (source_repr), source_name,
1276 PyUnicode_AsUTF8 (target_repr), target_name);
1277 Py_DECREF (source_repr);
1278 Py_DECREF (target_repr);
1279 return NULL;
1280 }
1281
1282 return pygobject_new (G_OBJECT (binding));
1283 }
1284
1285 static PyObject *
1286 connect_helper (PyGObject *self, gchar *name, PyObject *callback,
1287 PyObject *extra_args, PyObject *object, gboolean after)
1288 {
1289 guint sigid;
1290 GQuark detail = 0;
1291 GClosure *closure = NULL;
1292 gulong handlerid;
1293 GSignalQuery query_info;
1294
1295 if (!g_signal_parse_name (name, G_OBJECT_TYPE (self->obj), &sigid, &detail,
1296 TRUE)) {
1297 PyObject *repr = PyObject_Repr ((PyObject *)self);
1298 PyErr_Format (PyExc_TypeError, "%s: unknown signal name: %s",
1299 PyUnicode_AsUTF8 (repr), name);
1300 Py_DECREF (repr);
1301 return NULL;
1302 }
1303
1304 if (object && !PyObject_TypeCheck (object, &PyGObject_Type)) {
1305 if (PyErr_WarnEx (PyGIDeprecationWarning,
1306 "Using non GObject arguments for connect_object() "
1307 "is deprecated, use: "
1308 "connect_data(signal, callback, data, "
1309 "connect_flags=GObject.ConnectFlags.SWAPPED)",
1310 1)) {
1311 return NULL;
1312 }
1313 }
1314
1315 g_signal_query (sigid, &query_info);
1316 if (!pyg_gtype_is_custom (query_info.itype)) {
1317 /* The signal is implemented by a non-Python class, probably
1318 * something in the gi repository. */
1319 closure = pygi_signal_closure_new (self, query_info.itype,
1320 query_info.signal_name, callback,
1321 extra_args, object);
1322 }
1323
1324 if (!closure) {
1325 /* The signal is either implemented at the Python level, or it comes
1326 * from a foreign class that we don't have introspection data for. */
1327 closure = pyg_closure_new (callback, extra_args, object);
1328 }
1329
1330 pygobject_watch_closure ((PyObject *)self, closure);
1331 handlerid = g_signal_connect_closure_by_id (self->obj, sigid, detail,
1332 closure, after);
1333 return pygi_gulong_to_py (handlerid);
1334 }
1335
1336 static PyObject *
1337 pygobject_connect (PyGObject *self, PyObject *args)
1338 {
1339 PyObject *first, *callback, *extra_args, *ret;
1340 gchar *name;
1341 Py_ssize_t len;
1342
1343 len = PyTuple_Size (args);
1344 if (len < 2) {
1345 PyErr_SetString (PyExc_TypeError,
1346 "GObject.connect requires at least 2 arguments");
1347 return NULL;
1348 }
1349 first = PySequence_GetSlice (args, 0, 2);
1350 if (!PyArg_ParseTuple (first, "sO:GObject.connect", &name, &callback)) {
1351 Py_DECREF (first);
1352 return NULL;
1353 }
1354 Py_DECREF (first);
1355 if (!PyCallable_Check (callback)) {
1356 PyErr_SetString (PyExc_TypeError, "second argument must be callable");
1357 return NULL;
1358 }
1359
1360 CHECK_GOBJECT (self);
1361
1362 extra_args = PySequence_GetSlice (args, 2, len);
1363 if (extra_args == NULL) return NULL;
1364
1365 ret = connect_helper (self, name, callback, extra_args, NULL, FALSE);
1366 Py_DECREF (extra_args);
1367 return ret;
1368 }
1369
1370 static PyObject *
1371 pygobject_connect_after (PyGObject *self, PyObject *args)
1372 {
1373 PyObject *first, *callback, *extra_args, *ret;
1374 gchar *name;
1375 Py_ssize_t len;
1376
1377 len = PyTuple_Size (args);
1378 if (len < 2) {
1379 PyErr_SetString (
1380 PyExc_TypeError,
1381 "GObject.connect_after requires at least 2 arguments");
1382 return NULL;
1383 }
1384 first = PySequence_GetSlice (args, 0, 2);
1385 if (!PyArg_ParseTuple (first, "sO:GObject.connect_after", &name,
1386 &callback)) {
1387 Py_DECREF (first);
1388 return NULL;
1389 }
1390 Py_DECREF (first);
1391 if (!PyCallable_Check (callback)) {
1392 PyErr_SetString (PyExc_TypeError, "second argument must be callable");
1393 return NULL;
1394 }
1395
1396 CHECK_GOBJECT (self);
1397
1398 extra_args = PySequence_GetSlice (args, 2, len);
1399 if (extra_args == NULL) return NULL;
1400
1401 ret = connect_helper (self, name, callback, extra_args, NULL, TRUE);
1402 Py_DECREF (extra_args);
1403 return ret;
1404 }
1405
1406 static PyObject *
1407 pygobject_connect_object (PyGObject *self, PyObject *args)
1408 {
1409 PyObject *first, *callback, *extra_args, *object, *ret;
1410 gchar *name;
1411 Py_ssize_t len;
1412
1413 len = PyTuple_Size (args);
1414 if (len < 3) {
1415 PyErr_SetString (
1416 PyExc_TypeError,
1417 "GObject.connect_object requires at least 3 arguments");
1418 return NULL;
1419 }
1420 first = PySequence_GetSlice (args, 0, 3);
1421 if (!PyArg_ParseTuple (first, "sOO:GObject.connect_object", &name,
1422 &callback, &object)) {
1423 Py_DECREF (first);
1424 return NULL;
1425 }
1426 Py_DECREF (first);
1427 if (!PyCallable_Check (callback)) {
1428 PyErr_SetString (PyExc_TypeError, "second argument must be callable");
1429 return NULL;
1430 }
1431
1432 CHECK_GOBJECT (self);
1433
1434 extra_args = PySequence_GetSlice (args, 3, len);
1435 if (extra_args == NULL) return NULL;
1436
1437 ret = connect_helper (self, name, callback, extra_args, object, FALSE);
1438 Py_DECREF (extra_args);
1439 return ret;
1440 }
1441
1442 static PyObject *
1443 pygobject_connect_object_after (PyGObject *self, PyObject *args)
1444 {
1445 PyObject *first, *callback, *extra_args, *object, *ret;
1446 gchar *name;
1447 Py_ssize_t len;
1448
1449 len = PyTuple_Size (args);
1450 if (len < 3) {
1451 PyErr_SetString (
1452 PyExc_TypeError,
1453 "GObject.connect_object_after requires at least 3 arguments");
1454 return NULL;
1455 }
1456 first = PySequence_GetSlice (args, 0, 3);
1457 if (!PyArg_ParseTuple (first, "sOO:GObject.connect_object_after", &name,
1458 &callback, &object)) {
1459 Py_DECREF (first);
1460 return NULL;
1461 }
1462 Py_DECREF (first);
1463 if (!PyCallable_Check (callback)) {
1464 PyErr_SetString (PyExc_TypeError, "second argument must be callable");
1465 return NULL;
1466 }
1467
1468 CHECK_GOBJECT (self);
1469
1470 extra_args = PySequence_GetSlice (args, 3, len);
1471 if (extra_args == NULL) return NULL;
1472
1473 ret = connect_helper (self, name, callback, extra_args, object, TRUE);
1474 Py_DECREF (extra_args);
1475 return ret;
1476 }
1477
1478 static PyObject *
1479 pygobject_emit (PyGObject *self, PyObject *args)
1480 {
1481 guint signal_id, i, j;
1482 Py_ssize_t len;
1483 GQuark detail;
1484 PyObject *first, *py_ret, *repr = NULL;
1485 gchar *name;
1486 GSignalQuery query;
1487 GValue *params, ret = {
1488 0,
1489 };
1490
1491 len = PyTuple_Size (args);
1492 if (len < 1) {
1493 PyErr_SetString (PyExc_TypeError,
1494 "GObject.emit needs at least one arg");
1495 return NULL;
1496 }
1497 first = PySequence_GetSlice (args, 0, 1);
1498 if (!PyArg_ParseTuple (first, "s:GObject.emit", &name)) {
1499 Py_DECREF (first);
1500 return NULL;
1501 }
1502 Py_DECREF (first);
1503
1504 CHECK_GOBJECT (self);
1505
1506 if (!g_signal_parse_name (name, G_OBJECT_TYPE (self->obj), &signal_id,
1507 &detail, TRUE)) {
1508 repr = PyObject_Repr ((PyObject *)self);
1509 PyErr_Format (PyExc_TypeError, "%s: unknown signal name: %s",
1510 PyUnicode_AsUTF8 (repr), name);
1511 Py_DECREF (repr);
1512 return NULL;
1513 }
1514 g_signal_query (signal_id, &query);
1515 if ((gsize)len != query.n_params + 1) {
1516 gchar buf[128];
1517
1518 g_snprintf (buf, sizeof (buf),
1519 "%d parameters needed for signal %s; %ld given",
1520 query.n_params, name, (long int)(len - 1));
1521 PyErr_SetString (PyExc_TypeError, buf);
1522 return NULL;
1523 }
1524
1525 params = g_new0 (GValue, query.n_params + 1);
1526 g_value_init (&params[0], G_OBJECT_TYPE (self->obj));
1527 g_value_set_object (&params[0], G_OBJECT (self->obj));
1528
1529 for (i = 0; i < query.n_params; i++)
1530 g_value_init (&params[i + 1],
1531 query.param_types[i] & ~G_SIGNAL_TYPE_STATIC_SCOPE);
1532 for (i = 0; i < query.n_params; i++) {
1533 PyObject *item = PyTuple_GetItem (args, i + 1);
1534
1535 if (pyg_value_from_pyobject (&params[i + 1], item) < 0) {
1536 gchar buf[128];
1537 g_snprintf (
1538 buf, sizeof (buf),
1539 "could not convert type %s to %s required for parameter %d",
1540 Py_TYPE (item)->tp_name, G_VALUE_TYPE_NAME (&params[i + 1]),
1541 i);
1542 PyErr_SetString (PyExc_TypeError, buf);
1543
1544 for (j = 0; j <= i; j++) g_value_unset (&params[j]);
1545
1546 g_free (params);
1547 return NULL;
1548 }
1549 }
1550
1551 if (query.return_type != G_TYPE_NONE)
1552 g_value_init (&ret, query.return_type & ~G_SIGNAL_TYPE_STATIC_SCOPE);
1553
1554 Py_BEGIN_ALLOW_THREADS;
1555 g_signal_emitv (params, signal_id, detail, &ret);
1556 Py_END_ALLOW_THREADS;
1557
1558 for (i = 0; i < query.n_params + 1; i++) g_value_unset (&params[i]);
1559
1560 g_free (params);
1561 if ((query.return_type & ~G_SIGNAL_TYPE_STATIC_SCOPE) != G_TYPE_NONE) {
1562 gboolean was_floating = FALSE;
1563
1564 if (G_VALUE_HOLDS_OBJECT (&ret)) {
1565 GObject *obj = g_value_get_object (&ret);
1566 if (obj != NULL && G_IS_OBJECT (obj)) {
1567 was_floating = g_object_is_floating (obj);
1568 }
1569 }
1570 py_ret = pyg_value_to_pyobject (&ret, TRUE);
1571 if (!was_floating) g_value_unset (&ret);
1572 } else {
1573 py_ret = Py_NewRef (Py_None);
1574 }
1575
1576 return py_ret;
1577 }
1578
1579 static PyObject *
1580 pygobject_chain_from_overridden (PyGObject *self, PyObject *args)
1581 {
1582 GSignalInvocationHint *ihint;
1583 guint signal_id, i;
1584 Py_ssize_t len;
1585 PyObject *py_ret;
1586 const gchar *name;
1587 GSignalQuery query;
1588 GValue *params, ret = {
1589 0,
1590 };
1591
1592 CHECK_GOBJECT (self);
1593
1594 ihint = g_signal_get_invocation_hint (self->obj);
1595 if (!ihint) {
1596 PyErr_SetString (PyExc_TypeError,
1597 "could not find signal invocation "
1598 "information for this object.");
1599 return NULL;
1600 }
1601
1602 signal_id = ihint->signal_id;
1603 name = g_signal_name (signal_id);
1604
1605 len = PyTuple_Size (args);
1606 if (signal_id == 0) {
1607 PyErr_SetString (PyExc_TypeError, "unknown signal name");
1608 return NULL;
1609 }
1610 g_signal_query (signal_id, &query);
1611 if (len < 0 || (gsize)len != query.n_params) {
1612 gchar buf[128];
1613
1614 g_snprintf (buf, sizeof (buf),
1615 "%d parameters needed for signal %s; %ld given",
1616 query.n_params, name, (long int)len);
1617 PyErr_SetString (PyExc_TypeError, buf);
1618 return NULL;
1619 }
1620 params = g_new0 (GValue, query.n_params + 1);
1621 g_value_init (&params[0], G_OBJECT_TYPE (self->obj));
1622 g_value_set_object (&params[0], G_OBJECT (self->obj));
1623
1624 for (i = 0; i < query.n_params; i++)
1625 g_value_init (&params[i + 1],
1626 query.param_types[i] & ~G_SIGNAL_TYPE_STATIC_SCOPE);
1627 for (i = 0; i < query.n_params; i++) {
1628 PyObject *item = PyTuple_GetItem (args, i);
1629
1630 if (pyg_boxed_check (
1631 item, query.param_types[i] & ~G_SIGNAL_TYPE_STATIC_SCOPE)) {
1632 g_value_set_static_boxed (&params[i + 1],
1633 pyg_boxed_get (item, void));
1634 } else if (pyg_value_from_pyobject (&params[i + 1], item) < 0) {
1635 gchar buf[128];
1636
1637 g_snprintf (
1638 buf, sizeof (buf),
1639 "could not convert type %s to %s required for parameter %d",
1640 Py_TYPE (item)->tp_name,
1641 g_type_name (G_VALUE_TYPE (&params[i + 1])), i);
1642 PyErr_SetString (PyExc_TypeError, buf);
1643 for (i = 0; i < query.n_params + 1; i++)
1644 g_value_unset (&params[i]);
1645 g_free (params);
1646 return NULL;
1647 }
1648 }
1649 if (query.return_type != G_TYPE_NONE)
1650 g_value_init (&ret, query.return_type & ~G_SIGNAL_TYPE_STATIC_SCOPE);
1651 g_signal_chain_from_overridden (params, &ret);
1652 for (i = 0; i < query.n_params + 1; i++) g_value_unset (&params[i]);
1653 g_free (params);
1654 if (query.return_type != G_TYPE_NONE) {
1655 py_ret = pyg_value_to_pyobject (&ret, TRUE);
1656 g_value_unset (&ret);
1657 } else {
1658 py_ret = Py_NewRef (Py_None);
1659 }
1660 return py_ret;
1661 }
1662
1663
1664 static PyObject *
1665 pygobject_weak_ref (PyGObject *self, PyObject *args)
1666 {
1667 Py_ssize_t len;
1668 PyObject *callback = NULL, *user_data = NULL;
1669 PyObject *retval;
1670
1671 CHECK_GOBJECT (self);
1672
1673 if ((len = PySequence_Length (args)) >= 1) {
1674 callback = PySequence_ITEM (args, 0);
1675 user_data = PySequence_GetSlice (args, 1, len);
1676 }
1677 retval = pygobject_weak_ref_new (self->obj, callback, user_data);
1678 Py_XDECREF (callback);
1679 Py_XDECREF (user_data);
1680 return retval;
1681 }
1682
1683 static PyObject *
1684 pygobject_do_constructed (PyObject *self)
1685 {
1686 Py_RETURN_NONE;
1687 }
1688
1689 static PyObject *
1690 pygobject_do_dispose (PyObject *self)
1691 {
1692 Py_RETURN_NONE;
1693 }
1694
1695 static PyObject *
1696 pygobject_copy (PyGObject *self)
1697 {
1698 PyErr_SetString (PyExc_TypeError,
1699 "GObject descendants' instances are non-copyable");
1700 return NULL;
1701 }
1702
1703 static PyObject *
1704 pygobject_deepcopy (PyGObject *self, PyObject *args)
1705 {
1706 PyErr_SetString (PyExc_TypeError,
1707 "GObject descendants' instances are non-copyable");
1708 return NULL;
1709 }
1710
1711
1712 static PyObject *
1713 pygobject_disconnect_by_func (PyGObject *self, PyObject *args)
1714 {
1715 PyObject *pyfunc = NULL, *repr = NULL;
1716 GClosure *closure = NULL;
1717 guint retval;
1718
1719 CHECK_GOBJECT (self);
1720
1721 if (!PyArg_ParseTuple (args, "O:GObject.disconnect_by_func", &pyfunc))
1722 return NULL;
1723
1724 if (!PyCallable_Check (pyfunc)) {
1725 PyErr_SetString (PyExc_TypeError, "first argument must be callable");
1726 return NULL;
1727 }
1728
1729 closure = gclosure_from_pyfunc (self, pyfunc);
1730 if (!closure) {
1731 repr = PyObject_Repr ((PyObject *)pyfunc);
1732 PyErr_Format (PyExc_TypeError, "nothing connected to %s",
1733 PyUnicode_AsUTF8 (repr));
1734 Py_DECREF (repr);
1735 return NULL;
1736 }
1737
1738 retval = g_signal_handlers_disconnect_matched (
1739 self->obj, G_SIGNAL_MATCH_CLOSURE, 0, 0, closure, NULL, NULL);
1740 return pygi_guint_to_py (retval);
1741 }
1742
1743 static PyObject *
1744 pygobject_handler_block_by_func (PyGObject *self, PyObject *args)
1745 {
1746 PyObject *pyfunc = NULL, *repr = NULL;
1747 GClosure *closure = NULL;
1748 guint retval;
1749
1750 CHECK_GOBJECT (self);
1751
1752 if (!PyArg_ParseTuple (args, "O:GObject.handler_block_by_func", &pyfunc))
1753 return NULL;
1754
1755 if (!PyCallable_Check (pyfunc)) {
1756 PyErr_SetString (PyExc_TypeError, "first argument must be callable");
1757 return NULL;
1758 }
1759
1760 closure = gclosure_from_pyfunc (self, pyfunc);
1761 if (!closure) {
1762 repr = PyObject_Repr ((PyObject *)pyfunc);
1763 PyErr_Format (PyExc_TypeError, "nothing connected to %s",
1764 PyUnicode_AsUTF8 (repr));
1765 Py_DECREF (repr);
1766 return NULL;
1767 }
1768
1769 retval = g_signal_handlers_block_matched (
1770 self->obj, G_SIGNAL_MATCH_CLOSURE, 0, 0, closure, NULL, NULL);
1771 return pygi_guint_to_py (retval);
1772 }
1773
1774 static PyObject *
1775 pygobject_handler_unblock_by_func (PyGObject *self, PyObject *args)
1776 {
1777 PyObject *pyfunc = NULL, *repr = NULL;
1778 GClosure *closure = NULL;
1779 guint retval;
1780
1781 CHECK_GOBJECT (self);
1782
1783 if (!PyArg_ParseTuple (args, "O:GObject.handler_unblock_by_func", &pyfunc))
1784 return NULL;
1785
1786 if (!PyCallable_Check (pyfunc)) {
1787 PyErr_SetString (PyExc_TypeError, "first argument must be callable");
1788 return NULL;
1789 }
1790
1791 closure = gclosure_from_pyfunc (self, pyfunc);
1792 if (!closure) {
1793 repr = PyObject_Repr ((PyObject *)pyfunc);
1794 PyErr_Format (PyExc_TypeError, "nothing connected to %s",
1795 PyUnicode_AsUTF8 (repr));
1796 Py_DECREF (repr);
1797 return NULL;
1798 }
1799
1800 retval = g_signal_handlers_unblock_matched (
1801 self->obj, G_SIGNAL_MATCH_CLOSURE, 0, 0, closure, NULL, NULL);
1802 return pygi_guint_to_py (retval);
1803 }
1804
1805
1806 static PyMethodDef pygobject_methods[] = {
1807 { "get_property", (PyCFunction)pygobject_get_property, METH_VARARGS },
1808 { "get_properties", (PyCFunction)pygobject_get_properties, METH_VARARGS },
1809 { "set_property", (PyCFunction)pygobject_set_property, METH_VARARGS },
1810 { "set_properties", (PyCFunction)pygobject_set_properties,
1811 METH_VARARGS | METH_KEYWORDS },
1812 { "bind_property", (PyCFunction)pygobject_bind_property,
1813 METH_VARARGS | METH_KEYWORDS },
1814 { "connect", (PyCFunction)pygobject_connect, METH_VARARGS },
1815 { "connect_after", (PyCFunction)pygobject_connect_after, METH_VARARGS },
1816 { "connect_object", (PyCFunction)pygobject_connect_object, METH_VARARGS },
1817 { "connect_object_after", (PyCFunction)pygobject_connect_object_after,
1818 METH_VARARGS },
1819 { "disconnect_by_func", (PyCFunction)pygobject_disconnect_by_func,
1820 METH_VARARGS },
1821 { "handler_block_by_func", (PyCFunction)pygobject_handler_block_by_func,
1822 METH_VARARGS },
1823 { "handler_unblock_by_func",
1824 (PyCFunction)pygobject_handler_unblock_by_func, METH_VARARGS },
1825 { "emit", (PyCFunction)pygobject_emit, METH_VARARGS },
1826 { "chain", (PyCFunction)pygobject_chain_from_overridden, METH_VARARGS },
1827 { "weak_ref", (PyCFunction)pygobject_weak_ref, METH_VARARGS },
1828 { "do_constructed", (PyCFunction)pygobject_do_constructed, METH_NOARGS },
1829 { "do_dispose", (PyCFunction)pygobject_do_dispose, METH_NOARGS },
1830 { "__copy__", (PyCFunction)pygobject_copy, METH_NOARGS },
1831 { "__deepcopy__", (PyCFunction)pygobject_deepcopy, METH_VARARGS },
1832 { NULL, NULL, 0 },
1833 };
1834
1835 static PyObject *
1836 pygobject_get_refcount (PyGObject *self, void *closure)
1837 {
1838 if (self->obj == NULL) {
1839 PyErr_Format (PyExc_TypeError, "GObject instance is not yet created");
1840 return NULL;
1841 }
1842 return pygi_guint_to_py (self->obj->ref_count);
1843 }
1844
1845 static PyObject *
1846 pygobject_get_pointer (PyGObject *self, void *closure)
1847 {
1848 return PyCapsule_New (self->obj, NULL, NULL);
1849 }
1850
1851 static PyGetSetDef pygobject_getsets[] = {
1852 { "__dict__", PyObject_GenericGetDict, (setter)0 },
1853 {
1854 "__grefcount__",
1855 (getter)pygobject_get_refcount,
1856 (setter)0,
1857 },
1858 {
1859 "__gpointer__",
1860 (getter)pygobject_get_pointer,
1861 (setter)0,
1862 },
1863 { NULL, 0, 0 },
1864 };
1865
1866 /* ------------------------------------ */
1867 /* ****** GObject weak reference ****** */
1868 /* ------------------------------------ */
1869
1870 typedef struct {
1871 PyObject_HEAD
1872 GObject *obj;
1873 PyObject *callback;
1874 PyObject *user_data;
1875 gboolean have_floating_ref;
1876 } PyGObjectWeakRef;
1877
1878 PYGI_DEFINE_TYPE ("gi._gi.GObjectWeakRef", PyGObjectWeakRef_Type,
1879 PyGObjectWeakRef);
1880
1881 static int
1882 pygobject_weak_ref_traverse (PyGObjectWeakRef *self, visitproc visit,
1883 void *arg)
1884 {
1885 if (self->callback && visit (self->callback, arg) < 0) return -1;
1886 if (self->user_data && visit (self->user_data, arg) < 0) return -1;
1887 return 0;
1888 }
1889
1890 static void
1891 pygobject_weak_ref_notify (PyGObjectWeakRef *self, GObject *dummy)
1892 {
1893 self->obj = NULL;
1894 if (self->callback) {
1895 PyObject *retval;
1896 PyGILState_STATE state = PyGILState_Ensure ();
1897 retval = PyObject_Call (self->callback, self->user_data, NULL);
1898 if (retval) {
1899 if (!Py_IsNone (retval))
1900 PyErr_Format (PyExc_TypeError,
1901 "GObject weak notify callback returned a value"
1902 " of type %s, should return None",
1903 Py_TYPE (retval)->tp_name);
1904 Py_DECREF (retval);
1905 if (PyErr_Occurred ()) PyErr_Print ();
1906 } else
1907 PyErr_Print ();
1908 Py_CLEAR (self->callback);
1909 Py_CLEAR (self->user_data);
1910 if (self->have_floating_ref) {
1911 self->have_floating_ref = FALSE;
1912 Py_DECREF ((PyObject *)self);
1913 }
1914 PyGILState_Release (state);
1915 }
1916 }
1917
1918 static inline int
1919 pygobject_weak_ref_clear (PyGObjectWeakRef *self)
1920 {
1921 Py_CLEAR (self->callback);
1922 Py_CLEAR (self->user_data);
1923 if (self->obj) {
1924 g_object_weak_unref (self->obj, (GWeakNotify)pygobject_weak_ref_notify,
1925 self);
1926 self->obj = NULL;
1927 }
1928 return 0;
1929 }
1930
1931 static void
1932 pygobject_weak_ref_dealloc (PyGObjectWeakRef *self)
1933 {
1934 PyObject_GC_UnTrack ((PyObject *)self);
1935 pygobject_weak_ref_clear (self);
1936 PyObject_GC_Del (self);
1937 }
1938
1939 static PyObject *
1940 pygobject_weak_ref_new (GObject *obj, PyObject *callback, PyObject *user_data)
1941 {
1942 PyGObjectWeakRef *self;
1943
1944 self = PyObject_GC_New (PyGObjectWeakRef, &PyGObjectWeakRef_Type);
1945 self->callback = callback;
1946 self->user_data = user_data;
1947 Py_XINCREF (self->callback);
1948 Py_XINCREF (self->user_data);
1949 self->obj = obj;
1950 g_object_weak_ref (self->obj, (GWeakNotify)pygobject_weak_ref_notify,
1951 self);
1952 if (callback != NULL) {
1953 /* when we have a callback, we should INCREF the weakref
1954 * object to make it stay alive even if it goes out of scope */
1955 self->have_floating_ref = TRUE;
1956 Py_INCREF ((PyObject *)self);
1957 }
1958 return (PyObject *)self;
1959 }
1960
1961 static PyObject *
1962 pygobject_weak_ref_unref (PyGObjectWeakRef *self, PyObject *args)
1963 {
1964 if (!self->obj) {
1965 PyErr_SetString (PyExc_ValueError, "weak ref already unreffed");
1966 return NULL;
1967 }
1968 g_object_weak_unref (self->obj, (GWeakNotify)pygobject_weak_ref_notify,
1969 self);
1970 self->obj = NULL;
1971 if (self->have_floating_ref) {
1972 self->have_floating_ref = FALSE;
1973 Py_DECREF (self);
1974 }
1975 Py_RETURN_NONE;
1976 }
1977
1978 static PyMethodDef pygobject_weak_ref_methods[] = {
1979 { "unref", (PyCFunction)pygobject_weak_ref_unref, METH_NOARGS },
1980 { NULL, NULL, 0 },
1981 };
1982
1983 static PyObject *
1984 pygobject_weak_ref_call (PyGObjectWeakRef *self, PyObject *args, PyObject *kw)
1985 {
1986 static char *argnames[] = { NULL };
1987
1988 if (!PyArg_ParseTupleAndKeywords (args, kw, ":__call__", argnames))
1989 return NULL;
1990
1991 if (self->obj)
1992 return pygobject_new (self->obj);
1993 else {
1994 Py_RETURN_NONE;
1995 }
1996 }
1997
1998 static gpointer
1999 pyobject_copy (gpointer boxed)
2000 {
2001 PyObject *object = boxed;
2002 PyGILState_STATE state;
2003
2004 state = PyGILState_Ensure ();
2005 Py_INCREF (object);
2006 PyGILState_Release (state);
2007 return object;
2008 }
2009
2010 static void
2011 pyobject_free (gpointer boxed)
2012 {
2013 PyObject *object = boxed;
2014 PyGILState_STATE state;
2015
2016 state = PyGILState_Ensure ();
2017 Py_DECREF (object);
2018 PyGILState_Release (state);
2019 }
2020
2021 /**
2022 * Returns 0 on success, or -1 and sets an exception.
2023 */
2024 int
2025 pyg_object_register_types (PyObject *d)
2026 {
2027 PyObject *o, *descr;
2028
2029 pygobject_custom_key = g_quark_from_static_string ("PyGObject::custom");
2030 pygobject_class_key = g_quark_from_static_string ("PyGObject::class");
2031 pygobject_class_init_key =
2032 g_quark_from_static_string ("PyGObject::class-init");
2033 pygobject_wrapper_key = g_quark_from_static_string ("PyGObject::wrapper");
2034 pygobject_instance_init_ref_count =
2035 g_quark_from_static_string ("PyGObject::instance-init-ref-count");
2036
2037 pygobject_instance_data_key =
2038 g_quark_from_static_string ("PyGObject::instance-data");
2039
2040 /* GObject */
2041 if (!PY_TYPE_OBJECT)
2042 PY_TYPE_OBJECT = g_boxed_type_register_static (
2043 "PyObject", pyobject_copy, pyobject_free);
2044 PyGObject_Type.tp_dealloc = (destructor)pygobject_dealloc;
2045 PyGObject_Type.tp_richcompare = pygobject_richcompare;
2046 PyGObject_Type.tp_repr = (reprfunc)pygobject_repr;
2047 PyGObject_Type.tp_hash = (hashfunc)pygobject_hash;
2048 PyGObject_Type.tp_flags =
2049 (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC);
2050 PyGObject_Type.tp_traverse = (traverseproc)pygobject_traverse;
2051 PyGObject_Type.tp_clear = (inquiry)pygobject_clear;
2052 PyGObject_Type.tp_weaklistoffset = offsetof (PyGObject, weakreflist);
2053 PyGObject_Type.tp_methods = pygobject_methods;
2054 PyGObject_Type.tp_getset = pygobject_getsets;
2055 #ifndef PYPY_VERSION
2056 PyGObject_Type.tp_dictoffset = offsetof (PyGObject, inst_dict);
2057 PyGObject_Type.tp_finalize = (destructor)pygobject_finalize;
2058 #endif
2059 PyGObject_Type.tp_init = (initproc)pygobject_init;
2060 PyGObject_Type.tp_free = (freefunc)pygobject_free;
2061 PyGObject_Type.tp_alloc = PyType_GenericAlloc;
2062 PyGObject_Type.tp_new = PyType_GenericNew;
2063 pygobject_register_class (d, "GObject", G_TYPE_OBJECT, &PyGObject_Type,
2064 NULL);
2065 PyDict_SetItemString (PyGObject_Type.tp_dict, "__gdoc__",
2066 pyg_object_descr_doc_get ());
2067
2068 descr = PyObject_New (PyObject, &PyGPropsDescr_Type);
2069 PyDict_SetItemString (PyGObject_Type.tp_dict, "props", descr);
2070 PyDict_SetItemString (PyGObject_Type.tp_dict, "__module__",
2071 o = PyUnicode_FromString ("gi._gi"));
2072 Py_DECREF (o);
2073
2074 PyGObjectWeakRef_Type.tp_dealloc = (destructor)pygobject_weak_ref_dealloc;
2075 PyGObjectWeakRef_Type.tp_call = (ternaryfunc)pygobject_weak_ref_call;
2076 PyGObjectWeakRef_Type.tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC;
2077 PyGObjectWeakRef_Type.tp_doc = "A GObject weak reference";
2078 PyGObjectWeakRef_Type.tp_traverse =
2079 (traverseproc)pygobject_weak_ref_traverse;
2080 PyGObjectWeakRef_Type.tp_clear = (inquiry)pygobject_weak_ref_clear;
2081 PyGObjectWeakRef_Type.tp_methods = pygobject_weak_ref_methods;
2082 if (PyType_Ready (&PyGObjectWeakRef_Type) < 0) return -1;
2083 PyDict_SetItemString (d, "GObjectWeakRef",
2084 (PyObject *)&PyGObjectWeakRef_Type);
2085
2086 return 0;
2087 }
2088
2089 PyObject *
2090 pyg_object_new (PyGObject *self, PyObject *args, PyObject *kwargs)
2091 {
2092 PyObject *pytype;
2093 GType type;
2094 GObject *obj = NULL;
2095 GObjectClass *class;
2096 guint n_properties = 0, i;
2097 const GValue *values = NULL;
2098 const PyGIArgumentFromPyCleanupData *cleanup_data = NULL;
2099 const char **names = NULL;
2100
2101 if (!PyArg_ParseTuple (args, "O:gobject.new", &pytype)) {
2102 return NULL;
2103 }
2104
2105 if ((type = pyg_type_from_object (pytype)) == 0) return NULL;
2106
2107 if (G_TYPE_IS_ABSTRACT (type)) {
2108 PyErr_Format (PyExc_TypeError,
2109 "cannot create instance of abstract "
2110 "(non-instantiable) type `%s'",
2111 g_type_name (type));
2112 return NULL;
2113 }
2114
2115 if ((class = g_type_class_ref (type)) == NULL) {
2116 PyErr_SetString (PyExc_TypeError,
2117 "could not get a reference to type class");
2118 return NULL;
2119 }
2120
2121 if (pygobject_prepare_construct_properties (
2122 class, kwargs, &n_properties, &names, &values, &cleanup_data)) {
2123 obj = g_object_new_with_properties (type, n_properties, names, values);
2124 }
2125
2126 for (i = 0; i < n_properties; i++) {
2127 pygi_argument_from_py_cleanup (&cleanup_data[i]);
2128 g_free (names[i]);
2129 g_value_unset (&values[i]);
2130 }
2131 g_free (names);
2132 g_free (values);
2133 g_free (cleanup_data);
2134
2135 g_type_class_unref (class);
2136
2137 if (PyErr_Occurred ()) {
2138 g_object_unref (obj);
2139 return NULL;
2140 }
2141
2142 if (obj) {
2143 if (G_IS_INITIALLY_UNOWNED (obj)) {
2144 g_object_ref_sink (obj);
2145 }
2146
2147 self = g_object_get_qdata (obj, pygobject_wrapper_key);
2148 if (self == NULL) {
2149 self = (PyGObject *)pygobject_new ((GObject *)obj);
2150 g_object_unref (obj);
2151 }
2152 } else {
2153 if (!PyErr_Occurred ())
2154 PyErr_SetString (PyExc_RuntimeError, "could not create object");
2155 return NULL;
2156 }
2157
2158 return (PyObject *)self;
2159 }