Do not raise clients in client_manage
[awesome.git] / luaa.c
blob9c7b017cc666abf30d288b981cd31b54c6cf09a6
1 /*
2 * luaa.c - Lua configuration management
4 * Copyright © 2008-2009 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 #define _GNU_SOURCE
24 #include <lua.h>
25 #include <lauxlib.h>
26 #include <lualib.h>
28 #include <basedir_fs.h>
30 #include <xcb/xcb_atom.h>
32 #include "awesome.h"
33 #include "config.h"
34 #include "objects/timer.h"
35 #include "awesome-version-internal.h"
36 #include "ewmh.h"
37 #include "luaa.h"
38 #include "spawn.h"
39 #include "objects/tag.h"
40 #include "objects/client.h"
41 #include "objects/drawin.h"
42 #include "objects/drawable.h"
43 #include "screen.h"
44 #include "event.h"
45 #include "property.h"
46 #include "selection.h"
47 #include "systray.h"
48 #include "common/xcursor.h"
49 #include "common/buffer.h"
50 #include "common/backtrace.h"
52 #ifdef WITH_DBUS
53 extern const struct luaL_Reg awesome_dbus_lib[];
54 #endif
55 extern const struct luaL_Reg awesome_keygrabber_lib[];
56 extern const struct luaL_Reg awesome_mousegrabber_lib[];
57 extern const struct luaL_Reg awesome_root_lib[];
58 extern const struct luaL_Reg awesome_mouse_methods[];
59 extern const struct luaL_Reg awesome_mouse_meta[];
60 extern const struct luaL_Reg awesome_screen_methods[];
61 extern const struct luaL_Reg awesome_screen_meta[];
63 /** Path to config file */
64 static char *conffile;
66 /** Check whether a composite manager is running.
67 * \return True if such a manager is running.
69 static bool
70 composite_manager_running(void)
72 xcb_intern_atom_reply_t *atom_r;
73 xcb_get_selection_owner_reply_t *selection_r;
74 char *atom_name;
75 bool result;
77 if(!(atom_name = xcb_atom_name_by_screen("_NET_WM_CM", globalconf.default_screen)))
79 warn("error getting composite manager atom");
80 return false;
83 atom_r = xcb_intern_atom_reply(globalconf.connection,
84 xcb_intern_atom_unchecked(globalconf.connection, false,
85 a_strlen(atom_name), atom_name),
86 NULL);
87 p_delete(&atom_name);
88 if(!atom_r)
89 return false;
91 selection_r = xcb_get_selection_owner_reply(globalconf.connection,
92 xcb_get_selection_owner_unchecked(globalconf.connection,
93 atom_r->atom),
94 NULL);
95 p_delete(&atom_r);
97 result = selection_r != NULL && selection_r->owner != XCB_NONE;
98 p_delete(&selection_r);
100 return result;
103 /** Quit awesome.
104 * \param L The Lua VM state.
105 * \return The number of elements pushed on stack.
107 static int
108 luaA_quit(lua_State *L)
110 g_main_loop_quit(globalconf.loop);
111 return 0;
114 /** Execute another application, probably a window manager, to replace
115 * awesome.
116 * \param L The Lua VM state.
117 * \return The number of elements pushed on stack.
118 * \luastack
119 * \lparam The command line to execute.
121 static int
122 luaA_exec(lua_State *L)
124 const char *cmd = luaL_checkstring(L, 1);
126 awesome_atexit(false);
128 a_exec(cmd);
129 return 0;
132 /** Restart awesome.
134 static int
135 luaA_restart(lua_State *L)
137 awesome_restart();
138 return 0;
141 /** Load an image from a given path.
142 * \param L The Lua VM state.
143 * \return The number of elements pushed on stack.
144 * \luastack
145 * \lparam The command line to execute.
147 static int
148 luaA_load_image(lua_State *L)
150 const char *filename = luaL_checkstring(L, 1);
151 cairo_surface_t *surface = draw_load_image(L, filename);
152 if (!surface)
153 return 0;
154 /* lua has to make sure to free the ref or we have a leak */
155 lua_pushlightuserdata(L, surface);
156 return 1;
159 /** UTF-8 aware string length computing.
160 * \param L The Lua VM state.
161 * \return The number of elements pushed on stack.
163 static int
164 luaA_mbstrlen(lua_State *L)
166 const char *cmd = luaL_checkstring(L, 1);
167 lua_pushnumber(L, (ssize_t) mbstowcs(NULL, NONULL(cmd), 0));
168 return 1;
171 /** Overload standard Lua next function to use __next key on metatable.
172 * \param L The Lua VM state.
173 * \return The number of elements pushed on stack.
175 static int
176 luaAe_next(lua_State *L)
178 if(luaL_getmetafield(L, 1, "__next"))
180 lua_insert(L, 1);
181 lua_call(L, lua_gettop(L) - 1, LUA_MULTRET);
182 return lua_gettop(L);
185 luaL_checktype(L, 1, LUA_TTABLE);
186 lua_settop(L, 2);
187 if(lua_next(L, 1))
188 return 2;
189 lua_pushnil(L);
190 return 1;
193 /** Overload lua_next() function by using __next metatable field
194 * to get next elements.
195 * \param L The Lua VM stack.
196 * \param idx The index number of elements in stack.
197 * \return 1 if more elements to come, 0 otherwise.
199 static int
200 luaA_next(lua_State *L, int idx)
202 if(luaL_getmetafield(L, idx, "__next"))
204 /* if idx is relative, reduce it since we got __next */
205 if(idx < 0) idx--;
206 /* copy table and then move key */
207 lua_pushvalue(L, idx);
208 lua_pushvalue(L, -3);
209 lua_remove(L, -4);
210 lua_pcall(L, 2, 2, 0);
211 /* next returned nil, it's the end */
212 if(lua_isnil(L, -1))
214 /* remove nil */
215 lua_pop(L, 2);
216 return 0;
218 return 1;
220 else if(lua_istable(L, idx))
221 return lua_next(L, idx);
222 /* remove the key */
223 lua_pop(L, 1);
224 return 0;
227 /** Generic pairs function.
228 * \param L The Lua VM state.
229 * \return The number of elements pushed on stack.
231 static int
232 luaA_generic_pairs(lua_State *L)
234 lua_pushvalue(L, lua_upvalueindex(1)); /* return generator, */
235 lua_pushvalue(L, 1); /* state, */
236 lua_pushnil(L); /* and initial value */
237 return 3;
240 /** Overload standard pairs function to use __pairs field of metatables.
241 * \param L The Lua VM state.
242 * \return The number of elements pushed on stack.
244 static int
245 luaAe_pairs(lua_State *L)
247 if(luaL_getmetafield(L, 1, "__pairs"))
249 lua_insert(L, 1);
250 lua_call(L, lua_gettop(L) - 1, LUA_MULTRET);
251 return lua_gettop(L);
254 luaL_checktype(L, 1, LUA_TTABLE);
255 return luaA_generic_pairs(L);
258 static int
259 luaA_ipairs_aux(lua_State *L)
261 int i = luaL_checkint(L, 2) + 1;
262 luaL_checktype(L, 1, LUA_TTABLE);
263 lua_pushinteger(L, i);
264 lua_rawgeti(L, 1, i);
265 return (lua_isnil(L, -1)) ? 0 : 2;
268 /** Overload standard ipairs function to use __ipairs field of metatables.
269 * \param L The Lua VM state.
270 * \return The number of elements pushed on stack.
272 static int
273 luaAe_ipairs(lua_State *L)
275 if(luaL_getmetafield(L, 1, "__ipairs"))
277 lua_insert(L, 1);
278 lua_call(L, lua_gettop(L) - 1, LUA_MULTRET);
279 return lua_gettop(L);
282 luaL_checktype(L, 1, LUA_TTABLE);
283 lua_pushvalue(L, lua_upvalueindex(1));
284 lua_pushvalue(L, 1);
285 lua_pushinteger(L, 0); /* and initial value */
286 return 3;
289 /** Enhanced type() function which recognize awesome objects.
290 * \param L The Lua VM state.
291 * \return The number of arguments pushed on the stack.
293 static int
294 luaAe_type(lua_State *L)
296 luaL_checkany(L, 1);
297 lua_pushstring(L, luaA_typename(L, 1));
298 return 1;
301 /** Replace various standards Lua functions with our own.
302 * \param L The Lua VM state.
304 static void
305 luaA_fixups(lua_State *L)
307 /* export string.wlen */
308 lua_getglobal(L, "string");
309 lua_pushcfunction(L, luaA_mbstrlen);
310 lua_setfield(L, -2, "wlen");
311 lua_pop(L, 1);
312 /* replace next */
313 lua_pushcfunction(L, luaAe_next);
314 lua_setglobal(L, "next");
315 /* replace pairs */
316 lua_pushcfunction(L, luaAe_next);
317 lua_pushcclosure(L, luaAe_pairs, 1); /* pairs get next as upvalue */
318 lua_setglobal(L, "pairs");
319 /* replace ipairs */
320 lua_pushcfunction(L, luaA_ipairs_aux);
321 lua_pushcclosure(L, luaAe_ipairs, 1);
322 lua_setglobal(L, "ipairs");
323 /* replace type */
324 lua_pushcfunction(L, luaAe_type);
325 lua_setglobal(L, "type");
326 /* set selection */
327 lua_pushcfunction(L, luaA_selection_get);
328 lua_setglobal(L, "selection");
331 /** Look for an item: table, function, etc.
332 * \param L The Lua VM state.
333 * \param item The pointer item.
335 bool
336 luaA_hasitem(lua_State *L, const void *item)
338 lua_pushnil(L);
339 while(luaA_next(L, -2))
341 if(lua_topointer(L, -1) == item)
343 /* remove value and key */
344 lua_pop(L, 2);
345 return true;
347 if(lua_istable(L, -1))
348 if(luaA_hasitem(L, item))
350 /* remove key and value */
351 lua_pop(L, 2);
352 return true;
354 /* remove value */
355 lua_pop(L, 1);
357 return false;
360 /** Browse a table pushed on top of the index, and put all its table and
361 * sub-table into an array.
362 * \param L The Lua VM state.
363 * \param elems The elements array.
364 * \return False if we encounter an elements already in list.
366 static bool
367 luaA_isloop_check(lua_State *L, cptr_array_t *elems)
369 if(lua_istable(L, -1))
371 const void *object = lua_topointer(L, -1);
373 /* Check that the object table is not already in the list */
374 for(int i = 0; i < elems->len; i++)
375 if(elems->tab[i] == object)
376 return false;
378 /* push the table in the elements list */
379 cptr_array_append(elems, object);
381 /* look every object in the "table" */
382 lua_pushnil(L);
383 while(luaA_next(L, -2))
385 if(!luaA_isloop_check(L, elems))
387 /* remove key and value */
388 lua_pop(L, 2);
389 return false;
391 /* remove value, keep key for next iteration */
392 lua_pop(L, 1);
395 return true;
398 /** Check if a table is a loop. When using tables as direct acyclic digram,
399 * this is useful.
400 * \param L The Lua VM state.
401 * \param idx The index of the table in the stack
402 * \return True if the table loops.
404 bool
405 luaA_isloop(lua_State *L, int idx)
407 /* elems is an elements array that we will fill with all array we
408 * encounter while browsing the tables */
409 cptr_array_t elems;
411 cptr_array_init(&elems);
413 /* push table on top */
414 lua_pushvalue(L, idx);
416 bool ret = luaA_isloop_check(L, &elems);
418 /* remove pushed table */
419 lua_pop(L, 1);
421 cptr_array_wipe(&elems);
423 return !ret;
426 /** awesome global table.
427 * \param L The Lua VM state.
428 * \return The number of elements pushed on stack.
429 * \luastack
430 * \lfield conffile The configuration file which has been loaded.
431 * \lfield version The version of awesome.
432 * \lfield release The release name of awesome.
433 * \lfield startup_errors Error message for errors that occured during startup.
434 * \lfield composite_manager_running True if a composite manager is running.
436 static int
437 luaA_awesome_index(lua_State *L)
439 if(luaA_usemetatable(L, 1, 2))
440 return 1;
442 const char *buf = luaL_checkstring(L, 2);
444 if(A_STREQ(buf, "conffile"))
446 lua_pushstring(L, conffile);
447 return 1;
450 if(A_STREQ(buf, "version"))
452 lua_pushliteral(L, AWESOME_VERSION);
453 return 1;
456 if(A_STREQ(buf, "release"))
458 lua_pushliteral(L, AWESOME_RELEASE);
459 return 1;
462 if(A_STREQ(buf, "startup_errors") && globalconf.startup_errors.len != 0)
464 lua_pushstring(L, globalconf.startup_errors.s);
465 return 1;
468 if(A_STREQ(buf, "composite_manager_running"))
470 lua_pushboolean(L, composite_manager_running());
471 return 1;
474 return 0;
477 /** Add a global signal.
478 * \param L The Lua VM state.
479 * \return The number of elements pushed on stack.
480 * \luastack
481 * \lparam A string with the event name.
482 * \lparam The function to call.
484 static int
485 luaA_awesome_connect_signal(lua_State *L)
487 const char *name = luaL_checkstring(L, 1);
488 luaA_checkfunction(L, 2);
489 signal_connect(&global_signals, name, luaA_object_ref(L, 2));
490 return 0;
493 /** Remove a global signal.
494 * \param L The Lua VM state.
495 * \return The number of elements pushed on stack.
496 * \luastack
497 * \lparam A string with the event name.
498 * \lparam The function to call.
500 static int
501 luaA_awesome_disconnect_signal(lua_State *L)
503 const char *name = luaL_checkstring(L, 1);
504 luaA_checkfunction(L, 2);
505 const void *func = lua_topointer(L, 2);
506 signal_disconnect(&global_signals, name, func);
507 luaA_object_unref(L, (void *) func);
508 return 0;
511 /** Emit a global signal.
512 * \param L The Lua VM state.
513 * \return The number of elements pushed on stack.
514 * \luastack
515 * \lparam A string with the event name.
516 * \lparam The function to call.
518 static int
519 luaA_awesome_emit_signal(lua_State *L)
521 signal_object_emit(L, &global_signals, luaL_checkstring(L, 1), lua_gettop(L) - 1);
522 return 0;
525 static int
526 luaA_panic(lua_State *L)
528 warn("unprotected error in call to Lua API (%s)",
529 lua_tostring(L, -1));
530 buffer_t buf;
531 backtrace_get(&buf);
532 warn("dumping backtrace\n%s", buf.s);
533 warn("restarting awesome");
534 awesome_restart();
535 return 0;
538 static int
539 luaA_dofunction_on_error(lua_State *L)
541 /* duplicate string error */
542 lua_pushvalue(L, -1);
543 /* emit error signal */
544 signal_object_emit(L, &global_signals, "debug::error", 1);
546 if(!luaL_dostring(L, "return debug.traceback(\"error while running function\", 3)"))
548 /* Move traceback before error */
549 lua_insert(L, -2);
550 /* Insert sentence */
551 lua_pushliteral(L, "\nerror: ");
552 /* Move it before error */
553 lua_insert(L, -2);
554 lua_concat(L, 3);
556 return 1;
559 /** Initialize the Lua VM
560 * \param xdg An xdg handle to use to get XDG basedir.
562 void
563 luaA_init(xdgHandle* xdg)
565 lua_State *L;
566 static const struct luaL_Reg awesome_lib[] =
568 { "quit", luaA_quit },
569 { "exec", luaA_exec },
570 { "spawn", luaA_spawn },
571 { "restart", luaA_restart },
572 { "connect_signal", luaA_awesome_connect_signal },
573 { "disconnect_signal", luaA_awesome_disconnect_signal },
574 { "emit_signal", luaA_awesome_emit_signal },
575 { "systray", luaA_systray },
576 { "load_image", luaA_load_image },
577 { "register_xproperty", luaA_register_xproperty },
578 { "__index", luaA_awesome_index },
579 { NULL, NULL }
582 L = globalconf.L = luaL_newstate();
584 /* Set panic function */
585 lua_atpanic(L, luaA_panic);
587 /* Set error handling function */
588 lualib_dofunction_on_error = luaA_dofunction_on_error;
590 luaL_openlibs(L);
592 luaA_fixups(L);
594 luaA_object_setup(L);
596 /* Export awesome lib */
597 luaA_openlib(L, "awesome", awesome_lib, awesome_lib);
599 /* Export root lib */
600 luaA_registerlib(L, "root", awesome_root_lib);
601 lua_pop(L, 1); /* luaA_registerlib() leaves the table on stack */
603 #ifdef WITH_DBUS
604 /* Export D-Bus lib */
605 luaA_registerlib(L, "dbus", awesome_dbus_lib);
606 lua_pop(L, 1); /* luaA_registerlib() leaves the table on stack */
607 #endif
609 /* Export keygrabber lib */
610 luaA_registerlib(L, "keygrabber", awesome_keygrabber_lib);
611 lua_pop(L, 1); /* luaA_registerlib() leaves the table on stack */
613 /* Export mousegrabber lib */
614 luaA_registerlib(L, "mousegrabber", awesome_mousegrabber_lib);
615 lua_pop(L, 1); /* luaA_registerlib() leaves the table on stack */
617 /* Export screen */
618 luaA_openlib(L, "screen", awesome_screen_methods, awesome_screen_meta);
620 /* Export mouse */
621 luaA_openlib(L, "mouse", awesome_mouse_methods, awesome_mouse_meta);
623 /* Export button */
624 button_class_setup(L);
626 /* Export tag */
627 tag_class_setup(L);
629 /* Export window */
630 window_class_setup(L);
632 /* Export drawable */
633 drawable_class_setup(L);
635 /* Export drawin */
636 drawin_class_setup(L);
638 /* Export client */
639 client_class_setup(L);
641 /* Export keys */
642 key_class_setup(L);
644 /* Export timer */
645 timer_class_setup(L);
647 /* add Lua search paths */
648 lua_getglobal(L, "package");
649 if (LUA_TTABLE != lua_type(L, 1))
651 warn("package is not a table");
652 return;
654 lua_getfield(L, 1, "path");
655 if (LUA_TSTRING != lua_type(L, 2))
657 warn("package.path is not a string");
658 lua_pop(L, 1);
659 return;
662 /* add XDG_CONFIG_DIR as include path */
663 const char * const *xdgconfigdirs = xdgSearchableConfigDirectories(xdg);
664 for(; *xdgconfigdirs; xdgconfigdirs++)
666 size_t len = a_strlen(*xdgconfigdirs);
667 lua_pushliteral(L, ";");
668 lua_pushlstring(L, *xdgconfigdirs, len);
669 lua_pushliteral(L, "/awesome/?.lua");
670 lua_concat(L, 3);
672 lua_pushliteral(L, ";");
673 lua_pushlstring(L, *xdgconfigdirs, len);
674 lua_pushliteral(L, "/awesome/?/init.lua");
675 lua_concat(L, 3);
677 lua_concat(L, 3); /* concatenate with package.path */
680 /* add Lua lib path (/usr/share/awesome/lib by default) */
681 lua_pushliteral(L, ";" AWESOME_LUA_LIB_PATH "/?.lua");
682 lua_pushliteral(L, ";" AWESOME_LUA_LIB_PATH "/?/init.lua");
683 lua_concat(L, 3); /* concatenate with package.path */
684 lua_setfield(L, 1, "path"); /* package.path = "concatenated string" */
686 lua_getfield(L, 1, "loaded");
688 lua_pop(L, 2); /* pop "package" and "package.loaded" */
690 signal_add(&global_signals, "debug::error");
691 signal_add(&global_signals, "debug::deprecation");
692 signal_add(&global_signals, "debug::index::miss");
693 signal_add(&global_signals, "debug::newindex::miss");
694 signal_add(&global_signals, "systray::update");
695 signal_add(&global_signals, "wallpaper_changed");
696 signal_add(&global_signals, "refresh");
697 signal_add(&global_signals, "exit");
700 static void
701 luaA_startup_error(const char *err)
703 if (globalconf.startup_errors.len > 0)
704 buffer_addsl(&globalconf.startup_errors, "\n\n");
705 buffer_adds(&globalconf.startup_errors, err);
708 static bool
709 luaA_loadrc(const char *confpath, bool run)
711 if(!luaL_loadfile(globalconf.L, confpath))
713 if(run)
715 /* Set the conffile right now so it can be used inside the
716 * configuration file. */
717 conffile = a_strdup(confpath);
718 /* Move error handling function before function */
719 lua_pushcfunction(globalconf.L, luaA_dofunction_on_error);
720 lua_insert(globalconf.L, -2);
721 if(lua_pcall(globalconf.L, 0, LUA_MULTRET, -2))
723 const char *err = lua_tostring(globalconf.L, -1);
724 luaA_startup_error(err);
725 fprintf(stderr, "%s\n", err);
726 /* An error happened, so reset this. */
727 conffile = NULL;
729 else
730 return true;
732 else
734 lua_pop(globalconf.L, 1);
735 return true;
738 else
740 const char *err = lua_tostring(globalconf.L, -1);
741 luaA_startup_error(err);
742 fprintf(stderr, "%s\n", err);
745 return false;
748 /** Load a configuration file.
749 * \param xdg An xdg handle to use to get XDG basedir.
750 * \param confpatharg The configuration file to load.
751 * \param run Run the configuration file.
753 bool
754 luaA_parserc(xdgHandle* xdg, const char *confpatharg, bool run)
756 char *confpath = NULL;
757 bool ret = false;
759 /* try to load, return if it's ok */
760 if(confpatharg)
762 if(luaA_loadrc(confpatharg, run))
764 ret = true;
765 goto bailout;
767 else if(!run)
768 goto bailout;
771 confpath = xdgConfigFind("awesome/rc.lua", xdg);
773 char *tmp = confpath;
775 /* confpath is "string1\0string2\0string3\0\0" */
776 while(*tmp)
778 if(luaA_loadrc(tmp, run))
780 ret = true;
781 goto bailout;
783 else if(!run)
784 goto bailout;
785 tmp += a_strlen(tmp) + 1;
788 bailout:
790 p_delete(&confpath);
792 return ret;
796 luaA_class_index_miss_property(lua_State *L, lua_object_t *obj)
798 signal_object_emit(L, &global_signals, "debug::index::miss", 2);
799 return 0;
803 luaA_class_newindex_miss_property(lua_State *L, lua_object_t *obj)
805 signal_object_emit(L, &global_signals, "debug::newindex::miss", 3);
806 return 0;
809 void
810 luaA_emit_refresh()
812 signal_object_emit(globalconf.L, &global_signals, "refresh", 0);
815 // vim: filetype=c:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:textwidth=80