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