Debian Codegraph @

gi/pygenum.c

raw
1 /* -*- Mode: C; c-basic-offset: 4 -*-
2 * pygtk- Python bindings for the GTK toolkit.
3 * Copyright (C) 1998-2003 James Henstridge
4 * Copyright (C) 2004 Johan Dahlin
5 *
6 * pygenum.c: GEnum wrapper
7 *
8 * This library is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU Lesser General Public
10 * License as published by the Free Software Foundation; either
11 * version 2.1 of the License, or (at your option) any later version.
12 *
13 * This library is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 * Lesser General Public License for more details.
17 *
18 * You should have received a copy of the GNU Lesser General Public
19 * License along with this library; if not, see <http://www.gnu.org/licenses/>.
20 */
21
22 #include "pygenum.h"
23 #include "pygi-basictype.h"
24 #include "pygi-type.h"
25 #include "pygi-util.h"
26
27 GQuark pygenum_class_key;
28
29 PyTypeObject *PyGEnum_Type;
30 static PyObject *IntEnum_Type;
31
32 PyObject *
33 pyg_enum_val_new (PyObject *pyclass, int value)
34 {
35 PyObject *retval, *intvalue;
36 PyObject *args[2] = { NULL };
37
38 intvalue = PyLong_FromLong (value);
39 if (!intvalue) return NULL;
40
41 args[1] = intvalue;
42 retval = PyObject_Vectorcall (pyclass, &args[1],
43 1 + PY_VECTORCALL_ARGUMENTS_OFFSET, NULL);
44 if (!retval && PyErr_ExceptionMatches (PyExc_ValueError)) {
45 PyErr_Clear ();
46 return intvalue;
47 }
48 Py_DECREF (intvalue);
49
50 return retval;
51 }
52
53 PyObject *
54 pyg_enum_from_gtype (GType gtype, int value)
55 {
56 PyObject *pyclass;
57
58 g_return_val_if_fail (gtype != G_TYPE_INVALID, NULL);
59
60 /* Get a wrapper class by:
61 * 1. check for one attached to the gtype
62 * 2. lookup one in a typelib
63 * 3. creating a new one
64 */
65 pyclass = (PyObject *)g_type_get_qdata (gtype, pygenum_class_key);
66 if (!pyclass) pyclass = pygi_type_import_by_g_type (gtype);
67 if (!pyclass)
68 pyclass = pyg_enum_add (NULL, g_type_name (gtype), NULL, gtype);
69 if (!pyclass) return PyLong_FromLong (value);
70
71 return pyg_enum_val_new (pyclass, value);
72 }
73
74 static void
75 add_value (PyObject *dict, const char *value_nick, int value)
76 {
77 char *upper = g_ascii_strup (value_nick, -1);
78 char *c;
79 PyObject *v;
80
81 for (c = upper; *c != '\0'; c++) {
82 if (*c == '-') *c = '_';
83 }
84
85 /* skip if the name already exists in the dictionary */
86 if (PyMapping_HasKeyString (dict, upper)) {
87 g_free (upper);
88 return;
89 }
90
91 v = PyLong_FromLong (value);
92 PyMapping_SetItemString (dict, upper, v);
93 Py_DECREF (v);
94 g_free (upper);
95 }
96
97 PyObject *
98 pyg_enum_add_full (PyObject *module, const char *typename, GType gtype,
99 GIEnumInfo *info)
100 {
101 PyObject *stub;
102 PyObject *base_class, *method_name, *enum_name, *bases, *values;
103 PyObject *args[4] = { NULL };
104
105 if (gtype == G_TYPE_NONE && info == NULL) {
106 PyErr_SetString (PyExc_ValueError,
107 "cannot create enum without a GType or EnumInfo");
108 return NULL;
109 }
110 if (gtype != G_TYPE_NONE && !g_type_is_a (gtype, G_TYPE_ENUM)) {
111 PyErr_Format (PyExc_TypeError,
112 "Trying to register gtype '%s' as enum when in fact it "
113 "is of type '%s'",
114 g_type_name (gtype),
115 g_type_name (G_TYPE_FUNDAMENTAL (gtype)));
116 return NULL;
117 }
118 if (info != NULL) {
119 GType info_gtype = gi_registered_type_info_get_g_type (
120 GI_REGISTERED_TYPE_INFO (info));
121
122 if (info_gtype != gtype) {
123 PyErr_Format (PyExc_ValueError,
124 "gtype '%s' does not match EnumInfo '%s'",
125 g_type_name (gtype),
126 gi_base_info_get_name (GI_BASE_INFO (info)));
127 return NULL;
128 }
129 }
130
131 if (gtype == G_TYPE_NONE)
132 base_class = IntEnum_Type;
133 else
134 base_class = (PyObject *)PyGEnum_Type;
135 enum_name = PyUnicode_FromString (typename);
136 bases = PyTuple_New (1);
137 PyTuple_SET_ITEM (bases, 0, Py_NewRef (base_class));
138
139 args[0] = (PyObject *)Py_TYPE (base_class);
140 args[1] = enum_name;
141 args[2] = bases;
142
143 method_name = PyUnicode_FromString ("__prepare__");
144 values = PyObject_VectorcallMethod (
145 method_name, args, 3 + PY_VECTORCALL_ARGUMENTS_OFFSET, NULL);
146 Py_DECREF (method_name);
147 if (!values) {
148 Py_DECREF (enum_name);
149 Py_DECREF (bases);
150 return NULL;
151 }
152
153 /* Collect values from registered GType */
154 if (gtype != G_TYPE_NONE) {
155 GEnumClass *eclass;
156 unsigned int i;
157
158 eclass = G_ENUM_CLASS (g_type_class_ref (gtype));
159 for (i = 0; i < eclass->n_values; i++) {
160 add_value (values, eclass->values[i].value_nick,
161 eclass->values[i].value);
162 }
163 g_type_class_unref (eclass);
164 }
165
166 /* Collect values from GIEnumInfo (which may include additional aliases) */
167 if (info != NULL) {
168 unsigned int i, length;
169
170 length = gi_enum_info_get_n_values (info);
171 for (i = 0; i < length; i++) {
172 GIValueInfo *v = gi_enum_info_get_value (info, i);
173
174 add_value (values, gi_base_info_get_name (GI_BASE_INFO (v)),
175 (int)gi_value_info_get_value (v));
176 gi_base_info_unref (v);
177 }
178 }
179
180 if (module && !Py_IsNone (module)) {
181 PyObject *module_name = PyModule_GetNameObject (module);
182
183 PyMapping_SetItemString (values, "__module__", module_name);
184 Py_DECREF (module_name);
185 }
186 if (gtype != G_TYPE_NONE) {
187 PyObject *o = pyg_type_wrapper_new (gtype);
188
189 PyMapping_SetItemString (values, "__gtype__", o);
190 Py_DECREF (o);
191 }
192
193 args[3] = values;
194 stub = PyObject_Vectorcall ((PyObject *)Py_TYPE (base_class), &args[1],
195 3 + PY_VECTORCALL_ARGUMENTS_OFFSET, NULL);
196 Py_DECREF (values);
197 Py_DECREF (bases);
198 Py_DECREF (enum_name);
199
200 if (!stub) return NULL;
201
202 ((PyTypeObject *)stub)->tp_flags &= ~Py_TPFLAGS_BASETYPE;
203 if (gtype != G_TYPE_NONE) {
204 g_type_set_qdata (gtype, pygenum_class_key, stub);
205 }
206
207 return stub;
208 }
209
210 /*
211 * pyg_enum_add
212 * Dynamically create a class derived from PyGEnum based on the given GType.
213 */
214 PyObject *
215 pyg_enum_add (PyObject *module, const char *typename, const char *strip_prefix,
216 GType gtype)
217 {
218 PyGILState_STATE state;
219 PyObject *stub;
220
221 g_return_val_if_fail (typename != NULL, NULL);
222 if (!g_type_is_a (gtype, G_TYPE_ENUM)) {
223 PyErr_Format (PyExc_TypeError,
224 "Trying to register gtype '%s' as enum when in fact it "
225 "is of type '%s'",
226 g_type_name (gtype),
227 g_type_name (G_TYPE_FUNDAMENTAL (gtype)));
228 return NULL;
229 }
230
231 state = PyGILState_Ensure ();
232
233 stub = pyg_enum_add_full (module, typename, gtype, NULL);
234 if (!stub) {
235 PyGILState_Release (state);
236 return NULL;
237 }
238
239 if (module) {
240 GEnumClass *eclass;
241 guint i;
242
243 /* Add it to the module name space */
244 PyModule_AddObject (module, (char *)typename, stub);
245 Py_INCREF (stub);
246
247 /* Register enum values */
248 eclass = G_ENUM_CLASS (g_type_class_ref (gtype));
249 for (i = 0; i < eclass->n_values; i++) {
250 PyObject *item, *intval;
251 PyObject *args[2] = { NULL };
252 char *prefix;
253
254 intval = PyLong_FromLong (eclass->values[i].value);
255 args[1] = intval;
256 item = PyObject_Vectorcall (
257 stub, &args[1], 1 + PY_VECTORCALL_ARGUMENTS_OFFSET, NULL);
258 Py_DECREF (intval);
259
260 prefix = g_strdup (pyg_constant_strip_prefix (
261 eclass->values[i].value_name, strip_prefix));
262 PyModule_AddObject (module, prefix, item);
263 g_free (prefix);
264 }
265 g_type_class_unref (eclass);
266 }
267
268 PyGILState_Release (state);
269 return stub;
270 }
271
272 gboolean
273 pyg_enum_register (PyTypeObject *enum_class, char *type_name)
274 {
275 gboolean result = FALSE;
276 GType gtype = G_TYPE_INVALID;
277 GEnumValue *enum_values = NULL;
278 PyObject *values = NULL, *pygtype = NULL;
279 Py_ssize_t length, i;
280
281 values = PySequence_List ((PyObject *)enum_class);
282 if (!values) goto out;
283
284 length = PyList_Size (values);
285 enum_values = g_new0 (GEnumValue, length + 1);
286 for (i = 0; i < length; i++) {
287 PyObject *value = PyList_GetItem (values, i);
288 PyObject *name = PyObject_GetAttrString (value, "name");
289 char *c;
290
291 if (!name) {
292 goto out;
293 }
294 if (!PyUnicode_Check (name)) {
295 PyErr_SetString (PyExc_TypeError,
296 "enum value names should be strings");
297 Py_DECREF (name);
298 goto out;
299 }
300
301 enum_values[i].value = (int)PyLong_AsLong (value);
302 enum_values[i].value_name =
303 g_strdup (PyUnicode_AsUTF8AndSize (name, NULL));
304 c = g_ascii_strdown (enum_values[i].value_name, -1);
305 enum_values[i].value_nick = c;
306 while (*c != '\0') {
307 if (*c == '_') *c = '-';
308 c++;
309 }
310 Py_DECREF (name);
311 }
312
313 gtype = g_enum_register_static (type_name, enum_values);
314 if (gtype == G_TYPE_INVALID) {
315 PyErr_Format (PyExc_RuntimeError, "Unable to register enum '%s'",
316 type_name);
317 goto out;
318 }
319 g_type_set_qdata (gtype, pygenum_class_key, enum_class);
320
321 pygtype = pyg_type_wrapper_new (gtype);
322 if (!pygtype) goto out;
323 PyObject_SetAttrString ((PyObject *)enum_class, "__gtype__", pygtype);
324
325 result = TRUE;
326
327 out:
328 Py_XDECREF (pygtype);
329 Py_XDECREF (values);
330 /* If type registration succeeded, this data should not be freed */
331 if (gtype == G_TYPE_INVALID) {
332 g_free (type_name);
333 if (enum_values != NULL) {
334 GEnumValue *v;
335 for (v = enum_values; v->value_name != NULL; v++) {
336 g_free ((char *)v->value_name);
337 g_free ((char *)v->value_nick);
338 }
339 g_free (enum_values);
340 }
341 }
342 return result;
343 }
344
345 static GType
346 get_enum_gtype (PyTypeObject *type)
347 {
348 PyObject *pytc;
349 GType gtype;
350
351 pytc = PyObject_GetAttrString ((PyObject *)type, "__gtype__");
352 if (!pytc) return G_TYPE_INVALID;
353
354 if (!PyObject_TypeCheck (pytc, &PyGTypeWrapper_Type)) {
355 Py_DECREF (pytc);
356 PyErr_SetString (PyExc_TypeError,
357 "__gtype__ attribute not a typecode");
358 return G_TYPE_INVALID;
359 }
360
361 gtype = pyg_type_from_object (pytc);
362 Py_DECREF (pytc);
363
364 if (!G_TYPE_IS_ENUM (gtype)) {
365 PyErr_SetString (PyExc_TypeError,
366 "__gtype__ attribute not an enum typecode");
367 return G_TYPE_INVALID;
368 }
369
370 return gtype;
371 }
372
373 static PyObject *
374 pyg_enum_get_value_name (PyObject *self, void *closure)
375 {
376 GType gtype;
377 GEnumClass *enum_class;
378 GEnumValue *enum_value;
379 PyObject *retval;
380 gint intvalue;
381
382 if (!pygi_gint_from_py ((PyObject *)self, &intvalue)) return NULL;
383
384 gtype = get_enum_gtype (Py_TYPE (self));
385 if (gtype == G_TYPE_INVALID) return NULL;
386 enum_class = g_type_class_ref (gtype);
387 g_assert (G_IS_ENUM_CLASS (enum_class));
388
389 enum_value = g_enum_get_value (enum_class, intvalue);
390 if (enum_value == NULL) {
391 PyErr_Format (PyExc_ValueError, "no GEnumValue found for %d",
392 intvalue);
393 g_type_class_unref (enum_class);
394 return NULL;
395 }
396
397 retval = pygi_utf8_to_py (enum_value->value_name);
398 g_type_class_unref (enum_class);
399
400 return retval;
401 }
402
403 static PyObject *
404 pyg_enum_get_value_nick (PyObject *self, void *closure)
405 {
406 GType gtype;
407 GEnumClass *enum_class;
408 GEnumValue *enum_value;
409 PyObject *retval;
410 gint intvalue;
411
412 if (!pygi_gint_from_py ((PyObject *)self, &intvalue)) return NULL;
413
414 gtype = get_enum_gtype (Py_TYPE (self));
415 if (gtype == G_TYPE_INVALID) return NULL;
416 enum_class = g_type_class_ref (gtype);
417 g_assert (G_IS_ENUM_CLASS (enum_class));
418
419 enum_value = g_enum_get_value (enum_class, intvalue);
420 if (enum_value == NULL) {
421 PyErr_Format (PyExc_ValueError, "no GEnumValue found for %d",
422 intvalue);
423 g_type_class_unref (enum_class);
424 return NULL;
425 }
426
427 retval = pygi_utf8_to_py (enum_value->value_nick);
428
429 g_type_class_unref (enum_class);
430
431 return retval;
432 }
433
434 static PyGetSetDef pyg_enum_getsets[] = {
435 { "value_name", (getter)pyg_enum_get_value_name, (setter)0 },
436 { "value_nick", (getter)pyg_enum_get_value_nick, (setter)0 },
437 { NULL, 0, 0 },
438 };
439
440 /**
441 * Returns 0 on success, or -1 and sets an exception.
442 */
443 int
444 pygi_enum_register_types (PyObject *mod)
445 {
446 PyObject *enum_module, *item;
447 int i;
448
449 pygenum_class_key = g_quark_from_static_string ("PyGEnum::class");
450
451 enum_module = PyImport_ImportModule ("enum");
452 if (!enum_module) return -1;
453
454 IntEnum_Type = PyObject_GetAttrString (enum_module, "IntEnum");
455 Py_DECREF (enum_module);
456 if (!IntEnum_Type) return -1;
457
458 enum_module = PyImport_ImportModule ("gi._enum");
459 if (!enum_module) return -1;
460
461 PyGEnum_Type =
462 (PyTypeObject *)PyObject_GetAttrString (enum_module, "GEnum");
463 Py_DECREF (enum_module);
464 if (!PyGEnum_Type) return -1;
465
466 item = pyg_type_wrapper_new (G_TYPE_ENUM);
467 PyObject_SetAttrString ((PyObject *)PyGEnum_Type, "__gtype__", item);
468 Py_DECREF (item);
469
470 for (i = 0; pyg_enum_getsets[i].name != NULL; i++) {
471 item = PyDescr_NewGetSet (PyGEnum_Type, &pyg_enum_getsets[i]);
472 PyObject_SetAttrString ((PyObject *)PyGEnum_Type,
473 pyg_enum_getsets[i].name, item);
474 Py_DECREF (item);
475 }
476
477 PyModule_AddObject (mod, "GEnum", Py_NewRef ((PyObject *)PyGEnum_Type));
478
479 return 0;
480 }