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