1 /* Lua scripting support
3 * Copyright (c) 2008 Sadrul Habib Chowdhury (sadrul@users.sf.net)
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)
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>
42 static int StackDump(lua_State
*L
, const char *message
)
44 FILE *f
= fopen("/tmp/debug/stack", "ab");
45 int i
= lua_gettop(L
);
47 fprintf(f
, "%s", message
);
50 int t
= lua_type(L
, i
);
54 fprintf(f
, "String: %s\n", lua_tostring(L
, i
));
58 fprintf(f
, "Boolean: %s\n", lua_toboolean(L
, i
) ? "true" : "false");
62 fprintf(f
, "Number: %g\n", lua_tonumber(L
, i
));
66 fprintf(f
, "Type: %s\n", lua_typename(L
, t
));
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
);
88 LUA_HANDLER_TYPE_N
= 1,
100 struct listener
*listener
;
105 #define CHECK_TYPE(name, type) \
107 check_##name(lua_State *L, int index) \
110 luaL_checktype(L, index, LUA_TUSERDATA); \
111 var = (type **) luaL_checkudata(L, index, #name); \
113 luaL_typerror(L, index, #name); \
117 #define PUSH_TYPE(name, type) \
119 push_##name(lua_State *L, type **t) \
126 r = (type **)lua_newuserdata(L, sizeof(type *)); \
128 luaL_getmetatable(L, #name); \
129 lua_setmetatable(L,-2); \
133 /* Much of the following template comes from:
134 * http://lua-users.org/wiki/BindingWithMembersAndMethods
137 static int get_int (lua_State
*L
, void *v
)
139 lua_pushinteger (L
, *(int*)v
);
143 static int set_int (lua_State
*L
, void *v
)
145 *(int*)v
= luaL_checkint(L
, 3);
149 static int get_number (lua_State
*L
, void *v
)
151 lua_pushnumber(L
, *(lua_Number
*)v
);
155 static int set_number (lua_State
*L
, void *v
)
157 *(lua_Number
*)v
= luaL_checknumber(L
, 3);
161 static int get_string (lua_State
*L
, void *v
)
163 lua_pushstring(L
, (char*)v
);
167 static int set_string (lua_State
*L
, void *v
)
169 *(const char**)v
= luaL_checkstring(L
, 3);
173 typedef int (*Xet_func
) (lua_State
*L
, void *v
);
175 /* member info for get and set handlers */
178 const char *name
; /* member name */
179 Xet_func func
; /* get or set function for type of member */
180 size_t offset
; /* offset of member within the struct */
181 int (*absolute
)(lua_State
*);
184 static void Xet_add (lua_State
*L
, const struct Xet_reg
*l
)
190 lua_pushstring(L
, l
->name
);
191 lua_pushlightuserdata(L
, (void*)l
);
196 static int Xet_call (lua_State
*L
)
198 /* for get: stack has userdata, index, lightuserdata */
199 /* for set: stack has userdata, index, value, lightuserdata */
200 const struct Xet_reg
*m
= (const struct Xet_reg
*)lua_touserdata(L
, -1); /* member info */
201 lua_pop(L
, 1); /* drop lightuserdata */
202 luaL_checktype(L
, 1, LUA_TUSERDATA
);
204 return m
->absolute(L
);
205 return m
->func(L
, *(char**)lua_touserdata(L
, 1) + m
->offset
);
208 static int index_handler (lua_State
*L
)
210 /* stack has userdata, index */
211 lua_pushvalue(L
, 2); /* dup index */
212 lua_rawget(L
, lua_upvalueindex(1)); /* lookup member by name */
213 if (!lua_islightuserdata(L
, -1))
215 lua_pop(L
, 1); /* drop value */
216 lua_pushvalue(L
, 2); /* dup index */
217 lua_gettable(L
, lua_upvalueindex(2)); /* else try methods */
218 if (lua_isnil(L
, -1)) /* invalid member */
219 luaL_error(L
, "cannot get member '%s'", lua_tostring(L
, 2));
222 return Xet_call(L
); /* call get function */
225 static int newindex_handler (lua_State
*L
)
227 /* stack has userdata, index, value */
228 lua_pushvalue(L
, 2); /* dup index */
229 lua_rawget(L
, lua_upvalueindex(1)); /* lookup member by name */
230 if (!lua_islightuserdata(L
, -1)) /* invalid member */
231 luaL_error(L
, "cannot set member '%s'", lua_tostring(L
, 2));
232 return Xet_call(L
); /* call set function */
236 struct_register(lua_State
*L
, const char *name
, const luaL_reg fn_methods
[], const luaL_reg meta_methods
[],
237 const struct Xet_reg setters
[], const struct Xet_reg getters
[])
239 int metatable
, methods
;
241 /* create methods table & add it to the table of globals */
242 luaL_register(L
, name
, fn_methods
);
243 methods
= lua_gettop(L
);
245 /* create metatable & add it to the registry */
246 luaL_newmetatable(L
, name
);
247 luaL_register(L
, 0, meta_methods
); /* fill metatable */
249 /* To identify the type of object */
250 lua_pushstring(L
, "_objname");
251 lua_pushstring(L
, name
);
254 metatable
= lua_gettop(L
);
256 lua_pushliteral(L
, "__metatable");
257 lua_pushvalue(L
, methods
); /* dup methods table*/
258 lua_rawset(L
, metatable
); /* hide metatable:
259 metatable.__metatable = methods */
261 lua_pushliteral(L
, "__index");
262 lua_pushvalue(L
, metatable
); /* upvalue index 1 */
263 Xet_add(L
, getters
); /* fill metatable with getters */
264 lua_pushvalue(L
, methods
); /* upvalue index 2 */
265 lua_pushcclosure(L
, index_handler
, 2);
266 lua_rawset(L
, metatable
); /* metatable.__index = index_handler */
268 lua_pushliteral(L
, "__newindex");
269 lua_newtable(L
); /* table for members you can set */
270 Xet_add(L
, setters
); /* fill with setters */
271 lua_pushcclosure(L
, newindex_handler
, 1);
272 lua_rawset(L
, metatable
); /* metatable.__newindex = newindex_handler */
274 lua_pop(L
, 1); /* drop metatable */
275 return 1; /* return methods on the stack */
281 PUSH_TYPE(callback
, struct lua_handler
)
283 CHECK_TYPE(callback
, struct lua_handler
)
286 callback_unhook(lua_State
*L
)
288 struct lua_handler
*lh
= check_callback(L
, 1);
291 lua_pushboolean(L
, 0);
292 lua_pushstring(L
, "Callback already unhooked.");
297 if (lh
->type
== LUA_HANDLER_TYPE_N
)
303 luaL_unref(L
, LUA_REGISTRYINDEX
, lh
->u
.reference
);
306 unregister_listener(lh
->listener
);
308 lua_pushboolean(L
, 1);
313 static const luaL_reg callback_methods
[] = {
314 {"unhook", callback_unhook
},
318 static const luaL_reg callback_metamethods
[] = {
322 static const struct Xet_reg callback_setters
[] = {
326 static const struct Xet_reg callback_getters
[] = {
335 PUSH_TYPE(window
, struct win
)
337 CHECK_TYPE(window
, struct win
)
339 static int get_window(lua_State
*L
, void *v
)
341 push_window(L
, (struct win
**)v
);
346 window_change_title(lua_State
*L
)
348 struct win
*w
= check_window(L
, 1);
350 const char *title
= luaL_checklstring(L
, 2, &len
);
351 ChangeAKA(w
, (char *)title
, len
);
356 window_get_monitor_status(lua_State
*L
)
358 struct win
*w
= check_window(L
, 1);
359 int activity
= luaL_checkint(L
, 2);
362 lua_pushinteger(L
, w
->w_monitor
!= MON_OFF
);
365 lua_pushinteger(L
, w
->w_silence
== SILENCE_ON
? w
->w_silencewait
: 0);
370 static const luaL_reg window_methods
[] = {
371 {"get_monitor_status", window_get_monitor_status
},
372 {"hook", LuaRegEvent
},
377 window_tostring(lua_State
*L
)
380 struct win
*w
= check_window(L
, 1);
381 snprintf(str
, sizeof(str
), "{window #%d: '%s'}", w
->w_number
, w
->w_title
);
382 lua_pushstring(L
, str
);
387 window_equality(lua_State
*L
)
389 struct win
*w1
= check_window(L
, 1), *w2
= check_window(L
, 2);
390 lua_pushboolean(L
, (w1
== w2
|| (w1
&& w2
&& w1
->w_number
== w2
->w_number
)));
394 static const luaL_reg window_metamethods
[] = {
395 {"__tostring", window_tostring
},
396 {"__eq", window_equality
},
400 static const struct Xet_reg window_setters
[] = {
401 {"title", 0, 0, window_change_title
/*absolute setter*/},
405 static const struct Xet_reg window_getters
[] = {
406 {"title", get_string
, offsetof(struct win
, w_title
) + 8},
407 {"number", get_int
, offsetof(struct win
, w_number
)},
408 {"dir", get_string
, offsetof(struct win
, w_dir
)},
409 {"tty", get_string
, offsetof(struct win
, w_tty
)},
410 {"pid", get_int
, offsetof(struct win
, w_pid
)},
411 {"group", get_window
, offsetof(struct win
, w_group
)},
412 {"bell", get_int
, offsetof(struct win
, w_bell
)},
421 PUSH_TYPE(user
, struct acluser
)
423 CHECK_TYPE(user
, struct acluser
)
426 get_user(lua_State
*L
, void *v
)
428 push_user(L
, (struct acluser
**)v
);
432 static const luaL_reg user_methods
[] = {
437 user_tostring(lua_State
*L
)
440 struct acluser
*u
= check_user(L
, 1);
441 snprintf(str
, sizeof(str
), "{user '%s'}", u
->u_name
);
442 lua_pushstring(L
, str
);
446 static const luaL_reg user_metamethods
[] = {
447 {"__tostring", user_tostring
},
451 static const struct Xet_reg user_setters
[] = {
455 static const struct Xet_reg user_getters
[] = {
456 {"name", get_string
, offsetof(struct acluser
, u_name
)},
457 {"password", get_string
, offsetof(struct acluser
, u_password
)},
465 PUSH_TYPE(canvas
, struct canvas
)
467 CHECK_TYPE(canvas
, struct canvas
)
470 get_canvas(lua_State
*L
, void *v
)
472 push_canvas(L
, (struct canvas
**)v
);
477 canvas_select(lua_State
*L
)
479 struct canvas
*c
= check_canvas(L
, 1);
480 if (!display
|| D_forecv
== c
)
482 SetCanvasWindow(c
, Layer2Window(c
->c_layer
));
485 /* XXX: the following all is duplicated from process.c:DoAction.
486 * Should these be in some better place?
488 ResizeCanvas(&D_canvas
);
489 RecreateCanvasChain();
490 RethinkDisplayViewports();
491 ResizeLayersToCanvases(); /* redisplays */
492 fore
= D_fore
= Layer2Window(D_forecv
->c_layer
);
493 flayer
= D_forecv
->c_layer
;
495 if (D_xtermosc
[2] || D_xtermosc
[3])
505 flayer
= D_forecv
->c_layer
;
506 CV_CALL(D_forecv
, LayRestore();LaySetCursor());
507 WindowChanged(0, 'F');
511 static const luaL_reg canvas_methods
[] = {
512 {"select", canvas_select
},
516 static const luaL_reg canvas_metamethods
[] = {
520 static const struct Xet_reg canvas_setters
[] = {
525 canvas_get_window(lua_State
*L
)
527 struct canvas
*c
= check_canvas(L
, 1);
528 struct win
*win
= Layer2Window(c
->c_layer
);
530 push_window(L
, &win
);
536 static const struct Xet_reg canvas_getters
[] = {
537 {"next", get_canvas
, offsetof(struct canvas
, c_next
)},
538 {"xoff", get_int
, offsetof(struct canvas
, c_xoff
)},
539 {"yoff", get_int
, offsetof(struct canvas
, c_yoff
)},
540 {"xs", get_int
, offsetof(struct canvas
, c_xs
)},
541 {"ys", get_int
, offsetof(struct canvas
, c_ys
)},
542 {"xe", get_int
, offsetof(struct canvas
, c_xe
)},
543 {"ye", get_int
, offsetof(struct canvas
, c_ye
)},
544 {"window", 0, 0, canvas_get_window
},
552 PUSH_TYPE(layout
, struct layout
)
553 CHECK_TYPE(layout
, struct layout
)
555 static const struct Xet_reg layout_getters
[] = {
560 get_layout(lua_State
*L
, void *v
)
562 push_layout(L
, (struct layout
**)v
);
570 PUSH_TYPE(display
, struct display
)
572 CHECK_TYPE(display
, struct display
)
575 display_get_canvases(lua_State
*L
)
581 d
= check_display(L
, 1);
583 for (iter
= d
->d_cvlist
, count
= 0; iter
; iter
= iter
->c_next
, count
++) {
584 lua_pushinteger(L
, count
);
585 push_canvas(L
, &iter
);
592 static const luaL_reg display_methods
[] = {
593 {"get_canvases", display_get_canvases
},
598 display_tostring(lua_State
*L
)
601 struct display
*d
= check_display(L
, 1);
602 snprintf(str
, sizeof(str
), "{display: tty = '%s', term = '%s'}", d
->d_usertty
, d
->d_termname
);
603 lua_pushstring(L
, str
);
607 static const luaL_reg display_metamethods
[] = {
608 {"__tostring", display_tostring
},
612 static const struct Xet_reg display_setters
[] = {
616 static const struct Xet_reg display_getters
[] = {
617 {"tty", get_string
, offsetof(struct display
, d_usertty
)},
618 {"term", get_string
, offsetof(struct display
, d_termname
)},
619 {"fore", get_window
, offsetof(struct display
, d_fore
)},
620 {"other", get_window
, offsetof(struct display
, d_other
)},
621 {"width", get_int
, offsetof(struct display
, d_width
)},
622 {"height", get_int
, offsetof(struct display
, d_height
)},
623 {"user", get_user
, offsetof(struct display
, d_user
)},
624 {"layout", get_layout
, offsetof(struct display
, d_layout
)},
633 screen_get_windows(lua_State
*L
)
639 for (iter
= windows
, count
= 0; iter
; iter
= iter
->w_next
, count
++) {
640 lua_pushinteger(L
, iter
->w_number
);
641 push_window(L
, &iter
);
649 screen_get_displays(lua_State
*L
)
651 struct display
*iter
;
655 for (iter
= displays
, count
= 0; iter
; iter
= iter
->d_next
, count
++) {
656 lua_pushinteger(L
, count
);
657 push_display(L
, &iter
);
665 screen_get_display(lua_State
*L
)
667 push_display(L
, &display
);
672 screen_exec_command(lua_State
*L
)
677 command
= luaL_checklstring(L
, 1, &len
);
679 RcLine((char *)command
, len
);
685 screen_append_msg(lua_State
*L
)
687 const char *msg
, *color
;
689 msg
= luaL_checklstring(L
, 1, &len
);
693 color
= luaL_checklstring(L
, 2, &len
);
694 AppendWinMsgRend(msg
, color
);
698 static const luaL_reg screen_methods
[] = {
699 {"windows", screen_get_windows
},
700 {"displays", screen_get_displays
},
701 {"display", screen_get_display
},
702 {"command", screen_exec_command
},
703 {"append_msg", screen_append_msg
},
704 {"hook", LuaRegEvent
},
708 static const luaL_reg screen_metamethods
[] = {
712 static const struct Xet_reg screen_setters
[] = {
716 static const struct Xet_reg screen_getters
[] = {
722 /** Public functions {{{ */
730 #define REGISTER(X) struct_register(L, #X , X ## _methods, X##_metamethods, X##_setters, X##_getters)
742 /* An error message on top of the stack. */
744 LuaShowErr(lua_State
*L
)
746 struct display
*d
= display
;
748 const char *message
= luaL_checklstring(L
, -1, &len
);
749 LMsg(0, "%s", message
? message
: "Unknown error");
756 void (*push_fn
)(lua_State
*, void*);
761 LuaCallProcess(const char *name
, struct fn_def defs
[])
765 lua_getfield(L
, LUA_GLOBALSINDEX
, name
);
766 if (lua_isnil(L
, -1))
768 for (argc
= 0; defs
[argc
].push_fn
; argc
++)
769 defs
[argc
].push_fn(L
, defs
[argc
].value
);
770 if (lua_pcall(L
, argc
, 0, 0) == LUA_ERRRUN
&& lua_isstring(L
, -1))
778 int LuaSource(const char *file
, int async
)
783 if (stat(file
, &st
) == -1)
784 Msg(errno
, "Error loading lua script file '%s'", file
);
787 int len
= strlen(file
);
788 if (len
< 4 || strncmp(file
+ len
- 4, ".lua", 4) != 0)
790 if (luaL_dofile(L
, file
) && lua_isstring(L
, -1))
809 LuaProcessCaption(const char *caption
, struct win
*win
, int len
)
813 struct fn_def params
[] = {
814 {lua_pushstring
, caption
},
816 {lua_pushinteger
, len
},
819 return LuaCallProcess("process_caption", params
);
823 push_stringarray(lua_State
*L
, char **args
)
827 for (i
= 1; args
&& *args
; i
++) {
828 lua_pushinteger(L
, i
);
829 lua_pushstring(L
, *args
++);
835 LuaPushParams(lua_State
*L
, const char *params
, va_list va
)
843 lua_pushstring(L
, va_arg(va
, char *));
846 push_stringarray(L
, va_arg(va
, char **));
849 lua_pushinteger(L
, va_arg(va
, int));
853 struct display
*d
= va_arg(va
, struct display
*);
864 int LuaCall(char *func
, char **argv
)
870 StackDump(L
, "Before LuaCall\n");
871 lua_getfield(L
, LUA_GLOBALSINDEX
, func
);
872 if (lua_isnil(L
, -1))
874 lua_pushstring(L
, "Could not find the script function\n");
878 for (argc
= 0; *argv
; argv
++, argc
++)
880 lua_pushstring(L
, *argv
);
882 if (lua_pcall(L
, argc
, 0, 0) == LUA_ERRRUN
)
884 if(lua_isstring(L
, -1))
886 StackDump(L
, "After LuaCall\n");
895 LuaDispatch(void *handler
, const char *params
, va_list va
)
897 struct lua_handler
*lh
= handler
;
900 if (lh
->type
== LUA_HANDLER_TYPE_N
)
901 lua_getfield(L
, LUA_GLOBALSINDEX
, lh
->u
.name
);
903 lua_rawgeti(L
, LUA_REGISTRYINDEX
, lh
->u
.reference
);
905 if (lua_isnil(L
, -1))
907 argc
= LuaPushParams(L
, params
, va
);
909 if (lua_pcall(L
, argc
, 1, 0) == LUA_ERRRUN
&& lua_isstring(L
, -1))
911 StackDump(L
, "After LuaDispatch\n");
915 retvalue
= lua_tonumber(L
, -1);
920 int LuaForeWindowChanged(void)
922 struct fn_def params
[] = {
923 {push_display
, &display
},
924 {push_window
, display
? &D_fore
: &fore
},
929 return LuaCallProcess("fore_changed", params
);
934 LuaCommandExecuted(const char *command, const char **args, int argc)
938 struct fn_def params[] = {
939 {lua_pushstring, command},
940 {push_stringarray, args},
943 return LuaCallProcess("command_executed", params);
946 #define SEVNAME_MAX 30
948 LuaRegEvent(lua_State
*L
)
950 /* signature: hook(obj, event, handler, priv);
951 * or: hook(event, handler, priv)
952 * returns: A ticket for later unregister. */
953 int idx
= 1, argc
= lua_gettop(L
);
954 int priv
= 31; /* Default privilege */
955 struct lua_handler lh
;
958 const char *objname
= "global";
960 static char evbuf
[SEVNAME_MAX
];
963 struct script_event
*sev
;
965 StackDump(L
, "Before RegEvent\n");
967 /* Identify the object, if specified */
968 if (luaL_getmetafield(L
, 1, "_objname"))
970 objname
= luaL_checkstring(L
, -1);
972 if (!strcmp("screen", objname
))
975 obj
= *(char **)lua_touserdata(L
, 1);
979 event
= luaL_checkstring(L
, idx
++);
980 snprintf(evbuf
, SEVNAME_MAX
, "%s_%s", objname
, event
);
982 if (lua_isfunction(L
, idx
))
984 lua_pushvalue(L
, idx
);
985 lh
.u
.reference
= luaL_ref(L
, LUA_REGISTRYINDEX
);
986 lh
.type
= LUA_HANDLER_TYPE_F
;
991 lh
.type
= LUA_HANDLER_TYPE_N
;
992 lh
.u
.name
= SaveStr(luaL_checkstring(L
, idx
++));
995 StackDump(L
, "In RegEvent\n");
998 priv
= luaL_checkinteger(L
, idx
);
1000 sev
= object_get_event(obj
, evbuf
);
1004 l
= (struct listener
*)malloc(sizeof(struct listener
));
1006 return luaL_error(L
, "Out of memory");
1009 l
->dispatcher
= LuaDispatch
;
1010 if (register_listener(sev
, l
))
1013 if (lh
.type
== LUA_HANDLER_TYPE_N
)
1014 return luaL_error(L
, "Handler %s has already been registered", lh
.u
.name
);
1016 return luaL_error(L
, "Handler has already been registered");
1018 /* Return the handler for un-register */
1019 l
->handler
= lua_newuserdata(L
, sizeof(struct lua_handler
));
1020 memcpy(l
->handler
, &lh
, sizeof(struct lua_handler
));
1021 ((struct lua_handler
*)l
->handler
)->listener
= l
;
1022 push_callback(L
, &l
->handler
);
1025 return luaL_error(L
, "Invalid event specified: %s for object %s", event
, objname
);
1027 StackDump(L
, "After RegEvent\n");
1032 LuaUnRegEvent(lua_State
*L
)
1034 /* signature: unhook([obj], ticket)
1035 * returns: true of success, false otherwise */
1039 /* If the param is not as expected */
1040 if (!lua_islightuserdata(L
, idx
))
1042 /* Then it should be the userdata to be ignore, but if not ... */
1043 if (!lua_isuserdata(L
, idx
))
1044 luaL_checktype(L
, idx
, LUA_TLIGHTUSERDATA
);
1046 luaL_checktype(L
, idx
, LUA_TLIGHTUSERDATA
);
1049 l
= (struct listener
*)lua_touserdata(L
, idx
++);
1051 /* Validate the listener structure */
1052 if (!l
|| !l
->handler
)
1055 lua_pushboolean(L
,0);
1059 struct lua_handler
*lh
= l
->handler
;
1060 if (lh
->type
== LUA_HANDLER_TYPE_N
)
1063 unregister_listener(l
);
1064 lua_pushboolean(L
, 1);
1072 struct ScriptFuncs LuaFuncs
=
1074 LuaForeWindowChanged
,
1078 struct binding lua_binding
=