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