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