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