1 /* -*- Mode: C; c-set-style: python; c-basic-offset: 4 -*-
2 * pyglib - Python bindings for GLib toolkit.
3 * Copyright (C) 1998-2003 James Henstridge
4 * 2004-2008 Johan Dahlin
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2.1 of the License, or (at your option) any later version.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301
29 #include "pyglib-private.h"
30 #include "pygmaincontext.h"
31 #include "pygoptioncontext.h"
32 #include "pygoptiongroup.h"
34 static struct _PyGLib_Functions *_PyGLib_API;
35 static int pyglib_thread_state_tls_key;
36 static PyObject *exception_table = NULL;
41 PyObject *glib, *cobject;
43 glib = PyImport_ImportModule("glib");
45 if (PyErr_Occurred()) {
46 PyObject *type, *value, *traceback;
47 PyObject *py_orig_exc;
48 PyErr_Fetch(&type, &value, &traceback);
49 py_orig_exc = PyObject_Repr(value);
52 Py_XDECREF(traceback);
53 PyErr_Format(PyExc_ImportError,
54 "could not import glib (error was: %s)",
55 PYGLIB_PyUnicode_AsString(py_orig_exc));
56 Py_DECREF(py_orig_exc);
58 PyErr_SetString(PyExc_ImportError,
59 "could not import glib (no error given)");
64 cobject = PyObject_GetAttrString(glib, "_PyGLib_API");
65 if (cobject && PYGLIB_CPointer_Check(cobject))
66 _PyGLib_API = (struct _PyGLib_Functions *) PYGLIB_CPointer_GetPointer(cobject, "glib._PyGLib_API");
68 PyErr_SetString(PyExc_ImportError,
69 "could not import glib (could not find _PyGLib_API object)");
76 pyglib_init_internal(PyObject *api)
78 _PyGLib_API = (struct _PyGLib_Functions *) PYGLIB_CPointer_GetPointer(api, "glib._PyGLib_API");
82 pyglib_threads_enabled(void)
84 g_return_val_if_fail (_PyGLib_API != NULL, FALSE);
86 return _PyGLib_API->threads_enabled;
90 pyglib_gil_state_ensure(void)
92 g_return_val_if_fail (_PyGLib_API != NULL, PyGILState_LOCKED);
94 if (!_PyGLib_API->threads_enabled)
95 return PyGILState_LOCKED;
97 #ifdef DISABLE_THREADING
98 return PyGILState_LOCKED;
100 return PyGILState_Ensure();
105 pyglib_gil_state_release(PyGILState_STATE state)
107 g_return_if_fail (_PyGLib_API != NULL);
109 if (!_PyGLib_API->threads_enabled)
112 #ifndef DISABLE_THREADING
113 PyGILState_Release(state);
118 * pyglib_enable_threads:
120 * Returns: TRUE if threading is enabled, FALSE otherwise.
123 #ifdef DISABLE_THREADING
125 pyglib_enable_threads(void)
127 PyErr_SetString(PyExc_RuntimeError,
128 "pyglib threading disabled at compile time");
133 _pyglib_notify_on_enabling_threads(PyGLibThreadsEnabledFunc callback)
135 /* Ignore, threads cannot be enabled. */
140 static GSList *thread_enabling_callbacks = NULL;
142 /* Enable threading; note that the GIL must be held by the current
143 * thread when this function is called
146 pyglib_enable_threads(void)
150 g_return_val_if_fail (_PyGLib_API != NULL, FALSE);
152 if (_PyGLib_API->threads_enabled)
155 PyEval_InitThreads();
156 if (!g_threads_got_initialized)
159 _PyGLib_API->threads_enabled = TRUE;
160 pyglib_thread_state_tls_key = PyThread_create_key();
162 for (callback = thread_enabling_callbacks; callback; callback = callback->next)
163 ((PyGLibThreadsEnabledFunc) callback->data) ();
165 g_slist_free(thread_enabling_callbacks);
170 _pyglib_notify_on_enabling_threads(PyGLibThreadsEnabledFunc callback)
172 if (callback && !pyglib_threads_enabled())
173 thread_enabling_callbacks = g_slist_append(thread_enabling_callbacks, callback);
178 pyglib_gil_state_ensure_py23 (void)
180 #ifdef DISABLE_THREADING
183 return PyGILState_Ensure();
188 pyglib_gil_state_release_py23 (int flag)
190 #ifndef DISABLE_THREADING
191 PyGILState_Release(flag);
196 * pyglib_block_threads:
200 pyglib_block_threads(void)
202 g_return_if_fail (_PyGLib_API != NULL);
204 if (_PyGLib_API->block_threads != NULL)
205 (* _PyGLib_API->block_threads)();
209 * pyglib_unblock_threads:
213 pyglib_unblock_threads(void)
215 g_return_if_fail (_PyGLib_API != NULL);
216 if (_PyGLib_API->unblock_threads != NULL)
217 (* _PyGLib_API->unblock_threads)();
221 * pyglib_set_thread_block_funcs:
223 * hooks to register handlers for getting GDK threads to cooperate
224 * with python threading
227 pyglib_set_thread_block_funcs (PyGLibThreadBlockFunc block_threads_func,
228 PyGLibThreadBlockFunc unblock_threads_func)
230 g_return_if_fail (_PyGLib_API != NULL);
232 _PyGLib_API->block_threads = block_threads_func;
233 _PyGLib_API->unblock_threads = unblock_threads_func;
238 * pyglib_error_check:
239 * @error: a pointer to the GError.
241 * Checks to see if the GError has been set. If the error has been
242 * set, then the glib.GError Python exception will be raised, and
243 * the GError cleared.
245 * Returns: True if an error was set.
248 pyglib_error_check(GError **error)
250 PyGILState_STATE state;
252 PyObject *exc_instance;
255 g_return_val_if_fail(error != NULL, FALSE);
260 state = pyglib_gil_state_ensure();
262 exc_type = _PyGLib_API->gerror_exception;
263 if (exception_table != NULL)
266 item = PyDict_GetItem(exception_table, PYGLIB_PyLong_FromLong((*error)->domain));
271 exc_instance = PyObject_CallFunction(exc_type, "z", (*error)->message);
273 if ((*error)->domain) {
274 PyObject_SetAttrString(exc_instance, "domain",
275 d=PYGLIB_PyUnicode_FromString(g_quark_to_string((*error)->domain)));
279 PyObject_SetAttrString(exc_instance, "domain", Py_None);
281 PyObject_SetAttrString(exc_instance, "code",
282 d=PYGLIB_PyLong_FromLong((*error)->code));
285 if ((*error)->message) {
286 PyObject_SetAttrString(exc_instance, "message",
287 d=PYGLIB_PyUnicode_FromString((*error)->message));
290 PyObject_SetAttrString(exc_instance, "message", Py_None);
293 PyErr_SetObject(_PyGLib_API->gerror_exception, exc_instance);
294 Py_DECREF(exc_instance);
295 g_clear_error(error);
297 pyglib_gil_state_release(state);
303 * pyglib_gerror_exception_check:
304 * @error: a standard GLib GError ** output parameter
306 * Checks to see if a GError exception has been raised, and if so
307 * translates the python exception to a standard GLib GError. If the
308 * raised exception is not a GError then PyErr_Print() is called.
310 * Returns: 0 if no exception has been raised, -1 if it is a
311 * valid glib.GError, -2 otherwise.
314 pyglib_gerror_exception_check(GError **error)
316 PyObject *type, *value, *traceback;
317 PyObject *py_message, *py_domain, *py_code;
318 const char *bad_gerror_message;
320 PyErr_Fetch(&type, &value, &traceback);
323 PyErr_NormalizeException(&type, &value, &traceback);
325 PyErr_Restore(type, value, traceback);
330 !PyErr_GivenExceptionMatches(type,
331 (PyObject *) _PyGLib_API->gerror_exception)) {
332 PyErr_Restore(type, value, traceback);
337 Py_XDECREF(traceback);
339 py_message = PyObject_GetAttrString(value, "message");
340 if (!py_message || !PYGLIB_PyUnicode_Check(py_message)) {
341 bad_gerror_message = "glib.GError instances must have a 'message' string attribute";
345 py_domain = PyObject_GetAttrString(value, "domain");
346 if (!py_domain || !PYGLIB_PyUnicode_Check(py_domain)) {
347 bad_gerror_message = "glib.GError instances must have a 'domain' string attribute";
348 Py_DECREF(py_message);
352 py_code = PyObject_GetAttrString(value, "code");
353 if (!py_code || !PYGLIB_PyLong_Check(py_code)) {
354 bad_gerror_message = "glib.GError instances must have a 'code' int attribute";
355 Py_DECREF(py_message);
356 Py_DECREF(py_domain);
360 g_set_error(error, g_quark_from_string(PYGLIB_PyUnicode_AsString(py_domain)),
361 PYGLIB_PyLong_AsLong(py_code), "%s", PYGLIB_PyUnicode_AsString(py_message));
363 Py_DECREF(py_message);
365 Py_DECREF(py_domain);
370 g_set_error(error, g_quark_from_static_string("pyglib"), 0, "%s", bad_gerror_message);
371 PyErr_SetString(PyExc_ValueError, bad_gerror_message);
377 * pyglib_register_exception_for_domain:
378 * @name: name of the exception
379 * @error_domain: error domain
381 * Registers a new glib.GError exception subclass called #name for
382 * a specific #domain. This exception will be raised when a GError
383 * of the same domain is passed in to pyglib_error_check().
385 * Returns: the new exception
388 pyglib_register_exception_for_domain(gchar *name,
393 exception = PyErr_NewException(name, _PyGLib_API->gerror_exception, NULL);
395 if (exception_table == NULL)
396 exception_table = PyDict_New();
398 PyDict_SetItem(exception_table,
399 PYGLIB_PyLong_FromLong(error_domain),
406 * pyglib_main_context_new:
407 * @context: a GMainContext.
409 * Creates a wrapper for a GMainContext.
411 * Returns: the GMainContext wrapper.
414 pyglib_main_context_new(GMainContext *context)
416 return _PyGLib_API->main_context_new(context);
420 * pyg_option_group_transfer_group:
421 * @group: a GOptionGroup wrapper
423 * This is used to transfer the GOptionGroup to a GOptionContext. After this
424 * is called, the calle must handle the release of the GOptionGroup.
426 * When #NULL is returned, the GOptionGroup was already transfered.
428 * Returns: Either #NULL or the wrapped GOptionGroup.
431 pyglib_option_group_transfer_group(PyObject *obj)
433 PyGOptionGroup *self = (PyGOptionGroup*)obj;
435 if (self->is_in_context)
438 self->is_in_context = TRUE;
440 /* Here we increase the reference count of the PyGOptionGroup, because now
441 * the GOptionContext holds an reference to us (it is the userdata passed
442 * to g_option_group_new().
444 * The GOptionGroup is freed with the GOptionContext.
446 * We set it here because if we would do this in the init method we would
447 * hold two references and the PyGOptionGroup would never be freed.
455 * pyglib_option_group_new:
456 * @group: a GOptionGroup
458 * The returned GOptionGroup can't be used to set any hooks, translation domains
459 * or add entries. It's only intend is, to use for GOptionContext.add_group().
461 * Returns: the GOptionGroup wrapper.
464 pyglib_option_group_new (GOptionGroup *group)
466 return _PyGLib_API->option_group_new(group);
470 * pyglib_option_context_new:
471 * @context: a GOptionContext
473 * Returns: A new GOptionContext wrapper.
476 pyglib_option_context_new (GOptionContext *context)
478 return _PyGLib_API->option_context_new(context);
482 * pyglib_option_context_new:
483 * @context: a GTimeVal struct
485 * Converts a GTimeVal struct to a python float
487 * Returns: a float representing the timeval
490 pyglib_float_from_timeval(GTimeVal timeval)
493 ret = (double)timeval.tv_sec + (double)timeval.tv_usec * 0.000001;
494 return PyFloat_FromDouble(ret);
498 /****** Private *****/
501 * _pyglib_destroy_notify:
502 * @user_data: a PyObject pointer.
504 * A function that can be used as a GDestroyNotify callback that will
505 * call Py_DECREF on the data.
508 _pyglib_destroy_notify(gpointer user_data)
510 PyObject *obj = (PyObject *)user_data;
511 PyGILState_STATE state;
513 g_return_if_fail (_PyGLib_API != NULL);
515 state = pyglib_gil_state_ensure();
517 pyglib_gil_state_release(state);
521 _pyglib_handler_marshal(gpointer user_data)
523 PyObject *tuple, *ret;
525 PyGILState_STATE state;
527 g_return_val_if_fail(user_data != NULL, FALSE);
529 state = pyglib_gil_state_ensure();
531 tuple = (PyObject *)user_data;
532 ret = PyObject_CallObject(PyTuple_GetItem(tuple, 0),
533 PyTuple_GetItem(tuple, 1));
538 res = PyObject_IsTrue(ret);
542 pyglib_gil_state_release(state);
548 _pyglib_generic_ptr_richcompare(void* a, void *b, int op)
555 res = (a == b) ? Py_True : Py_False;
559 res = (a != b) ? Py_True : Py_False;
563 res = (a < b) ? Py_True : Py_False;
567 res = (a <= b) ? Py_True : Py_False;
571 res = (a > b) ? Py_True : Py_False;
575 res = (a >= b) ? Py_True : Py_False;
579 res = Py_NotImplemented;
588 _pyglib_generic_long_richcompare(long a, long b, int op)
595 res = (a == b) ? Py_True : Py_False;
600 res = (a != b) ? Py_True : Py_False;
606 res = (a < b) ? Py_True : Py_False;
611 res = (a <= b) ? Py_True : Py_False;
616 res = (a > b) ? Py_True : Py_False;
621 res = (a >= b) ? Py_True : Py_False;
626 res = Py_NotImplemented;