]> git.sur5r.net Git - i3/i3/blob - i3-config-wizard/main.c
46cf8aa8d9e8d2da8fc3e163829dafa914133795
[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__) || (defined(__FreeBSD__) && __FreeBSD_version < 800000) || defined(__OpenBSD__)
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 <ev.h>
25 #include <stdio.h>
26 #include <sys/types.h>
27 #include <stdlib.h>
28 #include <stdbool.h>
29 #include <unistd.h>
30 #include <string.h>
31 #include <ctype.h>
32 #include <errno.h>
33 #include <err.h>
34 #include <stdint.h>
35 #include <getopt.h>
36 #include <limits.h>
37 #include <sys/stat.h>
38 #include <fcntl.h>
39 #include <glob.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
49 /* We need SYSCONFDIR for the path to the keycode config template, so raise an
50  * error if it’s not defined for whatever reason */
51 #ifndef SYSCONFDIR
52 #error "SYSCONFDIR not defined"
53 #endif
54
55 #define FREE(pointer) do { \
56     if (pointer != NULL) { \
57         free(pointer); \
58         pointer = NULL; \
59     } \
60 } \
61 while (0)
62
63 #include "xcb.h"
64 #include "libi3.h"
65
66 enum { STEP_WELCOME, STEP_GENERATE } current_step = STEP_WELCOME;
67 enum { MOD_Mod1, MOD_Mod4 } modifier = MOD_Mod4;
68
69 static char *config_path;
70 static uint32_t xcb_numlock_mask;
71 xcb_connection_t *conn;
72 xcb_screen_t *root_screen;
73 static xcb_get_modifier_mapping_reply_t *modmap_reply;
74 static i3Font font;
75 static i3Font bold_font;
76 static char *socket_path;
77 static xcb_window_t win;
78 static xcb_pixmap_t pixmap;
79 static xcb_gcontext_t pixmap_gc;
80 static xcb_key_symbols_t *symbols;
81 xcb_window_t root;
82 Display *dpy;
83
84 char *rewrite_binding(const char *bindingline);
85 static void finish();
86
87 /*
88  * This function resolves ~ in pathnames.
89  * It may resolve wildcards in the first part of the path, but if no match
90  * or multiple matches are found, it just returns a copy of path as given.
91  *
92  */
93 static char *resolve_tilde(const char *path) {
94     static glob_t globbuf;
95     char *head, *tail, *result;
96
97     tail = strchr(path, '/');
98     head = strndup(path, tail ? tail - path : strlen(path));
99
100     int res = glob(head, GLOB_TILDE, NULL, &globbuf);
101     free(head);
102     /* no match, or many wildcard matches are bad */
103     if (res == GLOB_NOMATCH || globbuf.gl_pathc != 1)
104         result = strdup(path);
105     else if (res != 0) {
106         err(1, "glob() failed");
107     } else {
108         head = globbuf.gl_pathv[0];
109         result = calloc(1, strlen(head) + (tail ? strlen(tail) : 0) + 1);
110         strncpy(result, head, strlen(head));
111         if (tail)
112             strncat(result, tail, strlen(tail));
113     }
114     globfree(&globbuf);
115
116     return result;
117 }
118
119 /*
120  * Handles expose events, that is, draws the window contents.
121  *
122  */
123 static int handle_expose() {
124     /* re-draw the background */
125     xcb_rectangle_t border = {0, 0, 300, (15 * font.height) + 8};
126     xcb_change_gc(conn, pixmap_gc, XCB_GC_FOREGROUND, (uint32_t[]){ get_colorpixel("#000000") });
127     xcb_poly_fill_rectangle(conn, pixmap, pixmap_gc, 1, &border);
128
129     set_font(&font);
130
131 #define txt(x, row, text) \
132     draw_text_ascii(text, pixmap, pixmap_gc,\
133             x, (row - 1) * font.height + 4, 300 - x * 2)
134
135     if (current_step == STEP_WELCOME) {
136         /* restore font color */
137         set_font_colors(pixmap_gc, get_colorpixel("#FFFFFF"), get_colorpixel("#000000"));
138
139         txt(10, 2, "You have not configured i3 yet.");
140         txt(10, 3, "Do you want me to generate ~/.i3/config?");
141         txt(85, 5, "Yes, generate ~/.i3/config");
142         txt(85, 7, "No, I will use the defaults");
143
144         /* green */
145         set_font_colors(pixmap_gc, get_colorpixel("#00FF00"), get_colorpixel("#000000"));
146         txt(25, 5, "<Enter>");
147
148         /* red */
149         set_font_colors(pixmap_gc, get_colorpixel("#FF0000"), get_colorpixel("#000000"));
150         txt(31, 7, "<ESC>");
151     }
152
153     if (current_step == STEP_GENERATE) {
154         set_font_colors(pixmap_gc, get_colorpixel("#FFFFFF"), get_colorpixel("#000000"));
155
156         txt(10, 2, "Please choose either:");
157         txt(85, 4, "Win as default modifier");
158         txt(85, 5, "Alt as default modifier");
159         txt(10, 7, "Afterwards, press");
160         txt(85, 9, "to write ~/.i3/config");
161         txt(85, 10, "to abort");
162
163         /* the not-selected modifier */
164         if (modifier == MOD_Mod4)
165             txt(31, 5, "<Alt>");
166         else txt(31, 4, "<Win>");
167
168         /* the selected modifier */
169         set_font(&bold_font);
170         set_font_colors(pixmap_gc, get_colorpixel("#FFFFFF"), get_colorpixel("#000000"));
171         if (modifier == MOD_Mod4)
172             txt(10, 4, "-> <Win>");
173         else txt(10, 5, "-> <Alt>");
174
175         /* green */
176         set_font(&font);
177         set_font_colors(pixmap_gc, get_colorpixel("#00FF00"), get_colorpixel("#000000"));
178         txt(25, 9, "<Enter>");
179
180         /* red */
181         set_font_colors(pixmap_gc, get_colorpixel("#FF0000"), get_colorpixel("#000000"));
182         txt(31, 10, "<ESC>");
183     }
184
185     /* Copy the contents of the pixmap to the real window */
186     xcb_copy_area(conn, pixmap, win, pixmap_gc, 0, 0, 0, 0, /* */ 500, 500);
187     xcb_flush(conn);
188
189     return 1;
190 }
191
192 static int handle_key_press(void *ignored, xcb_connection_t *conn, xcb_key_press_event_t *event) {
193     printf("Keypress %d, state raw = %d\n", event->detail, event->state);
194
195     /* Remove the numlock bit, all other bits are modifiers we can bind to */
196     uint16_t state_filtered = event->state & ~(xcb_numlock_mask | XCB_MOD_MASK_LOCK);
197     /* Only use the lower 8 bits of the state (modifier masks) so that mouse
198      * button masks are filtered out */
199     state_filtered &= 0xFF;
200
201     xcb_keysym_t sym = xcb_key_press_lookup_keysym(symbols, event, state_filtered);
202
203     printf("sym = %c (%d)\n", sym, sym);
204
205     if (sym == XK_Return || sym == XK_KP_Enter) {
206         if (current_step == STEP_WELCOME) {
207             current_step = STEP_GENERATE;
208             /* Set window title */
209             xcb_change_property(conn,
210                 XCB_PROP_MODE_REPLACE,
211                 win,
212                 A__NET_WM_NAME,
213                 A_UTF8_STRING,
214                 8,
215                 strlen("i3: generate config"),
216                 "i3: generate config");
217             xcb_flush(conn);
218         }
219         else finish();
220     }
221
222     /* cancel any time */
223     if (sym == XK_Escape)
224         exit(0);
225
226     /* Check if this is Mod1 or Mod4. The modmap contains Shift, Lock, Control,
227      * Mod1, Mod2, Mod3, Mod4, Mod5 (in that order) */
228     xcb_keycode_t *modmap = xcb_get_modifier_mapping_keycodes(modmap_reply);
229     /* Mod1? */
230     int mask = 3;
231     for (int i = 0; i < modmap_reply->keycodes_per_modifier; i++) {
232         xcb_keycode_t code = modmap[(mask * modmap_reply->keycodes_per_modifier) + i];
233         if (code == XCB_NONE)
234             continue;
235         printf("Modifier keycode for Mod1: 0x%02x\n", code);
236         if (code == event->detail) {
237             modifier = MOD_Mod1;
238             printf("This is Mod1!\n");
239         }
240     }
241
242     /* Mod4? */
243     mask = 6;
244     for (int i = 0; i < modmap_reply->keycodes_per_modifier; i++) {
245         xcb_keycode_t code = modmap[(mask * modmap_reply->keycodes_per_modifier) + i];
246         if (code == XCB_NONE)
247             continue;
248         printf("Modifier keycode for Mod4: 0x%02x\n", code);
249         if (code == event->detail) {
250             modifier = MOD_Mod4;
251             printf("This is Mod4!\n");
252         }
253     }
254
255     handle_expose();
256     return 1;
257 }
258
259 /*
260  * Handle button presses to make clicking on "<win>" and "<alt>" work
261  *
262  */
263 static void handle_button_press(xcb_button_press_event_t* event) {
264     if (current_step != STEP_GENERATE)
265         return;
266
267     if (event->event_x >= 32 && event->event_x <= 68 &&
268         event->event_y >= 45 && event->event_y <= 54) {
269         modifier = MOD_Mod4;
270         handle_expose();
271     }
272
273     if (event->event_x >= 32 && event->event_x <= 68 &&
274         event->event_y >= 56 && event->event_y <= 70) {
275         modifier = MOD_Mod1;
276         handle_expose();
277     }
278
279     return;
280 }
281
282 /*
283  * Creates the config file and tells i3 to reload.
284  *
285  */
286 static void finish() {
287     printf("creating \"%s\"...\n", config_path);
288
289     if (!(dpy = XOpenDisplay(NULL)))
290         errx(1, "Could not connect to X11");
291
292     FILE *kc_config = fopen(SYSCONFDIR "/i3/config.keycodes", "r");
293     if (kc_config == NULL)
294         err(1, "Could not open input file \"%s\"", SYSCONFDIR "/i3/config.keycodes");
295
296     FILE *ks_config = fopen(config_path, "w");
297     if (ks_config == NULL)
298         err(1, "Could not open output config file \"%s\"", config_path);
299     free(config_path);
300
301     char *line = NULL;
302     size_t len = 0;
303 #ifndef USE_FGETLN
304     ssize_t read;
305 #endif
306     bool head_of_file = true;
307
308     /* write a header about auto-generation to the output file */
309     fputs("# This file has been auto-generated by i3-config-wizard(1).\n", ks_config);
310     fputs("# It will not be overwritten, so edit it as you like.\n", ks_config);
311     fputs("#\n", ks_config);
312     fputs("# Should you change your keyboard layout somewhen, delete\n", ks_config);
313     fputs("# this file and re-run i3-config-wizard(1).\n", ks_config);
314     fputs("#\n", ks_config);
315
316 #ifdef USE_FGETLN
317     char *buf = NULL;
318     while ((buf = fgetln(kc_config, &len)) != NULL) {
319         /* fgetln does not return null-terminated strings */
320         FREE(line);
321         sasprintf(&line, "%.*s", len, buf);
322 #else
323     size_t linecap = 0;
324     while ((read = getline(&line, &linecap, kc_config)) != -1) {
325         len = strlen(line);
326 #endif
327         /* skip the warning block at the beginning of the input file */
328         if (head_of_file &&
329             strncmp("# WARNING", line, strlen("# WARNING")) == 0)
330             continue;
331
332         head_of_file = false;
333
334         /* Skip leading whitespace */
335         char *walk = line;
336         while (isspace(*walk) && walk < (line + len)) {
337             /* Pre-output the skipped whitespaces to keep proper indentation */
338             fputc(*walk, ks_config);
339             walk++;
340         }
341
342         /* Set the modifier the user chose */
343         if (strncmp(walk, "set $mod ", strlen("set $mod ")) == 0) {
344             if (modifier == MOD_Mod1)
345                 fputs("set $mod Mod1\n", ks_config);
346             else fputs("set $mod Mod4\n", ks_config);
347             continue;
348         }
349
350         /* Check for 'bindcode'. If it’s not a bindcode line, we
351          * just copy it to the output file */
352         if (strncmp(walk, "bindcode", strlen("bindcode")) != 0) {
353             fputs(walk, ks_config);
354             continue;
355         }
356         char *result = rewrite_binding(walk);
357         fputs(result, ks_config);
358         free(result);
359     }
360
361     /* sync to do our best in order to have the file really stored on disk */
362     fflush(ks_config);
363     fsync(fileno(ks_config));
364
365 #ifndef USE_FGETLN
366     free(line);
367 #endif
368
369     fclose(kc_config);
370     fclose(ks_config);
371
372     /* tell i3 to reload the config file */
373     int sockfd = ipc_connect(socket_path);
374     ipc_send_message(sockfd, strlen("reload"), 0, (uint8_t*)"reload");
375     close(sockfd);
376
377     exit(0);
378 }
379
380 int main(int argc, char *argv[]) {
381     config_path = resolve_tilde("~/.i3/config");
382     socket_path = getenv("I3SOCK");
383     char *pattern = "-misc-fixed-medium-r-normal--13-120-75-75-C-70-iso10646-1";
384     char *patternbold = "-misc-fixed-bold-r-normal--13-120-75-75-C-70-iso10646-1";
385     int o, option_index = 0;
386
387     static struct option long_options[] = {
388         {"socket", required_argument, 0, 's'},
389         {"version", no_argument, 0, 'v'},
390         {"limit", required_argument, 0, 'l'},
391         {"prompt", required_argument, 0, 'P'},
392         {"prefix", required_argument, 0, 'p'},
393         {"font", required_argument, 0, 'f'},
394         {"help", no_argument, 0, 'h'},
395         {0, 0, 0, 0}
396     };
397
398     char *options_string = "s:vh";
399
400     while ((o = getopt_long(argc, argv, options_string, long_options, &option_index)) != -1) {
401         switch (o) {
402             case 's':
403                 FREE(socket_path);
404                 socket_path = strdup(optarg);
405                 break;
406             case 'v':
407                 printf("i3-config-wizard " I3_VERSION "\n");
408                 return 0;
409             case 'h':
410                 printf("i3-config-wizard " I3_VERSION "\n");
411                 printf("i3-config-wizard [-s <socket>] [-v]\n");
412                 return 0;
413         }
414     }
415
416     /* Check if the destination config file does not exist but the path is
417      * writable. If not, exit now, this program is not useful in that case. */
418     struct stat stbuf;
419     if (stat(config_path, &stbuf) == 0) {
420         printf("The config file \"%s\" already exists. Exiting.\n", config_path);
421         return 0;
422     }
423
424     /* Create ~/.i3 if it does not yet exist */
425     char *config_dir = resolve_tilde("~/.i3");
426     if (stat(config_dir, &stbuf) != 0)
427         if (mkdir(config_dir, 0755) == -1)
428             err(1, "mkdir(%s) failed", config_dir);
429     free(config_dir);
430
431     int fd;
432     if ((fd = open(config_path, O_CREAT | O_RDWR, 0644)) == -1) {
433         printf("Cannot open file \"%s\" for writing: %s. Exiting.\n", config_path, strerror(errno));
434         return 0;
435     }
436     close(fd);
437     unlink(config_path);
438
439     if (socket_path == NULL)
440         socket_path = root_atom_contents("I3_SOCKET_PATH");
441
442     if (socket_path == NULL)
443         socket_path = "/tmp/i3-ipc.sock";
444
445     int screens;
446     if ((conn = xcb_connect(NULL, &screens)) == NULL ||
447         xcb_connection_has_error(conn))
448         errx(1, "Cannot open display\n");
449
450     xcb_get_modifier_mapping_cookie_t modmap_cookie;
451     modmap_cookie = xcb_get_modifier_mapping(conn);
452     symbols = xcb_key_symbols_alloc(conn);
453
454     /* Place requests for the atoms we need as soon as possible */
455     #define xmacro(atom) \
456         xcb_intern_atom_cookie_t atom ## _cookie = xcb_intern_atom(conn, 0, strlen(#atom), #atom);
457     #include "atoms.xmacro"
458     #undef xmacro
459
460     root_screen = xcb_aux_get_screen(conn, screens);
461     root = root_screen->root;
462
463     if (!(modmap_reply = xcb_get_modifier_mapping_reply(conn, modmap_cookie, NULL)))
464         errx(EXIT_FAILURE, "Could not get modifier mapping\n");
465
466     xcb_numlock_mask = get_mod_mask_for(XCB_NUM_LOCK, symbols, modmap_reply);
467
468     font = load_font(pattern, true);
469     bold_font = load_font(patternbold, true);
470
471     /* Open an input window */
472     win = xcb_generate_id(conn);
473     xcb_create_window(
474         conn,
475         XCB_COPY_FROM_PARENT,
476         win, /* the window id */
477         root, /* parent == root */
478         490, 297, 300, 205, /* dimensions */
479         0, /* X11 border = 0, we draw our own */
480         XCB_WINDOW_CLASS_INPUT_OUTPUT,
481         XCB_WINDOW_CLASS_COPY_FROM_PARENT, /* copy visual from parent */
482         XCB_CW_BACK_PIXEL | XCB_CW_EVENT_MASK,
483         (uint32_t[]){
484             0, /* back pixel: black */
485             XCB_EVENT_MASK_EXPOSURE |
486             XCB_EVENT_MASK_BUTTON_PRESS
487         });
488
489     /* Map the window (make it visible) */
490     xcb_map_window(conn, win);
491
492     /* Setup NetWM atoms */
493     #define xmacro(name) \
494         do { \
495             xcb_intern_atom_reply_t *reply = xcb_intern_atom_reply(conn, name ## _cookie, NULL); \
496             if (!reply) \
497                 errx(EXIT_FAILURE, "Could not get atom " # name "\n"); \
498             \
499             A_ ## name = reply->atom; \
500             free(reply); \
501         } while (0);
502     #include "atoms.xmacro"
503     #undef xmacro
504
505     /* Set dock mode */
506     xcb_change_property(conn,
507         XCB_PROP_MODE_REPLACE,
508         win,
509         A__NET_WM_WINDOW_TYPE,
510         A_ATOM,
511         32,
512         1,
513         (unsigned char*) &A__NET_WM_WINDOW_TYPE_DIALOG);
514
515     /* Set window title */
516     xcb_change_property(conn,
517         XCB_PROP_MODE_REPLACE,
518         win,
519         A__NET_WM_NAME,
520         A_UTF8_STRING,
521         8,
522         strlen("i3: first configuration"),
523         "i3: first configuration");
524
525     /* Create pixmap */
526     pixmap = xcb_generate_id(conn);
527     pixmap_gc = xcb_generate_id(conn);
528     xcb_create_pixmap(conn, root_screen->root_depth, pixmap, win, 500, 500);
529     xcb_create_gc(conn, pixmap_gc, pixmap, 0, 0);
530
531     /* Grab the keyboard to get all input */
532     xcb_flush(conn);
533
534     /* Try (repeatedly, if necessary) to grab the keyboard. We might not
535      * get the keyboard at the first attempt because of the keybinding
536      * still being active when started via a wm’s keybinding. */
537     xcb_grab_keyboard_cookie_t cookie;
538     xcb_grab_keyboard_reply_t *reply = NULL;
539
540     int count = 0;
541     while ((reply == NULL || reply->status != XCB_GRAB_STATUS_SUCCESS) && (count++ < 500)) {
542         cookie = xcb_grab_keyboard(conn, false, win, XCB_CURRENT_TIME, XCB_GRAB_MODE_ASYNC, XCB_GRAB_MODE_ASYNC);
543         reply = xcb_grab_keyboard_reply(conn, cookie, NULL);
544         usleep(1000);
545     }
546
547     if (reply->status != XCB_GRAB_STATUS_SUCCESS) {
548         fprintf(stderr, "Could not grab keyboard, status = %d\n", reply->status);
549         exit(-1);
550     }
551
552     xcb_flush(conn);
553
554     xcb_generic_event_t *event;
555     while ((event = xcb_wait_for_event(conn)) != NULL) {
556         if (event->response_type == 0) {
557             fprintf(stderr, "X11 Error received! sequence %x\n", event->sequence);
558             continue;
559         }
560
561         /* Strip off the highest bit (set if the event is generated) */
562         int type = (event->response_type & 0x7F);
563
564         switch (type) {
565             case XCB_KEY_PRESS:
566                 handle_key_press(NULL, conn, (xcb_key_press_event_t*)event);
567                 break;
568
569             /* TODO: handle mappingnotify */
570
571             case XCB_BUTTON_PRESS:
572                 handle_button_press((xcb_button_press_event_t*)event);
573                 break;
574
575             case XCB_EXPOSE:
576                 handle_expose();
577                 break;
578         }
579
580         free(event);
581     }
582
583     return 0;
584 }