]> 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  *
6  * © 2009-2011 Michael Stapelberg and contributors
7  *
8  * See file LICENSE for license information.
9  *
10  * i3-input/main.c: Utility which lets the user input commands and sends them
11  * to i3.
12  *
13  */
14 #include <ev.h>
15 #include <stdio.h>
16 #include <sys/types.h>
17 #include <stdlib.h>
18 #include <stdbool.h>
19 #include <unistd.h>
20 #include <string.h>
21 #include <errno.h>
22 #include <err.h>
23 #include <stdint.h>
24 #include <getopt.h>
25 #include <limits.h>
26
27 #include <xcb/xcb.h>
28 #include <xcb/xcb_aux.h>
29 #include <xcb/xcb_event.h>
30 #include <xcb/xcb_keysyms.h>
31
32 #include <X11/keysym.h>
33
34 #include "keysym2ucs.h"
35
36 #include "i3-input.h"
37
38 /* IPC format string. %s will be replaced with what the user entered, then
39  * the command will be sent to i3 */
40 static char *format;
41
42 static char *socket_path;
43 static int sockfd;
44 static xcb_key_symbols_t *symbols;
45 static int modeswitchmask;
46 static int numlockmask;
47 static bool modeswitch_active = false;
48 static xcb_window_t win;
49 static xcb_pixmap_t pixmap;
50 static xcb_gcontext_t pixmap_gc;
51 static char *glyphs_ucs[512];
52 static char *glyphs_utf8[512];
53 static int input_position;
54 static int font_height;
55 static char *prompt;
56 static int prompt_len;
57 static int limit;
58 xcb_window_t root;
59
60 /*
61  * Try to get the socket path from X11 and return NULL if it doesn’t work.
62  * As i3-msg is a short-running tool, we don’t bother with cleaning up the
63  * connection and leave it up to the operating system on exit.
64  *
65  */
66 static char *socket_path_from_x11() {
67     xcb_connection_t *conn;
68     int screen;
69     if ((conn = xcb_connect(NULL, &screen)) == NULL ||
70         xcb_connection_has_error(conn))
71         return NULL;
72     xcb_screen_t *root_screen = xcb_aux_get_screen(conn, screen);
73     xcb_window_t root = root_screen->root;
74
75     xcb_intern_atom_cookie_t atom_cookie;
76     xcb_intern_atom_reply_t *atom_reply;
77
78     atom_cookie = xcb_intern_atom(conn, 0, strlen("I3_SOCKET_PATH"), "I3_SOCKET_PATH");
79     atom_reply = xcb_intern_atom_reply(conn, atom_cookie, NULL);
80     if (atom_reply == NULL)
81         return NULL;
82
83     xcb_get_property_cookie_t prop_cookie;
84     xcb_get_property_reply_t *prop_reply;
85     prop_cookie = xcb_get_property_unchecked(conn, false, root, atom_reply->atom,
86                                              XCB_GET_PROPERTY_TYPE_ANY, 0, PATH_MAX);
87     prop_reply = xcb_get_property_reply(conn, prop_cookie, NULL);
88     if (prop_reply == NULL || xcb_get_property_value_length(prop_reply) == 0)
89         return NULL;
90     if (asprintf(&socket_path, "%.*s", xcb_get_property_value_length(prop_reply),
91                  (char*)xcb_get_property_value(prop_reply)) == -1)
92         return NULL;
93     return socket_path;
94 }
95
96 /*
97  * Concats the glyphs (either UCS-2 or UTF-8) to a single string, suitable for
98  * rendering it (UCS-2) or sending it to i3 (UTF-8).
99  *
100  */
101 static uint8_t *concat_strings(char **glyphs, int max) {
102     uint8_t *output = calloc(max+1, 4);
103     uint8_t *walk = output;
104     for (int c = 0; c < max; c++) {
105         printf("at %c\n", glyphs[c][0]);
106         /* if the first byte is 0, this has to be UCS2 */
107         if (glyphs[c][0] == '\0') {
108             memcpy(walk, glyphs[c], 2);
109             walk += 2;
110         } else {
111             strcpy((char*)walk, glyphs[c]);
112             walk += strlen(glyphs[c]);
113         }
114     }
115     printf("output = %s\n", output);
116     return output;
117 }
118
119 /*
120  * Handles expose events (redraws of the window) and rendering in general. Will
121  * be called from the code with event == NULL or from X with event != NULL.
122  *
123  */
124 static int handle_expose(void *data, xcb_connection_t *conn, xcb_expose_event_t *event) {
125     printf("expose!\n");
126
127     /* re-draw the background */
128     xcb_rectangle_t border = {0, 0, 500, font_height + 8}, inner = {2, 2, 496, font_height + 8 - 4};
129     xcb_change_gc_single(conn, pixmap_gc, XCB_GC_FOREGROUND, get_colorpixel(conn, "#FF0000"));
130     xcb_poly_fill_rectangle(conn, pixmap, pixmap_gc, 1, &border);
131     xcb_change_gc_single(conn, pixmap_gc, XCB_GC_FOREGROUND, get_colorpixel(conn, "#000000"));
132     xcb_poly_fill_rectangle(conn, pixmap, pixmap_gc, 1, &inner);
133
134     /* restore font color */
135     xcb_change_gc_single(conn, pixmap_gc, XCB_GC_FOREGROUND, get_colorpixel(conn, "#FFFFFF"));
136     uint8_t *con = concat_strings(glyphs_ucs, input_position);
137     char *full_text = (char*)con;
138     if (prompt != NULL) {
139         full_text = malloc((prompt_len + input_position) * 2 + 1);
140         if (full_text == NULL)
141             err(EXIT_FAILURE, "malloc() failed\n");
142         memcpy(full_text, prompt, prompt_len * 2);
143         memcpy(full_text + (prompt_len * 2), con, input_position * 2);
144     }
145     xcb_image_text_16(conn, input_position + prompt_len, pixmap, pixmap_gc, 4 /* X */,
146                       font_height + 2 /* Y = baseline of font */, (xcb_char2b_t*)full_text);
147
148     /* Copy the contents of the pixmap to the real window */
149     xcb_copy_area(conn, pixmap, win, pixmap_gc, 0, 0, 0, 0, /* */ 500, font_height + 8);
150     xcb_flush(conn);
151     free(con);
152     if (prompt != NULL)
153         free(full_text);
154
155     return 1;
156 }
157
158 /*
159  * Deactivates the Mode_switch bit upon release of the Mode_switch key.
160  *
161  */
162 static int handle_key_release(void *ignored, xcb_connection_t *conn, xcb_key_release_event_t *event) {
163     printf("releasing %d, state raw = %d\n", event->detail, event->state);
164
165     /* fix state */
166     event->state &= ~numlockmask;
167
168     xcb_keysym_t sym = xcb_key_press_lookup_keysym(symbols, event, event->state);
169     if (sym == XK_Mode_switch) {
170         printf("Mode switch disabled\n");
171         modeswitch_active = false;
172     }
173
174     return 1;
175 }
176
177 static void finish_input() {
178     char *command = (char*)concat_strings(glyphs_utf8, input_position);
179
180     /* count the occurences of %s in the string */
181     int c;
182     int len = strlen(format);
183     int cnt = 0;
184     for (c = 0; c < (len-1); c++)
185         if (format[c] == '%' && format[c+1] == 's')
186             cnt++;
187     printf("occurences = %d\n", cnt);
188
189     /* allocate space for the output */
190     int inputlen = strlen(command);
191     char *full = calloc(1,
192                         strlen(format) - (2 * cnt) /* format without all %s */
193                         + (inputlen * cnt)         /* replaced %s */
194                         + 1);                      /* trailing NUL */
195     char *dest = full;
196     for (c = 0; c < len; c++) {
197         /* if this is not % or it is % but without a following 's',
198          * just copy the character */
199         if (format[c] != '%' || (c == (len-1)) || format[c+1] != 's')
200             *(dest++) = format[c];
201         else {
202             strncat(dest, command, inputlen);
203             dest += inputlen;
204             /* skip the following 's' of '%s' */
205             c++;
206         }
207     }
208
209     /* prefix the command if a prefix was specified on commandline */
210     printf("command = %s\n", full);
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     /* fix state */
234     if (modeswitch_active)
235         event->state |= modeswitchmask;
236
237     /* Apparantly, after activating numlock once, the numlock modifier
238      * stays turned on (use xev(1) to verify). So, to resolve useful
239      * keysyms, we remove the numlock flag from the event state */
240     event->state &= ~numlockmask;
241
242     xcb_keysym_t sym = xcb_key_press_lookup_keysym(symbols, event, event->state);
243     if (sym == XK_Mode_switch) {
244         printf("Mode switch enabled\n");
245         modeswitch_active = true;
246         return 1;
247     }
248
249     if (sym == XK_Return)
250         finish_input();
251
252     if (sym == XK_BackSpace) {
253         if (input_position == 0)
254             return 1;
255
256         input_position--;
257         free(glyphs_ucs[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         exit(0);
265     }
266
267     /* TODO: handle all of these? */
268     printf("is_keypad_key = %d\n", xcb_is_keypad_key(sym));
269     printf("is_private_keypad_key = %d\n", xcb_is_private_keypad_key(sym));
270     printf("xcb_is_cursor_key = %d\n", xcb_is_cursor_key(sym));
271     printf("xcb_is_pf_key = %d\n", xcb_is_pf_key(sym));
272     printf("xcb_is_function_key = %d\n", xcb_is_function_key(sym));
273     printf("xcb_is_misc_function_key = %d\n", xcb_is_misc_function_key(sym));
274     printf("xcb_is_modifier_key = %d\n", xcb_is_modifier_key(sym));
275
276     if (xcb_is_modifier_key(sym) || xcb_is_cursor_key(sym))
277         return 1;
278
279     printf("sym = %c (%d)\n", sym, sym);
280
281     /* convert the keysym to UCS */
282     uint16_t ucs = keysym2ucs(sym);
283     if ((int16_t)ucs == -1) {
284         fprintf(stderr, "Keysym could not be converted to UCS, skipping\n");
285         return 1;
286     }
287
288     /* store the UCS into a string */
289     uint8_t inp[3] = {(ucs & 0xFF00) >> 8, (ucs & 0xFF), 0};
290
291     printf("inp[0] = %02x, inp[1] = %02x, inp[2] = %02x\n", inp[0], inp[1], inp[2]);
292     /* convert it to UTF-8 */
293     char *out = convert_ucs_to_utf8((char*)inp);
294     printf("converted to %s\n", out);
295
296     glyphs_ucs[input_position] = malloc(3 * sizeof(uint8_t));
297     if (glyphs_ucs[input_position] == NULL)
298         err(EXIT_FAILURE, "malloc() failed\n");
299     memcpy(glyphs_ucs[input_position], inp, 3);
300     glyphs_utf8[input_position] = strdup(out);
301     input_position++;
302
303     if (input_position == limit)
304         finish_input();
305
306     handle_expose(NULL, conn, NULL);
307     return 1;
308 }
309
310 int main(int argc, char *argv[]) {
311     format = strdup("%s");
312     socket_path = getenv("I3SOCK");
313     char *pattern = "-misc-fixed-medium-r-normal--13-120-75-75-C-70-iso10646-1";
314     int o, option_index = 0;
315
316     static struct option long_options[] = {
317         {"socket", required_argument, 0, 's'},
318         {"version", no_argument, 0, 'v'},
319         {"limit", required_argument, 0, 'l'},
320         {"prompt", required_argument, 0, 'P'},
321         {"prefix", required_argument, 0, 'p'},
322         {"format", required_argument, 0, 'F'},
323         {"font", required_argument, 0, 'f'},
324         {"help", no_argument, 0, 'h'},
325         {0, 0, 0, 0}
326     };
327
328     char *options_string = "s:p:P:f:l:F:vh";
329
330     while ((o = getopt_long(argc, argv, options_string, long_options, &option_index)) != -1) {
331         switch (o) {
332             case 's':
333                 FREE(socket_path);
334                 socket_path = strdup(optarg);
335                 break;
336             case 'v':
337                 printf("i3-input " I3_VERSION);
338                 return 0;
339             case 'p':
340                 /* This option is deprecated, but will still work in i3 v4.1, 4.2 and 4.3 */
341                 fprintf(stderr, "i3-input: WARNING: the -p option is DEPRECATED in favor of the -F (format) option\n");
342                 FREE(format);
343                 asprintf(&format, "%s%%s", optarg);
344                 break;
345             case 'l':
346                 limit = atoi(optarg);
347                 break;
348             case 'P':
349                 FREE(prompt);
350                 prompt = strdup(optarg);
351                 break;
352             case 'f':
353                 FREE(pattern);
354                 pattern = strdup(optarg);
355                 break;
356             case 'F':
357                 FREE(format);
358                 format = strdup(optarg);
359                 break;
360             case 'h':
361                 printf("i3-input " I3_VERSION "\n");
362                 printf("i3-input [-s <socket>] [-F <format>] [-l <limit>] [-P <prompt>] [-f <font>] [-v]\n");
363                 printf("\n");
364                 printf("Example:\n");
365                 printf("    i3-input -F 'workspace \"%%s\"' -P 'Switch to workspace: '\n");
366                 return 0;
367         }
368     }
369
370     printf("using format \"%s\"\n", format);
371
372     if (socket_path == NULL)
373         socket_path = socket_path_from_x11();
374
375     if (socket_path == NULL)
376         socket_path = "/tmp/i3-ipc.sock";
377
378     sockfd = connect_ipc(socket_path);
379
380     if (prompt != NULL)
381         prompt = convert_utf8_to_ucs2(prompt, &prompt_len);
382
383     int screens;
384     xcb_connection_t *conn = xcb_connect(NULL, &screens);
385     if (xcb_connection_has_error(conn))
386         die("Cannot open display\n");
387
388     xcb_screen_t *root_screen = xcb_aux_get_screen(conn, screens);
389     root = root_screen->root;
390
391     modeswitchmask = get_mod_mask(conn, XK_Mode_switch);
392     numlockmask = get_mod_mask(conn, XK_Num_Lock);
393     symbols = xcb_key_symbols_alloc(conn);
394
395     uint32_t font_id = get_font_id(conn, pattern, &font_height);
396
397     /* Open an input window */
398     win = open_input_window(conn, 500, font_height + 8);
399
400     /* Create pixmap */
401     pixmap = xcb_generate_id(conn);
402     pixmap_gc = xcb_generate_id(conn);
403     xcb_create_pixmap(conn, root_screen->root_depth, pixmap, win, 500, font_height + 8);
404     xcb_create_gc(conn, pixmap_gc, pixmap, 0, 0);
405
406     /* Set input focus (we have override_redirect=1, so the wm will not do
407      * this for us) */
408     xcb_set_input_focus(conn, XCB_INPUT_FOCUS_POINTER_ROOT, win, XCB_CURRENT_TIME);
409
410     /* Create graphics context */
411     xcb_change_gc_single(conn, pixmap_gc, XCB_GC_FONT, font_id);
412
413     /* Grab the keyboard to get all input */
414     xcb_flush(conn);
415
416     /* Try (repeatedly, if necessary) to grab the keyboard. We might not
417      * get the keyboard at the first attempt because of the keybinding
418      * still being active when started via a wm’s keybinding. */
419     xcb_grab_keyboard_cookie_t cookie;
420     xcb_grab_keyboard_reply_t *reply = NULL;
421
422     int count = 0;
423     while ((reply == NULL || reply->status != XCB_GRAB_STATUS_SUCCESS) && (count++ < 500)) {
424         cookie = xcb_grab_keyboard(conn, false, win, XCB_CURRENT_TIME, XCB_GRAB_MODE_ASYNC, XCB_GRAB_MODE_ASYNC);
425         reply = xcb_grab_keyboard_reply(conn, cookie, NULL);
426         usleep(1000);
427     }
428
429     if (reply->status != XCB_GRAB_STATUS_SUCCESS) {
430         fprintf(stderr, "Could not grab keyboard, status = %d\n", reply->status);
431         exit(-1);
432     }
433
434     xcb_flush(conn);
435
436     xcb_generic_event_t *event;
437     while ((event = xcb_wait_for_event(conn)) != NULL) {
438         if (event->response_type == 0) {
439             fprintf(stderr, "X11 Error received! sequence %x\n", event->sequence);
440             continue;
441         }
442
443         /* Strip off the highest bit (set if the event is generated) */
444         int type = (event->response_type & 0x7F);
445
446         switch (type) {
447             case XCB_KEY_PRESS:
448                 handle_key_press(NULL, conn, (xcb_key_press_event_t*)event);
449                 break;
450
451             case XCB_KEY_RELEASE:
452                 handle_key_release(NULL, conn, (xcb_key_release_event_t*)event);
453                 break;
454
455             case XCB_EXPOSE:
456                 handle_expose(NULL, conn, (xcb_expose_event_t*)event);
457                 break;
458         }
459
460         free(event);
461     }
462
463     return 0;
464 }