]> git.sur5r.net Git - i3/i3/blob - i3-config-wizard/main.c
Merge pull request #1816 from tcreech/tcreech-for-illumos
[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 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, 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 a config at");
486
487         char *msg;
488         sasprintf(&msg, "%s?", config_path);
489         txt(logical_px(10), 4, msg);
490         free(msg);
491
492         txt(logical_px(85), 6, "Yes, generate the config");
493         txt(logical_px(85), 8, "No, I will use the defaults");
494
495         /* green */
496         set_font_colors(pixmap_gc, get_colorpixel("#00FF00"), get_colorpixel("#000000"));
497         txt(logical_px(25), 6, "<Enter>");
498
499         /* red */
500         set_font_colors(pixmap_gc, get_colorpixel("#FF0000"), get_colorpixel("#000000"));
501         txt(logical_px(31), 8, "<ESC>");
502     }
503
504     if (current_step == STEP_GENERATE) {
505         set_font_colors(pixmap_gc, get_colorpixel("#FFFFFF"), get_colorpixel("#000000"));
506
507         txt(logical_px(10), 2, "Please choose either:");
508         txt(logical_px(85), 4, "Win as default modifier");
509         txt(logical_px(85), 5, "Alt as default modifier");
510         txt(logical_px(10), 7, "Afterwards, press");
511         txt(logical_px(85), 9, "to write the config");
512         txt(logical_px(85), 10, "to abort");
513
514         /* the not-selected modifier */
515         if (modifier == MOD_Mod4)
516             txt(logical_px(31), 5, "<Alt>");
517         else
518             txt(logical_px(31), 4, "<Win>");
519
520         /* the selected modifier */
521         set_font(&bold_font);
522         set_font_colors(pixmap_gc, get_colorpixel("#FFFFFF"), get_colorpixel("#000000"));
523         if (modifier == MOD_Mod4)
524             txt(logical_px(10), 4, "-> <Win>");
525         else
526             txt(logical_px(10), 5, "-> <Alt>");
527
528         /* green */
529         set_font(&font);
530         set_font_colors(pixmap_gc, get_colorpixel("#00FF00"), get_colorpixel("#000000"));
531         txt(logical_px(25), 9, "<Enter>");
532
533         /* red */
534         set_font_colors(pixmap_gc, get_colorpixel("#FF0000"), get_colorpixel("#000000"));
535         txt(logical_px(31), 10, "<ESC>");
536     }
537
538     /* Copy the contents of the pixmap to the real window */
539     xcb_copy_area(conn, pixmap, win, pixmap_gc, 0, 0, 0, 0, logical_px(500), logical_px(500));
540     xcb_flush(conn);
541
542     return 1;
543 }
544
545 static int handle_key_press(void *ignored, xcb_connection_t *conn, xcb_key_press_event_t *event) {
546     printf("Keypress %d, state raw = %d\n", event->detail, event->state);
547
548     /* Remove the numlock bit, all other bits are modifiers we can bind to */
549     uint16_t state_filtered = event->state & ~(xcb_numlock_mask | XCB_MOD_MASK_LOCK);
550     /* Only use the lower 8 bits of the state (modifier masks) so that mouse
551      * button masks are filtered out */
552     state_filtered &= 0xFF;
553
554     xcb_keysym_t sym = xcb_key_press_lookup_keysym(symbols, event, state_filtered);
555
556     printf("sym = %c (%d)\n", sym, sym);
557
558     if (sym == XK_Return || sym == XK_KP_Enter) {
559         if (current_step == STEP_WELCOME) {
560             current_step = STEP_GENERATE;
561             /* Set window title */
562             xcb_change_property(conn,
563                                 XCB_PROP_MODE_REPLACE,
564                                 win,
565                                 A__NET_WM_NAME,
566                                 A_UTF8_STRING,
567                                 8,
568                                 strlen("i3: generate config"),
569                                 "i3: generate config");
570             xcb_flush(conn);
571         } else
572             finish();
573     }
574
575     /* Swap between modifiers when up or down is pressed. */
576     if (sym == XK_Up || sym == XK_Down) {
577         modifier = (modifier == MOD_Mod1) ? MOD_Mod4 : MOD_Mod1;
578         handle_expose();
579     }
580
581     /* cancel any time */
582     if (sym == XK_Escape)
583         exit(0);
584
585     /* Check if this is Mod1 or Mod4. The modmap contains Shift, Lock, Control,
586      * Mod1, Mod2, Mod3, Mod4, Mod5 (in that order) */
587     xcb_keycode_t *modmap = xcb_get_modifier_mapping_keycodes(modmap_reply);
588     /* Mod1? */
589     int mask = 3;
590     for (int i = 0; i < modmap_reply->keycodes_per_modifier; i++) {
591         xcb_keycode_t code = modmap[(mask * modmap_reply->keycodes_per_modifier) + i];
592         if (code == XCB_NONE)
593             continue;
594         printf("Modifier keycode for Mod1: 0x%02x\n", code);
595         if (code == event->detail) {
596             modifier = MOD_Mod1;
597             printf("This is Mod1!\n");
598         }
599     }
600
601     /* Mod4? */
602     mask = 6;
603     for (int i = 0; i < modmap_reply->keycodes_per_modifier; i++) {
604         xcb_keycode_t code = modmap[(mask * modmap_reply->keycodes_per_modifier) + i];
605         if (code == XCB_NONE)
606             continue;
607         printf("Modifier keycode for Mod4: 0x%02x\n", code);
608         if (code == event->detail) {
609             modifier = MOD_Mod4;
610             printf("This is Mod4!\n");
611         }
612     }
613
614     handle_expose();
615     return 1;
616 }
617
618 /*
619  * Handle button presses to make clicking on "<win>" and "<alt>" work
620  *
621  */
622 static void handle_button_press(xcb_button_press_event_t *event) {
623     if (current_step != STEP_GENERATE)
624         return;
625
626     if (event->event_x < logical_px(32) ||
627         event->event_x > (logical_px(32) + char_width * 5))
628         return;
629
630     if (event->event_y >= row_y(4) && event->event_y <= (row_y(4) + font.height)) {
631         modifier = MOD_Mod4;
632         handle_expose();
633     }
634
635     if (event->event_y >= row_y(5) && event->event_y <= (row_y(5) + font.height)) {
636         modifier = MOD_Mod1;
637         handle_expose();
638     }
639
640     return;
641 }
642
643 /*
644  * Creates the config file and tells i3 to reload.
645  *
646  */
647 static void finish() {
648     printf("creating \"%s\"...\n", config_path);
649
650     struct xkb_context *xkb_context;
651
652     if ((xkb_context = xkb_context_new(0)) == NULL)
653         errx(1, "could not create xkbcommon context");
654
655     int32_t device_id = xkb_x11_get_core_keyboard_device_id(conn);
656     if ((xkb_keymap = xkb_x11_keymap_new_from_device(xkb_context, conn, device_id, 0)) == NULL)
657         errx(1, "xkb_x11_keymap_new_from_device failed");
658
659     FILE *kc_config = fopen(SYSCONFDIR "/i3/config.keycodes", "r");
660     if (kc_config == NULL)
661         err(1, "Could not open input file \"%s\"", SYSCONFDIR "/i3/config.keycodes");
662
663     FILE *ks_config = fopen(config_path, "w");
664     if (ks_config == NULL)
665         err(1, "Could not open output config file \"%s\"", config_path);
666     free(config_path);
667
668     char *line = NULL;
669     size_t len = 0;
670 #ifndef USE_FGETLN
671     ssize_t read;
672 #endif
673     bool head_of_file = true;
674
675     /* write a header about auto-generation to the output file */
676     fputs("# This file has been auto-generated by i3-config-wizard(1).\n", ks_config);
677     fputs("# It will not be overwritten, so edit it as you like.\n", ks_config);
678     fputs("#\n", ks_config);
679     fputs("# Should you change your keyboard layout some time, delete\n", ks_config);
680     fputs("# this file and re-run i3-config-wizard(1).\n", ks_config);
681     fputs("#\n", ks_config);
682
683 #ifdef USE_FGETLN
684     char *buf = NULL;
685     while ((buf = fgetln(kc_config, &len)) != NULL) {
686         /* fgetln does not return null-terminated strings */
687         FREE(line);
688         sasprintf(&line, "%.*s", len, buf);
689 #else
690     size_t linecap = 0;
691     while ((read = getline(&line, &linecap, kc_config)) != -1) {
692         len = strlen(line);
693 #endif
694         /* skip the warning block at the beginning of the input file */
695         if (head_of_file &&
696             strncmp("# WARNING", line, strlen("# WARNING")) == 0)
697             continue;
698
699         head_of_file = false;
700
701         /* Skip leading whitespace */
702         char *walk = line;
703         while (isspace(*walk) && walk < (line + len)) {
704             /* Pre-output the skipped whitespaces to keep proper indentation */
705             fputc(*walk, ks_config);
706             walk++;
707         }
708
709         /* Set the modifier the user chose */
710         if (strncmp(walk, "set $mod ", strlen("set $mod ")) == 0) {
711             if (modifier == MOD_Mod1)
712                 fputs("set $mod Mod1\n", ks_config);
713             else
714                 fputs("set $mod Mod4\n", ks_config);
715             continue;
716         }
717
718         /* Check for 'bindcode'. If it’s not a bindcode line, we
719          * just copy it to the output file */
720         if (strncmp(walk, "bindcode", strlen("bindcode")) != 0) {
721             fputs(walk, ks_config);
722             continue;
723         }
724         char *result = rewrite_binding(walk);
725         fputs(result, ks_config);
726         free(result);
727     }
728
729     /* sync to do our best in order to have the file really stored on disk */
730     fflush(ks_config);
731     fsync(fileno(ks_config));
732
733 #ifndef USE_FGETLN
734     free(line);
735 #endif
736
737     fclose(kc_config);
738     fclose(ks_config);
739
740     /* tell i3 to reload the config file */
741     int sockfd = ipc_connect(socket_path);
742     ipc_send_message(sockfd, strlen("reload"), 0, (uint8_t *)"reload");
743     close(sockfd);
744
745     exit(0);
746 }
747
748 int main(int argc, char *argv[]) {
749     char *xdg_config_home;
750     socket_path = getenv("I3SOCK");
751     char *pattern = "pango:monospace 8";
752     char *patternbold = "pango:monospace bold 8";
753     int o, option_index = 0;
754
755     static struct option long_options[] = {
756         {"socket", required_argument, 0, 's'},
757         {"version", no_argument, 0, 'v'},
758         {"limit", required_argument, 0, 'l'},
759         {"prompt", required_argument, 0, 'P'},
760         {"prefix", required_argument, 0, 'p'},
761         {"font", required_argument, 0, 'f'},
762         {"help", no_argument, 0, 'h'},
763         {0, 0, 0, 0}};
764
765     char *options_string = "s:vh";
766
767     while ((o = getopt_long(argc, argv, options_string, long_options, &option_index)) != -1) {
768         switch (o) {
769             case 's':
770                 FREE(socket_path);
771                 socket_path = sstrdup(optarg);
772                 break;
773             case 'v':
774                 printf("i3-config-wizard " I3_VERSION "\n");
775                 return 0;
776             case 'h':
777                 printf("i3-config-wizard " I3_VERSION "\n");
778                 printf("i3-config-wizard [-s <socket>] [-v]\n");
779                 return 0;
780         }
781     }
782
783     char *path = get_config_path(NULL, false);
784     if (path != NULL) {
785         printf("The config file \"%s\" already exists. Exiting.\n", path);
786         free(path);
787         return 0;
788     }
789
790     /* Always write to $XDG_CONFIG_HOME/i3/config by default. */
791     if ((xdg_config_home = getenv("XDG_CONFIG_HOME")) == NULL)
792         xdg_config_home = "~/.config";
793
794     xdg_config_home = resolve_tilde(xdg_config_home);
795     sasprintf(&config_path, "%s/i3/config", xdg_config_home);
796
797     /* Create $XDG_CONFIG_HOME/i3 if it does not yet exist */
798     char *config_dir;
799     struct stat stbuf;
800     sasprintf(&config_dir, "%s/i3", xdg_config_home);
801     if (stat(config_dir, &stbuf) != 0)
802         if (mkdirp(config_dir, DEFAULT_DIR_MODE) != 0)
803             err(EXIT_FAILURE, "mkdirp(%s) failed", config_dir);
804     free(config_dir);
805     free(xdg_config_home);
806
807     int fd;
808     if ((fd = open(config_path, O_CREAT | O_RDWR, 0644)) == -1) {
809         printf("Cannot open file \"%s\" for writing: %s. Exiting.\n", config_path, strerror(errno));
810         return 0;
811     }
812     close(fd);
813     unlink(config_path);
814
815     int screen;
816     if ((conn = xcb_connect(NULL, &screen)) == NULL ||
817         xcb_connection_has_error(conn))
818         errx(1, "Cannot open display\n");
819
820     if (xkb_x11_setup_xkb_extension(conn,
821                                     XKB_X11_MIN_MAJOR_XKB_VERSION,
822                                     XKB_X11_MIN_MINOR_XKB_VERSION,
823                                     0,
824                                     NULL,
825                                     NULL,
826                                     &xkb_base_event,
827                                     &xkb_base_error) != 1)
828         errx(EXIT_FAILURE, "Could not setup XKB extension.");
829
830     if (socket_path == NULL)
831         socket_path = root_atom_contents("I3_SOCKET_PATH", conn, screen);
832
833     if (socket_path == NULL)
834         socket_path = "/tmp/i3-ipc.sock";
835
836     keysyms = xcb_key_symbols_alloc(conn);
837     xcb_get_modifier_mapping_cookie_t modmap_cookie;
838     modmap_cookie = xcb_get_modifier_mapping(conn);
839     symbols = xcb_key_symbols_alloc(conn);
840
841 /* Place requests for the atoms we need as soon as possible */
842 #define xmacro(atom) \
843     xcb_intern_atom_cookie_t atom##_cookie = xcb_intern_atom(conn, 0, strlen(#atom), #atom);
844 #include "atoms.xmacro"
845 #undef xmacro
846
847     root_screen = xcb_aux_get_screen(conn, screen);
848     root = root_screen->root;
849
850     if (!(modmap_reply = xcb_get_modifier_mapping_reply(conn, modmap_cookie, NULL)))
851         errx(EXIT_FAILURE, "Could not get modifier mapping\n");
852
853     xcb_numlock_mask = get_mod_mask_for(XCB_NUM_LOCK, symbols, modmap_reply);
854
855     font = load_font(pattern, true);
856     bold_font = load_font(patternbold, true);
857
858     /* Determine character width in the default font. */
859     set_font(&font);
860     char_width = predict_text_width(i3string_from_utf8("a"));
861
862     /* Open an input window */
863     win = xcb_generate_id(conn);
864     xcb_create_window(
865         conn,
866         XCB_COPY_FROM_PARENT,
867         win,                                                                /* the window id */
868         root,                                                               /* parent == root */
869         logical_px(490), logical_px(297), logical_px(300), window_height(), /* dimensions */
870         0,                                                                  /* X11 border = 0, we draw our own */
871         XCB_WINDOW_CLASS_INPUT_OUTPUT,
872         XCB_WINDOW_CLASS_COPY_FROM_PARENT, /* copy visual from parent */
873         XCB_CW_BACK_PIXEL | XCB_CW_EVENT_MASK,
874         (uint32_t[]){
875             0, /* back pixel: black */
876             XCB_EVENT_MASK_EXPOSURE |
877                 XCB_EVENT_MASK_BUTTON_PRESS});
878
879     /* Map the window (make it visible) */
880     xcb_map_window(conn, win);
881
882 /* Setup NetWM atoms */
883 #define xmacro(name)                                                                       \
884     do {                                                                                   \
885         xcb_intern_atom_reply_t *reply = xcb_intern_atom_reply(conn, name##_cookie, NULL); \
886         if (!reply)                                                                        \
887             errx(EXIT_FAILURE, "Could not get atom " #name "\n");                          \
888                                                                                            \
889         A_##name = reply->atom;                                                            \
890         free(reply);                                                                       \
891     } while (0);
892 #include "atoms.xmacro"
893 #undef xmacro
894
895     /* Set dock mode */
896     xcb_change_property(conn,
897                         XCB_PROP_MODE_REPLACE,
898                         win,
899                         A__NET_WM_WINDOW_TYPE,
900                         A_ATOM,
901                         32,
902                         1,
903                         (unsigned char *)&A__NET_WM_WINDOW_TYPE_DIALOG);
904
905     /* Set window title */
906     xcb_change_property(conn,
907                         XCB_PROP_MODE_REPLACE,
908                         win,
909                         A__NET_WM_NAME,
910                         A_UTF8_STRING,
911                         8,
912                         strlen("i3: first configuration"),
913                         "i3: first configuration");
914
915     /* Create pixmap */
916     pixmap = xcb_generate_id(conn);
917     pixmap_gc = xcb_generate_id(conn);
918     xcb_create_pixmap(conn, root_screen->root_depth, pixmap, win, logical_px(500), logical_px(500));
919     xcb_create_gc(conn, pixmap_gc, pixmap, 0, 0);
920
921     /* Grab the keyboard to get all input */
922     xcb_flush(conn);
923
924     /* Try (repeatedly, if necessary) to grab the keyboard. We might not
925      * get the keyboard at the first attempt because of the keybinding
926      * still being active when started via a wm’s keybinding. */
927     xcb_grab_keyboard_cookie_t cookie;
928     xcb_grab_keyboard_reply_t *reply = NULL;
929
930     int count = 0;
931     while ((reply == NULL || reply->status != XCB_GRAB_STATUS_SUCCESS) && (count++ < 500)) {
932         cookie = xcb_grab_keyboard(conn, false, win, XCB_CURRENT_TIME, XCB_GRAB_MODE_ASYNC, XCB_GRAB_MODE_ASYNC);
933         reply = xcb_grab_keyboard_reply(conn, cookie, NULL);
934         usleep(1000);
935     }
936
937     if (reply->status != XCB_GRAB_STATUS_SUCCESS) {
938         fprintf(stderr, "Could not grab keyboard, status = %d\n", reply->status);
939         exit(-1);
940     }
941
942     xcb_flush(conn);
943
944     xcb_generic_event_t *event;
945     while ((event = xcb_wait_for_event(conn)) != NULL) {
946         if (event->response_type == 0) {
947             fprintf(stderr, "X11 Error received! sequence %x\n", event->sequence);
948             continue;
949         }
950
951         /* Strip off the highest bit (set if the event is generated) */
952         int type = (event->response_type & 0x7F);
953
954         switch (type) {
955             case XCB_KEY_PRESS:
956                 handle_key_press(NULL, conn, (xcb_key_press_event_t *)event);
957                 break;
958
959             /* TODO: handle mappingnotify */
960
961             case XCB_BUTTON_PRESS:
962                 handle_button_press((xcb_button_press_event_t *)event);
963                 break;
964
965             case XCB_EXPOSE:
966                 handle_expose();
967                 break;
968         }
969
970         free(event);
971     }
972
973     return 0;
974 }