blob: e93e6d0181aa91a592730fe77e2e2e82822407fb [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
Bram Moolenaar9186a272016-02-23 19:34:01 +01001495#ifdef FEAT_CHANNEL
1496 /* Check channel while waiting input. */
1497 if (dwWaitTime > 100)
1498 dwWaitTime = 100;
1499#endif
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001500#ifdef FEAT_MZSCHEME
1501 if (mzthreads_allowed() && p_mzq > 0
1502 && (msec < 0 || (long)dwWaitTime > p_mzq))
1503 dwWaitTime = p_mzq; /* don't wait longer than 'mzquantum' */
1504#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001505#ifdef FEAT_CLIENTSERVER
1506 /* Wait for either an event on the console input or a message in
1507 * the client-server window. */
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +02001508 if (msg_wait_for_multiple_objects(1, &g_hConIn, FALSE,
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001509 dwWaitTime, QS_SENDMESSAGE) != WAIT_OBJECT_0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001510#else
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +02001511 if (wait_for_single_object(g_hConIn, dwWaitTime) != WAIT_OBJECT_0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001512#endif
1513 continue;
1514 }
1515
1516 cRecords = 0;
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001517 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001518
1519#ifdef FEAT_MBYTE_IME
1520 if (State & CMDLINE && msg_row == Rows - 1)
1521 {
1522 CONSOLE_SCREEN_BUFFER_INFO csbi;
1523
1524 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
1525 {
1526 if (csbi.dwCursorPosition.Y != msg_row)
1527 {
1528 /* The screen is now messed up, must redraw the
1529 * command line and later all the windows. */
1530 redraw_all_later(CLEAR);
1531 cmdline_row -= (msg_row - csbi.dwCursorPosition.Y);
1532 redrawcmd();
1533 }
1534 }
1535 }
1536#endif
1537
1538 if (cRecords > 0)
1539 {
1540 if (ir.EventType == KEY_EVENT && ir.Event.KeyEvent.bKeyDown)
1541 {
1542#ifdef FEAT_MBYTE_IME
1543 /* Windows IME sends two '\n's with only one 'ENTER'. First:
1544 * wVirtualKeyCode == 13. second: wVirtualKeyCode == 0 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001545 if (ir.Event.KeyEvent.UChar == 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00001546 && ir.Event.KeyEvent.wVirtualKeyCode == 13)
1547 {
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001548 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001549 continue;
1550 }
1551#endif
1552 if (decode_key_event(&ir.Event.KeyEvent, &ch, &ch2,
1553 NULL, FALSE))
1554 return TRUE;
1555 }
1556
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001557 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001558
1559 if (ir.EventType == FOCUS_EVENT)
1560 handle_focus_event(ir);
1561 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
1562 shell_resized();
1563#ifdef FEAT_MOUSE
1564 else if (ir.EventType == MOUSE_EVENT
1565 && decode_mouse_event(&ir.Event.MouseEvent))
1566 return TRUE;
1567#endif
1568 }
1569 else if (msec == 0)
1570 break;
1571 }
1572
1573#ifdef FEAT_CLIENTSERVER
1574 /* Something might have been received while we were waiting. */
1575 if (input_available())
1576 return TRUE;
1577#endif
Bram Moolenaarf12d9832016-01-29 21:11:25 +01001578
Bram Moolenaar071d4272004-06-13 20:20:40 +00001579 return FALSE;
1580}
1581
1582#ifndef FEAT_GUI_MSWIN
1583/*
1584 * return non-zero if a character is available
1585 */
1586 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001587mch_char_avail(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001588{
1589 return WaitForChar(0L);
1590}
1591#endif
1592
1593/*
1594 * Create the console input. Used when reading stdin doesn't work.
1595 */
1596 static void
1597create_conin(void)
1598{
1599 g_hConIn = CreateFile("CONIN$", GENERIC_READ|GENERIC_WRITE,
1600 FILE_SHARE_READ|FILE_SHARE_WRITE,
1601 (LPSECURITY_ATTRIBUTES) NULL,
Bram Moolenaareb3593b2006-04-22 22:33:57 +00001602 OPEN_EXISTING, 0, (HANDLE)NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001603 did_create_conin = TRUE;
1604}
1605
1606/*
1607 * Get a keystroke or a mouse event
1608 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001609 static WCHAR
1610tgetch(int *pmodifiers, WCHAR *pch2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001611{
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001612 WCHAR ch;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001613
1614 for (;;)
1615 {
1616 INPUT_RECORD ir;
1617 DWORD cRecords = 0;
1618
1619#ifdef FEAT_CLIENTSERVER
1620 (void)WaitForChar(-1L);
1621 if (input_available())
1622 return 0;
1623# ifdef FEAT_MOUSE
1624 if (g_nMouseClick != -1)
1625 return 0;
1626# endif
1627#endif
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001628 if (read_console_input(g_hConIn, &ir, 1, &cRecords) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001629 {
1630 if (did_create_conin)
1631 read_error_exit();
1632 create_conin();
1633 continue;
1634 }
1635
1636 if (ir.EventType == KEY_EVENT)
1637 {
1638 if (decode_key_event(&ir.Event.KeyEvent, &ch, pch2,
1639 pmodifiers, TRUE))
1640 return ch;
1641 }
1642 else if (ir.EventType == FOCUS_EVENT)
1643 handle_focus_event(ir);
1644 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
1645 shell_resized();
1646#ifdef FEAT_MOUSE
1647 else if (ir.EventType == MOUSE_EVENT)
1648 {
1649 if (decode_mouse_event(&ir.Event.MouseEvent))
1650 return 0;
1651 }
1652#endif
1653 }
1654}
1655#endif /* !FEAT_GUI_W32 */
1656
1657
1658/*
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02001659 * mch_inchar(): low-level input function.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001660 * Get one or more characters from the keyboard or the mouse.
1661 * If time == 0, do not wait for characters.
1662 * If time == n, wait a short time for characters.
1663 * If time == -1, wait forever for characters.
1664 * Returns the number of characters read into buf.
1665 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00001666/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00001667 int
1668mch_inchar(
1669 char_u *buf,
1670 int maxlen,
1671 long time,
1672 int tb_change_cnt)
1673{
1674#ifndef FEAT_GUI_W32 /* this isn't used for the GUI */
1675
1676 int len;
1677 int c;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001678#define TYPEAHEADLEN 20
1679 static char_u typeahead[TYPEAHEADLEN]; /* previously typed bytes. */
1680 static int typeaheadlen = 0;
1681
1682 /* First use any typeahead that was kept because "buf" was too small. */
1683 if (typeaheadlen > 0)
1684 goto theend;
1685
1686#ifdef FEAT_SNIFF
1687 if (want_sniff_request)
1688 {
1689 if (sniff_request_waiting)
1690 {
1691 /* return K_SNIFF */
1692 typeahead[typeaheadlen++] = CSI;
1693 typeahead[typeaheadlen++] = (char_u)KS_EXTRA;
1694 typeahead[typeaheadlen++] = (char_u)KE_SNIFF;
1695 sniff_request_waiting = 0;
1696 want_sniff_request = 0;
1697 goto theend;
1698 }
1699 else if (time < 0 || time > 250)
1700 {
1701 /* don't wait too long, a request might be pending */
1702 time = 250;
1703 }
1704 }
1705#endif
1706
1707 if (time >= 0)
1708 {
1709 if (!WaitForChar(time)) /* no character available */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001710 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001711 }
1712 else /* time == -1, wait forever */
1713 {
1714 mch_set_winsize_now(); /* Allow winsize changes from now on */
1715
Bram Moolenaar3918c952005-03-15 22:34:55 +00001716 /*
1717 * If there is no character available within 2 seconds (default)
1718 * write the autoscript file to disk. Or cause the CursorHold event
1719 * to be triggered.
1720 */
1721 if (!WaitForChar(p_ut))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001722 {
1723#ifdef FEAT_AUTOCMD
Bram Moolenaard35f9712005-12-18 22:02:33 +00001724 if (trigger_cursorhold() && maxlen >= 3)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001725 {
Bram Moolenaar3918c952005-03-15 22:34:55 +00001726 buf[0] = K_SPECIAL;
1727 buf[1] = KS_EXTRA;
1728 buf[2] = (int)KE_CURSORHOLD;
1729 return 3;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001730 }
1731#endif
Bram Moolenaar702517d2005-06-27 22:34:07 +00001732 before_blocking();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001733 }
1734 }
1735
1736 /*
1737 * Try to read as many characters as there are, until the buffer is full.
1738 */
1739
1740 /* we will get at least one key. Get more if they are available. */
1741 g_fCBrkPressed = FALSE;
1742
1743#ifdef MCH_WRITE_DUMP
1744 if (fdDump)
1745 fputc('[', fdDump);
1746#endif
1747
1748 /* Keep looping until there is something in the typeahead buffer and more
1749 * to get and still room in the buffer (up to two bytes for a char and
1750 * three bytes for a modifier). */
1751 while ((typeaheadlen == 0 || WaitForChar(0L))
1752 && typeaheadlen + 5 <= TYPEAHEADLEN)
1753 {
1754 if (typebuf_changed(tb_change_cnt))
1755 {
1756 /* "buf" may be invalid now if a client put something in the
1757 * typeahead buffer and "buf" is in the typeahead buffer. */
1758 typeaheadlen = 0;
1759 break;
1760 }
1761#ifdef FEAT_MOUSE
1762 if (g_nMouseClick != -1)
1763 {
1764# ifdef MCH_WRITE_DUMP
1765 if (fdDump)
1766 fprintf(fdDump, "{%02x @ %d, %d}",
1767 g_nMouseClick, g_xMouse, g_yMouse);
1768# endif
1769 typeahead[typeaheadlen++] = ESC + 128;
1770 typeahead[typeaheadlen++] = 'M';
1771 typeahead[typeaheadlen++] = g_nMouseClick;
1772 typeahead[typeaheadlen++] = g_xMouse + '!';
1773 typeahead[typeaheadlen++] = g_yMouse + '!';
1774 g_nMouseClick = -1;
1775 }
1776 else
1777#endif
1778 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001779 WCHAR ch2 = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001780 int modifiers = 0;
1781
1782 c = tgetch(&modifiers, &ch2);
1783
1784 if (typebuf_changed(tb_change_cnt))
1785 {
1786 /* "buf" may be invalid now if a client put something in the
1787 * typeahead buffer and "buf" is in the typeahead buffer. */
1788 typeaheadlen = 0;
1789 break;
1790 }
1791
1792 if (c == Ctrl_C && ctrl_c_interrupts)
1793 {
1794#if defined(FEAT_CLIENTSERVER)
1795 trash_input_buf();
1796#endif
1797 got_int = TRUE;
1798 }
1799
1800#ifdef FEAT_MOUSE
1801 if (g_nMouseClick == -1)
1802#endif
1803 {
1804 int n = 1;
Bram Moolenaar45500912014-07-09 20:51:07 +02001805 int conv = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001806
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001807#ifdef FEAT_MBYTE
1808 if (ch2 == NUL)
1809 {
1810 int i;
1811 char_u *p;
1812 WCHAR ch[2];
1813
1814 ch[0] = c;
1815 if (c >= 0xD800 && c <= 0xDBFF) /* High surrogate */
1816 {
1817 ch[1] = tgetch(&modifiers, &ch2);
1818 n++;
1819 }
1820 p = utf16_to_enc(ch, &n);
1821 if (p != NULL)
1822 {
1823 for (i = 0; i < n; i++)
1824 typeahead[typeaheadlen + i] = p[i];
1825 vim_free(p);
1826 }
1827 }
1828 else
1829#endif
1830 typeahead[typeaheadlen] = c;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001831 if (ch2 != NUL)
1832 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001833 typeahead[typeaheadlen + n] = 3;
1834 typeahead[typeaheadlen + n + 1] = (char_u)ch2;
Bram Moolenaar45500912014-07-09 20:51:07 +02001835 n += 2;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001836 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001837
Bram Moolenaar45500912014-07-09 20:51:07 +02001838 if (conv)
1839 {
1840 char_u *p = typeahead + typeaheadlen;
Bram Moolenaar45500912014-07-09 20:51:07 +02001841
Bram Moolenaar1ec4dd42015-01-20 19:39:35 +01001842 if (*p != K_NUL)
Bram Moolenaar45500912014-07-09 20:51:07 +02001843 {
Bram Moolenaar1ec4dd42015-01-20 19:39:35 +01001844 char_u *e = typeahead + TYPEAHEADLEN;
1845
1846 while (*p && p < e)
Bram Moolenaar45500912014-07-09 20:51:07 +02001847 {
Bram Moolenaar1ec4dd42015-01-20 19:39:35 +01001848 if (*p == K_NUL)
1849 {
1850 ++p;
1851 mch_memmove(p + 1, p, ((size_t)(e - p)) - 1);
1852 *p = 3;
1853 ++n;
1854 }
Bram Moolenaar45500912014-07-09 20:51:07 +02001855 ++p;
Bram Moolenaar45500912014-07-09 20:51:07 +02001856 }
Bram Moolenaar45500912014-07-09 20:51:07 +02001857 }
1858 }
1859
Bram Moolenaar071d4272004-06-13 20:20:40 +00001860 /* Use the ALT key to set the 8th bit of the character
1861 * when it's one byte, the 8th bit isn't set yet and not
1862 * using a double-byte encoding (would become a lead
1863 * byte). */
1864 if ((modifiers & MOD_MASK_ALT)
1865 && n == 1
1866 && (typeahead[typeaheadlen] & 0x80) == 0
1867#ifdef FEAT_MBYTE
1868 && !enc_dbcs
1869#endif
1870 )
1871 {
Bram Moolenaar85a3e5c2007-11-20 16:22:16 +00001872#ifdef FEAT_MBYTE
1873 n = (*mb_char2bytes)(typeahead[typeaheadlen] | 0x80,
1874 typeahead + typeaheadlen);
1875#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00001876 typeahead[typeaheadlen] |= 0x80;
Bram Moolenaar85a3e5c2007-11-20 16:22:16 +00001877#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001878 modifiers &= ~MOD_MASK_ALT;
1879 }
1880
1881 if (modifiers != 0)
1882 {
1883 /* Prepend modifiers to the character. */
1884 mch_memmove(typeahead + typeaheadlen + 3,
1885 typeahead + typeaheadlen, n);
1886 typeahead[typeaheadlen++] = K_SPECIAL;
1887 typeahead[typeaheadlen++] = (char_u)KS_MODIFIER;
1888 typeahead[typeaheadlen++] = modifiers;
1889 }
1890
1891 typeaheadlen += n;
1892
1893#ifdef MCH_WRITE_DUMP
1894 if (fdDump)
1895 fputc(c, fdDump);
1896#endif
1897 }
1898 }
1899 }
1900
1901#ifdef MCH_WRITE_DUMP
1902 if (fdDump)
1903 {
1904 fputs("]\n", fdDump);
1905 fflush(fdDump);
1906 }
1907#endif
1908
Bram Moolenaar071d4272004-06-13 20:20:40 +00001909theend:
1910 /* Move typeahead to "buf", as much as fits. */
1911 len = 0;
1912 while (len < maxlen && typeaheadlen > 0)
1913 {
1914 buf[len++] = typeahead[0];
1915 mch_memmove(typeahead, typeahead + 1, --typeaheadlen);
1916 }
1917 return len;
1918
1919#else /* FEAT_GUI_W32 */
1920 return 0;
1921#endif /* FEAT_GUI_W32 */
1922}
1923
Bram Moolenaar82881492012-11-20 16:53:39 +01001924#ifndef PROTO
1925# ifndef __MINGW32__
1926# include <shellapi.h> /* required for FindExecutable() */
1927# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001928#endif
1929
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001930/*
1931 * Return TRUE if "name" is in $PATH.
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00001932 * TODO: Should somehow check if it's really executable.
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001933 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001934 static int
Bram Moolenaarc7f02552014-04-01 21:00:59 +02001935executable_exists(char *name, char_u **path)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001936{
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001937 char *dum;
1938 char fname[_MAX_PATH];
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02001939 char *curpath, *newpath;
1940 long n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001941
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001942#ifdef FEAT_MBYTE
1943 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001944 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01001945 WCHAR *p = enc_to_utf16((char_u *)name, NULL);
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001946 WCHAR fnamew[_MAX_PATH];
1947 WCHAR *dumw;
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02001948 WCHAR *wcurpath, *wnewpath;
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001949
1950 if (p != NULL)
1951 {
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02001952 wcurpath = _wgetenv(L"PATH");
1953 wnewpath = (WCHAR*)alloc((unsigned)(wcslen(wcurpath) + 3)
1954 * sizeof(WCHAR));
1955 if (wnewpath == NULL)
1956 return FALSE;
1957 wcscpy(wnewpath, L".;");
1958 wcscat(wnewpath, wcurpath);
1959 n = (long)SearchPathW(wnewpath, p, NULL, _MAX_PATH, fnamew, &dumw);
1960 vim_free(wnewpath);
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001961 vim_free(p);
1962 if (n > 0 || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
1963 {
1964 if (n == 0)
1965 return FALSE;
1966 if (GetFileAttributesW(fnamew) & FILE_ATTRIBUTE_DIRECTORY)
1967 return FALSE;
Bram Moolenaarc7f02552014-04-01 21:00:59 +02001968 if (path != NULL)
1969 *path = utf16_to_enc(fnamew, NULL);
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001970 return TRUE;
1971 }
1972 /* Retry with non-wide function (for Windows 98). */
1973 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001974 }
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001975#endif
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02001976
1977 curpath = getenv("PATH");
1978 newpath = (char*)alloc((unsigned)(STRLEN(curpath) + 3));
1979 if (newpath == NULL)
1980 return FALSE;
1981 STRCPY(newpath, ".;");
1982 STRCAT(newpath, curpath);
1983 n = (long)SearchPath(newpath, name, NULL, _MAX_PATH, fname, &dum);
1984 vim_free(newpath);
1985 if (n == 0)
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001986 return FALSE;
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01001987 if (mch_isdir((char_u *)fname))
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001988 return FALSE;
Bram Moolenaarc7f02552014-04-01 21:00:59 +02001989 if (path != NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01001990 *path = vim_strsave((char_u *)fname);
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001991 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001992}
1993
Bram Moolenaard32a99a2010-09-21 17:29:23 +02001994#if ((defined(__MINGW32__) || defined (__CYGWIN32__)) && \
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02001995 __MSVCRT_VERSION__ >= 0x800) || (defined(_MSC_VER) && _MSC_VER >= 1400)
Bram Moolenaard32a99a2010-09-21 17:29:23 +02001996/*
1997 * Bad parameter handler.
1998 *
1999 * Certain MS CRT functions will intentionally crash when passed invalid
2000 * parameters to highlight possible security holes. Setting this function as
2001 * the bad parameter handler will prevent the crash.
2002 *
2003 * In debug builds the parameters contain CRT information that might help track
2004 * down the source of a problem, but in non-debug builds the arguments are all
2005 * NULL/0. Debug builds will also produce assert dialogs from the CRT, it is
2006 * worth allowing these to make debugging of issues easier.
2007 */
2008 static void
2009bad_param_handler(const wchar_t *expression,
2010 const wchar_t *function,
2011 const wchar_t *file,
2012 unsigned int line,
2013 uintptr_t pReserved)
2014{
2015}
2016
2017# define SET_INVALID_PARAM_HANDLER \
2018 ((void)_set_invalid_parameter_handler(bad_param_handler))
2019#else
2020# define SET_INVALID_PARAM_HANDLER
2021#endif
2022
Bram Moolenaar071d4272004-06-13 20:20:40 +00002023#ifdef FEAT_GUI_W32
2024
2025/*
2026 * GUI version of mch_init().
2027 */
2028 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002029mch_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002030{
2031#ifndef __MINGW32__
2032 extern int _fmode;
2033#endif
2034
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002035 /* Silently handle invalid parameters to CRT functions */
2036 SET_INVALID_PARAM_HANDLER;
2037
Bram Moolenaar071d4272004-06-13 20:20:40 +00002038 /* Let critical errors result in a failure, not in a dialog box. Required
2039 * for the timestamp test to work on removed floppies. */
2040 SetErrorMode(SEM_FAILCRITICALERRORS);
2041
2042 _fmode = O_BINARY; /* we do our own CR-LF translation */
2043
2044 /* Specify window size. Is there a place to get the default from? */
2045 Rows = 25;
2046 Columns = 80;
2047
2048 /* Look for 'vimrun' */
2049 if (!gui_is_win32s())
2050 {
2051 char_u vimrun_location[_MAX_PATH + 4];
2052
2053 /* First try in same directory as gvim.exe */
2054 STRCPY(vimrun_location, exe_name);
2055 STRCPY(gettail(vimrun_location), "vimrun.exe");
2056 if (mch_getperm(vimrun_location) >= 0)
2057 {
2058 if (*skiptowhite(vimrun_location) != NUL)
2059 {
2060 /* Enclose path with white space in double quotes. */
2061 mch_memmove(vimrun_location + 1, vimrun_location,
2062 STRLEN(vimrun_location) + 1);
2063 *vimrun_location = '"';
2064 STRCPY(gettail(vimrun_location), "vimrun\" ");
2065 }
2066 else
2067 STRCPY(gettail(vimrun_location), "vimrun ");
2068
2069 vimrun_path = (char *)vim_strsave(vimrun_location);
2070 s_dont_use_vimrun = FALSE;
2071 }
Bram Moolenaarc7f02552014-04-01 21:00:59 +02002072 else if (executable_exists("vimrun.exe", NULL))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002073 s_dont_use_vimrun = FALSE;
2074
2075 /* Don't give the warning for a missing vimrun.exe right now, but only
2076 * when vimrun was supposed to be used. Don't bother people that do
2077 * not need vimrun.exe. */
2078 if (s_dont_use_vimrun)
2079 need_vimrun_warning = TRUE;
2080 }
2081
2082 /*
2083 * If "finstr.exe" doesn't exist, use "grep -n" for 'grepprg'.
2084 * Otherwise the default "findstr /n" is used.
2085 */
Bram Moolenaarc7f02552014-04-01 21:00:59 +02002086 if (!executable_exists("findstr.exe", NULL))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002087 set_option_value((char_u *)"grepprg", 0, (char_u *)"grep -n", 0);
2088
2089#ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01002090 win_clip_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002091#endif
2092}
2093
2094
2095#else /* FEAT_GUI_W32 */
2096
2097#define SRWIDTH(sr) ((sr).Right - (sr).Left + 1)
2098#define SRHEIGHT(sr) ((sr).Bottom - (sr).Top + 1)
2099
2100/*
2101 * ClearConsoleBuffer()
2102 * Description:
2103 * Clears the entire contents of the console screen buffer, using the
2104 * specified attribute.
2105 * Returns:
2106 * TRUE on success
2107 */
2108 static BOOL
2109ClearConsoleBuffer(WORD wAttribute)
2110{
2111 CONSOLE_SCREEN_BUFFER_INFO csbi;
2112 COORD coord;
2113 DWORD NumCells, dummy;
2114
2115 if (!GetConsoleScreenBufferInfo(g_hConOut, &csbi))
2116 return FALSE;
2117
2118 NumCells = csbi.dwSize.X * csbi.dwSize.Y;
2119 coord.X = 0;
2120 coord.Y = 0;
2121 if (!FillConsoleOutputCharacter(g_hConOut, ' ', NumCells,
2122 coord, &dummy))
2123 {
2124 return FALSE;
2125 }
2126 if (!FillConsoleOutputAttribute(g_hConOut, wAttribute, NumCells,
2127 coord, &dummy))
2128 {
2129 return FALSE;
2130 }
2131
2132 return TRUE;
2133}
2134
2135/*
2136 * FitConsoleWindow()
2137 * Description:
2138 * Checks if the console window will fit within given buffer dimensions.
2139 * Also, if requested, will shrink the window to fit.
2140 * Returns:
2141 * TRUE on success
2142 */
2143 static BOOL
2144FitConsoleWindow(
2145 COORD dwBufferSize,
2146 BOOL WantAdjust)
2147{
2148 CONSOLE_SCREEN_BUFFER_INFO csbi;
2149 COORD dwWindowSize;
2150 BOOL NeedAdjust = FALSE;
2151
2152 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
2153 {
2154 /*
2155 * A buffer resize will fail if the current console window does
2156 * not lie completely within that buffer. To avoid this, we might
2157 * have to move and possibly shrink the window.
2158 */
2159 if (csbi.srWindow.Right >= dwBufferSize.X)
2160 {
2161 dwWindowSize.X = SRWIDTH(csbi.srWindow);
2162 if (dwWindowSize.X > dwBufferSize.X)
2163 dwWindowSize.X = dwBufferSize.X;
2164 csbi.srWindow.Right = dwBufferSize.X - 1;
2165 csbi.srWindow.Left = dwBufferSize.X - dwWindowSize.X;
2166 NeedAdjust = TRUE;
2167 }
2168 if (csbi.srWindow.Bottom >= dwBufferSize.Y)
2169 {
2170 dwWindowSize.Y = SRHEIGHT(csbi.srWindow);
2171 if (dwWindowSize.Y > dwBufferSize.Y)
2172 dwWindowSize.Y = dwBufferSize.Y;
2173 csbi.srWindow.Bottom = dwBufferSize.Y - 1;
2174 csbi.srWindow.Top = dwBufferSize.Y - dwWindowSize.Y;
2175 NeedAdjust = TRUE;
2176 }
2177 if (NeedAdjust && WantAdjust)
2178 {
2179 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &csbi.srWindow))
2180 return FALSE;
2181 }
2182 return TRUE;
2183 }
2184
2185 return FALSE;
2186}
2187
2188typedef struct ConsoleBufferStruct
2189{
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002190 BOOL IsValid;
2191 CONSOLE_SCREEN_BUFFER_INFO Info;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002192 PCHAR_INFO Buffer;
2193 COORD BufferSize;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002194} ConsoleBuffer;
2195
2196/*
2197 * SaveConsoleBuffer()
2198 * Description:
2199 * Saves important information about the console buffer, including the
2200 * actual buffer contents. The saved information is suitable for later
2201 * restoration by RestoreConsoleBuffer().
2202 * Returns:
2203 * TRUE if all information was saved; FALSE otherwise
2204 * If FALSE, still sets cb->IsValid if buffer characteristics were saved.
2205 */
2206 static BOOL
2207SaveConsoleBuffer(
2208 ConsoleBuffer *cb)
2209{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002210 DWORD NumCells;
2211 COORD BufferCoord;
2212 SMALL_RECT ReadRegion;
2213 WORD Y, Y_incr;
2214
Bram Moolenaar071d4272004-06-13 20:20:40 +00002215 if (cb == NULL)
2216 return FALSE;
2217
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002218 if (!GetConsoleScreenBufferInfo(g_hConOut, &cb->Info))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002219 {
2220 cb->IsValid = FALSE;
2221 return FALSE;
2222 }
2223 cb->IsValid = TRUE;
2224
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002225 /*
2226 * Allocate a buffer large enough to hold the entire console screen
2227 * buffer. If this ConsoleBuffer structure has already been initialized
2228 * with a buffer of the correct size, then just use that one.
2229 */
2230 if (!cb->IsValid || cb->Buffer == NULL ||
2231 cb->BufferSize.X != cb->Info.dwSize.X ||
2232 cb->BufferSize.Y != cb->Info.dwSize.Y)
2233 {
2234 cb->BufferSize.X = cb->Info.dwSize.X;
2235 cb->BufferSize.Y = cb->Info.dwSize.Y;
2236 NumCells = cb->BufferSize.X * cb->BufferSize.Y;
2237 vim_free(cb->Buffer);
2238 cb->Buffer = (PCHAR_INFO)alloc(NumCells * sizeof(CHAR_INFO));
2239 if (cb->Buffer == NULL)
2240 return FALSE;
2241 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002242
2243 /*
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002244 * We will now copy the console screen buffer into our buffer.
2245 * ReadConsoleOutput() seems to be limited as far as how much you
2246 * can read at a time. Empirically, this number seems to be about
2247 * 12000 cells (rows * columns). Start at position (0, 0) and copy
2248 * in chunks until it is all copied. The chunks will all have the
2249 * same horizontal characteristics, so initialize them now. The
2250 * height of each chunk will be (12000 / width).
Bram Moolenaar071d4272004-06-13 20:20:40 +00002251 */
Bram Moolenaar61594242015-09-01 20:23:37 +02002252 BufferCoord.X = 0;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002253 ReadRegion.Left = 0;
2254 ReadRegion.Right = cb->Info.dwSize.X - 1;
2255 Y_incr = 12000 / cb->Info.dwSize.X;
2256 for (Y = 0; Y < cb->BufferSize.Y; Y += Y_incr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002257 {
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002258 /*
2259 * Read into position (0, Y) in our buffer.
2260 */
2261 BufferCoord.Y = Y;
2262 /*
2263 * Read the region whose top left corner is (0, Y) and whose bottom
2264 * right corner is (width - 1, Y + Y_incr - 1). This should define
2265 * a region of size width by Y_incr. Don't worry if this region is
2266 * too large for the remaining buffer; it will be cropped.
2267 */
2268 ReadRegion.Top = Y;
2269 ReadRegion.Bottom = Y + Y_incr - 1;
2270 if (!ReadConsoleOutput(g_hConOut, /* output handle */
2271 cb->Buffer, /* our buffer */
2272 cb->BufferSize, /* dimensions of our buffer */
2273 BufferCoord, /* offset in our buffer */
2274 &ReadRegion)) /* region to save */
2275 {
2276 vim_free(cb->Buffer);
2277 cb->Buffer = NULL;
2278 return FALSE;
2279 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002280 }
2281
2282 return TRUE;
2283}
2284
2285/*
2286 * RestoreConsoleBuffer()
2287 * Description:
2288 * Restores important information about the console buffer, including the
2289 * actual buffer contents, if desired. The information to restore is in
2290 * the same format used by SaveConsoleBuffer().
2291 * Returns:
2292 * TRUE on success
2293 */
2294 static BOOL
2295RestoreConsoleBuffer(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002296 ConsoleBuffer *cb,
2297 BOOL RestoreScreen)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002298{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002299 COORD BufferCoord;
2300 SMALL_RECT WriteRegion;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002301
2302 if (cb == NULL || !cb->IsValid)
2303 return FALSE;
2304
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002305 /*
2306 * Before restoring the buffer contents, clear the current buffer, and
2307 * restore the cursor position and window information. Doing this now
2308 * prevents old buffer contents from "flashing" onto the screen.
2309 */
2310 if (RestoreScreen)
2311 ClearConsoleBuffer(cb->Info.wAttributes);
2312
2313 FitConsoleWindow(cb->Info.dwSize, TRUE);
2314 if (!SetConsoleScreenBufferSize(g_hConOut, cb->Info.dwSize))
2315 return FALSE;
2316 if (!SetConsoleTextAttribute(g_hConOut, cb->Info.wAttributes))
2317 return FALSE;
2318
2319 if (!RestoreScreen)
2320 {
2321 /*
2322 * No need to restore the screen buffer contents, so we're done.
2323 */
2324 return TRUE;
2325 }
2326
2327 if (!SetConsoleCursorPosition(g_hConOut, cb->Info.dwCursorPosition))
2328 return FALSE;
2329 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &cb->Info.srWindow))
2330 return FALSE;
2331
2332 /*
2333 * Restore the screen buffer contents.
2334 */
2335 if (cb->Buffer != NULL)
2336 {
2337 BufferCoord.X = 0;
2338 BufferCoord.Y = 0;
2339 WriteRegion.Left = 0;
2340 WriteRegion.Top = 0;
2341 WriteRegion.Right = cb->Info.dwSize.X - 1;
2342 WriteRegion.Bottom = cb->Info.dwSize.Y - 1;
2343 if (!WriteConsoleOutput(g_hConOut, /* output handle */
2344 cb->Buffer, /* our buffer */
2345 cb->BufferSize, /* dimensions of our buffer */
2346 BufferCoord, /* offset in our buffer */
2347 &WriteRegion)) /* region to restore */
2348 {
2349 return FALSE;
2350 }
2351 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002352
2353 return TRUE;
2354}
2355
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002356#define FEAT_RESTORE_ORIG_SCREEN
2357#ifdef FEAT_RESTORE_ORIG_SCREEN
2358static ConsoleBuffer g_cbOrig = { 0 };
2359#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002360static ConsoleBuffer g_cbNonTermcap = { 0 };
2361static ConsoleBuffer g_cbTermcap = { 0 };
2362
2363#ifdef FEAT_TITLE
2364#ifdef __BORLANDC__
2365typedef HWND (__stdcall *GETCONSOLEWINDOWPROC)(VOID);
2366#else
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002367typedef HWND (WINAPI *GETCONSOLEWINDOWPROC)(VOID);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002368#endif
2369char g_szOrigTitle[256] = { 0 };
2370HWND g_hWnd = NULL; /* also used in os_mswin.c */
2371static HICON g_hOrigIconSmall = NULL;
2372static HICON g_hOrigIcon = NULL;
2373static HICON g_hVimIcon = NULL;
2374static BOOL g_fCanChangeIcon = FALSE;
2375
2376/* ICON* are not defined in VC++ 4.0 */
2377#ifndef ICON_SMALL
2378#define ICON_SMALL 0
2379#endif
2380#ifndef ICON_BIG
2381#define ICON_BIG 1
2382#endif
2383/*
2384 * GetConsoleIcon()
2385 * Description:
2386 * Attempts to retrieve the small icon and/or the big icon currently in
2387 * use by a given window.
2388 * Returns:
2389 * TRUE on success
2390 */
2391 static BOOL
2392GetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002393 HWND hWnd,
2394 HICON *phIconSmall,
2395 HICON *phIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002396{
2397 if (hWnd == NULL)
2398 return FALSE;
2399
2400 if (phIconSmall != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002401 *phIconSmall = (HICON)SendMessage(hWnd, WM_GETICON,
2402 (WPARAM)ICON_SMALL, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002403 if (phIcon != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002404 *phIcon = (HICON)SendMessage(hWnd, WM_GETICON,
2405 (WPARAM)ICON_BIG, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002406 return TRUE;
2407}
2408
2409/*
2410 * SetConsoleIcon()
2411 * Description:
2412 * Attempts to change the small icon and/or the big icon currently in
2413 * use by a given window.
2414 * Returns:
2415 * TRUE on success
2416 */
2417 static BOOL
2418SetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002419 HWND hWnd,
2420 HICON hIconSmall,
2421 HICON hIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002422{
Bram Moolenaar071d4272004-06-13 20:20:40 +00002423 if (hWnd == NULL)
2424 return FALSE;
2425
2426 if (hIconSmall != NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002427 SendMessage(hWnd, WM_SETICON,
2428 (WPARAM)ICON_SMALL, (LPARAM)hIconSmall);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002429 if (hIcon != NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002430 SendMessage(hWnd, WM_SETICON,
2431 (WPARAM)ICON_BIG, (LPARAM) hIcon);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002432 return TRUE;
2433}
2434
2435/*
2436 * SaveConsoleTitleAndIcon()
2437 * Description:
2438 * Saves the current console window title in g_szOrigTitle, for later
2439 * restoration. Also, attempts to obtain a handle to the console window,
2440 * and use it to save the small and big icons currently in use by the
2441 * console window. This is not always possible on some versions of Windows;
2442 * nor is it possible when running Vim remotely using Telnet (since the
2443 * console window the user sees is owned by a remote process).
2444 */
2445 static void
2446SaveConsoleTitleAndIcon(void)
2447{
2448 GETCONSOLEWINDOWPROC GetConsoleWindowProc;
2449
2450 /* Save the original title. */
2451 if (!GetConsoleTitle(g_szOrigTitle, sizeof(g_szOrigTitle)))
2452 return;
2453
2454 /*
2455 * Obtain a handle to the console window using GetConsoleWindow() from
2456 * KERNEL32.DLL; we need to handle in order to change the window icon.
2457 * This function only exists on NT-based Windows, starting with Windows
2458 * 2000. On older operating systems, we can't change the window icon
2459 * anyway.
2460 */
2461 if ((GetConsoleWindowProc = (GETCONSOLEWINDOWPROC)
2462 GetProcAddress(GetModuleHandle("KERNEL32.DLL"),
2463 "GetConsoleWindow")) != NULL)
2464 {
2465 g_hWnd = (*GetConsoleWindowProc)();
2466 }
2467 if (g_hWnd == NULL)
2468 return;
2469
2470 /* Save the original console window icon. */
2471 GetConsoleIcon(g_hWnd, &g_hOrigIconSmall, &g_hOrigIcon);
2472 if (g_hOrigIconSmall == NULL || g_hOrigIcon == NULL)
2473 return;
2474
2475 /* Extract the first icon contained in the Vim executable. */
Bram Moolenaarcddc91c2014-09-23 21:53:41 +02002476 if (mch_icon_load((HANDLE *)&g_hVimIcon) == FAIL || g_hVimIcon == NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002477 g_hVimIcon = ExtractIcon(NULL, (LPCSTR)exe_name, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002478 if (g_hVimIcon != NULL)
2479 g_fCanChangeIcon = TRUE;
2480}
2481#endif
2482
2483static int g_fWindInitCalled = FALSE;
2484static int g_fTermcapMode = FALSE;
2485static CONSOLE_CURSOR_INFO g_cci;
2486static DWORD g_cmodein = 0;
2487static DWORD g_cmodeout = 0;
2488
2489/*
2490 * non-GUI version of mch_init().
2491 */
2492 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002493mch_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002494{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002495#ifndef FEAT_RESTORE_ORIG_SCREEN
2496 CONSOLE_SCREEN_BUFFER_INFO csbi;
2497#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002498#ifndef __MINGW32__
2499 extern int _fmode;
2500#endif
2501
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002502 /* Silently handle invalid parameters to CRT functions */
2503 SET_INVALID_PARAM_HANDLER;
2504
Bram Moolenaar071d4272004-06-13 20:20:40 +00002505 /* Let critical errors result in a failure, not in a dialog box. Required
2506 * for the timestamp test to work on removed floppies. */
2507 SetErrorMode(SEM_FAILCRITICALERRORS);
2508
2509 _fmode = O_BINARY; /* we do our own CR-LF translation */
2510 out_flush();
2511
2512 /* Obtain handles for the standard Console I/O devices */
2513 if (read_cmd_fd == 0)
2514 g_hConIn = GetStdHandle(STD_INPUT_HANDLE);
2515 else
2516 create_conin();
2517 g_hConOut = GetStdHandle(STD_OUTPUT_HANDLE);
2518
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002519#ifdef FEAT_RESTORE_ORIG_SCREEN
2520 /* Save the initial console buffer for later restoration */
2521 SaveConsoleBuffer(&g_cbOrig);
2522 g_attrCurrent = g_attrDefault = g_cbOrig.Info.wAttributes;
2523#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00002524 /* Get current text attributes */
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002525 GetConsoleScreenBufferInfo(g_hConOut, &csbi);
2526 g_attrCurrent = g_attrDefault = csbi.wAttributes;
2527#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002528 if (cterm_normal_fg_color == 0)
2529 cterm_normal_fg_color = (g_attrCurrent & 0xf) + 1;
2530 if (cterm_normal_bg_color == 0)
2531 cterm_normal_bg_color = ((g_attrCurrent >> 4) & 0xf) + 1;
2532
2533 /* set termcap codes to current text attributes */
2534 update_tcap(g_attrCurrent);
2535
2536 GetConsoleCursorInfo(g_hConOut, &g_cci);
2537 GetConsoleMode(g_hConIn, &g_cmodein);
2538 GetConsoleMode(g_hConOut, &g_cmodeout);
2539
2540#ifdef FEAT_TITLE
2541 SaveConsoleTitleAndIcon();
2542 /*
2543 * Set both the small and big icons of the console window to Vim's icon.
2544 * Note that Vim presently only has one size of icon (32x32), but it
2545 * automatically gets scaled down to 16x16 when setting the small icon.
2546 */
2547 if (g_fCanChangeIcon)
2548 SetConsoleIcon(g_hWnd, g_hVimIcon, g_hVimIcon);
2549#endif
2550
2551 ui_get_shellsize();
2552
2553#ifdef MCH_WRITE_DUMP
2554 fdDump = fopen("dump", "wt");
2555
2556 if (fdDump)
2557 {
2558 time_t t;
2559
2560 time(&t);
2561 fputs(ctime(&t), fdDump);
2562 fflush(fdDump);
2563 }
2564#endif
2565
2566 g_fWindInitCalled = TRUE;
2567
2568#ifdef FEAT_MOUSE
2569 g_fMouseAvail = GetSystemMetrics(SM_MOUSEPRESENT);
2570#endif
2571
2572#ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01002573 win_clip_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002574#endif
2575
2576 /* This will be NULL on anything but NT 4.0 */
2577 s_pfnGetConsoleKeyboardLayoutName =
2578 (PFNGCKLN) GetProcAddress(GetModuleHandle("kernel32.dll"),
2579 "GetConsoleKeyboardLayoutNameA");
2580}
2581
2582/*
2583 * non-GUI version of mch_exit().
2584 * Shut down and exit with status `r'
2585 * Careful: mch_exit() may be called before mch_init()!
2586 */
2587 void
2588mch_exit(int r)
2589{
2590 stoptermcap();
2591
2592 if (g_fWindInitCalled)
2593 settmode(TMODE_COOK);
2594
2595 ml_close_all(TRUE); /* remove all memfiles */
2596
2597 if (g_fWindInitCalled)
2598 {
2599#ifdef FEAT_TITLE
2600 mch_restore_title(3);
2601 /*
2602 * Restore both the small and big icons of the console window to
2603 * what they were at startup. Don't do this when the window is
2604 * closed, Vim would hang here.
2605 */
2606 if (g_fCanChangeIcon && !g_fForceExit)
2607 SetConsoleIcon(g_hWnd, g_hOrigIconSmall, g_hOrigIcon);
2608#endif
2609
2610#ifdef MCH_WRITE_DUMP
2611 if (fdDump)
2612 {
2613 time_t t;
2614
2615 time(&t);
2616 fputs(ctime(&t), fdDump);
2617 fclose(fdDump);
2618 }
2619 fdDump = NULL;
2620#endif
2621 }
2622
2623 SetConsoleCursorInfo(g_hConOut, &g_cci);
2624 SetConsoleMode(g_hConIn, g_cmodein);
2625 SetConsoleMode(g_hConOut, g_cmodeout);
2626
2627#ifdef DYNAMIC_GETTEXT
2628 dyn_libintl_end();
2629#endif
2630
2631 exit(r);
2632}
2633#endif /* !FEAT_GUI_W32 */
2634
Bram Moolenaar071d4272004-06-13 20:20:40 +00002635/*
2636 * Do we have an interactive window?
2637 */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00002638/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00002639 int
2640mch_check_win(
2641 int argc,
2642 char **argv)
2643{
2644 get_exe_name();
2645
2646#ifdef FEAT_GUI_W32
2647 return OK; /* GUI always has a tty */
2648#else
2649 if (isatty(1))
2650 return OK;
2651 return FAIL;
2652#endif
2653}
2654
2655
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002656#ifdef FEAT_MBYTE
2657/*
2658 * fname_casew(): Wide version of fname_case(). Set the case of the file name,
2659 * if it already exists. When "len" is > 0, also expand short to long
2660 * filenames.
2661 * Return FAIL if wide functions are not available, OK otherwise.
2662 * NOTE: much of this is identical to fname_case(), keep in sync!
2663 */
2664 static int
2665fname_casew(
2666 WCHAR *name,
2667 int len)
2668{
2669 WCHAR szTrueName[_MAX_PATH + 2];
2670 WCHAR szTrueNameTemp[_MAX_PATH + 2];
2671 WCHAR *ptrue, *ptruePrev;
2672 WCHAR *porig, *porigPrev;
2673 int flen;
2674 WIN32_FIND_DATAW fb;
Bram Moolenaar73c61632013-12-07 14:48:10 +01002675 HANDLE hFind = INVALID_HANDLE_VALUE;
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002676 int c;
2677 int slen;
2678
2679 flen = (int)wcslen(name);
2680 if (flen > _MAX_PATH)
2681 return OK;
2682
2683 /* slash_adjust(name) not needed, already adjusted by fname_case(). */
2684
2685 /* Build the new name in szTrueName[] one component at a time. */
2686 porig = name;
2687 ptrue = szTrueName;
2688
2689 if (iswalpha(porig[0]) && porig[1] == L':')
2690 {
2691 /* copy leading drive letter */
2692 *ptrue++ = *porig++;
2693 *ptrue++ = *porig++;
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002694 }
Bram Moolenaar73c61632013-12-07 14:48:10 +01002695 *ptrue = NUL; /* in case nothing follows */
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002696
2697 while (*porig != NUL)
2698 {
2699 /* copy \ characters */
2700 while (*porig == psepc)
2701 *ptrue++ = *porig++;
2702
2703 ptruePrev = ptrue;
2704 porigPrev = porig;
2705 while (*porig != NUL && *porig != psepc)
2706 {
2707 *ptrue++ = *porig++;
2708 }
2709 *ptrue = NUL;
2710
2711 /* To avoid a slow failure append "\*" when searching a directory,
2712 * server or network share. */
2713 wcscpy(szTrueNameTemp, szTrueName);
2714 slen = (int)wcslen(szTrueNameTemp);
2715 if (*porig == psepc && slen + 2 < _MAX_PATH)
2716 wcscpy(szTrueNameTemp + slen, L"\\*");
2717
2718 /* Skip "", "." and "..". */
2719 if (ptrue > ptruePrev
2720 && (ptruePrev[0] != L'.'
2721 || (ptruePrev[1] != NUL
2722 && (ptruePrev[1] != L'.' || ptruePrev[2] != NUL)))
2723 && (hFind = FindFirstFileW(szTrueNameTemp, &fb))
2724 != INVALID_HANDLE_VALUE)
2725 {
2726 c = *porig;
2727 *porig = NUL;
2728
2729 /* Only use the match when it's the same name (ignoring case) or
2730 * expansion is allowed and there is a match with the short name
2731 * and there is enough room. */
2732 if (_wcsicoll(porigPrev, fb.cFileName) == 0
2733 || (len > 0
2734 && (_wcsicoll(porigPrev, fb.cAlternateFileName) == 0
2735 && (int)(ptruePrev - szTrueName)
2736 + (int)wcslen(fb.cFileName) < len)))
2737 {
2738 wcscpy(ptruePrev, fb.cFileName);
2739
2740 /* Look for exact match and prefer it if found. Must be a
2741 * long name, otherwise there would be only one match. */
2742 while (FindNextFileW(hFind, &fb))
2743 {
2744 if (*fb.cAlternateFileName != NUL
2745 && (wcscoll(porigPrev, fb.cFileName) == 0
2746 || (len > 0
2747 && (_wcsicoll(porigPrev,
2748 fb.cAlternateFileName) == 0
2749 && (int)(ptruePrev - szTrueName)
2750 + (int)wcslen(fb.cFileName) < len))))
2751 {
2752 wcscpy(ptruePrev, fb.cFileName);
2753 break;
2754 }
2755 }
2756 }
2757 FindClose(hFind);
2758 *porig = c;
2759 ptrue = ptruePrev + wcslen(ptruePrev);
2760 }
2761 else if (hFind == INVALID_HANDLE_VALUE
2762 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
2763 return FAIL;
2764 }
2765
2766 wcscpy(name, szTrueName);
2767 return OK;
2768}
2769#endif
2770
Bram Moolenaar071d4272004-06-13 20:20:40 +00002771/*
2772 * fname_case(): Set the case of the file name, if it already exists.
2773 * When "len" is > 0, also expand short to long filenames.
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002774 * NOTE: much of this is identical to fname_casew(), keep in sync!
Bram Moolenaar071d4272004-06-13 20:20:40 +00002775 */
2776 void
2777fname_case(
2778 char_u *name,
2779 int len)
2780{
2781 char szTrueName[_MAX_PATH + 2];
Bram Moolenaar464c9252010-10-13 20:37:41 +02002782 char szTrueNameTemp[_MAX_PATH + 2];
Bram Moolenaar071d4272004-06-13 20:20:40 +00002783 char *ptrue, *ptruePrev;
2784 char *porig, *porigPrev;
2785 int flen;
2786 WIN32_FIND_DATA fb;
2787 HANDLE hFind;
2788 int c;
Bram Moolenaar464c9252010-10-13 20:37:41 +02002789 int slen;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002790
Bram Moolenaara3ffd9c2005-07-21 21:03:15 +00002791 flen = (int)STRLEN(name);
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002792 if (flen == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002793 return;
2794
2795 slash_adjust(name);
2796
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002797#ifdef FEAT_MBYTE
2798 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2799 {
2800 WCHAR *p = enc_to_utf16(name, NULL);
2801
2802 if (p != NULL)
2803 {
2804 char_u *q;
Bram Moolenaar21d89b62014-10-07 10:38:40 +02002805 WCHAR buf[_MAX_PATH + 1];
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002806
Bram Moolenaar21d89b62014-10-07 10:38:40 +02002807 wcsncpy(buf, p, _MAX_PATH);
2808 buf[_MAX_PATH] = L'\0';
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002809 vim_free(p);
2810
2811 if (fname_casew(buf, (len > 0) ? _MAX_PATH : 0) == OK)
2812 {
2813 q = utf16_to_enc(buf, NULL);
2814 if (q != NULL)
2815 {
2816 vim_strncpy(name, q, (len > 0) ? len - 1 : flen);
2817 vim_free(q);
2818 return;
2819 }
2820 }
2821 }
2822 /* Retry with non-wide function (for Windows 98). */
2823 }
2824#endif
2825
2826 /* If 'enc' is utf-8, flen can be larger than _MAX_PATH.
2827 * So we should check this after calling wide function. */
2828 if (flen > _MAX_PATH)
2829 return;
2830
Bram Moolenaar071d4272004-06-13 20:20:40 +00002831 /* Build the new name in szTrueName[] one component at a time. */
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002832 porig = (char *)name;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002833 ptrue = szTrueName;
2834
2835 if (isalpha(porig[0]) && porig[1] == ':')
2836 {
2837 /* copy leading drive letter */
2838 *ptrue++ = *porig++;
2839 *ptrue++ = *porig++;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002840 }
Bram Moolenaar73c61632013-12-07 14:48:10 +01002841 *ptrue = NUL; /* in case nothing follows */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002842
2843 while (*porig != NUL)
2844 {
2845 /* copy \ characters */
2846 while (*porig == psepc)
2847 *ptrue++ = *porig++;
2848
2849 ptruePrev = ptrue;
2850 porigPrev = porig;
2851 while (*porig != NUL && *porig != psepc)
2852 {
2853#ifdef FEAT_MBYTE
2854 int l;
2855
2856 if (enc_dbcs)
2857 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002858 l = (*mb_ptr2len)((char_u *)porig);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002859 while (--l >= 0)
2860 *ptrue++ = *porig++;
2861 }
2862 else
2863#endif
2864 *ptrue++ = *porig++;
2865 }
2866 *ptrue = NUL;
2867
Bram Moolenaar464c9252010-10-13 20:37:41 +02002868 /* To avoid a slow failure append "\*" when searching a directory,
2869 * server or network share. */
2870 STRCPY(szTrueNameTemp, szTrueName);
Bram Moolenaar6b5ef062010-10-27 12:18:00 +02002871 slen = (int)strlen(szTrueNameTemp);
Bram Moolenaar464c9252010-10-13 20:37:41 +02002872 if (*porig == psepc && slen + 2 < _MAX_PATH)
2873 STRCPY(szTrueNameTemp + slen, "\\*");
2874
Bram Moolenaar071d4272004-06-13 20:20:40 +00002875 /* Skip "", "." and "..". */
2876 if (ptrue > ptruePrev
2877 && (ptruePrev[0] != '.'
2878 || (ptruePrev[1] != NUL
2879 && (ptruePrev[1] != '.' || ptruePrev[2] != NUL)))
Bram Moolenaar464c9252010-10-13 20:37:41 +02002880 && (hFind = FindFirstFile(szTrueNameTemp, &fb))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002881 != INVALID_HANDLE_VALUE)
2882 {
2883 c = *porig;
2884 *porig = NUL;
2885
2886 /* Only use the match when it's the same name (ignoring case) or
2887 * expansion is allowed and there is a match with the short name
2888 * and there is enough room. */
2889 if (_stricoll(porigPrev, fb.cFileName) == 0
2890 || (len > 0
2891 && (_stricoll(porigPrev, fb.cAlternateFileName) == 0
2892 && (int)(ptruePrev - szTrueName)
2893 + (int)strlen(fb.cFileName) < len)))
2894 {
2895 STRCPY(ptruePrev, fb.cFileName);
2896
2897 /* Look for exact match and prefer it if found. Must be a
2898 * long name, otherwise there would be only one match. */
2899 while (FindNextFile(hFind, &fb))
2900 {
2901 if (*fb.cAlternateFileName != NUL
2902 && (strcoll(porigPrev, fb.cFileName) == 0
2903 || (len > 0
2904 && (_stricoll(porigPrev,
2905 fb.cAlternateFileName) == 0
2906 && (int)(ptruePrev - szTrueName)
2907 + (int)strlen(fb.cFileName) < len))))
2908 {
2909 STRCPY(ptruePrev, fb.cFileName);
2910 break;
2911 }
2912 }
2913 }
2914 FindClose(hFind);
2915 *porig = c;
2916 ptrue = ptruePrev + strlen(ptruePrev);
2917 }
2918 }
2919
2920 STRCPY(name, szTrueName);
2921}
2922
2923
2924/*
2925 * Insert user name in s[len].
2926 */
2927 int
2928mch_get_user_name(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002929 char_u *s,
2930 int len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002931{
Bram Moolenaar41a09032007-10-01 18:34:34 +00002932 char szUserName[256 + 1]; /* UNLEN is 256 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002933 DWORD cch = sizeof szUserName;
2934
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01002935#ifdef FEAT_MBYTE
2936 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2937 {
2938 WCHAR wszUserName[256 + 1]; /* UNLEN is 256 */
2939 DWORD wcch = sizeof(wszUserName) / sizeof(WCHAR);
2940
2941 if (GetUserNameW(wszUserName, &wcch))
2942 {
2943 char_u *p = utf16_to_enc(wszUserName, NULL);
2944
2945 if (p != NULL)
2946 {
2947 vim_strncpy(s, p, len - 1);
2948 vim_free(p);
2949 return OK;
2950 }
2951 }
Bram Moolenaarcd981f22014-02-11 17:06:00 +01002952 else if (GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
2953 return FAIL;
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01002954 /* Retry with non-wide function (for Windows 98). */
2955 }
2956#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002957 if (GetUserName(szUserName, &cch))
2958 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002959 vim_strncpy(s, (char_u *)szUserName, len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002960 return OK;
2961 }
2962 s[0] = NUL;
2963 return FAIL;
2964}
2965
2966
2967/*
2968 * Insert host name in s[len].
2969 */
2970 void
2971mch_get_host_name(
2972 char_u *s,
2973 int len)
2974{
2975 DWORD cch = len;
2976
Bram Moolenaar2cc87382013-12-11 18:21:45 +01002977#ifdef FEAT_MBYTE
2978 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2979 {
2980 WCHAR wszHostName[256 + 1];
2981 DWORD wcch = sizeof(wszHostName) / sizeof(WCHAR);
2982
2983 if (GetComputerNameW(wszHostName, &wcch))
2984 {
2985 char_u *p = utf16_to_enc(wszHostName, NULL);
2986
2987 if (p != NULL)
2988 {
2989 vim_strncpy(s, p, len - 1);
2990 vim_free(p);
2991 return;
2992 }
2993 }
Bram Moolenaarcd981f22014-02-11 17:06:00 +01002994 else if (GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
2995 return;
Bram Moolenaar2cc87382013-12-11 18:21:45 +01002996 /* Retry with non-wide function (for Windows 98). */
2997 }
2998#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002999 if (!GetComputerName((LPSTR)s, &cch))
3000 vim_strncpy(s, (char_u *)"PC (Win32 Vim)", len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003001}
3002
3003
3004/*
3005 * return process ID
3006 */
3007 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003008mch_get_pid(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003009{
3010 return (long)GetCurrentProcessId();
3011}
3012
3013
3014/*
3015 * Get name of current directory into buffer 'buf' of length 'len' bytes.
3016 * Return OK for success, FAIL for failure.
3017 */
3018 int
3019mch_dirname(
3020 char_u *buf,
3021 int len)
3022{
3023 /*
3024 * Originally this was:
3025 * return (getcwd(buf, len) != NULL ? OK : FAIL);
3026 * But the Win32s known bug list says that getcwd() doesn't work
3027 * so use the Win32 system call instead. <Negri>
3028 */
3029#ifdef FEAT_MBYTE
3030 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3031 {
3032 WCHAR wbuf[_MAX_PATH + 1];
3033
3034 if (GetCurrentDirectoryW(_MAX_PATH, wbuf) != 0)
3035 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00003036 char_u *p = utf16_to_enc(wbuf, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003037
3038 if (p != NULL)
3039 {
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00003040 vim_strncpy(buf, p, len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003041 vim_free(p);
3042 return OK;
3043 }
3044 }
Bram Moolenaarcd981f22014-02-11 17:06:00 +01003045 else if (GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
3046 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003047 /* Retry with non-wide function (for Windows 98). */
3048 }
3049#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003050 return (GetCurrentDirectory(len, (LPSTR)buf) != 0 ? OK : FAIL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003051}
3052
3053/*
Bram Moolenaarffa22202013-11-21 12:34:11 +01003054 * Get file permissions for "name".
3055 * Return mode_t or -1 for error.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003056 */
3057 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003058mch_getperm(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003059{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003060 struct stat st;
Bram Moolenaarffa22202013-11-21 12:34:11 +01003061 int n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003062
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003063 n = mch_stat((char *)name, &st);
Bram Moolenaar78cf3f02014-01-10 18:16:07 +01003064 return n == 0 ? (long)(unsigned short)st.st_mode : -1L;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003065}
3066
3067
3068/*
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003069 * Set file permission for "name" to "perm".
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003070 *
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003071 * Return FAIL for failure, OK otherwise.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003072 */
3073 int
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003074mch_setperm(char_u *name, long perm)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003075{
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003076 long n = -1;
3077
Bram Moolenaar071d4272004-06-13 20:20:40 +00003078#ifdef FEAT_MBYTE
3079 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3080 {
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003081 WCHAR *p = enc_to_utf16(name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003082
3083 if (p != NULL)
3084 {
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003085 n = _wchmod(p, perm);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003086 vim_free(p);
Bram Moolenaarcd981f22014-02-11 17:06:00 +01003087 if (n == -1 && g_PlatformId == VER_PLATFORM_WIN32_NT)
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003088 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003089 /* Retry with non-wide function (for Windows 98). */
3090 }
3091 }
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003092 if (n == -1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003093#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003094 n = _chmod((const char *)name, perm);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003095 if (n == -1)
3096 return FAIL;
3097
3098 win32_set_archive(name);
3099
3100 return OK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003101}
3102
3103/*
3104 * Set hidden flag for "name".
3105 */
3106 void
3107mch_hide(char_u *name)
3108{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003109 int attrs = win32_getattrs(name);
3110 if (attrs == -1)
3111 return;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003112
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003113 attrs |= FILE_ATTRIBUTE_HIDDEN;
3114 win32_setattrs(name, attrs);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003115}
3116
3117/*
Bram Moolenaar8a52ba72015-11-02 14:45:56 +01003118 * Return TRUE if file "name" exists and is hidden.
3119 */
3120 int
3121mch_ishidden(char_u *name)
3122{
3123 int f = win32_getattrs(name);
3124
3125 if (f == -1)
3126 return FALSE; /* file does not exist at all */
3127
3128 return (f & FILE_ATTRIBUTE_HIDDEN) != 0;
3129}
3130
3131/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003132 * return TRUE if "name" is a directory
3133 * return FALSE if "name" is not a directory or upon error
3134 */
3135 int
3136mch_isdir(char_u *name)
3137{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003138 int f = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003139
3140 if (f == -1)
3141 return FALSE; /* file does not exist at all */
3142
3143 return (f & FILE_ATTRIBUTE_DIRECTORY) != 0;
3144}
3145
3146/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01003147 * return TRUE if "name" is a directory, NOT a symlink to a directory
3148 * return FALSE if "name" is not a directory
3149 * return FALSE for error
3150 */
3151 int
3152mch_isrealdir(char_u *name)
3153{
3154 return mch_isdir(name) && !mch_is_symbolic_link(name);
3155}
3156
3157/*
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003158 * Create directory "name".
3159 * Return 0 on success, -1 on error.
3160 */
3161 int
3162mch_mkdir(char_u *name)
3163{
3164#ifdef FEAT_MBYTE
3165 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3166 {
3167 WCHAR *p;
3168 int retval;
3169
3170 p = enc_to_utf16(name, NULL);
3171 if (p == NULL)
3172 return -1;
3173 retval = _wmkdir(p);
3174 vim_free(p);
3175 return retval;
3176 }
3177#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003178 return _mkdir((const char *)name);
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003179}
3180
3181/*
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003182 * Delete directory "name".
3183 * Return 0 on success, -1 on error.
3184 */
3185 int
3186mch_rmdir(char_u *name)
3187{
3188#ifdef FEAT_MBYTE
3189 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3190 {
3191 WCHAR *p;
3192 int retval;
3193
3194 p = enc_to_utf16(name, NULL);
3195 if (p == NULL)
3196 return -1;
3197 retval = _wrmdir(p);
3198 vim_free(p);
3199 return retval;
3200 }
3201#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003202 return _rmdir((const char *)name);
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003203}
3204
3205/*
Bram Moolenaar03f48552006-02-28 23:52:23 +00003206 * Return TRUE if file "fname" has more than one link.
3207 */
3208 int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003209mch_is_hard_link(char_u *fname)
Bram Moolenaar03f48552006-02-28 23:52:23 +00003210{
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003211 BY_HANDLE_FILE_INFORMATION info;
3212
3213 return win32_fileinfo(fname, &info) == FILEINFO_OK
3214 && info.nNumberOfLinks > 1;
3215}
3216
3217/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01003218 * Return TRUE if "name" is a symbolic link (or a junction).
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003219 */
3220 int
Bram Moolenaar203258c2016-01-17 22:15:16 +01003221mch_is_symbolic_link(char_u *name)
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003222{
3223 HANDLE hFind;
3224 int res = FALSE;
3225 WIN32_FIND_DATAA findDataA;
3226 DWORD fileFlags = 0, reparseTag = 0;
3227#ifdef FEAT_MBYTE
3228 WCHAR *wn = NULL;
3229 WIN32_FIND_DATAW findDataW;
3230
3231 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar203258c2016-01-17 22:15:16 +01003232 wn = enc_to_utf16(name, NULL);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003233 if (wn != NULL)
3234 {
3235 hFind = FindFirstFileW(wn, &findDataW);
3236 vim_free(wn);
3237 if (hFind == INVALID_HANDLE_VALUE
3238 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
3239 {
3240 /* Retry with non-wide function (for Windows 98). */
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003241 hFind = FindFirstFile((LPCSTR)name, &findDataA);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003242 if (hFind != INVALID_HANDLE_VALUE)
3243 {
3244 fileFlags = findDataA.dwFileAttributes;
3245 reparseTag = findDataA.dwReserved0;
3246 }
3247 }
3248 else
3249 {
3250 fileFlags = findDataW.dwFileAttributes;
3251 reparseTag = findDataW.dwReserved0;
3252 }
3253 }
Bram Moolenaar03e114b2013-06-16 16:34:56 +02003254 else
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003255#endif
Bram Moolenaar03e114b2013-06-16 16:34:56 +02003256 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003257 hFind = FindFirstFile((LPCSTR)name, &findDataA);
Bram Moolenaar03e114b2013-06-16 16:34:56 +02003258 if (hFind != INVALID_HANDLE_VALUE)
3259 {
3260 fileFlags = findDataA.dwFileAttributes;
3261 reparseTag = findDataA.dwReserved0;
3262 }
3263 }
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003264
3265 if (hFind != INVALID_HANDLE_VALUE)
3266 FindClose(hFind);
3267
3268 if ((fileFlags & FILE_ATTRIBUTE_REPARSE_POINT)
Bram Moolenaar203258c2016-01-17 22:15:16 +01003269 && (reparseTag == IO_REPARSE_TAG_SYMLINK
3270 || reparseTag == IO_REPARSE_TAG_MOUNT_POINT))
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003271 res = TRUE;
3272
3273 return res;
3274}
3275
3276/*
3277 * Return TRUE if file "fname" has more than one link or if it is a symbolic
3278 * link.
3279 */
3280 int
3281mch_is_linked(char_u *fname)
3282{
3283 if (mch_is_hard_link(fname) || mch_is_symbolic_link(fname))
3284 return TRUE;
3285 return FALSE;
3286}
3287
3288/*
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003289 * Get the by-handle-file-information for "fname".
3290 * Returns FILEINFO_OK when OK.
3291 * returns FILEINFO_ENC_FAIL when enc_to_utf16() failed.
3292 * Returns FILEINFO_READ_FAIL when CreateFile() failed.
3293 * Returns FILEINFO_INFO_FAIL when GetFileInformationByHandle() failed.
3294 */
3295 int
3296win32_fileinfo(char_u *fname, BY_HANDLE_FILE_INFORMATION *info)
3297{
Bram Moolenaar03f48552006-02-28 23:52:23 +00003298 HANDLE hFile;
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003299 int res = FILEINFO_READ_FAIL;
Bram Moolenaar03f48552006-02-28 23:52:23 +00003300#ifdef FEAT_MBYTE
3301 WCHAR *wn = NULL;
3302
3303 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003304 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00003305 wn = enc_to_utf16(fname, NULL);
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003306 if (wn == NULL)
3307 res = FILEINFO_ENC_FAIL;
3308 }
Bram Moolenaar03f48552006-02-28 23:52:23 +00003309 if (wn != NULL)
3310 {
3311 hFile = CreateFileW(wn, /* file name */
3312 GENERIC_READ, /* access mode */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003313 FILE_SHARE_READ | FILE_SHARE_WRITE, /* share mode */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003314 NULL, /* security descriptor */
3315 OPEN_EXISTING, /* creation disposition */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003316 FILE_FLAG_BACKUP_SEMANTICS, /* file attributes */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003317 NULL); /* handle to template file */
3318 if (hFile == INVALID_HANDLE_VALUE
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003319 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
Bram Moolenaar03f48552006-02-28 23:52:23 +00003320 {
3321 /* Retry with non-wide function (for Windows 98). */
3322 vim_free(wn);
3323 wn = NULL;
3324 }
3325 }
3326 if (wn == NULL)
3327#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003328 hFile = CreateFile((LPCSTR)fname, /* file name */
3329 GENERIC_READ, /* access mode */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003330 FILE_SHARE_READ | FILE_SHARE_WRITE, /* share mode */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003331 NULL, /* security descriptor */
3332 OPEN_EXISTING, /* creation disposition */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003333 FILE_FLAG_BACKUP_SEMANTICS, /* file attributes */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003334 NULL); /* handle to template file */
3335
3336 if (hFile != INVALID_HANDLE_VALUE)
3337 {
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003338 if (GetFileInformationByHandle(hFile, info) != 0)
3339 res = FILEINFO_OK;
3340 else
3341 res = FILEINFO_INFO_FAIL;
Bram Moolenaar03f48552006-02-28 23:52:23 +00003342 CloseHandle(hFile);
3343 }
3344
3345#ifdef FEAT_MBYTE
3346 vim_free(wn);
3347#endif
3348 return res;
3349}
3350
3351/*
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003352 * get file attributes for `name'
3353 * -1 : error
3354 * else FILE_ATTRIBUTE_* defined in winnt.h
3355 */
Bram Moolenaarffa22202013-11-21 12:34:11 +01003356 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003357win32_getattrs(char_u *name)
3358{
3359 int attr;
3360#ifdef FEAT_MBYTE
3361 WCHAR *p = NULL;
3362
3363 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3364 p = enc_to_utf16(name, NULL);
3365
3366 if (p != NULL)
3367 {
3368 attr = GetFileAttributesW(p);
3369 if (attr < 0 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
3370 {
3371 /* Retry with non-wide function (for Windows 98). */
3372 vim_free(p);
3373 p = NULL;
3374 }
3375 }
3376 if (p == NULL)
3377#endif
3378 attr = GetFileAttributes((char *)name);
3379#ifdef FEAT_MBYTE
3380 vim_free(p);
3381#endif
3382 return attr;
3383}
3384
3385/*
3386 * set file attributes for `name' to `attrs'
3387 *
3388 * return -1 for failure, 0 otherwise
3389 */
3390 static
3391 int
3392win32_setattrs(char_u *name, int attrs)
3393{
3394 int res;
3395#ifdef FEAT_MBYTE
3396 WCHAR *p = NULL;
3397
3398 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3399 p = enc_to_utf16(name, NULL);
3400
3401 if (p != NULL)
3402 {
3403 res = SetFileAttributesW(p, attrs);
3404 if (res == FALSE
3405 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
3406 {
3407 /* Retry with non-wide function (for Windows 98). */
3408 vim_free(p);
3409 p = NULL;
3410 }
3411 }
3412 if (p == NULL)
3413#endif
3414 res = SetFileAttributes((char *)name, attrs);
3415#ifdef FEAT_MBYTE
3416 vim_free(p);
3417#endif
3418 return res ? 0 : -1;
3419}
3420
3421/*
3422 * Set archive flag for "name".
3423 */
3424 static
3425 int
3426win32_set_archive(char_u *name)
3427{
3428 int attrs = win32_getattrs(name);
3429 if (attrs == -1)
3430 return -1;
3431
3432 attrs |= FILE_ATTRIBUTE_ARCHIVE;
3433 return win32_setattrs(name, attrs);
3434}
3435
3436/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003437 * Return TRUE if file or directory "name" is writable (not readonly).
3438 * Strange semantics of Win32: a readonly directory is writable, but you can't
3439 * delete a file. Let's say this means it is writable.
3440 */
3441 int
3442mch_writable(char_u *name)
3443{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003444 int attrs = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003445
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003446 return (attrs != -1 && (!(attrs & FILE_ATTRIBUTE_READONLY)
3447 || (attrs & FILE_ATTRIBUTE_DIRECTORY)));
Bram Moolenaar071d4272004-06-13 20:20:40 +00003448}
3449
Bram Moolenaar071d4272004-06-13 20:20:40 +00003450/*
3451 * Return 1 if "name" can be executed, 0 if not.
Bram Moolenaar77b77102015-03-21 22:18:41 +01003452 * If "use_path" is FALSE only check if "name" is executable.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003453 * Return -1 if unknown.
3454 */
3455 int
Bram Moolenaar77b77102015-03-21 22:18:41 +01003456mch_can_exe(char_u *name, char_u **path, int use_path)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003457{
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003458 char_u buf[_MAX_PATH];
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00003459 int len = (int)STRLEN(name);
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003460 char_u *p;
3461
3462 if (len >= _MAX_PATH) /* safety check */
3463 return FALSE;
Bram Moolenaar77b77102015-03-21 22:18:41 +01003464 if (!use_path)
3465 {
3466 /* TODO: check if file is really executable. */
3467 return mch_getperm(name) != -1 && !mch_isdir(name);
3468 }
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003469
3470 /* If there already is an extension try using the name directly. Also do
3471 * this with a Unix-shell like 'shell'. */
3472 if (vim_strchr(gettail(name), '.') != NULL
3473 || strstr((char *)gettail(p_sh), "sh") != NULL)
Bram Moolenaarc7f02552014-04-01 21:00:59 +02003474 if (executable_exists((char *)name, path))
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003475 return TRUE;
3476
3477 /*
3478 * Loop over all extensions in $PATHEXT.
3479 */
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00003480 vim_strncpy(buf, name, _MAX_PATH - 1);
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003481 p = mch_getenv("PATHEXT");
3482 if (p == NULL)
3483 p = (char_u *)".com;.exe;.bat;.cmd";
3484 while (*p)
3485 {
3486 if (p[0] == '.' && (p[1] == NUL || p[1] == ';'))
3487 {
3488 /* A single "." means no extension is added. */
3489 buf[len] = NUL;
3490 ++p;
3491 if (*p)
3492 ++p;
3493 }
3494 else
3495 copy_option_part(&p, buf + len, _MAX_PATH - len, ";");
Bram Moolenaarc7f02552014-04-01 21:00:59 +02003496 if (executable_exists((char *)buf, path))
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003497 return TRUE;
3498 }
3499 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003500}
Bram Moolenaar071d4272004-06-13 20:20:40 +00003501
3502/*
3503 * Check what "name" is:
3504 * NODE_NORMAL: file or directory (or doesn't exist)
3505 * NODE_WRITABLE: writable device, socket, fifo, etc.
3506 * NODE_OTHER: non-writable things
3507 */
3508 int
3509mch_nodetype(char_u *name)
3510{
3511 HANDLE hFile;
3512 int type;
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003513#ifdef FEAT_MBYTE
3514 WCHAR *wn = NULL;
3515#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003516
Bram Moolenaar043545e2006-10-10 16:44:07 +00003517 /* We can't open a file with a name "\\.\con" or "\\.\prn" and trying to
3518 * read from it later will cause Vim to hang. Thus return NODE_WRITABLE
3519 * here. */
3520 if (STRNCMP(name, "\\\\.\\", 4) == 0)
3521 return NODE_WRITABLE;
3522
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003523#ifdef FEAT_MBYTE
3524 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3525 {
3526 wn = enc_to_utf16(name, NULL);
3527 if (wn != NULL)
3528 {
3529 hFile = CreateFileW(wn, /* file name */
3530 GENERIC_WRITE, /* access mode */
3531 0, /* share mode */
3532 NULL, /* security descriptor */
3533 OPEN_EXISTING, /* creation disposition */
3534 0, /* file attributes */
3535 NULL); /* handle to template file */
3536 if (hFile == INVALID_HANDLE_VALUE
3537 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
3538 {
3539 /* Retry with non-wide function (for Windows 98). */
3540 vim_free(wn);
3541 wn = NULL;
3542 }
3543 }
3544 }
3545 if (wn == NULL)
3546#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003547 hFile = CreateFile((LPCSTR)name, /* file name */
3548 GENERIC_WRITE, /* access mode */
3549 0, /* share mode */
3550 NULL, /* security descriptor */
3551 OPEN_EXISTING, /* creation disposition */
3552 0, /* file attributes */
3553 NULL); /* handle to template file */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003554
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003555#ifdef FEAT_MBYTE
3556 vim_free(wn);
3557#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003558 if (hFile == INVALID_HANDLE_VALUE)
3559 return NODE_NORMAL;
3560
3561 type = GetFileType(hFile);
3562 CloseHandle(hFile);
3563 if (type == FILE_TYPE_CHAR)
3564 return NODE_WRITABLE;
3565 if (type == FILE_TYPE_DISK)
3566 return NODE_NORMAL;
3567 return NODE_OTHER;
3568}
3569
3570#ifdef HAVE_ACL
3571struct my_acl
3572{
3573 PSECURITY_DESCRIPTOR pSecurityDescriptor;
3574 PSID pSidOwner;
3575 PSID pSidGroup;
3576 PACL pDacl;
3577 PACL pSacl;
3578};
3579#endif
3580
3581/*
3582 * Return a pointer to the ACL of file "fname" in allocated memory.
3583 * Return NULL if the ACL is not available for whatever reason.
3584 */
3585 vim_acl_T
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003586mch_get_acl(char_u *fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003587{
3588#ifndef HAVE_ACL
3589 return (vim_acl_T)NULL;
3590#else
3591 struct my_acl *p = NULL;
Bram Moolenaar27515922013-06-29 15:36:26 +02003592 DWORD err;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003593
3594 /* This only works on Windows NT and 2000. */
3595 if (g_PlatformId == VER_PLATFORM_WIN32_NT && advapi_lib != NULL)
3596 {
3597 p = (struct my_acl *)alloc_clear((unsigned)sizeof(struct my_acl));
3598 if (p != NULL)
3599 {
Bram Moolenaar27515922013-06-29 15:36:26 +02003600# ifdef FEAT_MBYTE
3601 WCHAR *wn = NULL;
3602
3603 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3604 wn = enc_to_utf16(fname, NULL);
3605 if (wn != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003606 {
Bram Moolenaar27515922013-06-29 15:36:26 +02003607 /* Try to retrieve the entire security descriptor. */
3608 err = pGetNamedSecurityInfoW(
3609 wn, // Abstract filename
3610 SE_FILE_OBJECT, // File Object
3611 OWNER_SECURITY_INFORMATION |
3612 GROUP_SECURITY_INFORMATION |
3613 DACL_SECURITY_INFORMATION |
3614 SACL_SECURITY_INFORMATION,
3615 &p->pSidOwner, // Ownership information.
3616 &p->pSidGroup, // Group membership.
3617 &p->pDacl, // Discretionary information.
3618 &p->pSacl, // For auditing purposes.
3619 &p->pSecurityDescriptor);
3620 if (err == ERROR_ACCESS_DENIED ||
3621 err == ERROR_PRIVILEGE_NOT_HELD)
3622 {
3623 /* Retrieve only DACL. */
3624 (void)pGetNamedSecurityInfoW(
3625 wn,
3626 SE_FILE_OBJECT,
3627 DACL_SECURITY_INFORMATION,
3628 NULL,
3629 NULL,
3630 &p->pDacl,
3631 NULL,
3632 &p->pSecurityDescriptor);
3633 }
3634 if (p->pSecurityDescriptor == NULL)
3635 {
3636 mch_free_acl((vim_acl_T)p);
3637 p = NULL;
3638 }
3639 vim_free(wn);
3640 }
3641 else
3642# endif
3643 {
3644 /* Try to retrieve the entire security descriptor. */
3645 err = pGetNamedSecurityInfo(
3646 (LPSTR)fname, // Abstract filename
3647 SE_FILE_OBJECT, // File Object
3648 OWNER_SECURITY_INFORMATION |
3649 GROUP_SECURITY_INFORMATION |
3650 DACL_SECURITY_INFORMATION |
3651 SACL_SECURITY_INFORMATION,
3652 &p->pSidOwner, // Ownership information.
3653 &p->pSidGroup, // Group membership.
3654 &p->pDacl, // Discretionary information.
3655 &p->pSacl, // For auditing purposes.
3656 &p->pSecurityDescriptor);
3657 if (err == ERROR_ACCESS_DENIED ||
3658 err == ERROR_PRIVILEGE_NOT_HELD)
3659 {
3660 /* Retrieve only DACL. */
3661 (void)pGetNamedSecurityInfo(
3662 (LPSTR)fname,
3663 SE_FILE_OBJECT,
3664 DACL_SECURITY_INFORMATION,
3665 NULL,
3666 NULL,
3667 &p->pDacl,
3668 NULL,
3669 &p->pSecurityDescriptor);
3670 }
3671 if (p->pSecurityDescriptor == NULL)
3672 {
3673 mch_free_acl((vim_acl_T)p);
3674 p = NULL;
3675 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003676 }
3677 }
3678 }
3679
3680 return (vim_acl_T)p;
3681#endif
3682}
3683
Bram Moolenaar27515922013-06-29 15:36:26 +02003684#ifdef HAVE_ACL
3685/*
3686 * Check if "acl" contains inherited ACE.
3687 */
3688 static BOOL
3689is_acl_inherited(PACL acl)
3690{
3691 DWORD i;
3692 ACL_SIZE_INFORMATION acl_info;
3693 PACCESS_ALLOWED_ACE ace;
3694
3695 acl_info.AceCount = 0;
3696 GetAclInformation(acl, &acl_info, sizeof(acl_info), AclSizeInformation);
3697 for (i = 0; i < acl_info.AceCount; i++)
3698 {
3699 GetAce(acl, i, (LPVOID *)&ace);
3700 if (ace->Header.AceFlags & INHERITED_ACE)
3701 return TRUE;
3702 }
3703 return FALSE;
3704}
3705#endif
3706
Bram Moolenaar071d4272004-06-13 20:20:40 +00003707/*
3708 * Set the ACL of file "fname" to "acl" (unless it's NULL).
3709 * Errors are ignored.
3710 * This must only be called with "acl" equal to what mch_get_acl() returned.
3711 */
3712 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003713mch_set_acl(char_u *fname, vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003714{
3715#ifdef HAVE_ACL
3716 struct my_acl *p = (struct my_acl *)acl;
Bram Moolenaar27515922013-06-29 15:36:26 +02003717 SECURITY_INFORMATION sec_info = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003718
3719 if (p != NULL && advapi_lib != NULL)
Bram Moolenaar27515922013-06-29 15:36:26 +02003720 {
3721# ifdef FEAT_MBYTE
3722 WCHAR *wn = NULL;
3723# endif
3724
3725 /* Set security flags */
3726 if (p->pSidOwner)
3727 sec_info |= OWNER_SECURITY_INFORMATION;
3728 if (p->pSidGroup)
3729 sec_info |= GROUP_SECURITY_INFORMATION;
3730 if (p->pDacl)
3731 {
3732 sec_info |= DACL_SECURITY_INFORMATION;
3733 /* Do not inherit its parent's DACL.
3734 * If the DACL is inherited, Cygwin permissions would be changed.
3735 */
3736 if (!is_acl_inherited(p->pDacl))
3737 sec_info |= PROTECTED_DACL_SECURITY_INFORMATION;
3738 }
3739 if (p->pSacl)
3740 sec_info |= SACL_SECURITY_INFORMATION;
3741
3742# ifdef FEAT_MBYTE
3743 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3744 wn = enc_to_utf16(fname, NULL);
3745 if (wn != NULL)
3746 {
3747 (void)pSetNamedSecurityInfoW(
3748 wn, // Abstract filename
3749 SE_FILE_OBJECT, // File Object
3750 sec_info,
3751 p->pSidOwner, // Ownership information.
3752 p->pSidGroup, // Group membership.
3753 p->pDacl, // Discretionary information.
3754 p->pSacl // For auditing purposes.
3755 );
3756 vim_free(wn);
3757 }
3758 else
3759# endif
3760 {
3761 (void)pSetNamedSecurityInfo(
3762 (LPSTR)fname, // Abstract filename
3763 SE_FILE_OBJECT, // File Object
3764 sec_info,
3765 p->pSidOwner, // Ownership information.
3766 p->pSidGroup, // Group membership.
3767 p->pDacl, // Discretionary information.
3768 p->pSacl // For auditing purposes.
3769 );
3770 }
3771 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003772#endif
3773}
3774
3775 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003776mch_free_acl(vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003777{
3778#ifdef HAVE_ACL
3779 struct my_acl *p = (struct my_acl *)acl;
3780
3781 if (p != NULL)
3782 {
3783 LocalFree(p->pSecurityDescriptor); // Free the memory just in case
3784 vim_free(p);
3785 }
3786#endif
3787}
3788
3789#ifndef FEAT_GUI_W32
3790
3791/*
3792 * handler for ctrl-break, ctrl-c interrupts, and fatal events.
3793 */
3794 static BOOL WINAPI
3795handler_routine(
3796 DWORD dwCtrlType)
3797{
3798 switch (dwCtrlType)
3799 {
3800 case CTRL_C_EVENT:
3801 if (ctrl_c_interrupts)
3802 g_fCtrlCPressed = TRUE;
3803 return TRUE;
3804
3805 case CTRL_BREAK_EVENT:
3806 g_fCBrkPressed = TRUE;
3807 return TRUE;
3808
3809 /* fatal events: shut down gracefully */
3810 case CTRL_CLOSE_EVENT:
3811 case CTRL_LOGOFF_EVENT:
3812 case CTRL_SHUTDOWN_EVENT:
3813 windgoto((int)Rows - 1, 0);
3814 g_fForceExit = TRUE;
3815
Bram Moolenaar0fde2902008-03-16 13:54:13 +00003816 vim_snprintf((char *)IObuff, IOSIZE, _("Vim: Caught %s event\n"),
Bram Moolenaar071d4272004-06-13 20:20:40 +00003817 (dwCtrlType == CTRL_CLOSE_EVENT
3818 ? _("close")
3819 : dwCtrlType == CTRL_LOGOFF_EVENT
3820 ? _("logoff")
3821 : _("shutdown")));
3822#ifdef DEBUG
3823 OutputDebugString(IObuff);
3824#endif
3825
3826 preserve_exit(); /* output IObuff, preserve files and exit */
3827
3828 return TRUE; /* not reached */
3829
3830 default:
3831 return FALSE;
3832 }
3833}
3834
3835
3836/*
3837 * set the tty in (raw) ? "raw" : "cooked" mode
3838 */
3839 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003840mch_settmode(int tmode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003841{
3842 DWORD cmodein;
3843 DWORD cmodeout;
3844 BOOL bEnableHandler;
3845
3846 GetConsoleMode(g_hConIn, &cmodein);
3847 GetConsoleMode(g_hConOut, &cmodeout);
3848 if (tmode == TMODE_RAW)
3849 {
3850 cmodein &= ~(ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
3851 ENABLE_ECHO_INPUT);
3852#ifdef FEAT_MOUSE
3853 if (g_fMouseActive)
3854 cmodein |= ENABLE_MOUSE_INPUT;
3855#endif
3856 cmodeout &= ~(ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
3857 bEnableHandler = TRUE;
3858 }
3859 else /* cooked */
3860 {
3861 cmodein |= (ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
3862 ENABLE_ECHO_INPUT);
3863 cmodeout |= (ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
3864 bEnableHandler = FALSE;
3865 }
3866 SetConsoleMode(g_hConIn, cmodein);
3867 SetConsoleMode(g_hConOut, cmodeout);
3868 SetConsoleCtrlHandler(handler_routine, bEnableHandler);
3869
3870#ifdef MCH_WRITE_DUMP
3871 if (fdDump)
3872 {
3873 fprintf(fdDump, "mch_settmode(%s, in = %x, out = %x)\n",
3874 tmode == TMODE_RAW ? "raw" :
3875 tmode == TMODE_COOK ? "cooked" : "normal",
3876 cmodein, cmodeout);
3877 fflush(fdDump);
3878 }
3879#endif
3880}
3881
3882
3883/*
3884 * Get the size of the current window in `Rows' and `Columns'
3885 * Return OK when size could be determined, FAIL otherwise.
3886 */
3887 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003888mch_get_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003889{
3890 CONSOLE_SCREEN_BUFFER_INFO csbi;
3891
3892 if (!g_fTermcapMode && g_cbTermcap.IsValid)
3893 {
3894 /*
3895 * For some reason, we are trying to get the screen dimensions
3896 * even though we are not in termcap mode. The 'Rows' and 'Columns'
3897 * variables are really intended to mean the size of Vim screen
3898 * while in termcap mode.
3899 */
3900 Rows = g_cbTermcap.Info.dwSize.Y;
3901 Columns = g_cbTermcap.Info.dwSize.X;
3902 }
3903 else if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3904 {
3905 Rows = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
3906 Columns = csbi.srWindow.Right - csbi.srWindow.Left + 1;
3907 }
3908 else
3909 {
3910 Rows = 25;
3911 Columns = 80;
3912 }
3913 return OK;
3914}
3915
3916/*
3917 * Set a console window to `xSize' * `ySize'
3918 */
3919 static void
3920ResizeConBufAndWindow(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003921 HANDLE hConsole,
3922 int xSize,
3923 int ySize)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003924{
3925 CONSOLE_SCREEN_BUFFER_INFO csbi; /* hold current console buffer info */
3926 SMALL_RECT srWindowRect; /* hold the new console size */
3927 COORD coordScreen;
3928
3929#ifdef MCH_WRITE_DUMP
3930 if (fdDump)
3931 {
3932 fprintf(fdDump, "ResizeConBufAndWindow(%d, %d)\n", xSize, ySize);
3933 fflush(fdDump);
3934 }
3935#endif
3936
3937 /* get the largest size we can size the console window to */
3938 coordScreen = GetLargestConsoleWindowSize(hConsole);
3939
3940 /* define the new console window size and scroll position */
3941 srWindowRect.Left = srWindowRect.Top = (SHORT) 0;
3942 srWindowRect.Right = (SHORT) (min(xSize, coordScreen.X) - 1);
3943 srWindowRect.Bottom = (SHORT) (min(ySize, coordScreen.Y) - 1);
3944
3945 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3946 {
3947 int sx, sy;
3948
3949 sx = csbi.srWindow.Right - csbi.srWindow.Left + 1;
3950 sy = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
3951 if (sy < ySize || sx < xSize)
3952 {
3953 /*
3954 * Increasing number of lines/columns, do buffer first.
3955 * Use the maximal size in x and y direction.
3956 */
3957 if (sy < ySize)
3958 coordScreen.Y = ySize;
3959 else
3960 coordScreen.Y = sy;
3961 if (sx < xSize)
3962 coordScreen.X = xSize;
3963 else
3964 coordScreen.X = sx;
3965 SetConsoleScreenBufferSize(hConsole, coordScreen);
3966 }
3967 }
3968
3969 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &srWindowRect))
3970 {
3971#ifdef MCH_WRITE_DUMP
3972 if (fdDump)
3973 {
3974 fprintf(fdDump, "SetConsoleWindowInfo failed: %lx\n",
3975 GetLastError());
3976 fflush(fdDump);
3977 }
3978#endif
3979 }
3980
3981 /* define the new console buffer size */
3982 coordScreen.X = xSize;
3983 coordScreen.Y = ySize;
3984
3985 if (!SetConsoleScreenBufferSize(hConsole, coordScreen))
3986 {
3987#ifdef MCH_WRITE_DUMP
3988 if (fdDump)
3989 {
3990 fprintf(fdDump, "SetConsoleScreenBufferSize failed: %lx\n",
3991 GetLastError());
3992 fflush(fdDump);
3993 }
3994#endif
3995 }
3996}
3997
3998
3999/*
4000 * Set the console window to `Rows' * `Columns'
4001 */
4002 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004003mch_set_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004004{
4005 COORD coordScreen;
4006
4007 /* Don't change window size while still starting up */
4008 if (suppress_winsize != 0)
4009 {
4010 suppress_winsize = 2;
4011 return;
4012 }
4013
4014 if (term_console)
4015 {
4016 coordScreen = GetLargestConsoleWindowSize(g_hConOut);
4017
4018 /* Clamp Rows and Columns to reasonable values */
4019 if (Rows > coordScreen.Y)
4020 Rows = coordScreen.Y;
4021 if (Columns > coordScreen.X)
4022 Columns = coordScreen.X;
4023
4024 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
4025 }
4026}
4027
4028/*
4029 * Rows and/or Columns has changed.
4030 */
4031 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004032mch_new_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004033{
4034 set_scroll_region(0, 0, Columns - 1, Rows - 1);
4035}
4036
4037
4038/*
4039 * Called when started up, to set the winsize that was delayed.
4040 */
4041 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004042mch_set_winsize_now(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004043{
4044 if (suppress_winsize == 2)
4045 {
4046 suppress_winsize = 0;
4047 mch_set_shellsize();
4048 shell_resized();
4049 }
4050 suppress_winsize = 0;
4051}
4052#endif /* FEAT_GUI_W32 */
4053
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004054 static BOOL
4055vim_create_process(
Bram Moolenaar36c85b22013-12-12 20:25:44 +01004056 char *cmd,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004057 BOOL inherit_handles,
Bram Moolenaar3f1138e2014-01-05 13:29:26 +01004058 DWORD flags,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004059 STARTUPINFO *si,
4060 PROCESS_INFORMATION *pi)
4061{
4062# ifdef FEAT_MBYTE
4063 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4064 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004065 WCHAR *wcmd = enc_to_utf16((char_u *)cmd, NULL);
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004066
4067 if (wcmd != NULL)
4068 {
4069 BOOL ret;
4070 ret = CreateProcessW(
4071 NULL, /* Executable name */
4072 wcmd, /* Command to execute */
4073 NULL, /* Process security attributes */
4074 NULL, /* Thread security attributes */
4075 inherit_handles, /* Inherit handles */
4076 flags, /* Creation flags */
4077 NULL, /* Environment */
4078 NULL, /* Current directory */
Bram Moolenaar36c85b22013-12-12 20:25:44 +01004079 (LPSTARTUPINFOW)si, /* Startup information */
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004080 pi); /* Process information */
4081 vim_free(wcmd);
4082 return ret;
4083 }
4084 }
4085#endif
4086 return CreateProcess(
4087 NULL, /* Executable name */
4088 cmd, /* Command to execute */
4089 NULL, /* Process security attributes */
4090 NULL, /* Thread security attributes */
4091 inherit_handles, /* Inherit handles */
4092 flags, /* Creation flags */
4093 NULL, /* Environment */
4094 NULL, /* Current directory */
4095 si, /* Startup information */
4096 pi); /* Process information */
4097}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004098
4099
4100#if defined(FEAT_GUI_W32) || defined(PROTO)
4101
4102/*
4103 * Specialised version of system() for Win32 GUI mode.
4104 * This version proceeds as follows:
4105 * 1. Create a console window for use by the subprocess
4106 * 2. Run the subprocess (it gets the allocated console by default)
4107 * 3. Wait for the subprocess to terminate and get its exit code
4108 * 4. Prompt the user to press a key to close the console window
4109 */
4110 static int
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004111mch_system_classic(char *cmd, int options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004112{
4113 STARTUPINFO si;
4114 PROCESS_INFORMATION pi;
4115 DWORD ret = 0;
4116 HWND hwnd = GetFocus();
4117
4118 si.cb = sizeof(si);
4119 si.lpReserved = NULL;
4120 si.lpDesktop = NULL;
4121 si.lpTitle = NULL;
4122 si.dwFlags = STARTF_USESHOWWINDOW;
4123 /*
4124 * It's nicer to run a filter command in a minimized window, but in
4125 * Windows 95 this makes the command MUCH slower. We can't do it under
4126 * Win32s either as it stops the synchronous spawn workaround working.
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01004127 * Don't activate the window to keep focus on Vim.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004128 */
4129 if ((options & SHELL_DOOUT) && !mch_windows95() && !gui_is_win32s())
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01004130 si.wShowWindow = SW_SHOWMINNOACTIVE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004131 else
4132 si.wShowWindow = SW_SHOWNORMAL;
4133 si.cbReserved2 = 0;
4134 si.lpReserved2 = NULL;
4135
Bram Moolenaar942d6b22016-02-07 19:57:16 +01004136 /* There is a strange error on Windows 95 when using "c:\command.com".
Bram Moolenaar071d4272004-06-13 20:20:40 +00004137 * When the "c:\\" is left out it works OK...? */
4138 if (mch_windows95()
4139 && (STRNICMP(cmd, "c:/command.com", 14) == 0
4140 || STRNICMP(cmd, "c:\\command.com", 14) == 0))
4141 cmd += 3;
4142
4143 /* Now, run the command */
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004144 vim_create_process(cmd, FALSE,
4145 CREATE_DEFAULT_ERROR_MODE | CREATE_NEW_CONSOLE, &si, &pi);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004146
4147 /* Wait for the command to terminate before continuing */
4148 if (g_PlatformId != VER_PLATFORM_WIN32s)
4149 {
4150#ifdef FEAT_GUI
4151 int delay = 1;
4152
4153 /* Keep updating the window while waiting for the shell to finish. */
4154 for (;;)
4155 {
4156 MSG msg;
4157
Bram Moolenaar8c85fa32011-08-10 17:08:03 +02004158 if (pPeekMessage(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004159 {
4160 TranslateMessage(&msg);
Bram Moolenaar8c85fa32011-08-10 17:08:03 +02004161 pDispatchMessage(&msg);
Bram Moolenaare4195c52012-08-02 12:31:44 +02004162 delay = 1;
4163 continue;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004164 }
4165 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
4166 break;
4167
4168 /* We start waiting for a very short time and then increase it, so
4169 * that we respond quickly when the process is quick, and don't
4170 * consume too much overhead when it's slow. */
4171 if (delay < 50)
4172 delay += 10;
4173 }
4174#else
4175 WaitForSingleObject(pi.hProcess, INFINITE);
4176#endif
4177
4178 /* Get the command exit code */
4179 GetExitCodeProcess(pi.hProcess, &ret);
4180 }
4181 else
4182 {
4183 /*
4184 * This ugly code is the only quick way of performing
4185 * a synchronous spawn under Win32s. Yuk.
4186 */
4187 num_windows = 0;
4188 EnumWindows(win32ssynch_cb, 0);
4189 old_num_windows = num_windows;
4190 do
4191 {
4192 Sleep(1000);
4193 num_windows = 0;
4194 EnumWindows(win32ssynch_cb, 0);
4195 } while (num_windows == old_num_windows);
4196 ret = 0;
4197 }
4198
4199 /* Close the handles to the subprocess, so that it goes away */
4200 CloseHandle(pi.hThread);
4201 CloseHandle(pi.hProcess);
4202
4203 /* Try to get input focus back. Doesn't always work though. */
4204 PostMessage(hwnd, WM_SETFOCUS, 0, 0);
4205
4206 return ret;
4207}
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004208
4209/*
4210 * Thread launched by the gui to send the current buffer data to the
4211 * process. This way avoid to hang up vim totally if the children
4212 * process take a long time to process the lines.
4213 */
4214 static DWORD WINAPI
4215sub_process_writer(LPVOID param)
4216{
4217 HANDLE g_hChildStd_IN_Wr = param;
4218 linenr_T lnum = curbuf->b_op_start.lnum;
4219 DWORD len = 0;
4220 DWORD l;
4221 char_u *lp = ml_get(lnum);
4222 char_u *s;
4223 int written = 0;
4224
4225 for (;;)
4226 {
4227 l = (DWORD)STRLEN(lp + written);
4228 if (l == 0)
4229 len = 0;
4230 else if (lp[written] == NL)
4231 {
4232 /* NL -> NUL translation */
4233 WriteFile(g_hChildStd_IN_Wr, "", 1, &len, NULL);
4234 }
4235 else
4236 {
4237 s = vim_strchr(lp + written, NL);
4238 WriteFile(g_hChildStd_IN_Wr, (char *)lp + written,
4239 s == NULL ? l : (DWORD)(s - (lp + written)),
4240 &len, NULL);
4241 }
4242 if (len == (int)l)
4243 {
4244 /* Finished a line, add a NL, unless this line should not have
4245 * one. */
4246 if (lnum != curbuf->b_op_end.lnum
Bram Moolenaar34d72d42015-07-17 14:18:08 +02004247 || (!curbuf->b_p_bin
4248 && curbuf->b_p_fixeol)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004249 || (lnum != curbuf->b_no_eol_lnum
4250 && (lnum != curbuf->b_ml.ml_line_count
4251 || curbuf->b_p_eol)))
4252 {
Bram Moolenaaraf62ff32013-03-19 14:48:29 +01004253 WriteFile(g_hChildStd_IN_Wr, "\n", 1, (LPDWORD)&ignored, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004254 }
4255
4256 ++lnum;
4257 if (lnum > curbuf->b_op_end.lnum)
4258 break;
4259
4260 lp = ml_get(lnum);
4261 written = 0;
4262 }
4263 else if (len > 0)
4264 written += len;
4265 }
4266
4267 /* finished all the lines, close pipe */
4268 CloseHandle(g_hChildStd_IN_Wr);
4269 ExitThread(0);
4270}
4271
4272
4273# define BUFLEN 100 /* length for buffer, stolen from unix version */
4274
4275/*
4276 * This function read from the children's stdout and write the
4277 * data on screen or in the buffer accordingly.
4278 */
4279 static void
4280dump_pipe(int options,
4281 HANDLE g_hChildStd_OUT_Rd,
4282 garray_T *ga,
4283 char_u buffer[],
4284 DWORD *buffer_off)
4285{
4286 DWORD availableBytes = 0;
4287 DWORD i;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004288 int ret;
4289 DWORD len;
4290 DWORD toRead;
4291 int repeatCount;
4292
4293 /* we query the pipe to see if there is any data to read
4294 * to avoid to perform a blocking read */
4295 ret = PeekNamedPipe(g_hChildStd_OUT_Rd, /* pipe to query */
4296 NULL, /* optional buffer */
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02004297 0, /* buffer size */
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004298 NULL, /* number of read bytes */
4299 &availableBytes, /* available bytes total */
4300 NULL); /* byteLeft */
4301
4302 repeatCount = 0;
4303 /* We got real data in the pipe, read it */
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02004304 while (ret != 0 && availableBytes > 0)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004305 {
4306 repeatCount++;
4307 toRead =
4308# ifdef FEAT_MBYTE
4309 (DWORD)(BUFLEN - *buffer_off);
4310# else
4311 (DWORD)BUFLEN;
4312# endif
4313 toRead = availableBytes < toRead ? availableBytes : toRead;
4314 ReadFile(g_hChildStd_OUT_Rd, buffer
4315# ifdef FEAT_MBYTE
4316 + *buffer_off, toRead
4317# else
4318 , toRead
4319# endif
4320 , &len, NULL);
4321
4322 /* If we haven't read anything, there is a problem */
4323 if (len == 0)
4324 break;
4325
4326 availableBytes -= len;
4327
4328 if (options & SHELL_READ)
4329 {
4330 /* Do NUL -> NL translation, append NL separated
4331 * lines to the current buffer. */
4332 for (i = 0; i < len; ++i)
4333 {
4334 if (buffer[i] == NL)
4335 append_ga_line(ga);
4336 else if (buffer[i] == NUL)
4337 ga_append(ga, NL);
4338 else
4339 ga_append(ga, buffer[i]);
4340 }
4341 }
4342# ifdef FEAT_MBYTE
4343 else if (has_mbyte)
4344 {
4345 int l;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004346 int c;
4347 char_u *p;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004348
4349 len += *buffer_off;
4350 buffer[len] = NUL;
4351
4352 /* Check if the last character in buffer[] is
4353 * incomplete, keep these bytes for the next
4354 * round. */
4355 for (p = buffer; p < buffer + len; p += l)
4356 {
4357 l = mb_cptr2len(p);
4358 if (l == 0)
4359 l = 1; /* NUL byte? */
4360 else if (MB_BYTE2LEN(*p) != l)
4361 break;
4362 }
4363 if (p == buffer) /* no complete character */
4364 {
4365 /* avoid getting stuck at an illegal byte */
4366 if (len >= 12)
4367 ++p;
4368 else
4369 {
4370 *buffer_off = len;
4371 return;
4372 }
4373 }
4374 c = *p;
4375 *p = NUL;
4376 msg_puts(buffer);
4377 if (p < buffer + len)
4378 {
4379 *p = c;
4380 *buffer_off = (DWORD)((buffer + len) - p);
4381 mch_memmove(buffer, p, *buffer_off);
4382 return;
4383 }
4384 *buffer_off = 0;
4385 }
4386# endif /* FEAT_MBYTE */
4387 else
4388 {
4389 buffer[len] = NUL;
4390 msg_puts(buffer);
4391 }
4392
4393 windgoto(msg_row, msg_col);
4394 cursor_on();
4395 out_flush();
4396 }
4397}
4398
4399/*
4400 * Version of system to use for windows NT > 5.0 (Win2K), use pipe
4401 * for communication and doesn't open any new window.
4402 */
4403 static int
4404mch_system_piped(char *cmd, int options)
4405{
4406 STARTUPINFO si;
4407 PROCESS_INFORMATION pi;
4408 DWORD ret = 0;
4409
4410 HANDLE g_hChildStd_IN_Rd = NULL;
4411 HANDLE g_hChildStd_IN_Wr = NULL;
4412 HANDLE g_hChildStd_OUT_Rd = NULL;
4413 HANDLE g_hChildStd_OUT_Wr = NULL;
4414
4415 char_u buffer[BUFLEN + 1]; /* reading buffer + size */
4416 DWORD len;
4417
4418 /* buffer used to receive keys */
4419 char_u ta_buf[BUFLEN + 1]; /* TypeAHead */
4420 int ta_len = 0; /* valid bytes in ta_buf[] */
4421
4422 DWORD i;
4423 int c;
4424 int noread_cnt = 0;
4425 garray_T ga;
4426 int delay = 1;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004427 DWORD buffer_off = 0; /* valid bytes in buffer[] */
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004428 char *p = NULL;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004429
4430 SECURITY_ATTRIBUTES saAttr;
4431
4432 /* Set the bInheritHandle flag so pipe handles are inherited. */
4433 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
4434 saAttr.bInheritHandle = TRUE;
4435 saAttr.lpSecurityDescriptor = NULL;
4436
4437 if ( ! CreatePipe(&g_hChildStd_OUT_Rd, &g_hChildStd_OUT_Wr, &saAttr, 0)
4438 /* Ensure the read handle to the pipe for STDOUT is not inherited. */
4439 || ! pSetHandleInformation(g_hChildStd_OUT_Rd, HANDLE_FLAG_INHERIT, 0)
4440 /* Create a pipe for the child process's STDIN. */
4441 || ! CreatePipe(&g_hChildStd_IN_Rd, &g_hChildStd_IN_Wr, &saAttr, 0)
4442 /* Ensure the write handle to the pipe for STDIN is not inherited. */
4443 || ! pSetHandleInformation(g_hChildStd_IN_Wr, HANDLE_FLAG_INHERIT, 0) )
4444 {
4445 CloseHandle(g_hChildStd_IN_Rd);
4446 CloseHandle(g_hChildStd_IN_Wr);
4447 CloseHandle(g_hChildStd_OUT_Rd);
4448 CloseHandle(g_hChildStd_OUT_Wr);
4449 MSG_PUTS(_("\nCannot create pipes\n"));
4450 }
4451
4452 si.cb = sizeof(si);
4453 si.lpReserved = NULL;
4454 si.lpDesktop = NULL;
4455 si.lpTitle = NULL;
4456 si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
4457
4458 /* set-up our file redirection */
4459 si.hStdError = g_hChildStd_OUT_Wr;
4460 si.hStdOutput = g_hChildStd_OUT_Wr;
4461 si.hStdInput = g_hChildStd_IN_Rd;
4462 si.wShowWindow = SW_HIDE;
4463 si.cbReserved2 = 0;
4464 si.lpReserved2 = NULL;
4465
4466 if (options & SHELL_READ)
4467 ga_init2(&ga, 1, BUFLEN);
4468
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004469 if (cmd != NULL)
4470 {
4471 p = (char *)vim_strsave((char_u *)cmd);
4472 if (p != NULL)
4473 unescape_shellxquote((char_u *)p, p_sxe);
4474 else
4475 p = cmd;
4476 }
4477
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004478 /* Now, run the command.
4479 * About "Inherit handles" being TRUE: this command can be litigious,
4480 * handle inheritance was deactivated for pending temp file, but, if we
4481 * deactivate it, the pipes don't work for some reason. */
4482 vim_create_process(p, TRUE, CREATE_DEFAULT_ERROR_MODE, &si, &pi);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004483
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004484 if (p != cmd)
4485 vim_free(p);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004486
4487 /* Close our unused side of the pipes */
4488 CloseHandle(g_hChildStd_IN_Rd);
4489 CloseHandle(g_hChildStd_OUT_Wr);
4490
4491 if (options & SHELL_WRITE)
4492 {
4493 HANDLE thread =
4494 CreateThread(NULL, /* security attributes */
4495 0, /* default stack size */
4496 sub_process_writer, /* function to be executed */
4497 g_hChildStd_IN_Wr, /* parameter */
4498 0, /* creation flag, start immediately */
4499 NULL); /* we don't care about thread id */
4500 CloseHandle(thread);
4501 g_hChildStd_IN_Wr = NULL;
4502 }
4503
4504 /* Keep updating the window while waiting for the shell to finish. */
4505 for (;;)
4506 {
4507 MSG msg;
4508
Bram Moolenaar175d0702013-12-11 18:36:33 +01004509 if (pPeekMessage(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004510 {
4511 TranslateMessage(&msg);
Bram Moolenaar175d0702013-12-11 18:36:33 +01004512 pDispatchMessage(&msg);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004513 }
4514
4515 /* write pipe information in the window */
4516 if ((options & (SHELL_READ|SHELL_WRITE))
4517# ifdef FEAT_GUI
4518 || gui.in_use
4519# endif
4520 )
4521 {
4522 len = 0;
4523 if (!(options & SHELL_EXPAND)
4524 && ((options &
4525 (SHELL_READ|SHELL_WRITE|SHELL_COOKED))
4526 != (SHELL_READ|SHELL_WRITE|SHELL_COOKED)
4527# ifdef FEAT_GUI
4528 || gui.in_use
4529# endif
4530 )
4531 && (ta_len > 0 || noread_cnt > 4))
4532 {
4533 if (ta_len == 0)
4534 {
4535 /* Get extra characters when we don't have any. Reset the
4536 * counter and timer. */
4537 noread_cnt = 0;
4538# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
4539 gettimeofday(&start_tv, NULL);
4540# endif
4541 len = ui_inchar(ta_buf, BUFLEN, 10L, 0);
4542 }
4543 if (ta_len > 0 || len > 0)
4544 {
4545 /*
4546 * For pipes: Check for CTRL-C: send interrupt signal to
4547 * child. Check for CTRL-D: EOF, close pipe to child.
4548 */
4549 if (len == 1 && cmd != NULL)
4550 {
4551 if (ta_buf[ta_len] == Ctrl_C)
4552 {
4553 /* Learn what exit code is expected, for
4554 * now put 9 as SIGKILL */
4555 TerminateProcess(pi.hProcess, 9);
4556 }
4557 if (ta_buf[ta_len] == Ctrl_D)
4558 {
4559 CloseHandle(g_hChildStd_IN_Wr);
4560 g_hChildStd_IN_Wr = NULL;
4561 }
4562 }
4563
4564 /* replace K_BS by <BS> and K_DEL by <DEL> */
4565 for (i = ta_len; i < ta_len + len; ++i)
4566 {
4567 if (ta_buf[i] == CSI && len - i > 2)
4568 {
4569 c = TERMCAP2KEY(ta_buf[i + 1], ta_buf[i + 2]);
4570 if (c == K_DEL || c == K_KDEL || c == K_BS)
4571 {
4572 mch_memmove(ta_buf + i + 1, ta_buf + i + 3,
4573 (size_t)(len - i - 2));
4574 if (c == K_DEL || c == K_KDEL)
4575 ta_buf[i] = DEL;
4576 else
4577 ta_buf[i] = Ctrl_H;
4578 len -= 2;
4579 }
4580 }
4581 else if (ta_buf[i] == '\r')
4582 ta_buf[i] = '\n';
4583# ifdef FEAT_MBYTE
4584 if (has_mbyte)
4585 i += (*mb_ptr2len_len)(ta_buf + i,
4586 ta_len + len - i) - 1;
4587# endif
4588 }
4589
4590 /*
4591 * For pipes: echo the typed characters. For a pty this
4592 * does not seem to work.
4593 */
4594 for (i = ta_len; i < ta_len + len; ++i)
4595 {
4596 if (ta_buf[i] == '\n' || ta_buf[i] == '\b')
4597 msg_putchar(ta_buf[i]);
4598# ifdef FEAT_MBYTE
4599 else if (has_mbyte)
4600 {
4601 int l = (*mb_ptr2len)(ta_buf + i);
4602
4603 msg_outtrans_len(ta_buf + i, l);
4604 i += l - 1;
4605 }
4606# endif
4607 else
4608 msg_outtrans_len(ta_buf + i, 1);
4609 }
4610 windgoto(msg_row, msg_col);
4611 out_flush();
4612
4613 ta_len += len;
4614
4615 /*
4616 * Write the characters to the child, unless EOF has been
4617 * typed for pipes. Write one character at a time, to
4618 * avoid losing too much typeahead. When writing buffer
4619 * lines, drop the typed characters (only check for
4620 * CTRL-C).
4621 */
4622 if (options & SHELL_WRITE)
4623 ta_len = 0;
4624 else if (g_hChildStd_IN_Wr != NULL)
4625 {
4626 WriteFile(g_hChildStd_IN_Wr, (char*)ta_buf,
4627 1, &len, NULL);
4628 // if we are typing in, we want to keep things reactive
4629 delay = 1;
4630 if (len > 0)
4631 {
4632 ta_len -= len;
4633 mch_memmove(ta_buf, ta_buf + len, ta_len);
4634 }
4635 }
4636 }
4637 }
4638 }
4639
4640 if (ta_len)
4641 ui_inchar_undo(ta_buf, ta_len);
4642
4643 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
4644 {
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 break;
4647 }
4648
4649 ++noread_cnt;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004650 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004651
4652 /* We start waiting for a very short time and then increase it, so
4653 * that we respond quickly when the process is quick, and don't
4654 * consume too much overhead when it's slow. */
4655 if (delay < 50)
4656 delay += 10;
4657 }
4658
4659 /* Close the pipe */
4660 CloseHandle(g_hChildStd_OUT_Rd);
4661 if (g_hChildStd_IN_Wr != NULL)
4662 CloseHandle(g_hChildStd_IN_Wr);
4663
4664 WaitForSingleObject(pi.hProcess, INFINITE);
4665
4666 /* Get the command exit code */
4667 GetExitCodeProcess(pi.hProcess, &ret);
4668
4669 if (options & SHELL_READ)
4670 {
4671 if (ga.ga_len > 0)
4672 {
4673 append_ga_line(&ga);
4674 /* remember that the NL was missing */
4675 curbuf->b_no_eol_lnum = curwin->w_cursor.lnum;
4676 }
4677 else
4678 curbuf->b_no_eol_lnum = 0;
4679 ga_clear(&ga);
4680 }
4681
4682 /* Close the handles to the subprocess, so that it goes away */
4683 CloseHandle(pi.hThread);
4684 CloseHandle(pi.hProcess);
4685
4686 return ret;
4687}
4688
4689 static int
4690mch_system(char *cmd, int options)
4691{
4692 /* if we can pipe and the shelltemp option is off */
4693 if (allowPiping && !p_stmp)
4694 return mch_system_piped(cmd, options);
4695 else
4696 return mch_system_classic(cmd, options);
4697}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004698#else
4699
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004700# ifdef FEAT_MBYTE
4701 static int
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01004702mch_system(char *cmd, int options)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004703{
4704 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4705 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004706 WCHAR *wcmd = enc_to_utf16((char_u *)cmd, NULL);
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004707 if (wcmd != NULL)
4708 {
4709 int ret = _wsystem(wcmd);
4710 vim_free(wcmd);
4711 return ret;
4712 }
4713 }
4714 return system(cmd);
4715}
4716# else
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01004717# define mch_system(c, o) system(c)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004718# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004719
4720#endif
4721
4722/*
4723 * Either execute a command by calling the shell or start a new shell
4724 */
4725 int
4726mch_call_shell(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004727 char_u *cmd,
4728 int options) /* SHELL_*, see vim.h */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004729{
4730 int x = 0;
4731 int tmode = cur_tmode;
4732#ifdef FEAT_TITLE
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004733 char szShellTitle[512];
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004734# ifdef FEAT_MBYTE
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004735 int did_set_title = FALSE;
4736
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004737 /* Change the title to reflect that we are in a subshell. */
4738 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4739 {
4740 WCHAR szShellTitle[512];
4741
4742 if (GetConsoleTitleW(szShellTitle,
4743 sizeof(szShellTitle)/sizeof(WCHAR) - 4) > 0)
4744 {
4745 if (cmd == NULL)
4746 wcscat(szShellTitle, L" :sh");
4747 else
4748 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004749 WCHAR *wn = enc_to_utf16((char_u *)cmd, NULL);
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004750
4751 if (wn != NULL)
4752 {
4753 wcscat(szShellTitle, L" - !");
4754 if ((wcslen(szShellTitle) + wcslen(wn) <
4755 sizeof(szShellTitle)/sizeof(WCHAR)))
4756 wcscat(szShellTitle, wn);
4757 SetConsoleTitleW(szShellTitle);
4758 vim_free(wn);
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004759 did_set_title = TRUE;
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004760 }
4761 }
4762 }
4763 }
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004764 if (!did_set_title)
4765# endif
4766 /* Change the title to reflect that we are in a subshell. */
4767 if (GetConsoleTitle(szShellTitle, sizeof(szShellTitle) - 4) > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004768 {
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004769 if (cmd == NULL)
4770 strcat(szShellTitle, " :sh");
4771 else
4772 {
4773 strcat(szShellTitle, " - !");
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004774 if ((strlen(szShellTitle) + strlen((char *)cmd)
4775 < sizeof(szShellTitle)))
4776 strcat(szShellTitle, (char *)cmd);
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004777 }
4778 SetConsoleTitle(szShellTitle);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004779 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004780#endif
4781
4782 out_flush();
4783
4784#ifdef MCH_WRITE_DUMP
4785 if (fdDump)
4786 {
4787 fprintf(fdDump, "mch_call_shell(\"%s\", %d)\n", cmd, options);
4788 fflush(fdDump);
4789 }
4790#endif
4791
4792 /*
4793 * Catch all deadly signals while running the external command, because a
4794 * CTRL-C, Ctrl-Break or illegal instruction might otherwise kill us.
4795 */
4796 signal(SIGINT, SIG_IGN);
4797#if defined(__GNUC__) && !defined(__MINGW32__)
4798 signal(SIGKILL, SIG_IGN);
4799#else
4800 signal(SIGBREAK, SIG_IGN);
4801#endif
4802 signal(SIGILL, SIG_IGN);
4803 signal(SIGFPE, SIG_IGN);
4804 signal(SIGSEGV, SIG_IGN);
4805 signal(SIGTERM, SIG_IGN);
4806 signal(SIGABRT, SIG_IGN);
4807
4808 if (options & SHELL_COOKED)
4809 settmode(TMODE_COOK); /* set to normal mode */
4810
4811 if (cmd == NULL)
4812 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004813 x = mch_system((char *)p_sh, options);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004814 }
4815 else
4816 {
4817 /* we use "command" or "cmd" to start the shell; slow but easy */
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004818 char_u *newcmd = NULL;
4819 char_u *cmdbase = cmd;
4820 long_u cmdlen;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004821
4822 /* Skip a leading ", ( and "(. */
4823 if (*cmdbase == '"' )
4824 ++cmdbase;
4825 if (*cmdbase == '(')
4826 ++cmdbase;
4827
4828 if ((STRNICMP(cmdbase, "start", 5) == 0) && vim_iswhite(cmdbase[5]))
4829 {
4830 STARTUPINFO si;
4831 PROCESS_INFORMATION pi;
4832 DWORD flags = CREATE_NEW_CONSOLE;
4833 char_u *p;
4834
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01004835 ZeroMemory(&si, sizeof(si));
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004836 si.cb = sizeof(si);
4837 si.lpReserved = NULL;
4838 si.lpDesktop = NULL;
4839 si.lpTitle = NULL;
4840 si.dwFlags = 0;
4841 si.cbReserved2 = 0;
4842 si.lpReserved2 = NULL;
4843
4844 cmdbase = skipwhite(cmdbase + 5);
4845 if ((STRNICMP(cmdbase, "/min", 4) == 0)
4846 && vim_iswhite(cmdbase[4]))
4847 {
4848 cmdbase = skipwhite(cmdbase + 4);
4849 si.dwFlags = STARTF_USESHOWWINDOW;
4850 si.wShowWindow = SW_SHOWMINNOACTIVE;
4851 }
4852 else if ((STRNICMP(cmdbase, "/b", 2) == 0)
4853 && vim_iswhite(cmdbase[2]))
4854 {
4855 cmdbase = skipwhite(cmdbase + 2);
4856 flags = CREATE_NO_WINDOW;
4857 si.dwFlags = STARTF_USESTDHANDLES;
4858 si.hStdInput = CreateFile("\\\\.\\NUL", // File name
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004859 GENERIC_READ, // Access flags
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004860 0, // Share flags
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004861 NULL, // Security att.
4862 OPEN_EXISTING, // Open flags
4863 FILE_ATTRIBUTE_NORMAL, // File att.
4864 NULL); // Temp file
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004865 si.hStdOutput = si.hStdInput;
4866 si.hStdError = si.hStdInput;
4867 }
4868
4869 /* Remove a trailing ", ) and )" if they have a match
4870 * at the start of the command. */
4871 if (cmdbase > cmd)
4872 {
4873 p = cmdbase + STRLEN(cmdbase);
4874 if (p > cmdbase && p[-1] == '"' && *cmd == '"')
4875 *--p = NUL;
4876 if (p > cmdbase && p[-1] == ')'
4877 && (*cmd =='(' || cmd[1] == '('))
4878 *--p = NUL;
4879 }
4880
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004881 newcmd = cmdbase;
4882 unescape_shellxquote(cmdbase, p_sxe);
4883
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004884 /*
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004885 * If creating new console, arguments are passed to the
4886 * 'cmd.exe' as-is. If it's not, arguments are not treated
4887 * correctly for current 'cmd.exe'. So unescape characters in
4888 * shellxescape except '|' for avoiding to be treated as
4889 * argument to them. Pass the arguments to sub-shell.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004890 */
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004891 if (flags != CREATE_NEW_CONSOLE)
4892 {
4893 char_u *subcmd;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004894 char_u *cmd_shell = mch_getenv("COMSPEC");
4895
4896 if (cmd_shell == NULL || *cmd_shell == NUL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004897 cmd_shell = (char_u *)default_shell();
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004898
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004899 subcmd = vim_strsave_escaped_ext(cmdbase,
4900 (char_u *)"|", '^', FALSE);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004901 if (subcmd != NULL)
4902 {
4903 /* make "cmd.exe /c arguments" */
4904 cmdlen = STRLEN(cmd_shell) + STRLEN(subcmd) + 5;
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004905 newcmd = lalloc(cmdlen, TRUE);
4906 if (newcmd != NULL)
4907 vim_snprintf((char *)newcmd, cmdlen, "%s /c %s",
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004908 cmd_shell, subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004909 else
4910 newcmd = cmdbase;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004911 vim_free(subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004912 }
4913 }
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004914
4915 /*
4916 * Now, start the command as a process, so that it doesn't
4917 * inherit our handles which causes unpleasant dangling swap
4918 * files if we exit before the spawned process
4919 */
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004920 if (vim_create_process((char *)newcmd, FALSE, flags, &si, &pi))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004921 x = 0;
4922 else
4923 {
4924 x = -1;
4925#ifdef FEAT_GUI_W32
4926 EMSG(_("E371: Command not found"));
4927#endif
4928 }
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004929
4930 if (newcmd != cmdbase)
4931 vim_free(newcmd);
4932
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01004933 if (si.dwFlags == STARTF_USESTDHANDLES && si.hStdInput != NULL)
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004934 {
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01004935 /* Close the handle to \\.\NUL created above. */
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004936 CloseHandle(si.hStdInput);
4937 }
4938 /* Close the handles to the subprocess, so that it goes away */
4939 CloseHandle(pi.hThread);
4940 CloseHandle(pi.hProcess);
4941 }
4942 else
4943 {
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004944 cmdlen = (
Bram Moolenaar071d4272004-06-13 20:20:40 +00004945#ifdef FEAT_GUI_W32
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004946 (allowPiping && !p_stmp ? 0 : STRLEN(vimrun_path)) +
Bram Moolenaar071d4272004-06-13 20:20:40 +00004947#endif
Bram Moolenaar0fde2902008-03-16 13:54:13 +00004948 STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10);
4949
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004950 newcmd = lalloc(cmdlen, TRUE);
4951 if (newcmd != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004952 {
4953#if defined(FEAT_GUI_W32)
4954 if (need_vimrun_warning)
4955 {
4956 MessageBox(NULL,
4957 _("VIMRUN.EXE not found in your $PATH.\n"
4958 "External commands will not pause after completion.\n"
4959 "See :help win32-vimrun for more information."),
4960 _("Vim Warning"),
4961 MB_ICONWARNING);
4962 need_vimrun_warning = FALSE;
4963 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004964 if (!s_dont_use_vimrun && (!allowPiping || p_stmp))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004965 /* Use vimrun to execute the command. It opens a console
4966 * window, which can be closed without killing Vim. */
Bram Moolenaarcc448b32010-07-14 16:52:17 +02004967 vim_snprintf((char *)newcmd, cmdlen, "%s%s%s %s %s",
Bram Moolenaar071d4272004-06-13 20:20:40 +00004968 vimrun_path,
4969 (msg_silent != 0 || (options & SHELL_DOOUT))
4970 ? "-s " : "",
4971 p_sh, p_shcf, cmd);
4972 else
4973#endif
Bram Moolenaarcc448b32010-07-14 16:52:17 +02004974 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s",
Bram Moolenaar0fde2902008-03-16 13:54:13 +00004975 p_sh, p_shcf, cmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004976 x = mch_system((char *)newcmd, options);
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004977 vim_free(newcmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004978 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004979 }
4980 }
4981
4982 if (tmode == TMODE_RAW)
4983 settmode(TMODE_RAW); /* set to raw mode */
4984
4985 /* Print the return value, unless "vimrun" was used. */
4986 if (x != 0 && !(options & SHELL_SILENT) && !emsg_silent
4987#if defined(FEAT_GUI_W32)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004988 && ((options & SHELL_DOOUT) || s_dont_use_vimrun
4989 || (allowPiping && !p_stmp))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004990#endif
4991 )
4992 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004993 smsg((char_u *)_("shell returned %d"), x);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004994 msg_putchar('\n');
4995 }
4996#ifdef FEAT_TITLE
4997 resettitle();
4998#endif
4999
5000 signal(SIGINT, SIG_DFL);
5001#if defined(__GNUC__) && !defined(__MINGW32__)
5002 signal(SIGKILL, SIG_DFL);
5003#else
5004 signal(SIGBREAK, SIG_DFL);
5005#endif
5006 signal(SIGILL, SIG_DFL);
5007 signal(SIGFPE, SIG_DFL);
5008 signal(SIGSEGV, SIG_DFL);
5009 signal(SIGTERM, SIG_DFL);
5010 signal(SIGABRT, SIG_DFL);
5011
5012 return x;
5013}
5014
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005015#if defined(FEAT_JOB) || defined(PROTO)
5016 void
Bram Moolenaar9a6e33a2016-02-16 19:25:12 +01005017mch_start_job(char *cmd, job_T *job, jobopt_T *options)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005018{
5019 STARTUPINFO si;
5020 PROCESS_INFORMATION pi;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005021 HANDLE jo;
Bram Moolenaar16eb4f82016-02-14 23:02:34 +01005022# ifdef FEAT_CHANNEL
5023 channel_T *channel;
Bram Moolenaard8070362016-02-15 21:56:54 +01005024 HANDLE ifd[2];
5025 HANDLE ofd[2];
5026 HANDLE efd[2];
5027 SECURITY_ATTRIBUTES saAttr;
5028
5029 ifd[0] = INVALID_HANDLE_VALUE;
5030 ifd[1] = INVALID_HANDLE_VALUE;
5031 ofd[0] = INVALID_HANDLE_VALUE;
5032 ofd[1] = INVALID_HANDLE_VALUE;
5033 efd[0] = INVALID_HANDLE_VALUE;
5034 efd[1] = INVALID_HANDLE_VALUE;
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005035
5036 channel = add_channel();
5037 if (channel == NULL)
5038 return;
Bram Moolenaar16eb4f82016-02-14 23:02:34 +01005039# endif
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005040
Bram Moolenaar76467df2016-02-12 19:30:26 +01005041 jo = CreateJobObject(NULL, NULL);
5042 if (jo == NULL)
5043 {
5044 job->jv_status = JOB_FAILED;
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005045 goto failed;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005046 }
5047
5048 ZeroMemory(&pi, sizeof(pi));
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005049 ZeroMemory(&si, sizeof(si));
5050 si.cb = sizeof(si);
Bram Moolenaard8070362016-02-15 21:56:54 +01005051 si.dwFlags |= STARTF_USESHOWWINDOW;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005052 si.wShowWindow = SW_HIDE;
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005053
Bram Moolenaar5d54a042016-02-16 16:39:51 +01005054# ifdef FEAT_CHANNEL
Bram Moolenaard8070362016-02-15 21:56:54 +01005055 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
5056 saAttr.bInheritHandle = TRUE;
5057 saAttr.lpSecurityDescriptor = NULL;
5058 if (!CreatePipe(&ifd[0], &ifd[1], &saAttr, 0)
5059 || !pSetHandleInformation(ifd[1], HANDLE_FLAG_INHERIT, 0)
5060 || !CreatePipe(&ofd[0], &ofd[1], &saAttr, 0)
5061 || !pSetHandleInformation(ofd[0], HANDLE_FLAG_INHERIT, 0)
5062 || !CreatePipe(&efd[0], &efd[1], &saAttr, 0)
5063 || !pSetHandleInformation(efd[0], HANDLE_FLAG_INHERIT, 0))
5064 goto failed;
5065 si.dwFlags |= STARTF_USESTDHANDLES;
5066 si.hStdInput = ifd[0];
5067 si.hStdOutput = ofd[1];
5068 si.hStdError = efd[1];
Bram Moolenaar5d54a042016-02-16 16:39:51 +01005069# endif
Bram Moolenaard8070362016-02-15 21:56:54 +01005070
5071 if (!vim_create_process(cmd, TRUE,
Bram Moolenaar76467df2016-02-12 19:30:26 +01005072 CREATE_SUSPENDED |
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005073 CREATE_DEFAULT_ERROR_MODE |
5074 CREATE_NEW_PROCESS_GROUP |
Bram Moolenaar76467df2016-02-12 19:30:26 +01005075 CREATE_NEW_CONSOLE,
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005076 &si, &pi))
Bram Moolenaar76467df2016-02-12 19:30:26 +01005077 {
5078 CloseHandle(jo);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005079 job->jv_status = JOB_FAILED;
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005080 goto failed;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005081 }
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005082
5083 if (!AssignProcessToJobObject(jo, pi.hProcess))
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005084 {
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005085 /* if failing, switch the way to terminate
5086 * process with TerminateProcess. */
5087 CloseHandle(jo);
5088 jo = NULL;
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005089 }
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005090 ResumeThread(pi.hThread);
5091 CloseHandle(job->jv_proc_info.hThread);
5092 job->jv_proc_info = pi;
5093 job->jv_job_object = jo;
5094 job->jv_status = JOB_STARTED;
5095
Bram Moolenaar5d54a042016-02-16 16:39:51 +01005096# ifdef FEAT_CHANNEL
Bram Moolenaard8070362016-02-15 21:56:54 +01005097 CloseHandle(ifd[0]);
5098 CloseHandle(ofd[1]);
5099 CloseHandle(efd[1]);
5100
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005101 job->jv_channel = channel;
Bram Moolenaard8070362016-02-15 21:56:54 +01005102 channel_set_pipes(channel, (sock_T)ifd[1], (sock_T)ofd[0], (sock_T)efd[0]);
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005103 channel_set_job(channel, job);
Bram Moolenaar910b8aa2016-02-16 21:03:07 +01005104 channel_set_options(channel, options);
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005105
Bram Moolenaar16eb4f82016-02-14 23:02:34 +01005106# ifdef FEAT_GUI
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005107 channel_gui_register(channel);
Bram Moolenaar16eb4f82016-02-14 23:02:34 +01005108# endif
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005109# endif
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005110 return;
5111
5112failed:
Bram Moolenaar16eb4f82016-02-14 23:02:34 +01005113# ifdef FEAT_CHANNEL
Bram Moolenaard8070362016-02-15 21:56:54 +01005114 CloseHandle(ifd[0]);
5115 CloseHandle(ofd[0]);
5116 CloseHandle(efd[0]);
5117 CloseHandle(ifd[1]);
5118 CloseHandle(ofd[1]);
5119 CloseHandle(efd[1]);
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005120 channel_free(channel);
Bram Moolenaar71b0f7b2016-02-15 12:44:20 +01005121# else
5122 ; /* make compiler happy */
Bram Moolenaar16eb4f82016-02-14 23:02:34 +01005123# endif
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005124}
5125
5126 char *
5127mch_job_status(job_T *job)
5128{
5129 DWORD dwExitCode = 0;
5130
Bram Moolenaar76467df2016-02-12 19:30:26 +01005131 if (!GetExitCodeProcess(job->jv_proc_info.hProcess, &dwExitCode)
5132 || dwExitCode != STILL_ACTIVE)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005133 {
Bram Moolenaar76467df2016-02-12 19:30:26 +01005134 job->jv_status = JOB_ENDED;
Bram Moolenaareab089d2016-02-21 19:32:02 +01005135 job->jv_exitval = (int)dwExitCode;
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005136 return "dead";
5137 }
5138 return "run";
5139}
5140
5141 int
5142mch_stop_job(job_T *job, char_u *how)
5143{
Bram Moolenaar76467df2016-02-12 19:30:26 +01005144 int ret = 0;
5145 int ctrl_c = STRCMP(how, "int") == 0;
5146
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005147 if (STRCMP(how, "kill") == 0)
Bram Moolenaar76467df2016-02-12 19:30:26 +01005148 {
5149 if (job->jv_job_object != NULL)
5150 return TerminateJobObject(job->jv_job_object, 0) ? OK : FAIL;
5151 else
5152 return TerminateProcess(job->jv_proc_info.hProcess, 0) ? OK : FAIL;
5153 }
5154
5155 if (!AttachConsole(job->jv_proc_info.dwProcessId))
5156 return FAIL;
5157 ret = GenerateConsoleCtrlEvent(
5158 ctrl_c ? CTRL_C_EVENT : CTRL_BREAK_EVENT,
5159 job->jv_proc_info.dwProcessId)
5160 ? OK : FAIL;
5161 FreeConsole();
5162 return ret;
5163}
5164
5165/*
5166 * Clear the data related to "job".
5167 */
5168 void
5169mch_clear_job(job_T *job)
5170{
5171 if (job->jv_status != JOB_FAILED)
5172 {
5173 if (job->jv_job_object != NULL)
5174 CloseHandle(job->jv_job_object);
5175 CloseHandle(job->jv_proc_info.hProcess);
5176 }
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005177}
5178#endif
5179
Bram Moolenaar071d4272004-06-13 20:20:40 +00005180
5181#ifndef FEAT_GUI_W32
5182
5183/*
5184 * Start termcap mode
5185 */
5186 static void
5187termcap_mode_start(void)
5188{
5189 DWORD cmodein;
5190
5191 if (g_fTermcapMode)
5192 return;
5193
5194 SaveConsoleBuffer(&g_cbNonTermcap);
5195
5196 if (g_cbTermcap.IsValid)
5197 {
5198 /*
5199 * We've been in termcap mode before. Restore certain screen
5200 * characteristics, including the buffer size and the window
5201 * size. Since we will be redrawing the screen, we don't need
5202 * to restore the actual contents of the buffer.
5203 */
5204 RestoreConsoleBuffer(&g_cbTermcap, FALSE);
5205 SetConsoleWindowInfo(g_hConOut, TRUE, &g_cbTermcap.Info.srWindow);
5206 Rows = g_cbTermcap.Info.dwSize.Y;
5207 Columns = g_cbTermcap.Info.dwSize.X;
5208 }
5209 else
5210 {
5211 /*
5212 * This is our first time entering termcap mode. Clear the console
5213 * screen buffer, and resize the buffer to match the current window
5214 * size. We will use this as the size of our editing environment.
5215 */
5216 ClearConsoleBuffer(g_attrCurrent);
5217 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
5218 }
5219
5220#ifdef FEAT_TITLE
5221 resettitle();
5222#endif
5223
5224 GetConsoleMode(g_hConIn, &cmodein);
5225#ifdef FEAT_MOUSE
5226 if (g_fMouseActive)
5227 cmodein |= ENABLE_MOUSE_INPUT;
5228 else
5229 cmodein &= ~ENABLE_MOUSE_INPUT;
5230#endif
5231 cmodein |= ENABLE_WINDOW_INPUT;
5232 SetConsoleMode(g_hConIn, cmodein);
5233
5234 redraw_later_clear();
5235 g_fTermcapMode = TRUE;
5236}
5237
5238
5239/*
5240 * End termcap mode
5241 */
5242 static void
5243termcap_mode_end(void)
5244{
5245 DWORD cmodein;
5246 ConsoleBuffer *cb;
5247 COORD coord;
5248 DWORD dwDummy;
5249
5250 if (!g_fTermcapMode)
5251 return;
5252
5253 SaveConsoleBuffer(&g_cbTermcap);
5254
5255 GetConsoleMode(g_hConIn, &cmodein);
5256 cmodein &= ~(ENABLE_MOUSE_INPUT | ENABLE_WINDOW_INPUT);
5257 SetConsoleMode(g_hConIn, cmodein);
5258
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01005259#ifdef FEAT_RESTORE_ORIG_SCREEN
5260 cb = exiting ? &g_cbOrig : &g_cbNonTermcap;
5261#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00005262 cb = &g_cbNonTermcap;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01005263#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005264 RestoreConsoleBuffer(cb, p_rs);
5265 SetConsoleCursorInfo(g_hConOut, &g_cci);
5266
5267 if (p_rs || exiting)
5268 {
5269 /*
5270 * Clear anything that happens to be on the current line.
5271 */
5272 coord.X = 0;
5273 coord.Y = (SHORT) (p_rs ? cb->Info.dwCursorPosition.Y : (Rows - 1));
5274 FillConsoleOutputCharacter(g_hConOut, ' ',
5275 cb->Info.dwSize.X, coord, &dwDummy);
5276 /*
5277 * The following is just for aesthetics. If we are exiting without
5278 * restoring the screen, then we want to have a prompt string
5279 * appear at the bottom line. However, the command interpreter
5280 * seems to always advance the cursor one line before displaying
5281 * the prompt string, which causes the screen to scroll. To
5282 * counter this, move the cursor up one line before exiting.
5283 */
5284 if (exiting && !p_rs)
5285 coord.Y--;
5286 /*
5287 * Position the cursor at the leftmost column of the desired row.
5288 */
5289 SetConsoleCursorPosition(g_hConOut, coord);
5290 }
5291
5292 g_fTermcapMode = FALSE;
5293}
5294#endif /* FEAT_GUI_W32 */
5295
5296
5297#ifdef FEAT_GUI_W32
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00005298/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00005299 void
5300mch_write(
5301 char_u *s,
5302 int len)
5303{
5304 /* never used */
5305}
5306
5307#else
5308
5309/*
5310 * clear `n' chars, starting from `coord'
5311 */
5312 static void
5313clear_chars(
5314 COORD coord,
5315 DWORD n)
5316{
5317 DWORD dwDummy;
5318
5319 FillConsoleOutputCharacter(g_hConOut, ' ', n, coord, &dwDummy);
5320 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, n, coord, &dwDummy);
5321}
5322
5323
5324/*
5325 * Clear the screen
5326 */
5327 static void
5328clear_screen(void)
5329{
5330 g_coord.X = g_coord.Y = 0;
5331 clear_chars(g_coord, Rows * Columns);
5332}
5333
5334
5335/*
5336 * Clear to end of display
5337 */
5338 static void
5339clear_to_end_of_display(void)
5340{
5341 clear_chars(g_coord, (Rows - g_coord.Y - 1)
5342 * Columns + (Columns - g_coord.X));
5343}
5344
5345
5346/*
5347 * Clear to end of line
5348 */
5349 static void
5350clear_to_end_of_line(void)
5351{
5352 clear_chars(g_coord, Columns - g_coord.X);
5353}
5354
5355
5356/*
5357 * Scroll the scroll region up by `cLines' lines
5358 */
5359 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005360scroll(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005361{
5362 COORD oldcoord = g_coord;
5363
5364 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
5365 delete_lines(cLines);
5366
5367 g_coord = oldcoord;
5368}
5369
5370
5371/*
5372 * Set the scroll region
5373 */
5374 static void
5375set_scroll_region(
5376 unsigned left,
5377 unsigned top,
5378 unsigned right,
5379 unsigned bottom)
5380{
5381 if (left >= right
5382 || top >= bottom
5383 || right > (unsigned) Columns - 1
5384 || bottom > (unsigned) Rows - 1)
5385 return;
5386
5387 g_srScrollRegion.Left = left;
5388 g_srScrollRegion.Top = top;
5389 g_srScrollRegion.Right = right;
5390 g_srScrollRegion.Bottom = bottom;
5391}
5392
5393
5394/*
5395 * Insert `cLines' lines at the current cursor position
5396 */
5397 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005398insert_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005399{
5400 SMALL_RECT source;
5401 COORD dest;
5402 CHAR_INFO fill;
5403
5404 dest.X = 0;
5405 dest.Y = g_coord.Y + cLines;
5406
5407 source.Left = 0;
5408 source.Top = g_coord.Y;
5409 source.Right = g_srScrollRegion.Right;
5410 source.Bottom = g_srScrollRegion.Bottom - cLines;
5411
5412 fill.Char.AsciiChar = ' ';
5413 fill.Attributes = g_attrCurrent;
5414
5415 ScrollConsoleScreenBuffer(g_hConOut, &source, NULL, dest, &fill);
5416
5417 /* Here we have to deal with a win32 console flake: If the scroll
5418 * region looks like abc and we scroll c to a and fill with d we get
5419 * cbd... if we scroll block c one line at a time to a, we get cdd...
5420 * vim expects cdd consistently... So we have to deal with that
5421 * here... (this also occurs scrolling the same way in the other
5422 * direction). */
5423
5424 if (source.Bottom < dest.Y)
5425 {
5426 COORD coord;
5427
5428 coord.X = 0;
5429 coord.Y = source.Bottom;
5430 clear_chars(coord, Columns * (dest.Y - source.Bottom));
5431 }
5432}
5433
5434
5435/*
5436 * Delete `cLines' lines at the current cursor position
5437 */
5438 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005439delete_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005440{
5441 SMALL_RECT source;
5442 COORD dest;
5443 CHAR_INFO fill;
5444 int nb;
5445
5446 dest.X = 0;
5447 dest.Y = g_coord.Y;
5448
5449 source.Left = 0;
5450 source.Top = g_coord.Y + cLines;
5451 source.Right = g_srScrollRegion.Right;
5452 source.Bottom = g_srScrollRegion.Bottom;
5453
5454 fill.Char.AsciiChar = ' ';
5455 fill.Attributes = g_attrCurrent;
5456
5457 ScrollConsoleScreenBuffer(g_hConOut, &source, NULL, dest, &fill);
5458
5459 /* Here we have to deal with a win32 console flake: If the scroll
5460 * region looks like abc and we scroll c to a and fill with d we get
5461 * cbd... if we scroll block c one line at a time to a, we get cdd...
5462 * vim expects cdd consistently... So we have to deal with that
5463 * here... (this also occurs scrolling the same way in the other
5464 * direction). */
5465
5466 nb = dest.Y + (source.Bottom - source.Top) + 1;
5467
5468 if (nb < source.Top)
5469 {
5470 COORD coord;
5471
5472 coord.X = 0;
5473 coord.Y = nb;
5474 clear_chars(coord, Columns * (source.Top - nb));
5475 }
5476}
5477
5478
5479/*
5480 * Set the cursor position
5481 */
5482 static void
5483gotoxy(
5484 unsigned x,
5485 unsigned y)
5486{
5487 if (x < 1 || x > (unsigned)Columns || y < 1 || y > (unsigned)Rows)
5488 return;
5489
5490 /* external cursor coords are 1-based; internal are 0-based */
5491 g_coord.X = x - 1;
5492 g_coord.Y = y - 1;
5493 SetConsoleCursorPosition(g_hConOut, g_coord);
5494}
5495
5496
5497/*
5498 * Set the current text attribute = (foreground | background)
5499 * See ../doc/os_win32.txt for the numbers.
5500 */
5501 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005502textattr(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005503{
Bram Moolenaar6383b922015-03-24 17:12:19 +01005504 g_attrCurrent = wAttr & 0xff;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005505
5506 SetConsoleTextAttribute(g_hConOut, wAttr);
5507}
5508
5509
5510 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005511textcolor(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005512{
Bram Moolenaar6383b922015-03-24 17:12:19 +01005513 g_attrCurrent = (g_attrCurrent & 0xf0) + (wAttr & 0x0f);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005514
5515 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
5516}
5517
5518
5519 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005520textbackground(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005521{
Bram Moolenaar6383b922015-03-24 17:12:19 +01005522 g_attrCurrent = (g_attrCurrent & 0x0f) + ((wAttr & 0x0f) << 4);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005523
5524 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
5525}
5526
5527
5528/*
5529 * restore the default text attribute (whatever we started with)
5530 */
5531 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005532normvideo(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005533{
5534 textattr(g_attrDefault);
5535}
5536
5537
5538static WORD g_attrPreStandout = 0;
5539
5540/*
5541 * Make the text standout, by brightening it
5542 */
5543 static void
5544standout(void)
5545{
5546 g_attrPreStandout = g_attrCurrent;
5547 textattr((WORD) (g_attrCurrent|FOREGROUND_INTENSITY|BACKGROUND_INTENSITY));
5548}
5549
5550
5551/*
5552 * Turn off standout mode
5553 */
5554 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005555standend(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005556{
5557 if (g_attrPreStandout)
5558 {
5559 textattr(g_attrPreStandout);
5560 g_attrPreStandout = 0;
5561 }
5562}
5563
5564
5565/*
Bram Moolenaarff1d0d42007-05-10 17:24:16 +00005566 * Set normal fg/bg color, based on T_ME. Called when t_me has been set.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005567 */
5568 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005569mch_set_normal_colors(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005570{
5571 char_u *p;
5572 int n;
5573
5574 cterm_normal_fg_color = (g_attrDefault & 0xf) + 1;
5575 cterm_normal_bg_color = ((g_attrDefault >> 4) & 0xf) + 1;
5576 if (T_ME[0] == ESC && T_ME[1] == '|')
5577 {
5578 p = T_ME + 2;
5579 n = getdigits(&p);
5580 if (*p == 'm' && n > 0)
5581 {
5582 cterm_normal_fg_color = (n & 0xf) + 1;
5583 cterm_normal_bg_color = ((n >> 4) & 0xf) + 1;
5584 }
5585 }
5586}
5587
5588
5589/*
5590 * visual bell: flash the screen
5591 */
5592 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005593visual_bell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005594{
5595 COORD coordOrigin = {0, 0};
5596 WORD attrFlash = ~g_attrCurrent & 0xff;
5597
5598 DWORD dwDummy;
5599 LPWORD oldattrs = (LPWORD)alloc(Rows * Columns * sizeof(WORD));
5600
5601 if (oldattrs == NULL)
5602 return;
5603 ReadConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
5604 coordOrigin, &dwDummy);
5605 FillConsoleOutputAttribute(g_hConOut, attrFlash, Rows * Columns,
5606 coordOrigin, &dwDummy);
5607
5608 Sleep(15); /* wait for 15 msec */
5609 WriteConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
5610 coordOrigin, &dwDummy);
5611 vim_free(oldattrs);
5612}
5613
5614
5615/*
5616 * Make the cursor visible or invisible
5617 */
5618 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005619cursor_visible(BOOL fVisible)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005620{
5621 s_cursor_visible = fVisible;
5622#ifdef MCH_CURSOR_SHAPE
5623 mch_update_cursor();
5624#endif
5625}
5626
5627
5628/*
Bram Moolenaarac360bf2015-09-01 20:31:20 +02005629 * write `cbToWrite' bytes in `pchBuf' to the screen
5630 * Returns the number of bytes actually written (at least one).
Bram Moolenaar071d4272004-06-13 20:20:40 +00005631 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02005632 static DWORD
Bram Moolenaar071d4272004-06-13 20:20:40 +00005633write_chars(
Bram Moolenaarac360bf2015-09-01 20:31:20 +02005634 char_u *pchBuf,
5635 DWORD cbToWrite)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005636{
5637 COORD coord = g_coord;
5638 DWORD written;
5639
Bram Moolenaarac360bf2015-09-01 20:31:20 +02005640#ifdef FEAT_MBYTE
5641 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
5642 {
5643 static WCHAR *unicodebuf = NULL;
5644 static int unibuflen = 0;
5645 int length;
5646 DWORD n, cchwritten, cells;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005647
Bram Moolenaarac360bf2015-09-01 20:31:20 +02005648 length = MultiByteToWideChar(CP_UTF8, 0, (LPCSTR)pchBuf, cbToWrite, 0, 0);
5649 if (unicodebuf == NULL || length > unibuflen)
5650 {
5651 vim_free(unicodebuf);
5652 unicodebuf = (WCHAR *)lalloc(length * sizeof(WCHAR), FALSE);
5653 unibuflen = length;
5654 }
5655 MultiByteToWideChar(CP_UTF8, 0, (LPCSTR)pchBuf, cbToWrite,
5656 unicodebuf, unibuflen);
5657
5658 cells = mb_string2cells(pchBuf, cbToWrite);
5659 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, cells,
5660 coord, &written);
5661 /* When writing fails or didn't write a single character, pretend one
5662 * character was written, otherwise we get stuck. */
5663 if (WriteConsoleOutputCharacterW(g_hConOut, unicodebuf, length,
5664 coord, &cchwritten) == 0
5665 || cchwritten == 0)
5666 cchwritten = 1;
5667
5668 if (cchwritten == length)
5669 {
5670 written = cbToWrite;
5671 g_coord.X += (SHORT)cells;
5672 }
5673 else
5674 {
5675 char_u *p = pchBuf;
5676 for (n = 0; n < cchwritten; n++)
5677 mb_cptr_adv(p);
5678 written = p - pchBuf;
5679 g_coord.X += (SHORT)mb_string2cells(pchBuf, written);
5680 }
5681 }
5682 else
5683#endif
5684 {
5685 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, cbToWrite,
5686 coord, &written);
5687 /* When writing fails or didn't write a single character, pretend one
5688 * character was written, otherwise we get stuck. */
5689 if (WriteConsoleOutputCharacter(g_hConOut, (LPCSTR)pchBuf, cbToWrite,
5690 coord, &written) == 0
5691 || written == 0)
5692 written = 1;
5693
5694 g_coord.X += (SHORT) written;
5695 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005696
5697 while (g_coord.X > g_srScrollRegion.Right)
5698 {
5699 g_coord.X -= (SHORT) Columns;
5700 if (g_coord.Y < g_srScrollRegion.Bottom)
5701 g_coord.Y++;
5702 }
5703
5704 gotoxy(g_coord.X + 1, g_coord.Y + 1);
5705
5706 return written;
5707}
5708
5709
5710/*
5711 * mch_write(): write the output buffer to the screen, translating ESC
5712 * sequences into calls to console output routines.
5713 */
5714 void
5715mch_write(
5716 char_u *s,
5717 int len)
5718{
5719 s[len] = NUL;
5720
5721 if (!term_console)
5722 {
5723 write(1, s, (unsigned)len);
5724 return;
5725 }
5726
5727 /* translate ESC | sequences into faked bios calls */
5728 while (len--)
5729 {
5730 /* optimization: use one single write_chars for runs of text,
5731 * rather than once per character It ain't curses, but it helps. */
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01005732 DWORD prefix = (DWORD)strcspn((char *)s, "\n\r\b\a\033");
Bram Moolenaar071d4272004-06-13 20:20:40 +00005733
5734 if (p_wd)
5735 {
5736 WaitForChar(p_wd);
5737 if (prefix != 0)
5738 prefix = 1;
5739 }
5740
5741 if (prefix != 0)
5742 {
5743 DWORD nWritten;
5744
5745 nWritten = write_chars(s, prefix);
5746#ifdef MCH_WRITE_DUMP
5747 if (fdDump)
5748 {
5749 fputc('>', fdDump);
5750 fwrite(s, sizeof(char_u), nWritten, fdDump);
5751 fputs("<\n", fdDump);
5752 }
5753#endif
5754 len -= (nWritten - 1);
5755 s += nWritten;
5756 }
5757 else if (s[0] == '\n')
5758 {
5759 /* \n, newline: go to the beginning of the next line or scroll */
5760 if (g_coord.Y == g_srScrollRegion.Bottom)
5761 {
5762 scroll(1);
5763 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Bottom + 1);
5764 }
5765 else
5766 {
5767 gotoxy(g_srScrollRegion.Left + 1, g_coord.Y + 2);
5768 }
5769#ifdef MCH_WRITE_DUMP
5770 if (fdDump)
5771 fputs("\\n\n", fdDump);
5772#endif
5773 s++;
5774 }
5775 else if (s[0] == '\r')
5776 {
5777 /* \r, carriage return: go to beginning of line */
5778 gotoxy(g_srScrollRegion.Left+1, g_coord.Y + 1);
5779#ifdef MCH_WRITE_DUMP
5780 if (fdDump)
5781 fputs("\\r\n", fdDump);
5782#endif
5783 s++;
5784 }
5785 else if (s[0] == '\b')
5786 {
5787 /* \b, backspace: move cursor one position left */
5788 if (g_coord.X > g_srScrollRegion.Left)
5789 g_coord.X--;
5790 else if (g_coord.Y > g_srScrollRegion.Top)
5791 {
5792 g_coord.X = g_srScrollRegion.Right;
5793 g_coord.Y--;
5794 }
5795 gotoxy(g_coord.X + 1, g_coord.Y + 1);
5796#ifdef MCH_WRITE_DUMP
5797 if (fdDump)
5798 fputs("\\b\n", fdDump);
5799#endif
5800 s++;
5801 }
5802 else if (s[0] == '\a')
5803 {
5804 /* \a, bell */
5805 MessageBeep(0xFFFFFFFF);
5806#ifdef MCH_WRITE_DUMP
5807 if (fdDump)
5808 fputs("\\a\n", fdDump);
5809#endif
5810 s++;
5811 }
5812 else if (s[0] == ESC && len >= 3-1 && s[1] == '|')
5813 {
5814#ifdef MCH_WRITE_DUMP
Bram Moolenaarc0197e22004-09-13 20:26:32 +00005815 char_u *old_s = s;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005816#endif
Bram Moolenaarc0197e22004-09-13 20:26:32 +00005817 char_u *p;
5818 int arg1 = 0, arg2 = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005819
5820 switch (s[2])
5821 {
5822 /* one or two numeric arguments, separated by ';' */
5823
5824 case '0': case '1': case '2': case '3': case '4':
5825 case '5': case '6': case '7': case '8': case '9':
5826 p = s + 2;
5827 arg1 = getdigits(&p); /* no check for length! */
5828 if (p > s + len)
5829 break;
5830
5831 if (*p == ';')
5832 {
5833 ++p;
5834 arg2 = getdigits(&p); /* no check for length! */
5835 if (p > s + len)
5836 break;
5837
5838 if (*p == 'H')
5839 gotoxy(arg2, arg1);
5840 else if (*p == 'r')
5841 set_scroll_region(0, arg1 - 1, Columns - 1, arg2 - 1);
5842 }
5843 else if (*p == 'A')
5844 {
5845 /* move cursor up arg1 lines in same column */
5846 gotoxy(g_coord.X + 1,
5847 max(g_srScrollRegion.Top, g_coord.Y - arg1) + 1);
5848 }
5849 else if (*p == 'C')
5850 {
5851 /* move cursor right arg1 columns in same line */
5852 gotoxy(min(g_srScrollRegion.Right, g_coord.X + arg1) + 1,
5853 g_coord.Y + 1);
5854 }
5855 else if (*p == 'H')
5856 {
5857 gotoxy(1, arg1);
5858 }
5859 else if (*p == 'L')
5860 {
5861 insert_lines(arg1);
5862 }
5863 else if (*p == 'm')
5864 {
5865 if (arg1 == 0)
5866 normvideo();
5867 else
5868 textattr((WORD) arg1);
5869 }
5870 else if (*p == 'f')
5871 {
5872 textcolor((WORD) arg1);
5873 }
5874 else if (*p == 'b')
5875 {
5876 textbackground((WORD) arg1);
5877 }
5878 else if (*p == 'M')
5879 {
5880 delete_lines(arg1);
5881 }
5882
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005883 len -= (int)(p - s);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005884 s = p + 1;
5885 break;
5886
5887
5888 /* Three-character escape sequences */
5889
5890 case 'A':
5891 /* move cursor up one line in same column */
5892 gotoxy(g_coord.X + 1,
5893 max(g_srScrollRegion.Top, g_coord.Y - 1) + 1);
5894 goto got3;
5895
5896 case 'B':
5897 visual_bell();
5898 goto got3;
5899
5900 case 'C':
5901 /* move cursor right one column in same line */
5902 gotoxy(min(g_srScrollRegion.Right, g_coord.X + 1) + 1,
5903 g_coord.Y + 1);
5904 goto got3;
5905
5906 case 'E':
5907 termcap_mode_end();
5908 goto got3;
5909
5910 case 'F':
5911 standout();
5912 goto got3;
5913
5914 case 'f':
5915 standend();
5916 goto got3;
5917
5918 case 'H':
5919 gotoxy(1, 1);
5920 goto got3;
5921
5922 case 'j':
5923 clear_to_end_of_display();
5924 goto got3;
5925
5926 case 'J':
5927 clear_screen();
5928 goto got3;
5929
5930 case 'K':
5931 clear_to_end_of_line();
5932 goto got3;
5933
5934 case 'L':
5935 insert_lines(1);
5936 goto got3;
5937
5938 case 'M':
5939 delete_lines(1);
5940 goto got3;
5941
5942 case 'S':
5943 termcap_mode_start();
5944 goto got3;
5945
5946 case 'V':
5947 cursor_visible(TRUE);
5948 goto got3;
5949
5950 case 'v':
5951 cursor_visible(FALSE);
5952 goto got3;
5953
5954 got3:
5955 s += 3;
5956 len -= 2;
5957 }
5958
5959#ifdef MCH_WRITE_DUMP
5960 if (fdDump)
5961 {
5962 fputs("ESC | ", fdDump);
5963 fwrite(old_s + 2, sizeof(char_u), s - old_s - 2, fdDump);
5964 fputc('\n', fdDump);
5965 }
5966#endif
5967 }
5968 else
5969 {
5970 /* Write a single character */
5971 DWORD nWritten;
5972
5973 nWritten = write_chars(s, 1);
5974#ifdef MCH_WRITE_DUMP
5975 if (fdDump)
5976 {
5977 fputc('>', fdDump);
5978 fwrite(s, sizeof(char_u), nWritten, fdDump);
5979 fputs("<\n", fdDump);
5980 }
5981#endif
5982
5983 len -= (nWritten - 1);
5984 s += nWritten;
5985 }
5986 }
5987
5988#ifdef MCH_WRITE_DUMP
5989 if (fdDump)
5990 fflush(fdDump);
5991#endif
5992}
5993
5994#endif /* FEAT_GUI_W32 */
5995
5996
5997/*
5998 * Delay for half a second.
5999 */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00006000/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00006001 void
6002mch_delay(
6003 long msec,
6004 int ignoreinput)
6005{
6006#ifdef FEAT_GUI_W32
6007 Sleep((int)msec); /* never wait for input */
Bram Moolenaar325b7a22004-07-05 15:58:32 +00006008#else /* Console */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006009 if (ignoreinput)
Bram Moolenaar325b7a22004-07-05 15:58:32 +00006010# ifdef FEAT_MZSCHEME
6011 if (mzthreads_allowed() && p_mzq > 0 && msec > p_mzq)
6012 {
6013 int towait = p_mzq;
6014
6015 /* if msec is large enough, wait by portions in p_mzq */
6016 while (msec > 0)
6017 {
6018 mzvim_check_threads();
6019 if (msec < towait)
6020 towait = msec;
6021 Sleep(towait);
6022 msec -= towait;
6023 }
6024 }
6025 else
6026# endif
6027 Sleep((int)msec);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006028 else
6029 WaitForChar(msec);
6030#endif
6031}
6032
6033
6034/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01006035 * This version of remove is not scared by a readonly (backup) file.
6036 * This can also remove a symbolic link like Unix.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006037 * Return 0 for success, -1 for failure.
6038 */
6039 int
6040mch_remove(char_u *name)
6041{
6042#ifdef FEAT_MBYTE
6043 WCHAR *wn = NULL;
6044 int n;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02006045#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006046
Bram Moolenaar203258c2016-01-17 22:15:16 +01006047 /*
6048 * On Windows, deleting a directory's symbolic link is done by
6049 * RemoveDirectory(): mch_rmdir. It seems unnatural, but it is fact.
6050 */
6051 if (mch_isdir(name) && mch_is_symbolic_link(name))
6052 return mch_rmdir(name);
6053
Bram Moolenaar12b559e2013-06-12 22:41:37 +02006054 win32_setattrs(name, FILE_ATTRIBUTE_NORMAL);
6055
6056#ifdef FEAT_MBYTE
Bram Moolenaar071d4272004-06-13 20:20:40 +00006057 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
6058 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006059 wn = enc_to_utf16(name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006060 if (wn != NULL)
6061 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006062 n = DeleteFileW(wn) ? 0 : -1;
6063 vim_free(wn);
6064 if (n == 0 || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
6065 return n;
6066 /* Retry with non-wide function (for Windows 98). */
6067 }
6068 }
6069#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006070 return DeleteFile((LPCSTR)name) ? 0 : -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006071}
6072
6073
6074/*
6075 * check for an "interrupt signal": CTRL-break or CTRL-C
6076 */
6077 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006078mch_breakcheck(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006079{
6080#ifndef FEAT_GUI_W32 /* never used */
6081 if (g_fCtrlCPressed || g_fCBrkPressed)
6082 {
6083 g_fCtrlCPressed = g_fCBrkPressed = FALSE;
6084 got_int = TRUE;
6085 }
6086#endif
6087}
6088
Bram Moolenaaree273972016-01-02 21:11:51 +01006089/* physical RAM to leave for the OS */
6090#define WINNT_RESERVE_BYTES (256*1024*1024)
6091#define WIN95_RESERVE_BYTES (8*1024*1024)
6092
6093/*
6094 * How much main memory in KiB that can be used by VIM.
6095 */
6096/*ARGSUSED*/
6097 long_u
6098mch_total_mem(int special)
6099{
6100 PlatformId();
6101#if (defined(_MSC_VER) && (WINVER > 0x0400)) || defined(MEMORYSTATUSEX)
6102 if (g_PlatformId == VER_PLATFORM_WIN32_NT)
6103 {
6104 MEMORYSTATUSEX ms;
6105
6106 /* Need to use GlobalMemoryStatusEx() when there is more memory than
6107 * what fits in 32 bits. But it's not always available. */
6108 ms.dwLength = sizeof(MEMORYSTATUSEX);
6109 GlobalMemoryStatusEx(&ms);
6110 if (ms.ullAvailVirtual < ms.ullTotalPhys)
6111 {
6112 /* Process address space fits in physical RAM, use all of it. */
6113 return (long_u)(ms.ullAvailVirtual / 1024);
6114 }
6115 if (ms.ullTotalPhys <= WINNT_RESERVE_BYTES)
6116 {
6117 /* Catch old NT box or perverse hardware setup. */
6118 return (long_u)((ms.ullTotalPhys / 2) / 1024);
6119 }
6120 /* Use physical RAM less reserve for OS + data. */
6121 return (long_u)((ms.ullTotalPhys - WINNT_RESERVE_BYTES) / 1024);
6122 }
6123 else
6124#endif
6125 {
6126 /* Pre-XP or 95 OS handling. */
6127 MEMORYSTATUS ms;
6128 long_u os_reserve_bytes;
6129
6130 ms.dwLength = sizeof(MEMORYSTATUS);
6131 GlobalMemoryStatus(&ms);
6132 if (ms.dwAvailVirtual < ms.dwTotalPhys)
6133 {
6134 /* Process address space fits in physical RAM, use all of it. */
6135 return (long_u)(ms.dwAvailVirtual / 1024);
6136 }
6137 os_reserve_bytes = (g_PlatformId == VER_PLATFORM_WIN32_NT)
6138 ? WINNT_RESERVE_BYTES
6139 : WIN95_RESERVE_BYTES;
6140 if (ms.dwTotalPhys <= os_reserve_bytes)
6141 {
6142 /* Catch old boxes or perverse hardware setup. */
6143 return (long_u)((ms.dwTotalPhys / 2) / 1024);
6144 }
6145 /* Use physical RAM less reserve for OS + data. */
6146 return (long_u)((ms.dwTotalPhys - os_reserve_bytes) / 1024);
6147 }
6148}
Bram Moolenaar071d4272004-06-13 20:20:40 +00006149
Bram Moolenaar071d4272004-06-13 20:20:40 +00006150#ifdef FEAT_MBYTE
6151/*
6152 * Same code as below, but with wide functions and no comments.
6153 * Return 0 for success, non-zero for failure.
6154 */
6155 int
6156mch_wrename(WCHAR *wold, WCHAR *wnew)
6157{
6158 WCHAR *p;
6159 int i;
6160 WCHAR szTempFile[_MAX_PATH + 1];
6161 WCHAR szNewPath[_MAX_PATH + 1];
6162 HANDLE hf;
6163
6164 if (!mch_windows95())
6165 {
6166 p = wold;
6167 for (i = 0; wold[i] != NUL; ++i)
6168 if ((wold[i] == '/' || wold[i] == '\\' || wold[i] == ':')
6169 && wold[i + 1] != 0)
6170 p = wold + i + 1;
6171 if ((int)(wold + i - p) < 8 || p[6] != '~')
6172 return (MoveFileW(wold, wnew) == 0);
6173 }
6174
6175 if (GetFullPathNameW(wnew, _MAX_PATH, szNewPath, &p) == 0 || p == NULL)
6176 return -1;
6177 *p = NUL;
6178
6179 if (GetTempFileNameW(szNewPath, L"VIM", 0, szTempFile) == 0)
6180 return -2;
6181
6182 if (!DeleteFileW(szTempFile))
6183 return -3;
6184
6185 if (!MoveFileW(wold, szTempFile))
6186 return -4;
6187
6188 if ((hf = CreateFileW(wold, GENERIC_WRITE, 0, NULL, CREATE_NEW,
6189 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
6190 return -5;
6191 if (!CloseHandle(hf))
6192 return -6;
6193
6194 if (!MoveFileW(szTempFile, wnew))
6195 {
6196 (void)MoveFileW(szTempFile, wold);
6197 return -7;
6198 }
6199
6200 DeleteFileW(szTempFile);
6201
6202 if (!DeleteFileW(wold))
6203 return -8;
6204
6205 return 0;
6206}
6207#endif
6208
6209
6210/*
6211 * mch_rename() works around a bug in rename (aka MoveFile) in
6212 * Windows 95: rename("foo.bar", "foo.bar~") will generate a
6213 * file whose short file name is "FOO.BAR" (its long file name will
6214 * be correct: "foo.bar~"). Because a file can be accessed by
6215 * either its SFN or its LFN, "foo.bar" has effectively been
6216 * renamed to "foo.bar", which is not at all what was wanted. This
6217 * seems to happen only when renaming files with three-character
6218 * extensions by appending a suffix that does not include ".".
6219 * Windows NT gets it right, however, with an SFN of "FOO~1.BAR".
6220 *
6221 * There is another problem, which isn't really a bug but isn't right either:
6222 * When renaming "abcdef~1.txt" to "abcdef~1.txt~", the short name can be
6223 * "abcdef~1.txt" again. This has been reported on Windows NT 4.0 with
6224 * service pack 6. Doesn't seem to happen on Windows 98.
6225 *
6226 * Like rename(), returns 0 upon success, non-zero upon failure.
6227 * Should probably set errno appropriately when errors occur.
6228 */
6229 int
6230mch_rename(
6231 const char *pszOldFile,
6232 const char *pszNewFile)
6233{
6234 char szTempFile[_MAX_PATH+1];
6235 char szNewPath[_MAX_PATH+1];
6236 char *pszFilePart;
6237 HANDLE hf;
6238#ifdef FEAT_MBYTE
6239 WCHAR *wold = NULL;
6240 WCHAR *wnew = NULL;
6241 int retval = -1;
6242
6243 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
6244 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006245 wold = enc_to_utf16((char_u *)pszOldFile, NULL);
6246 wnew = enc_to_utf16((char_u *)pszNewFile, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006247 if (wold != NULL && wnew != NULL)
6248 retval = mch_wrename(wold, wnew);
6249 vim_free(wold);
6250 vim_free(wnew);
6251 if (retval == 0 || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
6252 return retval;
6253 /* Retry with non-wide function (for Windows 98). */
6254 }
6255#endif
6256
6257 /*
6258 * No need to play tricks if not running Windows 95, unless the file name
6259 * contains a "~" as the seventh character.
6260 */
6261 if (!mch_windows95())
6262 {
6263 pszFilePart = (char *)gettail((char_u *)pszOldFile);
6264 if (STRLEN(pszFilePart) < 8 || pszFilePart[6] != '~')
6265 return rename(pszOldFile, pszNewFile);
6266 }
6267
6268 /* Get base path of new file name. Undocumented feature: If pszNewFile is
6269 * a directory, no error is returned and pszFilePart will be NULL. */
6270 if (GetFullPathName(pszNewFile, _MAX_PATH, szNewPath, &pszFilePart) == 0
6271 || pszFilePart == NULL)
6272 return -1;
6273 *pszFilePart = NUL;
6274
6275 /* Get (and create) a unique temporary file name in directory of new file */
6276 if (GetTempFileName(szNewPath, "VIM", 0, szTempFile) == 0)
6277 return -2;
6278
6279 /* blow the temp file away */
6280 if (!DeleteFile(szTempFile))
6281 return -3;
6282
6283 /* rename old file to the temp file */
6284 if (!MoveFile(pszOldFile, szTempFile))
6285 return -4;
6286
6287 /* now create an empty file called pszOldFile; this prevents the operating
6288 * system using pszOldFile as an alias (SFN) if we're renaming within the
6289 * same directory. For example, we're editing a file called
6290 * filename.asc.txt by its SFN, filena~1.txt. If we rename filena~1.txt
6291 * to filena~1.txt~ (i.e., we're making a backup while writing it), the
6292 * SFN for filena~1.txt~ will be filena~1.txt, by default, which will
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006293 * cause all sorts of problems later in buf_write(). So, we create an
6294 * empty file called filena~1.txt and the system will have to find some
6295 * other SFN for filena~1.txt~, such as filena~2.txt
Bram Moolenaar071d4272004-06-13 20:20:40 +00006296 */
6297 if ((hf = CreateFile(pszOldFile, GENERIC_WRITE, 0, NULL, CREATE_NEW,
6298 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
6299 return -5;
6300 if (!CloseHandle(hf))
6301 return -6;
6302
6303 /* rename the temp file to the new file */
6304 if (!MoveFile(szTempFile, pszNewFile))
6305 {
6306 /* Renaming failed. Rename the file back to its old name, so that it
6307 * looks like nothing happened. */
6308 (void)MoveFile(szTempFile, pszOldFile);
6309
6310 return -7;
6311 }
6312
6313 /* Seems to be left around on Novell filesystems */
6314 DeleteFile(szTempFile);
6315
6316 /* finally, remove the empty old file */
6317 if (!DeleteFile(pszOldFile))
6318 return -8;
6319
6320 return 0; /* success */
6321}
6322
6323/*
6324 * Get the default shell for the current hardware platform
6325 */
6326 char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006327default_shell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006328{
6329 char* psz = NULL;
6330
6331 PlatformId();
6332
6333 if (g_PlatformId == VER_PLATFORM_WIN32_NT) /* Windows NT */
6334 psz = "cmd.exe";
6335 else if (g_PlatformId == VER_PLATFORM_WIN32_WINDOWS) /* Windows 95 */
6336 psz = "command.com";
6337
6338 return psz;
6339}
6340
6341/*
6342 * mch_access() extends access() to do more detailed check on network drives.
6343 * Returns 0 if file "n" has access rights according to "p", -1 otherwise.
6344 */
6345 int
6346mch_access(char *n, int p)
6347{
6348 HANDLE hFile;
6349 DWORD am;
6350 int retval = -1; /* default: fail */
6351#ifdef FEAT_MBYTE
6352 WCHAR *wn = NULL;
6353
6354 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006355 wn = enc_to_utf16((char_u *)n, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006356#endif
6357
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006358 if (mch_isdir((char_u *)n))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006359 {
6360 char TempName[_MAX_PATH + 16] = "";
6361#ifdef FEAT_MBYTE
6362 WCHAR TempNameW[_MAX_PATH + 16] = L"";
6363#endif
6364
6365 if (p & R_OK)
6366 {
6367 /* Read check is performed by seeing if we can do a find file on
6368 * the directory for any file. */
6369#ifdef FEAT_MBYTE
6370 if (wn != NULL)
6371 {
6372 int i;
6373 WIN32_FIND_DATAW d;
6374
6375 for (i = 0; i < _MAX_PATH && wn[i] != 0; ++i)
6376 TempNameW[i] = wn[i];
6377 if (TempNameW[i - 1] != '\\' && TempNameW[i - 1] != '/')
6378 TempNameW[i++] = '\\';
6379 TempNameW[i++] = '*';
6380 TempNameW[i++] = 0;
6381
6382 hFile = FindFirstFileW(TempNameW, &d);
6383 if (hFile == INVALID_HANDLE_VALUE)
6384 {
6385 if (GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
6386 goto getout;
6387
6388 /* Retry with non-wide function (for Windows 98). */
6389 vim_free(wn);
6390 wn = NULL;
6391 }
6392 else
6393 (void)FindClose(hFile);
6394 }
6395 if (wn == NULL)
6396#endif
6397 {
6398 char *pch;
6399 WIN32_FIND_DATA d;
6400
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006401 vim_strncpy((char_u *)TempName, (char_u *)n, _MAX_PATH);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006402 pch = TempName + STRLEN(TempName) - 1;
6403 if (*pch != '\\' && *pch != '/')
6404 *++pch = '\\';
6405 *++pch = '*';
6406 *++pch = NUL;
6407
6408 hFile = FindFirstFile(TempName, &d);
6409 if (hFile == INVALID_HANDLE_VALUE)
6410 goto getout;
6411 (void)FindClose(hFile);
6412 }
6413 }
6414
6415 if (p & W_OK)
6416 {
6417 /* Trying to create a temporary file in the directory should catch
6418 * directories on read-only network shares. However, in
6419 * directories whose ACL allows writes but denies deletes will end
6420 * up keeping the temporary file :-(. */
6421#ifdef FEAT_MBYTE
6422 if (wn != NULL)
6423 {
6424 if (!GetTempFileNameW(wn, L"VIM", 0, TempNameW))
6425 {
6426 if (GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
6427 goto getout;
6428
6429 /* Retry with non-wide function (for Windows 98). */
6430 vim_free(wn);
6431 wn = NULL;
6432 }
6433 else
6434 DeleteFileW(TempNameW);
6435 }
6436 if (wn == NULL)
6437#endif
6438 {
6439 if (!GetTempFileName(n, "VIM", 0, TempName))
6440 goto getout;
6441 mch_remove((char_u *)TempName);
6442 }
6443 }
6444 }
6445 else
6446 {
6447 /* Trying to open the file for the required access does ACL, read-only
6448 * network share, and file attribute checks. */
6449 am = ((p & W_OK) ? GENERIC_WRITE : 0)
6450 | ((p & R_OK) ? GENERIC_READ : 0);
6451#ifdef FEAT_MBYTE
6452 if (wn != NULL)
6453 {
6454 hFile = CreateFileW(wn, am, 0, NULL, OPEN_EXISTING, 0, NULL);
6455 if (hFile == INVALID_HANDLE_VALUE
6456 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
6457 {
6458 /* Retry with non-wide function (for Windows 98). */
6459 vim_free(wn);
6460 wn = NULL;
6461 }
6462 }
6463 if (wn == NULL)
6464#endif
6465 hFile = CreateFile(n, am, 0, NULL, OPEN_EXISTING, 0, NULL);
6466 if (hFile == INVALID_HANDLE_VALUE)
6467 goto getout;
6468 CloseHandle(hFile);
6469 }
6470
6471 retval = 0; /* success */
6472getout:
6473#ifdef FEAT_MBYTE
6474 vim_free(wn);
6475#endif
6476 return retval;
6477}
6478
6479#if defined(FEAT_MBYTE) || defined(PROTO)
6480/*
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006481 * Version of open() that may use UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006482 */
6483 int
6484mch_open(char *name, int flags, int mode)
6485{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006486 /* _wopen() does not work with Borland C 5.5: creates a read-only file. */
6487# ifndef __BORLANDC__
Bram Moolenaar071d4272004-06-13 20:20:40 +00006488 WCHAR *wn;
6489 int f;
6490
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006491 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006492 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006493 wn = enc_to_utf16((char_u *)name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006494 if (wn != NULL)
6495 {
6496 f = _wopen(wn, flags, mode);
6497 vim_free(wn);
Bram Moolenaarcd981f22014-02-11 17:06:00 +01006498 if (f >= 0 || g_PlatformId == VER_PLATFORM_WIN32_NT)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006499 return f;
6500 /* Retry with non-wide function (for Windows 98). Can't use
6501 * GetLastError() here and it's unclear what errno gets set to if
6502 * the _wopen() fails for missing wide functions. */
6503 }
6504 }
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006505# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006506
Bram Moolenaarf9e6c3b2014-11-05 18:36:03 +01006507 /* open() can open a file which name is longer than _MAX_PATH bytes
6508 * and shorter than _MAX_PATH characters successfully, but sometimes it
6509 * causes unexpected error in another part. We make it an error explicitly
6510 * here. */
6511 if (strlen(name) >= _MAX_PATH)
6512 return -1;
6513
Bram Moolenaar071d4272004-06-13 20:20:40 +00006514 return open(name, flags, mode);
6515}
6516
6517/*
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006518 * Version of fopen() that may use UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006519 */
6520 FILE *
6521mch_fopen(char *name, char *mode)
6522{
6523 WCHAR *wn, *wm;
6524 FILE *f = NULL;
6525
6526 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage
6527# ifdef __BORLANDC__
6528 /* Wide functions of Borland C 5.5 do not work on Windows 98. */
6529 && g_PlatformId == VER_PLATFORM_WIN32_NT
6530# endif
6531 )
6532 {
Bram Moolenaare6a91fd2008-07-24 18:51:11 +00006533# if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0fde2902008-03-16 13:54:13 +00006534 /* Work around an annoying assertion in the Microsoft debug CRT
6535 * when mode's text/binary setting doesn't match _get_fmode(). */
6536 char newMode = mode[strlen(mode) - 1];
6537 int oldMode = 0;
6538
6539 _get_fmode(&oldMode);
6540 if (newMode == 't')
6541 _set_fmode(_O_TEXT);
6542 else if (newMode == 'b')
6543 _set_fmode(_O_BINARY);
6544# endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006545 wn = enc_to_utf16((char_u *)name, NULL);
6546 wm = enc_to_utf16((char_u *)mode, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006547 if (wn != NULL && wm != NULL)
6548 f = _wfopen(wn, wm);
6549 vim_free(wn);
6550 vim_free(wm);
Bram Moolenaar0fde2902008-03-16 13:54:13 +00006551
Bram Moolenaare6a91fd2008-07-24 18:51:11 +00006552# if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0fde2902008-03-16 13:54:13 +00006553 _set_fmode(oldMode);
6554# endif
6555
Bram Moolenaarcd981f22014-02-11 17:06:00 +01006556 if (f != NULL || g_PlatformId == VER_PLATFORM_WIN32_NT)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006557 return f;
6558 /* Retry with non-wide function (for Windows 98). Can't use
6559 * GetLastError() here and it's unclear what errno gets set to if
6560 * the _wfopen() fails for missing wide functions. */
6561 }
6562
Bram Moolenaarf9e6c3b2014-11-05 18:36:03 +01006563 /* fopen() can open a file which name is longer than _MAX_PATH bytes
6564 * and shorter than _MAX_PATH characters successfully, but sometimes it
6565 * causes unexpected error in another part. We make it an error explicitly
6566 * here. */
6567 if (strlen(name) >= _MAX_PATH)
6568 return NULL;
6569
Bram Moolenaar071d4272004-06-13 20:20:40 +00006570 return fopen(name, mode);
6571}
6572#endif
6573
6574#ifdef FEAT_MBYTE
6575/*
6576 * SUB STREAM (aka info stream) handling:
6577 *
6578 * NTFS can have sub streams for each file. Normal contents of file is
6579 * stored in the main stream, and extra contents (author information and
6580 * title and so on) can be stored in sub stream. After Windows 2000, user
6581 * can access and store those informations in sub streams via explorer's
6582 * property menuitem in right click menu. Those informations in sub streams
6583 * were lost when copying only the main stream. So we have to copy sub
6584 * streams.
6585 *
6586 * Incomplete explanation:
6587 * http://msdn.microsoft.com/library/en-us/dnw2k/html/ntfs5.asp
6588 * More useful info and an example:
6589 * http://www.sysinternals.com/ntw2k/source/misc.shtml#streams
6590 */
6591
6592/*
6593 * Copy info stream data "substream". Read from the file with BackupRead(sh)
6594 * and write to stream "substream" of file "to".
6595 * Errors are ignored.
6596 */
6597 static void
6598copy_substream(HANDLE sh, void *context, WCHAR *to, WCHAR *substream, long len)
6599{
6600 HANDLE hTo;
6601 WCHAR *to_name;
6602
6603 to_name = malloc((wcslen(to) + wcslen(substream) + 1) * sizeof(WCHAR));
6604 wcscpy(to_name, to);
6605 wcscat(to_name, substream);
6606
6607 hTo = CreateFileW(to_name, GENERIC_WRITE, 0, NULL, OPEN_ALWAYS,
6608 FILE_ATTRIBUTE_NORMAL, NULL);
6609 if (hTo != INVALID_HANDLE_VALUE)
6610 {
6611 long done;
6612 DWORD todo;
6613 DWORD readcnt, written;
6614 char buf[4096];
6615
6616 /* Copy block of bytes at a time. Abort when something goes wrong. */
6617 for (done = 0; done < len; done += written)
6618 {
6619 /* (size_t) cast for Borland C 5.5 */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006620 todo = (DWORD)((size_t)(len - done) > sizeof(buf) ? sizeof(buf)
6621 : (size_t)(len - done));
Bram Moolenaar071d4272004-06-13 20:20:40 +00006622 if (!BackupRead(sh, (LPBYTE)buf, todo, &readcnt,
6623 FALSE, FALSE, context)
6624 || readcnt != todo
6625 || !WriteFile(hTo, buf, todo, &written, NULL)
6626 || written != todo)
6627 break;
6628 }
6629 CloseHandle(hTo);
6630 }
6631
6632 free(to_name);
6633}
6634
6635/*
6636 * Copy info streams from file "from" to file "to".
6637 */
6638 static void
6639copy_infostreams(char_u *from, char_u *to)
6640{
6641 WCHAR *fromw;
6642 WCHAR *tow;
6643 HANDLE sh;
6644 WIN32_STREAM_ID sid;
6645 int headersize;
6646 WCHAR streamname[_MAX_PATH];
6647 DWORD readcount;
6648 void *context = NULL;
6649 DWORD lo, hi;
6650 int len;
6651
6652 /* Convert the file names to wide characters. */
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006653 fromw = enc_to_utf16(from, NULL);
6654 tow = enc_to_utf16(to, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006655 if (fromw != NULL && tow != NULL)
6656 {
6657 /* Open the file for reading. */
6658 sh = CreateFileW(fromw, GENERIC_READ, FILE_SHARE_READ, NULL,
6659 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
6660 if (sh != INVALID_HANDLE_VALUE)
6661 {
6662 /* Use BackupRead() to find the info streams. Repeat until we
6663 * have done them all.*/
6664 for (;;)
6665 {
6666 /* Get the header to find the length of the stream name. If
6667 * the "readcount" is zero we have done all info streams. */
6668 ZeroMemory(&sid, sizeof(WIN32_STREAM_ID));
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006669 headersize = (int)((char *)&sid.cStreamName - (char *)&sid.dwStreamId);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006670 if (!BackupRead(sh, (LPBYTE)&sid, headersize,
6671 &readcount, FALSE, FALSE, &context)
6672 || readcount == 0)
6673 break;
6674
6675 /* We only deal with streams that have a name. The normal
6676 * file data appears to be without a name, even though docs
6677 * suggest it is called "::$DATA". */
6678 if (sid.dwStreamNameSize > 0)
6679 {
6680 /* Read the stream name. */
6681 if (!BackupRead(sh, (LPBYTE)streamname,
6682 sid.dwStreamNameSize,
6683 &readcount, FALSE, FALSE, &context))
6684 break;
6685
6686 /* Copy an info stream with a name ":anything:$DATA".
6687 * Skip "::$DATA", it has no stream name (examples suggest
6688 * it might be used for the normal file contents).
6689 * Note that BackupRead() counts bytes, but the name is in
6690 * wide characters. */
6691 len = readcount / sizeof(WCHAR);
6692 streamname[len] = 0;
6693 if (len > 7 && wcsicmp(streamname + len - 6,
6694 L":$DATA") == 0)
6695 {
6696 streamname[len - 6] = 0;
6697 copy_substream(sh, &context, tow, streamname,
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00006698 (long)sid.Size.u.LowPart);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006699 }
6700 }
6701
6702 /* Advance to the next stream. We might try seeking too far,
6703 * but BackupSeek() doesn't skip over stream borders, thus
6704 * that's OK. */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00006705 (void)BackupSeek(sh, sid.Size.u.LowPart, sid.Size.u.HighPart,
Bram Moolenaar071d4272004-06-13 20:20:40 +00006706 &lo, &hi, &context);
6707 }
6708
6709 /* Clear the context. */
6710 (void)BackupRead(sh, NULL, 0, &readcount, TRUE, FALSE, &context);
6711
6712 CloseHandle(sh);
6713 }
6714 }
6715 vim_free(fromw);
6716 vim_free(tow);
6717}
6718#endif
6719
6720/*
6721 * Copy file attributes from file "from" to file "to".
6722 * For Windows NT and later we copy info streams.
6723 * Always returns zero, errors are ignored.
6724 */
6725 int
6726mch_copy_file_attribute(char_u *from, char_u *to)
6727{
6728#ifdef FEAT_MBYTE
6729 /* File streams only work on Windows NT and later. */
6730 PlatformId();
6731 if (g_PlatformId == VER_PLATFORM_WIN32_NT)
6732 copy_infostreams(from, to);
6733#endif
6734 return 0;
6735}
6736
6737#if defined(MYRESETSTKOFLW) || defined(PROTO)
6738/*
6739 * Recreate a destroyed stack guard page in win32.
6740 * Written by Benjamin Peterson.
6741 */
6742
6743/* These magic numbers are from the MS header files */
6744#define MIN_STACK_WIN9X 17
6745#define MIN_STACK_WINNT 2
6746
6747/*
6748 * This function does the same thing as _resetstkoflw(), which is only
6749 * available in DevStudio .net and later.
6750 * Returns 0 for failure, 1 for success.
6751 */
6752 int
6753myresetstkoflw(void)
6754{
6755 BYTE *pStackPtr;
6756 BYTE *pGuardPage;
6757 BYTE *pStackBase;
6758 BYTE *pLowestPossiblePage;
6759 MEMORY_BASIC_INFORMATION mbi;
6760 SYSTEM_INFO si;
6761 DWORD nPageSize;
6762 DWORD dummy;
6763
6764 /* This code will not work on win32s. */
6765 PlatformId();
6766 if (g_PlatformId == VER_PLATFORM_WIN32s)
6767 return 0;
6768
6769 /* We need to know the system page size. */
6770 GetSystemInfo(&si);
6771 nPageSize = si.dwPageSize;
6772
6773 /* ...and the current stack pointer */
6774 pStackPtr = (BYTE*)_alloca(1);
6775
6776 /* ...and the base of the stack. */
6777 if (VirtualQuery(pStackPtr, &mbi, sizeof mbi) == 0)
6778 return 0;
6779 pStackBase = (BYTE*)mbi.AllocationBase;
6780
6781 /* ...and the page thats min_stack_req pages away from stack base; this is
6782 * the lowest page we could use. */
6783 pLowestPossiblePage = pStackBase + ((g_PlatformId == VER_PLATFORM_WIN32_NT)
6784 ? MIN_STACK_WINNT : MIN_STACK_WIN9X) * nPageSize;
6785
6786 /* On Win95, we want the next page down from the end of the stack. */
6787 if (g_PlatformId == VER_PLATFORM_WIN32_WINDOWS)
6788 {
6789 /* Find the page that's only 1 page down from the page that the stack
6790 * ptr is in. */
6791 pGuardPage = (BYTE*)((DWORD)nPageSize * (((DWORD)pStackPtr
6792 / (DWORD)nPageSize) - 1));
6793 if (pGuardPage < pLowestPossiblePage)
6794 return 0;
6795
6796 /* Apply the noaccess attribute to the page -- there's no guard
6797 * attribute in win95-type OSes. */
6798 if (!VirtualProtect(pGuardPage, nPageSize, PAGE_NOACCESS, &dummy))
6799 return 0;
6800 }
6801 else
6802 {
6803 /* On NT, however, we want the first committed page in the stack Start
6804 * at the stack base and move forward through memory until we find a
6805 * committed block. */
6806 BYTE *pBlock = pStackBase;
6807
Bram Moolenaara466c992005-07-09 21:03:22 +00006808 for (;;)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006809 {
6810 if (VirtualQuery(pBlock, &mbi, sizeof mbi) == 0)
6811 return 0;
6812
6813 pBlock += mbi.RegionSize;
6814
6815 if (mbi.State & MEM_COMMIT)
6816 break;
6817 }
6818
6819 /* mbi now describes the first committed block in the stack. */
6820 if (mbi.Protect & PAGE_GUARD)
6821 return 1;
6822
6823 /* decide where the guard page should start */
6824 if ((long_u)(mbi.BaseAddress) < (long_u)pLowestPossiblePage)
6825 pGuardPage = pLowestPossiblePage;
6826 else
6827 pGuardPage = (BYTE*)mbi.BaseAddress;
6828
6829 /* allocate the guard page */
6830 if (!VirtualAlloc(pGuardPage, nPageSize, MEM_COMMIT, PAGE_READWRITE))
6831 return 0;
6832
6833 /* apply the guard attribute to the page */
6834 if (!VirtualProtect(pGuardPage, nPageSize, PAGE_READWRITE | PAGE_GUARD,
6835 &dummy))
6836 return 0;
6837 }
6838
6839 return 1;
6840}
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006841#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006842
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006843
6844#if defined(FEAT_MBYTE) || defined(PROTO)
6845/*
6846 * The command line arguments in UCS2
6847 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00006848static int nArgsW = 0;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006849static LPWSTR *ArglistW = NULL;
6850static int global_argc = 0;
6851static char **global_argv;
6852
6853static int used_file_argc = 0; /* last argument in global_argv[] used
6854 for the argument list. */
6855static int *used_file_indexes = NULL; /* indexes in global_argv[] for
6856 command line arguments added to
6857 the argument list */
6858static int used_file_count = 0; /* nr of entries in used_file_indexes */
6859static int used_file_literal = FALSE; /* take file names literally */
6860static int used_file_full_path = FALSE; /* file name was full path */
Bram Moolenaar910f66f2006-04-05 20:41:53 +00006861static int used_file_diff_mode = FALSE; /* file name was with diff mode */
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006862static int used_alist_count = 0;
6863
6864
6865/*
6866 * Get the command line arguments. Unicode version.
6867 * Returns argc. Zero when something fails.
6868 */
6869 int
6870get_cmd_argsW(char ***argvp)
6871{
6872 char **argv = NULL;
6873 int argc = 0;
6874 int i;
6875
Bram Moolenaar14993322014-09-09 12:25:33 +02006876 free_cmd_argsW();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006877 ArglistW = CommandLineToArgvW(GetCommandLineW(), &nArgsW);
6878 if (ArglistW != NULL)
6879 {
6880 argv = malloc((nArgsW + 1) * sizeof(char *));
6881 if (argv != NULL)
6882 {
6883 argc = nArgsW;
6884 argv[argc] = NULL;
6885 for (i = 0; i < argc; ++i)
6886 {
6887 int len;
6888
6889 /* Convert each Unicode argument to the current codepage. */
6890 WideCharToMultiByte_alloc(GetACP(), 0,
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006891 ArglistW[i], (int)wcslen(ArglistW[i]) + 1,
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006892 (LPSTR *)&argv[i], &len, 0, 0);
6893 if (argv[i] == NULL)
6894 {
6895 /* Out of memory, clear everything. */
6896 while (i > 0)
6897 free(argv[--i]);
6898 free(argv);
Bram Moolenaar73c61632013-12-07 14:48:10 +01006899 argv = NULL;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006900 argc = 0;
6901 }
6902 }
6903 }
6904 }
6905
6906 global_argc = argc;
6907 global_argv = argv;
6908 if (argc > 0)
Bram Moolenaar14993322014-09-09 12:25:33 +02006909 {
6910 if (used_file_indexes != NULL)
6911 free(used_file_indexes);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006912 used_file_indexes = malloc(argc * sizeof(int));
Bram Moolenaar14993322014-09-09 12:25:33 +02006913 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006914
6915 if (argvp != NULL)
6916 *argvp = argv;
6917 return argc;
6918}
6919
6920 void
6921free_cmd_argsW(void)
6922{
6923 if (ArglistW != NULL)
6924 {
6925 GlobalFree(ArglistW);
6926 ArglistW = NULL;
6927 }
6928}
6929
6930/*
6931 * Remember "name" is an argument that was added to the argument list.
6932 * This avoids that we have to re-parse the argument list when fix_arg_enc()
6933 * is called.
6934 */
6935 void
Bram Moolenaar910f66f2006-04-05 20:41:53 +00006936used_file_arg(char *name, int literal, int full_path, int diff_mode)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006937{
6938 int i;
6939
6940 if (used_file_indexes == NULL)
6941 return;
6942 for (i = used_file_argc + 1; i < global_argc; ++i)
6943 if (STRCMP(global_argv[i], name) == 0)
6944 {
6945 used_file_argc = i;
6946 used_file_indexes[used_file_count++] = i;
6947 break;
6948 }
6949 used_file_literal = literal;
6950 used_file_full_path = full_path;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00006951 used_file_diff_mode = diff_mode;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006952}
6953
6954/*
6955 * Remember the length of the argument list as it was. If it changes then we
6956 * leave it alone when 'encoding' is set.
6957 */
6958 void
6959set_alist_count(void)
6960{
6961 used_alist_count = GARGCOUNT;
6962}
6963
6964/*
6965 * Fix the encoding of the command line arguments. Invoked when 'encoding'
6966 * has been changed while starting up. Use the UCS-2 command line arguments
6967 * and convert them to 'encoding'.
6968 */
6969 void
6970fix_arg_enc(void)
6971{
6972 int i;
6973 int idx;
6974 char_u *str;
Bram Moolenaar86b68352004-12-27 21:59:20 +00006975 int *fnum_list;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006976
6977 /* Safety checks:
6978 * - if argument count differs between the wide and non-wide argument
6979 * list, something must be wrong.
6980 * - the file name arguments must have been located.
6981 * - the length of the argument list wasn't changed by the user.
6982 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00006983 if (global_argc != nArgsW
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006984 || ArglistW == NULL
6985 || used_file_indexes == NULL
6986 || used_file_count == 0
6987 || used_alist_count != GARGCOUNT)
6988 return;
6989
Bram Moolenaar86b68352004-12-27 21:59:20 +00006990 /* Remember the buffer numbers for the arguments. */
6991 fnum_list = (int *)alloc((int)sizeof(int) * GARGCOUNT);
6992 if (fnum_list == NULL)
6993 return; /* out of memory */
6994 for (i = 0; i < GARGCOUNT; ++i)
6995 fnum_list[i] = GARGLIST[i].ae_fnum;
6996
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006997 /* Clear the argument list. Make room for the new arguments. */
6998 alist_clear(&global_alist);
6999 if (ga_grow(&global_alist.al_ga, used_file_count) == FAIL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00007000 return; /* out of memory */
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007001
7002 for (i = 0; i < used_file_count; ++i)
7003 {
7004 idx = used_file_indexes[i];
Bram Moolenaar36f692d2008-11-20 16:10:17 +00007005 str = utf16_to_enc(ArglistW[idx], NULL);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007006 if (str != NULL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00007007 {
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007008#ifdef FEAT_DIFF
7009 /* When using diff mode may need to concatenate file name to
7010 * directory name. Just like it's done in main(). */
7011 if (used_file_diff_mode && mch_isdir(str) && GARGCOUNT > 0
7012 && !mch_isdir(alist_name(&GARGLIST[0])))
7013 {
7014 char_u *r;
7015
7016 r = concat_fnames(str, gettail(alist_name(&GARGLIST[0])), TRUE);
7017 if (r != NULL)
7018 {
7019 vim_free(str);
7020 str = r;
7021 }
7022 }
7023#endif
Bram Moolenaar86b68352004-12-27 21:59:20 +00007024 /* Re-use the old buffer by renaming it. When not using literal
7025 * names it's done by alist_expand() below. */
7026 if (used_file_literal)
7027 buf_set_name(fnum_list[i], str);
7028
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007029 alist_add(&global_alist, str, used_file_literal ? 2 : 0);
Bram Moolenaar86b68352004-12-27 21:59:20 +00007030 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007031 }
7032
7033 if (!used_file_literal)
7034 {
7035 /* Now expand wildcards in the arguments. */
7036 /* Temporarily add '(' and ')' to 'isfname'. These are valid
7037 * filename characters but are excluded from 'isfname' to make
7038 * "gf" work on a file name in parenthesis (e.g.: see vim.h). */
7039 do_cmdline_cmd((char_u *)":let SaVe_ISF = &isf|set isf+=(,)");
Bram Moolenaar86b68352004-12-27 21:59:20 +00007040 alist_expand(fnum_list, used_alist_count);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007041 do_cmdline_cmd((char_u *)":let &isf = SaVe_ISF|unlet SaVe_ISF");
7042 }
7043
7044 /* If wildcard expansion failed, we are editing the first file of the
7045 * arglist and there is no file name: Edit the first argument now. */
7046 if (curwin->w_arg_idx == 0 && curbuf->b_fname == NULL)
7047 {
7048 do_cmdline_cmd((char_u *)":rewind");
7049 if (GARGCOUNT == 1 && used_file_full_path)
7050 (void)vim_chdirfile(alist_name(&GARGLIST[0]));
7051 }
Bram Moolenaar86b68352004-12-27 21:59:20 +00007052
7053 set_alist_count();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007054}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007055#endif