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