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 #define CHECK_TYPE(name, type) \
86 check_##name(lua_State *L, int index) \
89 luaL_checktype(L, index, LUA_TUSERDATA); \
90 var = (type **) luaL_checkudata(L, index, #name); \
92 luaL_typerror(L, index, #name); \
96 #define PUSH_TYPE(name, type) \
98 push_##name(lua_State *L, type **t) \
105 r = (type **)lua_newuserdata(L, sizeof(type *)); \
107 luaL_getmetatable(L, #name); \
108 lua_setmetatable(L,-2); \
112 /* Much of the following template comes from:
113 * http://lua-users.org/wiki/BindingWithMembersAndMethods
116 static int get_int (lua_State
*L
, void *v
)
118 lua_pushinteger (L
, *(int*)v
);
122 static int set_int (lua_State
*L
, void *v
)
124 *(int*)v
= luaL_checkint(L
, 3);
128 static int get_number (lua_State
*L
, void *v
)
130 lua_pushnumber(L
, *(lua_Number
*)v
);
134 static int set_number (lua_State
*L
, void *v
)
136 *(lua_Number
*)v
= luaL_checknumber(L
, 3);
140 static int get_string (lua_State
*L
, void *v
)
142 lua_pushstring(L
, (char*)v
);
146 static int set_string (lua_State
*L
, void *v
)
148 *(const char**)v
= luaL_checkstring(L
, 3);
152 typedef int (*Xet_func
) (lua_State
*L
, void *v
);
154 /* member info for get and set handlers */
157 const char *name
; /* member name */
158 Xet_func func
; /* get or set function for type of member */
159 size_t offset
; /* offset of member within the struct */
160 int (*absolute
)(lua_State
*);
163 static void Xet_add (lua_State
*L
, const struct Xet_reg
*l
)
169 lua_pushstring(L
, l
->name
);
170 lua_pushlightuserdata(L
, (void*)l
);
175 static int Xet_call (lua_State
*L
)
177 /* for get: stack has userdata, index, lightuserdata */
178 /* for set: stack has userdata, index, value, lightuserdata */
179 const struct Xet_reg
*m
= (const struct Xet_reg
*)lua_touserdata(L
, -1); /* member info */
180 lua_pop(L
, 1); /* drop lightuserdata */
181 luaL_checktype(L
, 1, LUA_TUSERDATA
);
183 return m
->absolute(L
);
184 return m
->func(L
, *(char**)lua_touserdata(L
, 1) + m
->offset
);
187 static int index_handler (lua_State
*L
)
189 /* stack has userdata, index */
190 lua_pushvalue(L
, 2); /* dup index */
191 lua_rawget(L
, lua_upvalueindex(1)); /* lookup member by name */
192 if (!lua_islightuserdata(L
, -1))
194 lua_pop(L
, 1); /* drop value */
195 lua_pushvalue(L
, 2); /* dup index */
196 lua_gettable(L
, lua_upvalueindex(2)); /* else try methods */
197 if (lua_isnil(L
, -1)) /* invalid member */
198 luaL_error(L
, "cannot get member '%s'", lua_tostring(L
, 2));
201 return Xet_call(L
); /* call get function */
204 static int newindex_handler (lua_State
*L
)
206 /* stack has userdata, index, value */
207 lua_pushvalue(L
, 2); /* dup index */
208 lua_rawget(L
, lua_upvalueindex(1)); /* lookup member by name */
209 if (!lua_islightuserdata(L
, -1)) /* invalid member */
210 luaL_error(L
, "cannot set member '%s'", lua_tostring(L
, 2));
211 return Xet_call(L
); /* call set function */
215 struct_register(lua_State
*L
, const char *name
, const luaL_reg fn_methods
[], const luaL_reg meta_methods
[],
216 const struct Xet_reg setters
[], const struct Xet_reg getters
[])
218 int metatable
, methods
;
220 /* create methods table & add it to the table of globals */
221 luaL_register(L
, name
, fn_methods
);
222 methods
= lua_gettop(L
);
224 /* create metatable & add it to the registry */
225 luaL_newmetatable(L
, name
);
226 luaL_register(L
, 0, meta_methods
); /* fill metatable */
228 /* To identify the type of object */
229 lua_pushstring(L
, "_objname");
230 lua_pushstring(L
, name
);
233 metatable
= lua_gettop(L
);
235 lua_pushliteral(L
, "__metatable");
236 lua_pushvalue(L
, methods
); /* dup methods table*/
237 lua_rawset(L
, metatable
); /* hide metatable:
238 metatable.__metatable = methods */
240 lua_pushliteral(L
, "__index");
241 lua_pushvalue(L
, metatable
); /* upvalue index 1 */
242 Xet_add(L
, getters
); /* fill metatable with getters */
243 lua_pushvalue(L
, methods
); /* upvalue index 2 */
244 lua_pushcclosure(L
, index_handler
, 2);
245 lua_rawset(L
, metatable
); /* metatable.__index = index_handler */
247 lua_pushliteral(L
, "__newindex");
248 lua_newtable(L
); /* table for members you can set */
249 Xet_add(L
, setters
); /* fill with setters */
250 lua_pushcclosure(L
, newindex_handler
, 1);
251 lua_rawset(L
, metatable
); /* metatable.__newindex = newindex_handler */
253 lua_pop(L
, 1); /* drop metatable */
254 return 1; /* return methods on the stack */
261 PUSH_TYPE(window
, struct win
)
263 CHECK_TYPE(window
, struct win
)
265 static int get_window(lua_State
*L
, void *v
)
267 push_window(L
, (struct win
**)v
);
272 window_change_title(lua_State
*L
)
274 struct win
*w
= check_window(L
, 1);
276 const char *title
= luaL_checklstring(L
, 2, &len
);
277 ChangeAKA(w
, (char *)title
, len
);
282 window_get_monitor_status(lua_State
*L
)
284 struct win
*w
= check_window(L
, 1);
285 int activity
= luaL_checkint(L
, 2);
288 lua_pushinteger(L
, w
->w_monitor
!= MON_OFF
);
291 lua_pushinteger(L
, w
->w_silence
== SILENCE_ON
? w
->w_silencewait
: 0);
296 static const luaL_reg window_methods
[] = {
297 {"get_monitor_status", window_get_monitor_status
},
298 {"hook", LuaRegEvent
},
303 window_tostring(lua_State
*L
)
306 struct win
*w
= check_window(L
, 1);
307 snprintf(str
, sizeof(str
), "{window #%d: '%s'}", w
->w_number
, w
->w_title
);
308 lua_pushstring(L
, str
);
313 window_equality(lua_State
*L
)
315 struct win
*w1
= check_window(L
, 1), *w2
= check_window(L
, 2);
316 lua_pushboolean(L
, (w1
== w2
|| (w1
&& w2
&& w1
->w_number
== w2
->w_number
)));
320 static const luaL_reg window_metamethods
[] = {
321 {"__tostring", window_tostring
},
322 {"__eq", window_equality
},
326 static const struct Xet_reg window_setters
[] = {
327 {"title", 0, 0, window_change_title
/*absolute setter*/},
331 static const struct Xet_reg window_getters
[] = {
332 {"title", get_string
, offsetof(struct win
, w_title
) + 8},
333 {"number", get_int
, offsetof(struct win
, w_number
)},
334 {"dir", get_string
, offsetof(struct win
, w_dir
)},
335 {"tty", get_string
, offsetof(struct win
, w_tty
)},
336 {"pid", get_int
, offsetof(struct win
, w_pid
)},
337 {"group", get_window
, offsetof(struct win
, w_group
)},
338 {"bell", get_int
, offsetof(struct win
, w_bell
)},
347 PUSH_TYPE(user
, struct acluser
)
349 CHECK_TYPE(user
, struct acluser
)
352 get_user(lua_State
*L
, void *v
)
354 push_user(L
, (struct acluser
**)v
);
358 static const luaL_reg user_methods
[] = {
363 user_tostring(lua_State
*L
)
366 struct acluser
*u
= check_user(L
, 1);
367 snprintf(str
, sizeof(str
), "{user '%s'}", u
->u_name
);
368 lua_pushstring(L
, str
);
372 static const luaL_reg user_metamethods
[] = {
373 {"__tostring", user_tostring
},
377 static const struct Xet_reg user_setters
[] = {
381 static const struct Xet_reg user_getters
[] = {
382 {"name", get_string
, offsetof(struct acluser
, u_name
)},
383 {"password", get_string
, offsetof(struct acluser
, u_password
)},
391 PUSH_TYPE(canvas
, struct canvas
)
393 CHECK_TYPE(canvas
, struct canvas
)
396 get_canvas(lua_State
*L
, void *v
)
398 push_canvas(L
, (struct canvas
**)v
);
403 canvas_select(lua_State
*L
)
405 struct canvas
*c
= check_canvas(L
, 1);
406 if (!display
|| D_forecv
== c
)
408 SetCanvasWindow(c
, Layer2Window(c
->c_layer
));
411 /* XXX: the following all is duplicated from process.c:DoAction.
412 * Should these be in some better place?
414 ResizeCanvas(&D_canvas
);
415 RecreateCanvasChain();
416 RethinkDisplayViewports();
417 ResizeLayersToCanvases(); /* redisplays */
418 fore
= D_fore
= Layer2Window(D_forecv
->c_layer
);
419 flayer
= D_forecv
->c_layer
;
421 if (D_xtermosc
[2] || D_xtermosc
[3])
431 flayer
= D_forecv
->c_layer
;
432 CV_CALL(D_forecv
, LayRestore();LaySetCursor());
433 WindowChanged(0, 'F');
437 static const luaL_reg canvas_methods
[] = {
438 {"select", canvas_select
},
442 static const luaL_reg canvas_metamethods
[] = {
446 static const struct Xet_reg canvas_setters
[] = {
451 canvas_get_window(lua_State
*L
)
453 struct canvas
*c
= check_canvas(L
, 1);
454 struct win
*win
= Layer2Window(c
->c_layer
);
456 push_window(L
, &win
);
462 static const struct Xet_reg canvas_getters
[] = {
463 {"next", get_canvas
, offsetof(struct canvas
, c_next
)},
464 {"xoff", get_int
, offsetof(struct canvas
, c_xoff
)},
465 {"yoff", get_int
, offsetof(struct canvas
, c_yoff
)},
466 {"xs", get_int
, offsetof(struct canvas
, c_xs
)},
467 {"ys", get_int
, offsetof(struct canvas
, c_ys
)},
468 {"xe", get_int
, offsetof(struct canvas
, c_xe
)},
469 {"ye", get_int
, offsetof(struct canvas
, c_ye
)},
470 {"window", 0, 0, canvas_get_window
},
478 PUSH_TYPE(layout
, struct layout
)
479 CHECK_TYPE(layout
, struct layout
)
481 static const struct Xet_reg layout_getters
[] = {
486 get_layout(lua_State
*L
, void *v
)
488 push_layout(L
, (struct layout
**)v
);
496 PUSH_TYPE(display
, struct display
)
498 CHECK_TYPE(display
, struct display
)
501 display_get_canvases(lua_State
*L
)
507 d
= check_display(L
, 1);
509 for (iter
= d
->d_cvlist
, count
= 0; iter
; iter
= iter
->c_next
, count
++) {
510 lua_pushinteger(L
, count
);
511 push_canvas(L
, &iter
);
518 static const luaL_reg display_methods
[] = {
519 {"get_canvases", display_get_canvases
},
524 display_tostring(lua_State
*L
)
527 struct display
*d
= check_display(L
, 1);
528 snprintf(str
, sizeof(str
), "{display: tty = '%s', term = '%s'}", d
->d_usertty
, d
->d_termname
);
529 lua_pushstring(L
, str
);
533 static const luaL_reg display_metamethods
[] = {
534 {"__tostring", display_tostring
},
538 static const struct Xet_reg display_setters
[] = {
542 static const struct Xet_reg display_getters
[] = {
543 {"tty", get_string
, offsetof(struct display
, d_usertty
)},
544 {"term", get_string
, offsetof(struct display
, d_termname
)},
545 {"fore", get_window
, offsetof(struct display
, d_fore
)},
546 {"other", get_window
, offsetof(struct display
, d_other
)},
547 {"width", get_int
, offsetof(struct display
, d_width
)},
548 {"height", get_int
, offsetof(struct display
, d_height
)},
549 {"user", get_user
, offsetof(struct display
, d_user
)},
550 {"layout", get_layout
, offsetof(struct display
, d_layout
)},
559 screen_get_windows(lua_State
*L
)
565 for (iter
= windows
, count
= 0; iter
; iter
= iter
->w_next
, count
++) {
566 lua_pushinteger(L
, iter
->w_number
);
567 push_window(L
, &iter
);
575 screen_get_displays(lua_State
*L
)
577 struct display
*iter
;
581 for (iter
= displays
, count
= 0; iter
; iter
= iter
->d_next
, count
++) {
582 lua_pushinteger(L
, count
);
583 push_display(L
, &iter
);
591 screen_get_display(lua_State
*L
)
593 push_display(L
, &display
);
598 screen_exec_command(lua_State
*L
)
603 command
= luaL_checklstring(L
, 1, &len
);
605 RcLine((char *)command
, len
);
611 screen_append_msg(lua_State
*L
)
613 const char *msg
, *color
;
615 msg
= luaL_checklstring(L
, 1, &len
);
619 color
= luaL_checklstring(L
, 2, &len
);
620 AppendWinMsgRend(msg
, color
);
624 static const luaL_reg screen_methods
[] = {
625 {"windows", screen_get_windows
},
626 {"displays", screen_get_displays
},
627 {"display", screen_get_display
},
628 {"command", screen_exec_command
},
629 {"append_msg", screen_append_msg
},
630 {"hook", LuaRegEvent
},
631 {"unhook", LuaUnRegEvent
},
635 static const luaL_reg screen_metamethods
[] = {
639 static const struct Xet_reg screen_setters
[] = {
643 static const struct Xet_reg screen_getters
[] = {
649 /** Public functions {{{ */
657 #define REGISTER(X) struct_register(L, #X , X ## _methods, X##_metamethods, X##_setters, X##_getters)
668 /* An error message on top of the stack. */
670 LuaShowErr(lua_State
*L
)
672 struct display
*d
= display
;
674 const char *message
= luaL_checklstring(L
, -1, &len
);
675 LMsg(0, "%s", message
? message
: "Unknown error");
682 void (*push_fn
)(lua_State
*, void*);
687 LuaCallProcess(const char *name
, struct fn_def defs
[])
691 lua_getfield(L
, LUA_GLOBALSINDEX
, name
);
692 if (lua_isnil(L
, -1))
694 for (argc
= 0; defs
[argc
].push_fn
; argc
++)
695 defs
[argc
].push_fn(L
, defs
[argc
].value
);
696 if (lua_pcall(L
, argc
, 0, 0) == LUA_ERRRUN
&& lua_isstring(L
, -1))
704 int LuaSource(const char *file
, int async
)
709 if (stat(file
, &st
) == -1)
710 Msg(errno
, "Error loading lua script file '%s'", file
);
713 int len
= strlen(file
);
714 if (len
< 4 || strncmp(file
+ len
- 4, ".lua", 4) != 0)
716 if (luaL_dofile(L
, file
) && lua_isstring(L
, -1))
735 LuaProcessCaption(const char *caption
, struct win
*win
, int len
)
739 struct fn_def params
[] = {
740 {lua_pushstring
, caption
},
742 {lua_pushinteger
, len
},
745 return LuaCallProcess("process_caption", params
);
749 push_stringarray(lua_State
*L
, char **args
)
753 for (i
= 1; args
&& *args
; i
++) {
754 lua_pushinteger(L
, i
);
755 lua_pushstring(L
, *args
++);
761 LuaPushParams(lua_State
*L
, const char *params
, va_list va
)
769 lua_pushstring(L
, va_arg(va
, char *));
772 push_stringarray(L
, va_arg(va
, char **));
775 lua_pushinteger(L
, va_arg(va
, int));
783 int LuaCall(char *func
, char **argv
)
789 StackDump(L
, "Before LuaCall\n");
790 lua_getfield(L
, LUA_GLOBALSINDEX
, func
);
791 if (lua_isnil(L
, -1))
793 lua_pushstring(L
, "Could not find the script function\n");
797 for (argc
= 0; *argv
; argv
++, argc
++)
799 lua_pushstring(L
, *argv
);
801 if (lua_pcall(L
, argc
, 0, 0) == LUA_ERRRUN
)
803 if(lua_isstring(L
, -1))
805 StackDump(L
, "After LuaCall\n");
814 LuaDispatch(void *handler
, const char *params
, va_list va
)
816 const char *func
= handler
;
819 lua_getfield(L
, LUA_GLOBALSINDEX
, func
);
820 if (lua_isnil(L
, -1))
822 argc
= LuaPushParams(L
, params
, va
);
824 if (lua_pcall(L
, argc
, 0, 0) == LUA_ERRRUN
&& lua_isstring(L
, -1))
826 StackDump(L
, "After LuaDispatch\n");
833 int LuaForeWindowChanged(void)
835 struct fn_def params
[] = {
836 {push_display
, &display
},
837 {push_window
, display
? &D_fore
: &fore
},
842 return LuaCallProcess("fore_changed", params
);
847 LuaCommandExecuted(const char *command, const char **args, int argc)
851 struct fn_def params[] = {
852 {lua_pushstring, command},
853 {push_stringarray, args},
856 return LuaCallProcess("command_executed", params);
859 #define SEVNAME_MAX 30
861 LuaRegEvent(lua_State
*L
)
863 /* signature: hook(obj, event, handler, priv);
864 * or: hook(event, handler, priv)
865 * returns: A ticket for later unregister. */
866 int idx
= 1, argc
= lua_gettop(L
);
867 int priv
= 31; /* Default privilege */
870 const char *objname
= "global";
872 static char evbuf
[SEVNAME_MAX
];
873 const char *event
, *handler
;
875 struct script_event
*sev
;
877 StackDump(L
, "Before RegEvent\n");
879 /* Identify the object, if specified */
880 if (luaL_getmetafield(L
, 1, "_objname"))
882 objname
= luaL_checkstring(L
, -1);
884 if (!strcmp("screen", objname
))
887 obj
= *(char **)lua_touserdata(L
, 1);
891 event
= luaL_checkstring(L
, idx
++);
892 snprintf(evbuf
, SEVNAME_MAX
, "%s_%s", objname
, event
);
893 handler
= luaL_checkstring(L
, idx
++);
895 StackDump(L
, "In RegEvent\n");
898 priv
= luaL_checkinteger(L
, idx
);
900 sev
= object_get_event(obj
, evbuf
);
904 l
= (struct listener
*)malloc(sizeof(struct listener
));
906 return luaL_error(L
, "Out of memory");
907 l
->handler
= (void *)handler
;
909 l
->dispatcher
= LuaDispatch
;
910 if (register_listener(sev
, l
))
913 return luaL_error(L
, "Handler %s has already been registered", handler
);
915 /*Return the handler for un-register*/
916 lua_pushlightuserdata(L
, l
);
919 return luaL_error(L
, "Invalid event specified: %s for object %s", event
, objname
);
921 StackDump(L
, "After RegEvent\n");
926 LuaUnRegEvent(lua_State
*L
)
928 /* signature: release([obj], ticket, handler)
929 * returns: true of success, false otherwise */
934 /* If the param is not as expected */
935 if (!lua_islightuserdata(L
, idx
))
937 /* Then it should be the userdata to be ignore, but if not ... */
938 if (!lua_isuserdata(L
, idx
))
939 luaL_checktype(L
, idx
, LUA_TLIGHTUSERDATA
);
941 luaL_checktype(L
, idx
, LUA_TLIGHTUSERDATA
);
944 l
= (struct listener
*)lua_touserdata(L
, idx
++);
945 handler
= luaL_checkstring(L
, idx
++);
947 /*Validate the listener structure*/
948 if (!l
|| !l
->handler
949 || strncmp((char *)handler
, (char *)l
->handler
, SEVNAME_MAX
))
952 lua_pushboolean(L
,0);
956 unregister_listener(l
);
957 lua_pushboolean(L
, 1);
965 struct ScriptFuncs LuaFuncs
=
967 LuaForeWindowChanged
,
971 struct binding lua_binding
=