Debian Codegraph @

gi/gimodule.c

raw
1 /* -*- Mode: C; c-basic-offset: 4 -*-
2 * vim: tabstop=4 shiftwidth=4 expandtab
3 *
4 * Copyright (C) 2005-2009 Johan Dahlin <[email protected]>
5 *
6 * gimodule.c: wrapper for the gobject-introspection library.
7 *
8 * This library is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU Lesser General Public
10 * License as published by the Free Software Foundation; either
11 * version 2.1 of the License, or (at your option) any later version.
12 *
13 * This library is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 * Lesser General Public License for more details.
17 *
18 * You should have received a copy of the GNU Lesser General Public
19 * License along with this library; if not, write to the Free Software
20 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
21 * USA
22 */
23
24 #include "config.h"
25 #include "pygenum.h"
26 #include "pygflags.h"
27 #include "pygboxed.h"
28 #include "pygi-async.h"
29 #include "pygi-basictype.h"
30 #include "pygi-boxed.h"
31 #include "pygi-capi.h"
32 #include "pygi-ccallback.h"
33 #include "pygi-closure.h"
34 #include "pygi-error.h"
35 #include "pygi-foreign.h"
36 #include "pygi-fundamental.h"
37 #include "pygi-info.h"
38 #include "pygi-property.h"
39 #include "pygi-repository.h"
40 #include "pygi-resulttuple.h"
41 #include "pygi-source.h"
42 #include "pygi-struct.h"
43 #include "pygi-type.h"
44 #include "pygi-util.h"
45 #include "pygi-value.h"
46 #include "pyginterface.h"
47 #include "pygobject-types.h"
48 #include "pygobject-object.h"
49 #include "pygobject-props.h"
50 #include "pygpointer.h"
51 #include "pygspawn.h"
52
53 PyObject *PyGIWarning;
54 PyObject *PyGIDeprecationWarning;
55 PyObject *_PyGIDefaultArgPlaceholder;
56
57 static int _gi_exec (PyObject *module);
58
59
60 /* This implementation is bad, see bug 566571 for an example why.
61 * Instead of scanning explicitly declared bases for interfaces, we
62 * should automatically initialize all implemented interfaces to
63 * prevent bugs like that one. However, this will lead to
64 * performance degradation as each virtual method in derived classes
65 * will round-trip through do_*() stuff, *even* if it is not
66 * overriden. We need to teach codegen to retain parent method
67 * instead of setting virtual to *_proxy_do_*() if corresponding
68 * do_*() is not overriden. Ok, that was a messy explanation.
69 */
70 static void
71 pyg_type_add_interfaces (PyTypeObject *class, GType instance_type,
72 PyObject *bases, GType *parent_interfaces,
73 guint n_parent_interfaces)
74 {
75 int i;
76
77 if (!bases) {
78 g_warning ("type has no bases");
79 return;
80 }
81
82 for (i = 0; i < PyTuple_GET_SIZE (bases); ++i) {
83 PyObject *base = PyTuple_GET_ITEM (bases, i);
84 GType itype;
85 const GInterfaceInfo *iinfo;
86 GInterfaceInfo iinfo_copy;
87
88 /* 'base' can also be a PyClassObject, see bug #566571. */
89 if (!PyType_Check (base)) continue;
90
91 if (!PyType_IsSubtype ((PyTypeObject *)base, &PyGInterface_Type))
92 continue;
93
94 itype = pyg_type_from_object (base);
95
96 /* Happens for _implementations_ of an interface. */
97 if (!G_TYPE_IS_INTERFACE (itype)) continue;
98
99 iinfo = pyg_lookup_interface_info (itype);
100 if (!iinfo) {
101 gchar *error;
102 error = g_strdup_printf (
103 "Interface type %s "
104 "has no Python implementation support",
105 ((PyTypeObject *)base)->tp_name);
106 PyErr_Warn (PyExc_RuntimeWarning, error);
107 g_free (error);
108 continue;
109 }
110
111 iinfo_copy = *iinfo;
112 iinfo_copy.interface_data = class;
113 g_type_add_interface_static (instance_type, itype, &iinfo_copy);
114 }
115 }
116
117 static int
118 pyg_run_class_init (GType gtype, gpointer gclass, PyTypeObject *pyclass)
119 {
120 GSList *list;
121 PyGClassInitFunc class_init;
122 GType parent_type;
123 int rv;
124
125 parent_type = g_type_parent (gtype);
126 if (parent_type) {
127 rv = pyg_run_class_init (parent_type, gclass, pyclass);
128 if (rv) return rv;
129 }
130
131 list = g_type_get_qdata (gtype, pygobject_class_init_key);
132 for (; list; list = list->next) {
133 class_init = list->data;
134 rv = class_init (gclass, pyclass);
135 if (rv) return rv;
136 }
137
138 return 0;
139 }
140
141 static char *
142 get_type_name_for_class (PyTypeObject *class)
143 {
144 gint i, name_serial;
145 char name_serial_str[16];
146 PyObject *module;
147 char *type_name = NULL;
148
149 /* make name for new GType */
150 name_serial = 1;
151 /* give up after 1000 tries, just in case.. */
152 while (name_serial < 1000) {
153 g_free (type_name);
154 g_snprintf (name_serial_str, 16, "-v%i", name_serial);
155 module = PyObject_GetAttrString ((PyObject *)class, "__module__");
156 if (module && PyUnicode_Check (module)) {
157 type_name =
158 g_strconcat (PyUnicode_AsUTF8 (module), ".", class->tp_name,
159 name_serial > 1 ? name_serial_str : NULL, NULL);
160 Py_DECREF (module);
161 } else {
162 if (module)
163 Py_DECREF (module);
164 else
165 PyErr_Clear ();
166 type_name = g_strconcat (class->tp_name,
167 name_serial > 1 ? name_serial_str : NULL,
168 NULL);
169 }
170 /* convert '.' in type name to '+', which isn't banned (grumble) */
171 for (i = 0; type_name[i] != '\0'; i++)
172 if (type_name[i] == '.') type_name[i] = '+';
173 if (g_type_from_name (type_name) == 0)
174 break; /* we now have a unique name */
175 ++name_serial;
176 }
177
178 return type_name;
179 }
180
181 static int
182 pyg_type_register (PyTypeObject *class, const char *type_name)
183 {
184 PyObject *gtype;
185 GType parent_type, instance_type;
186 GType *parent_interfaces;
187 guint n_parent_interfaces;
188 GTypeQuery query;
189 gpointer gclass;
190 GTypeInfo type_info = {
191 0, /* class_size */
192
193 (GBaseInitFunc)NULL,
194 (GBaseFinalizeFunc)NULL,
195
196 (GClassInitFunc)NULL,
197 (GClassFinalizeFunc)NULL,
198 NULL, /* class_data */
199
200 0, /* instance_size */
201 0, /* n_preallocs */
202 (GInstanceInitFunc)NULL,
203 };
204 gchar *new_type_name;
205
206 if (PyType_IsSubtype (class, &PyGObject_Type)) {
207 type_info.class_init = (GClassInitFunc)pygobject__g_class_init;
208 type_info.instance_init = pygobject__g_instance_init;
209 }
210
211 /* find the GType of the parent */
212 parent_type = pyg_type_from_object ((PyObject *)class);
213 if (!parent_type) return -1;
214
215 parent_interfaces = g_type_interfaces (parent_type, &n_parent_interfaces);
216
217 if (type_name) /* care is taken below not to free this */
218 new_type_name = (gchar *)type_name;
219 else
220 new_type_name = get_type_name_for_class (class);
221
222 /* set class_data that will be passed to the class_init function. */
223 type_info.class_data = class;
224
225 /* fill in missing values of GTypeInfo struct */
226 g_type_query (parent_type, &query);
227 type_info.class_size = (guint16)query.class_size;
228 type_info.instance_size = (guint16)query.instance_size;
229
230 /* create new typecode */
231 instance_type =
232 g_type_register_static (parent_type, new_type_name, &type_info, 0);
233 if (instance_type == 0) {
234 PyErr_Format (PyExc_RuntimeError,
235 "could not create new GType: %s (subclass of %s)",
236 new_type_name, g_type_name (parent_type));
237
238 if (type_name == NULL) g_free (new_type_name);
239
240 return -1;
241 }
242
243 if (type_name == NULL) g_free (new_type_name);
244
245 /* store pointer to the class with the GType */
246 Py_INCREF (class);
247 g_type_set_qdata (instance_type, pygobject_class_key, class);
248
249 /* Mark this GType as a custom python type */
250 g_type_set_qdata (instance_type, pygobject_custom_key,
251 GINT_TO_POINTER (1));
252
253 /* set new value of __gtype__ on class */
254 gtype = pyg_type_wrapper_new (instance_type);
255 PyObject_SetAttrString ((PyObject *)class, "__gtype__", gtype);
256 Py_DECREF (gtype);
257
258 /* if no __doc__, set it to the auto doc descriptor */
259 if (PyDict_GetItemString (class->tp_dict, "__doc__") == NULL) {
260 PyDict_SetItemString (class->tp_dict, "__doc__",
261 pyg_object_descr_doc_get ());
262 }
263
264 /*
265 * Note, all interfaces need to be registered before the first
266 * g_type_class_ref(), see bug #686149.
267 *
268 * See also comment above pyg_type_add_interfaces().
269 */
270 pyg_type_add_interfaces (class, instance_type, class->tp_bases,
271 parent_interfaces, n_parent_interfaces);
272
273
274 gclass = g_type_class_ref (instance_type);
275 if (PyErr_Occurred () != NULL) {
276 g_type_class_unref (gclass);
277 g_free (parent_interfaces);
278 return -1;
279 }
280
281 if (pyg_run_class_init (instance_type, gclass, class)) {
282 g_type_class_unref (gclass);
283 g_free (parent_interfaces);
284 return -1;
285 }
286 g_type_class_unref (gclass);
287 g_free (parent_interfaces);
288
289 if (PyErr_Occurred () != NULL) return -1;
290 return 0;
291 }
292
293 static PyObject *
294 _wrap_pyg_type_register (PyObject *self, PyObject *args)
295 {
296 PyTypeObject *class;
297 char *type_name = NULL;
298
299 if (!PyArg_ParseTuple (args, "O!|z:gobject.type_register", &PyType_Type,
300 &class, &type_name))
301 return NULL;
302
303 GType base_gtype = pyg_type_from_object ((PyObject *)class->tp_base);
304
305 if (base_gtype == G_TYPE_INVALID) {
306 PyErr_SetString (PyExc_TypeError,
307 "argument must be a Fundamental or GObject subclass");
308 return NULL;
309 }
310
311 /* Check if type already registered */
312 if (pyg_type_from_object ((PyObject *)class) == base_gtype) {
313 if (pyg_type_register (class, type_name)) return NULL;
314 }
315
316 return Py_NewRef (class);
317 }
318
319 static PyObject *
320 _wrap_pyg_enum_register (PyObject *self, PyObject *args)
321 {
322 PyTypeObject *class;
323 const char *type_name = NULL;
324 char *new_type_name;
325
326 if (!PyArg_ParseTuple (args, "O!z:enum_register", &PyType_Type, &class,
327 &type_name))
328 return NULL;
329
330 if (!PyObject_IsSubclass ((PyObject *)class, (PyObject *)PyGEnum_Type)) {
331 PyErr_SetString (PyExc_TypeError, "class is not a GEnum");
332 return NULL;
333 }
334
335 if (type_name)
336 new_type_name = g_strdup (type_name);
337 else
338 new_type_name = get_type_name_for_class (class);
339
340 if (!pyg_enum_register (class, new_type_name)) return NULL;
341
342 Py_RETURN_NONE;
343 }
344
345 static PyObject *
346 _wrap_pyg_flags_register (PyObject *self, PyObject *args)
347 {
348 PyTypeObject *class;
349 const char *type_name = NULL;
350 char *new_type_name;
351
352 if (!PyArg_ParseTuple (args, "O!z:flags_register", &PyType_Type, &class,
353 &type_name))
354 return NULL;
355
356 if (!PyObject_IsSubclass ((PyObject *)class, (PyObject *)PyGFlags_Type)) {
357 PyErr_SetString (PyExc_TypeError, "class is not a GFlags");
358 return NULL;
359 }
360
361 if (type_name)
362 new_type_name = g_strdup (type_name);
363 else
364 new_type_name = get_type_name_for_class (class);
365
366 if (!pyg_flags_register (class, new_type_name)) return NULL;
367
368 Py_RETURN_NONE;
369 }
370
371 static PyObject *
372 _wrap_pyg_enum_add (PyObject *self, PyObject *args, PyObject *kwargs)
373 {
374 static char *kwlist[] = { "module", "name", "g_type", "enum_info", NULL };
375 PyObject *module, *py_g_type;
376 PyGIBaseInfo *py_info;
377 const char *name;
378 GType g_type;
379 GIEnumInfo *info;
380
381 if (!PyArg_ParseTupleAndKeywords (args, kwargs, "OsOO:enum_add", kwlist,
382 &module, &name, &py_g_type, &py_info)) {
383 return NULL;
384 }
385
386 if (!Py_IsNone (module) && !PyModule_Check (module)) {
387 PyErr_SetString (PyExc_TypeError,
388 "first argument must be module or None");
389 return NULL;
390 }
391
392 g_type = pyg_type_from_object (py_g_type);
393 if (g_type == G_TYPE_INVALID) {
394 return NULL;
395 }
396
397 if (Py_TYPE (py_info) == &PyGIEnumInfo_Type) {
398 info = GI_ENUM_INFO (py_info->info);
399 } else {
400 info = NULL;
401 }
402
403 return pyg_enum_add_full (module, name, g_type, info);
404 }
405
406 static PyObject *
407 _wrap_pyg_flags_add (PyObject *self, PyObject *args, PyObject *kwargs)
408 {
409 static char *kwlist[] = { "module", "name", "g_type", "flags_info", NULL };
410 PyObject *module, *py_g_type;
411 PyGIBaseInfo *py_info;
412 const char *name;
413 GType g_type;
414 GIFlagsInfo *info;
415
416 if (!PyArg_ParseTupleAndKeywords (args, kwargs, "OsOO:flags_add", kwlist,
417 &module, &name, &py_g_type, &py_info)) {
418 return NULL;
419 }
420
421 if (!Py_IsNone (module) && !PyModule_Check (module)) {
422 PyErr_SetString (PyExc_TypeError,
423 "first argument must be module or None");
424 return NULL;
425 }
426
427 g_type = pyg_type_from_object (py_g_type);
428 if (g_type == G_TYPE_INVALID) {
429 return NULL;
430 }
431
432 if (Py_TYPE (py_info) == &PyGIEnumInfo_Type
433 && GI_IS_FLAGS_INFO (py_info->info)) {
434 info = GI_FLAGS_INFO (py_info->info);
435 } else {
436 info = NULL;
437 }
438
439 return pyg_flags_add_full (module, name, g_type, info);
440 }
441
442 static void
443 initialize_interface (GTypeInterface *iface, PyTypeObject *pytype)
444 {
445 /* pygobject prints a warning if interface_init is NULL */
446 }
447
448 static PyObject *
449 _wrap_pyg_register_interface_info (PyObject *self, PyObject *args)
450 {
451 PyObject *py_g_type;
452 GType g_type;
453 GInterfaceInfo *info;
454
455 if (!PyArg_ParseTuple (args, "O!:register_interface_info",
456 &PyGTypeWrapper_Type, &py_g_type)) {
457 return NULL;
458 }
459
460 g_type = pyg_type_from_object (py_g_type);
461 if (!g_type_is_a (g_type, G_TYPE_INTERFACE)) {
462 PyErr_SetString (PyExc_TypeError, "must be an interface");
463 return NULL;
464 }
465
466 info = g_new0 (GInterfaceInfo, 1);
467 info->interface_init = (GInterfaceInitFunc)initialize_interface;
468
469 pyg_register_interface_info (g_type, info);
470 g_free (info);
471
472 Py_RETURN_NONE;
473 }
474
475 static void
476 find_vfunc_info (GIBaseInfo *vfunc_info, GType implementor_gtype,
477 gpointer *implementor_class_ret,
478 gpointer *implementor_vtable_ret,
479 GIFieldInfo **field_info_ret)
480 {
481 GType ancestor_g_type = 0;
482 GIBaseInfo *ancestor_info;
483 GIStructInfo *struct_info;
484 gpointer implementor_class = NULL;
485 gboolean is_interface = FALSE;
486 GIFieldInfo *field_info;
487
488 ancestor_info = gi_base_info_get_container (vfunc_info);
489 is_interface = GI_IS_INTERFACE_INFO (ancestor_info);
490
491 ancestor_g_type = gi_registered_type_info_get_g_type (
492 (GIRegisteredTypeInfo *)ancestor_info);
493 implementor_class = g_type_class_ref (implementor_gtype);
494 if (is_interface) {
495 GTypeInstance *implementor_iface_class;
496 implementor_iface_class =
497 g_type_interface_peek (implementor_class, ancestor_g_type);
498 if (implementor_iface_class == NULL) {
499 g_type_class_unref (implementor_class);
500 PyErr_Format (
501 PyExc_RuntimeError,
502 "Couldn't find GType of implementor of interface %s. "
503 "Forgot to set __gtype_name__?",
504 g_type_name (ancestor_g_type));
505 return;
506 }
507
508 *implementor_vtable_ret = implementor_iface_class;
509
510 struct_info = gi_interface_info_get_iface_struct (
511 (GIInterfaceInfo *)ancestor_info);
512 } else {
513 struct_info =
514 gi_object_info_get_class_struct ((GIObjectInfo *)ancestor_info);
515 *implementor_vtable_ret = implementor_class;
516 }
517
518 *implementor_class_ret = implementor_class;
519
520 field_info = gi_struct_info_find_field (
521 struct_info, gi_base_info_get_name ((GIBaseInfo *)vfunc_info));
522 if (field_info != NULL) {
523 GITypeInfo *type_info;
524
525 type_info = gi_field_info_get_type_info (field_info);
526 if (gi_type_info_get_tag (type_info) == GI_TYPE_TAG_INTERFACE) {
527 *field_info_ret = field_info;
528 } else {
529 gi_base_info_unref (field_info);
530 }
531 gi_base_info_unref (type_info);
532 }
533
534 gi_base_info_unref (struct_info);
535 }
536
537 static PyObject *
538 _wrap_pyg_hook_up_vfunc_implementation (PyObject *self, PyObject *args)
539 {
540 PyGIBaseInfo *py_info;
541 PyObject *py_type;
542 PyObject *py_function;
543 GType implementor_gtype = 0;
544 gpointer implementor_class = NULL;
545 gpointer implementor_vtable = NULL;
546 GIFieldInfo *field_info = NULL;
547 gpointer *method_ptr = NULL;
548 PyGICClosure *closure = NULL;
549 PyGIClosureCache *cache = NULL;
550
551 if (!PyArg_ParseTuple (args, "O!O!O:hook_up_vfunc_implementation",
552 &PyGIBaseInfo_Type, &py_info, &PyGTypeWrapper_Type,
553 &py_type, &py_function))
554 return NULL;
555
556 implementor_gtype = pyg_type_from_object (py_type);
557 g_assert (G_TYPE_IS_CLASSED (implementor_gtype));
558
559 find_vfunc_info (py_info->info, implementor_gtype, &implementor_class,
560 &implementor_vtable, &field_info);
561 if (field_info != NULL) {
562 GITypeInfo *type_info;
563 GICallableInfo *callable_info;
564 size_t offset;
565
566 type_info = gi_field_info_get_type_info (field_info);
567 callable_info =
568 GI_CALLABLE_INFO (gi_type_info_get_interface (type_info));
569 offset = gi_field_info_get_offset (field_info);
570 method_ptr = G_STRUCT_MEMBER_P (implementor_vtable, offset);
571
572 cache = pygi_closure_cache_new (callable_info);
573 closure = _pygi_make_native_closure ((GICallableInfo *)callable_info,
574 cache, GI_SCOPE_TYPE_NOTIFIED,
575 py_function, NULL);
576
577 *method_ptr = gi_callable_info_get_closure_native_address (
578 callable_info, closure->closure);
579
580 gi_base_info_unref (callable_info);
581 gi_base_info_unref (type_info);
582 gi_base_info_unref (field_info);
583 }
584 g_type_class_unref (implementor_class);
585
586 Py_RETURN_NONE;
587 }
588
589 static PyObject *
590 _wrap_pyg_variant_type_from_string (PyObject *self, PyObject *args)
591 {
592 char *type_string;
593 PyObject *py_type;
594 PyObject *py_variant = NULL;
595
596 if (!PyArg_ParseTuple (args, "s:variant_type_from_string", &type_string)) {
597 return NULL;
598 }
599
600 py_type = pygi_type_import_by_name ("GLib", "VariantType");
601
602 py_variant =
603 pygi_boxed_new ((PyTypeObject *)py_type, type_string, FALSE, 0);
604
605 return py_variant;
606 }
607
608 #define CHUNK_SIZE 8192
609
610 static PyObject *
611 pyg_channel_read (PyObject *self, PyObject *args, PyObject *kwargs)
612 {
613 int max_count = -1;
614 PyObject *py_iochannel, *ret_obj = NULL;
615 gsize total_read = 0;
616 GError *error = NULL;
617 GIOStatus status = G_IO_STATUS_NORMAL;
618 GIOChannel *iochannel = NULL;
619
620 if (!PyArg_ParseTuple (args, "Oi:pyg_channel_read", &py_iochannel,
621 &max_count)) {
622 return NULL;
623 }
624 if (!pyg_boxed_check (py_iochannel, G_TYPE_IO_CHANNEL)) {
625 PyErr_SetString (PyExc_TypeError,
626 "first argument is not a GLib.IOChannel");
627 return NULL;
628 }
629
630 if (max_count == 0) return PyBytes_FromString ("");
631
632 iochannel = pyg_boxed_get (py_iochannel, GIOChannel);
633
634 while (status == G_IO_STATUS_NORMAL
635 && (max_count == -1 || total_read < (gsize)max_count)) {
636 gsize single_read;
637 char *buf;
638 gsize buf_size;
639
640 if (max_count == -1)
641 buf_size = CHUNK_SIZE;
642 else {
643 buf_size = max_count - total_read;
644 if (buf_size > CHUNK_SIZE) buf_size = CHUNK_SIZE;
645 }
646
647 if (ret_obj == NULL) {
648 ret_obj = PyBytes_FromStringAndSize ((char *)NULL, buf_size);
649 if (ret_obj == NULL) goto failure;
650 } else if (buf_size + total_read > (gsize)PyBytes_Size (ret_obj)) {
651 if (_PyBytes_Resize (&ret_obj, buf_size + total_read) == -1)
652 goto failure;
653 }
654
655 buf = PyBytes_AsString (ret_obj) + total_read;
656
657 Py_BEGIN_ALLOW_THREADS;
658 status = g_io_channel_read_chars (iochannel, buf, buf_size,
659 &single_read, &error);
660 Py_END_ALLOW_THREADS;
661
662 if (pygi_error_check (&error)) goto failure;
663
664 total_read += single_read;
665 }
666
667 if (total_read != (gsize)PyBytes_Size (ret_obj)) {
668 if (_PyBytes_Resize (&ret_obj, total_read) == -1) goto failure;
669 }
670
671 return ret_obj;
672
673 failure:
674 Py_XDECREF (ret_obj);
675 return NULL;
676 }
677
678 static PyObject *
679 pyg_main_context_query (PyObject *self, PyObject *args, PyObject *kwargs)
680 {
681 PyObject *py_main_context;
682 int max_priority = -1, n_fds;
683 GMainContext *context;
684 int timeout_msec = 0;
685 GPollFD *fds;
686 int n_poll, read_fds, i;
687 PyObject *py_out, *py_fds;
688
689 if (!PyArg_ParseTuple (args, "Oi:pyg_main_context_query", &py_main_context,
690 &max_priority)) {
691 return NULL;
692 }
693
694 if (!pyg_boxed_check (py_main_context, G_TYPE_MAIN_CONTEXT)) {
695 PyErr_SetString (PyExc_TypeError,
696 "first argument is not a GLib.MainContext");
697 return NULL;
698 }
699
700 context = pyg_boxed_get (py_main_context, GMainContext);
701
702 n_fds = g_main_context_query (context, max_priority, NULL, NULL, 0);
703
704 fds = g_new0 (GPollFD, n_fds);
705
706 n_poll = g_main_context_query (context, max_priority, &timeout_msec, fds,
707 n_fds);
708
709 read_fds = MIN (n_fds, n_poll);
710 py_fds = PyList_New (read_fds);
711 for (i = 0; i < read_fds; i++) {
712 PyObject *py_boxed =
713 pygi_gboxed_new (G_TYPE_POLLFD, &fds[i], TRUE, TRUE);
714 if (py_boxed == NULL) {
715 Py_DECREF (py_fds);
716 g_free (fds);
717 return NULL;
718 }
719 PyList_SET_ITEM (py_fds, i, py_boxed);
720 }
721 g_free (fds);
722
723 py_out = PyTuple_New (2);
724 PyTuple_SET_ITEM (py_out, 0, PyLong_FromLong (timeout_msec));
725 PyTuple_SET_ITEM (py_out, 1, py_fds);
726
727 return py_out;
728 }
729
730 static gboolean
731 marshal_emission_hook (GSignalInvocationHint *ihint, guint n_param_values,
732 const GValue *param_values, gpointer user_data)
733 {
734 PyGILState_STATE state;
735 gboolean retval = FALSE;
736 PyObject *func, *args;
737 PyObject *retobj;
738 PyObject *params;
739 guint i;
740
741 state = PyGILState_Ensure ();
742
743 /* construct Python tuple for the parameter values */
744 params = PyTuple_New (n_param_values);
745
746 for (i = 0; i < n_param_values; i++) {
747 PyObject *item = pyg_value_to_pyobject (&param_values[i], FALSE);
748
749 /* error condition */
750 if (!item) {
751 goto out;
752 }
753 PyTuple_SetItem (params, i, item);
754 }
755
756 args = (PyObject *)user_data;
757 func = PyTuple_GetItem (args, 0);
758 args = PySequence_Concat (params, PyTuple_GetItem (args, 1));
759 Py_DECREF (params);
760
761 /* params passed to function may have extra arguments */
762
763 retobj = PyObject_CallObject (func, args);
764 Py_DECREF (args);
765 if (retobj == NULL) {
766 PyErr_Print ();
767 }
768
769 retval = Py_IsTrue (retobj);
770 Py_XDECREF (retobj);
771 out:
772 PyGILState_Release (state);
773 return retval;
774 }
775
776 static PyObject *
777 pyg_add_emission_hook (PyGObject *self, PyObject *args)
778 {
779 PyObject *first, *callback, *extra_args, *data, *repr;
780 gchar *name;
781 gulong hook_id;
782 guint sigid;
783 Py_ssize_t len;
784 GQuark detail = 0;
785 GType gtype;
786 PyObject *pygtype;
787
788 len = PyTuple_Size (args);
789 if (len < 3) {
790 PyErr_SetString (
791 PyExc_TypeError,
792 "gobject.add_emission_hook requires at least 3 arguments");
793 return NULL;
794 }
795 first = PySequence_GetSlice (args, 0, 3);
796 if (!PyArg_ParseTuple (first, "OsO:add_emission_hook", &pygtype, &name,
797 &callback)) {
798 Py_DECREF (first);
799 return NULL;
800 }
801 Py_DECREF (first);
802
803 if ((gtype = pyg_type_from_object (pygtype)) == 0) {
804 return NULL;
805 }
806 if (!PyCallable_Check (callback)) {
807 PyErr_SetString (PyExc_TypeError, "third argument must be callable");
808 return NULL;
809 }
810
811 if (!g_signal_parse_name (name, gtype, &sigid, &detail, TRUE)) {
812 repr = PyObject_Repr ((PyObject *)self);
813 PyErr_Format (PyExc_TypeError, "%s: unknown signal name: %s",
814 PyUnicode_AsUTF8 (repr), name);
815 Py_DECREF (repr);
816 return NULL;
817 }
818 extra_args = PySequence_GetSlice (args, 3, len);
819 if (extra_args == NULL) return NULL;
820
821 data = Py_BuildValue ("(ON)", callback, extra_args);
822 if (data == NULL) return NULL;
823
824 hook_id = g_signal_add_emission_hook (sigid, detail, marshal_emission_hook,
825 data,
826 (GDestroyNotify)pyg_destroy_notify);
827
828 return pygi_gulong_to_py (hook_id);
829 }
830
831 static PyObject *
832 pyg_signal_new (PyObject *self, PyObject *args)
833 {
834 gchar *signal_name;
835 PyObject *py_type;
836 GSignalFlags signal_flags;
837 GType return_type;
838 PyObject *py_return_type, *py_param_types;
839
840 GType instance_type = 0;
841 Py_ssize_t py_n_params;
842 guint n_params, i;
843 GType *param_types;
844
845 guint signal_id;
846
847 if (!PyArg_ParseTuple (args, "sOiOO:gobject.signal_new", &signal_name,
848 &py_type, &signal_flags, &py_return_type,
849 &py_param_types))
850 return NULL;
851
852 instance_type = pyg_type_from_object (py_type);
853 if (!instance_type) return NULL;
854 if (!(G_TYPE_IS_INSTANTIATABLE (instance_type)
855 || G_TYPE_IS_INTERFACE (instance_type))) {
856 PyErr_SetString (
857 PyExc_TypeError,
858 "argument 2 must be an object type or interface type");
859 return NULL;
860 }
861
862 return_type = pyg_type_from_object (py_return_type);
863 if (!return_type) return NULL;
864
865 if (!PySequence_Check (py_param_types)) {
866 PyErr_SetString (PyExc_TypeError,
867 "argument 5 must be a sequence of GType codes");
868 return NULL;
869 }
870
871 py_n_params = PySequence_Length (py_param_types);
872 if (py_n_params < 0) return FALSE;
873
874 if (!pygi_guint_from_pyssize (py_n_params, &n_params)) return FALSE;
875
876 param_types = g_new (GType, n_params);
877 for (i = 0; i < n_params; i++) {
878 PyObject *item = PySequence_GetItem (py_param_types, i);
879
880 param_types[i] = pyg_type_from_object (item);
881 if (param_types[i] == 0) {
882 PyErr_Clear ();
883 Py_DECREF (item);
884 PyErr_SetString (PyExc_TypeError,
885 "argument 5 must be a sequence of GType codes");
886 g_free (param_types);
887 return NULL;
888 }
889 Py_DECREF (item);
890 }
891
892 signal_id = g_signal_newv (
893 signal_name, instance_type, signal_flags,
894 pyg_signal_class_closure_get (), (GSignalAccumulator)0, NULL,
895 (GSignalCMarshaller)0, return_type, n_params, param_types);
896 g_free (param_types);
897 if (signal_id != 0) return pygi_guint_to_py (signal_id);
898 PyErr_SetString (PyExc_RuntimeError, "could not create signal");
899 return NULL;
900 }
901
902 static PyObject *
903 pyg_object_class_list_properties (PyObject *self, PyObject *args)
904 {
905 GParamSpec **specs;
906 PyObject *py_itype, *list;
907 GType itype;
908 GObjectClass *class = NULL;
909 gpointer iface = NULL;
910 guint nprops;
911 guint i;
912
913 if (!PyArg_ParseTuple (args, "O:gobject.list_properties", &py_itype))
914 return NULL;
915 if ((itype = pyg_type_from_object (py_itype)) == 0) return NULL;
916
917 if (G_TYPE_IS_INTERFACE (itype)) {
918 iface = g_type_default_interface_ref (itype);
919 if (!iface) {
920 PyErr_SetString (PyExc_RuntimeError,
921 "could not get a reference to interface type");
922 return NULL;
923 }
924 specs = g_object_interface_list_properties (iface, &nprops);
925 } else if (g_type_is_a (itype, G_TYPE_OBJECT)) {
926 class = g_type_class_ref (itype);
927 if (!class) {
928 PyErr_SetString (PyExc_RuntimeError,
929 "could not get a reference to type class");
930 return NULL;
931 }
932 specs = g_object_class_list_properties (class, &nprops);
933 } else {
934 PyErr_SetString (PyExc_TypeError,
935 "type must be derived from GObject or an interface");
936 return NULL;
937 }
938
939 list = PyTuple_New (nprops);
940 if (list == NULL) {
941 g_free (specs);
942 g_type_class_unref (class);
943 return NULL;
944 }
945 for (i = 0; i < nprops; i++) {
946 PyTuple_SetItem (list, i, pygi_fundamental_new (specs[i]));
947 }
948 g_free (specs);
949 if (class)
950 g_type_class_unref (class);
951 else
952 g_type_default_interface_unref (iface);
953
954 return list;
955 }
956
957 static PyObject *
958 pyg__install_metaclass (PyObject *dummy, PyTypeObject *metaclass)
959 {
960 PyGObject_MetaType = (PyTypeObject *)Py_NewRef (metaclass);
961 Py_SET_TYPE (&PyGObject_Type, (PyTypeObject *)Py_NewRef (metaclass));
962
963 Py_RETURN_NONE;
964 }
965
966 static PyObject *
967 _wrap_pyig_pyos_getsig (PyObject *self, PyObject *args)
968 {
969 int sig_num;
970
971 if (!PyArg_ParseTuple (args, "i:pyos_getsig", &sig_num)) return NULL;
972
973 return PyLong_FromVoidPtr ((void *)(PyOS_getsig (sig_num)));
974 }
975
976 static PyObject *
977 _wrap_pyig_pyos_setsig (PyObject *self, PyObject *args)
978 {
979 int sig_num;
980 PyObject *sig_handler;
981
982 if (!PyArg_ParseTuple (args, "iO!:pyos_setsig", &sig_num, &PyLong_Type,
983 &sig_handler))
984 return NULL;
985
986 return PyLong_FromVoidPtr ((void *)(PyOS_setsig (
987 sig_num, (PyOS_sighandler_t)PyLong_AsVoidPtr (sig_handler))));
988 }
989
990 static PyObject *
991 _wrap_pygobject_new_full (PyObject *self, PyObject *args)
992 {
993 PyObject *ptr_value, *long_value;
994 PyObject *steal;
995 GObject *obj;
996
997 if (!PyArg_ParseTuple (args, "OO", &ptr_value, &steal)) return NULL;
998
999 long_value = PyNumber_Long (ptr_value);
1000 if (!long_value) {
1001 PyErr_SetString (PyExc_TypeError, "first argument must be an integer");
1002 return NULL;
1003 }
1004 obj = PyLong_AsVoidPtr (long_value);
1005 Py_DECREF (long_value);
1006
1007 if (!G_IS_OBJECT (obj)) {
1008 PyErr_SetString (PyExc_TypeError, "pointer is not a GObject");
1009 return NULL;
1010 }
1011
1012 return pygobject_new_full (obj, PyObject_IsTrue (steal), NULL);
1013 }
1014
1015 static PyMethodDef _gi_functions[] = {
1016 { "pygobject_new_full", (PyCFunction)_wrap_pygobject_new_full,
1017 METH_VARARGS },
1018 { "enum_add", (PyCFunction)_wrap_pyg_enum_add,
1019 METH_VARARGS | METH_KEYWORDS },
1020 { "flags_add", (PyCFunction)_wrap_pyg_flags_add,
1021 METH_VARARGS | METH_KEYWORDS },
1022
1023 { "register_interface_info",
1024 (PyCFunction)_wrap_pyg_register_interface_info, METH_VARARGS },
1025 { "hook_up_vfunc_implementation",
1026 (PyCFunction)_wrap_pyg_hook_up_vfunc_implementation, METH_VARARGS },
1027 { "variant_type_from_string",
1028 (PyCFunction)_wrap_pyg_variant_type_from_string, METH_VARARGS },
1029 { "source_new", (PyCFunction)pygi_source_new, METH_NOARGS },
1030 { "pyos_getsig", (PyCFunction)_wrap_pyig_pyos_getsig, METH_VARARGS },
1031 { "pyos_setsig", (PyCFunction)_wrap_pyig_pyos_setsig, METH_VARARGS },
1032 { "source_set_callback", (PyCFunction)pygi_source_set_callback,
1033 METH_VARARGS },
1034 { "io_channel_read", (PyCFunction)pyg_channel_read, METH_VARARGS },
1035 { "main_context_query", (PyCFunction)pyg_main_context_query,
1036 METH_VARARGS },
1037 { "require_foreign", (PyCFunction)pygi_require_foreign,
1038 METH_VARARGS | METH_KEYWORDS },
1039 { "register_foreign", (PyCFunction)pygi_register_foreign, METH_NOARGS },
1040 { "spawn_async", (PyCFunction)pyglib_spawn_async,
1041 METH_VARARGS | METH_KEYWORDS,
1042 "spawn_async(argv, envp=None, working_directory=None,\n"
1043 " flags=0, child_setup=None, user_data=None,\n"
1044 " standard_input=None, standard_output=None,\n"
1045 " standard_error=None) -> (pid, stdin, stdout, stderr)\n"
1046 "\n"
1047 "Execute a child program asynchronously within a glib.MainLoop()\n"
1048 "See the reference manual for a complete reference.\n" },
1049 { "type_register", _wrap_pyg_type_register, METH_VARARGS },
1050 { "enum_register", _wrap_pyg_enum_register, METH_VARARGS },
1051 { "flags_register", _wrap_pyg_flags_register, METH_VARARGS },
1052 { "signal_new", pyg_signal_new, METH_VARARGS },
1053 { "list_properties", pyg_object_class_list_properties, METH_VARARGS },
1054 { "new", (PyCFunction)pyg_object_new, METH_VARARGS | METH_KEYWORDS },
1055 { "add_emission_hook", (PyCFunction)pyg_add_emission_hook, METH_VARARGS },
1056 { "_install_metaclass", (PyCFunction)pyg__install_metaclass, METH_O },
1057 { "_gvalue_get", (PyCFunction)pyg__gvalue_get, METH_O },
1058 { "_gvalue_get_type", (PyCFunction)pyg__gvalue_get_type, METH_O },
1059 { "_gvalue_set", (PyCFunction)pyg__gvalue_set, METH_VARARGS },
1060 { NULL, NULL, 0 },
1061 };
1062
1063 static struct PyGI_API CAPI = {
1064 pygi_register_foreign_struct,
1065 };
1066
1067 /**
1068 * Returns 0 on success, or -1 and sets an exception.
1069 */
1070 static int
1071 pygi_register_constants (PyObject *m)
1072 {
1073 /* PyFloat_ return a new ref, and add object takes the ref */
1074 PyModule_AddObject (m, "G_MINFLOAT", pygi_gfloat_to_py (G_MINFLOAT));
1075 PyModule_AddObject (m, "G_MAXFLOAT", pygi_gfloat_to_py (G_MAXFLOAT));
1076 PyModule_AddObject (m, "G_MINDOUBLE", pygi_gdouble_to_py (G_MINDOUBLE));
1077 PyModule_AddObject (m, "G_MAXDOUBLE", pygi_gdouble_to_py (G_MAXDOUBLE));
1078 PyModule_AddIntConstant (m, "G_MINSHORT", G_MINSHORT);
1079 PyModule_AddIntConstant (m, "G_MAXSHORT", G_MAXSHORT);
1080 PyModule_AddIntConstant (m, "G_MAXUSHORT", G_MAXUSHORT);
1081 PyModule_AddIntConstant (m, "G_MININT", G_MININT);
1082 PyModule_AddIntConstant (m, "G_MAXINT", G_MAXINT);
1083 PyModule_AddObject (m, "G_MAXUINT", pygi_guint_to_py (G_MAXUINT));
1084 PyModule_AddObject (m, "G_MINLONG", pygi_glong_to_py (G_MINLONG));
1085 PyModule_AddObject (m, "G_MAXLONG", pygi_glong_to_py (G_MAXLONG));
1086 PyModule_AddObject (m, "G_MAXULONG", pygi_gulong_to_py (G_MAXULONG));
1087 PyModule_AddObject (m, "G_MAXSIZE", pygi_gsize_to_py (G_MAXSIZE));
1088 PyModule_AddObject (m, "G_MAXSSIZE", pygi_gssize_to_py (G_MAXSSIZE));
1089 PyModule_AddObject (m, "G_MINSSIZE", pygi_gssize_to_py (G_MINSSIZE));
1090 PyModule_AddObject (m, "G_MINOFFSET", pygi_gint64_to_py (G_MINOFFSET));
1091 PyModule_AddObject (m, "G_MAXOFFSET", pygi_gint64_to_py (G_MAXOFFSET));
1092
1093 PyModule_AddIntConstant (m, "SIGNAL_RUN_FIRST", G_SIGNAL_RUN_FIRST);
1094 PyModule_AddIntConstant (m, "PARAM_READWRITE", G_PARAM_READWRITE);
1095
1096 /* The rest of the types are set in __init__.py */
1097 PyModule_AddObject (m, "TYPE_INVALID",
1098 pyg_type_wrapper_new (G_TYPE_INVALID));
1099 PyModule_AddObject (m, "TYPE_GSTRING",
1100 pyg_type_wrapper_new (G_TYPE_GSTRING));
1101
1102 return 0;
1103 }
1104
1105 /**
1106 * Returns 0 on success, or -1 and sets an exception.
1107 */
1108 static int
1109 pygi_register_version_tuples (PyObject *d)
1110 {
1111 PyObject *tuple;
1112
1113 /* pygobject version */
1114 tuple = Py_BuildValue ("(iii)", PYGOBJECT_MAJOR_VERSION,
1115 PYGOBJECT_MINOR_VERSION, PYGOBJECT_MICRO_VERSION);
1116 PyDict_SetItemString (d, "pygobject_version", tuple);
1117 Py_DECREF (tuple);
1118 return 0;
1119 }
1120
1121 static PyModuleDef_Slot _gi_slots[] = {
1122 { Py_mod_exec, _gi_exec },
1123 { 0, NULL },
1124 };
1125
1126 static struct PyModuleDef __gimodule = {
1127 PyModuleDef_HEAD_INIT,
1128 "_gi",
1129 NULL,
1130 0,
1131 _gi_functions,
1132 _gi_slots,
1133 NULL,
1134 NULL,
1135 NULL,
1136 };
1137
1138 #ifdef __GNUC__
1139 #define PYGI_MODINIT_FUNC \
1140 __attribute__ ((visibility ("default"))) PyMODINIT_FUNC
1141 #else
1142 #define PYGI_MODINIT_FUNC PyMODINIT_FUNC
1143 #endif
1144
1145 PYGI_MODINIT_FUNC PyInit__gi (void);
1146
1147 PYGI_MODINIT_FUNC
1148 PyInit__gi (void) { return PyModuleDef_Init (&__gimodule); }
1149
1150 static int
1151 _gi_exec (PyObject *module)
1152 {
1153 PyObject *api;
1154 PyObject *module_dict = PyModule_GetDict (module);
1155 int ret;
1156
1157 #if PY_VERSION_HEX < 0x03090000 || defined(PYPY_VERSION)
1158 /* Deprecated since 3.9 */
1159 /* Except in PyPy it's still not a no-op: https://foss.heptapod.net/pypy/pypy/-/issues/3691, https://github.com/pypy/pypy/issues/3690 */
1160
1161 /* Always enable Python threads since we cannot predict which GI repositories
1162 * might accept Python callbacks run within non-Python threads or might trigger
1163 * toggle ref notifications.
1164 * See: https://bugzilla.gnome.org/show_bug.cgi?id=709223
1165 */
1166 PyEval_InitThreads ();
1167 #endif
1168
1169 PyModule_AddStringConstant (module, "__package__", "gi._gi");
1170
1171 if ((ret = pygi_foreign_init ()) < 0) return ret;
1172 if ((ret = pygi_error_register_types (module)) < 0) return ret;
1173 if ((ret = pygi_repository_register_types (module)) < 0) return ret;
1174 if ((ret = pygi_info_register_types (module)) < 0) return ret;
1175 if ((ret = pygi_type_register_types (module_dict)) < 0) return ret;
1176 if ((ret = pygi_pointer_register_types (module_dict)) < 0) return ret;
1177 if ((ret = pygi_struct_register_types (module)) < 0) return ret;
1178 if ((ret = pygi_gboxed_register_types (module_dict)) < 0) return ret;
1179 if ((ret = pygi_fundamental_register_types (module)) < 0) return ret;
1180 if ((ret = pygi_boxed_register_types (module)) < 0) return ret;
1181 if ((ret = pygi_ccallback_register_types (module)) < 0) return ret;
1182 if ((ret = pygi_resulttuple_register_types (module)) < 0) return ret;
1183 if ((ret = pygi_async_register_types (module) < 0)) return ret;
1184
1185 if ((ret = pygi_spawn_register_types (module_dict)) < 0) return ret;
1186
1187 if ((ret = pygi_register_constants (module)) < 0) return ret;
1188 if ((ret = pygi_register_version_tuples (module_dict)) < 0) return ret;
1189 if ((ret = pygi_register_warnings (module_dict)) < 0) return ret;
1190 if ((ret = pyg_object_props_register_types (module_dict)) < 0) return ret;
1191 if ((ret = pyg_object_register_types (module_dict)) < 0) return ret;
1192 if ((ret = pygi_interface_register_types (module_dict)) < 0) return ret;
1193 if ((ret = pygi_enum_register_types (module)) < 0) return ret;
1194 if ((ret = pygi_flags_register_types (module)) < 0) return ret;
1195 if ((ret = pygi_register_api (module_dict)) < 0) return ret;
1196
1197 PyGIWarning = PyErr_NewException ("gi.PyGIWarning", PyExc_Warning, NULL);
1198 if (PyGIWarning == NULL) return -1;
1199
1200 PyGIDeprecationWarning = PyErr_NewException (
1201 "gi.PyGIDeprecationWarning", PyExc_DeprecationWarning, NULL);
1202
1203 /* Place holder object used to fill in "from Python" argument lists
1204 * for values not supplied by the caller but support a GI default.
1205 */
1206 _PyGIDefaultArgPlaceholder = PyList_New (0);
1207
1208 Py_INCREF (PyGIWarning);
1209 PyModule_AddObject (module, "PyGIWarning", PyGIWarning);
1210
1211 Py_INCREF (PyGIDeprecationWarning);
1212 PyModule_AddObject (module, "PyGIDeprecationWarning",
1213 PyGIDeprecationWarning);
1214
1215 api = PyCapsule_New ((void *)&CAPI, "gi._API", NULL);
1216 if (api == NULL) {
1217 return -1;
1218 }
1219 PyModule_AddObject (module, "_API", api);
1220
1221 return 0;
1222 }