1 /* Lua scripting support
3 * Copyright (c) 2008 Sadrul Habib Chowdhury (sadrul@users.sf.net)
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 3, or (at your option)
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program (see the file COPYING); if not, write to the
17 * Free Software Foundation, Inc.,
18 * 51 Franklin Street, Fifth Floor, Boston, MA 02111-1301 USA
20 ****************************************************************
22 #include <sys/types.h>
39 static int StackDump(lua_State
*L
, const char *message
)
41 FILE *f
= fopen("/tmp/debug/stack", "ab");
42 int i
= lua_gettop(L
);
44 fprintf(f
, "%s", message
);
47 int t
= lua_type(L
, i
);
51 fprintf(f
, "String: %s\n", lua_tostring(L
, i
));
55 fprintf(f
, "Boolean: %s\n", lua_toboolean(L
, i
) ? "true" : "false");
59 fprintf(f
, "Number: %g\n", lua_tonumber(L
, i
));
63 fprintf(f
, "Type: %s\n", lua_typename(L
, t
));
73 extern struct win
*windows
, *fore
;
74 extern struct display
*displays
, *display
;
75 extern struct LayFuncs WinLf
;
76 extern struct layer
*flayer
;
78 static int LuaDispatch(void *handler
, const char *params
, va_list va
);
79 static int LuaRegEvent(lua_State
*L
);
80 static int LuaUnRegEvent(lua_State
*L
);
84 LUA_HANDLER_TYPE_N
= 1,
100 #define CHECK_TYPE(name, type) \
102 check_##name(lua_State *L, int index) \
105 luaL_checktype(L, index, LUA_TUSERDATA); \
106 var = (type **) luaL_checkudata(L, index, #name); \
108 luaL_typerror(L, index, #name); \
112 #define PUSH_TYPE(name, type) \
114 push_##name(lua_State *L, type **t) \
121 r = (type **)lua_newuserdata(L, sizeof(type *)); \
123 luaL_getmetatable(L, #name); \
124 lua_setmetatable(L,-2); \
128 /* Much of the following template comes from:
129 * http://lua-users.org/wiki/BindingWithMembersAndMethods
132 static int get_int (lua_State
*L
, void *v
)
134 lua_pushinteger (L
, *(int*)v
);
138 static int set_int (lua_State
*L
, void *v
)
140 *(int*)v
= luaL_checkint(L
, 3);
144 static int get_number (lua_State
*L
, void *v
)
146 lua_pushnumber(L
, *(lua_Number
*)v
);
150 static int set_number (lua_State
*L
, void *v
)
152 *(lua_Number
*)v
= luaL_checknumber(L
, 3);
156 static int get_string (lua_State
*L
, void *v
)
158 lua_pushstring(L
, (char*)v
);
162 static int set_string (lua_State
*L
, void *v
)
164 *(const char**)v
= luaL_checkstring(L
, 3);
168 typedef int (*Xet_func
) (lua_State
*L
, void *v
);
170 /* member info for get and set handlers */
173 const char *name
; /* member name */
174 Xet_func func
; /* get or set function for type of member */
175 size_t offset
; /* offset of member within the struct */
176 int (*absolute
)(lua_State
*);
179 static void Xet_add (lua_State
*L
, const struct Xet_reg
*l
)
185 lua_pushstring(L
, l
->name
);
186 lua_pushlightuserdata(L
, (void*)l
);
191 static int Xet_call (lua_State
*L
)
193 /* for get: stack has userdata, index, lightuserdata */
194 /* for set: stack has userdata, index, value, lightuserdata */
195 const struct Xet_reg
*m
= (const struct Xet_reg
*)lua_touserdata(L
, -1); /* member info */
196 lua_pop(L
, 1); /* drop lightuserdata */
197 luaL_checktype(L
, 1, LUA_TUSERDATA
);
199 return m
->absolute(L
);
200 return m
->func(L
, *(char**)lua_touserdata(L
, 1) + m
->offset
);
203 static int index_handler (lua_State
*L
)
205 /* stack has userdata, index */
206 lua_pushvalue(L
, 2); /* dup index */
207 lua_rawget(L
, lua_upvalueindex(1)); /* lookup member by name */
208 if (!lua_islightuserdata(L
, -1))
210 lua_pop(L
, 1); /* drop value */
211 lua_pushvalue(L
, 2); /* dup index */
212 lua_gettable(L
, lua_upvalueindex(2)); /* else try methods */
213 if (lua_isnil(L
, -1)) /* invalid member */
214 luaL_error(L
, "cannot get member '%s'", lua_tostring(L
, 2));
217 return Xet_call(L
); /* call get function */
220 static int newindex_handler (lua_State
*L
)
222 /* stack has userdata, index, value */
223 lua_pushvalue(L
, 2); /* dup index */
224 lua_rawget(L
, lua_upvalueindex(1)); /* lookup member by name */
225 if (!lua_islightuserdata(L
, -1)) /* invalid member */
226 luaL_error(L
, "cannot set member '%s'", lua_tostring(L
, 2));
227 return Xet_call(L
); /* call set function */
231 struct_register(lua_State
*L
, const char *name
, const luaL_reg fn_methods
[], const luaL_reg meta_methods
[],
232 const struct Xet_reg setters
[], const struct Xet_reg getters
[])
234 int metatable
, methods
;
236 /* create methods table & add it to the table of globals */
237 luaL_register(L
, name
, fn_methods
);
238 methods
= lua_gettop(L
);
240 /* create metatable & add it to the registry */
241 luaL_newmetatable(L
, name
);
242 luaL_register(L
, 0, meta_methods
); /* fill metatable */
244 /* To identify the type of object */
245 lua_pushstring(L
, "_objname");
246 lua_pushstring(L
, name
);
249 metatable
= lua_gettop(L
);
251 lua_pushliteral(L
, "__metatable");
252 lua_pushvalue(L
, methods
); /* dup methods table*/
253 lua_rawset(L
, metatable
); /* hide metatable:
254 metatable.__metatable = methods */
256 lua_pushliteral(L
, "__index");
257 lua_pushvalue(L
, metatable
); /* upvalue index 1 */
258 Xet_add(L
, getters
); /* fill metatable with getters */
259 lua_pushvalue(L
, methods
); /* upvalue index 2 */
260 lua_pushcclosure(L
, index_handler
, 2);
261 lua_rawset(L
, metatable
); /* metatable.__index = index_handler */
263 lua_pushliteral(L
, "__newindex");
264 lua_newtable(L
); /* table for members you can set */
265 Xet_add(L
, setters
); /* fill with setters */
266 lua_pushcclosure(L
, newindex_handler
, 1);
267 lua_rawset(L
, metatable
); /* metatable.__newindex = newindex_handler */
269 lua_pop(L
, 1); /* drop metatable */
270 return 1; /* return methods on the stack */
277 PUSH_TYPE(window
, struct win
)
279 CHECK_TYPE(window
, struct win
)
281 static int get_window(lua_State
*L
, void *v
)
283 push_window(L
, (struct win
**)v
);
288 window_change_title(lua_State
*L
)
290 struct win
*w
= check_window(L
, 1);
292 const char *title
= luaL_checklstring(L
, 2, &len
);
293 ChangeAKA(w
, (char *)title
, len
);
298 window_get_monitor_status(lua_State
*L
)
300 struct win
*w
= check_window(L
, 1);
301 int activity
= luaL_checkint(L
, 2);
304 lua_pushinteger(L
, w
->w_monitor
!= MON_OFF
);
307 lua_pushinteger(L
, w
->w_silence
== SILENCE_ON
? w
->w_silencewait
: 0);
312 static const luaL_reg window_methods
[] = {
313 {"get_monitor_status", window_get_monitor_status
},
314 {"hook", LuaRegEvent
},
319 window_tostring(lua_State
*L
)
322 struct win
*w
= check_window(L
, 1);
323 snprintf(str
, sizeof(str
), "{window #%d: '%s'}", w
->w_number
, w
->w_title
);
324 lua_pushstring(L
, str
);
329 window_equality(lua_State
*L
)
331 struct win
*w1
= check_window(L
, 1), *w2
= check_window(L
, 2);
332 lua_pushboolean(L
, (w1
== w2
|| (w1
&& w2
&& w1
->w_number
== w2
->w_number
)));
336 static const luaL_reg window_metamethods
[] = {
337 {"__tostring", window_tostring
},
338 {"__eq", window_equality
},
342 static const struct Xet_reg window_setters
[] = {
343 {"title", 0, 0, window_change_title
/*absolute setter*/},
347 static const struct Xet_reg window_getters
[] = {
348 {"title", get_string
, offsetof(struct win
, w_title
) + 8},
349 {"number", get_int
, offsetof(struct win
, w_number
)},
350 {"dir", get_string
, offsetof(struct win
, w_dir
)},
351 {"tty", get_string
, offsetof(struct win
, w_tty
)},
352 {"pid", get_int
, offsetof(struct win
, w_pid
)},
353 {"group", get_window
, offsetof(struct win
, w_group
)},
354 {"bell", get_int
, offsetof(struct win
, w_bell
)},
363 PUSH_TYPE(user
, struct acluser
)
365 CHECK_TYPE(user
, struct acluser
)
368 get_user(lua_State
*L
, void *v
)
370 push_user(L
, (struct acluser
**)v
);
374 static const luaL_reg user_methods
[] = {
379 user_tostring(lua_State
*L
)
382 struct acluser
*u
= check_user(L
, 1);
383 snprintf(str
, sizeof(str
), "{user '%s'}", u
->u_name
);
384 lua_pushstring(L
, str
);
388 static const luaL_reg user_metamethods
[] = {
389 {"__tostring", user_tostring
},
393 static const struct Xet_reg user_setters
[] = {
397 static const struct Xet_reg user_getters
[] = {
398 {"name", get_string
, offsetof(struct acluser
, u_name
)},
399 {"password", get_string
, offsetof(struct acluser
, u_password
)},
407 PUSH_TYPE(canvas
, struct canvas
)
409 CHECK_TYPE(canvas
, struct canvas
)
412 get_canvas(lua_State
*L
, void *v
)
414 push_canvas(L
, (struct canvas
**)v
);
419 canvas_select(lua_State
*L
)
421 struct canvas
*c
= check_canvas(L
, 1);
422 if (!display
|| D_forecv
== c
)
424 SetCanvasWindow(c
, Layer2Window(c
->c_layer
));
427 /* XXX: the following all is duplicated from process.c:DoAction.
428 * Should these be in some better place?
430 ResizeCanvas(&D_canvas
);
431 RecreateCanvasChain();
432 RethinkDisplayViewports();
433 ResizeLayersToCanvases(); /* redisplays */
434 fore
= D_fore
= Layer2Window(D_forecv
->c_layer
);
435 flayer
= D_forecv
->c_layer
;
437 if (D_xtermosc
[2] || D_xtermosc
[3])
447 flayer
= D_forecv
->c_layer
;
448 CV_CALL(D_forecv
, LayRestore();LaySetCursor());
449 WindowChanged(0, 'F');
453 static const luaL_reg canvas_methods
[] = {
454 {"select", canvas_select
},
458 static const luaL_reg canvas_metamethods
[] = {
462 static const struct Xet_reg canvas_setters
[] = {
467 canvas_get_window(lua_State
*L
)
469 struct canvas
*c
= check_canvas(L
, 1);
470 struct win
*win
= Layer2Window(c
->c_layer
);
472 push_window(L
, &win
);
478 static const struct Xet_reg canvas_getters
[] = {
479 {"next", get_canvas
, offsetof(struct canvas
, c_next
)},
480 {"xoff", get_int
, offsetof(struct canvas
, c_xoff
)},
481 {"yoff", get_int
, offsetof(struct canvas
, c_yoff
)},
482 {"xs", get_int
, offsetof(struct canvas
, c_xs
)},
483 {"ys", get_int
, offsetof(struct canvas
, c_ys
)},
484 {"xe", get_int
, offsetof(struct canvas
, c_xe
)},
485 {"ye", get_int
, offsetof(struct canvas
, c_ye
)},
486 {"window", 0, 0, canvas_get_window
},
494 PUSH_TYPE(layout
, struct layout
)
495 CHECK_TYPE(layout
, struct layout
)
497 static const struct Xet_reg layout_getters
[] = {
502 get_layout(lua_State
*L
, void *v
)
504 push_layout(L
, (struct layout
**)v
);
512 PUSH_TYPE(display
, struct display
)
514 CHECK_TYPE(display
, struct display
)
517 display_get_canvases(lua_State
*L
)
523 d
= check_display(L
, 1);
525 for (iter
= d
->d_cvlist
, count
= 0; iter
; iter
= iter
->c_next
, count
++) {
526 lua_pushinteger(L
, count
);
527 push_canvas(L
, &iter
);
534 static const luaL_reg display_methods
[] = {
535 {"get_canvases", display_get_canvases
},
540 display_tostring(lua_State
*L
)
543 struct display
*d
= check_display(L
, 1);
544 snprintf(str
, sizeof(str
), "{display: tty = '%s', term = '%s'}", d
->d_usertty
, d
->d_termname
);
545 lua_pushstring(L
, str
);
549 static const luaL_reg display_metamethods
[] = {
550 {"__tostring", display_tostring
},
554 static const struct Xet_reg display_setters
[] = {
558 static const struct Xet_reg display_getters
[] = {
559 {"tty", get_string
, offsetof(struct display
, d_usertty
)},
560 {"term", get_string
, offsetof(struct display
, d_termname
)},
561 {"fore", get_window
, offsetof(struct display
, d_fore
)},
562 {"other", get_window
, offsetof(struct display
, d_other
)},
563 {"width", get_int
, offsetof(struct display
, d_width
)},
564 {"height", get_int
, offsetof(struct display
, d_height
)},
565 {"user", get_user
, offsetof(struct display
, d_user
)},
566 {"layout", get_layout
, offsetof(struct display
, d_layout
)},
575 screen_get_windows(lua_State
*L
)
581 for (iter
= windows
, count
= 0; iter
; iter
= iter
->w_next
, count
++) {
582 lua_pushinteger(L
, iter
->w_number
);
583 push_window(L
, &iter
);
591 screen_get_displays(lua_State
*L
)
593 struct display
*iter
;
597 for (iter
= displays
, count
= 0; iter
; iter
= iter
->d_next
, count
++) {
598 lua_pushinteger(L
, count
);
599 push_display(L
, &iter
);
607 screen_get_display(lua_State
*L
)
609 push_display(L
, &display
);
614 screen_exec_command(lua_State
*L
)
619 command
= luaL_checklstring(L
, 1, &len
);
621 RcLine((char *)command
, len
);
627 screen_append_msg(lua_State
*L
)
629 const char *msg
, *color
;
631 msg
= luaL_checklstring(L
, 1, &len
);
635 color
= luaL_checklstring(L
, 2, &len
);
636 AppendWinMsgRend(msg
, color
);
640 static const luaL_reg screen_methods
[] = {
641 {"windows", screen_get_windows
},
642 {"displays", screen_get_displays
},
643 {"display", screen_get_display
},
644 {"command", screen_exec_command
},
645 {"append_msg", screen_append_msg
},
646 {"hook", LuaRegEvent
},
647 {"unhook", LuaUnRegEvent
},
651 static const luaL_reg screen_metamethods
[] = {
655 static const struct Xet_reg screen_setters
[] = {
659 static const struct Xet_reg screen_getters
[] = {
665 /** Public functions {{{ */
673 #define REGISTER(X) struct_register(L, #X , X ## _methods, X##_metamethods, X##_setters, X##_getters)
684 /* An error message on top of the stack. */
686 LuaShowErr(lua_State
*L
)
688 struct display
*d
= display
;
690 const char *message
= luaL_checklstring(L
, -1, &len
);
691 LMsg(0, "%s", message
? message
: "Unknown error");
698 void (*push_fn
)(lua_State
*, void*);
703 LuaCallProcess(const char *name
, struct fn_def defs
[])
707 lua_getfield(L
, LUA_GLOBALSINDEX
, name
);
708 if (lua_isnil(L
, -1))
710 for (argc
= 0; defs
[argc
].push_fn
; argc
++)
711 defs
[argc
].push_fn(L
, defs
[argc
].value
);
712 if (lua_pcall(L
, argc
, 0, 0) == LUA_ERRRUN
&& lua_isstring(L
, -1))
720 int LuaSource(const char *file
, int async
)
725 if (stat(file
, &st
) == -1)
726 Msg(errno
, "Error loading lua script file '%s'", file
);
729 int len
= strlen(file
);
730 if (len
< 4 || strncmp(file
+ len
- 4, ".lua", 4) != 0)
732 if (luaL_dofile(L
, file
) && lua_isstring(L
, -1))
751 LuaProcessCaption(const char *caption
, struct win
*win
, int len
)
755 struct fn_def params
[] = {
756 {lua_pushstring
, caption
},
758 {lua_pushinteger
, len
},
761 return LuaCallProcess("process_caption", params
);
765 push_stringarray(lua_State
*L
, char **args
)
769 for (i
= 1; args
&& *args
; i
++) {
770 lua_pushinteger(L
, i
);
771 lua_pushstring(L
, *args
++);
777 LuaPushParams(lua_State
*L
, const char *params
, va_list va
)
785 lua_pushstring(L
, va_arg(va
, char *));
788 push_stringarray(L
, va_arg(va
, char **));
791 lua_pushinteger(L
, va_arg(va
, int));
795 struct display
*d
= va_arg(va
, struct display
*);
806 int LuaCall(char *func
, char **argv
)
812 StackDump(L
, "Before LuaCall\n");
813 lua_getfield(L
, LUA_GLOBALSINDEX
, func
);
814 if (lua_isnil(L
, -1))
816 lua_pushstring(L
, "Could not find the script function\n");
820 for (argc
= 0; *argv
; argv
++, argc
++)
822 lua_pushstring(L
, *argv
);
824 if (lua_pcall(L
, argc
, 0, 0) == LUA_ERRRUN
)
826 if(lua_isstring(L
, -1))
828 StackDump(L
, "After LuaCall\n");
837 LuaDispatch(void *handler
, const char *params
, va_list va
)
839 struct lua_handler
*lh
= handler
;
842 if (lh
->type
== LUA_HANDLER_TYPE_N
)
843 lua_getfield(L
, LUA_GLOBALSINDEX
, lh
->u
.name
);
845 lua_rawgeti(L
, LUA_REGISTRYINDEX
, lh
->u
.reference
);
847 if (lua_isnil(L
, -1))
849 argc
= LuaPushParams(L
, params
, va
);
851 if (lua_pcall(L
, argc
, 1, 0) == LUA_ERRRUN
&& lua_isstring(L
, -1))
853 StackDump(L
, "After LuaDispatch\n");
857 retvalue
= lua_tonumber(L
, -1);
862 int LuaForeWindowChanged(void)
864 struct fn_def params
[] = {
865 {push_display
, &display
},
866 {push_window
, display
? &D_fore
: &fore
},
871 return LuaCallProcess("fore_changed", params
);
876 LuaCommandExecuted(const char *command, const char **args, int argc)
880 struct fn_def params[] = {
881 {lua_pushstring, command},
882 {push_stringarray, args},
885 return LuaCallProcess("command_executed", params);
888 #define SEVNAME_MAX 30
890 LuaRegEvent(lua_State
*L
)
892 /* signature: hook(obj, event, handler, priv);
893 * or: hook(event, handler, priv)
894 * returns: A ticket for later unregister. */
895 int idx
= 1, argc
= lua_gettop(L
);
896 int priv
= 31; /* Default privilege */
897 struct lua_handler lh
;
900 const char *objname
= "global";
902 static char evbuf
[SEVNAME_MAX
];
905 struct script_event
*sev
;
907 StackDump(L
, "Before RegEvent\n");
909 /* Identify the object, if specified */
910 if (luaL_getmetafield(L
, 1, "_objname"))
912 objname
= luaL_checkstring(L
, -1);
914 if (!strcmp("screen", objname
))
917 obj
= *(char **)lua_touserdata(L
, 1);
921 event
= luaL_checkstring(L
, idx
++);
922 snprintf(evbuf
, SEVNAME_MAX
, "%s_%s", objname
, event
);
924 if (lua_isfunction(L
, idx
))
926 lua_pushvalue(L
, idx
);
927 lh
.u
.reference
= luaL_ref(L
, LUA_REGISTRYINDEX
);
928 lh
.type
= LUA_HANDLER_TYPE_F
;
933 lh
.type
= LUA_HANDLER_TYPE_N
;
934 lh
.u
.name
= SaveStr(luaL_checkstring(L
, idx
++));
937 StackDump(L
, "In RegEvent\n");
940 priv
= luaL_checkinteger(L
, idx
);
942 sev
= object_get_event(obj
, evbuf
);
946 l
= (struct listener
*)malloc(sizeof(struct listener
));
948 return luaL_error(L
, "Out of memory");
951 l
->dispatcher
= LuaDispatch
;
952 if (register_listener(sev
, l
))
955 if (lh
.type
== LUA_HANDLER_TYPE_N
)
956 return luaL_error(L
, "Handler %s has already been registered", lh
.u
.name
);
958 return luaL_error(L
, "Handler has already been registered");
960 /* Return the handler for un-register */
961 l
->handler
= malloc(sizeof(struct lua_handler
));
962 memcpy(l
->handler
, &lh
, sizeof(struct lua_handler
));
963 lua_pushlightuserdata(L
, l
);
966 return luaL_error(L
, "Invalid event specified: %s for object %s", event
, objname
);
968 StackDump(L
, "After RegEvent\n");
973 LuaUnRegEvent(lua_State
*L
)
975 /* signature: unhook([obj], ticket)
976 * returns: true of success, false otherwise */
980 /* If the param is not as expected */
981 if (!lua_islightuserdata(L
, idx
))
983 /* Then it should be the userdata to be ignore, but if not ... */
984 if (!lua_isuserdata(L
, idx
))
985 luaL_checktype(L
, idx
, LUA_TLIGHTUSERDATA
);
987 luaL_checktype(L
, idx
, LUA_TLIGHTUSERDATA
);
990 l
= (struct listener
*)lua_touserdata(L
, idx
++);
992 /* Validate the listener structure */
993 if (!l
|| !l
->handler
)
996 lua_pushboolean(L
,0);
1000 struct lua_handler
*lh
= l
->handler
;
1001 if (lh
->type
== LUA_HANDLER_TYPE_N
)
1004 unregister_listener(l
);
1005 lua_pushboolean(L
, 1);
1013 struct ScriptFuncs LuaFuncs
=
1015 LuaForeWindowChanged
,
1019 struct binding lua_binding
=