Represent!
[screen-lua.git] / src / python.c
blobf33a03e57100f6f8ed8602e12e24ec9d4fae7aa5
1 /* Python scripting support
3 * Copyright (c) 2009 Sadrul Habib Chowdhury (sadrul@users.sf.net)
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 3, or (at your option)
8 * any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program (see the file COPYING); if not, write to the
17 * Free Software Foundation, Inc.,
18 * 51 Franklin Street, Fifth Floor, Boston, MA 02111-1301 USA
20 ****************************************************************
22 #include <sys/types.h>
24 #include "config.h"
25 #include "screen.h"
26 #include "script.h"
27 #include <sys/stat.h>
28 #include <unistd.h>
30 #include <stdio.h>
31 #include <string.h>
32 #include <stdlib.h>
34 #include "extern.h"
35 #include "logfile.h"
37 #include <Python.h>
38 #include <structmember.h>
40 #define RETURN_NONE do { Py_INCREF(Py_None); return Py_None; } while (0)
42 extern struct win *windows;
43 extern struct display *display, *displays;
44 extern struct layer *flayer;
46 static PyObject * SPy_Get(PyObject *obj, void *closure);
47 static PyObject * SPy_Set(PyObject *obj, PyObject *value, void *closure);
48 static int PyDispatch(void *handler, const char *params, va_list va);
50 typedef struct
52 PyObject *callback;
53 struct listener *listener;
54 } SPyCallback;
56 typedef struct
58 char *name;
59 char *doc;
61 int type;
62 size_t offset1;
63 size_t offset2;
64 PyObject * (*conv)(void *);
65 } SPyClosure;
68 #define compare_display NULL
69 #define compare_callback NULL
71 #define repr_display NULL
72 #define repr_callback NULL
74 #define REGISTER_TYPE(type, Type, closures, methods) \
75 static int \
76 register_##type(PyObject *module) \
77 { \
78 static PyGetSetDef getsets[sizeof(closures)]; \
79 int i, count = sizeof(closures); \
80 for (i = 0; i < count; i++) \
81 { \
82 getsets[i].name = closures[i].name; \
83 getsets[i].doc = closures[i].doc; \
84 getsets[i].closure = &closures[i]; \
85 getsets[i].get = SPy_Get; \
86 getsets[i].set = SPy_Set; \
87 } \
88 PyType##Type.tp_getset = getsets; \
89 PyType##Type.tp_methods = methods; \
90 PyType##Type.tp_compare = compare_##type; \
91 PyType##Type.tp_repr = repr_##type; \
92 PyType_Ready(&PyType##Type); \
93 Py_INCREF(&PyType##Type); \
94 PyModule_AddObject(module, #Type, (PyObject *)&PyType##Type); \
95 return 1; \
98 #define DEFINE_TYPE(str, Type) \
99 typedef struct \
101 PyObject_HEAD \
102 str *_obj; \
103 } Py##Type; \
105 static PyTypeObject PyType##Type = \
107 PyObject_HEAD_INIT(NULL) \
108 .ob_size = 0, \
109 .tp_name = "screen." #Type, \
110 .tp_basicsize = sizeof(Py##Type), \
111 .tp_flags = Py_TPFLAGS_DEFAULT, \
112 .tp_doc = #Type " object", \
113 .tp_methods = NULL, \
114 .tp_getset = NULL, \
115 }; \
117 static PyObject * \
118 PyObject_From##Type(str *_obj) \
120 Py##Type *obj = PyType##Type.tp_alloc(&PyType##Type, 0); \
121 obj->_obj = _obj; \
122 return (PyObject *)obj; \
125 static PyObject *
126 PyString_FromStringSafe(const char *str)
128 if (str)
129 return PyString_FromString(str);
130 RETURN_NONE;
133 /** Window {{{ */
134 DEFINE_TYPE(struct win, Window)
136 #define SPY_CLOSURE(name, doc, type, member, func) \
137 {name, doc, type, offsetof(PyWindow, _obj), offsetof(struct win, member), func}
138 static SPyClosure wclosures[] =
140 SPY_CLOSURE("title", "Window title", T_STRING, w_title, NULL),
141 SPY_CLOSURE("number", "Window number", T_INT, w_number, NULL),
142 SPY_CLOSURE("dir", "Window directory", T_STRING, w_dir, NULL),
143 SPY_CLOSURE("tty", "TTY belonging to the window", T_STRING_INPLACE, w_tty, NULL),
144 SPY_CLOSURE("group", "The group the window belongs to", T_OBJECT_EX, w_group, PyObject_FromWindow),
145 SPY_CLOSURE("pid", "Window pid", T_INT, w_pid, NULL),
146 {NULL}
149 static PyObject *
150 window_select(PyObject *self)
152 PyWindow *win = self;
153 struct win *w = win->_obj;
154 SwitchWindow(w->w_number);
155 RETURN_NONE;
158 static PyMethodDef wmethods[] = {
159 {"select", (PyCFunction)window_select, METH_NOARGS, "Select the window."},
160 {NULL},
163 static int
164 compare_window(PyWindow *one, PyWindow *two)
166 struct win *wone = one->_obj;
167 struct win *wtwo = two->_obj;
169 return wtwo->w_number - wone->w_number;
172 static PyObject *
173 repr_window(PyObject *obj)
175 PyWindow *w = obj;
176 struct win *win = w->_obj;
177 return PyString_FromFormat("window (title: %s, number: %d)", win->w_title, win->w_number);
180 REGISTER_TYPE(window, Window, wclosures, wmethods)
181 #undef SPY_CLOSURE
182 /** }}} */
184 /** Display {{{ */
185 DEFINE_TYPE(struct display, Display)
187 #define SPY_CLOSURE(name, doc, type, member, func) \
188 {name, doc, type, offsetof(PyDisplay, _obj), offsetof(struct display, member), func}
189 static SPyClosure dclosures[] =
191 SPY_CLOSURE("tty", "Display TTY", T_STRING_INPLACE, d_usertty, NULL),
192 SPY_CLOSURE("term", "Display Term", T_STRING_INPLACE, d_termname, NULL),
193 SPY_CLOSURE("fore", "Foreground window of the display", T_OBJECT_EX, d_fore, PyObject_FromWindow),
194 SPY_CLOSURE("width", "Display width", T_INT, d_width, NULL),
195 SPY_CLOSURE("height", "Display height", T_INT, d_height, NULL),
196 {NULL}
198 REGISTER_TYPE(display, Display, dclosures, NULL)
199 #undef SPY_CLOSURE
200 /** }}} */
202 /** Callback {{{ */
203 DEFINE_TYPE(SPyCallback, Callback)
204 static SPyClosure cclosures[] = {{NULL}};
206 static void
207 FreeCallback(SPyCallback *scallback)
209 Py_XDECREF(scallback->callback);
210 Free(scallback);
213 static PyObject *
214 callback_unhook(PyObject *obj)
216 PyCallback *cb = obj;
217 SPyCallback *scallback = cb->_obj;
218 if (!scallback)
219 return NULL;
220 unregister_listener(scallback->listener);
221 FreeCallback(scallback);
222 cb->_obj = NULL;
223 RETURN_NONE;
226 static PyMethodDef cmethods[] = {
227 {"unhook", (PyCFunction)callback_unhook, METH_NOARGS, "Unhook this event callback."},
228 {NULL}
230 REGISTER_TYPE(callback, Callback, cclosures, cmethods)
231 /** }}} */
233 static PyObject *
234 SPy_Get(PyObject *obj, void *closure)
236 SPyClosure *sc = closure;
237 char **first = (char *)obj + sc->offset1;
238 char **second = (char *)*first + sc->offset2;
239 PyObject *(*cb)(void *) = sc->conv;
240 void *data = *second;
242 if (!cb)
244 switch (sc->type)
246 case T_STRING:
247 cb = PyString_FromStringSafe;
248 data = *second;
249 break;
250 case T_STRING_INPLACE:
251 cb = PyString_FromStringSafe;
252 data = second;
253 break;
254 case T_INT:
255 cb = PyInt_FromLong;
256 data = *second;
257 break;
260 return cb(data);
263 static PyObject *
264 SPy_Set(PyObject *obj, PyObject *value, void *closure)
266 return NULL;
269 static int
270 PyDispatch(void *handler, const char *params, va_list va)
272 PyCallback *callback = handler;
273 PyObject *args, *ret;
274 int count, retval;
275 const char *p;
276 SPyCallback *scallback = callback->_obj;
278 for (count = 0, p = params; *p; p++, count++)
280 if (count > 0)
281 args = PyTuple_New(count);
282 else
283 args = NULL;
285 for (count = 0, p = params; *p; p++, count++)
287 PyObject *item = NULL;
288 switch (*p)
290 case 's':
291 item = PyString_FromStringSafe(va_arg(va, char *));
292 break;
293 case 'S':
295 char **ls = va_arg(va, char **), **iter;
296 int c = 0;
297 for (iter = ls; iter && *iter; iter++, c++)
299 if (c == 0)
300 break;
301 item = PyTuple_New(c);
302 for (c = 0, iter = ls; iter && *iter; iter++, c++)
303 PyTuple_SetItem(item, c, PyString_FromStringSafe(*iter));
305 break;
306 case 'i':
307 item = PyInt_FromLong(va_arg(va, int));
308 break;
309 case 'd':
310 item = PyObject_FromDisplay(va_arg(va, struct display *));
311 break;
314 if (!item)
316 item = Py_None;
317 Py_INCREF(Py_None);
319 PyTuple_SetItem(args, count, item);
322 ret = PyObject_CallObject(scallback->callback, args);
323 Py_DECREF(args);
324 if (!ret)
325 return 0;
327 retval = (int)PyInt_AsLong(ret);
328 Py_DECREF(ret);
329 return retval;
332 /** Screen {{{ */
333 static PyObject *
334 screen_display(PyObject *self)
336 if (!display)
338 RETURN_NONE;
340 return PyObject_FromDisplay(display);
343 static PyObject *
344 screen_displays(PyObject *self)
346 struct display *d = displays;
347 int count = 0;
348 for (; d; d = d->d_next)
349 ++count;
350 PyObject *tuple = PyTuple_New(count);
352 for (d = displays, count = 0; d; d = d->d_next, ++count)
353 PyTuple_SetItem(tuple, count, PyObject_FromDisplay(d));
355 return tuple;
358 static PyObject *
359 screen_windows(PyObject *self)
361 struct win *w = windows;
362 int count = 0;
363 for (; w; w = w->w_next)
364 ++count;
365 PyObject *tuple = PyTuple_New(count);
367 for (w = windows, count = 0; w; w = w->w_next, ++count)
368 PyTuple_SetItem(tuple, count, PyObject_FromWindow(w));
370 return tuple;
373 static PyObject *
374 hook_event(PyObject *self, PyObject *args, PyObject *kw)
376 static char *kwlist[] = {"event", "callback", NULL};
377 PyObject *callback;
378 char *name;
380 struct script_event *sev;
381 struct listener *l;
382 SPyCallback *scallback;
384 if (!PyArg_ParseTupleAndKeywords(args, kw, "sO:screen.hook", kwlist, &name, &callback))
385 return NULL; /* Return Py_None instead? */
387 if (!PyCallable_Check(callback))
389 PyErr_SetString(PyExc_TypeError, "The event-callback functions must be callable.");
390 LMsg(0, "The event-callback functions must be callable.");
391 return NULL;
394 sev = object_get_event(NULL, name);
395 if (!sev)
397 LMsg(0, "No event named '%s'", name);
398 return NULL;
401 l = malloc(sizeof(struct listener));
403 scallback = malloc(sizeof(SPyCallback));
404 scallback->callback = callback;
405 scallback->listener = l;
406 Py_INCREF(scallback->callback);
408 l->handler = PyObject_FromCallback(scallback);
409 l->priv = 0;
410 l->dispatcher = PyDispatch;
411 if (register_listener(sev, l))
413 Py_DECREF((PyObject *)l->handler);
414 FreeCallback(scallback);
415 Free(l);
417 LMsg(0, "Hook could not be registered.");
419 RETURN_NONE;
422 Py_INCREF((PyObject *)l->handler);
423 return l->handler;
426 static void
427 screen_input_cb(char *buf, int len, char *p)
429 PyObject *callback = p;
430 PyObject *str = PyTuple_New(1);
431 PyTuple_SetItem(str, 0, PyString_FromStringSafe(buf));
432 PyObject_CallObject(callback, str);
433 Py_DECREF(str);
434 Py_DECREF(callback);
437 static PyObject *
438 screen_input(PyObject *self, PyObject *args, PyObject *kw)
440 static char *kwlist[] = {"prompt", "callback", "value (optional)", NULL};
441 char *prompt, *pre = NULL;
442 PyObject *callback;
444 if (!PyArg_ParseTupleAndKeywords(args, kw, "sO|s:screen.input", kwlist, &prompt, &callback, &pre))
446 LMsg(0, "Could not parse all the parameters to screen.input call.");
447 return NULL;
450 if (!PyCallable_Check(callback))
452 LMsg(0, "Input callback must be a callable object.");
453 return NULL;
456 Py_INCREF(callback);
457 Input(prompt, 100 /* huh? */,
458 INP_COOKED, screen_input_cb, callback, 0);
460 if (pre && *pre)
462 int len = strlen(pre);
463 LayProcess(&pre, &len);
466 RETURN_NONE;
469 const PyMethodDef py_methods[] = {
470 {"display", (PyCFunction)screen_display, METH_NOARGS, "Get the current display."},
471 {"displays", (PyCFunction)screen_displays, METH_NOARGS, "Get the list of displays."},
472 {"hook", (PyCFunction)hook_event, METH_VARARGS|METH_KEYWORDS, "Hook a callback to an event."},
473 {"input", (PyCFunction)screen_input, METH_VARARGS|METH_KEYWORDS, "Read user input interactively."},
474 {"windows", (PyCFunction)screen_windows, METH_NOARGS, "Get the list of windows."},
475 {NULL, NULL, 0, NULL}
477 /** }}} */
479 static int
480 SPyInit(void)
482 PyObject *m;
484 Py_Initialize();
486 m = Py_InitModule3 ("screen", py_methods, NULL);
487 register_window(m);
488 register_display(m);
489 register_callback(m);
491 return 0;
494 static int
495 SPyFinit(void)
497 Py_Finalize();
498 return 0;
501 static int
502 SPySource(const char *file, int async)
504 FILE *f = fopen(file, "rb");
505 int ret = PyRun_SimpleFile(f, file);
506 fclose(f);
508 if (ret == 0)
509 return 1; /* Success */
511 if (PyErr_Occurred())
513 PyErr_Print();
514 return 0;
517 return 1;
520 struct binding py_binding =
522 "python",
525 SPyInit,
526 SPyFinit,
528 SPySource,