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