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