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