A simple asynchronous input interface.
[screen-lua.git] / src / lua.c
blob0ef4ef5c01e915c900b18d5d4f0ce29d7951e785
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);
82 struct binding lua_binding;
84 typedef int lua_handler;
85 #define LuaAllocHandler(a) a
86 #define LuaFreeHandler(a)
88 void LuaPushHandler(lua_State *L, lua_handler lh);
89 void LuaHRef(lua_State *L, int key, int reg);
90 lua_handler LuaCheckHandler(lua_State *L, int idx, int ref);
92 /** Template {{{ */
94 #define CHECK_TYPE(name, type) \
95 static type * \
96 check_##name(lua_State *L, int index) \
97 { \
98 type **var; \
99 luaL_checktype(L, index, LUA_TUSERDATA); \
100 var = (type **) luaL_checkudata(L, index, #name); \
101 if (!var || !*var) \
102 luaL_typerror(L, index, #name); \
103 return *var; \
106 #define PUSH_TYPE(name, type) \
107 static void \
108 push_##name(lua_State *L, type **t) \
110 if (!t || !*t) \
111 lua_pushnil(L); \
112 else \
114 type **r; \
115 r = (type **)lua_newuserdata(L, sizeof(type *)); \
116 *r = *t; \
117 luaL_getmetatable(L, #name); \
118 lua_setmetatable(L,-2); \
122 /* Much of the following template comes from:
123 * http://lua-users.org/wiki/BindingWithMembersAndMethods
126 static int get_int (lua_State *L, void *v)
128 lua_pushinteger (L, *(int*)v);
129 return 1;
132 static int set_int (lua_State *L, void *v)
134 *(int*)v = luaL_checkint(L, 3);
135 return 0;
138 static int get_number (lua_State *L, void *v)
140 lua_pushnumber(L, *(lua_Number*)v);
141 return 1;
144 static int set_number (lua_State *L, void *v)
146 *(lua_Number*)v = luaL_checknumber(L, 3);
147 return 0;
150 static int get_string (lua_State *L, void *v)
152 lua_pushstring(L, (char*)v );
153 return 1;
156 static int set_string (lua_State *L, void *v)
158 *(const char**)v = luaL_checkstring(L, 3);
159 return 0;
162 typedef int (*Xet_func) (lua_State *L, void *v);
164 /* member info for get and set handlers */
165 struct Xet_reg
167 const char *name; /* member name */
168 Xet_func func; /* get or set function for type of member */
169 size_t offset; /* offset of member within the struct */
170 int (*absolute)(lua_State *);
173 static void Xet_add (lua_State *L, const struct Xet_reg *l)
175 if (!l)
176 return;
177 for (; l->name; l++)
179 lua_pushstring(L, l->name);
180 lua_pushlightuserdata(L, (void*)l);
181 lua_settable(L, -3);
185 static int Xet_call (lua_State *L)
187 /* for get: stack has userdata, index, lightuserdata */
188 /* for set: stack has userdata, index, value, lightuserdata */
189 const struct Xet_reg *m = (const struct Xet_reg *)lua_touserdata(L, -1); /* member info */
190 lua_pop(L, 1); /* drop lightuserdata */
191 luaL_checktype(L, 1, LUA_TUSERDATA);
192 if (m->absolute)
193 return m->absolute(L);
194 return m->func(L, *(char**)lua_touserdata(L, 1) + m->offset);
197 static int index_handler (lua_State *L)
199 /* stack has userdata, index */
200 lua_pushvalue(L, 2); /* dup index */
201 lua_rawget(L, lua_upvalueindex(1)); /* lookup member by name */
202 if (!lua_islightuserdata(L, -1))
204 lua_pop(L, 1); /* drop value */
205 lua_pushvalue(L, 2); /* dup index */
206 lua_gettable(L, lua_upvalueindex(2)); /* else try methods */
207 if (lua_isnil(L, -1)) /* invalid member */
208 luaL_error(L, "cannot get member '%s'", lua_tostring(L, 2));
209 return 1;
211 return Xet_call(L); /* call get function */
214 static int newindex_handler (lua_State *L)
216 /* stack has userdata, index, value */
217 lua_pushvalue(L, 2); /* dup index */
218 lua_rawget(L, lua_upvalueindex(1)); /* lookup member by name */
219 if (!lua_islightuserdata(L, -1)) /* invalid member */
220 luaL_error(L, "cannot set member '%s'", lua_tostring(L, 2));
221 return Xet_call(L); /* call set function */
224 static int
225 struct_register(lua_State *L, const char *name, const luaL_reg fn_methods[], const luaL_reg meta_methods[],
226 const struct Xet_reg setters[], const struct Xet_reg getters[])
228 int metatable, methods;
230 /* create methods table & add it to the table of globals */
231 luaL_register(L, name, fn_methods);
232 methods = lua_gettop(L);
234 /* create metatable & add it to the registry */
235 luaL_newmetatable(L, name);
236 luaL_register(L, 0, meta_methods); /* fill metatable */
238 /* To identify the type of object */
239 lua_pushstring(L, "_objname");
240 lua_pushstring(L, name);
241 lua_rawset(L, -3);
243 metatable = lua_gettop(L);
245 lua_pushliteral(L, "__metatable");
246 lua_pushvalue(L, methods); /* dup methods table*/
247 lua_rawset(L, metatable); /* hide metatable:
248 metatable.__metatable = methods */
250 lua_pushliteral(L, "__index");
251 lua_pushvalue(L, metatable); /* upvalue index 1 */
252 Xet_add(L, getters); /* fill metatable with getters */
253 lua_pushvalue(L, methods); /* upvalue index 2 */
254 lua_pushcclosure(L, index_handler, 2);
255 lua_rawset(L, metatable); /* metatable.__index = index_handler */
257 lua_pushliteral(L, "__newindex");
258 lua_newtable(L); /* table for members you can set */
259 Xet_add(L, setters); /* fill with setters */
260 lua_pushcclosure(L, newindex_handler, 1);
261 lua_rawset(L, metatable); /* metatable.__newindex = newindex_handler */
263 /* FIXME: Why do we leave an element on the stack? */
264 lua_pop(L, 1); /* drop metatable */
265 return 1; /* return methods on the stack */
268 /** }}} */
270 /** Window {{{ */
272 PUSH_TYPE(window, struct win)
274 CHECK_TYPE(window, struct win)
276 static int get_window(lua_State *L, void *v)
278 push_window(L, (struct win **)v);
279 return 1;
282 static int
283 window_change_title(lua_State *L)
285 struct win *w = check_window(L, 1);
286 unsigned int len;
287 const char *title = luaL_checklstring(L, 2, &len);
288 ChangeAKA(w, (char *)title, len);
289 return 0;
292 static int
293 window_get_monitor_status(lua_State *L)
295 struct win *w = check_window(L, 1);
296 int activity = luaL_checkint(L, 2);
297 if (activity)
298 /*monitor*/
299 lua_pushinteger(L, w->w_monitor != MON_OFF);
300 else
301 /*silence*/
302 lua_pushinteger(L, w->w_silence == SILENCE_ON ? w->w_silencewait: 0);
304 return 1;
307 static const luaL_reg window_methods[] = {
308 {"get_monitor_status", window_get_monitor_status},
309 {"hook", LuaRegEvent},
310 {0, 0}
313 static int
314 window_tostring(lua_State *L)
316 char str[128];
317 struct win *w = check_window(L, 1);
318 snprintf(str, sizeof(str), "{window #%d: '%s'}", w->w_number, w->w_title);
319 lua_pushstring(L, str);
320 return 1;
323 static int
324 window_equality(lua_State *L)
326 struct win *w1 = check_window(L, 1), *w2 = check_window(L, 2);
327 lua_pushboolean(L, (w1 == w2 || (w1 && w2 && w1->w_number == w2->w_number)));
328 return 1;
331 static const luaL_reg window_metamethods[] = {
332 {"__tostring", window_tostring},
333 {"__eq", window_equality},
334 {0, 0}
337 static const struct Xet_reg window_setters[] = {
338 {"title", 0, 0, window_change_title/*absolute setter*/},
339 {0, 0}
342 static const struct Xet_reg window_getters[] = {
343 {"title", get_string, offsetof(struct win, w_title) + 8},
344 {"number", get_int, offsetof(struct win, w_number)},
345 {"dir", get_string, offsetof(struct win, w_dir)},
346 {"tty", get_string, offsetof(struct win, w_tty)},
347 {"pid", get_int, offsetof(struct win, w_pid)},
348 {"group", get_window, offsetof(struct win, w_group)},
349 {"bell", get_int, offsetof(struct win, w_bell)},
350 {0, 0}
354 /** }}} */
356 /** AclUser {{{ */
358 PUSH_TYPE(user, struct acluser)
360 CHECK_TYPE(user, struct acluser)
362 static int
363 get_user(lua_State *L, void *v)
365 push_user(L, (struct acluser **)v);
366 return 1;
369 static const luaL_reg user_methods[] = {
370 {0, 0}
373 static int
374 user_tostring(lua_State *L)
376 char str[128];
377 struct acluser *u = check_user(L, 1);
378 snprintf(str, sizeof(str), "{user '%s'}", u->u_name);
379 lua_pushstring(L, str);
380 return 1;
383 static const luaL_reg user_metamethods[] = {
384 {"__tostring", user_tostring},
385 {0, 0}
388 static const struct Xet_reg user_setters[] = {
389 {0, 0}
392 static const struct Xet_reg user_getters[] = {
393 {"name", get_string, offsetof(struct acluser, u_name)},
394 {"password", get_string, offsetof(struct acluser, u_password)},
395 {0, 0}
398 /** }}} */
400 /** Canvas {{{ */
402 PUSH_TYPE(canvas, struct canvas)
404 CHECK_TYPE(canvas, struct canvas)
406 static int
407 get_canvas(lua_State *L, void *v)
409 push_canvas(L, (struct canvas **)v);
410 return 1;
413 static int
414 canvas_select(lua_State *L)
416 struct canvas *c = check_canvas(L, 1);
417 if (!display || D_forecv == c)
418 return 0;
419 SetCanvasWindow(c, Layer2Window(c->c_layer));
420 D_forecv = c;
422 /* XXX: the following all is duplicated from process.c:DoAction.
423 * Should these be in some better place?
425 ResizeCanvas(&D_canvas);
426 RecreateCanvasChain();
427 RethinkDisplayViewports();
428 ResizeLayersToCanvases(); /* redisplays */
429 fore = D_fore = Layer2Window(D_forecv->c_layer);
430 flayer = D_forecv->c_layer;
431 #ifdef RXVT_OSC
432 if (D_xtermosc[2] || D_xtermosc[3])
434 Activate(-1);
435 break;
437 #endif
438 RefreshHStatus();
439 #ifdef RXVT_OSC
440 RefreshXtermOSC();
441 #endif
442 flayer = D_forecv->c_layer;
443 CV_CALL(D_forecv, LayRestore();LaySetCursor());
444 WindowChanged(0, 'F');
445 return 1;
448 static const luaL_reg canvas_methods[] = {
449 {"select", canvas_select},
450 {0, 0}
453 static const luaL_reg canvas_metamethods[] = {
454 {0, 0}
457 static const struct Xet_reg canvas_setters[] = {
458 {0, 0}
461 static int
462 canvas_get_window(lua_State *L)
464 struct canvas *c = check_canvas(L, 1);
465 struct win *win = Layer2Window(c->c_layer);
466 if (win)
467 push_window(L, &win);
468 else
469 lua_pushnil(L);
470 return 1;
473 static const struct Xet_reg canvas_getters[] = {
474 {"next", get_canvas, offsetof(struct canvas, c_next)},
475 {"xoff", get_int, offsetof(struct canvas, c_xoff)},
476 {"yoff", get_int, offsetof(struct canvas, c_yoff)},
477 {"xs", get_int, offsetof(struct canvas, c_xs)},
478 {"ys", get_int, offsetof(struct canvas, c_ys)},
479 {"xe", get_int, offsetof(struct canvas, c_xe)},
480 {"ye", get_int, offsetof(struct canvas, c_ye)},
481 {"window", 0, 0, canvas_get_window},
482 {0, 0}
485 /** }}} */
487 /** Layout {{{ */
489 PUSH_TYPE(layout, struct layout)
490 CHECK_TYPE(layout, struct layout)
492 static const struct Xet_reg layout_getters[] = {
493 {0,0}
496 static int
497 get_layout(lua_State *L, void *v)
499 push_layout(L, (struct layout **)v);
500 return 1;
503 /** }}} */
505 /** Display {{{ */
507 PUSH_TYPE(display, struct display)
509 CHECK_TYPE(display, struct display)
511 static int
512 display_get_canvases(lua_State *L)
514 struct display *d;
515 struct canvas *iter;
516 int count;
518 d = check_display(L, 1);
519 lua_newtable(L);
520 for (iter = d->d_cvlist, count = 0; iter; iter = iter->c_next, count++) {
521 lua_pushinteger(L, count);
522 push_canvas(L, &iter);
523 lua_settable(L, -3);
526 return 1;
529 static const luaL_reg display_methods[] = {
530 {"get_canvases", display_get_canvases},
531 {0, 0}
534 static int
535 display_tostring(lua_State *L)
537 char str[128];
538 struct display *d = check_display(L, 1);
539 snprintf(str, sizeof(str), "{display: tty = '%s', term = '%s'}", d->d_usertty, d->d_termname);
540 lua_pushstring(L, str);
541 return 1;
544 static const luaL_reg display_metamethods[] = {
545 {"__tostring", display_tostring},
546 {0, 0}
549 static const struct Xet_reg display_setters[] = {
550 {0, 0}
553 static const struct Xet_reg display_getters[] = {
554 {"tty", get_string, offsetof(struct display, d_usertty)},
555 {"term", get_string, offsetof(struct display, d_termname)},
556 {"fore", get_window, offsetof(struct display, d_fore)},
557 {"other", get_window, offsetof(struct display, d_other)},
558 {"width", get_int, offsetof(struct display, d_width)},
559 {"height", get_int, offsetof(struct display, d_height)},
560 {"user", get_user, offsetof(struct display, d_user)},
561 {"layout", get_layout, offsetof(struct display, d_layout)},
562 {0, 0}
565 /** }}} */
567 /** Screen {{{ */
569 static int
570 screen_get_windows(lua_State *L)
572 struct win *iter;
573 int count;
575 lua_newtable(L);
576 for (iter = windows, count = 0; iter; iter = iter->w_next, count++) {
577 lua_pushinteger(L, iter->w_number);
578 push_window(L, &iter);
579 lua_settable(L, -3);
582 return 1;
585 static int
586 screen_get_displays(lua_State *L)
588 struct display *iter;
589 int count;
591 lua_newtable(L);
592 for (iter = displays, count = 0; iter; iter = iter->d_next, count++) {
593 lua_pushinteger(L, count);
594 push_display(L, &iter);
595 lua_settable(L, -3);
598 return 1;
601 static int
602 screen_get_display(lua_State *L)
604 push_display(L, &display);
605 return 1;
608 static int
609 screen_exec_command(lua_State *L)
611 const char *command;
612 unsigned int len;
614 command = luaL_checklstring(L, 1, &len);
615 if (command)
616 RcLine((char *)command, len);
618 return 0;
621 static int
622 screen_append_msg(lua_State *L)
624 const char *msg, *color;
625 unsigned int len;
626 msg = luaL_checklstring(L, 1, &len);
627 if (lua_isnil(L, 2))
628 color = NULL;
629 else
630 color = luaL_checklstring(L, 2, &len);
631 AppendWinMsgRend(msg, color);
632 return 0;
635 struct sinput_data
637 lua_State *L;
638 lua_handler lh;
640 void
641 script_input_fn(char *buf, int len, char *priv)
643 struct sinput_data *sidata = (struct sinput_data *)priv;
644 lua_handler lh = sidata->lh;
645 lua_State *L = sidata->L;
647 LuaPushHandler(L, lh);
648 lua_pushstring(L, buf);
649 if (lua_pcall(L, 1, 0, 0) == LUA_ERRRUN)
651 if(lua_isstring(L, -1))
653 LuaShowErr(L);
656 free(sidata);
657 LuaHRef(L, lh, 0);
660 static int
661 screen_input(lua_State *L)
663 char * prompt = NULL;
664 lua_handler lh;
665 struct sinput_data *sidata;
667 prompt = (char *)luaL_checkstring(L, 1);
668 lh = LuaCheckHandler(L, 2, 1);
669 sidata = (struct sinput_data *)malloc(sizeof(struct sinput_data));
670 if (!sidata)
671 luaL_error(L, "Out of Memory");
673 sidata->L = L;
674 sidata->lh = lh;
675 Input(prompt, 100, INP_COOKED, script_input_fn, (char *)sidata, 0);
677 return 0;
680 static const luaL_reg screen_methods[] = {
681 {"windows", screen_get_windows},
682 {"displays", screen_get_displays},
683 {"display", screen_get_display},
684 {"command", screen_exec_command},
685 {"append_msg", screen_append_msg},
686 {"hook", LuaRegEvent},
687 {"unhook", LuaUnRegEvent},
688 {"input", screen_input},
689 {0, 0}
692 static const luaL_reg screen_metamethods[] = {
693 {0, 0}
696 static const struct Xet_reg screen_setters[] = {
697 {0, 0}
700 static const struct Xet_reg screen_getters[] = {
701 {0, 0}
704 /** }}} */
706 /** Public functions {{{ */
708 /* FIXME: Think about this: will it affect the registered handlers?*/
709 static lua_State *L;
710 int LuaInit(void)
712 L = luaL_newstate();
714 luaL_openlibs(L);
716 #define REGISTER(X) struct_register(L, #X , X ## _methods, X##_metamethods, X##_setters, X##_getters)
718 REGISTER(screen);
719 REGISTER(window);
720 REGISTER(display);
721 REGISTER(user);
722 REGISTER(canvas);
724 /* To store handler funcs */
725 luaL_getmetatable(L, "screen");
726 /* two kinds of info in this table:
727 * _funckey[func]->key
728 * _funckey[key]->refcnt */
729 lua_pushstring(L, "_funckey");
730 lua_newtable(L);
731 lua_rawset(L, -3);
732 /* two kinds of info in this table:
733 * _keyfunc[key]->func
734 * _keyfunc[func]->name */
735 lua_pushstring(L, "_keyfunc");
736 lua_newtable(L);
737 lua_rawset(L, -3);
738 lua_pop(L, 1);
740 return 0;
743 /* An error message on top of the stack. */
744 static void
745 LuaShowErr(lua_State *L)
747 struct display *d = display;
748 unsigned int len;
749 const char *message = luaL_checklstring(L, -1, &len);
750 LMsg(0, "%s", message ? message : "Unknown error");
751 lua_pop(L, 1);
752 display = d;
755 struct fn_def
757 void (*push_fn)(lua_State *, void*);
758 void *value;
761 static int
762 LuaCallProcess(const char *name, struct fn_def defs[])
764 int argc = 0;
766 lua_getfield(L, LUA_GLOBALSINDEX, name);
767 if (lua_isnil(L, -1))
769 lua_pop(L,1);
770 return 0;
772 for (argc = 0; defs[argc].push_fn; argc++)
773 defs[argc].push_fn(L, defs[argc].value);
774 if (lua_pcall(L, argc, 0, 0) == LUA_ERRRUN && lua_isstring(L, -1))
776 LuaShowErr(L);
777 return 0;
779 return 1;
782 int LuaSource(const char *file, int async)
784 if (!L)
785 return 0;
786 struct stat st;
787 if (stat(file, &st) == -1)
788 Msg(errno, "Error loading lua script file '%s'", file);
789 else
791 int len = strlen(file);
792 if (len < 4 || strncmp(file + len - 4, ".lua", 4) != 0)
793 return 0;
794 if (luaL_dofile(L, file) && lua_isstring(L, -1))
796 LuaShowErr(L);
798 return 1;
800 return 0;
803 int LuaFinit(void)
805 if (!L)
806 return 0;
807 lua_close(L);
808 L = (lua_State*)0;
809 return 0;
813 LuaProcessCaption(const char *caption, struct win *win, int len)
815 if (!L)
816 return 0;
817 struct fn_def params[] = {
818 {lua_pushstring, caption},
819 {push_window, &win},
820 {lua_pushinteger, len},
821 {NULL, NULL}
823 return LuaCallProcess("process_caption", params);
826 static void
827 push_stringarray(lua_State *L, char **args)
829 int i;
830 lua_newtable(L);
831 for (i = 1; args && *args; i++) {
832 lua_pushinteger(L, i);
833 lua_pushstring(L, *args++);
834 lua_settable(L, -3);
839 LuaPushParams(lua_State *L, const char *params, va_list va)
841 int num = 0;
842 while (*params)
844 switch (*params)
846 case 's':
847 lua_pushstring(L, va_arg(va, char *));
848 break;
849 case 'S':
850 push_stringarray(L, va_arg(va, char **));
851 break;
852 case 'i':
853 lua_pushinteger(L, va_arg(va, int));
854 break;
855 case 'd':
857 struct display *d = va_arg(va, struct display *);
858 push_display(L, &d);
859 break;
862 params++;
863 num++;
865 return num;
868 int LuaCall(const char *func, const char **argv)
870 int argc;
871 if (!L)
872 return 0;
874 StackDump(L, "Before LuaCall\n");
875 lua_getfield(L, LUA_GLOBALSINDEX, func);
876 if (lua_isnil(L, -1))
878 lua_pop(L, 1);
879 lua_pushstring(L, "Could not find the script function\n");
880 LuaShowErr(L);
881 return 0;
883 for (argc = 0; *argv; argv++, argc++)
885 lua_pushstring(L, *argv);
887 if (lua_pcall(L, argc, 0, 0) == LUA_ERRRUN)
889 if(lua_isstring(L, -1))
891 StackDump(L, "After LuaCall\n");
892 LuaShowErr(L);
893 return 0;
896 return 1;
899 /*** Lua callback handler management {{{ */
902 LuaPushHTable(lua_State *L, int screen, const char * t)
904 lua_pushstring(L, t);
905 lua_rawget(L, screen);
906 /* FIXME: Do we need to balance the stack here? */
907 if (lua_isnil(L, -1))
908 luaL_error(L, "Fatal! Fail to get function registeration table!");
909 return lua_gettop(L);
912 void
913 LuaPushHandler(lua_State *L, lua_handler lh)
915 int keyfunc;
916 luaL_getmetatable(L, "screen");
917 keyfunc = LuaPushHTable(L, lua_gettop(L), "_keyfunc");
918 lua_rawgeti(L, keyfunc, lh);
919 lua_replace(L, -3);
920 lua_pop(L, 1);
923 void
924 LuaHRef(lua_State *L, int key, int reg)
926 int funckey, keyfunc, cnt, sc, idx;
927 luaL_getmetatable(L, "screen");
928 sc = lua_gettop(L);
929 funckey = LuaPushHTable(L, sc, "_funckey");
930 keyfunc = LuaPushHTable(L, sc, "_keyfunc");
932 lua_rawgeti(L, keyfunc, key);
933 idx = lua_gettop(L);
935 lua_rawgeti(L, funckey, key);
936 cnt = lua_tointeger(L, -1);/*cnt = htable[key]*/
937 if (!reg && cnt <= 1)
939 /*release the last reference*/
940 luaL_unref(L, funckey, key);
941 lua_pushvalue(L, idx);
942 lua_pushnil(L);
943 lua_settable(L, funckey); /*htable[func]=key*/
945 else
947 lua_pushinteger(L, key);
948 lua_pushinteger(L, reg? cnt + 1 : cnt - 1);
949 lua_settable(L, funckey); /*htable[key] = cnt + 1*/
951 lua_pop(L, 5);
954 /* Ref when asked to. Never unref*/
956 LuaFuncKey(lua_State *L, int idx, int ref)
958 int key, funckey, sc;
959 luaL_getmetatable(L, "screen");
960 sc = lua_gettop(L);
961 funckey = LuaPushHTable(L, sc, "_funckey");
963 lua_pushvalue(L, idx);
964 lua_gettable(L, funckey);/*funckey[func] ==?*/
965 if (lua_isnil(L, -1))
967 /* Not found, alloc a new key */
968 if (!ref)
969 return LUA_NOREF;
971 /*funckey[key] = 1*/
972 lua_pushinteger(L, 1);
973 key = luaL_ref(L, funckey);
975 /*funckey[func]=key*/
976 lua_pushvalue(L, idx);
977 lua_pushinteger(L, key);
978 lua_settable(L, funckey);
980 int keyfunc = LuaPushHTable(L, sc, "_keyfunc");
981 /*keyfunc[key] = func*/
982 lua_pushinteger(L, key);
983 lua_pushvalue(L, idx);
984 lua_settable(L, keyfunc);
986 lua_pop(L, 1);
988 else
990 key = lua_tointeger(L, -1);/*key = funckey[func]*/
991 if (ref)
992 LuaHRef(L, key, 1);
995 lua_pop(L, 3);
996 return key;
999 void
1000 LuaHSetName(lua_State *L, int key, int name)
1002 int keyfunc, sc;
1003 luaL_getmetatable(L, "screen");
1004 sc = lua_gettop(L);
1005 keyfunc = LuaPushHTable(L, sc, "_keyfunc");
1007 lua_rawgeti(L, keyfunc, key);
1008 lua_pushvalue(L, name);
1009 lua_rawset(L, keyfunc);
1011 lua_pop(L, 2);
1014 /* Do not hold the return value for long */
1015 const char *
1016 LuaHGetName(lua_State *L, lua_handler key)
1018 int keyfunc, sc;
1019 const char * name;
1020 luaL_getmetatable(L, "screen");
1021 sc = lua_gettop(L);
1022 keyfunc = LuaPushHTable(L, sc, "_keyfunc");
1024 lua_rawgeti(L, keyfunc, key);
1025 lua_rawget(L, keyfunc);
1026 name = lua_tostring(L, -1);
1027 lua_pop(L, 3);
1028 return name;
1031 lua_handler
1032 LuaCheckHandler(lua_State *L, int idx, int ref)
1034 int name = 0, key;
1035 if (lua_isstring(L, idx))
1037 const char * handler;
1038 /* registered with func name.*/
1039 handler = luaL_checkstring(L, idx);
1040 name = idx++;
1041 lua_getfield(L, LUA_GLOBALSINDEX, handler);
1042 if (!lua_isfunction(L, -1))
1043 luaL_error(L, "The specified handler %s in param #%d is not a function", handler, idx);
1045 else if (!lua_isfunction(L, idx))
1046 luaL_error(L, "Handler should be a function or the name of function");
1048 key = LuaFuncKey(L, idx, ref);
1049 if (name && key != LUA_NOREF)
1051 LuaHSetName(L, key, name);
1052 lua_pop(L, 1);
1054 return LuaAllocHandler(key);
1058 LuaHdlrComp(void *h1, void *h2)
1060 return (lua_handler)h1 - (lua_handler)h2;
1063 /* }}} **/
1065 static int
1066 LuaDispatch(void *handler, const char *params, va_list va)
1068 lua_handler lh = (lua_handler)handler;
1069 int argc, retvalue;
1071 StackDump(L, "before dispatch");
1073 LuaPushHandler(L, lh);
1074 if (lua_isnil(L, -1))
1076 lua_pop(L, 1);
1077 return 0;
1079 argc = LuaPushParams(L, params, va);
1081 if (lua_pcall(L, argc, 1, 0) == LUA_ERRRUN && lua_isstring(L, -1))
1083 StackDump(L, "After LuaDispatch\n");
1084 LuaShowErr(L);
1085 return 0;
1087 retvalue = lua_tonumber(L, -1);
1088 lua_pop(L, 1);
1089 return retvalue;
1092 int LuaForeWindowChanged(void)
1094 struct fn_def params[] = {
1095 {push_display, &display},
1096 {push_window, display ? &D_fore : &fore},
1097 {NULL, NULL}
1099 if (!L)
1100 return 0;
1101 return LuaCallProcess("fore_changed", params);
1104 #define SEVNAME_MAX 30
1105 static int
1106 LuaRegEvent(lua_State *L)
1108 /* signature: hook(obj, event, handler, priv);
1109 * or: hook(event, handler, priv)
1110 * returns: A ticket for later unregister. */
1111 int idx = 1, argc = lua_gettop(L);
1112 unsigned int priv = 31; /* Default privilege */
1113 lua_handler lh;
1115 char *obj = NULL;
1116 const char *objname = "global";
1118 static char evbuf[SEVNAME_MAX];
1119 const char *event;
1121 struct script_event *sev;
1123 StackDump(L, "Before RegEvent\n");
1125 /* Identify the object, if specified */
1126 if (luaL_getmetafield(L, 1, "_objname"))
1128 objname = luaL_checkstring(L, -1);
1129 lua_pop(L, 1);
1130 if (!strcmp("screen", objname))
1131 objname = "global";
1132 else
1133 obj = *(char **)lua_touserdata(L, 1);
1134 idx++;
1137 event = luaL_checkstring(L, idx++);
1138 snprintf(evbuf, SEVNAME_MAX, "%s_%s", objname, event);
1140 /* Check and get the handler */
1141 lh = LuaCheckHandler(L, idx++, 1);
1142 if (!lh)
1143 luaL_error(L, "Out of memory");
1145 StackDump(L, "In RegEvent\n");
1147 if (idx <= argc)
1148 priv = luaL_checkinteger(L, idx);
1150 sev = object_get_event(obj, evbuf);
1151 if (sev)
1153 struct listener *l;
1154 l = (struct listener *)malloc(sizeof(struct listener));
1155 if (!l)
1156 return luaL_error(L, "Out of memory");
1157 l->priv = priv;
1158 l->bd = &lua_binding;
1159 l->handler = (void *)lh;
1160 if (register_listener(sev, l))
1162 const char *fname = LuaHGetName(L, lh);
1163 free(l);
1164 if (fname)
1165 return luaL_error(L, "Handler %s has already been registered", fname);
1166 else
1167 return luaL_error(L, "Handler has already been registered");
1169 /* Return the handler for un-register */
1170 lua_pushlightuserdata(L, l);
1172 else
1173 return luaL_error(L, "Invalid event specified: %s for object %s", event, objname);
1175 StackDump(L, "After RegEvent\n");
1176 return 1;
1179 static int
1180 LuaUnRegEvent(lua_State *L)
1182 /* signature: unhook([obj], ticket, func)
1183 * returns: true of success, false otherwise */
1184 int idx = 1;
1185 struct listener *l;
1186 lua_handler lh;
1188 /* If the param is not as expected */
1189 if (!lua_islightuserdata(L, idx))
1191 /* Then it should be the userdata to be ignore, but if not ... */
1192 if (!lua_isuserdata(L, idx))
1193 luaL_checktype(L, idx, LUA_TLIGHTUSERDATA);
1194 idx++;
1195 luaL_checktype(L, idx, LUA_TLIGHTUSERDATA);
1198 l = (struct listener*)lua_touserdata(L, idx++);
1199 /* the handler is used to validate the ticket.
1200 * This is important, otherwise double unhook can crash screen. */
1201 lh = LuaCheckHandler(L, idx, 0);
1203 /* Validate the listener structure */
1204 if (lh == LUA_NOREF || !l || !l->handler)
1206 /* invalid */
1207 lua_pushboolean(L,0);
1209 else
1211 LuaHRef(L, (lua_handler)l->handler, 0);
1212 LuaFreeHandler(((lua_handler)&(l->handler)));
1213 unregister_listener(l);
1214 lua_pushboolean(L, 1);
1217 return 1;
1220 /** }}} */
1222 struct ScriptFuncs LuaFuncs =
1224 LuaForeWindowChanged,
1225 LuaProcessCaption
1228 struct binding lua_binding =
1230 "lua", /*name*/
1231 0, /*inited*/
1232 0, /*registered*/
1233 LuaInit,
1234 LuaFinit,
1235 LuaCall,
1236 LuaSource,
1237 LuaDispatch,
1238 LuaHdlrComp,
1239 0, /*b_next*/
1240 &LuaFuncs