Merge branch 'lua-scripting' (early part) into screen-scripting-soc
[screen-lua.git] / src / lua.c
blob0bbd2b280dfed87ee12cbd358c82301f21323d96
1 /* Lua scripting support
3 * Copyright (c) 2008 Sadrul Habib Chowdhury (sadrul@users.sf.net)
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 3, or (at your option)
8 * any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program (see the file COPYING); if not, write to the
17 * Free Software Foundation, Inc.,
18 * 51 Franklin Street, Fifth Floor, Boston, MA 02111-1301 USA
20 ****************************************************************
22 #include <sys/types.h>
23 #include "config.h"
24 #include "screen.h"
25 #include <sys/stat.h>
26 #include <unistd.h>
28 #include <stdio.h>
29 #include <string.h>
30 #include <stdlib.h>
32 #include "extern.h"
33 #include "logfile.h"
35 #include <lua.h>
36 #include <lauxlib.h>
37 #include <lualib.h>
39 static int StackDump(lua_State *L, const char *message)
41 FILE *f = fopen("/tmp/debug/stack", "ab");
42 int i = lua_gettop(L);
43 if (message)
44 fprintf(f, "%s", message);
45 while (i)
47 int t = lua_type(L, i);
48 switch (t)
50 case LUA_TSTRING:
51 fprintf(f, "String: %s\n", lua_tostring(L, i));
52 break;
54 case LUA_TBOOLEAN:
55 fprintf(f, "Boolean: %s\n", lua_toboolean(L, i) ? "true" : "false");
56 break;
58 case LUA_TNUMBER:
59 fprintf(f, "Number: %g\n", lua_tonumber(L, i));
60 break;
62 default:
63 fprintf(f, "Type: %s\n", lua_typename(L, t));
65 i--;
67 if (message)
68 fprintf(f, "----\n");
69 fclose(f);
70 return 0;
73 extern struct win *windows, *fore;
74 extern struct display *displays, *display;
75 extern struct LayFuncs WinLf;
76 extern struct layer *flayer;
78 static int LuaDispatch(void *handler, const char *params, va_list va);
79 static int LuaRegEvent(lua_State *L);
80 static int LuaUnRegEvent(lua_State *L);
81 static void LuaShowErr(lua_State *L);
83 /** Template {{{ */
85 #define CHECK_TYPE(name, type) \
86 static type * \
87 check_##name(lua_State *L, int index) \
88 { \
89 type **var; \
90 luaL_checktype(L, index, LUA_TUSERDATA); \
91 var = (type **) luaL_checkudata(L, index, #name); \
92 if (!var || !*var) \
93 luaL_typerror(L, index, #name); \
94 return *var; \
97 #define PUSH_TYPE(name, type) \
98 static void \
99 push_##name(lua_State *L, type **t) \
101 if (!t || !*t) \
102 lua_pushnil(L); \
103 else \
105 type **r; \
106 r = (type **)lua_newuserdata(L, sizeof(type *)); \
107 *r = *t; \
108 luaL_getmetatable(L, #name); \
109 lua_setmetatable(L,-2); \
113 /* Much of the following template comes from:
114 * http://lua-users.org/wiki/BindingWithMembersAndMethods
117 static int get_int (lua_State *L, void *v)
119 lua_pushinteger (L, *(int*)v);
120 return 1;
123 static int set_int (lua_State *L, void *v)
125 *(int*)v = luaL_checkint(L, 3);
126 return 0;
129 static int get_number (lua_State *L, void *v)
131 lua_pushnumber(L, *(lua_Number*)v);
132 return 1;
135 static int set_number (lua_State *L, void *v)
137 *(lua_Number*)v = luaL_checknumber(L, 3);
138 return 0;
141 static int get_string (lua_State *L, void *v)
143 lua_pushstring(L, (char*)v );
144 return 1;
147 static int set_string (lua_State *L, void *v)
149 *(const char**)v = luaL_checkstring(L, 3);
150 return 0;
153 typedef int (*Xet_func) (lua_State *L, void *v);
155 /* member info for get and set handlers */
156 struct Xet_reg
158 const char *name; /* member name */
159 Xet_func func; /* get or set function for type of member */
160 size_t offset; /* offset of member within the struct */
161 int (*absolute)(lua_State *);
164 static void Xet_add (lua_State *L, const struct Xet_reg *l)
166 if (!l)
167 return;
168 for (; l->name; l++)
170 lua_pushstring(L, l->name);
171 lua_pushlightuserdata(L, (void*)l);
172 lua_settable(L, -3);
176 static int Xet_call (lua_State *L)
178 /* for get: stack has userdata, index, lightuserdata */
179 /* for set: stack has userdata, index, value, lightuserdata */
180 const struct Xet_reg *m = (const struct Xet_reg *)lua_touserdata(L, -1); /* member info */
181 lua_pop(L, 1); /* drop lightuserdata */
182 luaL_checktype(L, 1, LUA_TUSERDATA);
183 if (m->absolute)
184 return m->absolute(L);
185 return m->func(L, *(char**)lua_touserdata(L, 1) + m->offset);
188 static int index_handler (lua_State *L)
190 /* stack has userdata, index */
191 lua_pushvalue(L, 2); /* dup index */
192 lua_rawget(L, lua_upvalueindex(1)); /* lookup member by name */
193 if (!lua_islightuserdata(L, -1))
195 lua_pop(L, 1); /* drop value */
196 lua_pushvalue(L, 2); /* dup index */
197 lua_gettable(L, lua_upvalueindex(2)); /* else try methods */
198 if (lua_isnil(L, -1)) /* invalid member */
199 luaL_error(L, "cannot get member '%s'", lua_tostring(L, 2));
200 return 1;
202 return Xet_call(L); /* call get function */
205 static int newindex_handler (lua_State *L)
207 /* stack has userdata, index, value */
208 lua_pushvalue(L, 2); /* dup index */
209 lua_rawget(L, lua_upvalueindex(1)); /* lookup member by name */
210 if (!lua_islightuserdata(L, -1)) /* invalid member */
211 luaL_error(L, "cannot set member '%s'", lua_tostring(L, 2));
212 return Xet_call(L); /* call set function */
215 static int
216 struct_register(lua_State *L, const char *name, const luaL_reg fn_methods[], const luaL_reg meta_methods[],
217 const struct Xet_reg setters[], const struct Xet_reg getters[])
219 int metatable, methods;
221 /* create methods table & add it to the table of globals */
222 luaL_register(L, name, fn_methods);
223 methods = lua_gettop(L);
225 /* create metatable & add it to the registry */
226 luaL_newmetatable(L, name);
227 luaL_register(L, 0, meta_methods); /* fill metatable */
229 /* To identify the type of object */
230 lua_pushstring(L, "_objname");
231 lua_pushstring(L, name);
232 lua_rawset(L, -3);
234 metatable = lua_gettop(L);
236 lua_pushliteral(L, "__metatable");
237 lua_pushvalue(L, methods); /* dup methods table*/
238 lua_rawset(L, metatable); /* hide metatable:
239 metatable.__metatable = methods */
241 lua_pushliteral(L, "__index");
242 lua_pushvalue(L, metatable); /* upvalue index 1 */
243 Xet_add(L, getters); /* fill metatable with getters */
244 lua_pushvalue(L, methods); /* upvalue index 2 */
245 lua_pushcclosure(L, index_handler, 2);
246 lua_rawset(L, metatable); /* metatable.__index = index_handler */
248 lua_pushliteral(L, "__newindex");
249 lua_newtable(L); /* table for members you can set */
250 Xet_add(L, setters); /* fill with setters */
251 lua_pushcclosure(L, newindex_handler, 1);
252 lua_rawset(L, metatable); /* metatable.__newindex = newindex_handler */
254 lua_pop(L, 1); /* drop metatable */
255 return 1; /* return methods on the stack */
258 /** }}} */
260 /** Window {{{ */
262 PUSH_TYPE(window, struct win)
264 CHECK_TYPE(window, struct win)
266 static int get_window(lua_State *L, void *v)
268 push_window(L, (struct win **)v);
269 return 1;
272 static int
273 window_change_title(lua_State *L)
275 struct win *w = check_window(L, 1);
276 unsigned int len;
277 const char *title = luaL_checklstring(L, 2, &len);
278 ChangeAKA(w, (char *)title, len);
279 return 0;
282 static int
283 window_get_monitor_status(lua_State *L)
285 struct win *w = check_window(L, 1);
286 int activity = luaL_checkint(L, 2);
287 if (activity)
288 /*monitor*/
289 lua_pushinteger(L, w->w_monitor != MON_OFF);
290 else
291 /*silence*/
292 lua_pushinteger(L, w->w_silence == SILENCE_ON ? w->w_silencewait: 0);
294 return 1;
297 static const luaL_reg window_methods[] = {
298 {"get_monitor_status", window_get_monitor_status},
299 {"hook", LuaRegEvent},
300 {0, 0}
303 static int
304 window_tostring(lua_State *L)
306 char str[128];
307 struct win *w = check_window(L, 1);
308 snprintf(str, sizeof(str), "{window #%d: '%s'}", w->w_number, w->w_title);
309 lua_pushstring(L, str);
310 return 1;
313 static int
314 window_equality(lua_State *L)
316 struct win *w1 = check_window(L, 1), *w2 = check_window(L, 2);
317 lua_pushboolean(L, (w1 == w2 || (w1 && w2 && w1->w_number == w2->w_number)));
318 return 1;
321 static const luaL_reg window_metamethods[] = {
322 {"__tostring", window_tostring},
323 {"__eq", window_equality},
324 {0, 0}
327 static const struct Xet_reg window_setters[] = {
328 {"title", 0, 0, window_change_title/*absolute setter*/},
329 {0, 0}
332 static const struct Xet_reg window_getters[] = {
333 {"title", get_string, offsetof(struct win, w_title) + 8},
334 {"number", get_int, offsetof(struct win, w_number)},
335 {"dir", get_string, offsetof(struct win, w_dir)},
336 {"tty", get_string, offsetof(struct win, w_tty)},
337 {"pid", get_int, offsetof(struct win, w_pid)},
338 {"group", get_window, offsetof(struct win, w_group)},
339 {"bell", get_int, offsetof(struct win, w_bell)},
340 {0, 0}
344 /** }}} */
346 /** AclUser {{{ */
348 PUSH_TYPE(user, struct acluser)
350 CHECK_TYPE(user, struct acluser)
352 static int
353 get_user(lua_State *L, void *v)
355 push_user(L, (struct acluser **)v);
356 return 1;
359 static const luaL_reg user_methods[] = {
360 {0, 0}
363 static int
364 user_tostring(lua_State *L)
366 char str[128];
367 struct acluser *u = check_user(L, 1);
368 snprintf(str, sizeof(str), "{user '%s'}", u->u_name);
369 lua_pushstring(L, str);
370 return 1;
373 static const luaL_reg user_metamethods[] = {
374 {"__tostring", user_tostring},
375 {0, 0}
378 static const struct Xet_reg user_setters[] = {
379 {0, 0}
382 static const struct Xet_reg user_getters[] = {
383 {"name", get_string, offsetof(struct acluser, u_name)},
384 {"password", get_string, offsetof(struct acluser, u_password)},
385 {0, 0}
388 /** }}} */
390 /** Canvas {{{ */
392 PUSH_TYPE(canvas, struct canvas)
394 CHECK_TYPE(canvas, struct canvas)
396 static int
397 get_canvas(lua_State *L, void *v)
399 push_canvas(L, (struct canvas **)v);
400 return 1;
403 static int
404 canvas_select(lua_State *L)
406 struct canvas *c = check_canvas(L, 1);
407 if (!display || D_forecv == c)
408 return 0;
409 SetCanvasWindow(c, Layer2Window(c->c_layer));
410 D_forecv = c;
412 /* XXX: the following all is duplicated from process.c:DoAction.
413 * Should these be in some better place?
415 ResizeCanvas(&D_canvas);
416 RecreateCanvasChain();
417 RethinkDisplayViewports();
418 ResizeLayersToCanvases(); /* redisplays */
419 fore = D_fore = Layer2Window(D_forecv->c_layer);
420 flayer = D_forecv->c_layer;
421 #ifdef RXVT_OSC
422 if (D_xtermosc[2] || D_xtermosc[3])
424 Activate(-1);
425 break;
427 #endif
428 RefreshHStatus();
429 #ifdef RXVT_OSC
430 RefreshXtermOSC();
431 #endif
432 flayer = D_forecv->c_layer;
433 CV_CALL(D_forecv, LayRestore();LaySetCursor());
434 WindowChanged(0, 'F');
435 return 1;
438 static const luaL_reg canvas_methods[] = {
439 {"select", canvas_select},
440 {0, 0}
443 static const luaL_reg canvas_metamethods[] = {
444 {0, 0}
447 static const struct Xet_reg canvas_setters[] = {
448 {0, 0}
451 static int
452 canvas_get_window(lua_State *L)
454 struct canvas *c = check_canvas(L, 1);
455 struct win *win = Layer2Window(c->c_layer);
456 if (win)
457 push_window(L, &win);
458 else
459 lua_pushnil(L);
460 return 1;
463 static const struct Xet_reg canvas_getters[] = {
464 {"next", get_canvas, offsetof(struct canvas, c_next)},
465 {"xoff", get_int, offsetof(struct canvas, c_xoff)},
466 {"yoff", get_int, offsetof(struct canvas, c_yoff)},
467 {"xs", get_int, offsetof(struct canvas, c_xs)},
468 {"ys", get_int, offsetof(struct canvas, c_ys)},
469 {"xe", get_int, offsetof(struct canvas, c_xe)},
470 {"ye", get_int, offsetof(struct canvas, c_ye)},
471 {"window", 0, 0, canvas_get_window},
472 {0, 0}
475 /** }}} */
477 /** Layout {{{ */
479 PUSH_TYPE(layout, struct layout)
480 CHECK_TYPE(layout, struct layout)
482 static const struct Xet_reg layout_getters[] = {
483 {0,0}
486 static int
487 get_layout(lua_State *L, void *v)
489 push_layout(L, (struct layout **)v);
490 return 1;
493 /** }}} */
495 /** Display {{{ */
497 PUSH_TYPE(display, struct display)
499 CHECK_TYPE(display, struct display)
501 static int
502 display_get_canvases(lua_State *L)
504 struct display *d;
505 struct canvas *iter;
506 int count;
508 d = check_display(L, 1);
509 lua_newtable(L);
510 for (iter = d->d_cvlist, count = 0; iter; iter = iter->c_next, count++) {
511 lua_pushinteger(L, count);
512 push_canvas(L, &iter);
513 lua_settable(L, -3);
516 return 1;
519 static const luaL_reg display_methods[] = {
520 {"get_canvases", display_get_canvases},
521 {0, 0}
524 static int
525 display_tostring(lua_State *L)
527 char str[128];
528 struct display *d = check_display(L, 1);
529 snprintf(str, sizeof(str), "{display: tty = '%s', term = '%s'}", d->d_usertty, d->d_termname);
530 lua_pushstring(L, str);
531 return 1;
534 static const luaL_reg display_metamethods[] = {
535 {"__tostring", display_tostring},
536 {0, 0}
539 static const struct Xet_reg display_setters[] = {
540 {0, 0}
543 static const struct Xet_reg display_getters[] = {
544 {"tty", get_string, offsetof(struct display, d_usertty)},
545 {"term", get_string, offsetof(struct display, d_termname)},
546 {"fore", get_window, offsetof(struct display, d_fore)},
547 {"other", get_window, offsetof(struct display, d_other)},
548 {"width", get_int, offsetof(struct display, d_width)},
549 {"height", get_int, offsetof(struct display, d_height)},
550 {"user", get_user, offsetof(struct display, d_user)},
551 {"layout", get_layout, offsetof(struct display, d_layout)},
552 {0, 0}
555 /** }}} */
557 /** Screen {{{ */
559 static int
560 screen_get_windows(lua_State *L)
562 struct win *iter;
563 int count;
565 lua_newtable(L);
566 for (iter = windows, count = 0; iter; iter = iter->w_next, count++) {
567 lua_pushinteger(L, iter->w_number);
568 push_window(L, &iter);
569 lua_settable(L, -3);
572 return 1;
575 static int
576 screen_get_displays(lua_State *L)
578 struct display *iter;
579 int count;
581 lua_newtable(L);
582 for (iter = displays, count = 0; iter; iter = iter->d_next, count++) {
583 lua_pushinteger(L, count);
584 push_display(L, &iter);
585 lua_settable(L, -3);
588 return 1;
591 static int
592 screen_get_display(lua_State *L)
594 push_display(L, &display);
595 return 1;
598 static int
599 screen_exec_command(lua_State *L)
601 const char *command;
602 unsigned int len;
604 command = luaL_checklstring(L, 1, &len);
605 if (command)
606 RcLine((char *)command, len);
608 return 0;
611 static int
612 screen_append_msg(lua_State *L)
614 const char *msg, *color;
615 int len;
616 msg = luaL_checklstring(L, 1, &len);
617 if (lua_isnil(L, 2))
618 color = NULL;
619 else
620 color = luaL_checklstring(L, 2, &len);
621 AppendWinMsgRend(msg, color);
622 return 0;
625 void
626 script_input_fn(char *buf, int len, char *priv)
628 lua_State *L = (lua_State *)priv;
629 lua_pushstring(L, buf);
630 if (lua_pcall(L, 1, 0, 0) == LUA_ERRRUN)
632 if(lua_isstring(L, -1))
634 LuaShowErr(L);
639 static int
640 screen_input(lua_State *L)
642 char * prompt = NULL;
644 prompt = (char *)luaL_checkstring(L, 1);
645 Input(prompt, 100, INP_COOKED, script_input_fn, (char *)L, 0);
647 return 0;
650 static const luaL_reg screen_methods[] = {
651 {"windows", screen_get_windows},
652 {"displays", screen_get_displays},
653 {"display", screen_get_display},
654 {"command", screen_exec_command},
655 {"append_msg", screen_append_msg},
656 {"hook", LuaRegEvent},
657 {"unhook", LuaUnRegEvent},
658 {"input", screen_input},
659 {0, 0}
662 static const luaL_reg screen_metamethods[] = {
663 {0, 0}
666 static const struct Xet_reg screen_setters[] = {
667 {0, 0}
670 static const struct Xet_reg screen_getters[] = {
671 {0, 0}
674 /** }}} */
676 /** Public functions {{{ */
677 static lua_State *L;
678 int LuaInit(void)
680 L = luaL_newstate();
682 luaL_openlibs(L);
684 #define REGISTER(X) struct_register(L, #X , X ## _methods, X##_metamethods, X##_setters, X##_getters)
686 REGISTER(screen);
687 REGISTER(window);
688 REGISTER(display);
689 REGISTER(user);
690 REGISTER(canvas);
692 /* To store handler funcs */
693 luaL_getmetatable(L, "screen");
694 lua_pushstring(L, "_handlers");
695 lua_newtable(L);
696 lua_rawset(L, -3);
697 lua_pop(L, 1);
699 return 0;
702 /* An error message on top of the stack. */
703 static void
704 LuaShowErr(lua_State *L)
706 struct display *d = display;
707 unsigned int len;
708 const char *message = luaL_checklstring(L, -1, &len);
709 LMsg(0, "%s", message ? message : "Unknown error");
710 lua_pop(L, 1);
711 display = d;
714 struct fn_def
716 void (*push_fn)(lua_State *, void*);
717 void *value;
720 static int
721 LuaCallProcess(const char *name, struct fn_def defs[])
723 int argc = 0;
725 lua_getfield(L, LUA_GLOBALSINDEX, name);
726 if (lua_isnil(L, -1))
727 return 0;
728 for (argc = 0; defs[argc].push_fn; argc++)
729 defs[argc].push_fn(L, defs[argc].value);
730 if (lua_pcall(L, argc, 0, 0) == LUA_ERRRUN && lua_isstring(L, -1))
732 LuaShowErr(L);
733 return 0;
735 return 1;
738 int LuaSource(const char *file, int async)
740 if (!L)
741 return 0;
742 struct stat st;
743 if (stat(file, &st) == -1)
744 Msg(errno, "Error loading lua script file '%s'", file);
745 else
747 int len = strlen(file);
748 if (len < 4 || strncmp(file + len - 4, ".lua", 4) != 0)
749 return 0;
750 if (luaL_dofile(L, file) && lua_isstring(L, -1))
752 LuaShowErr(L);
754 return 1;
756 return 0;
759 int LuaFinit(void)
761 if (!L)
762 return 0;
763 lua_close(L);
764 L = (lua_State*)0;
765 return 0;
769 LuaProcessCaption(const char *caption, struct win *win, int len)
771 if (!L)
772 return 0;
773 struct fn_def params[] = {
774 {lua_pushstring, caption},
775 {push_window, &win},
776 {lua_pushinteger, len},
777 {NULL, NULL}
779 return LuaCallProcess("process_caption", params);
782 static void
783 push_stringarray(lua_State *L, char **args)
785 int i;
786 lua_newtable(L);
787 for (i = 1; args && *args; i++) {
788 lua_pushinteger(L, i);
789 lua_pushstring(L, *args++);
790 lua_settable(L, -3);
795 LuaPushParams(lua_State *L, const char *params, va_list va)
797 int num = 0;
798 while (*params)
800 switch (*params)
802 case 's':
803 lua_pushstring(L, va_arg(va, char *));
804 break;
805 case 'S':
806 push_stringarray(L, va_arg(va, char **));
807 break;
808 case 'i':
809 lua_pushinteger(L, va_arg(va, int));
811 params++;
812 num++;
814 return num;
817 int LuaCall(char *func, char **argv)
819 int argc;
820 if (!L)
821 return 0;
823 StackDump(L, "Before LuaCall\n");
824 lua_getfield(L, LUA_GLOBALSINDEX, func);
825 if (lua_isnil(L, -1))
827 lua_pushstring(L, "Could not find the script function\n");
828 LuaShowErr(L);
829 return 0;
831 for (argc = 0; *argv; argv++, argc++)
833 lua_pushstring(L, *argv);
835 if (lua_pcall(L, argc, 0, 0) == LUA_ERRRUN)
837 if(lua_isstring(L, -1))
839 StackDump(L, "After LuaCall\n");
840 LuaShowErr(L);
841 return 0;
844 return 1;
847 static int
848 LuaDispatch(void *handler, const char *params, va_list va)
850 const char *func = handler;
851 int argc;
853 lua_getfield(L, LUA_GLOBALSINDEX, func);
854 if (lua_isnil(L, -1))
855 return 0;
856 argc = LuaPushParams(L, params, va);
858 if (lua_pcall(L, argc, 0, 0) == LUA_ERRRUN && lua_isstring(L, -1))
860 StackDump(L, "After LuaDispatch\n");
861 LuaShowErr(L);
862 return 0;
864 return 0;
867 int LuaForeWindowChanged(void)
869 struct fn_def params[] = {
870 {push_display, &display},
871 {push_window, display ? &D_fore : &fore},
872 {NULL, NULL}
874 if (!L)
875 return 0;
876 return LuaCallProcess("fore_changed", params);
879 char *
880 LuaCheckHandler(lua_State *L, int idx, int reg)
882 if (lua_isstring(L, idx))
884 const char * handler;
885 /* registered with func name.*/
886 handler = luaL_checkstring(L, idx);
887 lua_getfield(L, LUA_GLOBALSINDEX, handler);
888 if (!lua_isfunction(L, -1))
889 luaL_error(L, "The specified handler %s in param #%d is not a function", handler, idx);
890 lua_pop(L, 1);
891 return SaveStr(handler);
893 else if (lua_isfunction(L, idx))
895 char buf[20];
896 int key, htable;
897 if (idx < 0)
898 idx = lua_gettop(L) + 1 - idx;
900 luaL_getmetatable(L, "screen");
901 lua_pushstring(L, "_handlers");
902 lua_rawget(L, -2);
903 if (lua_isnil(L, -1))
904 luaL_error(L, "Fatal! Should not happen! Fail to get global handler table!");
905 /* Map func to unique key and do reference count */
906 htable = lua_gettop(L);
907 lua_pushvalue(L, idx);
908 lua_gettable(L, htable);/*htable[func] ==?*/
909 if (lua_isnil(L, -1))
911 /* not found */
912 if (!reg)
913 return NULL;
914 lua_pushinteger(L, 1);
915 key = luaL_ref(L, htable); /*htable[key] = 1*/
916 lua_pushvalue(L, idx);
917 lua_pushinteger(L, key);
918 lua_settable(L, htable); /*htable[func]=key*/
920 else
922 int cnt;
923 key = lua_tointeger(L, -1);/*key = htable[func]*/
924 lua_gettable(L, htable);
925 cnt = lua_tointeger(L, -1);/*cnt = htable[key]*/
926 if (!reg && cnt <= 1)
928 /*release the last reference*/
929 luaL_unref(L, htable, key);
930 lua_pushvalue(L, idx);
931 lua_pushnil(L);
932 lua_settable(L, htable); /*htable[func]=key*/
934 else
936 lua_pushinteger(L, key);
937 lua_pushinteger(L, reg? cnt + 1 : cnt - 1);
938 lua_settable(L, htable); /*htable[key] = cnt + 1*/
942 lua_pop(L, 3);
943 snprintf(buf, 20, "%d", key);
944 return SaveStr(buf);
946 else
947 luaL_error(L, "Handler should be a function or the name of function");
948 return NULL;
951 #define SEVNAME_MAX 30
952 static int
953 LuaRegEvent(lua_State *L)
955 /* signature: hook(obj, event, handler, priv);
956 * or: hook(event, handler, priv)
957 * returns: A ticket for later unregister. */
958 int idx = 1, argc = lua_gettop(L);
959 unsigned int priv = 31; /* Default privilege */
961 char *obj = NULL;
962 const char *objname = "global";
964 static char evbuf[SEVNAME_MAX];
965 const char *event, *handler;
967 struct script_event *sev;
969 StackDump(L, "Before RegEvent\n");
971 /* Identify the object, if specified */
972 if (luaL_getmetafield(L, 1, "_objname"))
974 objname = luaL_checkstring(L, -1);
975 lua_pop(L, 1);
976 if (!strcmp("screen", objname))
977 objname = "global";
978 else
979 obj = *(char **)lua_touserdata(L, 1);
980 idx++;
983 event = luaL_checkstring(L, idx++);
984 snprintf(evbuf, SEVNAME_MAX, "%s_%s", objname, event);
986 /* Check and get the handler */
987 handler = LuaCheckHandler(L, idx++, 1);
989 StackDump(L, "In RegEvent\n");
991 if (idx <= argc)
992 priv = luaL_checkinteger(L, idx);
994 sev = object_get_event(obj, evbuf);
995 if (sev)
997 struct listener *l;
998 l = (struct listener *)malloc(sizeof(struct listener));
999 if (!l)
1000 return luaL_error(L, "Out of memory");
1001 l->handler = (void *)handler;
1002 l->priv = priv;
1003 l->dispatcher = LuaDispatch;
1004 if (register_listener(sev, l))
1006 free(l);
1007 return luaL_error(L, "Handler %s has already been registered", handler);
1009 /*Return the handler for un-register*/
1010 lua_pushlightuserdata(L, l);
1012 else
1013 return luaL_error(L, "Invalid event specified: %s for object %s", event, objname);
1015 StackDump(L, "After RegEvent\n");
1016 return 1;
1019 static int
1020 LuaUnRegEvent(lua_State *L)
1022 /* signature: release([obj], ticket, handler)
1023 * returns: true of success, false otherwise */
1024 int idx = 1;
1025 struct listener *l;
1026 const char *handler;
1028 /* If the param is not as expected */
1029 if (!lua_islightuserdata(L, idx))
1031 /* Then it should be the userdata to be ignore, but if not ... */
1032 if (!lua_isuserdata(L, idx))
1033 luaL_checktype(L, idx, LUA_TLIGHTUSERDATA);
1034 idx++;
1035 luaL_checktype(L, idx, LUA_TLIGHTUSERDATA);
1038 l = (struct listener*)lua_touserdata(L, idx++);
1039 /* FIXME: May unref the func too earily*/
1040 handler = LuaCheckHandler(L, idx++, 0);
1042 /*Validate the listener structure*/
1043 if (!l || !l->handler
1044 || strncmp((char *)handler, (char *)l->handler, SEVNAME_MAX))
1046 /* invalid */
1047 lua_pushboolean(L,0);
1049 else
1051 free(l->handler);
1052 unregister_listener(l);
1053 lua_pushboolean(L, 1);
1056 free(handler);
1057 return 1;
1060 /** }}} */
1062 struct ScriptFuncs LuaFuncs =
1064 LuaForeWindowChanged,
1065 LuaProcessCaption
1068 struct binding lua_binding =
1070 "lua", /*name*/
1071 0, /*inited*/
1072 0, /*registered*/
1073 LuaInit,
1074 LuaFinit,
1075 LuaCall,
1076 LuaSource,
1077 0, /*b_next*/
1078 &LuaFuncs