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