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