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