Get rid of some codes that no longer needed.
[screen-lua.git] / src / lua.c
blobb69f2e30abc007f8ff4057be144b84891d24b194
1 /* Lua scripting support
3 * Copyright (c) 2008 Sadrul Habib Chowdhury (sadrul@users.sf.net)
4 * Copyright (c) 2009
5 * Sadrul Habib Chowdhury (sadrul@users.sf.net)
6 * Rui Guo (firemeteor.guo@gmail.com)
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 3, or (at your option)
11 * any later version.
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
18 * You should have received a copy of the GNU General Public License
19 * along with this program (see the file COPYING); if not, write to the
20 * Free Software Foundation, Inc.,
21 * 51 Franklin Street, Fifth Floor, Boston, MA 02111-1301 USA
23 ****************************************************************
25 #include <sys/types.h>
26 #include "config.h"
27 #include "screen.h"
28 #include <sys/stat.h>
29 #include <unistd.h>
31 #include <stdio.h>
32 #include <string.h>
33 #include <stdlib.h>
35 #include "extern.h"
36 #include "logfile.h"
38 #include <lua.h>
39 #include <lauxlib.h>
40 #include <lualib.h>
42 static int StackDump(lua_State *L, const char *message)
44 FILE *f = fopen("/tmp/debug/stack", "ab");
45 int i = lua_gettop(L);
46 if (message)
47 fprintf(f, "%s", message);
48 while (i)
50 int t = lua_type(L, i);
51 switch (t)
53 case LUA_TSTRING:
54 fprintf(f, "String: %s\n", lua_tostring(L, i));
55 break;
57 case LUA_TBOOLEAN:
58 fprintf(f, "Boolean: %s\n", lua_toboolean(L, i) ? "true" : "false");
59 break;
61 case LUA_TNUMBER:
62 fprintf(f, "Number: %g\n", lua_tonumber(L, i));
63 break;
65 default:
66 fprintf(f, "Type: %s\n", lua_typename(L, t));
68 i--;
70 if (message)
71 fprintf(f, "----\n");
72 fclose(f);
73 return 0;
76 extern struct win *windows, *fore;
77 extern struct display *displays, *display;
78 extern struct LayFuncs WinLf;
79 extern struct layer *flayer;
80 extern void AppendWinMsgRend(const char *str, const char *color);
81 extern void FocusCanvas(struct canvas *cv);
83 static int LuaDispatch(void *handler, const char *params, va_list va);
84 static int LuaRegEvent(lua_State *L);
85 static void LuaShowErr(lua_State *L);
86 struct binding lua_binding;
88 enum
90 LUA_HANDLER_TYPE_N = 1,
91 LUA_HANDLER_TYPE_F
94 struct lua_handler
96 int type;
97 lua_State *L;
98 union
100 const char *name;
101 int reference;
102 } u;
105 typedef struct lua_handler *lua_handler;
106 void LuaPushHandler(lua_handler lh);
107 void LuaHUnRef(lua_State *L, int key);
108 lua_handler LuaCheckHandler(lua_State *L, int idx, int ref);
110 lua_handler
111 LuaAllocHandler(lua_State *L, const char *name, int ref)
113 struct lua_handler *lh;
114 lh = (struct lua_handler*) malloc(sizeof(struct lua_handler));
115 if (!lh)
116 return NULL;
118 lh->L = L;
119 if (name)
121 lh->type = LUA_HANDLER_TYPE_N;
122 lh->u.name = SaveStr(name);
124 else
126 lh->type = LUA_HANDLER_TYPE_F;
127 lh->u.reference = ref;
130 return lh;
133 void
134 LuaFreeHandler(lua_State *L, struct lua_handler **lh)
136 if ((*lh)->type == LUA_HANDLER_TYPE_N)
137 Free((*lh)->u.name)
138 else
140 LuaHUnRef(L, (*lh)->u.reference);
141 (*lh)->u.reference = 0;
143 Free(*lh);
145 /** Template {{{ */
147 #define CHECK_TYPE(name, type) \
148 static type * \
149 check_##name(lua_State *L, int index) \
151 struct broker **broker; \
152 type *var; \
153 luaL_checktype(L, index, LUA_TUSERDATA); \
154 broker = (struct broker **) luaL_checkudata(L, index, #name); \
155 if (broker) { \
156 var = (type *)get_broker_obj(broker); \
158 if (!broker || !*broker) \
159 luaL_typerror(L, index, #name); \
160 return var; \
163 #define PUSH_TYPE(name, type) \
164 static void \
165 push_##name(lua_State *L, type **t) \
167 if (!t || !*t) \
168 lua_pushnil(L); \
169 else \
171 struct broker **r; \
172 r = (struct broker **)lua_newuserdata(L, sizeof(struct broker *)); \
173 *r = get_obj_broker(*t); \
174 luaL_getmetatable(L, #name); \
175 lua_setmetatable(L,-2); \
179 /* Much of the following template comes from:
180 * http://lua-users.org/wiki/BindingWithMembersAndMethods
183 static int get_int (lua_State *L, void *v)
185 lua_pushinteger (L, *(int*)v);
186 return 1;
189 static int set_int (lua_State *L, void *v)
191 *(int*)v = luaL_checkint(L, 3);
192 return 0;
195 static int get_number (lua_State *L, void *v)
197 lua_pushnumber(L, *(lua_Number*)v);
198 return 1;
201 static int set_number (lua_State *L, void *v)
203 *(lua_Number*)v = luaL_checknumber(L, 3);
204 return 0;
207 static int get_string (lua_State *L, void *v)
209 lua_pushstring(L, (char*)v );
210 return 1;
213 static int set_string (lua_State *L, void *v)
215 *(const char**)v = luaL_checkstring(L, 3);
216 return 0;
219 typedef int (*Xet_func) (lua_State *L, void *v);
221 /* member info for get and set handlers */
222 struct Xet_reg
224 const char *name; /* member name */
225 Xet_func func; /* get or set function for type of member */
226 size_t offset; /* offset of member within the struct */
227 int (*absolute)(lua_State *);
230 static void Xet_add (lua_State *L, const struct Xet_reg *l)
232 if (!l)
233 return;
234 for (; l->name; l++)
236 lua_pushstring(L, l->name);
237 lua_pushlightuserdata(L, (void*)l);
238 lua_settable(L, -3);
242 static int Xet_call (lua_State *L)
244 /* for get: stack has userdata, index, lightuserdata */
245 /* for set: stack has userdata, index, value, lightuserdata */
246 const struct Xet_reg *m = (const struct Xet_reg *)lua_touserdata(L, -1); /* member info */
247 void *obj;
248 lua_pop(L, 1); /* drop lightuserdata */
249 luaL_checktype(L, 1, LUA_TUSERDATA);
250 if (m->absolute)
251 return m->absolute(L);
252 obj = get_broker_obj((struct broker **)lua_touserdata(L, 1));
253 return m->func(L, (char *)obj + m->offset);
256 static int index_handler (lua_State *L)
258 /* stack has userdata, index */
259 lua_pushvalue(L, 2); /* dup index */
260 lua_rawget(L, lua_upvalueindex(1)); /* lookup member by name */
261 if (!lua_islightuserdata(L, -1))
263 lua_pop(L, 1); /* drop value */
264 lua_pushvalue(L, 2); /* dup index */
265 lua_gettable(L, lua_upvalueindex(2)); /* else try methods */
266 if (lua_isnil(L, -1)) /* invalid member */
267 luaL_error(L, "cannot get member '%s'", lua_tostring(L, 2));
268 return 1;
270 return Xet_call(L); /* call get function */
273 static int newindex_handler (lua_State *L)
275 /* stack has userdata, index, value */
276 lua_pushvalue(L, 2); /* dup index */
277 lua_rawget(L, lua_upvalueindex(1)); /* lookup member by name */
278 if (!lua_islightuserdata(L, -1)) /* invalid member */
279 luaL_error(L, "cannot set member '%s'", lua_tostring(L, 2));
280 return Xet_call(L); /* call set function */
283 static int
284 struct_register(lua_State *L, const char *name, const luaL_reg fn_methods[], const luaL_reg meta_methods[],
285 const struct Xet_reg setters[], const struct Xet_reg getters[])
287 int metatable, methods;
289 /* create methods table & add it to the table of globals */
290 luaL_register(L, name, fn_methods);
291 methods = lua_gettop(L);
293 /* create metatable & add it to the registry */
294 luaL_newmetatable(L, name);
295 luaL_register(L, 0, meta_methods); /* fill metatable */
297 /* To identify the type of object */
298 lua_pushstring(L, "_objname");
299 lua_pushstring(L, name);
300 lua_rawset(L, -3);
302 metatable = lua_gettop(L);
304 lua_pushliteral(L, "__metatable");
305 lua_pushvalue(L, methods); /* dup methods table*/
306 lua_rawset(L, metatable); /* hide metatable:
307 metatable.__metatable = methods */
309 lua_pushliteral(L, "__index");
310 lua_pushvalue(L, metatable); /* upvalue index 1 */
311 Xet_add(L, getters); /* fill metatable with getters */
312 lua_pushvalue(L, methods); /* upvalue index 2 */
313 lua_pushcclosure(L, index_handler, 2);
314 lua_rawset(L, metatable); /* metatable.__index = index_handler */
316 lua_pushliteral(L, "__newindex");
317 lua_newtable(L); /* table for members you can set */
318 Xet_add(L, setters); /* fill with setters */
319 lua_pushcclosure(L, newindex_handler, 1);
320 lua_rawset(L, metatable); /* metatable.__newindex = newindex_handler */
322 /* FIXME: Why do we leave an element on the stack? */
323 lua_pop(L, 1); /* drop metatable */
324 return 1; /* return methods on the stack */
327 /** }}} */
329 /** Callback {{{ */
330 static void
331 push_callback(lua_State *L, struct listener **t)
333 if (!t || !*t)
334 lua_pushnil(L);
335 else
337 struct listener **r;
338 r = (struct listener **)lua_newuserdata(L, sizeof(struct listener *));
339 *r = *t;
340 luaL_getmetatable(L, "callback");
341 lua_setmetatable(L,-2);
346 static int
347 internal_unhook(lua_State *L, int warn)
349 /*Emulate check_callback() */
350 struct listener **ppl;
351 luaL_checktype(L, 1, LUA_TUSERDATA);
352 ppl = (struct listener **) luaL_checkudata(L, 1, "callback");
354 if (!ppl)
355 luaL_typerror(L, 1, "callback");
357 if (!*ppl)
359 if (warn)
361 lua_pushboolean(L, 0);
362 lua_pushstring(L, "Callback already unhooked.");
363 LuaShowErr(L);
366 else
368 LuaFreeHandler(L, (lua_handler *)&(*ppl)->handler);
369 unregister_listener(*ppl);
370 *ppl = 0;
371 if (warn)
372 lua_pushboolean(L, 1);
374 return warn != 0;
376 static int
377 callback_unhook(lua_State *L)
379 return internal_unhook(L, 1);
382 static const luaL_reg callback_methods[] = {
383 {"unhook", callback_unhook},
384 {0, 0}
388 callback_collect(lua_State *L)
390 return internal_unhook(L, 0);
393 static const luaL_reg callback_metamethods[] = {
394 {"__gc", callback_collect},
395 {0, 0}
398 static const struct Xet_reg callback_setters[] = {
399 {0, 0}
402 static const struct Xet_reg callback_getters[] = {
403 {0, 0}
407 /** }}} */
409 static int
410 screen_object_collect(lua_State *L)
412 struct broker **pbroker;
413 luaL_checktype(L, 1, LUA_TUSERDATA);
414 pbroker = (struct broker **)lua_touserdata(L, 1);
415 broker_unref(pbroker);
416 return 0;
419 /** Window {{{ */
421 PUSH_TYPE(window, struct win)
423 CHECK_TYPE(window, struct win)
425 static int get_window(lua_State *L, void *v)
427 push_window(L, (struct win **)v);
428 return 1;
431 static int
432 window_change_title(lua_State *L)
434 struct win *w = check_window(L, 1);
435 unsigned int len;
436 const char *title = luaL_checklstring(L, 3, &len);
437 ChangeAKA(w, (char *)title, len);
438 return 0;
441 static int
442 window_change_number(lua_State *L)
444 struct win *w = check_window(L, 1);
445 int newnum = luaL_checkint(L, 3);
446 ChangeWinNum(w->w_number, newnum);
447 return 0;
450 static int
451 window_get_monitor_status(lua_State *L)
453 struct win *w = check_window(L, 1);
454 int activity = luaL_checkint(L, 2);
455 if (activity)
456 /*monitor*/
457 lua_pushinteger(L, w->w_monitor != MON_OFF);
458 else
459 /*silence*/
460 lua_pushinteger(L, w->w_silence == SILENCE_ON ? w->w_silencewait: 0);
462 return 1;
465 static int
466 window_stuff(lua_State *L)
468 unsigned int len;
469 struct layer *oldflayer = flayer;
470 struct win *w = check_window(L, 1);
471 const char *str = luaL_checklstring(L, 2, &len);
473 flayer = &w->w_layer;
474 while(len)
475 LayProcess((char **)&str, (int *) &len);
476 flayer = oldflayer;
477 return 0;
480 static int
481 window_activate(lua_State *L)
483 struct win *w = check_window(L, 1);
484 SetForeWindow(w);
485 return 0;
488 static void push_canvas(lua_State *L, struct canvas **t);
490 static int
491 window_get_showing_canvases(lua_State *L)
493 struct win *w = check_window(L, 1);
494 int count = 0;
495 struct canvas *cv = w->w_layer.l_cvlist;
496 if (!cv) {
497 lua_pushnil(L);
498 return 1;
500 lua_newtable(L);
501 while (cv) {
502 lua_pushinteger(L, count++);
503 push_canvas(L, &cv);
504 lua_settable(L, -3);
505 cv = cv->c_lnext;
508 return 1;
511 static int
512 window_getlines(lua_State *L)
514 struct win *w = check_window(L, 1);
515 int i;
516 lua_newtable(L);
517 for (i = 0; i < fore->w_height; i++)
519 char *p = (char *)w->w_mlines[i].image;
520 int k, save;
521 for (k = fore->w_width - 1; k >= 0 && p[k] == ' '; k--)
523 k +=(p[k] != ' ');
524 save = p[k];
525 p[k] = 0;
526 lua_pushinteger(L, i);
527 lua_pushstring(L, p);
528 lua_settable(L, -3);
529 p[k] = save;
532 return 1;
535 static int
536 window_gethistory(lua_State *L)
538 struct win *w = check_window(L, 1);
539 int i;
540 lua_newtable(L);
541 for (i = 0; i < fore->w_height; i++)
543 char *p = (char *) w->w_hlines[(w->w_histidx + i) % w->w_histheight].image;
544 int k, save;
545 for (k = fore->w_width - 1; k >= 0 && p[k] == ' '; k--)
547 k +=(p[k] != ' ');
548 save = p[k];
549 p[k] = 0;
550 lua_pushinteger(L, i);
551 lua_pushstring(L, p);
552 lua_settable(L, -3);
553 p[k] = save;
556 return 1;
559 static const luaL_reg window_methods[] = {
560 {"get_monitor_status", window_get_monitor_status},
561 {"showing_canvases", window_get_showing_canvases},
562 {"stuff", window_stuff},
563 {"activate", window_activate},
564 {"get_lines", window_getlines},
565 {"get_history", window_gethistory},
566 {"hook", LuaRegEvent},
567 {0, 0}
570 static int
571 window_tostring(lua_State *L)
573 char str[128];
574 struct win *w = check_window(L, 1);
575 snprintf(str, sizeof(str), "{window #%d: '%s'}", w->w_number, w->w_title);
576 lua_pushstring(L, str);
577 return 1;
580 static int
581 window_equality(lua_State *L)
583 struct win *w1 = check_window(L, 1), *w2 = check_window(L, 2);
584 lua_pushboolean(L, (w1 == w2 || (w1 && w2 && w1->w_number == w2->w_number)));
585 return 1;
588 static const luaL_reg window_metamethods[] = {
589 {"__tostring", window_tostring},
590 {"__eq", window_equality},
591 {"__gc", screen_object_collect},
592 {0, 0}
595 static const struct Xet_reg window_setters[] = {
596 {"title", 0, 0, window_change_title/*absolute setter*/},
597 {"number", 0, 0, window_change_number/*absolute setter*/},
598 {0, 0}
601 static const struct Xet_reg window_getters[] = {
602 {"title", get_string, offsetof(struct win, w_title) + 8},
603 {"number", get_int, offsetof(struct win, w_number)},
604 {"dir", get_string, offsetof(struct win, w_dir)},
605 {"tty", get_string, offsetof(struct win, w_tty)},
606 {"pid", get_int, offsetof(struct win, w_pid)},
607 {"group", get_window, offsetof(struct win, w_group)},
608 {"bell", get_int, offsetof(struct win, w_bell)},
609 {0, 0}
613 /** }}} */
615 /** AclUser {{{ */
617 PUSH_TYPE(user, struct acluser)
619 CHECK_TYPE(user, struct acluser)
621 static int
622 get_user(lua_State *L, void *v)
624 push_user(L, (struct acluser **)v);
625 return 1;
628 static const luaL_reg user_methods[] = {
629 {0, 0}
632 static int
633 user_tostring(lua_State *L)
635 char str[128];
636 struct acluser *u = check_user(L, 1);
637 snprintf(str, sizeof(str), "{user '%s'}", u->u_name);
638 lua_pushstring(L, str);
639 return 1;
642 static const luaL_reg user_metamethods[] = {
643 {"__tostring", user_tostring},
644 {"__gc", screen_object_collect},
645 {0, 0}
648 static const struct Xet_reg user_setters[] = {
649 {0, 0}
652 static const struct Xet_reg user_getters[] = {
653 {"name", get_string, offsetof(struct acluser, u_name)},
654 {"password", get_string, offsetof(struct acluser, u_password)},
655 {0, 0}
658 /** }}} */
660 static int get_display(lua_State *L, void *v);
661 /** Canvas {{{ */
663 PUSH_TYPE(canvas, struct canvas)
665 CHECK_TYPE(canvas, struct canvas)
667 static int
668 get_canvas(lua_State *L, void *v)
670 push_canvas(L, (struct canvas **)v);
671 return 1;
674 static int
675 canvas_select(lua_State *L)
677 struct canvas *c = check_canvas(L, 1);
678 if (!display || D_forecv == c)
679 return 0;
680 /* FIXME: why do we need this? */
681 SetCanvasWindow(c, Layer2Window(c->c_layer));
683 FocusCanvas(c);
684 return 0;
687 static int
688 canvas_split(lua_State *L)
690 struct canvas *c = check_canvas(L, 1);
691 struct canvas *oldfore = D_forecv;
692 D_forecv = c;
693 int hori = lua_toboolean(L, 2);
694 if (hori)
695 AddCanvas(SLICE_HORI);
696 else
697 AddCanvas(SLICE_VERT);
698 Activate(-1);
699 D_forecv = oldfore;
700 return 0;
703 static int
704 canvas_showwin(lua_State *L)
706 struct canvas *c = check_canvas(L, 1);
707 if (lua_isnil(L, 2))
708 SetCanvasWindow(c, 0);
709 else
711 struct win *w = check_window(L, 2);
712 SetCanvasWindow(c, w);
714 return 0;
717 static const luaL_reg canvas_methods[] = {
718 {"select", canvas_select},
719 {"split", canvas_split},
720 {"showwin", canvas_showwin},
721 {0, 0}
724 static const luaL_reg canvas_metamethods[] = {
725 {"__gc", screen_object_collect},
726 {0, 0}
729 extern struct mchar mchar_so;
730 static int
731 canvas_update_caption(lua_State *L)
733 struct canvas *cv = check_canvas(L, 1);
734 unsigned int len;
735 const char *caption = luaL_checklstring(L, 3, &len);
736 int l, padlen;
737 padlen = cv->c_xe - cv->c_xs +
738 (display ? (cv->c_xe + 1 < D_width || D_CLP): 0);
739 struct win *w = Layer2Window(cv->c_layer);
740 char * buf = MakeWinMsgEv((char *)caption, w, '%', padlen, &cv->c_captev, 0);
741 if (cv->c_captev.timeout.tv_sec)
742 evenq(&cv->c_captev);
743 l = strlen(buf);
745 GotoPos(cv->c_xs, cv->c_ye+1);
746 /*XXX:what does this mean?*/
747 SetRendition(&mchar_so);
748 if (l > cv->c_xe - cv->c_xs + 1)
749 l = cv->c_xe - cv->c_xs + 1;
750 PutWinMsg(buf, cv->c_xs, l);
751 l += cv->c_xs;
752 for (; l <= cv->c_xe; l++)
753 PUTCHARLP(' ');
755 return 0;
758 static const struct Xet_reg canvas_setters[] = {
759 {"caption", 0, 0, canvas_update_caption/*absolute setter*/},
760 {0, 0}
763 static int
764 canvas_get_window(lua_State *L)
766 struct canvas *c = check_canvas(L, 1);
767 struct win *win = Layer2Window(c->c_layer);
768 if (win)
769 push_window(L, &win);
770 else
771 lua_pushnil(L);
772 return 1;
775 static const struct Xet_reg canvas_getters[] = {
776 {"next", get_canvas, offsetof(struct canvas, c_next)},
777 {"xoff", get_int, offsetof(struct canvas, c_xoff)},
778 {"yoff", get_int, offsetof(struct canvas, c_yoff)},
779 {"xs", get_int, offsetof(struct canvas, c_xs)},
780 {"ys", get_int, offsetof(struct canvas, c_ys)},
781 {"xe", get_int, offsetof(struct canvas, c_xe)},
782 {"ye", get_int, offsetof(struct canvas, c_ye)},
783 {"window", 0, 0, canvas_get_window},
784 {"display", get_display, offsetof(struct canvas, c_display)},
785 {0, 0}
788 /** }}} */
790 /** Layout {{{ */
792 PUSH_TYPE(layout, struct layout)
793 CHECK_TYPE(layout, struct layout)
795 static const struct Xet_reg layout_getters[] = {
796 {"title", get_string, offsetof(struct layout, lay_title)},
797 {"number", get_string, offsetof(struct layout, lay_title)},
798 {"autosave", get_string, offsetof(struct layout, lay_autosave)},
799 {0,0}
803 layout_change_title(lua_State *L)
805 struct layout *lay = check_layout(L, 1);
806 unsigned int len;
807 const char *title = luaL_checklstring(L, 3, &len);
808 free(lay->lay_title);
809 lay->lay_title= SaveStr(title);
810 return 0;
813 void LayoutChangeNumber(struct layout *lay, int newnum);
816 layout_change_number(lua_State *L)
818 struct layout *lay = check_layout(L, 1);
819 int newnum = luaL_checkint(L, 3);
820 LayoutChangeNumber(lay, newnum);
821 return 0;
824 static const struct Xet_reg layout_setters[] = {
825 {"title", 0, 0, layout_change_title/*absolute setter*/},
826 {"number", 0, 0, layout_change_number/*absolute setter*/},
827 {"autosave", get_string, offsetof(struct layout, lay_autosave)},
828 {0, 0}
832 layout_select(lua_State *L)
834 struct layout *lay = check_layout(L, 1);
835 if (!display) return 0;
836 LoadLayout(lay, &D_canvas);
837 Activate(0);
838 return 0;
841 static const luaL_reg layout_methods[] = {
842 {"select", layout_select},
843 {0, 0}
846 static const luaL_reg layout_metamethods[] = {
847 {"__gc", screen_object_collect},
848 {0, 0}
851 static int
852 get_layout(lua_State *L, void *v)
854 push_layout(L, (struct layout **)v);
855 return 1;
858 /** }}} */
860 /** Display {{{ */
862 PUSH_TYPE(display, struct display)
864 CHECK_TYPE(display, struct display)
866 static int
867 get_display(lua_State *L, void *v)
869 push_display(L, (struct display **)v);
870 return 1;
873 static int
874 display_get_canvases(lua_State *L)
876 struct display *d;
877 struct canvas *iter;
878 int count;
880 d = check_display(L, 1);
881 lua_newtable(L);
882 for (iter = d->d_cvlist, count = 0; iter; iter = iter->c_next, count++) {
883 lua_pushinteger(L, count);
884 push_canvas(L, &iter);
885 lua_settable(L, -3);
888 return 1;
891 static int
892 display_top_canvas(lua_State *L)
894 struct display *d;
895 d = check_display(L, 1);
896 push_canvas(L, &d->d_cvlist);
898 return 1;
901 static int
902 display_bot_canvas(lua_State *L)
904 struct display *d;
905 struct canvas *c;
906 d = check_display(L, 1);
908 for (c = d->d_cvlist; c->c_next; c = c->c_next)
910 push_canvas(L, &c);
912 return 1;
915 static const luaL_reg display_methods[] = {
916 {"get_canvases", display_get_canvases},
917 {"top_canvas", display_top_canvas},
918 {"bottom_canvas", display_bot_canvas},
919 {0, 0}
922 static int
923 display_tostring(lua_State *L)
925 char str[128];
926 struct display *d = check_display(L, 1);
927 snprintf(str, sizeof(str), "{display: tty = '%s', term = '%s'}", d->d_usertty, d->d_termname);
928 lua_pushstring(L, str);
929 return 1;
932 static const luaL_reg display_metamethods[] = {
933 {"__tostring", display_tostring},
934 {"__gc", screen_object_collect},
935 {0, 0}
938 static int
939 display_new_idle_timeout(lua_State *L)
941 struct display *disp = check_display(L, 1);
942 int timeout = luaL_checkinteger(L, 3) * 1000;
943 struct event *ev = &disp->d_idleev;
944 if (timeout > 0)
946 SetTimeout(ev, timeout);
947 if (!ev->queued)
948 evenq(ev);
950 else
951 evdeq(ev);
953 return 0;
956 static const struct Xet_reg display_setters[] = {
957 {"idle_timeout", 0, 0, display_new_idle_timeout/*absolute setter*/},
958 {0, 0}
961 static const struct Xet_reg display_getters[] = {
962 {"tty", get_string, offsetof(struct display, d_usertty)},
963 {"term", get_string, offsetof(struct display, d_termname)},
964 {"fore", get_window, offsetof(struct display, d_fore)},
965 {"other", get_window, offsetof(struct display, d_other)},
966 {"width", get_int, offsetof(struct display, d_width)},
967 {"height", get_int, offsetof(struct display, d_height)},
968 {"user", get_user, offsetof(struct display, d_user)},
969 {"layout", get_layout, offsetof(struct display, d_layout)},
970 {0, 0}
973 /** }}} */
975 /** Screen {{{ */
977 static int
978 screen_get_windows(lua_State *L)
980 struct win *iter;
981 int count;
983 lua_newtable(L);
984 for (iter = windows, count = 0; iter; iter = iter->w_next, count++) {
985 lua_pushinteger(L, iter->w_number);
986 push_window(L, &iter);
987 lua_settable(L, -3);
990 return 1;
993 static int
994 screen_get_displays(lua_State *L)
996 struct display *iter;
997 int count;
999 lua_newtable(L);
1000 for (iter = displays, count = 0; iter; iter = iter->d_next, count++) {
1001 lua_pushinteger(L, count);
1002 push_display(L, &iter);
1003 lua_settable(L, -3);
1006 return 1;
1009 extern struct layout *layouts;
1010 static int
1011 screen_get_layouts(lua_State *L)
1013 struct layout *iter;
1014 int count;
1016 lua_newtable(L);
1017 for (iter = layouts, count = 0; iter; iter = iter->lay_next, count++) {
1018 lua_pushinteger(L, iter->lay_number);
1019 push_layout(L, &iter);
1020 lua_settable(L, -3);
1023 return 1;
1026 static int
1027 screen_get_display(lua_State *L)
1029 push_display(L, &display);
1030 return 1;
1033 static int
1034 screen_exec_command(lua_State *L)
1036 const char *command;
1037 unsigned int len;
1039 command = luaL_checklstring(L, 1, &len);
1040 if (command)
1041 RcLine((char *)command, len);
1043 return 0;
1046 static int
1047 screen_append_msg(lua_State *L)
1049 const char *msg, *color;
1050 unsigned int len;
1051 msg = luaL_checklstring(L, 1, &len);
1052 if (lua_isnil(L, 2))
1053 color = NULL;
1054 else
1055 color = luaL_checklstring(L, 2, &len);
1056 AppendWinMsgRend(msg, color);
1057 return 0;
1060 void
1061 script_input_fn(char *buf, int len, char *priv)
1063 lua_handler lh = (lua_handler)priv;
1064 lua_State *L = lh->L;
1066 LuaPushHandler(lh);
1067 lua_pushstring(L, buf);
1068 if (lua_pcall(L, 1, 0, 0) == LUA_ERRRUN)
1070 if(lua_isstring(L, -1))
1072 LuaShowErr(L);
1075 LuaFreeHandler(L, &lh);
1078 static int
1079 screen_input(lua_State *L)
1081 char *ss;
1082 int n;
1083 const char * prompt = NULL, *prefill = NULL;
1084 lua_handler lh;
1086 prompt = luaL_checkstring(L, 1);
1087 lh = LuaCheckHandler(L, 2, 1);
1088 if (!lh)
1089 luaL_error(L, "Out of Memory");
1091 if (lua_gettop(L) >= 3)
1092 prefill = luaL_checkstring(L, 3);
1095 Input((char *)prompt, 100, INP_COOKED, script_input_fn, (char *)lh, 0);
1097 if (!prefill)
1098 return 0;
1099 for (; *prefill; prefill++)
1101 if ((*(unsigned char *)prefill & 0x7f) < 0x20 || *prefill == 0x7f)
1102 continue;
1103 ss = (char *)prefill;
1104 n = 1;
1105 LayProcess(&ss, &n);
1107 return 0;
1110 static void
1111 sev_schedule_fn(struct event *ev, char *data)
1113 lua_handler lh = (lua_handler)data;
1114 lua_State *L = lh->L;
1115 evdeq(ev);
1116 Free(ev);
1118 LuaPushHandler(lh);
1119 if (lua_pcall(L, 1, 0, 0) == LUA_ERRRUN)
1121 if(lua_isstring(L, -1))
1123 LuaShowErr(L);
1126 LuaFreeHandler(L, &lh);
1129 static int
1130 screen_schedule(lua_State *L)
1132 int timeout = luaL_checkinteger(L, 1);
1133 lua_handler lh = LuaCheckHandler(L, 2, 1);
1134 struct event *ev;
1135 if (timeout <= 0)
1136 return 0;
1138 ev = (struct event *) calloc(1, sizeof(struct event));
1139 if (!ev)
1141 LuaFreeHandler(L, &lh);
1142 luaL_error(L, "Out of Memory");
1145 ev->type = EV_TIMEOUT;
1146 ev->data = (char *)lh;
1147 ev->handler = sev_schedule_fn;
1148 evenq(ev);
1149 SetTimeout(ev, timeout * 1000);
1150 return 0;
1153 static const luaL_reg screen_methods[] = {
1154 {"windows", screen_get_windows},
1155 {"displays", screen_get_displays},
1156 {"layouts", screen_get_layouts},
1157 {"display", screen_get_display},
1158 {"command", screen_exec_command},
1159 {"append_msg", screen_append_msg},
1160 {"hook", LuaRegEvent},
1161 {"input", screen_input},
1162 {"schedule", screen_schedule},
1163 {0, 0}
1166 static const luaL_reg screen_metamethods[] = {
1167 {0, 0}
1170 static const struct Xet_reg screen_setters[] = {
1171 {0, 0}
1174 static const struct Xet_reg screen_getters[] = {
1175 {0, 0}
1178 /** }}} */
1180 /** Public functions {{{ */
1182 /* FIXME: This code only tracks one unhook ticket for a lua func.
1183 * So it does not work if one func is registered more than one times. */
1184 static void
1185 prepare_weak_table(lua_State *L, const char *name, const char *mode)
1187 luaL_getmetatable(L, "screen");
1189 lua_pushstring(L, name);
1190 lua_newtable(L);
1192 /* prepare a metatable to indicate weak table */
1193 lua_newtable(L);
1194 lua_pushstring(L, "__mode");
1195 lua_pushstring(L, mode);
1196 lua_rawset(L, -3);
1197 /* Mark weak table */
1198 lua_setmetatable(L, -2);
1199 lua_rawset(L, -3);
1200 lua_pop(L, 1);
1203 struct sfile {
1204 lua_State *L;
1205 ino_t inode;
1206 struct sfile *next;
1209 struct sfile *scripts = NULL;
1211 int LuaInit(void)
1213 return 0;
1215 lua_State *
1216 LuaNewState(struct sfile *slist)
1218 lua_State *L = luaL_newstate();
1220 luaL_openlibs(L);
1222 #define REGISTER(X) struct_register(L, #X , X ## _methods, X##_metamethods, X##_setters, X##_getters)
1224 REGISTER(screen);
1225 REGISTER(window);
1226 REGISTER(display);
1227 REGISTER(user);
1228 REGISTER(canvas);
1229 REGISTER(callback);
1231 /* To store handler funcs */
1233 /*_two kinds of information are mantained:
1235 * funcreg[key]->func
1236 * The 'func' part of the tables are weak. That means the registered funcs
1237 * will be collected once the func is no longer available (e.g. overwritten
1238 * by a new instance of the script)
1240 * To make this process happens faster, GC is forced at the end of each
1241 * source.
1242 * TODO: What if some events are triggered within the sourcing
1243 * procedure?
1244 * */
1245 prepare_weak_table(L, "_funcreg", " ");
1247 /* funcunhook[func]->listener
1248 * The listener is the unhook ticket of the hook. which should be collected
1249 * once the func is collected. The gc metamethod will be triggered
1250 * accordingly. */
1251 prepare_weak_table(L, "_funcunhook", " ");
1253 /* Hold a reference to the sfile structure to ease unloading the script.*/
1254 luaL_getmetatable(L, "screen");
1255 lua_pushstring(L, "_sfile");
1256 lua_pushlightuserdata(L, slist);
1257 lua_rawset(L, -3);
1258 lua_pop(L, 1);
1259 slist->L = L;
1260 return L;
1263 /* An error message on top of the stack. */
1264 static void
1265 LuaShowErr(lua_State *L)
1267 struct display *d = display;
1268 unsigned int len;
1269 const char *message = luaL_checklstring(L, -1, &len);
1270 lua_pop(L, 1);
1271 LMsg(0, "%s", message ? message : "Unknown error");
1272 display = d;
1275 void
1276 LuaUnload(struct sfile *slist)
1278 struct sfile **plist = &scripts;
1279 lua_close(slist->L);
1280 while (*plist) {
1281 if (*plist == slist) {
1282 *plist = slist->next;
1283 break;
1285 plist = &(*plist)->next;
1287 free(slist);
1290 /* FIXME: Think about this: will it affect the registered handlers?*/
1291 int LuaSource(const char *file, int async)
1293 struct stat st;
1294 if (stat(file, &st) == -1)
1295 Msg(errno, "Error loading lua script file '%s'", file);
1296 else
1298 int len = strlen(file);
1299 ino_t inode = st.st_ino;
1300 struct sfile *slist = scripts;
1302 if (len < 4 || strncmp(file + len - 4, ".lua", 4) != 0)
1303 return 0;
1305 while (slist) {
1306 if (slist->inode == inode)
1307 break;
1308 slist = slist->next;
1310 if (slist)
1311 LuaUnload(slist);
1313 slist = (struct sfile *) malloc(sizeof(struct sfile));
1314 slist->next = scripts;
1315 LuaNewState(slist);
1316 slist->inode = inode;
1318 if (luaL_dofile(slist->L, file) && lua_isstring(slist->L, -1))
1320 LuaShowErr(slist->L);
1321 lua_close(slist->L);
1322 free(slist);
1323 return 0;
1325 else
1327 /* It seems that I need two GC passes to really collect the unhook
1328 * ticket, after changing the reference to ticket in the
1329 * 'funcunhook' table from weak to strong. This should not be
1330 * harmful, but how can I make sure that two passes is enough?
1332 * Possible reason:
1333 * This seems reasonable, since the first pass will collect the func
1334 * itself and make the ticket garbage, and the second pass will
1335 * collect the ticket itself.
1337 * TODO: check this out. maybe ask some lua gurus. */
1338 lua_gc(slist->L, LUA_GCCOLLECT, 0);
1339 lua_gc(slist->L, LUA_GCCOLLECT, 0);
1340 scripts = slist;
1342 return 1;
1344 return 0;
1347 int LuaFinit(void)
1349 struct sfile *slist = scripts;
1350 while (slist) {
1351 struct sfile *tmp = slist;
1352 lua_close(slist->L);
1353 slist = slist->next;
1354 free(tmp);
1356 scripts = 0;
1357 return 0;
1360 static void
1361 push_stringarray(lua_State *L, char **args)
1363 int i;
1364 lua_newtable(L);
1365 for (i = 1; args && *args; i++) {
1366 lua_pushinteger(L, i);
1367 lua_pushstring(L, *args++);
1368 lua_settable(L, -3);
1373 LuaPushParams(lua_State *L, const char *params, va_list va)
1375 int num = 0;
1376 while (*params)
1378 switch (*params)
1380 case 's':
1381 lua_pushstring(L, va_arg(va, char *));
1382 break;
1383 case 'S':
1384 push_stringarray(L, va_arg(va, char **));
1385 break;
1386 case 'i':
1387 lua_pushinteger(L, va_arg(va, int));
1388 break;
1389 case 'd':
1391 struct display *d = va_arg(va, struct display *);
1392 push_display(L, &d);
1393 break;
1395 case 'w':
1397 struct win *w = va_arg(va, struct win *);
1398 push_window(L, &w);
1399 break;
1401 case 'c':
1403 struct canvas *c = va_arg(va, struct canvas *);
1404 push_canvas(L, &c);
1405 break;
1408 params++;
1409 num++;
1411 return num;
1414 int LuaCall(const char *func, const char **argv)
1416 int argc;
1417 struct sfile *slist = scripts;
1418 lua_State *L = NULL;
1419 while (slist) {
1420 L = slist->L;
1421 lua_getfield(L, LUA_GLOBALSINDEX, func);
1422 if (lua_isnil(L, -1))
1424 lua_pop(L, 1);
1425 slist = slist->next;
1426 return 0;
1428 else
1429 break;
1432 if (!slist) {
1433 if (L) {
1434 lua_pushstring(L, "Could not find the script function\n");
1435 LuaShowErr(L);
1437 return 0;
1439 StackDump(L, "Before LuaCall\n");
1441 for (argc = 0; *argv; argv++, argc++)
1443 lua_pushstring(L, *argv);
1445 if (lua_pcall(L, argc, 0, 0) == LUA_ERRRUN)
1447 if(lua_isstring(L, -1))
1449 StackDump(L, "After LuaCall\n");
1450 LuaShowErr(L);
1451 return 0;
1454 return 1;
1457 /*** Lua callback handler management {{{ */
1460 LuaPushHTable(lua_State *L, int screen, const char * t)
1462 lua_pushstring(L, t);
1463 lua_rawget(L, screen);
1464 /* FIXME: Do we need to balance the stack here? */
1465 if (lua_isnil(L, -1))
1466 luaL_error(L, "Fatal! Fail to get function registeration table!");
1467 return lua_gettop(L);
1470 struct sfile *
1471 LuaGetSFile(lua_State *L)
1473 struct sfile *slist;
1474 luaL_getmetatable(L, "screen");
1475 lua_pushstring(L, "_sfile");
1476 lua_rawget(L, -1);
1477 slist = (struct sfile *)lua_touserdata(L, -1);
1478 lua_pop(L, 2);
1479 return slist;
1482 void
1483 LuaPushHandler(lua_handler lh)
1485 int funcreg;
1486 lua_State *L = lh->L;
1487 if (lh->type == LUA_HANDLER_TYPE_F)
1489 luaL_getmetatable(L, "screen");
1490 funcreg = LuaPushHTable(L, lua_gettop(L), "_funcreg");
1491 lua_rawgeti(L, funcreg, lh->u.reference);
1492 lua_replace(L, -3);
1493 lua_pop(L, 1);
1495 else
1497 lua_getfield(L, LUA_GLOBALSINDEX, lh->u.name);
1502 LuaFuncKey(lua_State *L, int idx, int ref)
1504 int key, funcreg, sc;
1505 luaL_getmetatable(L, "screen");
1506 sc = lua_gettop(L);
1507 funcreg = LuaPushHTable(L, sc, "_funcreg");
1509 lua_pushvalue(L, idx);
1510 key = luaL_ref(L, funcreg);
1511 lua_pop(L, 2);
1512 return key;
1515 void
1516 LuaHUnRef(lua_State *L, int key)
1518 int funcreg, sc;
1519 luaL_getmetatable(L, "screen");
1520 sc = lua_gettop(L);
1521 funcreg = LuaPushHTable(L, sc, "_funcreg");
1522 luaL_unref(L, funcreg, key);
1525 lua_handler
1526 LuaCheckHandler(lua_State *L, int idx, int ref)
1528 int key;
1529 if (idx < 0)
1530 idx = lua_gettop(L) + 1 - idx;
1532 if (lua_isstring(L, idx))
1534 const char * handler;
1535 /* registered with func name.*/
1536 handler = luaL_checkstring(L, idx);
1537 lua_getfield(L, LUA_GLOBALSINDEX, handler);
1538 if (!lua_isfunction(L, -1))
1539 luaL_error(L, "The specified handler %s in param #%d is not a function", handler, idx);
1540 lua_pop(L, 1);
1541 return LuaAllocHandler(L, handler, 0);
1543 else if (!lua_isfunction(L, idx))
1544 luaL_error(L, "Handler should be a function or the name of function");
1546 key = LuaFuncKey(L, idx, ref);
1547 return LuaAllocHandler(L, NULL, key);
1550 /* }}} **/
1552 static int
1553 LuaDispatch(void *handler, const char *params, va_list va)
1555 lua_handler lh = (lua_handler)handler;
1556 int argc, retvalue;
1557 lua_State *L = lh->L;
1559 StackDump(L, "before dispatch");
1561 LuaPushHandler(lh);
1562 if (lua_isnil(L, -1))
1564 lua_pop(L, 1);
1565 return 0;
1567 argc = LuaPushParams(L, params, va);
1569 if (lua_pcall(L, argc, 1, 0) == LUA_ERRRUN && lua_isstring(L, -1))
1571 StackDump(L, "After LuaDispatch\n");
1572 LuaShowErr(L);
1573 return 0;
1575 retvalue = lua_tonumber(L, -1);
1576 lua_pop(L, 1);
1577 return retvalue;
1580 /*FIXME: what if a func is registered twice or more? */
1581 void
1582 LuaRegAutoUnHook(lua_State *L, lua_handler lh, int ticket)
1584 int sc, funcunhook;
1585 luaL_getmetatable(L, "screen");
1586 sc = lua_gettop(L);
1587 funcunhook = LuaPushHTable(L, sc, "_funcunhook");
1588 LuaPushHandler(lh);
1589 lua_pushvalue(L, ticket);
1590 lua_rawset(L, funcunhook);
1591 lua_pop(L, 2);
1594 #define SEVNAME_MAX 30
1595 static int
1596 LuaRegEvent(lua_State *L)
1598 /* signature: hook(obj, event, handler, priv);
1599 * or: hook(event, handler, priv)
1600 * returns: A ticket for later unregister. */
1601 int idx = 1, argc = lua_gettop(L);
1602 unsigned int priv = 31; /* Default privilege */
1603 lua_handler lh;
1605 char *obj = NULL;
1606 const char *objname = "global";
1608 static char evbuf[SEVNAME_MAX];
1609 const char *event;
1611 struct script_event *sev;
1613 StackDump(L, "Before RegEvent\n");
1615 /* Identify the object, if specified */
1616 if (luaL_getmetafield(L, 1, "_objname"))
1618 objname = luaL_checkstring(L, -1);
1619 lua_pop(L, 1);
1620 if (!strcmp("screen", objname))
1621 objname = "global";
1622 else
1624 obj = get_broker_obj((struct broker **)lua_touserdata(L, 1));
1625 if (!obj)
1626 return luaL_error(L, "Invalid object specified");
1628 idx++;
1631 event = luaL_checkstring(L, idx++);
1632 snprintf(evbuf, SEVNAME_MAX, "%s_%s", objname, event);
1634 /* Check and get the handler */
1635 lh = LuaCheckHandler(L, idx++, 1);
1636 if (!lh)
1637 luaL_error(L, "Out of memory");
1639 StackDump(L, "In RegEvent\n");
1641 if (idx <= argc)
1642 priv = luaL_checkinteger(L, idx);
1644 sev = object_get_event(obj, evbuf);
1645 if (sev)
1647 struct listener *l;
1648 int ticket;
1649 l = (struct listener *)malloc(sizeof(struct listener));
1650 if (!l)
1651 return luaL_error(L, "Out of memory");
1652 l->priv = priv;
1653 l->bd = &lua_binding;
1654 l->handler = (void *)lh;
1655 register_listener(sev, l);
1656 /* Return the ticket for un-register */
1657 push_callback(L, &l);
1658 ticket = lua_gettop(L);
1660 LuaRegAutoUnHook(L, lh, ticket);
1662 else
1663 return luaL_error(L, "Invalid event specified: %s for object %s", event, objname);
1665 StackDump(L, "After RegEvent\n");
1666 return 1;
1669 /** }}} */
1671 struct binding lua_binding =
1673 "lua", /*name*/
1674 0, /*inited*/
1675 0, /*registered*/
1676 LuaInit,
1677 LuaFinit,
1678 LuaCall,
1679 LuaSource,
1680 LuaDispatch,
1681 0, /*b_next*/