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