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