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