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