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 ev_loop_destroy(main_loop);
187 int main(int argc, char *argv[]) {
188 char *override_configpath = NULL;
189 bool autostart = true;
190 char *layout_path = NULL;
191 bool delete_layout_path = false;
192 bool only_check_config = false;
193 bool force_xinerama = false;
194 bool disable_signalhandler = false;
195 static struct option long_options[] = {
196 {"no-autostart", no_argument, 0, 'a'},
197 {"config", required_argument, 0, 'c'},
198 {"version", no_argument, 0, 'v'},
199 {"help", no_argument, 0, 'h'},
200 {"layout", required_argument, 0, 'L'},
201 {"restart", required_argument, 0, 0},
202 {"force-xinerama", no_argument, 0, 0},
203 {"disable-signalhandler", no_argument, 0, 0},
204 {"get-socketpath", no_argument, 0, 0},
207 int option_index = 0, opt;
209 setlocale(LC_ALL, "");
211 /* Disable output buffering to make redirects in .xsession actually useful for debugging */
212 if (!isatty(fileno(stdout)))
213 setbuf(stdout, NULL);
219 while ((opt = getopt_long(argc, argv, "c:CvaL:hld:V", long_options, &option_index)) != -1) {
222 LOG("Autostart disabled using -a\n");
227 layout_path = sstrdup(optarg);
228 delete_layout_path = false;
231 FREE(override_configpath);
232 override_configpath = sstrdup(optarg);
235 LOG("Checking configuration file only (-C)\n");
236 only_check_config = true;
239 printf("i3 version " I3_VERSION " © 2009-2011 Michael Stapelberg and contributors\n");
245 LOG("Enabling debug loglevel %s\n", optarg);
246 add_loglevel(optarg);
249 /* DEPRECATED, ignored for the next 3 versions (3.e, 3.f, 3.g) */
252 if (strcmp(long_options[option_index].name, "force-xinerama") == 0) {
253 force_xinerama = true;
254 ELOG("Using Xinerama instead of RandR. This option should be "
255 "avoided at all cost because it does not refresh the list "
256 "of screens, so you cannot configure displays at runtime. "
257 "Please check if your driver really does not support RandR "
258 "and disable this option as soon as you can.\n");
260 } else if (strcmp(long_options[option_index].name, "disable-signalhandler") == 0) {
261 disable_signalhandler = true;
263 } else if (strcmp(long_options[option_index].name, "get-socketpath") == 0) {
264 char *socket_path = socket_path_from_x11();
266 printf("%s\n", socket_path);
271 } else if (strcmp(long_options[option_index].name, "restart") == 0) {
273 layout_path = sstrdup(optarg);
274 delete_layout_path = true;
279 fprintf(stderr, "Usage: %s [-c configfile] [-d loglevel] [-a] [-v] [-V] [-C]\n", argv[0]);
280 fprintf(stderr, "\n");
281 fprintf(stderr, "\t-a disable autostart ('exec' lines in config)\n");
282 fprintf(stderr, "\t-c <file> use the provided configfile instead\n");
283 fprintf(stderr, "\t-C validate configuration file and exit\n");
284 fprintf(stderr, "\t-d <level> enable debug output with the specified loglevel\n");
285 fprintf(stderr, "\t-L <file> path to the serialized layout during restarts\n");
286 fprintf(stderr, "\t-v display version and exit\n");
287 fprintf(stderr, "\t-V enable verbose mode\n");
288 fprintf(stderr, "\n");
289 fprintf(stderr, "\t--force-xinerama\n"
290 "\tUse Xinerama instead of RandR.\n"
291 "\tThis option should only be used if you are stuck with the\n"
292 "\tnvidia closed source driver which does not support RandR.\n");
293 fprintf(stderr, "\n");
294 fprintf(stderr, "\t--get-socketpath\n"
295 "\tRetrieve the i3 IPC socket path from X11, print it, then exit.\n");
296 fprintf(stderr, "\n");
297 fprintf(stderr, "If you pass plain text arguments, i3 will interpret them as a command\n"
298 "to send to a currently running i3 (like i3-msg). This allows you to\n"
299 "use nice and logical commands, such as:\n"
302 "\ti3 floating toggle\n"
309 /* If the user passes more arguments, we act like i3-msg would: Just send
310 * the arguments as an IPC message to i3. This allows for nice semantic
311 * commands such as 'i3 border none'. */
313 /* We enable verbose mode so that the user knows what’s going on.
314 * This should make it easier to find mistakes when the user passes
315 * arguments by mistake. */
318 LOG("Additional arguments passed. Sending them as a command to i3.\n");
319 char *payload = NULL;
320 while (optind < argc) {
322 payload = sstrdup(argv[optind]);
325 if (asprintf(&both, "%s %s", payload, argv[optind]) == -1)
326 err(EXIT_FAILURE, "asprintf");
332 LOG("Command is: %s (%d bytes)\n", payload, strlen(payload));
333 char *socket_path = socket_path_from_x11();
335 ELOG("Could not get i3 IPC socket path\n");
339 int sockfd = socket(AF_LOCAL, SOCK_STREAM, 0);
341 err(EXIT_FAILURE, "Could not create socket");
343 struct sockaddr_un addr;
344 memset(&addr, 0, sizeof(struct sockaddr_un));
345 addr.sun_family = AF_LOCAL;
346 strncpy(addr.sun_path, socket_path, sizeof(addr.sun_path) - 1);
347 if (connect(sockfd, (const struct sockaddr*)&addr, sizeof(struct sockaddr_un)) < 0)
348 err(EXIT_FAILURE, "Could not connect to i3");
350 if (ipc_send_message(sockfd, strlen(payload), I3_IPC_MESSAGE_TYPE_COMMAND,
351 (uint8_t*)payload) == -1)
352 err(EXIT_FAILURE, "IPC: write()");
354 uint32_t reply_length;
357 if ((ret = ipc_recv_message(sockfd, I3_IPC_MESSAGE_TYPE_COMMAND,
358 &reply_length, &reply)) != 0) {
360 err(EXIT_FAILURE, "IPC: read()");
363 printf("%.*s\n", reply_length, reply);
367 LOG("i3 (tree) version " I3_VERSION " starting\n");
369 conn = xcb_connect(NULL, &conn_screen);
370 if (xcb_connection_has_error(conn))
371 errx(EXIT_FAILURE, "Cannot open display\n");
373 sndisplay = sn_xcb_display_new(conn, NULL, NULL);
375 /* Initialize the libev event loop. This needs to be done before loading
376 * the config file because the parser will install an ev_child watcher
377 * for the nagbar when config errors are found. */
378 main_loop = EV_DEFAULT;
379 if (main_loop == NULL)
380 die("Could not initialize libev. Bad LIBEV_FLAGS?\n");
382 root_screen = xcb_aux_get_screen(conn, conn_screen);
383 root = root_screen->root;
384 root_depth = root_screen->root_depth;
385 xcb_get_geometry_cookie_t gcookie = xcb_get_geometry(conn, root);
386 xcb_query_pointer_cookie_t pointercookie = xcb_query_pointer(conn, root);
388 load_configuration(conn, override_configpath, false);
389 if (only_check_config) {
390 LOG("Done checking configuration file. Exiting.\n");
394 if (config.ipc_socket_path == NULL) {
395 /* Fall back to a file name in /tmp/ based on the PID */
396 if ((config.ipc_socket_path = getenv("I3SOCK")) == NULL)
397 config.ipc_socket_path = get_process_filename("ipc-socket");
399 config.ipc_socket_path = sstrdup(config.ipc_socket_path);
402 uint32_t mask = XCB_CW_EVENT_MASK;
403 uint32_t values[] = { XCB_EVENT_MASK_SUBSTRUCTURE_REDIRECT |
404 XCB_EVENT_MASK_STRUCTURE_NOTIFY | /* when the user adds a screen (e.g. video
405 projector), the root window gets a
407 XCB_EVENT_MASK_POINTER_MOTION |
408 XCB_EVENT_MASK_PROPERTY_CHANGE |
409 XCB_EVENT_MASK_ENTER_WINDOW };
410 xcb_void_cookie_t cookie;
411 cookie = xcb_change_window_attributes_checked(conn, root, mask, values);
412 check_error(conn, cookie, "Another window manager seems to be running");
414 xcb_get_geometry_reply_t *greply = xcb_get_geometry_reply(conn, gcookie, NULL);
415 if (greply == NULL) {
416 ELOG("Could not get geometry of the root window, exiting\n");
419 DLOG("root geometry reply: (%d, %d) %d x %d\n", greply->x, greply->y, greply->width, greply->height);
421 /* Place requests for the atoms we need as soon as possible */
422 #define xmacro(atom) \
423 xcb_intern_atom_cookie_t atom ## _cookie = xcb_intern_atom(conn, 0, strlen(#atom), #atom);
424 #include "atoms.xmacro"
427 /* Initialize the Xlib connection */
428 xlibdpy = xkbdpy = XOpenDisplay(NULL);
430 /* Try to load the X cursors and initialize the XKB extension */
431 if (xlibdpy == NULL) {
432 ELOG("ERROR: XOpenDisplay() failed, disabling libXcursor/XKB support\n");
433 xcursor_supported = false;
434 xkb_supported = false;
435 } else if (fcntl(ConnectionNumber(xlibdpy), F_SETFD, FD_CLOEXEC) == -1) {
436 ELOG("Could not set FD_CLOEXEC on xkbdpy\n");
439 xcursor_load_cursors();
443 /* Set a cursor for the root window (otherwise the root window will show no
444 cursor until the first client is launched). */
445 if (xcursor_supported)
446 xcursor_set_root_cursor(XCURSOR_CURSOR_POINTER);
447 else xcb_set_root_cursor(XCURSOR_CURSOR_POINTER);
451 major = XkbMajorVersion,
452 minor = XkbMinorVersion;
454 if (fcntl(ConnectionNumber(xkbdpy), F_SETFD, FD_CLOEXEC) == -1) {
455 fprintf(stderr, "Could not set FD_CLOEXEC on xkbdpy\n");
460 if (!XkbQueryExtension(xkbdpy,&i1,&xkb_event_base,&errBase,&major,&minor)) {
461 fprintf(stderr, "XKB not supported by X-server\n");
464 /* end of ugliness */
466 if (!XkbSelectEvents(xkbdpy, XkbUseCoreKbd,
467 XkbMapNotifyMask | XkbStateNotifyMask,
468 XkbMapNotifyMask | XkbStateNotifyMask)) {
469 fprintf(stderr, "Could not set XKB event mask\n");
474 /* Setup NetWM atoms */
475 #define xmacro(name) \
477 xcb_intern_atom_reply_t *reply = xcb_intern_atom_reply(conn, name ## _cookie, NULL); \
479 ELOG("Could not get atom " #name "\n"); \
482 A_ ## name = reply->atom; \
485 #include "atoms.xmacro"
488 property_handlers_init();
490 /* Set up the atoms we support */
491 xcb_atom_t supported_atoms[] = {
492 #define xmacro(atom) A_ ## atom,
493 #include "atoms.xmacro"
496 xcb_change_property(conn, XCB_PROP_MODE_REPLACE, root, A__NET_SUPPORTED, XCB_ATOM_ATOM, 32, 16, supported_atoms);
497 /* Set up the window manager’s name */
498 xcb_change_property(conn, XCB_PROP_MODE_REPLACE, root, A__NET_SUPPORTING_WM_CHECK, XCB_ATOM_WINDOW, 32, 1, &root);
499 xcb_change_property(conn, XCB_PROP_MODE_REPLACE, root, A__NET_WM_NAME, A_UTF8_STRING, 8, strlen("i3"), "i3");
501 keysyms = xcb_key_symbols_alloc(conn);
503 xcb_get_numlock_mask(conn);
506 grab_all_keys(conn, false);
508 bool needs_tree_init = true;
510 LOG("Trying to restore the layout from %s...", layout_path);
511 needs_tree_init = !tree_restore(layout_path, greply);
512 if (delete_layout_path)
521 /* Force Xinerama (for drivers which don't support RandR yet, esp. the
522 * nVidia binary graphics driver), when specified either in the config
523 * file or on command-line */
524 if (force_xinerama || config.force_xinerama) {
527 DLOG("Checking for XRandR...\n");
528 randr_init(&randr_base);
531 xcb_query_pointer_reply_t *pointerreply;
532 Output *output = NULL;
533 if (!(pointerreply = xcb_query_pointer_reply(conn, pointercookie, NULL))) {
534 ELOG("Could not query pointer position, using first screen\n");
535 output = get_first_output();
537 DLOG("Pointer at %d, %d\n", pointerreply->root_x, pointerreply->root_y);
538 output = get_output_containing(pointerreply->root_x, pointerreply->root_y);
540 ELOG("ERROR: No screen at (%d, %d), starting on the first screen\n",
541 pointerreply->root_x, pointerreply->root_y);
542 output = get_first_output();
545 con_focus(con_descend_focused(output_get_content(output->con)));
550 /* Create the UNIX domain socket for IPC */
551 int ipc_socket = ipc_create_socket(config.ipc_socket_path);
552 if (ipc_socket == -1) {
553 ELOG("Could not create the IPC socket, IPC disabled\n");
555 free(config.ipc_socket_path);
556 struct ev_io *ipc_io = scalloc(sizeof(struct ev_io));
557 ev_io_init(ipc_io, ipc_new_client, ipc_socket, EV_READ);
558 ev_io_start(main_loop, ipc_io);
561 /* Also handle the UNIX domain sockets passed via socket activation */
562 int fds = sd_listen_fds(1);
564 ELOG("socket activation: Error in sd_listen_fds\n");
566 DLOG("socket activation: no sockets passed\n");
568 for (int fd = SD_LISTEN_FDS_START; fd < (SD_LISTEN_FDS_START + fds); fd++) {
569 DLOG("socket activation: also listening on fd %d\n", fd);
570 struct ev_io *ipc_io = scalloc(sizeof(struct ev_io));
571 ev_io_init(ipc_io, ipc_new_client, fd, EV_READ);
572 ev_io_start(main_loop, ipc_io);
576 /* Set up i3 specific atoms like I3_SOCKET_PATH and I3_CONFIG_PATH */
579 struct ev_io *xcb_watcher = scalloc(sizeof(struct ev_io));
580 struct ev_io *xkb = scalloc(sizeof(struct ev_io));
581 struct ev_check *xcb_check = scalloc(sizeof(struct ev_check));
582 struct ev_prepare *xcb_prepare = scalloc(sizeof(struct ev_prepare));
584 ev_io_init(xcb_watcher, xcb_got_event, xcb_get_file_descriptor(conn), EV_READ);
585 ev_io_start(main_loop, xcb_watcher);
589 ev_io_init(xkb, xkb_got_event, ConnectionNumber(xkbdpy), EV_READ);
590 ev_io_start(main_loop, xkb);
592 /* Flush the buffer so that libev can properly get new events */
596 ev_check_init(xcb_check, xcb_check_cb);
597 ev_check_start(main_loop, xcb_check);
599 ev_prepare_init(xcb_prepare, xcb_prepare_cb);
600 ev_prepare_start(main_loop, xcb_prepare);
604 manage_existing_windows(root);
606 if (!disable_signalhandler)
607 setup_signal_handler();
609 /* Ignore SIGPIPE to survive errors when an IPC client disconnects
610 * while we are sending him a message */
611 signal(SIGPIPE, SIG_IGN);
613 /* Autostarting exec-lines */
615 struct Autostart *exec;
616 TAILQ_FOREACH(exec, &autostarts, autostarts) {
617 LOG("auto-starting %s\n", exec->command);
618 start_application(exec->command);
622 /* Autostarting exec_always-lines */
623 struct Autostart *exec_always;
624 TAILQ_FOREACH(exec_always, &autostarts_always, autostarts_always) {
625 LOG("auto-starting (always!) %s\n", exec_always->command);
626 start_application(exec_always->command);
629 /* Make sure to destroy the event loop to invoke the cleeanup callbacks
630 * when calling exit() */
633 ev_loop(main_loop, 0);