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