]> git.sur5r.net Git - i3/i3/blob - i3-config-wizard/main.c
2355750f6a84d1bc57cb8b4003c64d82a4f173e2
[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  *
6  * © 2011 Michael Stapelberg and contributors
7  *
8  * See file LICENSE for license information.
9  *
10  * i3-config-wizard: Program to convert configs using keycodes to configs using
11  * keysyms.
12  *
13  */
14 #include <ev.h>
15 #include <stdio.h>
16 #include <sys/types.h>
17 #include <stdlib.h>
18 #include <stdbool.h>
19 #include <unistd.h>
20 #include <string.h>
21 #include <ctype.h>
22 #include <errno.h>
23 #include <err.h>
24 #include <stdint.h>
25 #include <getopt.h>
26 #include <limits.h>
27 #include <sys/stat.h>
28 #include <fcntl.h>
29 #include <glob.h>
30
31 #include <xcb/xcb.h>
32 #include <xcb/xcb_aux.h>
33 #include <xcb/xcb_event.h>
34 #include <xcb/xcb_keysyms.h>
35
36 #include <X11/Xlib.h>
37 #include <X11/keysym.h>
38
39 /* We need SYSCONFDIR for the path to the keycode config template, so raise an
40  * error if it’s not defined for whatever reason */
41 #ifndef SYSCONFDIR
42 #error "SYSCONFDIR not defined"
43 #endif
44
45 #define FREE(pointer) do { \
46     if (pointer != NULL) { \
47         free(pointer); \
48         pointer = NULL; \
49     } \
50 } \
51 while (0)
52
53 #include "xcb.h"
54 #include "libi3.h"
55
56 enum { STEP_WELCOME, STEP_GENERATE } current_step = STEP_WELCOME;
57 enum { MOD_Mod1, MOD_Mod4 } modifier = MOD_Mod4;
58
59 static char *config_path;
60 static xcb_connection_t *conn;
61 static xcb_get_modifier_mapping_reply_t *modmap_reply;
62 static uint32_t font_id;
63 static uint32_t font_bold_id;
64 static char *socket_path;
65 static int font_height;
66 static int font_bold_height;
67 static xcb_window_t win;
68 static xcb_pixmap_t pixmap;
69 static xcb_gcontext_t pixmap_gc;
70 static xcb_key_symbols_t *symbols;
71 xcb_window_t root;
72 Display *dpy;
73
74 char *rewrite_binding(const char *bindingline);
75 static void finish();
76
77 #if defined(__APPLE__)
78
79 /*
80  * Taken from FreeBSD
81  * Returns a pointer to a new string which is a duplicate of the
82  * string, but only copies at most n characters.
83  *
84  */
85 char *strndup(const char *str, size_t n) {
86     size_t len;
87     char *copy;
88
89     for (len = 0; len < n && str[len]; len++)
90         continue;
91
92     if ((copy = malloc(len + 1)) == NULL)
93         return (NULL);
94     memcpy(copy, str, len);
95     copy[len] = '\0';
96     return (copy);
97 }
98
99 #endif
100
101 /*
102  * This function resolves ~ in pathnames.
103  * It may resolve wildcards in the first part of the path, but if no match
104  * or multiple matches are found, it just returns a copy of path as given.
105  *
106  */
107 static char *resolve_tilde(const char *path) {
108     static glob_t globbuf;
109     char *head, *tail, *result;
110
111     tail = strchr(path, '/');
112     head = strndup(path, tail ? tail - path : strlen(path));
113
114     int res = glob(head, GLOB_TILDE, NULL, &globbuf);
115     free(head);
116     /* no match, or many wildcard matches are bad */
117     if (res == GLOB_NOMATCH || globbuf.gl_pathc != 1)
118         result = strdup(path);
119     else if (res != 0) {
120         err(1, "glob() failed");
121     } else {
122         head = globbuf.gl_pathv[0];
123         result = calloc(1, strlen(head) + (tail ? strlen(tail) : 0) + 1);
124         strncpy(result, head, strlen(head));
125         if (tail)
126             strncat(result, tail, strlen(tail));
127     }
128     globfree(&globbuf);
129
130     return result;
131 }
132
133 /*
134  * Handles expose events, that is, draws the window contents.
135  *
136  */
137 static int handle_expose() {
138     /* re-draw the background */
139     xcb_rectangle_t border = {0, 0, 300, (15*font_height) + 8};
140     xcb_change_gc_single(conn, pixmap_gc, XCB_GC_FOREGROUND, get_colorpixel("#000000"));
141     xcb_poly_fill_rectangle(conn, pixmap, pixmap_gc, 1, &border);
142
143     xcb_change_gc_single(conn, pixmap_gc, XCB_GC_FONT, font_id);
144
145 #define txt(x, row, text) xcb_image_text_8(conn, strlen(text), pixmap, pixmap_gc, x, (row * font_height) + 2, text)
146
147     if (current_step == STEP_WELCOME) {
148         /* restore font color */
149         xcb_change_gc_single(conn, pixmap_gc, XCB_GC_FOREGROUND, get_colorpixel("#FFFFFF"));
150
151         txt(10, 2, "You have not configured i3 yet.");
152         txt(10, 3, "Do you want me to generate ~/.i3/config?");
153         txt(85, 5, "Yes, generate ~/.i3/config");
154         txt(85, 7, "No, I will use the defaults");
155
156         /* green */
157         xcb_change_gc_single(conn, pixmap_gc, XCB_GC_FOREGROUND, get_colorpixel("#00FF00"));
158         txt(25, 5, "<Enter>");
159
160         /* red */
161         xcb_change_gc_single(conn, pixmap_gc, XCB_GC_FOREGROUND, get_colorpixel("#FF0000"));
162         txt(31, 7, "<ESC>");
163     }
164
165     if (current_step == STEP_GENERATE) {
166         xcb_change_gc_single(conn, pixmap_gc, XCB_GC_FOREGROUND, get_colorpixel("#FFFFFF"));
167
168         txt(10, 2, "Please choose either:");
169         txt(85, 4, "Win as default modifier");
170         txt(85, 5, "Alt as default modifier");
171         txt(10, 7, "Afterwards, press");
172         txt(85, 9, "to write ~/.i3/config");
173         txt(85, 10, "to abort");
174
175         /* the not-selected modifier */
176         if (modifier == MOD_Mod4)
177             txt(31, 5, "<Alt>");
178         else txt(31, 4, "<Win>");
179
180         /* the selected modifier */
181         xcb_change_gc_single(conn, pixmap_gc, XCB_GC_FONT, font_bold_id);
182         if (modifier == MOD_Mod4)
183             txt(31, 4, "<Win>");
184         else txt(31, 5, "<Alt>");
185
186         /* green */
187         uint32_t mask = XCB_GC_FOREGROUND | XCB_GC_FONT;
188         uint32_t values[] = { get_colorpixel("#00FF00"), font_id };
189         xcb_change_gc(conn, pixmap_gc, mask, values);
190
191         txt(25, 9, "<Enter>");
192
193         /* red */
194         xcb_change_gc_single(conn, pixmap_gc, XCB_GC_FOREGROUND, get_colorpixel("#FF0000"));
195         txt(31, 10, "<ESC>");
196     }
197
198     /* Copy the contents of the pixmap to the real window */
199     xcb_copy_area(conn, pixmap, win, pixmap_gc, 0, 0, 0, 0, /* */ 500, 500);
200     xcb_flush(conn);
201
202     return 1;
203 }
204
205 static int handle_key_press(void *ignored, xcb_connection_t *conn, xcb_key_press_event_t *event) {
206     printf("Keypress %d, state raw = %d\n", event->detail, event->state);
207
208     /* Remove the numlock bit, all other bits are modifiers we can bind to */
209     uint16_t state_filtered = event->state & ~(xcb_numlock_mask | XCB_MOD_MASK_LOCK);
210     /* Only use the lower 8 bits of the state (modifier masks) so that mouse
211      * button masks are filtered out */
212     state_filtered &= 0xFF;
213
214     xcb_keysym_t sym = xcb_key_press_lookup_keysym(symbols, event, state_filtered);
215
216     printf("sym = %c (%d)\n", sym, sym);
217
218     if (sym == XK_Return || sym == XK_KP_Enter) {
219         if (current_step == STEP_WELCOME) {
220             current_step = STEP_GENERATE;
221             /* Set window title */
222             xcb_change_property(conn,
223                 XCB_PROP_MODE_REPLACE,
224                 win,
225                 A__NET_WM_NAME,
226                 A_UTF8_STRING,
227                 8,
228                 strlen("i3: generate config"),
229                 "i3: generate config");
230             xcb_flush(conn);
231         }
232         else finish();
233     }
234
235     /* cancel any time */
236     if (sym == XK_Escape)
237         exit(0);
238
239     /* Check if this is Mod1 or Mod4. The modmap contains Shift, Lock, Control,
240      * Mod1, Mod2, Mod3, Mod4, Mod5 (in that order) */
241     xcb_keycode_t *modmap = xcb_get_modifier_mapping_keycodes(modmap_reply);
242     /* Mod1? */
243     int mask = 3;
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 Mod1: 0x%02x\n", code);
249         if (code == event->detail) {
250             modifier = MOD_Mod1;
251             printf("This is Mod1!\n");
252         }
253     }
254
255     /* Mod4? */
256     mask = 6;
257     for (int i = 0; i < modmap_reply->keycodes_per_modifier; i++) {
258         xcb_keycode_t code = modmap[(mask * modmap_reply->keycodes_per_modifier) + i];
259         if (code == XCB_NONE)
260             continue;
261         printf("Modifier keycode for Mod4: 0x%02x\n", code);
262         if (code == event->detail) {
263             modifier = MOD_Mod4;
264             printf("This is Mod4!\n");
265         }
266     }
267
268     handle_expose();
269     return 1;
270 }
271
272 /*
273  * Handle button presses to make clicking on "<win>" and "<alt>" work
274  *
275  */
276 static void handle_button_press(xcb_button_press_event_t* event) {
277     if (current_step != STEP_GENERATE)
278         return;
279
280     if (event->event_x >= 32 && event->event_x <= 68 &&
281         event->event_y >= 45 && event->event_y <= 54) {
282         modifier = MOD_Mod4;
283         handle_expose();
284     }
285
286     if (event->event_x >= 32 && event->event_x <= 68 &&
287         event->event_y >= 56 && event->event_y <= 70) {
288         modifier = MOD_Mod1;
289         handle_expose();
290     }
291
292     return;
293 }
294
295 /*
296  * Creates the config file and tells i3 to reload.
297  *
298  */
299 static void finish() {
300     printf("creating \"%s\"...\n", config_path);
301
302     if (!(dpy = XOpenDisplay(NULL)))
303         errx(1, "Could not connect to X11");
304
305     FILE *kc_config = fopen(SYSCONFDIR "/i3/config.keycodes", "r");
306     if (kc_config == NULL)
307         err(1, "Could not open input file \"%s\"", SYSCONFDIR "/i3/config.keycodes");
308
309     FILE *ks_config = fopen(config_path, "w");
310     if (ks_config == NULL)
311         err(1, "Could not open output config file \"%s\"", config_path);
312
313     char *line = NULL;
314     size_t len = 0;
315 #if !defined(__APPLE__)
316     ssize_t read;
317 #endif
318     bool head_of_file = true;
319
320     /* write a header about auto-generation to the output file */
321     fputs("# This file has been auto-generated by i3-config-wizard(1).\n", ks_config);
322     fputs("# It will not be overwritten, so edit it as you like.\n", ks_config);
323     fputs("#\n", ks_config);
324     fputs("# Should you change your keyboard layout somewhen, delete\n", ks_config);
325     fputs("# this file and re-run i3-config-wizard(1).\n", ks_config);
326     fputs("#\n", ks_config);
327
328 #if defined(__APPLE__)
329     while ((line = fgetln(kc_config, &len)) != NULL) {
330 #else
331     while ((read = getline(&line, &len, kc_config)) != -1) {
332 #endif
333         /* skip the warning block at the beginning of the input file */
334         if (head_of_file &&
335             strncmp("# WARNING", line, strlen("# WARNING")) == 0)
336             continue;
337
338         head_of_file = false;
339
340         /* Skip leading whitespace */
341         char *walk = line;
342         while (isspace(*walk) && walk < (line + len))
343             walk++;
344
345         /* Set the modifier the user chose */
346         if (strncmp(walk, "set $mod ", strlen("set $mod ")) == 0) {
347             if (modifier == MOD_Mod1)
348                 fputs("set $mod Mod1\n", ks_config);
349             else fputs("set $mod Mod4\n", ks_config);
350             continue;
351         }
352
353         /* Check for 'bindcode'. If it’s not a bindcode line, we
354          * just copy it to the output file */
355         if (strncmp(walk, "bindcode", strlen("bindcode")) != 0) {
356             fputs(line, ks_config);
357             continue;
358         }
359         char *result = rewrite_binding(walk);
360         fputs(result, ks_config);
361         free(result);
362     }
363
364     /* sync to do our best in order to have the file really stored on disk */
365     fflush(ks_config);
366     fsync(fileno(ks_config));
367
368     free(line);
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 = socket_path_from_x11();
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
453     /* Place requests for the atoms we need as soon as possible */
454     #define xmacro(atom) \
455         xcb_intern_atom_cookie_t atom ## _cookie = xcb_intern_atom(conn, 0, strlen(#atom), #atom);
456     #include "atoms.xmacro"
457     #undef xmacro
458
459     xcb_screen_t *root_screen = xcb_aux_get_screen(conn, screens);
460     root = root_screen->root;
461
462     if (!(modmap_reply = xcb_get_modifier_mapping_reply(conn, modmap_cookie, NULL)))
463         errx(EXIT_FAILURE, "Could not get modifier mapping\n");
464
465     /* XXX: we should refactor xcb_get_numlock_mask so that it uses the
466      * modifier mapping we already have */
467     xcb_get_numlock_mask(conn);
468
469     symbols = xcb_key_symbols_alloc(conn);
470
471     font_id = get_font_id(conn, pattern, &font_height);
472     font_bold_id = get_font_id(conn, patternbold, &font_bold_height);
473
474     /* Open an input window */
475     win = open_input_window(conn, 300, 205);
476
477     /* Setup NetWM atoms */
478     #define xmacro(name) \
479         do { \
480             xcb_intern_atom_reply_t *reply = xcb_intern_atom_reply(conn, name ## _cookie, NULL); \
481             if (!reply) \
482                 errx(EXIT_FAILURE, "Could not get atom " # name "\n"); \
483             \
484             A_ ## name = reply->atom; \
485             free(reply); \
486         } while (0);
487     #include "atoms.xmacro"
488     #undef xmacro
489
490     /* Set dock mode */
491     xcb_change_property(conn,
492         XCB_PROP_MODE_REPLACE,
493         win,
494         A__NET_WM_WINDOW_TYPE,
495         A_ATOM,
496         32,
497         1,
498         (unsigned char*) &A__NET_WM_WINDOW_TYPE_DIALOG);
499
500     /* Set window title */
501     xcb_change_property(conn,
502         XCB_PROP_MODE_REPLACE,
503         win,
504         A__NET_WM_NAME,
505         A_UTF8_STRING,
506         8,
507         strlen("i3: first configuration"),
508         "i3: first configuration");
509
510     /* Create pixmap */
511     pixmap = xcb_generate_id(conn);
512     pixmap_gc = xcb_generate_id(conn);
513     xcb_create_pixmap(conn, root_screen->root_depth, pixmap, win, 500, 500);
514     xcb_create_gc(conn, pixmap_gc, pixmap, 0, 0);
515
516     /* Grab the keyboard to get all input */
517     xcb_flush(conn);
518
519     /* Try (repeatedly, if necessary) to grab the keyboard. We might not
520      * get the keyboard at the first attempt because of the keybinding
521      * still being active when started via a wm’s keybinding. */
522     xcb_grab_keyboard_cookie_t cookie;
523     xcb_grab_keyboard_reply_t *reply = NULL;
524
525     int count = 0;
526     while ((reply == NULL || reply->status != XCB_GRAB_STATUS_SUCCESS) && (count++ < 500)) {
527         cookie = xcb_grab_keyboard(conn, false, win, XCB_CURRENT_TIME, XCB_GRAB_MODE_ASYNC, XCB_GRAB_MODE_ASYNC);
528         reply = xcb_grab_keyboard_reply(conn, cookie, NULL);
529         usleep(1000);
530     }
531
532     if (reply->status != XCB_GRAB_STATUS_SUCCESS) {
533         fprintf(stderr, "Could not grab keyboard, status = %d\n", reply->status);
534         exit(-1);
535     }
536
537     xcb_flush(conn);
538
539     xcb_generic_event_t *event;
540     while ((event = xcb_wait_for_event(conn)) != NULL) {
541         if (event->response_type == 0) {
542             fprintf(stderr, "X11 Error received! sequence %x\n", event->sequence);
543             continue;
544         }
545
546         /* Strip off the highest bit (set if the event is generated) */
547         int type = (event->response_type & 0x7F);
548
549         switch (type) {
550             case XCB_KEY_PRESS:
551                 handle_key_press(NULL, conn, (xcb_key_press_event_t*)event);
552                 break;
553
554             /* TODO: handle mappingnotify */
555
556             case XCB_BUTTON_PRESS:
557                 handle_button_press((xcb_button_press_event_t*)event);
558                 break;
559
560             case XCB_EXPOSE:
561                 handle_expose();
562                 break;
563         }
564
565         free(event);
566     }
567
568     return 0;
569 }