|
| 1 | +#define PY_SSIZE_T_CLEAN |
| 2 | +#include <Python.h> |
| 3 | + |
| 4 | +#ifdef __linux__ |
| 5 | +#include <dlfcn.h> |
| 6 | +#endif |
| 7 | + |
| 8 | +static PyObject* mpl_invalid_display(PyObject* module) |
| 9 | +{ |
| 10 | +#ifdef __linux__ |
| 11 | + void* x11; |
| 12 | + typedef struct Display Display; |
| 13 | + Display* (* XOpenDisplay)(char* display_name); |
| 14 | + int (* XCloseDisplay)(Display* display); |
| 15 | + if (!(x11 = dlopen("libX11.so", RTLD_LAZY)) || |
| 16 | + !(XOpenDisplay = dlsym(x11, "XOpenDisplay")) || |
| 17 | + !(XCloseDisplay = dlsym(x11, "XCloseDisplay"))) { |
| 18 | + Py_RETURN_FALSE; |
| 19 | + } |
| 20 | + Display* display = XOpenDisplay(NULL); |
| 21 | + if (display) { |
| 22 | + XCloseDisplay(display); |
| 23 | + } |
| 24 | + if (dlclose(x11)) { |
| 25 | + PyErr_SetString(PyExc_RuntimeError, dlerror()); |
| 26 | + return NULL; |
| 27 | + } |
| 28 | + if (display) { |
| 29 | + Py_RETURN_FALSE; |
| 30 | + } else { |
| 31 | + Py_RETURN_TRUE; |
| 32 | + } |
| 33 | +#else |
| 34 | + Py_RETURN_FALSE; |
| 35 | +#endif |
| 36 | +} |
| 37 | + |
| 38 | +static PyMethodDef functions[] = { |
| 39 | + {"invalid_display", (PyCFunction)mpl_invalid_display, METH_NOARGS, |
| 40 | + "invalid_display()\n--\n\n" |
| 41 | + "Attempt to check whether the current X11 display is invalid.\n\n" |
| 42 | + "Returns True if running on Linux and libX11 can be loaded and \n" |
| 43 | + "XOpenDisplay(NULL) returns NULL, False otherwise."}, |
| 44 | + {NULL, NULL}}; // sentinel. |
| 45 | +static PyModuleDef util_module = { |
| 46 | + PyModuleDef_HEAD_INIT, "_c_internal_utils", "", 0, functions, NULL, NULL, NULL, NULL}; |
| 47 | + |
| 48 | +PyMODINIT_FUNC PyInit__c_internal_utils(void) |
| 49 | +{ |
| 50 | + return PyModule_Create(&util_module); |
| 51 | +} |
0 commit comments