2 * vim:ts=4:sw=4:expandtab
4 * i3 - an improved dynamic tiling window manager
5 * © 2009-2011 Michael Stapelberg and contributors (see also: LICENSE)
7 * main.c: Initialization, main loop
12 #include <sys/types.h>
13 #include <sys/socket.h>
17 #include "sd-daemon.h"
19 static int xkb_event_base;
21 int xkb_current_group;
27 xcb_connection_t *conn;
28 /* The screen (0 when you are using DISPLAY=:0) of the connection 'conn' */
31 /* Display handle for libstartup-notification */
34 /* The last timestamp we got from X11 (timestamps are included in some events
35 * and are used for some things, like determining a unique ID in startup
37 xcb_timestamp_t last_timestamp = XCB_CURRENT_TIME;
39 xcb_screen_t *root_screen;
43 struct ev_loop *main_loop;
45 xcb_key_symbols_t *keysyms;
47 /* Those are our connections to X11 for use with libXcursor and XKB */
48 Display *xlibdpy, *xkbdpy;
50 /* The list of key bindings */
51 struct bindings_head *bindings;
53 /* The list of exec-lines */
54 struct autostarts_head autostarts = TAILQ_HEAD_INITIALIZER(autostarts);
56 /* The list of exec_always lines */
57 struct autostarts_always_head autostarts_always = TAILQ_HEAD_INITIALIZER(autostarts_always);
59 /* The list of assignments */
60 struct assignments_head assignments = TAILQ_HEAD_INITIALIZER(assignments);
62 /* The list of workspace assignments (which workspace should end up on which
64 struct ws_assignments_head ws_assignments = TAILQ_HEAD_INITIALIZER(ws_assignments);
66 /* We hope that those are supported and set them to true */
67 bool xcursor_supported = true;
68 bool xkb_supported = true;
70 /* This will be set to true when -C is used so that functions can behave
71 * slightly differently. We don’t want i3-nagbar to be started when validating
72 * the config, for example. */
73 bool only_check_config = false;
76 * This callback is only a dummy, see xcb_prepare_cb and xcb_check_cb.
77 * See also man libev(3): "ev_prepare" and "ev_check" - customise your event loop
80 static void xcb_got_event(EV_P_ struct ev_io *w, int revents) {
81 /* empty, because xcb_prepare_cb and xcb_check_cb are used */
85 * Flush before blocking (and waiting for new events)
88 static void xcb_prepare_cb(EV_P_ ev_prepare *w, int revents) {
93 * Instead of polling the X connection socket we leave this to
94 * xcb_poll_for_event() which knows better than we can ever know.
97 static void xcb_check_cb(EV_P_ ev_check *w, int revents) {
98 xcb_generic_event_t *event;
100 while ((event = xcb_poll_for_event(conn)) != NULL) {
101 if (event->response_type == 0) {
102 if (event_is_ignored(event->sequence, 0))
103 DLOG("Expected X11 Error received for sequence %x\n", event->sequence);
105 xcb_generic_error_t *error = (xcb_generic_error_t*)event;
106 ELOG("X11 Error received! sequence 0x%x, error_code = %d\n",
107 error->sequence, error->error_code);
113 /* Strip off the highest bit (set if the event is generated) */
114 int type = (event->response_type & 0x7F);
116 handle_event(type, event);
124 * When using xmodmap to change the keyboard mapping, this event
125 * is only sent via XKB. Therefore, we need this special handler.
128 static void xkb_got_event(EV_P_ struct ev_io *w, int revents) {
129 DLOG("Handling XKB event\n");
132 /* When using xmodmap, every change (!) gets an own event.
133 * Therefore, we just read all events and only handle the
134 * mapping_notify once. */
135 bool mapping_changed = false;
136 while (XPending(xkbdpy)) {
137 XNextEvent(xkbdpy, (XEvent*)&ev);
138 /* While we should never receive a non-XKB event,
139 * better do sanity checking */
140 if (ev.type != xkb_event_base)
143 if (ev.any.xkb_type == XkbMapNotify) {
144 mapping_changed = true;
148 if (ev.any.xkb_type != XkbStateNotify) {
149 ELOG("Unknown XKB event received (type %d)\n", ev.any.xkb_type);
153 /* See The XKB Extension: Library Specification, section 14.1 */
154 /* We check if the current group (each group contains
155 * two levels) has been changed. Mode_switch activates
156 * group XkbGroup2Index */
157 if (xkb_current_group == ev.state.group)
160 xkb_current_group = ev.state.group;
162 if (ev.state.group == XkbGroup2Index) {
163 DLOG("Mode_switch enabled\n");
164 grab_all_keys(conn, true);
167 if (ev.state.group == XkbGroup1Index) {
168 DLOG("Mode_switch disabled\n");
169 ungrab_all_keys(conn);
170 grab_all_keys(conn, false);
174 if (!mapping_changed)
177 DLOG("Keyboard mapping changed, updating keybindings\n");
178 xcb_key_symbols_free(keysyms);
179 keysyms = xcb_key_symbols_alloc(conn);
181 xcb_get_numlock_mask(conn);
183 ungrab_all_keys(conn);
184 DLOG("Re-grabbing...\n");
186 grab_all_keys(conn, (xkb_current_group == XkbGroup2Index));
191 * Exit handler which destroys the main_loop. Will trigger cleanup handlers.
194 static void i3_exit() {
195 /* We need ev >= 4 for the following code. Since it is not *that* important (it
196 * only makes sure that there are no i3-nagbar instances left behind) we still
197 * support old systems with libev 3. */
198 #if EV_VERSION_MAJOR >= 4
199 ev_loop_destroy(main_loop);
203 int main(int argc, char *argv[]) {
204 char *override_configpath = NULL;
205 bool autostart = true;
206 char *layout_path = NULL;
207 bool delete_layout_path = false;
208 bool force_xinerama = false;
209 bool disable_signalhandler = false;
210 static struct option long_options[] = {
211 {"no-autostart", no_argument, 0, 'a'},
212 {"config", required_argument, 0, 'c'},
213 {"version", no_argument, 0, 'v'},
214 {"help", no_argument, 0, 'h'},
215 {"layout", required_argument, 0, 'L'},
216 {"restart", required_argument, 0, 0},
217 {"force-xinerama", no_argument, 0, 0},
218 {"disable-signalhandler", no_argument, 0, 0},
219 {"get-socketpath", no_argument, 0, 0},
222 int option_index = 0, opt;
224 setlocale(LC_ALL, "");
226 /* Disable output buffering to make redirects in .xsession actually useful for debugging */
227 if (!isatty(fileno(stdout)))
228 setbuf(stdout, NULL);
236 while ((opt = getopt_long(argc, argv, "c:CvaL:hld:V", long_options, &option_index)) != -1) {
239 LOG("Autostart disabled using -a\n");
244 layout_path = sstrdup(optarg);
245 delete_layout_path = false;
248 FREE(override_configpath);
249 override_configpath = sstrdup(optarg);
252 LOG("Checking configuration file only (-C)\n");
253 only_check_config = true;
256 printf("i3 version " I3_VERSION " © 2009-2011 Michael Stapelberg and contributors\n");
262 LOG("Enabling debug loglevel %s\n", optarg);
263 add_loglevel(optarg);
266 /* DEPRECATED, ignored for the next 3 versions (3.e, 3.f, 3.g) */
269 if (strcmp(long_options[option_index].name, "force-xinerama") == 0) {
270 force_xinerama = true;
271 ELOG("Using Xinerama instead of RandR. This option should be "
272 "avoided at all cost because it does not refresh the list "
273 "of screens, so you cannot configure displays at runtime. "
274 "Please check if your driver really does not support RandR "
275 "and disable this option as soon as you can.\n");
277 } else if (strcmp(long_options[option_index].name, "disable-signalhandler") == 0) {
278 disable_signalhandler = true;
280 } else if (strcmp(long_options[option_index].name, "get-socketpath") == 0) {
281 char *socket_path = socket_path_from_x11();
283 printf("%s\n", socket_path);
288 } else if (strcmp(long_options[option_index].name, "restart") == 0) {
290 layout_path = sstrdup(optarg);
291 delete_layout_path = true;
296 fprintf(stderr, "Usage: %s [-c configfile] [-d loglevel] [-a] [-v] [-V] [-C]\n", argv[0]);
297 fprintf(stderr, "\n");
298 fprintf(stderr, "\t-a disable autostart ('exec' lines in config)\n");
299 fprintf(stderr, "\t-c <file> use the provided configfile instead\n");
300 fprintf(stderr, "\t-C validate configuration file and exit\n");
301 fprintf(stderr, "\t-d <level> enable debug output with the specified loglevel\n");
302 fprintf(stderr, "\t-L <file> path to the serialized layout during restarts\n");
303 fprintf(stderr, "\t-v display version and exit\n");
304 fprintf(stderr, "\t-V enable verbose mode\n");
305 fprintf(stderr, "\n");
306 fprintf(stderr, "\t--force-xinerama\n"
307 "\tUse Xinerama instead of RandR.\n"
308 "\tThis option should only be used if you are stuck with the\n"
309 "\tnvidia closed source driver which does not support RandR.\n");
310 fprintf(stderr, "\n");
311 fprintf(stderr, "\t--get-socketpath\n"
312 "\tRetrieve the i3 IPC socket path from X11, print it, then exit.\n");
313 fprintf(stderr, "\n");
314 fprintf(stderr, "If you pass plain text arguments, i3 will interpret them as a command\n"
315 "to send to a currently running i3 (like i3-msg). This allows you to\n"
316 "use nice and logical commands, such as:\n"
319 "\ti3 floating toggle\n"
326 /* If the user passes more arguments, we act like i3-msg would: Just send
327 * the arguments as an IPC message to i3. This allows for nice semantic
328 * commands such as 'i3 border none'. */
330 /* We enable verbose mode so that the user knows what’s going on.
331 * This should make it easier to find mistakes when the user passes
332 * arguments by mistake. */
335 LOG("Additional arguments passed. Sending them as a command to i3.\n");
336 char *payload = NULL;
337 while (optind < argc) {
339 payload = sstrdup(argv[optind]);
342 if (asprintf(&both, "%s %s", payload, argv[optind]) == -1)
343 err(EXIT_FAILURE, "asprintf");
349 LOG("Command is: %s (%d bytes)\n", payload, strlen(payload));
350 char *socket_path = socket_path_from_x11();
352 ELOG("Could not get i3 IPC socket path\n");
356 int sockfd = socket(AF_LOCAL, SOCK_STREAM, 0);
358 err(EXIT_FAILURE, "Could not create socket");
360 struct sockaddr_un addr;
361 memset(&addr, 0, sizeof(struct sockaddr_un));
362 addr.sun_family = AF_LOCAL;
363 strncpy(addr.sun_path, socket_path, sizeof(addr.sun_path) - 1);
364 if (connect(sockfd, (const struct sockaddr*)&addr, sizeof(struct sockaddr_un)) < 0)
365 err(EXIT_FAILURE, "Could not connect to i3");
367 if (ipc_send_message(sockfd, strlen(payload), I3_IPC_MESSAGE_TYPE_COMMAND,
368 (uint8_t*)payload) == -1)
369 err(EXIT_FAILURE, "IPC: write()");
371 uint32_t reply_length;
374 if ((ret = ipc_recv_message(sockfd, I3_IPC_MESSAGE_TYPE_COMMAND,
375 &reply_length, &reply)) != 0) {
377 err(EXIT_FAILURE, "IPC: read()");
380 printf("%.*s\n", reply_length, reply);
384 LOG("i3 (tree) version " I3_VERSION " starting\n");
386 conn = xcb_connect(NULL, &conn_screen);
387 if (xcb_connection_has_error(conn))
388 errx(EXIT_FAILURE, "Cannot open display\n");
390 sndisplay = sn_xcb_display_new(conn, NULL, NULL);
392 /* Initialize the libev event loop. This needs to be done before loading
393 * the config file because the parser will install an ev_child watcher
394 * for the nagbar when config errors are found. */
395 main_loop = EV_DEFAULT;
396 if (main_loop == NULL)
397 die("Could not initialize libev. Bad LIBEV_FLAGS?\n");
399 root_screen = xcb_aux_get_screen(conn, conn_screen);
400 root = root_screen->root;
401 root_depth = root_screen->root_depth;
402 xcb_get_geometry_cookie_t gcookie = xcb_get_geometry(conn, root);
403 xcb_query_pointer_cookie_t pointercookie = xcb_query_pointer(conn, root);
405 load_configuration(conn, override_configpath, false);
406 if (only_check_config) {
407 LOG("Done checking configuration file. Exiting.\n");
411 if (config.ipc_socket_path == NULL) {
412 /* Fall back to a file name in /tmp/ based on the PID */
413 if ((config.ipc_socket_path = getenv("I3SOCK")) == NULL)
414 config.ipc_socket_path = get_process_filename("ipc-socket");
416 config.ipc_socket_path = sstrdup(config.ipc_socket_path);
419 uint32_t mask = XCB_CW_EVENT_MASK;
420 uint32_t values[] = { XCB_EVENT_MASK_SUBSTRUCTURE_REDIRECT |
421 XCB_EVENT_MASK_STRUCTURE_NOTIFY | /* when the user adds a screen (e.g. video
422 projector), the root window gets a
424 XCB_EVENT_MASK_POINTER_MOTION |
425 XCB_EVENT_MASK_PROPERTY_CHANGE |
426 XCB_EVENT_MASK_ENTER_WINDOW };
427 xcb_void_cookie_t cookie;
428 cookie = xcb_change_window_attributes_checked(conn, root, mask, values);
429 check_error(conn, cookie, "Another window manager seems to be running");
431 xcb_get_geometry_reply_t *greply = xcb_get_geometry_reply(conn, gcookie, NULL);
432 if (greply == NULL) {
433 ELOG("Could not get geometry of the root window, exiting\n");
436 DLOG("root geometry reply: (%d, %d) %d x %d\n", greply->x, greply->y, greply->width, greply->height);
438 /* Place requests for the atoms we need as soon as possible */
439 #define xmacro(atom) \
440 xcb_intern_atom_cookie_t atom ## _cookie = xcb_intern_atom(conn, 0, strlen(#atom), #atom);
441 #include "atoms.xmacro"
444 /* Initialize the Xlib connection */
445 xlibdpy = xkbdpy = XOpenDisplay(NULL);
447 /* Try to load the X cursors and initialize the XKB extension */
448 if (xlibdpy == NULL) {
449 ELOG("ERROR: XOpenDisplay() failed, disabling libXcursor/XKB support\n");
450 xcursor_supported = false;
451 xkb_supported = false;
452 } else if (fcntl(ConnectionNumber(xlibdpy), F_SETFD, FD_CLOEXEC) == -1) {
453 ELOG("Could not set FD_CLOEXEC on xkbdpy\n");
456 xcursor_load_cursors();
460 /* Set a cursor for the root window (otherwise the root window will show no
461 cursor until the first client is launched). */
462 if (xcursor_supported)
463 xcursor_set_root_cursor(XCURSOR_CURSOR_POINTER);
464 else xcb_set_root_cursor(XCURSOR_CURSOR_POINTER);
468 major = XkbMajorVersion,
469 minor = XkbMinorVersion;
471 if (fcntl(ConnectionNumber(xkbdpy), F_SETFD, FD_CLOEXEC) == -1) {
472 fprintf(stderr, "Could not set FD_CLOEXEC on xkbdpy\n");
477 if (!XkbQueryExtension(xkbdpy,&i1,&xkb_event_base,&errBase,&major,&minor)) {
478 fprintf(stderr, "XKB not supported by X-server\n");
481 /* end of ugliness */
483 if (!XkbSelectEvents(xkbdpy, XkbUseCoreKbd,
484 XkbMapNotifyMask | XkbStateNotifyMask,
485 XkbMapNotifyMask | XkbStateNotifyMask)) {
486 fprintf(stderr, "Could not set XKB event mask\n");
491 /* Setup NetWM atoms */
492 #define xmacro(name) \
494 xcb_intern_atom_reply_t *reply = xcb_intern_atom_reply(conn, name ## _cookie, NULL); \
496 ELOG("Could not get atom " #name "\n"); \
499 A_ ## name = reply->atom; \
502 #include "atoms.xmacro"
505 property_handlers_init();
507 /* Set up the atoms we support */
508 xcb_atom_t supported_atoms[] = {
509 #define xmacro(atom) A_ ## atom,
510 #include "atoms.xmacro"
513 xcb_change_property(conn, XCB_PROP_MODE_REPLACE, root, A__NET_SUPPORTED, XCB_ATOM_ATOM, 32, 16, supported_atoms);
514 /* Set up the window manager’s name */
515 xcb_change_property(conn, XCB_PROP_MODE_REPLACE, root, A__NET_SUPPORTING_WM_CHECK, XCB_ATOM_WINDOW, 32, 1, &root);
516 xcb_change_property(conn, XCB_PROP_MODE_REPLACE, root, A__NET_WM_NAME, A_UTF8_STRING, 8, strlen("i3"), "i3");
518 keysyms = xcb_key_symbols_alloc(conn);
520 xcb_get_numlock_mask(conn);
523 grab_all_keys(conn, false);
525 bool needs_tree_init = true;
527 LOG("Trying to restore the layout from %s...", layout_path);
528 needs_tree_init = !tree_restore(layout_path, greply);
529 if (delete_layout_path)
538 /* Force Xinerama (for drivers which don't support RandR yet, esp. the
539 * nVidia binary graphics driver), when specified either in the config
540 * file or on command-line */
541 if (force_xinerama || config.force_xinerama) {
544 DLOG("Checking for XRandR...\n");
545 randr_init(&randr_base);
548 xcb_query_pointer_reply_t *pointerreply;
549 Output *output = NULL;
550 if (!(pointerreply = xcb_query_pointer_reply(conn, pointercookie, NULL))) {
551 ELOG("Could not query pointer position, using first screen\n");
552 output = get_first_output();
554 DLOG("Pointer at %d, %d\n", pointerreply->root_x, pointerreply->root_y);
555 output = get_output_containing(pointerreply->root_x, pointerreply->root_y);
557 ELOG("ERROR: No screen at (%d, %d), starting on the first screen\n",
558 pointerreply->root_x, pointerreply->root_y);
559 output = get_first_output();
562 con_focus(con_descend_focused(output_get_content(output->con)));
567 /* Create the UNIX domain socket for IPC */
568 int ipc_socket = ipc_create_socket(config.ipc_socket_path);
569 if (ipc_socket == -1) {
570 ELOG("Could not create the IPC socket, IPC disabled\n");
572 free(config.ipc_socket_path);
573 struct ev_io *ipc_io = scalloc(sizeof(struct ev_io));
574 ev_io_init(ipc_io, ipc_new_client, ipc_socket, EV_READ);
575 ev_io_start(main_loop, ipc_io);
578 /* Also handle the UNIX domain sockets passed via socket activation */
579 int fds = sd_listen_fds(1);
581 ELOG("socket activation: Error in sd_listen_fds\n");
583 DLOG("socket activation: no sockets passed\n");
585 for (int fd = SD_LISTEN_FDS_START; fd < (SD_LISTEN_FDS_START + fds); fd++) {
586 DLOG("socket activation: also listening on fd %d\n", fd);
587 struct ev_io *ipc_io = scalloc(sizeof(struct ev_io));
588 ev_io_init(ipc_io, ipc_new_client, fd, EV_READ);
589 ev_io_start(main_loop, ipc_io);
593 /* Set up i3 specific atoms like I3_SOCKET_PATH and I3_CONFIG_PATH */
596 struct ev_io *xcb_watcher = scalloc(sizeof(struct ev_io));
597 struct ev_io *xkb = scalloc(sizeof(struct ev_io));
598 struct ev_check *xcb_check = scalloc(sizeof(struct ev_check));
599 struct ev_prepare *xcb_prepare = scalloc(sizeof(struct ev_prepare));
601 ev_io_init(xcb_watcher, xcb_got_event, xcb_get_file_descriptor(conn), EV_READ);
602 ev_io_start(main_loop, xcb_watcher);
606 ev_io_init(xkb, xkb_got_event, ConnectionNumber(xkbdpy), EV_READ);
607 ev_io_start(main_loop, xkb);
609 /* Flush the buffer so that libev can properly get new events */
613 ev_check_init(xcb_check, xcb_check_cb);
614 ev_check_start(main_loop, xcb_check);
616 ev_prepare_init(xcb_prepare, xcb_prepare_cb);
617 ev_prepare_start(main_loop, xcb_prepare);
621 manage_existing_windows(root);
623 if (!disable_signalhandler)
624 setup_signal_handler();
626 /* Ignore SIGPIPE to survive errors when an IPC client disconnects
627 * while we are sending him a message */
628 signal(SIGPIPE, SIG_IGN);
630 /* Autostarting exec-lines */
632 struct Autostart *exec;
633 TAILQ_FOREACH(exec, &autostarts, autostarts) {
634 LOG("auto-starting %s\n", exec->command);
635 start_application(exec->command);
639 /* Autostarting exec_always-lines */
640 struct Autostart *exec_always;
641 TAILQ_FOREACH(exec_always, &autostarts_always, autostarts_always) {
642 LOG("auto-starting (always!) %s\n", exec_always->command);
643 start_application(exec_always->command);
646 /* Start i3bar processes for all configured bars */
647 Barconfig *barconfig;
648 TAILQ_FOREACH(barconfig, &barconfigs, configs) {
649 char *command = NULL;
650 asprintf(&command, "i3bar --bar_id=%s --socket=\"%s\"",
651 barconfig->id, current_socketpath);
652 LOG("Starting bar process: %s\n", command);
653 start_application(command);
657 /* Make sure to destroy the event loop to invoke the cleeanup callbacks
658 * when calling exit() */
661 ev_loop(main_loop, 0);