1 /*
2 * Copyright (C) 1984-2024 Mark Nudelman
3 *
4 * You may distribute under the terms of either the GNU General Public
5 * License or the Less License, as specified in the README file.
6 *
7 * For more information, see the README file.
8 */
9
10
11 /*
12 * Routines which deal with the characteristics of the terminal.
13 * Uses termcap to be as terminal-independent as possible.
14 */
15
16 #include "less.h"
17 #include "cmd.h"
18
19 #if MSDOS_COMPILER
20 #include "pckeys.h"
21 #if MSDOS_COMPILER==MSOFTC
22 #include <graph.h>
23 #else
24 #if MSDOS_COMPILER==BORLANDC || MSDOS_COMPILER==DJGPPC
25 #include <conio.h>
26 #if MSDOS_COMPILER==DJGPPC
27 #include <pc.h>
28 extern int fd0;
29 #endif
30 #else
31 #if MSDOS_COMPILER==WIN32C
32 #include <windows.h>
33 #endif
34 #endif
35 #endif
36 #include <time.h>
37
38 #ifndef FOREGROUND_BLUE
39 #define FOREGROUND_BLUE 0x0001
40 #endif
41 #ifndef FOREGROUND_GREEN
42 #define FOREGROUND_GREEN 0x0002
43 #endif
44 #ifndef FOREGROUND_RED
45 #define FOREGROUND_RED 0x0004
46 #endif
47 #ifndef FOREGROUND_INTENSITY
48 #define FOREGROUND_INTENSITY 0x0008
49 #endif
50
51 #else
52
53 #if HAVE_SYS_IOCTL_H
54 #include <sys/ioctl.h>
55 #endif
56
57 #if HAVE_TERMIOS_H && HAVE_TERMIOS_FUNCS
58 #include <termios.h>
59 #else
60 #if HAVE_TERMIO_H
61 #include <termio.h>
62 #else
63 #if HAVE_SGSTAT_H
64 #include <sgstat.h>
65 #else
66 #include <sgtty.h>
67 #endif
68 #endif
69 #endif
70
71 #if HAVE_NCURSESW_TERMCAP_H
72 #include <ncursesw/termcap.h>
73 #else
74 #if HAVE_NCURSES_TERMCAP_H
75 #include <ncurses/termcap.h>
76 #else
77 #if HAVE_TERMCAP_H
78 #include <termcap.h>
79 #endif
80 #endif
81 #endif
82 #ifdef _OSK
83 #include <signal.h>
84 #endif
85 #if OS2
86 #include <sys/signal.h>
87 #include "pckeys.h"
88 #endif
89 #if HAVE_SYS_STREAM_H
90 #include <sys/stream.h>
91 #endif
92 #if HAVE_SYS_PTEM_H
93 #include <sys/ptem.h>
94 #endif
95
96 #endif /* MSDOS_COMPILER */
97
98 /*
99 * Check for broken termios package that forces you to manually
100 * set the line discipline.
101 */
102 #ifdef __ultrix__
103 #define MUST_SET_LINE_DISCIPLINE 1
104 #else
105 #define MUST_SET_LINE_DISCIPLINE 0
106 #endif
107
108 #if OS2
109 #define DEFAULT_TERM "ansi"
110 static char *windowid;
111 #else
112 #define DEFAULT_TERM "unknown"
113 #endif
114
115 #if MSDOS_COMPILER==MSOFTC
116 static int videopages;
117 static long msec_loops;
118 static int flash_created = 0;
119 #define SET_FG_COLOR(fg) _settextcolor(fg)
120 #define SET_BG_COLOR(bg) _setbkcolor(bg)
121 #define SETCOLORS(fg,bg) { SET_FG_COLOR(fg); SET_BG_COLOR(bg); }
122 #endif
123
124 #if MSDOS_COMPILER==BORLANDC
125 static unsigned short *whitescreen;
126 static int flash_created = 0;
127 #endif
128 #if MSDOS_COMPILER==BORLANDC || MSDOS_COMPILER==DJGPPC
129 #define _settextposition(y,x) gotoxy(x,y)
130 #define _clearscreen(m) clrscr()
131 #define _outtext(s) cputs(s)
132 #define SET_FG_COLOR(fg) textcolor(fg)
133 #define SET_BG_COLOR(bg) textbackground(bg)
134 #define SETCOLORS(fg,bg) { SET_FG_COLOR(fg); SET_BG_COLOR(bg); }
135 extern int sc_height;
136 #endif
137
138 #if MSDOS_COMPILER==WIN32C
139 #define UTF8_MAX_LENGTH 4
140
141 static WORD curr_attr;
142
143 static HANDLE con_out_save = INVALID_HANDLE_VALUE; /* previous console */
144 static HANDLE con_out_ours = INVALID_HANDLE_VALUE; /* our own */
145 HANDLE con_out = INVALID_HANDLE_VALUE; /* current console */
146
147 extern int utf_mode;
148 extern int quitting;
149 static void win32_init_term();
150 static void win32_deinit_term();
151
152 #ifndef ENABLE_VIRTUAL_TERMINAL_PROCESSING
153 #define ENABLE_VIRTUAL_TERMINAL_PROCESSING 4
154 #endif
155
156 #define FG_COLORS (FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE | FOREGROUND_INTENSITY)
157 #define BG_COLORS (BACKGROUND_RED | BACKGROUND_GREEN | BACKGROUND_BLUE | BACKGROUND_INTENSITY)
158 #define MAKEATTR(fg,bg) ((WORD)((fg)|((bg)<<4)))
159 #define APPLY_COLORS() { if (SetConsoleTextAttribute(con_out, curr_attr) == 0) \
160 error("SETCOLORS failed", NULL_PARG); }
161 #define SET_FG_COLOR(fg) { curr_attr &= ~0x0f; curr_attr |= (fg); APPLY_COLORS(); }
162 #define SET_BG_COLOR(bg) { curr_attr &= ~0xf0; curr_attr |= ((bg)<<4); APPLY_COLORS(); }
163 #define SETCOLORS(fg,bg) { curr_attr = MAKEATTR(fg,bg); APPLY_COLORS(); }
164 #endif
165
166 #if MSDOS_COMPILER
167 public int nm_fg_color = CV_ERROR; /* Color of normal text */
168 public int nm_bg_color = CV_ERROR;
169 public int nm_attr = 0;
170 public int bo_fg_color = CV_ERROR; /* Color of bold text */
171 public int bo_bg_color = CV_ERROR;
172 public int bo_attr = 0;
173 public int ul_fg_color = CV_ERROR; /* Color of underlined text */
174 public int ul_bg_color = CV_ERROR;
175 public int ul_attr = 0;
176 public int so_fg_color = CV_ERROR; /* Color of standout text */
177 public int so_bg_color = CV_ERROR;
178 public int so_attr = 0;
179 public int bl_fg_color = CV_ERROR; /* Color of blinking text */
180 public int bl_bg_color = CV_ERROR;
181 public int bl_attr = 0;
182 static int sy_fg_color; /* Color of system text (before less) */
183 static int sy_bg_color;
184 public int sgr_mode; /* Honor ANSI sequences rather than using above */
185 #if MSDOS_COMPILER==WIN32C
186 static DWORD init_console_output_mode;
187 extern DWORD init_console_input_mode;
188 extern DWORD curr_console_input_mode;
189 extern DWORD base_console_input_mode;
190 extern DWORD mouse_console_input_mode;
191 public int vt_enabled = -1; /* Is virtual terminal processing available? */
192 #endif
193 #else
194
195 /*
196 * Strings passed to tputs() to do various terminal functions.
197 */
198 static constant char
199 *sc_pad, /* Pad string */
200 *sc_home, /* Cursor home */
201 *sc_addline, /* Add line, scroll down following lines */
202 *sc_lower_left, /* Cursor to last line, first column */
203 *sc_return, /* Cursor to beginning of current line */
204 *sc_move, /* General cursor positioning */
205 *sc_clear, /* Clear screen */
206 *sc_eol_clear, /* Clear to end of line */
207 *sc_eos_clear, /* Clear to end of screen */
208 *sc_s_in, /* Enter standout (highlighted) mode */
209 *sc_s_out, /* Exit standout mode */
210 *sc_u_in, /* Enter underline mode */
211 *sc_u_out, /* Exit underline mode */
212 *sc_b_in, /* Enter bold mode */
213 *sc_b_out, /* Exit bold mode */
214 *sc_bl_in, /* Enter blink mode */
215 *sc_bl_out, /* Exit blink mode */
216 *sc_visual_bell, /* Visual bell (flash screen) sequence */
217 *sc_backspace, /* Backspace cursor */
218 *sc_s_keypad, /* Start keypad mode */
219 *sc_e_keypad, /* End keypad mode */
220 *sc_s_mousecap, /* Start mouse capture mode */
221 *sc_e_mousecap, /* End mouse capture mode */
222 *sc_init, /* Startup terminal initialization */
223 *sc_deinit; /* Exit terminal de-initialization */
224
225 static int attrcolor = -1;
226 #endif
227
228 static int init_done = 0;
229
230 public int auto_wrap; /* Terminal does \r\n when write past margin */
231 public int ignaw; /* Terminal ignores \n immediately after wrap */
232 public int erase_char; /* The user's erase char */
233 public int erase2_char; /* The user's other erase char */
234 public int kill_char; /* The user's line-kill char */
235 public int werase_char; /* The user's word-erase char */
236 public int sc_width, sc_height; /* Height & width of screen */
237 public int bo_s_width, bo_e_width; /* Printing width of boldface seq */
238 public int ul_s_width, ul_e_width; /* Printing width of underline seq */
239 public int so_s_width, so_e_width; /* Printing width of standout seq */
240 public int bl_s_width, bl_e_width; /* Printing width of blink seq */
241 public int above_mem, below_mem; /* Memory retained above/below screen */
242 public int can_goto_line; /* Can move cursor to any line */
243 public int clear_bg; /* Clear fills with background color */
244 public int missing_cap = 0; /* Some capability is missing */
245 public constant char *kent = NULL; /* Keypad ENTER sequence */
246 public lbool term_init_done = FALSE;
247 public lbool full_screen = TRUE;
248
249 static int attrmode = AT_NORMAL;
250 static int termcap_debug = -1;
251 static int no_alt_screen; /* sc_init does not switch to alt screen */
252 extern int binattr;
253 extern int one_screen;
254
255 #if !MSDOS_COMPILER
256 static constant char *cheaper(constant char *t1, constant char *t2, constant char *def);
257 static void tmodes(constant char *incap, constant char *outcap, constant char **instr,
258 constant char **outstr, constant char *def_instr, constant char *def_outstr, char **spp);
259 #endif
260
261 /*
262 * These two variables are sometimes defined in,
263 * and needed by, the termcap library.
264 */
265 #if MUST_DEFINE_OSPEED
266 extern short ospeed; /* Terminal output baud rate */
267 extern char PC; /* Pad character */
268 #endif
269 #ifdef _OSK
270 short ospeed;
271 char PC_, *UP, *BC;
272 #endif
273
274 extern int quiet; /* If VERY_QUIET, use visual bell for bell */
275 extern int no_vbell;
276 extern int no_back_scroll;
277 extern int no_init;
278 extern int no_keypad;
279 extern int sigs;
280 extern int top_scroll;
281 extern int quit_if_one_screen;
282 extern int oldbot;
283 extern int mousecap;
284 extern int is_tty;
285 extern int use_color;
286 #if HILITE_SEARCH
287 extern int hilite_search;
288 #endif
289 #if MSDOS_COMPILER==WIN32C
290 extern int wscroll;
291 extern HANDLE tty;
292 #else
293 extern int tty;
294 #endif
295
296 #if (HAVE_TERMIOS_H && HAVE_TERMIOS_FUNCS) || defined(TCGETA)
297 /*
298 * Set termio flags for use by less.
299 */
set_termio_flags(struct termios * s)300 static void set_termio_flags(
301 #if HAVE_TERMIOS_H && HAVE_TERMIOS_FUNCS
302 struct termios *s
303 #else
304 struct termio *s
305 #endif
306 )
307 {
308 s->c_lflag &= ~(0
309 #ifdef ICANON
310 | ICANON
311 #endif
312 #ifdef ECHO
313 | ECHO
314 #endif
315 #ifdef ECHOE
316 | ECHOE
317 #endif
318 #ifdef ECHOK
319 | ECHOK
320 #endif
321 #ifdef ECHONL
322 | ECHONL
323 #endif
324 );
325
326 s->c_oflag |= (0
327 #ifdef OXTABS
328 | OXTABS
329 #else
330 #ifdef TAB3
331 | TAB3
332 #else
333 #ifdef XTABS
334 | XTABS
335 #endif
336 #endif
337 #endif
338 #ifdef OPOST
339 | OPOST
340 #endif
341 #ifdef ONLCR
342 | ONLCR
343 #endif
344 );
345
346 s->c_oflag &= ~(0
347 #ifdef ONOEOT
348 | ONOEOT
349 #endif
350 #ifdef OCRNL
351 | OCRNL
352 #endif
353 #ifdef ONOCR
354 | ONOCR
355 #endif
356 #ifdef ONLRET
357 | ONLRET
358 #endif
359 );
360 }
361 #endif
362
363 /*
364 * Change terminal to "raw mode", or restore to "normal" mode.
365 * "Raw mode" means
366 * 1. An outstanding read will complete on receipt of a single keystroke.
367 * 2. Input is not echoed.
368 * 3. On output, \n is mapped to \r\n.
369 * 4. \t is NOT expanded into spaces.
370 * 5. Signal-causing characters such as ctrl-C (interrupt),
371 * etc. are NOT disabled.
372 * It doesn't matter whether an input \n is mapped to \r, or vice versa.
373 */
raw_mode(int on)374 public void raw_mode(int on)
375 {
376 static int curr_on = 0;
377
378 if (on == curr_on)
379 return;
380 erase2_char = '\b'; /* in case OS doesn't know about erase2 */
381 #if LESSTEST
382 if (is_lesstest())
383 {
384 /* {{ For consistent conditions when running tests. }} */
385 erase_char = '\b';
386 kill_char = CONTROL('U');
387 werase_char = CONTROL('W');
388 } else
389 #endif /*LESSTEST*/
390 #if HAVE_TERMIOS_H && HAVE_TERMIOS_FUNCS
391 {
392 struct termios s;
393 static struct termios save_term;
394 static int saved_term = 0;
395
396 if (on)
397 {
398 /*
399 * Get terminal modes.
400 */
401 if (tcgetattr(tty, &s) < 0)
402 {
403 erase_char = '\b';
404 kill_char = CONTROL('U');
405 werase_char = CONTROL('W');
406 } else
407 {
408 /*
409 * Save modes and set certain variables dependent on modes.
410 */
411 if (!saved_term)
412 {
413 save_term = s;
414 saved_term = 1;
415 }
416 #if HAVE_OSPEED
417 switch (cfgetospeed(&s))
418 {
419 #ifdef B0
420 case B0: ospeed = 0; break;
421 #endif
422 #ifdef B50
423 case B50: ospeed = 1; break;
424 #endif
425 #ifdef B75
426 case B75: ospeed = 2; break;
427 #endif
428 #ifdef B110
429 case B110: ospeed = 3; break;
430 #endif
431 #ifdef B134
432 case B134: ospeed = 4; break;
433 #endif
434 #ifdef B150
435 case B150: ospeed = 5; break;
436 #endif
437 #ifdef B200
438 case B200: ospeed = 6; break;
439 #endif
440 #ifdef B300
441 case B300: ospeed = 7; break;
442 #endif
443 #ifdef B600
444 case B600: ospeed = 8; break;
445 #endif
446 #ifdef B1200
447 case B1200: ospeed = 9; break;
448 #endif
449 #ifdef B1800
450 case B1800: ospeed = 10; break;
451 #endif
452 #ifdef B2400
453 case B2400: ospeed = 11; break;
454 #endif
455 #ifdef B4800
456 case B4800: ospeed = 12; break;
457 #endif
458 #ifdef B9600
459 case B9600: ospeed = 13; break;
460 #endif
461 #ifdef EXTA
462 case EXTA: ospeed = 14; break;
463 #endif
464 #ifdef EXTB
465 case EXTB: ospeed = 15; break;
466 #endif
467 #ifdef B57600
468 case B57600: ospeed = 16; break;
469 #endif
470 #ifdef B115200
471 case B115200: ospeed = 17; break;
472 #endif
473 default: ;
474 }
475 #endif
476 erase_char = s.c_cc[VERASE];
477 #ifdef VERASE2
478 erase2_char = s.c_cc[VERASE2];
479 #endif
480 kill_char = s.c_cc[VKILL];
481 #ifdef VWERASE
482 werase_char = s.c_cc[VWERASE];
483 #else
484 werase_char = CONTROL('W');
485 #endif
486
487 /*
488 * Set the modes to the way we want them.
489 */
490 set_termio_flags(&s);
491 s.c_cc[VMIN] = 1;
492 s.c_cc[VTIME] = 0;
493 #ifdef VLNEXT
494 s.c_cc[VLNEXT] = 0;
495 #endif
496 #ifdef VDSUSP
497 s.c_cc[VDSUSP] = 0;
498 #endif
499 #ifdef VSTOP
500 s.c_cc[VSTOP] = 0;
501 #endif
502 #ifdef VSTART
503 s.c_cc[VSTART] = 0;
504 #endif
505 #ifdef VDISCARD
506 s.c_cc[VDISCARD] = 0;
507 #endif
508 #if MUST_SET_LINE_DISCIPLINE
509 /*
510 * System's termios is broken; need to explicitly
511 * request TERMIODISC line discipline.
512 */
513 s.c_line = TERMIODISC;
514 #endif
515 }
516 } else
517 {
518 /*
519 * Restore saved modes.
520 */
521 s = save_term;
522 }
523 #if HAVE_FSYNC
524 fsync(tty);
525 #endif
526 tcsetattr(tty, TCSADRAIN, &s);
527 #if MUST_SET_LINE_DISCIPLINE
528 if (!on)
529 {
530 /*
531 * Broken termios *ignores* any line discipline
532 * except TERMIODISC. A different old line discipline
533 * is therefore not restored, yet. Restore the old
534 * line discipline by hand.
535 */
536 ioctl(tty, TIOCSETD, &save_term.c_line);
537 }
538 #endif
539 }
540 #else
541 #ifdef TCGETA
542 {
543 struct termio s;
544 static struct termio save_term;
545 static int saved_term = 0;
546
547 if (on)
548 {
549 /*
550 * Get terminal modes.
551 */
552 ioctl(tty, TCGETA, &s);
553
554 /*
555 * Save modes and set certain variables dependent on modes.
556 */
557 if (!saved_term)
558 {
559 save_term = s;
560 saved_term = 1;
561 }
562 #if HAVE_OSPEED
563 ospeed = s.c_cflag & CBAUD;
564 #endif
565 erase_char = s.c_cc[VERASE];
566 kill_char = s.c_cc[VKILL];
567 #ifdef VWERASE
568 werase_char = s.c_cc[VWERASE];
569 #else
570 werase_char = CONTROL('W');
571 #endif
572
573 /*
574 * Set the modes to the way we want them.
575 */
576 set_termio_flags(&s);
577 s.c_cc[VMIN] = 1;
578 s.c_cc[VTIME] = 0;
579 #ifdef VSTOP
580 s.c_cc[VSTOP] = 0;
581 #endif
582 #ifdef VSTART
583 s.c_cc[VSTART] = 0;
584 #endif
585 } else
586 {
587 /*
588 * Restore saved modes.
589 */
590 s = save_term;
591 }
592 ioctl(tty, TCSETAW, &s);
593 }
594 #else
595 #ifdef TIOCGETP
596 {
597 struct sgttyb s;
598 static struct sgttyb save_term;
599 static int saved_term = 0;
600
601 if (on)
602 {
603 /*
604 * Get terminal modes.
605 */
606 ioctl(tty, TIOCGETP, &s);
607
608 /*
609 * Save modes and set certain variables dependent on modes.
610 */
611 if (!saved_term)
612 {
613 save_term = s;
614 saved_term = 1;
615 }
616 #if HAVE_OSPEED
617 ospeed = s.sg_ospeed;
618 #endif
619 erase_char = s.sg_erase;
620 kill_char = s.sg_kill;
621 werase_char = CONTROL('W');
622
623 /*
624 * Set the modes to the way we want them.
625 */
626 s.sg_flags |= CBREAK;
627 s.sg_flags &= ~(ECHO|XTABS);
628 } else
629 {
630 /*
631 * Restore saved modes.
632 */
633 s = save_term;
634 }
635 ioctl(tty, TIOCSETN, &s);
636 }
637 #else
638 #ifdef _OSK
639 {
640 struct sgbuf s;
641 static struct sgbuf save_term;
642 static int saved_term = 0;
643
644 if (on)
645 {
646 /*
647 * Get terminal modes.
648 */
649 _gs_opt(tty, &s);
650
651 /*
652 * Save modes and set certain variables dependent on modes.
653 */
654 if (!saved_term)
655 {
656 save_term = s;
657 saved_term = 1;
658 }
659 erase_char = s.sg_bspch;
660 kill_char = s.sg_dlnch;
661 werase_char = CONTROL('W');
662
663 /*
664 * Set the modes to the way we want them.
665 */
666 s.sg_echo = 0;
667 s.sg_eofch = 0;
668 s.sg_pause = 0;
669 s.sg_psch = 0;
670 } else
671 {
672 /*
673 * Restore saved modes.
674 */
675 s = save_term;
676 }
677 _ss_opt(tty, &s);
678 }
679 #else
680 /* MS-DOS, Windows, or OS2 */
681 #if OS2
682 /* OS2 */
683 LSIGNAL(SIGINT, SIG_IGN);
684 #endif
685 erase_char = '\b';
686 #if MSDOS_COMPILER==DJGPPC
687 kill_char = CONTROL('U');
688 /*
689 * So that when we shell out or run another program, its
690 * stdin is in cooked mode. We do not switch stdin to binary
691 * mode if fd0 is zero, since that means we were called before
692 * tty was reopened in open_getchr, in which case we would be
693 * changing the original stdin device outside less.
694 */
695 if (fd0 != 0)
696 setmode(0, on ? O_BINARY : O_TEXT);
697 #else
698 kill_char = ESC;
699 #endif
700 werase_char = CONTROL('W');
701 #endif
702 #endif
703 #endif
704 #endif
705 curr_on = on;
706 }
707
708 #if !MSDOS_COMPILER
709 /*
710 * Some glue to prevent calling termcap functions if tgetent() failed.
711 */
712 static int hardcopy;
713
ltget_env(constant char * capname)714 static constant char * ltget_env(constant char *capname)
715 {
716 char name[64];
717
718 if (termcap_debug)
719 {
720 struct env { struct env *next; char *name; char *value; };
721 static struct env *envs = NULL;
722 struct env *p;
723 for (p = envs; p != NULL; p = p->next)
724 if (strcmp(p->name, capname) == 0)
725 return p->value;
726 p = (struct env *) ecalloc(1, sizeof(struct env));
727 p->name = save(capname);
728 p->value = (char *) ecalloc(strlen(capname)+3, sizeof(char));
729 sprintf(p->value, "<%s>", capname);
730 p->next = envs;
731 envs = p;
732 return p->value;
733 }
734 SNPRINTF1(name, sizeof(name), "LESS_TERMCAP_%s", capname);
735 return (lgetenv(name));
736 }
737
ltgetflag(constant char * capname)738 static int ltgetflag(constant char *capname)
739 {
740 constant char *s;
741
742 if ((s = ltget_env(capname)) != NULL)
743 return (*s != '\0' && *s != '0');
744 if (hardcopy)
745 return (0);
746 return (tgetflag(capname));
747 }
748
ltgetnum(constant char * capname)749 static int ltgetnum(constant char *capname)
750 {
751 constant char *s;
752
753 if ((s = ltget_env(capname)) != NULL)
754 return (atoi(s));
755 if (hardcopy)
756 return (-1);
757 return (tgetnum(capname));
758 }
759
ltgetstr(constant char * capname,char ** pp)760 static constant char * ltgetstr(constant char *capname, char **pp)
761 {
762 constant char *s;
763
764 if ((s = ltget_env(capname)) != NULL)
765 return (s);
766 if (hardcopy)
767 return (NULL);
768 return (tgetstr(capname, pp));
769 }
770 #endif /* MSDOS_COMPILER */
771
772 /*
773 * Get size of the output screen.
774 */
scrsize(void)775 static void scrsize(void)
776 {
777 constant char *s;
778 int sys_height;
779 int sys_width;
780 #if !MSDOS_COMPILER
781 int n;
782 #endif
783
784 #define DEF_SC_WIDTH 80
785 #if MSDOS_COMPILER
786 #define DEF_SC_HEIGHT 25
787 #else
788 #define DEF_SC_HEIGHT 24
789 #endif
790
791
792 sys_width = sys_height = 0;
793
794 #if LESSTEST
795 if (0) /* can't use is_lesstest(): ttyin_name may not be set by scan_option yet */
796 #endif /*LESSTEST*/
797 {
798 #if MSDOS_COMPILER==MSOFTC
799 {
800 struct videoconfig w;
801 _getvideoconfig(&w);
802 sys_height = w.numtextrows;
803 sys_width = w.numtextcols;
804 }
805 #else
806 #if MSDOS_COMPILER==BORLANDC || MSDOS_COMPILER==DJGPPC
807 {
808 struct text_info w;
809 gettextinfo(&w);
810 sys_height = w.screenheight;
811 sys_width = w.screenwidth;
812 }
813 #else
814 #if MSDOS_COMPILER==WIN32C
815 {
816 CONSOLE_SCREEN_BUFFER_INFO scr;
817 GetConsoleScreenBufferInfo(con_out, &scr);
818 sys_height = scr.srWindow.Bottom - scr.srWindow.Top + 1;
819 sys_width = scr.srWindow.Right - scr.srWindow.Left + 1;
820 }
821 #else
822 #if OS2
823 {
824 int s[2];
825 _scrsize(s);
826 sys_width = s[0];
827 sys_height = s[1];
828 /*
829 * When using terminal emulators for XFree86/OS2, the
830 * _scrsize function does not work well.
831 * Call the scrsize.exe program to get the window size.
832 */
833 windowid = getenv("WINDOWID");
834 if (windowid != NULL)
835 {
836 FILE *fd = popen("scrsize", "rt");
837 if (fd != NULL)
838 {
839 int w, h;
840 fscanf(fd, "%i %i", &w, &h);
841 if (w > 0 && h > 0)
842 {
843 sys_width = w;
844 sys_height = h;
845 }
846 pclose(fd);
847 }
848 }
849 }
850 #else
851 #ifdef TIOCGWINSZ
852 {
853 struct winsize w;
854 if (ioctl(2, TIOCGWINSZ, &w) == 0)
855 {
856 if (w.ws_row > 0)
857 sys_height = w.ws_row;
858 if (w.ws_col > 0)
859 sys_width = w.ws_col;
860 }
861 }
862 #else
863 #ifdef WIOCGETD
864 {
865 struct uwdata w;
866 if (ioctl(2, WIOCGETD, &w) == 0)
867 {
868 if (w.uw_height > 0)
869 sys_height = w.uw_height / w.uw_vs;
870 if (w.uw_width > 0)
871 sys_width = w.uw_width / w.uw_hs;
872 }
873 }
874 #endif
875 #endif
876 #endif
877 #endif
878 #endif
879 #endif
880 }
881
882 if (sys_height > 0)
883 sc_height = sys_height;
884 else if ((s = lgetenv("LINES")) != NULL)
885 sc_height = atoi(s);
886 #if !MSDOS_COMPILER
887 else if ((n = ltgetnum("li")) > 0)
888 sc_height = n;
889 #endif
890 if ((s = lgetenv("LESS_LINES")) != NULL)
891 {
892 int height = atoi(s);
893 sc_height = (height < 0) ? sc_height + height : height;
894 full_screen = FALSE;
895 }
896 if (sc_height <= 0)
897 sc_height = DEF_SC_HEIGHT;
898
899 if (sys_width > 0)
900 sc_width = sys_width;
901 else if ((s = lgetenv("COLUMNS")) != NULL)
902 sc_width = atoi(s);
903 #if !MSDOS_COMPILER
904 else if ((n = ltgetnum("co")) > 0)
905 sc_width = n;
906 #endif
907 if ((s = lgetenv("LESS_COLUMNS")) != NULL)
908 {
909 int width = atoi(s);
910 sc_width = (width < 0) ? sc_width + width : width;
911 }
912 if (sc_width <= 0)
913 sc_width = DEF_SC_WIDTH;
914 screen_size_changed();
915 }
916
917 /*
918 * Recalculate things that depend on the screen size.
919 */
screen_size_changed(void)920 public void screen_size_changed(void)
921 {
922 calc_jump_sline();
923 calc_shift_count();
924 calc_match_shift();
925 }
926
927 #if MSDOS_COMPILER==MSOFTC
928 /*
929 * Figure out how many empty loops it takes to delay a millisecond.
930 */
get_clock(void)931 static void get_clock(void)
932 {
933 clock_t start;
934
935 /*
936 * Get synchronized at the start of a tick.
937 */
938 start = clock();
939 while (clock() == start)
940 ;
941 /*
942 * Now count loops till the next tick.
943 */
944 start = clock();
945 msec_loops = 0;
946 while (clock() == start)
947 msec_loops++;
948 /*
949 * Convert from (loops per clock) to (loops per millisecond).
950 */
951 msec_loops *= CLOCKS_PER_SEC;
952 msec_loops /= 1000;
953 }
954
955 /*
956 * Delay for a specified number of milliseconds.
957 */
delay(int msec)958 static void delay(int msec)
959 {
960 long i;
961
962 while (msec-- > 0)
963 {
964 for (i = 0; i < msec_loops; i++)
965 (void) clock();
966 }
967 }
968 #endif
969
970 /*
971 * Return the characters actually input by a "special" key.
972 */
special_key_str(int key)973 public constant char * special_key_str(int key)
974 {
975 static char tbuf[40];
976 constant char *s;
977 #if MSDOS_COMPILER || OS2
978 static char k_right[] = { '\340', PCK_RIGHT, 0 };
979 static char k_left[] = { '\340', PCK_LEFT, 0 };
980 static char k_ctl_right[] = { '\340', PCK_CTL_RIGHT, 0 };
981 static char k_ctl_left[] = { '\340', PCK_CTL_LEFT, 0 };
982 static char k_insert[] = { '\340', PCK_INSERT, 0 };
983 static char k_delete[] = { '\340', PCK_DELETE, 0 };
984 static char k_ctl_delete[] = { '\340', PCK_CTL_DELETE, 0 };
985 static char k_ctl_backspace[] = { '\177', 0 };
986 static char k_backspace[] = { '\b', 0 };
987 static char k_home[] = { '\340', PCK_HOME, 0 };
988 static char k_end[] = { '\340', PCK_END, 0 };
989 static char k_up[] = { '\340', PCK_UP, 0 };
990 static char k_down[] = { '\340', PCK_DOWN, 0 };
991 static char k_backtab[] = { '\340', PCK_SHIFT_TAB, 0 };
992 static char k_pagedown[] = { '\340', PCK_PAGEDOWN, 0 };
993 static char k_pageup[] = { '\340', PCK_PAGEUP, 0 };
994 static char k_f1[] = { '\340', PCK_F1, 0 };
995 #endif
996 #if !MSDOS_COMPILER
997 char *sp = tbuf;
998 #endif
999
1000 switch (key)
1001 {
1002 #if OS2
1003 /*
1004 * If windowid is not NULL, assume less is executed in
1005 * the XFree86 environment.
1006 */
1007 case SK_RIGHT_ARROW:
1008 s = windowid ? ltgetstr("kr", &sp) : k_right;
1009 break;
1010 case SK_LEFT_ARROW:
1011 s = windowid ? ltgetstr("kl", &sp) : k_left;
1012 break;
1013 case SK_UP_ARROW:
1014 s = windowid ? ltgetstr("ku", &sp) : k_up;
1015 break;
1016 case SK_DOWN_ARROW:
1017 s = windowid ? ltgetstr("kd", &sp) : k_down;
1018 break;
1019 case SK_PAGE_UP:
1020 s = windowid ? ltgetstr("kP", &sp) : k_pageup;
1021 break;
1022 case SK_PAGE_DOWN:
1023 s = windowid ? ltgetstr("kN", &sp) : k_pagedown;
1024 break;
1025 case SK_HOME:
1026 s = windowid ? ltgetstr("kh", &sp) : k_home;
1027 break;
1028 case SK_END:
1029 s = windowid ? ltgetstr("@7", &sp) : k_end;
1030 break;
1031 case SK_DELETE:
1032 s = windowid ? ltgetstr("kD", &sp) : k_delete;
1033 if (s == NULL)
1034 {
1035 tbuf[0] = '\177';
1036 tbuf[1] = '\0';
1037 s = tbuf;
1038 }
1039 break;
1040 #endif
1041 #if MSDOS_COMPILER
1042 case SK_RIGHT_ARROW:
1043 s = k_right;
1044 break;
1045 case SK_LEFT_ARROW:
1046 s = k_left;
1047 break;
1048 case SK_UP_ARROW:
1049 s = k_up;
1050 break;
1051 case SK_DOWN_ARROW:
1052 s = k_down;
1053 break;
1054 case SK_PAGE_UP:
1055 s = k_pageup;
1056 break;
1057 case SK_PAGE_DOWN:
1058 s = k_pagedown;
1059 break;
1060 case SK_HOME:
1061 s = k_home;
1062 break;
1063 case SK_END:
1064 s = k_end;
1065 break;
1066 case SK_DELETE:
1067 s = k_delete;
1068 break;
1069 #endif
1070 #if MSDOS_COMPILER || OS2
1071 case SK_INSERT:
1072 s = k_insert;
1073 break;
1074 case SK_CTL_LEFT_ARROW:
1075 s = k_ctl_left;
1076 break;
1077 case SK_CTL_RIGHT_ARROW:
1078 s = k_ctl_right;
1079 break;
1080 case SK_CTL_BACKSPACE:
1081 s = k_ctl_backspace;
1082 break;
1083 case SK_CTL_DELETE:
1084 s = k_ctl_delete;
1085 break;
1086 case SK_BACKSPACE:
1087 s = k_backspace;
1088 break;
1089 case SK_F1:
1090 s = k_f1;
1091 break;
1092 case SK_BACKTAB:
1093 s = k_backtab;
1094 break;
1095 #else
1096 case SK_RIGHT_ARROW:
1097 s = ltgetstr("kr", &sp);
1098 break;
1099 case SK_LEFT_ARROW:
1100 s = ltgetstr("kl", &sp);
1101 break;
1102 case SK_UP_ARROW:
1103 s = ltgetstr("ku", &sp);
1104 break;
1105 case SK_DOWN_ARROW:
1106 s = ltgetstr("kd", &sp);
1107 break;
1108 case SK_PAGE_UP:
1109 s = ltgetstr("kP", &sp);
1110 break;
1111 case SK_PAGE_DOWN:
1112 s = ltgetstr("kN", &sp);
1113 break;
1114 case SK_HOME:
1115 s = ltgetstr("kh", &sp);
1116 break;
1117 case SK_END:
1118 s = ltgetstr("@7", &sp);
1119 break;
1120 case SK_DELETE:
1121 s = ltgetstr("kD", &sp);
1122 if (s == NULL)
1123 {
1124 tbuf[0] = '\177';
1125 tbuf[1] = '\0';
1126 s = tbuf;
1127 }
1128 break;
1129 case SK_BACKSPACE:
1130 s = ltgetstr("kb", &sp);
1131 if (s == NULL)
1132 {
1133 tbuf[0] = '\b';
1134 tbuf[1] = '\0';
1135 s = tbuf;
1136 }
1137 break;
1138 #endif
1139 case SK_CONTROL_K:
1140 tbuf[0] = CONTROL('K');
1141 tbuf[1] = '\0';
1142 s = tbuf;
1143 break;
1144 default:
1145 return (NULL);
1146 }
1147 return (s);
1148 }
1149
1150 #if MSDOS_COMPILER
init_win_colors(void)1151 public void init_win_colors(void)
1152 {
1153 if (nm_fg_color == CV_ERROR || nm_fg_color == CV_NOCHANGE) nm_fg_color = sy_fg_color;
1154 if (nm_bg_color == CV_ERROR || nm_bg_color == CV_NOCHANGE) nm_bg_color = sy_bg_color;
1155 if (bo_fg_color == CV_NOCHANGE) bo_fg_color = sy_fg_color; else if (bo_fg_color == CV_ERROR) bo_fg_color = sy_fg_color | 8;
1156 if (bo_bg_color == CV_NOCHANGE) bo_bg_color = sy_bg_color; else if (bo_bg_color == CV_ERROR) bo_bg_color = sy_bg_color;
1157 if (ul_fg_color == CV_NOCHANGE) ul_fg_color = sy_fg_color; else if (ul_fg_color == CV_ERROR) ul_fg_color = (sy_bg_color == 3 || sy_bg_color == 11) ? 0 : 11;
1158 if (ul_bg_color == CV_NOCHANGE) ul_bg_color = sy_bg_color; else if (ul_bg_color == CV_ERROR) ul_bg_color = sy_bg_color;
1159 if (so_fg_color == CV_NOCHANGE) so_fg_color = sy_fg_color; else if (so_fg_color == CV_ERROR) so_fg_color = sy_bg_color;
1160 if (so_bg_color == CV_NOCHANGE) so_bg_color = sy_bg_color; else if (so_bg_color == CV_ERROR) so_bg_color = sy_fg_color;
1161 if (bl_fg_color == CV_NOCHANGE) bl_fg_color = sy_fg_color; else if (bl_fg_color == CV_ERROR) bl_fg_color = ul_bg_color;
1162 if (bl_bg_color == CV_NOCHANGE) bl_bg_color = sy_bg_color; else if (bl_bg_color == CV_ERROR) bl_bg_color = ul_fg_color;
1163 nm_fg_color |= nm_attr;
1164 bo_fg_color |= bo_attr;
1165 ul_fg_color |= ul_attr;
1166 so_fg_color |= so_attr;
1167 bl_fg_color |= bl_attr;
1168 }
1169 #endif /* MSDOS_COMPILER */
1170
1171 /*
1172 * Get terminal capabilities via termcap.
1173 */
get_term(void)1174 public void get_term(void)
1175 {
1176 termcap_debug = !isnullenv(lgetenv("LESS_TERMCAP_DEBUG"));
1177 #if MSDOS_COMPILER
1178 auto_wrap = 1;
1179 ignaw = 0;
1180 can_goto_line = 1;
1181 clear_bg = 1;
1182 /*
1183 * Set up default colors.
1184 * The xx_s_width and xx_e_width vars are already initialized to 0.
1185 */
1186 #if MSDOS_COMPILER==MSOFTC
1187 sy_bg_color = _getbkcolor();
1188 sy_fg_color = _gettextcolor();
1189 get_clock();
1190 #else
1191 #if MSDOS_COMPILER==BORLANDC || MSDOS_COMPILER==DJGPPC
1192 {
1193 struct text_info w;
1194 gettextinfo(&w);
1195 sy_bg_color = (w.attribute >> 4) & 0x0F;
1196 sy_fg_color = (w.attribute >> 0) & 0x0F;
1197 }
1198 #else
1199 #if MSDOS_COMPILER==WIN32C
1200 {
1201 CONSOLE_SCREEN_BUFFER_INFO scr;
1202
1203 con_out_save = con_out = GetStdHandle(STD_OUTPUT_HANDLE);
1204 /*
1205 * Always open stdin in binary. Note this *must* be done
1206 * before any file operations have been done on fd0.
1207 */
1208 SET_BINARY(0);
1209 GetConsoleMode(con_out, &init_console_output_mode);
1210 GetConsoleScreenBufferInfo(con_out, &scr);
1211 curr_attr = scr.wAttributes;
1212 sy_bg_color = (curr_attr & BG_COLORS) >> 4; /* normalize */
1213 sy_fg_color = curr_attr & FG_COLORS;
1214 }
1215 #endif
1216 #endif
1217 #endif
1218 init_win_colors();
1219
1220 /*
1221 * Get size of the screen.
1222 */
1223 scrsize();
1224 pos_init();
1225
1226 #else /* !MSDOS_COMPILER */
1227 {
1228 char *sp;
1229 constant char *t1;
1230 constant char *t2;
1231 constant char *term;
1232 /*
1233 * Some termcap libraries assume termbuf is static
1234 * (accessible after tgetent returns).
1235 */
1236 static char termbuf[TERMBUF_SIZE];
1237 static char sbuf[TERMSBUF_SIZE];
1238
1239 #if OS2
1240 /*
1241 * Make sure the termcap database is available.
1242 */
1243 constant char *cp = lgetenv("TERMCAP");
1244 if (isnullenv(cp))
1245 {
1246 char *termcap;
1247 if ((sp = homefile("termcap.dat")) != NULL)
1248 {
1249 termcap = (char *) ecalloc(strlen(sp)+9, sizeof(char));
1250 sprintf(termcap, "TERMCAP=%s", sp);
1251 free(sp);
1252 putenv(termcap);
1253 }
1254 }
1255 #endif
1256 /*
1257 * Find out what kind of terminal this is.
1258 */
1259 if ((term = lgetenv("TERM")) == NULL)
1260 term = DEFAULT_TERM;
1261 hardcopy = 0;
1262 /* {{ Should probably just pass NULL instead of termbuf. }} */
1263 if (tgetent(termbuf, term) != TGETENT_OK)
1264 hardcopy = 1;
1265 if (ltgetflag("hc"))
1266 hardcopy = 1;
1267
1268 /*
1269 * Get size of the screen.
1270 */
1271 scrsize();
1272 pos_init();
1273
1274 auto_wrap = ltgetflag("am");
1275 ignaw = ltgetflag("xn");
1276 above_mem = ltgetflag("da");
1277 below_mem = ltgetflag("db");
1278 clear_bg = ltgetflag("ut");
1279 no_alt_screen = ltgetflag("NR");
1280
1281 /*
1282 * Assumes termcap variable "sg" is the printing width of:
1283 * the standout sequence, the end standout sequence,
1284 * the underline sequence, the end underline sequence,
1285 * the boldface sequence, and the end boldface sequence.
1286 */
1287 if ((so_s_width = ltgetnum("sg")) < 0)
1288 so_s_width = 0;
1289 so_e_width = so_s_width;
1290
1291 bo_s_width = bo_e_width = so_s_width;
1292 ul_s_width = ul_e_width = so_s_width;
1293 bl_s_width = bl_e_width = so_s_width;
1294
1295 #if HILITE_SEARCH
1296 if (so_s_width > 0 || so_e_width > 0)
1297 /*
1298 * Disable highlighting by default on magic cookie terminals.
1299 * Turning on highlighting might change the displayed width
1300 * of a line, causing the display to get messed up.
1301 * The user can turn it back on with -g,
1302 * but she won't like the results.
1303 */
1304 hilite_search = 0;
1305 #endif
1306
1307 /*
1308 * Get various string-valued capabilities.
1309 */
1310 sp = sbuf;
1311
1312 #if HAVE_OSPEED
1313 sc_pad = ltgetstr("pc", &sp);
1314 if (sc_pad != NULL)
1315 PC = *sc_pad;
1316 #endif
1317
1318 sc_s_keypad = ltgetstr("ks", &sp);
1319 if (sc_s_keypad == NULL)
1320 sc_s_keypad = "";
1321 sc_e_keypad = ltgetstr("ke", &sp);
1322 if (sc_e_keypad == NULL)
1323 sc_e_keypad = "";
1324 kent = ltgetstr("@8", &sp);
1325
1326 sc_s_mousecap = ltgetstr("MOUSE_START", &sp);
1327 if (sc_s_mousecap == NULL)
1328 sc_s_mousecap = ESCS "[?1000h" ESCS "[?1006h";
1329 sc_e_mousecap = ltgetstr("MOUSE_END", &sp);
1330 if (sc_e_mousecap == NULL)
1331 sc_e_mousecap = ESCS "[?1006l" ESCS "[?1000l";
1332
1333 sc_init = ltgetstr("ti", &sp);
1334 if (sc_init == NULL)
1335 sc_init = "";
1336
1337 sc_deinit= ltgetstr("te", &sp);
1338 if (sc_deinit == NULL)
1339 sc_deinit = "";
1340
1341 sc_eol_clear = ltgetstr("ce", &sp);
1342 if (sc_eol_clear == NULL || *sc_eol_clear == '\0')
1343 {
1344 missing_cap = 1;
1345 sc_eol_clear = "";
1346 }
1347
1348 sc_eos_clear = ltgetstr("cd", &sp);
1349 if (below_mem && (sc_eos_clear == NULL || *sc_eos_clear == '\0'))
1350 {
1351 missing_cap = 1;
1352 sc_eos_clear = "";
1353 }
1354
1355 sc_clear = ltgetstr("cl", &sp);
1356 if (sc_clear == NULL || *sc_clear == '\0')
1357 {
1358 missing_cap = 1;
1359 sc_clear = "\n\n";
1360 }
1361
1362 sc_move = ltgetstr("cm", &sp);
1363 if (sc_move == NULL || *sc_move == '\0')
1364 {
1365 /*
1366 * This is not an error here, because we don't
1367 * always need sc_move.
1368 * We need it only if we don't have home or lower-left.
1369 */
1370 sc_move = "";
1371 can_goto_line = 0;
1372 } else
1373 can_goto_line = 1;
1374
1375 tmodes("so", "se", &sc_s_in, &sc_s_out, "", "", &sp);
1376 tmodes("us", "ue", &sc_u_in, &sc_u_out, sc_s_in, sc_s_out, &sp);
1377 tmodes("md", "me", &sc_b_in, &sc_b_out, sc_s_in, sc_s_out, &sp);
1378 tmodes("mb", "me", &sc_bl_in, &sc_bl_out, sc_s_in, sc_s_out, &sp);
1379
1380 sc_visual_bell = ltgetstr("vb", &sp);
1381 if (sc_visual_bell == NULL)
1382 sc_visual_bell = "";
1383
1384 if (ltgetflag("bs"))
1385 sc_backspace = "\b";
1386 else
1387 {
1388 sc_backspace = ltgetstr("bc", &sp);
1389 if (sc_backspace == NULL || *sc_backspace == '\0')
1390 sc_backspace = "\b";
1391 }
1392
1393 /*
1394 * Choose between using "ho" and "cm" ("home" and "cursor move")
1395 * to move the cursor to the upper left corner of the screen.
1396 */
1397 t1 = ltgetstr("ho", &sp);
1398 if (t1 == NULL)
1399 t1 = "";
1400 if (*sc_move == '\0')
1401 t2 = "";
1402 else
1403 {
1404 strcpy(sp, tgoto(sc_move, 0, 0));
1405 t2 = sp;
1406 sp += strlen(sp) + 1;
1407 }
1408 sc_home = cheaper(t1, t2, "|\b^");
1409
1410 /*
1411 * Choose between using "ll" and "cm" ("lower left" and "cursor move")
1412 * to move the cursor to the lower left corner of the screen.
1413 */
1414 t1 = ltgetstr("ll", &sp);
1415 if (t1 == NULL || !full_screen)
1416 t1 = "";
1417 if (*sc_move == '\0')
1418 t2 = "";
1419 else
1420 {
1421 strcpy(sp, tgoto(sc_move, 0, sc_height-1));
1422 t2 = sp;
1423 sp += strlen(sp) + 1;
1424 }
1425 sc_lower_left = cheaper(t1, t2, "\r");
1426
1427 /*
1428 * Get carriage return string.
1429 */
1430 sc_return = ltgetstr("cr", &sp);
1431 if (sc_return == NULL)
1432 sc_return = "\r";
1433
1434 /*
1435 * Choose between using "al" or "sr" ("add line" or "scroll reverse")
1436 * to add a line at the top of the screen.
1437 */
1438 t1 = ltgetstr("al", &sp);
1439 if (t1 == NULL)
1440 t1 = "";
1441 t2 = ltgetstr("sr", &sp);
1442 if (t2 == NULL)
1443 t2 = "";
1444 #if OS2
1445 if (*t1 == '\0' && *t2 == '\0')
1446 sc_addline = "";
1447 else
1448 #endif
1449 if (above_mem)
1450 sc_addline = t1;
1451 else
1452 sc_addline = cheaper(t1, t2, "");
1453 if (*sc_addline == '\0')
1454 {
1455 /*
1456 * Force repaint on any backward movement.
1457 */
1458 no_back_scroll = 1;
1459 }
1460 }
1461 #endif /* MSDOS_COMPILER */
1462 }
1463
1464 #if !MSDOS_COMPILER
1465 /*
1466 * Return the cost of displaying a termcap string.
1467 * We use the trick of calling tputs, but as a char printing function
1468 * we give it inc_costcount, which just increments "costcount".
1469 * This tells us how many chars would be printed by using this string.
1470 * {{ Couldn't we just use strlen? }}
1471 */
1472 static int costcount;
1473
1474 /*ARGSUSED*/
inc_costcount(int c)1475 static int inc_costcount(int c)
1476 {
1477 costcount++;
1478 return (c);
1479 }
1480
cost(constant char * t)1481 static int cost(constant char *t)
1482 {
1483 costcount = 0;
1484 tputs(t, sc_height, inc_costcount);
1485 return (costcount);
1486 }
1487
1488 /*
1489 * Return the "best" of the two given termcap strings.
1490 * The best, if both exist, is the one with the lower
1491 * cost (see cost() function).
1492 */
cheaper(constant char * t1,constant char * t2,constant char * def)1493 static constant char * cheaper(constant char *t1, constant char *t2, constant char *def)
1494 {
1495 if (*t1 == '\0' && *t2 == '\0')
1496 {
1497 missing_cap = 1;
1498 return (def);
1499 }
1500 if (*t1 == '\0')
1501 return (t2);
1502 if (*t2 == '\0')
1503 return (t1);
1504 if (cost(t1) < cost(t2))
1505 return (t1);
1506 return (t2);
1507 }
1508
tmodes(constant char * incap,constant char * outcap,constant char ** instr,constant char ** outstr,constant char * def_instr,constant char * def_outstr,char ** spp)1509 static void tmodes(constant char *incap, constant char *outcap, constant char **instr, constant char **outstr, constant char *def_instr, constant char *def_outstr, char **spp)
1510 {
1511 *instr = ltgetstr(incap, spp);
1512 if (*instr == NULL)
1513 {
1514 /* Use defaults. */
1515 *instr = def_instr;
1516 *outstr = def_outstr;
1517 return;
1518 }
1519
1520 *outstr = ltgetstr(outcap, spp);
1521 if (*outstr == NULL)
1522 /* No specific out capability; use "me". */
1523 *outstr = ltgetstr("me", spp);
1524 if (*outstr == NULL)
1525 /* Don't even have "me"; use a null string. */
1526 *outstr = "";
1527 }
1528
1529 #endif /* MSDOS_COMPILER */
1530
1531
1532 /*
1533 * Below are the functions which perform all the
1534 * terminal-specific screen manipulation.
1535 */
1536
1537
1538 #if MSDOS_COMPILER
1539
1540 #if MSDOS_COMPILER==WIN32C
_settextposition(int row,int col)1541 static void _settextposition(int row, int col)
1542 {
1543 COORD cpos;
1544 CONSOLE_SCREEN_BUFFER_INFO csbi;
1545
1546 GetConsoleScreenBufferInfo(con_out, &csbi);
1547 cpos.X = csbi.srWindow.Left + (col - 1);
1548 cpos.Y = csbi.srWindow.Top + (row - 1);
1549 SetConsoleCursorPosition(con_out, cpos);
1550 }
1551 #endif
1552
1553 /*
1554 * Initialize the screen to the correct color at startup.
1555 */
initcolor(void)1556 static void initcolor(void)
1557 {
1558 #if MSDOS_COMPILER==BORLANDC || MSDOS_COMPILER==DJGPPC
1559 intensevideo();
1560 #endif
1561 SETCOLORS(nm_fg_color, nm_bg_color);
1562 #if 0
1563 /*
1564 * This clears the screen at startup. This is different from
1565 * the behavior of other versions of less. Disable it for now.
1566 */
1567 char *blanks;
1568 int row;
1569 int col;
1570
1571 /*
1572 * Create a complete, blank screen using "normal" colors.
1573 */
1574 SETCOLORS(nm_fg_color, nm_bg_color);
1575 blanks = (char *) ecalloc(width+1, sizeof(char));
1576 for (col = 0; col < sc_width; col++)
1577 blanks[col] = ' ';
1578 blanks[sc_width] = '\0';
1579 for (row = 0; row < sc_height; row++)
1580 _outtext(blanks);
1581 free(blanks);
1582 #endif
1583 }
1584 #endif
1585
1586 #if MSDOS_COMPILER==WIN32C
1587
1588 /*
1589 * Enable virtual terminal processing, if available.
1590 */
win32_init_vt_term(void)1591 static void win32_init_vt_term(void)
1592 {
1593 DWORD console_output_mode;
1594
1595 if (vt_enabled == 0 || (vt_enabled == 1 && con_out == con_out_ours))
1596 return;
1597
1598 console_output_mode = init_console_output_mode | ENABLE_VIRTUAL_TERMINAL_PROCESSING;
1599 vt_enabled = SetConsoleMode(con_out, console_output_mode);
1600 if (vt_enabled)
1601 {
1602 auto_wrap = 0;
1603 ignaw = 1;
1604 }
1605 }
1606
win32_deinit_vt_term(void)1607 static void win32_deinit_vt_term(void)
1608 {
1609 if (vt_enabled == 1 && con_out == con_out_save)
1610 SetConsoleMode(con_out, init_console_output_mode);
1611 }
1612
1613 /*
1614 * Termcap-like init with a private win32 console.
1615 */
win32_init_term(void)1616 static void win32_init_term(void)
1617 {
1618 CONSOLE_SCREEN_BUFFER_INFO scr;
1619 COORD size;
1620
1621 if (con_out_save == INVALID_HANDLE_VALUE)
1622 return;
1623
1624 GetConsoleScreenBufferInfo(con_out_save, &scr);
1625
1626 if (con_out_ours == INVALID_HANDLE_VALUE)
1627 {
1628 /*
1629 * Create our own screen buffer, so that we
1630 * may restore the original when done.
1631 */
1632 con_out_ours = CreateConsoleScreenBuffer(
1633 GENERIC_WRITE | GENERIC_READ,
1634 FILE_SHARE_WRITE | FILE_SHARE_READ,
1635 (LPSECURITY_ATTRIBUTES) NULL,
1636 CONSOLE_TEXTMODE_BUFFER,
1637 (LPVOID) NULL);
1638 }
1639
1640 size.X = scr.srWindow.Right - scr.srWindow.Left + 1;
1641 size.Y = scr.srWindow.Bottom - scr.srWindow.Top + 1;
1642 SetConsoleScreenBufferSize(con_out_ours, size);
1643 SetConsoleActiveScreenBuffer(con_out_ours);
1644 con_out = con_out_ours;
1645 }
1646
1647 /*
1648 * Restore the startup console.
1649 */
win32_deinit_term(void)1650 static void win32_deinit_term(void)
1651 {
1652 if (con_out_save == INVALID_HANDLE_VALUE)
1653 return;
1654 if (quitting)
1655 (void) CloseHandle(con_out_ours);
1656 SetConsoleActiveScreenBuffer(con_out_save);
1657 con_out = con_out_save;
1658 }
1659
1660 #endif
1661
1662 #if !MSDOS_COMPILER
do_tputs(constant char * str,int affcnt,int (* f_putc)(int))1663 static void do_tputs(constant char *str, int affcnt, int (*f_putc)(int))
1664 {
1665 #if LESSTEST
1666 if (is_lesstest() && f_putc == putchr)
1667 putstr(str);
1668 else
1669 #endif /*LESSTEST*/
1670 tputs(str, affcnt, f_putc);
1671 }
1672
1673 /*
1674 * Like tputs but we handle $<...> delay strings here because
1675 * some implementations of tputs don't perform delays correctly.
1676 */
ltputs(constant char * str,int affcnt,int (* f_putc)(int))1677 static void ltputs(constant char *str, int affcnt, int (*f_putc)(int))
1678 {
1679 while (str != NULL && *str != '\0')
1680 {
1681 #if HAVE_STRSTR
1682 constant char *obrac = strstr(str, "$<");
1683 if (obrac != NULL)
1684 {
1685 char str2[64];
1686 size_t slen = ptr_diff(obrac, str);
1687 if (slen < sizeof(str2))
1688 {
1689 int delay;
1690 /* Output first part of string (before "$<"). */
1691 memcpy(str2, str, slen);
1692 str2[slen] = '\0';
1693 do_tputs(str2, affcnt, f_putc);
1694 str += slen + 2;
1695 /* Perform the delay. */
1696 delay = lstrtoic(str, &str, 10);
1697 if (*str == '*')
1698 if (ckd_mul(&delay, delay, affcnt))
1699 delay = INT_MAX;
1700 flush();
1701 sleep_ms(delay);
1702 /* Skip past closing ">" at end of delay string. */
1703 str = strstr(str, ">");
1704 if (str != NULL)
1705 str++;
1706 continue;
1707 }
1708 }
1709 #endif
1710 /* Pass the rest of the string to tputs and we're done. */
1711 do_tputs(str, affcnt, f_putc);
1712 break;
1713 }
1714 }
1715 #endif /* MSDOS_COMPILER */
1716
1717 /*
1718 * Configure the terminal so mouse clicks and wheel moves
1719 * produce input to less.
1720 */
init_mouse(void)1721 public void init_mouse(void)
1722 {
1723 #if !MSDOS_COMPILER
1724 ltputs(sc_s_mousecap, sc_height, putchr);
1725 #else
1726 #if MSDOS_COMPILER==WIN32C
1727 curr_console_input_mode = mouse_console_input_mode;
1728 SetConsoleMode(tty, curr_console_input_mode);
1729 #endif
1730 #endif
1731 }
1732
1733 /*
1734 * Configure the terminal so mouse clicks and wheel moves
1735 * are handled by the system (so text can be selected, etc).
1736 */
deinit_mouse(void)1737 public void deinit_mouse(void)
1738 {
1739 #if !MSDOS_COMPILER
1740 ltputs(sc_e_mousecap, sc_height, putchr);
1741 #else
1742 #if MSDOS_COMPILER==WIN32C
1743 curr_console_input_mode = base_console_input_mode;
1744 SetConsoleMode(tty, curr_console_input_mode);
1745 #endif
1746 #endif
1747 }
1748
1749 /*
1750 * Initialize terminal
1751 */
init(void)1752 public void init(void)
1753 {
1754 clear_bot_if_needed();
1755 #if !MSDOS_COMPILER
1756 if (!(quit_if_one_screen && one_screen))
1757 {
1758 if (!no_init)
1759 {
1760 ltputs(sc_init, sc_height, putchr);
1761 /*
1762 * Some terminals leave the cursor unmoved when switching
1763 * to the alt screen. To avoid having the text appear at
1764 * a seemingly random line on the alt screen, move to
1765 * lower left if we are using an alt screen.
1766 */
1767 if (*sc_init != '\0' && *sc_deinit != '\0' && !no_alt_screen)
1768 lower_left();
1769 term_init_done = 1;
1770 }
1771 if (!no_keypad)
1772 ltputs(sc_s_keypad, sc_height, putchr);
1773 if (mousecap)
1774 init_mouse();
1775 }
1776 init_done = 1;
1777 if (top_scroll)
1778 {
1779 int i;
1780
1781 /*
1782 * This is nice to terminals with no alternate screen,
1783 * but with saved scrolled-off-the-top lines. This way,
1784 * no previous line is lost, but we start with a whole
1785 * screen to ourself.
1786 */
1787 for (i = 1; i < sc_height; i++)
1788 putchr('\n');
1789 } else
1790 line_left();
1791 #else
1792 #if MSDOS_COMPILER==WIN32C
1793 if (!(quit_if_one_screen && one_screen))
1794 {
1795 if (!no_init)
1796 {
1797 win32_init_term();
1798 term_init_done = 1;
1799 }
1800 if (mousecap)
1801 init_mouse();
1802
1803 }
1804 win32_init_vt_term();
1805 #endif
1806 init_done = 1;
1807 initcolor();
1808 flush();
1809 #endif
1810 }
1811
1812 /*
1813 * Deinitialize terminal
1814 */
deinit(void)1815 public void deinit(void)
1816 {
1817 if (!init_done)
1818 return;
1819 #if !MSDOS_COMPILER
1820 if (!(quit_if_one_screen && one_screen))
1821 {
1822 if (mousecap)
1823 deinit_mouse();
1824 if (!no_keypad)
1825 ltputs(sc_e_keypad, sc_height, putchr);
1826 if (!no_init)
1827 ltputs(sc_deinit, sc_height, putchr);
1828 }
1829 #else
1830 /* Restore system colors. */
1831 SETCOLORS(sy_fg_color, sy_bg_color);
1832 #if MSDOS_COMPILER==WIN32C
1833 win32_deinit_vt_term();
1834 if (!(quit_if_one_screen && one_screen))
1835 {
1836 if (mousecap)
1837 deinit_mouse();
1838 if (!no_init)
1839 win32_deinit_term();
1840 }
1841 #else
1842 /* Need clreol to make SETCOLORS take effect. */
1843 clreol();
1844 #endif
1845 #endif
1846 init_done = 0;
1847 }
1848
1849 /*
1850 * Are we interactive (ie. writing to an initialized tty)?
1851 */
interactive(void)1852 public int interactive(void)
1853 {
1854 return (is_tty && init_done);
1855 }
1856
assert_interactive(void)1857 static void assert_interactive(void)
1858 {
1859 if (interactive()) return;
1860 /* abort(); */
1861 }
1862
1863 /*
1864 * Home cursor (move to upper left corner of screen).
1865 */
home(void)1866 public void home(void)
1867 {
1868 assert_interactive();
1869 #if !MSDOS_COMPILER
1870 ltputs(sc_home, 1, putchr);
1871 #else
1872 flush();
1873 _settextposition(1,1);
1874 #endif
1875 }
1876
1877 #if LESSTEST
dump_screen(void)1878 public void dump_screen(void)
1879 {
1880 char dump_cmd[32];
1881 SNPRINTF1(dump_cmd, sizeof(dump_cmd), ESCS"0;0;%dR", sc_width * sc_height);
1882 ltputs(dump_cmd, sc_height, putchr);
1883 flush();
1884 }
1885 #endif /*LESSTEST*/
1886
1887 /*
1888 * Add a blank line (called with cursor at home).
1889 * Should scroll the display down.
1890 */
add_line(void)1891 public void add_line(void)
1892 {
1893 assert_interactive();
1894 #if !MSDOS_COMPILER
1895 ltputs(sc_addline, sc_height, putchr);
1896 #else
1897 flush();
1898 #if MSDOS_COMPILER==MSOFTC
1899 _scrolltextwindow(_GSCROLLDOWN);
1900 _settextposition(1,1);
1901 #else
1902 #if MSDOS_COMPILER==BORLANDC || MSDOS_COMPILER==DJGPPC
1903 movetext(1,1, sc_width,sc_height-1, 1,2);
1904 gotoxy(1,1);
1905 clreol();
1906 #else
1907 #if MSDOS_COMPILER==WIN32C
1908 {
1909 CHAR_INFO fillchar;
1910 SMALL_RECT rcSrc, rcClip;
1911 COORD new_org;
1912 CONSOLE_SCREEN_BUFFER_INFO csbi;
1913
1914 GetConsoleScreenBufferInfo(con_out,&csbi);
1915
1916 /* The clip rectangle is the entire visible screen. */
1917 rcClip.Left = csbi.srWindow.Left;
1918 rcClip.Top = csbi.srWindow.Top;
1919 rcClip.Right = csbi.srWindow.Right;
1920 rcClip.Bottom = csbi.srWindow.Bottom;
1921
1922 /* The source rectangle is the visible screen minus the last line. */
1923 rcSrc = rcClip;
1924 rcSrc.Bottom--;
1925
1926 /* Move the top left corner of the source window down one row. */
1927 new_org.X = rcSrc.Left;
1928 new_org.Y = rcSrc.Top + 1;
1929
1930 /* Fill the right character and attributes. */
1931 fillchar.Char.AsciiChar = ' ';
1932 curr_attr = MAKEATTR(nm_fg_color, nm_bg_color);
1933 fillchar.Attributes = curr_attr;
1934 ScrollConsoleScreenBuffer(con_out, &rcSrc, &rcClip, new_org, &fillchar);
1935 _settextposition(1,1);
1936 }
1937 #endif
1938 #endif
1939 #endif
1940 #endif
1941 }
1942
1943 #if 0
1944 /*
1945 * Remove the n topmost lines and scroll everything below it in the
1946 * window upward. This is needed to stop leaking the topmost line
1947 * into the scrollback buffer when we go down-one-line (in WIN32).
1948 */
1949 public void remove_top(int n)
1950 {
1951 #if MSDOS_COMPILER==WIN32C
1952 SMALL_RECT rcSrc, rcClip;
1953 CHAR_INFO fillchar;
1954 COORD new_org;
1955 CONSOLE_SCREEN_BUFFER_INFO csbi; /* to get buffer info */
1956
1957 if (n >= sc_height - 1)
1958 {
1959 clear();
1960 home();
1961 return;
1962 }
1963
1964 flush();
1965
1966 GetConsoleScreenBufferInfo(con_out, &csbi);
1967
1968 /* Get the extent of all-visible-rows-but-the-last. */
1969 rcSrc.Left = csbi.srWindow.Left;
1970 rcSrc.Top = csbi.srWindow.Top + n;
1971 rcSrc.Right = csbi.srWindow.Right;
1972 rcSrc.Bottom = csbi.srWindow.Bottom;
1973
1974 /* Get the clip rectangle. */
1975 rcClip.Left = rcSrc.Left;
1976 rcClip.Top = csbi.srWindow.Top;
1977 rcClip.Right = rcSrc.Right;
1978 rcClip.Bottom = rcSrc.Bottom ;
1979
1980 /* Move the source window up n rows. */
1981 new_org.X = rcSrc.Left;
1982 new_org.Y = rcSrc.Top - n;
1983
1984 /* Fill the right character and attributes. */
1985 fillchar.Char.AsciiChar = ' ';
1986 curr_attr = MAKEATTR(nm_fg_color, nm_bg_color);
1987 fillchar.Attributes = curr_attr;
1988
1989 ScrollConsoleScreenBuffer(con_out, &rcSrc, &rcClip, new_org, &fillchar);
1990
1991 /* Position cursor on first blank line. */
1992 goto_line(sc_height - n - 1);
1993 #endif
1994 }
1995 #endif
1996
1997 #if MSDOS_COMPILER==WIN32C
1998 /*
1999 * Clear the screen.
2000 */
win32_clear(void)2001 static void win32_clear(void)
2002 {
2003 /*
2004 * This will clear only the currently visible rows of the NT
2005 * console buffer, which means none of the precious scrollback
2006 * rows are touched making for faster scrolling. Note that, if
2007 * the window has fewer columns than the console buffer (i.e.
2008 * there is a horizontal scrollbar as well), the entire width
2009 * of the visible rows will be cleared.
2010 */
2011 COORD topleft;
2012 DWORD nchars;
2013 DWORD winsz;
2014 CONSOLE_SCREEN_BUFFER_INFO csbi;
2015
2016 /* get the number of cells in the current buffer */
2017 GetConsoleScreenBufferInfo(con_out, &csbi);
2018 winsz = csbi.dwSize.X * (csbi.srWindow.Bottom - csbi.srWindow.Top + 1);
2019 topleft.X = 0;
2020 topleft.Y = csbi.srWindow.Top;
2021
2022 curr_attr = MAKEATTR(nm_fg_color, nm_bg_color);
2023 FillConsoleOutputCharacter(con_out, ' ', winsz, topleft, &nchars);
2024 FillConsoleOutputAttribute(con_out, curr_attr, winsz, topleft, &nchars);
2025 }
2026
2027 /*
2028 * Remove the n topmost lines and scroll everything below it in the
2029 * window upward.
2030 */
win32_scroll_up(int n)2031 public void win32_scroll_up(int n)
2032 {
2033 SMALL_RECT rcSrc, rcClip;
2034 CHAR_INFO fillchar;
2035 COORD topleft;
2036 COORD new_org;
2037 DWORD nchars;
2038 DWORD size;
2039 CONSOLE_SCREEN_BUFFER_INFO csbi;
2040
2041 if (n <= 0)
2042 return;
2043
2044 if (n >= sc_height - 1)
2045 {
2046 win32_clear();
2047 _settextposition(1,1);
2048 return;
2049 }
2050
2051 /* Get the extent of what will remain visible after scrolling. */
2052 GetConsoleScreenBufferInfo(con_out, &csbi);
2053 rcSrc.Left = csbi.srWindow.Left;
2054 rcSrc.Top = csbi.srWindow.Top + n;
2055 rcSrc.Right = csbi.srWindow.Right;
2056 rcSrc.Bottom = csbi.srWindow.Bottom;
2057
2058 /* Get the clip rectangle. */
2059 rcClip.Left = rcSrc.Left;
2060 rcClip.Top = csbi.srWindow.Top;
2061 rcClip.Right = rcSrc.Right;
2062 rcClip.Bottom = rcSrc.Bottom ;
2063
2064 /* Move the source text to the top of the screen. */
2065 new_org.X = rcSrc.Left;
2066 new_org.Y = rcClip.Top;
2067
2068 /* Fill the right character and attributes. */
2069 fillchar.Char.AsciiChar = ' ';
2070 fillchar.Attributes = MAKEATTR(nm_fg_color, nm_bg_color);
2071
2072 /* Scroll the window. */
2073 SetConsoleTextAttribute(con_out, fillchar.Attributes);
2074 ScrollConsoleScreenBuffer(con_out, &rcSrc, &rcClip, new_org, &fillchar);
2075
2076 /* Clear remaining lines at bottom. */
2077 topleft.X = csbi.dwCursorPosition.X;
2078 topleft.Y = rcSrc.Bottom - n;
2079 size = (n * csbi.dwSize.X) + (rcSrc.Right - topleft.X);
2080 FillConsoleOutputCharacter(con_out, ' ', size, topleft,
2081 &nchars);
2082 FillConsoleOutputAttribute(con_out, fillchar.Attributes, size, topleft,
2083 &nchars);
2084 SetConsoleTextAttribute(con_out, curr_attr);
2085
2086 /* Move cursor n lines up from where it was. */
2087 csbi.dwCursorPosition.Y -= n;
2088 SetConsoleCursorPosition(con_out, csbi.dwCursorPosition);
2089 }
2090 #endif
2091
2092 /*
2093 * Move cursor to lower left corner of screen.
2094 */
lower_left(void)2095 public void lower_left(void)
2096 {
2097 assert_interactive();
2098 #if !MSDOS_COMPILER
2099 ltputs(sc_lower_left, 1, putchr);
2100 #else
2101 flush();
2102 _settextposition(sc_height, 1);
2103 #endif
2104 }
2105
2106 /*
2107 * Move cursor to left position of current line.
2108 */
line_left(void)2109 public void line_left(void)
2110 {
2111 assert_interactive();
2112 #if !MSDOS_COMPILER
2113 ltputs(sc_return, 1, putchr);
2114 #else
2115 {
2116 int row;
2117 flush();
2118 #if MSDOS_COMPILER==WIN32C
2119 {
2120 CONSOLE_SCREEN_BUFFER_INFO scr;
2121 GetConsoleScreenBufferInfo(con_out, &scr);
2122 row = scr.dwCursorPosition.Y - scr.srWindow.Top + 1;
2123 }
2124 #else
2125 #if MSDOS_COMPILER==BORLANDC || MSDOS_COMPILER==DJGPPC
2126 row = wherey();
2127 #else
2128 {
2129 struct rccoord tpos = _gettextposition();
2130 row = tpos.row;
2131 }
2132 #endif
2133 #endif
2134 _settextposition(row, 1);
2135 }
2136 #endif
2137 }
2138
2139 /*
2140 * Check if the console size has changed and reset internals
2141 * (in lieu of SIGWINCH for WIN32).
2142 */
check_winch(void)2143 public void check_winch(void)
2144 {
2145 #if MSDOS_COMPILER==WIN32C
2146 CONSOLE_SCREEN_BUFFER_INFO scr;
2147 COORD size;
2148
2149 if (con_out == INVALID_HANDLE_VALUE)
2150 return;
2151
2152 flush();
2153 GetConsoleScreenBufferInfo(con_out, &scr);
2154 size.Y = scr.srWindow.Bottom - scr.srWindow.Top + 1;
2155 size.X = scr.srWindow.Right - scr.srWindow.Left + 1;
2156 if (size.Y != sc_height || size.X != sc_width)
2157 {
2158 sc_height = size.Y;
2159 sc_width = size.X;
2160 if (!no_init && con_out_ours == con_out)
2161 SetConsoleScreenBufferSize(con_out, size);
2162 pos_init();
2163 wscroll = (sc_height + 1) / 2;
2164 screen_trashed();
2165 }
2166 #endif
2167 }
2168
2169 /*
2170 * Goto a specific line on the screen.
2171 */
goto_line(int sindex)2172 public void goto_line(int sindex)
2173 {
2174 assert_interactive();
2175 #if !MSDOS_COMPILER
2176 ltputs(tgoto(sc_move, 0, sindex), 1, putchr);
2177 #else
2178 flush();
2179 _settextposition(sindex+1, 1);
2180 #endif
2181 }
2182
2183 #if MSDOS_COMPILER==MSOFTC || MSDOS_COMPILER==BORLANDC
2184 /*
2185 * Create an alternate screen which is all white.
2186 * This screen is used to create a "flash" effect, by displaying it
2187 * briefly and then switching back to the normal screen.
2188 * {{ Yuck! There must be a better way to get a visual bell. }}
2189 */
create_flash(void)2190 static void create_flash(void)
2191 {
2192 #if MSDOS_COMPILER==MSOFTC
2193 struct videoconfig w;
2194 char *blanks;
2195 int row, col;
2196
2197 _getvideoconfig(&w);
2198 videopages = w.numvideopages;
2199 if (videopages < 2)
2200 {
2201 at_enter(AT_STANDOUT);
2202 at_exit();
2203 } else
2204 {
2205 _setactivepage(1);
2206 at_enter(AT_STANDOUT);
2207 blanks = (char *) ecalloc(w.numtextcols, sizeof(char));
2208 for (col = 0; col < w.numtextcols; col++)
2209 blanks[col] = ' ';
2210 for (row = w.numtextrows; row > 0; row--)
2211 _outmem(blanks, w.numtextcols);
2212 _setactivepage(0);
2213 _setvisualpage(0);
2214 free(blanks);
2215 at_exit();
2216 }
2217 #else
2218 #if MSDOS_COMPILER==BORLANDC
2219 int n;
2220
2221 whitescreen = (unsigned short *)
2222 malloc(sc_width * sc_height * sizeof(short));
2223 if (whitescreen == NULL)
2224 return;
2225 for (n = 0; n < sc_width * sc_height; n++)
2226 whitescreen[n] = 0x7020;
2227 #endif
2228 #endif
2229 flash_created = 1;
2230 }
2231 #endif /* MSDOS_COMPILER */
2232
2233 /*
2234 * Output the "visual bell", if there is one.
2235 */
vbell(void)2236 public void vbell(void)
2237 {
2238 if (no_vbell)
2239 return;
2240 #if !MSDOS_COMPILER
2241 if (*sc_visual_bell == '\0')
2242 return;
2243 ltputs(sc_visual_bell, sc_height, putchr);
2244 #else
2245 #if MSDOS_COMPILER==DJGPPC
2246 ScreenVisualBell();
2247 #else
2248 #if MSDOS_COMPILER==MSOFTC
2249 /*
2250 * Create a flash screen on the second video page.
2251 * Switch to that page, then switch back.
2252 */
2253 if (!flash_created)
2254 create_flash();
2255 if (videopages < 2)
2256 return;
2257 _setvisualpage(1);
2258 delay(100);
2259 _setvisualpage(0);
2260 #else
2261 #if MSDOS_COMPILER==BORLANDC
2262 unsigned short *currscreen;
2263
2264 /*
2265 * Get a copy of the current screen.
2266 * Display the flash screen.
2267 * Then restore the old screen.
2268 */
2269 if (!flash_created)
2270 create_flash();
2271 if (whitescreen == NULL)
2272 return;
2273 currscreen = (unsigned short *)
2274 malloc(sc_width * sc_height * sizeof(short));
2275 if (currscreen == NULL) return;
2276 gettext(1, 1, sc_width, sc_height, currscreen);
2277 puttext(1, 1, sc_width, sc_height, whitescreen);
2278 delay(100);
2279 puttext(1, 1, sc_width, sc_height, currscreen);
2280 free(currscreen);
2281 #else
2282 #if MSDOS_COMPILER==WIN32C
2283 /* paint screen with an inverse color */
2284 clear();
2285
2286 /* leave it displayed for 100 msec. */
2287 Sleep(100);
2288
2289 /* restore with a redraw */
2290 repaint();
2291 #endif
2292 #endif
2293 #endif
2294 #endif
2295 #endif
2296 }
2297
2298 /*
2299 * Make a noise.
2300 */
beep(void)2301 static void beep(void)
2302 {
2303 #if !MSDOS_COMPILER
2304 putchr(CONTROL('G'));
2305 #else
2306 #if MSDOS_COMPILER==WIN32C
2307 MessageBeep(0);
2308 #else
2309 write(1, "\7", 1);
2310 #endif
2311 #endif
2312 }
2313
2314 /*
2315 * Ring the terminal bell.
2316 */
bell(void)2317 public void bell(void)
2318 {
2319 if (quiet == VERY_QUIET)
2320 vbell();
2321 else
2322 beep();
2323 }
2324
2325 /*
2326 * Clear the screen.
2327 */
clear(void)2328 public void clear(void)
2329 {
2330 assert_interactive();
2331 #if !MSDOS_COMPILER
2332 ltputs(sc_clear, sc_height, putchr);
2333 #else
2334 flush();
2335 #if MSDOS_COMPILER==WIN32C
2336 win32_clear();
2337 #else
2338 _clearscreen(_GCLEARSCREEN);
2339 #endif
2340 #endif
2341 }
2342
2343 /*
2344 * Clear from the cursor to the end of the cursor's line.
2345 * {{ This must not move the cursor. }}
2346 */
clear_eol(void)2347 public void clear_eol(void)
2348 {
2349 /* assert_interactive();*/
2350 #if !MSDOS_COMPILER
2351 ltputs(sc_eol_clear, 1, putchr);
2352 #else
2353 #if MSDOS_COMPILER==MSOFTC
2354 short top, left;
2355 short bot, right;
2356 struct rccoord tpos;
2357
2358 flush();
2359 /*
2360 * Save current state.
2361 */
2362 tpos = _gettextposition();
2363 _gettextwindow(&top, &left, &bot, &right);
2364 /*
2365 * Set a temporary window to the current line,
2366 * from the cursor's position to the right edge of the screen.
2367 * Then clear that window.
2368 */
2369 _settextwindow(tpos.row, tpos.col, tpos.row, sc_width);
2370 _clearscreen(_GWINDOW);
2371 /*
2372 * Restore state.
2373 */
2374 _settextwindow(top, left, bot, right);
2375 _settextposition(tpos.row, tpos.col);
2376 #else
2377 #if MSDOS_COMPILER==BORLANDC || MSDOS_COMPILER==DJGPPC
2378 flush();
2379 clreol();
2380 #else
2381 #if MSDOS_COMPILER==WIN32C
2382 DWORD nchars;
2383 COORD cpos;
2384 CONSOLE_SCREEN_BUFFER_INFO scr;
2385
2386 flush();
2387 memset(&scr, 0, sizeof(scr));
2388 GetConsoleScreenBufferInfo(con_out, &scr);
2389 cpos.X = scr.dwCursorPosition.X;
2390 cpos.Y = scr.dwCursorPosition.Y;
2391 curr_attr = MAKEATTR(nm_fg_color, nm_bg_color);
2392 FillConsoleOutputAttribute(con_out, curr_attr,
2393 scr.dwSize.X - cpos.X, cpos, &nchars);
2394 FillConsoleOutputCharacter(con_out, ' ',
2395 scr.dwSize.X - cpos.X, cpos, &nchars);
2396 #endif
2397 #endif
2398 #endif
2399 #endif
2400 }
2401
2402 /*
2403 * Clear the current line.
2404 * Clear the screen if there's off-screen memory below the display.
2405 */
clear_eol_bot(void)2406 static void clear_eol_bot(void)
2407 {
2408 assert_interactive();
2409 #if MSDOS_COMPILER
2410 clear_eol();
2411 #else
2412 if (below_mem)
2413 ltputs(sc_eos_clear, 1, putchr);
2414 else
2415 ltputs(sc_eol_clear, 1, putchr);
2416 #endif
2417 }
2418
2419 /*
2420 * Clear the bottom line of the display.
2421 * Leave the cursor at the beginning of the bottom line.
2422 */
clear_bot(void)2423 public void clear_bot(void)
2424 {
2425 /*
2426 * If we're in a non-normal attribute mode, temporarily exit
2427 * the mode while we do the clear. Some terminals fill the
2428 * cleared area with the current attribute.
2429 */
2430 if (oldbot)
2431 lower_left();
2432 else
2433 line_left();
2434
2435 if (attrmode == AT_NORMAL)
2436 clear_eol_bot();
2437 else
2438 {
2439 int saved_attrmode = attrmode;
2440
2441 at_exit();
2442 clear_eol_bot();
2443 at_enter(saved_attrmode);
2444 }
2445 }
2446
2447 /*
2448 * Color string may be "x[y]" where x and y are 4-bit color chars,
2449 * or "N[.M]" where N and M are decimal integers>
2450 * Any of x,y,N,M may also be "-" to mean "unchanged".
2451 */
2452
2453 /*
2454 * Parse a 4-bit color char.
2455 */
parse_color4(char ch)2456 static int parse_color4(char ch)
2457 {
2458 switch (ch)
2459 {
2460 case 'k': return 0;
2461 case 'r': return CV_RED;
2462 case 'g': return CV_GREEN;
2463 case 'y': return CV_RED|CV_GREEN;
2464 case 'b': return CV_BLUE;
2465 case 'm': return CV_RED|CV_BLUE;
2466 case 'c': return CV_GREEN|CV_BLUE;
2467 case 'w': return CV_RED|CV_GREEN|CV_BLUE;
2468 case 'K': return 0|CV_BRIGHT;
2469 case 'R': return CV_RED|CV_BRIGHT;
2470 case 'G': return CV_GREEN|CV_BRIGHT;
2471 case 'Y': return CV_RED|CV_GREEN|CV_BRIGHT;
2472 case 'B': return CV_BLUE|CV_BRIGHT;
2473 case 'M': return CV_RED|CV_BLUE|CV_BRIGHT;
2474 case 'C': return CV_GREEN|CV_BLUE|CV_BRIGHT;
2475 case 'W': return CV_RED|CV_GREEN|CV_BLUE|CV_BRIGHT;
2476 case '-': return CV_NOCHANGE;
2477 default: return CV_ERROR;
2478 }
2479 }
2480
2481 /*
2482 * Parse a color as a decimal integer.
2483 */
parse_color6(constant char ** ps)2484 static int parse_color6(constant char **ps)
2485 {
2486 if (**ps == '-')
2487 {
2488 (*ps)++;
2489 return CV_NOCHANGE;
2490 } else
2491 {
2492 constant char *os = *ps;
2493 int color = lstrtoic(os, ps, 10);
2494 if (color < 0 || *ps == os)
2495 return CV_ERROR;
2496 return color;
2497 }
2498 }
2499
2500 /*
2501 * Parse a color pair and return the foreground/background/attribute values.
2502 * Return type of color specifier:
2503 * CV_4BIT: fg/bg values are OR of CV_{RGB} bits.
2504 * CV_6BIT: fg/bg values are integers entered by user.
2505 */
parse_color(constant char * str,mutable int * p_fg,mutable int * p_bg,mutable CHAR_ATTR * p_cattr)2506 public COLOR_TYPE parse_color(constant char *str, mutable int *p_fg, mutable int *p_bg, mutable CHAR_ATTR *p_cattr)
2507 {
2508 int fg;
2509 int bg = CV_ERROR;
2510 CHAR_ATTR cattr = CATTR_NULL;
2511 COLOR_TYPE type = CT_NULL;
2512
2513 if (str == NULL || *str == '\0')
2514 return CT_NULL;
2515 if (*str == '+')
2516 str++; /* ignore leading + */
2517
2518 fg = parse_color4(*str);
2519 if (fg != CV_ERROR)
2520 {
2521 if (str[1] == '\0' || strchr("*~_&dsul", str[1]) != NULL)
2522 {
2523 bg = CV_NOCHANGE;
2524 str++; /* skip the fg char */
2525 } else
2526 {
2527 bg = parse_color4(str[1]);
2528 if (bg != CV_ERROR)
2529 str += 2; /* skip both fg and bg chars */
2530 }
2531 }
2532 if (fg != CV_ERROR && bg != CV_ERROR)
2533 type = CT_4BIT;
2534 else
2535 {
2536 fg = (*str == '.') ? CV_NOCHANGE : parse_color6(&str);
2537 if (fg != CV_ERROR)
2538 {
2539 if (*str != '.')
2540 bg = CV_NOCHANGE;
2541 else
2542 {
2543 str++; /* skip the dot */
2544 bg = parse_color6(&str);
2545 }
2546 }
2547 if (fg != CV_ERROR && bg != CV_ERROR)
2548 type = CT_6BIT;
2549 }
2550 if (type != CT_NULL)
2551 {
2552 for (;; str++)
2553 {
2554 if (*str == '*' || *str == 'd')
2555 cattr |= CATTR_BOLD;
2556 else if (*str == '~' || *str == 's')
2557 cattr |= CATTR_STANDOUT;
2558 else if (*str == '_' || *str == 'u')
2559 cattr |= CATTR_UNDERLINE;
2560 else if (*str == '&' || *str == 'l') /* can't use 'k' because of conflict with "black" */
2561 cattr |= CATTR_BLINK;
2562 else
2563 break;
2564 }
2565 if (p_fg != NULL) *p_fg = fg;
2566 if (p_bg != NULL) *p_bg = bg;
2567 if (p_cattr != NULL) *p_cattr = cattr;
2568 }
2569 return type;
2570 }
2571
2572 #if !MSDOS_COMPILER
2573
sgr_color(int color)2574 static int sgr_color(int color)
2575 {
2576 switch (color)
2577 {
2578 case 0: return 30;
2579 case CV_RED: return 31;
2580 case CV_GREEN: return 32;
2581 case CV_RED|CV_GREEN: return 33;
2582 case CV_BLUE: return 34;
2583 case CV_RED|CV_BLUE: return 35;
2584 case CV_GREEN|CV_BLUE: return 36;
2585 case CV_RED|CV_GREEN|CV_BLUE: return 37;
2586
2587 case CV_BRIGHT: return 90;
2588 case CV_RED|CV_BRIGHT: return 91;
2589 case CV_GREEN|CV_BRIGHT: return 92;
2590 case CV_RED|CV_GREEN|CV_BRIGHT: return 93;
2591 case CV_BLUE|CV_BRIGHT: return 94;
2592 case CV_RED|CV_BLUE|CV_BRIGHT: return 95;
2593 case CV_GREEN|CV_BLUE|CV_BRIGHT: return 96;
2594 case CV_RED|CV_GREEN|CV_BLUE|CV_BRIGHT: return 97;
2595
2596 default: return color;
2597 }
2598 }
2599
tput_fmt(constant char * fmt,int color,int (* f_putc)(int))2600 static void tput_fmt(constant char *fmt, int color, int (*f_putc)(int))
2601 {
2602 char buf[INT_STRLEN_BOUND(int)+16];
2603 if (color == attrcolor)
2604 return;
2605 SNPRINTF1(buf, sizeof(buf), fmt, color);
2606 ltputs(buf, 1, f_putc);
2607 attrcolor = color;
2608 }
2609
tput_char_cattr(CHAR_ATTR cattr,int (* f_putc)(int))2610 static void tput_char_cattr(CHAR_ATTR cattr, int (*f_putc)(int))
2611 {
2612 if (cattr & CATTR_UNDERLINE)
2613 ltputs(sc_u_in, 1, f_putc);
2614 if (cattr & CATTR_BOLD)
2615 ltputs(sc_b_in, 1, f_putc);
2616 if (cattr & CATTR_BLINK)
2617 ltputs(sc_bl_in, 1, f_putc);
2618 if (cattr & CATTR_STANDOUT)
2619 ltputs(sc_s_in, 1, f_putc);
2620 }
2621
tput_color(constant char * str,int (* f_putc)(int))2622 static void tput_color(constant char *str, int (*f_putc)(int))
2623 {
2624 int fg;
2625 int bg;
2626 CHAR_ATTR cattr;
2627
2628 if (str != NULL && strcmp(str, "*") == 0)
2629 {
2630 /* Special case: reset to normal */
2631 tput_fmt(ESCS"[m", -1, f_putc);
2632 return;
2633 }
2634 switch (parse_color(str, &fg, &bg, &cattr))
2635 {
2636 case CT_4BIT:
2637 if (fg >= 0)
2638 tput_fmt(ESCS"[%dm", sgr_color(fg), f_putc);
2639 if (bg >= 0)
2640 tput_fmt(ESCS"[%dm", sgr_color(bg)+10, f_putc);
2641 tput_char_cattr(cattr, f_putc);
2642 break;
2643 case CT_6BIT:
2644 if (fg >= 0)
2645 tput_fmt(ESCS"[38;5;%dm", fg, f_putc);
2646 if (bg >= 0)
2647 tput_fmt(ESCS"[48;5;%dm", bg, f_putc);
2648 tput_char_cattr(cattr, f_putc);
2649 break;
2650 default:
2651 break;
2652 }
2653 }
2654
tput_inmode(constant char * mode_str,int attr,int attr_bit,int (* f_putc)(int))2655 static void tput_inmode(constant char *mode_str, int attr, int attr_bit, int (*f_putc)(int))
2656 {
2657 constant char *color_str;
2658 if ((attr & attr_bit) == 0)
2659 return;
2660 color_str = get_color_map(attr_bit);
2661 if (color_str == NULL || *color_str == '\0' || *color_str == '+')
2662 {
2663 ltputs(mode_str, 1, f_putc);
2664 if (color_str == NULL || *color_str++ != '+')
2665 return;
2666 }
2667 /* Color overrides mode string */
2668 tput_color(color_str, f_putc);
2669 }
2670
tput_outmode(constant char * mode_str,int attr_bit,int (* f_putc)(int))2671 static void tput_outmode(constant char *mode_str, int attr_bit, int (*f_putc)(int))
2672 {
2673 if ((attrmode & attr_bit) == 0)
2674 return;
2675 ltputs(mode_str, 1, f_putc);
2676 }
2677
2678 #else /* MSDOS_COMPILER */
2679
2680 #if MSDOS_COMPILER==WIN32C
WIN32put_fmt(constant char * fmt,int color)2681 static lbool WIN32put_fmt(constant char *fmt, int color)
2682 {
2683 char buf[INT_STRLEN_BOUND(int)+16];
2684 int len = (size_t) SNPRINTF1(buf, sizeof(buf), fmt, color);
2685 if (len > 0)
2686 WIN32textout(buf, (size_t) len);
2687 return TRUE;
2688 }
2689
win_set_cattr(CHAR_ATTR cattr)2690 static void win_set_cattr(CHAR_ATTR cattr)
2691 {
2692 if (cattr & CATTR_UNDERLINE)
2693 WIN32textout(ESCS"[4m", 4);
2694 if (cattr & CATTR_BOLD)
2695 WIN32textout(ESCS"[1m", 4);
2696 if (cattr & CATTR_BLINK)
2697 WIN32textout(ESCS"[5m", 4);
2698 if (cattr & CATTR_STANDOUT)
2699 WIN32textout(ESCS"[7m", 4);
2700 }
2701 #endif
2702
win_set_color(int attr)2703 static lbool win_set_color(int attr)
2704 {
2705 int fg;
2706 int bg;
2707 CHAR_ATTR cattr;
2708 lbool out = FALSE;
2709 constant char *str = get_color_map(attr);
2710 if (str == NULL || str[0] == '\0')
2711 return FALSE;
2712 switch (parse_color(str, &fg, &bg, &cattr))
2713 {
2714 case CT_4BIT:
2715 if (fg >= 0 && bg >= 0)
2716 {
2717 SETCOLORS(fg, bg);
2718 out = TRUE;
2719 } else if (fg >= 0)
2720 {
2721 SET_FG_COLOR(fg);
2722 out = TRUE;
2723 } else if (bg >= 0)
2724 {
2725 SET_BG_COLOR(bg);
2726 out = TRUE;
2727 }
2728 #if MSDOS_COMPILER==WIN32C
2729 if (vt_enabled)
2730 win_set_cattr(cattr);
2731 #endif
2732 break;
2733 #if MSDOS_COMPILER==WIN32C
2734 case CT_6BIT:
2735 if (vt_enabled)
2736 {
2737 if (fg > 0)
2738 out = WIN32put_fmt(ESCS"[38;5;%dm", fg);
2739 if (bg > 0)
2740 out = WIN32put_fmt(ESCS"[48;5;%dm", bg);
2741 win_set_cattr(cattr);
2742 }
2743 break;
2744 #endif
2745 default:
2746 break;
2747 }
2748 return out;
2749 }
2750
2751 #endif /* MSDOS_COMPILER */
2752
at_enter(int attr)2753 public void at_enter(int attr)
2754 {
2755 attr = apply_at_specials(attr);
2756 #if !MSDOS_COMPILER
2757 /* The one with the most priority is last. */
2758 tput_inmode(sc_u_in, attr, AT_UNDERLINE, putchr);
2759 tput_inmode(sc_b_in, attr, AT_BOLD, putchr);
2760 tput_inmode(sc_bl_in, attr, AT_BLINK, putchr);
2761 /* Don't use standout and color at the same time. */
2762 if (use_color && (attr & AT_COLOR))
2763 tput_color(get_color_map(attr), putchr);
2764 else
2765 tput_inmode(sc_s_in, attr, AT_STANDOUT, putchr);
2766 #else
2767 flush();
2768 /* The one with the most priority is first. */
2769 if ((attr & AT_COLOR) && use_color)
2770 {
2771 win_set_color(attr);
2772 } else if (attr & AT_STANDOUT)
2773 {
2774 SETCOLORS(so_fg_color, so_bg_color);
2775 } else if (attr & AT_BLINK)
2776 {
2777 SETCOLORS(bl_fg_color, bl_bg_color);
2778 } else if (attr & AT_BOLD)
2779 {
2780 SETCOLORS(bo_fg_color, bo_bg_color);
2781 } else if (attr & AT_UNDERLINE)
2782 {
2783 SETCOLORS(ul_fg_color, ul_bg_color);
2784 }
2785 #endif
2786 attrmode = attr;
2787 }
2788
at_exit(void)2789 public void at_exit(void)
2790 {
2791 #if !MSDOS_COMPILER
2792 /* Undo things in the reverse order we did them. */
2793 tput_color("*", putchr);
2794 tput_outmode(sc_s_out, AT_STANDOUT, putchr);
2795 tput_outmode(sc_bl_out, AT_BLINK, putchr);
2796 tput_outmode(sc_b_out, AT_BOLD, putchr);
2797 tput_outmode(sc_u_out, AT_UNDERLINE, putchr);
2798 #else
2799 flush();
2800 SETCOLORS(nm_fg_color, nm_bg_color);
2801 #endif
2802 attrmode = AT_NORMAL;
2803 }
2804
at_switch(int attr)2805 public void at_switch(int attr)
2806 {
2807 int new_attrmode = apply_at_specials(attr);
2808 int ignore_modes = AT_ANSI;
2809
2810 if ((new_attrmode & ~ignore_modes) != (attrmode & ~ignore_modes))
2811 {
2812 at_exit();
2813 at_enter(attr);
2814 }
2815 }
2816
is_at_equiv(int attr1,int attr2)2817 public lbool is_at_equiv(int attr1, int attr2)
2818 {
2819 attr1 = apply_at_specials(attr1);
2820 attr2 = apply_at_specials(attr2);
2821
2822 return (attr1 == attr2);
2823 }
2824
apply_at_specials(int attr)2825 public int apply_at_specials(int attr)
2826 {
2827 if (attr & AT_BINARY)
2828 attr |= binattr;
2829 if (attr & AT_HILITE)
2830 attr |= AT_STANDOUT;
2831 attr &= ~(AT_BINARY|AT_HILITE);
2832
2833 return attr;
2834 }
2835
2836 /*
2837 * Output a plain backspace, without erasing the previous char.
2838 */
putbs(void)2839 public void putbs(void)
2840 {
2841 if (termcap_debug)
2842 putstr("<bs>");
2843 else
2844 {
2845 #if !MSDOS_COMPILER
2846 ltputs(sc_backspace, 1, putchr);
2847 #else
2848 int row, col;
2849
2850 flush();
2851 {
2852 #if MSDOS_COMPILER==MSOFTC
2853 struct rccoord tpos;
2854 tpos = _gettextposition();
2855 row = tpos.row;
2856 col = tpos.col;
2857 #else
2858 #if MSDOS_COMPILER==BORLANDC || MSDOS_COMPILER==DJGPPC
2859 row = wherey();
2860 col = wherex();
2861 #else
2862 #if MSDOS_COMPILER==WIN32C
2863 CONSOLE_SCREEN_BUFFER_INFO scr;
2864 GetConsoleScreenBufferInfo(con_out, &scr);
2865 row = scr.dwCursorPosition.Y - scr.srWindow.Top + 1;
2866 col = scr.dwCursorPosition.X - scr.srWindow.Left + 1;
2867 #endif
2868 #endif
2869 #endif
2870 }
2871 if (col <= 1)
2872 return;
2873 _settextposition(row, col-1);
2874 #endif /* MSDOS_COMPILER */
2875 }
2876 }
2877
2878 #if MSDOS_COMPILER==WIN32C
2879
2880 #define WIN32_MAX_REPEAT 3
2881 #define LAST_DOWN_COUNT 8
2882 static LWCHAR last_downs[LAST_DOWN_COUNT] = { 0 };
2883 static int last_down_index = 0;
2884 static LWCHAR hi_surr = 0;
2885
2886 typedef struct XINPUT_RECORD {
2887 INPUT_RECORD ir;
2888 LWCHAR ichar; /* because ir...UnicodeChar is only 16 bits */
2889 } XINPUT_RECORD;
2890
2891 typedef struct WIN32_CHAR {
2892 struct WIN32_CHAR *wc_next;
2893 char wc_ch;
2894 } WIN32_CHAR;
2895
2896 static WIN32_CHAR *win32_queue = NULL;
2897
2898 /*
2899 * Is the win32_queue nonempty?
2900 */
win32_queued_char(void)2901 static int win32_queued_char(void)
2902 {
2903 return (win32_queue != NULL);
2904 }
2905
2906 /*
2907 * Push a char onto the back of the win32_queue.
2908 */
win32_enqueue(char ch)2909 static void win32_enqueue(char ch)
2910 {
2911 WIN32_CHAR *wch = (WIN32_CHAR *) ecalloc(1, sizeof(WIN32_CHAR));
2912 wch->wc_ch = ch;
2913 wch->wc_next = NULL;
2914 if (win32_queue == NULL)
2915 win32_queue = wch;
2916 else
2917 {
2918 WIN32_CHAR *pch;
2919 for (pch = win32_queue; pch->wc_next != NULL; pch = pch->wc_next)
2920 continue;
2921 pch->wc_next = wch;
2922 }
2923 }
2924
2925 /*
2926 * Push a char onto the front of the win32_queue.
2927 * Makes the next call to WIN32getch return ch.
2928 */
WIN32ungetch(int ch)2929 public void WIN32ungetch(int ch)
2930 {
2931 WIN32_CHAR *wch = (WIN32_CHAR *) ecalloc(1, sizeof(WIN32_CHAR));
2932 wch->wc_ch = ch;
2933 wch->wc_next = win32_queue;
2934 win32_queue = wch;
2935 }
2936
2937 /*
2938 * Get a char from the front of the win32_queue.
2939 */
win32_get_queue(void)2940 static char win32_get_queue(void)
2941 {
2942 WIN32_CHAR *wch = win32_queue;
2943 char ch = wch->wc_ch;
2944 win32_queue = wch->wc_next;
2945 free(wch);
2946 return ch;
2947 }
2948
2949 /*
2950 * Handle a mouse input event.
2951 */
win32_mouse_event(XINPUT_RECORD * xip)2952 static lbool win32_mouse_event(XINPUT_RECORD *xip)
2953 {
2954 char b;
2955
2956 if (!mousecap || xip->ir.EventType != MOUSE_EVENT ||
2957 xip->ir.Event.MouseEvent.dwEventFlags == MOUSE_MOVED)
2958 return (FALSE);
2959
2960 /* Generate an X11 mouse sequence from the mouse event. */
2961 /* TODO: switch to the 1006 protocol to allow specific-button-up reports */
2962 switch (xip->ir.Event.MouseEvent.dwEventFlags)
2963 {
2964 case 0: /* press or release */
2965 if (xip->ir.Event.MouseEvent.dwButtonState == 0)
2966 b = X11MOUSE_OFFSET + X11MOUSE_BUTTON_REL;
2967 else if (xip->ir.Event.MouseEvent.dwButtonState == 1) /* leftmost */
2968 b = X11MOUSE_OFFSET + X11MOUSE_BUTTON1;
2969 else if (xip->ir.Event.MouseEvent.dwButtonState == 2) /* rightmost */
2970 b = X11MOUSE_OFFSET + X11MOUSE_BUTTON3;
2971 else if (xip->ir.Event.MouseEvent.dwButtonState == 4) /* middle ("next-to-leftmost") */
2972 b = X11MOUSE_OFFSET + X11MOUSE_BUTTON2;
2973 else /* don't bother to figure out what changed */
2974 return (FALSE);
2975 break;
2976 case MOUSE_WHEELED:
2977 b = X11MOUSE_OFFSET + (((int)xip->ir.Event.MouseEvent.dwButtonState < 0) ? X11MOUSE_WHEEL_DOWN : X11MOUSE_WHEEL_UP);
2978 break;
2979 default:
2980 return (FALSE);
2981 }
2982 /* {{ TODO: change to X11 1006 format. }} */
2983 win32_enqueue(ESC);
2984 win32_enqueue('[');
2985 win32_enqueue('M');
2986 win32_enqueue(b);
2987 win32_enqueue(X11MOUSE_OFFSET + xip->ir.Event.MouseEvent.dwMousePosition.X + 1);
2988 win32_enqueue(X11MOUSE_OFFSET + xip->ir.Event.MouseEvent.dwMousePosition.Y + 1);
2989 return (TRUE);
2990 }
2991
set_last_down(LWCHAR ch)2992 static void set_last_down(LWCHAR ch)
2993 {
2994 if (ch == 0) return;
2995 last_downs[last_down_index] = ch;
2996 if (++last_down_index >= LAST_DOWN_COUNT)
2997 last_down_index = 0;
2998 }
2999
find_last_down(LWCHAR ch)3000 static LWCHAR *find_last_down(LWCHAR ch)
3001 {
3002 int i;
3003 for (i = 0; i < LAST_DOWN_COUNT; ++i)
3004 if (last_downs[i] == ch)
3005 return &last_downs[i];
3006 return NULL;
3007 }
3008
3009 /*
3010 * Get an input char from an INPUT_RECORD and store in xip->ichar.
3011 * Handles surrogate chars, and KeyUp without previous corresponding KeyDown.
3012 */
win32_get_ichar(XINPUT_RECORD * xip)3013 static lbool win32_get_ichar(XINPUT_RECORD *xip)
3014 {
3015 LWCHAR ch = xip->ir.Event.KeyEvent.uChar.UnicodeChar;
3016 xip->ichar = ch;
3017 if (!is_ascii_char(ch))
3018 {
3019 int is_down = xip->ir.Event.KeyEvent.bKeyDown;
3020 LWCHAR *last_down = find_last_down(ch);
3021 if (last_down == NULL) { /* key was up */
3022 if (is_down) { /* key was up, now is down */
3023 set_last_down(ch);
3024 } else { /* key up without previous down: pretend this is a down. */
3025 xip->ir.Event.KeyEvent.bKeyDown = 1;
3026 }
3027 } else if (!is_down) { /* key was down, now is up */
3028 *last_down = 0; /* use this last_down only once */
3029 }
3030
3031 if (ch >= 0xD800 && ch < 0xDC00) { /* high surrogate */
3032 hi_surr = 0x10000 + ((ch - 0xD800) << 10);
3033 return (FALSE); /* get next input, which should be the low surrogate */
3034 }
3035 if (ch >= 0xDC00 && ch < 0xE000) { /* low surrogate */
3036 xip->ichar = hi_surr + (ch - 0xDC00);
3037 hi_surr = 0;
3038 }
3039 }
3040 return (TRUE);
3041 }
3042
3043 /*
3044 * Handle a scan code (non-ASCII) key input.
3045 */
win32_scan_code(XINPUT_RECORD * xip)3046 static lbool win32_scan_code(XINPUT_RECORD *xip)
3047 {
3048 int scan = -1;
3049 if (xip->ir.Event.KeyEvent.dwControlKeyState & (LEFT_CTRL_PRESSED | RIGHT_CTRL_PRESSED))
3050 {
3051 switch (xip->ir.Event.KeyEvent.wVirtualScanCode)
3052 {
3053 case PCK_RIGHT: /* right arrow */
3054 scan = PCK_CTL_RIGHT;
3055 break;
3056 case PCK_LEFT: /* left arrow */
3057 scan = PCK_CTL_LEFT;
3058 break;
3059 case PCK_DELETE: /* delete */
3060 scan = PCK_CTL_DELETE;
3061 break;
3062 }
3063 } else if (xip->ir.Event.KeyEvent.dwControlKeyState & SHIFT_PRESSED)
3064 {
3065 if (xip->ichar == '\t')
3066 scan = PCK_SHIFT_TAB;
3067 }
3068 if (scan < 0 && xip->ichar == 0)
3069 scan = xip->ir.Event.KeyEvent.wVirtualScanCode;
3070 if (scan < 0)
3071 return (FALSE);
3072 /*
3073 * An extended key returns a 2 byte sequence consisting of
3074 * a zero byte followed by the scan code.
3075 */
3076 win32_enqueue('\0');
3077 win32_enqueue(scan);
3078 return (TRUE);
3079 }
3080
3081 /*
3082 * Handle a key input event.
3083 */
win32_key_event(XINPUT_RECORD * xip)3084 static lbool win32_key_event(XINPUT_RECORD *xip)
3085 {
3086 int repeat;
3087 char utf8[UTF8_MAX_LENGTH];
3088 char *up;
3089
3090 if (xip->ir.EventType != KEY_EVENT ||
3091 ((xip->ir.Event.KeyEvent.dwControlKeyState & (RIGHT_ALT_PRESSED|LEFT_CTRL_PRESSED)) == (RIGHT_ALT_PRESSED|LEFT_CTRL_PRESSED) && xip->ir.Event.KeyEvent.uChar.UnicodeChar == 0) ||
3092 (xip->ir.Event.KeyEvent.wVirtualScanCode == 0 && xip->ir.Event.KeyEvent.uChar.UnicodeChar == 0) ||
3093 xip->ir.Event.KeyEvent.wVirtualScanCode == PCK_CAPS_LOCK ||
3094 xip->ir.Event.KeyEvent.wVirtualScanCode == PCK_NUM_LOCK ||
3095 (xip->ir.Event.KeyEvent.wVirtualKeyCode == VK_MENU && xip->ir.Event.KeyEvent.uChar.UnicodeChar == 0) ||
3096 xip->ir.Event.KeyEvent.wVirtualKeyCode == VK_KANJI ||
3097 xip->ir.Event.KeyEvent.wVirtualKeyCode == VK_SHIFT ||
3098 xip->ir.Event.KeyEvent.wVirtualKeyCode == VK_CONTROL)
3099 return (FALSE);
3100
3101 if (!win32_get_ichar(xip))
3102 return (FALSE);
3103 if (!xip->ir.Event.KeyEvent.bKeyDown)
3104 return (FALSE);
3105
3106 if (win32_scan_code(xip))
3107 return (TRUE);
3108
3109 repeat = xip->ir.Event.KeyEvent.wRepeatCount;
3110 if (repeat > WIN32_MAX_REPEAT)
3111 repeat = WIN32_MAX_REPEAT;
3112 up = utf8;
3113 put_wchar(&up, xip->ichar);
3114 for (; repeat > 0; --repeat)
3115 {
3116 constant char *p;
3117 for (p = utf8; p < up; ++p)
3118 win32_enqueue(*p);
3119 }
3120 return (TRUE);
3121 }
3122
3123 /*
3124 * Determine whether an input character is waiting to be read.
3125 */
win32_kbhit(void)3126 public lbool win32_kbhit(void)
3127 {
3128 XINPUT_RECORD xip;
3129
3130 if (win32_queued_char())
3131 return (TRUE);
3132
3133 for (;;)
3134 {
3135 DWORD nread;
3136 DWORD console_input_mode;
3137 /*
3138 * When an input pipe closes, cmd may reset the console mode,
3139 * so set the mode every time we read input.
3140 */
3141 if (GetConsoleMode(tty, &console_input_mode) && console_input_mode != curr_console_input_mode)
3142 SetConsoleMode(tty, curr_console_input_mode);
3143 PeekConsoleInputW(tty, &xip.ir, 1, &nread);
3144 if (nread == 0)
3145 return (FALSE);
3146 ReadConsoleInputW(tty, &xip.ir, 1, &nread);
3147 if (nread == 0)
3148 return (FALSE);
3149 if (win32_mouse_event(&xip) || win32_key_event(&xip))
3150 break;
3151 }
3152 return (TRUE);
3153 }
3154
3155 /*
3156 * Read a character from the keyboard.
3157 */
WIN32getch(void)3158 public char WIN32getch(void)
3159 {
3160 while (!win32_kbhit())
3161 {
3162 Sleep(20);
3163 if (ABORT_SIGS())
3164 return ('\003');
3165 }
3166 return (win32_get_queue());
3167 }
3168
win32_getch_clear(void)3169 public void win32_getch_clear(void)
3170 {
3171 while (win32_kbhit())
3172 (void) WIN32getch();
3173 }
3174
3175 #endif /* MSDOS_COMPILER==WIN32C */
3176
3177 #if MSDOS_COMPILER
3178 /*
3179 */
WIN32setcolors(int fg,int bg)3180 public void WIN32setcolors(int fg, int bg)
3181 {
3182 SETCOLORS(fg, bg);
3183 }
3184
3185 /*
3186 */
WIN32textout(constant char * text,size_t len)3187 public void WIN32textout(constant char *text, size_t len)
3188 {
3189 #if MSDOS_COMPILER==WIN32C
3190 DWORD written;
3191 if (utf_mode == 2)
3192 {
3193 /*
3194 * We've got UTF-8 text in a non-UTF-8 console. Convert it to
3195 * wide and use WriteConsoleW.
3196 * Biggest input len is OUTBUF_SIZE of obuf from win_flush,
3197 * which is also the biggest output count if it's ASCII.
3198 * "static" wtext is not a state - only avoid 16K on stack.
3199 */
3200 static WCHAR wtext[OUTBUF_SIZE];
3201 len = MultiByteToWideChar(CP_UTF8, 0, text, len, wtext, countof(wtext));
3202 WriteConsoleW(con_out, wtext, len, &written, NULL);
3203 } else
3204 WriteConsole(con_out, text, len, &written, NULL);
3205 #else
3206 char buf[2048];
3207 if (len >= sizeof(buf))
3208 len = sizeof(buf) - 1;
3209 memcpy(buf, text, len);
3210 buf[len] = 0;
3211 cputs(buf);
3212 #endif
3213 }
3214 #endif
3215