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