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