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