Push broker to lua script, instead of the pointer itself.
[screen-lua.git] / src / lua.c
blob43c412fd176e2f931eb17fa733d91287040a1293
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 /** Window {{{ */
409 PUSH_TYPE(window, struct win)
411 CHECK_TYPE(window, struct win)
413 static int get_window(lua_State *L, void *v)
415 push_window(L, (struct win **)v);
416 return 1;
419 static int
420 window_change_title(lua_State *L)
422 struct win *w = check_window(L, 1);
423 unsigned int len;
424 const char *title = luaL_checklstring(L, 3, &len);
425 ChangeAKA(w, (char *)title, len);
426 return 0;
429 static int
430 window_change_number(lua_State *L)
432 struct win *w = check_window(L, 1);
433 int newnum = luaL_checkint(L, 3);
434 ChangeWinNum(w->w_number, newnum);
435 return 0;
438 static int
439 window_get_monitor_status(lua_State *L)
441 struct win *w = check_window(L, 1);
442 int activity = luaL_checkint(L, 2);
443 if (activity)
444 /*monitor*/
445 lua_pushinteger(L, w->w_monitor != MON_OFF);
446 else
447 /*silence*/
448 lua_pushinteger(L, w->w_silence == SILENCE_ON ? w->w_silencewait: 0);
450 return 1;
453 static int
454 window_stuff(lua_State *L)
456 unsigned int len;
457 struct layer *oldflayer = flayer;
458 struct win *w = check_window(L, 1);
459 const char *str = luaL_checklstring(L, 2, &len);
461 flayer = &w->w_layer;
462 while(len)
463 LayProcess((char **)&str, (int *) &len);
464 flayer = oldflayer;
465 return 0;
468 static int
469 window_activate(lua_State *L)
471 struct win *w = check_window(L, 1);
472 SetForeWindow(w);
473 return 0;
476 static const luaL_reg window_methods[] = {
477 {"get_monitor_status", window_get_monitor_status},
478 {"stuff", window_stuff},
479 {"activate", window_activate},
480 {"hook", LuaRegEvent},
481 {0, 0}
484 static int
485 window_tostring(lua_State *L)
487 char str[128];
488 struct win *w = check_window(L, 1);
489 snprintf(str, sizeof(str), "{window #%d: '%s'}", w->w_number, w->w_title);
490 lua_pushstring(L, str);
491 return 1;
494 static int
495 window_equality(lua_State *L)
497 struct win *w1 = check_window(L, 1), *w2 = check_window(L, 2);
498 lua_pushboolean(L, (w1 == w2 || (w1 && w2 && w1->w_number == w2->w_number)));
499 return 1;
502 static const luaL_reg window_metamethods[] = {
503 {"__tostring", window_tostring},
504 {"__eq", window_equality},
505 {0, 0}
508 static const struct Xet_reg window_setters[] = {
509 {"title", 0, 0, window_change_title/*absolute setter*/},
510 {"number", 0, 0, window_change_number/*absolute setter*/},
511 {0, 0}
514 static const struct Xet_reg window_getters[] = {
515 {"title", get_string, offsetof(struct win, w_title) + 8},
516 {"number", get_int, offsetof(struct win, w_number)},
517 {"dir", get_string, offsetof(struct win, w_dir)},
518 {"tty", get_string, offsetof(struct win, w_tty)},
519 {"pid", get_int, offsetof(struct win, w_pid)},
520 {"group", get_window, offsetof(struct win, w_group)},
521 {"bell", get_int, offsetof(struct win, w_bell)},
522 {0, 0}
526 /** }}} */
528 /** AclUser {{{ */
530 PUSH_TYPE(user, struct acluser)
532 CHECK_TYPE(user, struct acluser)
534 static int
535 get_user(lua_State *L, void *v)
537 push_user(L, (struct acluser **)v);
538 return 1;
541 static const luaL_reg user_methods[] = {
542 {0, 0}
545 static int
546 user_tostring(lua_State *L)
548 char str[128];
549 struct acluser *u = check_user(L, 1);
550 snprintf(str, sizeof(str), "{user '%s'}", u->u_name);
551 lua_pushstring(L, str);
552 return 1;
555 static const luaL_reg user_metamethods[] = {
556 {"__tostring", user_tostring},
557 {0, 0}
560 static const struct Xet_reg user_setters[] = {
561 {0, 0}
564 static const struct Xet_reg user_getters[] = {
565 {"name", get_string, offsetof(struct acluser, u_name)},
566 {"password", get_string, offsetof(struct acluser, u_password)},
567 {0, 0}
570 /** }}} */
572 static int get_display(lua_State *L, void *v);
573 /** Canvas {{{ */
575 PUSH_TYPE(canvas, struct canvas)
577 CHECK_TYPE(canvas, struct canvas)
579 static int
580 get_canvas(lua_State *L, void *v)
582 push_canvas(L, (struct canvas **)v);
583 return 1;
586 static int
587 canvas_select(lua_State *L)
589 struct canvas *c = check_canvas(L, 1);
590 if (!display || D_forecv == c)
591 return 0;
592 /* FIXME: why do we need this? */
593 SetCanvasWindow(c, Layer2Window(c->c_layer));
595 FocusCanvas(c);
596 return 0;
599 static int
600 canvas_split(lua_State *L)
602 struct canvas *c = check_canvas(L, 1);
603 int hori = lua_toboolean(L, 2);
604 if (hori)
605 AddCanvas(SLICE_HORI);
606 else
607 AddCanvas(SLICE_VERT);
608 Activate(-1);
609 return 0;
612 static int
613 canvas_showwin(lua_State *L)
615 struct canvas *c = check_canvas(L, 1);
616 if (lua_isnil(L, 2))
617 SetCanvasWindow(c, 0);
618 else
620 struct win *w = check_window(L, 2);
621 SetCanvasWindow(c, w);
623 return 0;
626 static const luaL_reg canvas_methods[] = {
627 {"select", canvas_select},
628 {"split", canvas_split},
629 {"showwin", canvas_showwin},
630 {0, 0}
633 static const luaL_reg canvas_metamethods[] = {
634 {0, 0}
637 extern struct mchar mchar_so;
638 static int
639 canvas_update_caption(lua_State *L)
641 struct canvas *cv = check_canvas(L, 1);
642 unsigned int len;
643 const char *caption = luaL_checklstring(L, 3, &len);
644 int l, padlen;
645 padlen = cv->c_xe - cv->c_xs +
646 (display ? (cv->c_xe + 1 < D_width || D_CLP): 0);
647 struct win *w = Layer2Window(cv->c_layer);
648 char * buf = MakeWinMsgEv((char *)caption, w, '%', padlen, &cv->c_captev, 0);
649 if (cv->c_captev.timeout.tv_sec)
650 evenq(&cv->c_captev);
651 l = strlen(buf);
653 GotoPos(cv->c_xs, cv->c_ye+1);
654 /*XXX:what does this mean?*/
655 SetRendition(&mchar_so);
656 if (l > cv->c_xe - cv->c_xs + 1)
657 l = cv->c_xe - cv->c_xs + 1;
658 PutWinMsg(buf, cv->c_xs, l);
660 return 0;
663 static const struct Xet_reg canvas_setters[] = {
664 {"caption", 0, 0, canvas_update_caption/*absolute setter*/},
665 {0, 0}
668 static int
669 canvas_get_window(lua_State *L)
671 struct canvas *c = check_canvas(L, 1);
672 struct win *win = Layer2Window(c->c_layer);
673 if (win)
674 push_window(L, &win);
675 else
676 lua_pushnil(L);
677 return 1;
680 static const struct Xet_reg canvas_getters[] = {
681 {"next", get_canvas, offsetof(struct canvas, c_next)},
682 {"xoff", get_int, offsetof(struct canvas, c_xoff)},
683 {"yoff", get_int, offsetof(struct canvas, c_yoff)},
684 {"xs", get_int, offsetof(struct canvas, c_xs)},
685 {"ys", get_int, offsetof(struct canvas, c_ys)},
686 {"xe", get_int, offsetof(struct canvas, c_xe)},
687 {"ye", get_int, offsetof(struct canvas, c_ye)},
688 {"window", 0, 0, canvas_get_window},
689 {"display", get_display, offsetof(struct canvas, c_display)},
690 {0, 0}
693 /** }}} */
695 /** Layout {{{ */
697 PUSH_TYPE(layout, struct layout)
698 CHECK_TYPE(layout, struct layout)
700 static const struct Xet_reg layout_getters[] = {
701 {"title", get_string, offsetof(struct layout, lay_title)},
702 {"number", get_string, offsetof(struct layout, lay_title)},
703 {"autosave", get_string, offsetof(struct layout, lay_autosave)},
704 {0,0}
708 layout_change_title(lua_State *L)
710 struct layout *lay = check_layout(L, 1);
711 unsigned int len;
712 const char *title = luaL_checklstring(L, 3, &len);
713 free(lay->lay_title);
714 lay->lay_title= SaveStr(title);
715 return 0;
718 void LayoutChangeNumber(struct layout *lay, int newnum);
721 layout_change_number(lua_State *L)
723 struct layout *lay = check_layout(L, 1);
724 int newnum = luaL_checkint(L, 3);
725 LayoutChangeNumber(lay, newnum);
726 return 0;
729 static const struct Xet_reg layout_setters[] = {
730 {"title", 0, 0, layout_change_title/*absolute setter*/},
731 {"number", 0, 0, layout_change_number/*absolute setter*/},
732 {"autosave", get_string, offsetof(struct layout, lay_autosave)},
733 {0, 0}
737 layout_select(lua_State *L)
739 struct layout *lay = check_layout(L, 1);
740 if (!display) return;
741 LoadLayout(lay, &D_canvas);
742 Activate(0);
743 return 0;
746 static const luaL_reg layout_methods[] = {
747 {"select", layout_select},
748 {0, 0}
751 static int
752 get_layout(lua_State *L, void *v)
754 push_layout(L, (struct layout **)v);
755 return 1;
758 /** }}} */
760 /** Display {{{ */
762 PUSH_TYPE(display, struct display)
764 CHECK_TYPE(display, struct display)
766 static int
767 get_display(lua_State *L, void *v)
769 push_display(L, (struct display **)v);
770 return 1;
773 static int
774 display_get_canvases(lua_State *L)
776 struct display *d;
777 struct canvas *iter;
778 int count;
780 d = check_display(L, 1);
781 lua_newtable(L);
782 for (iter = d->d_cvlist, count = 0; iter; iter = iter->c_next, count++) {
783 lua_pushinteger(L, count);
784 push_canvas(L, &iter);
785 lua_settable(L, -3);
788 return 1;
791 static int
792 display_top_canvas(lua_State *L)
794 struct display *d;
795 d = check_display(L, 1);
796 push_canvas(L, &d->d_cvlist);
798 return 1;
801 static int
802 display_bot_canvas(lua_State *L)
804 struct display *d;
805 struct canvas *c;
806 d = check_display(L, 1);
808 for (c = d->d_cvlist; c->c_next; c = c->c_next)
810 push_canvas(L, &c);
812 return 1;
815 static const luaL_reg display_methods[] = {
816 {"get_canvases", display_get_canvases},
817 {"top_canvas", display_top_canvas},
818 {"bottom_canvas", display_bot_canvas},
819 {0, 0}
822 static int
823 display_tostring(lua_State *L)
825 char str[128];
826 struct display *d = check_display(L, 1);
827 snprintf(str, sizeof(str), "{display: tty = '%s', term = '%s'}", d->d_usertty, d->d_termname);
828 lua_pushstring(L, str);
829 return 1;
832 static const luaL_reg display_metamethods[] = {
833 {"__tostring", display_tostring},
834 {0, 0}
837 static int
838 display_new_idle_timeout(lua_State *L)
840 struct display *disp = check_display(L, 1);
841 int timeout = luaL_checkinteger(L, 3) * 1000;
842 struct event *ev = &disp->d_idleev;
843 if (timeout > 0)
845 SetTimeout(ev, timeout);
846 if (!ev->queued)
847 evenq(ev);
849 else
850 evdeq(ev);
852 return 0;
855 static const struct Xet_reg display_setters[] = {
856 {"idle_timeout", 0, 0, display_new_idle_timeout/*absolute setter*/},
857 {0, 0}
860 static const struct Xet_reg display_getters[] = {
861 {"tty", get_string, offsetof(struct display, d_usertty)},
862 {"term", get_string, offsetof(struct display, d_termname)},
863 {"fore", get_window, offsetof(struct display, d_fore)},
864 {"other", get_window, offsetof(struct display, d_other)},
865 {"width", get_int, offsetof(struct display, d_width)},
866 {"height", get_int, offsetof(struct display, d_height)},
867 {"user", get_user, offsetof(struct display, d_user)},
868 {"layout", get_layout, offsetof(struct display, d_layout)},
869 {0, 0}
872 /** }}} */
874 /** Screen {{{ */
876 static int
877 screen_get_windows(lua_State *L)
879 struct win *iter;
880 int count;
882 lua_newtable(L);
883 for (iter = windows, count = 0; iter; iter = iter->w_next, count++) {
884 lua_pushinteger(L, iter->w_number);
885 push_window(L, &iter);
886 lua_settable(L, -3);
889 return 1;
892 static int
893 screen_get_displays(lua_State *L)
895 struct display *iter;
896 int count;
898 lua_newtable(L);
899 for (iter = displays, count = 0; iter; iter = iter->d_next, count++) {
900 lua_pushinteger(L, count);
901 push_display(L, &iter);
902 lua_settable(L, -3);
905 return 1;
908 extern struct layout *layouts;
909 static int
910 screen_get_layouts(lua_State *L)
912 struct layout *iter;
913 int count;
915 lua_newtable(L);
916 for (iter = layouts, count = 0; iter; iter = iter->lay_next, count++) {
917 lua_pushinteger(L, iter->lay_number);
918 push_layout(L, &iter);
919 lua_settable(L, -3);
922 return 1;
925 static int
926 screen_get_display(lua_State *L)
928 push_display(L, &display);
929 return 1;
932 static int
933 screen_exec_command(lua_State *L)
935 const char *command;
936 unsigned int len;
938 command = luaL_checklstring(L, 1, &len);
939 if (command)
940 RcLine((char *)command, len);
942 return 0;
945 static int
946 screen_append_msg(lua_State *L)
948 const char *msg, *color;
949 unsigned int len;
950 msg = luaL_checklstring(L, 1, &len);
951 if (lua_isnil(L, 2))
952 color = NULL;
953 else
954 color = luaL_checklstring(L, 2, &len);
955 AppendWinMsgRend(msg, color);
956 return 0;
959 struct sinput_data
961 lua_State *L;
962 lua_handler lh;
965 void
966 script_input_fn(char *buf, int len, char *priv)
968 struct sinput_data *sidata = (struct sinput_data *)priv;
969 lua_handler lh = sidata->lh;
970 lua_State *L = sidata->L;
972 LuaPushHandler(L, lh);
973 lua_pushstring(L, buf);
974 if (lua_pcall(L, 1, 0, 0) == LUA_ERRRUN)
976 if(lua_isstring(L, -1))
978 LuaShowErr(L);
981 free(sidata);
982 LuaFreeHandler(L, &lh);
985 static int
986 screen_input(lua_State *L)
988 char *ss;
989 int n;
990 const char * prompt = NULL, *prefill = NULL;
991 lua_handler lh;
992 struct sinput_data *sidata;
994 prompt = luaL_checkstring(L, 1);
995 lh = LuaCheckHandler(L, 2, 1);
996 if (!lh)
997 luaL_error(L, "Out of Memory");
999 if (lua_gettop(L) >= 3)
1000 prefill = luaL_checkstring(L, 3);
1003 sidata = (struct sinput_data *)malloc(sizeof(struct sinput_data));
1004 if (!sidata)
1006 LuaFreeHandler(L, &lh);
1007 luaL_error(L, "Out of Memory");
1010 sidata->L = L;
1011 sidata->lh = lh;
1012 Input((char *)prompt, 100, INP_COOKED, script_input_fn, (char *)sidata, 0);
1014 if (!prefill)
1015 return 0;
1016 for (; *prefill; prefill++)
1018 if ((*(unsigned char *)prefill & 0x7f) < 0x20 || *prefill == 0x7f)
1019 continue;
1020 ss = (char *)prefill;
1021 n = 1;
1022 LayProcess(&ss, &n);
1024 return 0;
1027 static void
1028 sev_schedule_fn(struct event *ev, char *data)
1030 struct sinput_data *si = (struct sinput_data *)data;
1031 lua_handler lh = si->lh;
1032 lua_State *L = si->L;
1033 free(si);
1034 evdeq(ev);
1035 Free(ev);
1037 LuaPushHandler(L, lh);
1038 if (lua_pcall(L, 1, 0, 0) == LUA_ERRRUN)
1040 if(lua_isstring(L, -1))
1042 LuaShowErr(L);
1045 LuaFreeHandler(L, &lh);
1048 static int
1049 screen_schedule(lua_State *L)
1051 int timeout = luaL_checkinteger(L, 1);
1052 lua_handler lh = LuaCheckHandler(L, 2, 1);
1053 struct sinput_data *si;
1054 struct event *ev;
1055 if (timeout <= 0)
1056 return 0;
1058 ev = (struct event *) calloc(1, sizeof(struct event));
1059 if (!ev)
1061 LuaFreeHandler(L, &lh);
1062 luaL_error(L, "Out of Memory");
1064 si = (struct sinput_data *) malloc(sizeof(struct sinput_data));
1065 if (!si)
1067 LuaFreeHandler(L, &lh);
1068 Free(ev);
1069 luaL_error(L, "Out of Memory");
1071 si->lh = lh;
1072 si->L = L;
1074 ev->type = EV_TIMEOUT;
1075 ev->data = (char *)si;
1076 ev->handler = sev_schedule_fn;
1077 evenq(ev);
1078 SetTimeout(ev, timeout * 1000);
1079 return 0;
1082 static const luaL_reg screen_methods[] = {
1083 {"windows", screen_get_windows},
1084 {"displays", screen_get_displays},
1085 {"layouts", screen_get_layouts},
1086 {"display", screen_get_display},
1087 {"command", screen_exec_command},
1088 {"append_msg", screen_append_msg},
1089 {"hook", LuaRegEvent},
1090 {"input", screen_input},
1091 {"schedule", screen_schedule},
1092 {0, 0}
1095 static const luaL_reg screen_metamethods[] = {
1096 {0, 0}
1099 static const struct Xet_reg screen_setters[] = {
1100 {0, 0}
1103 static const struct Xet_reg screen_getters[] = {
1104 {0, 0}
1107 /** }}} */
1109 /** Public functions {{{ */
1111 /* FIXME: This code only tracks one unhook ticket for a lua func.
1112 * So it does not work if one func is registered more than one times. */
1113 static void
1114 prepare_weak_table(lua_State *L, const char *name, const char *mode)
1116 luaL_getmetatable(L, "screen");
1118 lua_pushstring(L, name);
1119 lua_newtable(L);
1121 /* prepare a metatable to indicate weak table */
1122 lua_newtable(L);
1123 lua_pushstring(L, "__mode");
1124 lua_pushstring(L, mode);
1125 lua_rawset(L, -3);
1126 /* Mark weak table */
1127 lua_setmetatable(L, -2);
1128 lua_rawset(L, -3);
1129 lua_pop(L, 1);
1132 static lua_State *L;
1133 int LuaInit(void)
1135 L = luaL_newstate();
1137 luaL_openlibs(L);
1139 #define REGISTER(X) struct_register(L, #X , X ## _methods, X##_metamethods, X##_setters, X##_getters)
1141 REGISTER(screen);
1142 REGISTER(window);
1143 REGISTER(display);
1144 REGISTER(user);
1145 REGISTER(canvas);
1146 REGISTER(callback);
1148 /* To store handler funcs */
1150 /*_two kinds of information are mantained:
1152 * funcreg[key]->func
1153 * The 'func' part of the tables are weak. That means the registered funcs
1154 * will be collected once the func is no longer available (e.g. overwritten
1155 * by a new instance of the script)
1157 * To make this process happens faster, GC is forced at the end of each
1158 * source.
1159 * TODO: What if some events are triggered within the sourcing
1160 * procedure?
1161 * */
1162 prepare_weak_table(L, "_funcreg", "v");
1164 /* funcunhook[func]->listener
1165 * The listener is the unhook ticket of the hook. which should be collected
1166 * once the func is collected. The gc metamethod will be triggered
1167 * accordingly. */
1168 prepare_weak_table(L, "_funcunhook", "k");
1170 return 0;
1173 /* An error message on top of the stack. */
1174 static void
1175 LuaShowErr(lua_State *L)
1177 struct display *d = display;
1178 unsigned int len;
1179 const char *message = luaL_checklstring(L, -1, &len);
1180 lua_pop(L, 1);
1181 LMsg(0, "%s", message ? message : "Unknown error");
1182 display = d;
1185 struct fn_def
1187 void (*push_fn)(lua_State *, void*);
1188 void *value;
1191 static int
1192 LuaCallProcess(const char *name, struct fn_def defs[])
1194 int argc = 0;
1196 lua_getfield(L, LUA_GLOBALSINDEX, name);
1197 if (lua_isnil(L, -1))
1199 lua_pop(L,1);
1200 return 0;
1202 for (argc = 0; defs[argc].push_fn; argc++)
1203 defs[argc].push_fn(L, defs[argc].value);
1204 if (lua_pcall(L, argc, 0, 0) == LUA_ERRRUN && lua_isstring(L, -1))
1206 LuaShowErr(L);
1207 return 0;
1209 return 1;
1212 /* FIXME: Think about this: will it affect the registered handlers?*/
1213 int LuaSource(const char *file, int async)
1215 if (!L)
1216 return 0;
1217 struct stat st;
1218 if (stat(file, &st) == -1)
1219 Msg(errno, "Error loading lua script file '%s'", file);
1220 else
1222 int len = strlen(file);
1223 if (len < 4 || strncmp(file + len - 4, ".lua", 4) != 0)
1224 return 0;
1225 if (luaL_dofile(L, file) && lua_isstring(L, -1))
1227 LuaShowErr(L);
1228 return 0;
1230 else
1232 /* It seems that I need two GC passes to really collect the unhook
1233 * ticket, after changing the reference to ticket in the
1234 * 'funcunhook' table from weak to strong. This should not be
1235 * harmful, but how can I make sure that two passes is enough?
1237 * Possible reason:
1238 * This seems reasonable, since the first pass will collect the func
1239 * itself and make the ticket garbage, and the second pass will
1240 * collect the ticket itself.
1242 * TODO: check this out. maybe ask some lua gurus. */
1243 lua_gc(L, LUA_GCCOLLECT, 0);
1244 lua_gc(L, LUA_GCCOLLECT, 0);
1246 return 1;
1248 return 0;
1251 int LuaFinit(void)
1253 if (!L)
1254 return 0;
1255 lua_close(L);
1256 L = (lua_State*)0;
1257 return 0;
1260 static void
1261 push_stringarray(lua_State *L, char **args)
1263 int i;
1264 lua_newtable(L);
1265 for (i = 1; args && *args; i++) {
1266 lua_pushinteger(L, i);
1267 lua_pushstring(L, *args++);
1268 lua_settable(L, -3);
1273 LuaPushParams(lua_State *L, const char *params, va_list va)
1275 int num = 0;
1276 while (*params)
1278 switch (*params)
1280 case 's':
1281 lua_pushstring(L, va_arg(va, char *));
1282 break;
1283 case 'S':
1284 push_stringarray(L, va_arg(va, char **));
1285 break;
1286 case 'i':
1287 lua_pushinteger(L, va_arg(va, int));
1288 break;
1289 case 'd':
1291 struct display *d = va_arg(va, struct display *);
1292 push_display(L, &d);
1293 break;
1295 case 'w':
1297 struct win *w = va_arg(va, struct win *);
1298 push_window(L, &w);
1299 break;
1301 case 'c':
1303 struct canvas *c = va_arg(va, struct canvas *);
1304 push_canvas(L, &c);
1305 break;
1308 params++;
1309 num++;
1311 return num;
1314 int LuaCall(const char *func, const char **argv)
1316 int argc;
1317 if (!L)
1318 return 0;
1320 StackDump(L, "Before LuaCall\n");
1321 lua_getfield(L, LUA_GLOBALSINDEX, func);
1322 if (lua_isnil(L, -1))
1324 lua_pop(L, 1);
1325 lua_pushstring(L, "Could not find the script function\n");
1326 LuaShowErr(L);
1327 return 0;
1329 for (argc = 0; *argv; argv++, argc++)
1331 lua_pushstring(L, *argv);
1333 if (lua_pcall(L, argc, 0, 0) == LUA_ERRRUN)
1335 if(lua_isstring(L, -1))
1337 StackDump(L, "After LuaCall\n");
1338 LuaShowErr(L);
1339 return 0;
1342 return 1;
1345 /*** Lua callback handler management {{{ */
1348 LuaPushHTable(lua_State *L, int screen, const char * t)
1350 lua_pushstring(L, t);
1351 lua_rawget(L, screen);
1352 /* FIXME: Do we need to balance the stack here? */
1353 if (lua_isnil(L, -1))
1354 luaL_error(L, "Fatal! Fail to get function registeration table!");
1355 return lua_gettop(L);
1358 void
1359 LuaPushHandler(lua_State *L, lua_handler lh)
1361 int funcreg;
1362 if (lh->type == LUA_HANDLER_TYPE_F)
1364 luaL_getmetatable(L, "screen");
1365 funcreg = LuaPushHTable(L, lua_gettop(L), "_funcreg");
1366 lua_rawgeti(L, funcreg, lh->u.reference);
1367 lua_replace(L, -3);
1368 lua_pop(L, 1);
1370 else
1372 lua_getfield(L, LUA_GLOBALSINDEX, lh->u.name);
1377 LuaFuncKey(lua_State *L, int idx, int ref)
1379 int key, funcreg, sc;
1380 luaL_getmetatable(L, "screen");
1381 sc = lua_gettop(L);
1382 funcreg = LuaPushHTable(L, sc, "_funcreg");
1384 lua_pushvalue(L, idx);
1385 key = luaL_ref(L, funcreg);
1386 lua_pop(L, 2);
1387 return key;
1390 void
1391 LuaHUnRef(lua_State *L, int key)
1393 int funcreg, sc;
1394 luaL_getmetatable(L, "screen");
1395 sc = lua_gettop(L);
1396 funcreg = LuaPushHTable(L, sc, "_funcreg");
1397 luaL_unref(L, funcreg, key);
1400 lua_handler
1401 LuaCheckHandler(lua_State *L, int idx, int ref)
1403 int key;
1404 if (idx < 0)
1405 idx = lua_gettop(L) + 1 - idx;
1407 if (lua_isstring(L, idx))
1409 const char * handler;
1410 /* registered with func name.*/
1411 handler = luaL_checkstring(L, idx);
1412 lua_getfield(L, LUA_GLOBALSINDEX, handler);
1413 if (!lua_isfunction(L, -1))
1414 luaL_error(L, "The specified handler %s in param #%d is not a function", handler, idx);
1415 lua_pop(L, 1);
1416 return LuaAllocHandler(handler, 0);
1418 else if (!lua_isfunction(L, idx))
1419 luaL_error(L, "Handler should be a function or the name of function");
1421 key = LuaFuncKey(L, idx, ref);
1422 return LuaAllocHandler(NULL, key);
1425 /* }}} **/
1427 static int
1428 LuaDispatch(void *handler, const char *params, va_list va)
1430 lua_handler lh = (lua_handler)handler;
1431 int argc, retvalue;
1433 StackDump(L, "before dispatch");
1435 LuaPushHandler(L, lh);
1436 if (lua_isnil(L, -1))
1438 lua_pop(L, 1);
1439 return 0;
1441 argc = LuaPushParams(L, params, va);
1443 if (lua_pcall(L, argc, 1, 0) == LUA_ERRRUN && lua_isstring(L, -1))
1445 StackDump(L, "After LuaDispatch\n");
1446 LuaShowErr(L);
1447 return 0;
1449 retvalue = lua_tonumber(L, -1);
1450 lua_pop(L, 1);
1451 return retvalue;
1454 /*FIXME: what if a func is registered twice or more? */
1455 void
1456 LuaRegAutoUnHook(lua_State *L, lua_handler lh, int ticket)
1458 int sc, funcunhook;
1459 luaL_getmetatable(L, "screen");
1460 sc = lua_gettop(L);
1461 funcunhook = LuaPushHTable(L, sc, "_funcunhook");
1462 LuaPushHandler(L, lh);
1463 lua_pushvalue(L, ticket);
1464 lua_rawset(L, funcunhook);
1465 lua_pop(L, 2);
1468 #define SEVNAME_MAX 30
1469 static int
1470 LuaRegEvent(lua_State *L)
1472 /* signature: hook(obj, event, handler, priv);
1473 * or: hook(event, handler, priv)
1474 * returns: A ticket for later unregister. */
1475 int idx = 1, argc = lua_gettop(L);
1476 unsigned int priv = 31; /* Default privilege */
1477 lua_handler lh;
1479 char *obj = NULL;
1480 const char *objname = "global";
1482 static char evbuf[SEVNAME_MAX];
1483 const char *event;
1485 struct script_event *sev;
1487 StackDump(L, "Before RegEvent\n");
1489 /* Identify the object, if specified */
1490 if (luaL_getmetafield(L, 1, "_objname"))
1492 objname = luaL_checkstring(L, -1);
1493 lua_pop(L, 1);
1494 if (!strcmp("screen", objname))
1495 objname = "global";
1496 else
1497 obj = *(char **)lua_touserdata(L, 1);
1498 idx++;
1501 event = luaL_checkstring(L, idx++);
1502 snprintf(evbuf, SEVNAME_MAX, "%s_%s", objname, event);
1504 /* Check and get the handler */
1505 lh = LuaCheckHandler(L, idx++, 1);
1506 if (!lh)
1507 luaL_error(L, "Out of memory");
1509 StackDump(L, "In RegEvent\n");
1511 if (idx <= argc)
1512 priv = luaL_checkinteger(L, idx);
1514 sev = object_get_event(obj, evbuf);
1515 if (sev)
1517 struct listener *l;
1518 int ticket;
1519 l = (struct listener *)malloc(sizeof(struct listener));
1520 if (!l)
1521 return luaL_error(L, "Out of memory");
1522 l->priv = priv;
1523 l->bd = &lua_binding;
1524 l->handler = (void *)lh;
1525 register_listener(sev, l);
1526 /* Return the ticket for un-register */
1527 push_callback(L, &l);
1528 ticket = lua_gettop(L);
1530 LuaRegAutoUnHook(L, lh, ticket);
1532 else
1533 return luaL_error(L, "Invalid event specified: %s for object %s", event, objname);
1535 StackDump(L, "After RegEvent\n");
1536 return 1;
1539 /** }}} */
1541 struct binding lua_binding =
1543 "lua", /*name*/
1544 0, /*inited*/
1545 0, /*registered*/
1546 LuaInit,
1547 LuaFinit,
1548 LuaCall,
1549 LuaSource,
1550 LuaDispatch,
1551 0, /*b_next*/