08048ea79783affda407bed043c72b307bb768d5
[screen-lua.git] / src / lua.c
blob08048ea79783affda407bed043c72b307bb768d5
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 void push_canvas(lua_State *L, struct canvas **t);
488 static int
489 window_get_showing_canvases(lua_State *L)
491 struct win *w = check_window(L, 1);
492 int count = 0;
493 struct canvas *cv = w->w_layer.l_cvlist;
494 if (!cv) {
495 lua_pushnil(L);
496 return 1;
498 lua_newtable(L);
499 while (cv) {
500 lua_pushinteger(L, count++);
501 push_canvas(L, &cv);
502 lua_settable(L, -3);
503 cv = cv->c_lnext;
506 return 1;
509 static int
510 window_getlines(lua_State *L)
512 struct win *w = check_window(L, 1);
513 int i;
514 lua_newtable(L);
515 for (i = 0; i < fore->w_height; i++)
517 char *p = (char *)w->w_mlines[i].image;
518 int k, save;
519 for (k = fore->w_width - 1; k >= 0 && p[k] == ' '; k--)
521 k +=(p[k] != ' ');
522 save = p[k];
523 p[k] = 0;
524 lua_pushinteger(L, i);
525 lua_pushstring(L, p);
526 lua_settable(L, -3);
527 p[k] = save;
530 return 1;
533 static int
534 window_gethistory(lua_State *L)
536 struct win *w = check_window(L, 1);
537 int i;
538 lua_newtable(L);
539 for (i = 0; i < fore->w_height; i++)
541 char *p = (char *) w->w_hlines[(w->w_histidx + i) % w->w_histheight].image;
542 int k, save;
543 for (k = fore->w_width - 1; k >= 0 && p[k] == ' '; k--)
545 k +=(p[k] != ' ');
546 save = p[k];
547 p[k] = 0;
548 lua_pushinteger(L, i);
549 lua_pushstring(L, p);
550 lua_settable(L, -3);
551 p[k] = save;
554 return 1;
557 static const luaL_reg window_methods[] = {
558 {"get_monitor_status", window_get_monitor_status},
559 {"showing_canvases", window_get_showing_canvases},
560 {"stuff", window_stuff},
561 {"activate", window_activate},
562 {"get_lines", window_getlines},
563 {"get_history", window_gethistory},
564 {"hook", LuaRegEvent},
565 {0, 0}
568 static int
569 window_tostring(lua_State *L)
571 char str[128];
572 struct win *w = check_window(L, 1);
573 snprintf(str, sizeof(str), "{window #%d: '%s'}", w->w_number, w->w_title);
574 lua_pushstring(L, str);
575 return 1;
578 static int
579 window_equality(lua_State *L)
581 struct win *w1 = check_window(L, 1), *w2 = check_window(L, 2);
582 lua_pushboolean(L, (w1 == w2 || (w1 && w2 && w1->w_number == w2->w_number)));
583 return 1;
586 static const luaL_reg window_metamethods[] = {
587 {"__tostring", window_tostring},
588 {"__eq", window_equality},
589 {"__gc", screen_object_collect},
590 {0, 0}
593 static const struct Xet_reg window_setters[] = {
594 {"title", 0, 0, window_change_title/*absolute setter*/},
595 {"number", 0, 0, window_change_number/*absolute setter*/},
596 {0, 0}
599 static const struct Xet_reg window_getters[] = {
600 {"title", get_string, offsetof(struct win, w_title) + 8},
601 {"number", get_int, offsetof(struct win, w_number)},
602 {"dir", get_string, offsetof(struct win, w_dir)},
603 {"tty", get_string, offsetof(struct win, w_tty)},
604 {"pid", get_int, offsetof(struct win, w_pid)},
605 {"group", get_window, offsetof(struct win, w_group)},
606 {"bell", get_int, offsetof(struct win, w_bell)},
607 {0, 0}
611 /** }}} */
613 /** AclUser {{{ */
615 PUSH_TYPE(user, struct acluser)
617 CHECK_TYPE(user, struct acluser)
619 static int
620 get_user(lua_State *L, void *v)
622 push_user(L, (struct acluser **)v);
623 return 1;
626 static const luaL_reg user_methods[] = {
627 {0, 0}
630 static int
631 user_tostring(lua_State *L)
633 char str[128];
634 struct acluser *u = check_user(L, 1);
635 snprintf(str, sizeof(str), "{user '%s'}", u->u_name);
636 lua_pushstring(L, str);
637 return 1;
640 static const luaL_reg user_metamethods[] = {
641 {"__tostring", user_tostring},
642 {"__gc", screen_object_collect},
643 {0, 0}
646 static const struct Xet_reg user_setters[] = {
647 {0, 0}
650 static const struct Xet_reg user_getters[] = {
651 {"name", get_string, offsetof(struct acluser, u_name)},
652 {"password", get_string, offsetof(struct acluser, u_password)},
653 {0, 0}
656 /** }}} */
658 static int get_display(lua_State *L, void *v);
659 /** Canvas {{{ */
661 PUSH_TYPE(canvas, struct canvas)
663 CHECK_TYPE(canvas, struct canvas)
665 static int
666 get_canvas(lua_State *L, void *v)
668 push_canvas(L, (struct canvas **)v);
669 return 1;
672 static int
673 canvas_select(lua_State *L)
675 struct canvas *c = check_canvas(L, 1);
676 if (!display || D_forecv == c)
677 return 0;
678 /* FIXME: why do we need this? */
679 SetCanvasWindow(c, Layer2Window(c->c_layer));
681 FocusCanvas(c);
682 return 0;
685 static int
686 canvas_split(lua_State *L)
688 struct canvas *c = check_canvas(L, 1);
689 struct canvas *oldfore = D_forecv;
690 D_forecv = c;
691 int hori = lua_toboolean(L, 2);
692 if (hori)
693 AddCanvas(SLICE_HORI);
694 else
695 AddCanvas(SLICE_VERT);
696 Activate(-1);
697 D_forecv = oldfore;
698 return 0;
701 static int
702 canvas_showwin(lua_State *L)
704 struct canvas *c = check_canvas(L, 1);
705 if (lua_isnil(L, 2))
706 SetCanvasWindow(c, 0);
707 else
709 struct win *w = check_window(L, 2);
710 SetCanvasWindow(c, w);
712 return 0;
715 static const luaL_reg canvas_methods[] = {
716 {"select", canvas_select},
717 {"split", canvas_split},
718 {"showwin", canvas_showwin},
719 {0, 0}
722 static const luaL_reg canvas_metamethods[] = {
723 {"__gc", screen_object_collect},
724 {0, 0}
727 extern struct mchar mchar_so;
728 static int
729 canvas_update_caption(lua_State *L)
731 struct canvas *cv = check_canvas(L, 1);
732 unsigned int len;
733 const char *caption = luaL_checklstring(L, 3, &len);
734 int l, padlen;
735 padlen = cv->c_xe - cv->c_xs +
736 (display ? (cv->c_xe + 1 < D_width || D_CLP): 0);
737 struct win *w = Layer2Window(cv->c_layer);
738 char * buf = MakeWinMsgEv((char *)caption, w, '%', padlen, &cv->c_captev, 0);
739 if (cv->c_captev.timeout.tv_sec)
740 evenq(&cv->c_captev);
741 l = strlen(buf);
743 GotoPos(cv->c_xs, cv->c_ye+1);
744 /*XXX:what does this mean?*/
745 SetRendition(&mchar_so);
746 if (l > cv->c_xe - cv->c_xs + 1)
747 l = cv->c_xe - cv->c_xs + 1;
748 PutWinMsg(buf, cv->c_xs, l);
749 l += cv->c_xs;
750 for (; l <= cv->c_xe; l++)
751 PUTCHARLP(' ');
753 return 0;
756 static const struct Xet_reg canvas_setters[] = {
757 {"caption", 0, 0, canvas_update_caption/*absolute setter*/},
758 {0, 0}
761 static int
762 canvas_get_window(lua_State *L)
764 struct canvas *c = check_canvas(L, 1);
765 struct win *win = Layer2Window(c->c_layer);
766 if (win)
767 push_window(L, &win);
768 else
769 lua_pushnil(L);
770 return 1;
773 static const struct Xet_reg canvas_getters[] = {
774 {"next", get_canvas, offsetof(struct canvas, c_next)},
775 {"xoff", get_int, offsetof(struct canvas, c_xoff)},
776 {"yoff", get_int, offsetof(struct canvas, c_yoff)},
777 {"xs", get_int, offsetof(struct canvas, c_xs)},
778 {"ys", get_int, offsetof(struct canvas, c_ys)},
779 {"xe", get_int, offsetof(struct canvas, c_xe)},
780 {"ye", get_int, offsetof(struct canvas, c_ye)},
781 {"window", 0, 0, canvas_get_window},
782 {"display", get_display, offsetof(struct canvas, c_display)},
783 {0, 0}
786 /** }}} */
788 /** Layout {{{ */
790 PUSH_TYPE(layout, struct layout)
791 CHECK_TYPE(layout, struct layout)
793 static const struct Xet_reg layout_getters[] = {
794 {"title", get_string, offsetof(struct layout, lay_title)},
795 {"number", get_string, offsetof(struct layout, lay_title)},
796 {"autosave", get_string, offsetof(struct layout, lay_autosave)},
797 {0,0}
801 layout_change_title(lua_State *L)
803 struct layout *lay = check_layout(L, 1);
804 unsigned int len;
805 const char *title = luaL_checklstring(L, 3, &len);
806 free(lay->lay_title);
807 lay->lay_title= SaveStr(title);
808 return 0;
811 void LayoutChangeNumber(struct layout *lay, int newnum);
814 layout_change_number(lua_State *L)
816 struct layout *lay = check_layout(L, 1);
817 int newnum = luaL_checkint(L, 3);
818 LayoutChangeNumber(lay, newnum);
819 return 0;
822 static const struct Xet_reg layout_setters[] = {
823 {"title", 0, 0, layout_change_title/*absolute setter*/},
824 {"number", 0, 0, layout_change_number/*absolute setter*/},
825 {"autosave", get_string, offsetof(struct layout, lay_autosave)},
826 {0, 0}
830 layout_select(lua_State *L)
832 struct layout *lay = check_layout(L, 1);
833 if (!display) return 0;
834 LoadLayout(lay, &D_canvas);
835 Activate(0);
836 return 0;
839 static const luaL_reg layout_methods[] = {
840 {"select", layout_select},
841 {0, 0}
844 static const luaL_reg layout_metamethods[] = {
845 {"__gc", screen_object_collect},
846 {0, 0}
849 static int
850 get_layout(lua_State *L, void *v)
852 push_layout(L, (struct layout **)v);
853 return 1;
856 /** }}} */
858 /** Display {{{ */
860 PUSH_TYPE(display, struct display)
862 CHECK_TYPE(display, struct display)
864 static int
865 get_display(lua_State *L, void *v)
867 push_display(L, (struct display **)v);
868 return 1;
871 static int
872 display_get_canvases(lua_State *L)
874 struct display *d;
875 struct canvas *iter;
876 int count;
878 d = check_display(L, 1);
879 lua_newtable(L);
880 for (iter = d->d_cvlist, count = 0; iter; iter = iter->c_next, count++) {
881 lua_pushinteger(L, count);
882 push_canvas(L, &iter);
883 lua_settable(L, -3);
886 return 1;
889 static int
890 display_top_canvas(lua_State *L)
892 struct display *d;
893 d = check_display(L, 1);
894 push_canvas(L, &d->d_cvlist);
896 return 1;
899 static int
900 display_bot_canvas(lua_State *L)
902 struct display *d;
903 struct canvas *c;
904 d = check_display(L, 1);
906 for (c = d->d_cvlist; c->c_next; c = c->c_next)
908 push_canvas(L, &c);
910 return 1;
913 static const luaL_reg display_methods[] = {
914 {"get_canvases", display_get_canvases},
915 {"top_canvas", display_top_canvas},
916 {"bottom_canvas", display_bot_canvas},
917 {0, 0}
920 static int
921 display_tostring(lua_State *L)
923 char str[128];
924 struct display *d = check_display(L, 1);
925 snprintf(str, sizeof(str), "{display: tty = '%s', term = '%s'}", d->d_usertty, d->d_termname);
926 lua_pushstring(L, str);
927 return 1;
930 static const luaL_reg display_metamethods[] = {
931 {"__tostring", display_tostring},
932 {"__gc", screen_object_collect},
933 {0, 0}
936 static int
937 display_new_idle_timeout(lua_State *L)
939 struct display *disp = check_display(L, 1);
940 int timeout = luaL_checkinteger(L, 3) * 1000;
941 struct event *ev = &disp->d_idleev;
942 if (timeout > 0)
944 SetTimeout(ev, timeout);
945 if (!ev->queued)
946 evenq(ev);
948 else
949 evdeq(ev);
951 return 0;
954 static const struct Xet_reg display_setters[] = {
955 {"idle_timeout", 0, 0, display_new_idle_timeout/*absolute setter*/},
956 {0, 0}
959 static const struct Xet_reg display_getters[] = {
960 {"tty", get_string, offsetof(struct display, d_usertty)},
961 {"term", get_string, offsetof(struct display, d_termname)},
962 {"fore", get_window, offsetof(struct display, d_fore)},
963 {"other", get_window, offsetof(struct display, d_other)},
964 {"width", get_int, offsetof(struct display, d_width)},
965 {"height", get_int, offsetof(struct display, d_height)},
966 {"user", get_user, offsetof(struct display, d_user)},
967 {"layout", get_layout, offsetof(struct display, d_layout)},
968 {0, 0}
971 /** }}} */
973 /** Screen {{{ */
975 static int
976 screen_get_windows(lua_State *L)
978 struct win *iter;
979 int count;
981 lua_newtable(L);
982 for (iter = windows, count = 0; iter; iter = iter->w_next, count++) {
983 lua_pushinteger(L, iter->w_number);
984 push_window(L, &iter);
985 lua_settable(L, -3);
988 return 1;
991 static int
992 screen_get_displays(lua_State *L)
994 struct display *iter;
995 int count;
997 lua_newtable(L);
998 for (iter = displays, count = 0; iter; iter = iter->d_next, count++) {
999 lua_pushinteger(L, count);
1000 push_display(L, &iter);
1001 lua_settable(L, -3);
1004 return 1;
1007 extern struct layout *layouts;
1008 static int
1009 screen_get_layouts(lua_State *L)
1011 struct layout *iter;
1012 int count;
1014 lua_newtable(L);
1015 for (iter = layouts, count = 0; iter; iter = iter->lay_next, count++) {
1016 lua_pushinteger(L, iter->lay_number);
1017 push_layout(L, &iter);
1018 lua_settable(L, -3);
1021 return 1;
1024 static int
1025 screen_get_display(lua_State *L)
1027 push_display(L, &display);
1028 return 1;
1031 static int
1032 screen_exec_command(lua_State *L)
1034 const char *command;
1035 unsigned int len;
1037 command = luaL_checklstring(L, 1, &len);
1038 if (command)
1039 RcLine((char *)command, len);
1041 return 0;
1044 static int
1045 screen_append_msg(lua_State *L)
1047 const char *msg, *color;
1048 unsigned int len;
1049 msg = luaL_checklstring(L, 1, &len);
1050 if (lua_isnil(L, 2))
1051 color = NULL;
1052 else
1053 color = luaL_checklstring(L, 2, &len);
1054 AppendWinMsgRend(msg, color);
1055 return 0;
1058 struct sinput_data
1060 lua_State *L;
1061 lua_handler lh;
1064 void
1065 script_input_fn(char *buf, int len, char *priv)
1067 struct sinput_data *sidata = (struct sinput_data *)priv;
1068 lua_handler lh = sidata->lh;
1069 lua_State *L = sidata->L;
1071 LuaPushHandler(L, lh);
1072 lua_pushstring(L, buf);
1073 if (lua_pcall(L, 1, 0, 0) == LUA_ERRRUN)
1075 if(lua_isstring(L, -1))
1077 LuaShowErr(L);
1080 free(sidata);
1081 LuaFreeHandler(L, &lh);
1084 static int
1085 screen_input(lua_State *L)
1087 char *ss;
1088 int n;
1089 const char * prompt = NULL, *prefill = NULL;
1090 lua_handler lh;
1091 struct sinput_data *sidata;
1093 prompt = luaL_checkstring(L, 1);
1094 lh = LuaCheckHandler(L, 2, 1);
1095 if (!lh)
1096 luaL_error(L, "Out of Memory");
1098 if (lua_gettop(L) >= 3)
1099 prefill = luaL_checkstring(L, 3);
1102 sidata = (struct sinput_data *)malloc(sizeof(struct sinput_data));
1103 if (!sidata)
1105 LuaFreeHandler(L, &lh);
1106 luaL_error(L, "Out of Memory");
1109 sidata->L = L;
1110 sidata->lh = lh;
1111 Input((char *)prompt, 100, INP_COOKED, script_input_fn, (char *)sidata, 0);
1113 if (!prefill)
1114 return 0;
1115 for (; *prefill; prefill++)
1117 if ((*(unsigned char *)prefill & 0x7f) < 0x20 || *prefill == 0x7f)
1118 continue;
1119 ss = (char *)prefill;
1120 n = 1;
1121 LayProcess(&ss, &n);
1123 return 0;
1126 static void
1127 sev_schedule_fn(struct event *ev, char *data)
1129 struct sinput_data *si = (struct sinput_data *)data;
1130 lua_handler lh = si->lh;
1131 lua_State *L = si->L;
1132 free(si);
1133 evdeq(ev);
1134 Free(ev);
1136 LuaPushHandler(L, lh);
1137 if (lua_pcall(L, 1, 0, 0) == LUA_ERRRUN)
1139 if(lua_isstring(L, -1))
1141 LuaShowErr(L);
1144 LuaFreeHandler(L, &lh);
1147 static int
1148 screen_schedule(lua_State *L)
1150 int timeout = luaL_checkinteger(L, 1);
1151 lua_handler lh = LuaCheckHandler(L, 2, 1);
1152 struct sinput_data *si;
1153 struct event *ev;
1154 if (timeout <= 0)
1155 return 0;
1157 ev = (struct event *) calloc(1, sizeof(struct event));
1158 if (!ev)
1160 LuaFreeHandler(L, &lh);
1161 luaL_error(L, "Out of Memory");
1163 si = (struct sinput_data *) malloc(sizeof(struct sinput_data));
1164 if (!si)
1166 LuaFreeHandler(L, &lh);
1167 Free(ev);
1168 luaL_error(L, "Out of Memory");
1170 si->lh = lh;
1171 si->L = L;
1173 ev->type = EV_TIMEOUT;
1174 ev->data = (char *)si;
1175 ev->handler = sev_schedule_fn;
1176 evenq(ev);
1177 SetTimeout(ev, timeout * 1000);
1178 return 0;
1181 static const luaL_reg screen_methods[] = {
1182 {"windows", screen_get_windows},
1183 {"displays", screen_get_displays},
1184 {"layouts", screen_get_layouts},
1185 {"display", screen_get_display},
1186 {"command", screen_exec_command},
1187 {"append_msg", screen_append_msg},
1188 {"hook", LuaRegEvent},
1189 {"input", screen_input},
1190 {"schedule", screen_schedule},
1191 {0, 0}
1194 static const luaL_reg screen_metamethods[] = {
1195 {0, 0}
1198 static const struct Xet_reg screen_setters[] = {
1199 {0, 0}
1202 static const struct Xet_reg screen_getters[] = {
1203 {0, 0}
1206 /** }}} */
1208 /** Public functions {{{ */
1210 /* FIXME: This code only tracks one unhook ticket for a lua func.
1211 * So it does not work if one func is registered more than one times. */
1212 static void
1213 prepare_weak_table(lua_State *L, const char *name, const char *mode)
1215 luaL_getmetatable(L, "screen");
1217 lua_pushstring(L, name);
1218 lua_newtable(L);
1220 /* prepare a metatable to indicate weak table */
1221 lua_newtable(L);
1222 lua_pushstring(L, "__mode");
1223 lua_pushstring(L, mode);
1224 lua_rawset(L, -3);
1225 /* Mark weak table */
1226 lua_setmetatable(L, -2);
1227 lua_rawset(L, -3);
1228 lua_pop(L, 1);
1231 static lua_State *L;
1232 int LuaInit(void)
1234 L = luaL_newstate();
1236 luaL_openlibs(L);
1238 #define REGISTER(X) struct_register(L, #X , X ## _methods, X##_metamethods, X##_setters, X##_getters)
1240 REGISTER(screen);
1241 REGISTER(window);
1242 REGISTER(display);
1243 REGISTER(user);
1244 REGISTER(canvas);
1245 REGISTER(callback);
1247 /* To store handler funcs */
1249 /*_two kinds of information are mantained:
1251 * funcreg[key]->func
1252 * The 'func' part of the tables are weak. That means the registered funcs
1253 * will be collected once the func is no longer available (e.g. overwritten
1254 * by a new instance of the script)
1256 * To make this process happens faster, GC is forced at the end of each
1257 * source.
1258 * TODO: What if some events are triggered within the sourcing
1259 * procedure?
1260 * */
1261 prepare_weak_table(L, "_funcreg", "v");
1263 /* funcunhook[func]->listener
1264 * The listener is the unhook ticket of the hook. which should be collected
1265 * once the func is collected. The gc metamethod will be triggered
1266 * accordingly. */
1267 prepare_weak_table(L, "_funcunhook", "k");
1269 return 0;
1272 /* An error message on top of the stack. */
1273 static void
1274 LuaShowErr(lua_State *L)
1276 struct display *d = display;
1277 unsigned int len;
1278 const char *message = luaL_checklstring(L, -1, &len);
1279 lua_pop(L, 1);
1280 LMsg(0, "%s", message ? message : "Unknown error");
1281 display = d;
1284 struct fn_def
1286 void (*push_fn)(lua_State *, void*);
1287 void *value;
1290 static int
1291 LuaCallProcess(const char *name, struct fn_def defs[])
1293 int argc = 0;
1295 lua_getfield(L, LUA_GLOBALSINDEX, name);
1296 if (lua_isnil(L, -1))
1298 lua_pop(L,1);
1299 return 0;
1301 for (argc = 0; defs[argc].push_fn; argc++)
1302 defs[argc].push_fn(L, defs[argc].value);
1303 if (lua_pcall(L, argc, 0, 0) == LUA_ERRRUN && lua_isstring(L, -1))
1305 LuaShowErr(L);
1306 return 0;
1308 return 1;
1311 /* FIXME: Think about this: will it affect the registered handlers?*/
1312 int LuaSource(const char *file, int async)
1314 if (!L)
1315 return 0;
1316 struct stat st;
1317 if (stat(file, &st) == -1)
1318 Msg(errno, "Error loading lua script file '%s'", file);
1319 else
1321 int len = strlen(file);
1322 if (len < 4 || strncmp(file + len - 4, ".lua", 4) != 0)
1323 return 0;
1324 if (luaL_dofile(L, file) && lua_isstring(L, -1))
1326 LuaShowErr(L);
1327 return 0;
1329 else
1331 /* It seems that I need two GC passes to really collect the unhook
1332 * ticket, after changing the reference to ticket in the
1333 * 'funcunhook' table from weak to strong. This should not be
1334 * harmful, but how can I make sure that two passes is enough?
1336 * Possible reason:
1337 * This seems reasonable, since the first pass will collect the func
1338 * itself and make the ticket garbage, and the second pass will
1339 * collect the ticket itself.
1341 * TODO: check this out. maybe ask some lua gurus. */
1342 lua_gc(L, LUA_GCCOLLECT, 0);
1343 lua_gc(L, LUA_GCCOLLECT, 0);
1345 return 1;
1347 return 0;
1350 int LuaFinit(void)
1352 if (!L)
1353 return 0;
1354 lua_close(L);
1355 L = (lua_State*)0;
1356 return 0;
1359 static void
1360 push_stringarray(lua_State *L, char **args)
1362 int i;
1363 lua_newtable(L);
1364 for (i = 1; args && *args; i++) {
1365 lua_pushinteger(L, i);
1366 lua_pushstring(L, *args++);
1367 lua_settable(L, -3);
1372 LuaPushParams(lua_State *L, const char *params, va_list va)
1374 int num = 0;
1375 while (*params)
1377 switch (*params)
1379 case 's':
1380 lua_pushstring(L, va_arg(va, char *));
1381 break;
1382 case 'S':
1383 push_stringarray(L, va_arg(va, char **));
1384 break;
1385 case 'i':
1386 lua_pushinteger(L, va_arg(va, int));
1387 break;
1388 case 'd':
1390 struct display *d = va_arg(va, struct display *);
1391 push_display(L, &d);
1392 break;
1394 case 'w':
1396 struct win *w = va_arg(va, struct win *);
1397 push_window(L, &w);
1398 break;
1400 case 'c':
1402 struct canvas *c = va_arg(va, struct canvas *);
1403 push_canvas(L, &c);
1404 break;
1407 params++;
1408 num++;
1410 return num;
1413 int LuaCall(const char *func, const char **argv)
1415 int argc;
1416 if (!L)
1417 return 0;
1419 StackDump(L, "Before LuaCall\n");
1420 lua_getfield(L, LUA_GLOBALSINDEX, func);
1421 if (lua_isnil(L, -1))
1423 lua_pop(L, 1);
1424 lua_pushstring(L, "Could not find the script function\n");
1425 LuaShowErr(L);
1426 return 0;
1428 for (argc = 0; *argv; argv++, argc++)
1430 lua_pushstring(L, *argv);
1432 if (lua_pcall(L, argc, 0, 0) == LUA_ERRRUN)
1434 if(lua_isstring(L, -1))
1436 StackDump(L, "After LuaCall\n");
1437 LuaShowErr(L);
1438 return 0;
1441 return 1;
1444 /*** Lua callback handler management {{{ */
1447 LuaPushHTable(lua_State *L, int screen, const char * t)
1449 lua_pushstring(L, t);
1450 lua_rawget(L, screen);
1451 /* FIXME: Do we need to balance the stack here? */
1452 if (lua_isnil(L, -1))
1453 luaL_error(L, "Fatal! Fail to get function registeration table!");
1454 return lua_gettop(L);
1457 void
1458 LuaPushHandler(lua_State *L, lua_handler lh)
1460 int funcreg;
1461 if (lh->type == LUA_HANDLER_TYPE_F)
1463 luaL_getmetatable(L, "screen");
1464 funcreg = LuaPushHTable(L, lua_gettop(L), "_funcreg");
1465 lua_rawgeti(L, funcreg, lh->u.reference);
1466 lua_replace(L, -3);
1467 lua_pop(L, 1);
1469 else
1471 lua_getfield(L, LUA_GLOBALSINDEX, lh->u.name);
1476 LuaFuncKey(lua_State *L, int idx, int ref)
1478 int key, funcreg, sc;
1479 luaL_getmetatable(L, "screen");
1480 sc = lua_gettop(L);
1481 funcreg = LuaPushHTable(L, sc, "_funcreg");
1483 lua_pushvalue(L, idx);
1484 key = luaL_ref(L, funcreg);
1485 lua_pop(L, 2);
1486 return key;
1489 void
1490 LuaHUnRef(lua_State *L, int key)
1492 int funcreg, sc;
1493 luaL_getmetatable(L, "screen");
1494 sc = lua_gettop(L);
1495 funcreg = LuaPushHTable(L, sc, "_funcreg");
1496 luaL_unref(L, funcreg, key);
1499 lua_handler
1500 LuaCheckHandler(lua_State *L, int idx, int ref)
1502 int key;
1503 if (idx < 0)
1504 idx = lua_gettop(L) + 1 - idx;
1506 if (lua_isstring(L, idx))
1508 const char * handler;
1509 /* registered with func name.*/
1510 handler = luaL_checkstring(L, idx);
1511 lua_getfield(L, LUA_GLOBALSINDEX, handler);
1512 if (!lua_isfunction(L, -1))
1513 luaL_error(L, "The specified handler %s in param #%d is not a function", handler, idx);
1514 lua_pop(L, 1);
1515 return LuaAllocHandler(handler, 0);
1517 else if (!lua_isfunction(L, idx))
1518 luaL_error(L, "Handler should be a function or the name of function");
1520 key = LuaFuncKey(L, idx, ref);
1521 return LuaAllocHandler(NULL, key);
1524 /* }}} **/
1526 static int
1527 LuaDispatch(void *handler, const char *params, va_list va)
1529 lua_handler lh = (lua_handler)handler;
1530 int argc, retvalue;
1532 StackDump(L, "before dispatch");
1534 LuaPushHandler(L, lh);
1535 if (lua_isnil(L, -1))
1537 lua_pop(L, 1);
1538 return 0;
1540 argc = LuaPushParams(L, params, va);
1542 if (lua_pcall(L, argc, 1, 0) == LUA_ERRRUN && lua_isstring(L, -1))
1544 StackDump(L, "After LuaDispatch\n");
1545 LuaShowErr(L);
1546 return 0;
1548 retvalue = lua_tonumber(L, -1);
1549 lua_pop(L, 1);
1550 return retvalue;
1553 /*FIXME: what if a func is registered twice or more? */
1554 void
1555 LuaRegAutoUnHook(lua_State *L, lua_handler lh, int ticket)
1557 int sc, funcunhook;
1558 luaL_getmetatable(L, "screen");
1559 sc = lua_gettop(L);
1560 funcunhook = LuaPushHTable(L, sc, "_funcunhook");
1561 LuaPushHandler(L, lh);
1562 lua_pushvalue(L, ticket);
1563 lua_rawset(L, funcunhook);
1564 lua_pop(L, 2);
1567 #define SEVNAME_MAX 30
1568 static int
1569 LuaRegEvent(lua_State *L)
1571 /* signature: hook(obj, event, handler, priv);
1572 * or: hook(event, handler, priv)
1573 * returns: A ticket for later unregister. */
1574 int idx = 1, argc = lua_gettop(L);
1575 unsigned int priv = 31; /* Default privilege */
1576 lua_handler lh;
1578 char *obj = NULL;
1579 const char *objname = "global";
1581 static char evbuf[SEVNAME_MAX];
1582 const char *event;
1584 struct script_event *sev;
1586 StackDump(L, "Before RegEvent\n");
1588 /* Identify the object, if specified */
1589 if (luaL_getmetafield(L, 1, "_objname"))
1591 objname = luaL_checkstring(L, -1);
1592 lua_pop(L, 1);
1593 if (!strcmp("screen", objname))
1594 objname = "global";
1595 else
1597 obj = get_broker_obj((struct broker **)lua_touserdata(L, 1));
1598 if (!obj)
1599 return luaL_error(L, "Invalid object specified");
1601 idx++;
1604 event = luaL_checkstring(L, idx++);
1605 snprintf(evbuf, SEVNAME_MAX, "%s_%s", objname, event);
1607 /* Check and get the handler */
1608 lh = LuaCheckHandler(L, idx++, 1);
1609 if (!lh)
1610 luaL_error(L, "Out of memory");
1612 StackDump(L, "In RegEvent\n");
1614 if (idx <= argc)
1615 priv = luaL_checkinteger(L, idx);
1617 sev = object_get_event(obj, evbuf);
1618 if (sev)
1620 struct listener *l;
1621 int ticket;
1622 l = (struct listener *)malloc(sizeof(struct listener));
1623 if (!l)
1624 return luaL_error(L, "Out of memory");
1625 l->priv = priv;
1626 l->bd = &lua_binding;
1627 l->handler = (void *)lh;
1628 register_listener(sev, l);
1629 /* Return the ticket for un-register */
1630 push_callback(L, &l);
1631 ticket = lua_gettop(L);
1633 LuaRegAutoUnHook(L, lh, ticket);
1635 else
1636 return luaL_error(L, "Invalid event specified: %s for object %s", event, objname);
1638 StackDump(L, "After RegEvent\n");
1639 return 1;
1642 /** }}} */
1644 struct binding lua_binding =
1646 "lua", /*name*/
1647 0, /*inited*/
1648 0, /*registered*/
1649 LuaInit,
1650 LuaFinit,
1651 LuaCall,
1652 LuaSource,
1653 LuaDispatch,
1654 0, /*b_next*/