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