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