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