Some tweak & fixes on interface definitions.
[screen-lua.git] / src / lua.c
blobc12709e2dd154e7989446d9d8658f9250957649c
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, int *error, 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, 0);
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 {"uid", get_int, offsetof(struct acluser, u_id)},
677 {"esc", get_int, offsetof(struct acluser, u_Esc)},
678 {"metaesc", get_int, offsetof(struct acluser, u_MetaEsc)},
679 {"password", get_string, offsetof(struct acluser, u_password)},
680 {0, 0}
683 /** }}} */
685 static int get_display(lua_State *L, void *v);
686 /** Canvas {{{ */
688 PUSH_TYPE(canvas, struct canvas)
690 CHECK_TYPE(canvas, struct canvas)
692 static int
693 get_canvas(lua_State *L, void *v)
695 push_canvas(L, (struct canvas **)v);
696 return 1;
699 static int
700 canvas_select(lua_State *L)
702 struct canvas *c = check_canvas(L, 1);
703 if (!display || D_forecv == c)
704 return 0;
705 /* FIXME: why do we need this? */
706 SetCanvasWindow(c, Layer2Window(c->c_layer));
708 FocusCanvas(c);
709 return 0;
712 static int
713 canvas_split(lua_State *L)
715 struct canvas *c = check_canvas(L, 1);
716 struct canvas *oldfore = D_forecv;
717 D_forecv = c;
718 int hori = lua_toboolean(L, 2);
719 if (hori)
720 AddCanvas(SLICE_HORI);
721 else
722 AddCanvas(SLICE_VERT);
723 Activate(-1);
724 D_forecv = oldfore;
725 return 0;
728 static int
729 canvas_showwin(lua_State *L)
731 struct canvas *c = check_canvas(L, 1);
732 if (lua_isnil(L, 2))
733 SetCanvasWindow(c, 0);
734 else
736 struct win *w = check_window(L, 2);
737 SetCanvasWindow(c, w);
739 return 0;
742 static const luaL_reg canvas_methods[] = {
743 {"select", canvas_select},
744 {"split", canvas_split},
745 {0, 0}
748 static const luaL_reg canvas_metamethods[] = {
749 {"__gc", screen_object_collect},
750 {0, 0}
753 extern struct mchar mchar_so;
754 static int
755 canvas_update_caption(lua_State *L)
757 struct canvas *cv = check_canvas(L, 1);
758 unsigned int len;
759 const char *caption = luaL_checklstring(L, 3, &len);
760 int l, padlen;
761 padlen = cv->c_xe - cv->c_xs +
762 (display ? (cv->c_xe + 1 < D_width || D_CLP): 0);
763 struct win *w = Layer2Window(cv->c_layer);
764 char * buf = MakeWinMsgEv((char *)caption, w, '%', padlen, &cv->c_captev, 0);
765 if (cv->c_captev.timeout.tv_sec)
766 evenq(&cv->c_captev);
767 l = strlen(buf);
769 GotoPos(cv->c_xs, cv->c_ye+1);
770 /*XXX:what does this mean?*/
771 SetRendition(&mchar_so);
772 if (l > cv->c_xe - cv->c_xs + 1)
773 l = cv->c_xe - cv->c_xs + 1;
774 PutWinMsg(buf, cv->c_xs, l);
775 l += cv->c_xs;
776 for (; l <= cv->c_xe; l++)
777 PUTCHARLP(' ');
779 return 0;
782 static const struct Xet_reg canvas_setters[] = {
783 {"caption", 0, 0, canvas_update_caption/*absolute setter*/},
784 {"window", 0, 0, canvas_showwin/*absolute setter*/},
785 {0, 0}
788 static int
789 canvas_get_window(lua_State *L)
791 struct canvas *c = check_canvas(L, 1);
792 struct win *win = Layer2Window(c->c_layer);
793 if (win)
794 push_window(L, &win);
795 else
796 lua_pushnil(L);
797 return 1;
800 static const struct Xet_reg canvas_getters[] = {
801 {"next", get_canvas, offsetof(struct canvas, c_next)},
802 {"xoff", get_int, offsetof(struct canvas, c_xoff)},
803 {"yoff", get_int, offsetof(struct canvas, c_yoff)},
804 {"xe", get_int, offsetof(struct canvas, c_xe)},
805 {"ye", get_int, offsetof(struct canvas, c_ye)},
806 {"window", 0, 0, canvas_get_window},
807 {"display", get_display, offsetof(struct canvas, c_display)},
808 {0, 0}
811 /** }}} */
813 /** Layout {{{ */
815 PUSH_TYPE(layout, struct layout)
816 CHECK_TYPE(layout, struct layout)
818 static const struct Xet_reg layout_getters[] = {
819 {"title", get_string, offsetof(struct layout, lay_title)},
820 {"number", get_string, offsetof(struct layout, lay_title)},
821 {"autosave", get_int, offsetof(struct layout, lay_autosave)},
822 {0,0}
826 layout_change_title(lua_State *L)
828 struct layout *lay = check_layout(L, 1);
829 unsigned int len;
830 const char *title = luaL_checklstring(L, 3, &len);
831 free(lay->lay_title);
832 lay->lay_title= SaveStr(title);
833 return 0;
836 void LayoutChangeNumber(struct layout *lay, int newnum);
839 layout_change_number(lua_State *L)
841 struct layout *lay = check_layout(L, 1);
842 int newnum = luaL_checkint(L, 3);
843 LayoutChangeNumber(lay, newnum);
844 return 0;
847 static const struct Xet_reg layout_setters[] = {
848 {"title", 0, 0, layout_change_title/*absolute setter*/},
849 {"number", 0, 0, layout_change_number/*absolute setter*/},
850 {"autosave", get_int, offsetof(struct layout, lay_autosave)},
851 {0, 0}
855 layout_select(lua_State *L)
857 struct layout *lay = check_layout(L, 1);
858 if (!display) return 0;
859 LoadLayout(lay, &D_canvas);
860 Activate(0);
861 return 0;
864 static const luaL_reg layout_methods[] = {
865 {"select", layout_select},
866 {0, 0}
869 static const luaL_reg layout_metamethods[] = {
870 {"__gc", screen_object_collect},
871 {0, 0}
874 static int
875 get_layout(lua_State *L, void *v)
877 push_layout(L, (struct layout **)v);
878 return 1;
881 /** }}} */
883 /** Display {{{ */
885 PUSH_TYPE(display, struct display)
887 CHECK_TYPE(display, struct display)
889 static int
890 get_display(lua_State *L, void *v)
892 push_display(L, (struct display **)v);
893 return 1;
896 static int
897 display_get_canvases(lua_State *L)
899 struct display *d;
900 struct canvas *iter;
901 int count;
903 d = check_display(L, 1);
904 lua_newtable(L);
905 for (iter = d->d_cvlist, count = 0; iter; iter = iter->c_next, count++) {
906 lua_pushinteger(L, count);
907 push_canvas(L, &iter);
908 lua_settable(L, -3);
911 return 1;
914 static int
915 display_top_canvas(lua_State *L)
917 struct display *d;
918 d = check_display(L, 1);
919 push_canvas(L, &d->d_cvlist);
921 return 1;
924 static int
925 display_bot_canvas(lua_State *L)
927 struct display *d;
928 struct canvas *c;
929 d = check_display(L, 1);
931 for (c = d->d_cvlist; c->c_next; c = c->c_next)
933 push_canvas(L, &c);
935 return 1;
938 static const luaL_reg display_methods[] = {
939 {"get_canvases", display_get_canvases},
940 {"top_canvas", display_top_canvas},
941 {"bottom_canvas", display_bot_canvas},
942 {0, 0}
945 static int
946 display_tostring(lua_State *L)
948 char str[128];
949 struct display *d = check_display(L, 1);
950 snprintf(str, sizeof(str), "{display: tty = '%s', term = '%s'}", d->d_usertty, d->d_termname);
951 lua_pushstring(L, str);
952 return 1;
955 static const luaL_reg display_metamethods[] = {
956 {"__tostring", display_tostring},
957 {"__gc", screen_object_collect},
958 {0, 0}
961 static int
962 display_new_idle_timeout(lua_State *L)
964 struct display *disp = check_display(L, 1);
965 int timeout = luaL_checkinteger(L, 3) * 1000;
966 struct event *ev = &disp->d_idleev;
967 if (timeout > 0)
969 SetTimeout(ev, timeout);
970 if (!ev->queued)
971 evenq(ev);
973 else
974 evdeq(ev);
976 return 0;
979 static const struct Xet_reg display_setters[] = {
980 {"idle_timeout", 0, 0, display_new_idle_timeout/*absolute setter*/},
981 {0, 0}
984 static const struct Xet_reg display_getters[] = {
985 {"tty", get_string, offsetof(struct display, d_usertty)},
986 {"term", get_string, offsetof(struct display, d_termname)},
987 {"fore", get_window, offsetof(struct display, d_fore)},
988 {"other", get_window, offsetof(struct display, d_other)},
989 {"width", get_int, offsetof(struct display, d_width)},
990 {"height", get_int, offsetof(struct display, d_height)},
991 {"user", get_user, offsetof(struct display, d_user)},
992 {"layout", get_layout, offsetof(struct display, d_layout)},
993 {0, 0}
996 /** }}} */
998 /** Screen {{{ */
1000 extern struct win *wtab[];
1002 static int
1003 screen_get_windows(lua_State *L)
1005 struct win **iter = wtab;
1006 int count, i;
1008 lua_newtable(L);
1009 i = 1;
1010 for (count = 0; count < MAXWIN; count++)
1012 if (!*iter) {
1013 iter++;
1014 continue;
1016 lua_pushinteger(L, i++);
1017 push_window(L, iter);
1018 lua_settable(L, -3);
1019 iter++;
1022 return 1;
1025 static int
1026 screen_get_displays(lua_State *L)
1028 struct display *iter;
1029 int count;
1031 lua_newtable(L);
1032 for (iter = displays, count = 0; iter; iter = iter->d_next, count++) {
1033 lua_pushinteger(L, count);
1034 push_display(L, &iter);
1035 lua_settable(L, -3);
1038 return 1;
1041 extern struct layout *layouts;
1042 static int
1043 screen_get_layouts(lua_State *L)
1045 struct layout *iter;
1046 int count;
1048 lua_newtable(L);
1049 for (iter = layouts, count = 0; iter; iter = iter->lay_next, count++) {
1050 lua_pushinteger(L, iter->lay_number);
1051 push_layout(L, &iter);
1052 lua_settable(L, -3);
1055 return 1;
1058 static int
1059 screen_get_display(lua_State *L)
1061 push_display(L, &display);
1062 return 1;
1065 static int
1066 screen_exec_command(lua_State *L)
1068 const char *command;
1069 unsigned int len;
1071 command = luaL_checklstring(L, 1, &len);
1072 if (command)
1073 RcLine((char *)command, len);
1075 return 0;
1078 static int
1079 screen_append_msg(lua_State *L)
1081 const char *msg, *color;
1082 unsigned int len;
1083 msg = luaL_checklstring(L, 1, &len);
1084 if (lua_isnil(L, 2))
1085 color = NULL;
1086 else
1087 color = luaL_checklstring(L, 2, &len);
1088 AppendWinMsgRend(msg, color);
1089 return 0;
1092 void
1093 script_input_fn(char *buf, int len, char *priv)
1095 lua_handler lh = (lua_handler)priv;
1096 struct sfile *sf = (struct sfile *)lh->L;
1097 lua_State *L = sf->L;
1098 if (!L) {
1099 free(sf);
1100 LuaFreeHandler(L, &lh);
1101 return;
1104 lh->L = L;
1105 LuaPushHandler(lh);
1106 lua_pushstring(L, buf);
1107 if (lua_pcall(L, 1, 0, 0) == LUA_ERRRUN)
1109 if(lua_isstring(L, -1))
1111 LuaShowErr(L);
1114 sf->inuse = 0;
1115 LuaFreeHandler(L, &lh);
1118 static int
1119 screen_input(lua_State *L)
1121 char *ss;
1122 int n;
1123 const char * prompt = NULL, *prefill = NULL;
1124 lua_handler lh;
1125 struct sfile *sf = LuaGetSFile(L);
1127 prompt = luaL_checkstring(L, 1);
1128 lh = LuaCheckHandler(L, 2, 1);
1129 /* Hack! This is used to prevent from accessing unloaded script.*/
1130 lh->L = (lua_State *)sf;
1131 if (!lh)
1132 luaL_error(L, "Out of Memory");
1134 if (lua_gettop(L) >= 3)
1135 prefill = luaL_checkstring(L, 3);
1138 sf->inuse = 1;
1139 Input((char *)prompt, 100, INP_COOKED, script_input_fn, (char *)lh, 0);
1141 if (!prefill)
1142 return 0;
1143 for (; *prefill; prefill++)
1145 if ((*(unsigned char *)prefill & 0x7f) < 0x20 || *prefill == 0x7f)
1146 continue;
1147 ss = (char *)prefill;
1148 n = 1;
1149 LayProcess(&ss, &n);
1151 return 0;
1154 static void
1155 sev_schedule_fn(struct event *ev, char *data)
1157 lua_handler lh = (lua_handler)data;
1158 struct sfile *sf = (struct sfile *)lh->L;
1159 lua_State *L = sf->L;
1160 if (!L) {
1161 free(sf);
1162 LuaFreeHandler(L, &lh);
1163 return;
1166 evdeq(ev);
1167 Free(ev);
1169 lh->L = L;
1170 LuaPushHandler(lh);
1171 if (lua_pcall(L, 1, 0, 0) == LUA_ERRRUN)
1173 if(lua_isstring(L, -1))
1175 LuaShowErr(L);
1178 sf->inuse = 0;
1179 LuaFreeHandler(L, &lh);
1182 static int
1183 screen_schedule(lua_State *L)
1185 int timeout = luaL_checkinteger(L, 1);
1186 lua_handler lh;
1187 struct sfile *sf = LuaGetSFile(L);
1188 struct event *ev;
1189 if (timeout <= 0)
1190 return 0;
1191 lh = LuaCheckHandler(L, 2, 1);
1192 lh->L = (lua_State *)sf;
1194 ev = (struct event *) calloc(1, sizeof(struct event));
1195 if (!ev)
1197 LuaFreeHandler(L, &lh);
1198 luaL_error(L, "Out of Memory");
1201 ev->type = EV_TIMEOUT;
1202 ev->data = (char *)lh;
1203 ev->handler = sev_schedule_fn;
1204 evenq(ev);
1205 SetTimeout(ev, timeout * 1000);
1206 sf->inuse = 1;
1207 return 0;
1210 static const luaL_reg screen_methods[] = {
1211 {"windows", screen_get_windows},
1212 {"displays", screen_get_displays},
1213 {"layouts", screen_get_layouts},
1214 {"display", screen_get_display},
1215 {"command", screen_exec_command},
1216 {"append_msg", screen_append_msg},
1217 {"hook", LuaRegEvent},
1218 {"input", screen_input},
1219 {"schedule", screen_schedule},
1220 {0, 0}
1223 static const luaL_reg screen_metamethods[] = {
1224 {0, 0}
1227 static const struct Xet_reg screen_setters[] = {
1228 {0, 0}
1231 static const struct Xet_reg screen_getters[] = {
1232 {0, 0}
1235 /** }}} */
1237 /** Public functions {{{ */
1239 /* FIXME: This code only tracks one unhook ticket for a lua func.
1240 * So it does not work if one func is registered more than one times. */
1241 static void
1242 prepare_weak_table(lua_State *L, const char *name, const char *mode)
1244 luaL_getmetatable(L, "screen");
1246 lua_pushstring(L, name);
1247 lua_newtable(L);
1249 /* prepare a metatable to indicate weak table */
1250 lua_newtable(L);
1251 lua_pushstring(L, "__mode");
1252 lua_pushstring(L, mode);
1253 lua_rawset(L, -3);
1254 /* Mark weak table */
1255 lua_setmetatable(L, -2);
1256 lua_rawset(L, -3);
1257 lua_pop(L, 1);
1260 int LuaInit(void)
1262 return 0;
1264 lua_State *
1265 LuaNewState(struct sfile *slist)
1267 lua_State *L = luaL_newstate();
1269 luaL_openlibs(L);
1271 #define REGISTER(X) struct_register(L, #X , X ## _methods, X##_metamethods, X##_setters, X##_getters)
1273 REGISTER(screen);
1274 REGISTER(window);
1275 REGISTER(display);
1276 REGISTER(user);
1277 REGISTER(canvas);
1278 REGISTER(callback);
1280 /* To store handler funcs */
1283 * funcreg[key]->func
1284 * */
1285 prepare_weak_table(L, "_funcreg", " ");
1287 /* Hold a reference to the sfile structure to ease unloading the script.*/
1288 luaL_getmetatable(L, "screen");
1289 lua_pushstring(L, "_sfile");
1290 lua_pushlightuserdata(L, slist);
1291 lua_rawset(L, -3);
1292 lua_pop(L, 1);
1293 slist->L = L;
1294 slist->inuse = 0;
1295 return L;
1298 /* An error message on top of the stack. */
1299 static void
1300 LuaShowErr(lua_State *L)
1302 struct display *d = display;
1303 unsigned int len;
1304 const char *message = luaL_checklstring(L, -1, &len);
1305 lua_pop(L, 1);
1306 LMsg(0, "%s", message ? message : "Unknown error");
1307 display = d;
1310 void
1311 LuaUnload(struct sfile *slist)
1313 struct sfile **plist = &scripts;
1314 lua_close(slist->L);
1315 while (*plist) {
1316 if (*plist == slist) {
1317 *plist = slist->next;
1318 break;
1320 plist = &(*plist)->next;
1323 //Delay reclaiming the structure if it's still in use.
1324 if (!slist->inuse)
1325 free(slist);
1326 else
1327 slist->L = NULL;
1330 /* FIXME: Think about this: will it affect the registered handlers?*/
1331 int LuaSource(const char *file, int async)
1333 struct stat st;
1334 if (stat(file, &st) == -1)
1335 Msg(errno, "Error loading lua script file '%s'", file);
1336 else
1338 int len = strlen(file);
1339 ino_t inode = st.st_ino;
1340 struct sfile *slist = scripts;
1342 if (len < 4 || strncmp(file + len - 4, ".lua", 4) != 0)
1343 return 0;
1345 while (slist) {
1346 if (slist->inode == inode)
1347 break;
1348 slist = slist->next;
1350 if (slist)
1351 LuaUnload(slist);
1353 slist = (struct sfile *) malloc(sizeof(struct sfile));
1354 slist->next = scripts;
1355 LuaNewState(slist);
1356 slist->inode = inode;
1358 if (luaL_dofile(slist->L, file) && lua_isstring(slist->L, -1))
1360 LuaShowErr(slist->L);
1361 lua_close(slist->L);
1362 free(slist);
1363 return 0;
1365 scripts = slist;
1366 return 1;
1368 return 0;
1371 int LuaFinit(void)
1373 struct sfile *slist = scripts;
1374 while (slist) {
1375 struct sfile *tmp = slist;
1376 lua_close(slist->L);
1377 slist = slist->next;
1378 free(tmp);
1380 scripts = 0;
1381 return 0;
1384 static void
1385 push_stringarray(lua_State *L, char **args)
1387 int i;
1388 lua_newtable(L);
1389 for (i = 1; args && *args; i++) {
1390 lua_pushinteger(L, i);
1391 lua_pushstring(L, *args++);
1392 lua_settable(L, -3);
1397 LuaPushParams(lua_State *L, const char *params, va_list va)
1399 int num = 0;
1400 while (*params)
1402 switch (*params)
1404 case 's':
1405 lua_pushstring(L, va_arg(va, char *));
1406 break;
1407 case 'S':
1408 push_stringarray(L, va_arg(va, char **));
1409 break;
1410 case 'i':
1411 lua_pushinteger(L, va_arg(va, int));
1412 break;
1413 case 'd':
1415 struct display *d = va_arg(va, struct display *);
1416 push_display(L, &d);
1417 break;
1419 case 'w':
1421 struct win *w = va_arg(va, struct win *);
1422 push_window(L, &w);
1423 break;
1425 case 'c':
1427 struct canvas *c = va_arg(va, struct canvas *);
1428 push_canvas(L, &c);
1429 break;
1432 params++;
1433 num++;
1435 return num;
1438 int LuaCall(const char *func, const char **argv)
1440 int argc;
1441 struct sfile *slist = scripts;
1442 lua_State *L = NULL;
1443 while (slist) {
1444 L = slist->L;
1445 lua_getfield(L, LUA_GLOBALSINDEX, func);
1446 if (lua_isnil(L, -1))
1448 lua_pop(L, 1);
1449 slist = slist->next;
1450 return 0;
1452 else
1453 break;
1456 if (!slist) {
1457 if (L) {
1458 lua_pushstring(L, "Could not find the script function\n");
1459 LuaShowErr(L);
1461 return 0;
1463 StackDump(L, "Before LuaCall\n");
1465 for (argc = 0; *argv; argv++, argc++)
1467 lua_pushstring(L, *argv);
1469 if (lua_pcall(L, argc, 0, 0) == LUA_ERRRUN)
1471 if(lua_isstring(L, -1))
1473 StackDump(L, "After LuaCall\n");
1474 LuaShowErr(L);
1475 return 0;
1478 return 1;
1481 /*** Lua callback handler management {{{ */
1484 LuaPushHTable(lua_State *L, int screen, const char * t)
1486 lua_pushstring(L, t);
1487 lua_rawget(L, screen);
1488 /* FIXME: Do we need to balance the stack here? */
1489 if (lua_isnil(L, -1))
1490 luaL_error(L, "Fatal! Fail to get function registeration table!");
1491 return lua_gettop(L);
1494 void
1495 LuaPushHandler(lua_handler lh)
1497 int funcreg;
1498 lua_State *L = lh->L;
1499 if (lh->type == LUA_HANDLER_TYPE_F)
1501 luaL_getmetatable(L, "screen");
1502 funcreg = LuaPushHTable(L, lua_gettop(L), "_funcreg");
1503 lua_rawgeti(L, funcreg, lh->u.reference);
1504 lua_replace(L, -3);
1505 lua_pop(L, 1);
1507 else
1509 lua_getfield(L, LUA_GLOBALSINDEX, lh->u.name);
1514 LuaFuncKey(lua_State *L, int idx, int ref)
1516 int key, funcreg, sc;
1517 luaL_getmetatable(L, "screen");
1518 sc = lua_gettop(L);
1519 funcreg = LuaPushHTable(L, sc, "_funcreg");
1521 lua_pushvalue(L, idx);
1522 key = luaL_ref(L, funcreg);
1523 lua_pop(L, 2);
1524 return key;
1527 void
1528 LuaHUnRef(lua_State *L, int key)
1530 int funcreg, sc;
1531 luaL_getmetatable(L, "screen");
1532 sc = lua_gettop(L);
1533 funcreg = LuaPushHTable(L, sc, "_funcreg");
1534 luaL_unref(L, funcreg, key);
1537 lua_handler
1538 LuaCheckHandler(lua_State *L, int idx, int ref)
1540 int key;
1541 if (idx < 0)
1542 idx = lua_gettop(L) + 1 - idx;
1544 if (lua_isstring(L, idx))
1546 const char * handler;
1547 /* registered with func name.*/
1548 handler = luaL_checkstring(L, idx);
1549 lua_getfield(L, LUA_GLOBALSINDEX, handler);
1550 if (!lua_isfunction(L, -1))
1551 luaL_error(L, "The specified handler %s in param #%d is not a function", handler, idx);
1552 lua_pop(L, 1);
1553 return LuaAllocHandler(L, handler, 0);
1555 else if (!lua_isfunction(L, idx))
1556 luaL_error(L, "Handler should be a function or the name of function");
1558 key = LuaFuncKey(L, idx, ref);
1559 return LuaAllocHandler(L, NULL, key);
1562 /* }}} **/
1564 static int
1565 LuaDispatch(void *handler, int *error, const char *params, va_list va)
1567 lua_handler lh = (lua_handler)handler;
1568 int argc, retvalue;
1569 lua_State *L = lh->L;
1571 StackDump(L, "before dispatch");
1573 LuaPushHandler(lh);
1574 if (lua_isnil(L, -1))
1576 lua_pop(L, 1);
1577 return 0;
1579 argc = LuaPushParams(L, params, va);
1581 if (lua_pcall(L, argc, 1, 0) == LUA_ERRRUN && lua_isstring(L, -1))
1583 StackDump(L, "After LuaDispatch\n");
1584 LuaShowErr(L);
1585 *error = 1;
1586 return 0;
1588 retvalue = lua_tonumber(L, -1);
1589 lua_pop(L, 1);
1590 *error = 0;
1591 return retvalue;
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 l = (struct listener *)malloc(sizeof(struct listener));
1649 if (!l)
1650 return luaL_error(L, "Out of memory");
1651 l->priv = priv;
1652 l->bd = &lua_binding;
1653 l->handler = (void *)lh;
1654 register_listener(sev, l);
1655 /* Return the ticket for un-register */
1656 push_callback(L, &l);
1658 else
1659 return luaL_error(L, "Invalid event specified: %s for object %s", event, objname);
1661 StackDump(L, "After RegEvent\n");
1662 return 1;
1665 /** }}} */
1667 struct binding lua_binding =
1669 "lua", /*name*/
1670 0, /*inited*/
1671 0, /*registered*/
1672 LuaInit,
1673 LuaFinit,
1674 LuaCall,
1675 LuaSource,
1676 LuaDispatch,
1677 0, /*b_next*/