blob: 371363bf00bc813671a74e584a68113dcdc3a962 [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
Bram Moolenaar8c85fa32011-08-10 17:08:03 +0200155/* Enable common dialogs input unicode from IME if posible. */
156#ifdef FEAT_MBYTE
157LRESULT (WINAPI *pDispatchMessage)(LPMSG) = DispatchMessage;
158BOOL (WINAPI *pGetMessage)(LPMSG, HWND, UINT, UINT) = GetMessage;
159BOOL (WINAPI *pIsDialogMessage)(HWND, LPMSG) = IsDialogMessage;
160BOOL (WINAPI *pPeekMessage)(LPMSG, HWND, UINT, UINT, UINT) = PeekMessage;
161#endif
162
Bram Moolenaar071d4272004-06-13 20:20:40 +0000163#ifndef FEAT_GUI_W32
164/* Win32 Console handles for input and output */
165static HANDLE g_hConIn = INVALID_HANDLE_VALUE;
166static HANDLE g_hConOut = INVALID_HANDLE_VALUE;
167
168/* Win32 Screen buffer,coordinate,console I/O information */
169static SMALL_RECT g_srScrollRegion;
170static COORD g_coord; /* 0-based, but external coords are 1-based */
171
172/* The attribute of the screen when the editor was started */
173static WORD g_attrDefault = 7; /* lightgray text on black background */
174static WORD g_attrCurrent;
175
176static int g_fCBrkPressed = FALSE; /* set by ctrl-break interrupt */
177static int g_fCtrlCPressed = FALSE; /* set when ctrl-C or ctrl-break detected */
178static int g_fForceExit = FALSE; /* set when forcefully exiting */
179
180static void termcap_mode_start(void);
181static void termcap_mode_end(void);
182static void clear_chars(COORD coord, DWORD n);
183static void clear_screen(void);
184static void clear_to_end_of_display(void);
185static void clear_to_end_of_line(void);
186static void scroll(unsigned cLines);
187static void set_scroll_region(unsigned left, unsigned top,
188 unsigned right, unsigned bottom);
189static void insert_lines(unsigned cLines);
190static void delete_lines(unsigned cLines);
191static void gotoxy(unsigned x, unsigned y);
192static void normvideo(void);
193static void textattr(WORD wAttr);
194static void textcolor(WORD wAttr);
195static void textbackground(WORD wAttr);
196static void standout(void);
197static void standend(void);
198static void visual_bell(void);
199static void cursor_visible(BOOL fVisible);
200static BOOL write_chars(LPCSTR pchBuf, DWORD cchToWrite);
201static char_u tgetch(int *pmodifiers, char_u *pch2);
202static void create_conin(void);
203static int s_cursor_visible = TRUE;
204static int did_create_conin = FALSE;
205#else
206static int s_dont_use_vimrun = TRUE;
207static int need_vimrun_warning = FALSE;
208static char *vimrun_path = "vimrun ";
209#endif
210
211#ifndef FEAT_GUI_W32
212static int suppress_winsize = 1; /* don't fiddle with console */
213#endif
214
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200215static char_u *exe_path = NULL;
216
Bram Moolenaar071d4272004-06-13 20:20:40 +0000217 static void
218get_exe_name(void)
219{
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100220 /* Maximum length of $PATH is more than MAXPATHL. 8191 is often mentioned
221 * as the maximum length that works (plus a NUL byte). */
222#define MAX_ENV_PATH_LEN 8192
223 char temp[MAX_ENV_PATH_LEN];
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200224 char_u *p;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000225
226 if (exe_name == NULL)
227 {
228 /* store the name of the executable, may be used for $VIM */
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100229 GetModuleFileName(NULL, temp, MAX_ENV_PATH_LEN - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000230 if (*temp != NUL)
231 exe_name = FullName_save((char_u *)temp, FALSE);
232 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000233
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200234 if (exe_path == NULL && exe_name != NULL)
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000235 {
Bram Moolenaar6b5ef062010-10-27 12:18:00 +0200236 exe_path = vim_strnsave(exe_name,
237 (int)(gettail_sep(exe_name) - exe_name));
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200238 if (exe_path != NULL)
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000239 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200240 /* Append our starting directory to $PATH, so that when doing
241 * "!xxd" it's found in our starting directory. Needed because
242 * SearchPath() also looks there. */
243 p = mch_getenv("PATH");
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100244 if (p == NULL
245 || STRLEN(p) + STRLEN(exe_path) + 2 < MAX_ENV_PATH_LEN)
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200246 {
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100247 if (p == NULL || *p == NUL)
248 temp[0] = NUL;
249 else
250 {
251 STRCPY(temp, p);
252 STRCAT(temp, ";");
253 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200254 STRCAT(temp, exe_path);
255 vim_setenv((char_u *)"PATH", temp);
256 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000257 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000258 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000259}
260
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200261/*
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100262 * Unescape characters in "p" that appear in "escaped".
263 */
264 static void
265unescape_shellxquote(char_u *p, char_u *escaped)
266{
Bram Moolenaar4336cdf2012-02-29 13:58:47 +0100267 int l = (int)STRLEN(p);
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100268 int n;
269
270 while (*p != NUL)
271 {
272 if (*p == '^' && vim_strchr(escaped, p[1]) != NULL)
273 mch_memmove(p, p + 1, l--);
274#ifdef FEAT_MBYTE
275 n = (*mb_ptr2len)(p);
276#else
277 n = 1;
278#endif
279 p += n;
280 l -= n;
281 }
282}
283
284/*
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200285 * Load library "name".
286 */
287 HINSTANCE
288vimLoadLib(char *name)
289{
290 HINSTANCE dll = NULL;
291 char old_dir[MAXPATHL];
292
293 if (exe_path == NULL)
294 get_exe_name();
295 if (exe_path != NULL && mch_dirname(old_dir, MAXPATHL) == OK)
296 {
297 /* Change directory to where the executable is, both to make sure we
298 * find a .dll there and to avoid looking for a .dll in the current
299 * directory. */
300 mch_chdir(exe_path);
301 dll = LoadLibrary(name);
302 mch_chdir(old_dir);
303 }
304 return dll;
305}
306
Bram Moolenaar071d4272004-06-13 20:20:40 +0000307#if defined(DYNAMIC_GETTEXT) || defined(PROTO)
308# ifndef GETTEXT_DLL
309# define GETTEXT_DLL "libintl.dll"
310# endif
311/* Dummy funcitons */
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000312static char *null_libintl_gettext(const char *);
313static char *null_libintl_textdomain(const char *);
314static char *null_libintl_bindtextdomain(const char *, const char *);
315static char *null_libintl_bind_textdomain_codeset(const char *, const char *);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000316
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200317static HINSTANCE hLibintlDLL = NULL;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000318char *(*dyn_libintl_gettext)(const char *) = null_libintl_gettext;
319char *(*dyn_libintl_textdomain)(const char *) = null_libintl_textdomain;
320char *(*dyn_libintl_bindtextdomain)(const char *, const char *)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000321 = null_libintl_bindtextdomain;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000322char *(*dyn_libintl_bind_textdomain_codeset)(const char *, const char *)
323 = null_libintl_bind_textdomain_codeset;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000324
325 int
326dyn_libintl_init(char *libname)
327{
328 int i;
329 static struct
330 {
331 char *name;
332 FARPROC *ptr;
333 } libintl_entry[] =
334 {
335 {"gettext", (FARPROC*)&dyn_libintl_gettext},
336 {"textdomain", (FARPROC*)&dyn_libintl_textdomain},
337 {"bindtextdomain", (FARPROC*)&dyn_libintl_bindtextdomain},
338 {NULL, NULL}
339 };
340
341 /* No need to initialize twice. */
342 if (hLibintlDLL)
343 return 1;
344 /* Load gettext library (libintl.dll) */
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200345 hLibintlDLL = vimLoadLib(libname != NULL ? libname : GETTEXT_DLL);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000346 if (!hLibintlDLL)
347 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200348 if (p_verbose > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000349 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200350 verbose_enter();
351 EMSG2(_(e_loadlib), GETTEXT_DLL);
352 verbose_leave();
Bram Moolenaar071d4272004-06-13 20:20:40 +0000353 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200354 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000355 }
356 for (i = 0; libintl_entry[i].name != NULL
357 && libintl_entry[i].ptr != NULL; ++i)
358 {
359 if ((*libintl_entry[i].ptr = (FARPROC)GetProcAddress(hLibintlDLL,
360 libintl_entry[i].name)) == NULL)
361 {
362 dyn_libintl_end();
363 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +0000364 {
365 verbose_enter();
Bram Moolenaar071d4272004-06-13 20:20:40 +0000366 EMSG2(_(e_loadfunc), libintl_entry[i].name);
Bram Moolenaara04f10b2005-05-31 22:09:46 +0000367 verbose_leave();
368 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000369 return 0;
370 }
371 }
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000372
373 /* The bind_textdomain_codeset() function is optional. */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000374 dyn_libintl_bind_textdomain_codeset = (void *)GetProcAddress(hLibintlDLL,
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000375 "bind_textdomain_codeset");
376 if (dyn_libintl_bind_textdomain_codeset == NULL)
377 dyn_libintl_bind_textdomain_codeset =
378 null_libintl_bind_textdomain_codeset;
379
Bram Moolenaar071d4272004-06-13 20:20:40 +0000380 return 1;
381}
382
383 void
384dyn_libintl_end()
385{
386 if (hLibintlDLL)
387 FreeLibrary(hLibintlDLL);
388 hLibintlDLL = NULL;
389 dyn_libintl_gettext = null_libintl_gettext;
390 dyn_libintl_textdomain = null_libintl_textdomain;
391 dyn_libintl_bindtextdomain = null_libintl_bindtextdomain;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000392 dyn_libintl_bind_textdomain_codeset = null_libintl_bind_textdomain_codeset;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000393}
394
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000395/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +0000396 static char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000397null_libintl_gettext(const char *msgid)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000398{
399 return (char*)msgid;
400}
401
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000402/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +0000403 static char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000404null_libintl_bindtextdomain(const char *domainname, const char *dirname)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000405{
406 return NULL;
407}
408
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000409/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +0000410 static char *
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000411null_libintl_bind_textdomain_codeset(const char *domainname,
412 const char *codeset)
413{
414 return NULL;
415}
416
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000417/*ARGSUSED*/
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000418 static char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000419null_libintl_textdomain(const char *domainname)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000420{
421 return NULL;
422}
423
424#endif /* DYNAMIC_GETTEXT */
425
426/* This symbol is not defined in older versions of the SDK or Visual C++ */
427
428#ifndef VER_PLATFORM_WIN32_WINDOWS
429# define VER_PLATFORM_WIN32_WINDOWS 1
430#endif
431
432DWORD g_PlatformId;
433
434#ifdef HAVE_ACL
435# include <aclapi.h>
436/*
437 * These are needed to dynamically load the ADVAPI DLL, which is not
438 * implemented under Windows 95 (and causes VIM to crash)
439 */
440typedef DWORD (WINAPI *PSNSECINFO) (LPTSTR, enum SE_OBJECT_TYPE,
441 SECURITY_INFORMATION, PSID, PSID, PACL, PACL);
442typedef DWORD (WINAPI *PGNSECINFO) (LPSTR, enum SE_OBJECT_TYPE,
443 SECURITY_INFORMATION, PSID *, PSID *, PACL *, PACL *,
444 PSECURITY_DESCRIPTOR *);
445
446static HANDLE advapi_lib = NULL; /* Handle for ADVAPI library */
447static PSNSECINFO pSetNamedSecurityInfo;
448static PGNSECINFO pGetNamedSecurityInfo;
449#endif
450
Bram Moolenaar4b9669f2011-07-07 16:20:52 +0200451typedef BOOL (WINAPI *PSETHANDLEINFORMATION)(HANDLE, DWORD, DWORD);
452
453static BOOL allowPiping = FALSE;
454static PSETHANDLEINFORMATION pSetHandleInformation;
455
Bram Moolenaar071d4272004-06-13 20:20:40 +0000456/*
457 * Set g_PlatformId to VER_PLATFORM_WIN32_NT (NT) or
458 * VER_PLATFORM_WIN32_WINDOWS (Win95).
459 */
460 void
461PlatformId(void)
462{
463 static int done = FALSE;
464
465 if (!done)
466 {
467 OSVERSIONINFO ovi;
468
469 ovi.dwOSVersionInfoSize = sizeof(ovi);
470 GetVersionEx(&ovi);
471
472 g_PlatformId = ovi.dwPlatformId;
473
474#ifdef HAVE_ACL
475 /*
476 * Load the ADVAPI runtime if we are on anything
477 * other than Windows 95
478 */
479 if (g_PlatformId == VER_PLATFORM_WIN32_NT)
480 {
481 /*
482 * do this load. Problems: Doesn't unload at end of run (this is
483 * theoretically okay, since Windows should unload it when VIM
484 * terminates). Should we be using the 'mch_libcall' routines?
485 * Seems like a lot of overhead to load/unload ADVAPI32.DLL each
486 * time we verify security...
487 */
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200488 advapi_lib = vimLoadLib("ADVAPI32.DLL");
Bram Moolenaar071d4272004-06-13 20:20:40 +0000489 if (advapi_lib != NULL)
490 {
491 pSetNamedSecurityInfo = (PSNSECINFO)GetProcAddress(advapi_lib,
492 "SetNamedSecurityInfoA");
493 pGetNamedSecurityInfo = (PGNSECINFO)GetProcAddress(advapi_lib,
494 "GetNamedSecurityInfoA");
495 if (pSetNamedSecurityInfo == NULL
496 || pGetNamedSecurityInfo == NULL)
497 {
498 /* If we can't get the function addresses, set advapi_lib
499 * to NULL so that we don't use them. */
500 FreeLibrary(advapi_lib);
501 advapi_lib = NULL;
502 }
503 }
504 }
505#endif
Bram Moolenaar4b9669f2011-07-07 16:20:52 +0200506 /*
507 * If we are on windows NT, try to load the pipe functions, only
508 * available from Win2K.
509 */
510 if (g_PlatformId == VER_PLATFORM_WIN32_NT)
511 {
512 HANDLE kernel32 = GetModuleHandle("kernel32");
513 pSetHandleInformation = (PSETHANDLEINFORMATION)GetProcAddress(
514 kernel32, "SetHandleInformation");
515
516 allowPiping = pSetHandleInformation != NULL;
517 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000518 done = TRUE;
519 }
520}
521
522/*
523 * Return TRUE when running on Windows 95 (or 98 or ME).
524 * Only to be used after mch_init().
525 */
526 int
527mch_windows95(void)
528{
529 return g_PlatformId == VER_PLATFORM_WIN32_WINDOWS;
530}
531
532#ifdef FEAT_GUI_W32
533/*
534 * Used to work around the "can't do synchronous spawn"
535 * problem on Win32s, without resorting to Universal Thunk.
536 */
537static int old_num_windows;
538static int num_windows;
539
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000540/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +0000541 static BOOL CALLBACK
542win32ssynch_cb(HWND hwnd, LPARAM lparam)
543{
544 num_windows++;
545 return TRUE;
546}
547#endif
548
549#ifndef FEAT_GUI_W32
550
551#define SHIFT (SHIFT_PRESSED)
552#define CTRL (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED)
553#define ALT (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED)
554#define ALT_GR (RIGHT_ALT_PRESSED | LEFT_CTRL_PRESSED)
555
556
557/* When uChar.AsciiChar is 0, then we need to look at wVirtualKeyCode.
558 * We map function keys to their ANSI terminal equivalents, as produced
559 * by ANSI.SYS, for compatibility with the MS-DOS version of Vim. Any
560 * ANSI key with a value >= '\300' is nonstandard, but provided anyway
561 * so that the user can have access to all SHIFT-, CTRL-, and ALT-
562 * combinations of function/arrow/etc keys.
563 */
564
Bram Moolenaard6f676d2005-06-01 21:51:55 +0000565static const struct
Bram Moolenaar071d4272004-06-13 20:20:40 +0000566{
567 WORD wVirtKey;
568 BOOL fAnsiKey;
569 int chAlone;
570 int chShift;
571 int chCtrl;
572 int chAlt;
573} VirtKeyMap[] =
574{
575
576/* Key ANSI alone shift ctrl alt */
577 { VK_ESCAPE,FALSE, ESC, ESC, ESC, ESC, },
578
579 { VK_F1, TRUE, ';', 'T', '^', 'h', },
580 { VK_F2, TRUE, '<', 'U', '_', 'i', },
581 { VK_F3, TRUE, '=', 'V', '`', 'j', },
582 { VK_F4, TRUE, '>', 'W', 'a', 'k', },
583 { VK_F5, TRUE, '?', 'X', 'b', 'l', },
584 { VK_F6, TRUE, '@', 'Y', 'c', 'm', },
585 { VK_F7, TRUE, 'A', 'Z', 'd', 'n', },
586 { VK_F8, TRUE, 'B', '[', 'e', 'o', },
587 { VK_F9, TRUE, 'C', '\\', 'f', 'p', },
588 { VK_F10, TRUE, 'D', ']', 'g', 'q', },
589 { VK_F11, TRUE, '\205', '\207', '\211', '\213', },
590 { VK_F12, TRUE, '\206', '\210', '\212', '\214', },
591
592 { VK_HOME, TRUE, 'G', '\302', 'w', '\303', },
593 { VK_UP, TRUE, 'H', '\304', '\305', '\306', },
594 { VK_PRIOR, TRUE, 'I', '\307', '\204', '\310', }, /*PgUp*/
595 { VK_LEFT, TRUE, 'K', '\311', 's', '\312', },
596 { VK_RIGHT, TRUE, 'M', '\313', 't', '\314', },
597 { VK_END, TRUE, 'O', '\315', 'u', '\316', },
598 { VK_DOWN, TRUE, 'P', '\317', '\320', '\321', },
599 { VK_NEXT, TRUE, 'Q', '\322', 'v', '\323', }, /*PgDn*/
600 { VK_INSERT,TRUE, 'R', '\324', '\325', '\326', },
601 { VK_DELETE,TRUE, 'S', '\327', '\330', '\331', },
602
603 { VK_SNAPSHOT,TRUE, 0, 0, 0, 'r', }, /*PrtScrn*/
604
605#if 0
606 /* Most people don't have F13-F20, but what the hell... */
607 { VK_F13, TRUE, '\332', '\333', '\334', '\335', },
608 { VK_F14, TRUE, '\336', '\337', '\340', '\341', },
609 { VK_F15, TRUE, '\342', '\343', '\344', '\345', },
610 { VK_F16, TRUE, '\346', '\347', '\350', '\351', },
611 { VK_F17, TRUE, '\352', '\353', '\354', '\355', },
612 { VK_F18, TRUE, '\356', '\357', '\360', '\361', },
613 { VK_F19, TRUE, '\362', '\363', '\364', '\365', },
614 { VK_F20, TRUE, '\366', '\367', '\370', '\371', },
615#endif
616 { VK_ADD, TRUE, 'N', 'N', 'N', 'N', }, /* keyp '+' */
617 { VK_SUBTRACT, TRUE,'J', 'J', 'J', 'J', }, /* keyp '-' */
618 /* { VK_DIVIDE, TRUE,'N', 'N', 'N', 'N', }, keyp '/' */
619 { VK_MULTIPLY, TRUE,'7', '7', '7', '7', }, /* keyp '*' */
620
621 { VK_NUMPAD0,TRUE, '\332', '\333', '\334', '\335', },
622 { VK_NUMPAD1,TRUE, '\336', '\337', '\340', '\341', },
623 { VK_NUMPAD2,TRUE, '\342', '\343', '\344', '\345', },
624 { VK_NUMPAD3,TRUE, '\346', '\347', '\350', '\351', },
625 { VK_NUMPAD4,TRUE, '\352', '\353', '\354', '\355', },
626 { VK_NUMPAD5,TRUE, '\356', '\357', '\360', '\361', },
627 { VK_NUMPAD6,TRUE, '\362', '\363', '\364', '\365', },
628 { VK_NUMPAD7,TRUE, '\366', '\367', '\370', '\371', },
629 { VK_NUMPAD8,TRUE, '\372', '\373', '\374', '\375', },
630 /* Sorry, out of number space! <negri>*/
631 { VK_NUMPAD9,TRUE, '\376', '\377', '\377', '\367', },
632
633};
634
635
636#ifdef _MSC_VER
637// The ToAscii bug destroys several registers. Need to turn off optimization
638// or the GetConsoleKeyboardLayoutName hack will fail in non-debug versions
Bram Moolenaar7b5f8322006-03-23 22:47:08 +0000639# pragma warning(push)
640# pragma warning(disable: 4748)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000641# pragma optimize("", off)
642#endif
643
644#if defined(__GNUC__) && !defined(__MINGW32__) && !defined(__CYGWIN__)
645# define AChar AsciiChar
646#else
647# define AChar uChar.AsciiChar
648#endif
649
650/* The return code indicates key code size. */
651 static int
652#ifdef __BORLANDC__
653 __stdcall
654#endif
655win32_kbd_patch_key(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000656 KEY_EVENT_RECORD *pker)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000657{
658 UINT uMods = pker->dwControlKeyState;
659 static int s_iIsDead = 0;
660 static WORD awAnsiCode[2];
661 static BYTE abKeystate[256];
662
663
664 if (s_iIsDead == 2)
665 {
666 pker->AChar = (CHAR) awAnsiCode[1];
667 s_iIsDead = 0;
668 return 1;
669 }
670
671 if (pker->AChar != 0)
672 return 1;
673
Bram Moolenaar7db5fc82010-05-24 11:59:29 +0200674 vim_memset(abKeystate, 0, sizeof (abKeystate));
Bram Moolenaar071d4272004-06-13 20:20:40 +0000675
676 // Should only be non-NULL on NT 4.0
677 if (s_pfnGetConsoleKeyboardLayoutName != NULL)
678 {
679 CHAR szKLID[KL_NAMELENGTH];
680
681 if ((*s_pfnGetConsoleKeyboardLayoutName)(szKLID))
682 (void)LoadKeyboardLayout(szKLID, KLF_ACTIVATE);
683 }
684
685 /* Clear any pending dead keys */
686 ToAscii(VK_SPACE, MapVirtualKey(VK_SPACE, 0), abKeystate, awAnsiCode, 0);
687
688 if (uMods & SHIFT_PRESSED)
689 abKeystate[VK_SHIFT] = 0x80;
690 if (uMods & CAPSLOCK_ON)
691 abKeystate[VK_CAPITAL] = 1;
692
693 if ((uMods & ALT_GR) == ALT_GR)
694 {
695 abKeystate[VK_CONTROL] = abKeystate[VK_LCONTROL] =
696 abKeystate[VK_MENU] = abKeystate[VK_RMENU] = 0x80;
697 }
698
699 s_iIsDead = ToAscii(pker->wVirtualKeyCode, pker->wVirtualScanCode,
700 abKeystate, awAnsiCode, 0);
701
702 if (s_iIsDead > 0)
703 pker->AChar = (CHAR) awAnsiCode[0];
704
705 return s_iIsDead;
706}
707
708#ifdef _MSC_VER
709/* MUST switch optimization on again here, otherwise a call to
710 * decode_key_event() may crash (e.g. when hitting caps-lock) */
711# pragma optimize("", on)
Bram Moolenaar7b5f8322006-03-23 22:47:08 +0000712# pragma warning(pop)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000713
714# if (_MSC_VER < 1100)
715/* MUST turn off global optimisation for this next function, or
716 * pressing ctrl-minus in insert mode crashes Vim when built with
717 * VC4.1. -- negri. */
718# pragma optimize("g", off)
719# endif
720#endif
721
722static BOOL g_fJustGotFocus = FALSE;
723
724/*
725 * Decode a KEY_EVENT into one or two keystrokes
726 */
727 static BOOL
728decode_key_event(
729 KEY_EVENT_RECORD *pker,
730 char_u *pch,
731 char_u *pch2,
732 int *pmodifiers,
733 BOOL fDoPost)
734{
735 int i;
736 const int nModifs = pker->dwControlKeyState & (SHIFT | ALT | CTRL);
737
738 *pch = *pch2 = NUL;
739 g_fJustGotFocus = FALSE;
740
741 /* ignore key up events */
742 if (!pker->bKeyDown)
743 return FALSE;
744
745 /* ignore some keystrokes */
746 switch (pker->wVirtualKeyCode)
747 {
748 /* modifiers */
749 case VK_SHIFT:
750 case VK_CONTROL:
751 case VK_MENU: /* Alt key */
752 return FALSE;
753
754 default:
755 break;
756 }
757
758 /* special cases */
759 if ((nModifs & CTRL) != 0 && (nModifs & ~CTRL) == 0 && pker->AChar == NUL)
760 {
761 /* Ctrl-6 is Ctrl-^ */
762 if (pker->wVirtualKeyCode == '6')
763 {
764 *pch = Ctrl_HAT;
765 return TRUE;
766 }
767 /* Ctrl-2 is Ctrl-@ */
768 else if (pker->wVirtualKeyCode == '2')
769 {
770 *pch = NUL;
771 return TRUE;
772 }
773 /* Ctrl-- is Ctrl-_ */
774 else if (pker->wVirtualKeyCode == 0xBD)
775 {
776 *pch = Ctrl__;
777 return TRUE;
778 }
779 }
780
781 /* Shift-TAB */
782 if (pker->wVirtualKeyCode == VK_TAB && (nModifs & SHIFT_PRESSED))
783 {
784 *pch = K_NUL;
785 *pch2 = '\017';
786 return TRUE;
787 }
788
789 for (i = sizeof(VirtKeyMap) / sizeof(VirtKeyMap[0]); --i >= 0; )
790 {
791 if (VirtKeyMap[i].wVirtKey == pker->wVirtualKeyCode)
792 {
793 if (nModifs == 0)
794 *pch = VirtKeyMap[i].chAlone;
795 else if ((nModifs & SHIFT) != 0 && (nModifs & ~SHIFT) == 0)
796 *pch = VirtKeyMap[i].chShift;
797 else if ((nModifs & CTRL) != 0 && (nModifs & ~CTRL) == 0)
798 *pch = VirtKeyMap[i].chCtrl;
799 else if ((nModifs & ALT) != 0 && (nModifs & ~ALT) == 0)
800 *pch = VirtKeyMap[i].chAlt;
801
802 if (*pch != 0)
803 {
804 if (VirtKeyMap[i].fAnsiKey)
805 {
806 *pch2 = *pch;
807 *pch = K_NUL;
808 }
809
810 return TRUE;
811 }
812 }
813 }
814
815 i = win32_kbd_patch_key(pker);
816
817 if (i < 0)
818 *pch = NUL;
819 else
820 {
821 *pch = (i > 0) ? pker->AChar : NUL;
822
823 if (pmodifiers != NULL)
824 {
825 /* Pass on the ALT key as a modifier, but only when not combined
826 * with CTRL (which is ALTGR). */
827 if ((nModifs & ALT) != 0 && (nModifs & CTRL) == 0)
828 *pmodifiers |= MOD_MASK_ALT;
829
830 /* Pass on SHIFT only for special keys, because we don't know when
831 * it's already included with the character. */
832 if ((nModifs & SHIFT) != 0 && *pch <= 0x20)
833 *pmodifiers |= MOD_MASK_SHIFT;
834
835 /* Pass on CTRL only for non-special keys, because we don't know
836 * when it's already included with the character. And not when
837 * combined with ALT (which is ALTGR). */
838 if ((nModifs & CTRL) != 0 && (nModifs & ALT) == 0
839 && *pch >= 0x20 && *pch < 0x80)
840 *pmodifiers |= MOD_MASK_CTRL;
841 }
842 }
843
844 return (*pch != NUL);
845}
846
847#ifdef _MSC_VER
848# pragma optimize("", on)
849#endif
850
851#endif /* FEAT_GUI_W32 */
852
853
854#ifdef FEAT_MOUSE
855
856/*
857 * For the GUI the mouse handling is in gui_w32.c.
858 */
859# ifdef FEAT_GUI_W32
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000860/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +0000861 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000862mch_setmouse(int on)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000863{
864}
865# else
866static int g_fMouseAvail = FALSE; /* mouse present */
867static int g_fMouseActive = FALSE; /* mouse enabled */
868static int g_nMouseClick = -1; /* mouse status */
869static int g_xMouse; /* mouse x coordinate */
870static int g_yMouse; /* mouse y coordinate */
871
872/*
873 * Enable or disable mouse input
874 */
875 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000876mch_setmouse(int on)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000877{
878 DWORD cmodein;
879
880 if (!g_fMouseAvail)
881 return;
882
883 g_fMouseActive = on;
884 GetConsoleMode(g_hConIn, &cmodein);
885
886 if (g_fMouseActive)
887 cmodein |= ENABLE_MOUSE_INPUT;
888 else
889 cmodein &= ~ENABLE_MOUSE_INPUT;
890
891 SetConsoleMode(g_hConIn, cmodein);
892}
893
894
895/*
896 * Decode a MOUSE_EVENT. If it's a valid event, return MOUSE_LEFT,
897 * MOUSE_MIDDLE, or MOUSE_RIGHT for a click; MOUSE_DRAG for a mouse
898 * move with a button held down; and MOUSE_RELEASE after a MOUSE_DRAG
899 * or a MOUSE_LEFT, _MIDDLE, or _RIGHT. We encode the button type,
900 * the number of clicks, and the Shift/Ctrl/Alt modifiers in g_nMouseClick,
901 * and we return the mouse position in g_xMouse and g_yMouse.
902 *
903 * Every MOUSE_LEFT, _MIDDLE, or _RIGHT will be followed by zero or more
904 * MOUSE_DRAGs and one MOUSE_RELEASE. MOUSE_RELEASE will be followed only
905 * by MOUSE_LEFT, _MIDDLE, or _RIGHT.
906 *
907 * For multiple clicks, we send, say, MOUSE_LEFT/1 click, MOUSE_RELEASE,
908 * MOUSE_LEFT/2 clicks, MOUSE_RELEASE, MOUSE_LEFT/3 clicks, MOUSE_RELEASE, ....
909 *
910 * Windows will send us MOUSE_MOVED notifications whenever the mouse
911 * moves, even if it stays within the same character cell. We ignore
912 * all MOUSE_MOVED messages if the position hasn't really changed, and
913 * we ignore all MOUSE_MOVED messages where no button is held down (i.e.,
914 * we're only interested in MOUSE_DRAG).
915 *
916 * All of this is complicated by the code that fakes MOUSE_MIDDLE on
917 * 2-button mouses by pressing the left & right buttons simultaneously.
918 * In practice, it's almost impossible to click both at the same time,
919 * so we need to delay a little. Also, we tend not to get MOUSE_RELEASE
920 * in such cases, if the user is clicking quickly.
921 */
922 static BOOL
923decode_mouse_event(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000924 MOUSE_EVENT_RECORD *pmer)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000925{
926 static int s_nOldButton = -1;
927 static int s_nOldMouseClick = -1;
928 static int s_xOldMouse = -1;
929 static int s_yOldMouse = -1;
930 static linenr_T s_old_topline = 0;
931#ifdef FEAT_DIFF
932 static int s_old_topfill = 0;
933#endif
934 static int s_cClicks = 1;
935 static BOOL s_fReleased = TRUE;
936 static DWORD s_dwLastClickTime = 0;
937 static BOOL s_fNextIsMiddle = FALSE;
938
939 static DWORD cButtons = 0; /* number of buttons supported */
940
941 const DWORD LEFT = FROM_LEFT_1ST_BUTTON_PRESSED;
942 const DWORD MIDDLE = FROM_LEFT_2ND_BUTTON_PRESSED;
943 const DWORD RIGHT = RIGHTMOST_BUTTON_PRESSED;
944 const DWORD LEFT_RIGHT = LEFT | RIGHT;
945
946 int nButton;
947
948 if (cButtons == 0 && !GetNumberOfConsoleMouseButtons(&cButtons))
949 cButtons = 2;
950
951 if (!g_fMouseAvail || !g_fMouseActive)
952 {
953 g_nMouseClick = -1;
954 return FALSE;
955 }
956
957 /* get a spurious MOUSE_EVENT immediately after receiving focus; ignore */
958 if (g_fJustGotFocus)
959 {
960 g_fJustGotFocus = FALSE;
961 return FALSE;
962 }
963
964 /* unprocessed mouse click? */
965 if (g_nMouseClick != -1)
966 return TRUE;
967
968 nButton = -1;
969 g_xMouse = pmer->dwMousePosition.X;
970 g_yMouse = pmer->dwMousePosition.Y;
971
972 if (pmer->dwEventFlags == MOUSE_MOVED)
973 {
974 /* ignore MOUSE_MOVED events if (x, y) hasn't changed. (We get these
975 * events even when the mouse moves only within a char cell.) */
976 if (s_xOldMouse == g_xMouse && s_yOldMouse == g_yMouse)
977 return FALSE;
978 }
979
980 /* If no buttons are pressed... */
981 if ((pmer->dwButtonState & ((1 << cButtons) - 1)) == 0)
982 {
983 /* If the last thing returned was MOUSE_RELEASE, ignore this */
984 if (s_fReleased)
985 return FALSE;
986
987 nButton = MOUSE_RELEASE;
988 s_fReleased = TRUE;
989 }
990 else /* one or more buttons pressed */
991 {
992 /* on a 2-button mouse, hold down left and right buttons
993 * simultaneously to get MIDDLE. */
994
995 if (cButtons == 2 && s_nOldButton != MOUSE_DRAG)
996 {
997 DWORD dwLR = (pmer->dwButtonState & LEFT_RIGHT);
998
999 /* if either left or right button only is pressed, see if the
1000 * the next mouse event has both of them pressed */
1001 if (dwLR == LEFT || dwLR == RIGHT)
1002 {
1003 for (;;)
1004 {
1005 /* wait a short time for next input event */
1006 if (WaitForSingleObject(g_hConIn, p_mouset / 3)
1007 != WAIT_OBJECT_0)
1008 break;
1009 else
1010 {
1011 DWORD cRecords = 0;
1012 INPUT_RECORD ir;
1013 MOUSE_EVENT_RECORD* pmer2 = &ir.Event.MouseEvent;
1014
1015 PeekConsoleInput(g_hConIn, &ir, 1, &cRecords);
1016
1017 if (cRecords == 0 || ir.EventType != MOUSE_EVENT
1018 || !(pmer2->dwButtonState & LEFT_RIGHT))
1019 break;
1020 else
1021 {
1022 if (pmer2->dwEventFlags != MOUSE_MOVED)
1023 {
1024 ReadConsoleInput(g_hConIn, &ir, 1, &cRecords);
1025
1026 return decode_mouse_event(pmer2);
1027 }
1028 else if (s_xOldMouse == pmer2->dwMousePosition.X &&
1029 s_yOldMouse == pmer2->dwMousePosition.Y)
1030 {
1031 /* throw away spurious mouse move */
1032 ReadConsoleInput(g_hConIn, &ir, 1, &cRecords);
1033
1034 /* are there any more mouse events in queue? */
1035 PeekConsoleInput(g_hConIn, &ir, 1, &cRecords);
1036
1037 if (cRecords==0 || ir.EventType != MOUSE_EVENT)
1038 break;
1039 }
1040 else
1041 break;
1042 }
1043 }
1044 }
1045 }
1046 }
1047
1048 if (s_fNextIsMiddle)
1049 {
1050 nButton = (pmer->dwEventFlags == MOUSE_MOVED)
1051 ? MOUSE_DRAG : MOUSE_MIDDLE;
1052 s_fNextIsMiddle = FALSE;
1053 }
1054 else if (cButtons == 2 &&
1055 ((pmer->dwButtonState & LEFT_RIGHT) == LEFT_RIGHT))
1056 {
1057 nButton = MOUSE_MIDDLE;
1058
1059 if (! s_fReleased && pmer->dwEventFlags != MOUSE_MOVED)
1060 {
1061 s_fNextIsMiddle = TRUE;
1062 nButton = MOUSE_RELEASE;
1063 }
1064 }
1065 else if ((pmer->dwButtonState & LEFT) == LEFT)
1066 nButton = MOUSE_LEFT;
1067 else if ((pmer->dwButtonState & MIDDLE) == MIDDLE)
1068 nButton = MOUSE_MIDDLE;
1069 else if ((pmer->dwButtonState & RIGHT) == RIGHT)
1070 nButton = MOUSE_RIGHT;
1071
1072 if (! s_fReleased && ! s_fNextIsMiddle
1073 && nButton != s_nOldButton && s_nOldButton != MOUSE_DRAG)
1074 return FALSE;
1075
1076 s_fReleased = s_fNextIsMiddle;
1077 }
1078
1079 if (pmer->dwEventFlags == 0 || pmer->dwEventFlags == DOUBLE_CLICK)
1080 {
1081 /* button pressed or released, without mouse moving */
1082 if (nButton != -1 && nButton != MOUSE_RELEASE)
1083 {
1084 DWORD dwCurrentTime = GetTickCount();
1085
1086 if (s_xOldMouse != g_xMouse
1087 || s_yOldMouse != g_yMouse
1088 || s_nOldButton != nButton
1089 || s_old_topline != curwin->w_topline
1090#ifdef FEAT_DIFF
1091 || s_old_topfill != curwin->w_topfill
1092#endif
1093 || (int)(dwCurrentTime - s_dwLastClickTime) > p_mouset)
1094 {
1095 s_cClicks = 1;
1096 }
1097 else if (++s_cClicks > 4)
1098 {
1099 s_cClicks = 1;
1100 }
1101
1102 s_dwLastClickTime = dwCurrentTime;
1103 }
1104 }
1105 else if (pmer->dwEventFlags == MOUSE_MOVED)
1106 {
1107 if (nButton != -1 && nButton != MOUSE_RELEASE)
1108 nButton = MOUSE_DRAG;
1109
1110 s_cClicks = 1;
1111 }
1112
1113 if (nButton == -1)
1114 return FALSE;
1115
1116 if (nButton != MOUSE_RELEASE)
1117 s_nOldButton = nButton;
1118
1119 g_nMouseClick = nButton;
1120
1121 if (pmer->dwControlKeyState & SHIFT_PRESSED)
1122 g_nMouseClick |= MOUSE_SHIFT;
1123 if (pmer->dwControlKeyState & (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED))
1124 g_nMouseClick |= MOUSE_CTRL;
1125 if (pmer->dwControlKeyState & (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED))
1126 g_nMouseClick |= MOUSE_ALT;
1127
1128 if (nButton != MOUSE_DRAG && nButton != MOUSE_RELEASE)
1129 SET_NUM_MOUSE_CLICKS(g_nMouseClick, s_cClicks);
1130
1131 /* only pass on interesting (i.e., different) mouse events */
1132 if (s_xOldMouse == g_xMouse
1133 && s_yOldMouse == g_yMouse
1134 && s_nOldMouseClick == g_nMouseClick)
1135 {
1136 g_nMouseClick = -1;
1137 return FALSE;
1138 }
1139
1140 s_xOldMouse = g_xMouse;
1141 s_yOldMouse = g_yMouse;
1142 s_old_topline = curwin->w_topline;
1143#ifdef FEAT_DIFF
1144 s_old_topfill = curwin->w_topfill;
1145#endif
1146 s_nOldMouseClick = g_nMouseClick;
1147
1148 return TRUE;
1149}
1150
1151# endif /* FEAT_GUI_W32 */
1152#endif /* FEAT_MOUSE */
1153
1154
1155#ifdef MCH_CURSOR_SHAPE
1156/*
1157 * Set the shape of the cursor.
1158 * 'thickness' can be from 1 (thin) to 99 (block)
1159 */
1160 static void
1161mch_set_cursor_shape(int thickness)
1162{
1163 CONSOLE_CURSOR_INFO ConsoleCursorInfo;
1164 ConsoleCursorInfo.dwSize = thickness;
1165 ConsoleCursorInfo.bVisible = s_cursor_visible;
1166
1167 SetConsoleCursorInfo(g_hConOut, &ConsoleCursorInfo);
1168 if (s_cursor_visible)
1169 SetConsoleCursorPosition(g_hConOut, g_coord);
1170}
1171
1172 void
1173mch_update_cursor(void)
1174{
1175 int idx;
1176 int thickness;
1177
1178 /*
1179 * How the cursor is drawn depends on the current mode.
1180 */
1181 idx = get_shape_idx(FALSE);
1182
1183 if (shape_table[idx].shape == SHAPE_BLOCK)
1184 thickness = 99; /* 100 doesn't work on W95 */
1185 else
1186 thickness = shape_table[idx].percentage;
1187 mch_set_cursor_shape(thickness);
1188}
1189#endif
1190
1191#ifndef FEAT_GUI_W32 /* this isn't used for the GUI */
1192/*
1193 * Handle FOCUS_EVENT.
1194 */
1195 static void
1196handle_focus_event(INPUT_RECORD ir)
1197{
1198 g_fJustGotFocus = ir.Event.FocusEvent.bSetFocus;
1199 ui_focus_change((int)g_fJustGotFocus);
1200}
1201
1202/*
1203 * Wait until console input from keyboard or mouse is available,
1204 * or the time is up.
1205 * Return TRUE if something is available FALSE if not.
1206 */
1207 static int
1208WaitForChar(long msec)
1209{
1210 DWORD dwNow = 0, dwEndTime = 0;
1211 INPUT_RECORD ir;
1212 DWORD cRecords;
1213 char_u ch, ch2;
1214
1215 if (msec > 0)
1216 /* Wait until the specified time has elapsed. */
1217 dwEndTime = GetTickCount() + msec;
1218 else if (msec < 0)
1219 /* Wait forever. */
1220 dwEndTime = INFINITE;
1221
1222 /* We need to loop until the end of the time period, because
1223 * we might get multiple unusable mouse events in that time.
1224 */
1225 for (;;)
1226 {
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001227#ifdef FEAT_MZSCHEME
1228 mzvim_check_threads();
1229#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001230#ifdef FEAT_CLIENTSERVER
1231 serverProcessPendingMessages();
1232#endif
1233 if (0
1234#ifdef FEAT_MOUSE
1235 || g_nMouseClick != -1
1236#endif
1237#ifdef FEAT_CLIENTSERVER
1238 || input_available()
1239#endif
1240 )
1241 return TRUE;
1242
1243 if (msec > 0)
1244 {
1245 /* If the specified wait time has passed, return. */
1246 dwNow = GetTickCount();
1247 if (dwNow >= dwEndTime)
1248 break;
1249 }
1250 if (msec != 0)
1251 {
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001252 DWORD dwWaitTime = dwEndTime - dwNow;
1253
1254#ifdef FEAT_MZSCHEME
1255 if (mzthreads_allowed() && p_mzq > 0
1256 && (msec < 0 || (long)dwWaitTime > p_mzq))
1257 dwWaitTime = p_mzq; /* don't wait longer than 'mzquantum' */
1258#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001259#ifdef FEAT_CLIENTSERVER
1260 /* Wait for either an event on the console input or a message in
1261 * the client-server window. */
1262 if (MsgWaitForMultipleObjects(1, &g_hConIn, FALSE,
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001263 dwWaitTime, QS_SENDMESSAGE) != WAIT_OBJECT_0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001264#else
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001265 if (WaitForSingleObject(g_hConIn, dwWaitTime) != WAIT_OBJECT_0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001266#endif
1267 continue;
1268 }
1269
1270 cRecords = 0;
1271 PeekConsoleInput(g_hConIn, &ir, 1, &cRecords);
1272
1273#ifdef FEAT_MBYTE_IME
1274 if (State & CMDLINE && msg_row == Rows - 1)
1275 {
1276 CONSOLE_SCREEN_BUFFER_INFO csbi;
1277
1278 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
1279 {
1280 if (csbi.dwCursorPosition.Y != msg_row)
1281 {
1282 /* The screen is now messed up, must redraw the
1283 * command line and later all the windows. */
1284 redraw_all_later(CLEAR);
1285 cmdline_row -= (msg_row - csbi.dwCursorPosition.Y);
1286 redrawcmd();
1287 }
1288 }
1289 }
1290#endif
1291
1292 if (cRecords > 0)
1293 {
1294 if (ir.EventType == KEY_EVENT && ir.Event.KeyEvent.bKeyDown)
1295 {
1296#ifdef FEAT_MBYTE_IME
1297 /* Windows IME sends two '\n's with only one 'ENTER'. First:
1298 * wVirtualKeyCode == 13. second: wVirtualKeyCode == 0 */
1299 if (ir.Event.KeyEvent.uChar.UnicodeChar == 0
1300 && ir.Event.KeyEvent.wVirtualKeyCode == 13)
1301 {
1302 ReadConsoleInput(g_hConIn, &ir, 1, &cRecords);
1303 continue;
1304 }
1305#endif
1306 if (decode_key_event(&ir.Event.KeyEvent, &ch, &ch2,
1307 NULL, FALSE))
1308 return TRUE;
1309 }
1310
1311 ReadConsoleInput(g_hConIn, &ir, 1, &cRecords);
1312
1313 if (ir.EventType == FOCUS_EVENT)
1314 handle_focus_event(ir);
1315 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
1316 shell_resized();
1317#ifdef FEAT_MOUSE
1318 else if (ir.EventType == MOUSE_EVENT
1319 && decode_mouse_event(&ir.Event.MouseEvent))
1320 return TRUE;
1321#endif
1322 }
1323 else if (msec == 0)
1324 break;
1325 }
1326
1327#ifdef FEAT_CLIENTSERVER
1328 /* Something might have been received while we were waiting. */
1329 if (input_available())
1330 return TRUE;
1331#endif
1332 return FALSE;
1333}
1334
1335#ifndef FEAT_GUI_MSWIN
1336/*
1337 * return non-zero if a character is available
1338 */
1339 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001340mch_char_avail(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001341{
1342 return WaitForChar(0L);
1343}
1344#endif
1345
1346/*
1347 * Create the console input. Used when reading stdin doesn't work.
1348 */
1349 static void
1350create_conin(void)
1351{
1352 g_hConIn = CreateFile("CONIN$", GENERIC_READ|GENERIC_WRITE,
1353 FILE_SHARE_READ|FILE_SHARE_WRITE,
1354 (LPSECURITY_ATTRIBUTES) NULL,
Bram Moolenaareb3593b2006-04-22 22:33:57 +00001355 OPEN_EXISTING, 0, (HANDLE)NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001356 did_create_conin = TRUE;
1357}
1358
1359/*
1360 * Get a keystroke or a mouse event
1361 */
1362 static char_u
1363tgetch(int *pmodifiers, char_u *pch2)
1364{
1365 char_u ch;
1366
1367 for (;;)
1368 {
1369 INPUT_RECORD ir;
1370 DWORD cRecords = 0;
1371
1372#ifdef FEAT_CLIENTSERVER
1373 (void)WaitForChar(-1L);
1374 if (input_available())
1375 return 0;
1376# ifdef FEAT_MOUSE
1377 if (g_nMouseClick != -1)
1378 return 0;
1379# endif
1380#endif
1381 if (ReadConsoleInput(g_hConIn, &ir, 1, &cRecords) == 0)
1382 {
1383 if (did_create_conin)
1384 read_error_exit();
1385 create_conin();
1386 continue;
1387 }
1388
1389 if (ir.EventType == KEY_EVENT)
1390 {
1391 if (decode_key_event(&ir.Event.KeyEvent, &ch, pch2,
1392 pmodifiers, TRUE))
1393 return ch;
1394 }
1395 else if (ir.EventType == FOCUS_EVENT)
1396 handle_focus_event(ir);
1397 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
1398 shell_resized();
1399#ifdef FEAT_MOUSE
1400 else if (ir.EventType == MOUSE_EVENT)
1401 {
1402 if (decode_mouse_event(&ir.Event.MouseEvent))
1403 return 0;
1404 }
1405#endif
1406 }
1407}
1408#endif /* !FEAT_GUI_W32 */
1409
1410
1411/*
1412 * mch_inchar(): low-level input funcion.
1413 * Get one or more characters from the keyboard or the mouse.
1414 * If time == 0, do not wait for characters.
1415 * If time == n, wait a short time for characters.
1416 * If time == -1, wait forever for characters.
1417 * Returns the number of characters read into buf.
1418 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00001419/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00001420 int
1421mch_inchar(
1422 char_u *buf,
1423 int maxlen,
1424 long time,
1425 int tb_change_cnt)
1426{
1427#ifndef FEAT_GUI_W32 /* this isn't used for the GUI */
1428
1429 int len;
1430 int c;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001431#define TYPEAHEADLEN 20
1432 static char_u typeahead[TYPEAHEADLEN]; /* previously typed bytes. */
1433 static int typeaheadlen = 0;
1434
1435 /* First use any typeahead that was kept because "buf" was too small. */
1436 if (typeaheadlen > 0)
1437 goto theend;
1438
1439#ifdef FEAT_SNIFF
1440 if (want_sniff_request)
1441 {
1442 if (sniff_request_waiting)
1443 {
1444 /* return K_SNIFF */
1445 typeahead[typeaheadlen++] = CSI;
1446 typeahead[typeaheadlen++] = (char_u)KS_EXTRA;
1447 typeahead[typeaheadlen++] = (char_u)KE_SNIFF;
1448 sniff_request_waiting = 0;
1449 want_sniff_request = 0;
1450 goto theend;
1451 }
1452 else if (time < 0 || time > 250)
1453 {
1454 /* don't wait too long, a request might be pending */
1455 time = 250;
1456 }
1457 }
1458#endif
1459
1460 if (time >= 0)
1461 {
1462 if (!WaitForChar(time)) /* no character available */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001463 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001464 }
1465 else /* time == -1, wait forever */
1466 {
1467 mch_set_winsize_now(); /* Allow winsize changes from now on */
1468
Bram Moolenaar3918c952005-03-15 22:34:55 +00001469 /*
1470 * If there is no character available within 2 seconds (default)
1471 * write the autoscript file to disk. Or cause the CursorHold event
1472 * to be triggered.
1473 */
1474 if (!WaitForChar(p_ut))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001475 {
1476#ifdef FEAT_AUTOCMD
Bram Moolenaard35f9712005-12-18 22:02:33 +00001477 if (trigger_cursorhold() && maxlen >= 3)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001478 {
Bram Moolenaar3918c952005-03-15 22:34:55 +00001479 buf[0] = K_SPECIAL;
1480 buf[1] = KS_EXTRA;
1481 buf[2] = (int)KE_CURSORHOLD;
1482 return 3;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001483 }
1484#endif
Bram Moolenaar702517d2005-06-27 22:34:07 +00001485 before_blocking();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001486 }
1487 }
1488
1489 /*
1490 * Try to read as many characters as there are, until the buffer is full.
1491 */
1492
1493 /* we will get at least one key. Get more if they are available. */
1494 g_fCBrkPressed = FALSE;
1495
1496#ifdef MCH_WRITE_DUMP
1497 if (fdDump)
1498 fputc('[', fdDump);
1499#endif
1500
1501 /* Keep looping until there is something in the typeahead buffer and more
1502 * to get and still room in the buffer (up to two bytes for a char and
1503 * three bytes for a modifier). */
1504 while ((typeaheadlen == 0 || WaitForChar(0L))
1505 && typeaheadlen + 5 <= TYPEAHEADLEN)
1506 {
1507 if (typebuf_changed(tb_change_cnt))
1508 {
1509 /* "buf" may be invalid now if a client put something in the
1510 * typeahead buffer and "buf" is in the typeahead buffer. */
1511 typeaheadlen = 0;
1512 break;
1513 }
1514#ifdef FEAT_MOUSE
1515 if (g_nMouseClick != -1)
1516 {
1517# ifdef MCH_WRITE_DUMP
1518 if (fdDump)
1519 fprintf(fdDump, "{%02x @ %d, %d}",
1520 g_nMouseClick, g_xMouse, g_yMouse);
1521# endif
1522 typeahead[typeaheadlen++] = ESC + 128;
1523 typeahead[typeaheadlen++] = 'M';
1524 typeahead[typeaheadlen++] = g_nMouseClick;
1525 typeahead[typeaheadlen++] = g_xMouse + '!';
1526 typeahead[typeaheadlen++] = g_yMouse + '!';
1527 g_nMouseClick = -1;
1528 }
1529 else
1530#endif
1531 {
1532 char_u ch2 = NUL;
1533 int modifiers = 0;
1534
1535 c = tgetch(&modifiers, &ch2);
1536
1537 if (typebuf_changed(tb_change_cnt))
1538 {
1539 /* "buf" may be invalid now if a client put something in the
1540 * typeahead buffer and "buf" is in the typeahead buffer. */
1541 typeaheadlen = 0;
1542 break;
1543 }
1544
1545 if (c == Ctrl_C && ctrl_c_interrupts)
1546 {
1547#if defined(FEAT_CLIENTSERVER)
1548 trash_input_buf();
1549#endif
1550 got_int = TRUE;
1551 }
1552
1553#ifdef FEAT_MOUSE
1554 if (g_nMouseClick == -1)
1555#endif
1556 {
1557 int n = 1;
1558
1559 /* A key may have one or two bytes. */
1560 typeahead[typeaheadlen] = c;
1561 if (ch2 != NUL)
1562 {
1563 typeahead[typeaheadlen + 1] = ch2;
1564 ++n;
1565 }
1566#ifdef FEAT_MBYTE
1567 /* Only convert normal characters, not special keys. Need to
1568 * convert before applying ALT, otherwise mapping <M-x> breaks
1569 * when 'tenc' is set. */
1570 if (input_conv.vc_type != CONV_NONE
1571 && (ch2 == NUL || c != K_NUL))
1572 n = convert_input(typeahead + typeaheadlen, n,
1573 TYPEAHEADLEN - typeaheadlen);
1574#endif
1575
1576 /* Use the ALT key to set the 8th bit of the character
1577 * when it's one byte, the 8th bit isn't set yet and not
1578 * using a double-byte encoding (would become a lead
1579 * byte). */
1580 if ((modifiers & MOD_MASK_ALT)
1581 && n == 1
1582 && (typeahead[typeaheadlen] & 0x80) == 0
1583#ifdef FEAT_MBYTE
1584 && !enc_dbcs
1585#endif
1586 )
1587 {
Bram Moolenaar85a3e5c2007-11-20 16:22:16 +00001588#ifdef FEAT_MBYTE
1589 n = (*mb_char2bytes)(typeahead[typeaheadlen] | 0x80,
1590 typeahead + typeaheadlen);
1591#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00001592 typeahead[typeaheadlen] |= 0x80;
Bram Moolenaar85a3e5c2007-11-20 16:22:16 +00001593#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001594 modifiers &= ~MOD_MASK_ALT;
1595 }
1596
1597 if (modifiers != 0)
1598 {
1599 /* Prepend modifiers to the character. */
1600 mch_memmove(typeahead + typeaheadlen + 3,
1601 typeahead + typeaheadlen, n);
1602 typeahead[typeaheadlen++] = K_SPECIAL;
1603 typeahead[typeaheadlen++] = (char_u)KS_MODIFIER;
1604 typeahead[typeaheadlen++] = modifiers;
1605 }
1606
1607 typeaheadlen += n;
1608
1609#ifdef MCH_WRITE_DUMP
1610 if (fdDump)
1611 fputc(c, fdDump);
1612#endif
1613 }
1614 }
1615 }
1616
1617#ifdef MCH_WRITE_DUMP
1618 if (fdDump)
1619 {
1620 fputs("]\n", fdDump);
1621 fflush(fdDump);
1622 }
1623#endif
1624
Bram Moolenaar071d4272004-06-13 20:20:40 +00001625theend:
1626 /* Move typeahead to "buf", as much as fits. */
1627 len = 0;
1628 while (len < maxlen && typeaheadlen > 0)
1629 {
1630 buf[len++] = typeahead[0];
1631 mch_memmove(typeahead, typeahead + 1, --typeaheadlen);
1632 }
1633 return len;
1634
1635#else /* FEAT_GUI_W32 */
1636 return 0;
1637#endif /* FEAT_GUI_W32 */
1638}
1639
1640#ifndef __MINGW32__
1641# include <shellapi.h> /* required for FindExecutable() */
1642#endif
1643
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001644/*
1645 * Return TRUE if "name" is in $PATH.
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00001646 * TODO: Should somehow check if it's really executable.
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001647 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001648 static int
1649executable_exists(char *name)
1650{
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001651 char *dum;
1652 char fname[_MAX_PATH];
Bram Moolenaar071d4272004-06-13 20:20:40 +00001653
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001654#ifdef FEAT_MBYTE
1655 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001656 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00001657 WCHAR *p = enc_to_utf16(name, NULL);
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001658 WCHAR fnamew[_MAX_PATH];
1659 WCHAR *dumw;
1660 long n;
1661
1662 if (p != NULL)
1663 {
1664 n = (long)SearchPathW(NULL, p, NULL, _MAX_PATH, fnamew, &dumw);
1665 vim_free(p);
1666 if (n > 0 || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
1667 {
1668 if (n == 0)
1669 return FALSE;
1670 if (GetFileAttributesW(fnamew) & FILE_ATTRIBUTE_DIRECTORY)
1671 return FALSE;
1672 return TRUE;
1673 }
1674 /* Retry with non-wide function (for Windows 98). */
1675 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001676 }
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001677#endif
1678 if (SearchPath(NULL, name, NULL, _MAX_PATH, fname, &dum) == 0)
1679 return FALSE;
1680 if (mch_isdir(fname))
1681 return FALSE;
1682 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001683}
1684
Bram Moolenaard32a99a2010-09-21 17:29:23 +02001685#if ((defined(__MINGW32__) || defined (__CYGWIN32__)) && \
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02001686 __MSVCRT_VERSION__ >= 0x800) || (defined(_MSC_VER) && _MSC_VER >= 1400)
Bram Moolenaard32a99a2010-09-21 17:29:23 +02001687/*
1688 * Bad parameter handler.
1689 *
1690 * Certain MS CRT functions will intentionally crash when passed invalid
1691 * parameters to highlight possible security holes. Setting this function as
1692 * the bad parameter handler will prevent the crash.
1693 *
1694 * In debug builds the parameters contain CRT information that might help track
1695 * down the source of a problem, but in non-debug builds the arguments are all
1696 * NULL/0. Debug builds will also produce assert dialogs from the CRT, it is
1697 * worth allowing these to make debugging of issues easier.
1698 */
1699 static void
1700bad_param_handler(const wchar_t *expression,
1701 const wchar_t *function,
1702 const wchar_t *file,
1703 unsigned int line,
1704 uintptr_t pReserved)
1705{
1706}
1707
1708# define SET_INVALID_PARAM_HANDLER \
1709 ((void)_set_invalid_parameter_handler(bad_param_handler))
1710#else
1711# define SET_INVALID_PARAM_HANDLER
1712#endif
1713
Bram Moolenaar071d4272004-06-13 20:20:40 +00001714#ifdef FEAT_GUI_W32
1715
1716/*
1717 * GUI version of mch_init().
1718 */
1719 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001720mch_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001721{
1722#ifndef __MINGW32__
1723 extern int _fmode;
1724#endif
1725
Bram Moolenaard32a99a2010-09-21 17:29:23 +02001726 /* Silently handle invalid parameters to CRT functions */
1727 SET_INVALID_PARAM_HANDLER;
1728
Bram Moolenaar071d4272004-06-13 20:20:40 +00001729 /* Let critical errors result in a failure, not in a dialog box. Required
1730 * for the timestamp test to work on removed floppies. */
1731 SetErrorMode(SEM_FAILCRITICALERRORS);
1732
1733 _fmode = O_BINARY; /* we do our own CR-LF translation */
1734
1735 /* Specify window size. Is there a place to get the default from? */
1736 Rows = 25;
1737 Columns = 80;
1738
1739 /* Look for 'vimrun' */
1740 if (!gui_is_win32s())
1741 {
1742 char_u vimrun_location[_MAX_PATH + 4];
1743
1744 /* First try in same directory as gvim.exe */
1745 STRCPY(vimrun_location, exe_name);
1746 STRCPY(gettail(vimrun_location), "vimrun.exe");
1747 if (mch_getperm(vimrun_location) >= 0)
1748 {
1749 if (*skiptowhite(vimrun_location) != NUL)
1750 {
1751 /* Enclose path with white space in double quotes. */
1752 mch_memmove(vimrun_location + 1, vimrun_location,
1753 STRLEN(vimrun_location) + 1);
1754 *vimrun_location = '"';
1755 STRCPY(gettail(vimrun_location), "vimrun\" ");
1756 }
1757 else
1758 STRCPY(gettail(vimrun_location), "vimrun ");
1759
1760 vimrun_path = (char *)vim_strsave(vimrun_location);
1761 s_dont_use_vimrun = FALSE;
1762 }
1763 else if (executable_exists("vimrun.exe"))
1764 s_dont_use_vimrun = FALSE;
1765
1766 /* Don't give the warning for a missing vimrun.exe right now, but only
1767 * when vimrun was supposed to be used. Don't bother people that do
1768 * not need vimrun.exe. */
1769 if (s_dont_use_vimrun)
1770 need_vimrun_warning = TRUE;
1771 }
1772
1773 /*
1774 * If "finstr.exe" doesn't exist, use "grep -n" for 'grepprg'.
1775 * Otherwise the default "findstr /n" is used.
1776 */
1777 if (!executable_exists("findstr.exe"))
1778 set_option_value((char_u *)"grepprg", 0, (char_u *)"grep -n", 0);
1779
1780#ifdef FEAT_CLIPBOARD
1781 clip_init(TRUE);
1782
1783 /*
Bram Moolenaar7528dd62007-05-06 12:32:12 +00001784 * Vim's own clipboard format recognises whether the text is char, line,
1785 * or rectangular block. Only useful for copying between two Vims.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001786 * "VimClipboard" was used for previous versions, using the first
1787 * character to specify MCHAR, MLINE or MBLOCK.
1788 */
1789 clip_star.format = RegisterClipboardFormat("VimClipboard2");
1790 clip_star.format_raw = RegisterClipboardFormat("VimRawBytes");
1791#endif
1792}
1793
1794
1795#else /* FEAT_GUI_W32 */
1796
1797#define SRWIDTH(sr) ((sr).Right - (sr).Left + 1)
1798#define SRHEIGHT(sr) ((sr).Bottom - (sr).Top + 1)
1799
1800/*
1801 * ClearConsoleBuffer()
1802 * Description:
1803 * Clears the entire contents of the console screen buffer, using the
1804 * specified attribute.
1805 * Returns:
1806 * TRUE on success
1807 */
1808 static BOOL
1809ClearConsoleBuffer(WORD wAttribute)
1810{
1811 CONSOLE_SCREEN_BUFFER_INFO csbi;
1812 COORD coord;
1813 DWORD NumCells, dummy;
1814
1815 if (!GetConsoleScreenBufferInfo(g_hConOut, &csbi))
1816 return FALSE;
1817
1818 NumCells = csbi.dwSize.X * csbi.dwSize.Y;
1819 coord.X = 0;
1820 coord.Y = 0;
1821 if (!FillConsoleOutputCharacter(g_hConOut, ' ', NumCells,
1822 coord, &dummy))
1823 {
1824 return FALSE;
1825 }
1826 if (!FillConsoleOutputAttribute(g_hConOut, wAttribute, NumCells,
1827 coord, &dummy))
1828 {
1829 return FALSE;
1830 }
1831
1832 return TRUE;
1833}
1834
1835/*
1836 * FitConsoleWindow()
1837 * Description:
1838 * Checks if the console window will fit within given buffer dimensions.
1839 * Also, if requested, will shrink the window to fit.
1840 * Returns:
1841 * TRUE on success
1842 */
1843 static BOOL
1844FitConsoleWindow(
1845 COORD dwBufferSize,
1846 BOOL WantAdjust)
1847{
1848 CONSOLE_SCREEN_BUFFER_INFO csbi;
1849 COORD dwWindowSize;
1850 BOOL NeedAdjust = FALSE;
1851
1852 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
1853 {
1854 /*
1855 * A buffer resize will fail if the current console window does
1856 * not lie completely within that buffer. To avoid this, we might
1857 * have to move and possibly shrink the window.
1858 */
1859 if (csbi.srWindow.Right >= dwBufferSize.X)
1860 {
1861 dwWindowSize.X = SRWIDTH(csbi.srWindow);
1862 if (dwWindowSize.X > dwBufferSize.X)
1863 dwWindowSize.X = dwBufferSize.X;
1864 csbi.srWindow.Right = dwBufferSize.X - 1;
1865 csbi.srWindow.Left = dwBufferSize.X - dwWindowSize.X;
1866 NeedAdjust = TRUE;
1867 }
1868 if (csbi.srWindow.Bottom >= dwBufferSize.Y)
1869 {
1870 dwWindowSize.Y = SRHEIGHT(csbi.srWindow);
1871 if (dwWindowSize.Y > dwBufferSize.Y)
1872 dwWindowSize.Y = dwBufferSize.Y;
1873 csbi.srWindow.Bottom = dwBufferSize.Y - 1;
1874 csbi.srWindow.Top = dwBufferSize.Y - dwWindowSize.Y;
1875 NeedAdjust = TRUE;
1876 }
1877 if (NeedAdjust && WantAdjust)
1878 {
1879 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &csbi.srWindow))
1880 return FALSE;
1881 }
1882 return TRUE;
1883 }
1884
1885 return FALSE;
1886}
1887
1888typedef struct ConsoleBufferStruct
1889{
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001890 BOOL IsValid;
1891 CONSOLE_SCREEN_BUFFER_INFO Info;
1892 PCHAR_INFO Buffer;
1893 COORD BufferSize;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001894} ConsoleBuffer;
1895
1896/*
1897 * SaveConsoleBuffer()
1898 * Description:
1899 * Saves important information about the console buffer, including the
1900 * actual buffer contents. The saved information is suitable for later
1901 * restoration by RestoreConsoleBuffer().
1902 * Returns:
1903 * TRUE if all information was saved; FALSE otherwise
1904 * If FALSE, still sets cb->IsValid if buffer characteristics were saved.
1905 */
1906 static BOOL
1907SaveConsoleBuffer(
1908 ConsoleBuffer *cb)
1909{
1910 DWORD NumCells;
1911 COORD BufferCoord;
1912 SMALL_RECT ReadRegion;
1913 WORD Y, Y_incr;
1914
1915 if (cb == NULL)
1916 return FALSE;
1917
1918 if (!GetConsoleScreenBufferInfo(g_hConOut, &cb->Info))
1919 {
1920 cb->IsValid = FALSE;
1921 return FALSE;
1922 }
1923 cb->IsValid = TRUE;
1924
1925 /*
1926 * Allocate a buffer large enough to hold the entire console screen
1927 * buffer. If this ConsoleBuffer structure has already been initialized
1928 * with a buffer of the correct size, then just use that one.
1929 */
1930 if (!cb->IsValid || cb->Buffer == NULL ||
1931 cb->BufferSize.X != cb->Info.dwSize.X ||
1932 cb->BufferSize.Y != cb->Info.dwSize.Y)
1933 {
1934 cb->BufferSize.X = cb->Info.dwSize.X;
1935 cb->BufferSize.Y = cb->Info.dwSize.Y;
1936 NumCells = cb->BufferSize.X * cb->BufferSize.Y;
Bram Moolenaar3c2d6532011-02-01 13:48:53 +01001937 vim_free(cb->Buffer);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001938 cb->Buffer = (PCHAR_INFO)alloc(NumCells * sizeof(CHAR_INFO));
1939 if (cb->Buffer == NULL)
1940 return FALSE;
1941 }
1942
1943 /*
1944 * We will now copy the console screen buffer into our buffer.
1945 * ReadConsoleOutput() seems to be limited as far as how much you
1946 * can read at a time. Empirically, this number seems to be about
1947 * 12000 cells (rows * columns). Start at position (0, 0) and copy
1948 * in chunks until it is all copied. The chunks will all have the
1949 * same horizontal characteristics, so initialize them now. The
1950 * height of each chunk will be (12000 / width).
1951 */
1952 BufferCoord.X = 0;
1953 ReadRegion.Left = 0;
1954 ReadRegion.Right = cb->Info.dwSize.X - 1;
1955 Y_incr = 12000 / cb->Info.dwSize.X;
1956 for (Y = 0; Y < cb->BufferSize.Y; Y += Y_incr)
1957 {
1958 /*
1959 * Read into position (0, Y) in our buffer.
1960 */
1961 BufferCoord.Y = Y;
1962 /*
1963 * Read the region whose top left corner is (0, Y) and whose bottom
1964 * right corner is (width - 1, Y + Y_incr - 1). This should define
1965 * a region of size width by Y_incr. Don't worry if this region is
1966 * too large for the remaining buffer; it will be cropped.
1967 */
1968 ReadRegion.Top = Y;
1969 ReadRegion.Bottom = Y + Y_incr - 1;
1970 if (!ReadConsoleOutput(g_hConOut, /* output handle */
1971 cb->Buffer, /* our buffer */
1972 cb->BufferSize, /* dimensions of our buffer */
1973 BufferCoord, /* offset in our buffer */
1974 &ReadRegion)) /* region to save */
1975 {
1976 vim_free(cb->Buffer);
1977 cb->Buffer = NULL;
1978 return FALSE;
1979 }
1980 }
1981
1982 return TRUE;
1983}
1984
1985/*
1986 * RestoreConsoleBuffer()
1987 * Description:
1988 * Restores important information about the console buffer, including the
1989 * actual buffer contents, if desired. The information to restore is in
1990 * the same format used by SaveConsoleBuffer().
1991 * Returns:
1992 * TRUE on success
1993 */
1994 static BOOL
1995RestoreConsoleBuffer(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001996 ConsoleBuffer *cb,
1997 BOOL RestoreScreen)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001998{
1999 COORD BufferCoord;
2000 SMALL_RECT WriteRegion;
2001
2002 if (cb == NULL || !cb->IsValid)
2003 return FALSE;
2004
2005 /*
2006 * Before restoring the buffer contents, clear the current buffer, and
2007 * restore the cursor position and window information. Doing this now
2008 * prevents old buffer contents from "flashing" onto the screen.
2009 */
2010 if (RestoreScreen)
2011 ClearConsoleBuffer(cb->Info.wAttributes);
2012
2013 FitConsoleWindow(cb->Info.dwSize, TRUE);
2014 if (!SetConsoleScreenBufferSize(g_hConOut, cb->Info.dwSize))
2015 return FALSE;
2016 if (!SetConsoleTextAttribute(g_hConOut, cb->Info.wAttributes))
2017 return FALSE;
2018
2019 if (!RestoreScreen)
2020 {
2021 /*
2022 * No need to restore the screen buffer contents, so we're done.
2023 */
2024 return TRUE;
2025 }
2026
2027 if (!SetConsoleCursorPosition(g_hConOut, cb->Info.dwCursorPosition))
2028 return FALSE;
2029 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &cb->Info.srWindow))
2030 return FALSE;
2031
2032 /*
2033 * Restore the screen buffer contents.
2034 */
2035 if (cb->Buffer != NULL)
2036 {
2037 BufferCoord.X = 0;
2038 BufferCoord.Y = 0;
2039 WriteRegion.Left = 0;
2040 WriteRegion.Top = 0;
2041 WriteRegion.Right = cb->Info.dwSize.X - 1;
2042 WriteRegion.Bottom = cb->Info.dwSize.Y - 1;
2043 if (!WriteConsoleOutput(g_hConOut, /* output handle */
2044 cb->Buffer, /* our buffer */
2045 cb->BufferSize, /* dimensions of our buffer */
2046 BufferCoord, /* offset in our buffer */
2047 &WriteRegion)) /* region to restore */
2048 {
2049 return FALSE;
2050 }
2051 }
2052
2053 return TRUE;
2054}
2055
Bram Moolenaar362e1a32006-03-06 23:29:24 +00002056#define FEAT_RESTORE_ORIG_SCREEN
Bram Moolenaar071d4272004-06-13 20:20:40 +00002057#ifdef FEAT_RESTORE_ORIG_SCREEN
2058static ConsoleBuffer g_cbOrig = { 0 };
2059#endif
2060static ConsoleBuffer g_cbNonTermcap = { 0 };
2061static ConsoleBuffer g_cbTermcap = { 0 };
2062
2063#ifdef FEAT_TITLE
2064#ifdef __BORLANDC__
2065typedef HWND (__stdcall *GETCONSOLEWINDOWPROC)(VOID);
2066#else
2067typedef WINBASEAPI HWND (WINAPI *GETCONSOLEWINDOWPROC)(VOID);
2068#endif
2069char g_szOrigTitle[256] = { 0 };
2070HWND g_hWnd = NULL; /* also used in os_mswin.c */
2071static HICON g_hOrigIconSmall = NULL;
2072static HICON g_hOrigIcon = NULL;
2073static HICON g_hVimIcon = NULL;
2074static BOOL g_fCanChangeIcon = FALSE;
2075
2076/* ICON* are not defined in VC++ 4.0 */
2077#ifndef ICON_SMALL
2078#define ICON_SMALL 0
2079#endif
2080#ifndef ICON_BIG
2081#define ICON_BIG 1
2082#endif
2083/*
2084 * GetConsoleIcon()
2085 * Description:
2086 * Attempts to retrieve the small icon and/or the big icon currently in
2087 * use by a given window.
2088 * Returns:
2089 * TRUE on success
2090 */
2091 static BOOL
2092GetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002093 HWND hWnd,
2094 HICON *phIconSmall,
2095 HICON *phIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002096{
2097 if (hWnd == NULL)
2098 return FALSE;
2099
2100 if (phIconSmall != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002101 *phIconSmall = (HICON)SendMessage(hWnd, WM_GETICON,
2102 (WPARAM)ICON_SMALL, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002103 if (phIcon != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002104 *phIcon = (HICON)SendMessage(hWnd, WM_GETICON,
2105 (WPARAM)ICON_BIG, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002106 return TRUE;
2107}
2108
2109/*
2110 * SetConsoleIcon()
2111 * Description:
2112 * Attempts to change the small icon and/or the big icon currently in
2113 * use by a given window.
2114 * Returns:
2115 * TRUE on success
2116 */
2117 static BOOL
2118SetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002119 HWND hWnd,
2120 HICON hIconSmall,
2121 HICON hIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002122{
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002123 HICON hPrevIconSmall;
2124 HICON hPrevIcon;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002125
2126 if (hWnd == NULL)
2127 return FALSE;
2128
2129 if (hIconSmall != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002130 hPrevIconSmall = (HICON)SendMessage(hWnd, WM_SETICON,
2131 (WPARAM)ICON_SMALL, (LPARAM)hIconSmall);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002132 if (hIcon != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002133 hPrevIcon = (HICON)SendMessage(hWnd, WM_SETICON,
2134 (WPARAM)ICON_BIG,(LPARAM) hIcon);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002135 return TRUE;
2136}
2137
2138/*
2139 * SaveConsoleTitleAndIcon()
2140 * Description:
2141 * Saves the current console window title in g_szOrigTitle, for later
2142 * restoration. Also, attempts to obtain a handle to the console window,
2143 * and use it to save the small and big icons currently in use by the
2144 * console window. This is not always possible on some versions of Windows;
2145 * nor is it possible when running Vim remotely using Telnet (since the
2146 * console window the user sees is owned by a remote process).
2147 */
2148 static void
2149SaveConsoleTitleAndIcon(void)
2150{
2151 GETCONSOLEWINDOWPROC GetConsoleWindowProc;
2152
2153 /* Save the original title. */
2154 if (!GetConsoleTitle(g_szOrigTitle, sizeof(g_szOrigTitle)))
2155 return;
2156
2157 /*
2158 * Obtain a handle to the console window using GetConsoleWindow() from
2159 * KERNEL32.DLL; we need to handle in order to change the window icon.
2160 * This function only exists on NT-based Windows, starting with Windows
2161 * 2000. On older operating systems, we can't change the window icon
2162 * anyway.
2163 */
2164 if ((GetConsoleWindowProc = (GETCONSOLEWINDOWPROC)
2165 GetProcAddress(GetModuleHandle("KERNEL32.DLL"),
2166 "GetConsoleWindow")) != NULL)
2167 {
2168 g_hWnd = (*GetConsoleWindowProc)();
2169 }
2170 if (g_hWnd == NULL)
2171 return;
2172
2173 /* Save the original console window icon. */
2174 GetConsoleIcon(g_hWnd, &g_hOrigIconSmall, &g_hOrigIcon);
2175 if (g_hOrigIconSmall == NULL || g_hOrigIcon == NULL)
2176 return;
2177
2178 /* Extract the first icon contained in the Vim executable. */
2179 g_hVimIcon = ExtractIcon(NULL, exe_name, 0);
2180 if (g_hVimIcon != NULL)
2181 g_fCanChangeIcon = TRUE;
2182}
2183#endif
2184
2185static int g_fWindInitCalled = FALSE;
2186static int g_fTermcapMode = FALSE;
2187static CONSOLE_CURSOR_INFO g_cci;
2188static DWORD g_cmodein = 0;
2189static DWORD g_cmodeout = 0;
2190
2191/*
2192 * non-GUI version of mch_init().
2193 */
2194 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002195mch_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002196{
2197#ifndef FEAT_RESTORE_ORIG_SCREEN
2198 CONSOLE_SCREEN_BUFFER_INFO csbi;
2199#endif
2200#ifndef __MINGW32__
2201 extern int _fmode;
2202#endif
2203
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002204 /* Silently handle invalid parameters to CRT functions */
2205 SET_INVALID_PARAM_HANDLER;
2206
Bram Moolenaar071d4272004-06-13 20:20:40 +00002207 /* Let critical errors result in a failure, not in a dialog box. Required
2208 * for the timestamp test to work on removed floppies. */
2209 SetErrorMode(SEM_FAILCRITICALERRORS);
2210
2211 _fmode = O_BINARY; /* we do our own CR-LF translation */
2212 out_flush();
2213
2214 /* Obtain handles for the standard Console I/O devices */
2215 if (read_cmd_fd == 0)
2216 g_hConIn = GetStdHandle(STD_INPUT_HANDLE);
2217 else
2218 create_conin();
2219 g_hConOut = GetStdHandle(STD_OUTPUT_HANDLE);
2220
2221#ifdef FEAT_RESTORE_ORIG_SCREEN
2222 /* Save the initial console buffer for later restoration */
2223 SaveConsoleBuffer(&g_cbOrig);
2224 g_attrCurrent = g_attrDefault = g_cbOrig.Info.wAttributes;
2225#else
2226 /* Get current text attributes */
2227 GetConsoleScreenBufferInfo(g_hConOut, &csbi);
2228 g_attrCurrent = g_attrDefault = csbi.wAttributes;
2229#endif
2230 if (cterm_normal_fg_color == 0)
2231 cterm_normal_fg_color = (g_attrCurrent & 0xf) + 1;
2232 if (cterm_normal_bg_color == 0)
2233 cterm_normal_bg_color = ((g_attrCurrent >> 4) & 0xf) + 1;
2234
2235 /* set termcap codes to current text attributes */
2236 update_tcap(g_attrCurrent);
2237
2238 GetConsoleCursorInfo(g_hConOut, &g_cci);
2239 GetConsoleMode(g_hConIn, &g_cmodein);
2240 GetConsoleMode(g_hConOut, &g_cmodeout);
2241
2242#ifdef FEAT_TITLE
2243 SaveConsoleTitleAndIcon();
2244 /*
2245 * Set both the small and big icons of the console window to Vim's icon.
2246 * Note that Vim presently only has one size of icon (32x32), but it
2247 * automatically gets scaled down to 16x16 when setting the small icon.
2248 */
2249 if (g_fCanChangeIcon)
2250 SetConsoleIcon(g_hWnd, g_hVimIcon, g_hVimIcon);
2251#endif
2252
2253 ui_get_shellsize();
2254
2255#ifdef MCH_WRITE_DUMP
2256 fdDump = fopen("dump", "wt");
2257
2258 if (fdDump)
2259 {
2260 time_t t;
2261
2262 time(&t);
2263 fputs(ctime(&t), fdDump);
2264 fflush(fdDump);
2265 }
2266#endif
2267
2268 g_fWindInitCalled = TRUE;
2269
2270#ifdef FEAT_MOUSE
2271 g_fMouseAvail = GetSystemMetrics(SM_MOUSEPRESENT);
2272#endif
2273
2274#ifdef FEAT_CLIPBOARD
2275 clip_init(TRUE);
2276
2277 /*
2278 * Vim's own clipboard format recognises whether the text is char, line, or
2279 * rectangular block. Only useful for copying between two Vims.
2280 * "VimClipboard" was used for previous versions, using the first
2281 * character to specify MCHAR, MLINE or MBLOCK.
2282 */
2283 clip_star.format = RegisterClipboardFormat("VimClipboard2");
2284 clip_star.format_raw = RegisterClipboardFormat("VimRawBytes");
2285#endif
2286
2287 /* This will be NULL on anything but NT 4.0 */
2288 s_pfnGetConsoleKeyboardLayoutName =
2289 (PFNGCKLN) GetProcAddress(GetModuleHandle("kernel32.dll"),
2290 "GetConsoleKeyboardLayoutNameA");
2291}
2292
2293/*
2294 * non-GUI version of mch_exit().
2295 * Shut down and exit with status `r'
2296 * Careful: mch_exit() may be called before mch_init()!
2297 */
2298 void
2299mch_exit(int r)
2300{
2301 stoptermcap();
2302
2303 if (g_fWindInitCalled)
2304 settmode(TMODE_COOK);
2305
2306 ml_close_all(TRUE); /* remove all memfiles */
2307
2308 if (g_fWindInitCalled)
2309 {
2310#ifdef FEAT_TITLE
2311 mch_restore_title(3);
2312 /*
2313 * Restore both the small and big icons of the console window to
2314 * what they were at startup. Don't do this when the window is
2315 * closed, Vim would hang here.
2316 */
2317 if (g_fCanChangeIcon && !g_fForceExit)
2318 SetConsoleIcon(g_hWnd, g_hOrigIconSmall, g_hOrigIcon);
2319#endif
2320
2321#ifdef MCH_WRITE_DUMP
2322 if (fdDump)
2323 {
2324 time_t t;
2325
2326 time(&t);
2327 fputs(ctime(&t), fdDump);
2328 fclose(fdDump);
2329 }
2330 fdDump = NULL;
2331#endif
2332 }
2333
2334 SetConsoleCursorInfo(g_hConOut, &g_cci);
2335 SetConsoleMode(g_hConIn, g_cmodein);
2336 SetConsoleMode(g_hConOut, g_cmodeout);
2337
2338#ifdef DYNAMIC_GETTEXT
2339 dyn_libintl_end();
2340#endif
2341
2342 exit(r);
2343}
2344#endif /* !FEAT_GUI_W32 */
2345
Bram Moolenaar071d4272004-06-13 20:20:40 +00002346/*
2347 * Do we have an interactive window?
2348 */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00002349/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00002350 int
2351mch_check_win(
2352 int argc,
2353 char **argv)
2354{
2355 get_exe_name();
2356
2357#ifdef FEAT_GUI_W32
2358 return OK; /* GUI always has a tty */
2359#else
2360 if (isatty(1))
2361 return OK;
2362 return FAIL;
2363#endif
2364}
2365
2366
2367/*
2368 * fname_case(): Set the case of the file name, if it already exists.
2369 * When "len" is > 0, also expand short to long filenames.
2370 */
2371 void
2372fname_case(
2373 char_u *name,
2374 int len)
2375{
2376 char szTrueName[_MAX_PATH + 2];
Bram Moolenaar464c9252010-10-13 20:37:41 +02002377 char szTrueNameTemp[_MAX_PATH + 2];
Bram Moolenaar071d4272004-06-13 20:20:40 +00002378 char *ptrue, *ptruePrev;
2379 char *porig, *porigPrev;
2380 int flen;
2381 WIN32_FIND_DATA fb;
2382 HANDLE hFind;
2383 int c;
Bram Moolenaar464c9252010-10-13 20:37:41 +02002384 int slen;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002385
Bram Moolenaara3ffd9c2005-07-21 21:03:15 +00002386 flen = (int)STRLEN(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002387 if (flen == 0 || flen > _MAX_PATH)
2388 return;
2389
2390 slash_adjust(name);
2391
2392 /* Build the new name in szTrueName[] one component at a time. */
2393 porig = name;
2394 ptrue = szTrueName;
2395
2396 if (isalpha(porig[0]) && porig[1] == ':')
2397 {
2398 /* copy leading drive letter */
2399 *ptrue++ = *porig++;
2400 *ptrue++ = *porig++;
2401 *ptrue = NUL; /* in case nothing follows */
2402 }
2403
2404 while (*porig != NUL)
2405 {
2406 /* copy \ characters */
2407 while (*porig == psepc)
2408 *ptrue++ = *porig++;
2409
2410 ptruePrev = ptrue;
2411 porigPrev = porig;
2412 while (*porig != NUL && *porig != psepc)
2413 {
2414#ifdef FEAT_MBYTE
2415 int l;
2416
2417 if (enc_dbcs)
2418 {
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00002419 l = (*mb_ptr2len)(porig);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002420 while (--l >= 0)
2421 *ptrue++ = *porig++;
2422 }
2423 else
2424#endif
2425 *ptrue++ = *porig++;
2426 }
2427 *ptrue = NUL;
2428
Bram Moolenaar464c9252010-10-13 20:37:41 +02002429 /* To avoid a slow failure append "\*" when searching a directory,
2430 * server or network share. */
2431 STRCPY(szTrueNameTemp, szTrueName);
Bram Moolenaar6b5ef062010-10-27 12:18:00 +02002432 slen = (int)strlen(szTrueNameTemp);
Bram Moolenaar464c9252010-10-13 20:37:41 +02002433 if (*porig == psepc && slen + 2 < _MAX_PATH)
2434 STRCPY(szTrueNameTemp + slen, "\\*");
2435
Bram Moolenaar071d4272004-06-13 20:20:40 +00002436 /* Skip "", "." and "..". */
2437 if (ptrue > ptruePrev
2438 && (ptruePrev[0] != '.'
2439 || (ptruePrev[1] != NUL
2440 && (ptruePrev[1] != '.' || ptruePrev[2] != NUL)))
Bram Moolenaar464c9252010-10-13 20:37:41 +02002441 && (hFind = FindFirstFile(szTrueNameTemp, &fb))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002442 != INVALID_HANDLE_VALUE)
2443 {
2444 c = *porig;
2445 *porig = NUL;
2446
2447 /* Only use the match when it's the same name (ignoring case) or
2448 * expansion is allowed and there is a match with the short name
2449 * and there is enough room. */
2450 if (_stricoll(porigPrev, fb.cFileName) == 0
2451 || (len > 0
2452 && (_stricoll(porigPrev, fb.cAlternateFileName) == 0
2453 && (int)(ptruePrev - szTrueName)
2454 + (int)strlen(fb.cFileName) < len)))
2455 {
2456 STRCPY(ptruePrev, fb.cFileName);
2457
2458 /* Look for exact match and prefer it if found. Must be a
2459 * long name, otherwise there would be only one match. */
2460 while (FindNextFile(hFind, &fb))
2461 {
2462 if (*fb.cAlternateFileName != NUL
2463 && (strcoll(porigPrev, fb.cFileName) == 0
2464 || (len > 0
2465 && (_stricoll(porigPrev,
2466 fb.cAlternateFileName) == 0
2467 && (int)(ptruePrev - szTrueName)
2468 + (int)strlen(fb.cFileName) < len))))
2469 {
2470 STRCPY(ptruePrev, fb.cFileName);
2471 break;
2472 }
2473 }
2474 }
2475 FindClose(hFind);
2476 *porig = c;
2477 ptrue = ptruePrev + strlen(ptruePrev);
2478 }
2479 }
2480
2481 STRCPY(name, szTrueName);
2482}
2483
2484
2485/*
2486 * Insert user name in s[len].
2487 */
2488 int
2489mch_get_user_name(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002490 char_u *s,
2491 int len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002492{
Bram Moolenaar41a09032007-10-01 18:34:34 +00002493 char szUserName[256 + 1]; /* UNLEN is 256 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002494 DWORD cch = sizeof szUserName;
2495
2496 if (GetUserName(szUserName, &cch))
2497 {
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00002498 vim_strncpy(s, szUserName, len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002499 return OK;
2500 }
2501 s[0] = NUL;
2502 return FAIL;
2503}
2504
2505
2506/*
2507 * Insert host name in s[len].
2508 */
2509 void
2510mch_get_host_name(
2511 char_u *s,
2512 int len)
2513{
2514 DWORD cch = len;
2515
2516 if (!GetComputerName(s, &cch))
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00002517 vim_strncpy(s, "PC (Win32 Vim)", len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002518}
2519
2520
2521/*
2522 * return process ID
2523 */
2524 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002525mch_get_pid(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002526{
2527 return (long)GetCurrentProcessId();
2528}
2529
2530
2531/*
2532 * Get name of current directory into buffer 'buf' of length 'len' bytes.
2533 * Return OK for success, FAIL for failure.
2534 */
2535 int
2536mch_dirname(
2537 char_u *buf,
2538 int len)
2539{
2540 /*
2541 * Originally this was:
2542 * return (getcwd(buf, len) != NULL ? OK : FAIL);
2543 * But the Win32s known bug list says that getcwd() doesn't work
2544 * so use the Win32 system call instead. <Negri>
2545 */
2546#ifdef FEAT_MBYTE
2547 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2548 {
2549 WCHAR wbuf[_MAX_PATH + 1];
2550
2551 if (GetCurrentDirectoryW(_MAX_PATH, wbuf) != 0)
2552 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00002553 char_u *p = utf16_to_enc(wbuf, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002554
2555 if (p != NULL)
2556 {
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00002557 vim_strncpy(buf, p, len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002558 vim_free(p);
2559 return OK;
2560 }
2561 }
2562 /* Retry with non-wide function (for Windows 98). */
2563 }
2564#endif
2565 return (GetCurrentDirectory(len, buf) != 0 ? OK : FAIL);
2566}
2567
2568/*
2569 * get file permissions for `name'
2570 * -1 : error
2571 * else FILE_ATTRIBUTE_* defined in winnt.h
2572 */
2573 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002574mch_getperm(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002575{
2576#ifdef FEAT_MBYTE
2577 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2578 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00002579 WCHAR *p = enc_to_utf16(name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002580 long n;
2581
2582 if (p != NULL)
2583 {
2584 n = (long)GetFileAttributesW(p);
2585 vim_free(p);
2586 if (n >= 0 || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
2587 return n;
2588 /* Retry with non-wide function (for Windows 98). */
2589 }
2590 }
2591#endif
2592 return (long)GetFileAttributes((char *)name);
2593}
2594
2595
2596/*
2597 * set file permission for `name' to `perm'
2598 */
2599 int
2600mch_setperm(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002601 char_u *name,
2602 long perm)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002603{
2604 perm |= FILE_ATTRIBUTE_ARCHIVE; /* file has changed, set archive bit */
2605#ifdef FEAT_MBYTE
2606 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2607 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00002608 WCHAR *p = enc_to_utf16(name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002609 long n;
2610
2611 if (p != NULL)
2612 {
2613 n = (long)SetFileAttributesW(p, perm);
2614 vim_free(p);
2615 if (n || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
2616 return n ? OK : FAIL;
2617 /* Retry with non-wide function (for Windows 98). */
2618 }
2619 }
2620#endif
2621 return SetFileAttributes((char *)name, perm) ? OK : FAIL;
2622}
2623
2624/*
2625 * Set hidden flag for "name".
2626 */
2627 void
2628mch_hide(char_u *name)
2629{
2630 int perm;
2631#ifdef FEAT_MBYTE
2632 WCHAR *p = NULL;
2633
2634 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar36f692d2008-11-20 16:10:17 +00002635 p = enc_to_utf16(name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002636#endif
2637
2638#ifdef FEAT_MBYTE
2639 if (p != NULL)
2640 {
2641 perm = GetFileAttributesW(p);
2642 if (perm < 0 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
2643 {
2644 /* Retry with non-wide function (for Windows 98). */
2645 vim_free(p);
2646 p = NULL;
2647 }
2648 }
2649 if (p == NULL)
2650#endif
2651 perm = GetFileAttributes((char *)name);
2652 if (perm >= 0)
2653 {
2654 perm |= FILE_ATTRIBUTE_HIDDEN;
2655#ifdef FEAT_MBYTE
2656 if (p != NULL)
2657 {
2658 if (SetFileAttributesW(p, perm) == 0
2659 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
2660 {
2661 /* Retry with non-wide function (for Windows 98). */
2662 vim_free(p);
2663 p = NULL;
2664 }
2665 }
2666 if (p == NULL)
2667#endif
2668 SetFileAttributes((char *)name, perm);
2669 }
2670#ifdef FEAT_MBYTE
2671 vim_free(p);
2672#endif
2673}
2674
2675/*
2676 * return TRUE if "name" is a directory
2677 * return FALSE if "name" is not a directory or upon error
2678 */
2679 int
2680mch_isdir(char_u *name)
2681{
2682 int f = mch_getperm(name);
2683
2684 if (f == -1)
2685 return FALSE; /* file does not exist at all */
2686
2687 return (f & FILE_ATTRIBUTE_DIRECTORY) != 0;
2688}
2689
2690/*
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02002691 * Create directory "name".
2692 * Return 0 on success, -1 on error.
2693 */
2694 int
2695mch_mkdir(char_u *name)
2696{
2697#ifdef FEAT_MBYTE
2698 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2699 {
2700 WCHAR *p;
2701 int retval;
2702
2703 p = enc_to_utf16(name, NULL);
2704 if (p == NULL)
2705 return -1;
2706 retval = _wmkdir(p);
2707 vim_free(p);
2708 return retval;
2709 }
2710#endif
2711 return _mkdir(name);
2712}
2713
2714/*
Bram Moolenaar03f48552006-02-28 23:52:23 +00002715 * Return TRUE if file "fname" has more than one link.
2716 */
2717 int
2718mch_is_linked(char_u *fname)
2719{
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02002720 BY_HANDLE_FILE_INFORMATION info;
2721
2722 return win32_fileinfo(fname, &info) == FILEINFO_OK
2723 && info.nNumberOfLinks > 1;
2724}
2725
2726/*
2727 * Get the by-handle-file-information for "fname".
2728 * Returns FILEINFO_OK when OK.
2729 * returns FILEINFO_ENC_FAIL when enc_to_utf16() failed.
2730 * Returns FILEINFO_READ_FAIL when CreateFile() failed.
2731 * Returns FILEINFO_INFO_FAIL when GetFileInformationByHandle() failed.
2732 */
2733 int
2734win32_fileinfo(char_u *fname, BY_HANDLE_FILE_INFORMATION *info)
2735{
Bram Moolenaar03f48552006-02-28 23:52:23 +00002736 HANDLE hFile;
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02002737 int res = FILEINFO_READ_FAIL;
Bram Moolenaar03f48552006-02-28 23:52:23 +00002738#ifdef FEAT_MBYTE
2739 WCHAR *wn = NULL;
2740
2741 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02002742 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00002743 wn = enc_to_utf16(fname, NULL);
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02002744 if (wn == NULL)
2745 res = FILEINFO_ENC_FAIL;
2746 }
Bram Moolenaar03f48552006-02-28 23:52:23 +00002747 if (wn != NULL)
2748 {
2749 hFile = CreateFileW(wn, /* file name */
2750 GENERIC_READ, /* access mode */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02002751 FILE_SHARE_READ | FILE_SHARE_WRITE, /* share mode */
Bram Moolenaar03f48552006-02-28 23:52:23 +00002752 NULL, /* security descriptor */
2753 OPEN_EXISTING, /* creation disposition */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02002754 FILE_FLAG_BACKUP_SEMANTICS, /* file attributes */
Bram Moolenaar03f48552006-02-28 23:52:23 +00002755 NULL); /* handle to template file */
2756 if (hFile == INVALID_HANDLE_VALUE
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02002757 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
Bram Moolenaar03f48552006-02-28 23:52:23 +00002758 {
2759 /* Retry with non-wide function (for Windows 98). */
2760 vim_free(wn);
2761 wn = NULL;
2762 }
2763 }
2764 if (wn == NULL)
2765#endif
2766 hFile = CreateFile(fname, /* file name */
2767 GENERIC_READ, /* access mode */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02002768 FILE_SHARE_READ | FILE_SHARE_WRITE, /* share mode */
Bram Moolenaar03f48552006-02-28 23:52:23 +00002769 NULL, /* security descriptor */
2770 OPEN_EXISTING, /* creation disposition */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02002771 FILE_FLAG_BACKUP_SEMANTICS, /* file attributes */
Bram Moolenaar03f48552006-02-28 23:52:23 +00002772 NULL); /* handle to template file */
2773
2774 if (hFile != INVALID_HANDLE_VALUE)
2775 {
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02002776 if (GetFileInformationByHandle(hFile, info) != 0)
2777 res = FILEINFO_OK;
2778 else
2779 res = FILEINFO_INFO_FAIL;
Bram Moolenaar03f48552006-02-28 23:52:23 +00002780 CloseHandle(hFile);
2781 }
2782
2783#ifdef FEAT_MBYTE
2784 vim_free(wn);
2785#endif
2786 return res;
2787}
2788
2789/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00002790 * Return TRUE if file or directory "name" is writable (not readonly).
2791 * Strange semantics of Win32: a readonly directory is writable, but you can't
2792 * delete a file. Let's say this means it is writable.
2793 */
2794 int
2795mch_writable(char_u *name)
2796{
2797 int perm = mch_getperm(name);
2798
2799 return (perm != -1 && (!(perm & FILE_ATTRIBUTE_READONLY)
2800 || (perm & FILE_ATTRIBUTE_DIRECTORY)));
2801}
2802
Bram Moolenaar071d4272004-06-13 20:20:40 +00002803/*
2804 * Return 1 if "name" can be executed, 0 if not.
2805 * Return -1 if unknown.
2806 */
2807 int
2808mch_can_exe(char_u *name)
2809{
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00002810 char_u buf[_MAX_PATH];
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00002811 int len = (int)STRLEN(name);
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00002812 char_u *p;
2813
2814 if (len >= _MAX_PATH) /* safety check */
2815 return FALSE;
2816
2817 /* If there already is an extension try using the name directly. Also do
2818 * this with a Unix-shell like 'shell'. */
2819 if (vim_strchr(gettail(name), '.') != NULL
2820 || strstr((char *)gettail(p_sh), "sh") != NULL)
2821 if (executable_exists((char *)name))
2822 return TRUE;
2823
2824 /*
2825 * Loop over all extensions in $PATHEXT.
2826 */
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00002827 vim_strncpy(buf, name, _MAX_PATH - 1);
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00002828 p = mch_getenv("PATHEXT");
2829 if (p == NULL)
2830 p = (char_u *)".com;.exe;.bat;.cmd";
2831 while (*p)
2832 {
2833 if (p[0] == '.' && (p[1] == NUL || p[1] == ';'))
2834 {
2835 /* A single "." means no extension is added. */
2836 buf[len] = NUL;
2837 ++p;
2838 if (*p)
2839 ++p;
2840 }
2841 else
2842 copy_option_part(&p, buf + len, _MAX_PATH - len, ";");
2843 if (executable_exists((char *)buf))
2844 return TRUE;
2845 }
2846 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002847}
Bram Moolenaar071d4272004-06-13 20:20:40 +00002848
2849/*
2850 * Check what "name" is:
2851 * NODE_NORMAL: file or directory (or doesn't exist)
2852 * NODE_WRITABLE: writable device, socket, fifo, etc.
2853 * NODE_OTHER: non-writable things
2854 */
2855 int
2856mch_nodetype(char_u *name)
2857{
2858 HANDLE hFile;
2859 int type;
2860
Bram Moolenaar043545e2006-10-10 16:44:07 +00002861 /* We can't open a file with a name "\\.\con" or "\\.\prn" and trying to
2862 * read from it later will cause Vim to hang. Thus return NODE_WRITABLE
2863 * here. */
2864 if (STRNCMP(name, "\\\\.\\", 4) == 0)
2865 return NODE_WRITABLE;
2866
Bram Moolenaar071d4272004-06-13 20:20:40 +00002867 hFile = CreateFile(name, /* file name */
2868 GENERIC_WRITE, /* access mode */
2869 0, /* share mode */
2870 NULL, /* security descriptor */
2871 OPEN_EXISTING, /* creation disposition */
2872 0, /* file attributes */
2873 NULL); /* handle to template file */
2874
2875 if (hFile == INVALID_HANDLE_VALUE)
2876 return NODE_NORMAL;
2877
2878 type = GetFileType(hFile);
2879 CloseHandle(hFile);
2880 if (type == FILE_TYPE_CHAR)
2881 return NODE_WRITABLE;
2882 if (type == FILE_TYPE_DISK)
2883 return NODE_NORMAL;
2884 return NODE_OTHER;
2885}
2886
2887#ifdef HAVE_ACL
2888struct my_acl
2889{
2890 PSECURITY_DESCRIPTOR pSecurityDescriptor;
2891 PSID pSidOwner;
2892 PSID pSidGroup;
2893 PACL pDacl;
2894 PACL pSacl;
2895};
2896#endif
2897
2898/*
2899 * Return a pointer to the ACL of file "fname" in allocated memory.
2900 * Return NULL if the ACL is not available for whatever reason.
2901 */
2902 vim_acl_T
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002903mch_get_acl(char_u *fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002904{
2905#ifndef HAVE_ACL
2906 return (vim_acl_T)NULL;
2907#else
2908 struct my_acl *p = NULL;
2909
2910 /* This only works on Windows NT and 2000. */
2911 if (g_PlatformId == VER_PLATFORM_WIN32_NT && advapi_lib != NULL)
2912 {
2913 p = (struct my_acl *)alloc_clear((unsigned)sizeof(struct my_acl));
2914 if (p != NULL)
2915 {
2916 if (pGetNamedSecurityInfo(
2917 (LPTSTR)fname, // Abstract filename
2918 SE_FILE_OBJECT, // File Object
2919 // Retrieve the entire security descriptor.
2920 OWNER_SECURITY_INFORMATION |
2921 GROUP_SECURITY_INFORMATION |
2922 DACL_SECURITY_INFORMATION |
2923 SACL_SECURITY_INFORMATION,
2924 &p->pSidOwner, // Ownership information.
2925 &p->pSidGroup, // Group membership.
2926 &p->pDacl, // Discretionary information.
2927 &p->pSacl, // For auditing purposes.
2928 &p->pSecurityDescriptor
2929 ) != ERROR_SUCCESS)
2930 {
2931 mch_free_acl((vim_acl_T)p);
2932 p = NULL;
2933 }
2934 }
2935 }
2936
2937 return (vim_acl_T)p;
2938#endif
2939}
2940
2941/*
2942 * Set the ACL of file "fname" to "acl" (unless it's NULL).
2943 * Errors are ignored.
2944 * This must only be called with "acl" equal to what mch_get_acl() returned.
2945 */
2946 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002947mch_set_acl(char_u *fname, vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002948{
2949#ifdef HAVE_ACL
2950 struct my_acl *p = (struct my_acl *)acl;
2951
2952 if (p != NULL && advapi_lib != NULL)
2953 (void)pSetNamedSecurityInfo(
2954 (LPTSTR)fname, // Abstract filename
2955 SE_FILE_OBJECT, // File Object
2956 // Retrieve the entire security descriptor.
2957 OWNER_SECURITY_INFORMATION |
2958 GROUP_SECURITY_INFORMATION |
2959 DACL_SECURITY_INFORMATION |
2960 SACL_SECURITY_INFORMATION,
2961 p->pSidOwner, // Ownership information.
2962 p->pSidGroup, // Group membership.
2963 p->pDacl, // Discretionary information.
2964 p->pSacl // For auditing purposes.
2965 );
2966#endif
2967}
2968
2969 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002970mch_free_acl(vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002971{
2972#ifdef HAVE_ACL
2973 struct my_acl *p = (struct my_acl *)acl;
2974
2975 if (p != NULL)
2976 {
2977 LocalFree(p->pSecurityDescriptor); // Free the memory just in case
2978 vim_free(p);
2979 }
2980#endif
2981}
2982
2983#ifndef FEAT_GUI_W32
2984
2985/*
2986 * handler for ctrl-break, ctrl-c interrupts, and fatal events.
2987 */
2988 static BOOL WINAPI
2989handler_routine(
2990 DWORD dwCtrlType)
2991{
2992 switch (dwCtrlType)
2993 {
2994 case CTRL_C_EVENT:
2995 if (ctrl_c_interrupts)
2996 g_fCtrlCPressed = TRUE;
2997 return TRUE;
2998
2999 case CTRL_BREAK_EVENT:
3000 g_fCBrkPressed = TRUE;
3001 return TRUE;
3002
3003 /* fatal events: shut down gracefully */
3004 case CTRL_CLOSE_EVENT:
3005 case CTRL_LOGOFF_EVENT:
3006 case CTRL_SHUTDOWN_EVENT:
3007 windgoto((int)Rows - 1, 0);
3008 g_fForceExit = TRUE;
3009
Bram Moolenaar0fde2902008-03-16 13:54:13 +00003010 vim_snprintf((char *)IObuff, IOSIZE, _("Vim: Caught %s event\n"),
Bram Moolenaar071d4272004-06-13 20:20:40 +00003011 (dwCtrlType == CTRL_CLOSE_EVENT
3012 ? _("close")
3013 : dwCtrlType == CTRL_LOGOFF_EVENT
3014 ? _("logoff")
3015 : _("shutdown")));
3016#ifdef DEBUG
3017 OutputDebugString(IObuff);
3018#endif
3019
3020 preserve_exit(); /* output IObuff, preserve files and exit */
3021
3022 return TRUE; /* not reached */
3023
3024 default:
3025 return FALSE;
3026 }
3027}
3028
3029
3030/*
3031 * set the tty in (raw) ? "raw" : "cooked" mode
3032 */
3033 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003034mch_settmode(int tmode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003035{
3036 DWORD cmodein;
3037 DWORD cmodeout;
3038 BOOL bEnableHandler;
3039
3040 GetConsoleMode(g_hConIn, &cmodein);
3041 GetConsoleMode(g_hConOut, &cmodeout);
3042 if (tmode == TMODE_RAW)
3043 {
3044 cmodein &= ~(ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
3045 ENABLE_ECHO_INPUT);
3046#ifdef FEAT_MOUSE
3047 if (g_fMouseActive)
3048 cmodein |= ENABLE_MOUSE_INPUT;
3049#endif
3050 cmodeout &= ~(ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
3051 bEnableHandler = TRUE;
3052 }
3053 else /* cooked */
3054 {
3055 cmodein |= (ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
3056 ENABLE_ECHO_INPUT);
3057 cmodeout |= (ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
3058 bEnableHandler = FALSE;
3059 }
3060 SetConsoleMode(g_hConIn, cmodein);
3061 SetConsoleMode(g_hConOut, cmodeout);
3062 SetConsoleCtrlHandler(handler_routine, bEnableHandler);
3063
3064#ifdef MCH_WRITE_DUMP
3065 if (fdDump)
3066 {
3067 fprintf(fdDump, "mch_settmode(%s, in = %x, out = %x)\n",
3068 tmode == TMODE_RAW ? "raw" :
3069 tmode == TMODE_COOK ? "cooked" : "normal",
3070 cmodein, cmodeout);
3071 fflush(fdDump);
3072 }
3073#endif
3074}
3075
3076
3077/*
3078 * Get the size of the current window in `Rows' and `Columns'
3079 * Return OK when size could be determined, FAIL otherwise.
3080 */
3081 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003082mch_get_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003083{
3084 CONSOLE_SCREEN_BUFFER_INFO csbi;
3085
3086 if (!g_fTermcapMode && g_cbTermcap.IsValid)
3087 {
3088 /*
3089 * For some reason, we are trying to get the screen dimensions
3090 * even though we are not in termcap mode. The 'Rows' and 'Columns'
3091 * variables are really intended to mean the size of Vim screen
3092 * while in termcap mode.
3093 */
3094 Rows = g_cbTermcap.Info.dwSize.Y;
3095 Columns = g_cbTermcap.Info.dwSize.X;
3096 }
3097 else if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3098 {
3099 Rows = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
3100 Columns = csbi.srWindow.Right - csbi.srWindow.Left + 1;
3101 }
3102 else
3103 {
3104 Rows = 25;
3105 Columns = 80;
3106 }
3107 return OK;
3108}
3109
3110/*
3111 * Set a console window to `xSize' * `ySize'
3112 */
3113 static void
3114ResizeConBufAndWindow(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003115 HANDLE hConsole,
3116 int xSize,
3117 int ySize)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003118{
3119 CONSOLE_SCREEN_BUFFER_INFO csbi; /* hold current console buffer info */
3120 SMALL_RECT srWindowRect; /* hold the new console size */
3121 COORD coordScreen;
3122
3123#ifdef MCH_WRITE_DUMP
3124 if (fdDump)
3125 {
3126 fprintf(fdDump, "ResizeConBufAndWindow(%d, %d)\n", xSize, ySize);
3127 fflush(fdDump);
3128 }
3129#endif
3130
3131 /* get the largest size we can size the console window to */
3132 coordScreen = GetLargestConsoleWindowSize(hConsole);
3133
3134 /* define the new console window size and scroll position */
3135 srWindowRect.Left = srWindowRect.Top = (SHORT) 0;
3136 srWindowRect.Right = (SHORT) (min(xSize, coordScreen.X) - 1);
3137 srWindowRect.Bottom = (SHORT) (min(ySize, coordScreen.Y) - 1);
3138
3139 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3140 {
3141 int sx, sy;
3142
3143 sx = csbi.srWindow.Right - csbi.srWindow.Left + 1;
3144 sy = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
3145 if (sy < ySize || sx < xSize)
3146 {
3147 /*
3148 * Increasing number of lines/columns, do buffer first.
3149 * Use the maximal size in x and y direction.
3150 */
3151 if (sy < ySize)
3152 coordScreen.Y = ySize;
3153 else
3154 coordScreen.Y = sy;
3155 if (sx < xSize)
3156 coordScreen.X = xSize;
3157 else
3158 coordScreen.X = sx;
3159 SetConsoleScreenBufferSize(hConsole, coordScreen);
3160 }
3161 }
3162
3163 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &srWindowRect))
3164 {
3165#ifdef MCH_WRITE_DUMP
3166 if (fdDump)
3167 {
3168 fprintf(fdDump, "SetConsoleWindowInfo failed: %lx\n",
3169 GetLastError());
3170 fflush(fdDump);
3171 }
3172#endif
3173 }
3174
3175 /* define the new console buffer size */
3176 coordScreen.X = xSize;
3177 coordScreen.Y = ySize;
3178
3179 if (!SetConsoleScreenBufferSize(hConsole, coordScreen))
3180 {
3181#ifdef MCH_WRITE_DUMP
3182 if (fdDump)
3183 {
3184 fprintf(fdDump, "SetConsoleScreenBufferSize failed: %lx\n",
3185 GetLastError());
3186 fflush(fdDump);
3187 }
3188#endif
3189 }
3190}
3191
3192
3193/*
3194 * Set the console window to `Rows' * `Columns'
3195 */
3196 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003197mch_set_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003198{
3199 COORD coordScreen;
3200
3201 /* Don't change window size while still starting up */
3202 if (suppress_winsize != 0)
3203 {
3204 suppress_winsize = 2;
3205 return;
3206 }
3207
3208 if (term_console)
3209 {
3210 coordScreen = GetLargestConsoleWindowSize(g_hConOut);
3211
3212 /* Clamp Rows and Columns to reasonable values */
3213 if (Rows > coordScreen.Y)
3214 Rows = coordScreen.Y;
3215 if (Columns > coordScreen.X)
3216 Columns = coordScreen.X;
3217
3218 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
3219 }
3220}
3221
3222/*
3223 * Rows and/or Columns has changed.
3224 */
3225 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003226mch_new_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003227{
3228 set_scroll_region(0, 0, Columns - 1, Rows - 1);
3229}
3230
3231
3232/*
3233 * Called when started up, to set the winsize that was delayed.
3234 */
3235 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003236mch_set_winsize_now(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003237{
3238 if (suppress_winsize == 2)
3239 {
3240 suppress_winsize = 0;
3241 mch_set_shellsize();
3242 shell_resized();
3243 }
3244 suppress_winsize = 0;
3245}
3246#endif /* FEAT_GUI_W32 */
3247
3248
3249
3250#if defined(FEAT_GUI_W32) || defined(PROTO)
3251
3252/*
3253 * Specialised version of system() for Win32 GUI mode.
3254 * This version proceeds as follows:
3255 * 1. Create a console window for use by the subprocess
3256 * 2. Run the subprocess (it gets the allocated console by default)
3257 * 3. Wait for the subprocess to terminate and get its exit code
3258 * 4. Prompt the user to press a key to close the console window
3259 */
3260 static int
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02003261mch_system_classic(char *cmd, int options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003262{
3263 STARTUPINFO si;
3264 PROCESS_INFORMATION pi;
3265 DWORD ret = 0;
3266 HWND hwnd = GetFocus();
3267
3268 si.cb = sizeof(si);
3269 si.lpReserved = NULL;
3270 si.lpDesktop = NULL;
3271 si.lpTitle = NULL;
3272 si.dwFlags = STARTF_USESHOWWINDOW;
3273 /*
3274 * It's nicer to run a filter command in a minimized window, but in
3275 * Windows 95 this makes the command MUCH slower. We can't do it under
3276 * Win32s either as it stops the synchronous spawn workaround working.
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01003277 * Don't activate the window to keep focus on Vim.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003278 */
3279 if ((options & SHELL_DOOUT) && !mch_windows95() && !gui_is_win32s())
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01003280 si.wShowWindow = SW_SHOWMINNOACTIVE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003281 else
3282 si.wShowWindow = SW_SHOWNORMAL;
3283 si.cbReserved2 = 0;
3284 si.lpReserved2 = NULL;
3285
3286 /* There is a strange error on Windows 95 when using "c:\\command.com".
3287 * When the "c:\\" is left out it works OK...? */
3288 if (mch_windows95()
3289 && (STRNICMP(cmd, "c:/command.com", 14) == 0
3290 || STRNICMP(cmd, "c:\\command.com", 14) == 0))
3291 cmd += 3;
3292
3293 /* Now, run the command */
3294 CreateProcess(NULL, /* Executable name */
3295 cmd, /* Command to execute */
3296 NULL, /* Process security attributes */
3297 NULL, /* Thread security attributes */
3298 FALSE, /* Inherit handles */
3299 CREATE_DEFAULT_ERROR_MODE | /* Creation flags */
3300 CREATE_NEW_CONSOLE,
3301 NULL, /* Environment */
3302 NULL, /* Current directory */
3303 &si, /* Startup information */
3304 &pi); /* Process information */
3305
3306
3307 /* Wait for the command to terminate before continuing */
3308 if (g_PlatformId != VER_PLATFORM_WIN32s)
3309 {
3310#ifdef FEAT_GUI
3311 int delay = 1;
3312
3313 /* Keep updating the window while waiting for the shell to finish. */
3314 for (;;)
3315 {
3316 MSG msg;
3317
Bram Moolenaar8c85fa32011-08-10 17:08:03 +02003318 if (pPeekMessage(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003319 {
3320 TranslateMessage(&msg);
Bram Moolenaar8c85fa32011-08-10 17:08:03 +02003321 pDispatchMessage(&msg);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003322 }
3323 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
3324 break;
3325
3326 /* We start waiting for a very short time and then increase it, so
3327 * that we respond quickly when the process is quick, and don't
3328 * consume too much overhead when it's slow. */
3329 if (delay < 50)
3330 delay += 10;
3331 }
3332#else
3333 WaitForSingleObject(pi.hProcess, INFINITE);
3334#endif
3335
3336 /* Get the command exit code */
3337 GetExitCodeProcess(pi.hProcess, &ret);
3338 }
3339 else
3340 {
3341 /*
3342 * This ugly code is the only quick way of performing
3343 * a synchronous spawn under Win32s. Yuk.
3344 */
3345 num_windows = 0;
3346 EnumWindows(win32ssynch_cb, 0);
3347 old_num_windows = num_windows;
3348 do
3349 {
3350 Sleep(1000);
3351 num_windows = 0;
3352 EnumWindows(win32ssynch_cb, 0);
3353 } while (num_windows == old_num_windows);
3354 ret = 0;
3355 }
3356
3357 /* Close the handles to the subprocess, so that it goes away */
3358 CloseHandle(pi.hThread);
3359 CloseHandle(pi.hProcess);
3360
3361 /* Try to get input focus back. Doesn't always work though. */
3362 PostMessage(hwnd, WM_SETFOCUS, 0, 0);
3363
3364 return ret;
3365}
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02003366
3367/*
3368 * Thread launched by the gui to send the current buffer data to the
3369 * process. This way avoid to hang up vim totally if the children
3370 * process take a long time to process the lines.
3371 */
3372 static DWORD WINAPI
3373sub_process_writer(LPVOID param)
3374{
3375 HANDLE g_hChildStd_IN_Wr = param;
3376 linenr_T lnum = curbuf->b_op_start.lnum;
3377 DWORD len = 0;
3378 DWORD l;
3379 char_u *lp = ml_get(lnum);
3380 char_u *s;
3381 int written = 0;
3382
3383 for (;;)
3384 {
3385 l = (DWORD)STRLEN(lp + written);
3386 if (l == 0)
3387 len = 0;
3388 else if (lp[written] == NL)
3389 {
3390 /* NL -> NUL translation */
3391 WriteFile(g_hChildStd_IN_Wr, "", 1, &len, NULL);
3392 }
3393 else
3394 {
3395 s = vim_strchr(lp + written, NL);
3396 WriteFile(g_hChildStd_IN_Wr, (char *)lp + written,
3397 s == NULL ? l : (DWORD)(s - (lp + written)),
3398 &len, NULL);
3399 }
3400 if (len == (int)l)
3401 {
3402 /* Finished a line, add a NL, unless this line should not have
3403 * one. */
3404 if (lnum != curbuf->b_op_end.lnum
3405 || !curbuf->b_p_bin
3406 || (lnum != curbuf->b_no_eol_lnum
3407 && (lnum != curbuf->b_ml.ml_line_count
3408 || curbuf->b_p_eol)))
3409 {
3410 WriteFile(g_hChildStd_IN_Wr, "\n", 1, &ignored, NULL);
3411 }
3412
3413 ++lnum;
3414 if (lnum > curbuf->b_op_end.lnum)
3415 break;
3416
3417 lp = ml_get(lnum);
3418 written = 0;
3419 }
3420 else if (len > 0)
3421 written += len;
3422 }
3423
3424 /* finished all the lines, close pipe */
3425 CloseHandle(g_hChildStd_IN_Wr);
3426 ExitThread(0);
3427}
3428
3429
3430# define BUFLEN 100 /* length for buffer, stolen from unix version */
3431
3432/*
3433 * This function read from the children's stdout and write the
3434 * data on screen or in the buffer accordingly.
3435 */
3436 static void
3437dump_pipe(int options,
3438 HANDLE g_hChildStd_OUT_Rd,
3439 garray_T *ga,
3440 char_u buffer[],
3441 DWORD *buffer_off)
3442{
3443 DWORD availableBytes = 0;
3444 DWORD i;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02003445 int ret;
3446 DWORD len;
3447 DWORD toRead;
3448 int repeatCount;
3449
3450 /* we query the pipe to see if there is any data to read
3451 * to avoid to perform a blocking read */
3452 ret = PeekNamedPipe(g_hChildStd_OUT_Rd, /* pipe to query */
3453 NULL, /* optional buffer */
3454 0, /* buffe size */
3455 NULL, /* number of read bytes */
3456 &availableBytes, /* available bytes total */
3457 NULL); /* byteLeft */
3458
3459 repeatCount = 0;
3460 /* We got real data in the pipe, read it */
3461 while (ret != 0 && availableBytes > 0 && availableBytes > 0)
3462 {
3463 repeatCount++;
3464 toRead =
3465# ifdef FEAT_MBYTE
3466 (DWORD)(BUFLEN - *buffer_off);
3467# else
3468 (DWORD)BUFLEN;
3469# endif
3470 toRead = availableBytes < toRead ? availableBytes : toRead;
3471 ReadFile(g_hChildStd_OUT_Rd, buffer
3472# ifdef FEAT_MBYTE
3473 + *buffer_off, toRead
3474# else
3475 , toRead
3476# endif
3477 , &len, NULL);
3478
3479 /* If we haven't read anything, there is a problem */
3480 if (len == 0)
3481 break;
3482
3483 availableBytes -= len;
3484
3485 if (options & SHELL_READ)
3486 {
3487 /* Do NUL -> NL translation, append NL separated
3488 * lines to the current buffer. */
3489 for (i = 0; i < len; ++i)
3490 {
3491 if (buffer[i] == NL)
3492 append_ga_line(ga);
3493 else if (buffer[i] == NUL)
3494 ga_append(ga, NL);
3495 else
3496 ga_append(ga, buffer[i]);
3497 }
3498 }
3499# ifdef FEAT_MBYTE
3500 else if (has_mbyte)
3501 {
3502 int l;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02003503 int c;
3504 char_u *p;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02003505
3506 len += *buffer_off;
3507 buffer[len] = NUL;
3508
3509 /* Check if the last character in buffer[] is
3510 * incomplete, keep these bytes for the next
3511 * round. */
3512 for (p = buffer; p < buffer + len; p += l)
3513 {
3514 l = mb_cptr2len(p);
3515 if (l == 0)
3516 l = 1; /* NUL byte? */
3517 else if (MB_BYTE2LEN(*p) != l)
3518 break;
3519 }
3520 if (p == buffer) /* no complete character */
3521 {
3522 /* avoid getting stuck at an illegal byte */
3523 if (len >= 12)
3524 ++p;
3525 else
3526 {
3527 *buffer_off = len;
3528 return;
3529 }
3530 }
3531 c = *p;
3532 *p = NUL;
3533 msg_puts(buffer);
3534 if (p < buffer + len)
3535 {
3536 *p = c;
3537 *buffer_off = (DWORD)((buffer + len) - p);
3538 mch_memmove(buffer, p, *buffer_off);
3539 return;
3540 }
3541 *buffer_off = 0;
3542 }
3543# endif /* FEAT_MBYTE */
3544 else
3545 {
3546 buffer[len] = NUL;
3547 msg_puts(buffer);
3548 }
3549
3550 windgoto(msg_row, msg_col);
3551 cursor_on();
3552 out_flush();
3553 }
3554}
3555
3556/*
3557 * Version of system to use for windows NT > 5.0 (Win2K), use pipe
3558 * for communication and doesn't open any new window.
3559 */
3560 static int
3561mch_system_piped(char *cmd, int options)
3562{
3563 STARTUPINFO si;
3564 PROCESS_INFORMATION pi;
3565 DWORD ret = 0;
3566
3567 HANDLE g_hChildStd_IN_Rd = NULL;
3568 HANDLE g_hChildStd_IN_Wr = NULL;
3569 HANDLE g_hChildStd_OUT_Rd = NULL;
3570 HANDLE g_hChildStd_OUT_Wr = NULL;
3571
3572 char_u buffer[BUFLEN + 1]; /* reading buffer + size */
3573 DWORD len;
3574
3575 /* buffer used to receive keys */
3576 char_u ta_buf[BUFLEN + 1]; /* TypeAHead */
3577 int ta_len = 0; /* valid bytes in ta_buf[] */
3578
3579 DWORD i;
3580 int c;
3581 int noread_cnt = 0;
3582 garray_T ga;
3583 int delay = 1;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02003584 DWORD buffer_off = 0; /* valid bytes in buffer[] */
Bram Moolenaar6b707b42012-02-21 21:22:44 +01003585 char *p = NULL;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02003586
3587 SECURITY_ATTRIBUTES saAttr;
3588
3589 /* Set the bInheritHandle flag so pipe handles are inherited. */
3590 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
3591 saAttr.bInheritHandle = TRUE;
3592 saAttr.lpSecurityDescriptor = NULL;
3593
3594 if ( ! CreatePipe(&g_hChildStd_OUT_Rd, &g_hChildStd_OUT_Wr, &saAttr, 0)
3595 /* Ensure the read handle to the pipe for STDOUT is not inherited. */
3596 || ! pSetHandleInformation(g_hChildStd_OUT_Rd, HANDLE_FLAG_INHERIT, 0)
3597 /* Create a pipe for the child process's STDIN. */
3598 || ! CreatePipe(&g_hChildStd_IN_Rd, &g_hChildStd_IN_Wr, &saAttr, 0)
3599 /* Ensure the write handle to the pipe for STDIN is not inherited. */
3600 || ! pSetHandleInformation(g_hChildStd_IN_Wr, HANDLE_FLAG_INHERIT, 0) )
3601 {
3602 CloseHandle(g_hChildStd_IN_Rd);
3603 CloseHandle(g_hChildStd_IN_Wr);
3604 CloseHandle(g_hChildStd_OUT_Rd);
3605 CloseHandle(g_hChildStd_OUT_Wr);
3606 MSG_PUTS(_("\nCannot create pipes\n"));
3607 }
3608
3609 si.cb = sizeof(si);
3610 si.lpReserved = NULL;
3611 si.lpDesktop = NULL;
3612 si.lpTitle = NULL;
3613 si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
3614
3615 /* set-up our file redirection */
3616 si.hStdError = g_hChildStd_OUT_Wr;
3617 si.hStdOutput = g_hChildStd_OUT_Wr;
3618 si.hStdInput = g_hChildStd_IN_Rd;
3619 si.wShowWindow = SW_HIDE;
3620 si.cbReserved2 = 0;
3621 si.lpReserved2 = NULL;
3622
3623 if (options & SHELL_READ)
3624 ga_init2(&ga, 1, BUFLEN);
3625
Bram Moolenaar6b707b42012-02-21 21:22:44 +01003626 if (cmd != NULL)
3627 {
3628 p = (char *)vim_strsave((char_u *)cmd);
3629 if (p != NULL)
3630 unescape_shellxquote((char_u *)p, p_sxe);
3631 else
3632 p = cmd;
3633 }
3634
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02003635 /* Now, run the command */
3636 CreateProcess(NULL, /* Executable name */
Bram Moolenaar6b707b42012-02-21 21:22:44 +01003637 p, /* Command to execute */
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02003638 NULL, /* Process security attributes */
3639 NULL, /* Thread security attributes */
3640
3641 // this command can be litigeous, handle inheritence was
3642 // deactivated for pending temp file, but, if we deactivate
3643 // it, the pipes don't work for some reason.
3644 TRUE, /* Inherit handles, first deactivated,
3645 * but needed */
3646 CREATE_DEFAULT_ERROR_MODE, /* Creation flags */
3647 NULL, /* Environment */
3648 NULL, /* Current directory */
3649 &si, /* Startup information */
3650 &pi); /* Process information */
3651
Bram Moolenaar6b707b42012-02-21 21:22:44 +01003652 if (p != cmd)
3653 vim_free(p);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02003654
3655 /* Close our unused side of the pipes */
3656 CloseHandle(g_hChildStd_IN_Rd);
3657 CloseHandle(g_hChildStd_OUT_Wr);
3658
3659 if (options & SHELL_WRITE)
3660 {
3661 HANDLE thread =
3662 CreateThread(NULL, /* security attributes */
3663 0, /* default stack size */
3664 sub_process_writer, /* function to be executed */
3665 g_hChildStd_IN_Wr, /* parameter */
3666 0, /* creation flag, start immediately */
3667 NULL); /* we don't care about thread id */
3668 CloseHandle(thread);
3669 g_hChildStd_IN_Wr = NULL;
3670 }
3671
3672 /* Keep updating the window while waiting for the shell to finish. */
3673 for (;;)
3674 {
3675 MSG msg;
3676
3677 if (PeekMessage(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
3678 {
3679 TranslateMessage(&msg);
3680 DispatchMessage(&msg);
3681 }
3682
3683 /* write pipe information in the window */
3684 if ((options & (SHELL_READ|SHELL_WRITE))
3685# ifdef FEAT_GUI
3686 || gui.in_use
3687# endif
3688 )
3689 {
3690 len = 0;
3691 if (!(options & SHELL_EXPAND)
3692 && ((options &
3693 (SHELL_READ|SHELL_WRITE|SHELL_COOKED))
3694 != (SHELL_READ|SHELL_WRITE|SHELL_COOKED)
3695# ifdef FEAT_GUI
3696 || gui.in_use
3697# endif
3698 )
3699 && (ta_len > 0 || noread_cnt > 4))
3700 {
3701 if (ta_len == 0)
3702 {
3703 /* Get extra characters when we don't have any. Reset the
3704 * counter and timer. */
3705 noread_cnt = 0;
3706# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
3707 gettimeofday(&start_tv, NULL);
3708# endif
3709 len = ui_inchar(ta_buf, BUFLEN, 10L, 0);
3710 }
3711 if (ta_len > 0 || len > 0)
3712 {
3713 /*
3714 * For pipes: Check for CTRL-C: send interrupt signal to
3715 * child. Check for CTRL-D: EOF, close pipe to child.
3716 */
3717 if (len == 1 && cmd != NULL)
3718 {
3719 if (ta_buf[ta_len] == Ctrl_C)
3720 {
3721 /* Learn what exit code is expected, for
3722 * now put 9 as SIGKILL */
3723 TerminateProcess(pi.hProcess, 9);
3724 }
3725 if (ta_buf[ta_len] == Ctrl_D)
3726 {
3727 CloseHandle(g_hChildStd_IN_Wr);
3728 g_hChildStd_IN_Wr = NULL;
3729 }
3730 }
3731
3732 /* replace K_BS by <BS> and K_DEL by <DEL> */
3733 for (i = ta_len; i < ta_len + len; ++i)
3734 {
3735 if (ta_buf[i] == CSI && len - i > 2)
3736 {
3737 c = TERMCAP2KEY(ta_buf[i + 1], ta_buf[i + 2]);
3738 if (c == K_DEL || c == K_KDEL || c == K_BS)
3739 {
3740 mch_memmove(ta_buf + i + 1, ta_buf + i + 3,
3741 (size_t)(len - i - 2));
3742 if (c == K_DEL || c == K_KDEL)
3743 ta_buf[i] = DEL;
3744 else
3745 ta_buf[i] = Ctrl_H;
3746 len -= 2;
3747 }
3748 }
3749 else if (ta_buf[i] == '\r')
3750 ta_buf[i] = '\n';
3751# ifdef FEAT_MBYTE
3752 if (has_mbyte)
3753 i += (*mb_ptr2len_len)(ta_buf + i,
3754 ta_len + len - i) - 1;
3755# endif
3756 }
3757
3758 /*
3759 * For pipes: echo the typed characters. For a pty this
3760 * does not seem to work.
3761 */
3762 for (i = ta_len; i < ta_len + len; ++i)
3763 {
3764 if (ta_buf[i] == '\n' || ta_buf[i] == '\b')
3765 msg_putchar(ta_buf[i]);
3766# ifdef FEAT_MBYTE
3767 else if (has_mbyte)
3768 {
3769 int l = (*mb_ptr2len)(ta_buf + i);
3770
3771 msg_outtrans_len(ta_buf + i, l);
3772 i += l - 1;
3773 }
3774# endif
3775 else
3776 msg_outtrans_len(ta_buf + i, 1);
3777 }
3778 windgoto(msg_row, msg_col);
3779 out_flush();
3780
3781 ta_len += len;
3782
3783 /*
3784 * Write the characters to the child, unless EOF has been
3785 * typed for pipes. Write one character at a time, to
3786 * avoid losing too much typeahead. When writing buffer
3787 * lines, drop the typed characters (only check for
3788 * CTRL-C).
3789 */
3790 if (options & SHELL_WRITE)
3791 ta_len = 0;
3792 else if (g_hChildStd_IN_Wr != NULL)
3793 {
3794 WriteFile(g_hChildStd_IN_Wr, (char*)ta_buf,
3795 1, &len, NULL);
3796 // if we are typing in, we want to keep things reactive
3797 delay = 1;
3798 if (len > 0)
3799 {
3800 ta_len -= len;
3801 mch_memmove(ta_buf, ta_buf + len, ta_len);
3802 }
3803 }
3804 }
3805 }
3806 }
3807
3808 if (ta_len)
3809 ui_inchar_undo(ta_buf, ta_len);
3810
3811 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
3812 {
Bram Moolenaar2eba1822011-08-27 15:10:04 +02003813 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02003814 break;
3815 }
3816
3817 ++noread_cnt;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02003818 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02003819
3820 /* We start waiting for a very short time and then increase it, so
3821 * that we respond quickly when the process is quick, and don't
3822 * consume too much overhead when it's slow. */
3823 if (delay < 50)
3824 delay += 10;
3825 }
3826
3827 /* Close the pipe */
3828 CloseHandle(g_hChildStd_OUT_Rd);
3829 if (g_hChildStd_IN_Wr != NULL)
3830 CloseHandle(g_hChildStd_IN_Wr);
3831
3832 WaitForSingleObject(pi.hProcess, INFINITE);
3833
3834 /* Get the command exit code */
3835 GetExitCodeProcess(pi.hProcess, &ret);
3836
3837 if (options & SHELL_READ)
3838 {
3839 if (ga.ga_len > 0)
3840 {
3841 append_ga_line(&ga);
3842 /* remember that the NL was missing */
3843 curbuf->b_no_eol_lnum = curwin->w_cursor.lnum;
3844 }
3845 else
3846 curbuf->b_no_eol_lnum = 0;
3847 ga_clear(&ga);
3848 }
3849
3850 /* Close the handles to the subprocess, so that it goes away */
3851 CloseHandle(pi.hThread);
3852 CloseHandle(pi.hProcess);
3853
3854 return ret;
3855}
3856
3857 static int
3858mch_system(char *cmd, int options)
3859{
3860 /* if we can pipe and the shelltemp option is off */
3861 if (allowPiping && !p_stmp)
3862 return mch_system_piped(cmd, options);
3863 else
3864 return mch_system_classic(cmd, options);
3865}
Bram Moolenaar071d4272004-06-13 20:20:40 +00003866#else
3867
3868# define mch_system(c, o) system(c)
3869
3870#endif
3871
3872/*
3873 * Either execute a command by calling the shell or start a new shell
3874 */
3875 int
3876mch_call_shell(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003877 char_u *cmd,
3878 int options) /* SHELL_*, see vim.h */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003879{
3880 int x = 0;
3881 int tmode = cur_tmode;
3882#ifdef FEAT_TITLE
3883 char szShellTitle[512];
3884
3885 /* Change the title to reflect that we are in a subshell. */
3886 if (GetConsoleTitle(szShellTitle, sizeof(szShellTitle) - 4) > 0)
3887 {
3888 if (cmd == NULL)
3889 strcat(szShellTitle, " :sh");
3890 else
3891 {
3892 strcat(szShellTitle, " - !");
3893 if ((strlen(szShellTitle) + strlen(cmd) < sizeof(szShellTitle)))
3894 strcat(szShellTitle, cmd);
3895 }
3896 mch_settitle(szShellTitle, NULL);
3897 }
3898#endif
3899
3900 out_flush();
3901
3902#ifdef MCH_WRITE_DUMP
3903 if (fdDump)
3904 {
3905 fprintf(fdDump, "mch_call_shell(\"%s\", %d)\n", cmd, options);
3906 fflush(fdDump);
3907 }
3908#endif
3909
3910 /*
3911 * Catch all deadly signals while running the external command, because a
3912 * CTRL-C, Ctrl-Break or illegal instruction might otherwise kill us.
3913 */
3914 signal(SIGINT, SIG_IGN);
3915#if defined(__GNUC__) && !defined(__MINGW32__)
3916 signal(SIGKILL, SIG_IGN);
3917#else
3918 signal(SIGBREAK, SIG_IGN);
3919#endif
3920 signal(SIGILL, SIG_IGN);
3921 signal(SIGFPE, SIG_IGN);
3922 signal(SIGSEGV, SIG_IGN);
3923 signal(SIGTERM, SIG_IGN);
3924 signal(SIGABRT, SIG_IGN);
3925
3926 if (options & SHELL_COOKED)
3927 settmode(TMODE_COOK); /* set to normal mode */
3928
3929 if (cmd == NULL)
3930 {
3931 x = mch_system(p_sh, options);
3932 }
3933 else
3934 {
3935 /* we use "command" or "cmd" to start the shell; slow but easy */
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01003936 char_u *newcmd = NULL;
3937 char_u *cmdbase = cmd;
3938 long_u cmdlen;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01003939
3940 /* Skip a leading ", ( and "(. */
3941 if (*cmdbase == '"' )
3942 ++cmdbase;
3943 if (*cmdbase == '(')
3944 ++cmdbase;
3945
3946 if ((STRNICMP(cmdbase, "start", 5) == 0) && vim_iswhite(cmdbase[5]))
3947 {
3948 STARTUPINFO si;
3949 PROCESS_INFORMATION pi;
3950 DWORD flags = CREATE_NEW_CONSOLE;
3951 char_u *p;
3952
3953 si.cb = sizeof(si);
3954 si.lpReserved = NULL;
3955 si.lpDesktop = NULL;
3956 si.lpTitle = NULL;
3957 si.dwFlags = 0;
3958 si.cbReserved2 = 0;
3959 si.lpReserved2 = NULL;
3960
3961 cmdbase = skipwhite(cmdbase + 5);
3962 if ((STRNICMP(cmdbase, "/min", 4) == 0)
3963 && vim_iswhite(cmdbase[4]))
3964 {
3965 cmdbase = skipwhite(cmdbase + 4);
3966 si.dwFlags = STARTF_USESHOWWINDOW;
3967 si.wShowWindow = SW_SHOWMINNOACTIVE;
3968 }
3969 else if ((STRNICMP(cmdbase, "/b", 2) == 0)
3970 && vim_iswhite(cmdbase[2]))
3971 {
3972 cmdbase = skipwhite(cmdbase + 2);
3973 flags = CREATE_NO_WINDOW;
3974 si.dwFlags = STARTF_USESTDHANDLES;
3975 si.hStdInput = CreateFile("\\\\.\\NUL", // File name
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01003976 GENERIC_READ, // Access flags
Bram Moolenaar6b707b42012-02-21 21:22:44 +01003977 0, // Share flags
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01003978 NULL, // Security att.
3979 OPEN_EXISTING, // Open flags
3980 FILE_ATTRIBUTE_NORMAL, // File att.
3981 NULL); // Temp file
Bram Moolenaar6b707b42012-02-21 21:22:44 +01003982 si.hStdOutput = si.hStdInput;
3983 si.hStdError = si.hStdInput;
3984 }
3985
3986 /* Remove a trailing ", ) and )" if they have a match
3987 * at the start of the command. */
3988 if (cmdbase > cmd)
3989 {
3990 p = cmdbase + STRLEN(cmdbase);
3991 if (p > cmdbase && p[-1] == '"' && *cmd == '"')
3992 *--p = NUL;
3993 if (p > cmdbase && p[-1] == ')'
3994 && (*cmd =='(' || cmd[1] == '('))
3995 *--p = NUL;
3996 }
3997
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01003998 newcmd = cmdbase;
3999 unescape_shellxquote(cmdbase, p_sxe);
4000
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004001 /*
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004002 * If creating new console, arguments are passed to the
4003 * 'cmd.exe' as-is. If it's not, arguments are not treated
4004 * correctly for current 'cmd.exe'. So unescape characters in
4005 * shellxescape except '|' for avoiding to be treated as
4006 * argument to them. Pass the arguments to sub-shell.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004007 */
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004008 if (flags != CREATE_NEW_CONSOLE)
4009 {
4010 char_u *subcmd;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004011 char_u *cmd_shell = mch_getenv("COMSPEC");
4012
4013 if (cmd_shell == NULL || *cmd_shell == NUL)
4014 cmd_shell = default_shell();
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004015
4016 subcmd = vim_strsave_escaped_ext(cmdbase, "|", '^', FALSE);
4017 if (subcmd != NULL)
4018 {
4019 /* make "cmd.exe /c arguments" */
4020 cmdlen = STRLEN(cmd_shell) + STRLEN(subcmd) + 5;
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004021 newcmd = lalloc(cmdlen, TRUE);
4022 if (newcmd != NULL)
4023 vim_snprintf((char *)newcmd, cmdlen, "%s /c %s",
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004024 cmd_shell, subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004025 else
4026 newcmd = cmdbase;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004027 vim_free(subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004028 }
4029 }
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004030
4031 /*
4032 * Now, start the command as a process, so that it doesn't
4033 * inherit our handles which causes unpleasant dangling swap
4034 * files if we exit before the spawned process
4035 */
4036 if (CreateProcess(NULL, // Executable name
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004037 newcmd, // Command to execute
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004038 NULL, // Process security attributes
4039 NULL, // Thread security attributes
4040 FALSE, // Inherit handles
4041 flags, // Creation flags
4042 NULL, // Environment
4043 NULL, // Current directory
4044 &si, // Startup information
4045 &pi)) // Process information
4046 x = 0;
4047 else
4048 {
4049 x = -1;
4050#ifdef FEAT_GUI_W32
4051 EMSG(_("E371: Command not found"));
4052#endif
4053 }
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004054
4055 if (newcmd != cmdbase)
4056 vim_free(newcmd);
4057
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004058 if (si.hStdInput != NULL)
4059 {
4060 /* Close the handle to \\.\NUL */
4061 CloseHandle(si.hStdInput);
4062 }
4063 /* Close the handles to the subprocess, so that it goes away */
4064 CloseHandle(pi.hThread);
4065 CloseHandle(pi.hProcess);
4066 }
4067 else
4068 {
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004069 cmdlen = (
Bram Moolenaar071d4272004-06-13 20:20:40 +00004070#ifdef FEAT_GUI_W32
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004071 (allowPiping && !p_stmp ? 0 : STRLEN(vimrun_path)) +
Bram Moolenaar071d4272004-06-13 20:20:40 +00004072#endif
Bram Moolenaar0fde2902008-03-16 13:54:13 +00004073 STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10);
4074
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004075 newcmd = lalloc(cmdlen, TRUE);
4076 if (newcmd != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004077 {
4078#if defined(FEAT_GUI_W32)
4079 if (need_vimrun_warning)
4080 {
4081 MessageBox(NULL,
4082 _("VIMRUN.EXE not found in your $PATH.\n"
4083 "External commands will not pause after completion.\n"
4084 "See :help win32-vimrun for more information."),
4085 _("Vim Warning"),
4086 MB_ICONWARNING);
4087 need_vimrun_warning = FALSE;
4088 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004089 if (!s_dont_use_vimrun && (!allowPiping || p_stmp))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004090 /* Use vimrun to execute the command. It opens a console
4091 * window, which can be closed without killing Vim. */
Bram Moolenaarcc448b32010-07-14 16:52:17 +02004092 vim_snprintf((char *)newcmd, cmdlen, "%s%s%s %s %s",
Bram Moolenaar071d4272004-06-13 20:20:40 +00004093 vimrun_path,
4094 (msg_silent != 0 || (options & SHELL_DOOUT))
4095 ? "-s " : "",
4096 p_sh, p_shcf, cmd);
4097 else
4098#endif
Bram Moolenaarcc448b32010-07-14 16:52:17 +02004099 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s",
Bram Moolenaar0fde2902008-03-16 13:54:13 +00004100 p_sh, p_shcf, cmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004101 x = mch_system((char *)newcmd, options);
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004102 vim_free(newcmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004103 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004104 }
4105 }
4106
4107 if (tmode == TMODE_RAW)
4108 settmode(TMODE_RAW); /* set to raw mode */
4109
4110 /* Print the return value, unless "vimrun" was used. */
4111 if (x != 0 && !(options & SHELL_SILENT) && !emsg_silent
4112#if defined(FEAT_GUI_W32)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004113 && ((options & SHELL_DOOUT) || s_dont_use_vimrun
4114 || (allowPiping && !p_stmp))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004115#endif
4116 )
4117 {
4118 smsg(_("shell returned %d"), x);
4119 msg_putchar('\n');
4120 }
4121#ifdef FEAT_TITLE
4122 resettitle();
4123#endif
4124
4125 signal(SIGINT, SIG_DFL);
4126#if defined(__GNUC__) && !defined(__MINGW32__)
4127 signal(SIGKILL, SIG_DFL);
4128#else
4129 signal(SIGBREAK, SIG_DFL);
4130#endif
4131 signal(SIGILL, SIG_DFL);
4132 signal(SIGFPE, SIG_DFL);
4133 signal(SIGSEGV, SIG_DFL);
4134 signal(SIGTERM, SIG_DFL);
4135 signal(SIGABRT, SIG_DFL);
4136
4137 return x;
4138}
4139
4140
4141#ifndef FEAT_GUI_W32
4142
4143/*
4144 * Start termcap mode
4145 */
4146 static void
4147termcap_mode_start(void)
4148{
4149 DWORD cmodein;
4150
4151 if (g_fTermcapMode)
4152 return;
4153
4154 SaveConsoleBuffer(&g_cbNonTermcap);
4155
4156 if (g_cbTermcap.IsValid)
4157 {
4158 /*
4159 * We've been in termcap mode before. Restore certain screen
4160 * characteristics, including the buffer size and the window
4161 * size. Since we will be redrawing the screen, we don't need
4162 * to restore the actual contents of the buffer.
4163 */
4164 RestoreConsoleBuffer(&g_cbTermcap, FALSE);
4165 SetConsoleWindowInfo(g_hConOut, TRUE, &g_cbTermcap.Info.srWindow);
4166 Rows = g_cbTermcap.Info.dwSize.Y;
4167 Columns = g_cbTermcap.Info.dwSize.X;
4168 }
4169 else
4170 {
4171 /*
4172 * This is our first time entering termcap mode. Clear the console
4173 * screen buffer, and resize the buffer to match the current window
4174 * size. We will use this as the size of our editing environment.
4175 */
4176 ClearConsoleBuffer(g_attrCurrent);
4177 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
4178 }
4179
4180#ifdef FEAT_TITLE
4181 resettitle();
4182#endif
4183
4184 GetConsoleMode(g_hConIn, &cmodein);
4185#ifdef FEAT_MOUSE
4186 if (g_fMouseActive)
4187 cmodein |= ENABLE_MOUSE_INPUT;
4188 else
4189 cmodein &= ~ENABLE_MOUSE_INPUT;
4190#endif
4191 cmodein |= ENABLE_WINDOW_INPUT;
4192 SetConsoleMode(g_hConIn, cmodein);
4193
4194 redraw_later_clear();
4195 g_fTermcapMode = TRUE;
4196}
4197
4198
4199/*
4200 * End termcap mode
4201 */
4202 static void
4203termcap_mode_end(void)
4204{
4205 DWORD cmodein;
4206 ConsoleBuffer *cb;
4207 COORD coord;
4208 DWORD dwDummy;
4209
4210 if (!g_fTermcapMode)
4211 return;
4212
4213 SaveConsoleBuffer(&g_cbTermcap);
4214
4215 GetConsoleMode(g_hConIn, &cmodein);
4216 cmodein &= ~(ENABLE_MOUSE_INPUT | ENABLE_WINDOW_INPUT);
4217 SetConsoleMode(g_hConIn, cmodein);
4218
4219#ifdef FEAT_RESTORE_ORIG_SCREEN
4220 cb = exiting ? &g_cbOrig : &g_cbNonTermcap;
4221#else
4222 cb = &g_cbNonTermcap;
4223#endif
4224 RestoreConsoleBuffer(cb, p_rs);
4225 SetConsoleCursorInfo(g_hConOut, &g_cci);
4226
4227 if (p_rs || exiting)
4228 {
4229 /*
4230 * Clear anything that happens to be on the current line.
4231 */
4232 coord.X = 0;
4233 coord.Y = (SHORT) (p_rs ? cb->Info.dwCursorPosition.Y : (Rows - 1));
4234 FillConsoleOutputCharacter(g_hConOut, ' ',
4235 cb->Info.dwSize.X, coord, &dwDummy);
4236 /*
4237 * The following is just for aesthetics. If we are exiting without
4238 * restoring the screen, then we want to have a prompt string
4239 * appear at the bottom line. However, the command interpreter
4240 * seems to always advance the cursor one line before displaying
4241 * the prompt string, which causes the screen to scroll. To
4242 * counter this, move the cursor up one line before exiting.
4243 */
4244 if (exiting && !p_rs)
4245 coord.Y--;
4246 /*
4247 * Position the cursor at the leftmost column of the desired row.
4248 */
4249 SetConsoleCursorPosition(g_hConOut, coord);
4250 }
4251
4252 g_fTermcapMode = FALSE;
4253}
4254#endif /* FEAT_GUI_W32 */
4255
4256
4257#ifdef FEAT_GUI_W32
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00004258/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00004259 void
4260mch_write(
4261 char_u *s,
4262 int len)
4263{
4264 /* never used */
4265}
4266
4267#else
4268
4269/*
4270 * clear `n' chars, starting from `coord'
4271 */
4272 static void
4273clear_chars(
4274 COORD coord,
4275 DWORD n)
4276{
4277 DWORD dwDummy;
4278
4279 FillConsoleOutputCharacter(g_hConOut, ' ', n, coord, &dwDummy);
4280 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, n, coord, &dwDummy);
4281}
4282
4283
4284/*
4285 * Clear the screen
4286 */
4287 static void
4288clear_screen(void)
4289{
4290 g_coord.X = g_coord.Y = 0;
4291 clear_chars(g_coord, Rows * Columns);
4292}
4293
4294
4295/*
4296 * Clear to end of display
4297 */
4298 static void
4299clear_to_end_of_display(void)
4300{
4301 clear_chars(g_coord, (Rows - g_coord.Y - 1)
4302 * Columns + (Columns - g_coord.X));
4303}
4304
4305
4306/*
4307 * Clear to end of line
4308 */
4309 static void
4310clear_to_end_of_line(void)
4311{
4312 clear_chars(g_coord, Columns - g_coord.X);
4313}
4314
4315
4316/*
4317 * Scroll the scroll region up by `cLines' lines
4318 */
4319 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004320scroll(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004321{
4322 COORD oldcoord = g_coord;
4323
4324 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
4325 delete_lines(cLines);
4326
4327 g_coord = oldcoord;
4328}
4329
4330
4331/*
4332 * Set the scroll region
4333 */
4334 static void
4335set_scroll_region(
4336 unsigned left,
4337 unsigned top,
4338 unsigned right,
4339 unsigned bottom)
4340{
4341 if (left >= right
4342 || top >= bottom
4343 || right > (unsigned) Columns - 1
4344 || bottom > (unsigned) Rows - 1)
4345 return;
4346
4347 g_srScrollRegion.Left = left;
4348 g_srScrollRegion.Top = top;
4349 g_srScrollRegion.Right = right;
4350 g_srScrollRegion.Bottom = bottom;
4351}
4352
4353
4354/*
4355 * Insert `cLines' lines at the current cursor position
4356 */
4357 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004358insert_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004359{
4360 SMALL_RECT source;
4361 COORD dest;
4362 CHAR_INFO fill;
4363
4364 dest.X = 0;
4365 dest.Y = g_coord.Y + cLines;
4366
4367 source.Left = 0;
4368 source.Top = g_coord.Y;
4369 source.Right = g_srScrollRegion.Right;
4370 source.Bottom = g_srScrollRegion.Bottom - cLines;
4371
4372 fill.Char.AsciiChar = ' ';
4373 fill.Attributes = g_attrCurrent;
4374
4375 ScrollConsoleScreenBuffer(g_hConOut, &source, NULL, dest, &fill);
4376
4377 /* Here we have to deal with a win32 console flake: If the scroll
4378 * region looks like abc and we scroll c to a and fill with d we get
4379 * cbd... if we scroll block c one line at a time to a, we get cdd...
4380 * vim expects cdd consistently... So we have to deal with that
4381 * here... (this also occurs scrolling the same way in the other
4382 * direction). */
4383
4384 if (source.Bottom < dest.Y)
4385 {
4386 COORD coord;
4387
4388 coord.X = 0;
4389 coord.Y = source.Bottom;
4390 clear_chars(coord, Columns * (dest.Y - source.Bottom));
4391 }
4392}
4393
4394
4395/*
4396 * Delete `cLines' lines at the current cursor position
4397 */
4398 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004399delete_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004400{
4401 SMALL_RECT source;
4402 COORD dest;
4403 CHAR_INFO fill;
4404 int nb;
4405
4406 dest.X = 0;
4407 dest.Y = g_coord.Y;
4408
4409 source.Left = 0;
4410 source.Top = g_coord.Y + cLines;
4411 source.Right = g_srScrollRegion.Right;
4412 source.Bottom = g_srScrollRegion.Bottom;
4413
4414 fill.Char.AsciiChar = ' ';
4415 fill.Attributes = g_attrCurrent;
4416
4417 ScrollConsoleScreenBuffer(g_hConOut, &source, NULL, dest, &fill);
4418
4419 /* Here we have to deal with a win32 console flake: If the scroll
4420 * region looks like abc and we scroll c to a and fill with d we get
4421 * cbd... if we scroll block c one line at a time to a, we get cdd...
4422 * vim expects cdd consistently... So we have to deal with that
4423 * here... (this also occurs scrolling the same way in the other
4424 * direction). */
4425
4426 nb = dest.Y + (source.Bottom - source.Top) + 1;
4427
4428 if (nb < source.Top)
4429 {
4430 COORD coord;
4431
4432 coord.X = 0;
4433 coord.Y = nb;
4434 clear_chars(coord, Columns * (source.Top - nb));
4435 }
4436}
4437
4438
4439/*
4440 * Set the cursor position
4441 */
4442 static void
4443gotoxy(
4444 unsigned x,
4445 unsigned y)
4446{
4447 if (x < 1 || x > (unsigned)Columns || y < 1 || y > (unsigned)Rows)
4448 return;
4449
4450 /* external cursor coords are 1-based; internal are 0-based */
4451 g_coord.X = x - 1;
4452 g_coord.Y = y - 1;
4453 SetConsoleCursorPosition(g_hConOut, g_coord);
4454}
4455
4456
4457/*
4458 * Set the current text attribute = (foreground | background)
4459 * See ../doc/os_win32.txt for the numbers.
4460 */
4461 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004462textattr(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004463{
4464 g_attrCurrent = wAttr;
4465
4466 SetConsoleTextAttribute(g_hConOut, wAttr);
4467}
4468
4469
4470 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004471textcolor(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004472{
4473 g_attrCurrent = (g_attrCurrent & 0xf0) + wAttr;
4474
4475 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
4476}
4477
4478
4479 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004480textbackground(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004481{
4482 g_attrCurrent = (g_attrCurrent & 0x0f) + (wAttr << 4);
4483
4484 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
4485}
4486
4487
4488/*
4489 * restore the default text attribute (whatever we started with)
4490 */
4491 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004492normvideo(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004493{
4494 textattr(g_attrDefault);
4495}
4496
4497
4498static WORD g_attrPreStandout = 0;
4499
4500/*
4501 * Make the text standout, by brightening it
4502 */
4503 static void
4504standout(void)
4505{
4506 g_attrPreStandout = g_attrCurrent;
4507 textattr((WORD) (g_attrCurrent|FOREGROUND_INTENSITY|BACKGROUND_INTENSITY));
4508}
4509
4510
4511/*
4512 * Turn off standout mode
4513 */
4514 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004515standend(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004516{
4517 if (g_attrPreStandout)
4518 {
4519 textattr(g_attrPreStandout);
4520 g_attrPreStandout = 0;
4521 }
4522}
4523
4524
4525/*
Bram Moolenaarff1d0d42007-05-10 17:24:16 +00004526 * Set normal fg/bg color, based on T_ME. Called when t_me has been set.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004527 */
4528 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004529mch_set_normal_colors(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004530{
4531 char_u *p;
4532 int n;
4533
4534 cterm_normal_fg_color = (g_attrDefault & 0xf) + 1;
4535 cterm_normal_bg_color = ((g_attrDefault >> 4) & 0xf) + 1;
4536 if (T_ME[0] == ESC && T_ME[1] == '|')
4537 {
4538 p = T_ME + 2;
4539 n = getdigits(&p);
4540 if (*p == 'm' && n > 0)
4541 {
4542 cterm_normal_fg_color = (n & 0xf) + 1;
4543 cterm_normal_bg_color = ((n >> 4) & 0xf) + 1;
4544 }
4545 }
4546}
4547
4548
4549/*
4550 * visual bell: flash the screen
4551 */
4552 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004553visual_bell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004554{
4555 COORD coordOrigin = {0, 0};
4556 WORD attrFlash = ~g_attrCurrent & 0xff;
4557
4558 DWORD dwDummy;
4559 LPWORD oldattrs = (LPWORD)alloc(Rows * Columns * sizeof(WORD));
4560
4561 if (oldattrs == NULL)
4562 return;
4563 ReadConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
4564 coordOrigin, &dwDummy);
4565 FillConsoleOutputAttribute(g_hConOut, attrFlash, Rows * Columns,
4566 coordOrigin, &dwDummy);
4567
4568 Sleep(15); /* wait for 15 msec */
4569 WriteConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
4570 coordOrigin, &dwDummy);
4571 vim_free(oldattrs);
4572}
4573
4574
4575/*
4576 * Make the cursor visible or invisible
4577 */
4578 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004579cursor_visible(BOOL fVisible)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004580{
4581 s_cursor_visible = fVisible;
4582#ifdef MCH_CURSOR_SHAPE
4583 mch_update_cursor();
4584#endif
4585}
4586
4587
4588/*
4589 * write `cchToWrite' characters in `pchBuf' to the screen
4590 * Returns the number of characters actually written (at least one).
4591 */
4592 static BOOL
4593write_chars(
4594 LPCSTR pchBuf,
4595 DWORD cchToWrite)
4596{
4597 COORD coord = g_coord;
4598 DWORD written;
4599
4600 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, cchToWrite,
4601 coord, &written);
4602 /* When writing fails or didn't write a single character, pretend one
4603 * character was written, otherwise we get stuck. */
4604 if (WriteConsoleOutputCharacter(g_hConOut, pchBuf, cchToWrite,
4605 coord, &written) == 0
4606 || written == 0)
4607 written = 1;
4608
4609 g_coord.X += (SHORT) written;
4610
4611 while (g_coord.X > g_srScrollRegion.Right)
4612 {
4613 g_coord.X -= (SHORT) Columns;
4614 if (g_coord.Y < g_srScrollRegion.Bottom)
4615 g_coord.Y++;
4616 }
4617
4618 gotoxy(g_coord.X + 1, g_coord.Y + 1);
4619
4620 return written;
4621}
4622
4623
4624/*
4625 * mch_write(): write the output buffer to the screen, translating ESC
4626 * sequences into calls to console output routines.
4627 */
4628 void
4629mch_write(
4630 char_u *s,
4631 int len)
4632{
4633 s[len] = NUL;
4634
4635 if (!term_console)
4636 {
4637 write(1, s, (unsigned)len);
4638 return;
4639 }
4640
4641 /* translate ESC | sequences into faked bios calls */
4642 while (len--)
4643 {
4644 /* optimization: use one single write_chars for runs of text,
4645 * rather than once per character It ain't curses, but it helps. */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00004646 DWORD prefix = (DWORD)strcspn(s, "\n\r\b\a\033");
Bram Moolenaar071d4272004-06-13 20:20:40 +00004647
4648 if (p_wd)
4649 {
4650 WaitForChar(p_wd);
4651 if (prefix != 0)
4652 prefix = 1;
4653 }
4654
4655 if (prefix != 0)
4656 {
4657 DWORD nWritten;
4658
4659 nWritten = write_chars(s, prefix);
4660#ifdef MCH_WRITE_DUMP
4661 if (fdDump)
4662 {
4663 fputc('>', fdDump);
4664 fwrite(s, sizeof(char_u), nWritten, fdDump);
4665 fputs("<\n", fdDump);
4666 }
4667#endif
4668 len -= (nWritten - 1);
4669 s += nWritten;
4670 }
4671 else if (s[0] == '\n')
4672 {
4673 /* \n, newline: go to the beginning of the next line or scroll */
4674 if (g_coord.Y == g_srScrollRegion.Bottom)
4675 {
4676 scroll(1);
4677 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Bottom + 1);
4678 }
4679 else
4680 {
4681 gotoxy(g_srScrollRegion.Left + 1, g_coord.Y + 2);
4682 }
4683#ifdef MCH_WRITE_DUMP
4684 if (fdDump)
4685 fputs("\\n\n", fdDump);
4686#endif
4687 s++;
4688 }
4689 else if (s[0] == '\r')
4690 {
4691 /* \r, carriage return: go to beginning of line */
4692 gotoxy(g_srScrollRegion.Left+1, g_coord.Y + 1);
4693#ifdef MCH_WRITE_DUMP
4694 if (fdDump)
4695 fputs("\\r\n", fdDump);
4696#endif
4697 s++;
4698 }
4699 else if (s[0] == '\b')
4700 {
4701 /* \b, backspace: move cursor one position left */
4702 if (g_coord.X > g_srScrollRegion.Left)
4703 g_coord.X--;
4704 else if (g_coord.Y > g_srScrollRegion.Top)
4705 {
4706 g_coord.X = g_srScrollRegion.Right;
4707 g_coord.Y--;
4708 }
4709 gotoxy(g_coord.X + 1, g_coord.Y + 1);
4710#ifdef MCH_WRITE_DUMP
4711 if (fdDump)
4712 fputs("\\b\n", fdDump);
4713#endif
4714 s++;
4715 }
4716 else if (s[0] == '\a')
4717 {
4718 /* \a, bell */
4719 MessageBeep(0xFFFFFFFF);
4720#ifdef MCH_WRITE_DUMP
4721 if (fdDump)
4722 fputs("\\a\n", fdDump);
4723#endif
4724 s++;
4725 }
4726 else if (s[0] == ESC && len >= 3-1 && s[1] == '|')
4727 {
4728#ifdef MCH_WRITE_DUMP
Bram Moolenaarc0197e22004-09-13 20:26:32 +00004729 char_u *old_s = s;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004730#endif
Bram Moolenaarc0197e22004-09-13 20:26:32 +00004731 char_u *p;
4732 int arg1 = 0, arg2 = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004733
4734 switch (s[2])
4735 {
4736 /* one or two numeric arguments, separated by ';' */
4737
4738 case '0': case '1': case '2': case '3': case '4':
4739 case '5': case '6': case '7': case '8': case '9':
4740 p = s + 2;
4741 arg1 = getdigits(&p); /* no check for length! */
4742 if (p > s + len)
4743 break;
4744
4745 if (*p == ';')
4746 {
4747 ++p;
4748 arg2 = getdigits(&p); /* no check for length! */
4749 if (p > s + len)
4750 break;
4751
4752 if (*p == 'H')
4753 gotoxy(arg2, arg1);
4754 else if (*p == 'r')
4755 set_scroll_region(0, arg1 - 1, Columns - 1, arg2 - 1);
4756 }
4757 else if (*p == 'A')
4758 {
4759 /* move cursor up arg1 lines in same column */
4760 gotoxy(g_coord.X + 1,
4761 max(g_srScrollRegion.Top, g_coord.Y - arg1) + 1);
4762 }
4763 else if (*p == 'C')
4764 {
4765 /* move cursor right arg1 columns in same line */
4766 gotoxy(min(g_srScrollRegion.Right, g_coord.X + arg1) + 1,
4767 g_coord.Y + 1);
4768 }
4769 else if (*p == 'H')
4770 {
4771 gotoxy(1, arg1);
4772 }
4773 else if (*p == 'L')
4774 {
4775 insert_lines(arg1);
4776 }
4777 else if (*p == 'm')
4778 {
4779 if (arg1 == 0)
4780 normvideo();
4781 else
4782 textattr((WORD) arg1);
4783 }
4784 else if (*p == 'f')
4785 {
4786 textcolor((WORD) arg1);
4787 }
4788 else if (*p == 'b')
4789 {
4790 textbackground((WORD) arg1);
4791 }
4792 else if (*p == 'M')
4793 {
4794 delete_lines(arg1);
4795 }
4796
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00004797 len -= (int)(p - s);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004798 s = p + 1;
4799 break;
4800
4801
4802 /* Three-character escape sequences */
4803
4804 case 'A':
4805 /* move cursor up one line in same column */
4806 gotoxy(g_coord.X + 1,
4807 max(g_srScrollRegion.Top, g_coord.Y - 1) + 1);
4808 goto got3;
4809
4810 case 'B':
4811 visual_bell();
4812 goto got3;
4813
4814 case 'C':
4815 /* move cursor right one column in same line */
4816 gotoxy(min(g_srScrollRegion.Right, g_coord.X + 1) + 1,
4817 g_coord.Y + 1);
4818 goto got3;
4819
4820 case 'E':
4821 termcap_mode_end();
4822 goto got3;
4823
4824 case 'F':
4825 standout();
4826 goto got3;
4827
4828 case 'f':
4829 standend();
4830 goto got3;
4831
4832 case 'H':
4833 gotoxy(1, 1);
4834 goto got3;
4835
4836 case 'j':
4837 clear_to_end_of_display();
4838 goto got3;
4839
4840 case 'J':
4841 clear_screen();
4842 goto got3;
4843
4844 case 'K':
4845 clear_to_end_of_line();
4846 goto got3;
4847
4848 case 'L':
4849 insert_lines(1);
4850 goto got3;
4851
4852 case 'M':
4853 delete_lines(1);
4854 goto got3;
4855
4856 case 'S':
4857 termcap_mode_start();
4858 goto got3;
4859
4860 case 'V':
4861 cursor_visible(TRUE);
4862 goto got3;
4863
4864 case 'v':
4865 cursor_visible(FALSE);
4866 goto got3;
4867
4868 got3:
4869 s += 3;
4870 len -= 2;
4871 }
4872
4873#ifdef MCH_WRITE_DUMP
4874 if (fdDump)
4875 {
4876 fputs("ESC | ", fdDump);
4877 fwrite(old_s + 2, sizeof(char_u), s - old_s - 2, fdDump);
4878 fputc('\n', fdDump);
4879 }
4880#endif
4881 }
4882 else
4883 {
4884 /* Write a single character */
4885 DWORD nWritten;
4886
4887 nWritten = write_chars(s, 1);
4888#ifdef MCH_WRITE_DUMP
4889 if (fdDump)
4890 {
4891 fputc('>', fdDump);
4892 fwrite(s, sizeof(char_u), nWritten, fdDump);
4893 fputs("<\n", fdDump);
4894 }
4895#endif
4896
4897 len -= (nWritten - 1);
4898 s += nWritten;
4899 }
4900 }
4901
4902#ifdef MCH_WRITE_DUMP
4903 if (fdDump)
4904 fflush(fdDump);
4905#endif
4906}
4907
4908#endif /* FEAT_GUI_W32 */
4909
4910
4911/*
4912 * Delay for half a second.
4913 */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00004914/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00004915 void
4916mch_delay(
4917 long msec,
4918 int ignoreinput)
4919{
4920#ifdef FEAT_GUI_W32
4921 Sleep((int)msec); /* never wait for input */
Bram Moolenaar325b7a22004-07-05 15:58:32 +00004922#else /* Console */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004923 if (ignoreinput)
Bram Moolenaar325b7a22004-07-05 15:58:32 +00004924# ifdef FEAT_MZSCHEME
4925 if (mzthreads_allowed() && p_mzq > 0 && msec > p_mzq)
4926 {
4927 int towait = p_mzq;
4928
4929 /* if msec is large enough, wait by portions in p_mzq */
4930 while (msec > 0)
4931 {
4932 mzvim_check_threads();
4933 if (msec < towait)
4934 towait = msec;
4935 Sleep(towait);
4936 msec -= towait;
4937 }
4938 }
4939 else
4940# endif
4941 Sleep((int)msec);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004942 else
4943 WaitForChar(msec);
4944#endif
4945}
4946
4947
4948/*
4949 * this version of remove is not scared by a readonly (backup) file
4950 * Return 0 for success, -1 for failure.
4951 */
4952 int
4953mch_remove(char_u *name)
4954{
4955#ifdef FEAT_MBYTE
4956 WCHAR *wn = NULL;
4957 int n;
4958
4959 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4960 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00004961 wn = enc_to_utf16(name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004962 if (wn != NULL)
4963 {
4964 SetFileAttributesW(wn, FILE_ATTRIBUTE_NORMAL);
4965 n = DeleteFileW(wn) ? 0 : -1;
4966 vim_free(wn);
4967 if (n == 0 || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
4968 return n;
4969 /* Retry with non-wide function (for Windows 98). */
4970 }
4971 }
4972#endif
4973 SetFileAttributes(name, FILE_ATTRIBUTE_NORMAL);
4974 return DeleteFile(name) ? 0 : -1;
4975}
4976
4977
4978/*
4979 * check for an "interrupt signal": CTRL-break or CTRL-C
4980 */
4981 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004982mch_breakcheck(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004983{
4984#ifndef FEAT_GUI_W32 /* never used */
4985 if (g_fCtrlCPressed || g_fCBrkPressed)
4986 {
4987 g_fCtrlCPressed = g_fCBrkPressed = FALSE;
4988 got_int = TRUE;
4989 }
4990#endif
4991}
4992
4993
4994/*
4995 * How much memory is available?
4996 * Return sum of available physical and page file memory.
4997 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00004998/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00004999 long_u
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005000mch_avail_mem(int special)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005001{
5002 MEMORYSTATUS ms;
5003
5004 ms.dwLength = sizeof(MEMORYSTATUS);
5005 GlobalMemoryStatus(&ms);
5006 return (long_u) (ms.dwAvailPhys + ms.dwAvailPageFile);
5007}
5008
5009#ifdef FEAT_MBYTE
5010/*
5011 * Same code as below, but with wide functions and no comments.
5012 * Return 0 for success, non-zero for failure.
5013 */
5014 int
5015mch_wrename(WCHAR *wold, WCHAR *wnew)
5016{
5017 WCHAR *p;
5018 int i;
5019 WCHAR szTempFile[_MAX_PATH + 1];
5020 WCHAR szNewPath[_MAX_PATH + 1];
5021 HANDLE hf;
5022
5023 if (!mch_windows95())
5024 {
5025 p = wold;
5026 for (i = 0; wold[i] != NUL; ++i)
5027 if ((wold[i] == '/' || wold[i] == '\\' || wold[i] == ':')
5028 && wold[i + 1] != 0)
5029 p = wold + i + 1;
5030 if ((int)(wold + i - p) < 8 || p[6] != '~')
5031 return (MoveFileW(wold, wnew) == 0);
5032 }
5033
5034 if (GetFullPathNameW(wnew, _MAX_PATH, szNewPath, &p) == 0 || p == NULL)
5035 return -1;
5036 *p = NUL;
5037
5038 if (GetTempFileNameW(szNewPath, L"VIM", 0, szTempFile) == 0)
5039 return -2;
5040
5041 if (!DeleteFileW(szTempFile))
5042 return -3;
5043
5044 if (!MoveFileW(wold, szTempFile))
5045 return -4;
5046
5047 if ((hf = CreateFileW(wold, GENERIC_WRITE, 0, NULL, CREATE_NEW,
5048 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
5049 return -5;
5050 if (!CloseHandle(hf))
5051 return -6;
5052
5053 if (!MoveFileW(szTempFile, wnew))
5054 {
5055 (void)MoveFileW(szTempFile, wold);
5056 return -7;
5057 }
5058
5059 DeleteFileW(szTempFile);
5060
5061 if (!DeleteFileW(wold))
5062 return -8;
5063
5064 return 0;
5065}
5066#endif
5067
5068
5069/*
5070 * mch_rename() works around a bug in rename (aka MoveFile) in
5071 * Windows 95: rename("foo.bar", "foo.bar~") will generate a
5072 * file whose short file name is "FOO.BAR" (its long file name will
5073 * be correct: "foo.bar~"). Because a file can be accessed by
5074 * either its SFN or its LFN, "foo.bar" has effectively been
5075 * renamed to "foo.bar", which is not at all what was wanted. This
5076 * seems to happen only when renaming files with three-character
5077 * extensions by appending a suffix that does not include ".".
5078 * Windows NT gets it right, however, with an SFN of "FOO~1.BAR".
5079 *
5080 * There is another problem, which isn't really a bug but isn't right either:
5081 * When renaming "abcdef~1.txt" to "abcdef~1.txt~", the short name can be
5082 * "abcdef~1.txt" again. This has been reported on Windows NT 4.0 with
5083 * service pack 6. Doesn't seem to happen on Windows 98.
5084 *
5085 * Like rename(), returns 0 upon success, non-zero upon failure.
5086 * Should probably set errno appropriately when errors occur.
5087 */
5088 int
5089mch_rename(
5090 const char *pszOldFile,
5091 const char *pszNewFile)
5092{
5093 char szTempFile[_MAX_PATH+1];
5094 char szNewPath[_MAX_PATH+1];
5095 char *pszFilePart;
5096 HANDLE hf;
5097#ifdef FEAT_MBYTE
5098 WCHAR *wold = NULL;
5099 WCHAR *wnew = NULL;
5100 int retval = -1;
5101
5102 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
5103 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00005104 wold = enc_to_utf16((char_u *)pszOldFile, NULL);
5105 wnew = enc_to_utf16((char_u *)pszNewFile, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005106 if (wold != NULL && wnew != NULL)
5107 retval = mch_wrename(wold, wnew);
5108 vim_free(wold);
5109 vim_free(wnew);
5110 if (retval == 0 || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
5111 return retval;
5112 /* Retry with non-wide function (for Windows 98). */
5113 }
5114#endif
5115
5116 /*
5117 * No need to play tricks if not running Windows 95, unless the file name
5118 * contains a "~" as the seventh character.
5119 */
5120 if (!mch_windows95())
5121 {
5122 pszFilePart = (char *)gettail((char_u *)pszOldFile);
5123 if (STRLEN(pszFilePart) < 8 || pszFilePart[6] != '~')
5124 return rename(pszOldFile, pszNewFile);
5125 }
5126
5127 /* Get base path of new file name. Undocumented feature: If pszNewFile is
5128 * a directory, no error is returned and pszFilePart will be NULL. */
5129 if (GetFullPathName(pszNewFile, _MAX_PATH, szNewPath, &pszFilePart) == 0
5130 || pszFilePart == NULL)
5131 return -1;
5132 *pszFilePart = NUL;
5133
5134 /* Get (and create) a unique temporary file name in directory of new file */
5135 if (GetTempFileName(szNewPath, "VIM", 0, szTempFile) == 0)
5136 return -2;
5137
5138 /* blow the temp file away */
5139 if (!DeleteFile(szTempFile))
5140 return -3;
5141
5142 /* rename old file to the temp file */
5143 if (!MoveFile(pszOldFile, szTempFile))
5144 return -4;
5145
5146 /* now create an empty file called pszOldFile; this prevents the operating
5147 * system using pszOldFile as an alias (SFN) if we're renaming within the
5148 * same directory. For example, we're editing a file called
5149 * filename.asc.txt by its SFN, filena~1.txt. If we rename filena~1.txt
5150 * to filena~1.txt~ (i.e., we're making a backup while writing it), the
5151 * SFN for filena~1.txt~ will be filena~1.txt, by default, which will
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00005152 * cause all sorts of problems later in buf_write(). So, we create an
5153 * empty file called filena~1.txt and the system will have to find some
5154 * other SFN for filena~1.txt~, such as filena~2.txt
Bram Moolenaar071d4272004-06-13 20:20:40 +00005155 */
5156 if ((hf = CreateFile(pszOldFile, GENERIC_WRITE, 0, NULL, CREATE_NEW,
5157 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
5158 return -5;
5159 if (!CloseHandle(hf))
5160 return -6;
5161
5162 /* rename the temp file to the new file */
5163 if (!MoveFile(szTempFile, pszNewFile))
5164 {
5165 /* Renaming failed. Rename the file back to its old name, so that it
5166 * looks like nothing happened. */
5167 (void)MoveFile(szTempFile, pszOldFile);
5168
5169 return -7;
5170 }
5171
5172 /* Seems to be left around on Novell filesystems */
5173 DeleteFile(szTempFile);
5174
5175 /* finally, remove the empty old file */
5176 if (!DeleteFile(pszOldFile))
5177 return -8;
5178
5179 return 0; /* success */
5180}
5181
5182/*
5183 * Get the default shell for the current hardware platform
5184 */
5185 char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005186default_shell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005187{
5188 char* psz = NULL;
5189
5190 PlatformId();
5191
5192 if (g_PlatformId == VER_PLATFORM_WIN32_NT) /* Windows NT */
5193 psz = "cmd.exe";
5194 else if (g_PlatformId == VER_PLATFORM_WIN32_WINDOWS) /* Windows 95 */
5195 psz = "command.com";
5196
5197 return psz;
5198}
5199
5200/*
5201 * mch_access() extends access() to do more detailed check on network drives.
5202 * Returns 0 if file "n" has access rights according to "p", -1 otherwise.
5203 */
5204 int
5205mch_access(char *n, int p)
5206{
5207 HANDLE hFile;
5208 DWORD am;
5209 int retval = -1; /* default: fail */
5210#ifdef FEAT_MBYTE
5211 WCHAR *wn = NULL;
5212
5213 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar36f692d2008-11-20 16:10:17 +00005214 wn = enc_to_utf16(n, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005215#endif
5216
5217 if (mch_isdir(n))
5218 {
5219 char TempName[_MAX_PATH + 16] = "";
5220#ifdef FEAT_MBYTE
5221 WCHAR TempNameW[_MAX_PATH + 16] = L"";
5222#endif
5223
5224 if (p & R_OK)
5225 {
5226 /* Read check is performed by seeing if we can do a find file on
5227 * the directory for any file. */
5228#ifdef FEAT_MBYTE
5229 if (wn != NULL)
5230 {
5231 int i;
5232 WIN32_FIND_DATAW d;
5233
5234 for (i = 0; i < _MAX_PATH && wn[i] != 0; ++i)
5235 TempNameW[i] = wn[i];
5236 if (TempNameW[i - 1] != '\\' && TempNameW[i - 1] != '/')
5237 TempNameW[i++] = '\\';
5238 TempNameW[i++] = '*';
5239 TempNameW[i++] = 0;
5240
5241 hFile = FindFirstFileW(TempNameW, &d);
5242 if (hFile == INVALID_HANDLE_VALUE)
5243 {
5244 if (GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
5245 goto getout;
5246
5247 /* Retry with non-wide function (for Windows 98). */
5248 vim_free(wn);
5249 wn = NULL;
5250 }
5251 else
5252 (void)FindClose(hFile);
5253 }
5254 if (wn == NULL)
5255#endif
5256 {
5257 char *pch;
5258 WIN32_FIND_DATA d;
5259
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00005260 vim_strncpy(TempName, n, _MAX_PATH);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005261 pch = TempName + STRLEN(TempName) - 1;
5262 if (*pch != '\\' && *pch != '/')
5263 *++pch = '\\';
5264 *++pch = '*';
5265 *++pch = NUL;
5266
5267 hFile = FindFirstFile(TempName, &d);
5268 if (hFile == INVALID_HANDLE_VALUE)
5269 goto getout;
5270 (void)FindClose(hFile);
5271 }
5272 }
5273
5274 if (p & W_OK)
5275 {
5276 /* Trying to create a temporary file in the directory should catch
5277 * directories on read-only network shares. However, in
5278 * directories whose ACL allows writes but denies deletes will end
5279 * up keeping the temporary file :-(. */
5280#ifdef FEAT_MBYTE
5281 if (wn != NULL)
5282 {
5283 if (!GetTempFileNameW(wn, L"VIM", 0, TempNameW))
5284 {
5285 if (GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
5286 goto getout;
5287
5288 /* Retry with non-wide function (for Windows 98). */
5289 vim_free(wn);
5290 wn = NULL;
5291 }
5292 else
5293 DeleteFileW(TempNameW);
5294 }
5295 if (wn == NULL)
5296#endif
5297 {
5298 if (!GetTempFileName(n, "VIM", 0, TempName))
5299 goto getout;
5300 mch_remove((char_u *)TempName);
5301 }
5302 }
5303 }
5304 else
5305 {
5306 /* Trying to open the file for the required access does ACL, read-only
5307 * network share, and file attribute checks. */
5308 am = ((p & W_OK) ? GENERIC_WRITE : 0)
5309 | ((p & R_OK) ? GENERIC_READ : 0);
5310#ifdef FEAT_MBYTE
5311 if (wn != NULL)
5312 {
5313 hFile = CreateFileW(wn, am, 0, NULL, OPEN_EXISTING, 0, NULL);
5314 if (hFile == INVALID_HANDLE_VALUE
5315 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
5316 {
5317 /* Retry with non-wide function (for Windows 98). */
5318 vim_free(wn);
5319 wn = NULL;
5320 }
5321 }
5322 if (wn == NULL)
5323#endif
5324 hFile = CreateFile(n, am, 0, NULL, OPEN_EXISTING, 0, NULL);
5325 if (hFile == INVALID_HANDLE_VALUE)
5326 goto getout;
5327 CloseHandle(hFile);
5328 }
5329
5330 retval = 0; /* success */
5331getout:
5332#ifdef FEAT_MBYTE
5333 vim_free(wn);
5334#endif
5335 return retval;
5336}
5337
5338#if defined(FEAT_MBYTE) || defined(PROTO)
5339/*
Bram Moolenaar36f692d2008-11-20 16:10:17 +00005340 * Version of open() that may use UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005341 */
5342 int
5343mch_open(char *name, int flags, int mode)
5344{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00005345 /* _wopen() does not work with Borland C 5.5: creates a read-only file. */
5346# ifndef __BORLANDC__
Bram Moolenaar071d4272004-06-13 20:20:40 +00005347 WCHAR *wn;
5348 int f;
5349
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00005350 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005351 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00005352 wn = enc_to_utf16(name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005353 if (wn != NULL)
5354 {
5355 f = _wopen(wn, flags, mode);
5356 vim_free(wn);
5357 if (f >= 0)
5358 return f;
5359 /* Retry with non-wide function (for Windows 98). Can't use
5360 * GetLastError() here and it's unclear what errno gets set to if
5361 * the _wopen() fails for missing wide functions. */
5362 }
5363 }
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00005364# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005365
5366 return open(name, flags, mode);
5367}
5368
5369/*
Bram Moolenaar36f692d2008-11-20 16:10:17 +00005370 * Version of fopen() that may use UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005371 */
5372 FILE *
5373mch_fopen(char *name, char *mode)
5374{
5375 WCHAR *wn, *wm;
5376 FILE *f = NULL;
5377
5378 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage
5379# ifdef __BORLANDC__
5380 /* Wide functions of Borland C 5.5 do not work on Windows 98. */
5381 && g_PlatformId == VER_PLATFORM_WIN32_NT
5382# endif
5383 )
5384 {
Bram Moolenaare6a91fd2008-07-24 18:51:11 +00005385# if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0fde2902008-03-16 13:54:13 +00005386 /* Work around an annoying assertion in the Microsoft debug CRT
5387 * when mode's text/binary setting doesn't match _get_fmode(). */
5388 char newMode = mode[strlen(mode) - 1];
5389 int oldMode = 0;
5390
5391 _get_fmode(&oldMode);
5392 if (newMode == 't')
5393 _set_fmode(_O_TEXT);
5394 else if (newMode == 'b')
5395 _set_fmode(_O_BINARY);
5396# endif
Bram Moolenaar36f692d2008-11-20 16:10:17 +00005397 wn = enc_to_utf16(name, NULL);
5398 wm = enc_to_utf16(mode, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005399 if (wn != NULL && wm != NULL)
5400 f = _wfopen(wn, wm);
5401 vim_free(wn);
5402 vim_free(wm);
Bram Moolenaar0fde2902008-03-16 13:54:13 +00005403
Bram Moolenaare6a91fd2008-07-24 18:51:11 +00005404# if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0fde2902008-03-16 13:54:13 +00005405 _set_fmode(oldMode);
5406# endif
5407
Bram Moolenaar071d4272004-06-13 20:20:40 +00005408 if (f != NULL)
5409 return f;
5410 /* Retry with non-wide function (for Windows 98). Can't use
5411 * GetLastError() here and it's unclear what errno gets set to if
5412 * the _wfopen() fails for missing wide functions. */
5413 }
5414
5415 return fopen(name, mode);
5416}
5417#endif
5418
5419#ifdef FEAT_MBYTE
5420/*
5421 * SUB STREAM (aka info stream) handling:
5422 *
5423 * NTFS can have sub streams for each file. Normal contents of file is
5424 * stored in the main stream, and extra contents (author information and
5425 * title and so on) can be stored in sub stream. After Windows 2000, user
5426 * can access and store those informations in sub streams via explorer's
5427 * property menuitem in right click menu. Those informations in sub streams
5428 * were lost when copying only the main stream. So we have to copy sub
5429 * streams.
5430 *
5431 * Incomplete explanation:
5432 * http://msdn.microsoft.com/library/en-us/dnw2k/html/ntfs5.asp
5433 * More useful info and an example:
5434 * http://www.sysinternals.com/ntw2k/source/misc.shtml#streams
5435 */
5436
5437/*
5438 * Copy info stream data "substream". Read from the file with BackupRead(sh)
5439 * and write to stream "substream" of file "to".
5440 * Errors are ignored.
5441 */
5442 static void
5443copy_substream(HANDLE sh, void *context, WCHAR *to, WCHAR *substream, long len)
5444{
5445 HANDLE hTo;
5446 WCHAR *to_name;
5447
5448 to_name = malloc((wcslen(to) + wcslen(substream) + 1) * sizeof(WCHAR));
5449 wcscpy(to_name, to);
5450 wcscat(to_name, substream);
5451
5452 hTo = CreateFileW(to_name, GENERIC_WRITE, 0, NULL, OPEN_ALWAYS,
5453 FILE_ATTRIBUTE_NORMAL, NULL);
5454 if (hTo != INVALID_HANDLE_VALUE)
5455 {
5456 long done;
5457 DWORD todo;
5458 DWORD readcnt, written;
5459 char buf[4096];
5460
5461 /* Copy block of bytes at a time. Abort when something goes wrong. */
5462 for (done = 0; done < len; done += written)
5463 {
5464 /* (size_t) cast for Borland C 5.5 */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005465 todo = (DWORD)((size_t)(len - done) > sizeof(buf) ? sizeof(buf)
5466 : (size_t)(len - done));
Bram Moolenaar071d4272004-06-13 20:20:40 +00005467 if (!BackupRead(sh, (LPBYTE)buf, todo, &readcnt,
5468 FALSE, FALSE, context)
5469 || readcnt != todo
5470 || !WriteFile(hTo, buf, todo, &written, NULL)
5471 || written != todo)
5472 break;
5473 }
5474 CloseHandle(hTo);
5475 }
5476
5477 free(to_name);
5478}
5479
5480/*
5481 * Copy info streams from file "from" to file "to".
5482 */
5483 static void
5484copy_infostreams(char_u *from, char_u *to)
5485{
5486 WCHAR *fromw;
5487 WCHAR *tow;
5488 HANDLE sh;
5489 WIN32_STREAM_ID sid;
5490 int headersize;
5491 WCHAR streamname[_MAX_PATH];
5492 DWORD readcount;
5493 void *context = NULL;
5494 DWORD lo, hi;
5495 int len;
5496
5497 /* Convert the file names to wide characters. */
Bram Moolenaar36f692d2008-11-20 16:10:17 +00005498 fromw = enc_to_utf16(from, NULL);
5499 tow = enc_to_utf16(to, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005500 if (fromw != NULL && tow != NULL)
5501 {
5502 /* Open the file for reading. */
5503 sh = CreateFileW(fromw, GENERIC_READ, FILE_SHARE_READ, NULL,
5504 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
5505 if (sh != INVALID_HANDLE_VALUE)
5506 {
5507 /* Use BackupRead() to find the info streams. Repeat until we
5508 * have done them all.*/
5509 for (;;)
5510 {
5511 /* Get the header to find the length of the stream name. If
5512 * the "readcount" is zero we have done all info streams. */
5513 ZeroMemory(&sid, sizeof(WIN32_STREAM_ID));
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005514 headersize = (int)((char *)&sid.cStreamName - (char *)&sid.dwStreamId);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005515 if (!BackupRead(sh, (LPBYTE)&sid, headersize,
5516 &readcount, FALSE, FALSE, &context)
5517 || readcount == 0)
5518 break;
5519
5520 /* We only deal with streams that have a name. The normal
5521 * file data appears to be without a name, even though docs
5522 * suggest it is called "::$DATA". */
5523 if (sid.dwStreamNameSize > 0)
5524 {
5525 /* Read the stream name. */
5526 if (!BackupRead(sh, (LPBYTE)streamname,
5527 sid.dwStreamNameSize,
5528 &readcount, FALSE, FALSE, &context))
5529 break;
5530
5531 /* Copy an info stream with a name ":anything:$DATA".
5532 * Skip "::$DATA", it has no stream name (examples suggest
5533 * it might be used for the normal file contents).
5534 * Note that BackupRead() counts bytes, but the name is in
5535 * wide characters. */
5536 len = readcount / sizeof(WCHAR);
5537 streamname[len] = 0;
5538 if (len > 7 && wcsicmp(streamname + len - 6,
5539 L":$DATA") == 0)
5540 {
5541 streamname[len - 6] = 0;
5542 copy_substream(sh, &context, tow, streamname,
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00005543 (long)sid.Size.u.LowPart);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005544 }
5545 }
5546
5547 /* Advance to the next stream. We might try seeking too far,
5548 * but BackupSeek() doesn't skip over stream borders, thus
5549 * that's OK. */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00005550 (void)BackupSeek(sh, sid.Size.u.LowPart, sid.Size.u.HighPart,
Bram Moolenaar071d4272004-06-13 20:20:40 +00005551 &lo, &hi, &context);
5552 }
5553
5554 /* Clear the context. */
5555 (void)BackupRead(sh, NULL, 0, &readcount, TRUE, FALSE, &context);
5556
5557 CloseHandle(sh);
5558 }
5559 }
5560 vim_free(fromw);
5561 vim_free(tow);
5562}
5563#endif
5564
5565/*
5566 * Copy file attributes from file "from" to file "to".
5567 * For Windows NT and later we copy info streams.
5568 * Always returns zero, errors are ignored.
5569 */
5570 int
5571mch_copy_file_attribute(char_u *from, char_u *to)
5572{
5573#ifdef FEAT_MBYTE
5574 /* File streams only work on Windows NT and later. */
5575 PlatformId();
5576 if (g_PlatformId == VER_PLATFORM_WIN32_NT)
5577 copy_infostreams(from, to);
5578#endif
5579 return 0;
5580}
5581
5582#if defined(MYRESETSTKOFLW) || defined(PROTO)
5583/*
5584 * Recreate a destroyed stack guard page in win32.
5585 * Written by Benjamin Peterson.
5586 */
5587
5588/* These magic numbers are from the MS header files */
5589#define MIN_STACK_WIN9X 17
5590#define MIN_STACK_WINNT 2
5591
5592/*
5593 * This function does the same thing as _resetstkoflw(), which is only
5594 * available in DevStudio .net and later.
5595 * Returns 0 for failure, 1 for success.
5596 */
5597 int
5598myresetstkoflw(void)
5599{
5600 BYTE *pStackPtr;
5601 BYTE *pGuardPage;
5602 BYTE *pStackBase;
5603 BYTE *pLowestPossiblePage;
5604 MEMORY_BASIC_INFORMATION mbi;
5605 SYSTEM_INFO si;
5606 DWORD nPageSize;
5607 DWORD dummy;
5608
5609 /* This code will not work on win32s. */
5610 PlatformId();
5611 if (g_PlatformId == VER_PLATFORM_WIN32s)
5612 return 0;
5613
5614 /* We need to know the system page size. */
5615 GetSystemInfo(&si);
5616 nPageSize = si.dwPageSize;
5617
5618 /* ...and the current stack pointer */
5619 pStackPtr = (BYTE*)_alloca(1);
5620
5621 /* ...and the base of the stack. */
5622 if (VirtualQuery(pStackPtr, &mbi, sizeof mbi) == 0)
5623 return 0;
5624 pStackBase = (BYTE*)mbi.AllocationBase;
5625
5626 /* ...and the page thats min_stack_req pages away from stack base; this is
5627 * the lowest page we could use. */
5628 pLowestPossiblePage = pStackBase + ((g_PlatformId == VER_PLATFORM_WIN32_NT)
5629 ? MIN_STACK_WINNT : MIN_STACK_WIN9X) * nPageSize;
5630
5631 /* On Win95, we want the next page down from the end of the stack. */
5632 if (g_PlatformId == VER_PLATFORM_WIN32_WINDOWS)
5633 {
5634 /* Find the page that's only 1 page down from the page that the stack
5635 * ptr is in. */
5636 pGuardPage = (BYTE*)((DWORD)nPageSize * (((DWORD)pStackPtr
5637 / (DWORD)nPageSize) - 1));
5638 if (pGuardPage < pLowestPossiblePage)
5639 return 0;
5640
5641 /* Apply the noaccess attribute to the page -- there's no guard
5642 * attribute in win95-type OSes. */
5643 if (!VirtualProtect(pGuardPage, nPageSize, PAGE_NOACCESS, &dummy))
5644 return 0;
5645 }
5646 else
5647 {
5648 /* On NT, however, we want the first committed page in the stack Start
5649 * at the stack base and move forward through memory until we find a
5650 * committed block. */
5651 BYTE *pBlock = pStackBase;
5652
Bram Moolenaara466c992005-07-09 21:03:22 +00005653 for (;;)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005654 {
5655 if (VirtualQuery(pBlock, &mbi, sizeof mbi) == 0)
5656 return 0;
5657
5658 pBlock += mbi.RegionSize;
5659
5660 if (mbi.State & MEM_COMMIT)
5661 break;
5662 }
5663
5664 /* mbi now describes the first committed block in the stack. */
5665 if (mbi.Protect & PAGE_GUARD)
5666 return 1;
5667
5668 /* decide where the guard page should start */
5669 if ((long_u)(mbi.BaseAddress) < (long_u)pLowestPossiblePage)
5670 pGuardPage = pLowestPossiblePage;
5671 else
5672 pGuardPage = (BYTE*)mbi.BaseAddress;
5673
5674 /* allocate the guard page */
5675 if (!VirtualAlloc(pGuardPage, nPageSize, MEM_COMMIT, PAGE_READWRITE))
5676 return 0;
5677
5678 /* apply the guard attribute to the page */
5679 if (!VirtualProtect(pGuardPage, nPageSize, PAGE_READWRITE | PAGE_GUARD,
5680 &dummy))
5681 return 0;
5682 }
5683
5684 return 1;
5685}
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005686#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005687
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005688
5689#if defined(FEAT_MBYTE) || defined(PROTO)
5690/*
5691 * The command line arguments in UCS2
5692 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00005693static int nArgsW = 0;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005694static LPWSTR *ArglistW = NULL;
5695static int global_argc = 0;
5696static char **global_argv;
5697
5698static int used_file_argc = 0; /* last argument in global_argv[] used
5699 for the argument list. */
5700static int *used_file_indexes = NULL; /* indexes in global_argv[] for
5701 command line arguments added to
5702 the argument list */
5703static int used_file_count = 0; /* nr of entries in used_file_indexes */
5704static int used_file_literal = FALSE; /* take file names literally */
5705static int used_file_full_path = FALSE; /* file name was full path */
Bram Moolenaar910f66f2006-04-05 20:41:53 +00005706static int used_file_diff_mode = FALSE; /* file name was with diff mode */
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005707static int used_alist_count = 0;
5708
5709
5710/*
5711 * Get the command line arguments. Unicode version.
5712 * Returns argc. Zero when something fails.
5713 */
5714 int
5715get_cmd_argsW(char ***argvp)
5716{
5717 char **argv = NULL;
5718 int argc = 0;
5719 int i;
5720
5721 ArglistW = CommandLineToArgvW(GetCommandLineW(), &nArgsW);
5722 if (ArglistW != NULL)
5723 {
5724 argv = malloc((nArgsW + 1) * sizeof(char *));
5725 if (argv != NULL)
5726 {
5727 argc = nArgsW;
5728 argv[argc] = NULL;
5729 for (i = 0; i < argc; ++i)
5730 {
5731 int len;
5732
5733 /* Convert each Unicode argument to the current codepage. */
5734 WideCharToMultiByte_alloc(GetACP(), 0,
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005735 ArglistW[i], (int)wcslen(ArglistW[i]) + 1,
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005736 (LPSTR *)&argv[i], &len, 0, 0);
5737 if (argv[i] == NULL)
5738 {
5739 /* Out of memory, clear everything. */
5740 while (i > 0)
5741 free(argv[--i]);
5742 free(argv);
5743 argc = 0;
5744 }
5745 }
5746 }
5747 }
5748
5749 global_argc = argc;
5750 global_argv = argv;
5751 if (argc > 0)
5752 used_file_indexes = malloc(argc * sizeof(int));
5753
5754 if (argvp != NULL)
5755 *argvp = argv;
5756 return argc;
5757}
5758
5759 void
5760free_cmd_argsW(void)
5761{
5762 if (ArglistW != NULL)
5763 {
5764 GlobalFree(ArglistW);
5765 ArglistW = NULL;
5766 }
5767}
5768
5769/*
5770 * Remember "name" is an argument that was added to the argument list.
5771 * This avoids that we have to re-parse the argument list when fix_arg_enc()
5772 * is called.
5773 */
5774 void
Bram Moolenaar910f66f2006-04-05 20:41:53 +00005775used_file_arg(char *name, int literal, int full_path, int diff_mode)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005776{
5777 int i;
5778
5779 if (used_file_indexes == NULL)
5780 return;
5781 for (i = used_file_argc + 1; i < global_argc; ++i)
5782 if (STRCMP(global_argv[i], name) == 0)
5783 {
5784 used_file_argc = i;
5785 used_file_indexes[used_file_count++] = i;
5786 break;
5787 }
5788 used_file_literal = literal;
5789 used_file_full_path = full_path;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00005790 used_file_diff_mode = diff_mode;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005791}
5792
5793/*
5794 * Remember the length of the argument list as it was. If it changes then we
5795 * leave it alone when 'encoding' is set.
5796 */
5797 void
5798set_alist_count(void)
5799{
5800 used_alist_count = GARGCOUNT;
5801}
5802
5803/*
5804 * Fix the encoding of the command line arguments. Invoked when 'encoding'
5805 * has been changed while starting up. Use the UCS-2 command line arguments
5806 * and convert them to 'encoding'.
5807 */
5808 void
5809fix_arg_enc(void)
5810{
5811 int i;
5812 int idx;
5813 char_u *str;
Bram Moolenaar86b68352004-12-27 21:59:20 +00005814 int *fnum_list;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005815
5816 /* Safety checks:
5817 * - if argument count differs between the wide and non-wide argument
5818 * list, something must be wrong.
5819 * - the file name arguments must have been located.
5820 * - the length of the argument list wasn't changed by the user.
5821 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00005822 if (global_argc != nArgsW
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005823 || ArglistW == NULL
5824 || used_file_indexes == NULL
5825 || used_file_count == 0
5826 || used_alist_count != GARGCOUNT)
5827 return;
5828
Bram Moolenaar86b68352004-12-27 21:59:20 +00005829 /* Remember the buffer numbers for the arguments. */
5830 fnum_list = (int *)alloc((int)sizeof(int) * GARGCOUNT);
5831 if (fnum_list == NULL)
5832 return; /* out of memory */
5833 for (i = 0; i < GARGCOUNT; ++i)
5834 fnum_list[i] = GARGLIST[i].ae_fnum;
5835
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005836 /* Clear the argument list. Make room for the new arguments. */
5837 alist_clear(&global_alist);
5838 if (ga_grow(&global_alist.al_ga, used_file_count) == FAIL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00005839 return; /* out of memory */
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005840
5841 for (i = 0; i < used_file_count; ++i)
5842 {
5843 idx = used_file_indexes[i];
Bram Moolenaar36f692d2008-11-20 16:10:17 +00005844 str = utf16_to_enc(ArglistW[idx], NULL);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005845 if (str != NULL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00005846 {
Bram Moolenaar910f66f2006-04-05 20:41:53 +00005847#ifdef FEAT_DIFF
5848 /* When using diff mode may need to concatenate file name to
5849 * directory name. Just like it's done in main(). */
5850 if (used_file_diff_mode && mch_isdir(str) && GARGCOUNT > 0
5851 && !mch_isdir(alist_name(&GARGLIST[0])))
5852 {
5853 char_u *r;
5854
5855 r = concat_fnames(str, gettail(alist_name(&GARGLIST[0])), TRUE);
5856 if (r != NULL)
5857 {
5858 vim_free(str);
5859 str = r;
5860 }
5861 }
5862#endif
Bram Moolenaar86b68352004-12-27 21:59:20 +00005863 /* Re-use the old buffer by renaming it. When not using literal
5864 * names it's done by alist_expand() below. */
5865 if (used_file_literal)
5866 buf_set_name(fnum_list[i], str);
5867
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005868 alist_add(&global_alist, str, used_file_literal ? 2 : 0);
Bram Moolenaar86b68352004-12-27 21:59:20 +00005869 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005870 }
5871
5872 if (!used_file_literal)
5873 {
5874 /* Now expand wildcards in the arguments. */
5875 /* Temporarily add '(' and ')' to 'isfname'. These are valid
5876 * filename characters but are excluded from 'isfname' to make
5877 * "gf" work on a file name in parenthesis (e.g.: see vim.h). */
5878 do_cmdline_cmd((char_u *)":let SaVe_ISF = &isf|set isf+=(,)");
Bram Moolenaar86b68352004-12-27 21:59:20 +00005879 alist_expand(fnum_list, used_alist_count);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005880 do_cmdline_cmd((char_u *)":let &isf = SaVe_ISF|unlet SaVe_ISF");
5881 }
5882
5883 /* If wildcard expansion failed, we are editing the first file of the
5884 * arglist and there is no file name: Edit the first argument now. */
5885 if (curwin->w_arg_idx == 0 && curbuf->b_fname == NULL)
5886 {
5887 do_cmdline_cmd((char_u *)":rewind");
5888 if (GARGCOUNT == 1 && used_file_full_path)
5889 (void)vim_chdirfile(alist_name(&GARGLIST[0]));
5890 }
Bram Moolenaar86b68352004-12-27 21:59:20 +00005891
5892 set_alist_count();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005893}
Bram Moolenaar071d4272004-06-13 20:20:40 +00005894#endif