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