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