Unhook the event handler if it causes error.
[screen-lua.git] / src / lua.c
blobaad76ac286ae5591084658cf181fab7d74e7827e
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, int *error, 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 if (L)
140 LuaHUnRef(L, (*lh)->u.reference);
141 (*lh)->u.reference = 0;
143 Free(*lh);
146 struct sfile {
147 lua_State *L;
148 ino_t inode;
149 int inuse;
150 struct sfile *next;
153 struct sfile *scripts = NULL;
155 struct sfile *
156 LuaGetSFile(lua_State *L)
158 struct sfile *slist;
159 luaL_getmetatable(L, "screen");
160 lua_pushstring(L, "_sfile");
161 lua_rawget(L, -2);
162 slist = (struct sfile *)lua_touserdata(L, -1);
163 lua_pop(L, 2);
164 return slist;
167 /** Template {{{ */
169 #define CHECK_TYPE(name, type) \
170 static type * \
171 check_##name(lua_State *L, int index) \
173 struct broker **broker; \
174 type *var; \
175 luaL_checktype(L, index, LUA_TUSERDATA); \
176 broker = (struct broker **) luaL_checkudata(L, index, #name); \
177 if (broker) { \
178 var = (type *)get_broker_obj(broker); \
180 if (!broker || !*broker) \
181 luaL_typerror(L, index, #name); \
182 return var; \
185 #define PUSH_TYPE(name, type) \
186 static void \
187 push_##name(lua_State *L, type **t) \
189 if (!t || !*t) \
190 lua_pushnil(L); \
191 else \
193 struct broker **r; \
194 r = (struct broker **)lua_newuserdata(L, sizeof(struct broker *)); \
195 *r = get_obj_broker(*t); \
196 luaL_getmetatable(L, #name); \
197 lua_setmetatable(L,-2); \
201 /* Much of the following template comes from:
202 * http://lua-users.org/wiki/BindingWithMembersAndMethods
205 static int get_int (lua_State *L, void *v)
207 lua_pushinteger (L, *(int*)v);
208 return 1;
211 static int set_int (lua_State *L, void *v)
213 *(int*)v = luaL_checkint(L, 3);
214 return 0;
217 static int get_number (lua_State *L, void *v)
219 lua_pushnumber(L, *(lua_Number*)v);
220 return 1;
223 static int set_number (lua_State *L, void *v)
225 *(lua_Number*)v = luaL_checknumber(L, 3);
226 return 0;
229 static int get_string (lua_State *L, void *v)
231 lua_pushstring(L, (char*)v );
232 return 1;
235 static int set_string (lua_State *L, void *v)
237 *(const char**)v = luaL_checkstring(L, 3);
238 return 0;
241 typedef int (*Xet_func) (lua_State *L, void *v);
243 /* member info for get and set handlers */
244 struct Xet_reg
246 const char *name; /* member name */
247 Xet_func func; /* get or set function for type of member */
248 size_t offset; /* offset of member within the struct */
249 int (*absolute)(lua_State *);
252 static void Xet_add (lua_State *L, const struct Xet_reg *l)
254 if (!l)
255 return;
256 for (; l->name; l++)
258 lua_pushstring(L, l->name);
259 lua_pushlightuserdata(L, (void*)l);
260 lua_settable(L, -3);
264 static int Xet_call (lua_State *L)
266 /* for get: stack has userdata, index, lightuserdata */
267 /* for set: stack has userdata, index, value, lightuserdata */
268 const struct Xet_reg *m = (const struct Xet_reg *)lua_touserdata(L, -1); /* member info */
269 void *obj;
270 lua_pop(L, 1); /* drop lightuserdata */
271 luaL_checktype(L, 1, LUA_TUSERDATA);
272 if (m->absolute)
273 return m->absolute(L);
274 obj = get_broker_obj((struct broker **)lua_touserdata(L, 1));
275 return m->func(L, (char *)obj + m->offset);
278 static int index_handler (lua_State *L)
280 /* stack has userdata, index */
281 lua_pushvalue(L, 2); /* dup index */
282 lua_rawget(L, lua_upvalueindex(1)); /* lookup member by name */
283 if (!lua_islightuserdata(L, -1))
285 lua_pop(L, 1); /* drop value */
286 lua_pushvalue(L, 2); /* dup index */
287 lua_gettable(L, lua_upvalueindex(2)); /* else try methods */
288 if (lua_isnil(L, -1)) /* invalid member */
289 luaL_error(L, "cannot get member '%s'", lua_tostring(L, 2));
290 return 1;
292 return Xet_call(L); /* call get function */
295 static int newindex_handler (lua_State *L)
297 /* stack has userdata, index, value */
298 lua_pushvalue(L, 2); /* dup index */
299 lua_rawget(L, lua_upvalueindex(1)); /* lookup member by name */
300 if (!lua_islightuserdata(L, -1)) /* invalid member */
301 luaL_error(L, "cannot set member '%s'", lua_tostring(L, 2));
302 return Xet_call(L); /* call set function */
305 static int
306 struct_register(lua_State *L, const char *name, const luaL_reg fn_methods[], const luaL_reg meta_methods[],
307 const struct Xet_reg setters[], const struct Xet_reg getters[])
309 int metatable, methods;
311 /* create methods table & add it to the table of globals */
312 luaL_register(L, name, fn_methods);
313 methods = lua_gettop(L);
315 /* create metatable & add it to the registry */
316 luaL_newmetatable(L, name);
317 luaL_register(L, 0, meta_methods); /* fill metatable */
319 /* To identify the type of object */
320 lua_pushstring(L, "_objname");
321 lua_pushstring(L, name);
322 lua_rawset(L, -3);
324 metatable = lua_gettop(L);
326 lua_pushliteral(L, "__metatable");
327 lua_pushvalue(L, methods); /* dup methods table*/
328 lua_rawset(L, metatable); /* hide metatable:
329 metatable.__metatable = methods */
331 lua_pushliteral(L, "__index");
332 lua_pushvalue(L, metatable); /* upvalue index 1 */
333 Xet_add(L, getters); /* fill metatable with getters */
334 lua_pushvalue(L, methods); /* upvalue index 2 */
335 lua_pushcclosure(L, index_handler, 2);
336 lua_rawset(L, metatable); /* metatable.__index = index_handler */
338 lua_pushliteral(L, "__newindex");
339 lua_newtable(L); /* table for members you can set */
340 Xet_add(L, setters); /* fill with setters */
341 lua_pushcclosure(L, newindex_handler, 1);
342 lua_rawset(L, metatable); /* metatable.__newindex = newindex_handler */
344 /* FIXME: Why do we leave an element on the stack? */
345 lua_pop(L, 1); /* drop metatable */
346 return 1; /* return methods on the stack */
349 /** }}} */
351 /** Callback {{{ */
352 static void
353 push_callback(lua_State *L, struct listener **t)
355 if (!t || !*t)
356 lua_pushnil(L);
357 else
359 struct listener **r;
360 r = (struct listener **)lua_newuserdata(L, sizeof(struct listener *));
361 *r = *t;
362 luaL_getmetatable(L, "callback");
363 lua_setmetatable(L,-2);
368 static int
369 internal_unhook(lua_State *L, int warn)
371 /*Emulate check_callback() */
372 struct listener **ppl;
373 luaL_checktype(L, 1, LUA_TUSERDATA);
374 ppl = (struct listener **) luaL_checkudata(L, 1, "callback");
376 if (!ppl)
377 luaL_typerror(L, 1, "callback");
379 if (!*ppl)
381 if (warn)
383 lua_pushboolean(L, 0);
384 lua_pushstring(L, "Callback already unhooked.");
385 LuaShowErr(L);
388 else
390 LuaFreeHandler(L, (lua_handler *)&(*ppl)->handler);
391 unregister_listener(*ppl, 0);
392 *ppl = 0;
393 if (warn)
394 lua_pushboolean(L, 1);
396 return warn != 0;
398 static int
399 callback_unhook(lua_State *L)
401 return internal_unhook(L, 1);
404 static const luaL_reg callback_methods[] = {
405 {"unhook", callback_unhook},
406 {0, 0}
410 callback_collect(lua_State *L)
412 return internal_unhook(L, 0);
415 static const luaL_reg callback_metamethods[] = {
416 {"__gc", callback_collect},
417 {0, 0}
420 static const struct Xet_reg callback_setters[] = {
421 {0, 0}
424 static const struct Xet_reg callback_getters[] = {
425 {0, 0}
429 /** }}} */
431 static int
432 screen_object_collect(lua_State *L)
434 struct broker **pbroker;
435 luaL_checktype(L, 1, LUA_TUSERDATA);
436 pbroker = (struct broker **)lua_touserdata(L, 1);
437 broker_unref(pbroker);
438 return 0;
441 /** Window {{{ */
443 PUSH_TYPE(window, struct win)
445 CHECK_TYPE(window, struct win)
447 static int get_window(lua_State *L, void *v)
449 push_window(L, (struct win **)v);
450 return 1;
453 static int
454 window_change_title(lua_State *L)
456 struct win *w = check_window(L, 1);
457 unsigned int len;
458 const char *title = luaL_checklstring(L, 3, &len);
459 ChangeAKA(w, (char *)title, len);
460 return 0;
463 static int
464 window_change_number(lua_State *L)
466 struct win *w = check_window(L, 1);
467 int newnum = luaL_checkint(L, 3);
468 ChangeWinNum(w->w_number, newnum);
469 return 0;
472 static int
473 window_get_monitor_status(lua_State *L)
475 struct win *w = check_window(L, 1);
476 int activity = luaL_checkint(L, 2);
477 if (activity)
478 /*monitor*/
479 lua_pushinteger(L, w->w_monitor != MON_OFF);
480 else
481 /*silence*/
482 lua_pushinteger(L, w->w_silence == SILENCE_ON ? w->w_silencewait: 0);
484 return 1;
487 static int
488 window_stuff(lua_State *L)
490 unsigned int len;
491 struct layer *oldflayer = flayer;
492 struct win *w = check_window(L, 1);
493 const char *str = luaL_checklstring(L, 2, &len);
495 flayer = &w->w_layer;
496 while(len)
497 LayProcess((char **)&str, (int *) &len);
498 flayer = oldflayer;
499 return 0;
502 static int
503 window_activate(lua_State *L)
505 struct win *w = check_window(L, 1);
506 SetForeWindow(w);
507 return 0;
510 static void push_canvas(lua_State *L, struct canvas **t);
512 static int
513 window_get_showing_canvases(lua_State *L)
515 struct win *w = check_window(L, 1);
516 int count = 0;
517 struct canvas *cv = w->w_layer.l_cvlist;
518 if (!cv) {
519 lua_pushnil(L);
520 return 1;
522 lua_newtable(L);
523 while (cv) {
524 lua_pushinteger(L, count++);
525 push_canvas(L, &cv);
526 lua_settable(L, -3);
527 cv = cv->c_lnext;
530 return 1;
533 static int
534 window_getlines(lua_State *L)
536 struct win *w = check_window(L, 1);
537 int i;
538 lua_newtable(L);
539 for (i = 0; i < fore->w_height; i++)
541 char *p = (char *)w->w_mlines[i].image;
542 int k, save;
543 for (k = fore->w_width - 1; k >= 0 && p[k] == ' '; k--)
545 k +=(p[k] != ' ');
546 save = p[k];
547 p[k] = 0;
548 lua_pushinteger(L, i);
549 lua_pushstring(L, p);
550 lua_settable(L, -3);
551 p[k] = save;
554 return 1;
557 static int
558 window_gethistory(lua_State *L)
560 struct win *w = check_window(L, 1);
561 int i;
562 lua_newtable(L);
563 for (i = 0; i < fore->w_height; i++)
565 char *p = (char *) w->w_hlines[(w->w_histidx + i) % w->w_histheight].image;
566 int k, save;
567 for (k = fore->w_width - 1; k >= 0 && p[k] == ' '; k--)
569 k +=(p[k] != ' ');
570 save = p[k];
571 p[k] = 0;
572 lua_pushinteger(L, i);
573 lua_pushstring(L, p);
574 lua_settable(L, -3);
575 p[k] = save;
578 return 1;
581 static const luaL_reg window_methods[] = {
582 {"get_monitor_status", window_get_monitor_status},
583 {"showing_canvases", window_get_showing_canvases},
584 {"stuff", window_stuff},
585 {"activate", window_activate},
586 {"get_lines", window_getlines},
587 {"get_history", window_gethistory},
588 {"hook", LuaRegEvent},
589 {0, 0}
592 static int
593 window_tostring(lua_State *L)
595 char str[128];
596 struct win *w = check_window(L, 1);
597 snprintf(str, sizeof(str), "{window #%d: '%s'}", w->w_number, w->w_title);
598 lua_pushstring(L, str);
599 return 1;
602 static int
603 window_equality(lua_State *L)
605 struct win *w1 = check_window(L, 1), *w2 = check_window(L, 2);
606 lua_pushboolean(L, (w1 == w2 || (w1 && w2 && w1->w_number == w2->w_number)));
607 return 1;
610 static const luaL_reg window_metamethods[] = {
611 {"__tostring", window_tostring},
612 {"__eq", window_equality},
613 {"__gc", screen_object_collect},
614 {0, 0}
617 static const struct Xet_reg window_setters[] = {
618 {"title", 0, 0, window_change_title/*absolute setter*/},
619 {"number", 0, 0, window_change_number/*absolute setter*/},
620 {0, 0}
623 static const struct Xet_reg window_getters[] = {
624 {"title", get_string, offsetof(struct win, w_title) + 8},
625 {"number", get_int, offsetof(struct win, w_number)},
626 {"dir", get_string, offsetof(struct win, w_dir)},
627 {"tty", get_string, offsetof(struct win, w_tty)},
628 {"pid", get_int, offsetof(struct win, w_pid)},
629 {"group", get_window, offsetof(struct win, w_group)},
630 {"bell", get_int, offsetof(struct win, w_bell)},
631 {0, 0}
635 /** }}} */
637 /** AclUser {{{ */
639 PUSH_TYPE(user, struct acluser)
641 CHECK_TYPE(user, struct acluser)
643 static int
644 get_user(lua_State *L, void *v)
646 push_user(L, (struct acluser **)v);
647 return 1;
650 static const luaL_reg user_methods[] = {
651 {0, 0}
654 static int
655 user_tostring(lua_State *L)
657 char str[128];
658 struct acluser *u = check_user(L, 1);
659 snprintf(str, sizeof(str), "{user '%s'}", u->u_name);
660 lua_pushstring(L, str);
661 return 1;
664 static const luaL_reg user_metamethods[] = {
665 {"__tostring", user_tostring},
666 {"__gc", screen_object_collect},
667 {0, 0}
670 static const struct Xet_reg user_setters[] = {
671 {0, 0}
674 static const struct Xet_reg user_getters[] = {
675 {"name", get_string, offsetof(struct acluser, u_name)},
676 {"password", get_string, offsetof(struct acluser, u_password)},
677 {0, 0}
680 /** }}} */
682 static int get_display(lua_State *L, void *v);
683 /** Canvas {{{ */
685 PUSH_TYPE(canvas, struct canvas)
687 CHECK_TYPE(canvas, struct canvas)
689 static int
690 get_canvas(lua_State *L, void *v)
692 push_canvas(L, (struct canvas **)v);
693 return 1;
696 static int
697 canvas_select(lua_State *L)
699 struct canvas *c = check_canvas(L, 1);
700 if (!display || D_forecv == c)
701 return 0;
702 /* FIXME: why do we need this? */
703 SetCanvasWindow(c, Layer2Window(c->c_layer));
705 FocusCanvas(c);
706 return 0;
709 static int
710 canvas_split(lua_State *L)
712 struct canvas *c = check_canvas(L, 1);
713 struct canvas *oldfore = D_forecv;
714 D_forecv = c;
715 int hori = lua_toboolean(L, 2);
716 if (hori)
717 AddCanvas(SLICE_HORI);
718 else
719 AddCanvas(SLICE_VERT);
720 Activate(-1);
721 D_forecv = oldfore;
722 return 0;
725 static int
726 canvas_showwin(lua_State *L)
728 struct canvas *c = check_canvas(L, 1);
729 if (lua_isnil(L, 2))
730 SetCanvasWindow(c, 0);
731 else
733 struct win *w = check_window(L, 2);
734 SetCanvasWindow(c, w);
736 return 0;
739 static const luaL_reg canvas_methods[] = {
740 {"select", canvas_select},
741 {"split", canvas_split},
742 {"showwin", canvas_showwin},
743 {0, 0}
746 static const luaL_reg canvas_metamethods[] = {
747 {"__gc", screen_object_collect},
748 {0, 0}
751 extern struct mchar mchar_so;
752 static int
753 canvas_update_caption(lua_State *L)
755 struct canvas *cv = check_canvas(L, 1);
756 unsigned int len;
757 const char *caption = luaL_checklstring(L, 3, &len);
758 int l, padlen;
759 padlen = cv->c_xe - cv->c_xs +
760 (display ? (cv->c_xe + 1 < D_width || D_CLP): 0);
761 struct win *w = Layer2Window(cv->c_layer);
762 char * buf = MakeWinMsgEv((char *)caption, w, '%', padlen, &cv->c_captev, 0);
763 if (cv->c_captev.timeout.tv_sec)
764 evenq(&cv->c_captev);
765 l = strlen(buf);
767 GotoPos(cv->c_xs, cv->c_ye+1);
768 /*XXX:what does this mean?*/
769 SetRendition(&mchar_so);
770 if (l > cv->c_xe - cv->c_xs + 1)
771 l = cv->c_xe - cv->c_xs + 1;
772 PutWinMsg(buf, cv->c_xs, l);
773 l += cv->c_xs;
774 for (; l <= cv->c_xe; l++)
775 PUTCHARLP(' ');
777 return 0;
780 static const struct Xet_reg canvas_setters[] = {
781 {"caption", 0, 0, canvas_update_caption/*absolute setter*/},
782 {0, 0}
785 static int
786 canvas_get_window(lua_State *L)
788 struct canvas *c = check_canvas(L, 1);
789 struct win *win = Layer2Window(c->c_layer);
790 if (win)
791 push_window(L, &win);
792 else
793 lua_pushnil(L);
794 return 1;
797 static const struct Xet_reg canvas_getters[] = {
798 {"next", get_canvas, offsetof(struct canvas, c_next)},
799 {"xoff", get_int, offsetof(struct canvas, c_xoff)},
800 {"yoff", get_int, offsetof(struct canvas, c_yoff)},
801 {"xs", get_int, offsetof(struct canvas, c_xs)},
802 {"ys", get_int, offsetof(struct canvas, c_ys)},
803 {"xe", get_int, offsetof(struct canvas, c_xe)},
804 {"ye", get_int, offsetof(struct canvas, c_ye)},
805 {"window", 0, 0, canvas_get_window},
806 {"display", get_display, offsetof(struct canvas, c_display)},
807 {0, 0}
810 /** }}} */
812 /** Layout {{{ */
814 PUSH_TYPE(layout, struct layout)
815 CHECK_TYPE(layout, struct layout)
817 static const struct Xet_reg layout_getters[] = {
818 {"title", get_string, offsetof(struct layout, lay_title)},
819 {"number", get_string, offsetof(struct layout, lay_title)},
820 {"autosave", get_string, offsetof(struct layout, lay_autosave)},
821 {0,0}
825 layout_change_title(lua_State *L)
827 struct layout *lay = check_layout(L, 1);
828 unsigned int len;
829 const char *title = luaL_checklstring(L, 3, &len);
830 free(lay->lay_title);
831 lay->lay_title= SaveStr(title);
832 return 0;
835 void LayoutChangeNumber(struct layout *lay, int newnum);
838 layout_change_number(lua_State *L)
840 struct layout *lay = check_layout(L, 1);
841 int newnum = luaL_checkint(L, 3);
842 LayoutChangeNumber(lay, newnum);
843 return 0;
846 static const struct Xet_reg layout_setters[] = {
847 {"title", 0, 0, layout_change_title/*absolute setter*/},
848 {"number", 0, 0, layout_change_number/*absolute setter*/},
849 {"autosave", get_string, offsetof(struct layout, lay_autosave)},
850 {0, 0}
854 layout_select(lua_State *L)
856 struct layout *lay = check_layout(L, 1);
857 if (!display) return 0;
858 LoadLayout(lay, &D_canvas);
859 Activate(0);
860 return 0;
863 static const luaL_reg layout_methods[] = {
864 {"select", layout_select},
865 {0, 0}
868 static const luaL_reg layout_metamethods[] = {
869 {"__gc", screen_object_collect},
870 {0, 0}
873 static int
874 get_layout(lua_State *L, void *v)
876 push_layout(L, (struct layout **)v);
877 return 1;
880 /** }}} */
882 /** Display {{{ */
884 PUSH_TYPE(display, struct display)
886 CHECK_TYPE(display, struct display)
888 static int
889 get_display(lua_State *L, void *v)
891 push_display(L, (struct display **)v);
892 return 1;
895 static int
896 display_get_canvases(lua_State *L)
898 struct display *d;
899 struct canvas *iter;
900 int count;
902 d = check_display(L, 1);
903 lua_newtable(L);
904 for (iter = d->d_cvlist, count = 0; iter; iter = iter->c_next, count++) {
905 lua_pushinteger(L, count);
906 push_canvas(L, &iter);
907 lua_settable(L, -3);
910 return 1;
913 static int
914 display_top_canvas(lua_State *L)
916 struct display *d;
917 d = check_display(L, 1);
918 push_canvas(L, &d->d_cvlist);
920 return 1;
923 static int
924 display_bot_canvas(lua_State *L)
926 struct display *d;
927 struct canvas *c;
928 d = check_display(L, 1);
930 for (c = d->d_cvlist; c->c_next; c = c->c_next)
932 push_canvas(L, &c);
934 return 1;
937 static const luaL_reg display_methods[] = {
938 {"get_canvases", display_get_canvases},
939 {"top_canvas", display_top_canvas},
940 {"bottom_canvas", display_bot_canvas},
941 {0, 0}
944 static int
945 display_tostring(lua_State *L)
947 char str[128];
948 struct display *d = check_display(L, 1);
949 snprintf(str, sizeof(str), "{display: tty = '%s', term = '%s'}", d->d_usertty, d->d_termname);
950 lua_pushstring(L, str);
951 return 1;
954 static const luaL_reg display_metamethods[] = {
955 {"__tostring", display_tostring},
956 {"__gc", screen_object_collect},
957 {0, 0}
960 static int
961 display_new_idle_timeout(lua_State *L)
963 struct display *disp = check_display(L, 1);
964 int timeout = luaL_checkinteger(L, 3) * 1000;
965 struct event *ev = &disp->d_idleev;
966 if (timeout > 0)
968 SetTimeout(ev, timeout);
969 if (!ev->queued)
970 evenq(ev);
972 else
973 evdeq(ev);
975 return 0;
978 static const struct Xet_reg display_setters[] = {
979 {"idle_timeout", 0, 0, display_new_idle_timeout/*absolute setter*/},
980 {0, 0}
983 static const struct Xet_reg display_getters[] = {
984 {"tty", get_string, offsetof(struct display, d_usertty)},
985 {"term", get_string, offsetof(struct display, d_termname)},
986 {"fore", get_window, offsetof(struct display, d_fore)},
987 {"other", get_window, offsetof(struct display, d_other)},
988 {"width", get_int, offsetof(struct display, d_width)},
989 {"height", get_int, offsetof(struct display, d_height)},
990 {"user", get_user, offsetof(struct display, d_user)},
991 {"layout", get_layout, offsetof(struct display, d_layout)},
992 {0, 0}
995 /** }}} */
997 /** Screen {{{ */
999 extern struct win *wtab[];
1001 static int
1002 screen_get_windows(lua_State *L)
1004 struct win **iter = wtab;
1005 int count, i;
1007 lua_newtable(L);
1008 i = 1;
1009 for (count = 0; count < MAXWIN; count++)
1011 if (!*iter) {
1012 iter++;
1013 continue;
1015 lua_pushinteger(L, i++);
1016 push_window(L, iter);
1017 lua_settable(L, -3);
1018 iter++;
1021 return 1;
1024 static int
1025 screen_get_displays(lua_State *L)
1027 struct display *iter;
1028 int count;
1030 lua_newtable(L);
1031 for (iter = displays, count = 0; iter; iter = iter->d_next, count++) {
1032 lua_pushinteger(L, count);
1033 push_display(L, &iter);
1034 lua_settable(L, -3);
1037 return 1;
1040 extern struct layout *layouts;
1041 static int
1042 screen_get_layouts(lua_State *L)
1044 struct layout *iter;
1045 int count;
1047 lua_newtable(L);
1048 for (iter = layouts, count = 0; iter; iter = iter->lay_next, count++) {
1049 lua_pushinteger(L, iter->lay_number);
1050 push_layout(L, &iter);
1051 lua_settable(L, -3);
1054 return 1;
1057 static int
1058 screen_get_display(lua_State *L)
1060 push_display(L, &display);
1061 return 1;
1064 static int
1065 screen_exec_command(lua_State *L)
1067 const char *command;
1068 unsigned int len;
1070 command = luaL_checklstring(L, 1, &len);
1071 if (command)
1072 RcLine((char *)command, len);
1074 return 0;
1077 static int
1078 screen_append_msg(lua_State *L)
1080 const char *msg, *color;
1081 unsigned int len;
1082 msg = luaL_checklstring(L, 1, &len);
1083 if (lua_isnil(L, 2))
1084 color = NULL;
1085 else
1086 color = luaL_checklstring(L, 2, &len);
1087 AppendWinMsgRend(msg, color);
1088 return 0;
1091 void
1092 script_input_fn(char *buf, int len, char *priv)
1094 lua_handler lh = (lua_handler)priv;
1095 struct sfile *sf = (struct sfile *)lh->L;
1096 lua_State *L = sf->L;
1097 if (!L) {
1098 free(sf);
1099 LuaFreeHandler(L, &lh);
1100 return;
1103 lh->L = L;
1104 LuaPushHandler(lh);
1105 lua_pushstring(L, buf);
1106 if (lua_pcall(L, 1, 0, 0) == LUA_ERRRUN)
1108 if(lua_isstring(L, -1))
1110 LuaShowErr(L);
1113 sf->inuse = 0;
1114 LuaFreeHandler(L, &lh);
1117 static int
1118 screen_input(lua_State *L)
1120 char *ss;
1121 int n;
1122 const char * prompt = NULL, *prefill = NULL;
1123 lua_handler lh;
1124 struct sfile *sf = LuaGetSFile(L);
1126 prompt = luaL_checkstring(L, 1);
1127 lh = LuaCheckHandler(L, 2, 1);
1128 /* Hack! This is used to prevent from accessing unloaded script.*/
1129 lh->L = (lua_State *)sf;
1130 if (!lh)
1131 luaL_error(L, "Out of Memory");
1133 if (lua_gettop(L) >= 3)
1134 prefill = luaL_checkstring(L, 3);
1137 sf->inuse = 1;
1138 Input((char *)prompt, 100, INP_COOKED, script_input_fn, (char *)lh, 0);
1140 if (!prefill)
1141 return 0;
1142 for (; *prefill; prefill++)
1144 if ((*(unsigned char *)prefill & 0x7f) < 0x20 || *prefill == 0x7f)
1145 continue;
1146 ss = (char *)prefill;
1147 n = 1;
1148 LayProcess(&ss, &n);
1150 return 0;
1153 static void
1154 sev_schedule_fn(struct event *ev, char *data)
1156 lua_handler lh = (lua_handler)data;
1157 struct sfile *sf = (struct sfile *)lh->L;
1158 lua_State *L = sf->L;
1159 if (!L) {
1160 free(sf);
1161 LuaFreeHandler(L, &lh);
1162 return;
1165 evdeq(ev);
1166 Free(ev);
1168 lh->L = L;
1169 LuaPushHandler(lh);
1170 if (lua_pcall(L, 1, 0, 0) == LUA_ERRRUN)
1172 if(lua_isstring(L, -1))
1174 LuaShowErr(L);
1177 sf->inuse = 0;
1178 LuaFreeHandler(L, &lh);
1181 static int
1182 screen_schedule(lua_State *L)
1184 int timeout = luaL_checkinteger(L, 1);
1185 lua_handler lh;
1186 struct sfile *sf = LuaGetSFile(L);
1187 struct event *ev;
1188 if (timeout <= 0)
1189 return 0;
1190 lh = LuaCheckHandler(L, 2, 1);
1191 lh->L = (lua_State *)sf;
1193 ev = (struct event *) calloc(1, sizeof(struct event));
1194 if (!ev)
1196 LuaFreeHandler(L, &lh);
1197 luaL_error(L, "Out of Memory");
1200 ev->type = EV_TIMEOUT;
1201 ev->data = (char *)lh;
1202 ev->handler = sev_schedule_fn;
1203 evenq(ev);
1204 SetTimeout(ev, timeout * 1000);
1205 sf->inuse = 1;
1206 return 0;
1209 static const luaL_reg screen_methods[] = {
1210 {"windows", screen_get_windows},
1211 {"displays", screen_get_displays},
1212 {"layouts", screen_get_layouts},
1213 {"display", screen_get_display},
1214 {"command", screen_exec_command},
1215 {"append_msg", screen_append_msg},
1216 {"hook", LuaRegEvent},
1217 {"input", screen_input},
1218 {"schedule", screen_schedule},
1219 {0, 0}
1222 static const luaL_reg screen_metamethods[] = {
1223 {0, 0}
1226 static const struct Xet_reg screen_setters[] = {
1227 {0, 0}
1230 static const struct Xet_reg screen_getters[] = {
1231 {0, 0}
1234 /** }}} */
1236 /** Public functions {{{ */
1238 /* FIXME: This code only tracks one unhook ticket for a lua func.
1239 * So it does not work if one func is registered more than one times. */
1240 static void
1241 prepare_weak_table(lua_State *L, const char *name, const char *mode)
1243 luaL_getmetatable(L, "screen");
1245 lua_pushstring(L, name);
1246 lua_newtable(L);
1248 /* prepare a metatable to indicate weak table */
1249 lua_newtable(L);
1250 lua_pushstring(L, "__mode");
1251 lua_pushstring(L, mode);
1252 lua_rawset(L, -3);
1253 /* Mark weak table */
1254 lua_setmetatable(L, -2);
1255 lua_rawset(L, -3);
1256 lua_pop(L, 1);
1259 int LuaInit(void)
1261 return 0;
1263 lua_State *
1264 LuaNewState(struct sfile *slist)
1266 lua_State *L = luaL_newstate();
1268 luaL_openlibs(L);
1270 #define REGISTER(X) struct_register(L, #X , X ## _methods, X##_metamethods, X##_setters, X##_getters)
1272 REGISTER(screen);
1273 REGISTER(window);
1274 REGISTER(display);
1275 REGISTER(user);
1276 REGISTER(canvas);
1277 REGISTER(callback);
1279 /* To store handler funcs */
1282 * funcreg[key]->func
1283 * */
1284 prepare_weak_table(L, "_funcreg", " ");
1286 /* Hold a reference to the sfile structure to ease unloading the script.*/
1287 luaL_getmetatable(L, "screen");
1288 lua_pushstring(L, "_sfile");
1289 lua_pushlightuserdata(L, slist);
1290 lua_rawset(L, -3);
1291 lua_pop(L, 1);
1292 slist->L = L;
1293 slist->inuse = 0;
1294 return L;
1297 /* An error message on top of the stack. */
1298 static void
1299 LuaShowErr(lua_State *L)
1301 struct display *d = display;
1302 unsigned int len;
1303 const char *message = luaL_checklstring(L, -1, &len);
1304 lua_pop(L, 1);
1305 LMsg(0, "%s", message ? message : "Unknown error");
1306 display = d;
1309 void
1310 LuaUnload(struct sfile *slist)
1312 struct sfile **plist = &scripts;
1313 lua_close(slist->L);
1314 while (*plist) {
1315 if (*plist == slist) {
1316 *plist = slist->next;
1317 break;
1319 plist = &(*plist)->next;
1322 //Delay reclaiming the structure if it's still in use.
1323 if (!slist->inuse)
1324 free(slist);
1325 else
1326 slist->L = NULL;
1329 /* FIXME: Think about this: will it affect the registered handlers?*/
1330 int LuaSource(const char *file, int async)
1332 struct stat st;
1333 if (stat(file, &st) == -1)
1334 Msg(errno, "Error loading lua script file '%s'", file);
1335 else
1337 int len = strlen(file);
1338 ino_t inode = st.st_ino;
1339 struct sfile *slist = scripts;
1341 if (len < 4 || strncmp(file + len - 4, ".lua", 4) != 0)
1342 return 0;
1344 while (slist) {
1345 if (slist->inode == inode)
1346 break;
1347 slist = slist->next;
1349 if (slist)
1350 LuaUnload(slist);
1352 slist = (struct sfile *) malloc(sizeof(struct sfile));
1353 slist->next = scripts;
1354 LuaNewState(slist);
1355 slist->inode = inode;
1357 if (luaL_dofile(slist->L, file) && lua_isstring(slist->L, -1))
1359 LuaShowErr(slist->L);
1360 lua_close(slist->L);
1361 free(slist);
1362 return 0;
1364 scripts = slist;
1365 return 1;
1367 return 0;
1370 int LuaFinit(void)
1372 struct sfile *slist = scripts;
1373 while (slist) {
1374 struct sfile *tmp = slist;
1375 lua_close(slist->L);
1376 slist = slist->next;
1377 free(tmp);
1379 scripts = 0;
1380 return 0;
1383 static void
1384 push_stringarray(lua_State *L, char **args)
1386 int i;
1387 lua_newtable(L);
1388 for (i = 1; args && *args; i++) {
1389 lua_pushinteger(L, i);
1390 lua_pushstring(L, *args++);
1391 lua_settable(L, -3);
1396 LuaPushParams(lua_State *L, const char *params, va_list va)
1398 int num = 0;
1399 while (*params)
1401 switch (*params)
1403 case 's':
1404 lua_pushstring(L, va_arg(va, char *));
1405 break;
1406 case 'S':
1407 push_stringarray(L, va_arg(va, char **));
1408 break;
1409 case 'i':
1410 lua_pushinteger(L, va_arg(va, int));
1411 break;
1412 case 'd':
1414 struct display *d = va_arg(va, struct display *);
1415 push_display(L, &d);
1416 break;
1418 case 'w':
1420 struct win *w = va_arg(va, struct win *);
1421 push_window(L, &w);
1422 break;
1424 case 'c':
1426 struct canvas *c = va_arg(va, struct canvas *);
1427 push_canvas(L, &c);
1428 break;
1431 params++;
1432 num++;
1434 return num;
1437 int LuaCall(const char *func, const char **argv)
1439 int argc;
1440 struct sfile *slist = scripts;
1441 lua_State *L = NULL;
1442 while (slist) {
1443 L = slist->L;
1444 lua_getfield(L, LUA_GLOBALSINDEX, func);
1445 if (lua_isnil(L, -1))
1447 lua_pop(L, 1);
1448 slist = slist->next;
1449 return 0;
1451 else
1452 break;
1455 if (!slist) {
1456 if (L) {
1457 lua_pushstring(L, "Could not find the script function\n");
1458 LuaShowErr(L);
1460 return 0;
1462 StackDump(L, "Before LuaCall\n");
1464 for (argc = 0; *argv; argv++, argc++)
1466 lua_pushstring(L, *argv);
1468 if (lua_pcall(L, argc, 0, 0) == LUA_ERRRUN)
1470 if(lua_isstring(L, -1))
1472 StackDump(L, "After LuaCall\n");
1473 LuaShowErr(L);
1474 return 0;
1477 return 1;
1480 /*** Lua callback handler management {{{ */
1483 LuaPushHTable(lua_State *L, int screen, const char * t)
1485 lua_pushstring(L, t);
1486 lua_rawget(L, screen);
1487 /* FIXME: Do we need to balance the stack here? */
1488 if (lua_isnil(L, -1))
1489 luaL_error(L, "Fatal! Fail to get function registeration table!");
1490 return lua_gettop(L);
1493 void
1494 LuaPushHandler(lua_handler lh)
1496 int funcreg;
1497 lua_State *L = lh->L;
1498 if (lh->type == LUA_HANDLER_TYPE_F)
1500 luaL_getmetatable(L, "screen");
1501 funcreg = LuaPushHTable(L, lua_gettop(L), "_funcreg");
1502 lua_rawgeti(L, funcreg, lh->u.reference);
1503 lua_replace(L, -3);
1504 lua_pop(L, 1);
1506 else
1508 lua_getfield(L, LUA_GLOBALSINDEX, lh->u.name);
1513 LuaFuncKey(lua_State *L, int idx, int ref)
1515 int key, funcreg, sc;
1516 luaL_getmetatable(L, "screen");
1517 sc = lua_gettop(L);
1518 funcreg = LuaPushHTable(L, sc, "_funcreg");
1520 lua_pushvalue(L, idx);
1521 key = luaL_ref(L, funcreg);
1522 lua_pop(L, 2);
1523 return key;
1526 void
1527 LuaHUnRef(lua_State *L, int key)
1529 int funcreg, sc;
1530 luaL_getmetatable(L, "screen");
1531 sc = lua_gettop(L);
1532 funcreg = LuaPushHTable(L, sc, "_funcreg");
1533 luaL_unref(L, funcreg, key);
1536 lua_handler
1537 LuaCheckHandler(lua_State *L, int idx, int ref)
1539 int key;
1540 if (idx < 0)
1541 idx = lua_gettop(L) + 1 - idx;
1543 if (lua_isstring(L, idx))
1545 const char * handler;
1546 /* registered with func name.*/
1547 handler = luaL_checkstring(L, idx);
1548 lua_getfield(L, LUA_GLOBALSINDEX, handler);
1549 if (!lua_isfunction(L, -1))
1550 luaL_error(L, "The specified handler %s in param #%d is not a function", handler, idx);
1551 lua_pop(L, 1);
1552 return LuaAllocHandler(L, handler, 0);
1554 else if (!lua_isfunction(L, idx))
1555 luaL_error(L, "Handler should be a function or the name of function");
1557 key = LuaFuncKey(L, idx, ref);
1558 return LuaAllocHandler(L, NULL, key);
1561 /* }}} **/
1563 static int
1564 LuaDispatch(void *handler, int *error, const char *params, va_list va)
1566 lua_handler lh = (lua_handler)handler;
1567 int argc, retvalue;
1568 lua_State *L = lh->L;
1570 StackDump(L, "before dispatch");
1572 LuaPushHandler(lh);
1573 if (lua_isnil(L, -1))
1575 lua_pop(L, 1);
1576 return 0;
1578 argc = LuaPushParams(L, params, va);
1580 if (lua_pcall(L, argc, 1, 0) == LUA_ERRRUN && lua_isstring(L, -1))
1582 StackDump(L, "After LuaDispatch\n");
1583 LuaShowErr(L);
1584 *error = 1;
1585 return 0;
1587 retvalue = lua_tonumber(L, -1);
1588 lua_pop(L, 1);
1589 *error = 0;
1590 return retvalue;
1593 #define SEVNAME_MAX 30
1594 static int
1595 LuaRegEvent(lua_State *L)
1597 /* signature: hook(obj, event, handler, priv);
1598 * or: hook(event, handler, priv)
1599 * returns: A ticket for later unregister. */
1600 int idx = 1, argc = lua_gettop(L);
1601 unsigned int priv = 31; /* Default privilege */
1602 lua_handler lh;
1604 char *obj = NULL;
1605 const char *objname = "global";
1607 static char evbuf[SEVNAME_MAX];
1608 const char *event;
1610 struct script_event *sev;
1612 StackDump(L, "Before RegEvent\n");
1614 /* Identify the object, if specified */
1615 if (luaL_getmetafield(L, 1, "_objname"))
1617 objname = luaL_checkstring(L, -1);
1618 lua_pop(L, 1);
1619 if (!strcmp("screen", objname))
1620 objname = "global";
1621 else
1623 obj = get_broker_obj((struct broker **)lua_touserdata(L, 1));
1624 if (!obj)
1625 return luaL_error(L, "Invalid object specified");
1627 idx++;
1630 event = luaL_checkstring(L, idx++);
1631 snprintf(evbuf, SEVNAME_MAX, "%s_%s", objname, event);
1633 /* Check and get the handler */
1634 lh = LuaCheckHandler(L, idx++, 1);
1635 if (!lh)
1636 luaL_error(L, "Out of memory");
1638 StackDump(L, "In RegEvent\n");
1640 if (idx <= argc)
1641 priv = luaL_checkinteger(L, idx);
1643 sev = object_get_event(obj, evbuf);
1644 if (sev)
1646 struct listener *l;
1647 l = (struct listener *)malloc(sizeof(struct listener));
1648 if (!l)
1649 return luaL_error(L, "Out of memory");
1650 l->priv = priv;
1651 l->bd = &lua_binding;
1652 l->handler = (void *)lh;
1653 register_listener(sev, l);
1654 /* Return the ticket for un-register */
1655 push_callback(L, &l);
1657 else
1658 return luaL_error(L, "Invalid event specified: %s for object %s", event, objname);
1660 StackDump(L, "After RegEvent\n");
1661 return 1;
1664 /** }}} */
1666 struct binding lua_binding =
1668 "lua", /*name*/
1669 0, /*inited*/
1670 0, /*registered*/
1671 LuaInit,
1672 LuaFinit,
1673 LuaCall,
1674 LuaSource,
1675 LuaDispatch,
1676 0, /*b_next*/