Merge branch 'lua-scripting' into screen-scripting-soc
[screen-lua.git] / src / lua.c
blob5f607b65e0c8dd0ce95d0312d3f3034651b9aa34
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 enum
85 LUA_HANDLER_TYPE_N = 1,
86 LUA_HANDLER_TYPE_F
89 struct lua_handler
91 int type;
92 union
94 const char *name;
95 int reference;
96 } u;
99 struct lua_handler *
100 LuaAllocHandler(const char *name, int ref)
102 struct lua_handler *lh;
103 lh = (struct lua_handler*) malloc(sizeof(struct lua_handler));
104 if (!lh)
105 return NULL;
107 if (name)
109 lh->type = LUA_HANDLER_TYPE_N;
110 lh->u.name = name;
112 else
114 lh->type = LUA_HANDLER_TYPE_F;
115 lh->u.reference = ref;
118 return lh;
121 void
122 LuaFreeHandler(struct lua_handler **lh)
124 if ((*lh)->type == LUA_HANDLER_TYPE_N)
125 Free((*lh)->u.name);
126 Free(*lh);
129 /** Template {{{ */
131 #define CHECK_TYPE(name, type) \
132 static type * \
133 check_##name(lua_State *L, int index) \
135 type **var; \
136 luaL_checktype(L, index, LUA_TUSERDATA); \
137 var = (type **) luaL_checkudata(L, index, #name); \
138 if (!var || !*var) \
139 luaL_typerror(L, index, #name); \
140 return *var; \
143 #define PUSH_TYPE(name, type) \
144 static void \
145 push_##name(lua_State *L, type **t) \
147 if (!t || !*t) \
148 lua_pushnil(L); \
149 else \
151 type **r; \
152 r = (type **)lua_newuserdata(L, sizeof(type *)); \
153 *r = *t; \
154 luaL_getmetatable(L, #name); \
155 lua_setmetatable(L,-2); \
159 /* Much of the following template comes from:
160 * http://lua-users.org/wiki/BindingWithMembersAndMethods
163 static int get_int (lua_State *L, void *v)
165 lua_pushinteger (L, *(int*)v);
166 return 1;
169 static int set_int (lua_State *L, void *v)
171 *(int*)v = luaL_checkint(L, 3);
172 return 0;
175 static int get_number (lua_State *L, void *v)
177 lua_pushnumber(L, *(lua_Number*)v);
178 return 1;
181 static int set_number (lua_State *L, void *v)
183 *(lua_Number*)v = luaL_checknumber(L, 3);
184 return 0;
187 static int get_string (lua_State *L, void *v)
189 lua_pushstring(L, (char*)v );
190 return 1;
193 static int set_string (lua_State *L, void *v)
195 *(const char**)v = luaL_checkstring(L, 3);
196 return 0;
199 typedef int (*Xet_func) (lua_State *L, void *v);
201 /* member info for get and set handlers */
202 struct Xet_reg
204 const char *name; /* member name */
205 Xet_func func; /* get or set function for type of member */
206 size_t offset; /* offset of member within the struct */
207 int (*absolute)(lua_State *);
210 static void Xet_add (lua_State *L, const struct Xet_reg *l)
212 if (!l)
213 return;
214 for (; l->name; l++)
216 lua_pushstring(L, l->name);
217 lua_pushlightuserdata(L, (void*)l);
218 lua_settable(L, -3);
222 static int Xet_call (lua_State *L)
224 /* for get: stack has userdata, index, lightuserdata */
225 /* for set: stack has userdata, index, value, lightuserdata */
226 const struct Xet_reg *m = (const struct Xet_reg *)lua_touserdata(L, -1); /* member info */
227 lua_pop(L, 1); /* drop lightuserdata */
228 luaL_checktype(L, 1, LUA_TUSERDATA);
229 if (m->absolute)
230 return m->absolute(L);
231 return m->func(L, *(char**)lua_touserdata(L, 1) + m->offset);
234 static int index_handler (lua_State *L)
236 /* stack has userdata, index */
237 lua_pushvalue(L, 2); /* dup index */
238 lua_rawget(L, lua_upvalueindex(1)); /* lookup member by name */
239 if (!lua_islightuserdata(L, -1))
241 lua_pop(L, 1); /* drop value */
242 lua_pushvalue(L, 2); /* dup index */
243 lua_gettable(L, lua_upvalueindex(2)); /* else try methods */
244 if (lua_isnil(L, -1)) /* invalid member */
245 luaL_error(L, "cannot get member '%s'", lua_tostring(L, 2));
246 return 1;
248 return Xet_call(L); /* call get function */
251 static int newindex_handler (lua_State *L)
253 /* stack has userdata, index, value */
254 lua_pushvalue(L, 2); /* dup index */
255 lua_rawget(L, lua_upvalueindex(1)); /* lookup member by name */
256 if (!lua_islightuserdata(L, -1)) /* invalid member */
257 luaL_error(L, "cannot set member '%s'", lua_tostring(L, 2));
258 return Xet_call(L); /* call set function */
261 static int
262 struct_register(lua_State *L, const char *name, const luaL_reg fn_methods[], const luaL_reg meta_methods[],
263 const struct Xet_reg setters[], const struct Xet_reg getters[])
265 int metatable, methods;
267 /* create methods table & add it to the table of globals */
268 luaL_register(L, name, fn_methods);
269 methods = lua_gettop(L);
271 /* create metatable & add it to the registry */
272 luaL_newmetatable(L, name);
273 luaL_register(L, 0, meta_methods); /* fill metatable */
275 /* To identify the type of object */
276 lua_pushstring(L, "_objname");
277 lua_pushstring(L, name);
278 lua_rawset(L, -3);
280 metatable = lua_gettop(L);
282 lua_pushliteral(L, "__metatable");
283 lua_pushvalue(L, methods); /* dup methods table*/
284 lua_rawset(L, metatable); /* hide metatable:
285 metatable.__metatable = methods */
287 lua_pushliteral(L, "__index");
288 lua_pushvalue(L, metatable); /* upvalue index 1 */
289 Xet_add(L, getters); /* fill metatable with getters */
290 lua_pushvalue(L, methods); /* upvalue index 2 */
291 lua_pushcclosure(L, index_handler, 2);
292 lua_rawset(L, metatable); /* metatable.__index = index_handler */
294 lua_pushliteral(L, "__newindex");
295 lua_newtable(L); /* table for members you can set */
296 Xet_add(L, setters); /* fill with setters */
297 lua_pushcclosure(L, newindex_handler, 1);
298 lua_rawset(L, metatable); /* metatable.__newindex = newindex_handler */
300 lua_pop(L, 1); /* drop metatable */
301 return 1; /* return methods on the stack */
304 /** }}} */
306 /** Window {{{ */
308 PUSH_TYPE(window, struct win)
310 CHECK_TYPE(window, struct win)
312 static int get_window(lua_State *L, void *v)
314 push_window(L, (struct win **)v);
315 return 1;
318 static int
319 window_change_title(lua_State *L)
321 struct win *w = check_window(L, 1);
322 unsigned int len;
323 const char *title = luaL_checklstring(L, 2, &len);
324 ChangeAKA(w, (char *)title, len);
325 return 0;
328 static int
329 window_get_monitor_status(lua_State *L)
331 struct win *w = check_window(L, 1);
332 int activity = luaL_checkint(L, 2);
333 if (activity)
334 /*monitor*/
335 lua_pushinteger(L, w->w_monitor != MON_OFF);
336 else
337 /*silence*/
338 lua_pushinteger(L, w->w_silence == SILENCE_ON ? w->w_silencewait: 0);
340 return 1;
343 static const luaL_reg window_methods[] = {
344 {"get_monitor_status", window_get_monitor_status},
345 {"hook", LuaRegEvent},
346 {0, 0}
349 static int
350 window_tostring(lua_State *L)
352 char str[128];
353 struct win *w = check_window(L, 1);
354 snprintf(str, sizeof(str), "{window #%d: '%s'}", w->w_number, w->w_title);
355 lua_pushstring(L, str);
356 return 1;
359 static int
360 window_equality(lua_State *L)
362 struct win *w1 = check_window(L, 1), *w2 = check_window(L, 2);
363 lua_pushboolean(L, (w1 == w2 || (w1 && w2 && w1->w_number == w2->w_number)));
364 return 1;
367 static const luaL_reg window_metamethods[] = {
368 {"__tostring", window_tostring},
369 {"__eq", window_equality},
370 {0, 0}
373 static const struct Xet_reg window_setters[] = {
374 {"title", 0, 0, window_change_title/*absolute setter*/},
375 {0, 0}
378 static const struct Xet_reg window_getters[] = {
379 {"title", get_string, offsetof(struct win, w_title) + 8},
380 {"number", get_int, offsetof(struct win, w_number)},
381 {"dir", get_string, offsetof(struct win, w_dir)},
382 {"tty", get_string, offsetof(struct win, w_tty)},
383 {"pid", get_int, offsetof(struct win, w_pid)},
384 {"group", get_window, offsetof(struct win, w_group)},
385 {"bell", get_int, offsetof(struct win, w_bell)},
386 {0, 0}
390 /** }}} */
392 /** AclUser {{{ */
394 PUSH_TYPE(user, struct acluser)
396 CHECK_TYPE(user, struct acluser)
398 static int
399 get_user(lua_State *L, void *v)
401 push_user(L, (struct acluser **)v);
402 return 1;
405 static const luaL_reg user_methods[] = {
406 {0, 0}
409 static int
410 user_tostring(lua_State *L)
412 char str[128];
413 struct acluser *u = check_user(L, 1);
414 snprintf(str, sizeof(str), "{user '%s'}", u->u_name);
415 lua_pushstring(L, str);
416 return 1;
419 static const luaL_reg user_metamethods[] = {
420 {"__tostring", user_tostring},
421 {0, 0}
424 static const struct Xet_reg user_setters[] = {
425 {0, 0}
428 static const struct Xet_reg user_getters[] = {
429 {"name", get_string, offsetof(struct acluser, u_name)},
430 {"password", get_string, offsetof(struct acluser, u_password)},
431 {0, 0}
434 /** }}} */
436 /** Canvas {{{ */
438 PUSH_TYPE(canvas, struct canvas)
440 CHECK_TYPE(canvas, struct canvas)
442 static int
443 get_canvas(lua_State *L, void *v)
445 push_canvas(L, (struct canvas **)v);
446 return 1;
449 static int
450 canvas_select(lua_State *L)
452 struct canvas *c = check_canvas(L, 1);
453 if (!display || D_forecv == c)
454 return 0;
455 SetCanvasWindow(c, Layer2Window(c->c_layer));
456 D_forecv = c;
458 /* XXX: the following all is duplicated from process.c:DoAction.
459 * Should these be in some better place?
461 ResizeCanvas(&D_canvas);
462 RecreateCanvasChain();
463 RethinkDisplayViewports();
464 ResizeLayersToCanvases(); /* redisplays */
465 fore = D_fore = Layer2Window(D_forecv->c_layer);
466 flayer = D_forecv->c_layer;
467 #ifdef RXVT_OSC
468 if (D_xtermosc[2] || D_xtermosc[3])
470 Activate(-1);
471 break;
473 #endif
474 RefreshHStatus();
475 #ifdef RXVT_OSC
476 RefreshXtermOSC();
477 #endif
478 flayer = D_forecv->c_layer;
479 CV_CALL(D_forecv, LayRestore();LaySetCursor());
480 WindowChanged(0, 'F');
481 return 1;
484 static const luaL_reg canvas_methods[] = {
485 {"select", canvas_select},
486 {0, 0}
489 static const luaL_reg canvas_metamethods[] = {
490 {0, 0}
493 static const struct Xet_reg canvas_setters[] = {
494 {0, 0}
497 static int
498 canvas_get_window(lua_State *L)
500 struct canvas *c = check_canvas(L, 1);
501 struct win *win = Layer2Window(c->c_layer);
502 if (win)
503 push_window(L, &win);
504 else
505 lua_pushnil(L);
506 return 1;
509 static const struct Xet_reg canvas_getters[] = {
510 {"next", get_canvas, offsetof(struct canvas, c_next)},
511 {"xoff", get_int, offsetof(struct canvas, c_xoff)},
512 {"yoff", get_int, offsetof(struct canvas, c_yoff)},
513 {"xs", get_int, offsetof(struct canvas, c_xs)},
514 {"ys", get_int, offsetof(struct canvas, c_ys)},
515 {"xe", get_int, offsetof(struct canvas, c_xe)},
516 {"ye", get_int, offsetof(struct canvas, c_ye)},
517 {"window", 0, 0, canvas_get_window},
518 {0, 0}
521 /** }}} */
523 /** Layout {{{ */
525 PUSH_TYPE(layout, struct layout)
526 CHECK_TYPE(layout, struct layout)
528 static const struct Xet_reg layout_getters[] = {
529 {0,0}
532 static int
533 get_layout(lua_State *L, void *v)
535 push_layout(L, (struct layout **)v);
536 return 1;
539 /** }}} */
541 /** Display {{{ */
543 PUSH_TYPE(display, struct display)
545 CHECK_TYPE(display, struct display)
547 static int
548 display_get_canvases(lua_State *L)
550 struct display *d;
551 struct canvas *iter;
552 int count;
554 d = check_display(L, 1);
555 lua_newtable(L);
556 for (iter = d->d_cvlist, count = 0; iter; iter = iter->c_next, count++) {
557 lua_pushinteger(L, count);
558 push_canvas(L, &iter);
559 lua_settable(L, -3);
562 return 1;
565 static const luaL_reg display_methods[] = {
566 {"get_canvases", display_get_canvases},
567 {0, 0}
570 static int
571 display_tostring(lua_State *L)
573 char str[128];
574 struct display *d = check_display(L, 1);
575 snprintf(str, sizeof(str), "{display: tty = '%s', term = '%s'}", d->d_usertty, d->d_termname);
576 lua_pushstring(L, str);
577 return 1;
580 static const luaL_reg display_metamethods[] = {
581 {"__tostring", display_tostring},
582 {0, 0}
585 static const struct Xet_reg display_setters[] = {
586 {0, 0}
589 static const struct Xet_reg display_getters[] = {
590 {"tty", get_string, offsetof(struct display, d_usertty)},
591 {"term", get_string, offsetof(struct display, d_termname)},
592 {"fore", get_window, offsetof(struct display, d_fore)},
593 {"other", get_window, offsetof(struct display, d_other)},
594 {"width", get_int, offsetof(struct display, d_width)},
595 {"height", get_int, offsetof(struct display, d_height)},
596 {"user", get_user, offsetof(struct display, d_user)},
597 {"layout", get_layout, offsetof(struct display, d_layout)},
598 {0, 0}
601 /** }}} */
603 /** Screen {{{ */
605 static int
606 screen_get_windows(lua_State *L)
608 struct win *iter;
609 int count;
611 lua_newtable(L);
612 for (iter = windows, count = 0; iter; iter = iter->w_next, count++) {
613 lua_pushinteger(L, iter->w_number);
614 push_window(L, &iter);
615 lua_settable(L, -3);
618 return 1;
621 static int
622 screen_get_displays(lua_State *L)
624 struct display *iter;
625 int count;
627 lua_newtable(L);
628 for (iter = displays, count = 0; iter; iter = iter->d_next, count++) {
629 lua_pushinteger(L, count);
630 push_display(L, &iter);
631 lua_settable(L, -3);
634 return 1;
637 static int
638 screen_get_display(lua_State *L)
640 push_display(L, &display);
641 return 1;
644 static int
645 screen_exec_command(lua_State *L)
647 const char *command;
648 unsigned int len;
650 command = luaL_checklstring(L, 1, &len);
651 if (command)
652 RcLine((char *)command, len);
654 return 0;
657 static int
658 screen_append_msg(lua_State *L)
660 const char *msg, *color;
661 int len;
662 msg = luaL_checklstring(L, 1, &len);
663 if (lua_isnil(L, 2))
664 color = NULL;
665 else
666 color = luaL_checklstring(L, 2, &len);
667 AppendWinMsgRend(msg, color);
668 return 0;
671 void
672 script_input_fn(char *buf, int len, char *priv)
674 lua_State *L = (lua_State *)priv;
675 lua_pushstring(L, buf);
676 if (lua_pcall(L, 1, 0, 0) == LUA_ERRRUN)
678 if(lua_isstring(L, -1))
680 LuaShowErr(L);
685 static int
686 screen_input(lua_State *L)
688 char * prompt = NULL;
690 prompt = (char *)luaL_checkstring(L, 1);
691 Input(prompt, 100, INP_COOKED, script_input_fn, (char *)L, 0);
693 return 0;
696 static const luaL_reg screen_methods[] = {
697 {"windows", screen_get_windows},
698 {"displays", screen_get_displays},
699 {"display", screen_get_display},
700 {"command", screen_exec_command},
701 {"append_msg", screen_append_msg},
702 {"hook", LuaRegEvent},
703 {"unhook", LuaUnRegEvent},
704 {"input", screen_input},
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);
738 /* To store handler funcs */
739 luaL_getmetatable(L, "screen");
740 lua_pushstring(L, "_handlers");
741 lua_newtable(L);
742 lua_rawset(L, -3);
743 lua_pop(L, 1);
745 return 0;
748 /* An error message on top of the stack. */
749 static void
750 LuaShowErr(lua_State *L)
752 struct display *d = display;
753 unsigned int len;
754 const char *message = luaL_checklstring(L, -1, &len);
755 LMsg(0, "%s", message ? message : "Unknown error");
756 lua_pop(L, 1);
757 display = d;
760 struct fn_def
762 void (*push_fn)(lua_State *, void*);
763 void *value;
766 static int
767 LuaCallProcess(const char *name, struct fn_def defs[])
769 int argc = 0;
771 lua_getfield(L, LUA_GLOBALSINDEX, name);
772 if (lua_isnil(L, -1))
773 return 0;
774 for (argc = 0; defs[argc].push_fn; argc++)
775 defs[argc].push_fn(L, defs[argc].value);
776 if (lua_pcall(L, argc, 0, 0) == LUA_ERRRUN && lua_isstring(L, -1))
778 LuaShowErr(L);
779 return 0;
781 return 1;
784 int LuaSource(const char *file, int async)
786 if (!L)
787 return 0;
788 struct stat st;
789 if (stat(file, &st) == -1)
790 Msg(errno, "Error loading lua script file '%s'", file);
791 else
793 int len = strlen(file);
794 if (len < 4 || strncmp(file + len - 4, ".lua", 4) != 0)
795 return 0;
796 if (luaL_dofile(L, file) && lua_isstring(L, -1))
798 LuaShowErr(L);
800 return 1;
802 return 0;
805 int LuaFinit(void)
807 if (!L)
808 return 0;
809 lua_close(L);
810 L = (lua_State*)0;
811 return 0;
815 LuaProcessCaption(const char *caption, struct win *win, int len)
817 if (!L)
818 return 0;
819 struct fn_def params[] = {
820 {lua_pushstring, caption},
821 {push_window, &win},
822 {lua_pushinteger, len},
823 {NULL, NULL}
825 return LuaCallProcess("process_caption", params);
828 static void
829 push_stringarray(lua_State *L, char **args)
831 int i;
832 lua_newtable(L);
833 for (i = 1; args && *args; i++) {
834 lua_pushinteger(L, i);
835 lua_pushstring(L, *args++);
836 lua_settable(L, -3);
841 LuaPushParams(lua_State *L, const char *params, va_list va)
843 int num = 0;
844 while (*params)
846 switch (*params)
848 case 's':
849 lua_pushstring(L, va_arg(va, char *));
850 break;
851 case 'S':
852 push_stringarray(L, va_arg(va, char **));
853 break;
854 case 'i':
855 lua_pushinteger(L, va_arg(va, int));
857 params++;
858 num++;
860 return num;
863 int LuaCall(char *func, char **argv)
865 int argc;
866 if (!L)
867 return 0;
869 StackDump(L, "Before LuaCall\n");
870 lua_getfield(L, LUA_GLOBALSINDEX, func);
871 if (lua_isnil(L, -1))
873 lua_pushstring(L, "Could not find the script function\n");
874 LuaShowErr(L);
875 return 0;
877 for (argc = 0; *argv; argv++, argc++)
879 lua_pushstring(L, *argv);
881 if (lua_pcall(L, argc, 0, 0) == LUA_ERRRUN)
883 if(lua_isstring(L, -1))
885 StackDump(L, "After LuaCall\n");
886 LuaShowErr(L);
887 return 0;
890 return 1;
893 static int
894 LuaDispatch(void *handler, const char *params, va_list va)
896 struct lua_handler *lh = handler;
897 int argc, retvalue;
899 if (lh->type == LUA_HANDLER_TYPE_N)
900 lua_getfield(L, LUA_GLOBALSINDEX, lh->u.name);
901 else
902 lua_rawgeti(L, LUA_REGISTRYINDEX, lh->u.reference);
904 if (lua_isnil(L, -1))
905 return 0;
906 argc = LuaPushParams(L, params, va);
908 if (lua_pcall(L, argc, 1, 0) == LUA_ERRRUN && lua_isstring(L, -1))
910 StackDump(L, "After LuaDispatch\n");
911 LuaShowErr(L);
912 return 0;
914 retvalue = lua_tonumber(L, -1);
915 lua_pop(L, 1);
916 return retvalue;
919 int LuaForeWindowChanged(void)
921 struct fn_def params[] = {
922 {push_display, &display},
923 {push_window, display ? &D_fore : &fore},
924 {NULL, NULL}
926 if (!L)
927 return 0;
928 return LuaCallProcess("fore_changed", params);
931 struct lua_handler *
932 LuaCheckHandler(lua_State *L, int idx, int reg)
934 if (lua_isstring(L, idx))
936 const char * handler;
937 /* registered with func name.*/
938 handler = luaL_checkstring(L, idx);
939 lua_getfield(L, LUA_GLOBALSINDEX, handler);
940 if (!lua_isfunction(L, -1))
941 luaL_error(L, "The specified handler %s in param #%d is not a function", handler, idx);
942 lua_pop(L, 1);
943 return LuaAllocHandler(handler, 0);
945 else if (lua_isfunction(L, idx))
947 char buf[20];
948 int key, htable;
949 if (idx < 0)
950 idx = lua_gettop(L) + 1 - idx;
952 luaL_getmetatable(L, "screen");
953 lua_pushstring(L, "_handlers");
954 lua_rawget(L, -2);
955 if (lua_isnil(L, -1))
956 luaL_error(L, "Fatal! Should not happen! Fail to get global handler table!");
957 /* Map func to unique key and do reference count */
958 htable = lua_gettop(L);
959 lua_pushvalue(L, idx);
960 lua_gettable(L, htable);/*htable[func] ==?*/
961 if (lua_isnil(L, -1))
963 /* not found */
964 if (!reg)
965 return NULL;
966 lua_pushinteger(L, 1);
967 key = luaL_ref(L, htable); /*htable[key] = 1*/
968 lua_pushvalue(L, idx);
969 lua_pushinteger(L, key);
970 lua_settable(L, htable); /*htable[func]=key*/
972 else
974 int cnt;
975 key = lua_tointeger(L, -1);/*key = htable[func]*/
976 lua_gettable(L, htable);
977 cnt = lua_tointeger(L, -1);/*cnt = htable[key]*/
978 if (!reg && cnt <= 1)
980 /*release the last reference*/
981 luaL_unref(L, htable, key);
982 lua_pushvalue(L, idx);
983 lua_pushnil(L);
984 lua_settable(L, htable); /*htable[func]=key*/
986 else
988 lua_pushinteger(L, key);
989 lua_pushinteger(L, reg? cnt + 1 : cnt - 1);
990 lua_settable(L, htable); /*htable[key] = cnt + 1*/
994 lua_pop(L, 3);
995 return LuaAllocHandler(NULL, key);
997 else
998 luaL_error(L, "Handler should be a function or the name of function");
999 return NULL;
1002 #define SEVNAME_MAX 30
1003 static int
1004 LuaRegEvent(lua_State *L)
1006 /* signature: hook(obj, event, handler, priv);
1007 * or: hook(event, handler, priv)
1008 * returns: A ticket for later unregister. */
1009 int idx = 1, argc = lua_gettop(L);
1010 unsigned int priv = 31; /* Default privilege */
1011 struct lua_handler *lh;
1013 char *obj = NULL;
1014 const char *objname = "global";
1016 static char evbuf[SEVNAME_MAX];
1017 const char *event;
1019 struct script_event *sev;
1021 StackDump(L, "Before RegEvent\n");
1023 /* Identify the object, if specified */
1024 if (luaL_getmetafield(L, 1, "_objname"))
1026 objname = luaL_checkstring(L, -1);
1027 lua_pop(L, 1);
1028 if (!strcmp("screen", objname))
1029 objname = "global";
1030 else
1031 obj = *(char **)lua_touserdata(L, 1);
1032 idx++;
1035 event = luaL_checkstring(L, idx++);
1036 snprintf(evbuf, SEVNAME_MAX, "%s_%s", objname, event);
1038 /* Check and get the handler */
1039 lh = LuaCheckHandler(L, idx++, 1);
1040 if (!lh)
1041 luaL_error(L, "Out of memory");
1043 StackDump(L, "In RegEvent\n");
1045 if (idx <= argc)
1046 priv = luaL_checkinteger(L, idx);
1048 sev = object_get_event(obj, evbuf);
1049 if (sev)
1051 struct listener *l;
1052 l = (struct listener *)malloc(sizeof(struct listener));
1053 if (!l)
1054 return luaL_error(L, "Out of memory");
1055 l->priv = priv;
1056 l->dispatcher = LuaDispatch;
1057 if (register_listener(sev, l))
1059 free(l);
1060 if (lh->type == LUA_HANDLER_TYPE_N)
1061 return luaL_error(L, "Handler %s has already been registered", lh->u.name);
1062 else
1063 return luaL_error(L, "Handler has already been registered");
1065 /* Return the handler for un-register */
1066 l->handler = lh;
1067 lua_pushlightuserdata(L, l);
1069 else
1070 return luaL_error(L, "Invalid event specified: %s for object %s", event, objname);
1072 StackDump(L, "After RegEvent\n");
1073 return 1;
1076 static int
1077 LuaUnRegEvent(lua_State *L)
1079 /* signature: unhook([obj], ticket)
1080 * returns: true of success, false otherwise */
1081 int idx = 1;
1082 struct listener *l;
1084 /* If the param is not as expected */
1085 if (!lua_islightuserdata(L, idx))
1087 /* Then it should be the userdata to be ignore, but if not ... */
1088 if (!lua_isuserdata(L, idx))
1089 luaL_checktype(L, idx, LUA_TLIGHTUSERDATA);
1090 idx++;
1091 luaL_checktype(L, idx, LUA_TLIGHTUSERDATA);
1094 l = (struct listener*)lua_touserdata(L, idx++);
1096 /* Validate the listener structure */
1097 if (!l || !l->handler)
1099 /* invalid */
1100 lua_pushboolean(L,0);
1102 else
1104 LuaFreeHandler(&l->handler);
1105 unregister_listener(l);
1106 lua_pushboolean(L, 1);
1109 return 1;
1112 /** }}} */
1114 struct ScriptFuncs LuaFuncs =
1116 LuaForeWindowChanged,
1117 LuaProcessCaption
1120 struct binding lua_binding =
1122 "lua", /*name*/
1123 0, /*inited*/
1124 0, /*registered*/
1125 LuaInit,
1126 LuaFinit,
1127 LuaCall,
1128 LuaSource,
1129 0, /*b_next*/
1130 &LuaFuncs