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