1 /* -*- Mode: C; c-basic-offset: 4 -*-
2 * pygtk- Python bindings for the GTK toolkit.
3 * Copyright (C) 1998-2003 James Henstridge
5 * gobjectmodule.c: wrapper for the gobject library.
7 * This library is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
12 * This library is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with this library; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301
27 #include <gobject/gvaluecollector.h>
28 #include <girepository.h>
31 #include "pygobject-private.h"
35 #include "pyginterface.h"
36 #include "pygparamspec.h"
37 #include "pygpointer.h"
40 static GHashTable *log_handlers = NULL;
41 static gboolean log_handlers_disabled = FALSE;
43 static void pyg_flags_add_constants(PyObject *module, GType flags_type,
44 const gchar *strip_prefix);
47 /* -------------- GDK threading hooks ---------------------------- */
50 * pyg_set_thread_block_funcs:
51 * @block_threads_func: a function to block Python threads.
52 * @unblock_threads_func: a function to unblock Python threads.
54 * an interface to allow pygtk to add hooks to handle threading
55 * similar to the old PyGTK 0.6.x releases. May not work quite right
59 pyg_set_thread_block_funcs (PyGThreadBlockFunc block_threads_func,
60 PyGThreadBlockFunc unblock_threads_func)
62 g_return_if_fail(pygobject_api_functions.block_threads == NULL &&
63 pygobject_api_functions.unblock_threads == NULL);
65 pygobject_api_functions.block_threads = block_threads_func;
66 pygobject_api_functions.unblock_threads = unblock_threads_func;
67 pyglib_set_thread_block_funcs(block_threads_func,
68 unblock_threads_func);
73 * @user_data: a PyObject pointer.
75 * A function that can be used as a GDestroyNotify callback that will
76 * call Py_DECREF on the data.
79 pyg_destroy_notify(gpointer user_data)
81 PyObject *obj = (PyObject *)user_data;
82 PyGILState_STATE state;
84 state = pyglib_gil_state_ensure();
86 pyglib_gil_state_release(state);
90 /* ---------------- gobject module functions -------------------- */
93 pyg_type_name (PyObject *self, PyObject *args)
100 if (PyErr_Warn(PyExc_DeprecationWarning,
101 "gobject.type_name is deprecated; "
102 "use GType.name instead"))
106 if (!PyArg_ParseTuple(args, "O:gobject.type_name", >ype))
108 if ((type = pyg_type_from_object(gtype)) == 0)
110 name = g_type_name(type);
112 return PYGLIB_PyUnicode_FromString(name);
113 PyErr_SetString(PyExc_RuntimeError, "unknown typecode");
118 pyg_type_from_name (PyObject *self, PyObject *args)
122 PyObject *repr = NULL;
124 if (PyErr_Warn(PyExc_DeprecationWarning,
125 "gobject.type_from_name is deprecated; "
126 "use GType.from_name instead"))
129 if (!PyArg_ParseTuple(args, "s:gobject.type_from_name", &name))
131 type = _pyg_type_from_name(name);
133 return pyg_type_wrapper_new(type);
134 repr = PyObject_Repr((PyObject*)self);
135 PyErr_Format(PyExc_RuntimeError, "%s: unknown type name: %s",
136 PYGLIB_PyUnicode_AsString(repr),
143 pyg_type_is_a (PyObject *self, PyObject *args)
145 PyObject *gtype, *gparent;
148 if (PyErr_Warn(PyExc_DeprecationWarning,
149 "gobject.type_is_a is deprecated; "
150 "use GType.is_a instead"))
153 if (!PyArg_ParseTuple(args, "OO:gobject.type_is_a", >ype, &gparent))
155 if ((type = pyg_type_from_object(gtype)) == 0)
157 if ((parent = pyg_type_from_object(gparent)) == 0)
159 return PyBool_FromLong(g_type_is_a(type, parent));
163 pyg_object_set_property (GObject *object, guint property_id,
164 const GValue *value, GParamSpec *pspec)
166 PyObject *object_wrapper, *retval;
167 PyObject *py_pspec, *py_value;
168 PyGILState_STATE state;
170 state = pyglib_gil_state_ensure();
172 object_wrapper = pygobject_new(object);
174 if (object_wrapper == NULL) {
175 pyglib_gil_state_release(state);
179 py_pspec = pyg_param_spec_new(pspec);
180 py_value = pyg_value_as_pyobject (value, TRUE);
182 retval = PyObject_CallMethod(object_wrapper, "do_set_property",
183 "OO", py_pspec, py_value);
190 Py_DECREF(object_wrapper);
194 pyglib_gil_state_release(state);
198 pyg_object_get_property (GObject *object, guint property_id,
199 GValue *value, GParamSpec *pspec)
201 PyObject *object_wrapper, *retval;
203 PyGILState_STATE state;
205 state = pyglib_gil_state_ensure();
207 object_wrapper = pygobject_new(object);
209 if (object_wrapper == NULL) {
210 pyglib_gil_state_release(state);
214 py_pspec = pyg_param_spec_new(pspec);
215 retval = PyObject_CallMethod(object_wrapper, "do_get_property",
217 if (retval == NULL || pyg_value_from_pyobject(value, retval) < 0) {
220 Py_DECREF(object_wrapper);
224 pyglib_gil_state_release(state);
227 typedef struct _PyGSignalAccumulatorData {
230 } PyGSignalAccumulatorData;
233 _pyg_signal_accumulator(GSignalInvocationHint *ihint,
235 const GValue *handler_return,
238 PyObject *py_ihint, *py_return_accu, *py_handler_return, *py_detail;
240 gboolean retval = FALSE;
241 PyGSignalAccumulatorData *data = _data;
242 PyGILState_STATE state;
244 state = pyglib_gil_state_ensure();
246 py_detail = PYGLIB_PyUnicode_FromString(g_quark_to_string(ihint->detail));
252 py_ihint = Py_BuildValue("lNi", (long int) ihint->signal_id,
253 py_detail, ihint->run_type);
254 py_handler_return = pyg_value_as_pyobject(handler_return, TRUE);
255 py_return_accu = pyg_value_as_pyobject(return_accu, FALSE);
257 py_retval = PyObject_CallFunction(data->callable, "NNNO", py_ihint,
258 py_return_accu, py_handler_return,
261 py_retval = PyObject_CallFunction(data->callable, "NNN", py_ihint,
262 py_return_accu, py_handler_return);
266 if (!PyTuple_Check(py_retval) || PyTuple_Size(py_retval) != 2) {
267 PyErr_SetString(PyExc_TypeError, "accumulator function must return"
268 " a (bool, object) tuple");
271 retval = PyObject_IsTrue(PyTuple_GET_ITEM(py_retval, 0));
272 if (pyg_value_from_pyobject(return_accu, PyTuple_GET_ITEM(py_retval, 1))) {
276 Py_DECREF(py_retval);
278 pyglib_gil_state_release(state);
283 create_signal (GType instance_type, const gchar *signal_name, PyObject *tuple)
285 GSignalFlags signal_flags;
286 PyObject *py_return_type, *py_param_types;
291 GSignalAccumulator accumulator = NULL;
292 PyGSignalAccumulatorData *accum_data = NULL;
293 PyObject *py_accum = NULL, *py_accum_data = NULL;
295 if (!PyArg_ParseTuple(tuple, "iOO|OO", &signal_flags, &py_return_type,
296 &py_param_types, &py_accum, &py_accum_data))
301 g_snprintf(buf, sizeof(buf),
302 "value for __gsignals__['%s'] not in correct format", signal_name);
303 PyErr_SetString(PyExc_TypeError, buf);
307 if (py_accum && py_accum != Py_None && !PyCallable_Check(py_accum))
311 g_snprintf(buf, sizeof(buf),
312 "accumulator for __gsignals__['%s'] must be callable", signal_name);
313 PyErr_SetString(PyExc_TypeError, buf);
317 return_type = pyg_type_from_object(py_return_type);
320 if (!PySequence_Check(py_param_types)) {
323 g_snprintf(buf, sizeof(buf),
324 "third element of __gsignals__['%s'] tuple must be a sequence", signal_name);
325 PyErr_SetString(PyExc_TypeError, buf);
328 n_params = PySequence_Length(py_param_types);
329 param_types = g_new(GType, n_params);
330 for (i = 0; i < n_params; i++) {
331 PyObject *item = PySequence_GetItem(py_param_types, i);
333 param_types[i] = pyg_type_from_object(item);
334 if (param_types[i] == 0) {
342 if (py_accum != NULL && py_accum != Py_None) {
343 accum_data = g_new(PyGSignalAccumulatorData, 1);
344 accum_data->callable = py_accum;
346 accum_data->user_data = py_accum_data;
347 Py_XINCREF(py_accum_data);
348 accumulator = _pyg_signal_accumulator;
351 signal_id = g_signal_newv(signal_name, instance_type, signal_flags,
352 pyg_signal_class_closure_get(),
353 accumulator, accum_data,
354 gi_cclosure_marshal_generic,
355 return_type, n_params, param_types);
358 if (signal_id == 0) {
361 g_snprintf(buf, sizeof(buf), "could not create signal for %s",
363 PyErr_SetString(PyExc_RuntimeError, buf);
370 override_signal(GType instance_type, const gchar *signal_name)
374 signal_id = g_signal_lookup(signal_name, instance_type);
378 g_snprintf(buf, sizeof(buf), "could not look up %s", signal_name);
379 PyErr_SetString(PyExc_TypeError, buf);
382 g_signal_override_class_closure(signal_id, instance_type,
383 pyg_signal_class_closure_get());
388 add_signals (GObjectClass *klass, PyObject *signals)
392 PyObject *key, *value, *overridden_signals = NULL;
393 GType instance_type = G_OBJECT_CLASS_TYPE (klass);
395 overridden_signals = PyDict_New();
396 while (PyDict_Next(signals, &pos, &key, &value)) {
397 const gchar *signal_name;
398 gchar *signal_name_canon, *c;
400 if (!PYGLIB_PyUnicode_Check(key)) {
401 PyErr_SetString(PyExc_TypeError,
402 "__gsignals__ keys must be strings");
406 signal_name = PYGLIB_PyUnicode_AsString (key);
408 if (value == Py_None ||
409 (PYGLIB_PyUnicode_Check(value) &&
410 !strcmp(PYGLIB_PyUnicode_AsString(value), "override")))
412 /* canonicalize signal name, replacing '-' with '_' */
413 signal_name_canon = g_strdup(signal_name);
414 for (c = signal_name_canon; *c; ++c)
417 if (PyDict_SetItemString(overridden_signals,
418 signal_name_canon, key)) {
419 g_free(signal_name_canon);
423 g_free(signal_name_canon);
425 ret = override_signal(instance_type, signal_name);
427 ret = create_signal(instance_type, signal_name, value);
434 return overridden_signals;
436 Py_XDECREF(overridden_signals);
442 create_property (const gchar *prop_name,
449 GParamSpec *pspec = NULL;
451 switch (G_TYPE_FUNDAMENTAL(prop_type)) {
454 gchar minimum, maximum, default_value;
456 if (!PyArg_ParseTuple(args, "ccc", &minimum, &maximum,
459 pspec = g_param_spec_char (prop_name, nick, blurb, minimum,
460 maximum, default_value, flags);
465 gchar minimum, maximum, default_value;
467 if (!PyArg_ParseTuple(args, "ccc", &minimum, &maximum,
470 pspec = g_param_spec_uchar (prop_name, nick, blurb, minimum,
471 maximum, default_value, flags);
476 gboolean default_value;
478 if (!PyArg_ParseTuple(args, "i", &default_value))
480 pspec = g_param_spec_boolean (prop_name, nick, blurb,
481 default_value, flags);
486 gint minimum, maximum, default_value;
488 if (!PyArg_ParseTuple(args, "iii", &minimum, &maximum,
491 pspec = g_param_spec_int (prop_name, nick, blurb, minimum,
492 maximum, default_value, flags);
497 guint minimum, maximum, default_value;
499 if (!PyArg_ParseTuple(args, "III", &minimum, &maximum,
502 pspec = g_param_spec_uint (prop_name, nick, blurb, minimum,
503 maximum, default_value, flags);
508 glong minimum, maximum, default_value;
510 if (!PyArg_ParseTuple(args, "lll", &minimum, &maximum,
513 pspec = g_param_spec_long (prop_name, nick, blurb, minimum,
514 maximum, default_value, flags);
519 gulong minimum, maximum, default_value;
521 if (!PyArg_ParseTuple(args, "kkk", &minimum, &maximum,
524 pspec = g_param_spec_ulong (prop_name, nick, blurb, minimum,
525 maximum, default_value, flags);
530 gint64 minimum, maximum, default_value;
532 if (!PyArg_ParseTuple(args, "LLL", &minimum, &maximum,
535 pspec = g_param_spec_int64 (prop_name, nick, blurb, minimum,
536 maximum, default_value, flags);
541 guint64 minimum, maximum, default_value;
543 if (!PyArg_ParseTuple(args, "KKK", &minimum, &maximum,
546 pspec = g_param_spec_uint64 (prop_name, nick, blurb, minimum,
547 maximum, default_value, flags);
555 if (!PyArg_ParseTuple(args, "O", &pydefault))
558 if (pyg_enum_get_value(prop_type, pydefault,
559 (gint *)&default_value))
562 pspec = g_param_spec_enum (prop_name, nick, blurb,
563 prop_type, default_value, flags);
571 if (!PyArg_ParseTuple(args, "O", &pydefault))
574 if (pyg_flags_get_value(prop_type, pydefault,
578 pspec = g_param_spec_flags (prop_name, nick, blurb,
579 prop_type, default_value, flags);
584 gfloat minimum, maximum, default_value;
586 if (!PyArg_ParseTuple(args, "fff", &minimum, &maximum,
589 pspec = g_param_spec_float (prop_name, nick, blurb, minimum,
590 maximum, default_value, flags);
595 gdouble minimum, maximum, default_value;
597 if (!PyArg_ParseTuple(args, "ddd", &minimum, &maximum,
600 pspec = g_param_spec_double (prop_name, nick, blurb, minimum,
601 maximum, default_value, flags);
606 const gchar *default_value;
608 if (!PyArg_ParseTuple(args, "z", &default_value))
610 pspec = g_param_spec_string (prop_name, nick, blurb,
611 default_value, flags);
615 if (!PyArg_ParseTuple(args, ""))
617 pspec = g_param_spec_param (prop_name, nick, blurb, prop_type, flags);
620 if (!PyArg_ParseTuple(args, ""))
622 pspec = g_param_spec_boxed (prop_name, nick, blurb, prop_type, flags);
625 if (!PyArg_ParseTuple(args, ""))
627 if (prop_type == G_TYPE_GTYPE)
628 pspec = g_param_spec_gtype (prop_name, nick, blurb, G_TYPE_NONE, flags);
630 pspec = g_param_spec_pointer (prop_name, nick, blurb, flags);
633 if (!PyArg_ParseTuple(args, ""))
635 pspec = g_param_spec_object (prop_name, nick, blurb, prop_type, flags);
640 GVariant *default_value = NULL;
642 if (!PyArg_ParseTuple(args, "O", &pydefault))
644 if (pydefault != Py_None)
645 default_value = pyg_boxed_get (pydefault, GVariant);
646 pspec = g_param_spec_variant (prop_name, nick, blurb, G_VARIANT_TYPE_ANY, default_value, flags);
650 /* unhandled pspec type ... */
657 g_snprintf(buf, sizeof(buf), "could not create param spec for type %s",
658 g_type_name(prop_type));
659 PyErr_SetString(PyExc_TypeError, buf);
667 pyg_param_spec_from_object (PyObject *tuple)
670 const gchar *prop_name;
672 const gchar *nick, *blurb;
673 PyObject *slice, *item, *py_prop_type;
676 val_length = PyTuple_Size(tuple);
677 if (val_length < 4) {
678 PyErr_SetString(PyExc_TypeError,
679 "paramspec tuples must be at least 4 elements long");
683 slice = PySequence_GetSlice(tuple, 0, 4);
688 if (!PyArg_ParseTuple(slice, "sOzz", &prop_name, &py_prop_type, &nick, &blurb)) {
695 prop_type = pyg_type_from_object(py_prop_type);
700 item = PyTuple_GetItem(tuple, val_length-1);
701 if (!PYGLIB_PyLong_Check(item)) {
702 PyErr_SetString(PyExc_TypeError,
703 "last element in tuple must be an int");
707 /* slice is the extra items in the tuple */
708 slice = PySequence_GetSlice(tuple, 4, val_length-1);
709 pspec = create_property(prop_name, prop_type,
711 PYGLIB_PyLong_AsLong(item));
717 add_properties (GObjectClass *klass, PyObject *properties)
721 PyObject *key, *value;
723 while (PyDict_Next(properties, &pos, &key, &value)) {
724 const gchar *prop_name;
726 const gchar *nick, *blurb;
729 PyObject *slice, *item, *py_prop_type;
732 /* values are of format (type,nick,blurb, type_specific_args, flags) */
734 if (!PYGLIB_PyUnicode_Check(key)) {
735 PyErr_SetString(PyExc_TypeError,
736 "__gproperties__ keys must be strings");
740 prop_name = PYGLIB_PyUnicode_AsString (key);
742 if (!PyTuple_Check(value)) {
743 PyErr_SetString(PyExc_TypeError,
744 "__gproperties__ values must be tuples");
748 val_length = PyTuple_Size(value);
749 if (val_length < 4) {
750 PyErr_SetString(PyExc_TypeError,
751 "__gproperties__ values must be at least 4 elements long");
756 slice = PySequence_GetSlice(value, 0, 3);
761 if (!PyArg_ParseTuple(slice, "Ozz", &py_prop_type, &nick, &blurb)) {
767 prop_type = pyg_type_from_object(py_prop_type);
772 item = PyTuple_GetItem(value, val_length-1);
773 if (!PYGLIB_PyLong_Check(item)) {
774 PyErr_SetString(PyExc_TypeError,
775 "last element in __gproperties__ value tuple must be an int");
779 flags = PYGLIB_PyLong_AsLong(item);
781 /* slice is the extra items in the tuple */
782 slice = PySequence_GetSlice(value, 3, val_length-1);
783 pspec = create_property(prop_name, prop_type, nick, blurb,
788 g_object_class_install_property(klass, 1, pspec);
790 PyObject *type, *value, *traceback;
792 PyErr_Fetch(&type, &value, &traceback);
793 if (PYGLIB_PyUnicode_Check(value)) {
796 "%s (while registering property '%s' for GType '%s')",
797 PYGLIB_PyUnicode_AsString(value),
798 prop_name, G_OBJECT_CLASS_NAME(klass));
800 value = PYGLIB_PyUnicode_FromString(msg);
802 PyErr_Restore(type, value, traceback);
811 pyg_object_class_init(GObjectClass *class, PyObject *py_class)
813 PyObject *gproperties, *gsignals, *overridden_signals;
814 PyObject *class_dict = ((PyTypeObject*) py_class)->tp_dict;
816 class->set_property = pyg_object_set_property;
817 class->get_property = pyg_object_get_property;
819 /* install signals */
820 /* we look this up in the instance dictionary, so we don't
821 * accidentally get a parent type's __gsignals__ attribute. */
822 gsignals = PyDict_GetItemString(class_dict, "__gsignals__");
824 if (!PyDict_Check(gsignals)) {
825 PyErr_SetString(PyExc_TypeError,
826 "__gsignals__ attribute not a dict!");
829 if (!(overridden_signals = add_signals(class, gsignals))) {
832 if (PyDict_SetItemString(class_dict, "__gsignals__",
833 overridden_signals)) {
836 Py_DECREF(overridden_signals);
838 PyDict_DelItemString(class_dict, "__gsignals__");
843 /* install properties */
844 /* we look this up in the instance dictionary, so we don't
845 * accidentally get a parent type's __gproperties__ attribute. */
846 gproperties = PyDict_GetItemString(class_dict, "__gproperties__");
848 if (!PyDict_Check(gproperties)) {
849 PyErr_SetString(PyExc_TypeError,
850 "__gproperties__ attribute not a dict!");
853 if (!add_properties(class, gproperties)) {
856 PyDict_DelItemString(class_dict, "__gproperties__");
857 /* Borrowed reference. Py_DECREF(gproperties); */
864 pyg_register_class_init(GType gtype, PyGClassInitFunc class_init)
868 list = g_type_get_qdata(gtype, pygobject_class_init_key);
869 list = g_slist_prepend(list, class_init);
870 g_type_set_qdata(gtype, pygobject_class_init_key, list);
874 pyg_run_class_init(GType gtype, gpointer gclass, PyTypeObject *pyclass)
877 PyGClassInitFunc class_init;
881 parent_type = g_type_parent(gtype);
883 rv = pyg_run_class_init(parent_type, gclass, pyclass);
888 list = g_type_get_qdata(gtype, pygobject_class_init_key);
889 for (; list; list = list->next) {
890 class_init = list->data;
891 rv = class_init(gclass, pyclass);
900 _wrap_pyg_type_register(PyObject *self, PyObject *args)
903 char *type_name = NULL;
905 if (!PyArg_ParseTuple(args, "O!|z:gobject.type_register",
906 &PyType_Type, &class, &type_name))
908 if (!PyType_IsSubtype(class, &PyGObject_Type)) {
909 PyErr_SetString(PyExc_TypeError,
910 "argument must be a GObject subclass");
914 /* Check if type already registered */
915 if (pyg_type_from_object((PyObject *) class) ==
916 pyg_type_from_object((PyObject *) class->tp_base))
918 if (pyg_type_register(class, type_name))
923 return (PyObject *) class;
927 get_type_name_for_class(PyTypeObject *class)
930 char name_serial_str[16];
932 char *type_name = NULL;
934 /* make name for new GType */
936 /* give up after 1000 tries, just in case.. */
937 while (name_serial < 1000)
940 snprintf(name_serial_str, 16, "-v%i", name_serial);
941 module = PyObject_GetAttrString((PyObject *)class, "__module__");
942 if (module && PYGLIB_PyUnicode_Check(module)) {
943 type_name = g_strconcat(PYGLIB_PyUnicode_AsString(module), ".",
945 name_serial > 1 ? name_serial_str : NULL,
953 type_name = g_strconcat(class->tp_name,
954 name_serial > 1 ? name_serial_str : NULL,
957 /* convert '.' in type name to '+', which isn't banned (grumble) */
958 for (i = 0; type_name[i] != '\0'; i++)
959 if (type_name[i] == '.')
961 if (_pyg_type_from_name(type_name) == 0)
962 break; /* we now have a unique name */
970 static GPrivate pygobject_construction_wrapper;
973 pygobject_init_wrapper_set(PyObject *wrapper)
975 g_private_set(&pygobject_construction_wrapper, wrapper);
978 static inline PyObject *
979 pygobject_init_wrapper_get(void)
981 return (PyObject *) g_private_get(&pygobject_construction_wrapper);
985 pygobject_constructv(PyGObject *self,
987 GParameter *parameters)
989 if (self->obj == NULL) {
991 pygobject_init_wrapper_set((PyObject *) self);
992 obj = g_object_newv(pyg_type_from_object((PyObject *) self),
993 n_parameters, parameters);
995 if (g_object_is_floating (obj))
996 self->private_flags.flags |= PYGOBJECT_GOBJECT_WAS_FLOATING;
997 pygobject_sink (obj);
999 pygobject_init_wrapper_set(NULL);
1000 if (self->obj == NULL) {
1002 pygobject_register_wrapper((PyObject *) self);
1006 for (i = 0; i < n_parameters; ++i)
1007 g_object_set_property(self->obj,
1009 ¶meters[i].value);
1015 pygobject__g_instance_init(GTypeInstance *instance,
1018 GObject *object = (GObject *) instance;
1019 PyObject *wrapper, *args, *kwargs;
1021 wrapper = g_object_get_qdata(object, pygobject_wrapper_key);
1022 if (wrapper == NULL) {
1023 wrapper = pygobject_init_wrapper_get();
1024 if (wrapper && ((PyGObject *) wrapper)->obj == NULL) {
1025 ((PyGObject *) wrapper)->obj = object;
1026 pygobject_register_wrapper(wrapper);
1029 pygobject_init_wrapper_set(NULL);
1030 if (wrapper == NULL) {
1031 /* this looks like a python object created through
1032 * g_object_new -> we have no python wrapper, so create it
1034 PyGILState_STATE state;
1035 state = pyglib_gil_state_ensure();
1036 wrapper = pygobject_new_full(object,
1040 /* float the wrapper ref here because we are going to orphan it
1041 * so we don't destroy the wrapper. The next call to pygobject_new_full
1042 * will take the ref */
1043 pygobject_ref_float ((PyGObject *) wrapper);
1044 args = PyTuple_New(0);
1045 kwargs = PyDict_New();
1046 if (Py_TYPE(wrapper)->tp_init(wrapper, args, kwargs))
1051 pyglib_gil_state_release(state);
1056 /* This implementation is bad, see bug 566571 for an example why.
1057 * Instead of scanning explicitly declared bases for interfaces, we
1058 * should automatically initialize all implemented interfaces to
1059 * prevent bugs like that one. However, this will lead to
1060 * performance degradation as each virtual method in derived classes
1061 * will round-trip through do_*() stuff, *even* if it is not
1062 * overriden. We need to teach codegen to retain parent method
1063 * instead of setting virtual to *_proxy_do_*() if corresponding
1064 * do_*() is not overriden. Ok, that was a messy explanation.
1067 pyg_type_add_interfaces(PyTypeObject *class, GType instance_type,
1069 GType *parent_interfaces, guint n_parent_interfaces)
1074 g_warning("type has no bases");
1078 for (i = 0; i < PyTuple_GET_SIZE(bases); ++i) {
1079 PyObject *base = PyTuple_GET_ITEM(bases, i);
1081 const GInterfaceInfo *iinfo;
1082 GInterfaceInfo iinfo_copy;
1084 /* 'base' can also be a PyClassObject, see bug #566571. */
1085 if (!PyType_Check(base))
1088 if (!PyType_IsSubtype((PyTypeObject*) base, &PyGInterface_Type))
1091 itype = pyg_type_from_object(base);
1093 /* Happens for _implementations_ of an interface. */
1094 if (!G_TYPE_IS_INTERFACE(itype))
1097 iinfo = pyg_lookup_interface_info(itype);
1100 error = g_strdup_printf("Interface type %s "
1101 "has no Python implementation support",
1102 ((PyTypeObject *) base)->tp_name);
1103 PyErr_Warn(PyExc_RuntimeWarning, error);
1108 iinfo_copy = *iinfo;
1109 iinfo_copy.interface_data = class;
1110 g_type_add_interface_static(instance_type, itype, &iinfo_copy);
1115 pyg_type_register(PyTypeObject *class, const char *type_name)
1118 GType parent_type, instance_type;
1119 GType *parent_interfaces;
1120 guint n_parent_interfaces;
1123 GTypeInfo type_info = {
1126 (GBaseInitFunc) NULL,
1127 (GBaseFinalizeFunc) NULL,
1129 (GClassInitFunc) pyg_object_class_init,
1130 (GClassFinalizeFunc) NULL,
1131 NULL, /* class_data */
1133 0, /* instance_size */
1134 0, /* n_preallocs */
1135 (GInstanceInitFunc) pygobject__g_instance_init
1137 gchar *new_type_name;
1139 /* find the GType of the parent */
1140 parent_type = pyg_type_from_object((PyObject *)class);
1144 parent_interfaces = g_type_interfaces(parent_type, &n_parent_interfaces);
1147 /* care is taken below not to free this */
1148 new_type_name = (gchar *) type_name;
1150 new_type_name = get_type_name_for_class(class);
1152 /* set class_data that will be passed to the class_init function. */
1153 type_info.class_data = class;
1155 /* fill in missing values of GTypeInfo struct */
1156 g_type_query(parent_type, &query);
1157 type_info.class_size = query.class_size;
1158 type_info.instance_size = query.instance_size;
1160 /* create new typecode */
1161 instance_type = g_type_register_static(parent_type, new_type_name,
1163 if (instance_type == 0) {
1164 PyErr_Format(PyExc_RuntimeError,
1165 "could not create new GType: %s (subclass of %s)",
1167 g_type_name(parent_type));
1169 if (type_name == NULL)
1170 g_free(new_type_name);
1175 if (type_name == NULL)
1176 g_free(new_type_name);
1178 /* store pointer to the class with the GType */
1180 g_type_set_qdata(instance_type, g_quark_from_string("PyGObject::class"),
1183 /* set new value of __gtype__ on class */
1184 gtype = pyg_type_wrapper_new(instance_type);
1185 PyObject_SetAttrString((PyObject *)class, "__gtype__", gtype);
1188 /* if no __doc__, set it to the auto doc descriptor */
1189 if (PyDict_GetItemString(class->tp_dict, "__doc__") == NULL) {
1190 PyDict_SetItemString(class->tp_dict, "__doc__",
1191 pyg_object_descr_doc_get());
1195 * Note, all interfaces need to be registered before the first
1196 * g_type_class_ref(), see bug #686149.
1198 * See also comment above pyg_type_add_interfaces().
1200 pyg_type_add_interfaces(class, instance_type, class->tp_bases,
1201 parent_interfaces, n_parent_interfaces);
1204 gclass = g_type_class_ref(instance_type);
1205 if (PyErr_Occurred() != NULL) {
1206 g_type_class_unref(gclass);
1207 g_free(parent_interfaces);
1211 if (pyg_run_class_init(instance_type, gclass, class)) {
1212 g_type_class_unref(gclass);
1213 g_free(parent_interfaces);
1216 g_type_class_unref(gclass);
1217 g_free(parent_interfaces);
1219 if (PyErr_Occurred() != NULL)
1225 pyg_signal_new(PyObject *self, PyObject *args)
1229 GSignalFlags signal_flags;
1231 PyObject *py_return_type, *py_param_types;
1233 GType instance_type = 0;
1234 Py_ssize_t n_params, i;
1239 if (!PyArg_ParseTuple(args, "sOiOO:gobject.signal_new", &signal_name,
1240 &py_type, &signal_flags, &py_return_type,
1244 instance_type = pyg_type_from_object(py_type);
1247 if (!(G_TYPE_IS_INSTANTIATABLE(instance_type) || G_TYPE_IS_INTERFACE(instance_type))) {
1248 PyErr_SetString(PyExc_TypeError,
1249 "argument 2 must be an object type or interface type");
1253 return_type = pyg_type_from_object(py_return_type);
1257 if (!PySequence_Check(py_param_types)) {
1258 PyErr_SetString(PyExc_TypeError,
1259 "argument 5 must be a sequence of GType codes");
1262 n_params = PySequence_Length(py_param_types);
1263 param_types = g_new(GType, n_params);
1264 for (i = 0; i < n_params; i++) {
1265 PyObject *item = PySequence_GetItem(py_param_types, i);
1267 param_types[i] = pyg_type_from_object(item);
1268 if (param_types[i] == 0) {
1271 PyErr_SetString(PyExc_TypeError,
1272 "argument 5 must be a sequence of GType codes");
1273 g_free(param_types);
1279 signal_id = g_signal_newv(signal_name, instance_type, signal_flags,
1280 pyg_signal_class_closure_get(),
1281 (GSignalAccumulator)0, NULL,
1282 (GSignalCMarshaller)0,
1283 return_type, n_params, param_types);
1284 g_free(param_types);
1286 return PYGLIB_PyLong_FromLong(signal_id);
1287 PyErr_SetString(PyExc_RuntimeError, "could not create signal");
1292 pyg_signal_query (PyObject *self, PyObject *args, PyObject *kwargs)
1294 static char *kwlist1[] = { "name", "type", NULL };
1295 static char *kwlist2[] = { "signal_id", NULL };
1296 PyObject *py_query, *params_list, *py_itype;
1297 GObjectClass *class = NULL;
1303 gpointer iface = NULL;
1305 if (PyArg_ParseTupleAndKeywords(args, kwargs, "sO:gobject.signal_query",
1306 kwlist1, &signal_name, &py_itype)) {
1307 if ((itype = pyg_type_from_object(py_itype)) == 0)
1310 if (G_TYPE_IS_INSTANTIATABLE(itype)) {
1311 class = g_type_class_ref(itype);
1313 PyErr_SetString(PyExc_RuntimeError,
1314 "could not get a reference to type class");
1317 } else if (!G_TYPE_IS_INTERFACE(itype)) {
1318 PyErr_SetString(PyExc_TypeError,
1319 "type must be instantiable or an interface");
1322 iface = g_type_default_interface_ref(itype);
1324 id = g_signal_lookup(signal_name, itype);
1327 if (!PyArg_ParseTupleAndKeywords(args, kwargs,
1328 "i:gobject.signal_query",
1331 PyErr_SetString(PyExc_TypeError,
1333 " gobject.signal_query(name, type)\n"
1334 " gobject.signal_query(signal_id)");
1340 g_signal_query(id, &query);
1342 if (query.signal_id == 0) {
1347 py_query = PyTuple_New(6);
1348 if (py_query == NULL) {
1351 params_list = PyTuple_New(query.n_params);
1352 if (params_list == NULL) {
1353 Py_DECREF(py_query);
1358 PyTuple_SET_ITEM(py_query, 0, PYGLIB_PyLong_FromLong(query.signal_id));
1359 PyTuple_SET_ITEM(py_query, 1, PYGLIB_PyUnicode_FromString(query.signal_name));
1360 PyTuple_SET_ITEM(py_query, 2, pyg_type_wrapper_new(query.itype));
1361 PyTuple_SET_ITEM(py_query, 3, PYGLIB_PyLong_FromLong(query.signal_flags));
1362 PyTuple_SET_ITEM(py_query, 4, pyg_type_wrapper_new(query.return_type));
1363 for (i = 0; i < query.n_params; i++) {
1364 PyTuple_SET_ITEM(params_list, i,
1365 pyg_type_wrapper_new(query.param_types[i]));
1367 PyTuple_SET_ITEM(py_query, 5, params_list);
1371 g_type_class_unref(class);
1373 g_type_default_interface_unref(iface);
1379 pyg_object_class_list_properties (PyObject *self, PyObject *args)
1382 PyObject *py_itype, *list;
1384 GObjectClass *class = NULL;
1385 gpointer iface = NULL;
1389 if (!PyArg_ParseTuple(args, "O:gobject.list_properties",
1392 if ((itype = pyg_type_from_object(py_itype)) == 0)
1395 if (G_TYPE_IS_INTERFACE(itype)) {
1396 iface = g_type_default_interface_ref(itype);
1398 PyErr_SetString(PyExc_RuntimeError,
1399 "could not get a reference to interface type");
1402 specs = g_object_interface_list_properties(iface, &nprops);
1403 } else if (g_type_is_a(itype, G_TYPE_OBJECT)) {
1404 class = g_type_class_ref(itype);
1406 PyErr_SetString(PyExc_RuntimeError,
1407 "could not get a reference to type class");
1410 specs = g_object_class_list_properties(class, &nprops);
1412 PyErr_SetString(PyExc_TypeError,
1413 "type must be derived from GObject or an interface");
1417 list = PyTuple_New(nprops);
1420 g_type_class_unref(class);
1423 for (i = 0; i < nprops; i++) {
1424 PyTuple_SetItem(list, i, pyg_param_spec_new(specs[i]));
1428 g_type_class_unref(class);
1430 g_type_default_interface_unref(iface);
1436 pyg_object_new (PyGObject *self, PyObject *args, PyObject *kwargs)
1440 GObject *obj = NULL;
1441 GObjectClass *class;
1442 guint n_params = 0, i;
1443 GParameter *params = NULL;
1445 if (!PyArg_ParseTuple (args, "O:gobject.new", &pytype)) {
1449 if ((type = pyg_type_from_object (pytype)) == 0)
1452 if (G_TYPE_IS_ABSTRACT(type)) {
1453 PyErr_Format(PyExc_TypeError, "cannot create instance of abstract "
1454 "(non-instantiable) type `%s'", g_type_name(type));
1458 if ((class = g_type_class_ref (type)) == NULL) {
1459 PyErr_SetString(PyExc_TypeError,
1460 "could not get a reference to type class");
1464 if (!pygobject_prepare_construct_properties (class, kwargs, &n_params, ¶ms))
1467 obj = g_object_newv(type, n_params, params);
1469 PyErr_SetString (PyExc_RuntimeError, "could not create object");
1472 for (i = 0; i < n_params; i++) {
1473 g_free((gchar *) params[i].name);
1474 g_value_unset(¶ms[i].value);
1477 g_type_class_unref(class);
1480 pygobject_sink (obj);
1481 self = (PyGObject *) pygobject_new((GObject *)obj);
1482 g_object_unref(obj);
1486 return (PyObject *) self;
1490 pyg_handler_marshal(gpointer user_data)
1492 PyObject *tuple, *ret;
1494 PyGILState_STATE state;
1496 g_return_val_if_fail(user_data != NULL, FALSE);
1498 state = pyglib_gil_state_ensure();
1500 tuple = (PyObject *)user_data;
1501 ret = PyObject_CallObject(PyTuple_GetItem(tuple, 0),
1502 PyTuple_GetItem(tuple, 1));
1507 res = PyObject_IsTrue(ret);
1511 pyglib_gil_state_release(state);
1517 pygobject_gil_state_ensure (void)
1519 return pyglib_gil_state_ensure ();
1523 pygobject_gil_state_release (int flag)
1525 pyglib_gil_state_release(flag);
1529 pyg_threads_init (PyObject *unused, PyObject *args, PyObject *kwargs)
1531 if (!pyglib_enable_threads())
1538 /* Only for backwards compatibility */
1540 pygobject_enable_threads(void)
1542 if (!pyglib_enable_threads())
1548 pyg_note_threads_enabled(void)
1550 pygobject_api_functions.threads_enabled = TRUE;
1554 pyg_signal_accumulator_true_handled(PyObject *unused, PyObject *args)
1556 PyErr_SetString(PyExc_TypeError,
1557 "signal_accumulator_true_handled can only"
1558 " be used as accumulator argument when registering signals");
1563 marshal_emission_hook(GSignalInvocationHint *ihint,
1564 guint n_param_values,
1565 const GValue *param_values,
1568 PyGILState_STATE state;
1569 gboolean retval = FALSE;
1570 PyObject *func, *args;
1575 state = pyglib_gil_state_ensure();
1577 /* construct Python tuple for the parameter values */
1578 params = PyTuple_New(n_param_values);
1580 for (i = 0; i < n_param_values; i++) {
1581 PyObject *item = pyg_value_as_pyobject(¶m_values[i], FALSE);
1583 /* error condition */
1587 PyTuple_SetItem(params, i, item);
1590 args = (PyObject *)user_data;
1591 func = PyTuple_GetItem(args, 0);
1592 args = PySequence_Concat(params, PyTuple_GetItem(args, 1));
1595 /* params passed to function may have extra arguments */
1597 retobj = PyObject_CallObject(func, args);
1599 if (retobj == NULL) {
1603 retval = (retobj == Py_True ? TRUE : FALSE);
1606 pyglib_gil_state_release(state);
1611 pyg_add_emission_hook(PyGObject *self, PyObject *args)
1613 PyObject *first, *callback, *extra_args, *data, *repr;
1622 len = PyTuple_Size(args);
1624 PyErr_SetString(PyExc_TypeError,
1625 "gobject.add_emission_hook requires at least 3 arguments");
1628 first = PySequence_GetSlice(args, 0, 3);
1629 if (!PyArg_ParseTuple(first, "OsO:add_emission_hook",
1630 &pygtype, &name, &callback)) {
1636 if ((gtype = pyg_type_from_object(pygtype)) == 0) {
1639 if (!PyCallable_Check(callback)) {
1640 PyErr_SetString(PyExc_TypeError, "third argument must be callable");
1644 if (!g_signal_parse_name(name, gtype, &sigid, &detail, TRUE)) {
1645 repr = PyObject_Repr((PyObject*)self);
1646 PyErr_Format(PyExc_TypeError, "%s: unknown signal name: %s",
1647 PYGLIB_PyUnicode_AsString(repr),
1652 extra_args = PySequence_GetSlice(args, 3, len);
1653 if (extra_args == NULL)
1656 data = Py_BuildValue("(ON)", callback, extra_args);
1660 hook_id = g_signal_add_emission_hook(sigid, detail,
1661 marshal_emission_hook,
1663 (GDestroyNotify)pyg_destroy_notify);
1665 return PyLong_FromUnsignedLong(hook_id);
1669 pyg__install_metaclass(PyObject *dummy, PyTypeObject *metaclass)
1671 Py_INCREF(metaclass);
1672 PyGObject_MetaType = metaclass;
1673 Py_INCREF(metaclass);
1675 Py_TYPE(&PyGObject_Type) = metaclass;
1681 static PyMethodDef _gobject_functions[] = {
1682 { "type_name", pyg_type_name, METH_VARARGS },
1683 { "type_from_name", pyg_type_from_name, METH_VARARGS },
1684 { "type_is_a", pyg_type_is_a, METH_VARARGS },
1685 { "type_register", _wrap_pyg_type_register, METH_VARARGS },
1686 { "signal_new", pyg_signal_new, METH_VARARGS },
1688 (PyCFunction)pyg_signal_query, METH_VARARGS|METH_KEYWORDS },
1689 { "list_properties",
1690 pyg_object_class_list_properties, METH_VARARGS },
1692 (PyCFunction)pyg_object_new, METH_VARARGS|METH_KEYWORDS },
1694 (PyCFunction)pyg_threads_init, METH_VARARGS|METH_KEYWORDS },
1695 { "signal_accumulator_true_handled",
1696 (PyCFunction)pyg_signal_accumulator_true_handled, METH_VARARGS },
1697 { "add_emission_hook",
1698 (PyCFunction)pyg_add_emission_hook, METH_VARARGS },
1699 { "_install_metaclass",
1700 (PyCFunction)pyg__install_metaclass, METH_O },
1706 /* ----------------- Constant extraction ------------------------ */
1709 * pyg_constant_strip_prefix:
1710 * @name: the constant name.
1711 * @strip_prefix: the prefix to strip.
1713 * Advances the pointer @name by strlen(@strip_prefix) characters. If
1714 * the resulting name does not start with a letter or underscore, the
1715 * @name pointer will be rewound. This is to ensure that the
1716 * resulting name is a valid identifier. Hence the returned string is
1717 * a pointer into the string @name.
1719 * Returns: the stripped constant name.
1722 pyg_constant_strip_prefix(const gchar *name, const gchar *strip_prefix)
1727 prefix_len = strlen(strip_prefix);
1729 /* Check so name starts with strip_prefix, if it doesn't:
1730 * return the rest of the part which doesn't match
1732 for (i = 0; i < prefix_len; i++) {
1733 if (name[i] != strip_prefix[i] && name[i] != '_') {
1738 /* strip off prefix from value name, while keeping it a valid
1740 for (i = prefix_len; i >= 0; i--) {
1741 if (g_ascii_isalpha(name[i]) || name[i] == '_') {
1749 * pyg_enum_add_constants:
1750 * @module: a Python module
1751 * @enum_type: the GType of the enumeration.
1752 * @strip_prefix: the prefix to strip from the constant names.
1754 * Adds constants to the given Python module for each value name of
1755 * the enumeration. A prefix will be stripped from each enum name.
1758 pyg_enum_add_constants(PyObject *module, GType enum_type,
1759 const gchar *strip_prefix)
1764 if (!G_TYPE_IS_ENUM(enum_type)) {
1765 if (G_TYPE_IS_FLAGS(enum_type)) /* See bug #136204 */
1766 pyg_flags_add_constants(module, enum_type, strip_prefix);
1768 g_warning("`%s' is not an enum type", g_type_name(enum_type));
1771 g_return_if_fail (strip_prefix != NULL);
1773 eclass = G_ENUM_CLASS(g_type_class_ref(enum_type));
1775 for (i = 0; i < eclass->n_values; i++) {
1776 const gchar *name = eclass->values[i].value_name;
1777 gint value = eclass->values[i].value;
1779 PyModule_AddIntConstant(module,
1780 (char*) pyg_constant_strip_prefix(name, strip_prefix),
1784 g_type_class_unref(eclass);
1788 * pyg_flags_add_constants:
1789 * @module: a Python module
1790 * @flags_type: the GType of the flags type.
1791 * @strip_prefix: the prefix to strip from the constant names.
1793 * Adds constants to the given Python module for each value name of
1794 * the flags set. A prefix will be stripped from each flag name.
1797 pyg_flags_add_constants(PyObject *module, GType flags_type,
1798 const gchar *strip_prefix)
1800 GFlagsClass *fclass;
1803 if (!G_TYPE_IS_FLAGS(flags_type)) {
1804 if (G_TYPE_IS_ENUM(flags_type)) /* See bug #136204 */
1805 pyg_enum_add_constants(module, flags_type, strip_prefix);
1807 g_warning("`%s' is not an flags type", g_type_name(flags_type));
1810 g_return_if_fail (strip_prefix != NULL);
1812 fclass = G_FLAGS_CLASS(g_type_class_ref(flags_type));
1814 for (i = 0; i < fclass->n_values; i++) {
1815 const gchar *name = fclass->values[i].value_name;
1816 guint value = fclass->values[i].value;
1818 PyModule_AddIntConstant(module,
1819 (char*) pyg_constant_strip_prefix(name, strip_prefix),
1823 g_type_class_unref(fclass);
1828 * @error: a pointer to the GError.
1830 * Checks to see if the GError has been set. If the error has been
1831 * set, then the gobject.GError Python exception will be raised, and
1832 * the GError cleared.
1834 * Returns: True if an error was set.
1836 * Deprecated: Since 2.16, use pyglib_error_check instead.
1839 pyg_error_check(GError **error)
1842 if (PyErr_Warn(PyExc_DeprecationWarning,
1843 "pyg_error_check is deprecated, use "
1844 "pyglib_error_check instead"))
1847 return pyglib_error_check(error);
1851 * pyg_gerror_exception_check:
1852 * @error: a standard GLib GError ** output parameter
1854 * Checks to see if a GError exception has been raised, and if so
1855 * translates the python exception to a standard GLib GError. If the
1856 * raised exception is not a GError then PyErr_Print() is called.
1858 * Returns: 0 if no exception has been raised, -1 if it is a
1859 * valid gobject.GError, -2 otherwise.
1861 * Deprecated: Since 2.16, use pyglib_gerror_exception_check instead.
1864 pyg_gerror_exception_check(GError **error)
1867 if (PyErr_Warn(PyExc_DeprecationWarning,
1868 "pyg_gerror_exception_check is deprecated, use "
1869 "pyglib_gerror_exception_check instead"))
1872 return pyglib_gerror_exception_check(error);
1876 * pyg_parse_constructor_args: helper function for PyGObject constructors
1877 * @obj_type: GType of the GObject, for parameter introspection
1878 * @arg_names: %NULL-terminated array of constructor argument names
1879 * @prop_names: %NULL-terminated array of property names, with direct
1880 * correspondence to @arg_names
1881 * @params: GParameter array where parameters will be placed; length
1882 * of this array must be at least equal to the number of
1883 * arguments/properties
1884 * @nparams: output parameter to contain actual number of arguments found
1885 * @py_args: array of PyObject* containing the actual constructor arguments
1887 * Parses an array of PyObject's and creates a GParameter array
1889 * Return value: %TRUE if all is successful, otherwise %FALSE and
1890 * python exception set.
1893 pyg_parse_constructor_args(GType obj_type,
1900 guint arg_i, param_i;
1901 GObjectClass *oclass;
1903 oclass = g_type_class_ref(obj_type);
1904 g_return_val_if_fail(oclass, FALSE);
1906 for (param_i = arg_i = 0; arg_names[arg_i]; ++arg_i) {
1908 if (!py_args[arg_i])
1910 spec = g_object_class_find_property(oclass, prop_names[arg_i]);
1911 params[param_i].name = prop_names[arg_i];
1912 g_value_init(¶ms[param_i].value, spec->value_type);
1913 if (pyg_value_from_pyobject(¶ms[param_i].value, py_args[arg_i]) == -1) {
1915 PyErr_Format(PyExc_TypeError, "could not convert parameter '%s' of type '%s'",
1916 arg_names[arg_i], g_type_name(spec->value_type));
1917 g_type_class_unref(oclass);
1918 for (i = 0; i < param_i; ++i)
1919 g_value_unset(¶ms[i].value);
1924 g_type_class_unref(oclass);
1930 pyg_integer_richcompare(PyObject *v, PyObject *w, int op)
1936 case Py_EQ: t = PYGLIB_PyLong_AS_LONG(v) == PYGLIB_PyLong_AS_LONG(w); break;
1937 case Py_NE: t = PYGLIB_PyLong_AS_LONG(v) != PYGLIB_PyLong_AS_LONG(w); break;
1938 case Py_LE: t = PYGLIB_PyLong_AS_LONG(v) <= PYGLIB_PyLong_AS_LONG(w); break;
1939 case Py_GE: t = PYGLIB_PyLong_AS_LONG(v) >= PYGLIB_PyLong_AS_LONG(w); break;
1940 case Py_LT: t = PYGLIB_PyLong_AS_LONG(v) < PYGLIB_PyLong_AS_LONG(w); break;
1941 case Py_GT: t = PYGLIB_PyLong_AS_LONG(v) > PYGLIB_PyLong_AS_LONG(w); break;
1942 default: g_assert_not_reached();
1945 result = t ? Py_True : Py_False;
1951 _log_func(const gchar *log_domain,
1952 GLogLevelFlags log_level,
1953 const gchar *message,
1956 if (G_LIKELY(Py_IsInitialized()))
1958 PyGILState_STATE state;
1959 PyObject* warning = user_data;
1961 state = pyglib_gil_state_ensure();
1962 PyErr_Warn(warning, (char *) message);
1963 pyglib_gil_state_release(state);
1965 g_log_default_handler(log_domain, log_level, message, user_data);
1969 add_warning_redirection(const char *domain,
1972 g_return_if_fail(domain != NULL);
1973 g_return_if_fail(warning != NULL);
1975 if (!log_handlers_disabled)
1978 gpointer old_handler;
1981 log_handlers = g_hash_table_new_full(g_str_hash, g_str_equal, g_free, NULL);
1983 if ((old_handler = g_hash_table_lookup(log_handlers, domain)))
1984 g_log_remove_handler(domain, GPOINTER_TO_UINT(old_handler));
1986 handler = g_log_set_handler(domain, G_LOG_LEVEL_CRITICAL|G_LOG_LEVEL_WARNING,
1987 _log_func, warning);
1988 g_hash_table_insert(log_handlers, g_strdup(domain), GUINT_TO_POINTER(handler));
1993 remove_handler(gpointer domain,
1997 g_log_remove_handler(domain, GPOINTER_TO_UINT(handler));
2001 disable_warning_redirections(void)
2003 log_handlers_disabled = TRUE;
2007 g_hash_table_foreach(log_handlers, remove_handler, NULL);
2008 g_hash_table_destroy(log_handlers);
2009 log_handlers = NULL;
2013 /* ----------------- gobject module initialisation -------------- */
2015 struct _PyGObject_Functions pygobject_api_functions = {
2016 pygobject_register_class,
2017 pygobject_register_wrapper,
2018 pygobject_lookup_class,
2022 pygobject_watch_closure,
2025 pyg_type_from_object,
2026 pyg_type_wrapper_new,
2028 pyg_flags_get_value,
2029 pyg_register_gtype_custom,
2030 pyg_value_from_pyobject,
2031 pyg_value_as_pyobject,
2033 pyg_register_interface,
2040 pyg_register_pointer,
2043 pyg_enum_add_constants,
2044 pyg_flags_add_constants,
2046 pyg_constant_strip_prefix,
2050 pyg_set_thread_block_funcs,
2051 (PyGThreadBlockFunc)0, /* block_threads */
2052 (PyGThreadBlockFunc)0, /* unblock_threads */
2056 pyg_param_spec_from_object,
2058 pyg_pyobj_to_unichar_conv,
2059 pyg_parse_constructor_args,
2060 pyg_param_gvalue_as_pyobject,
2061 pyg_param_gvalue_from_pyobject,
2065 pyg_enum_from_gtype,
2069 pyg_flags_from_gtype,
2071 FALSE, /* threads_enabled */
2072 pygobject_enable_threads,
2073 pygobject_gil_state_ensure,
2074 pygobject_gil_state_release,
2075 pyg_register_class_init,
2076 pyg_register_interface_info,
2078 pyg_closure_set_exception_handler,
2080 add_warning_redirection,
2081 disable_warning_redirections,
2083 pyg_type_register_custom_callback,
2084 pyg_gerror_exception_check,
2086 pyglib_option_group_new,
2087 pyg_type_from_object_strict,
2092 /* for addon libraries ... */
2094 pygobject_register_api(PyObject *d)
2098 api = PYGLIB_CPointer_WrapPointer(&pygobject_api_functions, "gobject._PyGObject_API");
2099 PyDict_SetItemString(d, "_PyGObject_API", api);
2103 /* some constants */
2105 pygobject_register_constants(PyObject *m)
2107 /* PyFloat_ return a new ref, and add object takes the ref */
2108 PyModule_AddObject(m, "G_MINFLOAT", PyFloat_FromDouble(G_MINFLOAT));
2109 PyModule_AddObject(m, "G_MAXFLOAT", PyFloat_FromDouble(G_MAXFLOAT));
2110 PyModule_AddObject(m, "G_MINDOUBLE", PyFloat_FromDouble(G_MINDOUBLE));
2111 PyModule_AddObject(m, "G_MAXDOUBLE", PyFloat_FromDouble(G_MAXDOUBLE));
2112 PyModule_AddIntConstant(m, "G_MINSHORT", G_MINSHORT);
2113 PyModule_AddIntConstant(m, "G_MAXSHORT", G_MAXSHORT);
2114 PyModule_AddIntConstant(m, "G_MAXUSHORT", G_MAXUSHORT);
2115 PyModule_AddIntConstant(m, "G_MININT", G_MININT);
2116 PyModule_AddIntConstant(m, "G_MAXINT", G_MAXINT);
2117 PyModule_AddObject(m, "G_MAXUINT", PyLong_FromUnsignedLong(G_MAXUINT));
2118 PyModule_AddObject(m, "G_MINLONG", PyLong_FromLong(G_MINLONG));
2119 PyModule_AddObject(m, "G_MAXLONG", PyLong_FromLong(G_MAXLONG));
2120 PyModule_AddObject(m, "G_MAXULONG", PyLong_FromUnsignedLong(G_MAXULONG));
2121 PyModule_AddObject(m, "G_MAXSIZE", PyLong_FromSize_t(G_MAXSIZE));
2122 PyModule_AddObject(m, "G_MAXSSIZE", PyLong_FromSsize_t(G_MAXSSIZE));
2123 PyModule_AddObject(m, "G_MINSSIZE", PyLong_FromSsize_t(G_MINSSIZE));
2124 PyModule_AddObject(m, "G_MINOFFSET", PyLong_FromLongLong(G_MINOFFSET));
2125 PyModule_AddObject(m, "G_MAXOFFSET", PyLong_FromLongLong(G_MAXOFFSET));
2127 PyModule_AddIntConstant(m, "SIGNAL_RUN_FIRST", G_SIGNAL_RUN_FIRST);
2128 PyModule_AddIntConstant(m, "PARAM_READWRITE", G_PARAM_READWRITE);
2130 /* The rest of the types are set in __init__.py */
2131 PyModule_AddObject(m, "TYPE_INVALID", pyg_type_wrapper_new(G_TYPE_INVALID));
2132 PyModule_AddObject(m, "TYPE_GSTRING", pyg_type_wrapper_new(G_TYPE_GSTRING));
2137 pygobject_register_features(PyObject *d)
2141 features = PyDict_New();
2142 PyDict_SetItemString(features, "generic-c-marshaller", Py_True);
2143 PyDict_SetItemString(d, "features", features);
2144 Py_DECREF(features);
2148 pygobject_register_version_tuples(PyObject *d)
2152 /* pygobject version */
2153 tuple = Py_BuildValue ("(iii)",
2154 PYGOBJECT_MAJOR_VERSION,
2155 PYGOBJECT_MINOR_VERSION,
2156 PYGOBJECT_MICRO_VERSION);
2157 PyDict_SetItemString(d, "pygobject_version", tuple);
2161 pygobject_register_warnings(PyObject *d)
2165 warning = PyErr_NewException("gobject.Warning", PyExc_Warning, NULL);
2166 PyDict_SetItemString(d, "Warning", warning);
2167 add_warning_redirection("GLib", warning);
2168 add_warning_redirection("GLib-GObject", warning);
2169 add_warning_redirection("GThread", warning);
2173 PYGLIB_MODULE_START(_gobject, "_gobject")
2177 #if !defined(GLIB_VERSION_2_36)
2182 d = PyModule_GetDict(module);
2183 pygobject_register_api(d);
2184 pygobject_register_constants(module);
2185 pygobject_register_features(d);
2186 pygobject_register_version_tuples(d);
2187 pygobject_register_warnings(d);
2188 pygobject_type_register_types(d);
2189 pygobject_object_register_types(d);
2190 pygobject_interface_register_types(d);
2191 pygobject_paramspec_register_types(d);
2192 pygobject_boxed_register_types(d);
2193 pygobject_pointer_register_types(d);
2194 pygobject_enum_register_types(d);
2195 pygobject_flags_register_types(d);
2197 pygobject_api_functions.threads_enabled = pyglib_threads_enabled();
2198 _pyglib_notify_on_enabling_threads(pyg_note_threads_enabled);