misc changes
[bpt/emacs.git] / src / msdos.c
1 /* MS-DOS specific C utilities. -*- coding: cp850 -*-
2
3 Copyright (C) 1993-1997, 1999-2014 Free Software 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 /* Contributed by Morten Welinder */
21 /* New display, keyboard, and mouse control by Kim F. Storm */
22
23 /* Note: This file MUST use a unibyte encoding, to both display the
24 keys on the non-US keyboard layout as their respective labels, and
25 provide the correct byte values for the keyboard input to inject
26 into Emacs. See 'struct dos_keyboard_map' below. As long as there
27 are only European keyboard layouts here, we are OK with DOS
28 codepage 850 encoding. */
29
30 /* Note: some of the stuff here was taken from end of sysdep.c in demacs. */
31
32 #include <config.h>
33
34 #ifdef MSDOS
35 #include <setjmp.h>
36 #include "lisp.h"
37 #include <stdio.h>
38 #include <time.h>
39 #include <sys/param.h>
40 #include <sys/time.h>
41 /* gettime and settime in dos.h clash with their namesakes from
42 gnulib, so we move out of our way the prototypes in dos.h. */
43 #define gettime dos_h_gettime_
44 #define settime dos_h_settime_
45 #include <dos.h>
46 #undef gettime
47 #undef settime
48 #include <errno.h>
49 #include <sys/stat.h> /* for _fixpath */
50 #include <unistd.h> /* for chdir, dup, dup2, etc. */
51 #include <dir.h> /* for getdisk */
52 #pragma pack(0) /* dir.h does a pack(4), which isn't GCC's default */
53 #undef opendir
54 #include <dirent.h> /* for opendir */
55 #include <fcntl.h>
56 #include <io.h> /* for setmode */
57 #include <dpmi.h> /* for __dpmi_xxx stuff */
58 #include <sys/farptr.h> /* for _farsetsel, _farnspokeb */
59 #include <libc/dosio.h> /* for _USE_LFN */
60 #include <conio.h> /* for cputs */
61
62 #include "msdos.h"
63 #include "systime.h"
64 #include "frame.h"
65 #include "termhooks.h"
66 #include "termchar.h"
67 #include "dispextern.h"
68 #include "dosfns.h"
69 #include "termopts.h"
70 #include "character.h"
71 #include "coding.h"
72 #include "disptab.h"
73 #include "window.h"
74 #include "buffer.h"
75 #include "commands.h"
76 #include "blockinput.h"
77 #include "keyboard.h"
78 #include "intervals.h"
79 #include <go32.h>
80 #include <pc.h>
81 #include <ctype.h>
82 /* #include <process.h> */
83 /* Damn that local process.h! Instead we can define P_WAIT and
84 spawnve ourselves. */
85 #define P_WAIT 1
86 extern int spawnve (int, const char *, char *const [], char *const []);
87
88 #ifndef _USE_LFN
89 #define _USE_LFN 0
90 #endif
91
92 #ifndef _dos_ds
93 #define _dos_ds _go32_info_block.selector_for_linear_memory
94 #endif
95
96 #include <signal.h>
97 #include "syssignal.h"
98
99 #include "careadlinkat.h"
100 #include "allocator.h"
101
102 #ifndef SYSTEM_MALLOC
103
104 #ifdef GNU_MALLOC
105
106 /* If other `malloc' than ours is used, force our `sbrk' behave like
107 Unix programs expect (resize memory blocks to keep them contiguous).
108 If `sbrk' from `ralloc.c' is NOT used, also zero-out sbrk'ed memory,
109 because that's what `gmalloc' expects to get. */
110 #include <crt0.h>
111
112 #ifdef REL_ALLOC
113 int _crt0_startup_flags = _CRT0_FLAG_UNIX_SBRK;
114 #else /* not REL_ALLOC */
115 int _crt0_startup_flags = (_CRT0_FLAG_UNIX_SBRK | _CRT0_FLAG_FILL_SBRK_MEMORY);
116 #endif /* not REL_ALLOC */
117 #endif /* GNU_MALLOC */
118
119 #endif /* not SYSTEM_MALLOC */
120
121 /* Return the current timestamp in milliseconds since midnight. */
122 static unsigned long
123 event_timestamp (void)
124 {
125 struct timespec t;
126 unsigned long s;
127
128 gettime (&t);
129 s = t.tv_sec;
130 s %= 86400;
131 s *= 1000;
132 s += t.tv_nsec * 1000000;
133
134 return s;
135 }
136
137 \f
138 /* ------------------------ Mouse control ---------------------------
139 *
140 * Coordinates are in screen positions and zero based.
141 * Mouse buttons are numbered from left to right and also zero based.
142 */
143
144 /* This used to be in termhooks.h, but mainstream Emacs code no longer
145 uses it, and it was removed... */
146 #define NUM_MOUSE_BUTTONS (5)
147
148 int have_mouse; /* 0: no, 1: enabled, -1: disabled */
149 static int mouse_visible;
150
151 static int mouse_last_x;
152 static int mouse_last_y;
153
154 static int mouse_button_translate[NUM_MOUSE_BUTTONS];
155 static int mouse_button_count;
156
157 void
158 mouse_on (void)
159 {
160 union REGS regs;
161
162 if (have_mouse > 0 && !mouse_visible)
163 {
164 struct tty_display_info *tty = CURTTY ();
165
166 if (tty->termscript)
167 fprintf (tty->termscript, "<M_ON>");
168 regs.x.ax = 0x0001;
169 int86 (0x33, &regs, &regs);
170 mouse_visible = 1;
171 }
172 }
173
174 void
175 mouse_off (void)
176 {
177 union REGS regs;
178
179 if (have_mouse > 0 && mouse_visible)
180 {
181 struct tty_display_info *tty = CURTTY ();
182
183 if (tty->termscript)
184 fprintf (tty->termscript, "<M_OFF>");
185 regs.x.ax = 0x0002;
186 int86 (0x33, &regs, &regs);
187 mouse_visible = 0;
188 }
189 }
190
191 static void
192 mouse_setup_buttons (int n_buttons)
193 {
194 if (n_buttons == 3)
195 {
196 mouse_button_count = 3;
197 mouse_button_translate[0] = 0; /* Left */
198 mouse_button_translate[1] = 2; /* Middle */
199 mouse_button_translate[2] = 1; /* Right */
200 }
201 else /* two, what else? */
202 {
203 mouse_button_count = 2;
204 mouse_button_translate[0] = 0;
205 mouse_button_translate[1] = 1;
206 }
207 }
208
209 DEFUN ("msdos-set-mouse-buttons", Fmsdos_set_mouse_buttons, Smsdos_set_mouse_buttons,
210 1, 1, "NSet number of mouse buttons to: ",
211 doc: /* Set the number of mouse buttons to use by Emacs.
212 This is useful with mice that report the number of buttons inconsistently,
213 e.g., if the number of buttons is reported as 3, but Emacs only sees 2 of
214 them. This happens with wheeled mice on Windows 9X, for example. */)
215 (Lisp_Object nbuttons)
216 {
217 int n;
218
219 CHECK_NUMBER (nbuttons);
220 n = XINT (nbuttons);
221 if (n < 2 || n > 3)
222 xsignal2 (Qargs_out_of_range,
223 build_string ("only 2 or 3 mouse buttons are supported"),
224 nbuttons);
225 mouse_setup_buttons (n);
226 return Qnil;
227 }
228
229 static void
230 mouse_get_xy (int *x, int *y)
231 {
232 union REGS regs;
233
234 regs.x.ax = 0x0003;
235 int86 (0x33, &regs, &regs);
236 *x = regs.x.cx / 8;
237 *y = regs.x.dx / 8;
238 }
239
240 void
241 mouse_moveto (int x, int y)
242 {
243 union REGS regs;
244 struct tty_display_info *tty = CURTTY ();
245
246 if (tty->termscript)
247 fprintf (tty->termscript, "<M_XY=%dx%d>", x, y);
248 regs.x.ax = 0x0004;
249 mouse_last_x = regs.x.cx = x * 8;
250 mouse_last_y = regs.x.dx = y * 8;
251 int86 (0x33, &regs, &regs);
252 }
253
254 static int
255 mouse_pressed (int b, int *xp, int *yp)
256 {
257 union REGS regs;
258
259 if (b >= mouse_button_count)
260 return 0;
261 regs.x.ax = 0x0005;
262 regs.x.bx = mouse_button_translate[b];
263 int86 (0x33, &regs, &regs);
264 if (regs.x.bx)
265 *xp = regs.x.cx / 8, *yp = regs.x.dx / 8;
266 return (regs.x.bx != 0);
267 }
268
269 static int
270 mouse_released (int b, int *xp, int *yp)
271 {
272 union REGS regs;
273
274 if (b >= mouse_button_count)
275 return 0;
276 regs.x.ax = 0x0006;
277 regs.x.bx = mouse_button_translate[b];
278 int86 (0x33, &regs, &regs);
279 if (regs.x.bx)
280 *xp = regs.x.cx / 8, *yp = regs.x.dx / 8;
281 return (regs.x.bx != 0);
282 }
283
284 static int
285 mouse_button_depressed (int b, int *xp, int *yp)
286 {
287 union REGS regs;
288
289 if (b >= mouse_button_count)
290 return 0;
291 regs.x.ax = 0x0003;
292 int86 (0x33, &regs, &regs);
293 if ((regs.x.bx & (1 << mouse_button_translate[b])) != 0)
294 {
295 *xp = regs.x.cx / 8;
296 *yp = regs.x.dx / 8;
297 return 1;
298 }
299 return 0;
300 }
301
302 void
303 mouse_get_pos (struct frame **f, int insist, Lisp_Object *bar_window,
304 enum scroll_bar_part *part, Lisp_Object *x, Lisp_Object *y,
305 Time *time)
306 {
307 int ix, iy;
308 Lisp_Object frame, tail;
309
310 /* Clear the mouse-moved flag for every frame on this display. */
311 FOR_EACH_FRAME (tail, frame)
312 XFRAME (frame)->mouse_moved = 0;
313
314 *f = SELECTED_FRAME ();
315 *bar_window = Qnil;
316 mouse_get_xy (&ix, &iy);
317 *time = event_timestamp ();
318 *x = make_number (mouse_last_x = ix);
319 *y = make_number (mouse_last_y = iy);
320 }
321
322 static void
323 mouse_check_moved (void)
324 {
325 int x, y;
326
327 mouse_get_xy (&x, &y);
328 SELECTED_FRAME ()->mouse_moved |= (x != mouse_last_x || y != mouse_last_y);
329 mouse_last_x = x;
330 mouse_last_y = y;
331 }
332
333 /* Force the mouse driver to ``forget'' about any button clicks until
334 now. */
335 static void
336 mouse_clear_clicks (void)
337 {
338 int b;
339
340 for (b = 0; b < mouse_button_count; b++)
341 {
342 int dummy_x, dummy_y;
343
344 (void) mouse_pressed (b, &dummy_x, &dummy_y);
345 (void) mouse_released (b, &dummy_x, &dummy_y);
346 }
347 }
348
349 void
350 mouse_init (void)
351 {
352 union REGS regs;
353 struct tty_display_info *tty = CURTTY ();
354
355 if (tty->termscript)
356 fprintf (tty->termscript, "<M_INIT>");
357
358 regs.x.ax = 0x0021;
359 int86 (0x33, &regs, &regs);
360
361 /* Reset the mouse last press/release info. It seems that Windows
362 doesn't do that automatically when function 21h is called, which
363 causes Emacs to ``remember'' the click that switched focus to the
364 window just before Emacs was started from that window. */
365 mouse_clear_clicks ();
366
367 regs.x.ax = 0x0007;
368 regs.x.cx = 0;
369 regs.x.dx = 8 * (ScreenCols () - 1);
370 int86 (0x33, &regs, &regs);
371
372 regs.x.ax = 0x0008;
373 regs.x.cx = 0;
374 regs.x.dx = 8 * (ScreenRows () - 1);
375 int86 (0x33, &regs, &regs);
376
377 mouse_moveto (0, 0);
378 mouse_visible = 0;
379 }
380 \f
381 /* ------------------------- Screen control ----------------------
382 *
383 */
384
385 static int internal_terminal = 0;
386
387 #ifndef HAVE_X_WINDOWS
388 extern unsigned char ScreenAttrib;
389 static int screen_face;
390
391 static int screen_size_X;
392 static int screen_size_Y;
393 static int screen_size;
394
395 static int current_pos_X;
396 static int current_pos_Y;
397 static int new_pos_X;
398 static int new_pos_Y;
399
400 static void *startup_screen_buffer;
401 static int startup_screen_size_X;
402 static int startup_screen_size_Y;
403 static int startup_pos_X;
404 static int startup_pos_Y;
405 static unsigned char startup_screen_attrib;
406
407 static clock_t startup_time;
408
409 static int term_setup_done;
410
411 static unsigned short outside_cursor;
412
413 /* The only display since MS-DOS does not support multiple ones. */
414 struct tty_display_info the_only_display_info;
415
416 /* Support for DOS/V (allows Japanese characters to be displayed on
417 standard, non-Japanese, ATs). Only supported for DJGPP v2 and later. */
418
419 /* Holds the address of the text-mode screen buffer. */
420 static unsigned long screen_old_address = 0;
421 /* Segment and offset of the virtual screen. If 0, DOS/V is NOT loaded. */
422 static unsigned short screen_virtual_segment = 0;
423 static unsigned short screen_virtual_offset = 0;
424 extern Lisp_Object Qcursor_type;
425 extern Lisp_Object Qbar, Qhbar;
426
427 /* The screen colors of the current frame, which serve as the default
428 colors for newly-created frames. */
429 static int initial_screen_colors[2];
430
431 /* Update the screen from a part of relocated DOS/V screen buffer which
432 begins at OFFSET and includes COUNT characters. */
433 static void
434 dosv_refresh_virtual_screen (int offset, int count)
435 {
436 __dpmi_regs regs;
437
438 if (offset < 0 || count < 0) /* paranoia; invalid values crash DOS/V */
439 return;
440
441 regs.h.ah = 0xff; /* update relocated screen */
442 regs.x.es = screen_virtual_segment;
443 regs.x.di = screen_virtual_offset + offset;
444 regs.x.cx = count;
445 __dpmi_int (0x10, &regs);
446 }
447
448 static void
449 dos_direct_output (int y, int x, char *buf, int len)
450 {
451 int t0 = 2 * (x + y * screen_size_X);
452 int t = t0 + (int) ScreenPrimary;
453 int l0 = len;
454
455 /* This is faster. */
456 for (_farsetsel (_dos_ds); --len >= 0; t += 2, buf++)
457 _farnspokeb (t, *buf);
458
459 if (screen_virtual_segment)
460 dosv_refresh_virtual_screen (t0, l0);
461 }
462 #endif
463
464 #ifndef HAVE_X_WINDOWS
465
466 static int blink_bit = -1; /* the state of the blink bit at startup */
467
468 /* Enable bright background colors. */
469 static void
470 bright_bg (void)
471 {
472 union REGS regs;
473
474 /* Remember the original state of the blink/bright-background bit.
475 It is stored at 0040:0065h in the BIOS data area. */
476 if (blink_bit == -1)
477 blink_bit = (_farpeekb (_dos_ds, 0x465) & 0x20) == 0x20;
478
479 regs.h.bl = 0;
480 regs.x.ax = 0x1003;
481 int86 (0x10, &regs, &regs);
482 }
483
484 /* Disable bright background colors (and enable blinking) if we found
485 the video system in that state at startup. */
486 static void
487 maybe_enable_blinking (void)
488 {
489 if (blink_bit == 1)
490 {
491 union REGS regs;
492
493 regs.h.bl = 1;
494 regs.x.ax = 0x1003;
495 int86 (0x10, &regs, &regs);
496 }
497 }
498
499 /* Return non-zero if the system has a VGA adapter. */
500 static int
501 vga_installed (void)
502 {
503 union REGS regs;
504
505 regs.x.ax = 0x1a00;
506 int86 (0x10, &regs, &regs);
507 if (regs.h.al == 0x1a && regs.h.bl > 5 && regs.h.bl < 13)
508 return 1;
509 return 0;
510 }
511
512 /* Set the screen dimensions so that it can show no less than
513 ROWS x COLS frame. */
514
515 void
516 dos_set_window_size (int *rows, int *cols)
517 {
518 char video_name[30];
519 union REGS regs;
520 Lisp_Object video_mode;
521 int video_mode_value, have_vga = 0;
522 int current_rows = ScreenRows (), current_cols = ScreenCols ();
523
524 if (*rows == current_rows && *cols == current_cols)
525 return;
526
527 mouse_off ();
528 have_vga = vga_installed ();
529
530 /* If the user specified a special video mode for these dimensions,
531 use that mode. */
532 video_mode
533 = Fsymbol_value (Fintern_soft (make_formatted_string
534 (video_name, "screen-dimensions-%dx%d",
535 *rows, *cols), Qnil));
536
537 if (INTEGERP (video_mode)
538 && (video_mode_value = XINT (video_mode)) > 0)
539 {
540 regs.x.ax = video_mode_value;
541 int86 (0x10, &regs, &regs);
542
543 if (have_mouse)
544 {
545 /* Must hardware-reset the mouse, or else it won't update
546 its notion of screen dimensions for some non-standard
547 video modes. This is *painfully* slow... */
548 regs.x.ax = 0;
549 int86 (0x33, &regs, &regs);
550 }
551 }
552
553 /* Find one of the dimensions supported by standard EGA/VGA
554 which gives us at least the required dimensions. */
555 else
556 {
557 static struct {
558 int rows, need_vga;
559 } std_dimension[] = {
560 {25, 0},
561 {28, 1},
562 {35, 0},
563 {40, 1},
564 {43, 0},
565 {50, 1}
566 };
567 int i = 0;
568
569 while (i < ARRAYELTS (std_dimension))
570 {
571 if (std_dimension[i].need_vga <= have_vga
572 && std_dimension[i].rows >= *rows)
573 {
574 if (std_dimension[i].rows != current_rows
575 || *cols != current_cols)
576 _set_screen_lines (std_dimension[i].rows);
577 break;
578 }
579 i++;
580 }
581 }
582
583
584 if (have_mouse)
585 {
586 mouse_init ();
587 mouse_on ();
588 }
589
590 /* Tell the caller what dimensions have been REALLY set. */
591 *rows = ScreenRows ();
592 *cols = ScreenCols ();
593
594 /* Update Emacs' notion of screen dimensions. */
595 screen_size_X = *cols;
596 screen_size_Y = *rows;
597 screen_size = *cols * *rows;
598
599 /* If the dimensions changed, the mouse highlight info is invalid. */
600 if (current_rows != *rows || current_cols != *cols)
601 {
602 struct frame *f = SELECTED_FRAME ();
603 Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (f);
604 Lisp_Object window = hlinfo->mouse_face_window;
605
606 if (! NILP (window) && XFRAME (XWINDOW (window)->frame) == f)
607 reset_mouse_highlight (hlinfo);
608 }
609
610 /* Enable bright background colors. */
611 bright_bg ();
612
613 /* FIXME: I'm not sure the above will run at all on DOS/V. But let's
614 be defensive anyway. */
615 if (screen_virtual_segment)
616 dosv_refresh_virtual_screen (0, *cols * *rows);
617 }
618
619 /* If we write a character in the position where the mouse is,
620 the mouse cursor may need to be refreshed. */
621
622 static void
623 mouse_off_maybe (void)
624 {
625 int x, y;
626
627 if (!mouse_visible)
628 return;
629
630 mouse_get_xy (&x, &y);
631 if (y != new_pos_Y || x < new_pos_X)
632 return;
633
634 mouse_off ();
635 }
636
637 #define DEFAULT_CURSOR_START (-1)
638 #define DEFAULT_CURSOR_WIDTH (-1)
639 #define BOX_CURSOR_WIDTH (-32)
640
641 /* Set cursor to begin at scan line START_LINE in the character cell
642 and extend for WIDTH scan lines. Scan lines are counted from top
643 of the character cell, starting from zero. */
644 static void
645 msdos_set_cursor_shape (struct frame *f, int start_line, int width)
646 {
647 unsigned desired_cursor;
648 __dpmi_regs regs;
649 int max_line, top_line, bot_line;
650 struct tty_display_info *tty = FRAME_TTY (f);
651
652 /* Avoid the costly BIOS call if F isn't the currently selected
653 frame. Allow for NULL as unconditionally meaning the selected
654 frame. */
655 if (f && f != SELECTED_FRAME ())
656 return;
657
658 if (tty->termscript)
659 fprintf (tty->termscript, "\nCURSOR SHAPE=(%d,%d)", start_line, width);
660
661 /* The character cell size in scan lines is stored at 40:85 in the
662 BIOS data area. */
663 max_line = _farpeekw (_dos_ds, 0x485) - 1;
664 switch (max_line)
665 {
666 default: /* this relies on CGA cursor emulation being ON! */
667 case 7:
668 bot_line = 7;
669 break;
670 case 9:
671 bot_line = 9;
672 break;
673 case 13:
674 bot_line = 12;
675 break;
676 case 15:
677 bot_line = 14;
678 break;
679 }
680
681 if (width < 0)
682 {
683 if (width == BOX_CURSOR_WIDTH)
684 {
685 top_line = 0;
686 bot_line = max_line;
687 }
688 else if (start_line != DEFAULT_CURSOR_START)
689 {
690 top_line = start_line;
691 bot_line = top_line - width - 1;
692 }
693 else if (width != DEFAULT_CURSOR_WIDTH)
694 {
695 top_line = 0;
696 bot_line = -1 - width;
697 }
698 else
699 top_line = bot_line + 1;
700 }
701 else if (width == 0)
702 {
703 /* [31, 0] seems to DTRT for all screen sizes. */
704 top_line = 31;
705 bot_line = 0;
706 }
707 else /* WIDTH is positive */
708 {
709 if (start_line != DEFAULT_CURSOR_START)
710 bot_line = start_line;
711 top_line = bot_line - (width - 1);
712 }
713
714 /* If the current cursor shape is already what they want, we are
715 history here. */
716 desired_cursor = ((top_line & 0x1f) << 8) | (bot_line & 0x1f);
717 if (desired_cursor == _farpeekw (_dos_ds, 0x460))
718 return;
719
720 regs.h.ah = 1;
721 regs.x.cx = desired_cursor;
722 __dpmi_int (0x10, &regs);
723 }
724
725 static void
726 IT_set_cursor_type (struct frame *f, Lisp_Object cursor_type)
727 {
728 if (EQ (cursor_type, Qbar) || EQ (cursor_type, Qhbar))
729 {
730 /* Just BAR means the normal EGA/VGA cursor. */
731 msdos_set_cursor_shape (f, DEFAULT_CURSOR_START, DEFAULT_CURSOR_WIDTH);
732 }
733 else if (CONSP (cursor_type)
734 && (EQ (XCAR (cursor_type), Qbar)
735 || EQ (XCAR (cursor_type), Qhbar)))
736 {
737 Lisp_Object bar_parms = XCDR (cursor_type);
738 int width;
739
740 if (INTEGERP (bar_parms))
741 {
742 /* Feature: negative WIDTH means cursor at the top
743 of the character cell, zero means invisible cursor. */
744 width = XINT (bar_parms);
745 msdos_set_cursor_shape (f, width >= 0 ? DEFAULT_CURSOR_START : 0,
746 width);
747 }
748 else if (CONSP (bar_parms)
749 && INTEGERP (XCAR (bar_parms))
750 && INTEGERP (XCDR (bar_parms)))
751 {
752 int start_line = XINT (XCDR (bar_parms));
753
754 width = XINT (XCAR (bar_parms));
755 msdos_set_cursor_shape (f, start_line, width);
756 }
757 }
758 else
759 {
760 /* Treat anything unknown as "box cursor". This includes nil, so
761 that a frame which doesn't specify a cursor type gets a box,
762 which is the default in Emacs. */
763 msdos_set_cursor_shape (f, 0, BOX_CURSOR_WIDTH);
764 }
765 }
766
767 static void
768 IT_ring_bell (struct frame *f)
769 {
770 if (visible_bell)
771 {
772 mouse_off ();
773 ScreenVisualBell ();
774 }
775 else
776 {
777 union REGS inregs, outregs;
778 inregs.h.ah = 2;
779 inregs.h.dl = 7;
780 intdos (&inregs, &outregs);
781 }
782 }
783
784 /* Given a face id FACE, extract the face parameters to be used for
785 display until the face changes. The face parameters (actually, its
786 color) are used to construct the video attribute byte for each
787 glyph during the construction of the buffer that is then blitted to
788 the video RAM. */
789 static void
790 IT_set_face (int face)
791 {
792 struct frame *sf = SELECTED_FRAME ();
793 struct face *fp = FACE_FROM_ID (sf, face);
794 struct face *dfp = FACE_FROM_ID (sf, DEFAULT_FACE_ID);
795 unsigned long fg, bg, dflt_fg, dflt_bg;
796 struct tty_display_info *tty = FRAME_TTY (sf);
797
798 if (!fp)
799 {
800 fp = dfp;
801 /* The default face for the frame should always be realized and
802 cached. */
803 if (!fp)
804 emacs_abort ();
805 }
806 screen_face = face;
807 fg = fp->foreground;
808 bg = fp->background;
809 dflt_fg = dfp->foreground;
810 dflt_bg = dfp->background;
811
812 /* Don't use invalid colors. In particular, FACE_TTY_DEFAULT_* colors
813 mean use the colors of the default face. Note that we assume all
814 16 colors to be available for the background, since Emacs switches
815 on this mode (and loses the blinking attribute) at startup. */
816 if (fg == FACE_TTY_DEFAULT_COLOR || fg == FACE_TTY_DEFAULT_FG_COLOR)
817 fg = FRAME_FOREGROUND_PIXEL (sf);
818 else if (fg == FACE_TTY_DEFAULT_BG_COLOR)
819 fg = FRAME_BACKGROUND_PIXEL (sf);
820 if (bg == FACE_TTY_DEFAULT_COLOR || bg == FACE_TTY_DEFAULT_BG_COLOR)
821 bg = FRAME_BACKGROUND_PIXEL (sf);
822 else if (bg == FACE_TTY_DEFAULT_FG_COLOR)
823 bg = FRAME_FOREGROUND_PIXEL (sf);
824
825 /* Make sure highlighted lines really stand out, come what may. */
826 if (fp->tty_reverse_p && (fg == dflt_fg && bg == dflt_bg))
827 {
828 unsigned long tem = fg;
829
830 fg = bg;
831 bg = tem;
832 }
833 /* If the user requested inverse video, obey. */
834 if (inverse_video)
835 {
836 unsigned long tem2 = fg;
837
838 fg = bg;
839 bg = tem2;
840 }
841 if (tty->termscript)
842 fprintf (tty->termscript, "<FACE %d: %lu/%lu[FG:%lu/BG:%lu]>", face,
843 fp->foreground, fp->background, fg, bg);
844 if (fg >= 0 && fg < 16)
845 {
846 ScreenAttrib &= 0xf0;
847 ScreenAttrib |= fg;
848 }
849 if (bg >= 0 && bg < 16)
850 {
851 ScreenAttrib &= 0x0f;
852 ScreenAttrib |= ((bg & 0x0f) << 4);
853 }
854 }
855
856 /* According to RBIL (INTERRUP.A, V-1000), 160 is the maximum possible
857 width of a DOS display in any known text mode. We multiply by 2 to
858 accommodate the screen attribute byte. */
859 #define MAX_SCREEN_BUF 160*2
860
861 extern unsigned char *encode_terminal_code (struct glyph *, int,
862 struct coding_system *);
863
864 static void
865 IT_write_glyphs (struct frame *f, struct glyph *str, int str_len)
866 {
867 unsigned char screen_buf[MAX_SCREEN_BUF], *screen_bp, *bp;
868 int offset = 2 * (new_pos_X + screen_size_X * new_pos_Y);
869 register int sl = str_len;
870 struct tty_display_info *tty = FRAME_TTY (f);
871 struct frame *sf;
872 unsigned char *conversion_buffer;
873
874 /* If terminal_coding does any conversion, use it, otherwise use
875 safe_terminal_coding. We can't use CODING_REQUIRE_ENCODING here
876 because it always returns 1 if terminal_coding.src_multibyte is 1. */
877 struct coding_system *coding = FRAME_TERMINAL_CODING (f);
878
879 if (!(coding->common_flags & CODING_REQUIRE_ENCODING_MASK))
880 coding = &safe_terminal_coding;
881
882 if (str_len <= 0) return;
883
884 sf = SELECTED_FRAME ();
885
886 /* Since faces get cached and uncached behind our back, we can't
887 rely on their indices in the cache being consistent across
888 invocations. So always reset the screen face to the default
889 face of the frame, before writing glyphs, and let the glyphs
890 set the right face if it's different from the default. */
891 IT_set_face (DEFAULT_FACE_ID);
892
893 /* The mode bit CODING_MODE_LAST_BLOCK should be set to 1 only at
894 the tail. */
895 coding->mode &= ~CODING_MODE_LAST_BLOCK;
896 screen_bp = &screen_buf[0];
897 while (sl > 0)
898 {
899 int cf;
900 int n;
901
902 /* If the face of this glyph is different from the current
903 screen face, update the screen attribute byte. */
904 cf = str->face_id;
905 if (cf != screen_face)
906 IT_set_face (cf); /* handles invalid faces gracefully */
907
908 /* Identify a run of glyphs with the same face. */
909 for (n = 1; n < sl; ++n)
910 if (str[n].face_id != cf)
911 break;
912
913 if (n >= sl)
914 /* This is the last glyph. */
915 coding->mode |= CODING_MODE_LAST_BLOCK;
916
917 conversion_buffer = encode_terminal_code (str, n, coding);
918 if (coding->produced > 0)
919 {
920 /* Copy the encoded bytes to the screen buffer. */
921 for (bp = conversion_buffer; coding->produced--; bp++)
922 {
923 /* Paranoia: discard bytes that would overrun the end of
924 the screen buffer. */
925 if (screen_bp - screen_buf <= MAX_SCREEN_BUF - 2)
926 {
927 *screen_bp++ = (unsigned char)*bp;
928 *screen_bp++ = ScreenAttrib;
929 }
930 if (tty->termscript)
931 fputc (*bp, tty->termscript);
932 }
933 }
934 /* Update STR and its remaining length. */
935 str += n;
936 sl -= n;
937 }
938
939 /* Dump whatever we have in the screen buffer. */
940 mouse_off_maybe ();
941 dosmemput (screen_buf, screen_bp - screen_buf, (int)ScreenPrimary + offset);
942 if (screen_virtual_segment)
943 dosv_refresh_virtual_screen (offset, (screen_bp - screen_buf) / 2);
944 new_pos_X += (screen_bp - screen_buf) / 2;
945 }
946
947 /************************************************************************
948 Mouse Highlight (and friends..)
949 ************************************************************************/
950
951 static int mouse_preempted = 0; /* non-zero when XMenu gobbles mouse events */
952
953 int
954 popup_activated (void)
955 {
956 return mouse_preempted;
957 }
958
959 /* Draw TEXT_AREA glyphs between START and END of glyph row ROW on
960 window W. X is relative to TEXT_AREA in W. HL is a face override
961 for drawing the glyphs. */
962 void
963 tty_draw_row_with_mouse_face (struct window *w, struct glyph_row *row,
964 int start_hpos, int end_hpos,
965 enum draw_glyphs_face hl)
966 {
967 struct frame *f = XFRAME (WINDOW_FRAME (w));
968 struct tty_display_info *tty = FRAME_TTY (f);
969 Mouse_HLInfo *hlinfo = &tty->mouse_highlight;
970
971 if (hl == DRAW_MOUSE_FACE)
972 {
973 int vpos = row->y + WINDOW_TOP_EDGE_Y (w);
974 int kstart = start_hpos + WINDOW_LEFT_EDGE_X (w);
975 int nglyphs = end_hpos - start_hpos;
976 int offset = ScreenPrimary + 2*(vpos*screen_size_X + kstart) + 1;
977 int start_offset = offset;
978
979 if (tty->termscript)
980 fprintf (tty->termscript, "\n<MH+ %d-%d:%d>",
981 kstart, kstart + nglyphs - 1, vpos);
982
983 mouse_off ();
984 IT_set_face (hlinfo->mouse_face_face_id);
985 /* Since we are going to change only the _colors_ of already
986 displayed text, there's no need to go through all the pain of
987 generating and encoding the text from the glyphs. Instead,
988 we simply poke the attribute byte of each affected position
989 in video memory with the colors computed by IT_set_face! */
990 _farsetsel (_dos_ds);
991 while (nglyphs--)
992 {
993 _farnspokeb (offset, ScreenAttrib);
994 offset += 2;
995 }
996 if (screen_virtual_segment)
997 dosv_refresh_virtual_screen (start_offset, end_hpos - start_hpos);
998 mouse_on ();
999 }
1000 else if (hl == DRAW_NORMAL_TEXT)
1001 {
1002 /* We are removing a previously-drawn mouse highlight. The
1003 safest way to do so is to redraw the glyphs anew, since all
1004 kinds of faces and display tables could have changed behind
1005 our back. */
1006 int nglyphs = end_hpos - start_hpos;
1007 int save_x = new_pos_X, save_y = new_pos_Y;
1008
1009 if (end_hpos >= row->used[TEXT_AREA])
1010 nglyphs = row->used[TEXT_AREA] - start_hpos;
1011
1012 /* IT_write_glyphs writes at cursor position, so we need to
1013 temporarily move cursor coordinates to the beginning of
1014 the highlight region. */
1015 new_pos_X = start_hpos + WINDOW_LEFT_EDGE_X (w);
1016 new_pos_Y = row->y + WINDOW_TOP_EDGE_Y (w);
1017
1018 if (tty->termscript)
1019 fprintf (tty->termscript, "<MH- %d-%d:%d>",
1020 new_pos_X, new_pos_X + nglyphs - 1, new_pos_Y);
1021 IT_write_glyphs (f, row->glyphs[TEXT_AREA] + start_hpos, nglyphs);
1022 if (tty->termscript)
1023 fputs ("\n", tty->termscript);
1024 new_pos_X = save_x;
1025 new_pos_Y = save_y;
1026 }
1027 }
1028
1029 static void
1030 IT_clear_end_of_line (struct frame *f, int first_unused)
1031 {
1032 char *spaces, *sp;
1033 int i, j, offset = 2 * (new_pos_X + screen_size_X * new_pos_Y);
1034 struct tty_display_info *tty = FRAME_TTY (f);
1035
1036 if (new_pos_X >= first_unused || fatal_error_in_progress)
1037 return;
1038
1039 IT_set_face (0);
1040 i = (j = first_unused - new_pos_X) * 2;
1041 if (tty->termscript)
1042 fprintf (tty->termscript, "<CLR:EOL[%d..%d)>", new_pos_X, first_unused);
1043 spaces = sp = alloca (i);
1044
1045 while (--j >= 0)
1046 {
1047 *sp++ = ' ';
1048 *sp++ = ScreenAttrib;
1049 }
1050
1051 mouse_off_maybe ();
1052 dosmemput (spaces, i, (int)ScreenPrimary + offset);
1053 if (screen_virtual_segment)
1054 dosv_refresh_virtual_screen (offset, i / 2);
1055
1056 /* clear_end_of_line_raw on term.c leaves the cursor at first_unused.
1057 Let's follow their lead, in case someone relies on this. */
1058 new_pos_X = first_unused;
1059 }
1060
1061 static void
1062 IT_clear_screen (struct frame *f)
1063 {
1064 struct tty_display_info *tty = FRAME_TTY (f);
1065
1066 if (tty->termscript)
1067 fprintf (tty->termscript, "<CLR:SCR>");
1068 /* We are sometimes called (from clear_garbaged_frames) when a new
1069 frame is being created, but its faces are not yet realized. In
1070 such a case we cannot call IT_set_face, since it will fail to find
1071 any valid faces and will abort. Instead, use the initial screen
1072 colors; that should mimic what a Unix tty does, which simply clears
1073 the screen with whatever default colors are in use. */
1074 if (FACE_FROM_ID (SELECTED_FRAME (), DEFAULT_FACE_ID) == NULL)
1075 ScreenAttrib = (initial_screen_colors[0] << 4) | initial_screen_colors[1];
1076 else
1077 IT_set_face (0);
1078 mouse_off ();
1079 ScreenClear ();
1080 if (screen_virtual_segment)
1081 dosv_refresh_virtual_screen (0, screen_size);
1082 new_pos_X = new_pos_Y = 0;
1083 }
1084
1085 static void
1086 IT_clear_to_end (struct frame *f)
1087 {
1088 struct tty_display_info *tty = FRAME_TTY (f);
1089
1090 if (tty->termscript)
1091 fprintf (tty->termscript, "<CLR:EOS>");
1092
1093 while (new_pos_Y < screen_size_Y) {
1094 new_pos_X = 0;
1095 IT_clear_end_of_line (f, screen_size_X);
1096 new_pos_Y++;
1097 }
1098 }
1099
1100 static void
1101 IT_cursor_to (struct frame *f, int y, int x)
1102 {
1103 struct tty_display_info *tty = FRAME_TTY (f);
1104
1105 if (tty->termscript)
1106 fprintf (tty->termscript, "\n<XY=%dx%d>", x, y);
1107 new_pos_X = x;
1108 new_pos_Y = y;
1109 }
1110
1111 static int cursor_cleared;
1112
1113 static void
1114 IT_display_cursor (int on)
1115 {
1116 struct tty_display_info *tty = CURTTY ();
1117
1118 if (on && cursor_cleared)
1119 {
1120 ScreenSetCursor (current_pos_Y, current_pos_X);
1121 cursor_cleared = 0;
1122 if (tty->termscript)
1123 fprintf (tty->termscript, "\nCURSOR ON (%dx%d)",
1124 current_pos_Y, current_pos_X);
1125 }
1126 else if (!on && !cursor_cleared)
1127 {
1128 ScreenSetCursor (-1, -1);
1129 cursor_cleared = 1;
1130 if (tty->termscript)
1131 fprintf (tty->termscript, "\nCURSOR OFF (%dx%d)",
1132 current_pos_Y, current_pos_X);
1133 }
1134 }
1135
1136 /* Emacs calls cursor-movement functions a lot when it updates the
1137 display (probably a legacy of old terminals where you cannot
1138 update a screen line without first moving the cursor there).
1139 However, cursor movement is expensive on MSDOS (it calls a slow
1140 BIOS function and requires 2 mode switches), while actual screen
1141 updates access the video memory directly and don't depend on
1142 cursor position. To avoid slowing down the redisplay, we cheat:
1143 all functions that move the cursor only set internal variables
1144 which record the cursor position, whereas the cursor is only
1145 moved to its final position whenever screen update is complete.
1146
1147 `IT_cmgoto' is called from the keyboard reading loop and when the
1148 frame update is complete. This means that we are ready for user
1149 input, so we update the cursor position to show where the point is,
1150 and also make the mouse pointer visible.
1151
1152 Special treatment is required when the cursor is in the echo area,
1153 to put the cursor at the end of the text displayed there. */
1154
1155 static void
1156 IT_cmgoto (struct frame *f)
1157 {
1158 /* Only set the cursor to where it should be if the display is
1159 already in sync with the window contents. */
1160 int update_cursor_pos = 1; /* MODIFF == unchanged_modified; */
1161 struct tty_display_info *tty = FRAME_TTY (f);
1162
1163 /* FIXME: This needs to be rewritten for the new redisplay, or
1164 removed. */
1165 #if 0
1166 static int previous_pos_X = -1;
1167
1168 update_cursor_pos = 1; /* temporary!!! */
1169
1170 /* If the display is in sync, forget any previous knowledge about
1171 cursor position. This is primarily for unexpected events like
1172 C-g in the minibuffer. */
1173 if (update_cursor_pos && previous_pos_X >= 0)
1174 previous_pos_X = -1;
1175 /* If we are in the echo area, put the cursor at the
1176 end of the echo area message. */
1177 if (!update_cursor_pos
1178 && WINDOW_TOP_EDGE_LINE (XWINDOW (FRAME_MINIBUF_WINDOW (f))) <= new_pos_Y)
1179 {
1180 int tem_X = current_pos_X, dummy;
1181
1182 if (echo_area_glyphs)
1183 {
1184 tem_X = echo_area_glyphs_length;
1185 /* Save current cursor position, to be restored after the
1186 echo area message is erased. Only remember one level
1187 of previous cursor position. */
1188 if (previous_pos_X == -1)
1189 ScreenGetCursor (&dummy, &previous_pos_X);
1190 }
1191 else if (previous_pos_X >= 0)
1192 {
1193 /* We wind up here after the echo area message is erased.
1194 Restore the cursor position we remembered above. */
1195 tem_X = previous_pos_X;
1196 previous_pos_X = -1;
1197 }
1198
1199 if (current_pos_X != tem_X)
1200 {
1201 new_pos_X = tem_X;
1202 update_cursor_pos = 1;
1203 }
1204 }
1205 #endif
1206
1207 if (update_cursor_pos
1208 && (current_pos_X != new_pos_X || current_pos_Y != new_pos_Y))
1209 {
1210 ScreenSetCursor (current_pos_Y = new_pos_Y, current_pos_X = new_pos_X);
1211 if (tty->termscript)
1212 fprintf (tty->termscript, "\n<CURSOR:%dx%d>", current_pos_X, current_pos_Y);
1213 }
1214
1215 /* Maybe cursor is invisible, so make it visible. */
1216 IT_display_cursor (1);
1217
1218 /* Mouse pointer should be always visible if we are waiting for
1219 keyboard input. */
1220 if (!mouse_visible)
1221 mouse_on ();
1222 }
1223
1224 static void
1225 IT_update_begin (struct frame *f)
1226 {
1227 struct tty_display_info *display_info = FRAME_DISPLAY_INFO (f);
1228 Mouse_HLInfo *hlinfo = &display_info->mouse_highlight;
1229 struct frame *mouse_face_frame = hlinfo->mouse_face_mouse_frame;
1230
1231 if (display_info->termscript)
1232 fprintf (display_info->termscript, "\n\n<UPDATE_BEGIN");
1233
1234 block_input ();
1235
1236 if (f && f == mouse_face_frame)
1237 {
1238 /* Don't do highlighting for mouse motion during the update. */
1239 hlinfo->mouse_face_defer = 1;
1240
1241 /* If F needs to be redrawn, simply forget about any prior mouse
1242 highlighting. */
1243 if (FRAME_GARBAGED_P (f))
1244 hlinfo->mouse_face_window = Qnil;
1245
1246 /* Can we tell that this update does not affect the window
1247 where the mouse highlight is? If so, no need to turn off.
1248 Likewise, don't do anything if none of the enabled rows
1249 contains glyphs highlighted in mouse face. */
1250 if (!NILP (hlinfo->mouse_face_window)
1251 && WINDOWP (hlinfo->mouse_face_window))
1252 {
1253 struct window *w = XWINDOW (hlinfo->mouse_face_window);
1254 int i;
1255
1256 /* If the mouse highlight is in the window that was deleted
1257 (e.g., if it was popped by completion), clear highlight
1258 unconditionally. */
1259 if (NILP (w->contents))
1260 hlinfo->mouse_face_window = Qnil;
1261 else
1262 {
1263 for (i = 0; i < w->desired_matrix->nrows; ++i)
1264 if (MATRIX_ROW_ENABLED_P (w->desired_matrix, i)
1265 && MATRIX_ROW (w->current_matrix, i)->mouse_face_p)
1266 break;
1267 }
1268
1269 if (NILP (w->contents) || i < w->desired_matrix->nrows)
1270 clear_mouse_face (hlinfo);
1271 }
1272 }
1273 else if (mouse_face_frame && !FRAME_LIVE_P (mouse_face_frame))
1274 /* If the frame with mouse highlight was deleted, invalidate the
1275 highlight info. */
1276 reset_mouse_highlight (hlinfo);
1277
1278 unblock_input ();
1279 }
1280
1281 static void
1282 IT_update_end (struct frame *f)
1283 {
1284 struct tty_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
1285
1286 if (dpyinfo->termscript)
1287 fprintf (dpyinfo->termscript, "\n<UPDATE_END\n");
1288 dpyinfo->mouse_highlight.mouse_face_defer = 0;
1289 }
1290
1291 static void
1292 IT_frame_up_to_date (struct frame *f)
1293 {
1294 Lisp_Object new_cursor, frame_desired_cursor;
1295 struct window *sw;
1296
1297 FRAME_MOUSE_UPDATE (f);
1298
1299 /* Set the cursor type to whatever they wanted. In a minibuffer
1300 window, we want the cursor to appear only if we are reading input
1301 from this window, and we want the cursor to be taken from the
1302 frame parameters. For the selected window, we use either its
1303 buffer-local value or the value from the frame parameters if the
1304 buffer doesn't define its local value for the cursor type. */
1305 sw = XWINDOW (f->selected_window);
1306 frame_desired_cursor = Fcdr (Fassq (Qcursor_type, f->param_alist));
1307 if (cursor_in_echo_area
1308 && FRAME_HAS_MINIBUF_P (f)
1309 && EQ (FRAME_MINIBUF_WINDOW (f), echo_area_window)
1310 && sw == XWINDOW (echo_area_window))
1311 new_cursor = frame_desired_cursor;
1312 else
1313 {
1314 struct buffer *b = XBUFFER (sw->contents);
1315
1316 if (EQ (BVAR (b,cursor_type), Qt))
1317 new_cursor = frame_desired_cursor;
1318 else if (NILP (BVAR (b, cursor_type))) /* nil means no cursor */
1319 new_cursor = Fcons (Qbar, make_number (0));
1320 else
1321 new_cursor = BVAR (b, cursor_type);
1322 }
1323
1324 IT_set_cursor_type (f, new_cursor);
1325
1326 IT_cmgoto (f); /* position cursor when update is done */
1327 }
1328
1329 /* Copy LEN glyphs displayed on a single line whose vertical position
1330 is YPOS, beginning at horizontal position XFROM to horizontal
1331 position XTO, by moving blocks in the video memory. Used by
1332 functions that insert and delete glyphs. */
1333 static void
1334 IT_copy_glyphs (int xfrom, int xto, size_t len, int ypos)
1335 {
1336 /* The offsets of source and destination relative to the
1337 conventional memory selector. */
1338 int from = 2 * (xfrom + screen_size_X * ypos) + ScreenPrimary;
1339 int to = 2 * (xto + screen_size_X * ypos) + ScreenPrimary;
1340
1341 if (from == to || len <= 0)
1342 return;
1343
1344 _farsetsel (_dos_ds);
1345
1346 /* The source and destination might overlap, so we need to move
1347 glyphs non-destructively. */
1348 if (from > to)
1349 {
1350 for ( ; len; from += 2, to += 2, len--)
1351 _farnspokew (to, _farnspeekw (from));
1352 }
1353 else
1354 {
1355 from += (len - 1) * 2;
1356 to += (len - 1) * 2;
1357 for ( ; len; from -= 2, to -= 2, len--)
1358 _farnspokew (to, _farnspeekw (from));
1359 }
1360 if (screen_virtual_segment)
1361 dosv_refresh_virtual_screen (ypos * screen_size_X * 2, screen_size_X);
1362 }
1363
1364 /* Insert and delete glyphs. */
1365 static void
1366 IT_insert_glyphs (struct frame *f, struct glyph *start, int len)
1367 {
1368 int shift_by_width = screen_size_X - (new_pos_X + len);
1369
1370 /* Shift right the glyphs from the nominal cursor position to the
1371 end of this line. */
1372 IT_copy_glyphs (new_pos_X, new_pos_X + len, shift_by_width, new_pos_Y);
1373
1374 /* Now write the glyphs to be inserted. */
1375 IT_write_glyphs (f, start, len);
1376 }
1377
1378 static void
1379 IT_delete_glyphs (struct frame *f, int n)
1380 {
1381 emacs_abort ();
1382 }
1383
1384 /* This was copied from xfaces.c */
1385
1386 extern Lisp_Object Qbackground_color;
1387 extern Lisp_Object Qforeground_color;
1388 Lisp_Object Qreverse;
1389 extern Lisp_Object Qtitle;
1390
1391 /* IT_set_terminal_modes is called when emacs is started,
1392 resumed, and whenever the screen is redrawn! */
1393
1394 static void
1395 IT_set_terminal_modes (struct terminal *term)
1396 {
1397 struct tty_display_info *tty;
1398
1399 /* If called with initial terminal, it's too early to do anything
1400 useful. */
1401 if (term->type == output_initial)
1402 return;
1403
1404 tty = term->display_info.tty;
1405
1406 if (tty->termscript)
1407 fprintf (tty->termscript, "\n<SET_TERM>");
1408
1409 screen_size_X = ScreenCols ();
1410 screen_size_Y = ScreenRows ();
1411 screen_size = screen_size_X * screen_size_Y;
1412
1413 new_pos_X = new_pos_Y = 0;
1414 current_pos_X = current_pos_Y = -1;
1415
1416 if (term_setup_done)
1417 return;
1418 term_setup_done = 1;
1419
1420 startup_screen_size_X = screen_size_X;
1421 startup_screen_size_Y = screen_size_Y;
1422 startup_screen_attrib = ScreenAttrib;
1423
1424 /* Is DOS/V (or any other RSIS software which relocates
1425 the screen) installed? */
1426 {
1427 unsigned short es_value;
1428 __dpmi_regs regs;
1429
1430 regs.h.ah = 0xfe; /* get relocated screen address */
1431 if (ScreenPrimary == 0xb0000UL || ScreenPrimary == 0xb8000UL)
1432 regs.x.es = (ScreenPrimary >> 4) & 0xffff;
1433 else if (screen_old_address) /* already switched to Japanese mode once */
1434 regs.x.es = (screen_old_address >> 4) & 0xffff;
1435 else
1436 regs.x.es = ScreenMode () == 7 ? 0xb000 : 0xb800;
1437 regs.x.di = 0;
1438 es_value = regs.x.es;
1439 __dpmi_int (0x10, &regs);
1440
1441 if (regs.x.es != es_value)
1442 {
1443 /* screen_old_address is only set if ScreenPrimary does NOT
1444 already point to the relocated buffer address returned by
1445 the Int 10h/AX=FEh call above. DJGPP v2.02 and later sets
1446 ScreenPrimary to that address at startup under DOS/V. */
1447 if (regs.x.es != ((ScreenPrimary >> 4) & 0xffff))
1448 screen_old_address = ScreenPrimary;
1449 screen_virtual_segment = regs.x.es;
1450 screen_virtual_offset = regs.x.di;
1451 ScreenPrimary = (screen_virtual_segment << 4) + screen_virtual_offset;
1452 }
1453 }
1454
1455 ScreenGetCursor (&startup_pos_Y, &startup_pos_X);
1456 ScreenRetrieve (startup_screen_buffer = xmalloc (screen_size * 2));
1457
1458 bright_bg ();
1459 }
1460
1461 /* IT_reset_terminal_modes is called when emacs is
1462 suspended or killed. */
1463
1464 static void
1465 IT_reset_terminal_modes (struct terminal *term)
1466 {
1467 int display_row_start = (int) ScreenPrimary;
1468 int saved_row_len = startup_screen_size_X * 2;
1469 int update_row_len = ScreenCols () * 2, current_rows = ScreenRows ();
1470 int to_next_row = update_row_len;
1471 unsigned char *saved_row = startup_screen_buffer;
1472 int cursor_pos_X = ScreenCols () - 1, cursor_pos_Y = ScreenRows () - 1;
1473 struct tty_display_info *tty = term->display_info.tty;
1474
1475 if (tty->termscript)
1476 fprintf (tty->termscript, "\n<RESET_TERM>");
1477
1478 if (!term_setup_done)
1479 return;
1480
1481 mouse_off ();
1482
1483 /* Leave the video system in the same state as we found it,
1484 as far as the blink/bright-background bit is concerned. */
1485 maybe_enable_blinking ();
1486
1487 /* We have a situation here.
1488 We cannot just do ScreenUpdate(startup_screen_buffer) because
1489 the luser could have changed screen dimensions inside Emacs
1490 and failed (or didn't want) to restore them before killing
1491 Emacs. ScreenUpdate() uses the *current* screen dimensions and
1492 thus will happily use memory outside what was allocated for
1493 `startup_screen_buffer'.
1494 Thus we only restore as much as the current screen dimensions
1495 can hold, and clear the rest (if the saved screen is smaller than
1496 the current) with the color attribute saved at startup. The cursor
1497 is also restored within the visible dimensions. */
1498
1499 ScreenAttrib = startup_screen_attrib;
1500
1501 /* Don't restore the screen if we are exiting less than 2 seconds
1502 after startup: we might be crashing, and the screen might show
1503 some vital clues to what's wrong. */
1504 if (clock () - startup_time >= 2*CLOCKS_PER_SEC)
1505 {
1506 ScreenClear ();
1507 if (screen_virtual_segment)
1508 dosv_refresh_virtual_screen (0, screen_size);
1509
1510 if (update_row_len > saved_row_len)
1511 update_row_len = saved_row_len;
1512 if (current_rows > startup_screen_size_Y)
1513 current_rows = startup_screen_size_Y;
1514
1515 if (tty->termscript)
1516 fprintf (tty->termscript, "<SCREEN RESTORED (dimensions=%dx%d)>\n",
1517 update_row_len / 2, current_rows);
1518
1519 while (current_rows--)
1520 {
1521 dosmemput (saved_row, update_row_len, display_row_start);
1522 if (screen_virtual_segment)
1523 dosv_refresh_virtual_screen (display_row_start - ScreenPrimary,
1524 update_row_len / 2);
1525 saved_row += saved_row_len;
1526 display_row_start += to_next_row;
1527 }
1528 }
1529 if (startup_pos_X < cursor_pos_X)
1530 cursor_pos_X = startup_pos_X;
1531 if (startup_pos_Y < cursor_pos_Y)
1532 cursor_pos_Y = startup_pos_Y;
1533
1534 ScreenSetCursor (cursor_pos_Y, cursor_pos_X);
1535 xfree (startup_screen_buffer);
1536 startup_screen_buffer = NULL;
1537
1538 term_setup_done = 0;
1539 }
1540
1541 /* Remember the screen colors of the current frame, to serve as the
1542 default colors for newly-created frames. */
1543 DEFUN ("msdos-remember-default-colors", Fmsdos_remember_default_colors,
1544 Smsdos_remember_default_colors, 1, 1, 0,
1545 doc: /* Remember the screen colors of the current frame. */)
1546 (Lisp_Object frame)
1547 {
1548 struct frame *f;
1549
1550 CHECK_FRAME (frame);
1551 f = XFRAME (frame);
1552
1553 /* This function is called after applying default-frame-alist to the
1554 initial frame. At that time, if reverse-colors option was
1555 specified in default-frame-alist, it was already applied, and
1556 frame colors are reversed. */
1557 initial_screen_colors[0] = FRAME_FOREGROUND_PIXEL (f);
1558 initial_screen_colors[1] = FRAME_BACKGROUND_PIXEL (f);
1559
1560 return Qnil;
1561 }
1562
1563 void
1564 IT_set_frame_parameters (struct frame *f, Lisp_Object alist)
1565 {
1566 Lisp_Object tail;
1567 int i, j, length = XINT (Flength (alist));
1568 Lisp_Object *parms
1569 = (Lisp_Object *) alloca (length * word_size);
1570 Lisp_Object *values
1571 = (Lisp_Object *) alloca (length * word_size);
1572 /* Do we have to reverse the foreground and background colors? */
1573 int reverse = EQ (Fcdr (Fassq (Qreverse, f->param_alist)), Qt);
1574 int redraw = 0, fg_set = 0, bg_set = 0;
1575 unsigned long orig_fg, orig_bg;
1576 struct tty_display_info *tty = FRAME_TTY (f);
1577
1578 /* If we are creating a new frame, begin with the original screen colors
1579 used for the initial frame. */
1580 if (!f->default_face_done_p
1581 && initial_screen_colors[0] != -1 && initial_screen_colors[1] != -1)
1582 {
1583 FRAME_FOREGROUND_PIXEL (f) = initial_screen_colors[0];
1584 FRAME_BACKGROUND_PIXEL (f) = initial_screen_colors[1];
1585 init_frame_faces (f);
1586 f->default_face_done_p = 1;
1587 }
1588 orig_fg = reverse ? FRAME_BACKGROUND_PIXEL (f) : FRAME_FOREGROUND_PIXEL (f);
1589 orig_bg = reverse ? FRAME_FOREGROUND_PIXEL (f) : FRAME_BACKGROUND_PIXEL (f);
1590
1591 /* Extract parm names and values into those vectors. */
1592 i = 0;
1593 for (tail = alist; CONSP (tail); tail = XCDR (tail))
1594 {
1595 Lisp_Object elt = XCAR (tail);
1596 parms[i] = Fcar (elt);
1597 CHECK_SYMBOL (parms[i]);
1598 values[i] = Fcdr (elt);
1599 i++;
1600 }
1601
1602 j = i;
1603
1604 for (i = 0; i < j; i++)
1605 {
1606 Lisp_Object prop, val;
1607
1608 prop = parms[i];
1609 val = values[i];
1610
1611 if (EQ (prop, Qreverse))
1612 reverse = EQ (val, Qt);
1613 }
1614
1615 if (tty->termscript && reverse)
1616 fprintf (tty->termscript, "<INVERSE-VIDEO>\n");
1617
1618 /* Now process the alist elements in reverse of specified order. */
1619 for (i--; i >= 0; i--)
1620 {
1621 Lisp_Object prop, val;
1622
1623 prop = parms[i];
1624 val = values[i];
1625
1626 if (EQ (prop, Qforeground_color))
1627 {
1628 unsigned long new_color = load_color (f, NULL, val, reverse
1629 ? LFACE_BACKGROUND_INDEX
1630 : LFACE_FOREGROUND_INDEX);
1631 if (new_color != FACE_TTY_DEFAULT_COLOR
1632 && new_color != FACE_TTY_DEFAULT_FG_COLOR
1633 && new_color != FACE_TTY_DEFAULT_BG_COLOR)
1634 {
1635 if (!reverse)
1636 {
1637 FRAME_FOREGROUND_PIXEL (f) = new_color;
1638 /* Make sure the foreground of the default face for
1639 this frame is changed as well. */
1640 update_face_from_frame_parameter (f, Qforeground_color, val);
1641 fg_set = 1;
1642 if (tty->termscript)
1643 fprintf (tty->termscript, "<FGCOLOR %lu>\n", new_color);
1644 }
1645 else
1646 {
1647 FRAME_BACKGROUND_PIXEL (f) = new_color;
1648 update_face_from_frame_parameter (f, Qbackground_color, val);
1649 bg_set = 1;
1650 if (tty->termscript)
1651 fprintf (tty->termscript, "<BGCOLOR %lu>\n", new_color);
1652 }
1653 redraw = 1;
1654 }
1655 }
1656 else if (EQ (prop, Qbackground_color))
1657 {
1658 unsigned long new_color = load_color (f, NULL, val, reverse
1659 ? LFACE_FOREGROUND_INDEX
1660 : LFACE_BACKGROUND_INDEX);
1661 if (new_color != FACE_TTY_DEFAULT_COLOR
1662 && new_color != FACE_TTY_DEFAULT_FG_COLOR
1663 && new_color != FACE_TTY_DEFAULT_BG_COLOR)
1664 {
1665 if (!reverse)
1666 {
1667 FRAME_BACKGROUND_PIXEL (f) = new_color;
1668 /* Make sure the background of the default face for
1669 this frame is changed as well. */
1670 bg_set = 1;
1671 update_face_from_frame_parameter (f, Qbackground_color, val);
1672 if (tty->termscript)
1673 fprintf (tty->termscript, "<BGCOLOR %lu>\n", new_color);
1674 }
1675 else
1676 {
1677 FRAME_FOREGROUND_PIXEL (f) = new_color;
1678 fg_set = 1;
1679 update_face_from_frame_parameter (f, Qforeground_color, val);
1680 if (tty->termscript)
1681 fprintf (tty->termscript, "<FGCOLOR %lu>\n", new_color);
1682 }
1683 redraw = 1;
1684 }
1685 }
1686 else if (EQ (prop, Qtitle))
1687 {
1688 x_set_title (f, val);
1689 if (tty->termscript)
1690 fprintf (tty->termscript, "<TITLE: %s>\n", SDATA (val));
1691 }
1692 else if (EQ (prop, Qcursor_type))
1693 {
1694 IT_set_cursor_type (f, val);
1695 if (tty->termscript)
1696 fprintf (tty->termscript, "<CTYPE: %s>\n",
1697 EQ (val, Qbar)
1698 || EQ (val, Qhbar)
1699 || (CONSP (val) && (EQ (XCAR (val), Qbar)
1700 || EQ (XCAR (val), Qhbar)))
1701 ? "bar" : "box");
1702 }
1703 else if (EQ (prop, Qtty_type))
1704 {
1705 internal_terminal_init ();
1706 if (tty->termscript)
1707 fprintf (tty->termscript, "<TERM_INIT done, TTY_TYPE: %.*s>\n",
1708 SBYTES (val), SDATA (val));
1709 }
1710 store_frame_param (f, prop, val);
1711 }
1712
1713 /* If they specified "reverse", but not the colors, we need to swap
1714 the current frame colors. */
1715 if (reverse)
1716 {
1717 if (!fg_set)
1718 {
1719 FRAME_FOREGROUND_PIXEL (f) = orig_bg;
1720 update_face_from_frame_parameter (f, Qforeground_color,
1721 tty_color_name (f, orig_bg));
1722 redraw = 1;
1723 }
1724 if (!bg_set)
1725 {
1726 FRAME_BACKGROUND_PIXEL (f) = orig_fg;
1727 update_face_from_frame_parameter (f, Qbackground_color,
1728 tty_color_name (f, orig_fg));
1729 redraw = 1;
1730 }
1731 }
1732
1733 if (redraw)
1734 {
1735 face_change_count++; /* forces xdisp.c to recompute basic faces */
1736 if (f == SELECTED_FRAME ())
1737 redraw_frame (f);
1738 }
1739 }
1740
1741 extern void init_frame_faces (struct frame *);
1742
1743 #endif /* !HAVE_X_WINDOWS */
1744
1745
1746 /* Do we need the internal terminal? */
1747
1748 void
1749 internal_terminal_init (void)
1750 {
1751 static int init_needed = 1;
1752 char *term = getenv ("TERM"), *colors;
1753 struct frame *sf = SELECTED_FRAME ();
1754 struct tty_display_info *tty;
1755
1756 #ifdef HAVE_X_WINDOWS
1757 if (!inhibit_window_system)
1758 return;
1759 #endif
1760
1761 /* If this is the initial terminal, we are done here. */
1762 if (sf->output_method == output_initial)
1763 return;
1764
1765 internal_terminal
1766 = (!noninteractive) && term && !strcmp (term, "internal");
1767
1768 #ifndef HAVE_X_WINDOWS
1769 if (!internal_terminal || inhibit_window_system)
1770 {
1771 sf->output_method = output_termcap;
1772 return;
1773 }
1774
1775 tty = FRAME_TTY (sf);
1776 kset_window_system (current_kboard, Qpc);
1777 sf->output_method = output_msdos_raw;
1778 if (init_needed)
1779 {
1780 if (!tty->termscript && getenv ("EMACSTEST"))
1781 tty->termscript = fopen (getenv ("EMACSTEST"), "wt");
1782 if (tty->termscript)
1783 {
1784 time_t now = time (NULL);
1785 struct tm *tnow = localtime (&now);
1786 char tbuf[100];
1787
1788 strftime (tbuf, sizeof (tbuf) - 1, "%a %b %e %Y %H:%M:%S %Z", tnow);
1789 fprintf (tty->termscript, "\nEmacs session started at %s\n", tbuf);
1790 fprintf (tty->termscript, "=====================\n\n");
1791 }
1792
1793 Vinitial_window_system = Qpc;
1794 Vwindow_system_version = make_number (24); /* RE Emacs version */
1795 tty->terminal->type = output_msdos_raw;
1796
1797 /* If Emacs was dumped on DOS/V machine, forget the stale VRAM
1798 address. */
1799 screen_old_address = 0;
1800
1801 /* Forget the stale screen colors as well. */
1802 initial_screen_colors[0] = initial_screen_colors[1] = -1;
1803
1804 FRAME_BACKGROUND_PIXEL (SELECTED_FRAME ()) = 7; /* White */
1805 FRAME_FOREGROUND_PIXEL (SELECTED_FRAME ()) = 0; /* Black */
1806 bright_bg ();
1807 colors = getenv ("EMACSCOLORS");
1808 if (colors && strlen (colors) >= 2)
1809 {
1810 /* The colors use 4 bits each (we enable bright background). */
1811 if (isdigit (colors[0]))
1812 colors[0] -= '0';
1813 else if (isxdigit (colors[0]))
1814 colors[0] -= (isupper (colors[0]) ? 'A' : 'a') - 10;
1815 if (colors[0] >= 0 && colors[0] < 16)
1816 FRAME_FOREGROUND_PIXEL (SELECTED_FRAME ()) = colors[0];
1817 if (isdigit (colors[1]))
1818 colors[1] -= '0';
1819 else if (isxdigit (colors[1]))
1820 colors[1] -= (isupper (colors[1]) ? 'A' : 'a') - 10;
1821 if (colors[1] >= 0 && colors[1] < 16)
1822 FRAME_BACKGROUND_PIXEL (SELECTED_FRAME ()) = colors[1];
1823 }
1824
1825 reset_mouse_highlight (&the_only_display_info.mouse_highlight);
1826
1827 if (have_mouse) /* detected in dos_ttraw, which see */
1828 {
1829 have_mouse = 1; /* enable mouse */
1830 mouse_visible = 0;
1831 mouse_setup_buttons (mouse_button_count);
1832 tty->terminal->mouse_position_hook = &mouse_get_pos;
1833 mouse_init ();
1834 }
1835
1836 if (tty->termscript && screen_size)
1837 fprintf (tty->termscript, "<SCREEN SAVED (dimensions=%dx%d)>\n",
1838 screen_size_X, screen_size_Y);
1839
1840 init_frame_faces (sf);
1841 init_needed = 0;
1842 }
1843 #endif
1844 }
1845
1846 void
1847 initialize_msdos_display (struct terminal *term)
1848 {
1849 term->rif = 0; /* we don't support window-based display */
1850 term->cursor_to_hook = term->raw_cursor_to_hook = IT_cursor_to;
1851 term->clear_to_end_hook = IT_clear_to_end;
1852 term->clear_frame_hook = IT_clear_screen;
1853 term->clear_end_of_line_hook = IT_clear_end_of_line;
1854 term->ins_del_lines_hook = 0;
1855 term->insert_glyphs_hook = IT_insert_glyphs;
1856 term->write_glyphs_hook = IT_write_glyphs;
1857 term->delete_glyphs_hook = IT_delete_glyphs;
1858 term->ring_bell_hook = IT_ring_bell;
1859 term->reset_terminal_modes_hook = IT_reset_terminal_modes;
1860 term->set_terminal_modes_hook = IT_set_terminal_modes;
1861 term->set_terminal_window_hook = NULL;
1862 term->update_begin_hook = IT_update_begin;
1863 term->update_end_hook = IT_update_end;
1864 term->frame_up_to_date_hook = IT_frame_up_to_date;
1865 term->mouse_position_hook = 0; /* set later by dos_ttraw */
1866 term->menu_show_hook = x_menu_show;
1867 term->frame_rehighlight_hook = 0;
1868 term->frame_raise_lower_hook = 0;
1869 term->set_vertical_scroll_bar_hook = 0;
1870 term->condemn_scroll_bars_hook = 0;
1871 term->redeem_scroll_bar_hook = 0;
1872 term->judge_scroll_bars_hook = 0;
1873 term->read_socket_hook = &tty_read_avail_input; /* from keyboard.c */
1874 }
1875
1876 int
1877 dos_get_saved_screen (char **screen, int *rows, int *cols)
1878 {
1879 #ifndef HAVE_X_WINDOWS
1880 *screen = startup_screen_buffer;
1881 *cols = startup_screen_size_X;
1882 *rows = startup_screen_size_Y;
1883 return *screen != (char *)0;
1884 #else
1885 return 0;
1886 #endif
1887 }
1888
1889 \f
1890 /* ----------------------- Keyboard control ----------------------
1891 *
1892 * Keymaps reflect the following keyboard layout:
1893 *
1894 * 0 1 2 3 4 5 6 7 8 9 10 11 12 BS
1895 * TAB 15 16 17 18 19 20 21 22 23 24 25 26 (41)
1896 * CLOK 30 31 32 33 34 35 36 37 38 39 40 (41) RET
1897 * SH () 45 46 47 48 49 50 51 52 53 54 SHIFT
1898 * SPACE
1899 */
1900
1901 #define Ignore 0x0000
1902 #define Normal 0x0000 /* normal key - alt changes scan-code */
1903 #define FctKey 0x1000 /* func key if c == 0, else c */
1904 #define Special 0x2000 /* func key even if c != 0 */
1905 #define ModFct 0x3000 /* special if mod-keys, else 'c' */
1906 #define Map 0x4000 /* alt scan-code, map to unshift/shift key */
1907 #define KeyPad 0x5000 /* map to insert/kp-0 depending on c == 0xe0 */
1908 #define Grey 0x6000 /* Grey keypad key */
1909
1910 #define Alt 0x0100 /* alt scan-code */
1911 #define Ctrl 0x0200 /* ctrl scan-code */
1912 #define Shift 0x0400 /* shift scan-code */
1913
1914 static int extended_kbd; /* 101 (102) keyboard present. */
1915
1916 struct kbd_translate {
1917 unsigned char sc;
1918 unsigned char ch;
1919 unsigned short code;
1920 };
1921
1922 struct dos_keyboard_map
1923 {
1924 char *unshifted;
1925 char *shifted;
1926 char *alt_gr;
1927 struct kbd_translate *translate_table;
1928 };
1929
1930
1931 static struct dos_keyboard_map us_keyboard = {
1932 /* 0 1 2 3 4 5 */
1933 /* 01234567890123456789012345678901234567890 123 45678901234 */
1934 "`1234567890-= qwertyuiop[] asdfghjkl;'\\ \\zxcvbnm,./ ",
1935 /* 0123456789012345678901234567890123456789 012345678901234 */
1936 "~!@#$%^&*()_+ QWERTYUIOP{} ASDFGHJKL:\"| |ZXCVBNM<>? ",
1937 0, /* no Alt-Gr key */
1938 0 /* no translate table */
1939 };
1940
1941 static struct dos_keyboard_map fr_keyboard = {
1942 /* 0 1 2 3 4 5 */
1943 /* 012 3456789012345678901234567890123456789012345678901234 */
1944 "ý&\82\"'(-\8a_\80\85)= azertyuiop^$ qsdfghjklm\97* <wxcvbn,;:! ",
1945 /* 0123456789012345678901234567890123456789012345678901234 */
1946 " 1234567890ø+ AZERTYUIOPù\9c QSDFGHJKLM%æ >WXCVBN?./õ ",
1947 /* 01234567 89012345678901234567890123456789012345678901234 */
1948 " ~#{[|`\\^@]} Ï ",
1949 0 /* no translate table */
1950 };
1951
1952 /*
1953 * Italian keyboard support, country code 39.
1954 * '<' 56:3c*0000
1955 * '>' 56:3e*0000
1956 * added also {,},` as, respectively, AltGr-8, AltGr-9, AltGr-'
1957 * Donated by Stefano Brozzi <brozzis@mag00.cedi.unipr.it>
1958 */
1959
1960 static struct kbd_translate it_kbd_translate_table[] = {
1961 { 0x56, 0x3c, Normal | 13 },
1962 { 0x56, 0x3e, Normal | 27 },
1963 { 0, 0, 0 }
1964 };
1965 static struct dos_keyboard_map it_keyboard = {
1966 /* 0 1 2 3 4 5 */
1967 /* 0 123456789012345678901234567890123456789012345678901234 */
1968 "\\1234567890'\8d< qwertyuiop\8a+> asdfghjkl\95\85\97 <zxcvbnm,.- ",
1969 /* 01 23456789012345678901234567890123456789012345678901234 */
1970 "|!\"\9c$%&/()=?^> QWERTYUIOP\82* ASDFGHJKL\87øõ >ZXCVBNM;:_ ",
1971 /* 0123456789012345678901234567890123456789012345678901234 */
1972 " {}~` [] @# ",
1973 it_kbd_translate_table
1974 };
1975
1976 static struct dos_keyboard_map dk_keyboard = {
1977 /* 0 1 2 3 4 5 */
1978 /* 0123456789012345678901234567890123456789012345678901234 */
1979 "«1234567890+| qwertyuiop\86~ asdfghjkl\91\9b' <zxcvbnm,.- ",
1980 /* 01 23456789012345678901234567890123456789012345678901234 */
1981 "õ!\"#$%&/()=?` QWERTYUIOP\8f^ ASDFGHJKL\92\9d* >ZXCVBNM;:_ ",
1982 /* 0123456789012345678901234567890123456789012345678901234 */
1983 " @\9c$ {[]} | ",
1984 0 /* no translate table */
1985 };
1986
1987 static struct kbd_translate jp_kbd_translate_table[] = {
1988 { 0x73, 0x5c, Normal | 0 },
1989 { 0x73, 0x5f, Normal | 0 },
1990 { 0x73, 0x1c, Map | 0 },
1991 { 0x7d, 0x5c, Normal | 13 },
1992 { 0x7d, 0x7c, Normal | 13 },
1993 { 0x7d, 0x1c, Map | 13 },
1994 { 0, 0, 0 }
1995 };
1996 static struct dos_keyboard_map jp_keyboard = {
1997 /* 0 1 2 3 4 5 */
1998 /* 0123456789012 345678901234567890123456789012345678901234 */
1999 "\\1234567890-^\\ qwertyuiop@[ asdfghjkl;:] zxcvbnm,./ ",
2000 /* 01 23456789012345678901234567890123456789012345678901234 */
2001 "_!\"#$%&'()~=~| QWERTYUIOP`{ ASDFGHJKL+*} ZXCVBNM<>? ",
2002 0, /* no Alt-Gr key */
2003 jp_kbd_translate_table
2004 };
2005
2006 static struct keyboard_layout_list
2007 {
2008 int country_code;
2009 struct dos_keyboard_map *keyboard_map;
2010 } keyboard_layout_list[] =
2011 {
2012 { 1, &us_keyboard },
2013 { 33, &fr_keyboard },
2014 { 39, &it_keyboard },
2015 { 45, &dk_keyboard },
2016 { 81, &jp_keyboard }
2017 };
2018
2019 static struct dos_keyboard_map *keyboard;
2020 static int keyboard_map_all;
2021 static int international_keyboard;
2022
2023 int
2024 dos_set_keyboard (int code, int always)
2025 {
2026 int i;
2027 _go32_dpmi_registers regs;
2028
2029 /* See if Keyb.Com is installed (for international keyboard support).
2030 Note: calling Int 2Fh via int86 wedges the DOS box on some versions
2031 of Windows 9X! So don't do that! */
2032 regs.x.ax = 0xad80;
2033 regs.x.ss = regs.x.sp = regs.x.flags = 0;
2034 _go32_dpmi_simulate_int (0x2f, &regs);
2035 if (regs.h.al == 0xff)
2036 international_keyboard = 1;
2037
2038 /* Initialize to US settings, for countries that don't have their own. */
2039 keyboard = keyboard_layout_list[0].keyboard_map;
2040 keyboard_map_all = always;
2041 dos_keyboard_layout = 1;
2042
2043 for (i = 0; i < (sizeof (keyboard_layout_list)/sizeof (struct keyboard_layout_list)); i++)
2044 if (code == keyboard_layout_list[i].country_code)
2045 {
2046 keyboard = keyboard_layout_list[i].keyboard_map;
2047 keyboard_map_all = always;
2048 dos_keyboard_layout = code;
2049 return 1;
2050 }
2051 return 0;
2052 }
2053 \f
2054 static struct
2055 {
2056 unsigned char char_code; /* normal code */
2057 unsigned char meta_code; /* M- code */
2058 unsigned char keypad_code; /* keypad code */
2059 unsigned char editkey_code; /* edit key */
2060 } keypad_translate_map[] = {
2061 { '0', '0', 0xb0, /* kp-0 */ 0x63 /* insert */ },
2062 { '1', '1', 0xb1, /* kp-1 */ 0x57 /* end */ },
2063 { '2', '2', 0xb2, /* kp-2 */ 0x54 /* down */ },
2064 { '3', '3', 0xb3, /* kp-3 */ 0x56 /* next */ },
2065 { '4', '4', 0xb4, /* kp-4 */ 0x51 /* left */ },
2066 { '5', '5', 0xb5, /* kp-5 */ 0xb5 /* kp-5 */ },
2067 { '6', '6', 0xb6, /* kp-6 */ 0x53 /* right */ },
2068 { '7', '7', 0xb7, /* kp-7 */ 0x50 /* home */ },
2069 { '8', '8', 0xb8, /* kp-8 */ 0x52 /* up */ },
2070 { '9', '9', 0xb9, /* kp-9 */ 0x55 /* prior */ },
2071 { '.', '-', 0xae, /* kp-decimal */ 0xff /* delete */}
2072 };
2073
2074 static struct
2075 {
2076 unsigned char char_code; /* normal code */
2077 unsigned char keypad_code; /* keypad code */
2078 } grey_key_translate_map[] = {
2079 { '/', 0xaf /* kp-decimal */ },
2080 { '*', 0xaa /* kp-multiply */ },
2081 { '-', 0xad /* kp-subtract */ },
2082 { '+', 0xab /* kp-add */ },
2083 { '\r', 0x8d /* kp-enter */ }
2084 };
2085
2086 static unsigned short
2087 ibmpc_translate_map[] =
2088 {
2089 /* --------------- 00 to 0f --------------- */
2090 Normal | 0xff, /* Ctrl Break + Alt-NNN */
2091 Alt | ModFct | 0x1b, /* Escape */
2092 Normal | 1, /* '1' */
2093 Normal | 2, /* '2' */
2094 Normal | 3, /* '3' */
2095 Normal | 4, /* '4' */
2096 Normal | 5, /* '5' */
2097 Normal | 6, /* '6' */
2098 Normal | 7, /* '7' */
2099 Normal | 8, /* '8' */
2100 Normal | 9, /* '9' */
2101 Normal | 10, /* '0' */
2102 Normal | 11, /* '-' */
2103 Normal | 12, /* '=' */
2104 Special | 0x08, /* Backspace */
2105 ModFct | 0x74, /* Tab/Backtab */
2106
2107 /* --------------- 10 to 1f --------------- */
2108 Map | 15, /* 'q' */
2109 Map | 16, /* 'w' */
2110 Map | 17, /* 'e' */
2111 Map | 18, /* 'r' */
2112 Map | 19, /* 't' */
2113 Map | 20, /* 'y' */
2114 Map | 21, /* 'u' */
2115 Map | 22, /* 'i' */
2116 Map | 23, /* 'o' */
2117 Map | 24, /* 'p' */
2118 Map | 25, /* '[' */
2119 Map | 26, /* ']' */
2120 ModFct | 0x0d, /* Return */
2121 Ignore, /* Ctrl */
2122 Map | 30, /* 'a' */
2123 Map | 31, /* 's' */
2124
2125 /* --------------- 20 to 2f --------------- */
2126 Map | 32, /* 'd' */
2127 Map | 33, /* 'f' */
2128 Map | 34, /* 'g' */
2129 Map | 35, /* 'h' */
2130 Map | 36, /* 'j' */
2131 Map | 37, /* 'k' */
2132 Map | 38, /* 'l' */
2133 Map | 39, /* ';' */
2134 Map | 40, /* '\'' */
2135 Map | 0, /* '`' */
2136 Ignore, /* Left shift */
2137 Map | 41, /* '\\' */
2138 Map | 45, /* 'z' */
2139 Map | 46, /* 'x' */
2140 Map | 47, /* 'c' */
2141 Map | 48, /* 'v' */
2142
2143 /* --------------- 30 to 3f --------------- */
2144 Map | 49, /* 'b' */
2145 Map | 50, /* 'n' */
2146 Map | 51, /* 'm' */
2147 Map | 52, /* ',' */
2148 Map | 53, /* '.' */
2149 Map | 54, /* '/' */
2150 Ignore, /* Right shift */
2151 Grey | 1, /* Grey * */
2152 Ignore, /* Alt */
2153 Normal | 55, /* ' ' */
2154 Ignore, /* Caps Lock */
2155 FctKey | 0xbe, /* F1 */
2156 FctKey | 0xbf, /* F2 */
2157 FctKey | 0xc0, /* F3 */
2158 FctKey | 0xc1, /* F4 */
2159 FctKey | 0xc2, /* F5 */
2160
2161 /* --------------- 40 to 4f --------------- */
2162 FctKey | 0xc3, /* F6 */
2163 FctKey | 0xc4, /* F7 */
2164 FctKey | 0xc5, /* F8 */
2165 FctKey | 0xc6, /* F9 */
2166 FctKey | 0xc7, /* F10 */
2167 Ignore, /* Num Lock */
2168 Ignore, /* Scroll Lock */
2169 KeyPad | 7, /* Home */
2170 KeyPad | 8, /* Up */
2171 KeyPad | 9, /* Page Up */
2172 Grey | 2, /* Grey - */
2173 KeyPad | 4, /* Left */
2174 KeyPad | 5, /* Keypad 5 */
2175 KeyPad | 6, /* Right */
2176 Grey | 3, /* Grey + */
2177 KeyPad | 1, /* End */
2178
2179 /* --------------- 50 to 5f --------------- */
2180 KeyPad | 2, /* Down */
2181 KeyPad | 3, /* Page Down */
2182 KeyPad | 0, /* Insert */
2183 KeyPad | 10, /* Delete */
2184 Shift | FctKey | 0xbe, /* (Shift) F1 */
2185 Shift | FctKey | 0xbf, /* (Shift) F2 */
2186 Shift | FctKey | 0xc0, /* (Shift) F3 */
2187 Shift | FctKey | 0xc1, /* (Shift) F4 */
2188 Shift | FctKey | 0xc2, /* (Shift) F5 */
2189 Shift | FctKey | 0xc3, /* (Shift) F6 */
2190 Shift | FctKey | 0xc4, /* (Shift) F7 */
2191 Shift | FctKey | 0xc5, /* (Shift) F8 */
2192 Shift | FctKey | 0xc6, /* (Shift) F9 */
2193 Shift | FctKey | 0xc7, /* (Shift) F10 */
2194 Ctrl | FctKey | 0xbe, /* (Ctrl) F1 */
2195 Ctrl | FctKey | 0xbf, /* (Ctrl) F2 */
2196
2197 /* --------------- 60 to 6f --------------- */
2198 Ctrl | FctKey | 0xc0, /* (Ctrl) F3 */
2199 Ctrl | FctKey | 0xc1, /* (Ctrl) F4 */
2200 Ctrl | FctKey | 0xc2, /* (Ctrl) F5 */
2201 Ctrl | FctKey | 0xc3, /* (Ctrl) F6 */
2202 Ctrl | FctKey | 0xc4, /* (Ctrl) F7 */
2203 Ctrl | FctKey | 0xc5, /* (Ctrl) F8 */
2204 Ctrl | FctKey | 0xc6, /* (Ctrl) F9 */
2205 Ctrl | FctKey | 0xc7, /* (Ctrl) F10 */
2206 Alt | FctKey | 0xbe, /* (Alt) F1 */
2207 Alt | FctKey | 0xbf, /* (Alt) F2 */
2208 Alt | FctKey | 0xc0, /* (Alt) F3 */
2209 Alt | FctKey | 0xc1, /* (Alt) F4 */
2210 Alt | FctKey | 0xc2, /* (Alt) F5 */
2211 Alt | FctKey | 0xc3, /* (Alt) F6 */
2212 Alt | FctKey | 0xc4, /* (Alt) F7 */
2213 Alt | FctKey | 0xc5, /* (Alt) F8 */
2214
2215 /* --------------- 70 to 7f --------------- */
2216 Alt | FctKey | 0xc6, /* (Alt) F9 */
2217 Alt | FctKey | 0xc7, /* (Alt) F10 */
2218 Ctrl | FctKey | 0x6d, /* (Ctrl) Sys Rq */
2219 Ctrl | KeyPad | 4, /* (Ctrl) Left */
2220 Ctrl | KeyPad | 6, /* (Ctrl) Right */
2221 Ctrl | KeyPad | 1, /* (Ctrl) End */
2222 Ctrl | KeyPad | 3, /* (Ctrl) Page Down */
2223 Ctrl | KeyPad | 7, /* (Ctrl) Home */
2224 Alt | Map | 1, /* '1' */
2225 Alt | Map | 2, /* '2' */
2226 Alt | Map | 3, /* '3' */
2227 Alt | Map | 4, /* '4' */
2228 Alt | Map | 5, /* '5' */
2229 Alt | Map | 6, /* '6' */
2230 Alt | Map | 7, /* '7' */
2231 Alt | Map | 8, /* '8' */
2232
2233 /* --------------- 80 to 8f --------------- */
2234 Alt | Map | 9, /* '9' */
2235 Alt | Map | 10, /* '0' */
2236 Alt | Map | 11, /* '-' */
2237 Alt | Map | 12, /* '=' */
2238 Ctrl | KeyPad | 9, /* (Ctrl) Page Up */
2239 FctKey | 0xc8, /* F11 */
2240 FctKey | 0xc9, /* F12 */
2241 Shift | FctKey | 0xc8, /* (Shift) F11 */
2242 Shift | FctKey | 0xc9, /* (Shift) F12 */
2243 Ctrl | FctKey | 0xc8, /* (Ctrl) F11 */
2244 Ctrl | FctKey | 0xc9, /* (Ctrl) F12 */
2245 Alt | FctKey | 0xc8, /* (Alt) F11 */
2246 Alt | FctKey | 0xc9, /* (Alt) F12 */
2247 Ctrl | KeyPad | 8, /* (Ctrl) Up */
2248 Ctrl | Grey | 2, /* (Ctrl) Grey - */
2249 Ctrl | KeyPad | 5, /* (Ctrl) Keypad 5 */
2250
2251 /* --------------- 90 to 9f --------------- */
2252 Ctrl | Grey | 3, /* (Ctrl) Grey + */
2253 Ctrl | KeyPad | 2, /* (Ctrl) Down */
2254 Ctrl | KeyPad | 0, /* (Ctrl) Insert */
2255 Ctrl | KeyPad | 10, /* (Ctrl) Delete */
2256 Ctrl | FctKey | 0x09, /* (Ctrl) Tab */
2257 Ctrl | Grey | 0, /* (Ctrl) Grey / */
2258 Ctrl | Grey | 1, /* (Ctrl) Grey * */
2259 Alt | FctKey | 0x50, /* (Alt) Home */
2260 Alt | FctKey | 0x52, /* (Alt) Up */
2261 Alt | FctKey | 0x55, /* (Alt) Page Up */
2262 Ignore, /* NO KEY */
2263 Alt | FctKey | 0x51, /* (Alt) Left */
2264 Ignore, /* NO KEY */
2265 Alt | FctKey | 0x53, /* (Alt) Right */
2266 Ignore, /* NO KEY */
2267 Alt | FctKey | 0x57, /* (Alt) End */
2268
2269 /* --------------- a0 to af --------------- */
2270 Alt | KeyPad | 2, /* (Alt) Down */
2271 Alt | KeyPad | 3, /* (Alt) Page Down */
2272 Alt | KeyPad | 0, /* (Alt) Insert */
2273 Alt | KeyPad | 10, /* (Alt) Delete */
2274 Alt | Grey | 0, /* (Alt) Grey / */
2275 Alt | FctKey | 0x09, /* (Alt) Tab */
2276 Alt | Grey | 4 /* (Alt) Keypad Enter */
2277 };
2278 \f
2279 /* These bit-positions corresponds to values returned by BIOS */
2280 #define SHIFT_P 0x0003 /* two bits! */
2281 #define CTRL_P 0x0004
2282 #define ALT_P 0x0008
2283 #define SCRLOCK_P 0x0010
2284 #define NUMLOCK_P 0x0020
2285 #define CAPSLOCK_P 0x0040
2286 #define ALT_GR_P 0x0800
2287 #define SUPER_P 0x4000 /* pseudo */
2288 #define HYPER_P 0x8000 /* pseudo */
2289
2290 static int
2291 dos_get_modifiers (int *keymask)
2292 {
2293 union REGS regs;
2294 int mask, modifiers = 0;
2295
2296 /* Calculate modifier bits */
2297 regs.h.ah = extended_kbd ? 0x12 : 0x02;
2298 int86 (0x16, &regs, &regs);
2299
2300 if (!extended_kbd)
2301 {
2302 mask = regs.h.al & (SHIFT_P | CTRL_P | ALT_P |
2303 SCRLOCK_P | NUMLOCK_P | CAPSLOCK_P);
2304 }
2305 else
2306 {
2307 mask = regs.h.al & (SHIFT_P |
2308 SCRLOCK_P | NUMLOCK_P | CAPSLOCK_P);
2309
2310 /* Do not break international keyboard support. */
2311 /* When Keyb.Com is loaded, the right Alt key is */
2312 /* used for accessing characters like { and } */
2313 if (regs.h.ah & 2) /* Left ALT pressed ? */
2314 mask |= ALT_P;
2315
2316 if ((regs.h.ah & 8) != 0) /* Right ALT pressed ? */
2317 {
2318 mask |= ALT_GR_P;
2319 if (dos_hyper_key == 1)
2320 {
2321 mask |= HYPER_P;
2322 modifiers |= hyper_modifier;
2323 }
2324 else if (dos_super_key == 1)
2325 {
2326 mask |= SUPER_P;
2327 modifiers |= super_modifier;
2328 }
2329 else if (!international_keyboard)
2330 {
2331 /* If Keyb.Com is NOT installed, let Right Alt behave
2332 like the Left Alt. */
2333 mask &= ~ALT_GR_P;
2334 mask |= ALT_P;
2335 }
2336 }
2337
2338 if (regs.h.ah & 1) /* Left CTRL pressed ? */
2339 mask |= CTRL_P;
2340
2341 if (regs.h.ah & 4) /* Right CTRL pressed ? */
2342 {
2343 if (dos_hyper_key == 2)
2344 {
2345 mask |= HYPER_P;
2346 modifiers |= hyper_modifier;
2347 }
2348 else if (dos_super_key == 2)
2349 {
2350 mask |= SUPER_P;
2351 modifiers |= super_modifier;
2352 }
2353 else
2354 mask |= CTRL_P;
2355 }
2356 }
2357
2358 if (mask & SHIFT_P)
2359 modifiers |= shift_modifier;
2360 if (mask & CTRL_P)
2361 modifiers |= ctrl_modifier;
2362 if (mask & ALT_P)
2363 modifiers |= meta_modifier;
2364
2365 if (keymask)
2366 *keymask = mask;
2367 return modifiers;
2368 }
2369
2370 #define NUM_RECENT_DOSKEYS (100)
2371 int recent_doskeys_index; /* Index for storing next element into recent_doskeys */
2372 int total_doskeys; /* Total number of elements stored into recent_doskeys */
2373 Lisp_Object recent_doskeys; /* A vector, holding the last 100 keystrokes */
2374
2375 DEFUN ("recent-doskeys", Frecent_doskeys, Srecent_doskeys, 0, 0, 0,
2376 doc: /* Return vector of last 100 keyboard input values seen in dos_rawgetc.
2377 Each input key receives two values in this vector: first the ASCII code,
2378 and then the scan code. */)
2379 (void)
2380 {
2381 Lisp_Object val, *keys = XVECTOR (recent_doskeys)->contents;
2382
2383 if (total_doskeys < NUM_RECENT_DOSKEYS)
2384 return Fvector (total_doskeys, keys);
2385 else
2386 {
2387 val = Fvector (NUM_RECENT_DOSKEYS, keys);
2388 vcopy (val, 0, keys + recent_doskeys_index,
2389 NUM_RECENT_DOSKEYS - recent_doskeys_index);
2390 vcopy (val, NUM_RECENT_DOSKEYS - recent_doskeys_index,
2391 keys, recent_doskeys_index);
2392 return val;
2393 }
2394 }
2395
2396 /* Get a char from keyboard. Function keys are put into the event queue. */
2397 static int
2398 dos_rawgetc (void)
2399 {
2400 struct input_event event;
2401 union REGS regs;
2402 Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (SELECTED_FRAME ());
2403 EVENT_INIT (event);
2404
2405 #ifndef HAVE_X_WINDOWS
2406 /* Maybe put the cursor where it should be. */
2407 IT_cmgoto (SELECTED_FRAME ());
2408 #endif
2409
2410 /* The following condition is equivalent to `kbhit ()', except that
2411 it uses the bios to do its job. This pleases DESQview/X. */
2412 while ((regs.h.ah = extended_kbd ? 0x11 : 0x01),
2413 int86 (0x16, &regs, &regs),
2414 (regs.x.flags & 0x40) == 0)
2415 {
2416 union REGS regs;
2417 register unsigned char c;
2418 int modifiers, sc, code = -1, mask, kp_mode;
2419
2420 regs.h.ah = extended_kbd ? 0x10 : 0x00;
2421 int86 (0x16, &regs, &regs);
2422 c = regs.h.al;
2423 sc = regs.h.ah;
2424
2425 total_doskeys += 2;
2426 ASET (recent_doskeys, recent_doskeys_index, make_number (c));
2427 recent_doskeys_index++;
2428 if (recent_doskeys_index == NUM_RECENT_DOSKEYS)
2429 recent_doskeys_index = 0;
2430 ASET (recent_doskeys, recent_doskeys_index, make_number (sc));
2431 recent_doskeys_index++;
2432 if (recent_doskeys_index == NUM_RECENT_DOSKEYS)
2433 recent_doskeys_index = 0;
2434
2435 modifiers = dos_get_modifiers (&mask);
2436
2437 #ifndef HAVE_X_WINDOWS
2438 if (!NILP (Vdos_display_scancodes))
2439 {
2440 char buf[11];
2441 sprintf (buf, "%02x:%02x*%04x",
2442 (unsigned) (sc&0xff), (unsigned) c, mask);
2443 dos_direct_output (screen_size_Y - 2, screen_size_X - 12, buf, 10);
2444 }
2445 #endif
2446
2447 if (sc == 0xe0)
2448 {
2449 switch (c)
2450 {
2451 case 10: /* Ctrl Grey Enter */
2452 code = Ctrl | Grey | 4;
2453 break;
2454 case 13: /* Grey Enter */
2455 code = Grey | 4;
2456 break;
2457 case '/': /* Grey / */
2458 code = Grey | 0;
2459 break;
2460 default:
2461 continue;
2462 };
2463 c = 0;
2464 }
2465 else
2466 {
2467 /* Try the keyboard-private translation table first. */
2468 if (keyboard->translate_table)
2469 {
2470 struct kbd_translate *p = keyboard->translate_table;
2471
2472 while (p->sc)
2473 {
2474 if (p->sc == sc && p->ch == c)
2475 {
2476 code = p->code;
2477 break;
2478 }
2479 p++;
2480 }
2481 }
2482 /* If the private table didn't translate it, use the general
2483 one. */
2484 if (code == -1)
2485 {
2486 if (sc >= (sizeof (ibmpc_translate_map) / sizeof (short)))
2487 continue;
2488 if ((code = ibmpc_translate_map[sc]) == Ignore)
2489 continue;
2490 }
2491 }
2492
2493 if (c == 0)
2494 {
2495 /* We only look at the keyboard Ctrl/Shift/Alt keys when
2496 Emacs is ready to read a key. Therefore, if they press
2497 `Alt-x' when Emacs is busy, by the time we get to
2498 `dos_get_modifiers', they might have already released the
2499 Alt key, and Emacs gets just `x', which is BAD.
2500 However, for keys with the `Map' property set, the ASCII
2501 code returns zero only if Alt is pressed. So, when we DON'T
2502 have to support international_keyboard, we don't have to
2503 distinguish between the left and right Alt keys, and we
2504 can set the META modifier for any keys with the `Map'
2505 property if they return zero ASCII code (c = 0). */
2506 if ( (code & Alt)
2507 || ( (code & 0xf000) == Map && !international_keyboard))
2508 modifiers |= meta_modifier;
2509 if (code & Ctrl)
2510 modifiers |= ctrl_modifier;
2511 if (code & Shift)
2512 modifiers |= shift_modifier;
2513 }
2514
2515 switch (code & 0xf000)
2516 {
2517 case ModFct:
2518 if (c && !(mask & (SHIFT_P | ALT_P | CTRL_P | HYPER_P | SUPER_P)))
2519 return c;
2520 c = 0; /* Special */
2521
2522 case FctKey:
2523 if (c != 0)
2524 return c;
2525
2526 case Special:
2527 code |= 0xff00;
2528 break;
2529
2530 case Normal:
2531 if (sc == 0)
2532 {
2533 if (c == 0) /* ctrl-break */
2534 continue;
2535 return c; /* ALT-nnn */
2536 }
2537 if (!keyboard_map_all)
2538 {
2539 if (c != ' ')
2540 return c;
2541 code = c;
2542 break;
2543 }
2544
2545 case Map:
2546 if (c && !(mask & ALT_P) && !((mask & SHIFT_P) && (mask & CTRL_P)))
2547 if (!keyboard_map_all)
2548 return c;
2549
2550 code &= 0xff;
2551 if (mask & ALT_P && code <= 10 && code > 0 && dos_keypad_mode & 0x200)
2552 mask |= SHIFT_P; /* ALT-1 => M-! etc. */
2553
2554 if (mask & SHIFT_P)
2555 {
2556 code = keyboard->shifted[code];
2557 mask -= SHIFT_P;
2558 modifiers &= ~shift_modifier;
2559 }
2560 else
2561 if ((mask & ALT_GR_P) && keyboard->alt_gr && keyboard->alt_gr[code] != ' ')
2562 code = keyboard->alt_gr[code];
2563 else
2564 code = keyboard->unshifted[code];
2565 break;
2566
2567 case KeyPad:
2568 code &= 0xff;
2569 if (c == 0xe0) /* edit key */
2570 kp_mode = 3;
2571 else
2572 if ((mask & (NUMLOCK_P|CTRL_P|SHIFT_P|ALT_P)) == NUMLOCK_P) /* numlock on */
2573 kp_mode = dos_keypad_mode & 0x03;
2574 else
2575 kp_mode = (dos_keypad_mode >> 4) & 0x03;
2576
2577 switch (kp_mode)
2578 {
2579 case 0:
2580 if (code == 10 && dos_decimal_point)
2581 return dos_decimal_point;
2582 return keypad_translate_map[code].char_code;
2583
2584 case 1:
2585 code = 0xff00 | keypad_translate_map[code].keypad_code;
2586 break;
2587
2588 case 2:
2589 code = keypad_translate_map[code].meta_code;
2590 modifiers = meta_modifier;
2591 break;
2592
2593 case 3:
2594 code = 0xff00 | keypad_translate_map[code].editkey_code;
2595 break;
2596 }
2597 break;
2598
2599 case Grey:
2600 code &= 0xff;
2601 kp_mode = ((mask & (NUMLOCK_P|CTRL_P|SHIFT_P|ALT_P)) == NUMLOCK_P) ? 0x04 : 0x40;
2602 if (dos_keypad_mode & kp_mode)
2603 code = 0xff00 | grey_key_translate_map[code].keypad_code;
2604 else
2605 code = grey_key_translate_map[code].char_code;
2606 break;
2607 }
2608
2609 if (code == 0)
2610 continue;
2611
2612 if (!hlinfo->mouse_face_hidden && INTEGERP (Vmouse_highlight))
2613 {
2614 clear_mouse_face (hlinfo);
2615 hlinfo->mouse_face_hidden = 1;
2616 }
2617
2618 if (code >= 0x100)
2619 event.kind = NON_ASCII_KEYSTROKE_EVENT;
2620 else
2621 event.kind = ASCII_KEYSTROKE_EVENT;
2622 event.code = code;
2623 event.modifiers = modifiers;
2624 event.frame_or_window = selected_frame;
2625 event.arg = Qnil;
2626 event.timestamp = event_timestamp ();
2627 kbd_buffer_store_event (&event);
2628 }
2629
2630 if (have_mouse > 0 && !mouse_preempted)
2631 {
2632 int but, press, x, y, ok;
2633 int mouse_prev_x = mouse_last_x, mouse_prev_y = mouse_last_y;
2634 Lisp_Object mouse_window = Qnil;
2635
2636 /* Check for mouse movement *before* buttons. */
2637 mouse_check_moved ();
2638
2639 /* If the mouse moved from the spot of its last sighting, we
2640 might need to update mouse highlight. */
2641 if (mouse_last_x != mouse_prev_x || mouse_last_y != mouse_prev_y)
2642 {
2643 if (hlinfo->mouse_face_hidden)
2644 {
2645 hlinfo->mouse_face_hidden = 0;
2646 clear_mouse_face (hlinfo);
2647 }
2648
2649 /* Generate SELECT_WINDOW_EVENTs when needed. */
2650 if (!NILP (Vmouse_autoselect_window))
2651 {
2652 static Lisp_Object last_mouse_window;
2653
2654 mouse_window = window_from_coordinates
2655 (SELECTED_FRAME (), mouse_last_x, mouse_last_y, 0, 0);
2656 /* A window will be selected only when it is not
2657 selected now, and the last mouse movement event was
2658 not in it. A minibuffer window will be selected iff
2659 it is active. */
2660 if (WINDOWP (mouse_window)
2661 && !EQ (mouse_window, last_mouse_window)
2662 && !EQ (mouse_window, selected_window))
2663 {
2664 event.kind = SELECT_WINDOW_EVENT;
2665 event.frame_or_window = mouse_window;
2666 event.arg = Qnil;
2667 event.timestamp = event_timestamp ();
2668 kbd_buffer_store_event (&event);
2669 }
2670 /* Remember the last window where we saw the mouse. */
2671 last_mouse_window = mouse_window;
2672 }
2673
2674 previous_help_echo_string = help_echo_string;
2675 help_echo_string = help_echo_object = help_echo_window = Qnil;
2676 help_echo_pos = -1;
2677 note_mouse_highlight (SELECTED_FRAME (), mouse_last_x, mouse_last_y);
2678 /* If the contents of the global variable help_echo has
2679 changed, generate a HELP_EVENT. */
2680 if (!NILP (help_echo_string) || !NILP (previous_help_echo_string))
2681 gen_help_event (help_echo_string, selected_frame, help_echo_window,
2682 help_echo_object, help_echo_pos);
2683 }
2684
2685 for (but = 0; but < NUM_MOUSE_BUTTONS; but++)
2686 for (press = 0; press < 2; press++)
2687 {
2688 int button_num = but;
2689
2690 if (press)
2691 ok = mouse_pressed (but, &x, &y);
2692 else
2693 ok = mouse_released (but, &x, &y);
2694 if (ok)
2695 {
2696 /* Allow a simultaneous press/release of Mouse-1 and
2697 Mouse-2 to simulate Mouse-3 on two-button mice. */
2698 if (mouse_button_count == 2 && but < 2)
2699 {
2700 int x2, y2; /* don't clobber original coordinates */
2701
2702 /* If only one button is pressed, wait 100 msec and
2703 check again. This way, Speedy Gonzales isn't
2704 punished, while the slow get their chance. */
2705 if ((press && mouse_pressed (1-but, &x2, &y2))
2706 || (!press && mouse_released (1-but, &x2, &y2)))
2707 button_num = 2;
2708 else
2709 {
2710 delay (100);
2711 if ((press && mouse_pressed (1-but, &x2, &y2))
2712 || (!press && mouse_released (1-but, &x2, &y2)))
2713 button_num = 2;
2714 }
2715 }
2716
2717 event.kind = MOUSE_CLICK_EVENT;
2718 event.code = button_num;
2719 event.modifiers = dos_get_modifiers (0)
2720 | (press ? down_modifier : up_modifier);
2721 event.x = make_number (x);
2722 event.y = make_number (y);
2723 event.frame_or_window = selected_frame;
2724 event.arg = Qnil;
2725 event.timestamp = event_timestamp ();
2726 kbd_buffer_store_event (&event);
2727 }
2728 }
2729 }
2730
2731 return -1;
2732 }
2733
2734 static int prev_get_char = -1;
2735
2736 /* Return 1 if a key is ready to be read without suspending execution. */
2737 int
2738 dos_keysns (void)
2739 {
2740 if (prev_get_char != -1)
2741 return 1;
2742 else
2743 return ((prev_get_char = dos_rawgetc ()) != -1);
2744 }
2745
2746 /* Read a key. Return -1 if no key is ready. */
2747 int
2748 dos_keyread (void)
2749 {
2750 if (prev_get_char != -1)
2751 {
2752 int c = prev_get_char;
2753 prev_get_char = -1;
2754 return c;
2755 }
2756 else
2757 return dos_rawgetc ();
2758 }
2759 \f
2760 #ifndef HAVE_X_WINDOWS
2761
2762 /* Simulation of X's menus. Nothing too fancy here -- just make it work
2763 for now.
2764
2765 Actually, I don't know the meaning of all the parameters of the functions
2766 here -- I only know how they are called by xmenu.c. I could of course
2767 grab the nearest Xlib manual (down the hall, second-to-last door on the
2768 left), but I don't think it's worth the effort. */
2769
2770 /* These hold text of the current and the previous menu help messages. */
2771 static const char *menu_help_message, *prev_menu_help_message;
2772 /* Pane number and item number of the menu item which generated the
2773 last menu help message. */
2774 static int menu_help_paneno, menu_help_itemno;
2775
2776 static XMenu *
2777 IT_menu_create (void)
2778 {
2779 XMenu *menu;
2780
2781 menu = xmalloc (sizeof (XMenu));
2782 menu->allocated = menu->count = menu->panecount = menu->width = 0;
2783 return menu;
2784 }
2785
2786 /* Allocate some (more) memory for MENU ensuring that there is room for one
2787 for item. */
2788
2789 static void
2790 IT_menu_make_room (XMenu *menu)
2791 {
2792 if (menu->allocated == 0)
2793 {
2794 int count = menu->allocated = 10;
2795 menu->text = xmalloc (count * sizeof (char *));
2796 menu->submenu = xmalloc (count * sizeof (XMenu *));
2797 menu->panenumber = xmalloc (count * sizeof (int));
2798 menu->help_text = xmalloc (count * sizeof (char *));
2799 }
2800 else if (menu->allocated == menu->count)
2801 {
2802 int count = menu->allocated = menu->allocated + 10;
2803 menu->text
2804 = (char **) xrealloc (menu->text, count * sizeof (char *));
2805 menu->submenu
2806 = (XMenu **) xrealloc (menu->submenu, count * sizeof (XMenu *));
2807 menu->panenumber
2808 = (int *) xrealloc (menu->panenumber, count * sizeof (int));
2809 menu->help_text
2810 = (const char **) xrealloc (menu->help_text, count * sizeof (char *));
2811 }
2812 }
2813
2814 /* Search the given menu structure for a given pane number. */
2815
2816 static XMenu *
2817 IT_menu_search_pane (XMenu *menu, int pane)
2818 {
2819 int i;
2820 XMenu *try;
2821
2822 for (i = 0; i < menu->count; i++)
2823 if (menu->submenu[i])
2824 {
2825 if (pane == menu->panenumber[i])
2826 return menu->submenu[i];
2827 if ((try = IT_menu_search_pane (menu->submenu[i], pane)))
2828 return try;
2829 }
2830 return (XMenu *) 0;
2831 }
2832
2833 /* Determine how much screen space a given menu needs. */
2834
2835 static void
2836 IT_menu_calc_size (XMenu *menu, int *width, int *height)
2837 {
2838 int i, h2, w2, maxsubwidth, maxheight;
2839
2840 maxsubwidth = 0;
2841 maxheight = menu->count;
2842 for (i = 0; i < menu->count; i++)
2843 {
2844 if (menu->submenu[i])
2845 {
2846 IT_menu_calc_size (menu->submenu[i], &w2, &h2);
2847 if (w2 > maxsubwidth) maxsubwidth = w2;
2848 if (i + h2 > maxheight) maxheight = i + h2;
2849 }
2850 }
2851 *width = menu->width + maxsubwidth;
2852 *height = maxheight;
2853 }
2854
2855 /* Display MENU at (X,Y) using FACES. */
2856
2857 #define BUILD_CHAR_GLYPH(GLYPH, CODE, FACE_ID, PADDING_P) \
2858 do \
2859 { \
2860 (GLYPH).type = CHAR_GLYPH; \
2861 SET_CHAR_GLYPH ((GLYPH), CODE, FACE_ID, PADDING_P); \
2862 (GLYPH).charpos = -1; \
2863 } \
2864 while (0)
2865
2866 static void
2867 IT_menu_display (XMenu *menu, int y, int x, int pn, int *faces, int disp_help)
2868 {
2869 int i, j, face, width, mx, my, enabled, mousehere, row, col;
2870 struct glyph *text, *p;
2871 const unsigned char *q;
2872 struct frame *sf = SELECTED_FRAME ();
2873
2874 menu_help_message = NULL;
2875
2876 width = menu->width;
2877 /* We multiply width by 2 to account for possible control characters.
2878 FIXME: cater to non-ASCII characters in menus. */
2879 text = xmalloc ((width * 2 + 2) * sizeof (struct glyph));
2880 ScreenGetCursor (&row, &col);
2881 mouse_get_xy (&mx, &my);
2882 IT_update_begin (sf);
2883 for (i = 0; i < menu->count; i++)
2884 {
2885 int max_width = width + 2;
2886
2887 IT_cursor_to (sf, y + i, x);
2888 enabled
2889 = (!menu->submenu[i] && menu->panenumber[i]) || (menu->submenu[i]);
2890 mousehere = (y + i == my && x <= mx && mx < x + max_width);
2891 face = faces[enabled + mousehere * 2];
2892 /* The following if clause means that we display the menu help
2893 strings even if the menu item is currently disabled. */
2894 if (disp_help && enabled + mousehere * 2 >= 2)
2895 {
2896 menu_help_message = menu->help_text[i];
2897 menu_help_paneno = pn - 1;
2898 menu_help_itemno = i;
2899 }
2900 p = text;
2901 BUILD_CHAR_GLYPH (*p, ' ', face, 0);
2902 p++;
2903 for (j = 0, q = menu->text[i]; *q; j++)
2904 {
2905 unsigned c = STRING_CHAR_ADVANCE (q);
2906
2907 if (c > 26)
2908 {
2909 BUILD_CHAR_GLYPH (*p, c, face, 0);
2910 p++;
2911 }
2912 else /* make '^x' */
2913 {
2914 BUILD_CHAR_GLYPH (*p, '^', face, 0);
2915 p++;
2916 j++;
2917 BUILD_CHAR_GLYPH (*p, c + 64, face, 0);
2918 p++;
2919 }
2920 }
2921 /* Don't let the menu text overflow into the next screen row. */
2922 if (x + max_width > screen_size_X)
2923 {
2924 max_width = screen_size_X - x;
2925 text[max_width - 1].u.ch = '$'; /* indicate it's truncated */
2926 }
2927 for (; j < max_width - 2; j++, p++)
2928 BUILD_CHAR_GLYPH (*p, ' ', face, 0);
2929
2930 /* 16 is the character code of a character that on DOS terminal
2931 produces a nice-looking right-pointing arrow glyph. */
2932 BUILD_CHAR_GLYPH (*p, menu->submenu[i] ? 16 : ' ', face, 0);
2933 p++;
2934 IT_write_glyphs (sf, text, max_width);
2935 }
2936 IT_update_end (sf);
2937 IT_cursor_to (sf, row, col);
2938 xfree (text);
2939 }
2940 \f
2941 /* --------------------------- X Menu emulation ---------------------- */
2942
2943 /* Create a brand new menu structure. */
2944
2945 XMenu *
2946 XMenuCreate (Display *foo1, Window foo2, char *foo3)
2947 {
2948 return IT_menu_create ();
2949 }
2950
2951 /* Create a new pane and place it on the outer-most level. It is not
2952 clear that it should be placed out there, but I don't know what else
2953 to do. */
2954
2955 int
2956 XMenuAddPane (Display *foo, XMenu *menu, const char *txt, int enable)
2957 {
2958 int len;
2959 const char *p;
2960
2961 if (!enable)
2962 emacs_abort ();
2963
2964 IT_menu_make_room (menu);
2965 menu->submenu[menu->count] = IT_menu_create ();
2966 menu->text[menu->count] = (char *)txt;
2967 menu->panenumber[menu->count] = ++menu->panecount;
2968 menu->help_text[menu->count] = NULL;
2969 menu->count++;
2970
2971 /* Adjust length for possible control characters (which will
2972 be written as ^x). */
2973 for (len = strlen (txt), p = txt; *p; p++)
2974 if (*p < 27)
2975 len++;
2976
2977 if (len > menu->width)
2978 menu->width = len;
2979
2980 return menu->panecount;
2981 }
2982
2983 /* Create a new item in a menu pane. */
2984
2985 int
2986 XMenuAddSelection (Display *bar, XMenu *menu, int pane,
2987 int foo, char *txt, int enable, char const *help_text)
2988 {
2989 int len;
2990 char *p;
2991
2992 if (pane)
2993 if (!(menu = IT_menu_search_pane (menu, pane)))
2994 return XM_FAILURE;
2995 IT_menu_make_room (menu);
2996 menu->submenu[menu->count] = (XMenu *) 0;
2997 menu->text[menu->count] = txt;
2998 menu->panenumber[menu->count] = enable;
2999 menu->help_text[menu->count] = help_text;
3000 menu->count++;
3001
3002 /* Adjust length for possible control characters (which will
3003 be written as ^x). */
3004 for (len = strlen (txt), p = txt; *p; p++)
3005 if (*p < 27)
3006 len++;
3007
3008 if (len > menu->width)
3009 menu->width = len;
3010
3011 return XM_SUCCESS;
3012 }
3013
3014 /* Decide where the menu would be placed if requested at (X,Y). */
3015
3016 void
3017 XMenuLocate (Display *foo0, XMenu *menu, int foo1, int foo2, int x, int y,
3018 int *ulx, int *uly, int *width, int *height)
3019 {
3020 IT_menu_calc_size (menu, width, height);
3021 *ulx = x + 1;
3022 *uly = y;
3023 *width += 2;
3024 }
3025
3026 struct IT_menu_state
3027 {
3028 void *screen_behind;
3029 XMenu *menu;
3030 int pane;
3031 int x, y;
3032 };
3033
3034
3035 /* Display menu, wait for user's response, and return that response. */
3036
3037 int
3038 XMenuActivate (Display *foo, XMenu *menu, int *pane, int *selidx,
3039 int x0, int y0, unsigned ButtonMask, char **txt,
3040 void (*help_callback)(char const *, int, int))
3041 {
3042 struct IT_menu_state *state;
3043 int statecount, x, y, i, b, screensize, leave, result, onepane;
3044 int title_faces[4]; /* face to display the menu title */
3045 int faces[4], buffers_num_deleted = 0;
3046 struct frame *sf = SELECTED_FRAME ();
3047 Lisp_Object saved_echo_area_message, selectface;
3048
3049 /* Just in case we got here without a mouse present... */
3050 if (have_mouse <= 0)
3051 return XM_IA_SELECT;
3052 /* Don't allow non-positive x0 and y0, lest the menu will wrap
3053 around the display. */
3054 if (x0 <= 0)
3055 x0 = 1;
3056 if (y0 <= 0)
3057 y0 = 1;
3058
3059 /* We will process all the mouse events directly, so we had
3060 better prevent dos_rawgetc from stealing them from us. */
3061 mouse_preempted++;
3062
3063 state = alloca (menu->panecount * sizeof (struct IT_menu_state));
3064 screensize = screen_size * 2;
3065 faces[0]
3066 = lookup_derived_face (sf, intern ("msdos-menu-passive-face"),
3067 DEFAULT_FACE_ID, 1);
3068 faces[1]
3069 = lookup_derived_face (sf, intern ("msdos-menu-active-face"),
3070 DEFAULT_FACE_ID, 1);
3071 selectface = intern ("msdos-menu-select-face");
3072 faces[2] = lookup_derived_face (sf, selectface,
3073 faces[0], 1);
3074 faces[3] = lookup_derived_face (sf, selectface,
3075 faces[1], 1);
3076
3077 /* Make sure the menu title is always displayed with
3078 `msdos-menu-active-face', no matter where the mouse pointer is. */
3079 for (i = 0; i < 4; i++)
3080 title_faces[i] = faces[3];
3081
3082 statecount = 1;
3083
3084 /* Don't let the title for the "Buffers" popup menu include a
3085 digit (which is ugly).
3086
3087 This is a terrible kludge, but I think the "Buffers" case is
3088 the only one where the title includes a number, so it doesn't
3089 seem to be necessary to make this more general. */
3090 if (strncmp (menu->text[0], "Buffers 1", 9) == 0)
3091 {
3092 menu->text[0][7] = '\0';
3093 buffers_num_deleted = 1;
3094 }
3095
3096 /* We need to save the current echo area message, so that we could
3097 restore it below, before we exit. See the commentary below,
3098 before the call to message_with_string. */
3099 saved_echo_area_message = Fcurrent_message ();
3100 state[0].menu = menu;
3101 mouse_off ();
3102 ScreenRetrieve (state[0].screen_behind = xmalloc (screensize));
3103
3104 /* Turn off the cursor. Otherwise it shows through the menu
3105 panes, which is ugly. */
3106 IT_display_cursor (0);
3107
3108 /* Display the menu title. */
3109 IT_menu_display (menu, y0 - 1, x0 - 1, 1, title_faces, 0);
3110 if (buffers_num_deleted)
3111 menu->text[0][7] = ' ';
3112 if ((onepane = menu->count == 1 && menu->submenu[0]))
3113 {
3114 menu->width = menu->submenu[0]->width;
3115 state[0].menu = menu->submenu[0];
3116 }
3117 else
3118 {
3119 state[0].menu = menu;
3120 }
3121 state[0].x = x0 - 1;
3122 state[0].y = y0;
3123 state[0].pane = onepane;
3124
3125 mouse_last_x = -1; /* A hack that forces display. */
3126 leave = 0;
3127 while (!leave)
3128 {
3129 if (!mouse_visible) mouse_on ();
3130 mouse_check_moved ();
3131 if (sf->mouse_moved)
3132 {
3133 sf->mouse_moved = 0;
3134 result = XM_IA_SELECT;
3135 mouse_get_xy (&x, &y);
3136 for (i = 0; i < statecount; i++)
3137 if (state[i].x <= x && x < state[i].x + state[i].menu->width + 2)
3138 {
3139 int dy = y - state[i].y;
3140 if (0 <= dy && dy < state[i].menu->count)
3141 {
3142 if (!state[i].menu->submenu[dy])
3143 {
3144 if (state[i].menu->panenumber[dy])
3145 result = XM_SUCCESS;
3146 else
3147 result = XM_IA_SELECT;
3148 }
3149 *pane = state[i].pane - 1;
3150 *selidx = dy;
3151 /* We hit some part of a menu, so drop extra menus that
3152 have been opened. That does not include an open and
3153 active submenu. */
3154 if (i != statecount - 2
3155 || state[i].menu->submenu[dy] != state[i+1].menu)
3156 while (i != statecount - 1)
3157 {
3158 statecount--;
3159 mouse_off ();
3160 ScreenUpdate (state[statecount].screen_behind);
3161 if (screen_virtual_segment)
3162 dosv_refresh_virtual_screen (0, screen_size);
3163 xfree (state[statecount].screen_behind);
3164 }
3165 if (i == statecount - 1 && state[i].menu->submenu[dy])
3166 {
3167 IT_menu_display (state[i].menu,
3168 state[i].y,
3169 state[i].x,
3170 state[i].pane,
3171 faces, 1);
3172 state[statecount].menu = state[i].menu->submenu[dy];
3173 state[statecount].pane = state[i].menu->panenumber[dy];
3174 mouse_off ();
3175 ScreenRetrieve (state[statecount].screen_behind
3176 = xmalloc (screensize));
3177 state[statecount].x
3178 = state[i].x + state[i].menu->width + 2;
3179 state[statecount].y = y;
3180 statecount++;
3181 }
3182 }
3183 }
3184 IT_menu_display (state[statecount - 1].menu,
3185 state[statecount - 1].y,
3186 state[statecount - 1].x,
3187 state[statecount - 1].pane,
3188 faces, 1);
3189 }
3190 else
3191 {
3192 if ((menu_help_message || prev_menu_help_message)
3193 && menu_help_message != prev_menu_help_message)
3194 {
3195 help_callback (menu_help_message,
3196 menu_help_paneno, menu_help_itemno);
3197 IT_display_cursor (0);
3198 prev_menu_help_message = menu_help_message;
3199 }
3200 /* We are busy-waiting for the mouse to move, so let's be nice
3201 to other Windows applications by releasing our time slice. */
3202 __dpmi_yield ();
3203 }
3204 for (b = 0; b < mouse_button_count && !leave; b++)
3205 {
3206 /* Only leave if user both pressed and released the mouse, and in
3207 that order. This avoids popping down the menu pane unless
3208 the user is really done with it. */
3209 if (mouse_pressed (b, &x, &y))
3210 {
3211 while (mouse_button_depressed (b, &x, &y))
3212 __dpmi_yield ();
3213 leave = 1;
3214 }
3215 (void) mouse_released (b, &x, &y);
3216 }
3217 }
3218
3219 mouse_off ();
3220 ScreenUpdate (state[0].screen_behind);
3221 if (screen_virtual_segment)
3222 dosv_refresh_virtual_screen (0, screen_size);
3223
3224 /* We have a situation here. ScreenUpdate has just restored the
3225 screen contents as it was before we started drawing this menu.
3226 That includes any echo area message that could have been
3227 displayed back then. (In reality, that echo area message will
3228 almost always be the ``keystroke echo'' that echoes the sequence
3229 of menu items chosen by the user.) However, if the menu had some
3230 help messages, then displaying those messages caused Emacs to
3231 forget about the original echo area message. So when
3232 ScreenUpdate restored it, it created a discrepancy between the
3233 actual screen contents and what Emacs internal data structures
3234 know about it.
3235
3236 To avoid this conflict, we force Emacs to restore the original
3237 echo area message as we found it when we entered this function.
3238 The irony of this is that we then erase the restored message
3239 right away, so the only purpose of restoring it is so that
3240 erasing it works correctly... */
3241 if (! NILP (saved_echo_area_message))
3242 message_with_string ("%s", saved_echo_area_message, 0);
3243 message1 (0);
3244 while (statecount--)
3245 xfree (state[statecount].screen_behind);
3246 IT_display_cursor (1); /* Turn cursor back on. */
3247 /* Clean up any mouse events that are waiting inside Emacs event queue.
3248 These events are likely to be generated before the menu was even
3249 displayed, probably because the user pressed and released the button
3250 (which invoked the menu) too quickly. If we don't remove these events,
3251 Emacs will process them after we return and surprise the user. */
3252 discard_mouse_events ();
3253 mouse_clear_clicks ();
3254 if (!kbd_buffer_events_waiting ())
3255 clear_input_pending ();
3256 /* Allow mouse events generation by dos_rawgetc. */
3257 mouse_preempted--;
3258 return result;
3259 }
3260
3261 /* Dispose of a menu. */
3262
3263 void
3264 XMenuDestroy (Display *foo, XMenu *menu)
3265 {
3266 int i;
3267 if (menu->allocated)
3268 {
3269 for (i = 0; i < menu->count; i++)
3270 if (menu->submenu[i])
3271 XMenuDestroy (foo, menu->submenu[i]);
3272 xfree (menu->text);
3273 xfree (menu->submenu);
3274 xfree (menu->panenumber);
3275 xfree (menu->help_text);
3276 }
3277 xfree (menu);
3278 menu_help_message = prev_menu_help_message = NULL;
3279 }
3280 #endif /* !HAVE_X_WINDOWS */
3281 \f
3282 /* ----------------------- DOS / UNIX conversion --------------------- */
3283
3284 void msdos_downcase_filename (unsigned char *);
3285
3286 /* Destructively turn backslashes into slashes. */
3287
3288 void
3289 dostounix_filename (char *p)
3290 {
3291 msdos_downcase_filename (p);
3292
3293 while (*p)
3294 {
3295 if (*p == '\\')
3296 *p = '/';
3297 p++;
3298 }
3299 }
3300
3301 /* Destructively turn slashes into backslashes. */
3302
3303 void
3304 unixtodos_filename (char *p)
3305 {
3306 if (p[1] == ':' && *p >= 'A' && *p <= 'Z')
3307 {
3308 *p += 'a' - 'A';
3309 p += 2;
3310 }
3311
3312 while (*p)
3313 {
3314 if (*p == '/')
3315 *p = '\\';
3316 p++;
3317 }
3318 }
3319
3320 /* Get the default directory for a given drive. 0=def, 1=A, 2=B, ... */
3321
3322 int
3323 getdefdir (int drive, char *dst)
3324 {
3325 char in_path[4], *p = in_path, e = errno;
3326
3327 /* Generate "X:." (when drive is X) or "." (when drive is 0). */
3328 if (drive != 0)
3329 {
3330 *p++ = drive + 'A' - 1;
3331 *p++ = ':';
3332 }
3333
3334 *p++ = '.';
3335 *p = '\0';
3336 errno = 0;
3337 _fixpath (in_path, dst);
3338 /* _fixpath can set errno to ENOSYS on non-LFN systems because
3339 it queries the LFN support, so ignore that error. */
3340 if ((errno && errno != ENOSYS) || *dst == '\0')
3341 return 0;
3342
3343 msdos_downcase_filename (dst);
3344
3345 errno = e;
3346 return 1;
3347 }
3348
3349 char *
3350 emacs_root_dir (void)
3351 {
3352 static char root_dir[4];
3353
3354 sprintf (root_dir, "%c:/", 'A' + getdisk ());
3355 root_dir[0] = tolower (root_dir[0]);
3356 return root_dir;
3357 }
3358
3359 /* Remove all CR's that are followed by a LF. */
3360
3361 int
3362 crlf_to_lf (int n, unsigned char *buf)
3363 {
3364 unsigned char *np = buf, *startp = buf, *endp = buf + n;
3365
3366 if (n == 0)
3367 return n;
3368 while (buf < endp - 1)
3369 {
3370 if (*buf == 0x0d)
3371 {
3372 if (*(++buf) != 0x0a)
3373 *np++ = 0x0d;
3374 }
3375 else
3376 *np++ = *buf++;
3377 }
3378 if (buf < endp)
3379 *np++ = *buf++;
3380 return np - startp;
3381 }
3382
3383 DEFUN ("msdos-long-file-names", Fmsdos_long_file_names, Smsdos_long_file_names,
3384 0, 0, 0,
3385 doc: /* Return non-nil if long file names are supported on MS-DOS. */)
3386 (void)
3387 {
3388 return (_USE_LFN ? Qt : Qnil);
3389 }
3390
3391 /* Convert alphabetic characters in a filename to lower-case. */
3392
3393 void
3394 msdos_downcase_filename (unsigned char *p)
3395 {
3396 /* Always lower-case drive letters a-z, even if the filesystem
3397 preserves case in filenames.
3398 This is so MSDOS filenames could be compared by string comparison
3399 functions that are case-sensitive. Even case-preserving filesystems
3400 do not distinguish case in drive letters. */
3401 if (p[1] == ':' && *p >= 'A' && *p <= 'Z')
3402 {
3403 *p += 'a' - 'A';
3404 p += 2;
3405 }
3406
3407 /* Under LFN we expect to get pathnames in their true case. */
3408 if (NILP (Fmsdos_long_file_names ()))
3409 for ( ; *p; p++)
3410 if (*p >= 'A' && *p <= 'Z')
3411 *p += 'a' - 'A';
3412 }
3413
3414 DEFUN ("msdos-downcase-filename", Fmsdos_downcase_filename, Smsdos_downcase_filename,
3415 1, 1, 0,
3416 doc: /* Convert alphabetic characters in FILENAME to lower case and return that.
3417 When long filenames are supported, doesn't change FILENAME.
3418 If FILENAME is not a string, returns nil.
3419 The argument object is never altered--the value is a copy. */)
3420 (Lisp_Object filename)
3421 {
3422 Lisp_Object tem;
3423
3424 if (! STRINGP (filename))
3425 return Qnil;
3426
3427 tem = Fcopy_sequence (filename);
3428 msdos_downcase_filename (SDATA (tem));
3429 return tem;
3430 }
3431 \f
3432 /* The Emacs root directory as determined by init_environment. */
3433
3434 static char emacsroot[MAXPATHLEN];
3435
3436 char *
3437 rootrelativepath (char *rel)
3438 {
3439 static char result[MAXPATHLEN + 10];
3440
3441 strcpy (result, emacsroot);
3442 strcat (result, "/");
3443 strcat (result, rel);
3444 return result;
3445 }
3446
3447 /* Define a lot of environment variables if not already defined. Don't
3448 remove anything unless you know what you're doing -- lots of code will
3449 break if one or more of these are missing. */
3450
3451 void
3452 init_environment (int argc, char **argv, int skip_args)
3453 {
3454 char *s, *t, *root;
3455 int len, i;
3456 static const char * const tempdirs[] = {
3457 "$TMPDIR", "$TEMP", "$TMP", "c:/"
3458 };
3459 const int imax = ARRAYELTS (tempdirs);
3460
3461 /* Make sure they have a usable $TMPDIR. Many Emacs functions use
3462 temporary files and assume "/tmp" if $TMPDIR is unset, which
3463 will break on DOS/Windows. Refuse to work if we cannot find
3464 a directory, not even "c:/", usable for that purpose. */
3465 for (i = 0; i < imax ; i++)
3466 {
3467 const char *tmp = tempdirs[i];
3468 char buf[FILENAME_MAX];
3469
3470 if (*tmp == '$')
3471 {
3472 int tmp_len;
3473
3474 tmp = getenv (tmp + 1);
3475 if (!tmp)
3476 continue;
3477
3478 /* Some lusers set TMPDIR=e:, probably because some losing
3479 programs cannot handle multiple slashes if they use e:/.
3480 e: fails in `access' below, so we interpret e: as e:/. */
3481 tmp_len = strlen (tmp);
3482 if (tmp[tmp_len - 1] != '/' && tmp[tmp_len - 1] != '\\')
3483 {
3484 strcpy (buf, tmp);
3485 buf[tmp_len++] = '/', buf[tmp_len] = 0;
3486 tmp = buf;
3487 }
3488 }
3489
3490 /* Note that `access' can lie to us if the directory resides on a
3491 read-only filesystem, like CD-ROM or a write-protected floppy.
3492 The only way to be really sure is to actually create a file and
3493 see if it succeeds. But I think that's too much to ask. */
3494 if (tmp && access (tmp, D_OK) == 0)
3495 {
3496 setenv ("TMPDIR", tmp, 1);
3497 break;
3498 }
3499 }
3500 if (i >= imax)
3501 cmd_error_internal
3502 (Fcons (Qerror,
3503 Fcons (build_string ("no usable temporary directories found!!"),
3504 Qnil)),
3505 "While setting TMPDIR: ");
3506
3507 /* Note the startup time, so we know not to clear the screen if we
3508 exit immediately; see IT_reset_terminal_modes.
3509 (Yes, I know `clock' returns zero the first time it's called, but
3510 I do this anyway, in case some wiseguy changes that at some point.) */
3511 startup_time = clock ();
3512
3513 /* Find our root from argv[0]. Assuming argv[0] is, say,
3514 "c:/emacs/bin/emacs.exe" our root will be "c:/emacs". */
3515 root = alloca (MAXPATHLEN + 20);
3516 _fixpath (argv[0], root);
3517 msdos_downcase_filename (root);
3518 len = strlen (root);
3519 while (len > 0 && root[len] != '/' && root[len] != ':')
3520 len--;
3521 root[len] = '\0';
3522 if (len > 4
3523 && (strcmp (root + len - 4, "/bin") == 0
3524 || strcmp (root + len - 4, "/src") == 0)) /* under a debugger */
3525 root[len - 4] = '\0';
3526 else
3527 strcpy (root, "c:/emacs"); /* let's be defensive */
3528 len = strlen (root);
3529 strcpy (emacsroot, root);
3530
3531 /* We default HOME to our root. */
3532 setenv ("HOME", root, 0);
3533
3534 /* We default EMACSPATH to root + "/bin". */
3535 strcpy (root + len, "/bin");
3536 setenv ("EMACSPATH", root, 0);
3537
3538 /* I don't expect anybody to ever use other terminals so the internal
3539 terminal is the default. */
3540 setenv ("TERM", "internal", 0);
3541
3542 #ifdef HAVE_X_WINDOWS
3543 /* Emacs expects DISPLAY to be set. */
3544 setenv ("DISPLAY", "unix:0.0", 0);
3545 #endif
3546
3547 /* SHELL is a bit tricky -- COMSPEC is the closest we come, but we must
3548 downcase it and mirror the backslashes. */
3549 s = getenv ("COMSPEC");
3550 if (!s) s = "c:/command.com";
3551 t = alloca (strlen (s) + 1);
3552 strcpy (t, s);
3553 dostounix_filename (t);
3554 setenv ("SHELL", t, 0);
3555
3556 /* PATH is also downcased and backslashes mirrored. */
3557 s = getenv ("PATH");
3558 if (!s) s = "";
3559 t = alloca (strlen (s) + 3);
3560 /* Current directory is always considered part of MsDos's path but it is
3561 not normally mentioned. Now it is. */
3562 strcat (strcpy (t, ".;"), s);
3563 dostounix_filename (t); /* Not a single file name, but this should work. */
3564 setenv ("PATH", t, 1);
3565
3566 /* In some sense all dos users have root privileges, so... */
3567 setenv ("USER", "root", 0);
3568 setenv ("NAME", getenv ("USER"), 0);
3569
3570 /* Time zone determined from country code. To make this possible, the
3571 country code may not span more than one time zone. In other words,
3572 in the USA, you lose. */
3573 if (!getenv ("TZ"))
3574 switch (dos_country_code)
3575 {
3576 case 31: /* Belgium */
3577 case 32: /* The Netherlands */
3578 case 33: /* France */
3579 case 34: /* Spain */
3580 case 36: /* Hungary */
3581 case 38: /* Yugoslavia (or what's left of it?) */
3582 case 39: /* Italy */
3583 case 41: /* Switzerland */
3584 case 42: /* Tjekia */
3585 case 45: /* Denmark */
3586 case 46: /* Sweden */
3587 case 47: /* Norway */
3588 case 48: /* Poland */
3589 case 49: /* Germany */
3590 /* Daylight saving from last Sunday in March to last Sunday in
3591 September, both at 2AM. */
3592 setenv ("TZ", "MET-01METDST-02,M3.5.0/02:00,M9.5.0/02:00", 0);
3593 break;
3594 case 44: /* United Kingdom */
3595 case 351: /* Portugal */
3596 case 354: /* Iceland */
3597 setenv ("TZ", "GMT+00", 0);
3598 break;
3599 case 81: /* Japan */
3600 case 82: /* Korea */
3601 setenv ("TZ", "JST-09", 0);
3602 break;
3603 case 90: /* Turkey */
3604 case 358: /* Finland */
3605 setenv ("TZ", "EET-02", 0);
3606 break;
3607 case 972: /* Israel */
3608 /* This is an approximation. (For exact rules, use the
3609 `zoneinfo/israel' file which comes with DJGPP, but you need
3610 to install it in `/usr/share/zoneinfo/' directory first.) */
3611 setenv ("TZ", "IST-02IDT-03,M4.1.6/00:00,M9.5.6/01:00", 0);
3612 break;
3613 }
3614 tzset ();
3615 }
3616
3617 \f
3618
3619 static int break_stat; /* BREAK check mode status. */
3620 static int stdin_stat; /* stdin IOCTL status. */
3621
3622 /* Turn off Dos' Ctrl-C checking and inhibit interpretation of
3623 control chars by DOS. Determine the keyboard type. */
3624
3625 int
3626 dos_ttraw (struct tty_display_info *tty)
3627 {
3628 union REGS inregs, outregs;
3629 static int first_time = 1;
3630
3631 /* If we are called for the initial terminal, it's too early to do
3632 anything, and termscript isn't set up. */
3633 if (tty->terminal->type == output_initial)
3634 return 2;
3635
3636 break_stat = getcbrk ();
3637 setcbrk (0);
3638
3639 if (first_time)
3640 {
3641 inregs.h.ah = 0xc0;
3642 int86 (0x15, &inregs, &outregs);
3643 extended_kbd = (!outregs.x.cflag) && (outregs.h.ah == 0);
3644
3645 have_mouse = 0;
3646
3647 if (1
3648 #ifdef HAVE_X_WINDOWS
3649 && inhibit_window_system
3650 #endif
3651 )
3652 {
3653 inregs.x.ax = 0x0021;
3654 int86 (0x33, &inregs, &outregs);
3655 have_mouse = (outregs.x.ax & 0xffff) == 0xffff;
3656 if (!have_mouse)
3657 {
3658 /* Reportedly, the above doesn't work for some mouse drivers. There
3659 is an additional detection method that should work, but might be
3660 a little slower. Use that as an alternative. */
3661 inregs.x.ax = 0x0000;
3662 int86 (0x33, &inregs, &outregs);
3663 have_mouse = (outregs.x.ax & 0xffff) == 0xffff;
3664 }
3665 if (have_mouse)
3666 mouse_button_count = outregs.x.bx;
3667
3668 #ifndef HAVE_X_WINDOWS
3669 /* Save the cursor shape used outside Emacs. */
3670 outside_cursor = _farpeekw (_dos_ds, 0x460);
3671 #endif
3672 }
3673
3674 first_time = 0;
3675
3676 stdin_stat = setmode (fileno (stdin), O_BINARY);
3677 return (stdin_stat != -1);
3678 }
3679 else
3680 return (setmode (fileno (stdin), O_BINARY) != -1);
3681 }
3682
3683 /* Restore status of standard input and Ctrl-C checking. */
3684
3685 int
3686 dos_ttcooked (void)
3687 {
3688 union REGS inregs, outregs;
3689
3690 setcbrk (break_stat);
3691 mouse_off ();
3692
3693 #ifndef HAVE_X_WINDOWS
3694 /* Restore the cursor shape we found on startup. */
3695 if (outside_cursor)
3696 {
3697 inregs.h.ah = 1;
3698 inregs.x.cx = outside_cursor;
3699 int86 (0x10, &inregs, &outregs);
3700 }
3701 #endif
3702
3703 return (setmode (fileno (stdin), stdin_stat) != -1);
3704 }
3705
3706 \f
3707 /* Run command as specified by ARGV in directory DIR.
3708 The command is run with input from TEMPIN, output to
3709 file TEMPOUT and stderr to TEMPERR. */
3710
3711 int
3712 run_msdos_command (unsigned char **argv, const char *working_dir,
3713 int tempin, int tempout, int temperr, char **envv)
3714 {
3715 char *saveargv1, *saveargv2, *lowcase_argv0, *pa, *pl;
3716 char oldwd[MAXPATHLEN + 1]; /* Fixed size is safe on MSDOS. */
3717 int msshell, result = -1, inbak, outbak, errbak, x, y;
3718 Lisp_Object cmd;
3719
3720 /* Get current directory as MSDOS cwd is not per-process. */
3721 getwd (oldwd);
3722
3723 /* If argv[0] is the shell, it might come in any lettercase.
3724 Since `Fmember' is case-sensitive, we need to downcase
3725 argv[0], even if we are on case-preserving filesystems. */
3726 lowcase_argv0 = alloca (strlen (argv[0]) + 1);
3727 for (pa = argv[0], pl = lowcase_argv0; *pa; pl++)
3728 {
3729 *pl = *pa++;
3730 if (*pl >= 'A' && *pl <= 'Z')
3731 *pl += 'a' - 'A';
3732 }
3733 *pl = '\0';
3734
3735 cmd = Ffile_name_nondirectory (build_string (lowcase_argv0));
3736 msshell = !NILP (Fmember (cmd, Fsymbol_value (intern ("msdos-shells"))))
3737 && !strcmp ("-c", argv[1]);
3738 if (msshell)
3739 {
3740 saveargv1 = argv[1];
3741 saveargv2 = argv[2];
3742 argv[1] = "/c";
3743 /* We only need to mirror slashes if a DOS shell will be invoked
3744 not via `system' (which does the mirroring itself). Yes, that
3745 means DJGPP v1.x will lose here. */
3746 if (argv[2] && argv[3])
3747 {
3748 char *p = alloca (strlen (argv[2]) + 1);
3749
3750 strcpy (argv[2] = p, saveargv2);
3751 while (*p && isspace (*p))
3752 p++;
3753 while (*p)
3754 {
3755 if (*p == '/')
3756 *p++ = '\\';
3757 else
3758 p++;
3759 }
3760 }
3761 }
3762
3763 chdir (working_dir);
3764 inbak = dup (0);
3765 outbak = dup (1);
3766 errbak = dup (2);
3767 if (inbak < 0 || outbak < 0 || errbak < 0)
3768 goto done; /* Allocation might fail due to lack of descriptors. */
3769
3770 if (have_mouse > 0)
3771 mouse_get_xy (&x, &y);
3772
3773 if (!noninteractive)
3774 dos_ttcooked (); /* do it here while 0 = stdin */
3775
3776 dup2 (tempin, 0);
3777 dup2 (tempout, 1);
3778 dup2 (temperr, 2);
3779
3780 if (msshell && !argv[3])
3781 {
3782 /* MS-DOS native shells are too restrictive. For starters, they
3783 cannot grok commands longer than 126 characters. In DJGPP v2
3784 and later, `system' is much smarter, so we'll call it instead. */
3785
3786 const char *cmnd;
3787
3788 /* A shell gets a single argument--its full command
3789 line--whose original was saved in `saveargv2'. */
3790
3791 /* Don't let them pass empty command lines to `system', since
3792 with some shells it will try to invoke an interactive shell,
3793 which will hang Emacs. */
3794 for (cmnd = saveargv2; *cmnd && isspace (*cmnd); cmnd++)
3795 ;
3796 if (*cmnd)
3797 {
3798 extern char **environ;
3799 char **save_env = environ;
3800 int save_system_flags = __system_flags;
3801
3802 /* Request the most powerful version of `system'. We need
3803 all the help we can get to avoid calling stock DOS shells. */
3804 __system_flags = (__system_redirect
3805 | __system_use_shell
3806 | __system_allow_multiple_cmds
3807 | __system_allow_long_cmds
3808 | __system_handle_null_commands
3809 | __system_emulate_chdir);
3810
3811 environ = envv;
3812 result = system (cmnd);
3813 __system_flags = save_system_flags;
3814 environ = save_env;
3815 }
3816 else
3817 result = 0; /* emulate Unixy shell behavior with empty cmd line */
3818 }
3819 else
3820 result = spawnve (P_WAIT, argv[0], (char **)argv, envv);
3821
3822 dup2 (inbak, 0);
3823 dup2 (outbak, 1);
3824 dup2 (errbak, 2);
3825 emacs_close (inbak);
3826 emacs_close (outbak);
3827 emacs_close (errbak);
3828
3829 if (!noninteractive)
3830 dos_ttraw (CURTTY ());
3831 if (have_mouse > 0)
3832 {
3833 mouse_init ();
3834 mouse_moveto (x, y);
3835 }
3836
3837 /* Some programs might change the meaning of the highest bit of the
3838 text attribute byte, so we get blinking characters instead of the
3839 bright background colors. Restore that. */
3840 if (!noninteractive)
3841 bright_bg ();
3842
3843 done:
3844 chdir (oldwd);
3845 if (msshell)
3846 {
3847 argv[1] = saveargv1;
3848 argv[2] = saveargv2;
3849 }
3850 return result;
3851 }
3852
3853 void
3854 croak (char *badfunc)
3855 {
3856 fprintf (stderr, "%s not yet implemented\r\n", badfunc);
3857 reset_all_sys_modes ();
3858 exit (1);
3859 }
3860 \f
3861 /*
3862 * A few unimplemented functions that we silently ignore.
3863 */
3864 pid_t tcgetpgrp (int fd) { return 0; }
3865 int setpgid (int pid, int pgid) { return 0; }
3866 int setpriority (int x, int y, int z) { return 0; }
3867 pid_t setsid (void) { return 0; }
3868
3869 \f
3870 /* Gnulib support and emulation. */
3871
3872 #if __DJGPP__ == 2 && __DJGPP_MINOR__ < 4
3873 ssize_t
3874 readlink (const char *name, char *dummy1, size_t dummy2)
3875 {
3876 /* `access' is much faster than `stat' on MS-DOS. */
3877 if (access (name, F_OK) == 0)
3878 errno = EINVAL;
3879 return -1;
3880 }
3881 #endif
3882
3883 /* dir_pathname is set by sys_opendir and used in readlinkat and in
3884 fstatat, when they get a special FD of zero, which means use the
3885 last directory opened by opendir. */
3886 static char dir_pathname[MAXPATHLEN];
3887 DIR *
3888 sys_opendir (const char *dirname)
3889 {
3890 _fixpath (dirname, dir_pathname);
3891 return opendir (dirname);
3892 }
3893
3894 ssize_t
3895 readlinkat (int fd, char const *name, char *buffer, size_t buffer_size)
3896 {
3897 /* Rely on a hack: an open directory is modeled as file descriptor 0,
3898 as in fstatat. FIXME: Add proper support for readlinkat. */
3899 char fullname[MAXPATHLEN];
3900
3901 if (fd != AT_FDCWD)
3902 {
3903 if (strlen (dir_pathname) + strlen (name) + 1 >= MAXPATHLEN)
3904 {
3905 errno = ENAMETOOLONG;
3906 return -1;
3907 }
3908 sprintf (fullname, "%s/%s", dir_pathname, name);
3909 name = fullname;
3910 }
3911
3912 return readlink (name, buffer, buffer_size);
3913 }
3914
3915 char *
3916 careadlinkat (int fd, char const *filename,
3917 char *buffer, size_t buffer_size,
3918 struct allocator const *alloc,
3919 ssize_t (*preadlinkat) (int, char const *, char *, size_t))
3920 {
3921 if (!buffer)
3922 {
3923 /* We don't support the fancy auto-allocation feature. */
3924 if (!buffer_size)
3925 errno = ENOSYS;
3926 else
3927 errno = EINVAL;
3928 buffer = NULL;
3929 }
3930 else
3931 {
3932 ssize_t len = preadlinkat (fd, filename, buffer, buffer_size);
3933
3934 if (len < 0 || len == buffer_size)
3935 buffer = NULL;
3936 else
3937 buffer[len + 1] = '\0';
3938 }
3939 return buffer;
3940 }
3941
3942 /* Emulate faccessat(2). */
3943 int
3944 faccessat (int dirfd, const char * path, int mode, int flags)
3945 {
3946 /* We silently ignore FLAGS. */
3947 flags = flags;
3948
3949 if (dirfd != AT_FDCWD
3950 && !(IS_DIRECTORY_SEP (path[0])
3951 || IS_DEVICE_SEP (path[1])))
3952 {
3953 errno = EBADF;
3954 return -1;
3955 }
3956
3957 return access (path, mode);
3958 }
3959
3960 /* Emulate fstatat. */
3961 int
3962 fstatat (int fd, char const *name, struct stat *st, int flags)
3963 {
3964 /* Rely on a hack: an open directory is modeled as file descriptor 0.
3965 This is good enough for the current usage in Emacs, but is fragile.
3966
3967 FIXME: Add proper support for fdopendir, fstatat, readlinkat.
3968 Gnulib does this and can serve as a model. */
3969 char fullname[MAXPATHLEN];
3970
3971 flags = flags;
3972
3973 if (fd != AT_FDCWD)
3974 {
3975 char lastc = dir_pathname[strlen (dir_pathname) - 1];
3976
3977 if (strlen (dir_pathname) + strlen (name) + IS_DIRECTORY_SEP (lastc)
3978 >= MAXPATHLEN)
3979 {
3980 errno = ENAMETOOLONG;
3981 return -1;
3982 }
3983
3984 sprintf (fullname, "%s%s%s",
3985 dir_pathname, IS_DIRECTORY_SEP (lastc) ? "" : "/", name);
3986 name = fullname;
3987 }
3988
3989 #if __DJGPP__ > 2 || __DJGPP_MINOR__ > 3
3990 return (flags & AT_SYMLINK_NOFOLLOW) ? lstat (name, st) : stat (name, st);
3991 #else
3992 return stat (name, st);
3993 #endif
3994 }
3995
3996 #if __DJGPP__ == 2 && __DJGPP_MINOR__ < 4
3997 /* Emulate the Posix unsetenv. DJGPP v2.04 has this in the library. */
3998 int
3999 unsetenv (const char *name)
4000 {
4001 char *var;
4002 size_t name_len;
4003 int retval;
4004
4005 if (name == NULL || *name == '\0' || strchr (name, '=') != NULL)
4006 {
4007 errno = EINVAL;
4008 return -1;
4009 }
4010
4011 /* DJGPP's 'putenv' deletes the entry if it doesn't include '='. */
4012 putenv (name);
4013
4014 return 0;
4015 }
4016 #endif
4017
4018 \f
4019 #if __DJGPP__ == 2 && __DJGPP_MINOR__ < 2
4020
4021 /* Augment DJGPP library POSIX signal functions. This is needed
4022 as of DJGPP v2.01, but might be in the library in later releases. */
4023
4024 #include <libc/bss.h>
4025
4026 /* A counter to know when to re-initialize the static sets. */
4027 static int sigprocmask_count = -1;
4028
4029 /* Which signals are currently blocked (initially none). */
4030 static sigset_t current_mask;
4031
4032 /* Which signals are pending (initially none). */
4033 static sigset_t msdos_pending_signals;
4034
4035 /* Previous handlers to restore when the blocked signals are unblocked. */
4036 typedef void (*sighandler_t)(int);
4037 static sighandler_t prev_handlers[320];
4038
4039 /* A signal handler which just records that a signal occurred
4040 (it will be raised later, if and when the signal is unblocked). */
4041 static void
4042 sig_suspender (int signo)
4043 {
4044 sigaddset (&msdos_pending_signals, signo);
4045 }
4046
4047 int
4048 sigprocmask (int how, const sigset_t *new_set, sigset_t *old_set)
4049 {
4050 int signo;
4051 sigset_t new_mask;
4052
4053 /* If called for the first time, initialize. */
4054 if (sigprocmask_count != __bss_count)
4055 {
4056 sigprocmask_count = __bss_count;
4057 sigemptyset (&msdos_pending_signals);
4058 sigemptyset (&current_mask);
4059 for (signo = 0; signo < 320; signo++)
4060 prev_handlers[signo] = SIG_ERR;
4061 }
4062
4063 if (old_set)
4064 *old_set = current_mask;
4065
4066 if (new_set == 0)
4067 return 0;
4068
4069 if (how != SIG_BLOCK && how != SIG_UNBLOCK && how != SIG_SETMASK)
4070 {
4071 errno = EINVAL;
4072 return -1;
4073 }
4074
4075 sigemptyset (&new_mask);
4076
4077 /* DJGPP supports upto 320 signals. */
4078 for (signo = 0; signo < 320; signo++)
4079 {
4080 if (sigismember (&current_mask, signo))
4081 sigaddset (&new_mask, signo);
4082 else if (sigismember (new_set, signo) && how != SIG_UNBLOCK)
4083 {
4084 sigaddset (&new_mask, signo);
4085
4086 /* SIGKILL is silently ignored, as on other platforms. */
4087 if (signo != SIGKILL && prev_handlers[signo] == SIG_ERR)
4088 prev_handlers[signo] = signal (signo, sig_suspender);
4089 }
4090 if (( how == SIG_UNBLOCK
4091 && sigismember (&new_mask, signo)
4092 && sigismember (new_set, signo))
4093 || (how == SIG_SETMASK
4094 && sigismember (&new_mask, signo)
4095 && !sigismember (new_set, signo)))
4096 {
4097 sigdelset (&new_mask, signo);
4098 if (prev_handlers[signo] != SIG_ERR)
4099 {
4100 signal (signo, prev_handlers[signo]);
4101 prev_handlers[signo] = SIG_ERR;
4102 }
4103 if (sigismember (&msdos_pending_signals, signo))
4104 {
4105 sigdelset (&msdos_pending_signals, signo);
4106 raise (signo);
4107 }
4108 }
4109 }
4110 current_mask = new_mask;
4111 return 0;
4112 }
4113
4114 #endif /* not __DJGPP_MINOR__ < 2 */
4115
4116 #ifndef HAVE_SELECT
4117 #include "sysselect.h"
4118
4119 /* This yields the rest of the current time slice to the task manager.
4120 It should be called by any code which knows that it has nothing
4121 useful to do except idle.
4122
4123 I don't use __dpmi_yield here, since versions of library before 2.02
4124 called Int 2Fh/AX=1680h there in a way that would wedge the DOS box
4125 on some versions of Windows 9X. */
4126
4127 void
4128 dos_yield_time_slice (void)
4129 {
4130 _go32_dpmi_registers r;
4131
4132 r.x.ax = 0x1680;
4133 r.x.ss = r.x.sp = r.x.flags = 0;
4134 _go32_dpmi_simulate_int (0x2f, &r);
4135 if (r.h.al == 0x80)
4136 errno = ENOSYS;
4137 }
4138
4139 /* Only event queue is checked. */
4140 /* We don't have to call timer_check here
4141 because wait_reading_process_output takes care of that. */
4142 int
4143 sys_select (int nfds, fd_set *rfds, fd_set *wfds, fd_set *efds,
4144 struct timespec *timeout, void *ignored)
4145 {
4146 int check_input;
4147 struct timespec t;
4148
4149 check_input = 0;
4150 if (rfds)
4151 {
4152 check_input = FD_ISSET (0, rfds);
4153 FD_ZERO (rfds);
4154 }
4155 if (wfds)
4156 FD_ZERO (wfds);
4157 if (efds)
4158 FD_ZERO (efds);
4159
4160 if (nfds != 1)
4161 emacs_abort ();
4162
4163 /* If we are looking only for the terminal, with no timeout,
4164 just read it and wait -- that's more efficient. */
4165 if (!timeout)
4166 {
4167 while (!detect_input_pending ())
4168 {
4169 dos_yield_time_slice ();
4170 }
4171 }
4172 else
4173 {
4174 struct timespec clnow, cllast, cldiff;
4175
4176 gettime (&t);
4177 cllast = make_timespec (t.tv_sec, t.tv_nsec);
4178
4179 while (!check_input || !detect_input_pending ())
4180 {
4181 gettime (&t);
4182 clnow = make_timespec (t.tv_sec, t.tv_nsec);
4183 cldiff = timespec_sub (clnow, cllast);
4184 *timeout = timespec_sub (*timeout, cldiff);
4185
4186 /* Stop when timeout value crosses zero. */
4187 if (timespec_sign (*timeout) <= 0)
4188 return 0;
4189 cllast = clnow;
4190 dos_yield_time_slice ();
4191 }
4192 }
4193
4194 FD_SET (0, rfds);
4195 return 1;
4196 }
4197 #endif
4198
4199 /*
4200 * Define overlaid functions:
4201 *
4202 * chdir -> sys_chdir
4203 * tzset -> init_gettimeofday
4204 * abort -> dos_abort
4205 */
4206
4207 #ifdef chdir
4208 #undef chdir
4209 extern int chdir (const char *);
4210
4211 int
4212 sys_chdir (const char *path)
4213 {
4214 int len = strlen (path);
4215 char *tmp = (char *)path;
4216
4217 if (*tmp && tmp[1] == ':')
4218 {
4219 if (getdisk () != tolower (tmp[0]) - 'a')
4220 setdisk (tolower (tmp[0]) - 'a');
4221 tmp += 2; /* strip drive: KFS 1995-07-06 */
4222 len -= 2;
4223 }
4224
4225 if (len > 1 && (tmp[len - 1] == '/'))
4226 {
4227 char *tmp1 = (char *) alloca (len + 1);
4228 strcpy (tmp1, tmp);
4229 tmp1[len - 1] = 0;
4230 tmp = tmp1;
4231 }
4232 return chdir (tmp);
4233 }
4234 #endif
4235
4236 #ifdef tzset
4237 #undef tzset
4238 extern void tzset (void);
4239
4240 void
4241 init_gettimeofday (void)
4242 {
4243 time_t ltm, gtm;
4244 struct tm *lstm;
4245
4246 tzset ();
4247 ltm = gtm = time (NULL);
4248 ltm = mktime (lstm = localtime (&ltm));
4249 gtm = mktime (gmtime (&gtm));
4250 time_rec.tm_hour = 99; /* force gettimeofday to get date */
4251 time_rec.tm_isdst = lstm->tm_isdst;
4252 dos_timezone_offset = time_rec.tm_gmtoff = (int)(gtm - ltm) / 60;
4253 }
4254 #endif
4255
4256 static void
4257 msdos_abort (void)
4258 {
4259 dos_ttcooked ();
4260 ScreenSetCursor (10, 0);
4261 cputs ("\r\n\nEmacs aborted!\r\n");
4262 #if __DJGPP__ == 2 && __DJGPP_MINOR__ < 2
4263 if (screen_virtual_segment)
4264 dosv_refresh_virtual_screen (2 * 10 * screen_size_X, 4 * screen_size_X);
4265 /* Generate traceback, so we could tell whodunit. */
4266 signal (SIGINT, SIG_DFL);
4267 __asm__ __volatile__ ("movb $0x1b,%al;call ___djgpp_hw_exception");
4268 #else /* __DJGPP_MINOR__ >= 2 */
4269 raise (SIGABRT);
4270 #endif /* __DJGPP_MINOR__ >= 2 */
4271 exit (2);
4272 }
4273
4274 void
4275 msdos_fatal_signal (int sig)
4276 {
4277 if (sig == SIGABRT)
4278 msdos_abort ();
4279 else
4280 raise (sig);
4281 }
4282
4283 void
4284 syms_of_msdos (void)
4285 {
4286 #include "msdos.x"
4287
4288 recent_doskeys = Fmake_vector (make_number (NUM_RECENT_DOSKEYS), Qnil);
4289 staticpro (&recent_doskeys);
4290
4291 #ifndef HAVE_X_WINDOWS
4292
4293 /* The following two are from xfns.c: */
4294 DEFSYM (Qreverse, "reverse");
4295
4296 DEFVAR_LISP ("dos-unsupported-char-glyph", Vdos_unsupported_char_glyph,
4297 doc: /* Glyph to display instead of chars not supported by current codepage.
4298 This variable is used only by MS-DOS terminals. */);
4299 Vdos_unsupported_char_glyph = make_number ('\177');
4300
4301 #endif
4302 }
4303
4304 #endif /* MSDOS */