544cd3ed33ed1dc5ac1fee76167bf32ba771480d
[screen-lua.git] / src / lua.c
blob544cd3ed33ed1dc5ac1fee76167bf32ba771480d
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 /* FIXME: Why do we leave an element on the stack? */
301 lua_pop(L, 1); /* drop metatable */
302 return 1; /* return methods on the stack */
305 /** }}} */
307 /** Window {{{ */
309 PUSH_TYPE(window, struct win)
311 CHECK_TYPE(window, struct win)
313 static int get_window(lua_State *L, void *v)
315 push_window(L, (struct win **)v);
316 return 1;
319 static int
320 window_change_title(lua_State *L)
322 struct win *w = check_window(L, 1);
323 unsigned int len;
324 const char *title = luaL_checklstring(L, 2, &len);
325 ChangeAKA(w, (char *)title, len);
326 return 0;
329 static int
330 window_get_monitor_status(lua_State *L)
332 struct win *w = check_window(L, 1);
333 int activity = luaL_checkint(L, 2);
334 if (activity)
335 /*monitor*/
336 lua_pushinteger(L, w->w_monitor != MON_OFF);
337 else
338 /*silence*/
339 lua_pushinteger(L, w->w_silence == SILENCE_ON ? w->w_silencewait: 0);
341 return 1;
344 static const luaL_reg window_methods[] = {
345 {"get_monitor_status", window_get_monitor_status},
346 {"hook", LuaRegEvent},
347 {0, 0}
350 static int
351 window_tostring(lua_State *L)
353 char str[128];
354 struct win *w = check_window(L, 1);
355 snprintf(str, sizeof(str), "{window #%d: '%s'}", w->w_number, w->w_title);
356 lua_pushstring(L, str);
357 return 1;
360 static int
361 window_equality(lua_State *L)
363 struct win *w1 = check_window(L, 1), *w2 = check_window(L, 2);
364 lua_pushboolean(L, (w1 == w2 || (w1 && w2 && w1->w_number == w2->w_number)));
365 return 1;
368 static const luaL_reg window_metamethods[] = {
369 {"__tostring", window_tostring},
370 {"__eq", window_equality},
371 {0, 0}
374 static const struct Xet_reg window_setters[] = {
375 {"title", 0, 0, window_change_title/*absolute setter*/},
376 {0, 0}
379 static const struct Xet_reg window_getters[] = {
380 {"title", get_string, offsetof(struct win, w_title) + 8},
381 {"number", get_int, offsetof(struct win, w_number)},
382 {"dir", get_string, offsetof(struct win, w_dir)},
383 {"tty", get_string, offsetof(struct win, w_tty)},
384 {"pid", get_int, offsetof(struct win, w_pid)},
385 {"group", get_window, offsetof(struct win, w_group)},
386 {"bell", get_int, offsetof(struct win, w_bell)},
387 {0, 0}
391 /** }}} */
393 /** AclUser {{{ */
395 PUSH_TYPE(user, struct acluser)
397 CHECK_TYPE(user, struct acluser)
399 static int
400 get_user(lua_State *L, void *v)
402 push_user(L, (struct acluser **)v);
403 return 1;
406 static const luaL_reg user_methods[] = {
407 {0, 0}
410 static int
411 user_tostring(lua_State *L)
413 char str[128];
414 struct acluser *u = check_user(L, 1);
415 snprintf(str, sizeof(str), "{user '%s'}", u->u_name);
416 lua_pushstring(L, str);
417 return 1;
420 static const luaL_reg user_metamethods[] = {
421 {"__tostring", user_tostring},
422 {0, 0}
425 static const struct Xet_reg user_setters[] = {
426 {0, 0}
429 static const struct Xet_reg user_getters[] = {
430 {"name", get_string, offsetof(struct acluser, u_name)},
431 {"password", get_string, offsetof(struct acluser, u_password)},
432 {0, 0}
435 /** }}} */
437 /** Canvas {{{ */
439 PUSH_TYPE(canvas, struct canvas)
441 CHECK_TYPE(canvas, struct canvas)
443 static int
444 get_canvas(lua_State *L, void *v)
446 push_canvas(L, (struct canvas **)v);
447 return 1;
450 static int
451 canvas_select(lua_State *L)
453 struct canvas *c = check_canvas(L, 1);
454 if (!display || D_forecv == c)
455 return 0;
456 SetCanvasWindow(c, Layer2Window(c->c_layer));
457 D_forecv = c;
459 /* XXX: the following all is duplicated from process.c:DoAction.
460 * Should these be in some better place?
462 ResizeCanvas(&D_canvas);
463 RecreateCanvasChain();
464 RethinkDisplayViewports();
465 ResizeLayersToCanvases(); /* redisplays */
466 fore = D_fore = Layer2Window(D_forecv->c_layer);
467 flayer = D_forecv->c_layer;
468 #ifdef RXVT_OSC
469 if (D_xtermosc[2] || D_xtermosc[3])
471 Activate(-1);
472 break;
474 #endif
475 RefreshHStatus();
476 #ifdef RXVT_OSC
477 RefreshXtermOSC();
478 #endif
479 flayer = D_forecv->c_layer;
480 CV_CALL(D_forecv, LayRestore();LaySetCursor());
481 WindowChanged(0, 'F');
482 return 1;
485 static const luaL_reg canvas_methods[] = {
486 {"select", canvas_select},
487 {0, 0}
490 static const luaL_reg canvas_metamethods[] = {
491 {0, 0}
494 static const struct Xet_reg canvas_setters[] = {
495 {0, 0}
498 static int
499 canvas_get_window(lua_State *L)
501 struct canvas *c = check_canvas(L, 1);
502 struct win *win = Layer2Window(c->c_layer);
503 if (win)
504 push_window(L, &win);
505 else
506 lua_pushnil(L);
507 return 1;
510 static const struct Xet_reg canvas_getters[] = {
511 {"next", get_canvas, offsetof(struct canvas, c_next)},
512 {"xoff", get_int, offsetof(struct canvas, c_xoff)},
513 {"yoff", get_int, offsetof(struct canvas, c_yoff)},
514 {"xs", get_int, offsetof(struct canvas, c_xs)},
515 {"ys", get_int, offsetof(struct canvas, c_ys)},
516 {"xe", get_int, offsetof(struct canvas, c_xe)},
517 {"ye", get_int, offsetof(struct canvas, c_ye)},
518 {"window", 0, 0, canvas_get_window},
519 {0, 0}
522 /** }}} */
524 /** Layout {{{ */
526 PUSH_TYPE(layout, struct layout)
527 CHECK_TYPE(layout, struct layout)
529 static const struct Xet_reg layout_getters[] = {
530 {0,0}
533 static int
534 get_layout(lua_State *L, void *v)
536 push_layout(L, (struct layout **)v);
537 return 1;
540 /** }}} */
542 /** Display {{{ */
544 PUSH_TYPE(display, struct display)
546 CHECK_TYPE(display, struct display)
548 static int
549 display_get_canvases(lua_State *L)
551 struct display *d;
552 struct canvas *iter;
553 int count;
555 d = check_display(L, 1);
556 lua_newtable(L);
557 for (iter = d->d_cvlist, count = 0; iter; iter = iter->c_next, count++) {
558 lua_pushinteger(L, count);
559 push_canvas(L, &iter);
560 lua_settable(L, -3);
563 return 1;
566 static const luaL_reg display_methods[] = {
567 {"get_canvases", display_get_canvases},
568 {0, 0}
571 static int
572 display_tostring(lua_State *L)
574 char str[128];
575 struct display *d = check_display(L, 1);
576 snprintf(str, sizeof(str), "{display: tty = '%s', term = '%s'}", d->d_usertty, d->d_termname);
577 lua_pushstring(L, str);
578 return 1;
581 static const luaL_reg display_metamethods[] = {
582 {"__tostring", display_tostring},
583 {0, 0}
586 static const struct Xet_reg display_setters[] = {
587 {0, 0}
590 static const struct Xet_reg display_getters[] = {
591 {"tty", get_string, offsetof(struct display, d_usertty)},
592 {"term", get_string, offsetof(struct display, d_termname)},
593 {"fore", get_window, offsetof(struct display, d_fore)},
594 {"other", get_window, offsetof(struct display, d_other)},
595 {"width", get_int, offsetof(struct display, d_width)},
596 {"height", get_int, offsetof(struct display, d_height)},
597 {"user", get_user, offsetof(struct display, d_user)},
598 {"layout", get_layout, offsetof(struct display, d_layout)},
599 {0, 0}
602 /** }}} */
604 /** Screen {{{ */
606 static int
607 screen_get_windows(lua_State *L)
609 struct win *iter;
610 int count;
612 lua_newtable(L);
613 for (iter = windows, count = 0; iter; iter = iter->w_next, count++) {
614 lua_pushinteger(L, iter->w_number);
615 push_window(L, &iter);
616 lua_settable(L, -3);
619 return 1;
622 static int
623 screen_get_displays(lua_State *L)
625 struct display *iter;
626 int count;
628 lua_newtable(L);
629 for (iter = displays, count = 0; iter; iter = iter->d_next, count++) {
630 lua_pushinteger(L, count);
631 push_display(L, &iter);
632 lua_settable(L, -3);
635 return 1;
638 static int
639 screen_get_display(lua_State *L)
641 push_display(L, &display);
642 return 1;
645 static int
646 screen_exec_command(lua_State *L)
648 const char *command;
649 unsigned int len;
651 command = luaL_checklstring(L, 1, &len);
652 if (command)
653 RcLine((char *)command, len);
655 return 0;
658 static int
659 screen_append_msg(lua_State *L)
661 const char *msg, *color;
662 unsigned int len;
663 msg = luaL_checklstring(L, 1, &len);
664 if (lua_isnil(L, 2))
665 color = NULL;
666 else
667 color = luaL_checklstring(L, 2, &len);
668 AppendWinMsgRend(msg, color);
669 return 0;
672 void
673 script_input_fn(char *buf, int len, char *priv)
675 lua_State *L = (lua_State *)priv;
676 lua_pushstring(L, buf);
677 if (lua_pcall(L, 1, 0, 0) == LUA_ERRRUN)
679 if(lua_isstring(L, -1))
681 LuaShowErr(L);
686 static int
687 screen_input(lua_State *L)
689 char * prompt = NULL;
691 prompt = (char *)luaL_checkstring(L, 1);
692 Input(prompt, 100, INP_COOKED, script_input_fn, (char *)L, 0);
694 return 0;
697 static const luaL_reg screen_methods[] = {
698 {"windows", screen_get_windows},
699 {"displays", screen_get_displays},
700 {"display", screen_get_display},
701 {"command", screen_exec_command},
702 {"append_msg", screen_append_msg},
703 {"hook", LuaRegEvent},
704 {"unhook", LuaUnRegEvent},
705 {"input", screen_input},
706 {0, 0}
709 static const luaL_reg screen_metamethods[] = {
710 {0, 0}
713 static const struct Xet_reg screen_setters[] = {
714 {0, 0}
717 static const struct Xet_reg screen_getters[] = {
718 {0, 0}
721 /** }}} */
723 /** Public functions {{{ */
724 static lua_State *L;
725 int LuaInit(void)
727 L = luaL_newstate();
729 luaL_openlibs(L);
731 #define REGISTER(X) struct_register(L, #X , X ## _methods, X##_metamethods, X##_setters, X##_getters)
733 REGISTER(screen);
734 REGISTER(window);
735 REGISTER(display);
736 REGISTER(user);
737 REGISTER(canvas);
739 /* To store handler funcs */
740 luaL_getmetatable(L, "screen");
741 /* two kinds of info in this table:
742 * _funckey[func]->key
743 * _funckey[key]->refcnt */
744 lua_pushstring(L, "_funckey");
745 lua_newtable(L);
746 lua_rawset(L, -3);
747 /* two kinds of info in this table:
748 * _keyfunc[key]->func
749 * _keyfunc[func]->name */
750 lua_pushstring(L, "_keyfunc");
751 lua_newtable(L);
752 lua_rawset(L, -3);
753 lua_pop(L, 1);
755 return 0;
758 /* An error message on top of the stack. */
759 static void
760 LuaShowErr(lua_State *L)
762 struct display *d = display;
763 unsigned int len;
764 const char *message = luaL_checklstring(L, -1, &len);
765 LMsg(0, "%s", message ? message : "Unknown error");
766 lua_pop(L, 1);
767 display = d;
770 struct fn_def
772 void (*push_fn)(lua_State *, void*);
773 void *value;
776 static int
777 LuaCallProcess(const char *name, struct fn_def defs[])
779 int argc = 0;
781 lua_getfield(L, LUA_GLOBALSINDEX, name);
782 if (lua_isnil(L, -1))
784 lua_pop(L,1);
785 return 0;
787 for (argc = 0; defs[argc].push_fn; argc++)
788 defs[argc].push_fn(L, defs[argc].value);
789 if (lua_pcall(L, argc, 0, 0) == LUA_ERRRUN && lua_isstring(L, -1))
791 LuaShowErr(L);
792 return 0;
794 return 1;
797 int LuaSource(const char *file, int async)
799 if (!L)
800 return 0;
801 struct stat st;
802 if (stat(file, &st) == -1)
803 Msg(errno, "Error loading lua script file '%s'", file);
804 else
806 int len = strlen(file);
807 if (len < 4 || strncmp(file + len - 4, ".lua", 4) != 0)
808 return 0;
809 if (luaL_dofile(L, file) && lua_isstring(L, -1))
811 LuaShowErr(L);
813 return 1;
815 return 0;
818 int LuaFinit(void)
820 if (!L)
821 return 0;
822 lua_close(L);
823 L = (lua_State*)0;
824 return 0;
828 LuaProcessCaption(const char *caption, struct win *win, int len)
830 if (!L)
831 return 0;
832 struct fn_def params[] = {
833 {lua_pushstring, caption},
834 {push_window, &win},
835 {lua_pushinteger, len},
836 {NULL, NULL}
838 return LuaCallProcess("process_caption", params);
841 static void
842 push_stringarray(lua_State *L, char **args)
844 int i;
845 lua_newtable(L);
846 for (i = 1; args && *args; i++) {
847 lua_pushinteger(L, i);
848 lua_pushstring(L, *args++);
849 lua_settable(L, -3);
854 LuaPushParams(lua_State *L, const char *params, va_list va)
856 int num = 0;
857 while (*params)
859 switch (*params)
861 case 's':
862 lua_pushstring(L, va_arg(va, char *));
863 break;
864 case 'S':
865 push_stringarray(L, va_arg(va, char **));
866 break;
867 case 'i':
868 lua_pushinteger(L, va_arg(va, int));
870 params++;
871 num++;
873 return num;
876 int LuaCall(char *func, char **argv)
878 int argc;
879 if (!L)
880 return 0;
882 StackDump(L, "Before LuaCall\n");
883 lua_getfield(L, LUA_GLOBALSINDEX, func);
884 if (lua_isnil(L, -1))
886 lua_pop(L, 1);
887 lua_pushstring(L, "Could not find the script function\n");
888 LuaShowErr(L);
889 return 0;
891 for (argc = 0; *argv; argv++, argc++)
893 lua_pushstring(L, *argv);
895 if (lua_pcall(L, argc, 0, 0) == LUA_ERRRUN)
897 if(lua_isstring(L, -1))
899 StackDump(L, "After LuaCall\n");
900 LuaShowErr(L);
901 return 0;
904 return 1;
907 /*** Lua callback handler management {{{ */
910 LuaPushHTable(lua_State *L, int screen, const char * t)
912 lua_pushstring(L, t);
913 lua_rawget(L, screen);
914 /* FIXME: Do we need to balance the stack here? */
915 if (lua_isnil(L, -1))
916 luaL_error(L, "Fatal! Fail to get function registeration table!");
917 return lua_gettop(L);
920 void
921 LuaPushHandler(lua_State *L, struct lua_handler * lh)
923 int keyfunc;
924 luaL_getmetatable(L, "screen");
925 keyfunc = LuaPushHTable(L, -1, "_keyfunc");
926 lua_rawgeti(L, keyfunc, lh->u.reference);
927 lua_replace(L, -3);
928 lua_pop(L, 1);
932 LuaFuncKey(lua_State *L, int idx)
934 int key, funckey, sc;
935 luaL_getmetatable(L, "screen");
936 sc = lua_gettop(L);
937 funckey = LuaPushHTable(L, sc, "_funckey");
939 lua_pushvalue(L, idx);
940 lua_gettable(L, funckey);/*funckey[func] ==?*/
941 if (lua_isnil(L, -1))
943 /* Not found, alloc a new key */
945 /*funckey[key] = 1*/
946 lua_pushinteger(L, 1);
947 key = luaL_ref(L, funckey);
949 /*funckey[func]=key*/
950 lua_pushvalue(L, idx);
951 lua_pushinteger(L, key);
952 lua_settable(L, funckey);
954 int keyfunc = LuaPushHTable(L, sc, "_keyfunc");
955 /*keyfunc[key] = func*/
956 lua_pushinteger(L, key);
957 lua_pushvalue(L, idx);
958 lua_settable(L, keyfunc);
960 lua_pop(L, 1);
962 else
963 key = lua_tointeger(L, -1);/*key = funckey[func]*/
965 lua_pop(L, 3);
966 return key;
969 void
970 LuaHRef(lua_State *L, int key, int reg)
972 int funckey, keyfunc, cnt, sc, idx;
973 luaL_getmetatable(L, "screen");
974 sc = lua_gettop(L);
975 funckey = LuaPushHTable(L, sc, "_funckey");
976 keyfunc = LuaPushHTable(L, sc, "_keyfunc");
978 lua_rawgeti(L, keyfunc, key);
979 idx = lua_gettop(L);
981 lua_rawgeti(L, funckey, key);
982 cnt = lua_tointeger(L, -1);/*cnt = htable[key]*/
983 if (!reg && cnt <= 1)
985 /*release the last reference*/
986 luaL_unref(L, funckey, key);
987 lua_pushvalue(L, idx);
988 lua_pushnil(L);
989 lua_settable(L, funckey); /*htable[func]=key*/
991 else
993 lua_pushinteger(L, key);
994 lua_pushinteger(L, reg? cnt + 1 : cnt - 1);
995 lua_settable(L, funckey); /*htable[key] = cnt + 1*/
997 lua_pop(L, 3);
1000 void
1001 LuaHSetName(lua_State *L, int key, int name)
1003 int keyfunc, sc;
1004 luaL_getmetatable(L, "screen");
1005 sc = lua_gettop(L);
1006 keyfunc = LuaPushHTable(L, sc, "_keyfunc");
1008 lua_rawgeti(L, keyfunc, key);
1009 lua_pushvalue(L, name);
1010 lua_rawset(L, keyfunc);
1012 lua_pop(L, 2);
1015 /* Do not hold the return value for long */
1016 const char *
1017 LuaHGetName(lua_State *L, int key)
1019 int keyfunc, sc;
1020 const char * name;
1021 luaL_getmetatable(L, "screen");
1022 sc = lua_gettop(L);
1023 keyfunc = LuaPushHTable(L, sc, "_keyfunc");
1025 lua_rawgeti(L, keyfunc, key);
1026 lua_rawget(L, keyfunc);
1027 name = lua_tostring(L, -1);
1028 lua_pop(L, 3);
1029 return name;
1032 struct lua_handler *
1033 LuaCheckHandler(lua_State *L, int idx, int reg)
1035 int name = 0, key, sc;
1036 if (lua_isstring(L, idx))
1038 const char * handler;
1039 /* registered with func name.*/
1040 handler = luaL_checkstring(L, idx);
1041 name = idx++;
1042 lua_getfield(L, LUA_GLOBALSINDEX, handler);
1043 if (!lua_isfunction(L, -1))
1044 luaL_error(L, "The specified handler %s in param #%d is not a function", handler, idx);
1046 else if (!lua_isfunction(L, idx))
1047 luaL_error(L, "Handler should be a function or the name of function");
1049 sc = lua_gettop(L);
1050 key = LuaFuncKey(L, idx );
1051 LuaHRef(L, key, reg);
1052 if (name)
1054 LuaHSetName(L, key, name);
1055 lua_pop(L, 1);
1057 return LuaAllocHandler(NULL, key);
1060 /* }}} **/
1062 static int
1063 LuaDispatch(void *handler, const char *params, va_list va)
1065 struct lua_handler *lh = handler;
1066 int argc, retvalue;
1068 StackDump(L, "before dispatch");
1070 LuaPushHandler(L, lh);
1071 if (lua_isnil(L, -1))
1073 lua_pop(L, 1);
1074 return 0;
1076 argc = LuaPushParams(L, params, va);
1078 if (lua_pcall(L, argc, 1, 0) == LUA_ERRRUN && lua_isstring(L, -1))
1080 StackDump(L, "After LuaDispatch\n");
1081 LuaShowErr(L);
1082 return 0;
1084 retvalue = lua_tonumber(L, -1);
1085 lua_pop(L, 1);
1086 return retvalue;
1089 int LuaForeWindowChanged(void)
1091 struct fn_def params[] = {
1092 {push_display, &display},
1093 {push_window, display ? &D_fore : &fore},
1094 {NULL, NULL}
1096 if (!L)
1097 return 0;
1098 return LuaCallProcess("fore_changed", params);
1101 #define SEVNAME_MAX 30
1102 static int
1103 LuaRegEvent(lua_State *L)
1105 /* signature: hook(obj, event, handler, priv);
1106 * or: hook(event, handler, priv)
1107 * returns: A ticket for later unregister. */
1108 int idx = 1, argc = lua_gettop(L);
1109 unsigned int priv = 31; /* Default privilege */
1110 struct lua_handler *lh;
1112 char *obj = NULL;
1113 const char *objname = "global";
1115 static char evbuf[SEVNAME_MAX];
1116 const char *event;
1118 struct script_event *sev;
1120 StackDump(L, "Before RegEvent\n");
1122 /* Identify the object, if specified */
1123 if (luaL_getmetafield(L, 1, "_objname"))
1125 objname = luaL_checkstring(L, -1);
1126 lua_pop(L, 1);
1127 if (!strcmp("screen", objname))
1128 objname = "global";
1129 else
1130 obj = *(char **)lua_touserdata(L, 1);
1131 idx++;
1134 event = luaL_checkstring(L, idx++);
1135 snprintf(evbuf, SEVNAME_MAX, "%s_%s", objname, event);
1137 /* Check and get the handler */
1138 lh = LuaCheckHandler(L, idx++, 1);
1139 if (!lh)
1140 luaL_error(L, "Out of memory");
1142 StackDump(L, "In RegEvent\n");
1144 if (idx <= argc)
1145 priv = luaL_checkinteger(L, idx);
1147 sev = object_get_event(obj, evbuf);
1148 if (sev)
1150 struct listener *l;
1151 l = (struct listener *)malloc(sizeof(struct listener));
1152 if (!l)
1153 return luaL_error(L, "Out of memory");
1154 l->priv = priv;
1155 l->dispatcher = LuaDispatch;
1156 if (register_listener(sev, l))
1158 const char *fname = LuaHGetName(L, lh->u.reference);
1159 free(l);
1160 if (fname)
1161 return luaL_error(L, "Handler %s has already been registered", fname);
1162 else
1163 return luaL_error(L, "Handler has already been registered");
1165 /* Return the handler for un-register */
1166 l->handler = lh;
1167 lua_pushlightuserdata(L, l);
1169 else
1170 return luaL_error(L, "Invalid event specified: %s for object %s", event, objname);
1172 StackDump(L, "After RegEvent\n");
1173 return 1;
1176 static int
1177 LuaUnRegEvent(lua_State *L)
1179 /* signature: unhook([obj], ticket)
1180 * returns: true of success, false otherwise */
1181 int idx = 1;
1182 struct listener *l;
1184 /* If the param is not as expected */
1185 if (!lua_islightuserdata(L, idx))
1187 /* Then it should be the userdata to be ignore, but if not ... */
1188 if (!lua_isuserdata(L, idx))
1189 luaL_checktype(L, idx, LUA_TLIGHTUSERDATA);
1190 idx++;
1191 luaL_checktype(L, idx, LUA_TLIGHTUSERDATA);
1194 l = (struct listener*)lua_touserdata(L, idx++);
1196 /* Validate the listener structure */
1197 if (!l || !l->handler)
1199 /* invalid */
1200 lua_pushboolean(L,0);
1202 else
1204 LuaFreeHandler(((struct lua_handler **)&(l->handler)));
1205 unregister_listener(l);
1206 lua_pushboolean(L, 1);
1209 return 1;
1212 /** }}} */
1214 struct ScriptFuncs LuaFuncs =
1216 LuaForeWindowChanged,
1217 LuaProcessCaption
1220 struct binding lua_binding =
1222 "lua", /*name*/
1223 0, /*inited*/
1224 0, /*registered*/
1225 LuaInit,
1226 LuaFinit,
1227 LuaCall,
1228 LuaSource,
1229 0, /*b_next*/
1230 &LuaFuncs