]> git.sur5r.net Git - i3/i3/blob - i3-config-wizard/main.c
Merge pull request #1600 from Deiz/libi3
[i3/i3] / i3-config-wizard / main.c
1 /*
2  * vim:ts=4:sw=4:expandtab
3  *
4  * i3 - an improved dynamic tiling window manager
5  * © 2009-2012 Michael Stapelberg and contributors (see also: LICENSE)
6  *
7  * i3-config-wizard: Program to convert configs using keycodes to configs using
8  *                   keysyms.
9  *
10  */
11 #if defined(__FreeBSD__)
12 #include <sys/param.h>
13 #endif
14
15 /* For systems without getline, fall back to fgetln */
16 #if defined(__APPLE__)
17 #define USE_FGETLN
18 #elif defined(__FreeBSD__)
19 /* Defining this macro before including stdio.h is necessary in order to have
20  * a prototype for getline in FreeBSD. */
21 #define _WITH_GETLINE
22 #endif
23
24 #include <stdio.h>
25 #include <sys/types.h>
26 #include <stdlib.h>
27 #include <stdbool.h>
28 #include <unistd.h>
29 #include <string.h>
30 #include <ctype.h>
31 #include <errno.h>
32 #include <err.h>
33 #include <stdint.h>
34 #include <getopt.h>
35 #include <limits.h>
36 #include <sys/stat.h>
37 #include <fcntl.h>
38 #include <glob.h>
39 #include <assert.h>
40
41 #include <xcb/xcb.h>
42 #include <xcb/xcb_aux.h>
43 #include <xcb/xcb_event.h>
44 #include <xcb/xcb_keysyms.h>
45
46 #include <xkbcommon/xkbcommon.h>
47 #include <xkbcommon/xkbcommon-x11.h>
48
49 #include <X11/Xlib.h>
50 #include <X11/keysym.h>
51 #include <X11/XKBlib.h>
52
53 /* We need SYSCONFDIR for the path to the keycode config template, so raise an
54  * error if it’s not defined for whatever reason */
55 #ifndef SYSCONFDIR
56 #error "SYSCONFDIR not defined"
57 #endif
58
59 #define FREE(pointer)          \
60     do {                       \
61         if (pointer != NULL) { \
62             free(pointer);     \
63             pointer = NULL;    \
64         }                      \
65     } while (0)
66
67 #include "xcb.h"
68 #include "libi3.h"
69
70 #define row_y(row) \
71     (((row)-1) * font.height + logical_px(4))
72 #define window_height() \
73     (row_y(15) + font.height)
74
75 enum { STEP_WELCOME,
76        STEP_GENERATE } current_step = STEP_WELCOME;
77 enum { MOD_Mod1,
78        MOD_Mod4 } modifier = MOD_Mod4;
79
80 static char *config_path;
81 static uint32_t xcb_numlock_mask;
82 xcb_connection_t *conn;
83 static xcb_key_symbols_t *keysyms;
84 xcb_screen_t *root_screen;
85 static xcb_get_modifier_mapping_reply_t *modmap_reply;
86 static i3Font font;
87 static i3Font bold_font;
88 static int char_width;
89 static char *socket_path;
90 static xcb_window_t win;
91 static xcb_pixmap_t pixmap;
92 static xcb_gcontext_t pixmap_gc;
93 static xcb_key_symbols_t *symbols;
94 xcb_window_t root;
95 static struct xkb_keymap *xkb_keymap;
96 static uint8_t xkb_base_event;
97 static uint8_t xkb_base_error;
98
99 static void finish();
100
101 #include "GENERATED_config_enums.h"
102
103 typedef struct token {
104     char *name;
105     char *identifier;
106     /* This might be __CALL */
107     cmdp_state next_state;
108     union {
109         uint16_t call_identifier;
110     } extra;
111 } cmdp_token;
112
113 typedef struct tokenptr {
114     cmdp_token *array;
115     int n;
116 } cmdp_token_ptr;
117
118 #include "GENERATED_config_tokens.h"
119
120 static cmdp_state state;
121 /* A list which contains the states that lead to the current state, e.g.
122  * INITIAL, WORKSPACE_LAYOUT.
123  * When jumping back to INITIAL, statelist_idx will simply be set to 1
124  * (likewise for other states, e.g. MODE or BAR).
125  * This list is used to process the nearest error token. */
126 static cmdp_state statelist[10] = {INITIAL};
127 /* NB: statelist_idx points to where the next entry will be inserted */
128 static int statelist_idx = 1;
129
130 struct stack_entry {
131     /* Just a pointer, not dynamically allocated. */
132     const char *identifier;
133     enum {
134         STACK_STR = 0,
135         STACK_LONG = 1,
136     } type;
137     union {
138         char *str;
139         long num;
140     } val;
141 };
142
143 /* 10 entries should be enough for everybody. */
144 static struct stack_entry stack[10];
145
146 /*
147  * Pushes a string (identified by 'identifier') on the stack. We simply use a
148  * single array, since the number of entries we have to store is very small.
149  *
150  */
151 static void push_string(const char *identifier, const char *str) {
152     for (int c = 0; c < 10; c++) {
153         if (stack[c].identifier != NULL &&
154             strcmp(stack[c].identifier, identifier) != 0)
155             continue;
156         if (stack[c].identifier == NULL) {
157             /* Found a free slot, let’s store it here. */
158             stack[c].identifier = identifier;
159             stack[c].val.str = sstrdup(str);
160             stack[c].type = STACK_STR;
161         } else {
162             /* Append the value. */
163             char *prev = stack[c].val.str;
164             sasprintf(&(stack[c].val.str), "%s,%s", prev, str);
165             free(prev);
166         }
167         return;
168     }
169
170     /* When we arrive here, the stack is full. This should not happen and
171      * means there’s either a bug in this parser or the specification
172      * contains a command with more than 10 identified tokens. */
173     fprintf(stderr, "BUG: commands_parser stack full. This means either a bug "
174                     "in the code, or a new command which contains more than "
175                     "10 identified tokens.\n");
176     exit(1);
177 }
178
179 static void push_long(const char *identifier, long num) {
180     for (int c = 0; c < 10; c++) {
181         if (stack[c].identifier != NULL)
182             continue;
183         /* Found a free slot, let’s store it here. */
184         stack[c].identifier = identifier;
185         stack[c].val.num = num;
186         stack[c].type = STACK_LONG;
187         return;
188     }
189
190     /* When we arrive here, the stack is full. This should not happen and
191      * means there’s either a bug in this parser or the specification
192      * contains a command with more than 10 identified tokens. */
193     fprintf(stderr, "BUG: commands_parser stack full. This means either a bug "
194                     "in the code, or a new command which contains more than "
195                     "10 identified tokens.\n");
196     exit(1);
197 }
198
199 static const char *get_string(const char *identifier) {
200     for (int c = 0; c < 10; c++) {
201         if (stack[c].identifier == NULL)
202             break;
203         if (strcmp(identifier, stack[c].identifier) == 0)
204             return stack[c].val.str;
205     }
206     return NULL;
207 }
208
209 static void clear_stack(void) {
210     for (int c = 0; c < 10; c++) {
211         if (stack[c].type == STACK_STR && stack[c].val.str != NULL)
212             free(stack[c].val.str);
213         stack[c].identifier = NULL;
214         stack[c].val.str = NULL;
215         stack[c].val.num = 0;
216     }
217 }
218
219 /*
220  * Returns true if sym is bound to any key except for 'except_keycode' on the
221  * first four layers (normal, shift, mode_switch, mode_switch + shift).
222  *
223  */
224 static bool keysym_used_on_other_key(KeySym sym, xcb_keycode_t except_keycode) {
225     xcb_keycode_t i,
226         min_keycode = xcb_get_setup(conn)->min_keycode,
227         max_keycode = xcb_get_setup(conn)->max_keycode;
228
229     for (i = min_keycode; i && i <= max_keycode; i++) {
230         if (i == except_keycode)
231             continue;
232         for (int level = 0; level < 4; level++) {
233             if (xcb_key_symbols_get_keysym(keysyms, i, level) != sym)
234                 continue;
235             return true;
236         }
237     }
238     return false;
239 }
240
241 static char *next_state(const cmdp_token *token) {
242     cmdp_state _next_state = token->next_state;
243
244     if (token->next_state == __CALL) {
245         const char *modifiers = get_string("modifiers");
246         int keycode = atoi(get_string("key"));
247         int level = 0;
248         if (modifiers != NULL &&
249             strstr(modifiers, "Shift") != NULL) {
250             /* When shift is included, we really need to use the second-level
251              * symbol (upper-case). The lower-case symbol could be on a
252              * different key than the upper-case one (unlikely for letters, but
253              * more likely for special characters). */
254             level = 1;
255
256             /* Try to use the keysym on the first level (lower-case). In case
257              * this doesn’t make it ambiguous (think of a keyboard layout
258              * having '1' on two different keys, but '!' only on keycode 10),
259              * we’ll stick with the keysym of the first level.
260              *
261              * This reduces a lot of confusion for users who switch keyboard
262              * layouts from qwerty to qwertz or other slight variations of
263              * qwerty (yes, that happens quite often). */
264             const xkb_keysym_t *syms;
265             int num = xkb_keymap_key_get_syms_by_level(xkb_keymap, keycode, 0, 0, &syms);
266             if (num == 0)
267                 errx(1, "xkb_keymap_key_get_syms_by_level returned no symbols for keycode %d", keycode);
268             if (!keysym_used_on_other_key(syms[0], keycode))
269                 level = 0;
270         }
271
272         const xkb_keysym_t *syms;
273         int num = xkb_keymap_key_get_syms_by_level(xkb_keymap, keycode, 0, level, &syms);
274         if (num == 0)
275             errx(1, "xkb_keymap_key_get_syms_by_level returned no symbols for keycode %d", keycode);
276         if (num > 1)
277             printf("xkb_keymap_key_get_syms_by_level (keycode = %d) returned %d symbolsinstead of 1, using only the first one.\n", keycode, num);
278
279         char str[4096];
280         if (xkb_keysym_get_name(syms[0], str, sizeof(str)) == -1)
281             errx(EXIT_FAILURE, "xkb_keysym_get_name(%u) failed", syms[0]);
282         const char *release = get_string("release");
283         char *res;
284         char *modrep = (modifiers == NULL ? sstrdup("") : sstrdup(modifiers));
285         char *comma;
286         while ((comma = strchr(modrep, ',')) != NULL) {
287             *comma = '+';
288         }
289         sasprintf(&res, "bindsym %s%s%s %s%s\n", (modifiers == NULL ? "" : modrep), (modifiers == NULL ? "" : "+"), str, (release == NULL ? "" : release), get_string("command"));
290         clear_stack();
291         return res;
292     }
293
294     state = _next_state;
295
296     /* See if we are jumping back to a state in which we were in previously
297      * (statelist contains INITIAL) and just move statelist_idx accordingly. */
298     for (int i = 0; i < statelist_idx; i++) {
299         if (statelist[i] != _next_state)
300             continue;
301         statelist_idx = i + 1;
302         return NULL;
303     }
304
305     /* Otherwise, the state is new and we add it to the list */
306     statelist[statelist_idx++] = _next_state;
307     return NULL;
308 }
309
310 static char *rewrite_binding(const char *input) {
311     state = INITIAL;
312     statelist_idx = 1;
313
314     const char *walk = input;
315     const size_t len = strlen(input);
316     int c;
317     const cmdp_token *token;
318     char *result = NULL;
319
320     /* The "<=" operator is intentional: We also handle the terminating 0-byte
321      * explicitly by looking for an 'end' token. */
322     while ((size_t)(walk - input) <= len) {
323         /* Skip whitespace before every token, newlines are relevant since they
324          * separate configuration directives. */
325         while ((*walk == ' ' || *walk == '\t') && *walk != '\0')
326             walk++;
327
328         //printf("remaining input: %s\n", walk);
329
330         cmdp_token_ptr *ptr = &(tokens[state]);
331         for (c = 0; c < ptr->n; c++) {
332             token = &(ptr->array[c]);
333
334             /* A literal. */
335             if (token->name[0] == '\'') {
336                 if (strncasecmp(walk, token->name + 1, strlen(token->name) - 1) == 0) {
337                     if (token->identifier != NULL)
338                         push_string(token->identifier, token->name + 1);
339                     walk += strlen(token->name) - 1;
340                     if ((result = next_state(token)) != NULL)
341                         return result;
342                     break;
343                 }
344                 continue;
345             }
346
347             if (strcmp(token->name, "number") == 0) {
348                 /* Handle numbers. We only accept decimal numbers for now. */
349                 char *end = NULL;
350                 errno = 0;
351                 long int num = strtol(walk, &end, 10);
352                 if ((errno == ERANGE && (num == LONG_MIN || num == LONG_MAX)) ||
353                     (errno != 0 && num == 0))
354                     continue;
355
356                 /* No valid numbers found */
357                 if (end == walk)
358                     continue;
359
360                 if (token->identifier != NULL)
361                     push_long(token->identifier, num);
362
363                 /* Set walk to the first non-number character */
364                 walk = end;
365                 if ((result = next_state(token)) != NULL)
366                     return result;
367                 break;
368             }
369
370             if (strcmp(token->name, "string") == 0 ||
371                 strcmp(token->name, "word") == 0) {
372                 const char *beginning = walk;
373                 /* Handle quoted strings (or words). */
374                 if (*walk == '"') {
375                     beginning++;
376                     walk++;
377                     while (*walk != '\0' && (*walk != '"' || *(walk - 1) == '\\'))
378                         walk++;
379                 } else {
380                     if (token->name[0] == 's') {
381                         while (*walk != '\0' && *walk != '\r' && *walk != '\n')
382                             walk++;
383                     } else {
384                         /* For a word, the delimiters are white space (' ' or
385                          * '\t'), closing square bracket (]), comma (,) and
386                          * semicolon (;). */
387                         while (*walk != ' ' && *walk != '\t' &&
388                                *walk != ']' && *walk != ',' &&
389                                *walk != ';' && *walk != '\r' &&
390                                *walk != '\n' && *walk != '\0')
391                             walk++;
392                     }
393                 }
394                 if (walk != beginning) {
395                     char *str = scalloc(walk - beginning + 1);
396                     /* We copy manually to handle escaping of characters. */
397                     int inpos, outpos;
398                     for (inpos = 0, outpos = 0;
399                          inpos < (walk - beginning);
400                          inpos++, outpos++) {
401                         /* We only handle escaped double quotes to not break
402                          * backwards compatibility with people using \w in
403                          * regular expressions etc. */
404                         if (beginning[inpos] == '\\' && beginning[inpos + 1] == '"')
405                             inpos++;
406                         str[outpos] = beginning[inpos];
407                     }
408                     if (token->identifier)
409                         push_string(token->identifier, str);
410                     free(str);
411                     /* If we are at the end of a quoted string, skip the ending
412                      * double quote. */
413                     if (*walk == '"')
414                         walk++;
415                     if ((result = next_state(token)) != NULL)
416                         return result;
417                     break;
418                 }
419             }
420
421             if (strcmp(token->name, "end") == 0) {
422                 //printf("checking for end: *%s*\n", walk);
423                 if (*walk == '\0' || *walk == '\n' || *walk == '\r') {
424                     if ((result = next_state(token)) != NULL)
425                         return result;
426                     /* To make sure we start with an appropriate matching
427                      * datastructure for commands which do *not* specify any
428                      * criteria, we re-initialize the criteria system after
429                      * every command. */
430                     // TODO: make this testable
431                     walk++;
432                     break;
433                 }
434             }
435         }
436     }
437
438     return NULL;
439 }
440
441 /*
442  * Having verboselog(), errorlog() and debuglog() is necessary when using libi3.
443  *
444  */
445 void verboselog(char *fmt, ...) {
446     va_list args;
447
448     va_start(args, fmt);
449     vfprintf(stdout, fmt, args);
450     va_end(args);
451 }
452
453 void errorlog(char *fmt, ...) {
454     va_list args;
455
456     va_start(args, fmt);
457     vfprintf(stderr, fmt, args);
458     va_end(args);
459 }
460
461 void debuglog(char *fmt, ...) {
462 }
463
464 /*
465  * Handles expose events, that is, draws the window contents.
466  *
467  */
468 static int handle_expose() {
469     /* re-draw the background */
470     xcb_rectangle_t border = {0, 0, logical_px(300), window_height()};
471     xcb_change_gc(conn, pixmap_gc, XCB_GC_FOREGROUND, (uint32_t[]){get_colorpixel("#000000")});
472     xcb_poly_fill_rectangle(conn, pixmap, pixmap_gc, 1, &border);
473
474     set_font(&font);
475
476 #define txt(x, row, text)                    \
477     draw_text_ascii(text, pixmap, pixmap_gc, \
478                     x, row_y(row), logical_px(500) - x * 2)
479
480     if (current_step == STEP_WELCOME) {
481         /* restore font color */
482         set_font_colors(pixmap_gc, get_colorpixel("#FFFFFF"), get_colorpixel("#000000"));
483
484         txt(logical_px(10), 2, "You have not configured i3 yet.");
485         txt(logical_px(10), 3, "Do you want me to generate ~/.i3/config?");
486         txt(logical_px(85), 5, "Yes, generate ~/.i3/config");
487         txt(logical_px(85), 7, "No, I will use the defaults");
488
489         /* green */
490         set_font_colors(pixmap_gc, get_colorpixel("#00FF00"), get_colorpixel("#000000"));
491         txt(logical_px(25), 5, "<Enter>");
492
493         /* red */
494         set_font_colors(pixmap_gc, get_colorpixel("#FF0000"), get_colorpixel("#000000"));
495         txt(logical_px(31), 7, "<ESC>");
496     }
497
498     if (current_step == STEP_GENERATE) {
499         set_font_colors(pixmap_gc, get_colorpixel("#FFFFFF"), get_colorpixel("#000000"));
500
501         txt(logical_px(10), 2, "Please choose either:");
502         txt(logical_px(85), 4, "Win as default modifier");
503         txt(logical_px(85), 5, "Alt as default modifier");
504         txt(logical_px(10), 7, "Afterwards, press");
505         txt(logical_px(85), 9, "to write ~/.i3/config");
506         txt(logical_px(85), 10, "to abort");
507
508         /* the not-selected modifier */
509         if (modifier == MOD_Mod4)
510             txt(logical_px(31), 5, "<Alt>");
511         else
512             txt(logical_px(31), 4, "<Win>");
513
514         /* the selected modifier */
515         set_font(&bold_font);
516         set_font_colors(pixmap_gc, get_colorpixel("#FFFFFF"), get_colorpixel("#000000"));
517         if (modifier == MOD_Mod4)
518             txt(logical_px(10), 4, "-> <Win>");
519         else
520             txt(logical_px(10), 5, "-> <Alt>");
521
522         /* green */
523         set_font(&font);
524         set_font_colors(pixmap_gc, get_colorpixel("#00FF00"), get_colorpixel("#000000"));
525         txt(logical_px(25), 9, "<Enter>");
526
527         /* red */
528         set_font_colors(pixmap_gc, get_colorpixel("#FF0000"), get_colorpixel("#000000"));
529         txt(logical_px(31), 10, "<ESC>");
530     }
531
532     /* Copy the contents of the pixmap to the real window */
533     xcb_copy_area(conn, pixmap, win, pixmap_gc, 0, 0, 0, 0, logical_px(500), logical_px(500));
534     xcb_flush(conn);
535
536     return 1;
537 }
538
539 static int handle_key_press(void *ignored, xcb_connection_t *conn, xcb_key_press_event_t *event) {
540     printf("Keypress %d, state raw = %d\n", event->detail, event->state);
541
542     /* Remove the numlock bit, all other bits are modifiers we can bind to */
543     uint16_t state_filtered = event->state & ~(xcb_numlock_mask | XCB_MOD_MASK_LOCK);
544     /* Only use the lower 8 bits of the state (modifier masks) so that mouse
545      * button masks are filtered out */
546     state_filtered &= 0xFF;
547
548     xcb_keysym_t sym = xcb_key_press_lookup_keysym(symbols, event, state_filtered);
549
550     printf("sym = %c (%d)\n", sym, sym);
551
552     if (sym == XK_Return || sym == XK_KP_Enter) {
553         if (current_step == STEP_WELCOME) {
554             current_step = STEP_GENERATE;
555             /* Set window title */
556             xcb_change_property(conn,
557                                 XCB_PROP_MODE_REPLACE,
558                                 win,
559                                 A__NET_WM_NAME,
560                                 A_UTF8_STRING,
561                                 8,
562                                 strlen("i3: generate config"),
563                                 "i3: generate config");
564             xcb_flush(conn);
565         } else
566             finish();
567     }
568
569     /* Swap between modifiers when up or down is pressed. */
570     if (sym == XK_Up || sym == XK_Down) {
571         modifier = (modifier == MOD_Mod1) ? MOD_Mod4 : MOD_Mod1;
572         handle_expose();
573     }
574
575     /* cancel any time */
576     if (sym == XK_Escape)
577         exit(0);
578
579     /* Check if this is Mod1 or Mod4. The modmap contains Shift, Lock, Control,
580      * Mod1, Mod2, Mod3, Mod4, Mod5 (in that order) */
581     xcb_keycode_t *modmap = xcb_get_modifier_mapping_keycodes(modmap_reply);
582     /* Mod1? */
583     int mask = 3;
584     for (int i = 0; i < modmap_reply->keycodes_per_modifier; i++) {
585         xcb_keycode_t code = modmap[(mask * modmap_reply->keycodes_per_modifier) + i];
586         if (code == XCB_NONE)
587             continue;
588         printf("Modifier keycode for Mod1: 0x%02x\n", code);
589         if (code == event->detail) {
590             modifier = MOD_Mod1;
591             printf("This is Mod1!\n");
592         }
593     }
594
595     /* Mod4? */
596     mask = 6;
597     for (int i = 0; i < modmap_reply->keycodes_per_modifier; i++) {
598         xcb_keycode_t code = modmap[(mask * modmap_reply->keycodes_per_modifier) + i];
599         if (code == XCB_NONE)
600             continue;
601         printf("Modifier keycode for Mod4: 0x%02x\n", code);
602         if (code == event->detail) {
603             modifier = MOD_Mod4;
604             printf("This is Mod4!\n");
605         }
606     }
607
608     handle_expose();
609     return 1;
610 }
611
612 /*
613  * Handle button presses to make clicking on "<win>" and "<alt>" work
614  *
615  */
616 static void handle_button_press(xcb_button_press_event_t *event) {
617     if (current_step != STEP_GENERATE)
618         return;
619
620     if (event->event_x < logical_px(32) ||
621         event->event_x > (logical_px(32) + char_width * 5))
622         return;
623
624     if (event->event_y >= row_y(4) && event->event_y <= (row_y(4) + font.height)) {
625         modifier = MOD_Mod4;
626         handle_expose();
627     }
628
629     if (event->event_y >= row_y(5) && event->event_y <= (row_y(5) + font.height)) {
630         modifier = MOD_Mod1;
631         handle_expose();
632     }
633
634     return;
635 }
636
637 /*
638  * Creates the config file and tells i3 to reload.
639  *
640  */
641 static void finish() {
642     printf("creating \"%s\"...\n", config_path);
643
644     struct xkb_context *xkb_context;
645
646     if ((xkb_context = xkb_context_new(0)) == NULL)
647         errx(1, "could not create xkbcommon context");
648
649     int32_t device_id = xkb_x11_get_core_keyboard_device_id(conn);
650     if ((xkb_keymap = xkb_x11_keymap_new_from_device(xkb_context, conn, device_id, 0)) == NULL)
651         errx(1, "xkb_x11_keymap_new_from_device failed");
652
653     FILE *kc_config = fopen(SYSCONFDIR "/i3/config.keycodes", "r");
654     if (kc_config == NULL)
655         err(1, "Could not open input file \"%s\"", SYSCONFDIR "/i3/config.keycodes");
656
657     FILE *ks_config = fopen(config_path, "w");
658     if (ks_config == NULL)
659         err(1, "Could not open output config file \"%s\"", config_path);
660     free(config_path);
661
662     char *line = NULL;
663     size_t len = 0;
664 #ifndef USE_FGETLN
665     ssize_t read;
666 #endif
667     bool head_of_file = true;
668
669     /* write a header about auto-generation to the output file */
670     fputs("# This file has been auto-generated by i3-config-wizard(1).\n", ks_config);
671     fputs("# It will not be overwritten, so edit it as you like.\n", ks_config);
672     fputs("#\n", ks_config);
673     fputs("# Should you change your keyboard layout some time, delete\n", ks_config);
674     fputs("# this file and re-run i3-config-wizard(1).\n", ks_config);
675     fputs("#\n", ks_config);
676
677 #ifdef USE_FGETLN
678     char *buf = NULL;
679     while ((buf = fgetln(kc_config, &len)) != NULL) {
680         /* fgetln does not return null-terminated strings */
681         FREE(line);
682         sasprintf(&line, "%.*s", len, buf);
683 #else
684     size_t linecap = 0;
685     while ((read = getline(&line, &linecap, kc_config)) != -1) {
686         len = strlen(line);
687 #endif
688         /* skip the warning block at the beginning of the input file */
689         if (head_of_file &&
690             strncmp("# WARNING", line, strlen("# WARNING")) == 0)
691             continue;
692
693         head_of_file = false;
694
695         /* Skip leading whitespace */
696         char *walk = line;
697         while (isspace(*walk) && walk < (line + len)) {
698             /* Pre-output the skipped whitespaces to keep proper indentation */
699             fputc(*walk, ks_config);
700             walk++;
701         }
702
703         /* Set the modifier the user chose */
704         if (strncmp(walk, "set $mod ", strlen("set $mod ")) == 0) {
705             if (modifier == MOD_Mod1)
706                 fputs("set $mod Mod1\n", ks_config);
707             else
708                 fputs("set $mod Mod4\n", ks_config);
709             continue;
710         }
711
712         /* Check for 'bindcode'. If it’s not a bindcode line, we
713          * just copy it to the output file */
714         if (strncmp(walk, "bindcode", strlen("bindcode")) != 0) {
715             fputs(walk, ks_config);
716             continue;
717         }
718         char *result = rewrite_binding(walk);
719         fputs(result, ks_config);
720         free(result);
721     }
722
723     /* sync to do our best in order to have the file really stored on disk */
724     fflush(ks_config);
725     fsync(fileno(ks_config));
726
727 #ifndef USE_FGETLN
728     free(line);
729 #endif
730
731     fclose(kc_config);
732     fclose(ks_config);
733
734     /* tell i3 to reload the config file */
735     int sockfd = ipc_connect(socket_path);
736     ipc_send_message(sockfd, strlen("reload"), 0, (uint8_t *)"reload");
737     close(sockfd);
738
739     exit(0);
740 }
741
742 int main(int argc, char *argv[]) {
743     config_path = resolve_tilde("~/.i3/config");
744     socket_path = getenv("I3SOCK");
745     char *pattern = "pango:monospace 8";
746     char *patternbold = "pango:monospace bold 8";
747     int o, option_index = 0;
748
749     static struct option long_options[] = {
750         {"socket", required_argument, 0, 's'},
751         {"version", no_argument, 0, 'v'},
752         {"limit", required_argument, 0, 'l'},
753         {"prompt", required_argument, 0, 'P'},
754         {"prefix", required_argument, 0, 'p'},
755         {"font", required_argument, 0, 'f'},
756         {"help", no_argument, 0, 'h'},
757         {0, 0, 0, 0}};
758
759     char *options_string = "s:vh";
760
761     while ((o = getopt_long(argc, argv, options_string, long_options, &option_index)) != -1) {
762         switch (o) {
763             case 's':
764                 FREE(socket_path);
765                 socket_path = strdup(optarg);
766                 break;
767             case 'v':
768                 printf("i3-config-wizard " I3_VERSION "\n");
769                 return 0;
770             case 'h':
771                 printf("i3-config-wizard " I3_VERSION "\n");
772                 printf("i3-config-wizard [-s <socket>] [-v]\n");
773                 return 0;
774         }
775     }
776
777     /* Check if the destination config file does not exist but the path is
778      * writable. If not, exit now, this program is not useful in that case. */
779     struct stat stbuf;
780     if (stat(config_path, &stbuf) == 0) {
781         printf("The config file \"%s\" already exists. Exiting.\n", config_path);
782         return 0;
783     }
784
785     /* Create ~/.i3 if it does not yet exist */
786     char *config_dir = resolve_tilde("~/.i3");
787     if (stat(config_dir, &stbuf) != 0)
788         if (mkdir(config_dir, 0755) == -1)
789             err(1, "mkdir(%s) failed", config_dir);
790     free(config_dir);
791
792     int fd;
793     if ((fd = open(config_path, O_CREAT | O_RDWR, 0644)) == -1) {
794         printf("Cannot open file \"%s\" for writing: %s. Exiting.\n", config_path, strerror(errno));
795         return 0;
796     }
797     close(fd);
798     unlink(config_path);
799
800     int screen;
801     if ((conn = xcb_connect(NULL, &screen)) == NULL ||
802         xcb_connection_has_error(conn))
803         errx(1, "Cannot open display\n");
804
805     if (xkb_x11_setup_xkb_extension(conn,
806                                     XKB_X11_MIN_MAJOR_XKB_VERSION,
807                                     XKB_X11_MIN_MINOR_XKB_VERSION,
808                                     0,
809                                     NULL,
810                                     NULL,
811                                     &xkb_base_event,
812                                     &xkb_base_error) != 1)
813         errx(EXIT_FAILURE, "Could not setup XKB extension.");
814
815     if (socket_path == NULL)
816         socket_path = root_atom_contents("I3_SOCKET_PATH", conn, screen);
817
818     if (socket_path == NULL)
819         socket_path = "/tmp/i3-ipc.sock";
820
821     keysyms = xcb_key_symbols_alloc(conn);
822     xcb_get_modifier_mapping_cookie_t modmap_cookie;
823     modmap_cookie = xcb_get_modifier_mapping(conn);
824     symbols = xcb_key_symbols_alloc(conn);
825
826 /* Place requests for the atoms we need as soon as possible */
827 #define xmacro(atom) \
828     xcb_intern_atom_cookie_t atom##_cookie = xcb_intern_atom(conn, 0, strlen(#atom), #atom);
829 #include "atoms.xmacro"
830 #undef xmacro
831
832     root_screen = xcb_aux_get_screen(conn, screen);
833     root = root_screen->root;
834
835     if (!(modmap_reply = xcb_get_modifier_mapping_reply(conn, modmap_cookie, NULL)))
836         errx(EXIT_FAILURE, "Could not get modifier mapping\n");
837
838     xcb_numlock_mask = get_mod_mask_for(XCB_NUM_LOCK, symbols, modmap_reply);
839
840     font = load_font(pattern, true);
841     bold_font = load_font(patternbold, true);
842
843     /* Determine character width in the default font. */
844     set_font(&font);
845     char_width = predict_text_width(i3string_from_utf8("a"));
846
847     /* Open an input window */
848     win = xcb_generate_id(conn);
849     xcb_create_window(
850         conn,
851         XCB_COPY_FROM_PARENT,
852         win,                                                                /* the window id */
853         root,                                                               /* parent == root */
854         logical_px(490), logical_px(297), logical_px(300), window_height(), /* dimensions */
855         0,                                                                  /* X11 border = 0, we draw our own */
856         XCB_WINDOW_CLASS_INPUT_OUTPUT,
857         XCB_WINDOW_CLASS_COPY_FROM_PARENT, /* copy visual from parent */
858         XCB_CW_BACK_PIXEL | XCB_CW_EVENT_MASK,
859         (uint32_t[]){
860             0, /* back pixel: black */
861             XCB_EVENT_MASK_EXPOSURE |
862                 XCB_EVENT_MASK_BUTTON_PRESS});
863
864     /* Map the window (make it visible) */
865     xcb_map_window(conn, win);
866
867 /* Setup NetWM atoms */
868 #define xmacro(name)                                                                       \
869     do {                                                                                   \
870         xcb_intern_atom_reply_t *reply = xcb_intern_atom_reply(conn, name##_cookie, NULL); \
871         if (!reply)                                                                        \
872             errx(EXIT_FAILURE, "Could not get atom " #name "\n");                          \
873                                                                                            \
874         A_##name = reply->atom;                                                            \
875         free(reply);                                                                       \
876     } while (0);
877 #include "atoms.xmacro"
878 #undef xmacro
879
880     /* Set dock mode */
881     xcb_change_property(conn,
882                         XCB_PROP_MODE_REPLACE,
883                         win,
884                         A__NET_WM_WINDOW_TYPE,
885                         A_ATOM,
886                         32,
887                         1,
888                         (unsigned char *)&A__NET_WM_WINDOW_TYPE_DIALOG);
889
890     /* Set window title */
891     xcb_change_property(conn,
892                         XCB_PROP_MODE_REPLACE,
893                         win,
894                         A__NET_WM_NAME,
895                         A_UTF8_STRING,
896                         8,
897                         strlen("i3: first configuration"),
898                         "i3: first configuration");
899
900     /* Create pixmap */
901     pixmap = xcb_generate_id(conn);
902     pixmap_gc = xcb_generate_id(conn);
903     xcb_create_pixmap(conn, root_screen->root_depth, pixmap, win, logical_px(500), logical_px(500));
904     xcb_create_gc(conn, pixmap_gc, pixmap, 0, 0);
905
906     /* Grab the keyboard to get all input */
907     xcb_flush(conn);
908
909     /* Try (repeatedly, if necessary) to grab the keyboard. We might not
910      * get the keyboard at the first attempt because of the keybinding
911      * still being active when started via a wm’s keybinding. */
912     xcb_grab_keyboard_cookie_t cookie;
913     xcb_grab_keyboard_reply_t *reply = NULL;
914
915     int count = 0;
916     while ((reply == NULL || reply->status != XCB_GRAB_STATUS_SUCCESS) && (count++ < 500)) {
917         cookie = xcb_grab_keyboard(conn, false, win, XCB_CURRENT_TIME, XCB_GRAB_MODE_ASYNC, XCB_GRAB_MODE_ASYNC);
918         reply = xcb_grab_keyboard_reply(conn, cookie, NULL);
919         usleep(1000);
920     }
921
922     if (reply->status != XCB_GRAB_STATUS_SUCCESS) {
923         fprintf(stderr, "Could not grab keyboard, status = %d\n", reply->status);
924         exit(-1);
925     }
926
927     xcb_flush(conn);
928
929     xcb_generic_event_t *event;
930     while ((event = xcb_wait_for_event(conn)) != NULL) {
931         if (event->response_type == 0) {
932             fprintf(stderr, "X11 Error received! sequence %x\n", event->sequence);
933             continue;
934         }
935
936         /* Strip off the highest bit (set if the event is generated) */
937         int type = (event->response_type & 0x7F);
938
939         switch (type) {
940             case XCB_KEY_PRESS:
941                 handle_key_press(NULL, conn, (xcb_key_press_event_t *)event);
942                 break;
943
944             /* TODO: handle mappingnotify */
945
946             case XCB_BUTTON_PRESS:
947                 handle_button_press((xcb_button_press_event_t *)event);
948                 break;
949
950             case XCB_EXPOSE:
951                 handle_expose();
952                 break;
953         }
954
955         free(event);
956     }
957
958     return 0;
959 }