621b1a1d4eb356402572eb62192d0ccf61568d2b
[screen-lua.git] / src / lua.c
blob621b1a1d4eb356402572eb62192d0ccf61568d2b
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 const luaL_reg window_methods[] = {
433 {"get_monitor_status", window_get_monitor_status},
434 {"hook", LuaRegEvent},
435 {0, 0}
438 static int
439 window_tostring(lua_State *L)
441 char str[128];
442 struct win *w = check_window(L, 1);
443 snprintf(str, sizeof(str), "{window #%d: '%s'}", w->w_number, w->w_title);
444 lua_pushstring(L, str);
445 return 1;
448 static int
449 window_equality(lua_State *L)
451 struct win *w1 = check_window(L, 1), *w2 = check_window(L, 2);
452 lua_pushboolean(L, (w1 == w2 || (w1 && w2 && w1->w_number == w2->w_number)));
453 return 1;
456 static const luaL_reg window_metamethods[] = {
457 {"__tostring", window_tostring},
458 {"__eq", window_equality},
459 {0, 0}
462 static const struct Xet_reg window_setters[] = {
463 {"title", 0, 0, window_change_title/*absolute setter*/},
464 {"number", 0, 0, window_change_number/*absolute setter*/},
465 {0, 0}
468 static const struct Xet_reg window_getters[] = {
469 {"title", get_string, offsetof(struct win, w_title) + 8},
470 {"number", get_int, offsetof(struct win, w_number)},
471 {"dir", get_string, offsetof(struct win, w_dir)},
472 {"tty", get_string, offsetof(struct win, w_tty)},
473 {"pid", get_int, offsetof(struct win, w_pid)},
474 {"group", get_window, offsetof(struct win, w_group)},
475 {"bell", get_int, offsetof(struct win, w_bell)},
476 {0, 0}
480 /** }}} */
482 /** AclUser {{{ */
484 PUSH_TYPE(user, struct acluser)
486 CHECK_TYPE(user, struct acluser)
488 static int
489 get_user(lua_State *L, void *v)
491 push_user(L, (struct acluser **)v);
492 return 1;
495 static const luaL_reg user_methods[] = {
496 {0, 0}
499 static int
500 user_tostring(lua_State *L)
502 char str[128];
503 struct acluser *u = check_user(L, 1);
504 snprintf(str, sizeof(str), "{user '%s'}", u->u_name);
505 lua_pushstring(L, str);
506 return 1;
509 static const luaL_reg user_metamethods[] = {
510 {"__tostring", user_tostring},
511 {0, 0}
514 static const struct Xet_reg user_setters[] = {
515 {0, 0}
518 static const struct Xet_reg user_getters[] = {
519 {"name", get_string, offsetof(struct acluser, u_name)},
520 {"password", get_string, offsetof(struct acluser, u_password)},
521 {0, 0}
524 /** }}} */
526 /** Canvas {{{ */
528 PUSH_TYPE(canvas, struct canvas)
530 CHECK_TYPE(canvas, struct canvas)
532 static int
533 get_canvas(lua_State *L, void *v)
535 push_canvas(L, (struct canvas **)v);
536 return 1;
539 static int
540 canvas_select(lua_State *L)
542 struct canvas *c = check_canvas(L, 1);
543 if (!display || D_forecv == c)
544 return 0;
545 SetCanvasWindow(c, Layer2Window(c->c_layer));
546 D_forecv = c;
548 /* XXX: the following all is duplicated from process.c:DoAction.
549 * Should these be in some better place?
551 ResizeCanvas(&D_canvas);
552 RecreateCanvasChain();
553 RethinkDisplayViewports();
554 ResizeLayersToCanvases(); /* redisplays */
555 fore = D_fore = Layer2Window(D_forecv->c_layer);
556 flayer = D_forecv->c_layer;
557 #ifdef RXVT_OSC
558 if (D_xtermosc[2] || D_xtermosc[3])
560 Activate(-1);
561 break;
563 #endif
564 RefreshHStatus();
565 #ifdef RXVT_OSC
566 RefreshXtermOSC();
567 #endif
568 flayer = D_forecv->c_layer;
569 CV_CALL(D_forecv, LayRestore();LaySetCursor());
570 WindowChanged(0, 'F');
571 return 1;
574 static const luaL_reg canvas_methods[] = {
575 {"select", canvas_select},
576 {0, 0}
579 static const luaL_reg canvas_metamethods[] = {
580 {0, 0}
583 static const struct Xet_reg canvas_setters[] = {
584 {0, 0}
587 static int
588 canvas_get_window(lua_State *L)
590 struct canvas *c = check_canvas(L, 1);
591 struct win *win = Layer2Window(c->c_layer);
592 if (win)
593 push_window(L, &win);
594 else
595 lua_pushnil(L);
596 return 1;
599 static const struct Xet_reg canvas_getters[] = {
600 {"next", get_canvas, offsetof(struct canvas, c_next)},
601 {"xoff", get_int, offsetof(struct canvas, c_xoff)},
602 {"yoff", get_int, offsetof(struct canvas, c_yoff)},
603 {"xs", get_int, offsetof(struct canvas, c_xs)},
604 {"ys", get_int, offsetof(struct canvas, c_ys)},
605 {"xe", get_int, offsetof(struct canvas, c_xe)},
606 {"ye", get_int, offsetof(struct canvas, c_ye)},
607 {"window", 0, 0, canvas_get_window},
608 {0, 0}
611 /** }}} */
613 /** Layout {{{ */
615 PUSH_TYPE(layout, struct layout)
616 CHECK_TYPE(layout, struct layout)
618 static const struct Xet_reg layout_getters[] = {
619 {0,0}
622 static int
623 get_layout(lua_State *L, void *v)
625 push_layout(L, (struct layout **)v);
626 return 1;
629 /** }}} */
631 /** Display {{{ */
633 PUSH_TYPE(display, struct display)
635 CHECK_TYPE(display, struct display)
637 static int
638 display_get_canvases(lua_State *L)
640 struct display *d;
641 struct canvas *iter;
642 int count;
644 d = check_display(L, 1);
645 lua_newtable(L);
646 for (iter = d->d_cvlist, count = 0; iter; iter = iter->c_next, count++) {
647 lua_pushinteger(L, count);
648 push_canvas(L, &iter);
649 lua_settable(L, -3);
652 return 1;
655 static const luaL_reg display_methods[] = {
656 {"get_canvases", display_get_canvases},
657 {0, 0}
660 static int
661 display_tostring(lua_State *L)
663 char str[128];
664 struct display *d = check_display(L, 1);
665 snprintf(str, sizeof(str), "{display: tty = '%s', term = '%s'}", d->d_usertty, d->d_termname);
666 lua_pushstring(L, str);
667 return 1;
670 static const luaL_reg display_metamethods[] = {
671 {"__tostring", display_tostring},
672 {0, 0}
675 static const struct Xet_reg display_setters[] = {
676 {0, 0}
679 static const struct Xet_reg display_getters[] = {
680 {"tty", get_string, offsetof(struct display, d_usertty)},
681 {"term", get_string, offsetof(struct display, d_termname)},
682 {"fore", get_window, offsetof(struct display, d_fore)},
683 {"other", get_window, offsetof(struct display, d_other)},
684 {"width", get_int, offsetof(struct display, d_width)},
685 {"height", get_int, offsetof(struct display, d_height)},
686 {"user", get_user, offsetof(struct display, d_user)},
687 {"layout", get_layout, offsetof(struct display, d_layout)},
688 {0, 0}
691 /** }}} */
693 /** Screen {{{ */
695 static int
696 screen_get_windows(lua_State *L)
698 struct win *iter;
699 int count;
701 lua_newtable(L);
702 for (iter = windows, count = 0; iter; iter = iter->w_next, count++) {
703 lua_pushinteger(L, iter->w_number);
704 push_window(L, &iter);
705 lua_settable(L, -3);
708 return 1;
711 static int
712 screen_get_displays(lua_State *L)
714 struct display *iter;
715 int count;
717 lua_newtable(L);
718 for (iter = displays, count = 0; iter; iter = iter->d_next, count++) {
719 lua_pushinteger(L, count);
720 push_display(L, &iter);
721 lua_settable(L, -3);
724 return 1;
727 static int
728 screen_get_display(lua_State *L)
730 push_display(L, &display);
731 return 1;
734 static int
735 screen_exec_command(lua_State *L)
737 const char *command;
738 unsigned int len;
740 command = luaL_checklstring(L, 1, &len);
741 if (command)
742 RcLine((char *)command, len);
744 return 0;
747 static int
748 screen_append_msg(lua_State *L)
750 const char *msg, *color;
751 unsigned int len;
752 msg = luaL_checklstring(L, 1, &len);
753 if (lua_isnil(L, 2))
754 color = NULL;
755 else
756 color = luaL_checklstring(L, 2, &len);
757 AppendWinMsgRend(msg, color);
758 return 0;
761 struct sinput_data
763 lua_State *L;
764 lua_handler lh;
767 void
768 script_input_fn(char *buf, int len, char *priv)
770 struct sinput_data *sidata = (struct sinput_data *)priv;
771 lua_handler lh = sidata->lh;
772 lua_State *L = sidata->L;
774 LuaPushHandler(L, lh);
775 lua_pushstring(L, buf);
776 if (lua_pcall(L, 1, 0, 0) == LUA_ERRRUN)
778 if(lua_isstring(L, -1))
780 LuaShowErr(L);
783 free(sidata);
784 LuaFreeHandler(L, &lh);
787 static int
788 screen_input(lua_State *L)
790 char *ss;
791 int n;
792 const char * prompt = NULL, *prefill = NULL;
793 lua_handler lh;
794 struct sinput_data *sidata;
796 prompt = luaL_checkstring(L, 1);
797 lh = LuaCheckHandler(L, 2, 1);
798 if (!lh)
799 luaL_error(L, "Out of Memory");
801 if (lua_gettop(L) >= 3)
802 prefill = luaL_checkstring(L, 3);
805 sidata = (struct sinput_data *)malloc(sizeof(struct sinput_data));
806 if (!sidata)
808 Free(lh);
809 luaL_error(L, "Out of Memory");
812 sidata->L = L;
813 sidata->lh = lh;
814 Input((char *)prompt, 100, INP_COOKED, script_input_fn, (char *)sidata, 0);
816 if (!prefill)
817 return 0;
818 for (; *prefill; prefill++)
820 if ((*(unsigned char *)prefill & 0x7f) < 0x20 || *prefill == 0x7f)
821 continue;
822 ss = (char *)prefill;
823 n = 1;
824 LayProcess(&ss, &n);
826 return 0;
829 static const luaL_reg screen_methods[] = {
830 {"windows", screen_get_windows},
831 {"displays", screen_get_displays},
832 {"display", screen_get_display},
833 {"command", screen_exec_command},
834 {"append_msg", screen_append_msg},
835 {"hook", LuaRegEvent},
836 {"input", screen_input},
837 {0, 0}
840 static const luaL_reg screen_metamethods[] = {
841 {0, 0}
844 static const struct Xet_reg screen_setters[] = {
845 {0, 0}
848 static const struct Xet_reg screen_getters[] = {
849 {0, 0}
852 /** }}} */
854 /** Public functions {{{ */
856 /* FIXME: This code only tracks one unhook ticket for a lua func.
857 * So it does not work if one func is registered more than one times. */
858 static void
859 prepare_weak_table(lua_State *L, const char *name, const char *mode)
861 luaL_getmetatable(L, "screen");
863 lua_pushstring(L, name);
864 lua_newtable(L);
866 /* prepare a metatable to indicate weak table */
867 lua_newtable(L);
868 lua_pushstring(L, "__mode");
869 lua_pushstring(L, mode);
870 lua_rawset(L, -3);
871 /* Mark weak table */
872 lua_setmetatable(L, -2);
873 lua_rawset(L, -3);
874 lua_pop(L, 1);
877 static lua_State *L;
878 int LuaInit(void)
880 L = luaL_newstate();
882 luaL_openlibs(L);
884 #define REGISTER(X) struct_register(L, #X , X ## _methods, X##_metamethods, X##_setters, X##_getters)
886 REGISTER(screen);
887 REGISTER(window);
888 REGISTER(display);
889 REGISTER(user);
890 REGISTER(canvas);
891 REGISTER(callback);
893 /* To store handler funcs */
895 /*_two kinds of information are mantained:
897 * funcreg[key]->func
898 * The 'func' part of the tables are weak. That means the registered funcs
899 * will be collected once the func is no longer available (e.g. overwritten
900 * by a new instance of the script)
902 * To make this process happens faster, GC is forced at the end of each
903 * source.
904 * TODO: What if some events are triggered within the sourcing
905 * procedure?
906 * */
907 prepare_weak_table(L, "_funcreg", "v");
909 /* funcunhook[func]->listener
910 * The listener is the unhook ticket of the hook. which should be collected
911 * once the func is collected. The gc metamethod will be triggered
912 * accordingly. */
913 prepare_weak_table(L, "_funcunhook", "k");
915 return 0;
918 /* An error message on top of the stack. */
919 static void
920 LuaShowErr(lua_State *L)
922 struct display *d = display;
923 unsigned int len;
924 const char *message = luaL_checklstring(L, -1, &len);
925 LMsg(0, "%s", message ? message : "Unknown error");
926 lua_pop(L, 1);
927 display = d;
930 struct fn_def
932 void (*push_fn)(lua_State *, void*);
933 void *value;
936 static int
937 LuaCallProcess(const char *name, struct fn_def defs[])
939 int argc = 0;
941 lua_getfield(L, LUA_GLOBALSINDEX, name);
942 if (lua_isnil(L, -1))
944 lua_pop(L,1);
945 return 0;
947 for (argc = 0; defs[argc].push_fn; argc++)
948 defs[argc].push_fn(L, defs[argc].value);
949 if (lua_pcall(L, argc, 0, 0) == LUA_ERRRUN && lua_isstring(L, -1))
951 LuaShowErr(L);
952 return 0;
954 return 1;
957 /* FIXME: Think about this: will it affect the registered handlers?*/
958 int LuaSource(const char *file, int async)
960 if (!L)
961 return 0;
962 struct stat st;
963 if (stat(file, &st) == -1)
964 Msg(errno, "Error loading lua script file '%s'", file);
965 else
967 int len = strlen(file);
968 if (len < 4 || strncmp(file + len - 4, ".lua", 4) != 0)
969 return 0;
970 if (luaL_dofile(L, file) && lua_isstring(L, -1))
972 LuaShowErr(L);
973 return 0;
975 else
977 /* It seems that I need two GC passes to really collect the unhook
978 * ticket, after changing the reference to ticket in the
979 * 'funcunhook' table from weak to strong. This should not be
980 * harmful, but how can I make sure that two passes is enough?
982 * Possible reason:
983 * This seems reasonable, since the first pass will collect the func
984 * itself and make the ticket garbage, and the second pass will
985 * collect the ticket itself.
987 * TODO: check this out. maybe ask some lua gurus. */
988 lua_gc(L, LUA_GCCOLLECT, 0);
989 lua_gc(L, LUA_GCCOLLECT, 0);
991 return 1;
993 return 0;
996 int LuaFinit(void)
998 if (!L)
999 return 0;
1000 lua_close(L);
1001 L = (lua_State*)0;
1002 return 0;
1006 LuaProcessCaption(const char *caption, struct win *win, int len)
1008 if (!L)
1009 return 0;
1010 struct fn_def params[] = {
1011 {lua_pushstring, caption},
1012 {push_window, &win},
1013 {lua_pushinteger, len},
1014 {NULL, NULL}
1016 return LuaCallProcess("process_caption", params);
1019 static void
1020 push_stringarray(lua_State *L, char **args)
1022 int i;
1023 lua_newtable(L);
1024 for (i = 1; args && *args; i++) {
1025 lua_pushinteger(L, i);
1026 lua_pushstring(L, *args++);
1027 lua_settable(L, -3);
1032 LuaPushParams(lua_State *L, const char *params, va_list va)
1034 int num = 0;
1035 while (*params)
1037 switch (*params)
1039 case 's':
1040 lua_pushstring(L, va_arg(va, char *));
1041 break;
1042 case 'S':
1043 push_stringarray(L, va_arg(va, char **));
1044 break;
1045 case 'i':
1046 lua_pushinteger(L, va_arg(va, int));
1047 break;
1048 case 'd':
1050 struct display *d = va_arg(va, struct display *);
1051 push_display(L, &d);
1052 break;
1055 params++;
1056 num++;
1058 return num;
1061 int LuaCall(const char *func, const char **argv)
1063 int argc;
1064 if (!L)
1065 return 0;
1067 StackDump(L, "Before LuaCall\n");
1068 lua_getfield(L, LUA_GLOBALSINDEX, func);
1069 if (lua_isnil(L, -1))
1071 lua_pop(L, 1);
1072 lua_pushstring(L, "Could not find the script function\n");
1073 LuaShowErr(L);
1074 return 0;
1076 for (argc = 0; *argv; argv++, argc++)
1078 lua_pushstring(L, *argv);
1080 if (lua_pcall(L, argc, 0, 0) == LUA_ERRRUN)
1082 if(lua_isstring(L, -1))
1084 StackDump(L, "After LuaCall\n");
1085 LuaShowErr(L);
1086 return 0;
1089 return 1;
1092 /*** Lua callback handler management {{{ */
1095 LuaPushHTable(lua_State *L, int screen, const char * t)
1097 lua_pushstring(L, t);
1098 lua_rawget(L, screen);
1099 /* FIXME: Do we need to balance the stack here? */
1100 if (lua_isnil(L, -1))
1101 luaL_error(L, "Fatal! Fail to get function registeration table!");
1102 return lua_gettop(L);
1105 void
1106 LuaPushHandler(lua_State *L, lua_handler lh)
1108 int funcreg;
1109 if (lh->type == LUA_HANDLER_TYPE_F)
1111 luaL_getmetatable(L, "screen");
1112 funcreg = LuaPushHTable(L, lua_gettop(L), "_funcreg");
1113 lua_rawgeti(L, funcreg, lh->u.reference);
1114 lua_replace(L, -3);
1115 lua_pop(L, 1);
1117 else
1119 lua_getfield(L, LUA_GLOBALSINDEX, lh->u.name);
1124 LuaFuncKey(lua_State *L, int idx, int ref)
1126 int key, funcreg, sc;
1127 luaL_getmetatable(L, "screen");
1128 sc = lua_gettop(L);
1129 funcreg = LuaPushHTable(L, sc, "_funcreg");
1131 lua_pushvalue(L, idx);
1132 key = luaL_ref(L, funcreg);
1133 lua_pop(L, 2);
1134 return key;
1137 void
1138 LuaHUnRef(lua_State *L, int key)
1140 int funcreg, sc;
1141 luaL_getmetatable(L, "screen");
1142 sc = lua_gettop(L);
1143 funcreg = LuaPushHTable(L, sc, "_funcreg");
1144 luaL_unref(L, funcreg, key);
1147 lua_handler
1148 LuaCheckHandler(lua_State *L, int idx, int ref)
1150 int key;
1151 if (idx < 0)
1152 idx = lua_gettop(L) + 1 - idx;
1154 if (lua_isstring(L, idx))
1156 const char * handler;
1157 /* registered with func name.*/
1158 handler = luaL_checkstring(L, idx);
1159 lua_getfield(L, LUA_GLOBALSINDEX, handler);
1160 if (!lua_isfunction(L, -1))
1161 luaL_error(L, "The specified handler %s in param #%d is not a function", handler, idx);
1162 lua_pop(L, 1);
1163 return LuaAllocHandler(handler, 0);
1165 else if (!lua_isfunction(L, idx))
1166 luaL_error(L, "Handler should be a function or the name of function");
1168 key = LuaFuncKey(L, idx, ref);
1169 return LuaAllocHandler(NULL, key);
1172 /* }}} **/
1174 static int
1175 LuaDispatch(void *handler, const char *params, va_list va)
1177 lua_handler lh = (lua_handler)handler;
1178 int argc, retvalue;
1180 StackDump(L, "before dispatch");
1182 LuaPushHandler(L, lh);
1183 if (lua_isnil(L, -1))
1185 lua_pop(L, 1);
1186 return 0;
1188 argc = LuaPushParams(L, params, va);
1190 if (lua_pcall(L, argc, 1, 0) == LUA_ERRRUN && lua_isstring(L, -1))
1192 StackDump(L, "After LuaDispatch\n");
1193 LuaShowErr(L);
1194 return 0;
1196 retvalue = lua_tonumber(L, -1);
1197 lua_pop(L, 1);
1198 return retvalue;
1201 int LuaForeWindowChanged(void)
1203 struct fn_def params[] = {
1204 {push_display, &display},
1205 {push_window, display ? &D_fore : &fore},
1206 {NULL, NULL}
1208 if (!L)
1209 return 0;
1210 return LuaCallProcess("fore_changed", params);
1213 /*FIXME: what if a func is registered twice or more? */
1214 void
1215 LuaRegAutoUnHook(lua_State *L, lua_handler lh, int ticket)
1217 int sc, funcunhook;
1218 luaL_getmetatable(L, "screen");
1219 sc = lua_gettop(L);
1220 funcunhook = LuaPushHTable(L, sc, "_funcunhook");
1221 LuaPushHandler(L, lh);
1222 lua_pushvalue(L, ticket);
1223 lua_rawset(L, funcunhook);
1224 lua_pop(L, 2);
1227 #define SEVNAME_MAX 30
1228 static int
1229 LuaRegEvent(lua_State *L)
1231 /* signature: hook(obj, event, handler, priv);
1232 * or: hook(event, handler, priv)
1233 * returns: A ticket for later unregister. */
1234 int idx = 1, argc = lua_gettop(L);
1235 unsigned int priv = 31; /* Default privilege */
1236 lua_handler lh;
1238 char *obj = NULL;
1239 const char *objname = "global";
1241 static char evbuf[SEVNAME_MAX];
1242 const char *event;
1244 struct script_event *sev;
1246 StackDump(L, "Before RegEvent\n");
1248 /* Identify the object, if specified */
1249 if (luaL_getmetafield(L, 1, "_objname"))
1251 objname = luaL_checkstring(L, -1);
1252 lua_pop(L, 1);
1253 if (!strcmp("screen", objname))
1254 objname = "global";
1255 else
1256 obj = *(char **)lua_touserdata(L, 1);
1257 idx++;
1260 event = luaL_checkstring(L, idx++);
1261 snprintf(evbuf, SEVNAME_MAX, "%s_%s", objname, event);
1263 /* Check and get the handler */
1264 lh = LuaCheckHandler(L, idx++, 1);
1265 if (!lh)
1266 luaL_error(L, "Out of memory");
1268 StackDump(L, "In RegEvent\n");
1270 if (idx <= argc)
1271 priv = luaL_checkinteger(L, idx);
1273 sev = object_get_event(obj, evbuf);
1274 if (sev)
1276 struct listener *l;
1277 int ticket;
1278 l = (struct listener *)malloc(sizeof(struct listener));
1279 if (!l)
1280 return luaL_error(L, "Out of memory");
1281 l->priv = priv;
1282 l->bd = &lua_binding;
1283 l->handler = (void *)lh;
1284 register_listener(sev, l);
1285 /* Return the ticket for un-register */
1286 push_callback(L, &l);
1287 ticket = lua_gettop(L);
1289 LuaRegAutoUnHook(L, lh, ticket);
1291 else
1292 return luaL_error(L, "Invalid event specified: %s for object %s", event, objname);
1294 StackDump(L, "After RegEvent\n");
1295 return 1;
1298 /** }}} */
1300 struct ScriptFuncs LuaFuncs =
1302 LuaForeWindowChanged,
1303 LuaProcessCaption
1306 struct binding lua_binding =
1308 "lua", /*name*/
1309 0, /*inited*/
1310 0, /*registered*/
1311 LuaInit,
1312 LuaFinit,
1313 LuaCall,
1314 LuaSource,
1315 LuaDispatch,
1316 0, /*b_next*/
1317 &LuaFuncs