Do not do refcount any more.
[screen-lua.git] / src / lua.c
blobd5fb1d970c52b7e0ebf85afd3c20f808ac891aa5
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);
82 static int LuaDispatch(void *handler, const char *params, va_list va);
83 static int LuaRegEvent(lua_State *L);
84 static void LuaShowErr(lua_State *L);
85 struct binding lua_binding;
87 enum
89 LUA_HANDLER_TYPE_N = 1,
90 LUA_HANDLER_TYPE_F
93 struct lua_handler
95 int type;
96 union
98 const char *name;
99 int reference;
100 } u;
103 typedef struct lua_handler *lua_handler;
104 void LuaPushHandler(lua_State *L, lua_handler lh);
105 void LuaHUnRef(lua_State *L, int key);
106 lua_handler LuaCheckHandler(lua_State *L, int idx, int ref);
108 lua_handler
109 LuaAllocHandler(const char *name, int ref)
111 struct lua_handler *lh;
112 lh = (struct lua_handler*) malloc(sizeof(struct lua_handler));
113 if (!lh)
114 return NULL;
116 if (name)
118 lh->type = LUA_HANDLER_TYPE_N;
119 lh->u.name = SaveStr(name);
121 else
123 lh->type = LUA_HANDLER_TYPE_F;
124 lh->u.reference = ref;
127 return lh;
130 void
131 LuaFreeHandler(lua_State *L, struct lua_handler **lh)
133 if ((*lh)->type == LUA_HANDLER_TYPE_N)
134 Free((*lh)->u.name)
135 else
137 LuaHUnRef(L, (*lh)->u.reference);
138 (*lh)->u.reference = 0;
140 Free(*lh);
142 /** Template {{{ */
144 #define CHECK_TYPE(name, type) \
145 static type * \
146 check_##name(lua_State *L, int index) \
148 type **var; \
149 luaL_checktype(L, index, LUA_TUSERDATA); \
150 var = (type **) luaL_checkudata(L, index, #name); \
151 if (!var || !*var) \
152 luaL_typerror(L, index, #name); \
153 return *var; \
156 #define PUSH_TYPE(name, type) \
157 static void \
158 push_##name(lua_State *L, type **t) \
160 if (!t || !*t) \
161 lua_pushnil(L); \
162 else \
164 type **r; \
165 r = (type **)lua_newuserdata(L, sizeof(type *)); \
166 *r = *t; \
167 luaL_getmetatable(L, #name); \
168 lua_setmetatable(L,-2); \
172 /* Much of the following template comes from:
173 * http://lua-users.org/wiki/BindingWithMembersAndMethods
176 static int get_int (lua_State *L, void *v)
178 lua_pushinteger (L, *(int*)v);
179 return 1;
182 static int set_int (lua_State *L, void *v)
184 *(int*)v = luaL_checkint(L, 3);
185 return 0;
188 static int get_number (lua_State *L, void *v)
190 lua_pushnumber(L, *(lua_Number*)v);
191 return 1;
194 static int set_number (lua_State *L, void *v)
196 *(lua_Number*)v = luaL_checknumber(L, 3);
197 return 0;
200 static int get_string (lua_State *L, void *v)
202 lua_pushstring(L, (char*)v );
203 return 1;
206 static int set_string (lua_State *L, void *v)
208 *(const char**)v = luaL_checkstring(L, 3);
209 return 0;
212 typedef int (*Xet_func) (lua_State *L, void *v);
214 /* member info for get and set handlers */
215 struct Xet_reg
217 const char *name; /* member name */
218 Xet_func func; /* get or set function for type of member */
219 size_t offset; /* offset of member within the struct */
220 int (*absolute)(lua_State *);
223 static void Xet_add (lua_State *L, const struct Xet_reg *l)
225 if (!l)
226 return;
227 for (; l->name; l++)
229 lua_pushstring(L, l->name);
230 lua_pushlightuserdata(L, (void*)l);
231 lua_settable(L, -3);
235 static int Xet_call (lua_State *L)
237 /* for get: stack has userdata, index, lightuserdata */
238 /* for set: stack has userdata, index, value, lightuserdata */
239 const struct Xet_reg *m = (const struct Xet_reg *)lua_touserdata(L, -1); /* member info */
240 lua_pop(L, 1); /* drop lightuserdata */
241 luaL_checktype(L, 1, LUA_TUSERDATA);
242 if (m->absolute)
243 return m->absolute(L);
244 return m->func(L, *(char**)lua_touserdata(L, 1) + m->offset);
247 static int index_handler (lua_State *L)
249 /* stack has userdata, index */
250 lua_pushvalue(L, 2); /* dup index */
251 lua_rawget(L, lua_upvalueindex(1)); /* lookup member by name */
252 if (!lua_islightuserdata(L, -1))
254 lua_pop(L, 1); /* drop value */
255 lua_pushvalue(L, 2); /* dup index */
256 lua_gettable(L, lua_upvalueindex(2)); /* else try methods */
257 if (lua_isnil(L, -1)) /* invalid member */
258 luaL_error(L, "cannot get member '%s'", lua_tostring(L, 2));
259 return 1;
261 return Xet_call(L); /* call get function */
264 static int newindex_handler (lua_State *L)
266 /* stack has userdata, index, value */
267 lua_pushvalue(L, 2); /* dup index */
268 lua_rawget(L, lua_upvalueindex(1)); /* lookup member by name */
269 if (!lua_islightuserdata(L, -1)) /* invalid member */
270 luaL_error(L, "cannot set member '%s'", lua_tostring(L, 2));
271 return Xet_call(L); /* call set function */
274 static int
275 struct_register(lua_State *L, const char *name, const luaL_reg fn_methods[], const luaL_reg meta_methods[],
276 const struct Xet_reg setters[], const struct Xet_reg getters[])
278 int metatable, methods;
280 /* create methods table & add it to the table of globals */
281 luaL_register(L, name, fn_methods);
282 methods = lua_gettop(L);
284 /* create metatable & add it to the registry */
285 luaL_newmetatable(L, name);
286 luaL_register(L, 0, meta_methods); /* fill metatable */
288 /* To identify the type of object */
289 lua_pushstring(L, "_objname");
290 lua_pushstring(L, name);
291 lua_rawset(L, -3);
293 metatable = lua_gettop(L);
295 lua_pushliteral(L, "__metatable");
296 lua_pushvalue(L, methods); /* dup methods table*/
297 lua_rawset(L, metatable); /* hide metatable:
298 metatable.__metatable = methods */
300 lua_pushliteral(L, "__index");
301 lua_pushvalue(L, metatable); /* upvalue index 1 */
302 Xet_add(L, getters); /* fill metatable with getters */
303 lua_pushvalue(L, methods); /* upvalue index 2 */
304 lua_pushcclosure(L, index_handler, 2);
305 lua_rawset(L, metatable); /* metatable.__index = index_handler */
307 lua_pushliteral(L, "__newindex");
308 lua_newtable(L); /* table for members you can set */
309 Xet_add(L, setters); /* fill with setters */
310 lua_pushcclosure(L, newindex_handler, 1);
311 lua_rawset(L, metatable); /* metatable.__newindex = newindex_handler */
313 /* FIXME: Why do we leave an element on the stack? */
314 lua_pop(L, 1); /* drop metatable */
315 return 1; /* return methods on the stack */
318 /** }}} */
320 /** Callback {{{ */
321 PUSH_TYPE(callback, struct listener)
323 static int
324 callback_unhook(lua_State *L)
326 /*Emulate check_callback() */
327 struct listener **ppl;
328 luaL_checktype(L, 1, LUA_TUSERDATA);
329 ppl = (struct listener **) luaL_checkudata(L, 1, "callback");
331 if (!ppl)
332 luaL_typerror(L, 1, "callback");
334 if (!*ppl)
336 lua_pushboolean(L, 0);
337 lua_pushstring(L, "Callback already unhooked.");
338 LuaShowErr(L);
340 else
342 LuaFreeHandler(L, (lua_handler *)&(*ppl)->handler);
343 unregister_listener(*ppl);
344 *ppl = 0;
345 lua_pushboolean(L, 1);
347 return 1;
350 static const luaL_reg callback_methods[] = {
351 {"unhook", callback_unhook},
352 {0, 0}
355 static const luaL_reg callback_metamethods[] = {
356 {0, 0}
359 static const struct Xet_reg callback_setters[] = {
360 {0, 0}
363 static const struct Xet_reg callback_getters[] = {
364 {0, 0}
368 /** }}} */
370 /** Window {{{ */
372 PUSH_TYPE(window, struct win)
374 CHECK_TYPE(window, struct win)
376 static int get_window(lua_State *L, void *v)
378 push_window(L, (struct win **)v);
379 return 1;
382 static int
383 window_change_title(lua_State *L)
385 struct win *w = check_window(L, 1);
386 unsigned int len;
387 const char *title = luaL_checklstring(L, 2, &len);
388 ChangeAKA(w, (char *)title, len);
389 return 0;
392 static int
393 window_get_monitor_status(lua_State *L)
395 struct win *w = check_window(L, 1);
396 int activity = luaL_checkint(L, 2);
397 if (activity)
398 /*monitor*/
399 lua_pushinteger(L, w->w_monitor != MON_OFF);
400 else
401 /*silence*/
402 lua_pushinteger(L, w->w_silence == SILENCE_ON ? w->w_silencewait: 0);
404 return 1;
407 static const luaL_reg window_methods[] = {
408 {"get_monitor_status", window_get_monitor_status},
409 {"hook", LuaRegEvent},
410 {0, 0}
413 static int
414 window_tostring(lua_State *L)
416 char str[128];
417 struct win *w = check_window(L, 1);
418 snprintf(str, sizeof(str), "{window #%d: '%s'}", w->w_number, w->w_title);
419 lua_pushstring(L, str);
420 return 1;
423 static int
424 window_equality(lua_State *L)
426 struct win *w1 = check_window(L, 1), *w2 = check_window(L, 2);
427 lua_pushboolean(L, (w1 == w2 || (w1 && w2 && w1->w_number == w2->w_number)));
428 return 1;
431 static const luaL_reg window_metamethods[] = {
432 {"__tostring", window_tostring},
433 {"__eq", window_equality},
434 {0, 0}
437 static const struct Xet_reg window_setters[] = {
438 {"title", 0, 0, window_change_title/*absolute setter*/},
439 {0, 0}
442 static const struct Xet_reg window_getters[] = {
443 {"title", get_string, offsetof(struct win, w_title) + 8},
444 {"number", get_int, offsetof(struct win, w_number)},
445 {"dir", get_string, offsetof(struct win, w_dir)},
446 {"tty", get_string, offsetof(struct win, w_tty)},
447 {"pid", get_int, offsetof(struct win, w_pid)},
448 {"group", get_window, offsetof(struct win, w_group)},
449 {"bell", get_int, offsetof(struct win, w_bell)},
450 {0, 0}
454 /** }}} */
456 /** AclUser {{{ */
458 PUSH_TYPE(user, struct acluser)
460 CHECK_TYPE(user, struct acluser)
462 static int
463 get_user(lua_State *L, void *v)
465 push_user(L, (struct acluser **)v);
466 return 1;
469 static const luaL_reg user_methods[] = {
470 {0, 0}
473 static int
474 user_tostring(lua_State *L)
476 char str[128];
477 struct acluser *u = check_user(L, 1);
478 snprintf(str, sizeof(str), "{user '%s'}", u->u_name);
479 lua_pushstring(L, str);
480 return 1;
483 static const luaL_reg user_metamethods[] = {
484 {"__tostring", user_tostring},
485 {0, 0}
488 static const struct Xet_reg user_setters[] = {
489 {0, 0}
492 static const struct Xet_reg user_getters[] = {
493 {"name", get_string, offsetof(struct acluser, u_name)},
494 {"password", get_string, offsetof(struct acluser, u_password)},
495 {0, 0}
498 /** }}} */
500 /** Canvas {{{ */
502 PUSH_TYPE(canvas, struct canvas)
504 CHECK_TYPE(canvas, struct canvas)
506 static int
507 get_canvas(lua_State *L, void *v)
509 push_canvas(L, (struct canvas **)v);
510 return 1;
513 static int
514 canvas_select(lua_State *L)
516 struct canvas *c = check_canvas(L, 1);
517 if (!display || D_forecv == c)
518 return 0;
519 SetCanvasWindow(c, Layer2Window(c->c_layer));
520 D_forecv = c;
522 /* XXX: the following all is duplicated from process.c:DoAction.
523 * Should these be in some better place?
525 ResizeCanvas(&D_canvas);
526 RecreateCanvasChain();
527 RethinkDisplayViewports();
528 ResizeLayersToCanvases(); /* redisplays */
529 fore = D_fore = Layer2Window(D_forecv->c_layer);
530 flayer = D_forecv->c_layer;
531 #ifdef RXVT_OSC
532 if (D_xtermosc[2] || D_xtermosc[3])
534 Activate(-1);
535 break;
537 #endif
538 RefreshHStatus();
539 #ifdef RXVT_OSC
540 RefreshXtermOSC();
541 #endif
542 flayer = D_forecv->c_layer;
543 CV_CALL(D_forecv, LayRestore();LaySetCursor());
544 WindowChanged(0, 'F');
545 return 1;
548 static const luaL_reg canvas_methods[] = {
549 {"select", canvas_select},
550 {0, 0}
553 static const luaL_reg canvas_metamethods[] = {
554 {0, 0}
557 static const struct Xet_reg canvas_setters[] = {
558 {0, 0}
561 static int
562 canvas_get_window(lua_State *L)
564 struct canvas *c = check_canvas(L, 1);
565 struct win *win = Layer2Window(c->c_layer);
566 if (win)
567 push_window(L, &win);
568 else
569 lua_pushnil(L);
570 return 1;
573 static const struct Xet_reg canvas_getters[] = {
574 {"next", get_canvas, offsetof(struct canvas, c_next)},
575 {"xoff", get_int, offsetof(struct canvas, c_xoff)},
576 {"yoff", get_int, offsetof(struct canvas, c_yoff)},
577 {"xs", get_int, offsetof(struct canvas, c_xs)},
578 {"ys", get_int, offsetof(struct canvas, c_ys)},
579 {"xe", get_int, offsetof(struct canvas, c_xe)},
580 {"ye", get_int, offsetof(struct canvas, c_ye)},
581 {"window", 0, 0, canvas_get_window},
582 {0, 0}
585 /** }}} */
587 /** Layout {{{ */
589 PUSH_TYPE(layout, struct layout)
590 CHECK_TYPE(layout, struct layout)
592 static const struct Xet_reg layout_getters[] = {
593 {0,0}
596 static int
597 get_layout(lua_State *L, void *v)
599 push_layout(L, (struct layout **)v);
600 return 1;
603 /** }}} */
605 /** Display {{{ */
607 PUSH_TYPE(display, struct display)
609 CHECK_TYPE(display, struct display)
611 static int
612 display_get_canvases(lua_State *L)
614 struct display *d;
615 struct canvas *iter;
616 int count;
618 d = check_display(L, 1);
619 lua_newtable(L);
620 for (iter = d->d_cvlist, count = 0; iter; iter = iter->c_next, count++) {
621 lua_pushinteger(L, count);
622 push_canvas(L, &iter);
623 lua_settable(L, -3);
626 return 1;
629 static const luaL_reg display_methods[] = {
630 {"get_canvases", display_get_canvases},
631 {0, 0}
634 static int
635 display_tostring(lua_State *L)
637 char str[128];
638 struct display *d = check_display(L, 1);
639 snprintf(str, sizeof(str), "{display: tty = '%s', term = '%s'}", d->d_usertty, d->d_termname);
640 lua_pushstring(L, str);
641 return 1;
644 static const luaL_reg display_metamethods[] = {
645 {"__tostring", display_tostring},
646 {0, 0}
649 static const struct Xet_reg display_setters[] = {
650 {0, 0}
653 static const struct Xet_reg display_getters[] = {
654 {"tty", get_string, offsetof(struct display, d_usertty)},
655 {"term", get_string, offsetof(struct display, d_termname)},
656 {"fore", get_window, offsetof(struct display, d_fore)},
657 {"other", get_window, offsetof(struct display, d_other)},
658 {"width", get_int, offsetof(struct display, d_width)},
659 {"height", get_int, offsetof(struct display, d_height)},
660 {"user", get_user, offsetof(struct display, d_user)},
661 {"layout", get_layout, offsetof(struct display, d_layout)},
662 {0, 0}
665 /** }}} */
667 /** Screen {{{ */
669 static int
670 screen_get_windows(lua_State *L)
672 struct win *iter;
673 int count;
675 lua_newtable(L);
676 for (iter = windows, count = 0; iter; iter = iter->w_next, count++) {
677 lua_pushinteger(L, iter->w_number);
678 push_window(L, &iter);
679 lua_settable(L, -3);
682 return 1;
685 static int
686 screen_get_displays(lua_State *L)
688 struct display *iter;
689 int count;
691 lua_newtable(L);
692 for (iter = displays, count = 0; iter; iter = iter->d_next, count++) {
693 lua_pushinteger(L, count);
694 push_display(L, &iter);
695 lua_settable(L, -3);
698 return 1;
701 static int
702 screen_get_display(lua_State *L)
704 push_display(L, &display);
705 return 1;
708 static int
709 screen_exec_command(lua_State *L)
711 const char *command;
712 unsigned int len;
714 command = luaL_checklstring(L, 1, &len);
715 if (command)
716 RcLine((char *)command, len);
718 return 0;
721 static int
722 screen_append_msg(lua_State *L)
724 const char *msg, *color;
725 unsigned int len;
726 msg = luaL_checklstring(L, 1, &len);
727 if (lua_isnil(L, 2))
728 color = NULL;
729 else
730 color = luaL_checklstring(L, 2, &len);
731 AppendWinMsgRend(msg, color);
732 return 0;
735 struct sinput_data
737 lua_State *L;
738 lua_handler lh;
741 void
742 script_input_fn(char *buf, int len, char *priv)
744 struct sinput_data *sidata = (struct sinput_data *)priv;
745 lua_handler lh = sidata->lh;
746 lua_State *L = sidata->L;
748 LuaPushHandler(L, lh);
749 lua_pushstring(L, buf);
750 if (lua_pcall(L, 1, 0, 0) == LUA_ERRRUN)
752 if(lua_isstring(L, -1))
754 LuaShowErr(L);
757 free(sidata);
758 LuaFreeHandler(L, &lh);
761 static int
762 screen_input(lua_State *L)
764 char * prompt = NULL;
765 lua_handler lh;
766 struct sinput_data *sidata;
768 prompt = (char *)luaL_checkstring(L, 1);
769 lh = LuaCheckHandler(L, 2, 1);
770 sidata = (struct sinput_data *)malloc(sizeof(struct sinput_data));
771 if (!sidata)
772 luaL_error(L, "Out of Memory");
774 sidata->L = L;
775 sidata->lh = lh;
776 Input(prompt, 100, INP_COOKED, script_input_fn, (char *)sidata, 0);
778 return 0;
781 static const luaL_reg screen_methods[] = {
782 {"windows", screen_get_windows},
783 {"displays", screen_get_displays},
784 {"display", screen_get_display},
785 {"command", screen_exec_command},
786 {"append_msg", screen_append_msg},
787 {"hook", LuaRegEvent},
788 {"input", screen_input},
789 {0, 0}
792 static const luaL_reg screen_metamethods[] = {
793 {0, 0}
796 static const struct Xet_reg screen_setters[] = {
797 {0, 0}
800 static const struct Xet_reg screen_getters[] = {
801 {0, 0}
804 /** }}} */
806 /** Public functions {{{ */
808 /* FIXME: Think about this: will it affect the registered handlers?*/
809 static lua_State *L;
810 int LuaInit(void)
812 L = luaL_newstate();
814 luaL_openlibs(L);
816 #define REGISTER(X) struct_register(L, #X , X ## _methods, X##_metamethods, X##_setters, X##_getters)
818 REGISTER(screen);
819 REGISTER(window);
820 REGISTER(display);
821 REGISTER(user);
822 REGISTER(canvas);
823 REGISTER(callback);
825 /* To store handler funcs */
826 luaL_getmetatable(L, "screen");
827 /* _keyfunc[key]->func */
828 lua_pushstring(L, "_funcreg");
829 lua_newtable(L);
830 lua_rawset(L, -3);
831 lua_pop(L, 1);
833 return 0;
836 /* An error message on top of the stack. */
837 static void
838 LuaShowErr(lua_State *L)
840 struct display *d = display;
841 unsigned int len;
842 const char *message = luaL_checklstring(L, -1, &len);
843 LMsg(0, "%s", message ? message : "Unknown error");
844 lua_pop(L, 1);
845 display = d;
848 struct fn_def
850 void (*push_fn)(lua_State *, void*);
851 void *value;
854 static int
855 LuaCallProcess(const char *name, struct fn_def defs[])
857 int argc = 0;
859 lua_getfield(L, LUA_GLOBALSINDEX, name);
860 if (lua_isnil(L, -1))
862 lua_pop(L,1);
863 return 0;
865 for (argc = 0; defs[argc].push_fn; argc++)
866 defs[argc].push_fn(L, defs[argc].value);
867 if (lua_pcall(L, argc, 0, 0) == LUA_ERRRUN && lua_isstring(L, -1))
869 LuaShowErr(L);
870 return 0;
872 return 1;
875 int LuaSource(const char *file, int async)
877 if (!L)
878 return 0;
879 struct stat st;
880 if (stat(file, &st) == -1)
881 Msg(errno, "Error loading lua script file '%s'", file);
882 else
884 int len = strlen(file);
885 if (len < 4 || strncmp(file + len - 4, ".lua", 4) != 0)
886 return 0;
887 if (luaL_dofile(L, file) && lua_isstring(L, -1))
889 LuaShowErr(L);
890 return 0;
892 return 1;
894 return 0;
897 int LuaFinit(void)
899 if (!L)
900 return 0;
901 lua_close(L);
902 L = (lua_State*)0;
903 return 0;
907 LuaProcessCaption(const char *caption, struct win *win, int len)
909 if (!L)
910 return 0;
911 struct fn_def params[] = {
912 {lua_pushstring, caption},
913 {push_window, &win},
914 {lua_pushinteger, len},
915 {NULL, NULL}
917 return LuaCallProcess("process_caption", params);
920 static void
921 push_stringarray(lua_State *L, char **args)
923 int i;
924 lua_newtable(L);
925 for (i = 1; args && *args; i++) {
926 lua_pushinteger(L, i);
927 lua_pushstring(L, *args++);
928 lua_settable(L, -3);
933 LuaPushParams(lua_State *L, const char *params, va_list va)
935 int num = 0;
936 while (*params)
938 switch (*params)
940 case 's':
941 lua_pushstring(L, va_arg(va, char *));
942 break;
943 case 'S':
944 push_stringarray(L, va_arg(va, char **));
945 break;
946 case 'i':
947 lua_pushinteger(L, va_arg(va, int));
948 break;
949 case 'd':
951 struct display *d = va_arg(va, struct display *);
952 push_display(L, &d);
953 break;
956 params++;
957 num++;
959 return num;
962 int LuaCall(const char *func, const char **argv)
964 int argc;
965 if (!L)
966 return 0;
968 StackDump(L, "Before LuaCall\n");
969 lua_getfield(L, LUA_GLOBALSINDEX, func);
970 if (lua_isnil(L, -1))
972 lua_pop(L, 1);
973 lua_pushstring(L, "Could not find the script function\n");
974 LuaShowErr(L);
975 return 0;
977 for (argc = 0; *argv; argv++, argc++)
979 lua_pushstring(L, *argv);
981 if (lua_pcall(L, argc, 0, 0) == LUA_ERRRUN)
983 if(lua_isstring(L, -1))
985 StackDump(L, "After LuaCall\n");
986 LuaShowErr(L);
987 return 0;
990 return 1;
993 /*** Lua callback handler management {{{ */
996 LuaPushHTable(lua_State *L, int screen, const char * t)
998 lua_pushstring(L, t);
999 lua_rawget(L, screen);
1000 /* FIXME: Do we need to balance the stack here? */
1001 if (lua_isnil(L, -1))
1002 luaL_error(L, "Fatal! Fail to get function registeration table!");
1003 return lua_gettop(L);
1006 void
1007 LuaPushHandler(lua_State *L, lua_handler lh)
1009 int funcreg;
1010 if (lh->type == LUA_HANDLER_TYPE_F)
1012 luaL_getmetatable(L, "screen");
1013 funcreg = LuaPushHTable(L, lua_gettop(L), "_funcreg");
1014 lua_rawgeti(L, funcreg, lh->u.reference);
1015 lua_replace(L, -3);
1016 lua_pop(L, 1);
1018 else
1020 lua_getfield(L, LUA_GLOBALSINDEX, lh->u.name);
1025 LuaFuncKey(lua_State *L, int idx, int ref)
1027 int key, funcreg, sc;
1028 luaL_getmetatable(L, "screen");
1029 sc = lua_gettop(L);
1030 funcreg = LuaPushHTable(L, sc, "_funcreg");
1032 lua_pushvalue(L, idx);
1033 key = luaL_ref(L, funcreg);
1034 lua_pop(L, 2);
1035 return key;
1038 void
1039 LuaHUnRef(lua_State *L, int key)
1041 int funcreg, sc;
1042 luaL_getmetatable(L, "screen");
1043 sc = lua_gettop(L);
1044 funcreg = LuaPushHTable(L, sc, "_funcreg");
1045 luaL_unref(L, funcreg, key);
1048 lua_handler
1049 LuaCheckHandler(lua_State *L, int idx, int ref)
1051 int key;
1052 if (idx < 0)
1053 idx = lua_gettop(L) + 1 - idx;
1055 if (lua_isstring(L, idx))
1057 const char * handler;
1058 /* registered with func name.*/
1059 handler = luaL_checkstring(L, idx);
1060 lua_getfield(L, LUA_GLOBALSINDEX, handler);
1061 if (!lua_isfunction(L, -1))
1062 luaL_error(L, "The specified handler %s in param #%d is not a function", handler, idx);
1063 lua_pop(L, 1);
1064 return LuaAllocHandler(handler, 0);
1066 else if (!lua_isfunction(L, idx))
1067 luaL_error(L, "Handler should be a function or the name of function");
1069 key = LuaFuncKey(L, idx, ref);
1070 return LuaAllocHandler(NULL, key);
1073 /* }}} **/
1075 static int
1076 LuaDispatch(void *handler, const char *params, va_list va)
1078 lua_handler lh = (lua_handler)handler;
1079 int argc, retvalue;
1081 StackDump(L, "before dispatch");
1083 LuaPushHandler(L, lh);
1084 if (lua_isnil(L, -1))
1086 lua_pop(L, 1);
1087 return 0;
1089 argc = LuaPushParams(L, params, va);
1091 if (lua_pcall(L, argc, 1, 0) == LUA_ERRRUN && lua_isstring(L, -1))
1093 StackDump(L, "After LuaDispatch\n");
1094 LuaShowErr(L);
1095 return 0;
1097 retvalue = lua_tonumber(L, -1);
1098 lua_pop(L, 1);
1099 return retvalue;
1102 int LuaForeWindowChanged(void)
1104 struct fn_def params[] = {
1105 {push_display, &display},
1106 {push_window, display ? &D_fore : &fore},
1107 {NULL, NULL}
1109 if (!L)
1110 return 0;
1111 return LuaCallProcess("fore_changed", params);
1114 #define SEVNAME_MAX 30
1115 static int
1116 LuaRegEvent(lua_State *L)
1118 /* signature: hook(obj, event, handler, priv);
1119 * or: hook(event, handler, priv)
1120 * returns: A ticket for later unregister. */
1121 int idx = 1, argc = lua_gettop(L);
1122 unsigned int priv = 31; /* Default privilege */
1123 lua_handler lh;
1125 char *obj = NULL;
1126 const char *objname = "global";
1128 static char evbuf[SEVNAME_MAX];
1129 const char *event;
1131 struct script_event *sev;
1133 StackDump(L, "Before RegEvent\n");
1135 /* Identify the object, if specified */
1136 if (luaL_getmetafield(L, 1, "_objname"))
1138 objname = luaL_checkstring(L, -1);
1139 lua_pop(L, 1);
1140 if (!strcmp("screen", objname))
1141 objname = "global";
1142 else
1143 obj = *(char **)lua_touserdata(L, 1);
1144 idx++;
1147 event = luaL_checkstring(L, idx++);
1148 snprintf(evbuf, SEVNAME_MAX, "%s_%s", objname, event);
1150 /* Check and get the handler */
1151 lh = LuaCheckHandler(L, idx++, 1);
1152 if (!lh)
1153 luaL_error(L, "Out of memory");
1155 StackDump(L, "In RegEvent\n");
1157 if (idx <= argc)
1158 priv = luaL_checkinteger(L, idx);
1160 sev = object_get_event(obj, evbuf);
1161 if (sev)
1163 struct listener *l;
1164 l = (struct listener *)malloc(sizeof(struct listener));
1165 if (!l)
1166 return luaL_error(L, "Out of memory");
1167 l->priv = priv;
1168 l->bd = &lua_binding;
1169 l->handler = (void *)lh;
1170 register_listener(sev, l);
1171 /* Return the ticket for un-register */
1172 push_callback(L, &l);
1174 else
1175 return luaL_error(L, "Invalid event specified: %s for object %s", event, objname);
1177 StackDump(L, "After RegEvent\n");
1178 return 1;
1181 /** }}} */
1183 struct ScriptFuncs LuaFuncs =
1185 LuaForeWindowChanged,
1186 LuaProcessCaption
1189 struct binding lua_binding =
1191 "lua", /*name*/
1192 0, /*inited*/
1193 0, /*registered*/
1194 LuaInit,
1195 LuaFinit,
1196 LuaCall,
1197 LuaSource,
1198 LuaDispatch,
1199 0, /*b_next*/
1200 &LuaFuncs