fb00b3842156b638e296d1a1afeb689609d16a50
[screen-lua.git] / src / lua.c
blobfb00b3842156b638e296d1a1afeb689609d16a50
1 /* Lua scripting support
3 * Copyright (c) 2008 Sadrul Habib Chowdhury (sadrul@users.sf.net)
4 * Copyright (c) 2009
5 * Sadrul Habib Chowdhury (sadrul@users.sf.net)
6 * Rui Guo (firemeteor.guo@gmail.com)
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 3, or (at your option)
11 * any later version.
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
18 * You should have received a copy of the GNU General Public License
19 * along with this program (see the file COPYING); if not, write to the
20 * Free Software Foundation, Inc.,
21 * 51 Franklin Street, Fifth Floor, Boston, MA 02111-1301 USA
23 ****************************************************************
25 #include <sys/types.h>
26 #include "config.h"
27 #include "screen.h"
28 #include <sys/stat.h>
29 #include <unistd.h>
31 #include <stdio.h>
32 #include <string.h>
33 #include <stdlib.h>
35 #include "extern.h"
36 #include "logfile.h"
38 #include <lua.h>
39 #include <lauxlib.h>
40 #include <lualib.h>
42 static int StackDump(lua_State *L, const char *message)
44 FILE *f = fopen("/tmp/debug/stack", "ab");
45 int i = lua_gettop(L);
46 if (message)
47 fprintf(f, "%s", message);
48 while (i)
50 int t = lua_type(L, i);
51 switch (t)
53 case LUA_TSTRING:
54 fprintf(f, "String: %s\n", lua_tostring(L, i));
55 break;
57 case LUA_TBOOLEAN:
58 fprintf(f, "Boolean: %s\n", lua_toboolean(L, i) ? "true" : "false");
59 break;
61 case LUA_TNUMBER:
62 fprintf(f, "Number: %g\n", lua_tonumber(L, i));
63 break;
65 default:
66 fprintf(f, "Type: %s\n", lua_typename(L, t));
68 i--;
70 if (message)
71 fprintf(f, "----\n");
72 fclose(f);
73 return 0;
76 extern struct win *windows, *fore;
77 extern struct display *displays, *display;
78 extern struct LayFuncs WinLf;
79 extern struct layer *flayer;
80 extern void AppendWinMsgRend(const char *str, const char *color);
82 static int LuaDispatch(void *handler, const char *params, va_list va);
83 static int LuaRegEvent(lua_State *L);
84 static void LuaShowErr(lua_State *L);
85 struct binding lua_binding;
87 enum
89 LUA_HANDLER_TYPE_N = 1,
90 LUA_HANDLER_TYPE_F
93 struct lua_handler
95 int type;
96 union
98 const char *name;
99 int reference;
100 } u;
103 typedef struct lua_handler *lua_handler;
104 void LuaPushHandler(lua_State *L, lua_handler lh);
105 void LuaHUnRef(lua_State *L, int key);
106 lua_handler LuaCheckHandler(lua_State *L, int idx, int ref);
108 lua_handler
109 LuaAllocHandler(const char *name, int ref)
111 struct lua_handler *lh;
112 lh = (struct lua_handler*) malloc(sizeof(struct lua_handler));
113 if (!lh)
114 return NULL;
116 if (name)
118 lh->type = LUA_HANDLER_TYPE_N;
119 lh->u.name = SaveStr(name);
121 else
123 lh->type = LUA_HANDLER_TYPE_F;
124 lh->u.reference = ref;
127 return lh;
130 void
131 LuaFreeHandler(lua_State *L, struct lua_handler **lh)
133 if ((*lh)->type == LUA_HANDLER_TYPE_N)
134 Free((*lh)->u.name)
135 else
137 LuaHUnRef(L, (*lh)->u.reference);
138 (*lh)->u.reference = 0;
140 Free(*lh);
142 /** Template {{{ */
144 #define CHECK_TYPE(name, type) \
145 static type * \
146 check_##name(lua_State *L, int index) \
148 type **var; \
149 luaL_checktype(L, index, LUA_TUSERDATA); \
150 var = (type **) luaL_checkudata(L, index, #name); \
151 if (!var || !*var) \
152 luaL_typerror(L, index, #name); \
153 return *var; \
156 #define PUSH_TYPE(name, type) \
157 static void \
158 push_##name(lua_State *L, type **t) \
160 if (!t || !*t) \
161 lua_pushnil(L); \
162 else \
164 type **r; \
165 r = (type **)lua_newuserdata(L, sizeof(type *)); \
166 *r = *t; \
167 luaL_getmetatable(L, #name); \
168 lua_setmetatable(L,-2); \
172 /* Much of the following template comes from:
173 * http://lua-users.org/wiki/BindingWithMembersAndMethods
176 static int get_int (lua_State *L, void *v)
178 lua_pushinteger (L, *(int*)v);
179 return 1;
182 static int set_int (lua_State *L, void *v)
184 *(int*)v = luaL_checkint(L, 3);
185 return 0;
188 static int get_number (lua_State *L, void *v)
190 lua_pushnumber(L, *(lua_Number*)v);
191 return 1;
194 static int set_number (lua_State *L, void *v)
196 *(lua_Number*)v = luaL_checknumber(L, 3);
197 return 0;
200 static int get_string (lua_State *L, void *v)
202 lua_pushstring(L, (char*)v );
203 return 1;
206 static int set_string (lua_State *L, void *v)
208 *(const char**)v = luaL_checkstring(L, 3);
209 return 0;
212 typedef int (*Xet_func) (lua_State *L, void *v);
214 /* member info for get and set handlers */
215 struct Xet_reg
217 const char *name; /* member name */
218 Xet_func func; /* get or set function for type of member */
219 size_t offset; /* offset of member within the struct */
220 int (*absolute)(lua_State *);
223 static void Xet_add (lua_State *L, const struct Xet_reg *l)
225 if (!l)
226 return;
227 for (; l->name; l++)
229 lua_pushstring(L, l->name);
230 lua_pushlightuserdata(L, (void*)l);
231 lua_settable(L, -3);
235 static int Xet_call (lua_State *L)
237 /* for get: stack has userdata, index, lightuserdata */
238 /* for set: stack has userdata, index, value, lightuserdata */
239 const struct Xet_reg *m = (const struct Xet_reg *)lua_touserdata(L, -1); /* member info */
240 lua_pop(L, 1); /* drop lightuserdata */
241 luaL_checktype(L, 1, LUA_TUSERDATA);
242 if (m->absolute)
243 return m->absolute(L);
244 return m->func(L, *(char**)lua_touserdata(L, 1) + m->offset);
247 static int index_handler (lua_State *L)
249 /* stack has userdata, index */
250 lua_pushvalue(L, 2); /* dup index */
251 lua_rawget(L, lua_upvalueindex(1)); /* lookup member by name */
252 if (!lua_islightuserdata(L, -1))
254 lua_pop(L, 1); /* drop value */
255 lua_pushvalue(L, 2); /* dup index */
256 lua_gettable(L, lua_upvalueindex(2)); /* else try methods */
257 if (lua_isnil(L, -1)) /* invalid member */
258 luaL_error(L, "cannot get member '%s'", lua_tostring(L, 2));
259 return 1;
261 return Xet_call(L); /* call get function */
264 static int newindex_handler (lua_State *L)
266 /* stack has userdata, index, value */
267 lua_pushvalue(L, 2); /* dup index */
268 lua_rawget(L, lua_upvalueindex(1)); /* lookup member by name */
269 if (!lua_islightuserdata(L, -1)) /* invalid member */
270 luaL_error(L, "cannot set member '%s'", lua_tostring(L, 2));
271 return Xet_call(L); /* call set function */
274 static int
275 struct_register(lua_State *L, const char *name, const luaL_reg fn_methods[], const luaL_reg meta_methods[],
276 const struct Xet_reg setters[], const struct Xet_reg getters[])
278 int metatable, methods;
280 /* create methods table & add it to the table of globals */
281 luaL_register(L, name, fn_methods);
282 methods = lua_gettop(L);
284 /* create metatable & add it to the registry */
285 luaL_newmetatable(L, name);
286 luaL_register(L, 0, meta_methods); /* fill metatable */
288 /* To identify the type of object */
289 lua_pushstring(L, "_objname");
290 lua_pushstring(L, name);
291 lua_rawset(L, -3);
293 metatable = lua_gettop(L);
295 lua_pushliteral(L, "__metatable");
296 lua_pushvalue(L, methods); /* dup methods table*/
297 lua_rawset(L, metatable); /* hide metatable:
298 metatable.__metatable = methods */
300 lua_pushliteral(L, "__index");
301 lua_pushvalue(L, metatable); /* upvalue index 1 */
302 Xet_add(L, getters); /* fill metatable with getters */
303 lua_pushvalue(L, methods); /* upvalue index 2 */
304 lua_pushcclosure(L, index_handler, 2);
305 lua_rawset(L, metatable); /* metatable.__index = index_handler */
307 lua_pushliteral(L, "__newindex");
308 lua_newtable(L); /* table for members you can set */
309 Xet_add(L, setters); /* fill with setters */
310 lua_pushcclosure(L, newindex_handler, 1);
311 lua_rawset(L, metatable); /* metatable.__newindex = newindex_handler */
313 /* FIXME: Why do we leave an element on the stack? */
314 lua_pop(L, 1); /* drop metatable */
315 return 1; /* return methods on the stack */
318 /** }}} */
320 /** Callback {{{ */
321 PUSH_TYPE(callback, struct listener)
323 static int
324 internal_unhook(lua_State *L, int warn)
326 /*Emulate check_callback() */
327 struct listener **ppl;
328 luaL_checktype(L, 1, LUA_TUSERDATA);
329 ppl = (struct listener **) luaL_checkudata(L, 1, "callback");
331 if (!ppl)
332 luaL_typerror(L, 1, "callback");
334 if (!*ppl)
336 if (warn)
338 lua_pushboolean(L, 0);
339 lua_pushstring(L, "Callback already unhooked.");
340 LuaShowErr(L);
343 else
345 LuaFreeHandler(L, (lua_handler *)&(*ppl)->handler);
346 unregister_listener(*ppl);
347 *ppl = 0;
348 if (warn)
349 lua_pushboolean(L, 1);
351 return warn != 0;
353 static int
354 callback_unhook(lua_State *L)
356 return internal_unhook(L, 1);
359 static const luaL_reg callback_methods[] = {
360 {"unhook", callback_unhook},
361 {0, 0}
365 callback_collect(lua_State *L)
367 return internal_unhook(L, 0);
370 static const luaL_reg callback_metamethods[] = {
371 {"__gc", callback_collect},
372 {0, 0}
375 static const struct Xet_reg callback_setters[] = {
376 {0, 0}
379 static const struct Xet_reg callback_getters[] = {
380 {0, 0}
384 /** }}} */
386 /** Window {{{ */
388 PUSH_TYPE(window, struct win)
390 CHECK_TYPE(window, struct win)
392 static int get_window(lua_State *L, void *v)
394 push_window(L, (struct win **)v);
395 return 1;
398 static int
399 window_change_title(lua_State *L)
401 struct win *w = check_window(L, 1);
402 unsigned int len;
403 const char *title = luaL_checklstring(L, 2, &len);
404 ChangeAKA(w, (char *)title, len);
405 return 0;
408 static int
409 window_get_monitor_status(lua_State *L)
411 struct win *w = check_window(L, 1);
412 int activity = luaL_checkint(L, 2);
413 if (activity)
414 /*monitor*/
415 lua_pushinteger(L, w->w_monitor != MON_OFF);
416 else
417 /*silence*/
418 lua_pushinteger(L, w->w_silence == SILENCE_ON ? w->w_silencewait: 0);
420 return 1;
423 static const luaL_reg window_methods[] = {
424 {"get_monitor_status", window_get_monitor_status},
425 {"hook", LuaRegEvent},
426 {0, 0}
429 static int
430 window_tostring(lua_State *L)
432 char str[128];
433 struct win *w = check_window(L, 1);
434 snprintf(str, sizeof(str), "{window #%d: '%s'}", w->w_number, w->w_title);
435 lua_pushstring(L, str);
436 return 1;
439 static int
440 window_equality(lua_State *L)
442 struct win *w1 = check_window(L, 1), *w2 = check_window(L, 2);
443 lua_pushboolean(L, (w1 == w2 || (w1 && w2 && w1->w_number == w2->w_number)));
444 return 1;
447 static const luaL_reg window_metamethods[] = {
448 {"__tostring", window_tostring},
449 {"__eq", window_equality},
450 {0, 0}
453 static const struct Xet_reg window_setters[] = {
454 {"title", 0, 0, window_change_title/*absolute setter*/},
455 {0, 0}
458 static const struct Xet_reg window_getters[] = {
459 {"title", get_string, offsetof(struct win, w_title) + 8},
460 {"number", get_int, offsetof(struct win, w_number)},
461 {"dir", get_string, offsetof(struct win, w_dir)},
462 {"tty", get_string, offsetof(struct win, w_tty)},
463 {"pid", get_int, offsetof(struct win, w_pid)},
464 {"group", get_window, offsetof(struct win, w_group)},
465 {"bell", get_int, offsetof(struct win, w_bell)},
466 {0, 0}
470 /** }}} */
472 /** AclUser {{{ */
474 PUSH_TYPE(user, struct acluser)
476 CHECK_TYPE(user, struct acluser)
478 static int
479 get_user(lua_State *L, void *v)
481 push_user(L, (struct acluser **)v);
482 return 1;
485 static const luaL_reg user_methods[] = {
486 {0, 0}
489 static int
490 user_tostring(lua_State *L)
492 char str[128];
493 struct acluser *u = check_user(L, 1);
494 snprintf(str, sizeof(str), "{user '%s'}", u->u_name);
495 lua_pushstring(L, str);
496 return 1;
499 static const luaL_reg user_metamethods[] = {
500 {"__tostring", user_tostring},
501 {0, 0}
504 static const struct Xet_reg user_setters[] = {
505 {0, 0}
508 static const struct Xet_reg user_getters[] = {
509 {"name", get_string, offsetof(struct acluser, u_name)},
510 {"password", get_string, offsetof(struct acluser, u_password)},
511 {0, 0}
514 /** }}} */
516 /** Canvas {{{ */
518 PUSH_TYPE(canvas, struct canvas)
520 CHECK_TYPE(canvas, struct canvas)
522 static int
523 get_canvas(lua_State *L, void *v)
525 push_canvas(L, (struct canvas **)v);
526 return 1;
529 static int
530 canvas_select(lua_State *L)
532 struct canvas *c = check_canvas(L, 1);
533 if (!display || D_forecv == c)
534 return 0;
535 SetCanvasWindow(c, Layer2Window(c->c_layer));
536 D_forecv = c;
538 /* XXX: the following all is duplicated from process.c:DoAction.
539 * Should these be in some better place?
541 ResizeCanvas(&D_canvas);
542 RecreateCanvasChain();
543 RethinkDisplayViewports();
544 ResizeLayersToCanvases(); /* redisplays */
545 fore = D_fore = Layer2Window(D_forecv->c_layer);
546 flayer = D_forecv->c_layer;
547 #ifdef RXVT_OSC
548 if (D_xtermosc[2] || D_xtermosc[3])
550 Activate(-1);
551 break;
553 #endif
554 RefreshHStatus();
555 #ifdef RXVT_OSC
556 RefreshXtermOSC();
557 #endif
558 flayer = D_forecv->c_layer;
559 CV_CALL(D_forecv, LayRestore();LaySetCursor());
560 WindowChanged(0, 'F');
561 return 1;
564 static const luaL_reg canvas_methods[] = {
565 {"select", canvas_select},
566 {0, 0}
569 static const luaL_reg canvas_metamethods[] = {
570 {0, 0}
573 static const struct Xet_reg canvas_setters[] = {
574 {0, 0}
577 static int
578 canvas_get_window(lua_State *L)
580 struct canvas *c = check_canvas(L, 1);
581 struct win *win = Layer2Window(c->c_layer);
582 if (win)
583 push_window(L, &win);
584 else
585 lua_pushnil(L);
586 return 1;
589 static const struct Xet_reg canvas_getters[] = {
590 {"next", get_canvas, offsetof(struct canvas, c_next)},
591 {"xoff", get_int, offsetof(struct canvas, c_xoff)},
592 {"yoff", get_int, offsetof(struct canvas, c_yoff)},
593 {"xs", get_int, offsetof(struct canvas, c_xs)},
594 {"ys", get_int, offsetof(struct canvas, c_ys)},
595 {"xe", get_int, offsetof(struct canvas, c_xe)},
596 {"ye", get_int, offsetof(struct canvas, c_ye)},
597 {"window", 0, 0, canvas_get_window},
598 {0, 0}
601 /** }}} */
603 /** Layout {{{ */
605 PUSH_TYPE(layout, struct layout)
606 CHECK_TYPE(layout, struct layout)
608 static const struct Xet_reg layout_getters[] = {
609 {0,0}
612 static int
613 get_layout(lua_State *L, void *v)
615 push_layout(L, (struct layout **)v);
616 return 1;
619 /** }}} */
621 /** Display {{{ */
623 PUSH_TYPE(display, struct display)
625 CHECK_TYPE(display, struct display)
627 static int
628 display_get_canvases(lua_State *L)
630 struct display *d;
631 struct canvas *iter;
632 int count;
634 d = check_display(L, 1);
635 lua_newtable(L);
636 for (iter = d->d_cvlist, count = 0; iter; iter = iter->c_next, count++) {
637 lua_pushinteger(L, count);
638 push_canvas(L, &iter);
639 lua_settable(L, -3);
642 return 1;
645 static const luaL_reg display_methods[] = {
646 {"get_canvases", display_get_canvases},
647 {0, 0}
650 static int
651 display_tostring(lua_State *L)
653 char str[128];
654 struct display *d = check_display(L, 1);
655 snprintf(str, sizeof(str), "{display: tty = '%s', term = '%s'}", d->d_usertty, d->d_termname);
656 lua_pushstring(L, str);
657 return 1;
660 static const luaL_reg display_metamethods[] = {
661 {"__tostring", display_tostring},
662 {0, 0}
665 static const struct Xet_reg display_setters[] = {
666 {0, 0}
669 static const struct Xet_reg display_getters[] = {
670 {"tty", get_string, offsetof(struct display, d_usertty)},
671 {"term", get_string, offsetof(struct display, d_termname)},
672 {"fore", get_window, offsetof(struct display, d_fore)},
673 {"other", get_window, offsetof(struct display, d_other)},
674 {"width", get_int, offsetof(struct display, d_width)},
675 {"height", get_int, offsetof(struct display, d_height)},
676 {"user", get_user, offsetof(struct display, d_user)},
677 {"layout", get_layout, offsetof(struct display, d_layout)},
678 {0, 0}
681 /** }}} */
683 /** Screen {{{ */
685 static int
686 screen_get_windows(lua_State *L)
688 struct win *iter;
689 int count;
691 lua_newtable(L);
692 for (iter = windows, count = 0; iter; iter = iter->w_next, count++) {
693 lua_pushinteger(L, iter->w_number);
694 push_window(L, &iter);
695 lua_settable(L, -3);
698 return 1;
701 static int
702 screen_get_displays(lua_State *L)
704 struct display *iter;
705 int count;
707 lua_newtable(L);
708 for (iter = displays, count = 0; iter; iter = iter->d_next, count++) {
709 lua_pushinteger(L, count);
710 push_display(L, &iter);
711 lua_settable(L, -3);
714 return 1;
717 static int
718 screen_get_display(lua_State *L)
720 push_display(L, &display);
721 return 1;
724 static int
725 screen_exec_command(lua_State *L)
727 const char *command;
728 unsigned int len;
730 command = luaL_checklstring(L, 1, &len);
731 if (command)
732 RcLine((char *)command, len);
734 return 0;
737 static int
738 screen_append_msg(lua_State *L)
740 const char *msg, *color;
741 unsigned int len;
742 msg = luaL_checklstring(L, 1, &len);
743 if (lua_isnil(L, 2))
744 color = NULL;
745 else
746 color = luaL_checklstring(L, 2, &len);
747 AppendWinMsgRend(msg, color);
748 return 0;
751 struct sinput_data
753 lua_State *L;
754 lua_handler lh;
757 void
758 script_input_fn(char *buf, int len, char *priv)
760 struct sinput_data *sidata = (struct sinput_data *)priv;
761 lua_handler lh = sidata->lh;
762 lua_State *L = sidata->L;
764 LuaPushHandler(L, lh);
765 lua_pushstring(L, buf);
766 if (lua_pcall(L, 1, 0, 0) == LUA_ERRRUN)
768 if(lua_isstring(L, -1))
770 LuaShowErr(L);
773 free(sidata);
774 LuaFreeHandler(L, &lh);
777 static int
778 screen_input(lua_State *L)
780 char *ss;
781 int n;
782 const char * prompt = NULL, *prefill = NULL;
783 lua_handler lh;
784 struct sinput_data *sidata;
786 prompt = luaL_checkstring(L, 1);
787 lh = LuaCheckHandler(L, 2, 1);
788 if (!lh)
789 luaL_error(L, "Out of Memory");
791 if (lua_gettop(L) >= 3)
792 prefill = luaL_checkstring(L, 3);
795 sidata = (struct sinput_data *)malloc(sizeof(struct sinput_data));
796 if (!sidata)
798 Free(lh);
799 luaL_error(L, "Out of Memory");
802 sidata->L = L;
803 sidata->lh = lh;
804 Input((char *)prompt, 100, INP_COOKED, script_input_fn, (char *)sidata, 0);
806 if (!prefill)
807 return 0;
808 for (; *prefill; prefill++)
810 if ((*(unsigned char *)prefill & 0x7f) < 0x20 || *prefill == 0x7f)
811 continue;
812 ss = (char *)prefill;
813 n = 1;
814 LayProcess(&ss, &n);
816 return 0;
819 static const luaL_reg screen_methods[] = {
820 {"windows", screen_get_windows},
821 {"displays", screen_get_displays},
822 {"display", screen_get_display},
823 {"command", screen_exec_command},
824 {"append_msg", screen_append_msg},
825 {"hook", LuaRegEvent},
826 {"input", screen_input},
827 {0, 0}
830 static const luaL_reg screen_metamethods[] = {
831 {0, 0}
834 static const struct Xet_reg screen_setters[] = {
835 {0, 0}
838 static const struct Xet_reg screen_getters[] = {
839 {0, 0}
842 /** }}} */
844 /** Public functions {{{ */
846 /* FIXME: This code only tracks one unhook ticket for a lua func.
847 * So it does not work if one func is registered more than one times. */
848 static void
849 prepare_weak_table(lua_State *L, const char *name, const char *mode)
851 luaL_getmetatable(L, "screen");
853 lua_pushstring(L, name);
854 lua_newtable(L);
856 /* prepare a metatable to indicate weak table */
857 lua_newtable(L);
858 lua_pushstring(L, "__mode");
859 lua_pushstring(L, mode);
860 lua_rawset(L, -3);
861 /* Mark weak table */
862 lua_setmetatable(L, -2);
863 lua_rawset(L, -3);
864 lua_pop(L, 1);
867 static lua_State *L;
868 int LuaInit(void)
870 L = luaL_newstate();
872 luaL_openlibs(L);
874 #define REGISTER(X) struct_register(L, #X , X ## _methods, X##_metamethods, X##_setters, X##_getters)
876 REGISTER(screen);
877 REGISTER(window);
878 REGISTER(display);
879 REGISTER(user);
880 REGISTER(canvas);
881 REGISTER(callback);
883 /* To store handler funcs */
885 /*_two kinds of information are mantained:
887 * funcreg[key]->func
888 * The 'func' part of the tables are weak. That means the registered funcs
889 * will be collected once the func is no longer available (e.g. overwritten
890 * by a new instance of the script)
892 * To make this process happens faster, GC is forced at the end of each
893 * source.
894 * TODO: What if some events are triggered within the sourcing
895 * procedure?
896 * */
897 prepare_weak_table(L, "_funcreg", "v");
899 /* funcunhook[func]->listener
900 * The listener is the unhook ticket of the hook. which should be collected
901 * once the func is collected. The gc metamethod will be triggered
902 * accordingly. */
903 prepare_weak_table(L, "_funcunhook", "k");
905 return 0;
908 /* An error message on top of the stack. */
909 static void
910 LuaShowErr(lua_State *L)
912 struct display *d = display;
913 unsigned int len;
914 const char *message = luaL_checklstring(L, -1, &len);
915 LMsg(0, "%s", message ? message : "Unknown error");
916 lua_pop(L, 1);
917 display = d;
920 struct fn_def
922 void (*push_fn)(lua_State *, void*);
923 void *value;
926 static int
927 LuaCallProcess(const char *name, struct fn_def defs[])
929 int argc = 0;
931 lua_getfield(L, LUA_GLOBALSINDEX, name);
932 if (lua_isnil(L, -1))
934 lua_pop(L,1);
935 return 0;
937 for (argc = 0; defs[argc].push_fn; argc++)
938 defs[argc].push_fn(L, defs[argc].value);
939 if (lua_pcall(L, argc, 0, 0) == LUA_ERRRUN && lua_isstring(L, -1))
941 LuaShowErr(L);
942 return 0;
944 return 1;
947 /* FIXME: Think about this: will it affect the registered handlers?*/
948 int LuaSource(const char *file, int async)
950 if (!L)
951 return 0;
952 struct stat st;
953 if (stat(file, &st) == -1)
954 Msg(errno, "Error loading lua script file '%s'", file);
955 else
957 int len = strlen(file);
958 if (len < 4 || strncmp(file + len - 4, ".lua", 4) != 0)
959 return 0;
960 if (luaL_dofile(L, file) && lua_isstring(L, -1))
962 LuaShowErr(L);
963 return 0;
965 else
967 /* It seems that I need two GC passes to really collect the unhook
968 * ticket, after changing the reference to ticket in the
969 * 'funcunhook' table from weak to strong. This should not be
970 * harmful, but how can I make sure that two passes is enough?
972 * Possible reason:
973 * This seems reasonable, since the first pass will collect the func
974 * itself and make the ticket garbage, and the second pass will
975 * collect the ticket itself.
977 * TODO: check this out. maybe ask some lua gurus. */
978 lua_gc(L, LUA_GCCOLLECT, 0);
979 lua_gc(L, LUA_GCCOLLECT, 0);
981 return 1;
983 return 0;
986 int LuaFinit(void)
988 if (!L)
989 return 0;
990 lua_close(L);
991 L = (lua_State*)0;
992 return 0;
996 LuaProcessCaption(const char *caption, struct win *win, int len)
998 if (!L)
999 return 0;
1000 struct fn_def params[] = {
1001 {lua_pushstring, caption},
1002 {push_window, &win},
1003 {lua_pushinteger, len},
1004 {NULL, NULL}
1006 return LuaCallProcess("process_caption", params);
1009 static void
1010 push_stringarray(lua_State *L, char **args)
1012 int i;
1013 lua_newtable(L);
1014 for (i = 1; args && *args; i++) {
1015 lua_pushinteger(L, i);
1016 lua_pushstring(L, *args++);
1017 lua_settable(L, -3);
1022 LuaPushParams(lua_State *L, const char *params, va_list va)
1024 int num = 0;
1025 while (*params)
1027 switch (*params)
1029 case 's':
1030 lua_pushstring(L, va_arg(va, char *));
1031 break;
1032 case 'S':
1033 push_stringarray(L, va_arg(va, char **));
1034 break;
1035 case 'i':
1036 lua_pushinteger(L, va_arg(va, int));
1037 break;
1038 case 'd':
1040 struct display *d = va_arg(va, struct display *);
1041 push_display(L, &d);
1042 break;
1045 params++;
1046 num++;
1048 return num;
1051 int LuaCall(const char *func, const char **argv)
1053 int argc;
1054 if (!L)
1055 return 0;
1057 StackDump(L, "Before LuaCall\n");
1058 lua_getfield(L, LUA_GLOBALSINDEX, func);
1059 if (lua_isnil(L, -1))
1061 lua_pop(L, 1);
1062 lua_pushstring(L, "Could not find the script function\n");
1063 LuaShowErr(L);
1064 return 0;
1066 for (argc = 0; *argv; argv++, argc++)
1068 lua_pushstring(L, *argv);
1070 if (lua_pcall(L, argc, 0, 0) == LUA_ERRRUN)
1072 if(lua_isstring(L, -1))
1074 StackDump(L, "After LuaCall\n");
1075 LuaShowErr(L);
1076 return 0;
1079 return 1;
1082 /*** Lua callback handler management {{{ */
1085 LuaPushHTable(lua_State *L, int screen, const char * t)
1087 lua_pushstring(L, t);
1088 lua_rawget(L, screen);
1089 /* FIXME: Do we need to balance the stack here? */
1090 if (lua_isnil(L, -1))
1091 luaL_error(L, "Fatal! Fail to get function registeration table!");
1092 return lua_gettop(L);
1095 void
1096 LuaPushHandler(lua_State *L, lua_handler lh)
1098 int funcreg;
1099 if (lh->type == LUA_HANDLER_TYPE_F)
1101 luaL_getmetatable(L, "screen");
1102 funcreg = LuaPushHTable(L, lua_gettop(L), "_funcreg");
1103 lua_rawgeti(L, funcreg, lh->u.reference);
1104 lua_replace(L, -3);
1105 lua_pop(L, 1);
1107 else
1109 lua_getfield(L, LUA_GLOBALSINDEX, lh->u.name);
1114 LuaFuncKey(lua_State *L, int idx, int ref)
1116 int key, funcreg, sc;
1117 luaL_getmetatable(L, "screen");
1118 sc = lua_gettop(L);
1119 funcreg = LuaPushHTable(L, sc, "_funcreg");
1121 lua_pushvalue(L, idx);
1122 key = luaL_ref(L, funcreg);
1123 lua_pop(L, 2);
1124 return key;
1127 void
1128 LuaHUnRef(lua_State *L, int key)
1130 int funcreg, sc;
1131 luaL_getmetatable(L, "screen");
1132 sc = lua_gettop(L);
1133 funcreg = LuaPushHTable(L, sc, "_funcreg");
1134 luaL_unref(L, funcreg, key);
1137 lua_handler
1138 LuaCheckHandler(lua_State *L, int idx, int ref)
1140 int key;
1141 if (idx < 0)
1142 idx = lua_gettop(L) + 1 - idx;
1144 if (lua_isstring(L, idx))
1146 const char * handler;
1147 /* registered with func name.*/
1148 handler = luaL_checkstring(L, idx);
1149 lua_getfield(L, LUA_GLOBALSINDEX, handler);
1150 if (!lua_isfunction(L, -1))
1151 luaL_error(L, "The specified handler %s in param #%d is not a function", handler, idx);
1152 lua_pop(L, 1);
1153 return LuaAllocHandler(handler, 0);
1155 else if (!lua_isfunction(L, idx))
1156 luaL_error(L, "Handler should be a function or the name of function");
1158 key = LuaFuncKey(L, idx, ref);
1159 return LuaAllocHandler(NULL, key);
1162 /* }}} **/
1164 static int
1165 LuaDispatch(void *handler, const char *params, va_list va)
1167 lua_handler lh = (lua_handler)handler;
1168 int argc, retvalue;
1170 StackDump(L, "before dispatch");
1172 LuaPushHandler(L, lh);
1173 if (lua_isnil(L, -1))
1175 lua_pop(L, 1);
1176 return 0;
1178 argc = LuaPushParams(L, params, va);
1180 if (lua_pcall(L, argc, 1, 0) == LUA_ERRRUN && lua_isstring(L, -1))
1182 StackDump(L, "After LuaDispatch\n");
1183 LuaShowErr(L);
1184 return 0;
1186 retvalue = lua_tonumber(L, -1);
1187 lua_pop(L, 1);
1188 return retvalue;
1191 int LuaForeWindowChanged(void)
1193 struct fn_def params[] = {
1194 {push_display, &display},
1195 {push_window, display ? &D_fore : &fore},
1196 {NULL, NULL}
1198 if (!L)
1199 return 0;
1200 return LuaCallProcess("fore_changed", params);
1203 /*FIXME: what if a func is registered twice or more? */
1204 void
1205 LuaRegAutoUnHook(lua_State *L, lua_handler lh, int ticket)
1207 int sc, funcunhook;
1208 luaL_getmetatable(L, "screen");
1209 sc = lua_gettop(L);
1210 funcunhook = LuaPushHTable(L, sc, "_funcunhook");
1211 LuaPushHandler(L, lh);
1212 lua_pushvalue(L, ticket);
1213 lua_rawset(L, funcunhook);
1214 lua_pop(L, 2);
1217 #define SEVNAME_MAX 30
1218 static int
1219 LuaRegEvent(lua_State *L)
1221 /* signature: hook(obj, event, handler, priv);
1222 * or: hook(event, handler, priv)
1223 * returns: A ticket for later unregister. */
1224 int idx = 1, argc = lua_gettop(L);
1225 unsigned int priv = 31; /* Default privilege */
1226 lua_handler lh;
1228 char *obj = NULL;
1229 const char *objname = "global";
1231 static char evbuf[SEVNAME_MAX];
1232 const char *event;
1234 struct script_event *sev;
1236 StackDump(L, "Before RegEvent\n");
1238 /* Identify the object, if specified */
1239 if (luaL_getmetafield(L, 1, "_objname"))
1241 objname = luaL_checkstring(L, -1);
1242 lua_pop(L, 1);
1243 if (!strcmp("screen", objname))
1244 objname = "global";
1245 else
1246 obj = *(char **)lua_touserdata(L, 1);
1247 idx++;
1250 event = luaL_checkstring(L, idx++);
1251 snprintf(evbuf, SEVNAME_MAX, "%s_%s", objname, event);
1253 /* Check and get the handler */
1254 lh = LuaCheckHandler(L, idx++, 1);
1255 if (!lh)
1256 luaL_error(L, "Out of memory");
1258 StackDump(L, "In RegEvent\n");
1260 if (idx <= argc)
1261 priv = luaL_checkinteger(L, idx);
1263 sev = object_get_event(obj, evbuf);
1264 if (sev)
1266 struct listener *l;
1267 int ticket;
1268 l = (struct listener *)malloc(sizeof(struct listener));
1269 if (!l)
1270 return luaL_error(L, "Out of memory");
1271 l->priv = priv;
1272 l->bd = &lua_binding;
1273 l->handler = (void *)lh;
1274 register_listener(sev, l);
1275 /* Return the ticket for un-register */
1276 push_callback(L, &l);
1277 ticket = lua_gettop(L);
1279 LuaRegAutoUnHook(L, lh, ticket);
1281 else
1282 return luaL_error(L, "Invalid event specified: %s for object %s", event, objname);
1284 StackDump(L, "After RegEvent\n");
1285 return 1;
1288 /** }}} */
1290 struct ScriptFuncs LuaFuncs =
1292 LuaForeWindowChanged,
1293 LuaProcessCaption
1296 struct binding lua_binding =
1298 "lua", /*name*/
1299 0, /*inited*/
1300 0, /*registered*/
1301 LuaInit,
1302 LuaFinit,
1303 LuaCall,
1304 LuaSource,
1305 LuaDispatch,
1306 0, /*b_next*/
1307 &LuaFuncs