blob: 3184e2eb818d19c3e3369ea85f3cd292fb8c89ba [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 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00001328/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00001329 int
1330mch_inchar(
1331 char_u *buf,
1332 int maxlen,
1333 long time,
1334 int tb_change_cnt)
1335{
1336#ifndef FEAT_GUI_W32 /* this isn't used for the GUI */
1337
1338 int len;
1339 int c;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001340#define TYPEAHEADLEN 20
1341 static char_u typeahead[TYPEAHEADLEN]; /* previously typed bytes. */
1342 static int typeaheadlen = 0;
1343
1344 /* First use any typeahead that was kept because "buf" was too small. */
1345 if (typeaheadlen > 0)
1346 goto theend;
1347
1348#ifdef FEAT_SNIFF
1349 if (want_sniff_request)
1350 {
1351 if (sniff_request_waiting)
1352 {
1353 /* return K_SNIFF */
1354 typeahead[typeaheadlen++] = CSI;
1355 typeahead[typeaheadlen++] = (char_u)KS_EXTRA;
1356 typeahead[typeaheadlen++] = (char_u)KE_SNIFF;
1357 sniff_request_waiting = 0;
1358 want_sniff_request = 0;
1359 goto theend;
1360 }
1361 else if (time < 0 || time > 250)
1362 {
1363 /* don't wait too long, a request might be pending */
1364 time = 250;
1365 }
1366 }
1367#endif
1368
1369 if (time >= 0)
1370 {
1371 if (!WaitForChar(time)) /* no character available */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001372 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001373 }
1374 else /* time == -1, wait forever */
1375 {
1376 mch_set_winsize_now(); /* Allow winsize changes from now on */
1377
Bram Moolenaar3918c952005-03-15 22:34:55 +00001378 /*
1379 * If there is no character available within 2 seconds (default)
1380 * write the autoscript file to disk. Or cause the CursorHold event
1381 * to be triggered.
1382 */
1383 if (!WaitForChar(p_ut))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001384 {
1385#ifdef FEAT_AUTOCMD
Bram Moolenaar3918c952005-03-15 22:34:55 +00001386 if (!did_cursorhold && has_cursorhold()
1387 && get_real_state() == NORMAL_BUSY && maxlen >= 3)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001388 {
Bram Moolenaar3918c952005-03-15 22:34:55 +00001389 buf[0] = K_SPECIAL;
1390 buf[1] = KS_EXTRA;
1391 buf[2] = (int)KE_CURSORHOLD;
1392 return 3;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001393 }
Bram Moolenaar3918c952005-03-15 22:34:55 +00001394 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00001395#endif
1396 updatescript(0);
1397 }
1398 }
1399
1400 /*
1401 * Try to read as many characters as there are, until the buffer is full.
1402 */
1403
1404 /* we will get at least one key. Get more if they are available. */
1405 g_fCBrkPressed = FALSE;
1406
1407#ifdef MCH_WRITE_DUMP
1408 if (fdDump)
1409 fputc('[', fdDump);
1410#endif
1411
1412 /* Keep looping until there is something in the typeahead buffer and more
1413 * to get and still room in the buffer (up to two bytes for a char and
1414 * three bytes for a modifier). */
1415 while ((typeaheadlen == 0 || WaitForChar(0L))
1416 && typeaheadlen + 5 <= TYPEAHEADLEN)
1417 {
1418 if (typebuf_changed(tb_change_cnt))
1419 {
1420 /* "buf" may be invalid now if a client put something in the
1421 * typeahead buffer and "buf" is in the typeahead buffer. */
1422 typeaheadlen = 0;
1423 break;
1424 }
1425#ifdef FEAT_MOUSE
1426 if (g_nMouseClick != -1)
1427 {
1428# ifdef MCH_WRITE_DUMP
1429 if (fdDump)
1430 fprintf(fdDump, "{%02x @ %d, %d}",
1431 g_nMouseClick, g_xMouse, g_yMouse);
1432# endif
1433 typeahead[typeaheadlen++] = ESC + 128;
1434 typeahead[typeaheadlen++] = 'M';
1435 typeahead[typeaheadlen++] = g_nMouseClick;
1436 typeahead[typeaheadlen++] = g_xMouse + '!';
1437 typeahead[typeaheadlen++] = g_yMouse + '!';
1438 g_nMouseClick = -1;
1439 }
1440 else
1441#endif
1442 {
1443 char_u ch2 = NUL;
1444 int modifiers = 0;
1445
1446 c = tgetch(&modifiers, &ch2);
1447
1448 if (typebuf_changed(tb_change_cnt))
1449 {
1450 /* "buf" may be invalid now if a client put something in the
1451 * typeahead buffer and "buf" is in the typeahead buffer. */
1452 typeaheadlen = 0;
1453 break;
1454 }
1455
1456 if (c == Ctrl_C && ctrl_c_interrupts)
1457 {
1458#if defined(FEAT_CLIENTSERVER)
1459 trash_input_buf();
1460#endif
1461 got_int = TRUE;
1462 }
1463
1464#ifdef FEAT_MOUSE
1465 if (g_nMouseClick == -1)
1466#endif
1467 {
1468 int n = 1;
1469
1470 /* A key may have one or two bytes. */
1471 typeahead[typeaheadlen] = c;
1472 if (ch2 != NUL)
1473 {
1474 typeahead[typeaheadlen + 1] = ch2;
1475 ++n;
1476 }
1477#ifdef FEAT_MBYTE
1478 /* Only convert normal characters, not special keys. Need to
1479 * convert before applying ALT, otherwise mapping <M-x> breaks
1480 * when 'tenc' is set. */
1481 if (input_conv.vc_type != CONV_NONE
1482 && (ch2 == NUL || c != K_NUL))
1483 n = convert_input(typeahead + typeaheadlen, n,
1484 TYPEAHEADLEN - typeaheadlen);
1485#endif
1486
1487 /* Use the ALT key to set the 8th bit of the character
1488 * when it's one byte, the 8th bit isn't set yet and not
1489 * using a double-byte encoding (would become a lead
1490 * byte). */
1491 if ((modifiers & MOD_MASK_ALT)
1492 && n == 1
1493 && (typeahead[typeaheadlen] & 0x80) == 0
1494#ifdef FEAT_MBYTE
1495 && !enc_dbcs
1496#endif
1497 )
1498 {
1499 typeahead[typeaheadlen] |= 0x80;
1500 modifiers &= ~MOD_MASK_ALT;
1501 }
1502
1503 if (modifiers != 0)
1504 {
1505 /* Prepend modifiers to the character. */
1506 mch_memmove(typeahead + typeaheadlen + 3,
1507 typeahead + typeaheadlen, n);
1508 typeahead[typeaheadlen++] = K_SPECIAL;
1509 typeahead[typeaheadlen++] = (char_u)KS_MODIFIER;
1510 typeahead[typeaheadlen++] = modifiers;
1511 }
1512
1513 typeaheadlen += n;
1514
1515#ifdef MCH_WRITE_DUMP
1516 if (fdDump)
1517 fputc(c, fdDump);
1518#endif
1519 }
1520 }
1521 }
1522
1523#ifdef MCH_WRITE_DUMP
1524 if (fdDump)
1525 {
1526 fputs("]\n", fdDump);
1527 fflush(fdDump);
1528 }
1529#endif
1530
Bram Moolenaar071d4272004-06-13 20:20:40 +00001531theend:
1532 /* Move typeahead to "buf", as much as fits. */
1533 len = 0;
1534 while (len < maxlen && typeaheadlen > 0)
1535 {
1536 buf[len++] = typeahead[0];
1537 mch_memmove(typeahead, typeahead + 1, --typeaheadlen);
1538 }
1539 return len;
1540
1541#else /* FEAT_GUI_W32 */
1542 return 0;
1543#endif /* FEAT_GUI_W32 */
1544}
1545
1546#ifndef __MINGW32__
1547# include <shellapi.h> /* required for FindExecutable() */
1548#endif
1549
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001550/*
1551 * Return TRUE if "name" is in $PATH.
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00001552 * TODO: Should somehow check if it's really executable.
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001553 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001554 static int
1555executable_exists(char *name)
1556{
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001557 char *dum;
1558 char fname[_MAX_PATH];
Bram Moolenaar071d4272004-06-13 20:20:40 +00001559
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001560#ifdef FEAT_MBYTE
1561 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001562 {
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001563 WCHAR *p = enc_to_ucs2(name, NULL);
1564 WCHAR fnamew[_MAX_PATH];
1565 WCHAR *dumw;
1566 long n;
1567
1568 if (p != NULL)
1569 {
1570 n = (long)SearchPathW(NULL, p, NULL, _MAX_PATH, fnamew, &dumw);
1571 vim_free(p);
1572 if (n > 0 || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
1573 {
1574 if (n == 0)
1575 return FALSE;
1576 if (GetFileAttributesW(fnamew) & FILE_ATTRIBUTE_DIRECTORY)
1577 return FALSE;
1578 return TRUE;
1579 }
1580 /* Retry with non-wide function (for Windows 98). */
1581 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001582 }
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001583#endif
1584 if (SearchPath(NULL, name, NULL, _MAX_PATH, fname, &dum) == 0)
1585 return FALSE;
1586 if (mch_isdir(fname))
1587 return FALSE;
1588 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001589}
1590
1591#ifdef FEAT_GUI_W32
1592
1593/*
1594 * GUI version of mch_init().
1595 */
1596 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001597mch_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001598{
1599#ifndef __MINGW32__
1600 extern int _fmode;
1601#endif
1602
1603 /* Let critical errors result in a failure, not in a dialog box. Required
1604 * for the timestamp test to work on removed floppies. */
1605 SetErrorMode(SEM_FAILCRITICALERRORS);
1606
1607 _fmode = O_BINARY; /* we do our own CR-LF translation */
1608
1609 /* Specify window size. Is there a place to get the default from? */
1610 Rows = 25;
1611 Columns = 80;
1612
1613 /* Look for 'vimrun' */
1614 if (!gui_is_win32s())
1615 {
1616 char_u vimrun_location[_MAX_PATH + 4];
1617
1618 /* First try in same directory as gvim.exe */
1619 STRCPY(vimrun_location, exe_name);
1620 STRCPY(gettail(vimrun_location), "vimrun.exe");
1621 if (mch_getperm(vimrun_location) >= 0)
1622 {
1623 if (*skiptowhite(vimrun_location) != NUL)
1624 {
1625 /* Enclose path with white space in double quotes. */
1626 mch_memmove(vimrun_location + 1, vimrun_location,
1627 STRLEN(vimrun_location) + 1);
1628 *vimrun_location = '"';
1629 STRCPY(gettail(vimrun_location), "vimrun\" ");
1630 }
1631 else
1632 STRCPY(gettail(vimrun_location), "vimrun ");
1633
1634 vimrun_path = (char *)vim_strsave(vimrun_location);
1635 s_dont_use_vimrun = FALSE;
1636 }
1637 else if (executable_exists("vimrun.exe"))
1638 s_dont_use_vimrun = FALSE;
1639
1640 /* Don't give the warning for a missing vimrun.exe right now, but only
1641 * when vimrun was supposed to be used. Don't bother people that do
1642 * not need vimrun.exe. */
1643 if (s_dont_use_vimrun)
1644 need_vimrun_warning = TRUE;
1645 }
1646
1647 /*
1648 * If "finstr.exe" doesn't exist, use "grep -n" for 'grepprg'.
1649 * Otherwise the default "findstr /n" is used.
1650 */
1651 if (!executable_exists("findstr.exe"))
1652 set_option_value((char_u *)"grepprg", 0, (char_u *)"grep -n", 0);
1653
1654#ifdef FEAT_CLIPBOARD
1655 clip_init(TRUE);
1656
1657 /*
1658 * Vim's own clipboard format recognises whether the text is char, line, or
1659 * rectangular block. Only useful for copying between two Vims.
1660 * "VimClipboard" was used for previous versions, using the first
1661 * character to specify MCHAR, MLINE or MBLOCK.
1662 */
1663 clip_star.format = RegisterClipboardFormat("VimClipboard2");
1664 clip_star.format_raw = RegisterClipboardFormat("VimRawBytes");
1665#endif
1666}
1667
1668
1669#else /* FEAT_GUI_W32 */
1670
1671#define SRWIDTH(sr) ((sr).Right - (sr).Left + 1)
1672#define SRHEIGHT(sr) ((sr).Bottom - (sr).Top + 1)
1673
1674/*
1675 * ClearConsoleBuffer()
1676 * Description:
1677 * Clears the entire contents of the console screen buffer, using the
1678 * specified attribute.
1679 * Returns:
1680 * TRUE on success
1681 */
1682 static BOOL
1683ClearConsoleBuffer(WORD wAttribute)
1684{
1685 CONSOLE_SCREEN_BUFFER_INFO csbi;
1686 COORD coord;
1687 DWORD NumCells, dummy;
1688
1689 if (!GetConsoleScreenBufferInfo(g_hConOut, &csbi))
1690 return FALSE;
1691
1692 NumCells = csbi.dwSize.X * csbi.dwSize.Y;
1693 coord.X = 0;
1694 coord.Y = 0;
1695 if (!FillConsoleOutputCharacter(g_hConOut, ' ', NumCells,
1696 coord, &dummy))
1697 {
1698 return FALSE;
1699 }
1700 if (!FillConsoleOutputAttribute(g_hConOut, wAttribute, NumCells,
1701 coord, &dummy))
1702 {
1703 return FALSE;
1704 }
1705
1706 return TRUE;
1707}
1708
1709/*
1710 * FitConsoleWindow()
1711 * Description:
1712 * Checks if the console window will fit within given buffer dimensions.
1713 * Also, if requested, will shrink the window to fit.
1714 * Returns:
1715 * TRUE on success
1716 */
1717 static BOOL
1718FitConsoleWindow(
1719 COORD dwBufferSize,
1720 BOOL WantAdjust)
1721{
1722 CONSOLE_SCREEN_BUFFER_INFO csbi;
1723 COORD dwWindowSize;
1724 BOOL NeedAdjust = FALSE;
1725
1726 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
1727 {
1728 /*
1729 * A buffer resize will fail if the current console window does
1730 * not lie completely within that buffer. To avoid this, we might
1731 * have to move and possibly shrink the window.
1732 */
1733 if (csbi.srWindow.Right >= dwBufferSize.X)
1734 {
1735 dwWindowSize.X = SRWIDTH(csbi.srWindow);
1736 if (dwWindowSize.X > dwBufferSize.X)
1737 dwWindowSize.X = dwBufferSize.X;
1738 csbi.srWindow.Right = dwBufferSize.X - 1;
1739 csbi.srWindow.Left = dwBufferSize.X - dwWindowSize.X;
1740 NeedAdjust = TRUE;
1741 }
1742 if (csbi.srWindow.Bottom >= dwBufferSize.Y)
1743 {
1744 dwWindowSize.Y = SRHEIGHT(csbi.srWindow);
1745 if (dwWindowSize.Y > dwBufferSize.Y)
1746 dwWindowSize.Y = dwBufferSize.Y;
1747 csbi.srWindow.Bottom = dwBufferSize.Y - 1;
1748 csbi.srWindow.Top = dwBufferSize.Y - dwWindowSize.Y;
1749 NeedAdjust = TRUE;
1750 }
1751 if (NeedAdjust && WantAdjust)
1752 {
1753 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &csbi.srWindow))
1754 return FALSE;
1755 }
1756 return TRUE;
1757 }
1758
1759 return FALSE;
1760}
1761
1762typedef struct ConsoleBufferStruct
1763{
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001764 BOOL IsValid;
1765 CONSOLE_SCREEN_BUFFER_INFO Info;
1766 PCHAR_INFO Buffer;
1767 COORD BufferSize;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001768} ConsoleBuffer;
1769
1770/*
1771 * SaveConsoleBuffer()
1772 * Description:
1773 * Saves important information about the console buffer, including the
1774 * actual buffer contents. The saved information is suitable for later
1775 * restoration by RestoreConsoleBuffer().
1776 * Returns:
1777 * TRUE if all information was saved; FALSE otherwise
1778 * If FALSE, still sets cb->IsValid if buffer characteristics were saved.
1779 */
1780 static BOOL
1781SaveConsoleBuffer(
1782 ConsoleBuffer *cb)
1783{
1784 DWORD NumCells;
1785 COORD BufferCoord;
1786 SMALL_RECT ReadRegion;
1787 WORD Y, Y_incr;
1788
1789 if (cb == NULL)
1790 return FALSE;
1791
1792 if (!GetConsoleScreenBufferInfo(g_hConOut, &cb->Info))
1793 {
1794 cb->IsValid = FALSE;
1795 return FALSE;
1796 }
1797 cb->IsValid = TRUE;
1798
1799 /*
1800 * Allocate a buffer large enough to hold the entire console screen
1801 * buffer. If this ConsoleBuffer structure has already been initialized
1802 * with a buffer of the correct size, then just use that one.
1803 */
1804 if (!cb->IsValid || cb->Buffer == NULL ||
1805 cb->BufferSize.X != cb->Info.dwSize.X ||
1806 cb->BufferSize.Y != cb->Info.dwSize.Y)
1807 {
1808 cb->BufferSize.X = cb->Info.dwSize.X;
1809 cb->BufferSize.Y = cb->Info.dwSize.Y;
1810 NumCells = cb->BufferSize.X * cb->BufferSize.Y;
1811 if (cb->Buffer != NULL)
1812 vim_free(cb->Buffer);
1813 cb->Buffer = (PCHAR_INFO)alloc(NumCells * sizeof(CHAR_INFO));
1814 if (cb->Buffer == NULL)
1815 return FALSE;
1816 }
1817
1818 /*
1819 * We will now copy the console screen buffer into our buffer.
1820 * ReadConsoleOutput() seems to be limited as far as how much you
1821 * can read at a time. Empirically, this number seems to be about
1822 * 12000 cells (rows * columns). Start at position (0, 0) and copy
1823 * in chunks until it is all copied. The chunks will all have the
1824 * same horizontal characteristics, so initialize them now. The
1825 * height of each chunk will be (12000 / width).
1826 */
1827 BufferCoord.X = 0;
1828 ReadRegion.Left = 0;
1829 ReadRegion.Right = cb->Info.dwSize.X - 1;
1830 Y_incr = 12000 / cb->Info.dwSize.X;
1831 for (Y = 0; Y < cb->BufferSize.Y; Y += Y_incr)
1832 {
1833 /*
1834 * Read into position (0, Y) in our buffer.
1835 */
1836 BufferCoord.Y = Y;
1837 /*
1838 * Read the region whose top left corner is (0, Y) and whose bottom
1839 * right corner is (width - 1, Y + Y_incr - 1). This should define
1840 * a region of size width by Y_incr. Don't worry if this region is
1841 * too large for the remaining buffer; it will be cropped.
1842 */
1843 ReadRegion.Top = Y;
1844 ReadRegion.Bottom = Y + Y_incr - 1;
1845 if (!ReadConsoleOutput(g_hConOut, /* output handle */
1846 cb->Buffer, /* our buffer */
1847 cb->BufferSize, /* dimensions of our buffer */
1848 BufferCoord, /* offset in our buffer */
1849 &ReadRegion)) /* region to save */
1850 {
1851 vim_free(cb->Buffer);
1852 cb->Buffer = NULL;
1853 return FALSE;
1854 }
1855 }
1856
1857 return TRUE;
1858}
1859
1860/*
1861 * RestoreConsoleBuffer()
1862 * Description:
1863 * Restores important information about the console buffer, including the
1864 * actual buffer contents, if desired. The information to restore is in
1865 * the same format used by SaveConsoleBuffer().
1866 * Returns:
1867 * TRUE on success
1868 */
1869 static BOOL
1870RestoreConsoleBuffer(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001871 ConsoleBuffer *cb,
1872 BOOL RestoreScreen)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001873{
1874 COORD BufferCoord;
1875 SMALL_RECT WriteRegion;
1876
1877 if (cb == NULL || !cb->IsValid)
1878 return FALSE;
1879
1880 /*
1881 * Before restoring the buffer contents, clear the current buffer, and
1882 * restore the cursor position and window information. Doing this now
1883 * prevents old buffer contents from "flashing" onto the screen.
1884 */
1885 if (RestoreScreen)
1886 ClearConsoleBuffer(cb->Info.wAttributes);
1887
1888 FitConsoleWindow(cb->Info.dwSize, TRUE);
1889 if (!SetConsoleScreenBufferSize(g_hConOut, cb->Info.dwSize))
1890 return FALSE;
1891 if (!SetConsoleTextAttribute(g_hConOut, cb->Info.wAttributes))
1892 return FALSE;
1893
1894 if (!RestoreScreen)
1895 {
1896 /*
1897 * No need to restore the screen buffer contents, so we're done.
1898 */
1899 return TRUE;
1900 }
1901
1902 if (!SetConsoleCursorPosition(g_hConOut, cb->Info.dwCursorPosition))
1903 return FALSE;
1904 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &cb->Info.srWindow))
1905 return FALSE;
1906
1907 /*
1908 * Restore the screen buffer contents.
1909 */
1910 if (cb->Buffer != NULL)
1911 {
1912 BufferCoord.X = 0;
1913 BufferCoord.Y = 0;
1914 WriteRegion.Left = 0;
1915 WriteRegion.Top = 0;
1916 WriteRegion.Right = cb->Info.dwSize.X - 1;
1917 WriteRegion.Bottom = cb->Info.dwSize.Y - 1;
1918 if (!WriteConsoleOutput(g_hConOut, /* output handle */
1919 cb->Buffer, /* our buffer */
1920 cb->BufferSize, /* dimensions of our buffer */
1921 BufferCoord, /* offset in our buffer */
1922 &WriteRegion)) /* region to restore */
1923 {
1924 return FALSE;
1925 }
1926 }
1927
1928 return TRUE;
1929}
1930
1931#ifdef FEAT_RESTORE_ORIG_SCREEN
1932static ConsoleBuffer g_cbOrig = { 0 };
1933#endif
1934static ConsoleBuffer g_cbNonTermcap = { 0 };
1935static ConsoleBuffer g_cbTermcap = { 0 };
1936
1937#ifdef FEAT_TITLE
1938#ifdef __BORLANDC__
1939typedef HWND (__stdcall *GETCONSOLEWINDOWPROC)(VOID);
1940#else
1941typedef WINBASEAPI HWND (WINAPI *GETCONSOLEWINDOWPROC)(VOID);
1942#endif
1943char g_szOrigTitle[256] = { 0 };
1944HWND g_hWnd = NULL; /* also used in os_mswin.c */
1945static HICON g_hOrigIconSmall = NULL;
1946static HICON g_hOrigIcon = NULL;
1947static HICON g_hVimIcon = NULL;
1948static BOOL g_fCanChangeIcon = FALSE;
1949
1950/* ICON* are not defined in VC++ 4.0 */
1951#ifndef ICON_SMALL
1952#define ICON_SMALL 0
1953#endif
1954#ifndef ICON_BIG
1955#define ICON_BIG 1
1956#endif
1957/*
1958 * GetConsoleIcon()
1959 * Description:
1960 * Attempts to retrieve the small icon and/or the big icon currently in
1961 * use by a given window.
1962 * Returns:
1963 * TRUE on success
1964 */
1965 static BOOL
1966GetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001967 HWND hWnd,
1968 HICON *phIconSmall,
1969 HICON *phIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001970{
1971 if (hWnd == NULL)
1972 return FALSE;
1973
1974 if (phIconSmall != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001975 *phIconSmall = (HICON)SendMessage(hWnd, WM_GETICON,
1976 (WPARAM)ICON_SMALL, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001977 if (phIcon != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001978 *phIcon = (HICON)SendMessage(hWnd, WM_GETICON,
1979 (WPARAM)ICON_BIG, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001980 return TRUE;
1981}
1982
1983/*
1984 * SetConsoleIcon()
1985 * Description:
1986 * Attempts to change the small icon and/or the big icon currently in
1987 * use by a given window.
1988 * Returns:
1989 * TRUE on success
1990 */
1991 static BOOL
1992SetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001993 HWND hWnd,
1994 HICON hIconSmall,
1995 HICON hIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001996{
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001997 HICON hPrevIconSmall;
1998 HICON hPrevIcon;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001999
2000 if (hWnd == NULL)
2001 return FALSE;
2002
2003 if (hIconSmall != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002004 hPrevIconSmall = (HICON)SendMessage(hWnd, WM_SETICON,
2005 (WPARAM)ICON_SMALL, (LPARAM)hIconSmall);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002006 if (hIcon != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002007 hPrevIcon = (HICON)SendMessage(hWnd, WM_SETICON,
2008 (WPARAM)ICON_BIG,(LPARAM) hIcon);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002009 return TRUE;
2010}
2011
2012/*
2013 * SaveConsoleTitleAndIcon()
2014 * Description:
2015 * Saves the current console window title in g_szOrigTitle, for later
2016 * restoration. Also, attempts to obtain a handle to the console window,
2017 * and use it to save the small and big icons currently in use by the
2018 * console window. This is not always possible on some versions of Windows;
2019 * nor is it possible when running Vim remotely using Telnet (since the
2020 * console window the user sees is owned by a remote process).
2021 */
2022 static void
2023SaveConsoleTitleAndIcon(void)
2024{
2025 GETCONSOLEWINDOWPROC GetConsoleWindowProc;
2026
2027 /* Save the original title. */
2028 if (!GetConsoleTitle(g_szOrigTitle, sizeof(g_szOrigTitle)))
2029 return;
2030
2031 /*
2032 * Obtain a handle to the console window using GetConsoleWindow() from
2033 * KERNEL32.DLL; we need to handle in order to change the window icon.
2034 * This function only exists on NT-based Windows, starting with Windows
2035 * 2000. On older operating systems, we can't change the window icon
2036 * anyway.
2037 */
2038 if ((GetConsoleWindowProc = (GETCONSOLEWINDOWPROC)
2039 GetProcAddress(GetModuleHandle("KERNEL32.DLL"),
2040 "GetConsoleWindow")) != NULL)
2041 {
2042 g_hWnd = (*GetConsoleWindowProc)();
2043 }
2044 if (g_hWnd == NULL)
2045 return;
2046
2047 /* Save the original console window icon. */
2048 GetConsoleIcon(g_hWnd, &g_hOrigIconSmall, &g_hOrigIcon);
2049 if (g_hOrigIconSmall == NULL || g_hOrigIcon == NULL)
2050 return;
2051
2052 /* Extract the first icon contained in the Vim executable. */
2053 g_hVimIcon = ExtractIcon(NULL, exe_name, 0);
2054 if (g_hVimIcon != NULL)
2055 g_fCanChangeIcon = TRUE;
2056}
2057#endif
2058
2059static int g_fWindInitCalled = FALSE;
2060static int g_fTermcapMode = FALSE;
2061static CONSOLE_CURSOR_INFO g_cci;
2062static DWORD g_cmodein = 0;
2063static DWORD g_cmodeout = 0;
2064
2065/*
2066 * non-GUI version of mch_init().
2067 */
2068 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002069mch_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002070{
2071#ifndef FEAT_RESTORE_ORIG_SCREEN
2072 CONSOLE_SCREEN_BUFFER_INFO csbi;
2073#endif
2074#ifndef __MINGW32__
2075 extern int _fmode;
2076#endif
2077
2078 /* Let critical errors result in a failure, not in a dialog box. Required
2079 * for the timestamp test to work on removed floppies. */
2080 SetErrorMode(SEM_FAILCRITICALERRORS);
2081
2082 _fmode = O_BINARY; /* we do our own CR-LF translation */
2083 out_flush();
2084
2085 /* Obtain handles for the standard Console I/O devices */
2086 if (read_cmd_fd == 0)
2087 g_hConIn = GetStdHandle(STD_INPUT_HANDLE);
2088 else
2089 create_conin();
2090 g_hConOut = GetStdHandle(STD_OUTPUT_HANDLE);
2091
2092#ifdef FEAT_RESTORE_ORIG_SCREEN
2093 /* Save the initial console buffer for later restoration */
2094 SaveConsoleBuffer(&g_cbOrig);
2095 g_attrCurrent = g_attrDefault = g_cbOrig.Info.wAttributes;
2096#else
2097 /* Get current text attributes */
2098 GetConsoleScreenBufferInfo(g_hConOut, &csbi);
2099 g_attrCurrent = g_attrDefault = csbi.wAttributes;
2100#endif
2101 if (cterm_normal_fg_color == 0)
2102 cterm_normal_fg_color = (g_attrCurrent & 0xf) + 1;
2103 if (cterm_normal_bg_color == 0)
2104 cterm_normal_bg_color = ((g_attrCurrent >> 4) & 0xf) + 1;
2105
2106 /* set termcap codes to current text attributes */
2107 update_tcap(g_attrCurrent);
2108
2109 GetConsoleCursorInfo(g_hConOut, &g_cci);
2110 GetConsoleMode(g_hConIn, &g_cmodein);
2111 GetConsoleMode(g_hConOut, &g_cmodeout);
2112
2113#ifdef FEAT_TITLE
2114 SaveConsoleTitleAndIcon();
2115 /*
2116 * Set both the small and big icons of the console window to Vim's icon.
2117 * Note that Vim presently only has one size of icon (32x32), but it
2118 * automatically gets scaled down to 16x16 when setting the small icon.
2119 */
2120 if (g_fCanChangeIcon)
2121 SetConsoleIcon(g_hWnd, g_hVimIcon, g_hVimIcon);
2122#endif
2123
2124 ui_get_shellsize();
2125
2126#ifdef MCH_WRITE_DUMP
2127 fdDump = fopen("dump", "wt");
2128
2129 if (fdDump)
2130 {
2131 time_t t;
2132
2133 time(&t);
2134 fputs(ctime(&t), fdDump);
2135 fflush(fdDump);
2136 }
2137#endif
2138
2139 g_fWindInitCalled = TRUE;
2140
2141#ifdef FEAT_MOUSE
2142 g_fMouseAvail = GetSystemMetrics(SM_MOUSEPRESENT);
2143#endif
2144
2145#ifdef FEAT_CLIPBOARD
2146 clip_init(TRUE);
2147
2148 /*
2149 * Vim's own clipboard format recognises whether the text is char, line, or
2150 * rectangular block. Only useful for copying between two Vims.
2151 * "VimClipboard" was used for previous versions, using the first
2152 * character to specify MCHAR, MLINE or MBLOCK.
2153 */
2154 clip_star.format = RegisterClipboardFormat("VimClipboard2");
2155 clip_star.format_raw = RegisterClipboardFormat("VimRawBytes");
2156#endif
2157
2158 /* This will be NULL on anything but NT 4.0 */
2159 s_pfnGetConsoleKeyboardLayoutName =
2160 (PFNGCKLN) GetProcAddress(GetModuleHandle("kernel32.dll"),
2161 "GetConsoleKeyboardLayoutNameA");
2162}
2163
2164/*
2165 * non-GUI version of mch_exit().
2166 * Shut down and exit with status `r'
2167 * Careful: mch_exit() may be called before mch_init()!
2168 */
2169 void
2170mch_exit(int r)
2171{
2172 stoptermcap();
2173
2174 if (g_fWindInitCalled)
2175 settmode(TMODE_COOK);
2176
2177 ml_close_all(TRUE); /* remove all memfiles */
2178
2179 if (g_fWindInitCalled)
2180 {
2181#ifdef FEAT_TITLE
2182 mch_restore_title(3);
2183 /*
2184 * Restore both the small and big icons of the console window to
2185 * what they were at startup. Don't do this when the window is
2186 * closed, Vim would hang here.
2187 */
2188 if (g_fCanChangeIcon && !g_fForceExit)
2189 SetConsoleIcon(g_hWnd, g_hOrigIconSmall, g_hOrigIcon);
2190#endif
2191
2192#ifdef MCH_WRITE_DUMP
2193 if (fdDump)
2194 {
2195 time_t t;
2196
2197 time(&t);
2198 fputs(ctime(&t), fdDump);
2199 fclose(fdDump);
2200 }
2201 fdDump = NULL;
2202#endif
2203 }
2204
2205 SetConsoleCursorInfo(g_hConOut, &g_cci);
2206 SetConsoleMode(g_hConIn, g_cmodein);
2207 SetConsoleMode(g_hConOut, g_cmodeout);
2208
2209#ifdef DYNAMIC_GETTEXT
2210 dyn_libintl_end();
2211#endif
2212
2213 exit(r);
2214}
2215#endif /* !FEAT_GUI_W32 */
2216
Bram Moolenaar071d4272004-06-13 20:20:40 +00002217/*
2218 * Do we have an interactive window?
2219 */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00002220/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00002221 int
2222mch_check_win(
2223 int argc,
2224 char **argv)
2225{
2226 get_exe_name();
2227
2228#ifdef FEAT_GUI_W32
2229 return OK; /* GUI always has a tty */
2230#else
2231 if (isatty(1))
2232 return OK;
2233 return FAIL;
2234#endif
2235}
2236
2237
2238/*
2239 * fname_case(): Set the case of the file name, if it already exists.
2240 * When "len" is > 0, also expand short to long filenames.
2241 */
2242 void
2243fname_case(
2244 char_u *name,
2245 int len)
2246{
2247 char szTrueName[_MAX_PATH + 2];
2248 char *ptrue, *ptruePrev;
2249 char *porig, *porigPrev;
2250 int flen;
2251 WIN32_FIND_DATA fb;
2252 HANDLE hFind;
2253 int c;
2254
2255 flen = (name != NULL) ? (int)STRLEN(name) : 0;
2256 if (flen == 0 || flen > _MAX_PATH)
2257 return;
2258
2259 slash_adjust(name);
2260
2261 /* Build the new name in szTrueName[] one component at a time. */
2262 porig = name;
2263 ptrue = szTrueName;
2264
2265 if (isalpha(porig[0]) && porig[1] == ':')
2266 {
2267 /* copy leading drive letter */
2268 *ptrue++ = *porig++;
2269 *ptrue++ = *porig++;
2270 *ptrue = NUL; /* in case nothing follows */
2271 }
2272
2273 while (*porig != NUL)
2274 {
2275 /* copy \ characters */
2276 while (*porig == psepc)
2277 *ptrue++ = *porig++;
2278
2279 ptruePrev = ptrue;
2280 porigPrev = porig;
2281 while (*porig != NUL && *porig != psepc)
2282 {
2283#ifdef FEAT_MBYTE
2284 int l;
2285
2286 if (enc_dbcs)
2287 {
2288 l = (*mb_ptr2len_check)(porig);
2289 while (--l >= 0)
2290 *ptrue++ = *porig++;
2291 }
2292 else
2293#endif
2294 *ptrue++ = *porig++;
2295 }
2296 *ptrue = NUL;
2297
2298 /* Skip "", "." and "..". */
2299 if (ptrue > ptruePrev
2300 && (ptruePrev[0] != '.'
2301 || (ptruePrev[1] != NUL
2302 && (ptruePrev[1] != '.' || ptruePrev[2] != NUL)))
2303 && (hFind = FindFirstFile(szTrueName, &fb))
2304 != INVALID_HANDLE_VALUE)
2305 {
2306 c = *porig;
2307 *porig = NUL;
2308
2309 /* Only use the match when it's the same name (ignoring case) or
2310 * expansion is allowed and there is a match with the short name
2311 * and there is enough room. */
2312 if (_stricoll(porigPrev, fb.cFileName) == 0
2313 || (len > 0
2314 && (_stricoll(porigPrev, fb.cAlternateFileName) == 0
2315 && (int)(ptruePrev - szTrueName)
2316 + (int)strlen(fb.cFileName) < len)))
2317 {
2318 STRCPY(ptruePrev, fb.cFileName);
2319
2320 /* Look for exact match and prefer it if found. Must be a
2321 * long name, otherwise there would be only one match. */
2322 while (FindNextFile(hFind, &fb))
2323 {
2324 if (*fb.cAlternateFileName != NUL
2325 && (strcoll(porigPrev, fb.cFileName) == 0
2326 || (len > 0
2327 && (_stricoll(porigPrev,
2328 fb.cAlternateFileName) == 0
2329 && (int)(ptruePrev - szTrueName)
2330 + (int)strlen(fb.cFileName) < len))))
2331 {
2332 STRCPY(ptruePrev, fb.cFileName);
2333 break;
2334 }
2335 }
2336 }
2337 FindClose(hFind);
2338 *porig = c;
2339 ptrue = ptruePrev + strlen(ptruePrev);
2340 }
2341 }
2342
2343 STRCPY(name, szTrueName);
2344}
2345
2346
2347/*
2348 * Insert user name in s[len].
2349 */
2350 int
2351mch_get_user_name(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002352 char_u *s,
2353 int len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002354{
2355 char szUserName[MAX_COMPUTERNAME_LENGTH + 1];
2356 DWORD cch = sizeof szUserName;
2357
2358 if (GetUserName(szUserName, &cch))
2359 {
2360 STRNCPY(s, szUserName, len);
2361 return OK;
2362 }
2363 s[0] = NUL;
2364 return FAIL;
2365}
2366
2367
2368/*
2369 * Insert host name in s[len].
2370 */
2371 void
2372mch_get_host_name(
2373 char_u *s,
2374 int len)
2375{
2376 DWORD cch = len;
2377
2378 if (!GetComputerName(s, &cch))
2379 {
2380 STRNCPY(s, "PC (Win32 Vim)", len);
2381 s[len - 1] = NUL; /* make sure it's terminated */
2382 }
2383}
2384
2385
2386/*
2387 * return process ID
2388 */
2389 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002390mch_get_pid(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002391{
2392 return (long)GetCurrentProcessId();
2393}
2394
2395
2396/*
2397 * Get name of current directory into buffer 'buf' of length 'len' bytes.
2398 * Return OK for success, FAIL for failure.
2399 */
2400 int
2401mch_dirname(
2402 char_u *buf,
2403 int len)
2404{
2405 /*
2406 * Originally this was:
2407 * return (getcwd(buf, len) != NULL ? OK : FAIL);
2408 * But the Win32s known bug list says that getcwd() doesn't work
2409 * so use the Win32 system call instead. <Negri>
2410 */
2411#ifdef FEAT_MBYTE
2412 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2413 {
2414 WCHAR wbuf[_MAX_PATH + 1];
2415
2416 if (GetCurrentDirectoryW(_MAX_PATH, wbuf) != 0)
2417 {
2418 char_u *p = ucs2_to_enc(wbuf, NULL);
2419
2420 if (p != NULL)
2421 {
2422 STRNCPY(buf, p, len - 1);
2423 buf[len - 1] = NUL;
2424 vim_free(p);
2425 return OK;
2426 }
2427 }
2428 /* Retry with non-wide function (for Windows 98). */
2429 }
2430#endif
2431 return (GetCurrentDirectory(len, buf) != 0 ? OK : FAIL);
2432}
2433
2434/*
2435 * get file permissions for `name'
2436 * -1 : error
2437 * else FILE_ATTRIBUTE_* defined in winnt.h
2438 */
2439 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002440mch_getperm(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002441{
2442#ifdef FEAT_MBYTE
2443 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2444 {
2445 WCHAR *p = enc_to_ucs2(name, NULL);
2446 long n;
2447
2448 if (p != NULL)
2449 {
2450 n = (long)GetFileAttributesW(p);
2451 vim_free(p);
2452 if (n >= 0 || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
2453 return n;
2454 /* Retry with non-wide function (for Windows 98). */
2455 }
2456 }
2457#endif
2458 return (long)GetFileAttributes((char *)name);
2459}
2460
2461
2462/*
2463 * set file permission for `name' to `perm'
2464 */
2465 int
2466mch_setperm(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002467 char_u *name,
2468 long perm)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002469{
2470 perm |= FILE_ATTRIBUTE_ARCHIVE; /* file has changed, set archive bit */
2471#ifdef FEAT_MBYTE
2472 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2473 {
2474 WCHAR *p = enc_to_ucs2(name, NULL);
2475 long n;
2476
2477 if (p != NULL)
2478 {
2479 n = (long)SetFileAttributesW(p, perm);
2480 vim_free(p);
2481 if (n || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
2482 return n ? OK : FAIL;
2483 /* Retry with non-wide function (for Windows 98). */
2484 }
2485 }
2486#endif
2487 return SetFileAttributes((char *)name, perm) ? OK : FAIL;
2488}
2489
2490/*
2491 * Set hidden flag for "name".
2492 */
2493 void
2494mch_hide(char_u *name)
2495{
2496 int perm;
2497#ifdef FEAT_MBYTE
2498 WCHAR *p = NULL;
2499
2500 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2501 p = enc_to_ucs2(name, NULL);
2502#endif
2503
2504#ifdef FEAT_MBYTE
2505 if (p != NULL)
2506 {
2507 perm = GetFileAttributesW(p);
2508 if (perm < 0 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
2509 {
2510 /* Retry with non-wide function (for Windows 98). */
2511 vim_free(p);
2512 p = NULL;
2513 }
2514 }
2515 if (p == NULL)
2516#endif
2517 perm = GetFileAttributes((char *)name);
2518 if (perm >= 0)
2519 {
2520 perm |= FILE_ATTRIBUTE_HIDDEN;
2521#ifdef FEAT_MBYTE
2522 if (p != NULL)
2523 {
2524 if (SetFileAttributesW(p, perm) == 0
2525 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
2526 {
2527 /* Retry with non-wide function (for Windows 98). */
2528 vim_free(p);
2529 p = NULL;
2530 }
2531 }
2532 if (p == NULL)
2533#endif
2534 SetFileAttributes((char *)name, perm);
2535 }
2536#ifdef FEAT_MBYTE
2537 vim_free(p);
2538#endif
2539}
2540
2541/*
2542 * return TRUE if "name" is a directory
2543 * return FALSE if "name" is not a directory or upon error
2544 */
2545 int
2546mch_isdir(char_u *name)
2547{
2548 int f = mch_getperm(name);
2549
2550 if (f == -1)
2551 return FALSE; /* file does not exist at all */
2552
2553 return (f & FILE_ATTRIBUTE_DIRECTORY) != 0;
2554}
2555
2556/*
2557 * Return TRUE if file or directory "name" is writable (not readonly).
2558 * Strange semantics of Win32: a readonly directory is writable, but you can't
2559 * delete a file. Let's say this means it is writable.
2560 */
2561 int
2562mch_writable(char_u *name)
2563{
2564 int perm = mch_getperm(name);
2565
2566 return (perm != -1 && (!(perm & FILE_ATTRIBUTE_READONLY)
2567 || (perm & FILE_ATTRIBUTE_DIRECTORY)));
2568}
2569
2570#if defined(FEAT_EVAL) || defined(PROTO)
2571/*
2572 * Return 1 if "name" can be executed, 0 if not.
2573 * Return -1 if unknown.
2574 */
2575 int
2576mch_can_exe(char_u *name)
2577{
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00002578 char_u buf[_MAX_PATH];
2579 int len = STRLEN(name);
2580 char_u *p;
2581
2582 if (len >= _MAX_PATH) /* safety check */
2583 return FALSE;
2584
2585 /* If there already is an extension try using the name directly. Also do
2586 * this with a Unix-shell like 'shell'. */
2587 if (vim_strchr(gettail(name), '.') != NULL
2588 || strstr((char *)gettail(p_sh), "sh") != NULL)
2589 if (executable_exists((char *)name))
2590 return TRUE;
2591
2592 /*
2593 * Loop over all extensions in $PATHEXT.
2594 */
2595 STRNCPY(buf, name, _MAX_PATH);
2596 p = mch_getenv("PATHEXT");
2597 if (p == NULL)
2598 p = (char_u *)".com;.exe;.bat;.cmd";
2599 while (*p)
2600 {
2601 if (p[0] == '.' && (p[1] == NUL || p[1] == ';'))
2602 {
2603 /* A single "." means no extension is added. */
2604 buf[len] = NUL;
2605 ++p;
2606 if (*p)
2607 ++p;
2608 }
2609 else
2610 copy_option_part(&p, buf + len, _MAX_PATH - len, ";");
2611 if (executable_exists((char *)buf))
2612 return TRUE;
2613 }
2614 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002615}
2616#endif
2617
2618/*
2619 * Check what "name" is:
2620 * NODE_NORMAL: file or directory (or doesn't exist)
2621 * NODE_WRITABLE: writable device, socket, fifo, etc.
2622 * NODE_OTHER: non-writable things
2623 */
2624 int
2625mch_nodetype(char_u *name)
2626{
2627 HANDLE hFile;
2628 int type;
2629
2630 hFile = CreateFile(name, /* file name */
2631 GENERIC_WRITE, /* access mode */
2632 0, /* share mode */
2633 NULL, /* security descriptor */
2634 OPEN_EXISTING, /* creation disposition */
2635 0, /* file attributes */
2636 NULL); /* handle to template file */
2637
2638 if (hFile == INVALID_HANDLE_VALUE)
2639 return NODE_NORMAL;
2640
2641 type = GetFileType(hFile);
2642 CloseHandle(hFile);
2643 if (type == FILE_TYPE_CHAR)
2644 return NODE_WRITABLE;
2645 if (type == FILE_TYPE_DISK)
2646 return NODE_NORMAL;
2647 return NODE_OTHER;
2648}
2649
2650#ifdef HAVE_ACL
2651struct my_acl
2652{
2653 PSECURITY_DESCRIPTOR pSecurityDescriptor;
2654 PSID pSidOwner;
2655 PSID pSidGroup;
2656 PACL pDacl;
2657 PACL pSacl;
2658};
2659#endif
2660
2661/*
2662 * Return a pointer to the ACL of file "fname" in allocated memory.
2663 * Return NULL if the ACL is not available for whatever reason.
2664 */
2665 vim_acl_T
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002666mch_get_acl(char_u *fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002667{
2668#ifndef HAVE_ACL
2669 return (vim_acl_T)NULL;
2670#else
2671 struct my_acl *p = NULL;
2672
2673 /* This only works on Windows NT and 2000. */
2674 if (g_PlatformId == VER_PLATFORM_WIN32_NT && advapi_lib != NULL)
2675 {
2676 p = (struct my_acl *)alloc_clear((unsigned)sizeof(struct my_acl));
2677 if (p != NULL)
2678 {
2679 if (pGetNamedSecurityInfo(
2680 (LPTSTR)fname, // Abstract filename
2681 SE_FILE_OBJECT, // File Object
2682 // Retrieve the entire security descriptor.
2683 OWNER_SECURITY_INFORMATION |
2684 GROUP_SECURITY_INFORMATION |
2685 DACL_SECURITY_INFORMATION |
2686 SACL_SECURITY_INFORMATION,
2687 &p->pSidOwner, // Ownership information.
2688 &p->pSidGroup, // Group membership.
2689 &p->pDacl, // Discretionary information.
2690 &p->pSacl, // For auditing purposes.
2691 &p->pSecurityDescriptor
2692 ) != ERROR_SUCCESS)
2693 {
2694 mch_free_acl((vim_acl_T)p);
2695 p = NULL;
2696 }
2697 }
2698 }
2699
2700 return (vim_acl_T)p;
2701#endif
2702}
2703
2704/*
2705 * Set the ACL of file "fname" to "acl" (unless it's NULL).
2706 * Errors are ignored.
2707 * This must only be called with "acl" equal to what mch_get_acl() returned.
2708 */
2709 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002710mch_set_acl(char_u *fname, vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002711{
2712#ifdef HAVE_ACL
2713 struct my_acl *p = (struct my_acl *)acl;
2714
2715 if (p != NULL && advapi_lib != NULL)
2716 (void)pSetNamedSecurityInfo(
2717 (LPTSTR)fname, // Abstract filename
2718 SE_FILE_OBJECT, // File Object
2719 // Retrieve the entire security descriptor.
2720 OWNER_SECURITY_INFORMATION |
2721 GROUP_SECURITY_INFORMATION |
2722 DACL_SECURITY_INFORMATION |
2723 SACL_SECURITY_INFORMATION,
2724 p->pSidOwner, // Ownership information.
2725 p->pSidGroup, // Group membership.
2726 p->pDacl, // Discretionary information.
2727 p->pSacl // For auditing purposes.
2728 );
2729#endif
2730}
2731
2732 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002733mch_free_acl(vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002734{
2735#ifdef HAVE_ACL
2736 struct my_acl *p = (struct my_acl *)acl;
2737
2738 if (p != NULL)
2739 {
2740 LocalFree(p->pSecurityDescriptor); // Free the memory just in case
2741 vim_free(p);
2742 }
2743#endif
2744}
2745
2746#ifndef FEAT_GUI_W32
2747
2748/*
2749 * handler for ctrl-break, ctrl-c interrupts, and fatal events.
2750 */
2751 static BOOL WINAPI
2752handler_routine(
2753 DWORD dwCtrlType)
2754{
2755 switch (dwCtrlType)
2756 {
2757 case CTRL_C_EVENT:
2758 if (ctrl_c_interrupts)
2759 g_fCtrlCPressed = TRUE;
2760 return TRUE;
2761
2762 case CTRL_BREAK_EVENT:
2763 g_fCBrkPressed = TRUE;
2764 return TRUE;
2765
2766 /* fatal events: shut down gracefully */
2767 case CTRL_CLOSE_EVENT:
2768 case CTRL_LOGOFF_EVENT:
2769 case CTRL_SHUTDOWN_EVENT:
2770 windgoto((int)Rows - 1, 0);
2771 g_fForceExit = TRUE;
2772
2773 sprintf((char *)IObuff, _("Vim: Caught %s event\n"),
2774 (dwCtrlType == CTRL_CLOSE_EVENT
2775 ? _("close")
2776 : dwCtrlType == CTRL_LOGOFF_EVENT
2777 ? _("logoff")
2778 : _("shutdown")));
2779#ifdef DEBUG
2780 OutputDebugString(IObuff);
2781#endif
2782
2783 preserve_exit(); /* output IObuff, preserve files and exit */
2784
2785 return TRUE; /* not reached */
2786
2787 default:
2788 return FALSE;
2789 }
2790}
2791
2792
2793/*
2794 * set the tty in (raw) ? "raw" : "cooked" mode
2795 */
2796 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002797mch_settmode(int tmode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002798{
2799 DWORD cmodein;
2800 DWORD cmodeout;
2801 BOOL bEnableHandler;
2802
2803 GetConsoleMode(g_hConIn, &cmodein);
2804 GetConsoleMode(g_hConOut, &cmodeout);
2805 if (tmode == TMODE_RAW)
2806 {
2807 cmodein &= ~(ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
2808 ENABLE_ECHO_INPUT);
2809#ifdef FEAT_MOUSE
2810 if (g_fMouseActive)
2811 cmodein |= ENABLE_MOUSE_INPUT;
2812#endif
2813 cmodeout &= ~(ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
2814 bEnableHandler = TRUE;
2815 }
2816 else /* cooked */
2817 {
2818 cmodein |= (ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
2819 ENABLE_ECHO_INPUT);
2820 cmodeout |= (ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
2821 bEnableHandler = FALSE;
2822 }
2823 SetConsoleMode(g_hConIn, cmodein);
2824 SetConsoleMode(g_hConOut, cmodeout);
2825 SetConsoleCtrlHandler(handler_routine, bEnableHandler);
2826
2827#ifdef MCH_WRITE_DUMP
2828 if (fdDump)
2829 {
2830 fprintf(fdDump, "mch_settmode(%s, in = %x, out = %x)\n",
2831 tmode == TMODE_RAW ? "raw" :
2832 tmode == TMODE_COOK ? "cooked" : "normal",
2833 cmodein, cmodeout);
2834 fflush(fdDump);
2835 }
2836#endif
2837}
2838
2839
2840/*
2841 * Get the size of the current window in `Rows' and `Columns'
2842 * Return OK when size could be determined, FAIL otherwise.
2843 */
2844 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002845mch_get_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002846{
2847 CONSOLE_SCREEN_BUFFER_INFO csbi;
2848
2849 if (!g_fTermcapMode && g_cbTermcap.IsValid)
2850 {
2851 /*
2852 * For some reason, we are trying to get the screen dimensions
2853 * even though we are not in termcap mode. The 'Rows' and 'Columns'
2854 * variables are really intended to mean the size of Vim screen
2855 * while in termcap mode.
2856 */
2857 Rows = g_cbTermcap.Info.dwSize.Y;
2858 Columns = g_cbTermcap.Info.dwSize.X;
2859 }
2860 else if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
2861 {
2862 Rows = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
2863 Columns = csbi.srWindow.Right - csbi.srWindow.Left + 1;
2864 }
2865 else
2866 {
2867 Rows = 25;
2868 Columns = 80;
2869 }
2870 return OK;
2871}
2872
2873/*
2874 * Set a console window to `xSize' * `ySize'
2875 */
2876 static void
2877ResizeConBufAndWindow(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002878 HANDLE hConsole,
2879 int xSize,
2880 int ySize)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002881{
2882 CONSOLE_SCREEN_BUFFER_INFO csbi; /* hold current console buffer info */
2883 SMALL_RECT srWindowRect; /* hold the new console size */
2884 COORD coordScreen;
2885
2886#ifdef MCH_WRITE_DUMP
2887 if (fdDump)
2888 {
2889 fprintf(fdDump, "ResizeConBufAndWindow(%d, %d)\n", xSize, ySize);
2890 fflush(fdDump);
2891 }
2892#endif
2893
2894 /* get the largest size we can size the console window to */
2895 coordScreen = GetLargestConsoleWindowSize(hConsole);
2896
2897 /* define the new console window size and scroll position */
2898 srWindowRect.Left = srWindowRect.Top = (SHORT) 0;
2899 srWindowRect.Right = (SHORT) (min(xSize, coordScreen.X) - 1);
2900 srWindowRect.Bottom = (SHORT) (min(ySize, coordScreen.Y) - 1);
2901
2902 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
2903 {
2904 int sx, sy;
2905
2906 sx = csbi.srWindow.Right - csbi.srWindow.Left + 1;
2907 sy = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
2908 if (sy < ySize || sx < xSize)
2909 {
2910 /*
2911 * Increasing number of lines/columns, do buffer first.
2912 * Use the maximal size in x and y direction.
2913 */
2914 if (sy < ySize)
2915 coordScreen.Y = ySize;
2916 else
2917 coordScreen.Y = sy;
2918 if (sx < xSize)
2919 coordScreen.X = xSize;
2920 else
2921 coordScreen.X = sx;
2922 SetConsoleScreenBufferSize(hConsole, coordScreen);
2923 }
2924 }
2925
2926 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &srWindowRect))
2927 {
2928#ifdef MCH_WRITE_DUMP
2929 if (fdDump)
2930 {
2931 fprintf(fdDump, "SetConsoleWindowInfo failed: %lx\n",
2932 GetLastError());
2933 fflush(fdDump);
2934 }
2935#endif
2936 }
2937
2938 /* define the new console buffer size */
2939 coordScreen.X = xSize;
2940 coordScreen.Y = ySize;
2941
2942 if (!SetConsoleScreenBufferSize(hConsole, coordScreen))
2943 {
2944#ifdef MCH_WRITE_DUMP
2945 if (fdDump)
2946 {
2947 fprintf(fdDump, "SetConsoleScreenBufferSize failed: %lx\n",
2948 GetLastError());
2949 fflush(fdDump);
2950 }
2951#endif
2952 }
2953}
2954
2955
2956/*
2957 * Set the console window to `Rows' * `Columns'
2958 */
2959 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002960mch_set_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002961{
2962 COORD coordScreen;
2963
2964 /* Don't change window size while still starting up */
2965 if (suppress_winsize != 0)
2966 {
2967 suppress_winsize = 2;
2968 return;
2969 }
2970
2971 if (term_console)
2972 {
2973 coordScreen = GetLargestConsoleWindowSize(g_hConOut);
2974
2975 /* Clamp Rows and Columns to reasonable values */
2976 if (Rows > coordScreen.Y)
2977 Rows = coordScreen.Y;
2978 if (Columns > coordScreen.X)
2979 Columns = coordScreen.X;
2980
2981 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
2982 }
2983}
2984
2985/*
2986 * Rows and/or Columns has changed.
2987 */
2988 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002989mch_new_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002990{
2991 set_scroll_region(0, 0, Columns - 1, Rows - 1);
2992}
2993
2994
2995/*
2996 * Called when started up, to set the winsize that was delayed.
2997 */
2998 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002999mch_set_winsize_now(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003000{
3001 if (suppress_winsize == 2)
3002 {
3003 suppress_winsize = 0;
3004 mch_set_shellsize();
3005 shell_resized();
3006 }
3007 suppress_winsize = 0;
3008}
3009#endif /* FEAT_GUI_W32 */
3010
3011
3012
3013#if defined(FEAT_GUI_W32) || defined(PROTO)
3014
3015/*
3016 * Specialised version of system() for Win32 GUI mode.
3017 * This version proceeds as follows:
3018 * 1. Create a console window for use by the subprocess
3019 * 2. Run the subprocess (it gets the allocated console by default)
3020 * 3. Wait for the subprocess to terminate and get its exit code
3021 * 4. Prompt the user to press a key to close the console window
3022 */
3023 static int
3024mch_system(char *cmd, int options)
3025{
3026 STARTUPINFO si;
3027 PROCESS_INFORMATION pi;
3028 DWORD ret = 0;
3029 HWND hwnd = GetFocus();
3030
3031 si.cb = sizeof(si);
3032 si.lpReserved = NULL;
3033 si.lpDesktop = NULL;
3034 si.lpTitle = NULL;
3035 si.dwFlags = STARTF_USESHOWWINDOW;
3036 /*
3037 * It's nicer to run a filter command in a minimized window, but in
3038 * Windows 95 this makes the command MUCH slower. We can't do it under
3039 * Win32s either as it stops the synchronous spawn workaround working.
3040 */
3041 if ((options & SHELL_DOOUT) && !mch_windows95() && !gui_is_win32s())
3042 si.wShowWindow = SW_SHOWMINIMIZED;
3043 else
3044 si.wShowWindow = SW_SHOWNORMAL;
3045 si.cbReserved2 = 0;
3046 si.lpReserved2 = NULL;
3047
3048 /* There is a strange error on Windows 95 when using "c:\\command.com".
3049 * When the "c:\\" is left out it works OK...? */
3050 if (mch_windows95()
3051 && (STRNICMP(cmd, "c:/command.com", 14) == 0
3052 || STRNICMP(cmd, "c:\\command.com", 14) == 0))
3053 cmd += 3;
3054
3055 /* Now, run the command */
3056 CreateProcess(NULL, /* Executable name */
3057 cmd, /* Command to execute */
3058 NULL, /* Process security attributes */
3059 NULL, /* Thread security attributes */
3060 FALSE, /* Inherit handles */
3061 CREATE_DEFAULT_ERROR_MODE | /* Creation flags */
3062 CREATE_NEW_CONSOLE,
3063 NULL, /* Environment */
3064 NULL, /* Current directory */
3065 &si, /* Startup information */
3066 &pi); /* Process information */
3067
3068
3069 /* Wait for the command to terminate before continuing */
3070 if (g_PlatformId != VER_PLATFORM_WIN32s)
3071 {
3072#ifdef FEAT_GUI
3073 int delay = 1;
3074
3075 /* Keep updating the window while waiting for the shell to finish. */
3076 for (;;)
3077 {
3078 MSG msg;
3079
3080 if (PeekMessage(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
3081 {
3082 TranslateMessage(&msg);
3083 DispatchMessage(&msg);
3084 }
3085 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
3086 break;
3087
3088 /* We start waiting for a very short time and then increase it, so
3089 * that we respond quickly when the process is quick, and don't
3090 * consume too much overhead when it's slow. */
3091 if (delay < 50)
3092 delay += 10;
3093 }
3094#else
3095 WaitForSingleObject(pi.hProcess, INFINITE);
3096#endif
3097
3098 /* Get the command exit code */
3099 GetExitCodeProcess(pi.hProcess, &ret);
3100 }
3101 else
3102 {
3103 /*
3104 * This ugly code is the only quick way of performing
3105 * a synchronous spawn under Win32s. Yuk.
3106 */
3107 num_windows = 0;
3108 EnumWindows(win32ssynch_cb, 0);
3109 old_num_windows = num_windows;
3110 do
3111 {
3112 Sleep(1000);
3113 num_windows = 0;
3114 EnumWindows(win32ssynch_cb, 0);
3115 } while (num_windows == old_num_windows);
3116 ret = 0;
3117 }
3118
3119 /* Close the handles to the subprocess, so that it goes away */
3120 CloseHandle(pi.hThread);
3121 CloseHandle(pi.hProcess);
3122
3123 /* Try to get input focus back. Doesn't always work though. */
3124 PostMessage(hwnd, WM_SETFOCUS, 0, 0);
3125
3126 return ret;
3127}
3128#else
3129
3130# define mch_system(c, o) system(c)
3131
3132#endif
3133
3134/*
3135 * Either execute a command by calling the shell or start a new shell
3136 */
3137 int
3138mch_call_shell(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003139 char_u *cmd,
3140 int options) /* SHELL_*, see vim.h */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003141{
3142 int x = 0;
3143 int tmode = cur_tmode;
3144#ifdef FEAT_TITLE
3145 char szShellTitle[512];
3146
3147 /* Change the title to reflect that we are in a subshell. */
3148 if (GetConsoleTitle(szShellTitle, sizeof(szShellTitle) - 4) > 0)
3149 {
3150 if (cmd == NULL)
3151 strcat(szShellTitle, " :sh");
3152 else
3153 {
3154 strcat(szShellTitle, " - !");
3155 if ((strlen(szShellTitle) + strlen(cmd) < sizeof(szShellTitle)))
3156 strcat(szShellTitle, cmd);
3157 }
3158 mch_settitle(szShellTitle, NULL);
3159 }
3160#endif
3161
3162 out_flush();
3163
3164#ifdef MCH_WRITE_DUMP
3165 if (fdDump)
3166 {
3167 fprintf(fdDump, "mch_call_shell(\"%s\", %d)\n", cmd, options);
3168 fflush(fdDump);
3169 }
3170#endif
3171
3172 /*
3173 * Catch all deadly signals while running the external command, because a
3174 * CTRL-C, Ctrl-Break or illegal instruction might otherwise kill us.
3175 */
3176 signal(SIGINT, SIG_IGN);
3177#if defined(__GNUC__) && !defined(__MINGW32__)
3178 signal(SIGKILL, SIG_IGN);
3179#else
3180 signal(SIGBREAK, SIG_IGN);
3181#endif
3182 signal(SIGILL, SIG_IGN);
3183 signal(SIGFPE, SIG_IGN);
3184 signal(SIGSEGV, SIG_IGN);
3185 signal(SIGTERM, SIG_IGN);
3186 signal(SIGABRT, SIG_IGN);
3187
3188 if (options & SHELL_COOKED)
3189 settmode(TMODE_COOK); /* set to normal mode */
3190
3191 if (cmd == NULL)
3192 {
3193 x = mch_system(p_sh, options);
3194 }
3195 else
3196 {
3197 /* we use "command" or "cmd" to start the shell; slow but easy */
3198 char_u *newcmd;
3199
3200 newcmd = lalloc((long_u) (
3201#ifdef FEAT_GUI_W32
3202 STRLEN(vimrun_path) +
3203#endif
3204 STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10), TRUE);
3205 if (newcmd != NULL)
3206 {
3207 char_u *cmdbase = (*cmd == '"' ? cmd + 1 : cmd);
3208
3209 if ((STRNICMP(cmdbase, "start", 5) == 0) && vim_iswhite(cmdbase[5]))
3210 {
3211 STARTUPINFO si;
3212 PROCESS_INFORMATION pi;
3213
3214 si.cb = sizeof(si);
3215 si.lpReserved = NULL;
3216 si.lpDesktop = NULL;
3217 si.lpTitle = NULL;
3218 si.dwFlags = 0;
3219 si.cbReserved2 = 0;
3220 si.lpReserved2 = NULL;
3221
3222 cmdbase = skipwhite(cmdbase + 5);
3223 if ((STRNICMP(cmdbase, "/min", 4) == 0)
3224 && vim_iswhite(cmdbase[4]))
3225 {
3226 cmdbase = skipwhite(cmdbase + 4);
3227 si.dwFlags = STARTF_USESHOWWINDOW;
3228 si.wShowWindow = SW_SHOWMINNOACTIVE;
3229 }
3230
3231 /* When the command is in double quotes, but 'shellxquote' is
3232 * empty, keep the double quotes around the command.
3233 * Otherwise remove the double quotes, they aren't needed
3234 * here, because we don't use a shell to run the command. */
3235 if (*cmd == '"' && *p_sxq == NUL)
3236 {
3237 newcmd[0] = '"';
3238 STRCPY(newcmd + 1, cmdbase);
3239 }
3240 else
3241 {
3242 STRCPY(newcmd, cmdbase);
3243 if (*cmd == '"' && *newcmd != NUL)
3244 newcmd[STRLEN(newcmd) - 1] = NUL;
3245 }
3246
3247 /*
3248 * Now, start the command as a process, so that it doesn't
3249 * inherit our handles which causes unpleasant dangling swap
3250 * files if we exit before the spawned process
3251 */
3252 if (CreateProcess (NULL, // Executable name
3253 newcmd, // Command to execute
3254 NULL, // Process security attributes
3255 NULL, // Thread security attributes
3256 FALSE, // Inherit handles
3257 CREATE_NEW_CONSOLE, // Creation flags
3258 NULL, // Environment
3259 NULL, // Current directory
3260 &si, // Startup information
3261 &pi)) // Process information
3262 x = 0;
3263 else
3264 {
3265 x = -1;
3266#ifdef FEAT_GUI_W32
3267 EMSG(_("E371: Command not found"));
3268#endif
3269 }
3270 /* Close the handles to the subprocess, so that it goes away */
3271 CloseHandle(pi.hThread);
3272 CloseHandle(pi.hProcess);
3273 }
3274 else
3275 {
3276#if defined(FEAT_GUI_W32)
3277 if (need_vimrun_warning)
3278 {
3279 MessageBox(NULL,
3280 _("VIMRUN.EXE not found in your $PATH.\n"
3281 "External commands will not pause after completion.\n"
3282 "See :help win32-vimrun for more information."),
3283 _("Vim Warning"),
3284 MB_ICONWARNING);
3285 need_vimrun_warning = FALSE;
3286 }
3287 if (!s_dont_use_vimrun)
3288 /* Use vimrun to execute the command. It opens a console
3289 * window, which can be closed without killing Vim. */
3290 sprintf((char *)newcmd, "%s%s%s %s %s",
3291 vimrun_path,
3292 (msg_silent != 0 || (options & SHELL_DOOUT))
3293 ? "-s " : "",
3294 p_sh, p_shcf, cmd);
3295 else
3296#endif
3297 sprintf((char *)newcmd, "%s %s %s", p_sh, p_shcf, cmd);
3298 x = mch_system((char *)newcmd, options);
3299 }
3300 vim_free(newcmd);
3301 }
3302 }
3303
3304 if (tmode == TMODE_RAW)
3305 settmode(TMODE_RAW); /* set to raw mode */
3306
3307 /* Print the return value, unless "vimrun" was used. */
3308 if (x != 0 && !(options & SHELL_SILENT) && !emsg_silent
3309#if defined(FEAT_GUI_W32)
3310 && ((options & SHELL_DOOUT) || s_dont_use_vimrun)
3311#endif
3312 )
3313 {
3314 smsg(_("shell returned %d"), x);
3315 msg_putchar('\n');
3316 }
3317#ifdef FEAT_TITLE
3318 resettitle();
3319#endif
3320
3321 signal(SIGINT, SIG_DFL);
3322#if defined(__GNUC__) && !defined(__MINGW32__)
3323 signal(SIGKILL, SIG_DFL);
3324#else
3325 signal(SIGBREAK, SIG_DFL);
3326#endif
3327 signal(SIGILL, SIG_DFL);
3328 signal(SIGFPE, SIG_DFL);
3329 signal(SIGSEGV, SIG_DFL);
3330 signal(SIGTERM, SIG_DFL);
3331 signal(SIGABRT, SIG_DFL);
3332
3333 return x;
3334}
3335
3336
3337#ifndef FEAT_GUI_W32
3338
3339/*
3340 * Start termcap mode
3341 */
3342 static void
3343termcap_mode_start(void)
3344{
3345 DWORD cmodein;
3346
3347 if (g_fTermcapMode)
3348 return;
3349
3350 SaveConsoleBuffer(&g_cbNonTermcap);
3351
3352 if (g_cbTermcap.IsValid)
3353 {
3354 /*
3355 * We've been in termcap mode before. Restore certain screen
3356 * characteristics, including the buffer size and the window
3357 * size. Since we will be redrawing the screen, we don't need
3358 * to restore the actual contents of the buffer.
3359 */
3360 RestoreConsoleBuffer(&g_cbTermcap, FALSE);
3361 SetConsoleWindowInfo(g_hConOut, TRUE, &g_cbTermcap.Info.srWindow);
3362 Rows = g_cbTermcap.Info.dwSize.Y;
3363 Columns = g_cbTermcap.Info.dwSize.X;
3364 }
3365 else
3366 {
3367 /*
3368 * This is our first time entering termcap mode. Clear the console
3369 * screen buffer, and resize the buffer to match the current window
3370 * size. We will use this as the size of our editing environment.
3371 */
3372 ClearConsoleBuffer(g_attrCurrent);
3373 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
3374 }
3375
3376#ifdef FEAT_TITLE
3377 resettitle();
3378#endif
3379
3380 GetConsoleMode(g_hConIn, &cmodein);
3381#ifdef FEAT_MOUSE
3382 if (g_fMouseActive)
3383 cmodein |= ENABLE_MOUSE_INPUT;
3384 else
3385 cmodein &= ~ENABLE_MOUSE_INPUT;
3386#endif
3387 cmodein |= ENABLE_WINDOW_INPUT;
3388 SetConsoleMode(g_hConIn, cmodein);
3389
3390 redraw_later_clear();
3391 g_fTermcapMode = TRUE;
3392}
3393
3394
3395/*
3396 * End termcap mode
3397 */
3398 static void
3399termcap_mode_end(void)
3400{
3401 DWORD cmodein;
3402 ConsoleBuffer *cb;
3403 COORD coord;
3404 DWORD dwDummy;
3405
3406 if (!g_fTermcapMode)
3407 return;
3408
3409 SaveConsoleBuffer(&g_cbTermcap);
3410
3411 GetConsoleMode(g_hConIn, &cmodein);
3412 cmodein &= ~(ENABLE_MOUSE_INPUT | ENABLE_WINDOW_INPUT);
3413 SetConsoleMode(g_hConIn, cmodein);
3414
3415#ifdef FEAT_RESTORE_ORIG_SCREEN
3416 cb = exiting ? &g_cbOrig : &g_cbNonTermcap;
3417#else
3418 cb = &g_cbNonTermcap;
3419#endif
3420 RestoreConsoleBuffer(cb, p_rs);
3421 SetConsoleCursorInfo(g_hConOut, &g_cci);
3422
3423 if (p_rs || exiting)
3424 {
3425 /*
3426 * Clear anything that happens to be on the current line.
3427 */
3428 coord.X = 0;
3429 coord.Y = (SHORT) (p_rs ? cb->Info.dwCursorPosition.Y : (Rows - 1));
3430 FillConsoleOutputCharacter(g_hConOut, ' ',
3431 cb->Info.dwSize.X, coord, &dwDummy);
3432 /*
3433 * The following is just for aesthetics. If we are exiting without
3434 * restoring the screen, then we want to have a prompt string
3435 * appear at the bottom line. However, the command interpreter
3436 * seems to always advance the cursor one line before displaying
3437 * the prompt string, which causes the screen to scroll. To
3438 * counter this, move the cursor up one line before exiting.
3439 */
3440 if (exiting && !p_rs)
3441 coord.Y--;
3442 /*
3443 * Position the cursor at the leftmost column of the desired row.
3444 */
3445 SetConsoleCursorPosition(g_hConOut, coord);
3446 }
3447
3448 g_fTermcapMode = FALSE;
3449}
3450#endif /* FEAT_GUI_W32 */
3451
3452
3453#ifdef FEAT_GUI_W32
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00003454/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00003455 void
3456mch_write(
3457 char_u *s,
3458 int len)
3459{
3460 /* never used */
3461}
3462
3463#else
3464
3465/*
3466 * clear `n' chars, starting from `coord'
3467 */
3468 static void
3469clear_chars(
3470 COORD coord,
3471 DWORD n)
3472{
3473 DWORD dwDummy;
3474
3475 FillConsoleOutputCharacter(g_hConOut, ' ', n, coord, &dwDummy);
3476 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, n, coord, &dwDummy);
3477}
3478
3479
3480/*
3481 * Clear the screen
3482 */
3483 static void
3484clear_screen(void)
3485{
3486 g_coord.X = g_coord.Y = 0;
3487 clear_chars(g_coord, Rows * Columns);
3488}
3489
3490
3491/*
3492 * Clear to end of display
3493 */
3494 static void
3495clear_to_end_of_display(void)
3496{
3497 clear_chars(g_coord, (Rows - g_coord.Y - 1)
3498 * Columns + (Columns - g_coord.X));
3499}
3500
3501
3502/*
3503 * Clear to end of line
3504 */
3505 static void
3506clear_to_end_of_line(void)
3507{
3508 clear_chars(g_coord, Columns - g_coord.X);
3509}
3510
3511
3512/*
3513 * Scroll the scroll region up by `cLines' lines
3514 */
3515 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003516scroll(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003517{
3518 COORD oldcoord = g_coord;
3519
3520 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
3521 delete_lines(cLines);
3522
3523 g_coord = oldcoord;
3524}
3525
3526
3527/*
3528 * Set the scroll region
3529 */
3530 static void
3531set_scroll_region(
3532 unsigned left,
3533 unsigned top,
3534 unsigned right,
3535 unsigned bottom)
3536{
3537 if (left >= right
3538 || top >= bottom
3539 || right > (unsigned) Columns - 1
3540 || bottom > (unsigned) Rows - 1)
3541 return;
3542
3543 g_srScrollRegion.Left = left;
3544 g_srScrollRegion.Top = top;
3545 g_srScrollRegion.Right = right;
3546 g_srScrollRegion.Bottom = bottom;
3547}
3548
3549
3550/*
3551 * Insert `cLines' lines at the current cursor position
3552 */
3553 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003554insert_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003555{
3556 SMALL_RECT source;
3557 COORD dest;
3558 CHAR_INFO fill;
3559
3560 dest.X = 0;
3561 dest.Y = g_coord.Y + cLines;
3562
3563 source.Left = 0;
3564 source.Top = g_coord.Y;
3565 source.Right = g_srScrollRegion.Right;
3566 source.Bottom = g_srScrollRegion.Bottom - cLines;
3567
3568 fill.Char.AsciiChar = ' ';
3569 fill.Attributes = g_attrCurrent;
3570
3571 ScrollConsoleScreenBuffer(g_hConOut, &source, NULL, dest, &fill);
3572
3573 /* Here we have to deal with a win32 console flake: If the scroll
3574 * region looks like abc and we scroll c to a and fill with d we get
3575 * cbd... if we scroll block c one line at a time to a, we get cdd...
3576 * vim expects cdd consistently... So we have to deal with that
3577 * here... (this also occurs scrolling the same way in the other
3578 * direction). */
3579
3580 if (source.Bottom < dest.Y)
3581 {
3582 COORD coord;
3583
3584 coord.X = 0;
3585 coord.Y = source.Bottom;
3586 clear_chars(coord, Columns * (dest.Y - source.Bottom));
3587 }
3588}
3589
3590
3591/*
3592 * Delete `cLines' lines at the current cursor position
3593 */
3594 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003595delete_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003596{
3597 SMALL_RECT source;
3598 COORD dest;
3599 CHAR_INFO fill;
3600 int nb;
3601
3602 dest.X = 0;
3603 dest.Y = g_coord.Y;
3604
3605 source.Left = 0;
3606 source.Top = g_coord.Y + cLines;
3607 source.Right = g_srScrollRegion.Right;
3608 source.Bottom = g_srScrollRegion.Bottom;
3609
3610 fill.Char.AsciiChar = ' ';
3611 fill.Attributes = g_attrCurrent;
3612
3613 ScrollConsoleScreenBuffer(g_hConOut, &source, NULL, dest, &fill);
3614
3615 /* Here we have to deal with a win32 console flake: If the scroll
3616 * region looks like abc and we scroll c to a and fill with d we get
3617 * cbd... if we scroll block c one line at a time to a, we get cdd...
3618 * vim expects cdd consistently... So we have to deal with that
3619 * here... (this also occurs scrolling the same way in the other
3620 * direction). */
3621
3622 nb = dest.Y + (source.Bottom - source.Top) + 1;
3623
3624 if (nb < source.Top)
3625 {
3626 COORD coord;
3627
3628 coord.X = 0;
3629 coord.Y = nb;
3630 clear_chars(coord, Columns * (source.Top - nb));
3631 }
3632}
3633
3634
3635/*
3636 * Set the cursor position
3637 */
3638 static void
3639gotoxy(
3640 unsigned x,
3641 unsigned y)
3642{
3643 if (x < 1 || x > (unsigned)Columns || y < 1 || y > (unsigned)Rows)
3644 return;
3645
3646 /* external cursor coords are 1-based; internal are 0-based */
3647 g_coord.X = x - 1;
3648 g_coord.Y = y - 1;
3649 SetConsoleCursorPosition(g_hConOut, g_coord);
3650}
3651
3652
3653/*
3654 * Set the current text attribute = (foreground | background)
3655 * See ../doc/os_win32.txt for the numbers.
3656 */
3657 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003658textattr(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003659{
3660 g_attrCurrent = wAttr;
3661
3662 SetConsoleTextAttribute(g_hConOut, wAttr);
3663}
3664
3665
3666 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003667textcolor(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003668{
3669 g_attrCurrent = (g_attrCurrent & 0xf0) + wAttr;
3670
3671 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
3672}
3673
3674
3675 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003676textbackground(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003677{
3678 g_attrCurrent = (g_attrCurrent & 0x0f) + (wAttr << 4);
3679
3680 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
3681}
3682
3683
3684/*
3685 * restore the default text attribute (whatever we started with)
3686 */
3687 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003688normvideo(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003689{
3690 textattr(g_attrDefault);
3691}
3692
3693
3694static WORD g_attrPreStandout = 0;
3695
3696/*
3697 * Make the text standout, by brightening it
3698 */
3699 static void
3700standout(void)
3701{
3702 g_attrPreStandout = g_attrCurrent;
3703 textattr((WORD) (g_attrCurrent|FOREGROUND_INTENSITY|BACKGROUND_INTENSITY));
3704}
3705
3706
3707/*
3708 * Turn off standout mode
3709 */
3710 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003711standend(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003712{
3713 if (g_attrPreStandout)
3714 {
3715 textattr(g_attrPreStandout);
3716 g_attrPreStandout = 0;
3717 }
3718}
3719
3720
3721/*
3722 * Set normal fg/bg color, based on T_ME. Called whem t_me has been set.
3723 */
3724 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003725mch_set_normal_colors(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003726{
3727 char_u *p;
3728 int n;
3729
3730 cterm_normal_fg_color = (g_attrDefault & 0xf) + 1;
3731 cterm_normal_bg_color = ((g_attrDefault >> 4) & 0xf) + 1;
3732 if (T_ME[0] == ESC && T_ME[1] == '|')
3733 {
3734 p = T_ME + 2;
3735 n = getdigits(&p);
3736 if (*p == 'm' && n > 0)
3737 {
3738 cterm_normal_fg_color = (n & 0xf) + 1;
3739 cterm_normal_bg_color = ((n >> 4) & 0xf) + 1;
3740 }
3741 }
3742}
3743
3744
3745/*
3746 * visual bell: flash the screen
3747 */
3748 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003749visual_bell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003750{
3751 COORD coordOrigin = {0, 0};
3752 WORD attrFlash = ~g_attrCurrent & 0xff;
3753
3754 DWORD dwDummy;
3755 LPWORD oldattrs = (LPWORD)alloc(Rows * Columns * sizeof(WORD));
3756
3757 if (oldattrs == NULL)
3758 return;
3759 ReadConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
3760 coordOrigin, &dwDummy);
3761 FillConsoleOutputAttribute(g_hConOut, attrFlash, Rows * Columns,
3762 coordOrigin, &dwDummy);
3763
3764 Sleep(15); /* wait for 15 msec */
3765 WriteConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
3766 coordOrigin, &dwDummy);
3767 vim_free(oldattrs);
3768}
3769
3770
3771/*
3772 * Make the cursor visible or invisible
3773 */
3774 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003775cursor_visible(BOOL fVisible)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003776{
3777 s_cursor_visible = fVisible;
3778#ifdef MCH_CURSOR_SHAPE
3779 mch_update_cursor();
3780#endif
3781}
3782
3783
3784/*
3785 * write `cchToWrite' characters in `pchBuf' to the screen
3786 * Returns the number of characters actually written (at least one).
3787 */
3788 static BOOL
3789write_chars(
3790 LPCSTR pchBuf,
3791 DWORD cchToWrite)
3792{
3793 COORD coord = g_coord;
3794 DWORD written;
3795
3796 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, cchToWrite,
3797 coord, &written);
3798 /* When writing fails or didn't write a single character, pretend one
3799 * character was written, otherwise we get stuck. */
3800 if (WriteConsoleOutputCharacter(g_hConOut, pchBuf, cchToWrite,
3801 coord, &written) == 0
3802 || written == 0)
3803 written = 1;
3804
3805 g_coord.X += (SHORT) written;
3806
3807 while (g_coord.X > g_srScrollRegion.Right)
3808 {
3809 g_coord.X -= (SHORT) Columns;
3810 if (g_coord.Y < g_srScrollRegion.Bottom)
3811 g_coord.Y++;
3812 }
3813
3814 gotoxy(g_coord.X + 1, g_coord.Y + 1);
3815
3816 return written;
3817}
3818
3819
3820/*
3821 * mch_write(): write the output buffer to the screen, translating ESC
3822 * sequences into calls to console output routines.
3823 */
3824 void
3825mch_write(
3826 char_u *s,
3827 int len)
3828{
3829 s[len] = NUL;
3830
3831 if (!term_console)
3832 {
3833 write(1, s, (unsigned)len);
3834 return;
3835 }
3836
3837 /* translate ESC | sequences into faked bios calls */
3838 while (len--)
3839 {
3840 /* optimization: use one single write_chars for runs of text,
3841 * rather than once per character It ain't curses, but it helps. */
3842 DWORD prefix = strcspn(s, "\n\r\b\a\033");
3843
3844 if (p_wd)
3845 {
3846 WaitForChar(p_wd);
3847 if (prefix != 0)
3848 prefix = 1;
3849 }
3850
3851 if (prefix != 0)
3852 {
3853 DWORD nWritten;
3854
3855 nWritten = write_chars(s, prefix);
3856#ifdef MCH_WRITE_DUMP
3857 if (fdDump)
3858 {
3859 fputc('>', fdDump);
3860 fwrite(s, sizeof(char_u), nWritten, fdDump);
3861 fputs("<\n", fdDump);
3862 }
3863#endif
3864 len -= (nWritten - 1);
3865 s += nWritten;
3866 }
3867 else if (s[0] == '\n')
3868 {
3869 /* \n, newline: go to the beginning of the next line or scroll */
3870 if (g_coord.Y == g_srScrollRegion.Bottom)
3871 {
3872 scroll(1);
3873 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Bottom + 1);
3874 }
3875 else
3876 {
3877 gotoxy(g_srScrollRegion.Left + 1, g_coord.Y + 2);
3878 }
3879#ifdef MCH_WRITE_DUMP
3880 if (fdDump)
3881 fputs("\\n\n", fdDump);
3882#endif
3883 s++;
3884 }
3885 else if (s[0] == '\r')
3886 {
3887 /* \r, carriage return: go to beginning of line */
3888 gotoxy(g_srScrollRegion.Left+1, g_coord.Y + 1);
3889#ifdef MCH_WRITE_DUMP
3890 if (fdDump)
3891 fputs("\\r\n", fdDump);
3892#endif
3893 s++;
3894 }
3895 else if (s[0] == '\b')
3896 {
3897 /* \b, backspace: move cursor one position left */
3898 if (g_coord.X > g_srScrollRegion.Left)
3899 g_coord.X--;
3900 else if (g_coord.Y > g_srScrollRegion.Top)
3901 {
3902 g_coord.X = g_srScrollRegion.Right;
3903 g_coord.Y--;
3904 }
3905 gotoxy(g_coord.X + 1, g_coord.Y + 1);
3906#ifdef MCH_WRITE_DUMP
3907 if (fdDump)
3908 fputs("\\b\n", fdDump);
3909#endif
3910 s++;
3911 }
3912 else if (s[0] == '\a')
3913 {
3914 /* \a, bell */
3915 MessageBeep(0xFFFFFFFF);
3916#ifdef MCH_WRITE_DUMP
3917 if (fdDump)
3918 fputs("\\a\n", fdDump);
3919#endif
3920 s++;
3921 }
3922 else if (s[0] == ESC && len >= 3-1 && s[1] == '|')
3923 {
3924#ifdef MCH_WRITE_DUMP
Bram Moolenaarc0197e22004-09-13 20:26:32 +00003925 char_u *old_s = s;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003926#endif
Bram Moolenaarc0197e22004-09-13 20:26:32 +00003927 char_u *p;
3928 int arg1 = 0, arg2 = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003929
3930 switch (s[2])
3931 {
3932 /* one or two numeric arguments, separated by ';' */
3933
3934 case '0': case '1': case '2': case '3': case '4':
3935 case '5': case '6': case '7': case '8': case '9':
3936 p = s + 2;
3937 arg1 = getdigits(&p); /* no check for length! */
3938 if (p > s + len)
3939 break;
3940
3941 if (*p == ';')
3942 {
3943 ++p;
3944 arg2 = getdigits(&p); /* no check for length! */
3945 if (p > s + len)
3946 break;
3947
3948 if (*p == 'H')
3949 gotoxy(arg2, arg1);
3950 else if (*p == 'r')
3951 set_scroll_region(0, arg1 - 1, Columns - 1, arg2 - 1);
3952 }
3953 else if (*p == 'A')
3954 {
3955 /* move cursor up arg1 lines in same column */
3956 gotoxy(g_coord.X + 1,
3957 max(g_srScrollRegion.Top, g_coord.Y - arg1) + 1);
3958 }
3959 else if (*p == 'C')
3960 {
3961 /* move cursor right arg1 columns in same line */
3962 gotoxy(min(g_srScrollRegion.Right, g_coord.X + arg1) + 1,
3963 g_coord.Y + 1);
3964 }
3965 else if (*p == 'H')
3966 {
3967 gotoxy(1, arg1);
3968 }
3969 else if (*p == 'L')
3970 {
3971 insert_lines(arg1);
3972 }
3973 else if (*p == 'm')
3974 {
3975 if (arg1 == 0)
3976 normvideo();
3977 else
3978 textattr((WORD) arg1);
3979 }
3980 else if (*p == 'f')
3981 {
3982 textcolor((WORD) arg1);
3983 }
3984 else if (*p == 'b')
3985 {
3986 textbackground((WORD) arg1);
3987 }
3988 else if (*p == 'M')
3989 {
3990 delete_lines(arg1);
3991 }
3992
3993 len -= p - s;
3994 s = p + 1;
3995 break;
3996
3997
3998 /* Three-character escape sequences */
3999
4000 case 'A':
4001 /* move cursor up one line in same column */
4002 gotoxy(g_coord.X + 1,
4003 max(g_srScrollRegion.Top, g_coord.Y - 1) + 1);
4004 goto got3;
4005
4006 case 'B':
4007 visual_bell();
4008 goto got3;
4009
4010 case 'C':
4011 /* move cursor right one column in same line */
4012 gotoxy(min(g_srScrollRegion.Right, g_coord.X + 1) + 1,
4013 g_coord.Y + 1);
4014 goto got3;
4015
4016 case 'E':
4017 termcap_mode_end();
4018 goto got3;
4019
4020 case 'F':
4021 standout();
4022 goto got3;
4023
4024 case 'f':
4025 standend();
4026 goto got3;
4027
4028 case 'H':
4029 gotoxy(1, 1);
4030 goto got3;
4031
4032 case 'j':
4033 clear_to_end_of_display();
4034 goto got3;
4035
4036 case 'J':
4037 clear_screen();
4038 goto got3;
4039
4040 case 'K':
4041 clear_to_end_of_line();
4042 goto got3;
4043
4044 case 'L':
4045 insert_lines(1);
4046 goto got3;
4047
4048 case 'M':
4049 delete_lines(1);
4050 goto got3;
4051
4052 case 'S':
4053 termcap_mode_start();
4054 goto got3;
4055
4056 case 'V':
4057 cursor_visible(TRUE);
4058 goto got3;
4059
4060 case 'v':
4061 cursor_visible(FALSE);
4062 goto got3;
4063
4064 got3:
4065 s += 3;
4066 len -= 2;
4067 }
4068
4069#ifdef MCH_WRITE_DUMP
4070 if (fdDump)
4071 {
4072 fputs("ESC | ", fdDump);
4073 fwrite(old_s + 2, sizeof(char_u), s - old_s - 2, fdDump);
4074 fputc('\n', fdDump);
4075 }
4076#endif
4077 }
4078 else
4079 {
4080 /* Write a single character */
4081 DWORD nWritten;
4082
4083 nWritten = write_chars(s, 1);
4084#ifdef MCH_WRITE_DUMP
4085 if (fdDump)
4086 {
4087 fputc('>', fdDump);
4088 fwrite(s, sizeof(char_u), nWritten, fdDump);
4089 fputs("<\n", fdDump);
4090 }
4091#endif
4092
4093 len -= (nWritten - 1);
4094 s += nWritten;
4095 }
4096 }
4097
4098#ifdef MCH_WRITE_DUMP
4099 if (fdDump)
4100 fflush(fdDump);
4101#endif
4102}
4103
4104#endif /* FEAT_GUI_W32 */
4105
4106
4107/*
4108 * Delay for half a second.
4109 */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00004110/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00004111 void
4112mch_delay(
4113 long msec,
4114 int ignoreinput)
4115{
4116#ifdef FEAT_GUI_W32
4117 Sleep((int)msec); /* never wait for input */
Bram Moolenaar325b7a22004-07-05 15:58:32 +00004118#else /* Console */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004119 if (ignoreinput)
Bram Moolenaar325b7a22004-07-05 15:58:32 +00004120# ifdef FEAT_MZSCHEME
4121 if (mzthreads_allowed() && p_mzq > 0 && msec > p_mzq)
4122 {
4123 int towait = p_mzq;
4124
4125 /* if msec is large enough, wait by portions in p_mzq */
4126 while (msec > 0)
4127 {
4128 mzvim_check_threads();
4129 if (msec < towait)
4130 towait = msec;
4131 Sleep(towait);
4132 msec -= towait;
4133 }
4134 }
4135 else
4136# endif
4137 Sleep((int)msec);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004138 else
4139 WaitForChar(msec);
4140#endif
4141}
4142
4143
4144/*
4145 * this version of remove is not scared by a readonly (backup) file
4146 * Return 0 for success, -1 for failure.
4147 */
4148 int
4149mch_remove(char_u *name)
4150{
4151#ifdef FEAT_MBYTE
4152 WCHAR *wn = NULL;
4153 int n;
4154
4155 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4156 {
4157 wn = enc_to_ucs2(name, NULL);
4158 if (wn != NULL)
4159 {
4160 SetFileAttributesW(wn, FILE_ATTRIBUTE_NORMAL);
4161 n = DeleteFileW(wn) ? 0 : -1;
4162 vim_free(wn);
4163 if (n == 0 || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
4164 return n;
4165 /* Retry with non-wide function (for Windows 98). */
4166 }
4167 }
4168#endif
4169 SetFileAttributes(name, FILE_ATTRIBUTE_NORMAL);
4170 return DeleteFile(name) ? 0 : -1;
4171}
4172
4173
4174/*
4175 * check for an "interrupt signal": CTRL-break or CTRL-C
4176 */
4177 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004178mch_breakcheck(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004179{
4180#ifndef FEAT_GUI_W32 /* never used */
4181 if (g_fCtrlCPressed || g_fCBrkPressed)
4182 {
4183 g_fCtrlCPressed = g_fCBrkPressed = FALSE;
4184 got_int = TRUE;
4185 }
4186#endif
4187}
4188
4189
4190/*
4191 * How much memory is available?
4192 * Return sum of available physical and page file memory.
4193 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00004194/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00004195 long_u
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004196mch_avail_mem(int special)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004197{
4198 MEMORYSTATUS ms;
4199
4200 ms.dwLength = sizeof(MEMORYSTATUS);
4201 GlobalMemoryStatus(&ms);
4202 return (long_u) (ms.dwAvailPhys + ms.dwAvailPageFile);
4203}
4204
4205#ifdef FEAT_MBYTE
4206/*
4207 * Same code as below, but with wide functions and no comments.
4208 * Return 0 for success, non-zero for failure.
4209 */
4210 int
4211mch_wrename(WCHAR *wold, WCHAR *wnew)
4212{
4213 WCHAR *p;
4214 int i;
4215 WCHAR szTempFile[_MAX_PATH + 1];
4216 WCHAR szNewPath[_MAX_PATH + 1];
4217 HANDLE hf;
4218
4219 if (!mch_windows95())
4220 {
4221 p = wold;
4222 for (i = 0; wold[i] != NUL; ++i)
4223 if ((wold[i] == '/' || wold[i] == '\\' || wold[i] == ':')
4224 && wold[i + 1] != 0)
4225 p = wold + i + 1;
4226 if ((int)(wold + i - p) < 8 || p[6] != '~')
4227 return (MoveFileW(wold, wnew) == 0);
4228 }
4229
4230 if (GetFullPathNameW(wnew, _MAX_PATH, szNewPath, &p) == 0 || p == NULL)
4231 return -1;
4232 *p = NUL;
4233
4234 if (GetTempFileNameW(szNewPath, L"VIM", 0, szTempFile) == 0)
4235 return -2;
4236
4237 if (!DeleteFileW(szTempFile))
4238 return -3;
4239
4240 if (!MoveFileW(wold, szTempFile))
4241 return -4;
4242
4243 if ((hf = CreateFileW(wold, GENERIC_WRITE, 0, NULL, CREATE_NEW,
4244 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
4245 return -5;
4246 if (!CloseHandle(hf))
4247 return -6;
4248
4249 if (!MoveFileW(szTempFile, wnew))
4250 {
4251 (void)MoveFileW(szTempFile, wold);
4252 return -7;
4253 }
4254
4255 DeleteFileW(szTempFile);
4256
4257 if (!DeleteFileW(wold))
4258 return -8;
4259
4260 return 0;
4261}
4262#endif
4263
4264
4265/*
4266 * mch_rename() works around a bug in rename (aka MoveFile) in
4267 * Windows 95: rename("foo.bar", "foo.bar~") will generate a
4268 * file whose short file name is "FOO.BAR" (its long file name will
4269 * be correct: "foo.bar~"). Because a file can be accessed by
4270 * either its SFN or its LFN, "foo.bar" has effectively been
4271 * renamed to "foo.bar", which is not at all what was wanted. This
4272 * seems to happen only when renaming files with three-character
4273 * extensions by appending a suffix that does not include ".".
4274 * Windows NT gets it right, however, with an SFN of "FOO~1.BAR".
4275 *
4276 * There is another problem, which isn't really a bug but isn't right either:
4277 * When renaming "abcdef~1.txt" to "abcdef~1.txt~", the short name can be
4278 * "abcdef~1.txt" again. This has been reported on Windows NT 4.0 with
4279 * service pack 6. Doesn't seem to happen on Windows 98.
4280 *
4281 * Like rename(), returns 0 upon success, non-zero upon failure.
4282 * Should probably set errno appropriately when errors occur.
4283 */
4284 int
4285mch_rename(
4286 const char *pszOldFile,
4287 const char *pszNewFile)
4288{
4289 char szTempFile[_MAX_PATH+1];
4290 char szNewPath[_MAX_PATH+1];
4291 char *pszFilePart;
4292 HANDLE hf;
4293#ifdef FEAT_MBYTE
4294 WCHAR *wold = NULL;
4295 WCHAR *wnew = NULL;
4296 int retval = -1;
4297
4298 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4299 {
4300 wold = enc_to_ucs2((char_u *)pszOldFile, NULL);
4301 wnew = enc_to_ucs2((char_u *)pszNewFile, NULL);
4302 if (wold != NULL && wnew != NULL)
4303 retval = mch_wrename(wold, wnew);
4304 vim_free(wold);
4305 vim_free(wnew);
4306 if (retval == 0 || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
4307 return retval;
4308 /* Retry with non-wide function (for Windows 98). */
4309 }
4310#endif
4311
4312 /*
4313 * No need to play tricks if not running Windows 95, unless the file name
4314 * contains a "~" as the seventh character.
4315 */
4316 if (!mch_windows95())
4317 {
4318 pszFilePart = (char *)gettail((char_u *)pszOldFile);
4319 if (STRLEN(pszFilePart) < 8 || pszFilePart[6] != '~')
4320 return rename(pszOldFile, pszNewFile);
4321 }
4322
4323 /* Get base path of new file name. Undocumented feature: If pszNewFile is
4324 * a directory, no error is returned and pszFilePart will be NULL. */
4325 if (GetFullPathName(pszNewFile, _MAX_PATH, szNewPath, &pszFilePart) == 0
4326 || pszFilePart == NULL)
4327 return -1;
4328 *pszFilePart = NUL;
4329
4330 /* Get (and create) a unique temporary file name in directory of new file */
4331 if (GetTempFileName(szNewPath, "VIM", 0, szTempFile) == 0)
4332 return -2;
4333
4334 /* blow the temp file away */
4335 if (!DeleteFile(szTempFile))
4336 return -3;
4337
4338 /* rename old file to the temp file */
4339 if (!MoveFile(pszOldFile, szTempFile))
4340 return -4;
4341
4342 /* now create an empty file called pszOldFile; this prevents the operating
4343 * system using pszOldFile as an alias (SFN) if we're renaming within the
4344 * same directory. For example, we're editing a file called
4345 * filename.asc.txt by its SFN, filena~1.txt. If we rename filena~1.txt
4346 * to filena~1.txt~ (i.e., we're making a backup while writing it), the
4347 * SFN for filena~1.txt~ will be filena~1.txt, by default, which will
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004348 * cause all sorts of problems later in buf_write(). So, we create an
4349 * empty file called filena~1.txt and the system will have to find some
4350 * other SFN for filena~1.txt~, such as filena~2.txt
Bram Moolenaar071d4272004-06-13 20:20:40 +00004351 */
4352 if ((hf = CreateFile(pszOldFile, GENERIC_WRITE, 0, NULL, CREATE_NEW,
4353 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
4354 return -5;
4355 if (!CloseHandle(hf))
4356 return -6;
4357
4358 /* rename the temp file to the new file */
4359 if (!MoveFile(szTempFile, pszNewFile))
4360 {
4361 /* Renaming failed. Rename the file back to its old name, so that it
4362 * looks like nothing happened. */
4363 (void)MoveFile(szTempFile, pszOldFile);
4364
4365 return -7;
4366 }
4367
4368 /* Seems to be left around on Novell filesystems */
4369 DeleteFile(szTempFile);
4370
4371 /* finally, remove the empty old file */
4372 if (!DeleteFile(pszOldFile))
4373 return -8;
4374
4375 return 0; /* success */
4376}
4377
4378/*
4379 * Get the default shell for the current hardware platform
4380 */
4381 char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004382default_shell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004383{
4384 char* psz = NULL;
4385
4386 PlatformId();
4387
4388 if (g_PlatformId == VER_PLATFORM_WIN32_NT) /* Windows NT */
4389 psz = "cmd.exe";
4390 else if (g_PlatformId == VER_PLATFORM_WIN32_WINDOWS) /* Windows 95 */
4391 psz = "command.com";
4392
4393 return psz;
4394}
4395
4396/*
4397 * mch_access() extends access() to do more detailed check on network drives.
4398 * Returns 0 if file "n" has access rights according to "p", -1 otherwise.
4399 */
4400 int
4401mch_access(char *n, int p)
4402{
4403 HANDLE hFile;
4404 DWORD am;
4405 int retval = -1; /* default: fail */
4406#ifdef FEAT_MBYTE
4407 WCHAR *wn = NULL;
4408
4409 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4410 wn = enc_to_ucs2(n, NULL);
4411#endif
4412
4413 if (mch_isdir(n))
4414 {
4415 char TempName[_MAX_PATH + 16] = "";
4416#ifdef FEAT_MBYTE
4417 WCHAR TempNameW[_MAX_PATH + 16] = L"";
4418#endif
4419
4420 if (p & R_OK)
4421 {
4422 /* Read check is performed by seeing if we can do a find file on
4423 * the directory for any file. */
4424#ifdef FEAT_MBYTE
4425 if (wn != NULL)
4426 {
4427 int i;
4428 WIN32_FIND_DATAW d;
4429
4430 for (i = 0; i < _MAX_PATH && wn[i] != 0; ++i)
4431 TempNameW[i] = wn[i];
4432 if (TempNameW[i - 1] != '\\' && TempNameW[i - 1] != '/')
4433 TempNameW[i++] = '\\';
4434 TempNameW[i++] = '*';
4435 TempNameW[i++] = 0;
4436
4437 hFile = FindFirstFileW(TempNameW, &d);
4438 if (hFile == INVALID_HANDLE_VALUE)
4439 {
4440 if (GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
4441 goto getout;
4442
4443 /* Retry with non-wide function (for Windows 98). */
4444 vim_free(wn);
4445 wn = NULL;
4446 }
4447 else
4448 (void)FindClose(hFile);
4449 }
4450 if (wn == NULL)
4451#endif
4452 {
4453 char *pch;
4454 WIN32_FIND_DATA d;
4455
4456 STRNCPY(TempName, n, _MAX_PATH);
4457 pch = TempName + STRLEN(TempName) - 1;
4458 if (*pch != '\\' && *pch != '/')
4459 *++pch = '\\';
4460 *++pch = '*';
4461 *++pch = NUL;
4462
4463 hFile = FindFirstFile(TempName, &d);
4464 if (hFile == INVALID_HANDLE_VALUE)
4465 goto getout;
4466 (void)FindClose(hFile);
4467 }
4468 }
4469
4470 if (p & W_OK)
4471 {
4472 /* Trying to create a temporary file in the directory should catch
4473 * directories on read-only network shares. However, in
4474 * directories whose ACL allows writes but denies deletes will end
4475 * up keeping the temporary file :-(. */
4476#ifdef FEAT_MBYTE
4477 if (wn != NULL)
4478 {
4479 if (!GetTempFileNameW(wn, L"VIM", 0, TempNameW))
4480 {
4481 if (GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
4482 goto getout;
4483
4484 /* Retry with non-wide function (for Windows 98). */
4485 vim_free(wn);
4486 wn = NULL;
4487 }
4488 else
4489 DeleteFileW(TempNameW);
4490 }
4491 if (wn == NULL)
4492#endif
4493 {
4494 if (!GetTempFileName(n, "VIM", 0, TempName))
4495 goto getout;
4496 mch_remove((char_u *)TempName);
4497 }
4498 }
4499 }
4500 else
4501 {
4502 /* Trying to open the file for the required access does ACL, read-only
4503 * network share, and file attribute checks. */
4504 am = ((p & W_OK) ? GENERIC_WRITE : 0)
4505 | ((p & R_OK) ? GENERIC_READ : 0);
4506#ifdef FEAT_MBYTE
4507 if (wn != NULL)
4508 {
4509 hFile = CreateFileW(wn, am, 0, NULL, OPEN_EXISTING, 0, NULL);
4510 if (hFile == INVALID_HANDLE_VALUE
4511 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
4512 {
4513 /* Retry with non-wide function (for Windows 98). */
4514 vim_free(wn);
4515 wn = NULL;
4516 }
4517 }
4518 if (wn == NULL)
4519#endif
4520 hFile = CreateFile(n, am, 0, NULL, OPEN_EXISTING, 0, NULL);
4521 if (hFile == INVALID_HANDLE_VALUE)
4522 goto getout;
4523 CloseHandle(hFile);
4524 }
4525
4526 retval = 0; /* success */
4527getout:
4528#ifdef FEAT_MBYTE
4529 vim_free(wn);
4530#endif
4531 return retval;
4532}
4533
4534#if defined(FEAT_MBYTE) || defined(PROTO)
4535/*
4536 * Version of open() that may use ucs2 file name.
4537 */
4538 int
4539mch_open(char *name, int flags, int mode)
4540{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004541 /* _wopen() does not work with Borland C 5.5: creates a read-only file. */
4542# ifndef __BORLANDC__
Bram Moolenaar071d4272004-06-13 20:20:40 +00004543 WCHAR *wn;
4544 int f;
4545
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004546 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004547 {
4548 wn = enc_to_ucs2(name, NULL);
4549 if (wn != NULL)
4550 {
4551 f = _wopen(wn, flags, mode);
4552 vim_free(wn);
4553 if (f >= 0)
4554 return f;
4555 /* Retry with non-wide function (for Windows 98). Can't use
4556 * GetLastError() here and it's unclear what errno gets set to if
4557 * the _wopen() fails for missing wide functions. */
4558 }
4559 }
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004560# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004561
4562 return open(name, flags, mode);
4563}
4564
4565/*
4566 * Version of fopen() that may use ucs2 file name.
4567 */
4568 FILE *
4569mch_fopen(char *name, char *mode)
4570{
4571 WCHAR *wn, *wm;
4572 FILE *f = NULL;
4573
4574 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage
4575# ifdef __BORLANDC__
4576 /* Wide functions of Borland C 5.5 do not work on Windows 98. */
4577 && g_PlatformId == VER_PLATFORM_WIN32_NT
4578# endif
4579 )
4580 {
4581 wn = enc_to_ucs2(name, NULL);
4582 wm = enc_to_ucs2(mode, NULL);
4583 if (wn != NULL && wm != NULL)
4584 f = _wfopen(wn, wm);
4585 vim_free(wn);
4586 vim_free(wm);
4587 if (f != NULL)
4588 return f;
4589 /* Retry with non-wide function (for Windows 98). Can't use
4590 * GetLastError() here and it's unclear what errno gets set to if
4591 * the _wfopen() fails for missing wide functions. */
4592 }
4593
4594 return fopen(name, mode);
4595}
4596#endif
4597
4598#ifdef FEAT_MBYTE
4599/*
4600 * SUB STREAM (aka info stream) handling:
4601 *
4602 * NTFS can have sub streams for each file. Normal contents of file is
4603 * stored in the main stream, and extra contents (author information and
4604 * title and so on) can be stored in sub stream. After Windows 2000, user
4605 * can access and store those informations in sub streams via explorer's
4606 * property menuitem in right click menu. Those informations in sub streams
4607 * were lost when copying only the main stream. So we have to copy sub
4608 * streams.
4609 *
4610 * Incomplete explanation:
4611 * http://msdn.microsoft.com/library/en-us/dnw2k/html/ntfs5.asp
4612 * More useful info and an example:
4613 * http://www.sysinternals.com/ntw2k/source/misc.shtml#streams
4614 */
4615
4616/*
4617 * Copy info stream data "substream". Read from the file with BackupRead(sh)
4618 * and write to stream "substream" of file "to".
4619 * Errors are ignored.
4620 */
4621 static void
4622copy_substream(HANDLE sh, void *context, WCHAR *to, WCHAR *substream, long len)
4623{
4624 HANDLE hTo;
4625 WCHAR *to_name;
4626
4627 to_name = malloc((wcslen(to) + wcslen(substream) + 1) * sizeof(WCHAR));
4628 wcscpy(to_name, to);
4629 wcscat(to_name, substream);
4630
4631 hTo = CreateFileW(to_name, GENERIC_WRITE, 0, NULL, OPEN_ALWAYS,
4632 FILE_ATTRIBUTE_NORMAL, NULL);
4633 if (hTo != INVALID_HANDLE_VALUE)
4634 {
4635 long done;
4636 DWORD todo;
4637 DWORD readcnt, written;
4638 char buf[4096];
4639
4640 /* Copy block of bytes at a time. Abort when something goes wrong. */
4641 for (done = 0; done < len; done += written)
4642 {
4643 /* (size_t) cast for Borland C 5.5 */
4644 todo = (size_t)(len - done) > sizeof(buf) ? sizeof(buf)
4645 : (size_t)(len - done);
4646 if (!BackupRead(sh, (LPBYTE)buf, todo, &readcnt,
4647 FALSE, FALSE, context)
4648 || readcnt != todo
4649 || !WriteFile(hTo, buf, todo, &written, NULL)
4650 || written != todo)
4651 break;
4652 }
4653 CloseHandle(hTo);
4654 }
4655
4656 free(to_name);
4657}
4658
4659/*
4660 * Copy info streams from file "from" to file "to".
4661 */
4662 static void
4663copy_infostreams(char_u *from, char_u *to)
4664{
4665 WCHAR *fromw;
4666 WCHAR *tow;
4667 HANDLE sh;
4668 WIN32_STREAM_ID sid;
4669 int headersize;
4670 WCHAR streamname[_MAX_PATH];
4671 DWORD readcount;
4672 void *context = NULL;
4673 DWORD lo, hi;
4674 int len;
4675
4676 /* Convert the file names to wide characters. */
4677 fromw = enc_to_ucs2(from, NULL);
4678 tow = enc_to_ucs2(to, NULL);
4679 if (fromw != NULL && tow != NULL)
4680 {
4681 /* Open the file for reading. */
4682 sh = CreateFileW(fromw, GENERIC_READ, FILE_SHARE_READ, NULL,
4683 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
4684 if (sh != INVALID_HANDLE_VALUE)
4685 {
4686 /* Use BackupRead() to find the info streams. Repeat until we
4687 * have done them all.*/
4688 for (;;)
4689 {
4690 /* Get the header to find the length of the stream name. If
4691 * the "readcount" is zero we have done all info streams. */
4692 ZeroMemory(&sid, sizeof(WIN32_STREAM_ID));
4693 headersize = (char *)&sid.cStreamName - (char *)&sid.dwStreamId;
4694 if (!BackupRead(sh, (LPBYTE)&sid, headersize,
4695 &readcount, FALSE, FALSE, &context)
4696 || readcount == 0)
4697 break;
4698
4699 /* We only deal with streams that have a name. The normal
4700 * file data appears to be without a name, even though docs
4701 * suggest it is called "::$DATA". */
4702 if (sid.dwStreamNameSize > 0)
4703 {
4704 /* Read the stream name. */
4705 if (!BackupRead(sh, (LPBYTE)streamname,
4706 sid.dwStreamNameSize,
4707 &readcount, FALSE, FALSE, &context))
4708 break;
4709
4710 /* Copy an info stream with a name ":anything:$DATA".
4711 * Skip "::$DATA", it has no stream name (examples suggest
4712 * it might be used for the normal file contents).
4713 * Note that BackupRead() counts bytes, but the name is in
4714 * wide characters. */
4715 len = readcount / sizeof(WCHAR);
4716 streamname[len] = 0;
4717 if (len > 7 && wcsicmp(streamname + len - 6,
4718 L":$DATA") == 0)
4719 {
4720 streamname[len - 6] = 0;
4721 copy_substream(sh, &context, tow, streamname,
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00004722 (long)sid.Size.u.LowPart);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004723 }
4724 }
4725
4726 /* Advance to the next stream. We might try seeking too far,
4727 * but BackupSeek() doesn't skip over stream borders, thus
4728 * that's OK. */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00004729 (void)BackupSeek(sh, sid.Size.u.LowPart, sid.Size.u.HighPart,
Bram Moolenaar071d4272004-06-13 20:20:40 +00004730 &lo, &hi, &context);
4731 }
4732
4733 /* Clear the context. */
4734 (void)BackupRead(sh, NULL, 0, &readcount, TRUE, FALSE, &context);
4735
4736 CloseHandle(sh);
4737 }
4738 }
4739 vim_free(fromw);
4740 vim_free(tow);
4741}
4742#endif
4743
4744/*
4745 * Copy file attributes from file "from" to file "to".
4746 * For Windows NT and later we copy info streams.
4747 * Always returns zero, errors are ignored.
4748 */
4749 int
4750mch_copy_file_attribute(char_u *from, char_u *to)
4751{
4752#ifdef FEAT_MBYTE
4753 /* File streams only work on Windows NT and later. */
4754 PlatformId();
4755 if (g_PlatformId == VER_PLATFORM_WIN32_NT)
4756 copy_infostreams(from, to);
4757#endif
4758 return 0;
4759}
4760
4761#if defined(MYRESETSTKOFLW) || defined(PROTO)
4762/*
4763 * Recreate a destroyed stack guard page in win32.
4764 * Written by Benjamin Peterson.
4765 */
4766
4767/* These magic numbers are from the MS header files */
4768#define MIN_STACK_WIN9X 17
4769#define MIN_STACK_WINNT 2
4770
4771/*
4772 * This function does the same thing as _resetstkoflw(), which is only
4773 * available in DevStudio .net and later.
4774 * Returns 0 for failure, 1 for success.
4775 */
4776 int
4777myresetstkoflw(void)
4778{
4779 BYTE *pStackPtr;
4780 BYTE *pGuardPage;
4781 BYTE *pStackBase;
4782 BYTE *pLowestPossiblePage;
4783 MEMORY_BASIC_INFORMATION mbi;
4784 SYSTEM_INFO si;
4785 DWORD nPageSize;
4786 DWORD dummy;
4787
4788 /* This code will not work on win32s. */
4789 PlatformId();
4790 if (g_PlatformId == VER_PLATFORM_WIN32s)
4791 return 0;
4792
4793 /* We need to know the system page size. */
4794 GetSystemInfo(&si);
4795 nPageSize = si.dwPageSize;
4796
4797 /* ...and the current stack pointer */
4798 pStackPtr = (BYTE*)_alloca(1);
4799
4800 /* ...and the base of the stack. */
4801 if (VirtualQuery(pStackPtr, &mbi, sizeof mbi) == 0)
4802 return 0;
4803 pStackBase = (BYTE*)mbi.AllocationBase;
4804
4805 /* ...and the page thats min_stack_req pages away from stack base; this is
4806 * the lowest page we could use. */
4807 pLowestPossiblePage = pStackBase + ((g_PlatformId == VER_PLATFORM_WIN32_NT)
4808 ? MIN_STACK_WINNT : MIN_STACK_WIN9X) * nPageSize;
4809
4810 /* On Win95, we want the next page down from the end of the stack. */
4811 if (g_PlatformId == VER_PLATFORM_WIN32_WINDOWS)
4812 {
4813 /* Find the page that's only 1 page down from the page that the stack
4814 * ptr is in. */
4815 pGuardPage = (BYTE*)((DWORD)nPageSize * (((DWORD)pStackPtr
4816 / (DWORD)nPageSize) - 1));
4817 if (pGuardPage < pLowestPossiblePage)
4818 return 0;
4819
4820 /* Apply the noaccess attribute to the page -- there's no guard
4821 * attribute in win95-type OSes. */
4822 if (!VirtualProtect(pGuardPage, nPageSize, PAGE_NOACCESS, &dummy))
4823 return 0;
4824 }
4825 else
4826 {
4827 /* On NT, however, we want the first committed page in the stack Start
4828 * at the stack base and move forward through memory until we find a
4829 * committed block. */
4830 BYTE *pBlock = pStackBase;
4831
4832 while (1)
4833 {
4834 if (VirtualQuery(pBlock, &mbi, sizeof mbi) == 0)
4835 return 0;
4836
4837 pBlock += mbi.RegionSize;
4838
4839 if (mbi.State & MEM_COMMIT)
4840 break;
4841 }
4842
4843 /* mbi now describes the first committed block in the stack. */
4844 if (mbi.Protect & PAGE_GUARD)
4845 return 1;
4846
4847 /* decide where the guard page should start */
4848 if ((long_u)(mbi.BaseAddress) < (long_u)pLowestPossiblePage)
4849 pGuardPage = pLowestPossiblePage;
4850 else
4851 pGuardPage = (BYTE*)mbi.BaseAddress;
4852
4853 /* allocate the guard page */
4854 if (!VirtualAlloc(pGuardPage, nPageSize, MEM_COMMIT, PAGE_READWRITE))
4855 return 0;
4856
4857 /* apply the guard attribute to the page */
4858 if (!VirtualProtect(pGuardPage, nPageSize, PAGE_READWRITE | PAGE_GUARD,
4859 &dummy))
4860 return 0;
4861 }
4862
4863 return 1;
4864}
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004865#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004866
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004867
4868#if defined(FEAT_MBYTE) || defined(PROTO)
4869/*
4870 * The command line arguments in UCS2
4871 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00004872static int nArgsW = 0;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004873static LPWSTR *ArglistW = NULL;
4874static int global_argc = 0;
4875static char **global_argv;
4876
4877static int used_file_argc = 0; /* last argument in global_argv[] used
4878 for the argument list. */
4879static int *used_file_indexes = NULL; /* indexes in global_argv[] for
4880 command line arguments added to
4881 the argument list */
4882static int used_file_count = 0; /* nr of entries in used_file_indexes */
4883static int used_file_literal = FALSE; /* take file names literally */
4884static int used_file_full_path = FALSE; /* file name was full path */
4885static int used_alist_count = 0;
4886
4887
4888/*
4889 * Get the command line arguments. Unicode version.
4890 * Returns argc. Zero when something fails.
4891 */
4892 int
4893get_cmd_argsW(char ***argvp)
4894{
4895 char **argv = NULL;
4896 int argc = 0;
4897 int i;
4898
4899 ArglistW = CommandLineToArgvW(GetCommandLineW(), &nArgsW);
4900 if (ArglistW != NULL)
4901 {
4902 argv = malloc((nArgsW + 1) * sizeof(char *));
4903 if (argv != NULL)
4904 {
4905 argc = nArgsW;
4906 argv[argc] = NULL;
4907 for (i = 0; i < argc; ++i)
4908 {
4909 int len;
4910
4911 /* Convert each Unicode argument to the current codepage. */
4912 WideCharToMultiByte_alloc(GetACP(), 0,
4913 ArglistW[i], wcslen(ArglistW[i]) + 1,
4914 (LPSTR *)&argv[i], &len, 0, 0);
4915 if (argv[i] == NULL)
4916 {
4917 /* Out of memory, clear everything. */
4918 while (i > 0)
4919 free(argv[--i]);
4920 free(argv);
4921 argc = 0;
4922 }
4923 }
4924 }
4925 }
4926
4927 global_argc = argc;
4928 global_argv = argv;
4929 if (argc > 0)
4930 used_file_indexes = malloc(argc * sizeof(int));
4931
4932 if (argvp != NULL)
4933 *argvp = argv;
4934 return argc;
4935}
4936
4937 void
4938free_cmd_argsW(void)
4939{
4940 if (ArglistW != NULL)
4941 {
4942 GlobalFree(ArglistW);
4943 ArglistW = NULL;
4944 }
4945}
4946
4947/*
4948 * Remember "name" is an argument that was added to the argument list.
4949 * This avoids that we have to re-parse the argument list when fix_arg_enc()
4950 * is called.
4951 */
4952 void
4953used_file_arg(char *name, int literal, int full_path)
4954{
4955 int i;
4956
4957 if (used_file_indexes == NULL)
4958 return;
4959 for (i = used_file_argc + 1; i < global_argc; ++i)
4960 if (STRCMP(global_argv[i], name) == 0)
4961 {
4962 used_file_argc = i;
4963 used_file_indexes[used_file_count++] = i;
4964 break;
4965 }
4966 used_file_literal = literal;
4967 used_file_full_path = full_path;
4968}
4969
4970/*
4971 * Remember the length of the argument list as it was. If it changes then we
4972 * leave it alone when 'encoding' is set.
4973 */
4974 void
4975set_alist_count(void)
4976{
4977 used_alist_count = GARGCOUNT;
4978}
4979
4980/*
4981 * Fix the encoding of the command line arguments. Invoked when 'encoding'
4982 * has been changed while starting up. Use the UCS-2 command line arguments
4983 * and convert them to 'encoding'.
4984 */
4985 void
4986fix_arg_enc(void)
4987{
4988 int i;
4989 int idx;
4990 char_u *str;
Bram Moolenaar86b68352004-12-27 21:59:20 +00004991 int *fnum_list;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004992
4993 /* Safety checks:
4994 * - if argument count differs between the wide and non-wide argument
4995 * list, something must be wrong.
4996 * - the file name arguments must have been located.
4997 * - the length of the argument list wasn't changed by the user.
4998 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00004999 if (global_argc != nArgsW
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005000 || ArglistW == NULL
5001 || used_file_indexes == NULL
5002 || used_file_count == 0
5003 || used_alist_count != GARGCOUNT)
5004 return;
5005
Bram Moolenaar86b68352004-12-27 21:59:20 +00005006 /* Remember the buffer numbers for the arguments. */
5007 fnum_list = (int *)alloc((int)sizeof(int) * GARGCOUNT);
5008 if (fnum_list == NULL)
5009 return; /* out of memory */
5010 for (i = 0; i < GARGCOUNT; ++i)
5011 fnum_list[i] = GARGLIST[i].ae_fnum;
5012
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005013 /* Clear the argument list. Make room for the new arguments. */
5014 alist_clear(&global_alist);
5015 if (ga_grow(&global_alist.al_ga, used_file_count) == FAIL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00005016 return; /* out of memory */
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005017
5018 for (i = 0; i < used_file_count; ++i)
5019 {
5020 idx = used_file_indexes[i];
5021 str = ucs2_to_enc(ArglistW[idx], NULL);
5022 if (str != NULL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00005023 {
5024 /* Re-use the old buffer by renaming it. When not using literal
5025 * names it's done by alist_expand() below. */
5026 if (used_file_literal)
5027 buf_set_name(fnum_list[i], str);
5028
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005029 alist_add(&global_alist, str, used_file_literal ? 2 : 0);
Bram Moolenaar86b68352004-12-27 21:59:20 +00005030 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005031 }
5032
5033 if (!used_file_literal)
5034 {
5035 /* Now expand wildcards in the arguments. */
5036 /* Temporarily add '(' and ')' to 'isfname'. These are valid
5037 * filename characters but are excluded from 'isfname' to make
5038 * "gf" work on a file name in parenthesis (e.g.: see vim.h). */
5039 do_cmdline_cmd((char_u *)":let SaVe_ISF = &isf|set isf+=(,)");
Bram Moolenaar86b68352004-12-27 21:59:20 +00005040 alist_expand(fnum_list, used_alist_count);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005041 do_cmdline_cmd((char_u *)":let &isf = SaVe_ISF|unlet SaVe_ISF");
5042 }
5043
5044 /* If wildcard expansion failed, we are editing the first file of the
5045 * arglist and there is no file name: Edit the first argument now. */
5046 if (curwin->w_arg_idx == 0 && curbuf->b_fname == NULL)
5047 {
5048 do_cmdline_cmd((char_u *)":rewind");
5049 if (GARGCOUNT == 1 && used_file_full_path)
5050 (void)vim_chdirfile(alist_name(&GARGLIST[0]));
5051 }
Bram Moolenaar86b68352004-12-27 21:59:20 +00005052
5053 set_alist_count();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005054}
Bram Moolenaar071d4272004-06-13 20:20:40 +00005055#endif