3539cdae272b95c3cf132f92cef74f08ba750c89
[screen-lua.git] / src / lua.c
blob3539cdae272b95c3cf132f92cef74f08ba750c89
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 union
99 const char *name;
100 int reference;
101 } u;
104 typedef struct lua_handler *lua_handler;
105 void LuaPushHandler(lua_State *L, lua_handler lh);
106 void LuaHUnRef(lua_State *L, int key);
107 lua_handler LuaCheckHandler(lua_State *L, int idx, int ref);
109 lua_handler
110 LuaAllocHandler(const char *name, int ref)
112 struct lua_handler *lh;
113 lh = (struct lua_handler*) malloc(sizeof(struct lua_handler));
114 if (!lh)
115 return NULL;
117 if (name)
119 lh->type = LUA_HANDLER_TYPE_N;
120 lh->u.name = SaveStr(name);
122 else
124 lh->type = LUA_HANDLER_TYPE_F;
125 lh->u.reference = ref;
128 return lh;
131 void
132 LuaFreeHandler(lua_State *L, struct lua_handler **lh)
134 if ((*lh)->type == LUA_HANDLER_TYPE_N)
135 Free((*lh)->u.name)
136 else
138 LuaHUnRef(L, (*lh)->u.reference);
139 (*lh)->u.reference = 0;
141 Free(*lh);
143 /** Template {{{ */
145 #define CHECK_TYPE(name, type) \
146 static type * \
147 check_##name(lua_State *L, int index) \
149 struct broker **broker; \
150 type *var; \
151 luaL_checktype(L, index, LUA_TUSERDATA); \
152 broker = (struct broker **) luaL_checkudata(L, index, #name); \
153 if (broker) { \
154 var = (type *)get_broker_obj(broker); \
156 if (!broker || !*broker) \
157 luaL_typerror(L, index, #name); \
158 return var; \
161 #define PUSH_TYPE(name, type) \
162 static void \
163 push_##name(lua_State *L, type **t) \
165 if (!t || !*t) \
166 lua_pushnil(L); \
167 else \
169 struct broker **r; \
170 r = (struct broker **)lua_newuserdata(L, sizeof(struct broker *)); \
171 *r = get_obj_broker(*t); \
172 luaL_getmetatable(L, #name); \
173 lua_setmetatable(L,-2); \
177 /* Much of the following template comes from:
178 * http://lua-users.org/wiki/BindingWithMembersAndMethods
181 static int get_int (lua_State *L, void *v)
183 lua_pushinteger (L, *(int*)v);
184 return 1;
187 static int set_int (lua_State *L, void *v)
189 *(int*)v = luaL_checkint(L, 3);
190 return 0;
193 static int get_number (lua_State *L, void *v)
195 lua_pushnumber(L, *(lua_Number*)v);
196 return 1;
199 static int set_number (lua_State *L, void *v)
201 *(lua_Number*)v = luaL_checknumber(L, 3);
202 return 0;
205 static int get_string (lua_State *L, void *v)
207 lua_pushstring(L, (char*)v );
208 return 1;
211 static int set_string (lua_State *L, void *v)
213 *(const char**)v = luaL_checkstring(L, 3);
214 return 0;
217 typedef int (*Xet_func) (lua_State *L, void *v);
219 /* member info for get and set handlers */
220 struct Xet_reg
222 const char *name; /* member name */
223 Xet_func func; /* get or set function for type of member */
224 size_t offset; /* offset of member within the struct */
225 int (*absolute)(lua_State *);
228 static void Xet_add (lua_State *L, const struct Xet_reg *l)
230 if (!l)
231 return;
232 for (; l->name; l++)
234 lua_pushstring(L, l->name);
235 lua_pushlightuserdata(L, (void*)l);
236 lua_settable(L, -3);
240 static int Xet_call (lua_State *L)
242 /* for get: stack has userdata, index, lightuserdata */
243 /* for set: stack has userdata, index, value, lightuserdata */
244 const struct Xet_reg *m = (const struct Xet_reg *)lua_touserdata(L, -1); /* member info */
245 void *obj;
246 lua_pop(L, 1); /* drop lightuserdata */
247 luaL_checktype(L, 1, LUA_TUSERDATA);
248 if (m->absolute)
249 return m->absolute(L);
250 obj = get_broker_obj((struct broker **)lua_touserdata(L, 1));
251 return m->func(L, (char *)obj + m->offset);
254 static int index_handler (lua_State *L)
256 /* stack has userdata, index */
257 lua_pushvalue(L, 2); /* dup index */
258 lua_rawget(L, lua_upvalueindex(1)); /* lookup member by name */
259 if (!lua_islightuserdata(L, -1))
261 lua_pop(L, 1); /* drop value */
262 lua_pushvalue(L, 2); /* dup index */
263 lua_gettable(L, lua_upvalueindex(2)); /* else try methods */
264 if (lua_isnil(L, -1)) /* invalid member */
265 luaL_error(L, "cannot get member '%s'", lua_tostring(L, 2));
266 return 1;
268 return Xet_call(L); /* call get function */
271 static int newindex_handler (lua_State *L)
273 /* stack has userdata, index, value */
274 lua_pushvalue(L, 2); /* dup index */
275 lua_rawget(L, lua_upvalueindex(1)); /* lookup member by name */
276 if (!lua_islightuserdata(L, -1)) /* invalid member */
277 luaL_error(L, "cannot set member '%s'", lua_tostring(L, 2));
278 return Xet_call(L); /* call set function */
281 static int
282 struct_register(lua_State *L, const char *name, const luaL_reg fn_methods[], const luaL_reg meta_methods[],
283 const struct Xet_reg setters[], const struct Xet_reg getters[])
285 int metatable, methods;
287 /* create methods table & add it to the table of globals */
288 luaL_register(L, name, fn_methods);
289 methods = lua_gettop(L);
291 /* create metatable & add it to the registry */
292 luaL_newmetatable(L, name);
293 luaL_register(L, 0, meta_methods); /* fill metatable */
295 /* To identify the type of object */
296 lua_pushstring(L, "_objname");
297 lua_pushstring(L, name);
298 lua_rawset(L, -3);
300 metatable = lua_gettop(L);
302 lua_pushliteral(L, "__metatable");
303 lua_pushvalue(L, methods); /* dup methods table*/
304 lua_rawset(L, metatable); /* hide metatable:
305 metatable.__metatable = methods */
307 lua_pushliteral(L, "__index");
308 lua_pushvalue(L, metatable); /* upvalue index 1 */
309 Xet_add(L, getters); /* fill metatable with getters */
310 lua_pushvalue(L, methods); /* upvalue index 2 */
311 lua_pushcclosure(L, index_handler, 2);
312 lua_rawset(L, metatable); /* metatable.__index = index_handler */
314 lua_pushliteral(L, "__newindex");
315 lua_newtable(L); /* table for members you can set */
316 Xet_add(L, setters); /* fill with setters */
317 lua_pushcclosure(L, newindex_handler, 1);
318 lua_rawset(L, metatable); /* metatable.__newindex = newindex_handler */
320 /* FIXME: Why do we leave an element on the stack? */
321 lua_pop(L, 1); /* drop metatable */
322 return 1; /* return methods on the stack */
325 /** }}} */
327 /** Callback {{{ */
328 static void
329 push_callback(lua_State *L, struct listener **t)
331 if (!t || !*t)
332 lua_pushnil(L);
333 else
335 struct listener **r;
336 r = (struct listener **)lua_newuserdata(L, sizeof(struct listener *));
337 *r = *t;
338 luaL_getmetatable(L, "callback");
339 lua_setmetatable(L,-2);
344 static int
345 internal_unhook(lua_State *L, int warn)
347 /*Emulate check_callback() */
348 struct listener **ppl;
349 luaL_checktype(L, 1, LUA_TUSERDATA);
350 ppl = (struct listener **) luaL_checkudata(L, 1, "callback");
352 if (!ppl)
353 luaL_typerror(L, 1, "callback");
355 if (!*ppl)
357 if (warn)
359 lua_pushboolean(L, 0);
360 lua_pushstring(L, "Callback already unhooked.");
361 LuaShowErr(L);
364 else
366 LuaFreeHandler(L, (lua_handler *)&(*ppl)->handler);
367 unregister_listener(*ppl);
368 *ppl = 0;
369 if (warn)
370 lua_pushboolean(L, 1);
372 return warn != 0;
374 static int
375 callback_unhook(lua_State *L)
377 return internal_unhook(L, 1);
380 static const luaL_reg callback_methods[] = {
381 {"unhook", callback_unhook},
382 {0, 0}
386 callback_collect(lua_State *L)
388 return internal_unhook(L, 0);
391 static const luaL_reg callback_metamethods[] = {
392 {"__gc", callback_collect},
393 {0, 0}
396 static const struct Xet_reg callback_setters[] = {
397 {0, 0}
400 static const struct Xet_reg callback_getters[] = {
401 {0, 0}
405 /** }}} */
407 static int
408 screen_object_collect(lua_State *L)
410 struct broker **pbroker;
411 luaL_checktype(L, 1, LUA_TUSERDATA);
412 pbroker = (struct broker **)lua_touserdata(L, 1);
413 broker_unref(pbroker);
414 return 0;
417 /** Window {{{ */
419 PUSH_TYPE(window, struct win)
421 CHECK_TYPE(window, struct win)
423 static int get_window(lua_State *L, void *v)
425 push_window(L, (struct win **)v);
426 return 1;
429 static int
430 window_change_title(lua_State *L)
432 struct win *w = check_window(L, 1);
433 unsigned int len;
434 const char *title = luaL_checklstring(L, 3, &len);
435 ChangeAKA(w, (char *)title, len);
436 return 0;
439 static int
440 window_change_number(lua_State *L)
442 struct win *w = check_window(L, 1);
443 int newnum = luaL_checkint(L, 3);
444 ChangeWinNum(w->w_number, newnum);
445 return 0;
448 static int
449 window_get_monitor_status(lua_State *L)
451 struct win *w = check_window(L, 1);
452 int activity = luaL_checkint(L, 2);
453 if (activity)
454 /*monitor*/
455 lua_pushinteger(L, w->w_monitor != MON_OFF);
456 else
457 /*silence*/
458 lua_pushinteger(L, w->w_silence == SILENCE_ON ? w->w_silencewait: 0);
460 return 1;
463 static int
464 window_stuff(lua_State *L)
466 unsigned int len;
467 struct layer *oldflayer = flayer;
468 struct win *w = check_window(L, 1);
469 const char *str = luaL_checklstring(L, 2, &len);
471 flayer = &w->w_layer;
472 while(len)
473 LayProcess((char **)&str, (int *) &len);
474 flayer = oldflayer;
475 return 0;
478 static int
479 window_activate(lua_State *L)
481 struct win *w = check_window(L, 1);
482 SetForeWindow(w);
483 return 0;
486 static int
487 window_get_showing_canvases(lua_State *L)
489 struct win *w = check_window(L, 1);
490 int count = 0;
491 struct canvas *cv = w->w_layer.l_cvlist;
492 if (!cv) {
493 lua_pushnil(L);
494 return 1;
496 lua_newtable(L);
497 while (cv) {
498 lua_pushinteger(L, count++);
499 push_canvas(L, &cv);
500 lua_settable(L, -3);
501 cv = cv->c_lnext;
504 return 1;
507 static const luaL_reg window_methods[] = {
508 {"get_monitor_status", window_get_monitor_status},
509 {"showing_canvases", window_get_showing_canvases},
510 {"stuff", window_stuff},
511 {"activate", window_activate},
512 {"hook", LuaRegEvent},
513 {0, 0}
516 static int
517 window_tostring(lua_State *L)
519 char str[128];
520 struct win *w = check_window(L, 1);
521 snprintf(str, sizeof(str), "{window #%d: '%s'}", w->w_number, w->w_title);
522 lua_pushstring(L, str);
523 return 1;
526 static int
527 window_equality(lua_State *L)
529 struct win *w1 = check_window(L, 1), *w2 = check_window(L, 2);
530 lua_pushboolean(L, (w1 == w2 || (w1 && w2 && w1->w_number == w2->w_number)));
531 return 1;
534 static const luaL_reg window_metamethods[] = {
535 {"__tostring", window_tostring},
536 {"__eq", window_equality},
537 {"__gc", screen_object_collect},
538 {0, 0}
541 static const struct Xet_reg window_setters[] = {
542 {"title", 0, 0, window_change_title/*absolute setter*/},
543 {"number", 0, 0, window_change_number/*absolute setter*/},
544 {0, 0}
547 static const struct Xet_reg window_getters[] = {
548 {"title", get_string, offsetof(struct win, w_title) + 8},
549 {"number", get_int, offsetof(struct win, w_number)},
550 {"dir", get_string, offsetof(struct win, w_dir)},
551 {"tty", get_string, offsetof(struct win, w_tty)},
552 {"pid", get_int, offsetof(struct win, w_pid)},
553 {"group", get_window, offsetof(struct win, w_group)},
554 {"bell", get_int, offsetof(struct win, w_bell)},
555 {0, 0}
559 /** }}} */
561 /** AclUser {{{ */
563 PUSH_TYPE(user, struct acluser)
565 CHECK_TYPE(user, struct acluser)
567 static int
568 get_user(lua_State *L, void *v)
570 push_user(L, (struct acluser **)v);
571 return 1;
574 static const luaL_reg user_methods[] = {
575 {0, 0}
578 static int
579 user_tostring(lua_State *L)
581 char str[128];
582 struct acluser *u = check_user(L, 1);
583 snprintf(str, sizeof(str), "{user '%s'}", u->u_name);
584 lua_pushstring(L, str);
585 return 1;
588 static const luaL_reg user_metamethods[] = {
589 {"__tostring", user_tostring},
590 {"__gc", screen_object_collect},
591 {0, 0}
594 static const struct Xet_reg user_setters[] = {
595 {0, 0}
598 static const struct Xet_reg user_getters[] = {
599 {"name", get_string, offsetof(struct acluser, u_name)},
600 {"password", get_string, offsetof(struct acluser, u_password)},
601 {0, 0}
604 /** }}} */
606 static int get_display(lua_State *L, void *v);
607 /** Canvas {{{ */
609 PUSH_TYPE(canvas, struct canvas)
611 CHECK_TYPE(canvas, struct canvas)
613 static int
614 get_canvas(lua_State *L, void *v)
616 push_canvas(L, (struct canvas **)v);
617 return 1;
620 static int
621 canvas_select(lua_State *L)
623 struct canvas *c = check_canvas(L, 1);
624 if (!display || D_forecv == c)
625 return 0;
626 /* FIXME: why do we need this? */
627 SetCanvasWindow(c, Layer2Window(c->c_layer));
629 FocusCanvas(c);
630 return 0;
633 static int
634 canvas_split(lua_State *L)
636 struct canvas *c = check_canvas(L, 1);
637 int hori = lua_toboolean(L, 2);
638 if (hori)
639 AddCanvas(SLICE_HORI);
640 else
641 AddCanvas(SLICE_VERT);
642 Activate(-1);
643 return 0;
646 static int
647 canvas_showwin(lua_State *L)
649 struct canvas *c = check_canvas(L, 1);
650 if (lua_isnil(L, 2))
651 SetCanvasWindow(c, 0);
652 else
654 struct win *w = check_window(L, 2);
655 SetCanvasWindow(c, w);
657 return 0;
660 static const luaL_reg canvas_methods[] = {
661 {"select", canvas_select},
662 {"split", canvas_split},
663 {"showwin", canvas_showwin},
664 {0, 0}
667 static const luaL_reg canvas_metamethods[] = {
668 {"__gc", screen_object_collect},
669 {0, 0}
672 extern struct mchar mchar_so;
673 static int
674 canvas_update_caption(lua_State *L)
676 struct canvas *cv = check_canvas(L, 1);
677 unsigned int len;
678 const char *caption = luaL_checklstring(L, 3, &len);
679 int l, padlen;
680 padlen = cv->c_xe - cv->c_xs +
681 (display ? (cv->c_xe + 1 < D_width || D_CLP): 0);
682 struct win *w = Layer2Window(cv->c_layer);
683 char * buf = MakeWinMsgEv((char *)caption, w, '%', padlen, &cv->c_captev, 0);
684 if (cv->c_captev.timeout.tv_sec)
685 evenq(&cv->c_captev);
686 l = strlen(buf);
688 GotoPos(cv->c_xs, cv->c_ye+1);
689 /*XXX:what does this mean?*/
690 SetRendition(&mchar_so);
691 if (l > cv->c_xe - cv->c_xs + 1)
692 l = cv->c_xe - cv->c_xs + 1;
693 PutWinMsg(buf, cv->c_xs, l);
694 l += cv->c_xs;
695 for (; l <= cv->c_xe; l++)
696 PUTCHARLP(' ');
698 return 0;
701 static const struct Xet_reg canvas_setters[] = {
702 {"caption", 0, 0, canvas_update_caption/*absolute setter*/},
703 {0, 0}
706 static int
707 canvas_get_window(lua_State *L)
709 struct canvas *c = check_canvas(L, 1);
710 struct win *win = Layer2Window(c->c_layer);
711 if (win)
712 push_window(L, &win);
713 else
714 lua_pushnil(L);
715 return 1;
718 static const struct Xet_reg canvas_getters[] = {
719 {"next", get_canvas, offsetof(struct canvas, c_next)},
720 {"xoff", get_int, offsetof(struct canvas, c_xoff)},
721 {"yoff", get_int, offsetof(struct canvas, c_yoff)},
722 {"xs", get_int, offsetof(struct canvas, c_xs)},
723 {"ys", get_int, offsetof(struct canvas, c_ys)},
724 {"xe", get_int, offsetof(struct canvas, c_xe)},
725 {"ye", get_int, offsetof(struct canvas, c_ye)},
726 {"window", 0, 0, canvas_get_window},
727 {"display", get_display, offsetof(struct canvas, c_display)},
728 {0, 0}
731 /** }}} */
733 /** Layout {{{ */
735 PUSH_TYPE(layout, struct layout)
736 CHECK_TYPE(layout, struct layout)
738 static const struct Xet_reg layout_getters[] = {
739 {"title", get_string, offsetof(struct layout, lay_title)},
740 {"number", get_string, offsetof(struct layout, lay_title)},
741 {"autosave", get_string, offsetof(struct layout, lay_autosave)},
742 {0,0}
746 layout_change_title(lua_State *L)
748 struct layout *lay = check_layout(L, 1);
749 unsigned int len;
750 const char *title = luaL_checklstring(L, 3, &len);
751 free(lay->lay_title);
752 lay->lay_title= SaveStr(title);
753 return 0;
756 void LayoutChangeNumber(struct layout *lay, int newnum);
759 layout_change_number(lua_State *L)
761 struct layout *lay = check_layout(L, 1);
762 int newnum = luaL_checkint(L, 3);
763 LayoutChangeNumber(lay, newnum);
764 return 0;
767 static const struct Xet_reg layout_setters[] = {
768 {"title", 0, 0, layout_change_title/*absolute setter*/},
769 {"number", 0, 0, layout_change_number/*absolute setter*/},
770 {"autosave", get_string, offsetof(struct layout, lay_autosave)},
771 {0, 0}
775 layout_select(lua_State *L)
777 struct layout *lay = check_layout(L, 1);
778 if (!display) return 0;
779 LoadLayout(lay, &D_canvas);
780 Activate(0);
781 return 0;
784 static const luaL_reg layout_methods[] = {
785 {"select", layout_select},
786 {0, 0}
789 static const luaL_reg layout_metamethods[] = {
790 {"__gc", screen_object_collect},
791 {0, 0}
794 static int
795 get_layout(lua_State *L, void *v)
797 push_layout(L, (struct layout **)v);
798 return 1;
801 /** }}} */
803 /** Display {{{ */
805 PUSH_TYPE(display, struct display)
807 CHECK_TYPE(display, struct display)
809 static int
810 get_display(lua_State *L, void *v)
812 push_display(L, (struct display **)v);
813 return 1;
816 static int
817 display_get_canvases(lua_State *L)
819 struct display *d;
820 struct canvas *iter;
821 int count;
823 d = check_display(L, 1);
824 lua_newtable(L);
825 for (iter = d->d_cvlist, count = 0; iter; iter = iter->c_next, count++) {
826 lua_pushinteger(L, count);
827 push_canvas(L, &iter);
828 lua_settable(L, -3);
831 return 1;
834 static int
835 display_top_canvas(lua_State *L)
837 struct display *d;
838 d = check_display(L, 1);
839 push_canvas(L, &d->d_cvlist);
841 return 1;
844 static int
845 display_bot_canvas(lua_State *L)
847 struct display *d;
848 struct canvas *c;
849 d = check_display(L, 1);
851 for (c = d->d_cvlist; c->c_next; c = c->c_next)
853 push_canvas(L, &c);
855 return 1;
858 static const luaL_reg display_methods[] = {
859 {"get_canvases", display_get_canvases},
860 {"top_canvas", display_top_canvas},
861 {"bottom_canvas", display_bot_canvas},
862 {0, 0}
865 static int
866 display_tostring(lua_State *L)
868 char str[128];
869 struct display *d = check_display(L, 1);
870 snprintf(str, sizeof(str), "{display: tty = '%s', term = '%s'}", d->d_usertty, d->d_termname);
871 lua_pushstring(L, str);
872 return 1;
875 static const luaL_reg display_metamethods[] = {
876 {"__tostring", display_tostring},
877 {"__gc", screen_object_collect},
878 {0, 0}
881 static int
882 display_new_idle_timeout(lua_State *L)
884 struct display *disp = check_display(L, 1);
885 int timeout = luaL_checkinteger(L, 3) * 1000;
886 struct event *ev = &disp->d_idleev;
887 if (timeout > 0)
889 SetTimeout(ev, timeout);
890 if (!ev->queued)
891 evenq(ev);
893 else
894 evdeq(ev);
896 return 0;
899 static const struct Xet_reg display_setters[] = {
900 {"idle_timeout", 0, 0, display_new_idle_timeout/*absolute setter*/},
901 {0, 0}
904 static const struct Xet_reg display_getters[] = {
905 {"tty", get_string, offsetof(struct display, d_usertty)},
906 {"term", get_string, offsetof(struct display, d_termname)},
907 {"fore", get_window, offsetof(struct display, d_fore)},
908 {"other", get_window, offsetof(struct display, d_other)},
909 {"width", get_int, offsetof(struct display, d_width)},
910 {"height", get_int, offsetof(struct display, d_height)},
911 {"user", get_user, offsetof(struct display, d_user)},
912 {"layout", get_layout, offsetof(struct display, d_layout)},
913 {0, 0}
916 /** }}} */
918 /** Screen {{{ */
920 static int
921 screen_get_windows(lua_State *L)
923 struct win *iter;
924 int count;
926 lua_newtable(L);
927 for (iter = windows, count = 0; iter; iter = iter->w_next, count++) {
928 lua_pushinteger(L, iter->w_number);
929 push_window(L, &iter);
930 lua_settable(L, -3);
933 return 1;
936 static int
937 screen_get_displays(lua_State *L)
939 struct display *iter;
940 int count;
942 lua_newtable(L);
943 for (iter = displays, count = 0; iter; iter = iter->d_next, count++) {
944 lua_pushinteger(L, count);
945 push_display(L, &iter);
946 lua_settable(L, -3);
949 return 1;
952 extern struct layout *layouts;
953 static int
954 screen_get_layouts(lua_State *L)
956 struct layout *iter;
957 int count;
959 lua_newtable(L);
960 for (iter = layouts, count = 0; iter; iter = iter->lay_next, count++) {
961 lua_pushinteger(L, iter->lay_number);
962 push_layout(L, &iter);
963 lua_settable(L, -3);
966 return 1;
969 static int
970 screen_get_display(lua_State *L)
972 push_display(L, &display);
973 return 1;
976 static int
977 screen_exec_command(lua_State *L)
979 const char *command;
980 unsigned int len;
982 command = luaL_checklstring(L, 1, &len);
983 if (command)
984 RcLine((char *)command, len);
986 return 0;
989 static int
990 screen_append_msg(lua_State *L)
992 const char *msg, *color;
993 unsigned int len;
994 msg = luaL_checklstring(L, 1, &len);
995 if (lua_isnil(L, 2))
996 color = NULL;
997 else
998 color = luaL_checklstring(L, 2, &len);
999 AppendWinMsgRend(msg, color);
1000 return 0;
1003 struct sinput_data
1005 lua_State *L;
1006 lua_handler lh;
1009 void
1010 script_input_fn(char *buf, int len, char *priv)
1012 struct sinput_data *sidata = (struct sinput_data *)priv;
1013 lua_handler lh = sidata->lh;
1014 lua_State *L = sidata->L;
1016 LuaPushHandler(L, lh);
1017 lua_pushstring(L, buf);
1018 if (lua_pcall(L, 1, 0, 0) == LUA_ERRRUN)
1020 if(lua_isstring(L, -1))
1022 LuaShowErr(L);
1025 free(sidata);
1026 LuaFreeHandler(L, &lh);
1029 static int
1030 screen_input(lua_State *L)
1032 char *ss;
1033 int n;
1034 const char * prompt = NULL, *prefill = NULL;
1035 lua_handler lh;
1036 struct sinput_data *sidata;
1038 prompt = luaL_checkstring(L, 1);
1039 lh = LuaCheckHandler(L, 2, 1);
1040 if (!lh)
1041 luaL_error(L, "Out of Memory");
1043 if (lua_gettop(L) >= 3)
1044 prefill = luaL_checkstring(L, 3);
1047 sidata = (struct sinput_data *)malloc(sizeof(struct sinput_data));
1048 if (!sidata)
1050 LuaFreeHandler(L, &lh);
1051 luaL_error(L, "Out of Memory");
1054 sidata->L = L;
1055 sidata->lh = lh;
1056 Input((char *)prompt, 100, INP_COOKED, script_input_fn, (char *)sidata, 0);
1058 if (!prefill)
1059 return 0;
1060 for (; *prefill; prefill++)
1062 if ((*(unsigned char *)prefill & 0x7f) < 0x20 || *prefill == 0x7f)
1063 continue;
1064 ss = (char *)prefill;
1065 n = 1;
1066 LayProcess(&ss, &n);
1068 return 0;
1071 static void
1072 sev_schedule_fn(struct event *ev, char *data)
1074 struct sinput_data *si = (struct sinput_data *)data;
1075 lua_handler lh = si->lh;
1076 lua_State *L = si->L;
1077 free(si);
1078 evdeq(ev);
1079 Free(ev);
1081 LuaPushHandler(L, lh);
1082 if (lua_pcall(L, 1, 0, 0) == LUA_ERRRUN)
1084 if(lua_isstring(L, -1))
1086 LuaShowErr(L);
1089 LuaFreeHandler(L, &lh);
1092 static int
1093 screen_schedule(lua_State *L)
1095 int timeout = luaL_checkinteger(L, 1);
1096 lua_handler lh = LuaCheckHandler(L, 2, 1);
1097 struct sinput_data *si;
1098 struct event *ev;
1099 if (timeout <= 0)
1100 return 0;
1102 ev = (struct event *) calloc(1, sizeof(struct event));
1103 if (!ev)
1105 LuaFreeHandler(L, &lh);
1106 luaL_error(L, "Out of Memory");
1108 si = (struct sinput_data *) malloc(sizeof(struct sinput_data));
1109 if (!si)
1111 LuaFreeHandler(L, &lh);
1112 Free(ev);
1113 luaL_error(L, "Out of Memory");
1115 si->lh = lh;
1116 si->L = L;
1118 ev->type = EV_TIMEOUT;
1119 ev->data = (char *)si;
1120 ev->handler = sev_schedule_fn;
1121 evenq(ev);
1122 SetTimeout(ev, timeout * 1000);
1123 return 0;
1126 static const luaL_reg screen_methods[] = {
1127 {"windows", screen_get_windows},
1128 {"displays", screen_get_displays},
1129 {"layouts", screen_get_layouts},
1130 {"display", screen_get_display},
1131 {"command", screen_exec_command},
1132 {"append_msg", screen_append_msg},
1133 {"hook", LuaRegEvent},
1134 {"input", screen_input},
1135 {"schedule", screen_schedule},
1136 {0, 0}
1139 static const luaL_reg screen_metamethods[] = {
1140 {0, 0}
1143 static const struct Xet_reg screen_setters[] = {
1144 {0, 0}
1147 static const struct Xet_reg screen_getters[] = {
1148 {0, 0}
1151 /** }}} */
1153 /** Public functions {{{ */
1155 /* FIXME: This code only tracks one unhook ticket for a lua func.
1156 * So it does not work if one func is registered more than one times. */
1157 static void
1158 prepare_weak_table(lua_State *L, const char *name, const char *mode)
1160 luaL_getmetatable(L, "screen");
1162 lua_pushstring(L, name);
1163 lua_newtable(L);
1165 /* prepare a metatable to indicate weak table */
1166 lua_newtable(L);
1167 lua_pushstring(L, "__mode");
1168 lua_pushstring(L, mode);
1169 lua_rawset(L, -3);
1170 /* Mark weak table */
1171 lua_setmetatable(L, -2);
1172 lua_rawset(L, -3);
1173 lua_pop(L, 1);
1176 static lua_State *L;
1177 int LuaInit(void)
1179 L = luaL_newstate();
1181 luaL_openlibs(L);
1183 #define REGISTER(X) struct_register(L, #X , X ## _methods, X##_metamethods, X##_setters, X##_getters)
1185 REGISTER(screen);
1186 REGISTER(window);
1187 REGISTER(display);
1188 REGISTER(user);
1189 REGISTER(canvas);
1190 REGISTER(callback);
1192 /* To store handler funcs */
1194 /*_two kinds of information are mantained:
1196 * funcreg[key]->func
1197 * The 'func' part of the tables are weak. That means the registered funcs
1198 * will be collected once the func is no longer available (e.g. overwritten
1199 * by a new instance of the script)
1201 * To make this process happens faster, GC is forced at the end of each
1202 * source.
1203 * TODO: What if some events are triggered within the sourcing
1204 * procedure?
1205 * */
1206 prepare_weak_table(L, "_funcreg", "v");
1208 /* funcunhook[func]->listener
1209 * The listener is the unhook ticket of the hook. which should be collected
1210 * once the func is collected. The gc metamethod will be triggered
1211 * accordingly. */
1212 prepare_weak_table(L, "_funcunhook", "k");
1214 return 0;
1217 /* An error message on top of the stack. */
1218 static void
1219 LuaShowErr(lua_State *L)
1221 struct display *d = display;
1222 unsigned int len;
1223 const char *message = luaL_checklstring(L, -1, &len);
1224 lua_pop(L, 1);
1225 LMsg(0, "%s", message ? message : "Unknown error");
1226 display = d;
1229 struct fn_def
1231 void (*push_fn)(lua_State *, void*);
1232 void *value;
1235 static int
1236 LuaCallProcess(const char *name, struct fn_def defs[])
1238 int argc = 0;
1240 lua_getfield(L, LUA_GLOBALSINDEX, name);
1241 if (lua_isnil(L, -1))
1243 lua_pop(L,1);
1244 return 0;
1246 for (argc = 0; defs[argc].push_fn; argc++)
1247 defs[argc].push_fn(L, defs[argc].value);
1248 if (lua_pcall(L, argc, 0, 0) == LUA_ERRRUN && lua_isstring(L, -1))
1250 LuaShowErr(L);
1251 return 0;
1253 return 1;
1256 /* FIXME: Think about this: will it affect the registered handlers?*/
1257 int LuaSource(const char *file, int async)
1259 if (!L)
1260 return 0;
1261 struct stat st;
1262 if (stat(file, &st) == -1)
1263 Msg(errno, "Error loading lua script file '%s'", file);
1264 else
1266 int len = strlen(file);
1267 if (len < 4 || strncmp(file + len - 4, ".lua", 4) != 0)
1268 return 0;
1269 if (luaL_dofile(L, file) && lua_isstring(L, -1))
1271 LuaShowErr(L);
1272 return 0;
1274 else
1276 /* It seems that I need two GC passes to really collect the unhook
1277 * ticket, after changing the reference to ticket in the
1278 * 'funcunhook' table from weak to strong. This should not be
1279 * harmful, but how can I make sure that two passes is enough?
1281 * Possible reason:
1282 * This seems reasonable, since the first pass will collect the func
1283 * itself and make the ticket garbage, and the second pass will
1284 * collect the ticket itself.
1286 * TODO: check this out. maybe ask some lua gurus. */
1287 lua_gc(L, LUA_GCCOLLECT, 0);
1288 lua_gc(L, LUA_GCCOLLECT, 0);
1290 return 1;
1292 return 0;
1295 int LuaFinit(void)
1297 if (!L)
1298 return 0;
1299 lua_close(L);
1300 L = (lua_State*)0;
1301 return 0;
1304 static void
1305 push_stringarray(lua_State *L, char **args)
1307 int i;
1308 lua_newtable(L);
1309 for (i = 1; args && *args; i++) {
1310 lua_pushinteger(L, i);
1311 lua_pushstring(L, *args++);
1312 lua_settable(L, -3);
1317 LuaPushParams(lua_State *L, const char *params, va_list va)
1319 int num = 0;
1320 while (*params)
1322 switch (*params)
1324 case 's':
1325 lua_pushstring(L, va_arg(va, char *));
1326 break;
1327 case 'S':
1328 push_stringarray(L, va_arg(va, char **));
1329 break;
1330 case 'i':
1331 lua_pushinteger(L, va_arg(va, int));
1332 break;
1333 case 'd':
1335 struct display *d = va_arg(va, struct display *);
1336 push_display(L, &d);
1337 break;
1339 case 'w':
1341 struct win *w = va_arg(va, struct win *);
1342 push_window(L, &w);
1343 break;
1345 case 'c':
1347 struct canvas *c = va_arg(va, struct canvas *);
1348 push_canvas(L, &c);
1349 break;
1352 params++;
1353 num++;
1355 return num;
1358 int LuaCall(const char *func, const char **argv)
1360 int argc;
1361 if (!L)
1362 return 0;
1364 StackDump(L, "Before LuaCall\n");
1365 lua_getfield(L, LUA_GLOBALSINDEX, func);
1366 if (lua_isnil(L, -1))
1368 lua_pop(L, 1);
1369 lua_pushstring(L, "Could not find the script function\n");
1370 LuaShowErr(L);
1371 return 0;
1373 for (argc = 0; *argv; argv++, argc++)
1375 lua_pushstring(L, *argv);
1377 if (lua_pcall(L, argc, 0, 0) == LUA_ERRRUN)
1379 if(lua_isstring(L, -1))
1381 StackDump(L, "After LuaCall\n");
1382 LuaShowErr(L);
1383 return 0;
1386 return 1;
1389 /*** Lua callback handler management {{{ */
1392 LuaPushHTable(lua_State *L, int screen, const char * t)
1394 lua_pushstring(L, t);
1395 lua_rawget(L, screen);
1396 /* FIXME: Do we need to balance the stack here? */
1397 if (lua_isnil(L, -1))
1398 luaL_error(L, "Fatal! Fail to get function registeration table!");
1399 return lua_gettop(L);
1402 void
1403 LuaPushHandler(lua_State *L, lua_handler lh)
1405 int funcreg;
1406 if (lh->type == LUA_HANDLER_TYPE_F)
1408 luaL_getmetatable(L, "screen");
1409 funcreg = LuaPushHTable(L, lua_gettop(L), "_funcreg");
1410 lua_rawgeti(L, funcreg, lh->u.reference);
1411 lua_replace(L, -3);
1412 lua_pop(L, 1);
1414 else
1416 lua_getfield(L, LUA_GLOBALSINDEX, lh->u.name);
1421 LuaFuncKey(lua_State *L, int idx, int ref)
1423 int key, funcreg, sc;
1424 luaL_getmetatable(L, "screen");
1425 sc = lua_gettop(L);
1426 funcreg = LuaPushHTable(L, sc, "_funcreg");
1428 lua_pushvalue(L, idx);
1429 key = luaL_ref(L, funcreg);
1430 lua_pop(L, 2);
1431 return key;
1434 void
1435 LuaHUnRef(lua_State *L, int key)
1437 int funcreg, sc;
1438 luaL_getmetatable(L, "screen");
1439 sc = lua_gettop(L);
1440 funcreg = LuaPushHTable(L, sc, "_funcreg");
1441 luaL_unref(L, funcreg, key);
1444 lua_handler
1445 LuaCheckHandler(lua_State *L, int idx, int ref)
1447 int key;
1448 if (idx < 0)
1449 idx = lua_gettop(L) + 1 - idx;
1451 if (lua_isstring(L, idx))
1453 const char * handler;
1454 /* registered with func name.*/
1455 handler = luaL_checkstring(L, idx);
1456 lua_getfield(L, LUA_GLOBALSINDEX, handler);
1457 if (!lua_isfunction(L, -1))
1458 luaL_error(L, "The specified handler %s in param #%d is not a function", handler, idx);
1459 lua_pop(L, 1);
1460 return LuaAllocHandler(handler, 0);
1462 else if (!lua_isfunction(L, idx))
1463 luaL_error(L, "Handler should be a function or the name of function");
1465 key = LuaFuncKey(L, idx, ref);
1466 return LuaAllocHandler(NULL, key);
1469 /* }}} **/
1471 static int
1472 LuaDispatch(void *handler, const char *params, va_list va)
1474 lua_handler lh = (lua_handler)handler;
1475 int argc, retvalue;
1477 StackDump(L, "before dispatch");
1479 LuaPushHandler(L, lh);
1480 if (lua_isnil(L, -1))
1482 lua_pop(L, 1);
1483 return 0;
1485 argc = LuaPushParams(L, params, va);
1487 if (lua_pcall(L, argc, 1, 0) == LUA_ERRRUN && lua_isstring(L, -1))
1489 StackDump(L, "After LuaDispatch\n");
1490 LuaShowErr(L);
1491 return 0;
1493 retvalue = lua_tonumber(L, -1);
1494 lua_pop(L, 1);
1495 return retvalue;
1498 /*FIXME: what if a func is registered twice or more? */
1499 void
1500 LuaRegAutoUnHook(lua_State *L, lua_handler lh, int ticket)
1502 int sc, funcunhook;
1503 luaL_getmetatable(L, "screen");
1504 sc = lua_gettop(L);
1505 funcunhook = LuaPushHTable(L, sc, "_funcunhook");
1506 LuaPushHandler(L, lh);
1507 lua_pushvalue(L, ticket);
1508 lua_rawset(L, funcunhook);
1509 lua_pop(L, 2);
1512 #define SEVNAME_MAX 30
1513 static int
1514 LuaRegEvent(lua_State *L)
1516 /* signature: hook(obj, event, handler, priv);
1517 * or: hook(event, handler, priv)
1518 * returns: A ticket for later unregister. */
1519 int idx = 1, argc = lua_gettop(L);
1520 unsigned int priv = 31; /* Default privilege */
1521 lua_handler lh;
1523 char *obj = NULL;
1524 const char *objname = "global";
1526 static char evbuf[SEVNAME_MAX];
1527 const char *event;
1529 struct script_event *sev;
1531 StackDump(L, "Before RegEvent\n");
1533 /* Identify the object, if specified */
1534 if (luaL_getmetafield(L, 1, "_objname"))
1536 objname = luaL_checkstring(L, -1);
1537 lua_pop(L, 1);
1538 if (!strcmp("screen", objname))
1539 objname = "global";
1540 else
1542 obj = get_broker_obj((struct broker **)lua_touserdata(L, 1));
1543 if (!obj)
1544 return luaL_error(L, "Invalid object specified");
1546 idx++;
1549 event = luaL_checkstring(L, idx++);
1550 snprintf(evbuf, SEVNAME_MAX, "%s_%s", objname, event);
1552 /* Check and get the handler */
1553 lh = LuaCheckHandler(L, idx++, 1);
1554 if (!lh)
1555 luaL_error(L, "Out of memory");
1557 StackDump(L, "In RegEvent\n");
1559 if (idx <= argc)
1560 priv = luaL_checkinteger(L, idx);
1562 sev = object_get_event(obj, evbuf);
1563 if (sev)
1565 struct listener *l;
1566 int ticket;
1567 l = (struct listener *)malloc(sizeof(struct listener));
1568 if (!l)
1569 return luaL_error(L, "Out of memory");
1570 l->priv = priv;
1571 l->bd = &lua_binding;
1572 l->handler = (void *)lh;
1573 register_listener(sev, l);
1574 /* Return the ticket for un-register */
1575 push_callback(L, &l);
1576 ticket = lua_gettop(L);
1578 LuaRegAutoUnHook(L, lh, ticket);
1580 else
1581 return luaL_error(L, "Invalid event specified: %s for object %s", event, objname);
1583 StackDump(L, "After RegEvent\n");
1584 return 1;
1587 /** }}} */
1589 struct binding lua_binding =
1591 "lua", /*name*/
1592 0, /*inited*/
1593 0, /*registered*/
1594 LuaInit,
1595 LuaFinit,
1596 LuaCall,
1597 LuaSource,
1598 LuaDispatch,
1599 0, /*b_next*/