Removed the LuaUnReg() func.
[screen-lua.git] / src / lua.c
blob1be2b69d00c178b2c13edff4ef97274f7dcc6bad
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}
359 static const luaL_reg callback_metamethods[] = {
360 {0, 0}
363 static const struct Xet_reg callback_setters[] = {
364 {0, 0}
367 static const struct Xet_reg callback_getters[] = {
368 {0, 0}
372 /** }}} */
374 /** Window {{{ */
376 PUSH_TYPE(window, struct win)
378 CHECK_TYPE(window, struct win)
380 static int get_window(lua_State *L, void *v)
382 push_window(L, (struct win **)v);
383 return 1;
386 static int
387 window_change_title(lua_State *L)
389 struct win *w = check_window(L, 1);
390 unsigned int len;
391 const char *title = luaL_checklstring(L, 2, &len);
392 ChangeAKA(w, (char *)title, len);
393 return 0;
396 static int
397 window_get_monitor_status(lua_State *L)
399 struct win *w = check_window(L, 1);
400 int activity = luaL_checkint(L, 2);
401 if (activity)
402 /*monitor*/
403 lua_pushinteger(L, w->w_monitor != MON_OFF);
404 else
405 /*silence*/
406 lua_pushinteger(L, w->w_silence == SILENCE_ON ? w->w_silencewait: 0);
408 return 1;
411 static const luaL_reg window_methods[] = {
412 {"get_monitor_status", window_get_monitor_status},
413 {"hook", LuaRegEvent},
414 {0, 0}
417 static int
418 window_tostring(lua_State *L)
420 char str[128];
421 struct win *w = check_window(L, 1);
422 snprintf(str, sizeof(str), "{window #%d: '%s'}", w->w_number, w->w_title);
423 lua_pushstring(L, str);
424 return 1;
427 static int
428 window_equality(lua_State *L)
430 struct win *w1 = check_window(L, 1), *w2 = check_window(L, 2);
431 lua_pushboolean(L, (w1 == w2 || (w1 && w2 && w1->w_number == w2->w_number)));
432 return 1;
435 static const luaL_reg window_metamethods[] = {
436 {"__tostring", window_tostring},
437 {"__eq", window_equality},
438 {0, 0}
441 static const struct Xet_reg window_setters[] = {
442 {"title", 0, 0, window_change_title/*absolute setter*/},
443 {0, 0}
446 static const struct Xet_reg window_getters[] = {
447 {"title", get_string, offsetof(struct win, w_title) + 8},
448 {"number", get_int, offsetof(struct win, w_number)},
449 {"dir", get_string, offsetof(struct win, w_dir)},
450 {"tty", get_string, offsetof(struct win, w_tty)},
451 {"pid", get_int, offsetof(struct win, w_pid)},
452 {"group", get_window, offsetof(struct win, w_group)},
453 {"bell", get_int, offsetof(struct win, w_bell)},
454 {0, 0}
458 /** }}} */
460 /** AclUser {{{ */
462 PUSH_TYPE(user, struct acluser)
464 CHECK_TYPE(user, struct acluser)
466 static int
467 get_user(lua_State *L, void *v)
469 push_user(L, (struct acluser **)v);
470 return 1;
473 static const luaL_reg user_methods[] = {
474 {0, 0}
477 static int
478 user_tostring(lua_State *L)
480 char str[128];
481 struct acluser *u = check_user(L, 1);
482 snprintf(str, sizeof(str), "{user '%s'}", u->u_name);
483 lua_pushstring(L, str);
484 return 1;
487 static const luaL_reg user_metamethods[] = {
488 {"__tostring", user_tostring},
489 {0, 0}
492 static const struct Xet_reg user_setters[] = {
493 {0, 0}
496 static const struct Xet_reg user_getters[] = {
497 {"name", get_string, offsetof(struct acluser, u_name)},
498 {"password", get_string, offsetof(struct acluser, u_password)},
499 {0, 0}
502 /** }}} */
504 /** Canvas {{{ */
506 PUSH_TYPE(canvas, struct canvas)
508 CHECK_TYPE(canvas, struct canvas)
510 static int
511 get_canvas(lua_State *L, void *v)
513 push_canvas(L, (struct canvas **)v);
514 return 1;
517 static int
518 canvas_select(lua_State *L)
520 struct canvas *c = check_canvas(L, 1);
521 if (!display || D_forecv == c)
522 return 0;
523 SetCanvasWindow(c, Layer2Window(c->c_layer));
524 D_forecv = c;
526 /* XXX: the following all is duplicated from process.c:DoAction.
527 * Should these be in some better place?
529 ResizeCanvas(&D_canvas);
530 RecreateCanvasChain();
531 RethinkDisplayViewports();
532 ResizeLayersToCanvases(); /* redisplays */
533 fore = D_fore = Layer2Window(D_forecv->c_layer);
534 flayer = D_forecv->c_layer;
535 #ifdef RXVT_OSC
536 if (D_xtermosc[2] || D_xtermosc[3])
538 Activate(-1);
539 break;
541 #endif
542 RefreshHStatus();
543 #ifdef RXVT_OSC
544 RefreshXtermOSC();
545 #endif
546 flayer = D_forecv->c_layer;
547 CV_CALL(D_forecv, LayRestore();LaySetCursor());
548 WindowChanged(0, 'F');
549 return 1;
552 static const luaL_reg canvas_methods[] = {
553 {"select", canvas_select},
554 {0, 0}
557 static const luaL_reg canvas_metamethods[] = {
558 {0, 0}
561 static const struct Xet_reg canvas_setters[] = {
562 {0, 0}
565 static int
566 canvas_get_window(lua_State *L)
568 struct canvas *c = check_canvas(L, 1);
569 struct win *win = Layer2Window(c->c_layer);
570 if (win)
571 push_window(L, &win);
572 else
573 lua_pushnil(L);
574 return 1;
577 static const struct Xet_reg canvas_getters[] = {
578 {"next", get_canvas, offsetof(struct canvas, c_next)},
579 {"xoff", get_int, offsetof(struct canvas, c_xoff)},
580 {"yoff", get_int, offsetof(struct canvas, c_yoff)},
581 {"xs", get_int, offsetof(struct canvas, c_xs)},
582 {"ys", get_int, offsetof(struct canvas, c_ys)},
583 {"xe", get_int, offsetof(struct canvas, c_xe)},
584 {"ye", get_int, offsetof(struct canvas, c_ye)},
585 {"window", 0, 0, canvas_get_window},
586 {0, 0}
589 /** }}} */
591 /** Layout {{{ */
593 PUSH_TYPE(layout, struct layout)
594 CHECK_TYPE(layout, struct layout)
596 static const struct Xet_reg layout_getters[] = {
597 {0,0}
600 static int
601 get_layout(lua_State *L, void *v)
603 push_layout(L, (struct layout **)v);
604 return 1;
607 /** }}} */
609 /** Display {{{ */
611 PUSH_TYPE(display, struct display)
613 CHECK_TYPE(display, struct display)
615 static int
616 display_get_canvases(lua_State *L)
618 struct display *d;
619 struct canvas *iter;
620 int count;
622 d = check_display(L, 1);
623 lua_newtable(L);
624 for (iter = d->d_cvlist, count = 0; iter; iter = iter->c_next, count++) {
625 lua_pushinteger(L, count);
626 push_canvas(L, &iter);
627 lua_settable(L, -3);
630 return 1;
633 static const luaL_reg display_methods[] = {
634 {"get_canvases", display_get_canvases},
635 {0, 0}
638 static int
639 display_tostring(lua_State *L)
641 char str[128];
642 struct display *d = check_display(L, 1);
643 snprintf(str, sizeof(str), "{display: tty = '%s', term = '%s'}", d->d_usertty, d->d_termname);
644 lua_pushstring(L, str);
645 return 1;
648 static const luaL_reg display_metamethods[] = {
649 {"__tostring", display_tostring},
650 {0, 0}
653 static const struct Xet_reg display_setters[] = {
654 {0, 0}
657 static const struct Xet_reg display_getters[] = {
658 {"tty", get_string, offsetof(struct display, d_usertty)},
659 {"term", get_string, offsetof(struct display, d_termname)},
660 {"fore", get_window, offsetof(struct display, d_fore)},
661 {"other", get_window, offsetof(struct display, d_other)},
662 {"width", get_int, offsetof(struct display, d_width)},
663 {"height", get_int, offsetof(struct display, d_height)},
664 {"user", get_user, offsetof(struct display, d_user)},
665 {"layout", get_layout, offsetof(struct display, d_layout)},
666 {0, 0}
669 /** }}} */
671 /** Screen {{{ */
673 static int
674 screen_get_windows(lua_State *L)
676 struct win *iter;
677 int count;
679 lua_newtable(L);
680 for (iter = windows, count = 0; iter; iter = iter->w_next, count++) {
681 lua_pushinteger(L, iter->w_number);
682 push_window(L, &iter);
683 lua_settable(L, -3);
686 return 1;
689 static int
690 screen_get_displays(lua_State *L)
692 struct display *iter;
693 int count;
695 lua_newtable(L);
696 for (iter = displays, count = 0; iter; iter = iter->d_next, count++) {
697 lua_pushinteger(L, count);
698 push_display(L, &iter);
699 lua_settable(L, -3);
702 return 1;
705 static int
706 screen_get_display(lua_State *L)
708 push_display(L, &display);
709 return 1;
712 static int
713 screen_exec_command(lua_State *L)
715 const char *command;
716 unsigned int len;
718 command = luaL_checklstring(L, 1, &len);
719 if (command)
720 RcLine((char *)command, len);
722 return 0;
725 static int
726 screen_append_msg(lua_State *L)
728 const char *msg, *color;
729 unsigned int len;
730 msg = luaL_checklstring(L, 1, &len);
731 if (lua_isnil(L, 2))
732 color = NULL;
733 else
734 color = luaL_checklstring(L, 2, &len);
735 AppendWinMsgRend(msg, color);
736 return 0;
739 struct sinput_data
741 lua_State *L;
742 lua_handler lh;
745 void
746 script_input_fn(char *buf, int len, char *priv)
748 struct sinput_data *sidata = (struct sinput_data *)priv;
749 lua_handler lh = sidata->lh;
750 lua_State *L = sidata->L;
752 LuaPushHandler(L, lh);
753 lua_pushstring(L, buf);
754 if (lua_pcall(L, 1, 0, 0) == LUA_ERRRUN)
756 if(lua_isstring(L, -1))
758 LuaShowErr(L);
761 free(sidata);
762 LuaFreeHandler(L, &lh);
765 static int
766 screen_input(lua_State *L)
768 char * prompt = NULL;
769 lua_handler lh;
770 struct sinput_data *sidata;
772 prompt = (char *)luaL_checkstring(L, 1);
773 lh = LuaCheckHandler(L, 2, 1);
774 sidata = (struct sinput_data *)malloc(sizeof(struct sinput_data));
775 if (!sidata)
776 luaL_error(L, "Out of Memory");
778 sidata->L = L;
779 sidata->lh = lh;
780 Input(prompt, 100, INP_COOKED, script_input_fn, (char *)sidata, 0);
782 return 0;
785 static const luaL_reg screen_methods[] = {
786 {"windows", screen_get_windows},
787 {"displays", screen_get_displays},
788 {"display", screen_get_display},
789 {"command", screen_exec_command},
790 {"append_msg", screen_append_msg},
791 {"hook", LuaRegEvent},
792 {"input", screen_input},
793 {0, 0}
796 static const luaL_reg screen_metamethods[] = {
797 {0, 0}
800 static const struct Xet_reg screen_setters[] = {
801 {0, 0}
804 static const struct Xet_reg screen_getters[] = {
805 {0, 0}
808 /** }}} */
810 /** Public functions {{{ */
812 /* FIXME: Think about this: will it affect the registered handlers?*/
813 static lua_State *L;
814 int LuaInit(void)
816 L = luaL_newstate();
818 luaL_openlibs(L);
820 #define REGISTER(X) struct_register(L, #X , X ## _methods, X##_metamethods, X##_setters, X##_getters)
822 REGISTER(screen);
823 REGISTER(window);
824 REGISTER(display);
825 REGISTER(user);
826 REGISTER(canvas);
827 REGISTER(callback);
829 /* To store handler funcs */
830 luaL_getmetatable(L, "screen");
831 /* two kinds of info in this table:
832 * _funckey[func]->key
833 * _funckey[key]->refcnt */
834 lua_pushstring(L, "_funckey");
835 lua_newtable(L);
836 lua_rawset(L, -3);
837 /* two kinds of info in this table:
838 * _keyfunc[key]->func */
839 lua_pushstring(L, "_keyfunc");
840 lua_newtable(L);
841 lua_rawset(L, -3);
842 lua_pop(L, 1);
844 return 0;
847 /* An error message on top of the stack. */
848 static void
849 LuaShowErr(lua_State *L)
851 struct display *d = display;
852 unsigned int len;
853 const char *message = luaL_checklstring(L, -1, &len);
854 LMsg(0, "%s", message ? message : "Unknown error");
855 lua_pop(L, 1);
856 display = d;
859 struct fn_def
861 void (*push_fn)(lua_State *, void*);
862 void *value;
865 static int
866 LuaCallProcess(const char *name, struct fn_def defs[])
868 int argc = 0;
870 lua_getfield(L, LUA_GLOBALSINDEX, name);
871 if (lua_isnil(L, -1))
873 lua_pop(L,1);
874 return 0;
876 for (argc = 0; defs[argc].push_fn; argc++)
877 defs[argc].push_fn(L, defs[argc].value);
878 if (lua_pcall(L, argc, 0, 0) == LUA_ERRRUN && lua_isstring(L, -1))
880 LuaShowErr(L);
881 return 0;
883 return 1;
886 int LuaSource(const char *file, int async)
888 if (!L)
889 return 0;
890 struct stat st;
891 if (stat(file, &st) == -1)
892 Msg(errno, "Error loading lua script file '%s'", file);
893 else
895 int len = strlen(file);
896 if (len < 4 || strncmp(file + len - 4, ".lua", 4) != 0)
897 return 0;
898 if (luaL_dofile(L, file) && lua_isstring(L, -1))
900 LuaShowErr(L);
902 return 1;
904 return 0;
907 int LuaFinit(void)
909 if (!L)
910 return 0;
911 lua_close(L);
912 L = (lua_State*)0;
913 return 0;
917 LuaProcessCaption(const char *caption, struct win *win, int len)
919 if (!L)
920 return 0;
921 struct fn_def params[] = {
922 {lua_pushstring, caption},
923 {push_window, &win},
924 {lua_pushinteger, len},
925 {NULL, NULL}
927 return LuaCallProcess("process_caption", params);
930 static void
931 push_stringarray(lua_State *L, char **args)
933 int i;
934 lua_newtable(L);
935 for (i = 1; args && *args; i++) {
936 lua_pushinteger(L, i);
937 lua_pushstring(L, *args++);
938 lua_settable(L, -3);
943 LuaPushParams(lua_State *L, const char *params, va_list va)
945 int num = 0;
946 while (*params)
948 switch (*params)
950 case 's':
951 lua_pushstring(L, va_arg(va, char *));
952 break;
953 case 'S':
954 push_stringarray(L, va_arg(va, char **));
955 break;
956 case 'i':
957 lua_pushinteger(L, va_arg(va, int));
958 break;
959 case 'd':
961 struct display *d = va_arg(va, struct display *);
962 push_display(L, &d);
963 break;
966 params++;
967 num++;
969 return num;
972 int LuaCall(const char *func, const char **argv)
974 int argc;
975 if (!L)
976 return 0;
978 StackDump(L, "Before LuaCall\n");
979 lua_getfield(L, LUA_GLOBALSINDEX, func);
980 if (lua_isnil(L, -1))
982 lua_pop(L, 1);
983 lua_pushstring(L, "Could not find the script function\n");
984 LuaShowErr(L);
985 return 0;
987 for (argc = 0; *argv; argv++, argc++)
989 lua_pushstring(L, *argv);
991 if (lua_pcall(L, argc, 0, 0) == LUA_ERRRUN)
993 if(lua_isstring(L, -1))
995 StackDump(L, "After LuaCall\n");
996 LuaShowErr(L);
997 return 0;
1000 return 1;
1003 /*** Lua callback handler management {{{ */
1006 LuaPushHTable(lua_State *L, int screen, const char * t)
1008 lua_pushstring(L, t);
1009 lua_rawget(L, screen);
1010 /* FIXME: Do we need to balance the stack here? */
1011 if (lua_isnil(L, -1))
1012 luaL_error(L, "Fatal! Fail to get function registeration table!");
1013 return lua_gettop(L);
1016 void
1017 LuaPushHandler(lua_State *L, lua_handler lh)
1019 int keyfunc;
1020 if (lh->type == LUA_HANDLER_TYPE_F)
1022 luaL_getmetatable(L, "screen");
1023 keyfunc = LuaPushHTable(L, lua_gettop(L), "_keyfunc");
1024 lua_rawgeti(L, keyfunc, lh->u.reference);
1025 lua_replace(L, -3);
1026 lua_pop(L, 1);
1028 else
1030 lua_getfield(L, LUA_GLOBALSINDEX, lh->u.name);
1034 void
1035 LuaHRef(lua_State *L, int key, int reg)
1037 int funckey, keyfunc, cnt, sc, idx;
1038 luaL_getmetatable(L, "screen");
1039 sc = lua_gettop(L);
1040 funckey = LuaPushHTable(L, sc, "_funckey");
1041 keyfunc = LuaPushHTable(L, sc, "_keyfunc");
1043 lua_rawgeti(L, keyfunc, key);
1044 idx = lua_gettop(L);
1046 lua_rawgeti(L, funckey, key);
1047 cnt = lua_tointeger(L, -1);/*cnt = htable[key]*/
1048 if (!reg && cnt <= 1)
1050 /*release the last reference*/
1051 luaL_unref(L, funckey, key);
1052 lua_pushvalue(L, idx);
1053 lua_pushnil(L);
1054 lua_settable(L, funckey); /*htable[func]=key*/
1056 else
1058 lua_pushinteger(L, key);
1059 lua_pushinteger(L, reg? cnt + 1 : cnt - 1);
1060 lua_settable(L, funckey); /*htable[key] = cnt + 1*/
1062 lua_pop(L, 5);
1065 /* Ref when asked to. Never unref*/
1067 LuaFuncKey(lua_State *L, int idx, int ref)
1069 int key, funckey, sc;
1070 luaL_getmetatable(L, "screen");
1071 sc = lua_gettop(L);
1072 funckey = LuaPushHTable(L, sc, "_funckey");
1074 lua_pushvalue(L, idx);
1075 lua_gettable(L, funckey);/*funckey[func] ==?*/
1076 if (lua_isnil(L, -1))
1078 /* Not found, alloc a new key */
1079 if (!ref)
1080 return LUA_NOREF;
1082 /*funckey[key] = 1*/
1083 lua_pushinteger(L, 1);
1084 key = luaL_ref(L, funckey);
1086 /*funckey[func]=key*/
1087 lua_pushvalue(L, idx);
1088 lua_pushinteger(L, key);
1089 lua_settable(L, funckey);
1091 int keyfunc = LuaPushHTable(L, sc, "_keyfunc");
1092 /*keyfunc[key] = func*/
1093 lua_pushinteger(L, key);
1094 lua_pushvalue(L, idx);
1095 lua_settable(L, keyfunc);
1097 lua_pop(L, 1);
1099 else
1101 key = lua_tointeger(L, -1);/*key = funckey[func]*/
1102 if (ref)
1103 LuaHRef(L, key, 1);
1106 lua_pop(L, 3);
1107 return key;
1110 lua_handler
1111 LuaCheckHandler(lua_State *L, int idx, int ref)
1113 int key;
1114 if (lua_isstring(L, idx))
1116 const char * handler;
1117 /* registered with func name.*/
1118 handler = luaL_checkstring(L, idx);
1119 lua_getfield(L, LUA_GLOBALSINDEX, handler);
1120 if (!lua_isfunction(L, -1))
1121 luaL_error(L, "The specified handler %s in param #%d is not a function", handler, idx);
1122 lua_pop(L, 1);
1123 return LuaAllocHandler(handler, 0);
1125 else if (!lua_isfunction(L, idx))
1126 luaL_error(L, "Handler should be a function or the name of function");
1128 key = LuaFuncKey(L, idx, ref);
1129 return LuaAllocHandler(NULL, key);
1133 LuaHdlrComp(void *h1, void *h2)
1135 return (lua_handler)h1 - (lua_handler)h2;
1138 /* }}} **/
1140 static int
1141 LuaDispatch(void *handler, const char *params, va_list va)
1143 lua_handler lh = (lua_handler)handler;
1144 int argc, retvalue;
1146 StackDump(L, "before dispatch");
1148 LuaPushHandler(L, lh);
1149 if (lua_isnil(L, -1))
1151 lua_pop(L, 1);
1152 return 0;
1154 argc = LuaPushParams(L, params, va);
1156 if (lua_pcall(L, argc, 1, 0) == LUA_ERRRUN && lua_isstring(L, -1))
1158 StackDump(L, "After LuaDispatch\n");
1159 LuaShowErr(L);
1160 return 0;
1162 retvalue = lua_tonumber(L, -1);
1163 lua_pop(L, 1);
1164 return retvalue;
1167 int LuaForeWindowChanged(void)
1169 struct fn_def params[] = {
1170 {push_display, &display},
1171 {push_window, display ? &D_fore : &fore},
1172 {NULL, NULL}
1174 if (!L)
1175 return 0;
1176 return LuaCallProcess("fore_changed", params);
1179 #define SEVNAME_MAX 30
1180 static int
1181 LuaRegEvent(lua_State *L)
1183 /* signature: hook(obj, event, handler, priv);
1184 * or: hook(event, handler, priv)
1185 * returns: A ticket for later unregister. */
1186 int idx = 1, argc = lua_gettop(L);
1187 unsigned int priv = 31; /* Default privilege */
1188 lua_handler lh;
1190 char *obj = NULL;
1191 const char *objname = "global";
1193 static char evbuf[SEVNAME_MAX];
1194 const char *event;
1196 struct script_event *sev;
1198 StackDump(L, "Before RegEvent\n");
1200 /* Identify the object, if specified */
1201 if (luaL_getmetafield(L, 1, "_objname"))
1203 objname = luaL_checkstring(L, -1);
1204 lua_pop(L, 1);
1205 if (!strcmp("screen", objname))
1206 objname = "global";
1207 else
1208 obj = *(char **)lua_touserdata(L, 1);
1209 idx++;
1212 event = luaL_checkstring(L, idx++);
1213 snprintf(evbuf, SEVNAME_MAX, "%s_%s", objname, event);
1215 /* Check and get the handler */
1216 lh = LuaCheckHandler(L, idx++, 1);
1217 if (!lh)
1218 luaL_error(L, "Out of memory");
1220 StackDump(L, "In RegEvent\n");
1222 if (idx <= argc)
1223 priv = luaL_checkinteger(L, idx);
1225 sev = object_get_event(obj, evbuf);
1226 if (sev)
1228 struct listener *l;
1229 l = (struct listener *)malloc(sizeof(struct listener));
1230 if (!l)
1231 return luaL_error(L, "Out of memory");
1232 l->priv = priv;
1233 l->bd = &lua_binding;
1234 l->handler = (void *)lh;
1235 if (register_listener(sev, l))
1237 free(l);
1238 if (lh->type == LUA_HANDLER_TYPE_N)
1239 return luaL_error(L, "Handler %s has already been registered", lh->u.name);
1240 else
1241 return luaL_error(L, "Handler has already been registered");
1243 /* Return the handler for un-register */
1244 /*l->handler = lua_newuserdata(L, sizeof(struct lua_handler));
1245 memcpy(l->handler, &lh, sizeof(struct lua_handler));*/
1246 lh->listener = l;
1247 push_callback(L, (lua_handler *)&l->handler);
1249 else
1250 return luaL_error(L, "Invalid event specified: %s for object %s", event, objname);
1252 StackDump(L, "After RegEvent\n");
1253 return 1;
1256 /** }}} */
1258 struct ScriptFuncs LuaFuncs =
1260 LuaForeWindowChanged,
1261 LuaProcessCaption
1264 struct binding lua_binding =
1266 "lua", /*name*/
1267 0, /*inited*/
1268 0, /*registered*/
1269 LuaInit,
1270 LuaFinit,
1271 LuaCall,
1272 LuaSource,
1273 LuaDispatch,
1274 LuaHdlrComp,
1275 0, /*b_next*/
1276 &LuaFuncs