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