luaa: check that object is a table before calling lua_next()
[awesome.git] / luaa.c
blob2bce875d8e718dc41c7af64d9fb86d2b82961aa9
1 /*
2 * lua.c - Lua configuration management
4 * Copyright © 2008 Julien Danjou <julien@danjou.info>
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License along
17 * with this program; if not, write to the Free Software Foundation, Inc.,
18 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
22 #include "common/util.h"
24 #include <errno.h>
25 #include <sys/socket.h>
26 #include <sys/un.h>
27 #include <unistd.h>
28 #include <sys/types.h>
29 #include <sys/wait.h>
30 #include <unistd.h>
31 #include <fcntl.h>
33 #include <ev.h>
35 #include <lua.h>
36 #include <lauxlib.h>
37 #include <lualib.h>
39 #include <xcb/xcb.h>
41 #include "awesome.h"
42 #include "awesome-version-internal.h"
43 #include "ewmh.h"
44 #include "config.h"
45 #include "luaa.h"
46 #include "tag.h"
47 #include "client.h"
48 #include "screen.h"
49 #include "event.h"
50 #include "titlebar.h"
51 #include "mouse.h"
52 #include "layouts/tile.h"
53 #include "common/socket.h"
54 #include "common/buffer.h"
56 extern awesome_t globalconf;
58 extern const struct luaL_reg awesome_hooks_lib[];
59 extern const struct luaL_reg awesome_keygrabber_lib[];
60 extern const struct luaL_reg awesome_button_methods[];
61 extern const struct luaL_reg awesome_button_meta[];
62 extern const struct luaL_reg awesome_image_methods[];
63 extern const struct luaL_reg awesome_image_meta[];
64 extern const struct luaL_reg awesome_mouse_methods[];
65 extern const struct luaL_reg awesome_mouse_meta[];
66 extern const struct luaL_reg awesome_screen_methods[];
67 extern const struct luaL_reg awesome_screen_meta[];
68 extern const struct luaL_reg awesome_client_methods[];
69 extern const struct luaL_reg awesome_client_meta[];
70 extern const struct luaL_reg awesome_titlebar_methods[];
71 extern const struct luaL_reg awesome_titlebar_meta[];
72 extern const struct luaL_reg awesome_tag_methods[];
73 extern const struct luaL_reg awesome_tag_meta[];
74 extern const struct luaL_reg awesome_widget_methods[];
75 extern const struct luaL_reg awesome_widget_meta[];
76 extern const struct luaL_reg awesome_statusbar_methods[];
77 extern const struct luaL_reg awesome_statusbar_meta[];
78 extern const struct luaL_reg awesome_wibox_methods[];
79 extern const struct luaL_reg awesome_wibox_meta[];
80 extern const struct luaL_reg awesome_keybinding_methods[];
81 extern const struct luaL_reg awesome_keybinding_meta[];
83 static struct sockaddr_un *addr;
84 static ev_io csio = { .fd = -1 };
86 #define XDG_CONFIG_HOME_DEFAULT "/.config"
88 /** Get or set global mouse bindings.
89 * This binding will be available when you'll click on root window.
90 * \param L The Lua VM state.
91 * \return The number of element pushed on stack.
92 * \luastack
93 * \lvalue A client.
94 * \lparam An array of mouse button bindings objects, or nothing.
95 * \return The array of mouse button bindings objects of this client.
97 static int
98 luaA_buttons(lua_State *L)
100 button_array_t *buttons = &globalconf.buttons;
102 if(lua_gettop(L) == 1)
103 luaA_button_array_set(L, 1, buttons);
105 return luaA_button_array_get(L, buttons);
108 /** Quit awesome.
109 * \param L The Lua VM state.
110 * \return The number of elements pushed on stack.
112 static int
113 luaA_quit(lua_State *L __attribute__ ((unused)))
115 ev_unloop(globalconf.loop, 1);
116 return 0;
119 /** Execute another application, probably a window manager, to replace
120 * awesome.
121 * \param L The Lua VM state.
122 * \return The number of elements pushed on stack.
123 * \luastack
124 * \lparam The command line to execute.
126 static int
127 luaA_exec(lua_State *L)
129 const char *cmd = luaL_checkstring(L, 1);
131 awesome_atexit();
133 a_exec(cmd);
134 return 0;
137 /** Restart awesome.
139 static int
140 luaA_restart(lua_State *L __attribute__ ((unused)))
142 awesome_restart();
143 return 0;
146 /** Set default font. (DEPRECATED)
147 * \param L The Lua VM state.
148 * \return The number of elements pushed on stack.
149 * \luastack
150 * \lparam A string with a font name in Pango format.
152 static int
153 luaA_font_set(lua_State *L)
155 deprecate(L, "awesome.font attribute");
156 if(lua_gettop(L) == 1)
158 const char *newfont = luaL_checkstring(L, 1);
159 draw_font_delete(&globalconf.font);
160 globalconf.font = draw_font_new(newfont);
163 char *font = pango_font_description_to_string(globalconf.font->desc);
164 lua_pushstring(L, font);
165 g_free(font);
166 return 0;
169 /** Set default colors (DEPRECATED).
170 * \param L The Lua VM state.
171 * \return The number of elements pushed on stack.
172 * \luastack
173 * \lparam A table with `fg' and `bg' elements, containing colors.
174 * \lreturn A table with `fg' and `bg' elements, containing colors.
176 static int
177 luaA_colors(lua_State *L)
179 deprecate(L, "awesome.fg and awesome.bg attributes");
180 if(lua_gettop(L) == 1)
182 const char *buf;
183 size_t len;
184 int8_t colors_nbr = -1, i;
185 xcolor_init_request_t reqs[2];
187 luaA_checktable(L, 1);
189 if((buf = luaA_getopt_lstring(L, 1, "fg", NULL, &len)))
190 reqs[++colors_nbr] = xcolor_init_unchecked(&globalconf.colors.fg, buf, len);
192 if((buf = luaA_getopt_lstring(L, 1, "bg", NULL, &len)))
193 reqs[++colors_nbr] = xcolor_init_unchecked(&globalconf.colors.bg, buf, len);
195 for(i = 0; i <= colors_nbr; i++)
196 xcolor_init_reply(reqs[i]);
199 lua_newtable(L);
200 luaA_pushcolor(L, &globalconf.colors.fg);
201 lua_setfield(L, -2, "fg");
202 luaA_pushcolor(L, &globalconf.colors.bg);
203 lua_setfield(L, -2, "bg");
205 return 1;
208 /** Set default colors. (DEPRECATED)
209 * \param L The Lua VM state.
210 * \return The number of elements pushed on stack.
212 * \luastack
213 * \lparam A table with `fg' and `bg' elements, containing colors.
215 static int
216 luaA_colors_set(lua_State *L)
218 return luaA_colors(L);
221 static void
222 luaA_openlib(lua_State *L, const char *name,
223 const struct luaL_reg methods[],
224 const struct luaL_reg meta[])
226 luaL_newmetatable(L, name); /* 1 */
227 lua_pushvalue(L, -1); /* dup metatable 2 */
228 lua_setfield(L, -2, "__index"); /* metatable.__index = metatable 1 */
230 luaL_register(L, NULL, meta); /* 1 */
231 luaL_register(L, name, methods); /* 2 */
232 lua_pushvalue(L, -1); /* dup self as metatable 3 */
233 lua_setmetatable(L, -2); /* set self as metatable 2 */
234 lua_pop(L, 2);
237 /** UTF-8 aware string length computing.
238 * \param L The Lua VM state.
239 * \return The number of elements pushed on stack.
241 static int
242 luaA_mbstrlen(lua_State *L)
244 const char *cmd = luaL_checkstring(L, 1);
245 lua_pushnumber(L, mbstowcs(NULL, NONULL(cmd), 0));
246 return 1;
249 /** Overload standard Lua next function to use __next key on metatable.
250 * \param L The Lua VM state.
251 * \param The number of elements pushed on stack.
253 static int
254 luaAe_next(lua_State *L)
256 if(luaL_getmetafield(L, 1, "__next"))
258 lua_insert(L, 1);
259 lua_call(L, lua_gettop(L) - 1, LUA_MULTRET);
260 return lua_gettop(L);
263 luaL_checktype(L, 1, LUA_TTABLE);
264 lua_settop(L, 2);
265 if(lua_next(L, 1))
266 return 2;
267 lua_pushnil(L);
268 return 1;
271 /** Overload lua_next() function by using __next metatable field
272 * to get next elements.
273 * \param L The Lua VM stack.
274 * \param idx The index number of elements in stack.
275 * \return 1 if more elements to come, 0 otherwise.
278 luaA_next(lua_State *L, int idx)
280 if(luaL_getmetafield(L, idx, "__next"))
282 /* if idx is relative, reduce it since we got __next */
283 if(idx < 0) idx--;
284 /* copy table and then move key */
285 lua_pushvalue(L, idx);
286 lua_pushvalue(L, -3);
287 lua_remove(L, -4);
288 lua_pcall(L, 2, 2, 0);
289 /* next returned nil, it's the end */
290 if(lua_isnil(L, -1))
292 /* remove nil */
293 lua_pop(L, 2);
294 return 0;
296 return 1;
298 else if(lua_istable(L, idx))
299 return lua_next(L, idx);
300 return 0;
303 /** Generic pairs function.
304 * \param L The Lua VM state.
305 * \return The number of elements pushed on stack.
307 static int
308 luaA_generic_pairs(lua_State *L)
310 lua_pushvalue(L, lua_upvalueindex(1)); /* return generator, */
311 lua_pushvalue(L, 1); /* state, */
312 lua_pushnil(L); /* and initial value */
313 return 3;
316 /** Overload standard pairs function to use __pairs field of metatables.
317 * \param L The Lua VM state.
318 * \return The number of elements pushed on stack.
320 static int
321 luaAe_pairs(lua_State *L)
323 if(luaL_getmetafield(L, 1, "__pairs"))
325 lua_insert(L, 1);
326 lua_call(L, lua_gettop(L) - 1, LUA_MULTRET);
327 return lua_gettop(L);
330 luaL_checktype(L, 1, LUA_TTABLE);
331 return luaA_generic_pairs(L);
334 static int
335 luaA_ipairs_aux(lua_State *L)
337 int i = luaL_checkint(L, 2) + 1;
338 luaL_checktype(L, 1, LUA_TTABLE);
339 lua_pushinteger(L, i);
340 lua_rawgeti(L, 1, i);
341 return (lua_isnil(L, -1)) ? 0 : 2;
344 /** Overload standard ipairs function to use __ipairs field of metatables.
345 * \param L The Lua VM state.
346 * \return The number of elements pushed on stack.
348 static int
349 luaAe_ipairs(lua_State *L)
351 if(luaL_getmetafield(L, 1, "__ipairs"))
353 lua_insert(L, 1);
354 lua_call(L, lua_gettop(L) - 1, LUA_MULTRET);
355 return lua_gettop(L);
358 luaL_checktype(L, 1, LUA_TTABLE);
359 lua_pushvalue(L, lua_upvalueindex(1));
360 lua_pushvalue(L, 1);
361 lua_pushinteger(L, 0); /* and initial value */
362 return 3;
365 /** Replace various standards Lua functions with our own.
366 * \param L The Lua VM state.
368 static void
369 luaA_fixups(lua_State *L)
371 /* replace string.len */
372 lua_getglobal(L, "string");
373 lua_pushcfunction(L, luaA_mbstrlen);
374 lua_setfield(L, -2, "len");
375 lua_pop(L, 1);
376 /* replace next */
377 lua_pushliteral(L, "next");
378 lua_pushcfunction(L, luaAe_next);
379 lua_settable(L, LUA_GLOBALSINDEX);
380 /* replace pairs */
381 lua_pushliteral(L, "pairs");
382 lua_pushcfunction(L, luaAe_next);
383 lua_pushcclosure(L, luaAe_pairs, 1); /* pairs get next as upvalue */
384 lua_settable(L, LUA_GLOBALSINDEX);
385 /* replace ipairs */
386 lua_pushliteral(L, "ipairs");
387 lua_pushcfunction(L, luaA_ipairs_aux);
388 lua_pushcclosure(L, luaAe_ipairs, 1);
389 lua_settable(L, LUA_GLOBALSINDEX);
392 /** __next function for wtable objects.
393 * \param L The Lua VM state.
394 * \return The number of elements pushed on stack.
396 static int
397 luaA_wtable_next(lua_State *L)
399 /* upvalue 1 is content table */
400 if(lua_next(L, lua_upvalueindex(1)))
401 return 2;
402 lua_pushnil(L);
403 return 1;
406 /** __ipairs function for wtable objects.
407 * \param L The Lua VM state.
408 * \return The number of elements pushed on stack.
410 static int
411 luaA_wtable_ipairs(lua_State *L)
413 /* push ipairs_aux */
414 lua_pushvalue(L, lua_upvalueindex(2));
415 /* push content table */
416 lua_pushvalue(L, lua_upvalueindex(1));
417 lua_pushinteger(L, 0); /* and initial value */
418 return 3;
421 /** Index function of wtable objects.
422 * \param L The Lua VM state.
423 * \return The number of elements pushed on stack.
425 static int
426 luaA_wtable_index(lua_State *L)
428 size_t len;
429 const char *buf;
431 lua_pushvalue(L, 2);
432 /* check for size, waiting lua 5.2 and __len on tables */
433 if((buf = lua_tolstring(L, -1, &len)))
434 if(a_tokenize(buf, len) == A_TK_LEN)
436 lua_pushnumber(L, lua_objlen(L, lua_upvalueindex(1)));
437 return 1;
439 lua_pop(L, 1);
441 /* upvalue 1 is content table */
442 lua_rawget(L, lua_upvalueindex(1));
443 return 1;
446 /** Newndex function of wtable objects.
447 * \param L The Lua VM state.
448 * \return The number of elements pushed on stack.
450 static int
451 luaA_wtable_newindex(lua_State *L)
453 bool invalid = false;
455 /* push key on top */
456 lua_pushvalue(L, 2);
457 /* get current key value in content table */
458 lua_rawget(L, lua_upvalueindex(1));
459 /* if value is a widget, notify change */
460 if(lua_istable(L, -1) || luaA_toudata(L, -1, "widget"))
461 invalid = true;
463 lua_pop(L, 1); /* remove value */
465 /* if new value is a widget or a table */
466 if(lua_istable(L, 3))
468 luaA_table2wtable(L);
469 invalid = true;
471 else if(!invalid && luaA_toudata(L, 3, "widget"))
472 invalid = true;
474 /* upvalue 1 is content table */
475 lua_rawset(L, lua_upvalueindex(1));
477 if(invalid)
478 luaA_wibox_invalidate_byitem(L, lua_topointer(L, 1));
480 return 0;
483 /** Convert the top element of the stack to a proxied wtable.
484 * \param L The Lua VM state.
486 void
487 luaA_table2wtable(lua_State *L)
489 if(!lua_istable(L, -1))
490 return;
492 lua_newtable(L); /* create *real* content table */
493 lua_newtable(L); /* metatable */
494 lua_pushvalue(L, -2); /* copy content table */
495 lua_pushcfunction(L, luaA_ipairs_aux); /* push ipairs aux */
496 lua_pushcclosure(L, luaA_wtable_ipairs, 2);
497 lua_pushvalue(L, -3); /* copy content table */
498 lua_pushcclosure(L, luaA_wtable_next, 1); /* __next has the content table as upvalue */
499 lua_pushvalue(L, -4); /* copy content table */
500 lua_pushcclosure(L, luaA_wtable_index, 1); /* __index has the content table as upvalue */
501 lua_pushvalue(L, -5); /* copy content table */
502 lua_pushcclosure(L, luaA_wtable_newindex, 1); /* __newindex has the content table as upvalue */
503 /* set metatable field with just pushed closure */
504 lua_setfield(L, -5, "__newindex");
505 lua_setfield(L, -4, "__index");
506 lua_setfield(L, -3, "__next");
507 lua_setfield(L, -2, "__ipairs");
508 /* set metatable impossible to touch */
509 lua_pushliteral(L, "wtable");
510 lua_setfield(L, -2, "__metatable");
511 /* set new metatable on original table */
512 lua_setmetatable(L, -3);
514 /* initial key */
515 lua_pushnil(L);
516 /* go through original table */
517 while(lua_next(L, -3))
519 /* if convert value to wtable */
520 luaA_table2wtable(L);
521 /* copy key */
522 lua_pushvalue(L, -2);
523 /* move key before value */
524 lua_insert(L, -2);
525 /* set same value in content table */
526 lua_rawset(L, -4);
527 /* copy key */
528 lua_pushvalue(L, -1);
529 /* push the new value :-> */
530 lua_pushnil(L);
531 /* set orig[k] = nil */
532 lua_rawset(L, -5);
534 /* remove content table */
535 lua_pop(L, 1);
538 /** Look for an item: table, function, etc.
539 * \param L The Lua VM state.
540 * \param item The pointer item.
542 bool
543 luaA_hasitem(lua_State *L, const void *item)
545 lua_pushnil(L);
546 while(luaA_next(L, -2))
548 if(lua_topointer(L, -1) == item)
550 /* remove value and key */
551 lua_pop(L, 2);
552 return true;
554 if(lua_istable(L, -1))
555 if(luaA_hasitem(L, item))
557 /* remove key and value */
558 lua_pop(L, 2);
559 return true;
561 /* remove value */
562 lua_pop(L, 1);
564 return false;
567 /** Check if a table is a loop. When using table as direct acyclic digram,
568 * this is useful.
569 * \param L The Lua VM state.
570 * \param idx The index of the table in the stack
571 * \return True if the table loops.
573 bool
574 luaA_isloop(lua_State *L, int idx)
576 if(lua_istable(L, idx))
578 lua_pushvalue(L, idx); /* push table on top */
579 if(luaA_hasitem(L, lua_topointer(L, -1)))
581 lua_pop(L, 1); /* remove pushed table */
582 return true;
584 lua_pushnil(L);
585 while(luaA_next(L, -2))
587 /* check for recursivity */
588 if(luaA_isloop(L, -1))
590 lua_pop(L, 2); /* remove key and value */
591 return true;
593 lua_pop(L, 1); /* remove value */
595 lua_pop(L, 1); /* remove pushed table */
597 return false;
600 /** Object table.
601 * This table can use safely object as key.
602 * \param L The Lua VM state.
603 * \return The number of elements pushed on stack.
606 luaA_otable_index(lua_State *L)
608 void **obj, **v;
610 if((obj = lua_touserdata(L, 2)))
612 /* begins at nil */
613 lua_pushnil(L);
614 while(lua_next(L, 1))
616 /* check the key against the key if the key is a userdata,
617 * otherwise check it again the value. */
618 if((v = lua_touserdata(L, -2))
619 && *v == *obj)
620 /* return value */
621 return 1;
622 else if((v = lua_touserdata(L, -1))
623 && *v == *obj)
625 /* return key */
626 lua_pop(L, 1);
627 return 1;
629 /* removes 'value'; keeps 'key' for next iteration */
630 lua_pop(L, 1);
632 return 0;
635 lua_rawget(L, 1);
636 return 1;
639 /** Object table.
640 * This table can use safely object as key.
641 * \param L The Lua VM state.
642 * \return The number of elements pushed on stack.
644 static int
645 luaA_otable_newindex(lua_State *L)
647 void **obj, **v;
649 if((obj = lua_touserdata(L, 2)))
651 /* begins at nil */
652 lua_pushnil(L);
653 while(lua_next(L, 1))
655 if((v = lua_touserdata(L, -2))
656 && *v == *obj)
658 /* remove value */
659 lua_pop(L, 1);
660 /* push new value on top */
661 lua_pushvalue(L, 3);
662 /* set in table key = value */
663 lua_rawset(L, 1);
664 return 0;
666 /* removes 'value'; keeps 'key' for next iteration */
667 lua_pop(L, 1);
671 lua_rawset(L, 1);
673 return 0;
676 /** Spawn a program.
677 * This function is multi-head (Zaphod) aware and will set display to
678 * the right screen according to mouse position.
679 * \param L The Lua VM state.
680 * \return The number of elements pushed on stack
681 * \luastack
682 * \lparam The command to launch.
683 * \lparam The optional screen number to spawn the command on.
685 static int
686 luaA_spawn(lua_State *L)
688 char *host, newdisplay[128];
689 const char *cmd;
690 int screen = 0, screenp, displayp;
692 if(lua_gettop(L) == 2)
694 screen = luaL_checknumber(L, 2) - 1;
695 luaA_checkscreen(screen);
698 cmd = luaL_checkstring(L, 1);
700 if(!globalconf.xinerama_is_active)
702 xcb_parse_display(NULL, &host, &displayp, &screenp);
703 snprintf(newdisplay, sizeof(newdisplay), "%s:%d.%d", host, displayp, screen);
704 setenv("DISPLAY", newdisplay, 1);
705 p_delete(&host);
708 /* The double-fork construct avoids zombie processes and keeps the code
709 * clean from stupid signal handlers. */
710 if(fork() == 0)
712 if(fork() == 0)
714 if(globalconf.connection)
715 xcb_disconnect(globalconf.connection);
716 setsid();
717 a_exec(cmd);
718 warn("execl '%s' failed: %s\n", cmd, strerror(errno));
720 exit(EXIT_SUCCESS);
722 wait(0);
724 return 0;
727 /** Deprecated function, does nothing.
729 static int
730 luaA_mouse_add(lua_State *L)
732 deprecate(L, "awesome.buttons()");
733 return 0;
736 /** awesome global table.
737 * \param L The Lua VM state.
738 * \return The number of elements pushed on stack.
739 * \luastack
740 * \lfield font The default font.
741 * \lfield conffile The configuration file which has been loaded.
743 static int
744 luaA_awesome_index(lua_State *L)
746 if(luaA_usemetatable(L, 1, 2))
747 return 1;
749 size_t len;
750 const char *buf = luaL_checklstring(L, 2, &len);
752 switch(a_tokenize(buf, len))
754 case A_TK_FONT:
756 char *font = pango_font_description_to_string(globalconf.font->desc);
757 lua_pushstring(L, font);
758 g_free(font);
760 break;
761 case A_TK_CONFFILE:
762 lua_pushstring(L, globalconf.conffile);
763 break;
764 case A_TK_FG:
765 luaA_pushcolor(L, &globalconf.colors.fg);
766 break;
767 case A_TK_BG:
768 luaA_pushcolor(L, &globalconf.colors.bg);
769 break;
770 default:
771 return 0;
774 return 1;
777 /** Newindex function for the awesome global table.
778 * \param L The Lua VM state.
779 * \return The number of elements pushed on stack.
781 static int
782 luaA_awesome_newindex(lua_State *L)
784 if(luaA_usemetatable(L, 1, 2))
785 return 1;
787 size_t len;
788 const char *buf = luaL_checklstring(L, 2, &len);
790 switch(a_tokenize(buf, len))
792 case A_TK_FONT:
794 const char *newfont = luaL_checkstring(L, 3);
795 draw_font_delete(&globalconf.font);
796 globalconf.font = draw_font_new(newfont);
798 break;
799 case A_TK_FG:
800 if((buf = luaL_checklstring(L, 3, &len)))
801 xcolor_init_reply(xcolor_init_unchecked(&globalconf.colors.fg, buf, len));
802 break;
803 case A_TK_BG:
804 if((buf = luaL_checklstring(L, 3, &len)))
805 xcolor_init_reply(xcolor_init_unchecked(&globalconf.colors.bg, buf, len));
806 break;
807 default:
808 return 0;
811 return 0;
814 /** Initialize the Lua VM
816 void
817 luaA_init(void)
819 lua_State *L;
821 static const struct luaL_reg otable_methods[] =
823 { "__call", luaA_otable_new },
824 { NULL, NULL }
826 static const struct luaL_reg otable_meta[] =
828 { "__index", luaA_otable_index },
829 { "__newindex", luaA_otable_newindex },
830 { NULL, NULL }
832 static const struct luaL_reg awesome_lib[] =
834 { "quit", luaA_quit },
835 { "exec", luaA_exec },
836 { "spawn", luaA_spawn },
837 { "restart", luaA_restart },
838 { "buttons", luaA_buttons },
839 { "font_set", luaA_font_set },
840 { "colors_set", luaA_colors_set },
841 { "colors", luaA_colors },
842 { "__index", luaA_awesome_index },
843 { "__newindex", luaA_awesome_newindex },
844 /* deprecated */
845 { "mouse_add", luaA_mouse_add },
846 { NULL, NULL }
849 L = globalconf.L = luaL_newstate();
851 luaL_openlibs(L);
853 luaA_fixups(L);
855 /* Export awesome lib */
856 luaA_openlib(L, "awesome", awesome_lib, awesome_lib);
858 /* Export hooks lib */
859 luaL_register(L, "hooks", awesome_hooks_lib);
861 /* Export keygrabber lib */
862 luaL_register(L, "keygrabber", awesome_keygrabber_lib);
864 /* Export otable lib */
865 luaA_openlib(L, "otable", otable_methods, otable_meta);
867 /* Export screen */
868 luaA_openlib(L, "screen", awesome_screen_methods, awesome_screen_meta);
870 /* Export mouse */
871 luaA_openlib(L, "mouse", awesome_mouse_methods, awesome_mouse_meta);
873 /* Export button */
874 luaA_openlib(L, "button", awesome_button_methods, awesome_button_meta);
876 /* Export image */
877 luaA_openlib(L, "image", awesome_image_methods, awesome_image_meta);
879 /* Export tag */
880 luaA_openlib(L, "tag", awesome_tag_methods, awesome_tag_meta);
882 /* Export statusbar */
883 luaA_openlib(L, "statusbar", awesome_statusbar_methods, awesome_statusbar_meta);
885 /* Export wibox */
886 luaA_openlib(L, "wibox", awesome_wibox_methods, awesome_wibox_meta);
888 /* Export widget */
889 luaA_openlib(L, "widget", awesome_widget_methods, awesome_widget_meta);
891 /* Export client */
892 luaA_openlib(L, "client", awesome_client_methods, awesome_client_meta);
894 /* Export titlebar */
895 luaA_openlib(L, "titlebar", awesome_titlebar_methods, awesome_titlebar_meta);
897 /* Export keys */
898 luaA_openlib(L, "keybinding", awesome_keybinding_methods, awesome_keybinding_meta);
900 lua_pushliteral(L, "AWESOME_VERSION");
901 lua_pushstring(L, AWESOME_VERSION);
902 lua_settable(L, LUA_GLOBALSINDEX);
904 lua_pushliteral(L, "AWESOME_RELEASE");
905 lua_pushstring(L, AWESOME_RELEASE);
906 lua_settable(L, LUA_GLOBALSINDEX);
908 /* init hooks */
909 globalconf.hooks.manage = LUA_REFNIL;
910 globalconf.hooks.unmanage = LUA_REFNIL;
911 globalconf.hooks.focus = LUA_REFNIL;
912 globalconf.hooks.unfocus = LUA_REFNIL;
913 globalconf.hooks.mouse_enter = LUA_REFNIL;
914 globalconf.hooks.arrange = LUA_REFNIL;
915 globalconf.hooks.clients = LUA_REFNIL;
916 globalconf.hooks.tags = LUA_REFNIL;
917 globalconf.hooks.tagged = LUA_REFNIL;
918 globalconf.hooks.property = LUA_REFNIL;
919 globalconf.hooks.timer = LUA_REFNIL;
921 /* add Lua lib path (/usr/share/awesome/lib by default) */
922 luaA_dostring(L, "package.path = package.path .. \";" AWESOME_LUA_LIB_PATH "/?.lua\"");
923 luaA_dostring(L, "package.path = package.path .. \";" AWESOME_LUA_LIB_PATH "/?/init.lua\"");
925 /* add XDG_CONFIG_DIR (/etc/xdg/awesome by default) as include path */
926 luaA_dostring(L, "package.path = package.path .. \";" XDG_CONFIG_DIR "/awesome/?.lua\"");
927 luaA_dostring(L, "package.path = package.path .. \";" XDG_CONFIG_DIR "/awesome/?/init.lua\"");
929 /* add either XDG_CONFIG_HOME/awesome or HOME/.config/awesome to path */
930 char *dir;
931 if((dir = getenv("XDG_CONFIG_HOME")))
933 char *path;
934 a_asprintf(&path, "package.path = package.path .. \";%s/awesome/?.lua;%s/awesome/?/init.lua\"", dir, dir);
935 luaA_dostring(globalconf.L, path);
936 p_delete(&path);
938 else
940 char *path, *homedir = getenv("HOME");
941 a_asprintf(&path,
942 "package.path = package.path .. \";%s" XDG_CONFIG_HOME_DEFAULT "/awesome/?.lua;%s" XDG_CONFIG_HOME_DEFAULT "/awesome/?/init.lua\"",
943 homedir, homedir);
944 luaA_dostring(globalconf.L, path);
945 p_delete(&path);
948 /* add XDG_CONFIG_DIRS to include paths */
949 char *xdg_config_dirs = getenv("XDG_CONFIG_DIRS");
950 ssize_t len;
952 if((len = a_strlen(xdg_config_dirs)))
954 char **buf, **xdg_files = a_strsplit(xdg_config_dirs, len, ':');
956 for(buf = xdg_files; *buf; buf++)
958 char *confpath;
959 a_asprintf(&confpath, "package.path = package.path .. \";%s/awesome/?.lua;%s/awesome/?/init.lua\"",
960 *buf, *buf);
961 luaA_dostring(globalconf.L, confpath);
962 p_delete(&confpath);
965 for(buf = xdg_files; *buf; buf++)
966 p_delete(buf);
967 p_delete(&xdg_files);
971 #define AWESOME_CONFIG_FILE "/awesome/rc.lua"
973 static bool
974 luaA_loadrc(const char *confpath, bool run)
976 if(confpath)
978 if(!luaL_loadfile(globalconf.L, confpath))
980 if(run)
982 if(lua_pcall(globalconf.L, 0, LUA_MULTRET, 0))
983 fprintf(stderr, "%s\n", lua_tostring(globalconf.L, -1));
984 else
986 globalconf.conffile = a_strdup(confpath);
987 return true;
990 else
991 lua_pop(globalconf.L, 1);
992 return true;
994 else
995 fprintf(stderr, "%s\n", lua_tostring(globalconf.L, -1));
997 return false;
1000 /** Load a configuration file.
1001 * \param confpatharg The configuration file to load.
1002 * \param run Run the configuration file.
1004 bool
1005 luaA_parserc(const char *confpatharg, bool run)
1007 int screen;
1008 const char *confdir, *xdg_config_dirs;
1009 char *confpath = NULL, **xdg_files = NULL, **buf;
1010 ssize_t len;
1011 bool ret = false;
1013 /* try to load, return if it's ok */
1014 if(luaA_loadrc(confpatharg, run))
1016 ret = true;
1017 goto bailout;
1020 if((confdir = getenv("XDG_CONFIG_HOME")))
1021 a_asprintf(&confpath, "%s" AWESOME_CONFIG_FILE, confdir);
1022 else
1023 a_asprintf(&confpath, "%s" XDG_CONFIG_HOME_DEFAULT AWESOME_CONFIG_FILE, getenv("HOME"));
1025 /* try to run XDG_CONFIG_HOME/awesome/rc.lua */
1026 if(luaA_loadrc(confpath, run))
1028 ret = true;
1029 goto bailout;
1032 p_delete(&confpath);
1034 xdg_config_dirs = getenv("XDG_CONFIG_DIRS");
1036 if(!(len = a_strlen(xdg_config_dirs)))
1038 xdg_config_dirs = XDG_CONFIG_DIR;
1039 len = sizeof(XDG_CONFIG_DIR) - 1;
1042 xdg_files = a_strsplit(xdg_config_dirs, len, ':');
1044 for(buf = xdg_files; *buf && !ret; buf++)
1046 a_asprintf(&confpath, "%s" AWESOME_CONFIG_FILE, *buf);
1047 if(luaA_loadrc(confpath, run))
1049 ret = true;
1050 goto bailout;
1052 p_delete(&confpath);
1055 bailout:
1057 p_delete(&confpath);
1059 if(xdg_files)
1061 for(buf = xdg_files; *buf; buf++)
1062 p_delete(buf);
1063 p_delete(&xdg_files);
1066 /* Assure there's at least one tag */
1067 for(screen = 0; screen < globalconf.nscreen; screen++)
1068 if(!globalconf.screens[screen].tags.len)
1069 tag_append_to_screen(tag_new("default", sizeof("default") - 1, layout_tile, 0.5, 1, 0),
1070 &globalconf.screens[screen]);
1071 return ret;
1074 /** Parse a command.
1075 * \param cmd The buffer to parse.
1076 * \return the number of elements pushed on the stack by the last statement in cmd.
1077 * If there's an error, the message is pushed onto the stack and this returns 1.
1079 static int
1080 luaA_docmd(const char *cmd)
1082 char *p;
1083 int newtop, oldtop = lua_gettop(globalconf.L);
1085 while((p = strchr(cmd, '\n')))
1087 newtop = lua_gettop(globalconf.L);
1088 lua_pop(globalconf.L, newtop - oldtop);
1089 oldtop = newtop;
1091 *p = '\0';
1092 if (luaL_dostring(globalconf.L, cmd))
1094 warn("error executing Lua code: %s", lua_tostring(globalconf.L, -1));
1095 return 1;
1097 cmd = p + 1;
1099 return lua_gettop(globalconf.L) - oldtop;
1102 /** Pushes a Lua array containing the top n elements of the stack.
1103 * \param n The number of elements to put in the array.
1105 static void
1106 luaA_array(int n)
1108 int i;
1109 lua_createtable(globalconf.L, n, 0);
1110 lua_insert(globalconf.L, -n - 1);
1112 for (i = n; i > 0; i--)
1113 lua_rawseti(globalconf.L, -i - 1, i);
1116 /** Maps the top n elements of the stack to the result of
1117 * applying a function to that element.
1118 * \param n The number of elements to map.
1119 * \luastack
1120 * \lparam The function to map the elements by. This should be
1121 * at position -(n + 1).
1123 static void
1124 luaA_map(int n)
1126 int i;
1127 for (i = 0; i < n; i++)
1129 lua_pushvalue(globalconf.L, -n - 1); /* copy of the function */
1130 lua_pushvalue(globalconf.L, -n - 1); /* value to map */
1131 lua_pcall(globalconf.L, 1, 1, 0); /* call function */
1132 lua_remove(globalconf.L, -n - 1); /* remove old value */
1134 lua_remove(globalconf.L, -n - 1); /* remove function */
1137 static void luaA_conn_cleanup(EV_P_ ev_io *w)
1139 ev_ref(EV_DEFAULT_UC);
1140 ev_io_stop(EV_DEFAULT_UC_ w);
1141 if (close(w->fd))
1142 warn("error closing UNIX domain socket: %s", strerror(errno));
1143 p_delete(&w);
1146 static void
1147 luaA_cb(EV_P_ ev_io *w, int revents)
1149 char buf[1024];
1150 int r, els;
1151 const char *s;
1152 size_t len;
1154 switch(r = recv(w->fd, buf, sizeof(buf)-1, MSG_TRUNC))
1156 case -1:
1157 warn("error reading UNIX domain socket: %s", strerror(errno));
1158 case 0: /* 0 bytes are only transferred when the connection is closed */
1159 luaA_conn_cleanup(EV_DEFAULT_UC_ w);
1160 break;
1161 default:
1162 if(r >= ssizeof(buf))
1163 break;
1164 buf[r] = '\0';
1165 lua_getglobal(globalconf.L, "table");
1166 lua_getfield(globalconf.L, -1, "concat");
1167 lua_remove(globalconf.L, -2); /* remove table */
1169 lua_getglobal(globalconf.L, "tostring");
1170 els = luaA_docmd(buf);
1171 luaA_map(els); /* map results to strings */
1172 luaA_array(els); /* put strings in an array */
1174 lua_pushstring(globalconf.L, "\t");
1175 lua_pcall(globalconf.L, 2, 1, 0); /* concatenate results with tabs */
1177 s = lua_tolstring(globalconf.L, -1, &len);
1179 /* ignore ENOENT because the client may not read */
1180 if (send(w->fd, s, len, MSG_DONTWAIT) == -1)
1181 switch(errno)
1183 case ENOENT:
1184 case EAGAIN:
1185 break;
1186 default:
1187 warn("can't send back to client via domain socket: %s", strerror(errno));
1188 break;
1191 lua_pop(globalconf.L, 1); /* pop the string */
1193 awesome_refresh(globalconf.connection);
1197 static void
1198 luaA_conn_cb(EV_P_ ev_io *w, int revents)
1200 ev_io *csio_conn = p_new(ev_io, 1);
1201 int csfd = accept(w->fd, NULL, NULL);
1203 ev_io_init(csio_conn, &luaA_cb, csfd, EV_READ);
1204 ev_io_start(EV_DEFAULT_UC_ csio_conn);
1205 ev_unref(EV_DEFAULT_UC);
1208 void
1209 luaA_cs_init(void)
1211 int csfd = socket_getclient();
1213 if (csfd < 0 || fcntl(csfd, F_SETFD, FD_CLOEXEC) == -1)
1214 return;
1216 addr = socket_getaddr(getenv("DISPLAY"));
1218 if(bind(csfd, (const struct sockaddr *) addr, SUN_LEN(addr)))
1220 if(errno == EADDRINUSE)
1222 if(unlink(addr->sun_path))
1223 warn("error unlinking existing file: %s", strerror(errno));
1224 if(bind(csfd, (const struct sockaddr *) addr, SUN_LEN(addr)))
1225 return warn("error binding UNIX domain socket: %s", strerror(errno));
1227 else
1228 return warn("error binding UNIX domain socket: %s", strerror(errno));
1230 listen(csfd, 10);
1232 ev_io_init(&csio, &luaA_conn_cb, csfd, EV_READ);
1233 ev_io_start(EV_DEFAULT_UC_ &csio);
1234 ev_unref(EV_DEFAULT_UC);
1237 void
1238 luaA_cs_cleanup(void)
1240 if(csio.fd < 0)
1241 return;
1242 ev_ref(EV_DEFAULT_UC);
1243 ev_io_stop(EV_DEFAULT_UC_ &csio);
1244 if (close(csio.fd))
1245 warn("error closing UNIX domain socket: %s", strerror(errno));
1246 if(unlink(addr->sun_path))
1247 warn("error unlinking UNIX domain socket: %s", strerror(errno));
1248 p_delete(&addr);
1249 csio.fd = -1;
1252 void
1253 luaA_on_timer(EV_P_ ev_timer *w, int revents)
1255 if(globalconf.hooks.timer != LUA_REFNIL)
1256 luaA_dofunction(globalconf.L, globalconf.hooks.timer, 0, 0);
1257 awesome_refresh(globalconf.connection);
1260 /** Push a color as a string onto the stack
1261 * \param L The Lua VM state.
1262 * \param c The color to push.
1263 * \return The number of elements pushed on stack.
1266 luaA_pushcolor(lua_State *L, const xcolor_t *c)
1268 uint8_t r = (unsigned)c->red * 0xff / 0xffff;
1269 uint8_t g = (unsigned)c->green * 0xff / 0xffff;
1270 uint8_t b = (unsigned)c->blue * 0xff / 0xffff;
1271 uint8_t a = (unsigned)c->alpha * 0xff / 0xffff;
1272 char s[10];
1273 int len;
1274 /* do not print alpha if it's full */
1275 if(a == 0xff)
1276 len = snprintf(s, sizeof(s), "#%02x%02x%02x", r, g, b);
1277 else
1278 len = snprintf(s, sizeof(s), "#%02x%02x%02x%02x", r, g, b, a);
1279 lua_pushlstring(L, s, len);
1280 return 1;