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