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