2 * vim:ts=4:sw=4:expandtab
4 * i3 - an improved dynamic tiling window manager
5 * © 2009-2013 Michael Stapelberg and contributors (see also: LICENSE)
7 * i3-input/main.c: Utility which lets the user input commands and sends them
12 #include <sys/types.h>
24 #include <xcb/xcb_aux.h>
25 #include <xcb/xcb_event.h>
26 #include <xcb/xcb_keysyms.h>
28 #include <X11/keysym.h>
30 #include "keysym2ucs.h"
36 /* IPC format string. %s will be replaced with what the user entered, then
37 * the command will be sent to i3 */
40 static char *socket_path;
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;
51 static i3String *prompt;
52 static int prompt_offset = 0;
55 xcb_connection_t *conn;
56 xcb_screen_t *root_screen;
57 static xcb_get_input_focus_cookie_t focus_cookie;
60 * Having verboselog(), errorlog() and debuglog() is necessary when using libi3.
63 void verboselog(char *fmt, ...) {
67 vfprintf(stdout, fmt, args);
71 void errorlog(char *fmt, ...) {
75 vfprintf(stderr, fmt, args);
79 void debuglog(char *fmt, ...) {
83 * Restores the X11 input focus to whereever 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().
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);
93 fprintf(stderr, "[i3-input] ERROR: Could not restore input focus (X error %d)\n", error->error_code);
96 xcb_set_input_focus(conn, XCB_INPUT_FOCUS_POINTER_ROOT, reply->focus, XCB_CURRENT_TIME);
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).
105 static uint8_t *concat_strings(char **glyphs, int max) {
106 uint8_t *output = calloc(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);
115 strcpy((char *)walk, glyphs[c]);
116 walk += strlen(glyphs[c]);
119 printf("output = %s\n", output);
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.
128 static int handle_expose(void *data, xcb_connection_t *conn, xcb_expose_event_t *event) {
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);
139 /* restore font color */
140 set_font_colors(pixmap_gc, get_colorpixel("#FFFFFF"), get_colorpixel("#000000"));
142 /* draw the prompt … */
143 if (prompt != NULL) {
144 draw_text(prompt, pixmap, pixmap_gc, logical_px(4), logical_px(4), logical_px(492));
147 if (input_position > 0) {
148 i3String *input = i3string_from_ucs2(glyphs_ucs, input_position);
149 draw_text(input, pixmap, pixmap_gc, prompt_offset + logical_px(4), logical_px(4), logical_px(492));
150 i3string_free(input);
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));
161 * Deactivates the Mode_switch bit upon release of the Mode_switch key.
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);
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;
176 static void finish_input() {
177 char *command = (char *)concat_strings(glyphs_utf8, input_position);
179 /* count the occurences of %s in the string */
181 int len = strlen(format);
183 for (c = 0; c < (len - 1); c++)
184 if (format[c] == '%' && format[c + 1] == 's')
186 printf("occurences = %d\n", cnt);
188 /* allocate space for the output */
189 int inputlen = strlen(command);
190 char *full = calloc(1,
191 strlen(format) - (2 * cnt) /* format without all %s */
192 + (inputlen * cnt) /* replaced %s */
193 + 1); /* trailing NUL */
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];
201 strncat(dest, command, inputlen);
203 /* skip the following 's' of '%s' */
208 /* prefix the command if a prefix was specified on commandline */
209 printf("command = %s\n", full);
211 restore_input_focus();
215 ipc_send_message(sockfd, strlen(full), 0, (uint8_t *)full);
227 * Handles keypresses by converting the keycodes to keysymbols, then the
228 * keysymbols to UCS-2. If the conversion succeeded, the glyph is saved in the
229 * internal buffers and displayed in the input window.
231 * Also handles backspace (deleting one character) and return (sending the
235 static int handle_key_press(void *ignored, xcb_connection_t *conn, xcb_key_press_event_t *event) {
236 printf("Keypress %d, state raw = %d\n", event->detail, event->state);
238 // TODO: port the input handling code from i3lock once libxkbcommon ≥ 0.5.0
239 // is available in distros.
241 /* See the documentation of xcb_key_symbols_get_keysym for this one.
242 * Basically: We get either col 0 or col 1, depending on whether shift is
244 int col = (event->state & XCB_MOD_MASK_SHIFT);
246 /* If modeswitch is currently active, we need to look in group 2 or 3,
248 if (modeswitch_active)
251 xcb_keysym_t sym = xcb_key_press_lookup_keysym(symbols, event, col);
252 if (sym == XK_Mode_switch) {
253 printf("Mode switch enabled\n");
254 modeswitch_active = true;
258 if (sym == XK_Return)
261 if (sym == XK_BackSpace) {
262 if (input_position == 0)
266 free(glyphs_utf8[input_position]);
268 handle_expose(NULL, conn, NULL);
271 if (sym == XK_Escape) {
272 restore_input_focus();
276 /* TODO: handle all of these? */
277 printf("is_keypad_key = %d\n", xcb_is_keypad_key(sym));
278 printf("is_private_keypad_key = %d\n", xcb_is_private_keypad_key(sym));
279 printf("xcb_is_cursor_key = %d\n", xcb_is_cursor_key(sym));
280 printf("xcb_is_pf_key = %d\n", xcb_is_pf_key(sym));
281 printf("xcb_is_function_key = %d\n", xcb_is_function_key(sym));
282 printf("xcb_is_misc_function_key = %d\n", xcb_is_misc_function_key(sym));
283 printf("xcb_is_modifier_key = %d\n", xcb_is_modifier_key(sym));
285 if (xcb_is_modifier_key(sym) || xcb_is_cursor_key(sym))
288 printf("sym = %c (%d)\n", sym, sym);
290 /* convert the keysym to UCS */
291 uint16_t ucs = keysym2ucs(sym);
292 if ((int16_t)ucs == -1) {
293 fprintf(stderr, "Keysym could not be converted to UCS, skipping\n");
298 inp.byte1 = (ucs & 0xff00) >> 2;
299 inp.byte2 = (ucs & 0x00ff) >> 0;
301 printf("inp.byte1 = %02x, inp.byte2 = %02x\n", inp.byte1, inp.byte2);
302 /* convert it to UTF-8 */
303 char *out = convert_ucs2_to_utf8(&inp, 1);
304 printf("converted to %s\n", out);
306 glyphs_ucs[input_position] = inp;
307 glyphs_utf8[input_position] = out;
310 if (input_position == limit)
313 handle_expose(NULL, conn, NULL);
317 int main(int argc, char *argv[]) {
318 format = strdup("%s");
319 socket_path = getenv("I3SOCK");
320 char *pattern = sstrdup("pango:monospace 8");
321 int o, option_index = 0;
323 static struct option long_options[] = {
324 {"socket", required_argument, 0, 's'},
325 {"version", no_argument, 0, 'v'},
326 {"limit", required_argument, 0, 'l'},
327 {"prompt", required_argument, 0, 'P'},
328 {"prefix", required_argument, 0, 'p'},
329 {"format", required_argument, 0, 'F'},
330 {"font", required_argument, 0, 'f'},
331 {"help", no_argument, 0, 'h'},
334 char *options_string = "s:p:P:f:l:F:vh";
336 while ((o = getopt_long(argc, argv, options_string, long_options, &option_index)) != -1) {
340 socket_path = strdup(optarg);
343 printf("i3-input " I3_VERSION);
346 /* This option is deprecated, but will still work in i3 v4.1, 4.2 and 4.3 */
347 fprintf(stderr, "i3-input: WARNING: the -p option is DEPRECATED in favor of the -F (format) option\n");
349 sasprintf(&format, "%s%%s", optarg);
352 limit = atoi(optarg);
355 i3string_free(prompt);
356 prompt = i3string_from_utf8(optarg);
360 pattern = strdup(optarg);
364 format = strdup(optarg);
367 printf("i3-input " I3_VERSION "\n");
368 printf("i3-input [-s <socket>] [-F <format>] [-l <limit>] [-P <prompt>] [-f <font>] [-v]\n");
370 printf("Example:\n");
371 printf(" i3-input -F 'workspace \"%%s\"' -P 'Switch to workspace: '\n");
376 printf("using format \"%s\"\n", format);
379 conn = xcb_connect(NULL, &screen);
380 if (!conn || xcb_connection_has_error(conn))
381 die("Cannot open display\n");
383 if (socket_path == NULL)
384 socket_path = root_atom_contents("I3_SOCKET_PATH", conn, screen);
386 if (socket_path == NULL)
387 socket_path = "/tmp/i3-ipc.sock";
389 sockfd = ipc_connect(socket_path);
391 /* Request the current InputFocus to restore when i3-input exits. */
392 focus_cookie = xcb_get_input_focus(conn);
394 root_screen = xcb_aux_get_screen(conn, screen);
395 root = root_screen->root;
397 symbols = xcb_key_symbols_alloc(conn);
399 font = load_font(pattern, true);
403 prompt_offset = predict_text_width(prompt);
405 /* Open an input window */
406 win = xcb_generate_id(conn);
409 XCB_COPY_FROM_PARENT,
410 win, /* the window id */
411 root, /* parent == root */
412 logical_px(50), logical_px(50), logical_px(500), font.height + logical_px(8), /* dimensions */
413 0, /* X11 border = 0, we draw our own */
414 XCB_WINDOW_CLASS_INPUT_OUTPUT,
415 XCB_WINDOW_CLASS_COPY_FROM_PARENT, /* copy visual from parent */
416 XCB_CW_BACK_PIXEL | XCB_CW_OVERRIDE_REDIRECT | XCB_CW_EVENT_MASK,
418 0, /* back pixel: black */
419 1, /* override redirect: don’t manage this window */
420 XCB_EVENT_MASK_EXPOSURE});
422 /* Map the window (make it visible) */
423 xcb_map_window(conn, win);
426 pixmap = xcb_generate_id(conn);
427 pixmap_gc = xcb_generate_id(conn);
428 xcb_create_pixmap(conn, root_screen->root_depth, pixmap, win, logical_px(500), font.height + logical_px(8));
429 xcb_create_gc(conn, pixmap_gc, pixmap, 0, 0);
431 /* Set input focus (we have override_redirect=1, so the wm will not do
433 xcb_set_input_focus(conn, XCB_INPUT_FOCUS_POINTER_ROOT, win, XCB_CURRENT_TIME);
435 /* Grab the keyboard to get all input */
438 /* Try (repeatedly, if necessary) to grab the keyboard. We might not
439 * get the keyboard at the first attempt because of the keybinding
440 * still being active when started via a wm’s keybinding. */
441 xcb_grab_keyboard_cookie_t cookie;
442 xcb_grab_keyboard_reply_t *reply = NULL;
445 while ((reply == NULL || reply->status != XCB_GRAB_STATUS_SUCCESS) && (count++ < 500)) {
446 cookie = xcb_grab_keyboard(conn, false, win, XCB_CURRENT_TIME, XCB_GRAB_MODE_ASYNC, XCB_GRAB_MODE_ASYNC);
447 reply = xcb_grab_keyboard_reply(conn, cookie, NULL);
451 if (reply->status != XCB_GRAB_STATUS_SUCCESS) {
452 fprintf(stderr, "Could not grab keyboard, status = %d\n", reply->status);
453 restore_input_focus();
459 xcb_generic_event_t *event;
460 while ((event = xcb_wait_for_event(conn)) != NULL) {
461 if (event->response_type == 0) {
462 fprintf(stderr, "X11 Error received! sequence %x\n", event->sequence);
466 /* Strip off the highest bit (set if the event is generated) */
467 int type = (event->response_type & 0x7F);
471 handle_key_press(NULL, conn, (xcb_key_press_event_t *)event);
474 case XCB_KEY_RELEASE:
475 handle_key_release(NULL, conn, (xcb_key_release_event_t *)event);
479 handle_expose(NULL, conn, (xcb_expose_event_t *)event);