2 * vim:ts=4:sw=4:expandtab
7 #include <sys/socket.h>
11 #include "sd-daemon.h"
13 static int xkb_event_base;
15 int xkb_current_group;
21 xcb_connection_t *conn;
22 /* The screen (0 when you are using DISPLAY=:0) of the connection 'conn' */
25 /* Display handle for libstartup-notification */
28 /* The last timestamp we got from X11 (timestamps are included in some events
29 * and are used for some things, like determining a unique ID in startup
31 xcb_timestamp_t last_timestamp = XCB_CURRENT_TIME;
33 xcb_screen_t *root_screen;
37 struct ev_loop *main_loop;
39 xcb_key_symbols_t *keysyms;
41 /* Those are our connections to X11 for use with libXcursor and XKB */
42 Display *xlibdpy, *xkbdpy;
44 /* The list of key bindings */
45 struct bindings_head *bindings;
47 /* The list of exec-lines */
48 struct autostarts_head autostarts = TAILQ_HEAD_INITIALIZER(autostarts);
50 /* The list of exec_always lines */
51 struct autostarts_always_head autostarts_always = TAILQ_HEAD_INITIALIZER(autostarts_always);
53 /* The list of assignments */
54 struct assignments_head assignments = TAILQ_HEAD_INITIALIZER(assignments);
56 /* The list of workspace assignments (which workspace should end up on which
58 struct ws_assignments_head ws_assignments = TAILQ_HEAD_INITIALIZER(ws_assignments);
60 /* We hope that those are supported and set them to true */
61 bool xcursor_supported = true;
62 bool xkb_supported = true;
65 * This callback is only a dummy, see xcb_prepare_cb and xcb_check_cb.
66 * See also man libev(3): "ev_prepare" and "ev_check" - customise your event loop
69 static void xcb_got_event(EV_P_ struct ev_io *w, int revents) {
70 /* empty, because xcb_prepare_cb and xcb_check_cb are used */
74 * Flush before blocking (and waiting for new events)
77 static void xcb_prepare_cb(EV_P_ ev_prepare *w, int revents) {
82 * Instead of polling the X connection socket we leave this to
83 * xcb_poll_for_event() which knows better than we can ever know.
86 static void xcb_check_cb(EV_P_ ev_check *w, int revents) {
87 xcb_generic_event_t *event;
89 while ((event = xcb_poll_for_event(conn)) != NULL) {
90 if (event->response_type == 0) {
91 if (event_is_ignored(event->sequence, 0))
92 DLOG("Expected X11 Error received for sequence %x\n", event->sequence);
94 xcb_generic_error_t *error = (xcb_generic_error_t*)event;
95 ELOG("X11 Error received! sequence 0x%x, error_code = %d\n",
96 error->sequence, error->error_code);
102 /* Strip off the highest bit (set if the event is generated) */
103 int type = (event->response_type & 0x7F);
105 handle_event(type, event);
113 * When using xmodmap to change the keyboard mapping, this event
114 * is only sent via XKB. Therefore, we need this special handler.
117 static void xkb_got_event(EV_P_ struct ev_io *w, int revents) {
118 DLOG("Handling XKB event\n");
121 /* When using xmodmap, every change (!) gets an own event.
122 * Therefore, we just read all events and only handle the
123 * mapping_notify once. */
124 bool mapping_changed = false;
125 while (XPending(xkbdpy)) {
126 XNextEvent(xkbdpy, (XEvent*)&ev);
127 /* While we should never receive a non-XKB event,
128 * better do sanity checking */
129 if (ev.type != xkb_event_base)
132 if (ev.any.xkb_type == XkbMapNotify) {
133 mapping_changed = true;
137 if (ev.any.xkb_type != XkbStateNotify) {
138 ELOG("Unknown XKB event received (type %d)\n", ev.any.xkb_type);
142 /* See The XKB Extension: Library Specification, section 14.1 */
143 /* We check if the current group (each group contains
144 * two levels) has been changed. Mode_switch activates
145 * group XkbGroup2Index */
146 if (xkb_current_group == ev.state.group)
149 xkb_current_group = ev.state.group;
151 if (ev.state.group == XkbGroup2Index) {
152 DLOG("Mode_switch enabled\n");
153 grab_all_keys(conn, true);
156 if (ev.state.group == XkbGroup1Index) {
157 DLOG("Mode_switch disabled\n");
158 ungrab_all_keys(conn);
159 grab_all_keys(conn, false);
163 if (!mapping_changed)
166 DLOG("Keyboard mapping changed, updating keybindings\n");
167 xcb_key_symbols_free(keysyms);
168 keysyms = xcb_key_symbols_alloc(conn);
170 xcb_get_numlock_mask(conn);
172 ungrab_all_keys(conn);
173 DLOG("Re-grabbing...\n");
175 grab_all_keys(conn, (xkb_current_group == XkbGroup2Index));
180 * Exit handler which destroys the main_loop. Will trigger cleanup handlers.
183 static void i3_exit() {
184 /* We need ev >= 4 for the following code. Since it is not *that* important (it
185 * only makes sure that there are no i3-nagbar instances left behind) we still
186 * support old systems with libev 3. */
187 #if EV_VERSION_MAJOR >= 4
188 ev_loop_destroy(main_loop);
192 int main(int argc, char *argv[]) {
193 char *override_configpath = NULL;
194 bool autostart = true;
195 char *layout_path = NULL;
196 bool delete_layout_path = false;
197 bool only_check_config = false;
198 bool force_xinerama = false;
199 bool disable_signalhandler = 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 {"help", no_argument, 0, 'h'},
205 {"layout", required_argument, 0, 'L'},
206 {"restart", required_argument, 0, 0},
207 {"force-xinerama", no_argument, 0, 0},
208 {"disable-signalhandler", no_argument, 0, 0},
209 {"get-socketpath", no_argument, 0, 0},
212 int option_index = 0, opt;
214 setlocale(LC_ALL, "");
216 /* Disable output buffering to make redirects in .xsession actually useful for debugging */
217 if (!isatty(fileno(stdout)))
218 setbuf(stdout, NULL);
224 while ((opt = getopt_long(argc, argv, "c:CvaL:hld:V", long_options, &option_index)) != -1) {
227 LOG("Autostart disabled using -a\n");
232 layout_path = sstrdup(optarg);
233 delete_layout_path = false;
236 FREE(override_configpath);
237 override_configpath = sstrdup(optarg);
240 LOG("Checking configuration file only (-C)\n");
241 only_check_config = true;
244 printf("i3 version " I3_VERSION " © 2009-2011 Michael Stapelberg and contributors\n");
250 LOG("Enabling debug loglevel %s\n", optarg);
251 add_loglevel(optarg);
254 /* DEPRECATED, ignored for the next 3 versions (3.e, 3.f, 3.g) */
257 if (strcmp(long_options[option_index].name, "force-xinerama") == 0) {
258 force_xinerama = true;
259 ELOG("Using Xinerama instead of RandR. This option should be "
260 "avoided at all cost because it does not refresh the list "
261 "of screens, so you cannot configure displays at runtime. "
262 "Please check if your driver really does not support RandR "
263 "and disable this option as soon as you can.\n");
265 } else if (strcmp(long_options[option_index].name, "disable-signalhandler") == 0) {
266 disable_signalhandler = true;
268 } else if (strcmp(long_options[option_index].name, "get-socketpath") == 0) {
269 char *socket_path = socket_path_from_x11();
271 printf("%s\n", socket_path);
276 } else if (strcmp(long_options[option_index].name, "restart") == 0) {
278 layout_path = sstrdup(optarg);
279 delete_layout_path = true;
284 fprintf(stderr, "Usage: %s [-c configfile] [-d loglevel] [-a] [-v] [-V] [-C]\n", argv[0]);
285 fprintf(stderr, "\n");
286 fprintf(stderr, "\t-a disable autostart ('exec' lines in config)\n");
287 fprintf(stderr, "\t-c <file> use the provided configfile instead\n");
288 fprintf(stderr, "\t-C validate configuration file and exit\n");
289 fprintf(stderr, "\t-d <level> enable debug output with the specified loglevel\n");
290 fprintf(stderr, "\t-L <file> path to the serialized layout during restarts\n");
291 fprintf(stderr, "\t-v display version and exit\n");
292 fprintf(stderr, "\t-V enable verbose mode\n");
293 fprintf(stderr, "\n");
294 fprintf(stderr, "\t--force-xinerama\n"
295 "\tUse Xinerama instead of RandR.\n"
296 "\tThis option should only be used if you are stuck with the\n"
297 "\tnvidia closed source driver which does not support RandR.\n");
298 fprintf(stderr, "\n");
299 fprintf(stderr, "\t--get-socketpath\n"
300 "\tRetrieve the i3 IPC socket path from X11, print it, then exit.\n");
301 fprintf(stderr, "\n");
302 fprintf(stderr, "If you pass plain text arguments, i3 will interpret them as a command\n"
303 "to send to a currently running i3 (like i3-msg). This allows you to\n"
304 "use nice and logical commands, such as:\n"
307 "\ti3 floating toggle\n"
314 /* If the user passes more arguments, we act like i3-msg would: Just send
315 * the arguments as an IPC message to i3. This allows for nice semantic
316 * commands such as 'i3 border none'. */
318 /* We enable verbose mode so that the user knows what’s going on.
319 * This should make it easier to find mistakes when the user passes
320 * arguments by mistake. */
323 LOG("Additional arguments passed. Sending them as a command to i3.\n");
324 char *payload = NULL;
325 while (optind < argc) {
327 payload = sstrdup(argv[optind]);
330 if (asprintf(&both, "%s %s", payload, argv[optind]) == -1)
331 err(EXIT_FAILURE, "asprintf");
337 LOG("Command is: %s (%d bytes)\n", payload, strlen(payload));
338 char *socket_path = socket_path_from_x11();
340 ELOG("Could not get i3 IPC socket path\n");
344 int sockfd = socket(AF_LOCAL, SOCK_STREAM, 0);
346 err(EXIT_FAILURE, "Could not create socket");
348 struct sockaddr_un addr;
349 memset(&addr, 0, sizeof(struct sockaddr_un));
350 addr.sun_family = AF_LOCAL;
351 strncpy(addr.sun_path, socket_path, sizeof(addr.sun_path) - 1);
352 if (connect(sockfd, (const struct sockaddr*)&addr, sizeof(struct sockaddr_un)) < 0)
353 err(EXIT_FAILURE, "Could not connect to i3");
355 if (ipc_send_message(sockfd, strlen(payload), I3_IPC_MESSAGE_TYPE_COMMAND,
356 (uint8_t*)payload) == -1)
357 err(EXIT_FAILURE, "IPC: write()");
359 uint32_t reply_length;
362 if ((ret = ipc_recv_message(sockfd, I3_IPC_MESSAGE_TYPE_COMMAND,
363 &reply_length, &reply)) != 0) {
365 err(EXIT_FAILURE, "IPC: read()");
368 printf("%.*s\n", reply_length, reply);
372 LOG("i3 (tree) version " I3_VERSION " starting\n");
374 conn = xcb_connect(NULL, &conn_screen);
375 if (xcb_connection_has_error(conn))
376 errx(EXIT_FAILURE, "Cannot open display\n");
378 sndisplay = sn_xcb_display_new(conn, NULL, NULL);
380 /* Initialize the libev event loop. This needs to be done before loading
381 * the config file because the parser will install an ev_child watcher
382 * for the nagbar when config errors are found. */
383 main_loop = EV_DEFAULT;
384 if (main_loop == NULL)
385 die("Could not initialize libev. Bad LIBEV_FLAGS?\n");
387 root_screen = xcb_aux_get_screen(conn, conn_screen);
388 root = root_screen->root;
389 root_depth = root_screen->root_depth;
390 xcb_get_geometry_cookie_t gcookie = xcb_get_geometry(conn, root);
391 xcb_query_pointer_cookie_t pointercookie = xcb_query_pointer(conn, root);
393 load_configuration(conn, override_configpath, false);
394 if (only_check_config) {
395 LOG("Done checking configuration file. Exiting.\n");
399 if (config.ipc_socket_path == NULL) {
400 /* Fall back to a file name in /tmp/ based on the PID */
401 if ((config.ipc_socket_path = getenv("I3SOCK")) == NULL)
402 config.ipc_socket_path = get_process_filename("ipc-socket");
404 config.ipc_socket_path = sstrdup(config.ipc_socket_path);
407 uint32_t mask = XCB_CW_EVENT_MASK;
408 uint32_t values[] = { XCB_EVENT_MASK_SUBSTRUCTURE_REDIRECT |
409 XCB_EVENT_MASK_STRUCTURE_NOTIFY | /* when the user adds a screen (e.g. video
410 projector), the root window gets a
412 XCB_EVENT_MASK_POINTER_MOTION |
413 XCB_EVENT_MASK_PROPERTY_CHANGE |
414 XCB_EVENT_MASK_ENTER_WINDOW };
415 xcb_void_cookie_t cookie;
416 cookie = xcb_change_window_attributes_checked(conn, root, mask, values);
417 check_error(conn, cookie, "Another window manager seems to be running");
419 xcb_get_geometry_reply_t *greply = xcb_get_geometry_reply(conn, gcookie, NULL);
420 if (greply == NULL) {
421 ELOG("Could not get geometry of the root window, exiting\n");
424 DLOG("root geometry reply: (%d, %d) %d x %d\n", greply->x, greply->y, greply->width, greply->height);
426 /* Place requests for the atoms we need as soon as possible */
427 #define xmacro(atom) \
428 xcb_intern_atom_cookie_t atom ## _cookie = xcb_intern_atom(conn, 0, strlen(#atom), #atom);
429 #include "atoms.xmacro"
432 /* Initialize the Xlib connection */
433 xlibdpy = xkbdpy = XOpenDisplay(NULL);
435 /* Try to load the X cursors and initialize the XKB extension */
436 if (xlibdpy == NULL) {
437 ELOG("ERROR: XOpenDisplay() failed, disabling libXcursor/XKB support\n");
438 xcursor_supported = false;
439 xkb_supported = false;
440 } else if (fcntl(ConnectionNumber(xlibdpy), F_SETFD, FD_CLOEXEC) == -1) {
441 ELOG("Could not set FD_CLOEXEC on xkbdpy\n");
444 xcursor_load_cursors();
448 /* Set a cursor for the root window (otherwise the root window will show no
449 cursor until the first client is launched). */
450 if (xcursor_supported)
451 xcursor_set_root_cursor(XCURSOR_CURSOR_POINTER);
452 else xcb_set_root_cursor(XCURSOR_CURSOR_POINTER);
456 major = XkbMajorVersion,
457 minor = XkbMinorVersion;
459 if (fcntl(ConnectionNumber(xkbdpy), F_SETFD, FD_CLOEXEC) == -1) {
460 fprintf(stderr, "Could not set FD_CLOEXEC on xkbdpy\n");
465 if (!XkbQueryExtension(xkbdpy,&i1,&xkb_event_base,&errBase,&major,&minor)) {
466 fprintf(stderr, "XKB not supported by X-server\n");
469 /* end of ugliness */
471 if (!XkbSelectEvents(xkbdpy, XkbUseCoreKbd,
472 XkbMapNotifyMask | XkbStateNotifyMask,
473 XkbMapNotifyMask | XkbStateNotifyMask)) {
474 fprintf(stderr, "Could not set XKB event mask\n");
479 /* Setup NetWM atoms */
480 #define xmacro(name) \
482 xcb_intern_atom_reply_t *reply = xcb_intern_atom_reply(conn, name ## _cookie, NULL); \
484 ELOG("Could not get atom " #name "\n"); \
487 A_ ## name = reply->atom; \
490 #include "atoms.xmacro"
493 property_handlers_init();
495 /* Set up the atoms we support */
496 xcb_atom_t supported_atoms[] = {
497 #define xmacro(atom) A_ ## atom,
498 #include "atoms.xmacro"
501 xcb_change_property(conn, XCB_PROP_MODE_REPLACE, root, A__NET_SUPPORTED, XCB_ATOM_ATOM, 32, 16, supported_atoms);
502 /* Set up the window manager’s name */
503 xcb_change_property(conn, XCB_PROP_MODE_REPLACE, root, A__NET_SUPPORTING_WM_CHECK, XCB_ATOM_WINDOW, 32, 1, &root);
504 xcb_change_property(conn, XCB_PROP_MODE_REPLACE, root, A__NET_WM_NAME, A_UTF8_STRING, 8, strlen("i3"), "i3");
506 keysyms = xcb_key_symbols_alloc(conn);
508 xcb_get_numlock_mask(conn);
511 grab_all_keys(conn, false);
513 bool needs_tree_init = true;
515 LOG("Trying to restore the layout from %s...", layout_path);
516 needs_tree_init = !tree_restore(layout_path, greply);
517 if (delete_layout_path)
526 /* Force Xinerama (for drivers which don't support RandR yet, esp. the
527 * nVidia binary graphics driver), when specified either in the config
528 * file or on command-line */
529 if (force_xinerama || config.force_xinerama) {
532 DLOG("Checking for XRandR...\n");
533 randr_init(&randr_base);
536 xcb_query_pointer_reply_t *pointerreply;
537 Output *output = NULL;
538 if (!(pointerreply = xcb_query_pointer_reply(conn, pointercookie, NULL))) {
539 ELOG("Could not query pointer position, using first screen\n");
540 output = get_first_output();
542 DLOG("Pointer at %d, %d\n", pointerreply->root_x, pointerreply->root_y);
543 output = get_output_containing(pointerreply->root_x, pointerreply->root_y);
545 ELOG("ERROR: No screen at (%d, %d), starting on the first screen\n",
546 pointerreply->root_x, pointerreply->root_y);
547 output = get_first_output();
550 con_focus(con_descend_focused(output_get_content(output->con)));
555 /* Create the UNIX domain socket for IPC */
556 int ipc_socket = ipc_create_socket(config.ipc_socket_path);
557 if (ipc_socket == -1) {
558 ELOG("Could not create the IPC socket, IPC disabled\n");
560 free(config.ipc_socket_path);
561 struct ev_io *ipc_io = scalloc(sizeof(struct ev_io));
562 ev_io_init(ipc_io, ipc_new_client, ipc_socket, EV_READ);
563 ev_io_start(main_loop, ipc_io);
566 /* Also handle the UNIX domain sockets passed via socket activation */
567 int fds = sd_listen_fds(1);
569 ELOG("socket activation: Error in sd_listen_fds\n");
571 DLOG("socket activation: no sockets passed\n");
573 for (int fd = SD_LISTEN_FDS_START; fd < (SD_LISTEN_FDS_START + fds); fd++) {
574 DLOG("socket activation: also listening on fd %d\n", fd);
575 struct ev_io *ipc_io = scalloc(sizeof(struct ev_io));
576 ev_io_init(ipc_io, ipc_new_client, fd, EV_READ);
577 ev_io_start(main_loop, ipc_io);
581 /* Set up i3 specific atoms like I3_SOCKET_PATH and I3_CONFIG_PATH */
584 struct ev_io *xcb_watcher = scalloc(sizeof(struct ev_io));
585 struct ev_io *xkb = scalloc(sizeof(struct ev_io));
586 struct ev_check *xcb_check = scalloc(sizeof(struct ev_check));
587 struct ev_prepare *xcb_prepare = scalloc(sizeof(struct ev_prepare));
589 ev_io_init(xcb_watcher, xcb_got_event, xcb_get_file_descriptor(conn), EV_READ);
590 ev_io_start(main_loop, xcb_watcher);
594 ev_io_init(xkb, xkb_got_event, ConnectionNumber(xkbdpy), EV_READ);
595 ev_io_start(main_loop, xkb);
597 /* Flush the buffer so that libev can properly get new events */
601 ev_check_init(xcb_check, xcb_check_cb);
602 ev_check_start(main_loop, xcb_check);
604 ev_prepare_init(xcb_prepare, xcb_prepare_cb);
605 ev_prepare_start(main_loop, xcb_prepare);
609 manage_existing_windows(root);
611 if (!disable_signalhandler)
612 setup_signal_handler();
614 /* Ignore SIGPIPE to survive errors when an IPC client disconnects
615 * while we are sending him a message */
616 signal(SIGPIPE, SIG_IGN);
618 /* Autostarting exec-lines */
620 struct Autostart *exec;
621 TAILQ_FOREACH(exec, &autostarts, autostarts) {
622 LOG("auto-starting %s\n", exec->command);
623 start_application(exec->command);
627 /* Autostarting exec_always-lines */
628 struct Autostart *exec_always;
629 TAILQ_FOREACH(exec_always, &autostarts_always, autostarts_always) {
630 LOG("auto-starting (always!) %s\n", exec_always->command);
631 start_application(exec_always->command);
634 /* Make sure to destroy the event loop to invoke the cleeanup callbacks
635 * when calling exit() */
638 ev_loop(main_loop, 0);