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_visualtype_t *visual_type;
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;
90 bool xkb_supported = true;
93 * This callback is only a dummy, see xcb_prepare_cb and xcb_check_cb.
94 * See also man libev(3): "ev_prepare" and "ev_check" - customise your event loop
97 static void xcb_got_event(EV_P_ struct ev_io *w, int revents) {
98 /* empty, because xcb_prepare_cb and xcb_check_cb are used */
102 * Flush before blocking (and waiting for new events)
105 static void xcb_prepare_cb(EV_P_ ev_prepare *w, int revents) {
110 * Instead of polling the X connection socket we leave this to
111 * xcb_poll_for_event() which knows better than we can ever know.
114 static void xcb_check_cb(EV_P_ ev_check *w, int revents) {
115 xcb_generic_event_t *event;
117 while ((event = xcb_poll_for_event(conn)) != NULL) {
118 if (event->response_type == 0) {
119 if (event_is_ignored(event->sequence, 0))
120 DLOG("Expected X11 Error received for sequence %x\n", event->sequence);
122 xcb_generic_error_t *error = (xcb_generic_error_t *)event;
123 DLOG("X11 Error received (probably harmless)! sequence 0x%x, error_code = %d\n",
124 error->sequence, error->error_code);
130 /* Strip off the highest bit (set if the event is generated) */
131 int type = (event->response_type & 0x7F);
133 handle_event(type, event);
140 * Enable or disable the main X11 event handling function.
141 * This is used by drag_pointer() which has its own, modal event handler, which
142 * takes precedence over the normal event handler.
145 void main_set_x11_cb(bool enable) {
146 DLOG("Setting main X11 callback to enabled=%d\n", enable);
148 ev_check_start(main_loop, xcb_check);
149 /* Trigger the watcher explicitly to handle all remaining X11 events.
150 * drag_pointer()’s event handler exits in the middle of the loop. */
151 ev_feed_event(main_loop, xcb_check, 0);
153 ev_check_stop(main_loop, xcb_check);
158 * Exit handler which destroys the main_loop. Will trigger cleanup handlers.
161 static void i3_exit(void) {
162 /* We need ev >= 4 for the following code. Since it is not *that* important (it
163 * only makes sure that there are no i3-nagbar instances left behind) we still
164 * support old systems with libev 3. */
165 #if EV_VERSION_MAJOR >= 4
166 ev_loop_destroy(main_loop);
169 if (*shmlogname != '\0') {
170 fprintf(stderr, "Closing SHM log \"%s\"\n", shmlogname);
172 shm_unlink(shmlogname);
177 * (One-shot) Handler for all signals with default action "Term", see signal(7)
179 * Unlinks the SHM log and re-raises the signal.
182 static void handle_signal(int sig, siginfo_t *info, void *data) {
183 if (*shmlogname != '\0') {
184 shm_unlink(shmlogname);
189 int main(int argc, char *argv[]) {
190 /* Keep a symbol pointing to the I3_VERSION string constant so that we have
191 * it in gdb backtraces. */
192 static const char *_i3_version __attribute__((used)) = I3_VERSION;
193 char *override_configpath = NULL;
194 bool autostart = true;
195 char *layout_path = NULL;
196 bool delete_layout_path = false;
197 bool force_xinerama = false;
198 char *fake_outputs = NULL;
199 bool disable_signalhandler = false;
200 bool only_check_config = false;
201 static struct option long_options[] = {
202 {"no-autostart", no_argument, 0, 'a'},
203 {"config", required_argument, 0, 'c'},
204 {"version", no_argument, 0, 'v'},
205 {"moreversion", no_argument, 0, 'm'},
206 {"more-version", no_argument, 0, 'm'},
207 {"more_version", no_argument, 0, 'm'},
208 {"help", no_argument, 0, 'h'},
209 {"layout", required_argument, 0, 'L'},
210 {"restart", required_argument, 0, 0},
211 {"force-xinerama", no_argument, 0, 0},
212 {"force_xinerama", no_argument, 0, 0},
213 {"disable-signalhandler", no_argument, 0, 0},
214 {"shmlog-size", required_argument, 0, 0},
215 {"shmlog_size", required_argument, 0, 0},
216 {"get-socketpath", no_argument, 0, 0},
217 {"get_socketpath", no_argument, 0, 0},
218 {"fake_outputs", required_argument, 0, 0},
219 {"fake-outputs", required_argument, 0, 0},
220 {"force-old-config-parser-v4.4-only", no_argument, 0, 0},
222 int option_index = 0, opt;
224 setlocale(LC_ALL, "");
226 /* Get the RLIMIT_CORE limit at startup time to restore this before
227 * starting processes. */
228 getrlimit(RLIMIT_CORE, &original_rlimit_core);
230 /* Disable output buffering to make redirects in .xsession actually useful for debugging */
231 if (!isatty(fileno(stdout)))
232 setbuf(stdout, NULL);
236 /* Init logging *before* initializing debug_build to guarantee early
240 /* On release builds, disable SHM logging by default. */
241 shmlog_size = (is_debug_build() || strstr(argv[0], "i3-with-shmlog") != NULL ? default_shmlog_size : 0);
245 while ((opt = getopt_long(argc, argv, "c:CvmaL:hld:V", long_options, &option_index)) != -1) {
248 LOG("Autostart disabled using -a\n");
253 layout_path = sstrdup(optarg);
254 delete_layout_path = false;
257 FREE(override_configpath);
258 override_configpath = sstrdup(optarg);
261 LOG("Checking configuration file only (-C)\n");
262 only_check_config = true;
265 printf("i3 version %s © 2009 Michael Stapelberg and contributors\n", i3_version);
269 printf("Binary i3 version: %s © 2009 Michael Stapelberg and contributors\n", i3_version);
270 display_running_version();
277 LOG("Enabling debug logging\n");
278 set_debug_logging(true);
281 /* DEPRECATED, ignored for the next 3 versions (3.e, 3.f, 3.g) */
284 if (strcmp(long_options[option_index].name, "force-xinerama") == 0 ||
285 strcmp(long_options[option_index].name, "force_xinerama") == 0) {
286 force_xinerama = true;
287 ELOG("Using Xinerama instead of RandR. This option should be "
288 "avoided at all cost because it does not refresh the list "
289 "of screens, so you cannot configure displays at runtime. "
290 "Please check if your driver really does not support RandR "
291 "and disable this option as soon as you can.\n");
293 } else if (strcmp(long_options[option_index].name, "disable-signalhandler") == 0) {
294 disable_signalhandler = true;
296 } else if (strcmp(long_options[option_index].name, "get-socketpath") == 0 ||
297 strcmp(long_options[option_index].name, "get_socketpath") == 0) {
298 char *socket_path = root_atom_contents("I3_SOCKET_PATH", NULL, 0);
300 printf("%s\n", socket_path);
305 } else if (strcmp(long_options[option_index].name, "shmlog-size") == 0 ||
306 strcmp(long_options[option_index].name, "shmlog_size") == 0) {
307 shmlog_size = atoi(optarg);
308 /* Re-initialize logging immediately to get as many
309 * logmessages as possible into the SHM log. */
311 LOG("Limiting SHM log size to %d bytes\n", shmlog_size);
313 } else if (strcmp(long_options[option_index].name, "restart") == 0) {
315 layout_path = sstrdup(optarg);
316 delete_layout_path = true;
318 } else if (strcmp(long_options[option_index].name, "fake-outputs") == 0 ||
319 strcmp(long_options[option_index].name, "fake_outputs") == 0) {
320 LOG("Initializing fake outputs: %s\n", optarg);
321 fake_outputs = sstrdup(optarg);
323 } else if (strcmp(long_options[option_index].name, "force-old-config-parser-v4.4-only") == 0) {
324 ELOG("You are passing --force-old-config-parser-v4.4-only, but that flag was removed by now.\n");
329 fprintf(stderr, "Usage: %s [-c configfile] [-d all] [-a] [-v] [-V] [-C]\n", argv[0]);
330 fprintf(stderr, "\n");
331 fprintf(stderr, "\t-a disable autostart ('exec' lines in config)\n");
332 fprintf(stderr, "\t-c <file> use the provided configfile instead\n");
333 fprintf(stderr, "\t-C validate configuration file and exit\n");
334 fprintf(stderr, "\t-d all enable debug output\n");
335 fprintf(stderr, "\t-L <file> path to the serialized layout during restarts\n");
336 fprintf(stderr, "\t-v display version and exit\n");
337 fprintf(stderr, "\t-V enable verbose mode\n");
338 fprintf(stderr, "\n");
339 fprintf(stderr, "\t--force-xinerama\n"
340 "\tUse Xinerama instead of RandR.\n"
341 "\tThis option should only be used if you are stuck with the\n"
342 "\told nVidia closed source driver (older than 302.17), which does\n"
343 "\tnot support RandR.\n");
344 fprintf(stderr, "\n");
345 fprintf(stderr, "\t--get-socketpath\n"
346 "\tRetrieve the i3 IPC socket path from X11, print it, then exit.\n");
347 fprintf(stderr, "\n");
348 fprintf(stderr, "\t--shmlog-size <limit>\n"
349 "\tLimits the size of the i3 SHM log to <limit> bytes. Setting this\n"
350 "\tto 0 disables SHM logging entirely.\n"
351 "\tThe default is %d bytes.\n",
353 fprintf(stderr, "\n");
354 fprintf(stderr, "If you pass plain text arguments, i3 will interpret them as a command\n"
355 "to send to a currently running i3 (like i3-msg). This allows you to\n"
356 "use nice and logical commands, such as:\n"
359 "\ti3 floating toggle\n"
366 if (only_check_config) {
367 exit(parse_configuration(override_configpath, false) ? 0 : 1);
370 /* If the user passes more arguments, we act like i3-msg would: Just send
371 * the arguments as an IPC message to i3. This allows for nice semantic
372 * commands such as 'i3 border none'. */
374 /* We enable verbose mode so that the user knows what’s going on.
375 * This should make it easier to find mistakes when the user passes
376 * arguments by mistake. */
379 LOG("Additional arguments passed. Sending them as a command to i3.\n");
380 char *payload = NULL;
381 while (optind < argc) {
383 payload = sstrdup(argv[optind]);
386 sasprintf(&both, "%s %s", payload, argv[optind]);
392 DLOG("Command is: %s (%zd bytes)\n", payload, strlen(payload));
393 char *socket_path = root_atom_contents("I3_SOCKET_PATH", NULL, 0);
395 ELOG("Could not get i3 IPC socket path\n");
399 int sockfd = socket(AF_LOCAL, SOCK_STREAM, 0);
401 err(EXIT_FAILURE, "Could not create socket");
403 struct sockaddr_un addr;
404 memset(&addr, 0, sizeof(struct sockaddr_un));
405 addr.sun_family = AF_LOCAL;
406 strncpy(addr.sun_path, socket_path, sizeof(addr.sun_path) - 1);
407 if (connect(sockfd, (const struct sockaddr *)&addr, sizeof(struct sockaddr_un)) < 0)
408 err(EXIT_FAILURE, "Could not connect to i3");
410 if (ipc_send_message(sockfd, strlen(payload), I3_IPC_MESSAGE_TYPE_COMMAND,
411 (uint8_t *)payload) == -1)
412 err(EXIT_FAILURE, "IPC: write()");
414 uint32_t reply_length;
418 if ((ret = ipc_recv_message(sockfd, &reply_type, &reply_length, &reply)) != 0) {
420 err(EXIT_FAILURE, "IPC: read()");
423 if (reply_type != I3_IPC_MESSAGE_TYPE_COMMAND)
424 errx(EXIT_FAILURE, "IPC: received reply of type %d but expected %d (COMMAND)", reply_type, I3_IPC_MESSAGE_TYPE_COMMAND);
425 printf("%.*s\n", reply_length, reply);
429 /* Enable logging to handle the case when the user did not specify --shmlog-size */
432 /* Try to enable core dumps by default when running a debug build */
433 if (is_debug_build()) {
434 struct rlimit limit = {RLIM_INFINITY, RLIM_INFINITY};
435 setrlimit(RLIMIT_CORE, &limit);
437 /* The following code is helpful, but not required. We thus don’t pay
438 * much attention to error handling, non-linux or other edge cases. */
439 LOG("CORE DUMPS: You are running a development version of i3, so coredumps were automatically enabled (ulimit -c unlimited).\n");
440 size_t cwd_size = 1024;
441 char *cwd = smalloc(cwd_size);
443 while ((cwd_ret = getcwd(cwd, cwd_size)) == NULL && errno == ERANGE) {
444 cwd_size = cwd_size * 2;
445 cwd = srealloc(cwd, cwd_size);
448 LOG("CORE DUMPS: Your current working directory is \"%s\".\n", cwd);
450 if ((patternfd = open("/proc/sys/kernel/core_pattern", O_RDONLY)) >= 0) {
451 memset(cwd, '\0', cwd_size);
452 if (read(patternfd, cwd, cwd_size) > 0)
453 /* a trailing newline is included in cwd */
454 LOG("CORE DUMPS: Your core_pattern is: %s", cwd);
460 LOG("i3 %s starting\n", i3_version);
462 conn = xcb_connect(NULL, &conn_screen);
463 if (xcb_connection_has_error(conn))
464 errx(EXIT_FAILURE, "Cannot open display\n");
466 sndisplay = sn_xcb_display_new(conn, NULL, NULL);
468 /* Initialize the libev event loop. This needs to be done before loading
469 * the config file because the parser will install an ev_child watcher
470 * for the nagbar when config errors are found. */
471 main_loop = EV_DEFAULT;
472 if (main_loop == NULL)
473 die("Could not initialize libev. Bad LIBEV_FLAGS?\n");
475 root_screen = xcb_aux_get_screen(conn, conn_screen);
476 root = root_screen->root;
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 root_depth = root_screen->root_depth;
485 colormap = root_screen->default_colormap;
486 visual_type = xcb_aux_find_visual_by_attrs(root_screen, -1, 32);
487 if (visual_type != NULL) {
488 root_depth = xcb_aux_get_depth_of_visual(root_screen, visual_type->visual_id);
489 colormap = xcb_generate_id(conn);
491 xcb_void_cookie_t cm_cookie = xcb_create_colormap_checked(conn,
492 XCB_COLORMAP_ALLOC_NONE,
495 visual_type->visual_id);
497 xcb_generic_error_t *error = xcb_request_check(conn, cm_cookie);
499 ELOG("Could not create colormap. Error code: %d\n", error->error_code);
503 visual_type = get_visualtype(root_screen);
508 DLOG("root_depth = %d, visual_id = 0x%08x.\n", root_depth, visual_type->visual_id);
509 DLOG("root_screen->height_in_pixels = %d, root_screen->height_in_millimeters = %d\n",
510 root_screen->height_in_pixels, root_screen->height_in_millimeters);
511 DLOG("One logical pixel corresponds to %d physical pixels on this display.\n", logical_px(1));
513 xcb_get_geometry_cookie_t gcookie = xcb_get_geometry(conn, root);
514 xcb_query_pointer_cookie_t pointercookie = xcb_query_pointer(conn, root);
516 /* Setup NetWM atoms */
517 #define xmacro(name) \
519 xcb_intern_atom_reply_t *reply = xcb_intern_atom_reply(conn, name##_cookie, NULL); \
521 ELOG("Could not get atom " #name "\n"); \
524 A_##name = reply->atom; \
527 #include "atoms.xmacro"
530 load_configuration(conn, override_configpath, false);
532 if (config.ipc_socket_path == NULL) {
533 /* Fall back to a file name in /tmp/ based on the PID */
534 if ((config.ipc_socket_path = getenv("I3SOCK")) == NULL)
535 config.ipc_socket_path = get_process_filename("ipc-socket");
537 config.ipc_socket_path = sstrdup(config.ipc_socket_path);
540 xcb_void_cookie_t cookie;
541 cookie = xcb_change_window_attributes_checked(conn, root, XCB_CW_EVENT_MASK, (uint32_t[]){ROOT_EVENT_MASK});
542 xcb_generic_error_t *error = xcb_request_check(conn, cookie);
544 ELOG("Another window manager seems to be running (X error %d)\n", error->error_code);
548 xcb_get_geometry_reply_t *greply = xcb_get_geometry_reply(conn, gcookie, NULL);
549 if (greply == NULL) {
550 ELOG("Could not get geometry of the root window, exiting\n");
553 DLOG("root geometry reply: (%d, %d) %d x %d\n", greply->x, greply->y, greply->width, greply->height);
555 xcursor_load_cursors();
557 /* Set a cursor for the root window (otherwise the root window will show no
558 cursor until the first client is launched). */
559 if (xcursor_supported)
560 xcursor_set_root_cursor(XCURSOR_CURSOR_POINTER);
562 xcb_set_root_cursor(XCURSOR_CURSOR_POINTER);
564 const xcb_query_extension_reply_t *extreply;
565 extreply = xcb_get_extension_data(conn, &xcb_xkb_id);
566 xkb_supported = extreply->present;
567 if (!extreply->present) {
568 DLOG("xkb is not present on this server\n");
570 DLOG("initializing xcb-xkb\n");
571 xcb_xkb_use_extension(conn, XCB_XKB_MAJOR_VERSION, XCB_XKB_MINOR_VERSION);
572 xcb_xkb_select_events(conn,
573 XCB_XKB_ID_USE_CORE_KBD,
574 XCB_XKB_EVENT_TYPE_STATE_NOTIFY | XCB_XKB_EVENT_TYPE_MAP_NOTIFY | XCB_XKB_EVENT_TYPE_NEW_KEYBOARD_NOTIFY,
576 XCB_XKB_EVENT_TYPE_STATE_NOTIFY | XCB_XKB_EVENT_TYPE_MAP_NOTIFY | XCB_XKB_EVENT_TYPE_NEW_KEYBOARD_NOTIFY,
581 /* Setting both, XCB_XKB_PER_CLIENT_FLAG_GRABS_USE_XKB_STATE and
582 * XCB_XKB_PER_CLIENT_FLAG_LOOKUP_STATE_WHEN_GRABBED, will lead to the
583 * X server sending us the full XKB state in KeyPress and KeyRelease:
584 * https://sources.debian.net/src/xorg-server/2:1.17.2-1.1/xkb/xkbEvents.c/?hl=927#L927
586 xcb_xkb_per_client_flags_reply_t *pcf_reply;
587 /* The last three parameters are unset because they are only relevant
588 * when using a feature called “automatic reset of boolean controls”:
589 * http://www.x.org/releases/X11R7.7/doc/kbproto/xkbproto.html#Automatic_Reset_of_Boolean_Controls
591 pcf_reply = xcb_xkb_per_client_flags_reply(
593 xcb_xkb_per_client_flags(
595 XCB_XKB_ID_USE_CORE_KBD,
596 XCB_XKB_PER_CLIENT_FLAG_GRABS_USE_XKB_STATE | XCB_XKB_PER_CLIENT_FLAG_LOOKUP_STATE_WHEN_GRABBED,
597 XCB_XKB_PER_CLIENT_FLAG_GRABS_USE_XKB_STATE | XCB_XKB_PER_CLIENT_FLAG_LOOKUP_STATE_WHEN_GRABBED,
598 0 /* uint32_t ctrlsToChange */,
599 0 /* uint32_t autoCtrls */,
600 0 /* uint32_t autoCtrlsValues */),
602 if (pcf_reply == NULL ||
603 !(pcf_reply->value & XCB_XKB_PER_CLIENT_FLAG_GRABS_USE_XKB_STATE)) {
604 ELOG("Could not set XCB_XKB_PER_CLIENT_FLAG_GRABS_USE_XKB_STATE\n");
606 if (pcf_reply == NULL ||
607 !(pcf_reply->value & XCB_XKB_PER_CLIENT_FLAG_LOOKUP_STATE_WHEN_GRABBED)) {
608 ELOG("Could not set XCB_XKB_PER_CLIENT_FLAG_LOOKUP_STATE_WHEN_GRABBED\n");
611 xkb_base = extreply->first_event;
616 property_handlers_init();
620 keysyms = xcb_key_symbols_alloc(conn);
622 xcb_numlock_mask = aio_get_mod_mask_for(XCB_NUM_LOCK, keysyms);
625 die("Could not load keymap\n");
630 bool needs_tree_init = true;
631 if (layout_path != NULL) {
632 LOG("Trying to restore the layout from \"%s\".\n", layout_path);
633 needs_tree_init = !tree_restore(layout_path, greply);
634 if (delete_layout_path) {
636 const char *dir = dirname(layout_path);
637 /* possibly fails with ENOTEMPTY if there are files (or
647 /* Setup fake outputs for testing */
648 if (fake_outputs == NULL && config.fake_outputs != NULL)
649 fake_outputs = config.fake_outputs;
651 if (fake_outputs != NULL) {
652 fake_outputs_init(fake_outputs);
654 config.fake_outputs = NULL;
655 } else if (force_xinerama || config.force_xinerama) {
656 /* Force Xinerama (for drivers which don't support RandR yet, esp. the
657 * nVidia binary graphics driver), when specified either in the config
658 * file or on command-line */
661 DLOG("Checking for XRandR...\n");
662 randr_init(&randr_base);
665 /* We need to force disabling outputs which have been loaded from the
666 * layout file but are no longer active. This can happen if the output has
667 * been disabled in the short time between writing the restart layout file
668 * and restarting i3. See #2326. */
669 if (layout_path != NULL && randr_base > -1) {
671 TAILQ_FOREACH(con, &(croot->nodes_head), nodes) {
673 TAILQ_FOREACH(output, &outputs, outputs) {
674 if (output->active || strcmp(con->name, output->name) != 0)
677 /* This will correctly correlate the output with its content
678 * container. We need to make the connection to properly
679 * disable the output. */
680 if (output->con == NULL) {
681 output_init_con(output);
682 output->changed = false;
685 output->to_be_disabled = true;
686 randr_disable_output(output);
692 scratchpad_fix_resolution();
694 xcb_query_pointer_reply_t *pointerreply;
695 Output *output = NULL;
696 if (!(pointerreply = xcb_query_pointer_reply(conn, pointercookie, NULL))) {
697 ELOG("Could not query pointer position, using first screen\n");
699 DLOG("Pointer at %d, %d\n", pointerreply->root_x, pointerreply->root_y);
700 output = get_output_containing(pointerreply->root_x, pointerreply->root_y);
702 ELOG("ERROR: No screen at (%d, %d), starting on the first screen\n",
703 pointerreply->root_x, pointerreply->root_y);
704 output = get_first_output();
707 con_focus(con_descend_focused(output_get_content(output->con)));
713 /* Create the UNIX domain socket for IPC */
714 int ipc_socket = ipc_create_socket(config.ipc_socket_path);
715 if (ipc_socket == -1) {
716 ELOG("Could not create the IPC socket, IPC disabled\n");
718 struct ev_io *ipc_io = scalloc(1, sizeof(struct ev_io));
719 ev_io_init(ipc_io, ipc_new_client, ipc_socket, EV_READ);
720 ev_io_start(main_loop, ipc_io);
723 /* Also handle the UNIX domain sockets passed via socket activation. The
724 * parameter 1 means "remove the environment variables", we don’t want to
725 * pass these to child processes. */
726 listen_fds = sd_listen_fds(0);
728 ELOG("socket activation: Error in sd_listen_fds\n");
729 else if (listen_fds == 0)
730 DLOG("socket activation: no sockets passed\n");
733 for (int fd = SD_LISTEN_FDS_START;
734 fd < (SD_LISTEN_FDS_START + listen_fds);
736 DLOG("socket activation: also listening on fd %d\n", fd);
738 /* sd_listen_fds() enables FD_CLOEXEC by default.
739 * However, we need to keep the file descriptors open for in-place
740 * restarting, therefore we explicitly disable FD_CLOEXEC. */
741 if ((flags = fcntl(fd, F_GETFD)) < 0 ||
742 fcntl(fd, F_SETFD, flags & ~FD_CLOEXEC) < 0) {
743 ELOG("Could not disable FD_CLOEXEC on fd %d\n", fd);
746 struct ev_io *ipc_io = scalloc(1, sizeof(struct ev_io));
747 ev_io_init(ipc_io, ipc_new_client, fd, EV_READ);
748 ev_io_start(main_loop, ipc_io);
752 /* Set up i3 specific atoms like I3_SOCKET_PATH and I3_CONFIG_PATH */
754 ewmh_update_workarea();
756 /* Set the ewmh desktop properties. */
757 ewmh_update_current_desktop();
758 ewmh_update_number_of_desktops();
759 ewmh_update_desktop_names();
760 ewmh_update_desktop_viewport();
762 struct ev_io *xcb_watcher = scalloc(1, sizeof(struct ev_io));
763 xcb_check = scalloc(1, sizeof(struct ev_check));
764 struct ev_prepare *xcb_prepare = scalloc(1, sizeof(struct ev_prepare));
766 ev_io_init(xcb_watcher, xcb_got_event, xcb_get_file_descriptor(conn), EV_READ);
767 ev_io_start(main_loop, xcb_watcher);
769 ev_check_init(xcb_check, xcb_check_cb);
770 ev_check_start(main_loop, xcb_check);
772 ev_prepare_init(xcb_prepare, xcb_prepare_cb);
773 ev_prepare_start(main_loop, xcb_prepare);
777 /* What follows is a fugly consequence of X11 protocol race conditions like
778 * the following: In an i3 in-place restart, i3 will reparent all windows
779 * to the root window, then exec() itself. In the new process, it calls
780 * manage_existing_windows. However, in case any application sent a
781 * generated UnmapNotify message to the WM (as GIMP does), this message
782 * will be handled by i3 *after* managing the window, thus i3 thinks the
783 * window just closed itself. In reality, the message was sent in the time
784 * period where i3 wasn’t running yet.
786 * To prevent this, we grab the server (disables processing of any other
787 * connections), then discard all pending events (since we didn’t do
788 * anything, there cannot be any meaningful responses), then ungrab the
790 xcb_grab_server(conn);
793 xcb_generic_event_t *event;
794 while ((event = xcb_poll_for_event(conn)) != NULL) {
795 if (event->response_type == 0) {
800 /* Strip off the highest bit (set if the event is generated) */
801 int type = (event->response_type & 0x7F);
803 /* We still need to handle MapRequests which are sent in the
804 * timespan starting from when we register as a window manager and
805 * this piece of code which drops events. */
806 if (type == XCB_MAP_REQUEST)
807 handle_event(type, event);
811 manage_existing_windows(root);
813 xcb_ungrab_server(conn);
816 LOG("This is not an in-place restart, copying root window contents to a pixmap\n");
817 xcb_screen_t *root = xcb_aux_get_screen(conn, conn_screen);
818 uint16_t width = root->width_in_pixels;
819 uint16_t height = root->height_in_pixels;
820 xcb_pixmap_t pixmap = xcb_generate_id(conn);
821 xcb_gcontext_t gc = xcb_generate_id(conn);
823 xcb_create_pixmap(conn, root->root_depth, pixmap, root->root, width, height);
825 xcb_create_gc(conn, gc, root->root,
826 XCB_GC_FUNCTION | XCB_GC_PLANE_MASK | XCB_GC_FILL_STYLE | XCB_GC_SUBWINDOW_MODE,
827 (uint32_t[]){XCB_GX_COPY, ~0, XCB_FILL_STYLE_SOLID, XCB_SUBWINDOW_MODE_INCLUDE_INFERIORS});
829 xcb_copy_area(conn, root->root, pixmap, gc, 0, 0, 0, 0, width, height);
830 xcb_change_window_attributes(conn, root->root, XCB_CW_BACK_PIXMAP, (uint32_t[]){pixmap});
832 xcb_free_gc(conn, gc);
833 xcb_free_pixmap(conn, pixmap);
836 #if defined(__OpenBSD__)
837 if (pledge("stdio rpath wpath cpath proc exec unix", NULL) == -1)
838 err(EXIT_FAILURE, "pledge");
841 struct sigaction action;
843 action.sa_sigaction = handle_signal;
844 action.sa_flags = SA_NODEFER | SA_RESETHAND | SA_SIGINFO;
845 sigemptyset(&action.sa_mask);
847 if (!disable_signalhandler)
848 setup_signal_handler();
850 /* Catch all signals with default action "Core", see signal(7) */
851 if (sigaction(SIGQUIT, &action, NULL) == -1 ||
852 sigaction(SIGILL, &action, NULL) == -1 ||
853 sigaction(SIGABRT, &action, NULL) == -1 ||
854 sigaction(SIGFPE, &action, NULL) == -1 ||
855 sigaction(SIGSEGV, &action, NULL) == -1)
856 ELOG("Could not setup signal handler.\n");
859 /* Catch all signals with default action "Term", see signal(7) */
860 if (sigaction(SIGHUP, &action, NULL) == -1 ||
861 sigaction(SIGINT, &action, NULL) == -1 ||
862 sigaction(SIGALRM, &action, NULL) == -1 ||
863 sigaction(SIGUSR1, &action, NULL) == -1 ||
864 sigaction(SIGUSR2, &action, NULL) == -1)
865 ELOG("Could not setup signal handler.\n");
867 /* Ignore SIGPIPE to survive errors when an IPC client disconnects
868 * while we are sending them a message */
869 signal(SIGPIPE, SIG_IGN);
871 /* Autostarting exec-lines */
873 while (!TAILQ_EMPTY(&autostarts)) {
874 struct Autostart *exec = TAILQ_FIRST(&autostarts);
876 LOG("auto-starting %s\n", exec->command);
877 start_application(exec->command, exec->no_startup_id);
880 TAILQ_REMOVE(&autostarts, exec, autostarts);
885 /* Autostarting exec_always-lines */
886 while (!TAILQ_EMPTY(&autostarts_always)) {
887 struct Autostart *exec_always = TAILQ_FIRST(&autostarts_always);
889 LOG("auto-starting (always!) %s\n", exec_always->command);
890 start_application(exec_always->command, exec_always->no_startup_id);
892 FREE(exec_always->command);
893 TAILQ_REMOVE(&autostarts_always, exec_always, autostarts_always);
897 /* Start i3bar processes for all configured bars */
898 Barconfig *barconfig;
899 TAILQ_FOREACH(barconfig, &barconfigs, configs) {
900 char *command = NULL;
901 sasprintf(&command, "%s --bar_id=%s --socket=\"%s\"",
902 barconfig->i3bar_command ? barconfig->i3bar_command : "i3bar",
903 barconfig->id, current_socketpath);
904 LOG("Starting bar process: %s\n", command);
905 start_application(command, true);
909 /* Make sure to destroy the event loop to invoke the cleeanup callbacks
910 * when calling exit() */
913 ev_loop(main_loop, 0);