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