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