Clean up of the callback unhook part.
[screen-lua.git] / src / lua.c
blobd09e2804aac34c165b1181f6b72ca653659e1dfc
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 LuaHRef(lua_State *L, int key, int reg);
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 = 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 LuaHRef(L, (*lh)->u.reference, 0);
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 CHECK_TYPE(callback, struct listener)
325 static int
326 callback_unhook(lua_State *L)
328 /*Emulate check_callback() */
329 struct listener **ppl;
330 luaL_checktype(L, 1, LUA_TUSERDATA);
331 ppl = (struct listener **) luaL_checkudata(L, 1, "callback");
333 if (!ppl)
334 luaL_typerror(L, 1, "callback");
336 if (!*ppl)
338 lua_pushboolean(L, 0);
339 lua_pushstring(L, "Callback already unhooked.");
340 LuaShowErr(L);
342 else
344 LuaFreeHandler(L, &(*ppl)->handler);
345 unregister_listener(*ppl);
346 *ppl = 0;
347 lua_pushboolean(L, 1);
349 return 1;
352 static const luaL_reg callback_methods[] = {
353 {"unhook", callback_unhook},
354 {0, 0}
357 static const luaL_reg callback_metamethods[] = {
358 {0, 0}
361 static const struct Xet_reg callback_setters[] = {
362 {0, 0}
365 static const struct Xet_reg callback_getters[] = {
366 {0, 0}
370 /** }}} */
372 /** Window {{{ */
374 PUSH_TYPE(window, struct win)
376 CHECK_TYPE(window, struct win)
378 static int get_window(lua_State *L, void *v)
380 push_window(L, (struct win **)v);
381 return 1;
384 static int
385 window_change_title(lua_State *L)
387 struct win *w = check_window(L, 1);
388 unsigned int len;
389 const char *title = luaL_checklstring(L, 2, &len);
390 ChangeAKA(w, (char *)title, len);
391 return 0;
394 static int
395 window_get_monitor_status(lua_State *L)
397 struct win *w = check_window(L, 1);
398 int activity = luaL_checkint(L, 2);
399 if (activity)
400 /*monitor*/
401 lua_pushinteger(L, w->w_monitor != MON_OFF);
402 else
403 /*silence*/
404 lua_pushinteger(L, w->w_silence == SILENCE_ON ? w->w_silencewait: 0);
406 return 1;
409 static const luaL_reg window_methods[] = {
410 {"get_monitor_status", window_get_monitor_status},
411 {"hook", LuaRegEvent},
412 {0, 0}
415 static int
416 window_tostring(lua_State *L)
418 char str[128];
419 struct win *w = check_window(L, 1);
420 snprintf(str, sizeof(str), "{window #%d: '%s'}", w->w_number, w->w_title);
421 lua_pushstring(L, str);
422 return 1;
425 static int
426 window_equality(lua_State *L)
428 struct win *w1 = check_window(L, 1), *w2 = check_window(L, 2);
429 lua_pushboolean(L, (w1 == w2 || (w1 && w2 && w1->w_number == w2->w_number)));
430 return 1;
433 static const luaL_reg window_metamethods[] = {
434 {"__tostring", window_tostring},
435 {"__eq", window_equality},
436 {0, 0}
439 static const struct Xet_reg window_setters[] = {
440 {"title", 0, 0, window_change_title/*absolute setter*/},
441 {0, 0}
444 static const struct Xet_reg window_getters[] = {
445 {"title", get_string, offsetof(struct win, w_title) + 8},
446 {"number", get_int, offsetof(struct win, w_number)},
447 {"dir", get_string, offsetof(struct win, w_dir)},
448 {"tty", get_string, offsetof(struct win, w_tty)},
449 {"pid", get_int, offsetof(struct win, w_pid)},
450 {"group", get_window, offsetof(struct win, w_group)},
451 {"bell", get_int, offsetof(struct win, w_bell)},
452 {0, 0}
456 /** }}} */
458 /** AclUser {{{ */
460 PUSH_TYPE(user, struct acluser)
462 CHECK_TYPE(user, struct acluser)
464 static int
465 get_user(lua_State *L, void *v)
467 push_user(L, (struct acluser **)v);
468 return 1;
471 static const luaL_reg user_methods[] = {
472 {0, 0}
475 static int
476 user_tostring(lua_State *L)
478 char str[128];
479 struct acluser *u = check_user(L, 1);
480 snprintf(str, sizeof(str), "{user '%s'}", u->u_name);
481 lua_pushstring(L, str);
482 return 1;
485 static const luaL_reg user_metamethods[] = {
486 {"__tostring", user_tostring},
487 {0, 0}
490 static const struct Xet_reg user_setters[] = {
491 {0, 0}
494 static const struct Xet_reg user_getters[] = {
495 {"name", get_string, offsetof(struct acluser, u_name)},
496 {"password", get_string, offsetof(struct acluser, u_password)},
497 {0, 0}
500 /** }}} */
502 /** Canvas {{{ */
504 PUSH_TYPE(canvas, struct canvas)
506 CHECK_TYPE(canvas, struct canvas)
508 static int
509 get_canvas(lua_State *L, void *v)
511 push_canvas(L, (struct canvas **)v);
512 return 1;
515 static int
516 canvas_select(lua_State *L)
518 struct canvas *c = check_canvas(L, 1);
519 if (!display || D_forecv == c)
520 return 0;
521 SetCanvasWindow(c, Layer2Window(c->c_layer));
522 D_forecv = c;
524 /* XXX: the following all is duplicated from process.c:DoAction.
525 * Should these be in some better place?
527 ResizeCanvas(&D_canvas);
528 RecreateCanvasChain();
529 RethinkDisplayViewports();
530 ResizeLayersToCanvases(); /* redisplays */
531 fore = D_fore = Layer2Window(D_forecv->c_layer);
532 flayer = D_forecv->c_layer;
533 #ifdef RXVT_OSC
534 if (D_xtermosc[2] || D_xtermosc[3])
536 Activate(-1);
537 break;
539 #endif
540 RefreshHStatus();
541 #ifdef RXVT_OSC
542 RefreshXtermOSC();
543 #endif
544 flayer = D_forecv->c_layer;
545 CV_CALL(D_forecv, LayRestore();LaySetCursor());
546 WindowChanged(0, 'F');
547 return 1;
550 static const luaL_reg canvas_methods[] = {
551 {"select", canvas_select},
552 {0, 0}
555 static const luaL_reg canvas_metamethods[] = {
556 {0, 0}
559 static const struct Xet_reg canvas_setters[] = {
560 {0, 0}
563 static int
564 canvas_get_window(lua_State *L)
566 struct canvas *c = check_canvas(L, 1);
567 struct win *win = Layer2Window(c->c_layer);
568 if (win)
569 push_window(L, &win);
570 else
571 lua_pushnil(L);
572 return 1;
575 static const struct Xet_reg canvas_getters[] = {
576 {"next", get_canvas, offsetof(struct canvas, c_next)},
577 {"xoff", get_int, offsetof(struct canvas, c_xoff)},
578 {"yoff", get_int, offsetof(struct canvas, c_yoff)},
579 {"xs", get_int, offsetof(struct canvas, c_xs)},
580 {"ys", get_int, offsetof(struct canvas, c_ys)},
581 {"xe", get_int, offsetof(struct canvas, c_xe)},
582 {"ye", get_int, offsetof(struct canvas, c_ye)},
583 {"window", 0, 0, canvas_get_window},
584 {0, 0}
587 /** }}} */
589 /** Layout {{{ */
591 PUSH_TYPE(layout, struct layout)
592 CHECK_TYPE(layout, struct layout)
594 static const struct Xet_reg layout_getters[] = {
595 {0,0}
598 static int
599 get_layout(lua_State *L, void *v)
601 push_layout(L, (struct layout **)v);
602 return 1;
605 /** }}} */
607 /** Display {{{ */
609 PUSH_TYPE(display, struct display)
611 CHECK_TYPE(display, struct display)
613 static int
614 display_get_canvases(lua_State *L)
616 struct display *d;
617 struct canvas *iter;
618 int count;
620 d = check_display(L, 1);
621 lua_newtable(L);
622 for (iter = d->d_cvlist, count = 0; iter; iter = iter->c_next, count++) {
623 lua_pushinteger(L, count);
624 push_canvas(L, &iter);
625 lua_settable(L, -3);
628 return 1;
631 static const luaL_reg display_methods[] = {
632 {"get_canvases", display_get_canvases},
633 {0, 0}
636 static int
637 display_tostring(lua_State *L)
639 char str[128];
640 struct display *d = check_display(L, 1);
641 snprintf(str, sizeof(str), "{display: tty = '%s', term = '%s'}", d->d_usertty, d->d_termname);
642 lua_pushstring(L, str);
643 return 1;
646 static const luaL_reg display_metamethods[] = {
647 {"__tostring", display_tostring},
648 {0, 0}
651 static const struct Xet_reg display_setters[] = {
652 {0, 0}
655 static const struct Xet_reg display_getters[] = {
656 {"tty", get_string, offsetof(struct display, d_usertty)},
657 {"term", get_string, offsetof(struct display, d_termname)},
658 {"fore", get_window, offsetof(struct display, d_fore)},
659 {"other", get_window, offsetof(struct display, d_other)},
660 {"width", get_int, offsetof(struct display, d_width)},
661 {"height", get_int, offsetof(struct display, d_height)},
662 {"user", get_user, offsetof(struct display, d_user)},
663 {"layout", get_layout, offsetof(struct display, d_layout)},
664 {0, 0}
667 /** }}} */
669 /** Screen {{{ */
671 static int
672 screen_get_windows(lua_State *L)
674 struct win *iter;
675 int count;
677 lua_newtable(L);
678 for (iter = windows, count = 0; iter; iter = iter->w_next, count++) {
679 lua_pushinteger(L, iter->w_number);
680 push_window(L, &iter);
681 lua_settable(L, -3);
684 return 1;
687 static int
688 screen_get_displays(lua_State *L)
690 struct display *iter;
691 int count;
693 lua_newtable(L);
694 for (iter = displays, count = 0; iter; iter = iter->d_next, count++) {
695 lua_pushinteger(L, count);
696 push_display(L, &iter);
697 lua_settable(L, -3);
700 return 1;
703 static int
704 screen_get_display(lua_State *L)
706 push_display(L, &display);
707 return 1;
710 static int
711 screen_exec_command(lua_State *L)
713 const char *command;
714 unsigned int len;
716 command = luaL_checklstring(L, 1, &len);
717 if (command)
718 RcLine((char *)command, len);
720 return 0;
723 static int
724 screen_append_msg(lua_State *L)
726 const char *msg, *color;
727 unsigned int len;
728 msg = luaL_checklstring(L, 1, &len);
729 if (lua_isnil(L, 2))
730 color = NULL;
731 else
732 color = luaL_checklstring(L, 2, &len);
733 AppendWinMsgRend(msg, color);
734 return 0;
737 struct sinput_data
739 lua_State *L;
740 lua_handler lh;
743 void
744 script_input_fn(char *buf, int len, char *priv)
746 struct sinput_data *sidata = (struct sinput_data *)priv;
747 lua_handler lh = sidata->lh;
748 lua_State *L = sidata->L;
750 LuaPushHandler(L, lh);
751 lua_pushstring(L, buf);
752 if (lua_pcall(L, 1, 0, 0) == LUA_ERRRUN)
754 if(lua_isstring(L, -1))
756 LuaShowErr(L);
759 free(sidata);
760 LuaFreeHandler(L, &lh);
763 static int
764 screen_input(lua_State *L)
766 char * prompt = NULL;
767 lua_handler lh;
768 struct sinput_data *sidata;
770 prompt = (char *)luaL_checkstring(L, 1);
771 lh = LuaCheckHandler(L, 2, 1);
772 sidata = (struct sinput_data *)malloc(sizeof(struct sinput_data));
773 if (!sidata)
774 luaL_error(L, "Out of Memory");
776 sidata->L = L;
777 sidata->lh = lh;
778 Input(prompt, 100, INP_COOKED, script_input_fn, (char *)sidata, 0);
780 return 0;
783 static const luaL_reg screen_methods[] = {
784 {"windows", screen_get_windows},
785 {"displays", screen_get_displays},
786 {"display", screen_get_display},
787 {"command", screen_exec_command},
788 {"append_msg", screen_append_msg},
789 {"hook", LuaRegEvent},
790 {"input", screen_input},
791 {0, 0}
794 static const luaL_reg screen_metamethods[] = {
795 {0, 0}
798 static const struct Xet_reg screen_setters[] = {
799 {0, 0}
802 static const struct Xet_reg screen_getters[] = {
803 {0, 0}
806 /** }}} */
808 /** Public functions {{{ */
810 /* FIXME: Think about this: will it affect the registered handlers?*/
811 static lua_State *L;
812 int LuaInit(void)
814 L = luaL_newstate();
816 luaL_openlibs(L);
818 #define REGISTER(X) struct_register(L, #X , X ## _methods, X##_metamethods, X##_setters, X##_getters)
820 REGISTER(screen);
821 REGISTER(window);
822 REGISTER(display);
823 REGISTER(user);
824 REGISTER(canvas);
825 REGISTER(callback);
827 /* To store handler funcs */
828 luaL_getmetatable(L, "screen");
829 /* two kinds of info in this table:
830 * _funckey[func]->key
831 * _funckey[key]->refcnt */
832 lua_pushstring(L, "_funckey");
833 lua_newtable(L);
834 lua_rawset(L, -3);
835 /* two kinds of info in this table:
836 * _keyfunc[key]->func */
837 lua_pushstring(L, "_keyfunc");
838 lua_newtable(L);
839 lua_rawset(L, -3);
840 lua_pop(L, 1);
842 return 0;
845 /* An error message on top of the stack. */
846 static void
847 LuaShowErr(lua_State *L)
849 struct display *d = display;
850 unsigned int len;
851 const char *message = luaL_checklstring(L, -1, &len);
852 LMsg(0, "%s", message ? message : "Unknown error");
853 lua_pop(L, 1);
854 display = d;
857 struct fn_def
859 void (*push_fn)(lua_State *, void*);
860 void *value;
863 static int
864 LuaCallProcess(const char *name, struct fn_def defs[])
866 int argc = 0;
868 lua_getfield(L, LUA_GLOBALSINDEX, name);
869 if (lua_isnil(L, -1))
871 lua_pop(L,1);
872 return 0;
874 for (argc = 0; defs[argc].push_fn; argc++)
875 defs[argc].push_fn(L, defs[argc].value);
876 if (lua_pcall(L, argc, 0, 0) == LUA_ERRRUN && lua_isstring(L, -1))
878 LuaShowErr(L);
879 return 0;
881 return 1;
884 int LuaSource(const char *file, int async)
886 if (!L)
887 return 0;
888 struct stat st;
889 if (stat(file, &st) == -1)
890 Msg(errno, "Error loading lua script file '%s'", file);
891 else
893 int len = strlen(file);
894 if (len < 4 || strncmp(file + len - 4, ".lua", 4) != 0)
895 return 0;
896 if (luaL_dofile(L, file) && lua_isstring(L, -1))
898 LuaShowErr(L);
899 return 0;
901 return 1;
903 return 0;
906 int LuaFinit(void)
908 if (!L)
909 return 0;
910 lua_close(L);
911 L = (lua_State*)0;
912 return 0;
916 LuaProcessCaption(const char *caption, struct win *win, int len)
918 if (!L)
919 return 0;
920 struct fn_def params[] = {
921 {lua_pushstring, caption},
922 {push_window, &win},
923 {lua_pushinteger, len},
924 {NULL, NULL}
926 return LuaCallProcess("process_caption", params);
929 static void
930 push_stringarray(lua_State *L, char **args)
932 int i;
933 lua_newtable(L);
934 for (i = 1; args && *args; i++) {
935 lua_pushinteger(L, i);
936 lua_pushstring(L, *args++);
937 lua_settable(L, -3);
942 LuaPushParams(lua_State *L, const char *params, va_list va)
944 int num = 0;
945 while (*params)
947 switch (*params)
949 case 's':
950 lua_pushstring(L, va_arg(va, char *));
951 break;
952 case 'S':
953 push_stringarray(L, va_arg(va, char **));
954 break;
955 case 'i':
956 lua_pushinteger(L, va_arg(va, int));
957 break;
958 case 'd':
960 struct display *d = va_arg(va, struct display *);
961 push_display(L, &d);
962 break;
965 params++;
966 num++;
968 return num;
971 int LuaCall(const char *func, const char **argv)
973 int argc;
974 if (!L)
975 return 0;
977 StackDump(L, "Before LuaCall\n");
978 lua_getfield(L, LUA_GLOBALSINDEX, func);
979 if (lua_isnil(L, -1))
981 lua_pop(L, 1);
982 lua_pushstring(L, "Could not find the script function\n");
983 LuaShowErr(L);
984 return 0;
986 for (argc = 0; *argv; argv++, argc++)
988 lua_pushstring(L, *argv);
990 if (lua_pcall(L, argc, 0, 0) == LUA_ERRRUN)
992 if(lua_isstring(L, -1))
994 StackDump(L, "After LuaCall\n");
995 LuaShowErr(L);
996 return 0;
999 return 1;
1002 /*** Lua callback handler management {{{ */
1005 LuaPushHTable(lua_State *L, int screen, const char * t)
1007 lua_pushstring(L, t);
1008 lua_rawget(L, screen);
1009 /* FIXME: Do we need to balance the stack here? */
1010 if (lua_isnil(L, -1))
1011 luaL_error(L, "Fatal! Fail to get function registeration table!");
1012 return lua_gettop(L);
1015 void
1016 LuaPushHandler(lua_State *L, lua_handler lh)
1018 int keyfunc;
1019 if (lh->type == LUA_HANDLER_TYPE_F)
1021 luaL_getmetatable(L, "screen");
1022 keyfunc = LuaPushHTable(L, lua_gettop(L), "_keyfunc");
1023 lua_rawgeti(L, keyfunc, lh->u.reference);
1024 lua_replace(L, -3);
1025 lua_pop(L, 1);
1027 else
1029 lua_getfield(L, LUA_GLOBALSINDEX, lh->u.name);
1033 void
1034 LuaHRef(lua_State *L, int key, int reg)
1036 int funckey, keyfunc, cnt, sc, idx;
1037 luaL_getmetatable(L, "screen");
1038 sc = lua_gettop(L);
1039 funckey = LuaPushHTable(L, sc, "_funckey");
1040 keyfunc = LuaPushHTable(L, sc, "_keyfunc");
1042 lua_rawgeti(L, keyfunc, key);
1043 idx = lua_gettop(L);
1045 lua_rawgeti(L, funckey, key);
1046 cnt = lua_tointeger(L, -1);/*cnt = htable[key]*/
1047 if (!reg && cnt <= 1)
1049 /*release the last reference*/
1050 luaL_unref(L, funckey, key);
1051 lua_pushvalue(L, idx);
1052 lua_pushnil(L);
1053 lua_settable(L, funckey); /*htable[func]=key*/
1055 else
1057 lua_pushinteger(L, key);
1058 lua_pushinteger(L, reg? cnt + 1 : cnt - 1);
1059 lua_settable(L, funckey); /*htable[key] = cnt + 1*/
1061 lua_pop(L, 5);
1064 /* Ref when asked to. Never unref*/
1066 LuaFuncKey(lua_State *L, int idx, int ref)
1068 int key, funckey, sc;
1069 luaL_getmetatable(L, "screen");
1070 sc = lua_gettop(L);
1071 funckey = LuaPushHTable(L, sc, "_funckey");
1073 lua_pushvalue(L, idx);
1074 lua_gettable(L, funckey);/*funckey[func] ==?*/
1075 if (lua_isnil(L, -1))
1077 /* Not found, alloc a new key */
1078 if (!ref)
1079 return LUA_NOREF;
1081 /*funckey[key] = 1*/
1082 lua_pushinteger(L, 1);
1083 key = luaL_ref(L, funckey);
1085 /*funckey[func]=key*/
1086 lua_pushvalue(L, idx);
1087 lua_pushinteger(L, key);
1088 lua_settable(L, funckey);
1090 int keyfunc = LuaPushHTable(L, sc, "_keyfunc");
1091 /*keyfunc[key] = func*/
1092 lua_pushinteger(L, key);
1093 lua_pushvalue(L, idx);
1094 lua_settable(L, keyfunc);
1096 lua_pop(L, 1);
1098 else
1100 key = lua_tointeger(L, -1);/*key = funckey[func]*/
1101 if (ref)
1102 LuaHRef(L, key, 1);
1105 lua_pop(L, 3);
1106 return key;
1109 lua_handler
1110 LuaCheckHandler(lua_State *L, int idx, int ref)
1112 int key;
1113 if (lua_isstring(L, idx))
1115 const char * handler;
1116 /* registered with func name.*/
1117 handler = luaL_checkstring(L, idx);
1118 lua_getfield(L, LUA_GLOBALSINDEX, handler);
1119 if (!lua_isfunction(L, -1))
1120 luaL_error(L, "The specified handler %s in param #%d is not a function", handler, idx);
1121 lua_pop(L, 1);
1122 return LuaAllocHandler(handler, 0);
1124 else if (!lua_isfunction(L, idx))
1125 luaL_error(L, "Handler should be a function or the name of function");
1127 key = LuaFuncKey(L, idx, ref);
1128 return LuaAllocHandler(NULL, key);
1132 LuaHdlrComp(void *h1, void *h2)
1134 return (lua_handler)h1 - (lua_handler)h2;
1137 /* }}} **/
1139 static int
1140 LuaDispatch(void *handler, const char *params, va_list va)
1142 lua_handler lh = (lua_handler)handler;
1143 int argc, retvalue;
1145 StackDump(L, "before dispatch");
1147 LuaPushHandler(L, lh);
1148 if (lua_isnil(L, -1))
1150 lua_pop(L, 1);
1151 return 0;
1153 argc = LuaPushParams(L, params, va);
1155 if (lua_pcall(L, argc, 1, 0) == LUA_ERRRUN && lua_isstring(L, -1))
1157 StackDump(L, "After LuaDispatch\n");
1158 LuaShowErr(L);
1159 return 0;
1161 retvalue = lua_tonumber(L, -1);
1162 lua_pop(L, 1);
1163 return retvalue;
1166 int LuaForeWindowChanged(void)
1168 struct fn_def params[] = {
1169 {push_display, &display},
1170 {push_window, display ? &D_fore : &fore},
1171 {NULL, NULL}
1173 if (!L)
1174 return 0;
1175 return LuaCallProcess("fore_changed", params);
1178 #define SEVNAME_MAX 30
1179 static int
1180 LuaRegEvent(lua_State *L)
1182 /* signature: hook(obj, event, handler, priv);
1183 * or: hook(event, handler, priv)
1184 * returns: A ticket for later unregister. */
1185 int idx = 1, argc = lua_gettop(L);
1186 unsigned int priv = 31; /* Default privilege */
1187 lua_handler lh;
1189 char *obj = NULL;
1190 const char *objname = "global";
1192 static char evbuf[SEVNAME_MAX];
1193 const char *event;
1195 struct script_event *sev;
1197 StackDump(L, "Before RegEvent\n");
1199 /* Identify the object, if specified */
1200 if (luaL_getmetafield(L, 1, "_objname"))
1202 objname = luaL_checkstring(L, -1);
1203 lua_pop(L, 1);
1204 if (!strcmp("screen", objname))
1205 objname = "global";
1206 else
1207 obj = *(char **)lua_touserdata(L, 1);
1208 idx++;
1211 event = luaL_checkstring(L, idx++);
1212 snprintf(evbuf, SEVNAME_MAX, "%s_%s", objname, event);
1214 /* Check and get the handler */
1215 lh = LuaCheckHandler(L, idx++, 1);
1216 if (!lh)
1217 luaL_error(L, "Out of memory");
1219 StackDump(L, "In RegEvent\n");
1221 if (idx <= argc)
1222 priv = luaL_checkinteger(L, idx);
1224 sev = object_get_event(obj, evbuf);
1225 if (sev)
1227 struct listener *l;
1228 l = (struct listener *)malloc(sizeof(struct listener));
1229 if (!l)
1230 return luaL_error(L, "Out of memory");
1231 l->priv = priv;
1232 l->bd = &lua_binding;
1233 l->handler = (void *)lh;
1234 if (register_listener(sev, l))
1236 free(l);
1237 if (lh->type == LUA_HANDLER_TYPE_N)
1238 return luaL_error(L, "Handler %s has already been registered", lh->u.name);
1239 else
1240 return luaL_error(L, "Handler has already been registered");
1242 /* Return the ticket for un-register */
1243 push_callback(L, &l);
1245 else
1246 return luaL_error(L, "Invalid event specified: %s for object %s", event, objname);
1248 StackDump(L, "After RegEvent\n");
1249 return 1;
1252 /** }}} */
1254 struct ScriptFuncs LuaFuncs =
1256 LuaForeWindowChanged,
1257 LuaProcessCaption
1260 struct binding lua_binding =
1262 "lua", /*name*/
1263 0, /*inited*/
1264 0, /*registered*/
1265 LuaInit,
1266 LuaFinit,
1267 LuaCall,
1268 LuaSource,
1269 LuaDispatch,
1270 LuaHdlrComp,
1271 0, /*b_next*/
1272 &LuaFuncs