Merge branch 'scripting-lua-unhook' (early part) into screen-scripting-soc
[screen-lua.git] / src / lua.c
blob742a7d092284470fb9cbab9d742b2ac2ecc2a4dd
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);
85 struct binding lua_binding;
87 enum
89 LUA_HANDLER_TYPE_N = 1,
90 LUA_HANDLER_TYPE_F
93 struct lua_handler
95 int type;
96 union
98 char *name;
99 int reference;
100 } u;
101 struct listener *listener;
104 void LuaPushHandler(lua_State *L, lua_handler lh);
105 void LuaHRef(lua_State *L, int key, int reg);
106 lua_handler LuaCheckHandler(lua_State *L, int idx, int ref);
108 /** Template {{{ */
110 #define CHECK_TYPE(name, type) \
111 static type * \
112 check_##name(lua_State *L, int index) \
114 type **var; \
115 luaL_checktype(L, index, LUA_TUSERDATA); \
116 var = (type **) luaL_checkudata(L, index, #name); \
117 if (!var || !*var) \
118 luaL_typerror(L, index, #name); \
119 return *var; \
122 #define PUSH_TYPE(name, type) \
123 static void \
124 push_##name(lua_State *L, type **t) \
126 if (!t || !*t) \
127 lua_pushnil(L); \
128 else \
130 type **r; \
131 r = (type **)lua_newuserdata(L, sizeof(type *)); \
132 *r = *t; \
133 luaL_getmetatable(L, #name); \
134 lua_setmetatable(L,-2); \
138 /* Much of the following template comes from:
139 * http://lua-users.org/wiki/BindingWithMembersAndMethods
142 static int get_int (lua_State *L, void *v)
144 lua_pushinteger (L, *(int*)v);
145 return 1;
148 static int set_int (lua_State *L, void *v)
150 *(int*)v = luaL_checkint(L, 3);
151 return 0;
154 static int get_number (lua_State *L, void *v)
156 lua_pushnumber(L, *(lua_Number*)v);
157 return 1;
160 static int set_number (lua_State *L, void *v)
162 *(lua_Number*)v = luaL_checknumber(L, 3);
163 return 0;
166 static int get_string (lua_State *L, void *v)
168 lua_pushstring(L, (char*)v );
169 return 1;
172 static int set_string (lua_State *L, void *v)
174 *(const char**)v = luaL_checkstring(L, 3);
175 return 0;
178 typedef int (*Xet_func) (lua_State *L, void *v);
180 /* member info for get and set handlers */
181 struct Xet_reg
183 const char *name; /* member name */
184 Xet_func func; /* get or set function for type of member */
185 size_t offset; /* offset of member within the struct */
186 int (*absolute)(lua_State *);
189 static void Xet_add (lua_State *L, const struct Xet_reg *l)
191 if (!l)
192 return;
193 for (; l->name; l++)
195 lua_pushstring(L, l->name);
196 lua_pushlightuserdata(L, (void*)l);
197 lua_settable(L, -3);
201 static int Xet_call (lua_State *L)
203 /* for get: stack has userdata, index, lightuserdata */
204 /* for set: stack has userdata, index, value, lightuserdata */
205 const struct Xet_reg *m = (const struct Xet_reg *)lua_touserdata(L, -1); /* member info */
206 lua_pop(L, 1); /* drop lightuserdata */
207 luaL_checktype(L, 1, LUA_TUSERDATA);
208 if (m->absolute)
209 return m->absolute(L);
210 return m->func(L, *(char**)lua_touserdata(L, 1) + m->offset);
213 static int index_handler (lua_State *L)
215 /* stack has userdata, index */
216 lua_pushvalue(L, 2); /* dup index */
217 lua_rawget(L, lua_upvalueindex(1)); /* lookup member by name */
218 if (!lua_islightuserdata(L, -1))
220 lua_pop(L, 1); /* drop value */
221 lua_pushvalue(L, 2); /* dup index */
222 lua_gettable(L, lua_upvalueindex(2)); /* else try methods */
223 if (lua_isnil(L, -1)) /* invalid member */
224 luaL_error(L, "cannot get member '%s'", lua_tostring(L, 2));
225 return 1;
227 return Xet_call(L); /* call get function */
230 static int newindex_handler (lua_State *L)
232 /* stack has userdata, index, value */
233 lua_pushvalue(L, 2); /* dup index */
234 lua_rawget(L, lua_upvalueindex(1)); /* lookup member by name */
235 if (!lua_islightuserdata(L, -1)) /* invalid member */
236 luaL_error(L, "cannot set member '%s'", lua_tostring(L, 2));
237 return Xet_call(L); /* call set function */
240 static int
241 struct_register(lua_State *L, const char *name, const luaL_reg fn_methods[], const luaL_reg meta_methods[],
242 const struct Xet_reg setters[], const struct Xet_reg getters[])
244 int metatable, methods;
246 /* create methods table & add it to the table of globals */
247 luaL_register(L, name, fn_methods);
248 methods = lua_gettop(L);
250 /* create metatable & add it to the registry */
251 luaL_newmetatable(L, name);
252 luaL_register(L, 0, meta_methods); /* fill metatable */
254 /* To identify the type of object */
255 lua_pushstring(L, "_objname");
256 lua_pushstring(L, name);
257 lua_rawset(L, -3);
259 metatable = lua_gettop(L);
261 lua_pushliteral(L, "__metatable");
262 lua_pushvalue(L, methods); /* dup methods table*/
263 lua_rawset(L, metatable); /* hide metatable:
264 metatable.__metatable = methods */
266 lua_pushliteral(L, "__index");
267 lua_pushvalue(L, metatable); /* upvalue index 1 */
268 Xet_add(L, getters); /* fill metatable with getters */
269 lua_pushvalue(L, methods); /* upvalue index 2 */
270 lua_pushcclosure(L, index_handler, 2);
271 lua_rawset(L, metatable); /* metatable.__index = index_handler */
273 lua_pushliteral(L, "__newindex");
274 lua_newtable(L); /* table for members you can set */
275 Xet_add(L, setters); /* fill with setters */
276 lua_pushcclosure(L, newindex_handler, 1);
277 lua_rawset(L, metatable); /* metatable.__newindex = newindex_handler */
279 /* FIXME: Why do we leave an element on the stack? */
280 lua_pop(L, 1); /* drop metatable */
281 return 1; /* return methods on the stack */
284 /** }}} */
286 /** Callback {{{ */
287 PUSH_TYPE(callback, struct lua_handler)
289 CHECK_TYPE(callback, struct lua_handler)
291 static int
292 callback_unhook(lua_State *L)
294 struct lua_handler *lh = check_callback(L, 1);
295 if (!lh->listener)
297 lua_pushboolean(L, 0);
298 lua_pushstring(L, "Callback already unhooked.");
299 LuaShowErr(L);
301 else
303 if (lh->type == LUA_HANDLER_TYPE_N)
305 Free(lh->u.name);
307 else
309 luaL_unref(L, LUA_REGISTRYINDEX, lh->u.reference);
310 lh->u.reference = 0;
312 unregister_listener(lh->listener);
313 lh->listener = NULL;
314 lua_pushboolean(L, 1);
316 return 1;
319 static const luaL_reg callback_methods[] = {
320 {"unhook", callback_unhook},
321 {0, 0}
324 static const luaL_reg callback_metamethods[] = {
325 {0, 0}
328 static const struct Xet_reg callback_setters[] = {
329 {0, 0}
332 static const struct Xet_reg callback_getters[] = {
333 {0, 0}
337 /** }}} */
339 /** Window {{{ */
341 PUSH_TYPE(window, struct win)
343 CHECK_TYPE(window, struct win)
345 static int get_window(lua_State *L, void *v)
347 push_window(L, (struct win **)v);
348 return 1;
351 static int
352 window_change_title(lua_State *L)
354 struct win *w = check_window(L, 1);
355 unsigned int len;
356 const char *title = luaL_checklstring(L, 2, &len);
357 ChangeAKA(w, (char *)title, len);
358 return 0;
361 static int
362 window_get_monitor_status(lua_State *L)
364 struct win *w = check_window(L, 1);
365 int activity = luaL_checkint(L, 2);
366 if (activity)
367 /*monitor*/
368 lua_pushinteger(L, w->w_monitor != MON_OFF);
369 else
370 /*silence*/
371 lua_pushinteger(L, w->w_silence == SILENCE_ON ? w->w_silencewait: 0);
373 return 1;
376 static const luaL_reg window_methods[] = {
377 {"get_monitor_status", window_get_monitor_status},
378 {"hook", LuaRegEvent},
379 {0, 0}
382 static int
383 window_tostring(lua_State *L)
385 char str[128];
386 struct win *w = check_window(L, 1);
387 snprintf(str, sizeof(str), "{window #%d: '%s'}", w->w_number, w->w_title);
388 lua_pushstring(L, str);
389 return 1;
392 static int
393 window_equality(lua_State *L)
395 struct win *w1 = check_window(L, 1), *w2 = check_window(L, 2);
396 lua_pushboolean(L, (w1 == w2 || (w1 && w2 && w1->w_number == w2->w_number)));
397 return 1;
400 static const luaL_reg window_metamethods[] = {
401 {"__tostring", window_tostring},
402 {"__eq", window_equality},
403 {0, 0}
406 static const struct Xet_reg window_setters[] = {
407 {"title", 0, 0, window_change_title/*absolute setter*/},
408 {0, 0}
411 static const struct Xet_reg window_getters[] = {
412 {"title", get_string, offsetof(struct win, w_title) + 8},
413 {"number", get_int, offsetof(struct win, w_number)},
414 {"dir", get_string, offsetof(struct win, w_dir)},
415 {"tty", get_string, offsetof(struct win, w_tty)},
416 {"pid", get_int, offsetof(struct win, w_pid)},
417 {"group", get_window, offsetof(struct win, w_group)},
418 {"bell", get_int, offsetof(struct win, w_bell)},
419 {0, 0}
423 /** }}} */
425 /** AclUser {{{ */
427 PUSH_TYPE(user, struct acluser)
429 CHECK_TYPE(user, struct acluser)
431 static int
432 get_user(lua_State *L, void *v)
434 push_user(L, (struct acluser **)v);
435 return 1;
438 static const luaL_reg user_methods[] = {
439 {0, 0}
442 static int
443 user_tostring(lua_State *L)
445 char str[128];
446 struct acluser *u = check_user(L, 1);
447 snprintf(str, sizeof(str), "{user '%s'}", u->u_name);
448 lua_pushstring(L, str);
449 return 1;
452 static const luaL_reg user_metamethods[] = {
453 {"__tostring", user_tostring},
454 {0, 0}
457 static const struct Xet_reg user_setters[] = {
458 {0, 0}
461 static const struct Xet_reg user_getters[] = {
462 {"name", get_string, offsetof(struct acluser, u_name)},
463 {"password", get_string, offsetof(struct acluser, u_password)},
464 {0, 0}
467 /** }}} */
469 /** Canvas {{{ */
471 PUSH_TYPE(canvas, struct canvas)
473 CHECK_TYPE(canvas, struct canvas)
475 static int
476 get_canvas(lua_State *L, void *v)
478 push_canvas(L, (struct canvas **)v);
479 return 1;
482 static int
483 canvas_select(lua_State *L)
485 struct canvas *c = check_canvas(L, 1);
486 if (!display || D_forecv == c)
487 return 0;
488 SetCanvasWindow(c, Layer2Window(c->c_layer));
489 D_forecv = c;
491 /* XXX: the following all is duplicated from process.c:DoAction.
492 * Should these be in some better place?
494 ResizeCanvas(&D_canvas);
495 RecreateCanvasChain();
496 RethinkDisplayViewports();
497 ResizeLayersToCanvases(); /* redisplays */
498 fore = D_fore = Layer2Window(D_forecv->c_layer);
499 flayer = D_forecv->c_layer;
500 #ifdef RXVT_OSC
501 if (D_xtermosc[2] || D_xtermosc[3])
503 Activate(-1);
504 break;
506 #endif
507 RefreshHStatus();
508 #ifdef RXVT_OSC
509 RefreshXtermOSC();
510 #endif
511 flayer = D_forecv->c_layer;
512 CV_CALL(D_forecv, LayRestore();LaySetCursor());
513 WindowChanged(0, 'F');
514 return 1;
517 static const luaL_reg canvas_methods[] = {
518 {"select", canvas_select},
519 {0, 0}
522 static const luaL_reg canvas_metamethods[] = {
523 {0, 0}
526 static const struct Xet_reg canvas_setters[] = {
527 {0, 0}
530 static int
531 canvas_get_window(lua_State *L)
533 struct canvas *c = check_canvas(L, 1);
534 struct win *win = Layer2Window(c->c_layer);
535 if (win)
536 push_window(L, &win);
537 else
538 lua_pushnil(L);
539 return 1;
542 static const struct Xet_reg canvas_getters[] = {
543 {"next", get_canvas, offsetof(struct canvas, c_next)},
544 {"xoff", get_int, offsetof(struct canvas, c_xoff)},
545 {"yoff", get_int, offsetof(struct canvas, c_yoff)},
546 {"xs", get_int, offsetof(struct canvas, c_xs)},
547 {"ys", get_int, offsetof(struct canvas, c_ys)},
548 {"xe", get_int, offsetof(struct canvas, c_xe)},
549 {"ye", get_int, offsetof(struct canvas, c_ye)},
550 {"window", 0, 0, canvas_get_window},
551 {0, 0}
554 /** }}} */
556 /** Layout {{{ */
558 PUSH_TYPE(layout, struct layout)
559 CHECK_TYPE(layout, struct layout)
561 static const struct Xet_reg layout_getters[] = {
562 {0,0}
565 static int
566 get_layout(lua_State *L, void *v)
568 push_layout(L, (struct layout **)v);
569 return 1;
572 /** }}} */
574 /** Display {{{ */
576 PUSH_TYPE(display, struct display)
578 CHECK_TYPE(display, struct display)
580 static int
581 display_get_canvases(lua_State *L)
583 struct display *d;
584 struct canvas *iter;
585 int count;
587 d = check_display(L, 1);
588 lua_newtable(L);
589 for (iter = d->d_cvlist, count = 0; iter; iter = iter->c_next, count++) {
590 lua_pushinteger(L, count);
591 push_canvas(L, &iter);
592 lua_settable(L, -3);
595 return 1;
598 static const luaL_reg display_methods[] = {
599 {"get_canvases", display_get_canvases},
600 {0, 0}
603 static int
604 display_tostring(lua_State *L)
606 char str[128];
607 struct display *d = check_display(L, 1);
608 snprintf(str, sizeof(str), "{display: tty = '%s', term = '%s'}", d->d_usertty, d->d_termname);
609 lua_pushstring(L, str);
610 return 1;
613 static const luaL_reg display_metamethods[] = {
614 {"__tostring", display_tostring},
615 {0, 0}
618 static const struct Xet_reg display_setters[] = {
619 {0, 0}
622 static const struct Xet_reg display_getters[] = {
623 {"tty", get_string, offsetof(struct display, d_usertty)},
624 {"term", get_string, offsetof(struct display, d_termname)},
625 {"fore", get_window, offsetof(struct display, d_fore)},
626 {"other", get_window, offsetof(struct display, d_other)},
627 {"width", get_int, offsetof(struct display, d_width)},
628 {"height", get_int, offsetof(struct display, d_height)},
629 {"user", get_user, offsetof(struct display, d_user)},
630 {"layout", get_layout, offsetof(struct display, d_layout)},
631 {0, 0}
634 /** }}} */
636 /** Screen {{{ */
638 static int
639 screen_get_windows(lua_State *L)
641 struct win *iter;
642 int count;
644 lua_newtable(L);
645 for (iter = windows, count = 0; iter; iter = iter->w_next, count++) {
646 lua_pushinteger(L, iter->w_number);
647 push_window(L, &iter);
648 lua_settable(L, -3);
651 return 1;
654 static int
655 screen_get_displays(lua_State *L)
657 struct display *iter;
658 int count;
660 lua_newtable(L);
661 for (iter = displays, count = 0; iter; iter = iter->d_next, count++) {
662 lua_pushinteger(L, count);
663 push_display(L, &iter);
664 lua_settable(L, -3);
667 return 1;
670 static int
671 screen_get_display(lua_State *L)
673 push_display(L, &display);
674 return 1;
677 static int
678 screen_exec_command(lua_State *L)
680 const char *command;
681 unsigned int len;
683 command = luaL_checklstring(L, 1, &len);
684 if (command)
685 RcLine((char *)command, len);
687 return 0;
690 static int
691 screen_append_msg(lua_State *L)
693 const char *msg, *color;
694 unsigned int len;
695 msg = luaL_checklstring(L, 1, &len);
696 if (lua_isnil(L, 2))
697 color = NULL;
698 else
699 color = luaL_checklstring(L, 2, &len);
700 AppendWinMsgRend(msg, color);
701 return 0;
704 struct sinput_data
706 lua_State *L;
707 lua_handler lh;
709 void
710 script_input_fn(char *buf, int len, char *priv)
712 struct sinput_data *sidata = (struct sinput_data *)priv;
713 lua_handler lh = sidata->lh;
714 lua_State *L = sidata->L;
716 LuaPushHandler(L, lh);
717 lua_pushstring(L, buf);
718 if (lua_pcall(L, 1, 0, 0) == LUA_ERRRUN)
720 if(lua_isstring(L, -1))
722 LuaShowErr(L);
725 free(sidata);
726 LuaHRef(L, lh, 0);
729 static int
730 screen_input(lua_State *L)
732 char * prompt = NULL;
733 lua_handler lh;
734 struct sinput_data *sidata;
736 prompt = (char *)luaL_checkstring(L, 1);
737 lh = LuaCheckHandler(L, 2, 1);
738 sidata = (struct sinput_data *)malloc(sizeof(struct sinput_data));
739 if (!sidata)
740 luaL_error(L, "Out of Memory");
742 sidata->L = L;
743 sidata->lh = lh;
744 Input(prompt, 100, INP_COOKED, script_input_fn, (char *)sidata, 0);
746 return 0;
749 static const luaL_reg screen_methods[] = {
750 {"windows", screen_get_windows},
751 {"displays", screen_get_displays},
752 {"display", screen_get_display},
753 {"command", screen_exec_command},
754 {"append_msg", screen_append_msg},
755 {"hook", LuaRegEvent},
756 {"input", screen_input},
757 {0, 0}
760 static const luaL_reg screen_metamethods[] = {
761 {0, 0}
764 static const struct Xet_reg screen_setters[] = {
765 {0, 0}
768 static const struct Xet_reg screen_getters[] = {
769 {0, 0}
772 /** }}} */
774 /** Public functions {{{ */
776 /* FIXME: Think about this: will it affect the registered handlers?*/
777 static lua_State *L;
778 int LuaInit(void)
780 L = luaL_newstate();
782 luaL_openlibs(L);
784 #define REGISTER(X) struct_register(L, #X , X ## _methods, X##_metamethods, X##_setters, X##_getters)
786 REGISTER(screen);
787 REGISTER(window);
788 REGISTER(display);
789 REGISTER(user);
790 REGISTER(canvas);
791 REGISTER(callback);
793 /* To store handler funcs */
794 luaL_getmetatable(L, "screen");
795 /* two kinds of info in this table:
796 * _funckey[func]->key
797 * _funckey[key]->refcnt */
798 lua_pushstring(L, "_funckey");
799 lua_newtable(L);
800 lua_rawset(L, -3);
801 /* two kinds of info in this table:
802 * _keyfunc[key]->func
803 * _keyfunc[func]->name */
804 lua_pushstring(L, "_keyfunc");
805 lua_newtable(L);
806 lua_rawset(L, -3);
807 lua_pop(L, 1);
809 return 0;
812 /* An error message on top of the stack. */
813 static void
814 LuaShowErr(lua_State *L)
816 struct display *d = display;
817 unsigned int len;
818 const char *message = luaL_checklstring(L, -1, &len);
819 LMsg(0, "%s", message ? message : "Unknown error");
820 lua_pop(L, 1);
821 display = d;
824 struct fn_def
826 void (*push_fn)(lua_State *, void*);
827 void *value;
830 static int
831 LuaCallProcess(const char *name, struct fn_def defs[])
833 int argc = 0;
835 lua_getfield(L, LUA_GLOBALSINDEX, name);
836 if (lua_isnil(L, -1))
838 lua_pop(L,1);
839 return 0;
841 for (argc = 0; defs[argc].push_fn; argc++)
842 defs[argc].push_fn(L, defs[argc].value);
843 if (lua_pcall(L, argc, 0, 0) == LUA_ERRRUN && lua_isstring(L, -1))
845 LuaShowErr(L);
846 return 0;
848 return 1;
851 int LuaSource(const char *file, int async)
853 if (!L)
854 return 0;
855 struct stat st;
856 if (stat(file, &st) == -1)
857 Msg(errno, "Error loading lua script file '%s'", file);
858 else
860 int len = strlen(file);
861 if (len < 4 || strncmp(file + len - 4, ".lua", 4) != 0)
862 return 0;
863 if (luaL_dofile(L, file) && lua_isstring(L, -1))
865 LuaShowErr(L);
867 return 1;
869 return 0;
872 int LuaFinit(void)
874 if (!L)
875 return 0;
876 lua_close(L);
877 L = (lua_State*)0;
878 return 0;
882 LuaProcessCaption(const char *caption, struct win *win, int len)
884 if (!L)
885 return 0;
886 struct fn_def params[] = {
887 {lua_pushstring, caption},
888 {push_window, &win},
889 {lua_pushinteger, len},
890 {NULL, NULL}
892 return LuaCallProcess("process_caption", params);
895 static void
896 push_stringarray(lua_State *L, char **args)
898 int i;
899 lua_newtable(L);
900 for (i = 1; args && *args; i++) {
901 lua_pushinteger(L, i);
902 lua_pushstring(L, *args++);
903 lua_settable(L, -3);
908 LuaPushParams(lua_State *L, const char *params, va_list va)
910 int num = 0;
911 while (*params)
913 switch (*params)
915 case 's':
916 lua_pushstring(L, va_arg(va, char *));
917 break;
918 case 'S':
919 push_stringarray(L, va_arg(va, char **));
920 break;
921 case 'i':
922 lua_pushinteger(L, va_arg(va, int));
923 break;
924 case 'd':
926 struct display *d = va_arg(va, struct display *);
927 push_display(L, &d);
928 break;
931 params++;
932 num++;
934 return num;
937 int LuaCall(const char *func, const char **argv)
939 int argc;
940 if (!L)
941 return 0;
943 StackDump(L, "Before LuaCall\n");
944 lua_getfield(L, LUA_GLOBALSINDEX, func);
945 if (lua_isnil(L, -1))
947 lua_pop(L, 1);
948 lua_pushstring(L, "Could not find the script function\n");
949 LuaShowErr(L);
950 return 0;
952 for (argc = 0; *argv; argv++, argc++)
954 lua_pushstring(L, *argv);
956 if (lua_pcall(L, argc, 0, 0) == LUA_ERRRUN)
958 if(lua_isstring(L, -1))
960 StackDump(L, "After LuaCall\n");
961 LuaShowErr(L);
962 return 0;
965 return 1;
968 /*** Lua callback handler management {{{ */
971 LuaPushHTable(lua_State *L, int screen, const char * t)
973 lua_pushstring(L, t);
974 lua_rawget(L, screen);
975 /* FIXME: Do we need to balance the stack here? */
976 if (lua_isnil(L, -1))
977 luaL_error(L, "Fatal! Fail to get function registeration table!");
978 return lua_gettop(L);
981 void
982 LuaPushHandler(lua_State *L, lua_handler lh)
984 int keyfunc;
985 luaL_getmetatable(L, "screen");
986 keyfunc = LuaPushHTable(L, lua_gettop(L), "_keyfunc");
987 lua_rawgeti(L, keyfunc, lh);
988 lua_replace(L, -3);
989 lua_pop(L, 1);
992 void
993 LuaHRef(lua_State *L, int key, int reg)
995 int funckey, keyfunc, cnt, sc, idx;
996 luaL_getmetatable(L, "screen");
997 sc = lua_gettop(L);
998 funckey = LuaPushHTable(L, sc, "_funckey");
999 keyfunc = LuaPushHTable(L, sc, "_keyfunc");
1001 lua_rawgeti(L, keyfunc, key);
1002 idx = lua_gettop(L);
1004 lua_rawgeti(L, funckey, key);
1005 cnt = lua_tointeger(L, -1);/*cnt = htable[key]*/
1006 if (!reg && cnt <= 1)
1008 /*release the last reference*/
1009 luaL_unref(L, funckey, key);
1010 lua_pushvalue(L, idx);
1011 lua_pushnil(L);
1012 lua_settable(L, funckey); /*htable[func]=key*/
1014 else
1016 lua_pushinteger(L, key);
1017 lua_pushinteger(L, reg? cnt + 1 : cnt - 1);
1018 lua_settable(L, funckey); /*htable[key] = cnt + 1*/
1020 lua_pop(L, 5);
1023 /* Ref when asked to. Never unref*/
1025 LuaFuncKey(lua_State *L, int idx, int ref)
1027 int key, funckey, sc;
1028 luaL_getmetatable(L, "screen");
1029 sc = lua_gettop(L);
1030 funckey = LuaPushHTable(L, sc, "_funckey");
1032 lua_pushvalue(L, idx);
1033 lua_gettable(L, funckey);/*funckey[func] ==?*/
1034 if (lua_isnil(L, -1))
1036 /* Not found, alloc a new key */
1037 if (!ref)
1038 return LUA_NOREF;
1040 /*funckey[key] = 1*/
1041 lua_pushinteger(L, 1);
1042 key = luaL_ref(L, funckey);
1044 /*funckey[func]=key*/
1045 lua_pushvalue(L, idx);
1046 lua_pushinteger(L, key);
1047 lua_settable(L, funckey);
1049 int keyfunc = LuaPushHTable(L, sc, "_keyfunc");
1050 /*keyfunc[key] = func*/
1051 lua_pushinteger(L, key);
1052 lua_pushvalue(L, idx);
1053 lua_settable(L, keyfunc);
1055 lua_pop(L, 1);
1057 else
1059 key = lua_tointeger(L, -1);/*key = funckey[func]*/
1060 if (ref)
1061 LuaHRef(L, key, 1);
1064 lua_pop(L, 3);
1065 return key;
1068 void
1069 LuaHSetName(lua_State *L, int key, int name)
1071 int keyfunc, sc;
1072 luaL_getmetatable(L, "screen");
1073 sc = lua_gettop(L);
1074 keyfunc = LuaPushHTable(L, sc, "_keyfunc");
1076 lua_rawgeti(L, keyfunc, key);
1077 lua_pushvalue(L, name);
1078 lua_rawset(L, keyfunc);
1080 lua_pop(L, 2);
1083 /* Do not hold the return value for long */
1084 const char *
1085 LuaHGetName(lua_State *L, lua_handler key)
1087 int keyfunc, sc;
1088 const char * name;
1089 luaL_getmetatable(L, "screen");
1090 sc = lua_gettop(L);
1091 keyfunc = LuaPushHTable(L, sc, "_keyfunc");
1093 lua_rawgeti(L, keyfunc, key);
1094 lua_rawget(L, keyfunc);
1095 name = lua_tostring(L, -1);
1096 lua_pop(L, 3);
1097 return name;
1100 lua_handler
1101 LuaCheckHandler(lua_State *L, int idx, int ref)
1103 int name = 0, key;
1104 if (lua_isstring(L, idx))
1106 const char * handler;
1107 /* registered with func name.*/
1108 handler = luaL_checkstring(L, idx);
1109 name = idx++;
1110 lua_getfield(L, LUA_GLOBALSINDEX, handler);
1111 if (!lua_isfunction(L, -1))
1112 luaL_error(L, "The specified handler %s in param #%d is not a function", handler, idx);
1114 else if (!lua_isfunction(L, idx))
1115 luaL_error(L, "Handler should be a function or the name of function");
1117 key = LuaFuncKey(L, idx, ref);
1118 if (name && key != LUA_NOREF)
1120 LuaHSetName(L, key, name);
1121 lua_pop(L, 1);
1123 return LuaAllocHandler(key);
1127 LuaHdlrComp(void *h1, void *h2)
1129 return (lua_handler)h1 - (lua_handler)h2;
1132 /* }}} **/
1134 static int
1135 LuaDispatch(void *handler, const char *params, va_list va)
1137 lua_handler lh = (lua_handler)handler;
1138 int argc, retvalue;
1140 StackDump(L, "before dispatch");
1142 LuaPushHandler(L, lh);
1143 if (lua_isnil(L, -1))
1145 lua_pop(L, 1);
1146 return 0;
1148 argc = LuaPushParams(L, params, va);
1150 if (lua_pcall(L, argc, 1, 0) == LUA_ERRRUN && lua_isstring(L, -1))
1152 StackDump(L, "After LuaDispatch\n");
1153 LuaShowErr(L);
1154 return 0;
1156 retvalue = lua_tonumber(L, -1);
1157 lua_pop(L, 1);
1158 return retvalue;
1161 int LuaForeWindowChanged(void)
1163 struct fn_def params[] = {
1164 {push_display, &display},
1165 {push_window, display ? &D_fore : &fore},
1166 {NULL, NULL}
1168 if (!L)
1169 return 0;
1170 return LuaCallProcess("fore_changed", params);
1173 #define SEVNAME_MAX 30
1174 static int
1175 LuaRegEvent(lua_State *L)
1177 /* signature: hook(obj, event, handler, priv);
1178 * or: hook(event, handler, priv)
1179 * returns: A ticket for later unregister. */
1180 int idx = 1, argc = lua_gettop(L);
1181 unsigned int priv = 31; /* Default privilege */
1182 lua_handler lh;
1184 char *obj = NULL;
1185 const char *objname = "global";
1187 static char evbuf[SEVNAME_MAX];
1188 const char *event;
1190 struct script_event *sev;
1192 StackDump(L, "Before RegEvent\n");
1194 /* Identify the object, if specified */
1195 if (luaL_getmetafield(L, 1, "_objname"))
1197 objname = luaL_checkstring(L, -1);
1198 lua_pop(L, 1);
1199 if (!strcmp("screen", objname))
1200 objname = "global";
1201 else
1202 obj = *(char **)lua_touserdata(L, 1);
1203 idx++;
1206 event = luaL_checkstring(L, idx++);
1207 snprintf(evbuf, SEVNAME_MAX, "%s_%s", objname, event);
1209 /* Check and get the handler */
1210 lh = LuaCheckHandler(L, idx++, 1);
1211 if (!lh)
1212 luaL_error(L, "Out of memory");
1214 StackDump(L, "In RegEvent\n");
1216 if (idx <= argc)
1217 priv = luaL_checkinteger(L, idx);
1219 sev = object_get_event(obj, evbuf);
1220 if (sev)
1222 struct listener *l;
1223 l = (struct listener *)malloc(sizeof(struct listener));
1224 if (!l)
1225 return luaL_error(L, "Out of memory");
1226 l->priv = priv;
1227 l->bd = &lua_binding;
1228 l->handler = (void *)lh;
1229 if (register_listener(sev, l))
1231 const char *fname = LuaHGetName(L, lh);
1232 free(l);
1233 if (fname)
1234 return luaL_error(L, "Handler %s has already been registered", fname);
1235 else
1236 return luaL_error(L, "Handler has already been registered");
1238 /* Return the handler for un-register */
1239 l->handler = lua_newuserdata(L, sizeof(struct lua_handler));
1240 memcpy(l->handler, &lh, sizeof(struct lua_handler));
1241 ((struct lua_handler *)l->handler)->listener = l;
1242 push_callback(L, &l->handler);
1244 else
1245 return luaL_error(L, "Invalid event specified: %s for object %s", event, objname);
1247 StackDump(L, "After RegEvent\n");
1248 return 1;
1251 static int
1252 LuaUnRegEvent(lua_State *L)
1254 /* signature: unhook([obj], ticket)
1255 * returns: true of success, false otherwise */
1256 int idx = 1;
1257 struct listener *l;
1258 lua_handler lh;
1260 /* If the param is not as expected */
1261 if (!lua_islightuserdata(L, idx))
1263 /* Then it should be the userdata to be ignore, but if not ... */
1264 if (!lua_isuserdata(L, idx))
1265 luaL_checktype(L, idx, LUA_TLIGHTUSERDATA);
1266 idx++;
1267 luaL_checktype(L, idx, LUA_TLIGHTUSERDATA);
1270 l = (struct listener*)lua_touserdata(L, idx++);
1271 /* the handler is used to validate the ticket.
1272 * This is important, otherwise double unhook can crash screen. */
1273 lh = LuaCheckHandler(L, idx, 0);
1275 /* Validate the listener structure */
1276 if (lh == LUA_NOREF || !l || !l->handler)
1278 /* invalid */
1279 lua_pushboolean(L,0);
1281 else
1283 LuaHRef(L, (lua_handler)l->handler, 0);
1284 LuaFreeHandler(((lua_handler)&(l->handler)));
1285 unregister_listener(l);
1286 lua_pushboolean(L, 1);
1289 return 1;
1292 /** }}} */
1294 struct ScriptFuncs LuaFuncs =
1296 LuaForeWindowChanged,
1297 LuaProcessCaption
1300 struct binding lua_binding =
1302 "lua", /*name*/
1303 0, /*inited*/
1304 0, /*registered*/
1305 LuaInit,
1306 LuaFinit,
1307 LuaCall,
1308 LuaSource,
1309 LuaDispatch,
1310 LuaHdlrComp,
1311 0, /*b_next*/
1312 &LuaFuncs