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