Fix an memory leak on unhook ticket.
[screen-lua.git] / src / lua.c
blob332c5997e5540fb2f8ec6dc3f0602009480ee515
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;
80 extern void AppendWinMsgRend(const char *str, const char *color);
82 static int LuaDispatch(void *handler, const char *params, va_list va);
83 static int LuaRegEvent(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 const char *name;
99 int reference;
100 } u;
101 struct listener *listener;
104 typedef struct lua_handler *lua_handler;
105 void LuaPushHandler(lua_State *L, lua_handler lh);
106 void LuaHRef(lua_State *L, int key, int reg);
107 lua_handler LuaCheckHandler(lua_State *L, int idx, int ref);
109 lua_handler
110 LuaAllocHandler(const char *name, int ref)
112 struct lua_handler *lh;
113 lh = (struct lua_handler*) malloc(sizeof(struct lua_handler));
114 if (!lh)
115 return NULL;
117 if (name)
119 lh->type = LUA_HANDLER_TYPE_N;
120 lh->u.name = name;
122 else
124 lh->type = LUA_HANDLER_TYPE_F;
125 lh->u.reference = ref;
128 return lh;
131 void
132 LuaFreeHandler(lua_State *L, struct lua_handler **lh)
134 if ((*lh)->type == LUA_HANDLER_TYPE_N)
135 Free((*lh)->u.name)
136 else
138 LuaHRef(L, (*lh)->u.reference, 0);
139 (*lh)->u.reference = 0;
141 Free(*lh);
143 /** Template {{{ */
145 #define CHECK_TYPE(name, type) \
146 static type * \
147 check_##name(lua_State *L, int index) \
149 type **var; \
150 luaL_checktype(L, index, LUA_TUSERDATA); \
151 var = (type **) luaL_checkudata(L, index, #name); \
152 if (!var || !*var) \
153 luaL_typerror(L, index, #name); \
154 return *var; \
157 #define PUSH_TYPE(name, type) \
158 static void \
159 push_##name(lua_State *L, type **t) \
161 if (!t || !*t) \
162 lua_pushnil(L); \
163 else \
165 type **r; \
166 r = (type **)lua_newuserdata(L, sizeof(type *)); \
167 *r = *t; \
168 luaL_getmetatable(L, #name); \
169 lua_setmetatable(L,-2); \
173 /* Much of the following template comes from:
174 * http://lua-users.org/wiki/BindingWithMembersAndMethods
177 static int get_int (lua_State *L, void *v)
179 lua_pushinteger (L, *(int*)v);
180 return 1;
183 static int set_int (lua_State *L, void *v)
185 *(int*)v = luaL_checkint(L, 3);
186 return 0;
189 static int get_number (lua_State *L, void *v)
191 lua_pushnumber(L, *(lua_Number*)v);
192 return 1;
195 static int set_number (lua_State *L, void *v)
197 *(lua_Number*)v = luaL_checknumber(L, 3);
198 return 0;
201 static int get_string (lua_State *L, void *v)
203 lua_pushstring(L, (char*)v );
204 return 1;
207 static int set_string (lua_State *L, void *v)
209 *(const char**)v = luaL_checkstring(L, 3);
210 return 0;
213 typedef int (*Xet_func) (lua_State *L, void *v);
215 /* member info for get and set handlers */
216 struct Xet_reg
218 const char *name; /* member name */
219 Xet_func func; /* get or set function for type of member */
220 size_t offset; /* offset of member within the struct */
221 int (*absolute)(lua_State *);
224 static void Xet_add (lua_State *L, const struct Xet_reg *l)
226 if (!l)
227 return;
228 for (; l->name; l++)
230 lua_pushstring(L, l->name);
231 lua_pushlightuserdata(L, (void*)l);
232 lua_settable(L, -3);
236 static int Xet_call (lua_State *L)
238 /* for get: stack has userdata, index, lightuserdata */
239 /* for set: stack has userdata, index, value, lightuserdata */
240 const struct Xet_reg *m = (const struct Xet_reg *)lua_touserdata(L, -1); /* member info */
241 lua_pop(L, 1); /* drop lightuserdata */
242 luaL_checktype(L, 1, LUA_TUSERDATA);
243 if (m->absolute)
244 return m->absolute(L);
245 return m->func(L, *(char**)lua_touserdata(L, 1) + m->offset);
248 static int index_handler (lua_State *L)
250 /* stack has userdata, index */
251 lua_pushvalue(L, 2); /* dup index */
252 lua_rawget(L, lua_upvalueindex(1)); /* lookup member by name */
253 if (!lua_islightuserdata(L, -1))
255 lua_pop(L, 1); /* drop value */
256 lua_pushvalue(L, 2); /* dup index */
257 lua_gettable(L, lua_upvalueindex(2)); /* else try methods */
258 if (lua_isnil(L, -1)) /* invalid member */
259 luaL_error(L, "cannot get member '%s'", lua_tostring(L, 2));
260 return 1;
262 return Xet_call(L); /* call get function */
265 static int newindex_handler (lua_State *L)
267 /* stack has userdata, index, value */
268 lua_pushvalue(L, 2); /* dup index */
269 lua_rawget(L, lua_upvalueindex(1)); /* lookup member by name */
270 if (!lua_islightuserdata(L, -1)) /* invalid member */
271 luaL_error(L, "cannot set member '%s'", lua_tostring(L, 2));
272 return Xet_call(L); /* call set function */
275 static int
276 struct_register(lua_State *L, const char *name, const luaL_reg fn_methods[], const luaL_reg meta_methods[],
277 const struct Xet_reg setters[], const struct Xet_reg getters[])
279 int metatable, methods;
281 /* create methods table & add it to the table of globals */
282 luaL_register(L, name, fn_methods);
283 methods = lua_gettop(L);
285 /* create metatable & add it to the registry */
286 luaL_newmetatable(L, name);
287 luaL_register(L, 0, meta_methods); /* fill metatable */
289 /* To identify the type of object */
290 lua_pushstring(L, "_objname");
291 lua_pushstring(L, name);
292 lua_rawset(L, -3);
294 metatable = lua_gettop(L);
296 lua_pushliteral(L, "__metatable");
297 lua_pushvalue(L, methods); /* dup methods table*/
298 lua_rawset(L, metatable); /* hide metatable:
299 metatable.__metatable = methods */
301 lua_pushliteral(L, "__index");
302 lua_pushvalue(L, metatable); /* upvalue index 1 */
303 Xet_add(L, getters); /* fill metatable with getters */
304 lua_pushvalue(L, methods); /* upvalue index 2 */
305 lua_pushcclosure(L, index_handler, 2);
306 lua_rawset(L, metatable); /* metatable.__index = index_handler */
308 lua_pushliteral(L, "__newindex");
309 lua_newtable(L); /* table for members you can set */
310 Xet_add(L, setters); /* fill with setters */
311 lua_pushcclosure(L, newindex_handler, 1);
312 lua_rawset(L, metatable); /* metatable.__newindex = newindex_handler */
314 /* FIXME: Why do we leave an element on the stack? */
315 lua_pop(L, 1); /* drop metatable */
316 return 1; /* return methods on the stack */
319 /** }}} */
321 /** Callback {{{ */
322 PUSH_TYPE(callback, struct lua_handler)
324 CHECK_TYPE(callback, struct lua_handler)
326 static int
327 callback_unhook(lua_State *L)
329 struct lua_handler *lh = check_callback(L, 1);
330 if (!lh->listener)
332 lua_pushboolean(L, 0);
333 lua_pushstring(L, "Callback already unhooked.");
334 LuaShowErr(L);
336 else
338 if (lh->type == LUA_HANDLER_TYPE_N)
340 Free(lh->u.name);
342 else
344 LuaHRef(L, lh->u.reference, 0);
345 lh->u.reference = 0;
347 unregister_listener(lh->listener);
348 lh->listener = NULL;
349 lua_pushboolean(L, 1);
351 return 1;
354 static const luaL_reg callback_methods[] = {
355 {"unhook", callback_unhook},
356 {0, 0}
360 callback_gc(lua_State *L)
362 lua_handler lh = check_callback(L, 1);
363 /* If the callback is not unhooked, we can not reclaim this memory since
364 * it's still used by the event dispatcher */
365 if (lh->listener)
366 LuaFreeHandler(L, &lh);
368 return 0;
371 static const luaL_reg callback_metamethods[] = {
372 {"__gc", callback_gc},
373 {0, 0}
376 static const struct Xet_reg callback_setters[] = {
377 {0, 0}
380 static const struct Xet_reg callback_getters[] = {
381 {0, 0}
385 /** }}} */
387 /** Window {{{ */
389 PUSH_TYPE(window, struct win)
391 CHECK_TYPE(window, struct win)
393 static int get_window(lua_State *L, void *v)
395 push_window(L, (struct win **)v);
396 return 1;
399 static int
400 window_change_title(lua_State *L)
402 struct win *w = check_window(L, 1);
403 unsigned int len;
404 const char *title = luaL_checklstring(L, 2, &len);
405 ChangeAKA(w, (char *)title, len);
406 return 0;
409 static int
410 window_get_monitor_status(lua_State *L)
412 struct win *w = check_window(L, 1);
413 int activity = luaL_checkint(L, 2);
414 if (activity)
415 /*monitor*/
416 lua_pushinteger(L, w->w_monitor != MON_OFF);
417 else
418 /*silence*/
419 lua_pushinteger(L, w->w_silence == SILENCE_ON ? w->w_silencewait: 0);
421 return 1;
424 static const luaL_reg window_methods[] = {
425 {"get_monitor_status", window_get_monitor_status},
426 {"hook", LuaRegEvent},
427 {0, 0}
430 static int
431 window_tostring(lua_State *L)
433 char str[128];
434 struct win *w = check_window(L, 1);
435 snprintf(str, sizeof(str), "{window #%d: '%s'}", w->w_number, w->w_title);
436 lua_pushstring(L, str);
437 return 1;
440 static int
441 window_equality(lua_State *L)
443 struct win *w1 = check_window(L, 1), *w2 = check_window(L, 2);
444 lua_pushboolean(L, (w1 == w2 || (w1 && w2 && w1->w_number == w2->w_number)));
445 return 1;
448 static const luaL_reg window_metamethods[] = {
449 {"__tostring", window_tostring},
450 {"__eq", window_equality},
451 {0, 0}
454 static const struct Xet_reg window_setters[] = {
455 {"title", 0, 0, window_change_title/*absolute setter*/},
456 {0, 0}
459 static const struct Xet_reg window_getters[] = {
460 {"title", get_string, offsetof(struct win, w_title) + 8},
461 {"number", get_int, offsetof(struct win, w_number)},
462 {"dir", get_string, offsetof(struct win, w_dir)},
463 {"tty", get_string, offsetof(struct win, w_tty)},
464 {"pid", get_int, offsetof(struct win, w_pid)},
465 {"group", get_window, offsetof(struct win, w_group)},
466 {"bell", get_int, offsetof(struct win, w_bell)},
467 {0, 0}
471 /** }}} */
473 /** AclUser {{{ */
475 PUSH_TYPE(user, struct acluser)
477 CHECK_TYPE(user, struct acluser)
479 static int
480 get_user(lua_State *L, void *v)
482 push_user(L, (struct acluser **)v);
483 return 1;
486 static const luaL_reg user_methods[] = {
487 {0, 0}
490 static int
491 user_tostring(lua_State *L)
493 char str[128];
494 struct acluser *u = check_user(L, 1);
495 snprintf(str, sizeof(str), "{user '%s'}", u->u_name);
496 lua_pushstring(L, str);
497 return 1;
500 static const luaL_reg user_metamethods[] = {
501 {"__tostring", user_tostring},
502 {0, 0}
505 static const struct Xet_reg user_setters[] = {
506 {0, 0}
509 static const struct Xet_reg user_getters[] = {
510 {"name", get_string, offsetof(struct acluser, u_name)},
511 {"password", get_string, offsetof(struct acluser, u_password)},
512 {0, 0}
515 /** }}} */
517 /** Canvas {{{ */
519 PUSH_TYPE(canvas, struct canvas)
521 CHECK_TYPE(canvas, struct canvas)
523 static int
524 get_canvas(lua_State *L, void *v)
526 push_canvas(L, (struct canvas **)v);
527 return 1;
530 static int
531 canvas_select(lua_State *L)
533 struct canvas *c = check_canvas(L, 1);
534 if (!display || D_forecv == c)
535 return 0;
536 SetCanvasWindow(c, Layer2Window(c->c_layer));
537 D_forecv = c;
539 /* XXX: the following all is duplicated from process.c:DoAction.
540 * Should these be in some better place?
542 ResizeCanvas(&D_canvas);
543 RecreateCanvasChain();
544 RethinkDisplayViewports();
545 ResizeLayersToCanvases(); /* redisplays */
546 fore = D_fore = Layer2Window(D_forecv->c_layer);
547 flayer = D_forecv->c_layer;
548 #ifdef RXVT_OSC
549 if (D_xtermosc[2] || D_xtermosc[3])
551 Activate(-1);
552 break;
554 #endif
555 RefreshHStatus();
556 #ifdef RXVT_OSC
557 RefreshXtermOSC();
558 #endif
559 flayer = D_forecv->c_layer;
560 CV_CALL(D_forecv, LayRestore();LaySetCursor());
561 WindowChanged(0, 'F');
562 return 1;
565 static const luaL_reg canvas_methods[] = {
566 {"select", canvas_select},
567 {0, 0}
570 static const luaL_reg canvas_metamethods[] = {
571 {0, 0}
574 static const struct Xet_reg canvas_setters[] = {
575 {0, 0}
578 static int
579 canvas_get_window(lua_State *L)
581 struct canvas *c = check_canvas(L, 1);
582 struct win *win = Layer2Window(c->c_layer);
583 if (win)
584 push_window(L, &win);
585 else
586 lua_pushnil(L);
587 return 1;
590 static const struct Xet_reg canvas_getters[] = {
591 {"next", get_canvas, offsetof(struct canvas, c_next)},
592 {"xoff", get_int, offsetof(struct canvas, c_xoff)},
593 {"yoff", get_int, offsetof(struct canvas, c_yoff)},
594 {"xs", get_int, offsetof(struct canvas, c_xs)},
595 {"ys", get_int, offsetof(struct canvas, c_ys)},
596 {"xe", get_int, offsetof(struct canvas, c_xe)},
597 {"ye", get_int, offsetof(struct canvas, c_ye)},
598 {"window", 0, 0, canvas_get_window},
599 {0, 0}
602 /** }}} */
604 /** Layout {{{ */
606 PUSH_TYPE(layout, struct layout)
607 CHECK_TYPE(layout, struct layout)
609 static const struct Xet_reg layout_getters[] = {
610 {0,0}
613 static int
614 get_layout(lua_State *L, void *v)
616 push_layout(L, (struct layout **)v);
617 return 1;
620 /** }}} */
622 /** Display {{{ */
624 PUSH_TYPE(display, struct display)
626 CHECK_TYPE(display, struct display)
628 static int
629 display_get_canvases(lua_State *L)
631 struct display *d;
632 struct canvas *iter;
633 int count;
635 d = check_display(L, 1);
636 lua_newtable(L);
637 for (iter = d->d_cvlist, count = 0; iter; iter = iter->c_next, count++) {
638 lua_pushinteger(L, count);
639 push_canvas(L, &iter);
640 lua_settable(L, -3);
643 return 1;
646 static const luaL_reg display_methods[] = {
647 {"get_canvases", display_get_canvases},
648 {0, 0}
651 static int
652 display_tostring(lua_State *L)
654 char str[128];
655 struct display *d = check_display(L, 1);
656 snprintf(str, sizeof(str), "{display: tty = '%s', term = '%s'}", d->d_usertty, d->d_termname);
657 lua_pushstring(L, str);
658 return 1;
661 static const luaL_reg display_metamethods[] = {
662 {"__tostring", display_tostring},
663 {0, 0}
666 static const struct Xet_reg display_setters[] = {
667 {0, 0}
670 static const struct Xet_reg display_getters[] = {
671 {"tty", get_string, offsetof(struct display, d_usertty)},
672 {"term", get_string, offsetof(struct display, d_termname)},
673 {"fore", get_window, offsetof(struct display, d_fore)},
674 {"other", get_window, offsetof(struct display, d_other)},
675 {"width", get_int, offsetof(struct display, d_width)},
676 {"height", get_int, offsetof(struct display, d_height)},
677 {"user", get_user, offsetof(struct display, d_user)},
678 {"layout", get_layout, offsetof(struct display, d_layout)},
679 {0, 0}
682 /** }}} */
684 /** Screen {{{ */
686 static int
687 screen_get_windows(lua_State *L)
689 struct win *iter;
690 int count;
692 lua_newtable(L);
693 for (iter = windows, count = 0; iter; iter = iter->w_next, count++) {
694 lua_pushinteger(L, iter->w_number);
695 push_window(L, &iter);
696 lua_settable(L, -3);
699 return 1;
702 static int
703 screen_get_displays(lua_State *L)
705 struct display *iter;
706 int count;
708 lua_newtable(L);
709 for (iter = displays, count = 0; iter; iter = iter->d_next, count++) {
710 lua_pushinteger(L, count);
711 push_display(L, &iter);
712 lua_settable(L, -3);
715 return 1;
718 static int
719 screen_get_display(lua_State *L)
721 push_display(L, &display);
722 return 1;
725 static int
726 screen_exec_command(lua_State *L)
728 const char *command;
729 unsigned int len;
731 command = luaL_checklstring(L, 1, &len);
732 if (command)
733 RcLine((char *)command, len);
735 return 0;
738 static int
739 screen_append_msg(lua_State *L)
741 const char *msg, *color;
742 unsigned int len;
743 msg = luaL_checklstring(L, 1, &len);
744 if (lua_isnil(L, 2))
745 color = NULL;
746 else
747 color = luaL_checklstring(L, 2, &len);
748 AppendWinMsgRend(msg, color);
749 return 0;
752 struct sinput_data
754 lua_State *L;
755 lua_handler lh;
758 void
759 script_input_fn(char *buf, int len, char *priv)
761 struct sinput_data *sidata = (struct sinput_data *)priv;
762 lua_handler lh = sidata->lh;
763 lua_State *L = sidata->L;
765 LuaPushHandler(L, lh);
766 lua_pushstring(L, buf);
767 if (lua_pcall(L, 1, 0, 0) == LUA_ERRRUN)
769 if(lua_isstring(L, -1))
771 LuaShowErr(L);
774 free(sidata);
775 LuaFreeHandler(L, &lh);
778 static int
779 screen_input(lua_State *L)
781 char * prompt = NULL;
782 lua_handler lh;
783 struct sinput_data *sidata;
785 prompt = (char *)luaL_checkstring(L, 1);
786 lh = LuaCheckHandler(L, 2, 1);
787 sidata = (struct sinput_data *)malloc(sizeof(struct sinput_data));
788 if (!sidata)
789 luaL_error(L, "Out of Memory");
791 sidata->L = L;
792 sidata->lh = lh;
793 Input(prompt, 100, INP_COOKED, script_input_fn, (char *)sidata, 0);
795 return 0;
798 static const luaL_reg screen_methods[] = {
799 {"windows", screen_get_windows},
800 {"displays", screen_get_displays},
801 {"display", screen_get_display},
802 {"command", screen_exec_command},
803 {"append_msg", screen_append_msg},
804 {"hook", LuaRegEvent},
805 {"input", screen_input},
806 {0, 0}
809 static const luaL_reg screen_metamethods[] = {
810 {0, 0}
813 static const struct Xet_reg screen_setters[] = {
814 {0, 0}
817 static const struct Xet_reg screen_getters[] = {
818 {0, 0}
821 /** }}} */
823 /** Public functions {{{ */
825 /* FIXME: Think about this: will it affect the registered handlers?*/
826 static lua_State *L;
827 int LuaInit(void)
829 L = luaL_newstate();
831 luaL_openlibs(L);
833 #define REGISTER(X) struct_register(L, #X , X ## _methods, X##_metamethods, X##_setters, X##_getters)
835 REGISTER(screen);
836 REGISTER(window);
837 REGISTER(display);
838 REGISTER(user);
839 REGISTER(canvas);
840 REGISTER(callback);
842 /* To store handler funcs */
843 luaL_getmetatable(L, "screen");
844 /* two kinds of info in this table:
845 * _funckey[func]->key
846 * _funckey[key]->refcnt */
847 lua_pushstring(L, "_funckey");
848 lua_newtable(L);
849 lua_rawset(L, -3);
850 /* two kinds of info in this table:
851 * _keyfunc[key]->func */
852 lua_pushstring(L, "_keyfunc");
853 lua_newtable(L);
854 lua_rawset(L, -3);
855 lua_pop(L, 1);
857 return 0;
860 /* An error message on top of the stack. */
861 static void
862 LuaShowErr(lua_State *L)
864 struct display *d = display;
865 unsigned int len;
866 const char *message = luaL_checklstring(L, -1, &len);
867 LMsg(0, "%s", message ? message : "Unknown error");
868 lua_pop(L, 1);
869 display = d;
872 struct fn_def
874 void (*push_fn)(lua_State *, void*);
875 void *value;
878 static int
879 LuaCallProcess(const char *name, struct fn_def defs[])
881 int argc = 0;
883 lua_getfield(L, LUA_GLOBALSINDEX, name);
884 if (lua_isnil(L, -1))
886 lua_pop(L,1);
887 return 0;
889 for (argc = 0; defs[argc].push_fn; argc++)
890 defs[argc].push_fn(L, defs[argc].value);
891 if (lua_pcall(L, argc, 0, 0) == LUA_ERRRUN && lua_isstring(L, -1))
893 LuaShowErr(L);
894 return 0;
896 return 1;
899 int LuaSource(const char *file, int async)
901 if (!L)
902 return 0;
903 struct stat st;
904 if (stat(file, &st) == -1)
905 Msg(errno, "Error loading lua script file '%s'", file);
906 else
908 int len = strlen(file);
909 if (len < 4 || strncmp(file + len - 4, ".lua", 4) != 0)
910 return 0;
911 if (luaL_dofile(L, file) && lua_isstring(L, -1))
913 LuaShowErr(L);
914 return 0;
916 return 1;
918 return 0;
921 int LuaFinit(void)
923 if (!L)
924 return 0;
925 lua_close(L);
926 L = (lua_State*)0;
927 return 0;
931 LuaProcessCaption(const char *caption, struct win *win, int len)
933 if (!L)
934 return 0;
935 struct fn_def params[] = {
936 {lua_pushstring, caption},
937 {push_window, &win},
938 {lua_pushinteger, len},
939 {NULL, NULL}
941 return LuaCallProcess("process_caption", params);
944 static void
945 push_stringarray(lua_State *L, char **args)
947 int i;
948 lua_newtable(L);
949 for (i = 1; args && *args; i++) {
950 lua_pushinteger(L, i);
951 lua_pushstring(L, *args++);
952 lua_settable(L, -3);
957 LuaPushParams(lua_State *L, const char *params, va_list va)
959 int num = 0;
960 while (*params)
962 switch (*params)
964 case 's':
965 lua_pushstring(L, va_arg(va, char *));
966 break;
967 case 'S':
968 push_stringarray(L, va_arg(va, char **));
969 break;
970 case 'i':
971 lua_pushinteger(L, va_arg(va, int));
972 break;
973 case 'd':
975 struct display *d = va_arg(va, struct display *);
976 push_display(L, &d);
977 break;
980 params++;
981 num++;
983 return num;
986 int LuaCall(const char *func, const char **argv)
988 int argc;
989 if (!L)
990 return 0;
992 StackDump(L, "Before LuaCall\n");
993 lua_getfield(L, LUA_GLOBALSINDEX, func);
994 if (lua_isnil(L, -1))
996 lua_pop(L, 1);
997 lua_pushstring(L, "Could not find the script function\n");
998 LuaShowErr(L);
999 return 0;
1001 for (argc = 0; *argv; argv++, argc++)
1003 lua_pushstring(L, *argv);
1005 if (lua_pcall(L, argc, 0, 0) == LUA_ERRRUN)
1007 if(lua_isstring(L, -1))
1009 StackDump(L, "After LuaCall\n");
1010 LuaShowErr(L);
1011 return 0;
1014 return 1;
1017 /*** Lua callback handler management {{{ */
1020 LuaPushHTable(lua_State *L, int screen, const char * t)
1022 lua_pushstring(L, t);
1023 lua_rawget(L, screen);
1024 /* FIXME: Do we need to balance the stack here? */
1025 if (lua_isnil(L, -1))
1026 luaL_error(L, "Fatal! Fail to get function registeration table!");
1027 return lua_gettop(L);
1030 void
1031 LuaPushHandler(lua_State *L, lua_handler lh)
1033 int keyfunc;
1034 if (lh->type == LUA_HANDLER_TYPE_F)
1036 luaL_getmetatable(L, "screen");
1037 keyfunc = LuaPushHTable(L, lua_gettop(L), "_keyfunc");
1038 lua_rawgeti(L, keyfunc, lh->u.reference);
1039 lua_replace(L, -3);
1040 lua_pop(L, 1);
1042 else
1044 lua_getfield(L, LUA_GLOBALSINDEX, lh->u.name);
1048 void
1049 LuaHRef(lua_State *L, int key, int reg)
1051 int funckey, keyfunc, cnt, sc, idx;
1052 luaL_getmetatable(L, "screen");
1053 sc = lua_gettop(L);
1054 funckey = LuaPushHTable(L, sc, "_funckey");
1055 keyfunc = LuaPushHTable(L, sc, "_keyfunc");
1057 lua_rawgeti(L, keyfunc, key);
1058 idx = lua_gettop(L);
1060 lua_rawgeti(L, funckey, key);
1061 cnt = lua_tointeger(L, -1);/*cnt = htable[key]*/
1062 if (!reg && cnt <= 1)
1064 /*release the last reference*/
1065 luaL_unref(L, funckey, key);
1066 lua_pushvalue(L, idx);
1067 lua_pushnil(L);
1068 lua_settable(L, funckey); /*htable[func]=key*/
1070 else
1072 lua_pushinteger(L, key);
1073 lua_pushinteger(L, reg? cnt + 1 : cnt - 1);
1074 lua_settable(L, funckey); /*htable[key] = cnt + 1*/
1076 lua_pop(L, 5);
1079 /* Ref when asked to. Never unref*/
1081 LuaFuncKey(lua_State *L, int idx, int ref)
1083 int key, funckey, sc;
1084 luaL_getmetatable(L, "screen");
1085 sc = lua_gettop(L);
1086 funckey = LuaPushHTable(L, sc, "_funckey");
1088 lua_pushvalue(L, idx);
1089 lua_gettable(L, funckey);/*funckey[func] ==?*/
1090 if (lua_isnil(L, -1))
1092 /* Not found, alloc a new key */
1093 if (!ref)
1094 return LUA_NOREF;
1096 /*funckey[key] = 1*/
1097 lua_pushinteger(L, 1);
1098 key = luaL_ref(L, funckey);
1100 /*funckey[func]=key*/
1101 lua_pushvalue(L, idx);
1102 lua_pushinteger(L, key);
1103 lua_settable(L, funckey);
1105 int keyfunc = LuaPushHTable(L, sc, "_keyfunc");
1106 /*keyfunc[key] = func*/
1107 lua_pushinteger(L, key);
1108 lua_pushvalue(L, idx);
1109 lua_settable(L, keyfunc);
1111 lua_pop(L, 1);
1113 else
1115 key = lua_tointeger(L, -1);/*key = funckey[func]*/
1116 if (ref)
1117 LuaHRef(L, key, 1);
1120 lua_pop(L, 3);
1121 return key;
1124 lua_handler
1125 LuaCheckHandler(lua_State *L, int idx, int ref)
1127 int key;
1128 if (lua_isstring(L, idx))
1130 const char * handler;
1131 /* registered with func name.*/
1132 handler = luaL_checkstring(L, idx);
1133 lua_getfield(L, LUA_GLOBALSINDEX, handler);
1134 if (!lua_isfunction(L, -1))
1135 luaL_error(L, "The specified handler %s in param #%d is not a function", handler, idx);
1136 lua_pop(L, 1);
1137 return LuaAllocHandler(handler, 0);
1139 else if (!lua_isfunction(L, idx))
1140 luaL_error(L, "Handler should be a function or the name of function");
1142 key = LuaFuncKey(L, idx, ref);
1143 return LuaAllocHandler(NULL, key);
1147 LuaHdlrComp(void *h1, void *h2)
1149 return (lua_handler)h1 - (lua_handler)h2;
1152 /* }}} **/
1154 static int
1155 LuaDispatch(void *handler, const char *params, va_list va)
1157 lua_handler lh = (lua_handler)handler;
1158 int argc, retvalue;
1160 StackDump(L, "before dispatch");
1162 LuaPushHandler(L, lh);
1163 if (lua_isnil(L, -1))
1165 lua_pop(L, 1);
1166 return 0;
1168 argc = LuaPushParams(L, params, va);
1170 if (lua_pcall(L, argc, 1, 0) == LUA_ERRRUN && lua_isstring(L, -1))
1172 StackDump(L, "After LuaDispatch\n");
1173 LuaShowErr(L);
1174 return 0;
1176 retvalue = lua_tonumber(L, -1);
1177 lua_pop(L, 1);
1178 return retvalue;
1181 int LuaForeWindowChanged(void)
1183 struct fn_def params[] = {
1184 {push_display, &display},
1185 {push_window, display ? &D_fore : &fore},
1186 {NULL, NULL}
1188 if (!L)
1189 return 0;
1190 return LuaCallProcess("fore_changed", params);
1193 #define SEVNAME_MAX 30
1194 static int
1195 LuaRegEvent(lua_State *L)
1197 /* signature: hook(obj, event, handler, priv);
1198 * or: hook(event, handler, priv)
1199 * returns: A ticket for later unregister. */
1200 int idx = 1, argc = lua_gettop(L);
1201 unsigned int priv = 31; /* Default privilege */
1202 lua_handler lh;
1204 char *obj = NULL;
1205 const char *objname = "global";
1207 static char evbuf[SEVNAME_MAX];
1208 const char *event;
1210 struct script_event *sev;
1212 StackDump(L, "Before RegEvent\n");
1214 /* Identify the object, if specified */
1215 if (luaL_getmetafield(L, 1, "_objname"))
1217 objname = luaL_checkstring(L, -1);
1218 lua_pop(L, 1);
1219 if (!strcmp("screen", objname))
1220 objname = "global";
1221 else
1222 obj = *(char **)lua_touserdata(L, 1);
1223 idx++;
1226 event = luaL_checkstring(L, idx++);
1227 snprintf(evbuf, SEVNAME_MAX, "%s_%s", objname, event);
1229 /* Check and get the handler */
1230 lh = LuaCheckHandler(L, idx++, 1);
1231 if (!lh)
1232 luaL_error(L, "Out of memory");
1234 StackDump(L, "In RegEvent\n");
1236 if (idx <= argc)
1237 priv = luaL_checkinteger(L, idx);
1239 sev = object_get_event(obj, evbuf);
1240 if (sev)
1242 struct listener *l;
1243 l = (struct listener *)malloc(sizeof(struct listener));
1244 if (!l)
1245 return luaL_error(L, "Out of memory");
1246 l->priv = priv;
1247 l->bd = &lua_binding;
1248 l->handler = (void *)lh;
1249 if (register_listener(sev, l))
1251 free(l);
1252 if (lh->type == LUA_HANDLER_TYPE_N)
1253 return luaL_error(L, "Handler %s has already been registered", lh->u.name);
1254 else
1255 return luaL_error(L, "Handler has already been registered");
1257 /* Return the handler for un-register */
1258 lh->listener = l;
1259 push_callback(L, (lua_handler *)&l->handler);
1261 else
1262 return luaL_error(L, "Invalid event specified: %s for object %s", event, objname);
1264 StackDump(L, "After RegEvent\n");
1265 return 1;
1268 /** }}} */
1270 struct ScriptFuncs LuaFuncs =
1272 LuaForeWindowChanged,
1273 LuaProcessCaption
1276 struct binding lua_binding =
1278 "lua", /*name*/
1279 0, /*inited*/
1280 0, /*registered*/
1281 LuaInit,
1282 LuaFinit,
1283 LuaCall,
1284 LuaSource,
1285 LuaDispatch,
1286 LuaHdlrComp,
1287 0, /*b_next*/
1288 &LuaFuncs