blob: 047045047e32c10d20ec7fcadc18d8abeb8c47c7 [file] [log] [blame]
Bram Moolenaar071d4272004-06-13 20:20:40 +00001/* vi:set ts=8 sts=4 sw=4:
2 *
3 * VIM - Vi IMproved by Bram Moolenaar
4 *
5 * Do ":help uganda" in Vim to read copying and usage conditions.
6 * Do ":help credits" in Vim to see a list of people who contributed.
7 * See README.txt for an overview of the Vim source code.
8 */
9/*
10 * os_win32.c
11 *
12 * Used for both the console version and the Win32 GUI. A lot of code is for
13 * the console version only, so there is a lot of "#ifndef FEAT_GUI_W32".
14 *
15 * Win32 (Windows NT and Windows 95) system-dependent routines.
16 * Portions lifted from the Win32 SDK samples, the MSDOS-dependent code,
17 * NetHack 3.1.3, GNU Emacs 19.30, and Vile 5.5.
18 *
19 * George V. Reilly <george@reilly.org> wrote most of this.
20 * Roger Knobbe <rogerk@wonderware.com> did the initial port of Vim 3.0.
21 */
22
Bram Moolenaar071d4272004-06-13 20:20:40 +000023#include "vim.h"
24
Bram Moolenaar325b7a22004-07-05 15:58:32 +000025#ifdef FEAT_MZSCHEME
26# include "if_mzsch.h"
27#endif
28
Bram Moolenaar071d4272004-06-13 20:20:40 +000029#include <sys/types.h>
Bram Moolenaar071d4272004-06-13 20:20:40 +000030#include <signal.h>
31#include <limits.h>
Bram Moolenaar82881492012-11-20 16:53:39 +010032
33/* cproto fails on missing include files */
34#ifndef PROTO
35# include <process.h>
36#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +000037
38#undef chdir
39#ifdef __GNUC__
40# ifndef __MINGW32__
41# include <dirent.h>
42# endif
43#else
44# include <direct.h>
45#endif
46
Bram Moolenaar82881492012-11-20 16:53:39 +010047#ifndef PROTO
48# if defined(FEAT_TITLE) && !defined(FEAT_GUI_W32)
49# include <shellapi.h>
50# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +000051#endif
52
53#ifdef __MINGW32__
54# ifndef FROM_LEFT_1ST_BUTTON_PRESSED
55# define FROM_LEFT_1ST_BUTTON_PRESSED 0x0001
56# endif
57# ifndef RIGHTMOST_BUTTON_PRESSED
58# define RIGHTMOST_BUTTON_PRESSED 0x0002
59# endif
60# ifndef FROM_LEFT_2ND_BUTTON_PRESSED
61# define FROM_LEFT_2ND_BUTTON_PRESSED 0x0004
62# endif
63# ifndef FROM_LEFT_3RD_BUTTON_PRESSED
64# define FROM_LEFT_3RD_BUTTON_PRESSED 0x0008
65# endif
66# ifndef FROM_LEFT_4TH_BUTTON_PRESSED
67# define FROM_LEFT_4TH_BUTTON_PRESSED 0x0010
68# endif
69
70/*
71 * EventFlags
72 */
73# ifndef MOUSE_MOVED
74# define MOUSE_MOVED 0x0001
75# endif
76# ifndef DOUBLE_CLICK
77# define DOUBLE_CLICK 0x0002
78# endif
79#endif
80
81/* Record all output and all keyboard & mouse input */
82/* #define MCH_WRITE_DUMP */
83
84#ifdef MCH_WRITE_DUMP
85FILE* fdDump = NULL;
86#endif
87
88/*
89 * When generating prototypes for Win32 on Unix, these lines make the syntax
90 * errors disappear. They do not need to be correct.
91 */
92#ifdef PROTO
93#define WINAPI
Bram Moolenaar071d4272004-06-13 20:20:40 +000094typedef char * LPCSTR;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +000095typedef char * LPWSTR;
Bram Moolenaar071d4272004-06-13 20:20:40 +000096typedef int ACCESS_MASK;
97typedef int BOOL;
98typedef int COLORREF;
99typedef int CONSOLE_CURSOR_INFO;
100typedef int COORD;
101typedef int DWORD;
102typedef int HANDLE;
Bram Moolenaaref269542016-01-19 13:22:12 +0100103typedef int LPHANDLE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000104typedef int HDC;
105typedef int HFONT;
106typedef int HICON;
107typedef int HINSTANCE;
108typedef int HWND;
109typedef int INPUT_RECORD;
110typedef int KEY_EVENT_RECORD;
111typedef int LOGFONT;
112typedef int LPBOOL;
113typedef int LPCTSTR;
114typedef int LPDWORD;
115typedef int LPSTR;
116typedef int LPTSTR;
117typedef int LPVOID;
118typedef int MOUSE_EVENT_RECORD;
119typedef int PACL;
120typedef int PDWORD;
121typedef int PHANDLE;
122typedef int PRINTDLG;
123typedef int PSECURITY_DESCRIPTOR;
124typedef int PSID;
125typedef int SECURITY_INFORMATION;
126typedef int SHORT;
127typedef int SMALL_RECT;
128typedef int TEXTMETRIC;
129typedef int TOKEN_INFORMATION_CLASS;
130typedef int TRUSTEE;
131typedef int WORD;
132typedef int WCHAR;
133typedef void VOID;
Bram Moolenaar82881492012-11-20 16:53:39 +0100134typedef int BY_HANDLE_FILE_INFORMATION;
Bram Moolenaar32ac8cd2013-07-03 18:49:17 +0200135typedef int SE_OBJECT_TYPE;
136typedef int PSNSECINFO;
137typedef int PSNSECINFOW;
Bram Moolenaarb8e0bdb2014-11-12 16:10:48 +0100138typedef int STARTUPINFO;
139typedef int PROCESS_INFORMATION;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000140#endif
141
142#ifndef FEAT_GUI_W32
143/* Undocumented API in kernel32.dll needed to work around dead key bug in
144 * console-mode applications in NT 4.0. If you switch keyboard layouts
145 * in a console app to a layout that includes dead keys and then hit a
146 * dead key, a call to ToAscii will trash the stack. My thanks to Ian James
147 * and Michael Dietrich for helping me figure out this workaround.
148 */
149
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +0100150/* WINAPI BOOL WINAPI GetConsoleKeyboardLayoutNameA(LPSTR); */
151#ifndef WINAPI
152# define WINAPI __stdcall
Bram Moolenaar071d4272004-06-13 20:20:40 +0000153#endif
154#if defined(__BORLANDC__)
155typedef BOOL (__stdcall *PFNGCKLN)(LPSTR);
156#else
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +0100157typedef BOOL (WINAPI *PFNGCKLN)(LPSTR);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000158#endif
Bram Moolenaard6f676d2005-06-01 21:51:55 +0000159static PFNGCKLN s_pfnGetConsoleKeyboardLayoutName = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000160#endif
161
162#if defined(__BORLANDC__)
163/* Strangely Borland uses a non-standard name. */
164# define wcsicmp(a, b) wcscmpi((a), (b))
165#endif
166
Bram Moolenaar82881492012-11-20 16:53:39 +0100167#ifndef PROTO
168
Bram Moolenaar84a05ac2013-05-06 04:24:17 +0200169/* Enable common dialogs input unicode from IME if possible. */
Bram Moolenaar8c85fa32011-08-10 17:08:03 +0200170#ifdef FEAT_MBYTE
Bram Moolenaaraf62ff32013-03-19 14:48:29 +0100171LRESULT (WINAPI *pDispatchMessage)(CONST MSG *) = DispatchMessage;
Bram Moolenaar8c85fa32011-08-10 17:08:03 +0200172BOOL (WINAPI *pGetMessage)(LPMSG, HWND, UINT, UINT) = GetMessage;
173BOOL (WINAPI *pIsDialogMessage)(HWND, LPMSG) = IsDialogMessage;
174BOOL (WINAPI *pPeekMessage)(LPMSG, HWND, UINT, UINT, UINT) = PeekMessage;
175#endif
176
Bram Moolenaar82881492012-11-20 16:53:39 +0100177#endif /* PROTO */
178
Bram Moolenaar071d4272004-06-13 20:20:40 +0000179#ifndef FEAT_GUI_W32
180/* Win32 Console handles for input and output */
181static HANDLE g_hConIn = INVALID_HANDLE_VALUE;
182static HANDLE g_hConOut = INVALID_HANDLE_VALUE;
183
184/* Win32 Screen buffer,coordinate,console I/O information */
185static SMALL_RECT g_srScrollRegion;
186static COORD g_coord; /* 0-based, but external coords are 1-based */
187
188/* The attribute of the screen when the editor was started */
189static WORD g_attrDefault = 7; /* lightgray text on black background */
190static WORD g_attrCurrent;
191
192static int g_fCBrkPressed = FALSE; /* set by ctrl-break interrupt */
193static int g_fCtrlCPressed = FALSE; /* set when ctrl-C or ctrl-break detected */
194static int g_fForceExit = FALSE; /* set when forcefully exiting */
195
196static void termcap_mode_start(void);
197static void termcap_mode_end(void);
198static void clear_chars(COORD coord, DWORD n);
199static void clear_screen(void);
200static void clear_to_end_of_display(void);
201static void clear_to_end_of_line(void);
202static void scroll(unsigned cLines);
203static void set_scroll_region(unsigned left, unsigned top,
204 unsigned right, unsigned bottom);
205static void insert_lines(unsigned cLines);
206static void delete_lines(unsigned cLines);
207static void gotoxy(unsigned x, unsigned y);
208static void normvideo(void);
209static void textattr(WORD wAttr);
210static void textcolor(WORD wAttr);
211static void textbackground(WORD wAttr);
212static void standout(void);
213static void standend(void);
214static void visual_bell(void);
215static void cursor_visible(BOOL fVisible);
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200216static DWORD write_chars(char_u *pchBuf, DWORD cbToWrite);
217static WCHAR tgetch(int *pmodifiers, WCHAR *pch2);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000218static void create_conin(void);
219static int s_cursor_visible = TRUE;
220static int did_create_conin = FALSE;
221#else
222static int s_dont_use_vimrun = TRUE;
223static int need_vimrun_warning = FALSE;
224static char *vimrun_path = "vimrun ";
225#endif
226
Bram Moolenaar12b559e2013-06-12 22:41:37 +0200227static int win32_getattrs(char_u *name);
228static int win32_setattrs(char_u *name, int attrs);
229static int win32_set_archive(char_u *name);
230
Bram Moolenaar071d4272004-06-13 20:20:40 +0000231#ifndef FEAT_GUI_W32
232static int suppress_winsize = 1; /* don't fiddle with console */
233#endif
234
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200235static char_u *exe_path = NULL;
236
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100237static BOOL win8_or_later = FALSE;
238
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100239#ifndef FEAT_GUI_W32
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100240/*
241 * Version of ReadConsoleInput() that works with IME.
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100242 * Works around problems on Windows 8.
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100243 */
244 static BOOL
245read_console_input(
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100246 HANDLE hInput,
247 INPUT_RECORD *lpBuffer,
248 DWORD nLength,
249 LPDWORD lpEvents)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100250{
251 enum
252 {
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100253 IRSIZE = 10
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100254 };
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100255 static INPUT_RECORD s_irCache[IRSIZE];
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100256 static DWORD s_dwIndex = 0;
257 static DWORD s_dwMax = 0;
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100258 DWORD dwEvents;
Bram Moolenaardd415a62014-02-05 14:02:27 +0100259 int head;
260 int tail;
261 int i;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100262
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200263 if (nLength == -2)
264 return (s_dwMax > 0) ? TRUE : FALSE;
265
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100266 if (!win8_or_later)
267 {
268 if (nLength == -1)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200269 return PeekConsoleInputW(hInput, lpBuffer, 1, lpEvents);
270 return ReadConsoleInputW(hInput, lpBuffer, 1, &dwEvents);
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100271 }
272
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100273 if (s_dwMax == 0)
274 {
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100275 if (nLength == -1)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200276 return PeekConsoleInputW(hInput, lpBuffer, 1, lpEvents);
277 if (!ReadConsoleInputW(hInput, s_irCache, IRSIZE, &dwEvents))
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100278 return FALSE;
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100279 s_dwIndex = 0;
280 s_dwMax = dwEvents;
281 if (dwEvents == 0)
282 {
283 *lpEvents = 0;
284 return TRUE;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100285 }
Bram Moolenaardd415a62014-02-05 14:02:27 +0100286
287 if (s_dwMax > 1)
288 {
289 head = 0;
290 tail = s_dwMax - 1;
291 while (head != tail)
292 {
293 if (s_irCache[head].EventType == WINDOW_BUFFER_SIZE_EVENT
294 && s_irCache[head + 1].EventType
295 == WINDOW_BUFFER_SIZE_EVENT)
296 {
297 /* Remove duplicate event to avoid flicker. */
298 for (i = head; i < tail; ++i)
299 s_irCache[i] = s_irCache[i + 1];
300 --tail;
301 continue;
302 }
303 head++;
304 }
305 s_dwMax = tail + 1;
306 }
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100307 }
Bram Moolenaardd415a62014-02-05 14:02:27 +0100308
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100309 *lpBuffer = s_irCache[s_dwIndex];
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200310 if (!(nLength == -1 || nLength == -2) && ++s_dwIndex >= s_dwMax)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100311 s_dwMax = 0;
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100312 *lpEvents = 1;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100313 return TRUE;
314}
315
316/*
317 * Version of PeekConsoleInput() that works with IME.
318 */
319 static BOOL
320peek_console_input(
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100321 HANDLE hInput,
322 INPUT_RECORD *lpBuffer,
323 DWORD nLength,
324 LPDWORD lpEvents)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100325{
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100326 return read_console_input(hInput, lpBuffer, -1, lpEvents);
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100327}
328
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100329# ifdef FEAT_CLIENTSERVER
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200330 static DWORD
331msg_wait_for_multiple_objects(
332 DWORD nCount,
333 LPHANDLE pHandles,
334 BOOL fWaitAll,
335 DWORD dwMilliseconds,
336 DWORD dwWakeMask)
337{
338 if (read_console_input(NULL, NULL, -2, NULL))
339 return WAIT_OBJECT_0;
340 return MsgWaitForMultipleObjects(nCount, pHandles, fWaitAll,
341 dwMilliseconds, dwWakeMask);
342}
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100343# endif
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200344
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100345# ifndef FEAT_CLIENTSERVER
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200346 static DWORD
347wait_for_single_object(
348 HANDLE hHandle,
349 DWORD dwMilliseconds)
350{
351 if (read_console_input(NULL, NULL, -2, NULL))
352 return WAIT_OBJECT_0;
353 return WaitForSingleObject(hHandle, dwMilliseconds);
354}
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100355# endif
356#endif
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200357
Bram Moolenaar071d4272004-06-13 20:20:40 +0000358 static void
359get_exe_name(void)
360{
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100361 /* Maximum length of $PATH is more than MAXPATHL. 8191 is often mentioned
362 * as the maximum length that works (plus a NUL byte). */
363#define MAX_ENV_PATH_LEN 8192
364 char temp[MAX_ENV_PATH_LEN];
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200365 char_u *p;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000366
367 if (exe_name == NULL)
368 {
369 /* store the name of the executable, may be used for $VIM */
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100370 GetModuleFileName(NULL, temp, MAX_ENV_PATH_LEN - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000371 if (*temp != NUL)
372 exe_name = FullName_save((char_u *)temp, FALSE);
373 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000374
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200375 if (exe_path == NULL && exe_name != NULL)
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000376 {
Bram Moolenaar6b5ef062010-10-27 12:18:00 +0200377 exe_path = vim_strnsave(exe_name,
378 (int)(gettail_sep(exe_name) - exe_name));
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200379 if (exe_path != NULL)
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000380 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200381 /* Append our starting directory to $PATH, so that when doing
382 * "!xxd" it's found in our starting directory. Needed because
383 * SearchPath() also looks there. */
384 p = mch_getenv("PATH");
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100385 if (p == NULL
386 || STRLEN(p) + STRLEN(exe_path) + 2 < MAX_ENV_PATH_LEN)
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200387 {
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100388 if (p == NULL || *p == NUL)
389 temp[0] = NUL;
390 else
391 {
392 STRCPY(temp, p);
393 STRCAT(temp, ";");
394 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200395 STRCAT(temp, exe_path);
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +0100396 vim_setenv((char_u *)"PATH", (char_u *)temp);
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200397 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000398 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000399 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000400}
401
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200402/*
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100403 * Unescape characters in "p" that appear in "escaped".
404 */
405 static void
406unescape_shellxquote(char_u *p, char_u *escaped)
407{
Bram Moolenaar4336cdf2012-02-29 13:58:47 +0100408 int l = (int)STRLEN(p);
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100409 int n;
410
411 while (*p != NUL)
412 {
413 if (*p == '^' && vim_strchr(escaped, p[1]) != NULL)
414 mch_memmove(p, p + 1, l--);
415#ifdef FEAT_MBYTE
416 n = (*mb_ptr2len)(p);
417#else
418 n = 1;
419#endif
420 p += n;
421 l -= n;
422 }
423}
424
425/*
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200426 * Load library "name".
427 */
428 HINSTANCE
429vimLoadLib(char *name)
430{
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200431 HINSTANCE dll = NULL;
432 char old_dir[MAXPATHL];
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200433
Bram Moolenaarfaca8402012-10-21 02:37:10 +0200434 /* NOTE: Do not use mch_dirname() and mch_chdir() here, they may call
435 * vimLoadLib() recursively, which causes a stack overflow. */
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200436 if (exe_path == NULL)
437 get_exe_name();
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200438 if (exe_path != NULL)
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200439 {
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200440#ifdef FEAT_MBYTE
441 WCHAR old_dirw[MAXPATHL];
442
443 if (GetCurrentDirectoryW(MAXPATHL, old_dirw) != 0)
444 {
445 /* Change directory to where the executable is, both to make
446 * sure we find a .dll there and to avoid looking for a .dll
447 * in the current directory. */
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +0100448 SetCurrentDirectory((LPCSTR)exe_path);
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200449 dll = LoadLibrary(name);
450 SetCurrentDirectoryW(old_dirw);
451 return dll;
452 }
453 /* Retry with non-wide function (for Windows 98). */
454 if (GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
455#endif
456 if (GetCurrentDirectory(MAXPATHL, old_dir) != 0)
457 {
458 /* Change directory to where the executable is, both to make
459 * sure we find a .dll there and to avoid looking for a .dll
460 * in the current directory. */
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +0100461 SetCurrentDirectory((LPCSTR)exe_path);
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200462 dll = LoadLibrary(name);
463 SetCurrentDirectory(old_dir);
464 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200465 }
466 return dll;
467}
468
Bram Moolenaar071d4272004-06-13 20:20:40 +0000469#if defined(DYNAMIC_GETTEXT) || defined(PROTO)
470# ifndef GETTEXT_DLL
471# define GETTEXT_DLL "libintl.dll"
Bram Moolenaar286eacd2016-01-16 18:05:50 +0100472# define GETTEXT_DLL_ALT "libintl-8.dll"
Bram Moolenaar071d4272004-06-13 20:20:40 +0000473# endif
Bram Moolenaarf6a2b082012-06-29 13:14:03 +0200474/* Dummy functions */
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000475static char *null_libintl_gettext(const char *);
476static char *null_libintl_textdomain(const char *);
477static char *null_libintl_bindtextdomain(const char *, const char *);
478static char *null_libintl_bind_textdomain_codeset(const char *, const char *);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000479
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200480static HINSTANCE hLibintlDLL = NULL;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000481char *(*dyn_libintl_gettext)(const char *) = null_libintl_gettext;
482char *(*dyn_libintl_textdomain)(const char *) = null_libintl_textdomain;
483char *(*dyn_libintl_bindtextdomain)(const char *, const char *)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000484 = null_libintl_bindtextdomain;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000485char *(*dyn_libintl_bind_textdomain_codeset)(const char *, const char *)
486 = null_libintl_bind_textdomain_codeset;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000487
488 int
Bram Moolenaar05540972016-01-30 20:31:25 +0100489dyn_libintl_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000490{
491 int i;
492 static struct
493 {
494 char *name;
495 FARPROC *ptr;
496 } libintl_entry[] =
497 {
498 {"gettext", (FARPROC*)&dyn_libintl_gettext},
499 {"textdomain", (FARPROC*)&dyn_libintl_textdomain},
500 {"bindtextdomain", (FARPROC*)&dyn_libintl_bindtextdomain},
501 {NULL, NULL}
502 };
503
504 /* No need to initialize twice. */
505 if (hLibintlDLL)
506 return 1;
507 /* Load gettext library (libintl.dll) */
Bram Moolenaar923e43b2016-01-28 15:07:38 +0100508 hLibintlDLL = vimLoadLib(GETTEXT_DLL);
Bram Moolenaar938ee832016-01-24 15:36:03 +0100509#ifdef GETTEXT_DLL_ALT
Bram Moolenaar286eacd2016-01-16 18:05:50 +0100510 if (!hLibintlDLL)
511 hLibintlDLL = vimLoadLib(GETTEXT_DLL_ALT);
Bram Moolenaar938ee832016-01-24 15:36:03 +0100512#endif
513 if (!hLibintlDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000514 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200515 if (p_verbose > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000516 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200517 verbose_enter();
518 EMSG2(_(e_loadlib), GETTEXT_DLL);
519 verbose_leave();
Bram Moolenaar071d4272004-06-13 20:20:40 +0000520 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200521 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000522 }
523 for (i = 0; libintl_entry[i].name != NULL
524 && libintl_entry[i].ptr != NULL; ++i)
525 {
526 if ((*libintl_entry[i].ptr = (FARPROC)GetProcAddress(hLibintlDLL,
527 libintl_entry[i].name)) == NULL)
528 {
529 dyn_libintl_end();
530 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +0000531 {
532 verbose_enter();
Bram Moolenaar071d4272004-06-13 20:20:40 +0000533 EMSG2(_(e_loadfunc), libintl_entry[i].name);
Bram Moolenaara04f10b2005-05-31 22:09:46 +0000534 verbose_leave();
535 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000536 return 0;
537 }
538 }
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000539
540 /* The bind_textdomain_codeset() function is optional. */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000541 dyn_libintl_bind_textdomain_codeset = (void *)GetProcAddress(hLibintlDLL,
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000542 "bind_textdomain_codeset");
543 if (dyn_libintl_bind_textdomain_codeset == NULL)
544 dyn_libintl_bind_textdomain_codeset =
545 null_libintl_bind_textdomain_codeset;
546
Bram Moolenaar071d4272004-06-13 20:20:40 +0000547 return 1;
548}
549
550 void
Bram Moolenaar05540972016-01-30 20:31:25 +0100551dyn_libintl_end(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000552{
553 if (hLibintlDLL)
554 FreeLibrary(hLibintlDLL);
555 hLibintlDLL = NULL;
556 dyn_libintl_gettext = null_libintl_gettext;
557 dyn_libintl_textdomain = null_libintl_textdomain;
558 dyn_libintl_bindtextdomain = null_libintl_bindtextdomain;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000559 dyn_libintl_bind_textdomain_codeset = null_libintl_bind_textdomain_codeset;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000560}
561
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000562/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +0000563 static char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000564null_libintl_gettext(const char *msgid)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000565{
566 return (char*)msgid;
567}
568
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000569/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +0000570 static char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000571null_libintl_bindtextdomain(const char *domainname, const char *dirname)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000572{
573 return NULL;
574}
575
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000576/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +0000577 static char *
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000578null_libintl_bind_textdomain_codeset(const char *domainname,
579 const char *codeset)
580{
581 return NULL;
582}
583
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000584/*ARGSUSED*/
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000585 static char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000586null_libintl_textdomain(const char *domainname)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000587{
588 return NULL;
589}
590
591#endif /* DYNAMIC_GETTEXT */
592
593/* This symbol is not defined in older versions of the SDK or Visual C++ */
594
595#ifndef VER_PLATFORM_WIN32_WINDOWS
596# define VER_PLATFORM_WIN32_WINDOWS 1
597#endif
598
599DWORD g_PlatformId;
600
601#ifdef HAVE_ACL
Bram Moolenaar82881492012-11-20 16:53:39 +0100602# ifndef PROTO
603# include <aclapi.h>
604# endif
Bram Moolenaar27515922013-06-29 15:36:26 +0200605# ifndef PROTECTED_DACL_SECURITY_INFORMATION
606# define PROTECTED_DACL_SECURITY_INFORMATION 0x80000000L
607# endif
Bram Moolenaar82881492012-11-20 16:53:39 +0100608
Bram Moolenaar071d4272004-06-13 20:20:40 +0000609/*
610 * These are needed to dynamically load the ADVAPI DLL, which is not
611 * implemented under Windows 95 (and causes VIM to crash)
612 */
Bram Moolenaar39efa892013-06-29 15:40:04 +0200613typedef DWORD (WINAPI *PSNSECINFO) (LPSTR, SE_OBJECT_TYPE,
Bram Moolenaar071d4272004-06-13 20:20:40 +0000614 SECURITY_INFORMATION, PSID, PSID, PACL, PACL);
Bram Moolenaar39efa892013-06-29 15:40:04 +0200615typedef DWORD (WINAPI *PGNSECINFO) (LPSTR, SE_OBJECT_TYPE,
Bram Moolenaar071d4272004-06-13 20:20:40 +0000616 SECURITY_INFORMATION, PSID *, PSID *, PACL *, PACL *,
617 PSECURITY_DESCRIPTOR *);
Bram Moolenaar27515922013-06-29 15:36:26 +0200618# ifdef FEAT_MBYTE
Bram Moolenaar39efa892013-06-29 15:40:04 +0200619typedef DWORD (WINAPI *PSNSECINFOW) (LPWSTR, SE_OBJECT_TYPE,
Bram Moolenaar27515922013-06-29 15:36:26 +0200620 SECURITY_INFORMATION, PSID, PSID, PACL, PACL);
Bram Moolenaar39efa892013-06-29 15:40:04 +0200621typedef DWORD (WINAPI *PGNSECINFOW) (LPWSTR, SE_OBJECT_TYPE,
Bram Moolenaar27515922013-06-29 15:36:26 +0200622 SECURITY_INFORMATION, PSID *, PSID *, PACL *, PACL *,
623 PSECURITY_DESCRIPTOR *);
624# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000625
626static HANDLE advapi_lib = NULL; /* Handle for ADVAPI library */
627static PSNSECINFO pSetNamedSecurityInfo;
628static PGNSECINFO pGetNamedSecurityInfo;
Bram Moolenaar27515922013-06-29 15:36:26 +0200629# ifdef FEAT_MBYTE
630static PSNSECINFOW pSetNamedSecurityInfoW;
631static PGNSECINFOW pGetNamedSecurityInfoW;
632# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000633#endif
634
Bram Moolenaar4b9669f2011-07-07 16:20:52 +0200635typedef BOOL (WINAPI *PSETHANDLEINFORMATION)(HANDLE, DWORD, DWORD);
636
637static BOOL allowPiping = FALSE;
638static PSETHANDLEINFORMATION pSetHandleInformation;
639
Bram Moolenaar27515922013-06-29 15:36:26 +0200640#ifdef HAVE_ACL
641/*
642 * Enables or disables the specified privilege.
643 */
644 static BOOL
645win32_enable_privilege(LPTSTR lpszPrivilege, BOOL bEnable)
646{
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100647 BOOL bResult;
648 LUID luid;
649 HANDLE hToken;
650 TOKEN_PRIVILEGES tokenPrivileges;
Bram Moolenaar27515922013-06-29 15:36:26 +0200651
652 if (!OpenProcessToken(GetCurrentProcess(),
653 TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
654 return FALSE;
655
656 if (!LookupPrivilegeValue(NULL, lpszPrivilege, &luid))
657 {
658 CloseHandle(hToken);
659 return FALSE;
660 }
661
Bram Moolenaar45500912014-07-09 20:51:07 +0200662 tokenPrivileges.PrivilegeCount = 1;
Bram Moolenaar27515922013-06-29 15:36:26 +0200663 tokenPrivileges.Privileges[0].Luid = luid;
664 tokenPrivileges.Privileges[0].Attributes = bEnable ?
665 SE_PRIVILEGE_ENABLED : 0;
666
667 bResult = AdjustTokenPrivileges(hToken, FALSE, &tokenPrivileges,
668 sizeof(TOKEN_PRIVILEGES), NULL, NULL);
669
670 CloseHandle(hToken);
671
672 return bResult && GetLastError() == ERROR_SUCCESS;
673}
674#endif
675
Bram Moolenaar071d4272004-06-13 20:20:40 +0000676/*
677 * Set g_PlatformId to VER_PLATFORM_WIN32_NT (NT) or
678 * VER_PLATFORM_WIN32_WINDOWS (Win95).
679 */
680 void
681PlatformId(void)
682{
683 static int done = FALSE;
684
685 if (!done)
686 {
687 OSVERSIONINFO ovi;
688
689 ovi.dwOSVersionInfoSize = sizeof(ovi);
690 GetVersionEx(&ovi);
691
692 g_PlatformId = ovi.dwPlatformId;
693
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100694 if ((ovi.dwMajorVersion == 6 && ovi.dwMinorVersion >= 2)
695 || ovi.dwMajorVersion > 6)
696 win8_or_later = TRUE;
697
Bram Moolenaar071d4272004-06-13 20:20:40 +0000698#ifdef HAVE_ACL
699 /*
700 * Load the ADVAPI runtime if we are on anything
701 * other than Windows 95
702 */
703 if (g_PlatformId == VER_PLATFORM_WIN32_NT)
704 {
705 /*
706 * do this load. Problems: Doesn't unload at end of run (this is
707 * theoretically okay, since Windows should unload it when VIM
708 * terminates). Should we be using the 'mch_libcall' routines?
709 * Seems like a lot of overhead to load/unload ADVAPI32.DLL each
710 * time we verify security...
711 */
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200712 advapi_lib = vimLoadLib("ADVAPI32.DLL");
Bram Moolenaar071d4272004-06-13 20:20:40 +0000713 if (advapi_lib != NULL)
714 {
715 pSetNamedSecurityInfo = (PSNSECINFO)GetProcAddress(advapi_lib,
716 "SetNamedSecurityInfoA");
717 pGetNamedSecurityInfo = (PGNSECINFO)GetProcAddress(advapi_lib,
718 "GetNamedSecurityInfoA");
Bram Moolenaar27515922013-06-29 15:36:26 +0200719# ifdef FEAT_MBYTE
720 pSetNamedSecurityInfoW = (PSNSECINFOW)GetProcAddress(advapi_lib,
721 "SetNamedSecurityInfoW");
722 pGetNamedSecurityInfoW = (PGNSECINFOW)GetProcAddress(advapi_lib,
723 "GetNamedSecurityInfoW");
724# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000725 if (pSetNamedSecurityInfo == NULL
Bram Moolenaar27515922013-06-29 15:36:26 +0200726 || pGetNamedSecurityInfo == NULL
727# ifdef FEAT_MBYTE
728 || pSetNamedSecurityInfoW == NULL
729 || pGetNamedSecurityInfoW == NULL
730# endif
731 )
Bram Moolenaar071d4272004-06-13 20:20:40 +0000732 {
733 /* If we can't get the function addresses, set advapi_lib
734 * to NULL so that we don't use them. */
735 FreeLibrary(advapi_lib);
736 advapi_lib = NULL;
737 }
Bram Moolenaar27515922013-06-29 15:36:26 +0200738 /* Enable privilege for getting or setting SACLs. */
739 win32_enable_privilege(SE_SECURITY_NAME, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000740 }
741 }
742#endif
Bram Moolenaar4b9669f2011-07-07 16:20:52 +0200743 /*
744 * If we are on windows NT, try to load the pipe functions, only
745 * available from Win2K.
746 */
747 if (g_PlatformId == VER_PLATFORM_WIN32_NT)
748 {
749 HANDLE kernel32 = GetModuleHandle("kernel32");
750 pSetHandleInformation = (PSETHANDLEINFORMATION)GetProcAddress(
751 kernel32, "SetHandleInformation");
752
753 allowPiping = pSetHandleInformation != NULL;
754 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000755 done = TRUE;
756 }
757}
758
759/*
760 * Return TRUE when running on Windows 95 (or 98 or ME).
761 * Only to be used after mch_init().
762 */
763 int
764mch_windows95(void)
765{
766 return g_PlatformId == VER_PLATFORM_WIN32_WINDOWS;
767}
768
769#ifdef FEAT_GUI_W32
770/*
771 * Used to work around the "can't do synchronous spawn"
772 * problem on Win32s, without resorting to Universal Thunk.
773 */
774static int old_num_windows;
775static int num_windows;
776
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000777/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +0000778 static BOOL CALLBACK
779win32ssynch_cb(HWND hwnd, LPARAM lparam)
780{
781 num_windows++;
782 return TRUE;
783}
784#endif
785
786#ifndef FEAT_GUI_W32
787
788#define SHIFT (SHIFT_PRESSED)
789#define CTRL (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED)
790#define ALT (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED)
791#define ALT_GR (RIGHT_ALT_PRESSED | LEFT_CTRL_PRESSED)
792
793
794/* When uChar.AsciiChar is 0, then we need to look at wVirtualKeyCode.
795 * We map function keys to their ANSI terminal equivalents, as produced
796 * by ANSI.SYS, for compatibility with the MS-DOS version of Vim. Any
797 * ANSI key with a value >= '\300' is nonstandard, but provided anyway
798 * so that the user can have access to all SHIFT-, CTRL-, and ALT-
799 * combinations of function/arrow/etc keys.
800 */
801
Bram Moolenaard6f676d2005-06-01 21:51:55 +0000802static const struct
Bram Moolenaar071d4272004-06-13 20:20:40 +0000803{
804 WORD wVirtKey;
805 BOOL fAnsiKey;
806 int chAlone;
807 int chShift;
808 int chCtrl;
809 int chAlt;
810} VirtKeyMap[] =
811{
812
813/* Key ANSI alone shift ctrl alt */
814 { VK_ESCAPE,FALSE, ESC, ESC, ESC, ESC, },
815
816 { VK_F1, TRUE, ';', 'T', '^', 'h', },
817 { VK_F2, TRUE, '<', 'U', '_', 'i', },
818 { VK_F3, TRUE, '=', 'V', '`', 'j', },
819 { VK_F4, TRUE, '>', 'W', 'a', 'k', },
820 { VK_F5, TRUE, '?', 'X', 'b', 'l', },
821 { VK_F6, TRUE, '@', 'Y', 'c', 'm', },
822 { VK_F7, TRUE, 'A', 'Z', 'd', 'n', },
823 { VK_F8, TRUE, 'B', '[', 'e', 'o', },
824 { VK_F9, TRUE, 'C', '\\', 'f', 'p', },
825 { VK_F10, TRUE, 'D', ']', 'g', 'q', },
826 { VK_F11, TRUE, '\205', '\207', '\211', '\213', },
827 { VK_F12, TRUE, '\206', '\210', '\212', '\214', },
828
829 { VK_HOME, TRUE, 'G', '\302', 'w', '\303', },
830 { VK_UP, TRUE, 'H', '\304', '\305', '\306', },
831 { VK_PRIOR, TRUE, 'I', '\307', '\204', '\310', }, /*PgUp*/
832 { VK_LEFT, TRUE, 'K', '\311', 's', '\312', },
833 { VK_RIGHT, TRUE, 'M', '\313', 't', '\314', },
834 { VK_END, TRUE, 'O', '\315', 'u', '\316', },
835 { VK_DOWN, TRUE, 'P', '\317', '\320', '\321', },
836 { VK_NEXT, TRUE, 'Q', '\322', 'v', '\323', }, /*PgDn*/
837 { VK_INSERT,TRUE, 'R', '\324', '\325', '\326', },
838 { VK_DELETE,TRUE, 'S', '\327', '\330', '\331', },
839
840 { VK_SNAPSHOT,TRUE, 0, 0, 0, 'r', }, /*PrtScrn*/
841
842#if 0
843 /* Most people don't have F13-F20, but what the hell... */
844 { VK_F13, TRUE, '\332', '\333', '\334', '\335', },
845 { VK_F14, TRUE, '\336', '\337', '\340', '\341', },
846 { VK_F15, TRUE, '\342', '\343', '\344', '\345', },
847 { VK_F16, TRUE, '\346', '\347', '\350', '\351', },
848 { VK_F17, TRUE, '\352', '\353', '\354', '\355', },
849 { VK_F18, TRUE, '\356', '\357', '\360', '\361', },
850 { VK_F19, TRUE, '\362', '\363', '\364', '\365', },
851 { VK_F20, TRUE, '\366', '\367', '\370', '\371', },
852#endif
853 { VK_ADD, TRUE, 'N', 'N', 'N', 'N', }, /* keyp '+' */
854 { VK_SUBTRACT, TRUE,'J', 'J', 'J', 'J', }, /* keyp '-' */
855 /* { VK_DIVIDE, TRUE,'N', 'N', 'N', 'N', }, keyp '/' */
856 { VK_MULTIPLY, TRUE,'7', '7', '7', '7', }, /* keyp '*' */
857
858 { VK_NUMPAD0,TRUE, '\332', '\333', '\334', '\335', },
859 { VK_NUMPAD1,TRUE, '\336', '\337', '\340', '\341', },
860 { VK_NUMPAD2,TRUE, '\342', '\343', '\344', '\345', },
861 { VK_NUMPAD3,TRUE, '\346', '\347', '\350', '\351', },
862 { VK_NUMPAD4,TRUE, '\352', '\353', '\354', '\355', },
863 { VK_NUMPAD5,TRUE, '\356', '\357', '\360', '\361', },
864 { VK_NUMPAD6,TRUE, '\362', '\363', '\364', '\365', },
865 { VK_NUMPAD7,TRUE, '\366', '\367', '\370', '\371', },
866 { VK_NUMPAD8,TRUE, '\372', '\373', '\374', '\375', },
867 /* Sorry, out of number space! <negri>*/
868 { VK_NUMPAD9,TRUE, '\376', '\377', '\377', '\367', },
869
870};
871
872
873#ifdef _MSC_VER
874// The ToAscii bug destroys several registers. Need to turn off optimization
875// or the GetConsoleKeyboardLayoutName hack will fail in non-debug versions
Bram Moolenaar7b5f8322006-03-23 22:47:08 +0000876# pragma warning(push)
877# pragma warning(disable: 4748)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000878# pragma optimize("", off)
879#endif
880
881#if defined(__GNUC__) && !defined(__MINGW32__) && !defined(__CYGWIN__)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200882# define UChar UnicodeChar
Bram Moolenaar071d4272004-06-13 20:20:40 +0000883#else
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200884# define UChar uChar.UnicodeChar
Bram Moolenaar071d4272004-06-13 20:20:40 +0000885#endif
886
887/* The return code indicates key code size. */
888 static int
889#ifdef __BORLANDC__
890 __stdcall
891#endif
892win32_kbd_patch_key(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000893 KEY_EVENT_RECORD *pker)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000894{
895 UINT uMods = pker->dwControlKeyState;
896 static int s_iIsDead = 0;
897 static WORD awAnsiCode[2];
898 static BYTE abKeystate[256];
899
900
901 if (s_iIsDead == 2)
902 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200903 pker->UChar = (WCHAR) awAnsiCode[1];
Bram Moolenaar071d4272004-06-13 20:20:40 +0000904 s_iIsDead = 0;
905 return 1;
906 }
907
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200908 if (pker->UChar != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000909 return 1;
910
Bram Moolenaar7db5fc82010-05-24 11:59:29 +0200911 vim_memset(abKeystate, 0, sizeof (abKeystate));
Bram Moolenaar071d4272004-06-13 20:20:40 +0000912
913 // Should only be non-NULL on NT 4.0
914 if (s_pfnGetConsoleKeyboardLayoutName != NULL)
915 {
916 CHAR szKLID[KL_NAMELENGTH];
917
918 if ((*s_pfnGetConsoleKeyboardLayoutName)(szKLID))
919 (void)LoadKeyboardLayout(szKLID, KLF_ACTIVATE);
920 }
921
922 /* Clear any pending dead keys */
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200923 ToUnicode(VK_SPACE, MapVirtualKey(VK_SPACE, 0), abKeystate, awAnsiCode, 2, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000924
925 if (uMods & SHIFT_PRESSED)
926 abKeystate[VK_SHIFT] = 0x80;
927 if (uMods & CAPSLOCK_ON)
928 abKeystate[VK_CAPITAL] = 1;
929
930 if ((uMods & ALT_GR) == ALT_GR)
931 {
932 abKeystate[VK_CONTROL] = abKeystate[VK_LCONTROL] =
933 abKeystate[VK_MENU] = abKeystate[VK_RMENU] = 0x80;
934 }
935
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200936 s_iIsDead = ToUnicode(pker->wVirtualKeyCode, pker->wVirtualScanCode,
937 abKeystate, awAnsiCode, 2, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000938
939 if (s_iIsDead > 0)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200940 pker->UChar = (WCHAR) awAnsiCode[0];
Bram Moolenaar071d4272004-06-13 20:20:40 +0000941
942 return s_iIsDead;
943}
944
945#ifdef _MSC_VER
946/* MUST switch optimization on again here, otherwise a call to
947 * decode_key_event() may crash (e.g. when hitting caps-lock) */
948# pragma optimize("", on)
Bram Moolenaar7b5f8322006-03-23 22:47:08 +0000949# pragma warning(pop)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000950
951# if (_MSC_VER < 1100)
952/* MUST turn off global optimisation for this next function, or
953 * pressing ctrl-minus in insert mode crashes Vim when built with
954 * VC4.1. -- negri. */
955# pragma optimize("g", off)
956# endif
957#endif
958
959static BOOL g_fJustGotFocus = FALSE;
960
961/*
962 * Decode a KEY_EVENT into one or two keystrokes
963 */
964 static BOOL
965decode_key_event(
966 KEY_EVENT_RECORD *pker,
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200967 WCHAR *pch,
968 WCHAR *pch2,
Bram Moolenaar071d4272004-06-13 20:20:40 +0000969 int *pmodifiers,
970 BOOL fDoPost)
971{
972 int i;
973 const int nModifs = pker->dwControlKeyState & (SHIFT | ALT | CTRL);
974
975 *pch = *pch2 = NUL;
976 g_fJustGotFocus = FALSE;
977
978 /* ignore key up events */
979 if (!pker->bKeyDown)
980 return FALSE;
981
982 /* ignore some keystrokes */
983 switch (pker->wVirtualKeyCode)
984 {
985 /* modifiers */
986 case VK_SHIFT:
987 case VK_CONTROL:
988 case VK_MENU: /* Alt key */
989 return FALSE;
990
991 default:
992 break;
993 }
994
995 /* special cases */
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200996 if ((nModifs & CTRL) != 0 && (nModifs & ~CTRL) == 0 && pker->UChar == NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000997 {
998 /* Ctrl-6 is Ctrl-^ */
999 if (pker->wVirtualKeyCode == '6')
1000 {
1001 *pch = Ctrl_HAT;
1002 return TRUE;
1003 }
1004 /* Ctrl-2 is Ctrl-@ */
1005 else if (pker->wVirtualKeyCode == '2')
1006 {
1007 *pch = NUL;
1008 return TRUE;
1009 }
1010 /* Ctrl-- is Ctrl-_ */
1011 else if (pker->wVirtualKeyCode == 0xBD)
1012 {
1013 *pch = Ctrl__;
1014 return TRUE;
1015 }
1016 }
1017
1018 /* Shift-TAB */
1019 if (pker->wVirtualKeyCode == VK_TAB && (nModifs & SHIFT_PRESSED))
1020 {
1021 *pch = K_NUL;
1022 *pch2 = '\017';
1023 return TRUE;
1024 }
1025
1026 for (i = sizeof(VirtKeyMap) / sizeof(VirtKeyMap[0]); --i >= 0; )
1027 {
1028 if (VirtKeyMap[i].wVirtKey == pker->wVirtualKeyCode)
1029 {
1030 if (nModifs == 0)
1031 *pch = VirtKeyMap[i].chAlone;
1032 else if ((nModifs & SHIFT) != 0 && (nModifs & ~SHIFT) == 0)
1033 *pch = VirtKeyMap[i].chShift;
1034 else if ((nModifs & CTRL) != 0 && (nModifs & ~CTRL) == 0)
1035 *pch = VirtKeyMap[i].chCtrl;
1036 else if ((nModifs & ALT) != 0 && (nModifs & ~ALT) == 0)
1037 *pch = VirtKeyMap[i].chAlt;
1038
1039 if (*pch != 0)
1040 {
1041 if (VirtKeyMap[i].fAnsiKey)
1042 {
1043 *pch2 = *pch;
1044 *pch = K_NUL;
1045 }
1046
1047 return TRUE;
1048 }
1049 }
1050 }
1051
1052 i = win32_kbd_patch_key(pker);
1053
1054 if (i < 0)
1055 *pch = NUL;
1056 else
1057 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001058 *pch = (i > 0) ? pker->UChar : NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001059
1060 if (pmodifiers != NULL)
1061 {
1062 /* Pass on the ALT key as a modifier, but only when not combined
1063 * with CTRL (which is ALTGR). */
1064 if ((nModifs & ALT) != 0 && (nModifs & CTRL) == 0)
1065 *pmodifiers |= MOD_MASK_ALT;
1066
1067 /* Pass on SHIFT only for special keys, because we don't know when
1068 * it's already included with the character. */
1069 if ((nModifs & SHIFT) != 0 && *pch <= 0x20)
1070 *pmodifiers |= MOD_MASK_SHIFT;
1071
1072 /* Pass on CTRL only for non-special keys, because we don't know
1073 * when it's already included with the character. And not when
1074 * combined with ALT (which is ALTGR). */
1075 if ((nModifs & CTRL) != 0 && (nModifs & ALT) == 0
1076 && *pch >= 0x20 && *pch < 0x80)
1077 *pmodifiers |= MOD_MASK_CTRL;
1078 }
1079 }
1080
1081 return (*pch != NUL);
1082}
1083
1084#ifdef _MSC_VER
1085# pragma optimize("", on)
1086#endif
1087
1088#endif /* FEAT_GUI_W32 */
1089
1090
1091#ifdef FEAT_MOUSE
1092
1093/*
1094 * For the GUI the mouse handling is in gui_w32.c.
1095 */
1096# ifdef FEAT_GUI_W32
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00001097/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00001098 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001099mch_setmouse(int on)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001100{
1101}
1102# else
1103static int g_fMouseAvail = FALSE; /* mouse present */
1104static int g_fMouseActive = FALSE; /* mouse enabled */
1105static int g_nMouseClick = -1; /* mouse status */
1106static int g_xMouse; /* mouse x coordinate */
1107static int g_yMouse; /* mouse y coordinate */
1108
1109/*
1110 * Enable or disable mouse input
1111 */
1112 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001113mch_setmouse(int on)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001114{
1115 DWORD cmodein;
1116
1117 if (!g_fMouseAvail)
1118 return;
1119
1120 g_fMouseActive = on;
1121 GetConsoleMode(g_hConIn, &cmodein);
1122
1123 if (g_fMouseActive)
1124 cmodein |= ENABLE_MOUSE_INPUT;
1125 else
1126 cmodein &= ~ENABLE_MOUSE_INPUT;
1127
1128 SetConsoleMode(g_hConIn, cmodein);
1129}
1130
Bram Moolenaar071d4272004-06-13 20:20:40 +00001131/*
1132 * Decode a MOUSE_EVENT. If it's a valid event, return MOUSE_LEFT,
1133 * MOUSE_MIDDLE, or MOUSE_RIGHT for a click; MOUSE_DRAG for a mouse
1134 * move with a button held down; and MOUSE_RELEASE after a MOUSE_DRAG
1135 * or a MOUSE_LEFT, _MIDDLE, or _RIGHT. We encode the button type,
1136 * the number of clicks, and the Shift/Ctrl/Alt modifiers in g_nMouseClick,
1137 * and we return the mouse position in g_xMouse and g_yMouse.
1138 *
1139 * Every MOUSE_LEFT, _MIDDLE, or _RIGHT will be followed by zero or more
1140 * MOUSE_DRAGs and one MOUSE_RELEASE. MOUSE_RELEASE will be followed only
1141 * by MOUSE_LEFT, _MIDDLE, or _RIGHT.
1142 *
1143 * For multiple clicks, we send, say, MOUSE_LEFT/1 click, MOUSE_RELEASE,
1144 * MOUSE_LEFT/2 clicks, MOUSE_RELEASE, MOUSE_LEFT/3 clicks, MOUSE_RELEASE, ....
1145 *
1146 * Windows will send us MOUSE_MOVED notifications whenever the mouse
1147 * moves, even if it stays within the same character cell. We ignore
1148 * all MOUSE_MOVED messages if the position hasn't really changed, and
1149 * we ignore all MOUSE_MOVED messages where no button is held down (i.e.,
1150 * we're only interested in MOUSE_DRAG).
1151 *
1152 * All of this is complicated by the code that fakes MOUSE_MIDDLE on
1153 * 2-button mouses by pressing the left & right buttons simultaneously.
1154 * In practice, it's almost impossible to click both at the same time,
1155 * so we need to delay a little. Also, we tend not to get MOUSE_RELEASE
1156 * in such cases, if the user is clicking quickly.
1157 */
1158 static BOOL
1159decode_mouse_event(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001160 MOUSE_EVENT_RECORD *pmer)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001161{
1162 static int s_nOldButton = -1;
1163 static int s_nOldMouseClick = -1;
1164 static int s_xOldMouse = -1;
1165 static int s_yOldMouse = -1;
1166 static linenr_T s_old_topline = 0;
1167#ifdef FEAT_DIFF
1168 static int s_old_topfill = 0;
1169#endif
1170 static int s_cClicks = 1;
1171 static BOOL s_fReleased = TRUE;
1172 static DWORD s_dwLastClickTime = 0;
1173 static BOOL s_fNextIsMiddle = FALSE;
1174
1175 static DWORD cButtons = 0; /* number of buttons supported */
1176
1177 const DWORD LEFT = FROM_LEFT_1ST_BUTTON_PRESSED;
1178 const DWORD MIDDLE = FROM_LEFT_2ND_BUTTON_PRESSED;
1179 const DWORD RIGHT = RIGHTMOST_BUTTON_PRESSED;
1180 const DWORD LEFT_RIGHT = LEFT | RIGHT;
1181
1182 int nButton;
1183
1184 if (cButtons == 0 && !GetNumberOfConsoleMouseButtons(&cButtons))
1185 cButtons = 2;
1186
1187 if (!g_fMouseAvail || !g_fMouseActive)
1188 {
1189 g_nMouseClick = -1;
1190 return FALSE;
1191 }
1192
1193 /* get a spurious MOUSE_EVENT immediately after receiving focus; ignore */
1194 if (g_fJustGotFocus)
1195 {
1196 g_fJustGotFocus = FALSE;
1197 return FALSE;
1198 }
1199
1200 /* unprocessed mouse click? */
1201 if (g_nMouseClick != -1)
1202 return TRUE;
1203
1204 nButton = -1;
1205 g_xMouse = pmer->dwMousePosition.X;
1206 g_yMouse = pmer->dwMousePosition.Y;
1207
1208 if (pmer->dwEventFlags == MOUSE_MOVED)
1209 {
1210 /* ignore MOUSE_MOVED events if (x, y) hasn't changed. (We get these
1211 * events even when the mouse moves only within a char cell.) */
1212 if (s_xOldMouse == g_xMouse && s_yOldMouse == g_yMouse)
1213 return FALSE;
1214 }
1215
1216 /* If no buttons are pressed... */
1217 if ((pmer->dwButtonState & ((1 << cButtons) - 1)) == 0)
1218 {
1219 /* If the last thing returned was MOUSE_RELEASE, ignore this */
1220 if (s_fReleased)
1221 return FALSE;
1222
1223 nButton = MOUSE_RELEASE;
1224 s_fReleased = TRUE;
1225 }
1226 else /* one or more buttons pressed */
1227 {
1228 /* on a 2-button mouse, hold down left and right buttons
1229 * simultaneously to get MIDDLE. */
1230
1231 if (cButtons == 2 && s_nOldButton != MOUSE_DRAG)
1232 {
1233 DWORD dwLR = (pmer->dwButtonState & LEFT_RIGHT);
1234
1235 /* if either left or right button only is pressed, see if the
Bram Moolenaar84a05ac2013-05-06 04:24:17 +02001236 * next mouse event has both of them pressed */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001237 if (dwLR == LEFT || dwLR == RIGHT)
1238 {
1239 for (;;)
1240 {
1241 /* wait a short time for next input event */
1242 if (WaitForSingleObject(g_hConIn, p_mouset / 3)
1243 != WAIT_OBJECT_0)
1244 break;
1245 else
1246 {
1247 DWORD cRecords = 0;
1248 INPUT_RECORD ir;
1249 MOUSE_EVENT_RECORD* pmer2 = &ir.Event.MouseEvent;
1250
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001251 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001252
1253 if (cRecords == 0 || ir.EventType != MOUSE_EVENT
1254 || !(pmer2->dwButtonState & LEFT_RIGHT))
1255 break;
1256 else
1257 {
1258 if (pmer2->dwEventFlags != MOUSE_MOVED)
1259 {
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001260 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001261
1262 return decode_mouse_event(pmer2);
1263 }
1264 else if (s_xOldMouse == pmer2->dwMousePosition.X &&
1265 s_yOldMouse == pmer2->dwMousePosition.Y)
1266 {
1267 /* throw away spurious mouse move */
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001268 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001269
1270 /* are there any more mouse events in queue? */
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001271 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001272
1273 if (cRecords==0 || ir.EventType != MOUSE_EVENT)
1274 break;
1275 }
1276 else
1277 break;
1278 }
1279 }
1280 }
1281 }
1282 }
1283
1284 if (s_fNextIsMiddle)
1285 {
1286 nButton = (pmer->dwEventFlags == MOUSE_MOVED)
1287 ? MOUSE_DRAG : MOUSE_MIDDLE;
1288 s_fNextIsMiddle = FALSE;
1289 }
1290 else if (cButtons == 2 &&
1291 ((pmer->dwButtonState & LEFT_RIGHT) == LEFT_RIGHT))
1292 {
1293 nButton = MOUSE_MIDDLE;
1294
1295 if (! s_fReleased && pmer->dwEventFlags != MOUSE_MOVED)
1296 {
1297 s_fNextIsMiddle = TRUE;
1298 nButton = MOUSE_RELEASE;
1299 }
1300 }
1301 else if ((pmer->dwButtonState & LEFT) == LEFT)
1302 nButton = MOUSE_LEFT;
1303 else if ((pmer->dwButtonState & MIDDLE) == MIDDLE)
1304 nButton = MOUSE_MIDDLE;
1305 else if ((pmer->dwButtonState & RIGHT) == RIGHT)
1306 nButton = MOUSE_RIGHT;
1307
1308 if (! s_fReleased && ! s_fNextIsMiddle
1309 && nButton != s_nOldButton && s_nOldButton != MOUSE_DRAG)
1310 return FALSE;
1311
1312 s_fReleased = s_fNextIsMiddle;
1313 }
1314
1315 if (pmer->dwEventFlags == 0 || pmer->dwEventFlags == DOUBLE_CLICK)
1316 {
1317 /* button pressed or released, without mouse moving */
1318 if (nButton != -1 && nButton != MOUSE_RELEASE)
1319 {
1320 DWORD dwCurrentTime = GetTickCount();
1321
1322 if (s_xOldMouse != g_xMouse
1323 || s_yOldMouse != g_yMouse
1324 || s_nOldButton != nButton
1325 || s_old_topline != curwin->w_topline
1326#ifdef FEAT_DIFF
1327 || s_old_topfill != curwin->w_topfill
1328#endif
1329 || (int)(dwCurrentTime - s_dwLastClickTime) > p_mouset)
1330 {
1331 s_cClicks = 1;
1332 }
1333 else if (++s_cClicks > 4)
1334 {
1335 s_cClicks = 1;
1336 }
1337
1338 s_dwLastClickTime = dwCurrentTime;
1339 }
1340 }
1341 else if (pmer->dwEventFlags == MOUSE_MOVED)
1342 {
1343 if (nButton != -1 && nButton != MOUSE_RELEASE)
1344 nButton = MOUSE_DRAG;
1345
1346 s_cClicks = 1;
1347 }
1348
1349 if (nButton == -1)
1350 return FALSE;
1351
1352 if (nButton != MOUSE_RELEASE)
1353 s_nOldButton = nButton;
1354
1355 g_nMouseClick = nButton;
1356
1357 if (pmer->dwControlKeyState & SHIFT_PRESSED)
1358 g_nMouseClick |= MOUSE_SHIFT;
1359 if (pmer->dwControlKeyState & (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED))
1360 g_nMouseClick |= MOUSE_CTRL;
1361 if (pmer->dwControlKeyState & (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED))
1362 g_nMouseClick |= MOUSE_ALT;
1363
1364 if (nButton != MOUSE_DRAG && nButton != MOUSE_RELEASE)
1365 SET_NUM_MOUSE_CLICKS(g_nMouseClick, s_cClicks);
1366
1367 /* only pass on interesting (i.e., different) mouse events */
1368 if (s_xOldMouse == g_xMouse
1369 && s_yOldMouse == g_yMouse
1370 && s_nOldMouseClick == g_nMouseClick)
1371 {
1372 g_nMouseClick = -1;
1373 return FALSE;
1374 }
1375
1376 s_xOldMouse = g_xMouse;
1377 s_yOldMouse = g_yMouse;
1378 s_old_topline = curwin->w_topline;
1379#ifdef FEAT_DIFF
1380 s_old_topfill = curwin->w_topfill;
1381#endif
1382 s_nOldMouseClick = g_nMouseClick;
1383
1384 return TRUE;
1385}
1386
1387# endif /* FEAT_GUI_W32 */
1388#endif /* FEAT_MOUSE */
1389
1390
1391#ifdef MCH_CURSOR_SHAPE
1392/*
1393 * Set the shape of the cursor.
1394 * 'thickness' can be from 1 (thin) to 99 (block)
1395 */
1396 static void
1397mch_set_cursor_shape(int thickness)
1398{
1399 CONSOLE_CURSOR_INFO ConsoleCursorInfo;
1400 ConsoleCursorInfo.dwSize = thickness;
1401 ConsoleCursorInfo.bVisible = s_cursor_visible;
1402
1403 SetConsoleCursorInfo(g_hConOut, &ConsoleCursorInfo);
1404 if (s_cursor_visible)
1405 SetConsoleCursorPosition(g_hConOut, g_coord);
1406}
1407
1408 void
1409mch_update_cursor(void)
1410{
1411 int idx;
1412 int thickness;
1413
1414 /*
1415 * How the cursor is drawn depends on the current mode.
1416 */
1417 idx = get_shape_idx(FALSE);
1418
1419 if (shape_table[idx].shape == SHAPE_BLOCK)
1420 thickness = 99; /* 100 doesn't work on W95 */
1421 else
1422 thickness = shape_table[idx].percentage;
1423 mch_set_cursor_shape(thickness);
1424}
1425#endif
1426
1427#ifndef FEAT_GUI_W32 /* this isn't used for the GUI */
1428/*
1429 * Handle FOCUS_EVENT.
1430 */
1431 static void
1432handle_focus_event(INPUT_RECORD ir)
1433{
1434 g_fJustGotFocus = ir.Event.FocusEvent.bSetFocus;
1435 ui_focus_change((int)g_fJustGotFocus);
1436}
1437
1438/*
1439 * Wait until console input from keyboard or mouse is available,
1440 * or the time is up.
1441 * Return TRUE if something is available FALSE if not.
1442 */
1443 static int
1444WaitForChar(long msec)
1445{
1446 DWORD dwNow = 0, dwEndTime = 0;
1447 INPUT_RECORD ir;
1448 DWORD cRecords;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001449 WCHAR ch, ch2;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001450
1451 if (msec > 0)
1452 /* Wait until the specified time has elapsed. */
1453 dwEndTime = GetTickCount() + msec;
1454 else if (msec < 0)
1455 /* Wait forever. */
1456 dwEndTime = INFINITE;
1457
1458 /* We need to loop until the end of the time period, because
1459 * we might get multiple unusable mouse events in that time.
1460 */
1461 for (;;)
1462 {
Bram Moolenaarca568ae2016-02-01 21:32:58 +01001463#ifdef MESSAGE_QUEUE
1464 parse_queued_messages();
1465#endif
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001466#ifdef FEAT_MZSCHEME
1467 mzvim_check_threads();
1468#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001469#ifdef FEAT_CLIENTSERVER
1470 serverProcessPendingMessages();
1471#endif
Bram Moolenaarf12d9832016-01-29 21:11:25 +01001472
Bram Moolenaar071d4272004-06-13 20:20:40 +00001473 if (0
1474#ifdef FEAT_MOUSE
1475 || g_nMouseClick != -1
1476#endif
1477#ifdef FEAT_CLIENTSERVER
1478 || input_available()
1479#endif
1480 )
1481 return TRUE;
1482
1483 if (msec > 0)
1484 {
Bram Moolenaarb7512b72013-08-10 12:45:09 +02001485 /* If the specified wait time has passed, return. Beware that
1486 * GetTickCount() may wrap around (overflow). */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001487 dwNow = GetTickCount();
Bram Moolenaarb7512b72013-08-10 12:45:09 +02001488 if ((int)(dwNow - dwEndTime) >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001489 break;
1490 }
1491 if (msec != 0)
1492 {
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001493 DWORD dwWaitTime = dwEndTime - dwNow;
1494
1495#ifdef FEAT_MZSCHEME
1496 if (mzthreads_allowed() && p_mzq > 0
1497 && (msec < 0 || (long)dwWaitTime > p_mzq))
1498 dwWaitTime = p_mzq; /* don't wait longer than 'mzquantum' */
1499#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001500#ifdef FEAT_CLIENTSERVER
1501 /* Wait for either an event on the console input or a message in
1502 * the client-server window. */
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +02001503 if (msg_wait_for_multiple_objects(1, &g_hConIn, FALSE,
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001504 dwWaitTime, QS_SENDMESSAGE) != WAIT_OBJECT_0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001505#else
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +02001506 if (wait_for_single_object(g_hConIn, dwWaitTime) != WAIT_OBJECT_0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001507#endif
1508 continue;
1509 }
1510
1511 cRecords = 0;
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001512 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001513
1514#ifdef FEAT_MBYTE_IME
1515 if (State & CMDLINE && msg_row == Rows - 1)
1516 {
1517 CONSOLE_SCREEN_BUFFER_INFO csbi;
1518
1519 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
1520 {
1521 if (csbi.dwCursorPosition.Y != msg_row)
1522 {
1523 /* The screen is now messed up, must redraw the
1524 * command line and later all the windows. */
1525 redraw_all_later(CLEAR);
1526 cmdline_row -= (msg_row - csbi.dwCursorPosition.Y);
1527 redrawcmd();
1528 }
1529 }
1530 }
1531#endif
1532
1533 if (cRecords > 0)
1534 {
1535 if (ir.EventType == KEY_EVENT && ir.Event.KeyEvent.bKeyDown)
1536 {
1537#ifdef FEAT_MBYTE_IME
1538 /* Windows IME sends two '\n's with only one 'ENTER'. First:
1539 * wVirtualKeyCode == 13. second: wVirtualKeyCode == 0 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001540 if (ir.Event.KeyEvent.UChar == 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00001541 && ir.Event.KeyEvent.wVirtualKeyCode == 13)
1542 {
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001543 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001544 continue;
1545 }
1546#endif
1547 if (decode_key_event(&ir.Event.KeyEvent, &ch, &ch2,
1548 NULL, FALSE))
1549 return TRUE;
1550 }
1551
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001552 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001553
1554 if (ir.EventType == FOCUS_EVENT)
1555 handle_focus_event(ir);
1556 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
1557 shell_resized();
1558#ifdef FEAT_MOUSE
1559 else if (ir.EventType == MOUSE_EVENT
1560 && decode_mouse_event(&ir.Event.MouseEvent))
1561 return TRUE;
1562#endif
1563 }
1564 else if (msec == 0)
1565 break;
1566 }
1567
1568#ifdef FEAT_CLIENTSERVER
1569 /* Something might have been received while we were waiting. */
1570 if (input_available())
1571 return TRUE;
1572#endif
Bram Moolenaarf12d9832016-01-29 21:11:25 +01001573
Bram Moolenaar071d4272004-06-13 20:20:40 +00001574 return FALSE;
1575}
1576
1577#ifndef FEAT_GUI_MSWIN
1578/*
1579 * return non-zero if a character is available
1580 */
1581 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001582mch_char_avail(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001583{
1584 return WaitForChar(0L);
1585}
1586#endif
1587
1588/*
1589 * Create the console input. Used when reading stdin doesn't work.
1590 */
1591 static void
1592create_conin(void)
1593{
1594 g_hConIn = CreateFile("CONIN$", GENERIC_READ|GENERIC_WRITE,
1595 FILE_SHARE_READ|FILE_SHARE_WRITE,
1596 (LPSECURITY_ATTRIBUTES) NULL,
Bram Moolenaareb3593b2006-04-22 22:33:57 +00001597 OPEN_EXISTING, 0, (HANDLE)NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001598 did_create_conin = TRUE;
1599}
1600
1601/*
1602 * Get a keystroke or a mouse event
1603 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001604 static WCHAR
1605tgetch(int *pmodifiers, WCHAR *pch2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001606{
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001607 WCHAR ch;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001608
1609 for (;;)
1610 {
1611 INPUT_RECORD ir;
1612 DWORD cRecords = 0;
1613
1614#ifdef FEAT_CLIENTSERVER
1615 (void)WaitForChar(-1L);
1616 if (input_available())
1617 return 0;
1618# ifdef FEAT_MOUSE
1619 if (g_nMouseClick != -1)
1620 return 0;
1621# endif
1622#endif
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001623 if (read_console_input(g_hConIn, &ir, 1, &cRecords) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001624 {
1625 if (did_create_conin)
1626 read_error_exit();
1627 create_conin();
1628 continue;
1629 }
1630
1631 if (ir.EventType == KEY_EVENT)
1632 {
1633 if (decode_key_event(&ir.Event.KeyEvent, &ch, pch2,
1634 pmodifiers, TRUE))
1635 return ch;
1636 }
1637 else if (ir.EventType == FOCUS_EVENT)
1638 handle_focus_event(ir);
1639 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
1640 shell_resized();
1641#ifdef FEAT_MOUSE
1642 else if (ir.EventType == MOUSE_EVENT)
1643 {
1644 if (decode_mouse_event(&ir.Event.MouseEvent))
1645 return 0;
1646 }
1647#endif
1648 }
1649}
1650#endif /* !FEAT_GUI_W32 */
1651
1652
1653/*
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02001654 * mch_inchar(): low-level input function.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001655 * Get one or more characters from the keyboard or the mouse.
1656 * If time == 0, do not wait for characters.
1657 * If time == n, wait a short time for characters.
1658 * If time == -1, wait forever for characters.
1659 * Returns the number of characters read into buf.
1660 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00001661/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00001662 int
1663mch_inchar(
1664 char_u *buf,
1665 int maxlen,
1666 long time,
1667 int tb_change_cnt)
1668{
1669#ifndef FEAT_GUI_W32 /* this isn't used for the GUI */
1670
1671 int len;
1672 int c;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001673#define TYPEAHEADLEN 20
1674 static char_u typeahead[TYPEAHEADLEN]; /* previously typed bytes. */
1675 static int typeaheadlen = 0;
1676
1677 /* First use any typeahead that was kept because "buf" was too small. */
1678 if (typeaheadlen > 0)
1679 goto theend;
1680
1681#ifdef FEAT_SNIFF
1682 if (want_sniff_request)
1683 {
1684 if (sniff_request_waiting)
1685 {
1686 /* return K_SNIFF */
1687 typeahead[typeaheadlen++] = CSI;
1688 typeahead[typeaheadlen++] = (char_u)KS_EXTRA;
1689 typeahead[typeaheadlen++] = (char_u)KE_SNIFF;
1690 sniff_request_waiting = 0;
1691 want_sniff_request = 0;
1692 goto theend;
1693 }
1694 else if (time < 0 || time > 250)
1695 {
1696 /* don't wait too long, a request might be pending */
1697 time = 250;
1698 }
1699 }
1700#endif
1701
1702 if (time >= 0)
1703 {
1704 if (!WaitForChar(time)) /* no character available */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001705 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001706 }
1707 else /* time == -1, wait forever */
1708 {
1709 mch_set_winsize_now(); /* Allow winsize changes from now on */
1710
Bram Moolenaar3918c952005-03-15 22:34:55 +00001711 /*
1712 * If there is no character available within 2 seconds (default)
1713 * write the autoscript file to disk. Or cause the CursorHold event
1714 * to be triggered.
1715 */
1716 if (!WaitForChar(p_ut))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001717 {
1718#ifdef FEAT_AUTOCMD
Bram Moolenaard35f9712005-12-18 22:02:33 +00001719 if (trigger_cursorhold() && maxlen >= 3)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001720 {
Bram Moolenaar3918c952005-03-15 22:34:55 +00001721 buf[0] = K_SPECIAL;
1722 buf[1] = KS_EXTRA;
1723 buf[2] = (int)KE_CURSORHOLD;
1724 return 3;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001725 }
1726#endif
Bram Moolenaar702517d2005-06-27 22:34:07 +00001727 before_blocking();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001728 }
1729 }
1730
1731 /*
1732 * Try to read as many characters as there are, until the buffer is full.
1733 */
1734
1735 /* we will get at least one key. Get more if they are available. */
1736 g_fCBrkPressed = FALSE;
1737
1738#ifdef MCH_WRITE_DUMP
1739 if (fdDump)
1740 fputc('[', fdDump);
1741#endif
1742
1743 /* Keep looping until there is something in the typeahead buffer and more
1744 * to get and still room in the buffer (up to two bytes for a char and
1745 * three bytes for a modifier). */
1746 while ((typeaheadlen == 0 || WaitForChar(0L))
1747 && typeaheadlen + 5 <= TYPEAHEADLEN)
1748 {
1749 if (typebuf_changed(tb_change_cnt))
1750 {
1751 /* "buf" may be invalid now if a client put something in the
1752 * typeahead buffer and "buf" is in the typeahead buffer. */
1753 typeaheadlen = 0;
1754 break;
1755 }
1756#ifdef FEAT_MOUSE
1757 if (g_nMouseClick != -1)
1758 {
1759# ifdef MCH_WRITE_DUMP
1760 if (fdDump)
1761 fprintf(fdDump, "{%02x @ %d, %d}",
1762 g_nMouseClick, g_xMouse, g_yMouse);
1763# endif
1764 typeahead[typeaheadlen++] = ESC + 128;
1765 typeahead[typeaheadlen++] = 'M';
1766 typeahead[typeaheadlen++] = g_nMouseClick;
1767 typeahead[typeaheadlen++] = g_xMouse + '!';
1768 typeahead[typeaheadlen++] = g_yMouse + '!';
1769 g_nMouseClick = -1;
1770 }
1771 else
1772#endif
1773 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001774 WCHAR ch2 = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001775 int modifiers = 0;
1776
1777 c = tgetch(&modifiers, &ch2);
1778
1779 if (typebuf_changed(tb_change_cnt))
1780 {
1781 /* "buf" may be invalid now if a client put something in the
1782 * typeahead buffer and "buf" is in the typeahead buffer. */
1783 typeaheadlen = 0;
1784 break;
1785 }
1786
1787 if (c == Ctrl_C && ctrl_c_interrupts)
1788 {
1789#if defined(FEAT_CLIENTSERVER)
1790 trash_input_buf();
1791#endif
1792 got_int = TRUE;
1793 }
1794
1795#ifdef FEAT_MOUSE
1796 if (g_nMouseClick == -1)
1797#endif
1798 {
1799 int n = 1;
Bram Moolenaar45500912014-07-09 20:51:07 +02001800 int conv = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001801
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001802#ifdef FEAT_MBYTE
1803 if (ch2 == NUL)
1804 {
1805 int i;
1806 char_u *p;
1807 WCHAR ch[2];
1808
1809 ch[0] = c;
1810 if (c >= 0xD800 && c <= 0xDBFF) /* High surrogate */
1811 {
1812 ch[1] = tgetch(&modifiers, &ch2);
1813 n++;
1814 }
1815 p = utf16_to_enc(ch, &n);
1816 if (p != NULL)
1817 {
1818 for (i = 0; i < n; i++)
1819 typeahead[typeaheadlen + i] = p[i];
1820 vim_free(p);
1821 }
1822 }
1823 else
1824#endif
1825 typeahead[typeaheadlen] = c;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001826 if (ch2 != NUL)
1827 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001828 typeahead[typeaheadlen + n] = 3;
1829 typeahead[typeaheadlen + n + 1] = (char_u)ch2;
Bram Moolenaar45500912014-07-09 20:51:07 +02001830 n += 2;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001831 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001832
Bram Moolenaar45500912014-07-09 20:51:07 +02001833 if (conv)
1834 {
1835 char_u *p = typeahead + typeaheadlen;
Bram Moolenaar45500912014-07-09 20:51:07 +02001836
Bram Moolenaar1ec4dd42015-01-20 19:39:35 +01001837 if (*p != K_NUL)
Bram Moolenaar45500912014-07-09 20:51:07 +02001838 {
Bram Moolenaar1ec4dd42015-01-20 19:39:35 +01001839 char_u *e = typeahead + TYPEAHEADLEN;
1840
1841 while (*p && p < e)
Bram Moolenaar45500912014-07-09 20:51:07 +02001842 {
Bram Moolenaar1ec4dd42015-01-20 19:39:35 +01001843 if (*p == K_NUL)
1844 {
1845 ++p;
1846 mch_memmove(p + 1, p, ((size_t)(e - p)) - 1);
1847 *p = 3;
1848 ++n;
1849 }
Bram Moolenaar45500912014-07-09 20:51:07 +02001850 ++p;
Bram Moolenaar45500912014-07-09 20:51:07 +02001851 }
Bram Moolenaar45500912014-07-09 20:51:07 +02001852 }
1853 }
1854
Bram Moolenaar071d4272004-06-13 20:20:40 +00001855 /* Use the ALT key to set the 8th bit of the character
1856 * when it's one byte, the 8th bit isn't set yet and not
1857 * using a double-byte encoding (would become a lead
1858 * byte). */
1859 if ((modifiers & MOD_MASK_ALT)
1860 && n == 1
1861 && (typeahead[typeaheadlen] & 0x80) == 0
1862#ifdef FEAT_MBYTE
1863 && !enc_dbcs
1864#endif
1865 )
1866 {
Bram Moolenaar85a3e5c2007-11-20 16:22:16 +00001867#ifdef FEAT_MBYTE
1868 n = (*mb_char2bytes)(typeahead[typeaheadlen] | 0x80,
1869 typeahead + typeaheadlen);
1870#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00001871 typeahead[typeaheadlen] |= 0x80;
Bram Moolenaar85a3e5c2007-11-20 16:22:16 +00001872#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001873 modifiers &= ~MOD_MASK_ALT;
1874 }
1875
1876 if (modifiers != 0)
1877 {
1878 /* Prepend modifiers to the character. */
1879 mch_memmove(typeahead + typeaheadlen + 3,
1880 typeahead + typeaheadlen, n);
1881 typeahead[typeaheadlen++] = K_SPECIAL;
1882 typeahead[typeaheadlen++] = (char_u)KS_MODIFIER;
1883 typeahead[typeaheadlen++] = modifiers;
1884 }
1885
1886 typeaheadlen += n;
1887
1888#ifdef MCH_WRITE_DUMP
1889 if (fdDump)
1890 fputc(c, fdDump);
1891#endif
1892 }
1893 }
1894 }
1895
1896#ifdef MCH_WRITE_DUMP
1897 if (fdDump)
1898 {
1899 fputs("]\n", fdDump);
1900 fflush(fdDump);
1901 }
1902#endif
1903
Bram Moolenaar071d4272004-06-13 20:20:40 +00001904theend:
1905 /* Move typeahead to "buf", as much as fits. */
1906 len = 0;
1907 while (len < maxlen && typeaheadlen > 0)
1908 {
1909 buf[len++] = typeahead[0];
1910 mch_memmove(typeahead, typeahead + 1, --typeaheadlen);
1911 }
1912 return len;
1913
1914#else /* FEAT_GUI_W32 */
1915 return 0;
1916#endif /* FEAT_GUI_W32 */
1917}
1918
Bram Moolenaar82881492012-11-20 16:53:39 +01001919#ifndef PROTO
1920# ifndef __MINGW32__
1921# include <shellapi.h> /* required for FindExecutable() */
1922# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001923#endif
1924
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001925/*
1926 * Return TRUE if "name" is in $PATH.
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00001927 * TODO: Should somehow check if it's really executable.
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001928 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001929 static int
Bram Moolenaarc7f02552014-04-01 21:00:59 +02001930executable_exists(char *name, char_u **path)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001931{
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001932 char *dum;
1933 char fname[_MAX_PATH];
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02001934 char *curpath, *newpath;
1935 long n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001936
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001937#ifdef FEAT_MBYTE
1938 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001939 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01001940 WCHAR *p = enc_to_utf16((char_u *)name, NULL);
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001941 WCHAR fnamew[_MAX_PATH];
1942 WCHAR *dumw;
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02001943 WCHAR *wcurpath, *wnewpath;
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001944
1945 if (p != NULL)
1946 {
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02001947 wcurpath = _wgetenv(L"PATH");
1948 wnewpath = (WCHAR*)alloc((unsigned)(wcslen(wcurpath) + 3)
1949 * sizeof(WCHAR));
1950 if (wnewpath == NULL)
1951 return FALSE;
1952 wcscpy(wnewpath, L".;");
1953 wcscat(wnewpath, wcurpath);
1954 n = (long)SearchPathW(wnewpath, p, NULL, _MAX_PATH, fnamew, &dumw);
1955 vim_free(wnewpath);
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001956 vim_free(p);
1957 if (n > 0 || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
1958 {
1959 if (n == 0)
1960 return FALSE;
1961 if (GetFileAttributesW(fnamew) & FILE_ATTRIBUTE_DIRECTORY)
1962 return FALSE;
Bram Moolenaarc7f02552014-04-01 21:00:59 +02001963 if (path != NULL)
1964 *path = utf16_to_enc(fnamew, NULL);
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001965 return TRUE;
1966 }
1967 /* Retry with non-wide function (for Windows 98). */
1968 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001969 }
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001970#endif
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02001971
1972 curpath = getenv("PATH");
1973 newpath = (char*)alloc((unsigned)(STRLEN(curpath) + 3));
1974 if (newpath == NULL)
1975 return FALSE;
1976 STRCPY(newpath, ".;");
1977 STRCAT(newpath, curpath);
1978 n = (long)SearchPath(newpath, name, NULL, _MAX_PATH, fname, &dum);
1979 vim_free(newpath);
1980 if (n == 0)
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001981 return FALSE;
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01001982 if (mch_isdir((char_u *)fname))
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001983 return FALSE;
Bram Moolenaarc7f02552014-04-01 21:00:59 +02001984 if (path != NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01001985 *path = vim_strsave((char_u *)fname);
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001986 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001987}
1988
Bram Moolenaard32a99a2010-09-21 17:29:23 +02001989#if ((defined(__MINGW32__) || defined (__CYGWIN32__)) && \
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02001990 __MSVCRT_VERSION__ >= 0x800) || (defined(_MSC_VER) && _MSC_VER >= 1400)
Bram Moolenaard32a99a2010-09-21 17:29:23 +02001991/*
1992 * Bad parameter handler.
1993 *
1994 * Certain MS CRT functions will intentionally crash when passed invalid
1995 * parameters to highlight possible security holes. Setting this function as
1996 * the bad parameter handler will prevent the crash.
1997 *
1998 * In debug builds the parameters contain CRT information that might help track
1999 * down the source of a problem, but in non-debug builds the arguments are all
2000 * NULL/0. Debug builds will also produce assert dialogs from the CRT, it is
2001 * worth allowing these to make debugging of issues easier.
2002 */
2003 static void
2004bad_param_handler(const wchar_t *expression,
2005 const wchar_t *function,
2006 const wchar_t *file,
2007 unsigned int line,
2008 uintptr_t pReserved)
2009{
2010}
2011
2012# define SET_INVALID_PARAM_HANDLER \
2013 ((void)_set_invalid_parameter_handler(bad_param_handler))
2014#else
2015# define SET_INVALID_PARAM_HANDLER
2016#endif
2017
Bram Moolenaar071d4272004-06-13 20:20:40 +00002018#ifdef FEAT_GUI_W32
2019
2020/*
2021 * GUI version of mch_init().
2022 */
2023 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002024mch_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002025{
2026#ifndef __MINGW32__
2027 extern int _fmode;
2028#endif
2029
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002030 /* Silently handle invalid parameters to CRT functions */
2031 SET_INVALID_PARAM_HANDLER;
2032
Bram Moolenaar071d4272004-06-13 20:20:40 +00002033 /* Let critical errors result in a failure, not in a dialog box. Required
2034 * for the timestamp test to work on removed floppies. */
2035 SetErrorMode(SEM_FAILCRITICALERRORS);
2036
2037 _fmode = O_BINARY; /* we do our own CR-LF translation */
2038
2039 /* Specify window size. Is there a place to get the default from? */
2040 Rows = 25;
2041 Columns = 80;
2042
2043 /* Look for 'vimrun' */
2044 if (!gui_is_win32s())
2045 {
2046 char_u vimrun_location[_MAX_PATH + 4];
2047
2048 /* First try in same directory as gvim.exe */
2049 STRCPY(vimrun_location, exe_name);
2050 STRCPY(gettail(vimrun_location), "vimrun.exe");
2051 if (mch_getperm(vimrun_location) >= 0)
2052 {
2053 if (*skiptowhite(vimrun_location) != NUL)
2054 {
2055 /* Enclose path with white space in double quotes. */
2056 mch_memmove(vimrun_location + 1, vimrun_location,
2057 STRLEN(vimrun_location) + 1);
2058 *vimrun_location = '"';
2059 STRCPY(gettail(vimrun_location), "vimrun\" ");
2060 }
2061 else
2062 STRCPY(gettail(vimrun_location), "vimrun ");
2063
2064 vimrun_path = (char *)vim_strsave(vimrun_location);
2065 s_dont_use_vimrun = FALSE;
2066 }
Bram Moolenaarc7f02552014-04-01 21:00:59 +02002067 else if (executable_exists("vimrun.exe", NULL))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002068 s_dont_use_vimrun = FALSE;
2069
2070 /* Don't give the warning for a missing vimrun.exe right now, but only
2071 * when vimrun was supposed to be used. Don't bother people that do
2072 * not need vimrun.exe. */
2073 if (s_dont_use_vimrun)
2074 need_vimrun_warning = TRUE;
2075 }
2076
2077 /*
2078 * If "finstr.exe" doesn't exist, use "grep -n" for 'grepprg'.
2079 * Otherwise the default "findstr /n" is used.
2080 */
Bram Moolenaarc7f02552014-04-01 21:00:59 +02002081 if (!executable_exists("findstr.exe", NULL))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002082 set_option_value((char_u *)"grepprg", 0, (char_u *)"grep -n", 0);
2083
2084#ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01002085 win_clip_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002086#endif
2087}
2088
2089
2090#else /* FEAT_GUI_W32 */
2091
2092#define SRWIDTH(sr) ((sr).Right - (sr).Left + 1)
2093#define SRHEIGHT(sr) ((sr).Bottom - (sr).Top + 1)
2094
2095/*
2096 * ClearConsoleBuffer()
2097 * Description:
2098 * Clears the entire contents of the console screen buffer, using the
2099 * specified attribute.
2100 * Returns:
2101 * TRUE on success
2102 */
2103 static BOOL
2104ClearConsoleBuffer(WORD wAttribute)
2105{
2106 CONSOLE_SCREEN_BUFFER_INFO csbi;
2107 COORD coord;
2108 DWORD NumCells, dummy;
2109
2110 if (!GetConsoleScreenBufferInfo(g_hConOut, &csbi))
2111 return FALSE;
2112
2113 NumCells = csbi.dwSize.X * csbi.dwSize.Y;
2114 coord.X = 0;
2115 coord.Y = 0;
2116 if (!FillConsoleOutputCharacter(g_hConOut, ' ', NumCells,
2117 coord, &dummy))
2118 {
2119 return FALSE;
2120 }
2121 if (!FillConsoleOutputAttribute(g_hConOut, wAttribute, NumCells,
2122 coord, &dummy))
2123 {
2124 return FALSE;
2125 }
2126
2127 return TRUE;
2128}
2129
2130/*
2131 * FitConsoleWindow()
2132 * Description:
2133 * Checks if the console window will fit within given buffer dimensions.
2134 * Also, if requested, will shrink the window to fit.
2135 * Returns:
2136 * TRUE on success
2137 */
2138 static BOOL
2139FitConsoleWindow(
2140 COORD dwBufferSize,
2141 BOOL WantAdjust)
2142{
2143 CONSOLE_SCREEN_BUFFER_INFO csbi;
2144 COORD dwWindowSize;
2145 BOOL NeedAdjust = FALSE;
2146
2147 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
2148 {
2149 /*
2150 * A buffer resize will fail if the current console window does
2151 * not lie completely within that buffer. To avoid this, we might
2152 * have to move and possibly shrink the window.
2153 */
2154 if (csbi.srWindow.Right >= dwBufferSize.X)
2155 {
2156 dwWindowSize.X = SRWIDTH(csbi.srWindow);
2157 if (dwWindowSize.X > dwBufferSize.X)
2158 dwWindowSize.X = dwBufferSize.X;
2159 csbi.srWindow.Right = dwBufferSize.X - 1;
2160 csbi.srWindow.Left = dwBufferSize.X - dwWindowSize.X;
2161 NeedAdjust = TRUE;
2162 }
2163 if (csbi.srWindow.Bottom >= dwBufferSize.Y)
2164 {
2165 dwWindowSize.Y = SRHEIGHT(csbi.srWindow);
2166 if (dwWindowSize.Y > dwBufferSize.Y)
2167 dwWindowSize.Y = dwBufferSize.Y;
2168 csbi.srWindow.Bottom = dwBufferSize.Y - 1;
2169 csbi.srWindow.Top = dwBufferSize.Y - dwWindowSize.Y;
2170 NeedAdjust = TRUE;
2171 }
2172 if (NeedAdjust && WantAdjust)
2173 {
2174 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &csbi.srWindow))
2175 return FALSE;
2176 }
2177 return TRUE;
2178 }
2179
2180 return FALSE;
2181}
2182
2183typedef struct ConsoleBufferStruct
2184{
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002185 BOOL IsValid;
2186 CONSOLE_SCREEN_BUFFER_INFO Info;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002187 PCHAR_INFO Buffer;
2188 COORD BufferSize;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002189} ConsoleBuffer;
2190
2191/*
2192 * SaveConsoleBuffer()
2193 * Description:
2194 * Saves important information about the console buffer, including the
2195 * actual buffer contents. The saved information is suitable for later
2196 * restoration by RestoreConsoleBuffer().
2197 * Returns:
2198 * TRUE if all information was saved; FALSE otherwise
2199 * If FALSE, still sets cb->IsValid if buffer characteristics were saved.
2200 */
2201 static BOOL
2202SaveConsoleBuffer(
2203 ConsoleBuffer *cb)
2204{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002205 DWORD NumCells;
2206 COORD BufferCoord;
2207 SMALL_RECT ReadRegion;
2208 WORD Y, Y_incr;
2209
Bram Moolenaar071d4272004-06-13 20:20:40 +00002210 if (cb == NULL)
2211 return FALSE;
2212
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002213 if (!GetConsoleScreenBufferInfo(g_hConOut, &cb->Info))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002214 {
2215 cb->IsValid = FALSE;
2216 return FALSE;
2217 }
2218 cb->IsValid = TRUE;
2219
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002220 /*
2221 * Allocate a buffer large enough to hold the entire console screen
2222 * buffer. If this ConsoleBuffer structure has already been initialized
2223 * with a buffer of the correct size, then just use that one.
2224 */
2225 if (!cb->IsValid || cb->Buffer == NULL ||
2226 cb->BufferSize.X != cb->Info.dwSize.X ||
2227 cb->BufferSize.Y != cb->Info.dwSize.Y)
2228 {
2229 cb->BufferSize.X = cb->Info.dwSize.X;
2230 cb->BufferSize.Y = cb->Info.dwSize.Y;
2231 NumCells = cb->BufferSize.X * cb->BufferSize.Y;
2232 vim_free(cb->Buffer);
2233 cb->Buffer = (PCHAR_INFO)alloc(NumCells * sizeof(CHAR_INFO));
2234 if (cb->Buffer == NULL)
2235 return FALSE;
2236 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002237
2238 /*
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002239 * We will now copy the console screen buffer into our buffer.
2240 * ReadConsoleOutput() seems to be limited as far as how much you
2241 * can read at a time. Empirically, this number seems to be about
2242 * 12000 cells (rows * columns). Start at position (0, 0) and copy
2243 * in chunks until it is all copied. The chunks will all have the
2244 * same horizontal characteristics, so initialize them now. The
2245 * height of each chunk will be (12000 / width).
Bram Moolenaar071d4272004-06-13 20:20:40 +00002246 */
Bram Moolenaar61594242015-09-01 20:23:37 +02002247 BufferCoord.X = 0;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002248 ReadRegion.Left = 0;
2249 ReadRegion.Right = cb->Info.dwSize.X - 1;
2250 Y_incr = 12000 / cb->Info.dwSize.X;
2251 for (Y = 0; Y < cb->BufferSize.Y; Y += Y_incr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002252 {
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002253 /*
2254 * Read into position (0, Y) in our buffer.
2255 */
2256 BufferCoord.Y = Y;
2257 /*
2258 * Read the region whose top left corner is (0, Y) and whose bottom
2259 * right corner is (width - 1, Y + Y_incr - 1). This should define
2260 * a region of size width by Y_incr. Don't worry if this region is
2261 * too large for the remaining buffer; it will be cropped.
2262 */
2263 ReadRegion.Top = Y;
2264 ReadRegion.Bottom = Y + Y_incr - 1;
2265 if (!ReadConsoleOutput(g_hConOut, /* output handle */
2266 cb->Buffer, /* our buffer */
2267 cb->BufferSize, /* dimensions of our buffer */
2268 BufferCoord, /* offset in our buffer */
2269 &ReadRegion)) /* region to save */
2270 {
2271 vim_free(cb->Buffer);
2272 cb->Buffer = NULL;
2273 return FALSE;
2274 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002275 }
2276
2277 return TRUE;
2278}
2279
2280/*
2281 * RestoreConsoleBuffer()
2282 * Description:
2283 * Restores important information about the console buffer, including the
2284 * actual buffer contents, if desired. The information to restore is in
2285 * the same format used by SaveConsoleBuffer().
2286 * Returns:
2287 * TRUE on success
2288 */
2289 static BOOL
2290RestoreConsoleBuffer(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002291 ConsoleBuffer *cb,
2292 BOOL RestoreScreen)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002293{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002294 COORD BufferCoord;
2295 SMALL_RECT WriteRegion;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002296
2297 if (cb == NULL || !cb->IsValid)
2298 return FALSE;
2299
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002300 /*
2301 * Before restoring the buffer contents, clear the current buffer, and
2302 * restore the cursor position and window information. Doing this now
2303 * prevents old buffer contents from "flashing" onto the screen.
2304 */
2305 if (RestoreScreen)
2306 ClearConsoleBuffer(cb->Info.wAttributes);
2307
2308 FitConsoleWindow(cb->Info.dwSize, TRUE);
2309 if (!SetConsoleScreenBufferSize(g_hConOut, cb->Info.dwSize))
2310 return FALSE;
2311 if (!SetConsoleTextAttribute(g_hConOut, cb->Info.wAttributes))
2312 return FALSE;
2313
2314 if (!RestoreScreen)
2315 {
2316 /*
2317 * No need to restore the screen buffer contents, so we're done.
2318 */
2319 return TRUE;
2320 }
2321
2322 if (!SetConsoleCursorPosition(g_hConOut, cb->Info.dwCursorPosition))
2323 return FALSE;
2324 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &cb->Info.srWindow))
2325 return FALSE;
2326
2327 /*
2328 * Restore the screen buffer contents.
2329 */
2330 if (cb->Buffer != NULL)
2331 {
2332 BufferCoord.X = 0;
2333 BufferCoord.Y = 0;
2334 WriteRegion.Left = 0;
2335 WriteRegion.Top = 0;
2336 WriteRegion.Right = cb->Info.dwSize.X - 1;
2337 WriteRegion.Bottom = cb->Info.dwSize.Y - 1;
2338 if (!WriteConsoleOutput(g_hConOut, /* output handle */
2339 cb->Buffer, /* our buffer */
2340 cb->BufferSize, /* dimensions of our buffer */
2341 BufferCoord, /* offset in our buffer */
2342 &WriteRegion)) /* region to restore */
2343 {
2344 return FALSE;
2345 }
2346 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002347
2348 return TRUE;
2349}
2350
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002351#define FEAT_RESTORE_ORIG_SCREEN
2352#ifdef FEAT_RESTORE_ORIG_SCREEN
2353static ConsoleBuffer g_cbOrig = { 0 };
2354#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002355static ConsoleBuffer g_cbNonTermcap = { 0 };
2356static ConsoleBuffer g_cbTermcap = { 0 };
2357
2358#ifdef FEAT_TITLE
2359#ifdef __BORLANDC__
2360typedef HWND (__stdcall *GETCONSOLEWINDOWPROC)(VOID);
2361#else
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002362typedef HWND (WINAPI *GETCONSOLEWINDOWPROC)(VOID);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002363#endif
2364char g_szOrigTitle[256] = { 0 };
2365HWND g_hWnd = NULL; /* also used in os_mswin.c */
2366static HICON g_hOrigIconSmall = NULL;
2367static HICON g_hOrigIcon = NULL;
2368static HICON g_hVimIcon = NULL;
2369static BOOL g_fCanChangeIcon = FALSE;
2370
2371/* ICON* are not defined in VC++ 4.0 */
2372#ifndef ICON_SMALL
2373#define ICON_SMALL 0
2374#endif
2375#ifndef ICON_BIG
2376#define ICON_BIG 1
2377#endif
2378/*
2379 * GetConsoleIcon()
2380 * Description:
2381 * Attempts to retrieve the small icon and/or the big icon currently in
2382 * use by a given window.
2383 * Returns:
2384 * TRUE on success
2385 */
2386 static BOOL
2387GetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002388 HWND hWnd,
2389 HICON *phIconSmall,
2390 HICON *phIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002391{
2392 if (hWnd == NULL)
2393 return FALSE;
2394
2395 if (phIconSmall != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002396 *phIconSmall = (HICON)SendMessage(hWnd, WM_GETICON,
2397 (WPARAM)ICON_SMALL, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002398 if (phIcon != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002399 *phIcon = (HICON)SendMessage(hWnd, WM_GETICON,
2400 (WPARAM)ICON_BIG, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002401 return TRUE;
2402}
2403
2404/*
2405 * SetConsoleIcon()
2406 * Description:
2407 * Attempts to change the small icon and/or the big icon currently in
2408 * use by a given window.
2409 * Returns:
2410 * TRUE on success
2411 */
2412 static BOOL
2413SetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002414 HWND hWnd,
2415 HICON hIconSmall,
2416 HICON hIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002417{
Bram Moolenaar071d4272004-06-13 20:20:40 +00002418 if (hWnd == NULL)
2419 return FALSE;
2420
2421 if (hIconSmall != NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002422 SendMessage(hWnd, WM_SETICON,
2423 (WPARAM)ICON_SMALL, (LPARAM)hIconSmall);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002424 if (hIcon != NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002425 SendMessage(hWnd, WM_SETICON,
2426 (WPARAM)ICON_BIG, (LPARAM) hIcon);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002427 return TRUE;
2428}
2429
2430/*
2431 * SaveConsoleTitleAndIcon()
2432 * Description:
2433 * Saves the current console window title in g_szOrigTitle, for later
2434 * restoration. Also, attempts to obtain a handle to the console window,
2435 * and use it to save the small and big icons currently in use by the
2436 * console window. This is not always possible on some versions of Windows;
2437 * nor is it possible when running Vim remotely using Telnet (since the
2438 * console window the user sees is owned by a remote process).
2439 */
2440 static void
2441SaveConsoleTitleAndIcon(void)
2442{
2443 GETCONSOLEWINDOWPROC GetConsoleWindowProc;
2444
2445 /* Save the original title. */
2446 if (!GetConsoleTitle(g_szOrigTitle, sizeof(g_szOrigTitle)))
2447 return;
2448
2449 /*
2450 * Obtain a handle to the console window using GetConsoleWindow() from
2451 * KERNEL32.DLL; we need to handle in order to change the window icon.
2452 * This function only exists on NT-based Windows, starting with Windows
2453 * 2000. On older operating systems, we can't change the window icon
2454 * anyway.
2455 */
2456 if ((GetConsoleWindowProc = (GETCONSOLEWINDOWPROC)
2457 GetProcAddress(GetModuleHandle("KERNEL32.DLL"),
2458 "GetConsoleWindow")) != NULL)
2459 {
2460 g_hWnd = (*GetConsoleWindowProc)();
2461 }
2462 if (g_hWnd == NULL)
2463 return;
2464
2465 /* Save the original console window icon. */
2466 GetConsoleIcon(g_hWnd, &g_hOrigIconSmall, &g_hOrigIcon);
2467 if (g_hOrigIconSmall == NULL || g_hOrigIcon == NULL)
2468 return;
2469
2470 /* Extract the first icon contained in the Vim executable. */
Bram Moolenaarcddc91c2014-09-23 21:53:41 +02002471 if (mch_icon_load((HANDLE *)&g_hVimIcon) == FAIL || g_hVimIcon == NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002472 g_hVimIcon = ExtractIcon(NULL, (LPCSTR)exe_name, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002473 if (g_hVimIcon != NULL)
2474 g_fCanChangeIcon = TRUE;
2475}
2476#endif
2477
2478static int g_fWindInitCalled = FALSE;
2479static int g_fTermcapMode = FALSE;
2480static CONSOLE_CURSOR_INFO g_cci;
2481static DWORD g_cmodein = 0;
2482static DWORD g_cmodeout = 0;
2483
2484/*
2485 * non-GUI version of mch_init().
2486 */
2487 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002488mch_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002489{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002490#ifndef FEAT_RESTORE_ORIG_SCREEN
2491 CONSOLE_SCREEN_BUFFER_INFO csbi;
2492#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002493#ifndef __MINGW32__
2494 extern int _fmode;
2495#endif
2496
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002497 /* Silently handle invalid parameters to CRT functions */
2498 SET_INVALID_PARAM_HANDLER;
2499
Bram Moolenaar071d4272004-06-13 20:20:40 +00002500 /* Let critical errors result in a failure, not in a dialog box. Required
2501 * for the timestamp test to work on removed floppies. */
2502 SetErrorMode(SEM_FAILCRITICALERRORS);
2503
2504 _fmode = O_BINARY; /* we do our own CR-LF translation */
2505 out_flush();
2506
2507 /* Obtain handles for the standard Console I/O devices */
2508 if (read_cmd_fd == 0)
2509 g_hConIn = GetStdHandle(STD_INPUT_HANDLE);
2510 else
2511 create_conin();
2512 g_hConOut = GetStdHandle(STD_OUTPUT_HANDLE);
2513
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002514#ifdef FEAT_RESTORE_ORIG_SCREEN
2515 /* Save the initial console buffer for later restoration */
2516 SaveConsoleBuffer(&g_cbOrig);
2517 g_attrCurrent = g_attrDefault = g_cbOrig.Info.wAttributes;
2518#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00002519 /* Get current text attributes */
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002520 GetConsoleScreenBufferInfo(g_hConOut, &csbi);
2521 g_attrCurrent = g_attrDefault = csbi.wAttributes;
2522#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002523 if (cterm_normal_fg_color == 0)
2524 cterm_normal_fg_color = (g_attrCurrent & 0xf) + 1;
2525 if (cterm_normal_bg_color == 0)
2526 cterm_normal_bg_color = ((g_attrCurrent >> 4) & 0xf) + 1;
2527
2528 /* set termcap codes to current text attributes */
2529 update_tcap(g_attrCurrent);
2530
2531 GetConsoleCursorInfo(g_hConOut, &g_cci);
2532 GetConsoleMode(g_hConIn, &g_cmodein);
2533 GetConsoleMode(g_hConOut, &g_cmodeout);
2534
2535#ifdef FEAT_TITLE
2536 SaveConsoleTitleAndIcon();
2537 /*
2538 * Set both the small and big icons of the console window to Vim's icon.
2539 * Note that Vim presently only has one size of icon (32x32), but it
2540 * automatically gets scaled down to 16x16 when setting the small icon.
2541 */
2542 if (g_fCanChangeIcon)
2543 SetConsoleIcon(g_hWnd, g_hVimIcon, g_hVimIcon);
2544#endif
2545
2546 ui_get_shellsize();
2547
2548#ifdef MCH_WRITE_DUMP
2549 fdDump = fopen("dump", "wt");
2550
2551 if (fdDump)
2552 {
2553 time_t t;
2554
2555 time(&t);
2556 fputs(ctime(&t), fdDump);
2557 fflush(fdDump);
2558 }
2559#endif
2560
2561 g_fWindInitCalled = TRUE;
2562
2563#ifdef FEAT_MOUSE
2564 g_fMouseAvail = GetSystemMetrics(SM_MOUSEPRESENT);
2565#endif
2566
2567#ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01002568 win_clip_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002569#endif
2570
2571 /* This will be NULL on anything but NT 4.0 */
2572 s_pfnGetConsoleKeyboardLayoutName =
2573 (PFNGCKLN) GetProcAddress(GetModuleHandle("kernel32.dll"),
2574 "GetConsoleKeyboardLayoutNameA");
2575}
2576
2577/*
2578 * non-GUI version of mch_exit().
2579 * Shut down and exit with status `r'
2580 * Careful: mch_exit() may be called before mch_init()!
2581 */
2582 void
2583mch_exit(int r)
2584{
2585 stoptermcap();
2586
2587 if (g_fWindInitCalled)
2588 settmode(TMODE_COOK);
2589
2590 ml_close_all(TRUE); /* remove all memfiles */
2591
2592 if (g_fWindInitCalled)
2593 {
2594#ifdef FEAT_TITLE
2595 mch_restore_title(3);
2596 /*
2597 * Restore both the small and big icons of the console window to
2598 * what they were at startup. Don't do this when the window is
2599 * closed, Vim would hang here.
2600 */
2601 if (g_fCanChangeIcon && !g_fForceExit)
2602 SetConsoleIcon(g_hWnd, g_hOrigIconSmall, g_hOrigIcon);
2603#endif
2604
2605#ifdef MCH_WRITE_DUMP
2606 if (fdDump)
2607 {
2608 time_t t;
2609
2610 time(&t);
2611 fputs(ctime(&t), fdDump);
2612 fclose(fdDump);
2613 }
2614 fdDump = NULL;
2615#endif
2616 }
2617
2618 SetConsoleCursorInfo(g_hConOut, &g_cci);
2619 SetConsoleMode(g_hConIn, g_cmodein);
2620 SetConsoleMode(g_hConOut, g_cmodeout);
2621
2622#ifdef DYNAMIC_GETTEXT
2623 dyn_libintl_end();
2624#endif
2625
2626 exit(r);
2627}
2628#endif /* !FEAT_GUI_W32 */
2629
Bram Moolenaar071d4272004-06-13 20:20:40 +00002630/*
2631 * Do we have an interactive window?
2632 */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00002633/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00002634 int
2635mch_check_win(
2636 int argc,
2637 char **argv)
2638{
2639 get_exe_name();
2640
2641#ifdef FEAT_GUI_W32
2642 return OK; /* GUI always has a tty */
2643#else
2644 if (isatty(1))
2645 return OK;
2646 return FAIL;
2647#endif
2648}
2649
2650
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002651#ifdef FEAT_MBYTE
2652/*
2653 * fname_casew(): Wide version of fname_case(). Set the case of the file name,
2654 * if it already exists. When "len" is > 0, also expand short to long
2655 * filenames.
2656 * Return FAIL if wide functions are not available, OK otherwise.
2657 * NOTE: much of this is identical to fname_case(), keep in sync!
2658 */
2659 static int
2660fname_casew(
2661 WCHAR *name,
2662 int len)
2663{
2664 WCHAR szTrueName[_MAX_PATH + 2];
2665 WCHAR szTrueNameTemp[_MAX_PATH + 2];
2666 WCHAR *ptrue, *ptruePrev;
2667 WCHAR *porig, *porigPrev;
2668 int flen;
2669 WIN32_FIND_DATAW fb;
Bram Moolenaar73c61632013-12-07 14:48:10 +01002670 HANDLE hFind = INVALID_HANDLE_VALUE;
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002671 int c;
2672 int slen;
2673
2674 flen = (int)wcslen(name);
2675 if (flen > _MAX_PATH)
2676 return OK;
2677
2678 /* slash_adjust(name) not needed, already adjusted by fname_case(). */
2679
2680 /* Build the new name in szTrueName[] one component at a time. */
2681 porig = name;
2682 ptrue = szTrueName;
2683
2684 if (iswalpha(porig[0]) && porig[1] == L':')
2685 {
2686 /* copy leading drive letter */
2687 *ptrue++ = *porig++;
2688 *ptrue++ = *porig++;
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002689 }
Bram Moolenaar73c61632013-12-07 14:48:10 +01002690 *ptrue = NUL; /* in case nothing follows */
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002691
2692 while (*porig != NUL)
2693 {
2694 /* copy \ characters */
2695 while (*porig == psepc)
2696 *ptrue++ = *porig++;
2697
2698 ptruePrev = ptrue;
2699 porigPrev = porig;
2700 while (*porig != NUL && *porig != psepc)
2701 {
2702 *ptrue++ = *porig++;
2703 }
2704 *ptrue = NUL;
2705
2706 /* To avoid a slow failure append "\*" when searching a directory,
2707 * server or network share. */
2708 wcscpy(szTrueNameTemp, szTrueName);
2709 slen = (int)wcslen(szTrueNameTemp);
2710 if (*porig == psepc && slen + 2 < _MAX_PATH)
2711 wcscpy(szTrueNameTemp + slen, L"\\*");
2712
2713 /* Skip "", "." and "..". */
2714 if (ptrue > ptruePrev
2715 && (ptruePrev[0] != L'.'
2716 || (ptruePrev[1] != NUL
2717 && (ptruePrev[1] != L'.' || ptruePrev[2] != NUL)))
2718 && (hFind = FindFirstFileW(szTrueNameTemp, &fb))
2719 != INVALID_HANDLE_VALUE)
2720 {
2721 c = *porig;
2722 *porig = NUL;
2723
2724 /* Only use the match when it's the same name (ignoring case) or
2725 * expansion is allowed and there is a match with the short name
2726 * and there is enough room. */
2727 if (_wcsicoll(porigPrev, fb.cFileName) == 0
2728 || (len > 0
2729 && (_wcsicoll(porigPrev, fb.cAlternateFileName) == 0
2730 && (int)(ptruePrev - szTrueName)
2731 + (int)wcslen(fb.cFileName) < len)))
2732 {
2733 wcscpy(ptruePrev, fb.cFileName);
2734
2735 /* Look for exact match and prefer it if found. Must be a
2736 * long name, otherwise there would be only one match. */
2737 while (FindNextFileW(hFind, &fb))
2738 {
2739 if (*fb.cAlternateFileName != NUL
2740 && (wcscoll(porigPrev, fb.cFileName) == 0
2741 || (len > 0
2742 && (_wcsicoll(porigPrev,
2743 fb.cAlternateFileName) == 0
2744 && (int)(ptruePrev - szTrueName)
2745 + (int)wcslen(fb.cFileName) < len))))
2746 {
2747 wcscpy(ptruePrev, fb.cFileName);
2748 break;
2749 }
2750 }
2751 }
2752 FindClose(hFind);
2753 *porig = c;
2754 ptrue = ptruePrev + wcslen(ptruePrev);
2755 }
2756 else if (hFind == INVALID_HANDLE_VALUE
2757 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
2758 return FAIL;
2759 }
2760
2761 wcscpy(name, szTrueName);
2762 return OK;
2763}
2764#endif
2765
Bram Moolenaar071d4272004-06-13 20:20:40 +00002766/*
2767 * fname_case(): Set the case of the file name, if it already exists.
2768 * When "len" is > 0, also expand short to long filenames.
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002769 * NOTE: much of this is identical to fname_casew(), keep in sync!
Bram Moolenaar071d4272004-06-13 20:20:40 +00002770 */
2771 void
2772fname_case(
2773 char_u *name,
2774 int len)
2775{
2776 char szTrueName[_MAX_PATH + 2];
Bram Moolenaar464c9252010-10-13 20:37:41 +02002777 char szTrueNameTemp[_MAX_PATH + 2];
Bram Moolenaar071d4272004-06-13 20:20:40 +00002778 char *ptrue, *ptruePrev;
2779 char *porig, *porigPrev;
2780 int flen;
2781 WIN32_FIND_DATA fb;
2782 HANDLE hFind;
2783 int c;
Bram Moolenaar464c9252010-10-13 20:37:41 +02002784 int slen;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002785
Bram Moolenaara3ffd9c2005-07-21 21:03:15 +00002786 flen = (int)STRLEN(name);
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002787 if (flen == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002788 return;
2789
2790 slash_adjust(name);
2791
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002792#ifdef FEAT_MBYTE
2793 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2794 {
2795 WCHAR *p = enc_to_utf16(name, NULL);
2796
2797 if (p != NULL)
2798 {
2799 char_u *q;
Bram Moolenaar21d89b62014-10-07 10:38:40 +02002800 WCHAR buf[_MAX_PATH + 1];
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002801
Bram Moolenaar21d89b62014-10-07 10:38:40 +02002802 wcsncpy(buf, p, _MAX_PATH);
2803 buf[_MAX_PATH] = L'\0';
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002804 vim_free(p);
2805
2806 if (fname_casew(buf, (len > 0) ? _MAX_PATH : 0) == OK)
2807 {
2808 q = utf16_to_enc(buf, NULL);
2809 if (q != NULL)
2810 {
2811 vim_strncpy(name, q, (len > 0) ? len - 1 : flen);
2812 vim_free(q);
2813 return;
2814 }
2815 }
2816 }
2817 /* Retry with non-wide function (for Windows 98). */
2818 }
2819#endif
2820
2821 /* If 'enc' is utf-8, flen can be larger than _MAX_PATH.
2822 * So we should check this after calling wide function. */
2823 if (flen > _MAX_PATH)
2824 return;
2825
Bram Moolenaar071d4272004-06-13 20:20:40 +00002826 /* Build the new name in szTrueName[] one component at a time. */
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002827 porig = (char *)name;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002828 ptrue = szTrueName;
2829
2830 if (isalpha(porig[0]) && porig[1] == ':')
2831 {
2832 /* copy leading drive letter */
2833 *ptrue++ = *porig++;
2834 *ptrue++ = *porig++;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002835 }
Bram Moolenaar73c61632013-12-07 14:48:10 +01002836 *ptrue = NUL; /* in case nothing follows */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002837
2838 while (*porig != NUL)
2839 {
2840 /* copy \ characters */
2841 while (*porig == psepc)
2842 *ptrue++ = *porig++;
2843
2844 ptruePrev = ptrue;
2845 porigPrev = porig;
2846 while (*porig != NUL && *porig != psepc)
2847 {
2848#ifdef FEAT_MBYTE
2849 int l;
2850
2851 if (enc_dbcs)
2852 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002853 l = (*mb_ptr2len)((char_u *)porig);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002854 while (--l >= 0)
2855 *ptrue++ = *porig++;
2856 }
2857 else
2858#endif
2859 *ptrue++ = *porig++;
2860 }
2861 *ptrue = NUL;
2862
Bram Moolenaar464c9252010-10-13 20:37:41 +02002863 /* To avoid a slow failure append "\*" when searching a directory,
2864 * server or network share. */
2865 STRCPY(szTrueNameTemp, szTrueName);
Bram Moolenaar6b5ef062010-10-27 12:18:00 +02002866 slen = (int)strlen(szTrueNameTemp);
Bram Moolenaar464c9252010-10-13 20:37:41 +02002867 if (*porig == psepc && slen + 2 < _MAX_PATH)
2868 STRCPY(szTrueNameTemp + slen, "\\*");
2869
Bram Moolenaar071d4272004-06-13 20:20:40 +00002870 /* Skip "", "." and "..". */
2871 if (ptrue > ptruePrev
2872 && (ptruePrev[0] != '.'
2873 || (ptruePrev[1] != NUL
2874 && (ptruePrev[1] != '.' || ptruePrev[2] != NUL)))
Bram Moolenaar464c9252010-10-13 20:37:41 +02002875 && (hFind = FindFirstFile(szTrueNameTemp, &fb))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002876 != INVALID_HANDLE_VALUE)
2877 {
2878 c = *porig;
2879 *porig = NUL;
2880
2881 /* Only use the match when it's the same name (ignoring case) or
2882 * expansion is allowed and there is a match with the short name
2883 * and there is enough room. */
2884 if (_stricoll(porigPrev, fb.cFileName) == 0
2885 || (len > 0
2886 && (_stricoll(porigPrev, fb.cAlternateFileName) == 0
2887 && (int)(ptruePrev - szTrueName)
2888 + (int)strlen(fb.cFileName) < len)))
2889 {
2890 STRCPY(ptruePrev, fb.cFileName);
2891
2892 /* Look for exact match and prefer it if found. Must be a
2893 * long name, otherwise there would be only one match. */
2894 while (FindNextFile(hFind, &fb))
2895 {
2896 if (*fb.cAlternateFileName != NUL
2897 && (strcoll(porigPrev, fb.cFileName) == 0
2898 || (len > 0
2899 && (_stricoll(porigPrev,
2900 fb.cAlternateFileName) == 0
2901 && (int)(ptruePrev - szTrueName)
2902 + (int)strlen(fb.cFileName) < len))))
2903 {
2904 STRCPY(ptruePrev, fb.cFileName);
2905 break;
2906 }
2907 }
2908 }
2909 FindClose(hFind);
2910 *porig = c;
2911 ptrue = ptruePrev + strlen(ptruePrev);
2912 }
2913 }
2914
2915 STRCPY(name, szTrueName);
2916}
2917
2918
2919/*
2920 * Insert user name in s[len].
2921 */
2922 int
2923mch_get_user_name(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002924 char_u *s,
2925 int len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002926{
Bram Moolenaar41a09032007-10-01 18:34:34 +00002927 char szUserName[256 + 1]; /* UNLEN is 256 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002928 DWORD cch = sizeof szUserName;
2929
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01002930#ifdef FEAT_MBYTE
2931 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2932 {
2933 WCHAR wszUserName[256 + 1]; /* UNLEN is 256 */
2934 DWORD wcch = sizeof(wszUserName) / sizeof(WCHAR);
2935
2936 if (GetUserNameW(wszUserName, &wcch))
2937 {
2938 char_u *p = utf16_to_enc(wszUserName, NULL);
2939
2940 if (p != NULL)
2941 {
2942 vim_strncpy(s, p, len - 1);
2943 vim_free(p);
2944 return OK;
2945 }
2946 }
Bram Moolenaarcd981f22014-02-11 17:06:00 +01002947 else if (GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
2948 return FAIL;
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01002949 /* Retry with non-wide function (for Windows 98). */
2950 }
2951#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002952 if (GetUserName(szUserName, &cch))
2953 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002954 vim_strncpy(s, (char_u *)szUserName, len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002955 return OK;
2956 }
2957 s[0] = NUL;
2958 return FAIL;
2959}
2960
2961
2962/*
2963 * Insert host name in s[len].
2964 */
2965 void
2966mch_get_host_name(
2967 char_u *s,
2968 int len)
2969{
2970 DWORD cch = len;
2971
Bram Moolenaar2cc87382013-12-11 18:21:45 +01002972#ifdef FEAT_MBYTE
2973 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2974 {
2975 WCHAR wszHostName[256 + 1];
2976 DWORD wcch = sizeof(wszHostName) / sizeof(WCHAR);
2977
2978 if (GetComputerNameW(wszHostName, &wcch))
2979 {
2980 char_u *p = utf16_to_enc(wszHostName, NULL);
2981
2982 if (p != NULL)
2983 {
2984 vim_strncpy(s, p, len - 1);
2985 vim_free(p);
2986 return;
2987 }
2988 }
Bram Moolenaarcd981f22014-02-11 17:06:00 +01002989 else if (GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
2990 return;
Bram Moolenaar2cc87382013-12-11 18:21:45 +01002991 /* Retry with non-wide function (for Windows 98). */
2992 }
2993#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002994 if (!GetComputerName((LPSTR)s, &cch))
2995 vim_strncpy(s, (char_u *)"PC (Win32 Vim)", len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002996}
2997
2998
2999/*
3000 * return process ID
3001 */
3002 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003003mch_get_pid(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003004{
3005 return (long)GetCurrentProcessId();
3006}
3007
3008
3009/*
3010 * Get name of current directory into buffer 'buf' of length 'len' bytes.
3011 * Return OK for success, FAIL for failure.
3012 */
3013 int
3014mch_dirname(
3015 char_u *buf,
3016 int len)
3017{
3018 /*
3019 * Originally this was:
3020 * return (getcwd(buf, len) != NULL ? OK : FAIL);
3021 * But the Win32s known bug list says that getcwd() doesn't work
3022 * so use the Win32 system call instead. <Negri>
3023 */
3024#ifdef FEAT_MBYTE
3025 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3026 {
3027 WCHAR wbuf[_MAX_PATH + 1];
3028
3029 if (GetCurrentDirectoryW(_MAX_PATH, wbuf) != 0)
3030 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00003031 char_u *p = utf16_to_enc(wbuf, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003032
3033 if (p != NULL)
3034 {
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00003035 vim_strncpy(buf, p, len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003036 vim_free(p);
3037 return OK;
3038 }
3039 }
Bram Moolenaarcd981f22014-02-11 17:06:00 +01003040 else if (GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
3041 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003042 /* Retry with non-wide function (for Windows 98). */
3043 }
3044#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003045 return (GetCurrentDirectory(len, (LPSTR)buf) != 0 ? OK : FAIL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003046}
3047
3048/*
Bram Moolenaarffa22202013-11-21 12:34:11 +01003049 * Get file permissions for "name".
3050 * Return mode_t or -1 for error.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003051 */
3052 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003053mch_getperm(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003054{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003055 struct stat st;
Bram Moolenaarffa22202013-11-21 12:34:11 +01003056 int n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003057
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003058 n = mch_stat((char *)name, &st);
Bram Moolenaar78cf3f02014-01-10 18:16:07 +01003059 return n == 0 ? (long)(unsigned short)st.st_mode : -1L;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003060}
3061
3062
3063/*
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003064 * Set file permission for "name" to "perm".
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003065 *
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003066 * Return FAIL for failure, OK otherwise.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003067 */
3068 int
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003069mch_setperm(char_u *name, long perm)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003070{
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003071 long n = -1;
3072
Bram Moolenaar071d4272004-06-13 20:20:40 +00003073#ifdef FEAT_MBYTE
3074 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3075 {
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003076 WCHAR *p = enc_to_utf16(name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003077
3078 if (p != NULL)
3079 {
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003080 n = _wchmod(p, perm);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003081 vim_free(p);
Bram Moolenaarcd981f22014-02-11 17:06:00 +01003082 if (n == -1 && g_PlatformId == VER_PLATFORM_WIN32_NT)
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003083 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003084 /* Retry with non-wide function (for Windows 98). */
3085 }
3086 }
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003087 if (n == -1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003088#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003089 n = _chmod((const char *)name, perm);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003090 if (n == -1)
3091 return FAIL;
3092
3093 win32_set_archive(name);
3094
3095 return OK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003096}
3097
3098/*
3099 * Set hidden flag for "name".
3100 */
3101 void
3102mch_hide(char_u *name)
3103{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003104 int attrs = win32_getattrs(name);
3105 if (attrs == -1)
3106 return;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003107
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003108 attrs |= FILE_ATTRIBUTE_HIDDEN;
3109 win32_setattrs(name, attrs);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003110}
3111
3112/*
Bram Moolenaar8a52ba72015-11-02 14:45:56 +01003113 * Return TRUE if file "name" exists and is hidden.
3114 */
3115 int
3116mch_ishidden(char_u *name)
3117{
3118 int f = win32_getattrs(name);
3119
3120 if (f == -1)
3121 return FALSE; /* file does not exist at all */
3122
3123 return (f & FILE_ATTRIBUTE_HIDDEN) != 0;
3124}
3125
3126/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003127 * return TRUE if "name" is a directory
3128 * return FALSE if "name" is not a directory or upon error
3129 */
3130 int
3131mch_isdir(char_u *name)
3132{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003133 int f = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003134
3135 if (f == -1)
3136 return FALSE; /* file does not exist at all */
3137
3138 return (f & FILE_ATTRIBUTE_DIRECTORY) != 0;
3139}
3140
3141/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01003142 * return TRUE if "name" is a directory, NOT a symlink to a directory
3143 * return FALSE if "name" is not a directory
3144 * return FALSE for error
3145 */
3146 int
3147mch_isrealdir(char_u *name)
3148{
3149 return mch_isdir(name) && !mch_is_symbolic_link(name);
3150}
3151
3152/*
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003153 * Create directory "name".
3154 * Return 0 on success, -1 on error.
3155 */
3156 int
3157mch_mkdir(char_u *name)
3158{
3159#ifdef FEAT_MBYTE
3160 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3161 {
3162 WCHAR *p;
3163 int retval;
3164
3165 p = enc_to_utf16(name, NULL);
3166 if (p == NULL)
3167 return -1;
3168 retval = _wmkdir(p);
3169 vim_free(p);
3170 return retval;
3171 }
3172#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003173 return _mkdir((const char *)name);
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003174}
3175
3176/*
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003177 * Delete directory "name".
3178 * Return 0 on success, -1 on error.
3179 */
3180 int
3181mch_rmdir(char_u *name)
3182{
3183#ifdef FEAT_MBYTE
3184 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3185 {
3186 WCHAR *p;
3187 int retval;
3188
3189 p = enc_to_utf16(name, NULL);
3190 if (p == NULL)
3191 return -1;
3192 retval = _wrmdir(p);
3193 vim_free(p);
3194 return retval;
3195 }
3196#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003197 return _rmdir((const char *)name);
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003198}
3199
3200/*
Bram Moolenaar03f48552006-02-28 23:52:23 +00003201 * Return TRUE if file "fname" has more than one link.
3202 */
3203 int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003204mch_is_hard_link(char_u *fname)
Bram Moolenaar03f48552006-02-28 23:52:23 +00003205{
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003206 BY_HANDLE_FILE_INFORMATION info;
3207
3208 return win32_fileinfo(fname, &info) == FILEINFO_OK
3209 && info.nNumberOfLinks > 1;
3210}
3211
3212/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01003213 * Return TRUE if "name" is a symbolic link (or a junction).
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003214 */
3215 int
Bram Moolenaar203258c2016-01-17 22:15:16 +01003216mch_is_symbolic_link(char_u *name)
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003217{
3218 HANDLE hFind;
3219 int res = FALSE;
3220 WIN32_FIND_DATAA findDataA;
3221 DWORD fileFlags = 0, reparseTag = 0;
3222#ifdef FEAT_MBYTE
3223 WCHAR *wn = NULL;
3224 WIN32_FIND_DATAW findDataW;
3225
3226 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar203258c2016-01-17 22:15:16 +01003227 wn = enc_to_utf16(name, NULL);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003228 if (wn != NULL)
3229 {
3230 hFind = FindFirstFileW(wn, &findDataW);
3231 vim_free(wn);
3232 if (hFind == INVALID_HANDLE_VALUE
3233 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
3234 {
3235 /* Retry with non-wide function (for Windows 98). */
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003236 hFind = FindFirstFile((LPCSTR)name, &findDataA);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003237 if (hFind != INVALID_HANDLE_VALUE)
3238 {
3239 fileFlags = findDataA.dwFileAttributes;
3240 reparseTag = findDataA.dwReserved0;
3241 }
3242 }
3243 else
3244 {
3245 fileFlags = findDataW.dwFileAttributes;
3246 reparseTag = findDataW.dwReserved0;
3247 }
3248 }
Bram Moolenaar03e114b2013-06-16 16:34:56 +02003249 else
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003250#endif
Bram Moolenaar03e114b2013-06-16 16:34:56 +02003251 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003252 hFind = FindFirstFile((LPCSTR)name, &findDataA);
Bram Moolenaar03e114b2013-06-16 16:34:56 +02003253 if (hFind != INVALID_HANDLE_VALUE)
3254 {
3255 fileFlags = findDataA.dwFileAttributes;
3256 reparseTag = findDataA.dwReserved0;
3257 }
3258 }
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003259
3260 if (hFind != INVALID_HANDLE_VALUE)
3261 FindClose(hFind);
3262
3263 if ((fileFlags & FILE_ATTRIBUTE_REPARSE_POINT)
Bram Moolenaar203258c2016-01-17 22:15:16 +01003264 && (reparseTag == IO_REPARSE_TAG_SYMLINK
3265 || reparseTag == IO_REPARSE_TAG_MOUNT_POINT))
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003266 res = TRUE;
3267
3268 return res;
3269}
3270
3271/*
3272 * Return TRUE if file "fname" has more than one link or if it is a symbolic
3273 * link.
3274 */
3275 int
3276mch_is_linked(char_u *fname)
3277{
3278 if (mch_is_hard_link(fname) || mch_is_symbolic_link(fname))
3279 return TRUE;
3280 return FALSE;
3281}
3282
3283/*
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003284 * Get the by-handle-file-information for "fname".
3285 * Returns FILEINFO_OK when OK.
3286 * returns FILEINFO_ENC_FAIL when enc_to_utf16() failed.
3287 * Returns FILEINFO_READ_FAIL when CreateFile() failed.
3288 * Returns FILEINFO_INFO_FAIL when GetFileInformationByHandle() failed.
3289 */
3290 int
3291win32_fileinfo(char_u *fname, BY_HANDLE_FILE_INFORMATION *info)
3292{
Bram Moolenaar03f48552006-02-28 23:52:23 +00003293 HANDLE hFile;
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003294 int res = FILEINFO_READ_FAIL;
Bram Moolenaar03f48552006-02-28 23:52:23 +00003295#ifdef FEAT_MBYTE
3296 WCHAR *wn = NULL;
3297
3298 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003299 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00003300 wn = enc_to_utf16(fname, NULL);
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003301 if (wn == NULL)
3302 res = FILEINFO_ENC_FAIL;
3303 }
Bram Moolenaar03f48552006-02-28 23:52:23 +00003304 if (wn != NULL)
3305 {
3306 hFile = CreateFileW(wn, /* file name */
3307 GENERIC_READ, /* access mode */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003308 FILE_SHARE_READ | FILE_SHARE_WRITE, /* share mode */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003309 NULL, /* security descriptor */
3310 OPEN_EXISTING, /* creation disposition */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003311 FILE_FLAG_BACKUP_SEMANTICS, /* file attributes */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003312 NULL); /* handle to template file */
3313 if (hFile == INVALID_HANDLE_VALUE
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003314 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
Bram Moolenaar03f48552006-02-28 23:52:23 +00003315 {
3316 /* Retry with non-wide function (for Windows 98). */
3317 vim_free(wn);
3318 wn = NULL;
3319 }
3320 }
3321 if (wn == NULL)
3322#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003323 hFile = CreateFile((LPCSTR)fname, /* file name */
3324 GENERIC_READ, /* access mode */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003325 FILE_SHARE_READ | FILE_SHARE_WRITE, /* share mode */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003326 NULL, /* security descriptor */
3327 OPEN_EXISTING, /* creation disposition */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003328 FILE_FLAG_BACKUP_SEMANTICS, /* file attributes */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003329 NULL); /* handle to template file */
3330
3331 if (hFile != INVALID_HANDLE_VALUE)
3332 {
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003333 if (GetFileInformationByHandle(hFile, info) != 0)
3334 res = FILEINFO_OK;
3335 else
3336 res = FILEINFO_INFO_FAIL;
Bram Moolenaar03f48552006-02-28 23:52:23 +00003337 CloseHandle(hFile);
3338 }
3339
3340#ifdef FEAT_MBYTE
3341 vim_free(wn);
3342#endif
3343 return res;
3344}
3345
3346/*
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003347 * get file attributes for `name'
3348 * -1 : error
3349 * else FILE_ATTRIBUTE_* defined in winnt.h
3350 */
Bram Moolenaarffa22202013-11-21 12:34:11 +01003351 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003352win32_getattrs(char_u *name)
3353{
3354 int attr;
3355#ifdef FEAT_MBYTE
3356 WCHAR *p = NULL;
3357
3358 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3359 p = enc_to_utf16(name, NULL);
3360
3361 if (p != NULL)
3362 {
3363 attr = GetFileAttributesW(p);
3364 if (attr < 0 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
3365 {
3366 /* Retry with non-wide function (for Windows 98). */
3367 vim_free(p);
3368 p = NULL;
3369 }
3370 }
3371 if (p == NULL)
3372#endif
3373 attr = GetFileAttributes((char *)name);
3374#ifdef FEAT_MBYTE
3375 vim_free(p);
3376#endif
3377 return attr;
3378}
3379
3380/*
3381 * set file attributes for `name' to `attrs'
3382 *
3383 * return -1 for failure, 0 otherwise
3384 */
3385 static
3386 int
3387win32_setattrs(char_u *name, int attrs)
3388{
3389 int res;
3390#ifdef FEAT_MBYTE
3391 WCHAR *p = NULL;
3392
3393 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3394 p = enc_to_utf16(name, NULL);
3395
3396 if (p != NULL)
3397 {
3398 res = SetFileAttributesW(p, attrs);
3399 if (res == FALSE
3400 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
3401 {
3402 /* Retry with non-wide function (for Windows 98). */
3403 vim_free(p);
3404 p = NULL;
3405 }
3406 }
3407 if (p == NULL)
3408#endif
3409 res = SetFileAttributes((char *)name, attrs);
3410#ifdef FEAT_MBYTE
3411 vim_free(p);
3412#endif
3413 return res ? 0 : -1;
3414}
3415
3416/*
3417 * Set archive flag for "name".
3418 */
3419 static
3420 int
3421win32_set_archive(char_u *name)
3422{
3423 int attrs = win32_getattrs(name);
3424 if (attrs == -1)
3425 return -1;
3426
3427 attrs |= FILE_ATTRIBUTE_ARCHIVE;
3428 return win32_setattrs(name, attrs);
3429}
3430
3431/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003432 * Return TRUE if file or directory "name" is writable (not readonly).
3433 * Strange semantics of Win32: a readonly directory is writable, but you can't
3434 * delete a file. Let's say this means it is writable.
3435 */
3436 int
3437mch_writable(char_u *name)
3438{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003439 int attrs = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003440
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003441 return (attrs != -1 && (!(attrs & FILE_ATTRIBUTE_READONLY)
3442 || (attrs & FILE_ATTRIBUTE_DIRECTORY)));
Bram Moolenaar071d4272004-06-13 20:20:40 +00003443}
3444
Bram Moolenaar071d4272004-06-13 20:20:40 +00003445/*
3446 * Return 1 if "name" can be executed, 0 if not.
Bram Moolenaar77b77102015-03-21 22:18:41 +01003447 * If "use_path" is FALSE only check if "name" is executable.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003448 * Return -1 if unknown.
3449 */
3450 int
Bram Moolenaar77b77102015-03-21 22:18:41 +01003451mch_can_exe(char_u *name, char_u **path, int use_path)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003452{
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003453 char_u buf[_MAX_PATH];
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00003454 int len = (int)STRLEN(name);
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003455 char_u *p;
3456
3457 if (len >= _MAX_PATH) /* safety check */
3458 return FALSE;
Bram Moolenaar77b77102015-03-21 22:18:41 +01003459 if (!use_path)
3460 {
3461 /* TODO: check if file is really executable. */
3462 return mch_getperm(name) != -1 && !mch_isdir(name);
3463 }
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003464
3465 /* If there already is an extension try using the name directly. Also do
3466 * this with a Unix-shell like 'shell'. */
3467 if (vim_strchr(gettail(name), '.') != NULL
3468 || strstr((char *)gettail(p_sh), "sh") != NULL)
Bram Moolenaarc7f02552014-04-01 21:00:59 +02003469 if (executable_exists((char *)name, path))
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003470 return TRUE;
3471
3472 /*
3473 * Loop over all extensions in $PATHEXT.
3474 */
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00003475 vim_strncpy(buf, name, _MAX_PATH - 1);
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003476 p = mch_getenv("PATHEXT");
3477 if (p == NULL)
3478 p = (char_u *)".com;.exe;.bat;.cmd";
3479 while (*p)
3480 {
3481 if (p[0] == '.' && (p[1] == NUL || p[1] == ';'))
3482 {
3483 /* A single "." means no extension is added. */
3484 buf[len] = NUL;
3485 ++p;
3486 if (*p)
3487 ++p;
3488 }
3489 else
3490 copy_option_part(&p, buf + len, _MAX_PATH - len, ";");
Bram Moolenaarc7f02552014-04-01 21:00:59 +02003491 if (executable_exists((char *)buf, path))
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003492 return TRUE;
3493 }
3494 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003495}
Bram Moolenaar071d4272004-06-13 20:20:40 +00003496
3497/*
3498 * Check what "name" is:
3499 * NODE_NORMAL: file or directory (or doesn't exist)
3500 * NODE_WRITABLE: writable device, socket, fifo, etc.
3501 * NODE_OTHER: non-writable things
3502 */
3503 int
3504mch_nodetype(char_u *name)
3505{
3506 HANDLE hFile;
3507 int type;
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003508#ifdef FEAT_MBYTE
3509 WCHAR *wn = NULL;
3510#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003511
Bram Moolenaar043545e2006-10-10 16:44:07 +00003512 /* We can't open a file with a name "\\.\con" or "\\.\prn" and trying to
3513 * read from it later will cause Vim to hang. Thus return NODE_WRITABLE
3514 * here. */
3515 if (STRNCMP(name, "\\\\.\\", 4) == 0)
3516 return NODE_WRITABLE;
3517
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003518#ifdef FEAT_MBYTE
3519 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3520 {
3521 wn = enc_to_utf16(name, NULL);
3522 if (wn != NULL)
3523 {
3524 hFile = CreateFileW(wn, /* file name */
3525 GENERIC_WRITE, /* access mode */
3526 0, /* share mode */
3527 NULL, /* security descriptor */
3528 OPEN_EXISTING, /* creation disposition */
3529 0, /* file attributes */
3530 NULL); /* handle to template file */
3531 if (hFile == INVALID_HANDLE_VALUE
3532 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
3533 {
3534 /* Retry with non-wide function (for Windows 98). */
3535 vim_free(wn);
3536 wn = NULL;
3537 }
3538 }
3539 }
3540 if (wn == NULL)
3541#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003542 hFile = CreateFile((LPCSTR)name, /* file name */
3543 GENERIC_WRITE, /* access mode */
3544 0, /* share mode */
3545 NULL, /* security descriptor */
3546 OPEN_EXISTING, /* creation disposition */
3547 0, /* file attributes */
3548 NULL); /* handle to template file */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003549
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003550#ifdef FEAT_MBYTE
3551 vim_free(wn);
3552#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003553 if (hFile == INVALID_HANDLE_VALUE)
3554 return NODE_NORMAL;
3555
3556 type = GetFileType(hFile);
3557 CloseHandle(hFile);
3558 if (type == FILE_TYPE_CHAR)
3559 return NODE_WRITABLE;
3560 if (type == FILE_TYPE_DISK)
3561 return NODE_NORMAL;
3562 return NODE_OTHER;
3563}
3564
3565#ifdef HAVE_ACL
3566struct my_acl
3567{
3568 PSECURITY_DESCRIPTOR pSecurityDescriptor;
3569 PSID pSidOwner;
3570 PSID pSidGroup;
3571 PACL pDacl;
3572 PACL pSacl;
3573};
3574#endif
3575
3576/*
3577 * Return a pointer to the ACL of file "fname" in allocated memory.
3578 * Return NULL if the ACL is not available for whatever reason.
3579 */
3580 vim_acl_T
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003581mch_get_acl(char_u *fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003582{
3583#ifndef HAVE_ACL
3584 return (vim_acl_T)NULL;
3585#else
3586 struct my_acl *p = NULL;
Bram Moolenaar27515922013-06-29 15:36:26 +02003587 DWORD err;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003588
3589 /* This only works on Windows NT and 2000. */
3590 if (g_PlatformId == VER_PLATFORM_WIN32_NT && advapi_lib != NULL)
3591 {
3592 p = (struct my_acl *)alloc_clear((unsigned)sizeof(struct my_acl));
3593 if (p != NULL)
3594 {
Bram Moolenaar27515922013-06-29 15:36:26 +02003595# ifdef FEAT_MBYTE
3596 WCHAR *wn = NULL;
3597
3598 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3599 wn = enc_to_utf16(fname, NULL);
3600 if (wn != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003601 {
Bram Moolenaar27515922013-06-29 15:36:26 +02003602 /* Try to retrieve the entire security descriptor. */
3603 err = pGetNamedSecurityInfoW(
3604 wn, // Abstract filename
3605 SE_FILE_OBJECT, // File Object
3606 OWNER_SECURITY_INFORMATION |
3607 GROUP_SECURITY_INFORMATION |
3608 DACL_SECURITY_INFORMATION |
3609 SACL_SECURITY_INFORMATION,
3610 &p->pSidOwner, // Ownership information.
3611 &p->pSidGroup, // Group membership.
3612 &p->pDacl, // Discretionary information.
3613 &p->pSacl, // For auditing purposes.
3614 &p->pSecurityDescriptor);
3615 if (err == ERROR_ACCESS_DENIED ||
3616 err == ERROR_PRIVILEGE_NOT_HELD)
3617 {
3618 /* Retrieve only DACL. */
3619 (void)pGetNamedSecurityInfoW(
3620 wn,
3621 SE_FILE_OBJECT,
3622 DACL_SECURITY_INFORMATION,
3623 NULL,
3624 NULL,
3625 &p->pDacl,
3626 NULL,
3627 &p->pSecurityDescriptor);
3628 }
3629 if (p->pSecurityDescriptor == NULL)
3630 {
3631 mch_free_acl((vim_acl_T)p);
3632 p = NULL;
3633 }
3634 vim_free(wn);
3635 }
3636 else
3637# endif
3638 {
3639 /* Try to retrieve the entire security descriptor. */
3640 err = pGetNamedSecurityInfo(
3641 (LPSTR)fname, // Abstract filename
3642 SE_FILE_OBJECT, // File Object
3643 OWNER_SECURITY_INFORMATION |
3644 GROUP_SECURITY_INFORMATION |
3645 DACL_SECURITY_INFORMATION |
3646 SACL_SECURITY_INFORMATION,
3647 &p->pSidOwner, // Ownership information.
3648 &p->pSidGroup, // Group membership.
3649 &p->pDacl, // Discretionary information.
3650 &p->pSacl, // For auditing purposes.
3651 &p->pSecurityDescriptor);
3652 if (err == ERROR_ACCESS_DENIED ||
3653 err == ERROR_PRIVILEGE_NOT_HELD)
3654 {
3655 /* Retrieve only DACL. */
3656 (void)pGetNamedSecurityInfo(
3657 (LPSTR)fname,
3658 SE_FILE_OBJECT,
3659 DACL_SECURITY_INFORMATION,
3660 NULL,
3661 NULL,
3662 &p->pDacl,
3663 NULL,
3664 &p->pSecurityDescriptor);
3665 }
3666 if (p->pSecurityDescriptor == NULL)
3667 {
3668 mch_free_acl((vim_acl_T)p);
3669 p = NULL;
3670 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003671 }
3672 }
3673 }
3674
3675 return (vim_acl_T)p;
3676#endif
3677}
3678
Bram Moolenaar27515922013-06-29 15:36:26 +02003679#ifdef HAVE_ACL
3680/*
3681 * Check if "acl" contains inherited ACE.
3682 */
3683 static BOOL
3684is_acl_inherited(PACL acl)
3685{
3686 DWORD i;
3687 ACL_SIZE_INFORMATION acl_info;
3688 PACCESS_ALLOWED_ACE ace;
3689
3690 acl_info.AceCount = 0;
3691 GetAclInformation(acl, &acl_info, sizeof(acl_info), AclSizeInformation);
3692 for (i = 0; i < acl_info.AceCount; i++)
3693 {
3694 GetAce(acl, i, (LPVOID *)&ace);
3695 if (ace->Header.AceFlags & INHERITED_ACE)
3696 return TRUE;
3697 }
3698 return FALSE;
3699}
3700#endif
3701
Bram Moolenaar071d4272004-06-13 20:20:40 +00003702/*
3703 * Set the ACL of file "fname" to "acl" (unless it's NULL).
3704 * Errors are ignored.
3705 * This must only be called with "acl" equal to what mch_get_acl() returned.
3706 */
3707 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003708mch_set_acl(char_u *fname, vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003709{
3710#ifdef HAVE_ACL
3711 struct my_acl *p = (struct my_acl *)acl;
Bram Moolenaar27515922013-06-29 15:36:26 +02003712 SECURITY_INFORMATION sec_info = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003713
3714 if (p != NULL && advapi_lib != NULL)
Bram Moolenaar27515922013-06-29 15:36:26 +02003715 {
3716# ifdef FEAT_MBYTE
3717 WCHAR *wn = NULL;
3718# endif
3719
3720 /* Set security flags */
3721 if (p->pSidOwner)
3722 sec_info |= OWNER_SECURITY_INFORMATION;
3723 if (p->pSidGroup)
3724 sec_info |= GROUP_SECURITY_INFORMATION;
3725 if (p->pDacl)
3726 {
3727 sec_info |= DACL_SECURITY_INFORMATION;
3728 /* Do not inherit its parent's DACL.
3729 * If the DACL is inherited, Cygwin permissions would be changed.
3730 */
3731 if (!is_acl_inherited(p->pDacl))
3732 sec_info |= PROTECTED_DACL_SECURITY_INFORMATION;
3733 }
3734 if (p->pSacl)
3735 sec_info |= SACL_SECURITY_INFORMATION;
3736
3737# ifdef FEAT_MBYTE
3738 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3739 wn = enc_to_utf16(fname, NULL);
3740 if (wn != NULL)
3741 {
3742 (void)pSetNamedSecurityInfoW(
3743 wn, // Abstract filename
3744 SE_FILE_OBJECT, // File Object
3745 sec_info,
3746 p->pSidOwner, // Ownership information.
3747 p->pSidGroup, // Group membership.
3748 p->pDacl, // Discretionary information.
3749 p->pSacl // For auditing purposes.
3750 );
3751 vim_free(wn);
3752 }
3753 else
3754# endif
3755 {
3756 (void)pSetNamedSecurityInfo(
3757 (LPSTR)fname, // Abstract filename
3758 SE_FILE_OBJECT, // File Object
3759 sec_info,
3760 p->pSidOwner, // Ownership information.
3761 p->pSidGroup, // Group membership.
3762 p->pDacl, // Discretionary information.
3763 p->pSacl // For auditing purposes.
3764 );
3765 }
3766 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003767#endif
3768}
3769
3770 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003771mch_free_acl(vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003772{
3773#ifdef HAVE_ACL
3774 struct my_acl *p = (struct my_acl *)acl;
3775
3776 if (p != NULL)
3777 {
3778 LocalFree(p->pSecurityDescriptor); // Free the memory just in case
3779 vim_free(p);
3780 }
3781#endif
3782}
3783
3784#ifndef FEAT_GUI_W32
3785
3786/*
3787 * handler for ctrl-break, ctrl-c interrupts, and fatal events.
3788 */
3789 static BOOL WINAPI
3790handler_routine(
3791 DWORD dwCtrlType)
3792{
3793 switch (dwCtrlType)
3794 {
3795 case CTRL_C_EVENT:
3796 if (ctrl_c_interrupts)
3797 g_fCtrlCPressed = TRUE;
3798 return TRUE;
3799
3800 case CTRL_BREAK_EVENT:
3801 g_fCBrkPressed = TRUE;
3802 return TRUE;
3803
3804 /* fatal events: shut down gracefully */
3805 case CTRL_CLOSE_EVENT:
3806 case CTRL_LOGOFF_EVENT:
3807 case CTRL_SHUTDOWN_EVENT:
3808 windgoto((int)Rows - 1, 0);
3809 g_fForceExit = TRUE;
3810
Bram Moolenaar0fde2902008-03-16 13:54:13 +00003811 vim_snprintf((char *)IObuff, IOSIZE, _("Vim: Caught %s event\n"),
Bram Moolenaar071d4272004-06-13 20:20:40 +00003812 (dwCtrlType == CTRL_CLOSE_EVENT
3813 ? _("close")
3814 : dwCtrlType == CTRL_LOGOFF_EVENT
3815 ? _("logoff")
3816 : _("shutdown")));
3817#ifdef DEBUG
3818 OutputDebugString(IObuff);
3819#endif
3820
3821 preserve_exit(); /* output IObuff, preserve files and exit */
3822
3823 return TRUE; /* not reached */
3824
3825 default:
3826 return FALSE;
3827 }
3828}
3829
3830
3831/*
3832 * set the tty in (raw) ? "raw" : "cooked" mode
3833 */
3834 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003835mch_settmode(int tmode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003836{
3837 DWORD cmodein;
3838 DWORD cmodeout;
3839 BOOL bEnableHandler;
3840
3841 GetConsoleMode(g_hConIn, &cmodein);
3842 GetConsoleMode(g_hConOut, &cmodeout);
3843 if (tmode == TMODE_RAW)
3844 {
3845 cmodein &= ~(ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
3846 ENABLE_ECHO_INPUT);
3847#ifdef FEAT_MOUSE
3848 if (g_fMouseActive)
3849 cmodein |= ENABLE_MOUSE_INPUT;
3850#endif
3851 cmodeout &= ~(ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
3852 bEnableHandler = TRUE;
3853 }
3854 else /* cooked */
3855 {
3856 cmodein |= (ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
3857 ENABLE_ECHO_INPUT);
3858 cmodeout |= (ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
3859 bEnableHandler = FALSE;
3860 }
3861 SetConsoleMode(g_hConIn, cmodein);
3862 SetConsoleMode(g_hConOut, cmodeout);
3863 SetConsoleCtrlHandler(handler_routine, bEnableHandler);
3864
3865#ifdef MCH_WRITE_DUMP
3866 if (fdDump)
3867 {
3868 fprintf(fdDump, "mch_settmode(%s, in = %x, out = %x)\n",
3869 tmode == TMODE_RAW ? "raw" :
3870 tmode == TMODE_COOK ? "cooked" : "normal",
3871 cmodein, cmodeout);
3872 fflush(fdDump);
3873 }
3874#endif
3875}
3876
3877
3878/*
3879 * Get the size of the current window in `Rows' and `Columns'
3880 * Return OK when size could be determined, FAIL otherwise.
3881 */
3882 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003883mch_get_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003884{
3885 CONSOLE_SCREEN_BUFFER_INFO csbi;
3886
3887 if (!g_fTermcapMode && g_cbTermcap.IsValid)
3888 {
3889 /*
3890 * For some reason, we are trying to get the screen dimensions
3891 * even though we are not in termcap mode. The 'Rows' and 'Columns'
3892 * variables are really intended to mean the size of Vim screen
3893 * while in termcap mode.
3894 */
3895 Rows = g_cbTermcap.Info.dwSize.Y;
3896 Columns = g_cbTermcap.Info.dwSize.X;
3897 }
3898 else if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3899 {
3900 Rows = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
3901 Columns = csbi.srWindow.Right - csbi.srWindow.Left + 1;
3902 }
3903 else
3904 {
3905 Rows = 25;
3906 Columns = 80;
3907 }
3908 return OK;
3909}
3910
3911/*
3912 * Set a console window to `xSize' * `ySize'
3913 */
3914 static void
3915ResizeConBufAndWindow(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003916 HANDLE hConsole,
3917 int xSize,
3918 int ySize)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003919{
3920 CONSOLE_SCREEN_BUFFER_INFO csbi; /* hold current console buffer info */
3921 SMALL_RECT srWindowRect; /* hold the new console size */
3922 COORD coordScreen;
3923
3924#ifdef MCH_WRITE_DUMP
3925 if (fdDump)
3926 {
3927 fprintf(fdDump, "ResizeConBufAndWindow(%d, %d)\n", xSize, ySize);
3928 fflush(fdDump);
3929 }
3930#endif
3931
3932 /* get the largest size we can size the console window to */
3933 coordScreen = GetLargestConsoleWindowSize(hConsole);
3934
3935 /* define the new console window size and scroll position */
3936 srWindowRect.Left = srWindowRect.Top = (SHORT) 0;
3937 srWindowRect.Right = (SHORT) (min(xSize, coordScreen.X) - 1);
3938 srWindowRect.Bottom = (SHORT) (min(ySize, coordScreen.Y) - 1);
3939
3940 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3941 {
3942 int sx, sy;
3943
3944 sx = csbi.srWindow.Right - csbi.srWindow.Left + 1;
3945 sy = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
3946 if (sy < ySize || sx < xSize)
3947 {
3948 /*
3949 * Increasing number of lines/columns, do buffer first.
3950 * Use the maximal size in x and y direction.
3951 */
3952 if (sy < ySize)
3953 coordScreen.Y = ySize;
3954 else
3955 coordScreen.Y = sy;
3956 if (sx < xSize)
3957 coordScreen.X = xSize;
3958 else
3959 coordScreen.X = sx;
3960 SetConsoleScreenBufferSize(hConsole, coordScreen);
3961 }
3962 }
3963
3964 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &srWindowRect))
3965 {
3966#ifdef MCH_WRITE_DUMP
3967 if (fdDump)
3968 {
3969 fprintf(fdDump, "SetConsoleWindowInfo failed: %lx\n",
3970 GetLastError());
3971 fflush(fdDump);
3972 }
3973#endif
3974 }
3975
3976 /* define the new console buffer size */
3977 coordScreen.X = xSize;
3978 coordScreen.Y = ySize;
3979
3980 if (!SetConsoleScreenBufferSize(hConsole, coordScreen))
3981 {
3982#ifdef MCH_WRITE_DUMP
3983 if (fdDump)
3984 {
3985 fprintf(fdDump, "SetConsoleScreenBufferSize failed: %lx\n",
3986 GetLastError());
3987 fflush(fdDump);
3988 }
3989#endif
3990 }
3991}
3992
3993
3994/*
3995 * Set the console window to `Rows' * `Columns'
3996 */
3997 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003998mch_set_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003999{
4000 COORD coordScreen;
4001
4002 /* Don't change window size while still starting up */
4003 if (suppress_winsize != 0)
4004 {
4005 suppress_winsize = 2;
4006 return;
4007 }
4008
4009 if (term_console)
4010 {
4011 coordScreen = GetLargestConsoleWindowSize(g_hConOut);
4012
4013 /* Clamp Rows and Columns to reasonable values */
4014 if (Rows > coordScreen.Y)
4015 Rows = coordScreen.Y;
4016 if (Columns > coordScreen.X)
4017 Columns = coordScreen.X;
4018
4019 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
4020 }
4021}
4022
4023/*
4024 * Rows and/or Columns has changed.
4025 */
4026 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004027mch_new_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004028{
4029 set_scroll_region(0, 0, Columns - 1, Rows - 1);
4030}
4031
4032
4033/*
4034 * Called when started up, to set the winsize that was delayed.
4035 */
4036 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004037mch_set_winsize_now(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004038{
4039 if (suppress_winsize == 2)
4040 {
4041 suppress_winsize = 0;
4042 mch_set_shellsize();
4043 shell_resized();
4044 }
4045 suppress_winsize = 0;
4046}
4047#endif /* FEAT_GUI_W32 */
4048
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004049 static BOOL
4050vim_create_process(
Bram Moolenaar36c85b22013-12-12 20:25:44 +01004051 char *cmd,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004052 BOOL inherit_handles,
Bram Moolenaar3f1138e2014-01-05 13:29:26 +01004053 DWORD flags,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004054 STARTUPINFO *si,
4055 PROCESS_INFORMATION *pi)
4056{
4057# ifdef FEAT_MBYTE
4058 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4059 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004060 WCHAR *wcmd = enc_to_utf16((char_u *)cmd, NULL);
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004061
4062 if (wcmd != NULL)
4063 {
4064 BOOL ret;
4065 ret = CreateProcessW(
4066 NULL, /* Executable name */
4067 wcmd, /* Command to execute */
4068 NULL, /* Process security attributes */
4069 NULL, /* Thread security attributes */
4070 inherit_handles, /* Inherit handles */
4071 flags, /* Creation flags */
4072 NULL, /* Environment */
4073 NULL, /* Current directory */
Bram Moolenaar36c85b22013-12-12 20:25:44 +01004074 (LPSTARTUPINFOW)si, /* Startup information */
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004075 pi); /* Process information */
4076 vim_free(wcmd);
4077 return ret;
4078 }
4079 }
4080#endif
4081 return CreateProcess(
4082 NULL, /* Executable name */
4083 cmd, /* Command to execute */
4084 NULL, /* Process security attributes */
4085 NULL, /* Thread security attributes */
4086 inherit_handles, /* Inherit handles */
4087 flags, /* Creation flags */
4088 NULL, /* Environment */
4089 NULL, /* Current directory */
4090 si, /* Startup information */
4091 pi); /* Process information */
4092}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004093
4094
4095#if defined(FEAT_GUI_W32) || defined(PROTO)
4096
4097/*
4098 * Specialised version of system() for Win32 GUI mode.
4099 * This version proceeds as follows:
4100 * 1. Create a console window for use by the subprocess
4101 * 2. Run the subprocess (it gets the allocated console by default)
4102 * 3. Wait for the subprocess to terminate and get its exit code
4103 * 4. Prompt the user to press a key to close the console window
4104 */
4105 static int
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004106mch_system_classic(char *cmd, int options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004107{
4108 STARTUPINFO si;
4109 PROCESS_INFORMATION pi;
4110 DWORD ret = 0;
4111 HWND hwnd = GetFocus();
4112
4113 si.cb = sizeof(si);
4114 si.lpReserved = NULL;
4115 si.lpDesktop = NULL;
4116 si.lpTitle = NULL;
4117 si.dwFlags = STARTF_USESHOWWINDOW;
4118 /*
4119 * It's nicer to run a filter command in a minimized window, but in
4120 * Windows 95 this makes the command MUCH slower. We can't do it under
4121 * Win32s either as it stops the synchronous spawn workaround working.
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01004122 * Don't activate the window to keep focus on Vim.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004123 */
4124 if ((options & SHELL_DOOUT) && !mch_windows95() && !gui_is_win32s())
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01004125 si.wShowWindow = SW_SHOWMINNOACTIVE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004126 else
4127 si.wShowWindow = SW_SHOWNORMAL;
4128 si.cbReserved2 = 0;
4129 si.lpReserved2 = NULL;
4130
Bram Moolenaar942d6b22016-02-07 19:57:16 +01004131 /* There is a strange error on Windows 95 when using "c:\command.com".
Bram Moolenaar071d4272004-06-13 20:20:40 +00004132 * When the "c:\\" is left out it works OK...? */
4133 if (mch_windows95()
4134 && (STRNICMP(cmd, "c:/command.com", 14) == 0
4135 || STRNICMP(cmd, "c:\\command.com", 14) == 0))
4136 cmd += 3;
4137
4138 /* Now, run the command */
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004139 vim_create_process(cmd, FALSE,
4140 CREATE_DEFAULT_ERROR_MODE | CREATE_NEW_CONSOLE, &si, &pi);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004141
4142 /* Wait for the command to terminate before continuing */
4143 if (g_PlatformId != VER_PLATFORM_WIN32s)
4144 {
4145#ifdef FEAT_GUI
4146 int delay = 1;
4147
4148 /* Keep updating the window while waiting for the shell to finish. */
4149 for (;;)
4150 {
4151 MSG msg;
4152
Bram Moolenaar8c85fa32011-08-10 17:08:03 +02004153 if (pPeekMessage(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004154 {
4155 TranslateMessage(&msg);
Bram Moolenaar8c85fa32011-08-10 17:08:03 +02004156 pDispatchMessage(&msg);
Bram Moolenaare4195c52012-08-02 12:31:44 +02004157 delay = 1;
4158 continue;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004159 }
4160 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
4161 break;
4162
4163 /* We start waiting for a very short time and then increase it, so
4164 * that we respond quickly when the process is quick, and don't
4165 * consume too much overhead when it's slow. */
4166 if (delay < 50)
4167 delay += 10;
4168 }
4169#else
4170 WaitForSingleObject(pi.hProcess, INFINITE);
4171#endif
4172
4173 /* Get the command exit code */
4174 GetExitCodeProcess(pi.hProcess, &ret);
4175 }
4176 else
4177 {
4178 /*
4179 * This ugly code is the only quick way of performing
4180 * a synchronous spawn under Win32s. Yuk.
4181 */
4182 num_windows = 0;
4183 EnumWindows(win32ssynch_cb, 0);
4184 old_num_windows = num_windows;
4185 do
4186 {
4187 Sleep(1000);
4188 num_windows = 0;
4189 EnumWindows(win32ssynch_cb, 0);
4190 } while (num_windows == old_num_windows);
4191 ret = 0;
4192 }
4193
4194 /* Close the handles to the subprocess, so that it goes away */
4195 CloseHandle(pi.hThread);
4196 CloseHandle(pi.hProcess);
4197
4198 /* Try to get input focus back. Doesn't always work though. */
4199 PostMessage(hwnd, WM_SETFOCUS, 0, 0);
4200
4201 return ret;
4202}
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004203
4204/*
4205 * Thread launched by the gui to send the current buffer data to the
4206 * process. This way avoid to hang up vim totally if the children
4207 * process take a long time to process the lines.
4208 */
4209 static DWORD WINAPI
4210sub_process_writer(LPVOID param)
4211{
4212 HANDLE g_hChildStd_IN_Wr = param;
4213 linenr_T lnum = curbuf->b_op_start.lnum;
4214 DWORD len = 0;
4215 DWORD l;
4216 char_u *lp = ml_get(lnum);
4217 char_u *s;
4218 int written = 0;
4219
4220 for (;;)
4221 {
4222 l = (DWORD)STRLEN(lp + written);
4223 if (l == 0)
4224 len = 0;
4225 else if (lp[written] == NL)
4226 {
4227 /* NL -> NUL translation */
4228 WriteFile(g_hChildStd_IN_Wr, "", 1, &len, NULL);
4229 }
4230 else
4231 {
4232 s = vim_strchr(lp + written, NL);
4233 WriteFile(g_hChildStd_IN_Wr, (char *)lp + written,
4234 s == NULL ? l : (DWORD)(s - (lp + written)),
4235 &len, NULL);
4236 }
4237 if (len == (int)l)
4238 {
4239 /* Finished a line, add a NL, unless this line should not have
4240 * one. */
4241 if (lnum != curbuf->b_op_end.lnum
Bram Moolenaar34d72d42015-07-17 14:18:08 +02004242 || (!curbuf->b_p_bin
4243 && curbuf->b_p_fixeol)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004244 || (lnum != curbuf->b_no_eol_lnum
4245 && (lnum != curbuf->b_ml.ml_line_count
4246 || curbuf->b_p_eol)))
4247 {
Bram Moolenaaraf62ff32013-03-19 14:48:29 +01004248 WriteFile(g_hChildStd_IN_Wr, "\n", 1, (LPDWORD)&ignored, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004249 }
4250
4251 ++lnum;
4252 if (lnum > curbuf->b_op_end.lnum)
4253 break;
4254
4255 lp = ml_get(lnum);
4256 written = 0;
4257 }
4258 else if (len > 0)
4259 written += len;
4260 }
4261
4262 /* finished all the lines, close pipe */
4263 CloseHandle(g_hChildStd_IN_Wr);
4264 ExitThread(0);
4265}
4266
4267
4268# define BUFLEN 100 /* length for buffer, stolen from unix version */
4269
4270/*
4271 * This function read from the children's stdout and write the
4272 * data on screen or in the buffer accordingly.
4273 */
4274 static void
4275dump_pipe(int options,
4276 HANDLE g_hChildStd_OUT_Rd,
4277 garray_T *ga,
4278 char_u buffer[],
4279 DWORD *buffer_off)
4280{
4281 DWORD availableBytes = 0;
4282 DWORD i;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004283 int ret;
4284 DWORD len;
4285 DWORD toRead;
4286 int repeatCount;
4287
4288 /* we query the pipe to see if there is any data to read
4289 * to avoid to perform a blocking read */
4290 ret = PeekNamedPipe(g_hChildStd_OUT_Rd, /* pipe to query */
4291 NULL, /* optional buffer */
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02004292 0, /* buffer size */
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004293 NULL, /* number of read bytes */
4294 &availableBytes, /* available bytes total */
4295 NULL); /* byteLeft */
4296
4297 repeatCount = 0;
4298 /* We got real data in the pipe, read it */
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02004299 while (ret != 0 && availableBytes > 0)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004300 {
4301 repeatCount++;
4302 toRead =
4303# ifdef FEAT_MBYTE
4304 (DWORD)(BUFLEN - *buffer_off);
4305# else
4306 (DWORD)BUFLEN;
4307# endif
4308 toRead = availableBytes < toRead ? availableBytes : toRead;
4309 ReadFile(g_hChildStd_OUT_Rd, buffer
4310# ifdef FEAT_MBYTE
4311 + *buffer_off, toRead
4312# else
4313 , toRead
4314# endif
4315 , &len, NULL);
4316
4317 /* If we haven't read anything, there is a problem */
4318 if (len == 0)
4319 break;
4320
4321 availableBytes -= len;
4322
4323 if (options & SHELL_READ)
4324 {
4325 /* Do NUL -> NL translation, append NL separated
4326 * lines to the current buffer. */
4327 for (i = 0; i < len; ++i)
4328 {
4329 if (buffer[i] == NL)
4330 append_ga_line(ga);
4331 else if (buffer[i] == NUL)
4332 ga_append(ga, NL);
4333 else
4334 ga_append(ga, buffer[i]);
4335 }
4336 }
4337# ifdef FEAT_MBYTE
4338 else if (has_mbyte)
4339 {
4340 int l;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004341 int c;
4342 char_u *p;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004343
4344 len += *buffer_off;
4345 buffer[len] = NUL;
4346
4347 /* Check if the last character in buffer[] is
4348 * incomplete, keep these bytes for the next
4349 * round. */
4350 for (p = buffer; p < buffer + len; p += l)
4351 {
4352 l = mb_cptr2len(p);
4353 if (l == 0)
4354 l = 1; /* NUL byte? */
4355 else if (MB_BYTE2LEN(*p) != l)
4356 break;
4357 }
4358 if (p == buffer) /* no complete character */
4359 {
4360 /* avoid getting stuck at an illegal byte */
4361 if (len >= 12)
4362 ++p;
4363 else
4364 {
4365 *buffer_off = len;
4366 return;
4367 }
4368 }
4369 c = *p;
4370 *p = NUL;
4371 msg_puts(buffer);
4372 if (p < buffer + len)
4373 {
4374 *p = c;
4375 *buffer_off = (DWORD)((buffer + len) - p);
4376 mch_memmove(buffer, p, *buffer_off);
4377 return;
4378 }
4379 *buffer_off = 0;
4380 }
4381# endif /* FEAT_MBYTE */
4382 else
4383 {
4384 buffer[len] = NUL;
4385 msg_puts(buffer);
4386 }
4387
4388 windgoto(msg_row, msg_col);
4389 cursor_on();
4390 out_flush();
4391 }
4392}
4393
4394/*
4395 * Version of system to use for windows NT > 5.0 (Win2K), use pipe
4396 * for communication and doesn't open any new window.
4397 */
4398 static int
4399mch_system_piped(char *cmd, int options)
4400{
4401 STARTUPINFO si;
4402 PROCESS_INFORMATION pi;
4403 DWORD ret = 0;
4404
4405 HANDLE g_hChildStd_IN_Rd = NULL;
4406 HANDLE g_hChildStd_IN_Wr = NULL;
4407 HANDLE g_hChildStd_OUT_Rd = NULL;
4408 HANDLE g_hChildStd_OUT_Wr = NULL;
4409
4410 char_u buffer[BUFLEN + 1]; /* reading buffer + size */
4411 DWORD len;
4412
4413 /* buffer used to receive keys */
4414 char_u ta_buf[BUFLEN + 1]; /* TypeAHead */
4415 int ta_len = 0; /* valid bytes in ta_buf[] */
4416
4417 DWORD i;
4418 int c;
4419 int noread_cnt = 0;
4420 garray_T ga;
4421 int delay = 1;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004422 DWORD buffer_off = 0; /* valid bytes in buffer[] */
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004423 char *p = NULL;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004424
4425 SECURITY_ATTRIBUTES saAttr;
4426
4427 /* Set the bInheritHandle flag so pipe handles are inherited. */
4428 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
4429 saAttr.bInheritHandle = TRUE;
4430 saAttr.lpSecurityDescriptor = NULL;
4431
4432 if ( ! CreatePipe(&g_hChildStd_OUT_Rd, &g_hChildStd_OUT_Wr, &saAttr, 0)
4433 /* Ensure the read handle to the pipe for STDOUT is not inherited. */
4434 || ! pSetHandleInformation(g_hChildStd_OUT_Rd, HANDLE_FLAG_INHERIT, 0)
4435 /* Create a pipe for the child process's STDIN. */
4436 || ! CreatePipe(&g_hChildStd_IN_Rd, &g_hChildStd_IN_Wr, &saAttr, 0)
4437 /* Ensure the write handle to the pipe for STDIN is not inherited. */
4438 || ! pSetHandleInformation(g_hChildStd_IN_Wr, HANDLE_FLAG_INHERIT, 0) )
4439 {
4440 CloseHandle(g_hChildStd_IN_Rd);
4441 CloseHandle(g_hChildStd_IN_Wr);
4442 CloseHandle(g_hChildStd_OUT_Rd);
4443 CloseHandle(g_hChildStd_OUT_Wr);
4444 MSG_PUTS(_("\nCannot create pipes\n"));
4445 }
4446
4447 si.cb = sizeof(si);
4448 si.lpReserved = NULL;
4449 si.lpDesktop = NULL;
4450 si.lpTitle = NULL;
4451 si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
4452
4453 /* set-up our file redirection */
4454 si.hStdError = g_hChildStd_OUT_Wr;
4455 si.hStdOutput = g_hChildStd_OUT_Wr;
4456 si.hStdInput = g_hChildStd_IN_Rd;
4457 si.wShowWindow = SW_HIDE;
4458 si.cbReserved2 = 0;
4459 si.lpReserved2 = NULL;
4460
4461 if (options & SHELL_READ)
4462 ga_init2(&ga, 1, BUFLEN);
4463
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004464 if (cmd != NULL)
4465 {
4466 p = (char *)vim_strsave((char_u *)cmd);
4467 if (p != NULL)
4468 unescape_shellxquote((char_u *)p, p_sxe);
4469 else
4470 p = cmd;
4471 }
4472
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004473 /* Now, run the command.
4474 * About "Inherit handles" being TRUE: this command can be litigious,
4475 * handle inheritance was deactivated for pending temp file, but, if we
4476 * deactivate it, the pipes don't work for some reason. */
4477 vim_create_process(p, TRUE, CREATE_DEFAULT_ERROR_MODE, &si, &pi);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004478
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004479 if (p != cmd)
4480 vim_free(p);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004481
4482 /* Close our unused side of the pipes */
4483 CloseHandle(g_hChildStd_IN_Rd);
4484 CloseHandle(g_hChildStd_OUT_Wr);
4485
4486 if (options & SHELL_WRITE)
4487 {
4488 HANDLE thread =
4489 CreateThread(NULL, /* security attributes */
4490 0, /* default stack size */
4491 sub_process_writer, /* function to be executed */
4492 g_hChildStd_IN_Wr, /* parameter */
4493 0, /* creation flag, start immediately */
4494 NULL); /* we don't care about thread id */
4495 CloseHandle(thread);
4496 g_hChildStd_IN_Wr = NULL;
4497 }
4498
4499 /* Keep updating the window while waiting for the shell to finish. */
4500 for (;;)
4501 {
4502 MSG msg;
4503
Bram Moolenaar175d0702013-12-11 18:36:33 +01004504 if (pPeekMessage(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004505 {
4506 TranslateMessage(&msg);
Bram Moolenaar175d0702013-12-11 18:36:33 +01004507 pDispatchMessage(&msg);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004508 }
4509
4510 /* write pipe information in the window */
4511 if ((options & (SHELL_READ|SHELL_WRITE))
4512# ifdef FEAT_GUI
4513 || gui.in_use
4514# endif
4515 )
4516 {
4517 len = 0;
4518 if (!(options & SHELL_EXPAND)
4519 && ((options &
4520 (SHELL_READ|SHELL_WRITE|SHELL_COOKED))
4521 != (SHELL_READ|SHELL_WRITE|SHELL_COOKED)
4522# ifdef FEAT_GUI
4523 || gui.in_use
4524# endif
4525 )
4526 && (ta_len > 0 || noread_cnt > 4))
4527 {
4528 if (ta_len == 0)
4529 {
4530 /* Get extra characters when we don't have any. Reset the
4531 * counter and timer. */
4532 noread_cnt = 0;
4533# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
4534 gettimeofday(&start_tv, NULL);
4535# endif
4536 len = ui_inchar(ta_buf, BUFLEN, 10L, 0);
4537 }
4538 if (ta_len > 0 || len > 0)
4539 {
4540 /*
4541 * For pipes: Check for CTRL-C: send interrupt signal to
4542 * child. Check for CTRL-D: EOF, close pipe to child.
4543 */
4544 if (len == 1 && cmd != NULL)
4545 {
4546 if (ta_buf[ta_len] == Ctrl_C)
4547 {
4548 /* Learn what exit code is expected, for
4549 * now put 9 as SIGKILL */
4550 TerminateProcess(pi.hProcess, 9);
4551 }
4552 if (ta_buf[ta_len] == Ctrl_D)
4553 {
4554 CloseHandle(g_hChildStd_IN_Wr);
4555 g_hChildStd_IN_Wr = NULL;
4556 }
4557 }
4558
4559 /* replace K_BS by <BS> and K_DEL by <DEL> */
4560 for (i = ta_len; i < ta_len + len; ++i)
4561 {
4562 if (ta_buf[i] == CSI && len - i > 2)
4563 {
4564 c = TERMCAP2KEY(ta_buf[i + 1], ta_buf[i + 2]);
4565 if (c == K_DEL || c == K_KDEL || c == K_BS)
4566 {
4567 mch_memmove(ta_buf + i + 1, ta_buf + i + 3,
4568 (size_t)(len - i - 2));
4569 if (c == K_DEL || c == K_KDEL)
4570 ta_buf[i] = DEL;
4571 else
4572 ta_buf[i] = Ctrl_H;
4573 len -= 2;
4574 }
4575 }
4576 else if (ta_buf[i] == '\r')
4577 ta_buf[i] = '\n';
4578# ifdef FEAT_MBYTE
4579 if (has_mbyte)
4580 i += (*mb_ptr2len_len)(ta_buf + i,
4581 ta_len + len - i) - 1;
4582# endif
4583 }
4584
4585 /*
4586 * For pipes: echo the typed characters. For a pty this
4587 * does not seem to work.
4588 */
4589 for (i = ta_len; i < ta_len + len; ++i)
4590 {
4591 if (ta_buf[i] == '\n' || ta_buf[i] == '\b')
4592 msg_putchar(ta_buf[i]);
4593# ifdef FEAT_MBYTE
4594 else if (has_mbyte)
4595 {
4596 int l = (*mb_ptr2len)(ta_buf + i);
4597
4598 msg_outtrans_len(ta_buf + i, l);
4599 i += l - 1;
4600 }
4601# endif
4602 else
4603 msg_outtrans_len(ta_buf + i, 1);
4604 }
4605 windgoto(msg_row, msg_col);
4606 out_flush();
4607
4608 ta_len += len;
4609
4610 /*
4611 * Write the characters to the child, unless EOF has been
4612 * typed for pipes. Write one character at a time, to
4613 * avoid losing too much typeahead. When writing buffer
4614 * lines, drop the typed characters (only check for
4615 * CTRL-C).
4616 */
4617 if (options & SHELL_WRITE)
4618 ta_len = 0;
4619 else if (g_hChildStd_IN_Wr != NULL)
4620 {
4621 WriteFile(g_hChildStd_IN_Wr, (char*)ta_buf,
4622 1, &len, NULL);
4623 // if we are typing in, we want to keep things reactive
4624 delay = 1;
4625 if (len > 0)
4626 {
4627 ta_len -= len;
4628 mch_memmove(ta_buf, ta_buf + len, ta_len);
4629 }
4630 }
4631 }
4632 }
4633 }
4634
4635 if (ta_len)
4636 ui_inchar_undo(ta_buf, ta_len);
4637
4638 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
4639 {
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004640 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004641 break;
4642 }
4643
4644 ++noread_cnt;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004645 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004646
4647 /* We start waiting for a very short time and then increase it, so
4648 * that we respond quickly when the process is quick, and don't
4649 * consume too much overhead when it's slow. */
4650 if (delay < 50)
4651 delay += 10;
4652 }
4653
4654 /* Close the pipe */
4655 CloseHandle(g_hChildStd_OUT_Rd);
4656 if (g_hChildStd_IN_Wr != NULL)
4657 CloseHandle(g_hChildStd_IN_Wr);
4658
4659 WaitForSingleObject(pi.hProcess, INFINITE);
4660
4661 /* Get the command exit code */
4662 GetExitCodeProcess(pi.hProcess, &ret);
4663
4664 if (options & SHELL_READ)
4665 {
4666 if (ga.ga_len > 0)
4667 {
4668 append_ga_line(&ga);
4669 /* remember that the NL was missing */
4670 curbuf->b_no_eol_lnum = curwin->w_cursor.lnum;
4671 }
4672 else
4673 curbuf->b_no_eol_lnum = 0;
4674 ga_clear(&ga);
4675 }
4676
4677 /* Close the handles to the subprocess, so that it goes away */
4678 CloseHandle(pi.hThread);
4679 CloseHandle(pi.hProcess);
4680
4681 return ret;
4682}
4683
4684 static int
4685mch_system(char *cmd, int options)
4686{
4687 /* if we can pipe and the shelltemp option is off */
4688 if (allowPiping && !p_stmp)
4689 return mch_system_piped(cmd, options);
4690 else
4691 return mch_system_classic(cmd, options);
4692}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004693#else
4694
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004695# ifdef FEAT_MBYTE
4696 static int
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01004697mch_system(char *cmd, int options)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004698{
4699 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4700 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004701 WCHAR *wcmd = enc_to_utf16((char_u *)cmd, NULL);
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004702 if (wcmd != NULL)
4703 {
4704 int ret = _wsystem(wcmd);
4705 vim_free(wcmd);
4706 return ret;
4707 }
4708 }
4709 return system(cmd);
4710}
4711# else
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01004712# define mch_system(c, o) system(c)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004713# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004714
4715#endif
4716
4717/*
4718 * Either execute a command by calling the shell or start a new shell
4719 */
4720 int
4721mch_call_shell(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004722 char_u *cmd,
4723 int options) /* SHELL_*, see vim.h */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004724{
4725 int x = 0;
4726 int tmode = cur_tmode;
4727#ifdef FEAT_TITLE
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004728 char szShellTitle[512];
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004729# ifdef FEAT_MBYTE
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004730 int did_set_title = FALSE;
4731
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004732 /* Change the title to reflect that we are in a subshell. */
4733 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4734 {
4735 WCHAR szShellTitle[512];
4736
4737 if (GetConsoleTitleW(szShellTitle,
4738 sizeof(szShellTitle)/sizeof(WCHAR) - 4) > 0)
4739 {
4740 if (cmd == NULL)
4741 wcscat(szShellTitle, L" :sh");
4742 else
4743 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004744 WCHAR *wn = enc_to_utf16((char_u *)cmd, NULL);
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004745
4746 if (wn != NULL)
4747 {
4748 wcscat(szShellTitle, L" - !");
4749 if ((wcslen(szShellTitle) + wcslen(wn) <
4750 sizeof(szShellTitle)/sizeof(WCHAR)))
4751 wcscat(szShellTitle, wn);
4752 SetConsoleTitleW(szShellTitle);
4753 vim_free(wn);
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004754 did_set_title = TRUE;
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004755 }
4756 }
4757 }
4758 }
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004759 if (!did_set_title)
4760# endif
4761 /* Change the title to reflect that we are in a subshell. */
4762 if (GetConsoleTitle(szShellTitle, sizeof(szShellTitle) - 4) > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004763 {
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004764 if (cmd == NULL)
4765 strcat(szShellTitle, " :sh");
4766 else
4767 {
4768 strcat(szShellTitle, " - !");
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004769 if ((strlen(szShellTitle) + strlen((char *)cmd)
4770 < sizeof(szShellTitle)))
4771 strcat(szShellTitle, (char *)cmd);
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004772 }
4773 SetConsoleTitle(szShellTitle);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004774 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004775#endif
4776
4777 out_flush();
4778
4779#ifdef MCH_WRITE_DUMP
4780 if (fdDump)
4781 {
4782 fprintf(fdDump, "mch_call_shell(\"%s\", %d)\n", cmd, options);
4783 fflush(fdDump);
4784 }
4785#endif
4786
4787 /*
4788 * Catch all deadly signals while running the external command, because a
4789 * CTRL-C, Ctrl-Break or illegal instruction might otherwise kill us.
4790 */
4791 signal(SIGINT, SIG_IGN);
4792#if defined(__GNUC__) && !defined(__MINGW32__)
4793 signal(SIGKILL, SIG_IGN);
4794#else
4795 signal(SIGBREAK, SIG_IGN);
4796#endif
4797 signal(SIGILL, SIG_IGN);
4798 signal(SIGFPE, SIG_IGN);
4799 signal(SIGSEGV, SIG_IGN);
4800 signal(SIGTERM, SIG_IGN);
4801 signal(SIGABRT, SIG_IGN);
4802
4803 if (options & SHELL_COOKED)
4804 settmode(TMODE_COOK); /* set to normal mode */
4805
4806 if (cmd == NULL)
4807 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004808 x = mch_system((char *)p_sh, options);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004809 }
4810 else
4811 {
4812 /* we use "command" or "cmd" to start the shell; slow but easy */
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004813 char_u *newcmd = NULL;
4814 char_u *cmdbase = cmd;
4815 long_u cmdlen;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004816
4817 /* Skip a leading ", ( and "(. */
4818 if (*cmdbase == '"' )
4819 ++cmdbase;
4820 if (*cmdbase == '(')
4821 ++cmdbase;
4822
4823 if ((STRNICMP(cmdbase, "start", 5) == 0) && vim_iswhite(cmdbase[5]))
4824 {
4825 STARTUPINFO si;
4826 PROCESS_INFORMATION pi;
4827 DWORD flags = CREATE_NEW_CONSOLE;
4828 char_u *p;
4829
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01004830 ZeroMemory(&si, sizeof(si));
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004831 si.cb = sizeof(si);
4832 si.lpReserved = NULL;
4833 si.lpDesktop = NULL;
4834 si.lpTitle = NULL;
4835 si.dwFlags = 0;
4836 si.cbReserved2 = 0;
4837 si.lpReserved2 = NULL;
4838
4839 cmdbase = skipwhite(cmdbase + 5);
4840 if ((STRNICMP(cmdbase, "/min", 4) == 0)
4841 && vim_iswhite(cmdbase[4]))
4842 {
4843 cmdbase = skipwhite(cmdbase + 4);
4844 si.dwFlags = STARTF_USESHOWWINDOW;
4845 si.wShowWindow = SW_SHOWMINNOACTIVE;
4846 }
4847 else if ((STRNICMP(cmdbase, "/b", 2) == 0)
4848 && vim_iswhite(cmdbase[2]))
4849 {
4850 cmdbase = skipwhite(cmdbase + 2);
4851 flags = CREATE_NO_WINDOW;
4852 si.dwFlags = STARTF_USESTDHANDLES;
4853 si.hStdInput = CreateFile("\\\\.\\NUL", // File name
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004854 GENERIC_READ, // Access flags
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004855 0, // Share flags
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004856 NULL, // Security att.
4857 OPEN_EXISTING, // Open flags
4858 FILE_ATTRIBUTE_NORMAL, // File att.
4859 NULL); // Temp file
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004860 si.hStdOutput = si.hStdInput;
4861 si.hStdError = si.hStdInput;
4862 }
4863
4864 /* Remove a trailing ", ) and )" if they have a match
4865 * at the start of the command. */
4866 if (cmdbase > cmd)
4867 {
4868 p = cmdbase + STRLEN(cmdbase);
4869 if (p > cmdbase && p[-1] == '"' && *cmd == '"')
4870 *--p = NUL;
4871 if (p > cmdbase && p[-1] == ')'
4872 && (*cmd =='(' || cmd[1] == '('))
4873 *--p = NUL;
4874 }
4875
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004876 newcmd = cmdbase;
4877 unescape_shellxquote(cmdbase, p_sxe);
4878
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004879 /*
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004880 * If creating new console, arguments are passed to the
4881 * 'cmd.exe' as-is. If it's not, arguments are not treated
4882 * correctly for current 'cmd.exe'. So unescape characters in
4883 * shellxescape except '|' for avoiding to be treated as
4884 * argument to them. Pass the arguments to sub-shell.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004885 */
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004886 if (flags != CREATE_NEW_CONSOLE)
4887 {
4888 char_u *subcmd;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004889 char_u *cmd_shell = mch_getenv("COMSPEC");
4890
4891 if (cmd_shell == NULL || *cmd_shell == NUL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004892 cmd_shell = (char_u *)default_shell();
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004893
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004894 subcmd = vim_strsave_escaped_ext(cmdbase,
4895 (char_u *)"|", '^', FALSE);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004896 if (subcmd != NULL)
4897 {
4898 /* make "cmd.exe /c arguments" */
4899 cmdlen = STRLEN(cmd_shell) + STRLEN(subcmd) + 5;
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004900 newcmd = lalloc(cmdlen, TRUE);
4901 if (newcmd != NULL)
4902 vim_snprintf((char *)newcmd, cmdlen, "%s /c %s",
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004903 cmd_shell, subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004904 else
4905 newcmd = cmdbase;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004906 vim_free(subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004907 }
4908 }
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004909
4910 /*
4911 * Now, start the command as a process, so that it doesn't
4912 * inherit our handles which causes unpleasant dangling swap
4913 * files if we exit before the spawned process
4914 */
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004915 if (vim_create_process((char *)newcmd, FALSE, flags, &si, &pi))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004916 x = 0;
4917 else
4918 {
4919 x = -1;
4920#ifdef FEAT_GUI_W32
4921 EMSG(_("E371: Command not found"));
4922#endif
4923 }
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004924
4925 if (newcmd != cmdbase)
4926 vim_free(newcmd);
4927
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01004928 if (si.dwFlags == STARTF_USESTDHANDLES && si.hStdInput != NULL)
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004929 {
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01004930 /* Close the handle to \\.\NUL created above. */
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004931 CloseHandle(si.hStdInput);
4932 }
4933 /* Close the handles to the subprocess, so that it goes away */
4934 CloseHandle(pi.hThread);
4935 CloseHandle(pi.hProcess);
4936 }
4937 else
4938 {
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004939 cmdlen = (
Bram Moolenaar071d4272004-06-13 20:20:40 +00004940#ifdef FEAT_GUI_W32
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004941 (allowPiping && !p_stmp ? 0 : STRLEN(vimrun_path)) +
Bram Moolenaar071d4272004-06-13 20:20:40 +00004942#endif
Bram Moolenaar0fde2902008-03-16 13:54:13 +00004943 STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10);
4944
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004945 newcmd = lalloc(cmdlen, TRUE);
4946 if (newcmd != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004947 {
4948#if defined(FEAT_GUI_W32)
4949 if (need_vimrun_warning)
4950 {
4951 MessageBox(NULL,
4952 _("VIMRUN.EXE not found in your $PATH.\n"
4953 "External commands will not pause after completion.\n"
4954 "See :help win32-vimrun for more information."),
4955 _("Vim Warning"),
4956 MB_ICONWARNING);
4957 need_vimrun_warning = FALSE;
4958 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004959 if (!s_dont_use_vimrun && (!allowPiping || p_stmp))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004960 /* Use vimrun to execute the command. It opens a console
4961 * window, which can be closed without killing Vim. */
Bram Moolenaarcc448b32010-07-14 16:52:17 +02004962 vim_snprintf((char *)newcmd, cmdlen, "%s%s%s %s %s",
Bram Moolenaar071d4272004-06-13 20:20:40 +00004963 vimrun_path,
4964 (msg_silent != 0 || (options & SHELL_DOOUT))
4965 ? "-s " : "",
4966 p_sh, p_shcf, cmd);
4967 else
4968#endif
Bram Moolenaarcc448b32010-07-14 16:52:17 +02004969 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s",
Bram Moolenaar0fde2902008-03-16 13:54:13 +00004970 p_sh, p_shcf, cmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004971 x = mch_system((char *)newcmd, options);
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004972 vim_free(newcmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004973 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004974 }
4975 }
4976
4977 if (tmode == TMODE_RAW)
4978 settmode(TMODE_RAW); /* set to raw mode */
4979
4980 /* Print the return value, unless "vimrun" was used. */
4981 if (x != 0 && !(options & SHELL_SILENT) && !emsg_silent
4982#if defined(FEAT_GUI_W32)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004983 && ((options & SHELL_DOOUT) || s_dont_use_vimrun
4984 || (allowPiping && !p_stmp))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004985#endif
4986 )
4987 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004988 smsg((char_u *)_("shell returned %d"), x);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004989 msg_putchar('\n');
4990 }
4991#ifdef FEAT_TITLE
4992 resettitle();
4993#endif
4994
4995 signal(SIGINT, SIG_DFL);
4996#if defined(__GNUC__) && !defined(__MINGW32__)
4997 signal(SIGKILL, SIG_DFL);
4998#else
4999 signal(SIGBREAK, SIG_DFL);
5000#endif
5001 signal(SIGILL, SIG_DFL);
5002 signal(SIGFPE, SIG_DFL);
5003 signal(SIGSEGV, SIG_DFL);
5004 signal(SIGTERM, SIG_DFL);
5005 signal(SIGABRT, SIG_DFL);
5006
5007 return x;
5008}
5009
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005010#if defined(FEAT_JOB) || defined(PROTO)
5011 void
Bram Moolenaar9a6e33a2016-02-16 19:25:12 +01005012mch_start_job(char *cmd, job_T *job, jobopt_T *options)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005013{
5014 STARTUPINFO si;
5015 PROCESS_INFORMATION pi;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005016 HANDLE jo;
Bram Moolenaar16eb4f82016-02-14 23:02:34 +01005017# ifdef FEAT_CHANNEL
5018 channel_T *channel;
Bram Moolenaard8070362016-02-15 21:56:54 +01005019 HANDLE ifd[2];
5020 HANDLE ofd[2];
5021 HANDLE efd[2];
5022 SECURITY_ATTRIBUTES saAttr;
5023
5024 ifd[0] = INVALID_HANDLE_VALUE;
5025 ifd[1] = INVALID_HANDLE_VALUE;
5026 ofd[0] = INVALID_HANDLE_VALUE;
5027 ofd[1] = INVALID_HANDLE_VALUE;
5028 efd[0] = INVALID_HANDLE_VALUE;
5029 efd[1] = INVALID_HANDLE_VALUE;
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005030
5031 channel = add_channel();
5032 if (channel == NULL)
5033 return;
Bram Moolenaar16eb4f82016-02-14 23:02:34 +01005034# endif
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005035
Bram Moolenaar76467df2016-02-12 19:30:26 +01005036 jo = CreateJobObject(NULL, NULL);
5037 if (jo == NULL)
5038 {
5039 job->jv_status = JOB_FAILED;
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005040 goto failed;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005041 }
5042
5043 ZeroMemory(&pi, sizeof(pi));
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005044 ZeroMemory(&si, sizeof(si));
5045 si.cb = sizeof(si);
Bram Moolenaard8070362016-02-15 21:56:54 +01005046 si.dwFlags |= STARTF_USESHOWWINDOW;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005047 si.wShowWindow = SW_HIDE;
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005048
Bram Moolenaar5d54a042016-02-16 16:39:51 +01005049# ifdef FEAT_CHANNEL
Bram Moolenaard8070362016-02-15 21:56:54 +01005050 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
5051 saAttr.bInheritHandle = TRUE;
5052 saAttr.lpSecurityDescriptor = NULL;
5053 if (!CreatePipe(&ifd[0], &ifd[1], &saAttr, 0)
5054 || !pSetHandleInformation(ifd[1], HANDLE_FLAG_INHERIT, 0)
5055 || !CreatePipe(&ofd[0], &ofd[1], &saAttr, 0)
5056 || !pSetHandleInformation(ofd[0], HANDLE_FLAG_INHERIT, 0)
5057 || !CreatePipe(&efd[0], &efd[1], &saAttr, 0)
5058 || !pSetHandleInformation(efd[0], HANDLE_FLAG_INHERIT, 0))
5059 goto failed;
5060 si.dwFlags |= STARTF_USESTDHANDLES;
5061 si.hStdInput = ifd[0];
5062 si.hStdOutput = ofd[1];
5063 si.hStdError = efd[1];
Bram Moolenaar5d54a042016-02-16 16:39:51 +01005064# endif
Bram Moolenaard8070362016-02-15 21:56:54 +01005065
5066 if (!vim_create_process(cmd, TRUE,
Bram Moolenaar76467df2016-02-12 19:30:26 +01005067 CREATE_SUSPENDED |
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005068 CREATE_DEFAULT_ERROR_MODE |
5069 CREATE_NEW_PROCESS_GROUP |
Bram Moolenaar76467df2016-02-12 19:30:26 +01005070 CREATE_NEW_CONSOLE,
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005071 &si, &pi))
Bram Moolenaar76467df2016-02-12 19:30:26 +01005072 {
5073 CloseHandle(jo);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005074 job->jv_status = JOB_FAILED;
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005075 goto failed;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005076 }
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005077
5078 if (!AssignProcessToJobObject(jo, pi.hProcess))
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005079 {
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005080 /* if failing, switch the way to terminate
5081 * process with TerminateProcess. */
5082 CloseHandle(jo);
5083 jo = NULL;
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005084 }
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005085 ResumeThread(pi.hThread);
5086 CloseHandle(job->jv_proc_info.hThread);
5087 job->jv_proc_info = pi;
5088 job->jv_job_object = jo;
5089 job->jv_status = JOB_STARTED;
5090
Bram Moolenaar5d54a042016-02-16 16:39:51 +01005091# ifdef FEAT_CHANNEL
Bram Moolenaard8070362016-02-15 21:56:54 +01005092 CloseHandle(ifd[0]);
5093 CloseHandle(ofd[1]);
5094 CloseHandle(efd[1]);
5095
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005096 job->jv_channel = channel;
Bram Moolenaard8070362016-02-15 21:56:54 +01005097 channel_set_pipes(channel, (sock_T)ifd[1], (sock_T)ofd[0], (sock_T)efd[0]);
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005098 channel_set_job(channel, job);
Bram Moolenaar910b8aa2016-02-16 21:03:07 +01005099 channel_set_options(channel, options);
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005100
Bram Moolenaar16eb4f82016-02-14 23:02:34 +01005101# ifdef FEAT_GUI
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005102 channel_gui_register(channel);
Bram Moolenaar16eb4f82016-02-14 23:02:34 +01005103# endif
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005104# endif
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005105 return;
5106
5107failed:
Bram Moolenaar16eb4f82016-02-14 23:02:34 +01005108# ifdef FEAT_CHANNEL
Bram Moolenaard8070362016-02-15 21:56:54 +01005109 CloseHandle(ifd[0]);
5110 CloseHandle(ofd[0]);
5111 CloseHandle(efd[0]);
5112 CloseHandle(ifd[1]);
5113 CloseHandle(ofd[1]);
5114 CloseHandle(efd[1]);
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005115 channel_free(channel);
Bram Moolenaar71b0f7b2016-02-15 12:44:20 +01005116# else
5117 ; /* make compiler happy */
Bram Moolenaar16eb4f82016-02-14 23:02:34 +01005118# endif
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005119}
5120
5121 char *
5122mch_job_status(job_T *job)
5123{
5124 DWORD dwExitCode = 0;
5125
Bram Moolenaar76467df2016-02-12 19:30:26 +01005126 if (!GetExitCodeProcess(job->jv_proc_info.hProcess, &dwExitCode)
5127 || dwExitCode != STILL_ACTIVE)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005128 {
Bram Moolenaar76467df2016-02-12 19:30:26 +01005129 job->jv_status = JOB_ENDED;
Bram Moolenaareab089d2016-02-21 19:32:02 +01005130 job->jv_exitval = (int)dwExitCode;
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005131 return "dead";
5132 }
5133 return "run";
5134}
5135
5136 int
5137mch_stop_job(job_T *job, char_u *how)
5138{
Bram Moolenaar76467df2016-02-12 19:30:26 +01005139 int ret = 0;
5140 int ctrl_c = STRCMP(how, "int") == 0;
5141
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005142 if (STRCMP(how, "kill") == 0)
Bram Moolenaar76467df2016-02-12 19:30:26 +01005143 {
5144 if (job->jv_job_object != NULL)
5145 return TerminateJobObject(job->jv_job_object, 0) ? OK : FAIL;
5146 else
5147 return TerminateProcess(job->jv_proc_info.hProcess, 0) ? OK : FAIL;
5148 }
5149
5150 if (!AttachConsole(job->jv_proc_info.dwProcessId))
5151 return FAIL;
5152 ret = GenerateConsoleCtrlEvent(
5153 ctrl_c ? CTRL_C_EVENT : CTRL_BREAK_EVENT,
5154 job->jv_proc_info.dwProcessId)
5155 ? OK : FAIL;
5156 FreeConsole();
5157 return ret;
5158}
5159
5160/*
5161 * Clear the data related to "job".
5162 */
5163 void
5164mch_clear_job(job_T *job)
5165{
5166 if (job->jv_status != JOB_FAILED)
5167 {
5168 if (job->jv_job_object != NULL)
5169 CloseHandle(job->jv_job_object);
5170 CloseHandle(job->jv_proc_info.hProcess);
5171 }
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005172}
5173#endif
5174
Bram Moolenaar071d4272004-06-13 20:20:40 +00005175
5176#ifndef FEAT_GUI_W32
5177
5178/*
5179 * Start termcap mode
5180 */
5181 static void
5182termcap_mode_start(void)
5183{
5184 DWORD cmodein;
5185
5186 if (g_fTermcapMode)
5187 return;
5188
5189 SaveConsoleBuffer(&g_cbNonTermcap);
5190
5191 if (g_cbTermcap.IsValid)
5192 {
5193 /*
5194 * We've been in termcap mode before. Restore certain screen
5195 * characteristics, including the buffer size and the window
5196 * size. Since we will be redrawing the screen, we don't need
5197 * to restore the actual contents of the buffer.
5198 */
5199 RestoreConsoleBuffer(&g_cbTermcap, FALSE);
5200 SetConsoleWindowInfo(g_hConOut, TRUE, &g_cbTermcap.Info.srWindow);
5201 Rows = g_cbTermcap.Info.dwSize.Y;
5202 Columns = g_cbTermcap.Info.dwSize.X;
5203 }
5204 else
5205 {
5206 /*
5207 * This is our first time entering termcap mode. Clear the console
5208 * screen buffer, and resize the buffer to match the current window
5209 * size. We will use this as the size of our editing environment.
5210 */
5211 ClearConsoleBuffer(g_attrCurrent);
5212 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
5213 }
5214
5215#ifdef FEAT_TITLE
5216 resettitle();
5217#endif
5218
5219 GetConsoleMode(g_hConIn, &cmodein);
5220#ifdef FEAT_MOUSE
5221 if (g_fMouseActive)
5222 cmodein |= ENABLE_MOUSE_INPUT;
5223 else
5224 cmodein &= ~ENABLE_MOUSE_INPUT;
5225#endif
5226 cmodein |= ENABLE_WINDOW_INPUT;
5227 SetConsoleMode(g_hConIn, cmodein);
5228
5229 redraw_later_clear();
5230 g_fTermcapMode = TRUE;
5231}
5232
5233
5234/*
5235 * End termcap mode
5236 */
5237 static void
5238termcap_mode_end(void)
5239{
5240 DWORD cmodein;
5241 ConsoleBuffer *cb;
5242 COORD coord;
5243 DWORD dwDummy;
5244
5245 if (!g_fTermcapMode)
5246 return;
5247
5248 SaveConsoleBuffer(&g_cbTermcap);
5249
5250 GetConsoleMode(g_hConIn, &cmodein);
5251 cmodein &= ~(ENABLE_MOUSE_INPUT | ENABLE_WINDOW_INPUT);
5252 SetConsoleMode(g_hConIn, cmodein);
5253
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01005254#ifdef FEAT_RESTORE_ORIG_SCREEN
5255 cb = exiting ? &g_cbOrig : &g_cbNonTermcap;
5256#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00005257 cb = &g_cbNonTermcap;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01005258#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005259 RestoreConsoleBuffer(cb, p_rs);
5260 SetConsoleCursorInfo(g_hConOut, &g_cci);
5261
5262 if (p_rs || exiting)
5263 {
5264 /*
5265 * Clear anything that happens to be on the current line.
5266 */
5267 coord.X = 0;
5268 coord.Y = (SHORT) (p_rs ? cb->Info.dwCursorPosition.Y : (Rows - 1));
5269 FillConsoleOutputCharacter(g_hConOut, ' ',
5270 cb->Info.dwSize.X, coord, &dwDummy);
5271 /*
5272 * The following is just for aesthetics. If we are exiting without
5273 * restoring the screen, then we want to have a prompt string
5274 * appear at the bottom line. However, the command interpreter
5275 * seems to always advance the cursor one line before displaying
5276 * the prompt string, which causes the screen to scroll. To
5277 * counter this, move the cursor up one line before exiting.
5278 */
5279 if (exiting && !p_rs)
5280 coord.Y--;
5281 /*
5282 * Position the cursor at the leftmost column of the desired row.
5283 */
5284 SetConsoleCursorPosition(g_hConOut, coord);
5285 }
5286
5287 g_fTermcapMode = FALSE;
5288}
5289#endif /* FEAT_GUI_W32 */
5290
5291
5292#ifdef FEAT_GUI_W32
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00005293/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00005294 void
5295mch_write(
5296 char_u *s,
5297 int len)
5298{
5299 /* never used */
5300}
5301
5302#else
5303
5304/*
5305 * clear `n' chars, starting from `coord'
5306 */
5307 static void
5308clear_chars(
5309 COORD coord,
5310 DWORD n)
5311{
5312 DWORD dwDummy;
5313
5314 FillConsoleOutputCharacter(g_hConOut, ' ', n, coord, &dwDummy);
5315 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, n, coord, &dwDummy);
5316}
5317
5318
5319/*
5320 * Clear the screen
5321 */
5322 static void
5323clear_screen(void)
5324{
5325 g_coord.X = g_coord.Y = 0;
5326 clear_chars(g_coord, Rows * Columns);
5327}
5328
5329
5330/*
5331 * Clear to end of display
5332 */
5333 static void
5334clear_to_end_of_display(void)
5335{
5336 clear_chars(g_coord, (Rows - g_coord.Y - 1)
5337 * Columns + (Columns - g_coord.X));
5338}
5339
5340
5341/*
5342 * Clear to end of line
5343 */
5344 static void
5345clear_to_end_of_line(void)
5346{
5347 clear_chars(g_coord, Columns - g_coord.X);
5348}
5349
5350
5351/*
5352 * Scroll the scroll region up by `cLines' lines
5353 */
5354 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005355scroll(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005356{
5357 COORD oldcoord = g_coord;
5358
5359 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
5360 delete_lines(cLines);
5361
5362 g_coord = oldcoord;
5363}
5364
5365
5366/*
5367 * Set the scroll region
5368 */
5369 static void
5370set_scroll_region(
5371 unsigned left,
5372 unsigned top,
5373 unsigned right,
5374 unsigned bottom)
5375{
5376 if (left >= right
5377 || top >= bottom
5378 || right > (unsigned) Columns - 1
5379 || bottom > (unsigned) Rows - 1)
5380 return;
5381
5382 g_srScrollRegion.Left = left;
5383 g_srScrollRegion.Top = top;
5384 g_srScrollRegion.Right = right;
5385 g_srScrollRegion.Bottom = bottom;
5386}
5387
5388
5389/*
5390 * Insert `cLines' lines at the current cursor position
5391 */
5392 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005393insert_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005394{
5395 SMALL_RECT source;
5396 COORD dest;
5397 CHAR_INFO fill;
5398
5399 dest.X = 0;
5400 dest.Y = g_coord.Y + cLines;
5401
5402 source.Left = 0;
5403 source.Top = g_coord.Y;
5404 source.Right = g_srScrollRegion.Right;
5405 source.Bottom = g_srScrollRegion.Bottom - cLines;
5406
5407 fill.Char.AsciiChar = ' ';
5408 fill.Attributes = g_attrCurrent;
5409
5410 ScrollConsoleScreenBuffer(g_hConOut, &source, NULL, dest, &fill);
5411
5412 /* Here we have to deal with a win32 console flake: If the scroll
5413 * region looks like abc and we scroll c to a and fill with d we get
5414 * cbd... if we scroll block c one line at a time to a, we get cdd...
5415 * vim expects cdd consistently... So we have to deal with that
5416 * here... (this also occurs scrolling the same way in the other
5417 * direction). */
5418
5419 if (source.Bottom < dest.Y)
5420 {
5421 COORD coord;
5422
5423 coord.X = 0;
5424 coord.Y = source.Bottom;
5425 clear_chars(coord, Columns * (dest.Y - source.Bottom));
5426 }
5427}
5428
5429
5430/*
5431 * Delete `cLines' lines at the current cursor position
5432 */
5433 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005434delete_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005435{
5436 SMALL_RECT source;
5437 COORD dest;
5438 CHAR_INFO fill;
5439 int nb;
5440
5441 dest.X = 0;
5442 dest.Y = g_coord.Y;
5443
5444 source.Left = 0;
5445 source.Top = g_coord.Y + cLines;
5446 source.Right = g_srScrollRegion.Right;
5447 source.Bottom = g_srScrollRegion.Bottom;
5448
5449 fill.Char.AsciiChar = ' ';
5450 fill.Attributes = g_attrCurrent;
5451
5452 ScrollConsoleScreenBuffer(g_hConOut, &source, NULL, dest, &fill);
5453
5454 /* Here we have to deal with a win32 console flake: If the scroll
5455 * region looks like abc and we scroll c to a and fill with d we get
5456 * cbd... if we scroll block c one line at a time to a, we get cdd...
5457 * vim expects cdd consistently... So we have to deal with that
5458 * here... (this also occurs scrolling the same way in the other
5459 * direction). */
5460
5461 nb = dest.Y + (source.Bottom - source.Top) + 1;
5462
5463 if (nb < source.Top)
5464 {
5465 COORD coord;
5466
5467 coord.X = 0;
5468 coord.Y = nb;
5469 clear_chars(coord, Columns * (source.Top - nb));
5470 }
5471}
5472
5473
5474/*
5475 * Set the cursor position
5476 */
5477 static void
5478gotoxy(
5479 unsigned x,
5480 unsigned y)
5481{
5482 if (x < 1 || x > (unsigned)Columns || y < 1 || y > (unsigned)Rows)
5483 return;
5484
5485 /* external cursor coords are 1-based; internal are 0-based */
5486 g_coord.X = x - 1;
5487 g_coord.Y = y - 1;
5488 SetConsoleCursorPosition(g_hConOut, g_coord);
5489}
5490
5491
5492/*
5493 * Set the current text attribute = (foreground | background)
5494 * See ../doc/os_win32.txt for the numbers.
5495 */
5496 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005497textattr(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005498{
Bram Moolenaar6383b922015-03-24 17:12:19 +01005499 g_attrCurrent = wAttr & 0xff;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005500
5501 SetConsoleTextAttribute(g_hConOut, wAttr);
5502}
5503
5504
5505 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005506textcolor(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005507{
Bram Moolenaar6383b922015-03-24 17:12:19 +01005508 g_attrCurrent = (g_attrCurrent & 0xf0) + (wAttr & 0x0f);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005509
5510 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
5511}
5512
5513
5514 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005515textbackground(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005516{
Bram Moolenaar6383b922015-03-24 17:12:19 +01005517 g_attrCurrent = (g_attrCurrent & 0x0f) + ((wAttr & 0x0f) << 4);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005518
5519 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
5520}
5521
5522
5523/*
5524 * restore the default text attribute (whatever we started with)
5525 */
5526 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005527normvideo(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005528{
5529 textattr(g_attrDefault);
5530}
5531
5532
5533static WORD g_attrPreStandout = 0;
5534
5535/*
5536 * Make the text standout, by brightening it
5537 */
5538 static void
5539standout(void)
5540{
5541 g_attrPreStandout = g_attrCurrent;
5542 textattr((WORD) (g_attrCurrent|FOREGROUND_INTENSITY|BACKGROUND_INTENSITY));
5543}
5544
5545
5546/*
5547 * Turn off standout mode
5548 */
5549 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005550standend(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005551{
5552 if (g_attrPreStandout)
5553 {
5554 textattr(g_attrPreStandout);
5555 g_attrPreStandout = 0;
5556 }
5557}
5558
5559
5560/*
Bram Moolenaarff1d0d42007-05-10 17:24:16 +00005561 * Set normal fg/bg color, based on T_ME. Called when t_me has been set.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005562 */
5563 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005564mch_set_normal_colors(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005565{
5566 char_u *p;
5567 int n;
5568
5569 cterm_normal_fg_color = (g_attrDefault & 0xf) + 1;
5570 cterm_normal_bg_color = ((g_attrDefault >> 4) & 0xf) + 1;
5571 if (T_ME[0] == ESC && T_ME[1] == '|')
5572 {
5573 p = T_ME + 2;
5574 n = getdigits(&p);
5575 if (*p == 'm' && n > 0)
5576 {
5577 cterm_normal_fg_color = (n & 0xf) + 1;
5578 cterm_normal_bg_color = ((n >> 4) & 0xf) + 1;
5579 }
5580 }
5581}
5582
5583
5584/*
5585 * visual bell: flash the screen
5586 */
5587 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005588visual_bell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005589{
5590 COORD coordOrigin = {0, 0};
5591 WORD attrFlash = ~g_attrCurrent & 0xff;
5592
5593 DWORD dwDummy;
5594 LPWORD oldattrs = (LPWORD)alloc(Rows * Columns * sizeof(WORD));
5595
5596 if (oldattrs == NULL)
5597 return;
5598 ReadConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
5599 coordOrigin, &dwDummy);
5600 FillConsoleOutputAttribute(g_hConOut, attrFlash, Rows * Columns,
5601 coordOrigin, &dwDummy);
5602
5603 Sleep(15); /* wait for 15 msec */
5604 WriteConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
5605 coordOrigin, &dwDummy);
5606 vim_free(oldattrs);
5607}
5608
5609
5610/*
5611 * Make the cursor visible or invisible
5612 */
5613 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005614cursor_visible(BOOL fVisible)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005615{
5616 s_cursor_visible = fVisible;
5617#ifdef MCH_CURSOR_SHAPE
5618 mch_update_cursor();
5619#endif
5620}
5621
5622
5623/*
Bram Moolenaarac360bf2015-09-01 20:31:20 +02005624 * write `cbToWrite' bytes in `pchBuf' to the screen
5625 * Returns the number of bytes actually written (at least one).
Bram Moolenaar071d4272004-06-13 20:20:40 +00005626 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02005627 static DWORD
Bram Moolenaar071d4272004-06-13 20:20:40 +00005628write_chars(
Bram Moolenaarac360bf2015-09-01 20:31:20 +02005629 char_u *pchBuf,
5630 DWORD cbToWrite)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005631{
5632 COORD coord = g_coord;
5633 DWORD written;
5634
Bram Moolenaarac360bf2015-09-01 20:31:20 +02005635#ifdef FEAT_MBYTE
5636 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
5637 {
5638 static WCHAR *unicodebuf = NULL;
5639 static int unibuflen = 0;
5640 int length;
5641 DWORD n, cchwritten, cells;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005642
Bram Moolenaarac360bf2015-09-01 20:31:20 +02005643 length = MultiByteToWideChar(CP_UTF8, 0, (LPCSTR)pchBuf, cbToWrite, 0, 0);
5644 if (unicodebuf == NULL || length > unibuflen)
5645 {
5646 vim_free(unicodebuf);
5647 unicodebuf = (WCHAR *)lalloc(length * sizeof(WCHAR), FALSE);
5648 unibuflen = length;
5649 }
5650 MultiByteToWideChar(CP_UTF8, 0, (LPCSTR)pchBuf, cbToWrite,
5651 unicodebuf, unibuflen);
5652
5653 cells = mb_string2cells(pchBuf, cbToWrite);
5654 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, cells,
5655 coord, &written);
5656 /* When writing fails or didn't write a single character, pretend one
5657 * character was written, otherwise we get stuck. */
5658 if (WriteConsoleOutputCharacterW(g_hConOut, unicodebuf, length,
5659 coord, &cchwritten) == 0
5660 || cchwritten == 0)
5661 cchwritten = 1;
5662
5663 if (cchwritten == length)
5664 {
5665 written = cbToWrite;
5666 g_coord.X += (SHORT)cells;
5667 }
5668 else
5669 {
5670 char_u *p = pchBuf;
5671 for (n = 0; n < cchwritten; n++)
5672 mb_cptr_adv(p);
5673 written = p - pchBuf;
5674 g_coord.X += (SHORT)mb_string2cells(pchBuf, written);
5675 }
5676 }
5677 else
5678#endif
5679 {
5680 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, cbToWrite,
5681 coord, &written);
5682 /* When writing fails or didn't write a single character, pretend one
5683 * character was written, otherwise we get stuck. */
5684 if (WriteConsoleOutputCharacter(g_hConOut, (LPCSTR)pchBuf, cbToWrite,
5685 coord, &written) == 0
5686 || written == 0)
5687 written = 1;
5688
5689 g_coord.X += (SHORT) written;
5690 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005691
5692 while (g_coord.X > g_srScrollRegion.Right)
5693 {
5694 g_coord.X -= (SHORT) Columns;
5695 if (g_coord.Y < g_srScrollRegion.Bottom)
5696 g_coord.Y++;
5697 }
5698
5699 gotoxy(g_coord.X + 1, g_coord.Y + 1);
5700
5701 return written;
5702}
5703
5704
5705/*
5706 * mch_write(): write the output buffer to the screen, translating ESC
5707 * sequences into calls to console output routines.
5708 */
5709 void
5710mch_write(
5711 char_u *s,
5712 int len)
5713{
5714 s[len] = NUL;
5715
5716 if (!term_console)
5717 {
5718 write(1, s, (unsigned)len);
5719 return;
5720 }
5721
5722 /* translate ESC | sequences into faked bios calls */
5723 while (len--)
5724 {
5725 /* optimization: use one single write_chars for runs of text,
5726 * rather than once per character It ain't curses, but it helps. */
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01005727 DWORD prefix = (DWORD)strcspn((char *)s, "\n\r\b\a\033");
Bram Moolenaar071d4272004-06-13 20:20:40 +00005728
5729 if (p_wd)
5730 {
5731 WaitForChar(p_wd);
5732 if (prefix != 0)
5733 prefix = 1;
5734 }
5735
5736 if (prefix != 0)
5737 {
5738 DWORD nWritten;
5739
5740 nWritten = write_chars(s, prefix);
5741#ifdef MCH_WRITE_DUMP
5742 if (fdDump)
5743 {
5744 fputc('>', fdDump);
5745 fwrite(s, sizeof(char_u), nWritten, fdDump);
5746 fputs("<\n", fdDump);
5747 }
5748#endif
5749 len -= (nWritten - 1);
5750 s += nWritten;
5751 }
5752 else if (s[0] == '\n')
5753 {
5754 /* \n, newline: go to the beginning of the next line or scroll */
5755 if (g_coord.Y == g_srScrollRegion.Bottom)
5756 {
5757 scroll(1);
5758 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Bottom + 1);
5759 }
5760 else
5761 {
5762 gotoxy(g_srScrollRegion.Left + 1, g_coord.Y + 2);
5763 }
5764#ifdef MCH_WRITE_DUMP
5765 if (fdDump)
5766 fputs("\\n\n", fdDump);
5767#endif
5768 s++;
5769 }
5770 else if (s[0] == '\r')
5771 {
5772 /* \r, carriage return: go to beginning of line */
5773 gotoxy(g_srScrollRegion.Left+1, g_coord.Y + 1);
5774#ifdef MCH_WRITE_DUMP
5775 if (fdDump)
5776 fputs("\\r\n", fdDump);
5777#endif
5778 s++;
5779 }
5780 else if (s[0] == '\b')
5781 {
5782 /* \b, backspace: move cursor one position left */
5783 if (g_coord.X > g_srScrollRegion.Left)
5784 g_coord.X--;
5785 else if (g_coord.Y > g_srScrollRegion.Top)
5786 {
5787 g_coord.X = g_srScrollRegion.Right;
5788 g_coord.Y--;
5789 }
5790 gotoxy(g_coord.X + 1, g_coord.Y + 1);
5791#ifdef MCH_WRITE_DUMP
5792 if (fdDump)
5793 fputs("\\b\n", fdDump);
5794#endif
5795 s++;
5796 }
5797 else if (s[0] == '\a')
5798 {
5799 /* \a, bell */
5800 MessageBeep(0xFFFFFFFF);
5801#ifdef MCH_WRITE_DUMP
5802 if (fdDump)
5803 fputs("\\a\n", fdDump);
5804#endif
5805 s++;
5806 }
5807 else if (s[0] == ESC && len >= 3-1 && s[1] == '|')
5808 {
5809#ifdef MCH_WRITE_DUMP
Bram Moolenaarc0197e22004-09-13 20:26:32 +00005810 char_u *old_s = s;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005811#endif
Bram Moolenaarc0197e22004-09-13 20:26:32 +00005812 char_u *p;
5813 int arg1 = 0, arg2 = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005814
5815 switch (s[2])
5816 {
5817 /* one or two numeric arguments, separated by ';' */
5818
5819 case '0': case '1': case '2': case '3': case '4':
5820 case '5': case '6': case '7': case '8': case '9':
5821 p = s + 2;
5822 arg1 = getdigits(&p); /* no check for length! */
5823 if (p > s + len)
5824 break;
5825
5826 if (*p == ';')
5827 {
5828 ++p;
5829 arg2 = getdigits(&p); /* no check for length! */
5830 if (p > s + len)
5831 break;
5832
5833 if (*p == 'H')
5834 gotoxy(arg2, arg1);
5835 else if (*p == 'r')
5836 set_scroll_region(0, arg1 - 1, Columns - 1, arg2 - 1);
5837 }
5838 else if (*p == 'A')
5839 {
5840 /* move cursor up arg1 lines in same column */
5841 gotoxy(g_coord.X + 1,
5842 max(g_srScrollRegion.Top, g_coord.Y - arg1) + 1);
5843 }
5844 else if (*p == 'C')
5845 {
5846 /* move cursor right arg1 columns in same line */
5847 gotoxy(min(g_srScrollRegion.Right, g_coord.X + arg1) + 1,
5848 g_coord.Y + 1);
5849 }
5850 else if (*p == 'H')
5851 {
5852 gotoxy(1, arg1);
5853 }
5854 else if (*p == 'L')
5855 {
5856 insert_lines(arg1);
5857 }
5858 else if (*p == 'm')
5859 {
5860 if (arg1 == 0)
5861 normvideo();
5862 else
5863 textattr((WORD) arg1);
5864 }
5865 else if (*p == 'f')
5866 {
5867 textcolor((WORD) arg1);
5868 }
5869 else if (*p == 'b')
5870 {
5871 textbackground((WORD) arg1);
5872 }
5873 else if (*p == 'M')
5874 {
5875 delete_lines(arg1);
5876 }
5877
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005878 len -= (int)(p - s);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005879 s = p + 1;
5880 break;
5881
5882
5883 /* Three-character escape sequences */
5884
5885 case 'A':
5886 /* move cursor up one line in same column */
5887 gotoxy(g_coord.X + 1,
5888 max(g_srScrollRegion.Top, g_coord.Y - 1) + 1);
5889 goto got3;
5890
5891 case 'B':
5892 visual_bell();
5893 goto got3;
5894
5895 case 'C':
5896 /* move cursor right one column in same line */
5897 gotoxy(min(g_srScrollRegion.Right, g_coord.X + 1) + 1,
5898 g_coord.Y + 1);
5899 goto got3;
5900
5901 case 'E':
5902 termcap_mode_end();
5903 goto got3;
5904
5905 case 'F':
5906 standout();
5907 goto got3;
5908
5909 case 'f':
5910 standend();
5911 goto got3;
5912
5913 case 'H':
5914 gotoxy(1, 1);
5915 goto got3;
5916
5917 case 'j':
5918 clear_to_end_of_display();
5919 goto got3;
5920
5921 case 'J':
5922 clear_screen();
5923 goto got3;
5924
5925 case 'K':
5926 clear_to_end_of_line();
5927 goto got3;
5928
5929 case 'L':
5930 insert_lines(1);
5931 goto got3;
5932
5933 case 'M':
5934 delete_lines(1);
5935 goto got3;
5936
5937 case 'S':
5938 termcap_mode_start();
5939 goto got3;
5940
5941 case 'V':
5942 cursor_visible(TRUE);
5943 goto got3;
5944
5945 case 'v':
5946 cursor_visible(FALSE);
5947 goto got3;
5948
5949 got3:
5950 s += 3;
5951 len -= 2;
5952 }
5953
5954#ifdef MCH_WRITE_DUMP
5955 if (fdDump)
5956 {
5957 fputs("ESC | ", fdDump);
5958 fwrite(old_s + 2, sizeof(char_u), s - old_s - 2, fdDump);
5959 fputc('\n', fdDump);
5960 }
5961#endif
5962 }
5963 else
5964 {
5965 /* Write a single character */
5966 DWORD nWritten;
5967
5968 nWritten = write_chars(s, 1);
5969#ifdef MCH_WRITE_DUMP
5970 if (fdDump)
5971 {
5972 fputc('>', fdDump);
5973 fwrite(s, sizeof(char_u), nWritten, fdDump);
5974 fputs("<\n", fdDump);
5975 }
5976#endif
5977
5978 len -= (nWritten - 1);
5979 s += nWritten;
5980 }
5981 }
5982
5983#ifdef MCH_WRITE_DUMP
5984 if (fdDump)
5985 fflush(fdDump);
5986#endif
5987}
5988
5989#endif /* FEAT_GUI_W32 */
5990
5991
5992/*
5993 * Delay for half a second.
5994 */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00005995/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00005996 void
5997mch_delay(
5998 long msec,
5999 int ignoreinput)
6000{
6001#ifdef FEAT_GUI_W32
6002 Sleep((int)msec); /* never wait for input */
Bram Moolenaar325b7a22004-07-05 15:58:32 +00006003#else /* Console */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006004 if (ignoreinput)
Bram Moolenaar325b7a22004-07-05 15:58:32 +00006005# ifdef FEAT_MZSCHEME
6006 if (mzthreads_allowed() && p_mzq > 0 && msec > p_mzq)
6007 {
6008 int towait = p_mzq;
6009
6010 /* if msec is large enough, wait by portions in p_mzq */
6011 while (msec > 0)
6012 {
6013 mzvim_check_threads();
6014 if (msec < towait)
6015 towait = msec;
6016 Sleep(towait);
6017 msec -= towait;
6018 }
6019 }
6020 else
6021# endif
6022 Sleep((int)msec);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006023 else
6024 WaitForChar(msec);
6025#endif
6026}
6027
6028
6029/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01006030 * This version of remove is not scared by a readonly (backup) file.
6031 * This can also remove a symbolic link like Unix.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006032 * Return 0 for success, -1 for failure.
6033 */
6034 int
6035mch_remove(char_u *name)
6036{
6037#ifdef FEAT_MBYTE
6038 WCHAR *wn = NULL;
6039 int n;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02006040#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006041
Bram Moolenaar203258c2016-01-17 22:15:16 +01006042 /*
6043 * On Windows, deleting a directory's symbolic link is done by
6044 * RemoveDirectory(): mch_rmdir. It seems unnatural, but it is fact.
6045 */
6046 if (mch_isdir(name) && mch_is_symbolic_link(name))
6047 return mch_rmdir(name);
6048
Bram Moolenaar12b559e2013-06-12 22:41:37 +02006049 win32_setattrs(name, FILE_ATTRIBUTE_NORMAL);
6050
6051#ifdef FEAT_MBYTE
Bram Moolenaar071d4272004-06-13 20:20:40 +00006052 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
6053 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006054 wn = enc_to_utf16(name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006055 if (wn != NULL)
6056 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006057 n = DeleteFileW(wn) ? 0 : -1;
6058 vim_free(wn);
6059 if (n == 0 || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
6060 return n;
6061 /* Retry with non-wide function (for Windows 98). */
6062 }
6063 }
6064#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006065 return DeleteFile((LPCSTR)name) ? 0 : -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006066}
6067
6068
6069/*
6070 * check for an "interrupt signal": CTRL-break or CTRL-C
6071 */
6072 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006073mch_breakcheck(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006074{
6075#ifndef FEAT_GUI_W32 /* never used */
6076 if (g_fCtrlCPressed || g_fCBrkPressed)
6077 {
6078 g_fCtrlCPressed = g_fCBrkPressed = FALSE;
6079 got_int = TRUE;
6080 }
6081#endif
6082}
6083
Bram Moolenaaree273972016-01-02 21:11:51 +01006084/* physical RAM to leave for the OS */
6085#define WINNT_RESERVE_BYTES (256*1024*1024)
6086#define WIN95_RESERVE_BYTES (8*1024*1024)
6087
6088/*
6089 * How much main memory in KiB that can be used by VIM.
6090 */
6091/*ARGSUSED*/
6092 long_u
6093mch_total_mem(int special)
6094{
6095 PlatformId();
6096#if (defined(_MSC_VER) && (WINVER > 0x0400)) || defined(MEMORYSTATUSEX)
6097 if (g_PlatformId == VER_PLATFORM_WIN32_NT)
6098 {
6099 MEMORYSTATUSEX ms;
6100
6101 /* Need to use GlobalMemoryStatusEx() when there is more memory than
6102 * what fits in 32 bits. But it's not always available. */
6103 ms.dwLength = sizeof(MEMORYSTATUSEX);
6104 GlobalMemoryStatusEx(&ms);
6105 if (ms.ullAvailVirtual < ms.ullTotalPhys)
6106 {
6107 /* Process address space fits in physical RAM, use all of it. */
6108 return (long_u)(ms.ullAvailVirtual / 1024);
6109 }
6110 if (ms.ullTotalPhys <= WINNT_RESERVE_BYTES)
6111 {
6112 /* Catch old NT box or perverse hardware setup. */
6113 return (long_u)((ms.ullTotalPhys / 2) / 1024);
6114 }
6115 /* Use physical RAM less reserve for OS + data. */
6116 return (long_u)((ms.ullTotalPhys - WINNT_RESERVE_BYTES) / 1024);
6117 }
6118 else
6119#endif
6120 {
6121 /* Pre-XP or 95 OS handling. */
6122 MEMORYSTATUS ms;
6123 long_u os_reserve_bytes;
6124
6125 ms.dwLength = sizeof(MEMORYSTATUS);
6126 GlobalMemoryStatus(&ms);
6127 if (ms.dwAvailVirtual < ms.dwTotalPhys)
6128 {
6129 /* Process address space fits in physical RAM, use all of it. */
6130 return (long_u)(ms.dwAvailVirtual / 1024);
6131 }
6132 os_reserve_bytes = (g_PlatformId == VER_PLATFORM_WIN32_NT)
6133 ? WINNT_RESERVE_BYTES
6134 : WIN95_RESERVE_BYTES;
6135 if (ms.dwTotalPhys <= os_reserve_bytes)
6136 {
6137 /* Catch old boxes or perverse hardware setup. */
6138 return (long_u)((ms.dwTotalPhys / 2) / 1024);
6139 }
6140 /* Use physical RAM less reserve for OS + data. */
6141 return (long_u)((ms.dwTotalPhys - os_reserve_bytes) / 1024);
6142 }
6143}
Bram Moolenaar071d4272004-06-13 20:20:40 +00006144
Bram Moolenaar071d4272004-06-13 20:20:40 +00006145#ifdef FEAT_MBYTE
6146/*
6147 * Same code as below, but with wide functions and no comments.
6148 * Return 0 for success, non-zero for failure.
6149 */
6150 int
6151mch_wrename(WCHAR *wold, WCHAR *wnew)
6152{
6153 WCHAR *p;
6154 int i;
6155 WCHAR szTempFile[_MAX_PATH + 1];
6156 WCHAR szNewPath[_MAX_PATH + 1];
6157 HANDLE hf;
6158
6159 if (!mch_windows95())
6160 {
6161 p = wold;
6162 for (i = 0; wold[i] != NUL; ++i)
6163 if ((wold[i] == '/' || wold[i] == '\\' || wold[i] == ':')
6164 && wold[i + 1] != 0)
6165 p = wold + i + 1;
6166 if ((int)(wold + i - p) < 8 || p[6] != '~')
6167 return (MoveFileW(wold, wnew) == 0);
6168 }
6169
6170 if (GetFullPathNameW(wnew, _MAX_PATH, szNewPath, &p) == 0 || p == NULL)
6171 return -1;
6172 *p = NUL;
6173
6174 if (GetTempFileNameW(szNewPath, L"VIM", 0, szTempFile) == 0)
6175 return -2;
6176
6177 if (!DeleteFileW(szTempFile))
6178 return -3;
6179
6180 if (!MoveFileW(wold, szTempFile))
6181 return -4;
6182
6183 if ((hf = CreateFileW(wold, GENERIC_WRITE, 0, NULL, CREATE_NEW,
6184 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
6185 return -5;
6186 if (!CloseHandle(hf))
6187 return -6;
6188
6189 if (!MoveFileW(szTempFile, wnew))
6190 {
6191 (void)MoveFileW(szTempFile, wold);
6192 return -7;
6193 }
6194
6195 DeleteFileW(szTempFile);
6196
6197 if (!DeleteFileW(wold))
6198 return -8;
6199
6200 return 0;
6201}
6202#endif
6203
6204
6205/*
6206 * mch_rename() works around a bug in rename (aka MoveFile) in
6207 * Windows 95: rename("foo.bar", "foo.bar~") will generate a
6208 * file whose short file name is "FOO.BAR" (its long file name will
6209 * be correct: "foo.bar~"). Because a file can be accessed by
6210 * either its SFN or its LFN, "foo.bar" has effectively been
6211 * renamed to "foo.bar", which is not at all what was wanted. This
6212 * seems to happen only when renaming files with three-character
6213 * extensions by appending a suffix that does not include ".".
6214 * Windows NT gets it right, however, with an SFN of "FOO~1.BAR".
6215 *
6216 * There is another problem, which isn't really a bug but isn't right either:
6217 * When renaming "abcdef~1.txt" to "abcdef~1.txt~", the short name can be
6218 * "abcdef~1.txt" again. This has been reported on Windows NT 4.0 with
6219 * service pack 6. Doesn't seem to happen on Windows 98.
6220 *
6221 * Like rename(), returns 0 upon success, non-zero upon failure.
6222 * Should probably set errno appropriately when errors occur.
6223 */
6224 int
6225mch_rename(
6226 const char *pszOldFile,
6227 const char *pszNewFile)
6228{
6229 char szTempFile[_MAX_PATH+1];
6230 char szNewPath[_MAX_PATH+1];
6231 char *pszFilePart;
6232 HANDLE hf;
6233#ifdef FEAT_MBYTE
6234 WCHAR *wold = NULL;
6235 WCHAR *wnew = NULL;
6236 int retval = -1;
6237
6238 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
6239 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006240 wold = enc_to_utf16((char_u *)pszOldFile, NULL);
6241 wnew = enc_to_utf16((char_u *)pszNewFile, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006242 if (wold != NULL && wnew != NULL)
6243 retval = mch_wrename(wold, wnew);
6244 vim_free(wold);
6245 vim_free(wnew);
6246 if (retval == 0 || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
6247 return retval;
6248 /* Retry with non-wide function (for Windows 98). */
6249 }
6250#endif
6251
6252 /*
6253 * No need to play tricks if not running Windows 95, unless the file name
6254 * contains a "~" as the seventh character.
6255 */
6256 if (!mch_windows95())
6257 {
6258 pszFilePart = (char *)gettail((char_u *)pszOldFile);
6259 if (STRLEN(pszFilePart) < 8 || pszFilePart[6] != '~')
6260 return rename(pszOldFile, pszNewFile);
6261 }
6262
6263 /* Get base path of new file name. Undocumented feature: If pszNewFile is
6264 * a directory, no error is returned and pszFilePart will be NULL. */
6265 if (GetFullPathName(pszNewFile, _MAX_PATH, szNewPath, &pszFilePart) == 0
6266 || pszFilePart == NULL)
6267 return -1;
6268 *pszFilePart = NUL;
6269
6270 /* Get (and create) a unique temporary file name in directory of new file */
6271 if (GetTempFileName(szNewPath, "VIM", 0, szTempFile) == 0)
6272 return -2;
6273
6274 /* blow the temp file away */
6275 if (!DeleteFile(szTempFile))
6276 return -3;
6277
6278 /* rename old file to the temp file */
6279 if (!MoveFile(pszOldFile, szTempFile))
6280 return -4;
6281
6282 /* now create an empty file called pszOldFile; this prevents the operating
6283 * system using pszOldFile as an alias (SFN) if we're renaming within the
6284 * same directory. For example, we're editing a file called
6285 * filename.asc.txt by its SFN, filena~1.txt. If we rename filena~1.txt
6286 * to filena~1.txt~ (i.e., we're making a backup while writing it), the
6287 * SFN for filena~1.txt~ will be filena~1.txt, by default, which will
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006288 * cause all sorts of problems later in buf_write(). So, we create an
6289 * empty file called filena~1.txt and the system will have to find some
6290 * other SFN for filena~1.txt~, such as filena~2.txt
Bram Moolenaar071d4272004-06-13 20:20:40 +00006291 */
6292 if ((hf = CreateFile(pszOldFile, GENERIC_WRITE, 0, NULL, CREATE_NEW,
6293 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
6294 return -5;
6295 if (!CloseHandle(hf))
6296 return -6;
6297
6298 /* rename the temp file to the new file */
6299 if (!MoveFile(szTempFile, pszNewFile))
6300 {
6301 /* Renaming failed. Rename the file back to its old name, so that it
6302 * looks like nothing happened. */
6303 (void)MoveFile(szTempFile, pszOldFile);
6304
6305 return -7;
6306 }
6307
6308 /* Seems to be left around on Novell filesystems */
6309 DeleteFile(szTempFile);
6310
6311 /* finally, remove the empty old file */
6312 if (!DeleteFile(pszOldFile))
6313 return -8;
6314
6315 return 0; /* success */
6316}
6317
6318/*
6319 * Get the default shell for the current hardware platform
6320 */
6321 char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006322default_shell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006323{
6324 char* psz = NULL;
6325
6326 PlatformId();
6327
6328 if (g_PlatformId == VER_PLATFORM_WIN32_NT) /* Windows NT */
6329 psz = "cmd.exe";
6330 else if (g_PlatformId == VER_PLATFORM_WIN32_WINDOWS) /* Windows 95 */
6331 psz = "command.com";
6332
6333 return psz;
6334}
6335
6336/*
6337 * mch_access() extends access() to do more detailed check on network drives.
6338 * Returns 0 if file "n" has access rights according to "p", -1 otherwise.
6339 */
6340 int
6341mch_access(char *n, int p)
6342{
6343 HANDLE hFile;
6344 DWORD am;
6345 int retval = -1; /* default: fail */
6346#ifdef FEAT_MBYTE
6347 WCHAR *wn = NULL;
6348
6349 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006350 wn = enc_to_utf16((char_u *)n, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006351#endif
6352
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006353 if (mch_isdir((char_u *)n))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006354 {
6355 char TempName[_MAX_PATH + 16] = "";
6356#ifdef FEAT_MBYTE
6357 WCHAR TempNameW[_MAX_PATH + 16] = L"";
6358#endif
6359
6360 if (p & R_OK)
6361 {
6362 /* Read check is performed by seeing if we can do a find file on
6363 * the directory for any file. */
6364#ifdef FEAT_MBYTE
6365 if (wn != NULL)
6366 {
6367 int i;
6368 WIN32_FIND_DATAW d;
6369
6370 for (i = 0; i < _MAX_PATH && wn[i] != 0; ++i)
6371 TempNameW[i] = wn[i];
6372 if (TempNameW[i - 1] != '\\' && TempNameW[i - 1] != '/')
6373 TempNameW[i++] = '\\';
6374 TempNameW[i++] = '*';
6375 TempNameW[i++] = 0;
6376
6377 hFile = FindFirstFileW(TempNameW, &d);
6378 if (hFile == INVALID_HANDLE_VALUE)
6379 {
6380 if (GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
6381 goto getout;
6382
6383 /* Retry with non-wide function (for Windows 98). */
6384 vim_free(wn);
6385 wn = NULL;
6386 }
6387 else
6388 (void)FindClose(hFile);
6389 }
6390 if (wn == NULL)
6391#endif
6392 {
6393 char *pch;
6394 WIN32_FIND_DATA d;
6395
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006396 vim_strncpy((char_u *)TempName, (char_u *)n, _MAX_PATH);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006397 pch = TempName + STRLEN(TempName) - 1;
6398 if (*pch != '\\' && *pch != '/')
6399 *++pch = '\\';
6400 *++pch = '*';
6401 *++pch = NUL;
6402
6403 hFile = FindFirstFile(TempName, &d);
6404 if (hFile == INVALID_HANDLE_VALUE)
6405 goto getout;
6406 (void)FindClose(hFile);
6407 }
6408 }
6409
6410 if (p & W_OK)
6411 {
6412 /* Trying to create a temporary file in the directory should catch
6413 * directories on read-only network shares. However, in
6414 * directories whose ACL allows writes but denies deletes will end
6415 * up keeping the temporary file :-(. */
6416#ifdef FEAT_MBYTE
6417 if (wn != NULL)
6418 {
6419 if (!GetTempFileNameW(wn, L"VIM", 0, TempNameW))
6420 {
6421 if (GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
6422 goto getout;
6423
6424 /* Retry with non-wide function (for Windows 98). */
6425 vim_free(wn);
6426 wn = NULL;
6427 }
6428 else
6429 DeleteFileW(TempNameW);
6430 }
6431 if (wn == NULL)
6432#endif
6433 {
6434 if (!GetTempFileName(n, "VIM", 0, TempName))
6435 goto getout;
6436 mch_remove((char_u *)TempName);
6437 }
6438 }
6439 }
6440 else
6441 {
6442 /* Trying to open the file for the required access does ACL, read-only
6443 * network share, and file attribute checks. */
6444 am = ((p & W_OK) ? GENERIC_WRITE : 0)
6445 | ((p & R_OK) ? GENERIC_READ : 0);
6446#ifdef FEAT_MBYTE
6447 if (wn != NULL)
6448 {
6449 hFile = CreateFileW(wn, am, 0, NULL, OPEN_EXISTING, 0, NULL);
6450 if (hFile == INVALID_HANDLE_VALUE
6451 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
6452 {
6453 /* Retry with non-wide function (for Windows 98). */
6454 vim_free(wn);
6455 wn = NULL;
6456 }
6457 }
6458 if (wn == NULL)
6459#endif
6460 hFile = CreateFile(n, am, 0, NULL, OPEN_EXISTING, 0, NULL);
6461 if (hFile == INVALID_HANDLE_VALUE)
6462 goto getout;
6463 CloseHandle(hFile);
6464 }
6465
6466 retval = 0; /* success */
6467getout:
6468#ifdef FEAT_MBYTE
6469 vim_free(wn);
6470#endif
6471 return retval;
6472}
6473
6474#if defined(FEAT_MBYTE) || defined(PROTO)
6475/*
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006476 * Version of open() that may use UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006477 */
6478 int
6479mch_open(char *name, int flags, int mode)
6480{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006481 /* _wopen() does not work with Borland C 5.5: creates a read-only file. */
6482# ifndef __BORLANDC__
Bram Moolenaar071d4272004-06-13 20:20:40 +00006483 WCHAR *wn;
6484 int f;
6485
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006486 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006487 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006488 wn = enc_to_utf16((char_u *)name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006489 if (wn != NULL)
6490 {
6491 f = _wopen(wn, flags, mode);
6492 vim_free(wn);
Bram Moolenaarcd981f22014-02-11 17:06:00 +01006493 if (f >= 0 || g_PlatformId == VER_PLATFORM_WIN32_NT)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006494 return f;
6495 /* Retry with non-wide function (for Windows 98). Can't use
6496 * GetLastError() here and it's unclear what errno gets set to if
6497 * the _wopen() fails for missing wide functions. */
6498 }
6499 }
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006500# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006501
Bram Moolenaarf9e6c3b2014-11-05 18:36:03 +01006502 /* open() can open a file which name is longer than _MAX_PATH bytes
6503 * and shorter than _MAX_PATH characters successfully, but sometimes it
6504 * causes unexpected error in another part. We make it an error explicitly
6505 * here. */
6506 if (strlen(name) >= _MAX_PATH)
6507 return -1;
6508
Bram Moolenaar071d4272004-06-13 20:20:40 +00006509 return open(name, flags, mode);
6510}
6511
6512/*
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006513 * Version of fopen() that may use UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006514 */
6515 FILE *
6516mch_fopen(char *name, char *mode)
6517{
6518 WCHAR *wn, *wm;
6519 FILE *f = NULL;
6520
6521 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage
6522# ifdef __BORLANDC__
6523 /* Wide functions of Borland C 5.5 do not work on Windows 98. */
6524 && g_PlatformId == VER_PLATFORM_WIN32_NT
6525# endif
6526 )
6527 {
Bram Moolenaare6a91fd2008-07-24 18:51:11 +00006528# if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0fde2902008-03-16 13:54:13 +00006529 /* Work around an annoying assertion in the Microsoft debug CRT
6530 * when mode's text/binary setting doesn't match _get_fmode(). */
6531 char newMode = mode[strlen(mode) - 1];
6532 int oldMode = 0;
6533
6534 _get_fmode(&oldMode);
6535 if (newMode == 't')
6536 _set_fmode(_O_TEXT);
6537 else if (newMode == 'b')
6538 _set_fmode(_O_BINARY);
6539# endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006540 wn = enc_to_utf16((char_u *)name, NULL);
6541 wm = enc_to_utf16((char_u *)mode, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006542 if (wn != NULL && wm != NULL)
6543 f = _wfopen(wn, wm);
6544 vim_free(wn);
6545 vim_free(wm);
Bram Moolenaar0fde2902008-03-16 13:54:13 +00006546
Bram Moolenaare6a91fd2008-07-24 18:51:11 +00006547# if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0fde2902008-03-16 13:54:13 +00006548 _set_fmode(oldMode);
6549# endif
6550
Bram Moolenaarcd981f22014-02-11 17:06:00 +01006551 if (f != NULL || g_PlatformId == VER_PLATFORM_WIN32_NT)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006552 return f;
6553 /* Retry with non-wide function (for Windows 98). Can't use
6554 * GetLastError() here and it's unclear what errno gets set to if
6555 * the _wfopen() fails for missing wide functions. */
6556 }
6557
Bram Moolenaarf9e6c3b2014-11-05 18:36:03 +01006558 /* fopen() can open a file which name is longer than _MAX_PATH bytes
6559 * and shorter than _MAX_PATH characters successfully, but sometimes it
6560 * causes unexpected error in another part. We make it an error explicitly
6561 * here. */
6562 if (strlen(name) >= _MAX_PATH)
6563 return NULL;
6564
Bram Moolenaar071d4272004-06-13 20:20:40 +00006565 return fopen(name, mode);
6566}
6567#endif
6568
6569#ifdef FEAT_MBYTE
6570/*
6571 * SUB STREAM (aka info stream) handling:
6572 *
6573 * NTFS can have sub streams for each file. Normal contents of file is
6574 * stored in the main stream, and extra contents (author information and
6575 * title and so on) can be stored in sub stream. After Windows 2000, user
6576 * can access and store those informations in sub streams via explorer's
6577 * property menuitem in right click menu. Those informations in sub streams
6578 * were lost when copying only the main stream. So we have to copy sub
6579 * streams.
6580 *
6581 * Incomplete explanation:
6582 * http://msdn.microsoft.com/library/en-us/dnw2k/html/ntfs5.asp
6583 * More useful info and an example:
6584 * http://www.sysinternals.com/ntw2k/source/misc.shtml#streams
6585 */
6586
6587/*
6588 * Copy info stream data "substream". Read from the file with BackupRead(sh)
6589 * and write to stream "substream" of file "to".
6590 * Errors are ignored.
6591 */
6592 static void
6593copy_substream(HANDLE sh, void *context, WCHAR *to, WCHAR *substream, long len)
6594{
6595 HANDLE hTo;
6596 WCHAR *to_name;
6597
6598 to_name = malloc((wcslen(to) + wcslen(substream) + 1) * sizeof(WCHAR));
6599 wcscpy(to_name, to);
6600 wcscat(to_name, substream);
6601
6602 hTo = CreateFileW(to_name, GENERIC_WRITE, 0, NULL, OPEN_ALWAYS,
6603 FILE_ATTRIBUTE_NORMAL, NULL);
6604 if (hTo != INVALID_HANDLE_VALUE)
6605 {
6606 long done;
6607 DWORD todo;
6608 DWORD readcnt, written;
6609 char buf[4096];
6610
6611 /* Copy block of bytes at a time. Abort when something goes wrong. */
6612 for (done = 0; done < len; done += written)
6613 {
6614 /* (size_t) cast for Borland C 5.5 */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006615 todo = (DWORD)((size_t)(len - done) > sizeof(buf) ? sizeof(buf)
6616 : (size_t)(len - done));
Bram Moolenaar071d4272004-06-13 20:20:40 +00006617 if (!BackupRead(sh, (LPBYTE)buf, todo, &readcnt,
6618 FALSE, FALSE, context)
6619 || readcnt != todo
6620 || !WriteFile(hTo, buf, todo, &written, NULL)
6621 || written != todo)
6622 break;
6623 }
6624 CloseHandle(hTo);
6625 }
6626
6627 free(to_name);
6628}
6629
6630/*
6631 * Copy info streams from file "from" to file "to".
6632 */
6633 static void
6634copy_infostreams(char_u *from, char_u *to)
6635{
6636 WCHAR *fromw;
6637 WCHAR *tow;
6638 HANDLE sh;
6639 WIN32_STREAM_ID sid;
6640 int headersize;
6641 WCHAR streamname[_MAX_PATH];
6642 DWORD readcount;
6643 void *context = NULL;
6644 DWORD lo, hi;
6645 int len;
6646
6647 /* Convert the file names to wide characters. */
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006648 fromw = enc_to_utf16(from, NULL);
6649 tow = enc_to_utf16(to, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006650 if (fromw != NULL && tow != NULL)
6651 {
6652 /* Open the file for reading. */
6653 sh = CreateFileW(fromw, GENERIC_READ, FILE_SHARE_READ, NULL,
6654 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
6655 if (sh != INVALID_HANDLE_VALUE)
6656 {
6657 /* Use BackupRead() to find the info streams. Repeat until we
6658 * have done them all.*/
6659 for (;;)
6660 {
6661 /* Get the header to find the length of the stream name. If
6662 * the "readcount" is zero we have done all info streams. */
6663 ZeroMemory(&sid, sizeof(WIN32_STREAM_ID));
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006664 headersize = (int)((char *)&sid.cStreamName - (char *)&sid.dwStreamId);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006665 if (!BackupRead(sh, (LPBYTE)&sid, headersize,
6666 &readcount, FALSE, FALSE, &context)
6667 || readcount == 0)
6668 break;
6669
6670 /* We only deal with streams that have a name. The normal
6671 * file data appears to be without a name, even though docs
6672 * suggest it is called "::$DATA". */
6673 if (sid.dwStreamNameSize > 0)
6674 {
6675 /* Read the stream name. */
6676 if (!BackupRead(sh, (LPBYTE)streamname,
6677 sid.dwStreamNameSize,
6678 &readcount, FALSE, FALSE, &context))
6679 break;
6680
6681 /* Copy an info stream with a name ":anything:$DATA".
6682 * Skip "::$DATA", it has no stream name (examples suggest
6683 * it might be used for the normal file contents).
6684 * Note that BackupRead() counts bytes, but the name is in
6685 * wide characters. */
6686 len = readcount / sizeof(WCHAR);
6687 streamname[len] = 0;
6688 if (len > 7 && wcsicmp(streamname + len - 6,
6689 L":$DATA") == 0)
6690 {
6691 streamname[len - 6] = 0;
6692 copy_substream(sh, &context, tow, streamname,
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00006693 (long)sid.Size.u.LowPart);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006694 }
6695 }
6696
6697 /* Advance to the next stream. We might try seeking too far,
6698 * but BackupSeek() doesn't skip over stream borders, thus
6699 * that's OK. */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00006700 (void)BackupSeek(sh, sid.Size.u.LowPart, sid.Size.u.HighPart,
Bram Moolenaar071d4272004-06-13 20:20:40 +00006701 &lo, &hi, &context);
6702 }
6703
6704 /* Clear the context. */
6705 (void)BackupRead(sh, NULL, 0, &readcount, TRUE, FALSE, &context);
6706
6707 CloseHandle(sh);
6708 }
6709 }
6710 vim_free(fromw);
6711 vim_free(tow);
6712}
6713#endif
6714
6715/*
6716 * Copy file attributes from file "from" to file "to".
6717 * For Windows NT and later we copy info streams.
6718 * Always returns zero, errors are ignored.
6719 */
6720 int
6721mch_copy_file_attribute(char_u *from, char_u *to)
6722{
6723#ifdef FEAT_MBYTE
6724 /* File streams only work on Windows NT and later. */
6725 PlatformId();
6726 if (g_PlatformId == VER_PLATFORM_WIN32_NT)
6727 copy_infostreams(from, to);
6728#endif
6729 return 0;
6730}
6731
6732#if defined(MYRESETSTKOFLW) || defined(PROTO)
6733/*
6734 * Recreate a destroyed stack guard page in win32.
6735 * Written by Benjamin Peterson.
6736 */
6737
6738/* These magic numbers are from the MS header files */
6739#define MIN_STACK_WIN9X 17
6740#define MIN_STACK_WINNT 2
6741
6742/*
6743 * This function does the same thing as _resetstkoflw(), which is only
6744 * available in DevStudio .net and later.
6745 * Returns 0 for failure, 1 for success.
6746 */
6747 int
6748myresetstkoflw(void)
6749{
6750 BYTE *pStackPtr;
6751 BYTE *pGuardPage;
6752 BYTE *pStackBase;
6753 BYTE *pLowestPossiblePage;
6754 MEMORY_BASIC_INFORMATION mbi;
6755 SYSTEM_INFO si;
6756 DWORD nPageSize;
6757 DWORD dummy;
6758
6759 /* This code will not work on win32s. */
6760 PlatformId();
6761 if (g_PlatformId == VER_PLATFORM_WIN32s)
6762 return 0;
6763
6764 /* We need to know the system page size. */
6765 GetSystemInfo(&si);
6766 nPageSize = si.dwPageSize;
6767
6768 /* ...and the current stack pointer */
6769 pStackPtr = (BYTE*)_alloca(1);
6770
6771 /* ...and the base of the stack. */
6772 if (VirtualQuery(pStackPtr, &mbi, sizeof mbi) == 0)
6773 return 0;
6774 pStackBase = (BYTE*)mbi.AllocationBase;
6775
6776 /* ...and the page thats min_stack_req pages away from stack base; this is
6777 * the lowest page we could use. */
6778 pLowestPossiblePage = pStackBase + ((g_PlatformId == VER_PLATFORM_WIN32_NT)
6779 ? MIN_STACK_WINNT : MIN_STACK_WIN9X) * nPageSize;
6780
6781 /* On Win95, we want the next page down from the end of the stack. */
6782 if (g_PlatformId == VER_PLATFORM_WIN32_WINDOWS)
6783 {
6784 /* Find the page that's only 1 page down from the page that the stack
6785 * ptr is in. */
6786 pGuardPage = (BYTE*)((DWORD)nPageSize * (((DWORD)pStackPtr
6787 / (DWORD)nPageSize) - 1));
6788 if (pGuardPage < pLowestPossiblePage)
6789 return 0;
6790
6791 /* Apply the noaccess attribute to the page -- there's no guard
6792 * attribute in win95-type OSes. */
6793 if (!VirtualProtect(pGuardPage, nPageSize, PAGE_NOACCESS, &dummy))
6794 return 0;
6795 }
6796 else
6797 {
6798 /* On NT, however, we want the first committed page in the stack Start
6799 * at the stack base and move forward through memory until we find a
6800 * committed block. */
6801 BYTE *pBlock = pStackBase;
6802
Bram Moolenaara466c992005-07-09 21:03:22 +00006803 for (;;)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006804 {
6805 if (VirtualQuery(pBlock, &mbi, sizeof mbi) == 0)
6806 return 0;
6807
6808 pBlock += mbi.RegionSize;
6809
6810 if (mbi.State & MEM_COMMIT)
6811 break;
6812 }
6813
6814 /* mbi now describes the first committed block in the stack. */
6815 if (mbi.Protect & PAGE_GUARD)
6816 return 1;
6817
6818 /* decide where the guard page should start */
6819 if ((long_u)(mbi.BaseAddress) < (long_u)pLowestPossiblePage)
6820 pGuardPage = pLowestPossiblePage;
6821 else
6822 pGuardPage = (BYTE*)mbi.BaseAddress;
6823
6824 /* allocate the guard page */
6825 if (!VirtualAlloc(pGuardPage, nPageSize, MEM_COMMIT, PAGE_READWRITE))
6826 return 0;
6827
6828 /* apply the guard attribute to the page */
6829 if (!VirtualProtect(pGuardPage, nPageSize, PAGE_READWRITE | PAGE_GUARD,
6830 &dummy))
6831 return 0;
6832 }
6833
6834 return 1;
6835}
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006836#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006837
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006838
6839#if defined(FEAT_MBYTE) || defined(PROTO)
6840/*
6841 * The command line arguments in UCS2
6842 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00006843static int nArgsW = 0;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006844static LPWSTR *ArglistW = NULL;
6845static int global_argc = 0;
6846static char **global_argv;
6847
6848static int used_file_argc = 0; /* last argument in global_argv[] used
6849 for the argument list. */
6850static int *used_file_indexes = NULL; /* indexes in global_argv[] for
6851 command line arguments added to
6852 the argument list */
6853static int used_file_count = 0; /* nr of entries in used_file_indexes */
6854static int used_file_literal = FALSE; /* take file names literally */
6855static int used_file_full_path = FALSE; /* file name was full path */
Bram Moolenaar910f66f2006-04-05 20:41:53 +00006856static int used_file_diff_mode = FALSE; /* file name was with diff mode */
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006857static int used_alist_count = 0;
6858
6859
6860/*
6861 * Get the command line arguments. Unicode version.
6862 * Returns argc. Zero when something fails.
6863 */
6864 int
6865get_cmd_argsW(char ***argvp)
6866{
6867 char **argv = NULL;
6868 int argc = 0;
6869 int i;
6870
Bram Moolenaar14993322014-09-09 12:25:33 +02006871 free_cmd_argsW();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006872 ArglistW = CommandLineToArgvW(GetCommandLineW(), &nArgsW);
6873 if (ArglistW != NULL)
6874 {
6875 argv = malloc((nArgsW + 1) * sizeof(char *));
6876 if (argv != NULL)
6877 {
6878 argc = nArgsW;
6879 argv[argc] = NULL;
6880 for (i = 0; i < argc; ++i)
6881 {
6882 int len;
6883
6884 /* Convert each Unicode argument to the current codepage. */
6885 WideCharToMultiByte_alloc(GetACP(), 0,
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006886 ArglistW[i], (int)wcslen(ArglistW[i]) + 1,
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006887 (LPSTR *)&argv[i], &len, 0, 0);
6888 if (argv[i] == NULL)
6889 {
6890 /* Out of memory, clear everything. */
6891 while (i > 0)
6892 free(argv[--i]);
6893 free(argv);
Bram Moolenaar73c61632013-12-07 14:48:10 +01006894 argv = NULL;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006895 argc = 0;
6896 }
6897 }
6898 }
6899 }
6900
6901 global_argc = argc;
6902 global_argv = argv;
6903 if (argc > 0)
Bram Moolenaar14993322014-09-09 12:25:33 +02006904 {
6905 if (used_file_indexes != NULL)
6906 free(used_file_indexes);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006907 used_file_indexes = malloc(argc * sizeof(int));
Bram Moolenaar14993322014-09-09 12:25:33 +02006908 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006909
6910 if (argvp != NULL)
6911 *argvp = argv;
6912 return argc;
6913}
6914
6915 void
6916free_cmd_argsW(void)
6917{
6918 if (ArglistW != NULL)
6919 {
6920 GlobalFree(ArglistW);
6921 ArglistW = NULL;
6922 }
6923}
6924
6925/*
6926 * Remember "name" is an argument that was added to the argument list.
6927 * This avoids that we have to re-parse the argument list when fix_arg_enc()
6928 * is called.
6929 */
6930 void
Bram Moolenaar910f66f2006-04-05 20:41:53 +00006931used_file_arg(char *name, int literal, int full_path, int diff_mode)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006932{
6933 int i;
6934
6935 if (used_file_indexes == NULL)
6936 return;
6937 for (i = used_file_argc + 1; i < global_argc; ++i)
6938 if (STRCMP(global_argv[i], name) == 0)
6939 {
6940 used_file_argc = i;
6941 used_file_indexes[used_file_count++] = i;
6942 break;
6943 }
6944 used_file_literal = literal;
6945 used_file_full_path = full_path;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00006946 used_file_diff_mode = diff_mode;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006947}
6948
6949/*
6950 * Remember the length of the argument list as it was. If it changes then we
6951 * leave it alone when 'encoding' is set.
6952 */
6953 void
6954set_alist_count(void)
6955{
6956 used_alist_count = GARGCOUNT;
6957}
6958
6959/*
6960 * Fix the encoding of the command line arguments. Invoked when 'encoding'
6961 * has been changed while starting up. Use the UCS-2 command line arguments
6962 * and convert them to 'encoding'.
6963 */
6964 void
6965fix_arg_enc(void)
6966{
6967 int i;
6968 int idx;
6969 char_u *str;
Bram Moolenaar86b68352004-12-27 21:59:20 +00006970 int *fnum_list;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006971
6972 /* Safety checks:
6973 * - if argument count differs between the wide and non-wide argument
6974 * list, something must be wrong.
6975 * - the file name arguments must have been located.
6976 * - the length of the argument list wasn't changed by the user.
6977 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00006978 if (global_argc != nArgsW
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006979 || ArglistW == NULL
6980 || used_file_indexes == NULL
6981 || used_file_count == 0
6982 || used_alist_count != GARGCOUNT)
6983 return;
6984
Bram Moolenaar86b68352004-12-27 21:59:20 +00006985 /* Remember the buffer numbers for the arguments. */
6986 fnum_list = (int *)alloc((int)sizeof(int) * GARGCOUNT);
6987 if (fnum_list == NULL)
6988 return; /* out of memory */
6989 for (i = 0; i < GARGCOUNT; ++i)
6990 fnum_list[i] = GARGLIST[i].ae_fnum;
6991
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006992 /* Clear the argument list. Make room for the new arguments. */
6993 alist_clear(&global_alist);
6994 if (ga_grow(&global_alist.al_ga, used_file_count) == FAIL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00006995 return; /* out of memory */
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006996
6997 for (i = 0; i < used_file_count; ++i)
6998 {
6999 idx = used_file_indexes[i];
Bram Moolenaar36f692d2008-11-20 16:10:17 +00007000 str = utf16_to_enc(ArglistW[idx], NULL);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007001 if (str != NULL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00007002 {
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007003#ifdef FEAT_DIFF
7004 /* When using diff mode may need to concatenate file name to
7005 * directory name. Just like it's done in main(). */
7006 if (used_file_diff_mode && mch_isdir(str) && GARGCOUNT > 0
7007 && !mch_isdir(alist_name(&GARGLIST[0])))
7008 {
7009 char_u *r;
7010
7011 r = concat_fnames(str, gettail(alist_name(&GARGLIST[0])), TRUE);
7012 if (r != NULL)
7013 {
7014 vim_free(str);
7015 str = r;
7016 }
7017 }
7018#endif
Bram Moolenaar86b68352004-12-27 21:59:20 +00007019 /* Re-use the old buffer by renaming it. When not using literal
7020 * names it's done by alist_expand() below. */
7021 if (used_file_literal)
7022 buf_set_name(fnum_list[i], str);
7023
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007024 alist_add(&global_alist, str, used_file_literal ? 2 : 0);
Bram Moolenaar86b68352004-12-27 21:59:20 +00007025 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007026 }
7027
7028 if (!used_file_literal)
7029 {
7030 /* Now expand wildcards in the arguments. */
7031 /* Temporarily add '(' and ')' to 'isfname'. These are valid
7032 * filename characters but are excluded from 'isfname' to make
7033 * "gf" work on a file name in parenthesis (e.g.: see vim.h). */
7034 do_cmdline_cmd((char_u *)":let SaVe_ISF = &isf|set isf+=(,)");
Bram Moolenaar86b68352004-12-27 21:59:20 +00007035 alist_expand(fnum_list, used_alist_count);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007036 do_cmdline_cmd((char_u *)":let &isf = SaVe_ISF|unlet SaVe_ISF");
7037 }
7038
7039 /* If wildcard expansion failed, we are editing the first file of the
7040 * arglist and there is no file name: Edit the first argument now. */
7041 if (curwin->w_arg_idx == 0 && curbuf->b_fname == NULL)
7042 {
7043 do_cmdline_cmd((char_u *)":rewind");
7044 if (GARGCOUNT == 1 && used_file_full_path)
7045 (void)vim_chdirfile(alist_name(&GARGLIST[0]));
7046 }
Bram Moolenaar86b68352004-12-27 21:59:20 +00007047
7048 set_alist_count();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007049}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007050#endif