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