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