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>
16 #include <sys/resource.h>
19 #include "sd-daemon.h"
21 /* The original value of RLIMIT_CORE when i3 was started. We need to restore
22 * this before starting any other process, since we set RLIMIT_CORE to
23 * RLIM_INFINITY for i3 debugging versions. */
24 struct rlimit original_rlimit_core;
26 static int xkb_event_base;
28 int xkb_current_group;
34 xcb_connection_t *conn;
35 /* The screen (0 when you are using DISPLAY=:0) of the connection 'conn' */
38 /* Display handle for libstartup-notification */
41 /* The last timestamp we got from X11 (timestamps are included in some events
42 * and are used for some things, like determining a unique ID in startup
44 xcb_timestamp_t last_timestamp = XCB_CURRENT_TIME;
46 xcb_screen_t *root_screen;
50 struct ev_loop *main_loop;
52 xcb_key_symbols_t *keysyms;
54 /* Those are our connections to X11 for use with libXcursor and XKB */
55 Display *xlibdpy, *xkbdpy;
57 /* The list of key bindings */
58 struct bindings_head *bindings;
60 /* The list of exec-lines */
61 struct autostarts_head autostarts = TAILQ_HEAD_INITIALIZER(autostarts);
63 /* The list of exec_always lines */
64 struct autostarts_always_head autostarts_always = TAILQ_HEAD_INITIALIZER(autostarts_always);
66 /* The list of assignments */
67 struct assignments_head assignments = TAILQ_HEAD_INITIALIZER(assignments);
69 /* The list of workspace assignments (which workspace should end up on which
71 struct ws_assignments_head ws_assignments = TAILQ_HEAD_INITIALIZER(ws_assignments);
73 /* We hope that those are supported and set them to true */
74 bool xcursor_supported = true;
75 bool xkb_supported = true;
77 /* This will be set to true when -C is used so that functions can behave
78 * slightly differently. We don’t want i3-nagbar to be started when validating
79 * the config, for example. */
80 bool only_check_config = false;
83 * This callback is only a dummy, see xcb_prepare_cb and xcb_check_cb.
84 * See also man libev(3): "ev_prepare" and "ev_check" - customise your event loop
87 static void xcb_got_event(EV_P_ struct ev_io *w, int revents) {
88 /* empty, because xcb_prepare_cb and xcb_check_cb are used */
92 * Flush before blocking (and waiting for new events)
95 static void xcb_prepare_cb(EV_P_ ev_prepare *w, int revents) {
100 * Instead of polling the X connection socket we leave this to
101 * xcb_poll_for_event() which knows better than we can ever know.
104 static void xcb_check_cb(EV_P_ ev_check *w, int revents) {
105 xcb_generic_event_t *event;
107 while ((event = xcb_poll_for_event(conn)) != NULL) {
108 if (event->response_type == 0) {
109 if (event_is_ignored(event->sequence, 0))
110 DLOG("Expected X11 Error received for sequence %x\n", event->sequence);
112 xcb_generic_error_t *error = (xcb_generic_error_t*)event;
113 ELOG("X11 Error received! sequence 0x%x, error_code = %d\n",
114 error->sequence, error->error_code);
120 /* Strip off the highest bit (set if the event is generated) */
121 int type = (event->response_type & 0x7F);
123 handle_event(type, event);
131 * When using xmodmap to change the keyboard mapping, this event
132 * is only sent via XKB. Therefore, we need this special handler.
135 static void xkb_got_event(EV_P_ struct ev_io *w, int revents) {
136 DLOG("Handling XKB event\n");
139 /* When using xmodmap, every change (!) gets an own event.
140 * Therefore, we just read all events and only handle the
141 * mapping_notify once. */
142 bool mapping_changed = false;
143 while (XPending(xkbdpy)) {
144 XNextEvent(xkbdpy, (XEvent*)&ev);
145 /* While we should never receive a non-XKB event,
146 * better do sanity checking */
147 if (ev.type != xkb_event_base)
150 if (ev.any.xkb_type == XkbMapNotify) {
151 mapping_changed = true;
155 if (ev.any.xkb_type != XkbStateNotify) {
156 ELOG("Unknown XKB event received (type %d)\n", ev.any.xkb_type);
160 /* See The XKB Extension: Library Specification, section 14.1 */
161 /* We check if the current group (each group contains
162 * two levels) has been changed. Mode_switch activates
163 * group XkbGroup2Index */
164 if (xkb_current_group == ev.state.group)
167 xkb_current_group = ev.state.group;
169 if (ev.state.group == XkbGroup2Index) {
170 DLOG("Mode_switch enabled\n");
171 grab_all_keys(conn, true);
174 if (ev.state.group == XkbGroup1Index) {
175 DLOG("Mode_switch disabled\n");
176 ungrab_all_keys(conn);
177 grab_all_keys(conn, false);
181 if (!mapping_changed)
184 DLOG("Keyboard mapping changed, updating keybindings\n");
185 xcb_key_symbols_free(keysyms);
186 keysyms = xcb_key_symbols_alloc(conn);
188 xcb_numlock_mask = aio_get_mod_mask_for(XCB_NUM_LOCK, keysyms);
190 ungrab_all_keys(conn);
191 DLOG("Re-grabbing...\n");
193 grab_all_keys(conn, (xkb_current_group == XkbGroup2Index));
198 * Exit handler which destroys the main_loop. Will trigger cleanup handlers.
201 static void i3_exit() {
202 /* We need ev >= 4 for the following code. Since it is not *that* important (it
203 * only makes sure that there are no i3-nagbar instances left behind) we still
204 * support old systems with libev 3. */
205 #if EV_VERSION_MAJOR >= 4
206 ev_loop_destroy(main_loop);
210 int main(int argc, char *argv[]) {
211 char *override_configpath = NULL;
212 bool autostart = true;
213 char *layout_path = NULL;
214 bool delete_layout_path = false;
215 bool force_xinerama = false;
216 bool disable_signalhandler = false;
217 static struct option long_options[] = {
218 {"no-autostart", no_argument, 0, 'a'},
219 {"config", required_argument, 0, 'c'},
220 {"version", no_argument, 0, 'v'},
221 {"help", no_argument, 0, 'h'},
222 {"layout", required_argument, 0, 'L'},
223 {"restart", required_argument, 0, 0},
224 {"force-xinerama", no_argument, 0, 0},
225 {"force_xinerama", no_argument, 0, 0},
226 {"disable-signalhandler", no_argument, 0, 0},
227 {"get-socketpath", no_argument, 0, 0},
228 {"get_socketpath", no_argument, 0, 0},
231 int option_index = 0, opt;
233 setlocale(LC_ALL, "");
235 /* Get the RLIMIT_CORE limit at startup time to restore this before
236 * starting processes. */
237 getrlimit(RLIMIT_CORE, &original_rlimit_core);
239 /* Disable output buffering to make redirects in .xsession actually useful for debugging */
240 if (!isatty(fileno(stdout)))
241 setbuf(stdout, NULL);
249 while ((opt = getopt_long(argc, argv, "c:CvaL:hld:V", long_options, &option_index)) != -1) {
252 LOG("Autostart disabled using -a\n");
257 layout_path = sstrdup(optarg);
258 delete_layout_path = false;
261 FREE(override_configpath);
262 override_configpath = sstrdup(optarg);
265 LOG("Checking configuration file only (-C)\n");
266 only_check_config = true;
269 printf("i3 version " I3_VERSION " © 2009-2011 Michael Stapelberg and contributors\n");
275 LOG("Enabling debug loglevel %s\n", optarg);
276 add_loglevel(optarg);
279 /* DEPRECATED, ignored for the next 3 versions (3.e, 3.f, 3.g) */
282 if (strcmp(long_options[option_index].name, "force-xinerama") == 0 ||
283 strcmp(long_options[option_index].name, "force_xinerama") == 0) {
284 force_xinerama = true;
285 ELOG("Using Xinerama instead of RandR. This option should be "
286 "avoided at all cost because it does not refresh the list "
287 "of screens, so you cannot configure displays at runtime. "
288 "Please check if your driver really does not support RandR "
289 "and disable this option as soon as you can.\n");
291 } else if (strcmp(long_options[option_index].name, "disable-signalhandler") == 0) {
292 disable_signalhandler = true;
294 } else if (strcmp(long_options[option_index].name, "get-socketpath") == 0 ||
295 strcmp(long_options[option_index].name, "get_socketpath") == 0) {
296 char *socket_path = socket_path_from_x11();
298 printf("%s\n", socket_path);
303 } else if (strcmp(long_options[option_index].name, "restart") == 0) {
305 layout_path = sstrdup(optarg);
306 delete_layout_path = true;
311 fprintf(stderr, "Usage: %s [-c configfile] [-d loglevel] [-a] [-v] [-V] [-C]\n", argv[0]);
312 fprintf(stderr, "\n");
313 fprintf(stderr, "\t-a disable autostart ('exec' lines in config)\n");
314 fprintf(stderr, "\t-c <file> use the provided configfile instead\n");
315 fprintf(stderr, "\t-C validate configuration file and exit\n");
316 fprintf(stderr, "\t-d <level> enable debug output with the specified loglevel\n");
317 fprintf(stderr, "\t-L <file> path to the serialized layout during restarts\n");
318 fprintf(stderr, "\t-v display version and exit\n");
319 fprintf(stderr, "\t-V enable verbose mode\n");
320 fprintf(stderr, "\n");
321 fprintf(stderr, "\t--force-xinerama\n"
322 "\tUse Xinerama instead of RandR.\n"
323 "\tThis option should only be used if you are stuck with the\n"
324 "\tnvidia closed source driver which does not support RandR.\n");
325 fprintf(stderr, "\n");
326 fprintf(stderr, "\t--get-socketpath\n"
327 "\tRetrieve the i3 IPC socket path from X11, print it, then exit.\n");
328 fprintf(stderr, "\n");
329 fprintf(stderr, "If you pass plain text arguments, i3 will interpret them as a command\n"
330 "to send to a currently running i3 (like i3-msg). This allows you to\n"
331 "use nice and logical commands, such as:\n"
334 "\ti3 floating toggle\n"
341 /* If the user passes more arguments, we act like i3-msg would: Just send
342 * the arguments as an IPC message to i3. This allows for nice semantic
343 * commands such as 'i3 border none'. */
345 /* We enable verbose mode so that the user knows what’s going on.
346 * This should make it easier to find mistakes when the user passes
347 * arguments by mistake. */
350 LOG("Additional arguments passed. Sending them as a command to i3.\n");
351 char *payload = NULL;
352 while (optind < argc) {
354 payload = sstrdup(argv[optind]);
357 sasprintf(&both, "%s %s", payload, argv[optind]);
363 LOG("Command is: %s (%d bytes)\n", payload, strlen(payload));
364 char *socket_path = socket_path_from_x11();
366 ELOG("Could not get i3 IPC socket path\n");
370 int sockfd = socket(AF_LOCAL, SOCK_STREAM, 0);
372 err(EXIT_FAILURE, "Could not create socket");
374 struct sockaddr_un addr;
375 memset(&addr, 0, sizeof(struct sockaddr_un));
376 addr.sun_family = AF_LOCAL;
377 strncpy(addr.sun_path, socket_path, sizeof(addr.sun_path) - 1);
378 if (connect(sockfd, (const struct sockaddr*)&addr, sizeof(struct sockaddr_un)) < 0)
379 err(EXIT_FAILURE, "Could not connect to i3");
381 if (ipc_send_message(sockfd, strlen(payload), I3_IPC_MESSAGE_TYPE_COMMAND,
382 (uint8_t*)payload) == -1)
383 err(EXIT_FAILURE, "IPC: write()");
385 uint32_t reply_length;
388 if ((ret = ipc_recv_message(sockfd, I3_IPC_MESSAGE_TYPE_COMMAND,
389 &reply_length, &reply)) != 0) {
391 err(EXIT_FAILURE, "IPC: read()");
394 printf("%.*s\n", reply_length, reply);
398 /* I3_VERSION contains either something like this:
399 * "4.0.2 (2011-11-11, branch "release")".
400 * or: "4.0.2-123-gCOFFEEBABE (2011-11-11, branch "next")".
402 * So we check for the offset of the first opening round bracket to
403 * determine whether this is a git version or a release version. */
404 if ((strchr(I3_VERSION, '(') - I3_VERSION) > 10) {
405 struct rlimit limit = { RLIM_INFINITY, RLIM_INFINITY };
406 setrlimit(RLIMIT_CORE, &limit);
408 /* The following code is helpful, but not required. We thus don’t pay
409 * much attention to error handling, non-linux or other edge cases. */
411 LOG("CORE DUMPS: You are running a development version of i3, so coredumps were automatically enabled (ulimit -c unlimited).\n");
412 if (getcwd(cwd, sizeof(cwd)) != NULL)
413 LOG("CORE DUMPS: Your current working directory is \"%s\".\n", cwd);
415 if ((patternfd = open("/proc/sys/kernel/core_pattern", O_RDONLY)) >= 0) {
416 memset(cwd, '\0', sizeof(cwd));
417 if (read(patternfd, cwd, sizeof(cwd)) > 0)
418 /* a trailing newline is included in cwd */
419 LOG("CORE DUMPS: Your core_pattern is: %s", cwd);
424 LOG("i3 (tree) version " I3_VERSION " starting\n");
426 conn = xcb_connect(NULL, &conn_screen);
427 if (xcb_connection_has_error(conn))
428 errx(EXIT_FAILURE, "Cannot open display\n");
430 sndisplay = sn_xcb_display_new(conn, NULL, NULL);
432 /* Initialize the libev event loop. This needs to be done before loading
433 * the config file because the parser will install an ev_child watcher
434 * for the nagbar when config errors are found. */
435 main_loop = EV_DEFAULT;
436 if (main_loop == NULL)
437 die("Could not initialize libev. Bad LIBEV_FLAGS?\n");
439 root_screen = xcb_aux_get_screen(conn, conn_screen);
440 root = root_screen->root;
441 root_depth = root_screen->root_depth;
442 xcb_get_geometry_cookie_t gcookie = xcb_get_geometry(conn, root);
443 xcb_query_pointer_cookie_t pointercookie = xcb_query_pointer(conn, root);
445 load_configuration(conn, override_configpath, false);
446 if (only_check_config) {
447 LOG("Done checking configuration file. Exiting.\n");
451 if (config.ipc_socket_path == NULL) {
452 /* Fall back to a file name in /tmp/ based on the PID */
453 if ((config.ipc_socket_path = getenv("I3SOCK")) == NULL)
454 config.ipc_socket_path = get_process_filename("ipc-socket");
456 config.ipc_socket_path = sstrdup(config.ipc_socket_path);
459 uint32_t mask = XCB_CW_EVENT_MASK;
460 uint32_t values[] = { XCB_EVENT_MASK_SUBSTRUCTURE_REDIRECT |
461 XCB_EVENT_MASK_STRUCTURE_NOTIFY | /* when the user adds a screen (e.g. video
462 projector), the root window gets a
464 XCB_EVENT_MASK_POINTER_MOTION |
465 XCB_EVENT_MASK_PROPERTY_CHANGE |
466 XCB_EVENT_MASK_ENTER_WINDOW };
467 xcb_void_cookie_t cookie;
468 cookie = xcb_change_window_attributes_checked(conn, root, mask, values);
469 check_error(conn, cookie, "Another window manager seems to be running");
471 xcb_get_geometry_reply_t *greply = xcb_get_geometry_reply(conn, gcookie, NULL);
472 if (greply == NULL) {
473 ELOG("Could not get geometry of the root window, exiting\n");
476 DLOG("root geometry reply: (%d, %d) %d x %d\n", greply->x, greply->y, greply->width, greply->height);
478 /* Place requests for the atoms we need as soon as possible */
479 #define xmacro(atom) \
480 xcb_intern_atom_cookie_t atom ## _cookie = xcb_intern_atom(conn, 0, strlen(#atom), #atom);
481 #include "atoms.xmacro"
484 /* Initialize the Xlib connection */
485 xlibdpy = xkbdpy = XOpenDisplay(NULL);
487 /* Try to load the X cursors and initialize the XKB extension */
488 if (xlibdpy == NULL) {
489 ELOG("ERROR: XOpenDisplay() failed, disabling libXcursor/XKB support\n");
490 xcursor_supported = false;
491 xkb_supported = false;
492 } else if (fcntl(ConnectionNumber(xlibdpy), F_SETFD, FD_CLOEXEC) == -1) {
493 ELOG("Could not set FD_CLOEXEC on xkbdpy\n");
496 xcursor_load_cursors();
500 /* Set a cursor for the root window (otherwise the root window will show no
501 cursor until the first client is launched). */
502 if (xcursor_supported)
503 xcursor_set_root_cursor(XCURSOR_CURSOR_POINTER);
504 else xcb_set_root_cursor(XCURSOR_CURSOR_POINTER);
508 major = XkbMajorVersion,
509 minor = XkbMinorVersion;
511 if (fcntl(ConnectionNumber(xkbdpy), F_SETFD, FD_CLOEXEC) == -1) {
512 fprintf(stderr, "Could not set FD_CLOEXEC on xkbdpy\n");
517 if (!XkbQueryExtension(xkbdpy,&i1,&xkb_event_base,&errBase,&major,&minor)) {
518 fprintf(stderr, "XKB not supported by X-server\n");
521 /* end of ugliness */
523 if (!XkbSelectEvents(xkbdpy, XkbUseCoreKbd,
524 XkbMapNotifyMask | XkbStateNotifyMask,
525 XkbMapNotifyMask | XkbStateNotifyMask)) {
526 fprintf(stderr, "Could not set XKB event mask\n");
531 /* Setup NetWM atoms */
532 #define xmacro(name) \
534 xcb_intern_atom_reply_t *reply = xcb_intern_atom_reply(conn, name ## _cookie, NULL); \
536 ELOG("Could not get atom " #name "\n"); \
539 A_ ## name = reply->atom; \
542 #include "atoms.xmacro"
545 property_handlers_init();
547 /* Set up the atoms we support */
548 xcb_atom_t supported_atoms[] = {
549 #define xmacro(atom) A_ ## atom,
550 #include "atoms.xmacro"
553 xcb_change_property(conn, XCB_PROP_MODE_REPLACE, root, A__NET_SUPPORTED, XCB_ATOM_ATOM, 32, 16, supported_atoms);
554 /* Set up the window manager’s name */
555 xcb_change_property(conn, XCB_PROP_MODE_REPLACE, root, A__NET_SUPPORTING_WM_CHECK, XCB_ATOM_WINDOW, 32, 1, &root);
556 xcb_change_property(conn, XCB_PROP_MODE_REPLACE, root, A__NET_WM_NAME, A_UTF8_STRING, 8, strlen("i3"), "i3");
558 keysyms = xcb_key_symbols_alloc(conn);
560 xcb_numlock_mask = aio_get_mod_mask_for(XCB_NUM_LOCK, keysyms);
563 grab_all_keys(conn, false);
565 bool needs_tree_init = true;
567 LOG("Trying to restore the layout from %s...", layout_path);
568 needs_tree_init = !tree_restore(layout_path, greply);
569 if (delete_layout_path)
578 /* Force Xinerama (for drivers which don't support RandR yet, esp. the
579 * nVidia binary graphics driver), when specified either in the config
580 * file or on command-line */
581 if (force_xinerama || config.force_xinerama) {
584 DLOG("Checking for XRandR...\n");
585 randr_init(&randr_base);
588 xcb_query_pointer_reply_t *pointerreply;
589 Output *output = NULL;
590 if (!(pointerreply = xcb_query_pointer_reply(conn, pointercookie, NULL))) {
591 ELOG("Could not query pointer position, using first screen\n");
592 output = get_first_output();
594 DLOG("Pointer at %d, %d\n", pointerreply->root_x, pointerreply->root_y);
595 output = get_output_containing(pointerreply->root_x, pointerreply->root_y);
597 ELOG("ERROR: No screen at (%d, %d), starting on the first screen\n",
598 pointerreply->root_x, pointerreply->root_y);
599 output = get_first_output();
602 con_focus(con_descend_focused(output_get_content(output->con)));
607 /* Create the UNIX domain socket for IPC */
608 int ipc_socket = ipc_create_socket(config.ipc_socket_path);
609 if (ipc_socket == -1) {
610 ELOG("Could not create the IPC socket, IPC disabled\n");
612 free(config.ipc_socket_path);
613 struct ev_io *ipc_io = scalloc(sizeof(struct ev_io));
614 ev_io_init(ipc_io, ipc_new_client, ipc_socket, EV_READ);
615 ev_io_start(main_loop, ipc_io);
618 /* Also handle the UNIX domain sockets passed via socket activation. The
619 * parameter 1 means "remove the environment variables", we don’t want to
620 * pass these to child processes. */
621 int fds = sd_listen_fds(1);
623 ELOG("socket activation: Error in sd_listen_fds\n");
625 DLOG("socket activation: no sockets passed\n");
627 for (int fd = SD_LISTEN_FDS_START; fd < (SD_LISTEN_FDS_START + fds); fd++) {
628 DLOG("socket activation: also listening on fd %d\n", fd);
629 struct ev_io *ipc_io = scalloc(sizeof(struct ev_io));
630 ev_io_init(ipc_io, ipc_new_client, fd, EV_READ);
631 ev_io_start(main_loop, ipc_io);
635 /* Set up i3 specific atoms like I3_SOCKET_PATH and I3_CONFIG_PATH */
638 struct ev_io *xcb_watcher = scalloc(sizeof(struct ev_io));
639 struct ev_io *xkb = scalloc(sizeof(struct ev_io));
640 struct ev_check *xcb_check = scalloc(sizeof(struct ev_check));
641 struct ev_prepare *xcb_prepare = scalloc(sizeof(struct ev_prepare));
643 ev_io_init(xcb_watcher, xcb_got_event, xcb_get_file_descriptor(conn), EV_READ);
644 ev_io_start(main_loop, xcb_watcher);
648 ev_io_init(xkb, xkb_got_event, ConnectionNumber(xkbdpy), EV_READ);
649 ev_io_start(main_loop, xkb);
651 /* Flush the buffer so that libev can properly get new events */
655 ev_check_init(xcb_check, xcb_check_cb);
656 ev_check_start(main_loop, xcb_check);
658 ev_prepare_init(xcb_prepare, xcb_prepare_cb);
659 ev_prepare_start(main_loop, xcb_prepare);
663 manage_existing_windows(root);
665 if (!disable_signalhandler)
666 setup_signal_handler();
668 /* Ignore SIGPIPE to survive errors when an IPC client disconnects
669 * while we are sending him a message */
670 signal(SIGPIPE, SIG_IGN);
672 /* Autostarting exec-lines */
674 struct Autostart *exec;
675 TAILQ_FOREACH(exec, &autostarts, autostarts) {
676 LOG("auto-starting %s\n", exec->command);
677 start_application(exec->command, exec->no_startup_id);
681 /* Autostarting exec_always-lines */
682 struct Autostart *exec_always;
683 TAILQ_FOREACH(exec_always, &autostarts_always, autostarts_always) {
684 LOG("auto-starting (always!) %s\n", exec_always->command);
685 start_application(exec_always->command, exec_always->no_startup_id);
688 /* Start i3bar processes for all configured bars */
689 Barconfig *barconfig;
690 TAILQ_FOREACH(barconfig, &barconfigs, configs) {
691 char *command = NULL;
692 sasprintf(&command, "i3bar --bar_id=%s --socket=\"%s\"",
693 barconfig->id, current_socketpath);
694 LOG("Starting bar process: %s\n", command);
695 start_application(command, true);
699 /* Make sure to destroy the event loop to invoke the cleeanup callbacks
700 * when calling exit() */
703 ev_loop(main_loop, 0);