Recognize Insert key on cons25 (FreeBSD console)
[elinks.git] / src / terminal / kbd.c
blobd9ffde755899e4638788c9c4758dc744d8e78723
1 /** Support for keyboard interface
2 * @file
4 * @todo TODO: move stuff from here to itrm.{c,h} and mouse.{c,h}
5 */
7 #ifdef HAVE_CONFIG_H
8 #include "config.h"
9 #endif
11 #include <stdlib.h>
12 #include <string.h>
13 #ifdef HAVE_TERMIOS_H
14 #include <termios.h>
15 #endif
16 #ifdef HAVE_UNISTD_H
17 #include <unistd.h>
18 #endif
19 #ifdef __hpux__
20 #include <limits.h>
21 #define HPUX_PIPE (len > PIPE_BUF || errno != EAGAIN)
22 #else
23 #define HPUX_PIPE 1
24 #endif
26 #include "elinks.h"
28 #include "config/options.h"
29 #include "intl/gettext/libintl.h"
30 #include "main/select.h"
31 #include "main/timer.h"
32 #include "osdep/ascii.h"
33 #include "osdep/osdep.h"
34 #include "terminal/hardio.h"
35 #include "terminal/itrm.h"
36 #include "terminal/kbd.h"
37 #include "terminal/mouse.h"
38 #include "terminal/terminal.h"
39 #include "util/error.h"
40 #include "util/memory.h"
41 #include "util/string.h"
42 #include "util/time.h"
44 struct itrm *ditrm = NULL;
46 static void free_itrm(struct itrm *);
47 static void in_kbd(struct itrm *);
48 static void in_sock(struct itrm *);
49 static int process_queue(struct itrm *);
50 static void handle_itrm_stdin(struct itrm *);
51 static void unhandle_itrm_stdin(struct itrm *);
53 #ifdef CONFIG_DEBUG
54 /** This hack makes GCC put enum term_event_special_key in the debug
55 * information even though it is not otherwise used. The const
56 * prevents an unused-variable warning. */
57 static const enum term_event_special_key dummy_term_event_special_key;
58 #endif
61 int
62 is_blocked(void)
64 return ditrm && ditrm->blocked;
68 void
69 free_all_itrms(void)
71 if (ditrm) free_itrm(ditrm);
75 /** A select_handler_T write_func for itrm_out.sock. This is called
76 * when there is data in @c itrm->out.queue and it is possible to write
77 * it to @c itrm->out.sock. When @c itrm->out.queue becomes empty, this
78 * handler is temporarily removed. */
79 static void
80 itrm_queue_write(struct itrm *itrm)
82 int written;
83 int qlen = int_min(itrm->out.queue.len, 128);
85 assertm(qlen, "event queue empty");
86 if_assert_failed return;
88 written = safe_write(itrm->out.sock, itrm->out.queue.data, qlen);
89 if (written <= 0) {
90 if (written < 0) free_itrm(itrm); /* write error */
91 return;
94 itrm->out.queue.len -= written;
96 if (itrm->out.queue.len == 0) {
97 set_handlers(itrm->out.sock,
98 get_handler(itrm->out.sock, SELECT_HANDLER_READ),
99 NULL,
100 get_handler(itrm->out.sock, SELECT_HANDLER_ERROR),
101 get_handler(itrm->out.sock, SELECT_HANDLER_DATA));
102 } else {
103 assert(itrm->out.queue.len > 0);
104 memmove(itrm->out.queue.data, itrm->out.queue.data + written, itrm->out.queue.len);
109 void
110 itrm_queue_event(struct itrm *itrm, unsigned char *data, int len)
112 int w = 0;
114 if (!len) return;
116 if (!itrm->out.queue.len && can_write(itrm->out.sock)) {
117 w = safe_write(itrm->out.sock, data, len);
118 if (w <= 0 && HPUX_PIPE) {
119 register_bottom_half(free_itrm, itrm);
120 return;
124 if (w < len) {
125 int left = len - w;
126 unsigned char *c = mem_realloc(itrm->out.queue.data,
127 itrm->out.queue.len + left);
129 if (!c) {
130 free_itrm(itrm);
131 return;
134 itrm->out.queue.data = c;
135 memcpy(itrm->out.queue.data + itrm->out.queue.len, data + w, left);
136 itrm->out.queue.len += left;
137 set_handlers(itrm->out.sock,
138 get_handler(itrm->out.sock, SELECT_HANDLER_READ),
139 (select_handler_T) itrm_queue_write,
140 (select_handler_T) free_itrm, itrm);
145 void
146 kbd_ctrl_c(void)
148 struct interlink_event ev;
150 if (!ditrm) return;
151 set_kbd_interlink_event(&ev, KBD_CTRL_C, KBD_MOD_NONE);
152 itrm_queue_event(ditrm, (unsigned char *) &ev, sizeof(ev));
155 #define write_sequence(fd, seq) \
156 hard_write(fd, seq, sizeof(seq) - 1)
159 #define INIT_TERMINAL_SEQ "\033)0\0337" /**< Special Character and Line Drawing Set, Save Cursor */
160 #define INIT_ALT_SCREEN_SEQ "\033[?47h" /**< Use Alternate Screen Buffer */
162 static void
163 send_init_sequence(int h, int altscreen)
165 write_sequence(h, INIT_TERMINAL_SEQ);
167 /* If alternate screen is supported switch to it. */
168 if (altscreen) {
169 write_sequence(h, INIT_ALT_SCREEN_SEQ);
171 #ifdef CONFIG_MOUSE
172 send_mouse_init_sequence(h);
173 #endif
176 #define DONE_CLS_SEQ "\033[2J" /**< Erase in Display, Clear All */
177 #define DONE_TERMINAL_SEQ "\0338\r \b" /**< Restore Cursor (DECRC) + ??? */
178 #define DONE_ALT_SCREEN_SEQ "\033[?47l" /**< Use Normal Screen Buffer */
180 static void
181 send_done_sequence(int h, int altscreen)
183 write_sequence(h, DONE_CLS_SEQ);
185 #ifdef CONFIG_MOUSE
186 send_mouse_done_sequence(h);
187 #endif
189 /* Switch from alternate screen. */
190 if (altscreen) {
191 write_sequence(h, DONE_ALT_SCREEN_SEQ);
194 write_sequence(h, DONE_TERMINAL_SEQ);
198 #undef write_sequence
200 void
201 resize_terminal(void)
203 struct interlink_event ev;
204 int width, height;
206 get_terminal_size(ditrm->out.std, &width, &height);
207 set_resize_interlink_event(&ev, width, height);
208 itrm_queue_event(ditrm, (char *) &ev, sizeof(ev));
211 void
212 get_terminal_name(unsigned char name[MAX_TERM_LEN])
214 unsigned char *term = getenv("TERM");
215 int i;
217 memset(name, 0, MAX_TERM_LEN);
219 if (!term) return;
221 for (i = 0; term[i] != 0 && i < MAX_TERM_LEN - 1; i++)
222 name[i] = isident(term[i]) ? term[i] : '-';
226 static int
227 setraw(struct itrm *itrm, int save_orig)
229 struct termios t;
230 long vdisable;
232 memset(&t, 0, sizeof(t));
233 if (tcgetattr(itrm->in.ctl, &t)) return -1;
235 if (save_orig) copy_struct(&itrm->t, &t);
237 #ifdef _POSIX_VDISABLE
238 vdisable = _POSIX_VDISABLE;
239 #else
240 vdisable = fpathconf(itrm->in.ctl, _PC_VDISABLE);
241 #endif
242 if (vdisable != -1 && t.c_cc[VERASE] == vdisable)
243 itrm->verase = -1;
244 else
245 itrm->verase = (unsigned char) t.c_cc[VERASE];
247 elinks_cfmakeraw(&t);
248 t.c_lflag |= ISIG;
249 #ifdef TOSTOP
250 t.c_lflag |= TOSTOP;
251 #endif
252 t.c_oflag |= OPOST;
253 if (tcsetattr(itrm->in.ctl, TCSANOW, &t)) return -1;
255 return 0;
258 /** Construct the struct itrm of this process, make ::ditrm point to it,
259 * set up select() handlers, and send the initial interlink packet.
261 * The first five parameters are file descriptors that this function
262 * saves in submembers of struct itrm, and for which this function may
263 * set select() handlers. Please see the definitions of struct
264 * itrm_in and struct itrm_out for further explanations.
266 * @param std_in itrm_in.std: read tty device (or pipe)
267 * @param std_out itrm_out.std: write tty device (or pipe)
268 * @param sock_in itrm_in.sock
269 * - If master: == @a std_out (masterhood flag)
270 * - If slave: read socket from master
271 * @param sock_out itrm_out.sock
272 * - If master: write pipe to same process
273 * - If slave: write socket to master
274 * @param ctl_in itrm_in.ctl: control tty device
276 * The remaining three parameters control the initial interlink packet.
278 * @param init_string A string to be passed to the master process. Need
279 * not be null-terminated. If @a remote == 0, this is
280 * a URI. Otherwise, this is a remote command.
281 * @param init_len The length of init_string, in bytes.
282 * @param remote = 0 if asking the master to start a new session
283 * and display it via this process. Otherwise,
284 * enum ::remote_session_flags. */
285 void
286 handle_trm(int std_in, int std_out, int sock_in, int sock_out, int ctl_in,
287 void *init_string, int init_len, int remote)
289 struct itrm *itrm;
290 struct terminal_info info;
291 struct interlink_event_size *size = &info.event.info.size;
292 unsigned char *ts;
294 memset(&info, 0, sizeof(info));
296 get_terminal_size(ctl_in, &size->width, &size->height);
297 info.event.ev = EVENT_INIT;
298 info.system_env = get_system_env();
299 info.length = init_len;
301 if (remote) {
302 info.session_info = remote;
303 info.magic = INTERLINK_REMOTE_MAGIC;
304 } else {
305 info.session_info = get_cmd_opt_int("base-session");
306 info.magic = INTERLINK_NORMAL_MAGIC;
309 itrm = mem_calloc(1, sizeof(*itrm));
310 if (!itrm) return;
312 itrm->in.queue.data = mem_calloc(1, ITRM_IN_QUEUE_SIZE);
313 if (!itrm->in.queue.data) {
314 mem_free(itrm);
315 return;
318 ditrm = itrm;
319 itrm->in.std = std_in;
320 itrm->out.std = std_out;
321 itrm->in.sock = sock_in;
322 itrm->out.sock = sock_out;
323 itrm->in.ctl = ctl_in;
324 itrm->timer = TIMER_ID_UNDEF;
325 itrm->remote = !!remote;
327 /* FIXME: Combination altscreen + xwin does not work as it should,
328 * mouse clicks are reportedly partially ignored. */
329 if (info.system_env & (ENV_SCREEN | ENV_XWIN))
330 itrm->altscreen = 1;
332 if (!remote) {
333 if (ctl_in >= 0) setraw(itrm, 1);
334 send_init_sequence(std_out, itrm->altscreen);
335 handle_terminal_resize(ctl_in, resize_terminal);
336 #ifdef CONFIG_MOUSE
337 enable_mouse();
338 #endif
339 handle_itrm_stdin(itrm);
340 } else {
341 /* elinks -remote may not have a valid stdin if not run from a tty (bug 938) */
342 if (std_in >= 0) handle_itrm_stdin(itrm);
345 if (sock_in != std_out)
346 set_handlers(sock_in, (select_handler_T) in_sock,
347 NULL, (select_handler_T) free_itrm, itrm);
349 get_terminal_name(info.name);
351 ts = get_cwd();
352 if (ts) {
353 memcpy(info.cwd, ts, int_min(strlen(ts), MAX_CWD_LEN));
354 mem_free(ts);
357 itrm_queue_event(itrm, (char *) &info, TERMINAL_INFO_SIZE);
358 itrm_queue_event(itrm, (char *) init_string, init_len);
362 /** A select_handler_T read_func and error_func for the pipe (long) @a h.
363 * This is called when the subprocess started on the terminal of this
364 * ELinks process exits. ELinks then resumes using the terminal. */
365 static void
366 unblock_itrm_x(void *h)
368 close_handle(h);
369 if (!ditrm) return;
370 unblock_itrm();
371 resize_terminal();
376 unblock_itrm(void)
378 if (!ditrm) return -1;
380 if (ditrm->in.ctl >= 0 && setraw(ditrm, 0)) return -1;
381 ditrm->blocked = 0;
382 send_init_sequence(ditrm->out.std, ditrm->altscreen);
384 handle_itrm_stdin(ditrm);
385 resume_mouse(ditrm->mouse_h);
387 handle_terminal_resize(ditrm->in.ctl, resize_terminal);
388 unblock_stdin();
390 return 0;
394 void
395 block_itrm(void)
397 if (!ditrm) return;
399 ditrm->blocked = 1;
400 block_stdin();
401 kill_timer(&ditrm->timer);
402 ditrm->in.queue.len = 0;
403 unhandle_terminal_resize(ditrm->in.ctl);
404 send_done_sequence(ditrm->out.std, ditrm->altscreen);
405 tcsetattr(ditrm->in.ctl, TCSANOW, &ditrm->t);
406 unhandle_itrm_stdin(ditrm);
407 suspend_mouse(ditrm->mouse_h);
411 static void
412 free_itrm(struct itrm *itrm)
414 if (!itrm) return;
416 if (!itrm->remote) {
417 if (itrm->orig_title && *itrm->orig_title) {
418 set_window_title(itrm->orig_title);
420 } else if (itrm->touched_title) {
421 /* Set the window title to the value of $TERM if X11
422 * wasn't compiled in. Should hopefully make at least
423 * half the users happy. (debian bug #312955) */
424 unsigned char title[MAX_TERM_LEN];
426 get_terminal_name(title);
427 if (*title)
428 set_window_title(title);
432 unhandle_terminal_resize(itrm->in.ctl);
433 #ifdef CONFIG_MOUSE
434 disable_mouse();
435 #endif
436 send_done_sequence(itrm->out.std, itrm->altscreen);
437 tcsetattr(itrm->in.ctl, TCSANOW, &itrm->t);
440 mem_free_set(&itrm->orig_title, NULL);
442 /* elinks -remote may not have a valid stdin if not run from a tty (bug 938) */
443 if (!itrm->remote || itrm->in.std >= 0) clear_handlers(itrm->in.std);
444 clear_handlers(itrm->in.sock);
445 clear_handlers(itrm->out.std);
446 clear_handlers(itrm->out.sock);
448 kill_timer(&itrm->timer);
450 if (itrm == ditrm) ditrm = NULL;
451 mem_free_if(itrm->out.queue.data);
452 mem_free_if(itrm->in.queue.data);
453 mem_free(itrm);
456 /** Resize terminal to dimensions specified by @a text string.
457 * @a text should look like "width,height,old-width,old-height"
458 * where width and height are integers. */
459 static inline void
460 resize_terminal_from_str(unsigned char *text)
462 enum { NEW_WIDTH = 0, NEW_HEIGHT, OLD_WIDTH, OLD_HEIGHT, NUMBERS } i;
463 int numbers[NUMBERS];
465 assert(text && *text);
466 if_assert_failed return;
468 for (i = 0; i < NUMBERS; i++) {
469 unsigned char *p = strchr(text, ',');
471 if (p) {
472 *p++ = '\0';
474 } else if (i < OLD_HEIGHT) {
475 return;
478 numbers[i] = atoi(text);
480 if (p) text = p;
483 resize_window(numbers[NEW_WIDTH], numbers[NEW_HEIGHT],
484 numbers[OLD_WIDTH], numbers[OLD_HEIGHT]);
485 resize_terminal();
488 void
489 dispatch_special(unsigned char *text)
491 switch (text[0]) {
492 case TERM_FN_TITLE:
493 if (ditrm) {
494 if (ditrm->remote)
495 break;
497 if (!ditrm->orig_title)
498 ditrm->orig_title = get_window_title();
499 ditrm->touched_title = 1;
501 set_window_title(text + 1);
502 break;
503 case TERM_FN_RESIZE:
504 if (ditrm && ditrm->remote)
505 break;
507 resize_terminal_from_str(text + 1);
508 break;
512 static void inline
513 safe_hard_write(int fd, unsigned char *buf, int len)
515 if (is_blocked()) return;
517 want_draw();
518 hard_write(fd, buf, len);
519 done_draw();
522 /** A select_handler_T read_func for itrm_in.sock. A slave process
523 * calls this when the master sends it data to be displayed. The
524 * master process never calls this. */
525 static void
526 in_sock(struct itrm *itrm)
528 struct string path;
529 struct string delete;
530 char ch;
531 int fg; /* enum term_exec */
532 ssize_t bytes_read, i, p;
533 unsigned char buf[ITRM_OUT_QUEUE_SIZE];
535 bytes_read = safe_read(itrm->in.sock, buf, ITRM_OUT_QUEUE_SIZE);
536 if (bytes_read <= 0) goto free_and_return;
538 qwerty:
539 for (i = 0; i < bytes_read; i++)
540 if (!buf[i])
541 goto has_nul_byte;
543 safe_hard_write(itrm->out.std, buf, bytes_read);
544 return;
546 has_nul_byte:
547 if (i) safe_hard_write(itrm->out.std, buf, i);
549 i++;
550 assert(ITRM_OUT_QUEUE_SIZE - i > 0);
551 memmove(buf, buf + i, ITRM_OUT_QUEUE_SIZE - i);
552 bytes_read -= i;
553 p = 0;
555 #define RD(xx) { \
556 unsigned char cc; \
558 if (p < bytes_read) \
559 cc = buf[p++]; \
560 else if ((hard_read(itrm->in.sock, &cc, 1)) <= 0) \
561 goto free_and_return; \
562 xx = cc; \
565 RD(fg);
567 if (!init_string(&path)) goto free_and_return;
569 while (1) {
570 RD(ch);
571 if (!ch) break;
572 add_char_to_string(&path, ch);
575 if (!init_string(&delete)) {
576 done_string(&path);
577 goto free_and_return;
580 while (1) {
581 RD(ch);
582 if (!ch) break;
583 add_char_to_string(&delete, ch);
586 #undef RD
588 if (!*path.source) {
589 dispatch_special(delete.source);
591 } else {
592 int blockh;
593 unsigned char *param;
594 int path_len, del_len, param_len;
596 /* TODO: Should this be changed to allow TERM_EXEC_NEWWIN
597 * in a blocked terminal? There is similar code in
598 * exec_on_terminal(). --KON, 2007 */
599 if (is_blocked() && fg != TERM_EXEC_BG) {
600 if (*delete.source) unlink(delete.source);
601 goto nasty_thing;
604 path_len = path.length;
605 del_len = delete.length;
606 param_len = path_len + del_len + 3;
608 param = mem_alloc(param_len);
609 if (!param) goto nasty_thing;
611 param[0] = fg;
612 memcpy(param + 1, path.source, path_len + 1);
613 memcpy(param + 1 + path_len + 1, delete.source, del_len + 1);
615 if (fg == TERM_EXEC_FG) block_itrm();
617 blockh = start_thread((void (*)(void *, int)) exec_thread,
618 param, param_len);
619 mem_free(param);
621 if (blockh == -1) {
622 if (fg == TERM_EXEC_FG)
623 unblock_itrm();
625 goto nasty_thing;
628 if (fg == TERM_EXEC_FG) {
629 set_handlers(blockh, (select_handler_T) unblock_itrm_x,
630 NULL, (select_handler_T) unblock_itrm_x,
631 (void *) (long) blockh);
633 } else {
634 set_handlers(blockh, close_handle, NULL, close_handle,
635 (void *) (long) blockh);
639 nasty_thing:
640 done_string(&path);
641 done_string(&delete);
642 assert(ITRM_OUT_QUEUE_SIZE - p > 0);
643 memmove(buf, buf + p, ITRM_OUT_QUEUE_SIZE - p);
644 bytes_read -= p;
646 goto qwerty;
648 free_and_return:
649 free_itrm(itrm);
653 /** Parse an ECMA-48 control sequence that was received from a
654 * terminal. Extract the Final Byte (if there are no Intermediate
655 * Bytes) and the value of the first parameter (if it is an integer).
657 * This function assumes the control sequence begins with a CSI -
658 * CONTROL SEQUENCE INTRODUCER encoded as ESC [. (ECMA-48 also allows
659 * 0x9B as a single-byte CSI, but we don't support that here.)
661 * @returns one of:
662 * - -1 if the control sequence is not yet complete; the caller sets a timer.
663 * - 0 if the control sequence does not comply with ECMA-48.
664 * - The length of the control sequence otherwise. */
665 static inline int
666 get_esc_code(unsigned char *str, int len, unsigned char *final_byte,
667 int *first_param_value)
669 const int parameter_pos = 2;
670 int intermediate_pos;
671 int final_pos;
672 int pos;
674 *final_byte = '\0';
675 *first_param_value = 0;
677 /* Parameter Bytes */
678 pos = parameter_pos;
679 while (pos < len && str[pos] >= 0x30 && str[pos] <= 0x3F)
680 ++pos;
682 /* Intermediate Bytes */
683 intermediate_pos = pos;
684 while (pos < len && str[pos] >= 0x20 && str[pos] <= 0x2F)
685 ++pos;
687 /* Final Byte */
688 final_pos = pos;
689 if (pos >= len)
690 return -1;
691 if (!(str[pos] >= 0x40 && str[pos] <= 0x7E))
692 return 0;
694 /* The control sequence seems OK. If the first Parameter
695 * Byte indicates that the parameter string is formatted
696 * as specified in clause 5.4.2 of ECMA-48, and the first
697 * parameter is an integer, then compute its value.
698 * (We need not check @len here because the loop cannot get
699 * past the Final Byte.) */
700 for (pos = parameter_pos; str[pos] >= 0x30 && str[pos] <= 0x39; ++pos)
701 *first_param_value = *first_param_value * 10 + str[pos] - 0x30;
702 /* If the first parameter contains an embedded separator, then
703 * the value is not an integer, so discard what we computed. */
704 if (str[pos] == 0x3A)
705 *first_param_value = 0;
707 /* The meaning of the Final Byte depends on the Intermediate
708 * Bytes. Because we don't currently need to recognize any
709 * control sequences that use Intermediate Bytes, we just
710 * discard the Final Byte if there are any Intermediate
711 * Bytes. */
712 if (intermediate_pos == final_pos)
713 *final_byte = str[final_pos];
715 return final_pos + 1;
718 /* Define it to dump queue content in a readable form,
719 * it may help to determine terminal sequences, and see what goes on. --Zas */
720 /* #define DEBUG_ITRM_QUEUE */
722 #ifdef DEBUG_ITRM_QUEUE
723 #include <stdio.h>
724 #include <ctype.h> /* isprint() isspace() */
725 #endif
727 /** Decode a control sequence that begins with CSI (CONTROL SEQUENCE
728 * INTRODUCER) encoded as ESC [, and set @a *ev accordingly.
729 * (ECMA-48 also allows 0x9B as a single-byte CSI, but we don't
730 * support that here.)
732 * @returns one of:
733 * - -1 if the control sequence is not yet complete; the caller sets a timer.
734 * - 0 if the control sequence should be parsed by some other function.
735 * - The length of the control sequence otherwise.
736 * Returning >0 does not imply this function has altered @a *ev. */
737 static int
738 decode_terminal_escape_sequence(struct itrm *itrm, struct interlink_event *ev)
740 struct term_event_keyboard kbd = { KBD_UNDEF, KBD_MOD_NONE };
741 unsigned char c;
742 int v;
743 int el;
745 if (itrm->in.queue.len < 3) return -1;
747 if (itrm->in.queue.data[2] == '[') {
748 /* The terminfo entry for linux has "kf1=\E[[A", etc.
749 * These are not control sequences compliant with
750 * clause 5.4 of ECMA-48. (According to ECMA-48,
751 * "\E[[" is SRS - START REVERSED STRING.) */
752 if (itrm->in.queue.len >= 4
753 && itrm->in.queue.data[3] >= 'A'
754 && itrm->in.queue.data[3] <= 'L') {
755 kbd.key = number_to_kbd_fkey(itrm->in.queue.data[3] - 'A' + 1);
756 set_kbd_interlink_event(ev, kbd.key, kbd.modifier);
757 return 4;
760 return -1;
763 el = get_esc_code(itrm->in.queue.data, itrm->in.queue.len, &c, &v);
764 if (el == -1) {
765 /* If the control sequence is incomplete but itrm->in.queue
766 * is already full, then we must not wait for more input:
767 * kbd_timeout might call in_kbd and thus process_input
768 * and come right back here. Better just reject the whole
769 * thing and let the initial CSI be handled as Alt-[. */
770 if (itrm->in.queue.len == ITRM_IN_QUEUE_SIZE)
771 return 0;
772 else
773 return -1;
775 #ifdef DEBUG_ITRM_QUEUE
776 fprintf(stderr, "esc code: %c v=%d c=%c el=%d\n", itrm->in.queue.data[1], v, c, el);
777 fflush(stderr);
778 #endif
780 /* The following information should be listed for each escape
781 * sequence recognized here:
783 * 1. Which control function ECMA-48 assigns to the sequence.
784 * Put parentheses around this if the control function
785 * seems unrelated to how ELinks actually treats the
786 * sequence. Write "private" if it is a control sequence
787 * reserved for private or experimental use in ECMA-48.
788 * (Those have a Final Byte in the range 0x70 to 0x7F,
789 * optionally preceded by a single Intermediate Byte 0x20.)
791 * 2. The capname used by Terminfo, if any. These should help
792 * when ELinks is eventually changed to read escape
793 * sequences from Terminfo (bug 96).
795 * 3. The $TERM identifier of some terminal that generates
796 * this escape sequence with the meaning expected by
797 * ELinks. Escape sequences with no known terminal may end
798 * up being removed from ELinks when bug 96 is fixed.
799 */ /* ECMA-48 Terminfo $TERM */
800 switch (c) { /* ------- -------- ----- */
801 case 'A': kbd.key = KBD_UP; break; /* CUU kcuu1 vt200 */
802 case 'B': kbd.key = KBD_DOWN; break; /* CUD kcud1 vt200 */
803 case 'C': kbd.key = KBD_RIGHT; break; /* CUF kcuf1 vt200 */
804 case 'D': kbd.key = KBD_LEFT; break; /* CUB kcub1 vt200 */
805 case 'F': /* (CPL) kend cons25 */
806 case 'e': kbd.key = KBD_END; break; /* (VPR) kend */
807 case 'H': kbd.key = KBD_HOME; break; /* CUP khome cons25 */
808 case 'I': kbd.key = KBD_PAGE_UP; break; /* (CHT) kpp cons25 */
809 case 'G': kbd.key = KBD_PAGE_DOWN; break; /* (CHA) knp cons25 */
810 case 'L': kbd.key = KBD_INS; break; /* (IL) kich1 cons25 */
811 /* Free BSD (TERM=cons25 etc.) */
812 /* case 'M': kbd.key = KBD_F1; break;*/ /* (DL) kf1 cons25 */
813 case 'N': kbd.key = KBD_F2; break; /* (EF) kf2 cons25 */
814 case 'O': kbd.key = KBD_F3; break; /* (EA) kf3 cons25 */
815 case 'P': kbd.key = KBD_F4; break; /* (DCH) kf4 cons25 */
816 case 'Q': kbd.key = KBD_F5; break; /* (SEE) kf5 cons25 */
817 /* case 'R': kbd.key = KBD_F6; break;*/ /* (CPR) kf6 cons25 */
818 case 'S': kbd.key = KBD_F7; break; /* (SU) kf7 cons25 */
819 case 'T': kbd.key = KBD_F8; break; /* (SD) kf8 cons25 */
820 case 'U': kbd.key = KBD_F9; break; /* (NP) kf9 cons25 */
821 case 'V': kbd.key = KBD_F10; break; /* (PP) kf10 cons25 */
822 case 'W': kbd.key = KBD_F11; break; /* (CTC) kf11 cons25 */
823 case 'X': kbd.key = KBD_F12; break; /* (ECH) kf12 cons25 */
825 case 'Z': /* CBT kcbt cons25 */
826 kbd.key = KBD_TAB; kbd.modifier = KBD_MOD_SHIFT; break;
828 case 'z': switch (v) { /* private */
829 case 247: kbd.key = KBD_INS; break; /* kich1 */
830 case 214: kbd.key = KBD_HOME; break; /* khome sun */
831 case 220: kbd.key = KBD_END; break; /* kend sun */
832 case 216: kbd.key = KBD_PAGE_UP; break; /* kpp sun */
833 case 222: kbd.key = KBD_PAGE_DOWN; break; /* knp sun */
834 case 249: kbd.key = KBD_DEL; break; /* kdch1 */
835 } break;
837 case '~': switch (v) { /* private */
838 case 1: kbd.key = KBD_HOME; break; /* khome linux */
839 case 2: kbd.key = KBD_INS; break; /* kich1 linux */
840 case 3: kbd.key = KBD_DEL; break; /* kdch1 linux */
841 case 4: kbd.key = KBD_END; break; /* kend linux */
842 case 5: kbd.key = KBD_PAGE_UP; break; /* kpp linux */
843 case 6: kbd.key = KBD_PAGE_DOWN; break; /* knp linux */
844 case 7: kbd.key = KBD_HOME; break; /* khome rxvt */
845 case 8: kbd.key = KBD_END; break; /* kend rxvt */
847 case 11: kbd.key = KBD_F1; break; /* kf1 rxvt */
848 case 12: kbd.key = KBD_F2; break; /* kf2 rxvt */
849 case 13: kbd.key = KBD_F3; break; /* kf3 rxvt */
850 case 14: kbd.key = KBD_F4; break; /* kf4 rxvt */
851 case 15: kbd.key = KBD_F5; break; /* kf5 rxvt */
853 case 17: kbd.key = KBD_F6; break; /* kf6 vt200 */
854 case 18: kbd.key = KBD_F7; break; /* kf7 vt200 */
855 case 19: kbd.key = KBD_F8; break; /* kf8 vt200 */
856 case 20: kbd.key = KBD_F9; break; /* kf9 vt200 */
857 case 21: kbd.key = KBD_F10; break; /* kf10 vt200 */
859 case 23: kbd.key = KBD_F11; break; /* kf11 vt200 */
860 case 24: kbd.key = KBD_F12; break; /* kf12 vt200 */
862 /* Give preference to F11 and F12 over shifted F1 and F2. */
864 case 23: kbd.key = KBD_F1; kbd.modifier = KBD_MOD_SHIFT; break;
865 case 24: kbd.key = KBD_F2; kbd.modifier = KBD_MOD_SHIFT; break;
868 case 25: kbd.key = KBD_F3; kbd.modifier = KBD_MOD_SHIFT; break;
869 case 26: kbd.key = KBD_F4; kbd.modifier = KBD_MOD_SHIFT; break;
871 case 28: kbd.key = KBD_F5; kbd.modifier = KBD_MOD_SHIFT; break;
872 case 29: kbd.key = KBD_F6; kbd.modifier = KBD_MOD_SHIFT; break;
874 case 31: kbd.key = KBD_F7; kbd.modifier = KBD_MOD_SHIFT; break;
875 case 32: kbd.key = KBD_F8; kbd.modifier = KBD_MOD_SHIFT; break;
876 case 33: kbd.key = KBD_F9; kbd.modifier = KBD_MOD_SHIFT; break;
877 case 34: kbd.key = KBD_F10; kbd.modifier = KBD_MOD_SHIFT; break;
879 } break;
881 case 'R': resize_terminal(); break; /* CPR u6 */
882 case 'M': /* (DL) kmous xterm */
883 #ifdef CONFIG_MOUSE
884 el = decode_terminal_mouse_escape_sequence(itrm, ev, el, v);
885 #endif /* CONFIG_MOUSE */
886 break;
889 /* KBD_UNDEF here means it was unrecognized or a mouse event. */
890 if (kbd.key != KBD_UNDEF)
891 set_kbd_interlink_event(ev, kbd.key, kbd.modifier);
893 return el;
896 /** Decode an escape sequence that begins with SS3 (SINGLE SHIFT 3).
897 * These are used for application cursor keys and the application keypad.
898 * @returns one of:
899 * - -1 if the escape sequence is not yet complete; the caller sets a timer.
900 * - 0 if the escape sequence should be parsed by some other function.
901 * - The length of the escape sequence otherwise.
902 * Returning >0 does not imply this function has altered @a *ev. */
903 static int
904 decode_terminal_application_key(struct itrm *itrm, struct interlink_event *ev)
906 unsigned char c;
907 struct interlink_event_keyboard kbd = { KBD_UNDEF, KBD_MOD_NONE };
909 assert(itrm->in.queue.len >= 2);
910 assert(itrm->in.queue.data[0] == ASCII_ESC);
911 assert(itrm->in.queue.data[1] == 0x4F); /* == 'O', incidentally */
912 if_assert_failed return 0;
914 if (itrm->in.queue.len < 3) return -1;
915 /* According to ECMA-35 section 8.4, a single (possibly multibyte)
916 * character follows the SS3. We now assume the code identifies
917 * GL as the single-shift area and the designated set has 94
918 * characters. */
919 c = itrm->in.queue.data[2];
920 if (c < 0x21 || c > 0x7E) return 0;
922 switch (c) { /* Terminfo $TERM */
923 case ' ': kbd.key = ' '; break; /* xterm */
924 case 'A': kbd.key = KBD_UP; break; /* kcuu1 vt100 */
925 case 'B': kbd.key = KBD_DOWN; break; /* kcud1 vt100 */
926 case 'C': kbd.key = KBD_RIGHT; break; /* kcuf1 vt100 */
927 case 'D': kbd.key = KBD_LEFT; break; /* kcub1 vt100 */
928 case 'F': kbd.key = KBD_END; break; /* kend xterm */
929 case 'H': kbd.key = KBD_HOME; break; /* khome xterm */
930 case 'I': kbd.key = KBD_TAB; break; /* xterm */
931 case 'M': kbd.key = KBD_ENTER; break; /* kent vt100 */
932 /* FIXME: xterm generates ESC O 2 P for Shift-PF1 */
933 case 'P': kbd.key = KBD_F1; break; /* kf1 vt100 */
934 case 'Q': kbd.key = KBD_F2; break; /* kf2 vt100 */
935 case 'R': kbd.key = KBD_F3; break; /* kf3 vt100 */
936 case 'S': kbd.key = KBD_F4; break; /* kf4 vt100 */
937 case 'X': kbd.key = '='; break; /* xterm */
939 case 'j': case 'k': case 'l': case 'm': /* *+,- xterm */
940 case 'n': case 'o': case 'p': case 'q': /* ./01 xterm */
941 case 'r': case 's': case 't': case 'u': /* 2345 xterm */
942 case 'v': case 'w': case 'x': case 'y': /* 6789 xterm */
943 kbd.key = c - 'p' + '0'; break;
945 if (kbd.key != KBD_UNDEF)
946 copy_struct(&ev->info.keyboard, &kbd);
948 return 3; /* even if we didn't recognize it */
952 /** Initialize @a *ev to match the byte @a key received from the terminal.
953 * @a key must not be a value from enum term_event_special_key. */
954 static void
955 set_kbd_event(const struct itrm *itrm, struct interlink_event *ev,
956 int key, term_event_modifier_T modifier)
958 if (key == itrm->verase)
959 key = KBD_BS;
960 else switch (key) {
961 case ASCII_TAB:
962 key = KBD_TAB;
963 break;
964 case ASCII_DEL: /* often overridden by itrm->verase above */
965 key = KBD_DEL;
966 break;
967 case ASCII_LF:
968 case ASCII_CR:
969 key = KBD_ENTER;
970 break;
972 case ASCII_ESC:
973 key = KBD_ESC;
974 break;
976 case ASCII_BS: /* often overridden by itrm->verase above */
977 default:
978 if (key < ' ') {
979 key += 'A' - 1;
980 modifier |= KBD_MOD_CTRL;
984 set_kbd_interlink_event(ev, key, modifier);
987 /** Timer callback for itrm.timer. As explained in install_timer(),
988 * this function must erase the expired timer ID from all variables. */
989 static void
990 kbd_timeout(struct itrm *itrm)
992 struct interlink_event ev;
993 int el;
995 itrm->timer = TIMER_ID_UNDEF;
996 /* The expired timer ID has now been erased. */
998 assertm(itrm->in.queue.len, "timeout on empty queue");
999 assert(!itrm->blocked); /* block_itrm should have killed itrm->timer */
1000 if_assert_failed return;
1002 if (can_read(itrm->in.std)) {
1003 in_kbd(itrm);
1004 return;
1007 if (itrm->in.queue.len >= 2 && itrm->in.queue.data[0] == ASCII_ESC) {
1008 /* This is used for ESC [ and ESC O. */
1009 set_kbd_event(itrm, &ev, itrm->in.queue.data[1], KBD_MOD_ALT);
1010 el = 2;
1011 } else {
1012 set_kbd_event(itrm, &ev, itrm->in.queue.data[0], KBD_MOD_NONE);
1013 el = 1;
1015 itrm_queue_event(itrm, (char *) &ev, sizeof(ev));
1017 itrm->in.queue.len -= el;
1018 if (itrm->in.queue.len)
1019 memmove(itrm->in.queue.data, itrm->in.queue.data + el, itrm->in.queue.len);
1021 while (process_queue(itrm));
1024 /** Parse one event from itrm_in.queue and append to itrm_out.queue.
1025 * @pre On entry, @a *itrm must not be blocked.
1026 * @returns the number of bytes removed from itrm->in.queue; at least 0.
1027 * @post If this function leaves the queue not full, it also reenables
1028 * reading from itrm->in.std. (Because it does not add to the queue,
1029 * it never need disable reading.) */
1030 static int
1031 process_queue(struct itrm *itrm)
1033 struct interlink_event ev;
1034 int el = 0;
1036 if (!itrm->in.queue.len) goto return_without_event;
1037 assert(!itrm->blocked);
1038 if_assert_failed return 0; /* unlike goto, don't enable reading */
1040 set_kbd_interlink_event(&ev, KBD_UNDEF, KBD_MOD_NONE);
1042 #ifdef DEBUG_ITRM_QUEUE
1044 int i;
1046 /* Dump current queue in a readable form to stderr. */
1047 for (i = 0; i < itrm->in.queue.len; i++)
1048 if (itrm->in.queue.data[i] == ASCII_ESC)
1049 fprintf(stderr, "ESC ");
1050 else if (isprint(itrm->in.queue.data[i]) && !isspace(itrm->in.queue.data[i]))
1051 fprintf(stderr, "%c ", itrm->in.queue.data[i]);
1052 else
1053 fprintf(stderr, "0x%02x ", itrm->in.queue.data[i]);
1055 fprintf(stderr, "\n");
1056 fflush(stderr);
1058 #endif /* DEBUG_ITRM_QUEUE */
1060 /* el == -1 means itrm->in.queue appears to be the beginning of an
1061 * escape sequence but it is not yet complete. Set a timer;
1062 * if it times out, then assume it wasn't an escape sequence
1063 * after all.
1064 * el == 0 means this function has not yet figured out what the data
1065 * in itrm->in.queue is, but some possibilities remain.
1066 * One of them will be chosen before returning.
1067 * el > 0 means some bytes were successfully parsed from the beginning
1068 * of itrm->in.queue and should now be removed from there.
1069 * However, this does not always imply an event will be queued.
1072 /* ELinks should also recognize U+009B CONTROL SEQUENCE INTRODUCER
1073 * as meaning the same as ESC 0x5B, and U+008F SINGLE SHIFT THREE as
1074 * meaning the same as ESC 0x4F, but those cannot yet be implemented
1075 * because of bug 777: the UTF-8 decoder is run too late. */
1076 if (itrm->in.queue.data[0] == ASCII_ESC) {
1077 if (itrm->in.queue.len < 2) {
1078 el = -1;
1079 } else if (itrm->in.queue.data[1] == 0x5B /* CSI */) {
1080 el = decode_terminal_escape_sequence(itrm, &ev);
1081 } else if (itrm->in.queue.data[1] == 0x4F /* SS3 */) {
1082 el = decode_terminal_application_key(itrm, &ev);
1083 } else if (itrm->in.queue.data[1] == ASCII_ESC) {
1084 /* ESC ESC can be either Alt-Esc or the
1085 * beginning of e.g. ESC ESC 0x5B 0x41,
1086 * which we should parse as Esc Up. */
1087 if (itrm->in.queue.len < 3) {
1088 /* Need more data to figure it out. */
1089 el = -1;
1090 } else if (itrm->in.queue.data[2] == 0x5B
1091 || itrm->in.queue.data[2] == 0x4F) {
1092 /* The first ESC appears to be followed
1093 * by an escape sequence. Treat it as
1094 * a standalone Esc. */
1095 el = 1;
1096 set_kbd_event(itrm, &ev,
1097 itrm->in.queue.data[0],
1098 KBD_MOD_NONE);
1099 } else {
1100 /* The second ESC of ESC ESC is not the
1101 * beginning of any known escape sequence.
1102 * This must be Alt-Esc, then. */
1103 el = 2;
1104 set_kbd_event(itrm, &ev,
1105 itrm->in.queue.data[1],
1106 KBD_MOD_ALT);
1109 if (el == 0) { /* Begins with ESC, but none of the above */
1110 el = 2;
1111 set_kbd_event(itrm, &ev, itrm->in.queue.data[1],
1112 KBD_MOD_ALT);
1115 } else if (itrm->in.queue.data[0] == 0) {
1116 static const struct term_event_keyboard os2xtd[256] = {
1117 #include "terminal/key.inc"
1120 if (itrm->in.queue.len < 2)
1121 el = -1;
1122 else {
1123 el = 2;
1124 set_kbd_interlink_event(&ev,
1125 os2xtd[itrm->in.queue.data[1]].key,
1126 os2xtd[itrm->in.queue.data[1]].modifier);
1130 if (el == 0) {
1131 el = 1;
1132 set_kbd_event(itrm, &ev, itrm->in.queue.data[0], KBD_MOD_NONE);
1135 /* The call to decode_terminal_escape_sequence() might have changed the
1136 * keyboard event to a mouse event. */
1137 if (ev.ev == EVENT_MOUSE || ev.info.keyboard.key != KBD_UNDEF)
1138 itrm_queue_event(itrm, (char *) &ev, sizeof(ev));
1140 return_without_event:
1141 if (el == -1) {
1142 install_timer(&itrm->timer, ESC_TIMEOUT, (void (*)(void *)) kbd_timeout,
1143 itrm);
1144 return 0;
1145 } else {
1146 assertm(itrm->in.queue.len >= el, "event queue underflow");
1147 if_assert_failed { itrm->in.queue.len = el; }
1149 itrm->in.queue.len -= el;
1150 if (itrm->in.queue.len)
1151 memmove(itrm->in.queue.data, itrm->in.queue.data + el, itrm->in.queue.len);
1153 if (itrm->in.queue.len < ITRM_IN_QUEUE_SIZE)
1154 handle_itrm_stdin(itrm);
1156 return el;
1161 /** A select_handler_T read_func for itrm_in.std. This is called when
1162 * characters typed by the user arrive from the terminal. */
1163 static void
1164 in_kbd(struct itrm *itrm)
1166 int r;
1168 if (!can_read(itrm->in.std)) return;
1170 kill_timer(&itrm->timer);
1172 if (itrm->in.queue.len >= ITRM_IN_QUEUE_SIZE) {
1173 unhandle_itrm_stdin(itrm);
1174 while (process_queue(itrm));
1175 return;
1178 r = safe_read(itrm->in.std, itrm->in.queue.data + itrm->in.queue.len,
1179 ITRM_IN_QUEUE_SIZE - itrm->in.queue.len);
1180 if (r <= 0) {
1181 free_itrm(itrm);
1182 return;
1185 itrm->in.queue.len += r;
1186 if (itrm->in.queue.len > ITRM_IN_QUEUE_SIZE) {
1187 ERROR(gettext("Too many bytes read from the itrm!"));
1188 itrm->in.queue.len = ITRM_IN_QUEUE_SIZE;
1191 while (process_queue(itrm));
1194 /** Enable reading from itrm_in.std. ELinks will read any available
1195 * bytes from the tty into itrm->in.queue and then parse them.
1196 * Reading should be enabled whenever itrm->in.queue is not full and
1197 * itrm->blocked is 0. */
1198 static void
1199 handle_itrm_stdin(struct itrm *itrm)
1201 assert(itrm->in.std >= 0);
1202 if_assert_failed return;
1204 set_handlers(itrm->in.std, (select_handler_T) in_kbd, NULL,
1205 (select_handler_T) free_itrm, itrm);
1208 /** Disable reading from itrm_in.std. Reading should be disabled
1209 * whenever itrm->in.queue is full (there is no room for the data)
1210 * or itrm->blocked is 1 (other processes may read the data). */
1211 static void
1212 unhandle_itrm_stdin(struct itrm *itrm)
1214 assert(itrm->in.std >= 0);
1215 if_assert_failed return;
1217 set_handlers(itrm->in.std, (select_handler_T) NULL, NULL,
1218 (select_handler_T) free_itrm, itrm);