2 #define I3__FILE__ "main.c"
4 * vim:ts=4:sw=4:expandtab
6 * i3 - an improved dynamic tiling window manager
7 * © 2009 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>
25 #include "sd-daemon.h"
27 /* The original value of RLIMIT_CORE when i3 was started. We need to restore
28 * this before starting any other process, since we set RLIMIT_CORE to
29 * RLIM_INFINITY for i3 debugging versions. */
30 struct rlimit original_rlimit_core;
32 /** The number of file descriptors passed via socket activation. */
35 /* We keep the xcb_check watcher around to be able to enable and disable it
36 * temporarily for drag_pointer(). */
37 static struct ev_check *xcb_check;
43 xcb_connection_t *conn;
44 /* The screen (0 when you are using DISPLAY=:0) of the connection 'conn' */
47 /* Display handle for libstartup-notification */
50 /* The last timestamp we got from X11 (timestamps are included in some events
51 * and are used for some things, like determining a unique ID in startup
53 xcb_timestamp_t last_timestamp = XCB_CURRENT_TIME;
55 xcb_screen_t *root_screen;
58 /* Color depth, visual id and colormap to use when creating windows and
59 * pixmaps. Will use 32 bit depth and an appropriate visual, if available,
60 * otherwise the root window’s default (usually 24 bit TrueColor). */
62 xcb_visualid_t visual_id;
63 xcb_colormap_t colormap;
65 struct ev_loop *main_loop;
67 xcb_key_symbols_t *keysyms;
69 /* Default shmlog size if not set by user. */
70 const int default_shmlog_size = 25 * 1024 * 1024;
72 /* The list of key bindings */
73 struct bindings_head *bindings;
75 /* The list of exec-lines */
76 struct autostarts_head autostarts = TAILQ_HEAD_INITIALIZER(autostarts);
78 /* The list of exec_always lines */
79 struct autostarts_always_head autostarts_always = TAILQ_HEAD_INITIALIZER(autostarts_always);
81 /* The list of assignments */
82 struct assignments_head assignments = TAILQ_HEAD_INITIALIZER(assignments);
84 /* The list of workspace assignments (which workspace should end up on which
86 struct ws_assignments_head ws_assignments = TAILQ_HEAD_INITIALIZER(ws_assignments);
88 /* We hope that those are supported and set them to true */
89 bool xcursor_supported = true;
92 * This callback is only a dummy, see xcb_prepare_cb and xcb_check_cb.
93 * See also man libev(3): "ev_prepare" and "ev_check" - customise your event loop
96 static void xcb_got_event(EV_P_ struct ev_io *w, int revents) {
97 /* empty, because xcb_prepare_cb and xcb_check_cb are used */
101 * Flush before blocking (and waiting for new events)
104 static void xcb_prepare_cb(EV_P_ ev_prepare *w, int revents) {
109 * Instead of polling the X connection socket we leave this to
110 * xcb_poll_for_event() which knows better than we can ever know.
113 static void xcb_check_cb(EV_P_ ev_check *w, int revents) {
114 xcb_generic_event_t *event;
116 while ((event = xcb_poll_for_event(conn)) != NULL) {
117 if (event->response_type == 0) {
118 if (event_is_ignored(event->sequence, 0))
119 DLOG("Expected X11 Error received for sequence %x\n", event->sequence);
121 xcb_generic_error_t *error = (xcb_generic_error_t *)event;
122 DLOG("X11 Error received (probably harmless)! sequence 0x%x, error_code = %d\n",
123 error->sequence, error->error_code);
129 /* Strip off the highest bit (set if the event is generated) */
130 int type = (event->response_type & 0x7F);
132 handle_event(type, event);
139 * Enable or disable the main X11 event handling function.
140 * This is used by drag_pointer() which has its own, modal event handler, which
141 * takes precedence over the normal event handler.
144 void main_set_x11_cb(bool enable) {
145 DLOG("Setting main X11 callback to enabled=%d\n", enable);
147 ev_check_start(main_loop, xcb_check);
148 /* Trigger the watcher explicitly to handle all remaining X11 events.
149 * drag_pointer()’s event handler exits in the middle of the loop. */
150 ev_feed_event(main_loop, xcb_check, 0);
152 ev_check_stop(main_loop, xcb_check);
157 * Exit handler which destroys the main_loop. Will trigger cleanup handlers.
160 static void i3_exit(void) {
161 /* We need ev >= 4 for the following code. Since it is not *that* important (it
162 * only makes sure that there are no i3-nagbar instances left behind) we still
163 * support old systems with libev 3. */
164 #if EV_VERSION_MAJOR >= 4
165 ev_loop_destroy(main_loop);
168 if (*shmlogname != '\0') {
169 fprintf(stderr, "Closing SHM log \"%s\"\n", shmlogname);
171 shm_unlink(shmlogname);
176 * (One-shot) Handler for all signals with default action "Term", see signal(7)
178 * Unlinks the SHM log and re-raises the signal.
181 static void handle_signal(int sig, siginfo_t *info, void *data) {
182 if (*shmlogname != '\0') {
183 shm_unlink(shmlogname);
188 int main(int argc, char *argv[]) {
189 /* Keep a symbol pointing to the I3_VERSION string constant so that we have
190 * it in gdb backtraces. */
191 const char *_i3_version __attribute__((unused)) = i3_version;
192 char *override_configpath = NULL;
193 bool autostart = true;
194 char *layout_path = NULL;
195 bool delete_layout_path = false;
196 bool force_xinerama = false;
197 char *fake_outputs = NULL;
198 bool disable_signalhandler = false;
199 bool only_check_config = false;
200 static struct option long_options[] = {
201 {"no-autostart", no_argument, 0, 'a'},
202 {"config", required_argument, 0, 'c'},
203 {"version", no_argument, 0, 'v'},
204 {"moreversion", no_argument, 0, 'm'},
205 {"more-version", no_argument, 0, 'm'},
206 {"more_version", no_argument, 0, 'm'},
207 {"help", no_argument, 0, 'h'},
208 {"layout", required_argument, 0, 'L'},
209 {"restart", required_argument, 0, 0},
210 {"force-xinerama", no_argument, 0, 0},
211 {"force_xinerama", no_argument, 0, 0},
212 {"disable-signalhandler", no_argument, 0, 0},
213 {"shmlog-size", required_argument, 0, 0},
214 {"shmlog_size", required_argument, 0, 0},
215 {"get-socketpath", no_argument, 0, 0},
216 {"get_socketpath", no_argument, 0, 0},
217 {"fake_outputs", required_argument, 0, 0},
218 {"fake-outputs", required_argument, 0, 0},
219 {"force-old-config-parser-v4.4-only", no_argument, 0, 0},
221 int option_index = 0, opt;
223 setlocale(LC_ALL, "");
225 /* Get the RLIMIT_CORE limit at startup time to restore this before
226 * starting processes. */
227 getrlimit(RLIMIT_CORE, &original_rlimit_core);
229 /* Disable output buffering to make redirects in .xsession actually useful for debugging */
230 if (!isatty(fileno(stdout)))
231 setbuf(stdout, NULL);
235 /* Init logging *before* initializing debug_build to guarantee early
239 /* On release builds, disable SHM logging by default. */
240 shmlog_size = (is_debug_build() || strstr(argv[0], "i3-with-shmlog") != NULL ? default_shmlog_size : 0);
244 while ((opt = getopt_long(argc, argv, "c:CvmaL:hld:V", long_options, &option_index)) != -1) {
247 LOG("Autostart disabled using -a\n");
252 layout_path = sstrdup(optarg);
253 delete_layout_path = false;
256 FREE(override_configpath);
257 override_configpath = sstrdup(optarg);
260 LOG("Checking configuration file only (-C)\n");
261 only_check_config = true;
264 printf("i3 version %s © 2009 Michael Stapelberg and contributors\n", i3_version);
268 printf("Binary i3 version: %s © 2009 Michael Stapelberg and contributors\n", i3_version);
269 display_running_version();
276 LOG("Enabling debug logging\n");
277 set_debug_logging(true);
280 /* DEPRECATED, ignored for the next 3 versions (3.e, 3.f, 3.g) */
283 if (strcmp(long_options[option_index].name, "force-xinerama") == 0 ||
284 strcmp(long_options[option_index].name, "force_xinerama") == 0) {
285 force_xinerama = true;
286 ELOG("Using Xinerama instead of RandR. This option should be "
287 "avoided at all cost because it does not refresh the list "
288 "of screens, so you cannot configure displays at runtime. "
289 "Please check if your driver really does not support RandR "
290 "and disable this option as soon as you can.\n");
292 } else if (strcmp(long_options[option_index].name, "disable-signalhandler") == 0) {
293 disable_signalhandler = true;
295 } else if (strcmp(long_options[option_index].name, "get-socketpath") == 0 ||
296 strcmp(long_options[option_index].name, "get_socketpath") == 0) {
297 char *socket_path = root_atom_contents("I3_SOCKET_PATH", NULL, 0);
299 printf("%s\n", socket_path);
304 } else if (strcmp(long_options[option_index].name, "shmlog-size") == 0 ||
305 strcmp(long_options[option_index].name, "shmlog_size") == 0) {
306 shmlog_size = atoi(optarg);
307 /* Re-initialize logging immediately to get as many
308 * logmessages as possible into the SHM log. */
310 LOG("Limiting SHM log size to %d bytes\n", shmlog_size);
312 } else if (strcmp(long_options[option_index].name, "restart") == 0) {
314 layout_path = sstrdup(optarg);
315 delete_layout_path = true;
317 } else if (strcmp(long_options[option_index].name, "fake-outputs") == 0 ||
318 strcmp(long_options[option_index].name, "fake_outputs") == 0) {
319 LOG("Initializing fake outputs: %s\n", optarg);
320 fake_outputs = sstrdup(optarg);
322 } else if (strcmp(long_options[option_index].name, "force-old-config-parser-v4.4-only") == 0) {
323 ELOG("You are passing --force-old-config-parser-v4.4-only, but that flag was removed by now.\n");
328 fprintf(stderr, "Usage: %s [-c configfile] [-d all] [-a] [-v] [-V] [-C]\n", argv[0]);
329 fprintf(stderr, "\n");
330 fprintf(stderr, "\t-a disable autostart ('exec' lines in config)\n");
331 fprintf(stderr, "\t-c <file> use the provided configfile instead\n");
332 fprintf(stderr, "\t-C validate configuration file and exit\n");
333 fprintf(stderr, "\t-d all enable debug output\n");
334 fprintf(stderr, "\t-L <file> path to the serialized layout during restarts\n");
335 fprintf(stderr, "\t-v display version and exit\n");
336 fprintf(stderr, "\t-V enable verbose mode\n");
337 fprintf(stderr, "\n");
338 fprintf(stderr, "\t--force-xinerama\n"
339 "\tUse Xinerama instead of RandR.\n"
340 "\tThis option should only be used if you are stuck with the\n"
341 "\told nVidia closed source driver (older than 302.17), which does\n"
342 "\tnot support RandR.\n");
343 fprintf(stderr, "\n");
344 fprintf(stderr, "\t--get-socketpath\n"
345 "\tRetrieve the i3 IPC socket path from X11, print it, then exit.\n");
346 fprintf(stderr, "\n");
347 fprintf(stderr, "\t--shmlog-size <limit>\n"
348 "\tLimits the size of the i3 SHM log to <limit> bytes. Setting this\n"
349 "\tto 0 disables SHM logging entirely.\n"
350 "\tThe default is %d bytes.\n",
352 fprintf(stderr, "\n");
353 fprintf(stderr, "If you pass plain text arguments, i3 will interpret them as a command\n"
354 "to send to a currently running i3 (like i3-msg). This allows you to\n"
355 "use nice and logical commands, such as:\n"
358 "\ti3 floating toggle\n"
365 if (only_check_config) {
366 exit(parse_configuration(override_configpath, false) ? 0 : 1);
369 /* If the user passes more arguments, we act like i3-msg would: Just send
370 * the arguments as an IPC message to i3. This allows for nice semantic
371 * commands such as 'i3 border none'. */
373 /* We enable verbose mode so that the user knows what’s going on.
374 * This should make it easier to find mistakes when the user passes
375 * arguments by mistake. */
378 LOG("Additional arguments passed. Sending them as a command to i3.\n");
379 char *payload = NULL;
380 while (optind < argc) {
382 payload = sstrdup(argv[optind]);
385 sasprintf(&both, "%s %s", payload, argv[optind]);
391 DLOG("Command is: %s (%zd bytes)\n", payload, strlen(payload));
392 char *socket_path = root_atom_contents("I3_SOCKET_PATH", NULL, 0);
394 ELOG("Could not get i3 IPC socket path\n");
398 int sockfd = socket(AF_LOCAL, SOCK_STREAM, 0);
400 err(EXIT_FAILURE, "Could not create socket");
402 struct sockaddr_un addr;
403 memset(&addr, 0, sizeof(struct sockaddr_un));
404 addr.sun_family = AF_LOCAL;
405 strncpy(addr.sun_path, socket_path, sizeof(addr.sun_path) - 1);
406 if (connect(sockfd, (const struct sockaddr *)&addr, sizeof(struct sockaddr_un)) < 0)
407 err(EXIT_FAILURE, "Could not connect to i3");
409 if (ipc_send_message(sockfd, strlen(payload), I3_IPC_MESSAGE_TYPE_COMMAND,
410 (uint8_t *)payload) == -1)
411 err(EXIT_FAILURE, "IPC: write()");
413 uint32_t reply_length;
417 if ((ret = ipc_recv_message(sockfd, &reply_type, &reply_length, &reply)) != 0) {
419 err(EXIT_FAILURE, "IPC: read()");
422 if (reply_type != I3_IPC_MESSAGE_TYPE_COMMAND)
423 errx(EXIT_FAILURE, "IPC: received reply of type %d but expected %d (COMMAND)", reply_type, I3_IPC_MESSAGE_TYPE_COMMAND);
424 printf("%.*s\n", reply_length, reply);
428 /* Enable logging to handle the case when the user did not specify --shmlog-size */
431 /* Try to enable core dumps by default when running a debug build */
432 if (is_debug_build()) {
433 struct rlimit limit = {RLIM_INFINITY, RLIM_INFINITY};
434 setrlimit(RLIMIT_CORE, &limit);
436 /* The following code is helpful, but not required. We thus don’t pay
437 * much attention to error handling, non-linux or other edge cases. */
438 LOG("CORE DUMPS: You are running a development version of i3, so coredumps were automatically enabled (ulimit -c unlimited).\n");
439 size_t cwd_size = 1024;
440 char *cwd = smalloc(cwd_size);
442 while ((cwd_ret = getcwd(cwd, cwd_size)) == NULL && errno == ERANGE) {
443 cwd_size = cwd_size * 2;
444 cwd = srealloc(cwd, cwd_size);
447 LOG("CORE DUMPS: Your current working directory is \"%s\".\n", cwd);
449 if ((patternfd = open("/proc/sys/kernel/core_pattern", O_RDONLY)) >= 0) {
450 memset(cwd, '\0', cwd_size);
451 if (read(patternfd, cwd, cwd_size) > 0)
452 /* a trailing newline is included in cwd */
453 LOG("CORE DUMPS: Your core_pattern is: \"%s\".\n", cwd);
459 LOG("i3 %s starting\n", i3_version);
461 conn = xcb_connect(NULL, &conn_screen);
462 if (xcb_connection_has_error(conn))
463 errx(EXIT_FAILURE, "Cannot open display\n");
465 sndisplay = sn_xcb_display_new(conn, NULL, NULL);
467 /* Initialize the libev event loop. This needs to be done before loading
468 * the config file because the parser will install an ev_child watcher
469 * for the nagbar when config errors are found. */
470 main_loop = EV_DEFAULT;
471 if (main_loop == NULL)
472 die("Could not initialize libev. Bad LIBEV_FLAGS?\n");
474 root_screen = xcb_aux_get_screen(conn, conn_screen);
475 root = root_screen->root;
477 /* Place requests for the atoms we need as soon as possible */
478 #define xmacro(atom) \
479 xcb_intern_atom_cookie_t atom##_cookie = xcb_intern_atom(conn, 0, strlen(#atom), #atom);
480 #include "atoms.xmacro"
483 /* By default, we use the same depth and visual as the root window, which
484 * usually is TrueColor (24 bit depth) and the corresponding visual.
485 * However, we also check if a 32 bit depth and visual are available (for
486 * transparency) and use it if so. */
487 root_depth = root_screen->root_depth;
488 visual_id = root_screen->root_visual;
489 colormap = root_screen->default_colormap;
491 DLOG("root_depth = %d, visual_id = 0x%08x.\n", root_depth, visual_id);
492 DLOG("root_screen->height_in_pixels = %d, root_screen->height_in_millimeters = %d, dpi = %d\n",
493 root_screen->height_in_pixels, root_screen->height_in_millimeters,
494 (int)((double)root_screen->height_in_pixels * 25.4 / (double)root_screen->height_in_millimeters));
495 DLOG("One logical pixel corresponds to %d physical pixels on this display.\n", logical_px(1));
497 xcb_get_geometry_cookie_t gcookie = xcb_get_geometry(conn, root);
498 xcb_query_pointer_cookie_t pointercookie = xcb_query_pointer(conn, root);
500 /* Setup NetWM atoms */
501 #define xmacro(name) \
503 xcb_intern_atom_reply_t *reply = xcb_intern_atom_reply(conn, name##_cookie, NULL); \
505 ELOG("Could not get atom " #name "\n"); \
508 A_##name = reply->atom; \
511 #include "atoms.xmacro"
514 load_configuration(conn, override_configpath, false);
516 if (config.ipc_socket_path == NULL) {
517 /* Fall back to a file name in /tmp/ based on the PID */
518 if ((config.ipc_socket_path = getenv("I3SOCK")) == NULL)
519 config.ipc_socket_path = get_process_filename("ipc-socket");
521 config.ipc_socket_path = sstrdup(config.ipc_socket_path);
524 xcb_void_cookie_t cookie;
525 cookie = xcb_change_window_attributes_checked(conn, root, XCB_CW_EVENT_MASK, (uint32_t[]){ROOT_EVENT_MASK});
526 check_error(conn, cookie, "Another window manager seems to be running");
528 xcb_get_geometry_reply_t *greply = xcb_get_geometry_reply(conn, gcookie, NULL);
529 if (greply == NULL) {
530 ELOG("Could not get geometry of the root window, exiting\n");
533 DLOG("root geometry reply: (%d, %d) %d x %d\n", greply->x, greply->y, greply->width, greply->height);
535 xcursor_load_cursors();
537 /* Set a cursor for the root window (otherwise the root window will show no
538 cursor until the first client is launched). */
539 if (xcursor_supported)
540 xcursor_set_root_cursor(XCURSOR_CURSOR_POINTER);
542 xcb_set_root_cursor(XCURSOR_CURSOR_POINTER);
544 const xcb_query_extension_reply_t *extreply;
545 extreply = xcb_get_extension_data(conn, &xcb_xkb_id);
546 if (!extreply->present) {
547 DLOG("xkb is not present on this server\n");
549 DLOG("initializing xcb-xkb\n");
550 xcb_xkb_use_extension(conn, XCB_XKB_MAJOR_VERSION, XCB_XKB_MINOR_VERSION);
551 xcb_xkb_select_events(conn,
552 XCB_XKB_ID_USE_CORE_KBD,
553 XCB_XKB_EVENT_TYPE_STATE_NOTIFY | XCB_XKB_EVENT_TYPE_MAP_NOTIFY | XCB_XKB_EVENT_TYPE_NEW_KEYBOARD_NOTIFY,
555 XCB_XKB_EVENT_TYPE_STATE_NOTIFY | XCB_XKB_EVENT_TYPE_MAP_NOTIFY | XCB_XKB_EVENT_TYPE_NEW_KEYBOARD_NOTIFY,
560 /* Setting both, XCB_XKB_PER_CLIENT_FLAG_GRABS_USE_XKB_STATE and
561 * XCB_XKB_PER_CLIENT_FLAG_LOOKUP_STATE_WHEN_GRABBED, will lead to the
562 * X server sending us the full XKB state in KeyPress and KeyRelease:
563 * https://sources.debian.net/src/xorg-server/2:1.17.2-1.1/xkb/xkbEvents.c/?hl=927#L927
565 xcb_xkb_per_client_flags_reply_t *pcf_reply;
566 /* The last three parameters are unset because they are only relevant
567 * when using a feature called “automatic reset of boolean controls”:
568 * http://www.x.org/releases/X11R7.7/doc/kbproto/xkbproto.html#Automatic_Reset_of_Boolean_Controls
570 pcf_reply = xcb_xkb_per_client_flags_reply(
572 xcb_xkb_per_client_flags(
574 XCB_XKB_ID_USE_CORE_KBD,
575 XCB_XKB_PER_CLIENT_FLAG_GRABS_USE_XKB_STATE | XCB_XKB_PER_CLIENT_FLAG_LOOKUP_STATE_WHEN_GRABBED,
576 XCB_XKB_PER_CLIENT_FLAG_GRABS_USE_XKB_STATE | XCB_XKB_PER_CLIENT_FLAG_LOOKUP_STATE_WHEN_GRABBED,
577 0 /* uint32_t ctrlsToChange */,
578 0 /* uint32_t autoCtrls */,
579 0 /* uint32_t autoCtrlsValues */),
581 if (pcf_reply == NULL ||
582 !(pcf_reply->value & XCB_XKB_PER_CLIENT_FLAG_GRABS_USE_XKB_STATE)) {
583 ELOG("Could not set XCB_XKB_PER_CLIENT_FLAG_GRABS_USE_XKB_STATE\n");
585 if (pcf_reply == NULL ||
586 !(pcf_reply->value & XCB_XKB_PER_CLIENT_FLAG_LOOKUP_STATE_WHEN_GRABBED)) {
587 ELOG("Could not set XCB_XKB_PER_CLIENT_FLAG_LOOKUP_STATE_WHEN_GRABBED\n");
590 xkb_base = extreply->first_event;
595 property_handlers_init();
599 keysyms = xcb_key_symbols_alloc(conn);
601 xcb_numlock_mask = aio_get_mod_mask_for(XCB_NUM_LOCK, keysyms);
604 die("Could not load keymap\n");
609 bool needs_tree_init = true;
611 LOG("Trying to restore the layout from \"%s\".\n", layout_path);
612 needs_tree_init = !tree_restore(layout_path, greply);
613 if (delete_layout_path) {
615 const char *dir = dirname(layout_path);
616 /* possibly fails with ENOTEMPTY if there are files (or
627 /* Setup fake outputs for testing */
628 if (fake_outputs == NULL && config.fake_outputs != NULL)
629 fake_outputs = config.fake_outputs;
631 if (fake_outputs != NULL) {
632 fake_outputs_init(fake_outputs);
634 config.fake_outputs = NULL;
635 } else if (force_xinerama || config.force_xinerama) {
636 /* Force Xinerama (for drivers which don't support RandR yet, esp. the
637 * nVidia binary graphics driver), when specified either in the config
638 * file or on command-line */
641 DLOG("Checking for XRandR...\n");
642 randr_init(&randr_base);
645 scratchpad_fix_resolution();
647 xcb_query_pointer_reply_t *pointerreply;
648 Output *output = NULL;
649 if (!(pointerreply = xcb_query_pointer_reply(conn, pointercookie, NULL))) {
650 ELOG("Could not query pointer position, using first screen\n");
652 DLOG("Pointer at %d, %d\n", pointerreply->root_x, pointerreply->root_y);
653 output = get_output_containing(pointerreply->root_x, pointerreply->root_y);
655 ELOG("ERROR: No screen at (%d, %d), starting on the first screen\n",
656 pointerreply->root_x, pointerreply->root_y);
657 output = get_first_output();
660 con_focus(con_descend_focused(output_get_content(output->con)));
665 /* Create the UNIX domain socket for IPC */
666 int ipc_socket = ipc_create_socket(config.ipc_socket_path);
667 if (ipc_socket == -1) {
668 ELOG("Could not create the IPC socket, IPC disabled\n");
670 struct ev_io *ipc_io = scalloc(1, sizeof(struct ev_io));
671 ev_io_init(ipc_io, ipc_new_client, ipc_socket, EV_READ);
672 ev_io_start(main_loop, ipc_io);
675 /* Also handle the UNIX domain sockets passed via socket activation. The
676 * parameter 1 means "remove the environment variables", we don’t want to
677 * pass these to child processes. */
678 listen_fds = sd_listen_fds(0);
680 ELOG("socket activation: Error in sd_listen_fds\n");
681 else if (listen_fds == 0)
682 DLOG("socket activation: no sockets passed\n");
685 for (int fd = SD_LISTEN_FDS_START;
686 fd < (SD_LISTEN_FDS_START + listen_fds);
688 DLOG("socket activation: also listening on fd %d\n", fd);
690 /* sd_listen_fds() enables FD_CLOEXEC by default.
691 * However, we need to keep the file descriptors open for in-place
692 * restarting, therefore we explicitly disable FD_CLOEXEC. */
693 if ((flags = fcntl(fd, F_GETFD)) < 0 ||
694 fcntl(fd, F_SETFD, flags & ~FD_CLOEXEC) < 0) {
695 ELOG("Could not disable FD_CLOEXEC on fd %d\n", fd);
698 struct ev_io *ipc_io = scalloc(1, sizeof(struct ev_io));
699 ev_io_init(ipc_io, ipc_new_client, fd, EV_READ);
700 ev_io_start(main_loop, ipc_io);
704 /* Set up i3 specific atoms like I3_SOCKET_PATH and I3_CONFIG_PATH */
706 ewmh_update_workarea();
708 /* Set the ewmh desktop properties. */
709 ewmh_update_current_desktop();
710 ewmh_update_number_of_desktops();
711 ewmh_update_desktop_names();
712 ewmh_update_desktop_viewport();
714 struct ev_io *xcb_watcher = scalloc(1, sizeof(struct ev_io));
715 xcb_check = scalloc(1, sizeof(struct ev_check));
716 struct ev_prepare *xcb_prepare = scalloc(1, sizeof(struct ev_prepare));
718 ev_io_init(xcb_watcher, xcb_got_event, xcb_get_file_descriptor(conn), EV_READ);
719 ev_io_start(main_loop, xcb_watcher);
721 ev_check_init(xcb_check, xcb_check_cb);
722 ev_check_start(main_loop, xcb_check);
724 ev_prepare_init(xcb_prepare, xcb_prepare_cb);
725 ev_prepare_start(main_loop, xcb_prepare);
729 /* What follows is a fugly consequence of X11 protocol race conditions like
730 * the following: In an i3 in-place restart, i3 will reparent all windows
731 * to the root window, then exec() itself. In the new process, it calls
732 * manage_existing_windows. However, in case any application sent a
733 * generated UnmapNotify message to the WM (as GIMP does), this message
734 * will be handled by i3 *after* managing the window, thus i3 thinks the
735 * window just closed itself. In reality, the message was sent in the time
736 * period where i3 wasn’t running yet.
738 * To prevent this, we grab the server (disables processing of any other
739 * connections), then discard all pending events (since we didn’t do
740 * anything, there cannot be any meaningful responses), then ungrab the
742 xcb_grab_server(conn);
745 xcb_generic_event_t *event;
746 while ((event = xcb_poll_for_event(conn)) != NULL) {
747 if (event->response_type == 0) {
752 /* Strip off the highest bit (set if the event is generated) */
753 int type = (event->response_type & 0x7F);
755 /* We still need to handle MapRequests which are sent in the
756 * timespan starting from when we register as a window manager and
757 * this piece of code which drops events. */
758 if (type == XCB_MAP_REQUEST)
759 handle_event(type, event);
763 manage_existing_windows(root);
765 xcb_ungrab_server(conn);
768 LOG("This is not an in-place restart, copying root window contents to a pixmap\n");
769 xcb_screen_t *root = xcb_aux_get_screen(conn, conn_screen);
770 uint16_t width = root->width_in_pixels;
771 uint16_t height = root->height_in_pixels;
772 xcb_pixmap_t pixmap = xcb_generate_id(conn);
773 xcb_gcontext_t gc = xcb_generate_id(conn);
775 xcb_create_pixmap(conn, root->root_depth, pixmap, root->root, width, height);
777 xcb_create_gc(conn, gc, root->root,
778 XCB_GC_FUNCTION | XCB_GC_PLANE_MASK | XCB_GC_FILL_STYLE | XCB_GC_SUBWINDOW_MODE,
779 (uint32_t[]){XCB_GX_COPY, ~0, XCB_FILL_STYLE_SOLID, XCB_SUBWINDOW_MODE_INCLUDE_INFERIORS});
781 xcb_copy_area(conn, root->root, pixmap, gc, 0, 0, 0, 0, width, height);
782 xcb_change_window_attributes_checked(conn, root->root, XCB_CW_BACK_PIXMAP, (uint32_t[]){pixmap});
784 xcb_free_gc(conn, gc);
785 xcb_free_pixmap(conn, pixmap);
788 struct sigaction action;
790 action.sa_sigaction = handle_signal;
791 action.sa_flags = SA_NODEFER | SA_RESETHAND | SA_SIGINFO;
792 sigemptyset(&action.sa_mask);
794 if (!disable_signalhandler)
795 setup_signal_handler();
797 /* Catch all signals with default action "Core", see signal(7) */
798 if (sigaction(SIGQUIT, &action, NULL) == -1 ||
799 sigaction(SIGILL, &action, NULL) == -1 ||
800 sigaction(SIGABRT, &action, NULL) == -1 ||
801 sigaction(SIGFPE, &action, NULL) == -1 ||
802 sigaction(SIGSEGV, &action, NULL) == -1)
803 ELOG("Could not setup signal handler.\n");
806 /* Catch all signals with default action "Term", see signal(7) */
807 if (sigaction(SIGHUP, &action, NULL) == -1 ||
808 sigaction(SIGINT, &action, NULL) == -1 ||
809 sigaction(SIGALRM, &action, NULL) == -1 ||
810 sigaction(SIGUSR1, &action, NULL) == -1 ||
811 sigaction(SIGUSR2, &action, NULL) == -1)
812 ELOG("Could not setup signal handler.\n");
814 /* Ignore SIGPIPE to survive errors when an IPC client disconnects
815 * while we are sending them a message */
816 signal(SIGPIPE, SIG_IGN);
818 /* Autostarting exec-lines */
820 struct Autostart *exec;
821 TAILQ_FOREACH(exec, &autostarts, autostarts) {
822 LOG("auto-starting %s\n", exec->command);
823 start_application(exec->command, exec->no_startup_id);
827 /* Autostarting exec_always-lines */
828 struct Autostart *exec_always;
829 TAILQ_FOREACH(exec_always, &autostarts_always, autostarts_always) {
830 LOG("auto-starting (always!) %s\n", exec_always->command);
831 start_application(exec_always->command, exec_always->no_startup_id);
834 /* Start i3bar processes for all configured bars */
835 Barconfig *barconfig;
836 TAILQ_FOREACH(barconfig, &barconfigs, configs) {
837 char *command = NULL;
838 sasprintf(&command, "%s --bar_id=%s --socket=\"%s\"",
839 barconfig->i3bar_command ? barconfig->i3bar_command : "i3bar",
840 barconfig->id, current_socketpath);
841 LOG("Starting bar process: %s\n", command);
842 start_application(command, true);
846 /* Make sure to destroy the event loop to invoke the cleeanup callbacks
847 * when calling exit() */
850 ev_loop(main_loop, 0);