]> git.sur5r.net Git - i3/i3/blob - i3-input/main.c
c9ebd0103bf58d337cbf146fe99467c2d20b0c30
[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-2013 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 <stdio.h>
12 #include <sys/types.h>
13 #include <stdlib.h>
14 #include <stdbool.h>
15 #include <unistd.h>
16 #include <string.h>
17 #include <errno.h>
18 #include <err.h>
19 #include <stdint.h>
20 #include <getopt.h>
21 #include <limits.h>
22
23 #include <xcb/xcb.h>
24 #include <xcb/xcb_aux.h>
25 #include <xcb/xcb_event.h>
26 #include <xcb/xcb_keysyms.h>
27
28 #include <X11/keysym.h>
29
30 #include "keysym2ucs.h"
31
32 #include "i3-input.h"
33
34 #include "libi3.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 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().
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 = 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);
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, 500, font.height + 8}, inner = {2, 2, 496, font.height + 8 - 4};
133     xcb_change_gc(conn, pixmap_gc, XCB_GC_FOREGROUND, (uint32_t[]){ get_colorpixel("#FF0000") });
134     xcb_poly_fill_rectangle(conn, pixmap, pixmap_gc, 1, &border);
135     xcb_change_gc(conn, pixmap_gc, XCB_GC_FOREGROUND, (uint32_t[]){ get_colorpixel("#000000") });
136     xcb_poly_fill_rectangle(conn, pixmap, pixmap_gc, 1, &inner);
137
138     /* restore font color */
139     set_font_colors(pixmap_gc, get_colorpixel("#FFFFFF"), get_colorpixel("#000000"));
140
141     /* draw the prompt … */
142     if (prompt != NULL) {
143         draw_text(prompt, pixmap, pixmap_gc, 4, 4, 492);
144     }
145     /* … and the text */
146     if (input_position > 0)
147     {
148         i3String *input = i3string_from_ucs2(glyphs_ucs, input_position);
149         draw_text(input, pixmap, pixmap_gc, prompt_offset + 4, 4, 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, /* */ 500, font.height + 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 occurences 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("occurences = %d\n", cnt);
187
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 */
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 #if 0
220     free(command);
221     return 1;
222 #endif
223     exit(0);
224 }
225
226 /*
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.
230  *
231  * Also handles backspace (deleting one character) and return (sending the
232  * command to i3).
233  *
234  */
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);
237
238     /* See the documentation of xcb_key_symbols_get_keysym for this one.
239      * Basically: We get either col 0 or col 1, depending on whether shift is
240      * pressed. */
241     int col = (event->state & XCB_MOD_MASK_SHIFT);
242
243     /* If modeswitch is currently active, we need to look in group 2 or 3,
244      * respectively. */
245     if (modeswitch_active)
246         col += 2;
247
248     xcb_keysym_t sym = xcb_key_press_lookup_keysym(symbols, event, col);
249     if (sym == XK_Mode_switch) {
250         printf("Mode switch enabled\n");
251         modeswitch_active = true;
252         return 1;
253     }
254
255     if (sym == XK_Return)
256         finish_input();
257
258     if (sym == XK_BackSpace) {
259         if (input_position == 0)
260             return 1;
261
262         input_position--;
263         free(glyphs_utf8[input_position]);
264
265         handle_expose(NULL, conn, NULL);
266         return 1;
267     }
268     if (sym == XK_Escape) {
269         restore_input_focus();
270         exit(0);
271     }
272
273     /* TODO: handle all of these? */
274     printf("is_keypad_key = %d\n", xcb_is_keypad_key(sym));
275     printf("is_private_keypad_key = %d\n", xcb_is_private_keypad_key(sym));
276     printf("xcb_is_cursor_key = %d\n", xcb_is_cursor_key(sym));
277     printf("xcb_is_pf_key = %d\n", xcb_is_pf_key(sym));
278     printf("xcb_is_function_key = %d\n", xcb_is_function_key(sym));
279     printf("xcb_is_misc_function_key = %d\n", xcb_is_misc_function_key(sym));
280     printf("xcb_is_modifier_key = %d\n", xcb_is_modifier_key(sym));
281
282     if (xcb_is_modifier_key(sym) || xcb_is_cursor_key(sym))
283         return 1;
284
285     printf("sym = %c (%d)\n", sym, sym);
286
287     /* convert the keysym to UCS */
288     uint16_t ucs = keysym2ucs(sym);
289     if ((int16_t)ucs == -1) {
290         fprintf(stderr, "Keysym could not be converted to UCS, skipping\n");
291         return 1;
292     }
293
294     xcb_char2b_t inp;
295     inp.byte1 = ( ucs & 0xff00 ) >> 2;
296     inp.byte2 = ( ucs & 0x00ff ) >> 0;
297
298     printf("inp.byte1 = %02x, inp.byte2 = %02x\n", inp.byte1, inp.byte2);
299     /* convert it to UTF-8 */
300     char *out = convert_ucs2_to_utf8(&inp, 1);
301     printf("converted to %s\n", out);
302
303     glyphs_ucs[input_position] = inp;
304     glyphs_utf8[input_position] = out;
305     input_position++;
306
307     if (input_position == limit)
308         finish_input();
309
310     handle_expose(NULL, conn, NULL);
311     return 1;
312 }
313
314 int main(int argc, char *argv[]) {
315     format = strdup("%s");
316     socket_path = getenv("I3SOCK");
317     char *pattern = sstrdup("-misc-fixed-medium-r-normal--13-120-75-75-C-70-iso10646-1");
318     int o, option_index = 0;
319
320     static struct option long_options[] = {
321         {"socket", required_argument, 0, 's'},
322         {"version", no_argument, 0, 'v'},
323         {"limit", required_argument, 0, 'l'},
324         {"prompt", required_argument, 0, 'P'},
325         {"prefix", required_argument, 0, 'p'},
326         {"format", required_argument, 0, 'F'},
327         {"font", required_argument, 0, 'f'},
328         {"help", no_argument, 0, 'h'},
329         {0, 0, 0, 0}
330     };
331
332     char *options_string = "s:p:P:f:l:F:vh";
333
334     while ((o = getopt_long(argc, argv, options_string, long_options, &option_index)) != -1) {
335         switch (o) {
336             case 's':
337                 FREE(socket_path);
338                 socket_path = strdup(optarg);
339                 break;
340             case 'v':
341                 printf("i3-input " I3_VERSION);
342                 return 0;
343             case 'p':
344                 /* This option is deprecated, but will still work in i3 v4.1, 4.2 and 4.3 */
345                 fprintf(stderr, "i3-input: WARNING: the -p option is DEPRECATED in favor of the -F (format) option\n");
346                 FREE(format);
347                 sasprintf(&format, "%s%%s", optarg);
348                 break;
349             case 'l':
350                 limit = atoi(optarg);
351                 break;
352             case 'P':
353                 i3string_free(prompt);
354                 prompt = i3string_from_utf8(optarg);
355                 break;
356             case 'f':
357                 FREE(pattern);
358                 pattern = strdup(optarg);
359                 break;
360             case 'F':
361                 FREE(format);
362                 format = strdup(optarg);
363                 break;
364             case 'h':
365                 printf("i3-input " I3_VERSION "\n");
366                 printf("i3-input [-s <socket>] [-F <format>] [-l <limit>] [-P <prompt>] [-f <font>] [-v]\n");
367                 printf("\n");
368                 printf("Example:\n");
369                 printf("    i3-input -F 'workspace \"%%s\"' -P 'Switch to workspace: '\n");
370                 return 0;
371         }
372     }
373
374     printf("using format \"%s\"\n", format);
375
376     int screen;
377     conn = xcb_connect(NULL, &screen);
378     if (!conn || xcb_connection_has_error(conn))
379         die("Cannot open display\n");
380
381     if (socket_path == NULL)
382         socket_path = root_atom_contents("I3_SOCKET_PATH", conn, screen);
383
384     if (socket_path == NULL)
385         socket_path = "/tmp/i3-ipc.sock";
386
387     sockfd = ipc_connect(socket_path);
388
389     /* Request the current InputFocus to restore when i3-input exits. */
390     focus_cookie = xcb_get_input_focus(conn);
391
392     root_screen = xcb_aux_get_screen(conn, screen);
393     root = root_screen->root;
394
395     symbols = xcb_key_symbols_alloc(conn);
396
397     font = load_font(pattern, true);
398     set_font(&font);
399
400     if (prompt != NULL)
401         prompt_offset = predict_text_width(prompt);
402
403     /* Open an input window */
404     win = xcb_generate_id(conn);
405     xcb_create_window(
406         conn,
407         XCB_COPY_FROM_PARENT,
408         win, /* the window id */
409         root, /* parent == root */
410         50, 50, 500, font.height + 8, /* dimensions */
411         0, /* X11 border = 0, we draw our own */
412         XCB_WINDOW_CLASS_INPUT_OUTPUT,
413         XCB_WINDOW_CLASS_COPY_FROM_PARENT, /* copy visual from parent */
414         XCB_CW_BACK_PIXEL | XCB_CW_OVERRIDE_REDIRECT | XCB_CW_EVENT_MASK,
415         (uint32_t[]){
416             0, /* back pixel: black */
417             1, /* override redirect: don’t manage this window */
418             XCB_EVENT_MASK_EXPOSURE
419         });
420
421     /* Map the window (make it visible) */
422     xcb_map_window(conn, win);
423
424     /* Create pixmap */
425     pixmap = xcb_generate_id(conn);
426     pixmap_gc = xcb_generate_id(conn);
427     xcb_create_pixmap(conn, root_screen->root_depth, pixmap, win, 500, font.height + 8);
428     xcb_create_gc(conn, pixmap_gc, pixmap, 0, 0);
429
430     /* Set input focus (we have override_redirect=1, so the wm will not do
431      * this for us) */
432     xcb_set_input_focus(conn, XCB_INPUT_FOCUS_POINTER_ROOT, win, XCB_CURRENT_TIME);
433
434     /* Grab the keyboard to get all input */
435     xcb_flush(conn);
436
437     /* Try (repeatedly, if necessary) to grab the keyboard. We might not
438      * get the keyboard at the first attempt because of the keybinding
439      * still being active when started via a wm’s keybinding. */
440     xcb_grab_keyboard_cookie_t cookie;
441     xcb_grab_keyboard_reply_t *reply = NULL;
442
443     int count = 0;
444     while ((reply == NULL || reply->status != XCB_GRAB_STATUS_SUCCESS) && (count++ < 500)) {
445         cookie = xcb_grab_keyboard(conn, false, win, XCB_CURRENT_TIME, XCB_GRAB_MODE_ASYNC, XCB_GRAB_MODE_ASYNC);
446         reply = xcb_grab_keyboard_reply(conn, cookie, NULL);
447         usleep(1000);
448     }
449
450     if (reply->status != XCB_GRAB_STATUS_SUCCESS) {
451         fprintf(stderr, "Could not grab keyboard, status = %d\n", reply->status);
452         restore_input_focus();
453         exit(-1);
454     }
455
456     xcb_flush(conn);
457
458     xcb_generic_event_t *event;
459     while ((event = xcb_wait_for_event(conn)) != NULL) {
460         if (event->response_type == 0) {
461             fprintf(stderr, "X11 Error received! sequence %x\n", event->sequence);
462             continue;
463         }
464
465         /* Strip off the highest bit (set if the event is generated) */
466         int type = (event->response_type & 0x7F);
467
468         switch (type) {
469             case XCB_KEY_PRESS:
470                 handle_key_press(NULL, conn, (xcb_key_press_event_t*)event);
471                 break;
472
473             case XCB_KEY_RELEASE:
474                 handle_key_release(NULL, conn, (xcb_key_release_event_t*)event);
475                 break;
476
477             case XCB_EXPOSE:
478                 handle_expose(NULL, conn, (xcb_expose_event_t*)event);
479                 break;
480         }
481
482         free(event);
483     }
484
485     return 0;
486 }