aabfd6e9914db10f41f0b6623e1e034b7cc4d153
[screen-lua.git] / src / lua.c
blobaabfd6e9914db10f41f0b6623e1e034b7cc4d153
1 /* Lua scripting support
3 * Copyright (c) 2008 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>
23 #include "config.h"
24 #include "screen.h"
25 #include <sys/stat.h>
26 #include <unistd.h>
28 #include <stdio.h>
29 #include <string.h>
30 #include <stdlib.h>
32 #include "extern.h"
33 #include "logfile.h"
35 #include <lua.h>
36 #include <lauxlib.h>
37 #include <lualib.h>
39 extern struct win *windows, *fore;
40 extern struct display *displays, *display;
41 extern struct LayFuncs WinLf;
42 extern struct layer *flayer;
44 static int LuaDispatch(void *handler, const char *params, va_list va);
45 static int LuaRegEvent(lua_State *L);
47 /** Template {{{ */
49 #define CHECK_TYPE(name, type) \
50 static type * \
51 check_##name(lua_State *L, int index) \
52 { \
53 type **var; \
54 luaL_checktype(L, index, LUA_TUSERDATA); \
55 var = (type **) luaL_checkudata(L, index, #name); \
56 if (!var || !*var) \
57 luaL_typerror(L, index, #name); \
58 return *var; \
61 #define PUSH_TYPE(name, type) \
62 static void \
63 push_##name(lua_State *L, type **t) \
64 { \
65 if (!t || !*t) \
66 lua_pushnil(L); \
67 else \
68 { \
69 type **r; \
70 r = (type **)lua_newuserdata(L, sizeof(type *)); \
71 *r = *t; \
72 luaL_getmetatable(L, #name); \
73 lua_setmetatable(L,-2); \
74 } \
77 /* Much of the following template comes from:
78 * http://lua-users.org/wiki/BindingWithMembersAndMethods
81 static int get_int (lua_State *L, void *v)
83 lua_pushinteger (L, *(int*)v);
84 return 1;
87 static int set_int (lua_State *L, void *v)
89 *(int*)v = luaL_checkint(L, 3);
90 return 0;
93 static int get_number (lua_State *L, void *v)
95 lua_pushnumber(L, *(lua_Number*)v);
96 return 1;
99 static int set_number (lua_State *L, void *v)
101 *(lua_Number*)v = luaL_checknumber(L, 3);
102 return 0;
105 static int get_string (lua_State *L, void *v)
107 lua_pushstring(L, (char*)v );
108 return 1;
111 static int set_string (lua_State *L, void *v)
113 *(const char**)v = luaL_checkstring(L, 3);
114 return 0;
117 typedef int (*Xet_func) (lua_State *L, void *v);
119 /* member info for get and set handlers */
120 struct Xet_reg
122 const char *name; /* member name */
123 Xet_func func; /* get or set function for type of member */
124 size_t offset; /* offset of member within the struct */
125 int (*absolute)(lua_State *);
128 static void Xet_add (lua_State *L, const struct Xet_reg *l)
130 if (!l)
131 return;
132 for (; l->name; l++)
134 lua_pushstring(L, l->name);
135 lua_pushlightuserdata(L, (void*)l);
136 lua_settable(L, -3);
140 static int Xet_call (lua_State *L)
142 /* for get: stack has userdata, index, lightuserdata */
143 /* for set: stack has userdata, index, value, lightuserdata */
144 const struct Xet_reg *m = (const struct Xet_reg *)lua_touserdata(L, -1); /* member info */
145 lua_pop(L, 1); /* drop lightuserdata */
146 luaL_checktype(L, 1, LUA_TUSERDATA);
147 if (m->absolute)
148 return m->absolute(L);
149 return m->func(L, *(char**)lua_touserdata(L, 1) + m->offset);
152 static int index_handler (lua_State *L)
154 /* stack has userdata, index */
155 lua_pushvalue(L, 2); /* dup index */
156 lua_rawget(L, lua_upvalueindex(1)); /* lookup member by name */
157 if (!lua_islightuserdata(L, -1))
159 lua_pop(L, 1); /* drop value */
160 lua_pushvalue(L, 2); /* dup index */
161 lua_gettable(L, lua_upvalueindex(2)); /* else try methods */
162 if (lua_isnil(L, -1)) /* invalid member */
163 luaL_error(L, "cannot get member '%s'", lua_tostring(L, 2));
164 return 1;
166 return Xet_call(L); /* call get function */
169 static int newindex_handler (lua_State *L)
171 /* stack has userdata, index, value */
172 lua_pushvalue(L, 2); /* dup index */
173 lua_rawget(L, lua_upvalueindex(1)); /* lookup member by name */
174 if (!lua_islightuserdata(L, -1)) /* invalid member */
175 luaL_error(L, "cannot set member '%s'", lua_tostring(L, 2));
176 return Xet_call(L); /* call set function */
179 static int
180 struct_register(lua_State *L, const char *name, const luaL_reg fn_methods[], const luaL_reg meta_methods[],
181 const struct Xet_reg setters[], const struct Xet_reg getters[])
183 int metatable, methods;
185 /* create methods table & add it to the table of globals */
186 luaL_register(L, name, fn_methods);
187 methods = lua_gettop(L);
189 /* create metatable & add it to the registry */
190 luaL_newmetatable(L, name);
191 luaL_register(L, 0, meta_methods); /* fill metatable */
193 /* To identify the type of object */
194 lua_pushstring(L, "_objname");
195 lua_pushstring(L, name);
196 lua_settable(L, -3);
198 metatable = lua_gettop(L);
200 lua_pushliteral(L, "__metatable");
201 lua_pushvalue(L, methods); /* dup methods table*/
202 lua_rawset(L, metatable); /* hide metatable:
203 metatable.__metatable = methods */
205 lua_pushliteral(L, "__index");
206 lua_pushvalue(L, metatable); /* upvalue index 1 */
207 Xet_add(L, getters); /* fill metatable with getters */
208 lua_pushvalue(L, methods); /* upvalue index 2 */
209 lua_pushcclosure(L, index_handler, 2);
210 lua_rawset(L, metatable); /* metatable.__index = index_handler */
212 lua_pushliteral(L, "__newindex");
213 lua_newtable(L); /* table for members you can set */
214 Xet_add(L, setters); /* fill with setters */
215 lua_pushcclosure(L, newindex_handler, 1);
216 lua_rawset(L, metatable); /* metatable.__newindex = newindex_handler */
218 lua_pop(L, 1); /* drop metatable */
219 return 1; /* return methods on the stack */
222 /** }}} */
224 /** Window {{{ */
226 PUSH_TYPE(window, struct win)
228 CHECK_TYPE(window, struct win)
230 static int get_window(lua_State *L, void *v)
232 push_window(L, (struct win **)v);
233 return 1;
236 static int
237 window_change_title(lua_State *L)
239 struct win *w = check_window(L, 1);
240 unsigned int len;
241 const char *title = luaL_checklstring(L, 2, &len);
242 ChangeAKA(w, (char *)title, len);
243 return 0;
246 static int
247 window_get_monitor_status(lua_State *L)
249 struct win *w = check_window(L, 1);
250 int activity = luaL_checkint(L, 2);
251 if (activity)
252 /*monitor*/
253 lua_pushinteger(L, w->w_monitor != MON_OFF);
254 else
255 /*silence*/
256 lua_pushinteger(L, w->w_silence == SILENCE_ON ? w->w_silencewait: 0);
258 return 1;
261 static const luaL_reg window_methods[] = {
262 {"get_monitor_status", window_get_monitor_status},
263 {"listen_to", LuaRegEvent},
264 {0, 0}
267 static int
268 window_tostring(lua_State *L)
270 char str[128];
271 struct win *w = check_window(L, 1);
272 snprintf(str, sizeof(str), "{window #%d: '%s'}", w->w_number, w->w_title);
273 lua_pushstring(L, str);
274 return 1;
277 static int
278 window_equality(lua_State *L)
280 struct win *w1 = check_window(L, 1), *w2 = check_window(L, 2);
281 lua_pushboolean(L, (w1 == w2 || (w1 && w2 && w1->w_number == w2->w_number)));
282 return 1;
285 static const luaL_reg window_metamethods[] = {
286 {"__tostring", window_tostring},
287 {"__eq", window_equality},
288 {0, 0}
291 static const struct Xet_reg window_setters[] = {
292 {"title", 0, 0, window_change_title/*absolute setter*/},
293 {0, 0}
296 static const struct Xet_reg window_getters[] = {
297 {"title", get_string, offsetof(struct win, w_title) + 8},
298 {"number", get_int, offsetof(struct win, w_number)},
299 {"dir", get_string, offsetof(struct win, w_dir)},
300 {"tty", get_string, offsetof(struct win, w_tty)},
301 {"pid", get_int, offsetof(struct win, w_pid)},
302 {"group", get_window, offsetof(struct win, w_group)},
303 {"bell", get_int, offsetof(struct win, w_bell)},
304 {0, 0}
308 /** }}} */
310 /** AclUser {{{ */
312 PUSH_TYPE(user, struct acluser)
314 CHECK_TYPE(user, struct acluser)
316 static int
317 get_user(lua_State *L, void *v)
319 push_user(L, (struct acluser **)v);
320 return 1;
323 static const luaL_reg user_methods[] = {
324 {0, 0}
327 static int
328 user_tostring(lua_State *L)
330 char str[128];
331 struct acluser *u = check_user(L, 1);
332 snprintf(str, sizeof(str), "{user '%s'}", u->u_name);
333 lua_pushstring(L, str);
334 return 1;
337 static const luaL_reg user_metamethods[] = {
338 {"__tostring", user_tostring},
339 {0, 0}
342 static const struct Xet_reg user_setters[] = {
343 {0, 0}
346 static const struct Xet_reg user_getters[] = {
347 {"name", get_string, offsetof(struct acluser, u_name)},
348 {"password", get_string, offsetof(struct acluser, u_password)},
349 {0, 0}
352 /** }}} */
354 /** Canvas {{{ */
356 PUSH_TYPE(canvas, struct canvas)
358 CHECK_TYPE(canvas, struct canvas)
360 static int
361 get_canvas(lua_State *L, void *v)
363 push_canvas(L, (struct canvas **)v);
364 return 1;
367 static int
368 canvas_select(lua_State *L)
370 struct canvas *c = check_canvas(L, 1);
371 if (!display || D_forecv == c)
372 return 0;
373 SetCanvasWindow(c, Layer2Window(c->c_layer));
374 D_forecv = c;
376 /* XXX: the following all is duplicated from process.c:DoAction.
377 * Should these be in some better place?
379 ResizeCanvas(&D_canvas);
380 RecreateCanvasChain();
381 RethinkDisplayViewports();
382 ResizeLayersToCanvases(); /* redisplays */
383 fore = D_fore = Layer2Window(D_forecv->c_layer);
384 flayer = D_forecv->c_layer;
385 #ifdef RXVT_OSC
386 if (D_xtermosc[2] || D_xtermosc[3])
388 Activate(-1);
389 break;
391 #endif
392 RefreshHStatus();
393 #ifdef RXVT_OSC
394 RefreshXtermOSC();
395 #endif
396 flayer = D_forecv->c_layer;
397 CV_CALL(D_forecv, LayRestore();LaySetCursor());
398 WindowChanged(0, 'F');
399 return 1;
402 static const luaL_reg canvas_methods[] = {
403 {"select", canvas_select},
404 {0, 0}
407 static const luaL_reg canvas_metamethods[] = {
408 {0, 0}
411 static const struct Xet_reg canvas_setters[] = {
412 {0, 0}
415 static int
416 canvas_get_window(lua_State *L)
418 struct canvas *c = check_canvas(L, 1);
419 struct win *win = Layer2Window(c->c_layer);
420 if (win)
421 push_window(L, &win);
422 else
423 lua_pushnil(L);
424 return 1;
427 static const struct Xet_reg canvas_getters[] = {
428 {"next", get_canvas, offsetof(struct canvas, c_next)},
429 {"xoff", get_int, offsetof(struct canvas, c_xoff)},
430 {"yoff", get_int, offsetof(struct canvas, c_yoff)},
431 {"xs", get_int, offsetof(struct canvas, c_xs)},
432 {"ys", get_int, offsetof(struct canvas, c_ys)},
433 {"xe", get_int, offsetof(struct canvas, c_xe)},
434 {"ye", get_int, offsetof(struct canvas, c_ye)},
435 {"window", 0, 0, canvas_get_window},
436 {0, 0}
439 /** }}} */
441 /** Layout {{{ */
443 PUSH_TYPE(layout, struct layout)
444 CHECK_TYPE(layout, struct layout)
446 static const struct Xet_reg layout_getters[] = {
447 {0,0}
450 static int
451 get_layout(lua_State *L, void *v)
453 push_layout(L, (struct layout **)v);
454 return 1;
457 /** }}} */
459 /** Display {{{ */
461 PUSH_TYPE(display, struct display)
463 CHECK_TYPE(display, struct display)
465 static int
466 display_get_canvases(lua_State *L)
468 struct display *d;
469 struct canvas *iter;
470 int count;
472 d = check_display(L, 1);
473 lua_newtable(L);
474 for (iter = d->d_cvlist, count = 0; iter; iter = iter->c_next, count++) {
475 lua_pushinteger(L, count);
476 push_canvas(L, &iter);
477 lua_settable(L, -3);
480 return 1;
483 static const luaL_reg display_methods[] = {
484 {"get_canvases", display_get_canvases},
485 {0, 0}
488 static int
489 display_tostring(lua_State *L)
491 char str[128];
492 struct display *d = check_display(L, 1);
493 snprintf(str, sizeof(str), "{display: tty = '%s', term = '%s'}", d->d_usertty, d->d_termname);
494 lua_pushstring(L, str);
495 return 1;
498 static const luaL_reg display_metamethods[] = {
499 {"__tostring", display_tostring},
500 {0, 0}
503 static const struct Xet_reg display_setters[] = {
504 {0, 0}
507 static const struct Xet_reg display_getters[] = {
508 {"tty", get_string, offsetof(struct display, d_usertty)},
509 {"term", get_string, offsetof(struct display, d_termname)},
510 {"fore", get_window, offsetof(struct display, d_fore)},
511 {"other", get_window, offsetof(struct display, d_other)},
512 {"width", get_int, offsetof(struct display, d_width)},
513 {"height", get_int, offsetof(struct display, d_height)},
514 {"user", get_user, offsetof(struct display, d_user)},
515 {"layout", get_layout, offsetof(struct display, d_layout)},
516 {0, 0}
519 /** }}} */
521 /** Screen {{{ */
523 static int
524 screen_get_windows(lua_State *L)
526 struct win *iter;
527 int count;
529 lua_newtable(L);
530 for (iter = windows, count = 0; iter; iter = iter->w_next, count++) {
531 lua_pushinteger(L, iter->w_number);
532 push_window(L, &iter);
533 lua_settable(L, -3);
536 return 1;
539 static int
540 screen_get_displays(lua_State *L)
542 struct display *iter;
543 int count;
545 lua_newtable(L);
546 for (iter = displays, count = 0; iter; iter = iter->d_next, count++) {
547 lua_pushinteger(L, count);
548 push_display(L, &iter);
549 lua_settable(L, -3);
552 return 1;
555 static int
556 screen_get_display(lua_State *L)
558 push_display(L, &display);
559 return 1;
562 static int
563 screen_exec_command(lua_State *L)
565 const char *command;
566 unsigned int len;
568 command = luaL_checklstring(L, 1, &len);
569 if (command)
570 RcLine((char *)command, len);
572 return 0;
575 static int
576 screen_append_msg(lua_State *L)
578 const char *msg, *color;
579 int len;
580 msg = luaL_checklstring(L, 1, &len);
581 if (lua_isnil(L, 2))
582 color = NULL;
583 else
584 color = luaL_checklstring(L, 2, &len);
585 AppendWinMsgRend(msg, color);
586 return 0;
589 static const luaL_reg screen_methods[] = {
590 {"windows", screen_get_windows},
591 {"displays", screen_get_displays},
592 {"display", screen_get_display},
593 {"command", screen_exec_command},
594 {"append_msg", screen_append_msg},
595 {"listen_to", LuaRegEvent},
596 {0, 0}
599 static const luaL_reg screen_metamethods[] = {
600 {0, 0}
603 static const struct Xet_reg screen_setters[] = {
604 {0, 0}
607 static const struct Xet_reg screen_getters[] = {
608 {0, 0}
611 /** }}} */
613 /** Public functions {{{ */
614 static lua_State *L;
615 int LuaInit(void)
617 L = luaL_newstate();
619 luaL_openlibs(L);
621 #define REGISTER(X) struct_register(L, #X , X ## _methods, X##_metamethods, X##_setters, X##_getters)
623 REGISTER(screen);
624 REGISTER(window);
625 REGISTER(display);
626 REGISTER(user);
627 REGISTER(canvas);
629 return 0;
632 /* An error message on top of the stack. */
633 static void
634 LuaShowErr(lua_State *L)
636 struct display *d = display;
637 unsigned int len;
638 const char *message = luaL_checklstring(L, -1, &len);
639 LMsg(0, "%s", message ? message : "Unknown error");
640 lua_pop(L, 1);
641 display = d;
644 struct fn_def
646 void (*push_fn)(lua_State *, void*);
647 void *value;
650 static int
651 LuaCallProcess(const char *name, struct fn_def defs[])
653 int argc = 0;
655 lua_settop(L, 0);
656 lua_getfield(L, LUA_GLOBALSINDEX, name);
657 if (lua_isnil(L, -1))
658 return 0;
659 for (argc = 0; defs[argc].push_fn; argc++)
660 defs[argc].push_fn(L, defs[argc].value);
661 if (lua_pcall(L, argc, 0, 0) == LUA_ERRRUN && lua_isstring(L, -1))
663 LuaShowErr(L);
664 return 0;
666 return 1;
669 int LuaSource(const char *file, int async)
671 if (!L)
672 return 0;
673 struct stat st;
674 if (stat(file, &st) == -1)
675 Msg(errno, "Error loading lua script file '%s'", file);
676 else
678 int len = strlen(file);
679 if (len < 4 || strncmp(file + len - 4, ".lua", 4) != 0)
680 return 0;
681 if (luaL_dofile(L, file) && lua_isstring(L, -1))
683 LuaShowErr(L);
685 return 1;
687 return 0;
690 int LuaFinit(void)
692 if (!L)
693 return 0;
694 lua_close(L);
695 L = (lua_State*)0;
696 return 0;
700 LuaProcessCaption(const char *caption, struct win *win, int len)
702 if (!L)
703 return 0;
704 struct fn_def params[] = {
705 {lua_pushstring, caption},
706 {push_window, &win},
707 {lua_pushinteger, len},
708 {NULL, NULL}
710 return LuaCallProcess("process_caption", params);
713 static void
714 push_stringarray(lua_State *L, char **args)
716 int i;
717 lua_newtable(L);
718 for (i = 1; args && *args; i++) {
719 lua_pushinteger(L, i);
720 lua_pushstring(L, *args++);
721 lua_settable(L, -3);
726 LuaPushParams(lua_State *L, const char *params, va_list va)
728 int num = 0;
729 while (*params)
731 switch (*params)
733 case 's':
734 lua_pushstring(L, va_arg(va, char *));
735 break;
736 case 'S':
737 push_stringarray(L, va_arg(va, char **));
738 break;
739 case 'i':
740 lua_pushinteger(L, va_arg(va, int));
742 params++;
743 num++;
745 return num;
748 int LuaCall(char *func, char **argv)
750 int argc;
751 if (!L)
752 return 0;
754 lua_getfield(L, LUA_GLOBALSINDEX, func);
755 for (argc = 0; *argv; argv++, argc++)
757 lua_pushstring(L, *argv);
759 if (lua_pcall(L, argc, 0, 0) == LUA_ERRRUN)
761 if(lua_isstring(L, -1))
763 LuaShowErr(L);
764 return 0;
767 return 1;
770 static int
771 LuaDispatch(void *handler, const char *params, va_list va)
773 const char *func = handler;
774 int argc;
776 /*FIXME:Really need this?*/
777 lua_settop(L, 0);
779 lua_getfield(L, LUA_GLOBALSINDEX, func);
780 if (lua_isnil(L, -1))
781 return 0;
782 argc = LuaPushParams(L, params, va);
784 if (lua_pcall(L, argc, 0, 0) == LUA_ERRRUN && lua_isstring(L, -1))
786 LuaShowErr(L);
787 return 0;
789 return 1;
792 int LuaForeWindowChanged(void)
794 struct fn_def params[] = {
795 {push_display, &display},
796 {push_window, display ? &D_fore : &fore},
797 {NULL, NULL}
799 if (!L)
800 return 0;
801 return LuaCallProcess("fore_changed", params);
806 LuaCommandExecuted(const char *command, const char **args, int argc)
808 if (!L)
809 return 0;
810 struct fn_def params[] = {
811 {lua_pushstring, command},
812 {push_stringarray, args},
813 {NULL, NULL}
815 return LuaCallProcess("command_executed", params);
818 static int
819 LuaRegEvent(lua_State *L)
821 /* signature: listen_to(obj, event, handler, priv);
822 * or: listen_to(event, handler, priv)
823 * returns: A ticket for later unregister. */
824 int idx = 1, argc = lua_gettop(L);
825 int priv = 0;
827 char *obj = NULL;
828 const char *objname = "global";
830 static char evbuf[30];
831 const char *event, *handler;
833 struct script_event *sev;
835 /* Identify the object, if specified */
836 if (luaL_getmetafield(L, 1, "_objname"))
838 objname = luaL_checkstring(L, -1);
839 lua_pop(L, 1);
840 if (!strcmp("screen", objname))
841 objname = "global";
842 else
843 obj = *(char **)lua_touserdata(L, 1);
844 idx++;
847 event = luaL_checkstring(L, idx++);
848 snprintf(evbuf, 30, "%s_%s", objname, event);
849 handler = luaL_checkstring(L, idx++);
850 if (idx <= argc)
851 priv = luaL_checkinteger(L, idx);
853 sev = object_get_event(obj, evbuf);
854 if (sev)
856 struct listener *l;
857 l = (struct listener *)malloc(sizeof(struct listener));
858 if (!l)
859 return luaL_error(L, "Out of memory");
860 l->handler = (void *)handler;
861 l->priv = priv;
862 l->dispatcher = LuaDispatch;
863 register_listener(sev, l);
864 /*Return the handler for un-register*/
865 lua_pushlightuserdata(L, l);
867 else
868 return luaL_error(L, "Invalid event specified: %s for object %s", event, objname);
870 return 1;
873 static int
874 LuaUnRegEvent(lua_State *L)
876 /* signature: release([obj], ticket, handler)
877 * returns: zero of success, non-zero otherwise */
878 int idx = 1;
879 struct listener *l;
880 const char *handler;
881 if (lua_isuserdata(L, idx))
882 idx++;
884 luaL_checktype(L, idx, LUA_TLIGHTUSERDATA);
885 l = (struct listener*)lua_touserdata(L, idx++);
886 handler = luaL_checkstring(L, idx++);
888 /*Validate the listener structure*/
889 if (strcmp((char *)handler, (char *)l->handler))
891 /* invalid */
892 lua_pushinteger(L, 1);
894 else
896 unregister_listener(l);
897 lua_pushinteger(L, 0);
900 return 1;
903 /** }}} */
905 struct ScriptFuncs LuaFuncs =
907 LuaForeWindowChanged,
908 LuaProcessCaption
911 struct binding lua_binding =
913 "lua", /*name*/
914 0, /*inited*/
915 0, /*registered*/
916 LuaInit,
917 LuaFinit,
918 LuaCall,
919 LuaSource,
920 0, /*b_next*/
921 &LuaFuncs