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_Mod1, MOD_Mod4 } modifier = MOD_Mod4;
59 static char *config_path;
60 static xcb_connection_t *conn;
61 static xcb_get_modifier_mapping_reply_t *modmap_reply;
62 static uint32_t font_id;
63 static uint32_t font_bold_id;
64 static char *socket_path;
65 static int font_height;
66 static int font_bold_height;
67 static xcb_window_t win;
68 static xcb_pixmap_t pixmap;
69 static xcb_gcontext_t pixmap_gc;
70 static xcb_key_symbols_t *symbols;
74 char *rewrite_binding(const char *bindingline);
77 #if defined(__APPLE__)
81 * Returns a pointer to a new string which is a duplicate of the
82 * string, but only copies at most n characters.
85 char *strndup(const char *str, size_t n) {
89 for (len = 0; len < n && str[len]; len++)
92 if ((copy = malloc(len + 1)) == NULL)
94 memcpy(copy, str, len);
102 * This function resolves ~ in pathnames.
103 * It may resolve wildcards in the first part of the path, but if no match
104 * or multiple matches are found, it just returns a copy of path as given.
107 static char *resolve_tilde(const char *path) {
108 static glob_t globbuf;
109 char *head, *tail, *result;
111 tail = strchr(path, '/');
112 head = strndup(path, tail ? tail - path : strlen(path));
114 int res = glob(head, GLOB_TILDE, NULL, &globbuf);
116 /* no match, or many wildcard matches are bad */
117 if (res == GLOB_NOMATCH || globbuf.gl_pathc != 1)
118 result = strdup(path);
120 err(1, "glob() failed");
122 head = globbuf.gl_pathv[0];
123 result = calloc(1, strlen(head) + (tail ? strlen(tail) : 0) + 1);
124 strncpy(result, head, strlen(head));
126 strncat(result, tail, strlen(tail));
134 * Handles expose events, that is, draws the window contents.
137 static int handle_expose() {
138 /* re-draw the background */
139 xcb_rectangle_t border = {0, 0, 300, (15*font_height) + 8};
140 xcb_change_gc_single(conn, pixmap_gc, XCB_GC_FOREGROUND, get_colorpixel("#000000"));
141 xcb_poly_fill_rectangle(conn, pixmap, pixmap_gc, 1, &border);
143 xcb_change_gc_single(conn, pixmap_gc, XCB_GC_FONT, font_id);
145 #define txt(x, row, text) xcb_image_text_8(conn, strlen(text), pixmap, pixmap_gc, x, (row * font_height) + 2, text)
147 if (current_step == STEP_WELCOME) {
148 /* restore font color */
149 xcb_change_gc_single(conn, pixmap_gc, XCB_GC_FOREGROUND, get_colorpixel("#FFFFFF"));
151 txt(10, 2, "You have not configured i3 yet.");
152 txt(10, 3, "Do you want me to generate ~/.i3/config?");
153 txt(85, 5, "Yes, generate ~/.i3/config");
154 txt(85, 7, "No, I will use the defaults");
157 xcb_change_gc_single(conn, pixmap_gc, XCB_GC_FOREGROUND, get_colorpixel("#00FF00"));
158 txt(25, 5, "<Enter>");
161 xcb_change_gc_single(conn, pixmap_gc, XCB_GC_FOREGROUND, get_colorpixel("#FF0000"));
165 if (current_step == STEP_GENERATE) {
166 xcb_change_gc_single(conn, pixmap_gc, XCB_GC_FOREGROUND, get_colorpixel("#FFFFFF"));
168 txt(10, 2, "Please choose either:");
169 txt(85, 4, "Win as default modifier");
170 txt(85, 5, "Alt as default modifier");
171 txt(10, 7, "Afterwards, press");
172 txt(85, 9, "to write ~/.i3/config");
173 txt(85, 10, "to abort");
175 /* the not-selected modifier */
176 if (modifier == MOD_Mod4)
178 else txt(31, 4, "<Win>");
180 /* the selected modifier */
181 xcb_change_gc_single(conn, pixmap_gc, XCB_GC_FONT, font_bold_id);
182 if (modifier == MOD_Mod4)
184 else txt(31, 5, "<Alt>");
187 uint32_t mask = XCB_GC_FOREGROUND | XCB_GC_FONT;
188 uint32_t values[] = { get_colorpixel("#00FF00"), font_id };
189 xcb_change_gc(conn, pixmap_gc, mask, values);
191 txt(25, 9, "<Enter>");
194 xcb_change_gc_single(conn, pixmap_gc, XCB_GC_FOREGROUND, get_colorpixel("#FF0000"));
195 txt(31, 10, "<ESC>");
198 /* Copy the contents of the pixmap to the real window */
199 xcb_copy_area(conn, pixmap, win, pixmap_gc, 0, 0, 0, 0, /* */ 500, 500);
205 static int handle_key_press(void *ignored, xcb_connection_t *conn, xcb_key_press_event_t *event) {
206 printf("Keypress %d, state raw = %d\n", event->detail, event->state);
208 /* Remove the numlock bit, all other bits are modifiers we can bind to */
209 uint16_t state_filtered = event->state & ~(xcb_numlock_mask | XCB_MOD_MASK_LOCK);
210 /* Only use the lower 8 bits of the state (modifier masks) so that mouse
211 * button masks are filtered out */
212 state_filtered &= 0xFF;
214 xcb_keysym_t sym = xcb_key_press_lookup_keysym(symbols, event, state_filtered);
216 printf("sym = %c (%d)\n", sym, sym);
218 if (sym == XK_Return || sym == XK_KP_Enter) {
219 if (current_step == STEP_WELCOME) {
220 current_step = STEP_GENERATE;
221 /* Set window title */
222 xcb_change_property(conn,
223 XCB_PROP_MODE_REPLACE,
228 strlen("i3: generate config"),
229 "i3: generate config");
235 /* cancel any time */
236 if (sym == XK_Escape)
239 /* Check if this is Mod1 or Mod4. The modmap contains Shift, Lock, Control,
240 * Mod1, Mod2, Mod3, Mod4, Mod5 (in that order) */
241 xcb_keycode_t *modmap = xcb_get_modifier_mapping_keycodes(modmap_reply);
244 for (int i = 0; i < modmap_reply->keycodes_per_modifier; i++) {
245 xcb_keycode_t code = modmap[(mask * modmap_reply->keycodes_per_modifier) + i];
246 if (code == XCB_NONE)
248 printf("Modifier keycode for Mod1: 0x%02x\n", code);
249 if (code == event->detail) {
251 printf("This is Mod1!\n");
257 for (int i = 0; i < modmap_reply->keycodes_per_modifier; i++) {
258 xcb_keycode_t code = modmap[(mask * modmap_reply->keycodes_per_modifier) + i];
259 if (code == XCB_NONE)
261 printf("Modifier keycode for Mod4: 0x%02x\n", code);
262 if (code == event->detail) {
264 printf("This is Mod4!\n");
273 * Handle button presses to make clicking on "<win>" and "<alt>" work
276 static void handle_button_press(xcb_button_press_event_t* event) {
277 if (current_step != STEP_GENERATE)
280 if (event->event_x >= 32 && event->event_x <= 68 &&
281 event->event_y >= 45 && event->event_y <= 54) {
286 if (event->event_x >= 32 && event->event_x <= 68 &&
287 event->event_y >= 56 && event->event_y <= 70) {
296 * Creates the config file and tells i3 to reload.
299 static void finish() {
300 printf("creating \"%s\"...\n", config_path);
302 if (!(dpy = XOpenDisplay(NULL)))
303 errx(1, "Could not connect to X11");
305 FILE *kc_config = fopen(SYSCONFDIR "/i3/config.keycodes", "r");
306 if (kc_config == NULL)
307 err(1, "Could not open input file \"%s\"", SYSCONFDIR "/i3/config.keycodes");
309 FILE *ks_config = fopen(config_path, "w");
310 if (ks_config == NULL)
311 err(1, "Could not open output config file \"%s\"", config_path);
315 #if !defined(__APPLE__)
318 bool head_of_file = true;
320 /* write a header about auto-generation to the output file */
321 fputs("# This file has been auto-generated by i3-config-wizard(1).\n", ks_config);
322 fputs("# It will not be overwritten, so edit it as you like.\n", ks_config);
323 fputs("#\n", ks_config);
324 fputs("# Should you change your keyboard layout somewhen, delete\n", ks_config);
325 fputs("# this file and re-run i3-config-wizard(1).\n", ks_config);
326 fputs("#\n", ks_config);
328 #if defined(__APPLE__)
329 while ((line = fgetln(kc_config, &len)) != NULL) {
331 while ((read = getline(&line, &len, kc_config)) != -1) {
333 /* skip the warning block at the beginning of the input file */
335 strncmp("# WARNING", line, strlen("# WARNING")) == 0)
338 head_of_file = false;
340 /* Skip leading whitespace */
342 while (isspace(*walk) && walk < (line + len))
345 /* Set the modifier the user chose */
346 if (strncmp(walk, "set $mod ", strlen("set $mod ")) == 0) {
347 if (modifier == MOD_Mod1)
348 fputs("set $mod Mod1\n", ks_config);
349 else fputs("set $mod Mod4\n", ks_config);
353 /* Check for 'bindcode'. If it’s not a bindcode line, we
354 * just copy it to the output file */
355 if (strncmp(walk, "bindcode", strlen("bindcode")) != 0) {
356 fputs(line, ks_config);
359 char *result = rewrite_binding(walk);
360 fputs(result, ks_config);
364 /* sync to do our best in order to have the file really stored on disk */
366 fsync(fileno(ks_config));
372 /* tell i3 to reload the config file */
373 int sockfd = ipc_connect(socket_path);
374 ipc_send_message(sockfd, strlen("reload"), 0, (uint8_t*)"reload");
380 int main(int argc, char *argv[]) {
381 config_path = resolve_tilde("~/.i3/config");
382 socket_path = getenv("I3SOCK");
383 char *pattern = "-misc-fixed-medium-r-normal--13-120-75-75-C-70-iso10646-1";
384 char *patternbold = "-misc-fixed-bold-r-normal--13-120-75-75-C-70-iso10646-1";
385 int o, option_index = 0;
387 static struct option long_options[] = {
388 {"socket", required_argument, 0, 's'},
389 {"version", no_argument, 0, 'v'},
390 {"limit", required_argument, 0, 'l'},
391 {"prompt", required_argument, 0, 'P'},
392 {"prefix", required_argument, 0, 'p'},
393 {"font", required_argument, 0, 'f'},
394 {"help", no_argument, 0, 'h'},
398 char *options_string = "s:vh";
400 while ((o = getopt_long(argc, argv, options_string, long_options, &option_index)) != -1) {
404 socket_path = strdup(optarg);
407 printf("i3-config-wizard " I3_VERSION "\n");
410 printf("i3-config-wizard " I3_VERSION "\n");
411 printf("i3-config-wizard [-s <socket>] [-v]\n");
416 /* Check if the destination config file does not exist but the path is
417 * writable. If not, exit now, this program is not useful in that case. */
419 if (stat(config_path, &stbuf) == 0) {
420 printf("The config file \"%s\" already exists. Exiting.\n", config_path);
424 /* Create ~/.i3 if it does not yet exist */
425 char *config_dir = resolve_tilde("~/.i3");
426 if (stat(config_dir, &stbuf) != 0)
427 if (mkdir(config_dir, 0755) == -1)
428 err(1, "mkdir(%s) failed", config_dir);
432 if ((fd = open(config_path, O_CREAT | O_RDWR, 0644)) == -1) {
433 printf("Cannot open file \"%s\" for writing: %s. Exiting.\n", config_path, strerror(errno));
439 if (socket_path == NULL)
440 socket_path = socket_path_from_x11();
442 if (socket_path == NULL)
443 socket_path = "/tmp/i3-ipc.sock";
446 if ((conn = xcb_connect(NULL, &screens)) == NULL ||
447 xcb_connection_has_error(conn))
448 errx(1, "Cannot open display\n");
450 xcb_get_modifier_mapping_cookie_t modmap_cookie;
451 modmap_cookie = xcb_get_modifier_mapping(conn);
453 /* Place requests for the atoms we need as soon as possible */
454 #define xmacro(atom) \
455 xcb_intern_atom_cookie_t atom ## _cookie = xcb_intern_atom(conn, 0, strlen(#atom), #atom);
456 #include "atoms.xmacro"
459 xcb_screen_t *root_screen = xcb_aux_get_screen(conn, screens);
460 root = root_screen->root;
462 if (!(modmap_reply = xcb_get_modifier_mapping_reply(conn, modmap_cookie, NULL)))
463 errx(EXIT_FAILURE, "Could not get modifier mapping\n");
465 /* XXX: we should refactor xcb_get_numlock_mask so that it uses the
466 * modifier mapping we already have */
467 xcb_get_numlock_mask(conn);
469 symbols = xcb_key_symbols_alloc(conn);
471 font_id = get_font_id(conn, pattern, &font_height);
472 font_bold_id = get_font_id(conn, patternbold, &font_bold_height);
474 /* Open an input window */
475 win = open_input_window(conn, 300, 205);
477 /* Setup NetWM atoms */
478 #define xmacro(name) \
480 xcb_intern_atom_reply_t *reply = xcb_intern_atom_reply(conn, name ## _cookie, NULL); \
482 errx(EXIT_FAILURE, "Could not get atom " # name "\n"); \
484 A_ ## name = reply->atom; \
487 #include "atoms.xmacro"
491 xcb_change_property(conn,
492 XCB_PROP_MODE_REPLACE,
494 A__NET_WM_WINDOW_TYPE,
498 (unsigned char*) &A__NET_WM_WINDOW_TYPE_DIALOG);
500 /* Set window title */
501 xcb_change_property(conn,
502 XCB_PROP_MODE_REPLACE,
507 strlen("i3: first configuration"),
508 "i3: first configuration");
511 pixmap = xcb_generate_id(conn);
512 pixmap_gc = xcb_generate_id(conn);
513 xcb_create_pixmap(conn, root_screen->root_depth, pixmap, win, 500, 500);
514 xcb_create_gc(conn, pixmap_gc, pixmap, 0, 0);
516 /* Grab the keyboard to get all input */
519 /* Try (repeatedly, if necessary) to grab the keyboard. We might not
520 * get the keyboard at the first attempt because of the keybinding
521 * still being active when started via a wm’s keybinding. */
522 xcb_grab_keyboard_cookie_t cookie;
523 xcb_grab_keyboard_reply_t *reply = NULL;
526 while ((reply == NULL || reply->status != XCB_GRAB_STATUS_SUCCESS) && (count++ < 500)) {
527 cookie = xcb_grab_keyboard(conn, false, win, XCB_CURRENT_TIME, XCB_GRAB_MODE_ASYNC, XCB_GRAB_MODE_ASYNC);
528 reply = xcb_grab_keyboard_reply(conn, cookie, NULL);
532 if (reply->status != XCB_GRAB_STATUS_SUCCESS) {
533 fprintf(stderr, "Could not grab keyboard, status = %d\n", reply->status);
539 xcb_generic_event_t *event;
540 while ((event = xcb_wait_for_event(conn)) != NULL) {
541 if (event->response_type == 0) {
542 fprintf(stderr, "X11 Error received! sequence %x\n", event->sequence);
546 /* Strip off the highest bit (set if the event is generated) */
547 int type = (event->response_type & 0x7F);
551 handle_key_press(NULL, conn, (xcb_key_press_event_t*)event);
554 /* TODO: handle mappingnotify */
556 case XCB_BUTTON_PRESS:
557 handle_button_press((xcb_button_press_event_t*)event);