Imported Upstream version 3.21.91
[platform/upstream/python-gobject.git] / gi / gobjectmodule.c
1 /* -*- Mode: C; c-basic-offset: 4 -*-
2  * pygtk- Python bindings for the GTK toolkit.
3  * Copyright (C) 1998-2003  James Henstridge
4  *
5  *   gobjectmodule.c: wrapper for the gobject library.
6  *
7  * This library is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * This library is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with this library; if not, see <http://www.gnu.org/licenses/>.
19  */
20
21 #ifdef HAVE_CONFIG_H
22 #  include <config.h>
23 #endif
24
25 #include <Python.h>
26 #include <gobject/gvaluecollector.h>
27 #include <girepository.h>
28 #include <pyglib.h>
29 #include <pythread.h>
30 #include "gobjectmodule.h"
31 #include "pygboxed.h"
32 #include "pygenum.h"
33 #include "pygflags.h"
34 #include "pyginterface.h"
35 #include "pygparamspec.h"
36 #include "pygpointer.h"
37 #include "pygtype.h"
38 #include "pygoptiongroup.h"
39 #include "pygobject-object.h"
40
41 #include "pygi-value.h"
42 #include "pygi-error.h"
43 #include "pygi-property.h"
44
45 static GHashTable *log_handlers = NULL;
46 static gboolean log_handlers_disabled = FALSE;
47
48 static void pyg_flags_add_constants(PyObject *module, GType flags_type,
49                                     const gchar *strip_prefix);
50
51 static int pyg_type_register(PyTypeObject *class, const char *type_name);
52
53 /* -------------- GDK threading hooks ---------------------------- */
54
55 /**
56  * pyg_set_thread_block_funcs:
57  * Deprecated, only available for ABI compatibility.
58  */
59 static void
60 _pyg_set_thread_block_funcs (PyGThreadBlockFunc block_threads_func,
61                              PyGThreadBlockFunc unblock_threads_func)
62 {
63     PyGILState_STATE state = pyglib_gil_state_ensure ();
64     PyErr_Warn (PyExc_DeprecationWarning,
65                 "Using pyg_set_thread_block_funcs is not longer needed. "
66                 "PyGObject always uses Py_BLOCK/UNBLOCK_THREADS.");
67     pyglib_gil_state_release (state);
68 }
69
70 /**
71  * pyg_destroy_notify:
72  * @user_data: a PyObject pointer.
73  *
74  * A function that can be used as a GDestroyNotify callback that will
75  * call Py_DECREF on the data.
76  */
77 static void
78 pyg_destroy_notify(gpointer user_data)
79 {
80     PyObject *obj = (PyObject *)user_data;
81     PyGILState_STATE state;
82
83     state = pyglib_gil_state_ensure();
84     Py_DECREF(obj);
85     pyglib_gil_state_release(state);
86 }
87
88
89 /* ---------------- gobject module functions -------------------- */
90
91 static PyObject *
92 pyg_type_name (PyObject *self, PyObject *args)
93 {
94     PyObject *gtype;
95     GType type;
96     const gchar *name;
97
98 #if 0
99     if (PyErr_Warn(PyExc_DeprecationWarning,
100                    "gobject.type_name is deprecated; "
101                    "use GType.name instead"))
102         return NULL;
103 #endif
104
105     if (!PyArg_ParseTuple(args, "O:gobject.type_name", &gtype))
106         return NULL;
107     if ((type = pyg_type_from_object(gtype)) == 0)
108         return NULL;
109     name = g_type_name(type);
110     if (name)
111         return PYGLIB_PyUnicode_FromString(name);
112     PyErr_SetString(PyExc_RuntimeError, "unknown typecode");
113     return NULL;
114 }
115
116 static PyObject *
117 pyg_type_from_name (PyObject *self, PyObject *args)
118 {
119     const gchar *name;
120     GType type;
121     PyObject *repr = NULL;
122 #if 0
123     if (PyErr_Warn(PyExc_DeprecationWarning,
124                    "gobject.type_from_name is deprecated; "
125                    "use GType.from_name instead"))
126         return NULL;
127 #endif
128     if (!PyArg_ParseTuple(args, "s:gobject.type_from_name", &name))
129         return NULL;
130     type = g_type_from_name(name);
131     if (type != 0)
132         return pyg_type_wrapper_new(type);
133     repr = PyObject_Repr((PyObject*)self);
134     PyErr_Format(PyExc_RuntimeError, "%s: unknown type name: %s",
135          PYGLIB_PyUnicode_AsString(repr),
136                  name);
137     Py_DECREF(repr);
138     return NULL;
139 }
140
141 static PyObject *
142 pyg_type_is_a (PyObject *self, PyObject *args)
143 {
144     PyObject *gtype, *gparent;
145     GType type, parent;
146 #if 0
147     if (PyErr_Warn(PyExc_DeprecationWarning,
148                    "gobject.type_is_a is deprecated; "
149                    "use GType.is_a instead"))
150         return NULL;
151 #endif
152     if (!PyArg_ParseTuple(args, "OO:gobject.type_is_a", &gtype, &gparent))
153         return NULL;
154     if ((type = pyg_type_from_object(gtype)) == 0)
155         return NULL;
156     if ((parent = pyg_type_from_object(gparent)) == 0)
157         return NULL;
158     return PyBool_FromLong(g_type_is_a(type, parent));
159 }
160
161 static void
162 pyg_object_set_property (GObject *object, guint property_id,
163                          const GValue *value, GParamSpec *pspec)
164 {
165     PyObject *object_wrapper, *retval;
166     PyObject *py_pspec, *py_value;
167     PyGILState_STATE state;
168
169     state = pyglib_gil_state_ensure();
170
171     object_wrapper = pygobject_new(object);
172
173     if (object_wrapper == NULL) {
174         pyglib_gil_state_release(state);
175         return;
176     }
177
178     py_pspec = pyg_param_spec_new(pspec);
179     py_value = pyg_value_as_pyobject (value, TRUE);
180
181     retval = PyObject_CallMethod(object_wrapper, "do_set_property",
182                                  "OO", py_pspec, py_value);
183     if (retval) {
184         Py_DECREF(retval);
185     } else {
186         PyErr_Print();
187     }
188
189     Py_DECREF(object_wrapper);
190     Py_DECREF(py_pspec);
191     Py_DECREF(py_value);
192
193     pyglib_gil_state_release(state);
194 }
195
196 static void
197 pyg_object_get_property (GObject *object, guint property_id,
198                          GValue *value, GParamSpec *pspec)
199 {
200     PyObject *object_wrapper, *retval;
201     PyGILState_STATE state;
202
203     state = pyglib_gil_state_ensure();
204
205     object_wrapper = pygobject_new(object);
206
207     if (object_wrapper == NULL) {
208         pyglib_gil_state_release(state);
209         return;
210     }
211
212     retval = pygi_call_do_get_property (object_wrapper, pspec);
213     if (retval && pyg_value_from_pyobject (value, retval) < 0) {
214         PyErr_Print();
215     }
216     Py_DECREF(object_wrapper);
217     Py_XDECREF(retval);
218
219     pyglib_gil_state_release(state);
220 }
221
222 typedef struct _PyGSignalAccumulatorData {
223     PyObject *callable;
224     PyObject *user_data;
225 } PyGSignalAccumulatorData;
226
227 static gboolean
228 _pyg_signal_accumulator(GSignalInvocationHint *ihint,
229                         GValue *return_accu,
230                         const GValue *handler_return,
231                         gpointer _data)
232 {
233     PyObject *py_ihint, *py_return_accu, *py_handler_return, *py_detail;
234     PyObject *py_retval;
235     gboolean retval = FALSE;
236     PyGSignalAccumulatorData *data = _data;
237     PyGILState_STATE state;
238
239     state = pyglib_gil_state_ensure();
240     if (ihint->detail)
241         py_detail = PYGLIB_PyUnicode_FromString(g_quark_to_string(ihint->detail));
242     else {
243         Py_INCREF(Py_None);
244         py_detail = Py_None;
245     }
246
247     py_ihint = Py_BuildValue("lNi", (long int) ihint->signal_id,
248                              py_detail, ihint->run_type);
249     py_handler_return = pyg_value_as_pyobject(handler_return, TRUE);
250     py_return_accu = pyg_value_as_pyobject(return_accu, FALSE);
251     if (data->user_data)
252         py_retval = PyObject_CallFunction(data->callable, "NNNO", py_ihint,
253                                           py_return_accu, py_handler_return,
254                                           data->user_data);
255     else
256         py_retval = PyObject_CallFunction(data->callable, "NNN", py_ihint,
257                                           py_return_accu, py_handler_return);
258     if (!py_retval)
259         PyErr_Print();
260     else {
261         if (!PyTuple_Check(py_retval) || PyTuple_Size(py_retval) != 2) {
262             PyErr_SetString(PyExc_TypeError, "accumulator function must return"
263                             " a (bool, object) tuple");
264             PyErr_Print();
265         } else {
266             retval = PyObject_IsTrue(PyTuple_GET_ITEM(py_retval, 0));
267             if (pyg_value_from_pyobject(return_accu, PyTuple_GET_ITEM(py_retval, 1))) {
268                 PyErr_Print();
269             }
270         }
271         Py_DECREF(py_retval);
272     }
273     pyglib_gil_state_release(state);
274     return retval;
275 }
276
277 static gboolean
278 create_signal (GType instance_type, const gchar *signal_name, PyObject *tuple)
279 {
280     GSignalFlags signal_flags;
281     PyObject *py_return_type, *py_param_types;
282     GType return_type;
283     guint n_params, i;
284     GType *param_types;
285     guint signal_id;
286     GSignalAccumulator accumulator = NULL;
287     PyGSignalAccumulatorData *accum_data = NULL;
288     PyObject *py_accum = NULL, *py_accum_data = NULL;
289
290     if (!PyArg_ParseTuple(tuple, "iOO|OO", &signal_flags, &py_return_type,
291                           &py_param_types, &py_accum, &py_accum_data))
292     {
293         gchar buf[128];
294
295         PyErr_Clear();
296         g_snprintf(buf, sizeof(buf),
297                    "value for __gsignals__['%s'] not in correct format", signal_name);
298         PyErr_SetString(PyExc_TypeError, buf);
299         return FALSE;
300     }
301
302     if (py_accum && py_accum != Py_None && !PyCallable_Check(py_accum))
303     {
304         gchar buf[128];
305
306         g_snprintf(buf, sizeof(buf),
307                    "accumulator for __gsignals__['%s'] must be callable", signal_name);
308         PyErr_SetString(PyExc_TypeError, buf);
309         return FALSE;
310     }
311
312     return_type = pyg_type_from_object(py_return_type);
313     if (!return_type)
314         return FALSE;
315     if (!PySequence_Check(py_param_types)) {
316         gchar buf[128];
317
318         g_snprintf(buf, sizeof(buf),
319                    "third element of __gsignals__['%s'] tuple must be a sequence", signal_name);
320         PyErr_SetString(PyExc_TypeError, buf);
321         return FALSE;
322     }
323     n_params = PySequence_Length(py_param_types);
324     param_types = g_new(GType, n_params);
325     for (i = 0; i < n_params; i++) {
326         PyObject *item = PySequence_GetItem(py_param_types, i);
327
328         param_types[i] = pyg_type_from_object(item);
329         if (param_types[i] == 0) {
330             Py_DECREF(item);
331             g_free(param_types);
332             return FALSE;
333         }
334         Py_DECREF(item);
335     }
336
337     if (py_accum != NULL && py_accum != Py_None) {
338         accum_data = g_new(PyGSignalAccumulatorData, 1);
339         accum_data->callable = py_accum;
340         Py_INCREF(py_accum);
341         accum_data->user_data = py_accum_data;
342         Py_XINCREF(py_accum_data);
343         accumulator = _pyg_signal_accumulator;
344     }
345
346     signal_id = g_signal_newv(signal_name, instance_type, signal_flags,
347                               pyg_signal_class_closure_get(),
348                               accumulator, accum_data,
349                               gi_cclosure_marshal_generic,
350                               return_type, n_params, param_types);
351     g_free(param_types);
352
353     if (signal_id == 0) {
354         gchar buf[128];
355
356         g_snprintf(buf, sizeof(buf), "could not create signal for %s",
357                    signal_name);
358         PyErr_SetString(PyExc_RuntimeError, buf);
359         return FALSE;
360     }
361     return TRUE;
362 }
363
364 static gboolean
365 override_signal(GType instance_type, const gchar *signal_name)
366 {
367     guint signal_id;
368
369     signal_id = g_signal_lookup(signal_name, instance_type);
370     if (!signal_id) {
371         gchar buf[128];
372
373         g_snprintf(buf, sizeof(buf), "could not look up %s", signal_name);
374         PyErr_SetString(PyExc_TypeError, buf);
375         return FALSE;
376     }
377     g_signal_override_class_closure(signal_id, instance_type,
378                                     pyg_signal_class_closure_get());
379     return TRUE;
380 }
381
382 static PyObject *
383 add_signals (GObjectClass *klass, PyObject *signals)
384 {
385     gboolean ret = TRUE;
386     Py_ssize_t pos = 0;
387     PyObject *key, *value, *overridden_signals = NULL;
388     GType instance_type = G_OBJECT_CLASS_TYPE (klass);
389
390     overridden_signals = PyDict_New();
391     while (PyDict_Next(signals, &pos, &key, &value)) {
392         const gchar *signal_name;
393         gchar *signal_name_canon, *c;
394
395         if (!PYGLIB_PyUnicode_Check(key)) {
396             PyErr_SetString(PyExc_TypeError,
397                             "__gsignals__ keys must be strings");
398             ret = FALSE;
399             break;
400         }
401         signal_name = PYGLIB_PyUnicode_AsString (key);
402
403         if (value == Py_None ||
404             (PYGLIB_PyUnicode_Check(value) &&
405              !strcmp(PYGLIB_PyUnicode_AsString(value), "override")))
406         {
407               /* canonicalize signal name, replacing '-' with '_' */
408             signal_name_canon = g_strdup(signal_name);
409             for (c = signal_name_canon; *c; ++c)
410                 if (*c == '-')
411                     *c = '_';
412             if (PyDict_SetItemString(overridden_signals,
413                                      signal_name_canon, key)) {
414                 g_free(signal_name_canon);
415                 ret = FALSE;
416                 break;
417             }
418             g_free(signal_name_canon);
419
420             ret = override_signal(instance_type, signal_name);
421         } else {
422             ret = create_signal(instance_type, signal_name, value);
423         }
424
425         if (!ret)
426             break;
427     }
428     if (ret)
429         return overridden_signals;
430     else {
431         Py_XDECREF(overridden_signals);
432         return NULL;
433     }
434 }
435
436 static GParamSpec *
437 create_property (const gchar  *prop_name,
438                  GType         prop_type,
439                  const gchar  *nick,
440                  const gchar  *blurb,
441                  PyObject     *args,
442                  GParamFlags   flags)
443 {
444     GParamSpec *pspec = NULL;
445
446     switch (G_TYPE_FUNDAMENTAL(prop_type)) {
447     case G_TYPE_CHAR:
448         {
449             gchar minimum, maximum, default_value;
450
451             if (!PyArg_ParseTuple(args, "ccc", &minimum, &maximum,
452                                   &default_value))
453                 return NULL;
454             pspec = g_param_spec_char (prop_name, nick, blurb, minimum,
455                                        maximum, default_value, flags);
456         }
457         break;
458     case G_TYPE_UCHAR:
459         {
460             gchar minimum, maximum, default_value;
461
462             if (!PyArg_ParseTuple(args, "ccc", &minimum, &maximum,
463                                   &default_value))
464                 return NULL;
465             pspec = g_param_spec_uchar (prop_name, nick, blurb, minimum,
466                                         maximum, default_value, flags);
467         }
468         break;
469     case G_TYPE_BOOLEAN:
470         {
471             gboolean default_value;
472
473             if (!PyArg_ParseTuple(args, "i", &default_value))
474                 return NULL;
475             pspec = g_param_spec_boolean (prop_name, nick, blurb,
476                                           default_value, flags);
477         }
478         break;
479     case G_TYPE_INT:
480         {
481             gint minimum, maximum, default_value;
482
483             if (!PyArg_ParseTuple(args, "iii", &minimum, &maximum,
484                                   &default_value))
485                 return NULL;
486             pspec = g_param_spec_int (prop_name, nick, blurb, minimum,
487                                       maximum, default_value, flags);
488         }
489         break;
490     case G_TYPE_UINT:
491         {
492             guint minimum, maximum, default_value;
493
494             if (!PyArg_ParseTuple(args, "III", &minimum, &maximum,
495                                   &default_value))
496                 return NULL;
497             pspec = g_param_spec_uint (prop_name, nick, blurb, minimum,
498                                        maximum, default_value, flags);
499         }
500         break;
501     case G_TYPE_LONG:
502         {
503             glong minimum, maximum, default_value;
504
505             if (!PyArg_ParseTuple(args, "lll", &minimum, &maximum,
506                                   &default_value))
507                 return NULL;
508             pspec = g_param_spec_long (prop_name, nick, blurb, minimum,
509                                        maximum, default_value, flags);
510         }
511         break;
512     case G_TYPE_ULONG:
513         {
514             gulong minimum, maximum, default_value;
515
516             if (!PyArg_ParseTuple(args, "kkk", &minimum, &maximum,
517                                   &default_value))
518                 return NULL;
519             pspec = g_param_spec_ulong (prop_name, nick, blurb, minimum,
520                                         maximum, default_value, flags);
521         }
522         break;
523     case G_TYPE_INT64:
524         {
525             gint64 minimum, maximum, default_value;
526
527             if (!PyArg_ParseTuple(args, "LLL", &minimum, &maximum,
528                                   &default_value))
529                 return NULL;
530             pspec = g_param_spec_int64 (prop_name, nick, blurb, minimum,
531                                         maximum, default_value, flags);
532         }
533         break;
534     case G_TYPE_UINT64:
535         {
536             guint64 minimum, maximum, default_value;
537
538             if (!PyArg_ParseTuple(args, "KKK", &minimum, &maximum,
539                                   &default_value))
540                 return NULL;
541             pspec = g_param_spec_uint64 (prop_name, nick, blurb, minimum,
542                                          maximum, default_value, flags);
543         }
544         break;
545     case G_TYPE_ENUM:
546         {
547             gint default_value;
548             PyObject *pydefault;
549
550             if (!PyArg_ParseTuple(args, "O", &pydefault))
551                 return NULL;
552
553             if (pyg_enum_get_value(prop_type, pydefault,
554                                    (gint *)&default_value))
555                 return NULL;
556
557             pspec = g_param_spec_enum (prop_name, nick, blurb,
558                                        prop_type, default_value, flags);
559         }
560         break;
561     case G_TYPE_FLAGS:
562         {
563             guint default_value;
564             PyObject *pydefault;
565
566             if (!PyArg_ParseTuple(args, "O", &pydefault))
567                 return NULL;
568
569             if (pyg_flags_get_value(prop_type, pydefault,
570                                     &default_value))
571                 return NULL;
572
573             pspec = g_param_spec_flags (prop_name, nick, blurb,
574                                         prop_type, default_value, flags);
575         }
576         break;
577     case G_TYPE_FLOAT:
578         {
579             gfloat minimum, maximum, default_value;
580
581             if (!PyArg_ParseTuple(args, "fff", &minimum, &maximum,
582                                   &default_value))
583                 return NULL;
584             pspec = g_param_spec_float (prop_name, nick, blurb, minimum,
585                                         maximum, default_value, flags);
586         }
587         break;
588     case G_TYPE_DOUBLE:
589         {
590             gdouble minimum, maximum, default_value;
591
592             if (!PyArg_ParseTuple(args, "ddd", &minimum, &maximum,
593                                   &default_value))
594                 return NULL;
595             pspec = g_param_spec_double (prop_name, nick, blurb, minimum,
596                                          maximum, default_value, flags);
597         }
598         break;
599     case G_TYPE_STRING:
600         {
601             const gchar *default_value;
602
603             if (!PyArg_ParseTuple(args, "z", &default_value))
604                 return NULL;
605             pspec = g_param_spec_string (prop_name, nick, blurb,
606                                          default_value, flags);
607         }
608         break;
609     case G_TYPE_PARAM:
610         if (!PyArg_ParseTuple(args, ""))
611             return NULL;
612         pspec = g_param_spec_param (prop_name, nick, blurb, prop_type, flags);
613         break;
614     case G_TYPE_BOXED:
615         if (!PyArg_ParseTuple(args, ""))
616             return NULL;
617         pspec = g_param_spec_boxed (prop_name, nick, blurb, prop_type, flags);
618         break;
619     case G_TYPE_POINTER:
620         if (!PyArg_ParseTuple(args, ""))
621             return NULL;
622         if (prop_type == G_TYPE_GTYPE)
623             pspec = g_param_spec_gtype (prop_name, nick, blurb, G_TYPE_NONE, flags);
624         else
625             pspec = g_param_spec_pointer (prop_name, nick, blurb, flags);
626         break;
627     case G_TYPE_OBJECT:
628     case G_TYPE_INTERFACE:
629         if (!PyArg_ParseTuple(args, ""))
630             return NULL;
631         pspec = g_param_spec_object (prop_name, nick, blurb, prop_type, flags);
632         break;
633     case G_TYPE_VARIANT:
634         {
635             PyObject *pydefault;
636             GVariant *default_value = NULL;
637
638             if (!PyArg_ParseTuple(args, "O", &pydefault))
639                 return NULL;
640             if (pydefault != Py_None)
641                 default_value = pyg_boxed_get (pydefault, GVariant);
642             pspec = g_param_spec_variant (prop_name, nick, blurb, G_VARIANT_TYPE_ANY, default_value, flags);
643         }
644         break;
645     default:
646         /* unhandled pspec type ... */
647         break;
648     }
649
650     if (!pspec) {
651         char buf[128];
652
653         g_snprintf(buf, sizeof(buf), "could not create param spec for type %s",
654                    g_type_name(prop_type));
655         PyErr_SetString(PyExc_TypeError, buf);
656         return NULL;
657     }
658
659     return pspec;
660 }
661
662 static GParamSpec *
663 pyg_param_spec_from_object (PyObject *tuple)
664 {
665     gint val_length;
666     const gchar *prop_name;
667     GType prop_type;
668     const gchar *nick, *blurb;
669     PyObject *slice, *item, *py_prop_type;
670     GParamSpec *pspec;
671
672     val_length = PyTuple_Size(tuple);
673     if (val_length < 4) {
674         PyErr_SetString(PyExc_TypeError,
675                         "paramspec tuples must be at least 4 elements long");
676         return NULL;
677     }
678
679     slice = PySequence_GetSlice(tuple, 0, 4);
680     if (!slice) {
681         return NULL;
682     }
683
684     if (!PyArg_ParseTuple(slice, "sOzz", &prop_name, &py_prop_type, &nick, &blurb)) {
685         Py_DECREF(slice);
686         return NULL;
687     }
688
689     Py_DECREF(slice);
690
691     prop_type = pyg_type_from_object(py_prop_type);
692     if (!prop_type) {
693         return NULL;
694     }
695
696     item = PyTuple_GetItem(tuple, val_length-1);
697     if (!PYGLIB_PyLong_Check(item)) {
698         PyErr_SetString(PyExc_TypeError,
699                         "last element in tuple must be an int");
700         return NULL;
701     }
702
703     /* slice is the extra items in the tuple */
704     slice = PySequence_GetSlice(tuple, 4, val_length-1);
705     pspec = create_property(prop_name, prop_type,
706                             nick, blurb, slice,
707                             PYGLIB_PyLong_AsLong(item));
708
709     return pspec;
710 }
711
712 static gboolean
713 add_properties (GObjectClass *klass, PyObject *properties)
714 {
715     gboolean ret = TRUE;
716     Py_ssize_t pos = 0;
717     PyObject *key, *value;
718
719     while (PyDict_Next(properties, &pos, &key, &value)) {
720         const gchar *prop_name;
721         GType prop_type;
722         const gchar *nick, *blurb;
723         GParamFlags flags;
724         gint val_length;
725         PyObject *slice, *item, *py_prop_type;
726         GParamSpec *pspec;
727
728         /* values are of format (type,nick,blurb, type_specific_args, flags) */
729
730         if (!PYGLIB_PyUnicode_Check(key)) {
731             PyErr_SetString(PyExc_TypeError,
732                             "__gproperties__ keys must be strings");
733             ret = FALSE;
734             break;
735         }
736         prop_name = PYGLIB_PyUnicode_AsString (key);
737
738         if (!PyTuple_Check(value)) {
739             PyErr_SetString(PyExc_TypeError,
740                             "__gproperties__ values must be tuples");
741             ret = FALSE;
742             break;
743         }
744         val_length = PyTuple_Size(value);
745         if (val_length < 4) {
746             PyErr_SetString(PyExc_TypeError,
747                             "__gproperties__ values must be at least 4 elements long");
748             ret = FALSE;
749             break;
750         }
751
752         slice = PySequence_GetSlice(value, 0, 3);
753         if (!slice) {
754             ret = FALSE;
755             break;
756         }
757         if (!PyArg_ParseTuple(slice, "Ozz", &py_prop_type, &nick, &blurb)) {
758             Py_DECREF(slice);
759             ret = FALSE;
760             break;
761         }
762         Py_DECREF(slice);
763         prop_type = pyg_type_from_object(py_prop_type);
764         if (!prop_type) {
765             ret = FALSE;
766             break;
767         }
768         item = PyTuple_GetItem(value, val_length-1);
769         if (!PYGLIB_PyLong_Check(item)) {
770             PyErr_SetString(PyExc_TypeError,
771                 "last element in __gproperties__ value tuple must be an int");
772             ret = FALSE;
773             break;
774         }
775         flags = PYGLIB_PyLong_AsLong(item);
776
777         /* slice is the extra items in the tuple */
778         slice = PySequence_GetSlice(value, 3, val_length-1);
779         pspec = create_property(prop_name, prop_type, nick, blurb,
780                                 slice, flags);
781         Py_DECREF(slice);
782
783         if (pspec) {
784             g_object_class_install_property(klass, 1, pspec);
785         } else {
786             PyObject *type, *value, *traceback;
787             ret = FALSE;
788             PyErr_Fetch(&type, &value, &traceback);
789             if (PYGLIB_PyUnicode_Check(value)) {
790                 char msg[256];
791                 g_snprintf(msg, 256,
792                            "%s (while registering property '%s' for GType '%s')",
793                PYGLIB_PyUnicode_AsString(value),
794                            prop_name, G_OBJECT_CLASS_NAME(klass));
795                 Py_DECREF(value);
796                 value = PYGLIB_PyUnicode_FromString(msg);
797             }
798             PyErr_Restore(type, value, traceback);
799             break;
800         }
801     }
802
803     return ret;
804 }
805
806 static void
807 pyg_object_class_init(GObjectClass *class, PyObject *py_class)
808 {
809     PyObject *gproperties, *gsignals, *overridden_signals;
810     PyObject *class_dict = ((PyTypeObject*) py_class)->tp_dict;
811
812     class->set_property = pyg_object_set_property;
813     class->get_property = pyg_object_get_property;
814
815     /* install signals */
816     /* we look this up in the instance dictionary, so we don't
817      * accidentally get a parent type's __gsignals__ attribute. */
818     gsignals = PyDict_GetItemString(class_dict, "__gsignals__");
819     if (gsignals) {
820         if (!PyDict_Check(gsignals)) {
821             PyErr_SetString(PyExc_TypeError,
822                             "__gsignals__ attribute not a dict!");
823             return;
824         }
825         if (!(overridden_signals = add_signals(class, gsignals))) {
826             return;
827         }
828         if (PyDict_SetItemString(class_dict, "__gsignals__",
829                                  overridden_signals)) {
830             return;
831         }
832         Py_DECREF(overridden_signals);
833
834         PyDict_DelItemString(class_dict, "__gsignals__");
835     } else {
836         PyErr_Clear();
837     }
838
839     /* install properties */
840     /* we look this up in the instance dictionary, so we don't
841      * accidentally get a parent type's __gproperties__ attribute. */
842     gproperties = PyDict_GetItemString(class_dict, "__gproperties__");
843     if (gproperties) {
844         if (!PyDict_Check(gproperties)) {
845             PyErr_SetString(PyExc_TypeError,
846                             "__gproperties__ attribute not a dict!");
847             return;
848         }
849         if (!add_properties(class, gproperties)) {
850             return;
851         }
852         PyDict_DelItemString(class_dict, "__gproperties__");
853         /* Borrowed reference. Py_DECREF(gproperties); */
854     } else {
855         PyErr_Clear();
856     }
857 }
858
859 static void
860 pyg_register_class_init(GType gtype, PyGClassInitFunc class_init)
861 {
862     GSList *list;
863
864     list = g_type_get_qdata(gtype, pygobject_class_init_key);
865     list = g_slist_prepend(list, class_init);
866     g_type_set_qdata(gtype, pygobject_class_init_key, list);
867 }
868
869 static int
870 pyg_run_class_init(GType gtype, gpointer gclass, PyTypeObject *pyclass)
871 {
872     GSList *list;
873     PyGClassInitFunc class_init;
874     GType parent_type;
875     int rv;
876
877     parent_type = g_type_parent(gtype);
878     if (parent_type) {
879         rv = pyg_run_class_init(parent_type, gclass, pyclass);
880         if (rv)
881             return rv;
882     }
883
884     list = g_type_get_qdata(gtype, pygobject_class_init_key);
885     for (; list; list = list->next) {
886         class_init = list->data;
887         rv = class_init(gclass, pyclass);
888         if (rv)
889             return rv;
890     }
891
892     return 0;
893 }
894
895 static PyObject *
896 _wrap_pyg_type_register(PyObject *self, PyObject *args)
897 {
898     PyTypeObject *class;
899     char *type_name = NULL;
900
901     if (!PyArg_ParseTuple(args, "O!|z:gobject.type_register",
902                           &PyType_Type, &class, &type_name))
903         return NULL;
904     if (!PyType_IsSubtype(class, &PyGObject_Type)) {
905         PyErr_SetString(PyExc_TypeError,
906                         "argument must be a GObject subclass");
907         return NULL;
908     }
909
910       /* Check if type already registered */
911     if (pyg_type_from_object((PyObject *) class) ==
912         pyg_type_from_object((PyObject *) class->tp_base))
913     {
914         if (pyg_type_register(class, type_name))
915             return NULL;
916     }
917
918     Py_INCREF(class);
919     return (PyObject *) class;
920 }
921
922 static char *
923 get_type_name_for_class(PyTypeObject *class)
924 {
925     gint i, name_serial;
926     char name_serial_str[16];
927     PyObject *module;
928     char *type_name = NULL;
929
930     /* make name for new GType */
931     name_serial = 1;
932     /* give up after 1000 tries, just in case.. */
933     while (name_serial < 1000)
934     {
935         g_free(type_name);
936         g_snprintf(name_serial_str, 16, "-v%i", name_serial);
937         module = PyObject_GetAttrString((PyObject *)class, "__module__");
938         if (module && PYGLIB_PyUnicode_Check(module)) {
939             type_name = g_strconcat(PYGLIB_PyUnicode_AsString(module), ".",
940                                     class->tp_name,
941                                     name_serial > 1 ? name_serial_str : NULL,
942                                     NULL);
943             Py_DECREF(module);
944         } else {
945             if (module)
946                 Py_DECREF(module);
947             else
948                 PyErr_Clear();
949             type_name = g_strconcat(class->tp_name,
950                                     name_serial > 1 ? name_serial_str : NULL,
951                                     NULL);
952         }
953         /* convert '.' in type name to '+', which isn't banned (grumble) */
954         for (i = 0; type_name[i] != '\0'; i++)
955             if (type_name[i] == '.')
956                 type_name[i] = '+';
957         if (g_type_from_name(type_name) == 0)
958             break;              /* we now have a unique name */
959         ++name_serial;
960     }
961
962     return type_name;
963 }
964
965
966 static GPrivate pygobject_construction_wrapper;
967
968 static inline void
969 pygobject_init_wrapper_set(PyObject *wrapper)
970 {
971     g_private_set(&pygobject_construction_wrapper, wrapper);
972 }
973
974 static inline PyObject *
975 pygobject_init_wrapper_get(void)
976 {
977     return (PyObject *) g_private_get(&pygobject_construction_wrapper);
978 }
979
980 int
981 pygobject_constructv(PyGObject  *self,
982                      guint       n_parameters,
983                      GParameter *parameters)
984 {
985     GObject *obj;
986
987     g_assert (self->obj == NULL);
988     pygobject_init_wrapper_set((PyObject *) self);
989     obj = g_object_newv(pyg_type_from_object((PyObject *) self),
990                         n_parameters, parameters);
991
992     if (g_object_is_floating (obj))
993         self->private_flags.flags |= PYGOBJECT_GOBJECT_WAS_FLOATING;
994     pygobject_sink (obj);
995
996     pygobject_init_wrapper_set(NULL);
997     self->obj = obj;
998     pygobject_register_wrapper((PyObject *) self);
999
1000     return 0;
1001 }
1002
1003 static void
1004 pygobject__g_instance_init(GTypeInstance   *instance,
1005                            gpointer         g_class)
1006 {
1007     GObject *object = (GObject *) instance;
1008     PyObject *wrapper, *args, *kwargs;
1009
1010     wrapper = g_object_get_qdata(object, pygobject_wrapper_key);
1011     if (wrapper == NULL) {
1012         wrapper = pygobject_init_wrapper_get();
1013         if (wrapper && ((PyGObject *) wrapper)->obj == NULL) {
1014             ((PyGObject *) wrapper)->obj = object;
1015             pygobject_register_wrapper(wrapper);
1016         }
1017     }
1018     pygobject_init_wrapper_set(NULL);
1019     if (wrapper == NULL) {
1020           /* this looks like a python object created through
1021            * g_object_new -> we have no python wrapper, so create it
1022            * now */
1023         PyGILState_STATE state;
1024         state = pyglib_gil_state_ensure();
1025         wrapper = pygobject_new_full(object,
1026                                      /*steal=*/ FALSE,
1027                                      g_class);
1028
1029         /* float the wrapper ref here because we are going to orphan it
1030          * so we don't destroy the wrapper. The next call to pygobject_new_full
1031          * will take the ref */
1032         pygobject_ref_float ((PyGObject *) wrapper);
1033         args = PyTuple_New(0);
1034         kwargs = PyDict_New();
1035         if (Py_TYPE(wrapper)->tp_init(wrapper, args, kwargs))
1036             PyErr_Print();
1037
1038         Py_DECREF(args);
1039         Py_DECREF(kwargs);
1040         pyglib_gil_state_release(state);
1041     }
1042 }
1043
1044
1045 /*  This implementation is bad, see bug 566571 for an example why.
1046  *  Instead of scanning explicitly declared bases for interfaces, we
1047  *  should automatically initialize all implemented interfaces to
1048  *  prevent bugs like that one.  However, this will lead to
1049  *  performance degradation as each virtual method in derived classes
1050  *  will round-trip through do_*() stuff, *even* if it is not
1051  *  overriden.  We need to teach codegen to retain parent method
1052  *  instead of setting virtual to *_proxy_do_*() if corresponding
1053  *  do_*() is not overriden.  Ok, that was a messy explanation.
1054  */
1055 static void
1056 pyg_type_add_interfaces(PyTypeObject *class, GType instance_type,
1057                         PyObject *bases,
1058                         GType *parent_interfaces, guint n_parent_interfaces)
1059 {
1060     int i;
1061
1062     if (!bases) {
1063         g_warning("type has no bases");
1064         return;
1065     }
1066
1067     for (i = 0; i < PyTuple_GET_SIZE(bases); ++i) {
1068         PyObject *base = PyTuple_GET_ITEM(bases, i);
1069         GType itype;
1070         const GInterfaceInfo *iinfo;
1071         GInterfaceInfo iinfo_copy;
1072
1073         /* 'base' can also be a PyClassObject, see bug #566571. */
1074         if (!PyType_Check(base))
1075             continue;
1076
1077         if (!PyType_IsSubtype((PyTypeObject*) base, &PyGInterface_Type))
1078             continue;
1079
1080         itype = pyg_type_from_object(base);
1081
1082         /* Happens for _implementations_ of an interface. */
1083         if (!G_TYPE_IS_INTERFACE(itype))
1084             continue;
1085
1086         iinfo = pyg_lookup_interface_info(itype);
1087         if (!iinfo) {
1088             gchar *error;
1089             error = g_strdup_printf("Interface type %s "
1090                                     "has no Python implementation support",
1091                                     ((PyTypeObject *) base)->tp_name);
1092             PyErr_Warn(PyExc_RuntimeWarning, error);
1093             g_free(error);
1094             continue;
1095         }
1096
1097         iinfo_copy = *iinfo;
1098         iinfo_copy.interface_data = class;
1099         g_type_add_interface_static(instance_type, itype, &iinfo_copy);
1100     }
1101 }
1102
1103 static int
1104 pyg_type_register(PyTypeObject *class, const char *type_name)
1105 {
1106     PyObject *gtype;
1107     GType parent_type, instance_type;
1108     GType *parent_interfaces;
1109     guint n_parent_interfaces;
1110     GTypeQuery query;
1111     gpointer gclass;
1112     GTypeInfo type_info = {
1113         0,    /* class_size */
1114
1115         (GBaseInitFunc) NULL,
1116         (GBaseFinalizeFunc) NULL,
1117
1118         (GClassInitFunc) pyg_object_class_init,
1119         (GClassFinalizeFunc) NULL,
1120         NULL, /* class_data */
1121
1122         0,    /* instance_size */
1123         0,    /* n_preallocs */
1124         (GInstanceInitFunc) pygobject__g_instance_init
1125     };
1126     gchar *new_type_name;
1127
1128     /* find the GType of the parent */
1129     parent_type = pyg_type_from_object((PyObject *)class);
1130     if (!parent_type)
1131         return -1;
1132
1133     parent_interfaces = g_type_interfaces(parent_type, &n_parent_interfaces);
1134
1135     if (type_name)
1136         /* care is taken below not to free this */
1137         new_type_name = (gchar *) type_name;
1138     else
1139         new_type_name = get_type_name_for_class(class);
1140
1141     /* set class_data that will be passed to the class_init function. */
1142     type_info.class_data = class;
1143
1144     /* fill in missing values of GTypeInfo struct */
1145     g_type_query(parent_type, &query);
1146     type_info.class_size = query.class_size;
1147     type_info.instance_size = query.instance_size;
1148
1149     /* create new typecode */
1150     instance_type = g_type_register_static(parent_type, new_type_name,
1151                                            &type_info, 0);
1152     if (instance_type == 0) {
1153         PyErr_Format(PyExc_RuntimeError,
1154                      "could not create new GType: %s (subclass of %s)",
1155                      new_type_name,
1156                      g_type_name(parent_type));
1157
1158         if (type_name == NULL)
1159             g_free(new_type_name);
1160
1161         return -1;
1162     }
1163
1164     if (type_name == NULL)
1165         g_free(new_type_name);
1166
1167     /* store pointer to the class with the GType */
1168     Py_INCREF(class);
1169     g_type_set_qdata(instance_type, g_quark_from_string("PyGObject::class"),
1170                      class);
1171
1172     /* Mark this GType as a custom python type */
1173     g_type_set_qdata(instance_type, pygobject_custom_key,
1174                      GINT_TO_POINTER (1));
1175
1176     /* set new value of __gtype__ on class */
1177     gtype = pyg_type_wrapper_new(instance_type);
1178     PyObject_SetAttrString((PyObject *)class, "__gtype__", gtype);
1179     Py_DECREF(gtype);
1180
1181     /* if no __doc__, set it to the auto doc descriptor */
1182     if (PyDict_GetItemString(class->tp_dict, "__doc__") == NULL) {
1183         PyDict_SetItemString(class->tp_dict, "__doc__",
1184                              pyg_object_descr_doc_get());
1185     }
1186
1187     /*
1188      * Note, all interfaces need to be registered before the first
1189      * g_type_class_ref(), see bug #686149.
1190      *
1191      * See also comment above pyg_type_add_interfaces().
1192      */
1193     pyg_type_add_interfaces(class, instance_type, class->tp_bases,
1194                             parent_interfaces, n_parent_interfaces);
1195
1196
1197     gclass = g_type_class_ref(instance_type);
1198     if (PyErr_Occurred() != NULL) {
1199         g_type_class_unref(gclass);
1200         g_free(parent_interfaces);
1201         return -1;
1202     }
1203
1204     if (pyg_run_class_init(instance_type, gclass, class)) {
1205         g_type_class_unref(gclass);
1206         g_free(parent_interfaces);
1207         return -1;
1208     }
1209     g_type_class_unref(gclass);
1210     g_free(parent_interfaces);
1211
1212     if (PyErr_Occurred() != NULL)
1213         return -1;
1214     return 0;
1215 }
1216
1217 static PyObject *
1218 pyg_signal_new(PyObject *self, PyObject *args)
1219 {
1220     gchar *signal_name;
1221     PyObject *py_type;
1222     GSignalFlags signal_flags;
1223     GType return_type;
1224     PyObject *py_return_type, *py_param_types;
1225
1226     GType instance_type = 0;
1227     Py_ssize_t n_params, i;
1228     GType *param_types;
1229
1230     guint signal_id;
1231
1232     if (!PyArg_ParseTuple(args, "sOiOO:gobject.signal_new", &signal_name,
1233                           &py_type, &signal_flags, &py_return_type,
1234                           &py_param_types))
1235         return NULL;
1236
1237     instance_type = pyg_type_from_object(py_type);
1238     if (!instance_type)
1239         return NULL;
1240     if (!(G_TYPE_IS_INSTANTIATABLE(instance_type) || G_TYPE_IS_INTERFACE(instance_type))) {
1241         PyErr_SetString(PyExc_TypeError,
1242                         "argument 2 must be an object type or interface type");
1243         return NULL;
1244     }
1245
1246     return_type = pyg_type_from_object(py_return_type);
1247     if (!return_type)
1248         return NULL;
1249
1250     if (!PySequence_Check(py_param_types)) {
1251         PyErr_SetString(PyExc_TypeError,
1252                         "argument 5 must be a sequence of GType codes");
1253         return NULL;
1254     }
1255     n_params = PySequence_Length(py_param_types);
1256     param_types = g_new(GType, n_params);
1257     for (i = 0; i < n_params; i++) {
1258         PyObject *item = PySequence_GetItem(py_param_types, i);
1259
1260         param_types[i] = pyg_type_from_object(item);
1261         if (param_types[i] == 0) {
1262             PyErr_Clear();
1263             Py_DECREF(item);
1264             PyErr_SetString(PyExc_TypeError,
1265                             "argument 5 must be a sequence of GType codes");
1266             g_free(param_types);
1267             return NULL;
1268         }
1269         Py_DECREF(item);
1270     }
1271
1272     signal_id = g_signal_newv(signal_name, instance_type, signal_flags,
1273                               pyg_signal_class_closure_get(),
1274                               (GSignalAccumulator)0, NULL,
1275                               (GSignalCMarshaller)0,
1276                               return_type, n_params, param_types);
1277     g_free(param_types);
1278     if (signal_id != 0)
1279         return PYGLIB_PyLong_FromLong(signal_id);
1280     PyErr_SetString(PyExc_RuntimeError, "could not create signal");
1281     return NULL;
1282 }
1283
1284 static PyObject *
1285 pyg_object_class_list_properties (PyObject *self, PyObject *args)
1286 {
1287     GParamSpec **specs;
1288     PyObject *py_itype, *list;
1289     GType itype;
1290     GObjectClass *class = NULL;
1291     gpointer iface = NULL;
1292     guint nprops;
1293     guint i;
1294
1295     if (!PyArg_ParseTuple(args, "O:gobject.list_properties",
1296                           &py_itype))
1297         return NULL;
1298     if ((itype = pyg_type_from_object(py_itype)) == 0)
1299         return NULL;
1300
1301     if (G_TYPE_IS_INTERFACE(itype)) {
1302         iface = g_type_default_interface_ref(itype);
1303         if (!iface) {
1304             PyErr_SetString(PyExc_RuntimeError,
1305                             "could not get a reference to interface type");
1306             return NULL;
1307         }
1308         specs = g_object_interface_list_properties(iface, &nprops);
1309     } else if (g_type_is_a(itype, G_TYPE_OBJECT)) {
1310         class = g_type_class_ref(itype);
1311         if (!class) {
1312             PyErr_SetString(PyExc_RuntimeError,
1313                             "could not get a reference to type class");
1314             return NULL;
1315         }
1316         specs = g_object_class_list_properties(class, &nprops);
1317     } else {
1318         PyErr_SetString(PyExc_TypeError,
1319                         "type must be derived from GObject or an interface");
1320         return NULL;
1321     }
1322
1323     list = PyTuple_New(nprops);
1324     if (list == NULL) {
1325         g_free(specs);
1326         g_type_class_unref(class);
1327         return NULL;
1328     }
1329     for (i = 0; i < nprops; i++) {
1330         PyTuple_SetItem(list, i, pyg_param_spec_new(specs[i]));
1331     }
1332     g_free(specs);
1333     if (class)
1334         g_type_class_unref(class);
1335     else
1336         g_type_default_interface_unref(iface);
1337
1338     return list;
1339 }
1340
1341 static PyObject *
1342 pyg_object_new (PyGObject *self, PyObject *args, PyObject *kwargs)
1343 {
1344     PyObject *pytype;
1345     GType type;
1346     GObject *obj = NULL;
1347     GObjectClass *class;
1348     guint n_params = 0, i;
1349     GParameter *params = NULL;
1350
1351     if (!PyArg_ParseTuple (args, "O:gobject.new", &pytype)) {
1352         return NULL;
1353     }
1354
1355     if ((type = pyg_type_from_object (pytype)) == 0)
1356         return NULL;
1357
1358     if (G_TYPE_IS_ABSTRACT(type)) {
1359         PyErr_Format(PyExc_TypeError, "cannot create instance of abstract "
1360                      "(non-instantiable) type `%s'", g_type_name(type));
1361         return NULL;
1362     }
1363
1364     if ((class = g_type_class_ref (type)) == NULL) {
1365         PyErr_SetString(PyExc_TypeError,
1366                         "could not get a reference to type class");
1367         return NULL;
1368     }
1369
1370     if (!pygobject_prepare_construct_properties (class, kwargs, &n_params, &params))
1371         goto cleanup;
1372
1373     obj = g_object_newv(type, n_params, params);
1374     if (!obj)
1375         PyErr_SetString (PyExc_RuntimeError, "could not create object");
1376
1377  cleanup:
1378     for (i = 0; i < n_params; i++) {
1379         g_free((gchar *) params[i].name);
1380         g_value_unset(&params[i].value);
1381     }
1382     g_free(params);
1383     g_type_class_unref(class);
1384
1385     if (obj) {
1386         pygobject_sink (obj);
1387         self = (PyGObject *) pygobject_new((GObject *)obj);
1388         g_object_unref(obj);
1389     } else
1390         self = NULL;
1391
1392     return (PyObject *) self;
1393 }
1394
1395 static int
1396 pygobject_gil_state_ensure (void)
1397 {
1398     return pyglib_gil_state_ensure ();
1399 }
1400
1401 static void
1402 pygobject_gil_state_release (int flag)
1403 {
1404     pyglib_gil_state_release(flag);
1405 }
1406
1407 /* Only for backwards compatibility */
1408 static int
1409 pygobject_enable_threads(void)
1410 {
1411     return 0;
1412 }
1413
1414 static PyObject *
1415 pyg_signal_accumulator_true_handled(PyObject *unused, PyObject *args)
1416 {
1417     PyErr_SetString(PyExc_TypeError,
1418                     "signal_accumulator_true_handled can only"
1419                     " be used as accumulator argument when registering signals");
1420     return NULL;
1421 }
1422
1423 static gboolean
1424 marshal_emission_hook(GSignalInvocationHint *ihint,
1425                       guint n_param_values,
1426                       const GValue *param_values,
1427                       gpointer user_data)
1428 {
1429     PyGILState_STATE state;
1430     gboolean retval = FALSE;
1431     PyObject *func, *args;
1432     PyObject *retobj;
1433     PyObject *params;
1434     guint i;
1435
1436     state = pyglib_gil_state_ensure();
1437
1438     /* construct Python tuple for the parameter values */
1439     params = PyTuple_New(n_param_values);
1440
1441     for (i = 0; i < n_param_values; i++) {
1442         PyObject *item = pyg_value_as_pyobject(&param_values[i], FALSE);
1443
1444         /* error condition */
1445         if (!item) {
1446             goto out;
1447         }
1448         PyTuple_SetItem(params, i, item);
1449     }
1450
1451     args = (PyObject *)user_data;
1452     func = PyTuple_GetItem(args, 0);
1453     args = PySequence_Concat(params, PyTuple_GetItem(args, 1));
1454     Py_DECREF(params);
1455
1456     /* params passed to function may have extra arguments */
1457
1458     retobj = PyObject_CallObject(func, args);
1459     Py_DECREF(args);
1460     if (retobj == NULL) {
1461         PyErr_Print();
1462     }
1463
1464     retval = (retobj == Py_True ? TRUE : FALSE);
1465     Py_XDECREF(retobj);
1466 out:
1467     pyglib_gil_state_release(state);
1468     return retval;
1469 }
1470
1471 static PyObject *
1472 pyg_add_emission_hook(PyGObject *self, PyObject *args)
1473 {
1474     PyObject *first, *callback, *extra_args, *data, *repr;
1475     gchar *name;
1476     gulong hook_id;
1477     guint sigid;
1478     Py_ssize_t len;
1479     GQuark detail = 0;
1480     GType gtype;
1481     PyObject *pygtype;
1482
1483     len = PyTuple_Size(args);
1484     if (len < 3) {
1485         PyErr_SetString(PyExc_TypeError,
1486                         "gobject.add_emission_hook requires at least 3 arguments");
1487         return NULL;
1488     }
1489     first = PySequence_GetSlice(args, 0, 3);
1490     if (!PyArg_ParseTuple(first, "OsO:add_emission_hook",
1491                           &pygtype, &name, &callback)) {
1492         Py_DECREF(first);
1493         return NULL;
1494     }
1495     Py_DECREF(first);
1496
1497     if ((gtype = pyg_type_from_object(pygtype)) == 0) {
1498         return NULL;
1499     }
1500     if (!PyCallable_Check(callback)) {
1501         PyErr_SetString(PyExc_TypeError, "third argument must be callable");
1502         return NULL;
1503     }
1504
1505     if (!g_signal_parse_name(name, gtype, &sigid, &detail, TRUE)) {
1506         repr = PyObject_Repr((PyObject*)self);
1507         PyErr_Format(PyExc_TypeError, "%s: unknown signal name: %s",
1508                         PYGLIB_PyUnicode_AsString(repr),
1509                      name);
1510         Py_DECREF(repr);
1511         return NULL;
1512     }
1513     extra_args = PySequence_GetSlice(args, 3, len);
1514     if (extra_args == NULL)
1515         return NULL;
1516
1517     data = Py_BuildValue("(ON)", callback, extra_args);
1518     if (data == NULL)
1519       return NULL;
1520
1521     hook_id = g_signal_add_emission_hook(sigid, detail,
1522                                          marshal_emission_hook,
1523                                          data,
1524                                          (GDestroyNotify)pyg_destroy_notify);
1525
1526     return PyLong_FromUnsignedLong(hook_id);
1527 }
1528
1529 static PyObject *
1530 pyg__install_metaclass(PyObject *dummy, PyTypeObject *metaclass)
1531 {
1532     Py_INCREF(metaclass);
1533     PyGObject_MetaType = metaclass;
1534     Py_INCREF(metaclass);
1535
1536     Py_TYPE(&PyGObject_Type) = metaclass;
1537
1538     Py_INCREF(Py_None);
1539     return Py_None;
1540 }
1541
1542 static PyObject *
1543 pyg__gvalue_get(PyObject *module, PyObject *pygvalue)
1544 {
1545     if (!pyg_boxed_check (pygvalue, G_TYPE_VALUE)) {
1546         PyErr_SetString (PyExc_TypeError, "Expected GValue argument.");
1547         return NULL;
1548     }
1549
1550     return pyg_value_as_pyobject (pyg_boxed_get(pygvalue, GValue),
1551                                   /*copy_boxed=*/ TRUE);
1552 }
1553
1554 static PyObject *
1555 pyg__gvalue_set(PyObject *module, PyObject *args)
1556 {
1557     PyObject *pygvalue;
1558     PyObject *pyobject;
1559
1560     if (!PyArg_ParseTuple (args, "OO:_gobject._gvalue_set",
1561                            &pygvalue, &pyobject))
1562         return NULL;
1563
1564     if (!pyg_boxed_check (pygvalue, G_TYPE_VALUE)) {
1565         PyErr_SetString (PyExc_TypeError, "Expected GValue argument.");
1566         return NULL;
1567     }
1568
1569     if (pyg_value_from_pyobject_with_error (pyg_boxed_get (pygvalue, GValue),
1570                                             pyobject) == -1)
1571         return NULL;
1572
1573     Py_RETURN_NONE;
1574 }
1575
1576 static PyMethodDef _gobject_functions[] = {
1577     { "type_name", pyg_type_name, METH_VARARGS },
1578     { "type_from_name", pyg_type_from_name, METH_VARARGS },
1579     { "type_is_a", pyg_type_is_a, METH_VARARGS },
1580     { "type_register", _wrap_pyg_type_register, METH_VARARGS },
1581     { "signal_new", pyg_signal_new, METH_VARARGS },
1582     { "list_properties",
1583       pyg_object_class_list_properties, METH_VARARGS },
1584     { "new",
1585       (PyCFunction)pyg_object_new, METH_VARARGS|METH_KEYWORDS },
1586     { "signal_accumulator_true_handled",
1587       (PyCFunction)pyg_signal_accumulator_true_handled, METH_VARARGS },
1588     { "add_emission_hook",
1589       (PyCFunction)pyg_add_emission_hook, METH_VARARGS },
1590     { "_install_metaclass",
1591       (PyCFunction)pyg__install_metaclass, METH_O },
1592     { "_gvalue_get",
1593       (PyCFunction)pyg__gvalue_get, METH_O },
1594     { "_gvalue_set",
1595       (PyCFunction)pyg__gvalue_set, METH_VARARGS },
1596
1597     { NULL, NULL, 0 }
1598 };
1599
1600
1601 /* ----------------- Constant extraction ------------------------ */
1602
1603 /**
1604  * pyg_constant_strip_prefix:
1605  * @name: the constant name.
1606  * @strip_prefix: the prefix to strip.
1607  *
1608  * Advances the pointer @name by strlen(@strip_prefix) characters.  If
1609  * the resulting name does not start with a letter or underscore, the
1610  * @name pointer will be rewound.  This is to ensure that the
1611  * resulting name is a valid identifier.  Hence the returned string is
1612  * a pointer into the string @name.
1613  *
1614  * Returns: the stripped constant name.
1615  */
1616 const gchar *
1617 pyg_constant_strip_prefix(const gchar *name, const gchar *strip_prefix)
1618 {
1619     gint prefix_len;
1620     guint i;
1621
1622     prefix_len = strlen(strip_prefix);
1623
1624     /* Check so name starts with strip_prefix, if it doesn't:
1625      * return the rest of the part which doesn't match
1626      */
1627     for (i = 0; i < prefix_len; i++) {
1628         if (name[i] != strip_prefix[i] && name[i] != '_') {
1629             return &name[i];
1630         }
1631     }
1632
1633     /* strip off prefix from value name, while keeping it a valid
1634      * identifier */
1635     for (i = prefix_len; i >= 0; i--) {
1636         if (g_ascii_isalpha(name[i]) || name[i] == '_') {
1637             return &name[i];
1638         }
1639     }
1640     return name;
1641 }
1642
1643 /**
1644  * pyg_enum_add_constants:
1645  * @module: a Python module
1646  * @enum_type: the GType of the enumeration.
1647  * @strip_prefix: the prefix to strip from the constant names.
1648  *
1649  * Adds constants to the given Python module for each value name of
1650  * the enumeration.  A prefix will be stripped from each enum name.
1651  */
1652 static void
1653 pyg_enum_add_constants(PyObject *module, GType enum_type,
1654                        const gchar *strip_prefix)
1655 {
1656     GEnumClass *eclass;
1657     guint i;
1658
1659     if (!G_TYPE_IS_ENUM(enum_type)) {
1660         if (G_TYPE_IS_FLAGS(enum_type)) /* See bug #136204 */
1661             pyg_flags_add_constants(module, enum_type, strip_prefix);
1662         else
1663             g_warning("`%s' is not an enum type", g_type_name(enum_type));
1664         return;
1665     }
1666     g_return_if_fail (strip_prefix != NULL);
1667
1668     eclass = G_ENUM_CLASS(g_type_class_ref(enum_type));
1669
1670     for (i = 0; i < eclass->n_values; i++) {
1671         const gchar *name = eclass->values[i].value_name;
1672         gint value = eclass->values[i].value;
1673
1674         PyModule_AddIntConstant(module,
1675                                 (char*) pyg_constant_strip_prefix(name, strip_prefix),
1676                                 (long) value);
1677     }
1678
1679     g_type_class_unref(eclass);
1680 }
1681
1682 /**
1683  * pyg_flags_add_constants:
1684  * @module: a Python module
1685  * @flags_type: the GType of the flags type.
1686  * @strip_prefix: the prefix to strip from the constant names.
1687  *
1688  * Adds constants to the given Python module for each value name of
1689  * the flags set.  A prefix will be stripped from each flag name.
1690  */
1691 static void
1692 pyg_flags_add_constants(PyObject *module, GType flags_type,
1693                         const gchar *strip_prefix)
1694 {
1695     GFlagsClass *fclass;
1696     guint i;
1697
1698     if (!G_TYPE_IS_FLAGS(flags_type)) {
1699         if (G_TYPE_IS_ENUM(flags_type)) /* See bug #136204 */
1700             pyg_enum_add_constants(module, flags_type, strip_prefix);
1701         else
1702             g_warning("`%s' is not an flags type", g_type_name(flags_type));
1703         return;
1704     }
1705     g_return_if_fail (strip_prefix != NULL);
1706
1707     fclass = G_FLAGS_CLASS(g_type_class_ref(flags_type));
1708
1709     for (i = 0; i < fclass->n_values; i++) {
1710         const gchar *name = fclass->values[i].value_name;
1711         guint value = fclass->values[i].value;
1712
1713         PyModule_AddIntConstant(module,
1714                                 (char*) pyg_constant_strip_prefix(name, strip_prefix),
1715                                 (long) value);
1716     }
1717
1718     g_type_class_unref(fclass);
1719 }
1720
1721 /**
1722  * pyg_parse_constructor_args: helper function for PyGObject constructors
1723  * @obj_type: GType of the GObject, for parameter introspection
1724  * @arg_names: %NULL-terminated array of constructor argument names
1725  * @prop_names: %NULL-terminated array of property names, with direct
1726  * correspondence to @arg_names
1727  * @params: GParameter array where parameters will be placed; length
1728  * of this array must be at least equal to the number of
1729  * arguments/properties
1730  * @nparams: output parameter to contain actual number of arguments found
1731  * @py_args: array of PyObject* containing the actual constructor arguments
1732  *
1733  * Parses an array of PyObject's and creates a GParameter array
1734  *
1735  * Return value: %TRUE if all is successful, otherwise %FALSE and
1736  * python exception set.
1737  **/
1738 static gboolean
1739 pyg_parse_constructor_args(GType        obj_type,
1740                            char       **arg_names,
1741                            char       **prop_names,
1742                            GParameter  *params,
1743                            guint       *nparams,
1744                            PyObject   **py_args)
1745 {
1746     guint arg_i, param_i;
1747     GObjectClass *oclass;
1748
1749     oclass = g_type_class_ref(obj_type);
1750     g_return_val_if_fail(oclass, FALSE);
1751
1752     for (param_i = arg_i = 0; arg_names[arg_i]; ++arg_i) {
1753         GParamSpec *spec;
1754         if (!py_args[arg_i])
1755             continue;
1756         spec = g_object_class_find_property(oclass, prop_names[arg_i]);
1757         params[param_i].name = prop_names[arg_i];
1758         g_value_init(&params[param_i].value, spec->value_type);
1759         if (pyg_value_from_pyobject(&params[param_i].value, py_args[arg_i]) == -1) {
1760             int i;
1761             PyErr_Format(PyExc_TypeError, "could not convert parameter '%s' of type '%s'",
1762                          arg_names[arg_i], g_type_name(spec->value_type));
1763             g_type_class_unref(oclass);
1764             for (i = 0; i < param_i; ++i)
1765                 g_value_unset(&params[i].value);
1766             return FALSE;
1767         }
1768         ++param_i;
1769     }
1770     g_type_class_unref(oclass);
1771     *nparams = param_i;
1772     return TRUE;
1773 }
1774
1775 static void
1776 _log_func(const gchar *log_domain,
1777           GLogLevelFlags log_level,
1778           const gchar *message,
1779           gpointer user_data)
1780 {
1781     if (G_LIKELY(Py_IsInitialized()))
1782     {
1783         PyGILState_STATE state;
1784         PyObject* warning = user_data;
1785
1786         state = pyglib_gil_state_ensure();
1787         PyErr_Warn(warning, (char *) message);
1788         pyglib_gil_state_release(state);
1789     } else
1790         g_log_default_handler(log_domain, log_level, message, user_data);
1791 }
1792
1793 static void
1794 add_warning_redirection(const char *domain,
1795                         PyObject   *warning)
1796 {
1797     g_return_if_fail(domain != NULL);
1798     g_return_if_fail(warning != NULL);
1799
1800     if (!log_handlers_disabled)
1801     {
1802         guint handler;
1803         gpointer old_handler;
1804
1805         if (!log_handlers)
1806             log_handlers = g_hash_table_new_full(g_str_hash, g_str_equal, g_free, NULL);
1807
1808         if ((old_handler = g_hash_table_lookup(log_handlers, domain)))
1809             g_log_remove_handler(domain, GPOINTER_TO_UINT(old_handler));
1810
1811         handler = g_log_set_handler(domain, G_LOG_LEVEL_CRITICAL|G_LOG_LEVEL_WARNING,
1812                                     _log_func, warning);
1813         g_hash_table_insert(log_handlers, g_strdup(domain), GUINT_TO_POINTER(handler));
1814     }
1815 }
1816
1817 static void
1818 remove_handler(gpointer domain,
1819                gpointer handler,
1820                gpointer unused)
1821 {
1822     g_log_remove_handler(domain, GPOINTER_TO_UINT(handler));
1823 }
1824
1825 static void
1826 disable_warning_redirections(void)
1827 {
1828     log_handlers_disabled = TRUE;
1829
1830     if (log_handlers)
1831     {
1832         g_hash_table_foreach(log_handlers, remove_handler, NULL);
1833         g_hash_table_destroy(log_handlers);
1834         log_handlers = NULL;
1835     }
1836 }
1837
1838 /* ----------------- gobject module initialisation -------------- */
1839
1840 struct _PyGObject_Functions pygobject_api_functions = {
1841   pygobject_register_class,
1842   pygobject_register_wrapper,
1843   pygobject_lookup_class,
1844   pygobject_new,
1845
1846   pyg_closure_new,
1847   pygobject_watch_closure,
1848   pyg_destroy_notify,
1849
1850   pyg_type_from_object,
1851   pyg_type_wrapper_new,
1852   pyg_enum_get_value,
1853   pyg_flags_get_value,
1854   pyg_register_gtype_custom,
1855   pyg_value_from_pyobject,
1856   pyg_value_as_pyobject,
1857
1858   pyg_register_interface,
1859
1860   &PyGBoxed_Type,
1861   pyg_register_boxed,
1862   pyg_boxed_new,
1863
1864   &PyGPointer_Type,
1865   pyg_register_pointer,
1866   pyg_pointer_new,
1867
1868   pyg_enum_add_constants,
1869   pyg_flags_add_constants,
1870
1871   pyg_constant_strip_prefix,
1872
1873   pygi_error_check,
1874
1875   _pyg_set_thread_block_funcs,
1876   (PyGThreadBlockFunc)0, /* block_threads */
1877   (PyGThreadBlockFunc)0, /* unblock_threads */
1878
1879   &PyGParamSpec_Type,
1880   pyg_param_spec_new,
1881   pyg_param_spec_from_object,
1882
1883   pyg_pyobj_to_unichar_conv,
1884   pyg_parse_constructor_args,
1885   pyg_param_gvalue_as_pyobject,
1886   pyg_param_gvalue_from_pyobject,
1887
1888   &PyGEnum_Type,
1889   pyg_enum_add,
1890   pyg_enum_from_gtype,
1891
1892   &PyGFlags_Type,
1893   pyg_flags_add,
1894   pyg_flags_from_gtype,
1895
1896   /* threads_enabled */
1897 #ifdef DISABLE_THREADING
1898   FALSE,
1899 #else
1900   TRUE,
1901 #endif
1902
1903   pygobject_enable_threads,
1904   pygobject_gil_state_ensure,
1905   pygobject_gil_state_release,
1906   pyg_register_class_init,
1907   pyg_register_interface_info,
1908
1909   pyg_closure_set_exception_handler,
1910
1911   add_warning_redirection,
1912   disable_warning_redirections,
1913
1914   NULL, /* previously type_register_custom */
1915
1916   pygi_gerror_exception_check,
1917
1918   pyg_option_group_new,
1919   pyg_type_from_object_strict,
1920
1921   pygobject_new_full,
1922   &PyGObject_Type,
1923
1924   pyg_value_from_pyobject_with_error
1925 };
1926
1927 /* for addon libraries ... */
1928 static void
1929 pygobject_register_api(PyObject *d)
1930 {
1931     PyObject *api;
1932
1933     api = PYGLIB_CPointer_WrapPointer(&pygobject_api_functions, "gobject._PyGObject_API");
1934     PyDict_SetItemString(d, "_PyGObject_API", api);
1935     Py_DECREF(api);
1936 }
1937
1938 /* some constants */
1939 static void
1940 pygobject_register_constants(PyObject *m)
1941 {
1942     /* PyFloat_ return a new ref, and add object takes the ref */
1943     PyModule_AddObject(m,       "G_MINFLOAT", PyFloat_FromDouble(G_MINFLOAT));
1944     PyModule_AddObject(m,       "G_MAXFLOAT", PyFloat_FromDouble(G_MAXFLOAT));
1945     PyModule_AddObject(m,       "G_MINDOUBLE", PyFloat_FromDouble(G_MINDOUBLE));
1946     PyModule_AddObject(m,       "G_MAXDOUBLE", PyFloat_FromDouble(G_MAXDOUBLE));
1947     PyModule_AddIntConstant(m,  "G_MINSHORT", G_MINSHORT);
1948     PyModule_AddIntConstant(m,  "G_MAXSHORT", G_MAXSHORT);
1949     PyModule_AddIntConstant(m,  "G_MAXUSHORT", G_MAXUSHORT);
1950     PyModule_AddIntConstant(m,  "G_MININT", G_MININT);
1951     PyModule_AddIntConstant(m,  "G_MAXINT", G_MAXINT);
1952     PyModule_AddObject(m,       "G_MAXUINT", PyLong_FromUnsignedLong(G_MAXUINT));
1953     PyModule_AddObject(m,       "G_MINLONG", PyLong_FromLong(G_MINLONG));
1954     PyModule_AddObject(m,       "G_MAXLONG", PyLong_FromLong(G_MAXLONG));
1955     PyModule_AddObject(m,       "G_MAXULONG", PyLong_FromUnsignedLong(G_MAXULONG));
1956     PyModule_AddObject(m,       "G_MAXSIZE", PyLong_FromSize_t(G_MAXSIZE));
1957     PyModule_AddObject(m,       "G_MAXSSIZE", PyLong_FromSsize_t(G_MAXSSIZE));
1958     PyModule_AddObject(m,       "G_MINSSIZE", PyLong_FromSsize_t(G_MINSSIZE));
1959     PyModule_AddObject(m,       "G_MINOFFSET", PyLong_FromLongLong(G_MINOFFSET));
1960     PyModule_AddObject(m,       "G_MAXOFFSET", PyLong_FromLongLong(G_MAXOFFSET));
1961
1962     PyModule_AddIntConstant(m, "SIGNAL_RUN_FIRST", G_SIGNAL_RUN_FIRST);
1963     PyModule_AddIntConstant(m, "PARAM_READWRITE", G_PARAM_READWRITE);
1964
1965     /* The rest of the types are set in __init__.py */
1966     PyModule_AddObject(m, "TYPE_INVALID", pyg_type_wrapper_new(G_TYPE_INVALID));
1967     PyModule_AddObject(m, "TYPE_GSTRING", pyg_type_wrapper_new(G_TYPE_GSTRING));
1968 }
1969
1970 /* features */
1971 static void
1972 pygobject_register_features(PyObject *d)
1973 {
1974     PyObject *features;
1975
1976     features = PyDict_New();
1977     PyDict_SetItemString(features, "generic-c-marshaller", Py_True);
1978     PyDict_SetItemString(d, "features", features);
1979     Py_DECREF(features);
1980 }
1981
1982 static void
1983 pygobject_register_version_tuples(PyObject *d)
1984 {
1985     PyObject *tuple;
1986
1987     /* pygobject version */
1988     tuple = Py_BuildValue ("(iii)",
1989                            PYGOBJECT_MAJOR_VERSION,
1990                            PYGOBJECT_MINOR_VERSION,
1991                            PYGOBJECT_MICRO_VERSION);
1992     PyDict_SetItemString(d, "pygobject_version", tuple);
1993 }
1994
1995 static void
1996 pygobject_register_warnings(PyObject *d)
1997 {
1998     PyObject *warning;
1999
2000     warning = PyErr_NewException("gobject.Warning", PyExc_Warning, NULL);
2001     PyDict_SetItemString(d, "Warning", warning);
2002     add_warning_redirection("GLib", warning);
2003     add_warning_redirection("GLib-GObject", warning);
2004     add_warning_redirection("GThread", warning);
2005 }
2006
2007
2008 PYGLIB_MODULE_START(_gobject, "_gobject")
2009 {
2010     PyObject *d;
2011
2012     d = PyModule_GetDict(module);
2013     pygobject_register_api(d);
2014     pygobject_register_constants(module);
2015     pygobject_register_features(d);
2016     pygobject_register_version_tuples(d);
2017     pygobject_register_warnings(d);
2018     pygobject_type_register_types(d);
2019     pygobject_object_register_types(d);
2020     pygobject_interface_register_types(d);
2021     pygobject_paramspec_register_types(d);
2022     pygobject_boxed_register_types(d);
2023     pygobject_pointer_register_types(d);
2024     pygobject_enum_register_types(d);
2025     pygobject_flags_register_types(d);
2026 }
2027 PYGLIB_MODULE_END