Use separate lua_State for different script files.
[screen-lua.git] / src / lua.c
blob110eb8882de6657f014e5ae85890ceaf8e2be7e8
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);
81 extern void FocusCanvas(struct canvas *cv);
83 static int LuaDispatch(void *handler, const char *params, va_list va);
84 static int LuaRegEvent(lua_State *L);
85 static void LuaShowErr(lua_State *L);
86 struct binding lua_binding;
88 enum
90 LUA_HANDLER_TYPE_N = 1,
91 LUA_HANDLER_TYPE_F
94 struct lua_handler
96 int type;
97 lua_State *L;
98 union
100 const char *name;
101 int reference;
102 } u;
105 typedef struct lua_handler *lua_handler;
106 void LuaPushHandler(lua_handler lh);
107 void LuaHUnRef(lua_State *L, int key);
108 lua_handler LuaCheckHandler(lua_State *L, int idx, int ref);
110 lua_handler
111 LuaAllocHandler(lua_State *L, const char *name, int ref)
113 struct lua_handler *lh;
114 lh = (struct lua_handler*) malloc(sizeof(struct lua_handler));
115 if (!lh)
116 return NULL;
118 lh->L = L;
119 if (name)
121 lh->type = LUA_HANDLER_TYPE_N;
122 lh->u.name = SaveStr(name);
124 else
126 lh->type = LUA_HANDLER_TYPE_F;
127 lh->u.reference = ref;
130 return lh;
133 void
134 LuaFreeHandler(lua_State *L, struct lua_handler **lh)
136 if ((*lh)->type == LUA_HANDLER_TYPE_N)
137 Free((*lh)->u.name)
138 else
140 LuaHUnRef(L, (*lh)->u.reference);
141 (*lh)->u.reference = 0;
143 Free(*lh);
145 /** Template {{{ */
147 #define CHECK_TYPE(name, type) \
148 static type * \
149 check_##name(lua_State *L, int index) \
151 struct broker **broker; \
152 type *var; \
153 luaL_checktype(L, index, LUA_TUSERDATA); \
154 broker = (struct broker **) luaL_checkudata(L, index, #name); \
155 if (broker) { \
156 var = (type *)get_broker_obj(broker); \
158 if (!broker || !*broker) \
159 luaL_typerror(L, index, #name); \
160 return var; \
163 #define PUSH_TYPE(name, type) \
164 static void \
165 push_##name(lua_State *L, type **t) \
167 if (!t || !*t) \
168 lua_pushnil(L); \
169 else \
171 struct broker **r; \
172 r = (struct broker **)lua_newuserdata(L, sizeof(struct broker *)); \
173 *r = get_obj_broker(*t); \
174 luaL_getmetatable(L, #name); \
175 lua_setmetatable(L,-2); \
179 /* Much of the following template comes from:
180 * http://lua-users.org/wiki/BindingWithMembersAndMethods
183 static int get_int (lua_State *L, void *v)
185 lua_pushinteger (L, *(int*)v);
186 return 1;
189 static int set_int (lua_State *L, void *v)
191 *(int*)v = luaL_checkint(L, 3);
192 return 0;
195 static int get_number (lua_State *L, void *v)
197 lua_pushnumber(L, *(lua_Number*)v);
198 return 1;
201 static int set_number (lua_State *L, void *v)
203 *(lua_Number*)v = luaL_checknumber(L, 3);
204 return 0;
207 static int get_string (lua_State *L, void *v)
209 lua_pushstring(L, (char*)v );
210 return 1;
213 static int set_string (lua_State *L, void *v)
215 *(const char**)v = luaL_checkstring(L, 3);
216 return 0;
219 typedef int (*Xet_func) (lua_State *L, void *v);
221 /* member info for get and set handlers */
222 struct Xet_reg
224 const char *name; /* member name */
225 Xet_func func; /* get or set function for type of member */
226 size_t offset; /* offset of member within the struct */
227 int (*absolute)(lua_State *);
230 static void Xet_add (lua_State *L, const struct Xet_reg *l)
232 if (!l)
233 return;
234 for (; l->name; l++)
236 lua_pushstring(L, l->name);
237 lua_pushlightuserdata(L, (void*)l);
238 lua_settable(L, -3);
242 static int Xet_call (lua_State *L)
244 /* for get: stack has userdata, index, lightuserdata */
245 /* for set: stack has userdata, index, value, lightuserdata */
246 const struct Xet_reg *m = (const struct Xet_reg *)lua_touserdata(L, -1); /* member info */
247 void *obj;
248 lua_pop(L, 1); /* drop lightuserdata */
249 luaL_checktype(L, 1, LUA_TUSERDATA);
250 if (m->absolute)
251 return m->absolute(L);
252 obj = get_broker_obj((struct broker **)lua_touserdata(L, 1));
253 return m->func(L, (char *)obj + m->offset);
256 static int index_handler (lua_State *L)
258 /* stack has userdata, index */
259 lua_pushvalue(L, 2); /* dup index */
260 lua_rawget(L, lua_upvalueindex(1)); /* lookup member by name */
261 if (!lua_islightuserdata(L, -1))
263 lua_pop(L, 1); /* drop value */
264 lua_pushvalue(L, 2); /* dup index */
265 lua_gettable(L, lua_upvalueindex(2)); /* else try methods */
266 if (lua_isnil(L, -1)) /* invalid member */
267 luaL_error(L, "cannot get member '%s'", lua_tostring(L, 2));
268 return 1;
270 return Xet_call(L); /* call get function */
273 static int newindex_handler (lua_State *L)
275 /* stack has userdata, index, value */
276 lua_pushvalue(L, 2); /* dup index */
277 lua_rawget(L, lua_upvalueindex(1)); /* lookup member by name */
278 if (!lua_islightuserdata(L, -1)) /* invalid member */
279 luaL_error(L, "cannot set member '%s'", lua_tostring(L, 2));
280 return Xet_call(L); /* call set function */
283 static int
284 struct_register(lua_State *L, const char *name, const luaL_reg fn_methods[], const luaL_reg meta_methods[],
285 const struct Xet_reg setters[], const struct Xet_reg getters[])
287 int metatable, methods;
289 /* create methods table & add it to the table of globals */
290 luaL_register(L, name, fn_methods);
291 methods = lua_gettop(L);
293 /* create metatable & add it to the registry */
294 luaL_newmetatable(L, name);
295 luaL_register(L, 0, meta_methods); /* fill metatable */
297 /* To identify the type of object */
298 lua_pushstring(L, "_objname");
299 lua_pushstring(L, name);
300 lua_rawset(L, -3);
302 metatable = lua_gettop(L);
304 lua_pushliteral(L, "__metatable");
305 lua_pushvalue(L, methods); /* dup methods table*/
306 lua_rawset(L, metatable); /* hide metatable:
307 metatable.__metatable = methods */
309 lua_pushliteral(L, "__index");
310 lua_pushvalue(L, metatable); /* upvalue index 1 */
311 Xet_add(L, getters); /* fill metatable with getters */
312 lua_pushvalue(L, methods); /* upvalue index 2 */
313 lua_pushcclosure(L, index_handler, 2);
314 lua_rawset(L, metatable); /* metatable.__index = index_handler */
316 lua_pushliteral(L, "__newindex");
317 lua_newtable(L); /* table for members you can set */
318 Xet_add(L, setters); /* fill with setters */
319 lua_pushcclosure(L, newindex_handler, 1);
320 lua_rawset(L, metatable); /* metatable.__newindex = newindex_handler */
322 /* FIXME: Why do we leave an element on the stack? */
323 lua_pop(L, 1); /* drop metatable */
324 return 1; /* return methods on the stack */
327 /** }}} */
329 /** Callback {{{ */
330 static void
331 push_callback(lua_State *L, struct listener **t)
333 if (!t || !*t)
334 lua_pushnil(L);
335 else
337 struct listener **r;
338 r = (struct listener **)lua_newuserdata(L, sizeof(struct listener *));
339 *r = *t;
340 luaL_getmetatable(L, "callback");
341 lua_setmetatable(L,-2);
346 static int
347 internal_unhook(lua_State *L, int warn)
349 /*Emulate check_callback() */
350 struct listener **ppl;
351 luaL_checktype(L, 1, LUA_TUSERDATA);
352 ppl = (struct listener **) luaL_checkudata(L, 1, "callback");
354 if (!ppl)
355 luaL_typerror(L, 1, "callback");
357 if (!*ppl)
359 if (warn)
361 lua_pushboolean(L, 0);
362 lua_pushstring(L, "Callback already unhooked.");
363 LuaShowErr(L);
366 else
368 LuaFreeHandler(L, (lua_handler *)&(*ppl)->handler);
369 unregister_listener(*ppl);
370 *ppl = 0;
371 if (warn)
372 lua_pushboolean(L, 1);
374 return warn != 0;
376 static int
377 callback_unhook(lua_State *L)
379 return internal_unhook(L, 1);
382 static const luaL_reg callback_methods[] = {
383 {"unhook", callback_unhook},
384 {0, 0}
388 callback_collect(lua_State *L)
390 return internal_unhook(L, 0);
393 static const luaL_reg callback_metamethods[] = {
394 {"__gc", callback_collect},
395 {0, 0}
398 static const struct Xet_reg callback_setters[] = {
399 {0, 0}
402 static const struct Xet_reg callback_getters[] = {
403 {0, 0}
407 /** }}} */
409 static int
410 screen_object_collect(lua_State *L)
412 struct broker **pbroker;
413 luaL_checktype(L, 1, LUA_TUSERDATA);
414 pbroker = (struct broker **)lua_touserdata(L, 1);
415 broker_unref(pbroker);
416 return 0;
419 /** Window {{{ */
421 PUSH_TYPE(window, struct win)
423 CHECK_TYPE(window, struct win)
425 static int get_window(lua_State *L, void *v)
427 push_window(L, (struct win **)v);
428 return 1;
431 static int
432 window_change_title(lua_State *L)
434 struct win *w = check_window(L, 1);
435 unsigned int len;
436 const char *title = luaL_checklstring(L, 3, &len);
437 ChangeAKA(w, (char *)title, len);
438 return 0;
441 static int
442 window_change_number(lua_State *L)
444 struct win *w = check_window(L, 1);
445 int newnum = luaL_checkint(L, 3);
446 ChangeWinNum(w->w_number, newnum);
447 return 0;
450 static int
451 window_get_monitor_status(lua_State *L)
453 struct win *w = check_window(L, 1);
454 int activity = luaL_checkint(L, 2);
455 if (activity)
456 /*monitor*/
457 lua_pushinteger(L, w->w_monitor != MON_OFF);
458 else
459 /*silence*/
460 lua_pushinteger(L, w->w_silence == SILENCE_ON ? w->w_silencewait: 0);
462 return 1;
465 static int
466 window_stuff(lua_State *L)
468 unsigned int len;
469 struct layer *oldflayer = flayer;
470 struct win *w = check_window(L, 1);
471 const char *str = luaL_checklstring(L, 2, &len);
473 flayer = &w->w_layer;
474 while(len)
475 LayProcess((char **)&str, (int *) &len);
476 flayer = oldflayer;
477 return 0;
480 static int
481 window_activate(lua_State *L)
483 struct win *w = check_window(L, 1);
484 SetForeWindow(w);
485 return 0;
488 static void push_canvas(lua_State *L, struct canvas **t);
490 static int
491 window_get_showing_canvases(lua_State *L)
493 struct win *w = check_window(L, 1);
494 int count = 0;
495 struct canvas *cv = w->w_layer.l_cvlist;
496 if (!cv) {
497 lua_pushnil(L);
498 return 1;
500 lua_newtable(L);
501 while (cv) {
502 lua_pushinteger(L, count++);
503 push_canvas(L, &cv);
504 lua_settable(L, -3);
505 cv = cv->c_lnext;
508 return 1;
511 static int
512 window_getlines(lua_State *L)
514 struct win *w = check_window(L, 1);
515 int i;
516 lua_newtable(L);
517 for (i = 0; i < fore->w_height; i++)
519 char *p = (char *)w->w_mlines[i].image;
520 int k, save;
521 for (k = fore->w_width - 1; k >= 0 && p[k] == ' '; k--)
523 k +=(p[k] != ' ');
524 save = p[k];
525 p[k] = 0;
526 lua_pushinteger(L, i);
527 lua_pushstring(L, p);
528 lua_settable(L, -3);
529 p[k] = save;
532 return 1;
535 static int
536 window_gethistory(lua_State *L)
538 struct win *w = check_window(L, 1);
539 int i;
540 lua_newtable(L);
541 for (i = 0; i < fore->w_height; i++)
543 char *p = (char *) w->w_hlines[(w->w_histidx + i) % w->w_histheight].image;
544 int k, save;
545 for (k = fore->w_width - 1; k >= 0 && p[k] == ' '; k--)
547 k +=(p[k] != ' ');
548 save = p[k];
549 p[k] = 0;
550 lua_pushinteger(L, i);
551 lua_pushstring(L, p);
552 lua_settable(L, -3);
553 p[k] = save;
556 return 1;
559 static const luaL_reg window_methods[] = {
560 {"get_monitor_status", window_get_monitor_status},
561 {"showing_canvases", window_get_showing_canvases},
562 {"stuff", window_stuff},
563 {"activate", window_activate},
564 {"get_lines", window_getlines},
565 {"get_history", window_gethistory},
566 {"hook", LuaRegEvent},
567 {0, 0}
570 static int
571 window_tostring(lua_State *L)
573 char str[128];
574 struct win *w = check_window(L, 1);
575 snprintf(str, sizeof(str), "{window #%d: '%s'}", w->w_number, w->w_title);
576 lua_pushstring(L, str);
577 return 1;
580 static int
581 window_equality(lua_State *L)
583 struct win *w1 = check_window(L, 1), *w2 = check_window(L, 2);
584 lua_pushboolean(L, (w1 == w2 || (w1 && w2 && w1->w_number == w2->w_number)));
585 return 1;
588 static const luaL_reg window_metamethods[] = {
589 {"__tostring", window_tostring},
590 {"__eq", window_equality},
591 {"__gc", screen_object_collect},
592 {0, 0}
595 static const struct Xet_reg window_setters[] = {
596 {"title", 0, 0, window_change_title/*absolute setter*/},
597 {"number", 0, 0, window_change_number/*absolute setter*/},
598 {0, 0}
601 static const struct Xet_reg window_getters[] = {
602 {"title", get_string, offsetof(struct win, w_title) + 8},
603 {"number", get_int, offsetof(struct win, w_number)},
604 {"dir", get_string, offsetof(struct win, w_dir)},
605 {"tty", get_string, offsetof(struct win, w_tty)},
606 {"pid", get_int, offsetof(struct win, w_pid)},
607 {"group", get_window, offsetof(struct win, w_group)},
608 {"bell", get_int, offsetof(struct win, w_bell)},
609 {0, 0}
613 /** }}} */
615 /** AclUser {{{ */
617 PUSH_TYPE(user, struct acluser)
619 CHECK_TYPE(user, struct acluser)
621 static int
622 get_user(lua_State *L, void *v)
624 push_user(L, (struct acluser **)v);
625 return 1;
628 static const luaL_reg user_methods[] = {
629 {0, 0}
632 static int
633 user_tostring(lua_State *L)
635 char str[128];
636 struct acluser *u = check_user(L, 1);
637 snprintf(str, sizeof(str), "{user '%s'}", u->u_name);
638 lua_pushstring(L, str);
639 return 1;
642 static const luaL_reg user_metamethods[] = {
643 {"__tostring", user_tostring},
644 {"__gc", screen_object_collect},
645 {0, 0}
648 static const struct Xet_reg user_setters[] = {
649 {0, 0}
652 static const struct Xet_reg user_getters[] = {
653 {"name", get_string, offsetof(struct acluser, u_name)},
654 {"password", get_string, offsetof(struct acluser, u_password)},
655 {0, 0}
658 /** }}} */
660 static int get_display(lua_State *L, void *v);
661 /** Canvas {{{ */
663 PUSH_TYPE(canvas, struct canvas)
665 CHECK_TYPE(canvas, struct canvas)
667 static int
668 get_canvas(lua_State *L, void *v)
670 push_canvas(L, (struct canvas **)v);
671 return 1;
674 static int
675 canvas_select(lua_State *L)
677 struct canvas *c = check_canvas(L, 1);
678 if (!display || D_forecv == c)
679 return 0;
680 /* FIXME: why do we need this? */
681 SetCanvasWindow(c, Layer2Window(c->c_layer));
683 FocusCanvas(c);
684 return 0;
687 static int
688 canvas_split(lua_State *L)
690 struct canvas *c = check_canvas(L, 1);
691 struct canvas *oldfore = D_forecv;
692 D_forecv = c;
693 int hori = lua_toboolean(L, 2);
694 if (hori)
695 AddCanvas(SLICE_HORI);
696 else
697 AddCanvas(SLICE_VERT);
698 Activate(-1);
699 D_forecv = oldfore;
700 return 0;
703 static int
704 canvas_showwin(lua_State *L)
706 struct canvas *c = check_canvas(L, 1);
707 if (lua_isnil(L, 2))
708 SetCanvasWindow(c, 0);
709 else
711 struct win *w = check_window(L, 2);
712 SetCanvasWindow(c, w);
714 return 0;
717 static const luaL_reg canvas_methods[] = {
718 {"select", canvas_select},
719 {"split", canvas_split},
720 {"showwin", canvas_showwin},
721 {0, 0}
724 static const luaL_reg canvas_metamethods[] = {
725 {"__gc", screen_object_collect},
726 {0, 0}
729 extern struct mchar mchar_so;
730 static int
731 canvas_update_caption(lua_State *L)
733 struct canvas *cv = check_canvas(L, 1);
734 unsigned int len;
735 const char *caption = luaL_checklstring(L, 3, &len);
736 int l, padlen;
737 padlen = cv->c_xe - cv->c_xs +
738 (display ? (cv->c_xe + 1 < D_width || D_CLP): 0);
739 struct win *w = Layer2Window(cv->c_layer);
740 char * buf = MakeWinMsgEv((char *)caption, w, '%', padlen, &cv->c_captev, 0);
741 if (cv->c_captev.timeout.tv_sec)
742 evenq(&cv->c_captev);
743 l = strlen(buf);
745 GotoPos(cv->c_xs, cv->c_ye+1);
746 /*XXX:what does this mean?*/
747 SetRendition(&mchar_so);
748 if (l > cv->c_xe - cv->c_xs + 1)
749 l = cv->c_xe - cv->c_xs + 1;
750 PutWinMsg(buf, cv->c_xs, l);
751 l += cv->c_xs;
752 for (; l <= cv->c_xe; l++)
753 PUTCHARLP(' ');
755 return 0;
758 static const struct Xet_reg canvas_setters[] = {
759 {"caption", 0, 0, canvas_update_caption/*absolute setter*/},
760 {0, 0}
763 static int
764 canvas_get_window(lua_State *L)
766 struct canvas *c = check_canvas(L, 1);
767 struct win *win = Layer2Window(c->c_layer);
768 if (win)
769 push_window(L, &win);
770 else
771 lua_pushnil(L);
772 return 1;
775 static const struct Xet_reg canvas_getters[] = {
776 {"next", get_canvas, offsetof(struct canvas, c_next)},
777 {"xoff", get_int, offsetof(struct canvas, c_xoff)},
778 {"yoff", get_int, offsetof(struct canvas, c_yoff)},
779 {"xs", get_int, offsetof(struct canvas, c_xs)},
780 {"ys", get_int, offsetof(struct canvas, c_ys)},
781 {"xe", get_int, offsetof(struct canvas, c_xe)},
782 {"ye", get_int, offsetof(struct canvas, c_ye)},
783 {"window", 0, 0, canvas_get_window},
784 {"display", get_display, offsetof(struct canvas, c_display)},
785 {0, 0}
788 /** }}} */
790 /** Layout {{{ */
792 PUSH_TYPE(layout, struct layout)
793 CHECK_TYPE(layout, struct layout)
795 static const struct Xet_reg layout_getters[] = {
796 {"title", get_string, offsetof(struct layout, lay_title)},
797 {"number", get_string, offsetof(struct layout, lay_title)},
798 {"autosave", get_string, offsetof(struct layout, lay_autosave)},
799 {0,0}
803 layout_change_title(lua_State *L)
805 struct layout *lay = check_layout(L, 1);
806 unsigned int len;
807 const char *title = luaL_checklstring(L, 3, &len);
808 free(lay->lay_title);
809 lay->lay_title= SaveStr(title);
810 return 0;
813 void LayoutChangeNumber(struct layout *lay, int newnum);
816 layout_change_number(lua_State *L)
818 struct layout *lay = check_layout(L, 1);
819 int newnum = luaL_checkint(L, 3);
820 LayoutChangeNumber(lay, newnum);
821 return 0;
824 static const struct Xet_reg layout_setters[] = {
825 {"title", 0, 0, layout_change_title/*absolute setter*/},
826 {"number", 0, 0, layout_change_number/*absolute setter*/},
827 {"autosave", get_string, offsetof(struct layout, lay_autosave)},
828 {0, 0}
832 layout_select(lua_State *L)
834 struct layout *lay = check_layout(L, 1);
835 if (!display) return 0;
836 LoadLayout(lay, &D_canvas);
837 Activate(0);
838 return 0;
841 static const luaL_reg layout_methods[] = {
842 {"select", layout_select},
843 {0, 0}
846 static const luaL_reg layout_metamethods[] = {
847 {"__gc", screen_object_collect},
848 {0, 0}
851 static int
852 get_layout(lua_State *L, void *v)
854 push_layout(L, (struct layout **)v);
855 return 1;
858 /** }}} */
860 /** Display {{{ */
862 PUSH_TYPE(display, struct display)
864 CHECK_TYPE(display, struct display)
866 static int
867 get_display(lua_State *L, void *v)
869 push_display(L, (struct display **)v);
870 return 1;
873 static int
874 display_get_canvases(lua_State *L)
876 struct display *d;
877 struct canvas *iter;
878 int count;
880 d = check_display(L, 1);
881 lua_newtable(L);
882 for (iter = d->d_cvlist, count = 0; iter; iter = iter->c_next, count++) {
883 lua_pushinteger(L, count);
884 push_canvas(L, &iter);
885 lua_settable(L, -3);
888 return 1;
891 static int
892 display_top_canvas(lua_State *L)
894 struct display *d;
895 d = check_display(L, 1);
896 push_canvas(L, &d->d_cvlist);
898 return 1;
901 static int
902 display_bot_canvas(lua_State *L)
904 struct display *d;
905 struct canvas *c;
906 d = check_display(L, 1);
908 for (c = d->d_cvlist; c->c_next; c = c->c_next)
910 push_canvas(L, &c);
912 return 1;
915 static const luaL_reg display_methods[] = {
916 {"get_canvases", display_get_canvases},
917 {"top_canvas", display_top_canvas},
918 {"bottom_canvas", display_bot_canvas},
919 {0, 0}
922 static int
923 display_tostring(lua_State *L)
925 char str[128];
926 struct display *d = check_display(L, 1);
927 snprintf(str, sizeof(str), "{display: tty = '%s', term = '%s'}", d->d_usertty, d->d_termname);
928 lua_pushstring(L, str);
929 return 1;
932 static const luaL_reg display_metamethods[] = {
933 {"__tostring", display_tostring},
934 {"__gc", screen_object_collect},
935 {0, 0}
938 static int
939 display_new_idle_timeout(lua_State *L)
941 struct display *disp = check_display(L, 1);
942 int timeout = luaL_checkinteger(L, 3) * 1000;
943 struct event *ev = &disp->d_idleev;
944 if (timeout > 0)
946 SetTimeout(ev, timeout);
947 if (!ev->queued)
948 evenq(ev);
950 else
951 evdeq(ev);
953 return 0;
956 static const struct Xet_reg display_setters[] = {
957 {"idle_timeout", 0, 0, display_new_idle_timeout/*absolute setter*/},
958 {0, 0}
961 static const struct Xet_reg display_getters[] = {
962 {"tty", get_string, offsetof(struct display, d_usertty)},
963 {"term", get_string, offsetof(struct display, d_termname)},
964 {"fore", get_window, offsetof(struct display, d_fore)},
965 {"other", get_window, offsetof(struct display, d_other)},
966 {"width", get_int, offsetof(struct display, d_width)},
967 {"height", get_int, offsetof(struct display, d_height)},
968 {"user", get_user, offsetof(struct display, d_user)},
969 {"layout", get_layout, offsetof(struct display, d_layout)},
970 {0, 0}
973 /** }}} */
975 /** Screen {{{ */
977 static int
978 screen_get_windows(lua_State *L)
980 struct win *iter;
981 int count;
983 lua_newtable(L);
984 for (iter = windows, count = 0; iter; iter = iter->w_next, count++) {
985 lua_pushinteger(L, iter->w_number);
986 push_window(L, &iter);
987 lua_settable(L, -3);
990 return 1;
993 static int
994 screen_get_displays(lua_State *L)
996 struct display *iter;
997 int count;
999 lua_newtable(L);
1000 for (iter = displays, count = 0; iter; iter = iter->d_next, count++) {
1001 lua_pushinteger(L, count);
1002 push_display(L, &iter);
1003 lua_settable(L, -3);
1006 return 1;
1009 extern struct layout *layouts;
1010 static int
1011 screen_get_layouts(lua_State *L)
1013 struct layout *iter;
1014 int count;
1016 lua_newtable(L);
1017 for (iter = layouts, count = 0; iter; iter = iter->lay_next, count++) {
1018 lua_pushinteger(L, iter->lay_number);
1019 push_layout(L, &iter);
1020 lua_settable(L, -3);
1023 return 1;
1026 static int
1027 screen_get_display(lua_State *L)
1029 push_display(L, &display);
1030 return 1;
1033 static int
1034 screen_exec_command(lua_State *L)
1036 const char *command;
1037 unsigned int len;
1039 command = luaL_checklstring(L, 1, &len);
1040 if (command)
1041 RcLine((char *)command, len);
1043 return 0;
1046 static int
1047 screen_append_msg(lua_State *L)
1049 const char *msg, *color;
1050 unsigned int len;
1051 msg = luaL_checklstring(L, 1, &len);
1052 if (lua_isnil(L, 2))
1053 color = NULL;
1054 else
1055 color = luaL_checklstring(L, 2, &len);
1056 AppendWinMsgRend(msg, color);
1057 return 0;
1060 struct sinput_data
1062 lua_State *L;
1063 lua_handler lh;
1066 void
1067 script_input_fn(char *buf, int len, char *priv)
1069 struct sinput_data *sidata = (struct sinput_data *)priv;
1070 lua_handler lh = sidata->lh;
1071 lua_State *L = sidata->L;
1073 LuaPushHandler(lh);
1074 lua_pushstring(L, buf);
1075 if (lua_pcall(L, 1, 0, 0) == LUA_ERRRUN)
1077 if(lua_isstring(L, -1))
1079 LuaShowErr(L);
1082 free(sidata);
1083 LuaFreeHandler(L, &lh);
1086 static int
1087 screen_input(lua_State *L)
1089 char *ss;
1090 int n;
1091 const char * prompt = NULL, *prefill = NULL;
1092 lua_handler lh;
1093 struct sinput_data *sidata;
1095 prompt = luaL_checkstring(L, 1);
1096 lh = LuaCheckHandler(L, 2, 1);
1097 if (!lh)
1098 luaL_error(L, "Out of Memory");
1100 if (lua_gettop(L) >= 3)
1101 prefill = luaL_checkstring(L, 3);
1104 sidata = (struct sinput_data *)malloc(sizeof(struct sinput_data));
1105 if (!sidata)
1107 LuaFreeHandler(L, &lh);
1108 luaL_error(L, "Out of Memory");
1111 sidata->L = L;
1112 sidata->lh = lh;
1113 Input((char *)prompt, 100, INP_COOKED, script_input_fn, (char *)sidata, 0);
1115 if (!prefill)
1116 return 0;
1117 for (; *prefill; prefill++)
1119 if ((*(unsigned char *)prefill & 0x7f) < 0x20 || *prefill == 0x7f)
1120 continue;
1121 ss = (char *)prefill;
1122 n = 1;
1123 LayProcess(&ss, &n);
1125 return 0;
1128 static void
1129 sev_schedule_fn(struct event *ev, char *data)
1131 struct sinput_data *si = (struct sinput_data *)data;
1132 lua_handler lh = si->lh;
1133 lua_State *L = si->L;
1134 free(si);
1135 evdeq(ev);
1136 Free(ev);
1138 LuaPushHandler(lh);
1139 if (lua_pcall(L, 1, 0, 0) == LUA_ERRRUN)
1141 if(lua_isstring(L, -1))
1143 LuaShowErr(L);
1146 LuaFreeHandler(L, &lh);
1149 static int
1150 screen_schedule(lua_State *L)
1152 int timeout = luaL_checkinteger(L, 1);
1153 lua_handler lh = LuaCheckHandler(L, 2, 1);
1154 struct sinput_data *si;
1155 struct event *ev;
1156 if (timeout <= 0)
1157 return 0;
1159 ev = (struct event *) calloc(1, sizeof(struct event));
1160 if (!ev)
1162 LuaFreeHandler(L, &lh);
1163 luaL_error(L, "Out of Memory");
1165 si = (struct sinput_data *) malloc(sizeof(struct sinput_data));
1166 if (!si)
1168 LuaFreeHandler(L, &lh);
1169 Free(ev);
1170 luaL_error(L, "Out of Memory");
1172 si->lh = lh;
1173 si->L = L;
1175 ev->type = EV_TIMEOUT;
1176 ev->data = (char *)si;
1177 ev->handler = sev_schedule_fn;
1178 evenq(ev);
1179 SetTimeout(ev, timeout * 1000);
1180 return 0;
1183 static const luaL_reg screen_methods[] = {
1184 {"windows", screen_get_windows},
1185 {"displays", screen_get_displays},
1186 {"layouts", screen_get_layouts},
1187 {"display", screen_get_display},
1188 {"command", screen_exec_command},
1189 {"append_msg", screen_append_msg},
1190 {"hook", LuaRegEvent},
1191 {"input", screen_input},
1192 {"schedule", screen_schedule},
1193 {0, 0}
1196 static const luaL_reg screen_metamethods[] = {
1197 {0, 0}
1200 static const struct Xet_reg screen_setters[] = {
1201 {0, 0}
1204 static const struct Xet_reg screen_getters[] = {
1205 {0, 0}
1208 /** }}} */
1210 /** Public functions {{{ */
1212 /* FIXME: This code only tracks one unhook ticket for a lua func.
1213 * So it does not work if one func is registered more than one times. */
1214 static void
1215 prepare_weak_table(lua_State *L, const char *name, const char *mode)
1217 luaL_getmetatable(L, "screen");
1219 lua_pushstring(L, name);
1220 lua_newtable(L);
1222 /* prepare a metatable to indicate weak table */
1223 lua_newtable(L);
1224 lua_pushstring(L, "__mode");
1225 lua_pushstring(L, mode);
1226 lua_rawset(L, -3);
1227 /* Mark weak table */
1228 lua_setmetatable(L, -2);
1229 lua_rawset(L, -3);
1230 lua_pop(L, 1);
1233 struct sfile {
1234 lua_State *L;
1235 ino_t inode;
1236 struct sfile *next;
1239 struct sfile *scripts = NULL;
1241 int LuaInit(void)
1243 return 0;
1245 lua_State *
1246 LuaNewState(struct sfile *slist)
1248 lua_State *L = luaL_newstate();
1250 luaL_openlibs(L);
1252 #define REGISTER(X) struct_register(L, #X , X ## _methods, X##_metamethods, X##_setters, X##_getters)
1254 REGISTER(screen);
1255 REGISTER(window);
1256 REGISTER(display);
1257 REGISTER(user);
1258 REGISTER(canvas);
1259 REGISTER(callback);
1261 /* To store handler funcs */
1263 /*_two kinds of information are mantained:
1265 * funcreg[key]->func
1266 * The 'func' part of the tables are weak. That means the registered funcs
1267 * will be collected once the func is no longer available (e.g. overwritten
1268 * by a new instance of the script)
1270 * To make this process happens faster, GC is forced at the end of each
1271 * source.
1272 * TODO: What if some events are triggered within the sourcing
1273 * procedure?
1274 * */
1275 prepare_weak_table(L, "_funcreg", " ");
1277 /* funcunhook[func]->listener
1278 * The listener is the unhook ticket of the hook. which should be collected
1279 * once the func is collected. The gc metamethod will be triggered
1280 * accordingly. */
1281 prepare_weak_table(L, "_funcunhook", " ");
1283 /* Hold a reference to the sfile structure to ease unloading the script.*/
1284 luaL_getmetatable(L, "screen");
1285 lua_pushstring(L, "_sfile");
1286 lua_pushlightuserdata(L, slist);
1287 lua_rawset(L, -3);
1288 lua_pop(L, 1);
1289 slist->L = L;
1290 return L;
1293 /* An error message on top of the stack. */
1294 static void
1295 LuaShowErr(lua_State *L)
1297 struct display *d = display;
1298 unsigned int len;
1299 const char *message = luaL_checklstring(L, -1, &len);
1300 lua_pop(L, 1);
1301 LMsg(0, "%s", message ? message : "Unknown error");
1302 display = d;
1305 struct fn_def
1307 void (*push_fn)(lua_State *, void*);
1308 void *value;
1311 static int
1312 LuaCallProcess(const char *name, struct fn_def defs[])
1314 int argc = 0;
1315 lua_State *L;
1316 struct sfile *slist = scripts;
1318 while (slist) {
1319 L = slist->L;
1321 lua_getfield(L, LUA_GLOBALSINDEX, name);
1322 if (lua_isnil(L, -1))
1324 lua_pop(L,1);
1325 slist = slist->next;
1327 else
1328 break;
1331 if (!slist)
1332 return 0;
1334 for (argc = 0; defs[argc].push_fn; argc++)
1335 defs[argc].push_fn(L, defs[argc].value);
1336 if (lua_pcall(L, argc, 0, 0) == LUA_ERRRUN && lua_isstring(L, -1))
1338 LuaShowErr(L);
1339 return 0;
1341 return 1;
1344 void
1345 LuaUnload(struct sfile *slist)
1347 struct sfile **plist = &scripts;
1348 lua_close(slist->L);
1349 while (*plist) {
1350 if (*plist == slist) {
1351 *plist = slist->next;
1352 break;
1354 plist = &(*plist)->next;
1356 free(slist);
1359 /* FIXME: Think about this: will it affect the registered handlers?*/
1360 int LuaSource(const char *file, int async)
1362 struct stat st;
1363 if (stat(file, &st) == -1)
1364 Msg(errno, "Error loading lua script file '%s'", file);
1365 else
1367 int len = strlen(file);
1368 ino_t inode = st.st_ino;
1369 struct sfile *slist = scripts;
1371 if (len < 4 || strncmp(file + len - 4, ".lua", 4) != 0)
1372 return 0;
1374 while (slist) {
1375 if (slist->inode == inode)
1376 break;
1377 slist = slist->next;
1379 if (slist)
1380 LuaUnload(slist);
1382 slist = (struct sfile *) malloc(sizeof(struct sfile));
1383 slist->next = scripts;
1384 LuaNewState(slist);
1385 slist->inode = inode;
1387 if (luaL_dofile(slist->L, file) && lua_isstring(slist->L, -1))
1389 LuaShowErr(slist->L);
1390 lua_close(slist->L);
1391 free(slist);
1392 return 0;
1394 else
1396 /* It seems that I need two GC passes to really collect the unhook
1397 * ticket, after changing the reference to ticket in the
1398 * 'funcunhook' table from weak to strong. This should not be
1399 * harmful, but how can I make sure that two passes is enough?
1401 * Possible reason:
1402 * This seems reasonable, since the first pass will collect the func
1403 * itself and make the ticket garbage, and the second pass will
1404 * collect the ticket itself.
1406 * TODO: check this out. maybe ask some lua gurus. */
1407 lua_gc(slist->L, LUA_GCCOLLECT, 0);
1408 lua_gc(slist->L, LUA_GCCOLLECT, 0);
1409 scripts = slist;
1411 return 1;
1413 return 0;
1416 int LuaFinit(void)
1418 struct sfile *slist = scripts;
1419 while (slist) {
1420 struct sfile *tmp = slist;
1421 lua_close(slist->L);
1422 slist = slist->next;
1423 free(tmp);
1425 scripts = 0;
1426 return 0;
1429 static void
1430 push_stringarray(lua_State *L, char **args)
1432 int i;
1433 lua_newtable(L);
1434 for (i = 1; args && *args; i++) {
1435 lua_pushinteger(L, i);
1436 lua_pushstring(L, *args++);
1437 lua_settable(L, -3);
1442 LuaPushParams(lua_State *L, const char *params, va_list va)
1444 int num = 0;
1445 while (*params)
1447 switch (*params)
1449 case 's':
1450 lua_pushstring(L, va_arg(va, char *));
1451 break;
1452 case 'S':
1453 push_stringarray(L, va_arg(va, char **));
1454 break;
1455 case 'i':
1456 lua_pushinteger(L, va_arg(va, int));
1457 break;
1458 case 'd':
1460 struct display *d = va_arg(va, struct display *);
1461 push_display(L, &d);
1462 break;
1464 case 'w':
1466 struct win *w = va_arg(va, struct win *);
1467 push_window(L, &w);
1468 break;
1470 case 'c':
1472 struct canvas *c = va_arg(va, struct canvas *);
1473 push_canvas(L, &c);
1474 break;
1477 params++;
1478 num++;
1480 return num;
1483 int LuaCall(const char *func, const char **argv)
1485 int argc;
1486 struct sfile *slist = scripts;
1487 lua_State *L = NULL;
1488 while (slist) {
1489 L = slist->L;
1490 lua_getfield(L, LUA_GLOBALSINDEX, func);
1491 if (lua_isnil(L, -1))
1493 lua_pop(L, 1);
1494 slist = slist->next;
1495 return 0;
1497 else
1498 break;
1501 if (!slist) {
1502 if (L) {
1503 lua_pushstring(L, "Could not find the script function\n");
1504 LuaShowErr(L);
1506 return 0;
1508 StackDump(L, "Before LuaCall\n");
1510 for (argc = 0; *argv; argv++, argc++)
1512 lua_pushstring(L, *argv);
1514 if (lua_pcall(L, argc, 0, 0) == LUA_ERRRUN)
1516 if(lua_isstring(L, -1))
1518 StackDump(L, "After LuaCall\n");
1519 LuaShowErr(L);
1520 return 0;
1523 return 1;
1526 /*** Lua callback handler management {{{ */
1529 LuaPushHTable(lua_State *L, int screen, const char * t)
1531 lua_pushstring(L, t);
1532 lua_rawget(L, screen);
1533 /* FIXME: Do we need to balance the stack here? */
1534 if (lua_isnil(L, -1))
1535 luaL_error(L, "Fatal! Fail to get function registeration table!");
1536 return lua_gettop(L);
1539 struct sfile *
1540 LuaGetSFile(lua_State *L)
1542 struct sfile *slist;
1543 luaL_getmetatable(L, "screen");
1544 lua_pushstring(L, "_sfile");
1545 lua_rawget(L, -1);
1546 slist = (struct sfile *)lua_touserdata(L, -1);
1547 lua_pop(L, 2);
1548 return slist;
1551 void
1552 LuaPushHandler(lua_handler lh)
1554 int funcreg;
1555 lua_State *L = lh->L;
1556 if (lh->type == LUA_HANDLER_TYPE_F)
1558 luaL_getmetatable(L, "screen");
1559 funcreg = LuaPushHTable(L, lua_gettop(L), "_funcreg");
1560 lua_rawgeti(L, funcreg, lh->u.reference);
1561 lua_replace(L, -3);
1562 lua_pop(L, 1);
1564 else
1566 lua_getfield(L, LUA_GLOBALSINDEX, lh->u.name);
1571 LuaFuncKey(lua_State *L, int idx, int ref)
1573 int key, funcreg, sc;
1574 luaL_getmetatable(L, "screen");
1575 sc = lua_gettop(L);
1576 funcreg = LuaPushHTable(L, sc, "_funcreg");
1578 lua_pushvalue(L, idx);
1579 key = luaL_ref(L, funcreg);
1580 lua_pop(L, 2);
1581 return key;
1584 void
1585 LuaHUnRef(lua_State *L, int key)
1587 int funcreg, sc;
1588 luaL_getmetatable(L, "screen");
1589 sc = lua_gettop(L);
1590 funcreg = LuaPushHTable(L, sc, "_funcreg");
1591 luaL_unref(L, funcreg, key);
1594 lua_handler
1595 LuaCheckHandler(lua_State *L, int idx, int ref)
1597 int key;
1598 if (idx < 0)
1599 idx = lua_gettop(L) + 1 - idx;
1601 if (lua_isstring(L, idx))
1603 const char * handler;
1604 /* registered with func name.*/
1605 handler = luaL_checkstring(L, idx);
1606 lua_getfield(L, LUA_GLOBALSINDEX, handler);
1607 if (!lua_isfunction(L, -1))
1608 luaL_error(L, "The specified handler %s in param #%d is not a function", handler, idx);
1609 lua_pop(L, 1);
1610 return LuaAllocHandler(L, handler, 0);
1612 else if (!lua_isfunction(L, idx))
1613 luaL_error(L, "Handler should be a function or the name of function");
1615 key = LuaFuncKey(L, idx, ref);
1616 return LuaAllocHandler(L, NULL, key);
1619 /* }}} **/
1621 static int
1622 LuaDispatch(void *handler, const char *params, va_list va)
1624 lua_handler lh = (lua_handler)handler;
1625 int argc, retvalue;
1626 lua_State *L = lh->L;
1628 StackDump(L, "before dispatch");
1630 LuaPushHandler(lh);
1631 if (lua_isnil(L, -1))
1633 lua_pop(L, 1);
1634 return 0;
1636 argc = LuaPushParams(L, params, va);
1638 if (lua_pcall(L, argc, 1, 0) == LUA_ERRRUN && lua_isstring(L, -1))
1640 StackDump(L, "After LuaDispatch\n");
1641 LuaShowErr(L);
1642 return 0;
1644 retvalue = lua_tonumber(L, -1);
1645 lua_pop(L, 1);
1646 return retvalue;
1649 /*FIXME: what if a func is registered twice or more? */
1650 void
1651 LuaRegAutoUnHook(lua_State *L, lua_handler lh, int ticket)
1653 int sc, funcunhook;
1654 luaL_getmetatable(L, "screen");
1655 sc = lua_gettop(L);
1656 funcunhook = LuaPushHTable(L, sc, "_funcunhook");
1657 LuaPushHandler(lh);
1658 lua_pushvalue(L, ticket);
1659 lua_rawset(L, funcunhook);
1660 lua_pop(L, 2);
1663 #define SEVNAME_MAX 30
1664 static int
1665 LuaRegEvent(lua_State *L)
1667 /* signature: hook(obj, event, handler, priv);
1668 * or: hook(event, handler, priv)
1669 * returns: A ticket for later unregister. */
1670 int idx = 1, argc = lua_gettop(L);
1671 unsigned int priv = 31; /* Default privilege */
1672 lua_handler lh;
1674 char *obj = NULL;
1675 const char *objname = "global";
1677 static char evbuf[SEVNAME_MAX];
1678 const char *event;
1680 struct script_event *sev;
1682 StackDump(L, "Before RegEvent\n");
1684 /* Identify the object, if specified */
1685 if (luaL_getmetafield(L, 1, "_objname"))
1687 objname = luaL_checkstring(L, -1);
1688 lua_pop(L, 1);
1689 if (!strcmp("screen", objname))
1690 objname = "global";
1691 else
1693 obj = get_broker_obj((struct broker **)lua_touserdata(L, 1));
1694 if (!obj)
1695 return luaL_error(L, "Invalid object specified");
1697 idx++;
1700 event = luaL_checkstring(L, idx++);
1701 snprintf(evbuf, SEVNAME_MAX, "%s_%s", objname, event);
1703 /* Check and get the handler */
1704 lh = LuaCheckHandler(L, idx++, 1);
1705 if (!lh)
1706 luaL_error(L, "Out of memory");
1708 StackDump(L, "In RegEvent\n");
1710 if (idx <= argc)
1711 priv = luaL_checkinteger(L, idx);
1713 sev = object_get_event(obj, evbuf);
1714 if (sev)
1716 struct listener *l;
1717 int ticket;
1718 l = (struct listener *)malloc(sizeof(struct listener));
1719 if (!l)
1720 return luaL_error(L, "Out of memory");
1721 l->priv = priv;
1722 l->bd = &lua_binding;
1723 l->handler = (void *)lh;
1724 register_listener(sev, l);
1725 /* Return the ticket for un-register */
1726 push_callback(L, &l);
1727 ticket = lua_gettop(L);
1729 LuaRegAutoUnHook(L, lh, ticket);
1731 else
1732 return luaL_error(L, "Invalid event specified: %s for object %s", event, objname);
1734 StackDump(L, "After RegEvent\n");
1735 return 1;
1738 /** }}} */
1740 struct binding lua_binding =
1742 "lua", /*name*/
1743 0, /*inited*/
1744 0, /*registered*/
1745 LuaInit,
1746 LuaFinit,
1747 LuaCall,
1748 LuaSource,
1749 LuaDispatch,
1750 0, /*b_next*/