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