2 * vim:ts=4:sw=4:expandtab
4 * i3 - an improved dynamic tiling window manager
5 * © 2009-2011 Michael Stapelberg and contributors (see also: LICENSE)
7 * i3-config-wizard: Program to convert configs using keycodes to configs using
13 #include <sys/types.h>
29 #include <xcb/xcb_aux.h>
30 #include <xcb/xcb_event.h>
31 #include <xcb/xcb_keysyms.h>
34 #include <X11/keysym.h>
36 /* We need SYSCONFDIR for the path to the keycode config template, so raise an
37 * error if it’s not defined for whatever reason */
39 #error "SYSCONFDIR not defined"
42 #define FREE(pointer) do { \
43 if (pointer != NULL) { \
53 enum { STEP_WELCOME, STEP_GENERATE } current_step = STEP_WELCOME;
54 enum { MOD_Mod1, MOD_Mod4 } modifier = MOD_Mod4;
56 static char *config_path;
57 static uint32_t xcb_numlock_mask;
58 xcb_connection_t *conn;
59 static xcb_get_modifier_mapping_reply_t *modmap_reply;
61 static i3Font bold_font;
62 static char *socket_path;
63 static xcb_window_t win;
64 static xcb_pixmap_t pixmap;
65 static xcb_gcontext_t pixmap_gc;
66 static xcb_key_symbols_t *symbols;
70 char *rewrite_binding(const char *bindingline);
74 * This function resolves ~ in pathnames.
75 * It may resolve wildcards in the first part of the path, but if no match
76 * or multiple matches are found, it just returns a copy of path as given.
79 static char *resolve_tilde(const char *path) {
80 static glob_t globbuf;
81 char *head, *tail, *result;
83 tail = strchr(path, '/');
84 head = strndup(path, tail ? tail - path : strlen(path));
86 int res = glob(head, GLOB_TILDE, NULL, &globbuf);
88 /* no match, or many wildcard matches are bad */
89 if (res == GLOB_NOMATCH || globbuf.gl_pathc != 1)
90 result = strdup(path);
92 err(1, "glob() failed");
94 head = globbuf.gl_pathv[0];
95 result = calloc(1, strlen(head) + (tail ? strlen(tail) : 0) + 1);
96 strncpy(result, head, strlen(head));
98 strncat(result, tail, strlen(tail));
106 * Handles expose events, that is, draws the window contents.
109 static int handle_expose() {
110 /* re-draw the background */
111 xcb_rectangle_t border = {0, 0, 300, (15 * font.height) + 8};
112 xcb_change_gc(conn, pixmap_gc, XCB_GC_FOREGROUND, (uint32_t[]){ get_colorpixel("#000000") });
113 xcb_poly_fill_rectangle(conn, pixmap, pixmap_gc, 1, &border);
115 xcb_change_gc(conn, pixmap_gc, XCB_GC_FONT, (uint32_t[]){ font.id });
117 #define txt(x, row, text) xcb_image_text_8(conn, strlen(text), pixmap, pixmap_gc, x, (row * font.height) + 2, text)
119 if (current_step == STEP_WELCOME) {
120 /* restore font color */
121 xcb_change_gc(conn, pixmap_gc, XCB_GC_FOREGROUND, (uint32_t[]){ get_colorpixel("#FFFFFF") });
123 txt(10, 2, "You have not configured i3 yet.");
124 txt(10, 3, "Do you want me to generate ~/.i3/config?");
125 txt(85, 5, "Yes, generate ~/.i3/config");
126 txt(85, 7, "No, I will use the defaults");
129 xcb_change_gc(conn, pixmap_gc, XCB_GC_FOREGROUND, (uint32_t[]){ get_colorpixel("#00FF00") });
130 txt(25, 5, "<Enter>");
133 xcb_change_gc(conn, pixmap_gc, XCB_GC_FOREGROUND, (uint32_t[]){ get_colorpixel("#FF0000") });
137 if (current_step == STEP_GENERATE) {
138 xcb_change_gc(conn, pixmap_gc, XCB_GC_FOREGROUND, (uint32_t[]){ get_colorpixel("#FFFFFF") });
140 txt(10, 2, "Please choose either:");
141 txt(85, 4, "Win as default modifier");
142 txt(85, 5, "Alt as default modifier");
143 txt(10, 7, "Afterwards, press");
144 txt(85, 9, "to write ~/.i3/config");
145 txt(85, 10, "to abort");
147 /* the not-selected modifier */
148 if (modifier == MOD_Mod4)
150 else txt(31, 4, "<Win>");
152 /* the selected modifier */
153 xcb_change_gc(conn, pixmap_gc, XCB_GC_FONT, (uint32_t[]){ bold_font.id });
154 if (modifier == MOD_Mod4)
156 else txt(31, 5, "<Alt>");
159 xcb_change_gc(conn, pixmap_gc, XCB_GC_FOREGROUND | XCB_GC_FONT,
160 (uint32_t[]) { get_colorpixel("#00FF00"), font.id });
162 txt(25, 9, "<Enter>");
165 xcb_change_gc(conn, pixmap_gc, XCB_GC_FOREGROUND, (uint32_t[]){ get_colorpixel("#FF0000") });
166 txt(31, 10, "<ESC>");
169 /* Copy the contents of the pixmap to the real window */
170 xcb_copy_area(conn, pixmap, win, pixmap_gc, 0, 0, 0, 0, /* */ 500, 500);
176 static int handle_key_press(void *ignored, xcb_connection_t *conn, xcb_key_press_event_t *event) {
177 printf("Keypress %d, state raw = %d\n", event->detail, event->state);
179 /* Remove the numlock bit, all other bits are modifiers we can bind to */
180 uint16_t state_filtered = event->state & ~(xcb_numlock_mask | XCB_MOD_MASK_LOCK);
181 /* Only use the lower 8 bits of the state (modifier masks) so that mouse
182 * button masks are filtered out */
183 state_filtered &= 0xFF;
185 xcb_keysym_t sym = xcb_key_press_lookup_keysym(symbols, event, state_filtered);
187 printf("sym = %c (%d)\n", sym, sym);
189 if (sym == XK_Return || sym == XK_KP_Enter) {
190 if (current_step == STEP_WELCOME) {
191 current_step = STEP_GENERATE;
192 /* Set window title */
193 xcb_change_property(conn,
194 XCB_PROP_MODE_REPLACE,
199 strlen("i3: generate config"),
200 "i3: generate config");
206 /* cancel any time */
207 if (sym == XK_Escape)
210 /* Check if this is Mod1 or Mod4. The modmap contains Shift, Lock, Control,
211 * Mod1, Mod2, Mod3, Mod4, Mod5 (in that order) */
212 xcb_keycode_t *modmap = xcb_get_modifier_mapping_keycodes(modmap_reply);
215 for (int i = 0; i < modmap_reply->keycodes_per_modifier; i++) {
216 xcb_keycode_t code = modmap[(mask * modmap_reply->keycodes_per_modifier) + i];
217 if (code == XCB_NONE)
219 printf("Modifier keycode for Mod1: 0x%02x\n", code);
220 if (code == event->detail) {
222 printf("This is Mod1!\n");
228 for (int i = 0; i < modmap_reply->keycodes_per_modifier; i++) {
229 xcb_keycode_t code = modmap[(mask * modmap_reply->keycodes_per_modifier) + i];
230 if (code == XCB_NONE)
232 printf("Modifier keycode for Mod4: 0x%02x\n", code);
233 if (code == event->detail) {
235 printf("This is Mod4!\n");
244 * Handle button presses to make clicking on "<win>" and "<alt>" work
247 static void handle_button_press(xcb_button_press_event_t* event) {
248 if (current_step != STEP_GENERATE)
251 if (event->event_x >= 32 && event->event_x <= 68 &&
252 event->event_y >= 45 && event->event_y <= 54) {
257 if (event->event_x >= 32 && event->event_x <= 68 &&
258 event->event_y >= 56 && event->event_y <= 70) {
267 * Creates the config file and tells i3 to reload.
270 static void finish() {
271 printf("creating \"%s\"...\n", config_path);
273 if (!(dpy = XOpenDisplay(NULL)))
274 errx(1, "Could not connect to X11");
276 FILE *kc_config = fopen(SYSCONFDIR "/i3/config.keycodes", "r");
277 if (kc_config == NULL)
278 err(1, "Could not open input file \"%s\"", SYSCONFDIR "/i3/config.keycodes");
280 FILE *ks_config = fopen(config_path, "w");
281 if (ks_config == NULL)
282 err(1, "Could not open output config file \"%s\"", config_path);
286 #if !defined(__APPLE__)
289 bool head_of_file = true;
291 /* write a header about auto-generation to the output file */
292 fputs("# This file has been auto-generated by i3-config-wizard(1).\n", ks_config);
293 fputs("# It will not be overwritten, so edit it as you like.\n", ks_config);
294 fputs("#\n", ks_config);
295 fputs("# Should you change your keyboard layout somewhen, delete\n", ks_config);
296 fputs("# this file and re-run i3-config-wizard(1).\n", ks_config);
297 fputs("#\n", ks_config);
299 #if defined(__APPLE__)
300 while ((line = fgetln(kc_config, &len)) != NULL) {
302 while ((read = getline(&line, &len, kc_config)) != -1) {
304 /* skip the warning block at the beginning of the input file */
306 strncmp("# WARNING", line, strlen("# WARNING")) == 0)
309 head_of_file = false;
311 /* Skip leading whitespace */
313 while (isspace(*walk) && walk < (line + len))
316 /* Set the modifier the user chose */
317 if (strncmp(walk, "set $mod ", strlen("set $mod ")) == 0) {
318 if (modifier == MOD_Mod1)
319 fputs("set $mod Mod1\n", ks_config);
320 else fputs("set $mod Mod4\n", ks_config);
324 /* Check for 'bindcode'. If it’s not a bindcode line, we
325 * just copy it to the output file */
326 if (strncmp(walk, "bindcode", strlen("bindcode")) != 0) {
327 fputs(line, ks_config);
330 char *result = rewrite_binding(walk);
331 fputs(result, ks_config);
335 /* sync to do our best in order to have the file really stored on disk */
337 fsync(fileno(ks_config));
343 /* tell i3 to reload the config file */
344 int sockfd = ipc_connect(socket_path);
345 ipc_send_message(sockfd, strlen("reload"), 0, (uint8_t*)"reload");
351 int main(int argc, char *argv[]) {
352 config_path = resolve_tilde("~/.i3/config");
353 socket_path = getenv("I3SOCK");
354 char *pattern = "-misc-fixed-medium-r-normal--13-120-75-75-C-70-iso10646-1";
355 char *patternbold = "-misc-fixed-bold-r-normal--13-120-75-75-C-70-iso10646-1";
356 int o, option_index = 0;
358 static struct option long_options[] = {
359 {"socket", required_argument, 0, 's'},
360 {"version", no_argument, 0, 'v'},
361 {"limit", required_argument, 0, 'l'},
362 {"prompt", required_argument, 0, 'P'},
363 {"prefix", required_argument, 0, 'p'},
364 {"font", required_argument, 0, 'f'},
365 {"help", no_argument, 0, 'h'},
369 char *options_string = "s:vh";
371 while ((o = getopt_long(argc, argv, options_string, long_options, &option_index)) != -1) {
375 socket_path = strdup(optarg);
378 printf("i3-config-wizard " I3_VERSION "\n");
381 printf("i3-config-wizard " I3_VERSION "\n");
382 printf("i3-config-wizard [-s <socket>] [-v]\n");
387 /* Check if the destination config file does not exist but the path is
388 * writable. If not, exit now, this program is not useful in that case. */
390 if (stat(config_path, &stbuf) == 0) {
391 printf("The config file \"%s\" already exists. Exiting.\n", config_path);
395 /* Create ~/.i3 if it does not yet exist */
396 char *config_dir = resolve_tilde("~/.i3");
397 if (stat(config_dir, &stbuf) != 0)
398 if (mkdir(config_dir, 0755) == -1)
399 err(1, "mkdir(%s) failed", config_dir);
403 if ((fd = open(config_path, O_CREAT | O_RDWR, 0644)) == -1) {
404 printf("Cannot open file \"%s\" for writing: %s. Exiting.\n", config_path, strerror(errno));
410 if (socket_path == NULL)
411 socket_path = socket_path_from_x11();
413 if (socket_path == NULL)
414 socket_path = "/tmp/i3-ipc.sock";
417 if ((conn = xcb_connect(NULL, &screens)) == NULL ||
418 xcb_connection_has_error(conn))
419 errx(1, "Cannot open display\n");
421 xcb_get_modifier_mapping_cookie_t modmap_cookie;
422 modmap_cookie = xcb_get_modifier_mapping(conn);
423 symbols = xcb_key_symbols_alloc(conn);
425 /* Place requests for the atoms we need as soon as possible */
426 #define xmacro(atom) \
427 xcb_intern_atom_cookie_t atom ## _cookie = xcb_intern_atom(conn, 0, strlen(#atom), #atom);
428 #include "atoms.xmacro"
431 xcb_screen_t *root_screen = xcb_aux_get_screen(conn, screens);
432 root = root_screen->root;
434 if (!(modmap_reply = xcb_get_modifier_mapping_reply(conn, modmap_cookie, NULL)))
435 errx(EXIT_FAILURE, "Could not get modifier mapping\n");
437 xcb_numlock_mask = get_mod_mask_for(XCB_NUM_LOCK, symbols, modmap_reply);
439 font = load_font(pattern, true);
440 bold_font = load_font(patternbold, true);
442 /* Open an input window */
443 win = xcb_generate_id(conn);
446 XCB_COPY_FROM_PARENT,
447 win, /* the window id */
448 root, /* parent == root */
449 490, 297, 300, 205, /* dimensions */
450 0, /* X11 border = 0, we draw our own */
451 XCB_WINDOW_CLASS_INPUT_OUTPUT,
452 XCB_WINDOW_CLASS_COPY_FROM_PARENT, /* copy visual from parent */
453 XCB_CW_BACK_PIXEL | XCB_CW_EVENT_MASK,
455 0, /* back pixel: black */
456 XCB_EVENT_MASK_EXPOSURE |
457 XCB_EVENT_MASK_BUTTON_PRESS
460 /* Map the window (make it visible) */
461 xcb_map_window(conn, win);
463 /* Setup NetWM atoms */
464 #define xmacro(name) \
466 xcb_intern_atom_reply_t *reply = xcb_intern_atom_reply(conn, name ## _cookie, NULL); \
468 errx(EXIT_FAILURE, "Could not get atom " # name "\n"); \
470 A_ ## name = reply->atom; \
473 #include "atoms.xmacro"
477 xcb_change_property(conn,
478 XCB_PROP_MODE_REPLACE,
480 A__NET_WM_WINDOW_TYPE,
484 (unsigned char*) &A__NET_WM_WINDOW_TYPE_DIALOG);
486 /* Set window title */
487 xcb_change_property(conn,
488 XCB_PROP_MODE_REPLACE,
493 strlen("i3: first configuration"),
494 "i3: first configuration");
497 pixmap = xcb_generate_id(conn);
498 pixmap_gc = xcb_generate_id(conn);
499 xcb_create_pixmap(conn, root_screen->root_depth, pixmap, win, 500, 500);
500 xcb_create_gc(conn, pixmap_gc, pixmap, 0, 0);
502 /* Grab the keyboard to get all input */
505 /* Try (repeatedly, if necessary) to grab the keyboard. We might not
506 * get the keyboard at the first attempt because of the keybinding
507 * still being active when started via a wm’s keybinding. */
508 xcb_grab_keyboard_cookie_t cookie;
509 xcb_grab_keyboard_reply_t *reply = NULL;
512 while ((reply == NULL || reply->status != XCB_GRAB_STATUS_SUCCESS) && (count++ < 500)) {
513 cookie = xcb_grab_keyboard(conn, false, win, XCB_CURRENT_TIME, XCB_GRAB_MODE_ASYNC, XCB_GRAB_MODE_ASYNC);
514 reply = xcb_grab_keyboard_reply(conn, cookie, NULL);
518 if (reply->status != XCB_GRAB_STATUS_SUCCESS) {
519 fprintf(stderr, "Could not grab keyboard, status = %d\n", reply->status);
525 xcb_generic_event_t *event;
526 while ((event = xcb_wait_for_event(conn)) != NULL) {
527 if (event->response_type == 0) {
528 fprintf(stderr, "X11 Error received! sequence %x\n", event->sequence);
532 /* Strip off the highest bit (set if the event is generated) */
533 int type = (event->response_type & 0x7F);
537 handle_key_press(NULL, conn, (xcb_key_press_event_t*)event);
540 /* TODO: handle mappingnotify */
542 case XCB_BUTTON_PRESS:
543 handle_button_press((xcb_button_press_event_t*)event);