2 #define I3__FILE__ "main.c"
4 * vim:ts=4:sw=4:expandtab
6 * i3 - an improved dynamic tiling window manager
7 * © 2009-2013 Michael Stapelberg and contributors (see also: LICENSE)
9 * main.c: Initialization, main loop
14 #include <sys/types.h>
15 #include <sys/socket.h>
18 #include <sys/resource.h>
24 #include "sd-daemon.h"
26 /* The original value of RLIMIT_CORE when i3 was started. We need to restore
27 * this before starting any other process, since we set RLIMIT_CORE to
28 * RLIM_INFINITY for i3 debugging versions. */
29 struct rlimit original_rlimit_core;
31 /** The number of file descriptors passed via socket activation. */
34 static int xkb_event_base;
36 int xkb_current_group;
42 xcb_connection_t *conn;
43 /* The screen (0 when you are using DISPLAY=:0) of the connection 'conn' */
46 /* Display handle for libstartup-notification */
49 /* The last timestamp we got from X11 (timestamps are included in some events
50 * and are used for some things, like determining a unique ID in startup
52 xcb_timestamp_t last_timestamp = XCB_CURRENT_TIME;
54 xcb_screen_t *root_screen;
57 /* Color depth, visual id and colormap to use when creating windows and
58 * pixmaps. Will use 32 bit depth and an appropriate visual, if available,
59 * otherwise the root window’s default (usually 24 bit TrueColor). */
61 xcb_visualid_t visual_id;
62 xcb_colormap_t colormap;
64 struct ev_loop *main_loop;
66 xcb_key_symbols_t *keysyms;
68 /* Those are our connections to X11 for use with libXcursor and XKB */
69 Display *xlibdpy, *xkbdpy;
71 /* Default shmlog size if not set by user. */
72 const int default_shmlog_size = 25 * 1024 * 1024;
74 /* The list of key bindings */
75 struct bindings_head *bindings;
77 /* The list of exec-lines */
78 struct autostarts_head autostarts = TAILQ_HEAD_INITIALIZER(autostarts);
80 /* The list of exec_always lines */
81 struct autostarts_always_head autostarts_always = TAILQ_HEAD_INITIALIZER(autostarts_always);
83 /* The list of assignments */
84 struct assignments_head assignments = TAILQ_HEAD_INITIALIZER(assignments);
86 /* The list of workspace assignments (which workspace should end up on which
88 struct ws_assignments_head ws_assignments = TAILQ_HEAD_INITIALIZER(ws_assignments);
90 /* We hope that those are supported and set them to true */
91 bool xcursor_supported = true;
92 bool xkb_supported = true;
94 /* This will be set to true when -C is used so that functions can behave
95 * slightly differently. We don’t want i3-nagbar to be started when validating
96 * the config, for example. */
97 bool only_check_config = false;
100 * This callback is only a dummy, see xcb_prepare_cb and xcb_check_cb.
101 * See also man libev(3): "ev_prepare" and "ev_check" - customise your event loop
104 static void xcb_got_event(EV_P_ struct ev_io *w, int revents) {
105 /* empty, because xcb_prepare_cb and xcb_check_cb are used */
109 * Flush before blocking (and waiting for new events)
112 static void xcb_prepare_cb(EV_P_ ev_prepare *w, int revents) {
117 * Instead of polling the X connection socket we leave this to
118 * xcb_poll_for_event() which knows better than we can ever know.
121 static void xcb_check_cb(EV_P_ ev_check *w, int revents) {
122 xcb_generic_event_t *event;
124 while ((event = xcb_poll_for_event(conn)) != NULL) {
125 if (event->response_type == 0) {
126 if (event_is_ignored(event->sequence, 0))
127 DLOG("Expected X11 Error received for sequence %x\n", event->sequence);
129 xcb_generic_error_t *error = (xcb_generic_error_t*)event;
130 DLOG("X11 Error received (probably harmless)! sequence 0x%x, error_code = %d\n",
131 error->sequence, error->error_code);
137 /* Strip off the highest bit (set if the event is generated) */
138 int type = (event->response_type & 0x7F);
140 handle_event(type, event);
148 * When using xmodmap to change the keyboard mapping, this event
149 * is only sent via XKB. Therefore, we need this special handler.
152 static void xkb_got_event(EV_P_ struct ev_io *w, int revents) {
153 DLOG("Handling XKB event\n");
156 /* When using xmodmap, every change (!) gets an own event.
157 * Therefore, we just read all events and only handle the
158 * mapping_notify once. */
159 bool mapping_changed = false;
160 while (XPending(xkbdpy)) {
161 XNextEvent(xkbdpy, (XEvent*)&ev);
162 /* While we should never receive a non-XKB event,
163 * better do sanity checking */
164 if (ev.type != xkb_event_base)
167 if (ev.any.xkb_type == XkbMapNotify) {
168 mapping_changed = true;
172 if (ev.any.xkb_type != XkbStateNotify) {
173 ELOG("Unknown XKB event received (type %d)\n", ev.any.xkb_type);
177 /* See The XKB Extension: Library Specification, section 14.1 */
178 /* We check if the current group (each group contains
179 * two levels) has been changed. Mode_switch activates
180 * group XkbGroup2Index */
181 if (xkb_current_group == ev.state.group)
184 xkb_current_group = ev.state.group;
186 if (ev.state.group == XkbGroup2Index) {
187 DLOG("Mode_switch enabled\n");
188 grab_all_keys(conn, true);
191 if (ev.state.group == XkbGroup1Index) {
192 DLOG("Mode_switch disabled\n");
193 ungrab_all_keys(conn);
194 grab_all_keys(conn, false);
198 if (!mapping_changed)
201 DLOG("Keyboard mapping changed, updating keybindings\n");
202 xcb_key_symbols_free(keysyms);
203 keysyms = xcb_key_symbols_alloc(conn);
205 xcb_numlock_mask = aio_get_mod_mask_for(XCB_NUM_LOCK, keysyms);
207 ungrab_all_keys(conn);
208 DLOG("Re-grabbing...\n");
210 grab_all_keys(conn, (xkb_current_group == XkbGroup2Index));
215 * Exit handler which destroys the main_loop. Will trigger cleanup handlers.
218 static void i3_exit(void) {
219 /* We need ev >= 4 for the following code. Since it is not *that* important (it
220 * only makes sure that there are no i3-nagbar instances left behind) we still
221 * support old systems with libev 3. */
222 #if EV_VERSION_MAJOR >= 4
223 ev_loop_destroy(main_loop);
226 if (*shmlogname != '\0') {
227 fprintf(stderr, "Closing SHM log \"%s\"\n", shmlogname);
229 shm_unlink(shmlogname);
234 * (One-shot) Handler for all signals with default action "Term", see signal(7)
236 * Unlinks the SHM log and re-raises the signal.
239 static void handle_signal(int sig, siginfo_t *info, void *data) {
240 if (*shmlogname != '\0') {
241 shm_unlink(shmlogname);
246 int main(int argc, char *argv[]) {
247 /* Keep a symbol pointing to the I3_VERSION string constant so that we have
248 * it in gdb backtraces. */
249 const char *i3_version __attribute__ ((unused)) = I3_VERSION;
250 char *override_configpath = NULL;
251 bool autostart = true;
252 char *layout_path = NULL;
253 bool delete_layout_path = false;
254 bool force_xinerama = false;
255 char *fake_outputs = NULL;
256 bool disable_signalhandler = false;
257 static struct option long_options[] = {
258 {"no-autostart", no_argument, 0, 'a'},
259 {"config", required_argument, 0, 'c'},
260 {"version", no_argument, 0, 'v'},
261 {"moreversion", no_argument, 0, 'm'},
262 {"more-version", no_argument, 0, 'm'},
263 {"more_version", no_argument, 0, 'm'},
264 {"help", no_argument, 0, 'h'},
265 {"layout", required_argument, 0, 'L'},
266 {"restart", required_argument, 0, 0},
267 {"force-xinerama", no_argument, 0, 0},
268 {"force_xinerama", no_argument, 0, 0},
269 {"disable-signalhandler", no_argument, 0, 0},
270 {"shmlog-size", required_argument, 0, 0},
271 {"shmlog_size", required_argument, 0, 0},
272 {"get-socketpath", no_argument, 0, 0},
273 {"get_socketpath", no_argument, 0, 0},
274 {"fake_outputs", required_argument, 0, 0},
275 {"fake-outputs", required_argument, 0, 0},
276 {"force-old-config-parser-v4.4-only", no_argument, 0, 0},
279 int option_index = 0, opt;
281 setlocale(LC_ALL, "");
283 /* Get the RLIMIT_CORE limit at startup time to restore this before
284 * starting processes. */
285 getrlimit(RLIMIT_CORE, &original_rlimit_core);
287 /* Disable output buffering to make redirects in .xsession actually useful for debugging */
288 if (!isatty(fileno(stdout)))
289 setbuf(stdout, NULL);
293 /* Init logging *before* initializing debug_build to guarantee early
297 /* On release builds, disable SHM logging by default. */
298 shmlog_size = (is_debug_build() ? default_shmlog_size : 0);
302 while ((opt = getopt_long(argc, argv, "c:CvmaL:hld:V", long_options, &option_index)) != -1) {
305 LOG("Autostart disabled using -a\n");
310 layout_path = sstrdup(optarg);
311 delete_layout_path = false;
314 FREE(override_configpath);
315 override_configpath = sstrdup(optarg);
318 LOG("Checking configuration file only (-C)\n");
319 only_check_config = true;
322 printf("i3 version " I3_VERSION " © 2009-2013 Michael Stapelberg and contributors\n");
326 printf("Binary i3 version: " I3_VERSION " © 2009-2013 Michael Stapelberg and contributors\n");
327 display_running_version();
334 LOG("Enabling debug logging\n");
335 set_debug_logging(true);
338 /* DEPRECATED, ignored for the next 3 versions (3.e, 3.f, 3.g) */
341 if (strcmp(long_options[option_index].name, "force-xinerama") == 0 ||
342 strcmp(long_options[option_index].name, "force_xinerama") == 0) {
343 force_xinerama = true;
344 ELOG("Using Xinerama instead of RandR. This option should be "
345 "avoided at all cost because it does not refresh the list "
346 "of screens, so you cannot configure displays at runtime. "
347 "Please check if your driver really does not support RandR "
348 "and disable this option as soon as you can.\n");
350 } else if (strcmp(long_options[option_index].name, "disable-signalhandler") == 0) {
351 disable_signalhandler = true;
353 } else if (strcmp(long_options[option_index].name, "get-socketpath") == 0 ||
354 strcmp(long_options[option_index].name, "get_socketpath") == 0) {
355 char *socket_path = root_atom_contents("I3_SOCKET_PATH", NULL, 0);
357 printf("%s\n", socket_path);
362 } else if (strcmp(long_options[option_index].name, "shmlog-size") == 0 ||
363 strcmp(long_options[option_index].name, "shmlog_size") == 0) {
364 shmlog_size = atoi(optarg);
365 /* Re-initialize logging immediately to get as many
366 * logmessages as possible into the SHM log. */
368 LOG("Limiting SHM log size to %d bytes\n", shmlog_size);
370 } else if (strcmp(long_options[option_index].name, "restart") == 0) {
372 layout_path = sstrdup(optarg);
373 delete_layout_path = true;
375 } else if (strcmp(long_options[option_index].name, "fake-outputs") == 0 ||
376 strcmp(long_options[option_index].name, "fake_outputs") == 0) {
377 LOG("Initializing fake outputs: %s\n", optarg);
378 fake_outputs = sstrdup(optarg);
380 } else if (strcmp(long_options[option_index].name, "force-old-config-parser-v4.4-only") == 0) {
381 ELOG("You are passing --force-old-config-parser-v4.4-only, but that flag was removed by now.\n");
386 fprintf(stderr, "Usage: %s [-c configfile] [-d all] [-a] [-v] [-V] [-C]\n", argv[0]);
387 fprintf(stderr, "\n");
388 fprintf(stderr, "\t-a disable autostart ('exec' lines in config)\n");
389 fprintf(stderr, "\t-c <file> use the provided configfile instead\n");
390 fprintf(stderr, "\t-C validate configuration file and exit\n");
391 fprintf(stderr, "\t-d all enable debug output\n");
392 fprintf(stderr, "\t-L <file> path to the serialized layout during restarts\n");
393 fprintf(stderr, "\t-v display version and exit\n");
394 fprintf(stderr, "\t-V enable verbose mode\n");
395 fprintf(stderr, "\n");
396 fprintf(stderr, "\t--force-xinerama\n"
397 "\tUse Xinerama instead of RandR.\n"
398 "\tThis option should only be used if you are stuck with the\n"
399 "\told nVidia closed source driver (older than 302.17), which does\n"
400 "\tnot support RandR.\n");
401 fprintf(stderr, "\n");
402 fprintf(stderr, "\t--get-socketpath\n"
403 "\tRetrieve the i3 IPC socket path from X11, print it, then exit.\n");
404 fprintf(stderr, "\n");
405 fprintf(stderr, "\t--shmlog-size <limit>\n"
406 "\tLimits the size of the i3 SHM log to <limit> bytes. Setting this\n"
407 "\tto 0 disables SHM logging entirely.\n"
408 "\tThe default is %d bytes.\n", shmlog_size);
409 fprintf(stderr, "\n");
410 fprintf(stderr, "If you pass plain text arguments, i3 will interpret them as a command\n"
411 "to send to a currently running i3 (like i3-msg). This allows you to\n"
412 "use nice and logical commands, such as:\n"
415 "\ti3 floating toggle\n"
422 /* If the user passes more arguments, we act like i3-msg would: Just send
423 * the arguments as an IPC message to i3. This allows for nice semantic
424 * commands such as 'i3 border none'. */
425 if (!only_check_config && optind < argc) {
426 /* We enable verbose mode so that the user knows what’s going on.
427 * This should make it easier to find mistakes when the user passes
428 * arguments by mistake. */
431 LOG("Additional arguments passed. Sending them as a command to i3.\n");
432 char *payload = NULL;
433 while (optind < argc) {
435 payload = sstrdup(argv[optind]);
438 sasprintf(&both, "%s %s", payload, argv[optind]);
444 DLOG("Command is: %s (%zd bytes)\n", payload, strlen(payload));
445 char *socket_path = root_atom_contents("I3_SOCKET_PATH", NULL, 0);
447 ELOG("Could not get i3 IPC socket path\n");
451 int sockfd = socket(AF_LOCAL, SOCK_STREAM, 0);
453 err(EXIT_FAILURE, "Could not create socket");
455 struct sockaddr_un addr;
456 memset(&addr, 0, sizeof(struct sockaddr_un));
457 addr.sun_family = AF_LOCAL;
458 strncpy(addr.sun_path, socket_path, sizeof(addr.sun_path) - 1);
459 if (connect(sockfd, (const struct sockaddr*)&addr, sizeof(struct sockaddr_un)) < 0)
460 err(EXIT_FAILURE, "Could not connect to i3");
462 if (ipc_send_message(sockfd, strlen(payload), I3_IPC_MESSAGE_TYPE_COMMAND,
463 (uint8_t*)payload) == -1)
464 err(EXIT_FAILURE, "IPC: write()");
466 uint32_t reply_length;
470 if ((ret = ipc_recv_message(sockfd, &reply_type, &reply_length, &reply)) != 0) {
472 err(EXIT_FAILURE, "IPC: read()");
475 if (reply_type != I3_IPC_MESSAGE_TYPE_COMMAND)
476 errx(EXIT_FAILURE, "IPC: received reply of type %d but expected %d (COMMAND)", reply_type, I3_IPC_MESSAGE_TYPE_COMMAND);
477 printf("%.*s\n", reply_length, reply);
481 /* Enable logging to handle the case when the user did not specify --shmlog-size */
484 /* Try to enable core dumps by default when running a debug build */
485 if (is_debug_build()) {
486 struct rlimit limit = { RLIM_INFINITY, RLIM_INFINITY };
487 setrlimit(RLIMIT_CORE, &limit);
489 /* The following code is helpful, but not required. We thus don’t pay
490 * much attention to error handling, non-linux or other edge cases. */
491 LOG("CORE DUMPS: You are running a development version of i3, so coredumps were automatically enabled (ulimit -c unlimited).\n");
492 size_t cwd_size = 1024;
493 char *cwd = smalloc(cwd_size);
495 while ((cwd_ret = getcwd(cwd, cwd_size)) == NULL && errno == ERANGE) {
496 cwd_size = cwd_size * 2;
497 cwd = srealloc(cwd, cwd_size);
500 LOG("CORE DUMPS: Your current working directory is \"%s\".\n", cwd);
502 if ((patternfd = open("/proc/sys/kernel/core_pattern", O_RDONLY)) >= 0) {
503 memset(cwd, '\0', cwd_size);
504 if (read(patternfd, cwd, cwd_size) > 0)
505 /* a trailing newline is included in cwd */
506 LOG("CORE DUMPS: Your core_pattern is: %s", cwd);
512 LOG("i3 " I3_VERSION " starting\n");
514 conn = xcb_connect(NULL, &conn_screen);
515 if (xcb_connection_has_error(conn))
516 errx(EXIT_FAILURE, "Cannot open display\n");
518 sndisplay = sn_xcb_display_new(conn, NULL, NULL);
520 /* Initialize the libev event loop. This needs to be done before loading
521 * the config file because the parser will install an ev_child watcher
522 * for the nagbar when config errors are found. */
523 main_loop = EV_DEFAULT;
524 if (main_loop == NULL)
525 die("Could not initialize libev. Bad LIBEV_FLAGS?\n");
527 root_screen = xcb_aux_get_screen(conn, conn_screen);
528 root = root_screen->root;
530 /* By default, we use the same depth and visual as the root window, which
531 * usually is TrueColor (24 bit depth) and the corresponding visual.
532 * However, we also check if a 32 bit depth and visual are available (for
533 * transparency) and use it if so. */
534 root_depth = root_screen->root_depth;
535 visual_id = root_screen->root_visual;
536 colormap = root_screen->default_colormap;
538 DLOG("root_depth = %d, visual_id = 0x%08x.\n", root_depth, visual_id);
540 xcb_get_geometry_cookie_t gcookie = xcb_get_geometry(conn, root);
541 xcb_query_pointer_cookie_t pointercookie = xcb_query_pointer(conn, root);
543 load_configuration(conn, override_configpath, false);
544 if (only_check_config) {
545 LOG("Done checking configuration file. Exiting.\n");
549 if (config.ipc_socket_path == NULL) {
550 /* Fall back to a file name in /tmp/ based on the PID */
551 if ((config.ipc_socket_path = getenv("I3SOCK")) == NULL)
552 config.ipc_socket_path = get_process_filename("ipc-socket");
554 config.ipc_socket_path = sstrdup(config.ipc_socket_path);
557 xcb_void_cookie_t cookie;
558 cookie = xcb_change_window_attributes_checked(conn, root, XCB_CW_EVENT_MASK, (uint32_t[]){ ROOT_EVENT_MASK });
559 check_error(conn, cookie, "Another window manager seems to be running");
561 xcb_get_geometry_reply_t *greply = xcb_get_geometry_reply(conn, gcookie, NULL);
562 if (greply == NULL) {
563 ELOG("Could not get geometry of the root window, exiting\n");
566 DLOG("root geometry reply: (%d, %d) %d x %d\n", greply->x, greply->y, greply->width, greply->height);
568 /* Place requests for the atoms we need as soon as possible */
569 #define xmacro(atom) \
570 xcb_intern_atom_cookie_t atom ## _cookie = xcb_intern_atom(conn, 0, strlen(#atom), #atom);
571 #include "atoms.xmacro"
574 /* Initialize the Xlib connection */
575 xlibdpy = xkbdpy = XOpenDisplay(NULL);
577 /* Try to load the X cursors and initialize the XKB extension */
578 if (xlibdpy == NULL) {
579 ELOG("ERROR: XOpenDisplay() failed, disabling libXcursor/XKB support\n");
580 xcursor_supported = false;
581 xkb_supported = false;
582 } else if (fcntl(ConnectionNumber(xlibdpy), F_SETFD, FD_CLOEXEC) == -1) {
583 ELOG("Could not set FD_CLOEXEC on xkbdpy\n");
586 xcursor_load_cursors();
590 /* Set a cursor for the root window (otherwise the root window will show no
591 cursor until the first client is launched). */
592 if (xcursor_supported)
593 xcursor_set_root_cursor(XCURSOR_CURSOR_POINTER);
594 else xcb_set_root_cursor(XCURSOR_CURSOR_POINTER);
598 major = XkbMajorVersion,
599 minor = XkbMinorVersion;
601 if (fcntl(ConnectionNumber(xkbdpy), F_SETFD, FD_CLOEXEC) == -1) {
602 fprintf(stderr, "Could not set FD_CLOEXEC on xkbdpy\n");
607 if (!XkbQueryExtension(xkbdpy,&i1,&xkb_event_base,&errBase,&major,&minor)) {
608 fprintf(stderr, "XKB not supported by X-server\n");
609 xkb_supported = false;
611 /* end of ugliness */
613 if (xkb_supported && !XkbSelectEvents(xkbdpy, XkbUseCoreKbd,
614 XkbMapNotifyMask | XkbStateNotifyMask,
615 XkbMapNotifyMask | XkbStateNotifyMask)) {
616 fprintf(stderr, "Could not set XKB event mask\n");
621 /* Setup NetWM atoms */
622 #define xmacro(name) \
624 xcb_intern_atom_reply_t *reply = xcb_intern_atom_reply(conn, name ## _cookie, NULL); \
626 ELOG("Could not get atom " #name "\n"); \
629 A_ ## name = reply->atom; \
632 #include "atoms.xmacro"
635 property_handlers_init();
639 keysyms = xcb_key_symbols_alloc(conn);
641 xcb_numlock_mask = aio_get_mod_mask_for(XCB_NUM_LOCK, keysyms);
644 grab_all_keys(conn, false);
646 bool needs_tree_init = true;
648 LOG("Trying to restore the layout from %s...", layout_path);
649 needs_tree_init = !tree_restore(layout_path, greply);
650 if (delete_layout_path)
659 /* Setup fake outputs for testing */
660 if (fake_outputs == NULL && config.fake_outputs != NULL)
661 fake_outputs = config.fake_outputs;
663 if (fake_outputs != NULL) {
664 fake_outputs_init(fake_outputs);
666 config.fake_outputs = NULL;
667 } else if (force_xinerama || config.force_xinerama) {
668 /* Force Xinerama (for drivers which don't support RandR yet, esp. the
669 * nVidia binary graphics driver), when specified either in the config
670 * file or on command-line */
673 DLOG("Checking for XRandR...\n");
674 randr_init(&randr_base);
677 scratchpad_fix_resolution();
679 xcb_query_pointer_reply_t *pointerreply;
680 Output *output = NULL;
681 if (!(pointerreply = xcb_query_pointer_reply(conn, pointercookie, NULL))) {
682 ELOG("Could not query pointer position, using first screen\n");
684 DLOG("Pointer at %d, %d\n", pointerreply->root_x, pointerreply->root_y);
685 output = get_output_containing(pointerreply->root_x, pointerreply->root_y);
687 ELOG("ERROR: No screen at (%d, %d), starting on the first screen\n",
688 pointerreply->root_x, pointerreply->root_y);
689 output = get_first_output();
692 con_focus(con_descend_focused(output_get_content(output->con)));
697 /* Create the UNIX domain socket for IPC */
698 int ipc_socket = ipc_create_socket(config.ipc_socket_path);
699 if (ipc_socket == -1) {
700 ELOG("Could not create the IPC socket, IPC disabled\n");
702 free(config.ipc_socket_path);
703 struct ev_io *ipc_io = scalloc(sizeof(struct ev_io));
704 ev_io_init(ipc_io, ipc_new_client, ipc_socket, EV_READ);
705 ev_io_start(main_loop, ipc_io);
708 /* Also handle the UNIX domain sockets passed via socket activation. The
709 * parameter 1 means "remove the environment variables", we don’t want to
710 * pass these to child processes. */
711 listen_fds = sd_listen_fds(0);
713 ELOG("socket activation: Error in sd_listen_fds\n");
714 else if (listen_fds == 0)
715 DLOG("socket activation: no sockets passed\n");
718 for (int fd = SD_LISTEN_FDS_START;
719 fd < (SD_LISTEN_FDS_START + listen_fds);
721 DLOG("socket activation: also listening on fd %d\n", fd);
723 /* sd_listen_fds() enables FD_CLOEXEC by default.
724 * However, we need to keep the file descriptors open for in-place
725 * restarting, therefore we explicitly disable FD_CLOEXEC. */
726 if ((flags = fcntl(fd, F_GETFD)) < 0 ||
727 fcntl(fd, F_SETFD, flags & ~FD_CLOEXEC) < 0) {
728 ELOG("Could not disable FD_CLOEXEC on fd %d\n", fd);
731 struct ev_io *ipc_io = scalloc(sizeof(struct ev_io));
732 ev_io_init(ipc_io, ipc_new_client, fd, EV_READ);
733 ev_io_start(main_loop, ipc_io);
737 /* Set up i3 specific atoms like I3_SOCKET_PATH and I3_CONFIG_PATH */
739 ewmh_update_workarea();
741 struct ev_io *xcb_watcher = scalloc(sizeof(struct ev_io));
742 struct ev_io *xkb = scalloc(sizeof(struct ev_io));
743 struct ev_check *xcb_check = scalloc(sizeof(struct ev_check));
744 struct ev_prepare *xcb_prepare = scalloc(sizeof(struct ev_prepare));
746 ev_io_init(xcb_watcher, xcb_got_event, xcb_get_file_descriptor(conn), EV_READ);
747 ev_io_start(main_loop, xcb_watcher);
751 ev_io_init(xkb, xkb_got_event, ConnectionNumber(xkbdpy), EV_READ);
752 ev_io_start(main_loop, xkb);
754 /* Flush the buffer so that libev can properly get new events */
758 ev_check_init(xcb_check, xcb_check_cb);
759 ev_check_start(main_loop, xcb_check);
761 ev_prepare_init(xcb_prepare, xcb_prepare_cb);
762 ev_prepare_start(main_loop, xcb_prepare);
766 /* What follows is a fugly consequence of X11 protocol race conditions like
767 * the following: In an i3 in-place restart, i3 will reparent all windows
768 * to the root window, then exec() itself. In the new process, it calls
769 * manage_existing_windows. However, in case any application sent a
770 * generated UnmapNotify message to the WM (as GIMP does), this message
771 * will be handled by i3 *after* managing the window, thus i3 thinks the
772 * window just closed itself. In reality, the message was sent in the time
773 * period where i3 wasn’t running yet.
775 * To prevent this, we grab the server (disables processing of any other
776 * connections), then discard all pending events (since we didn’t do
777 * anything, there cannot be any meaningful responses), then ungrab the
779 xcb_grab_server(conn);
782 xcb_generic_event_t *event;
783 while ((event = xcb_poll_for_event(conn)) != NULL) {
784 if (event->response_type == 0) {
789 /* Strip off the highest bit (set if the event is generated) */
790 int type = (event->response_type & 0x7F);
792 /* We still need to handle MapRequests which are sent in the
793 * timespan starting from when we register as a window manager and
794 * this piece of code which drops events. */
795 if (type == XCB_MAP_REQUEST)
796 handle_event(type, event);
800 manage_existing_windows(root);
802 xcb_ungrab_server(conn);
805 LOG("This is not an in-place restart, copying root window contents to a pixmap\n");
806 xcb_screen_t *root = xcb_aux_get_screen(conn, conn_screen);
807 uint16_t width = root->width_in_pixels;
808 uint16_t height = root->height_in_pixels;
809 xcb_pixmap_t pixmap = xcb_generate_id(conn);
810 xcb_gcontext_t gc = xcb_generate_id(conn);
812 xcb_create_pixmap(conn, root->root_depth, pixmap, root->root, width, height);
814 xcb_create_gc(conn, gc, root->root,
815 XCB_GC_FUNCTION | XCB_GC_PLANE_MASK | XCB_GC_FILL_STYLE | XCB_GC_SUBWINDOW_MODE,
816 (uint32_t[]){ XCB_GX_COPY, ~0, XCB_FILL_STYLE_SOLID, XCB_SUBWINDOW_MODE_INCLUDE_INFERIORS });
818 xcb_copy_area(conn, root->root, pixmap, gc, 0, 0, 0, 0, width, height);
819 xcb_change_window_attributes_checked(conn, root->root, XCB_CW_BACK_PIXMAP, (uint32_t[]){ pixmap });
821 xcb_free_gc(conn, gc);
822 xcb_free_pixmap(conn, pixmap);
825 struct sigaction action;
827 action.sa_sigaction = handle_signal;
828 action.sa_flags = SA_NODEFER | SA_RESETHAND | SA_SIGINFO;
829 sigemptyset(&action.sa_mask);
831 if (!disable_signalhandler)
832 setup_signal_handler();
834 /* Catch all signals with default action "Core", see signal(7) */
835 if (sigaction(SIGQUIT, &action, NULL) == -1 ||
836 sigaction(SIGILL, &action, NULL) == -1 ||
837 sigaction(SIGABRT, &action, NULL) == -1 ||
838 sigaction(SIGFPE, &action, NULL) == -1 ||
839 sigaction(SIGSEGV, &action, NULL) == -1)
840 ELOG("Could not setup signal handler");
843 /* Catch all signals with default action "Term", see signal(7) */
844 if (sigaction(SIGHUP, &action, NULL) == -1 ||
845 sigaction(SIGINT, &action, NULL) == -1 ||
846 sigaction(SIGALRM, &action, NULL) == -1 ||
847 sigaction(SIGUSR1, &action, NULL) == -1 ||
848 sigaction(SIGUSR2, &action, NULL) == -1)
849 ELOG("Could not setup signal handler");
851 /* Ignore SIGPIPE to survive errors when an IPC client disconnects
852 * while we are sending him a message */
853 signal(SIGPIPE, SIG_IGN);
855 /* Autostarting exec-lines */
857 struct Autostart *exec;
858 TAILQ_FOREACH(exec, &autostarts, autostarts) {
859 LOG("auto-starting %s\n", exec->command);
860 start_application(exec->command, exec->no_startup_id);
864 /* Autostarting exec_always-lines */
865 struct Autostart *exec_always;
866 TAILQ_FOREACH(exec_always, &autostarts_always, autostarts_always) {
867 LOG("auto-starting (always!) %s\n", exec_always->command);
868 start_application(exec_always->command, exec_always->no_startup_id);
871 /* Start i3bar processes for all configured bars */
872 Barconfig *barconfig;
873 TAILQ_FOREACH(barconfig, &barconfigs, configs) {
874 char *command = NULL;
875 sasprintf(&command, "%s --bar_id=%s --socket=\"%s\"",
876 barconfig->i3bar_command ? barconfig->i3bar_command : "i3bar",
877 barconfig->id, current_socketpath);
878 LOG("Starting bar process: %s\n", command);
879 start_application(command, true);
883 /* Make sure to destroy the event loop to invoke the cleeanup callbacks
884 * when calling exit() */
887 ev_loop(main_loop, 0);