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