Use tokens for faster lookup in luaH_luakit_get_special_dir
[luakit.git] / luah.c
blobc99f7c27bc8c1a7ca97f4c51c8680a9d9e370063
1 /*
2 * luah.c - Lua helper functions
4 * Copyright (C) 2010 Mason Larobina <mason.larobina@gmail.com>
5 * Copyright (C) 2008-2009 Julien Danjou <julien@danjou.info>
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation, either version 3 of the License, or
10 * (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with this program. If not, see <http://www.gnu.org/licenses/>.
22 #include <gtk/gtk.h>
23 #include <stdlib.h>
24 #include "common/util.h"
25 #include "common/lualib.h"
26 #include "luakit.h"
27 #include "widget.h"
28 #include "luah.h"
30 void
31 luaH_modifier_table_push(lua_State *L, guint state) {
32 gint i = 1;
33 lua_newtable(L);
34 if (state & GDK_MODIFIER_MASK) {
36 #define MODKEY(key, name) \
37 if (state & GDK_##key##_MASK) { \
38 lua_pushstring(L, name); \
39 lua_rawseti(L, -2, i++); \
42 MODKEY(SHIFT, "Shift");
43 MODKEY(LOCK, "Lock");
44 MODKEY(CONTROL, "Control");
45 MODKEY(MOD1, "Mod1");
46 MODKEY(MOD2, "Mod2");
47 MODKEY(MOD3, "Mod3");
48 MODKEY(MOD4, "Mod4");
49 MODKEY(MOD5, "Mod5");
51 #undef MODKEY
56 void
57 luaH_keystr_push(lua_State *L, guint keyval)
59 gchar ucs[7];
60 guint ulen;
61 guint32 ukval = gdk_keyval_to_unicode(keyval);
63 /* check for printable unicode character */
64 if (g_unichar_isgraph(ukval)) {
65 ulen = g_unichar_to_utf8(ukval, ucs);
66 ucs[ulen] = 0;
67 lua_pushstring(L, ucs);
69 /* sent keysym for non-printable characters */
70 else
71 lua_pushstring(L, gdk_keyval_name(keyval));
74 /* UTF-8 aware string length computing.
75 * Returns the number of elements pushed on the stack. */
76 static gint
77 luaH_utf8_strlen(lua_State *L)
79 const gchar *cmd = luaL_checkstring(L, 1);
80 lua_pushnumber(L, (ssize_t) g_utf8_strlen(NONULL(cmd), -1));
81 return 1;
84 /* Overload standard Lua next function to use __next key on metatable.
85 * Returns the number of elements pushed on stack. */
86 static gint
87 luaHe_next(lua_State *L)
89 if(luaL_getmetafield(L, 1, "__next")) {
90 lua_insert(L, 1);
91 lua_call(L, lua_gettop(L) - 1, LUA_MULTRET);
92 return lua_gettop(L);
94 luaL_checktype(L, 1, LUA_TTABLE);
95 lua_settop(L, 2);
96 if(lua_next(L, 1))
97 return 2;
98 lua_pushnil(L);
99 return 1;
102 /* Overload lua_next() function by using __next metatable field to get
103 * next elements. `idx` is the index number of elements in stack.
104 * Returns 1 if more elements to come, 0 otherwise. */
105 gint
106 luaH_next(lua_State *L, gint idx)
108 if(luaL_getmetafield(L, idx, "__next")) {
109 /* if idx is relative, reduce it since we got __next */
110 if(idx < 0) idx--;
111 /* copy table and then move key */
112 lua_pushvalue(L, idx);
113 lua_pushvalue(L, -3);
114 lua_remove(L, -4);
115 lua_pcall(L, 2, 2, 0);
116 /* next returned nil, it's the end */
117 if(lua_isnil(L, -1)) {
118 /* remove nil */
119 lua_pop(L, 2);
120 return 0;
122 return 1;
124 else if(lua_istable(L, idx))
125 return lua_next(L, idx);
126 /* remove the key */
127 lua_pop(L, 1);
128 return 0;
131 /* Generic pairs function.
132 * Returns the number of elements pushed on stack. */
133 static gint
134 luaH_generic_pairs(lua_State *L)
136 lua_pushvalue(L, lua_upvalueindex(1)); /* return generator, */
137 lua_pushvalue(L, 1); /* state, */
138 lua_pushnil(L); /* and initial value */
139 return 3;
142 /* Overload standard pairs function to use __pairs field of metatables.
143 * Returns the number of elements pushed on stack. */
144 static gint
145 luaHe_pairs(lua_State *L)
147 if(luaL_getmetafield(L, 1, "__pairs")) {
148 lua_insert(L, 1);
149 lua_call(L, lua_gettop(L) - 1, LUA_MULTRET);
150 return lua_gettop(L);
152 luaL_checktype(L, 1, LUA_TTABLE);
153 return luaH_generic_pairs(L);
156 static gint
157 luaH_ipairs_aux(lua_State *L)
159 gint i = luaL_checkint(L, 2) + 1;
160 luaL_checktype(L, 1, LUA_TTABLE);
161 lua_pushinteger(L, i);
162 lua_rawgeti(L, 1, i);
163 return (lua_isnil(L, -1)) ? 0 : 2;
166 /* Overload standard ipairs function to use __ipairs field of metatables.
167 * Returns the number of elements pushed on stack. */
168 static gint
169 luaHe_ipairs(lua_State *L)
171 if(luaL_getmetafield(L, 1, "__ipairs")) {
172 lua_insert(L, 1);
173 lua_call(L, lua_gettop(L) - 1, LUA_MULTRET);
174 return lua_gettop(L);
177 luaL_checktype(L, 1, LUA_TTABLE);
178 lua_pushvalue(L, lua_upvalueindex(1));
179 lua_pushvalue(L, 1);
180 lua_pushinteger(L, 0); /* and initial value */
181 return 3;
184 /* Enhanced type() function which recognize luakit objects.
185 * \param L The Lua VM state.
186 * \return The number of arguments pushed on the stack.
188 static gint
189 luaHe_type(lua_State *L)
191 luaL_checkany(L, 1);
192 lua_pushstring(L, luaH_typename(L, 1));
193 return 1;
197 /* Fix up and add handy standard lib functions */
198 static void
199 luaH_fixups(lua_State *L)
201 /* export string.wlen */
202 lua_getglobal(L, "string");
203 lua_pushcfunction(L, &luaH_utf8_strlen);
204 lua_setfield(L, -2, "wlen");
205 lua_pop(L, 1);
206 /* replace next */
207 lua_pushliteral(L, "next");
208 lua_pushcfunction(L, luaHe_next);
209 lua_settable(L, LUA_GLOBALSINDEX);
210 /* replace pairs */
211 lua_pushliteral(L, "pairs");
212 lua_pushcfunction(L, luaHe_next);
213 lua_pushcclosure(L, luaHe_pairs, 1); /* pairs get next as upvalue */
214 lua_settable(L, LUA_GLOBALSINDEX);
215 /* replace ipairs */
216 lua_pushliteral(L, "ipairs");
217 lua_pushcfunction(L, luaH_ipairs_aux);
218 lua_pushcclosure(L, luaHe_ipairs, 1);
219 lua_settable(L, LUA_GLOBALSINDEX);
220 /* replace type */
221 lua_pushliteral(L, "type");
222 lua_pushcfunction(L, luaHe_type);
223 lua_settable(L, LUA_GLOBALSINDEX);
226 /* Look for an item: table, function, etc.
227 * \param L The Lua VM state.
228 * \param item The pointer item.
230 gboolean
231 luaH_hasitem(lua_State *L, gconstpointer item)
233 lua_pushnil(L);
234 while(luaH_next(L, -2)) {
235 if(lua_topointer(L, -1) == item) {
236 /* remove value and key */
237 lua_pop(L, 2);
238 return TRUE;
240 if(lua_istable(L, -1))
241 if(luaH_hasitem(L, item)) {
242 /* remove key and value */
243 lua_pop(L, 2);
244 return TRUE;
246 /* remove value */
247 lua_pop(L, 1);
249 return FALSE;
252 /* Browse a table pushed on top of the index, and put all its table and
253 * sub-table ginto an array.
254 * \param L The Lua VM state.
255 * \param elems The elements array.
256 * \return False if we encounter an elements already in list.
258 static gboolean
259 luaH_isloop_check(lua_State *L, GPtrArray *elems)
261 if(lua_istable(L, -1)) {
262 gconstpointer object = lua_topointer(L, -1);
264 /* Check that the object table is not already in the list */
265 for(guint i = 0; i < elems->len; i++)
266 if(elems->pdata[i] == object)
267 return FALSE;
269 /* push the table in the elements list */
270 g_ptr_array_add(elems, (gpointer) object);
272 /* look every object in the "table" */
273 lua_pushnil(L);
274 while(luaH_next(L, -2)) {
275 if(!luaH_isloop_check(L, elems)) {
276 /* remove key and value */
277 lua_pop(L, 2);
278 return FALSE;
280 /* remove value, keep key for next iteration */
281 lua_pop(L, 1);
284 return TRUE;
287 /* Check if a table is a loop. When using tables as direct acyclic digram,
288 * this is useful.
289 * \param L The Lua VM state.
290 * \param idx The index of the table in the stack
291 * \return True if the table loops.
293 gboolean
294 luaH_isloop(lua_State *L, gint idx)
296 /* elems is an elements array that we will fill with all array we
297 * encounter while browsing the tables */
298 GPtrArray *elems = g_ptr_array_new();
300 /* push table on top */
301 lua_pushvalue(L, idx);
303 gboolean ret = luaH_isloop_check(L, elems);
305 /* remove pushed table */
306 lua_pop(L, 1);
308 g_ptr_array_free(elems, TRUE);
310 return !ret;
313 /* Returns a string from X selection.
314 * \param L The Lua VM state.
315 * \return The number of elements pushed on stack (1).
317 static gint
318 luaH_luakit_selection(lua_State *L)
320 int n = lua_gettop(L);
321 GdkAtom atom = GDK_SELECTION_PRIMARY;
323 if (n) {
324 const gchar *arg = luaL_checkstring(L, 1);
325 /* Follow xclip(1) behavior: check only the first character of argument */
326 switch (arg[0]) {
327 case 'p':
328 break;
329 case 's':
330 atom = GDK_SELECTION_SECONDARY;
331 break;
332 case 'c':
333 atom = GDK_SELECTION_CLIPBOARD;
334 break;
335 default:
336 luaL_argerror(L, 1, "should be 'primary', 'secondary' or 'clipboard'");
337 break;
340 GtkClipboard *selection = gtk_clipboard_get(atom);
341 gchar *text = gtk_clipboard_wait_for_text(selection);
342 lua_pushstring(L, text);
343 g_free(text);
344 return 1;
347 static gint
348 luaH_luakit_get_special_dir(lua_State *L)
350 size_t len;
351 const gchar *name = luaL_checklstring(L, 1, &len);
352 luakit_token_t token = l_tokenize(name, len);
353 GUserDirectory atom;
354 /* match token with G_USER_DIR_* atom */
355 switch(token) {
356 case L_TK_DESKTOP: atom = G_USER_DIRECTORY_DESKTOP; break;
357 case L_TK_DOCUMENTS: atom = G_USER_DIRECTORY_DOCUMENTS; break;
358 case L_TK_DOWNLOAD: atom = G_USER_DIRECTORY_DOWNLOAD; break;
359 case L_TK_MUSIC: atom = G_USER_DIRECTORY_MUSIC; break;
360 case L_TK_PICTURES: atom = G_USER_DIRECTORY_PICTURES; break;
361 case L_TK_PUBLIC_SHARE: atom = G_USER_DIRECTORY_PUBLIC_SHARE; break;
362 case L_TK_TEMPLATES: atom = G_USER_DIRECTORY_TEMPLATES; break;
363 case L_TK_VIDEOS: atom = G_USER_DIRECTORY_VIDEOS; break;
364 default:
365 warn("unknown atom G_USER_DIRECTORY_%s", name);
366 luaL_argerror(L, 1, "invalid G_USER_DIRECTORY_* atom");
367 return 0;
369 lua_pushstring(L, g_get_user_special_dir(atom));
370 return 1;
373 /* luakit global table.
374 * \param L The Lua VM state.
375 * \return The number of elements pushed on stack.
376 * \luastack
377 * \lfield font The default font.
378 * \lfield font_height The default font height.
379 * \lfield conffile The configuration file which has been loaded.
381 static gint
382 luaH_luakit_index(lua_State *L)
384 if(luaH_usemetatable(L, 1, 2))
385 return 1;
387 size_t len;
388 widget_t *w;
389 const gchar *prop = luaL_checklstring(L, 2, &len);
390 luakit_token_t token = l_tokenize(prop, len);
392 switch(token)
394 case L_TK_WINDOWS:
395 lua_newtable(L);
396 for (guint i = 0; i < globalconf.windows->len; i++) {
397 w = globalconf.windows->pdata[i];
398 luaH_object_push(L, w->ref);
399 lua_rawseti(L, -2, i+1);
401 return 1;
403 case L_TK_SELECTION:
404 lua_pushcfunction(L, luaH_luakit_selection);
405 return 1;
407 case L_TK_INSTALL_PATH:
408 lua_pushliteral(L, LUAKIT_INSTALL_PATH);
409 return 1;
411 case L_TK_CONFIG_DIR:
412 lua_pushstring(L, globalconf.config_dir);
413 return 1;
415 case L_TK_DATA_DIR:
416 lua_pushstring(L, globalconf.data_dir);
417 return 1;
419 case L_TK_CACHE_DIR:
420 lua_pushstring(L, globalconf.cache_dir);
421 return 1;
423 case L_TK_VERBOSE:
424 lua_pushboolean(L, globalconf.verbose);
425 return 1;
427 case L_TK_GET_SPECIAL_DIR:
428 lua_pushcfunction(L, luaH_luakit_get_special_dir);
429 return 1;
431 default:
432 break;
434 return 0;
437 /* Newindex function for the luakit global table.
438 * \param L The Lua VM state.
439 * \return The number of elements pushed on stack.
441 static gint
442 luaH_luakit_newindex(lua_State *L)
444 if(luaH_usemetatable(L, 1, 2))
445 return 1;
447 size_t len;
448 const gchar *buf = luaL_checklstring(L, 2, &len);
450 debug("Luakit newindex %s", buf);
452 return 0;
455 /* Add a global signal.
456 * Returns the number of elements pushed on stack.
457 * \luastack
458 * \lparam A string with the event name.
459 * \lparam The function to call.
461 static gint
462 luaH_luakit_add_signal(lua_State *L)
464 const gchar *name = luaL_checkstring(L, 1);
465 luaH_checkfunction(L, 2);
466 signal_add(globalconf.signals, name, luaH_object_ref(L, 2));
467 return 0;
470 /* Remove a global signal.
471 * \param L The Lua VM state.
472 * \return The number of elements pushed on stack.
473 * \luastack
474 * \lparam A string with the event name.
475 * \lparam The function to call.
477 static gint
478 luaH_luakit_remove_signal(lua_State *L)
480 const gchar *name = luaL_checkstring(L, 1);
481 luaH_checkfunction(L, 2);
482 gpointer func = (gpointer) lua_topointer(L, 2);
483 signal_remove(globalconf.signals, name, func);
484 luaH_object_unref(L, (void *) func);
485 return 0;
488 /* Emit a global signal.
489 * \param L The Lua VM state.
490 * \return The number of elements pushed on stack.
491 * \luastack
492 * \lparam A string with the event name.
493 * \lparam The function to call.
495 static gint
496 luaH_luakit_emit_signal(lua_State *L)
498 signal_object_emit(L, globalconf.signals, luaL_checkstring(L, 1), lua_gettop(L) - 1);
499 return 0;
502 static gint
503 luaH_panic(lua_State *L)
505 warn("unprotected error in call to Lua API (%s)", lua_tostring(L, -1));
506 return 0;
509 static gint
510 luaH_quit(lua_State *L)
512 (void) L;
513 gtk_main_quit();
514 return 0;
517 static gint
518 luaH_dofunction_on_error(lua_State *L)
520 /* duplicate string error */
521 lua_pushvalue(L, -1);
522 /* emit error signal */
523 signal_object_emit(L, globalconf.signals, "debug::error", 1);
525 if(!luaL_dostring(L, "return debug.traceback(\"error while running function\", 3)"))
527 /* Move traceback before error */
528 lua_insert(L, -2);
529 /* Insert sentence */
530 lua_pushliteral(L, "\nerror: ");
531 /* Move it before error */
532 lua_insert(L, -2);
533 lua_concat(L, 3);
535 return 1;
538 void
539 luaH_init(void)
541 lua_State *L;
543 static const struct luaL_reg luakit_lib[] = {
544 { "quit", luaH_quit },
545 { "add_signal", luaH_luakit_add_signal },
546 { "remove_signal", luaH_luakit_remove_signal },
547 { "emit_signal", luaH_luakit_emit_signal },
548 { "__index", luaH_luakit_index },
549 { "__newindex", luaH_luakit_newindex },
550 { NULL, NULL }
553 /* Lua VM init */
554 L = globalconf.L = luaL_newstate();
556 /* Set panic fuction */
557 lua_atpanic(L, luaH_panic);
559 /* Set error handling function */
560 lualib_dofunction_on_error = luaH_dofunction_on_error;
562 luaL_openlibs(L);
564 luaH_fixups(L);
566 luaH_object_setup(L);
568 /* Export luakit lib */
569 luaH_openlib(L, "luakit", luakit_lib, luakit_lib);
571 /* Export widget */
572 widget_class_setup(L);
574 /* add Lua search paths */
575 lua_getglobal(L, "package");
576 if(LUA_TTABLE != lua_type(L, 1)) {
577 warn("package is not a table");
578 return;
580 lua_getfield(L, 1, "path");
581 if(LUA_TSTRING != lua_type(L, 2)) {
582 warn("package.path is not a string");
583 lua_pop(L, 1);
584 return;
587 /* compile list of package search paths */
588 GPtrArray *paths = g_ptr_array_new_with_free_func(g_free);
590 #if DEVELOPMENT_PATHS
591 /* allows for testing luakit in the project directory */
592 g_ptr_array_add(paths, g_strdup("./lib"));
593 #endif
595 /* add users config dir (see: XDG_CONFIG_DIR) */
596 g_ptr_array_add(paths, g_build_filename(globalconf.config_dir, "lib", NULL));
598 /* add system config dirs (see: XDG_CONFIG_DIRS) */
599 const gchar* const *config_dirs = g_get_system_config_dirs();
600 for (; *config_dirs; config_dirs++)
601 g_ptr_array_add(paths, g_build_filename(*config_dirs, "luakit", "lib", NULL));
603 /* add luakit install path */
604 g_ptr_array_add(paths, g_build_filename(LUAKIT_INSTALL_PATH, "lib", NULL));
606 for (gpointer *path = paths->pdata; *path; path++) {
607 lua_pushliteral(L, ";");
608 lua_pushstring(L, *path);
609 lua_pushliteral(L, "/?.lua");
610 lua_concat(L, 3);
612 lua_pushliteral(L, ";");
613 lua_pushstring(L, *path);
614 lua_pushliteral(L, "/?/init.lua");
615 lua_concat(L, 3);
617 /* concat with package.path */
618 lua_concat(L, 3);
621 g_ptr_array_free(paths, TRUE);
623 /* package.path = "concatenated string" */
624 lua_setfield(L, 1, "path");
627 gboolean
628 luaH_loadrc(const gchar *confpath, gboolean run)
630 debug("Loading rc: %s", confpath);
631 lua_State *L = globalconf.L;
632 if(!luaL_loadfile(L, confpath)) {
633 if(run) {
634 if(lua_pcall(L, 0, LUA_MULTRET, 0)) {
635 g_fprintf(stderr, "%s\n", lua_tostring(L, -1));
636 } else
637 return TRUE;
638 } else
639 lua_pop(L, 1);
640 return TRUE;
641 } else
642 g_fprintf(stderr, "%s\n", lua_tostring(L, -1));
643 return FALSE;
646 /* Load a configuration file. */
647 gboolean
648 luaH_parserc(const gchar *confpath, gboolean run)
650 const gchar* const *config_dirs = NULL;
651 gboolean ret = FALSE;
652 GPtrArray *paths = NULL;
654 /* try to load, return if it's ok */
655 if(confpath) {
656 if(luaH_loadrc(confpath, run))
657 ret = TRUE;
658 goto bailout;
661 /* compile list of config search paths */
662 paths = g_ptr_array_new_with_free_func(g_free);
664 #if DEVELOPMENT_PATHS
665 /* allows for testing luakit in the project directory */
666 g_ptr_array_add(paths, g_strdup("./rc.lua"));
667 #endif
669 /* search users config dir (see: XDG_CONFIG_HOME) */
670 g_ptr_array_add(paths, g_build_filename(globalconf.config_dir, "rc.lua", NULL));
672 /* search system config dirs (see: XDG_CONFIG_DIRS) */
673 config_dirs = g_get_system_config_dirs();
674 for(; *config_dirs; config_dirs++)
675 g_ptr_array_add(paths, g_build_filename(*config_dirs, "luakit", "rc.lua", NULL));
677 for (gpointer *path = paths->pdata; *path; path++) {
678 if (file_exists(*path)) {
679 if(luaH_loadrc(*path, run)) {
680 globalconf.confpath = g_strdup(*path);
681 ret = TRUE;
682 goto bailout;
683 } else if(!run)
684 goto bailout;
688 bailout:
690 if (paths) g_ptr_array_free(paths, TRUE);
691 return ret;
694 gint
695 luaH_class_index_miss_property(lua_State *L, lua_object_t *obj)
697 (void) obj;
698 signal_object_emit(L, globalconf.signals, "debug::index::miss", 2);
699 return 0;
702 gint
703 luaH_class_newindex_miss_property(lua_State *L, lua_object_t *obj)
705 (void) obj;
706 signal_object_emit(L, globalconf.signals, "debug::newindex::miss", 3);
707 return 0;
710 // vim: ft=c:et:sw=4:ts=8:sts=4:tw=80