8f5a5f46c75e79f8e124a789ceda4c7befacf7e0
[screen-lua.git] / src / lua.c
blob8f5a5f46c75e79f8e124a789ceda4c7befacf7e0
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 int LuaUnRegEvent(lua_State *L);
85 static void LuaShowErr(lua_State *L);
86 struct binding lua_binding;
88 enum
90 LUA_HANDLER_TYPE_N = 1,
91 LUA_HANDLER_TYPE_F
94 struct lua_handler
96 int type;
97 union
99 const char *name;
100 int reference;
101 } u;
102 struct listener *listener;
105 typedef struct lua_handler *lua_handler;
106 void LuaPushHandler(lua_State *L, lua_handler lh);
107 void LuaHRef(lua_State *L, int key, int reg);
108 lua_handler LuaCheckHandler(lua_State *L, int idx, int ref);
110 lua_handler
111 LuaAllocHandler(const char *name, int ref)
113 struct lua_handler *lh;
114 lh = (struct lua_handler*) malloc(sizeof(struct lua_handler));
115 if (!lh)
116 return NULL;
118 if (name)
120 lh->type = LUA_HANDLER_TYPE_N;
121 lh->u.name = name;
123 else
125 lh->type = LUA_HANDLER_TYPE_F;
126 lh->u.reference = ref;
129 return lh;
132 void
133 LuaFreeHandler(lua_State *L, struct lua_handler **lh)
135 if ((*lh)->type == LUA_HANDLER_TYPE_N)
136 Free((*lh)->u.name)
137 else
139 LuaHRef(L, (*lh)->u.reference, 0);
140 (*lh)->u.reference = 0;
142 Free(*lh);
144 /** Template {{{ */
146 #define CHECK_TYPE(name, type) \
147 static type * \
148 check_##name(lua_State *L, int index) \
150 type **var; \
151 luaL_checktype(L, index, LUA_TUSERDATA); \
152 var = (type **) luaL_checkudata(L, index, #name); \
153 if (!var || !*var) \
154 luaL_typerror(L, index, #name); \
155 return *var; \
158 #define PUSH_TYPE(name, type) \
159 static void \
160 push_##name(lua_State *L, type **t) \
162 if (!t || !*t) \
163 lua_pushnil(L); \
164 else \
166 type **r; \
167 r = (type **)lua_newuserdata(L, sizeof(type *)); \
168 *r = *t; \
169 luaL_getmetatable(L, #name); \
170 lua_setmetatable(L,-2); \
174 /* Much of the following template comes from:
175 * http://lua-users.org/wiki/BindingWithMembersAndMethods
178 static int get_int (lua_State *L, void *v)
180 lua_pushinteger (L, *(int*)v);
181 return 1;
184 static int set_int (lua_State *L, void *v)
186 *(int*)v = luaL_checkint(L, 3);
187 return 0;
190 static int get_number (lua_State *L, void *v)
192 lua_pushnumber(L, *(lua_Number*)v);
193 return 1;
196 static int set_number (lua_State *L, void *v)
198 *(lua_Number*)v = luaL_checknumber(L, 3);
199 return 0;
202 static int get_string (lua_State *L, void *v)
204 lua_pushstring(L, (char*)v );
205 return 1;
208 static int set_string (lua_State *L, void *v)
210 *(const char**)v = luaL_checkstring(L, 3);
211 return 0;
214 typedef int (*Xet_func) (lua_State *L, void *v);
216 /* member info for get and set handlers */
217 struct Xet_reg
219 const char *name; /* member name */
220 Xet_func func; /* get or set function for type of member */
221 size_t offset; /* offset of member within the struct */
222 int (*absolute)(lua_State *);
225 static void Xet_add (lua_State *L, const struct Xet_reg *l)
227 if (!l)
228 return;
229 for (; l->name; l++)
231 lua_pushstring(L, l->name);
232 lua_pushlightuserdata(L, (void*)l);
233 lua_settable(L, -3);
237 static int Xet_call (lua_State *L)
239 /* for get: stack has userdata, index, lightuserdata */
240 /* for set: stack has userdata, index, value, lightuserdata */
241 const struct Xet_reg *m = (const struct Xet_reg *)lua_touserdata(L, -1); /* member info */
242 lua_pop(L, 1); /* drop lightuserdata */
243 luaL_checktype(L, 1, LUA_TUSERDATA);
244 if (m->absolute)
245 return m->absolute(L);
246 return m->func(L, *(char**)lua_touserdata(L, 1) + m->offset);
249 static int index_handler (lua_State *L)
251 /* stack has userdata, index */
252 lua_pushvalue(L, 2); /* dup index */
253 lua_rawget(L, lua_upvalueindex(1)); /* lookup member by name */
254 if (!lua_islightuserdata(L, -1))
256 lua_pop(L, 1); /* drop value */
257 lua_pushvalue(L, 2); /* dup index */
258 lua_gettable(L, lua_upvalueindex(2)); /* else try methods */
259 if (lua_isnil(L, -1)) /* invalid member */
260 luaL_error(L, "cannot get member '%s'", lua_tostring(L, 2));
261 return 1;
263 return Xet_call(L); /* call get function */
266 static int newindex_handler (lua_State *L)
268 /* stack has userdata, index, value */
269 lua_pushvalue(L, 2); /* dup index */
270 lua_rawget(L, lua_upvalueindex(1)); /* lookup member by name */
271 if (!lua_islightuserdata(L, -1)) /* invalid member */
272 luaL_error(L, "cannot set member '%s'", lua_tostring(L, 2));
273 return Xet_call(L); /* call set function */
276 static int
277 struct_register(lua_State *L, const char *name, const luaL_reg fn_methods[], const luaL_reg meta_methods[],
278 const struct Xet_reg setters[], const struct Xet_reg getters[])
280 int metatable, methods;
282 /* create methods table & add it to the table of globals */
283 luaL_register(L, name, fn_methods);
284 methods = lua_gettop(L);
286 /* create metatable & add it to the registry */
287 luaL_newmetatable(L, name);
288 luaL_register(L, 0, meta_methods); /* fill metatable */
290 /* To identify the type of object */
291 lua_pushstring(L, "_objname");
292 lua_pushstring(L, name);
293 lua_rawset(L, -3);
295 metatable = lua_gettop(L);
297 lua_pushliteral(L, "__metatable");
298 lua_pushvalue(L, methods); /* dup methods table*/
299 lua_rawset(L, metatable); /* hide metatable:
300 metatable.__metatable = methods */
302 lua_pushliteral(L, "__index");
303 lua_pushvalue(L, metatable); /* upvalue index 1 */
304 Xet_add(L, getters); /* fill metatable with getters */
305 lua_pushvalue(L, methods); /* upvalue index 2 */
306 lua_pushcclosure(L, index_handler, 2);
307 lua_rawset(L, metatable); /* metatable.__index = index_handler */
309 lua_pushliteral(L, "__newindex");
310 lua_newtable(L); /* table for members you can set */
311 Xet_add(L, setters); /* fill with setters */
312 lua_pushcclosure(L, newindex_handler, 1);
313 lua_rawset(L, metatable); /* metatable.__newindex = newindex_handler */
315 /* FIXME: Why do we leave an element on the stack? */
316 lua_pop(L, 1); /* drop metatable */
317 return 1; /* return methods on the stack */
320 /** }}} */
322 /** Callback {{{ */
323 PUSH_TYPE(callback, struct lua_handler)
325 CHECK_TYPE(callback, struct lua_handler)
327 static int
328 callback_unhook(lua_State *L)
330 struct lua_handler *lh = check_callback(L, 1);
331 if (!lh->listener)
333 lua_pushboolean(L, 0);
334 lua_pushstring(L, "Callback already unhooked.");
335 LuaShowErr(L);
337 else
339 if (lh->type == LUA_HANDLER_TYPE_N)
341 Free(lh->u.name);
343 else
345 LuaHRef(L, lh->u.reference, 0);
346 lh->u.reference = 0;
348 unregister_listener(lh->listener);
349 lh->listener = NULL;
350 lua_pushboolean(L, 1);
352 return 1;
355 static const luaL_reg callback_methods[] = {
356 {"unhook", callback_unhook},
357 {0, 0}
360 static const luaL_reg callback_metamethods[] = {
361 {0, 0}
364 static const struct Xet_reg callback_setters[] = {
365 {0, 0}
368 static const struct Xet_reg callback_getters[] = {
369 {0, 0}
373 /** }}} */
375 /** Window {{{ */
377 PUSH_TYPE(window, struct win)
379 CHECK_TYPE(window, struct win)
381 static int get_window(lua_State *L, void *v)
383 push_window(L, (struct win **)v);
384 return 1;
387 static int
388 window_change_title(lua_State *L)
390 struct win *w = check_window(L, 1);
391 unsigned int len;
392 const char *title = luaL_checklstring(L, 2, &len);
393 ChangeAKA(w, (char *)title, len);
394 return 0;
397 static int
398 window_get_monitor_status(lua_State *L)
400 struct win *w = check_window(L, 1);
401 int activity = luaL_checkint(L, 2);
402 if (activity)
403 /*monitor*/
404 lua_pushinteger(L, w->w_monitor != MON_OFF);
405 else
406 /*silence*/
407 lua_pushinteger(L, w->w_silence == SILENCE_ON ? w->w_silencewait: 0);
409 return 1;
412 static const luaL_reg window_methods[] = {
413 {"get_monitor_status", window_get_monitor_status},
414 {"hook", LuaRegEvent},
415 {0, 0}
418 static int
419 window_tostring(lua_State *L)
421 char str[128];
422 struct win *w = check_window(L, 1);
423 snprintf(str, sizeof(str), "{window #%d: '%s'}", w->w_number, w->w_title);
424 lua_pushstring(L, str);
425 return 1;
428 static int
429 window_equality(lua_State *L)
431 struct win *w1 = check_window(L, 1), *w2 = check_window(L, 2);
432 lua_pushboolean(L, (w1 == w2 || (w1 && w2 && w1->w_number == w2->w_number)));
433 return 1;
436 static const luaL_reg window_metamethods[] = {
437 {"__tostring", window_tostring},
438 {"__eq", window_equality},
439 {0, 0}
442 static const struct Xet_reg window_setters[] = {
443 {"title", 0, 0, window_change_title/*absolute setter*/},
444 {0, 0}
447 static const struct Xet_reg window_getters[] = {
448 {"title", get_string, offsetof(struct win, w_title) + 8},
449 {"number", get_int, offsetof(struct win, w_number)},
450 {"dir", get_string, offsetof(struct win, w_dir)},
451 {"tty", get_string, offsetof(struct win, w_tty)},
452 {"pid", get_int, offsetof(struct win, w_pid)},
453 {"group", get_window, offsetof(struct win, w_group)},
454 {"bell", get_int, offsetof(struct win, w_bell)},
455 {0, 0}
459 /** }}} */
461 /** AclUser {{{ */
463 PUSH_TYPE(user, struct acluser)
465 CHECK_TYPE(user, struct acluser)
467 static int
468 get_user(lua_State *L, void *v)
470 push_user(L, (struct acluser **)v);
471 return 1;
474 static const luaL_reg user_methods[] = {
475 {0, 0}
478 static int
479 user_tostring(lua_State *L)
481 char str[128];
482 struct acluser *u = check_user(L, 1);
483 snprintf(str, sizeof(str), "{user '%s'}", u->u_name);
484 lua_pushstring(L, str);
485 return 1;
488 static const luaL_reg user_metamethods[] = {
489 {"__tostring", user_tostring},
490 {0, 0}
493 static const struct Xet_reg user_setters[] = {
494 {0, 0}
497 static const struct Xet_reg user_getters[] = {
498 {"name", get_string, offsetof(struct acluser, u_name)},
499 {"password", get_string, offsetof(struct acluser, u_password)},
500 {0, 0}
503 /** }}} */
505 /** Canvas {{{ */
507 PUSH_TYPE(canvas, struct canvas)
509 CHECK_TYPE(canvas, struct canvas)
511 static int
512 get_canvas(lua_State *L, void *v)
514 push_canvas(L, (struct canvas **)v);
515 return 1;
518 static int
519 canvas_select(lua_State *L)
521 struct canvas *c = check_canvas(L, 1);
522 if (!display || D_forecv == c)
523 return 0;
524 SetCanvasWindow(c, Layer2Window(c->c_layer));
525 D_forecv = c;
527 /* XXX: the following all is duplicated from process.c:DoAction.
528 * Should these be in some better place?
530 ResizeCanvas(&D_canvas);
531 RecreateCanvasChain();
532 RethinkDisplayViewports();
533 ResizeLayersToCanvases(); /* redisplays */
534 fore = D_fore = Layer2Window(D_forecv->c_layer);
535 flayer = D_forecv->c_layer;
536 #ifdef RXVT_OSC
537 if (D_xtermosc[2] || D_xtermosc[3])
539 Activate(-1);
540 break;
542 #endif
543 RefreshHStatus();
544 #ifdef RXVT_OSC
545 RefreshXtermOSC();
546 #endif
547 flayer = D_forecv->c_layer;
548 CV_CALL(D_forecv, LayRestore();LaySetCursor());
549 WindowChanged(0, 'F');
550 return 1;
553 static const luaL_reg canvas_methods[] = {
554 {"select", canvas_select},
555 {0, 0}
558 static const luaL_reg canvas_metamethods[] = {
559 {0, 0}
562 static const struct Xet_reg canvas_setters[] = {
563 {0, 0}
566 static int
567 canvas_get_window(lua_State *L)
569 struct canvas *c = check_canvas(L, 1);
570 struct win *win = Layer2Window(c->c_layer);
571 if (win)
572 push_window(L, &win);
573 else
574 lua_pushnil(L);
575 return 1;
578 static const struct Xet_reg canvas_getters[] = {
579 {"next", get_canvas, offsetof(struct canvas, c_next)},
580 {"xoff", get_int, offsetof(struct canvas, c_xoff)},
581 {"yoff", get_int, offsetof(struct canvas, c_yoff)},
582 {"xs", get_int, offsetof(struct canvas, c_xs)},
583 {"ys", get_int, offsetof(struct canvas, c_ys)},
584 {"xe", get_int, offsetof(struct canvas, c_xe)},
585 {"ye", get_int, offsetof(struct canvas, c_ye)},
586 {"window", 0, 0, canvas_get_window},
587 {0, 0}
590 /** }}} */
592 /** Layout {{{ */
594 PUSH_TYPE(layout, struct layout)
595 CHECK_TYPE(layout, struct layout)
597 static const struct Xet_reg layout_getters[] = {
598 {0,0}
601 static int
602 get_layout(lua_State *L, void *v)
604 push_layout(L, (struct layout **)v);
605 return 1;
608 /** }}} */
610 /** Display {{{ */
612 PUSH_TYPE(display, struct display)
614 CHECK_TYPE(display, struct display)
616 static int
617 display_get_canvases(lua_State *L)
619 struct display *d;
620 struct canvas *iter;
621 int count;
623 d = check_display(L, 1);
624 lua_newtable(L);
625 for (iter = d->d_cvlist, count = 0; iter; iter = iter->c_next, count++) {
626 lua_pushinteger(L, count);
627 push_canvas(L, &iter);
628 lua_settable(L, -3);
631 return 1;
634 static const luaL_reg display_methods[] = {
635 {"get_canvases", display_get_canvases},
636 {0, 0}
639 static int
640 display_tostring(lua_State *L)
642 char str[128];
643 struct display *d = check_display(L, 1);
644 snprintf(str, sizeof(str), "{display: tty = '%s', term = '%s'}", d->d_usertty, d->d_termname);
645 lua_pushstring(L, str);
646 return 1;
649 static const luaL_reg display_metamethods[] = {
650 {"__tostring", display_tostring},
651 {0, 0}
654 static const struct Xet_reg display_setters[] = {
655 {0, 0}
658 static const struct Xet_reg display_getters[] = {
659 {"tty", get_string, offsetof(struct display, d_usertty)},
660 {"term", get_string, offsetof(struct display, d_termname)},
661 {"fore", get_window, offsetof(struct display, d_fore)},
662 {"other", get_window, offsetof(struct display, d_other)},
663 {"width", get_int, offsetof(struct display, d_width)},
664 {"height", get_int, offsetof(struct display, d_height)},
665 {"user", get_user, offsetof(struct display, d_user)},
666 {"layout", get_layout, offsetof(struct display, d_layout)},
667 {0, 0}
670 /** }}} */
672 /** Screen {{{ */
674 static int
675 screen_get_windows(lua_State *L)
677 struct win *iter;
678 int count;
680 lua_newtable(L);
681 for (iter = windows, count = 0; iter; iter = iter->w_next, count++) {
682 lua_pushinteger(L, iter->w_number);
683 push_window(L, &iter);
684 lua_settable(L, -3);
687 return 1;
690 static int
691 screen_get_displays(lua_State *L)
693 struct display *iter;
694 int count;
696 lua_newtable(L);
697 for (iter = displays, count = 0; iter; iter = iter->d_next, count++) {
698 lua_pushinteger(L, count);
699 push_display(L, &iter);
700 lua_settable(L, -3);
703 return 1;
706 static int
707 screen_get_display(lua_State *L)
709 push_display(L, &display);
710 return 1;
713 static int
714 screen_exec_command(lua_State *L)
716 const char *command;
717 unsigned int len;
719 command = luaL_checklstring(L, 1, &len);
720 if (command)
721 RcLine((char *)command, len);
723 return 0;
726 static int
727 screen_append_msg(lua_State *L)
729 const char *msg, *color;
730 unsigned int len;
731 msg = luaL_checklstring(L, 1, &len);
732 if (lua_isnil(L, 2))
733 color = NULL;
734 else
735 color = luaL_checklstring(L, 2, &len);
736 AppendWinMsgRend(msg, color);
737 return 0;
740 struct sinput_data
742 lua_State *L;
743 lua_handler lh;
746 void
747 script_input_fn(char *buf, int len, char *priv)
749 struct sinput_data *sidata = (struct sinput_data *)priv;
750 lua_handler lh = sidata->lh;
751 lua_State *L = sidata->L;
753 LuaPushHandler(L, lh);
754 lua_pushstring(L, buf);
755 if (lua_pcall(L, 1, 0, 0) == LUA_ERRRUN)
757 if(lua_isstring(L, -1))
759 LuaShowErr(L);
762 free(sidata);
763 LuaFreeHandler(L, &lh);
766 static int
767 screen_input(lua_State *L)
769 char * prompt = NULL;
770 lua_handler lh;
771 struct sinput_data *sidata;
773 prompt = (char *)luaL_checkstring(L, 1);
774 lh = LuaCheckHandler(L, 2, 1);
775 sidata = (struct sinput_data *)malloc(sizeof(struct sinput_data));
776 if (!sidata)
777 luaL_error(L, "Out of Memory");
779 sidata->L = L;
780 sidata->lh = lh;
781 Input(prompt, 100, INP_COOKED, script_input_fn, (char *)sidata, 0);
783 return 0;
786 static const luaL_reg screen_methods[] = {
787 {"windows", screen_get_windows},
788 {"displays", screen_get_displays},
789 {"display", screen_get_display},
790 {"command", screen_exec_command},
791 {"append_msg", screen_append_msg},
792 {"hook", LuaRegEvent},
793 {"input", screen_input},
794 {0, 0}
797 static const luaL_reg screen_metamethods[] = {
798 {0, 0}
801 static const struct Xet_reg screen_setters[] = {
802 {0, 0}
805 static const struct Xet_reg screen_getters[] = {
806 {0, 0}
809 /** }}} */
811 /** Public functions {{{ */
813 /* FIXME: Think about this: will it affect the registered handlers?*/
814 static lua_State *L;
815 int LuaInit(void)
817 L = luaL_newstate();
819 luaL_openlibs(L);
821 #define REGISTER(X) struct_register(L, #X , X ## _methods, X##_metamethods, X##_setters, X##_getters)
823 REGISTER(screen);
824 REGISTER(window);
825 REGISTER(display);
826 REGISTER(user);
827 REGISTER(canvas);
828 REGISTER(callback);
830 /* To store handler funcs */
831 luaL_getmetatable(L, "screen");
832 /* two kinds of info in this table:
833 * _funckey[func]->key
834 * _funckey[key]->refcnt */
835 lua_pushstring(L, "_funckey");
836 lua_newtable(L);
837 lua_rawset(L, -3);
838 /* two kinds of info in this table:
839 * _keyfunc[key]->func */
840 lua_pushstring(L, "_keyfunc");
841 lua_newtable(L);
842 lua_rawset(L, -3);
843 lua_pop(L, 1);
845 return 0;
848 /* An error message on top of the stack. */
849 static void
850 LuaShowErr(lua_State *L)
852 struct display *d = display;
853 unsigned int len;
854 const char *message = luaL_checklstring(L, -1, &len);
855 LMsg(0, "%s", message ? message : "Unknown error");
856 lua_pop(L, 1);
857 display = d;
860 struct fn_def
862 void (*push_fn)(lua_State *, void*);
863 void *value;
866 static int
867 LuaCallProcess(const char *name, struct fn_def defs[])
869 int argc = 0;
871 lua_getfield(L, LUA_GLOBALSINDEX, name);
872 if (lua_isnil(L, -1))
874 lua_pop(L,1);
875 return 0;
877 for (argc = 0; defs[argc].push_fn; argc++)
878 defs[argc].push_fn(L, defs[argc].value);
879 if (lua_pcall(L, argc, 0, 0) == LUA_ERRRUN && lua_isstring(L, -1))
881 LuaShowErr(L);
882 return 0;
884 return 1;
887 int LuaSource(const char *file, int async)
889 if (!L)
890 return 0;
891 struct stat st;
892 if (stat(file, &st) == -1)
893 Msg(errno, "Error loading lua script file '%s'", file);
894 else
896 int len = strlen(file);
897 if (len < 4 || strncmp(file + len - 4, ".lua", 4) != 0)
898 return 0;
899 if (luaL_dofile(L, file) && lua_isstring(L, -1))
901 LuaShowErr(L);
903 return 1;
905 return 0;
908 int LuaFinit(void)
910 if (!L)
911 return 0;
912 lua_close(L);
913 L = (lua_State*)0;
914 return 0;
918 LuaProcessCaption(const char *caption, struct win *win, int len)
920 if (!L)
921 return 0;
922 struct fn_def params[] = {
923 {lua_pushstring, caption},
924 {push_window, &win},
925 {lua_pushinteger, len},
926 {NULL, NULL}
928 return LuaCallProcess("process_caption", params);
931 static void
932 push_stringarray(lua_State *L, char **args)
934 int i;
935 lua_newtable(L);
936 for (i = 1; args && *args; i++) {
937 lua_pushinteger(L, i);
938 lua_pushstring(L, *args++);
939 lua_settable(L, -3);
944 LuaPushParams(lua_State *L, const char *params, va_list va)
946 int num = 0;
947 while (*params)
949 switch (*params)
951 case 's':
952 lua_pushstring(L, va_arg(va, char *));
953 break;
954 case 'S':
955 push_stringarray(L, va_arg(va, char **));
956 break;
957 case 'i':
958 lua_pushinteger(L, va_arg(va, int));
959 break;
960 case 'd':
962 struct display *d = va_arg(va, struct display *);
963 push_display(L, &d);
964 break;
967 params++;
968 num++;
970 return num;
973 int LuaCall(const char *func, const char **argv)
975 int argc;
976 if (!L)
977 return 0;
979 StackDump(L, "Before LuaCall\n");
980 lua_getfield(L, LUA_GLOBALSINDEX, func);
981 if (lua_isnil(L, -1))
983 lua_pop(L, 1);
984 lua_pushstring(L, "Could not find the script function\n");
985 LuaShowErr(L);
986 return 0;
988 for (argc = 0; *argv; argv++, argc++)
990 lua_pushstring(L, *argv);
992 if (lua_pcall(L, argc, 0, 0) == LUA_ERRRUN)
994 if(lua_isstring(L, -1))
996 StackDump(L, "After LuaCall\n");
997 LuaShowErr(L);
998 return 0;
1001 return 1;
1004 /*** Lua callback handler management {{{ */
1007 LuaPushHTable(lua_State *L, int screen, const char * t)
1009 lua_pushstring(L, t);
1010 lua_rawget(L, screen);
1011 /* FIXME: Do we need to balance the stack here? */
1012 if (lua_isnil(L, -1))
1013 luaL_error(L, "Fatal! Fail to get function registeration table!");
1014 return lua_gettop(L);
1017 void
1018 LuaPushHandler(lua_State *L, lua_handler lh)
1020 int keyfunc;
1021 if (lh->type == LUA_HANDLER_TYPE_F)
1023 luaL_getmetatable(L, "screen");
1024 keyfunc = LuaPushHTable(L, lua_gettop(L), "_keyfunc");
1025 lua_rawgeti(L, keyfunc, lh->u.reference);
1026 lua_replace(L, -3);
1027 lua_pop(L, 1);
1029 else
1031 lua_getfield(L, LUA_GLOBALSINDEX, lh->u.name);
1035 void
1036 LuaHRef(lua_State *L, int key, int reg)
1038 int funckey, keyfunc, cnt, sc, idx;
1039 luaL_getmetatable(L, "screen");
1040 sc = lua_gettop(L);
1041 funckey = LuaPushHTable(L, sc, "_funckey");
1042 keyfunc = LuaPushHTable(L, sc, "_keyfunc");
1044 lua_rawgeti(L, keyfunc, key);
1045 idx = lua_gettop(L);
1047 lua_rawgeti(L, funckey, key);
1048 cnt = lua_tointeger(L, -1);/*cnt = htable[key]*/
1049 if (!reg && cnt <= 1)
1051 /*release the last reference*/
1052 luaL_unref(L, funckey, key);
1053 lua_pushvalue(L, idx);
1054 lua_pushnil(L);
1055 lua_settable(L, funckey); /*htable[func]=key*/
1057 else
1059 lua_pushinteger(L, key);
1060 lua_pushinteger(L, reg? cnt + 1 : cnt - 1);
1061 lua_settable(L, funckey); /*htable[key] = cnt + 1*/
1063 lua_pop(L, 5);
1066 /* Ref when asked to. Never unref*/
1068 LuaFuncKey(lua_State *L, int idx, int ref)
1070 int key, funckey, sc;
1071 luaL_getmetatable(L, "screen");
1072 sc = lua_gettop(L);
1073 funckey = LuaPushHTable(L, sc, "_funckey");
1075 lua_pushvalue(L, idx);
1076 lua_gettable(L, funckey);/*funckey[func] ==?*/
1077 if (lua_isnil(L, -1))
1079 /* Not found, alloc a new key */
1080 if (!ref)
1081 return LUA_NOREF;
1083 /*funckey[key] = 1*/
1084 lua_pushinteger(L, 1);
1085 key = luaL_ref(L, funckey);
1087 /*funckey[func]=key*/
1088 lua_pushvalue(L, idx);
1089 lua_pushinteger(L, key);
1090 lua_settable(L, funckey);
1092 int keyfunc = LuaPushHTable(L, sc, "_keyfunc");
1093 /*keyfunc[key] = func*/
1094 lua_pushinteger(L, key);
1095 lua_pushvalue(L, idx);
1096 lua_settable(L, keyfunc);
1098 lua_pop(L, 1);
1100 else
1102 key = lua_tointeger(L, -1);/*key = funckey[func]*/
1103 if (ref)
1104 LuaHRef(L, key, 1);
1107 lua_pop(L, 3);
1108 return key;
1111 lua_handler
1112 LuaCheckHandler(lua_State *L, int idx, int ref)
1114 int key;
1115 if (lua_isstring(L, idx))
1117 const char * handler;
1118 /* registered with func name.*/
1119 handler = luaL_checkstring(L, idx);
1120 lua_getfield(L, LUA_GLOBALSINDEX, handler);
1121 if (!lua_isfunction(L, -1))
1122 luaL_error(L, "The specified handler %s in param #%d is not a function", handler, idx);
1123 lua_pop(L, 1);
1124 return LuaAllocHandler(handler, 0);
1126 else if (!lua_isfunction(L, idx))
1127 luaL_error(L, "Handler should be a function or the name of function");
1129 key = LuaFuncKey(L, idx, ref);
1130 return LuaAllocHandler(NULL, key);
1134 LuaHdlrComp(void *h1, void *h2)
1136 return (lua_handler)h1 - (lua_handler)h2;
1139 /* }}} **/
1141 static int
1142 LuaDispatch(void *handler, const char *params, va_list va)
1144 lua_handler lh = (lua_handler)handler;
1145 int argc, retvalue;
1147 StackDump(L, "before dispatch");
1149 LuaPushHandler(L, lh);
1150 if (lua_isnil(L, -1))
1152 lua_pop(L, 1);
1153 return 0;
1155 argc = LuaPushParams(L, params, va);
1157 if (lua_pcall(L, argc, 1, 0) == LUA_ERRRUN && lua_isstring(L, -1))
1159 StackDump(L, "After LuaDispatch\n");
1160 LuaShowErr(L);
1161 return 0;
1163 retvalue = lua_tonumber(L, -1);
1164 lua_pop(L, 1);
1165 return retvalue;
1168 int LuaForeWindowChanged(void)
1170 struct fn_def params[] = {
1171 {push_display, &display},
1172 {push_window, display ? &D_fore : &fore},
1173 {NULL, NULL}
1175 if (!L)
1176 return 0;
1177 return LuaCallProcess("fore_changed", params);
1180 #define SEVNAME_MAX 30
1181 static int
1182 LuaRegEvent(lua_State *L)
1184 /* signature: hook(obj, event, handler, priv);
1185 * or: hook(event, handler, priv)
1186 * returns: A ticket for later unregister. */
1187 int idx = 1, argc = lua_gettop(L);
1188 unsigned int priv = 31; /* Default privilege */
1189 lua_handler lh;
1191 char *obj = NULL;
1192 const char *objname = "global";
1194 static char evbuf[SEVNAME_MAX];
1195 const char *event;
1197 struct script_event *sev;
1199 StackDump(L, "Before RegEvent\n");
1201 /* Identify the object, if specified */
1202 if (luaL_getmetafield(L, 1, "_objname"))
1204 objname = luaL_checkstring(L, -1);
1205 lua_pop(L, 1);
1206 if (!strcmp("screen", objname))
1207 objname = "global";
1208 else
1209 obj = *(char **)lua_touserdata(L, 1);
1210 idx++;
1213 event = luaL_checkstring(L, idx++);
1214 snprintf(evbuf, SEVNAME_MAX, "%s_%s", objname, event);
1216 /* Check and get the handler */
1217 lh = LuaCheckHandler(L, idx++, 1);
1218 if (!lh)
1219 luaL_error(L, "Out of memory");
1221 StackDump(L, "In RegEvent\n");
1223 if (idx <= argc)
1224 priv = luaL_checkinteger(L, idx);
1226 sev = object_get_event(obj, evbuf);
1227 if (sev)
1229 struct listener *l;
1230 l = (struct listener *)malloc(sizeof(struct listener));
1231 if (!l)
1232 return luaL_error(L, "Out of memory");
1233 l->priv = priv;
1234 l->bd = &lua_binding;
1235 l->handler = (void *)lh;
1236 if (register_listener(sev, l))
1238 free(l);
1239 if (lh->type == LUA_HANDLER_TYPE_N)
1240 return luaL_error(L, "Handler %s has already been registered", lh->u.name);
1241 else
1242 return luaL_error(L, "Handler has already been registered");
1244 /* Return the handler for un-register */
1245 /*l->handler = lua_newuserdata(L, sizeof(struct lua_handler));
1246 memcpy(l->handler, &lh, sizeof(struct lua_handler));*/
1247 lh->listener = l;
1248 push_callback(L, (lua_handler *)&l->handler);
1250 else
1251 return luaL_error(L, "Invalid event specified: %s for object %s", event, objname);
1253 StackDump(L, "After RegEvent\n");
1254 return 1;
1257 static int
1258 LuaUnRegEvent(lua_State *L)
1260 /* signature: unhook([obj], ticket)
1261 * returns: true of success, false otherwise */
1262 int idx = 1;
1263 struct listener *l;
1265 /* If the param is not as expected */
1266 if (!lua_islightuserdata(L, idx))
1268 /* Then it should be the userdata to be ignore, but if not ... */
1269 if (!lua_isuserdata(L, idx))
1270 luaL_checktype(L, idx, LUA_TLIGHTUSERDATA);
1271 idx++;
1272 luaL_checktype(L, idx, LUA_TLIGHTUSERDATA);
1275 l = (struct listener*)lua_touserdata(L, idx++);
1277 /* Validate the listener structure */
1278 if (!l || !l->handler)
1280 /* invalid */
1281 lua_pushboolean(L,0);
1283 else
1285 LuaFreeHandler(L, ((lua_handler *)&(l->handler)));
1286 unregister_listener(l);
1287 lua_pushboolean(L, 1);
1290 return 1;
1293 /** }}} */
1295 struct ScriptFuncs LuaFuncs =
1297 LuaForeWindowChanged,
1298 LuaProcessCaption
1301 struct binding lua_binding =
1303 "lua", /*name*/
1304 0, /*inited*/
1305 0, /*registered*/
1306 LuaInit,
1307 LuaFinit,
1308 LuaCall,
1309 LuaSource,
1310 LuaDispatch,
1311 LuaHdlrComp,
1312 0, /*b_next*/
1313 &LuaFuncs