blob: 8151e6054aee191a64e3a9e8fe7501b37a43fbeb [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
Bram Moolenaarf6a2b082012-06-29 13:14:03 +0200311/* Dummy functions */
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/*
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02001412 * mch_inchar(): low-level input function.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001413 * 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 Moolenaare4195c52012-08-02 12:31:44 +02003322 delay = 1;
3323 continue;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003324 }
3325 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
3326 break;
3327
3328 /* We start waiting for a very short time and then increase it, so
3329 * that we respond quickly when the process is quick, and don't
3330 * consume too much overhead when it's slow. */
3331 if (delay < 50)
3332 delay += 10;
3333 }
3334#else
3335 WaitForSingleObject(pi.hProcess, INFINITE);
3336#endif
3337
3338 /* Get the command exit code */
3339 GetExitCodeProcess(pi.hProcess, &ret);
3340 }
3341 else
3342 {
3343 /*
3344 * This ugly code is the only quick way of performing
3345 * a synchronous spawn under Win32s. Yuk.
3346 */
3347 num_windows = 0;
3348 EnumWindows(win32ssynch_cb, 0);
3349 old_num_windows = num_windows;
3350 do
3351 {
3352 Sleep(1000);
3353 num_windows = 0;
3354 EnumWindows(win32ssynch_cb, 0);
3355 } while (num_windows == old_num_windows);
3356 ret = 0;
3357 }
3358
3359 /* Close the handles to the subprocess, so that it goes away */
3360 CloseHandle(pi.hThread);
3361 CloseHandle(pi.hProcess);
3362
3363 /* Try to get input focus back. Doesn't always work though. */
3364 PostMessage(hwnd, WM_SETFOCUS, 0, 0);
3365
3366 return ret;
3367}
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02003368
3369/*
3370 * Thread launched by the gui to send the current buffer data to the
3371 * process. This way avoid to hang up vim totally if the children
3372 * process take a long time to process the lines.
3373 */
3374 static DWORD WINAPI
3375sub_process_writer(LPVOID param)
3376{
3377 HANDLE g_hChildStd_IN_Wr = param;
3378 linenr_T lnum = curbuf->b_op_start.lnum;
3379 DWORD len = 0;
3380 DWORD l;
3381 char_u *lp = ml_get(lnum);
3382 char_u *s;
3383 int written = 0;
3384
3385 for (;;)
3386 {
3387 l = (DWORD)STRLEN(lp + written);
3388 if (l == 0)
3389 len = 0;
3390 else if (lp[written] == NL)
3391 {
3392 /* NL -> NUL translation */
3393 WriteFile(g_hChildStd_IN_Wr, "", 1, &len, NULL);
3394 }
3395 else
3396 {
3397 s = vim_strchr(lp + written, NL);
3398 WriteFile(g_hChildStd_IN_Wr, (char *)lp + written,
3399 s == NULL ? l : (DWORD)(s - (lp + written)),
3400 &len, NULL);
3401 }
3402 if (len == (int)l)
3403 {
3404 /* Finished a line, add a NL, unless this line should not have
3405 * one. */
3406 if (lnum != curbuf->b_op_end.lnum
3407 || !curbuf->b_p_bin
3408 || (lnum != curbuf->b_no_eol_lnum
3409 && (lnum != curbuf->b_ml.ml_line_count
3410 || curbuf->b_p_eol)))
3411 {
3412 WriteFile(g_hChildStd_IN_Wr, "\n", 1, &ignored, NULL);
3413 }
3414
3415 ++lnum;
3416 if (lnum > curbuf->b_op_end.lnum)
3417 break;
3418
3419 lp = ml_get(lnum);
3420 written = 0;
3421 }
3422 else if (len > 0)
3423 written += len;
3424 }
3425
3426 /* finished all the lines, close pipe */
3427 CloseHandle(g_hChildStd_IN_Wr);
3428 ExitThread(0);
3429}
3430
3431
3432# define BUFLEN 100 /* length for buffer, stolen from unix version */
3433
3434/*
3435 * This function read from the children's stdout and write the
3436 * data on screen or in the buffer accordingly.
3437 */
3438 static void
3439dump_pipe(int options,
3440 HANDLE g_hChildStd_OUT_Rd,
3441 garray_T *ga,
3442 char_u buffer[],
3443 DWORD *buffer_off)
3444{
3445 DWORD availableBytes = 0;
3446 DWORD i;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02003447 int ret;
3448 DWORD len;
3449 DWORD toRead;
3450 int repeatCount;
3451
3452 /* we query the pipe to see if there is any data to read
3453 * to avoid to perform a blocking read */
3454 ret = PeekNamedPipe(g_hChildStd_OUT_Rd, /* pipe to query */
3455 NULL, /* optional buffer */
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02003456 0, /* buffer size */
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02003457 NULL, /* number of read bytes */
3458 &availableBytes, /* available bytes total */
3459 NULL); /* byteLeft */
3460
3461 repeatCount = 0;
3462 /* We got real data in the pipe, read it */
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02003463 while (ret != 0 && availableBytes > 0)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02003464 {
3465 repeatCount++;
3466 toRead =
3467# ifdef FEAT_MBYTE
3468 (DWORD)(BUFLEN - *buffer_off);
3469# else
3470 (DWORD)BUFLEN;
3471# endif
3472 toRead = availableBytes < toRead ? availableBytes : toRead;
3473 ReadFile(g_hChildStd_OUT_Rd, buffer
3474# ifdef FEAT_MBYTE
3475 + *buffer_off, toRead
3476# else
3477 , toRead
3478# endif
3479 , &len, NULL);
3480
3481 /* If we haven't read anything, there is a problem */
3482 if (len == 0)
3483 break;
3484
3485 availableBytes -= len;
3486
3487 if (options & SHELL_READ)
3488 {
3489 /* Do NUL -> NL translation, append NL separated
3490 * lines to the current buffer. */
3491 for (i = 0; i < len; ++i)
3492 {
3493 if (buffer[i] == NL)
3494 append_ga_line(ga);
3495 else if (buffer[i] == NUL)
3496 ga_append(ga, NL);
3497 else
3498 ga_append(ga, buffer[i]);
3499 }
3500 }
3501# ifdef FEAT_MBYTE
3502 else if (has_mbyte)
3503 {
3504 int l;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02003505 int c;
3506 char_u *p;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02003507
3508 len += *buffer_off;
3509 buffer[len] = NUL;
3510
3511 /* Check if the last character in buffer[] is
3512 * incomplete, keep these bytes for the next
3513 * round. */
3514 for (p = buffer; p < buffer + len; p += l)
3515 {
3516 l = mb_cptr2len(p);
3517 if (l == 0)
3518 l = 1; /* NUL byte? */
3519 else if (MB_BYTE2LEN(*p) != l)
3520 break;
3521 }
3522 if (p == buffer) /* no complete character */
3523 {
3524 /* avoid getting stuck at an illegal byte */
3525 if (len >= 12)
3526 ++p;
3527 else
3528 {
3529 *buffer_off = len;
3530 return;
3531 }
3532 }
3533 c = *p;
3534 *p = NUL;
3535 msg_puts(buffer);
3536 if (p < buffer + len)
3537 {
3538 *p = c;
3539 *buffer_off = (DWORD)((buffer + len) - p);
3540 mch_memmove(buffer, p, *buffer_off);
3541 return;
3542 }
3543 *buffer_off = 0;
3544 }
3545# endif /* FEAT_MBYTE */
3546 else
3547 {
3548 buffer[len] = NUL;
3549 msg_puts(buffer);
3550 }
3551
3552 windgoto(msg_row, msg_col);
3553 cursor_on();
3554 out_flush();
3555 }
3556}
3557
3558/*
3559 * Version of system to use for windows NT > 5.0 (Win2K), use pipe
3560 * for communication and doesn't open any new window.
3561 */
3562 static int
3563mch_system_piped(char *cmd, int options)
3564{
3565 STARTUPINFO si;
3566 PROCESS_INFORMATION pi;
3567 DWORD ret = 0;
3568
3569 HANDLE g_hChildStd_IN_Rd = NULL;
3570 HANDLE g_hChildStd_IN_Wr = NULL;
3571 HANDLE g_hChildStd_OUT_Rd = NULL;
3572 HANDLE g_hChildStd_OUT_Wr = NULL;
3573
3574 char_u buffer[BUFLEN + 1]; /* reading buffer + size */
3575 DWORD len;
3576
3577 /* buffer used to receive keys */
3578 char_u ta_buf[BUFLEN + 1]; /* TypeAHead */
3579 int ta_len = 0; /* valid bytes in ta_buf[] */
3580
3581 DWORD i;
3582 int c;
3583 int noread_cnt = 0;
3584 garray_T ga;
3585 int delay = 1;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02003586 DWORD buffer_off = 0; /* valid bytes in buffer[] */
Bram Moolenaar6b707b42012-02-21 21:22:44 +01003587 char *p = NULL;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02003588
3589 SECURITY_ATTRIBUTES saAttr;
3590
3591 /* Set the bInheritHandle flag so pipe handles are inherited. */
3592 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
3593 saAttr.bInheritHandle = TRUE;
3594 saAttr.lpSecurityDescriptor = NULL;
3595
3596 if ( ! CreatePipe(&g_hChildStd_OUT_Rd, &g_hChildStd_OUT_Wr, &saAttr, 0)
3597 /* Ensure the read handle to the pipe for STDOUT is not inherited. */
3598 || ! pSetHandleInformation(g_hChildStd_OUT_Rd, HANDLE_FLAG_INHERIT, 0)
3599 /* Create a pipe for the child process's STDIN. */
3600 || ! CreatePipe(&g_hChildStd_IN_Rd, &g_hChildStd_IN_Wr, &saAttr, 0)
3601 /* Ensure the write handle to the pipe for STDIN is not inherited. */
3602 || ! pSetHandleInformation(g_hChildStd_IN_Wr, HANDLE_FLAG_INHERIT, 0) )
3603 {
3604 CloseHandle(g_hChildStd_IN_Rd);
3605 CloseHandle(g_hChildStd_IN_Wr);
3606 CloseHandle(g_hChildStd_OUT_Rd);
3607 CloseHandle(g_hChildStd_OUT_Wr);
3608 MSG_PUTS(_("\nCannot create pipes\n"));
3609 }
3610
3611 si.cb = sizeof(si);
3612 si.lpReserved = NULL;
3613 si.lpDesktop = NULL;
3614 si.lpTitle = NULL;
3615 si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
3616
3617 /* set-up our file redirection */
3618 si.hStdError = g_hChildStd_OUT_Wr;
3619 si.hStdOutput = g_hChildStd_OUT_Wr;
3620 si.hStdInput = g_hChildStd_IN_Rd;
3621 si.wShowWindow = SW_HIDE;
3622 si.cbReserved2 = 0;
3623 si.lpReserved2 = NULL;
3624
3625 if (options & SHELL_READ)
3626 ga_init2(&ga, 1, BUFLEN);
3627
Bram Moolenaar6b707b42012-02-21 21:22:44 +01003628 if (cmd != NULL)
3629 {
3630 p = (char *)vim_strsave((char_u *)cmd);
3631 if (p != NULL)
3632 unescape_shellxquote((char_u *)p, p_sxe);
3633 else
3634 p = cmd;
3635 }
3636
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02003637 /* Now, run the command */
3638 CreateProcess(NULL, /* Executable name */
Bram Moolenaar6b707b42012-02-21 21:22:44 +01003639 p, /* Command to execute */
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02003640 NULL, /* Process security attributes */
3641 NULL, /* Thread security attributes */
3642
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02003643 // this command can be litigious, handle inheritance was
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02003644 // deactivated for pending temp file, but, if we deactivate
3645 // it, the pipes don't work for some reason.
3646 TRUE, /* Inherit handles, first deactivated,
3647 * but needed */
3648 CREATE_DEFAULT_ERROR_MODE, /* Creation flags */
3649 NULL, /* Environment */
3650 NULL, /* Current directory */
3651 &si, /* Startup information */
3652 &pi); /* Process information */
3653
Bram Moolenaar6b707b42012-02-21 21:22:44 +01003654 if (p != cmd)
3655 vim_free(p);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02003656
3657 /* Close our unused side of the pipes */
3658 CloseHandle(g_hChildStd_IN_Rd);
3659 CloseHandle(g_hChildStd_OUT_Wr);
3660
3661 if (options & SHELL_WRITE)
3662 {
3663 HANDLE thread =
3664 CreateThread(NULL, /* security attributes */
3665 0, /* default stack size */
3666 sub_process_writer, /* function to be executed */
3667 g_hChildStd_IN_Wr, /* parameter */
3668 0, /* creation flag, start immediately */
3669 NULL); /* we don't care about thread id */
3670 CloseHandle(thread);
3671 g_hChildStd_IN_Wr = NULL;
3672 }
3673
3674 /* Keep updating the window while waiting for the shell to finish. */
3675 for (;;)
3676 {
3677 MSG msg;
3678
3679 if (PeekMessage(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
3680 {
3681 TranslateMessage(&msg);
3682 DispatchMessage(&msg);
3683 }
3684
3685 /* write pipe information in the window */
3686 if ((options & (SHELL_READ|SHELL_WRITE))
3687# ifdef FEAT_GUI
3688 || gui.in_use
3689# endif
3690 )
3691 {
3692 len = 0;
3693 if (!(options & SHELL_EXPAND)
3694 && ((options &
3695 (SHELL_READ|SHELL_WRITE|SHELL_COOKED))
3696 != (SHELL_READ|SHELL_WRITE|SHELL_COOKED)
3697# ifdef FEAT_GUI
3698 || gui.in_use
3699# endif
3700 )
3701 && (ta_len > 0 || noread_cnt > 4))
3702 {
3703 if (ta_len == 0)
3704 {
3705 /* Get extra characters when we don't have any. Reset the
3706 * counter and timer. */
3707 noread_cnt = 0;
3708# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
3709 gettimeofday(&start_tv, NULL);
3710# endif
3711 len = ui_inchar(ta_buf, BUFLEN, 10L, 0);
3712 }
3713 if (ta_len > 0 || len > 0)
3714 {
3715 /*
3716 * For pipes: Check for CTRL-C: send interrupt signal to
3717 * child. Check for CTRL-D: EOF, close pipe to child.
3718 */
3719 if (len == 1 && cmd != NULL)
3720 {
3721 if (ta_buf[ta_len] == Ctrl_C)
3722 {
3723 /* Learn what exit code is expected, for
3724 * now put 9 as SIGKILL */
3725 TerminateProcess(pi.hProcess, 9);
3726 }
3727 if (ta_buf[ta_len] == Ctrl_D)
3728 {
3729 CloseHandle(g_hChildStd_IN_Wr);
3730 g_hChildStd_IN_Wr = NULL;
3731 }
3732 }
3733
3734 /* replace K_BS by <BS> and K_DEL by <DEL> */
3735 for (i = ta_len; i < ta_len + len; ++i)
3736 {
3737 if (ta_buf[i] == CSI && len - i > 2)
3738 {
3739 c = TERMCAP2KEY(ta_buf[i + 1], ta_buf[i + 2]);
3740 if (c == K_DEL || c == K_KDEL || c == K_BS)
3741 {
3742 mch_memmove(ta_buf + i + 1, ta_buf + i + 3,
3743 (size_t)(len - i - 2));
3744 if (c == K_DEL || c == K_KDEL)
3745 ta_buf[i] = DEL;
3746 else
3747 ta_buf[i] = Ctrl_H;
3748 len -= 2;
3749 }
3750 }
3751 else if (ta_buf[i] == '\r')
3752 ta_buf[i] = '\n';
3753# ifdef FEAT_MBYTE
3754 if (has_mbyte)
3755 i += (*mb_ptr2len_len)(ta_buf + i,
3756 ta_len + len - i) - 1;
3757# endif
3758 }
3759
3760 /*
3761 * For pipes: echo the typed characters. For a pty this
3762 * does not seem to work.
3763 */
3764 for (i = ta_len; i < ta_len + len; ++i)
3765 {
3766 if (ta_buf[i] == '\n' || ta_buf[i] == '\b')
3767 msg_putchar(ta_buf[i]);
3768# ifdef FEAT_MBYTE
3769 else if (has_mbyte)
3770 {
3771 int l = (*mb_ptr2len)(ta_buf + i);
3772
3773 msg_outtrans_len(ta_buf + i, l);
3774 i += l - 1;
3775 }
3776# endif
3777 else
3778 msg_outtrans_len(ta_buf + i, 1);
3779 }
3780 windgoto(msg_row, msg_col);
3781 out_flush();
3782
3783 ta_len += len;
3784
3785 /*
3786 * Write the characters to the child, unless EOF has been
3787 * typed for pipes. Write one character at a time, to
3788 * avoid losing too much typeahead. When writing buffer
3789 * lines, drop the typed characters (only check for
3790 * CTRL-C).
3791 */
3792 if (options & SHELL_WRITE)
3793 ta_len = 0;
3794 else if (g_hChildStd_IN_Wr != NULL)
3795 {
3796 WriteFile(g_hChildStd_IN_Wr, (char*)ta_buf,
3797 1, &len, NULL);
3798 // if we are typing in, we want to keep things reactive
3799 delay = 1;
3800 if (len > 0)
3801 {
3802 ta_len -= len;
3803 mch_memmove(ta_buf, ta_buf + len, ta_len);
3804 }
3805 }
3806 }
3807 }
3808 }
3809
3810 if (ta_len)
3811 ui_inchar_undo(ta_buf, ta_len);
3812
3813 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
3814 {
Bram Moolenaar2eba1822011-08-27 15:10:04 +02003815 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02003816 break;
3817 }
3818
3819 ++noread_cnt;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02003820 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02003821
3822 /* We start waiting for a very short time and then increase it, so
3823 * that we respond quickly when the process is quick, and don't
3824 * consume too much overhead when it's slow. */
3825 if (delay < 50)
3826 delay += 10;
3827 }
3828
3829 /* Close the pipe */
3830 CloseHandle(g_hChildStd_OUT_Rd);
3831 if (g_hChildStd_IN_Wr != NULL)
3832 CloseHandle(g_hChildStd_IN_Wr);
3833
3834 WaitForSingleObject(pi.hProcess, INFINITE);
3835
3836 /* Get the command exit code */
3837 GetExitCodeProcess(pi.hProcess, &ret);
3838
3839 if (options & SHELL_READ)
3840 {
3841 if (ga.ga_len > 0)
3842 {
3843 append_ga_line(&ga);
3844 /* remember that the NL was missing */
3845 curbuf->b_no_eol_lnum = curwin->w_cursor.lnum;
3846 }
3847 else
3848 curbuf->b_no_eol_lnum = 0;
3849 ga_clear(&ga);
3850 }
3851
3852 /* Close the handles to the subprocess, so that it goes away */
3853 CloseHandle(pi.hThread);
3854 CloseHandle(pi.hProcess);
3855
3856 return ret;
3857}
3858
3859 static int
3860mch_system(char *cmd, int options)
3861{
3862 /* if we can pipe and the shelltemp option is off */
3863 if (allowPiping && !p_stmp)
3864 return mch_system_piped(cmd, options);
3865 else
3866 return mch_system_classic(cmd, options);
3867}
Bram Moolenaar071d4272004-06-13 20:20:40 +00003868#else
3869
3870# define mch_system(c, o) system(c)
3871
3872#endif
3873
3874/*
3875 * Either execute a command by calling the shell or start a new shell
3876 */
3877 int
3878mch_call_shell(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003879 char_u *cmd,
3880 int options) /* SHELL_*, see vim.h */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003881{
3882 int x = 0;
3883 int tmode = cur_tmode;
3884#ifdef FEAT_TITLE
3885 char szShellTitle[512];
3886
3887 /* Change the title to reflect that we are in a subshell. */
3888 if (GetConsoleTitle(szShellTitle, sizeof(szShellTitle) - 4) > 0)
3889 {
3890 if (cmd == NULL)
3891 strcat(szShellTitle, " :sh");
3892 else
3893 {
3894 strcat(szShellTitle, " - !");
3895 if ((strlen(szShellTitle) + strlen(cmd) < sizeof(szShellTitle)))
3896 strcat(szShellTitle, cmd);
3897 }
3898 mch_settitle(szShellTitle, NULL);
3899 }
3900#endif
3901
3902 out_flush();
3903
3904#ifdef MCH_WRITE_DUMP
3905 if (fdDump)
3906 {
3907 fprintf(fdDump, "mch_call_shell(\"%s\", %d)\n", cmd, options);
3908 fflush(fdDump);
3909 }
3910#endif
3911
3912 /*
3913 * Catch all deadly signals while running the external command, because a
3914 * CTRL-C, Ctrl-Break or illegal instruction might otherwise kill us.
3915 */
3916 signal(SIGINT, SIG_IGN);
3917#if defined(__GNUC__) && !defined(__MINGW32__)
3918 signal(SIGKILL, SIG_IGN);
3919#else
3920 signal(SIGBREAK, SIG_IGN);
3921#endif
3922 signal(SIGILL, SIG_IGN);
3923 signal(SIGFPE, SIG_IGN);
3924 signal(SIGSEGV, SIG_IGN);
3925 signal(SIGTERM, SIG_IGN);
3926 signal(SIGABRT, SIG_IGN);
3927
3928 if (options & SHELL_COOKED)
3929 settmode(TMODE_COOK); /* set to normal mode */
3930
3931 if (cmd == NULL)
3932 {
3933 x = mch_system(p_sh, options);
3934 }
3935 else
3936 {
3937 /* we use "command" or "cmd" to start the shell; slow but easy */
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01003938 char_u *newcmd = NULL;
3939 char_u *cmdbase = cmd;
3940 long_u cmdlen;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01003941
3942 /* Skip a leading ", ( and "(. */
3943 if (*cmdbase == '"' )
3944 ++cmdbase;
3945 if (*cmdbase == '(')
3946 ++cmdbase;
3947
3948 if ((STRNICMP(cmdbase, "start", 5) == 0) && vim_iswhite(cmdbase[5]))
3949 {
3950 STARTUPINFO si;
3951 PROCESS_INFORMATION pi;
3952 DWORD flags = CREATE_NEW_CONSOLE;
3953 char_u *p;
3954
3955 si.cb = sizeof(si);
3956 si.lpReserved = NULL;
3957 si.lpDesktop = NULL;
3958 si.lpTitle = NULL;
3959 si.dwFlags = 0;
3960 si.cbReserved2 = 0;
3961 si.lpReserved2 = NULL;
3962
3963 cmdbase = skipwhite(cmdbase + 5);
3964 if ((STRNICMP(cmdbase, "/min", 4) == 0)
3965 && vim_iswhite(cmdbase[4]))
3966 {
3967 cmdbase = skipwhite(cmdbase + 4);
3968 si.dwFlags = STARTF_USESHOWWINDOW;
3969 si.wShowWindow = SW_SHOWMINNOACTIVE;
3970 }
3971 else if ((STRNICMP(cmdbase, "/b", 2) == 0)
3972 && vim_iswhite(cmdbase[2]))
3973 {
3974 cmdbase = skipwhite(cmdbase + 2);
3975 flags = CREATE_NO_WINDOW;
3976 si.dwFlags = STARTF_USESTDHANDLES;
3977 si.hStdInput = CreateFile("\\\\.\\NUL", // File name
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01003978 GENERIC_READ, // Access flags
Bram Moolenaar6b707b42012-02-21 21:22:44 +01003979 0, // Share flags
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01003980 NULL, // Security att.
3981 OPEN_EXISTING, // Open flags
3982 FILE_ATTRIBUTE_NORMAL, // File att.
3983 NULL); // Temp file
Bram Moolenaar6b707b42012-02-21 21:22:44 +01003984 si.hStdOutput = si.hStdInput;
3985 si.hStdError = si.hStdInput;
3986 }
3987
3988 /* Remove a trailing ", ) and )" if they have a match
3989 * at the start of the command. */
3990 if (cmdbase > cmd)
3991 {
3992 p = cmdbase + STRLEN(cmdbase);
3993 if (p > cmdbase && p[-1] == '"' && *cmd == '"')
3994 *--p = NUL;
3995 if (p > cmdbase && p[-1] == ')'
3996 && (*cmd =='(' || cmd[1] == '('))
3997 *--p = NUL;
3998 }
3999
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004000 newcmd = cmdbase;
4001 unescape_shellxquote(cmdbase, p_sxe);
4002
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004003 /*
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004004 * If creating new console, arguments are passed to the
4005 * 'cmd.exe' as-is. If it's not, arguments are not treated
4006 * correctly for current 'cmd.exe'. So unescape characters in
4007 * shellxescape except '|' for avoiding to be treated as
4008 * argument to them. Pass the arguments to sub-shell.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004009 */
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004010 if (flags != CREATE_NEW_CONSOLE)
4011 {
4012 char_u *subcmd;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004013 char_u *cmd_shell = mch_getenv("COMSPEC");
4014
4015 if (cmd_shell == NULL || *cmd_shell == NUL)
4016 cmd_shell = default_shell();
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004017
4018 subcmd = vim_strsave_escaped_ext(cmdbase, "|", '^', FALSE);
4019 if (subcmd != NULL)
4020 {
4021 /* make "cmd.exe /c arguments" */
4022 cmdlen = STRLEN(cmd_shell) + STRLEN(subcmd) + 5;
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004023 newcmd = lalloc(cmdlen, TRUE);
4024 if (newcmd != NULL)
4025 vim_snprintf((char *)newcmd, cmdlen, "%s /c %s",
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004026 cmd_shell, subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004027 else
4028 newcmd = cmdbase;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004029 vim_free(subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004030 }
4031 }
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004032
4033 /*
4034 * Now, start the command as a process, so that it doesn't
4035 * inherit our handles which causes unpleasant dangling swap
4036 * files if we exit before the spawned process
4037 */
4038 if (CreateProcess(NULL, // Executable name
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004039 newcmd, // Command to execute
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004040 NULL, // Process security attributes
4041 NULL, // Thread security attributes
4042 FALSE, // Inherit handles
4043 flags, // Creation flags
4044 NULL, // Environment
4045 NULL, // Current directory
4046 &si, // Startup information
4047 &pi)) // Process information
4048 x = 0;
4049 else
4050 {
4051 x = -1;
4052#ifdef FEAT_GUI_W32
4053 EMSG(_("E371: Command not found"));
4054#endif
4055 }
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004056
4057 if (newcmd != cmdbase)
4058 vim_free(newcmd);
4059
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004060 if (si.hStdInput != NULL)
4061 {
4062 /* Close the handle to \\.\NUL */
4063 CloseHandle(si.hStdInput);
4064 }
4065 /* Close the handles to the subprocess, so that it goes away */
4066 CloseHandle(pi.hThread);
4067 CloseHandle(pi.hProcess);
4068 }
4069 else
4070 {
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004071 cmdlen = (
Bram Moolenaar071d4272004-06-13 20:20:40 +00004072#ifdef FEAT_GUI_W32
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004073 (allowPiping && !p_stmp ? 0 : STRLEN(vimrun_path)) +
Bram Moolenaar071d4272004-06-13 20:20:40 +00004074#endif
Bram Moolenaar0fde2902008-03-16 13:54:13 +00004075 STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10);
4076
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004077 newcmd = lalloc(cmdlen, TRUE);
4078 if (newcmd != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004079 {
4080#if defined(FEAT_GUI_W32)
4081 if (need_vimrun_warning)
4082 {
4083 MessageBox(NULL,
4084 _("VIMRUN.EXE not found in your $PATH.\n"
4085 "External commands will not pause after completion.\n"
4086 "See :help win32-vimrun for more information."),
4087 _("Vim Warning"),
4088 MB_ICONWARNING);
4089 need_vimrun_warning = FALSE;
4090 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004091 if (!s_dont_use_vimrun && (!allowPiping || p_stmp))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004092 /* Use vimrun to execute the command. It opens a console
4093 * window, which can be closed without killing Vim. */
Bram Moolenaarcc448b32010-07-14 16:52:17 +02004094 vim_snprintf((char *)newcmd, cmdlen, "%s%s%s %s %s",
Bram Moolenaar071d4272004-06-13 20:20:40 +00004095 vimrun_path,
4096 (msg_silent != 0 || (options & SHELL_DOOUT))
4097 ? "-s " : "",
4098 p_sh, p_shcf, cmd);
4099 else
4100#endif
Bram Moolenaarcc448b32010-07-14 16:52:17 +02004101 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s",
Bram Moolenaar0fde2902008-03-16 13:54:13 +00004102 p_sh, p_shcf, cmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004103 x = mch_system((char *)newcmd, options);
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004104 vim_free(newcmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004105 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004106 }
4107 }
4108
4109 if (tmode == TMODE_RAW)
4110 settmode(TMODE_RAW); /* set to raw mode */
4111
4112 /* Print the return value, unless "vimrun" was used. */
4113 if (x != 0 && !(options & SHELL_SILENT) && !emsg_silent
4114#if defined(FEAT_GUI_W32)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004115 && ((options & SHELL_DOOUT) || s_dont_use_vimrun
4116 || (allowPiping && !p_stmp))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004117#endif
4118 )
4119 {
4120 smsg(_("shell returned %d"), x);
4121 msg_putchar('\n');
4122 }
4123#ifdef FEAT_TITLE
4124 resettitle();
4125#endif
4126
4127 signal(SIGINT, SIG_DFL);
4128#if defined(__GNUC__) && !defined(__MINGW32__)
4129 signal(SIGKILL, SIG_DFL);
4130#else
4131 signal(SIGBREAK, SIG_DFL);
4132#endif
4133 signal(SIGILL, SIG_DFL);
4134 signal(SIGFPE, SIG_DFL);
4135 signal(SIGSEGV, SIG_DFL);
4136 signal(SIGTERM, SIG_DFL);
4137 signal(SIGABRT, SIG_DFL);
4138
4139 return x;
4140}
4141
4142
4143#ifndef FEAT_GUI_W32
4144
4145/*
4146 * Start termcap mode
4147 */
4148 static void
4149termcap_mode_start(void)
4150{
4151 DWORD cmodein;
4152
4153 if (g_fTermcapMode)
4154 return;
4155
4156 SaveConsoleBuffer(&g_cbNonTermcap);
4157
4158 if (g_cbTermcap.IsValid)
4159 {
4160 /*
4161 * We've been in termcap mode before. Restore certain screen
4162 * characteristics, including the buffer size and the window
4163 * size. Since we will be redrawing the screen, we don't need
4164 * to restore the actual contents of the buffer.
4165 */
4166 RestoreConsoleBuffer(&g_cbTermcap, FALSE);
4167 SetConsoleWindowInfo(g_hConOut, TRUE, &g_cbTermcap.Info.srWindow);
4168 Rows = g_cbTermcap.Info.dwSize.Y;
4169 Columns = g_cbTermcap.Info.dwSize.X;
4170 }
4171 else
4172 {
4173 /*
4174 * This is our first time entering termcap mode. Clear the console
4175 * screen buffer, and resize the buffer to match the current window
4176 * size. We will use this as the size of our editing environment.
4177 */
4178 ClearConsoleBuffer(g_attrCurrent);
4179 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
4180 }
4181
4182#ifdef FEAT_TITLE
4183 resettitle();
4184#endif
4185
4186 GetConsoleMode(g_hConIn, &cmodein);
4187#ifdef FEAT_MOUSE
4188 if (g_fMouseActive)
4189 cmodein |= ENABLE_MOUSE_INPUT;
4190 else
4191 cmodein &= ~ENABLE_MOUSE_INPUT;
4192#endif
4193 cmodein |= ENABLE_WINDOW_INPUT;
4194 SetConsoleMode(g_hConIn, cmodein);
4195
4196 redraw_later_clear();
4197 g_fTermcapMode = TRUE;
4198}
4199
4200
4201/*
4202 * End termcap mode
4203 */
4204 static void
4205termcap_mode_end(void)
4206{
4207 DWORD cmodein;
4208 ConsoleBuffer *cb;
4209 COORD coord;
4210 DWORD dwDummy;
4211
4212 if (!g_fTermcapMode)
4213 return;
4214
4215 SaveConsoleBuffer(&g_cbTermcap);
4216
4217 GetConsoleMode(g_hConIn, &cmodein);
4218 cmodein &= ~(ENABLE_MOUSE_INPUT | ENABLE_WINDOW_INPUT);
4219 SetConsoleMode(g_hConIn, cmodein);
4220
4221#ifdef FEAT_RESTORE_ORIG_SCREEN
4222 cb = exiting ? &g_cbOrig : &g_cbNonTermcap;
4223#else
4224 cb = &g_cbNonTermcap;
4225#endif
4226 RestoreConsoleBuffer(cb, p_rs);
4227 SetConsoleCursorInfo(g_hConOut, &g_cci);
4228
4229 if (p_rs || exiting)
4230 {
4231 /*
4232 * Clear anything that happens to be on the current line.
4233 */
4234 coord.X = 0;
4235 coord.Y = (SHORT) (p_rs ? cb->Info.dwCursorPosition.Y : (Rows - 1));
4236 FillConsoleOutputCharacter(g_hConOut, ' ',
4237 cb->Info.dwSize.X, coord, &dwDummy);
4238 /*
4239 * The following is just for aesthetics. If we are exiting without
4240 * restoring the screen, then we want to have a prompt string
4241 * appear at the bottom line. However, the command interpreter
4242 * seems to always advance the cursor one line before displaying
4243 * the prompt string, which causes the screen to scroll. To
4244 * counter this, move the cursor up one line before exiting.
4245 */
4246 if (exiting && !p_rs)
4247 coord.Y--;
4248 /*
4249 * Position the cursor at the leftmost column of the desired row.
4250 */
4251 SetConsoleCursorPosition(g_hConOut, coord);
4252 }
4253
4254 g_fTermcapMode = FALSE;
4255}
4256#endif /* FEAT_GUI_W32 */
4257
4258
4259#ifdef FEAT_GUI_W32
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00004260/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00004261 void
4262mch_write(
4263 char_u *s,
4264 int len)
4265{
4266 /* never used */
4267}
4268
4269#else
4270
4271/*
4272 * clear `n' chars, starting from `coord'
4273 */
4274 static void
4275clear_chars(
4276 COORD coord,
4277 DWORD n)
4278{
4279 DWORD dwDummy;
4280
4281 FillConsoleOutputCharacter(g_hConOut, ' ', n, coord, &dwDummy);
4282 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, n, coord, &dwDummy);
4283}
4284
4285
4286/*
4287 * Clear the screen
4288 */
4289 static void
4290clear_screen(void)
4291{
4292 g_coord.X = g_coord.Y = 0;
4293 clear_chars(g_coord, Rows * Columns);
4294}
4295
4296
4297/*
4298 * Clear to end of display
4299 */
4300 static void
4301clear_to_end_of_display(void)
4302{
4303 clear_chars(g_coord, (Rows - g_coord.Y - 1)
4304 * Columns + (Columns - g_coord.X));
4305}
4306
4307
4308/*
4309 * Clear to end of line
4310 */
4311 static void
4312clear_to_end_of_line(void)
4313{
4314 clear_chars(g_coord, Columns - g_coord.X);
4315}
4316
4317
4318/*
4319 * Scroll the scroll region up by `cLines' lines
4320 */
4321 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004322scroll(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004323{
4324 COORD oldcoord = g_coord;
4325
4326 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
4327 delete_lines(cLines);
4328
4329 g_coord = oldcoord;
4330}
4331
4332
4333/*
4334 * Set the scroll region
4335 */
4336 static void
4337set_scroll_region(
4338 unsigned left,
4339 unsigned top,
4340 unsigned right,
4341 unsigned bottom)
4342{
4343 if (left >= right
4344 || top >= bottom
4345 || right > (unsigned) Columns - 1
4346 || bottom > (unsigned) Rows - 1)
4347 return;
4348
4349 g_srScrollRegion.Left = left;
4350 g_srScrollRegion.Top = top;
4351 g_srScrollRegion.Right = right;
4352 g_srScrollRegion.Bottom = bottom;
4353}
4354
4355
4356/*
4357 * Insert `cLines' lines at the current cursor position
4358 */
4359 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004360insert_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004361{
4362 SMALL_RECT source;
4363 COORD dest;
4364 CHAR_INFO fill;
4365
4366 dest.X = 0;
4367 dest.Y = g_coord.Y + cLines;
4368
4369 source.Left = 0;
4370 source.Top = g_coord.Y;
4371 source.Right = g_srScrollRegion.Right;
4372 source.Bottom = g_srScrollRegion.Bottom - cLines;
4373
4374 fill.Char.AsciiChar = ' ';
4375 fill.Attributes = g_attrCurrent;
4376
4377 ScrollConsoleScreenBuffer(g_hConOut, &source, NULL, dest, &fill);
4378
4379 /* Here we have to deal with a win32 console flake: If the scroll
4380 * region looks like abc and we scroll c to a and fill with d we get
4381 * cbd... if we scroll block c one line at a time to a, we get cdd...
4382 * vim expects cdd consistently... So we have to deal with that
4383 * here... (this also occurs scrolling the same way in the other
4384 * direction). */
4385
4386 if (source.Bottom < dest.Y)
4387 {
4388 COORD coord;
4389
4390 coord.X = 0;
4391 coord.Y = source.Bottom;
4392 clear_chars(coord, Columns * (dest.Y - source.Bottom));
4393 }
4394}
4395
4396
4397/*
4398 * Delete `cLines' lines at the current cursor position
4399 */
4400 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004401delete_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004402{
4403 SMALL_RECT source;
4404 COORD dest;
4405 CHAR_INFO fill;
4406 int nb;
4407
4408 dest.X = 0;
4409 dest.Y = g_coord.Y;
4410
4411 source.Left = 0;
4412 source.Top = g_coord.Y + cLines;
4413 source.Right = g_srScrollRegion.Right;
4414 source.Bottom = g_srScrollRegion.Bottom;
4415
4416 fill.Char.AsciiChar = ' ';
4417 fill.Attributes = g_attrCurrent;
4418
4419 ScrollConsoleScreenBuffer(g_hConOut, &source, NULL, dest, &fill);
4420
4421 /* Here we have to deal with a win32 console flake: If the scroll
4422 * region looks like abc and we scroll c to a and fill with d we get
4423 * cbd... if we scroll block c one line at a time to a, we get cdd...
4424 * vim expects cdd consistently... So we have to deal with that
4425 * here... (this also occurs scrolling the same way in the other
4426 * direction). */
4427
4428 nb = dest.Y + (source.Bottom - source.Top) + 1;
4429
4430 if (nb < source.Top)
4431 {
4432 COORD coord;
4433
4434 coord.X = 0;
4435 coord.Y = nb;
4436 clear_chars(coord, Columns * (source.Top - nb));
4437 }
4438}
4439
4440
4441/*
4442 * Set the cursor position
4443 */
4444 static void
4445gotoxy(
4446 unsigned x,
4447 unsigned y)
4448{
4449 if (x < 1 || x > (unsigned)Columns || y < 1 || y > (unsigned)Rows)
4450 return;
4451
4452 /* external cursor coords are 1-based; internal are 0-based */
4453 g_coord.X = x - 1;
4454 g_coord.Y = y - 1;
4455 SetConsoleCursorPosition(g_hConOut, g_coord);
4456}
4457
4458
4459/*
4460 * Set the current text attribute = (foreground | background)
4461 * See ../doc/os_win32.txt for the numbers.
4462 */
4463 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004464textattr(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004465{
4466 g_attrCurrent = wAttr;
4467
4468 SetConsoleTextAttribute(g_hConOut, wAttr);
4469}
4470
4471
4472 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004473textcolor(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004474{
4475 g_attrCurrent = (g_attrCurrent & 0xf0) + wAttr;
4476
4477 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
4478}
4479
4480
4481 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004482textbackground(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004483{
4484 g_attrCurrent = (g_attrCurrent & 0x0f) + (wAttr << 4);
4485
4486 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
4487}
4488
4489
4490/*
4491 * restore the default text attribute (whatever we started with)
4492 */
4493 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004494normvideo(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004495{
4496 textattr(g_attrDefault);
4497}
4498
4499
4500static WORD g_attrPreStandout = 0;
4501
4502/*
4503 * Make the text standout, by brightening it
4504 */
4505 static void
4506standout(void)
4507{
4508 g_attrPreStandout = g_attrCurrent;
4509 textattr((WORD) (g_attrCurrent|FOREGROUND_INTENSITY|BACKGROUND_INTENSITY));
4510}
4511
4512
4513/*
4514 * Turn off standout mode
4515 */
4516 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004517standend(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004518{
4519 if (g_attrPreStandout)
4520 {
4521 textattr(g_attrPreStandout);
4522 g_attrPreStandout = 0;
4523 }
4524}
4525
4526
4527/*
Bram Moolenaarff1d0d42007-05-10 17:24:16 +00004528 * Set normal fg/bg color, based on T_ME. Called when t_me has been set.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004529 */
4530 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004531mch_set_normal_colors(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004532{
4533 char_u *p;
4534 int n;
4535
4536 cterm_normal_fg_color = (g_attrDefault & 0xf) + 1;
4537 cterm_normal_bg_color = ((g_attrDefault >> 4) & 0xf) + 1;
4538 if (T_ME[0] == ESC && T_ME[1] == '|')
4539 {
4540 p = T_ME + 2;
4541 n = getdigits(&p);
4542 if (*p == 'm' && n > 0)
4543 {
4544 cterm_normal_fg_color = (n & 0xf) + 1;
4545 cterm_normal_bg_color = ((n >> 4) & 0xf) + 1;
4546 }
4547 }
4548}
4549
4550
4551/*
4552 * visual bell: flash the screen
4553 */
4554 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004555visual_bell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004556{
4557 COORD coordOrigin = {0, 0};
4558 WORD attrFlash = ~g_attrCurrent & 0xff;
4559
4560 DWORD dwDummy;
4561 LPWORD oldattrs = (LPWORD)alloc(Rows * Columns * sizeof(WORD));
4562
4563 if (oldattrs == NULL)
4564 return;
4565 ReadConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
4566 coordOrigin, &dwDummy);
4567 FillConsoleOutputAttribute(g_hConOut, attrFlash, Rows * Columns,
4568 coordOrigin, &dwDummy);
4569
4570 Sleep(15); /* wait for 15 msec */
4571 WriteConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
4572 coordOrigin, &dwDummy);
4573 vim_free(oldattrs);
4574}
4575
4576
4577/*
4578 * Make the cursor visible or invisible
4579 */
4580 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004581cursor_visible(BOOL fVisible)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004582{
4583 s_cursor_visible = fVisible;
4584#ifdef MCH_CURSOR_SHAPE
4585 mch_update_cursor();
4586#endif
4587}
4588
4589
4590/*
4591 * write `cchToWrite' characters in `pchBuf' to the screen
4592 * Returns the number of characters actually written (at least one).
4593 */
4594 static BOOL
4595write_chars(
4596 LPCSTR pchBuf,
4597 DWORD cchToWrite)
4598{
4599 COORD coord = g_coord;
4600 DWORD written;
4601
4602 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, cchToWrite,
4603 coord, &written);
4604 /* When writing fails or didn't write a single character, pretend one
4605 * character was written, otherwise we get stuck. */
4606 if (WriteConsoleOutputCharacter(g_hConOut, pchBuf, cchToWrite,
4607 coord, &written) == 0
4608 || written == 0)
4609 written = 1;
4610
4611 g_coord.X += (SHORT) written;
4612
4613 while (g_coord.X > g_srScrollRegion.Right)
4614 {
4615 g_coord.X -= (SHORT) Columns;
4616 if (g_coord.Y < g_srScrollRegion.Bottom)
4617 g_coord.Y++;
4618 }
4619
4620 gotoxy(g_coord.X + 1, g_coord.Y + 1);
4621
4622 return written;
4623}
4624
4625
4626/*
4627 * mch_write(): write the output buffer to the screen, translating ESC
4628 * sequences into calls to console output routines.
4629 */
4630 void
4631mch_write(
4632 char_u *s,
4633 int len)
4634{
4635 s[len] = NUL;
4636
4637 if (!term_console)
4638 {
4639 write(1, s, (unsigned)len);
4640 return;
4641 }
4642
4643 /* translate ESC | sequences into faked bios calls */
4644 while (len--)
4645 {
4646 /* optimization: use one single write_chars for runs of text,
4647 * rather than once per character It ain't curses, but it helps. */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00004648 DWORD prefix = (DWORD)strcspn(s, "\n\r\b\a\033");
Bram Moolenaar071d4272004-06-13 20:20:40 +00004649
4650 if (p_wd)
4651 {
4652 WaitForChar(p_wd);
4653 if (prefix != 0)
4654 prefix = 1;
4655 }
4656
4657 if (prefix != 0)
4658 {
4659 DWORD nWritten;
4660
4661 nWritten = write_chars(s, prefix);
4662#ifdef MCH_WRITE_DUMP
4663 if (fdDump)
4664 {
4665 fputc('>', fdDump);
4666 fwrite(s, sizeof(char_u), nWritten, fdDump);
4667 fputs("<\n", fdDump);
4668 }
4669#endif
4670 len -= (nWritten - 1);
4671 s += nWritten;
4672 }
4673 else if (s[0] == '\n')
4674 {
4675 /* \n, newline: go to the beginning of the next line or scroll */
4676 if (g_coord.Y == g_srScrollRegion.Bottom)
4677 {
4678 scroll(1);
4679 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Bottom + 1);
4680 }
4681 else
4682 {
4683 gotoxy(g_srScrollRegion.Left + 1, g_coord.Y + 2);
4684 }
4685#ifdef MCH_WRITE_DUMP
4686 if (fdDump)
4687 fputs("\\n\n", fdDump);
4688#endif
4689 s++;
4690 }
4691 else if (s[0] == '\r')
4692 {
4693 /* \r, carriage return: go to beginning of line */
4694 gotoxy(g_srScrollRegion.Left+1, g_coord.Y + 1);
4695#ifdef MCH_WRITE_DUMP
4696 if (fdDump)
4697 fputs("\\r\n", fdDump);
4698#endif
4699 s++;
4700 }
4701 else if (s[0] == '\b')
4702 {
4703 /* \b, backspace: move cursor one position left */
4704 if (g_coord.X > g_srScrollRegion.Left)
4705 g_coord.X--;
4706 else if (g_coord.Y > g_srScrollRegion.Top)
4707 {
4708 g_coord.X = g_srScrollRegion.Right;
4709 g_coord.Y--;
4710 }
4711 gotoxy(g_coord.X + 1, g_coord.Y + 1);
4712#ifdef MCH_WRITE_DUMP
4713 if (fdDump)
4714 fputs("\\b\n", fdDump);
4715#endif
4716 s++;
4717 }
4718 else if (s[0] == '\a')
4719 {
4720 /* \a, bell */
4721 MessageBeep(0xFFFFFFFF);
4722#ifdef MCH_WRITE_DUMP
4723 if (fdDump)
4724 fputs("\\a\n", fdDump);
4725#endif
4726 s++;
4727 }
4728 else if (s[0] == ESC && len >= 3-1 && s[1] == '|')
4729 {
4730#ifdef MCH_WRITE_DUMP
Bram Moolenaarc0197e22004-09-13 20:26:32 +00004731 char_u *old_s = s;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004732#endif
Bram Moolenaarc0197e22004-09-13 20:26:32 +00004733 char_u *p;
4734 int arg1 = 0, arg2 = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004735
4736 switch (s[2])
4737 {
4738 /* one or two numeric arguments, separated by ';' */
4739
4740 case '0': case '1': case '2': case '3': case '4':
4741 case '5': case '6': case '7': case '8': case '9':
4742 p = s + 2;
4743 arg1 = getdigits(&p); /* no check for length! */
4744 if (p > s + len)
4745 break;
4746
4747 if (*p == ';')
4748 {
4749 ++p;
4750 arg2 = getdigits(&p); /* no check for length! */
4751 if (p > s + len)
4752 break;
4753
4754 if (*p == 'H')
4755 gotoxy(arg2, arg1);
4756 else if (*p == 'r')
4757 set_scroll_region(0, arg1 - 1, Columns - 1, arg2 - 1);
4758 }
4759 else if (*p == 'A')
4760 {
4761 /* move cursor up arg1 lines in same column */
4762 gotoxy(g_coord.X + 1,
4763 max(g_srScrollRegion.Top, g_coord.Y - arg1) + 1);
4764 }
4765 else if (*p == 'C')
4766 {
4767 /* move cursor right arg1 columns in same line */
4768 gotoxy(min(g_srScrollRegion.Right, g_coord.X + arg1) + 1,
4769 g_coord.Y + 1);
4770 }
4771 else if (*p == 'H')
4772 {
4773 gotoxy(1, arg1);
4774 }
4775 else if (*p == 'L')
4776 {
4777 insert_lines(arg1);
4778 }
4779 else if (*p == 'm')
4780 {
4781 if (arg1 == 0)
4782 normvideo();
4783 else
4784 textattr((WORD) arg1);
4785 }
4786 else if (*p == 'f')
4787 {
4788 textcolor((WORD) arg1);
4789 }
4790 else if (*p == 'b')
4791 {
4792 textbackground((WORD) arg1);
4793 }
4794 else if (*p == 'M')
4795 {
4796 delete_lines(arg1);
4797 }
4798
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00004799 len -= (int)(p - s);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004800 s = p + 1;
4801 break;
4802
4803
4804 /* Three-character escape sequences */
4805
4806 case 'A':
4807 /* move cursor up one line in same column */
4808 gotoxy(g_coord.X + 1,
4809 max(g_srScrollRegion.Top, g_coord.Y - 1) + 1);
4810 goto got3;
4811
4812 case 'B':
4813 visual_bell();
4814 goto got3;
4815
4816 case 'C':
4817 /* move cursor right one column in same line */
4818 gotoxy(min(g_srScrollRegion.Right, g_coord.X + 1) + 1,
4819 g_coord.Y + 1);
4820 goto got3;
4821
4822 case 'E':
4823 termcap_mode_end();
4824 goto got3;
4825
4826 case 'F':
4827 standout();
4828 goto got3;
4829
4830 case 'f':
4831 standend();
4832 goto got3;
4833
4834 case 'H':
4835 gotoxy(1, 1);
4836 goto got3;
4837
4838 case 'j':
4839 clear_to_end_of_display();
4840 goto got3;
4841
4842 case 'J':
4843 clear_screen();
4844 goto got3;
4845
4846 case 'K':
4847 clear_to_end_of_line();
4848 goto got3;
4849
4850 case 'L':
4851 insert_lines(1);
4852 goto got3;
4853
4854 case 'M':
4855 delete_lines(1);
4856 goto got3;
4857
4858 case 'S':
4859 termcap_mode_start();
4860 goto got3;
4861
4862 case 'V':
4863 cursor_visible(TRUE);
4864 goto got3;
4865
4866 case 'v':
4867 cursor_visible(FALSE);
4868 goto got3;
4869
4870 got3:
4871 s += 3;
4872 len -= 2;
4873 }
4874
4875#ifdef MCH_WRITE_DUMP
4876 if (fdDump)
4877 {
4878 fputs("ESC | ", fdDump);
4879 fwrite(old_s + 2, sizeof(char_u), s - old_s - 2, fdDump);
4880 fputc('\n', fdDump);
4881 }
4882#endif
4883 }
4884 else
4885 {
4886 /* Write a single character */
4887 DWORD nWritten;
4888
4889 nWritten = write_chars(s, 1);
4890#ifdef MCH_WRITE_DUMP
4891 if (fdDump)
4892 {
4893 fputc('>', fdDump);
4894 fwrite(s, sizeof(char_u), nWritten, fdDump);
4895 fputs("<\n", fdDump);
4896 }
4897#endif
4898
4899 len -= (nWritten - 1);
4900 s += nWritten;
4901 }
4902 }
4903
4904#ifdef MCH_WRITE_DUMP
4905 if (fdDump)
4906 fflush(fdDump);
4907#endif
4908}
4909
4910#endif /* FEAT_GUI_W32 */
4911
4912
4913/*
4914 * Delay for half a second.
4915 */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00004916/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00004917 void
4918mch_delay(
4919 long msec,
4920 int ignoreinput)
4921{
4922#ifdef FEAT_GUI_W32
4923 Sleep((int)msec); /* never wait for input */
Bram Moolenaar325b7a22004-07-05 15:58:32 +00004924#else /* Console */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004925 if (ignoreinput)
Bram Moolenaar325b7a22004-07-05 15:58:32 +00004926# ifdef FEAT_MZSCHEME
4927 if (mzthreads_allowed() && p_mzq > 0 && msec > p_mzq)
4928 {
4929 int towait = p_mzq;
4930
4931 /* if msec is large enough, wait by portions in p_mzq */
4932 while (msec > 0)
4933 {
4934 mzvim_check_threads();
4935 if (msec < towait)
4936 towait = msec;
4937 Sleep(towait);
4938 msec -= towait;
4939 }
4940 }
4941 else
4942# endif
4943 Sleep((int)msec);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004944 else
4945 WaitForChar(msec);
4946#endif
4947}
4948
4949
4950/*
4951 * this version of remove is not scared by a readonly (backup) file
4952 * Return 0 for success, -1 for failure.
4953 */
4954 int
4955mch_remove(char_u *name)
4956{
4957#ifdef FEAT_MBYTE
4958 WCHAR *wn = NULL;
4959 int n;
4960
4961 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4962 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00004963 wn = enc_to_utf16(name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004964 if (wn != NULL)
4965 {
4966 SetFileAttributesW(wn, FILE_ATTRIBUTE_NORMAL);
4967 n = DeleteFileW(wn) ? 0 : -1;
4968 vim_free(wn);
4969 if (n == 0 || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
4970 return n;
4971 /* Retry with non-wide function (for Windows 98). */
4972 }
4973 }
4974#endif
4975 SetFileAttributes(name, FILE_ATTRIBUTE_NORMAL);
4976 return DeleteFile(name) ? 0 : -1;
4977}
4978
4979
4980/*
4981 * check for an "interrupt signal": CTRL-break or CTRL-C
4982 */
4983 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004984mch_breakcheck(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004985{
4986#ifndef FEAT_GUI_W32 /* never used */
4987 if (g_fCtrlCPressed || g_fCBrkPressed)
4988 {
4989 g_fCtrlCPressed = g_fCBrkPressed = FALSE;
4990 got_int = TRUE;
4991 }
4992#endif
4993}
4994
4995
4996/*
Bram Moolenaar11b73d62012-06-29 15:51:30 +02004997 * How much memory is available in Kbyte?
Bram Moolenaar071d4272004-06-13 20:20:40 +00004998 * Return sum of available physical and page file memory.
4999 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00005000/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00005001 long_u
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005002mch_avail_mem(int special)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005003{
Bram Moolenaar1a0cee52012-07-19 11:37:26 +02005004#ifdef MEMORYSTATUSEX
5005 PlatformId();
5006 if (g_PlatformId == VER_PLATFORM_WIN32_NT)
5007 {
5008 MEMORYSTATUSEX ms;
5009
5010 /* Need to use GlobalMemoryStatusEx() when there is more memory than
5011 * what fits in 32 bits. But it's not always available. */
5012 ms.dwLength = sizeof(MEMORYSTATUSEX);
5013 GlobalMemoryStatusEx(&ms);
5014 return (long_u)((ms.ullAvailPhys + ms.ullAvailPageFile) >> 10);
5015 }
5016 else
5017#endif
Bram Moolenaar11b73d62012-06-29 15:51:30 +02005018 {
5019 MEMORYSTATUS ms;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005020
Bram Moolenaar11b73d62012-06-29 15:51:30 +02005021 ms.dwLength = sizeof(MEMORYSTATUS);
5022 GlobalMemoryStatus(&ms);
5023 return (long_u)((ms.dwAvailPhys + ms.dwAvailPageFile) >> 10);
5024 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005025}
5026
5027#ifdef FEAT_MBYTE
5028/*
5029 * Same code as below, but with wide functions and no comments.
5030 * Return 0 for success, non-zero for failure.
5031 */
5032 int
5033mch_wrename(WCHAR *wold, WCHAR *wnew)
5034{
5035 WCHAR *p;
5036 int i;
5037 WCHAR szTempFile[_MAX_PATH + 1];
5038 WCHAR szNewPath[_MAX_PATH + 1];
5039 HANDLE hf;
5040
5041 if (!mch_windows95())
5042 {
5043 p = wold;
5044 for (i = 0; wold[i] != NUL; ++i)
5045 if ((wold[i] == '/' || wold[i] == '\\' || wold[i] == ':')
5046 && wold[i + 1] != 0)
5047 p = wold + i + 1;
5048 if ((int)(wold + i - p) < 8 || p[6] != '~')
5049 return (MoveFileW(wold, wnew) == 0);
5050 }
5051
5052 if (GetFullPathNameW(wnew, _MAX_PATH, szNewPath, &p) == 0 || p == NULL)
5053 return -1;
5054 *p = NUL;
5055
5056 if (GetTempFileNameW(szNewPath, L"VIM", 0, szTempFile) == 0)
5057 return -2;
5058
5059 if (!DeleteFileW(szTempFile))
5060 return -3;
5061
5062 if (!MoveFileW(wold, szTempFile))
5063 return -4;
5064
5065 if ((hf = CreateFileW(wold, GENERIC_WRITE, 0, NULL, CREATE_NEW,
5066 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
5067 return -5;
5068 if (!CloseHandle(hf))
5069 return -6;
5070
5071 if (!MoveFileW(szTempFile, wnew))
5072 {
5073 (void)MoveFileW(szTempFile, wold);
5074 return -7;
5075 }
5076
5077 DeleteFileW(szTempFile);
5078
5079 if (!DeleteFileW(wold))
5080 return -8;
5081
5082 return 0;
5083}
5084#endif
5085
5086
5087/*
5088 * mch_rename() works around a bug in rename (aka MoveFile) in
5089 * Windows 95: rename("foo.bar", "foo.bar~") will generate a
5090 * file whose short file name is "FOO.BAR" (its long file name will
5091 * be correct: "foo.bar~"). Because a file can be accessed by
5092 * either its SFN or its LFN, "foo.bar" has effectively been
5093 * renamed to "foo.bar", which is not at all what was wanted. This
5094 * seems to happen only when renaming files with three-character
5095 * extensions by appending a suffix that does not include ".".
5096 * Windows NT gets it right, however, with an SFN of "FOO~1.BAR".
5097 *
5098 * There is another problem, which isn't really a bug but isn't right either:
5099 * When renaming "abcdef~1.txt" to "abcdef~1.txt~", the short name can be
5100 * "abcdef~1.txt" again. This has been reported on Windows NT 4.0 with
5101 * service pack 6. Doesn't seem to happen on Windows 98.
5102 *
5103 * Like rename(), returns 0 upon success, non-zero upon failure.
5104 * Should probably set errno appropriately when errors occur.
5105 */
5106 int
5107mch_rename(
5108 const char *pszOldFile,
5109 const char *pszNewFile)
5110{
5111 char szTempFile[_MAX_PATH+1];
5112 char szNewPath[_MAX_PATH+1];
5113 char *pszFilePart;
5114 HANDLE hf;
5115#ifdef FEAT_MBYTE
5116 WCHAR *wold = NULL;
5117 WCHAR *wnew = NULL;
5118 int retval = -1;
5119
5120 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
5121 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00005122 wold = enc_to_utf16((char_u *)pszOldFile, NULL);
5123 wnew = enc_to_utf16((char_u *)pszNewFile, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005124 if (wold != NULL && wnew != NULL)
5125 retval = mch_wrename(wold, wnew);
5126 vim_free(wold);
5127 vim_free(wnew);
5128 if (retval == 0 || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
5129 return retval;
5130 /* Retry with non-wide function (for Windows 98). */
5131 }
5132#endif
5133
5134 /*
5135 * No need to play tricks if not running Windows 95, unless the file name
5136 * contains a "~" as the seventh character.
5137 */
5138 if (!mch_windows95())
5139 {
5140 pszFilePart = (char *)gettail((char_u *)pszOldFile);
5141 if (STRLEN(pszFilePart) < 8 || pszFilePart[6] != '~')
5142 return rename(pszOldFile, pszNewFile);
5143 }
5144
5145 /* Get base path of new file name. Undocumented feature: If pszNewFile is
5146 * a directory, no error is returned and pszFilePart will be NULL. */
5147 if (GetFullPathName(pszNewFile, _MAX_PATH, szNewPath, &pszFilePart) == 0
5148 || pszFilePart == NULL)
5149 return -1;
5150 *pszFilePart = NUL;
5151
5152 /* Get (and create) a unique temporary file name in directory of new file */
5153 if (GetTempFileName(szNewPath, "VIM", 0, szTempFile) == 0)
5154 return -2;
5155
5156 /* blow the temp file away */
5157 if (!DeleteFile(szTempFile))
5158 return -3;
5159
5160 /* rename old file to the temp file */
5161 if (!MoveFile(pszOldFile, szTempFile))
5162 return -4;
5163
5164 /* now create an empty file called pszOldFile; this prevents the operating
5165 * system using pszOldFile as an alias (SFN) if we're renaming within the
5166 * same directory. For example, we're editing a file called
5167 * filename.asc.txt by its SFN, filena~1.txt. If we rename filena~1.txt
5168 * to filena~1.txt~ (i.e., we're making a backup while writing it), the
5169 * SFN for filena~1.txt~ will be filena~1.txt, by default, which will
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00005170 * cause all sorts of problems later in buf_write(). So, we create an
5171 * empty file called filena~1.txt and the system will have to find some
5172 * other SFN for filena~1.txt~, such as filena~2.txt
Bram Moolenaar071d4272004-06-13 20:20:40 +00005173 */
5174 if ((hf = CreateFile(pszOldFile, GENERIC_WRITE, 0, NULL, CREATE_NEW,
5175 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
5176 return -5;
5177 if (!CloseHandle(hf))
5178 return -6;
5179
5180 /* rename the temp file to the new file */
5181 if (!MoveFile(szTempFile, pszNewFile))
5182 {
5183 /* Renaming failed. Rename the file back to its old name, so that it
5184 * looks like nothing happened. */
5185 (void)MoveFile(szTempFile, pszOldFile);
5186
5187 return -7;
5188 }
5189
5190 /* Seems to be left around on Novell filesystems */
5191 DeleteFile(szTempFile);
5192
5193 /* finally, remove the empty old file */
5194 if (!DeleteFile(pszOldFile))
5195 return -8;
5196
5197 return 0; /* success */
5198}
5199
5200/*
5201 * Get the default shell for the current hardware platform
5202 */
5203 char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005204default_shell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005205{
5206 char* psz = NULL;
5207
5208 PlatformId();
5209
5210 if (g_PlatformId == VER_PLATFORM_WIN32_NT) /* Windows NT */
5211 psz = "cmd.exe";
5212 else if (g_PlatformId == VER_PLATFORM_WIN32_WINDOWS) /* Windows 95 */
5213 psz = "command.com";
5214
5215 return psz;
5216}
5217
5218/*
5219 * mch_access() extends access() to do more detailed check on network drives.
5220 * Returns 0 if file "n" has access rights according to "p", -1 otherwise.
5221 */
5222 int
5223mch_access(char *n, int p)
5224{
5225 HANDLE hFile;
5226 DWORD am;
5227 int retval = -1; /* default: fail */
5228#ifdef FEAT_MBYTE
5229 WCHAR *wn = NULL;
5230
5231 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar36f692d2008-11-20 16:10:17 +00005232 wn = enc_to_utf16(n, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005233#endif
5234
5235 if (mch_isdir(n))
5236 {
5237 char TempName[_MAX_PATH + 16] = "";
5238#ifdef FEAT_MBYTE
5239 WCHAR TempNameW[_MAX_PATH + 16] = L"";
5240#endif
5241
5242 if (p & R_OK)
5243 {
5244 /* Read check is performed by seeing if we can do a find file on
5245 * the directory for any file. */
5246#ifdef FEAT_MBYTE
5247 if (wn != NULL)
5248 {
5249 int i;
5250 WIN32_FIND_DATAW d;
5251
5252 for (i = 0; i < _MAX_PATH && wn[i] != 0; ++i)
5253 TempNameW[i] = wn[i];
5254 if (TempNameW[i - 1] != '\\' && TempNameW[i - 1] != '/')
5255 TempNameW[i++] = '\\';
5256 TempNameW[i++] = '*';
5257 TempNameW[i++] = 0;
5258
5259 hFile = FindFirstFileW(TempNameW, &d);
5260 if (hFile == INVALID_HANDLE_VALUE)
5261 {
5262 if (GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
5263 goto getout;
5264
5265 /* Retry with non-wide function (for Windows 98). */
5266 vim_free(wn);
5267 wn = NULL;
5268 }
5269 else
5270 (void)FindClose(hFile);
5271 }
5272 if (wn == NULL)
5273#endif
5274 {
5275 char *pch;
5276 WIN32_FIND_DATA d;
5277
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00005278 vim_strncpy(TempName, n, _MAX_PATH);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005279 pch = TempName + STRLEN(TempName) - 1;
5280 if (*pch != '\\' && *pch != '/')
5281 *++pch = '\\';
5282 *++pch = '*';
5283 *++pch = NUL;
5284
5285 hFile = FindFirstFile(TempName, &d);
5286 if (hFile == INVALID_HANDLE_VALUE)
5287 goto getout;
5288 (void)FindClose(hFile);
5289 }
5290 }
5291
5292 if (p & W_OK)
5293 {
5294 /* Trying to create a temporary file in the directory should catch
5295 * directories on read-only network shares. However, in
5296 * directories whose ACL allows writes but denies deletes will end
5297 * up keeping the temporary file :-(. */
5298#ifdef FEAT_MBYTE
5299 if (wn != NULL)
5300 {
5301 if (!GetTempFileNameW(wn, L"VIM", 0, TempNameW))
5302 {
5303 if (GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
5304 goto getout;
5305
5306 /* Retry with non-wide function (for Windows 98). */
5307 vim_free(wn);
5308 wn = NULL;
5309 }
5310 else
5311 DeleteFileW(TempNameW);
5312 }
5313 if (wn == NULL)
5314#endif
5315 {
5316 if (!GetTempFileName(n, "VIM", 0, TempName))
5317 goto getout;
5318 mch_remove((char_u *)TempName);
5319 }
5320 }
5321 }
5322 else
5323 {
5324 /* Trying to open the file for the required access does ACL, read-only
5325 * network share, and file attribute checks. */
5326 am = ((p & W_OK) ? GENERIC_WRITE : 0)
5327 | ((p & R_OK) ? GENERIC_READ : 0);
5328#ifdef FEAT_MBYTE
5329 if (wn != NULL)
5330 {
5331 hFile = CreateFileW(wn, am, 0, NULL, OPEN_EXISTING, 0, NULL);
5332 if (hFile == INVALID_HANDLE_VALUE
5333 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
5334 {
5335 /* Retry with non-wide function (for Windows 98). */
5336 vim_free(wn);
5337 wn = NULL;
5338 }
5339 }
5340 if (wn == NULL)
5341#endif
5342 hFile = CreateFile(n, am, 0, NULL, OPEN_EXISTING, 0, NULL);
5343 if (hFile == INVALID_HANDLE_VALUE)
5344 goto getout;
5345 CloseHandle(hFile);
5346 }
5347
5348 retval = 0; /* success */
5349getout:
5350#ifdef FEAT_MBYTE
5351 vim_free(wn);
5352#endif
5353 return retval;
5354}
5355
5356#if defined(FEAT_MBYTE) || defined(PROTO)
5357/*
Bram Moolenaar36f692d2008-11-20 16:10:17 +00005358 * Version of open() that may use UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005359 */
5360 int
5361mch_open(char *name, int flags, int mode)
5362{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00005363 /* _wopen() does not work with Borland C 5.5: creates a read-only file. */
5364# ifndef __BORLANDC__
Bram Moolenaar071d4272004-06-13 20:20:40 +00005365 WCHAR *wn;
5366 int f;
5367
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00005368 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005369 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00005370 wn = enc_to_utf16(name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005371 if (wn != NULL)
5372 {
5373 f = _wopen(wn, flags, mode);
5374 vim_free(wn);
5375 if (f >= 0)
5376 return f;
5377 /* Retry with non-wide function (for Windows 98). Can't use
5378 * GetLastError() here and it's unclear what errno gets set to if
5379 * the _wopen() fails for missing wide functions. */
5380 }
5381 }
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00005382# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005383
5384 return open(name, flags, mode);
5385}
5386
5387/*
Bram Moolenaar36f692d2008-11-20 16:10:17 +00005388 * Version of fopen() that may use UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005389 */
5390 FILE *
5391mch_fopen(char *name, char *mode)
5392{
5393 WCHAR *wn, *wm;
5394 FILE *f = NULL;
5395
5396 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage
5397# ifdef __BORLANDC__
5398 /* Wide functions of Borland C 5.5 do not work on Windows 98. */
5399 && g_PlatformId == VER_PLATFORM_WIN32_NT
5400# endif
5401 )
5402 {
Bram Moolenaare6a91fd2008-07-24 18:51:11 +00005403# if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0fde2902008-03-16 13:54:13 +00005404 /* Work around an annoying assertion in the Microsoft debug CRT
5405 * when mode's text/binary setting doesn't match _get_fmode(). */
5406 char newMode = mode[strlen(mode) - 1];
5407 int oldMode = 0;
5408
5409 _get_fmode(&oldMode);
5410 if (newMode == 't')
5411 _set_fmode(_O_TEXT);
5412 else if (newMode == 'b')
5413 _set_fmode(_O_BINARY);
5414# endif
Bram Moolenaar36f692d2008-11-20 16:10:17 +00005415 wn = enc_to_utf16(name, NULL);
5416 wm = enc_to_utf16(mode, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005417 if (wn != NULL && wm != NULL)
5418 f = _wfopen(wn, wm);
5419 vim_free(wn);
5420 vim_free(wm);
Bram Moolenaar0fde2902008-03-16 13:54:13 +00005421
Bram Moolenaare6a91fd2008-07-24 18:51:11 +00005422# if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0fde2902008-03-16 13:54:13 +00005423 _set_fmode(oldMode);
5424# endif
5425
Bram Moolenaar071d4272004-06-13 20:20:40 +00005426 if (f != NULL)
5427 return f;
5428 /* Retry with non-wide function (for Windows 98). Can't use
5429 * GetLastError() here and it's unclear what errno gets set to if
5430 * the _wfopen() fails for missing wide functions. */
5431 }
5432
5433 return fopen(name, mode);
5434}
5435#endif
5436
5437#ifdef FEAT_MBYTE
5438/*
5439 * SUB STREAM (aka info stream) handling:
5440 *
5441 * NTFS can have sub streams for each file. Normal contents of file is
5442 * stored in the main stream, and extra contents (author information and
5443 * title and so on) can be stored in sub stream. After Windows 2000, user
5444 * can access and store those informations in sub streams via explorer's
5445 * property menuitem in right click menu. Those informations in sub streams
5446 * were lost when copying only the main stream. So we have to copy sub
5447 * streams.
5448 *
5449 * Incomplete explanation:
5450 * http://msdn.microsoft.com/library/en-us/dnw2k/html/ntfs5.asp
5451 * More useful info and an example:
5452 * http://www.sysinternals.com/ntw2k/source/misc.shtml#streams
5453 */
5454
5455/*
5456 * Copy info stream data "substream". Read from the file with BackupRead(sh)
5457 * and write to stream "substream" of file "to".
5458 * Errors are ignored.
5459 */
5460 static void
5461copy_substream(HANDLE sh, void *context, WCHAR *to, WCHAR *substream, long len)
5462{
5463 HANDLE hTo;
5464 WCHAR *to_name;
5465
5466 to_name = malloc((wcslen(to) + wcslen(substream) + 1) * sizeof(WCHAR));
5467 wcscpy(to_name, to);
5468 wcscat(to_name, substream);
5469
5470 hTo = CreateFileW(to_name, GENERIC_WRITE, 0, NULL, OPEN_ALWAYS,
5471 FILE_ATTRIBUTE_NORMAL, NULL);
5472 if (hTo != INVALID_HANDLE_VALUE)
5473 {
5474 long done;
5475 DWORD todo;
5476 DWORD readcnt, written;
5477 char buf[4096];
5478
5479 /* Copy block of bytes at a time. Abort when something goes wrong. */
5480 for (done = 0; done < len; done += written)
5481 {
5482 /* (size_t) cast for Borland C 5.5 */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005483 todo = (DWORD)((size_t)(len - done) > sizeof(buf) ? sizeof(buf)
5484 : (size_t)(len - done));
Bram Moolenaar071d4272004-06-13 20:20:40 +00005485 if (!BackupRead(sh, (LPBYTE)buf, todo, &readcnt,
5486 FALSE, FALSE, context)
5487 || readcnt != todo
5488 || !WriteFile(hTo, buf, todo, &written, NULL)
5489 || written != todo)
5490 break;
5491 }
5492 CloseHandle(hTo);
5493 }
5494
5495 free(to_name);
5496}
5497
5498/*
5499 * Copy info streams from file "from" to file "to".
5500 */
5501 static void
5502copy_infostreams(char_u *from, char_u *to)
5503{
5504 WCHAR *fromw;
5505 WCHAR *tow;
5506 HANDLE sh;
5507 WIN32_STREAM_ID sid;
5508 int headersize;
5509 WCHAR streamname[_MAX_PATH];
5510 DWORD readcount;
5511 void *context = NULL;
5512 DWORD lo, hi;
5513 int len;
5514
5515 /* Convert the file names to wide characters. */
Bram Moolenaar36f692d2008-11-20 16:10:17 +00005516 fromw = enc_to_utf16(from, NULL);
5517 tow = enc_to_utf16(to, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005518 if (fromw != NULL && tow != NULL)
5519 {
5520 /* Open the file for reading. */
5521 sh = CreateFileW(fromw, GENERIC_READ, FILE_SHARE_READ, NULL,
5522 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
5523 if (sh != INVALID_HANDLE_VALUE)
5524 {
5525 /* Use BackupRead() to find the info streams. Repeat until we
5526 * have done them all.*/
5527 for (;;)
5528 {
5529 /* Get the header to find the length of the stream name. If
5530 * the "readcount" is zero we have done all info streams. */
5531 ZeroMemory(&sid, sizeof(WIN32_STREAM_ID));
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005532 headersize = (int)((char *)&sid.cStreamName - (char *)&sid.dwStreamId);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005533 if (!BackupRead(sh, (LPBYTE)&sid, headersize,
5534 &readcount, FALSE, FALSE, &context)
5535 || readcount == 0)
5536 break;
5537
5538 /* We only deal with streams that have a name. The normal
5539 * file data appears to be without a name, even though docs
5540 * suggest it is called "::$DATA". */
5541 if (sid.dwStreamNameSize > 0)
5542 {
5543 /* Read the stream name. */
5544 if (!BackupRead(sh, (LPBYTE)streamname,
5545 sid.dwStreamNameSize,
5546 &readcount, FALSE, FALSE, &context))
5547 break;
5548
5549 /* Copy an info stream with a name ":anything:$DATA".
5550 * Skip "::$DATA", it has no stream name (examples suggest
5551 * it might be used for the normal file contents).
5552 * Note that BackupRead() counts bytes, but the name is in
5553 * wide characters. */
5554 len = readcount / sizeof(WCHAR);
5555 streamname[len] = 0;
5556 if (len > 7 && wcsicmp(streamname + len - 6,
5557 L":$DATA") == 0)
5558 {
5559 streamname[len - 6] = 0;
5560 copy_substream(sh, &context, tow, streamname,
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00005561 (long)sid.Size.u.LowPart);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005562 }
5563 }
5564
5565 /* Advance to the next stream. We might try seeking too far,
5566 * but BackupSeek() doesn't skip over stream borders, thus
5567 * that's OK. */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00005568 (void)BackupSeek(sh, sid.Size.u.LowPart, sid.Size.u.HighPart,
Bram Moolenaar071d4272004-06-13 20:20:40 +00005569 &lo, &hi, &context);
5570 }
5571
5572 /* Clear the context. */
5573 (void)BackupRead(sh, NULL, 0, &readcount, TRUE, FALSE, &context);
5574
5575 CloseHandle(sh);
5576 }
5577 }
5578 vim_free(fromw);
5579 vim_free(tow);
5580}
5581#endif
5582
5583/*
5584 * Copy file attributes from file "from" to file "to".
5585 * For Windows NT and later we copy info streams.
5586 * Always returns zero, errors are ignored.
5587 */
5588 int
5589mch_copy_file_attribute(char_u *from, char_u *to)
5590{
5591#ifdef FEAT_MBYTE
5592 /* File streams only work on Windows NT and later. */
5593 PlatformId();
5594 if (g_PlatformId == VER_PLATFORM_WIN32_NT)
5595 copy_infostreams(from, to);
5596#endif
5597 return 0;
5598}
5599
5600#if defined(MYRESETSTKOFLW) || defined(PROTO)
5601/*
5602 * Recreate a destroyed stack guard page in win32.
5603 * Written by Benjamin Peterson.
5604 */
5605
5606/* These magic numbers are from the MS header files */
5607#define MIN_STACK_WIN9X 17
5608#define MIN_STACK_WINNT 2
5609
5610/*
5611 * This function does the same thing as _resetstkoflw(), which is only
5612 * available in DevStudio .net and later.
5613 * Returns 0 for failure, 1 for success.
5614 */
5615 int
5616myresetstkoflw(void)
5617{
5618 BYTE *pStackPtr;
5619 BYTE *pGuardPage;
5620 BYTE *pStackBase;
5621 BYTE *pLowestPossiblePage;
5622 MEMORY_BASIC_INFORMATION mbi;
5623 SYSTEM_INFO si;
5624 DWORD nPageSize;
5625 DWORD dummy;
5626
5627 /* This code will not work on win32s. */
5628 PlatformId();
5629 if (g_PlatformId == VER_PLATFORM_WIN32s)
5630 return 0;
5631
5632 /* We need to know the system page size. */
5633 GetSystemInfo(&si);
5634 nPageSize = si.dwPageSize;
5635
5636 /* ...and the current stack pointer */
5637 pStackPtr = (BYTE*)_alloca(1);
5638
5639 /* ...and the base of the stack. */
5640 if (VirtualQuery(pStackPtr, &mbi, sizeof mbi) == 0)
5641 return 0;
5642 pStackBase = (BYTE*)mbi.AllocationBase;
5643
5644 /* ...and the page thats min_stack_req pages away from stack base; this is
5645 * the lowest page we could use. */
5646 pLowestPossiblePage = pStackBase + ((g_PlatformId == VER_PLATFORM_WIN32_NT)
5647 ? MIN_STACK_WINNT : MIN_STACK_WIN9X) * nPageSize;
5648
5649 /* On Win95, we want the next page down from the end of the stack. */
5650 if (g_PlatformId == VER_PLATFORM_WIN32_WINDOWS)
5651 {
5652 /* Find the page that's only 1 page down from the page that the stack
5653 * ptr is in. */
5654 pGuardPage = (BYTE*)((DWORD)nPageSize * (((DWORD)pStackPtr
5655 / (DWORD)nPageSize) - 1));
5656 if (pGuardPage < pLowestPossiblePage)
5657 return 0;
5658
5659 /* Apply the noaccess attribute to the page -- there's no guard
5660 * attribute in win95-type OSes. */
5661 if (!VirtualProtect(pGuardPage, nPageSize, PAGE_NOACCESS, &dummy))
5662 return 0;
5663 }
5664 else
5665 {
5666 /* On NT, however, we want the first committed page in the stack Start
5667 * at the stack base and move forward through memory until we find a
5668 * committed block. */
5669 BYTE *pBlock = pStackBase;
5670
Bram Moolenaara466c992005-07-09 21:03:22 +00005671 for (;;)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005672 {
5673 if (VirtualQuery(pBlock, &mbi, sizeof mbi) == 0)
5674 return 0;
5675
5676 pBlock += mbi.RegionSize;
5677
5678 if (mbi.State & MEM_COMMIT)
5679 break;
5680 }
5681
5682 /* mbi now describes the first committed block in the stack. */
5683 if (mbi.Protect & PAGE_GUARD)
5684 return 1;
5685
5686 /* decide where the guard page should start */
5687 if ((long_u)(mbi.BaseAddress) < (long_u)pLowestPossiblePage)
5688 pGuardPage = pLowestPossiblePage;
5689 else
5690 pGuardPage = (BYTE*)mbi.BaseAddress;
5691
5692 /* allocate the guard page */
5693 if (!VirtualAlloc(pGuardPage, nPageSize, MEM_COMMIT, PAGE_READWRITE))
5694 return 0;
5695
5696 /* apply the guard attribute to the page */
5697 if (!VirtualProtect(pGuardPage, nPageSize, PAGE_READWRITE | PAGE_GUARD,
5698 &dummy))
5699 return 0;
5700 }
5701
5702 return 1;
5703}
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005704#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005705
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005706
5707#if defined(FEAT_MBYTE) || defined(PROTO)
5708/*
5709 * The command line arguments in UCS2
5710 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00005711static int nArgsW = 0;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005712static LPWSTR *ArglistW = NULL;
5713static int global_argc = 0;
5714static char **global_argv;
5715
5716static int used_file_argc = 0; /* last argument in global_argv[] used
5717 for the argument list. */
5718static int *used_file_indexes = NULL; /* indexes in global_argv[] for
5719 command line arguments added to
5720 the argument list */
5721static int used_file_count = 0; /* nr of entries in used_file_indexes */
5722static int used_file_literal = FALSE; /* take file names literally */
5723static int used_file_full_path = FALSE; /* file name was full path */
Bram Moolenaar910f66f2006-04-05 20:41:53 +00005724static int used_file_diff_mode = FALSE; /* file name was with diff mode */
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005725static int used_alist_count = 0;
5726
5727
5728/*
5729 * Get the command line arguments. Unicode version.
5730 * Returns argc. Zero when something fails.
5731 */
5732 int
5733get_cmd_argsW(char ***argvp)
5734{
5735 char **argv = NULL;
5736 int argc = 0;
5737 int i;
5738
5739 ArglistW = CommandLineToArgvW(GetCommandLineW(), &nArgsW);
5740 if (ArglistW != NULL)
5741 {
5742 argv = malloc((nArgsW + 1) * sizeof(char *));
5743 if (argv != NULL)
5744 {
5745 argc = nArgsW;
5746 argv[argc] = NULL;
5747 for (i = 0; i < argc; ++i)
5748 {
5749 int len;
5750
5751 /* Convert each Unicode argument to the current codepage. */
5752 WideCharToMultiByte_alloc(GetACP(), 0,
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005753 ArglistW[i], (int)wcslen(ArglistW[i]) + 1,
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005754 (LPSTR *)&argv[i], &len, 0, 0);
5755 if (argv[i] == NULL)
5756 {
5757 /* Out of memory, clear everything. */
5758 while (i > 0)
5759 free(argv[--i]);
5760 free(argv);
5761 argc = 0;
5762 }
5763 }
5764 }
5765 }
5766
5767 global_argc = argc;
5768 global_argv = argv;
5769 if (argc > 0)
5770 used_file_indexes = malloc(argc * sizeof(int));
5771
5772 if (argvp != NULL)
5773 *argvp = argv;
5774 return argc;
5775}
5776
5777 void
5778free_cmd_argsW(void)
5779{
5780 if (ArglistW != NULL)
5781 {
5782 GlobalFree(ArglistW);
5783 ArglistW = NULL;
5784 }
5785}
5786
5787/*
5788 * Remember "name" is an argument that was added to the argument list.
5789 * This avoids that we have to re-parse the argument list when fix_arg_enc()
5790 * is called.
5791 */
5792 void
Bram Moolenaar910f66f2006-04-05 20:41:53 +00005793used_file_arg(char *name, int literal, int full_path, int diff_mode)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005794{
5795 int i;
5796
5797 if (used_file_indexes == NULL)
5798 return;
5799 for (i = used_file_argc + 1; i < global_argc; ++i)
5800 if (STRCMP(global_argv[i], name) == 0)
5801 {
5802 used_file_argc = i;
5803 used_file_indexes[used_file_count++] = i;
5804 break;
5805 }
5806 used_file_literal = literal;
5807 used_file_full_path = full_path;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00005808 used_file_diff_mode = diff_mode;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005809}
5810
5811/*
5812 * Remember the length of the argument list as it was. If it changes then we
5813 * leave it alone when 'encoding' is set.
5814 */
5815 void
5816set_alist_count(void)
5817{
5818 used_alist_count = GARGCOUNT;
5819}
5820
5821/*
5822 * Fix the encoding of the command line arguments. Invoked when 'encoding'
5823 * has been changed while starting up. Use the UCS-2 command line arguments
5824 * and convert them to 'encoding'.
5825 */
5826 void
5827fix_arg_enc(void)
5828{
5829 int i;
5830 int idx;
5831 char_u *str;
Bram Moolenaar86b68352004-12-27 21:59:20 +00005832 int *fnum_list;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005833
5834 /* Safety checks:
5835 * - if argument count differs between the wide and non-wide argument
5836 * list, something must be wrong.
5837 * - the file name arguments must have been located.
5838 * - the length of the argument list wasn't changed by the user.
5839 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00005840 if (global_argc != nArgsW
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005841 || ArglistW == NULL
5842 || used_file_indexes == NULL
5843 || used_file_count == 0
5844 || used_alist_count != GARGCOUNT)
5845 return;
5846
Bram Moolenaar86b68352004-12-27 21:59:20 +00005847 /* Remember the buffer numbers for the arguments. */
5848 fnum_list = (int *)alloc((int)sizeof(int) * GARGCOUNT);
5849 if (fnum_list == NULL)
5850 return; /* out of memory */
5851 for (i = 0; i < GARGCOUNT; ++i)
5852 fnum_list[i] = GARGLIST[i].ae_fnum;
5853
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005854 /* Clear the argument list. Make room for the new arguments. */
5855 alist_clear(&global_alist);
5856 if (ga_grow(&global_alist.al_ga, used_file_count) == FAIL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00005857 return; /* out of memory */
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005858
5859 for (i = 0; i < used_file_count; ++i)
5860 {
5861 idx = used_file_indexes[i];
Bram Moolenaar36f692d2008-11-20 16:10:17 +00005862 str = utf16_to_enc(ArglistW[idx], NULL);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005863 if (str != NULL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00005864 {
Bram Moolenaar910f66f2006-04-05 20:41:53 +00005865#ifdef FEAT_DIFF
5866 /* When using diff mode may need to concatenate file name to
5867 * directory name. Just like it's done in main(). */
5868 if (used_file_diff_mode && mch_isdir(str) && GARGCOUNT > 0
5869 && !mch_isdir(alist_name(&GARGLIST[0])))
5870 {
5871 char_u *r;
5872
5873 r = concat_fnames(str, gettail(alist_name(&GARGLIST[0])), TRUE);
5874 if (r != NULL)
5875 {
5876 vim_free(str);
5877 str = r;
5878 }
5879 }
5880#endif
Bram Moolenaar86b68352004-12-27 21:59:20 +00005881 /* Re-use the old buffer by renaming it. When not using literal
5882 * names it's done by alist_expand() below. */
5883 if (used_file_literal)
5884 buf_set_name(fnum_list[i], str);
5885
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005886 alist_add(&global_alist, str, used_file_literal ? 2 : 0);
Bram Moolenaar86b68352004-12-27 21:59:20 +00005887 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005888 }
5889
5890 if (!used_file_literal)
5891 {
5892 /* Now expand wildcards in the arguments. */
5893 /* Temporarily add '(' and ')' to 'isfname'. These are valid
5894 * filename characters but are excluded from 'isfname' to make
5895 * "gf" work on a file name in parenthesis (e.g.: see vim.h). */
5896 do_cmdline_cmd((char_u *)":let SaVe_ISF = &isf|set isf+=(,)");
Bram Moolenaar86b68352004-12-27 21:59:20 +00005897 alist_expand(fnum_list, used_alist_count);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005898 do_cmdline_cmd((char_u *)":let &isf = SaVe_ISF|unlet SaVe_ISF");
5899 }
5900
5901 /* If wildcard expansion failed, we are editing the first file of the
5902 * arglist and there is no file name: Edit the first argument now. */
5903 if (curwin->w_arg_idx == 0 && curbuf->b_fname == NULL)
5904 {
5905 do_cmdline_cmd((char_u *)":rewind");
5906 if (GARGCOUNT == 1 && used_file_full_path)
5907 (void)vim_chdirfile(alist_name(&GARGLIST[0]));
5908 }
Bram Moolenaar86b68352004-12-27 21:59:20 +00005909
5910 set_alist_count();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005911}
Bram Moolenaar071d4272004-06-13 20:20:40 +00005912#endif