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