Do not crash on unhook.
[screen-lua.git] / src / lua.c
blob7aa3aa517aca5b27a71e7e15b70a5530207cbba5
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;
81 static int LuaDispatch(void *handler, const char *params, va_list va);
82 static int LuaRegEvent(lua_State *L);
83 static int LuaUnRegEvent(lua_State *L);
84 static void LuaShowErr(lua_State *L);
86 enum
88 LUA_HANDLER_TYPE_N = 1,
89 LUA_HANDLER_TYPE_F
92 struct lua_handler
94 int type;
95 union
97 char *name;
98 int reference;
99 } u;
100 struct listener *listener;
103 /** Template {{{ */
105 #define CHECK_TYPE(name, type) \
106 static type * \
107 check_##name(lua_State *L, int index) \
109 type **var; \
110 luaL_checktype(L, index, LUA_TUSERDATA); \
111 var = (type **) luaL_checkudata(L, index, #name); \
112 if (!var || !*var) \
113 luaL_typerror(L, index, #name); \
114 return *var; \
117 #define PUSH_TYPE(name, type) \
118 static void \
119 push_##name(lua_State *L, type **t) \
121 if (!t || !*t) \
122 lua_pushnil(L); \
123 else \
125 type **r; \
126 r = (type **)lua_newuserdata(L, sizeof(type *)); \
127 *r = *t; \
128 luaL_getmetatable(L, #name); \
129 lua_setmetatable(L,-2); \
133 /* Much of the following template comes from:
134 * http://lua-users.org/wiki/BindingWithMembersAndMethods
137 static int get_int (lua_State *L, void *v)
139 lua_pushinteger (L, *(int*)v);
140 return 1;
143 static int set_int (lua_State *L, void *v)
145 *(int*)v = luaL_checkint(L, 3);
146 return 0;
149 static int get_number (lua_State *L, void *v)
151 lua_pushnumber(L, *(lua_Number*)v);
152 return 1;
155 static int set_number (lua_State *L, void *v)
157 *(lua_Number*)v = luaL_checknumber(L, 3);
158 return 0;
161 static int get_string (lua_State *L, void *v)
163 lua_pushstring(L, (char*)v );
164 return 1;
167 static int set_string (lua_State *L, void *v)
169 *(const char**)v = luaL_checkstring(L, 3);
170 return 0;
173 typedef int (*Xet_func) (lua_State *L, void *v);
175 /* member info for get and set handlers */
176 struct Xet_reg
178 const char *name; /* member name */
179 Xet_func func; /* get or set function for type of member */
180 size_t offset; /* offset of member within the struct */
181 int (*absolute)(lua_State *);
184 static void Xet_add (lua_State *L, const struct Xet_reg *l)
186 if (!l)
187 return;
188 for (; l->name; l++)
190 lua_pushstring(L, l->name);
191 lua_pushlightuserdata(L, (void*)l);
192 lua_settable(L, -3);
196 static int Xet_call (lua_State *L)
198 /* for get: stack has userdata, index, lightuserdata */
199 /* for set: stack has userdata, index, value, lightuserdata */
200 const struct Xet_reg *m = (const struct Xet_reg *)lua_touserdata(L, -1); /* member info */
201 lua_pop(L, 1); /* drop lightuserdata */
202 luaL_checktype(L, 1, LUA_TUSERDATA);
203 if (m->absolute)
204 return m->absolute(L);
205 return m->func(L, *(char**)lua_touserdata(L, 1) + m->offset);
208 static int index_handler (lua_State *L)
210 /* stack has userdata, index */
211 lua_pushvalue(L, 2); /* dup index */
212 lua_rawget(L, lua_upvalueindex(1)); /* lookup member by name */
213 if (!lua_islightuserdata(L, -1))
215 lua_pop(L, 1); /* drop value */
216 lua_pushvalue(L, 2); /* dup index */
217 lua_gettable(L, lua_upvalueindex(2)); /* else try methods */
218 if (lua_isnil(L, -1)) /* invalid member */
219 luaL_error(L, "cannot get member '%s'", lua_tostring(L, 2));
220 return 1;
222 return Xet_call(L); /* call get function */
225 static int newindex_handler (lua_State *L)
227 /* stack has userdata, index, value */
228 lua_pushvalue(L, 2); /* dup index */
229 lua_rawget(L, lua_upvalueindex(1)); /* lookup member by name */
230 if (!lua_islightuserdata(L, -1)) /* invalid member */
231 luaL_error(L, "cannot set member '%s'", lua_tostring(L, 2));
232 return Xet_call(L); /* call set function */
235 static int
236 struct_register(lua_State *L, const char *name, const luaL_reg fn_methods[], const luaL_reg meta_methods[],
237 const struct Xet_reg setters[], const struct Xet_reg getters[])
239 int metatable, methods;
241 /* create methods table & add it to the table of globals */
242 luaL_register(L, name, fn_methods);
243 methods = lua_gettop(L);
245 /* create metatable & add it to the registry */
246 luaL_newmetatable(L, name);
247 luaL_register(L, 0, meta_methods); /* fill metatable */
249 /* To identify the type of object */
250 lua_pushstring(L, "_objname");
251 lua_pushstring(L, name);
252 lua_settable(L, -3);
254 metatable = lua_gettop(L);
256 lua_pushliteral(L, "__metatable");
257 lua_pushvalue(L, methods); /* dup methods table*/
258 lua_rawset(L, metatable); /* hide metatable:
259 metatable.__metatable = methods */
261 lua_pushliteral(L, "__index");
262 lua_pushvalue(L, metatable); /* upvalue index 1 */
263 Xet_add(L, getters); /* fill metatable with getters */
264 lua_pushvalue(L, methods); /* upvalue index 2 */
265 lua_pushcclosure(L, index_handler, 2);
266 lua_rawset(L, metatable); /* metatable.__index = index_handler */
268 lua_pushliteral(L, "__newindex");
269 lua_newtable(L); /* table for members you can set */
270 Xet_add(L, setters); /* fill with setters */
271 lua_pushcclosure(L, newindex_handler, 1);
272 lua_rawset(L, metatable); /* metatable.__newindex = newindex_handler */
274 lua_pop(L, 1); /* drop metatable */
275 return 1; /* return methods on the stack */
278 /** }}} */
280 /** Callback {{{ */
281 PUSH_TYPE(callback, struct lua_handler)
283 CHECK_TYPE(callback, struct lua_handler)
285 static int
286 callback_unhook(lua_State *L)
288 struct lua_handler *lh = check_callback(L, 1);
289 if (!lh->listener)
291 lua_pushboolean(L, 0);
292 lua_pushstring(L, "Callback already unhooked.");
293 LuaShowErr(L);
295 else
297 if (lh->type == LUA_HANDLER_TYPE_N)
299 Free(lh->u.name);
301 else
303 luaL_unref(L, LUA_REGISTRYINDEX, lh->u.reference);
304 lh->u.reference = 0;
306 unregister_listener(lh->listener);
307 lh->listener = NULL;
308 lua_pushboolean(L, 1);
310 return 1;
313 static const luaL_reg callback_methods[] = {
314 {"unhook", callback_unhook},
315 {0, 0}
318 static const luaL_reg callback_metamethods[] = {
319 {0, 0}
322 static const struct Xet_reg callback_setters[] = {
323 {0, 0}
326 static const struct Xet_reg callback_getters[] = {
327 {0, 0}
331 /** }}} */
333 /** Window {{{ */
335 PUSH_TYPE(window, struct win)
337 CHECK_TYPE(window, struct win)
339 static int get_window(lua_State *L, void *v)
341 push_window(L, (struct win **)v);
342 return 1;
345 static int
346 window_change_title(lua_State *L)
348 struct win *w = check_window(L, 1);
349 unsigned int len;
350 const char *title = luaL_checklstring(L, 2, &len);
351 ChangeAKA(w, (char *)title, len);
352 return 0;
355 static int
356 window_get_monitor_status(lua_State *L)
358 struct win *w = check_window(L, 1);
359 int activity = luaL_checkint(L, 2);
360 if (activity)
361 /*monitor*/
362 lua_pushinteger(L, w->w_monitor != MON_OFF);
363 else
364 /*silence*/
365 lua_pushinteger(L, w->w_silence == SILENCE_ON ? w->w_silencewait: 0);
367 return 1;
370 static const luaL_reg window_methods[] = {
371 {"get_monitor_status", window_get_monitor_status},
372 {"hook", LuaRegEvent},
373 {0, 0}
376 static int
377 window_tostring(lua_State *L)
379 char str[128];
380 struct win *w = check_window(L, 1);
381 snprintf(str, sizeof(str), "{window #%d: '%s'}", w->w_number, w->w_title);
382 lua_pushstring(L, str);
383 return 1;
386 static int
387 window_equality(lua_State *L)
389 struct win *w1 = check_window(L, 1), *w2 = check_window(L, 2);
390 lua_pushboolean(L, (w1 == w2 || (w1 && w2 && w1->w_number == w2->w_number)));
391 return 1;
394 static const luaL_reg window_metamethods[] = {
395 {"__tostring", window_tostring},
396 {"__eq", window_equality},
397 {0, 0}
400 static const struct Xet_reg window_setters[] = {
401 {"title", 0, 0, window_change_title/*absolute setter*/},
402 {0, 0}
405 static const struct Xet_reg window_getters[] = {
406 {"title", get_string, offsetof(struct win, w_title) + 8},
407 {"number", get_int, offsetof(struct win, w_number)},
408 {"dir", get_string, offsetof(struct win, w_dir)},
409 {"tty", get_string, offsetof(struct win, w_tty)},
410 {"pid", get_int, offsetof(struct win, w_pid)},
411 {"group", get_window, offsetof(struct win, w_group)},
412 {"bell", get_int, offsetof(struct win, w_bell)},
413 {0, 0}
417 /** }}} */
419 /** AclUser {{{ */
421 PUSH_TYPE(user, struct acluser)
423 CHECK_TYPE(user, struct acluser)
425 static int
426 get_user(lua_State *L, void *v)
428 push_user(L, (struct acluser **)v);
429 return 1;
432 static const luaL_reg user_methods[] = {
433 {0, 0}
436 static int
437 user_tostring(lua_State *L)
439 char str[128];
440 struct acluser *u = check_user(L, 1);
441 snprintf(str, sizeof(str), "{user '%s'}", u->u_name);
442 lua_pushstring(L, str);
443 return 1;
446 static const luaL_reg user_metamethods[] = {
447 {"__tostring", user_tostring},
448 {0, 0}
451 static const struct Xet_reg user_setters[] = {
452 {0, 0}
455 static const struct Xet_reg user_getters[] = {
456 {"name", get_string, offsetof(struct acluser, u_name)},
457 {"password", get_string, offsetof(struct acluser, u_password)},
458 {0, 0}
461 /** }}} */
463 /** Canvas {{{ */
465 PUSH_TYPE(canvas, struct canvas)
467 CHECK_TYPE(canvas, struct canvas)
469 static int
470 get_canvas(lua_State *L, void *v)
472 push_canvas(L, (struct canvas **)v);
473 return 1;
476 static int
477 canvas_select(lua_State *L)
479 struct canvas *c = check_canvas(L, 1);
480 if (!display || D_forecv == c)
481 return 0;
482 SetCanvasWindow(c, Layer2Window(c->c_layer));
483 D_forecv = c;
485 /* XXX: the following all is duplicated from process.c:DoAction.
486 * Should these be in some better place?
488 ResizeCanvas(&D_canvas);
489 RecreateCanvasChain();
490 RethinkDisplayViewports();
491 ResizeLayersToCanvases(); /* redisplays */
492 fore = D_fore = Layer2Window(D_forecv->c_layer);
493 flayer = D_forecv->c_layer;
494 #ifdef RXVT_OSC
495 if (D_xtermosc[2] || D_xtermosc[3])
497 Activate(-1);
498 break;
500 #endif
501 RefreshHStatus();
502 #ifdef RXVT_OSC
503 RefreshXtermOSC();
504 #endif
505 flayer = D_forecv->c_layer;
506 CV_CALL(D_forecv, LayRestore();LaySetCursor());
507 WindowChanged(0, 'F');
508 return 1;
511 static const luaL_reg canvas_methods[] = {
512 {"select", canvas_select},
513 {0, 0}
516 static const luaL_reg canvas_metamethods[] = {
517 {0, 0}
520 static const struct Xet_reg canvas_setters[] = {
521 {0, 0}
524 static int
525 canvas_get_window(lua_State *L)
527 struct canvas *c = check_canvas(L, 1);
528 struct win *win = Layer2Window(c->c_layer);
529 if (win)
530 push_window(L, &win);
531 else
532 lua_pushnil(L);
533 return 1;
536 static const struct Xet_reg canvas_getters[] = {
537 {"next", get_canvas, offsetof(struct canvas, c_next)},
538 {"xoff", get_int, offsetof(struct canvas, c_xoff)},
539 {"yoff", get_int, offsetof(struct canvas, c_yoff)},
540 {"xs", get_int, offsetof(struct canvas, c_xs)},
541 {"ys", get_int, offsetof(struct canvas, c_ys)},
542 {"xe", get_int, offsetof(struct canvas, c_xe)},
543 {"ye", get_int, offsetof(struct canvas, c_ye)},
544 {"window", 0, 0, canvas_get_window},
545 {0, 0}
548 /** }}} */
550 /** Layout {{{ */
552 PUSH_TYPE(layout, struct layout)
553 CHECK_TYPE(layout, struct layout)
555 static const struct Xet_reg layout_getters[] = {
556 {0,0}
559 static int
560 get_layout(lua_State *L, void *v)
562 push_layout(L, (struct layout **)v);
563 return 1;
566 /** }}} */
568 /** Display {{{ */
570 PUSH_TYPE(display, struct display)
572 CHECK_TYPE(display, struct display)
574 static int
575 display_get_canvases(lua_State *L)
577 struct display *d;
578 struct canvas *iter;
579 int count;
581 d = check_display(L, 1);
582 lua_newtable(L);
583 for (iter = d->d_cvlist, count = 0; iter; iter = iter->c_next, count++) {
584 lua_pushinteger(L, count);
585 push_canvas(L, &iter);
586 lua_settable(L, -3);
589 return 1;
592 static const luaL_reg display_methods[] = {
593 {"get_canvases", display_get_canvases},
594 {0, 0}
597 static int
598 display_tostring(lua_State *L)
600 char str[128];
601 struct display *d = check_display(L, 1);
602 snprintf(str, sizeof(str), "{display: tty = '%s', term = '%s'}", d->d_usertty, d->d_termname);
603 lua_pushstring(L, str);
604 return 1;
607 static const luaL_reg display_metamethods[] = {
608 {"__tostring", display_tostring},
609 {0, 0}
612 static const struct Xet_reg display_setters[] = {
613 {0, 0}
616 static const struct Xet_reg display_getters[] = {
617 {"tty", get_string, offsetof(struct display, d_usertty)},
618 {"term", get_string, offsetof(struct display, d_termname)},
619 {"fore", get_window, offsetof(struct display, d_fore)},
620 {"other", get_window, offsetof(struct display, d_other)},
621 {"width", get_int, offsetof(struct display, d_width)},
622 {"height", get_int, offsetof(struct display, d_height)},
623 {"user", get_user, offsetof(struct display, d_user)},
624 {"layout", get_layout, offsetof(struct display, d_layout)},
625 {0, 0}
628 /** }}} */
630 /** Screen {{{ */
632 static int
633 screen_get_windows(lua_State *L)
635 struct win *iter;
636 int count;
638 lua_newtable(L);
639 for (iter = windows, count = 0; iter; iter = iter->w_next, count++) {
640 lua_pushinteger(L, iter->w_number);
641 push_window(L, &iter);
642 lua_settable(L, -3);
645 return 1;
648 static int
649 screen_get_displays(lua_State *L)
651 struct display *iter;
652 int count;
654 lua_newtable(L);
655 for (iter = displays, count = 0; iter; iter = iter->d_next, count++) {
656 lua_pushinteger(L, count);
657 push_display(L, &iter);
658 lua_settable(L, -3);
661 return 1;
664 static int
665 screen_get_display(lua_State *L)
667 push_display(L, &display);
668 return 1;
671 static int
672 screen_exec_command(lua_State *L)
674 const char *command;
675 unsigned int len;
677 command = luaL_checklstring(L, 1, &len);
678 if (command)
679 RcLine((char *)command, len);
681 return 0;
684 static int
685 screen_append_msg(lua_State *L)
687 const char *msg, *color;
688 int len;
689 msg = luaL_checklstring(L, 1, &len);
690 if (lua_isnil(L, 2))
691 color = NULL;
692 else
693 color = luaL_checklstring(L, 2, &len);
694 AppendWinMsgRend(msg, color);
695 return 0;
698 static const luaL_reg screen_methods[] = {
699 {"windows", screen_get_windows},
700 {"displays", screen_get_displays},
701 {"display", screen_get_display},
702 {"command", screen_exec_command},
703 {"append_msg", screen_append_msg},
704 {"hook", LuaRegEvent},
705 {0, 0}
708 static const luaL_reg screen_metamethods[] = {
709 {0, 0}
712 static const struct Xet_reg screen_setters[] = {
713 {0, 0}
716 static const struct Xet_reg screen_getters[] = {
717 {0, 0}
720 /** }}} */
722 /** Public functions {{{ */
723 static lua_State *L;
724 int LuaInit(void)
726 L = luaL_newstate();
728 luaL_openlibs(L);
730 #define REGISTER(X) struct_register(L, #X , X ## _methods, X##_metamethods, X##_setters, X##_getters)
732 REGISTER(screen);
733 REGISTER(window);
734 REGISTER(display);
735 REGISTER(user);
736 REGISTER(canvas);
737 REGISTER(callback);
739 return 0;
742 /* An error message on top of the stack. */
743 static void
744 LuaShowErr(lua_State *L)
746 struct display *d = display;
747 unsigned int len;
748 const char *message = luaL_checklstring(L, -1, &len);
749 LMsg(0, "%s", message ? message : "Unknown error");
750 lua_pop(L, 1);
751 display = d;
754 struct fn_def
756 void (*push_fn)(lua_State *, void*);
757 void *value;
760 static int
761 LuaCallProcess(const char *name, struct fn_def defs[])
763 int argc = 0;
765 lua_getfield(L, LUA_GLOBALSINDEX, name);
766 if (lua_isnil(L, -1))
767 return 0;
768 for (argc = 0; defs[argc].push_fn; argc++)
769 defs[argc].push_fn(L, defs[argc].value);
770 if (lua_pcall(L, argc, 0, 0) == LUA_ERRRUN && lua_isstring(L, -1))
772 LuaShowErr(L);
773 return 0;
775 return 1;
778 int LuaSource(const char *file, int async)
780 if (!L)
781 return 0;
782 struct stat st;
783 if (stat(file, &st) == -1)
784 Msg(errno, "Error loading lua script file '%s'", file);
785 else
787 int len = strlen(file);
788 if (len < 4 || strncmp(file + len - 4, ".lua", 4) != 0)
789 return 0;
790 if (luaL_dofile(L, file) && lua_isstring(L, -1))
792 LuaShowErr(L);
794 return 1;
796 return 0;
799 int LuaFinit(void)
801 if (!L)
802 return 0;
803 lua_close(L);
804 L = (lua_State*)0;
805 return 0;
809 LuaProcessCaption(const char *caption, struct win *win, int len)
811 if (!L)
812 return 0;
813 struct fn_def params[] = {
814 {lua_pushstring, caption},
815 {push_window, &win},
816 {lua_pushinteger, len},
817 {NULL, NULL}
819 return LuaCallProcess("process_caption", params);
822 static void
823 push_stringarray(lua_State *L, char **args)
825 int i;
826 lua_newtable(L);
827 for (i = 1; args && *args; i++) {
828 lua_pushinteger(L, i);
829 lua_pushstring(L, *args++);
830 lua_settable(L, -3);
835 LuaPushParams(lua_State *L, const char *params, va_list va)
837 int num = 0;
838 while (*params)
840 switch (*params)
842 case 's':
843 lua_pushstring(L, va_arg(va, char *));
844 break;
845 case 'S':
846 push_stringarray(L, va_arg(va, char **));
847 break;
848 case 'i':
849 lua_pushinteger(L, va_arg(va, int));
850 break;
851 case 'd':
853 struct display *d = va_arg(va, struct display *);
854 push_display(L, &d);
855 break;
858 params++;
859 num++;
861 return num;
864 int LuaCall(char *func, char **argv)
866 int argc;
867 if (!L)
868 return 0;
870 StackDump(L, "Before LuaCall\n");
871 lua_getfield(L, LUA_GLOBALSINDEX, func);
872 if (lua_isnil(L, -1))
874 lua_pushstring(L, "Could not find the script function\n");
875 LuaShowErr(L);
876 return 0;
878 for (argc = 0; *argv; argv++, argc++)
880 lua_pushstring(L, *argv);
882 if (lua_pcall(L, argc, 0, 0) == LUA_ERRRUN)
884 if(lua_isstring(L, -1))
886 StackDump(L, "After LuaCall\n");
887 LuaShowErr(L);
888 return 0;
891 return 1;
894 static int
895 LuaDispatch(void *handler, const char *params, va_list va)
897 struct lua_handler *lh = handler;
898 int argc, retvalue;
900 if (lh->type == LUA_HANDLER_TYPE_N)
901 lua_getfield(L, LUA_GLOBALSINDEX, lh->u.name);
902 else
903 lua_rawgeti(L, LUA_REGISTRYINDEX, lh->u.reference);
905 if (lua_isnil(L, -1))
906 return 0;
907 argc = LuaPushParams(L, params, va);
909 if (lua_pcall(L, argc, 1, 0) == LUA_ERRRUN && lua_isstring(L, -1))
911 StackDump(L, "After LuaDispatch\n");
912 LuaShowErr(L);
913 return 0;
915 retvalue = lua_tonumber(L, -1);
916 lua_pop(L, 1);
917 return retvalue;
920 int LuaForeWindowChanged(void)
922 struct fn_def params[] = {
923 {push_display, &display},
924 {push_window, display ? &D_fore : &fore},
925 {NULL, NULL}
927 if (!L)
928 return 0;
929 return LuaCallProcess("fore_changed", params);
934 LuaCommandExecuted(const char *command, const char **args, int argc)
936 if (!L)
937 return 0;
938 struct fn_def params[] = {
939 {lua_pushstring, command},
940 {push_stringarray, args},
941 {NULL, NULL}
943 return LuaCallProcess("command_executed", params);
946 #define SEVNAME_MAX 30
947 static int
948 LuaRegEvent(lua_State *L)
950 /* signature: hook(obj, event, handler, priv);
951 * or: hook(event, handler, priv)
952 * returns: A ticket for later unregister. */
953 int idx = 1, argc = lua_gettop(L);
954 int priv = 31; /* Default privilege */
955 struct lua_handler lh;
957 char *obj = NULL;
958 const char *objname = "global";
960 static char evbuf[SEVNAME_MAX];
961 const char *event;
963 struct script_event *sev;
965 StackDump(L, "Before RegEvent\n");
967 /* Identify the object, if specified */
968 if (luaL_getmetafield(L, 1, "_objname"))
970 objname = luaL_checkstring(L, -1);
971 lua_pop(L, 1);
972 if (!strcmp("screen", objname))
973 objname = "global";
974 else
975 obj = *(char **)lua_touserdata(L, 1);
976 idx++;
979 event = luaL_checkstring(L, idx++);
980 snprintf(evbuf, SEVNAME_MAX, "%s_%s", objname, event);
982 if (lua_isfunction(L, idx))
984 lua_pushvalue(L, idx);
985 lh.u.reference = luaL_ref(L, LUA_REGISTRYINDEX);
986 lh.type = LUA_HANDLER_TYPE_F;
987 idx++;
989 else
991 lh.type = LUA_HANDLER_TYPE_N;
992 lh.u.name = SaveStr(luaL_checkstring(L, idx++));
995 StackDump(L, "In RegEvent\n");
997 if (idx <= argc)
998 priv = luaL_checkinteger(L, idx);
1000 sev = object_get_event(obj, evbuf);
1001 if (sev)
1003 struct listener *l;
1004 l = (struct listener *)malloc(sizeof(struct listener));
1005 if (!l)
1006 return luaL_error(L, "Out of memory");
1007 l->handler = &lh;
1008 l->priv = priv;
1009 l->dispatcher = LuaDispatch;
1010 if (register_listener(sev, l))
1012 free(l);
1013 if (lh.type == LUA_HANDLER_TYPE_N)
1014 return luaL_error(L, "Handler %s has already been registered", lh.u.name);
1015 else
1016 return luaL_error(L, "Handler has already been registered");
1018 /* Return the handler for un-register */
1019 l->handler = lua_newuserdata(L, sizeof(struct lua_handler));
1020 memcpy(l->handler, &lh, sizeof(struct lua_handler));
1021 ((struct lua_handler *)l->handler)->listener = l;
1022 push_callback(L, &l->handler);
1024 else
1025 return luaL_error(L, "Invalid event specified: %s for object %s", event, objname);
1027 StackDump(L, "After RegEvent\n");
1028 return 1;
1031 static int
1032 LuaUnRegEvent(lua_State *L)
1034 /* signature: unhook([obj], ticket)
1035 * returns: true of success, false otherwise */
1036 int idx = 1;
1037 struct listener *l;
1039 /* If the param is not as expected */
1040 if (!lua_islightuserdata(L, idx))
1042 /* Then it should be the userdata to be ignore, but if not ... */
1043 if (!lua_isuserdata(L, idx))
1044 luaL_checktype(L, idx, LUA_TLIGHTUSERDATA);
1045 idx++;
1046 luaL_checktype(L, idx, LUA_TLIGHTUSERDATA);
1049 l = (struct listener*)lua_touserdata(L, idx++);
1051 /* Validate the listener structure */
1052 if (!l || !l->handler)
1054 /* invalid */
1055 lua_pushboolean(L,0);
1057 else
1059 struct lua_handler *lh = l->handler;
1060 if (lh->type == LUA_HANDLER_TYPE_N)
1061 Free(lh->u.name);
1062 Free(l->handler);
1063 unregister_listener(l);
1064 lua_pushboolean(L, 1);
1067 return 1;
1070 /** }}} */
1072 struct ScriptFuncs LuaFuncs =
1074 LuaForeWindowChanged,
1075 LuaProcessCaption
1078 struct binding lua_binding =
1080 "lua", /*name*/
1081 0, /*inited*/
1082 0, /*registered*/
1083 LuaInit,
1084 LuaFinit,
1085 LuaCall,
1086 LuaSource,
1087 0, /*b_next*/
1088 &LuaFuncs