]> code.delx.au - gnu-emacs/blob - src/term.c
Merge branch master of git.sv.gnu.org:/srv/git/emacs.
[gnu-emacs] / src / term.c
1 /* Terminal control module for terminals described by TERMCAP
2 Copyright (C) 1985-1987, 1993-1995, 1998, 2000-2015 Free Software
3 Foundation, Inc.
4
5 This file is part of GNU Emacs.
6
7 GNU Emacs is free software: you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation, either version 3 of the License, or
10 (at your option) any later version.
11
12 GNU Emacs is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
19
20 /* New redisplay, TTY faces by Gerd Moellmann <gerd@gnu.org>. */
21
22 #include <config.h>
23 #include <errno.h>
24 #include <fcntl.h>
25 #include <stdio.h>
26 #include <sys/file.h>
27 #include <sys/time.h>
28 #include <unistd.h>
29
30 #include "lisp.h"
31 #include "termchar.h"
32 #include "tparam.h"
33 #include "character.h"
34 #include "buffer.h"
35 #include "charset.h"
36 #include "coding.h"
37 #include "composite.h"
38 #include "keyboard.h"
39 #include "frame.h"
40 #include "disptab.h"
41 #include "termhooks.h"
42 #include "dispextern.h"
43 #include "window.h"
44 #include "keymap.h"
45 #include "blockinput.h"
46 #include "syssignal.h"
47 #include "systty.h"
48 #include "intervals.h"
49 #ifdef MSDOS
50 #include "msdos.h"
51 static int been_here = -1;
52 #endif
53
54 #ifdef USE_X_TOOLKIT
55 #include "../lwlib/lwlib.h"
56 #endif
57
58 #include "cm.h"
59 #ifdef HAVE_X_WINDOWS
60 #include "xterm.h"
61 #endif
62
63 #include "menu.h"
64
65 /* The name of the default console device. */
66 #ifdef WINDOWSNT
67 #define DEV_TTY "CONOUT$"
68 #include "w32term.h"
69 #else
70 #define DEV_TTY "/dev/tty"
71 #endif
72
73 static void tty_set_scroll_region (struct frame *f, int start, int stop);
74 static void turn_on_face (struct frame *, int face_id);
75 static void turn_off_face (struct frame *, int face_id);
76 static void tty_turn_off_highlight (struct tty_display_info *);
77 static void tty_show_cursor (struct tty_display_info *);
78 static void tty_hide_cursor (struct tty_display_info *);
79 static void tty_background_highlight (struct tty_display_info *tty);
80 static void clear_tty_hooks (struct terminal *terminal);
81 static void set_tty_hooks (struct terminal *terminal);
82 static void dissociate_if_controlling_tty (int fd);
83 static void delete_tty (struct terminal *);
84 static _Noreturn void maybe_fatal (bool, struct terminal *,
85 const char *, const char *, ...)
86 ATTRIBUTE_FORMAT_PRINTF (3, 5) ATTRIBUTE_FORMAT_PRINTF (4, 5);
87 static _Noreturn void vfatal (const char *str, va_list ap)
88 ATTRIBUTE_FORMAT_PRINTF (1, 0);
89
90
91 #define OUTPUT(tty, a) \
92 emacs_tputs ((tty), a, \
93 FRAME_TOTAL_LINES (XFRAME (selected_frame)) - curY (tty), \
94 cmputc)
95
96 #define OUTPUT1(tty, a) emacs_tputs ((tty), a, 1, cmputc)
97 #define OUTPUTL(tty, a, lines) emacs_tputs ((tty), a, lines, cmputc)
98
99 #define OUTPUT_IF(tty, a) \
100 do { \
101 if (a) \
102 OUTPUT (tty, a); \
103 } while (0)
104
105 #define OUTPUT1_IF(tty, a) do { if (a) emacs_tputs ((tty), a, 1, cmputc); } while (0)
106
107 /* Display space properties. */
108
109 /* Chain of all tty device parameters. */
110 struct tty_display_info *tty_list;
111
112 /* Meaning of bits in no_color_video. Each bit set means that the
113 corresponding attribute cannot be combined with colors. */
114
115 enum no_color_bit
116 {
117 NC_STANDOUT = 1 << 0,
118 NC_UNDERLINE = 1 << 1,
119 NC_REVERSE = 1 << 2,
120 NC_ITALIC = 1 << 3,
121 NC_DIM = 1 << 4,
122 NC_BOLD = 1 << 5,
123 NC_INVIS = 1 << 6,
124 NC_PROTECT = 1 << 7
125 };
126
127 /* internal state */
128
129 /* The largest frame width in any call to calculate_costs. */
130
131 static int max_frame_cols;
132
133 \f
134
135 #ifdef HAVE_GPM
136 #include <sys/fcntl.h>
137
138 /* The device for which we have enabled gpm support (or NULL). */
139 struct tty_display_info *gpm_tty = NULL;
140
141 /* Last recorded mouse coordinates. */
142 static int last_mouse_x, last_mouse_y;
143 #endif /* HAVE_GPM */
144
145 /* Ring the bell on a tty. */
146
147 static void
148 tty_ring_bell (struct frame *f)
149 {
150 struct tty_display_info *tty = FRAME_TTY (f);
151
152 if (tty->output)
153 {
154 OUTPUT (tty, (tty->TS_visible_bell && visible_bell
155 ? tty->TS_visible_bell
156 : tty->TS_bell));
157 fflush (tty->output);
158 }
159 }
160
161 /* Set up termcap modes for Emacs. */
162
163 static void
164 tty_send_additional_strings (struct terminal *terminal, Lisp_Object sym)
165 {
166 Lisp_Object lisp_terminal;
167 Lisp_Object extra_codes;
168 struct tty_display_info *tty = terminal->display_info.tty;
169
170 XSETTERMINAL (lisp_terminal, terminal);
171 for (extra_codes = Fterminal_parameter (lisp_terminal, sym);
172 CONSP (extra_codes);
173 extra_codes = XCDR (extra_codes))
174 {
175 Lisp_Object string = XCAR (extra_codes);
176 if (STRINGP (string))
177 {
178 fwrite (SDATA (string), 1, SBYTES (string), tty->output);
179 if (tty->termscript)
180 fwrite (SDATA (string), 1, SBYTES (string), tty->termscript);
181 }
182 }
183 }
184
185 static void
186 tty_set_terminal_modes (struct terminal *terminal)
187 {
188 struct tty_display_info *tty = terminal->display_info.tty;
189
190 if (tty->output)
191 {
192 if (tty->TS_termcap_modes)
193 OUTPUT (tty, tty->TS_termcap_modes);
194 else
195 {
196 /* Output enough newlines to scroll all the old screen contents
197 off the screen, so it won't be overwritten and lost. */
198 int i;
199 current_tty = tty;
200 for (i = 0; i < FRAME_TOTAL_LINES (XFRAME (selected_frame)); i++)
201 cmputc ('\n');
202 }
203
204 OUTPUT_IF (tty, visible_cursor ? tty->TS_cursor_visible : tty->TS_cursor_normal);
205 OUTPUT_IF (tty, tty->TS_keypad_mode);
206 losecursor (tty);
207 tty_send_additional_strings (terminal, Qtty_mode_set_strings);
208 fflush (tty->output);
209 }
210 }
211
212 /* Reset termcap modes before exiting Emacs. */
213
214 static void
215 tty_reset_terminal_modes (struct terminal *terminal)
216 {
217 struct tty_display_info *tty = terminal->display_info.tty;
218
219 if (tty->output)
220 {
221 tty_send_additional_strings (terminal, Qtty_mode_reset_strings);
222 tty_turn_off_highlight (tty);
223 tty_turn_off_insert (tty);
224 OUTPUT_IF (tty, tty->TS_end_keypad_mode);
225 OUTPUT_IF (tty, tty->TS_cursor_normal);
226 OUTPUT_IF (tty, tty->TS_end_termcap_modes);
227 OUTPUT_IF (tty, tty->TS_orig_pair);
228 /* Output raw CR so kernel can track the cursor hpos. */
229 current_tty = tty;
230 cmputc ('\r');
231 fflush (tty->output);
232 }
233 }
234
235 /* Flag the end of a display update on a termcap terminal. */
236
237 static void
238 tty_update_end (struct frame *f)
239 {
240 struct tty_display_info *tty = FRAME_TTY (f);
241
242 if (!XWINDOW (selected_window)->cursor_off_p)
243 tty_show_cursor (tty);
244 tty_turn_off_insert (tty);
245 tty_background_highlight (tty);
246 fflush (tty->output);
247 }
248
249 /* The implementation of set_terminal_window for termcap frames. */
250
251 static void
252 tty_set_terminal_window (struct frame *f, int size)
253 {
254 struct tty_display_info *tty = FRAME_TTY (f);
255
256 tty->specified_window = size ? size : FRAME_TOTAL_LINES (f);
257 if (FRAME_SCROLL_REGION_OK (f))
258 tty_set_scroll_region (f, 0, tty->specified_window);
259 }
260
261 static void
262 tty_set_scroll_region (struct frame *f, int start, int stop)
263 {
264 char *buf;
265 struct tty_display_info *tty = FRAME_TTY (f);
266
267 if (tty->TS_set_scroll_region)
268 buf = tparam (tty->TS_set_scroll_region, 0, 0, start, stop - 1, 0, 0);
269 else if (tty->TS_set_scroll_region_1)
270 buf = tparam (tty->TS_set_scroll_region_1, 0, 0,
271 FRAME_TOTAL_LINES (f), start,
272 FRAME_TOTAL_LINES (f) - stop,
273 FRAME_TOTAL_LINES (f));
274 else
275 buf = tparam (tty->TS_set_window, 0, 0, start, 0, stop, FRAME_COLS (f));
276
277 OUTPUT (tty, buf);
278 xfree (buf);
279 losecursor (tty);
280 }
281
282 \f
283 static void
284 tty_turn_on_insert (struct tty_display_info *tty)
285 {
286 if (!tty->insert_mode)
287 OUTPUT (tty, tty->TS_insert_mode);
288 tty->insert_mode = 1;
289 }
290
291 void
292 tty_turn_off_insert (struct tty_display_info *tty)
293 {
294 if (tty->insert_mode)
295 OUTPUT (tty, tty->TS_end_insert_mode);
296 tty->insert_mode = 0;
297 }
298 \f
299 /* Handle highlighting. */
300
301 static void
302 tty_turn_off_highlight (struct tty_display_info *tty)
303 {
304 if (tty->standout_mode)
305 OUTPUT_IF (tty, tty->TS_end_standout_mode);
306 tty->standout_mode = 0;
307 }
308
309 static void
310 tty_turn_on_highlight (struct tty_display_info *tty)
311 {
312 if (!tty->standout_mode)
313 OUTPUT_IF (tty, tty->TS_standout_mode);
314 tty->standout_mode = 1;
315 }
316
317 static void
318 tty_toggle_highlight (struct tty_display_info *tty)
319 {
320 if (tty->standout_mode)
321 tty_turn_off_highlight (tty);
322 else
323 tty_turn_on_highlight (tty);
324 }
325
326
327 /* Make cursor invisible. */
328
329 static void
330 tty_hide_cursor (struct tty_display_info *tty)
331 {
332 if (tty->cursor_hidden == 0)
333 {
334 tty->cursor_hidden = 1;
335 #ifdef WINDOWSNT
336 w32con_hide_cursor ();
337 #else
338 OUTPUT_IF (tty, tty->TS_cursor_invisible);
339 #endif
340 }
341 }
342
343
344 /* Ensure that cursor is visible. */
345
346 static void
347 tty_show_cursor (struct tty_display_info *tty)
348 {
349 if (tty->cursor_hidden)
350 {
351 tty->cursor_hidden = 0;
352 #ifdef WINDOWSNT
353 w32con_show_cursor ();
354 #else
355 OUTPUT_IF (tty, tty->TS_cursor_normal);
356 if (visible_cursor)
357 OUTPUT_IF (tty, tty->TS_cursor_visible);
358 #endif
359 }
360 }
361
362
363 /* Set standout mode to the state it should be in for
364 empty space inside windows. What this is,
365 depends on the user option inverse-video. */
366
367 static void
368 tty_background_highlight (struct tty_display_info *tty)
369 {
370 if (inverse_video)
371 tty_turn_on_highlight (tty);
372 else
373 tty_turn_off_highlight (tty);
374 }
375
376 /* Set standout mode to the mode specified for the text to be output. */
377
378 static void
379 tty_highlight_if_desired (struct tty_display_info *tty)
380 {
381 if (inverse_video)
382 tty_turn_on_highlight (tty);
383 else
384 tty_turn_off_highlight (tty);
385 }
386 \f
387
388 /* Move cursor to row/column position VPOS/HPOS. HPOS/VPOS are
389 frame-relative coordinates. */
390
391 static void
392 tty_cursor_to (struct frame *f, int vpos, int hpos)
393 {
394 struct tty_display_info *tty = FRAME_TTY (f);
395
396 /* Detect the case where we are called from reset_sys_modes
397 and the costs have never been calculated. Do nothing. */
398 if (! tty->costs_set)
399 return;
400
401 if (curY (tty) == vpos
402 && curX (tty) == hpos)
403 return;
404 if (!tty->TF_standout_motion)
405 tty_background_highlight (tty);
406 if (!tty->TF_insmode_motion)
407 tty_turn_off_insert (tty);
408 cmgoto (tty, vpos, hpos);
409 }
410
411 /* Similar but don't take any account of the wasted characters. */
412
413 static void
414 tty_raw_cursor_to (struct frame *f, int row, int col)
415 {
416 struct tty_display_info *tty = FRAME_TTY (f);
417
418 if (curY (tty) == row
419 && curX (tty) == col)
420 return;
421 if (!tty->TF_standout_motion)
422 tty_background_highlight (tty);
423 if (!tty->TF_insmode_motion)
424 tty_turn_off_insert (tty);
425 cmgoto (tty, row, col);
426 }
427 \f
428 /* Erase operations */
429
430 /* Clear from cursor to end of frame on a termcap device. */
431
432 static void
433 tty_clear_to_end (struct frame *f)
434 {
435 register int i;
436 struct tty_display_info *tty = FRAME_TTY (f);
437
438 if (tty->TS_clr_to_bottom)
439 {
440 tty_background_highlight (tty);
441 OUTPUT (tty, tty->TS_clr_to_bottom);
442 }
443 else
444 {
445 for (i = curY (tty); i < FRAME_TOTAL_LINES (f); i++)
446 {
447 cursor_to (f, i, 0);
448 clear_end_of_line (f, FRAME_COLS (f));
449 }
450 }
451 }
452
453 /* Clear an entire termcap frame. */
454
455 static void
456 tty_clear_frame (struct frame *f)
457 {
458 struct tty_display_info *tty = FRAME_TTY (f);
459
460 if (tty->TS_clr_frame)
461 {
462 tty_background_highlight (tty);
463 OUTPUT (tty, tty->TS_clr_frame);
464 cmat (tty, 0, 0);
465 }
466 else
467 {
468 cursor_to (f, 0, 0);
469 clear_to_end (f);
470 }
471 }
472
473 /* An implementation of clear_end_of_line for termcap frames.
474
475 Note that the cursor may be moved, on terminals lacking a `ce' string. */
476
477 static void
478 tty_clear_end_of_line (struct frame *f, int first_unused_hpos)
479 {
480 register int i;
481 struct tty_display_info *tty = FRAME_TTY (f);
482
483 /* Detect the case where we are called from reset_sys_modes
484 and the costs have never been calculated. Do nothing. */
485 if (! tty->costs_set)
486 return;
487
488 if (curX (tty) >= first_unused_hpos)
489 return;
490 tty_background_highlight (tty);
491 if (tty->TS_clr_line)
492 {
493 OUTPUT1 (tty, tty->TS_clr_line);
494 }
495 else
496 { /* have to do it the hard way */
497 tty_turn_off_insert (tty);
498
499 /* Do not write in last row last col with Auto-wrap on. */
500 if (AutoWrap (tty)
501 && curY (tty) == FrameRows (tty) - 1
502 && first_unused_hpos == FrameCols (tty))
503 first_unused_hpos--;
504
505 for (i = curX (tty); i < first_unused_hpos; i++)
506 {
507 if (tty->termscript)
508 fputc (' ', tty->termscript);
509 fputc (' ', tty->output);
510 }
511 cmplus (tty, first_unused_hpos - curX (tty));
512 }
513 }
514 \f
515 /* Buffers to store the source and result of code conversion for terminal. */
516 static unsigned char *encode_terminal_src;
517 static unsigned char *encode_terminal_dst;
518 /* Allocated sizes of the above buffers. */
519 static ptrdiff_t encode_terminal_src_size;
520 static ptrdiff_t encode_terminal_dst_size;
521
522 /* Encode SRC_LEN glyphs starting at SRC to terminal output codes.
523 Set CODING->produced to the byte-length of the resulting byte
524 sequence, and return a pointer to that byte sequence. */
525
526 unsigned char *
527 encode_terminal_code (struct glyph *src, int src_len,
528 struct coding_system *coding)
529 {
530 struct glyph *src_end = src + src_len;
531 unsigned char *buf;
532 ptrdiff_t nchars, nbytes, required;
533 ptrdiff_t tlen = GLYPH_TABLE_LENGTH;
534 register Lisp_Object *tbase = GLYPH_TABLE_BASE;
535 Lisp_Object charset_list;
536
537 /* Allocate sufficient size of buffer to store all characters in
538 multibyte-form. But, it may be enlarged on demand if
539 Vglyph_table contains a string or a composite glyph is
540 encountered. */
541 if (min (PTRDIFF_MAX, SIZE_MAX) / MAX_MULTIBYTE_LENGTH < src_len)
542 memory_full (SIZE_MAX);
543 required = src_len;
544 required *= MAX_MULTIBYTE_LENGTH;
545 if (encode_terminal_src_size < required)
546 {
547 encode_terminal_src = xrealloc (encode_terminal_src, required);
548 encode_terminal_src_size = required;
549 }
550
551 charset_list = coding_charset_list (coding);
552
553 buf = encode_terminal_src;
554 nchars = 0;
555 while (src < src_end)
556 {
557 if (src->type == COMPOSITE_GLYPH)
558 {
559 struct composition *cmp IF_LINT (= NULL);
560 Lisp_Object gstring IF_LINT (= Qnil);
561 int i;
562
563 nbytes = buf - encode_terminal_src;
564 if (src->u.cmp.automatic)
565 {
566 gstring = composition_gstring_from_id (src->u.cmp.id);
567 required = src->slice.cmp.to - src->slice.cmp.from + 1;
568 }
569 else
570 {
571 cmp = composition_table[src->u.cmp.id];
572 required = cmp->glyph_len;
573 required *= MAX_MULTIBYTE_LENGTH;
574 }
575
576 if (encode_terminal_src_size - nbytes < required)
577 {
578 encode_terminal_src =
579 xpalloc (encode_terminal_src, &encode_terminal_src_size,
580 required - (encode_terminal_src_size - nbytes),
581 -1, 1);
582 buf = encode_terminal_src + nbytes;
583 }
584
585 if (src->u.cmp.automatic)
586 for (i = src->slice.cmp.from; i <= src->slice.cmp.to; i++)
587 {
588 Lisp_Object g = LGSTRING_GLYPH (gstring, i);
589 int c = LGLYPH_CHAR (g);
590
591 if (! char_charset (c, charset_list, NULL))
592 c = '?';
593 buf += CHAR_STRING (c, buf);
594 nchars++;
595 }
596 else
597 for (i = 0; i < cmp->glyph_len; i++)
598 {
599 int c = COMPOSITION_GLYPH (cmp, i);
600
601 /* TAB in a composition means display glyphs with
602 padding space on the left or right. */
603 if (c == '\t')
604 continue;
605 if (char_charset (c, charset_list, NULL))
606 {
607 if (CHAR_WIDTH (c) == 0
608 && i > 0 && COMPOSITION_GLYPH (cmp, i - 1) == '\t')
609 /* Should be left-padded */
610 {
611 buf += CHAR_STRING (' ', buf);
612 nchars++;
613 }
614 }
615 else
616 c = '?';
617 buf += CHAR_STRING (c, buf);
618 nchars++;
619 }
620 }
621 /* We must skip glyphs to be padded for a wide character. */
622 else if (! CHAR_GLYPH_PADDING_P (*src))
623 {
624 GLYPH g;
625 int c IF_LINT (= 0);
626 Lisp_Object string;
627
628 string = Qnil;
629 SET_GLYPH_FROM_CHAR_GLYPH (g, src[0]);
630
631 if (GLYPH_INVALID_P (g) || GLYPH_SIMPLE_P (tbase, tlen, g))
632 {
633 /* This glyph doesn't have an entry in Vglyph_table. */
634 c = src->u.ch;
635 }
636 else
637 {
638 /* This glyph has an entry in Vglyph_table,
639 so process any alias before testing for simpleness. */
640 GLYPH_FOLLOW_ALIASES (tbase, tlen, g);
641
642 if (GLYPH_SIMPLE_P (tbase, tlen, g))
643 /* We set the multi-byte form of a character in G
644 (that should be an ASCII character) at WORKBUF. */
645 c = GLYPH_CHAR (g);
646 else
647 /* We have a string in Vglyph_table. */
648 string = tbase[GLYPH_CHAR (g)];
649 }
650
651 if (NILP (string))
652 {
653 nbytes = buf - encode_terminal_src;
654 if (encode_terminal_src_size - nbytes < MAX_MULTIBYTE_LENGTH)
655 {
656 encode_terminal_src =
657 xpalloc (encode_terminal_src, &encode_terminal_src_size,
658 MAX_MULTIBYTE_LENGTH, -1, 1);
659 buf = encode_terminal_src + nbytes;
660 }
661 if (CHAR_BYTE8_P (c)
662 || char_charset (c, charset_list, NULL))
663 {
664 /* Store the multibyte form of C at BUF. */
665 buf += CHAR_STRING (c, buf);
666 nchars++;
667 }
668 else
669 {
670 /* C is not encodable. */
671 *buf++ = '?';
672 nchars++;
673 while (src + 1 < src_end && CHAR_GLYPH_PADDING_P (src[1]))
674 {
675 *buf++ = '?';
676 nchars++;
677 src++;
678 }
679 }
680 }
681 else
682 {
683 if (! STRING_MULTIBYTE (string))
684 string = string_to_multibyte (string);
685 nbytes = buf - encode_terminal_src;
686 if (encode_terminal_src_size - nbytes < SBYTES (string))
687 {
688 encode_terminal_src =
689 xpalloc (encode_terminal_src, &encode_terminal_src_size,
690 (SBYTES (string)
691 - (encode_terminal_src_size - nbytes)),
692 -1, 1);
693 buf = encode_terminal_src + nbytes;
694 }
695 memcpy (buf, SDATA (string), SBYTES (string));
696 buf += SBYTES (string);
697 nchars += SCHARS (string);
698 }
699 }
700 src++;
701 }
702
703 if (nchars == 0)
704 {
705 coding->produced = 0;
706 return NULL;
707 }
708
709 nbytes = buf - encode_terminal_src;
710 coding->source = encode_terminal_src;
711 if (encode_terminal_dst_size == 0)
712 {
713 encode_terminal_dst = xrealloc (encode_terminal_dst,
714 encode_terminal_src_size);
715 encode_terminal_dst_size = encode_terminal_src_size;
716 }
717 coding->destination = encode_terminal_dst;
718 coding->dst_bytes = encode_terminal_dst_size;
719 encode_coding_object (coding, Qnil, 0, 0, nchars, nbytes, Qnil);
720 /* coding->destination may have been reallocated. */
721 encode_terminal_dst = coding->destination;
722 encode_terminal_dst_size = coding->dst_bytes;
723
724 return (encode_terminal_dst);
725 }
726
727
728
729 /* An implementation of write_glyphs for termcap frames. */
730
731 static void
732 tty_write_glyphs (struct frame *f, struct glyph *string, int len)
733 {
734 unsigned char *conversion_buffer;
735 struct coding_system *coding;
736 int n, stringlen;
737
738 struct tty_display_info *tty = FRAME_TTY (f);
739
740 tty_turn_off_insert (tty);
741 tty_hide_cursor (tty);
742
743 /* Don't dare write in last column of bottom line, if Auto-Wrap,
744 since that would scroll the whole frame on some terminals. */
745
746 if (AutoWrap (tty)
747 && curY (tty) + 1 == FRAME_TOTAL_LINES (f)
748 && (curX (tty) + len) == FRAME_COLS (f))
749 len --;
750 if (len <= 0)
751 return;
752
753 cmplus (tty, len);
754
755 /* If terminal_coding does any conversion, use it, otherwise use
756 safe_terminal_coding. We can't use CODING_REQUIRE_ENCODING here
757 because it always return 1 if the member src_multibyte is 1. */
758 coding = (FRAME_TERMINAL_CODING (f)->common_flags & CODING_REQUIRE_ENCODING_MASK
759 ? FRAME_TERMINAL_CODING (f) : &safe_terminal_coding);
760 /* The mode bit CODING_MODE_LAST_BLOCK should be set to 1 only at
761 the tail. */
762 coding->mode &= ~CODING_MODE_LAST_BLOCK;
763
764 for (stringlen = len; stringlen != 0; stringlen -= n)
765 {
766 /* Identify a run of glyphs with the same face. */
767 int face_id = string->face_id;
768
769 for (n = 1; n < stringlen; ++n)
770 if (string[n].face_id != face_id)
771 break;
772
773 /* Turn appearance modes of the face of the run on. */
774 tty_highlight_if_desired (tty);
775 turn_on_face (f, face_id);
776
777 if (n == stringlen)
778 /* This is the last run. */
779 coding->mode |= CODING_MODE_LAST_BLOCK;
780 conversion_buffer = encode_terminal_code (string, n, coding);
781 if (coding->produced > 0)
782 {
783 block_input ();
784 fwrite (conversion_buffer, 1, coding->produced, tty->output);
785 if (ferror (tty->output))
786 clearerr (tty->output);
787 if (tty->termscript)
788 fwrite (conversion_buffer, 1, coding->produced, tty->termscript);
789 unblock_input ();
790 }
791 string += n;
792
793 /* Turn appearance modes off. */
794 turn_off_face (f, face_id);
795 tty_turn_off_highlight (tty);
796 }
797
798 cmcheckmagic (tty);
799 }
800
801 #ifdef HAVE_GPM /* Only used by GPM code. */
802
803 static void
804 tty_write_glyphs_with_face (register struct frame *f, register struct glyph *string,
805 register int len, register int face_id)
806 {
807 unsigned char *conversion_buffer;
808 struct coding_system *coding;
809
810 struct tty_display_info *tty = FRAME_TTY (f);
811
812 tty_turn_off_insert (tty);
813 tty_hide_cursor (tty);
814
815 /* Don't dare write in last column of bottom line, if Auto-Wrap,
816 since that would scroll the whole frame on some terminals. */
817
818 if (AutoWrap (tty)
819 && curY (tty) + 1 == FRAME_TOTAL_LINES (f)
820 && (curX (tty) + len) == FRAME_COLS (f))
821 len --;
822 if (len <= 0)
823 return;
824
825 cmplus (tty, len);
826
827 /* If terminal_coding does any conversion, use it, otherwise use
828 safe_terminal_coding. We can't use CODING_REQUIRE_ENCODING here
829 because it always return 1 if the member src_multibyte is 1. */
830 coding = (FRAME_TERMINAL_CODING (f)->common_flags & CODING_REQUIRE_ENCODING_MASK
831 ? FRAME_TERMINAL_CODING (f) : &safe_terminal_coding);
832 /* The mode bit CODING_MODE_LAST_BLOCK should be set to 1 only at
833 the tail. */
834 coding->mode &= ~CODING_MODE_LAST_BLOCK;
835
836 /* Turn appearance modes of the face. */
837 tty_highlight_if_desired (tty);
838 turn_on_face (f, face_id);
839
840 coding->mode |= CODING_MODE_LAST_BLOCK;
841 conversion_buffer = encode_terminal_code (string, len, coding);
842 if (coding->produced > 0)
843 {
844 block_input ();
845 fwrite (conversion_buffer, 1, coding->produced, tty->output);
846 if (ferror (tty->output))
847 clearerr (tty->output);
848 if (tty->termscript)
849 fwrite (conversion_buffer, 1, coding->produced, tty->termscript);
850 unblock_input ();
851 }
852
853 /* Turn appearance modes off. */
854 turn_off_face (f, face_id);
855 tty_turn_off_highlight (tty);
856
857 cmcheckmagic (tty);
858 }
859 #endif
860
861 /* An implementation of insert_glyphs for termcap frames. */
862
863 static void
864 tty_insert_glyphs (struct frame *f, struct glyph *start, int len)
865 {
866 char *buf;
867 struct glyph *glyph = NULL;
868 unsigned char *conversion_buffer;
869 unsigned char space[1];
870 struct coding_system *coding;
871
872 struct tty_display_info *tty = FRAME_TTY (f);
873
874 if (tty->TS_ins_multi_chars)
875 {
876 buf = tparam (tty->TS_ins_multi_chars, 0, 0, len, 0, 0, 0);
877 OUTPUT1 (tty, buf);
878 xfree (buf);
879 if (start)
880 write_glyphs (f, start, len);
881 return;
882 }
883
884 tty_turn_on_insert (tty);
885 cmplus (tty, len);
886
887 if (! start)
888 space[0] = SPACEGLYPH;
889
890 /* If terminal_coding does any conversion, use it, otherwise use
891 safe_terminal_coding. We can't use CODING_REQUIRE_ENCODING here
892 because it always return 1 if the member src_multibyte is 1. */
893 coding = (FRAME_TERMINAL_CODING (f)->common_flags & CODING_REQUIRE_ENCODING_MASK
894 ? FRAME_TERMINAL_CODING (f) : &safe_terminal_coding);
895 /* The mode bit CODING_MODE_LAST_BLOCK should be set to 1 only at
896 the tail. */
897 coding->mode &= ~CODING_MODE_LAST_BLOCK;
898
899 while (len-- > 0)
900 {
901 OUTPUT1_IF (tty, tty->TS_ins_char);
902 if (!start)
903 {
904 conversion_buffer = space;
905 coding->produced = 1;
906 }
907 else
908 {
909 tty_highlight_if_desired (tty);
910 turn_on_face (f, start->face_id);
911 glyph = start;
912 ++start;
913 /* We must open sufficient space for a character which
914 occupies more than one column. */
915 while (len && CHAR_GLYPH_PADDING_P (*start))
916 {
917 OUTPUT1_IF (tty, tty->TS_ins_char);
918 start++, len--;
919 }
920
921 if (len <= 0)
922 /* This is the last glyph. */
923 coding->mode |= CODING_MODE_LAST_BLOCK;
924
925 conversion_buffer = encode_terminal_code (glyph, 1, coding);
926 }
927
928 if (coding->produced > 0)
929 {
930 block_input ();
931 fwrite (conversion_buffer, 1, coding->produced, tty->output);
932 if (ferror (tty->output))
933 clearerr (tty->output);
934 if (tty->termscript)
935 fwrite (conversion_buffer, 1, coding->produced, tty->termscript);
936 unblock_input ();
937 }
938
939 OUTPUT1_IF (tty, tty->TS_pad_inserted_char);
940 if (start)
941 {
942 turn_off_face (f, glyph->face_id);
943 tty_turn_off_highlight (tty);
944 }
945 }
946
947 cmcheckmagic (tty);
948 }
949
950 /* An implementation of delete_glyphs for termcap frames. */
951
952 static void
953 tty_delete_glyphs (struct frame *f, int n)
954 {
955 char *buf;
956 register int i;
957
958 struct tty_display_info *tty = FRAME_TTY (f);
959
960 if (tty->delete_in_insert_mode)
961 {
962 tty_turn_on_insert (tty);
963 }
964 else
965 {
966 tty_turn_off_insert (tty);
967 OUTPUT_IF (tty, tty->TS_delete_mode);
968 }
969
970 if (tty->TS_del_multi_chars)
971 {
972 buf = tparam (tty->TS_del_multi_chars, 0, 0, n, 0, 0, 0);
973 OUTPUT1 (tty, buf);
974 xfree (buf);
975 }
976 else
977 for (i = 0; i < n; i++)
978 OUTPUT1 (tty, tty->TS_del_char);
979 if (!tty->delete_in_insert_mode)
980 OUTPUT_IF (tty, tty->TS_end_delete_mode);
981 }
982 \f
983 /* An implementation of ins_del_lines for termcap frames. */
984
985 static void
986 tty_ins_del_lines (struct frame *f, int vpos, int n)
987 {
988 struct tty_display_info *tty = FRAME_TTY (f);
989 const char *multi =
990 n > 0 ? tty->TS_ins_multi_lines : tty->TS_del_multi_lines;
991 const char *single = n > 0 ? tty->TS_ins_line : tty->TS_del_line;
992 const char *scroll = n > 0 ? tty->TS_rev_scroll : tty->TS_fwd_scroll;
993
994 int i = eabs (n);
995 char *buf;
996
997 /* If the lines below the insertion are being pushed
998 into the end of the window, this is the same as clearing;
999 and we know the lines are already clear, since the matching
1000 deletion has already been done. So can ignore this. */
1001 /* If the lines below the deletion are blank lines coming
1002 out of the end of the window, don't bother,
1003 as there will be a matching inslines later that will flush them. */
1004 if (FRAME_SCROLL_REGION_OK (f)
1005 && vpos + i >= tty->specified_window)
1006 return;
1007 if (!FRAME_MEMORY_BELOW_FRAME (f)
1008 && vpos + i >= FRAME_TOTAL_LINES (f))
1009 return;
1010
1011 if (multi)
1012 {
1013 raw_cursor_to (f, vpos, 0);
1014 tty_background_highlight (tty);
1015 buf = tparam (multi, 0, 0, i, 0, 0, 0);
1016 OUTPUT (tty, buf);
1017 xfree (buf);
1018 }
1019 else if (single)
1020 {
1021 raw_cursor_to (f, vpos, 0);
1022 tty_background_highlight (tty);
1023 while (--i >= 0)
1024 OUTPUT (tty, single);
1025 if (tty->TF_teleray)
1026 curX (tty) = 0;
1027 }
1028 else
1029 {
1030 tty_set_scroll_region (f, vpos, tty->specified_window);
1031 if (n < 0)
1032 raw_cursor_to (f, tty->specified_window - 1, 0);
1033 else
1034 raw_cursor_to (f, vpos, 0);
1035 tty_background_highlight (tty);
1036 while (--i >= 0)
1037 OUTPUTL (tty, scroll, tty->specified_window - vpos);
1038 tty_set_scroll_region (f, 0, tty->specified_window);
1039 }
1040
1041 if (!FRAME_SCROLL_REGION_OK (f)
1042 && FRAME_MEMORY_BELOW_FRAME (f)
1043 && n < 0)
1044 {
1045 cursor_to (f, FRAME_TOTAL_LINES (f) + n, 0);
1046 clear_to_end (f);
1047 }
1048 }
1049 \f
1050 /* Compute cost of sending "str", in characters,
1051 not counting any line-dependent padding. */
1052
1053 int
1054 string_cost (const char *str)
1055 {
1056 cost = 0;
1057 if (str)
1058 tputs (str, 0, evalcost);
1059 return cost;
1060 }
1061
1062 /* Compute cost of sending "str", in characters,
1063 counting any line-dependent padding at one line. */
1064
1065 static int
1066 string_cost_one_line (const char *str)
1067 {
1068 cost = 0;
1069 if (str)
1070 tputs (str, 1, evalcost);
1071 return cost;
1072 }
1073
1074 /* Compute per line amount of line-dependent padding,
1075 in tenths of characters. */
1076
1077 int
1078 per_line_cost (const char *str)
1079 {
1080 cost = 0;
1081 if (str)
1082 tputs (str, 0, evalcost);
1083 cost = - cost;
1084 if (str)
1085 tputs (str, 10, evalcost);
1086 return cost;
1087 }
1088
1089 /* char_ins_del_cost[n] is cost of inserting N characters.
1090 char_ins_del_cost[-n] is cost of deleting N characters.
1091 The length of this vector is based on max_frame_cols. */
1092
1093 int *char_ins_del_vector;
1094
1095 #define char_ins_del_cost(f) (&char_ins_del_vector[FRAME_COLS ((f))])
1096
1097 /* ARGSUSED */
1098 static void
1099 calculate_ins_del_char_costs (struct frame *f)
1100 {
1101 struct tty_display_info *tty = FRAME_TTY (f);
1102 int ins_startup_cost, del_startup_cost;
1103 int ins_cost_per_char, del_cost_per_char;
1104 register int i;
1105 register int *p;
1106
1107 if (tty->TS_ins_multi_chars)
1108 {
1109 ins_cost_per_char = 0;
1110 ins_startup_cost = string_cost_one_line (tty->TS_ins_multi_chars);
1111 }
1112 else if (tty->TS_ins_char || tty->TS_pad_inserted_char
1113 || (tty->TS_insert_mode && tty->TS_end_insert_mode))
1114 {
1115 ins_startup_cost = (30 * (string_cost (tty->TS_insert_mode)
1116 + string_cost (tty->TS_end_insert_mode))) / 100;
1117 ins_cost_per_char = (string_cost_one_line (tty->TS_ins_char)
1118 + string_cost_one_line (tty->TS_pad_inserted_char));
1119 }
1120 else
1121 {
1122 ins_startup_cost = 9999;
1123 ins_cost_per_char = 0;
1124 }
1125
1126 if (tty->TS_del_multi_chars)
1127 {
1128 del_cost_per_char = 0;
1129 del_startup_cost = string_cost_one_line (tty->TS_del_multi_chars);
1130 }
1131 else if (tty->TS_del_char)
1132 {
1133 del_startup_cost = (string_cost (tty->TS_delete_mode)
1134 + string_cost (tty->TS_end_delete_mode));
1135 if (tty->delete_in_insert_mode)
1136 del_startup_cost /= 2;
1137 del_cost_per_char = string_cost_one_line (tty->TS_del_char);
1138 }
1139 else
1140 {
1141 del_startup_cost = 9999;
1142 del_cost_per_char = 0;
1143 }
1144
1145 /* Delete costs are at negative offsets */
1146 p = &char_ins_del_cost (f)[0];
1147 for (i = FRAME_COLS (f); --i >= 0;)
1148 *--p = (del_startup_cost += del_cost_per_char);
1149
1150 /* Doing nothing is free */
1151 p = &char_ins_del_cost (f)[0];
1152 *p++ = 0;
1153
1154 /* Insert costs are at positive offsets */
1155 for (i = FRAME_COLS (f); --i >= 0;)
1156 *p++ = (ins_startup_cost += ins_cost_per_char);
1157 }
1158
1159 void
1160 calculate_costs (struct frame *frame)
1161 {
1162 FRAME_COST_BAUD_RATE (frame) = baud_rate;
1163
1164 if (FRAME_TERMCAP_P (frame))
1165 {
1166 struct tty_display_info *tty = FRAME_TTY (frame);
1167 register const char *f = (tty->TS_set_scroll_region
1168 ? tty->TS_set_scroll_region
1169 : tty->TS_set_scroll_region_1);
1170
1171 FRAME_SCROLL_REGION_COST (frame) = string_cost (f);
1172
1173 tty->costs_set = 1;
1174
1175 /* These variables are only used for terminal stuff. They are
1176 allocated once for the terminal frame of X-windows emacs, but not
1177 used afterwards.
1178
1179 char_ins_del_vector (i.e., char_ins_del_cost) isn't used because
1180 X turns off char_ins_del_ok. */
1181
1182 max_frame_cols = max (max_frame_cols, FRAME_COLS (frame));
1183 if ((min (PTRDIFF_MAX, SIZE_MAX) / sizeof (int) - 1) / 2
1184 < max_frame_cols)
1185 memory_full (SIZE_MAX);
1186
1187 char_ins_del_vector =
1188 xrealloc (char_ins_del_vector,
1189 (sizeof (int) + 2 * sizeof (int) * max_frame_cols));
1190
1191 memset (char_ins_del_vector, 0,
1192 (sizeof (int) + 2 * sizeof (int) * max_frame_cols));
1193
1194
1195 if (f && (!tty->TS_ins_line && !tty->TS_del_line))
1196 do_line_insertion_deletion_costs (frame,
1197 tty->TS_rev_scroll, tty->TS_ins_multi_lines,
1198 tty->TS_fwd_scroll, tty->TS_del_multi_lines,
1199 f, f, 1);
1200 else
1201 do_line_insertion_deletion_costs (frame,
1202 tty->TS_ins_line, tty->TS_ins_multi_lines,
1203 tty->TS_del_line, tty->TS_del_multi_lines,
1204 0, 0, 1);
1205
1206 calculate_ins_del_char_costs (frame);
1207
1208 /* Don't use TS_repeat if its padding is worse than sending the chars */
1209 if (tty->TS_repeat && per_line_cost (tty->TS_repeat) * baud_rate < 9000)
1210 tty->RPov = string_cost (tty->TS_repeat);
1211 else
1212 tty->RPov = FRAME_COLS (frame) * 2;
1213
1214 cmcostinit (FRAME_TTY (frame)); /* set up cursor motion costs */
1215 }
1216 }
1217 \f
1218 struct fkey_table {
1219 const char *cap, *name;
1220 };
1221
1222 /* Termcap capability names that correspond directly to X keysyms.
1223 Some of these (marked "terminfo") aren't supplied by old-style
1224 (Berkeley) termcap entries. They're listed in X keysym order;
1225 except we put the keypad keys first, so that if they clash with
1226 other keys (as on the IBM PC keyboard) they get overridden.
1227 */
1228
1229 static const struct fkey_table keys[] =
1230 {
1231 {"kh", "home"}, /* termcap */
1232 {"kl", "left"}, /* termcap */
1233 {"ku", "up"}, /* termcap */
1234 {"kr", "right"}, /* termcap */
1235 {"kd", "down"}, /* termcap */
1236 {"%8", "prior"}, /* terminfo */
1237 {"%5", "next"}, /* terminfo */
1238 {"@7", "end"}, /* terminfo */
1239 {"@1", "begin"}, /* terminfo */
1240 {"*6", "select"}, /* terminfo */
1241 {"%9", "print"}, /* terminfo */
1242 {"@4", "execute"}, /* terminfo --- actually the `command' key */
1243 /*
1244 * "insert" --- see below
1245 */
1246 {"&8", "undo"}, /* terminfo */
1247 {"%0", "redo"}, /* terminfo */
1248 {"%7", "menu"}, /* terminfo --- actually the `options' key */
1249 {"@0", "find"}, /* terminfo */
1250 {"@2", "cancel"}, /* terminfo */
1251 {"%1", "help"}, /* terminfo */
1252 /*
1253 * "break" goes here, but can't be reliably intercepted with termcap
1254 */
1255 {"&4", "reset"}, /* terminfo --- actually `restart' */
1256 /*
1257 * "system" and "user" --- no termcaps
1258 */
1259 {"kE", "clearline"}, /* terminfo */
1260 {"kA", "insertline"}, /* terminfo */
1261 {"kL", "deleteline"}, /* terminfo */
1262 {"kI", "insertchar"}, /* terminfo */
1263 {"kD", "deletechar"}, /* terminfo */
1264 {"kB", "backtab"}, /* terminfo */
1265 /*
1266 * "kp_backtab", "kp-space", "kp-tab" --- no termcaps
1267 */
1268 {"@8", "kp-enter"}, /* terminfo */
1269 /*
1270 * "kp-f1", "kp-f2", "kp-f3" "kp-f4",
1271 * "kp-multiply", "kp-add", "kp-separator",
1272 * "kp-subtract", "kp-decimal", "kp-divide", "kp-0";
1273 * --- no termcaps for any of these.
1274 */
1275 {"K4", "kp-1"}, /* terminfo */
1276 /*
1277 * "kp-2" --- no termcap
1278 */
1279 {"K5", "kp-3"}, /* terminfo */
1280 /*
1281 * "kp-4" --- no termcap
1282 */
1283 {"K2", "kp-5"}, /* terminfo */
1284 /*
1285 * "kp-6" --- no termcap
1286 */
1287 {"K1", "kp-7"}, /* terminfo */
1288 /*
1289 * "kp-8" --- no termcap
1290 */
1291 {"K3", "kp-9"}, /* terminfo */
1292 /*
1293 * "kp-equal" --- no termcap
1294 */
1295 {"k1", "f1"},
1296 {"k2", "f2"},
1297 {"k3", "f3"},
1298 {"k4", "f4"},
1299 {"k5", "f5"},
1300 {"k6", "f6"},
1301 {"k7", "f7"},
1302 {"k8", "f8"},
1303 {"k9", "f9"},
1304
1305 {"&0", "S-cancel"}, /*shifted cancel key*/
1306 {"&9", "S-begin"}, /*shifted begin key*/
1307 {"*0", "S-find"}, /*shifted find key*/
1308 {"*1", "S-execute"}, /*shifted execute? actually shifted command key*/
1309 {"*4", "S-delete"}, /*shifted delete-character key*/
1310 {"*7", "S-end"}, /*shifted end key*/
1311 {"*8", "S-clearline"}, /*shifted clear-to end-of-line key*/
1312 {"#1", "S-help"}, /*shifted help key*/
1313 {"#2", "S-home"}, /*shifted home key*/
1314 {"#3", "S-insert"}, /*shifted insert-character key*/
1315 {"#4", "S-left"}, /*shifted left-arrow key*/
1316 {"%d", "S-menu"}, /*shifted menu? actually shifted options key*/
1317 {"%c", "S-next"}, /*shifted next key*/
1318 {"%e", "S-prior"}, /*shifted previous key*/
1319 {"%f", "S-print"}, /*shifted print key*/
1320 {"%g", "S-redo"}, /*shifted redo key*/
1321 {"%i", "S-right"}, /*shifted right-arrow key*/
1322 {"!3", "S-undo"} /*shifted undo key*/
1323 };
1324
1325 #ifndef DOS_NT
1326 static char **term_get_fkeys_address;
1327 static KBOARD *term_get_fkeys_kboard;
1328 static Lisp_Object term_get_fkeys_1 (void);
1329
1330 /* Find the escape codes sent by the function keys for Vinput_decode_map.
1331 This function scans the termcap function key sequence entries, and
1332 adds entries to Vinput_decode_map for each function key it finds. */
1333
1334 static void
1335 term_get_fkeys (char **address, KBOARD *kboard)
1336 {
1337 /* We run the body of the function (term_get_fkeys_1) and ignore all Lisp
1338 errors during the call. The only errors should be from Fdefine_key
1339 when given a key sequence containing an invalid prefix key. If the
1340 termcap defines function keys which use a prefix that is already bound
1341 to a command by the default bindings, we should silently ignore that
1342 function key specification, rather than giving the user an error and
1343 refusing to run at all on such a terminal. */
1344
1345 term_get_fkeys_address = address;
1346 term_get_fkeys_kboard = kboard;
1347 internal_condition_case (term_get_fkeys_1, Qerror, Fidentity);
1348 }
1349
1350 static Lisp_Object
1351 term_get_fkeys_1 (void)
1352 {
1353 int i;
1354
1355 char **address = term_get_fkeys_address;
1356 KBOARD *kboard = term_get_fkeys_kboard;
1357
1358 /* This can happen if CANNOT_DUMP or with strange options. */
1359 if (!KEYMAPP (KVAR (kboard, Vinput_decode_map)))
1360 kset_input_decode_map (kboard, Fmake_sparse_keymap (Qnil));
1361
1362 for (i = 0; i < ARRAYELTS (keys); i++)
1363 {
1364 char *sequence = tgetstr (keys[i].cap, address);
1365 if (sequence)
1366 Fdefine_key (KVAR (kboard, Vinput_decode_map), build_string (sequence),
1367 Fmake_vector (make_number (1),
1368 intern (keys[i].name)));
1369 }
1370
1371 /* The uses of the "k0" capability are inconsistent; sometimes it
1372 describes F10, whereas othertimes it describes F0 and "k;" describes F10.
1373 We will attempt to politely accommodate both systems by testing for
1374 "k;", and if it is present, assuming that "k0" denotes F0, otherwise F10.
1375 */
1376 {
1377 const char *k_semi = tgetstr ("k;", address);
1378 const char *k0 = tgetstr ("k0", address);
1379 const char *k0_name = "f10";
1380
1381 if (k_semi)
1382 {
1383 if (k0)
1384 /* Define f0 first, so that f10 takes precedence in case the
1385 key sequences happens to be the same. */
1386 Fdefine_key (KVAR (kboard, Vinput_decode_map), build_string (k0),
1387 Fmake_vector (make_number (1), intern ("f0")));
1388 Fdefine_key (KVAR (kboard, Vinput_decode_map), build_string (k_semi),
1389 Fmake_vector (make_number (1), intern ("f10")));
1390 }
1391 else if (k0)
1392 Fdefine_key (KVAR (kboard, Vinput_decode_map), build_string (k0),
1393 Fmake_vector (make_number (1), intern (k0_name)));
1394 }
1395
1396 /* Set up cookies for numbered function keys above f10. */
1397 {
1398 char fcap[3], fkey[4];
1399
1400 fcap[0] = 'F'; fcap[2] = '\0';
1401 for (i = 11; i < 64; i++)
1402 {
1403 if (i <= 19)
1404 fcap[1] = '1' + i - 11;
1405 else if (i <= 45)
1406 fcap[1] = 'A' + i - 20;
1407 else
1408 fcap[1] = 'a' + i - 46;
1409
1410 {
1411 char *sequence = tgetstr (fcap, address);
1412 if (sequence)
1413 {
1414 sprintf (fkey, "f%d", i);
1415 Fdefine_key (KVAR (kboard, Vinput_decode_map), build_string (sequence),
1416 Fmake_vector (make_number (1),
1417 intern (fkey)));
1418 }
1419 }
1420 }
1421 }
1422
1423 /*
1424 * Various mappings to try and get a better fit.
1425 */
1426 {
1427 #define CONDITIONAL_REASSIGN(cap1, cap2, sym) \
1428 if (!tgetstr (cap1, address)) \
1429 { \
1430 char *sequence = tgetstr (cap2, address); \
1431 if (sequence) \
1432 Fdefine_key (KVAR (kboard, Vinput_decode_map), build_string (sequence), \
1433 Fmake_vector (make_number (1), \
1434 intern (sym))); \
1435 }
1436
1437 /* if there's no key_next keycap, map key_npage to `next' keysym */
1438 CONDITIONAL_REASSIGN ("%5", "kN", "next");
1439 /* if there's no key_prev keycap, map key_ppage to `previous' keysym */
1440 CONDITIONAL_REASSIGN ("%8", "kP", "prior");
1441 /* if there's no key_dc keycap, map key_ic to `insert' keysym */
1442 CONDITIONAL_REASSIGN ("kD", "kI", "insert");
1443 /* if there's no key_end keycap, map key_ll to 'end' keysym */
1444 CONDITIONAL_REASSIGN ("@7", "kH", "end");
1445 #undef CONDITIONAL_REASSIGN
1446 }
1447
1448 return Qnil;
1449 }
1450 #endif /* not DOS_NT */
1451
1452 \f
1453 /***********************************************************************
1454 Character Display Information
1455 ***********************************************************************/
1456 static void append_glyph (struct it *);
1457 static void append_composite_glyph (struct it *);
1458 static void produce_composite_glyph (struct it *);
1459 static void append_glyphless_glyph (struct it *, int, const char *);
1460 static void produce_glyphless_glyph (struct it *, Lisp_Object);
1461
1462 /* Append glyphs to IT's glyph_row. Called from produce_glyphs for
1463 terminal frames if IT->glyph_row != NULL. IT->char_to_display is
1464 the character for which to produce glyphs; IT->face_id contains the
1465 character's face. Padding glyphs are appended if IT->c has a
1466 IT->pixel_width > 1. */
1467
1468 static void
1469 append_glyph (struct it *it)
1470 {
1471 struct glyph *glyph, *end;
1472 int i;
1473
1474 eassert (it->glyph_row);
1475 glyph = (it->glyph_row->glyphs[it->area]
1476 + it->glyph_row->used[it->area]);
1477 end = it->glyph_row->glyphs[1 + it->area];
1478
1479 /* If the glyph row is reversed, we need to prepend the glyph rather
1480 than append it. */
1481 if (it->glyph_row->reversed_p && it->area == TEXT_AREA)
1482 {
1483 struct glyph *g;
1484 int move_by = it->pixel_width;
1485
1486 /* Make room for the new glyphs. */
1487 if (move_by > end - glyph) /* don't overstep end of this area */
1488 move_by = end - glyph;
1489 for (g = glyph - 1; g >= it->glyph_row->glyphs[it->area]; g--)
1490 g[move_by] = *g;
1491 glyph = it->glyph_row->glyphs[it->area];
1492 end = glyph + move_by;
1493 }
1494
1495 /* BIDI Note: we put the glyphs of a "multi-pixel" character left to
1496 right, even in the REVERSED_P case, since (a) all of its u.ch are
1497 identical, and (b) the PADDING_P flag needs to be set for the
1498 leftmost one, because we write to the terminal left-to-right. */
1499 for (i = 0;
1500 i < it->pixel_width && glyph < end;
1501 ++i)
1502 {
1503 glyph->type = CHAR_GLYPH;
1504 glyph->pixel_width = 1;
1505 glyph->u.ch = it->char_to_display;
1506 glyph->face_id = it->face_id;
1507 glyph->padding_p = i > 0;
1508 glyph->charpos = CHARPOS (it->position);
1509 glyph->object = it->object;
1510 if (it->bidi_p)
1511 {
1512 glyph->resolved_level = it->bidi_it.resolved_level;
1513 eassert ((it->bidi_it.type & 7) == it->bidi_it.type);
1514 glyph->bidi_type = it->bidi_it.type;
1515 }
1516 else
1517 {
1518 glyph->resolved_level = 0;
1519 glyph->bidi_type = UNKNOWN_BT;
1520 }
1521
1522 ++it->glyph_row->used[it->area];
1523 ++glyph;
1524 }
1525 }
1526
1527 /* For external use. */
1528 void
1529 tty_append_glyph (struct it *it)
1530 {
1531 append_glyph (it);
1532 }
1533
1534
1535 /* Produce glyphs for the display element described by IT. *IT
1536 specifies what we want to produce a glyph for (character, image, ...),
1537 and where in the glyph matrix we currently are (glyph row and hpos).
1538 produce_glyphs fills in output fields of *IT with information such as the
1539 pixel width and height of a character, and maybe output actual glyphs at
1540 the same time if IT->glyph_row is non-null. For an overview, see
1541 the explanation in dispextern.h, before the definition of the
1542 display_element_type enumeration.
1543
1544 produce_glyphs also stores the result of glyph width, ascent
1545 etc. computations in *IT.
1546
1547 IT->glyph_row may be null, in which case produce_glyphs does not
1548 actually fill in the glyphs. This is used in the move_* functions
1549 in xdisp.c for text width and height computations.
1550
1551 Callers usually don't call produce_glyphs directly;
1552 instead they use the macro PRODUCE_GLYPHS. */
1553
1554 void
1555 produce_glyphs (struct it *it)
1556 {
1557 /* If a hook is installed, let it do the work. */
1558
1559 /* Nothing but characters are supported on terminal frames. */
1560 eassert (it->what == IT_CHARACTER
1561 || it->what == IT_COMPOSITION
1562 || it->what == IT_STRETCH
1563 || it->what == IT_GLYPHLESS);
1564
1565 if (it->what == IT_STRETCH)
1566 {
1567 produce_stretch_glyph (it);
1568 goto done;
1569 }
1570
1571 if (it->what == IT_COMPOSITION)
1572 {
1573 produce_composite_glyph (it);
1574 goto done;
1575 }
1576
1577 if (it->what == IT_GLYPHLESS)
1578 {
1579 produce_glyphless_glyph (it, Qnil);
1580 goto done;
1581 }
1582
1583 if (it->char_to_display >= 040 && it->char_to_display < 0177)
1584 {
1585 it->pixel_width = it->nglyphs = 1;
1586 if (it->glyph_row)
1587 append_glyph (it);
1588 }
1589 else if (it->char_to_display == '\n')
1590 it->pixel_width = it->nglyphs = 0;
1591 else if (it->char_to_display == '\t')
1592 {
1593 int absolute_x = (it->current_x
1594 + it->continuation_lines_width);
1595 int next_tab_x
1596 = (((1 + absolute_x + it->tab_width - 1)
1597 / it->tab_width)
1598 * it->tab_width);
1599 int nspaces;
1600
1601 /* If part of the TAB has been displayed on the previous line
1602 which is continued now, continuation_lines_width will have
1603 been incremented already by the part that fitted on the
1604 continued line. So, we will get the right number of spaces
1605 here. */
1606 nspaces = next_tab_x - absolute_x;
1607
1608 if (it->glyph_row)
1609 {
1610 int n = nspaces;
1611
1612 it->char_to_display = ' ';
1613 it->pixel_width = it->len = 1;
1614
1615 while (n--)
1616 append_glyph (it);
1617 }
1618
1619 it->pixel_width = nspaces;
1620 it->nglyphs = nspaces;
1621 }
1622 else if (CHAR_BYTE8_P (it->char_to_display))
1623 {
1624 /* Coming here means that we must send the raw 8-bit byte as is
1625 to the terminal. Although there's no way to know how many
1626 columns it occupies on a screen, it is a good assumption that
1627 a single byte code has 1-column width. */
1628 it->pixel_width = it->nglyphs = 1;
1629 if (it->glyph_row)
1630 append_glyph (it);
1631 }
1632 else
1633 {
1634 Lisp_Object charset_list = FRAME_TERMINAL (it->f)->charset_list;
1635
1636 if (char_charset (it->char_to_display, charset_list, NULL))
1637 {
1638 it->pixel_width = CHAR_WIDTH (it->char_to_display);
1639 it->nglyphs = it->pixel_width;
1640 if (it->glyph_row)
1641 append_glyph (it);
1642 }
1643 else
1644 {
1645 Lisp_Object acronym = lookup_glyphless_char_display (-1, it);
1646
1647 eassert (it->what == IT_GLYPHLESS);
1648 produce_glyphless_glyph (it, acronym);
1649 }
1650 }
1651
1652 done:
1653 /* Advance current_x by the pixel width as a convenience for
1654 the caller. */
1655 if (it->area == TEXT_AREA)
1656 it->current_x += it->pixel_width;
1657 it->ascent = it->max_ascent = it->phys_ascent = it->max_phys_ascent = 0;
1658 it->descent = it->max_descent = it->phys_descent = it->max_phys_descent = 1;
1659 }
1660
1661 /* Append glyphs to IT's glyph_row for the composition IT->cmp_id.
1662 Called from produce_composite_glyph for terminal frames if
1663 IT->glyph_row != NULL. IT->face_id contains the character's
1664 face. */
1665
1666 static void
1667 append_composite_glyph (struct it *it)
1668 {
1669 struct glyph *glyph;
1670
1671 eassert (it->glyph_row);
1672 glyph = it->glyph_row->glyphs[it->area] + it->glyph_row->used[it->area];
1673 if (glyph < it->glyph_row->glyphs[1 + it->area])
1674 {
1675 /* If the glyph row is reversed, we need to prepend the glyph
1676 rather than append it. */
1677 if (it->glyph_row->reversed_p && it->area == TEXT_AREA)
1678 {
1679 struct glyph *g;
1680
1681 /* Make room for the new glyph. */
1682 for (g = glyph - 1; g >= it->glyph_row->glyphs[it->area]; g--)
1683 g[1] = *g;
1684 glyph = it->glyph_row->glyphs[it->area];
1685 }
1686 glyph->type = COMPOSITE_GLYPH;
1687 glyph->pixel_width = it->pixel_width;
1688 glyph->u.cmp.id = it->cmp_it.id;
1689 if (it->cmp_it.ch < 0)
1690 {
1691 glyph->u.cmp.automatic = 0;
1692 glyph->u.cmp.id = it->cmp_it.id;
1693 }
1694 else
1695 {
1696 glyph->u.cmp.automatic = 1;
1697 glyph->u.cmp.id = it->cmp_it.id;
1698 glyph->slice.cmp.from = it->cmp_it.from;
1699 glyph->slice.cmp.to = it->cmp_it.to - 1;
1700 }
1701
1702 glyph->face_id = it->face_id;
1703 glyph->padding_p = 0;
1704 glyph->charpos = CHARPOS (it->position);
1705 glyph->object = it->object;
1706 if (it->bidi_p)
1707 {
1708 glyph->resolved_level = it->bidi_it.resolved_level;
1709 eassert ((it->bidi_it.type & 7) == it->bidi_it.type);
1710 glyph->bidi_type = it->bidi_it.type;
1711 }
1712 else
1713 {
1714 glyph->resolved_level = 0;
1715 glyph->bidi_type = UNKNOWN_BT;
1716 }
1717
1718 ++it->glyph_row->used[it->area];
1719 ++glyph;
1720 }
1721 }
1722
1723
1724 /* Produce a composite glyph for iterator IT. IT->cmp_id is the ID of
1725 the composition. We simply produces components of the composition
1726 assuming that the terminal has a capability to layout/render it
1727 correctly. */
1728
1729 static void
1730 produce_composite_glyph (struct it *it)
1731 {
1732 if (it->cmp_it.ch < 0)
1733 {
1734 struct composition *cmp = composition_table[it->cmp_it.id];
1735
1736 it->pixel_width = cmp->width;
1737 }
1738 else
1739 {
1740 Lisp_Object gstring = composition_gstring_from_id (it->cmp_it.id);
1741
1742 it->pixel_width = composition_gstring_width (gstring, it->cmp_it.from,
1743 it->cmp_it.to, NULL);
1744 }
1745 it->nglyphs = 1;
1746 if (it->glyph_row)
1747 append_composite_glyph (it);
1748 }
1749
1750
1751 /* Append a glyph for a glyphless character to IT->glyph_row. FACE_ID
1752 is a face ID to be used for the glyph. What is actually appended
1753 are glyphs of type CHAR_GLYPH whose characters are in STR (which
1754 comes from it->nglyphs bytes). */
1755
1756 static void
1757 append_glyphless_glyph (struct it *it, int face_id, const char *str)
1758 {
1759 struct glyph *glyph, *end;
1760 int i;
1761
1762 eassert (it->glyph_row);
1763 glyph = it->glyph_row->glyphs[it->area] + it->glyph_row->used[it->area];
1764 end = it->glyph_row->glyphs[1 + it->area];
1765
1766 /* If the glyph row is reversed, we need to prepend the glyph rather
1767 than append it. */
1768 if (it->glyph_row->reversed_p && it->area == TEXT_AREA)
1769 {
1770 struct glyph *g;
1771 int move_by = it->pixel_width;
1772
1773 /* Make room for the new glyphs. */
1774 if (move_by > end - glyph) /* don't overstep end of this area */
1775 move_by = end - glyph;
1776 for (g = glyph - 1; g >= it->glyph_row->glyphs[it->area]; g--)
1777 g[move_by] = *g;
1778 glyph = it->glyph_row->glyphs[it->area];
1779 end = glyph + move_by;
1780 }
1781
1782 if (glyph >= end)
1783 return;
1784 glyph->type = CHAR_GLYPH;
1785 glyph->pixel_width = 1;
1786 glyph->face_id = face_id;
1787 glyph->padding_p = 0;
1788 glyph->charpos = CHARPOS (it->position);
1789 glyph->object = it->object;
1790 if (it->bidi_p)
1791 {
1792 glyph->resolved_level = it->bidi_it.resolved_level;
1793 eassert ((it->bidi_it.type & 7) == it->bidi_it.type);
1794 glyph->bidi_type = it->bidi_it.type;
1795 }
1796 else
1797 {
1798 glyph->resolved_level = 0;
1799 glyph->bidi_type = UNKNOWN_BT;
1800 }
1801
1802 /* BIDI Note: we put the glyphs of characters left to right, even in
1803 the REVERSED_P case because we write to the terminal
1804 left-to-right. */
1805 for (i = 0; i < it->nglyphs && glyph < end; ++i)
1806 {
1807 if (i > 0)
1808 glyph[0] = glyph[-1];
1809 glyph->u.ch = str[i];
1810 ++it->glyph_row->used[it->area];
1811 ++glyph;
1812 }
1813 }
1814
1815 /* Produce glyphs for a glyphless character for iterator IT.
1816 IT->glyphless_method specifies which method to use for displaying
1817 the character. See the description of enum
1818 glyphless_display_method in dispextern.h for the details.
1819
1820 ACRONYM, if non-nil, is an acronym string for the character.
1821
1822 The glyphs actually produced are of type CHAR_GLYPH. */
1823
1824 static void
1825 produce_glyphless_glyph (struct it *it, Lisp_Object acronym)
1826 {
1827 int len, face_id = merge_glyphless_glyph_face (it);
1828 char buf[sizeof "\\x" + max (6, (sizeof it->c * CHAR_BIT + 3) / 4)];
1829 char const *str = " ";
1830
1831 if (it->glyphless_method == GLYPHLESS_DISPLAY_THIN_SPACE)
1832 {
1833 /* As there's no way to produce a thin space, we produce a space
1834 of canonical width. */
1835 len = 1;
1836 }
1837 else if (it->glyphless_method == GLYPHLESS_DISPLAY_EMPTY_BOX)
1838 {
1839 len = CHAR_WIDTH (it->c);
1840 if (len == 0)
1841 len = 1;
1842 else if (len > 4)
1843 len = 4;
1844 len = sprintf (buf, "[%.*s]", len, str);
1845 str = buf;
1846 }
1847 else
1848 {
1849 if (it->glyphless_method == GLYPHLESS_DISPLAY_ACRONYM)
1850 {
1851 if (! STRINGP (acronym) && CHAR_TABLE_P (Vglyphless_char_display))
1852 acronym = CHAR_TABLE_REF (Vglyphless_char_display, it->c);
1853 if (CONSP (acronym))
1854 acronym = XCDR (acronym);
1855 buf[0] = '[';
1856 str = STRINGP (acronym) ? SSDATA (acronym) : "";
1857 for (len = 0; len < 6 && str[len] && ASCII_CHAR_P (str[len]); len++)
1858 buf[1 + len] = str[len];
1859 buf[1 + len] = ']';
1860 len += 2;
1861 }
1862 else
1863 {
1864 eassert (it->glyphless_method == GLYPHLESS_DISPLAY_HEX_CODE);
1865 len = (it->c < 0x10000 ? sprintf (buf, "\\u%04X", it->c)
1866 : it->c <= MAX_UNICODE_CHAR ? sprintf (buf, "\\U%06X", it->c)
1867 : sprintf (buf, "\\x%06X", it->c));
1868 }
1869 str = buf;
1870 }
1871
1872 it->pixel_width = len;
1873 it->nglyphs = len;
1874 if (it->glyph_row)
1875 append_glyphless_glyph (it, face_id, str);
1876 }
1877
1878 \f
1879 /***********************************************************************
1880 Faces
1881 ***********************************************************************/
1882
1883 /* Value is non-zero if attribute ATTR may be used. ATTR should be
1884 one of the enumerators from enum no_color_bit, or a bit set built
1885 from them. Some display attributes may not be used together with
1886 color; the termcap capability `NC' specifies which ones. */
1887
1888 #define MAY_USE_WITH_COLORS_P(tty, ATTR) \
1889 (tty->TN_max_colors > 0 \
1890 ? (tty->TN_no_color_video & (ATTR)) == 0 \
1891 : 1)
1892
1893 /* Turn appearances of face FACE_ID on tty frame F on.
1894 FACE_ID is a realized face ID number, in the face cache. */
1895
1896 static void
1897 turn_on_face (struct frame *f, int face_id)
1898 {
1899 struct face *face = FACE_FROM_ID (f, face_id);
1900 unsigned long fg = face->foreground;
1901 unsigned long bg = face->background;
1902 struct tty_display_info *tty = FRAME_TTY (f);
1903
1904 /* Use reverse video if the face specifies that.
1905 Do this first because TS_end_standout_mode may be the same
1906 as TS_exit_attribute_mode, which turns all appearances off. */
1907 if (MAY_USE_WITH_COLORS_P (tty, NC_REVERSE)
1908 && (inverse_video
1909 ? fg == FACE_TTY_DEFAULT_FG_COLOR || bg == FACE_TTY_DEFAULT_BG_COLOR
1910 : fg == FACE_TTY_DEFAULT_BG_COLOR || bg == FACE_TTY_DEFAULT_FG_COLOR))
1911 tty_toggle_highlight (tty);
1912
1913 if (face->tty_bold_p && MAY_USE_WITH_COLORS_P (tty, NC_BOLD))
1914 OUTPUT1_IF (tty, tty->TS_enter_bold_mode);
1915
1916 if (face->tty_italic_p && MAY_USE_WITH_COLORS_P (tty, NC_ITALIC))
1917 {
1918 if (tty->TS_enter_italic_mode)
1919 OUTPUT1 (tty, tty->TS_enter_italic_mode);
1920 else
1921 /* Italics mode is unavailable on many terminals. In that
1922 case, map slant to dimmed text; we want italic text to
1923 appear different and dimming is not otherwise used. */
1924 OUTPUT1 (tty, tty->TS_enter_dim_mode);
1925 }
1926
1927 if (face->tty_underline_p && MAY_USE_WITH_COLORS_P (tty, NC_UNDERLINE))
1928 OUTPUT1_IF (tty, tty->TS_enter_underline_mode);
1929
1930 if (tty->TN_max_colors > 0)
1931 {
1932 const char *ts;
1933 char *p;
1934
1935 ts = tty->standout_mode ? tty->TS_set_background : tty->TS_set_foreground;
1936 if (face_tty_specified_color (fg) && ts)
1937 {
1938 p = tparam (ts, NULL, 0, fg, 0, 0, 0);
1939 OUTPUT (tty, p);
1940 xfree (p);
1941 }
1942
1943 ts = tty->standout_mode ? tty->TS_set_foreground : tty->TS_set_background;
1944 if (face_tty_specified_color (bg) && ts)
1945 {
1946 p = tparam (ts, NULL, 0, bg, 0, 0, 0);
1947 OUTPUT (tty, p);
1948 xfree (p);
1949 }
1950 }
1951 }
1952
1953
1954 /* Turn off appearances of face FACE_ID on tty frame F. */
1955
1956 static void
1957 turn_off_face (struct frame *f, int face_id)
1958 {
1959 struct face *face = FACE_FROM_ID (f, face_id);
1960 struct tty_display_info *tty = FRAME_TTY (f);
1961
1962 eassert (face != NULL);
1963
1964 if (tty->TS_exit_attribute_mode)
1965 {
1966 /* Capability "me" will turn off appearance modes double-bright,
1967 half-bright, reverse-video, standout, underline. It may or
1968 may not turn off alt-char-mode. */
1969 if (face->tty_bold_p
1970 || face->tty_italic_p
1971 || face->tty_reverse_p
1972 || face->tty_underline_p)
1973 {
1974 OUTPUT1_IF (tty, tty->TS_exit_attribute_mode);
1975 if (strcmp (tty->TS_exit_attribute_mode, tty->TS_end_standout_mode) == 0)
1976 tty->standout_mode = 0;
1977 }
1978 }
1979 else
1980 {
1981 /* If we don't have "me" we can only have those appearances
1982 that have exit sequences defined. */
1983 if (face->tty_underline_p)
1984 OUTPUT_IF (tty, tty->TS_exit_underline_mode);
1985 }
1986
1987 /* Switch back to default colors. */
1988 if (tty->TN_max_colors > 0
1989 && ((face->foreground != FACE_TTY_DEFAULT_COLOR
1990 && face->foreground != FACE_TTY_DEFAULT_FG_COLOR)
1991 || (face->background != FACE_TTY_DEFAULT_COLOR
1992 && face->background != FACE_TTY_DEFAULT_BG_COLOR)))
1993 OUTPUT1_IF (tty, tty->TS_orig_pair);
1994 }
1995
1996
1997 /* Return true if the terminal on frame F supports all of the
1998 capabilities in CAPS simultaneously. */
1999
2000 bool
2001 tty_capable_p (struct tty_display_info *tty, unsigned int caps)
2002 {
2003 #define TTY_CAPABLE_P_TRY(tty, cap, TS, NC_bit) \
2004 if ((caps & (cap)) && (!(TS) || !MAY_USE_WITH_COLORS_P(tty, NC_bit))) \
2005 return 0;
2006
2007 TTY_CAPABLE_P_TRY (tty, TTY_CAP_INVERSE, tty->TS_standout_mode, NC_REVERSE);
2008 TTY_CAPABLE_P_TRY (tty, TTY_CAP_UNDERLINE, tty->TS_enter_underline_mode, NC_UNDERLINE);
2009 TTY_CAPABLE_P_TRY (tty, TTY_CAP_BOLD, tty->TS_enter_bold_mode, NC_BOLD);
2010 TTY_CAPABLE_P_TRY (tty, TTY_CAP_DIM, tty->TS_enter_dim_mode, NC_DIM);
2011 TTY_CAPABLE_P_TRY (tty, TTY_CAP_ITALIC, tty->TS_enter_italic_mode, NC_ITALIC);
2012
2013 /* We can do it! */
2014 return 1;
2015 }
2016
2017 /* Return non-zero if the terminal is capable to display colors. */
2018
2019 DEFUN ("tty-display-color-p", Ftty_display_color_p, Stty_display_color_p,
2020 0, 1, 0,
2021 doc: /* Return non-nil if the tty device TERMINAL can display colors.
2022
2023 TERMINAL can be a terminal object, a frame, or nil (meaning the
2024 selected frame's terminal). This function always returns nil if
2025 TERMINAL does not refer to a text terminal. */)
2026 (Lisp_Object terminal)
2027 {
2028 struct terminal *t = decode_tty_terminal (terminal);
2029
2030 return (t && t->display_info.tty->TN_max_colors > 0) ? Qt : Qnil;
2031 }
2032
2033 /* Return the number of supported colors. */
2034 DEFUN ("tty-display-color-cells", Ftty_display_color_cells,
2035 Stty_display_color_cells, 0, 1, 0,
2036 doc: /* Return the number of colors supported by the tty device TERMINAL.
2037
2038 TERMINAL can be a terminal object, a frame, or nil (meaning the
2039 selected frame's terminal). This function always returns 0 if
2040 TERMINAL does not refer to a text terminal. */)
2041 (Lisp_Object terminal)
2042 {
2043 struct terminal *t = decode_tty_terminal (terminal);
2044
2045 return make_number (t ? t->display_info.tty->TN_max_colors : 0);
2046 }
2047
2048 #ifndef DOS_NT
2049
2050 /* Declare here rather than in the function, as in the rest of Emacs,
2051 to work around an HPUX compiler bug (?). See
2052 http://lists.gnu.org/archive/html/emacs-devel/2007-08/msg00410.html */
2053 static int default_max_colors;
2054 static int default_max_pairs;
2055 static int default_no_color_video;
2056 static char *default_orig_pair;
2057 static char *default_set_foreground;
2058 static char *default_set_background;
2059
2060 /* Save or restore the default color-related capabilities of this
2061 terminal. */
2062 static void
2063 tty_default_color_capabilities (struct tty_display_info *tty, bool save)
2064 {
2065
2066 if (save)
2067 {
2068 dupstring (&default_orig_pair, tty->TS_orig_pair);
2069 dupstring (&default_set_foreground, tty->TS_set_foreground);
2070 dupstring (&default_set_background, tty->TS_set_background);
2071 default_max_colors = tty->TN_max_colors;
2072 default_max_pairs = tty->TN_max_pairs;
2073 default_no_color_video = tty->TN_no_color_video;
2074 }
2075 else
2076 {
2077 tty->TS_orig_pair = default_orig_pair;
2078 tty->TS_set_foreground = default_set_foreground;
2079 tty->TS_set_background = default_set_background;
2080 tty->TN_max_colors = default_max_colors;
2081 tty->TN_max_pairs = default_max_pairs;
2082 tty->TN_no_color_video = default_no_color_video;
2083 }
2084 }
2085
2086 /* Setup one of the standard tty color schemes according to MODE.
2087 MODE's value is generally the number of colors which we want to
2088 support; zero means set up for the default capabilities, the ones
2089 we saw at init_tty time; -1 means turn off color support. */
2090 static void
2091 tty_setup_colors (struct tty_display_info *tty, int mode)
2092 {
2093 /* Canonicalize all negative values of MODE. */
2094 if (mode < -1)
2095 mode = -1;
2096
2097 switch (mode)
2098 {
2099 case -1: /* no colors at all */
2100 tty->TN_max_colors = 0;
2101 tty->TN_max_pairs = 0;
2102 tty->TN_no_color_video = 0;
2103 tty->TS_set_foreground = tty->TS_set_background = tty->TS_orig_pair = NULL;
2104 break;
2105 case 0: /* default colors, if any */
2106 default:
2107 tty_default_color_capabilities (tty, 0);
2108 break;
2109 case 8: /* 8 standard ANSI colors */
2110 tty->TS_orig_pair = "\033[0m";
2111 #ifdef TERMINFO
2112 tty->TS_set_foreground = "\033[3%p1%dm";
2113 tty->TS_set_background = "\033[4%p1%dm";
2114 #else
2115 tty->TS_set_foreground = "\033[3%dm";
2116 tty->TS_set_background = "\033[4%dm";
2117 #endif
2118 tty->TN_max_colors = 8;
2119 tty->TN_max_pairs = 64;
2120 tty->TN_no_color_video = 0;
2121 break;
2122 }
2123 }
2124
2125 void
2126 set_tty_color_mode (struct tty_display_info *tty, struct frame *f)
2127 {
2128 Lisp_Object tem, val;
2129 Lisp_Object color_mode;
2130 int mode;
2131 Lisp_Object tty_color_mode_alist
2132 = Fintern_soft (build_string ("tty-color-mode-alist"), Qnil);
2133
2134 tem = assq_no_quit (Qtty_color_mode, f->param_alist);
2135 val = CONSP (tem) ? XCDR (tem) : Qnil;
2136
2137 if (INTEGERP (val))
2138 color_mode = val;
2139 else if (SYMBOLP (tty_color_mode_alist))
2140 {
2141 tem = Fassq (val, Fsymbol_value (tty_color_mode_alist));
2142 color_mode = CONSP (tem) ? XCDR (tem) : Qnil;
2143 }
2144 else
2145 color_mode = Qnil;
2146
2147 mode = TYPE_RANGED_INTEGERP (int, color_mode) ? XINT (color_mode) : 0;
2148
2149 if (mode != tty->previous_color_mode)
2150 {
2151 tty->previous_color_mode = mode;
2152 tty_setup_colors (tty , mode);
2153 /* This recomputes all the faces given the new color definitions. */
2154 safe_call (1, intern ("tty-set-up-initial-frame-faces"));
2155 }
2156 }
2157
2158 #endif /* !DOS_NT */
2159
2160 DEFUN ("tty-type", Ftty_type, Stty_type, 0, 1, 0,
2161 doc: /* Return the type of the tty device that TERMINAL uses.
2162 Returns nil if TERMINAL is not on a tty device.
2163
2164 TERMINAL can be a terminal object, a frame, or nil (meaning the
2165 selected frame's terminal). */)
2166 (Lisp_Object terminal)
2167 {
2168 struct terminal *t = decode_tty_terminal (terminal);
2169
2170 return (t && t->display_info.tty->type
2171 ? build_string (t->display_info.tty->type) : Qnil);
2172 }
2173
2174 DEFUN ("controlling-tty-p", Fcontrolling_tty_p, Scontrolling_tty_p, 0, 1, 0,
2175 doc: /* Return non-nil if TERMINAL is the controlling tty of the Emacs process.
2176
2177 TERMINAL can be a terminal object, a frame, or nil (meaning the
2178 selected frame's terminal). This function always returns nil if
2179 TERMINAL is not on a tty device. */)
2180 (Lisp_Object terminal)
2181 {
2182 struct terminal *t = decode_tty_terminal (terminal);
2183
2184 return (t && !strcmp (t->display_info.tty->name, DEV_TTY) ? Qt : Qnil);
2185 }
2186
2187 DEFUN ("tty-no-underline", Ftty_no_underline, Stty_no_underline, 0, 1, 0,
2188 doc: /* Declare that the tty used by TERMINAL does not handle underlining.
2189 This is used to override the terminfo data, for certain terminals that
2190 do not really do underlining, but say that they do. This function has
2191 no effect if used on a non-tty terminal.
2192
2193 TERMINAL can be a terminal object, a frame or nil (meaning the
2194 selected frame's terminal). This function always returns nil if
2195 TERMINAL does not refer to a text terminal. */)
2196 (Lisp_Object terminal)
2197 {
2198 struct terminal *t = decode_live_terminal (terminal);
2199
2200 if (t->type == output_termcap)
2201 t->display_info.tty->TS_enter_underline_mode = 0;
2202 return Qnil;
2203 }
2204
2205 DEFUN ("tty-top-frame", Ftty_top_frame, Stty_top_frame, 0, 1, 0,
2206 doc: /* Return the topmost terminal frame on TERMINAL.
2207 TERMINAL can be a terminal object, a frame or nil (meaning the
2208 selected frame's terminal). This function returns nil if TERMINAL
2209 does not refer to a text terminal. Otherwise, it returns the
2210 top-most frame on the text terminal. */)
2211 (Lisp_Object terminal)
2212 {
2213 struct terminal *t = decode_live_terminal (terminal);
2214
2215 if (t->type == output_termcap)
2216 return t->display_info.tty->top_frame;
2217 return Qnil;
2218 }
2219
2220 \f
2221
2222 DEFUN ("suspend-tty", Fsuspend_tty, Ssuspend_tty, 0, 1, 0,
2223 doc: /* Suspend the terminal device TTY.
2224
2225 The device is restored to its default state, and Emacs ceases all
2226 access to the tty device. Frames that use the device are not deleted,
2227 but input is not read from them and if they change, their display is
2228 not updated.
2229
2230 TTY may be a terminal object, a frame, or nil for the terminal device
2231 of the currently selected frame.
2232
2233 This function runs `suspend-tty-functions' after suspending the
2234 device. The functions are run with one arg, the id of the suspended
2235 terminal device.
2236
2237 `suspend-tty' does nothing if it is called on a device that is already
2238 suspended.
2239
2240 A suspended tty may be resumed by calling `resume-tty' on it. */)
2241 (Lisp_Object tty)
2242 {
2243 struct terminal *t = decode_tty_terminal (tty);
2244 FILE *f;
2245
2246 if (!t)
2247 error ("Attempt to suspend a non-text terminal device");
2248
2249 f = t->display_info.tty->input;
2250
2251 if (f)
2252 {
2253 /* First run `suspend-tty-functions' and then clean up the tty
2254 state because `suspend-tty-functions' might need to change
2255 the tty state. */
2256 Lisp_Object args[2];
2257 args[0] = intern ("suspend-tty-functions");
2258 XSETTERMINAL (args[1], t);
2259 Frun_hook_with_args (2, args);
2260
2261 reset_sys_modes (t->display_info.tty);
2262 delete_keyboard_wait_descriptor (fileno (f));
2263
2264 #ifndef MSDOS
2265 fclose (f);
2266 if (f != t->display_info.tty->output)
2267 fclose (t->display_info.tty->output);
2268 #endif
2269
2270 t->display_info.tty->input = 0;
2271 t->display_info.tty->output = 0;
2272
2273 if (FRAMEP (t->display_info.tty->top_frame))
2274 SET_FRAME_VISIBLE (XFRAME (t->display_info.tty->top_frame), 0);
2275
2276 }
2277
2278 /* Clear display hooks to prevent further output. */
2279 clear_tty_hooks (t);
2280
2281 return Qnil;
2282 }
2283
2284 DEFUN ("resume-tty", Fresume_tty, Sresume_tty, 0, 1, 0,
2285 doc: /* Resume the previously suspended terminal device TTY.
2286 The terminal is opened and reinitialized. Frames that are on the
2287 suspended terminal are revived.
2288
2289 It is an error to resume a terminal while another terminal is active
2290 on the same device.
2291
2292 This function runs `resume-tty-functions' after resuming the terminal.
2293 The functions are run with one arg, the id of the resumed terminal
2294 device.
2295
2296 `resume-tty' does nothing if it is called on a device that is not
2297 suspended.
2298
2299 TTY may be a terminal object, a frame, or nil (meaning the selected
2300 frame's terminal). */)
2301 (Lisp_Object tty)
2302 {
2303 struct terminal *t = decode_tty_terminal (tty);
2304 int fd;
2305
2306 if (!t)
2307 error ("Attempt to resume a non-text terminal device");
2308
2309 if (!t->display_info.tty->input)
2310 {
2311 if (get_named_terminal (t->display_info.tty->name))
2312 error ("Cannot resume display while another display is active on the same device");
2313
2314 #ifdef MSDOS
2315 t->display_info.tty->output = stdout;
2316 t->display_info.tty->input = stdin;
2317 #else /* !MSDOS */
2318 fd = emacs_open (t->display_info.tty->name, O_RDWR | O_NOCTTY, 0);
2319 t->display_info.tty->input = t->display_info.tty->output
2320 = fd < 0 ? 0 : fdopen (fd, "w+");
2321
2322 if (! t->display_info.tty->input)
2323 {
2324 int open_errno = errno;
2325 emacs_close (fd);
2326 report_file_errno ("Cannot reopen tty device",
2327 build_string (t->display_info.tty->name),
2328 open_errno);
2329 }
2330
2331 if (!O_IGNORE_CTTY && strcmp (t->display_info.tty->name, DEV_TTY) != 0)
2332 dissociate_if_controlling_tty (fd);
2333 #endif
2334
2335 add_keyboard_wait_descriptor (fd);
2336
2337 if (FRAMEP (t->display_info.tty->top_frame))
2338 {
2339 struct frame *f = XFRAME (t->display_info.tty->top_frame);
2340 int width, height;
2341 int old_height = FRAME_COLS (f);
2342 int old_width = FRAME_TOTAL_LINES (f);
2343
2344 /* Check if terminal/window size has changed while the frame
2345 was suspended. */
2346 get_tty_size (fileno (t->display_info.tty->input), &width, &height);
2347 if (width != old_width || height != old_height)
2348 change_frame_size (f, width, height - FRAME_MENU_BAR_LINES (f),
2349 0, 0, 0, 0);
2350 SET_FRAME_VISIBLE (XFRAME (t->display_info.tty->top_frame), 1);
2351 }
2352
2353 set_tty_hooks (t);
2354 init_sys_modes (t->display_info.tty);
2355
2356 {
2357 /* Run `resume-tty-functions'. */
2358 Lisp_Object args[2];
2359 args[0] = intern ("resume-tty-functions");
2360 XSETTERMINAL (args[1], t);
2361 Frun_hook_with_args (2, args);
2362 }
2363 }
2364
2365 set_tty_hooks (t);
2366
2367 return Qnil;
2368 }
2369
2370 \f
2371 /***********************************************************************
2372 Mouse
2373 ***********************************************************************/
2374
2375 #ifdef HAVE_GPM
2376
2377 #ifndef HAVE_WINDOW_SYSTEM
2378 void
2379 term_mouse_moveto (int x, int y)
2380 {
2381 /* TODO: how to set mouse position?
2382 const char *name;
2383 int fd;
2384 name = (const char *) ttyname (0);
2385 fd = emacs_open (name, O_WRONLY, 0);
2386 SOME_FUNCTION (x, y, fd);
2387 emacs_close (fd);
2388 last_mouse_x = x;
2389 last_mouse_y = y; */
2390 }
2391 #endif /* HAVE_WINDOW_SYSTEM */
2392
2393 /* Implementation of draw_row_with_mouse_face for TTY/GPM. */
2394 void
2395 tty_draw_row_with_mouse_face (struct window *w, struct glyph_row *row,
2396 int start_hpos, int end_hpos,
2397 enum draw_glyphs_face draw)
2398 {
2399 int nglyphs = end_hpos - start_hpos;
2400 struct frame *f = XFRAME (WINDOW_FRAME (w));
2401 struct tty_display_info *tty = FRAME_TTY (f);
2402 int face_id = tty->mouse_highlight.mouse_face_face_id;
2403 int save_x, save_y, pos_x, pos_y;
2404
2405 if (end_hpos >= row->used[TEXT_AREA])
2406 nglyphs = row->used[TEXT_AREA] - start_hpos;
2407
2408 pos_y = row->y + WINDOW_TOP_EDGE_Y (w);
2409 pos_x = row->used[LEFT_MARGIN_AREA] + start_hpos + WINDOW_LEFT_EDGE_X (w);
2410
2411 /* Save current cursor co-ordinates. */
2412 save_y = curY (tty);
2413 save_x = curX (tty);
2414 cursor_to (f, pos_y, pos_x);
2415
2416 if (draw == DRAW_MOUSE_FACE)
2417 tty_write_glyphs_with_face (f, row->glyphs[TEXT_AREA] + start_hpos,
2418 nglyphs, face_id);
2419 else if (draw == DRAW_NORMAL_TEXT)
2420 write_glyphs (f, row->glyphs[TEXT_AREA] + start_hpos, nglyphs);
2421
2422 cursor_to (f, save_y, save_x);
2423 }
2424
2425 static bool
2426 term_mouse_movement (struct frame *frame, Gpm_Event *event)
2427 {
2428 /* Has the mouse moved off the glyph it was on at the last sighting? */
2429 if (event->x != last_mouse_x || event->y != last_mouse_y)
2430 {
2431 frame->mouse_moved = 1;
2432 note_mouse_highlight (frame, event->x, event->y);
2433 /* Remember which glyph we're now on. */
2434 last_mouse_x = event->x;
2435 last_mouse_y = event->y;
2436 return 1;
2437 }
2438 return 0;
2439 }
2440
2441 /* Return the Time that corresponds to T. Wrap around on overflow. */
2442 static Time
2443 timeval_to_Time (struct timeval const *t)
2444 {
2445 Time s_1000, ms;
2446
2447 s_1000 = t->tv_sec;
2448 s_1000 *= 1000;
2449 ms = t->tv_usec / 1000;
2450 return s_1000 + ms;
2451 }
2452
2453 /* Return the current position of the mouse.
2454
2455 Set *f to the frame the mouse is in, or zero if the mouse is in no
2456 Emacs frame. If it is set to zero, all the other arguments are
2457 garbage.
2458
2459 Set *bar_window to Qnil, and *x and *y to the column and
2460 row of the character cell the mouse is over.
2461
2462 Set *timeptr to the time the mouse was at the returned position.
2463
2464 This clears mouse_moved until the next motion
2465 event arrives. */
2466 static void
2467 term_mouse_position (struct frame **fp, int insist, Lisp_Object *bar_window,
2468 enum scroll_bar_part *part, Lisp_Object *x,
2469 Lisp_Object *y, Time *timeptr)
2470 {
2471 struct timeval now;
2472
2473 *fp = SELECTED_FRAME ();
2474 (*fp)->mouse_moved = 0;
2475
2476 *bar_window = Qnil;
2477 *part = scroll_bar_above_handle;
2478
2479 XSETINT (*x, last_mouse_x);
2480 XSETINT (*y, last_mouse_y);
2481 gettimeofday(&now, 0);
2482 *timeptr = timeval_to_Time (&now);
2483 }
2484
2485 /* Prepare a mouse-event in *RESULT for placement in the input queue.
2486
2487 If the event is a button press, then note that we have grabbed
2488 the mouse. */
2489
2490 static Lisp_Object
2491 term_mouse_click (struct input_event *result, Gpm_Event *event,
2492 struct frame *f)
2493 {
2494 struct timeval now;
2495 int i, j;
2496
2497 result->kind = GPM_CLICK_EVENT;
2498 for (i = 0, j = GPM_B_LEFT; i < 3; i++, j >>= 1 )
2499 {
2500 if (event->buttons & j) {
2501 result->code = i; /* button number */
2502 break;
2503 }
2504 }
2505 gettimeofday(&now, 0);
2506 result->timestamp = timeval_to_Time (&now);
2507
2508 if (event->type & GPM_UP)
2509 result->modifiers = up_modifier;
2510 else if (event->type & GPM_DOWN)
2511 result->modifiers = down_modifier;
2512 else
2513 result->modifiers = 0;
2514
2515 if (event->type & GPM_SINGLE)
2516 result->modifiers |= click_modifier;
2517
2518 if (event->type & GPM_DOUBLE)
2519 result->modifiers |= double_modifier;
2520
2521 if (event->type & GPM_TRIPLE)
2522 result->modifiers |= triple_modifier;
2523
2524 if (event->type & GPM_DRAG)
2525 result->modifiers |= drag_modifier;
2526
2527 if (!(event->type & (GPM_MOVE | GPM_DRAG))) {
2528
2529 /* 1 << KG_SHIFT */
2530 if (event->modifiers & (1 << 0))
2531 result->modifiers |= shift_modifier;
2532
2533 /* 1 << KG_CTRL */
2534 if (event->modifiers & (1 << 2))
2535 result->modifiers |= ctrl_modifier;
2536
2537 /* 1 << KG_ALT || KG_ALTGR */
2538 if (event->modifiers & (1 << 3)
2539 || event->modifiers & (1 << 1))
2540 result->modifiers |= meta_modifier;
2541 }
2542
2543 XSETINT (result->x, event->x);
2544 XSETINT (result->y, event->y);
2545 XSETFRAME (result->frame_or_window, f);
2546 result->arg = Qnil;
2547 return Qnil;
2548 }
2549
2550 int
2551 handle_one_term_event (struct tty_display_info *tty, Gpm_Event *event, struct input_event* hold_quit)
2552 {
2553 struct frame *f = XFRAME (tty->top_frame);
2554 struct input_event ie;
2555 bool do_help = 0;
2556 int count = 0;
2557
2558 EVENT_INIT (ie);
2559 ie.kind = NO_EVENT;
2560 ie.arg = Qnil;
2561
2562 if (event->type & (GPM_MOVE | GPM_DRAG)) {
2563 previous_help_echo_string = help_echo_string;
2564 help_echo_string = Qnil;
2565
2566 Gpm_DrawPointer (event->x, event->y, fileno (tty->output));
2567
2568 if (!term_mouse_movement (f, event))
2569 help_echo_string = previous_help_echo_string;
2570
2571 /* If the contents of the global variable help_echo_string
2572 has changed, generate a HELP_EVENT. */
2573 if (!NILP (help_echo_string)
2574 || !NILP (previous_help_echo_string))
2575 do_help = 1;
2576
2577 goto done;
2578 }
2579 else {
2580 f->mouse_moved = 0;
2581 term_mouse_click (&ie, event, f);
2582 }
2583
2584 done:
2585 if (ie.kind != NO_EVENT)
2586 {
2587 kbd_buffer_store_event_hold (&ie, hold_quit);
2588 count++;
2589 }
2590
2591 if (do_help
2592 && !(hold_quit && hold_quit->kind != NO_EVENT))
2593 {
2594 Lisp_Object frame;
2595
2596 if (f)
2597 XSETFRAME (frame, f);
2598 else
2599 frame = Qnil;
2600
2601 gen_help_event (help_echo_string, frame, help_echo_window,
2602 help_echo_object, help_echo_pos);
2603 count++;
2604 }
2605
2606 return count;
2607 }
2608
2609 DEFUN ("gpm-mouse-start", Fgpm_mouse_start, Sgpm_mouse_start,
2610 0, 0, 0,
2611 doc: /* Open a connection to Gpm.
2612 Gpm-mouse can only be activated for one tty at a time. */)
2613 (void)
2614 {
2615 struct frame *f = SELECTED_FRAME ();
2616 struct tty_display_info *tty
2617 = ((f)->output_method == output_termcap
2618 ? (f)->terminal->display_info.tty : NULL);
2619 Gpm_Connect connection;
2620
2621 if (!tty)
2622 error ("Gpm-mouse only works in the GNU/Linux console");
2623 if (gpm_tty == tty)
2624 return Qnil; /* Already activated, nothing to do. */
2625 if (gpm_tty)
2626 error ("Gpm-mouse can only be activated for one tty at a time");
2627
2628 connection.eventMask = ~0;
2629 connection.defaultMask = ~GPM_HARD;
2630 connection.maxMod = ~0;
2631 connection.minMod = 0;
2632 gpm_zerobased = 1;
2633
2634 if (Gpm_Open (&connection, 0) < 0)
2635 error ("Gpm-mouse failed to connect to the gpm daemon");
2636 else
2637 {
2638 gpm_tty = tty;
2639 /* `init_sys_modes' arranges for mouse movements sent through gpm_fd
2640 to generate SIGIOs. Apparently we need to call reset_sys_modes
2641 before calling init_sys_modes. */
2642 reset_sys_modes (tty);
2643 init_sys_modes (tty);
2644 add_gpm_wait_descriptor (gpm_fd);
2645 return Qnil;
2646 }
2647 }
2648
2649 void
2650 close_gpm (int fd)
2651 {
2652 if (fd >= 0)
2653 delete_gpm_wait_descriptor (fd);
2654 while (Gpm_Close()); /* close all the stack */
2655 gpm_tty = NULL;
2656 }
2657
2658 DEFUN ("gpm-mouse-stop", Fgpm_mouse_stop, Sgpm_mouse_stop,
2659 0, 0, 0,
2660 doc: /* Close a connection to Gpm. */)
2661 (void)
2662 {
2663 struct frame *f = SELECTED_FRAME ();
2664 struct tty_display_info *tty
2665 = ((f)->output_method == output_termcap
2666 ? (f)->terminal->display_info.tty : NULL);
2667
2668 if (!tty || gpm_tty != tty)
2669 return Qnil; /* Not activated on this terminal, nothing to do. */
2670
2671 close_gpm (gpm_fd);
2672 return Qnil;
2673 }
2674 #endif /* HAVE_GPM */
2675
2676 \f
2677 /***********************************************************************
2678 Menus
2679 ***********************************************************************/
2680
2681 #if !defined (MSDOS)
2682
2683 /* TTY menu implementation and main ideas are borrowed from msdos.c.
2684
2685 However, unlike on MSDOS, where the menu text is drawn directly to
2686 the display video memory, on a TTY we use display_string (see
2687 display_tty_menu_item in xdisp.c) to put the glyphs produced from
2688 the menu items into the frame's 'desired_matrix' glyph matrix, and
2689 then call update_frame_with_menu to deliver the results to the
2690 glass. The previous contents of the screen, in the form of the
2691 current_matrix, is stashed away, and used to restore screen
2692 contents when the menu selection changes or when the final
2693 selection is made and the menu should be popped down.
2694
2695 The idea of this implementation was suggested by Gerd Moellmann. */
2696
2697 #define TTYM_FAILURE -1
2698 #define TTYM_SUCCESS 1
2699 #define TTYM_NO_SELECT 2
2700 #define TTYM_IA_SELECT 3
2701 #define TTYM_NEXT 4
2702 #define TTYM_PREV 5
2703
2704 /* These hold text of the current and the previous menu help messages. */
2705 static const char *menu_help_message, *prev_menu_help_message;
2706 /* Pane number and item number of the menu item which generated the
2707 last menu help message. */
2708 static int menu_help_paneno, menu_help_itemno;
2709
2710 typedef struct tty_menu_struct
2711 {
2712 int count;
2713 char **text;
2714 struct tty_menu_struct **submenu;
2715 int *panenumber; /* Also used as enabled flag. */
2716 ptrdiff_t allocated;
2717 int panecount;
2718 int width;
2719 const char **help_text;
2720 } tty_menu;
2721
2722 /* Create a brand new menu structure. */
2723
2724 static tty_menu *
2725 tty_menu_create (void)
2726 {
2727 return xzalloc (sizeof *tty_menu_create ());
2728 }
2729
2730 /* Allocate some (more) memory for MENU ensuring that there is room for one
2731 more item. */
2732
2733 static void
2734 tty_menu_make_room (tty_menu *menu)
2735 {
2736 if (menu->allocated == menu->count)
2737 {
2738 ptrdiff_t allocated = menu->allocated;
2739 menu->text = xpalloc (menu->text, &allocated, 1, -1, sizeof *menu->text);
2740 menu->text = xrealloc (menu->text, allocated * sizeof *menu->text);
2741 menu->submenu = xrealloc (menu->submenu,
2742 allocated * sizeof *menu->submenu);
2743 menu->panenumber = xrealloc (menu->panenumber,
2744 allocated * sizeof *menu->panenumber);
2745 menu->help_text = xrealloc (menu->help_text,
2746 allocated * sizeof *menu->help_text);
2747 menu->allocated = allocated;
2748 }
2749 }
2750
2751 /* Search the given menu structure for a given pane number. */
2752
2753 static tty_menu *
2754 tty_menu_search_pane (tty_menu *menu, int pane)
2755 {
2756 int i;
2757 tty_menu *try;
2758
2759 for (i = 0; i < menu->count; i++)
2760 if (menu->submenu[i])
2761 {
2762 if (pane == menu->panenumber[i])
2763 return menu->submenu[i];
2764 try = tty_menu_search_pane (menu->submenu[i], pane);
2765 if (try)
2766 return try;
2767 }
2768 return (tty_menu *) 0;
2769 }
2770
2771 /* Determine how much screen space a given menu needs. */
2772
2773 static void
2774 tty_menu_calc_size (tty_menu *menu, int *width, int *height)
2775 {
2776 int i, h2, w2, maxsubwidth, maxheight;
2777
2778 maxsubwidth = menu->width;
2779 maxheight = menu->count;
2780 for (i = 0; i < menu->count; i++)
2781 {
2782 if (menu->submenu[i])
2783 {
2784 tty_menu_calc_size (menu->submenu[i], &w2, &h2);
2785 if (w2 > maxsubwidth) maxsubwidth = w2;
2786 if (i + h2 > maxheight) maxheight = i + h2;
2787 }
2788 }
2789 *width = maxsubwidth;
2790 *height = maxheight;
2791 }
2792
2793 static void
2794 mouse_get_xy (int *x, int *y)
2795 {
2796 struct frame *sf = SELECTED_FRAME ();
2797 Lisp_Object lmx = Qnil, lmy = Qnil, lisp_dummy;
2798 enum scroll_bar_part part_dummy;
2799 Time time_dummy;
2800
2801 if (FRAME_TERMINAL (sf)->mouse_position_hook)
2802 (*FRAME_TERMINAL (sf)->mouse_position_hook) (&sf, -1,
2803 &lisp_dummy, &part_dummy,
2804 &lmx, &lmy,
2805 &time_dummy);
2806 if (!NILP (lmx))
2807 {
2808 *x = XINT (lmx);
2809 *y = XINT (lmy);
2810 }
2811 }
2812
2813 /* Display MENU at (X,Y) using FACES, starting with FIRST_ITEM
2814 (zero-based). */
2815
2816 static void
2817 tty_menu_display (tty_menu *menu, int x, int y, int pn, int *faces,
2818 int mx, int my, int first_item, bool disp_help)
2819 {
2820 int i, face, width, enabled, mousehere, row, col;
2821 struct frame *sf = SELECTED_FRAME ();
2822 struct tty_display_info *tty = FRAME_TTY (sf);
2823 /* Don't try to display more menu items than the console can display
2824 using the available screen lines. Exclude the echo area line, as
2825 it will be overwritten by the help-echo anyway. */
2826 int max_items = min (menu->count - first_item, FRAME_TOTAL_LINES (sf) - 1 - y);
2827
2828 menu_help_message = NULL;
2829
2830 width = menu->width;
2831 col = cursorX (tty);
2832 row = cursorY (tty);
2833 for (i = 0; i < max_items; i++)
2834 {
2835 int max_width = width + 2; /* +2 for padding blanks on each side */
2836 int j = i + first_item;
2837
2838 if (menu->submenu[j])
2839 max_width += 2; /* for displaying " >" after the item */
2840 enabled
2841 = (!menu->submenu[j] && menu->panenumber[j]) || (menu->submenu[j]);
2842 mousehere = (y + i == my && x <= mx && mx < x + max_width);
2843 face = faces[enabled + mousehere * 2];
2844 /* Display the menu help string for the i-th menu item even if
2845 the menu item is currently disabled. That's what the GUI
2846 code does. */
2847 if (disp_help && enabled + mousehere * 2 >= 2)
2848 {
2849 menu_help_message = menu->help_text[j];
2850 menu_help_paneno = pn - 1;
2851 menu_help_itemno = j;
2852 }
2853 /* Take note of the coordinates of the active menu item, to
2854 display the cursor there. */
2855 if (mousehere)
2856 {
2857 row = y + i;
2858 col = x;
2859 }
2860 display_tty_menu_item (menu->text[j], max_width, face, x, y + i,
2861 menu->submenu[j] != NULL);
2862 }
2863 update_frame_with_menu (sf, row, col);
2864 }
2865
2866 /* --------------------------- X Menu emulation ---------------------- */
2867
2868 /* Create a new pane and place it on the outer-most level. */
2869
2870 static int
2871 tty_menu_add_pane (tty_menu *menu, const char *txt)
2872 {
2873 int len;
2874
2875 tty_menu_make_room (menu);
2876 menu->submenu[menu->count] = tty_menu_create ();
2877 menu->text[menu->count] = (char *)txt;
2878 menu->panenumber[menu->count] = ++menu->panecount;
2879 menu->help_text[menu->count] = NULL;
2880 menu->count++;
2881
2882 /* Update the menu width, if necessary. */
2883 len = menu_item_width ((const unsigned char *) txt);
2884 if (len > menu->width)
2885 menu->width = len;
2886
2887 return menu->panecount;
2888 }
2889
2890 /* Create a new item in a menu pane. */
2891
2892 static bool
2893 tty_menu_add_selection (tty_menu *menu, int pane,
2894 char *txt, bool enable, char const *help_text)
2895 {
2896 int len;
2897
2898 if (pane)
2899 {
2900 menu = tty_menu_search_pane (menu, pane);
2901 if (! menu)
2902 return 0;
2903 }
2904 tty_menu_make_room (menu);
2905 menu->submenu[menu->count] = (tty_menu *) 0;
2906 menu->text[menu->count] = txt;
2907 menu->panenumber[menu->count] = enable;
2908 menu->help_text[menu->count] = help_text;
2909 menu->count++;
2910
2911 /* Update the menu width, if necessary. */
2912 len = menu_item_width ((const unsigned char *) txt);
2913 if (len > menu->width)
2914 menu->width = len;
2915
2916 return 1;
2917 }
2918
2919 /* Decide where the menu would be placed if requested at (X,Y). */
2920
2921 static void
2922 tty_menu_locate (tty_menu *menu, int x, int y,
2923 int *ulx, int *uly, int *width, int *height)
2924 {
2925 tty_menu_calc_size (menu, width, height);
2926 *ulx = x + 1;
2927 *uly = y;
2928 *width += 2;
2929 }
2930
2931 struct tty_menu_state
2932 {
2933 struct glyph_matrix *screen_behind;
2934 tty_menu *menu;
2935 int pane;
2936 int x, y;
2937 };
2938
2939 /* Save away the contents of frame F's current frame matrix, and
2940 enable all its rows. Value is a glyph matrix holding the contents
2941 of F's current frame matrix with all its glyph rows enabled. */
2942
2943 static struct glyph_matrix *
2944 save_and_enable_current_matrix (struct frame *f)
2945 {
2946 int i;
2947 struct glyph_matrix *saved = xzalloc (sizeof *saved);
2948 saved->nrows = f->current_matrix->nrows;
2949 saved->rows = xzalloc (saved->nrows * sizeof *saved->rows);
2950
2951 for (i = 0; i < saved->nrows; ++i)
2952 {
2953 struct glyph_row *from = f->current_matrix->rows + i;
2954 struct glyph_row *to = saved->rows + i;
2955 ptrdiff_t nbytes = from->used[TEXT_AREA] * sizeof (struct glyph);
2956
2957 to->glyphs[TEXT_AREA] = xmalloc (nbytes);
2958 memcpy (to->glyphs[TEXT_AREA], from->glyphs[TEXT_AREA], nbytes);
2959 to->used[TEXT_AREA] = from->used[TEXT_AREA];
2960 /* Make sure every row is enabled, or else update_frame will not
2961 redraw them. (Rows that are identical to what is already on
2962 screen will not be redrawn anyway.) */
2963 to->enabled_p = true;
2964 to->hash = from->hash;
2965 }
2966
2967 return saved;
2968 }
2969
2970 /* Restore the contents of frame F's desired frame matrix from SAVED,
2971 and free memory associated with SAVED. */
2972
2973 static void
2974 restore_desired_matrix (struct frame *f, struct glyph_matrix *saved)
2975 {
2976 int i;
2977
2978 for (i = 0; i < saved->nrows; ++i)
2979 {
2980 struct glyph_row *from = saved->rows + i;
2981 struct glyph_row *to = f->desired_matrix->rows + i;
2982 ptrdiff_t nbytes = from->used[TEXT_AREA] * sizeof (struct glyph);
2983
2984 eassert (to->glyphs[TEXT_AREA] != from->glyphs[TEXT_AREA]);
2985 memcpy (to->glyphs[TEXT_AREA], from->glyphs[TEXT_AREA], nbytes);
2986 to->used[TEXT_AREA] = from->used[TEXT_AREA];
2987 to->enabled_p = from->enabled_p;
2988 to->hash = from->hash;
2989 }
2990 }
2991
2992 static void
2993 free_saved_screen (struct glyph_matrix *saved)
2994 {
2995 int i;
2996
2997 if (!saved)
2998 return; /* Already freed! */
2999
3000 for (i = 0; i < saved->nrows; ++i)
3001 {
3002 struct glyph_row *from = saved->rows + i;
3003
3004 xfree (from->glyphs[TEXT_AREA]);
3005 }
3006
3007 xfree (saved->rows);
3008 xfree (saved);
3009 }
3010
3011 /* Update the display of frame F from its saved contents. */
3012 static void
3013 screen_update (struct frame *f, struct glyph_matrix *mtx)
3014 {
3015 restore_desired_matrix (f, mtx);
3016 update_frame_with_menu (f, -1, -1);
3017 }
3018
3019 typedef enum {
3020 MI_QUIT_MENU = -1,
3021 MI_CONTINUE = 0,
3022 MI_ITEM_SELECTED = 1,
3023 MI_NEXT_ITEM = 2,
3024 MI_PREV_ITEM = 3,
3025 MI_SCROLL_FORWARD = 4,
3026 MI_SCROLL_BACK = 5
3027 } mi_result;
3028
3029 /* Read user input and return X and Y coordinates where that input
3030 puts us. We only consider mouse movement and click events, and
3031 keyboard movement commands; the rest are ignored. */
3032 static mi_result
3033 read_menu_input (struct frame *sf, int *x, int *y, int min_y, int max_y,
3034 bool *first_time)
3035 {
3036 if (*first_time)
3037 {
3038 *first_time = false;
3039 sf->mouse_moved = 1;
3040 }
3041 else
3042 {
3043 Lisp_Object cmd;
3044 bool usable_input = 1;
3045 mi_result st = MI_CONTINUE;
3046 struct tty_display_info *tty = FRAME_TTY (sf);
3047 Lisp_Object saved_mouse_tracking = do_mouse_tracking;
3048
3049 /* Signal the keyboard reading routines we are displaying a menu
3050 on this terminal. */
3051 tty->showing_menu = 1;
3052 /* We want mouse movements be reported by read_menu_command. */
3053 do_mouse_tracking = Qt;
3054 do {
3055 cmd = read_menu_command ();
3056 } while (NILP (cmd));
3057 tty->showing_menu = 0;
3058 do_mouse_tracking = saved_mouse_tracking;
3059
3060 if (EQ (cmd, Qt) || EQ (cmd, Qtty_menu_exit)
3061 /* If some input switched frames under our feet, exit the
3062 menu, since the menu faces are no longer valid, and the
3063 menu is no longer relevant anyway. */
3064 || sf != SELECTED_FRAME ())
3065 return MI_QUIT_MENU;
3066 if (EQ (cmd, Qtty_menu_mouse_movement))
3067 mouse_get_xy (x, y);
3068 else if (EQ (cmd, Qtty_menu_next_menu))
3069 {
3070 usable_input = 0;
3071 st = MI_NEXT_ITEM;
3072 }
3073 else if (EQ (cmd, Qtty_menu_prev_menu))
3074 {
3075 usable_input = 0;
3076 st = MI_PREV_ITEM;
3077 }
3078 else if (EQ (cmd, Qtty_menu_next_item))
3079 {
3080 if (*y < max_y)
3081 *y += 1;
3082 else
3083 st = MI_SCROLL_FORWARD;
3084 }
3085 else if (EQ (cmd, Qtty_menu_prev_item))
3086 {
3087 if (*y > min_y)
3088 *y -= 1;
3089 else
3090 st = MI_SCROLL_BACK;
3091 }
3092 else if (EQ (cmd, Qtty_menu_select))
3093 st = MI_ITEM_SELECTED;
3094 else if (!EQ (cmd, Qtty_menu_ignore))
3095 usable_input = 0;
3096 if (usable_input)
3097 sf->mouse_moved = 1;
3098 return st;
3099 }
3100 return MI_CONTINUE;
3101 }
3102
3103 /* Display menu, wait for user's response, and return that response. */
3104 static int
3105 tty_menu_activate (tty_menu *menu, int *pane, int *selidx,
3106 int x0, int y0, char **txt,
3107 void (*help_callback)(char const *, int, int),
3108 bool kbd_navigation)
3109 {
3110 struct tty_menu_state *state;
3111 int statecount, x, y, i;
3112 bool leave, onepane;
3113 int result IF_LINT (= 0);
3114 int title_faces[4]; /* Face to display the menu title. */
3115 int faces[4], buffers_num_deleted = 0;
3116 struct frame *sf = SELECTED_FRAME ();
3117 struct tty_display_info *tty = FRAME_TTY (sf);
3118 bool first_time;
3119 Lisp_Object selectface;
3120 int first_item = 0;
3121 int col, row;
3122 USE_SAFE_ALLOCA;
3123
3124 /* Don't allow non-positive x0 and y0, lest the menu will wrap
3125 around the display. */
3126 if (x0 <= 0)
3127 x0 = 1;
3128 if (y0 <= 0)
3129 y0 = 1;
3130
3131 SAFE_NALLOCA (state, 1, menu->panecount);
3132 memset (state, 0, sizeof (*state));
3133 faces[0]
3134 = lookup_derived_face (sf, intern ("tty-menu-disabled-face"),
3135 DEFAULT_FACE_ID, 1);
3136 faces[1]
3137 = lookup_derived_face (sf, intern ("tty-menu-enabled-face"),
3138 DEFAULT_FACE_ID, 1);
3139 selectface = intern ("tty-menu-selected-face");
3140 faces[2] = lookup_derived_face (sf, selectface,
3141 faces[0], 1);
3142 faces[3] = lookup_derived_face (sf, selectface,
3143 faces[1], 1);
3144
3145 /* Make sure the menu title is always displayed with
3146 `tty-menu-selected-face', no matter where the mouse pointer is. */
3147 for (i = 0; i < 4; i++)
3148 title_faces[i] = faces[3];
3149
3150 statecount = 1;
3151
3152 /* Don't let the title for the "Buffers" popup menu include a
3153 digit (which is ugly).
3154
3155 This is a terrible kludge, but I think the "Buffers" case is
3156 the only one where the title includes a number, so it doesn't
3157 seem to be necessary to make this more general. */
3158 if (strncmp (menu->text[0], "Buffers 1", 9) == 0)
3159 {
3160 menu->text[0][7] = '\0';
3161 buffers_num_deleted = 1;
3162 }
3163
3164 /* Force update of the current frame, so that the desired and the
3165 current matrices are identical. */
3166 update_frame_with_menu (sf, -1, -1);
3167 state[0].menu = menu;
3168 state[0].screen_behind = save_and_enable_current_matrix (sf);
3169
3170 /* Display the menu title. We subtract 1 from x0 and y0 because we
3171 want to interpret them as zero-based column and row coordinates,
3172 and also because we want the first item of the menu, not its
3173 title, to appear at x0,y0. */
3174 tty_menu_display (menu, x0 - 1, y0 - 1, 1, title_faces, x0 - 1, y0 - 1, 0, 0);
3175
3176 /* Turn off the cursor. Otherwise it shows through the menu
3177 panes, which is ugly. */
3178 col = cursorX (tty);
3179 row = cursorY (tty);
3180 tty_hide_cursor (tty);
3181
3182 if (buffers_num_deleted)
3183 menu->text[0][7] = ' ';
3184 onepane = menu->count == 1 && menu->submenu[0];
3185 if (onepane)
3186 {
3187 menu->width = menu->submenu[0]->width;
3188 state[0].menu = menu->submenu[0];
3189 }
3190 else
3191 {
3192 state[0].menu = menu;
3193 }
3194 state[0].x = x0 - 1;
3195 state[0].y = y0;
3196 state[0].pane = onepane;
3197
3198 x = state[0].x;
3199 y = state[0].y;
3200 first_time = true;
3201
3202 leave = 0;
3203 while (!leave)
3204 {
3205 mi_result input_status;
3206 int min_y = state[0].y;
3207 int max_y = min (min_y + state[0].menu->count, FRAME_TOTAL_LINES (sf) - 1) - 1;
3208
3209 input_status = read_menu_input (sf, &x, &y, min_y, max_y, &first_time);
3210 if (input_status)
3211 {
3212 leave = 1;
3213 switch (input_status)
3214 {
3215 case MI_QUIT_MENU:
3216 /* Remove the last help-echo, so that it doesn't
3217 re-appear after "Quit". */
3218 show_help_echo (Qnil, Qnil, Qnil, Qnil);
3219 result = TTYM_NO_SELECT;
3220 break;
3221 case MI_NEXT_ITEM:
3222 if (kbd_navigation)
3223 result = TTYM_NEXT;
3224 else
3225 leave = 0;
3226 break;
3227 case MI_PREV_ITEM:
3228 if (kbd_navigation)
3229 result = TTYM_PREV;
3230 else
3231 leave = 0;
3232 break;
3233 case MI_SCROLL_FORWARD:
3234 if (y - min_y == state[0].menu->count - 1 - first_item)
3235 {
3236 y = min_y;
3237 first_item = 0;
3238 }
3239 else
3240 first_item++;
3241 leave = 0;
3242 break;
3243 case MI_SCROLL_BACK:
3244 if (first_item == 0)
3245 {
3246 y = max_y;
3247 first_item = state[0].menu->count - 1 - (y - min_y);
3248 }
3249 else
3250 first_item--;
3251 leave = 0;
3252 break;
3253 default:
3254 /* MI_ITEM_SELECTED is handled below, so nothing to do. */
3255 break;
3256 }
3257 }
3258 if (sf->mouse_moved && input_status != MI_QUIT_MENU)
3259 {
3260 sf->mouse_moved = 0;
3261 result = TTYM_IA_SELECT;
3262 for (i = 0; i < statecount; i++)
3263 if (state[i].x <= x && x < state[i].x + state[i].menu->width + 2)
3264 {
3265 int dy = y - state[i].y + first_item;
3266 if (0 <= dy && dy < state[i].menu->count)
3267 {
3268 if (!state[i].menu->submenu[dy])
3269 {
3270 if (state[i].menu->panenumber[dy])
3271 result = TTYM_SUCCESS;
3272 else
3273 result = TTYM_IA_SELECT;
3274 }
3275 *pane = state[i].pane - 1;
3276 *selidx = dy;
3277 /* We hit some part of a menu, so drop extra menus that
3278 have been opened. That does not include an open and
3279 active submenu. */
3280 if (i != statecount - 2
3281 || state[i].menu->submenu[dy] != state[i + 1].menu)
3282 while (i != statecount - 1)
3283 {
3284 statecount--;
3285 screen_update (sf, state[statecount].screen_behind);
3286 state[statecount].screen_behind = NULL;
3287 }
3288 if (i == statecount - 1 && state[i].menu->submenu[dy])
3289 {
3290 tty_menu_display (state[i].menu,
3291 state[i].x,
3292 state[i].y,
3293 state[i].pane,
3294 faces, x, y, first_item, 1);
3295 state[statecount].menu = state[i].menu->submenu[dy];
3296 state[statecount].pane = state[i].menu->panenumber[dy];
3297 state[statecount].screen_behind
3298 = save_and_enable_current_matrix (sf);
3299 state[statecount].x
3300 = state[i].x + state[i].menu->width + 2;
3301 state[statecount].y = y;
3302 statecount++;
3303 }
3304 }
3305 }
3306 tty_menu_display (state[statecount - 1].menu,
3307 state[statecount - 1].x,
3308 state[statecount - 1].y,
3309 state[statecount - 1].pane,
3310 faces, x, y, first_item, 1);
3311 /* The call to display help-echo below will move the cursor,
3312 so remember its current position as computed by
3313 tty_menu_display. */
3314 col = cursorX (tty);
3315 row = cursorY (tty);
3316 }
3317
3318 /* Display the help-echo message for the currently-selected menu
3319 item. */
3320 if ((menu_help_message || prev_menu_help_message)
3321 && menu_help_message != prev_menu_help_message)
3322 {
3323 help_callback (menu_help_message,
3324 menu_help_paneno, menu_help_itemno);
3325 /* Move the cursor to the beginning of the current menu
3326 item, so that screen readers and other accessibility aids
3327 know where the active region is. */
3328 cursor_to (sf, row, col);
3329 prev_menu_help_message = menu_help_message;
3330 }
3331 /* Both tty_menu_display and help_callback invoke update_end,
3332 which calls tty_show_cursor. Re-hide it, so it doesn't show
3333 through the menus. */
3334 tty_hide_cursor (tty);
3335 fflush (tty->output);
3336 }
3337
3338 sf->mouse_moved = 0;
3339 screen_update (sf, state[0].screen_behind);
3340 while (statecount--)
3341 free_saved_screen (state[statecount].screen_behind);
3342 tty_show_cursor (tty); /* Turn cursor back on. */
3343 fflush (tty->output);
3344
3345 /* Clean up any mouse events that are waiting inside Emacs event queue.
3346 These events are likely to be generated before the menu was even
3347 displayed, probably because the user pressed and released the button
3348 (which invoked the menu) too quickly. If we don't remove these events,
3349 Emacs will process them after we return and surprise the user. */
3350 discard_mouse_events ();
3351 if (!kbd_buffer_events_waiting ())
3352 clear_input_pending ();
3353 SAFE_FREE ();
3354 return result;
3355 }
3356
3357 /* Dispose of a menu. */
3358
3359 static void
3360 tty_menu_destroy (tty_menu *menu)
3361 {
3362 int i;
3363 if (menu->allocated)
3364 {
3365 for (i = 0; i < menu->count; i++)
3366 if (menu->submenu[i])
3367 tty_menu_destroy (menu->submenu[i]);
3368 xfree (menu->text);
3369 xfree (menu->submenu);
3370 xfree (menu->panenumber);
3371 xfree (menu->help_text);
3372 }
3373 xfree (menu);
3374 menu_help_message = prev_menu_help_message = NULL;
3375 }
3376
3377 /* Show help HELP_STRING, or clear help if HELP_STRING is null.
3378
3379 PANE is the pane number, and ITEM is the menu item number in
3380 the menu (currently not used). */
3381
3382 static void
3383 tty_menu_help_callback (char const *help_string, int pane, int item)
3384 {
3385 Lisp_Object *first_item;
3386 Lisp_Object pane_name;
3387 Lisp_Object menu_object;
3388
3389 first_item = XVECTOR (menu_items)->contents;
3390 if (EQ (first_item[0], Qt))
3391 pane_name = first_item[MENU_ITEMS_PANE_NAME];
3392 else if (EQ (first_item[0], Qquote))
3393 /* This shouldn't happen, see xmenu_show. */
3394 pane_name = empty_unibyte_string;
3395 else
3396 pane_name = first_item[MENU_ITEMS_ITEM_NAME];
3397
3398 /* (menu-item MENU-NAME PANE-NUMBER) */
3399 menu_object = list3 (Qmenu_item, pane_name, make_number (pane));
3400 show_help_echo (help_string ? build_string (help_string) : Qnil,
3401 Qnil, menu_object, make_number (item));
3402 }
3403
3404 static void
3405 tty_pop_down_menu (Lisp_Object arg)
3406 {
3407 tty_menu *menu = XSAVE_POINTER (arg, 0);
3408
3409 block_input ();
3410 tty_menu_destroy (menu);
3411 unblock_input ();
3412 }
3413
3414 /* Return the zero-based index of the last menu-bar item on frame F. */
3415 static int
3416 tty_menu_last_menubar_item (struct frame *f)
3417 {
3418 int i = 0;
3419
3420 eassert (FRAME_TERMCAP_P (f) && FRAME_LIVE_P (f));
3421 if (FRAME_TERMCAP_P (f) && FRAME_LIVE_P (f))
3422 {
3423 Lisp_Object items = FRAME_MENU_BAR_ITEMS (f);
3424
3425 while (i < ASIZE (items))
3426 {
3427 Lisp_Object str;
3428
3429 str = AREF (items, i + 1);
3430 if (NILP (str))
3431 break;
3432 i += 4;
3433 }
3434 i -= 4; /* Went one too far! */
3435 }
3436 return i;
3437 }
3438
3439 /* Find in frame F's menu bar the menu item that is next or previous
3440 to the item at X/Y, and return that item's position in X/Y. WHICH
3441 says which one--next or previous--item to look for. X and Y are
3442 measured in character cells. This should only be called on TTY
3443 frames. */
3444 static void
3445 tty_menu_new_item_coords (struct frame *f, int which, int *x, int *y)
3446 {
3447 eassert (FRAME_TERMCAP_P (f) && FRAME_LIVE_P (f));
3448 if (FRAME_TERMCAP_P (f) && FRAME_LIVE_P (f))
3449 {
3450 Lisp_Object items = FRAME_MENU_BAR_ITEMS (f);
3451 int last_i = tty_menu_last_menubar_item (f);
3452 int i, prev_x;
3453
3454 /* This loop assumes a single menu-bar line, and will fail to
3455 find an item if it is not in the first line. Note that
3456 make_lispy_event in keyboard.c makes the same assumption. */
3457 for (i = 0, prev_x = -1; i < ASIZE (items); i += 4)
3458 {
3459 Lisp_Object pos, str;
3460 int ix;
3461
3462 str = AREF (items, i + 1);
3463 pos = AREF (items, i + 3);
3464 if (NILP (str))
3465 return;
3466 ix = XINT (pos);
3467 if (ix <= *x
3468 /* We use <= so the blank between 2 items on a TTY is
3469 considered part of the previous item. */
3470 && *x <= ix + menu_item_width (SDATA (str)))
3471 {
3472 /* Found current item. Now compute the X coordinate of
3473 the previous or next item. */
3474 if (which == TTYM_NEXT)
3475 {
3476 if (i < last_i)
3477 *x = XINT (AREF (items, i + 4 + 3));
3478 else
3479 *x = 0; /* Wrap around to the first item. */
3480 }
3481 else if (prev_x < 0)
3482 {
3483 /* Wrap around to the last item. */
3484 *x = XINT (AREF (items, last_i + 3));
3485 }
3486 else
3487 *x = prev_x;
3488 return;
3489 }
3490 prev_x = ix;
3491 }
3492 }
3493 }
3494
3495 /* WINDOWSNT uses this as menu_show_hook, see w32console.c. */
3496 Lisp_Object
3497 tty_menu_show (struct frame *f, int x, int y, int menuflags,
3498 Lisp_Object title, const char **error_name)
3499 {
3500 tty_menu *menu;
3501 int pane, selidx, lpane, status;
3502 Lisp_Object entry, pane_prefix;
3503 char *datap;
3504 int ulx, uly, width, height;
3505 int item_x, item_y;
3506 int dispwidth, dispheight;
3507 int i, j, lines, maxlines;
3508 int maxwidth;
3509 ptrdiff_t specpdl_count;
3510
3511 eassert (FRAME_TERMCAP_P (f));
3512
3513 *error_name = 0;
3514 if (menu_items_n_panes == 0)
3515 return Qnil;
3516
3517 if (menu_items_used <= MENU_ITEMS_PANE_LENGTH)
3518 {
3519 *error_name = "Empty menu";
3520 return Qnil;
3521 }
3522
3523 /* Make the menu on that window. */
3524 menu = tty_menu_create ();
3525
3526 /* Don't GC while we prepare and show the menu, because we give the
3527 menu functions pointers to the contents of strings. */
3528 specpdl_count = inhibit_garbage_collection ();
3529
3530 /* Avoid crashes if, e.g., another client will connect while we
3531 are in a menu. */
3532 temporarily_switch_to_single_kboard (f);
3533
3534 /* Adjust coordinates to be root-window-relative. */
3535 item_x = x += f->left_pos;
3536 item_y = y += f->top_pos;
3537
3538 /* Create all the necessary panes and their items. */
3539 USE_SAFE_ALLOCA;
3540 maxwidth = maxlines = lines = i = 0;
3541 lpane = TTYM_FAILURE;
3542 while (i < menu_items_used)
3543 {
3544 if (EQ (AREF (menu_items, i), Qt))
3545 {
3546 /* Create a new pane. */
3547 Lisp_Object pane_name, prefix;
3548 const char *pane_string;
3549
3550 maxlines = max (maxlines, lines);
3551 lines = 0;
3552 pane_name = AREF (menu_items, i + MENU_ITEMS_PANE_NAME);
3553 prefix = AREF (menu_items, i + MENU_ITEMS_PANE_PREFIX);
3554 pane_string = (NILP (pane_name)
3555 ? "" : SSDATA (pane_name));
3556 if ((menuflags & MENU_KEYMAPS) && !NILP (prefix))
3557 pane_string++;
3558
3559 lpane = tty_menu_add_pane (menu, pane_string);
3560 if (lpane == TTYM_FAILURE)
3561 {
3562 tty_menu_destroy (menu);
3563 *error_name = "Can't create pane";
3564 entry = Qnil;
3565 goto tty_menu_end;
3566 }
3567 i += MENU_ITEMS_PANE_LENGTH;
3568
3569 /* Find the width of the widest item in this pane. */
3570 j = i;
3571 while (j < menu_items_used)
3572 {
3573 Lisp_Object item;
3574 item = AREF (menu_items, j);
3575 if (EQ (item, Qt))
3576 break;
3577 if (NILP (item))
3578 {
3579 j++;
3580 continue;
3581 }
3582 width = SBYTES (item);
3583 if (width > maxwidth)
3584 maxwidth = width;
3585
3586 j += MENU_ITEMS_ITEM_LENGTH;
3587 }
3588 }
3589 /* Ignore a nil in the item list.
3590 It's meaningful only for dialog boxes. */
3591 else if (EQ (AREF (menu_items, i), Qquote))
3592 i += 1;
3593 else
3594 {
3595 /* Create a new item within current pane. */
3596 Lisp_Object item_name, enable, descrip, help;
3597 char *item_data;
3598 char const *help_string;
3599
3600 item_name = AREF (menu_items, i + MENU_ITEMS_ITEM_NAME);
3601 enable = AREF (menu_items, i + MENU_ITEMS_ITEM_ENABLE);
3602 descrip = AREF (menu_items, i + MENU_ITEMS_ITEM_EQUIV_KEY);
3603 help = AREF (menu_items, i + MENU_ITEMS_ITEM_HELP);
3604 help_string = STRINGP (help) ? SSDATA (help) : NULL;
3605
3606 if (!NILP (descrip))
3607 {
3608 item_data = SAFE_ALLOCA (maxwidth + SBYTES (descrip) + 1);
3609 memcpy (item_data, SSDATA (item_name), SBYTES (item_name));
3610 for (j = SCHARS (item_name); j < maxwidth; j++)
3611 item_data[j] = ' ';
3612 memcpy (item_data + j, SSDATA (descrip), SBYTES (descrip));
3613 item_data[j + SBYTES (descrip)] = 0;
3614 }
3615 else
3616 item_data = SSDATA (item_name);
3617
3618 if (lpane == TTYM_FAILURE
3619 || (! tty_menu_add_selection (menu, lpane, item_data,
3620 !NILP (enable), help_string)))
3621 {
3622 tty_menu_destroy (menu);
3623 *error_name = "Can't add selection to menu";
3624 entry = Qnil;
3625 goto tty_menu_end;
3626 }
3627 i += MENU_ITEMS_ITEM_LENGTH;
3628 lines++;
3629 }
3630 }
3631
3632 maxlines = max (maxlines, lines);
3633
3634 /* All set and ready to fly. */
3635 dispwidth = f->text_cols;
3636 dispheight = f->text_lines;
3637 x = min (x, dispwidth);
3638 y = min (y, dispheight);
3639 x = max (x, 1);
3640 y = max (y, 1);
3641 tty_menu_locate (menu, x, y, &ulx, &uly, &width, &height);
3642 if (ulx + width > dispwidth)
3643 {
3644 x -= (ulx + width) - dispwidth;
3645 ulx = dispwidth - width;
3646 }
3647 if (uly + height > dispheight)
3648 {
3649 y -= (uly + height) - dispheight;
3650 uly = dispheight - height;
3651 }
3652
3653 if (FRAME_HAS_MINIBUF_P (f) && uly + height > dispheight - 2)
3654 {
3655 /* Move the menu away of the echo area, to avoid overwriting the
3656 menu with help echo messages or vice versa. */
3657 if (BUFFERP (echo_area_buffer[0]) && WINDOWP (echo_area_window))
3658 {
3659 y -= WINDOW_TOTAL_LINES (XWINDOW (echo_area_window)) + 1;
3660 uly -= WINDOW_TOTAL_LINES (XWINDOW (echo_area_window)) + 1;
3661 }
3662 else
3663 {
3664 y -= 2;
3665 uly -= 2;
3666 }
3667 }
3668
3669 if (ulx < 0) x -= ulx;
3670 if (uly < 0) y -= uly;
3671
3672 #if 0
3673 /* This code doesn't make sense on a TTY, since it can easily annul
3674 the adjustments above that carefully avoid truncation of the menu
3675 items. I think it was written to fix some problem that only
3676 happens on X11. */
3677 if (! for_click)
3678 {
3679 /* If position was not given by a mouse click, adjust so upper left
3680 corner of the menu as a whole ends up at given coordinates. This
3681 is what x-popup-menu says in its documentation. */
3682 x += width / 2;
3683 y += 1.5 * height / (maxlines + 2);
3684 }
3685 #endif
3686
3687 pane = selidx = 0;
3688
3689 record_unwind_protect (tty_pop_down_menu, make_save_ptr (menu));
3690
3691 specbind (Qoverriding_terminal_local_map,
3692 Fsymbol_value (Qtty_menu_navigation_map));
3693 status = tty_menu_activate (menu, &pane, &selidx, x, y, &datap,
3694 tty_menu_help_callback,
3695 menuflags & MENU_KBD_NAVIGATION);
3696 entry = pane_prefix = Qnil;
3697
3698 switch (status)
3699 {
3700 case TTYM_SUCCESS:
3701 /* Find the item number SELIDX in pane number PANE. */
3702 i = 0;
3703 while (i < menu_items_used)
3704 {
3705 if (EQ (AREF (menu_items, i), Qt))
3706 {
3707 if (pane == 0)
3708 pane_prefix
3709 = AREF (menu_items, i + MENU_ITEMS_PANE_PREFIX);
3710 pane--;
3711 i += MENU_ITEMS_PANE_LENGTH;
3712 }
3713 else
3714 {
3715 if (pane == -1)
3716 {
3717 if (selidx == 0)
3718 {
3719 entry
3720 = AREF (menu_items, i + MENU_ITEMS_ITEM_VALUE);
3721 if (menuflags & MENU_KEYMAPS)
3722 {
3723 entry = Fcons (entry, Qnil);
3724 if (!NILP (pane_prefix))
3725 entry = Fcons (pane_prefix, entry);
3726 }
3727 break;
3728 }
3729 selidx--;
3730 }
3731 i += MENU_ITEMS_ITEM_LENGTH;
3732 }
3733 }
3734 break;
3735
3736 case TTYM_NEXT:
3737 case TTYM_PREV:
3738 tty_menu_new_item_coords (f, status, &item_x, &item_y);
3739 entry = Fcons (make_number (item_x), make_number (item_y));
3740 break;
3741
3742 case TTYM_FAILURE:
3743 *error_name = "Can't activate menu";
3744 case TTYM_IA_SELECT:
3745 break;
3746 case TTYM_NO_SELECT:
3747 /* If the selected frame was changed while we displayed a menu,
3748 throw to top level in order to undo any temporary settings
3749 made by TTY menu code. */
3750 if (f != SELECTED_FRAME ())
3751 Ftop_level ();
3752 /* Make "Cancel" equivalent to C-g unless FOR_CLICK (which means
3753 the menu was invoked with a mouse event as POSITION). */
3754 if (!(menuflags & MENU_FOR_CLICK))
3755 Fsignal (Qquit, Qnil);
3756 break;
3757 }
3758
3759 tty_menu_end:
3760
3761 SAFE_FREE ();
3762 unbind_to (specpdl_count, Qnil);
3763 return entry;
3764 }
3765
3766 #endif /* !MSDOS */
3767
3768 \f
3769 #ifndef MSDOS
3770 /***********************************************************************
3771 Initialization
3772 ***********************************************************************/
3773
3774 /* Initialize the tty-dependent part of frame F. The frame must
3775 already have its device initialized. */
3776
3777 void
3778 create_tty_output (struct frame *f)
3779 {
3780 struct tty_output *t = xzalloc (sizeof *t);
3781
3782 eassert (FRAME_TERMCAP_P (f));
3783
3784 t->display_info = FRAME_TERMINAL (f)->display_info.tty;
3785
3786 f->output_data.tty = t;
3787 }
3788
3789 /* Delete frame F's face cache, and its tty-dependent part. */
3790
3791 static void
3792 tty_free_frame_resources (struct frame *f)
3793 {
3794 eassert (FRAME_TERMCAP_P (f));
3795 free_frame_faces (f);
3796 xfree (f->output_data.tty);
3797 }
3798
3799 #else /* MSDOS */
3800
3801 /* Delete frame F's face cache. */
3802
3803 static void
3804 tty_free_frame_resources (struct frame *f)
3805 {
3806 eassert (FRAME_TERMCAP_P (f) || FRAME_MSDOS_P (f));
3807 free_frame_faces (f);
3808 }
3809 #endif /* MSDOS */
3810 \f
3811 /* Reset the hooks in TERMINAL. */
3812
3813 static void
3814 clear_tty_hooks (struct terminal *terminal)
3815 {
3816 terminal->rif = 0;
3817 terminal->cursor_to_hook = 0;
3818 terminal->raw_cursor_to_hook = 0;
3819 terminal->clear_to_end_hook = 0;
3820 terminal->clear_frame_hook = 0;
3821 terminal->clear_end_of_line_hook = 0;
3822 terminal->ins_del_lines_hook = 0;
3823 terminal->insert_glyphs_hook = 0;
3824 terminal->write_glyphs_hook = 0;
3825 terminal->delete_glyphs_hook = 0;
3826 terminal->ring_bell_hook = 0;
3827 terminal->reset_terminal_modes_hook = 0;
3828 terminal->set_terminal_modes_hook = 0;
3829 terminal->update_begin_hook = 0;
3830 terminal->update_end_hook = 0;
3831 terminal->set_terminal_window_hook = 0;
3832 terminal->mouse_position_hook = 0;
3833 terminal->frame_rehighlight_hook = 0;
3834 terminal->frame_raise_lower_hook = 0;
3835 terminal->fullscreen_hook = 0;
3836 terminal->menu_show_hook = 0;
3837 terminal->set_vertical_scroll_bar_hook = 0;
3838 terminal->set_horizontal_scroll_bar_hook = 0;
3839 terminal->condemn_scroll_bars_hook = 0;
3840 terminal->redeem_scroll_bar_hook = 0;
3841 terminal->judge_scroll_bars_hook = 0;
3842 terminal->read_socket_hook = 0;
3843 terminal->frame_up_to_date_hook = 0;
3844
3845 /* Leave these two set, or suspended frames are not deleted
3846 correctly. */
3847 terminal->delete_frame_hook = &tty_free_frame_resources;
3848 terminal->delete_terminal_hook = &delete_tty;
3849 }
3850
3851 /* Initialize hooks in TERMINAL with the values needed for a tty. */
3852
3853 static void
3854 set_tty_hooks (struct terminal *terminal)
3855 {
3856 terminal->cursor_to_hook = &tty_cursor_to;
3857 terminal->raw_cursor_to_hook = &tty_raw_cursor_to;
3858 terminal->clear_to_end_hook = &tty_clear_to_end;
3859 terminal->clear_frame_hook = &tty_clear_frame;
3860 terminal->clear_end_of_line_hook = &tty_clear_end_of_line;
3861 terminal->ins_del_lines_hook = &tty_ins_del_lines;
3862 terminal->insert_glyphs_hook = &tty_insert_glyphs;
3863 terminal->write_glyphs_hook = &tty_write_glyphs;
3864 terminal->delete_glyphs_hook = &tty_delete_glyphs;
3865 terminal->ring_bell_hook = &tty_ring_bell;
3866 terminal->reset_terminal_modes_hook = &tty_reset_terminal_modes;
3867 terminal->set_terminal_modes_hook = &tty_set_terminal_modes;
3868 terminal->update_end_hook = &tty_update_end;
3869 #ifdef MSDOS
3870 terminal->menu_show_hook = &x_menu_show;
3871 #else
3872 terminal->menu_show_hook = &tty_menu_show;
3873 #endif
3874 terminal->set_terminal_window_hook = &tty_set_terminal_window;
3875 terminal->read_socket_hook = &tty_read_avail_input; /* keyboard.c */
3876 terminal->delete_frame_hook = &tty_free_frame_resources;
3877 terminal->delete_terminal_hook = &delete_tty;
3878 /* Other hooks are NULL by default. */
3879 }
3880
3881 /* If FD is the controlling terminal, drop it. */
3882 static void
3883 dissociate_if_controlling_tty (int fd)
3884 {
3885 /* If tcgetpgrp succeeds, fd is the controlling terminal,
3886 so dissociate it by invoking setsid. */
3887 if (tcgetpgrp (fd) >= 0 && setsid () < 0)
3888 {
3889 #ifdef TIOCNOTTY
3890 /* setsid failed, presumably because Emacs is already a process
3891 group leader. Fall back on the obsolescent way to dissociate
3892 a controlling tty. */
3893 sigset_t oldset;
3894 block_tty_out_signal (&oldset);
3895 ioctl (fd, TIOCNOTTY, 0);
3896 unblock_tty_out_signal (&oldset);
3897 #endif
3898 }
3899 }
3900
3901 /* Create a termcap display on the tty device with the given name and
3902 type.
3903
3904 If NAME is NULL, then use the controlling tty, i.e., "/dev/tty".
3905 Otherwise NAME should be a path to the tty device file,
3906 e.g. "/dev/pts/7".
3907
3908 TERMINAL_TYPE is the termcap type of the device, e.g. "vt100".
3909
3910 If MUST_SUCCEED is true, then all errors are fatal. */
3911
3912 struct terminal *
3913 init_tty (const char *name, const char *terminal_type, bool must_succeed)
3914 {
3915 char *area;
3916 char **address = &area;
3917 int status;
3918 struct tty_display_info *tty = NULL;
3919 struct terminal *terminal = NULL;
3920 sigset_t oldset;
3921 bool ctty = false; /* True if asked to open controlling tty. */
3922
3923 if (!terminal_type)
3924 maybe_fatal (must_succeed, 0,
3925 "Unknown terminal type",
3926 "Unknown terminal type");
3927
3928 if (name == NULL)
3929 name = DEV_TTY;
3930 if (!strcmp (name, DEV_TTY))
3931 ctty = 1;
3932
3933 /* If we already have a terminal on the given device, use that. If
3934 all such terminals are suspended, create a new one instead. */
3935 /* XXX Perhaps this should be made explicit by having init_tty
3936 always create a new terminal and separating terminal and frame
3937 creation on Lisp level. */
3938 terminal = get_named_terminal (name);
3939 if (terminal)
3940 return terminal;
3941
3942 terminal = create_terminal (output_termcap, NULL);
3943 #ifdef MSDOS
3944 if (been_here > 0)
3945 maybe_fatal (0, 0, "Attempt to create another terminal %s", "",
3946 name, "");
3947 been_here = 1;
3948 tty = &the_only_display_info;
3949 #else
3950 tty = xzalloc (sizeof *tty);
3951 #endif
3952 tty->top_frame = Qnil;
3953 tty->next = tty_list;
3954 tty_list = tty;
3955
3956 terminal->display_info.tty = tty;
3957 tty->terminal = terminal;
3958
3959 tty->Wcm = xmalloc (sizeof *tty->Wcm);
3960 Wcm_clear (tty);
3961
3962 encode_terminal_src_size = 0;
3963 encode_terminal_dst_size = 0;
3964
3965
3966 #ifndef DOS_NT
3967 set_tty_hooks (terminal);
3968
3969 {
3970 /* Open the terminal device. */
3971
3972 /* If !ctty, don't recognize it as our controlling terminal, and
3973 don't make it the controlling tty if we don't have one now.
3974
3975 Alas, O_IGNORE_CTTY is a GNU extension that seems to be only
3976 defined on Hurd. On other systems, we need to explicitly
3977 dissociate ourselves from the controlling tty when we want to
3978 open a frame on the same terminal. */
3979 int flags = O_RDWR | O_NOCTTY | (ctty ? 0 : O_IGNORE_CTTY);
3980 int fd = emacs_open (name, flags, 0);
3981 tty->input = tty->output
3982 = ((fd < 0 || ! isatty (fd))
3983 ? NULL
3984 : fdopen (fd, "w+"));
3985
3986 if (! tty->input)
3987 {
3988 char const *diagnostic
3989 = (fd < 0) ? "Could not open file: %s" : "Not a tty device: %s";
3990 emacs_close (fd);
3991 maybe_fatal (must_succeed, terminal, diagnostic, diagnostic, name);
3992 }
3993
3994 tty->name = xstrdup (name);
3995 terminal->name = xstrdup (name);
3996
3997 if (!O_IGNORE_CTTY && !ctty)
3998 dissociate_if_controlling_tty (fd);
3999 }
4000
4001 tty->type = xstrdup (terminal_type);
4002
4003 add_keyboard_wait_descriptor (fileno (tty->input));
4004
4005 Wcm_clear (tty);
4006
4007 /* On some systems, tgetent tries to access the controlling
4008 terminal. */
4009 block_tty_out_signal (&oldset);
4010 status = tgetent (tty->termcap_term_buffer, terminal_type);
4011 if (tty->termcap_term_buffer[TERMCAP_BUFFER_SIZE - 1])
4012 emacs_abort ();
4013 unblock_tty_out_signal (&oldset);
4014
4015 if (status < 0)
4016 {
4017 #ifdef TERMINFO
4018 maybe_fatal (must_succeed, terminal,
4019 "Cannot open terminfo database file",
4020 "Cannot open terminfo database file");
4021 #else
4022 maybe_fatal (must_succeed, terminal,
4023 "Cannot open termcap database file",
4024 "Cannot open termcap database file");
4025 #endif
4026 }
4027 if (status == 0)
4028 {
4029 maybe_fatal (must_succeed, terminal,
4030 "Terminal type %s is not defined",
4031 "Terminal type %s is not defined.\n\
4032 If that is not the actual type of terminal you have,\n\
4033 use the Bourne shell command `TERM=... export TERM' (C-shell:\n\
4034 `setenv TERM ...') to specify the correct type. It may be necessary\n"
4035 #ifdef TERMINFO
4036 "to do `unset TERMINFO' (C-shell: `unsetenv TERMINFO') as well.",
4037 #else
4038 "to do `unset TERMCAP' (C-shell: `unsetenv TERMCAP') as well.",
4039 #endif
4040 terminal_type);
4041 }
4042
4043 area = tty->termcap_strings_buffer;
4044 tty->TS_ins_line = tgetstr ("al", address);
4045 tty->TS_ins_multi_lines = tgetstr ("AL", address);
4046 tty->TS_bell = tgetstr ("bl", address);
4047 BackTab (tty) = tgetstr ("bt", address);
4048 tty->TS_clr_to_bottom = tgetstr ("cd", address);
4049 tty->TS_clr_line = tgetstr ("ce", address);
4050 tty->TS_clr_frame = tgetstr ("cl", address);
4051 ColPosition (tty) = NULL; /* tgetstr ("ch", address); */
4052 AbsPosition (tty) = tgetstr ("cm", address);
4053 CR (tty) = tgetstr ("cr", address);
4054 tty->TS_set_scroll_region = tgetstr ("cs", address);
4055 tty->TS_set_scroll_region_1 = tgetstr ("cS", address);
4056 RowPosition (tty) = tgetstr ("cv", address);
4057 tty->TS_del_char = tgetstr ("dc", address);
4058 tty->TS_del_multi_chars = tgetstr ("DC", address);
4059 tty->TS_del_line = tgetstr ("dl", address);
4060 tty->TS_del_multi_lines = tgetstr ("DL", address);
4061 tty->TS_delete_mode = tgetstr ("dm", address);
4062 tty->TS_end_delete_mode = tgetstr ("ed", address);
4063 tty->TS_end_insert_mode = tgetstr ("ei", address);
4064 Home (tty) = tgetstr ("ho", address);
4065 tty->TS_ins_char = tgetstr ("ic", address);
4066 tty->TS_ins_multi_chars = tgetstr ("IC", address);
4067 tty->TS_insert_mode = tgetstr ("im", address);
4068 tty->TS_pad_inserted_char = tgetstr ("ip", address);
4069 tty->TS_end_keypad_mode = tgetstr ("ke", address);
4070 tty->TS_keypad_mode = tgetstr ("ks", address);
4071 LastLine (tty) = tgetstr ("ll", address);
4072 Right (tty) = tgetstr ("nd", address);
4073 Down (tty) = tgetstr ("do", address);
4074 if (!Down (tty))
4075 Down (tty) = tgetstr ("nl", address); /* Obsolete name for "do". */
4076 if (tgetflag ("bs"))
4077 Left (tty) = "\b"; /* Can't possibly be longer! */
4078 else /* (Actually, "bs" is obsolete...) */
4079 Left (tty) = tgetstr ("le", address);
4080 if (!Left (tty))
4081 Left (tty) = tgetstr ("bc", address); /* Obsolete name for "le". */
4082 tty->TS_pad_char = tgetstr ("pc", address);
4083 tty->TS_repeat = tgetstr ("rp", address);
4084 tty->TS_end_standout_mode = tgetstr ("se", address);
4085 tty->TS_fwd_scroll = tgetstr ("sf", address);
4086 tty->TS_standout_mode = tgetstr ("so", address);
4087 tty->TS_rev_scroll = tgetstr ("sr", address);
4088 tty->Wcm->cm_tab = tgetstr ("ta", address);
4089 tty->TS_end_termcap_modes = tgetstr ("te", address);
4090 tty->TS_termcap_modes = tgetstr ("ti", address);
4091 Up (tty) = tgetstr ("up", address);
4092 tty->TS_visible_bell = tgetstr ("vb", address);
4093 tty->TS_cursor_normal = tgetstr ("ve", address);
4094 tty->TS_cursor_visible = tgetstr ("vs", address);
4095 tty->TS_cursor_invisible = tgetstr ("vi", address);
4096 tty->TS_set_window = tgetstr ("wi", address);
4097
4098 tty->TS_enter_underline_mode = tgetstr ("us", address);
4099 tty->TS_exit_underline_mode = tgetstr ("ue", address);
4100 tty->TS_enter_bold_mode = tgetstr ("md", address);
4101 tty->TS_enter_italic_mode = tgetstr ("ZH", address);
4102 tty->TS_enter_dim_mode = tgetstr ("mh", address);
4103 tty->TS_enter_reverse_mode = tgetstr ("mr", address);
4104 tty->TS_enter_alt_charset_mode = tgetstr ("as", address);
4105 tty->TS_exit_alt_charset_mode = tgetstr ("ae", address);
4106 tty->TS_exit_attribute_mode = tgetstr ("me", address);
4107
4108 MultiUp (tty) = tgetstr ("UP", address);
4109 MultiDown (tty) = tgetstr ("DO", address);
4110 MultiLeft (tty) = tgetstr ("LE", address);
4111 MultiRight (tty) = tgetstr ("RI", address);
4112
4113 /* SVr4/ANSI color support. If "op" isn't available, don't support
4114 color because we can't switch back to the default foreground and
4115 background. */
4116 tty->TS_orig_pair = tgetstr ("op", address);
4117 if (tty->TS_orig_pair)
4118 {
4119 tty->TS_set_foreground = tgetstr ("AF", address);
4120 tty->TS_set_background = tgetstr ("AB", address);
4121 if (!tty->TS_set_foreground)
4122 {
4123 /* SVr4. */
4124 tty->TS_set_foreground = tgetstr ("Sf", address);
4125 tty->TS_set_background = tgetstr ("Sb", address);
4126 }
4127
4128 tty->TN_max_colors = tgetnum ("Co");
4129 tty->TN_max_pairs = tgetnum ("pa");
4130
4131 tty->TN_no_color_video = tgetnum ("NC");
4132 if (tty->TN_no_color_video == -1)
4133 tty->TN_no_color_video = 0;
4134 }
4135
4136 tty_default_color_capabilities (tty, 1);
4137
4138 MagicWrap (tty) = tgetflag ("xn");
4139 /* Since we make MagicWrap terminals look like AutoWrap, we need to have
4140 the former flag imply the latter. */
4141 AutoWrap (tty) = MagicWrap (tty) || tgetflag ("am");
4142 tty->memory_below_frame = tgetflag ("db");
4143 tty->TF_hazeltine = tgetflag ("hz");
4144 tty->must_write_spaces = tgetflag ("in");
4145 tty->meta_key = tgetflag ("km") || tgetflag ("MT");
4146 tty->TF_insmode_motion = tgetflag ("mi");
4147 tty->TF_standout_motion = tgetflag ("ms");
4148 tty->TF_underscore = tgetflag ("ul");
4149 tty->TF_teleray = tgetflag ("xt");
4150
4151 #else /* DOS_NT */
4152 #ifdef WINDOWSNT
4153 {
4154 struct frame *f = XFRAME (selected_frame);
4155 int height, width;
4156
4157 initialize_w32_display (terminal, &width, &height);
4158
4159 FrameRows (tty) = height;
4160 FrameCols (tty) = width;
4161 tty->specified_window = height;
4162
4163 FRAME_VERTICAL_SCROLL_BAR_TYPE (f) = vertical_scroll_bar_none;
4164 FRAME_HAS_HORIZONTAL_SCROLL_BARS (f) = 0;
4165 tty->char_ins_del_ok = 1;
4166 baud_rate = 19200;
4167 }
4168 #else /* MSDOS */
4169 {
4170 int height, width;
4171 if (strcmp (terminal_type, "internal") == 0)
4172 terminal->type = output_msdos_raw;
4173 initialize_msdos_display (terminal);
4174
4175 get_tty_size (fileno (tty->input), &width, &height);
4176 FrameCols (tty) = width;
4177 FrameRows (tty) = height;
4178 tty->char_ins_del_ok = 0;
4179 init_baud_rate (fileno (tty->input));
4180 }
4181 #endif /* MSDOS */
4182 tty->output = stdout;
4183 tty->input = stdin;
4184 /* The following two are inaccessible from w32console.c. */
4185 terminal->delete_frame_hook = &tty_free_frame_resources;
4186 terminal->delete_terminal_hook = &delete_tty;
4187
4188 tty->name = xstrdup (name);
4189 terminal->name = xstrdup (name);
4190 tty->type = xstrdup (terminal_type);
4191
4192 add_keyboard_wait_descriptor (0);
4193
4194 tty->delete_in_insert_mode = 1;
4195
4196 UseTabs (tty) = 0;
4197 tty->scroll_region_ok = 0;
4198
4199 /* Seems to insert lines when it's not supposed to, messing up the
4200 display. In doing a trace, it didn't seem to be called much, so I
4201 don't think we're losing anything by turning it off. */
4202 tty->line_ins_del_ok = 0;
4203
4204 tty->TN_max_colors = 16; /* Must be non-zero for tty-display-color-p. */
4205 #endif /* DOS_NT */
4206
4207 #ifdef HAVE_GPM
4208 terminal->mouse_position_hook = term_mouse_position;
4209 tty->mouse_highlight.mouse_face_window = Qnil;
4210 #endif
4211
4212 terminal->kboard = allocate_kboard (Qnil);
4213 terminal->kboard->reference_count++;
4214 /* Don't let the initial kboard remain current longer than necessary.
4215 That would cause problems if a file loaded on startup tries to
4216 prompt in the mini-buffer. */
4217 if (current_kboard == initial_kboard)
4218 current_kboard = terminal->kboard;
4219 #ifndef DOS_NT
4220 term_get_fkeys (address, terminal->kboard);
4221
4222 /* Get frame size from system, or else from termcap. */
4223 {
4224 int height, width;
4225 get_tty_size (fileno (tty->input), &width, &height);
4226 FrameCols (tty) = width;
4227 FrameRows (tty) = height;
4228 }
4229
4230 if (FrameCols (tty) <= 0)
4231 FrameCols (tty) = tgetnum ("co");
4232 if (FrameRows (tty) <= 0)
4233 FrameRows (tty) = tgetnum ("li");
4234
4235 if (FrameRows (tty) < 3 || FrameCols (tty) < 3)
4236 maybe_fatal (must_succeed, terminal,
4237 "Screen size %dx%d is too small",
4238 "Screen size %dx%d is too small",
4239 FrameCols (tty), FrameRows (tty));
4240
4241 TabWidth (tty) = tgetnum ("tw");
4242
4243 if (!tty->TS_bell)
4244 tty->TS_bell = "\07";
4245
4246 if (!tty->TS_fwd_scroll)
4247 tty->TS_fwd_scroll = Down (tty);
4248
4249 PC = tty->TS_pad_char ? *tty->TS_pad_char : 0;
4250
4251 if (TabWidth (tty) < 0)
4252 TabWidth (tty) = 8;
4253
4254 /* Turned off since /etc/termcap seems to have :ta= for most terminals
4255 and newer termcap doc does not seem to say there is a default.
4256 if (!tty->Wcm->cm_tab)
4257 tty->Wcm->cm_tab = "\t";
4258 */
4259
4260 /* We don't support standout modes that use `magic cookies', so
4261 turn off any that do. */
4262 if (tty->TS_standout_mode && tgetnum ("sg") >= 0)
4263 {
4264 tty->TS_standout_mode = 0;
4265 tty->TS_end_standout_mode = 0;
4266 }
4267 if (tty->TS_enter_underline_mode && tgetnum ("ug") >= 0)
4268 {
4269 tty->TS_enter_underline_mode = 0;
4270 tty->TS_exit_underline_mode = 0;
4271 }
4272
4273 /* If there's no standout mode, try to use underlining instead. */
4274 if (tty->TS_standout_mode == 0)
4275 {
4276 tty->TS_standout_mode = tty->TS_enter_underline_mode;
4277 tty->TS_end_standout_mode = tty->TS_exit_underline_mode;
4278 }
4279
4280 /* If no `se' string, try using a `me' string instead.
4281 If that fails, we can't use standout mode at all. */
4282 if (tty->TS_end_standout_mode == 0)
4283 {
4284 char *s = tgetstr ("me", address);
4285 if (s != 0)
4286 tty->TS_end_standout_mode = s;
4287 else
4288 tty->TS_standout_mode = 0;
4289 }
4290
4291 if (tty->TF_teleray)
4292 {
4293 tty->Wcm->cm_tab = 0;
4294 /* We can't support standout mode, because it uses magic cookies. */
4295 tty->TS_standout_mode = 0;
4296 /* But that means we cannot rely on ^M to go to column zero! */
4297 CR (tty) = 0;
4298 /* LF can't be trusted either -- can alter hpos. */
4299 /* If move at column 0 thru a line with TS_standout_mode. */
4300 Down (tty) = 0;
4301 }
4302
4303 tty->specified_window = FrameRows (tty);
4304
4305 if (Wcm_init (tty) == -1) /* Can't do cursor motion. */
4306 {
4307 maybe_fatal (must_succeed, terminal,
4308 "Terminal type \"%s\" is not powerful enough to run Emacs",
4309 "Terminal type \"%s\" is not powerful enough to run Emacs.\n\
4310 It lacks the ability to position the cursor.\n\
4311 If that is not the actual type of terminal you have,\n\
4312 use the Bourne shell command `TERM=... export TERM' (C-shell:\n\
4313 `setenv TERM ...') to specify the correct type. It may be necessary\n"
4314 # ifdef TERMINFO
4315 "to do `unset TERMINFO' (C-shell: `unsetenv TERMINFO') as well.",
4316 # else /* TERMCAP */
4317 "to do `unset TERMCAP' (C-shell: `unsetenv TERMCAP') as well.",
4318 # endif /* TERMINFO */
4319 terminal_type);
4320 }
4321
4322 if (FrameRows (tty) <= 0 || FrameCols (tty) <= 0)
4323 maybe_fatal (must_succeed, terminal,
4324 "Could not determine the frame size",
4325 "Could not determine the frame size");
4326
4327 tty->delete_in_insert_mode
4328 = tty->TS_delete_mode && tty->TS_insert_mode
4329 && !strcmp (tty->TS_delete_mode, tty->TS_insert_mode);
4330
4331 UseTabs (tty) = tabs_safe_p (fileno (tty->input)) && TabWidth (tty) == 8;
4332
4333 tty->scroll_region_ok
4334 = (tty->Wcm->cm_abs
4335 && (tty->TS_set_window || tty->TS_set_scroll_region || tty->TS_set_scroll_region_1));
4336
4337 tty->line_ins_del_ok
4338 = (((tty->TS_ins_line || tty->TS_ins_multi_lines)
4339 && (tty->TS_del_line || tty->TS_del_multi_lines))
4340 || (tty->scroll_region_ok
4341 && tty->TS_fwd_scroll && tty->TS_rev_scroll));
4342
4343 tty->char_ins_del_ok
4344 = ((tty->TS_ins_char || tty->TS_insert_mode
4345 || tty->TS_pad_inserted_char || tty->TS_ins_multi_chars)
4346 && (tty->TS_del_char || tty->TS_del_multi_chars));
4347
4348 init_baud_rate (fileno (tty->input));
4349
4350 #endif /* not DOS_NT */
4351
4352 /* Init system terminal modes (RAW or CBREAK, etc.). */
4353 init_sys_modes (tty);
4354
4355 return terminal;
4356 }
4357
4358
4359 static void
4360 vfatal (const char *str, va_list ap)
4361 {
4362 fprintf (stderr, "emacs: ");
4363 vfprintf (stderr, str, ap);
4364 if (!(strlen (str) > 0 && str[strlen (str) - 1] == '\n'))
4365 fprintf (stderr, "\n");
4366 fflush (stderr);
4367 exit (1);
4368 }
4369
4370
4371 /* Auxiliary error-handling function for init_tty.
4372 Delete TERMINAL, then call error or fatal with str1 or str2,
4373 respectively, according to whether MUST_SUCCEED is true. */
4374
4375 static void
4376 maybe_fatal (bool must_succeed, struct terminal *terminal,
4377 const char *str1, const char *str2, ...)
4378 {
4379 va_list ap;
4380 va_start (ap, str2);
4381 if (terminal)
4382 delete_tty (terminal);
4383
4384 if (must_succeed)
4385 vfatal (str2, ap);
4386 else
4387 verror (str1, ap);
4388 }
4389
4390 void
4391 fatal (const char *str, ...)
4392 {
4393 va_list ap;
4394 va_start (ap, str);
4395 vfatal (str, ap);
4396 }
4397
4398 \f
4399
4400 /* Delete the given tty terminal, closing all frames on it. */
4401
4402 static void
4403 delete_tty (struct terminal *terminal)
4404 {
4405 struct tty_display_info *tty;
4406
4407 /* Protect against recursive calls. delete_frame in
4408 delete_terminal calls us back when it deletes our last frame. */
4409 if (!terminal->name)
4410 return;
4411
4412 eassert (terminal->type == output_termcap);
4413
4414 tty = terminal->display_info.tty;
4415
4416 if (tty == tty_list)
4417 tty_list = tty->next;
4418 else
4419 {
4420 struct tty_display_info *p;
4421 for (p = tty_list; p && p->next != tty; p = p->next)
4422 ;
4423
4424 if (! p)
4425 /* This should not happen. */
4426 emacs_abort ();
4427
4428 p->next = tty->next;
4429 tty->next = 0;
4430 }
4431
4432 /* reset_sys_modes needs a valid device, so this call needs to be
4433 before delete_terminal. */
4434 reset_sys_modes (tty);
4435
4436 delete_terminal (terminal);
4437
4438 xfree (tty->name);
4439 xfree (tty->type);
4440
4441 if (tty->input)
4442 {
4443 delete_keyboard_wait_descriptor (fileno (tty->input));
4444 if (tty->input != stdin)
4445 fclose (tty->input);
4446 }
4447 if (tty->output && tty->output != stdout && tty->output != tty->input)
4448 fclose (tty->output);
4449 if (tty->termscript)
4450 fclose (tty->termscript);
4451
4452 xfree (tty->old_tty);
4453 xfree (tty->Wcm);
4454 xfree (tty);
4455 }
4456
4457 void
4458 syms_of_term (void)
4459 {
4460 DEFVAR_BOOL ("system-uses-terminfo", system_uses_terminfo,
4461 doc: /* Non-nil means the system uses terminfo rather than termcap.
4462 This variable can be used by terminal emulator packages. */);
4463 #ifdef TERMINFO
4464 system_uses_terminfo = 1;
4465 #else
4466 system_uses_terminfo = 0;
4467 #endif
4468
4469 DEFVAR_LISP ("suspend-tty-functions", Vsuspend_tty_functions,
4470 doc: /* Functions run after suspending a tty.
4471 The functions are run with one argument, the terminal object to be suspended.
4472 See `suspend-tty'. */);
4473 Vsuspend_tty_functions = Qnil;
4474
4475
4476 DEFVAR_LISP ("resume-tty-functions", Vresume_tty_functions,
4477 doc: /* Functions run after resuming a tty.
4478 The functions are run with one argument, the terminal object that was revived.
4479 See `resume-tty'. */);
4480 Vresume_tty_functions = Qnil;
4481
4482 DEFVAR_BOOL ("visible-cursor", visible_cursor,
4483 doc: /* Non-nil means to make the cursor very visible.
4484 This only has an effect when running in a text terminal.
4485 What means \"very visible\" is up to your terminal. It may make the cursor
4486 bigger, or it may make it blink, or it may do nothing at all. */);
4487 visible_cursor = 1;
4488
4489 defsubr (&Stty_display_color_p);
4490 defsubr (&Stty_display_color_cells);
4491 defsubr (&Stty_no_underline);
4492 defsubr (&Stty_type);
4493 defsubr (&Scontrolling_tty_p);
4494 defsubr (&Stty_top_frame);
4495 defsubr (&Ssuspend_tty);
4496 defsubr (&Sresume_tty);
4497 #ifdef HAVE_GPM
4498 defsubr (&Sgpm_mouse_start);
4499 defsubr (&Sgpm_mouse_stop);
4500 #endif /* HAVE_GPM */
4501
4502 #ifndef DOS_NT
4503 default_orig_pair = NULL;
4504 default_set_foreground = NULL;
4505 default_set_background = NULL;
4506 #endif /* !DOS_NT */
4507
4508 encode_terminal_src = NULL;
4509 encode_terminal_dst = NULL;
4510
4511 DEFSYM (Qtty_mode_set_strings, "tty-mode-set-strings");
4512 DEFSYM (Qtty_mode_reset_strings, "tty-mode-reset-strings");
4513
4514 #ifndef MSDOS
4515 DEFSYM (Qtty_menu_next_item, "tty-menu-next-item");
4516 DEFSYM (Qtty_menu_prev_item, "tty-menu-prev-item");
4517 DEFSYM (Qtty_menu_next_menu, "tty-menu-next-menu");
4518 DEFSYM (Qtty_menu_prev_menu, "tty-menu-prev-menu");
4519 DEFSYM (Qtty_menu_select, "tty-menu-select");
4520 DEFSYM (Qtty_menu_ignore, "tty-menu-ignore");
4521 DEFSYM (Qtty_menu_exit, "tty-menu-exit");
4522 DEFSYM (Qtty_menu_mouse_movement, "tty-menu-mouse-movement");
4523 DEFSYM (Qtty_menu_navigation_map, "tty-menu-navigation-map");
4524 #endif
4525 }