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