Rename pyglib-python-compat.h to pygi-python-compat.h
[pygobject.git] / gi / gimodule.c
blob0a8316ccf358ce72b3fb98299f345fa1b58a46da
1 /* -*- Mode: C; c-basic-offset: 4 -*-
2 * vim: tabstop=4 shiftwidth=4 expandtab
4 * Copyright (C) 2005-2009 Johan Dahlin <johan@gnome.org>
6 * gimodule.c: wrapper for the gobject-introspection library.
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.
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.
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
24 #include <Python.h>
25 #include <glib-object.h>
27 #include "config.h"
28 #include "pyginterface.h"
29 #include "pygi-repository.h"
30 #include "pygtype.h"
31 #include "pygenum.h"
32 #include "pygboxed.h"
33 #include "pygflags.h"
34 #include "pygi-error.h"
35 #include "pygi-foreign.h"
36 #include "pygi-resulttuple.h"
37 #include "pygi-source.h"
38 #include "pygi-ccallback.h"
39 #include "pygi-closure.h"
40 #include "pygi-type.h"
41 #include "pygi-boxed.h"
42 #include "pygi-info.h"
43 #include "pygi-struct.h"
44 #include "pygobject-object.h"
45 #include "pygoptioncontext.h"
46 #include "pygoptiongroup.h"
47 #include "pygspawn.h"
48 #include "pygparamspec.h"
49 #include "pygpointer.h"
50 #include "pygobject-internal.h"
51 #include "pygi-value.h"
52 #include "pygi-property.h"
53 #include "pygi-util.h"
54 #include "gimodule.h"
55 #include "pygi-python-compat.h"
57 PyObject *PyGIWarning;
58 PyObject *PyGIDeprecationWarning;
59 PyObject *_PyGIDefaultArgPlaceholder;
61 /* Returns a new flag/enum type or %NULL */
62 static PyObject *
63 flags_enum_from_gtype (GType g_type,
64 PyObject * (add_func) (PyObject *, const char *,
65 const char *, GType))
67 PyObject *new_type;
68 GIRepository *repository;
69 GIBaseInfo *info;
70 const gchar *type_name;
72 repository = g_irepository_get_default ();
73 info = g_irepository_find_by_gtype (repository, g_type);
74 if (info != NULL) {
75 type_name = g_base_info_get_name (info);
76 new_type = add_func (NULL, type_name, NULL, g_type);
77 g_base_info_unref (info);
78 } else {
79 type_name = g_type_name (g_type);
80 new_type = add_func (NULL, type_name, NULL, g_type);
83 return new_type;
86 static void pyg_flags_add_constants(PyObject *module, GType flags_type,
87 const gchar *strip_prefix);
89 /**
90 * pyg_enum_add_constants:
91 * @module: a Python module
92 * @enum_type: the GType of the enumeration.
93 * @strip_prefix: the prefix to strip from the constant names.
95 * Adds constants to the given Python module for each value name of
96 * the enumeration. A prefix will be stripped from each enum name.
98 static void
99 pyg_enum_add_constants(PyObject *module, GType enum_type,
100 const gchar *strip_prefix)
102 GEnumClass *eclass;
103 guint i;
105 if (!G_TYPE_IS_ENUM(enum_type)) {
106 if (G_TYPE_IS_FLAGS(enum_type)) /* See bug #136204 */
107 pyg_flags_add_constants(module, enum_type, strip_prefix);
108 else
109 g_warning("`%s' is not an enum type", g_type_name(enum_type));
110 return;
112 g_return_if_fail (strip_prefix != NULL);
114 eclass = G_ENUM_CLASS(g_type_class_ref(enum_type));
116 for (i = 0; i < eclass->n_values; i++) {
117 const gchar *name = eclass->values[i].value_name;
118 gint value = eclass->values[i].value;
120 PyModule_AddIntConstant(module,
121 (char*) pyg_constant_strip_prefix(name, strip_prefix),
122 (long) value);
125 g_type_class_unref(eclass);
129 * pyg_flags_add_constants:
130 * @module: a Python module
131 * @flags_type: the GType of the flags type.
132 * @strip_prefix: the prefix to strip from the constant names.
134 * Adds constants to the given Python module for each value name of
135 * the flags set. A prefix will be stripped from each flag name.
137 static void
138 pyg_flags_add_constants(PyObject *module, GType flags_type,
139 const gchar *strip_prefix)
141 GFlagsClass *fclass;
142 guint i;
144 if (!G_TYPE_IS_FLAGS(flags_type)) {
145 if (G_TYPE_IS_ENUM(flags_type)) /* See bug #136204 */
146 pyg_enum_add_constants(module, flags_type, strip_prefix);
147 else
148 g_warning("`%s' is not an flags type", g_type_name(flags_type));
149 return;
151 g_return_if_fail (strip_prefix != NULL);
153 fclass = G_FLAGS_CLASS(g_type_class_ref(flags_type));
155 for (i = 0; i < fclass->n_values; i++) {
156 const gchar *name = fclass->values[i].value_name;
157 guint value = fclass->values[i].value;
159 PyModule_AddIntConstant(module,
160 (char*) pyg_constant_strip_prefix(name, strip_prefix),
161 (long) value);
164 g_type_class_unref(fclass);
168 * pyg_set_thread_block_funcs:
169 * Deprecated, only available for ABI compatibility.
171 static void
172 _pyg_set_thread_block_funcs (PyGThreadBlockFunc block_threads_func,
173 PyGThreadBlockFunc unblock_threads_func)
175 PyGILState_STATE state = PyGILState_Ensure ();
176 PyErr_Warn (PyExc_DeprecationWarning,
177 "Using pyg_set_thread_block_funcs is not longer needed. "
178 "PyGObject always uses Py_BLOCK/UNBLOCK_THREADS.");
179 PyGILState_Release (state);
182 static GParamSpec *
183 create_property (const gchar *prop_name,
184 GType prop_type,
185 const gchar *nick,
186 const gchar *blurb,
187 PyObject *args,
188 GParamFlags flags)
190 GParamSpec *pspec = NULL;
192 switch (G_TYPE_FUNDAMENTAL(prop_type)) {
193 case G_TYPE_CHAR:
195 gchar minimum, maximum, default_value;
197 if (!PyArg_ParseTuple(args, "ccc", &minimum, &maximum,
198 &default_value))
199 return NULL;
200 pspec = g_param_spec_char (prop_name, nick, blurb, minimum,
201 maximum, default_value, flags);
203 break;
204 case G_TYPE_UCHAR:
206 gchar minimum, maximum, default_value;
208 if (!PyArg_ParseTuple(args, "ccc", &minimum, &maximum,
209 &default_value))
210 return NULL;
211 pspec = g_param_spec_uchar (prop_name, nick, blurb, minimum,
212 maximum, default_value, flags);
214 break;
215 case G_TYPE_BOOLEAN:
217 gboolean default_value;
219 if (!PyArg_ParseTuple(args, "i", &default_value))
220 return NULL;
221 pspec = g_param_spec_boolean (prop_name, nick, blurb,
222 default_value, flags);
224 break;
225 case G_TYPE_INT:
227 gint minimum, maximum, default_value;
229 if (!PyArg_ParseTuple(args, "iii", &minimum, &maximum,
230 &default_value))
231 return NULL;
232 pspec = g_param_spec_int (prop_name, nick, blurb, minimum,
233 maximum, default_value, flags);
235 break;
236 case G_TYPE_UINT:
238 guint minimum, maximum, default_value;
240 if (!PyArg_ParseTuple(args, "III", &minimum, &maximum,
241 &default_value))
242 return NULL;
243 pspec = g_param_spec_uint (prop_name, nick, blurb, minimum,
244 maximum, default_value, flags);
246 break;
247 case G_TYPE_LONG:
249 glong minimum, maximum, default_value;
251 if (!PyArg_ParseTuple(args, "lll", &minimum, &maximum,
252 &default_value))
253 return NULL;
254 pspec = g_param_spec_long (prop_name, nick, blurb, minimum,
255 maximum, default_value, flags);
257 break;
258 case G_TYPE_ULONG:
260 gulong minimum, maximum, default_value;
262 if (!PyArg_ParseTuple(args, "kkk", &minimum, &maximum,
263 &default_value))
264 return NULL;
265 pspec = g_param_spec_ulong (prop_name, nick, blurb, minimum,
266 maximum, default_value, flags);
268 break;
269 case G_TYPE_INT64:
271 gint64 minimum, maximum, default_value;
273 if (!PyArg_ParseTuple(args, "LLL", &minimum, &maximum,
274 &default_value))
275 return NULL;
276 pspec = g_param_spec_int64 (prop_name, nick, blurb, minimum,
277 maximum, default_value, flags);
279 break;
280 case G_TYPE_UINT64:
282 guint64 minimum, maximum, default_value;
284 if (!PyArg_ParseTuple(args, "KKK", &minimum, &maximum,
285 &default_value))
286 return NULL;
287 pspec = g_param_spec_uint64 (prop_name, nick, blurb, minimum,
288 maximum, default_value, flags);
290 break;
291 case G_TYPE_ENUM:
293 gint default_value;
294 PyObject *pydefault;
296 if (!PyArg_ParseTuple(args, "O", &pydefault))
297 return NULL;
299 if (pyg_enum_get_value(prop_type, pydefault,
300 (gint *)&default_value))
301 return NULL;
303 pspec = g_param_spec_enum (prop_name, nick, blurb,
304 prop_type, default_value, flags);
306 break;
307 case G_TYPE_FLAGS:
309 guint default_value;
310 PyObject *pydefault;
312 if (!PyArg_ParseTuple(args, "O", &pydefault))
313 return NULL;
315 if (pyg_flags_get_value(prop_type, pydefault,
316 &default_value))
317 return NULL;
319 pspec = g_param_spec_flags (prop_name, nick, blurb,
320 prop_type, default_value, flags);
322 break;
323 case G_TYPE_FLOAT:
325 gfloat minimum, maximum, default_value;
327 if (!PyArg_ParseTuple(args, "fff", &minimum, &maximum,
328 &default_value))
329 return NULL;
330 pspec = g_param_spec_float (prop_name, nick, blurb, minimum,
331 maximum, default_value, flags);
333 break;
334 case G_TYPE_DOUBLE:
336 gdouble minimum, maximum, default_value;
338 if (!PyArg_ParseTuple(args, "ddd", &minimum, &maximum,
339 &default_value))
340 return NULL;
341 pspec = g_param_spec_double (prop_name, nick, blurb, minimum,
342 maximum, default_value, flags);
344 break;
345 case G_TYPE_STRING:
347 const gchar *default_value;
349 if (!PyArg_ParseTuple(args, "z", &default_value))
350 return NULL;
351 pspec = g_param_spec_string (prop_name, nick, blurb,
352 default_value, flags);
354 break;
355 case G_TYPE_PARAM:
356 if (!PyArg_ParseTuple(args, ""))
357 return NULL;
358 pspec = g_param_spec_param (prop_name, nick, blurb, prop_type, flags);
359 break;
360 case G_TYPE_BOXED:
361 if (!PyArg_ParseTuple(args, ""))
362 return NULL;
363 pspec = g_param_spec_boxed (prop_name, nick, blurb, prop_type, flags);
364 break;
365 case G_TYPE_POINTER:
366 if (!PyArg_ParseTuple(args, ""))
367 return NULL;
368 if (prop_type == G_TYPE_GTYPE)
369 pspec = g_param_spec_gtype (prop_name, nick, blurb, G_TYPE_NONE, flags);
370 else
371 pspec = g_param_spec_pointer (prop_name, nick, blurb, flags);
372 break;
373 case G_TYPE_OBJECT:
374 case G_TYPE_INTERFACE:
375 if (!PyArg_ParseTuple(args, ""))
376 return NULL;
377 pspec = g_param_spec_object (prop_name, nick, blurb, prop_type, flags);
378 break;
379 case G_TYPE_VARIANT:
381 PyObject *pydefault;
382 GVariant *default_value = NULL;
384 if (!PyArg_ParseTuple(args, "O", &pydefault))
385 return NULL;
386 if (pydefault != Py_None)
387 default_value = pyg_boxed_get (pydefault, GVariant);
388 pspec = g_param_spec_variant (prop_name, nick, blurb, G_VARIANT_TYPE_ANY, default_value, flags);
390 break;
391 default:
392 /* unhandled pspec type ... */
393 break;
396 if (!pspec) {
397 char buf[128];
399 g_snprintf(buf, sizeof(buf), "could not create param spec for type %s",
400 g_type_name(prop_type));
401 PyErr_SetString(PyExc_TypeError, buf);
402 return NULL;
405 return pspec;
408 static GParamSpec *
409 pyg_param_spec_from_object (PyObject *tuple)
411 gint val_length;
412 const gchar *prop_name;
413 GType prop_type;
414 const gchar *nick, *blurb;
415 PyObject *slice, *item, *py_prop_type;
416 GParamSpec *pspec;
418 val_length = PyTuple_Size(tuple);
419 if (val_length < 4) {
420 PyErr_SetString(PyExc_TypeError,
421 "paramspec tuples must be at least 4 elements long");
422 return NULL;
425 slice = PySequence_GetSlice(tuple, 0, 4);
426 if (!slice) {
427 return NULL;
430 if (!PyArg_ParseTuple(slice, "sOzz", &prop_name, &py_prop_type, &nick, &blurb)) {
431 Py_DECREF(slice);
432 return NULL;
435 Py_DECREF(slice);
437 prop_type = pyg_type_from_object(py_prop_type);
438 if (!prop_type) {
439 return NULL;
442 item = PyTuple_GetItem(tuple, val_length-1);
443 if (!PYGLIB_PyLong_Check(item)) {
444 PyErr_SetString(PyExc_TypeError,
445 "last element in tuple must be an int");
446 return NULL;
449 /* slice is the extra items in the tuple */
450 slice = PySequence_GetSlice(tuple, 4, val_length-1);
451 pspec = create_property(prop_name, prop_type,
452 nick, blurb, slice,
453 PYGLIB_PyLong_AsLong(item));
455 return pspec;
459 * pyg_parse_constructor_args: helper function for PyGObject constructors
460 * @obj_type: GType of the GObject, for parameter introspection
461 * @arg_names: %NULL-terminated array of constructor argument names
462 * @prop_names: %NULL-terminated array of property names, with direct
463 * correspondence to @arg_names
464 * @params: GParameter array where parameters will be placed; length
465 * of this array must be at least equal to the number of
466 * arguments/properties
467 * @nparams: output parameter to contain actual number of arguments found
468 * @py_args: array of PyObject* containing the actual constructor arguments
470 * Parses an array of PyObject's and creates a GParameter array
472 * Return value: %TRUE if all is successful, otherwise %FALSE and
473 * python exception set.
475 static gboolean
476 pyg_parse_constructor_args(GType obj_type,
477 char **arg_names,
478 char **prop_names,
479 GParameter *params,
480 guint *nparams,
481 PyObject **py_args)
483 guint arg_i, param_i;
484 GObjectClass *oclass;
486 oclass = g_type_class_ref(obj_type);
487 g_return_val_if_fail(oclass, FALSE);
489 for (param_i = arg_i = 0; arg_names[arg_i]; ++arg_i) {
490 GParamSpec *spec;
491 if (!py_args[arg_i])
492 continue;
493 spec = g_object_class_find_property(oclass, prop_names[arg_i]);
494 params[param_i].name = prop_names[arg_i];
495 g_value_init(&params[param_i].value, spec->value_type);
496 if (pyg_value_from_pyobject(&params[param_i].value, py_args[arg_i]) == -1) {
497 guint i;
498 PyErr_Format(PyExc_TypeError, "could not convert parameter '%s' of type '%s'",
499 arg_names[arg_i], g_type_name(spec->value_type));
500 g_type_class_unref(oclass);
501 for (i = 0; i < param_i; ++i)
502 g_value_unset(&params[i].value);
503 return FALSE;
505 ++param_i;
507 g_type_class_unref(oclass);
508 *nparams = param_i;
509 return TRUE;
512 /* Only for backwards compatibility */
513 static int
514 pygobject_enable_threads(void)
516 return 0;
519 static int
520 pygobject_gil_state_ensure (void)
522 return PyGILState_Ensure ();
525 static void
526 pygobject_gil_state_release (int flag)
528 PyGILState_Release(flag);
531 static void
532 pyg_register_class_init(GType gtype, PyGClassInitFunc class_init)
534 GSList *list;
536 list = g_type_get_qdata(gtype, pygobject_class_init_key);
537 list = g_slist_prepend(list, class_init);
538 g_type_set_qdata(gtype, pygobject_class_init_key, list);
541 static gboolean
542 add_properties (GObjectClass *klass, PyObject *properties)
544 gboolean ret = TRUE;
545 Py_ssize_t pos = 0;
546 PyObject *key, *value;
548 while (PyDict_Next(properties, &pos, &key, &value)) {
549 const gchar *prop_name;
550 GType prop_type;
551 const gchar *nick, *blurb;
552 GParamFlags flags;
553 gint val_length;
554 PyObject *slice, *item, *py_prop_type;
555 GParamSpec *pspec;
557 /* values are of format (type,nick,blurb, type_specific_args, flags) */
559 if (!PYGLIB_PyUnicode_Check(key)) {
560 PyErr_SetString(PyExc_TypeError,
561 "__gproperties__ keys must be strings");
562 ret = FALSE;
563 break;
565 prop_name = PYGLIB_PyUnicode_AsString (key);
567 if (!PyTuple_Check(value)) {
568 PyErr_SetString(PyExc_TypeError,
569 "__gproperties__ values must be tuples");
570 ret = FALSE;
571 break;
573 val_length = PyTuple_Size(value);
574 if (val_length < 4) {
575 PyErr_SetString(PyExc_TypeError,
576 "__gproperties__ values must be at least 4 elements long");
577 ret = FALSE;
578 break;
581 slice = PySequence_GetSlice(value, 0, 3);
582 if (!slice) {
583 ret = FALSE;
584 break;
586 if (!PyArg_ParseTuple(slice, "Ozz", &py_prop_type, &nick, &blurb)) {
587 Py_DECREF(slice);
588 ret = FALSE;
589 break;
591 Py_DECREF(slice);
592 prop_type = pyg_type_from_object(py_prop_type);
593 if (!prop_type) {
594 ret = FALSE;
595 break;
597 item = PyTuple_GetItem(value, val_length-1);
598 if (!PYGLIB_PyLong_Check(item)) {
599 PyErr_SetString(PyExc_TypeError,
600 "last element in __gproperties__ value tuple must be an int");
601 ret = FALSE;
602 break;
604 flags = PYGLIB_PyLong_AsLong(item);
606 /* slice is the extra items in the tuple */
607 slice = PySequence_GetSlice(value, 3, val_length-1);
608 pspec = create_property(prop_name, prop_type, nick, blurb,
609 slice, flags);
610 Py_DECREF(slice);
612 if (pspec) {
613 g_object_class_install_property(klass, 1, pspec);
614 } else {
615 PyObject *type, *pvalue, *traceback;
616 ret = FALSE;
617 PyErr_Fetch(&type, &pvalue, &traceback);
618 if (PYGLIB_PyUnicode_Check(pvalue)) {
619 char msg[256];
620 g_snprintf(msg, 256,
621 "%s (while registering property '%s' for GType '%s')",
622 PYGLIB_PyUnicode_AsString(pvalue),
623 prop_name, G_OBJECT_CLASS_NAME(klass));
624 Py_DECREF(pvalue);
625 value = PYGLIB_PyUnicode_FromString(msg);
627 PyErr_Restore(type, pvalue, traceback);
628 break;
632 return ret;
635 static gboolean
636 override_signal(GType instance_type, const gchar *signal_name)
638 guint signal_id;
640 signal_id = g_signal_lookup(signal_name, instance_type);
641 if (!signal_id) {
642 gchar buf[128];
644 g_snprintf(buf, sizeof(buf), "could not look up %s", signal_name);
645 PyErr_SetString(PyExc_TypeError, buf);
646 return FALSE;
648 g_signal_override_class_closure(signal_id, instance_type,
649 pyg_signal_class_closure_get());
650 return TRUE;
653 typedef struct _PyGSignalAccumulatorData {
654 PyObject *callable;
655 PyObject *user_data;
656 } PyGSignalAccumulatorData;
659 static gboolean
660 _pyg_signal_accumulator(GSignalInvocationHint *ihint,
661 GValue *return_accu,
662 const GValue *handler_return,
663 gpointer _data)
665 PyObject *py_ihint, *py_return_accu, *py_handler_return, *py_detail;
666 PyObject *py_retval;
667 gboolean retval = FALSE;
668 PyGSignalAccumulatorData *data = _data;
669 PyGILState_STATE state;
671 state = PyGILState_Ensure();
672 if (ihint->detail)
673 py_detail = PYGLIB_PyUnicode_FromString(g_quark_to_string(ihint->detail));
674 else {
675 Py_INCREF(Py_None);
676 py_detail = Py_None;
679 py_ihint = Py_BuildValue("lNi", (long int) ihint->signal_id,
680 py_detail, ihint->run_type);
681 py_handler_return = pyg_value_as_pyobject(handler_return, TRUE);
682 py_return_accu = pyg_value_as_pyobject(return_accu, FALSE);
683 if (data->user_data)
684 py_retval = PyObject_CallFunction(data->callable, "NNNO", py_ihint,
685 py_return_accu, py_handler_return,
686 data->user_data);
687 else
688 py_retval = PyObject_CallFunction(data->callable, "NNN", py_ihint,
689 py_return_accu, py_handler_return);
690 if (!py_retval)
691 PyErr_Print();
692 else {
693 if (!PyTuple_Check(py_retval) || PyTuple_Size(py_retval) != 2) {
694 PyErr_SetString(PyExc_TypeError, "accumulator function must return"
695 " a (bool, object) tuple");
696 PyErr_Print();
697 } else {
698 retval = PyObject_IsTrue(PyTuple_GET_ITEM(py_retval, 0));
699 if (pyg_value_from_pyobject(return_accu, PyTuple_GET_ITEM(py_retval, 1))) {
700 PyErr_Print();
703 Py_DECREF(py_retval);
705 PyGILState_Release(state);
706 return retval;
709 static gboolean
710 create_signal (GType instance_type, const gchar *signal_name, PyObject *tuple)
712 GSignalFlags signal_flags;
713 PyObject *py_return_type, *py_param_types;
714 GType return_type;
715 guint n_params, i;
716 GType *param_types;
717 guint signal_id;
718 GSignalAccumulator accumulator = NULL;
719 PyGSignalAccumulatorData *accum_data = NULL;
720 PyObject *py_accum = NULL, *py_accum_data = NULL;
722 if (!PyArg_ParseTuple(tuple, "iOO|OO", &signal_flags, &py_return_type,
723 &py_param_types, &py_accum, &py_accum_data))
725 gchar buf[128];
727 PyErr_Clear();
728 g_snprintf(buf, sizeof(buf),
729 "value for __gsignals__['%s'] not in correct format", signal_name);
730 PyErr_SetString(PyExc_TypeError, buf);
731 return FALSE;
734 if (py_accum && py_accum != Py_None && !PyCallable_Check(py_accum))
736 gchar buf[128];
738 g_snprintf(buf, sizeof(buf),
739 "accumulator for __gsignals__['%s'] must be callable", signal_name);
740 PyErr_SetString(PyExc_TypeError, buf);
741 return FALSE;
744 return_type = pyg_type_from_object(py_return_type);
745 if (!return_type)
746 return FALSE;
747 if (!PySequence_Check(py_param_types)) {
748 gchar buf[128];
750 g_snprintf(buf, sizeof(buf),
751 "third element of __gsignals__['%s'] tuple must be a sequence", signal_name);
752 PyErr_SetString(PyExc_TypeError, buf);
753 return FALSE;
755 n_params = PySequence_Length(py_param_types);
756 param_types = g_new(GType, n_params);
757 for (i = 0; i < n_params; i++) {
758 PyObject *item = PySequence_GetItem(py_param_types, i);
760 param_types[i] = pyg_type_from_object(item);
761 if (param_types[i] == 0) {
762 Py_DECREF(item);
763 g_free(param_types);
764 return FALSE;
766 Py_DECREF(item);
769 if (py_accum != NULL && py_accum != Py_None) {
770 accum_data = g_new(PyGSignalAccumulatorData, 1);
771 accum_data->callable = py_accum;
772 Py_INCREF(py_accum);
773 accum_data->user_data = py_accum_data;
774 Py_XINCREF(py_accum_data);
775 accumulator = _pyg_signal_accumulator;
778 signal_id = g_signal_newv(signal_name, instance_type, signal_flags,
779 pyg_signal_class_closure_get(),
780 accumulator, accum_data,
781 gi_cclosure_marshal_generic,
782 return_type, n_params, param_types);
783 g_free(param_types);
785 if (signal_id == 0) {
786 gchar buf[128];
788 g_snprintf(buf, sizeof(buf), "could not create signal for %s",
789 signal_name);
790 PyErr_SetString(PyExc_RuntimeError, buf);
791 return FALSE;
793 return TRUE;
797 static PyObject *
798 add_signals (GObjectClass *klass, PyObject *signals)
800 gboolean ret = TRUE;
801 Py_ssize_t pos = 0;
802 PyObject *key, *value, *overridden_signals = NULL;
803 GType instance_type = G_OBJECT_CLASS_TYPE (klass);
805 overridden_signals = PyDict_New();
806 while (PyDict_Next(signals, &pos, &key, &value)) {
807 const gchar *signal_name;
808 gchar *signal_name_canon, *c;
810 if (!PYGLIB_PyUnicode_Check(key)) {
811 PyErr_SetString(PyExc_TypeError,
812 "__gsignals__ keys must be strings");
813 ret = FALSE;
814 break;
816 signal_name = PYGLIB_PyUnicode_AsString (key);
818 if (value == Py_None ||
819 (PYGLIB_PyUnicode_Check(value) &&
820 !strcmp(PYGLIB_PyUnicode_AsString(value), "override")))
822 /* canonicalize signal name, replacing '-' with '_' */
823 signal_name_canon = g_strdup(signal_name);
824 for (c = signal_name_canon; *c; ++c)
825 if (*c == '-')
826 *c = '_';
827 if (PyDict_SetItemString(overridden_signals,
828 signal_name_canon, key)) {
829 g_free(signal_name_canon);
830 ret = FALSE;
831 break;
833 g_free(signal_name_canon);
835 ret = override_signal(instance_type, signal_name);
836 } else {
837 ret = create_signal(instance_type, signal_name, value);
840 if (!ret)
841 break;
843 if (ret)
844 return overridden_signals;
845 else {
846 Py_XDECREF(overridden_signals);
847 return NULL;
851 static void
852 pyg_object_get_property (GObject *object, guint property_id,
853 GValue *value, GParamSpec *pspec)
855 PyObject *object_wrapper, *retval;
856 PyGILState_STATE state;
858 state = PyGILState_Ensure();
860 object_wrapper = g_object_get_qdata(object, pygobject_wrapper_key);
862 if (object_wrapper)
863 Py_INCREF (object_wrapper);
864 else
865 object_wrapper = pygobject_new(object);
867 if (object_wrapper == NULL) {
868 PyGILState_Release(state);
869 return;
872 retval = pygi_call_do_get_property (object_wrapper, pspec);
873 if (retval && pyg_value_from_pyobject (value, retval) < 0) {
874 PyErr_Print();
876 Py_DECREF(object_wrapper);
877 Py_XDECREF(retval);
879 PyGILState_Release(state);
882 static void
883 pyg_object_set_property (GObject *object, guint property_id,
884 const GValue *value, GParamSpec *pspec)
886 PyObject *object_wrapper, *retval;
887 PyObject *py_pspec, *py_value;
888 PyGILState_STATE state;
890 state = PyGILState_Ensure();
892 object_wrapper = g_object_get_qdata(object, pygobject_wrapper_key);
894 if (object_wrapper)
895 Py_INCREF (object_wrapper);
896 else
897 object_wrapper = pygobject_new(object);
899 if (object_wrapper == NULL) {
900 PyGILState_Release(state);
901 return;
904 py_pspec = pyg_param_spec_new(pspec);
905 py_value = pyg_value_as_pyobject (value, TRUE);
907 retval = PyObject_CallMethod(object_wrapper, "do_set_property",
908 "OO", py_pspec, py_value);
909 if (retval) {
910 Py_DECREF(retval);
911 } else {
912 PyErr_Print();
915 Py_DECREF(object_wrapper);
916 Py_DECREF(py_pspec);
917 Py_DECREF(py_value);
919 PyGILState_Release(state);
922 static void
923 pyg_object_class_init(GObjectClass *class, PyObject *py_class)
925 PyObject *gproperties, *gsignals, *overridden_signals;
926 PyObject *class_dict = ((PyTypeObject*) py_class)->tp_dict;
928 class->set_property = pyg_object_set_property;
929 class->get_property = pyg_object_get_property;
931 /* install signals */
932 /* we look this up in the instance dictionary, so we don't
933 * accidentally get a parent type's __gsignals__ attribute. */
934 gsignals = PyDict_GetItemString(class_dict, "__gsignals__");
935 if (gsignals) {
936 if (!PyDict_Check(gsignals)) {
937 PyErr_SetString(PyExc_TypeError,
938 "__gsignals__ attribute not a dict!");
939 return;
941 if (!(overridden_signals = add_signals(class, gsignals))) {
942 return;
944 if (PyDict_SetItemString(class_dict, "__gsignals__",
945 overridden_signals)) {
946 return;
948 Py_DECREF(overridden_signals);
950 PyDict_DelItemString(class_dict, "__gsignals__");
951 } else {
952 PyErr_Clear();
955 /* install properties */
956 /* we look this up in the instance dictionary, so we don't
957 * accidentally get a parent type's __gproperties__ attribute. */
958 gproperties = PyDict_GetItemString(class_dict, "__gproperties__");
959 if (gproperties) {
960 if (!PyDict_Check(gproperties)) {
961 PyErr_SetString(PyExc_TypeError,
962 "__gproperties__ attribute not a dict!");
963 return;
965 if (!add_properties(class, gproperties)) {
966 return;
968 PyDict_DelItemString(class_dict, "__gproperties__");
969 /* Borrowed reference. Py_DECREF(gproperties); */
970 } else {
971 PyErr_Clear();
975 static GPrivate pygobject_construction_wrapper;
977 static inline void
978 pygobject_init_wrapper_set(PyObject *wrapper)
980 g_private_set(&pygobject_construction_wrapper, wrapper);
983 static inline PyObject *
984 pygobject_init_wrapper_get(void)
986 return (PyObject *) g_private_get(&pygobject_construction_wrapper);
990 pygobject_constructv(PyGObject *self,
991 guint n_parameters,
992 GParameter *parameters)
994 GObject *obj;
996 g_assert (self->obj == NULL);
997 pygobject_init_wrapper_set((PyObject *) self);
998 G_GNUC_BEGIN_IGNORE_DEPRECATIONS
999 obj = g_object_newv(pyg_type_from_object((PyObject *) self),
1000 n_parameters, parameters);
1001 G_GNUC_END_IGNORE_DEPRECATIONS
1002 if (g_object_is_floating (obj))
1003 self->private_flags.flags |= PYGOBJECT_GOBJECT_WAS_FLOATING;
1004 pygobject_sink (obj);
1006 pygobject_init_wrapper_set(NULL);
1007 self->obj = obj;
1008 pygobject_register_wrapper((PyObject *) self);
1010 return 0;
1013 static void
1014 pygobject__g_instance_init(GTypeInstance *instance,
1015 gpointer g_class)
1017 GObject *object = (GObject *) instance;
1018 PyObject *wrapper, *args, *kwargs;
1020 wrapper = g_object_get_qdata(object, pygobject_wrapper_key);
1021 if (wrapper == NULL) {
1022 wrapper = pygobject_init_wrapper_get();
1023 if (wrapper && ((PyGObject *) wrapper)->obj == NULL) {
1024 ((PyGObject *) wrapper)->obj = object;
1025 pygobject_register_wrapper(wrapper);
1028 pygobject_init_wrapper_set(NULL);
1029 if (wrapper == NULL) {
1030 /* this looks like a python object created through
1031 * g_object_new -> we have no python wrapper, so create it
1032 * now */
1033 PyGILState_STATE state;
1034 state = PyGILState_Ensure();
1035 wrapper = pygobject_new_full(object,
1036 /*steal=*/ FALSE,
1037 g_class);
1039 /* float the wrapper ref here because we are going to orphan it
1040 * so we don't destroy the wrapper. The next call to pygobject_new_full
1041 * will take the ref */
1042 pygobject_ref_float ((PyGObject *) wrapper);
1043 args = PyTuple_New(0);
1044 kwargs = PyDict_New();
1045 if (Py_TYPE(wrapper)->tp_init(wrapper, args, kwargs))
1046 PyErr_Print();
1048 Py_DECREF(args);
1049 Py_DECREF(kwargs);
1050 PyGILState_Release(state);
1054 /* This implementation is bad, see bug 566571 for an example why.
1055 * Instead of scanning explicitly declared bases for interfaces, we
1056 * should automatically initialize all implemented interfaces to
1057 * prevent bugs like that one. However, this will lead to
1058 * performance degradation as each virtual method in derived classes
1059 * will round-trip through do_*() stuff, *even* if it is not
1060 * overriden. We need to teach codegen to retain parent method
1061 * instead of setting virtual to *_proxy_do_*() if corresponding
1062 * do_*() is not overriden. Ok, that was a messy explanation.
1064 static void
1065 pyg_type_add_interfaces(PyTypeObject *class, GType instance_type,
1066 PyObject *bases,
1067 GType *parent_interfaces, guint n_parent_interfaces)
1069 int i;
1071 if (!bases) {
1072 g_warning("type has no bases");
1073 return;
1076 for (i = 0; i < PyTuple_GET_SIZE(bases); ++i) {
1077 PyObject *base = PyTuple_GET_ITEM(bases, i);
1078 GType itype;
1079 const GInterfaceInfo *iinfo;
1080 GInterfaceInfo iinfo_copy;
1082 /* 'base' can also be a PyClassObject, see bug #566571. */
1083 if (!PyType_Check(base))
1084 continue;
1086 if (!PyType_IsSubtype((PyTypeObject*) base, &PyGInterface_Type))
1087 continue;
1089 itype = pyg_type_from_object(base);
1091 /* Happens for _implementations_ of an interface. */
1092 if (!G_TYPE_IS_INTERFACE(itype))
1093 continue;
1095 iinfo = pyg_lookup_interface_info(itype);
1096 if (!iinfo) {
1097 gchar *error;
1098 error = g_strdup_printf("Interface type %s "
1099 "has no Python implementation support",
1100 ((PyTypeObject *) base)->tp_name);
1101 PyErr_Warn(PyExc_RuntimeWarning, error);
1102 g_free(error);
1103 continue;
1106 iinfo_copy = *iinfo;
1107 iinfo_copy.interface_data = class;
1108 g_type_add_interface_static(instance_type, itype, &iinfo_copy);
1112 static int
1113 pyg_run_class_init(GType gtype, gpointer gclass, PyTypeObject *pyclass)
1115 GSList *list;
1116 PyGClassInitFunc class_init;
1117 GType parent_type;
1118 int rv;
1120 parent_type = g_type_parent(gtype);
1121 if (parent_type) {
1122 rv = pyg_run_class_init(parent_type, gclass, pyclass);
1123 if (rv)
1124 return rv;
1127 list = g_type_get_qdata(gtype, pygobject_class_init_key);
1128 for (; list; list = list->next) {
1129 class_init = list->data;
1130 rv = class_init(gclass, pyclass);
1131 if (rv)
1132 return rv;
1135 return 0;
1138 static char *
1139 get_type_name_for_class(PyTypeObject *class)
1141 gint i, name_serial;
1142 char name_serial_str[16];
1143 PyObject *module;
1144 char *type_name = NULL;
1146 /* make name for new GType */
1147 name_serial = 1;
1148 /* give up after 1000 tries, just in case.. */
1149 while (name_serial < 1000)
1151 g_free(type_name);
1152 g_snprintf(name_serial_str, 16, "-v%i", name_serial);
1153 module = PyObject_GetAttrString((PyObject *)class, "__module__");
1154 if (module && PYGLIB_PyUnicode_Check(module)) {
1155 type_name = g_strconcat(PYGLIB_PyUnicode_AsString(module), ".",
1156 class->tp_name,
1157 name_serial > 1 ? name_serial_str : NULL,
1158 NULL);
1159 Py_DECREF(module);
1160 } else {
1161 if (module)
1162 Py_DECREF(module);
1163 else
1164 PyErr_Clear();
1165 type_name = g_strconcat(class->tp_name,
1166 name_serial > 1 ? name_serial_str : NULL,
1167 NULL);
1169 /* convert '.' in type name to '+', which isn't banned (grumble) */
1170 for (i = 0; type_name[i] != '\0'; i++)
1171 if (type_name[i] == '.')
1172 type_name[i] = '+';
1173 if (g_type_from_name(type_name) == 0)
1174 break; /* we now have a unique name */
1175 ++name_serial;
1178 return type_name;
1181 static int
1182 pyg_type_register(PyTypeObject *class, const char *type_name)
1184 PyObject *gtype;
1185 GType parent_type, instance_type;
1186 GType *parent_interfaces;
1187 guint n_parent_interfaces;
1188 GTypeQuery query;
1189 gpointer gclass;
1190 GTypeInfo type_info = {
1191 0, /* class_size */
1193 (GBaseInitFunc) NULL,
1194 (GBaseFinalizeFunc) NULL,
1196 (GClassInitFunc) pyg_object_class_init,
1197 (GClassFinalizeFunc) NULL,
1198 NULL, /* class_data */
1200 0, /* instance_size */
1201 0, /* n_preallocs */
1202 (GInstanceInitFunc) pygobject__g_instance_init
1204 gchar *new_type_name;
1206 /* find the GType of the parent */
1207 parent_type = pyg_type_from_object((PyObject *)class);
1208 if (!parent_type)
1209 return -1;
1211 parent_interfaces = g_type_interfaces(parent_type, &n_parent_interfaces);
1213 if (type_name)
1214 /* care is taken below not to free this */
1215 new_type_name = (gchar *) type_name;
1216 else
1217 new_type_name = get_type_name_for_class(class);
1219 /* set class_data that will be passed to the class_init function. */
1220 type_info.class_data = class;
1222 /* fill in missing values of GTypeInfo struct */
1223 g_type_query(parent_type, &query);
1224 type_info.class_size = query.class_size;
1225 type_info.instance_size = query.instance_size;
1227 /* create new typecode */
1228 instance_type = g_type_register_static(parent_type, new_type_name,
1229 &type_info, 0);
1230 if (instance_type == 0) {
1231 PyErr_Format(PyExc_RuntimeError,
1232 "could not create new GType: %s (subclass of %s)",
1233 new_type_name,
1234 g_type_name(parent_type));
1236 if (type_name == NULL)
1237 g_free(new_type_name);
1239 return -1;
1242 if (type_name == NULL)
1243 g_free(new_type_name);
1245 /* store pointer to the class with the GType */
1246 Py_INCREF(class);
1247 g_type_set_qdata(instance_type, g_quark_from_string("PyGObject::class"),
1248 class);
1250 /* Mark this GType as a custom python type */
1251 g_type_set_qdata(instance_type, pygobject_custom_key,
1252 GINT_TO_POINTER (1));
1254 /* set new value of __gtype__ on class */
1255 gtype = pyg_type_wrapper_new(instance_type);
1256 PyObject_SetAttrString((PyObject *)class, "__gtype__", gtype);
1257 Py_DECREF(gtype);
1259 /* if no __doc__, set it to the auto doc descriptor */
1260 if (PyDict_GetItemString(class->tp_dict, "__doc__") == NULL) {
1261 PyDict_SetItemString(class->tp_dict, "__doc__",
1262 pyg_object_descr_doc_get());
1266 * Note, all interfaces need to be registered before the first
1267 * g_type_class_ref(), see bug #686149.
1269 * See also comment above pyg_type_add_interfaces().
1271 pyg_type_add_interfaces(class, instance_type, class->tp_bases,
1272 parent_interfaces, n_parent_interfaces);
1275 gclass = g_type_class_ref(instance_type);
1276 if (PyErr_Occurred() != NULL) {
1277 g_type_class_unref(gclass);
1278 g_free(parent_interfaces);
1279 return -1;
1282 if (pyg_run_class_init(instance_type, gclass, class)) {
1283 g_type_class_unref(gclass);
1284 g_free(parent_interfaces);
1285 return -1;
1287 g_type_class_unref(gclass);
1288 g_free(parent_interfaces);
1290 if (PyErr_Occurred() != NULL)
1291 return -1;
1292 return 0;
1295 static PyObject *
1296 _wrap_pyg_type_register(PyObject *self, PyObject *args)
1298 PyTypeObject *class;
1299 char *type_name = NULL;
1301 if (!PyArg_ParseTuple(args, "O!|z:gobject.type_register",
1302 &PyType_Type, &class, &type_name))
1303 return NULL;
1304 if (!PyType_IsSubtype(class, &PyGObject_Type)) {
1305 PyErr_SetString(PyExc_TypeError,
1306 "argument must be a GObject subclass");
1307 return NULL;
1310 /* Check if type already registered */
1311 if (pyg_type_from_object((PyObject *) class) ==
1312 pyg_type_from_object((PyObject *) class->tp_base))
1314 if (pyg_type_register(class, type_name))
1315 return NULL;
1318 Py_INCREF(class);
1319 return (PyObject *) class;
1322 static GHashTable *log_handlers = NULL;
1323 static gboolean log_handlers_disabled = FALSE;
1325 static void
1326 remove_handler(gpointer domain,
1327 gpointer handler,
1328 gpointer unused)
1330 g_log_remove_handler(domain, GPOINTER_TO_UINT(handler));
1333 static void
1334 _log_func(const gchar *log_domain,
1335 GLogLevelFlags log_level,
1336 const gchar *message,
1337 gpointer user_data)
1339 if (G_LIKELY(Py_IsInitialized()))
1341 PyGILState_STATE state;
1342 PyObject* warning = user_data;
1344 state = PyGILState_Ensure();
1345 PyErr_Warn(warning, (char *) message);
1346 PyGILState_Release(state);
1347 } else
1348 g_log_default_handler(log_domain, log_level, message, user_data);
1351 static void
1352 add_warning_redirection(const char *domain,
1353 PyObject *warning)
1355 g_return_if_fail(domain != NULL);
1356 g_return_if_fail(warning != NULL);
1358 if (!log_handlers_disabled)
1360 guint handler;
1361 gpointer old_handler;
1363 if (!log_handlers)
1364 log_handlers = g_hash_table_new_full(g_str_hash, g_str_equal, g_free, NULL);
1366 if ((old_handler = g_hash_table_lookup(log_handlers, domain)))
1367 g_log_remove_handler(domain, GPOINTER_TO_UINT(old_handler));
1369 handler = g_log_set_handler(domain, G_LOG_LEVEL_CRITICAL|G_LOG_LEVEL_WARNING,
1370 _log_func, warning);
1371 g_hash_table_insert(log_handlers, g_strdup(domain), GUINT_TO_POINTER(handler));
1375 static void
1376 disable_warning_redirections(void)
1378 log_handlers_disabled = TRUE;
1380 if (log_handlers)
1382 g_hash_table_foreach(log_handlers, remove_handler, NULL);
1383 g_hash_table_destroy(log_handlers);
1384 log_handlers = NULL;
1388 static void
1389 pygobject_register_warnings(PyObject *d)
1391 PyObject *warning;
1393 warning = PyErr_NewException("gobject.Warning", PyExc_Warning, NULL);
1394 PyDict_SetItemString(d, "Warning", warning);
1395 add_warning_redirection("GLib", warning);
1396 add_warning_redirection("GLib-GObject", warning);
1397 add_warning_redirection("GThread", warning);
1400 static PyObject *
1401 _wrap_pyg_enum_add (PyObject *self,
1402 PyObject *args,
1403 PyObject *kwargs)
1405 static char *kwlist[] = { "g_type", NULL };
1406 PyObject *py_g_type;
1407 GType g_type;
1409 if (!PyArg_ParseTupleAndKeywords (args, kwargs,
1410 "O!:enum_add",
1411 kwlist, &PyGTypeWrapper_Type, &py_g_type)) {
1412 return NULL;
1415 g_type = pyg_type_from_object (py_g_type);
1416 if (g_type == G_TYPE_INVALID) {
1417 return NULL;
1420 return flags_enum_from_gtype (g_type, pyg_enum_add);
1423 static PyObject *
1424 _wrap_pyg_enum_register_new_gtype_and_add (PyObject *self,
1425 PyObject *args,
1426 PyObject *kwargs)
1428 static char *kwlist[] = { "info", NULL };
1429 PyGIBaseInfo *py_info;
1430 GIEnumInfo *info;
1431 gint n_values;
1432 GEnumValue *g_enum_values;
1433 int i;
1434 const gchar *namespace;
1435 const gchar *type_name;
1436 gchar *full_name;
1437 GType g_type;
1439 if (!PyArg_ParseTupleAndKeywords (args, kwargs,
1440 "O:enum_add_make_new_gtype",
1441 kwlist, (PyObject *)&py_info)) {
1442 return NULL;
1445 if (!GI_IS_ENUM_INFO (py_info->info) ||
1446 g_base_info_get_type ((GIBaseInfo *) py_info->info) != GI_INFO_TYPE_ENUM) {
1447 PyErr_SetString (PyExc_TypeError, "info must be an EnumInfo with info type GI_INFO_TYPE_ENUM");
1448 return NULL;
1451 info = (GIEnumInfo *)py_info->info;
1452 n_values = g_enum_info_get_n_values (info);
1454 /* The new memory is zero filled which fulfills the registration
1455 * function requirement that the last item is zeroed out as a terminator.
1457 g_enum_values = g_new0 (GEnumValue, n_values + 1);
1459 for (i = 0; i < n_values; i++) {
1460 GIValueInfo *value_info;
1461 GEnumValue *enum_value;
1462 const gchar *name;
1463 const gchar *c_identifier;
1465 value_info = g_enum_info_get_value (info, i);
1466 name = g_base_info_get_name ((GIBaseInfo *) value_info);
1467 c_identifier = g_base_info_get_attribute ((GIBaseInfo *) value_info,
1468 "c:identifier");
1470 enum_value = &g_enum_values[i];
1471 enum_value->value_nick = g_strdup (name);
1472 enum_value->value = g_value_info_get_value (value_info);
1474 if (c_identifier == NULL) {
1475 enum_value->value_name = enum_value->value_nick;
1476 } else {
1477 enum_value->value_name = g_strdup (c_identifier);
1480 g_base_info_unref ((GIBaseInfo *) value_info);
1483 /* Obfuscate the full_name by prefixing it with "Py" to avoid conflicts
1484 * with real GTypes. See: https://bugzilla.gnome.org/show_bug.cgi?id=692515
1486 namespace = g_base_info_get_namespace ((GIBaseInfo *) info);
1487 type_name = g_base_info_get_name ((GIBaseInfo *) info);
1488 full_name = g_strconcat ("Py", namespace, type_name, NULL);
1490 /* If enum registration fails, free all the memory allocated
1491 * for the values array. This needs to leak when successful
1492 * as GObject keeps a reference to the data as specified in the docs.
1494 g_type = g_enum_register_static (full_name, g_enum_values);
1495 if (g_type == G_TYPE_INVALID) {
1496 for (i = 0; i < n_values; i++) {
1497 GEnumValue *enum_value = &g_enum_values[i];
1499 /* Only free value_name if it is different from value_nick to avoid
1500 * a double free. The pointer might have been is re-used in the case
1501 * c_identifier was NULL in the above loop.
1503 if (enum_value->value_name != enum_value->value_nick)
1504 g_free ((gchar *) enum_value->value_name);
1505 g_free ((gchar *) enum_value->value_nick);
1508 PyErr_Format (PyExc_RuntimeError, "Unable to register enum '%s'", full_name);
1510 g_free (g_enum_values);
1511 g_free (full_name);
1512 return NULL;
1515 g_free (full_name);
1516 return pyg_enum_add (NULL, type_name, NULL, g_type);
1519 static PyObject *
1520 _wrap_pyg_flags_add (PyObject *self,
1521 PyObject *args,
1522 PyObject *kwargs)
1524 static char *kwlist[] = { "g_type", NULL };
1525 PyObject *py_g_type;
1526 GType g_type;
1528 if (!PyArg_ParseTupleAndKeywords (args, kwargs,
1529 "O!:flags_add",
1530 kwlist, &PyGTypeWrapper_Type, &py_g_type)) {
1531 return NULL;
1534 g_type = pyg_type_from_object (py_g_type);
1535 if (g_type == G_TYPE_INVALID) {
1536 return NULL;
1539 return flags_enum_from_gtype (g_type, pyg_flags_add);
1542 static PyObject *
1543 _wrap_pyg_flags_register_new_gtype_and_add (PyObject *self,
1544 PyObject *args,
1545 PyObject *kwargs)
1547 static char *kwlist[] = { "info", NULL };
1548 PyGIBaseInfo *py_info;
1549 GIEnumInfo *info;
1550 gint n_values;
1551 GFlagsValue *g_flags_values;
1552 int i;
1553 const gchar *namespace;
1554 const gchar *type_name;
1555 gchar *full_name;
1556 GType g_type;
1558 if (!PyArg_ParseTupleAndKeywords (args, kwargs,
1559 "O:flags_add_make_new_gtype",
1560 kwlist, (PyObject *)&py_info)) {
1561 return NULL;
1564 if (!GI_IS_ENUM_INFO (py_info->info) ||
1565 g_base_info_get_type ((GIBaseInfo *) py_info->info) != GI_INFO_TYPE_FLAGS) {
1566 PyErr_SetString (PyExc_TypeError, "info must be an EnumInfo with info type GI_INFO_TYPE_FLAGS");
1567 return NULL;
1570 info = (GIEnumInfo *)py_info->info;
1571 n_values = g_enum_info_get_n_values (info);
1573 /* The new memory is zero filled which fulfills the registration
1574 * function requirement that the last item is zeroed out as a terminator.
1576 g_flags_values = g_new0 (GFlagsValue, n_values + 1);
1578 for (i = 0; i < n_values; i++) {
1579 GIValueInfo *value_info;
1580 GFlagsValue *flags_value;
1581 const gchar *name;
1582 const gchar *c_identifier;
1584 value_info = g_enum_info_get_value (info, i);
1585 name = g_base_info_get_name ((GIBaseInfo *) value_info);
1586 c_identifier = g_base_info_get_attribute ((GIBaseInfo *) value_info,
1587 "c:identifier");
1589 flags_value = &g_flags_values[i];
1590 flags_value->value_nick = g_strdup (name);
1591 flags_value->value = g_value_info_get_value (value_info);
1593 if (c_identifier == NULL) {
1594 flags_value->value_name = flags_value->value_nick;
1595 } else {
1596 flags_value->value_name = g_strdup (c_identifier);
1599 g_base_info_unref ((GIBaseInfo *) value_info);
1602 /* Obfuscate the full_name by prefixing it with "Py" to avoid conflicts
1603 * with real GTypes. See: https://bugzilla.gnome.org/show_bug.cgi?id=692515
1605 namespace = g_base_info_get_namespace ((GIBaseInfo *) info);
1606 type_name = g_base_info_get_name ((GIBaseInfo *) info);
1607 full_name = g_strconcat ("Py", namespace, type_name, NULL);
1609 /* If enum registration fails, free all the memory allocated
1610 * for the values array. This needs to leak when successful
1611 * as GObject keeps a reference to the data as specified in the docs.
1613 g_type = g_flags_register_static (full_name, g_flags_values);
1614 if (g_type == G_TYPE_INVALID) {
1615 for (i = 0; i < n_values; i++) {
1616 GFlagsValue *flags_value = &g_flags_values[i];
1618 /* Only free value_name if it is different from value_nick to avoid
1619 * a double free. The pointer might have been is re-used in the case
1620 * c_identifier was NULL in the above loop.
1622 if (flags_value->value_name != flags_value->value_nick)
1623 g_free ((gchar *) flags_value->value_name);
1624 g_free ((gchar *) flags_value->value_nick);
1627 PyErr_Format (PyExc_RuntimeError, "Unable to register flags '%s'", full_name);
1629 g_free (g_flags_values);
1630 g_free (full_name);
1631 return NULL;
1634 g_free (full_name);
1635 return pyg_flags_add (NULL, type_name, NULL, g_type);
1638 static void
1639 initialize_interface (GTypeInterface *iface, PyTypeObject *pytype)
1641 /* pygobject prints a warning if interface_init is NULL */
1644 static PyObject *
1645 _wrap_pyg_register_interface_info (PyObject *self, PyObject *args)
1647 PyObject *py_g_type;
1648 GType g_type;
1649 GInterfaceInfo *info;
1651 if (!PyArg_ParseTuple (args, "O!:register_interface_info",
1652 &PyGTypeWrapper_Type, &py_g_type)) {
1653 return NULL;
1656 g_type = pyg_type_from_object (py_g_type);
1657 if (!g_type_is_a (g_type, G_TYPE_INTERFACE)) {
1658 PyErr_SetString (PyExc_TypeError, "must be an interface");
1659 return NULL;
1662 info = g_new0 (GInterfaceInfo, 1);
1663 info->interface_init = (GInterfaceInitFunc) initialize_interface;
1665 pyg_register_interface_info (g_type, info);
1667 Py_RETURN_NONE;
1670 static void
1671 find_vfunc_info (GIBaseInfo *vfunc_info,
1672 GType implementor_gtype,
1673 gpointer *implementor_class_ret,
1674 gpointer *implementor_vtable_ret,
1675 GIFieldInfo **field_info_ret)
1677 GType ancestor_g_type = 0;
1678 int length, i;
1679 GIBaseInfo *ancestor_info;
1680 GIStructInfo *struct_info;
1681 gpointer implementor_class = NULL;
1682 gboolean is_interface = FALSE;
1684 ancestor_info = g_base_info_get_container (vfunc_info);
1685 is_interface = g_base_info_get_type (ancestor_info) == GI_INFO_TYPE_INTERFACE;
1687 ancestor_g_type = g_registered_type_info_get_g_type (
1688 (GIRegisteredTypeInfo *) ancestor_info);
1689 implementor_class = g_type_class_ref (implementor_gtype);
1690 if (is_interface) {
1691 GTypeInstance *implementor_iface_class;
1692 implementor_iface_class = g_type_interface_peek (implementor_class,
1693 ancestor_g_type);
1694 if (implementor_iface_class == NULL) {
1695 g_type_class_unref (implementor_class);
1696 PyErr_Format (PyExc_RuntimeError,
1697 "Couldn't find GType of implementor of interface %s. "
1698 "Forgot to set __gtype_name__?",
1699 g_type_name (ancestor_g_type));
1700 return;
1703 *implementor_vtable_ret = implementor_iface_class;
1705 struct_info = g_interface_info_get_iface_struct ( (GIInterfaceInfo*) ancestor_info);
1706 } else {
1707 struct_info = g_object_info_get_class_struct ( (GIObjectInfo*) ancestor_info);
1708 *implementor_vtable_ret = implementor_class;
1711 *implementor_class_ret = implementor_class;
1713 length = g_struct_info_get_n_fields (struct_info);
1714 for (i = 0; i < length; i++) {
1715 GIFieldInfo *field_info;
1716 GITypeInfo *type_info;
1718 field_info = g_struct_info_get_field (struct_info, i);
1720 if (strcmp (g_base_info_get_name ( (GIBaseInfo*) field_info),
1721 g_base_info_get_name ( (GIBaseInfo*) vfunc_info)) != 0) {
1722 g_base_info_unref (field_info);
1723 continue;
1726 type_info = g_field_info_get_type (field_info);
1727 if (g_type_info_get_tag (type_info) == GI_TYPE_TAG_INTERFACE) {
1728 g_base_info_unref (type_info);
1729 *field_info_ret = field_info;
1730 break;
1733 g_base_info_unref (type_info);
1734 g_base_info_unref (field_info);
1737 g_base_info_unref (struct_info);
1740 static PyObject *
1741 _wrap_pyg_hook_up_vfunc_implementation (PyObject *self, PyObject *args)
1743 PyGIBaseInfo *py_info;
1744 PyObject *py_type;
1745 PyObject *py_function;
1746 GType implementor_gtype = 0;
1747 gpointer implementor_class = NULL;
1748 gpointer implementor_vtable = NULL;
1749 GIFieldInfo *field_info = NULL;
1750 gpointer *method_ptr = NULL;
1751 PyGICClosure *closure = NULL;
1752 PyGIClosureCache *cache = NULL;
1754 if (!PyArg_ParseTuple (args, "O!O!O:hook_up_vfunc_implementation",
1755 &PyGIBaseInfo_Type, &py_info,
1756 &PyGTypeWrapper_Type, &py_type,
1757 &py_function))
1758 return NULL;
1760 implementor_gtype = pyg_type_from_object (py_type);
1761 g_assert (G_TYPE_IS_CLASSED (implementor_gtype));
1763 find_vfunc_info (py_info->info, implementor_gtype, &implementor_class, &implementor_vtable, &field_info);
1764 if (field_info != NULL) {
1765 GITypeInfo *type_info;
1766 GIBaseInfo *interface_info;
1767 GICallbackInfo *callback_info;
1768 gint offset;
1770 type_info = g_field_info_get_type (field_info);
1772 interface_info = g_type_info_get_interface (type_info);
1773 g_assert (g_base_info_get_type (interface_info) == GI_INFO_TYPE_CALLBACK);
1775 callback_info = (GICallbackInfo*) interface_info;
1776 offset = g_field_info_get_offset (field_info);
1777 method_ptr = G_STRUCT_MEMBER_P (implementor_vtable, offset);
1779 cache = pygi_closure_cache_new (callback_info);
1780 closure = _pygi_make_native_closure ( (GICallableInfo*) callback_info, cache,
1781 GI_SCOPE_TYPE_NOTIFIED, py_function, NULL);
1783 *method_ptr = closure->closure;
1785 g_base_info_unref (interface_info);
1786 g_base_info_unref (type_info);
1787 g_base_info_unref (field_info);
1789 g_type_class_unref (implementor_class);
1791 Py_RETURN_NONE;
1794 #if 0
1795 /* Not used, left around for future reference */
1796 static PyObject *
1797 _wrap_pyg_has_vfunc_implementation (PyObject *self, PyObject *args)
1799 PyGIBaseInfo *py_info;
1800 PyObject *py_type;
1801 PyObject *py_ret;
1802 gpointer implementor_class = NULL;
1803 gpointer implementor_vtable = NULL;
1804 GType implementor_gtype = 0;
1805 GIFieldInfo *field_info = NULL;
1807 if (!PyArg_ParseTuple (args, "O!O!:has_vfunc_implementation",
1808 &PyGIBaseInfo_Type, &py_info,
1809 &PyGTypeWrapper_Type, &py_type))
1810 return NULL;
1812 implementor_gtype = pyg_type_from_object (py_type);
1813 g_assert (G_TYPE_IS_CLASSED (implementor_gtype));
1815 py_ret = Py_False;
1816 find_vfunc_info (py_info->info, implementor_gtype, &implementor_class, &implementor_vtable, &field_info);
1817 if (field_info != NULL) {
1818 gpointer *method_ptr;
1819 gint offset;
1821 offset = g_field_info_get_offset (field_info);
1822 method_ptr = G_STRUCT_MEMBER_P (implementor_vtable, offset);
1823 if (*method_ptr != NULL) {
1824 py_ret = Py_True;
1827 g_base_info_unref (field_info);
1829 g_type_class_unref (implementor_class);
1831 Py_INCREF(py_ret);
1832 return py_ret;
1834 #endif
1836 static PyObject *
1837 _wrap_pyg_variant_type_from_string (PyObject *self, PyObject *args)
1839 char *type_string;
1840 PyObject *py_type;
1841 PyObject *py_variant = NULL;
1843 if (!PyArg_ParseTuple (args, "s:variant_type_from_string",
1844 &type_string)) {
1845 return NULL;
1848 py_type = _pygi_type_import_by_name ("GLib", "VariantType");
1850 py_variant = _pygi_boxed_new ( (PyTypeObject *) py_type, type_string, FALSE, 0);
1852 return py_variant;
1855 static PyObject *
1856 _wrap_pyg_source_new (PyObject *self, PyObject *args)
1858 return pyg_source_new ();
1861 #define CHUNK_SIZE 8192
1863 static PyObject*
1864 pyg_channel_read(PyObject* self, PyObject *args, PyObject *kwargs)
1866 int max_count = -1;
1867 PyObject *py_iochannel, *ret_obj = NULL;
1868 gsize total_read = 0;
1869 GError* error = NULL;
1870 GIOStatus status = G_IO_STATUS_NORMAL;
1871 GIOChannel *iochannel = NULL;
1873 if (!PyArg_ParseTuple (args, "Oi:pyg_channel_read", &py_iochannel, &max_count)) {
1874 return NULL;
1876 if (!pyg_boxed_check (py_iochannel, G_TYPE_IO_CHANNEL)) {
1877 PyErr_SetString(PyExc_TypeError, "first argument is not a GLib.IOChannel");
1878 return NULL;
1881 if (max_count == 0)
1882 return PYGLIB_PyBytes_FromString("");
1884 iochannel = pyg_boxed_get (py_iochannel, GIOChannel);
1886 while (status == G_IO_STATUS_NORMAL
1887 && (max_count == -1 || total_read < (gsize)max_count)) {
1888 gsize single_read;
1889 char* buf;
1890 gsize buf_size;
1892 if (max_count == -1)
1893 buf_size = CHUNK_SIZE;
1894 else {
1895 buf_size = max_count - total_read;
1896 if (buf_size > CHUNK_SIZE)
1897 buf_size = CHUNK_SIZE;
1900 if ( ret_obj == NULL ) {
1901 ret_obj = PYGLIB_PyBytes_FromStringAndSize((char *)NULL, buf_size);
1902 if (ret_obj == NULL)
1903 goto failure;
1905 else if (buf_size + total_read > (gsize)PYGLIB_PyBytes_Size(ret_obj)) {
1906 if (PYGLIB_PyBytes_Resize(&ret_obj, buf_size + total_read) == -1)
1907 goto failure;
1910 buf = PYGLIB_PyBytes_AsString(ret_obj) + total_read;
1912 Py_BEGIN_ALLOW_THREADS;
1913 status = g_io_channel_read_chars (iochannel, buf, buf_size, &single_read, &error);
1914 Py_END_ALLOW_THREADS;
1916 if (pygi_error_check (&error))
1917 goto failure;
1919 total_read += single_read;
1922 if ( total_read != (gsize)PYGLIB_PyBytes_Size(ret_obj) ) {
1923 if (PYGLIB_PyBytes_Resize(&ret_obj, total_read) == -1)
1924 goto failure;
1927 return ret_obj;
1929 failure:
1930 Py_XDECREF(ret_obj);
1931 return NULL;
1934 static gboolean
1935 marshal_emission_hook(GSignalInvocationHint *ihint,
1936 guint n_param_values,
1937 const GValue *param_values,
1938 gpointer user_data)
1940 PyGILState_STATE state;
1941 gboolean retval = FALSE;
1942 PyObject *func, *args;
1943 PyObject *retobj;
1944 PyObject *params;
1945 guint i;
1947 state = PyGILState_Ensure();
1949 /* construct Python tuple for the parameter values */
1950 params = PyTuple_New(n_param_values);
1952 for (i = 0; i < n_param_values; i++) {
1953 PyObject *item = pyg_value_as_pyobject(&param_values[i], FALSE);
1955 /* error condition */
1956 if (!item) {
1957 goto out;
1959 PyTuple_SetItem(params, i, item);
1962 args = (PyObject *)user_data;
1963 func = PyTuple_GetItem(args, 0);
1964 args = PySequence_Concat(params, PyTuple_GetItem(args, 1));
1965 Py_DECREF(params);
1967 /* params passed to function may have extra arguments */
1969 retobj = PyObject_CallObject(func, args);
1970 Py_DECREF(args);
1971 if (retobj == NULL) {
1972 PyErr_Print();
1975 retval = (retobj == Py_True ? TRUE : FALSE);
1976 Py_XDECREF(retobj);
1977 out:
1978 PyGILState_Release(state);
1979 return retval;
1983 * pyg_destroy_notify:
1984 * @user_data: a PyObject pointer.
1986 * A function that can be used as a GDestroyNotify callback that will
1987 * call Py_DECREF on the data.
1989 static void
1990 pyg_destroy_notify(gpointer user_data)
1992 PyObject *obj = (PyObject *)user_data;
1993 PyGILState_STATE state;
1995 state = PyGILState_Ensure();
1996 Py_DECREF(obj);
1997 PyGILState_Release(state);
2000 static PyObject *
2001 pyg_add_emission_hook(PyGObject *self, PyObject *args)
2003 PyObject *first, *callback, *extra_args, *data, *repr;
2004 gchar *name;
2005 gulong hook_id;
2006 guint sigid;
2007 Py_ssize_t len;
2008 GQuark detail = 0;
2009 GType gtype;
2010 PyObject *pygtype;
2012 len = PyTuple_Size(args);
2013 if (len < 3) {
2014 PyErr_SetString(PyExc_TypeError,
2015 "gobject.add_emission_hook requires at least 3 arguments");
2016 return NULL;
2018 first = PySequence_GetSlice(args, 0, 3);
2019 if (!PyArg_ParseTuple(first, "OsO:add_emission_hook",
2020 &pygtype, &name, &callback)) {
2021 Py_DECREF(first);
2022 return NULL;
2024 Py_DECREF(first);
2026 if ((gtype = pyg_type_from_object(pygtype)) == 0) {
2027 return NULL;
2029 if (!PyCallable_Check(callback)) {
2030 PyErr_SetString(PyExc_TypeError, "third argument must be callable");
2031 return NULL;
2034 if (!g_signal_parse_name(name, gtype, &sigid, &detail, TRUE)) {
2035 repr = PyObject_Repr((PyObject*)self);
2036 PyErr_Format(PyExc_TypeError, "%s: unknown signal name: %s",
2037 PYGLIB_PyUnicode_AsString(repr),
2038 name);
2039 Py_DECREF(repr);
2040 return NULL;
2042 extra_args = PySequence_GetSlice(args, 3, len);
2043 if (extra_args == NULL)
2044 return NULL;
2046 data = Py_BuildValue("(ON)", callback, extra_args);
2047 if (data == NULL)
2048 return NULL;
2050 hook_id = g_signal_add_emission_hook(sigid, detail,
2051 marshal_emission_hook,
2052 data,
2053 (GDestroyNotify)pyg_destroy_notify);
2055 return PyLong_FromUnsignedLong(hook_id);
2058 static PyObject *
2059 pyg_signal_new(PyObject *self, PyObject *args)
2061 gchar *signal_name;
2062 PyObject *py_type;
2063 GSignalFlags signal_flags;
2064 GType return_type;
2065 PyObject *py_return_type, *py_param_types;
2067 GType instance_type = 0;
2068 Py_ssize_t n_params, i;
2069 GType *param_types;
2071 guint signal_id;
2073 if (!PyArg_ParseTuple(args, "sOiOO:gobject.signal_new", &signal_name,
2074 &py_type, &signal_flags, &py_return_type,
2075 &py_param_types))
2076 return NULL;
2078 instance_type = pyg_type_from_object(py_type);
2079 if (!instance_type)
2080 return NULL;
2081 if (!(G_TYPE_IS_INSTANTIATABLE(instance_type) || G_TYPE_IS_INTERFACE(instance_type))) {
2082 PyErr_SetString(PyExc_TypeError,
2083 "argument 2 must be an object type or interface type");
2084 return NULL;
2087 return_type = pyg_type_from_object(py_return_type);
2088 if (!return_type)
2089 return NULL;
2091 if (!PySequence_Check(py_param_types)) {
2092 PyErr_SetString(PyExc_TypeError,
2093 "argument 5 must be a sequence of GType codes");
2094 return NULL;
2096 n_params = PySequence_Length(py_param_types);
2097 param_types = g_new(GType, n_params);
2098 for (i = 0; i < n_params; i++) {
2099 PyObject *item = PySequence_GetItem(py_param_types, i);
2101 param_types[i] = pyg_type_from_object(item);
2102 if (param_types[i] == 0) {
2103 PyErr_Clear();
2104 Py_DECREF(item);
2105 PyErr_SetString(PyExc_TypeError,
2106 "argument 5 must be a sequence of GType codes");
2107 g_free(param_types);
2108 return NULL;
2110 Py_DECREF(item);
2113 signal_id = g_signal_newv(signal_name, instance_type, signal_flags,
2114 pyg_signal_class_closure_get(),
2115 (GSignalAccumulator)0, NULL,
2116 (GSignalCMarshaller)0,
2117 return_type, n_params, param_types);
2118 g_free(param_types);
2119 if (signal_id != 0)
2120 return PYGLIB_PyLong_FromLong(signal_id);
2121 PyErr_SetString(PyExc_RuntimeError, "could not create signal");
2122 return NULL;
2125 static PyObject *
2126 pyg_object_class_list_properties (PyObject *self, PyObject *args)
2128 GParamSpec **specs;
2129 PyObject *py_itype, *list;
2130 GType itype;
2131 GObjectClass *class = NULL;
2132 gpointer iface = NULL;
2133 guint nprops;
2134 guint i;
2136 if (!PyArg_ParseTuple(args, "O:gobject.list_properties",
2137 &py_itype))
2138 return NULL;
2139 if ((itype = pyg_type_from_object(py_itype)) == 0)
2140 return NULL;
2142 if (G_TYPE_IS_INTERFACE(itype)) {
2143 iface = g_type_default_interface_ref(itype);
2144 if (!iface) {
2145 PyErr_SetString(PyExc_RuntimeError,
2146 "could not get a reference to interface type");
2147 return NULL;
2149 specs = g_object_interface_list_properties(iface, &nprops);
2150 } else if (g_type_is_a(itype, G_TYPE_OBJECT)) {
2151 class = g_type_class_ref(itype);
2152 if (!class) {
2153 PyErr_SetString(PyExc_RuntimeError,
2154 "could not get a reference to type class");
2155 return NULL;
2157 specs = g_object_class_list_properties(class, &nprops);
2158 } else {
2159 PyErr_SetString(PyExc_TypeError,
2160 "type must be derived from GObject or an interface");
2161 return NULL;
2164 list = PyTuple_New(nprops);
2165 if (list == NULL) {
2166 g_free(specs);
2167 g_type_class_unref(class);
2168 return NULL;
2170 for (i = 0; i < nprops; i++) {
2171 PyTuple_SetItem(list, i, pyg_param_spec_new(specs[i]));
2173 g_free(specs);
2174 if (class)
2175 g_type_class_unref(class);
2176 else
2177 g_type_default_interface_unref(iface);
2179 return list;
2182 static PyObject *
2183 pyg__install_metaclass(PyObject *dummy, PyTypeObject *metaclass)
2185 Py_INCREF(metaclass);
2186 PyGObject_MetaType = metaclass;
2187 Py_INCREF(metaclass);
2189 Py_TYPE(&PyGObject_Type) = metaclass;
2191 Py_INCREF(Py_None);
2192 return Py_None;
2195 static PyMethodDef _gi_functions[] = {
2196 { "enum_add", (PyCFunction) _wrap_pyg_enum_add, METH_VARARGS | METH_KEYWORDS },
2197 { "enum_register_new_gtype_and_add", (PyCFunction) _wrap_pyg_enum_register_new_gtype_and_add, METH_VARARGS | METH_KEYWORDS },
2198 { "flags_add", (PyCFunction) _wrap_pyg_flags_add, METH_VARARGS | METH_KEYWORDS },
2199 { "flags_register_new_gtype_and_add", (PyCFunction) _wrap_pyg_flags_register_new_gtype_and_add, METH_VARARGS | METH_KEYWORDS },
2201 { "register_interface_info", (PyCFunction) _wrap_pyg_register_interface_info, METH_VARARGS },
2202 { "hook_up_vfunc_implementation", (PyCFunction) _wrap_pyg_hook_up_vfunc_implementation, METH_VARARGS },
2203 { "variant_type_from_string", (PyCFunction) _wrap_pyg_variant_type_from_string, METH_VARARGS },
2204 { "source_new", (PyCFunction) _wrap_pyg_source_new, METH_NOARGS },
2205 { "source_set_callback", (PyCFunction) pyg_source_set_callback, METH_VARARGS },
2206 { "io_channel_read", (PyCFunction) pyg_channel_read, METH_VARARGS },
2207 { "require_foreign", (PyCFunction) pygi_require_foreign, METH_VARARGS | METH_KEYWORDS },
2208 { "spawn_async",
2209 (PyCFunction)pyglib_spawn_async, METH_VARARGS|METH_KEYWORDS,
2210 "spawn_async(argv, envp=None, working_directory=None,\n"
2211 " flags=0, child_setup=None, user_data=None,\n"
2212 " standard_input=None, standard_output=None,\n"
2213 " standard_error=None) -> (pid, stdin, stdout, stderr)\n"
2214 "\n"
2215 "Execute a child program asynchronously within a glib.MainLoop()\n"
2216 "See the reference manual for a complete reference.\n" },
2217 { "type_register", _wrap_pyg_type_register, METH_VARARGS },
2218 { "signal_new", pyg_signal_new, METH_VARARGS },
2219 { "list_properties",
2220 pyg_object_class_list_properties, METH_VARARGS },
2221 { "new",
2222 (PyCFunction)pyg_object_new, METH_VARARGS|METH_KEYWORDS },
2223 { "add_emission_hook",
2224 (PyCFunction)pyg_add_emission_hook, METH_VARARGS },
2225 { "_install_metaclass",
2226 (PyCFunction)pyg__install_metaclass, METH_O },
2227 { "_gvalue_get",
2228 (PyCFunction)pyg__gvalue_get, METH_O },
2229 { "_gvalue_set",
2230 (PyCFunction)pyg__gvalue_set, METH_VARARGS },
2231 { NULL, NULL, 0 }
2234 static struct PyGI_API CAPI = {
2235 pygi_register_foreign_struct,
2238 struct _PyGObject_Functions pygobject_api_functions = {
2239 pygobject_register_class,
2240 pygobject_register_wrapper,
2241 pygobject_lookup_class,
2242 pygobject_new,
2244 pyg_closure_new,
2245 pygobject_watch_closure,
2246 pyg_destroy_notify,
2248 pyg_type_from_object,
2249 pyg_type_wrapper_new,
2250 pyg_enum_get_value,
2251 pyg_flags_get_value,
2252 pyg_register_gtype_custom,
2253 pyg_value_from_pyobject,
2254 pyg_value_as_pyobject,
2256 pyg_register_interface,
2258 &PyGBoxed_Type,
2259 pyg_register_boxed,
2260 pyg_boxed_new,
2262 &PyGPointer_Type,
2263 pyg_register_pointer,
2264 pyg_pointer_new,
2266 pyg_enum_add_constants,
2267 pyg_flags_add_constants,
2269 pyg_constant_strip_prefix,
2271 pygi_error_check,
2273 _pyg_set_thread_block_funcs,
2274 (PyGThreadBlockFunc)0, /* block_threads */
2275 (PyGThreadBlockFunc)0, /* unblock_threads */
2277 &PyGParamSpec_Type,
2278 pyg_param_spec_new,
2279 pyg_param_spec_from_object,
2281 pyg_pyobj_to_unichar_conv,
2282 pyg_parse_constructor_args,
2283 pyg_param_gvalue_as_pyobject,
2284 pyg_param_gvalue_from_pyobject,
2286 &PyGEnum_Type,
2287 pyg_enum_add,
2288 pyg_enum_from_gtype,
2290 &PyGFlags_Type,
2291 pyg_flags_add,
2292 pyg_flags_from_gtype,
2294 TRUE, /* threads_enabled */
2296 pygobject_enable_threads,
2297 pygobject_gil_state_ensure,
2298 pygobject_gil_state_release,
2299 pyg_register_class_init,
2300 pyg_register_interface_info,
2302 pyg_closure_set_exception_handler,
2304 add_warning_redirection,
2305 disable_warning_redirections,
2307 NULL, /* previously type_register_custom */
2309 pygi_gerror_exception_check,
2311 pyg_option_group_new,
2312 pyg_type_from_object_strict,
2314 pygobject_new_full,
2315 &PyGObject_Type,
2317 pyg_value_from_pyobject_with_error
2320 static void
2321 pygobject_register_api(PyObject *d)
2323 PyObject *api;
2325 api = PYGLIB_CPointer_WrapPointer(&pygobject_api_functions, "gobject._PyGObject_API");
2326 PyDict_SetItemString(d, "_PyGObject_API", api);
2327 Py_DECREF(api);
2330 /* some constants */
2331 static void
2332 pygobject_register_constants(PyObject *m)
2334 /* PyFloat_ return a new ref, and add object takes the ref */
2335 PyModule_AddObject(m, "G_MINFLOAT", PyFloat_FromDouble(G_MINFLOAT));
2336 PyModule_AddObject(m, "G_MAXFLOAT", PyFloat_FromDouble(G_MAXFLOAT));
2337 PyModule_AddObject(m, "G_MINDOUBLE", PyFloat_FromDouble(G_MINDOUBLE));
2338 PyModule_AddObject(m, "G_MAXDOUBLE", PyFloat_FromDouble(G_MAXDOUBLE));
2339 PyModule_AddIntConstant(m, "G_MINSHORT", G_MINSHORT);
2340 PyModule_AddIntConstant(m, "G_MAXSHORT", G_MAXSHORT);
2341 PyModule_AddIntConstant(m, "G_MAXUSHORT", G_MAXUSHORT);
2342 PyModule_AddIntConstant(m, "G_MININT", G_MININT);
2343 PyModule_AddIntConstant(m, "G_MAXINT", G_MAXINT);
2344 PyModule_AddObject(m, "G_MAXUINT", PyLong_FromUnsignedLong(G_MAXUINT));
2345 PyModule_AddObject(m, "G_MINLONG", PyLong_FromLong(G_MINLONG));
2346 PyModule_AddObject(m, "G_MAXLONG", PyLong_FromLong(G_MAXLONG));
2347 PyModule_AddObject(m, "G_MAXULONG", PyLong_FromUnsignedLong(G_MAXULONG));
2348 PyModule_AddObject(m, "G_MAXSIZE", PyLong_FromSize_t(G_MAXSIZE));
2349 PyModule_AddObject(m, "G_MAXSSIZE", PyLong_FromSsize_t(G_MAXSSIZE));
2350 PyModule_AddObject(m, "G_MINSSIZE", PyLong_FromSsize_t(G_MINSSIZE));
2351 PyModule_AddObject(m, "G_MINOFFSET", PyLong_FromLongLong(G_MINOFFSET));
2352 PyModule_AddObject(m, "G_MAXOFFSET", PyLong_FromLongLong(G_MAXOFFSET));
2354 PyModule_AddIntConstant(m, "SIGNAL_RUN_FIRST", G_SIGNAL_RUN_FIRST);
2355 PyModule_AddIntConstant(m, "PARAM_READWRITE", G_PARAM_READWRITE);
2357 /* The rest of the types are set in __init__.py */
2358 PyModule_AddObject(m, "TYPE_INVALID", pyg_type_wrapper_new(G_TYPE_INVALID));
2359 PyModule_AddObject(m, "TYPE_GSTRING", pyg_type_wrapper_new(G_TYPE_GSTRING));
2362 static void
2363 pygobject_register_version_tuples(PyObject *d)
2365 PyObject *tuple;
2367 /* pygobject version */
2368 tuple = Py_BuildValue ("(iii)",
2369 PYGOBJECT_MAJOR_VERSION,
2370 PYGOBJECT_MINOR_VERSION,
2371 PYGOBJECT_MICRO_VERSION);
2372 PyDict_SetItemString(d, "pygobject_version", tuple);
2373 Py_DECREF (tuple);
2376 PYGLIB_MODULE_START(_gi, "_gi")
2378 PyObject *api;
2379 PyObject *module_dict = PyModule_GetDict (module);
2381 /* Always enable Python threads since we cannot predict which GI repositories
2382 * might accept Python callbacks run within non-Python threads or might trigger
2383 * toggle ref notifications.
2384 * See: https://bugzilla.gnome.org/show_bug.cgi?id=709223
2386 PyEval_InitThreads ();
2388 PyModule_AddStringConstant(module, "__package__", "gi._gi");
2390 pygi_foreign_init ();
2391 pygi_error_register_types (module);
2392 _pygi_repository_register_types (module);
2393 _pygi_info_register_types (module);
2394 _pygi_struct_register_types (module);
2395 _pygi_boxed_register_types (module);
2396 _pygi_ccallback_register_types (module);
2397 pygi_resulttuple_register_types (module);
2399 pyglib_spawn_register_types (module_dict);
2400 pyglib_option_context_register_types (module_dict);
2401 pyglib_option_group_register_types (module_dict);
2403 pygobject_register_api (module_dict);
2404 pygobject_register_constants (module);
2405 pygobject_register_version_tuples (module_dict);
2406 pygobject_register_warnings (module_dict);
2407 pygobject_type_register_types (module_dict);
2408 pygobject_object_register_types (module_dict);
2409 pygobject_interface_register_types (module_dict);
2410 pygobject_paramspec_register_types (module_dict);
2411 pygobject_boxed_register_types (module_dict);
2412 pygobject_pointer_register_types (module_dict);
2413 pygobject_enum_register_types (module_dict);
2414 pygobject_flags_register_types (module_dict);
2416 PyGIWarning = PyErr_NewException ("gi.PyGIWarning", PyExc_Warning, NULL);
2418 /* Use RuntimeWarning as the base class of PyGIDeprecationWarning
2419 * for unstable (odd minor version) and use DeprecationWarning for
2420 * stable (even minor version). This is so PyGObject deprecations
2421 * behave the same as regular Python deprecations in stable releases.
2423 #if PYGOBJECT_MINOR_VERSION % 2
2424 PyGIDeprecationWarning = PyErr_NewException("gi.PyGIDeprecationWarning",
2425 PyExc_RuntimeWarning, NULL);
2426 #else
2427 PyGIDeprecationWarning = PyErr_NewException("gi.PyGIDeprecationWarning",
2428 PyExc_DeprecationWarning, NULL);
2429 #endif
2431 /* Place holder object used to fill in "from Python" argument lists
2432 * for values not supplied by the caller but support a GI default.
2434 _PyGIDefaultArgPlaceholder = PyList_New(0);
2436 Py_INCREF (PyGIWarning);
2437 PyModule_AddObject (module, "PyGIWarning", PyGIWarning);
2439 Py_INCREF(PyGIDeprecationWarning);
2440 PyModule_AddObject(module, "PyGIDeprecationWarning", PyGIDeprecationWarning);
2442 api = PYGLIB_CPointer_WrapPointer ( (void *) &CAPI, "gi._API");
2443 if (api == NULL) {
2444 return PYGLIB_MODULE_ERROR_RETURN;
2446 PyModule_AddObject (module, "_API", api);
2448 PYGLIB_MODULE_END