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