[all] Implement an atom cache in xutil as an ordered linked-list
[awesome.git] / awesome.c
blobc4892f29bcc2db8e17682ecc96632bdbd120046e
1 /*
2 * awesome.c - awesome main functions
4 * Copyright © 2007-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 #define _GNU_SOURCE
23 #include <getopt.h>
25 #include <errno.h>
26 #include <locale.h>
27 #include <stdio.h>
28 #include <unistd.h>
29 #include <sys/select.h>
30 #include <sys/types.h>
31 #include <sys/stat.h>
32 #include <sys/socket.h>
33 #include <sys/un.h>
34 #include <fcntl.h>
35 #include <signal.h>
37 #include <xcb/xcb.h>
38 #include <xcb/shape.h>
39 #include <xcb/randr.h>
40 #include <xcb/xcb_aux.h>
41 #include <xcb/xcb_atom.h>
42 #include <xcb/xcb_icccm.h>
44 #include "config.h"
45 #include "awesome.h"
46 #include "event.h"
47 #include "layout.h"
48 #include "screen.h"
49 #include "statusbar.h"
50 #include "window.h"
51 #include "client.h"
52 #include "focus.h"
53 #include "ewmh.h"
54 #include "tag.h"
55 #include "dbus.h"
56 #include "common/socket.h"
57 #include "common/version.h"
58 #include "common/configopts.h"
59 #include "common/xutil.h"
61 static bool running = true;
63 AwesomeConf globalconf;
65 typedef struct
67 xcb_window_t id;
68 xcb_query_tree_cookie_t tree_cookie;
69 } root_win_t;
71 /** Scan X to find windows to manage
73 static void
74 scan()
76 int i, screen, real_screen, tree_c_len;
77 const int screen_max = xcb_setup_roots_length(xcb_get_setup(globalconf.connection));
78 root_win_t *root_wins = p_new(root_win_t, screen_max);
79 xcb_query_tree_reply_t *tree_r;
80 xcb_window_t *wins = NULL;
81 xcb_get_window_attributes_cookie_t *attr_wins = NULL;
82 xcb_get_geometry_cookie_t **geom_wins = NULL;
83 xcb_get_window_attributes_reply_t *attr_r;
84 xcb_get_geometry_reply_t *geom_r;
86 for(screen = 0; screen < screen_max; screen++)
88 /* Get the root window ID associated to this screen */
89 root_wins[screen].id = xcb_aux_get_screen(globalconf.connection, screen)->root;
91 /* Get the window tree associated to this screen */
92 root_wins[screen].tree_cookie = xcb_query_tree_unchecked(globalconf.connection,
93 root_wins[screen].id);
96 for(screen = 0; screen < screen_max; screen++)
98 tree_r = xcb_query_tree_reply(globalconf.connection,
99 root_wins[screen].tree_cookie,
100 NULL);
102 if(!tree_r)
103 continue;
105 /* Get the tree of the children Windows of the current root
106 * Window */
107 if(!(wins = xcb_query_tree_children(tree_r)))
108 eprint("E: cannot get tree children\n");
109 tree_c_len = xcb_query_tree_children_length(tree_r);
110 attr_wins = p_new(xcb_get_window_attributes_cookie_t, tree_c_len);
112 for(i = 0; i < tree_c_len; i++)
113 attr_wins[i] = xcb_get_window_attributes_unchecked(globalconf.connection,
114 wins[i]);
116 geom_wins = p_new(xcb_get_geometry_cookie_t *, tree_c_len);
118 for(i = 0; i < tree_c_len; i++)
120 attr_r = xcb_get_window_attributes_reply(globalconf.connection,
121 attr_wins[i],
122 NULL);
124 if(!attr_r || attr_r->override_redirect ||
125 !(attr_r->map_state == XCB_MAP_STATE_VIEWABLE ||
126 window_getstate(wins[i]) == XCB_WM_ICONIC_STATE))
128 p_delete(&attr_r);
129 continue;
132 p_delete(&attr_r);
134 /* Get the geometry of the current window */
135 geom_wins[i] = p_new(xcb_get_geometry_cookie_t, 1);
136 *(geom_wins[i]) = xcb_get_geometry_unchecked(globalconf.connection, wins[i]);
139 p_delete(&attr_wins);
141 for(i = 0; i < tree_c_len; i++)
143 if(!geom_wins[i])
144 continue;
146 if(!(geom_r = xcb_get_geometry_reply(globalconf.connection,
147 *(geom_wins[i]), NULL)))
148 continue;
150 real_screen = screen_get_bycoord(globalconf.screens_info, screen,
151 geom_r->x, geom_r->y);
153 client_manage(wins[i], geom_r, real_screen);
155 p_delete(&geom_r);
156 p_delete(&geom_wins[i]);
159 p_delete(&geom_wins);
160 p_delete(&tree_r);
162 p_delete(&root_wins);
165 /** Equivalent to 'XCreateFontCursor()', error are handled by the
166 * default current error handler
167 * \param cursor_font type of cursor to use
168 * \return allocated cursor font
170 static xcb_cursor_t
171 create_font_cursor(unsigned int cursor_font)
173 xcb_font_t font;
174 xcb_cursor_t cursor;
176 /* Get the font for the cursor*/
177 font = xcb_generate_id(globalconf.connection);
178 xcb_open_font(globalconf.connection, font, strlen("cursor"), "cursor");
180 cursor = xcb_generate_id(globalconf.connection);
181 xcb_create_glyph_cursor (globalconf.connection, cursor, font, font,
182 cursor_font, cursor_font + 1,
183 0, 0, 0,
184 65535, 65535, 65535);
186 return cursor;
189 /** Startup Error handler to check if another window manager
190 * is already running.
191 * \param data Additional optional parameters data
192 * \param c X connection
193 * \param error Error event
195 static int __attribute__ ((noreturn))
196 xerrorstart(void * data __attribute__ ((unused)),
197 xcb_connection_t * c __attribute__ ((unused)),
198 xcb_generic_error_t * error __attribute__ ((unused)))
200 eprint("another window manager is already running\n");
203 /** Quit awesome.
204 * \param screen Screen ID
205 * \param arg nothing
206 * \ingroup ui_callback
208 void
209 uicb_quit(int screen __attribute__ ((unused)), char *arg __attribute__ ((unused)))
211 running = false;
214 /** Function to exit on some signals.
215 * \param sig the signal received, unused
217 static void
218 exit_on_signal(int sig __attribute__ ((unused)))
220 running = false;
223 /** \brief awesome xerror function
224 * There's no way to check accesses to destroyed windows, thus those cases are
225 * ignored (especially on UnmapNotify's). Other types of errors call Xlibs
226 * default error handler, which may call exit.
227 * \param edpy display ref
228 * \param ee XErrorEvent event
229 * \return 0 if no error, or xerror's xlib return status
231 static int
232 xerror(void *data __attribute__ ((unused)),
233 xcb_connection_t *c __attribute__ ((unused)),
234 xcb_generic_error_t *e)
236 xutil_error_t *err = xutil_get_error(e);
237 if(!err)
238 return 0;
240 if(e->error_code == BadWindow
241 || (e->error_code == BadMatch && err->request_code == XCB_SET_INPUT_FOCUS)
242 || (e->error_code == BadValue && err->request_code == XCB_KILL_CLIENT)
243 || (err->request_code == XCB_CONFIGURE_WINDOW && e->error_code == BadMatch))
245 xutil_delete_error(err);
246 return 0;
249 warn("fatal error: request=%s, error=%s\n", err->request_label, err->error_label);
250 xutil_delete_error(err);
253 * Xlib code was using default X error handler, namely
254 * '_XDefaultError()', which displays more informations about the
255 * error and also exit if 'error_code'' equals to
256 * 'BadImplementation'
258 * \todo display more informations about the error (like the Xlib default error handler)
260 if(e->error_code == BadImplementation)
261 exit(EXIT_FAILURE);
263 return 0;
266 /** Print help and exit(2) with given exit_code.
267 * \param exit_code the exit code
269 static void __attribute__ ((noreturn))
270 exit_help(int exit_code)
272 FILE *outfile = (exit_code == EXIT_SUCCESS) ? stdout : stderr;
273 fprintf(outfile,
274 "Usage: awesome [OPTION]\n\
275 -h, --help show help\n\
276 -v, --version show version\n\
277 -c, --config FILE configuration file to use\n\
278 -k, --check check configuration file syntax\n");
279 exit(exit_code);
282 /** Hello, this is main.
283 * \param argc who knows
284 * \param argv who knows
285 * \return EXIT_SUCCESS I hope
288 main(int argc, char **argv)
290 char buf[1024];
291 const char *confpath = NULL;
292 int r, xfd, csfd, dbusfd, i, screen_nbr, opt;
293 ssize_t cmdlen = 1;
294 const xcb_query_extension_reply_t *shape_query, *randr_query;
295 statusbar_t *statusbar;
296 fd_set rd;
297 xcb_generic_event_t *ev;
298 struct sockaddr_un *addr;
299 client_t *c;
300 bool confcheck = false;
301 static struct option long_options[] =
303 {"help", 0, NULL, 'h'},
304 {"version", 0, NULL, 'v'},
305 {"check", 0, NULL, 'k'},
306 {"config", 1, NULL, 'c'},
307 {NULL, 0, NULL, 0}
310 /* save argv */
311 for(i = 0; i < argc; i++)
312 cmdlen += a_strlen(argv[i]) + 1;
314 globalconf.argv = p_new(char, cmdlen);
315 a_strcpy(globalconf.argv, cmdlen, argv[0]);
317 for(i = 1; i < argc; i++)
319 a_strcat(globalconf.argv, cmdlen, " ");
320 a_strcat(globalconf.argv, cmdlen, argv[i]);
323 /* check args */
324 while((opt = getopt_long(argc, argv, "vhkc:s",
325 long_options, NULL)) != -1)
326 switch(opt)
328 case 'v':
329 eprint_version("awesome");
330 break;
331 case 'h':
332 exit_help(EXIT_SUCCESS);
333 break;
334 case 'c':
335 if(a_strlen(optarg))
336 confpath = a_strdup(optarg);
337 else
338 eprint("-c option requires a file name\n");
339 break;
340 case 'k':
341 confcheck = true;
342 break;
345 /* Text won't be printed correctly otherwise */
346 setlocale(LC_CTYPE, "");
348 if(confcheck)
349 return config_check(confpath);
351 /* X stuff */
352 globalconf.connection = xcb_connect(NULL, &globalconf.default_screen);
353 if(xcb_connection_has_error(globalconf.connection))
354 eprint("cannot open display\n");
356 /* Get the file descriptor corresponding to the X connection */
357 xfd = xcb_get_file_descriptor(globalconf.connection);
359 /* Allocate a handler which will holds all errors and events */
360 globalconf.evenths = xcb_alloc_event_handlers(globalconf.connection);
361 xutil_set_error_handler_catch_all(globalconf.evenths, xerrorstart, NULL);
363 const uint32_t select_input_val = XCB_EVENT_MASK_SUBSTRUCTURE_REDIRECT;
365 for(screen_nbr = 0;
366 screen_nbr < xcb_setup_roots_length(xcb_get_setup(globalconf.connection));
367 screen_nbr++)
368 /* This causes an error if some other window manager is running */
369 xcb_change_window_attributes(globalconf.connection,
370 xcb_aux_get_screen(globalconf.connection, screen_nbr)->root,
371 XCB_CW_EVENT_MASK, &select_input_val);
373 /* Need to xcb_flush to validate error handler */
374 xcb_aux_sync(globalconf.connection);
376 /* Process all errors in the queue if any */
377 xcb_poll_for_event_loop(globalconf.evenths);
379 /* Set the default xerror handler */
380 xutil_set_error_handler_catch_all(globalconf.evenths, xerror, NULL);
382 /* Allocate the key symbols */
383 globalconf.keysyms = xcb_key_symbols_alloc(globalconf.connection);
385 /* Get the NumLock, ShiftLock and CapsLock masks */
386 xutil_getlockmask(globalconf.connection, globalconf.keysyms, &globalconf.numlockmask,
387 &globalconf.shiftlockmask, &globalconf.capslockmask);
389 /* init Atoms cache and then EWMH atoms */
390 atom_cache_list_init(&globalconf.atoms);
391 ewmh_init_atoms();
393 /* init screens struct */
394 globalconf.screens_info = screensinfo_new(globalconf.connection);
395 globalconf.screens = p_new(VirtScreen, globalconf.screens_info->nscreen);
396 focus_add_client(NULL);
398 /* parse config */
399 config_parse(confpath);
401 /* init cursors */
402 globalconf.cursor[CurNormal] = create_font_cursor(CURSOR_LEFT_PTR);
403 globalconf.cursor[CurResize] = create_font_cursor(CURSOR_SIZING);
404 globalconf.cursor[CurMove] = create_font_cursor(CURSOR_FLEUR);
406 /* for each virtual screen */
407 for(screen_nbr = 0; screen_nbr < globalconf.screens_info->nscreen; screen_nbr++)
409 /* view at least one tag */
410 tag_view(globalconf.screens[screen_nbr].tags, true);
411 for(statusbar = globalconf.screens[screen_nbr].statusbar;
412 statusbar; statusbar = statusbar->next)
413 statusbar_init(statusbar);
416 /* select for events */
417 const uint32_t change_win_vals[] =
419 XCB_EVENT_MASK_SUBSTRUCTURE_REDIRECT | XCB_EVENT_MASK_SUBSTRUCTURE_NOTIFY
420 | XCB_EVENT_MASK_ENTER_WINDOW | XCB_EVENT_MASK_LEAVE_WINDOW
421 | XCB_EVENT_MASK_STRUCTURE_NOTIFY,
422 globalconf.cursor[CurNormal]
425 /* do this only for real screen */
426 for(screen_nbr = 0;
427 screen_nbr < xcb_setup_roots_length(xcb_get_setup(globalconf.connection));
428 screen_nbr++)
430 xcb_change_window_attributes(globalconf.connection,
431 xcb_aux_get_screen(globalconf.connection, screen_nbr)->root,
432 XCB_CW_EVENT_MASK | XCB_CW_CURSOR,
433 change_win_vals);
434 ewmh_set_supported_hints(screen_nbr);
435 /* call this to at least grab root window clicks */
436 window_root_grabbuttons(screen_nbr);
437 window_root_grabkeys(screen_nbr);
440 /* scan existing windows */
441 scan();
443 /* process all errors in the queue if any */
444 xcb_poll_for_event_loop(globalconf.evenths);
446 set_button_press_event_handler(globalconf.evenths, event_handle_buttonpress, NULL);
447 set_configure_request_event_handler(globalconf.evenths, event_handle_configurerequest, NULL);
448 set_configure_notify_event_handler(globalconf.evenths, event_handle_configurenotify, NULL);
449 set_destroy_notify_event_handler(globalconf.evenths, event_handle_destroynotify, NULL);
450 set_enter_notify_event_handler(globalconf.evenths, event_handle_enternotify, NULL);
451 set_expose_event_handler(globalconf.evenths, event_handle_expose, NULL);
452 set_key_press_event_handler(globalconf.evenths, event_handle_keypress, NULL);
453 set_mapping_notify_event_handler(globalconf.evenths, event_handle_mappingnotify, NULL);
454 set_map_request_event_handler(globalconf.evenths, event_handle_maprequest, NULL);
455 set_property_notify_event_handler(globalconf.evenths, event_handle_propertynotify, NULL);
456 set_unmap_notify_event_handler(globalconf.evenths, event_handle_unmapnotify, NULL);
457 set_client_message_event_handler(globalconf.evenths, event_handle_clientmessage, NULL);
459 /* check for shape extension */
460 shape_query = xcb_get_extension_data(globalconf.connection, &xcb_shape_id);
461 if((globalconf.have_shape = shape_query->present))
462 xcb_set_event_handler(globalconf.evenths,
463 (shape_query->first_event + XCB_SHAPE_NOTIFY),
464 (xcb_generic_event_handler_t) event_handle_shape,
465 NULL);
467 /* check for randr extension */
468 randr_query = xcb_get_extension_data(globalconf.connection, &xcb_randr_id);
469 if((globalconf.have_randr = randr_query->present))
470 xcb_set_event_handler(globalconf.evenths,
471 (randr_query->first_event + XCB_RANDR_SCREEN_CHANGE_NOTIFY),
472 (xcb_generic_event_handler_t) event_handle_randr_screen_change_notify,
473 NULL);
475 xcb_aux_sync(globalconf.connection);
477 /* get socket fd */
478 csfd = socket_getclient();
479 addr = socket_getaddr(getenv("DISPLAY"));
481 if(bind(csfd, (const struct sockaddr *) addr, SUN_LEN(addr)))
483 if(errno == EADDRINUSE)
485 if(unlink(addr->sun_path))
486 warn("error unlinking existing file: %s\n", strerror(errno));
487 if(bind(csfd, (const struct sockaddr *) addr, SUN_LEN(addr)))
488 warn("error binding UNIX domain socket: %s\n", strerror(errno));
490 else
491 warn("error binding UNIX domain socket: %s\n", strerror(errno));
494 if(!a_dbus_init(&dbusfd))
495 dbusfd = -1;
497 /* register function for signals */
498 signal(SIGINT, &exit_on_signal);
499 signal(SIGTERM, &exit_on_signal);
500 signal(SIGHUP, &exit_on_signal);
502 /* refresh everything before waiting events */
503 statusbar_refresh();
504 layout_refresh();
506 /* main event loop, also reads status text from socket */
507 while(running)
509 FD_ZERO(&rd);
510 if(csfd >= 0)
511 FD_SET(csfd, &rd);
512 if(dbusfd >= 0)
513 FD_SET(dbusfd, &rd);
514 FD_SET(xfd, &rd);
515 if(select(MAX(MAX(xfd, csfd), dbusfd) + 1, &rd, NULL, NULL, NULL) == -1)
517 if(errno == EINTR)
518 continue;
519 eprint("select failed\n");
521 if(csfd >= 0 && FD_ISSET(csfd, &rd))
522 switch (r = recv(csfd, buf, sizeof(buf)-1, MSG_TRUNC))
524 case -1:
525 warn("error reading UNIX domain socket: %s\n", strerror(errno));
526 csfd = -1;
527 break;
528 case 0:
529 break;
530 default:
531 if(r >= ssizeof(buf))
532 break;
533 buf[r] = '\0';
534 __uicb_parsecmd(buf);
535 statusbar_refresh();
536 layout_refresh();
539 if(dbusfd >= 0 && FD_ISSET(dbusfd, &rd))
540 a_dbus_process_requests(&dbusfd);
542 /* two level XPending:
543 * we need to first check we have XEvent to handle
544 * and if so, we handle them all in a round.
545 * Then when we have refresh()'ed stuff so maybe new XEvent
546 * are available and select() won't tell us, so let's check
547 * with XPending() again.
549 while((ev = xcb_poll_for_event(globalconf.connection)))
553 xcb_handle_event(globalconf.evenths, ev);
555 /* need to resync */
556 xcb_aux_sync(globalconf.connection);
558 p_delete(&ev);
559 } while((ev = xcb_poll_for_event(globalconf.connection)));
561 statusbar_refresh();
562 layout_refresh();
564 /* need to resync */
565 xcb_aux_sync(globalconf.connection);
567 xcb_aux_sync(globalconf.connection);
570 a_dbus_cleanup();
572 if(csfd > 0 && close(csfd))
573 warn("error closing UNIX domain socket: %s\n", strerror(errno));
574 if(unlink(addr->sun_path))
575 warn("error unlinking UNIX domain socket: %s\n", strerror(errno));
576 p_delete(&addr);
578 /* remap all clients since some WM won't handle them otherwise */
579 for(c = globalconf.clients; c; c = c->next)
580 client_unban(c);
582 xcb_aux_sync(globalconf.connection);
584 xcb_disconnect(globalconf.connection);
586 return EXIT_SUCCESS;
589 // vim: filetype=c:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=80