Enable stuffing a window.
[screen-lua.git] / src / lua.c
blob6373061ac475350a00309dcd34890fec5bdf27ac
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, 3, &len);
404 ChangeAKA(w, (char *)title, len);
405 return 0;
408 static int
409 window_change_number(lua_State *L)
411 struct win *w = check_window(L, 1);
412 int newnum = luaL_checkint(L, 3);
413 ChangeWinNum(w->w_number, newnum);
414 return 0;
417 static int
418 window_get_monitor_status(lua_State *L)
420 struct win *w = check_window(L, 1);
421 int activity = luaL_checkint(L, 2);
422 if (activity)
423 /*monitor*/
424 lua_pushinteger(L, w->w_monitor != MON_OFF);
425 else
426 /*silence*/
427 lua_pushinteger(L, w->w_silence == SILENCE_ON ? w->w_silencewait: 0);
429 return 1;
432 static int
433 window_stuff(lua_State *L)
435 unsigned int len;
436 struct layer *oldflayer = flayer;
437 struct win *w = check_window(L, 1);
438 const char *str = luaL_checklstring(L, 2, &len);
440 flayer = &w->w_layer;
441 while(len)
442 LayProcess((char **)&str, (int *) &len);
443 flayer = oldflayer;
444 return 0;
447 static const luaL_reg window_methods[] = {
448 {"get_monitor_status", window_get_monitor_status},
449 {"stuff", window_stuff},
450 {"hook", LuaRegEvent},
451 {0, 0}
454 static int
455 window_tostring(lua_State *L)
457 char str[128];
458 struct win *w = check_window(L, 1);
459 snprintf(str, sizeof(str), "{window #%d: '%s'}", w->w_number, w->w_title);
460 lua_pushstring(L, str);
461 return 1;
464 static int
465 window_equality(lua_State *L)
467 struct win *w1 = check_window(L, 1), *w2 = check_window(L, 2);
468 lua_pushboolean(L, (w1 == w2 || (w1 && w2 && w1->w_number == w2->w_number)));
469 return 1;
472 static const luaL_reg window_metamethods[] = {
473 {"__tostring", window_tostring},
474 {"__eq", window_equality},
475 {0, 0}
478 static const struct Xet_reg window_setters[] = {
479 {"title", 0, 0, window_change_title/*absolute setter*/},
480 {"number", 0, 0, window_change_number/*absolute setter*/},
481 {0, 0}
484 static const struct Xet_reg window_getters[] = {
485 {"title", get_string, offsetof(struct win, w_title) + 8},
486 {"number", get_int, offsetof(struct win, w_number)},
487 {"dir", get_string, offsetof(struct win, w_dir)},
488 {"tty", get_string, offsetof(struct win, w_tty)},
489 {"pid", get_int, offsetof(struct win, w_pid)},
490 {"group", get_window, offsetof(struct win, w_group)},
491 {"bell", get_int, offsetof(struct win, w_bell)},
492 {0, 0}
496 /** }}} */
498 /** AclUser {{{ */
500 PUSH_TYPE(user, struct acluser)
502 CHECK_TYPE(user, struct acluser)
504 static int
505 get_user(lua_State *L, void *v)
507 push_user(L, (struct acluser **)v);
508 return 1;
511 static const luaL_reg user_methods[] = {
512 {0, 0}
515 static int
516 user_tostring(lua_State *L)
518 char str[128];
519 struct acluser *u = check_user(L, 1);
520 snprintf(str, sizeof(str), "{user '%s'}", u->u_name);
521 lua_pushstring(L, str);
522 return 1;
525 static const luaL_reg user_metamethods[] = {
526 {"__tostring", user_tostring},
527 {0, 0}
530 static const struct Xet_reg user_setters[] = {
531 {0, 0}
534 static const struct Xet_reg user_getters[] = {
535 {"name", get_string, offsetof(struct acluser, u_name)},
536 {"password", get_string, offsetof(struct acluser, u_password)},
537 {0, 0}
540 /** }}} */
542 /** Canvas {{{ */
544 PUSH_TYPE(canvas, struct canvas)
546 CHECK_TYPE(canvas, struct canvas)
548 static int
549 get_canvas(lua_State *L, void *v)
551 push_canvas(L, (struct canvas **)v);
552 return 1;
555 static int
556 canvas_select(lua_State *L)
558 struct canvas *c = check_canvas(L, 1);
559 if (!display || D_forecv == c)
560 return 0;
561 SetCanvasWindow(c, Layer2Window(c->c_layer));
562 D_forecv = c;
564 /* XXX: the following all is duplicated from process.c:DoAction.
565 * Should these be in some better place?
567 ResizeCanvas(&D_canvas);
568 RecreateCanvasChain();
569 RethinkDisplayViewports();
570 ResizeLayersToCanvases(); /* redisplays */
571 fore = D_fore = Layer2Window(D_forecv->c_layer);
572 flayer = D_forecv->c_layer;
573 #ifdef RXVT_OSC
574 if (D_xtermosc[2] || D_xtermosc[3])
576 Activate(-1);
577 break;
579 #endif
580 RefreshHStatus();
581 #ifdef RXVT_OSC
582 RefreshXtermOSC();
583 #endif
584 flayer = D_forecv->c_layer;
585 CV_CALL(D_forecv, LayRestore();LaySetCursor());
586 WindowChanged(0, 'F');
587 return 1;
590 static const luaL_reg canvas_methods[] = {
591 {"select", canvas_select},
592 {0, 0}
595 static const luaL_reg canvas_metamethods[] = {
596 {0, 0}
599 static const struct Xet_reg canvas_setters[] = {
600 {0, 0}
603 static int
604 canvas_get_window(lua_State *L)
606 struct canvas *c = check_canvas(L, 1);
607 struct win *win = Layer2Window(c->c_layer);
608 if (win)
609 push_window(L, &win);
610 else
611 lua_pushnil(L);
612 return 1;
615 static const struct Xet_reg canvas_getters[] = {
616 {"next", get_canvas, offsetof(struct canvas, c_next)},
617 {"xoff", get_int, offsetof(struct canvas, c_xoff)},
618 {"yoff", get_int, offsetof(struct canvas, c_yoff)},
619 {"xs", get_int, offsetof(struct canvas, c_xs)},
620 {"ys", get_int, offsetof(struct canvas, c_ys)},
621 {"xe", get_int, offsetof(struct canvas, c_xe)},
622 {"ye", get_int, offsetof(struct canvas, c_ye)},
623 {"window", 0, 0, canvas_get_window},
624 {0, 0}
627 /** }}} */
629 /** Layout {{{ */
631 PUSH_TYPE(layout, struct layout)
632 CHECK_TYPE(layout, struct layout)
634 static const struct Xet_reg layout_getters[] = {
635 {0,0}
638 static int
639 get_layout(lua_State *L, void *v)
641 push_layout(L, (struct layout **)v);
642 return 1;
645 /** }}} */
647 /** Display {{{ */
649 PUSH_TYPE(display, struct display)
651 CHECK_TYPE(display, struct display)
653 static int
654 display_get_canvases(lua_State *L)
656 struct display *d;
657 struct canvas *iter;
658 int count;
660 d = check_display(L, 1);
661 lua_newtable(L);
662 for (iter = d->d_cvlist, count = 0; iter; iter = iter->c_next, count++) {
663 lua_pushinteger(L, count);
664 push_canvas(L, &iter);
665 lua_settable(L, -3);
668 return 1;
671 static const luaL_reg display_methods[] = {
672 {"get_canvases", display_get_canvases},
673 {0, 0}
676 static int
677 display_tostring(lua_State *L)
679 char str[128];
680 struct display *d = check_display(L, 1);
681 snprintf(str, sizeof(str), "{display: tty = '%s', term = '%s'}", d->d_usertty, d->d_termname);
682 lua_pushstring(L, str);
683 return 1;
686 static const luaL_reg display_metamethods[] = {
687 {"__tostring", display_tostring},
688 {0, 0}
691 static const struct Xet_reg display_setters[] = {
692 {0, 0}
695 static const struct Xet_reg display_getters[] = {
696 {"tty", get_string, offsetof(struct display, d_usertty)},
697 {"term", get_string, offsetof(struct display, d_termname)},
698 {"fore", get_window, offsetof(struct display, d_fore)},
699 {"other", get_window, offsetof(struct display, d_other)},
700 {"width", get_int, offsetof(struct display, d_width)},
701 {"height", get_int, offsetof(struct display, d_height)},
702 {"user", get_user, offsetof(struct display, d_user)},
703 {"layout", get_layout, offsetof(struct display, d_layout)},
704 {0, 0}
707 /** }}} */
709 /** Screen {{{ */
711 static int
712 screen_get_windows(lua_State *L)
714 struct win *iter;
715 int count;
717 lua_newtable(L);
718 for (iter = windows, count = 0; iter; iter = iter->w_next, count++) {
719 lua_pushinteger(L, iter->w_number);
720 push_window(L, &iter);
721 lua_settable(L, -3);
724 return 1;
727 static int
728 screen_get_displays(lua_State *L)
730 struct display *iter;
731 int count;
733 lua_newtable(L);
734 for (iter = displays, count = 0; iter; iter = iter->d_next, count++) {
735 lua_pushinteger(L, count);
736 push_display(L, &iter);
737 lua_settable(L, -3);
740 return 1;
743 static int
744 screen_get_display(lua_State *L)
746 push_display(L, &display);
747 return 1;
750 static int
751 screen_exec_command(lua_State *L)
753 const char *command;
754 unsigned int len;
756 command = luaL_checklstring(L, 1, &len);
757 if (command)
758 RcLine((char *)command, len);
760 return 0;
763 static int
764 screen_append_msg(lua_State *L)
766 const char *msg, *color;
767 unsigned int len;
768 msg = luaL_checklstring(L, 1, &len);
769 if (lua_isnil(L, 2))
770 color = NULL;
771 else
772 color = luaL_checklstring(L, 2, &len);
773 AppendWinMsgRend(msg, color);
774 return 0;
777 struct sinput_data
779 lua_State *L;
780 lua_handler lh;
783 void
784 script_input_fn(char *buf, int len, char *priv)
786 struct sinput_data *sidata = (struct sinput_data *)priv;
787 lua_handler lh = sidata->lh;
788 lua_State *L = sidata->L;
790 LuaPushHandler(L, lh);
791 lua_pushstring(L, buf);
792 if (lua_pcall(L, 1, 0, 0) == LUA_ERRRUN)
794 if(lua_isstring(L, -1))
796 LuaShowErr(L);
799 free(sidata);
800 LuaFreeHandler(L, &lh);
803 static int
804 screen_input(lua_State *L)
806 char *ss;
807 int n;
808 const char * prompt = NULL, *prefill = NULL;
809 lua_handler lh;
810 struct sinput_data *sidata;
812 prompt = luaL_checkstring(L, 1);
813 lh = LuaCheckHandler(L, 2, 1);
814 if (!lh)
815 luaL_error(L, "Out of Memory");
817 if (lua_gettop(L) >= 3)
818 prefill = luaL_checkstring(L, 3);
821 sidata = (struct sinput_data *)malloc(sizeof(struct sinput_data));
822 if (!sidata)
824 Free(lh);
825 luaL_error(L, "Out of Memory");
828 sidata->L = L;
829 sidata->lh = lh;
830 Input((char *)prompt, 100, INP_COOKED, script_input_fn, (char *)sidata, 0);
832 if (!prefill)
833 return 0;
834 for (; *prefill; prefill++)
836 if ((*(unsigned char *)prefill & 0x7f) < 0x20 || *prefill == 0x7f)
837 continue;
838 ss = (char *)prefill;
839 n = 1;
840 LayProcess(&ss, &n);
842 return 0;
845 static const luaL_reg screen_methods[] = {
846 {"windows", screen_get_windows},
847 {"displays", screen_get_displays},
848 {"display", screen_get_display},
849 {"command", screen_exec_command},
850 {"append_msg", screen_append_msg},
851 {"hook", LuaRegEvent},
852 {"input", screen_input},
853 {0, 0}
856 static const luaL_reg screen_metamethods[] = {
857 {0, 0}
860 static const struct Xet_reg screen_setters[] = {
861 {0, 0}
864 static const struct Xet_reg screen_getters[] = {
865 {0, 0}
868 /** }}} */
870 /** Public functions {{{ */
872 /* FIXME: This code only tracks one unhook ticket for a lua func.
873 * So it does not work if one func is registered more than one times. */
874 static void
875 prepare_weak_table(lua_State *L, const char *name, const char *mode)
877 luaL_getmetatable(L, "screen");
879 lua_pushstring(L, name);
880 lua_newtable(L);
882 /* prepare a metatable to indicate weak table */
883 lua_newtable(L);
884 lua_pushstring(L, "__mode");
885 lua_pushstring(L, mode);
886 lua_rawset(L, -3);
887 /* Mark weak table */
888 lua_setmetatable(L, -2);
889 lua_rawset(L, -3);
890 lua_pop(L, 1);
893 static lua_State *L;
894 int LuaInit(void)
896 L = luaL_newstate();
898 luaL_openlibs(L);
900 #define REGISTER(X) struct_register(L, #X , X ## _methods, X##_metamethods, X##_setters, X##_getters)
902 REGISTER(screen);
903 REGISTER(window);
904 REGISTER(display);
905 REGISTER(user);
906 REGISTER(canvas);
907 REGISTER(callback);
909 /* To store handler funcs */
911 /*_two kinds of information are mantained:
913 * funcreg[key]->func
914 * The 'func' part of the tables are weak. That means the registered funcs
915 * will be collected once the func is no longer available (e.g. overwritten
916 * by a new instance of the script)
918 * To make this process happens faster, GC is forced at the end of each
919 * source.
920 * TODO: What if some events are triggered within the sourcing
921 * procedure?
922 * */
923 prepare_weak_table(L, "_funcreg", "v");
925 /* funcunhook[func]->listener
926 * The listener is the unhook ticket of the hook. which should be collected
927 * once the func is collected. The gc metamethod will be triggered
928 * accordingly. */
929 prepare_weak_table(L, "_funcunhook", "k");
931 return 0;
934 /* An error message on top of the stack. */
935 static void
936 LuaShowErr(lua_State *L)
938 struct display *d = display;
939 unsigned int len;
940 const char *message = luaL_checklstring(L, -1, &len);
941 LMsg(0, "%s", message ? message : "Unknown error");
942 lua_pop(L, 1);
943 display = d;
946 struct fn_def
948 void (*push_fn)(lua_State *, void*);
949 void *value;
952 static int
953 LuaCallProcess(const char *name, struct fn_def defs[])
955 int argc = 0;
957 lua_getfield(L, LUA_GLOBALSINDEX, name);
958 if (lua_isnil(L, -1))
960 lua_pop(L,1);
961 return 0;
963 for (argc = 0; defs[argc].push_fn; argc++)
964 defs[argc].push_fn(L, defs[argc].value);
965 if (lua_pcall(L, argc, 0, 0) == LUA_ERRRUN && lua_isstring(L, -1))
967 LuaShowErr(L);
968 return 0;
970 return 1;
973 /* FIXME: Think about this: will it affect the registered handlers?*/
974 int LuaSource(const char *file, int async)
976 if (!L)
977 return 0;
978 struct stat st;
979 if (stat(file, &st) == -1)
980 Msg(errno, "Error loading lua script file '%s'", file);
981 else
983 int len = strlen(file);
984 if (len < 4 || strncmp(file + len - 4, ".lua", 4) != 0)
985 return 0;
986 if (luaL_dofile(L, file) && lua_isstring(L, -1))
988 LuaShowErr(L);
989 return 0;
991 else
993 /* It seems that I need two GC passes to really collect the unhook
994 * ticket, after changing the reference to ticket in the
995 * 'funcunhook' table from weak to strong. This should not be
996 * harmful, but how can I make sure that two passes is enough?
998 * Possible reason:
999 * This seems reasonable, since the first pass will collect the func
1000 * itself and make the ticket garbage, and the second pass will
1001 * collect the ticket itself.
1003 * TODO: check this out. maybe ask some lua gurus. */
1004 lua_gc(L, LUA_GCCOLLECT, 0);
1005 lua_gc(L, LUA_GCCOLLECT, 0);
1007 return 1;
1009 return 0;
1012 int LuaFinit(void)
1014 if (!L)
1015 return 0;
1016 lua_close(L);
1017 L = (lua_State*)0;
1018 return 0;
1022 LuaProcessCaption(const char *caption, struct win *win, int len)
1024 if (!L)
1025 return 0;
1026 struct fn_def params[] = {
1027 {lua_pushstring, caption},
1028 {push_window, &win},
1029 {lua_pushinteger, len},
1030 {NULL, NULL}
1032 return LuaCallProcess("process_caption", params);
1035 static void
1036 push_stringarray(lua_State *L, char **args)
1038 int i;
1039 lua_newtable(L);
1040 for (i = 1; args && *args; i++) {
1041 lua_pushinteger(L, i);
1042 lua_pushstring(L, *args++);
1043 lua_settable(L, -3);
1048 LuaPushParams(lua_State *L, const char *params, va_list va)
1050 int num = 0;
1051 while (*params)
1053 switch (*params)
1055 case 's':
1056 lua_pushstring(L, va_arg(va, char *));
1057 break;
1058 case 'S':
1059 push_stringarray(L, va_arg(va, char **));
1060 break;
1061 case 'i':
1062 lua_pushinteger(L, va_arg(va, int));
1063 break;
1064 case 'd':
1066 struct display *d = va_arg(va, struct display *);
1067 push_display(L, &d);
1068 break;
1070 case 'w':
1072 struct win *w = va_arg(va, struct win *);
1073 push_window(L, &w);
1074 break;
1077 params++;
1078 num++;
1080 return num;
1083 int LuaCall(const char *func, const char **argv)
1085 int argc;
1086 if (!L)
1087 return 0;
1089 StackDump(L, "Before LuaCall\n");
1090 lua_getfield(L, LUA_GLOBALSINDEX, func);
1091 if (lua_isnil(L, -1))
1093 lua_pop(L, 1);
1094 lua_pushstring(L, "Could not find the script function\n");
1095 LuaShowErr(L);
1096 return 0;
1098 for (argc = 0; *argv; argv++, argc++)
1100 lua_pushstring(L, *argv);
1102 if (lua_pcall(L, argc, 0, 0) == LUA_ERRRUN)
1104 if(lua_isstring(L, -1))
1106 StackDump(L, "After LuaCall\n");
1107 LuaShowErr(L);
1108 return 0;
1111 return 1;
1114 /*** Lua callback handler management {{{ */
1117 LuaPushHTable(lua_State *L, int screen, const char * t)
1119 lua_pushstring(L, t);
1120 lua_rawget(L, screen);
1121 /* FIXME: Do we need to balance the stack here? */
1122 if (lua_isnil(L, -1))
1123 luaL_error(L, "Fatal! Fail to get function registeration table!");
1124 return lua_gettop(L);
1127 void
1128 LuaPushHandler(lua_State *L, lua_handler lh)
1130 int funcreg;
1131 if (lh->type == LUA_HANDLER_TYPE_F)
1133 luaL_getmetatable(L, "screen");
1134 funcreg = LuaPushHTable(L, lua_gettop(L), "_funcreg");
1135 lua_rawgeti(L, funcreg, lh->u.reference);
1136 lua_replace(L, -3);
1137 lua_pop(L, 1);
1139 else
1141 lua_getfield(L, LUA_GLOBALSINDEX, lh->u.name);
1146 LuaFuncKey(lua_State *L, int idx, int ref)
1148 int key, funcreg, sc;
1149 luaL_getmetatable(L, "screen");
1150 sc = lua_gettop(L);
1151 funcreg = LuaPushHTable(L, sc, "_funcreg");
1153 lua_pushvalue(L, idx);
1154 key = luaL_ref(L, funcreg);
1155 lua_pop(L, 2);
1156 return key;
1159 void
1160 LuaHUnRef(lua_State *L, int key)
1162 int funcreg, sc;
1163 luaL_getmetatable(L, "screen");
1164 sc = lua_gettop(L);
1165 funcreg = LuaPushHTable(L, sc, "_funcreg");
1166 luaL_unref(L, funcreg, key);
1169 lua_handler
1170 LuaCheckHandler(lua_State *L, int idx, int ref)
1172 int key;
1173 if (idx < 0)
1174 idx = lua_gettop(L) + 1 - idx;
1176 if (lua_isstring(L, idx))
1178 const char * handler;
1179 /* registered with func name.*/
1180 handler = luaL_checkstring(L, idx);
1181 lua_getfield(L, LUA_GLOBALSINDEX, handler);
1182 if (!lua_isfunction(L, -1))
1183 luaL_error(L, "The specified handler %s in param #%d is not a function", handler, idx);
1184 lua_pop(L, 1);
1185 return LuaAllocHandler(handler, 0);
1187 else if (!lua_isfunction(L, idx))
1188 luaL_error(L, "Handler should be a function or the name of function");
1190 key = LuaFuncKey(L, idx, ref);
1191 return LuaAllocHandler(NULL, key);
1194 /* }}} **/
1196 static int
1197 LuaDispatch(void *handler, const char *params, va_list va)
1199 lua_handler lh = (lua_handler)handler;
1200 int argc, retvalue;
1202 StackDump(L, "before dispatch");
1204 LuaPushHandler(L, lh);
1205 if (lua_isnil(L, -1))
1207 lua_pop(L, 1);
1208 return 0;
1210 argc = LuaPushParams(L, params, va);
1212 if (lua_pcall(L, argc, 1, 0) == LUA_ERRRUN && lua_isstring(L, -1))
1214 StackDump(L, "After LuaDispatch\n");
1215 LuaShowErr(L);
1216 return 0;
1218 retvalue = lua_tonumber(L, -1);
1219 lua_pop(L, 1);
1220 return retvalue;
1223 /*FIXME: what if a func is registered twice or more? */
1224 void
1225 LuaRegAutoUnHook(lua_State *L, lua_handler lh, int ticket)
1227 int sc, funcunhook;
1228 luaL_getmetatable(L, "screen");
1229 sc = lua_gettop(L);
1230 funcunhook = LuaPushHTable(L, sc, "_funcunhook");
1231 LuaPushHandler(L, lh);
1232 lua_pushvalue(L, ticket);
1233 lua_rawset(L, funcunhook);
1234 lua_pop(L, 2);
1237 #define SEVNAME_MAX 30
1238 static int
1239 LuaRegEvent(lua_State *L)
1241 /* signature: hook(obj, event, handler, priv);
1242 * or: hook(event, handler, priv)
1243 * returns: A ticket for later unregister. */
1244 int idx = 1, argc = lua_gettop(L);
1245 unsigned int priv = 31; /* Default privilege */
1246 lua_handler lh;
1248 char *obj = NULL;
1249 const char *objname = "global";
1251 static char evbuf[SEVNAME_MAX];
1252 const char *event;
1254 struct script_event *sev;
1256 StackDump(L, "Before RegEvent\n");
1258 /* Identify the object, if specified */
1259 if (luaL_getmetafield(L, 1, "_objname"))
1261 objname = luaL_checkstring(L, -1);
1262 lua_pop(L, 1);
1263 if (!strcmp("screen", objname))
1264 objname = "global";
1265 else
1266 obj = *(char **)lua_touserdata(L, 1);
1267 idx++;
1270 event = luaL_checkstring(L, idx++);
1271 snprintf(evbuf, SEVNAME_MAX, "%s_%s", objname, event);
1273 /* Check and get the handler */
1274 lh = LuaCheckHandler(L, idx++, 1);
1275 if (!lh)
1276 luaL_error(L, "Out of memory");
1278 StackDump(L, "In RegEvent\n");
1280 if (idx <= argc)
1281 priv = luaL_checkinteger(L, idx);
1283 sev = object_get_event(obj, evbuf);
1284 if (sev)
1286 struct listener *l;
1287 int ticket;
1288 l = (struct listener *)malloc(sizeof(struct listener));
1289 if (!l)
1290 return luaL_error(L, "Out of memory");
1291 l->priv = priv;
1292 l->bd = &lua_binding;
1293 l->handler = (void *)lh;
1294 register_listener(sev, l);
1295 /* Return the ticket for un-register */
1296 push_callback(L, &l);
1297 ticket = lua_gettop(L);
1299 LuaRegAutoUnHook(L, lh, ticket);
1301 else
1302 return luaL_error(L, "Invalid event specified: %s for object %s", event, objname);
1304 StackDump(L, "After RegEvent\n");
1305 return 1;
1308 /** }}} */
1310 struct ScriptFuncs LuaFuncs =
1312 LuaProcessCaption
1315 struct binding lua_binding =
1317 "lua", /*name*/
1318 0, /*inited*/
1319 0, /*registered*/
1320 LuaInit,
1321 LuaFinit,
1322 LuaCall,
1323 LuaSource,
1324 LuaDispatch,
1325 0, /*b_next*/
1326 &LuaFuncs