Added an empty Layout object interface to Lua script.
[screen-lua.git] / src / lua.c
blob083d042b0d7d621944e72c6c6b6fe113eec8f815
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)
8 * any later version.
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>
23 #include "config.h"
24 #include "screen.h"
25 #include <sys/stat.h>
26 #include <unistd.h>
28 #include <stdio.h>
29 #include <string.h>
30 #include <stdlib.h>
32 #include "extern.h"
33 #include "logfile.h"
35 #include <lua.h>
36 #include <lauxlib.h>
37 #include <lualib.h>
39 extern struct win *windows, *fore;
40 extern struct display *displays, *display;
41 extern struct LayFuncs WinLf;
42 extern struct layer *flayer;
44 /** Template {{{ */
46 #define CHECK_TYPE(name, type) \
47 static type * \
48 check_##name(lua_State *L, int index) \
49 { \
50 type **var; \
51 luaL_checktype(L, index, LUA_TUSERDATA); \
52 var = (type **) luaL_checkudata(L, index, #name); \
53 if (!var || !*var) \
54 luaL_typerror(L, index, #name); \
55 return *var; \
58 #define PUSH_TYPE(name, type) \
59 static void \
60 push_##name(lua_State *L, type **t) \
61 { \
62 if (!t || !*t) \
63 lua_pushnil(L); \
64 else \
65 { \
66 type **r; \
67 r = (type **)lua_newuserdata(L, sizeof(type *)); \
68 *r = *t; \
69 luaL_getmetatable(L, #name); \
70 lua_setmetatable(L,-2); \
71 } \
74 /* Much of the following template comes from:
75 * http://lua-users.org/wiki/BindingWithMembersAndMethods
78 static int get_int (lua_State *L, void *v)
80 lua_pushinteger (L, *(int*)v);
81 return 1;
84 static int set_int (lua_State *L, void *v)
86 *(int*)v = luaL_checkint(L, 3);
87 return 0;
90 static int get_number (lua_State *L, void *v)
92 lua_pushnumber(L, *(lua_Number*)v);
93 return 1;
96 static int set_number (lua_State *L, void *v)
98 *(lua_Number*)v = luaL_checknumber(L, 3);
99 return 0;
102 static int get_string (lua_State *L, void *v)
104 lua_pushstring(L, (char*)v );
105 return 1;
108 static int set_string (lua_State *L, void *v)
110 *(const char**)v = luaL_checkstring(L, 3);
111 return 0;
114 typedef int (*Xet_func) (lua_State *L, void *v);
116 /* member info for get and set handlers */
117 struct Xet_reg
119 const char *name; /* member name */
120 Xet_func func; /* get or set function for type of member */
121 size_t offset; /* offset of member within the struct */
122 int (*absolute)(lua_State *);
125 static void Xet_add (lua_State *L, const struct Xet_reg *l)
127 if (!l)
128 return;
129 for (; l->name; l++)
131 lua_pushstring(L, l->name);
132 lua_pushlightuserdata(L, (void*)l);
133 lua_settable(L, -3);
137 static int Xet_call (lua_State *L)
139 /* for get: stack has userdata, index, lightuserdata */
140 /* for set: stack has userdata, index, value, lightuserdata */
141 const struct Xet_reg *m = (const struct Xet_reg *)lua_touserdata(L, -1); /* member info */
142 lua_pop(L, 1); /* drop lightuserdata */
143 luaL_checktype(L, 1, LUA_TUSERDATA);
144 if (m->absolute)
145 return m->absolute(L);
146 return m->func(L, *(char**)lua_touserdata(L, 1) + m->offset);
149 static int index_handler (lua_State *L)
151 /* stack has userdata, index */
152 lua_pushvalue(L, 2); /* dup index */
153 lua_rawget(L, lua_upvalueindex(1)); /* lookup member by name */
154 if (!lua_islightuserdata(L, -1))
156 lua_pop(L, 1); /* drop value */
157 lua_pushvalue(L, 2); /* dup index */
158 lua_gettable(L, lua_upvalueindex(2)); /* else try methods */
159 if (lua_isnil(L, -1)) /* invalid member */
160 luaL_error(L, "cannot get member '%s'", lua_tostring(L, 2));
161 return 1;
163 return Xet_call(L); /* call get function */
166 static int newindex_handler (lua_State *L)
168 /* stack has userdata, index, value */
169 lua_pushvalue(L, 2); /* dup index */
170 lua_rawget(L, lua_upvalueindex(1)); /* lookup member by name */
171 if (!lua_islightuserdata(L, -1)) /* invalid member */
172 luaL_error(L, "cannot set member '%s'", lua_tostring(L, 2));
173 return Xet_call(L); /* call set function */
176 static int
177 struct_register(lua_State *L, const char *name, const luaL_reg fn_methods[], const luaL_reg meta_methods[],
178 const struct Xet_reg setters[], const struct Xet_reg getters[])
180 int metatable, methods;
182 /* create methods table & add it to the table of globals */
183 luaL_register(L, name, fn_methods);
184 methods = lua_gettop(L);
186 /* create metatable & add it to the registry */
187 luaL_newmetatable(L, name);
188 luaL_register(L, 0, meta_methods); /* fill metatable */
189 metatable = lua_gettop(L);
191 lua_pushliteral(L, "__metatable");
192 lua_pushvalue(L, methods); /* dup methods table*/
193 lua_rawset(L, metatable); /* hide metatable:
194 metatable.__metatable = methods */
196 lua_pushliteral(L, "__index");
197 lua_pushvalue(L, metatable); /* upvalue index 1 */
198 Xet_add(L, getters); /* fill metatable with getters */
199 lua_pushvalue(L, methods); /* upvalue index 2 */
200 lua_pushcclosure(L, index_handler, 2);
201 lua_rawset(L, metatable); /* metatable.__index = index_handler */
203 lua_pushliteral(L, "__newindex");
204 lua_newtable(L); /* table for members you can set */
205 Xet_add(L, setters); /* fill with setters */
206 lua_pushcclosure(L, newindex_handler, 1);
207 lua_rawset(L, metatable); /* metatable.__newindex = newindex_handler */
209 lua_pop(L, 1); /* drop metatable */
210 return 1; /* return methods on the stack */
213 /** }}} */
215 /** Window {{{ */
217 PUSH_TYPE(window, struct win)
219 CHECK_TYPE(window, struct win)
221 static int get_window(lua_State *L, void *v)
223 push_window(L, (struct win **)v);
224 return 1;
227 static int
228 window_change_title(lua_State *L)
230 struct win *w = check_window(L, 1);
231 unsigned int len;
232 const char *title = luaL_checklstring(L, 2, &len);
233 ChangeAKA(w, title, len);
234 return 0;
237 static const luaL_reg window_methods[] = {
238 {"change_title", window_change_title},
239 {0, 0}
242 static int
243 window_tostring(lua_State *L)
245 char str[128];
246 struct win *w = check_window(L, 1);
247 snprintf(str, sizeof(str), "{window #%d: '%s'}", w->w_number, w->w_title);
248 lua_pushstring(L, str);
249 return 1;
252 static int
253 window_equality(lua_State *L)
255 struct win *w1 = check_window(L, 1), *w2 = check_window(L, 2);
256 lua_pushboolean(L, (w1 == w2 || (w1 && w2 && w1->w_number == w2->w_number)));
257 return 1;
260 static const luaL_reg window_metamethods[] = {
261 {"__tostring", window_tostring},
262 {"__eq", window_equality},
263 {0, 0}
266 static const struct Xet_reg window_setters[] = {
267 {0, 0}
270 static const struct Xet_reg window_getters[] = {
271 {"title", get_string, offsetof(struct win, w_title) + 8},
272 {"number", get_int, offsetof(struct win, w_number)},
273 {"dir", get_string, offsetof(struct win, w_dir)},
274 {"tty", get_string, offsetof(struct win, w_tty)},
275 {"pid", get_int, offsetof(struct win, w_pid)},
276 {"group", get_window, offsetof(struct win, w_group)},
277 {"bell", get_int, offsetof(struct win, w_bell)},
278 {"monitor", get_int, offsetof(struct win, w_monitor)},
279 {0, 0}
283 /** }}} */
285 /** AclUser {{{ */
287 PUSH_TYPE(user, struct acluser)
289 CHECK_TYPE(user, struct acluser)
291 static int
292 get_user(lua_State *L, void *v)
294 push_user(L, (struct acluser **)v);
295 return 1;
298 static const luaL_reg user_methods[] = {
299 {0, 0}
302 static int
303 user_tostring(lua_State *L)
305 char str[128];
306 struct acluser *u = check_user(L, 1);
307 snprintf(str, sizeof(str), "{user '%s'}", u->u_name);
308 lua_pushstring(L, str);
309 return 1;
312 static const luaL_reg user_metamethods[] = {
313 {"__tostring", user_tostring},
314 {0, 0}
317 static const struct Xet_reg user_setters[] = {
318 {0, 0}
321 static const struct Xet_reg user_getters[] = {
322 {"name", get_string, offsetof(struct acluser, u_name)},
323 {"password", get_string, offsetof(struct acluser, u_password)},
324 {0, 0}
327 /** }}} */
329 /** Canvas {{{ */
331 PUSH_TYPE(canvas, struct canvas)
333 CHECK_TYPE(canvas, struct canvas)
335 static int
336 get_canvas(lua_State *L, void *v)
338 push_canvas(L, (struct canvas **)v);
339 return 1;
342 static int
343 canvas_select(lua_State *L)
345 struct canvas *c = check_canvas(L, 1);
346 if (!display || D_forecv == c)
347 return 0;
348 SetCanvasWindow(c, Layer2Window(c->c_layer));
349 D_forecv = c;
351 /* XXX: the following all is duplicated from process.c:DoAction.
352 * Should these be in some better place?
354 ResizeCanvas(&D_canvas);
355 RecreateCanvasChain();
356 RethinkDisplayViewports();
357 ResizeLayersToCanvases(); /* redisplays */
358 fore = D_fore = Layer2Window(D_forecv->c_layer);
359 flayer = D_forecv->c_layer;
360 #ifdef RXVT_OSC
361 if (D_xtermosc[2] || D_xtermosc[3])
363 Activate(-1);
364 break;
366 #endif
367 RefreshHStatus();
368 #ifdef RXVT_OSC
369 RefreshXtermOSC();
370 #endif
371 flayer = D_forecv->c_layer;
372 CV_CALL(D_forecv, LayRestore();LaySetCursor());
373 WindowChanged(0, 'F');
374 return 1;
377 static const luaL_reg canvas_methods[] = {
378 {"select", canvas_select},
379 {0, 0}
382 static const luaL_reg canvas_metamethods[] = {
383 {0, 0}
386 static const struct Xet_reg canvas_setters[] = {
387 {0, 0}
390 static int
391 canvas_get_window(lua_State *L)
393 struct canvas *c = check_canvas(L, 1);
394 struct win *win = Layer2Window(c->c_layer);
395 if (win)
396 push_window(L, &win);
397 else
398 lua_pushnil(L);
399 return 1;
402 static const struct Xet_reg canvas_getters[] = {
403 {"next", get_canvas, offsetof(struct canvas, c_next)},
404 {"xoff", get_int, offsetof(struct canvas, c_xoff)},
405 {"yoff", get_int, offsetof(struct canvas, c_yoff)},
406 {"xs", get_int, offsetof(struct canvas, c_xs)},
407 {"ys", get_int, offsetof(struct canvas, c_ys)},
408 {"xe", get_int, offsetof(struct canvas, c_xe)},
409 {"ye", get_int, offsetof(struct canvas, c_ye)},
410 {"window", 0, 0, canvas_get_window},
411 {0, 0}
414 /** }}} */
416 /** Layout {{{ */
418 PUSH_TYPE(layout, struct layout)
419 CHECK_TYPE(layout, struct layout)
421 static const struct Xet_reg layout_getters[] = {
422 {0,0}
425 static int
426 get_layout(lua_State *L, void *v)
428 push_layout(L, (struct layout **)v);
429 return 1;
432 /** }}} */
434 /** Display {{{ */
436 PUSH_TYPE(display, struct display)
438 CHECK_TYPE(display, struct display)
440 static int
441 display_get_canvases(lua_State *L)
443 struct display *d;
444 struct canvas *iter;
445 int count;
447 d = check_display(L, 1);
448 lua_newtable(L);
449 for (iter = d->d_cvlist, count = 0; iter; iter = iter->c_next, count++) {
450 lua_pushinteger(L, count);
451 push_canvas(L, &iter);
452 lua_settable(L, -3);
455 return 1;
458 static const luaL_reg display_methods[] = {
459 {"get_canvases", display_get_canvases},
460 {0, 0}
463 static int
464 display_tostring(lua_State *L)
466 char str[128];
467 struct display *d = check_display(L, 1);
468 snprintf(str, sizeof(str), "{display: tty = '%s', term = '%s'}", d->d_usertty, d->d_termname);
469 lua_pushstring(L, str);
470 return 1;
473 static const luaL_reg display_metamethods[] = {
474 {"__tostring", display_tostring},
475 {0, 0}
478 static const struct Xet_reg display_setters[] = {
479 {0, 0}
482 static const struct Xet_reg display_getters[] = {
483 {"tty", get_string, offsetof(struct display, d_usertty)},
484 {"term", get_string, offsetof(struct display, d_termname)},
485 {"fore", get_window, offsetof(struct display, d_fore)},
486 {"other", get_window, offsetof(struct display, d_other)},
487 {"width", get_int, offsetof(struct display, d_width)},
488 {"height", get_int, offsetof(struct display, d_height)},
489 {"user", get_user, offsetof(struct display, d_user)},
490 {"layout", get_layout, offsetof(struct display, d_layout)},
491 {0, 0}
494 /** }}} */
496 /** Screen {{{ */
498 static int
499 screen_get_windows(lua_State *L)
501 struct win *iter;
502 int count;
504 lua_newtable(L);
505 for (iter = windows, count = 0; iter; iter = iter->w_next, count++) {
506 lua_pushinteger(L, iter->w_number);
507 push_window(L, &iter);
508 lua_settable(L, -3);
511 return 1;
514 static int
515 screen_get_displays(lua_State *L)
517 struct display *iter;
518 int count;
520 lua_newtable(L);
521 for (iter = displays, count = 0; iter; iter = iter->d_next, count++) {
522 lua_pushinteger(L, count);
523 push_display(L, &iter);
524 lua_settable(L, -3);
527 return 1;
530 static int
531 screen_get_display(lua_State *L)
533 push_display(L, &display);
534 return 1;
537 static int
538 screen_exec_command(lua_State *L)
540 const char *command;
541 unsigned int len;
543 command = luaL_checklstring(L, 1, &len);
544 if (command)
545 RcLine(command, len);
547 return 0;
550 static int
551 screen_append_msg(lua_State *L)
553 const char *msg, *color;
554 int len;
555 msg = luaL_checklstring(L, 1, &len);
556 if (lua_isnil(L, 2))
557 color = NULL;
558 else
559 color = luaL_checklstring(L, 2, &len);
560 AppendWinMsgRend(msg, color);
561 return 0;
564 static const luaL_reg screen_methods[] = {
565 {"windows", screen_get_windows},
566 {"displays", screen_get_displays},
567 {"display", screen_get_display},
568 {"command", screen_exec_command},
569 {"append_msg", screen_append_msg},
570 {0, 0}
573 static const luaL_reg screen_metamethods[] = {
574 {0, 0}
577 static const struct Xet_reg screen_setters[] = {
578 {0, 0}
581 static const struct Xet_reg screen_getters[] = {
582 {0, 0}
585 /** }}} */
587 /** Public functions {{{ */
588 static lua_State *L;
589 int LuaInit(void)
591 L = luaL_newstate();
593 luaL_openlibs(L);
595 #define REGISTER(X) struct_register(L, #X , X ## _methods, X##_metamethods, X##_setters, X##_getters)
597 REGISTER(screen);
598 REGISTER(window);
599 REGISTER(display);
600 REGISTER(user);
601 REGISTER(canvas);
603 return 0;
606 struct fn_def
608 void (*push_fn)(lua_State *, void*);
609 void *value;
612 static int
613 LuaCallProcess(const char *name, struct fn_def defs[])
615 int argc = 0;
617 lua_settop(L, 0);
618 lua_getfield(L, LUA_GLOBALSINDEX, name);
619 if (lua_isnil(L, -1))
620 return 0;
621 for (argc = 0; defs[argc].push_fn; argc++)
622 defs[argc].push_fn(L, defs[argc].value);
623 if (lua_pcall(L, argc, 0, 0) == LUA_ERRRUN && lua_isstring(L, -1))
625 struct display *d = display;
626 unsigned int len;
627 char *message = luaL_checklstring(L, -1, &len);
628 LMsg(1, "%s", message ? message : "Unknown error");
629 lua_pop(L, 1);
630 display = d;
631 return 0;
633 return 1;
636 int LuaForeWindowChanged(void)
638 if (!L)
639 return 0;
640 lua_getfield(L, LUA_GLOBALSINDEX, "fore_changed");
641 if (lua_isnil(L, -1))
642 return 0;
643 push_display(L, &display);
644 push_window(L, display ? &D_fore : &fore);
645 if (lua_pcall(L, 2, 0, 0) == LUA_ERRRUN)
647 if(lua_isstring(L, -1))
649 unsigned int len;
650 char *message = luaL_checklstring(L, -1, &len);
651 LMsg(1, "%s", message ? message : "Unknown error");
652 lua_pop(L, 1);
655 return 0;
658 int LuaSource(const char *file)
660 if (!L)
661 return 0;
662 struct stat st;
663 if (stat(file, &st) == -1)
664 Msg(errno, "Error loading lua script file '%s'", file);
665 else
667 int len = strlen(file);
668 if (len < 4 || strncmp(file + len - 4, ".lua", 4) != 0)
669 return 0;
670 luaL_dofile(L, file);
671 return 1;
673 return 0;
676 int LuaFinit(void)
678 if (!L)
679 return 0;
680 lua_close(L);
681 L = (lua_State*)0;
682 return 0;
685 int LuaCall(char **argv)
687 int argc;
688 if (!L)
689 return 0;
691 lua_getfield(L, LUA_GLOBALSINDEX, *argv);
692 for (argc = 0, argv++; *argv; argv++, argc++)
694 lua_pushstring(L, *argv);
696 if (lua_pcall(L, argc, 0, 0) == LUA_ERRRUN)
698 if(lua_isstring(L, -1))
700 unsigned int len;
701 char *message = luaL_checklstring(L, -1, &len);
702 LMsg(1, "%s", message ? message : "Unknown error");
703 lua_pop(L, 1);
704 return 0;
707 return 1;
711 LuaProcessCaption(const char *caption, struct win *win, int len)
713 if (!L)
714 return 0;
715 struct fn_def params[] = {
716 {lua_pushstring, caption},
717 {push_window, &win},
718 {lua_pushinteger, len},
719 {NULL, NULL}
721 return LuaCallProcess("process_caption", params);
724 static void
725 push_stringarray(lua_State *L, void *data)
727 char **args = (char **)data;
728 int i;
729 lua_newtable(L);
730 for (i = 1; args && *args; i++) {
731 lua_pushinteger(L, i);
732 lua_pushstring(L, *args++);
733 lua_settable(L, -3);
738 LuaCommandExecuted(const char *command, const char **args, int argc)
740 if (!L)
741 return 0;
742 struct fn_def params[] = {
743 {lua_pushstring, command},
744 {push_stringarray, args},
745 {NULL, NULL}
747 return LuaCallProcess("command_executed", params);
750 /** }}} */
752 struct ScriptFuncs LuaFuncs =
754 LuaInit,
755 LuaFinit,
756 LuaForeWindowChanged,
757 LuaSource,
758 LuaProcessCaption,
759 LuaCommandExecuted