blob: 1c6868985166d80843870bf2f86c158ae57b0ce6 [file] [log] [blame]
Bram Moolenaar071d4272004-06-13 20:20:40 +00001/* vi:set ts=8 sts=4 sw=4:
2 *
3 * VIM - Vi IMproved by Bram Moolenaar
4 *
5 * Do ":help uganda" in Vim to read copying and usage conditions.
6 * Do ":help credits" in Vim to see a list of people who contributed.
7 * See README.txt for an overview of the Vim source code.
8 */
9/*
10 * os_win32.c
11 *
12 * Used for both the console version and the Win32 GUI. A lot of code is for
13 * the console version only, so there is a lot of "#ifndef FEAT_GUI_W32".
14 *
15 * Win32 (Windows NT and Windows 95) system-dependent routines.
16 * Portions lifted from the Win32 SDK samples, the MSDOS-dependent code,
17 * NetHack 3.1.3, GNU Emacs 19.30, and Vile 5.5.
18 *
19 * George V. Reilly <george@reilly.org> wrote most of this.
20 * Roger Knobbe <rogerk@wonderware.com> did the initial port of Vim 3.0.
21 */
22
23#include <io.h>
24#include "vim.h"
25
Bram Moolenaar325b7a22004-07-05 15:58:32 +000026#ifdef FEAT_MZSCHEME
27# include "if_mzsch.h"
28#endif
29
Bram Moolenaar071d4272004-06-13 20:20:40 +000030#ifdef HAVE_FCNTL_H
31# include <fcntl.h>
32#endif
33#include <sys/types.h>
34#include <errno.h>
35#include <signal.h>
36#include <limits.h>
37#include <process.h>
38
39#undef chdir
40#ifdef __GNUC__
41# ifndef __MINGW32__
42# include <dirent.h>
43# endif
44#else
45# include <direct.h>
46#endif
47
48#if defined(FEAT_TITLE) && !defined(FEAT_GUI_W32)
49# include <shellapi.h>
50#endif
51
52#ifdef __MINGW32__
53# ifndef FROM_LEFT_1ST_BUTTON_PRESSED
54# define FROM_LEFT_1ST_BUTTON_PRESSED 0x0001
55# endif
56# ifndef RIGHTMOST_BUTTON_PRESSED
57# define RIGHTMOST_BUTTON_PRESSED 0x0002
58# endif
59# ifndef FROM_LEFT_2ND_BUTTON_PRESSED
60# define FROM_LEFT_2ND_BUTTON_PRESSED 0x0004
61# endif
62# ifndef FROM_LEFT_3RD_BUTTON_PRESSED
63# define FROM_LEFT_3RD_BUTTON_PRESSED 0x0008
64# endif
65# ifndef FROM_LEFT_4TH_BUTTON_PRESSED
66# define FROM_LEFT_4TH_BUTTON_PRESSED 0x0010
67# endif
68
69/*
70 * EventFlags
71 */
72# ifndef MOUSE_MOVED
73# define MOUSE_MOVED 0x0001
74# endif
75# ifndef DOUBLE_CLICK
76# define DOUBLE_CLICK 0x0002
77# endif
78#endif
79
80/* Record all output and all keyboard & mouse input */
81/* #define MCH_WRITE_DUMP */
82
83#ifdef MCH_WRITE_DUMP
84FILE* fdDump = NULL;
85#endif
86
87/*
88 * When generating prototypes for Win32 on Unix, these lines make the syntax
89 * errors disappear. They do not need to be correct.
90 */
91#ifdef PROTO
92#define WINAPI
93#define WINBASEAPI
94typedef char * LPCSTR;
95typedef int ACCESS_MASK;
96typedef int BOOL;
97typedef int COLORREF;
98typedef int CONSOLE_CURSOR_INFO;
99typedef int COORD;
100typedef int DWORD;
101typedef int HANDLE;
102typedef int HDC;
103typedef int HFONT;
104typedef int HICON;
105typedef int HINSTANCE;
106typedef int HWND;
107typedef int INPUT_RECORD;
108typedef int KEY_EVENT_RECORD;
109typedef int LOGFONT;
110typedef int LPBOOL;
111typedef int LPCTSTR;
112typedef int LPDWORD;
113typedef int LPSTR;
114typedef int LPTSTR;
115typedef int LPVOID;
116typedef int MOUSE_EVENT_RECORD;
117typedef int PACL;
118typedef int PDWORD;
119typedef int PHANDLE;
120typedef int PRINTDLG;
121typedef int PSECURITY_DESCRIPTOR;
122typedef int PSID;
123typedef int SECURITY_INFORMATION;
124typedef int SHORT;
125typedef int SMALL_RECT;
126typedef int TEXTMETRIC;
127typedef int TOKEN_INFORMATION_CLASS;
128typedef int TRUSTEE;
129typedef int WORD;
130typedef int WCHAR;
131typedef void VOID;
132#endif
133
134#ifndef FEAT_GUI_W32
135/* Undocumented API in kernel32.dll needed to work around dead key bug in
136 * console-mode applications in NT 4.0. If you switch keyboard layouts
137 * in a console app to a layout that includes dead keys and then hit a
138 * dead key, a call to ToAscii will trash the stack. My thanks to Ian James
139 * and Michael Dietrich for helping me figure out this workaround.
140 */
141
142/* WINBASEAPI BOOL WINAPI GetConsoleKeyboardLayoutNameA(LPSTR); */
143#ifndef WINBASEAPI
144# define WINBASEAPI __stdcall
145#endif
146#if defined(__BORLANDC__)
147typedef BOOL (__stdcall *PFNGCKLN)(LPSTR);
148#else
149typedef WINBASEAPI BOOL (WINAPI *PFNGCKLN)(LPSTR);
150#endif
151PFNGCKLN s_pfnGetConsoleKeyboardLayoutName = NULL;
152#endif
153
154#if defined(__BORLANDC__)
155/* Strangely Borland uses a non-standard name. */
156# define wcsicmp(a, b) wcscmpi((a), (b))
157#endif
158
159#ifndef FEAT_GUI_W32
160/* Win32 Console handles for input and output */
161static HANDLE g_hConIn = INVALID_HANDLE_VALUE;
162static HANDLE g_hConOut = INVALID_HANDLE_VALUE;
163
164/* Win32 Screen buffer,coordinate,console I/O information */
165static SMALL_RECT g_srScrollRegion;
166static COORD g_coord; /* 0-based, but external coords are 1-based */
167
168/* The attribute of the screen when the editor was started */
169static WORD g_attrDefault = 7; /* lightgray text on black background */
170static WORD g_attrCurrent;
171
172static int g_fCBrkPressed = FALSE; /* set by ctrl-break interrupt */
173static int g_fCtrlCPressed = FALSE; /* set when ctrl-C or ctrl-break detected */
174static int g_fForceExit = FALSE; /* set when forcefully exiting */
175
176static void termcap_mode_start(void);
177static void termcap_mode_end(void);
178static void clear_chars(COORD coord, DWORD n);
179static void clear_screen(void);
180static void clear_to_end_of_display(void);
181static void clear_to_end_of_line(void);
182static void scroll(unsigned cLines);
183static void set_scroll_region(unsigned left, unsigned top,
184 unsigned right, unsigned bottom);
185static void insert_lines(unsigned cLines);
186static void delete_lines(unsigned cLines);
187static void gotoxy(unsigned x, unsigned y);
188static void normvideo(void);
189static void textattr(WORD wAttr);
190static void textcolor(WORD wAttr);
191static void textbackground(WORD wAttr);
192static void standout(void);
193static void standend(void);
194static void visual_bell(void);
195static void cursor_visible(BOOL fVisible);
196static BOOL write_chars(LPCSTR pchBuf, DWORD cchToWrite);
197static char_u tgetch(int *pmodifiers, char_u *pch2);
198static void create_conin(void);
199static int s_cursor_visible = TRUE;
200static int did_create_conin = FALSE;
201#else
202static int s_dont_use_vimrun = TRUE;
203static int need_vimrun_warning = FALSE;
204static char *vimrun_path = "vimrun ";
205#endif
206
207#ifndef FEAT_GUI_W32
208static int suppress_winsize = 1; /* don't fiddle with console */
209#endif
210
211 static void
212get_exe_name(void)
213{
214 char temp[256];
215
216 if (exe_name == NULL)
217 {
218 /* store the name of the executable, may be used for $VIM */
219 GetModuleFileName(NULL, temp, 255);
220 if (*temp != NUL)
221 exe_name = FullName_save((char_u *)temp, FALSE);
222 }
223}
224
225#if defined(DYNAMIC_GETTEXT) || defined(PROTO)
226# ifndef GETTEXT_DLL
227# define GETTEXT_DLL "libintl.dll"
228# endif
229/* Dummy funcitons */
230static char* null_libintl_gettext(const char *);
231static char* null_libintl_textdomain(const char *);
232static char* null_libintl_bindtextdomain(const char *, const char *);
233
234static HINSTANCE hLibintlDLL = 0;
235char* (*dyn_libintl_gettext)(const char *) = null_libintl_gettext;
236char* (*dyn_libintl_textdomain)(const char *) = null_libintl_textdomain;
237char* (*dyn_libintl_bindtextdomain)(const char *, const char *)
238 = null_libintl_bindtextdomain;
239
240 int
241dyn_libintl_init(char *libname)
242{
243 int i;
244 static struct
245 {
246 char *name;
247 FARPROC *ptr;
248 } libintl_entry[] =
249 {
250 {"gettext", (FARPROC*)&dyn_libintl_gettext},
251 {"textdomain", (FARPROC*)&dyn_libintl_textdomain},
252 {"bindtextdomain", (FARPROC*)&dyn_libintl_bindtextdomain},
253 {NULL, NULL}
254 };
255
256 /* No need to initialize twice. */
257 if (hLibintlDLL)
258 return 1;
259 /* Load gettext library (libintl.dll) */
260 hLibintlDLL = LoadLibrary(libname != NULL ? libname : GETTEXT_DLL);
261 if (!hLibintlDLL)
262 {
263 char_u dirname[_MAX_PATH];
264
265 /* Try using the path from gvim.exe to find the .dll there. */
266 get_exe_name();
267 STRCPY(dirname, exe_name);
268 STRCPY(gettail(dirname), GETTEXT_DLL);
269 hLibintlDLL = LoadLibrary((char *)dirname);
270 if (!hLibintlDLL)
271 {
272 if (p_verbose > 0)
273 EMSG2(_(e_loadlib), GETTEXT_DLL);
274 return 0;
275 }
276 }
277 for (i = 0; libintl_entry[i].name != NULL
278 && libintl_entry[i].ptr != NULL; ++i)
279 {
280 if ((*libintl_entry[i].ptr = (FARPROC)GetProcAddress(hLibintlDLL,
281 libintl_entry[i].name)) == NULL)
282 {
283 dyn_libintl_end();
284 if (p_verbose > 0)
285 EMSG2(_(e_loadfunc), libintl_entry[i].name);
286 return 0;
287 }
288 }
289 return 1;
290}
291
292 void
293dyn_libintl_end()
294{
295 if (hLibintlDLL)
296 FreeLibrary(hLibintlDLL);
297 hLibintlDLL = NULL;
298 dyn_libintl_gettext = null_libintl_gettext;
299 dyn_libintl_textdomain = null_libintl_textdomain;
300 dyn_libintl_bindtextdomain = null_libintl_bindtextdomain;
301}
302
303 static char *
304null_libintl_gettext(const char* msgid)
305{
306 return (char*)msgid;
307}
308
309 static char *
310null_libintl_bindtextdomain(const char* domainname, const char* dirname)
311{
312 return NULL;
313}
314
315 static char *
316null_libintl_textdomain(const char* domainname)
317{
318 return NULL;
319}
320
321#endif /* DYNAMIC_GETTEXT */
322
323/* This symbol is not defined in older versions of the SDK or Visual C++ */
324
325#ifndef VER_PLATFORM_WIN32_WINDOWS
326# define VER_PLATFORM_WIN32_WINDOWS 1
327#endif
328
329DWORD g_PlatformId;
330
331#ifdef HAVE_ACL
332# include <aclapi.h>
333/*
334 * These are needed to dynamically load the ADVAPI DLL, which is not
335 * implemented under Windows 95 (and causes VIM to crash)
336 */
337typedef DWORD (WINAPI *PSNSECINFO) (LPTSTR, enum SE_OBJECT_TYPE,
338 SECURITY_INFORMATION, PSID, PSID, PACL, PACL);
339typedef DWORD (WINAPI *PGNSECINFO) (LPSTR, enum SE_OBJECT_TYPE,
340 SECURITY_INFORMATION, PSID *, PSID *, PACL *, PACL *,
341 PSECURITY_DESCRIPTOR *);
342
343static HANDLE advapi_lib = NULL; /* Handle for ADVAPI library */
344static PSNSECINFO pSetNamedSecurityInfo;
345static PGNSECINFO pGetNamedSecurityInfo;
346#endif
347
348/*
349 * Set g_PlatformId to VER_PLATFORM_WIN32_NT (NT) or
350 * VER_PLATFORM_WIN32_WINDOWS (Win95).
351 */
352 void
353PlatformId(void)
354{
355 static int done = FALSE;
356
357 if (!done)
358 {
359 OSVERSIONINFO ovi;
360
361 ovi.dwOSVersionInfoSize = sizeof(ovi);
362 GetVersionEx(&ovi);
363
364 g_PlatformId = ovi.dwPlatformId;
365
366#ifdef HAVE_ACL
367 /*
368 * Load the ADVAPI runtime if we are on anything
369 * other than Windows 95
370 */
371 if (g_PlatformId == VER_PLATFORM_WIN32_NT)
372 {
373 /*
374 * do this load. Problems: Doesn't unload at end of run (this is
375 * theoretically okay, since Windows should unload it when VIM
376 * terminates). Should we be using the 'mch_libcall' routines?
377 * Seems like a lot of overhead to load/unload ADVAPI32.DLL each
378 * time we verify security...
379 */
380 advapi_lib = LoadLibrary("ADVAPI32.DLL");
381 if (advapi_lib != NULL)
382 {
383 pSetNamedSecurityInfo = (PSNSECINFO)GetProcAddress(advapi_lib,
384 "SetNamedSecurityInfoA");
385 pGetNamedSecurityInfo = (PGNSECINFO)GetProcAddress(advapi_lib,
386 "GetNamedSecurityInfoA");
387 if (pSetNamedSecurityInfo == NULL
388 || pGetNamedSecurityInfo == NULL)
389 {
390 /* If we can't get the function addresses, set advapi_lib
391 * to NULL so that we don't use them. */
392 FreeLibrary(advapi_lib);
393 advapi_lib = NULL;
394 }
395 }
396 }
397#endif
398 done = TRUE;
399 }
400}
401
402/*
403 * Return TRUE when running on Windows 95 (or 98 or ME).
404 * Only to be used after mch_init().
405 */
406 int
407mch_windows95(void)
408{
409 return g_PlatformId == VER_PLATFORM_WIN32_WINDOWS;
410}
411
412#ifdef FEAT_GUI_W32
413/*
414 * Used to work around the "can't do synchronous spawn"
415 * problem on Win32s, without resorting to Universal Thunk.
416 */
417static int old_num_windows;
418static int num_windows;
419
420 static BOOL CALLBACK
421win32ssynch_cb(HWND hwnd, LPARAM lparam)
422{
423 num_windows++;
424 return TRUE;
425}
426#endif
427
428#ifndef FEAT_GUI_W32
429
430#define SHIFT (SHIFT_PRESSED)
431#define CTRL (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED)
432#define ALT (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED)
433#define ALT_GR (RIGHT_ALT_PRESSED | LEFT_CTRL_PRESSED)
434
435
436/* When uChar.AsciiChar is 0, then we need to look at wVirtualKeyCode.
437 * We map function keys to their ANSI terminal equivalents, as produced
438 * by ANSI.SYS, for compatibility with the MS-DOS version of Vim. Any
439 * ANSI key with a value >= '\300' is nonstandard, but provided anyway
440 * so that the user can have access to all SHIFT-, CTRL-, and ALT-
441 * combinations of function/arrow/etc keys.
442 */
443
444const static struct
445{
446 WORD wVirtKey;
447 BOOL fAnsiKey;
448 int chAlone;
449 int chShift;
450 int chCtrl;
451 int chAlt;
452} VirtKeyMap[] =
453{
454
455/* Key ANSI alone shift ctrl alt */
456 { VK_ESCAPE,FALSE, ESC, ESC, ESC, ESC, },
457
458 { VK_F1, TRUE, ';', 'T', '^', 'h', },
459 { VK_F2, TRUE, '<', 'U', '_', 'i', },
460 { VK_F3, TRUE, '=', 'V', '`', 'j', },
461 { VK_F4, TRUE, '>', 'W', 'a', 'k', },
462 { VK_F5, TRUE, '?', 'X', 'b', 'l', },
463 { VK_F6, TRUE, '@', 'Y', 'c', 'm', },
464 { VK_F7, TRUE, 'A', 'Z', 'd', 'n', },
465 { VK_F8, TRUE, 'B', '[', 'e', 'o', },
466 { VK_F9, TRUE, 'C', '\\', 'f', 'p', },
467 { VK_F10, TRUE, 'D', ']', 'g', 'q', },
468 { VK_F11, TRUE, '\205', '\207', '\211', '\213', },
469 { VK_F12, TRUE, '\206', '\210', '\212', '\214', },
470
471 { VK_HOME, TRUE, 'G', '\302', 'w', '\303', },
472 { VK_UP, TRUE, 'H', '\304', '\305', '\306', },
473 { VK_PRIOR, TRUE, 'I', '\307', '\204', '\310', }, /*PgUp*/
474 { VK_LEFT, TRUE, 'K', '\311', 's', '\312', },
475 { VK_RIGHT, TRUE, 'M', '\313', 't', '\314', },
476 { VK_END, TRUE, 'O', '\315', 'u', '\316', },
477 { VK_DOWN, TRUE, 'P', '\317', '\320', '\321', },
478 { VK_NEXT, TRUE, 'Q', '\322', 'v', '\323', }, /*PgDn*/
479 { VK_INSERT,TRUE, 'R', '\324', '\325', '\326', },
480 { VK_DELETE,TRUE, 'S', '\327', '\330', '\331', },
481
482 { VK_SNAPSHOT,TRUE, 0, 0, 0, 'r', }, /*PrtScrn*/
483
484#if 0
485 /* Most people don't have F13-F20, but what the hell... */
486 { VK_F13, TRUE, '\332', '\333', '\334', '\335', },
487 { VK_F14, TRUE, '\336', '\337', '\340', '\341', },
488 { VK_F15, TRUE, '\342', '\343', '\344', '\345', },
489 { VK_F16, TRUE, '\346', '\347', '\350', '\351', },
490 { VK_F17, TRUE, '\352', '\353', '\354', '\355', },
491 { VK_F18, TRUE, '\356', '\357', '\360', '\361', },
492 { VK_F19, TRUE, '\362', '\363', '\364', '\365', },
493 { VK_F20, TRUE, '\366', '\367', '\370', '\371', },
494#endif
495 { VK_ADD, TRUE, 'N', 'N', 'N', 'N', }, /* keyp '+' */
496 { VK_SUBTRACT, TRUE,'J', 'J', 'J', 'J', }, /* keyp '-' */
497 /* { VK_DIVIDE, TRUE,'N', 'N', 'N', 'N', }, keyp '/' */
498 { VK_MULTIPLY, TRUE,'7', '7', '7', '7', }, /* keyp '*' */
499
500 { VK_NUMPAD0,TRUE, '\332', '\333', '\334', '\335', },
501 { VK_NUMPAD1,TRUE, '\336', '\337', '\340', '\341', },
502 { VK_NUMPAD2,TRUE, '\342', '\343', '\344', '\345', },
503 { VK_NUMPAD3,TRUE, '\346', '\347', '\350', '\351', },
504 { VK_NUMPAD4,TRUE, '\352', '\353', '\354', '\355', },
505 { VK_NUMPAD5,TRUE, '\356', '\357', '\360', '\361', },
506 { VK_NUMPAD6,TRUE, '\362', '\363', '\364', '\365', },
507 { VK_NUMPAD7,TRUE, '\366', '\367', '\370', '\371', },
508 { VK_NUMPAD8,TRUE, '\372', '\373', '\374', '\375', },
509 /* Sorry, out of number space! <negri>*/
510 { VK_NUMPAD9,TRUE, '\376', '\377', '\377', '\367', },
511
512};
513
514
515#ifdef _MSC_VER
516// The ToAscii bug destroys several registers. Need to turn off optimization
517// or the GetConsoleKeyboardLayoutName hack will fail in non-debug versions
518# pragma optimize("", off)
519#endif
520
521#if defined(__GNUC__) && !defined(__MINGW32__) && !defined(__CYGWIN__)
522# define AChar AsciiChar
523#else
524# define AChar uChar.AsciiChar
525#endif
526
527/* The return code indicates key code size. */
528 static int
529#ifdef __BORLANDC__
530 __stdcall
531#endif
532win32_kbd_patch_key(
533 KEY_EVENT_RECORD* pker)
534{
535 UINT uMods = pker->dwControlKeyState;
536 static int s_iIsDead = 0;
537 static WORD awAnsiCode[2];
538 static BYTE abKeystate[256];
539
540
541 if (s_iIsDead == 2)
542 {
543 pker->AChar = (CHAR) awAnsiCode[1];
544 s_iIsDead = 0;
545 return 1;
546 }
547
548 if (pker->AChar != 0)
549 return 1;
550
551 memset(abKeystate, 0, sizeof (abKeystate));
552
553 // Should only be non-NULL on NT 4.0
554 if (s_pfnGetConsoleKeyboardLayoutName != NULL)
555 {
556 CHAR szKLID[KL_NAMELENGTH];
557
558 if ((*s_pfnGetConsoleKeyboardLayoutName)(szKLID))
559 (void)LoadKeyboardLayout(szKLID, KLF_ACTIVATE);
560 }
561
562 /* Clear any pending dead keys */
563 ToAscii(VK_SPACE, MapVirtualKey(VK_SPACE, 0), abKeystate, awAnsiCode, 0);
564
565 if (uMods & SHIFT_PRESSED)
566 abKeystate[VK_SHIFT] = 0x80;
567 if (uMods & CAPSLOCK_ON)
568 abKeystate[VK_CAPITAL] = 1;
569
570 if ((uMods & ALT_GR) == ALT_GR)
571 {
572 abKeystate[VK_CONTROL] = abKeystate[VK_LCONTROL] =
573 abKeystate[VK_MENU] = abKeystate[VK_RMENU] = 0x80;
574 }
575
576 s_iIsDead = ToAscii(pker->wVirtualKeyCode, pker->wVirtualScanCode,
577 abKeystate, awAnsiCode, 0);
578
579 if (s_iIsDead > 0)
580 pker->AChar = (CHAR) awAnsiCode[0];
581
582 return s_iIsDead;
583}
584
585#ifdef _MSC_VER
586/* MUST switch optimization on again here, otherwise a call to
587 * decode_key_event() may crash (e.g. when hitting caps-lock) */
588# pragma optimize("", on)
589
590# if (_MSC_VER < 1100)
591/* MUST turn off global optimisation for this next function, or
592 * pressing ctrl-minus in insert mode crashes Vim when built with
593 * VC4.1. -- negri. */
594# pragma optimize("g", off)
595# endif
596#endif
597
598static BOOL g_fJustGotFocus = FALSE;
599
600/*
601 * Decode a KEY_EVENT into one or two keystrokes
602 */
603 static BOOL
604decode_key_event(
605 KEY_EVENT_RECORD *pker,
606 char_u *pch,
607 char_u *pch2,
608 int *pmodifiers,
609 BOOL fDoPost)
610{
611 int i;
612 const int nModifs = pker->dwControlKeyState & (SHIFT | ALT | CTRL);
613
614 *pch = *pch2 = NUL;
615 g_fJustGotFocus = FALSE;
616
617 /* ignore key up events */
618 if (!pker->bKeyDown)
619 return FALSE;
620
621 /* ignore some keystrokes */
622 switch (pker->wVirtualKeyCode)
623 {
624 /* modifiers */
625 case VK_SHIFT:
626 case VK_CONTROL:
627 case VK_MENU: /* Alt key */
628 return FALSE;
629
630 default:
631 break;
632 }
633
634 /* special cases */
635 if ((nModifs & CTRL) != 0 && (nModifs & ~CTRL) == 0 && pker->AChar == NUL)
636 {
637 /* Ctrl-6 is Ctrl-^ */
638 if (pker->wVirtualKeyCode == '6')
639 {
640 *pch = Ctrl_HAT;
641 return TRUE;
642 }
643 /* Ctrl-2 is Ctrl-@ */
644 else if (pker->wVirtualKeyCode == '2')
645 {
646 *pch = NUL;
647 return TRUE;
648 }
649 /* Ctrl-- is Ctrl-_ */
650 else if (pker->wVirtualKeyCode == 0xBD)
651 {
652 *pch = Ctrl__;
653 return TRUE;
654 }
655 }
656
657 /* Shift-TAB */
658 if (pker->wVirtualKeyCode == VK_TAB && (nModifs & SHIFT_PRESSED))
659 {
660 *pch = K_NUL;
661 *pch2 = '\017';
662 return TRUE;
663 }
664
665 for (i = sizeof(VirtKeyMap) / sizeof(VirtKeyMap[0]); --i >= 0; )
666 {
667 if (VirtKeyMap[i].wVirtKey == pker->wVirtualKeyCode)
668 {
669 if (nModifs == 0)
670 *pch = VirtKeyMap[i].chAlone;
671 else if ((nModifs & SHIFT) != 0 && (nModifs & ~SHIFT) == 0)
672 *pch = VirtKeyMap[i].chShift;
673 else if ((nModifs & CTRL) != 0 && (nModifs & ~CTRL) == 0)
674 *pch = VirtKeyMap[i].chCtrl;
675 else if ((nModifs & ALT) != 0 && (nModifs & ~ALT) == 0)
676 *pch = VirtKeyMap[i].chAlt;
677
678 if (*pch != 0)
679 {
680 if (VirtKeyMap[i].fAnsiKey)
681 {
682 *pch2 = *pch;
683 *pch = K_NUL;
684 }
685
686 return TRUE;
687 }
688 }
689 }
690
691 i = win32_kbd_patch_key(pker);
692
693 if (i < 0)
694 *pch = NUL;
695 else
696 {
697 *pch = (i > 0) ? pker->AChar : NUL;
698
699 if (pmodifiers != NULL)
700 {
701 /* Pass on the ALT key as a modifier, but only when not combined
702 * with CTRL (which is ALTGR). */
703 if ((nModifs & ALT) != 0 && (nModifs & CTRL) == 0)
704 *pmodifiers |= MOD_MASK_ALT;
705
706 /* Pass on SHIFT only for special keys, because we don't know when
707 * it's already included with the character. */
708 if ((nModifs & SHIFT) != 0 && *pch <= 0x20)
709 *pmodifiers |= MOD_MASK_SHIFT;
710
711 /* Pass on CTRL only for non-special keys, because we don't know
712 * when it's already included with the character. And not when
713 * combined with ALT (which is ALTGR). */
714 if ((nModifs & CTRL) != 0 && (nModifs & ALT) == 0
715 && *pch >= 0x20 && *pch < 0x80)
716 *pmodifiers |= MOD_MASK_CTRL;
717 }
718 }
719
720 return (*pch != NUL);
721}
722
723#ifdef _MSC_VER
724# pragma optimize("", on)
725#endif
726
727#endif /* FEAT_GUI_W32 */
728
729
730#ifdef FEAT_MOUSE
731
732/*
733 * For the GUI the mouse handling is in gui_w32.c.
734 */
735# ifdef FEAT_GUI_W32
736 void
737mch_setmouse(
738 int on)
739{
740}
741# else
742static int g_fMouseAvail = FALSE; /* mouse present */
743static int g_fMouseActive = FALSE; /* mouse enabled */
744static int g_nMouseClick = -1; /* mouse status */
745static int g_xMouse; /* mouse x coordinate */
746static int g_yMouse; /* mouse y coordinate */
747
748/*
749 * Enable or disable mouse input
750 */
751 void
752mch_setmouse(
753 int on)
754{
755 DWORD cmodein;
756
757 if (!g_fMouseAvail)
758 return;
759
760 g_fMouseActive = on;
761 GetConsoleMode(g_hConIn, &cmodein);
762
763 if (g_fMouseActive)
764 cmodein |= ENABLE_MOUSE_INPUT;
765 else
766 cmodein &= ~ENABLE_MOUSE_INPUT;
767
768 SetConsoleMode(g_hConIn, cmodein);
769}
770
771
772/*
773 * Decode a MOUSE_EVENT. If it's a valid event, return MOUSE_LEFT,
774 * MOUSE_MIDDLE, or MOUSE_RIGHT for a click; MOUSE_DRAG for a mouse
775 * move with a button held down; and MOUSE_RELEASE after a MOUSE_DRAG
776 * or a MOUSE_LEFT, _MIDDLE, or _RIGHT. We encode the button type,
777 * the number of clicks, and the Shift/Ctrl/Alt modifiers in g_nMouseClick,
778 * and we return the mouse position in g_xMouse and g_yMouse.
779 *
780 * Every MOUSE_LEFT, _MIDDLE, or _RIGHT will be followed by zero or more
781 * MOUSE_DRAGs and one MOUSE_RELEASE. MOUSE_RELEASE will be followed only
782 * by MOUSE_LEFT, _MIDDLE, or _RIGHT.
783 *
784 * For multiple clicks, we send, say, MOUSE_LEFT/1 click, MOUSE_RELEASE,
785 * MOUSE_LEFT/2 clicks, MOUSE_RELEASE, MOUSE_LEFT/3 clicks, MOUSE_RELEASE, ....
786 *
787 * Windows will send us MOUSE_MOVED notifications whenever the mouse
788 * moves, even if it stays within the same character cell. We ignore
789 * all MOUSE_MOVED messages if the position hasn't really changed, and
790 * we ignore all MOUSE_MOVED messages where no button is held down (i.e.,
791 * we're only interested in MOUSE_DRAG).
792 *
793 * All of this is complicated by the code that fakes MOUSE_MIDDLE on
794 * 2-button mouses by pressing the left & right buttons simultaneously.
795 * In practice, it's almost impossible to click both at the same time,
796 * so we need to delay a little. Also, we tend not to get MOUSE_RELEASE
797 * in such cases, if the user is clicking quickly.
798 */
799 static BOOL
800decode_mouse_event(
801 MOUSE_EVENT_RECORD* pmer)
802{
803 static int s_nOldButton = -1;
804 static int s_nOldMouseClick = -1;
805 static int s_xOldMouse = -1;
806 static int s_yOldMouse = -1;
807 static linenr_T s_old_topline = 0;
808#ifdef FEAT_DIFF
809 static int s_old_topfill = 0;
810#endif
811 static int s_cClicks = 1;
812 static BOOL s_fReleased = TRUE;
813 static DWORD s_dwLastClickTime = 0;
814 static BOOL s_fNextIsMiddle = FALSE;
815
816 static DWORD cButtons = 0; /* number of buttons supported */
817
818 const DWORD LEFT = FROM_LEFT_1ST_BUTTON_PRESSED;
819 const DWORD MIDDLE = FROM_LEFT_2ND_BUTTON_PRESSED;
820 const DWORD RIGHT = RIGHTMOST_BUTTON_PRESSED;
821 const DWORD LEFT_RIGHT = LEFT | RIGHT;
822
823 int nButton;
824
825 if (cButtons == 0 && !GetNumberOfConsoleMouseButtons(&cButtons))
826 cButtons = 2;
827
828 if (!g_fMouseAvail || !g_fMouseActive)
829 {
830 g_nMouseClick = -1;
831 return FALSE;
832 }
833
834 /* get a spurious MOUSE_EVENT immediately after receiving focus; ignore */
835 if (g_fJustGotFocus)
836 {
837 g_fJustGotFocus = FALSE;
838 return FALSE;
839 }
840
841 /* unprocessed mouse click? */
842 if (g_nMouseClick != -1)
843 return TRUE;
844
845 nButton = -1;
846 g_xMouse = pmer->dwMousePosition.X;
847 g_yMouse = pmer->dwMousePosition.Y;
848
849 if (pmer->dwEventFlags == MOUSE_MOVED)
850 {
851 /* ignore MOUSE_MOVED events if (x, y) hasn't changed. (We get these
852 * events even when the mouse moves only within a char cell.) */
853 if (s_xOldMouse == g_xMouse && s_yOldMouse == g_yMouse)
854 return FALSE;
855 }
856
857 /* If no buttons are pressed... */
858 if ((pmer->dwButtonState & ((1 << cButtons) - 1)) == 0)
859 {
860 /* If the last thing returned was MOUSE_RELEASE, ignore this */
861 if (s_fReleased)
862 return FALSE;
863
864 nButton = MOUSE_RELEASE;
865 s_fReleased = TRUE;
866 }
867 else /* one or more buttons pressed */
868 {
869 /* on a 2-button mouse, hold down left and right buttons
870 * simultaneously to get MIDDLE. */
871
872 if (cButtons == 2 && s_nOldButton != MOUSE_DRAG)
873 {
874 DWORD dwLR = (pmer->dwButtonState & LEFT_RIGHT);
875
876 /* if either left or right button only is pressed, see if the
877 * the next mouse event has both of them pressed */
878 if (dwLR == LEFT || dwLR == RIGHT)
879 {
880 for (;;)
881 {
882 /* wait a short time for next input event */
883 if (WaitForSingleObject(g_hConIn, p_mouset / 3)
884 != WAIT_OBJECT_0)
885 break;
886 else
887 {
888 DWORD cRecords = 0;
889 INPUT_RECORD ir;
890 MOUSE_EVENT_RECORD* pmer2 = &ir.Event.MouseEvent;
891
892 PeekConsoleInput(g_hConIn, &ir, 1, &cRecords);
893
894 if (cRecords == 0 || ir.EventType != MOUSE_EVENT
895 || !(pmer2->dwButtonState & LEFT_RIGHT))
896 break;
897 else
898 {
899 if (pmer2->dwEventFlags != MOUSE_MOVED)
900 {
901 ReadConsoleInput(g_hConIn, &ir, 1, &cRecords);
902
903 return decode_mouse_event(pmer2);
904 }
905 else if (s_xOldMouse == pmer2->dwMousePosition.X &&
906 s_yOldMouse == pmer2->dwMousePosition.Y)
907 {
908 /* throw away spurious mouse move */
909 ReadConsoleInput(g_hConIn, &ir, 1, &cRecords);
910
911 /* are there any more mouse events in queue? */
912 PeekConsoleInput(g_hConIn, &ir, 1, &cRecords);
913
914 if (cRecords==0 || ir.EventType != MOUSE_EVENT)
915 break;
916 }
917 else
918 break;
919 }
920 }
921 }
922 }
923 }
924
925 if (s_fNextIsMiddle)
926 {
927 nButton = (pmer->dwEventFlags == MOUSE_MOVED)
928 ? MOUSE_DRAG : MOUSE_MIDDLE;
929 s_fNextIsMiddle = FALSE;
930 }
931 else if (cButtons == 2 &&
932 ((pmer->dwButtonState & LEFT_RIGHT) == LEFT_RIGHT))
933 {
934 nButton = MOUSE_MIDDLE;
935
936 if (! s_fReleased && pmer->dwEventFlags != MOUSE_MOVED)
937 {
938 s_fNextIsMiddle = TRUE;
939 nButton = MOUSE_RELEASE;
940 }
941 }
942 else if ((pmer->dwButtonState & LEFT) == LEFT)
943 nButton = MOUSE_LEFT;
944 else if ((pmer->dwButtonState & MIDDLE) == MIDDLE)
945 nButton = MOUSE_MIDDLE;
946 else if ((pmer->dwButtonState & RIGHT) == RIGHT)
947 nButton = MOUSE_RIGHT;
948
949 if (! s_fReleased && ! s_fNextIsMiddle
950 && nButton != s_nOldButton && s_nOldButton != MOUSE_DRAG)
951 return FALSE;
952
953 s_fReleased = s_fNextIsMiddle;
954 }
955
956 if (pmer->dwEventFlags == 0 || pmer->dwEventFlags == DOUBLE_CLICK)
957 {
958 /* button pressed or released, without mouse moving */
959 if (nButton != -1 && nButton != MOUSE_RELEASE)
960 {
961 DWORD dwCurrentTime = GetTickCount();
962
963 if (s_xOldMouse != g_xMouse
964 || s_yOldMouse != g_yMouse
965 || s_nOldButton != nButton
966 || s_old_topline != curwin->w_topline
967#ifdef FEAT_DIFF
968 || s_old_topfill != curwin->w_topfill
969#endif
970 || (int)(dwCurrentTime - s_dwLastClickTime) > p_mouset)
971 {
972 s_cClicks = 1;
973 }
974 else if (++s_cClicks > 4)
975 {
976 s_cClicks = 1;
977 }
978
979 s_dwLastClickTime = dwCurrentTime;
980 }
981 }
982 else if (pmer->dwEventFlags == MOUSE_MOVED)
983 {
984 if (nButton != -1 && nButton != MOUSE_RELEASE)
985 nButton = MOUSE_DRAG;
986
987 s_cClicks = 1;
988 }
989
990 if (nButton == -1)
991 return FALSE;
992
993 if (nButton != MOUSE_RELEASE)
994 s_nOldButton = nButton;
995
996 g_nMouseClick = nButton;
997
998 if (pmer->dwControlKeyState & SHIFT_PRESSED)
999 g_nMouseClick |= MOUSE_SHIFT;
1000 if (pmer->dwControlKeyState & (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED))
1001 g_nMouseClick |= MOUSE_CTRL;
1002 if (pmer->dwControlKeyState & (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED))
1003 g_nMouseClick |= MOUSE_ALT;
1004
1005 if (nButton != MOUSE_DRAG && nButton != MOUSE_RELEASE)
1006 SET_NUM_MOUSE_CLICKS(g_nMouseClick, s_cClicks);
1007
1008 /* only pass on interesting (i.e., different) mouse events */
1009 if (s_xOldMouse == g_xMouse
1010 && s_yOldMouse == g_yMouse
1011 && s_nOldMouseClick == g_nMouseClick)
1012 {
1013 g_nMouseClick = -1;
1014 return FALSE;
1015 }
1016
1017 s_xOldMouse = g_xMouse;
1018 s_yOldMouse = g_yMouse;
1019 s_old_topline = curwin->w_topline;
1020#ifdef FEAT_DIFF
1021 s_old_topfill = curwin->w_topfill;
1022#endif
1023 s_nOldMouseClick = g_nMouseClick;
1024
1025 return TRUE;
1026}
1027
1028# endif /* FEAT_GUI_W32 */
1029#endif /* FEAT_MOUSE */
1030
1031
1032#ifdef MCH_CURSOR_SHAPE
1033/*
1034 * Set the shape of the cursor.
1035 * 'thickness' can be from 1 (thin) to 99 (block)
1036 */
1037 static void
1038mch_set_cursor_shape(int thickness)
1039{
1040 CONSOLE_CURSOR_INFO ConsoleCursorInfo;
1041 ConsoleCursorInfo.dwSize = thickness;
1042 ConsoleCursorInfo.bVisible = s_cursor_visible;
1043
1044 SetConsoleCursorInfo(g_hConOut, &ConsoleCursorInfo);
1045 if (s_cursor_visible)
1046 SetConsoleCursorPosition(g_hConOut, g_coord);
1047}
1048
1049 void
1050mch_update_cursor(void)
1051{
1052 int idx;
1053 int thickness;
1054
1055 /*
1056 * How the cursor is drawn depends on the current mode.
1057 */
1058 idx = get_shape_idx(FALSE);
1059
1060 if (shape_table[idx].shape == SHAPE_BLOCK)
1061 thickness = 99; /* 100 doesn't work on W95 */
1062 else
1063 thickness = shape_table[idx].percentage;
1064 mch_set_cursor_shape(thickness);
1065}
1066#endif
1067
1068#ifndef FEAT_GUI_W32 /* this isn't used for the GUI */
1069/*
1070 * Handle FOCUS_EVENT.
1071 */
1072 static void
1073handle_focus_event(INPUT_RECORD ir)
1074{
1075 g_fJustGotFocus = ir.Event.FocusEvent.bSetFocus;
1076 ui_focus_change((int)g_fJustGotFocus);
1077}
1078
1079/*
1080 * Wait until console input from keyboard or mouse is available,
1081 * or the time is up.
1082 * Return TRUE if something is available FALSE if not.
1083 */
1084 static int
1085WaitForChar(long msec)
1086{
1087 DWORD dwNow = 0, dwEndTime = 0;
1088 INPUT_RECORD ir;
1089 DWORD cRecords;
1090 char_u ch, ch2;
1091
1092 if (msec > 0)
1093 /* Wait until the specified time has elapsed. */
1094 dwEndTime = GetTickCount() + msec;
1095 else if (msec < 0)
1096 /* Wait forever. */
1097 dwEndTime = INFINITE;
1098
1099 /* We need to loop until the end of the time period, because
1100 * we might get multiple unusable mouse events in that time.
1101 */
1102 for (;;)
1103 {
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001104#ifdef FEAT_MZSCHEME
1105 mzvim_check_threads();
1106#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001107#ifdef FEAT_CLIENTSERVER
1108 serverProcessPendingMessages();
1109#endif
1110 if (0
1111#ifdef FEAT_MOUSE
1112 || g_nMouseClick != -1
1113#endif
1114#ifdef FEAT_CLIENTSERVER
1115 || input_available()
1116#endif
1117 )
1118 return TRUE;
1119
1120 if (msec > 0)
1121 {
1122 /* If the specified wait time has passed, return. */
1123 dwNow = GetTickCount();
1124 if (dwNow >= dwEndTime)
1125 break;
1126 }
1127 if (msec != 0)
1128 {
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001129 DWORD dwWaitTime = dwEndTime - dwNow;
1130
1131#ifdef FEAT_MZSCHEME
1132 if (mzthreads_allowed() && p_mzq > 0
1133 && (msec < 0 || (long)dwWaitTime > p_mzq))
1134 dwWaitTime = p_mzq; /* don't wait longer than 'mzquantum' */
1135#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001136#ifdef FEAT_CLIENTSERVER
1137 /* Wait for either an event on the console input or a message in
1138 * the client-server window. */
1139 if (MsgWaitForMultipleObjects(1, &g_hConIn, FALSE,
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001140 dwWaitTime, QS_SENDMESSAGE) != WAIT_OBJECT_0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001141#else
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001142 if (WaitForSingleObject(g_hConIn, dwWaitTime) != WAIT_OBJECT_0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001143#endif
1144 continue;
1145 }
1146
1147 cRecords = 0;
1148 PeekConsoleInput(g_hConIn, &ir, 1, &cRecords);
1149
1150#ifdef FEAT_MBYTE_IME
1151 if (State & CMDLINE && msg_row == Rows - 1)
1152 {
1153 CONSOLE_SCREEN_BUFFER_INFO csbi;
1154
1155 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
1156 {
1157 if (csbi.dwCursorPosition.Y != msg_row)
1158 {
1159 /* The screen is now messed up, must redraw the
1160 * command line and later all the windows. */
1161 redraw_all_later(CLEAR);
1162 cmdline_row -= (msg_row - csbi.dwCursorPosition.Y);
1163 redrawcmd();
1164 }
1165 }
1166 }
1167#endif
1168
1169 if (cRecords > 0)
1170 {
1171 if (ir.EventType == KEY_EVENT && ir.Event.KeyEvent.bKeyDown)
1172 {
1173#ifdef FEAT_MBYTE_IME
1174 /* Windows IME sends two '\n's with only one 'ENTER'. First:
1175 * wVirtualKeyCode == 13. second: wVirtualKeyCode == 0 */
1176 if (ir.Event.KeyEvent.uChar.UnicodeChar == 0
1177 && ir.Event.KeyEvent.wVirtualKeyCode == 13)
1178 {
1179 ReadConsoleInput(g_hConIn, &ir, 1, &cRecords);
1180 continue;
1181 }
1182#endif
1183 if (decode_key_event(&ir.Event.KeyEvent, &ch, &ch2,
1184 NULL, FALSE))
1185 return TRUE;
1186 }
1187
1188 ReadConsoleInput(g_hConIn, &ir, 1, &cRecords);
1189
1190 if (ir.EventType == FOCUS_EVENT)
1191 handle_focus_event(ir);
1192 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
1193 shell_resized();
1194#ifdef FEAT_MOUSE
1195 else if (ir.EventType == MOUSE_EVENT
1196 && decode_mouse_event(&ir.Event.MouseEvent))
1197 return TRUE;
1198#endif
1199 }
1200 else if (msec == 0)
1201 break;
1202 }
1203
1204#ifdef FEAT_CLIENTSERVER
1205 /* Something might have been received while we were waiting. */
1206 if (input_available())
1207 return TRUE;
1208#endif
1209 return FALSE;
1210}
1211
1212#ifndef FEAT_GUI_MSWIN
1213/*
1214 * return non-zero if a character is available
1215 */
1216 int
1217mch_char_avail()
1218{
1219 return WaitForChar(0L);
1220}
1221#endif
1222
1223/*
1224 * Create the console input. Used when reading stdin doesn't work.
1225 */
1226 static void
1227create_conin(void)
1228{
1229 g_hConIn = CreateFile("CONIN$", GENERIC_READ|GENERIC_WRITE,
1230 FILE_SHARE_READ|FILE_SHARE_WRITE,
1231 (LPSECURITY_ATTRIBUTES) NULL,
1232 OPEN_EXISTING, (DWORD)NULL, (HANDLE)NULL);
1233 did_create_conin = TRUE;
1234}
1235
1236/*
1237 * Get a keystroke or a mouse event
1238 */
1239 static char_u
1240tgetch(int *pmodifiers, char_u *pch2)
1241{
1242 char_u ch;
1243
1244 for (;;)
1245 {
1246 INPUT_RECORD ir;
1247 DWORD cRecords = 0;
1248
1249#ifdef FEAT_CLIENTSERVER
1250 (void)WaitForChar(-1L);
1251 if (input_available())
1252 return 0;
1253# ifdef FEAT_MOUSE
1254 if (g_nMouseClick != -1)
1255 return 0;
1256# endif
1257#endif
1258 if (ReadConsoleInput(g_hConIn, &ir, 1, &cRecords) == 0)
1259 {
1260 if (did_create_conin)
1261 read_error_exit();
1262 create_conin();
1263 continue;
1264 }
1265
1266 if (ir.EventType == KEY_EVENT)
1267 {
1268 if (decode_key_event(&ir.Event.KeyEvent, &ch, pch2,
1269 pmodifiers, TRUE))
1270 return ch;
1271 }
1272 else if (ir.EventType == FOCUS_EVENT)
1273 handle_focus_event(ir);
1274 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
1275 shell_resized();
1276#ifdef FEAT_MOUSE
1277 else if (ir.EventType == MOUSE_EVENT)
1278 {
1279 if (decode_mouse_event(&ir.Event.MouseEvent))
1280 return 0;
1281 }
1282#endif
1283 }
1284}
1285#endif /* !FEAT_GUI_W32 */
1286
1287
1288/*
1289 * mch_inchar(): low-level input funcion.
1290 * Get one or more characters from the keyboard or the mouse.
1291 * If time == 0, do not wait for characters.
1292 * If time == n, wait a short time for characters.
1293 * If time == -1, wait forever for characters.
1294 * Returns the number of characters read into buf.
1295 */
1296 int
1297mch_inchar(
1298 char_u *buf,
1299 int maxlen,
1300 long time,
1301 int tb_change_cnt)
1302{
1303#ifndef FEAT_GUI_W32 /* this isn't used for the GUI */
1304
1305 int len;
1306 int c;
1307#ifdef FEAT_AUTOCMD
1308 static int once_already = 0;
1309#endif
1310#define TYPEAHEADLEN 20
1311 static char_u typeahead[TYPEAHEADLEN]; /* previously typed bytes. */
1312 static int typeaheadlen = 0;
1313
1314 /* First use any typeahead that was kept because "buf" was too small. */
1315 if (typeaheadlen > 0)
1316 goto theend;
1317
1318#ifdef FEAT_SNIFF
1319 if (want_sniff_request)
1320 {
1321 if (sniff_request_waiting)
1322 {
1323 /* return K_SNIFF */
1324 typeahead[typeaheadlen++] = CSI;
1325 typeahead[typeaheadlen++] = (char_u)KS_EXTRA;
1326 typeahead[typeaheadlen++] = (char_u)KE_SNIFF;
1327 sniff_request_waiting = 0;
1328 want_sniff_request = 0;
1329 goto theend;
1330 }
1331 else if (time < 0 || time > 250)
1332 {
1333 /* don't wait too long, a request might be pending */
1334 time = 250;
1335 }
1336 }
1337#endif
1338
1339 if (time >= 0)
1340 {
1341 if (!WaitForChar(time)) /* no character available */
1342 {
1343#ifdef FEAT_AUTOCMD
1344 once_already = 0;
1345#endif
1346 return 0;
1347 }
1348 }
1349 else /* time == -1, wait forever */
1350 {
1351 mch_set_winsize_now(); /* Allow winsize changes from now on */
1352
1353#ifdef FEAT_AUTOCMD
1354 /* If there is no character available within 2 seconds (default),
1355 * write the autoscript file to disk */
1356 if (once_already == 2)
1357 updatescript(0);
1358 else if (once_already == 1)
1359 {
1360 setcursor();
1361 once_already = 2;
1362 return 0;
1363 }
1364 else
1365#endif
1366 if (!WaitForChar(p_ut))
1367 {
1368#ifdef FEAT_AUTOCMD
1369 if (has_cursorhold() && get_real_state() == NORMAL_BUSY)
1370 {
1371 apply_autocmds(EVENT_CURSORHOLD, NULL, NULL, FALSE, curbuf);
1372 update_screen(VALID);
1373 once_already = 1;
1374 return 0;
1375 }
1376#endif
1377 updatescript(0);
1378 }
1379 }
1380
1381 /*
1382 * Try to read as many characters as there are, until the buffer is full.
1383 */
1384
1385 /* we will get at least one key. Get more if they are available. */
1386 g_fCBrkPressed = FALSE;
1387
1388#ifdef MCH_WRITE_DUMP
1389 if (fdDump)
1390 fputc('[', fdDump);
1391#endif
1392
1393 /* Keep looping until there is something in the typeahead buffer and more
1394 * to get and still room in the buffer (up to two bytes for a char and
1395 * three bytes for a modifier). */
1396 while ((typeaheadlen == 0 || WaitForChar(0L))
1397 && typeaheadlen + 5 <= TYPEAHEADLEN)
1398 {
1399 if (typebuf_changed(tb_change_cnt))
1400 {
1401 /* "buf" may be invalid now if a client put something in the
1402 * typeahead buffer and "buf" is in the typeahead buffer. */
1403 typeaheadlen = 0;
1404 break;
1405 }
1406#ifdef FEAT_MOUSE
1407 if (g_nMouseClick != -1)
1408 {
1409# ifdef MCH_WRITE_DUMP
1410 if (fdDump)
1411 fprintf(fdDump, "{%02x @ %d, %d}",
1412 g_nMouseClick, g_xMouse, g_yMouse);
1413# endif
1414 typeahead[typeaheadlen++] = ESC + 128;
1415 typeahead[typeaheadlen++] = 'M';
1416 typeahead[typeaheadlen++] = g_nMouseClick;
1417 typeahead[typeaheadlen++] = g_xMouse + '!';
1418 typeahead[typeaheadlen++] = g_yMouse + '!';
1419 g_nMouseClick = -1;
1420 }
1421 else
1422#endif
1423 {
1424 char_u ch2 = NUL;
1425 int modifiers = 0;
1426
1427 c = tgetch(&modifiers, &ch2);
1428
1429 if (typebuf_changed(tb_change_cnt))
1430 {
1431 /* "buf" may be invalid now if a client put something in the
1432 * typeahead buffer and "buf" is in the typeahead buffer. */
1433 typeaheadlen = 0;
1434 break;
1435 }
1436
1437 if (c == Ctrl_C && ctrl_c_interrupts)
1438 {
1439#if defined(FEAT_CLIENTSERVER)
1440 trash_input_buf();
1441#endif
1442 got_int = TRUE;
1443 }
1444
1445#ifdef FEAT_MOUSE
1446 if (g_nMouseClick == -1)
1447#endif
1448 {
1449 int n = 1;
1450
1451 /* A key may have one or two bytes. */
1452 typeahead[typeaheadlen] = c;
1453 if (ch2 != NUL)
1454 {
1455 typeahead[typeaheadlen + 1] = ch2;
1456 ++n;
1457 }
1458#ifdef FEAT_MBYTE
1459 /* Only convert normal characters, not special keys. Need to
1460 * convert before applying ALT, otherwise mapping <M-x> breaks
1461 * when 'tenc' is set. */
1462 if (input_conv.vc_type != CONV_NONE
1463 && (ch2 == NUL || c != K_NUL))
1464 n = convert_input(typeahead + typeaheadlen, n,
1465 TYPEAHEADLEN - typeaheadlen);
1466#endif
1467
1468 /* Use the ALT key to set the 8th bit of the character
1469 * when it's one byte, the 8th bit isn't set yet and not
1470 * using a double-byte encoding (would become a lead
1471 * byte). */
1472 if ((modifiers & MOD_MASK_ALT)
1473 && n == 1
1474 && (typeahead[typeaheadlen] & 0x80) == 0
1475#ifdef FEAT_MBYTE
1476 && !enc_dbcs
1477#endif
1478 )
1479 {
1480 typeahead[typeaheadlen] |= 0x80;
1481 modifiers &= ~MOD_MASK_ALT;
1482 }
1483
1484 if (modifiers != 0)
1485 {
1486 /* Prepend modifiers to the character. */
1487 mch_memmove(typeahead + typeaheadlen + 3,
1488 typeahead + typeaheadlen, n);
1489 typeahead[typeaheadlen++] = K_SPECIAL;
1490 typeahead[typeaheadlen++] = (char_u)KS_MODIFIER;
1491 typeahead[typeaheadlen++] = modifiers;
1492 }
1493
1494 typeaheadlen += n;
1495
1496#ifdef MCH_WRITE_DUMP
1497 if (fdDump)
1498 fputc(c, fdDump);
1499#endif
1500 }
1501 }
1502 }
1503
1504#ifdef MCH_WRITE_DUMP
1505 if (fdDump)
1506 {
1507 fputs("]\n", fdDump);
1508 fflush(fdDump);
1509 }
1510#endif
1511
1512#ifdef FEAT_AUTOCMD
1513 once_already = 0;
1514#endif
1515
1516theend:
1517 /* Move typeahead to "buf", as much as fits. */
1518 len = 0;
1519 while (len < maxlen && typeaheadlen > 0)
1520 {
1521 buf[len++] = typeahead[0];
1522 mch_memmove(typeahead, typeahead + 1, --typeaheadlen);
1523 }
1524 return len;
1525
1526#else /* FEAT_GUI_W32 */
1527 return 0;
1528#endif /* FEAT_GUI_W32 */
1529}
1530
1531#ifndef __MINGW32__
1532# include <shellapi.h> /* required for FindExecutable() */
1533#endif
1534
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001535/*
1536 * Return TRUE if "name" is in $PATH.
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00001537 * TODO: Should somehow check if it's really executable.
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001538 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001539 static int
1540executable_exists(char *name)
1541{
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001542 char *dum;
1543 char fname[_MAX_PATH];
Bram Moolenaar071d4272004-06-13 20:20:40 +00001544
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001545#ifdef FEAT_MBYTE
1546 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001547 {
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001548 WCHAR *p = enc_to_ucs2(name, NULL);
1549 WCHAR fnamew[_MAX_PATH];
1550 WCHAR *dumw;
1551 long n;
1552
1553 if (p != NULL)
1554 {
1555 n = (long)SearchPathW(NULL, p, NULL, _MAX_PATH, fnamew, &dumw);
1556 vim_free(p);
1557 if (n > 0 || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
1558 {
1559 if (n == 0)
1560 return FALSE;
1561 if (GetFileAttributesW(fnamew) & FILE_ATTRIBUTE_DIRECTORY)
1562 return FALSE;
1563 return TRUE;
1564 }
1565 /* Retry with non-wide function (for Windows 98). */
1566 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001567 }
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001568#endif
1569 if (SearchPath(NULL, name, NULL, _MAX_PATH, fname, &dum) == 0)
1570 return FALSE;
1571 if (mch_isdir(fname))
1572 return FALSE;
1573 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001574}
1575
1576#ifdef FEAT_GUI_W32
1577
1578/*
1579 * GUI version of mch_init().
1580 */
1581 void
1582mch_init()
1583{
1584#ifndef __MINGW32__
1585 extern int _fmode;
1586#endif
1587
1588 /* Let critical errors result in a failure, not in a dialog box. Required
1589 * for the timestamp test to work on removed floppies. */
1590 SetErrorMode(SEM_FAILCRITICALERRORS);
1591
1592 _fmode = O_BINARY; /* we do our own CR-LF translation */
1593
1594 /* Specify window size. Is there a place to get the default from? */
1595 Rows = 25;
1596 Columns = 80;
1597
1598 /* Look for 'vimrun' */
1599 if (!gui_is_win32s())
1600 {
1601 char_u vimrun_location[_MAX_PATH + 4];
1602
1603 /* First try in same directory as gvim.exe */
1604 STRCPY(vimrun_location, exe_name);
1605 STRCPY(gettail(vimrun_location), "vimrun.exe");
1606 if (mch_getperm(vimrun_location) >= 0)
1607 {
1608 if (*skiptowhite(vimrun_location) != NUL)
1609 {
1610 /* Enclose path with white space in double quotes. */
1611 mch_memmove(vimrun_location + 1, vimrun_location,
1612 STRLEN(vimrun_location) + 1);
1613 *vimrun_location = '"';
1614 STRCPY(gettail(vimrun_location), "vimrun\" ");
1615 }
1616 else
1617 STRCPY(gettail(vimrun_location), "vimrun ");
1618
1619 vimrun_path = (char *)vim_strsave(vimrun_location);
1620 s_dont_use_vimrun = FALSE;
1621 }
1622 else if (executable_exists("vimrun.exe"))
1623 s_dont_use_vimrun = FALSE;
1624
1625 /* Don't give the warning for a missing vimrun.exe right now, but only
1626 * when vimrun was supposed to be used. Don't bother people that do
1627 * not need vimrun.exe. */
1628 if (s_dont_use_vimrun)
1629 need_vimrun_warning = TRUE;
1630 }
1631
1632 /*
1633 * If "finstr.exe" doesn't exist, use "grep -n" for 'grepprg'.
1634 * Otherwise the default "findstr /n" is used.
1635 */
1636 if (!executable_exists("findstr.exe"))
1637 set_option_value((char_u *)"grepprg", 0, (char_u *)"grep -n", 0);
1638
1639#ifdef FEAT_CLIPBOARD
1640 clip_init(TRUE);
1641
1642 /*
1643 * Vim's own clipboard format recognises whether the text is char, line, or
1644 * rectangular block. Only useful for copying between two Vims.
1645 * "VimClipboard" was used for previous versions, using the first
1646 * character to specify MCHAR, MLINE or MBLOCK.
1647 */
1648 clip_star.format = RegisterClipboardFormat("VimClipboard2");
1649 clip_star.format_raw = RegisterClipboardFormat("VimRawBytes");
1650#endif
1651}
1652
1653
1654#else /* FEAT_GUI_W32 */
1655
1656#define SRWIDTH(sr) ((sr).Right - (sr).Left + 1)
1657#define SRHEIGHT(sr) ((sr).Bottom - (sr).Top + 1)
1658
1659/*
1660 * ClearConsoleBuffer()
1661 * Description:
1662 * Clears the entire contents of the console screen buffer, using the
1663 * specified attribute.
1664 * Returns:
1665 * TRUE on success
1666 */
1667 static BOOL
1668ClearConsoleBuffer(WORD wAttribute)
1669{
1670 CONSOLE_SCREEN_BUFFER_INFO csbi;
1671 COORD coord;
1672 DWORD NumCells, dummy;
1673
1674 if (!GetConsoleScreenBufferInfo(g_hConOut, &csbi))
1675 return FALSE;
1676
1677 NumCells = csbi.dwSize.X * csbi.dwSize.Y;
1678 coord.X = 0;
1679 coord.Y = 0;
1680 if (!FillConsoleOutputCharacter(g_hConOut, ' ', NumCells,
1681 coord, &dummy))
1682 {
1683 return FALSE;
1684 }
1685 if (!FillConsoleOutputAttribute(g_hConOut, wAttribute, NumCells,
1686 coord, &dummy))
1687 {
1688 return FALSE;
1689 }
1690
1691 return TRUE;
1692}
1693
1694/*
1695 * FitConsoleWindow()
1696 * Description:
1697 * Checks if the console window will fit within given buffer dimensions.
1698 * Also, if requested, will shrink the window to fit.
1699 * Returns:
1700 * TRUE on success
1701 */
1702 static BOOL
1703FitConsoleWindow(
1704 COORD dwBufferSize,
1705 BOOL WantAdjust)
1706{
1707 CONSOLE_SCREEN_BUFFER_INFO csbi;
1708 COORD dwWindowSize;
1709 BOOL NeedAdjust = FALSE;
1710
1711 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
1712 {
1713 /*
1714 * A buffer resize will fail if the current console window does
1715 * not lie completely within that buffer. To avoid this, we might
1716 * have to move and possibly shrink the window.
1717 */
1718 if (csbi.srWindow.Right >= dwBufferSize.X)
1719 {
1720 dwWindowSize.X = SRWIDTH(csbi.srWindow);
1721 if (dwWindowSize.X > dwBufferSize.X)
1722 dwWindowSize.X = dwBufferSize.X;
1723 csbi.srWindow.Right = dwBufferSize.X - 1;
1724 csbi.srWindow.Left = dwBufferSize.X - dwWindowSize.X;
1725 NeedAdjust = TRUE;
1726 }
1727 if (csbi.srWindow.Bottom >= dwBufferSize.Y)
1728 {
1729 dwWindowSize.Y = SRHEIGHT(csbi.srWindow);
1730 if (dwWindowSize.Y > dwBufferSize.Y)
1731 dwWindowSize.Y = dwBufferSize.Y;
1732 csbi.srWindow.Bottom = dwBufferSize.Y - 1;
1733 csbi.srWindow.Top = dwBufferSize.Y - dwWindowSize.Y;
1734 NeedAdjust = TRUE;
1735 }
1736 if (NeedAdjust && WantAdjust)
1737 {
1738 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &csbi.srWindow))
1739 return FALSE;
1740 }
1741 return TRUE;
1742 }
1743
1744 return FALSE;
1745}
1746
1747typedef struct ConsoleBufferStruct
1748{
1749 BOOL IsValid;
1750 CONSOLE_SCREEN_BUFFER_INFO Info;
1751 PCHAR_INFO Buffer;
1752 COORD BufferSize;
1753} ConsoleBuffer;
1754
1755/*
1756 * SaveConsoleBuffer()
1757 * Description:
1758 * Saves important information about the console buffer, including the
1759 * actual buffer contents. The saved information is suitable for later
1760 * restoration by RestoreConsoleBuffer().
1761 * Returns:
1762 * TRUE if all information was saved; FALSE otherwise
1763 * If FALSE, still sets cb->IsValid if buffer characteristics were saved.
1764 */
1765 static BOOL
1766SaveConsoleBuffer(
1767 ConsoleBuffer *cb)
1768{
1769 DWORD NumCells;
1770 COORD BufferCoord;
1771 SMALL_RECT ReadRegion;
1772 WORD Y, Y_incr;
1773
1774 if (cb == NULL)
1775 return FALSE;
1776
1777 if (!GetConsoleScreenBufferInfo(g_hConOut, &cb->Info))
1778 {
1779 cb->IsValid = FALSE;
1780 return FALSE;
1781 }
1782 cb->IsValid = TRUE;
1783
1784 /*
1785 * Allocate a buffer large enough to hold the entire console screen
1786 * buffer. If this ConsoleBuffer structure has already been initialized
1787 * with a buffer of the correct size, then just use that one.
1788 */
1789 if (!cb->IsValid || cb->Buffer == NULL ||
1790 cb->BufferSize.X != cb->Info.dwSize.X ||
1791 cb->BufferSize.Y != cb->Info.dwSize.Y)
1792 {
1793 cb->BufferSize.X = cb->Info.dwSize.X;
1794 cb->BufferSize.Y = cb->Info.dwSize.Y;
1795 NumCells = cb->BufferSize.X * cb->BufferSize.Y;
1796 if (cb->Buffer != NULL)
1797 vim_free(cb->Buffer);
1798 cb->Buffer = (PCHAR_INFO)alloc(NumCells * sizeof(CHAR_INFO));
1799 if (cb->Buffer == NULL)
1800 return FALSE;
1801 }
1802
1803 /*
1804 * We will now copy the console screen buffer into our buffer.
1805 * ReadConsoleOutput() seems to be limited as far as how much you
1806 * can read at a time. Empirically, this number seems to be about
1807 * 12000 cells (rows * columns). Start at position (0, 0) and copy
1808 * in chunks until it is all copied. The chunks will all have the
1809 * same horizontal characteristics, so initialize them now. The
1810 * height of each chunk will be (12000 / width).
1811 */
1812 BufferCoord.X = 0;
1813 ReadRegion.Left = 0;
1814 ReadRegion.Right = cb->Info.dwSize.X - 1;
1815 Y_incr = 12000 / cb->Info.dwSize.X;
1816 for (Y = 0; Y < cb->BufferSize.Y; Y += Y_incr)
1817 {
1818 /*
1819 * Read into position (0, Y) in our buffer.
1820 */
1821 BufferCoord.Y = Y;
1822 /*
1823 * Read the region whose top left corner is (0, Y) and whose bottom
1824 * right corner is (width - 1, Y + Y_incr - 1). This should define
1825 * a region of size width by Y_incr. Don't worry if this region is
1826 * too large for the remaining buffer; it will be cropped.
1827 */
1828 ReadRegion.Top = Y;
1829 ReadRegion.Bottom = Y + Y_incr - 1;
1830 if (!ReadConsoleOutput(g_hConOut, /* output handle */
1831 cb->Buffer, /* our buffer */
1832 cb->BufferSize, /* dimensions of our buffer */
1833 BufferCoord, /* offset in our buffer */
1834 &ReadRegion)) /* region to save */
1835 {
1836 vim_free(cb->Buffer);
1837 cb->Buffer = NULL;
1838 return FALSE;
1839 }
1840 }
1841
1842 return TRUE;
1843}
1844
1845/*
1846 * RestoreConsoleBuffer()
1847 * Description:
1848 * Restores important information about the console buffer, including the
1849 * actual buffer contents, if desired. The information to restore is in
1850 * the same format used by SaveConsoleBuffer().
1851 * Returns:
1852 * TRUE on success
1853 */
1854 static BOOL
1855RestoreConsoleBuffer(
1856 ConsoleBuffer *cb,
1857 BOOL RestoreScreen)
1858{
1859 COORD BufferCoord;
1860 SMALL_RECT WriteRegion;
1861
1862 if (cb == NULL || !cb->IsValid)
1863 return FALSE;
1864
1865 /*
1866 * Before restoring the buffer contents, clear the current buffer, and
1867 * restore the cursor position and window information. Doing this now
1868 * prevents old buffer contents from "flashing" onto the screen.
1869 */
1870 if (RestoreScreen)
1871 ClearConsoleBuffer(cb->Info.wAttributes);
1872
1873 FitConsoleWindow(cb->Info.dwSize, TRUE);
1874 if (!SetConsoleScreenBufferSize(g_hConOut, cb->Info.dwSize))
1875 return FALSE;
1876 if (!SetConsoleTextAttribute(g_hConOut, cb->Info.wAttributes))
1877 return FALSE;
1878
1879 if (!RestoreScreen)
1880 {
1881 /*
1882 * No need to restore the screen buffer contents, so we're done.
1883 */
1884 return TRUE;
1885 }
1886
1887 if (!SetConsoleCursorPosition(g_hConOut, cb->Info.dwCursorPosition))
1888 return FALSE;
1889 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &cb->Info.srWindow))
1890 return FALSE;
1891
1892 /*
1893 * Restore the screen buffer contents.
1894 */
1895 if (cb->Buffer != NULL)
1896 {
1897 BufferCoord.X = 0;
1898 BufferCoord.Y = 0;
1899 WriteRegion.Left = 0;
1900 WriteRegion.Top = 0;
1901 WriteRegion.Right = cb->Info.dwSize.X - 1;
1902 WriteRegion.Bottom = cb->Info.dwSize.Y - 1;
1903 if (!WriteConsoleOutput(g_hConOut, /* output handle */
1904 cb->Buffer, /* our buffer */
1905 cb->BufferSize, /* dimensions of our buffer */
1906 BufferCoord, /* offset in our buffer */
1907 &WriteRegion)) /* region to restore */
1908 {
1909 return FALSE;
1910 }
1911 }
1912
1913 return TRUE;
1914}
1915
1916#ifdef FEAT_RESTORE_ORIG_SCREEN
1917static ConsoleBuffer g_cbOrig = { 0 };
1918#endif
1919static ConsoleBuffer g_cbNonTermcap = { 0 };
1920static ConsoleBuffer g_cbTermcap = { 0 };
1921
1922#ifdef FEAT_TITLE
1923#ifdef __BORLANDC__
1924typedef HWND (__stdcall *GETCONSOLEWINDOWPROC)(VOID);
1925#else
1926typedef WINBASEAPI HWND (WINAPI *GETCONSOLEWINDOWPROC)(VOID);
1927#endif
1928char g_szOrigTitle[256] = { 0 };
1929HWND g_hWnd = NULL; /* also used in os_mswin.c */
1930static HICON g_hOrigIconSmall = NULL;
1931static HICON g_hOrigIcon = NULL;
1932static HICON g_hVimIcon = NULL;
1933static BOOL g_fCanChangeIcon = FALSE;
1934
1935/* ICON* are not defined in VC++ 4.0 */
1936#ifndef ICON_SMALL
1937#define ICON_SMALL 0
1938#endif
1939#ifndef ICON_BIG
1940#define ICON_BIG 1
1941#endif
1942/*
1943 * GetConsoleIcon()
1944 * Description:
1945 * Attempts to retrieve the small icon and/or the big icon currently in
1946 * use by a given window.
1947 * Returns:
1948 * TRUE on success
1949 */
1950 static BOOL
1951GetConsoleIcon(
1952 HWND hWnd,
1953 HICON *phIconSmall,
1954 HICON *phIcon)
1955{
1956 if (hWnd == NULL)
1957 return FALSE;
1958
1959 if (phIconSmall != NULL)
1960 {
1961 *phIconSmall = (HICON) SendMessage(hWnd, WM_GETICON,
1962 (WPARAM) ICON_SMALL, (LPARAM) 0);
1963 }
1964 if (phIcon != NULL)
1965 {
1966 *phIcon = (HICON) SendMessage(hWnd, WM_GETICON,
1967 (WPARAM) ICON_BIG, (LPARAM) 0);
1968 }
1969 return TRUE;
1970}
1971
1972/*
1973 * SetConsoleIcon()
1974 * Description:
1975 * Attempts to change the small icon and/or the big icon currently in
1976 * use by a given window.
1977 * Returns:
1978 * TRUE on success
1979 */
1980 static BOOL
1981SetConsoleIcon(
1982 HWND hWnd,
1983 HICON hIconSmall,
1984 HICON hIcon)
1985{
1986 HICON hPrevIconSmall;
1987 HICON hPrevIcon;
1988
1989 if (hWnd == NULL)
1990 return FALSE;
1991
1992 if (hIconSmall != NULL)
1993 {
1994 hPrevIconSmall = (HICON) SendMessage(hWnd, WM_SETICON,
1995 (WPARAM) ICON_SMALL, (LPARAM) hIconSmall);
1996 }
1997 if (hIcon != NULL)
1998 {
1999 hPrevIcon = (HICON) SendMessage(hWnd, WM_SETICON,
2000 (WPARAM) ICON_BIG, (LPARAM) hIcon);
2001 }
2002 return TRUE;
2003}
2004
2005/*
2006 * SaveConsoleTitleAndIcon()
2007 * Description:
2008 * Saves the current console window title in g_szOrigTitle, for later
2009 * restoration. Also, attempts to obtain a handle to the console window,
2010 * and use it to save the small and big icons currently in use by the
2011 * console window. This is not always possible on some versions of Windows;
2012 * nor is it possible when running Vim remotely using Telnet (since the
2013 * console window the user sees is owned by a remote process).
2014 */
2015 static void
2016SaveConsoleTitleAndIcon(void)
2017{
2018 GETCONSOLEWINDOWPROC GetConsoleWindowProc;
2019
2020 /* Save the original title. */
2021 if (!GetConsoleTitle(g_szOrigTitle, sizeof(g_szOrigTitle)))
2022 return;
2023
2024 /*
2025 * Obtain a handle to the console window using GetConsoleWindow() from
2026 * KERNEL32.DLL; we need to handle in order to change the window icon.
2027 * This function only exists on NT-based Windows, starting with Windows
2028 * 2000. On older operating systems, we can't change the window icon
2029 * anyway.
2030 */
2031 if ((GetConsoleWindowProc = (GETCONSOLEWINDOWPROC)
2032 GetProcAddress(GetModuleHandle("KERNEL32.DLL"),
2033 "GetConsoleWindow")) != NULL)
2034 {
2035 g_hWnd = (*GetConsoleWindowProc)();
2036 }
2037 if (g_hWnd == NULL)
2038 return;
2039
2040 /* Save the original console window icon. */
2041 GetConsoleIcon(g_hWnd, &g_hOrigIconSmall, &g_hOrigIcon);
2042 if (g_hOrigIconSmall == NULL || g_hOrigIcon == NULL)
2043 return;
2044
2045 /* Extract the first icon contained in the Vim executable. */
2046 g_hVimIcon = ExtractIcon(NULL, exe_name, 0);
2047 if (g_hVimIcon != NULL)
2048 g_fCanChangeIcon = TRUE;
2049}
2050#endif
2051
2052static int g_fWindInitCalled = FALSE;
2053static int g_fTermcapMode = FALSE;
2054static CONSOLE_CURSOR_INFO g_cci;
2055static DWORD g_cmodein = 0;
2056static DWORD g_cmodeout = 0;
2057
2058/*
2059 * non-GUI version of mch_init().
2060 */
2061 void
2062mch_init()
2063{
2064#ifndef FEAT_RESTORE_ORIG_SCREEN
2065 CONSOLE_SCREEN_BUFFER_INFO csbi;
2066#endif
2067#ifndef __MINGW32__
2068 extern int _fmode;
2069#endif
2070
2071 /* Let critical errors result in a failure, not in a dialog box. Required
2072 * for the timestamp test to work on removed floppies. */
2073 SetErrorMode(SEM_FAILCRITICALERRORS);
2074
2075 _fmode = O_BINARY; /* we do our own CR-LF translation */
2076 out_flush();
2077
2078 /* Obtain handles for the standard Console I/O devices */
2079 if (read_cmd_fd == 0)
2080 g_hConIn = GetStdHandle(STD_INPUT_HANDLE);
2081 else
2082 create_conin();
2083 g_hConOut = GetStdHandle(STD_OUTPUT_HANDLE);
2084
2085#ifdef FEAT_RESTORE_ORIG_SCREEN
2086 /* Save the initial console buffer for later restoration */
2087 SaveConsoleBuffer(&g_cbOrig);
2088 g_attrCurrent = g_attrDefault = g_cbOrig.Info.wAttributes;
2089#else
2090 /* Get current text attributes */
2091 GetConsoleScreenBufferInfo(g_hConOut, &csbi);
2092 g_attrCurrent = g_attrDefault = csbi.wAttributes;
2093#endif
2094 if (cterm_normal_fg_color == 0)
2095 cterm_normal_fg_color = (g_attrCurrent & 0xf) + 1;
2096 if (cterm_normal_bg_color == 0)
2097 cterm_normal_bg_color = ((g_attrCurrent >> 4) & 0xf) + 1;
2098
2099 /* set termcap codes to current text attributes */
2100 update_tcap(g_attrCurrent);
2101
2102 GetConsoleCursorInfo(g_hConOut, &g_cci);
2103 GetConsoleMode(g_hConIn, &g_cmodein);
2104 GetConsoleMode(g_hConOut, &g_cmodeout);
2105
2106#ifdef FEAT_TITLE
2107 SaveConsoleTitleAndIcon();
2108 /*
2109 * Set both the small and big icons of the console window to Vim's icon.
2110 * Note that Vim presently only has one size of icon (32x32), but it
2111 * automatically gets scaled down to 16x16 when setting the small icon.
2112 */
2113 if (g_fCanChangeIcon)
2114 SetConsoleIcon(g_hWnd, g_hVimIcon, g_hVimIcon);
2115#endif
2116
2117 ui_get_shellsize();
2118
2119#ifdef MCH_WRITE_DUMP
2120 fdDump = fopen("dump", "wt");
2121
2122 if (fdDump)
2123 {
2124 time_t t;
2125
2126 time(&t);
2127 fputs(ctime(&t), fdDump);
2128 fflush(fdDump);
2129 }
2130#endif
2131
2132 g_fWindInitCalled = TRUE;
2133
2134#ifdef FEAT_MOUSE
2135 g_fMouseAvail = GetSystemMetrics(SM_MOUSEPRESENT);
2136#endif
2137
2138#ifdef FEAT_CLIPBOARD
2139 clip_init(TRUE);
2140
2141 /*
2142 * Vim's own clipboard format recognises whether the text is char, line, or
2143 * rectangular block. Only useful for copying between two Vims.
2144 * "VimClipboard" was used for previous versions, using the first
2145 * character to specify MCHAR, MLINE or MBLOCK.
2146 */
2147 clip_star.format = RegisterClipboardFormat("VimClipboard2");
2148 clip_star.format_raw = RegisterClipboardFormat("VimRawBytes");
2149#endif
2150
2151 /* This will be NULL on anything but NT 4.0 */
2152 s_pfnGetConsoleKeyboardLayoutName =
2153 (PFNGCKLN) GetProcAddress(GetModuleHandle("kernel32.dll"),
2154 "GetConsoleKeyboardLayoutNameA");
2155}
2156
2157/*
2158 * non-GUI version of mch_exit().
2159 * Shut down and exit with status `r'
2160 * Careful: mch_exit() may be called before mch_init()!
2161 */
2162 void
2163mch_exit(int r)
2164{
2165 stoptermcap();
2166
2167 if (g_fWindInitCalled)
2168 settmode(TMODE_COOK);
2169
2170 ml_close_all(TRUE); /* remove all memfiles */
2171
2172 if (g_fWindInitCalled)
2173 {
2174#ifdef FEAT_TITLE
2175 mch_restore_title(3);
2176 /*
2177 * Restore both the small and big icons of the console window to
2178 * what they were at startup. Don't do this when the window is
2179 * closed, Vim would hang here.
2180 */
2181 if (g_fCanChangeIcon && !g_fForceExit)
2182 SetConsoleIcon(g_hWnd, g_hOrigIconSmall, g_hOrigIcon);
2183#endif
2184
2185#ifdef MCH_WRITE_DUMP
2186 if (fdDump)
2187 {
2188 time_t t;
2189
2190 time(&t);
2191 fputs(ctime(&t), fdDump);
2192 fclose(fdDump);
2193 }
2194 fdDump = NULL;
2195#endif
2196 }
2197
2198 SetConsoleCursorInfo(g_hConOut, &g_cci);
2199 SetConsoleMode(g_hConIn, g_cmodein);
2200 SetConsoleMode(g_hConOut, g_cmodeout);
2201
2202#ifdef DYNAMIC_GETTEXT
2203 dyn_libintl_end();
2204#endif
2205
2206 exit(r);
2207}
2208#endif /* !FEAT_GUI_W32 */
2209
2210
2211/*
2212 * Do we have an interactive window?
2213 */
2214 int
2215mch_check_win(
2216 int argc,
2217 char **argv)
2218{
2219 get_exe_name();
2220
2221#ifdef FEAT_GUI_W32
2222 return OK; /* GUI always has a tty */
2223#else
2224 if (isatty(1))
2225 return OK;
2226 return FAIL;
2227#endif
2228}
2229
2230
2231/*
2232 * fname_case(): Set the case of the file name, if it already exists.
2233 * When "len" is > 0, also expand short to long filenames.
2234 */
2235 void
2236fname_case(
2237 char_u *name,
2238 int len)
2239{
2240 char szTrueName[_MAX_PATH + 2];
2241 char *ptrue, *ptruePrev;
2242 char *porig, *porigPrev;
2243 int flen;
2244 WIN32_FIND_DATA fb;
2245 HANDLE hFind;
2246 int c;
2247
2248 flen = (name != NULL) ? (int)STRLEN(name) : 0;
2249 if (flen == 0 || flen > _MAX_PATH)
2250 return;
2251
2252 slash_adjust(name);
2253
2254 /* Build the new name in szTrueName[] one component at a time. */
2255 porig = name;
2256 ptrue = szTrueName;
2257
2258 if (isalpha(porig[0]) && porig[1] == ':')
2259 {
2260 /* copy leading drive letter */
2261 *ptrue++ = *porig++;
2262 *ptrue++ = *porig++;
2263 *ptrue = NUL; /* in case nothing follows */
2264 }
2265
2266 while (*porig != NUL)
2267 {
2268 /* copy \ characters */
2269 while (*porig == psepc)
2270 *ptrue++ = *porig++;
2271
2272 ptruePrev = ptrue;
2273 porigPrev = porig;
2274 while (*porig != NUL && *porig != psepc)
2275 {
2276#ifdef FEAT_MBYTE
2277 int l;
2278
2279 if (enc_dbcs)
2280 {
2281 l = (*mb_ptr2len_check)(porig);
2282 while (--l >= 0)
2283 *ptrue++ = *porig++;
2284 }
2285 else
2286#endif
2287 *ptrue++ = *porig++;
2288 }
2289 *ptrue = NUL;
2290
2291 /* Skip "", "." and "..". */
2292 if (ptrue > ptruePrev
2293 && (ptruePrev[0] != '.'
2294 || (ptruePrev[1] != NUL
2295 && (ptruePrev[1] != '.' || ptruePrev[2] != NUL)))
2296 && (hFind = FindFirstFile(szTrueName, &fb))
2297 != INVALID_HANDLE_VALUE)
2298 {
2299 c = *porig;
2300 *porig = NUL;
2301
2302 /* Only use the match when it's the same name (ignoring case) or
2303 * expansion is allowed and there is a match with the short name
2304 * and there is enough room. */
2305 if (_stricoll(porigPrev, fb.cFileName) == 0
2306 || (len > 0
2307 && (_stricoll(porigPrev, fb.cAlternateFileName) == 0
2308 && (int)(ptruePrev - szTrueName)
2309 + (int)strlen(fb.cFileName) < len)))
2310 {
2311 STRCPY(ptruePrev, fb.cFileName);
2312
2313 /* Look for exact match and prefer it if found. Must be a
2314 * long name, otherwise there would be only one match. */
2315 while (FindNextFile(hFind, &fb))
2316 {
2317 if (*fb.cAlternateFileName != NUL
2318 && (strcoll(porigPrev, fb.cFileName) == 0
2319 || (len > 0
2320 && (_stricoll(porigPrev,
2321 fb.cAlternateFileName) == 0
2322 && (int)(ptruePrev - szTrueName)
2323 + (int)strlen(fb.cFileName) < len))))
2324 {
2325 STRCPY(ptruePrev, fb.cFileName);
2326 break;
2327 }
2328 }
2329 }
2330 FindClose(hFind);
2331 *porig = c;
2332 ptrue = ptruePrev + strlen(ptruePrev);
2333 }
2334 }
2335
2336 STRCPY(name, szTrueName);
2337}
2338
2339
2340/*
2341 * Insert user name in s[len].
2342 */
2343 int
2344mch_get_user_name(
2345 char_u *s,
2346 int len)
2347{
2348 char szUserName[MAX_COMPUTERNAME_LENGTH + 1];
2349 DWORD cch = sizeof szUserName;
2350
2351 if (GetUserName(szUserName, &cch))
2352 {
2353 STRNCPY(s, szUserName, len);
2354 return OK;
2355 }
2356 s[0] = NUL;
2357 return FAIL;
2358}
2359
2360
2361/*
2362 * Insert host name in s[len].
2363 */
2364 void
2365mch_get_host_name(
2366 char_u *s,
2367 int len)
2368{
2369 DWORD cch = len;
2370
2371 if (!GetComputerName(s, &cch))
2372 {
2373 STRNCPY(s, "PC (Win32 Vim)", len);
2374 s[len - 1] = NUL; /* make sure it's terminated */
2375 }
2376}
2377
2378
2379/*
2380 * return process ID
2381 */
2382 long
2383mch_get_pid()
2384{
2385 return (long)GetCurrentProcessId();
2386}
2387
2388
2389/*
2390 * Get name of current directory into buffer 'buf' of length 'len' bytes.
2391 * Return OK for success, FAIL for failure.
2392 */
2393 int
2394mch_dirname(
2395 char_u *buf,
2396 int len)
2397{
2398 /*
2399 * Originally this was:
2400 * return (getcwd(buf, len) != NULL ? OK : FAIL);
2401 * But the Win32s known bug list says that getcwd() doesn't work
2402 * so use the Win32 system call instead. <Negri>
2403 */
2404#ifdef FEAT_MBYTE
2405 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2406 {
2407 WCHAR wbuf[_MAX_PATH + 1];
2408
2409 if (GetCurrentDirectoryW(_MAX_PATH, wbuf) != 0)
2410 {
2411 char_u *p = ucs2_to_enc(wbuf, NULL);
2412
2413 if (p != NULL)
2414 {
2415 STRNCPY(buf, p, len - 1);
2416 buf[len - 1] = NUL;
2417 vim_free(p);
2418 return OK;
2419 }
2420 }
2421 /* Retry with non-wide function (for Windows 98). */
2422 }
2423#endif
2424 return (GetCurrentDirectory(len, buf) != 0 ? OK : FAIL);
2425}
2426
2427/*
2428 * get file permissions for `name'
2429 * -1 : error
2430 * else FILE_ATTRIBUTE_* defined in winnt.h
2431 */
2432 long
2433mch_getperm(
2434 char_u *name)
2435{
2436#ifdef FEAT_MBYTE
2437 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2438 {
2439 WCHAR *p = enc_to_ucs2(name, NULL);
2440 long n;
2441
2442 if (p != NULL)
2443 {
2444 n = (long)GetFileAttributesW(p);
2445 vim_free(p);
2446 if (n >= 0 || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
2447 return n;
2448 /* Retry with non-wide function (for Windows 98). */
2449 }
2450 }
2451#endif
2452 return (long)GetFileAttributes((char *)name);
2453}
2454
2455
2456/*
2457 * set file permission for `name' to `perm'
2458 */
2459 int
2460mch_setperm(
2461 char_u *name,
2462 long perm)
2463{
2464 perm |= FILE_ATTRIBUTE_ARCHIVE; /* file has changed, set archive bit */
2465#ifdef FEAT_MBYTE
2466 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2467 {
2468 WCHAR *p = enc_to_ucs2(name, NULL);
2469 long n;
2470
2471 if (p != NULL)
2472 {
2473 n = (long)SetFileAttributesW(p, perm);
2474 vim_free(p);
2475 if (n || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
2476 return n ? OK : FAIL;
2477 /* Retry with non-wide function (for Windows 98). */
2478 }
2479 }
2480#endif
2481 return SetFileAttributes((char *)name, perm) ? OK : FAIL;
2482}
2483
2484/*
2485 * Set hidden flag for "name".
2486 */
2487 void
2488mch_hide(char_u *name)
2489{
2490 int perm;
2491#ifdef FEAT_MBYTE
2492 WCHAR *p = NULL;
2493
2494 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2495 p = enc_to_ucs2(name, NULL);
2496#endif
2497
2498#ifdef FEAT_MBYTE
2499 if (p != NULL)
2500 {
2501 perm = GetFileAttributesW(p);
2502 if (perm < 0 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
2503 {
2504 /* Retry with non-wide function (for Windows 98). */
2505 vim_free(p);
2506 p = NULL;
2507 }
2508 }
2509 if (p == NULL)
2510#endif
2511 perm = GetFileAttributes((char *)name);
2512 if (perm >= 0)
2513 {
2514 perm |= FILE_ATTRIBUTE_HIDDEN;
2515#ifdef FEAT_MBYTE
2516 if (p != NULL)
2517 {
2518 if (SetFileAttributesW(p, perm) == 0
2519 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
2520 {
2521 /* Retry with non-wide function (for Windows 98). */
2522 vim_free(p);
2523 p = NULL;
2524 }
2525 }
2526 if (p == NULL)
2527#endif
2528 SetFileAttributes((char *)name, perm);
2529 }
2530#ifdef FEAT_MBYTE
2531 vim_free(p);
2532#endif
2533}
2534
2535/*
2536 * return TRUE if "name" is a directory
2537 * return FALSE if "name" is not a directory or upon error
2538 */
2539 int
2540mch_isdir(char_u *name)
2541{
2542 int f = mch_getperm(name);
2543
2544 if (f == -1)
2545 return FALSE; /* file does not exist at all */
2546
2547 return (f & FILE_ATTRIBUTE_DIRECTORY) != 0;
2548}
2549
2550/*
2551 * Return TRUE if file or directory "name" is writable (not readonly).
2552 * Strange semantics of Win32: a readonly directory is writable, but you can't
2553 * delete a file. Let's say this means it is writable.
2554 */
2555 int
2556mch_writable(char_u *name)
2557{
2558 int perm = mch_getperm(name);
2559
2560 return (perm != -1 && (!(perm & FILE_ATTRIBUTE_READONLY)
2561 || (perm & FILE_ATTRIBUTE_DIRECTORY)));
2562}
2563
2564#if defined(FEAT_EVAL) || defined(PROTO)
2565/*
2566 * Return 1 if "name" can be executed, 0 if not.
2567 * Return -1 if unknown.
2568 */
2569 int
2570mch_can_exe(char_u *name)
2571{
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00002572 char_u buf[_MAX_PATH];
2573 int len = STRLEN(name);
2574 char_u *p;
2575
2576 if (len >= _MAX_PATH) /* safety check */
2577 return FALSE;
2578
2579 /* If there already is an extension try using the name directly. Also do
2580 * this with a Unix-shell like 'shell'. */
2581 if (vim_strchr(gettail(name), '.') != NULL
2582 || strstr((char *)gettail(p_sh), "sh") != NULL)
2583 if (executable_exists((char *)name))
2584 return TRUE;
2585
2586 /*
2587 * Loop over all extensions in $PATHEXT.
2588 */
2589 STRNCPY(buf, name, _MAX_PATH);
2590 p = mch_getenv("PATHEXT");
2591 if (p == NULL)
2592 p = (char_u *)".com;.exe;.bat;.cmd";
2593 while (*p)
2594 {
2595 if (p[0] == '.' && (p[1] == NUL || p[1] == ';'))
2596 {
2597 /* A single "." means no extension is added. */
2598 buf[len] = NUL;
2599 ++p;
2600 if (*p)
2601 ++p;
2602 }
2603 else
2604 copy_option_part(&p, buf + len, _MAX_PATH - len, ";");
2605 if (executable_exists((char *)buf))
2606 return TRUE;
2607 }
2608 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002609}
2610#endif
2611
2612/*
2613 * Check what "name" is:
2614 * NODE_NORMAL: file or directory (or doesn't exist)
2615 * NODE_WRITABLE: writable device, socket, fifo, etc.
2616 * NODE_OTHER: non-writable things
2617 */
2618 int
2619mch_nodetype(char_u *name)
2620{
2621 HANDLE hFile;
2622 int type;
2623
2624 hFile = CreateFile(name, /* file name */
2625 GENERIC_WRITE, /* access mode */
2626 0, /* share mode */
2627 NULL, /* security descriptor */
2628 OPEN_EXISTING, /* creation disposition */
2629 0, /* file attributes */
2630 NULL); /* handle to template file */
2631
2632 if (hFile == INVALID_HANDLE_VALUE)
2633 return NODE_NORMAL;
2634
2635 type = GetFileType(hFile);
2636 CloseHandle(hFile);
2637 if (type == FILE_TYPE_CHAR)
2638 return NODE_WRITABLE;
2639 if (type == FILE_TYPE_DISK)
2640 return NODE_NORMAL;
2641 return NODE_OTHER;
2642}
2643
2644#ifdef HAVE_ACL
2645struct my_acl
2646{
2647 PSECURITY_DESCRIPTOR pSecurityDescriptor;
2648 PSID pSidOwner;
2649 PSID pSidGroup;
2650 PACL pDacl;
2651 PACL pSacl;
2652};
2653#endif
2654
2655/*
2656 * Return a pointer to the ACL of file "fname" in allocated memory.
2657 * Return NULL if the ACL is not available for whatever reason.
2658 */
2659 vim_acl_T
2660mch_get_acl(fname)
2661 char_u *fname;
2662{
2663#ifndef HAVE_ACL
2664 return (vim_acl_T)NULL;
2665#else
2666 struct my_acl *p = NULL;
2667
2668 /* This only works on Windows NT and 2000. */
2669 if (g_PlatformId == VER_PLATFORM_WIN32_NT && advapi_lib != NULL)
2670 {
2671 p = (struct my_acl *)alloc_clear((unsigned)sizeof(struct my_acl));
2672 if (p != NULL)
2673 {
2674 if (pGetNamedSecurityInfo(
2675 (LPTSTR)fname, // Abstract filename
2676 SE_FILE_OBJECT, // File Object
2677 // Retrieve the entire security descriptor.
2678 OWNER_SECURITY_INFORMATION |
2679 GROUP_SECURITY_INFORMATION |
2680 DACL_SECURITY_INFORMATION |
2681 SACL_SECURITY_INFORMATION,
2682 &p->pSidOwner, // Ownership information.
2683 &p->pSidGroup, // Group membership.
2684 &p->pDacl, // Discretionary information.
2685 &p->pSacl, // For auditing purposes.
2686 &p->pSecurityDescriptor
2687 ) != ERROR_SUCCESS)
2688 {
2689 mch_free_acl((vim_acl_T)p);
2690 p = NULL;
2691 }
2692 }
2693 }
2694
2695 return (vim_acl_T)p;
2696#endif
2697}
2698
2699/*
2700 * Set the ACL of file "fname" to "acl" (unless it's NULL).
2701 * Errors are ignored.
2702 * This must only be called with "acl" equal to what mch_get_acl() returned.
2703 */
2704 void
2705mch_set_acl(fname, acl)
2706 char_u *fname;
2707 vim_acl_T acl;
2708{
2709#ifdef HAVE_ACL
2710 struct my_acl *p = (struct my_acl *)acl;
2711
2712 if (p != NULL && advapi_lib != NULL)
2713 (void)pSetNamedSecurityInfo(
2714 (LPTSTR)fname, // Abstract filename
2715 SE_FILE_OBJECT, // File Object
2716 // Retrieve the entire security descriptor.
2717 OWNER_SECURITY_INFORMATION |
2718 GROUP_SECURITY_INFORMATION |
2719 DACL_SECURITY_INFORMATION |
2720 SACL_SECURITY_INFORMATION,
2721 p->pSidOwner, // Ownership information.
2722 p->pSidGroup, // Group membership.
2723 p->pDacl, // Discretionary information.
2724 p->pSacl // For auditing purposes.
2725 );
2726#endif
2727}
2728
2729 void
2730mch_free_acl(acl)
2731 vim_acl_T acl;
2732{
2733#ifdef HAVE_ACL
2734 struct my_acl *p = (struct my_acl *)acl;
2735
2736 if (p != NULL)
2737 {
2738 LocalFree(p->pSecurityDescriptor); // Free the memory just in case
2739 vim_free(p);
2740 }
2741#endif
2742}
2743
2744#ifndef FEAT_GUI_W32
2745
2746/*
2747 * handler for ctrl-break, ctrl-c interrupts, and fatal events.
2748 */
2749 static BOOL WINAPI
2750handler_routine(
2751 DWORD dwCtrlType)
2752{
2753 switch (dwCtrlType)
2754 {
2755 case CTRL_C_EVENT:
2756 if (ctrl_c_interrupts)
2757 g_fCtrlCPressed = TRUE;
2758 return TRUE;
2759
2760 case CTRL_BREAK_EVENT:
2761 g_fCBrkPressed = TRUE;
2762 return TRUE;
2763
2764 /* fatal events: shut down gracefully */
2765 case CTRL_CLOSE_EVENT:
2766 case CTRL_LOGOFF_EVENT:
2767 case CTRL_SHUTDOWN_EVENT:
2768 windgoto((int)Rows - 1, 0);
2769 g_fForceExit = TRUE;
2770
2771 sprintf((char *)IObuff, _("Vim: Caught %s event\n"),
2772 (dwCtrlType == CTRL_CLOSE_EVENT
2773 ? _("close")
2774 : dwCtrlType == CTRL_LOGOFF_EVENT
2775 ? _("logoff")
2776 : _("shutdown")));
2777#ifdef DEBUG
2778 OutputDebugString(IObuff);
2779#endif
2780
2781 preserve_exit(); /* output IObuff, preserve files and exit */
2782
2783 return TRUE; /* not reached */
2784
2785 default:
2786 return FALSE;
2787 }
2788}
2789
2790
2791/*
2792 * set the tty in (raw) ? "raw" : "cooked" mode
2793 */
2794 void
2795mch_settmode(
2796 int tmode)
2797{
2798 DWORD cmodein;
2799 DWORD cmodeout;
2800 BOOL bEnableHandler;
2801
2802 GetConsoleMode(g_hConIn, &cmodein);
2803 GetConsoleMode(g_hConOut, &cmodeout);
2804 if (tmode == TMODE_RAW)
2805 {
2806 cmodein &= ~(ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
2807 ENABLE_ECHO_INPUT);
2808#ifdef FEAT_MOUSE
2809 if (g_fMouseActive)
2810 cmodein |= ENABLE_MOUSE_INPUT;
2811#endif
2812 cmodeout &= ~(ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
2813 bEnableHandler = TRUE;
2814 }
2815 else /* cooked */
2816 {
2817 cmodein |= (ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
2818 ENABLE_ECHO_INPUT);
2819 cmodeout |= (ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
2820 bEnableHandler = FALSE;
2821 }
2822 SetConsoleMode(g_hConIn, cmodein);
2823 SetConsoleMode(g_hConOut, cmodeout);
2824 SetConsoleCtrlHandler(handler_routine, bEnableHandler);
2825
2826#ifdef MCH_WRITE_DUMP
2827 if (fdDump)
2828 {
2829 fprintf(fdDump, "mch_settmode(%s, in = %x, out = %x)\n",
2830 tmode == TMODE_RAW ? "raw" :
2831 tmode == TMODE_COOK ? "cooked" : "normal",
2832 cmodein, cmodeout);
2833 fflush(fdDump);
2834 }
2835#endif
2836}
2837
2838
2839/*
2840 * Get the size of the current window in `Rows' and `Columns'
2841 * Return OK when size could be determined, FAIL otherwise.
2842 */
2843 int
2844mch_get_shellsize()
2845{
2846 CONSOLE_SCREEN_BUFFER_INFO csbi;
2847
2848 if (!g_fTermcapMode && g_cbTermcap.IsValid)
2849 {
2850 /*
2851 * For some reason, we are trying to get the screen dimensions
2852 * even though we are not in termcap mode. The 'Rows' and 'Columns'
2853 * variables are really intended to mean the size of Vim screen
2854 * while in termcap mode.
2855 */
2856 Rows = g_cbTermcap.Info.dwSize.Y;
2857 Columns = g_cbTermcap.Info.dwSize.X;
2858 }
2859 else if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
2860 {
2861 Rows = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
2862 Columns = csbi.srWindow.Right - csbi.srWindow.Left + 1;
2863 }
2864 else
2865 {
2866 Rows = 25;
2867 Columns = 80;
2868 }
2869 return OK;
2870}
2871
2872/*
2873 * Set a console window to `xSize' * `ySize'
2874 */
2875 static void
2876ResizeConBufAndWindow(
2877 HANDLE hConsole,
2878 int xSize,
2879 int ySize)
2880{
2881 CONSOLE_SCREEN_BUFFER_INFO csbi; /* hold current console buffer info */
2882 SMALL_RECT srWindowRect; /* hold the new console size */
2883 COORD coordScreen;
2884
2885#ifdef MCH_WRITE_DUMP
2886 if (fdDump)
2887 {
2888 fprintf(fdDump, "ResizeConBufAndWindow(%d, %d)\n", xSize, ySize);
2889 fflush(fdDump);
2890 }
2891#endif
2892
2893 /* get the largest size we can size the console window to */
2894 coordScreen = GetLargestConsoleWindowSize(hConsole);
2895
2896 /* define the new console window size and scroll position */
2897 srWindowRect.Left = srWindowRect.Top = (SHORT) 0;
2898 srWindowRect.Right = (SHORT) (min(xSize, coordScreen.X) - 1);
2899 srWindowRect.Bottom = (SHORT) (min(ySize, coordScreen.Y) - 1);
2900
2901 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
2902 {
2903 int sx, sy;
2904
2905 sx = csbi.srWindow.Right - csbi.srWindow.Left + 1;
2906 sy = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
2907 if (sy < ySize || sx < xSize)
2908 {
2909 /*
2910 * Increasing number of lines/columns, do buffer first.
2911 * Use the maximal size in x and y direction.
2912 */
2913 if (sy < ySize)
2914 coordScreen.Y = ySize;
2915 else
2916 coordScreen.Y = sy;
2917 if (sx < xSize)
2918 coordScreen.X = xSize;
2919 else
2920 coordScreen.X = sx;
2921 SetConsoleScreenBufferSize(hConsole, coordScreen);
2922 }
2923 }
2924
2925 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &srWindowRect))
2926 {
2927#ifdef MCH_WRITE_DUMP
2928 if (fdDump)
2929 {
2930 fprintf(fdDump, "SetConsoleWindowInfo failed: %lx\n",
2931 GetLastError());
2932 fflush(fdDump);
2933 }
2934#endif
2935 }
2936
2937 /* define the new console buffer size */
2938 coordScreen.X = xSize;
2939 coordScreen.Y = ySize;
2940
2941 if (!SetConsoleScreenBufferSize(hConsole, coordScreen))
2942 {
2943#ifdef MCH_WRITE_DUMP
2944 if (fdDump)
2945 {
2946 fprintf(fdDump, "SetConsoleScreenBufferSize failed: %lx\n",
2947 GetLastError());
2948 fflush(fdDump);
2949 }
2950#endif
2951 }
2952}
2953
2954
2955/*
2956 * Set the console window to `Rows' * `Columns'
2957 */
2958 void
2959mch_set_shellsize()
2960{
2961 COORD coordScreen;
2962
2963 /* Don't change window size while still starting up */
2964 if (suppress_winsize != 0)
2965 {
2966 suppress_winsize = 2;
2967 return;
2968 }
2969
2970 if (term_console)
2971 {
2972 coordScreen = GetLargestConsoleWindowSize(g_hConOut);
2973
2974 /* Clamp Rows and Columns to reasonable values */
2975 if (Rows > coordScreen.Y)
2976 Rows = coordScreen.Y;
2977 if (Columns > coordScreen.X)
2978 Columns = coordScreen.X;
2979
2980 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
2981 }
2982}
2983
2984/*
2985 * Rows and/or Columns has changed.
2986 */
2987 void
2988mch_new_shellsize()
2989{
2990 set_scroll_region(0, 0, Columns - 1, Rows - 1);
2991}
2992
2993
2994/*
2995 * Called when started up, to set the winsize that was delayed.
2996 */
2997 void
2998mch_set_winsize_now()
2999{
3000 if (suppress_winsize == 2)
3001 {
3002 suppress_winsize = 0;
3003 mch_set_shellsize();
3004 shell_resized();
3005 }
3006 suppress_winsize = 0;
3007}
3008#endif /* FEAT_GUI_W32 */
3009
3010
3011
3012#if defined(FEAT_GUI_W32) || defined(PROTO)
3013
3014/*
3015 * Specialised version of system() for Win32 GUI mode.
3016 * This version proceeds as follows:
3017 * 1. Create a console window for use by the subprocess
3018 * 2. Run the subprocess (it gets the allocated console by default)
3019 * 3. Wait for the subprocess to terminate and get its exit code
3020 * 4. Prompt the user to press a key to close the console window
3021 */
3022 static int
3023mch_system(char *cmd, int options)
3024{
3025 STARTUPINFO si;
3026 PROCESS_INFORMATION pi;
3027 DWORD ret = 0;
3028 HWND hwnd = GetFocus();
3029
3030 si.cb = sizeof(si);
3031 si.lpReserved = NULL;
3032 si.lpDesktop = NULL;
3033 si.lpTitle = NULL;
3034 si.dwFlags = STARTF_USESHOWWINDOW;
3035 /*
3036 * It's nicer to run a filter command in a minimized window, but in
3037 * Windows 95 this makes the command MUCH slower. We can't do it under
3038 * Win32s either as it stops the synchronous spawn workaround working.
3039 */
3040 if ((options & SHELL_DOOUT) && !mch_windows95() && !gui_is_win32s())
3041 si.wShowWindow = SW_SHOWMINIMIZED;
3042 else
3043 si.wShowWindow = SW_SHOWNORMAL;
3044 si.cbReserved2 = 0;
3045 si.lpReserved2 = NULL;
3046
3047 /* There is a strange error on Windows 95 when using "c:\\command.com".
3048 * When the "c:\\" is left out it works OK...? */
3049 if (mch_windows95()
3050 && (STRNICMP(cmd, "c:/command.com", 14) == 0
3051 || STRNICMP(cmd, "c:\\command.com", 14) == 0))
3052 cmd += 3;
3053
3054 /* Now, run the command */
3055 CreateProcess(NULL, /* Executable name */
3056 cmd, /* Command to execute */
3057 NULL, /* Process security attributes */
3058 NULL, /* Thread security attributes */
3059 FALSE, /* Inherit handles */
3060 CREATE_DEFAULT_ERROR_MODE | /* Creation flags */
3061 CREATE_NEW_CONSOLE,
3062 NULL, /* Environment */
3063 NULL, /* Current directory */
3064 &si, /* Startup information */
3065 &pi); /* Process information */
3066
3067
3068 /* Wait for the command to terminate before continuing */
3069 if (g_PlatformId != VER_PLATFORM_WIN32s)
3070 {
3071#ifdef FEAT_GUI
3072 int delay = 1;
3073
3074 /* Keep updating the window while waiting for the shell to finish. */
3075 for (;;)
3076 {
3077 MSG msg;
3078
3079 if (PeekMessage(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
3080 {
3081 TranslateMessage(&msg);
3082 DispatchMessage(&msg);
3083 }
3084 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
3085 break;
3086
3087 /* We start waiting for a very short time and then increase it, so
3088 * that we respond quickly when the process is quick, and don't
3089 * consume too much overhead when it's slow. */
3090 if (delay < 50)
3091 delay += 10;
3092 }
3093#else
3094 WaitForSingleObject(pi.hProcess, INFINITE);
3095#endif
3096
3097 /* Get the command exit code */
3098 GetExitCodeProcess(pi.hProcess, &ret);
3099 }
3100 else
3101 {
3102 /*
3103 * This ugly code is the only quick way of performing
3104 * a synchronous spawn under Win32s. Yuk.
3105 */
3106 num_windows = 0;
3107 EnumWindows(win32ssynch_cb, 0);
3108 old_num_windows = num_windows;
3109 do
3110 {
3111 Sleep(1000);
3112 num_windows = 0;
3113 EnumWindows(win32ssynch_cb, 0);
3114 } while (num_windows == old_num_windows);
3115 ret = 0;
3116 }
3117
3118 /* Close the handles to the subprocess, so that it goes away */
3119 CloseHandle(pi.hThread);
3120 CloseHandle(pi.hProcess);
3121
3122 /* Try to get input focus back. Doesn't always work though. */
3123 PostMessage(hwnd, WM_SETFOCUS, 0, 0);
3124
3125 return ret;
3126}
3127#else
3128
3129# define mch_system(c, o) system(c)
3130
3131#endif
3132
3133/*
3134 * Either execute a command by calling the shell or start a new shell
3135 */
3136 int
3137mch_call_shell(
3138 char_u *cmd,
3139 int options) /* SHELL_*, see vim.h */
3140{
3141 int x = 0;
3142 int tmode = cur_tmode;
3143#ifdef FEAT_TITLE
3144 char szShellTitle[512];
3145
3146 /* Change the title to reflect that we are in a subshell. */
3147 if (GetConsoleTitle(szShellTitle, sizeof(szShellTitle) - 4) > 0)
3148 {
3149 if (cmd == NULL)
3150 strcat(szShellTitle, " :sh");
3151 else
3152 {
3153 strcat(szShellTitle, " - !");
3154 if ((strlen(szShellTitle) + strlen(cmd) < sizeof(szShellTitle)))
3155 strcat(szShellTitle, cmd);
3156 }
3157 mch_settitle(szShellTitle, NULL);
3158 }
3159#endif
3160
3161 out_flush();
3162
3163#ifdef MCH_WRITE_DUMP
3164 if (fdDump)
3165 {
3166 fprintf(fdDump, "mch_call_shell(\"%s\", %d)\n", cmd, options);
3167 fflush(fdDump);
3168 }
3169#endif
3170
3171 /*
3172 * Catch all deadly signals while running the external command, because a
3173 * CTRL-C, Ctrl-Break or illegal instruction might otherwise kill us.
3174 */
3175 signal(SIGINT, SIG_IGN);
3176#if defined(__GNUC__) && !defined(__MINGW32__)
3177 signal(SIGKILL, SIG_IGN);
3178#else
3179 signal(SIGBREAK, SIG_IGN);
3180#endif
3181 signal(SIGILL, SIG_IGN);
3182 signal(SIGFPE, SIG_IGN);
3183 signal(SIGSEGV, SIG_IGN);
3184 signal(SIGTERM, SIG_IGN);
3185 signal(SIGABRT, SIG_IGN);
3186
3187 if (options & SHELL_COOKED)
3188 settmode(TMODE_COOK); /* set to normal mode */
3189
3190 if (cmd == NULL)
3191 {
3192 x = mch_system(p_sh, options);
3193 }
3194 else
3195 {
3196 /* we use "command" or "cmd" to start the shell; slow but easy */
3197 char_u *newcmd;
3198
3199 newcmd = lalloc((long_u) (
3200#ifdef FEAT_GUI_W32
3201 STRLEN(vimrun_path) +
3202#endif
3203 STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10), TRUE);
3204 if (newcmd != NULL)
3205 {
3206 char_u *cmdbase = (*cmd == '"' ? cmd + 1 : cmd);
3207
3208 if ((STRNICMP(cmdbase, "start", 5) == 0) && vim_iswhite(cmdbase[5]))
3209 {
3210 STARTUPINFO si;
3211 PROCESS_INFORMATION pi;
3212
3213 si.cb = sizeof(si);
3214 si.lpReserved = NULL;
3215 si.lpDesktop = NULL;
3216 si.lpTitle = NULL;
3217 si.dwFlags = 0;
3218 si.cbReserved2 = 0;
3219 si.lpReserved2 = NULL;
3220
3221 cmdbase = skipwhite(cmdbase + 5);
3222 if ((STRNICMP(cmdbase, "/min", 4) == 0)
3223 && vim_iswhite(cmdbase[4]))
3224 {
3225 cmdbase = skipwhite(cmdbase + 4);
3226 si.dwFlags = STARTF_USESHOWWINDOW;
3227 si.wShowWindow = SW_SHOWMINNOACTIVE;
3228 }
3229
3230 /* When the command is in double quotes, but 'shellxquote' is
3231 * empty, keep the double quotes around the command.
3232 * Otherwise remove the double quotes, they aren't needed
3233 * here, because we don't use a shell to run the command. */
3234 if (*cmd == '"' && *p_sxq == NUL)
3235 {
3236 newcmd[0] = '"';
3237 STRCPY(newcmd + 1, cmdbase);
3238 }
3239 else
3240 {
3241 STRCPY(newcmd, cmdbase);
3242 if (*cmd == '"' && *newcmd != NUL)
3243 newcmd[STRLEN(newcmd) - 1] = NUL;
3244 }
3245
3246 /*
3247 * Now, start the command as a process, so that it doesn't
3248 * inherit our handles which causes unpleasant dangling swap
3249 * files if we exit before the spawned process
3250 */
3251 if (CreateProcess (NULL, // Executable name
3252 newcmd, // Command to execute
3253 NULL, // Process security attributes
3254 NULL, // Thread security attributes
3255 FALSE, // Inherit handles
3256 CREATE_NEW_CONSOLE, // Creation flags
3257 NULL, // Environment
3258 NULL, // Current directory
3259 &si, // Startup information
3260 &pi)) // Process information
3261 x = 0;
3262 else
3263 {
3264 x = -1;
3265#ifdef FEAT_GUI_W32
3266 EMSG(_("E371: Command not found"));
3267#endif
3268 }
3269 /* Close the handles to the subprocess, so that it goes away */
3270 CloseHandle(pi.hThread);
3271 CloseHandle(pi.hProcess);
3272 }
3273 else
3274 {
3275#if defined(FEAT_GUI_W32)
3276 if (need_vimrun_warning)
3277 {
3278 MessageBox(NULL,
3279 _("VIMRUN.EXE not found in your $PATH.\n"
3280 "External commands will not pause after completion.\n"
3281 "See :help win32-vimrun for more information."),
3282 _("Vim Warning"),
3283 MB_ICONWARNING);
3284 need_vimrun_warning = FALSE;
3285 }
3286 if (!s_dont_use_vimrun)
3287 /* Use vimrun to execute the command. It opens a console
3288 * window, which can be closed without killing Vim. */
3289 sprintf((char *)newcmd, "%s%s%s %s %s",
3290 vimrun_path,
3291 (msg_silent != 0 || (options & SHELL_DOOUT))
3292 ? "-s " : "",
3293 p_sh, p_shcf, cmd);
3294 else
3295#endif
3296 sprintf((char *)newcmd, "%s %s %s", p_sh, p_shcf, cmd);
3297 x = mch_system((char *)newcmd, options);
3298 }
3299 vim_free(newcmd);
3300 }
3301 }
3302
3303 if (tmode == TMODE_RAW)
3304 settmode(TMODE_RAW); /* set to raw mode */
3305
3306 /* Print the return value, unless "vimrun" was used. */
3307 if (x != 0 && !(options & SHELL_SILENT) && !emsg_silent
3308#if defined(FEAT_GUI_W32)
3309 && ((options & SHELL_DOOUT) || s_dont_use_vimrun)
3310#endif
3311 )
3312 {
3313 smsg(_("shell returned %d"), x);
3314 msg_putchar('\n');
3315 }
3316#ifdef FEAT_TITLE
3317 resettitle();
3318#endif
3319
3320 signal(SIGINT, SIG_DFL);
3321#if defined(__GNUC__) && !defined(__MINGW32__)
3322 signal(SIGKILL, SIG_DFL);
3323#else
3324 signal(SIGBREAK, SIG_DFL);
3325#endif
3326 signal(SIGILL, SIG_DFL);
3327 signal(SIGFPE, SIG_DFL);
3328 signal(SIGSEGV, SIG_DFL);
3329 signal(SIGTERM, SIG_DFL);
3330 signal(SIGABRT, SIG_DFL);
3331
3332 return x;
3333}
3334
3335
3336#ifndef FEAT_GUI_W32
3337
3338/*
3339 * Start termcap mode
3340 */
3341 static void
3342termcap_mode_start(void)
3343{
3344 DWORD cmodein;
3345
3346 if (g_fTermcapMode)
3347 return;
3348
3349 SaveConsoleBuffer(&g_cbNonTermcap);
3350
3351 if (g_cbTermcap.IsValid)
3352 {
3353 /*
3354 * We've been in termcap mode before. Restore certain screen
3355 * characteristics, including the buffer size and the window
3356 * size. Since we will be redrawing the screen, we don't need
3357 * to restore the actual contents of the buffer.
3358 */
3359 RestoreConsoleBuffer(&g_cbTermcap, FALSE);
3360 SetConsoleWindowInfo(g_hConOut, TRUE, &g_cbTermcap.Info.srWindow);
3361 Rows = g_cbTermcap.Info.dwSize.Y;
3362 Columns = g_cbTermcap.Info.dwSize.X;
3363 }
3364 else
3365 {
3366 /*
3367 * This is our first time entering termcap mode. Clear the console
3368 * screen buffer, and resize the buffer to match the current window
3369 * size. We will use this as the size of our editing environment.
3370 */
3371 ClearConsoleBuffer(g_attrCurrent);
3372 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
3373 }
3374
3375#ifdef FEAT_TITLE
3376 resettitle();
3377#endif
3378
3379 GetConsoleMode(g_hConIn, &cmodein);
3380#ifdef FEAT_MOUSE
3381 if (g_fMouseActive)
3382 cmodein |= ENABLE_MOUSE_INPUT;
3383 else
3384 cmodein &= ~ENABLE_MOUSE_INPUT;
3385#endif
3386 cmodein |= ENABLE_WINDOW_INPUT;
3387 SetConsoleMode(g_hConIn, cmodein);
3388
3389 redraw_later_clear();
3390 g_fTermcapMode = TRUE;
3391}
3392
3393
3394/*
3395 * End termcap mode
3396 */
3397 static void
3398termcap_mode_end(void)
3399{
3400 DWORD cmodein;
3401 ConsoleBuffer *cb;
3402 COORD coord;
3403 DWORD dwDummy;
3404
3405 if (!g_fTermcapMode)
3406 return;
3407
3408 SaveConsoleBuffer(&g_cbTermcap);
3409
3410 GetConsoleMode(g_hConIn, &cmodein);
3411 cmodein &= ~(ENABLE_MOUSE_INPUT | ENABLE_WINDOW_INPUT);
3412 SetConsoleMode(g_hConIn, cmodein);
3413
3414#ifdef FEAT_RESTORE_ORIG_SCREEN
3415 cb = exiting ? &g_cbOrig : &g_cbNonTermcap;
3416#else
3417 cb = &g_cbNonTermcap;
3418#endif
3419 RestoreConsoleBuffer(cb, p_rs);
3420 SetConsoleCursorInfo(g_hConOut, &g_cci);
3421
3422 if (p_rs || exiting)
3423 {
3424 /*
3425 * Clear anything that happens to be on the current line.
3426 */
3427 coord.X = 0;
3428 coord.Y = (SHORT) (p_rs ? cb->Info.dwCursorPosition.Y : (Rows - 1));
3429 FillConsoleOutputCharacter(g_hConOut, ' ',
3430 cb->Info.dwSize.X, coord, &dwDummy);
3431 /*
3432 * The following is just for aesthetics. If we are exiting without
3433 * restoring the screen, then we want to have a prompt string
3434 * appear at the bottom line. However, the command interpreter
3435 * seems to always advance the cursor one line before displaying
3436 * the prompt string, which causes the screen to scroll. To
3437 * counter this, move the cursor up one line before exiting.
3438 */
3439 if (exiting && !p_rs)
3440 coord.Y--;
3441 /*
3442 * Position the cursor at the leftmost column of the desired row.
3443 */
3444 SetConsoleCursorPosition(g_hConOut, coord);
3445 }
3446
3447 g_fTermcapMode = FALSE;
3448}
3449#endif /* FEAT_GUI_W32 */
3450
3451
3452#ifdef FEAT_GUI_W32
3453 void
3454mch_write(
3455 char_u *s,
3456 int len)
3457{
3458 /* never used */
3459}
3460
3461#else
3462
3463/*
3464 * clear `n' chars, starting from `coord'
3465 */
3466 static void
3467clear_chars(
3468 COORD coord,
3469 DWORD n)
3470{
3471 DWORD dwDummy;
3472
3473 FillConsoleOutputCharacter(g_hConOut, ' ', n, coord, &dwDummy);
3474 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, n, coord, &dwDummy);
3475}
3476
3477
3478/*
3479 * Clear the screen
3480 */
3481 static void
3482clear_screen(void)
3483{
3484 g_coord.X = g_coord.Y = 0;
3485 clear_chars(g_coord, Rows * Columns);
3486}
3487
3488
3489/*
3490 * Clear to end of display
3491 */
3492 static void
3493clear_to_end_of_display(void)
3494{
3495 clear_chars(g_coord, (Rows - g_coord.Y - 1)
3496 * Columns + (Columns - g_coord.X));
3497}
3498
3499
3500/*
3501 * Clear to end of line
3502 */
3503 static void
3504clear_to_end_of_line(void)
3505{
3506 clear_chars(g_coord, Columns - g_coord.X);
3507}
3508
3509
3510/*
3511 * Scroll the scroll region up by `cLines' lines
3512 */
3513 static void
3514scroll(
3515 unsigned cLines)
3516{
3517 COORD oldcoord = g_coord;
3518
3519 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
3520 delete_lines(cLines);
3521
3522 g_coord = oldcoord;
3523}
3524
3525
3526/*
3527 * Set the scroll region
3528 */
3529 static void
3530set_scroll_region(
3531 unsigned left,
3532 unsigned top,
3533 unsigned right,
3534 unsigned bottom)
3535{
3536 if (left >= right
3537 || top >= bottom
3538 || right > (unsigned) Columns - 1
3539 || bottom > (unsigned) Rows - 1)
3540 return;
3541
3542 g_srScrollRegion.Left = left;
3543 g_srScrollRegion.Top = top;
3544 g_srScrollRegion.Right = right;
3545 g_srScrollRegion.Bottom = bottom;
3546}
3547
3548
3549/*
3550 * Insert `cLines' lines at the current cursor position
3551 */
3552 static void
3553insert_lines(
3554 unsigned cLines)
3555{
3556 SMALL_RECT source;
3557 COORD dest;
3558 CHAR_INFO fill;
3559
3560 dest.X = 0;
3561 dest.Y = g_coord.Y + cLines;
3562
3563 source.Left = 0;
3564 source.Top = g_coord.Y;
3565 source.Right = g_srScrollRegion.Right;
3566 source.Bottom = g_srScrollRegion.Bottom - cLines;
3567
3568 fill.Char.AsciiChar = ' ';
3569 fill.Attributes = g_attrCurrent;
3570
3571 ScrollConsoleScreenBuffer(g_hConOut, &source, NULL, dest, &fill);
3572
3573 /* Here we have to deal with a win32 console flake: If the scroll
3574 * region looks like abc and we scroll c to a and fill with d we get
3575 * cbd... if we scroll block c one line at a time to a, we get cdd...
3576 * vim expects cdd consistently... So we have to deal with that
3577 * here... (this also occurs scrolling the same way in the other
3578 * direction). */
3579
3580 if (source.Bottom < dest.Y)
3581 {
3582 COORD coord;
3583
3584 coord.X = 0;
3585 coord.Y = source.Bottom;
3586 clear_chars(coord, Columns * (dest.Y - source.Bottom));
3587 }
3588}
3589
3590
3591/*
3592 * Delete `cLines' lines at the current cursor position
3593 */
3594 static void
3595delete_lines(
3596 unsigned cLines)
3597{
3598 SMALL_RECT source;
3599 COORD dest;
3600 CHAR_INFO fill;
3601 int nb;
3602
3603 dest.X = 0;
3604 dest.Y = g_coord.Y;
3605
3606 source.Left = 0;
3607 source.Top = g_coord.Y + cLines;
3608 source.Right = g_srScrollRegion.Right;
3609 source.Bottom = g_srScrollRegion.Bottom;
3610
3611 fill.Char.AsciiChar = ' ';
3612 fill.Attributes = g_attrCurrent;
3613
3614 ScrollConsoleScreenBuffer(g_hConOut, &source, NULL, dest, &fill);
3615
3616 /* Here we have to deal with a win32 console flake: If the scroll
3617 * region looks like abc and we scroll c to a and fill with d we get
3618 * cbd... if we scroll block c one line at a time to a, we get cdd...
3619 * vim expects cdd consistently... So we have to deal with that
3620 * here... (this also occurs scrolling the same way in the other
3621 * direction). */
3622
3623 nb = dest.Y + (source.Bottom - source.Top) + 1;
3624
3625 if (nb < source.Top)
3626 {
3627 COORD coord;
3628
3629 coord.X = 0;
3630 coord.Y = nb;
3631 clear_chars(coord, Columns * (source.Top - nb));
3632 }
3633}
3634
3635
3636/*
3637 * Set the cursor position
3638 */
3639 static void
3640gotoxy(
3641 unsigned x,
3642 unsigned y)
3643{
3644 if (x < 1 || x > (unsigned)Columns || y < 1 || y > (unsigned)Rows)
3645 return;
3646
3647 /* external cursor coords are 1-based; internal are 0-based */
3648 g_coord.X = x - 1;
3649 g_coord.Y = y - 1;
3650 SetConsoleCursorPosition(g_hConOut, g_coord);
3651}
3652
3653
3654/*
3655 * Set the current text attribute = (foreground | background)
3656 * See ../doc/os_win32.txt for the numbers.
3657 */
3658 static void
3659textattr(
3660 WORD wAttr)
3661{
3662 g_attrCurrent = wAttr;
3663
3664 SetConsoleTextAttribute(g_hConOut, wAttr);
3665}
3666
3667
3668 static void
3669textcolor(
3670 WORD wAttr)
3671{
3672 g_attrCurrent = (g_attrCurrent & 0xf0) + wAttr;
3673
3674 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
3675}
3676
3677
3678 static void
3679textbackground(
3680 WORD wAttr)
3681{
3682 g_attrCurrent = (g_attrCurrent & 0x0f) + (wAttr << 4);
3683
3684 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
3685}
3686
3687
3688/*
3689 * restore the default text attribute (whatever we started with)
3690 */
3691 static void
3692normvideo()
3693{
3694 textattr(g_attrDefault);
3695}
3696
3697
3698static WORD g_attrPreStandout = 0;
3699
3700/*
3701 * Make the text standout, by brightening it
3702 */
3703 static void
3704standout(void)
3705{
3706 g_attrPreStandout = g_attrCurrent;
3707 textattr((WORD) (g_attrCurrent|FOREGROUND_INTENSITY|BACKGROUND_INTENSITY));
3708}
3709
3710
3711/*
3712 * Turn off standout mode
3713 */
3714 static void
3715standend()
3716{
3717 if (g_attrPreStandout)
3718 {
3719 textattr(g_attrPreStandout);
3720 g_attrPreStandout = 0;
3721 }
3722}
3723
3724
3725/*
3726 * Set normal fg/bg color, based on T_ME. Called whem t_me has been set.
3727 */
3728 void
3729mch_set_normal_colors()
3730{
3731 char_u *p;
3732 int n;
3733
3734 cterm_normal_fg_color = (g_attrDefault & 0xf) + 1;
3735 cterm_normal_bg_color = ((g_attrDefault >> 4) & 0xf) + 1;
3736 if (T_ME[0] == ESC && T_ME[1] == '|')
3737 {
3738 p = T_ME + 2;
3739 n = getdigits(&p);
3740 if (*p == 'm' && n > 0)
3741 {
3742 cterm_normal_fg_color = (n & 0xf) + 1;
3743 cterm_normal_bg_color = ((n >> 4) & 0xf) + 1;
3744 }
3745 }
3746}
3747
3748
3749/*
3750 * visual bell: flash the screen
3751 */
3752 static void
3753visual_bell()
3754{
3755 COORD coordOrigin = {0, 0};
3756 WORD attrFlash = ~g_attrCurrent & 0xff;
3757
3758 DWORD dwDummy;
3759 LPWORD oldattrs = (LPWORD)alloc(Rows * Columns * sizeof(WORD));
3760
3761 if (oldattrs == NULL)
3762 return;
3763 ReadConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
3764 coordOrigin, &dwDummy);
3765 FillConsoleOutputAttribute(g_hConOut, attrFlash, Rows * Columns,
3766 coordOrigin, &dwDummy);
3767
3768 Sleep(15); /* wait for 15 msec */
3769 WriteConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
3770 coordOrigin, &dwDummy);
3771 vim_free(oldattrs);
3772}
3773
3774
3775/*
3776 * Make the cursor visible or invisible
3777 */
3778 static void
3779cursor_visible(
3780 BOOL fVisible)
3781{
3782 s_cursor_visible = fVisible;
3783#ifdef MCH_CURSOR_SHAPE
3784 mch_update_cursor();
3785#endif
3786}
3787
3788
3789/*
3790 * write `cchToWrite' characters in `pchBuf' to the screen
3791 * Returns the number of characters actually written (at least one).
3792 */
3793 static BOOL
3794write_chars(
3795 LPCSTR pchBuf,
3796 DWORD cchToWrite)
3797{
3798 COORD coord = g_coord;
3799 DWORD written;
3800
3801 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, cchToWrite,
3802 coord, &written);
3803 /* When writing fails or didn't write a single character, pretend one
3804 * character was written, otherwise we get stuck. */
3805 if (WriteConsoleOutputCharacter(g_hConOut, pchBuf, cchToWrite,
3806 coord, &written) == 0
3807 || written == 0)
3808 written = 1;
3809
3810 g_coord.X += (SHORT) written;
3811
3812 while (g_coord.X > g_srScrollRegion.Right)
3813 {
3814 g_coord.X -= (SHORT) Columns;
3815 if (g_coord.Y < g_srScrollRegion.Bottom)
3816 g_coord.Y++;
3817 }
3818
3819 gotoxy(g_coord.X + 1, g_coord.Y + 1);
3820
3821 return written;
3822}
3823
3824
3825/*
3826 * mch_write(): write the output buffer to the screen, translating ESC
3827 * sequences into calls to console output routines.
3828 */
3829 void
3830mch_write(
3831 char_u *s,
3832 int len)
3833{
3834 s[len] = NUL;
3835
3836 if (!term_console)
3837 {
3838 write(1, s, (unsigned)len);
3839 return;
3840 }
3841
3842 /* translate ESC | sequences into faked bios calls */
3843 while (len--)
3844 {
3845 /* optimization: use one single write_chars for runs of text,
3846 * rather than once per character It ain't curses, but it helps. */
3847 DWORD prefix = strcspn(s, "\n\r\b\a\033");
3848
3849 if (p_wd)
3850 {
3851 WaitForChar(p_wd);
3852 if (prefix != 0)
3853 prefix = 1;
3854 }
3855
3856 if (prefix != 0)
3857 {
3858 DWORD nWritten;
3859
3860 nWritten = write_chars(s, prefix);
3861#ifdef MCH_WRITE_DUMP
3862 if (fdDump)
3863 {
3864 fputc('>', fdDump);
3865 fwrite(s, sizeof(char_u), nWritten, fdDump);
3866 fputs("<\n", fdDump);
3867 }
3868#endif
3869 len -= (nWritten - 1);
3870 s += nWritten;
3871 }
3872 else if (s[0] == '\n')
3873 {
3874 /* \n, newline: go to the beginning of the next line or scroll */
3875 if (g_coord.Y == g_srScrollRegion.Bottom)
3876 {
3877 scroll(1);
3878 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Bottom + 1);
3879 }
3880 else
3881 {
3882 gotoxy(g_srScrollRegion.Left + 1, g_coord.Y + 2);
3883 }
3884#ifdef MCH_WRITE_DUMP
3885 if (fdDump)
3886 fputs("\\n\n", fdDump);
3887#endif
3888 s++;
3889 }
3890 else if (s[0] == '\r')
3891 {
3892 /* \r, carriage return: go to beginning of line */
3893 gotoxy(g_srScrollRegion.Left+1, g_coord.Y + 1);
3894#ifdef MCH_WRITE_DUMP
3895 if (fdDump)
3896 fputs("\\r\n", fdDump);
3897#endif
3898 s++;
3899 }
3900 else if (s[0] == '\b')
3901 {
3902 /* \b, backspace: move cursor one position left */
3903 if (g_coord.X > g_srScrollRegion.Left)
3904 g_coord.X--;
3905 else if (g_coord.Y > g_srScrollRegion.Top)
3906 {
3907 g_coord.X = g_srScrollRegion.Right;
3908 g_coord.Y--;
3909 }
3910 gotoxy(g_coord.X + 1, g_coord.Y + 1);
3911#ifdef MCH_WRITE_DUMP
3912 if (fdDump)
3913 fputs("\\b\n", fdDump);
3914#endif
3915 s++;
3916 }
3917 else if (s[0] == '\a')
3918 {
3919 /* \a, bell */
3920 MessageBeep(0xFFFFFFFF);
3921#ifdef MCH_WRITE_DUMP
3922 if (fdDump)
3923 fputs("\\a\n", fdDump);
3924#endif
3925 s++;
3926 }
3927 else if (s[0] == ESC && len >= 3-1 && s[1] == '|')
3928 {
3929#ifdef MCH_WRITE_DUMP
3930 char_u* old_s = s;
3931#endif
3932 char_u* p;
3933 int arg1 = 0, arg2 = 0;
3934
3935 switch (s[2])
3936 {
3937 /* one or two numeric arguments, separated by ';' */
3938
3939 case '0': case '1': case '2': case '3': case '4':
3940 case '5': case '6': case '7': case '8': case '9':
3941 p = s + 2;
3942 arg1 = getdigits(&p); /* no check for length! */
3943 if (p > s + len)
3944 break;
3945
3946 if (*p == ';')
3947 {
3948 ++p;
3949 arg2 = getdigits(&p); /* no check for length! */
3950 if (p > s + len)
3951 break;
3952
3953 if (*p == 'H')
3954 gotoxy(arg2, arg1);
3955 else if (*p == 'r')
3956 set_scroll_region(0, arg1 - 1, Columns - 1, arg2 - 1);
3957 }
3958 else if (*p == 'A')
3959 {
3960 /* move cursor up arg1 lines in same column */
3961 gotoxy(g_coord.X + 1,
3962 max(g_srScrollRegion.Top, g_coord.Y - arg1) + 1);
3963 }
3964 else if (*p == 'C')
3965 {
3966 /* move cursor right arg1 columns in same line */
3967 gotoxy(min(g_srScrollRegion.Right, g_coord.X + arg1) + 1,
3968 g_coord.Y + 1);
3969 }
3970 else if (*p == 'H')
3971 {
3972 gotoxy(1, arg1);
3973 }
3974 else if (*p == 'L')
3975 {
3976 insert_lines(arg1);
3977 }
3978 else if (*p == 'm')
3979 {
3980 if (arg1 == 0)
3981 normvideo();
3982 else
3983 textattr((WORD) arg1);
3984 }
3985 else if (*p == 'f')
3986 {
3987 textcolor((WORD) arg1);
3988 }
3989 else if (*p == 'b')
3990 {
3991 textbackground((WORD) arg1);
3992 }
3993 else if (*p == 'M')
3994 {
3995 delete_lines(arg1);
3996 }
3997
3998 len -= p - s;
3999 s = p + 1;
4000 break;
4001
4002
4003 /* Three-character escape sequences */
4004
4005 case 'A':
4006 /* move cursor up one line in same column */
4007 gotoxy(g_coord.X + 1,
4008 max(g_srScrollRegion.Top, g_coord.Y - 1) + 1);
4009 goto got3;
4010
4011 case 'B':
4012 visual_bell();
4013 goto got3;
4014
4015 case 'C':
4016 /* move cursor right one column in same line */
4017 gotoxy(min(g_srScrollRegion.Right, g_coord.X + 1) + 1,
4018 g_coord.Y + 1);
4019 goto got3;
4020
4021 case 'E':
4022 termcap_mode_end();
4023 goto got3;
4024
4025 case 'F':
4026 standout();
4027 goto got3;
4028
4029 case 'f':
4030 standend();
4031 goto got3;
4032
4033 case 'H':
4034 gotoxy(1, 1);
4035 goto got3;
4036
4037 case 'j':
4038 clear_to_end_of_display();
4039 goto got3;
4040
4041 case 'J':
4042 clear_screen();
4043 goto got3;
4044
4045 case 'K':
4046 clear_to_end_of_line();
4047 goto got3;
4048
4049 case 'L':
4050 insert_lines(1);
4051 goto got3;
4052
4053 case 'M':
4054 delete_lines(1);
4055 goto got3;
4056
4057 case 'S':
4058 termcap_mode_start();
4059 goto got3;
4060
4061 case 'V':
4062 cursor_visible(TRUE);
4063 goto got3;
4064
4065 case 'v':
4066 cursor_visible(FALSE);
4067 goto got3;
4068
4069 got3:
4070 s += 3;
4071 len -= 2;
4072 }
4073
4074#ifdef MCH_WRITE_DUMP
4075 if (fdDump)
4076 {
4077 fputs("ESC | ", fdDump);
4078 fwrite(old_s + 2, sizeof(char_u), s - old_s - 2, fdDump);
4079 fputc('\n', fdDump);
4080 }
4081#endif
4082 }
4083 else
4084 {
4085 /* Write a single character */
4086 DWORD nWritten;
4087
4088 nWritten = write_chars(s, 1);
4089#ifdef MCH_WRITE_DUMP
4090 if (fdDump)
4091 {
4092 fputc('>', fdDump);
4093 fwrite(s, sizeof(char_u), nWritten, fdDump);
4094 fputs("<\n", fdDump);
4095 }
4096#endif
4097
4098 len -= (nWritten - 1);
4099 s += nWritten;
4100 }
4101 }
4102
4103#ifdef MCH_WRITE_DUMP
4104 if (fdDump)
4105 fflush(fdDump);
4106#endif
4107}
4108
4109#endif /* FEAT_GUI_W32 */
4110
4111
4112/*
4113 * Delay for half a second.
4114 */
4115 void
4116mch_delay(
4117 long msec,
4118 int ignoreinput)
4119{
4120#ifdef FEAT_GUI_W32
4121 Sleep((int)msec); /* never wait for input */
Bram Moolenaar325b7a22004-07-05 15:58:32 +00004122#else /* Console */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004123 if (ignoreinput)
Bram Moolenaar325b7a22004-07-05 15:58:32 +00004124# ifdef FEAT_MZSCHEME
4125 if (mzthreads_allowed() && p_mzq > 0 && msec > p_mzq)
4126 {
4127 int towait = p_mzq;
4128
4129 /* if msec is large enough, wait by portions in p_mzq */
4130 while (msec > 0)
4131 {
4132 mzvim_check_threads();
4133 if (msec < towait)
4134 towait = msec;
4135 Sleep(towait);
4136 msec -= towait;
4137 }
4138 }
4139 else
4140# endif
4141 Sleep((int)msec);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004142 else
4143 WaitForChar(msec);
4144#endif
4145}
4146
4147
4148/*
4149 * this version of remove is not scared by a readonly (backup) file
4150 * Return 0 for success, -1 for failure.
4151 */
4152 int
4153mch_remove(char_u *name)
4154{
4155#ifdef FEAT_MBYTE
4156 WCHAR *wn = NULL;
4157 int n;
4158
4159 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4160 {
4161 wn = enc_to_ucs2(name, NULL);
4162 if (wn != NULL)
4163 {
4164 SetFileAttributesW(wn, FILE_ATTRIBUTE_NORMAL);
4165 n = DeleteFileW(wn) ? 0 : -1;
4166 vim_free(wn);
4167 if (n == 0 || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
4168 return n;
4169 /* Retry with non-wide function (for Windows 98). */
4170 }
4171 }
4172#endif
4173 SetFileAttributes(name, FILE_ATTRIBUTE_NORMAL);
4174 return DeleteFile(name) ? 0 : -1;
4175}
4176
4177
4178/*
4179 * check for an "interrupt signal": CTRL-break or CTRL-C
4180 */
4181 void
4182mch_breakcheck()
4183{
4184#ifndef FEAT_GUI_W32 /* never used */
4185 if (g_fCtrlCPressed || g_fCBrkPressed)
4186 {
4187 g_fCtrlCPressed = g_fCBrkPressed = FALSE;
4188 got_int = TRUE;
4189 }
4190#endif
4191}
4192
4193
4194/*
4195 * How much memory is available?
4196 * Return sum of available physical and page file memory.
4197 */
4198 long_u
4199mch_avail_mem(
4200 int special)
4201{
4202 MEMORYSTATUS ms;
4203
4204 ms.dwLength = sizeof(MEMORYSTATUS);
4205 GlobalMemoryStatus(&ms);
4206 return (long_u) (ms.dwAvailPhys + ms.dwAvailPageFile);
4207}
4208
4209#ifdef FEAT_MBYTE
4210/*
4211 * Same code as below, but with wide functions and no comments.
4212 * Return 0 for success, non-zero for failure.
4213 */
4214 int
4215mch_wrename(WCHAR *wold, WCHAR *wnew)
4216{
4217 WCHAR *p;
4218 int i;
4219 WCHAR szTempFile[_MAX_PATH + 1];
4220 WCHAR szNewPath[_MAX_PATH + 1];
4221 HANDLE hf;
4222
4223 if (!mch_windows95())
4224 {
4225 p = wold;
4226 for (i = 0; wold[i] != NUL; ++i)
4227 if ((wold[i] == '/' || wold[i] == '\\' || wold[i] == ':')
4228 && wold[i + 1] != 0)
4229 p = wold + i + 1;
4230 if ((int)(wold + i - p) < 8 || p[6] != '~')
4231 return (MoveFileW(wold, wnew) == 0);
4232 }
4233
4234 if (GetFullPathNameW(wnew, _MAX_PATH, szNewPath, &p) == 0 || p == NULL)
4235 return -1;
4236 *p = NUL;
4237
4238 if (GetTempFileNameW(szNewPath, L"VIM", 0, szTempFile) == 0)
4239 return -2;
4240
4241 if (!DeleteFileW(szTempFile))
4242 return -3;
4243
4244 if (!MoveFileW(wold, szTempFile))
4245 return -4;
4246
4247 if ((hf = CreateFileW(wold, GENERIC_WRITE, 0, NULL, CREATE_NEW,
4248 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
4249 return -5;
4250 if (!CloseHandle(hf))
4251 return -6;
4252
4253 if (!MoveFileW(szTempFile, wnew))
4254 {
4255 (void)MoveFileW(szTempFile, wold);
4256 return -7;
4257 }
4258
4259 DeleteFileW(szTempFile);
4260
4261 if (!DeleteFileW(wold))
4262 return -8;
4263
4264 return 0;
4265}
4266#endif
4267
4268
4269/*
4270 * mch_rename() works around a bug in rename (aka MoveFile) in
4271 * Windows 95: rename("foo.bar", "foo.bar~") will generate a
4272 * file whose short file name is "FOO.BAR" (its long file name will
4273 * be correct: "foo.bar~"). Because a file can be accessed by
4274 * either its SFN or its LFN, "foo.bar" has effectively been
4275 * renamed to "foo.bar", which is not at all what was wanted. This
4276 * seems to happen only when renaming files with three-character
4277 * extensions by appending a suffix that does not include ".".
4278 * Windows NT gets it right, however, with an SFN of "FOO~1.BAR".
4279 *
4280 * There is another problem, which isn't really a bug but isn't right either:
4281 * When renaming "abcdef~1.txt" to "abcdef~1.txt~", the short name can be
4282 * "abcdef~1.txt" again. This has been reported on Windows NT 4.0 with
4283 * service pack 6. Doesn't seem to happen on Windows 98.
4284 *
4285 * Like rename(), returns 0 upon success, non-zero upon failure.
4286 * Should probably set errno appropriately when errors occur.
4287 */
4288 int
4289mch_rename(
4290 const char *pszOldFile,
4291 const char *pszNewFile)
4292{
4293 char szTempFile[_MAX_PATH+1];
4294 char szNewPath[_MAX_PATH+1];
4295 char *pszFilePart;
4296 HANDLE hf;
4297#ifdef FEAT_MBYTE
4298 WCHAR *wold = NULL;
4299 WCHAR *wnew = NULL;
4300 int retval = -1;
4301
4302 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4303 {
4304 wold = enc_to_ucs2((char_u *)pszOldFile, NULL);
4305 wnew = enc_to_ucs2((char_u *)pszNewFile, NULL);
4306 if (wold != NULL && wnew != NULL)
4307 retval = mch_wrename(wold, wnew);
4308 vim_free(wold);
4309 vim_free(wnew);
4310 if (retval == 0 || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
4311 return retval;
4312 /* Retry with non-wide function (for Windows 98). */
4313 }
4314#endif
4315
4316 /*
4317 * No need to play tricks if not running Windows 95, unless the file name
4318 * contains a "~" as the seventh character.
4319 */
4320 if (!mch_windows95())
4321 {
4322 pszFilePart = (char *)gettail((char_u *)pszOldFile);
4323 if (STRLEN(pszFilePart) < 8 || pszFilePart[6] != '~')
4324 return rename(pszOldFile, pszNewFile);
4325 }
4326
4327 /* Get base path of new file name. Undocumented feature: If pszNewFile is
4328 * a directory, no error is returned and pszFilePart will be NULL. */
4329 if (GetFullPathName(pszNewFile, _MAX_PATH, szNewPath, &pszFilePart) == 0
4330 || pszFilePart == NULL)
4331 return -1;
4332 *pszFilePart = NUL;
4333
4334 /* Get (and create) a unique temporary file name in directory of new file */
4335 if (GetTempFileName(szNewPath, "VIM", 0, szTempFile) == 0)
4336 return -2;
4337
4338 /* blow the temp file away */
4339 if (!DeleteFile(szTempFile))
4340 return -3;
4341
4342 /* rename old file to the temp file */
4343 if (!MoveFile(pszOldFile, szTempFile))
4344 return -4;
4345
4346 /* now create an empty file called pszOldFile; this prevents the operating
4347 * system using pszOldFile as an alias (SFN) if we're renaming within the
4348 * same directory. For example, we're editing a file called
4349 * filename.asc.txt by its SFN, filena~1.txt. If we rename filena~1.txt
4350 * to filena~1.txt~ (i.e., we're making a backup while writing it), the
4351 * SFN for filena~1.txt~ will be filena~1.txt, by default, which will
4352 * cause all sorts of problems later in buf_write. So, we create an empty
4353 * file called filena~1.txt and the system will have to find some other
4354 * SFN for filena~1.txt~, such as filena~2.txt
4355 */
4356 if ((hf = CreateFile(pszOldFile, GENERIC_WRITE, 0, NULL, CREATE_NEW,
4357 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
4358 return -5;
4359 if (!CloseHandle(hf))
4360 return -6;
4361
4362 /* rename the temp file to the new file */
4363 if (!MoveFile(szTempFile, pszNewFile))
4364 {
4365 /* Renaming failed. Rename the file back to its old name, so that it
4366 * looks like nothing happened. */
4367 (void)MoveFile(szTempFile, pszOldFile);
4368
4369 return -7;
4370 }
4371
4372 /* Seems to be left around on Novell filesystems */
4373 DeleteFile(szTempFile);
4374
4375 /* finally, remove the empty old file */
4376 if (!DeleteFile(pszOldFile))
4377 return -8;
4378
4379 return 0; /* success */
4380}
4381
4382/*
4383 * Get the default shell for the current hardware platform
4384 */
4385 char *
4386default_shell()
4387{
4388 char* psz = NULL;
4389
4390 PlatformId();
4391
4392 if (g_PlatformId == VER_PLATFORM_WIN32_NT) /* Windows NT */
4393 psz = "cmd.exe";
4394 else if (g_PlatformId == VER_PLATFORM_WIN32_WINDOWS) /* Windows 95 */
4395 psz = "command.com";
4396
4397 return psz;
4398}
4399
4400/*
4401 * mch_access() extends access() to do more detailed check on network drives.
4402 * Returns 0 if file "n" has access rights according to "p", -1 otherwise.
4403 */
4404 int
4405mch_access(char *n, int p)
4406{
4407 HANDLE hFile;
4408 DWORD am;
4409 int retval = -1; /* default: fail */
4410#ifdef FEAT_MBYTE
4411 WCHAR *wn = NULL;
4412
4413 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4414 wn = enc_to_ucs2(n, NULL);
4415#endif
4416
4417 if (mch_isdir(n))
4418 {
4419 char TempName[_MAX_PATH + 16] = "";
4420#ifdef FEAT_MBYTE
4421 WCHAR TempNameW[_MAX_PATH + 16] = L"";
4422#endif
4423
4424 if (p & R_OK)
4425 {
4426 /* Read check is performed by seeing if we can do a find file on
4427 * the directory for any file. */
4428#ifdef FEAT_MBYTE
4429 if (wn != NULL)
4430 {
4431 int i;
4432 WIN32_FIND_DATAW d;
4433
4434 for (i = 0; i < _MAX_PATH && wn[i] != 0; ++i)
4435 TempNameW[i] = wn[i];
4436 if (TempNameW[i - 1] != '\\' && TempNameW[i - 1] != '/')
4437 TempNameW[i++] = '\\';
4438 TempNameW[i++] = '*';
4439 TempNameW[i++] = 0;
4440
4441 hFile = FindFirstFileW(TempNameW, &d);
4442 if (hFile == INVALID_HANDLE_VALUE)
4443 {
4444 if (GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
4445 goto getout;
4446
4447 /* Retry with non-wide function (for Windows 98). */
4448 vim_free(wn);
4449 wn = NULL;
4450 }
4451 else
4452 (void)FindClose(hFile);
4453 }
4454 if (wn == NULL)
4455#endif
4456 {
4457 char *pch;
4458 WIN32_FIND_DATA d;
4459
4460 STRNCPY(TempName, n, _MAX_PATH);
4461 pch = TempName + STRLEN(TempName) - 1;
4462 if (*pch != '\\' && *pch != '/')
4463 *++pch = '\\';
4464 *++pch = '*';
4465 *++pch = NUL;
4466
4467 hFile = FindFirstFile(TempName, &d);
4468 if (hFile == INVALID_HANDLE_VALUE)
4469 goto getout;
4470 (void)FindClose(hFile);
4471 }
4472 }
4473
4474 if (p & W_OK)
4475 {
4476 /* Trying to create a temporary file in the directory should catch
4477 * directories on read-only network shares. However, in
4478 * directories whose ACL allows writes but denies deletes will end
4479 * up keeping the temporary file :-(. */
4480#ifdef FEAT_MBYTE
4481 if (wn != NULL)
4482 {
4483 if (!GetTempFileNameW(wn, L"VIM", 0, TempNameW))
4484 {
4485 if (GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
4486 goto getout;
4487
4488 /* Retry with non-wide function (for Windows 98). */
4489 vim_free(wn);
4490 wn = NULL;
4491 }
4492 else
4493 DeleteFileW(TempNameW);
4494 }
4495 if (wn == NULL)
4496#endif
4497 {
4498 if (!GetTempFileName(n, "VIM", 0, TempName))
4499 goto getout;
4500 mch_remove((char_u *)TempName);
4501 }
4502 }
4503 }
4504 else
4505 {
4506 /* Trying to open the file for the required access does ACL, read-only
4507 * network share, and file attribute checks. */
4508 am = ((p & W_OK) ? GENERIC_WRITE : 0)
4509 | ((p & R_OK) ? GENERIC_READ : 0);
4510#ifdef FEAT_MBYTE
4511 if (wn != NULL)
4512 {
4513 hFile = CreateFileW(wn, am, 0, NULL, OPEN_EXISTING, 0, NULL);
4514 if (hFile == INVALID_HANDLE_VALUE
4515 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
4516 {
4517 /* Retry with non-wide function (for Windows 98). */
4518 vim_free(wn);
4519 wn = NULL;
4520 }
4521 }
4522 if (wn == NULL)
4523#endif
4524 hFile = CreateFile(n, am, 0, NULL, OPEN_EXISTING, 0, NULL);
4525 if (hFile == INVALID_HANDLE_VALUE)
4526 goto getout;
4527 CloseHandle(hFile);
4528 }
4529
4530 retval = 0; /* success */
4531getout:
4532#ifdef FEAT_MBYTE
4533 vim_free(wn);
4534#endif
4535 return retval;
4536}
4537
4538#if defined(FEAT_MBYTE) || defined(PROTO)
4539/*
4540 * Version of open() that may use ucs2 file name.
4541 */
4542 int
4543mch_open(char *name, int flags, int mode)
4544{
4545 WCHAR *wn;
4546 int f;
4547
4548 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage
4549# ifdef __BORLANDC__
4550 /* Wide functions of Borland C 5.5 do not work on Windows 98. */
4551 && g_PlatformId == VER_PLATFORM_WIN32_NT
4552# endif
4553 )
4554 {
4555 wn = enc_to_ucs2(name, NULL);
4556 if (wn != NULL)
4557 {
4558 f = _wopen(wn, flags, mode);
4559 vim_free(wn);
4560 if (f >= 0)
4561 return f;
4562 /* Retry with non-wide function (for Windows 98). Can't use
4563 * GetLastError() here and it's unclear what errno gets set to if
4564 * the _wopen() fails for missing wide functions. */
4565 }
4566 }
4567
4568 return open(name, flags, mode);
4569}
4570
4571/*
4572 * Version of fopen() that may use ucs2 file name.
4573 */
4574 FILE *
4575mch_fopen(char *name, char *mode)
4576{
4577 WCHAR *wn, *wm;
4578 FILE *f = NULL;
4579
4580 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage
4581# ifdef __BORLANDC__
4582 /* Wide functions of Borland C 5.5 do not work on Windows 98. */
4583 && g_PlatformId == VER_PLATFORM_WIN32_NT
4584# endif
4585 )
4586 {
4587 wn = enc_to_ucs2(name, NULL);
4588 wm = enc_to_ucs2(mode, NULL);
4589 if (wn != NULL && wm != NULL)
4590 f = _wfopen(wn, wm);
4591 vim_free(wn);
4592 vim_free(wm);
4593 if (f != NULL)
4594 return f;
4595 /* Retry with non-wide function (for Windows 98). Can't use
4596 * GetLastError() here and it's unclear what errno gets set to if
4597 * the _wfopen() fails for missing wide functions. */
4598 }
4599
4600 return fopen(name, mode);
4601}
4602#endif
4603
4604#ifdef FEAT_MBYTE
4605/*
4606 * SUB STREAM (aka info stream) handling:
4607 *
4608 * NTFS can have sub streams for each file. Normal contents of file is
4609 * stored in the main stream, and extra contents (author information and
4610 * title and so on) can be stored in sub stream. After Windows 2000, user
4611 * can access and store those informations in sub streams via explorer's
4612 * property menuitem in right click menu. Those informations in sub streams
4613 * were lost when copying only the main stream. So we have to copy sub
4614 * streams.
4615 *
4616 * Incomplete explanation:
4617 * http://msdn.microsoft.com/library/en-us/dnw2k/html/ntfs5.asp
4618 * More useful info and an example:
4619 * http://www.sysinternals.com/ntw2k/source/misc.shtml#streams
4620 */
4621
4622/*
4623 * Copy info stream data "substream". Read from the file with BackupRead(sh)
4624 * and write to stream "substream" of file "to".
4625 * Errors are ignored.
4626 */
4627 static void
4628copy_substream(HANDLE sh, void *context, WCHAR *to, WCHAR *substream, long len)
4629{
4630 HANDLE hTo;
4631 WCHAR *to_name;
4632
4633 to_name = malloc((wcslen(to) + wcslen(substream) + 1) * sizeof(WCHAR));
4634 wcscpy(to_name, to);
4635 wcscat(to_name, substream);
4636
4637 hTo = CreateFileW(to_name, GENERIC_WRITE, 0, NULL, OPEN_ALWAYS,
4638 FILE_ATTRIBUTE_NORMAL, NULL);
4639 if (hTo != INVALID_HANDLE_VALUE)
4640 {
4641 long done;
4642 DWORD todo;
4643 DWORD readcnt, written;
4644 char buf[4096];
4645
4646 /* Copy block of bytes at a time. Abort when something goes wrong. */
4647 for (done = 0; done < len; done += written)
4648 {
4649 /* (size_t) cast for Borland C 5.5 */
4650 todo = (size_t)(len - done) > sizeof(buf) ? sizeof(buf)
4651 : (size_t)(len - done);
4652 if (!BackupRead(sh, (LPBYTE)buf, todo, &readcnt,
4653 FALSE, FALSE, context)
4654 || readcnt != todo
4655 || !WriteFile(hTo, buf, todo, &written, NULL)
4656 || written != todo)
4657 break;
4658 }
4659 CloseHandle(hTo);
4660 }
4661
4662 free(to_name);
4663}
4664
4665/*
4666 * Copy info streams from file "from" to file "to".
4667 */
4668 static void
4669copy_infostreams(char_u *from, char_u *to)
4670{
4671 WCHAR *fromw;
4672 WCHAR *tow;
4673 HANDLE sh;
4674 WIN32_STREAM_ID sid;
4675 int headersize;
4676 WCHAR streamname[_MAX_PATH];
4677 DWORD readcount;
4678 void *context = NULL;
4679 DWORD lo, hi;
4680 int len;
4681
4682 /* Convert the file names to wide characters. */
4683 fromw = enc_to_ucs2(from, NULL);
4684 tow = enc_to_ucs2(to, NULL);
4685 if (fromw != NULL && tow != NULL)
4686 {
4687 /* Open the file for reading. */
4688 sh = CreateFileW(fromw, GENERIC_READ, FILE_SHARE_READ, NULL,
4689 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
4690 if (sh != INVALID_HANDLE_VALUE)
4691 {
4692 /* Use BackupRead() to find the info streams. Repeat until we
4693 * have done them all.*/
4694 for (;;)
4695 {
4696 /* Get the header to find the length of the stream name. If
4697 * the "readcount" is zero we have done all info streams. */
4698 ZeroMemory(&sid, sizeof(WIN32_STREAM_ID));
4699 headersize = (char *)&sid.cStreamName - (char *)&sid.dwStreamId;
4700 if (!BackupRead(sh, (LPBYTE)&sid, headersize,
4701 &readcount, FALSE, FALSE, &context)
4702 || readcount == 0)
4703 break;
4704
4705 /* We only deal with streams that have a name. The normal
4706 * file data appears to be without a name, even though docs
4707 * suggest it is called "::$DATA". */
4708 if (sid.dwStreamNameSize > 0)
4709 {
4710 /* Read the stream name. */
4711 if (!BackupRead(sh, (LPBYTE)streamname,
4712 sid.dwStreamNameSize,
4713 &readcount, FALSE, FALSE, &context))
4714 break;
4715
4716 /* Copy an info stream with a name ":anything:$DATA".
4717 * Skip "::$DATA", it has no stream name (examples suggest
4718 * it might be used for the normal file contents).
4719 * Note that BackupRead() counts bytes, but the name is in
4720 * wide characters. */
4721 len = readcount / sizeof(WCHAR);
4722 streamname[len] = 0;
4723 if (len > 7 && wcsicmp(streamname + len - 6,
4724 L":$DATA") == 0)
4725 {
4726 streamname[len - 6] = 0;
4727 copy_substream(sh, &context, tow, streamname,
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00004728 (long)sid.Size.u.LowPart);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004729 }
4730 }
4731
4732 /* Advance to the next stream. We might try seeking too far,
4733 * but BackupSeek() doesn't skip over stream borders, thus
4734 * that's OK. */
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00004735 (void)BackupSeek(sh, sid.Size.LowPart, sid.Size.u.HighPart,
Bram Moolenaar071d4272004-06-13 20:20:40 +00004736 &lo, &hi, &context);
4737 }
4738
4739 /* Clear the context. */
4740 (void)BackupRead(sh, NULL, 0, &readcount, TRUE, FALSE, &context);
4741
4742 CloseHandle(sh);
4743 }
4744 }
4745 vim_free(fromw);
4746 vim_free(tow);
4747}
4748#endif
4749
4750/*
4751 * Copy file attributes from file "from" to file "to".
4752 * For Windows NT and later we copy info streams.
4753 * Always returns zero, errors are ignored.
4754 */
4755 int
4756mch_copy_file_attribute(char_u *from, char_u *to)
4757{
4758#ifdef FEAT_MBYTE
4759 /* File streams only work on Windows NT and later. */
4760 PlatformId();
4761 if (g_PlatformId == VER_PLATFORM_WIN32_NT)
4762 copy_infostreams(from, to);
4763#endif
4764 return 0;
4765}
4766
4767#if defined(MYRESETSTKOFLW) || defined(PROTO)
4768/*
4769 * Recreate a destroyed stack guard page in win32.
4770 * Written by Benjamin Peterson.
4771 */
4772
4773/* These magic numbers are from the MS header files */
4774#define MIN_STACK_WIN9X 17
4775#define MIN_STACK_WINNT 2
4776
4777/*
4778 * This function does the same thing as _resetstkoflw(), which is only
4779 * available in DevStudio .net and later.
4780 * Returns 0 for failure, 1 for success.
4781 */
4782 int
4783myresetstkoflw(void)
4784{
4785 BYTE *pStackPtr;
4786 BYTE *pGuardPage;
4787 BYTE *pStackBase;
4788 BYTE *pLowestPossiblePage;
4789 MEMORY_BASIC_INFORMATION mbi;
4790 SYSTEM_INFO si;
4791 DWORD nPageSize;
4792 DWORD dummy;
4793
4794 /* This code will not work on win32s. */
4795 PlatformId();
4796 if (g_PlatformId == VER_PLATFORM_WIN32s)
4797 return 0;
4798
4799 /* We need to know the system page size. */
4800 GetSystemInfo(&si);
4801 nPageSize = si.dwPageSize;
4802
4803 /* ...and the current stack pointer */
4804 pStackPtr = (BYTE*)_alloca(1);
4805
4806 /* ...and the base of the stack. */
4807 if (VirtualQuery(pStackPtr, &mbi, sizeof mbi) == 0)
4808 return 0;
4809 pStackBase = (BYTE*)mbi.AllocationBase;
4810
4811 /* ...and the page thats min_stack_req pages away from stack base; this is
4812 * the lowest page we could use. */
4813 pLowestPossiblePage = pStackBase + ((g_PlatformId == VER_PLATFORM_WIN32_NT)
4814 ? MIN_STACK_WINNT : MIN_STACK_WIN9X) * nPageSize;
4815
4816 /* On Win95, we want the next page down from the end of the stack. */
4817 if (g_PlatformId == VER_PLATFORM_WIN32_WINDOWS)
4818 {
4819 /* Find the page that's only 1 page down from the page that the stack
4820 * ptr is in. */
4821 pGuardPage = (BYTE*)((DWORD)nPageSize * (((DWORD)pStackPtr
4822 / (DWORD)nPageSize) - 1));
4823 if (pGuardPage < pLowestPossiblePage)
4824 return 0;
4825
4826 /* Apply the noaccess attribute to the page -- there's no guard
4827 * attribute in win95-type OSes. */
4828 if (!VirtualProtect(pGuardPage, nPageSize, PAGE_NOACCESS, &dummy))
4829 return 0;
4830 }
4831 else
4832 {
4833 /* On NT, however, we want the first committed page in the stack Start
4834 * at the stack base and move forward through memory until we find a
4835 * committed block. */
4836 BYTE *pBlock = pStackBase;
4837
4838 while (1)
4839 {
4840 if (VirtualQuery(pBlock, &mbi, sizeof mbi) == 0)
4841 return 0;
4842
4843 pBlock += mbi.RegionSize;
4844
4845 if (mbi.State & MEM_COMMIT)
4846 break;
4847 }
4848
4849 /* mbi now describes the first committed block in the stack. */
4850 if (mbi.Protect & PAGE_GUARD)
4851 return 1;
4852
4853 /* decide where the guard page should start */
4854 if ((long_u)(mbi.BaseAddress) < (long_u)pLowestPossiblePage)
4855 pGuardPage = pLowestPossiblePage;
4856 else
4857 pGuardPage = (BYTE*)mbi.BaseAddress;
4858
4859 /* allocate the guard page */
4860 if (!VirtualAlloc(pGuardPage, nPageSize, MEM_COMMIT, PAGE_READWRITE))
4861 return 0;
4862
4863 /* apply the guard attribute to the page */
4864 if (!VirtualProtect(pGuardPage, nPageSize, PAGE_READWRITE | PAGE_GUARD,
4865 &dummy))
4866 return 0;
4867 }
4868
4869 return 1;
4870}
4871
4872#endif