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