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