5ee54aac080316165564a8c205e0e439bd099f51
[platform/upstream/pygobject2.git] / gobject / pygtype.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  *   pygtype.c: glue code to wrap the GType code.
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, write to the Free Software
19  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301
20  * USA
21  */
22
23 #ifdef HAVE_CONFIG_H
24 #  include <config.h>
25 #endif
26
27 #include <pyglib.h>
28
29 #include "pygobject-private.h"
30 #include "pygparamspec.h"
31 #include "pygtype.h"
32
33 /* -------------- __gtype__ objects ---------------------------- */
34
35 typedef struct {
36     PyObject_HEAD
37     GType type;
38 } PyGTypeWrapper;
39
40 PYGLIB_DEFINE_TYPE("gobject.GType", PyGTypeWrapper_Type, PyGTypeWrapper);
41
42 static PyObject*
43 pyg_type_wrapper_richcompare(PyObject *self, PyObject *other, int op)
44 {
45     if (Py_TYPE(self) == Py_TYPE(other) && Py_TYPE(self) == &PyGTypeWrapper_Type)
46         return _pyglib_generic_long_richcompare(((PyGTypeWrapper*)self)->type,
47                                                 ((PyGTypeWrapper*)other)->type,
48                                                 op);
49     else {
50         Py_INCREF(Py_NotImplemented);
51         return Py_NotImplemented;
52     }
53 }
54
55 static long
56 pyg_type_wrapper_hash(PyGTypeWrapper *self)
57 {
58     return (long)self->type;
59 }
60
61 static PyObject *
62 pyg_type_wrapper_repr(PyGTypeWrapper *self)
63 {
64     char buf[80];
65     const gchar *name = g_type_name(self->type);
66
67     g_snprintf(buf, sizeof(buf), "<GType %s (%lu)>",
68                name?name:"invalid", (unsigned long int) self->type);
69     return PYGLIB_PyUnicode_FromString(buf);
70 }
71
72 static void
73 pyg_type_wrapper_dealloc(PyGTypeWrapper *self)
74 {
75     PyObject_DEL(self);
76 }
77
78 static GQuark
79 _pyg_type_key(GType type) {
80     GQuark key;
81
82     if (g_type_is_a(type, G_TYPE_INTERFACE)) {
83         key = pyginterface_type_key;
84     } else if (g_type_is_a(type, G_TYPE_ENUM)) {
85         key = pygenum_class_key;
86     } else if (g_type_is_a(type, G_TYPE_FLAGS)) {
87         key = pygflags_class_key;
88     } else if (g_type_is_a(type, G_TYPE_POINTER)) {
89         key = pygpointer_class_key;
90     } else if (g_type_is_a(type, G_TYPE_BOXED)) {
91         key = pygboxed_type_key;
92     } else {
93         key = pygobject_class_key;
94     }
95
96     return key;
97 }
98
99 static PyObject *
100 _wrap_g_type_wrapper__get_pytype(PyGTypeWrapper *self, void *closure)
101 {
102     GQuark key;
103     PyObject *py_type;
104
105     key = _pyg_type_key(self->type);
106
107     py_type = g_type_get_qdata(self->type, key);
108     if (!py_type)
109       py_type = Py_None;
110
111     Py_INCREF(py_type);
112     return py_type;
113 }
114
115 static int
116 _wrap_g_type_wrapper__set_pytype(PyGTypeWrapper *self, PyObject* value, void *closure)
117 {
118     GQuark key;
119     PyObject *py_type;
120
121     key = _pyg_type_key(self->type);
122
123     py_type = g_type_get_qdata(self->type, key);
124     Py_CLEAR(py_type);
125     if (value == Py_None)
126         g_type_set_qdata(self->type, key, NULL);
127     else if (PyType_Check(value)) {
128         Py_INCREF(value);
129         g_type_set_qdata(self->type, key, value);
130     } else {
131         PyErr_SetString(PyExc_TypeError, "Value must be None or a type object");
132         return -1;
133     }
134
135     return 0;
136 }
137
138 static PyObject *
139 _wrap_g_type_wrapper__get_name(PyGTypeWrapper *self, void *closure)
140 {
141    const char *name = g_type_name(self->type);
142    return PYGLIB_PyUnicode_FromString(name ? name : "invalid");
143 }
144
145 static PyObject *
146 _wrap_g_type_wrapper__get_parent(PyGTypeWrapper *self, void *closure)
147 {
148    return pyg_type_wrapper_new(g_type_parent(self->type));
149 }
150
151 static PyObject *
152 _wrap_g_type_wrapper__get_fundamental(PyGTypeWrapper *self, void *closure)
153 {
154    return pyg_type_wrapper_new(g_type_fundamental(self->type));
155 }
156
157 static PyObject *
158 _wrap_g_type_wrapper__get_children(PyGTypeWrapper *self, void *closure)
159 {
160   guint n_children, i;
161   GType *children;
162   PyObject *retval;
163
164   children = g_type_children(self->type, &n_children);
165
166   retval = PyList_New(n_children);
167   for (i = 0; i < n_children; i++)
168       PyList_SetItem(retval, i, pyg_type_wrapper_new(children[i]));
169   g_free(children);
170
171   return retval;
172 }
173
174 static PyObject *
175 _wrap_g_type_wrapper__get_interfaces(PyGTypeWrapper *self, void *closure)
176 {
177   guint n_interfaces, i;
178   GType *interfaces;
179   PyObject *retval;
180
181   interfaces = g_type_interfaces(self->type, &n_interfaces);
182
183   retval = PyList_New(n_interfaces);
184   for (i = 0; i < n_interfaces; i++)
185       PyList_SetItem(retval, i, pyg_type_wrapper_new(interfaces[i]));
186   g_free(interfaces);
187
188   return retval;
189 }
190
191 static PyObject *
192 _wrap_g_type_wrapper__get_depth(PyGTypeWrapper *self, void *closure)
193 {
194   return PYGLIB_PyLong_FromLong(g_type_depth(self->type));
195 }
196
197 static PyGetSetDef _PyGTypeWrapper_getsets[] = {
198     { "pytype", (getter)_wrap_g_type_wrapper__get_pytype, (setter)_wrap_g_type_wrapper__set_pytype },
199     { "name",  (getter)_wrap_g_type_wrapper__get_name, (setter)0 },
200     { "fundamental",  (getter)_wrap_g_type_wrapper__get_fundamental, (setter)0 },
201     { "parent",  (getter)_wrap_g_type_wrapper__get_parent, (setter)0 },
202     { "children",  (getter)_wrap_g_type_wrapper__get_children, (setter)0 },
203     { "interfaces",  (getter)_wrap_g_type_wrapper__get_interfaces, (setter)0 },
204     { "depth",  (getter)_wrap_g_type_wrapper__get_depth, (setter)0 },
205     { NULL, (getter)0, (setter)0 }
206 };
207
208 static PyObject*
209 _wrap_g_type_is_interface(PyGTypeWrapper *self)
210 {
211     return PyBool_FromLong(G_TYPE_IS_INTERFACE(self->type));
212 }
213
214 static PyObject*
215 _wrap_g_type_is_classed(PyGTypeWrapper *self)
216 {
217     return PyBool_FromLong(G_TYPE_IS_CLASSED(self->type));
218 }
219
220 static PyObject*
221 _wrap_g_type_is_instantiatable(PyGTypeWrapper *self)
222 {
223     return PyBool_FromLong(G_TYPE_IS_INSTANTIATABLE(self->type));
224 }
225
226 static PyObject*
227 _wrap_g_type_is_derivable(PyGTypeWrapper *self)
228 {
229     return PyBool_FromLong(G_TYPE_IS_DERIVABLE(self->type));
230 }
231
232 static PyObject*
233 _wrap_g_type_is_deep_derivable(PyGTypeWrapper *self)
234 {
235     return PyBool_FromLong(G_TYPE_IS_DEEP_DERIVABLE(self->type));
236 }
237
238 static PyObject*
239 _wrap_g_type_is_abstract(PyGTypeWrapper *self)
240 {
241     return PyBool_FromLong(G_TYPE_IS_ABSTRACT(self->type));
242 }
243
244 static PyObject*
245 _wrap_g_type_is_value_abstract(PyGTypeWrapper *self)
246 {
247     return PyBool_FromLong(G_TYPE_IS_VALUE_ABSTRACT(self->type));
248 }
249
250 static PyObject*
251 _wrap_g_type_is_value_type(PyGTypeWrapper *self)
252 {
253     return PyBool_FromLong(G_TYPE_IS_VALUE_TYPE(self->type));
254 }
255
256 static PyObject*
257 _wrap_g_type_has_value_table(PyGTypeWrapper *self)
258 {
259     return PyBool_FromLong(G_TYPE_HAS_VALUE_TABLE(self->type));
260 }
261
262 static PyObject*
263 _wrap_g_type_from_name(PyGTypeWrapper *_, PyObject *args)
264 {
265     char *type_name;
266     GType type;
267
268     if (!PyArg_ParseTuple(args, "s:GType.from_name", &type_name))
269         return NULL;
270
271     type = _pyg_type_from_name(type_name);
272     if (type == 0) {
273         PyErr_SetString(PyExc_RuntimeError, "unknown type name");
274         return NULL;
275     }
276
277     return pyg_type_wrapper_new(type);
278 }
279
280 static PyObject*
281 _wrap_g_type_is_a(PyGTypeWrapper *self, PyObject *args)
282 {
283     PyObject *gparent;
284     GType parent;
285
286     if (!PyArg_ParseTuple(args, "O:GType.is_a", &gparent))
287         return NULL;
288     else if ((parent = pyg_type_from_object(gparent)) == 0)
289         return NULL;
290
291     return PyBool_FromLong(g_type_is_a(self->type, parent));
292 }
293
294 static PyMethodDef _PyGTypeWrapper_methods[] = {
295     { "is_interface", (PyCFunction)_wrap_g_type_is_interface, METH_NOARGS },
296     { "is_classed", (PyCFunction)_wrap_g_type_is_classed, METH_NOARGS },
297     { "is_instantiatable", (PyCFunction)_wrap_g_type_is_instantiatable, METH_NOARGS },
298     { "is_derivable", (PyCFunction)_wrap_g_type_is_derivable, METH_NOARGS },
299     { "is_deep_derivable", (PyCFunction)_wrap_g_type_is_deep_derivable, METH_NOARGS },
300     { "is_abstract", (PyCFunction)_wrap_g_type_is_abstract, METH_NOARGS },
301     { "is_value_abstract", (PyCFunction)_wrap_g_type_is_value_abstract, METH_NOARGS },
302     { "is_value_type", (PyCFunction)_wrap_g_type_is_value_type, METH_NOARGS },
303     { "has_value_table", (PyCFunction)_wrap_g_type_has_value_table, METH_NOARGS },
304     { "from_name", (PyCFunction)_wrap_g_type_from_name, METH_VARARGS | METH_STATIC },
305     { "is_a", (PyCFunction)_wrap_g_type_is_a, METH_VARARGS },
306     { NULL,  0, 0 }
307 };
308
309 static int
310 pyg_type_wrapper_init(PyGTypeWrapper *self, PyObject *args, PyObject *kwargs)
311 {
312     static char *kwlist[] = { "object", NULL };
313     PyObject *py_object;
314     GType type;
315
316     if (!PyArg_ParseTupleAndKeywords(args, kwargs,
317                                      "O:GType.__init__",
318                                      kwlist, &py_object))
319         return -1;
320
321     if (!(type = pyg_type_from_object(py_object)))
322         return -1;
323
324     self->type = type;
325
326     return 0;
327 }
328
329 /**
330  * pyg_type_wrapper_new:
331  * type: a GType
332  *
333  * Creates a Python wrapper for a GType.
334  *
335  * Returns: the Python wrapper.
336  */
337 PyObject *
338 pyg_type_wrapper_new(GType type)
339 {
340     PyGTypeWrapper *self;
341
342     self = (PyGTypeWrapper *)PyObject_NEW(PyGTypeWrapper,
343                                           &PyGTypeWrapper_Type);
344     if (self == NULL)
345         return NULL;
346
347     self->type = type;
348     return (PyObject *)self;
349 }
350
351 /**
352  * pyg_type_from_object_strict:
353  * obj: a Python object
354  * strict: if set to TRUE, raises an exception if it can't perform the
355  *         conversion
356  *
357  * converts a python object to a GType.  If strict is set, raises an 
358  * exception if it can't perform the conversion, otherwise returns
359  * PY_TYPE_OBJECT.
360  *
361  * Returns: the corresponding GType, or 0 on error.
362  */
363
364 GType
365 pyg_type_from_object_strict(PyObject *obj, gboolean strict)
366 {
367     PyObject *gtype;
368     GType type;
369
370     /* NULL check */
371     if (!obj) {
372         PyErr_SetString(PyExc_TypeError, "can't get type from NULL object");
373         return 0;
374     }
375
376     /* map some standard types to primitive GTypes ... */
377     if (obj == Py_None)
378         return G_TYPE_NONE;
379     if (PyType_Check(obj)) {
380         PyTypeObject *tp = (PyTypeObject *)obj;
381
382         if (tp == &PYGLIB_PyLong_Type)
383             return G_TYPE_INT;
384         else if (tp == &PyBool_Type)
385             return G_TYPE_BOOLEAN;
386         else if (tp == &PyLong_Type)
387             return G_TYPE_LONG;
388         else if (tp == &PyFloat_Type)
389             return G_TYPE_DOUBLE;
390         else if (tp == &PYGLIB_PyUnicode_Type)
391             return G_TYPE_STRING;
392         else if (tp == &PyBaseObject_Type)
393             return PY_TYPE_OBJECT;
394     }
395
396     if (Py_TYPE(obj) == &PyGTypeWrapper_Type) {
397         return ((PyGTypeWrapper *)obj)->type;
398     }
399
400     /* handle strings */
401     if (PYGLIB_PyUnicode_Check(obj)) {
402         gchar *name = PYGLIB_PyUnicode_AsString(obj);
403
404         type = _pyg_type_from_name(name);
405         if (type != 0) {
406             return type;
407         }
408     }
409
410     /* finally, look for a __gtype__ attribute on the object */
411     gtype = PyObject_GetAttrString(obj, "__gtype__");
412
413     if (gtype) {
414         if (Py_TYPE(gtype) == &PyGTypeWrapper_Type) {
415             type = ((PyGTypeWrapper *)gtype)->type;
416             Py_DECREF(gtype);
417             return type;
418         }
419         Py_DECREF(gtype);
420     }
421
422     PyErr_Clear();
423
424     /* Some API like those that take GValues can hold a python object as
425      * a pointer.  This is potentially dangerous becuase everything is 
426      * passed in as a PyObject so we can't actually type check it.  Only
427      * fallback to PY_TYPE_OBJECT if strict checking is disabled
428      */
429     if (!strict)
430         return PY_TYPE_OBJECT;
431
432     PyErr_SetString(PyExc_TypeError, "could not get typecode from object");
433     return 0;
434 }
435
436 /**
437  * pyg_type_from_object:
438  * obj: a Python object
439  *
440  * converts a python object to a GType.  Raises an exception if it
441  * can't perform the conversion.
442  *
443  * Returns: the corresponding GType, or 0 on error.
444  */
445 GType
446 pyg_type_from_object(PyObject *obj)
447 {
448     /* Legacy call always defaults to strict type checking */
449     return pyg_type_from_object_strict(obj, TRUE);
450 }
451
452 /* -------------- GValue marshalling ------------------ */
453
454 /**
455  * pyg_enum_get_value:
456  * @enum_type: the GType of the flag.
457  * @obj: a Python object representing the flag value
458  * @val: a pointer to the location to store the integer representation of the flag.
459  *
460  * Converts a Python object to the integer equivalent.  The conversion
461  * will depend on the type of the Python object.  If the object is an
462  * integer, it is passed through directly.  If it is a string, it will
463  * be treated as a full or short enum name as defined in the GType.
464  *
465  * Returns: 0 on success or -1 on failure
466  */
467 gint
468 pyg_enum_get_value(GType enum_type, PyObject *obj, gint *val)
469 {
470     GEnumClass *eclass = NULL;
471     gint res = -1;
472
473     g_return_val_if_fail(val != NULL, -1);
474     if (!obj) {
475         *val = 0;
476         res = 0;
477     } else if (PYGLIB_PyLong_Check(obj)) {
478         *val = PYGLIB_PyLong_AsLong(obj);
479         res = 0;
480
481         if (PyObject_TypeCheck(obj, &PyGEnum_Type) && ((PyGEnum *) obj)->gtype != enum_type) {
482             g_warning("expected enumeration type %s, but got %s instead",
483                       g_type_name(enum_type),
484                       g_type_name(((PyGEnum *) obj)->gtype));
485         }
486     /* Dumb code duplication, but probably not worth it to have yet another macro. */
487     } else if (PyLong_Check(obj)) {
488         *val = PyLong_AsLong(obj);
489         res = 0;
490
491         if (PyObject_TypeCheck(obj, &PyGEnum_Type) && ((PyGEnum *) obj)->gtype != enum_type) {
492             g_warning("expected enumeration type %s, but got %s instead",
493                       g_type_name(enum_type),
494                       g_type_name(((PyGEnum *) obj)->gtype));
495         }
496     } else if (PYGLIB_PyUnicode_Check(obj)) {
497         GEnumValue *info;
498         char *str = PYGLIB_PyUnicode_AsString(obj);
499
500         if (enum_type != G_TYPE_NONE)
501             eclass = G_ENUM_CLASS(g_type_class_ref(enum_type));
502         else {
503             PyErr_SetString(PyExc_TypeError, "could not convert string to enum because there is no GType associated to look up the value");
504             res = -1;
505         }
506         info = g_enum_get_value_by_name(eclass, str);
507         g_type_class_unref(eclass);
508
509         if (!info)
510             info = g_enum_get_value_by_nick(eclass, str);
511         if (info) {
512             *val = info->value;
513             res = 0;
514         } else {
515             PyErr_SetString(PyExc_TypeError, "could not convert string");
516             res = -1;
517         }
518     } else {
519         PyErr_SetString(PyExc_TypeError,"enum values must be strings or ints");
520         res = -1;
521     }
522     return res;
523 }
524
525 /**
526  * pyg_flags_get_value:
527  * @flag_type: the GType of the flag.
528  * @obj: a Python object representing the flag value
529  * @val: a pointer to the location to store the integer representation of the flag.
530  *
531  * Converts a Python object to the integer equivalent.  The conversion
532  * will depend on the type of the Python object.  If the object is an
533  * integer, it is passed through directly.  If it is a string, it will
534  * be treated as a full or short flag name as defined in the GType.
535  * If it is a tuple, then the items are treated as strings and ORed
536  * together.
537  *
538  * Returns: 0 on success or -1 on failure
539  */
540 gint
541 pyg_flags_get_value(GType flag_type, PyObject *obj, gint *val)
542 {
543     GFlagsClass *fclass = NULL;
544     gint res = -1;
545
546     g_return_val_if_fail(val != NULL, -1);
547     if (!obj) {
548         *val = 0;
549         res = 0;
550     } else if (PYGLIB_PyLong_Check(obj)) {
551         *val = PYGLIB_PyLong_AsLong(obj);
552         res = 0;
553     } else if (PyLong_Check(obj)) {
554         *val = PyLong_AsLongLong(obj);
555         res = 0;
556     } else if (PYGLIB_PyUnicode_Check(obj)) {
557         GFlagsValue *info;
558         char *str = PYGLIB_PyUnicode_AsString(obj);
559
560         if (flag_type != G_TYPE_NONE)
561             fclass = G_FLAGS_CLASS(g_type_class_ref(flag_type));
562         else {
563             PyErr_SetString(PyExc_TypeError, "could not convert string to flag because there is no GType associated to look up the value");
564             res = -1;
565         }
566         info = g_flags_get_value_by_name(fclass, str);
567         g_type_class_unref(fclass);
568
569         if (!info)
570             info = g_flags_get_value_by_nick(fclass, str);
571         if (info) {
572             *val = info->value;
573             res = 0;
574         } else {
575             PyErr_SetString(PyExc_TypeError, "could not convert string");
576             res = -1;
577         }
578     } else if (PyTuple_Check(obj)) {
579         int i, len;
580
581         len = PyTuple_Size(obj);
582         *val = 0;
583         res = 0;
584
585         if (flag_type != G_TYPE_NONE)
586             fclass = G_FLAGS_CLASS(g_type_class_ref(flag_type));
587         else {
588             PyErr_SetString(PyExc_TypeError, "could not convert string to flag because there is no GType associated to look up the value");
589             res = -1;
590         }
591
592         for (i = 0; i < len; i++) {
593             PyObject *item = PyTuple_GetItem(obj, i);
594             char *str = PYGLIB_PyUnicode_AsString(item);
595             GFlagsValue *info = g_flags_get_value_by_name(fclass, str);
596
597             if (!info)
598                 info = g_flags_get_value_by_nick(fclass, str);
599             if (info) {
600                 *val |= info->value;
601             } else {
602                 PyErr_SetString(PyExc_TypeError, "could not convert string");
603                 res = -1;
604                 break;
605             }
606         }
607         g_type_class_unref(fclass);
608     } else {
609         PyErr_SetString(PyExc_TypeError,
610                         "flag values must be strings, ints, longs, or tuples");
611         res = -1;
612     }
613     return res;
614 }
615
616 typedef struct {
617     fromvaluefunc fromvalue;
618     tovaluefunc tovalue;
619 } PyGTypeMarshal;
620 static GQuark pyg_type_marshal_key = 0;
621
622 static PyGTypeMarshal *
623 pyg_type_lookup(GType type)
624 {
625     GType       ptype = type;
626     PyGTypeMarshal      *tm = NULL;
627
628     /* recursively lookup types */
629     while (ptype) {
630         if ((tm = g_type_get_qdata(ptype, pyg_type_marshal_key)) != NULL)
631             break;
632         ptype = g_type_parent(ptype);
633     }
634     return tm;
635 }
636
637 /**
638  * pyg_register_gtype_custom:
639  * @gtype: the GType for the new type
640  * @from_func: a function to convert GValues to Python objects
641  * @to_func: a function to convert Python objects to GValues
642  *
643  * In order to handle specific conversion of gboxed types or new
644  * fundamental types, you may use this function to register conversion
645  * handlers.
646  */
647
648 void
649 pyg_register_gtype_custom(GType gtype,
650                           fromvaluefunc from_func,
651                           tovaluefunc to_func)
652 {
653     PyGTypeMarshal *tm;
654
655     if (!pyg_type_marshal_key)
656         pyg_type_marshal_key = g_quark_from_static_string("PyGType::marshal");
657
658     tm = g_new(PyGTypeMarshal, 1);
659     tm->fromvalue = from_func;
660     tm->tovalue = to_func;
661     g_type_set_qdata(gtype, pyg_type_marshal_key, tm);
662 }
663
664 static int
665 pyg_value_array_from_pyobject(GValue *value,
666                               PyObject *obj,
667                               const GParamSpecValueArray *pspec)
668 {
669     int len;
670     GValueArray *value_array;
671     int i;
672
673     len = PySequence_Length(obj);
674     if (len == -1) {
675         PyErr_Clear();
676         return -1;
677     }
678
679     if (pspec && pspec->fixed_n_elements > 0 && len != pspec->fixed_n_elements)
680         return -1;
681
682     value_array = g_value_array_new(len);
683
684     for (i = 0; i < len; ++i) {
685         PyObject *item = PySequence_GetItem(obj, i);
686         GType type;
687         GValue item_value = { 0, };
688         int status;
689
690         if (! item) {
691             PyErr_Clear();
692             g_value_array_free(value_array);
693             return -1;
694         }
695
696         if (pspec && pspec->element_spec)
697             type = G_PARAM_SPEC_VALUE_TYPE(pspec->element_spec);
698         else if (item == Py_None)
699             type = G_TYPE_POINTER; /* store None as NULL */
700         else {
701             type = pyg_type_from_object((PyObject*)Py_TYPE(item));
702             if (! type) {
703                 PyErr_Clear();
704                 g_value_array_free(value_array);
705                 Py_DECREF(item);
706                 return -1;
707             }
708         }
709
710         g_value_init(&item_value, type);
711         status = (pspec && pspec->element_spec)
712             ? pyg_param_gvalue_from_pyobject(&item_value, item, pspec->element_spec)
713             : pyg_value_from_pyobject(&item_value, item);
714         Py_DECREF(item);
715
716         if (status == -1) {
717             g_value_array_free(value_array);
718             g_value_unset(&item_value);
719             return -1;
720         }
721
722         g_value_array_append(value_array, &item_value);
723         g_value_unset(&item_value);
724     }
725
726     g_value_take_boxed(value, value_array);
727     return 0;
728 }
729
730 /**
731  * pyg_value_from_pyobject:
732  * @value: the GValue object to store the converted value in.
733  * @obj: the Python object to convert.
734  *
735  * This function converts a Python object and stores the result in a
736  * GValue.  The GValue must be initialised in advance with
737  * g_value_init().  If the Python object can't be converted to the
738  * type of the GValue, then an error is returned.
739  *
740  * Returns: 0 on success, -1 on error.
741  */
742 int
743 pyg_value_from_pyobject(GValue *value, PyObject *obj)
744 {
745     PyObject *tmp;
746
747     switch (G_TYPE_FUNDAMENTAL(G_VALUE_TYPE(value))) {
748     case G_TYPE_INTERFACE:
749         /* we only handle interface types that have a GObject prereq */
750         if (g_type_is_a(G_VALUE_TYPE(value), G_TYPE_OBJECT)) {
751             if (obj == Py_None)
752                 g_value_set_object(value, NULL);
753             else {
754                 if (!PyObject_TypeCheck(obj, &PyGObject_Type)) {
755                     return -1;
756                 }
757                 if (!G_TYPE_CHECK_INSTANCE_TYPE(pygobject_get(obj),
758                                                 G_VALUE_TYPE(value))) {
759                     return -1;
760                 }
761                 g_value_set_object(value, pygobject_get(obj));
762             }
763         } else {
764             return -1;
765         }
766         break;
767     case G_TYPE_CHAR:
768 #if PY_VERSION_HEX < 0x03000000
769         if (PyString_Check(obj)) {
770             g_value_set_char(value, PyString_AsString(obj)[0]);
771         } else
772 #endif
773         if (PyUnicode_Check(obj)) {
774             tmp = PyUnicode_AsUTF8String(obj);
775             g_value_set_char(value, PYGLIB_PyBytes_AsString(tmp)[0]);
776             Py_DECREF(tmp);
777         } else {
778             PyErr_Clear();
779             return -1;
780         }
781
782         break;
783     case G_TYPE_UCHAR:
784         if (PYGLIB_PyLong_Check(obj)) {
785             glong val;
786             val = PYGLIB_PyLong_AsLong(obj);
787             if (val >= 0 && val <= 255)
788               g_value_set_uchar(value, (guchar)PYGLIB_PyLong_AsLong (obj));
789             else
790               return -1;
791 #if PY_VERSION_HEX < 0x03000000
792         } else if (PyString_Check(obj)) {
793             g_value_set_uchar(value, PyString_AsString(obj)[0]);
794 #endif
795         } else if (PyUnicode_Check(obj)) {
796             tmp = PyUnicode_AsUTF8String(obj);
797             g_value_set_uchar(value, PYGLIB_PyBytes_AsString(tmp)[0]);
798             Py_DECREF(tmp);
799         } else {
800             PyErr_Clear();
801             return -1;
802         }
803         break;
804     case G_TYPE_BOOLEAN:
805         g_value_set_boolean(value, PyObject_IsTrue(obj));
806         break;
807     case G_TYPE_INT:
808         g_value_set_int(value, PYGLIB_PyLong_AsLong(obj));
809         break;
810     case G_TYPE_UINT:
811         {
812             if (PYGLIB_PyLong_Check(obj)) {
813                 glong val;
814
815                 val = PYGLIB_PyLong_AsLong(obj);
816                 if (val >= 0 && val <= G_MAXUINT)
817                     g_value_set_uint(value, (guint)val);
818                 else
819                     return -1;
820             } else {
821                 g_value_set_uint(value, PyLong_AsUnsignedLong(obj));
822             }
823         }
824         break;
825     case G_TYPE_LONG:
826         g_value_set_long(value, PYGLIB_PyLong_AsLong(obj));
827         break;
828     case G_TYPE_ULONG:
829 #if PY_VERSION_HEX < 0x03000000
830         if (PyInt_Check(obj)) {
831             long val;
832
833             val = PYGLIB_PyLong_AsLong(obj);
834             if (val < 0) {
835                 PyErr_SetString(PyExc_OverflowError, "negative value not allowed for uint64 property");
836                 return -1;
837             }
838             g_value_set_ulong(value, (gulong)val);
839         } else
840 #endif
841         if (PyLong_Check(obj))
842             g_value_set_ulong(value, PyLong_AsUnsignedLong(obj));
843         else
844             return -1;
845         break;
846     case G_TYPE_INT64:
847         g_value_set_int64(value, PyLong_AsLongLong(obj));
848         break;
849     case G_TYPE_UINT64:
850 #if PY_VERSION_HEX < 0x03000000
851         if (PyInt_Check(obj)) {
852             long v = PyInt_AsLong(obj);
853             if (v < 0) {
854                 PyErr_SetString(PyExc_OverflowError, "negative value not allowed for uint64 property");
855                 return -1;
856             }
857             g_value_set_uint64(value, v);
858         } else
859 #endif
860         if (PyLong_Check(obj))
861             g_value_set_uint64(value, PyLong_AsUnsignedLongLong(obj));
862         else
863             return -1;
864         break;
865     case G_TYPE_ENUM:
866         {
867             gint val = 0;
868             if (pyg_enum_get_value(G_VALUE_TYPE(value), obj, &val) < 0) {
869                 PyErr_Clear();
870                 return -1;
871             }
872             g_value_set_enum(value, val);
873         }
874         break;
875     case G_TYPE_FLAGS:
876         {
877             gint val = 0;
878             if (pyg_flags_get_value(G_VALUE_TYPE(value), obj, &val) < 0) {
879                 PyErr_Clear();
880                 return -1;
881             }
882             g_value_set_flags(value, val);
883         }
884         break;
885     case G_TYPE_FLOAT:
886         g_value_set_float(value, PyFloat_AsDouble(obj));
887         break;
888     case G_TYPE_DOUBLE:
889         g_value_set_double(value, PyFloat_AsDouble(obj));
890         break;
891     case G_TYPE_STRING:
892         if (obj == Py_None) {
893             g_value_set_string(value, NULL);
894         } else {
895             PyObject* tmp_str = PyObject_Str(obj);
896             if (tmp_str == NULL) {
897                 PyErr_Clear();
898                 if (PyUnicode_Check(obj)) {
899                     tmp = PyUnicode_AsUTF8String(obj);
900                     g_value_set_string(value, PYGLIB_PyBytes_AsString(tmp));
901                     Py_DECREF(tmp);
902                 } else {
903                     return -1;
904                 }
905             } else {
906 #if PY_VERSION_HEX < 0x03000000
907                g_value_set_string(value, PyString_AsString(tmp_str));
908 #else
909                tmp = PyUnicode_AsUTF8String(tmp_str);
910                g_value_set_string(value, PyBytes_AsString(tmp));
911                Py_DECREF(tmp);
912 #endif
913             }
914             Py_XDECREF(tmp_str);
915         }
916         break;
917     case G_TYPE_POINTER:
918         if (obj == Py_None)
919             g_value_set_pointer(value, NULL);
920         else if (PyObject_TypeCheck(obj, &PyGPointer_Type) &&
921                    G_VALUE_HOLDS(value, ((PyGPointer *)obj)->gtype))
922             g_value_set_pointer(value, pyg_pointer_get(obj, gpointer));
923         else if (PYGLIB_CPointer_Check(obj))
924             g_value_set_pointer(value, PYGLIB_CPointer_GetPointer(obj, NULL));
925         else
926             return -1;
927         break;
928     case G_TYPE_BOXED: {
929         PyGTypeMarshal *bm;
930
931         if (obj == Py_None)
932             g_value_set_boxed(value, NULL);
933         else if (G_VALUE_HOLDS(value, PY_TYPE_OBJECT))
934             g_value_set_boxed(value, obj);
935         else if (PyObject_TypeCheck(obj, &PyGBoxed_Type) &&
936                    G_VALUE_HOLDS(value, ((PyGBoxed *)obj)->gtype))
937             g_value_set_boxed(value, pyg_boxed_get(obj, gpointer));
938         else if (G_VALUE_HOLDS(value, G_TYPE_VALUE)) {
939             GType type;
940             GValue *n_value;
941
942             type = pyg_type_from_object((PyObject*)Py_TYPE(obj));
943             if (G_UNLIKELY (! type)) {
944                 PyErr_Clear();
945                 return -1;
946             }
947             n_value = g_new0 (GValue, 1);
948             g_value_init (n_value, type);
949             g_value_take_boxed (value, n_value);
950             return pyg_value_from_pyobject (n_value, obj);
951         }
952         else if (PySequence_Check(obj) &&
953                    G_VALUE_HOLDS(value, G_TYPE_VALUE_ARRAY))
954             return pyg_value_array_from_pyobject(value, obj, NULL);
955         else if (PYGLIB_PyUnicode_Check(obj) &&
956                  G_VALUE_HOLDS(value, G_TYPE_GSTRING)) {
957             GString *string;
958             char *buffer;
959             Py_ssize_t len;
960             if (PYGLIB_PyUnicode_AsStringAndSize(obj, &buffer, &len))
961                 return -1;
962             string = g_string_new_len(buffer, len);
963             g_value_set_boxed(value, string);
964             g_string_free (string, TRUE);
965             break;
966         }
967         else if ((bm = pyg_type_lookup(G_VALUE_TYPE(value))) != NULL)
968             return bm->tovalue(value, obj);
969         else if (PYGLIB_CPointer_Check(obj))
970             g_value_set_boxed(value, PYGLIB_CPointer_GetPointer(obj, NULL));
971         else
972             return -1;
973         break;
974     }
975     case G_TYPE_PARAM:
976         if (PyGParamSpec_Check(obj))
977             g_value_set_param(value, PYGLIB_CPointer_GetPointer(obj, NULL));
978         else
979             return -1;
980         break;
981     case G_TYPE_OBJECT:
982         if (obj == Py_None) {
983             g_value_set_object(value, NULL);
984         } else if (PyObject_TypeCheck(obj, &PyGObject_Type) &&
985                    G_TYPE_CHECK_INSTANCE_TYPE(pygobject_get(obj),
986                                               G_VALUE_TYPE(value))) {
987             g_value_set_object(value, pygobject_get(obj));
988         } else
989             return -1;
990         break;
991     default:
992         {
993             PyGTypeMarshal *bm;
994             if ((bm = pyg_type_lookup(G_VALUE_TYPE(value))) != NULL)
995                 return bm->tovalue(value, obj);
996             break;
997         }
998     }
999     if (PyErr_Occurred()) {
1000         g_value_unset(value);
1001         PyErr_Clear();
1002         return -1;
1003     }
1004     return 0;
1005 }
1006
1007 /**
1008  * pyg_value_as_pyobject:
1009  * @value: the GValue object.
1010  * @copy_boxed: true if boxed values should be copied.
1011  *
1012  * This function creates/returns a Python wrapper object that
1013  * represents the GValue passed as an argument.
1014  *
1015  * Returns: a PyObject representing the value.
1016  */
1017 PyObject *
1018 pyg_value_as_pyobject(const GValue *value, gboolean copy_boxed)
1019 {
1020     gchar buf[128];
1021
1022     switch (G_TYPE_FUNDAMENTAL(G_VALUE_TYPE(value))) {
1023     case G_TYPE_INTERFACE:
1024         if (g_type_is_a(G_VALUE_TYPE(value), G_TYPE_OBJECT))
1025             return pygobject_new_sunk(g_value_get_object(value));
1026         else
1027             break;
1028     case G_TYPE_CHAR: {
1029         gint8 val = g_value_get_char(value);
1030         return PYGLIB_PyUnicode_FromStringAndSize((char *)&val, 1);
1031     }
1032     case G_TYPE_UCHAR: {
1033         guint8 val = g_value_get_uchar(value);
1034         return PYGLIB_PyBytes_FromStringAndSize((char *)&val, 1);
1035     }
1036     case G_TYPE_BOOLEAN: {
1037         return PyBool_FromLong(g_value_get_boolean(value));
1038     }
1039     case G_TYPE_INT:
1040         return PYGLIB_PyLong_FromLong(g_value_get_int(value));
1041     case G_TYPE_UINT:
1042         {
1043             /* in Python, the Int object is backed by a long.  If a
1044                long can hold the whole value of an unsigned int, use
1045                an Int.  Otherwise, use a Long object to avoid overflow.
1046                This matches the ULongArg behavior in codegen/argtypes.h */
1047 #if (G_MAXUINT <= G_MAXLONG)
1048             return PYGLIB_PyLong_FromLong((glong) g_value_get_uint(value));
1049 #else
1050             return PyLong_FromUnsignedLong((gulong) g_value_get_uint(value));
1051 #endif
1052         }
1053     case G_TYPE_LONG:
1054         return PYGLIB_PyLong_FromLong(g_value_get_long(value));
1055     case G_TYPE_ULONG:
1056         {
1057             gulong val = g_value_get_ulong(value);
1058
1059             if (val <= G_MAXLONG)
1060                 return PYGLIB_PyLong_FromLong((glong) val);
1061             else
1062                 return PyLong_FromUnsignedLong(val);
1063         }
1064     case G_TYPE_INT64:
1065         {
1066             gint64 val = g_value_get_int64(value);
1067
1068             if (G_MINLONG <= val && val <= G_MAXLONG)
1069                 return PYGLIB_PyLong_FromLong((glong) val);
1070             else
1071                 return PyLong_FromLongLong(val);
1072         }
1073     case G_TYPE_UINT64:
1074         {
1075             guint64 val = g_value_get_uint64(value);
1076
1077             if (val <= G_MAXLONG)
1078                 return PYGLIB_PyLong_FromLong((glong) val);
1079             else
1080                 return PyLong_FromUnsignedLongLong(val);
1081         }
1082     case G_TYPE_ENUM:
1083         return pyg_enum_from_gtype(G_VALUE_TYPE(value), g_value_get_enum(value));
1084     case G_TYPE_FLAGS:
1085         return pyg_flags_from_gtype(G_VALUE_TYPE(value), g_value_get_flags(value));
1086     case G_TYPE_FLOAT:
1087         return PyFloat_FromDouble(g_value_get_float(value));
1088     case G_TYPE_DOUBLE:
1089         return PyFloat_FromDouble(g_value_get_double(value));
1090     case G_TYPE_STRING:
1091         {
1092             const gchar *str = g_value_get_string(value);
1093
1094             if (str)
1095                 return PYGLIB_PyUnicode_FromString(str);
1096             Py_INCREF(Py_None);
1097             return Py_None;
1098         }
1099     case G_TYPE_POINTER:
1100         return pyg_pointer_new(G_VALUE_TYPE(value),
1101                                g_value_get_pointer(value));
1102     case G_TYPE_BOXED: {
1103         PyGTypeMarshal *bm;
1104
1105         if (G_VALUE_HOLDS(value, PY_TYPE_OBJECT)) {
1106             PyObject *ret = (PyObject *)g_value_dup_boxed(value);
1107             if (ret == NULL) {
1108                 Py_INCREF(Py_None);
1109                 return Py_None;
1110             }
1111             return ret;
1112         } else if (G_VALUE_HOLDS(value, G_TYPE_VALUE)) {
1113             GValue *n_value = g_value_get_boxed (value);
1114             return pyg_value_as_pyobject(n_value, copy_boxed);
1115         } else if (G_VALUE_HOLDS(value, G_TYPE_VALUE_ARRAY)) {
1116             GValueArray *array = (GValueArray *) g_value_get_boxed(value);
1117             PyObject *ret = PyList_New(array->n_values);
1118             int i;
1119             for (i = 0; i < array->n_values; ++i)
1120                 PyList_SET_ITEM(ret, i, pyg_value_as_pyobject
1121                                 (array->values + i, copy_boxed));
1122             return ret;
1123         } else if (G_VALUE_HOLDS(value, G_TYPE_GSTRING)) {
1124             GString *string = (GString *) g_value_get_boxed(value);
1125             PyObject *ret = PYGLIB_PyUnicode_FromStringAndSize(string->str, string->len);
1126             return ret;
1127         }
1128         bm = pyg_type_lookup(G_VALUE_TYPE(value));
1129         if (bm) {
1130             return bm->fromvalue(value);
1131         } else {
1132             if (copy_boxed)
1133                 return pyg_boxed_new(G_VALUE_TYPE(value),
1134                                      g_value_get_boxed(value), TRUE, TRUE);
1135             else
1136                 return pyg_boxed_new(G_VALUE_TYPE(value),
1137                                      g_value_get_boxed(value),FALSE,FALSE);
1138         }
1139     }
1140     case G_TYPE_PARAM:
1141         return pyg_param_spec_new(g_value_get_param(value));
1142     case G_TYPE_OBJECT:
1143         return pygobject_new_sunk(g_value_get_object(value));
1144     default:
1145         {
1146             PyGTypeMarshal *bm;
1147             if ((bm = pyg_type_lookup(G_VALUE_TYPE(value))))
1148                 return bm->fromvalue(value);
1149             break;
1150         }
1151     }
1152     g_snprintf(buf, sizeof(buf), "unknown type %s",
1153                g_type_name(G_VALUE_TYPE(value)));
1154     PyErr_SetString(PyExc_TypeError, buf);
1155     return NULL;
1156 }
1157
1158 /* -------------- PyGClosure ----------------- */
1159
1160 static void
1161 pyg_closure_invalidate(gpointer data, GClosure *closure)
1162 {
1163     PyGClosure *pc = (PyGClosure *)closure;
1164     PyGILState_STATE state;
1165
1166     state = pyglib_gil_state_ensure();
1167     Py_XDECREF(pc->callback);
1168     Py_XDECREF(pc->extra_args);
1169     Py_XDECREF(pc->swap_data);
1170     pyglib_gil_state_release(state);
1171
1172     pc->callback = NULL;
1173     pc->extra_args = NULL;
1174     pc->swap_data = NULL;
1175 }
1176
1177 static void
1178 pyg_closure_marshal(GClosure *closure,
1179                     GValue *return_value,
1180                     guint n_param_values,
1181                     const GValue *param_values,
1182                     gpointer invocation_hint,
1183                     gpointer marshal_data)
1184 {
1185     PyGILState_STATE state;
1186     PyGClosure *pc = (PyGClosure *)closure;
1187     PyObject *params, *ret;
1188     guint i;
1189
1190     state = pyglib_gil_state_ensure();
1191
1192     /* construct Python tuple for the parameter values */
1193     params = PyTuple_New(n_param_values);
1194     for (i = 0; i < n_param_values; i++) {
1195         /* swap in a different initial data for connect_object() */
1196         if (i == 0 && G_CCLOSURE_SWAP_DATA(closure)) {
1197             g_return_if_fail(pc->swap_data != NULL);
1198             Py_INCREF(pc->swap_data);
1199             PyTuple_SetItem(params, 0, pc->swap_data);
1200         } else {
1201             PyObject *item = pyg_value_as_pyobject(&param_values[i], FALSE);
1202
1203             /* error condition */
1204             if (!item) {
1205                 goto out;
1206             }
1207             PyTuple_SetItem(params, i, item);
1208         }
1209     }
1210     /* params passed to function may have extra arguments */
1211     if (pc->extra_args) {
1212         PyObject *tuple = params;
1213         params = PySequence_Concat(tuple, pc->extra_args);
1214         Py_DECREF(tuple);
1215     }
1216     ret = PyObject_CallObject(pc->callback, params);
1217     if (ret == NULL) {
1218         if (pc->exception_handler)
1219             pc->exception_handler(return_value, n_param_values, param_values);
1220         else
1221             PyErr_Print();
1222         goto out;
1223     }
1224
1225     if (return_value && pyg_value_from_pyobject(return_value, ret) != 0) {
1226         PyErr_SetString(PyExc_TypeError,
1227                         "can't convert return value to desired type");
1228
1229         if (pc->exception_handler)
1230             pc->exception_handler(return_value, n_param_values, param_values);
1231         else
1232             PyErr_Print();
1233     }
1234     Py_DECREF(ret);
1235
1236  out:
1237     Py_DECREF(params);
1238     pyglib_gil_state_release(state);
1239 }
1240
1241 /**
1242  * pyg_closure_new:
1243  * callback: a Python callable object
1244  * extra_args: a tuple of extra arguments, or None/NULL.
1245  * swap_data: an alternative python object to pass first.
1246  *
1247  * Creates a GClosure wrapping a Python callable and optionally a set
1248  * of additional function arguments.  This is needed to attach python
1249  * handlers to signals, for instance.
1250  *
1251  * Returns: the new closure.
1252  */
1253 GClosure *
1254 pyg_closure_new(PyObject *callback, PyObject *extra_args, PyObject *swap_data)
1255 {
1256     GClosure *closure;
1257
1258     g_return_val_if_fail(callback != NULL, NULL);
1259     closure = g_closure_new_simple(sizeof(PyGClosure), NULL);
1260     g_closure_add_invalidate_notifier(closure, NULL, pyg_closure_invalidate);
1261     g_closure_set_marshal(closure, pyg_closure_marshal);
1262     Py_INCREF(callback);
1263     ((PyGClosure *)closure)->callback = callback;
1264     if (extra_args && extra_args != Py_None) {
1265         Py_INCREF(extra_args);
1266         if (!PyTuple_Check(extra_args)) {
1267             PyObject *tmp = PyTuple_New(1);
1268             PyTuple_SetItem(tmp, 0, extra_args);
1269             extra_args = tmp;
1270         }
1271         ((PyGClosure *)closure)->extra_args = extra_args;
1272     }
1273     if (swap_data) {
1274         Py_INCREF(swap_data);
1275         ((PyGClosure *)closure)->swap_data = swap_data;
1276         closure->derivative_flag = TRUE;
1277     }
1278     return closure;
1279 }
1280
1281 /**
1282  * pyg_closure_set_exception_handler:
1283  * @closure: a closure created with pyg_closure_new()
1284  * @handler: the handler to call when an exception occurs or NULL for none
1285  *
1286  * Sets the handler to call when an exception occurs during closure invocation.
1287  * The handler is responsible for providing a proper return value to the
1288  * closure invocation. If @handler is %NULL, the default handler will be used.
1289  * The default handler prints the exception to stderr and doesn't touch the
1290  * closure's return value.
1291  */
1292 void
1293 pyg_closure_set_exception_handler(GClosure *closure,
1294                                   PyClosureExceptionHandler handler)
1295 {
1296     PyGClosure *pygclosure;
1297
1298     g_return_if_fail(closure != NULL);
1299
1300     pygclosure = (PyGClosure *)closure;
1301     pygclosure->exception_handler = handler;
1302 }
1303 /* -------------- PySignalClassClosure ----------------- */
1304 /* a closure used for the `class closure' of a signal.  As this gets
1305  * all the info from the first argument to the closure and the
1306  * invocation hint, we can have a single closure that handles all
1307  * class closure cases.  We call a method by the name of the signal
1308  * with "do_" prepended.
1309  *
1310  *  We also remove the first argument from the * param list, as it is
1311  *  the instance object, which is passed * implicitly to the method
1312  *  object. */
1313
1314 static void
1315 pyg_signal_class_closure_marshal(GClosure *closure,
1316                                  GValue *return_value,
1317                                  guint n_param_values,
1318                                  const GValue *param_values,
1319                                  gpointer invocation_hint,
1320                                  gpointer marshal_data)
1321 {
1322     PyGILState_STATE state;
1323     GObject *object;
1324     PyObject *object_wrapper;
1325     GSignalInvocationHint *hint = (GSignalInvocationHint *)invocation_hint;
1326     gchar *method_name, *tmp;
1327     PyObject *method;
1328     PyObject *params, *ret;
1329     guint i, len;
1330
1331     state = pyglib_gil_state_ensure();
1332
1333     g_return_if_fail(invocation_hint != NULL);
1334     /* get the object passed as the first argument to the closure */
1335     object = g_value_get_object(&param_values[0]);
1336     g_return_if_fail(object != NULL && G_IS_OBJECT(object));
1337
1338     /* get the wrapper for this object */
1339     object_wrapper = pygobject_new_sunk(object);
1340     g_return_if_fail(object_wrapper != NULL);
1341
1342     /* construct method name for this class closure */
1343     method_name = g_strconcat("do_", g_signal_name(hint->signal_id), NULL);
1344
1345     /* convert dashes to underscores.  For some reason, g_signal_name
1346      * seems to convert all the underscores in the signal name to
1347        dashes??? */
1348     for (tmp = method_name; *tmp != '\0'; tmp++)
1349         if (*tmp == '-') *tmp = '_';
1350
1351     method = PyObject_GetAttrString(object_wrapper, method_name);
1352     g_free(method_name);
1353
1354     if (!method) {
1355         PyErr_Clear();
1356         Py_DECREF(object_wrapper);
1357         pyglib_gil_state_release(state);
1358         return;
1359     }
1360     Py_DECREF(object_wrapper);
1361
1362     /* construct Python tuple for the parameter values; don't copy boxed values
1363        initially because we'll check after the call to see if a copy is needed. */
1364     params = PyTuple_New(n_param_values - 1);
1365     for (i = 1; i < n_param_values; i++) {
1366         PyObject *item = pyg_value_as_pyobject(&param_values[i], FALSE);
1367
1368         /* error condition */
1369         if (!item) {
1370             Py_DECREF(params);
1371             pyglib_gil_state_release(state);
1372             return;
1373         }
1374         PyTuple_SetItem(params, i - 1, item);
1375     }
1376
1377     ret = PyObject_CallObject(method, params);
1378
1379     /* Copy boxed values if others ref them, this needs to be done regardless of
1380        exception status. */
1381     len = PyTuple_Size(params);
1382     for (i = 0; i < len; i++) {
1383         PyObject *item = PyTuple_GetItem(params, i);
1384         if (item != NULL && PyObject_TypeCheck(item, &PyGBoxed_Type)
1385             && item->ob_refcnt != 1) {
1386             PyGBoxed* boxed_item = (PyGBoxed*)item;
1387             if (!boxed_item->free_on_dealloc) {
1388                 boxed_item->boxed = g_boxed_copy(boxed_item->gtype, boxed_item->boxed);
1389                 boxed_item->free_on_dealloc = TRUE;
1390             }
1391         }
1392     }
1393
1394     if (ret == NULL) {
1395         PyErr_Print();
1396         Py_DECREF(method);
1397         Py_DECREF(params);
1398         pyglib_gil_state_release(state);
1399         return;
1400     }
1401     Py_DECREF(method);
1402     Py_DECREF(params);
1403     if (return_value)
1404         pyg_value_from_pyobject(return_value, ret);
1405     Py_DECREF(ret);
1406     pyglib_gil_state_release(state);
1407 }
1408
1409 /**
1410  * pyg_signal_class_closure_get:
1411  *
1412  * Returns the GClosure used for the class closure of signals.  When
1413  * called, it will invoke the method do_signalname (for the signal
1414  * "signalname").
1415  *
1416  * Returns: the closure.
1417  */
1418 GClosure *
1419 pyg_signal_class_closure_get(void)
1420 {
1421     static GClosure *closure;
1422
1423     if (closure == NULL) {
1424         closure = g_closure_new_simple(sizeof(GClosure), NULL);
1425         g_closure_set_marshal(closure, pyg_signal_class_closure_marshal);
1426
1427         g_closure_ref(closure);
1428         g_closure_sink(closure);
1429     }
1430     return closure;
1431 }
1432
1433 GClosure *
1434 gclosure_from_pyfunc(PyGObject *object, PyObject *func)
1435 {
1436     GSList *l;
1437     PyGObjectData *inst_data;
1438     inst_data = pyg_object_peek_inst_data(object->obj);
1439     if (inst_data) {
1440         for (l = inst_data->closures; l; l = l->next) {
1441             PyGClosure *pyclosure = l->data;
1442             int res = PyObject_RichCompareBool(pyclosure->callback, func, Py_EQ);
1443             if (res == -1) {
1444                 PyErr_Clear(); // Is there anything else to do?
1445             } else if (res) {
1446                 return (GClosure*)pyclosure;
1447             }
1448         }
1449     }
1450     return NULL;
1451 }
1452
1453 /* ----- __doc__ descriptor for GObject and GInterface ----- */
1454
1455 static void
1456 object_doc_dealloc(PyObject *self)
1457 {
1458     PyObject_FREE(self);
1459 }
1460
1461 /* append information about signals of a particular gtype */
1462 static void
1463 add_signal_docs(GType gtype, GString *string)
1464 {
1465     GTypeClass *class = NULL;
1466     guint *signal_ids, n_ids = 0, i;
1467
1468     if (G_TYPE_IS_CLASSED(gtype))
1469         class = g_type_class_ref(gtype);
1470     signal_ids = g_signal_list_ids(gtype, &n_ids);
1471
1472     if (n_ids > 0) {
1473         g_string_append_printf(string, "Signals from %s:\n",
1474                                g_type_name(gtype));
1475
1476         for (i = 0; i < n_ids; i++) {
1477             GSignalQuery query;
1478             guint j;
1479
1480             g_signal_query(signal_ids[i], &query);
1481
1482             g_string_append(string, "  ");
1483             g_string_append(string, query.signal_name);
1484             g_string_append(string, " (");
1485             for (j = 0; j < query.n_params; j++) {
1486                 g_string_append(string, g_type_name(query.param_types[j]));
1487                 if (j != query.n_params - 1)
1488                     g_string_append(string, ", ");
1489             }
1490             g_string_append(string, ")");
1491             if (query.return_type && query.return_type != G_TYPE_NONE) {
1492                 g_string_append(string, " -> ");
1493                 g_string_append(string, g_type_name(query.return_type));
1494             }
1495             g_string_append(string, "\n");
1496         }
1497         g_free(signal_ids);
1498         g_string_append(string, "\n");
1499     }
1500     if (class)
1501         g_type_class_unref(class);
1502 }
1503
1504 static void
1505 add_property_docs(GType gtype, GString *string)
1506 {
1507     GObjectClass *class;
1508     GParamSpec **props;
1509     guint n_props = 0, i;
1510     gboolean has_prop = FALSE;
1511     G_CONST_RETURN gchar *blurb=NULL;
1512
1513     class = g_type_class_ref(gtype);
1514     props = g_object_class_list_properties(class, &n_props);
1515
1516     for (i = 0; i < n_props; i++) {
1517         if (props[i]->owner_type != gtype)
1518             continue; /* these are from a parent type */
1519
1520         /* print out the heading first */
1521         if (!has_prop) {
1522             g_string_append_printf(string, "Properties from %s:\n",
1523                                    g_type_name(gtype));
1524             has_prop = TRUE;
1525         }
1526         g_string_append_printf(string, "  %s -> %s: %s\n",
1527                                g_param_spec_get_name(props[i]),
1528                                g_type_name(props[i]->value_type),
1529                                g_param_spec_get_nick(props[i]));
1530
1531         /* g_string_append_printf crashes on win32 if the third
1532            argument is NULL. */
1533         blurb=g_param_spec_get_blurb(props[i]);
1534         if (blurb)
1535             g_string_append_printf(string, "    %s\n",blurb);
1536     }
1537     g_free(props);
1538     if (has_prop)
1539         g_string_append(string, "\n");
1540     g_type_class_unref(class);
1541 }
1542
1543 static PyObject *
1544 object_doc_descr_get(PyObject *self, PyObject *obj, PyObject *type)
1545 {
1546     GType gtype = 0;
1547     GString *string;
1548     PyObject *pystring;
1549
1550     if (obj && pygobject_check(obj, &PyGObject_Type)) {
1551         gtype = G_OBJECT_TYPE(pygobject_get(obj));
1552         if (!gtype)
1553             PyErr_SetString(PyExc_RuntimeError, "could not get object type");
1554     } else {
1555         gtype = pyg_type_from_object(type);
1556     }
1557     if (!gtype)
1558         return NULL;
1559
1560     string = g_string_new_len(NULL, 512);
1561
1562     if (g_type_is_a(gtype, G_TYPE_INTERFACE))
1563         g_string_append_printf(string, "Interface %s\n\n", g_type_name(gtype));
1564     else if (g_type_is_a(gtype, G_TYPE_OBJECT))
1565         g_string_append_printf(string, "Object %s\n\n", g_type_name(gtype));
1566     else
1567         g_string_append_printf(string, "%s\n\n", g_type_name(gtype));
1568
1569     if (((PyTypeObject *) type)->tp_doc)
1570         g_string_append_printf(string, "%s\n\n", ((PyTypeObject *) type)->tp_doc);
1571
1572     if (g_type_is_a(gtype, G_TYPE_OBJECT)) {
1573         GType parent = G_TYPE_OBJECT;
1574         GArray *parents = g_array_new(FALSE, FALSE, sizeof(GType));
1575         int iparent;
1576
1577         while (parent) {
1578             g_array_append_val(parents, parent);
1579             parent = g_type_next_base(gtype, parent);
1580         }
1581
1582         for (iparent = parents->len - 1; iparent >= 0; --iparent) {
1583             GType *interfaces;
1584             guint n_interfaces, i;
1585
1586             parent = g_array_index(parents, GType, iparent);
1587             add_signal_docs(parent, string);
1588             add_property_docs(parent, string);
1589
1590             /* add docs for implemented interfaces */
1591             interfaces = g_type_interfaces(parent, &n_interfaces);
1592             for (i = 0; i < n_interfaces; i++)
1593                 add_signal_docs(interfaces[i], string);
1594             g_free(interfaces);
1595         }
1596         g_array_free(parents, TRUE);
1597     }
1598
1599     pystring = PYGLIB_PyUnicode_FromStringAndSize(string->str, string->len);
1600     g_string_free(string, TRUE);
1601     return pystring;
1602 }
1603
1604 PYGLIB_DEFINE_TYPE("gobject.GObject.__doc__", PyGObjectDoc_Type, PyObject);
1605
1606 /**
1607  * pyg_object_descr_doc_get:
1608  *
1609  * Returns an object intended to be the __doc__ attribute of GObject
1610  * wrappers.  When read in the context of the object it will return
1611  * some documentation about the signals and properties of the object.
1612  *
1613  * Returns: the descriptor.
1614  */
1615 PyObject *
1616 pyg_object_descr_doc_get(void)
1617 {
1618     static PyObject *doc_descr = NULL;
1619
1620     if (!doc_descr) {
1621         Py_TYPE(&PyGObjectDoc_Type) = &PyType_Type;
1622         if (PyType_Ready(&PyGObjectDoc_Type))
1623             return NULL;
1624
1625         doc_descr = PyObject_NEW(PyObject, &PyGObjectDoc_Type);
1626         if (doc_descr == NULL)
1627             return NULL;
1628     }
1629     return doc_descr;
1630 }
1631
1632
1633 /**
1634  * pyg_pyobj_to_unichar_conv:
1635  *
1636  * Converts PyObject value to a unichar and write result to memory
1637  * pointed to by ptr.  Follows the calling convention of a ParseArgs
1638  * converter (O& format specifier) so it may be used to convert function
1639  * arguments.
1640  *
1641  * Returns: 1 if the conversion succeeds and 0 otherwise.  If the conversion
1642  *          did not succeesd, a Python exception is raised
1643  */
1644 int pyg_pyobj_to_unichar_conv(PyObject* py_obj, void* ptr)
1645 {
1646     gunichar* u = ptr;
1647     const Py_UNICODE* uni_buffer;
1648     PyObject* tmp_uni = NULL;
1649
1650     if (PyUnicode_Check(py_obj)) {
1651         tmp_uni = py_obj;
1652         Py_INCREF(tmp_uni);
1653     }
1654     else {
1655         tmp_uni = PyUnicode_FromObject(py_obj);
1656         if (tmp_uni == NULL)
1657             goto failure;
1658     }
1659
1660     if ( PyUnicode_GetSize(tmp_uni) != 1) {
1661         PyErr_SetString(PyExc_ValueError, "unicode character value must be 1 character uniode string");
1662         goto failure;
1663     }
1664     uni_buffer = PyUnicode_AsUnicode(tmp_uni);
1665     if ( uni_buffer == NULL)
1666         goto failure;
1667     *u = uni_buffer[0];
1668
1669     Py_DECREF(tmp_uni);
1670     return 1;
1671
1672   failure:
1673     Py_XDECREF(tmp_uni);
1674     return 0;
1675 }
1676
1677
1678 int
1679 pyg_param_gvalue_from_pyobject(GValue* value,
1680                                PyObject* py_obj,
1681                                const GParamSpec* pspec)
1682 {
1683     if (G_IS_PARAM_SPEC_UNICHAR(pspec)) {
1684         gunichar u;
1685
1686         if (!pyg_pyobj_to_unichar_conv(py_obj, &u)) {
1687             PyErr_Clear();
1688             return -1;
1689         }
1690         g_value_set_uint(value, u);
1691         return 0;
1692     }
1693     else if (G_IS_PARAM_SPEC_VALUE_ARRAY(pspec))
1694         return pyg_value_array_from_pyobject(value, py_obj,
1695                                              G_PARAM_SPEC_VALUE_ARRAY(pspec));
1696     else {
1697         return pyg_value_from_pyobject(value, py_obj);
1698     }
1699 }
1700
1701 PyObject*
1702 pyg_param_gvalue_as_pyobject(const GValue* gvalue,
1703                              gboolean copy_boxed,
1704                              const GParamSpec* pspec)
1705 {
1706     if (G_IS_PARAM_SPEC_UNICHAR(pspec)) {
1707         gunichar u;
1708         Py_UNICODE uni_buffer[2] = { 0, 0 };
1709
1710         u = g_value_get_uint(gvalue);
1711         uni_buffer[0] = u;
1712         return PyUnicode_FromUnicode(uni_buffer, 1);
1713     }
1714     else {
1715         return pyg_value_as_pyobject(gvalue, copy_boxed);
1716     }
1717 }
1718
1719 /**
1720  * pyg_type_registration_callback
1721  * @gtypename: type name
1722  * @callback: function to run
1723  *
1724  */
1725 typedef struct {
1726     PyGTypeRegistrationFunction callback;
1727     gpointer data;
1728 } CustomTypeData;
1729
1730 void
1731 pyg_type_register_custom_callback(const gchar *typename,
1732                                   PyGTypeRegistrationFunction callback,
1733                                   gpointer user_data)
1734 {
1735     CustomTypeData *data;
1736
1737     if (!custom_type_registration)
1738         custom_type_registration = g_hash_table_new_full (g_str_hash, g_str_equal,
1739                                                           g_free, g_free);
1740
1741     data = g_new (CustomTypeData, 1);
1742     data->callback = callback;
1743     data->data = user_data;
1744
1745     g_hash_table_insert(custom_type_registration,
1746                         g_strdup(typename),
1747                         data);
1748 }
1749
1750 PyTypeObject *
1751 pyg_type_get_custom(const gchar *name)
1752 {
1753     CustomTypeData *data;
1754     PyTypeObject *retval;
1755
1756     if (!custom_type_registration)
1757         return NULL;
1758
1759     data = g_hash_table_lookup(custom_type_registration, name);
1760     if (!data)
1761         return NULL;
1762
1763     retval = data->callback(name, data->data);
1764
1765     g_hash_table_remove(custom_type_registration, name);
1766
1767     return retval;
1768 }
1769
1770 GType
1771 _pyg_type_from_name(const gchar *name)
1772 {
1773     GType type;
1774
1775     type = g_type_from_name(name);
1776     if (type == G_TYPE_INVALID) {
1777         pyg_type_get_custom(name);
1778         type = g_type_from_name(name);
1779     }
1780
1781     return type;
1782 }
1783
1784 static PyObject *
1785 _pyg_strv_from_gvalue(const GValue *value)
1786 {
1787     gchar    **argv = (gchar **) g_value_get_boxed(value);
1788     int        argc = 0, i;
1789     PyObject  *py_argv;
1790
1791     if (argv) {
1792         while (argv[argc])
1793             argc++;
1794     }
1795     py_argv = PyList_New(argc);
1796     for (i = 0; i < argc; ++i)
1797         PyList_SET_ITEM(py_argv, i, PYGLIB_PyUnicode_FromString(argv[i]));
1798     return py_argv;
1799 }
1800
1801 static int
1802 _pyg_strv_to_gvalue(GValue *value, PyObject *obj)
1803 {
1804     Py_ssize_t argc, i;
1805     gchar **argv;
1806
1807     if (!(PyTuple_Check(obj) || PyList_Check(obj)))
1808         return -1;
1809
1810     argc = PySequence_Length(obj);
1811     for (i = 0; i < argc; ++i)
1812         if (!PYGLIB_PyUnicode_Check(PySequence_Fast_GET_ITEM(obj, i)))
1813             return -1;
1814     argv = g_new(gchar *, argc + 1);
1815     for (i = 0; i < argc; ++i)
1816         argv[i] = g_strdup(PYGLIB_PyUnicode_AsString(PySequence_Fast_GET_ITEM(obj, i)));
1817     argv[i] = NULL;
1818     g_value_take_boxed(value, argv);
1819     return 0;
1820 }
1821
1822 void
1823 pygobject_type_register_types(PyObject *d)
1824 {
1825     PyGTypeWrapper_Type.tp_dealloc = (destructor)pyg_type_wrapper_dealloc;
1826     PyGTypeWrapper_Type.tp_richcompare = pyg_type_wrapper_richcompare;
1827     PyGTypeWrapper_Type.tp_repr = (reprfunc)pyg_type_wrapper_repr;
1828     PyGTypeWrapper_Type.tp_hash = (hashfunc)pyg_type_wrapper_hash;
1829     PyGTypeWrapper_Type.tp_flags = Py_TPFLAGS_DEFAULT;
1830     PyGTypeWrapper_Type.tp_methods = _PyGTypeWrapper_methods;
1831     PyGTypeWrapper_Type.tp_getset = _PyGTypeWrapper_getsets;
1832     PyGTypeWrapper_Type.tp_init = (initproc)pyg_type_wrapper_init;
1833     PYGLIB_REGISTER_TYPE(d, PyGTypeWrapper_Type, "GType");
1834
1835     /* This type lazily registered in pyg_object_descr_doc_get */
1836     PyGObjectDoc_Type.tp_dealloc = (destructor)object_doc_dealloc;
1837     PyGObjectDoc_Type.tp_flags = Py_TPFLAGS_DEFAULT;
1838     PyGObjectDoc_Type.tp_descr_get = (descrgetfunc)object_doc_descr_get;
1839
1840     pyg_register_gtype_custom(G_TYPE_STRV,
1841                               _pyg_strv_from_gvalue,
1842                               _pyg_strv_to_gvalue);
1843 }