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