]> git.sur5r.net Git - i3/i3/blob - i3-config-wizard/main.c
Fix clang -Wextra except -Wunused-parameter.
[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 ((size_t)(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(), errorlog() and debuglog() 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 void debuglog(char *fmt, ...) {
443 }
444
445 /*
446  * This function resolves ~ in pathnames.
447  * It may resolve wildcards in the first part of the path, but if no match
448  * or multiple matches are found, it just returns a copy of path as given.
449  *
450  */
451 static char *resolve_tilde(const char *path) {
452     static glob_t globbuf;
453     char *head, *tail, *result;
454
455     tail = strchr(path, '/');
456     head = strndup(path, tail ? tail - path : strlen(path));
457
458     int res = glob(head, GLOB_TILDE, NULL, &globbuf);
459     free(head);
460     /* no match, or many wildcard matches are bad */
461     if (res == GLOB_NOMATCH || globbuf.gl_pathc != 1)
462         result = strdup(path);
463     else if (res != 0) {
464         err(1, "glob() failed");
465     } else {
466         head = globbuf.gl_pathv[0];
467         result = calloc(1, strlen(head) + (tail ? strlen(tail) : 0) + 1);
468         strncpy(result, head, strlen(head));
469         if (tail)
470             strncat(result, tail, strlen(tail));
471     }
472     globfree(&globbuf);
473
474     return result;
475 }
476
477 /*
478  * Handles expose events, that is, draws the window contents.
479  *
480  */
481 static int handle_expose() {
482     /* re-draw the background */
483     xcb_rectangle_t border = {0, 0, 300, (15 * font.height) + 8};
484     xcb_change_gc(conn, pixmap_gc, XCB_GC_FOREGROUND, (uint32_t[]){ get_colorpixel("#000000") });
485     xcb_poly_fill_rectangle(conn, pixmap, pixmap_gc, 1, &border);
486
487     set_font(&font);
488
489 #define txt(x, row, text) \
490     draw_text_ascii(text, pixmap, pixmap_gc,\
491             x, (row - 1) * font.height + 4, 300 - x * 2)
492
493     if (current_step == STEP_WELCOME) {
494         /* restore font color */
495         set_font_colors(pixmap_gc, get_colorpixel("#FFFFFF"), get_colorpixel("#000000"));
496
497         txt(10, 2, "You have not configured i3 yet.");
498         txt(10, 3, "Do you want me to generate ~/.i3/config?");
499         txt(85, 5, "Yes, generate ~/.i3/config");
500         txt(85, 7, "No, I will use the defaults");
501
502         /* green */
503         set_font_colors(pixmap_gc, get_colorpixel("#00FF00"), get_colorpixel("#000000"));
504         txt(25, 5, "<Enter>");
505
506         /* red */
507         set_font_colors(pixmap_gc, get_colorpixel("#FF0000"), get_colorpixel("#000000"));
508         txt(31, 7, "<ESC>");
509     }
510
511     if (current_step == STEP_GENERATE) {
512         set_font_colors(pixmap_gc, get_colorpixel("#FFFFFF"), get_colorpixel("#000000"));
513
514         txt(10, 2, "Please choose either:");
515         txt(85, 4, "Win as default modifier");
516         txt(85, 5, "Alt as default modifier");
517         txt(10, 7, "Afterwards, press");
518         txt(85, 9, "to write ~/.i3/config");
519         txt(85, 10, "to abort");
520
521         /* the not-selected modifier */
522         if (modifier == MOD_Mod4)
523             txt(31, 5, "<Alt>");
524         else txt(31, 4, "<Win>");
525
526         /* the selected modifier */
527         set_font(&bold_font);
528         set_font_colors(pixmap_gc, get_colorpixel("#FFFFFF"), get_colorpixel("#000000"));
529         if (modifier == MOD_Mod4)
530             txt(10, 4, "-> <Win>");
531         else txt(10, 5, "-> <Alt>");
532
533         /* green */
534         set_font(&font);
535         set_font_colors(pixmap_gc, get_colorpixel("#00FF00"), get_colorpixel("#000000"));
536         txt(25, 9, "<Enter>");
537
538         /* red */
539         set_font_colors(pixmap_gc, get_colorpixel("#FF0000"), get_colorpixel("#000000"));
540         txt(31, 10, "<ESC>");
541     }
542
543     /* Copy the contents of the pixmap to the real window */
544     xcb_copy_area(conn, pixmap, win, pixmap_gc, 0, 0, 0, 0, /* */ 500, 500);
545     xcb_flush(conn);
546
547     return 1;
548 }
549
550 static int handle_key_press(void *ignored, xcb_connection_t *conn, xcb_key_press_event_t *event) {
551     printf("Keypress %d, state raw = %d\n", event->detail, event->state);
552
553     /* Remove the numlock bit, all other bits are modifiers we can bind to */
554     uint16_t state_filtered = event->state & ~(xcb_numlock_mask | XCB_MOD_MASK_LOCK);
555     /* Only use the lower 8 bits of the state (modifier masks) so that mouse
556      * button masks are filtered out */
557     state_filtered &= 0xFF;
558
559     xcb_keysym_t sym = xcb_key_press_lookup_keysym(symbols, event, state_filtered);
560
561     printf("sym = %c (%d)\n", sym, sym);
562
563     if (sym == XK_Return || sym == XK_KP_Enter) {
564         if (current_step == STEP_WELCOME) {
565             current_step = STEP_GENERATE;
566             /* Set window title */
567             xcb_change_property(conn,
568                 XCB_PROP_MODE_REPLACE,
569                 win,
570                 A__NET_WM_NAME,
571                 A_UTF8_STRING,
572                 8,
573                 strlen("i3: generate config"),
574                 "i3: generate config");
575             xcb_flush(conn);
576         }
577         else finish();
578     }
579
580     /* cancel any time */
581     if (sym == XK_Escape)
582         exit(0);
583
584     /* Check if this is Mod1 or Mod4. The modmap contains Shift, Lock, Control,
585      * Mod1, Mod2, Mod3, Mod4, Mod5 (in that order) */
586     xcb_keycode_t *modmap = xcb_get_modifier_mapping_keycodes(modmap_reply);
587     /* Mod1? */
588     int mask = 3;
589     for (int i = 0; i < modmap_reply->keycodes_per_modifier; i++) {
590         xcb_keycode_t code = modmap[(mask * modmap_reply->keycodes_per_modifier) + i];
591         if (code == XCB_NONE)
592             continue;
593         printf("Modifier keycode for Mod1: 0x%02x\n", code);
594         if (code == event->detail) {
595             modifier = MOD_Mod1;
596             printf("This is Mod1!\n");
597         }
598     }
599
600     /* Mod4? */
601     mask = 6;
602     for (int i = 0; i < modmap_reply->keycodes_per_modifier; i++) {
603         xcb_keycode_t code = modmap[(mask * modmap_reply->keycodes_per_modifier) + i];
604         if (code == XCB_NONE)
605             continue;
606         printf("Modifier keycode for Mod4: 0x%02x\n", code);
607         if (code == event->detail) {
608             modifier = MOD_Mod4;
609             printf("This is Mod4!\n");
610         }
611     }
612
613     handle_expose();
614     return 1;
615 }
616
617 /*
618  * Handle button presses to make clicking on "<win>" and "<alt>" work
619  *
620  */
621 static void handle_button_press(xcb_button_press_event_t* event) {
622     if (current_step != STEP_GENERATE)
623         return;
624
625     if (event->event_x >= 32 && event->event_x <= 68 &&
626         event->event_y >= 45 && event->event_y <= 54) {
627         modifier = MOD_Mod4;
628         handle_expose();
629     }
630
631     if (event->event_x >= 32 && event->event_x <= 68 &&
632         event->event_y >= 56 && event->event_y <= 70) {
633         modifier = MOD_Mod1;
634         handle_expose();
635     }
636
637     return;
638 }
639
640 /*
641  * Creates the config file and tells i3 to reload.
642  *
643  */
644 static void finish() {
645     printf("creating \"%s\"...\n", config_path);
646
647     if (!(dpy = XOpenDisplay(NULL)))
648         errx(1, "Could not connect to X11");
649
650     FILE *kc_config = fopen(SYSCONFDIR "/i3/config.keycodes", "r");
651     if (kc_config == NULL)
652         err(1, "Could not open input file \"%s\"", SYSCONFDIR "/i3/config.keycodes");
653
654     FILE *ks_config = fopen(config_path, "w");
655     if (ks_config == NULL)
656         err(1, "Could not open output config file \"%s\"", config_path);
657     free(config_path);
658
659     char *line = NULL;
660     size_t len = 0;
661 #ifndef USE_FGETLN
662     ssize_t read;
663 #endif
664     bool head_of_file = true;
665
666     /* write a header about auto-generation to the output file */
667     fputs("# This file has been auto-generated by i3-config-wizard(1).\n", ks_config);
668     fputs("# It will not be overwritten, so edit it as you like.\n", ks_config);
669     fputs("#\n", ks_config);
670     fputs("# Should you change your keyboard layout somewhen, delete\n", ks_config);
671     fputs("# this file and re-run i3-config-wizard(1).\n", ks_config);
672     fputs("#\n", ks_config);
673
674 #ifdef USE_FGETLN
675     char *buf = NULL;
676     while ((buf = fgetln(kc_config, &len)) != NULL) {
677         /* fgetln does not return null-terminated strings */
678         FREE(line);
679         sasprintf(&line, "%.*s", len, buf);
680 #else
681     size_t linecap = 0;
682     while ((read = getline(&line, &linecap, kc_config)) != -1) {
683         len = strlen(line);
684 #endif
685         /* skip the warning block at the beginning of the input file */
686         if (head_of_file &&
687             strncmp("# WARNING", line, strlen("# WARNING")) == 0)
688             continue;
689
690         head_of_file = false;
691
692         /* Skip leading whitespace */
693         char *walk = line;
694         while (isspace(*walk) && walk < (line + len)) {
695             /* Pre-output the skipped whitespaces to keep proper indentation */
696             fputc(*walk, ks_config);
697             walk++;
698         }
699
700         /* Set the modifier the user chose */
701         if (strncmp(walk, "set $mod ", strlen("set $mod ")) == 0) {
702             if (modifier == MOD_Mod1)
703                 fputs("set $mod Mod1\n", ks_config);
704             else fputs("set $mod Mod4\n", ks_config);
705             continue;
706         }
707
708         /* Check for 'bindcode'. If it’s not a bindcode line, we
709          * just copy it to the output file */
710         if (strncmp(walk, "bindcode", strlen("bindcode")) != 0) {
711             fputs(walk, ks_config);
712             continue;
713         }
714         char *result = rewrite_binding(walk);
715         fputs(result, ks_config);
716         free(result);
717     }
718
719     /* sync to do our best in order to have the file really stored on disk */
720     fflush(ks_config);
721     fsync(fileno(ks_config));
722
723 #ifndef USE_FGETLN
724     free(line);
725 #endif
726
727     fclose(kc_config);
728     fclose(ks_config);
729
730     /* tell i3 to reload the config file */
731     int sockfd = ipc_connect(socket_path);
732     ipc_send_message(sockfd, strlen("reload"), 0, (uint8_t*)"reload");
733     close(sockfd);
734
735     exit(0);
736 }
737
738 int main(int argc, char *argv[]) {
739     config_path = resolve_tilde("~/.i3/config");
740     socket_path = getenv("I3SOCK");
741     char *pattern = "-misc-fixed-medium-r-normal--13-120-75-75-C-70-iso10646-1";
742     char *patternbold = "-misc-fixed-bold-r-normal--13-120-75-75-C-70-iso10646-1";
743     int o, option_index = 0;
744
745     static struct option long_options[] = {
746         {"socket", required_argument, 0, 's'},
747         {"version", no_argument, 0, 'v'},
748         {"limit", required_argument, 0, 'l'},
749         {"prompt", required_argument, 0, 'P'},
750         {"prefix", required_argument, 0, 'p'},
751         {"font", required_argument, 0, 'f'},
752         {"help", no_argument, 0, 'h'},
753         {0, 0, 0, 0}
754     };
755
756     char *options_string = "s:vh";
757
758     while ((o = getopt_long(argc, argv, options_string, long_options, &option_index)) != -1) {
759         switch (o) {
760             case 's':
761                 FREE(socket_path);
762                 socket_path = strdup(optarg);
763                 break;
764             case 'v':
765                 printf("i3-config-wizard " I3_VERSION "\n");
766                 return 0;
767             case 'h':
768                 printf("i3-config-wizard " I3_VERSION "\n");
769                 printf("i3-config-wizard [-s <socket>] [-v]\n");
770                 return 0;
771         }
772     }
773
774     /* Check if the destination config file does not exist but the path is
775      * writable. If not, exit now, this program is not useful in that case. */
776     struct stat stbuf;
777     if (stat(config_path, &stbuf) == 0) {
778         printf("The config file \"%s\" already exists. Exiting.\n", config_path);
779         return 0;
780     }
781
782     /* Create ~/.i3 if it does not yet exist */
783     char *config_dir = resolve_tilde("~/.i3");
784     if (stat(config_dir, &stbuf) != 0)
785         if (mkdir(config_dir, 0755) == -1)
786             err(1, "mkdir(%s) failed", config_dir);
787     free(config_dir);
788
789     int fd;
790     if ((fd = open(config_path, O_CREAT | O_RDWR, 0644)) == -1) {
791         printf("Cannot open file \"%s\" for writing: %s. Exiting.\n", config_path, strerror(errno));
792         return 0;
793     }
794     close(fd);
795     unlink(config_path);
796
797     int screen;
798     if ((conn = xcb_connect(NULL, &screen)) == NULL ||
799         xcb_connection_has_error(conn))
800         errx(1, "Cannot open display\n");
801
802     if (socket_path == NULL)
803         socket_path = root_atom_contents("I3_SOCKET_PATH", conn, screen);
804
805     if (socket_path == NULL)
806         socket_path = "/tmp/i3-ipc.sock";
807
808     keysyms = xcb_key_symbols_alloc(conn);
809     xcb_get_modifier_mapping_cookie_t modmap_cookie;
810     modmap_cookie = xcb_get_modifier_mapping(conn);
811     symbols = xcb_key_symbols_alloc(conn);
812
813     /* Place requests for the atoms we need as soon as possible */
814     #define xmacro(atom) \
815         xcb_intern_atom_cookie_t atom ## _cookie = xcb_intern_atom(conn, 0, strlen(#atom), #atom);
816     #include "atoms.xmacro"
817     #undef xmacro
818
819     root_screen = xcb_aux_get_screen(conn, screen);
820     root = root_screen->root;
821
822     if (!(modmap_reply = xcb_get_modifier_mapping_reply(conn, modmap_cookie, NULL)))
823         errx(EXIT_FAILURE, "Could not get modifier mapping\n");
824
825     xcb_numlock_mask = get_mod_mask_for(XCB_NUM_LOCK, symbols, modmap_reply);
826
827     font = load_font(pattern, true);
828     bold_font = load_font(patternbold, true);
829
830     /* Open an input window */
831     win = xcb_generate_id(conn);
832     xcb_create_window(
833         conn,
834         XCB_COPY_FROM_PARENT,
835         win, /* the window id */
836         root, /* parent == root */
837         490, 297, 300, 205, /* dimensions */
838         0, /* X11 border = 0, we draw our own */
839         XCB_WINDOW_CLASS_INPUT_OUTPUT,
840         XCB_WINDOW_CLASS_COPY_FROM_PARENT, /* copy visual from parent */
841         XCB_CW_BACK_PIXEL | XCB_CW_EVENT_MASK,
842         (uint32_t[]){
843             0, /* back pixel: black */
844             XCB_EVENT_MASK_EXPOSURE |
845             XCB_EVENT_MASK_BUTTON_PRESS
846         });
847
848     /* Map the window (make it visible) */
849     xcb_map_window(conn, win);
850
851     /* Setup NetWM atoms */
852     #define xmacro(name) \
853         do { \
854             xcb_intern_atom_reply_t *reply = xcb_intern_atom_reply(conn, name ## _cookie, NULL); \
855             if (!reply) \
856                 errx(EXIT_FAILURE, "Could not get atom " # name "\n"); \
857             \
858             A_ ## name = reply->atom; \
859             free(reply); \
860         } while (0);
861     #include "atoms.xmacro"
862     #undef xmacro
863
864     /* Set dock mode */
865     xcb_change_property(conn,
866         XCB_PROP_MODE_REPLACE,
867         win,
868         A__NET_WM_WINDOW_TYPE,
869         A_ATOM,
870         32,
871         1,
872         (unsigned char*) &A__NET_WM_WINDOW_TYPE_DIALOG);
873
874     /* Set window title */
875     xcb_change_property(conn,
876         XCB_PROP_MODE_REPLACE,
877         win,
878         A__NET_WM_NAME,
879         A_UTF8_STRING,
880         8,
881         strlen("i3: first configuration"),
882         "i3: first configuration");
883
884     /* Create pixmap */
885     pixmap = xcb_generate_id(conn);
886     pixmap_gc = xcb_generate_id(conn);
887     xcb_create_pixmap(conn, root_screen->root_depth, pixmap, win, 500, 500);
888     xcb_create_gc(conn, pixmap_gc, pixmap, 0, 0);
889
890     /* Grab the keyboard to get all input */
891     xcb_flush(conn);
892
893     /* Try (repeatedly, if necessary) to grab the keyboard. We might not
894      * get the keyboard at the first attempt because of the keybinding
895      * still being active when started via a wm’s keybinding. */
896     xcb_grab_keyboard_cookie_t cookie;
897     xcb_grab_keyboard_reply_t *reply = NULL;
898
899     int count = 0;
900     while ((reply == NULL || reply->status != XCB_GRAB_STATUS_SUCCESS) && (count++ < 500)) {
901         cookie = xcb_grab_keyboard(conn, false, win, XCB_CURRENT_TIME, XCB_GRAB_MODE_ASYNC, XCB_GRAB_MODE_ASYNC);
902         reply = xcb_grab_keyboard_reply(conn, cookie, NULL);
903         usleep(1000);
904     }
905
906     if (reply->status != XCB_GRAB_STATUS_SUCCESS) {
907         fprintf(stderr, "Could not grab keyboard, status = %d\n", reply->status);
908         exit(-1);
909     }
910
911     xcb_flush(conn);
912
913     xcb_generic_event_t *event;
914     while ((event = xcb_wait_for_event(conn)) != NULL) {
915         if (event->response_type == 0) {
916             fprintf(stderr, "X11 Error received! sequence %x\n", event->sequence);
917             continue;
918         }
919
920         /* Strip off the highest bit (set if the event is generated) */
921         int type = (event->response_type & 0x7F);
922
923         switch (type) {
924             case XCB_KEY_PRESS:
925                 handle_key_press(NULL, conn, (xcb_key_press_event_t*)event);
926                 break;
927
928             /* TODO: handle mappingnotify */
929
930             case XCB_BUTTON_PRESS:
931                 handle_button_press((xcb_button_press_event_t*)event);
932                 break;
933
934             case XCB_EXPOSE:
935                 handle_expose();
936                 break;
937         }
938
939         free(event);
940     }
941
942     return 0;
943 }