2 * vim:ts=4:sw=4:expandtab
4 * i3 - an improved dynamic tiling window manager
6 * © 2011 Michael Stapelberg and contributors
8 * See file LICENSE for license information.
10 * i3-config-wizard: Program to convert configs using keycodes to configs using
16 #include <sys/types.h>
32 #include <xcb/xcb_aux.h>
33 #include <xcb/xcb_event.h>
34 #include <xcb/xcb_keysyms.h>
37 #include <X11/keysym.h>
39 /* We need SYSCONFDIR for the path to the keycode config template, so raise an
40 * error if it’s not defined for whatever reason */
42 #error "SYSCONFDIR not defined"
45 #define FREE(pointer) do { \
46 if (pointer != NULL) { \
56 enum { STEP_WELCOME, STEP_GENERATE } current_step = STEP_WELCOME;
57 enum { MOD_ALT, MOD_SUPER } modifier = MOD_SUPER;
59 static char *config_path;
60 static xcb_connection_t *conn;
61 static uint32_t font_id;
62 static uint32_t font_bold_id;
63 static char *socket_path;
64 static int font_height;
65 static int font_bold_height;
66 static xcb_window_t win;
67 static xcb_pixmap_t pixmap;
68 static xcb_gcontext_t pixmap_gc;
69 static xcb_key_symbols_t *symbols;
73 char *rewrite_binding(const char *bindingline);
76 #if defined(__APPLE__)
80 * Returns a pointer to a new string which is a duplicate of the
81 * string, but only copies at most n characters.
84 char *strndup(const char *str, size_t n) {
88 for (len = 0; len < n && str[len]; len++)
91 if ((copy = malloc(len + 1)) == NULL)
93 memcpy(copy, str, len);
101 * This function resolves ~ in pathnames.
102 * It may resolve wildcards in the first part of the path, but if no match
103 * or multiple matches are found, it just returns a copy of path as given.
106 static char *resolve_tilde(const char *path) {
107 static glob_t globbuf;
108 char *head, *tail, *result;
110 tail = strchr(path, '/');
111 head = strndup(path, tail ? tail - path : strlen(path));
113 int res = glob(head, GLOB_TILDE, NULL, &globbuf);
115 /* no match, or many wildcard matches are bad */
116 if (res == GLOB_NOMATCH || globbuf.gl_pathc != 1)
117 result = strdup(path);
119 err(1, "glob() failed");
121 head = globbuf.gl_pathv[0];
122 result = calloc(1, strlen(head) + (tail ? strlen(tail) : 0) + 1);
123 strncpy(result, head, strlen(head));
125 strncat(result, tail, strlen(tail));
133 * Try to get the socket path from X11 and return NULL if it doesn’t work.
134 * As i3-msg is a short-running tool, we don’t bother with cleaning up the
135 * connection and leave it up to the operating system on exit.
138 static char *socket_path_from_x11() {
139 xcb_connection_t *conn;
141 if ((conn = xcb_connect(NULL, &screen)) == NULL ||
142 xcb_connection_has_error(conn))
144 xcb_screen_t *root_screen = xcb_aux_get_screen(conn, screen);
145 xcb_window_t root = root_screen->root;
147 xcb_intern_atom_cookie_t atom_cookie;
148 xcb_intern_atom_reply_t *atom_reply;
150 atom_cookie = xcb_intern_atom(conn, 0, strlen("I3_SOCKET_PATH"), "I3_SOCKET_PATH");
151 atom_reply = xcb_intern_atom_reply(conn, atom_cookie, NULL);
152 if (atom_reply == NULL)
155 xcb_get_property_cookie_t prop_cookie;
156 xcb_get_property_reply_t *prop_reply;
157 prop_cookie = xcb_get_property_unchecked(conn, false, root, atom_reply->atom,
158 XCB_GET_PROPERTY_TYPE_ANY, 0, PATH_MAX);
159 prop_reply = xcb_get_property_reply(conn, prop_cookie, NULL);
160 if (prop_reply == NULL || xcb_get_property_value_length(prop_reply) == 0)
162 if (asprintf(&socket_path, "%.*s", xcb_get_property_value_length(prop_reply),
163 (char*)xcb_get_property_value(prop_reply)) == -1)
169 * Handles expose events, that is, draws the window contents.
172 static int handle_expose() {
173 /* re-draw the background */
174 xcb_rectangle_t border = {0, 0, 300, (15*font_height) + 8};
175 xcb_change_gc_single(conn, pixmap_gc, XCB_GC_FOREGROUND, get_colorpixel(conn, "#000000"));
176 xcb_poly_fill_rectangle(conn, pixmap, pixmap_gc, 1, &border);
178 xcb_change_gc_single(conn, pixmap_gc, XCB_GC_FONT, font_id);
180 #define txt(x, row, text) xcb_image_text_8(conn, strlen(text), pixmap, pixmap_gc, x, (row * font_height) + 2, text)
182 if (current_step == STEP_WELCOME) {
183 /* restore font color */
184 xcb_change_gc_single(conn, pixmap_gc, XCB_GC_FOREGROUND, get_colorpixel(conn, "#FFFFFF"));
186 txt(10, 2, "You have not configured i3 yet.");
187 txt(10, 3, "Do you want me to generate ~/.i3/config?");
188 txt(85, 5, "Yes, generate ~/.i3/config");
189 txt(85, 7, "No, I will use the defaults");
192 xcb_change_gc_single(conn, pixmap_gc, XCB_GC_FOREGROUND, get_colorpixel(conn, "#00FF00"));
193 txt(25, 5, "<Enter>");
196 xcb_change_gc_single(conn, pixmap_gc, XCB_GC_FOREGROUND, get_colorpixel(conn, "#FF0000"));
200 if (current_step == STEP_GENERATE) {
201 xcb_change_gc_single(conn, pixmap_gc, XCB_GC_FOREGROUND, get_colorpixel(conn, "#FFFFFF"));
203 txt(10, 2, "Please choose either:");
204 txt(85, 4, "Win as default modifier");
205 txt(85, 5, "Alt as default modifier");
206 txt(10, 7, "Afterwards, press");
207 txt(85, 9, "to write ~/.i3/config");
208 txt(85, 10, "to abort");
210 /* the not-selected modifier */
211 if (modifier == MOD_SUPER)
213 else txt(31, 4, "<Win>");
215 /* the selected modifier */
216 xcb_change_gc_single(conn, pixmap_gc, XCB_GC_FONT, font_bold_id);
217 if (modifier == MOD_SUPER)
219 else txt(31, 5, "<Alt>");
222 uint32_t mask = XCB_GC_FOREGROUND | XCB_GC_FONT;
223 uint32_t values[] = { get_colorpixel(conn, "#00FF00"), font_id };
224 xcb_change_gc(conn, pixmap_gc, mask, values);
226 txt(25, 9, "<Enter>");
229 xcb_change_gc_single(conn, pixmap_gc, XCB_GC_FOREGROUND, get_colorpixel(conn, "#FF0000"));
230 txt(31, 10, "<ESC>");
233 /* Copy the contents of the pixmap to the real window */
234 xcb_copy_area(conn, pixmap, win, pixmap_gc, 0, 0, 0, 0, /* */ 500, 500);
240 static int handle_key_press(void *ignored, xcb_connection_t *conn, xcb_key_press_event_t *event) {
241 printf("Keypress %d, state raw = %d\n", event->detail, event->state);
243 /* Remove the numlock bit, all other bits are modifiers we can bind to */
244 uint16_t state_filtered = event->state & ~(xcb_numlock_mask | XCB_MOD_MASK_LOCK);
245 /* Only use the lower 8 bits of the state (modifier masks) so that mouse
246 * button masks are filtered out */
247 state_filtered &= 0xFF;
249 xcb_keysym_t sym = xcb_key_press_lookup_keysym(symbols, event, state_filtered);
251 printf("sym = %c (%d)\n", sym, sym);
253 if (sym == XK_Return || sym == XK_KP_Enter) {
254 if (current_step == STEP_WELCOME) {
255 current_step = STEP_GENERATE;
256 /* Set window title */
257 xcb_change_property(conn,
258 XCB_PROP_MODE_REPLACE,
263 strlen("i3: generate config"),
264 "i3: generate config");
270 /* cancel any time */
271 if (sym == XK_Escape)
277 if (sym == XK_Super_L)
278 modifier = MOD_SUPER;
285 * Handle button presses to make clicking on "<win>" and "<alt>" work
288 static void handle_button_press(xcb_button_press_event_t* event) {
289 if (current_step != STEP_GENERATE)
292 if (event->event_x >= 32 && event->event_x <= 68 &&
293 event->event_y >= 45 && event->event_y <= 54) {
294 modifier = MOD_SUPER;
298 if (event->event_x >= 32 && event->event_x <= 68 &&
299 event->event_y >= 56 && event->event_y <= 70) {
308 * Creates the config file and tells i3 to reload.
311 static void finish() {
312 printf("creating \"%s\"...\n", config_path);
314 if (!(dpy = XOpenDisplay(NULL)))
315 errx(1, "Could not connect to X11");
317 FILE *kc_config = fopen(SYSCONFDIR "/i3/config.keycodes", "r");
318 if (kc_config == NULL)
319 err(1, "Could not open input file \"%s\"", SYSCONFDIR "/i3/config.keycodes");
321 FILE *ks_config = fopen(config_path, "w");
322 if (ks_config == NULL)
323 err(1, "Could not open output config file \"%s\"", config_path);
327 #if !defined(__APPLE__)
330 bool head_of_file = true;
332 /* write a header about auto-generation to the output file */
333 fputs("# This file has been auto-generated by i3-config-wizard(1).\n", ks_config);
334 fputs("# It will not be overwritten, so edit it as you like.\n", ks_config);
335 fputs("#\n", ks_config);
336 fputs("# Should you change your keyboard layout somewhen, delete\n", ks_config);
337 fputs("# this file and re-run i3-config-wizard(1).\n", ks_config);
338 fputs("#\n", ks_config);
340 #if defined(__APPLE__)
341 while ((line = fgetln(kc_config, &len)) != NULL) {
343 while ((read = getline(&line, &len, kc_config)) != -1) {
345 /* skip the warning block at the beginning of the input file */
347 strncmp("# WARNING", line, strlen("# WARNING")) == 0)
350 head_of_file = false;
352 /* Skip leading whitespace */
354 while (isspace(*walk) && walk < (line + len))
357 /* Set the modifier the user chose */
358 if (strncmp(walk, "set $mod ", strlen("set $mod ")) == 0) {
359 if (modifier == MOD_ALT)
360 fputs("set $mod Mod1\n", ks_config);
361 else fputs("set $mod Mod4\n", ks_config);
365 /* Check for 'bindcode'. If it’s not a bindcode line, we
366 * just copy it to the output file */
367 if (strncmp(walk, "bindcode", strlen("bindcode")) != 0) {
368 fputs(line, ks_config);
371 char *result = rewrite_binding(walk);
372 fputs(result, ks_config);
376 /* sync to do our best in order to have the file really stored on disk */
378 fsync(fileno(ks_config));
384 /* tell i3 to reload the config file */
385 int sockfd = connect_ipc(socket_path);
386 ipc_send_message(sockfd, strlen("reload"), 0, (uint8_t*)"reload");
392 int main(int argc, char *argv[]) {
393 config_path = resolve_tilde("~/.i3/config");
394 socket_path = getenv("I3SOCK");
395 char *pattern = "-misc-fixed-medium-r-normal--13-120-75-75-C-70-iso10646-1";
396 char *patternbold = "-misc-fixed-bold-r-normal--13-120-75-75-C-70-iso10646-1";
397 int o, option_index = 0;
399 static struct option long_options[] = {
400 {"socket", required_argument, 0, 's'},
401 {"version", no_argument, 0, 'v'},
402 {"limit", required_argument, 0, 'l'},
403 {"prompt", required_argument, 0, 'P'},
404 {"prefix", required_argument, 0, 'p'},
405 {"font", required_argument, 0, 'f'},
406 {"help", no_argument, 0, 'h'},
410 char *options_string = "s:vh";
412 while ((o = getopt_long(argc, argv, options_string, long_options, &option_index)) != -1) {
416 socket_path = strdup(optarg);
419 printf("i3-config-wizard " I3_VERSION "\n");
422 printf("i3-config-wizard " I3_VERSION "\n");
423 printf("i3-config-wizard [-s <socket>] [-v]\n");
428 /* Check if the destination config file does not exist but the path is
429 * writable. If not, exit now, this program is not useful in that case. */
431 if (stat(config_path, &stbuf) == 0) {
432 printf("The config file \"%s\" already exists. Exiting.\n", config_path);
436 /* Create ~/.i3 if it does not yet exist */
437 char *config_dir = resolve_tilde("~/.i3");
438 if (stat(config_dir, &stbuf) != 0)
439 if (mkdir(config_dir, 0755) == -1)
440 err(1, "mkdir(%s) failed", config_dir);
444 if ((fd = open(config_path, O_CREAT | O_RDWR, 0644)) == -1) {
445 printf("Cannot open file \"%s\" for writing: %s. Exiting.\n", config_path, strerror(errno));
451 if (socket_path == NULL)
452 socket_path = socket_path_from_x11();
454 if (socket_path == NULL)
455 socket_path = "/tmp/i3-ipc.sock";
458 if ((conn = xcb_connect(NULL, &screens)) == NULL ||
459 xcb_connection_has_error(conn))
460 errx(1, "Cannot open display\n");
462 /* Place requests for the atoms we need as soon as possible */
463 #define xmacro(atom) \
464 xcb_intern_atom_cookie_t atom ## _cookie = xcb_intern_atom(conn, 0, strlen(#atom), #atom);
465 #include "atoms.xmacro"
468 xcb_screen_t *root_screen = xcb_aux_get_screen(conn, screens);
469 root = root_screen->root;
471 xcb_get_numlock_mask(conn);
473 symbols = xcb_key_symbols_alloc(conn);
475 font_id = get_font_id(conn, pattern, &font_height);
476 font_bold_id = get_font_id(conn, patternbold, &font_bold_height);
478 /* Open an input window */
479 win = open_input_window(conn, 300, 205);
481 /* Setup NetWM atoms */
482 #define xmacro(name) \
484 xcb_intern_atom_reply_t *reply = xcb_intern_atom_reply(conn, name ## _cookie, NULL); \
486 errx(EXIT_FAILURE, "Could not get atom " # name "\n"); \
488 A_ ## name = reply->atom; \
491 #include "atoms.xmacro"
495 xcb_change_property(conn,
496 XCB_PROP_MODE_REPLACE,
498 A__NET_WM_WINDOW_TYPE,
502 (unsigned char*) &A__NET_WM_WINDOW_TYPE_DIALOG);
504 /* Set window title */
505 xcb_change_property(conn,
506 XCB_PROP_MODE_REPLACE,
511 strlen("i3: first configuration"),
512 "i3: first configuration");
515 pixmap = xcb_generate_id(conn);
516 pixmap_gc = xcb_generate_id(conn);
517 xcb_create_pixmap(conn, root_screen->root_depth, pixmap, win, 500, 500);
518 xcb_create_gc(conn, pixmap_gc, pixmap, 0, 0);
520 /* Grab the keyboard to get all input */
523 /* Try (repeatedly, if necessary) to grab the keyboard. We might not
524 * get the keyboard at the first attempt because of the keybinding
525 * still being active when started via a wm’s keybinding. */
526 xcb_grab_keyboard_cookie_t cookie;
527 xcb_grab_keyboard_reply_t *reply = NULL;
530 while ((reply == NULL || reply->status != XCB_GRAB_STATUS_SUCCESS) && (count++ < 500)) {
531 cookie = xcb_grab_keyboard(conn, false, win, XCB_CURRENT_TIME, XCB_GRAB_MODE_ASYNC, XCB_GRAB_MODE_ASYNC);
532 reply = xcb_grab_keyboard_reply(conn, cookie, NULL);
536 if (reply->status != XCB_GRAB_STATUS_SUCCESS) {
537 fprintf(stderr, "Could not grab keyboard, status = %d\n", reply->status);
543 xcb_generic_event_t *event;
544 while ((event = xcb_wait_for_event(conn)) != NULL) {
545 if (event->response_type == 0) {
546 fprintf(stderr, "X11 Error received! sequence %x\n", event->sequence);
550 /* Strip off the highest bit (set if the event is generated) */
551 int type = (event->response_type & 0x7F);
555 handle_key_press(NULL, conn, (xcb_key_press_event_t*)event);
558 /* TODO: handle mappingnotify */
560 case XCB_BUTTON_PRESS:
561 handle_button_press((xcb_button_press_event_t*)event);