Bug 1082: mem_free_set in abort_preloading
[elinks.git] / src / terminal / kbd.c
blobcd50a078030c63dda5eff0ceb0f5541c953f408d
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 /* This is called because of a signal, and there may be input
152 * pending from the terminal, so do not reset
153 * ditrm->bracketed_pasting. */
154 set_kbd_interlink_event(&ev, KBD_CTRL_C, KBD_MOD_NONE);
155 itrm_queue_event(ditrm, (unsigned char *) &ev, sizeof(ev));
158 #define write_sequence(fd, seq) \
159 hard_write(fd, seq, sizeof(seq) - 1)
162 #define INIT_TERMINAL_SEQ "\033)0\0337" /**< Special Character and Line Drawing Set, Save Cursor */
163 #define INIT_ALT_SCREEN_SEQ "\033[?47h" /**< Use Alternate Screen Buffer */
164 #define INIT_BRACKETED_PASTE_SEQ "\033[?2004h" /**< Enable XTerm bracketed paste mode */
166 static void
167 send_init_sequence(int h, int altscreen)
169 write_sequence(h, INIT_TERMINAL_SEQ);
171 /* If alternate screen is supported switch to it. */
172 if (altscreen) {
173 write_sequence(h, INIT_ALT_SCREEN_SEQ);
175 #ifdef CONFIG_MOUSE
176 send_mouse_init_sequence(h);
177 #endif
178 write_sequence(h, INIT_BRACKETED_PASTE_SEQ);
181 #define DONE_CLS_SEQ "\033[2J" /**< Erase in Display, Clear All */
182 #define DONE_TERMINAL_SEQ "\0338\r \b" /**< Restore Cursor (DECRC) + ??? */
183 #define DONE_ALT_SCREEN_SEQ "\033[?47l" /**< Use Normal Screen Buffer */
184 #define DONE_BRACKETED_PASTE_SEQ "\033[?2004l" /**< Disable XTerm bracketed paste mode */
186 static void
187 send_done_sequence(int h, int altscreen)
189 write_sequence(h, DONE_BRACKETED_PASTE_SEQ);
190 write_sequence(h, DONE_CLS_SEQ);
192 #ifdef CONFIG_MOUSE
193 send_mouse_done_sequence(h);
194 #endif
196 /* Switch from alternate screen. */
197 if (altscreen) {
198 write_sequence(h, DONE_ALT_SCREEN_SEQ);
201 write_sequence(h, DONE_TERMINAL_SEQ);
205 #undef write_sequence
207 void
208 resize_terminal(void)
210 struct interlink_event ev;
211 int width, height;
213 get_terminal_size(ditrm->out.std, &width, &height);
214 set_resize_interlink_event(&ev, width, height);
215 itrm_queue_event(ditrm, (char *) &ev, sizeof(ev));
218 void
219 get_terminal_name(unsigned char name[MAX_TERM_LEN])
221 unsigned char *term = getenv("TERM");
222 int i;
224 memset(name, 0, MAX_TERM_LEN);
226 if (!term) return;
228 for (i = 0; term[i] != 0 && i < MAX_TERM_LEN - 1; i++)
229 name[i] = isident(term[i]) ? term[i] : '-';
233 static int
234 setraw(struct itrm *itrm, int save_orig)
236 struct termios t;
237 long vdisable;
239 memset(&t, 0, sizeof(t));
240 if (tcgetattr(itrm->in.ctl, &t)) return -1;
242 if (save_orig) copy_struct(&itrm->t, &t);
244 #ifdef _POSIX_VDISABLE
245 vdisable = _POSIX_VDISABLE;
246 #else
247 vdisable = fpathconf(itrm->in.ctl, _PC_VDISABLE);
248 #endif
249 if (vdisable != -1 && t.c_cc[VERASE] == vdisable)
250 itrm->verase = -1;
251 else
252 itrm->verase = (unsigned char) t.c_cc[VERASE];
254 elinks_cfmakeraw(&t);
255 t.c_lflag |= ISIG;
256 #ifdef TOSTOP
257 t.c_lflag |= TOSTOP;
258 #endif
259 t.c_oflag |= OPOST;
260 if (tcsetattr(itrm->in.ctl, TCSANOW, &t)) return -1;
262 return 0;
265 /** Construct the struct itrm of this process, make ::ditrm point to it,
266 * set up select() handlers, and send the initial interlink packet.
268 * The first five parameters are file descriptors that this function
269 * saves in submembers of struct itrm, and for which this function may
270 * set select() handlers. Please see the definitions of struct
271 * itrm_in and struct itrm_out for further explanations.
273 * @param std_in itrm_in.std: read tty device (or pipe)
274 * @param std_out itrm_out.std: write tty device (or pipe)
275 * @param sock_in itrm_in.sock
276 * - If master: == @a std_out (masterhood flag)
277 * - If slave: read socket from master
278 * @param sock_out itrm_out.sock
279 * - If master: write pipe to same process
280 * - If slave: write socket to master
281 * @param ctl_in itrm_in.ctl: control tty device
283 * The remaining three parameters control the initial interlink packet.
285 * @param init_string A string to be passed to the master process. Need
286 * not be null-terminated. If @a remote == 0, this is
287 * a URI. Otherwise, this is a remote command.
288 * @param init_len The length of init_string, in bytes.
289 * @param remote = 0 if asking the master to start a new session
290 * and display it via this process. Otherwise,
291 * enum ::remote_session_flags. */
292 void
293 handle_trm(int std_in, int std_out, int sock_in, int sock_out, int ctl_in,
294 void *init_string, int init_len, int remote)
296 struct itrm *itrm;
297 struct terminal_info info;
298 struct interlink_event_size *size = &info.event.info.size;
299 unsigned char *ts;
301 memset(&info, 0, sizeof(info));
303 get_terminal_size(ctl_in, &size->width, &size->height);
304 info.event.ev = EVENT_INIT;
305 info.system_env = get_system_env();
306 info.length = init_len;
308 if (remote) {
309 info.session_info = remote;
310 info.magic = INTERLINK_REMOTE_MAGIC;
311 } else {
312 info.session_info = get_cmd_opt_int("base-session");
313 info.magic = INTERLINK_NORMAL_MAGIC;
316 itrm = mem_calloc(1, sizeof(*itrm));
317 if (!itrm) return;
319 itrm->in.queue.data = mem_calloc(1, ITRM_IN_QUEUE_SIZE);
320 if (!itrm->in.queue.data) {
321 mem_free(itrm);
322 return;
325 ditrm = itrm;
326 itrm->in.std = std_in;
327 itrm->out.std = std_out;
328 itrm->in.sock = sock_in;
329 itrm->out.sock = sock_out;
330 itrm->in.ctl = ctl_in;
331 itrm->timer = TIMER_ID_UNDEF;
332 itrm->remote = !!remote;
334 /* If the master does not tell which charset it's using in
335 * this terminal, assume it's some ISO 8859. Because that's
336 * what older versions of ELinks did. */
337 itrm->title_codepage = get_cp_index("ISO-8859-1");
339 /* FIXME: Combination altscreen + xwin does not work as it should,
340 * mouse clicks are reportedly partially ignored. */
341 if (info.system_env & (ENV_SCREEN | ENV_XWIN))
342 itrm->altscreen = 1;
344 if (!remote) {
345 if (ctl_in >= 0) setraw(itrm, 1);
346 send_init_sequence(std_out, itrm->altscreen);
347 handle_terminal_resize(ctl_in, resize_terminal);
348 #ifdef CONFIG_MOUSE
349 enable_mouse();
350 #endif
351 handle_itrm_stdin(itrm);
352 } else {
353 /* elinks -remote may not have a valid stdin if not run from a tty (bug 938) */
354 if (std_in >= 0) handle_itrm_stdin(itrm);
357 if (sock_in != std_out)
358 set_handlers(sock_in, (select_handler_T) in_sock,
359 NULL, (select_handler_T) free_itrm, itrm);
361 get_terminal_name(info.name);
363 ts = get_cwd();
364 if (ts) {
365 memcpy(info.cwd, ts, int_min(strlen(ts), MAX_CWD_LEN));
366 mem_free(ts);
369 itrm_queue_event(itrm, (char *) &info, TERMINAL_INFO_SIZE);
370 itrm_queue_event(itrm, (char *) init_string, init_len);
374 /** A select_handler_T read_func and error_func for the pipe (long) @a h.
375 * This is called when the subprocess started on the terminal of this
376 * ELinks process exits. ELinks then resumes using the terminal. */
377 static void
378 unblock_itrm_x(void *h)
380 close_handle(h);
381 if (!ditrm) return;
382 unblock_itrm();
384 /* Note: External editor support depends on this resize event. */
385 resize_terminal();
390 unblock_itrm(void)
392 if (!ditrm) return -1;
394 if (ditrm->in.ctl >= 0 && setraw(ditrm, 0)) return -1;
395 ditrm->blocked = 0;
396 send_init_sequence(ditrm->out.std, ditrm->altscreen);
398 handle_itrm_stdin(ditrm);
399 resume_mouse(ditrm->mouse_h);
401 handle_terminal_resize(ditrm->in.ctl, resize_terminal);
402 unblock_stdin();
404 return 0;
408 void
409 block_itrm(void)
411 if (!ditrm) return;
413 ditrm->blocked = 1;
414 block_stdin();
415 kill_timer(&ditrm->timer);
416 ditrm->in.queue.len = 0;
417 unhandle_terminal_resize(ditrm->in.ctl);
418 send_done_sequence(ditrm->out.std, ditrm->altscreen);
419 tcsetattr(ditrm->in.ctl, TCSANOW, &ditrm->t);
420 unhandle_itrm_stdin(ditrm);
421 suspend_mouse(ditrm->mouse_h);
425 static void
426 free_itrm(struct itrm *itrm)
428 if (!itrm) return;
430 if (!itrm->remote) {
431 if (itrm->orig_title && *itrm->orig_title) {
432 set_window_title(itrm->orig_title, itrm->title_codepage);
434 } else if (itrm->touched_title) {
435 /* Set the window title to the value of $TERM if X11
436 * wasn't compiled in. Should hopefully make at least
437 * half the users happy. (debian bug #312955) */
438 unsigned char title[MAX_TERM_LEN];
440 get_terminal_name(title);
441 if (*title)
442 set_window_title(title,
443 get_cp_index("US-ASCII"));
447 unhandle_terminal_resize(itrm->in.ctl);
448 #ifdef CONFIG_MOUSE
449 disable_mouse();
450 #endif
451 send_done_sequence(itrm->out.std, itrm->altscreen);
452 tcsetattr(itrm->in.ctl, TCSANOW, &itrm->t);
455 mem_free_set(&itrm->orig_title, NULL);
457 /* elinks -remote may not have a valid stdin if not run from a tty (bug 938) */
458 if (!itrm->remote || itrm->in.std >= 0) clear_handlers(itrm->in.std);
459 clear_handlers(itrm->in.sock);
460 clear_handlers(itrm->out.std);
461 clear_handlers(itrm->out.sock);
463 kill_timer(&itrm->timer);
465 if (itrm == ditrm) ditrm = NULL;
466 mem_free_if(itrm->out.queue.data);
467 mem_free_if(itrm->in.queue.data);
468 mem_free(itrm);
471 /** Resize terminal to dimensions specified by @a text string.
472 * @a text should look like "width,height,old-width,old-height"
473 * where width and height are integers. */
474 static inline void
475 resize_terminal_from_str(unsigned char *text)
477 enum { NEW_WIDTH = 0, NEW_HEIGHT, OLD_WIDTH, OLD_HEIGHT, NUMBERS } i;
478 int numbers[NUMBERS];
480 assert(text && *text);
481 if_assert_failed return;
483 for (i = 0; i < NUMBERS; i++) {
484 unsigned char *p = strchr(text, ',');
486 if (p) {
487 *p++ = '\0';
489 } else if (i < OLD_HEIGHT) {
490 return;
493 numbers[i] = atoi(text);
495 if (p) text = p;
498 resize_window(numbers[NEW_WIDTH], numbers[NEW_HEIGHT],
499 numbers[OLD_WIDTH], numbers[OLD_HEIGHT]);
500 resize_terminal();
503 void
504 dispatch_special(unsigned char *text)
506 switch (text[0]) {
507 case TERM_FN_TITLE:
508 if (ditrm) {
509 if (ditrm->remote)
510 break;
512 if (!ditrm->orig_title)
513 ditrm->orig_title = get_window_title();
514 ditrm->touched_title = 1;
516 /* TODO: Is it really possible to get here with
517 * ditrm == NULL, and which charset would then
518 * be most appropriate? */
519 set_window_title(text + 1,
520 ditrm ? ditrm->title_codepage
521 : get_cp_index("US-ASCII"));
522 break;
523 case TERM_FN_RESIZE:
524 if (ditrm && ditrm->remote)
525 break;
527 resize_terminal_from_str(text + 1);
528 break;
529 case TERM_FN_TITLE_CODEPAGE:
530 if (ditrm) {
531 int cp = get_cp_index(text + 1);
533 /* If the master sends the name of an
534 * unrecognized charset, assume only
535 * that it's ASCII compatible. */
536 if (cp == -1)
537 cp = get_cp_index("US-ASCII");
538 ditrm->title_codepage = cp;
540 break;
544 static void inline
545 safe_hard_write(int fd, unsigned char *buf, int len)
547 if (is_blocked()) return;
549 want_draw();
550 hard_write(fd, buf, len);
551 done_draw();
554 /** A select_handler_T read_func for itrm_in.sock. A slave process
555 * calls this when the master sends it data to be displayed. The
556 * master process never calls this. */
557 static void
558 in_sock(struct itrm *itrm)
560 struct string path;
561 struct string delete;
562 char ch;
563 int fg; /* enum term_exec */
564 ssize_t bytes_read, i, p;
565 unsigned char buf[ITRM_OUT_QUEUE_SIZE];
567 bytes_read = safe_read(itrm->in.sock, buf, ITRM_OUT_QUEUE_SIZE);
568 if (bytes_read <= 0) goto free_and_return;
570 qwerty:
571 for (i = 0; i < bytes_read; i++)
572 if (!buf[i])
573 goto has_nul_byte;
575 safe_hard_write(itrm->out.std, buf, bytes_read);
576 return;
578 has_nul_byte:
579 if (i) safe_hard_write(itrm->out.std, buf, i);
581 i++;
582 assert(ITRM_OUT_QUEUE_SIZE - i > 0);
583 memmove(buf, buf + i, ITRM_OUT_QUEUE_SIZE - i);
584 bytes_read -= i;
585 p = 0;
587 #define RD(xx) { \
588 unsigned char cc; \
590 if (p < bytes_read) \
591 cc = buf[p++]; \
592 else if ((hard_read(itrm->in.sock, &cc, 1)) <= 0) \
593 goto free_and_return; \
594 xx = cc; \
597 RD(fg);
599 if (!init_string(&path)) goto free_and_return;
601 while (1) {
602 RD(ch);
603 if (!ch) break;
604 add_char_to_string(&path, ch);
607 if (!init_string(&delete)) {
608 done_string(&path);
609 goto free_and_return;
612 while (1) {
613 RD(ch);
614 if (!ch) break;
615 add_char_to_string(&delete, ch);
618 #undef RD
620 if (!*path.source) {
621 dispatch_special(delete.source);
623 } else {
624 int blockh;
625 unsigned char *param;
626 int path_len, del_len, param_len;
628 /* TODO: Should this be changed to allow TERM_EXEC_NEWWIN
629 * in a blocked terminal? There is similar code in
630 * exec_on_terminal(). --KON, 2007 */
631 if (is_blocked() && fg != TERM_EXEC_BG) {
632 if (*delete.source) unlink(delete.source);
633 goto nasty_thing;
636 path_len = path.length;
637 del_len = delete.length;
638 param_len = path_len + del_len + 3;
640 param = mem_alloc(param_len);
641 if (!param) goto nasty_thing;
643 param[0] = fg;
644 memcpy(param + 1, path.source, path_len + 1);
645 memcpy(param + 1 + path_len + 1, delete.source, del_len + 1);
647 if (fg == TERM_EXEC_FG) block_itrm();
649 blockh = start_thread((void (*)(void *, int)) exec_thread,
650 param, param_len);
651 mem_free(param);
653 if (blockh == -1) {
654 if (fg == TERM_EXEC_FG)
655 unblock_itrm();
657 goto nasty_thing;
660 if (fg == TERM_EXEC_FG) {
661 set_handlers(blockh, (select_handler_T) unblock_itrm_x,
662 NULL, (select_handler_T) unblock_itrm_x,
663 (void *) (long) blockh);
665 } else {
666 set_handlers(blockh, close_handle, NULL, close_handle,
667 (void *) (long) blockh);
671 nasty_thing:
672 done_string(&path);
673 done_string(&delete);
674 assert(ITRM_OUT_QUEUE_SIZE - p > 0);
675 memmove(buf, buf + p, ITRM_OUT_QUEUE_SIZE - p);
676 bytes_read -= p;
678 goto qwerty;
680 free_and_return:
681 free_itrm(itrm);
685 /** Parse an ECMA-48 control sequence that was received from a
686 * terminal. Extract the Final Byte (if there are no Intermediate
687 * Bytes) and the value of the first parameter (if it is an integer).
689 * This function assumes the control sequence begins with a CSI -
690 * CONTROL SEQUENCE INTRODUCER encoded as ESC [. (ECMA-48 also allows
691 * 0x9B as a single-byte CSI, but we don't support that here.)
693 * @returns one of:
694 * - -1 if the control sequence is not yet complete; the caller sets a timer.
695 * - 0 if the control sequence does not comply with ECMA-48.
696 * - The length of the control sequence otherwise. */
697 static inline int
698 get_esc_code(unsigned char *str, int len, unsigned char *final_byte,
699 int *first_param_value)
701 const int parameter_pos = 2;
702 int intermediate_pos;
703 int final_pos;
704 int pos;
706 *final_byte = '\0';
707 *first_param_value = 0;
709 /* Parameter Bytes */
710 pos = parameter_pos;
711 while (pos < len && str[pos] >= 0x30 && str[pos] <= 0x3F)
712 ++pos;
714 /* Intermediate Bytes */
715 intermediate_pos = pos;
716 while (pos < len && str[pos] >= 0x20 && str[pos] <= 0x2F)
717 ++pos;
719 /* Final Byte */
720 final_pos = pos;
721 if (pos >= len)
722 return -1;
723 if (!(str[pos] >= 0x40 && str[pos] <= 0x7E))
724 return 0;
726 /* The control sequence seems OK. If the first Parameter
727 * Byte indicates that the parameter string is formatted
728 * as specified in clause 5.4.2 of ECMA-48, and the first
729 * parameter is an integer, then compute its value.
730 * (We need not check @len here because the loop cannot get
731 * past the Final Byte.) */
732 for (pos = parameter_pos; str[pos] >= 0x30 && str[pos] <= 0x39; ++pos)
733 *first_param_value = *first_param_value * 10 + str[pos] - 0x30;
734 /* If the first parameter contains an embedded separator, then
735 * the value is not an integer, so discard what we computed. */
736 if (str[pos] == 0x3A)
737 *first_param_value = 0;
739 /* The meaning of the Final Byte depends on the Intermediate
740 * Bytes. Because we don't currently need to recognize any
741 * control sequences that use Intermediate Bytes, we just
742 * discard the Final Byte if there are any Intermediate
743 * Bytes. */
744 if (intermediate_pos == final_pos)
745 *final_byte = str[final_pos];
747 return final_pos + 1;
750 /* Define it to dump queue content in a readable form,
751 * it may help to determine terminal sequences, and see what goes on. --Zas */
752 /* #define DEBUG_ITRM_QUEUE */
754 #ifdef DEBUG_ITRM_QUEUE
755 #include <stdio.h>
756 #include <ctype.h> /* isprint() isspace() */
757 #endif
759 /** Decode a control sequence that begins with CSI (CONTROL SEQUENCE
760 * INTRODUCER) encoded as ESC [, and set @a *ev accordingly.
761 * (ECMA-48 also allows 0x9B as a single-byte CSI, but we don't
762 * support that here.)
764 * @returns one of:
765 * - -1 if the control sequence is not yet complete; the caller sets a timer.
766 * - 0 if the control sequence should be parsed by some other function.
767 * - The length of the control sequence otherwise.
768 * Returning >0 does not imply this function has altered @a *ev. */
769 static int
770 decode_terminal_escape_sequence(struct itrm *itrm, struct interlink_event *ev)
772 struct term_event_keyboard kbd = { KBD_UNDEF, KBD_MOD_NONE };
773 unsigned char c;
774 int v;
775 int el;
777 if (itrm->in.queue.len < 3) return -1;
779 if (itrm->in.queue.data[2] == '[') {
780 /* The terminfo entry for linux has "kf1=\E[[A", etc.
781 * These are not control sequences compliant with
782 * clause 5.4 of ECMA-48. (According to ECMA-48,
783 * "\E[[" is SRS - START REVERSED STRING.) */
784 if (itrm->in.queue.len >= 4
785 && itrm->in.queue.data[3] >= 'A'
786 && itrm->in.queue.data[3] <= 'L') {
787 kbd.key = number_to_kbd_fkey(itrm->in.queue.data[3] - 'A' + 1);
788 set_kbd_interlink_event(ev, kbd.key, kbd.modifier);
789 return 4;
792 return -1;
795 el = get_esc_code(itrm->in.queue.data, itrm->in.queue.len, &c, &v);
796 if (el == -1) {
797 /* If the control sequence is incomplete but itrm->in.queue
798 * is already full, then we must not wait for more input:
799 * kbd_timeout might call in_kbd and thus process_input
800 * and come right back here. Better just reject the whole
801 * thing and let the initial CSI be handled as Alt-[. */
802 if (itrm->in.queue.len == ITRM_IN_QUEUE_SIZE)
803 return 0;
804 else
805 return -1;
807 #ifdef DEBUG_ITRM_QUEUE
808 fprintf(stderr, "esc code: %c v=%d c=%c el=%d\n", itrm->in.queue.data[1], v, c, el);
809 fflush(stderr);
810 #endif
812 /* The following information should be listed for each escape
813 * sequence recognized here:
815 * 1. Which control function ECMA-48 assigns to the sequence.
816 * Put parentheses around this if the control function
817 * seems unrelated to how ELinks actually treats the
818 * sequence. Write "private" if it is a control sequence
819 * reserved for private or experimental use in ECMA-48.
820 * (Those have a Final Byte in the range 0x70 to 0x7F,
821 * optionally preceded by a single Intermediate Byte 0x20.)
823 * 2. The capname used by Terminfo, if any. These should help
824 * when ELinks is eventually changed to read escape
825 * sequences from Terminfo (bug 96).
827 * 3. The $TERM identifier of some terminal that generates
828 * this escape sequence with the meaning expected by
829 * ELinks. Escape sequences with no known terminal may end
830 * up being removed from ELinks when bug 96 is fixed.
831 */ /* ECMA-48 Terminfo $TERM */
832 switch (c) { /* ------- -------- ----- */
833 case 'A': kbd.key = KBD_UP; break; /* CUU kcuu1 vt200 */
834 case 'B': kbd.key = KBD_DOWN; break; /* CUD kcud1 vt200 */
835 case 'C': kbd.key = KBD_RIGHT; break; /* CUF kcuf1 vt200 */
836 case 'D': kbd.key = KBD_LEFT; break; /* CUB kcub1 vt200 */
837 case 'F': /* (CPL) kend cons25 */
838 case 'e': kbd.key = KBD_END; break; /* (VPR) kend */
839 case 'H': kbd.key = KBD_HOME; break; /* CUP khome cons25 */
840 case 'I': kbd.key = KBD_PAGE_UP; break; /* (CHT) kpp cons25 */
841 case 'G': kbd.key = KBD_PAGE_DOWN; break; /* (CHA) knp cons25 */
842 case 'L': kbd.key = KBD_INS; break; /* (IL) kich1 cons25 */
843 /* Free BSD (TERM=cons25 etc.) */
844 /* case 'M': kbd.key = KBD_F1; break;*/ /* (DL) kf1 cons25 */
845 case 'N': kbd.key = KBD_F2; break; /* (EF) kf2 cons25 */
846 case 'O': kbd.key = KBD_F3; break; /* (EA) kf3 cons25 */
847 case 'P': kbd.key = KBD_F4; break; /* (DCH) kf4 cons25 */
848 case 'Q': kbd.key = KBD_F5; break; /* (SEE) kf5 cons25 */
849 /* case 'R': kbd.key = KBD_F6; break;*/ /* (CPR) kf6 cons25 */
850 case 'S': kbd.key = KBD_F7; break; /* (SU) kf7 cons25 */
851 case 'T': kbd.key = KBD_F8; break; /* (SD) kf8 cons25 */
852 case 'U': kbd.key = KBD_F9; break; /* (NP) kf9 cons25 */
853 case 'V': kbd.key = KBD_F10; break; /* (PP) kf10 cons25 */
854 case 'W': kbd.key = KBD_F11; break; /* (CTC) kf11 cons25 */
855 case 'X': kbd.key = KBD_F12; break; /* (ECH) kf12 cons25 */
857 case 'Z': /* CBT kcbt cons25 */
858 kbd.key = KBD_TAB; kbd.modifier = KBD_MOD_SHIFT; break;
860 case 'z': switch (v) { /* private */
861 case 247: kbd.key = KBD_INS; break; /* kich1 */
862 case 214: kbd.key = KBD_HOME; break; /* khome sun */
863 case 220: kbd.key = KBD_END; break; /* kend sun */
864 case 216: kbd.key = KBD_PAGE_UP; break; /* kpp sun */
865 case 222: kbd.key = KBD_PAGE_DOWN; break; /* knp sun */
866 case 249: kbd.key = KBD_DEL; break; /* kdch1 */
867 } break;
869 case '~': switch (v) { /* private */
870 case 1: kbd.key = KBD_HOME; break; /* khome linux */
871 case 2: kbd.key = KBD_INS; break; /* kich1 linux */
872 case 3: kbd.key = KBD_DEL; break; /* kdch1 linux */
873 case 4: kbd.key = KBD_END; break; /* kend linux */
874 case 5: kbd.key = KBD_PAGE_UP; break; /* kpp linux */
875 case 6: kbd.key = KBD_PAGE_DOWN; break; /* knp linux */
876 case 7: kbd.key = KBD_HOME; break; /* khome rxvt */
877 case 8: kbd.key = KBD_END; break; /* kend rxvt */
879 case 11: kbd.key = KBD_F1; break; /* kf1 rxvt */
880 case 12: kbd.key = KBD_F2; break; /* kf2 rxvt */
881 case 13: kbd.key = KBD_F3; break; /* kf3 rxvt */
882 case 14: kbd.key = KBD_F4; break; /* kf4 rxvt */
883 case 15: kbd.key = KBD_F5; break; /* kf5 rxvt */
885 case 17: kbd.key = KBD_F6; break; /* kf6 vt200 */
886 case 18: kbd.key = KBD_F7; break; /* kf7 vt200 */
887 case 19: kbd.key = KBD_F8; break; /* kf8 vt200 */
888 case 20: kbd.key = KBD_F9; break; /* kf9 vt200 */
889 case 21: kbd.key = KBD_F10; break; /* kf10 vt200 */
891 case 23: kbd.key = KBD_F11; break; /* kf11 vt200 */
892 case 24: kbd.key = KBD_F12; break; /* kf12 vt200 */
894 /* Give preference to F11 and F12 over shifted F1 and F2. */
896 case 23: kbd.key = KBD_F1; kbd.modifier = KBD_MOD_SHIFT; break;
897 case 24: kbd.key = KBD_F2; kbd.modifier = KBD_MOD_SHIFT; break;
900 case 25: kbd.key = KBD_F3; kbd.modifier = KBD_MOD_SHIFT; break;
901 case 26: kbd.key = KBD_F4; kbd.modifier = KBD_MOD_SHIFT; break;
903 case 28: kbd.key = KBD_F5; kbd.modifier = KBD_MOD_SHIFT; break;
904 case 29: kbd.key = KBD_F6; kbd.modifier = KBD_MOD_SHIFT; break;
906 case 31: kbd.key = KBD_F7; kbd.modifier = KBD_MOD_SHIFT; break;
907 case 32: kbd.key = KBD_F8; kbd.modifier = KBD_MOD_SHIFT; break;
908 case 33: kbd.key = KBD_F9; kbd.modifier = KBD_MOD_SHIFT; break;
909 case 34: kbd.key = KBD_F10; kbd.modifier = KBD_MOD_SHIFT; break;
911 case 200: itrm->bracketed_pasting = 1; break; /* xterm */
912 case 201: itrm->bracketed_pasting = 0; break; /* xterm */
914 } break;
916 case 'R': resize_terminal(); break; /* CPR u6 */
917 case 'M': /* (DL) kmous xterm */
918 #ifdef CONFIG_MOUSE
919 el = decode_terminal_mouse_escape_sequence(itrm, ev, el, v);
920 #endif /* CONFIG_MOUSE */
921 break;
924 /* KBD_UNDEF here means it was unrecognized or a mouse event. */
925 if (kbd.key != KBD_UNDEF)
926 set_kbd_interlink_event(ev, kbd.key, kbd.modifier);
928 return el;
931 /** Decode an escape sequence that begins with SS3 (SINGLE SHIFT 3).
932 * These are used for application cursor keys and the application keypad.
933 * @returns one of:
934 * - -1 if the escape sequence is not yet complete; the caller sets a timer.
935 * - 0 if the escape sequence should be parsed by some other function.
936 * - The length of the escape sequence otherwise.
937 * Returning >0 does not imply this function has altered @a *ev. */
938 static int
939 decode_terminal_application_key(struct itrm *itrm, struct interlink_event *ev)
941 unsigned char c;
942 struct interlink_event_keyboard kbd = { KBD_UNDEF, KBD_MOD_NONE };
944 assert(itrm->in.queue.len >= 2);
945 assert(itrm->in.queue.data[0] == ASCII_ESC);
946 assert(itrm->in.queue.data[1] == 0x4F); /* == 'O', incidentally */
947 if_assert_failed return 0;
949 if (itrm->in.queue.len < 3) return -1;
950 /* According to ECMA-35 section 8.4, a single (possibly multibyte)
951 * character follows the SS3. We now assume the code identifies
952 * GL as the single-shift area and the designated set has 94
953 * characters. */
954 c = itrm->in.queue.data[2];
955 if (c < 0x21 || c > 0x7E) return 0;
957 switch (c) { /* Terminfo $TERM */
958 case ' ': kbd.key = ' '; break; /* xterm */
959 case 'A': kbd.key = KBD_UP; break; /* kcuu1 vt100 */
960 case 'B': kbd.key = KBD_DOWN; break; /* kcud1 vt100 */
961 case 'C': kbd.key = KBD_RIGHT; break; /* kcuf1 vt100 */
962 case 'D': kbd.key = KBD_LEFT; break; /* kcub1 vt100 */
963 case 'F': kbd.key = KBD_END; break; /* kend xterm */
964 case 'H': kbd.key = KBD_HOME; break; /* khome xterm */
965 case 'I': kbd.key = KBD_TAB; break; /* xterm */
966 case 'M': kbd.key = KBD_ENTER; break; /* kent vt100 */
967 /* FIXME: xterm generates ESC O 2 P for Shift-PF1 */
968 case 'P': kbd.key = KBD_F1; break; /* kf1 vt100 */
969 case 'Q': kbd.key = KBD_F2; break; /* kf2 vt100 */
970 case 'R': kbd.key = KBD_F3; break; /* kf3 vt100 */
971 case 'S': kbd.key = KBD_F4; break; /* kf4 vt100 */
972 case 'X': kbd.key = '='; break; /* xterm */
974 case 'j': case 'k': case 'l': case 'm': /* *+,- xterm */
975 case 'n': case 'o': case 'p': case 'q': /* ./01 xterm */
976 case 'r': case 's': case 't': case 'u': /* 2345 xterm */
977 case 'v': case 'w': case 'x': case 'y': /* 6789 xterm */
978 kbd.key = c - 'p' + '0'; break;
980 if (kbd.key != KBD_UNDEF)
981 copy_struct(&ev->info.keyboard, &kbd);
983 return 3; /* even if we didn't recognize it */
987 /** Initialize @a *ev to match the byte @a key received from the terminal.
988 * @a key must not be a value from enum term_event_special_key. */
989 static void
990 set_kbd_event(const struct itrm *itrm, struct interlink_event *ev,
991 int key, term_event_modifier_T modifier)
993 if (key == itrm->verase)
994 key = KBD_BS;
995 else switch (key) {
996 case ASCII_TAB:
997 key = KBD_TAB;
998 break;
999 case ASCII_DEL: /* often overridden by itrm->verase above */
1000 key = KBD_DEL;
1001 break;
1002 case ASCII_LF:
1003 case ASCII_CR:
1004 key = KBD_ENTER;
1005 break;
1007 case ASCII_ESC:
1008 key = KBD_ESC;
1009 break;
1011 case ASCII_BS: /* often overridden by itrm->verase above */
1012 default:
1013 if (key < ' ') {
1014 key += 'A' - 1;
1015 modifier |= KBD_MOD_CTRL;
1019 set_kbd_interlink_event(ev, key, modifier);
1022 /** Timer callback for itrm.timer. As explained in install_timer(),
1023 * this function must erase the expired timer ID from all variables. */
1024 static void
1025 kbd_timeout(struct itrm *itrm)
1027 struct interlink_event ev;
1028 int el;
1030 itrm->timer = TIMER_ID_UNDEF;
1031 /* The expired timer ID has now been erased. */
1033 assertm(itrm->in.queue.len, "timeout on empty queue");
1034 assert(!itrm->blocked); /* block_itrm should have killed itrm->timer */
1035 if_assert_failed return;
1037 if (can_read(itrm->in.std)) {
1038 in_kbd(itrm);
1039 return;
1042 if (itrm->in.queue.len >= 2 && itrm->in.queue.data[0] == ASCII_ESC) {
1043 /* This is used for ESC [ and ESC O. */
1044 set_kbd_event(itrm, &ev, itrm->in.queue.data[1], KBD_MOD_ALT);
1045 el = 2;
1046 } else {
1047 set_kbd_event(itrm, &ev, itrm->in.queue.data[0], KBD_MOD_NONE);
1048 el = 1;
1050 itrm->bracketed_pasting = 0;
1051 itrm_queue_event(itrm, (char *) &ev, sizeof(ev));
1053 itrm->in.queue.len -= el;
1054 if (itrm->in.queue.len)
1055 memmove(itrm->in.queue.data, itrm->in.queue.data + el, itrm->in.queue.len);
1057 while (process_queue(itrm));
1060 /** Parse one event from itrm_in.queue and append to itrm_out.queue.
1061 * @pre On entry, @a *itrm must not be blocked.
1062 * @returns the number of bytes removed from itrm->in.queue; at least 0.
1063 * @post If this function leaves the queue not full, it also reenables
1064 * reading from itrm->in.std. (Because it does not add to the queue,
1065 * it never need disable reading.) */
1066 static int
1067 process_queue(struct itrm *itrm)
1069 struct interlink_event ev;
1070 int el = 0;
1072 if (!itrm->in.queue.len) goto return_without_event;
1073 assert(!itrm->blocked);
1074 if_assert_failed return 0; /* unlike goto, don't enable reading */
1076 set_kbd_interlink_event(&ev, KBD_UNDEF, KBD_MOD_NONE);
1078 #ifdef DEBUG_ITRM_QUEUE
1080 int i;
1082 /* Dump current queue in a readable form to stderr. */
1083 for (i = 0; i < itrm->in.queue.len; i++)
1084 if (itrm->in.queue.data[i] == ASCII_ESC)
1085 fprintf(stderr, "ESC ");
1086 else if (isprint(itrm->in.queue.data[i]) && !isspace(itrm->in.queue.data[i]))
1087 fprintf(stderr, "%c ", itrm->in.queue.data[i]);
1088 else
1089 fprintf(stderr, "0x%02x ", itrm->in.queue.data[i]);
1091 fprintf(stderr, "\n");
1092 fflush(stderr);
1094 #endif /* DEBUG_ITRM_QUEUE */
1096 /* el == -1 means itrm->in.queue appears to be the beginning of an
1097 * escape sequence but it is not yet complete. Set a timer;
1098 * if it times out, then assume it wasn't an escape sequence
1099 * after all.
1100 * el == 0 means this function has not yet figured out what the data
1101 * in itrm->in.queue is, but some possibilities remain.
1102 * One of them will be chosen before returning.
1103 * el > 0 means some bytes were successfully parsed from the beginning
1104 * of itrm->in.queue and should now be removed from there.
1105 * However, this does not always imply an event will be queued.
1108 /* ELinks should also recognize U+009B CONTROL SEQUENCE INTRODUCER
1109 * as meaning the same as ESC 0x5B, and U+008F SINGLE SHIFT THREE as
1110 * meaning the same as ESC 0x4F, but those cannot yet be implemented
1111 * because of bug 777: the UTF-8 decoder is run too late. */
1112 if (itrm->in.queue.data[0] == ASCII_ESC) {
1113 if (itrm->in.queue.len < 2) {
1114 el = -1;
1115 } else if (itrm->in.queue.data[1] == 0x5B /* CSI */) {
1116 el = decode_terminal_escape_sequence(itrm, &ev);
1117 } else if (itrm->in.queue.data[1] == 0x4F /* SS3 */) {
1118 el = decode_terminal_application_key(itrm, &ev);
1119 } else if (itrm->in.queue.data[1] == ASCII_ESC) {
1120 /* ESC ESC can be either Alt-Esc or the
1121 * beginning of e.g. ESC ESC 0x5B 0x41,
1122 * which we should parse as Esc Up. */
1123 if (itrm->in.queue.len < 3) {
1124 /* Need more data to figure it out. */
1125 el = -1;
1126 } else if (itrm->in.queue.data[2] == 0x5B
1127 || itrm->in.queue.data[2] == 0x4F) {
1128 /* The first ESC appears to be followed
1129 * by an escape sequence. Treat it as
1130 * a standalone Esc. */
1131 el = 1;
1132 set_kbd_event(itrm, &ev,
1133 itrm->in.queue.data[0],
1134 KBD_MOD_NONE);
1135 } else {
1136 /* The second ESC of ESC ESC is not the
1137 * beginning of any known escape sequence.
1138 * This must be Alt-Esc, then. */
1139 el = 2;
1140 set_kbd_event(itrm, &ev,
1141 itrm->in.queue.data[1],
1142 KBD_MOD_ALT);
1145 if (el == 0) { /* Begins with ESC, but none of the above */
1146 el = 2;
1147 set_kbd_event(itrm, &ev, itrm->in.queue.data[1],
1148 KBD_MOD_ALT);
1151 } else if (itrm->in.queue.data[0] == 0) {
1152 static const struct term_event_keyboard os2xtd[256] = {
1153 #include "terminal/key.inc"
1156 if (itrm->in.queue.len < 2)
1157 el = -1;
1158 else {
1159 el = 2;
1160 set_kbd_interlink_event(&ev,
1161 os2xtd[itrm->in.queue.data[1]].key,
1162 os2xtd[itrm->in.queue.data[1]].modifier);
1166 if (el == 0) {
1167 el = 1;
1168 set_kbd_event(itrm, &ev, itrm->in.queue.data[0],
1169 itrm->bracketed_pasting ? KBD_MOD_PASTE : KBD_MOD_NONE);
1172 /* The call to decode_terminal_escape_sequence() might have changed the
1173 * keyboard event to a mouse event. */
1174 if (ev.ev == EVENT_MOUSE || ev.info.keyboard.key != KBD_UNDEF) {
1175 itrm_queue_event(itrm, (char *) &ev, sizeof(ev));
1176 itrm->bracketed_pasting =
1177 (ev.ev == EVENT_KBD
1178 && (ev.info.keyboard.modifier & KBD_MOD_PASTE));
1181 return_without_event:
1182 if (el == -1) {
1183 install_timer(&itrm->timer, ESC_TIMEOUT, (void (*)(void *)) kbd_timeout,
1184 itrm);
1185 return 0;
1186 } else {
1187 assertm(itrm->in.queue.len >= el, "event queue underflow");
1188 if_assert_failed { itrm->in.queue.len = el; }
1190 itrm->in.queue.len -= el;
1191 if (itrm->in.queue.len)
1192 memmove(itrm->in.queue.data, itrm->in.queue.data + el, itrm->in.queue.len);
1194 if (itrm->in.queue.len < ITRM_IN_QUEUE_SIZE)
1195 handle_itrm_stdin(itrm);
1197 return el;
1202 /** A select_handler_T read_func for itrm_in.std. This is called when
1203 * characters typed by the user arrive from the terminal. */
1204 static void
1205 in_kbd(struct itrm *itrm)
1207 int r;
1209 if (!can_read(itrm->in.std)) return;
1211 kill_timer(&itrm->timer);
1213 if (itrm->in.queue.len >= ITRM_IN_QUEUE_SIZE) {
1214 unhandle_itrm_stdin(itrm);
1215 while (process_queue(itrm));
1216 return;
1219 r = safe_read(itrm->in.std, itrm->in.queue.data + itrm->in.queue.len,
1220 ITRM_IN_QUEUE_SIZE - itrm->in.queue.len);
1221 if (r <= 0) {
1222 free_itrm(itrm);
1223 return;
1226 itrm->in.queue.len += r;
1227 if (itrm->in.queue.len > ITRM_IN_QUEUE_SIZE) {
1228 ERROR(gettext("Too many bytes read from the itrm!"));
1229 itrm->in.queue.len = ITRM_IN_QUEUE_SIZE;
1232 while (process_queue(itrm));
1235 /** Enable reading from itrm_in.std. ELinks will read any available
1236 * bytes from the tty into itrm->in.queue and then parse them.
1237 * Reading should be enabled whenever itrm->in.queue is not full and
1238 * itrm->blocked is 0. */
1239 static void
1240 handle_itrm_stdin(struct itrm *itrm)
1242 assert(itrm->in.std >= 0);
1243 if_assert_failed return;
1245 set_handlers(itrm->in.std, (select_handler_T) in_kbd, NULL,
1246 (select_handler_T) free_itrm, itrm);
1249 /** Disable reading from itrm_in.std. Reading should be disabled
1250 * whenever itrm->in.queue is full (there is no room for the data)
1251 * or itrm->blocked is 1 (other processes may read the data). */
1252 static void
1253 unhandle_itrm_stdin(struct itrm *itrm)
1255 assert(itrm->in.std >= 0);
1256 if_assert_failed return;
1258 set_handlers(itrm->in.std, (select_handler_T) NULL, NULL,
1259 (select_handler_T) free_itrm, itrm);