]> git.sur5r.net Git - i3/i3/blob - i3-input/main.c
Only react on the last Expose event in a series of events. (#2636)
[i3/i3] / i3-input / main.c
1 /*
2  * vim:ts=4:sw=4:expandtab
3  *
4  * i3 - an improved dynamic tiling window manager
5  * © 2009 Michael Stapelberg and contributors (see also: LICENSE)
6  *
7  * i3-input/main.c: Utility which lets the user input commands and sends them
8  *                  to i3.
9  *
10  */
11 #include "libi3.h"
12
13 #include <stdio.h>
14 #include <sys/types.h>
15 #include <stdlib.h>
16 #include <stdbool.h>
17 #include <unistd.h>
18 #include <string.h>
19 #include <errno.h>
20 #include <err.h>
21 #include <stdint.h>
22 #include <getopt.h>
23 #include <limits.h>
24
25 #include <xcb/xcb.h>
26 #include <xcb/xcb_aux.h>
27 #include <xcb/xcb_event.h>
28 #include <xcb/xcb_keysyms.h>
29
30 #include <X11/keysym.h>
31
32 #include "keysym2ucs.h"
33
34 #include "i3-input.h"
35
36 /* IPC format string. %s will be replaced with what the user entered, then
37  * the command will be sent to i3 */
38 static char *format;
39
40 static char *socket_path;
41 static int sockfd;
42 static xcb_key_symbols_t *symbols;
43 static bool modeswitch_active = false;
44 static xcb_window_t win;
45 static xcb_pixmap_t pixmap;
46 static xcb_gcontext_t pixmap_gc;
47 static xcb_char2b_t glyphs_ucs[512];
48 static char *glyphs_utf8[512];
49 static int input_position;
50 static i3Font font;
51 static i3String *prompt;
52 static int prompt_offset = 0;
53 static int limit;
54 xcb_window_t root;
55 xcb_connection_t *conn;
56 xcb_screen_t *root_screen;
57
58 /*
59  * Having verboselog(), errorlog() and debuglog() is necessary when using libi3.
60  *
61  */
62 void verboselog(char *fmt, ...) {
63     va_list args;
64
65     va_start(args, fmt);
66     vfprintf(stdout, fmt, args);
67     va_end(args);
68 }
69
70 void errorlog(char *fmt, ...) {
71     va_list args;
72
73     va_start(args, fmt);
74     vfprintf(stderr, fmt, args);
75     va_end(args);
76 }
77
78 void debuglog(char *fmt, ...) {
79 }
80
81 /*
82  * Concats the glyphs (either UCS-2 or UTF-8) to a single string, suitable for
83  * rendering it (UCS-2) or sending it to i3 (UTF-8).
84  *
85  */
86 static uint8_t *concat_strings(char **glyphs, int max) {
87     uint8_t *output = scalloc(max + 1, 4);
88     uint8_t *walk = output;
89     for (int c = 0; c < max; c++) {
90         printf("at %c\n", glyphs[c][0]);
91         /* if the first byte is 0, this has to be UCS2 */
92         if (glyphs[c][0] == '\0') {
93             memcpy(walk, glyphs[c], 2);
94             walk += 2;
95         } else {
96             strcpy((char *)walk, glyphs[c]);
97             walk += strlen(glyphs[c]);
98         }
99     }
100     printf("output = %s\n", output);
101     return output;
102 }
103
104 /*
105  * Handles expose events (redraws of the window) and rendering in general. Will
106  * be called from the code with event == NULL or from X with event != NULL.
107  *
108  */
109 static int handle_expose(void *data, xcb_connection_t *conn, xcb_expose_event_t *event) {
110     printf("expose!\n");
111
112     /* re-draw the background */
113     xcb_rectangle_t border = {0, 0, logical_px(500), font.height + logical_px(8)},
114                     inner = {logical_px(2), logical_px(2), logical_px(496), font.height + logical_px(8) - logical_px(4)};
115     xcb_change_gc(conn, pixmap_gc, XCB_GC_FOREGROUND, (uint32_t[]){get_colorpixel("#FF0000")});
116     xcb_poly_fill_rectangle(conn, pixmap, pixmap_gc, 1, &border);
117     xcb_change_gc(conn, pixmap_gc, XCB_GC_FOREGROUND, (uint32_t[]){get_colorpixel("#000000")});
118     xcb_poly_fill_rectangle(conn, pixmap, pixmap_gc, 1, &inner);
119
120     /* restore font color */
121     set_font_colors(pixmap_gc, draw_util_hex_to_color("#FFFFFF"), draw_util_hex_to_color("#000000"));
122
123     /* draw the prompt … */
124     if (prompt != NULL) {
125         draw_text(prompt, pixmap, pixmap_gc, NULL, logical_px(4), logical_px(4), logical_px(492));
126     }
127     /* … and the text */
128     if (input_position > 0) {
129         i3String *input = i3string_from_ucs2(glyphs_ucs, input_position);
130         draw_text(input, pixmap, pixmap_gc, NULL, prompt_offset + logical_px(4), logical_px(4), logical_px(492));
131         i3string_free(input);
132     }
133
134     /* Copy the contents of the pixmap to the real window */
135     xcb_copy_area(conn, pixmap, win, pixmap_gc, 0, 0, 0, 0, logical_px(500), font.height + logical_px(8));
136     xcb_flush(conn);
137
138     return 1;
139 }
140
141 /*
142  * Deactivates the Mode_switch bit upon release of the Mode_switch key.
143  *
144  */
145 static int handle_key_release(void *ignored, xcb_connection_t *conn, xcb_key_release_event_t *event) {
146     printf("releasing %d, state raw = %d\n", event->detail, event->state);
147
148     xcb_keysym_t sym = xcb_key_press_lookup_keysym(symbols, event, event->state);
149     if (sym == XK_Mode_switch) {
150         printf("Mode switch disabled\n");
151         modeswitch_active = false;
152     }
153
154     return 1;
155 }
156
157 static void finish_input() {
158     char *command = (char *)concat_strings(glyphs_utf8, input_position);
159
160     /* count the occurrences of %s in the string */
161     int c;
162     int len = strlen(format);
163     int cnt = 0;
164     for (c = 0; c < (len - 1); c++)
165         if (format[c] == '%' && format[c + 1] == 's')
166             cnt++;
167     printf("occurrences = %d\n", cnt);
168
169     /* allocate space for the output */
170     int inputlen = strlen(command);
171     char *full = scalloc(strlen(format) - (2 * cnt) /* format without all %s */
172                              + (inputlen * cnt)     /* replaced %s */
173                              + 1,                   /* trailing NUL */
174                          1);
175     char *dest = full;
176     for (c = 0; c < len; c++) {
177         /* if this is not % or it is % but without a following 's',
178          * just copy the character */
179         if (format[c] != '%' || (c == (len - 1)) || format[c + 1] != 's')
180             *(dest++) = format[c];
181         else {
182             strncat(dest, command, inputlen);
183             dest += inputlen;
184             /* skip the following 's' of '%s' */
185             c++;
186         }
187     }
188
189     /* prefix the command if a prefix was specified on commandline */
190     printf("command = %s\n", full);
191
192     ipc_send_message(sockfd, strlen(full), 0, (uint8_t *)full);
193
194     free(full);
195
196     exit(0);
197 }
198
199 /*
200  * Handles keypresses by converting the keycodes to keysymbols, then the
201  * keysymbols to UCS-2. If the conversion succeeded, the glyph is saved in the
202  * internal buffers and displayed in the input window.
203  *
204  * Also handles backspace (deleting one character) and return (sending the
205  * command to i3).
206  *
207  */
208 static int handle_key_press(void *ignored, xcb_connection_t *conn, xcb_key_press_event_t *event) {
209     printf("Keypress %d, state raw = %d\n", event->detail, event->state);
210
211     // TODO: port the input handling code from i3lock once libxkbcommon ≥ 0.5.0
212     // is available in distros.
213
214     /* See the documentation of xcb_key_symbols_get_keysym for this one.
215      * Basically: We get either col 0 or col 1, depending on whether shift is
216      * pressed. */
217     int col = (event->state & XCB_MOD_MASK_SHIFT);
218
219     /* If modeswitch is currently active, we need to look in group 2 or 3,
220      * respectively. */
221     if (modeswitch_active)
222         col += 2;
223
224     xcb_keysym_t sym = xcb_key_press_lookup_keysym(symbols, event, col);
225     if (sym == XK_Mode_switch) {
226         printf("Mode switch enabled\n");
227         modeswitch_active = true;
228         return 1;
229     }
230
231     if (sym == XK_Return)
232         finish_input();
233
234     if (sym == XK_BackSpace) {
235         if (input_position == 0)
236             return 1;
237
238         input_position--;
239         free(glyphs_utf8[input_position]);
240
241         handle_expose(NULL, conn, NULL);
242         return 1;
243     }
244     if (sym == XK_Escape) {
245         exit(0);
246     }
247
248     /* TODO: handle all of these? */
249     printf("is_keypad_key = %d\n", xcb_is_keypad_key(sym));
250     printf("is_private_keypad_key = %d\n", xcb_is_private_keypad_key(sym));
251     printf("xcb_is_cursor_key = %d\n", xcb_is_cursor_key(sym));
252     printf("xcb_is_pf_key = %d\n", xcb_is_pf_key(sym));
253     printf("xcb_is_function_key = %d\n", xcb_is_function_key(sym));
254     printf("xcb_is_misc_function_key = %d\n", xcb_is_misc_function_key(sym));
255     printf("xcb_is_modifier_key = %d\n", xcb_is_modifier_key(sym));
256
257     if (xcb_is_modifier_key(sym) || xcb_is_cursor_key(sym))
258         return 1;
259
260     printf("sym = %c (%d)\n", sym, sym);
261
262     /* convert the keysym to UCS */
263     uint16_t ucs = keysym2ucs(sym);
264     if ((int16_t)ucs == -1) {
265         fprintf(stderr, "Keysym could not be converted to UCS, skipping\n");
266         return 1;
267     }
268
269     xcb_char2b_t inp;
270     inp.byte1 = (ucs & 0xff00) >> 2;
271     inp.byte2 = (ucs & 0x00ff) >> 0;
272
273     printf("inp.byte1 = %02x, inp.byte2 = %02x\n", inp.byte1, inp.byte2);
274     /* convert it to UTF-8 */
275     char *out = convert_ucs2_to_utf8(&inp, 1);
276     printf("converted to %s\n", out);
277
278     glyphs_ucs[input_position] = inp;
279     glyphs_utf8[input_position] = out;
280     input_position++;
281
282     if (input_position == limit)
283         finish_input();
284
285     handle_expose(NULL, conn, NULL);
286     return 1;
287 }
288
289 static xcb_rectangle_t get_window_position(void) {
290     xcb_rectangle_t result = (xcb_rectangle_t){logical_px(50), logical_px(50), logical_px(500), font.height + logical_px(8)};
291
292     xcb_get_property_reply_t *supporting_wm_reply = NULL;
293     xcb_get_input_focus_reply_t *input_focus = NULL;
294     xcb_get_geometry_reply_t *geometry = NULL;
295     xcb_get_property_reply_t *wm_class = NULL;
296     xcb_translate_coordinates_reply_t *coordinates = NULL;
297
298     xcb_atom_t A__NET_SUPPORTING_WM_CHECK;
299     xcb_intern_atom_cookie_t nswc_cookie = xcb_intern_atom(conn, 0, strlen("_NET_SUPPORTING_WM_CHECK"), "_NET_SUPPORTING_WM_CHECK");
300     xcb_intern_atom_reply_t *nswc_reply = xcb_intern_atom_reply(conn, nswc_cookie, NULL);
301     if (nswc_reply == NULL) {
302         ELOG("Could not intern atom _NET_SUPPORTING_WM_CHECK\n");
303         exit(-1);
304     }
305     A__NET_SUPPORTING_WM_CHECK = nswc_reply->atom;
306     free(nswc_reply);
307
308     supporting_wm_reply = xcb_get_property_reply(
309         conn, xcb_get_property(conn, false, root, A__NET_SUPPORTING_WM_CHECK, XCB_ATOM_WINDOW, 0, 32), NULL);
310     xcb_window_t *supporting_wm_win = NULL;
311     if (supporting_wm_reply == NULL || xcb_get_property_value_length(supporting_wm_reply) == 0) {
312         DLOG("Could not determine EWMH support window.\n");
313     } else {
314         supporting_wm_win = xcb_get_property_value(supporting_wm_reply);
315     }
316
317     /* In rare cases, the window holding the input focus might disappear while we are figuring out its
318      * position. To avoid this, we grab the server in the meantime. */
319     xcb_grab_server(conn);
320
321     input_focus = xcb_get_input_focus_reply(conn, xcb_get_input_focus(conn), NULL);
322     if (input_focus == NULL || input_focus->focus == XCB_NONE) {
323         DLOG("Failed to receive the current input focus or no window has the input focus right now.\n");
324         goto free_resources;
325     }
326
327     /* We need to ignore the EWMH support window to which the focus can be set if there's no suitable window to focus. */
328     if (supporting_wm_win != NULL && input_focus->focus == *supporting_wm_win) {
329         DLOG("Input focus is on the EWMH support window, ignoring.\n");
330         goto free_resources;
331     }
332
333     geometry = xcb_get_geometry_reply(conn, xcb_get_geometry(conn, input_focus->focus), NULL);
334     if (geometry == NULL) {
335         DLOG("Failed to received window geometry.\n");
336         goto free_resources;
337     }
338
339     wm_class = xcb_get_property_reply(
340         conn, xcb_get_property(conn, false, input_focus->focus, XCB_ATOM_WM_CLASS, XCB_GET_PROPERTY_TYPE_ANY, 0, 32), NULL);
341
342     /* We need to find out whether the input focus is on an i3 frame window. If it is, we must not translate the coordinates. */
343     if (wm_class == NULL || xcb_get_property_value_length(wm_class) == 0 || strcmp(xcb_get_property_value(wm_class), "i3-frame") != 0) {
344         coordinates = xcb_translate_coordinates_reply(
345             conn, xcb_translate_coordinates(conn, input_focus->focus, root, geometry->x, geometry->y), NULL);
346         if (coordinates == NULL) {
347             DLOG("Failed to translate coordinates.\n");
348             goto free_resources;
349         }
350
351         DLOG("Determined coordinates of window with input focus at x = %i / y = %i.\n", coordinates->dst_x, coordinates->dst_y);
352         result.x += coordinates->dst_x;
353         result.y += coordinates->dst_y;
354     } else {
355         DLOG("Determined coordinates of window with input focus at x = %i / y = %i.\n", geometry->x, geometry->y);
356         result.x += geometry->x;
357         result.y += geometry->y;
358     }
359
360 free_resources:
361     xcb_ungrab_server(conn);
362     xcb_flush(conn);
363
364     FREE(supporting_wm_reply);
365     FREE(input_focus);
366     FREE(geometry);
367     FREE(wm_class);
368     FREE(coordinates);
369     return result;
370 }
371
372 int main(int argc, char *argv[]) {
373     format = sstrdup("%s");
374     socket_path = getenv("I3SOCK");
375     char *pattern = sstrdup("pango:monospace 8");
376     int o, option_index = 0;
377
378     static struct option long_options[] = {
379         {"socket", required_argument, 0, 's'},
380         {"version", no_argument, 0, 'v'},
381         {"limit", required_argument, 0, 'l'},
382         {"prompt", required_argument, 0, 'P'},
383         {"prefix", required_argument, 0, 'p'},
384         {"format", required_argument, 0, 'F'},
385         {"font", required_argument, 0, 'f'},
386         {"help", no_argument, 0, 'h'},
387         {0, 0, 0, 0}};
388
389     char *options_string = "s:p:P:f:l:F:vh";
390
391     while ((o = getopt_long(argc, argv, options_string, long_options, &option_index)) != -1) {
392         switch (o) {
393             case 's':
394                 FREE(socket_path);
395                 socket_path = sstrdup(optarg);
396                 break;
397             case 'v':
398                 printf("i3-input " I3_VERSION);
399                 return 0;
400             case 'p':
401                 /* This option is deprecated, but will still work in i3 v4.1, 4.2 and 4.3 */
402                 fprintf(stderr, "i3-input: WARNING: the -p option is DEPRECATED in favor of the -F (format) option\n");
403                 FREE(format);
404                 sasprintf(&format, "%s%%s", optarg);
405                 break;
406             case 'l':
407                 limit = atoi(optarg);
408                 break;
409             case 'P':
410                 i3string_free(prompt);
411                 prompt = i3string_from_utf8(optarg);
412                 break;
413             case 'f':
414                 FREE(pattern);
415                 pattern = sstrdup(optarg);
416                 break;
417             case 'F':
418                 FREE(format);
419                 format = sstrdup(optarg);
420                 break;
421             case 'h':
422                 printf("i3-input " I3_VERSION "\n");
423                 printf("i3-input [-s <socket>] [-F <format>] [-l <limit>] [-P <prompt>] [-f <font>] [-v]\n");
424                 printf("\n");
425                 printf("Example:\n");
426                 printf("    i3-input -F 'workspace \"%%s\"' -P 'Switch to workspace: '\n");
427                 return 0;
428         }
429     }
430
431     printf("using format \"%s\"\n", format);
432
433     int screen;
434     conn = xcb_connect(NULL, &screen);
435     if (!conn || xcb_connection_has_error(conn))
436         die("Cannot open display\n");
437
438     if (socket_path == NULL)
439         socket_path = root_atom_contents("I3_SOCKET_PATH", conn, screen);
440
441     if (socket_path == NULL)
442         socket_path = "/tmp/i3-ipc.sock";
443
444     sockfd = ipc_connect(socket_path);
445
446     root_screen = xcb_aux_get_screen(conn, screen);
447     root = root_screen->root;
448
449     symbols = xcb_key_symbols_alloc(conn);
450
451     font = load_font(pattern, true);
452     set_font(&font);
453
454     if (prompt != NULL)
455         prompt_offset = predict_text_width(prompt);
456
457     const xcb_rectangle_t win_pos = get_window_position();
458
459     /* Open an input window */
460     win = xcb_generate_id(conn);
461     xcb_create_window(
462         conn,
463         XCB_COPY_FROM_PARENT,
464         win,                                                 /* the window id */
465         root,                                                /* parent == root */
466         win_pos.x, win_pos.y, win_pos.width, win_pos.height, /* dimensions */
467         0,                                                   /* X11 border = 0, we draw our own */
468         XCB_WINDOW_CLASS_INPUT_OUTPUT,
469         XCB_WINDOW_CLASS_COPY_FROM_PARENT, /* copy visual from parent */
470         XCB_CW_BACK_PIXEL | XCB_CW_OVERRIDE_REDIRECT | XCB_CW_EVENT_MASK,
471         (uint32_t[]){
472             0, /* back pixel: black */
473             1, /* override redirect: don’t manage this window */
474             XCB_EVENT_MASK_EXPOSURE});
475
476     /* Map the window (make it visible) */
477     xcb_map_window(conn, win);
478
479     /* Create pixmap */
480     pixmap = xcb_generate_id(conn);
481     pixmap_gc = xcb_generate_id(conn);
482     xcb_create_pixmap(conn, root_screen->root_depth, pixmap, win, logical_px(500), font.height + logical_px(8));
483     xcb_create_gc(conn, pixmap_gc, pixmap, 0, 0);
484
485     /* Grab the keyboard to get all input */
486     xcb_flush(conn);
487
488     /* Try (repeatedly, if necessary) to grab the keyboard. We might not
489      * get the keyboard at the first attempt because of the keybinding
490      * still being active when started via a wm’s keybinding. */
491     xcb_grab_keyboard_cookie_t cookie;
492     xcb_grab_keyboard_reply_t *reply = NULL;
493
494     int count = 0;
495     while ((reply == NULL || reply->status != XCB_GRAB_STATUS_SUCCESS) && (count++ < 500)) {
496         cookie = xcb_grab_keyboard(conn, false, win, XCB_CURRENT_TIME, XCB_GRAB_MODE_ASYNC, XCB_GRAB_MODE_ASYNC);
497         reply = xcb_grab_keyboard_reply(conn, cookie, NULL);
498         usleep(1000);
499     }
500
501     if (reply->status != XCB_GRAB_STATUS_SUCCESS) {
502         fprintf(stderr, "Could not grab keyboard, status = %d\n", reply->status);
503         exit(-1);
504     }
505
506     xcb_flush(conn);
507
508     xcb_generic_event_t *event;
509     while ((event = xcb_wait_for_event(conn)) != NULL) {
510         if (event->response_type == 0) {
511             fprintf(stderr, "X11 Error received! sequence %x\n", event->sequence);
512             continue;
513         }
514
515         /* Strip off the highest bit (set if the event is generated) */
516         int type = (event->response_type & 0x7F);
517
518         switch (type) {
519             case XCB_KEY_PRESS:
520                 handle_key_press(NULL, conn, (xcb_key_press_event_t *)event);
521                 break;
522
523             case XCB_KEY_RELEASE:
524                 handle_key_release(NULL, conn, (xcb_key_release_event_t *)event);
525                 break;
526
527             case XCB_EXPOSE:
528                 if (((xcb_expose_event_t *)event)->count == 0) {
529                     handle_expose(NULL, conn, (xcb_expose_event_t *)event);
530                 }
531
532                 break;
533         }
534
535         free(event);
536     }
537
538     return 0;
539 }