]> git.sur5r.net Git - i3/i3/blob - i3-input/main.c
Merge branch 'master' into next
[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() and errorlog() 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 /*
80  * Restores the X11 input focus to whereever it was before.
81  * This is necessary because i3-input’s window has override_redirect=1
82  * (→ unmanaged by the window manager) and thus i3-input changes focus itself.
83  * This function is called on exit().
84  *
85  */
86 static void restore_input_focus(void) {
87     xcb_generic_error_t *error;
88     xcb_get_input_focus_reply_t *reply = xcb_get_input_focus_reply(conn, focus_cookie, &error);
89     if (error != NULL) {
90         fprintf(stderr, "[i3-input] ERROR: Could not restore input focus (X error %d)\n", error->error_code);
91         return;
92     }
93     xcb_set_input_focus(conn, XCB_INPUT_FOCUS_POINTER_ROOT, reply->focus, XCB_CURRENT_TIME);
94     xcb_flush(conn);
95 }
96
97 /*
98  * Concats the glyphs (either UCS-2 or UTF-8) to a single string, suitable for
99  * rendering it (UCS-2) or sending it to i3 (UTF-8).
100  *
101  */
102 static uint8_t *concat_strings(char **glyphs, int max) {
103     uint8_t *output = calloc(max+1, 4);
104     uint8_t *walk = output;
105     for (int c = 0; c < max; c++) {
106         printf("at %c\n", glyphs[c][0]);
107         /* if the first byte is 0, this has to be UCS2 */
108         if (glyphs[c][0] == '\0') {
109             memcpy(walk, glyphs[c], 2);
110             walk += 2;
111         } else {
112             strcpy((char*)walk, glyphs[c]);
113             walk += strlen(glyphs[c]);
114         }
115     }
116     printf("output = %s\n", output);
117     return output;
118 }
119
120 /*
121  * Handles expose events (redraws of the window) and rendering in general. Will
122  * be called from the code with event == NULL or from X with event != NULL.
123  *
124  */
125 static int handle_expose(void *data, xcb_connection_t *conn, xcb_expose_event_t *event) {
126     printf("expose!\n");
127
128     /* re-draw the background */
129     xcb_rectangle_t border = {0, 0, 500, font.height + 8}, inner = {2, 2, 496, font.height + 8 - 4};
130     xcb_change_gc(conn, pixmap_gc, XCB_GC_FOREGROUND, (uint32_t[]){ get_colorpixel("#FF0000") });
131     xcb_poly_fill_rectangle(conn, pixmap, pixmap_gc, 1, &border);
132     xcb_change_gc(conn, pixmap_gc, XCB_GC_FOREGROUND, (uint32_t[]){ get_colorpixel("#000000") });
133     xcb_poly_fill_rectangle(conn, pixmap, pixmap_gc, 1, &inner);
134
135     /* restore font color */
136     set_font_colors(pixmap_gc, get_colorpixel("#FFFFFF"), get_colorpixel("#000000"));
137
138     /* draw the prompt … */
139     if (prompt != NULL) {
140         draw_text(prompt, pixmap, pixmap_gc, 4, 4, 492);
141     }
142     /* … and the text */
143     if (input_position > 0)
144     {
145         i3String *input = i3string_from_ucs2(glyphs_ucs, input_position);
146         draw_text(input, pixmap, pixmap_gc, prompt_offset + 4, 4, 492);
147         i3string_free(input);
148     }
149
150     /* Copy the contents of the pixmap to the real window */
151     xcb_copy_area(conn, pixmap, win, pixmap_gc, 0, 0, 0, 0, /* */ 500, font.height + 8);
152     xcb_flush(conn);
153
154     return 1;
155 }
156
157 /*
158  * Deactivates the Mode_switch bit upon release of the Mode_switch key.
159  *
160  */
161 static int handle_key_release(void *ignored, xcb_connection_t *conn, xcb_key_release_event_t *event) {
162     printf("releasing %d, state raw = %d\n", event->detail, event->state);
163
164     xcb_keysym_t sym = xcb_key_press_lookup_keysym(symbols, event, event->state);
165     if (sym == XK_Mode_switch) {
166         printf("Mode switch disabled\n");
167         modeswitch_active = false;
168     }
169
170     return 1;
171 }
172
173 static void finish_input() {
174     char *command = (char*)concat_strings(glyphs_utf8, input_position);
175
176     /* count the occurences of %s in the string */
177     int c;
178     int len = strlen(format);
179     int cnt = 0;
180     for (c = 0; c < (len-1); c++)
181         if (format[c] == '%' && format[c+1] == 's')
182             cnt++;
183     printf("occurences = %d\n", cnt);
184
185     /* allocate space for the output */
186     int inputlen = strlen(command);
187     char *full = calloc(1,
188                         strlen(format) - (2 * cnt) /* format without all %s */
189                         + (inputlen * cnt)         /* replaced %s */
190                         + 1);                      /* trailing NUL */
191     char *dest = full;
192     for (c = 0; c < len; c++) {
193         /* if this is not % or it is % but without a following 's',
194          * just copy the character */
195         if (format[c] != '%' || (c == (len-1)) || format[c+1] != 's')
196             *(dest++) = format[c];
197         else {
198             strncat(dest, command, inputlen);
199             dest += inputlen;
200             /* skip the following 's' of '%s' */
201             c++;
202         }
203     }
204
205     /* prefix the command if a prefix was specified on commandline */
206     printf("command = %s\n", full);
207
208     restore_input_focus();
209
210     xcb_aux_sync(conn);
211
212     ipc_send_message(sockfd, strlen(full), 0, (uint8_t*)full);
213
214 #if 0
215     free(command);
216     return 1;
217 #endif
218     exit(0);
219 }
220
221 /*
222  * Handles keypresses by converting the keycodes to keysymbols, then the
223  * keysymbols to UCS-2. If the conversion succeeded, the glyph is saved in the
224  * internal buffers and displayed in the input window.
225  *
226  * Also handles backspace (deleting one character) and return (sending the
227  * command to i3).
228  *
229  */
230 static int handle_key_press(void *ignored, xcb_connection_t *conn, xcb_key_press_event_t *event) {
231     printf("Keypress %d, state raw = %d\n", event->detail, event->state);
232
233     /* See the documentation of xcb_key_symbols_get_keysym for this one.
234      * Basically: We get either col 0 or col 1, depending on whether shift is
235      * pressed. */
236     int col = (event->state & XCB_MOD_MASK_SHIFT);
237
238     /* If modeswitch is currently active, we need to look in group 2 or 3,
239      * respectively. */
240     if (modeswitch_active)
241         col += 2;
242
243     xcb_keysym_t sym = xcb_key_press_lookup_keysym(symbols, event, col);
244     if (sym == XK_Mode_switch) {
245         printf("Mode switch enabled\n");
246         modeswitch_active = true;
247         return 1;
248     }
249
250     if (sym == XK_Return)
251         finish_input();
252
253     if (sym == XK_BackSpace) {
254         if (input_position == 0)
255             return 1;
256
257         input_position--;
258         free(glyphs_utf8[input_position]);
259
260         handle_expose(NULL, conn, NULL);
261         return 1;
262     }
263     if (sym == XK_Escape) {
264         restore_input_focus();
265         exit(0);
266     }
267
268     /* TODO: handle all of these? */
269     printf("is_keypad_key = %d\n", xcb_is_keypad_key(sym));
270     printf("is_private_keypad_key = %d\n", xcb_is_private_keypad_key(sym));
271     printf("xcb_is_cursor_key = %d\n", xcb_is_cursor_key(sym));
272     printf("xcb_is_pf_key = %d\n", xcb_is_pf_key(sym));
273     printf("xcb_is_function_key = %d\n", xcb_is_function_key(sym));
274     printf("xcb_is_misc_function_key = %d\n", xcb_is_misc_function_key(sym));
275     printf("xcb_is_modifier_key = %d\n", xcb_is_modifier_key(sym));
276
277     if (xcb_is_modifier_key(sym) || xcb_is_cursor_key(sym))
278         return 1;
279
280     printf("sym = %c (%d)\n", sym, sym);
281
282     /* convert the keysym to UCS */
283     uint16_t ucs = keysym2ucs(sym);
284     if ((int16_t)ucs == -1) {
285         fprintf(stderr, "Keysym could not be converted to UCS, skipping\n");
286         return 1;
287     }
288
289     xcb_char2b_t inp;
290     inp.byte1 = ( ucs & 0xff00 ) >> 2;
291     inp.byte2 = ( ucs & 0x00ff ) >> 0;
292
293     printf("inp.byte1 = %02x, inp.byte2 = %02x\n", inp.byte1, inp.byte2);
294     /* convert it to UTF-8 */
295     char *out = convert_ucs2_to_utf8(&inp, 1);
296     printf("converted to %s\n", out);
297
298     glyphs_ucs[input_position] = inp;
299     glyphs_utf8[input_position] = out;
300     input_position++;
301
302     if (input_position == limit)
303         finish_input();
304
305     handle_expose(NULL, conn, NULL);
306     return 1;
307 }
308
309 int main(int argc, char *argv[]) {
310     format = strdup("%s");
311     socket_path = getenv("I3SOCK");
312     char *pattern = sstrdup("-misc-fixed-medium-r-normal--13-120-75-75-C-70-iso10646-1");
313     int o, option_index = 0;
314
315     static struct option long_options[] = {
316         {"socket", required_argument, 0, 's'},
317         {"version", no_argument, 0, 'v'},
318         {"limit", required_argument, 0, 'l'},
319         {"prompt", required_argument, 0, 'P'},
320         {"prefix", required_argument, 0, 'p'},
321         {"format", required_argument, 0, 'F'},
322         {"font", required_argument, 0, 'f'},
323         {"help", no_argument, 0, 'h'},
324         {0, 0, 0, 0}
325     };
326
327     char *options_string = "s:p:P:f:l:F:vh";
328
329     while ((o = getopt_long(argc, argv, options_string, long_options, &option_index)) != -1) {
330         switch (o) {
331             case 's':
332                 FREE(socket_path);
333                 socket_path = strdup(optarg);
334                 break;
335             case 'v':
336                 printf("i3-input " I3_VERSION);
337                 return 0;
338             case 'p':
339                 /* This option is deprecated, but will still work in i3 v4.1, 4.2 and 4.3 */
340                 fprintf(stderr, "i3-input: WARNING: the -p option is DEPRECATED in favor of the -F (format) option\n");
341                 FREE(format);
342                 sasprintf(&format, "%s%%s", optarg);
343                 break;
344             case 'l':
345                 limit = atoi(optarg);
346                 break;
347             case 'P':
348                 i3string_free(prompt);
349                 prompt = i3string_from_utf8(optarg);
350                 break;
351             case 'f':
352                 FREE(pattern);
353                 pattern = strdup(optarg);
354                 break;
355             case 'F':
356                 FREE(format);
357                 format = strdup(optarg);
358                 break;
359             case 'h':
360                 printf("i3-input " I3_VERSION "\n");
361                 printf("i3-input [-s <socket>] [-F <format>] [-l <limit>] [-P <prompt>] [-f <font>] [-v]\n");
362                 printf("\n");
363                 printf("Example:\n");
364                 printf("    i3-input -F 'workspace \"%%s\"' -P 'Switch to workspace: '\n");
365                 return 0;
366         }
367     }
368
369     printf("using format \"%s\"\n", format);
370
371     if (socket_path == NULL)
372         socket_path = root_atom_contents("I3_SOCKET_PATH");
373
374     if (socket_path == NULL)
375         socket_path = "/tmp/i3-ipc.sock";
376
377     sockfd = ipc_connect(socket_path);
378
379     int screens;
380     conn = xcb_connect(NULL, &screens);
381     if (!conn || xcb_connection_has_error(conn))
382         die("Cannot open display\n");
383
384     /* Request the current InputFocus to restore when i3-input exits. */
385     focus_cookie = xcb_get_input_focus(conn);
386
387     root_screen = xcb_aux_get_screen(conn, screens);
388     root = root_screen->root;
389
390     symbols = xcb_key_symbols_alloc(conn);
391
392     font = load_font(pattern, true);
393     set_font(&font);
394
395     if (prompt != NULL)
396         prompt_offset = predict_text_width(prompt);
397
398     /* Open an input window */
399     win = xcb_generate_id(conn);
400     xcb_create_window(
401         conn,
402         XCB_COPY_FROM_PARENT,
403         win, /* the window id */
404         root, /* parent == root */
405         50, 50, 500, font.height + 8, /* dimensions */
406         0, /* X11 border = 0, we draw our own */
407         XCB_WINDOW_CLASS_INPUT_OUTPUT,
408         XCB_WINDOW_CLASS_COPY_FROM_PARENT, /* copy visual from parent */
409         XCB_CW_BACK_PIXEL | XCB_CW_OVERRIDE_REDIRECT | XCB_CW_EVENT_MASK,
410         (uint32_t[]){
411             0, /* back pixel: black */
412             1, /* override redirect: don’t manage this window */
413             XCB_EVENT_MASK_EXPOSURE
414         });
415
416     /* Map the window (make it visible) */
417     xcb_map_window(conn, win);
418
419     /* Create pixmap */
420     pixmap = xcb_generate_id(conn);
421     pixmap_gc = xcb_generate_id(conn);
422     xcb_create_pixmap(conn, root_screen->root_depth, pixmap, win, 500, font.height + 8);
423     xcb_create_gc(conn, pixmap_gc, pixmap, 0, 0);
424
425     /* Set input focus (we have override_redirect=1, so the wm will not do
426      * this for us) */
427     xcb_set_input_focus(conn, XCB_INPUT_FOCUS_POINTER_ROOT, win, XCB_CURRENT_TIME);
428
429     /* Grab the keyboard to get all input */
430     xcb_flush(conn);
431
432     /* Try (repeatedly, if necessary) to grab the keyboard. We might not
433      * get the keyboard at the first attempt because of the keybinding
434      * still being active when started via a wm’s keybinding. */
435     xcb_grab_keyboard_cookie_t cookie;
436     xcb_grab_keyboard_reply_t *reply = NULL;
437
438     int count = 0;
439     while ((reply == NULL || reply->status != XCB_GRAB_STATUS_SUCCESS) && (count++ < 500)) {
440         cookie = xcb_grab_keyboard(conn, false, win, XCB_CURRENT_TIME, XCB_GRAB_MODE_ASYNC, XCB_GRAB_MODE_ASYNC);
441         reply = xcb_grab_keyboard_reply(conn, cookie, NULL);
442         usleep(1000);
443     }
444
445     if (reply->status != XCB_GRAB_STATUS_SUCCESS) {
446         fprintf(stderr, "Could not grab keyboard, status = %d\n", reply->status);
447         restore_input_focus();
448         exit(-1);
449     }
450
451     xcb_flush(conn);
452
453     xcb_generic_event_t *event;
454     while ((event = xcb_wait_for_event(conn)) != NULL) {
455         if (event->response_type == 0) {
456             fprintf(stderr, "X11 Error received! sequence %x\n", event->sequence);
457             continue;
458         }
459
460         /* Strip off the highest bit (set if the event is generated) */
461         int type = (event->response_type & 0x7F);
462
463         switch (type) {
464             case XCB_KEY_PRESS:
465                 handle_key_press(NULL, conn, (xcb_key_press_event_t*)event);
466                 break;
467
468             case XCB_KEY_RELEASE:
469                 handle_key_release(NULL, conn, (xcb_key_release_event_t*)event);
470                 break;
471
472             case XCB_EXPOSE:
473                 handle_expose(NULL, conn, (xcb_expose_event_t*)event);
474                 break;
475         }
476
477         free(event);
478     }
479
480     return 0;
481 }