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