8da80f4ba2d6be89fc911cc24a4ad2f6443e9dea
[screen-lua.git] / src / lua.c
blob8da80f4ba2d6be89fc911cc24a4ad2f6443e9dea
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 /** Template {{{ */
47 #define CHECK_TYPE(name, type) \
48 static type * \
49 check_##name(lua_State *L, int index) \
50 { \
51 type **var; \
52 luaL_checktype(L, index, LUA_TUSERDATA); \
53 var = (type **) luaL_checkudata(L, index, #name); \
54 if (!var || !*var) \
55 luaL_typerror(L, index, #name); \
56 return *var; \
59 #define PUSH_TYPE(name, type) \
60 static void \
61 push_##name(lua_State *L, type **t) \
62 { \
63 if (!t || !*t) \
64 lua_pushnil(L); \
65 else \
66 { \
67 type **r; \
68 r = (type **)lua_newuserdata(L, sizeof(type *)); \
69 *r = *t; \
70 luaL_getmetatable(L, #name); \
71 lua_setmetatable(L,-2); \
72 } \
75 /* Much of the following template comes from:
76 * http://lua-users.org/wiki/BindingWithMembersAndMethods
79 static int get_int (lua_State *L, void *v)
81 lua_pushinteger (L, *(int*)v);
82 return 1;
85 static int set_int (lua_State *L, void *v)
87 *(int*)v = luaL_checkint(L, 3);
88 return 0;
91 static int get_number (lua_State *L, void *v)
93 lua_pushnumber(L, *(lua_Number*)v);
94 return 1;
97 static int set_number (lua_State *L, void *v)
99 *(lua_Number*)v = luaL_checknumber(L, 3);
100 return 0;
103 static int get_string (lua_State *L, void *v)
105 lua_pushstring(L, (char*)v );
106 return 1;
109 static int set_string (lua_State *L, void *v)
111 *(const char**)v = luaL_checkstring(L, 3);
112 return 0;
115 typedef int (*Xet_func) (lua_State *L, void *v);
117 /* member info for get and set handlers */
118 struct Xet_reg
120 const char *name; /* member name */
121 Xet_func func; /* get or set function for type of member */
122 size_t offset; /* offset of member within the struct */
123 int (*absolute)(lua_State *);
126 static void Xet_add (lua_State *L, const struct Xet_reg *l)
128 if (!l)
129 return;
130 for (; l->name; l++)
132 lua_pushstring(L, l->name);
133 lua_pushlightuserdata(L, (void*)l);
134 lua_settable(L, -3);
138 static int Xet_call (lua_State *L)
140 /* for get: stack has userdata, index, lightuserdata */
141 /* for set: stack has userdata, index, value, lightuserdata */
142 const struct Xet_reg *m = (const struct Xet_reg *)lua_touserdata(L, -1); /* member info */
143 lua_pop(L, 1); /* drop lightuserdata */
144 luaL_checktype(L, 1, LUA_TUSERDATA);
145 if (m->absolute)
146 return m->absolute(L);
147 return m->func(L, *(char**)lua_touserdata(L, 1) + m->offset);
150 static int index_handler (lua_State *L)
152 /* stack has userdata, index */
153 lua_pushvalue(L, 2); /* dup index */
154 lua_rawget(L, lua_upvalueindex(1)); /* lookup member by name */
155 if (!lua_islightuserdata(L, -1))
157 lua_pop(L, 1); /* drop value */
158 lua_pushvalue(L, 2); /* dup index */
159 lua_gettable(L, lua_upvalueindex(2)); /* else try methods */
160 if (lua_isnil(L, -1)) /* invalid member */
161 luaL_error(L, "cannot get member '%s'", lua_tostring(L, 2));
162 return 1;
164 return Xet_call(L); /* call get function */
167 static int newindex_handler (lua_State *L)
169 /* stack has userdata, index, value */
170 lua_pushvalue(L, 2); /* dup index */
171 lua_rawget(L, lua_upvalueindex(1)); /* lookup member by name */
172 if (!lua_islightuserdata(L, -1)) /* invalid member */
173 luaL_error(L, "cannot set member '%s'", lua_tostring(L, 2));
174 return Xet_call(L); /* call set function */
177 static int
178 struct_register(lua_State *L, const char *name, const luaL_reg fn_methods[], const luaL_reg meta_methods[],
179 const struct Xet_reg setters[], const struct Xet_reg getters[])
181 int metatable, methods;
183 /* create methods table & add it to the table of globals */
184 luaL_register(L, name, fn_methods);
185 methods = lua_gettop(L);
187 /* create metatable & add it to the registry */
188 luaL_newmetatable(L, name);
189 luaL_register(L, 0, meta_methods); /* fill metatable */
190 metatable = lua_gettop(L);
192 lua_pushliteral(L, "__metatable");
193 lua_pushvalue(L, methods); /* dup methods table*/
194 lua_rawset(L, metatable); /* hide metatable:
195 metatable.__metatable = methods */
197 lua_pushliteral(L, "__index");
198 lua_pushvalue(L, metatable); /* upvalue index 1 */
199 Xet_add(L, getters); /* fill metatable with getters */
200 lua_pushvalue(L, methods); /* upvalue index 2 */
201 lua_pushcclosure(L, index_handler, 2);
202 lua_rawset(L, metatable); /* metatable.__index = index_handler */
204 lua_pushliteral(L, "__newindex");
205 lua_newtable(L); /* table for members you can set */
206 Xet_add(L, setters); /* fill with setters */
207 lua_pushcclosure(L, newindex_handler, 1);
208 lua_rawset(L, metatable); /* metatable.__newindex = newindex_handler */
210 lua_pop(L, 1); /* drop metatable */
211 return 1; /* return methods on the stack */
214 /** }}} */
216 /** Window {{{ */
218 PUSH_TYPE(window, struct win)
220 CHECK_TYPE(window, struct win)
222 static int get_window(lua_State *L, void *v)
224 push_window(L, (struct win **)v);
225 return 1;
228 static int
229 window_change_title(lua_State *L)
231 struct win *w = check_window(L, 1);
232 unsigned int len;
233 const char *title = luaL_checklstring(L, 2, &len);
234 ChangeAKA(w, (char *)title, len);
235 return 0;
238 static int
239 window_get_monitor_status(lua_State *L)
241 struct win *w = check_window(L, 1);
242 int activity = luaL_checkint(L, 2);
243 if (activity)
244 /*monitor*/
245 lua_pushinteger(L, w->w_monitor != MON_OFF);
246 else
247 /*silence*/
248 lua_pushinteger(L, w->w_silence == SILENCE_ON ? w->w_silencewait: 0);
250 return 1;
253 static const luaL_reg window_methods[] = {
254 {"get_monitor_status", window_get_monitor_status},
255 {0, 0}
258 static int
259 window_tostring(lua_State *L)
261 char str[128];
262 struct win *w = check_window(L, 1);
263 snprintf(str, sizeof(str), "{window #%d: '%s'}", w->w_number, w->w_title);
264 lua_pushstring(L, str);
265 return 1;
268 static int
269 window_equality(lua_State *L)
271 struct win *w1 = check_window(L, 1), *w2 = check_window(L, 2);
272 lua_pushboolean(L, (w1 == w2 || (w1 && w2 && w1->w_number == w2->w_number)));
273 return 1;
276 static const luaL_reg window_metamethods[] = {
277 {"__tostring", window_tostring},
278 {"__eq", window_equality},
279 {0, 0}
282 static const struct Xet_reg window_setters[] = {
283 {"title", 0, 0, window_change_title/*absolute setter*/},
284 {0, 0}
287 static const struct Xet_reg window_getters[] = {
288 {"title", get_string, offsetof(struct win, w_title) + 8},
289 {"number", get_int, offsetof(struct win, w_number)},
290 {"dir", get_string, offsetof(struct win, w_dir)},
291 {"tty", get_string, offsetof(struct win, w_tty)},
292 {"pid", get_int, offsetof(struct win, w_pid)},
293 {"group", get_window, offsetof(struct win, w_group)},
294 {"bell", get_int, offsetof(struct win, w_bell)},
295 {0, 0}
299 /** }}} */
301 /** AclUser {{{ */
303 PUSH_TYPE(user, struct acluser)
305 CHECK_TYPE(user, struct acluser)
307 static int
308 get_user(lua_State *L, void *v)
310 push_user(L, (struct acluser **)v);
311 return 1;
314 static const luaL_reg user_methods[] = {
315 {0, 0}
318 static int
319 user_tostring(lua_State *L)
321 char str[128];
322 struct acluser *u = check_user(L, 1);
323 snprintf(str, sizeof(str), "{user '%s'}", u->u_name);
324 lua_pushstring(L, str);
325 return 1;
328 static const luaL_reg user_metamethods[] = {
329 {"__tostring", user_tostring},
330 {0, 0}
333 static const struct Xet_reg user_setters[] = {
334 {0, 0}
337 static const struct Xet_reg user_getters[] = {
338 {"name", get_string, offsetof(struct acluser, u_name)},
339 {"password", get_string, offsetof(struct acluser, u_password)},
340 {0, 0}
343 /** }}} */
345 /** Canvas {{{ */
347 PUSH_TYPE(canvas, struct canvas)
349 CHECK_TYPE(canvas, struct canvas)
351 static int
352 get_canvas(lua_State *L, void *v)
354 push_canvas(L, (struct canvas **)v);
355 return 1;
358 static int
359 canvas_select(lua_State *L)
361 struct canvas *c = check_canvas(L, 1);
362 if (!display || D_forecv == c)
363 return 0;
364 SetCanvasWindow(c, Layer2Window(c->c_layer));
365 D_forecv = c;
367 /* XXX: the following all is duplicated from process.c:DoAction.
368 * Should these be in some better place?
370 ResizeCanvas(&D_canvas);
371 RecreateCanvasChain();
372 RethinkDisplayViewports();
373 ResizeLayersToCanvases(); /* redisplays */
374 fore = D_fore = Layer2Window(D_forecv->c_layer);
375 flayer = D_forecv->c_layer;
376 #ifdef RXVT_OSC
377 if (D_xtermosc[2] || D_xtermosc[3])
379 Activate(-1);
380 break;
382 #endif
383 RefreshHStatus();
384 #ifdef RXVT_OSC
385 RefreshXtermOSC();
386 #endif
387 flayer = D_forecv->c_layer;
388 CV_CALL(D_forecv, LayRestore();LaySetCursor());
389 WindowChanged(0, 'F');
390 return 1;
393 static const luaL_reg canvas_methods[] = {
394 {"select", canvas_select},
395 {0, 0}
398 static const luaL_reg canvas_metamethods[] = {
399 {0, 0}
402 static const struct Xet_reg canvas_setters[] = {
403 {0, 0}
406 static int
407 canvas_get_window(lua_State *L)
409 struct canvas *c = check_canvas(L, 1);
410 struct win *win = Layer2Window(c->c_layer);
411 if (win)
412 push_window(L, &win);
413 else
414 lua_pushnil(L);
415 return 1;
418 static const struct Xet_reg canvas_getters[] = {
419 {"next", get_canvas, offsetof(struct canvas, c_next)},
420 {"xoff", get_int, offsetof(struct canvas, c_xoff)},
421 {"yoff", get_int, offsetof(struct canvas, c_yoff)},
422 {"xs", get_int, offsetof(struct canvas, c_xs)},
423 {"ys", get_int, offsetof(struct canvas, c_ys)},
424 {"xe", get_int, offsetof(struct canvas, c_xe)},
425 {"ye", get_int, offsetof(struct canvas, c_ye)},
426 {"window", 0, 0, canvas_get_window},
427 {0, 0}
430 /** }}} */
432 /** Layout {{{ */
434 PUSH_TYPE(layout, struct layout)
435 CHECK_TYPE(layout, struct layout)
437 static const struct Xet_reg layout_getters[] = {
438 {0,0}
441 static int
442 get_layout(lua_State *L, void *v)
444 push_layout(L, (struct layout **)v);
445 return 1;
448 /** }}} */
450 /** Display {{{ */
452 PUSH_TYPE(display, struct display)
454 CHECK_TYPE(display, struct display)
456 static int
457 display_get_canvases(lua_State *L)
459 struct display *d;
460 struct canvas *iter;
461 int count;
463 d = check_display(L, 1);
464 lua_newtable(L);
465 for (iter = d->d_cvlist, count = 0; iter; iter = iter->c_next, count++) {
466 lua_pushinteger(L, count);
467 push_canvas(L, &iter);
468 lua_settable(L, -3);
471 return 1;
474 static const luaL_reg display_methods[] = {
475 {"get_canvases", display_get_canvases},
476 {0, 0}
479 static int
480 display_tostring(lua_State *L)
482 char str[128];
483 struct display *d = check_display(L, 1);
484 snprintf(str, sizeof(str), "{display: tty = '%s', term = '%s'}", d->d_usertty, d->d_termname);
485 lua_pushstring(L, str);
486 return 1;
489 static const luaL_reg display_metamethods[] = {
490 {"__tostring", display_tostring},
491 {0, 0}
494 static const struct Xet_reg display_setters[] = {
495 {0, 0}
498 static const struct Xet_reg display_getters[] = {
499 {"tty", get_string, offsetof(struct display, d_usertty)},
500 {"term", get_string, offsetof(struct display, d_termname)},
501 {"fore", get_window, offsetof(struct display, d_fore)},
502 {"other", get_window, offsetof(struct display, d_other)},
503 {"width", get_int, offsetof(struct display, d_width)},
504 {"height", get_int, offsetof(struct display, d_height)},
505 {"user", get_user, offsetof(struct display, d_user)},
506 {"layout", get_layout, offsetof(struct display, d_layout)},
507 {0, 0}
510 /** }}} */
512 /** Screen {{{ */
514 static int
515 screen_get_windows(lua_State *L)
517 struct win *iter;
518 int count;
520 lua_newtable(L);
521 for (iter = windows, count = 0; iter; iter = iter->w_next, count++) {
522 lua_pushinteger(L, iter->w_number);
523 push_window(L, &iter);
524 lua_settable(L, -3);
527 return 1;
530 static int
531 screen_get_displays(lua_State *L)
533 struct display *iter;
534 int count;
536 lua_newtable(L);
537 for (iter = displays, count = 0; iter; iter = iter->d_next, count++) {
538 lua_pushinteger(L, count);
539 push_display(L, &iter);
540 lua_settable(L, -3);
543 return 1;
546 static int
547 screen_get_display(lua_State *L)
549 push_display(L, &display);
550 return 1;
553 static int
554 screen_exec_command(lua_State *L)
556 const char *command;
557 unsigned int len;
559 command = luaL_checklstring(L, 1, &len);
560 if (command)
561 RcLine((char *)command, len);
563 return 0;
566 static int
567 screen_append_msg(lua_State *L)
569 const char *msg, *color;
570 int len;
571 msg = luaL_checklstring(L, 1, &len);
572 if (lua_isnil(L, 2))
573 color = NULL;
574 else
575 color = luaL_checklstring(L, 2, &len);
576 AppendWinMsgRend(msg, color);
577 return 0;
580 static int
581 screen_register_event(lua_State *L)
583 int len;
584 const char *event, *handler;
585 struct listener *l;
586 struct script_event *sev;
587 event = luaL_checklstring(L, 1, &len);
588 handler = luaL_checklstring(L, 2, &len);
589 sev = object_get_event(NULL, event);
590 if (sev)
592 l = (struct listener *)malloc(sizeof(struct listener));
593 l->handler = (void *)handler;
594 l->dispatcher = LuaDispatch;
595 register_listener(sev, l);
599 static const luaL_reg screen_methods[] = {
600 {"windows", screen_get_windows},
601 {"displays", screen_get_displays},
602 {"display", screen_get_display},
603 {"command", screen_exec_command},
604 {"append_msg", screen_append_msg},
605 {"listen_to", screen_register_event},
606 {0, 0}
609 static const luaL_reg screen_metamethods[] = {
610 {0, 0}
613 static const struct Xet_reg screen_setters[] = {
614 {0, 0}
617 static const struct Xet_reg screen_getters[] = {
618 {0, 0}
621 /** }}} */
623 /** Public functions {{{ */
624 static lua_State *L;
625 int LuaInit(void)
627 L = luaL_newstate();
629 luaL_openlibs(L);
631 #define REGISTER(X) struct_register(L, #X , X ## _methods, X##_metamethods, X##_setters, X##_getters)
633 REGISTER(screen);
634 REGISTER(window);
635 REGISTER(display);
636 REGISTER(user);
637 REGISTER(canvas);
639 return 0;
642 struct fn_def
644 void (*push_fn)(lua_State *, void*);
645 void *value;
648 static int
649 LuaCallProcess(const char *name, struct fn_def defs[])
651 int argc = 0;
653 lua_settop(L, 0);
654 lua_getfield(L, LUA_GLOBALSINDEX, name);
655 if (lua_isnil(L, -1))
656 return 0;
657 for (argc = 0; defs[argc].push_fn; argc++)
658 defs[argc].push_fn(L, defs[argc].value);
659 if (lua_pcall(L, argc, 0, 0) == LUA_ERRRUN && lua_isstring(L, -1))
661 struct display *d = display;
662 unsigned int len;
663 const char *message = luaL_checklstring(L, -1, &len);
664 LMsg(1, "%s", message ? message : "Unknown error");
665 lua_pop(L, 1);
666 display = d;
667 return 0;
669 return 1;
672 int LuaForeWindowChanged(void)
674 if (!L)
675 return 0;
676 lua_getfield(L, LUA_GLOBALSINDEX, "fore_changed");
677 if (lua_isnil(L, -1))
678 return 0;
679 push_display(L, &display);
680 push_window(L, display ? &D_fore : &fore);
681 if (lua_pcall(L, 2, 0, 0) == LUA_ERRRUN)
683 if(lua_isstring(L, -1))
685 unsigned int len;
686 const char *message = luaL_checklstring(L, -1, &len);
687 LMsg(1, "%s", message ? message : "Unknown error");
688 lua_pop(L, 1);
691 return 0;
694 int LuaSource(const char *file, int async)
696 if (!L)
697 return 0;
698 struct stat st;
699 if (stat(file, &st) == -1)
700 Msg(errno, "Error loading lua script file '%s'", file);
701 else
703 int len = strlen(file);
704 if (len < 4 || strncmp(file + len - 4, ".lua", 4) != 0)
705 return 0;
706 luaL_dofile(L, file);
707 return 1;
709 return 0;
712 int LuaFinit(void)
714 if (!L)
715 return 0;
716 lua_close(L);
717 L = (lua_State*)0;
718 return 0;
721 int LuaCall(char *func, char **argv)
723 int argc;
724 if (!L)
725 return 0;
727 lua_getfield(L, LUA_GLOBALSINDEX, func);
728 for (argc = 0; *argv; argv++, argc++)
730 lua_pushstring(L, *argv);
732 if (lua_pcall(L, argc, 0, 0) == LUA_ERRRUN)
734 if(lua_isstring(L, -1))
736 unsigned int len;
737 const char *message = luaL_checklstring(L, -1, &len);
738 LMsg(1, "%s", message ? message : "Unknown error");
739 lua_pop(L, 1);
740 return 0;
743 return 1;
747 LuaProcessCaption(const char *caption, struct win *win, int len)
749 if (!L)
750 return 0;
751 struct fn_def params[] = {
752 {lua_pushstring, caption},
753 {push_window, &win},
754 {lua_pushinteger, len},
755 {NULL, NULL}
757 return LuaCallProcess("process_caption", params);
760 static void
761 push_stringarray(lua_State *L, void *data)
763 char **args = (char **)data;
764 int i;
765 lua_newtable(L);
766 for (i = 1; args && *args; i++) {
767 lua_pushinteger(L, i);
768 lua_pushstring(L, *args++);
769 lua_settable(L, -3);
773 int LuaPushParams(const char *params, va_list va)
775 int num = 0;
776 while (*params)
778 switch (*params)
780 case 's':
781 lua_pushstring(L, va_arg(va, char *));
782 break;
783 case 'S':
784 push_stringarray(L, va_arg(va, char **));
785 break;
786 case 'i':
787 lua_pushinteger(L, va_arg(va, int));
789 params++;
790 num++;
792 return num;
795 static int
796 LuaDispatch(void *handler, const char *params, va_list va)
798 const char *func = handler;
799 int argc;
801 /*FIXME:Really need this?*/
802 lua_settop(L, 0);
804 lua_getfield(L, LUA_GLOBALSINDEX, func);
805 if (lua_isnil(L, -1))
806 return 0;
807 argc = LuaPushParams(params, va);
809 if (lua_pcall(L, argc, 0, 0) == LUA_ERRRUN && lua_isstring(L, -1))
811 struct display *d = display;
812 unsigned int len;
813 char *message = luaL_checklstring(L, -1, &len);
814 LMsg(1, "%s", message ? message : "Unknown error");
815 lua_pop(L, 1);
816 display = d;
817 return 0;
819 return 1;
823 LuaCommandExecuted(const char *command, const char **args, int argc)
825 if (!L)
826 return 0;
827 struct fn_def params[] = {
828 {lua_pushstring, command},
829 {push_stringarray, args},
830 {NULL, NULL}
832 return LuaCallProcess("command_executed", params);
835 /** }}} */
837 struct ScriptFuncs LuaFuncs =
839 LuaForeWindowChanged,
840 LuaProcessCaption,
841 LuaCommandExecuted
844 struct binding lua_binding =
846 "lua", /*name*/
847 0, /*inited*/
848 0, /*registered*/
849 LuaInit,
850 LuaFinit,
851 LuaCall,
852 LuaSource,
853 0, /*b_next*/
854 &LuaFuncs