Implement screens.layouts.
[screen-lua.git] / src / lua.c
blob0231f4d3cf8f646bce682a5eddc95aa6b94c4c87
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 type **var; \
150 luaL_checktype(L, index, LUA_TUSERDATA); \
151 var = (type **) luaL_checkudata(L, index, #name); \
152 if (!var || !*var) \
153 luaL_typerror(L, index, #name); \
154 return *var; \
157 #define PUSH_TYPE(name, type) \
158 static void \
159 push_##name(lua_State *L, type **t) \
161 if (!t || !*t) \
162 lua_pushnil(L); \
163 else \
165 type **r; \
166 r = (type **)lua_newuserdata(L, sizeof(type *)); \
167 *r = *t; \
168 luaL_getmetatable(L, #name); \
169 lua_setmetatable(L,-2); \
173 /* Much of the following template comes from:
174 * http://lua-users.org/wiki/BindingWithMembersAndMethods
177 static int get_int (lua_State *L, void *v)
179 lua_pushinteger (L, *(int*)v);
180 return 1;
183 static int set_int (lua_State *L, void *v)
185 *(int*)v = luaL_checkint(L, 3);
186 return 0;
189 static int get_number (lua_State *L, void *v)
191 lua_pushnumber(L, *(lua_Number*)v);
192 return 1;
195 static int set_number (lua_State *L, void *v)
197 *(lua_Number*)v = luaL_checknumber(L, 3);
198 return 0;
201 static int get_string (lua_State *L, void *v)
203 lua_pushstring(L, (char*)v );
204 return 1;
207 static int set_string (lua_State *L, void *v)
209 *(const char**)v = luaL_checkstring(L, 3);
210 return 0;
213 typedef int (*Xet_func) (lua_State *L, void *v);
215 /* member info for get and set handlers */
216 struct Xet_reg
218 const char *name; /* member name */
219 Xet_func func; /* get or set function for type of member */
220 size_t offset; /* offset of member within the struct */
221 int (*absolute)(lua_State *);
224 static void Xet_add (lua_State *L, const struct Xet_reg *l)
226 if (!l)
227 return;
228 for (; l->name; l++)
230 lua_pushstring(L, l->name);
231 lua_pushlightuserdata(L, (void*)l);
232 lua_settable(L, -3);
236 static int Xet_call (lua_State *L)
238 /* for get: stack has userdata, index, lightuserdata */
239 /* for set: stack has userdata, index, value, lightuserdata */
240 const struct Xet_reg *m = (const struct Xet_reg *)lua_touserdata(L, -1); /* member info */
241 lua_pop(L, 1); /* drop lightuserdata */
242 luaL_checktype(L, 1, LUA_TUSERDATA);
243 if (m->absolute)
244 return m->absolute(L);
245 return m->func(L, *(char**)lua_touserdata(L, 1) + m->offset);
248 static int index_handler (lua_State *L)
250 /* stack has userdata, index */
251 lua_pushvalue(L, 2); /* dup index */
252 lua_rawget(L, lua_upvalueindex(1)); /* lookup member by name */
253 if (!lua_islightuserdata(L, -1))
255 lua_pop(L, 1); /* drop value */
256 lua_pushvalue(L, 2); /* dup index */
257 lua_gettable(L, lua_upvalueindex(2)); /* else try methods */
258 if (lua_isnil(L, -1)) /* invalid member */
259 luaL_error(L, "cannot get member '%s'", lua_tostring(L, 2));
260 return 1;
262 return Xet_call(L); /* call get function */
265 static int newindex_handler (lua_State *L)
267 /* stack has userdata, index, value */
268 lua_pushvalue(L, 2); /* dup index */
269 lua_rawget(L, lua_upvalueindex(1)); /* lookup member by name */
270 if (!lua_islightuserdata(L, -1)) /* invalid member */
271 luaL_error(L, "cannot set member '%s'", lua_tostring(L, 2));
272 return Xet_call(L); /* call set function */
275 static int
276 struct_register(lua_State *L, const char *name, const luaL_reg fn_methods[], const luaL_reg meta_methods[],
277 const struct Xet_reg setters[], const struct Xet_reg getters[])
279 int metatable, methods;
281 /* create methods table & add it to the table of globals */
282 luaL_register(L, name, fn_methods);
283 methods = lua_gettop(L);
285 /* create metatable & add it to the registry */
286 luaL_newmetatable(L, name);
287 luaL_register(L, 0, meta_methods); /* fill metatable */
289 /* To identify the type of object */
290 lua_pushstring(L, "_objname");
291 lua_pushstring(L, name);
292 lua_rawset(L, -3);
294 metatable = lua_gettop(L);
296 lua_pushliteral(L, "__metatable");
297 lua_pushvalue(L, methods); /* dup methods table*/
298 lua_rawset(L, metatable); /* hide metatable:
299 metatable.__metatable = methods */
301 lua_pushliteral(L, "__index");
302 lua_pushvalue(L, metatable); /* upvalue index 1 */
303 Xet_add(L, getters); /* fill metatable with getters */
304 lua_pushvalue(L, methods); /* upvalue index 2 */
305 lua_pushcclosure(L, index_handler, 2);
306 lua_rawset(L, metatable); /* metatable.__index = index_handler */
308 lua_pushliteral(L, "__newindex");
309 lua_newtable(L); /* table for members you can set */
310 Xet_add(L, setters); /* fill with setters */
311 lua_pushcclosure(L, newindex_handler, 1);
312 lua_rawset(L, metatable); /* metatable.__newindex = newindex_handler */
314 /* FIXME: Why do we leave an element on the stack? */
315 lua_pop(L, 1); /* drop metatable */
316 return 1; /* return methods on the stack */
319 /** }}} */
321 /** Callback {{{ */
322 PUSH_TYPE(callback, struct listener)
324 static int
325 internal_unhook(lua_State *L, int warn)
327 /*Emulate check_callback() */
328 struct listener **ppl;
329 luaL_checktype(L, 1, LUA_TUSERDATA);
330 ppl = (struct listener **) luaL_checkudata(L, 1, "callback");
332 if (!ppl)
333 luaL_typerror(L, 1, "callback");
335 if (!*ppl)
337 if (warn)
339 lua_pushboolean(L, 0);
340 lua_pushstring(L, "Callback already unhooked.");
341 LuaShowErr(L);
344 else
346 LuaFreeHandler(L, (lua_handler *)&(*ppl)->handler);
347 unregister_listener(*ppl);
348 *ppl = 0;
349 if (warn)
350 lua_pushboolean(L, 1);
352 return warn != 0;
354 static int
355 callback_unhook(lua_State *L)
357 return internal_unhook(L, 1);
360 static const luaL_reg callback_methods[] = {
361 {"unhook", callback_unhook},
362 {0, 0}
366 callback_collect(lua_State *L)
368 return internal_unhook(L, 0);
371 static const luaL_reg callback_metamethods[] = {
372 {"__gc", callback_collect},
373 {0, 0}
376 static const struct Xet_reg callback_setters[] = {
377 {0, 0}
380 static const struct Xet_reg callback_getters[] = {
381 {0, 0}
385 /** }}} */
387 /** Window {{{ */
389 PUSH_TYPE(window, struct win)
391 CHECK_TYPE(window, struct win)
393 static int get_window(lua_State *L, void *v)
395 push_window(L, (struct win **)v);
396 return 1;
399 static int
400 window_change_title(lua_State *L)
402 struct win *w = check_window(L, 1);
403 unsigned int len;
404 const char *title = luaL_checklstring(L, 3, &len);
405 ChangeAKA(w, (char *)title, len);
406 return 0;
409 static int
410 window_change_number(lua_State *L)
412 struct win *w = check_window(L, 1);
413 int newnum = luaL_checkint(L, 3);
414 ChangeWinNum(w->w_number, newnum);
415 return 0;
418 static int
419 window_get_monitor_status(lua_State *L)
421 struct win *w = check_window(L, 1);
422 int activity = luaL_checkint(L, 2);
423 if (activity)
424 /*monitor*/
425 lua_pushinteger(L, w->w_monitor != MON_OFF);
426 else
427 /*silence*/
428 lua_pushinteger(L, w->w_silence == SILENCE_ON ? w->w_silencewait: 0);
430 return 1;
433 static int
434 window_stuff(lua_State *L)
436 unsigned int len;
437 struct layer *oldflayer = flayer;
438 struct win *w = check_window(L, 1);
439 const char *str = luaL_checklstring(L, 2, &len);
441 flayer = &w->w_layer;
442 while(len)
443 LayProcess((char **)&str, (int *) &len);
444 flayer = oldflayer;
445 return 0;
448 static int
449 window_activate(lua_State *L)
451 struct win *w = check_window(L, 1);
452 SetForeWindow(w);
453 return 0;
456 static const luaL_reg window_methods[] = {
457 {"get_monitor_status", window_get_monitor_status},
458 {"stuff", window_stuff},
459 {"activate", window_activate},
460 {"hook", LuaRegEvent},
461 {0, 0}
464 static int
465 window_tostring(lua_State *L)
467 char str[128];
468 struct win *w = check_window(L, 1);
469 snprintf(str, sizeof(str), "{window #%d: '%s'}", w->w_number, w->w_title);
470 lua_pushstring(L, str);
471 return 1;
474 static int
475 window_equality(lua_State *L)
477 struct win *w1 = check_window(L, 1), *w2 = check_window(L, 2);
478 lua_pushboolean(L, (w1 == w2 || (w1 && w2 && w1->w_number == w2->w_number)));
479 return 1;
482 static const luaL_reg window_metamethods[] = {
483 {"__tostring", window_tostring},
484 {"__eq", window_equality},
485 {0, 0}
488 static const struct Xet_reg window_setters[] = {
489 {"title", 0, 0, window_change_title/*absolute setter*/},
490 {"number", 0, 0, window_change_number/*absolute setter*/},
491 {0, 0}
494 static const struct Xet_reg window_getters[] = {
495 {"title", get_string, offsetof(struct win, w_title) + 8},
496 {"number", get_int, offsetof(struct win, w_number)},
497 {"dir", get_string, offsetof(struct win, w_dir)},
498 {"tty", get_string, offsetof(struct win, w_tty)},
499 {"pid", get_int, offsetof(struct win, w_pid)},
500 {"group", get_window, offsetof(struct win, w_group)},
501 {"bell", get_int, offsetof(struct win, w_bell)},
502 {0, 0}
506 /** }}} */
508 /** AclUser {{{ */
510 PUSH_TYPE(user, struct acluser)
512 CHECK_TYPE(user, struct acluser)
514 static int
515 get_user(lua_State *L, void *v)
517 push_user(L, (struct acluser **)v);
518 return 1;
521 static const luaL_reg user_methods[] = {
522 {0, 0}
525 static int
526 user_tostring(lua_State *L)
528 char str[128];
529 struct acluser *u = check_user(L, 1);
530 snprintf(str, sizeof(str), "{user '%s'}", u->u_name);
531 lua_pushstring(L, str);
532 return 1;
535 static const luaL_reg user_metamethods[] = {
536 {"__tostring", user_tostring},
537 {0, 0}
540 static const struct Xet_reg user_setters[] = {
541 {0, 0}
544 static const struct Xet_reg user_getters[] = {
545 {"name", get_string, offsetof(struct acluser, u_name)},
546 {"password", get_string, offsetof(struct acluser, u_password)},
547 {0, 0}
550 /** }}} */
552 /** Canvas {{{ */
554 PUSH_TYPE(canvas, struct canvas)
556 CHECK_TYPE(canvas, struct canvas)
558 static int
559 get_canvas(lua_State *L, void *v)
561 push_canvas(L, (struct canvas **)v);
562 return 1;
565 static int
566 canvas_select(lua_State *L)
568 struct canvas *c = check_canvas(L, 1);
569 if (!display || D_forecv == c)
570 return 0;
571 /* FIXME: why do we need this? */
572 SetCanvasWindow(c, Layer2Window(c->c_layer));
574 FocusCanvas(c);
575 return 0;
578 static int
579 canvas_showwin(lua_State *L)
581 struct canvas *c = check_canvas(L, 1);
582 if (lua_isnil(L, 2))
583 SetCanvasWindow(c, 0);
584 else
586 struct win *w = check_window(L, 2);
587 SetCanvasWindow(c, w);
589 return 0;
592 static const luaL_reg canvas_methods[] = {
593 {"select", canvas_select},
594 {"showwin", canvas_showwin},
595 {0, 0}
598 static const luaL_reg canvas_metamethods[] = {
599 {0, 0}
602 static const struct Xet_reg canvas_setters[] = {
603 {0, 0}
606 static int
607 canvas_get_window(lua_State *L)
609 struct canvas *c = check_canvas(L, 1);
610 struct win *win = Layer2Window(c->c_layer);
611 if (win)
612 push_window(L, &win);
613 else
614 lua_pushnil(L);
615 return 1;
618 static const struct Xet_reg canvas_getters[] = {
619 {"next", get_canvas, offsetof(struct canvas, c_next)},
620 {"xoff", get_int, offsetof(struct canvas, c_xoff)},
621 {"yoff", get_int, offsetof(struct canvas, c_yoff)},
622 {"xs", get_int, offsetof(struct canvas, c_xs)},
623 {"ys", get_int, offsetof(struct canvas, c_ys)},
624 {"xe", get_int, offsetof(struct canvas, c_xe)},
625 {"ye", get_int, offsetof(struct canvas, c_ye)},
626 {"window", 0, 0, canvas_get_window},
627 {0, 0}
630 /** }}} */
632 /** Layout {{{ */
634 PUSH_TYPE(layout, struct layout)
635 CHECK_TYPE(layout, struct layout)
637 static const struct Xet_reg layout_getters[] = {
638 {"title", get_string, offsetof(struct layout, lay_title)},
639 {"number", get_string, offsetof(struct layout, lay_title)},
640 {"autosave", get_string, offsetof(struct layout, lay_autosave)},
641 {0,0}
645 layout_change_title(lua_State *L)
647 struct layout *lay = check_layout(L, 1);
648 unsigned int len;
649 const char *title = luaL_checklstring(L, 3, &len);
650 free(lay->lay_title);
651 lay->lay_title= SaveStr(title);
652 return 0;
655 void LayoutChangeNumber(struct layout *lay, int newnum);
658 layout_change_number(lua_State *L)
660 struct layout *lay = check_layout(L, 1);
661 int newnum = luaL_checkint(L, 3);
662 LayoutChangeNumber(lay, newnum);
663 return 0;
666 static const struct Xet_reg layout_setters[] = {
667 {"title", 0, 0, layout_change_title/*absolute setter*/},
668 {"number", 0, 0, layout_change_number/*absolute setter*/},
669 {"autosave", get_string, offsetof(struct layout, lay_autosave)},
670 {0, 0}
674 layout_select(lua_State *L)
676 struct layout *lay = check_layout(L, 1);
677 if (!display) return;
678 LoadLayout(lay, &D_canvas);
679 Activate(0);
680 return 0;
683 static const luaL_reg layout_methods[] = {
684 {"select", layout_select},
685 {0, 0}
688 static int
689 get_layout(lua_State *L, void *v)
691 push_layout(L, (struct layout **)v);
692 return 1;
695 /** }}} */
697 /** Display {{{ */
699 PUSH_TYPE(display, struct display)
701 CHECK_TYPE(display, struct display)
703 static int
704 display_get_canvases(lua_State *L)
706 struct display *d;
707 struct canvas *iter;
708 int count;
710 d = check_display(L, 1);
711 lua_newtable(L);
712 for (iter = d->d_cvlist, count = 0; iter; iter = iter->c_next, count++) {
713 lua_pushinteger(L, count);
714 push_canvas(L, &iter);
715 lua_settable(L, -3);
718 return 1;
721 static const luaL_reg display_methods[] = {
722 {"get_canvases", display_get_canvases},
723 {0, 0}
726 static int
727 display_tostring(lua_State *L)
729 char str[128];
730 struct display *d = check_display(L, 1);
731 snprintf(str, sizeof(str), "{display: tty = '%s', term = '%s'}", d->d_usertty, d->d_termname);
732 lua_pushstring(L, str);
733 return 1;
736 static const luaL_reg display_metamethods[] = {
737 {"__tostring", display_tostring},
738 {0, 0}
741 static const struct Xet_reg display_setters[] = {
742 {0, 0}
745 static const struct Xet_reg display_getters[] = {
746 {"tty", get_string, offsetof(struct display, d_usertty)},
747 {"term", get_string, offsetof(struct display, d_termname)},
748 {"fore", get_window, offsetof(struct display, d_fore)},
749 {"other", get_window, offsetof(struct display, d_other)},
750 {"width", get_int, offsetof(struct display, d_width)},
751 {"height", get_int, offsetof(struct display, d_height)},
752 {"user", get_user, offsetof(struct display, d_user)},
753 {"layout", get_layout, offsetof(struct display, d_layout)},
754 {0, 0}
757 /** }}} */
759 /** Screen {{{ */
761 static int
762 screen_get_windows(lua_State *L)
764 struct win *iter;
765 int count;
767 lua_newtable(L);
768 for (iter = windows, count = 0; iter; iter = iter->w_next, count++) {
769 lua_pushinteger(L, iter->w_number);
770 push_window(L, &iter);
771 lua_settable(L, -3);
774 return 1;
777 static int
778 screen_get_displays(lua_State *L)
780 struct display *iter;
781 int count;
783 lua_newtable(L);
784 for (iter = displays, count = 0; iter; iter = iter->d_next, count++) {
785 lua_pushinteger(L, count);
786 push_display(L, &iter);
787 lua_settable(L, -3);
790 return 1;
793 extern struct layout *layouts;
794 static int
795 screen_get_layouts(lua_State *L)
797 struct layout *iter;
798 int count;
800 lua_newtable(L);
801 for (iter = layouts, count = 0; iter; iter = iter->lay_next, count++) {
802 lua_pushinteger(L, iter->lay_number);
803 push_layout(L, &iter);
804 lua_settable(L, -3);
807 return 1;
810 static int
811 screen_get_display(lua_State *L)
813 push_display(L, &display);
814 return 1;
817 static int
818 screen_exec_command(lua_State *L)
820 const char *command;
821 unsigned int len;
823 command = luaL_checklstring(L, 1, &len);
824 if (command)
825 RcLine((char *)command, len);
827 return 0;
830 static int
831 screen_append_msg(lua_State *L)
833 const char *msg, *color;
834 unsigned int len;
835 msg = luaL_checklstring(L, 1, &len);
836 if (lua_isnil(L, 2))
837 color = NULL;
838 else
839 color = luaL_checklstring(L, 2, &len);
840 AppendWinMsgRend(msg, color);
841 return 0;
844 struct sinput_data
846 lua_State *L;
847 lua_handler lh;
850 void
851 script_input_fn(char *buf, int len, char *priv)
853 struct sinput_data *sidata = (struct sinput_data *)priv;
854 lua_handler lh = sidata->lh;
855 lua_State *L = sidata->L;
857 LuaPushHandler(L, lh);
858 lua_pushstring(L, buf);
859 if (lua_pcall(L, 1, 0, 0) == LUA_ERRRUN)
861 if(lua_isstring(L, -1))
863 LuaShowErr(L);
866 free(sidata);
867 LuaFreeHandler(L, &lh);
870 static int
871 screen_input(lua_State *L)
873 char *ss;
874 int n;
875 const char * prompt = NULL, *prefill = NULL;
876 lua_handler lh;
877 struct sinput_data *sidata;
879 prompt = luaL_checkstring(L, 1);
880 lh = LuaCheckHandler(L, 2, 1);
881 if (!lh)
882 luaL_error(L, "Out of Memory");
884 if (lua_gettop(L) >= 3)
885 prefill = luaL_checkstring(L, 3);
888 sidata = (struct sinput_data *)malloc(sizeof(struct sinput_data));
889 if (!sidata)
891 Free(lh);
892 luaL_error(L, "Out of Memory");
895 sidata->L = L;
896 sidata->lh = lh;
897 Input((char *)prompt, 100, INP_COOKED, script_input_fn, (char *)sidata, 0);
899 if (!prefill)
900 return 0;
901 for (; *prefill; prefill++)
903 if ((*(unsigned char *)prefill & 0x7f) < 0x20 || *prefill == 0x7f)
904 continue;
905 ss = (char *)prefill;
906 n = 1;
907 LayProcess(&ss, &n);
909 return 0;
912 static const luaL_reg screen_methods[] = {
913 {"windows", screen_get_windows},
914 {"displays", screen_get_displays},
915 {"layouts", screen_get_layouts},
916 {"display", screen_get_display},
917 {"command", screen_exec_command},
918 {"append_msg", screen_append_msg},
919 {"hook", LuaRegEvent},
920 {"input", screen_input},
921 {0, 0}
924 static const luaL_reg screen_metamethods[] = {
925 {0, 0}
928 static const struct Xet_reg screen_setters[] = {
929 {0, 0}
932 static const struct Xet_reg screen_getters[] = {
933 {0, 0}
936 /** }}} */
938 /** Public functions {{{ */
940 /* FIXME: This code only tracks one unhook ticket for a lua func.
941 * So it does not work if one func is registered more than one times. */
942 static void
943 prepare_weak_table(lua_State *L, const char *name, const char *mode)
945 luaL_getmetatable(L, "screen");
947 lua_pushstring(L, name);
948 lua_newtable(L);
950 /* prepare a metatable to indicate weak table */
951 lua_newtable(L);
952 lua_pushstring(L, "__mode");
953 lua_pushstring(L, mode);
954 lua_rawset(L, -3);
955 /* Mark weak table */
956 lua_setmetatable(L, -2);
957 lua_rawset(L, -3);
958 lua_pop(L, 1);
961 static lua_State *L;
962 int LuaInit(void)
964 L = luaL_newstate();
966 luaL_openlibs(L);
968 #define REGISTER(X) struct_register(L, #X , X ## _methods, X##_metamethods, X##_setters, X##_getters)
970 REGISTER(screen);
971 REGISTER(window);
972 REGISTER(display);
973 REGISTER(user);
974 REGISTER(canvas);
975 REGISTER(callback);
977 /* To store handler funcs */
979 /*_two kinds of information are mantained:
981 * funcreg[key]->func
982 * The 'func' part of the tables are weak. That means the registered funcs
983 * will be collected once the func is no longer available (e.g. overwritten
984 * by a new instance of the script)
986 * To make this process happens faster, GC is forced at the end of each
987 * source.
988 * TODO: What if some events are triggered within the sourcing
989 * procedure?
990 * */
991 prepare_weak_table(L, "_funcreg", "v");
993 /* funcunhook[func]->listener
994 * The listener is the unhook ticket of the hook. which should be collected
995 * once the func is collected. The gc metamethod will be triggered
996 * accordingly. */
997 prepare_weak_table(L, "_funcunhook", "k");
999 return 0;
1002 /* An error message on top of the stack. */
1003 static void
1004 LuaShowErr(lua_State *L)
1006 struct display *d = display;
1007 unsigned int len;
1008 const char *message = luaL_checklstring(L, -1, &len);
1009 LMsg(0, "%s", message ? message : "Unknown error");
1010 lua_pop(L, 1);
1011 display = d;
1014 struct fn_def
1016 void (*push_fn)(lua_State *, void*);
1017 void *value;
1020 static int
1021 LuaCallProcess(const char *name, struct fn_def defs[])
1023 int argc = 0;
1025 lua_getfield(L, LUA_GLOBALSINDEX, name);
1026 if (lua_isnil(L, -1))
1028 lua_pop(L,1);
1029 return 0;
1031 for (argc = 0; defs[argc].push_fn; argc++)
1032 defs[argc].push_fn(L, defs[argc].value);
1033 if (lua_pcall(L, argc, 0, 0) == LUA_ERRRUN && lua_isstring(L, -1))
1035 LuaShowErr(L);
1036 return 0;
1038 return 1;
1041 /* FIXME: Think about this: will it affect the registered handlers?*/
1042 int LuaSource(const char *file, int async)
1044 if (!L)
1045 return 0;
1046 struct stat st;
1047 if (stat(file, &st) == -1)
1048 Msg(errno, "Error loading lua script file '%s'", file);
1049 else
1051 int len = strlen(file);
1052 if (len < 4 || strncmp(file + len - 4, ".lua", 4) != 0)
1053 return 0;
1054 if (luaL_dofile(L, file) && lua_isstring(L, -1))
1056 LuaShowErr(L);
1057 return 0;
1059 else
1061 /* It seems that I need two GC passes to really collect the unhook
1062 * ticket, after changing the reference to ticket in the
1063 * 'funcunhook' table from weak to strong. This should not be
1064 * harmful, but how can I make sure that two passes is enough?
1066 * Possible reason:
1067 * This seems reasonable, since the first pass will collect the func
1068 * itself and make the ticket garbage, and the second pass will
1069 * collect the ticket itself.
1071 * TODO: check this out. maybe ask some lua gurus. */
1072 lua_gc(L, LUA_GCCOLLECT, 0);
1073 lua_gc(L, LUA_GCCOLLECT, 0);
1075 return 1;
1077 return 0;
1080 int LuaFinit(void)
1082 if (!L)
1083 return 0;
1084 lua_close(L);
1085 L = (lua_State*)0;
1086 return 0;
1089 static void
1090 push_stringarray(lua_State *L, char **args)
1092 int i;
1093 lua_newtable(L);
1094 for (i = 1; args && *args; i++) {
1095 lua_pushinteger(L, i);
1096 lua_pushstring(L, *args++);
1097 lua_settable(L, -3);
1102 LuaPushParams(lua_State *L, const char *params, va_list va)
1104 int num = 0;
1105 while (*params)
1107 switch (*params)
1109 case 's':
1110 lua_pushstring(L, va_arg(va, char *));
1111 break;
1112 case 'S':
1113 push_stringarray(L, va_arg(va, char **));
1114 break;
1115 case 'i':
1116 lua_pushinteger(L, va_arg(va, int));
1117 break;
1118 case 'd':
1120 struct display *d = va_arg(va, struct display *);
1121 push_display(L, &d);
1122 break;
1124 case 'w':
1126 struct win *w = va_arg(va, struct win *);
1127 push_window(L, &w);
1128 break;
1130 case 'c':
1132 struct canvas *c = va_arg(va, struct canvas *);
1133 push_canvas(L, &c);
1134 break;
1137 params++;
1138 num++;
1140 return num;
1143 int LuaCall(const char *func, const char **argv)
1145 int argc;
1146 if (!L)
1147 return 0;
1149 StackDump(L, "Before LuaCall\n");
1150 lua_getfield(L, LUA_GLOBALSINDEX, func);
1151 if (lua_isnil(L, -1))
1153 lua_pop(L, 1);
1154 lua_pushstring(L, "Could not find the script function\n");
1155 LuaShowErr(L);
1156 return 0;
1158 for (argc = 0; *argv; argv++, argc++)
1160 lua_pushstring(L, *argv);
1162 if (lua_pcall(L, argc, 0, 0) == LUA_ERRRUN)
1164 if(lua_isstring(L, -1))
1166 StackDump(L, "After LuaCall\n");
1167 LuaShowErr(L);
1168 return 0;
1171 return 1;
1174 /*** Lua callback handler management {{{ */
1177 LuaPushHTable(lua_State *L, int screen, const char * t)
1179 lua_pushstring(L, t);
1180 lua_rawget(L, screen);
1181 /* FIXME: Do we need to balance the stack here? */
1182 if (lua_isnil(L, -1))
1183 luaL_error(L, "Fatal! Fail to get function registeration table!");
1184 return lua_gettop(L);
1187 void
1188 LuaPushHandler(lua_State *L, lua_handler lh)
1190 int funcreg;
1191 if (lh->type == LUA_HANDLER_TYPE_F)
1193 luaL_getmetatable(L, "screen");
1194 funcreg = LuaPushHTable(L, lua_gettop(L), "_funcreg");
1195 lua_rawgeti(L, funcreg, lh->u.reference);
1196 lua_replace(L, -3);
1197 lua_pop(L, 1);
1199 else
1201 lua_getfield(L, LUA_GLOBALSINDEX, lh->u.name);
1206 LuaFuncKey(lua_State *L, int idx, int ref)
1208 int key, funcreg, sc;
1209 luaL_getmetatable(L, "screen");
1210 sc = lua_gettop(L);
1211 funcreg = LuaPushHTable(L, sc, "_funcreg");
1213 lua_pushvalue(L, idx);
1214 key = luaL_ref(L, funcreg);
1215 lua_pop(L, 2);
1216 return key;
1219 void
1220 LuaHUnRef(lua_State *L, int key)
1222 int funcreg, sc;
1223 luaL_getmetatable(L, "screen");
1224 sc = lua_gettop(L);
1225 funcreg = LuaPushHTable(L, sc, "_funcreg");
1226 luaL_unref(L, funcreg, key);
1229 lua_handler
1230 LuaCheckHandler(lua_State *L, int idx, int ref)
1232 int key;
1233 if (idx < 0)
1234 idx = lua_gettop(L) + 1 - idx;
1236 if (lua_isstring(L, idx))
1238 const char * handler;
1239 /* registered with func name.*/
1240 handler = luaL_checkstring(L, idx);
1241 lua_getfield(L, LUA_GLOBALSINDEX, handler);
1242 if (!lua_isfunction(L, -1))
1243 luaL_error(L, "The specified handler %s in param #%d is not a function", handler, idx);
1244 lua_pop(L, 1);
1245 return LuaAllocHandler(handler, 0);
1247 else if (!lua_isfunction(L, idx))
1248 luaL_error(L, "Handler should be a function or the name of function");
1250 key = LuaFuncKey(L, idx, ref);
1251 return LuaAllocHandler(NULL, key);
1254 /* }}} **/
1256 static int
1257 LuaDispatch(void *handler, const char *params, va_list va)
1259 lua_handler lh = (lua_handler)handler;
1260 int argc, retvalue;
1262 StackDump(L, "before dispatch");
1264 LuaPushHandler(L, lh);
1265 if (lua_isnil(L, -1))
1267 lua_pop(L, 1);
1268 return 0;
1270 argc = LuaPushParams(L, params, va);
1272 if (lua_pcall(L, argc, 1, 0) == LUA_ERRRUN && lua_isstring(L, -1))
1274 StackDump(L, "After LuaDispatch\n");
1275 LuaShowErr(L);
1276 return 0;
1278 retvalue = lua_tonumber(L, -1);
1279 lua_pop(L, 1);
1280 return retvalue;
1283 /*FIXME: what if a func is registered twice or more? */
1284 void
1285 LuaRegAutoUnHook(lua_State *L, lua_handler lh, int ticket)
1287 int sc, funcunhook;
1288 luaL_getmetatable(L, "screen");
1289 sc = lua_gettop(L);
1290 funcunhook = LuaPushHTable(L, sc, "_funcunhook");
1291 LuaPushHandler(L, lh);
1292 lua_pushvalue(L, ticket);
1293 lua_rawset(L, funcunhook);
1294 lua_pop(L, 2);
1297 #define SEVNAME_MAX 30
1298 static int
1299 LuaRegEvent(lua_State *L)
1301 /* signature: hook(obj, event, handler, priv);
1302 * or: hook(event, handler, priv)
1303 * returns: A ticket for later unregister. */
1304 int idx = 1, argc = lua_gettop(L);
1305 unsigned int priv = 31; /* Default privilege */
1306 lua_handler lh;
1308 char *obj = NULL;
1309 const char *objname = "global";
1311 static char evbuf[SEVNAME_MAX];
1312 const char *event;
1314 struct script_event *sev;
1316 StackDump(L, "Before RegEvent\n");
1318 /* Identify the object, if specified */
1319 if (luaL_getmetafield(L, 1, "_objname"))
1321 objname = luaL_checkstring(L, -1);
1322 lua_pop(L, 1);
1323 if (!strcmp("screen", objname))
1324 objname = "global";
1325 else
1326 obj = *(char **)lua_touserdata(L, 1);
1327 idx++;
1330 event = luaL_checkstring(L, idx++);
1331 snprintf(evbuf, SEVNAME_MAX, "%s_%s", objname, event);
1333 /* Check and get the handler */
1334 lh = LuaCheckHandler(L, idx++, 1);
1335 if (!lh)
1336 luaL_error(L, "Out of memory");
1338 StackDump(L, "In RegEvent\n");
1340 if (idx <= argc)
1341 priv = luaL_checkinteger(L, idx);
1343 sev = object_get_event(obj, evbuf);
1344 if (sev)
1346 struct listener *l;
1347 int ticket;
1348 l = (struct listener *)malloc(sizeof(struct listener));
1349 if (!l)
1350 return luaL_error(L, "Out of memory");
1351 l->priv = priv;
1352 l->bd = &lua_binding;
1353 l->handler = (void *)lh;
1354 register_listener(sev, l);
1355 /* Return the ticket for un-register */
1356 push_callback(L, &l);
1357 ticket = lua_gettop(L);
1359 LuaRegAutoUnHook(L, lh, ticket);
1361 else
1362 return luaL_error(L, "Invalid event specified: %s for object %s", event, objname);
1364 StackDump(L, "After RegEvent\n");
1365 return 1;
1368 /** }}} */
1370 struct binding lua_binding =
1372 "lua", /*name*/
1373 0, /*inited*/
1374 0, /*registered*/
1375 LuaInit,
1376 LuaFinit,
1377 LuaCall,
1378 LuaSource,
1379 LuaDispatch,
1380 0, /*b_next*/