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>
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;
39 static int xkb_event_base;
41 int xkb_current_group;
47 xcb_connection_t *conn;
48 /* The screen (0 when you are using DISPLAY=:0) of the connection 'conn' */
51 /* Display handle for libstartup-notification */
54 /* The last timestamp we got from X11 (timestamps are included in some events
55 * and are used for some things, like determining a unique ID in startup
57 xcb_timestamp_t last_timestamp = XCB_CURRENT_TIME;
59 xcb_screen_t *root_screen;
62 /* Color depth, visual id and colormap to use when creating windows and
63 * pixmaps. Will use 32 bit depth and an appropriate visual, if available,
64 * otherwise the root window’s default (usually 24 bit TrueColor). */
66 xcb_visualid_t visual_id;
67 xcb_colormap_t colormap;
69 struct ev_loop *main_loop;
71 xcb_key_symbols_t *keysyms;
73 /* Those are our connections to X11 for use with libXcursor and XKB */
74 Display *xlibdpy, *xkbdpy;
76 /* Default shmlog size if not set by user. */
77 const int default_shmlog_size = 25 * 1024 * 1024;
79 /* The list of key bindings */
80 struct bindings_head *bindings;
82 /* The list of exec-lines */
83 struct autostarts_head autostarts = TAILQ_HEAD_INITIALIZER(autostarts);
85 /* The list of exec_always lines */
86 struct autostarts_always_head autostarts_always = TAILQ_HEAD_INITIALIZER(autostarts_always);
88 /* The list of assignments */
89 struct assignments_head assignments = TAILQ_HEAD_INITIALIZER(assignments);
91 /* The list of workspace assignments (which workspace should end up on which
93 struct ws_assignments_head ws_assignments = TAILQ_HEAD_INITIALIZER(ws_assignments);
95 /* We hope that those are supported and set them to true */
96 bool xcursor_supported = true;
97 bool xkb_supported = true;
99 /* This will be set to true when -C is used so that functions can behave
100 * slightly differently. We don’t want i3-nagbar to be started when validating
101 * the config, for example. */
102 bool only_check_config = false;
105 * This callback is only a dummy, see xcb_prepare_cb and xcb_check_cb.
106 * See also man libev(3): "ev_prepare" and "ev_check" - customise your event loop
109 static void xcb_got_event(EV_P_ struct ev_io *w, int revents) {
110 /* empty, because xcb_prepare_cb and xcb_check_cb are used */
114 * Flush before blocking (and waiting for new events)
117 static void xcb_prepare_cb(EV_P_ ev_prepare *w, int revents) {
122 * Instead of polling the X connection socket we leave this to
123 * xcb_poll_for_event() which knows better than we can ever know.
126 static void xcb_check_cb(EV_P_ ev_check *w, int revents) {
127 xcb_generic_event_t *event;
129 while ((event = xcb_poll_for_event(conn)) != NULL) {
130 if (event->response_type == 0) {
131 if (event_is_ignored(event->sequence, 0))
132 DLOG("Expected X11 Error received for sequence %x\n", event->sequence);
134 xcb_generic_error_t *error = (xcb_generic_error_t*)event;
135 DLOG("X11 Error received (probably harmless)! sequence 0x%x, error_code = %d\n",
136 error->sequence, error->error_code);
142 /* Strip off the highest bit (set if the event is generated) */
143 int type = (event->response_type & 0x7F);
145 handle_event(type, event);
152 * Enable or disable the main X11 event handling function.
153 * This is used by drag_pointer() which has its own, modal event handler, which
154 * takes precedence over the normal event handler.
157 void main_set_x11_cb(bool enable) {
158 DLOG("Setting main X11 callback to enabled=%d\n", enable);
160 ev_check_start(main_loop, xcb_check);
161 /* Trigger the watcher explicitly to handle all remaining X11 events.
162 * drag_pointer()’s event handler exits in the middle of the loop. */
163 ev_feed_event(main_loop, xcb_check, 0);
165 ev_check_stop(main_loop, xcb_check);
170 * When using xmodmap to change the keyboard mapping, this event
171 * is only sent via XKB. Therefore, we need this special handler.
174 static void xkb_got_event(EV_P_ struct ev_io *w, int revents) {
175 DLOG("Handling XKB event\n");
178 /* When using xmodmap, every change (!) gets an own event.
179 * Therefore, we just read all events and only handle the
180 * mapping_notify once. */
181 bool mapping_changed = false;
182 while (XPending(xkbdpy)) {
183 XNextEvent(xkbdpy, (XEvent*)&ev);
184 /* While we should never receive a non-XKB event,
185 * better do sanity checking */
186 if (ev.type != xkb_event_base)
189 if (ev.any.xkb_type == XkbMapNotify) {
190 mapping_changed = true;
194 if (ev.any.xkb_type != XkbStateNotify) {
195 ELOG("Unknown XKB event received (type %d)\n", ev.any.xkb_type);
199 /* See The XKB Extension: Library Specification, section 14.1 */
200 /* We check if the current group (each group contains
201 * two levels) has been changed. Mode_switch activates
202 * group XkbGroup2Index */
203 if (xkb_current_group == ev.state.group)
206 xkb_current_group = ev.state.group;
208 if (ev.state.group == XkbGroup2Index) {
209 DLOG("Mode_switch enabled\n");
210 grab_all_keys(conn, true);
213 if (ev.state.group == XkbGroup1Index) {
214 DLOG("Mode_switch disabled\n");
215 ungrab_all_keys(conn);
216 grab_all_keys(conn, false);
220 if (!mapping_changed)
223 DLOG("Keyboard mapping changed, updating keybindings\n");
224 xcb_key_symbols_free(keysyms);
225 keysyms = xcb_key_symbols_alloc(conn);
227 xcb_numlock_mask = aio_get_mod_mask_for(XCB_NUM_LOCK, keysyms);
229 ungrab_all_keys(conn);
230 DLOG("Re-grabbing...\n");
232 grab_all_keys(conn, (xkb_current_group == XkbGroup2Index));
237 * Exit handler which destroys the main_loop. Will trigger cleanup handlers.
240 static void i3_exit(void) {
241 /* We need ev >= 4 for the following code. Since it is not *that* important (it
242 * only makes sure that there are no i3-nagbar instances left behind) we still
243 * support old systems with libev 3. */
244 #if EV_VERSION_MAJOR >= 4
245 ev_loop_destroy(main_loop);
248 if (*shmlogname != '\0') {
249 fprintf(stderr, "Closing SHM log \"%s\"\n", shmlogname);
251 shm_unlink(shmlogname);
256 * (One-shot) Handler for all signals with default action "Term", see signal(7)
258 * Unlinks the SHM log and re-raises the signal.
261 static void handle_signal(int sig, siginfo_t *info, void *data) {
262 if (*shmlogname != '\0') {
263 shm_unlink(shmlogname);
268 int main(int argc, char *argv[]) {
269 /* Keep a symbol pointing to the I3_VERSION string constant so that we have
270 * it in gdb backtraces. */
271 const char *i3_version __attribute__ ((unused)) = I3_VERSION;
272 char *override_configpath = NULL;
273 bool autostart = true;
274 char *layout_path = NULL;
275 bool delete_layout_path = false;
276 bool force_xinerama = false;
277 char *fake_outputs = NULL;
278 bool disable_signalhandler = false;
279 static struct option long_options[] = {
280 {"no-autostart", no_argument, 0, 'a'},
281 {"config", required_argument, 0, 'c'},
282 {"version", no_argument, 0, 'v'},
283 {"moreversion", no_argument, 0, 'm'},
284 {"more-version", no_argument, 0, 'm'},
285 {"more_version", no_argument, 0, 'm'},
286 {"help", no_argument, 0, 'h'},
287 {"layout", required_argument, 0, 'L'},
288 {"restart", required_argument, 0, 0},
289 {"force-xinerama", no_argument, 0, 0},
290 {"force_xinerama", no_argument, 0, 0},
291 {"disable-signalhandler", no_argument, 0, 0},
292 {"shmlog-size", required_argument, 0, 0},
293 {"shmlog_size", required_argument, 0, 0},
294 {"get-socketpath", no_argument, 0, 0},
295 {"get_socketpath", no_argument, 0, 0},
296 {"fake_outputs", required_argument, 0, 0},
297 {"fake-outputs", required_argument, 0, 0},
298 {"force-old-config-parser-v4.4-only", no_argument, 0, 0},
301 int option_index = 0, opt;
303 setlocale(LC_ALL, "");
305 /* Get the RLIMIT_CORE limit at startup time to restore this before
306 * starting processes. */
307 getrlimit(RLIMIT_CORE, &original_rlimit_core);
309 /* Disable output buffering to make redirects in .xsession actually useful for debugging */
310 if (!isatty(fileno(stdout)))
311 setbuf(stdout, NULL);
315 /* Init logging *before* initializing debug_build to guarantee early
319 /* On release builds, disable SHM logging by default. */
320 shmlog_size = (is_debug_build() || strstr(argv[0], "i3-with-shmlog") != NULL ? default_shmlog_size : 0);
324 while ((opt = getopt_long(argc, argv, "c:CvmaL:hld:V", long_options, &option_index)) != -1) {
327 LOG("Autostart disabled using -a\n");
332 layout_path = sstrdup(optarg);
333 delete_layout_path = false;
336 FREE(override_configpath);
337 override_configpath = sstrdup(optarg);
340 LOG("Checking configuration file only (-C)\n");
341 only_check_config = true;
344 printf("i3 version " I3_VERSION " © 2009-2014 Michael Stapelberg and contributors\n");
348 printf("Binary i3 version: " I3_VERSION " © 2009-2014 Michael Stapelberg and contributors\n");
349 display_running_version();
356 LOG("Enabling debug logging\n");
357 set_debug_logging(true);
360 /* DEPRECATED, ignored for the next 3 versions (3.e, 3.f, 3.g) */
363 if (strcmp(long_options[option_index].name, "force-xinerama") == 0 ||
364 strcmp(long_options[option_index].name, "force_xinerama") == 0) {
365 force_xinerama = true;
366 ELOG("Using Xinerama instead of RandR. This option should be "
367 "avoided at all cost because it does not refresh the list "
368 "of screens, so you cannot configure displays at runtime. "
369 "Please check if your driver really does not support RandR "
370 "and disable this option as soon as you can.\n");
372 } else if (strcmp(long_options[option_index].name, "disable-signalhandler") == 0) {
373 disable_signalhandler = true;
375 } else if (strcmp(long_options[option_index].name, "get-socketpath") == 0 ||
376 strcmp(long_options[option_index].name, "get_socketpath") == 0) {
377 char *socket_path = root_atom_contents("I3_SOCKET_PATH", NULL, 0);
379 printf("%s\n", socket_path);
384 } else if (strcmp(long_options[option_index].name, "shmlog-size") == 0 ||
385 strcmp(long_options[option_index].name, "shmlog_size") == 0) {
386 shmlog_size = atoi(optarg);
387 /* Re-initialize logging immediately to get as many
388 * logmessages as possible into the SHM log. */
390 LOG("Limiting SHM log size to %d bytes\n", shmlog_size);
392 } else if (strcmp(long_options[option_index].name, "restart") == 0) {
394 layout_path = sstrdup(optarg);
395 delete_layout_path = true;
397 } else if (strcmp(long_options[option_index].name, "fake-outputs") == 0 ||
398 strcmp(long_options[option_index].name, "fake_outputs") == 0) {
399 LOG("Initializing fake outputs: %s\n", optarg);
400 fake_outputs = sstrdup(optarg);
402 } else if (strcmp(long_options[option_index].name, "force-old-config-parser-v4.4-only") == 0) {
403 ELOG("You are passing --force-old-config-parser-v4.4-only, but that flag was removed by now.\n");
408 fprintf(stderr, "Usage: %s [-c configfile] [-d all] [-a] [-v] [-V] [-C]\n", argv[0]);
409 fprintf(stderr, "\n");
410 fprintf(stderr, "\t-a disable autostart ('exec' lines in config)\n");
411 fprintf(stderr, "\t-c <file> use the provided configfile instead\n");
412 fprintf(stderr, "\t-C validate configuration file and exit\n");
413 fprintf(stderr, "\t-d all enable debug output\n");
414 fprintf(stderr, "\t-L <file> path to the serialized layout during restarts\n");
415 fprintf(stderr, "\t-v display version and exit\n");
416 fprintf(stderr, "\t-V enable verbose mode\n");
417 fprintf(stderr, "\n");
418 fprintf(stderr, "\t--force-xinerama\n"
419 "\tUse Xinerama instead of RandR.\n"
420 "\tThis option should only be used if you are stuck with the\n"
421 "\told nVidia closed source driver (older than 302.17), which does\n"
422 "\tnot support RandR.\n");
423 fprintf(stderr, "\n");
424 fprintf(stderr, "\t--get-socketpath\n"
425 "\tRetrieve the i3 IPC socket path from X11, print it, then exit.\n");
426 fprintf(stderr, "\n");
427 fprintf(stderr, "\t--shmlog-size <limit>\n"
428 "\tLimits the size of the i3 SHM log to <limit> bytes. Setting this\n"
429 "\tto 0 disables SHM logging entirely.\n"
430 "\tThe default is %d bytes.\n", shmlog_size);
431 fprintf(stderr, "\n");
432 fprintf(stderr, "If you pass plain text arguments, i3 will interpret them as a command\n"
433 "to send to a currently running i3 (like i3-msg). This allows you to\n"
434 "use nice and logical commands, such as:\n"
437 "\ti3 floating toggle\n"
444 /* If the user passes more arguments, we act like i3-msg would: Just send
445 * the arguments as an IPC message to i3. This allows for nice semantic
446 * commands such as 'i3 border none'. */
447 if (!only_check_config && optind < argc) {
448 /* We enable verbose mode so that the user knows what’s going on.
449 * This should make it easier to find mistakes when the user passes
450 * arguments by mistake. */
453 LOG("Additional arguments passed. Sending them as a command to i3.\n");
454 char *payload = NULL;
455 while (optind < argc) {
457 payload = sstrdup(argv[optind]);
460 sasprintf(&both, "%s %s", payload, argv[optind]);
466 DLOG("Command is: %s (%zd bytes)\n", payload, strlen(payload));
467 char *socket_path = root_atom_contents("I3_SOCKET_PATH", NULL, 0);
469 ELOG("Could not get i3 IPC socket path\n");
473 int sockfd = socket(AF_LOCAL, SOCK_STREAM, 0);
475 err(EXIT_FAILURE, "Could not create socket");
477 struct sockaddr_un addr;
478 memset(&addr, 0, sizeof(struct sockaddr_un));
479 addr.sun_family = AF_LOCAL;
480 strncpy(addr.sun_path, socket_path, sizeof(addr.sun_path) - 1);
481 if (connect(sockfd, (const struct sockaddr*)&addr, sizeof(struct sockaddr_un)) < 0)
482 err(EXIT_FAILURE, "Could not connect to i3");
484 if (ipc_send_message(sockfd, strlen(payload), I3_IPC_MESSAGE_TYPE_COMMAND,
485 (uint8_t*)payload) == -1)
486 err(EXIT_FAILURE, "IPC: write()");
488 uint32_t reply_length;
492 if ((ret = ipc_recv_message(sockfd, &reply_type, &reply_length, &reply)) != 0) {
494 err(EXIT_FAILURE, "IPC: read()");
497 if (reply_type != I3_IPC_MESSAGE_TYPE_COMMAND)
498 errx(EXIT_FAILURE, "IPC: received reply of type %d but expected %d (COMMAND)", reply_type, I3_IPC_MESSAGE_TYPE_COMMAND);
499 printf("%.*s\n", reply_length, reply);
503 /* Enable logging to handle the case when the user did not specify --shmlog-size */
506 /* Try to enable core dumps by default when running a debug build */
507 if (is_debug_build()) {
508 struct rlimit limit = { RLIM_INFINITY, RLIM_INFINITY };
509 setrlimit(RLIMIT_CORE, &limit);
511 /* The following code is helpful, but not required. We thus don’t pay
512 * much attention to error handling, non-linux or other edge cases. */
513 LOG("CORE DUMPS: You are running a development version of i3, so coredumps were automatically enabled (ulimit -c unlimited).\n");
514 size_t cwd_size = 1024;
515 char *cwd = smalloc(cwd_size);
517 while ((cwd_ret = getcwd(cwd, cwd_size)) == NULL && errno == ERANGE) {
518 cwd_size = cwd_size * 2;
519 cwd = srealloc(cwd, cwd_size);
522 LOG("CORE DUMPS: Your current working directory is \"%s\".\n", cwd);
524 if ((patternfd = open("/proc/sys/kernel/core_pattern", O_RDONLY)) >= 0) {
525 memset(cwd, '\0', cwd_size);
526 if (read(patternfd, cwd, cwd_size) > 0)
527 /* a trailing newline is included in cwd */
528 LOG("CORE DUMPS: Your core_pattern is: %s", cwd);
534 LOG("i3 " I3_VERSION " starting\n");
536 conn = xcb_connect(NULL, &conn_screen);
537 if (xcb_connection_has_error(conn))
538 errx(EXIT_FAILURE, "Cannot open display\n");
540 sndisplay = sn_xcb_display_new(conn, NULL, NULL);
542 /* Initialize the libev event loop. This needs to be done before loading
543 * the config file because the parser will install an ev_child watcher
544 * for the nagbar when config errors are found. */
545 main_loop = EV_DEFAULT;
546 if (main_loop == NULL)
547 die("Could not initialize libev. Bad LIBEV_FLAGS?\n");
549 root_screen = xcb_aux_get_screen(conn, conn_screen);
550 root = root_screen->root;
552 /* By default, we use the same depth and visual as the root window, which
553 * usually is TrueColor (24 bit depth) and the corresponding visual.
554 * However, we also check if a 32 bit depth and visual are available (for
555 * transparency) and use it if so. */
556 root_depth = root_screen->root_depth;
557 visual_id = root_screen->root_visual;
558 colormap = root_screen->default_colormap;
560 DLOG("root_depth = %d, visual_id = 0x%08x.\n", root_depth, visual_id);
562 xcb_get_geometry_cookie_t gcookie = xcb_get_geometry(conn, root);
563 xcb_query_pointer_cookie_t pointercookie = xcb_query_pointer(conn, root);
565 load_configuration(conn, override_configpath, false);
566 if (only_check_config) {
567 LOG("Done checking configuration file. Exiting.\n");
571 if (config.ipc_socket_path == NULL) {
572 /* Fall back to a file name in /tmp/ based on the PID */
573 if ((config.ipc_socket_path = getenv("I3SOCK")) == NULL)
574 config.ipc_socket_path = get_process_filename("ipc-socket");
576 config.ipc_socket_path = sstrdup(config.ipc_socket_path);
579 xcb_void_cookie_t cookie;
580 cookie = xcb_change_window_attributes_checked(conn, root, XCB_CW_EVENT_MASK, (uint32_t[]){ ROOT_EVENT_MASK });
581 check_error(conn, cookie, "Another window manager seems to be running");
583 xcb_get_geometry_reply_t *greply = xcb_get_geometry_reply(conn, gcookie, NULL);
584 if (greply == NULL) {
585 ELOG("Could not get geometry of the root window, exiting\n");
588 DLOG("root geometry reply: (%d, %d) %d x %d\n", greply->x, greply->y, greply->width, greply->height);
590 /* Place requests for the atoms we need as soon as possible */
591 #define xmacro(atom) \
592 xcb_intern_atom_cookie_t atom ## _cookie = xcb_intern_atom(conn, 0, strlen(#atom), #atom);
593 #include "atoms.xmacro"
596 /* Initialize the Xlib connection */
597 xlibdpy = xkbdpy = XOpenDisplay(NULL);
599 /* Try to load the X cursors and initialize the XKB extension */
600 if (xlibdpy == NULL) {
601 ELOG("ERROR: XOpenDisplay() failed, disabling libXcursor/XKB support\n");
602 xcursor_supported = false;
603 xkb_supported = false;
604 } else if (fcntl(ConnectionNumber(xlibdpy), F_SETFD, FD_CLOEXEC) == -1) {
605 ELOG("Could not set FD_CLOEXEC on xkbdpy\n");
608 xcursor_load_cursors();
612 /* Set a cursor for the root window (otherwise the root window will show no
613 cursor until the first client is launched). */
614 if (xcursor_supported)
615 xcursor_set_root_cursor(XCURSOR_CURSOR_POINTER);
616 else xcb_set_root_cursor(XCURSOR_CURSOR_POINTER);
620 major = XkbMajorVersion,
621 minor = XkbMinorVersion;
623 if (fcntl(ConnectionNumber(xkbdpy), F_SETFD, FD_CLOEXEC) == -1) {
624 fprintf(stderr, "Could not set FD_CLOEXEC on xkbdpy\n");
629 if (!XkbQueryExtension(xkbdpy,&i1,&xkb_event_base,&errBase,&major,&minor)) {
630 fprintf(stderr, "XKB not supported by X-server\n");
631 xkb_supported = false;
633 /* end of ugliness */
635 if (xkb_supported && !XkbSelectEvents(xkbdpy, XkbUseCoreKbd,
636 XkbMapNotifyMask | XkbStateNotifyMask,
637 XkbMapNotifyMask | XkbStateNotifyMask)) {
638 fprintf(stderr, "Could not set XKB event mask\n");
645 /* Setup NetWM atoms */
646 #define xmacro(name) \
648 xcb_intern_atom_reply_t *reply = xcb_intern_atom_reply(conn, name ## _cookie, NULL); \
650 ELOG("Could not get atom " #name "\n"); \
653 A_ ## name = reply->atom; \
656 #include "atoms.xmacro"
659 property_handlers_init();
663 keysyms = xcb_key_symbols_alloc(conn);
665 xcb_numlock_mask = aio_get_mod_mask_for(XCB_NUM_LOCK, keysyms);
668 grab_all_keys(conn, false);
670 bool needs_tree_init = true;
672 LOG("Trying to restore the layout from %s...", layout_path);
673 needs_tree_init = !tree_restore(layout_path, greply);
674 if (delete_layout_path) {
676 const char *dir = dirname(layout_path);
677 /* possibly fails with ENOTEMPTY if there are files (or
688 /* Setup fake outputs for testing */
689 if (fake_outputs == NULL && config.fake_outputs != NULL)
690 fake_outputs = config.fake_outputs;
692 if (fake_outputs != NULL) {
693 fake_outputs_init(fake_outputs);
695 config.fake_outputs = NULL;
696 } else if (force_xinerama || config.force_xinerama) {
697 /* Force Xinerama (for drivers which don't support RandR yet, esp. the
698 * nVidia binary graphics driver), when specified either in the config
699 * file or on command-line */
702 DLOG("Checking for XRandR...\n");
703 randr_init(&randr_base);
706 scratchpad_fix_resolution();
708 xcb_query_pointer_reply_t *pointerreply;
709 Output *output = NULL;
710 if (!(pointerreply = xcb_query_pointer_reply(conn, pointercookie, NULL))) {
711 ELOG("Could not query pointer position, using first screen\n");
713 DLOG("Pointer at %d, %d\n", pointerreply->root_x, pointerreply->root_y);
714 output = get_output_containing(pointerreply->root_x, pointerreply->root_y);
716 ELOG("ERROR: No screen at (%d, %d), starting on the first screen\n",
717 pointerreply->root_x, pointerreply->root_y);
718 output = get_first_output();
721 con_focus(con_descend_focused(output_get_content(output->con)));
726 /* Create the UNIX domain socket for IPC */
727 int ipc_socket = ipc_create_socket(config.ipc_socket_path);
728 if (ipc_socket == -1) {
729 ELOG("Could not create the IPC socket, IPC disabled\n");
731 struct ev_io *ipc_io = scalloc(sizeof(struct ev_io));
732 ev_io_init(ipc_io, ipc_new_client, ipc_socket, EV_READ);
733 ev_io_start(main_loop, ipc_io);
736 /* Also handle the UNIX domain sockets passed via socket activation. The
737 * parameter 1 means "remove the environment variables", we don’t want to
738 * pass these to child processes. */
739 listen_fds = sd_listen_fds(0);
741 ELOG("socket activation: Error in sd_listen_fds\n");
742 else if (listen_fds == 0)
743 DLOG("socket activation: no sockets passed\n");
746 for (int fd = SD_LISTEN_FDS_START;
747 fd < (SD_LISTEN_FDS_START + listen_fds);
749 DLOG("socket activation: also listening on fd %d\n", fd);
751 /* sd_listen_fds() enables FD_CLOEXEC by default.
752 * However, we need to keep the file descriptors open for in-place
753 * restarting, therefore we explicitly disable FD_CLOEXEC. */
754 if ((flags = fcntl(fd, F_GETFD)) < 0 ||
755 fcntl(fd, F_SETFD, flags & ~FD_CLOEXEC) < 0) {
756 ELOG("Could not disable FD_CLOEXEC on fd %d\n", fd);
759 struct ev_io *ipc_io = scalloc(sizeof(struct ev_io));
760 ev_io_init(ipc_io, ipc_new_client, fd, EV_READ);
761 ev_io_start(main_loop, ipc_io);
765 /* Set up i3 specific atoms like I3_SOCKET_PATH and I3_CONFIG_PATH */
767 ewmh_update_workarea();
769 /* Set the _NET_CURRENT_DESKTOP property. */
770 ewmh_update_current_desktop();
772 struct ev_io *xcb_watcher = scalloc(sizeof(struct ev_io));
773 struct ev_io *xkb = scalloc(sizeof(struct ev_io));
774 xcb_check = scalloc(sizeof(struct ev_check));
775 struct ev_prepare *xcb_prepare = scalloc(sizeof(struct ev_prepare));
777 ev_io_init(xcb_watcher, xcb_got_event, xcb_get_file_descriptor(conn), EV_READ);
778 ev_io_start(main_loop, xcb_watcher);
782 ev_io_init(xkb, xkb_got_event, ConnectionNumber(xkbdpy), EV_READ);
783 ev_io_start(main_loop, xkb);
785 /* Flush the buffer so that libev can properly get new events */
789 ev_check_init(xcb_check, xcb_check_cb);
790 ev_check_start(main_loop, xcb_check);
792 ev_prepare_init(xcb_prepare, xcb_prepare_cb);
793 ev_prepare_start(main_loop, xcb_prepare);
797 /* What follows is a fugly consequence of X11 protocol race conditions like
798 * the following: In an i3 in-place restart, i3 will reparent all windows
799 * to the root window, then exec() itself. In the new process, it calls
800 * manage_existing_windows. However, in case any application sent a
801 * generated UnmapNotify message to the WM (as GIMP does), this message
802 * will be handled by i3 *after* managing the window, thus i3 thinks the
803 * window just closed itself. In reality, the message was sent in the time
804 * period where i3 wasn’t running yet.
806 * To prevent this, we grab the server (disables processing of any other
807 * connections), then discard all pending events (since we didn’t do
808 * anything, there cannot be any meaningful responses), then ungrab the
810 xcb_grab_server(conn);
813 xcb_generic_event_t *event;
814 while ((event = xcb_poll_for_event(conn)) != NULL) {
815 if (event->response_type == 0) {
820 /* Strip off the highest bit (set if the event is generated) */
821 int type = (event->response_type & 0x7F);
823 /* We still need to handle MapRequests which are sent in the
824 * timespan starting from when we register as a window manager and
825 * this piece of code which drops events. */
826 if (type == XCB_MAP_REQUEST)
827 handle_event(type, event);
831 manage_existing_windows(root);
833 xcb_ungrab_server(conn);
836 LOG("This is not an in-place restart, copying root window contents to a pixmap\n");
837 xcb_screen_t *root = xcb_aux_get_screen(conn, conn_screen);
838 uint16_t width = root->width_in_pixels;
839 uint16_t height = root->height_in_pixels;
840 xcb_pixmap_t pixmap = xcb_generate_id(conn);
841 xcb_gcontext_t gc = xcb_generate_id(conn);
843 xcb_create_pixmap(conn, root->root_depth, pixmap, root->root, width, height);
845 xcb_create_gc(conn, gc, root->root,
846 XCB_GC_FUNCTION | XCB_GC_PLANE_MASK | XCB_GC_FILL_STYLE | XCB_GC_SUBWINDOW_MODE,
847 (uint32_t[]){ XCB_GX_COPY, ~0, XCB_FILL_STYLE_SOLID, XCB_SUBWINDOW_MODE_INCLUDE_INFERIORS });
849 xcb_copy_area(conn, root->root, pixmap, gc, 0, 0, 0, 0, width, height);
850 xcb_change_window_attributes_checked(conn, root->root, XCB_CW_BACK_PIXMAP, (uint32_t[]){ pixmap });
852 xcb_free_gc(conn, gc);
853 xcb_free_pixmap(conn, pixmap);
856 struct sigaction action;
858 action.sa_sigaction = handle_signal;
859 action.sa_flags = SA_NODEFER | SA_RESETHAND | SA_SIGINFO;
860 sigemptyset(&action.sa_mask);
862 if (!disable_signalhandler)
863 setup_signal_handler();
865 /* Catch all signals with default action "Core", see signal(7) */
866 if (sigaction(SIGQUIT, &action, NULL) == -1 ||
867 sigaction(SIGILL, &action, NULL) == -1 ||
868 sigaction(SIGABRT, &action, NULL) == -1 ||
869 sigaction(SIGFPE, &action, NULL) == -1 ||
870 sigaction(SIGSEGV, &action, NULL) == -1)
871 ELOG("Could not setup signal handler");
874 /* Catch all signals with default action "Term", see signal(7) */
875 if (sigaction(SIGHUP, &action, NULL) == -1 ||
876 sigaction(SIGINT, &action, NULL) == -1 ||
877 sigaction(SIGALRM, &action, NULL) == -1 ||
878 sigaction(SIGUSR1, &action, NULL) == -1 ||
879 sigaction(SIGUSR2, &action, NULL) == -1)
880 ELOG("Could not setup signal handler");
882 /* Ignore SIGPIPE to survive errors when an IPC client disconnects
883 * while we are sending him a message */
884 signal(SIGPIPE, SIG_IGN);
886 /* Autostarting exec-lines */
888 struct Autostart *exec;
889 TAILQ_FOREACH(exec, &autostarts, autostarts) {
890 LOG("auto-starting %s\n", exec->command);
891 start_application(exec->command, exec->no_startup_id);
895 /* Autostarting exec_always-lines */
896 struct Autostart *exec_always;
897 TAILQ_FOREACH(exec_always, &autostarts_always, autostarts_always) {
898 LOG("auto-starting (always!) %s\n", exec_always->command);
899 start_application(exec_always->command, exec_always->no_startup_id);
902 /* Start i3bar processes for all configured bars */
903 Barconfig *barconfig;
904 TAILQ_FOREACH(barconfig, &barconfigs, configs) {
905 char *command = NULL;
906 sasprintf(&command, "%s --bar_id=%s --socket=\"%s\"",
907 barconfig->i3bar_command ? barconfig->i3bar_command : "i3bar",
908 barconfig->id, current_socketpath);
909 LOG("Starting bar process: %s\n", command);
910 start_application(command, true);
914 /* Make sure to destroy the event loop to invoke the cleeanup callbacks
915 * when calling exit() */
918 ev_loop(main_loop, 0);