blob: eaa8ba5f5e3c0baf1fada2a14abf3999e98b0bec [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 Moolenaar4d919d72016-02-05 22:36:41 +01001131#ifdef FEAT_CHANNEL
1132 static int
1133handle_channel_event(void)
1134{
1135 int ret;
1136 fd_set rfds;
1137 int maxfd;
1138
1139 FD_ZERO(&rfds);
1140 maxfd = channel_select_setup(-1, &rfds);
1141 if (maxfd >= 0)
1142 {
1143 struct timeval tv;
1144
1145 tv.tv_sec = 0;
1146 tv.tv_usec = 0;
1147 ret = select(maxfd + 1, &rfds, NULL, NULL, &tv);
1148 if (ret > 0 && channel_select_check(ret, &rfds) > 0)
1149 return TRUE;
1150 }
1151 return FALSE;
1152}
1153#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001154
1155/*
1156 * Decode a MOUSE_EVENT. If it's a valid event, return MOUSE_LEFT,
1157 * MOUSE_MIDDLE, or MOUSE_RIGHT for a click; MOUSE_DRAG for a mouse
1158 * move with a button held down; and MOUSE_RELEASE after a MOUSE_DRAG
1159 * or a MOUSE_LEFT, _MIDDLE, or _RIGHT. We encode the button type,
1160 * the number of clicks, and the Shift/Ctrl/Alt modifiers in g_nMouseClick,
1161 * and we return the mouse position in g_xMouse and g_yMouse.
1162 *
1163 * Every MOUSE_LEFT, _MIDDLE, or _RIGHT will be followed by zero or more
1164 * MOUSE_DRAGs and one MOUSE_RELEASE. MOUSE_RELEASE will be followed only
1165 * by MOUSE_LEFT, _MIDDLE, or _RIGHT.
1166 *
1167 * For multiple clicks, we send, say, MOUSE_LEFT/1 click, MOUSE_RELEASE,
1168 * MOUSE_LEFT/2 clicks, MOUSE_RELEASE, MOUSE_LEFT/3 clicks, MOUSE_RELEASE, ....
1169 *
1170 * Windows will send us MOUSE_MOVED notifications whenever the mouse
1171 * moves, even if it stays within the same character cell. We ignore
1172 * all MOUSE_MOVED messages if the position hasn't really changed, and
1173 * we ignore all MOUSE_MOVED messages where no button is held down (i.e.,
1174 * we're only interested in MOUSE_DRAG).
1175 *
1176 * All of this is complicated by the code that fakes MOUSE_MIDDLE on
1177 * 2-button mouses by pressing the left & right buttons simultaneously.
1178 * In practice, it's almost impossible to click both at the same time,
1179 * so we need to delay a little. Also, we tend not to get MOUSE_RELEASE
1180 * in such cases, if the user is clicking quickly.
1181 */
1182 static BOOL
1183decode_mouse_event(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001184 MOUSE_EVENT_RECORD *pmer)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001185{
1186 static int s_nOldButton = -1;
1187 static int s_nOldMouseClick = -1;
1188 static int s_xOldMouse = -1;
1189 static int s_yOldMouse = -1;
1190 static linenr_T s_old_topline = 0;
1191#ifdef FEAT_DIFF
1192 static int s_old_topfill = 0;
1193#endif
1194 static int s_cClicks = 1;
1195 static BOOL s_fReleased = TRUE;
1196 static DWORD s_dwLastClickTime = 0;
1197 static BOOL s_fNextIsMiddle = FALSE;
1198
1199 static DWORD cButtons = 0; /* number of buttons supported */
1200
1201 const DWORD LEFT = FROM_LEFT_1ST_BUTTON_PRESSED;
1202 const DWORD MIDDLE = FROM_LEFT_2ND_BUTTON_PRESSED;
1203 const DWORD RIGHT = RIGHTMOST_BUTTON_PRESSED;
1204 const DWORD LEFT_RIGHT = LEFT | RIGHT;
1205
1206 int nButton;
1207
1208 if (cButtons == 0 && !GetNumberOfConsoleMouseButtons(&cButtons))
1209 cButtons = 2;
1210
1211 if (!g_fMouseAvail || !g_fMouseActive)
1212 {
1213 g_nMouseClick = -1;
1214 return FALSE;
1215 }
1216
1217 /* get a spurious MOUSE_EVENT immediately after receiving focus; ignore */
1218 if (g_fJustGotFocus)
1219 {
1220 g_fJustGotFocus = FALSE;
1221 return FALSE;
1222 }
1223
1224 /* unprocessed mouse click? */
1225 if (g_nMouseClick != -1)
1226 return TRUE;
1227
1228 nButton = -1;
1229 g_xMouse = pmer->dwMousePosition.X;
1230 g_yMouse = pmer->dwMousePosition.Y;
1231
1232 if (pmer->dwEventFlags == MOUSE_MOVED)
1233 {
1234 /* ignore MOUSE_MOVED events if (x, y) hasn't changed. (We get these
1235 * events even when the mouse moves only within a char cell.) */
1236 if (s_xOldMouse == g_xMouse && s_yOldMouse == g_yMouse)
1237 return FALSE;
1238 }
1239
1240 /* If no buttons are pressed... */
1241 if ((pmer->dwButtonState & ((1 << cButtons) - 1)) == 0)
1242 {
1243 /* If the last thing returned was MOUSE_RELEASE, ignore this */
1244 if (s_fReleased)
1245 return FALSE;
1246
1247 nButton = MOUSE_RELEASE;
1248 s_fReleased = TRUE;
1249 }
1250 else /* one or more buttons pressed */
1251 {
1252 /* on a 2-button mouse, hold down left and right buttons
1253 * simultaneously to get MIDDLE. */
1254
1255 if (cButtons == 2 && s_nOldButton != MOUSE_DRAG)
1256 {
1257 DWORD dwLR = (pmer->dwButtonState & LEFT_RIGHT);
1258
1259 /* if either left or right button only is pressed, see if the
Bram Moolenaar84a05ac2013-05-06 04:24:17 +02001260 * next mouse event has both of them pressed */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001261 if (dwLR == LEFT || dwLR == RIGHT)
1262 {
1263 for (;;)
1264 {
1265 /* wait a short time for next input event */
1266 if (WaitForSingleObject(g_hConIn, p_mouset / 3)
1267 != WAIT_OBJECT_0)
1268 break;
1269 else
1270 {
1271 DWORD cRecords = 0;
1272 INPUT_RECORD ir;
1273 MOUSE_EVENT_RECORD* pmer2 = &ir.Event.MouseEvent;
1274
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001275 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001276
1277 if (cRecords == 0 || ir.EventType != MOUSE_EVENT
1278 || !(pmer2->dwButtonState & LEFT_RIGHT))
1279 break;
1280 else
1281 {
1282 if (pmer2->dwEventFlags != MOUSE_MOVED)
1283 {
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001284 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001285
1286 return decode_mouse_event(pmer2);
1287 }
1288 else if (s_xOldMouse == pmer2->dwMousePosition.X &&
1289 s_yOldMouse == pmer2->dwMousePosition.Y)
1290 {
1291 /* throw away spurious mouse move */
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001292 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001293
1294 /* are there any more mouse events in queue? */
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001295 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001296
1297 if (cRecords==0 || ir.EventType != MOUSE_EVENT)
1298 break;
1299 }
1300 else
1301 break;
1302 }
1303 }
1304 }
1305 }
1306 }
1307
1308 if (s_fNextIsMiddle)
1309 {
1310 nButton = (pmer->dwEventFlags == MOUSE_MOVED)
1311 ? MOUSE_DRAG : MOUSE_MIDDLE;
1312 s_fNextIsMiddle = FALSE;
1313 }
1314 else if (cButtons == 2 &&
1315 ((pmer->dwButtonState & LEFT_RIGHT) == LEFT_RIGHT))
1316 {
1317 nButton = MOUSE_MIDDLE;
1318
1319 if (! s_fReleased && pmer->dwEventFlags != MOUSE_MOVED)
1320 {
1321 s_fNextIsMiddle = TRUE;
1322 nButton = MOUSE_RELEASE;
1323 }
1324 }
1325 else if ((pmer->dwButtonState & LEFT) == LEFT)
1326 nButton = MOUSE_LEFT;
1327 else if ((pmer->dwButtonState & MIDDLE) == MIDDLE)
1328 nButton = MOUSE_MIDDLE;
1329 else if ((pmer->dwButtonState & RIGHT) == RIGHT)
1330 nButton = MOUSE_RIGHT;
1331
1332 if (! s_fReleased && ! s_fNextIsMiddle
1333 && nButton != s_nOldButton && s_nOldButton != MOUSE_DRAG)
1334 return FALSE;
1335
1336 s_fReleased = s_fNextIsMiddle;
1337 }
1338
1339 if (pmer->dwEventFlags == 0 || pmer->dwEventFlags == DOUBLE_CLICK)
1340 {
1341 /* button pressed or released, without mouse moving */
1342 if (nButton != -1 && nButton != MOUSE_RELEASE)
1343 {
1344 DWORD dwCurrentTime = GetTickCount();
1345
1346 if (s_xOldMouse != g_xMouse
1347 || s_yOldMouse != g_yMouse
1348 || s_nOldButton != nButton
1349 || s_old_topline != curwin->w_topline
1350#ifdef FEAT_DIFF
1351 || s_old_topfill != curwin->w_topfill
1352#endif
1353 || (int)(dwCurrentTime - s_dwLastClickTime) > p_mouset)
1354 {
1355 s_cClicks = 1;
1356 }
1357 else if (++s_cClicks > 4)
1358 {
1359 s_cClicks = 1;
1360 }
1361
1362 s_dwLastClickTime = dwCurrentTime;
1363 }
1364 }
1365 else if (pmer->dwEventFlags == MOUSE_MOVED)
1366 {
1367 if (nButton != -1 && nButton != MOUSE_RELEASE)
1368 nButton = MOUSE_DRAG;
1369
1370 s_cClicks = 1;
1371 }
1372
1373 if (nButton == -1)
1374 return FALSE;
1375
1376 if (nButton != MOUSE_RELEASE)
1377 s_nOldButton = nButton;
1378
1379 g_nMouseClick = nButton;
1380
1381 if (pmer->dwControlKeyState & SHIFT_PRESSED)
1382 g_nMouseClick |= MOUSE_SHIFT;
1383 if (pmer->dwControlKeyState & (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED))
1384 g_nMouseClick |= MOUSE_CTRL;
1385 if (pmer->dwControlKeyState & (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED))
1386 g_nMouseClick |= MOUSE_ALT;
1387
1388 if (nButton != MOUSE_DRAG && nButton != MOUSE_RELEASE)
1389 SET_NUM_MOUSE_CLICKS(g_nMouseClick, s_cClicks);
1390
1391 /* only pass on interesting (i.e., different) mouse events */
1392 if (s_xOldMouse == g_xMouse
1393 && s_yOldMouse == g_yMouse
1394 && s_nOldMouseClick == g_nMouseClick)
1395 {
1396 g_nMouseClick = -1;
1397 return FALSE;
1398 }
1399
1400 s_xOldMouse = g_xMouse;
1401 s_yOldMouse = g_yMouse;
1402 s_old_topline = curwin->w_topline;
1403#ifdef FEAT_DIFF
1404 s_old_topfill = curwin->w_topfill;
1405#endif
1406 s_nOldMouseClick = g_nMouseClick;
1407
1408 return TRUE;
1409}
1410
1411# endif /* FEAT_GUI_W32 */
1412#endif /* FEAT_MOUSE */
1413
1414
1415#ifdef MCH_CURSOR_SHAPE
1416/*
1417 * Set the shape of the cursor.
1418 * 'thickness' can be from 1 (thin) to 99 (block)
1419 */
1420 static void
1421mch_set_cursor_shape(int thickness)
1422{
1423 CONSOLE_CURSOR_INFO ConsoleCursorInfo;
1424 ConsoleCursorInfo.dwSize = thickness;
1425 ConsoleCursorInfo.bVisible = s_cursor_visible;
1426
1427 SetConsoleCursorInfo(g_hConOut, &ConsoleCursorInfo);
1428 if (s_cursor_visible)
1429 SetConsoleCursorPosition(g_hConOut, g_coord);
1430}
1431
1432 void
1433mch_update_cursor(void)
1434{
1435 int idx;
1436 int thickness;
1437
1438 /*
1439 * How the cursor is drawn depends on the current mode.
1440 */
1441 idx = get_shape_idx(FALSE);
1442
1443 if (shape_table[idx].shape == SHAPE_BLOCK)
1444 thickness = 99; /* 100 doesn't work on W95 */
1445 else
1446 thickness = shape_table[idx].percentage;
1447 mch_set_cursor_shape(thickness);
1448}
1449#endif
1450
1451#ifndef FEAT_GUI_W32 /* this isn't used for the GUI */
1452/*
1453 * Handle FOCUS_EVENT.
1454 */
1455 static void
1456handle_focus_event(INPUT_RECORD ir)
1457{
1458 g_fJustGotFocus = ir.Event.FocusEvent.bSetFocus;
1459 ui_focus_change((int)g_fJustGotFocus);
1460}
1461
1462/*
1463 * Wait until console input from keyboard or mouse is available,
1464 * or the time is up.
1465 * Return TRUE if something is available FALSE if not.
1466 */
1467 static int
1468WaitForChar(long msec)
1469{
1470 DWORD dwNow = 0, dwEndTime = 0;
1471 INPUT_RECORD ir;
1472 DWORD cRecords;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001473 WCHAR ch, ch2;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001474
1475 if (msec > 0)
1476 /* Wait until the specified time has elapsed. */
1477 dwEndTime = GetTickCount() + msec;
1478 else if (msec < 0)
1479 /* Wait forever. */
1480 dwEndTime = INFINITE;
1481
1482 /* We need to loop until the end of the time period, because
1483 * we might get multiple unusable mouse events in that time.
1484 */
1485 for (;;)
1486 {
Bram Moolenaarca568ae2016-02-01 21:32:58 +01001487#ifdef MESSAGE_QUEUE
1488 parse_queued_messages();
1489#endif
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001490#ifdef FEAT_MZSCHEME
1491 mzvim_check_threads();
1492#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001493#ifdef FEAT_CLIENTSERVER
1494 serverProcessPendingMessages();
1495#endif
Bram Moolenaarf12d9832016-01-29 21:11:25 +01001496
1497#ifdef FEAT_CHANNEL
Bram Moolenaar4d919d72016-02-05 22:36:41 +01001498 if (handle_channel_event())
1499 return TRUE;
Bram Moolenaarf12d9832016-01-29 21:11:25 +01001500#endif
1501
Bram Moolenaar071d4272004-06-13 20:20:40 +00001502 if (0
1503#ifdef FEAT_MOUSE
1504 || g_nMouseClick != -1
1505#endif
1506#ifdef FEAT_CLIENTSERVER
1507 || input_available()
1508#endif
1509 )
1510 return TRUE;
1511
1512 if (msec > 0)
1513 {
Bram Moolenaarb7512b72013-08-10 12:45:09 +02001514 /* If the specified wait time has passed, return. Beware that
1515 * GetTickCount() may wrap around (overflow). */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001516 dwNow = GetTickCount();
Bram Moolenaarb7512b72013-08-10 12:45:09 +02001517 if ((int)(dwNow - dwEndTime) >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001518 break;
1519 }
1520 if (msec != 0)
1521 {
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001522 DWORD dwWaitTime = dwEndTime - dwNow;
1523
1524#ifdef FEAT_MZSCHEME
1525 if (mzthreads_allowed() && p_mzq > 0
1526 && (msec < 0 || (long)dwWaitTime > p_mzq))
1527 dwWaitTime = p_mzq; /* don't wait longer than 'mzquantum' */
1528#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001529#ifdef FEAT_CLIENTSERVER
1530 /* Wait for either an event on the console input or a message in
1531 * the client-server window. */
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +02001532 if (msg_wait_for_multiple_objects(1, &g_hConIn, FALSE,
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001533 dwWaitTime, QS_SENDMESSAGE) != WAIT_OBJECT_0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001534#else
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +02001535 if (wait_for_single_object(g_hConIn, dwWaitTime) != WAIT_OBJECT_0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001536#endif
1537 continue;
1538 }
1539
1540 cRecords = 0;
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001541 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001542
1543#ifdef FEAT_MBYTE_IME
1544 if (State & CMDLINE && msg_row == Rows - 1)
1545 {
1546 CONSOLE_SCREEN_BUFFER_INFO csbi;
1547
1548 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
1549 {
1550 if (csbi.dwCursorPosition.Y != msg_row)
1551 {
1552 /* The screen is now messed up, must redraw the
1553 * command line and later all the windows. */
1554 redraw_all_later(CLEAR);
1555 cmdline_row -= (msg_row - csbi.dwCursorPosition.Y);
1556 redrawcmd();
1557 }
1558 }
1559 }
1560#endif
1561
1562 if (cRecords > 0)
1563 {
1564 if (ir.EventType == KEY_EVENT && ir.Event.KeyEvent.bKeyDown)
1565 {
1566#ifdef FEAT_MBYTE_IME
1567 /* Windows IME sends two '\n's with only one 'ENTER'. First:
1568 * wVirtualKeyCode == 13. second: wVirtualKeyCode == 0 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001569 if (ir.Event.KeyEvent.UChar == 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00001570 && ir.Event.KeyEvent.wVirtualKeyCode == 13)
1571 {
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001572 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001573 continue;
1574 }
1575#endif
1576 if (decode_key_event(&ir.Event.KeyEvent, &ch, &ch2,
1577 NULL, FALSE))
1578 return TRUE;
1579 }
1580
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001581 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001582
1583 if (ir.EventType == FOCUS_EVENT)
1584 handle_focus_event(ir);
1585 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
1586 shell_resized();
1587#ifdef FEAT_MOUSE
1588 else if (ir.EventType == MOUSE_EVENT
1589 && decode_mouse_event(&ir.Event.MouseEvent))
1590 return TRUE;
1591#endif
1592 }
1593 else if (msec == 0)
1594 break;
1595 }
1596
1597#ifdef FEAT_CLIENTSERVER
1598 /* Something might have been received while we were waiting. */
1599 if (input_available())
1600 return TRUE;
1601#endif
Bram Moolenaarf12d9832016-01-29 21:11:25 +01001602
Bram Moolenaar071d4272004-06-13 20:20:40 +00001603 return FALSE;
1604}
1605
1606#ifndef FEAT_GUI_MSWIN
1607/*
1608 * return non-zero if a character is available
1609 */
1610 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001611mch_char_avail(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001612{
1613 return WaitForChar(0L);
1614}
1615#endif
1616
1617/*
1618 * Create the console input. Used when reading stdin doesn't work.
1619 */
1620 static void
1621create_conin(void)
1622{
1623 g_hConIn = CreateFile("CONIN$", GENERIC_READ|GENERIC_WRITE,
1624 FILE_SHARE_READ|FILE_SHARE_WRITE,
1625 (LPSECURITY_ATTRIBUTES) NULL,
Bram Moolenaareb3593b2006-04-22 22:33:57 +00001626 OPEN_EXISTING, 0, (HANDLE)NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001627 did_create_conin = TRUE;
1628}
1629
1630/*
1631 * Get a keystroke or a mouse event
1632 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001633 static WCHAR
1634tgetch(int *pmodifiers, WCHAR *pch2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001635{
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001636 WCHAR ch;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001637
1638 for (;;)
1639 {
1640 INPUT_RECORD ir;
1641 DWORD cRecords = 0;
1642
1643#ifdef FEAT_CLIENTSERVER
1644 (void)WaitForChar(-1L);
1645 if (input_available())
1646 return 0;
1647# ifdef FEAT_MOUSE
1648 if (g_nMouseClick != -1)
1649 return 0;
1650# endif
1651#endif
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001652 if (read_console_input(g_hConIn, &ir, 1, &cRecords) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001653 {
1654 if (did_create_conin)
1655 read_error_exit();
1656 create_conin();
1657 continue;
1658 }
1659
1660 if (ir.EventType == KEY_EVENT)
1661 {
1662 if (decode_key_event(&ir.Event.KeyEvent, &ch, pch2,
1663 pmodifiers, TRUE))
1664 return ch;
1665 }
1666 else if (ir.EventType == FOCUS_EVENT)
1667 handle_focus_event(ir);
1668 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
1669 shell_resized();
1670#ifdef FEAT_MOUSE
1671 else if (ir.EventType == MOUSE_EVENT)
1672 {
1673 if (decode_mouse_event(&ir.Event.MouseEvent))
1674 return 0;
1675 }
1676#endif
1677 }
1678}
1679#endif /* !FEAT_GUI_W32 */
1680
1681
1682/*
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02001683 * mch_inchar(): low-level input function.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001684 * Get one or more characters from the keyboard or the mouse.
1685 * If time == 0, do not wait for characters.
1686 * If time == n, wait a short time for characters.
1687 * If time == -1, wait forever for characters.
1688 * Returns the number of characters read into buf.
1689 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00001690/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00001691 int
1692mch_inchar(
1693 char_u *buf,
1694 int maxlen,
1695 long time,
1696 int tb_change_cnt)
1697{
1698#ifndef FEAT_GUI_W32 /* this isn't used for the GUI */
1699
1700 int len;
1701 int c;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001702#define TYPEAHEADLEN 20
1703 static char_u typeahead[TYPEAHEADLEN]; /* previously typed bytes. */
1704 static int typeaheadlen = 0;
1705
1706 /* First use any typeahead that was kept because "buf" was too small. */
1707 if (typeaheadlen > 0)
1708 goto theend;
1709
1710#ifdef FEAT_SNIFF
1711 if (want_sniff_request)
1712 {
1713 if (sniff_request_waiting)
1714 {
1715 /* return K_SNIFF */
1716 typeahead[typeaheadlen++] = CSI;
1717 typeahead[typeaheadlen++] = (char_u)KS_EXTRA;
1718 typeahead[typeaheadlen++] = (char_u)KE_SNIFF;
1719 sniff_request_waiting = 0;
1720 want_sniff_request = 0;
1721 goto theend;
1722 }
1723 else if (time < 0 || time > 250)
1724 {
1725 /* don't wait too long, a request might be pending */
1726 time = 250;
1727 }
1728 }
1729#endif
1730
1731 if (time >= 0)
1732 {
1733 if (!WaitForChar(time)) /* no character available */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001734 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001735 }
1736 else /* time == -1, wait forever */
1737 {
1738 mch_set_winsize_now(); /* Allow winsize changes from now on */
1739
Bram Moolenaar3918c952005-03-15 22:34:55 +00001740 /*
1741 * If there is no character available within 2 seconds (default)
1742 * write the autoscript file to disk. Or cause the CursorHold event
1743 * to be triggered.
1744 */
1745 if (!WaitForChar(p_ut))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001746 {
1747#ifdef FEAT_AUTOCMD
Bram Moolenaard35f9712005-12-18 22:02:33 +00001748 if (trigger_cursorhold() && maxlen >= 3)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001749 {
Bram Moolenaar3918c952005-03-15 22:34:55 +00001750 buf[0] = K_SPECIAL;
1751 buf[1] = KS_EXTRA;
1752 buf[2] = (int)KE_CURSORHOLD;
1753 return 3;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001754 }
1755#endif
Bram Moolenaar702517d2005-06-27 22:34:07 +00001756 before_blocking();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001757 }
1758 }
1759
1760 /*
1761 * Try to read as many characters as there are, until the buffer is full.
1762 */
1763
1764 /* we will get at least one key. Get more if they are available. */
1765 g_fCBrkPressed = FALSE;
1766
1767#ifdef MCH_WRITE_DUMP
1768 if (fdDump)
1769 fputc('[', fdDump);
1770#endif
1771
1772 /* Keep looping until there is something in the typeahead buffer and more
1773 * to get and still room in the buffer (up to two bytes for a char and
1774 * three bytes for a modifier). */
1775 while ((typeaheadlen == 0 || WaitForChar(0L))
1776 && typeaheadlen + 5 <= TYPEAHEADLEN)
1777 {
1778 if (typebuf_changed(tb_change_cnt))
1779 {
1780 /* "buf" may be invalid now if a client put something in the
1781 * typeahead buffer and "buf" is in the typeahead buffer. */
1782 typeaheadlen = 0;
1783 break;
1784 }
1785#ifdef FEAT_MOUSE
1786 if (g_nMouseClick != -1)
1787 {
1788# ifdef MCH_WRITE_DUMP
1789 if (fdDump)
1790 fprintf(fdDump, "{%02x @ %d, %d}",
1791 g_nMouseClick, g_xMouse, g_yMouse);
1792# endif
1793 typeahead[typeaheadlen++] = ESC + 128;
1794 typeahead[typeaheadlen++] = 'M';
1795 typeahead[typeaheadlen++] = g_nMouseClick;
1796 typeahead[typeaheadlen++] = g_xMouse + '!';
1797 typeahead[typeaheadlen++] = g_yMouse + '!';
1798 g_nMouseClick = -1;
1799 }
1800 else
1801#endif
1802 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001803 WCHAR ch2 = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001804 int modifiers = 0;
1805
1806 c = tgetch(&modifiers, &ch2);
1807
1808 if (typebuf_changed(tb_change_cnt))
1809 {
1810 /* "buf" may be invalid now if a client put something in the
1811 * typeahead buffer and "buf" is in the typeahead buffer. */
1812 typeaheadlen = 0;
1813 break;
1814 }
1815
1816 if (c == Ctrl_C && ctrl_c_interrupts)
1817 {
1818#if defined(FEAT_CLIENTSERVER)
1819 trash_input_buf();
1820#endif
1821 got_int = TRUE;
1822 }
1823
1824#ifdef FEAT_MOUSE
1825 if (g_nMouseClick == -1)
1826#endif
1827 {
1828 int n = 1;
Bram Moolenaar45500912014-07-09 20:51:07 +02001829 int conv = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001830
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001831#ifdef FEAT_MBYTE
1832 if (ch2 == NUL)
1833 {
1834 int i;
1835 char_u *p;
1836 WCHAR ch[2];
1837
1838 ch[0] = c;
1839 if (c >= 0xD800 && c <= 0xDBFF) /* High surrogate */
1840 {
1841 ch[1] = tgetch(&modifiers, &ch2);
1842 n++;
1843 }
1844 p = utf16_to_enc(ch, &n);
1845 if (p != NULL)
1846 {
1847 for (i = 0; i < n; i++)
1848 typeahead[typeaheadlen + i] = p[i];
1849 vim_free(p);
1850 }
1851 }
1852 else
1853#endif
1854 typeahead[typeaheadlen] = c;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001855 if (ch2 != NUL)
1856 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001857 typeahead[typeaheadlen + n] = 3;
1858 typeahead[typeaheadlen + n + 1] = (char_u)ch2;
Bram Moolenaar45500912014-07-09 20:51:07 +02001859 n += 2;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001860 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001861
Bram Moolenaar45500912014-07-09 20:51:07 +02001862 if (conv)
1863 {
1864 char_u *p = typeahead + typeaheadlen;
Bram Moolenaar45500912014-07-09 20:51:07 +02001865
Bram Moolenaar1ec4dd42015-01-20 19:39:35 +01001866 if (*p != K_NUL)
Bram Moolenaar45500912014-07-09 20:51:07 +02001867 {
Bram Moolenaar1ec4dd42015-01-20 19:39:35 +01001868 char_u *e = typeahead + TYPEAHEADLEN;
1869
1870 while (*p && p < e)
Bram Moolenaar45500912014-07-09 20:51:07 +02001871 {
Bram Moolenaar1ec4dd42015-01-20 19:39:35 +01001872 if (*p == K_NUL)
1873 {
1874 ++p;
1875 mch_memmove(p + 1, p, ((size_t)(e - p)) - 1);
1876 *p = 3;
1877 ++n;
1878 }
Bram Moolenaar45500912014-07-09 20:51:07 +02001879 ++p;
Bram Moolenaar45500912014-07-09 20:51:07 +02001880 }
Bram Moolenaar45500912014-07-09 20:51:07 +02001881 }
1882 }
1883
Bram Moolenaar071d4272004-06-13 20:20:40 +00001884 /* Use the ALT key to set the 8th bit of the character
1885 * when it's one byte, the 8th bit isn't set yet and not
1886 * using a double-byte encoding (would become a lead
1887 * byte). */
1888 if ((modifiers & MOD_MASK_ALT)
1889 && n == 1
1890 && (typeahead[typeaheadlen] & 0x80) == 0
1891#ifdef FEAT_MBYTE
1892 && !enc_dbcs
1893#endif
1894 )
1895 {
Bram Moolenaar85a3e5c2007-11-20 16:22:16 +00001896#ifdef FEAT_MBYTE
1897 n = (*mb_char2bytes)(typeahead[typeaheadlen] | 0x80,
1898 typeahead + typeaheadlen);
1899#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00001900 typeahead[typeaheadlen] |= 0x80;
Bram Moolenaar85a3e5c2007-11-20 16:22:16 +00001901#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001902 modifiers &= ~MOD_MASK_ALT;
1903 }
1904
1905 if (modifiers != 0)
1906 {
1907 /* Prepend modifiers to the character. */
1908 mch_memmove(typeahead + typeaheadlen + 3,
1909 typeahead + typeaheadlen, n);
1910 typeahead[typeaheadlen++] = K_SPECIAL;
1911 typeahead[typeaheadlen++] = (char_u)KS_MODIFIER;
1912 typeahead[typeaheadlen++] = modifiers;
1913 }
1914
1915 typeaheadlen += n;
1916
1917#ifdef MCH_WRITE_DUMP
1918 if (fdDump)
1919 fputc(c, fdDump);
1920#endif
1921 }
1922 }
1923 }
1924
1925#ifdef MCH_WRITE_DUMP
1926 if (fdDump)
1927 {
1928 fputs("]\n", fdDump);
1929 fflush(fdDump);
1930 }
1931#endif
1932
Bram Moolenaar071d4272004-06-13 20:20:40 +00001933theend:
1934 /* Move typeahead to "buf", as much as fits. */
1935 len = 0;
1936 while (len < maxlen && typeaheadlen > 0)
1937 {
1938 buf[len++] = typeahead[0];
1939 mch_memmove(typeahead, typeahead + 1, --typeaheadlen);
1940 }
1941 return len;
1942
1943#else /* FEAT_GUI_W32 */
1944 return 0;
1945#endif /* FEAT_GUI_W32 */
1946}
1947
Bram Moolenaar82881492012-11-20 16:53:39 +01001948#ifndef PROTO
1949# ifndef __MINGW32__
1950# include <shellapi.h> /* required for FindExecutable() */
1951# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001952#endif
1953
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001954/*
1955 * Return TRUE if "name" is in $PATH.
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00001956 * TODO: Should somehow check if it's really executable.
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001957 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001958 static int
Bram Moolenaarc7f02552014-04-01 21:00:59 +02001959executable_exists(char *name, char_u **path)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001960{
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001961 char *dum;
1962 char fname[_MAX_PATH];
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02001963 char *curpath, *newpath;
1964 long n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001965
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001966#ifdef FEAT_MBYTE
1967 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001968 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01001969 WCHAR *p = enc_to_utf16((char_u *)name, NULL);
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001970 WCHAR fnamew[_MAX_PATH];
1971 WCHAR *dumw;
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02001972 WCHAR *wcurpath, *wnewpath;
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001973
1974 if (p != NULL)
1975 {
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02001976 wcurpath = _wgetenv(L"PATH");
1977 wnewpath = (WCHAR*)alloc((unsigned)(wcslen(wcurpath) + 3)
1978 * sizeof(WCHAR));
1979 if (wnewpath == NULL)
1980 return FALSE;
1981 wcscpy(wnewpath, L".;");
1982 wcscat(wnewpath, wcurpath);
1983 n = (long)SearchPathW(wnewpath, p, NULL, _MAX_PATH, fnamew, &dumw);
1984 vim_free(wnewpath);
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001985 vim_free(p);
1986 if (n > 0 || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
1987 {
1988 if (n == 0)
1989 return FALSE;
1990 if (GetFileAttributesW(fnamew) & FILE_ATTRIBUTE_DIRECTORY)
1991 return FALSE;
Bram Moolenaarc7f02552014-04-01 21:00:59 +02001992 if (path != NULL)
1993 *path = utf16_to_enc(fnamew, NULL);
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001994 return TRUE;
1995 }
1996 /* Retry with non-wide function (for Windows 98). */
1997 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001998 }
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001999#endif
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02002000
2001 curpath = getenv("PATH");
2002 newpath = (char*)alloc((unsigned)(STRLEN(curpath) + 3));
2003 if (newpath == NULL)
2004 return FALSE;
2005 STRCPY(newpath, ".;");
2006 STRCAT(newpath, curpath);
2007 n = (long)SearchPath(newpath, name, NULL, _MAX_PATH, fname, &dum);
2008 vim_free(newpath);
2009 if (n == 0)
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002010 return FALSE;
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002011 if (mch_isdir((char_u *)fname))
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002012 return FALSE;
Bram Moolenaarc7f02552014-04-01 21:00:59 +02002013 if (path != NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002014 *path = vim_strsave((char_u *)fname);
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002015 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002016}
2017
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002018#if ((defined(__MINGW32__) || defined (__CYGWIN32__)) && \
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02002019 __MSVCRT_VERSION__ >= 0x800) || (defined(_MSC_VER) && _MSC_VER >= 1400)
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002020/*
2021 * Bad parameter handler.
2022 *
2023 * Certain MS CRT functions will intentionally crash when passed invalid
2024 * parameters to highlight possible security holes. Setting this function as
2025 * the bad parameter handler will prevent the crash.
2026 *
2027 * In debug builds the parameters contain CRT information that might help track
2028 * down the source of a problem, but in non-debug builds the arguments are all
2029 * NULL/0. Debug builds will also produce assert dialogs from the CRT, it is
2030 * worth allowing these to make debugging of issues easier.
2031 */
2032 static void
2033bad_param_handler(const wchar_t *expression,
2034 const wchar_t *function,
2035 const wchar_t *file,
2036 unsigned int line,
2037 uintptr_t pReserved)
2038{
2039}
2040
2041# define SET_INVALID_PARAM_HANDLER \
2042 ((void)_set_invalid_parameter_handler(bad_param_handler))
2043#else
2044# define SET_INVALID_PARAM_HANDLER
2045#endif
2046
Bram Moolenaar071d4272004-06-13 20:20:40 +00002047#ifdef FEAT_GUI_W32
2048
2049/*
2050 * GUI version of mch_init().
2051 */
2052 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002053mch_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002054{
2055#ifndef __MINGW32__
2056 extern int _fmode;
2057#endif
2058
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002059 /* Silently handle invalid parameters to CRT functions */
2060 SET_INVALID_PARAM_HANDLER;
2061
Bram Moolenaar071d4272004-06-13 20:20:40 +00002062 /* Let critical errors result in a failure, not in a dialog box. Required
2063 * for the timestamp test to work on removed floppies. */
2064 SetErrorMode(SEM_FAILCRITICALERRORS);
2065
2066 _fmode = O_BINARY; /* we do our own CR-LF translation */
2067
2068 /* Specify window size. Is there a place to get the default from? */
2069 Rows = 25;
2070 Columns = 80;
2071
2072 /* Look for 'vimrun' */
2073 if (!gui_is_win32s())
2074 {
2075 char_u vimrun_location[_MAX_PATH + 4];
2076
2077 /* First try in same directory as gvim.exe */
2078 STRCPY(vimrun_location, exe_name);
2079 STRCPY(gettail(vimrun_location), "vimrun.exe");
2080 if (mch_getperm(vimrun_location) >= 0)
2081 {
2082 if (*skiptowhite(vimrun_location) != NUL)
2083 {
2084 /* Enclose path with white space in double quotes. */
2085 mch_memmove(vimrun_location + 1, vimrun_location,
2086 STRLEN(vimrun_location) + 1);
2087 *vimrun_location = '"';
2088 STRCPY(gettail(vimrun_location), "vimrun\" ");
2089 }
2090 else
2091 STRCPY(gettail(vimrun_location), "vimrun ");
2092
2093 vimrun_path = (char *)vim_strsave(vimrun_location);
2094 s_dont_use_vimrun = FALSE;
2095 }
Bram Moolenaarc7f02552014-04-01 21:00:59 +02002096 else if (executable_exists("vimrun.exe", NULL))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002097 s_dont_use_vimrun = FALSE;
2098
2099 /* Don't give the warning for a missing vimrun.exe right now, but only
2100 * when vimrun was supposed to be used. Don't bother people that do
2101 * not need vimrun.exe. */
2102 if (s_dont_use_vimrun)
2103 need_vimrun_warning = TRUE;
2104 }
2105
2106 /*
2107 * If "finstr.exe" doesn't exist, use "grep -n" for 'grepprg'.
2108 * Otherwise the default "findstr /n" is used.
2109 */
Bram Moolenaarc7f02552014-04-01 21:00:59 +02002110 if (!executable_exists("findstr.exe", NULL))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002111 set_option_value((char_u *)"grepprg", 0, (char_u *)"grep -n", 0);
2112
2113#ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01002114 win_clip_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002115#endif
2116}
2117
2118
2119#else /* FEAT_GUI_W32 */
2120
2121#define SRWIDTH(sr) ((sr).Right - (sr).Left + 1)
2122#define SRHEIGHT(sr) ((sr).Bottom - (sr).Top + 1)
2123
2124/*
2125 * ClearConsoleBuffer()
2126 * Description:
2127 * Clears the entire contents of the console screen buffer, using the
2128 * specified attribute.
2129 * Returns:
2130 * TRUE on success
2131 */
2132 static BOOL
2133ClearConsoleBuffer(WORD wAttribute)
2134{
2135 CONSOLE_SCREEN_BUFFER_INFO csbi;
2136 COORD coord;
2137 DWORD NumCells, dummy;
2138
2139 if (!GetConsoleScreenBufferInfo(g_hConOut, &csbi))
2140 return FALSE;
2141
2142 NumCells = csbi.dwSize.X * csbi.dwSize.Y;
2143 coord.X = 0;
2144 coord.Y = 0;
2145 if (!FillConsoleOutputCharacter(g_hConOut, ' ', NumCells,
2146 coord, &dummy))
2147 {
2148 return FALSE;
2149 }
2150 if (!FillConsoleOutputAttribute(g_hConOut, wAttribute, NumCells,
2151 coord, &dummy))
2152 {
2153 return FALSE;
2154 }
2155
2156 return TRUE;
2157}
2158
2159/*
2160 * FitConsoleWindow()
2161 * Description:
2162 * Checks if the console window will fit within given buffer dimensions.
2163 * Also, if requested, will shrink the window to fit.
2164 * Returns:
2165 * TRUE on success
2166 */
2167 static BOOL
2168FitConsoleWindow(
2169 COORD dwBufferSize,
2170 BOOL WantAdjust)
2171{
2172 CONSOLE_SCREEN_BUFFER_INFO csbi;
2173 COORD dwWindowSize;
2174 BOOL NeedAdjust = FALSE;
2175
2176 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
2177 {
2178 /*
2179 * A buffer resize will fail if the current console window does
2180 * not lie completely within that buffer. To avoid this, we might
2181 * have to move and possibly shrink the window.
2182 */
2183 if (csbi.srWindow.Right >= dwBufferSize.X)
2184 {
2185 dwWindowSize.X = SRWIDTH(csbi.srWindow);
2186 if (dwWindowSize.X > dwBufferSize.X)
2187 dwWindowSize.X = dwBufferSize.X;
2188 csbi.srWindow.Right = dwBufferSize.X - 1;
2189 csbi.srWindow.Left = dwBufferSize.X - dwWindowSize.X;
2190 NeedAdjust = TRUE;
2191 }
2192 if (csbi.srWindow.Bottom >= dwBufferSize.Y)
2193 {
2194 dwWindowSize.Y = SRHEIGHT(csbi.srWindow);
2195 if (dwWindowSize.Y > dwBufferSize.Y)
2196 dwWindowSize.Y = dwBufferSize.Y;
2197 csbi.srWindow.Bottom = dwBufferSize.Y - 1;
2198 csbi.srWindow.Top = dwBufferSize.Y - dwWindowSize.Y;
2199 NeedAdjust = TRUE;
2200 }
2201 if (NeedAdjust && WantAdjust)
2202 {
2203 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &csbi.srWindow))
2204 return FALSE;
2205 }
2206 return TRUE;
2207 }
2208
2209 return FALSE;
2210}
2211
2212typedef struct ConsoleBufferStruct
2213{
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002214 BOOL IsValid;
2215 CONSOLE_SCREEN_BUFFER_INFO Info;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002216 PCHAR_INFO Buffer;
2217 COORD BufferSize;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002218} ConsoleBuffer;
2219
2220/*
2221 * SaveConsoleBuffer()
2222 * Description:
2223 * Saves important information about the console buffer, including the
2224 * actual buffer contents. The saved information is suitable for later
2225 * restoration by RestoreConsoleBuffer().
2226 * Returns:
2227 * TRUE if all information was saved; FALSE otherwise
2228 * If FALSE, still sets cb->IsValid if buffer characteristics were saved.
2229 */
2230 static BOOL
2231SaveConsoleBuffer(
2232 ConsoleBuffer *cb)
2233{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002234 DWORD NumCells;
2235 COORD BufferCoord;
2236 SMALL_RECT ReadRegion;
2237 WORD Y, Y_incr;
2238
Bram Moolenaar071d4272004-06-13 20:20:40 +00002239 if (cb == NULL)
2240 return FALSE;
2241
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002242 if (!GetConsoleScreenBufferInfo(g_hConOut, &cb->Info))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002243 {
2244 cb->IsValid = FALSE;
2245 return FALSE;
2246 }
2247 cb->IsValid = TRUE;
2248
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002249 /*
2250 * Allocate a buffer large enough to hold the entire console screen
2251 * buffer. If this ConsoleBuffer structure has already been initialized
2252 * with a buffer of the correct size, then just use that one.
2253 */
2254 if (!cb->IsValid || cb->Buffer == NULL ||
2255 cb->BufferSize.X != cb->Info.dwSize.X ||
2256 cb->BufferSize.Y != cb->Info.dwSize.Y)
2257 {
2258 cb->BufferSize.X = cb->Info.dwSize.X;
2259 cb->BufferSize.Y = cb->Info.dwSize.Y;
2260 NumCells = cb->BufferSize.X * cb->BufferSize.Y;
2261 vim_free(cb->Buffer);
2262 cb->Buffer = (PCHAR_INFO)alloc(NumCells * sizeof(CHAR_INFO));
2263 if (cb->Buffer == NULL)
2264 return FALSE;
2265 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002266
2267 /*
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002268 * We will now copy the console screen buffer into our buffer.
2269 * ReadConsoleOutput() seems to be limited as far as how much you
2270 * can read at a time. Empirically, this number seems to be about
2271 * 12000 cells (rows * columns). Start at position (0, 0) and copy
2272 * in chunks until it is all copied. The chunks will all have the
2273 * same horizontal characteristics, so initialize them now. The
2274 * height of each chunk will be (12000 / width).
Bram Moolenaar071d4272004-06-13 20:20:40 +00002275 */
Bram Moolenaar61594242015-09-01 20:23:37 +02002276 BufferCoord.X = 0;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002277 ReadRegion.Left = 0;
2278 ReadRegion.Right = cb->Info.dwSize.X - 1;
2279 Y_incr = 12000 / cb->Info.dwSize.X;
2280 for (Y = 0; Y < cb->BufferSize.Y; Y += Y_incr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002281 {
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002282 /*
2283 * Read into position (0, Y) in our buffer.
2284 */
2285 BufferCoord.Y = Y;
2286 /*
2287 * Read the region whose top left corner is (0, Y) and whose bottom
2288 * right corner is (width - 1, Y + Y_incr - 1). This should define
2289 * a region of size width by Y_incr. Don't worry if this region is
2290 * too large for the remaining buffer; it will be cropped.
2291 */
2292 ReadRegion.Top = Y;
2293 ReadRegion.Bottom = Y + Y_incr - 1;
2294 if (!ReadConsoleOutput(g_hConOut, /* output handle */
2295 cb->Buffer, /* our buffer */
2296 cb->BufferSize, /* dimensions of our buffer */
2297 BufferCoord, /* offset in our buffer */
2298 &ReadRegion)) /* region to save */
2299 {
2300 vim_free(cb->Buffer);
2301 cb->Buffer = NULL;
2302 return FALSE;
2303 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002304 }
2305
2306 return TRUE;
2307}
2308
2309/*
2310 * RestoreConsoleBuffer()
2311 * Description:
2312 * Restores important information about the console buffer, including the
2313 * actual buffer contents, if desired. The information to restore is in
2314 * the same format used by SaveConsoleBuffer().
2315 * Returns:
2316 * TRUE on success
2317 */
2318 static BOOL
2319RestoreConsoleBuffer(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002320 ConsoleBuffer *cb,
2321 BOOL RestoreScreen)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002322{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002323 COORD BufferCoord;
2324 SMALL_RECT WriteRegion;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002325
2326 if (cb == NULL || !cb->IsValid)
2327 return FALSE;
2328
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002329 /*
2330 * Before restoring the buffer contents, clear the current buffer, and
2331 * restore the cursor position and window information. Doing this now
2332 * prevents old buffer contents from "flashing" onto the screen.
2333 */
2334 if (RestoreScreen)
2335 ClearConsoleBuffer(cb->Info.wAttributes);
2336
2337 FitConsoleWindow(cb->Info.dwSize, TRUE);
2338 if (!SetConsoleScreenBufferSize(g_hConOut, cb->Info.dwSize))
2339 return FALSE;
2340 if (!SetConsoleTextAttribute(g_hConOut, cb->Info.wAttributes))
2341 return FALSE;
2342
2343 if (!RestoreScreen)
2344 {
2345 /*
2346 * No need to restore the screen buffer contents, so we're done.
2347 */
2348 return TRUE;
2349 }
2350
2351 if (!SetConsoleCursorPosition(g_hConOut, cb->Info.dwCursorPosition))
2352 return FALSE;
2353 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &cb->Info.srWindow))
2354 return FALSE;
2355
2356 /*
2357 * Restore the screen buffer contents.
2358 */
2359 if (cb->Buffer != NULL)
2360 {
2361 BufferCoord.X = 0;
2362 BufferCoord.Y = 0;
2363 WriteRegion.Left = 0;
2364 WriteRegion.Top = 0;
2365 WriteRegion.Right = cb->Info.dwSize.X - 1;
2366 WriteRegion.Bottom = cb->Info.dwSize.Y - 1;
2367 if (!WriteConsoleOutput(g_hConOut, /* output handle */
2368 cb->Buffer, /* our buffer */
2369 cb->BufferSize, /* dimensions of our buffer */
2370 BufferCoord, /* offset in our buffer */
2371 &WriteRegion)) /* region to restore */
2372 {
2373 return FALSE;
2374 }
2375 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002376
2377 return TRUE;
2378}
2379
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002380#define FEAT_RESTORE_ORIG_SCREEN
2381#ifdef FEAT_RESTORE_ORIG_SCREEN
2382static ConsoleBuffer g_cbOrig = { 0 };
2383#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002384static ConsoleBuffer g_cbNonTermcap = { 0 };
2385static ConsoleBuffer g_cbTermcap = { 0 };
2386
2387#ifdef FEAT_TITLE
2388#ifdef __BORLANDC__
2389typedef HWND (__stdcall *GETCONSOLEWINDOWPROC)(VOID);
2390#else
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002391typedef HWND (WINAPI *GETCONSOLEWINDOWPROC)(VOID);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002392#endif
2393char g_szOrigTitle[256] = { 0 };
2394HWND g_hWnd = NULL; /* also used in os_mswin.c */
2395static HICON g_hOrigIconSmall = NULL;
2396static HICON g_hOrigIcon = NULL;
2397static HICON g_hVimIcon = NULL;
2398static BOOL g_fCanChangeIcon = FALSE;
2399
2400/* ICON* are not defined in VC++ 4.0 */
2401#ifndef ICON_SMALL
2402#define ICON_SMALL 0
2403#endif
2404#ifndef ICON_BIG
2405#define ICON_BIG 1
2406#endif
2407/*
2408 * GetConsoleIcon()
2409 * Description:
2410 * Attempts to retrieve the small icon and/or the big icon currently in
2411 * use by a given window.
2412 * Returns:
2413 * TRUE on success
2414 */
2415 static BOOL
2416GetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002417 HWND hWnd,
2418 HICON *phIconSmall,
2419 HICON *phIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002420{
2421 if (hWnd == NULL)
2422 return FALSE;
2423
2424 if (phIconSmall != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002425 *phIconSmall = (HICON)SendMessage(hWnd, WM_GETICON,
2426 (WPARAM)ICON_SMALL, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002427 if (phIcon != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002428 *phIcon = (HICON)SendMessage(hWnd, WM_GETICON,
2429 (WPARAM)ICON_BIG, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002430 return TRUE;
2431}
2432
2433/*
2434 * SetConsoleIcon()
2435 * Description:
2436 * Attempts to change the small icon and/or the big icon currently in
2437 * use by a given window.
2438 * Returns:
2439 * TRUE on success
2440 */
2441 static BOOL
2442SetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002443 HWND hWnd,
2444 HICON hIconSmall,
2445 HICON hIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002446{
Bram Moolenaar071d4272004-06-13 20:20:40 +00002447 if (hWnd == NULL)
2448 return FALSE;
2449
2450 if (hIconSmall != NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002451 SendMessage(hWnd, WM_SETICON,
2452 (WPARAM)ICON_SMALL, (LPARAM)hIconSmall);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002453 if (hIcon != NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002454 SendMessage(hWnd, WM_SETICON,
2455 (WPARAM)ICON_BIG, (LPARAM) hIcon);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002456 return TRUE;
2457}
2458
2459/*
2460 * SaveConsoleTitleAndIcon()
2461 * Description:
2462 * Saves the current console window title in g_szOrigTitle, for later
2463 * restoration. Also, attempts to obtain a handle to the console window,
2464 * and use it to save the small and big icons currently in use by the
2465 * console window. This is not always possible on some versions of Windows;
2466 * nor is it possible when running Vim remotely using Telnet (since the
2467 * console window the user sees is owned by a remote process).
2468 */
2469 static void
2470SaveConsoleTitleAndIcon(void)
2471{
2472 GETCONSOLEWINDOWPROC GetConsoleWindowProc;
2473
2474 /* Save the original title. */
2475 if (!GetConsoleTitle(g_szOrigTitle, sizeof(g_szOrigTitle)))
2476 return;
2477
2478 /*
2479 * Obtain a handle to the console window using GetConsoleWindow() from
2480 * KERNEL32.DLL; we need to handle in order to change the window icon.
2481 * This function only exists on NT-based Windows, starting with Windows
2482 * 2000. On older operating systems, we can't change the window icon
2483 * anyway.
2484 */
2485 if ((GetConsoleWindowProc = (GETCONSOLEWINDOWPROC)
2486 GetProcAddress(GetModuleHandle("KERNEL32.DLL"),
2487 "GetConsoleWindow")) != NULL)
2488 {
2489 g_hWnd = (*GetConsoleWindowProc)();
2490 }
2491 if (g_hWnd == NULL)
2492 return;
2493
2494 /* Save the original console window icon. */
2495 GetConsoleIcon(g_hWnd, &g_hOrigIconSmall, &g_hOrigIcon);
2496 if (g_hOrigIconSmall == NULL || g_hOrigIcon == NULL)
2497 return;
2498
2499 /* Extract the first icon contained in the Vim executable. */
Bram Moolenaarcddc91c2014-09-23 21:53:41 +02002500 if (mch_icon_load((HANDLE *)&g_hVimIcon) == FAIL || g_hVimIcon == NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002501 g_hVimIcon = ExtractIcon(NULL, (LPCSTR)exe_name, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002502 if (g_hVimIcon != NULL)
2503 g_fCanChangeIcon = TRUE;
2504}
2505#endif
2506
2507static int g_fWindInitCalled = FALSE;
2508static int g_fTermcapMode = FALSE;
2509static CONSOLE_CURSOR_INFO g_cci;
2510static DWORD g_cmodein = 0;
2511static DWORD g_cmodeout = 0;
2512
2513/*
2514 * non-GUI version of mch_init().
2515 */
2516 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002517mch_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002518{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002519#ifndef FEAT_RESTORE_ORIG_SCREEN
2520 CONSOLE_SCREEN_BUFFER_INFO csbi;
2521#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002522#ifndef __MINGW32__
2523 extern int _fmode;
2524#endif
2525
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002526 /* Silently handle invalid parameters to CRT functions */
2527 SET_INVALID_PARAM_HANDLER;
2528
Bram Moolenaar071d4272004-06-13 20:20:40 +00002529 /* Let critical errors result in a failure, not in a dialog box. Required
2530 * for the timestamp test to work on removed floppies. */
2531 SetErrorMode(SEM_FAILCRITICALERRORS);
2532
2533 _fmode = O_BINARY; /* we do our own CR-LF translation */
2534 out_flush();
2535
2536 /* Obtain handles for the standard Console I/O devices */
2537 if (read_cmd_fd == 0)
2538 g_hConIn = GetStdHandle(STD_INPUT_HANDLE);
2539 else
2540 create_conin();
2541 g_hConOut = GetStdHandle(STD_OUTPUT_HANDLE);
2542
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002543#ifdef FEAT_RESTORE_ORIG_SCREEN
2544 /* Save the initial console buffer for later restoration */
2545 SaveConsoleBuffer(&g_cbOrig);
2546 g_attrCurrent = g_attrDefault = g_cbOrig.Info.wAttributes;
2547#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00002548 /* Get current text attributes */
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002549 GetConsoleScreenBufferInfo(g_hConOut, &csbi);
2550 g_attrCurrent = g_attrDefault = csbi.wAttributes;
2551#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002552 if (cterm_normal_fg_color == 0)
2553 cterm_normal_fg_color = (g_attrCurrent & 0xf) + 1;
2554 if (cterm_normal_bg_color == 0)
2555 cterm_normal_bg_color = ((g_attrCurrent >> 4) & 0xf) + 1;
2556
2557 /* set termcap codes to current text attributes */
2558 update_tcap(g_attrCurrent);
2559
2560 GetConsoleCursorInfo(g_hConOut, &g_cci);
2561 GetConsoleMode(g_hConIn, &g_cmodein);
2562 GetConsoleMode(g_hConOut, &g_cmodeout);
2563
2564#ifdef FEAT_TITLE
2565 SaveConsoleTitleAndIcon();
2566 /*
2567 * Set both the small and big icons of the console window to Vim's icon.
2568 * Note that Vim presently only has one size of icon (32x32), but it
2569 * automatically gets scaled down to 16x16 when setting the small icon.
2570 */
2571 if (g_fCanChangeIcon)
2572 SetConsoleIcon(g_hWnd, g_hVimIcon, g_hVimIcon);
2573#endif
2574
2575 ui_get_shellsize();
2576
2577#ifdef MCH_WRITE_DUMP
2578 fdDump = fopen("dump", "wt");
2579
2580 if (fdDump)
2581 {
2582 time_t t;
2583
2584 time(&t);
2585 fputs(ctime(&t), fdDump);
2586 fflush(fdDump);
2587 }
2588#endif
2589
2590 g_fWindInitCalled = TRUE;
2591
2592#ifdef FEAT_MOUSE
2593 g_fMouseAvail = GetSystemMetrics(SM_MOUSEPRESENT);
2594#endif
2595
2596#ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01002597 win_clip_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002598#endif
2599
2600 /* This will be NULL on anything but NT 4.0 */
2601 s_pfnGetConsoleKeyboardLayoutName =
2602 (PFNGCKLN) GetProcAddress(GetModuleHandle("kernel32.dll"),
2603 "GetConsoleKeyboardLayoutNameA");
2604}
2605
2606/*
2607 * non-GUI version of mch_exit().
2608 * Shut down and exit with status `r'
2609 * Careful: mch_exit() may be called before mch_init()!
2610 */
2611 void
2612mch_exit(int r)
2613{
2614 stoptermcap();
2615
2616 if (g_fWindInitCalled)
2617 settmode(TMODE_COOK);
2618
2619 ml_close_all(TRUE); /* remove all memfiles */
2620
2621 if (g_fWindInitCalled)
2622 {
2623#ifdef FEAT_TITLE
2624 mch_restore_title(3);
2625 /*
2626 * Restore both the small and big icons of the console window to
2627 * what they were at startup. Don't do this when the window is
2628 * closed, Vim would hang here.
2629 */
2630 if (g_fCanChangeIcon && !g_fForceExit)
2631 SetConsoleIcon(g_hWnd, g_hOrigIconSmall, g_hOrigIcon);
2632#endif
2633
2634#ifdef MCH_WRITE_DUMP
2635 if (fdDump)
2636 {
2637 time_t t;
2638
2639 time(&t);
2640 fputs(ctime(&t), fdDump);
2641 fclose(fdDump);
2642 }
2643 fdDump = NULL;
2644#endif
2645 }
2646
2647 SetConsoleCursorInfo(g_hConOut, &g_cci);
2648 SetConsoleMode(g_hConIn, g_cmodein);
2649 SetConsoleMode(g_hConOut, g_cmodeout);
2650
2651#ifdef DYNAMIC_GETTEXT
2652 dyn_libintl_end();
2653#endif
2654
2655 exit(r);
2656}
2657#endif /* !FEAT_GUI_W32 */
2658
Bram Moolenaar071d4272004-06-13 20:20:40 +00002659/*
2660 * Do we have an interactive window?
2661 */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00002662/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00002663 int
2664mch_check_win(
2665 int argc,
2666 char **argv)
2667{
2668 get_exe_name();
2669
2670#ifdef FEAT_GUI_W32
2671 return OK; /* GUI always has a tty */
2672#else
2673 if (isatty(1))
2674 return OK;
2675 return FAIL;
2676#endif
2677}
2678
2679
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002680#ifdef FEAT_MBYTE
2681/*
2682 * fname_casew(): Wide version of fname_case(). Set the case of the file name,
2683 * if it already exists. When "len" is > 0, also expand short to long
2684 * filenames.
2685 * Return FAIL if wide functions are not available, OK otherwise.
2686 * NOTE: much of this is identical to fname_case(), keep in sync!
2687 */
2688 static int
2689fname_casew(
2690 WCHAR *name,
2691 int len)
2692{
2693 WCHAR szTrueName[_MAX_PATH + 2];
2694 WCHAR szTrueNameTemp[_MAX_PATH + 2];
2695 WCHAR *ptrue, *ptruePrev;
2696 WCHAR *porig, *porigPrev;
2697 int flen;
2698 WIN32_FIND_DATAW fb;
Bram Moolenaar73c61632013-12-07 14:48:10 +01002699 HANDLE hFind = INVALID_HANDLE_VALUE;
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002700 int c;
2701 int slen;
2702
2703 flen = (int)wcslen(name);
2704 if (flen > _MAX_PATH)
2705 return OK;
2706
2707 /* slash_adjust(name) not needed, already adjusted by fname_case(). */
2708
2709 /* Build the new name in szTrueName[] one component at a time. */
2710 porig = name;
2711 ptrue = szTrueName;
2712
2713 if (iswalpha(porig[0]) && porig[1] == L':')
2714 {
2715 /* copy leading drive letter */
2716 *ptrue++ = *porig++;
2717 *ptrue++ = *porig++;
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002718 }
Bram Moolenaar73c61632013-12-07 14:48:10 +01002719 *ptrue = NUL; /* in case nothing follows */
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002720
2721 while (*porig != NUL)
2722 {
2723 /* copy \ characters */
2724 while (*porig == psepc)
2725 *ptrue++ = *porig++;
2726
2727 ptruePrev = ptrue;
2728 porigPrev = porig;
2729 while (*porig != NUL && *porig != psepc)
2730 {
2731 *ptrue++ = *porig++;
2732 }
2733 *ptrue = NUL;
2734
2735 /* To avoid a slow failure append "\*" when searching a directory,
2736 * server or network share. */
2737 wcscpy(szTrueNameTemp, szTrueName);
2738 slen = (int)wcslen(szTrueNameTemp);
2739 if (*porig == psepc && slen + 2 < _MAX_PATH)
2740 wcscpy(szTrueNameTemp + slen, L"\\*");
2741
2742 /* Skip "", "." and "..". */
2743 if (ptrue > ptruePrev
2744 && (ptruePrev[0] != L'.'
2745 || (ptruePrev[1] != NUL
2746 && (ptruePrev[1] != L'.' || ptruePrev[2] != NUL)))
2747 && (hFind = FindFirstFileW(szTrueNameTemp, &fb))
2748 != INVALID_HANDLE_VALUE)
2749 {
2750 c = *porig;
2751 *porig = NUL;
2752
2753 /* Only use the match when it's the same name (ignoring case) or
2754 * expansion is allowed and there is a match with the short name
2755 * and there is enough room. */
2756 if (_wcsicoll(porigPrev, fb.cFileName) == 0
2757 || (len > 0
2758 && (_wcsicoll(porigPrev, fb.cAlternateFileName) == 0
2759 && (int)(ptruePrev - szTrueName)
2760 + (int)wcslen(fb.cFileName) < len)))
2761 {
2762 wcscpy(ptruePrev, fb.cFileName);
2763
2764 /* Look for exact match and prefer it if found. Must be a
2765 * long name, otherwise there would be only one match. */
2766 while (FindNextFileW(hFind, &fb))
2767 {
2768 if (*fb.cAlternateFileName != NUL
2769 && (wcscoll(porigPrev, fb.cFileName) == 0
2770 || (len > 0
2771 && (_wcsicoll(porigPrev,
2772 fb.cAlternateFileName) == 0
2773 && (int)(ptruePrev - szTrueName)
2774 + (int)wcslen(fb.cFileName) < len))))
2775 {
2776 wcscpy(ptruePrev, fb.cFileName);
2777 break;
2778 }
2779 }
2780 }
2781 FindClose(hFind);
2782 *porig = c;
2783 ptrue = ptruePrev + wcslen(ptruePrev);
2784 }
2785 else if (hFind == INVALID_HANDLE_VALUE
2786 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
2787 return FAIL;
2788 }
2789
2790 wcscpy(name, szTrueName);
2791 return OK;
2792}
2793#endif
2794
Bram Moolenaar071d4272004-06-13 20:20:40 +00002795/*
2796 * fname_case(): Set the case of the file name, if it already exists.
2797 * When "len" is > 0, also expand short to long filenames.
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002798 * NOTE: much of this is identical to fname_casew(), keep in sync!
Bram Moolenaar071d4272004-06-13 20:20:40 +00002799 */
2800 void
2801fname_case(
2802 char_u *name,
2803 int len)
2804{
2805 char szTrueName[_MAX_PATH + 2];
Bram Moolenaar464c9252010-10-13 20:37:41 +02002806 char szTrueNameTemp[_MAX_PATH + 2];
Bram Moolenaar071d4272004-06-13 20:20:40 +00002807 char *ptrue, *ptruePrev;
2808 char *porig, *porigPrev;
2809 int flen;
2810 WIN32_FIND_DATA fb;
2811 HANDLE hFind;
2812 int c;
Bram Moolenaar464c9252010-10-13 20:37:41 +02002813 int slen;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002814
Bram Moolenaara3ffd9c2005-07-21 21:03:15 +00002815 flen = (int)STRLEN(name);
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002816 if (flen == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002817 return;
2818
2819 slash_adjust(name);
2820
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002821#ifdef FEAT_MBYTE
2822 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2823 {
2824 WCHAR *p = enc_to_utf16(name, NULL);
2825
2826 if (p != NULL)
2827 {
2828 char_u *q;
Bram Moolenaar21d89b62014-10-07 10:38:40 +02002829 WCHAR buf[_MAX_PATH + 1];
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002830
Bram Moolenaar21d89b62014-10-07 10:38:40 +02002831 wcsncpy(buf, p, _MAX_PATH);
2832 buf[_MAX_PATH] = L'\0';
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002833 vim_free(p);
2834
2835 if (fname_casew(buf, (len > 0) ? _MAX_PATH : 0) == OK)
2836 {
2837 q = utf16_to_enc(buf, NULL);
2838 if (q != NULL)
2839 {
2840 vim_strncpy(name, q, (len > 0) ? len - 1 : flen);
2841 vim_free(q);
2842 return;
2843 }
2844 }
2845 }
2846 /* Retry with non-wide function (for Windows 98). */
2847 }
2848#endif
2849
2850 /* If 'enc' is utf-8, flen can be larger than _MAX_PATH.
2851 * So we should check this after calling wide function. */
2852 if (flen > _MAX_PATH)
2853 return;
2854
Bram Moolenaar071d4272004-06-13 20:20:40 +00002855 /* Build the new name in szTrueName[] one component at a time. */
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002856 porig = (char *)name;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002857 ptrue = szTrueName;
2858
2859 if (isalpha(porig[0]) && porig[1] == ':')
2860 {
2861 /* copy leading drive letter */
2862 *ptrue++ = *porig++;
2863 *ptrue++ = *porig++;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002864 }
Bram Moolenaar73c61632013-12-07 14:48:10 +01002865 *ptrue = NUL; /* in case nothing follows */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002866
2867 while (*porig != NUL)
2868 {
2869 /* copy \ characters */
2870 while (*porig == psepc)
2871 *ptrue++ = *porig++;
2872
2873 ptruePrev = ptrue;
2874 porigPrev = porig;
2875 while (*porig != NUL && *porig != psepc)
2876 {
2877#ifdef FEAT_MBYTE
2878 int l;
2879
2880 if (enc_dbcs)
2881 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002882 l = (*mb_ptr2len)((char_u *)porig);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002883 while (--l >= 0)
2884 *ptrue++ = *porig++;
2885 }
2886 else
2887#endif
2888 *ptrue++ = *porig++;
2889 }
2890 *ptrue = NUL;
2891
Bram Moolenaar464c9252010-10-13 20:37:41 +02002892 /* To avoid a slow failure append "\*" when searching a directory,
2893 * server or network share. */
2894 STRCPY(szTrueNameTemp, szTrueName);
Bram Moolenaar6b5ef062010-10-27 12:18:00 +02002895 slen = (int)strlen(szTrueNameTemp);
Bram Moolenaar464c9252010-10-13 20:37:41 +02002896 if (*porig == psepc && slen + 2 < _MAX_PATH)
2897 STRCPY(szTrueNameTemp + slen, "\\*");
2898
Bram Moolenaar071d4272004-06-13 20:20:40 +00002899 /* Skip "", "." and "..". */
2900 if (ptrue > ptruePrev
2901 && (ptruePrev[0] != '.'
2902 || (ptruePrev[1] != NUL
2903 && (ptruePrev[1] != '.' || ptruePrev[2] != NUL)))
Bram Moolenaar464c9252010-10-13 20:37:41 +02002904 && (hFind = FindFirstFile(szTrueNameTemp, &fb))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002905 != INVALID_HANDLE_VALUE)
2906 {
2907 c = *porig;
2908 *porig = NUL;
2909
2910 /* Only use the match when it's the same name (ignoring case) or
2911 * expansion is allowed and there is a match with the short name
2912 * and there is enough room. */
2913 if (_stricoll(porigPrev, fb.cFileName) == 0
2914 || (len > 0
2915 && (_stricoll(porigPrev, fb.cAlternateFileName) == 0
2916 && (int)(ptruePrev - szTrueName)
2917 + (int)strlen(fb.cFileName) < len)))
2918 {
2919 STRCPY(ptruePrev, fb.cFileName);
2920
2921 /* Look for exact match and prefer it if found. Must be a
2922 * long name, otherwise there would be only one match. */
2923 while (FindNextFile(hFind, &fb))
2924 {
2925 if (*fb.cAlternateFileName != NUL
2926 && (strcoll(porigPrev, fb.cFileName) == 0
2927 || (len > 0
2928 && (_stricoll(porigPrev,
2929 fb.cAlternateFileName) == 0
2930 && (int)(ptruePrev - szTrueName)
2931 + (int)strlen(fb.cFileName) < len))))
2932 {
2933 STRCPY(ptruePrev, fb.cFileName);
2934 break;
2935 }
2936 }
2937 }
2938 FindClose(hFind);
2939 *porig = c;
2940 ptrue = ptruePrev + strlen(ptruePrev);
2941 }
2942 }
2943
2944 STRCPY(name, szTrueName);
2945}
2946
2947
2948/*
2949 * Insert user name in s[len].
2950 */
2951 int
2952mch_get_user_name(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002953 char_u *s,
2954 int len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002955{
Bram Moolenaar41a09032007-10-01 18:34:34 +00002956 char szUserName[256 + 1]; /* UNLEN is 256 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002957 DWORD cch = sizeof szUserName;
2958
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01002959#ifdef FEAT_MBYTE
2960 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2961 {
2962 WCHAR wszUserName[256 + 1]; /* UNLEN is 256 */
2963 DWORD wcch = sizeof(wszUserName) / sizeof(WCHAR);
2964
2965 if (GetUserNameW(wszUserName, &wcch))
2966 {
2967 char_u *p = utf16_to_enc(wszUserName, NULL);
2968
2969 if (p != NULL)
2970 {
2971 vim_strncpy(s, p, len - 1);
2972 vim_free(p);
2973 return OK;
2974 }
2975 }
Bram Moolenaarcd981f22014-02-11 17:06:00 +01002976 else if (GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
2977 return FAIL;
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01002978 /* Retry with non-wide function (for Windows 98). */
2979 }
2980#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002981 if (GetUserName(szUserName, &cch))
2982 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002983 vim_strncpy(s, (char_u *)szUserName, len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002984 return OK;
2985 }
2986 s[0] = NUL;
2987 return FAIL;
2988}
2989
2990
2991/*
2992 * Insert host name in s[len].
2993 */
2994 void
2995mch_get_host_name(
2996 char_u *s,
2997 int len)
2998{
2999 DWORD cch = len;
3000
Bram Moolenaar2cc87382013-12-11 18:21:45 +01003001#ifdef FEAT_MBYTE
3002 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3003 {
3004 WCHAR wszHostName[256 + 1];
3005 DWORD wcch = sizeof(wszHostName) / sizeof(WCHAR);
3006
3007 if (GetComputerNameW(wszHostName, &wcch))
3008 {
3009 char_u *p = utf16_to_enc(wszHostName, NULL);
3010
3011 if (p != NULL)
3012 {
3013 vim_strncpy(s, p, len - 1);
3014 vim_free(p);
3015 return;
3016 }
3017 }
Bram Moolenaarcd981f22014-02-11 17:06:00 +01003018 else if (GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
3019 return;
Bram Moolenaar2cc87382013-12-11 18:21:45 +01003020 /* Retry with non-wide function (for Windows 98). */
3021 }
3022#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003023 if (!GetComputerName((LPSTR)s, &cch))
3024 vim_strncpy(s, (char_u *)"PC (Win32 Vim)", len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003025}
3026
3027
3028/*
3029 * return process ID
3030 */
3031 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003032mch_get_pid(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003033{
3034 return (long)GetCurrentProcessId();
3035}
3036
3037
3038/*
3039 * Get name of current directory into buffer 'buf' of length 'len' bytes.
3040 * Return OK for success, FAIL for failure.
3041 */
3042 int
3043mch_dirname(
3044 char_u *buf,
3045 int len)
3046{
3047 /*
3048 * Originally this was:
3049 * return (getcwd(buf, len) != NULL ? OK : FAIL);
3050 * But the Win32s known bug list says that getcwd() doesn't work
3051 * so use the Win32 system call instead. <Negri>
3052 */
3053#ifdef FEAT_MBYTE
3054 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3055 {
3056 WCHAR wbuf[_MAX_PATH + 1];
3057
3058 if (GetCurrentDirectoryW(_MAX_PATH, wbuf) != 0)
3059 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00003060 char_u *p = utf16_to_enc(wbuf, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003061
3062 if (p != NULL)
3063 {
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00003064 vim_strncpy(buf, p, len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003065 vim_free(p);
3066 return OK;
3067 }
3068 }
Bram Moolenaarcd981f22014-02-11 17:06:00 +01003069 else if (GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
3070 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003071 /* Retry with non-wide function (for Windows 98). */
3072 }
3073#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003074 return (GetCurrentDirectory(len, (LPSTR)buf) != 0 ? OK : FAIL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003075}
3076
3077/*
Bram Moolenaarffa22202013-11-21 12:34:11 +01003078 * Get file permissions for "name".
3079 * Return mode_t or -1 for error.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003080 */
3081 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003082mch_getperm(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003083{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003084 struct stat st;
Bram Moolenaarffa22202013-11-21 12:34:11 +01003085 int n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003086
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003087 n = mch_stat((char *)name, &st);
Bram Moolenaar78cf3f02014-01-10 18:16:07 +01003088 return n == 0 ? (long)(unsigned short)st.st_mode : -1L;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003089}
3090
3091
3092/*
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003093 * Set file permission for "name" to "perm".
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003094 *
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003095 * Return FAIL for failure, OK otherwise.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003096 */
3097 int
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003098mch_setperm(char_u *name, long perm)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003099{
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003100 long n = -1;
3101
Bram Moolenaar071d4272004-06-13 20:20:40 +00003102#ifdef FEAT_MBYTE
3103 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3104 {
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003105 WCHAR *p = enc_to_utf16(name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003106
3107 if (p != NULL)
3108 {
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003109 n = _wchmod(p, perm);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003110 vim_free(p);
Bram Moolenaarcd981f22014-02-11 17:06:00 +01003111 if (n == -1 && g_PlatformId == VER_PLATFORM_WIN32_NT)
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003112 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003113 /* Retry with non-wide function (for Windows 98). */
3114 }
3115 }
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003116 if (n == -1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003117#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003118 n = _chmod((const char *)name, perm);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003119 if (n == -1)
3120 return FAIL;
3121
3122 win32_set_archive(name);
3123
3124 return OK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003125}
3126
3127/*
3128 * Set hidden flag for "name".
3129 */
3130 void
3131mch_hide(char_u *name)
3132{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003133 int attrs = win32_getattrs(name);
3134 if (attrs == -1)
3135 return;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003136
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003137 attrs |= FILE_ATTRIBUTE_HIDDEN;
3138 win32_setattrs(name, attrs);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003139}
3140
3141/*
Bram Moolenaar8a52ba72015-11-02 14:45:56 +01003142 * Return TRUE if file "name" exists and is hidden.
3143 */
3144 int
3145mch_ishidden(char_u *name)
3146{
3147 int f = win32_getattrs(name);
3148
3149 if (f == -1)
3150 return FALSE; /* file does not exist at all */
3151
3152 return (f & FILE_ATTRIBUTE_HIDDEN) != 0;
3153}
3154
3155/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003156 * return TRUE if "name" is a directory
3157 * return FALSE if "name" is not a directory or upon error
3158 */
3159 int
3160mch_isdir(char_u *name)
3161{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003162 int f = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003163
3164 if (f == -1)
3165 return FALSE; /* file does not exist at all */
3166
3167 return (f & FILE_ATTRIBUTE_DIRECTORY) != 0;
3168}
3169
3170/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01003171 * return TRUE if "name" is a directory, NOT a symlink to a directory
3172 * return FALSE if "name" is not a directory
3173 * return FALSE for error
3174 */
3175 int
3176mch_isrealdir(char_u *name)
3177{
3178 return mch_isdir(name) && !mch_is_symbolic_link(name);
3179}
3180
3181/*
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003182 * Create directory "name".
3183 * Return 0 on success, -1 on error.
3184 */
3185 int
3186mch_mkdir(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 = _wmkdir(p);
3198 vim_free(p);
3199 return retval;
3200 }
3201#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003202 return _mkdir((const char *)name);
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003203}
3204
3205/*
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003206 * Delete directory "name".
3207 * Return 0 on success, -1 on error.
3208 */
3209 int
3210mch_rmdir(char_u *name)
3211{
3212#ifdef FEAT_MBYTE
3213 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3214 {
3215 WCHAR *p;
3216 int retval;
3217
3218 p = enc_to_utf16(name, NULL);
3219 if (p == NULL)
3220 return -1;
3221 retval = _wrmdir(p);
3222 vim_free(p);
3223 return retval;
3224 }
3225#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003226 return _rmdir((const char *)name);
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003227}
3228
3229/*
Bram Moolenaar03f48552006-02-28 23:52:23 +00003230 * Return TRUE if file "fname" has more than one link.
3231 */
3232 int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003233mch_is_hard_link(char_u *fname)
Bram Moolenaar03f48552006-02-28 23:52:23 +00003234{
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003235 BY_HANDLE_FILE_INFORMATION info;
3236
3237 return win32_fileinfo(fname, &info) == FILEINFO_OK
3238 && info.nNumberOfLinks > 1;
3239}
3240
3241/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01003242 * Return TRUE if "name" is a symbolic link (or a junction).
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003243 */
3244 int
Bram Moolenaar203258c2016-01-17 22:15:16 +01003245mch_is_symbolic_link(char_u *name)
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003246{
3247 HANDLE hFind;
3248 int res = FALSE;
3249 WIN32_FIND_DATAA findDataA;
3250 DWORD fileFlags = 0, reparseTag = 0;
3251#ifdef FEAT_MBYTE
3252 WCHAR *wn = NULL;
3253 WIN32_FIND_DATAW findDataW;
3254
3255 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar203258c2016-01-17 22:15:16 +01003256 wn = enc_to_utf16(name, NULL);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003257 if (wn != NULL)
3258 {
3259 hFind = FindFirstFileW(wn, &findDataW);
3260 vim_free(wn);
3261 if (hFind == INVALID_HANDLE_VALUE
3262 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
3263 {
3264 /* Retry with non-wide function (for Windows 98). */
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003265 hFind = FindFirstFile((LPCSTR)name, &findDataA);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003266 if (hFind != INVALID_HANDLE_VALUE)
3267 {
3268 fileFlags = findDataA.dwFileAttributes;
3269 reparseTag = findDataA.dwReserved0;
3270 }
3271 }
3272 else
3273 {
3274 fileFlags = findDataW.dwFileAttributes;
3275 reparseTag = findDataW.dwReserved0;
3276 }
3277 }
Bram Moolenaar03e114b2013-06-16 16:34:56 +02003278 else
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003279#endif
Bram Moolenaar03e114b2013-06-16 16:34:56 +02003280 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003281 hFind = FindFirstFile((LPCSTR)name, &findDataA);
Bram Moolenaar03e114b2013-06-16 16:34:56 +02003282 if (hFind != INVALID_HANDLE_VALUE)
3283 {
3284 fileFlags = findDataA.dwFileAttributes;
3285 reparseTag = findDataA.dwReserved0;
3286 }
3287 }
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003288
3289 if (hFind != INVALID_HANDLE_VALUE)
3290 FindClose(hFind);
3291
3292 if ((fileFlags & FILE_ATTRIBUTE_REPARSE_POINT)
Bram Moolenaar203258c2016-01-17 22:15:16 +01003293 && (reparseTag == IO_REPARSE_TAG_SYMLINK
3294 || reparseTag == IO_REPARSE_TAG_MOUNT_POINT))
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003295 res = TRUE;
3296
3297 return res;
3298}
3299
3300/*
3301 * Return TRUE if file "fname" has more than one link or if it is a symbolic
3302 * link.
3303 */
3304 int
3305mch_is_linked(char_u *fname)
3306{
3307 if (mch_is_hard_link(fname) || mch_is_symbolic_link(fname))
3308 return TRUE;
3309 return FALSE;
3310}
3311
3312/*
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003313 * Get the by-handle-file-information for "fname".
3314 * Returns FILEINFO_OK when OK.
3315 * returns FILEINFO_ENC_FAIL when enc_to_utf16() failed.
3316 * Returns FILEINFO_READ_FAIL when CreateFile() failed.
3317 * Returns FILEINFO_INFO_FAIL when GetFileInformationByHandle() failed.
3318 */
3319 int
3320win32_fileinfo(char_u *fname, BY_HANDLE_FILE_INFORMATION *info)
3321{
Bram Moolenaar03f48552006-02-28 23:52:23 +00003322 HANDLE hFile;
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003323 int res = FILEINFO_READ_FAIL;
Bram Moolenaar03f48552006-02-28 23:52:23 +00003324#ifdef FEAT_MBYTE
3325 WCHAR *wn = NULL;
3326
3327 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003328 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00003329 wn = enc_to_utf16(fname, NULL);
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003330 if (wn == NULL)
3331 res = FILEINFO_ENC_FAIL;
3332 }
Bram Moolenaar03f48552006-02-28 23:52:23 +00003333 if (wn != NULL)
3334 {
3335 hFile = CreateFileW(wn, /* file name */
3336 GENERIC_READ, /* access mode */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003337 FILE_SHARE_READ | FILE_SHARE_WRITE, /* share mode */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003338 NULL, /* security descriptor */
3339 OPEN_EXISTING, /* creation disposition */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003340 FILE_FLAG_BACKUP_SEMANTICS, /* file attributes */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003341 NULL); /* handle to template file */
3342 if (hFile == INVALID_HANDLE_VALUE
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003343 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
Bram Moolenaar03f48552006-02-28 23:52:23 +00003344 {
3345 /* Retry with non-wide function (for Windows 98). */
3346 vim_free(wn);
3347 wn = NULL;
3348 }
3349 }
3350 if (wn == NULL)
3351#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003352 hFile = CreateFile((LPCSTR)fname, /* file name */
3353 GENERIC_READ, /* access mode */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003354 FILE_SHARE_READ | FILE_SHARE_WRITE, /* share mode */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003355 NULL, /* security descriptor */
3356 OPEN_EXISTING, /* creation disposition */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003357 FILE_FLAG_BACKUP_SEMANTICS, /* file attributes */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003358 NULL); /* handle to template file */
3359
3360 if (hFile != INVALID_HANDLE_VALUE)
3361 {
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003362 if (GetFileInformationByHandle(hFile, info) != 0)
3363 res = FILEINFO_OK;
3364 else
3365 res = FILEINFO_INFO_FAIL;
Bram Moolenaar03f48552006-02-28 23:52:23 +00003366 CloseHandle(hFile);
3367 }
3368
3369#ifdef FEAT_MBYTE
3370 vim_free(wn);
3371#endif
3372 return res;
3373}
3374
3375/*
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003376 * get file attributes for `name'
3377 * -1 : error
3378 * else FILE_ATTRIBUTE_* defined in winnt.h
3379 */
Bram Moolenaarffa22202013-11-21 12:34:11 +01003380 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003381win32_getattrs(char_u *name)
3382{
3383 int attr;
3384#ifdef FEAT_MBYTE
3385 WCHAR *p = NULL;
3386
3387 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3388 p = enc_to_utf16(name, NULL);
3389
3390 if (p != NULL)
3391 {
3392 attr = GetFileAttributesW(p);
3393 if (attr < 0 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
3394 {
3395 /* Retry with non-wide function (for Windows 98). */
3396 vim_free(p);
3397 p = NULL;
3398 }
3399 }
3400 if (p == NULL)
3401#endif
3402 attr = GetFileAttributes((char *)name);
3403#ifdef FEAT_MBYTE
3404 vim_free(p);
3405#endif
3406 return attr;
3407}
3408
3409/*
3410 * set file attributes for `name' to `attrs'
3411 *
3412 * return -1 for failure, 0 otherwise
3413 */
3414 static
3415 int
3416win32_setattrs(char_u *name, int attrs)
3417{
3418 int res;
3419#ifdef FEAT_MBYTE
3420 WCHAR *p = NULL;
3421
3422 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3423 p = enc_to_utf16(name, NULL);
3424
3425 if (p != NULL)
3426 {
3427 res = SetFileAttributesW(p, attrs);
3428 if (res == FALSE
3429 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
3430 {
3431 /* Retry with non-wide function (for Windows 98). */
3432 vim_free(p);
3433 p = NULL;
3434 }
3435 }
3436 if (p == NULL)
3437#endif
3438 res = SetFileAttributes((char *)name, attrs);
3439#ifdef FEAT_MBYTE
3440 vim_free(p);
3441#endif
3442 return res ? 0 : -1;
3443}
3444
3445/*
3446 * Set archive flag for "name".
3447 */
3448 static
3449 int
3450win32_set_archive(char_u *name)
3451{
3452 int attrs = win32_getattrs(name);
3453 if (attrs == -1)
3454 return -1;
3455
3456 attrs |= FILE_ATTRIBUTE_ARCHIVE;
3457 return win32_setattrs(name, attrs);
3458}
3459
3460/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003461 * Return TRUE if file or directory "name" is writable (not readonly).
3462 * Strange semantics of Win32: a readonly directory is writable, but you can't
3463 * delete a file. Let's say this means it is writable.
3464 */
3465 int
3466mch_writable(char_u *name)
3467{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003468 int attrs = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003469
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003470 return (attrs != -1 && (!(attrs & FILE_ATTRIBUTE_READONLY)
3471 || (attrs & FILE_ATTRIBUTE_DIRECTORY)));
Bram Moolenaar071d4272004-06-13 20:20:40 +00003472}
3473
Bram Moolenaar071d4272004-06-13 20:20:40 +00003474/*
3475 * Return 1 if "name" can be executed, 0 if not.
Bram Moolenaar77b77102015-03-21 22:18:41 +01003476 * If "use_path" is FALSE only check if "name" is executable.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003477 * Return -1 if unknown.
3478 */
3479 int
Bram Moolenaar77b77102015-03-21 22:18:41 +01003480mch_can_exe(char_u *name, char_u **path, int use_path)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003481{
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003482 char_u buf[_MAX_PATH];
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00003483 int len = (int)STRLEN(name);
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003484 char_u *p;
3485
3486 if (len >= _MAX_PATH) /* safety check */
3487 return FALSE;
Bram Moolenaar77b77102015-03-21 22:18:41 +01003488 if (!use_path)
3489 {
3490 /* TODO: check if file is really executable. */
3491 return mch_getperm(name) != -1 && !mch_isdir(name);
3492 }
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003493
3494 /* If there already is an extension try using the name directly. Also do
3495 * this with a Unix-shell like 'shell'. */
3496 if (vim_strchr(gettail(name), '.') != NULL
3497 || strstr((char *)gettail(p_sh), "sh") != NULL)
Bram Moolenaarc7f02552014-04-01 21:00:59 +02003498 if (executable_exists((char *)name, path))
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003499 return TRUE;
3500
3501 /*
3502 * Loop over all extensions in $PATHEXT.
3503 */
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00003504 vim_strncpy(buf, name, _MAX_PATH - 1);
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003505 p = mch_getenv("PATHEXT");
3506 if (p == NULL)
3507 p = (char_u *)".com;.exe;.bat;.cmd";
3508 while (*p)
3509 {
3510 if (p[0] == '.' && (p[1] == NUL || p[1] == ';'))
3511 {
3512 /* A single "." means no extension is added. */
3513 buf[len] = NUL;
3514 ++p;
3515 if (*p)
3516 ++p;
3517 }
3518 else
3519 copy_option_part(&p, buf + len, _MAX_PATH - len, ";");
Bram Moolenaarc7f02552014-04-01 21:00:59 +02003520 if (executable_exists((char *)buf, path))
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003521 return TRUE;
3522 }
3523 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003524}
Bram Moolenaar071d4272004-06-13 20:20:40 +00003525
3526/*
3527 * Check what "name" is:
3528 * NODE_NORMAL: file or directory (or doesn't exist)
3529 * NODE_WRITABLE: writable device, socket, fifo, etc.
3530 * NODE_OTHER: non-writable things
3531 */
3532 int
3533mch_nodetype(char_u *name)
3534{
3535 HANDLE hFile;
3536 int type;
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003537#ifdef FEAT_MBYTE
3538 WCHAR *wn = NULL;
3539#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003540
Bram Moolenaar043545e2006-10-10 16:44:07 +00003541 /* We can't open a file with a name "\\.\con" or "\\.\prn" and trying to
3542 * read from it later will cause Vim to hang. Thus return NODE_WRITABLE
3543 * here. */
3544 if (STRNCMP(name, "\\\\.\\", 4) == 0)
3545 return NODE_WRITABLE;
3546
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003547#ifdef FEAT_MBYTE
3548 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3549 {
3550 wn = enc_to_utf16(name, NULL);
3551 if (wn != NULL)
3552 {
3553 hFile = CreateFileW(wn, /* file name */
3554 GENERIC_WRITE, /* access mode */
3555 0, /* share mode */
3556 NULL, /* security descriptor */
3557 OPEN_EXISTING, /* creation disposition */
3558 0, /* file attributes */
3559 NULL); /* handle to template file */
3560 if (hFile == INVALID_HANDLE_VALUE
3561 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
3562 {
3563 /* Retry with non-wide function (for Windows 98). */
3564 vim_free(wn);
3565 wn = NULL;
3566 }
3567 }
3568 }
3569 if (wn == NULL)
3570#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003571 hFile = CreateFile((LPCSTR)name, /* file name */
3572 GENERIC_WRITE, /* access mode */
3573 0, /* share mode */
3574 NULL, /* security descriptor */
3575 OPEN_EXISTING, /* creation disposition */
3576 0, /* file attributes */
3577 NULL); /* handle to template file */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003578
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003579#ifdef FEAT_MBYTE
3580 vim_free(wn);
3581#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003582 if (hFile == INVALID_HANDLE_VALUE)
3583 return NODE_NORMAL;
3584
3585 type = GetFileType(hFile);
3586 CloseHandle(hFile);
3587 if (type == FILE_TYPE_CHAR)
3588 return NODE_WRITABLE;
3589 if (type == FILE_TYPE_DISK)
3590 return NODE_NORMAL;
3591 return NODE_OTHER;
3592}
3593
3594#ifdef HAVE_ACL
3595struct my_acl
3596{
3597 PSECURITY_DESCRIPTOR pSecurityDescriptor;
3598 PSID pSidOwner;
3599 PSID pSidGroup;
3600 PACL pDacl;
3601 PACL pSacl;
3602};
3603#endif
3604
3605/*
3606 * Return a pointer to the ACL of file "fname" in allocated memory.
3607 * Return NULL if the ACL is not available for whatever reason.
3608 */
3609 vim_acl_T
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003610mch_get_acl(char_u *fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003611{
3612#ifndef HAVE_ACL
3613 return (vim_acl_T)NULL;
3614#else
3615 struct my_acl *p = NULL;
Bram Moolenaar27515922013-06-29 15:36:26 +02003616 DWORD err;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003617
3618 /* This only works on Windows NT and 2000. */
3619 if (g_PlatformId == VER_PLATFORM_WIN32_NT && advapi_lib != NULL)
3620 {
3621 p = (struct my_acl *)alloc_clear((unsigned)sizeof(struct my_acl));
3622 if (p != NULL)
3623 {
Bram Moolenaar27515922013-06-29 15:36:26 +02003624# ifdef FEAT_MBYTE
3625 WCHAR *wn = NULL;
3626
3627 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3628 wn = enc_to_utf16(fname, NULL);
3629 if (wn != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003630 {
Bram Moolenaar27515922013-06-29 15:36:26 +02003631 /* Try to retrieve the entire security descriptor. */
3632 err = pGetNamedSecurityInfoW(
3633 wn, // Abstract filename
3634 SE_FILE_OBJECT, // File Object
3635 OWNER_SECURITY_INFORMATION |
3636 GROUP_SECURITY_INFORMATION |
3637 DACL_SECURITY_INFORMATION |
3638 SACL_SECURITY_INFORMATION,
3639 &p->pSidOwner, // Ownership information.
3640 &p->pSidGroup, // Group membership.
3641 &p->pDacl, // Discretionary information.
3642 &p->pSacl, // For auditing purposes.
3643 &p->pSecurityDescriptor);
3644 if (err == ERROR_ACCESS_DENIED ||
3645 err == ERROR_PRIVILEGE_NOT_HELD)
3646 {
3647 /* Retrieve only DACL. */
3648 (void)pGetNamedSecurityInfoW(
3649 wn,
3650 SE_FILE_OBJECT,
3651 DACL_SECURITY_INFORMATION,
3652 NULL,
3653 NULL,
3654 &p->pDacl,
3655 NULL,
3656 &p->pSecurityDescriptor);
3657 }
3658 if (p->pSecurityDescriptor == NULL)
3659 {
3660 mch_free_acl((vim_acl_T)p);
3661 p = NULL;
3662 }
3663 vim_free(wn);
3664 }
3665 else
3666# endif
3667 {
3668 /* Try to retrieve the entire security descriptor. */
3669 err = pGetNamedSecurityInfo(
3670 (LPSTR)fname, // Abstract filename
3671 SE_FILE_OBJECT, // File Object
3672 OWNER_SECURITY_INFORMATION |
3673 GROUP_SECURITY_INFORMATION |
3674 DACL_SECURITY_INFORMATION |
3675 SACL_SECURITY_INFORMATION,
3676 &p->pSidOwner, // Ownership information.
3677 &p->pSidGroup, // Group membership.
3678 &p->pDacl, // Discretionary information.
3679 &p->pSacl, // For auditing purposes.
3680 &p->pSecurityDescriptor);
3681 if (err == ERROR_ACCESS_DENIED ||
3682 err == ERROR_PRIVILEGE_NOT_HELD)
3683 {
3684 /* Retrieve only DACL. */
3685 (void)pGetNamedSecurityInfo(
3686 (LPSTR)fname,
3687 SE_FILE_OBJECT,
3688 DACL_SECURITY_INFORMATION,
3689 NULL,
3690 NULL,
3691 &p->pDacl,
3692 NULL,
3693 &p->pSecurityDescriptor);
3694 }
3695 if (p->pSecurityDescriptor == NULL)
3696 {
3697 mch_free_acl((vim_acl_T)p);
3698 p = NULL;
3699 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003700 }
3701 }
3702 }
3703
3704 return (vim_acl_T)p;
3705#endif
3706}
3707
Bram Moolenaar27515922013-06-29 15:36:26 +02003708#ifdef HAVE_ACL
3709/*
3710 * Check if "acl" contains inherited ACE.
3711 */
3712 static BOOL
3713is_acl_inherited(PACL acl)
3714{
3715 DWORD i;
3716 ACL_SIZE_INFORMATION acl_info;
3717 PACCESS_ALLOWED_ACE ace;
3718
3719 acl_info.AceCount = 0;
3720 GetAclInformation(acl, &acl_info, sizeof(acl_info), AclSizeInformation);
3721 for (i = 0; i < acl_info.AceCount; i++)
3722 {
3723 GetAce(acl, i, (LPVOID *)&ace);
3724 if (ace->Header.AceFlags & INHERITED_ACE)
3725 return TRUE;
3726 }
3727 return FALSE;
3728}
3729#endif
3730
Bram Moolenaar071d4272004-06-13 20:20:40 +00003731/*
3732 * Set the ACL of file "fname" to "acl" (unless it's NULL).
3733 * Errors are ignored.
3734 * This must only be called with "acl" equal to what mch_get_acl() returned.
3735 */
3736 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003737mch_set_acl(char_u *fname, vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003738{
3739#ifdef HAVE_ACL
3740 struct my_acl *p = (struct my_acl *)acl;
Bram Moolenaar27515922013-06-29 15:36:26 +02003741 SECURITY_INFORMATION sec_info = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003742
3743 if (p != NULL && advapi_lib != NULL)
Bram Moolenaar27515922013-06-29 15:36:26 +02003744 {
3745# ifdef FEAT_MBYTE
3746 WCHAR *wn = NULL;
3747# endif
3748
3749 /* Set security flags */
3750 if (p->pSidOwner)
3751 sec_info |= OWNER_SECURITY_INFORMATION;
3752 if (p->pSidGroup)
3753 sec_info |= GROUP_SECURITY_INFORMATION;
3754 if (p->pDacl)
3755 {
3756 sec_info |= DACL_SECURITY_INFORMATION;
3757 /* Do not inherit its parent's DACL.
3758 * If the DACL is inherited, Cygwin permissions would be changed.
3759 */
3760 if (!is_acl_inherited(p->pDacl))
3761 sec_info |= PROTECTED_DACL_SECURITY_INFORMATION;
3762 }
3763 if (p->pSacl)
3764 sec_info |= SACL_SECURITY_INFORMATION;
3765
3766# ifdef FEAT_MBYTE
3767 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3768 wn = enc_to_utf16(fname, NULL);
3769 if (wn != NULL)
3770 {
3771 (void)pSetNamedSecurityInfoW(
3772 wn, // Abstract filename
3773 SE_FILE_OBJECT, // File Object
3774 sec_info,
3775 p->pSidOwner, // Ownership information.
3776 p->pSidGroup, // Group membership.
3777 p->pDacl, // Discretionary information.
3778 p->pSacl // For auditing purposes.
3779 );
3780 vim_free(wn);
3781 }
3782 else
3783# endif
3784 {
3785 (void)pSetNamedSecurityInfo(
3786 (LPSTR)fname, // Abstract filename
3787 SE_FILE_OBJECT, // File Object
3788 sec_info,
3789 p->pSidOwner, // Ownership information.
3790 p->pSidGroup, // Group membership.
3791 p->pDacl, // Discretionary information.
3792 p->pSacl // For auditing purposes.
3793 );
3794 }
3795 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003796#endif
3797}
3798
3799 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003800mch_free_acl(vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003801{
3802#ifdef HAVE_ACL
3803 struct my_acl *p = (struct my_acl *)acl;
3804
3805 if (p != NULL)
3806 {
3807 LocalFree(p->pSecurityDescriptor); // Free the memory just in case
3808 vim_free(p);
3809 }
3810#endif
3811}
3812
3813#ifndef FEAT_GUI_W32
3814
3815/*
3816 * handler for ctrl-break, ctrl-c interrupts, and fatal events.
3817 */
3818 static BOOL WINAPI
3819handler_routine(
3820 DWORD dwCtrlType)
3821{
3822 switch (dwCtrlType)
3823 {
3824 case CTRL_C_EVENT:
3825 if (ctrl_c_interrupts)
3826 g_fCtrlCPressed = TRUE;
3827 return TRUE;
3828
3829 case CTRL_BREAK_EVENT:
3830 g_fCBrkPressed = TRUE;
3831 return TRUE;
3832
3833 /* fatal events: shut down gracefully */
3834 case CTRL_CLOSE_EVENT:
3835 case CTRL_LOGOFF_EVENT:
3836 case CTRL_SHUTDOWN_EVENT:
3837 windgoto((int)Rows - 1, 0);
3838 g_fForceExit = TRUE;
3839
Bram Moolenaar0fde2902008-03-16 13:54:13 +00003840 vim_snprintf((char *)IObuff, IOSIZE, _("Vim: Caught %s event\n"),
Bram Moolenaar071d4272004-06-13 20:20:40 +00003841 (dwCtrlType == CTRL_CLOSE_EVENT
3842 ? _("close")
3843 : dwCtrlType == CTRL_LOGOFF_EVENT
3844 ? _("logoff")
3845 : _("shutdown")));
3846#ifdef DEBUG
3847 OutputDebugString(IObuff);
3848#endif
3849
3850 preserve_exit(); /* output IObuff, preserve files and exit */
3851
3852 return TRUE; /* not reached */
3853
3854 default:
3855 return FALSE;
3856 }
3857}
3858
3859
3860/*
3861 * set the tty in (raw) ? "raw" : "cooked" mode
3862 */
3863 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003864mch_settmode(int tmode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003865{
3866 DWORD cmodein;
3867 DWORD cmodeout;
3868 BOOL bEnableHandler;
3869
3870 GetConsoleMode(g_hConIn, &cmodein);
3871 GetConsoleMode(g_hConOut, &cmodeout);
3872 if (tmode == TMODE_RAW)
3873 {
3874 cmodein &= ~(ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
3875 ENABLE_ECHO_INPUT);
3876#ifdef FEAT_MOUSE
3877 if (g_fMouseActive)
3878 cmodein |= ENABLE_MOUSE_INPUT;
3879#endif
3880 cmodeout &= ~(ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
3881 bEnableHandler = TRUE;
3882 }
3883 else /* cooked */
3884 {
3885 cmodein |= (ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
3886 ENABLE_ECHO_INPUT);
3887 cmodeout |= (ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
3888 bEnableHandler = FALSE;
3889 }
3890 SetConsoleMode(g_hConIn, cmodein);
3891 SetConsoleMode(g_hConOut, cmodeout);
3892 SetConsoleCtrlHandler(handler_routine, bEnableHandler);
3893
3894#ifdef MCH_WRITE_DUMP
3895 if (fdDump)
3896 {
3897 fprintf(fdDump, "mch_settmode(%s, in = %x, out = %x)\n",
3898 tmode == TMODE_RAW ? "raw" :
3899 tmode == TMODE_COOK ? "cooked" : "normal",
3900 cmodein, cmodeout);
3901 fflush(fdDump);
3902 }
3903#endif
3904}
3905
3906
3907/*
3908 * Get the size of the current window in `Rows' and `Columns'
3909 * Return OK when size could be determined, FAIL otherwise.
3910 */
3911 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003912mch_get_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003913{
3914 CONSOLE_SCREEN_BUFFER_INFO csbi;
3915
3916 if (!g_fTermcapMode && g_cbTermcap.IsValid)
3917 {
3918 /*
3919 * For some reason, we are trying to get the screen dimensions
3920 * even though we are not in termcap mode. The 'Rows' and 'Columns'
3921 * variables are really intended to mean the size of Vim screen
3922 * while in termcap mode.
3923 */
3924 Rows = g_cbTermcap.Info.dwSize.Y;
3925 Columns = g_cbTermcap.Info.dwSize.X;
3926 }
3927 else if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3928 {
3929 Rows = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
3930 Columns = csbi.srWindow.Right - csbi.srWindow.Left + 1;
3931 }
3932 else
3933 {
3934 Rows = 25;
3935 Columns = 80;
3936 }
3937 return OK;
3938}
3939
3940/*
3941 * Set a console window to `xSize' * `ySize'
3942 */
3943 static void
3944ResizeConBufAndWindow(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003945 HANDLE hConsole,
3946 int xSize,
3947 int ySize)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003948{
3949 CONSOLE_SCREEN_BUFFER_INFO csbi; /* hold current console buffer info */
3950 SMALL_RECT srWindowRect; /* hold the new console size */
3951 COORD coordScreen;
3952
3953#ifdef MCH_WRITE_DUMP
3954 if (fdDump)
3955 {
3956 fprintf(fdDump, "ResizeConBufAndWindow(%d, %d)\n", xSize, ySize);
3957 fflush(fdDump);
3958 }
3959#endif
3960
3961 /* get the largest size we can size the console window to */
3962 coordScreen = GetLargestConsoleWindowSize(hConsole);
3963
3964 /* define the new console window size and scroll position */
3965 srWindowRect.Left = srWindowRect.Top = (SHORT) 0;
3966 srWindowRect.Right = (SHORT) (min(xSize, coordScreen.X) - 1);
3967 srWindowRect.Bottom = (SHORT) (min(ySize, coordScreen.Y) - 1);
3968
3969 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3970 {
3971 int sx, sy;
3972
3973 sx = csbi.srWindow.Right - csbi.srWindow.Left + 1;
3974 sy = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
3975 if (sy < ySize || sx < xSize)
3976 {
3977 /*
3978 * Increasing number of lines/columns, do buffer first.
3979 * Use the maximal size in x and y direction.
3980 */
3981 if (sy < ySize)
3982 coordScreen.Y = ySize;
3983 else
3984 coordScreen.Y = sy;
3985 if (sx < xSize)
3986 coordScreen.X = xSize;
3987 else
3988 coordScreen.X = sx;
3989 SetConsoleScreenBufferSize(hConsole, coordScreen);
3990 }
3991 }
3992
3993 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &srWindowRect))
3994 {
3995#ifdef MCH_WRITE_DUMP
3996 if (fdDump)
3997 {
3998 fprintf(fdDump, "SetConsoleWindowInfo failed: %lx\n",
3999 GetLastError());
4000 fflush(fdDump);
4001 }
4002#endif
4003 }
4004
4005 /* define the new console buffer size */
4006 coordScreen.X = xSize;
4007 coordScreen.Y = ySize;
4008
4009 if (!SetConsoleScreenBufferSize(hConsole, coordScreen))
4010 {
4011#ifdef MCH_WRITE_DUMP
4012 if (fdDump)
4013 {
4014 fprintf(fdDump, "SetConsoleScreenBufferSize failed: %lx\n",
4015 GetLastError());
4016 fflush(fdDump);
4017 }
4018#endif
4019 }
4020}
4021
4022
4023/*
4024 * Set the console window to `Rows' * `Columns'
4025 */
4026 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004027mch_set_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004028{
4029 COORD coordScreen;
4030
4031 /* Don't change window size while still starting up */
4032 if (suppress_winsize != 0)
4033 {
4034 suppress_winsize = 2;
4035 return;
4036 }
4037
4038 if (term_console)
4039 {
4040 coordScreen = GetLargestConsoleWindowSize(g_hConOut);
4041
4042 /* Clamp Rows and Columns to reasonable values */
4043 if (Rows > coordScreen.Y)
4044 Rows = coordScreen.Y;
4045 if (Columns > coordScreen.X)
4046 Columns = coordScreen.X;
4047
4048 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
4049 }
4050}
4051
4052/*
4053 * Rows and/or Columns has changed.
4054 */
4055 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004056mch_new_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004057{
4058 set_scroll_region(0, 0, Columns - 1, Rows - 1);
4059}
4060
4061
4062/*
4063 * Called when started up, to set the winsize that was delayed.
4064 */
4065 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004066mch_set_winsize_now(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004067{
4068 if (suppress_winsize == 2)
4069 {
4070 suppress_winsize = 0;
4071 mch_set_shellsize();
4072 shell_resized();
4073 }
4074 suppress_winsize = 0;
4075}
4076#endif /* FEAT_GUI_W32 */
4077
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004078 static BOOL
4079vim_create_process(
Bram Moolenaar36c85b22013-12-12 20:25:44 +01004080 char *cmd,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004081 BOOL inherit_handles,
Bram Moolenaar3f1138e2014-01-05 13:29:26 +01004082 DWORD flags,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004083 STARTUPINFO *si,
4084 PROCESS_INFORMATION *pi)
4085{
4086# ifdef FEAT_MBYTE
4087 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4088 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004089 WCHAR *wcmd = enc_to_utf16((char_u *)cmd, NULL);
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004090
4091 if (wcmd != NULL)
4092 {
4093 BOOL ret;
4094 ret = CreateProcessW(
4095 NULL, /* Executable name */
4096 wcmd, /* Command to execute */
4097 NULL, /* Process security attributes */
4098 NULL, /* Thread security attributes */
4099 inherit_handles, /* Inherit handles */
4100 flags, /* Creation flags */
4101 NULL, /* Environment */
4102 NULL, /* Current directory */
Bram Moolenaar36c85b22013-12-12 20:25:44 +01004103 (LPSTARTUPINFOW)si, /* Startup information */
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004104 pi); /* Process information */
4105 vim_free(wcmd);
4106 return ret;
4107 }
4108 }
4109#endif
4110 return CreateProcess(
4111 NULL, /* Executable name */
4112 cmd, /* Command to execute */
4113 NULL, /* Process security attributes */
4114 NULL, /* Thread security attributes */
4115 inherit_handles, /* Inherit handles */
4116 flags, /* Creation flags */
4117 NULL, /* Environment */
4118 NULL, /* Current directory */
4119 si, /* Startup information */
4120 pi); /* Process information */
4121}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004122
4123
4124#if defined(FEAT_GUI_W32) || defined(PROTO)
4125
4126/*
4127 * Specialised version of system() for Win32 GUI mode.
4128 * This version proceeds as follows:
4129 * 1. Create a console window for use by the subprocess
4130 * 2. Run the subprocess (it gets the allocated console by default)
4131 * 3. Wait for the subprocess to terminate and get its exit code
4132 * 4. Prompt the user to press a key to close the console window
4133 */
4134 static int
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004135mch_system_classic(char *cmd, int options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004136{
4137 STARTUPINFO si;
4138 PROCESS_INFORMATION pi;
4139 DWORD ret = 0;
4140 HWND hwnd = GetFocus();
4141
4142 si.cb = sizeof(si);
4143 si.lpReserved = NULL;
4144 si.lpDesktop = NULL;
4145 si.lpTitle = NULL;
4146 si.dwFlags = STARTF_USESHOWWINDOW;
4147 /*
4148 * It's nicer to run a filter command in a minimized window, but in
4149 * Windows 95 this makes the command MUCH slower. We can't do it under
4150 * Win32s either as it stops the synchronous spawn workaround working.
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01004151 * Don't activate the window to keep focus on Vim.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004152 */
4153 if ((options & SHELL_DOOUT) && !mch_windows95() && !gui_is_win32s())
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01004154 si.wShowWindow = SW_SHOWMINNOACTIVE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004155 else
4156 si.wShowWindow = SW_SHOWNORMAL;
4157 si.cbReserved2 = 0;
4158 si.lpReserved2 = NULL;
4159
Bram Moolenaar942d6b22016-02-07 19:57:16 +01004160 /* There is a strange error on Windows 95 when using "c:\command.com".
Bram Moolenaar071d4272004-06-13 20:20:40 +00004161 * When the "c:\\" is left out it works OK...? */
4162 if (mch_windows95()
4163 && (STRNICMP(cmd, "c:/command.com", 14) == 0
4164 || STRNICMP(cmd, "c:\\command.com", 14) == 0))
4165 cmd += 3;
4166
4167 /* Now, run the command */
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004168 vim_create_process(cmd, FALSE,
4169 CREATE_DEFAULT_ERROR_MODE | CREATE_NEW_CONSOLE, &si, &pi);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004170
4171 /* Wait for the command to terminate before continuing */
4172 if (g_PlatformId != VER_PLATFORM_WIN32s)
4173 {
4174#ifdef FEAT_GUI
4175 int delay = 1;
4176
4177 /* Keep updating the window while waiting for the shell to finish. */
4178 for (;;)
4179 {
4180 MSG msg;
4181
Bram Moolenaar8c85fa32011-08-10 17:08:03 +02004182 if (pPeekMessage(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004183 {
4184 TranslateMessage(&msg);
Bram Moolenaar8c85fa32011-08-10 17:08:03 +02004185 pDispatchMessage(&msg);
Bram Moolenaare4195c52012-08-02 12:31:44 +02004186 delay = 1;
4187 continue;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004188 }
4189 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
4190 break;
4191
4192 /* We start waiting for a very short time and then increase it, so
4193 * that we respond quickly when the process is quick, and don't
4194 * consume too much overhead when it's slow. */
4195 if (delay < 50)
4196 delay += 10;
4197 }
4198#else
4199 WaitForSingleObject(pi.hProcess, INFINITE);
4200#endif
4201
4202 /* Get the command exit code */
4203 GetExitCodeProcess(pi.hProcess, &ret);
4204 }
4205 else
4206 {
4207 /*
4208 * This ugly code is the only quick way of performing
4209 * a synchronous spawn under Win32s. Yuk.
4210 */
4211 num_windows = 0;
4212 EnumWindows(win32ssynch_cb, 0);
4213 old_num_windows = num_windows;
4214 do
4215 {
4216 Sleep(1000);
4217 num_windows = 0;
4218 EnumWindows(win32ssynch_cb, 0);
4219 } while (num_windows == old_num_windows);
4220 ret = 0;
4221 }
4222
4223 /* Close the handles to the subprocess, so that it goes away */
4224 CloseHandle(pi.hThread);
4225 CloseHandle(pi.hProcess);
4226
4227 /* Try to get input focus back. Doesn't always work though. */
4228 PostMessage(hwnd, WM_SETFOCUS, 0, 0);
4229
4230 return ret;
4231}
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004232
4233/*
4234 * Thread launched by the gui to send the current buffer data to the
4235 * process. This way avoid to hang up vim totally if the children
4236 * process take a long time to process the lines.
4237 */
4238 static DWORD WINAPI
4239sub_process_writer(LPVOID param)
4240{
4241 HANDLE g_hChildStd_IN_Wr = param;
4242 linenr_T lnum = curbuf->b_op_start.lnum;
4243 DWORD len = 0;
4244 DWORD l;
4245 char_u *lp = ml_get(lnum);
4246 char_u *s;
4247 int written = 0;
4248
4249 for (;;)
4250 {
4251 l = (DWORD)STRLEN(lp + written);
4252 if (l == 0)
4253 len = 0;
4254 else if (lp[written] == NL)
4255 {
4256 /* NL -> NUL translation */
4257 WriteFile(g_hChildStd_IN_Wr, "", 1, &len, NULL);
4258 }
4259 else
4260 {
4261 s = vim_strchr(lp + written, NL);
4262 WriteFile(g_hChildStd_IN_Wr, (char *)lp + written,
4263 s == NULL ? l : (DWORD)(s - (lp + written)),
4264 &len, NULL);
4265 }
4266 if (len == (int)l)
4267 {
4268 /* Finished a line, add a NL, unless this line should not have
4269 * one. */
4270 if (lnum != curbuf->b_op_end.lnum
Bram Moolenaar34d72d42015-07-17 14:18:08 +02004271 || (!curbuf->b_p_bin
4272 && curbuf->b_p_fixeol)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004273 || (lnum != curbuf->b_no_eol_lnum
4274 && (lnum != curbuf->b_ml.ml_line_count
4275 || curbuf->b_p_eol)))
4276 {
Bram Moolenaaraf62ff32013-03-19 14:48:29 +01004277 WriteFile(g_hChildStd_IN_Wr, "\n", 1, (LPDWORD)&ignored, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004278 }
4279
4280 ++lnum;
4281 if (lnum > curbuf->b_op_end.lnum)
4282 break;
4283
4284 lp = ml_get(lnum);
4285 written = 0;
4286 }
4287 else if (len > 0)
4288 written += len;
4289 }
4290
4291 /* finished all the lines, close pipe */
4292 CloseHandle(g_hChildStd_IN_Wr);
4293 ExitThread(0);
4294}
4295
4296
4297# define BUFLEN 100 /* length for buffer, stolen from unix version */
4298
4299/*
4300 * This function read from the children's stdout and write the
4301 * data on screen or in the buffer accordingly.
4302 */
4303 static void
4304dump_pipe(int options,
4305 HANDLE g_hChildStd_OUT_Rd,
4306 garray_T *ga,
4307 char_u buffer[],
4308 DWORD *buffer_off)
4309{
4310 DWORD availableBytes = 0;
4311 DWORD i;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004312 int ret;
4313 DWORD len;
4314 DWORD toRead;
4315 int repeatCount;
4316
4317 /* we query the pipe to see if there is any data to read
4318 * to avoid to perform a blocking read */
4319 ret = PeekNamedPipe(g_hChildStd_OUT_Rd, /* pipe to query */
4320 NULL, /* optional buffer */
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02004321 0, /* buffer size */
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004322 NULL, /* number of read bytes */
4323 &availableBytes, /* available bytes total */
4324 NULL); /* byteLeft */
4325
4326 repeatCount = 0;
4327 /* We got real data in the pipe, read it */
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02004328 while (ret != 0 && availableBytes > 0)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004329 {
4330 repeatCount++;
4331 toRead =
4332# ifdef FEAT_MBYTE
4333 (DWORD)(BUFLEN - *buffer_off);
4334# else
4335 (DWORD)BUFLEN;
4336# endif
4337 toRead = availableBytes < toRead ? availableBytes : toRead;
4338 ReadFile(g_hChildStd_OUT_Rd, buffer
4339# ifdef FEAT_MBYTE
4340 + *buffer_off, toRead
4341# else
4342 , toRead
4343# endif
4344 , &len, NULL);
4345
4346 /* If we haven't read anything, there is a problem */
4347 if (len == 0)
4348 break;
4349
4350 availableBytes -= len;
4351
4352 if (options & SHELL_READ)
4353 {
4354 /* Do NUL -> NL translation, append NL separated
4355 * lines to the current buffer. */
4356 for (i = 0; i < len; ++i)
4357 {
4358 if (buffer[i] == NL)
4359 append_ga_line(ga);
4360 else if (buffer[i] == NUL)
4361 ga_append(ga, NL);
4362 else
4363 ga_append(ga, buffer[i]);
4364 }
4365 }
4366# ifdef FEAT_MBYTE
4367 else if (has_mbyte)
4368 {
4369 int l;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004370 int c;
4371 char_u *p;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004372
4373 len += *buffer_off;
4374 buffer[len] = NUL;
4375
4376 /* Check if the last character in buffer[] is
4377 * incomplete, keep these bytes for the next
4378 * round. */
4379 for (p = buffer; p < buffer + len; p += l)
4380 {
4381 l = mb_cptr2len(p);
4382 if (l == 0)
4383 l = 1; /* NUL byte? */
4384 else if (MB_BYTE2LEN(*p) != l)
4385 break;
4386 }
4387 if (p == buffer) /* no complete character */
4388 {
4389 /* avoid getting stuck at an illegal byte */
4390 if (len >= 12)
4391 ++p;
4392 else
4393 {
4394 *buffer_off = len;
4395 return;
4396 }
4397 }
4398 c = *p;
4399 *p = NUL;
4400 msg_puts(buffer);
4401 if (p < buffer + len)
4402 {
4403 *p = c;
4404 *buffer_off = (DWORD)((buffer + len) - p);
4405 mch_memmove(buffer, p, *buffer_off);
4406 return;
4407 }
4408 *buffer_off = 0;
4409 }
4410# endif /* FEAT_MBYTE */
4411 else
4412 {
4413 buffer[len] = NUL;
4414 msg_puts(buffer);
4415 }
4416
4417 windgoto(msg_row, msg_col);
4418 cursor_on();
4419 out_flush();
4420 }
4421}
4422
4423/*
4424 * Version of system to use for windows NT > 5.0 (Win2K), use pipe
4425 * for communication and doesn't open any new window.
4426 */
4427 static int
4428mch_system_piped(char *cmd, int options)
4429{
4430 STARTUPINFO si;
4431 PROCESS_INFORMATION pi;
4432 DWORD ret = 0;
4433
4434 HANDLE g_hChildStd_IN_Rd = NULL;
4435 HANDLE g_hChildStd_IN_Wr = NULL;
4436 HANDLE g_hChildStd_OUT_Rd = NULL;
4437 HANDLE g_hChildStd_OUT_Wr = NULL;
4438
4439 char_u buffer[BUFLEN + 1]; /* reading buffer + size */
4440 DWORD len;
4441
4442 /* buffer used to receive keys */
4443 char_u ta_buf[BUFLEN + 1]; /* TypeAHead */
4444 int ta_len = 0; /* valid bytes in ta_buf[] */
4445
4446 DWORD i;
4447 int c;
4448 int noread_cnt = 0;
4449 garray_T ga;
4450 int delay = 1;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004451 DWORD buffer_off = 0; /* valid bytes in buffer[] */
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004452 char *p = NULL;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004453
4454 SECURITY_ATTRIBUTES saAttr;
4455
4456 /* Set the bInheritHandle flag so pipe handles are inherited. */
4457 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
4458 saAttr.bInheritHandle = TRUE;
4459 saAttr.lpSecurityDescriptor = NULL;
4460
4461 if ( ! CreatePipe(&g_hChildStd_OUT_Rd, &g_hChildStd_OUT_Wr, &saAttr, 0)
4462 /* Ensure the read handle to the pipe for STDOUT is not inherited. */
4463 || ! pSetHandleInformation(g_hChildStd_OUT_Rd, HANDLE_FLAG_INHERIT, 0)
4464 /* Create a pipe for the child process's STDIN. */
4465 || ! CreatePipe(&g_hChildStd_IN_Rd, &g_hChildStd_IN_Wr, &saAttr, 0)
4466 /* Ensure the write handle to the pipe for STDIN is not inherited. */
4467 || ! pSetHandleInformation(g_hChildStd_IN_Wr, HANDLE_FLAG_INHERIT, 0) )
4468 {
4469 CloseHandle(g_hChildStd_IN_Rd);
4470 CloseHandle(g_hChildStd_IN_Wr);
4471 CloseHandle(g_hChildStd_OUT_Rd);
4472 CloseHandle(g_hChildStd_OUT_Wr);
4473 MSG_PUTS(_("\nCannot create pipes\n"));
4474 }
4475
4476 si.cb = sizeof(si);
4477 si.lpReserved = NULL;
4478 si.lpDesktop = NULL;
4479 si.lpTitle = NULL;
4480 si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
4481
4482 /* set-up our file redirection */
4483 si.hStdError = g_hChildStd_OUT_Wr;
4484 si.hStdOutput = g_hChildStd_OUT_Wr;
4485 si.hStdInput = g_hChildStd_IN_Rd;
4486 si.wShowWindow = SW_HIDE;
4487 si.cbReserved2 = 0;
4488 si.lpReserved2 = NULL;
4489
4490 if (options & SHELL_READ)
4491 ga_init2(&ga, 1, BUFLEN);
4492
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004493 if (cmd != NULL)
4494 {
4495 p = (char *)vim_strsave((char_u *)cmd);
4496 if (p != NULL)
4497 unescape_shellxquote((char_u *)p, p_sxe);
4498 else
4499 p = cmd;
4500 }
4501
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004502 /* Now, run the command.
4503 * About "Inherit handles" being TRUE: this command can be litigious,
4504 * handle inheritance was deactivated for pending temp file, but, if we
4505 * deactivate it, the pipes don't work for some reason. */
4506 vim_create_process(p, TRUE, CREATE_DEFAULT_ERROR_MODE, &si, &pi);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004507
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004508 if (p != cmd)
4509 vim_free(p);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004510
4511 /* Close our unused side of the pipes */
4512 CloseHandle(g_hChildStd_IN_Rd);
4513 CloseHandle(g_hChildStd_OUT_Wr);
4514
4515 if (options & SHELL_WRITE)
4516 {
4517 HANDLE thread =
4518 CreateThread(NULL, /* security attributes */
4519 0, /* default stack size */
4520 sub_process_writer, /* function to be executed */
4521 g_hChildStd_IN_Wr, /* parameter */
4522 0, /* creation flag, start immediately */
4523 NULL); /* we don't care about thread id */
4524 CloseHandle(thread);
4525 g_hChildStd_IN_Wr = NULL;
4526 }
4527
4528 /* Keep updating the window while waiting for the shell to finish. */
4529 for (;;)
4530 {
4531 MSG msg;
4532
Bram Moolenaar175d0702013-12-11 18:36:33 +01004533 if (pPeekMessage(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004534 {
4535 TranslateMessage(&msg);
Bram Moolenaar175d0702013-12-11 18:36:33 +01004536 pDispatchMessage(&msg);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004537 }
4538
4539 /* write pipe information in the window */
4540 if ((options & (SHELL_READ|SHELL_WRITE))
4541# ifdef FEAT_GUI
4542 || gui.in_use
4543# endif
4544 )
4545 {
4546 len = 0;
4547 if (!(options & SHELL_EXPAND)
4548 && ((options &
4549 (SHELL_READ|SHELL_WRITE|SHELL_COOKED))
4550 != (SHELL_READ|SHELL_WRITE|SHELL_COOKED)
4551# ifdef FEAT_GUI
4552 || gui.in_use
4553# endif
4554 )
4555 && (ta_len > 0 || noread_cnt > 4))
4556 {
4557 if (ta_len == 0)
4558 {
4559 /* Get extra characters when we don't have any. Reset the
4560 * counter and timer. */
4561 noread_cnt = 0;
4562# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
4563 gettimeofday(&start_tv, NULL);
4564# endif
4565 len = ui_inchar(ta_buf, BUFLEN, 10L, 0);
4566 }
4567 if (ta_len > 0 || len > 0)
4568 {
4569 /*
4570 * For pipes: Check for CTRL-C: send interrupt signal to
4571 * child. Check for CTRL-D: EOF, close pipe to child.
4572 */
4573 if (len == 1 && cmd != NULL)
4574 {
4575 if (ta_buf[ta_len] == Ctrl_C)
4576 {
4577 /* Learn what exit code is expected, for
4578 * now put 9 as SIGKILL */
4579 TerminateProcess(pi.hProcess, 9);
4580 }
4581 if (ta_buf[ta_len] == Ctrl_D)
4582 {
4583 CloseHandle(g_hChildStd_IN_Wr);
4584 g_hChildStd_IN_Wr = NULL;
4585 }
4586 }
4587
4588 /* replace K_BS by <BS> and K_DEL by <DEL> */
4589 for (i = ta_len; i < ta_len + len; ++i)
4590 {
4591 if (ta_buf[i] == CSI && len - i > 2)
4592 {
4593 c = TERMCAP2KEY(ta_buf[i + 1], ta_buf[i + 2]);
4594 if (c == K_DEL || c == K_KDEL || c == K_BS)
4595 {
4596 mch_memmove(ta_buf + i + 1, ta_buf + i + 3,
4597 (size_t)(len - i - 2));
4598 if (c == K_DEL || c == K_KDEL)
4599 ta_buf[i] = DEL;
4600 else
4601 ta_buf[i] = Ctrl_H;
4602 len -= 2;
4603 }
4604 }
4605 else if (ta_buf[i] == '\r')
4606 ta_buf[i] = '\n';
4607# ifdef FEAT_MBYTE
4608 if (has_mbyte)
4609 i += (*mb_ptr2len_len)(ta_buf + i,
4610 ta_len + len - i) - 1;
4611# endif
4612 }
4613
4614 /*
4615 * For pipes: echo the typed characters. For a pty this
4616 * does not seem to work.
4617 */
4618 for (i = ta_len; i < ta_len + len; ++i)
4619 {
4620 if (ta_buf[i] == '\n' || ta_buf[i] == '\b')
4621 msg_putchar(ta_buf[i]);
4622# ifdef FEAT_MBYTE
4623 else if (has_mbyte)
4624 {
4625 int l = (*mb_ptr2len)(ta_buf + i);
4626
4627 msg_outtrans_len(ta_buf + i, l);
4628 i += l - 1;
4629 }
4630# endif
4631 else
4632 msg_outtrans_len(ta_buf + i, 1);
4633 }
4634 windgoto(msg_row, msg_col);
4635 out_flush();
4636
4637 ta_len += len;
4638
4639 /*
4640 * Write the characters to the child, unless EOF has been
4641 * typed for pipes. Write one character at a time, to
4642 * avoid losing too much typeahead. When writing buffer
4643 * lines, drop the typed characters (only check for
4644 * CTRL-C).
4645 */
4646 if (options & SHELL_WRITE)
4647 ta_len = 0;
4648 else if (g_hChildStd_IN_Wr != NULL)
4649 {
4650 WriteFile(g_hChildStd_IN_Wr, (char*)ta_buf,
4651 1, &len, NULL);
4652 // if we are typing in, we want to keep things reactive
4653 delay = 1;
4654 if (len > 0)
4655 {
4656 ta_len -= len;
4657 mch_memmove(ta_buf, ta_buf + len, ta_len);
4658 }
4659 }
4660 }
4661 }
4662 }
4663
4664 if (ta_len)
4665 ui_inchar_undo(ta_buf, ta_len);
4666
4667 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
4668 {
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004669 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004670 break;
4671 }
4672
4673 ++noread_cnt;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004674 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004675
4676 /* We start waiting for a very short time and then increase it, so
4677 * that we respond quickly when the process is quick, and don't
4678 * consume too much overhead when it's slow. */
4679 if (delay < 50)
4680 delay += 10;
4681 }
4682
4683 /* Close the pipe */
4684 CloseHandle(g_hChildStd_OUT_Rd);
4685 if (g_hChildStd_IN_Wr != NULL)
4686 CloseHandle(g_hChildStd_IN_Wr);
4687
4688 WaitForSingleObject(pi.hProcess, INFINITE);
4689
4690 /* Get the command exit code */
4691 GetExitCodeProcess(pi.hProcess, &ret);
4692
4693 if (options & SHELL_READ)
4694 {
4695 if (ga.ga_len > 0)
4696 {
4697 append_ga_line(&ga);
4698 /* remember that the NL was missing */
4699 curbuf->b_no_eol_lnum = curwin->w_cursor.lnum;
4700 }
4701 else
4702 curbuf->b_no_eol_lnum = 0;
4703 ga_clear(&ga);
4704 }
4705
4706 /* Close the handles to the subprocess, so that it goes away */
4707 CloseHandle(pi.hThread);
4708 CloseHandle(pi.hProcess);
4709
4710 return ret;
4711}
4712
4713 static int
4714mch_system(char *cmd, int options)
4715{
4716 /* if we can pipe and the shelltemp option is off */
4717 if (allowPiping && !p_stmp)
4718 return mch_system_piped(cmd, options);
4719 else
4720 return mch_system_classic(cmd, options);
4721}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004722#else
4723
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004724# ifdef FEAT_MBYTE
4725 static int
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01004726mch_system(char *cmd, int options)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004727{
4728 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4729 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004730 WCHAR *wcmd = enc_to_utf16((char_u *)cmd, NULL);
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004731 if (wcmd != NULL)
4732 {
4733 int ret = _wsystem(wcmd);
4734 vim_free(wcmd);
4735 return ret;
4736 }
4737 }
4738 return system(cmd);
4739}
4740# else
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01004741# define mch_system(c, o) system(c)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004742# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004743
4744#endif
4745
4746/*
4747 * Either execute a command by calling the shell or start a new shell
4748 */
4749 int
4750mch_call_shell(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004751 char_u *cmd,
4752 int options) /* SHELL_*, see vim.h */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004753{
4754 int x = 0;
4755 int tmode = cur_tmode;
4756#ifdef FEAT_TITLE
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004757 char szShellTitle[512];
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004758# ifdef FEAT_MBYTE
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004759 int did_set_title = FALSE;
4760
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004761 /* Change the title to reflect that we are in a subshell. */
4762 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4763 {
4764 WCHAR szShellTitle[512];
4765
4766 if (GetConsoleTitleW(szShellTitle,
4767 sizeof(szShellTitle)/sizeof(WCHAR) - 4) > 0)
4768 {
4769 if (cmd == NULL)
4770 wcscat(szShellTitle, L" :sh");
4771 else
4772 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004773 WCHAR *wn = enc_to_utf16((char_u *)cmd, NULL);
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004774
4775 if (wn != NULL)
4776 {
4777 wcscat(szShellTitle, L" - !");
4778 if ((wcslen(szShellTitle) + wcslen(wn) <
4779 sizeof(szShellTitle)/sizeof(WCHAR)))
4780 wcscat(szShellTitle, wn);
4781 SetConsoleTitleW(szShellTitle);
4782 vim_free(wn);
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004783 did_set_title = TRUE;
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004784 }
4785 }
4786 }
4787 }
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004788 if (!did_set_title)
4789# endif
4790 /* Change the title to reflect that we are in a subshell. */
4791 if (GetConsoleTitle(szShellTitle, sizeof(szShellTitle) - 4) > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004792 {
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004793 if (cmd == NULL)
4794 strcat(szShellTitle, " :sh");
4795 else
4796 {
4797 strcat(szShellTitle, " - !");
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004798 if ((strlen(szShellTitle) + strlen((char *)cmd)
4799 < sizeof(szShellTitle)))
4800 strcat(szShellTitle, (char *)cmd);
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004801 }
4802 SetConsoleTitle(szShellTitle);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004803 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004804#endif
4805
4806 out_flush();
4807
4808#ifdef MCH_WRITE_DUMP
4809 if (fdDump)
4810 {
4811 fprintf(fdDump, "mch_call_shell(\"%s\", %d)\n", cmd, options);
4812 fflush(fdDump);
4813 }
4814#endif
4815
4816 /*
4817 * Catch all deadly signals while running the external command, because a
4818 * CTRL-C, Ctrl-Break or illegal instruction might otherwise kill us.
4819 */
4820 signal(SIGINT, SIG_IGN);
4821#if defined(__GNUC__) && !defined(__MINGW32__)
4822 signal(SIGKILL, SIG_IGN);
4823#else
4824 signal(SIGBREAK, SIG_IGN);
4825#endif
4826 signal(SIGILL, SIG_IGN);
4827 signal(SIGFPE, SIG_IGN);
4828 signal(SIGSEGV, SIG_IGN);
4829 signal(SIGTERM, SIG_IGN);
4830 signal(SIGABRT, SIG_IGN);
4831
4832 if (options & SHELL_COOKED)
4833 settmode(TMODE_COOK); /* set to normal mode */
4834
4835 if (cmd == NULL)
4836 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004837 x = mch_system((char *)p_sh, options);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004838 }
4839 else
4840 {
4841 /* we use "command" or "cmd" to start the shell; slow but easy */
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004842 char_u *newcmd = NULL;
4843 char_u *cmdbase = cmd;
4844 long_u cmdlen;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004845
4846 /* Skip a leading ", ( and "(. */
4847 if (*cmdbase == '"' )
4848 ++cmdbase;
4849 if (*cmdbase == '(')
4850 ++cmdbase;
4851
4852 if ((STRNICMP(cmdbase, "start", 5) == 0) && vim_iswhite(cmdbase[5]))
4853 {
4854 STARTUPINFO si;
4855 PROCESS_INFORMATION pi;
4856 DWORD flags = CREATE_NEW_CONSOLE;
4857 char_u *p;
4858
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01004859 ZeroMemory(&si, sizeof(si));
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004860 si.cb = sizeof(si);
4861 si.lpReserved = NULL;
4862 si.lpDesktop = NULL;
4863 si.lpTitle = NULL;
4864 si.dwFlags = 0;
4865 si.cbReserved2 = 0;
4866 si.lpReserved2 = NULL;
4867
4868 cmdbase = skipwhite(cmdbase + 5);
4869 if ((STRNICMP(cmdbase, "/min", 4) == 0)
4870 && vim_iswhite(cmdbase[4]))
4871 {
4872 cmdbase = skipwhite(cmdbase + 4);
4873 si.dwFlags = STARTF_USESHOWWINDOW;
4874 si.wShowWindow = SW_SHOWMINNOACTIVE;
4875 }
4876 else if ((STRNICMP(cmdbase, "/b", 2) == 0)
4877 && vim_iswhite(cmdbase[2]))
4878 {
4879 cmdbase = skipwhite(cmdbase + 2);
4880 flags = CREATE_NO_WINDOW;
4881 si.dwFlags = STARTF_USESTDHANDLES;
4882 si.hStdInput = CreateFile("\\\\.\\NUL", // File name
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004883 GENERIC_READ, // Access flags
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004884 0, // Share flags
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004885 NULL, // Security att.
4886 OPEN_EXISTING, // Open flags
4887 FILE_ATTRIBUTE_NORMAL, // File att.
4888 NULL); // Temp file
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004889 si.hStdOutput = si.hStdInput;
4890 si.hStdError = si.hStdInput;
4891 }
4892
4893 /* Remove a trailing ", ) and )" if they have a match
4894 * at the start of the command. */
4895 if (cmdbase > cmd)
4896 {
4897 p = cmdbase + STRLEN(cmdbase);
4898 if (p > cmdbase && p[-1] == '"' && *cmd == '"')
4899 *--p = NUL;
4900 if (p > cmdbase && p[-1] == ')'
4901 && (*cmd =='(' || cmd[1] == '('))
4902 *--p = NUL;
4903 }
4904
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004905 newcmd = cmdbase;
4906 unescape_shellxquote(cmdbase, p_sxe);
4907
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004908 /*
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004909 * If creating new console, arguments are passed to the
4910 * 'cmd.exe' as-is. If it's not, arguments are not treated
4911 * correctly for current 'cmd.exe'. So unescape characters in
4912 * shellxescape except '|' for avoiding to be treated as
4913 * argument to them. Pass the arguments to sub-shell.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004914 */
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004915 if (flags != CREATE_NEW_CONSOLE)
4916 {
4917 char_u *subcmd;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004918 char_u *cmd_shell = mch_getenv("COMSPEC");
4919
4920 if (cmd_shell == NULL || *cmd_shell == NUL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004921 cmd_shell = (char_u *)default_shell();
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004922
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004923 subcmd = vim_strsave_escaped_ext(cmdbase,
4924 (char_u *)"|", '^', FALSE);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004925 if (subcmd != NULL)
4926 {
4927 /* make "cmd.exe /c arguments" */
4928 cmdlen = STRLEN(cmd_shell) + STRLEN(subcmd) + 5;
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004929 newcmd = lalloc(cmdlen, TRUE);
4930 if (newcmd != NULL)
4931 vim_snprintf((char *)newcmd, cmdlen, "%s /c %s",
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004932 cmd_shell, subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004933 else
4934 newcmd = cmdbase;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004935 vim_free(subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004936 }
4937 }
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004938
4939 /*
4940 * Now, start the command as a process, so that it doesn't
4941 * inherit our handles which causes unpleasant dangling swap
4942 * files if we exit before the spawned process
4943 */
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004944 if (vim_create_process((char *)newcmd, FALSE, flags, &si, &pi))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004945 x = 0;
4946 else
4947 {
4948 x = -1;
4949#ifdef FEAT_GUI_W32
4950 EMSG(_("E371: Command not found"));
4951#endif
4952 }
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004953
4954 if (newcmd != cmdbase)
4955 vim_free(newcmd);
4956
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01004957 if (si.dwFlags == STARTF_USESTDHANDLES && si.hStdInput != NULL)
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004958 {
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01004959 /* Close the handle to \\.\NUL created above. */
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004960 CloseHandle(si.hStdInput);
4961 }
4962 /* Close the handles to the subprocess, so that it goes away */
4963 CloseHandle(pi.hThread);
4964 CloseHandle(pi.hProcess);
4965 }
4966 else
4967 {
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004968 cmdlen = (
Bram Moolenaar071d4272004-06-13 20:20:40 +00004969#ifdef FEAT_GUI_W32
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004970 (allowPiping && !p_stmp ? 0 : STRLEN(vimrun_path)) +
Bram Moolenaar071d4272004-06-13 20:20:40 +00004971#endif
Bram Moolenaar0fde2902008-03-16 13:54:13 +00004972 STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10);
4973
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004974 newcmd = lalloc(cmdlen, TRUE);
4975 if (newcmd != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004976 {
4977#if defined(FEAT_GUI_W32)
4978 if (need_vimrun_warning)
4979 {
4980 MessageBox(NULL,
4981 _("VIMRUN.EXE not found in your $PATH.\n"
4982 "External commands will not pause after completion.\n"
4983 "See :help win32-vimrun for more information."),
4984 _("Vim Warning"),
4985 MB_ICONWARNING);
4986 need_vimrun_warning = FALSE;
4987 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004988 if (!s_dont_use_vimrun && (!allowPiping || p_stmp))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004989 /* Use vimrun to execute the command. It opens a console
4990 * window, which can be closed without killing Vim. */
Bram Moolenaarcc448b32010-07-14 16:52:17 +02004991 vim_snprintf((char *)newcmd, cmdlen, "%s%s%s %s %s",
Bram Moolenaar071d4272004-06-13 20:20:40 +00004992 vimrun_path,
4993 (msg_silent != 0 || (options & SHELL_DOOUT))
4994 ? "-s " : "",
4995 p_sh, p_shcf, cmd);
4996 else
4997#endif
Bram Moolenaarcc448b32010-07-14 16:52:17 +02004998 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s",
Bram Moolenaar0fde2902008-03-16 13:54:13 +00004999 p_sh, p_shcf, cmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005000 x = mch_system((char *)newcmd, options);
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005001 vim_free(newcmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005002 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005003 }
5004 }
5005
5006 if (tmode == TMODE_RAW)
5007 settmode(TMODE_RAW); /* set to raw mode */
5008
5009 /* Print the return value, unless "vimrun" was used. */
5010 if (x != 0 && !(options & SHELL_SILENT) && !emsg_silent
5011#if defined(FEAT_GUI_W32)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005012 && ((options & SHELL_DOOUT) || s_dont_use_vimrun
5013 || (allowPiping && !p_stmp))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005014#endif
5015 )
5016 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01005017 smsg((char_u *)_("shell returned %d"), x);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005018 msg_putchar('\n');
5019 }
5020#ifdef FEAT_TITLE
5021 resettitle();
5022#endif
5023
5024 signal(SIGINT, SIG_DFL);
5025#if defined(__GNUC__) && !defined(__MINGW32__)
5026 signal(SIGKILL, SIG_DFL);
5027#else
5028 signal(SIGBREAK, SIG_DFL);
5029#endif
5030 signal(SIGILL, SIG_DFL);
5031 signal(SIGFPE, SIG_DFL);
5032 signal(SIGSEGV, SIG_DFL);
5033 signal(SIGTERM, SIG_DFL);
5034 signal(SIGABRT, SIG_DFL);
5035
5036 return x;
5037}
5038
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005039#if defined(FEAT_JOB) || defined(PROTO)
5040 void
Bram Moolenaar9a6e33a2016-02-16 19:25:12 +01005041mch_start_job(char *cmd, job_T *job, jobopt_T *options)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005042{
5043 STARTUPINFO si;
5044 PROCESS_INFORMATION pi;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005045 HANDLE jo;
Bram Moolenaar16eb4f82016-02-14 23:02:34 +01005046# ifdef FEAT_CHANNEL
5047 channel_T *channel;
Bram Moolenaard8070362016-02-15 21:56:54 +01005048 HANDLE ifd[2];
5049 HANDLE ofd[2];
5050 HANDLE efd[2];
5051 SECURITY_ATTRIBUTES saAttr;
5052
5053 ifd[0] = INVALID_HANDLE_VALUE;
5054 ifd[1] = INVALID_HANDLE_VALUE;
5055 ofd[0] = INVALID_HANDLE_VALUE;
5056 ofd[1] = INVALID_HANDLE_VALUE;
5057 efd[0] = INVALID_HANDLE_VALUE;
5058 efd[1] = INVALID_HANDLE_VALUE;
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005059
5060 channel = add_channel();
5061 if (channel == NULL)
5062 return;
Bram Moolenaar16eb4f82016-02-14 23:02:34 +01005063# endif
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005064
Bram Moolenaar76467df2016-02-12 19:30:26 +01005065 jo = CreateJobObject(NULL, NULL);
5066 if (jo == NULL)
5067 {
5068 job->jv_status = JOB_FAILED;
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005069 goto failed;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005070 }
5071
5072 ZeroMemory(&pi, sizeof(pi));
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005073 ZeroMemory(&si, sizeof(si));
5074 si.cb = sizeof(si);
Bram Moolenaard8070362016-02-15 21:56:54 +01005075 si.dwFlags |= STARTF_USESHOWWINDOW;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005076 si.wShowWindow = SW_HIDE;
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005077
Bram Moolenaar5d54a042016-02-16 16:39:51 +01005078# ifdef FEAT_CHANNEL
Bram Moolenaard8070362016-02-15 21:56:54 +01005079 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
5080 saAttr.bInheritHandle = TRUE;
5081 saAttr.lpSecurityDescriptor = NULL;
5082 if (!CreatePipe(&ifd[0], &ifd[1], &saAttr, 0)
5083 || !pSetHandleInformation(ifd[1], HANDLE_FLAG_INHERIT, 0)
5084 || !CreatePipe(&ofd[0], &ofd[1], &saAttr, 0)
5085 || !pSetHandleInformation(ofd[0], HANDLE_FLAG_INHERIT, 0)
5086 || !CreatePipe(&efd[0], &efd[1], &saAttr, 0)
5087 || !pSetHandleInformation(efd[0], HANDLE_FLAG_INHERIT, 0))
5088 goto failed;
5089 si.dwFlags |= STARTF_USESTDHANDLES;
5090 si.hStdInput = ifd[0];
5091 si.hStdOutput = ofd[1];
5092 si.hStdError = efd[1];
Bram Moolenaar5d54a042016-02-16 16:39:51 +01005093# endif
Bram Moolenaard8070362016-02-15 21:56:54 +01005094
5095 if (!vim_create_process(cmd, TRUE,
Bram Moolenaar76467df2016-02-12 19:30:26 +01005096 CREATE_SUSPENDED |
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005097 CREATE_DEFAULT_ERROR_MODE |
5098 CREATE_NEW_PROCESS_GROUP |
Bram Moolenaar76467df2016-02-12 19:30:26 +01005099 CREATE_NEW_CONSOLE,
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005100 &si, &pi))
Bram Moolenaar76467df2016-02-12 19:30:26 +01005101 {
5102 CloseHandle(jo);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005103 job->jv_status = JOB_FAILED;
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005104 goto failed;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005105 }
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005106
5107 if (!AssignProcessToJobObject(jo, pi.hProcess))
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005108 {
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005109 /* if failing, switch the way to terminate
5110 * process with TerminateProcess. */
5111 CloseHandle(jo);
5112 jo = NULL;
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005113 }
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005114 ResumeThread(pi.hThread);
5115 CloseHandle(job->jv_proc_info.hThread);
5116 job->jv_proc_info = pi;
5117 job->jv_job_object = jo;
5118 job->jv_status = JOB_STARTED;
5119
Bram Moolenaar5d54a042016-02-16 16:39:51 +01005120# ifdef FEAT_CHANNEL
Bram Moolenaard8070362016-02-15 21:56:54 +01005121 CloseHandle(ifd[0]);
5122 CloseHandle(ofd[1]);
5123 CloseHandle(efd[1]);
5124
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005125 job->jv_channel = channel;
Bram Moolenaard8070362016-02-15 21:56:54 +01005126 channel_set_pipes(channel, (sock_T)ifd[1], (sock_T)ofd[0], (sock_T)efd[0]);
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005127 channel_set_job(channel, job);
Bram Moolenaar9a6e33a2016-02-16 19:25:12 +01005128 channel_set_mode(channel, options->jo_mode);
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005129
Bram Moolenaar16eb4f82016-02-14 23:02:34 +01005130# ifdef FEAT_GUI
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005131 channel_gui_register(channel);
Bram Moolenaar16eb4f82016-02-14 23:02:34 +01005132# endif
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005133# endif
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005134 return;
5135
5136failed:
Bram Moolenaar16eb4f82016-02-14 23:02:34 +01005137# ifdef FEAT_CHANNEL
Bram Moolenaard8070362016-02-15 21:56:54 +01005138 CloseHandle(ifd[0]);
5139 CloseHandle(ofd[0]);
5140 CloseHandle(efd[0]);
5141 CloseHandle(ifd[1]);
5142 CloseHandle(ofd[1]);
5143 CloseHandle(efd[1]);
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005144 channel_free(channel);
Bram Moolenaar71b0f7b2016-02-15 12:44:20 +01005145# else
5146 ; /* make compiler happy */
Bram Moolenaar16eb4f82016-02-14 23:02:34 +01005147# endif
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005148}
5149
5150 char *
5151mch_job_status(job_T *job)
5152{
5153 DWORD dwExitCode = 0;
5154
Bram Moolenaar76467df2016-02-12 19:30:26 +01005155 if (!GetExitCodeProcess(job->jv_proc_info.hProcess, &dwExitCode)
5156 || dwExitCode != STILL_ACTIVE)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005157 {
Bram Moolenaar76467df2016-02-12 19:30:26 +01005158 job->jv_status = JOB_ENDED;
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005159 return "dead";
5160 }
5161 return "run";
5162}
5163
5164 int
5165mch_stop_job(job_T *job, char_u *how)
5166{
Bram Moolenaar76467df2016-02-12 19:30:26 +01005167 int ret = 0;
5168 int ctrl_c = STRCMP(how, "int") == 0;
5169
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005170 if (STRCMP(how, "kill") == 0)
Bram Moolenaar76467df2016-02-12 19:30:26 +01005171 {
5172 if (job->jv_job_object != NULL)
5173 return TerminateJobObject(job->jv_job_object, 0) ? OK : FAIL;
5174 else
5175 return TerminateProcess(job->jv_proc_info.hProcess, 0) ? OK : FAIL;
5176 }
5177
5178 if (!AttachConsole(job->jv_proc_info.dwProcessId))
5179 return FAIL;
5180 ret = GenerateConsoleCtrlEvent(
5181 ctrl_c ? CTRL_C_EVENT : CTRL_BREAK_EVENT,
5182 job->jv_proc_info.dwProcessId)
5183 ? OK : FAIL;
5184 FreeConsole();
5185 return ret;
5186}
5187
5188/*
5189 * Clear the data related to "job".
5190 */
5191 void
5192mch_clear_job(job_T *job)
5193{
5194 if (job->jv_status != JOB_FAILED)
5195 {
5196 if (job->jv_job_object != NULL)
5197 CloseHandle(job->jv_job_object);
5198 CloseHandle(job->jv_proc_info.hProcess);
5199 }
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005200}
5201#endif
5202
Bram Moolenaar071d4272004-06-13 20:20:40 +00005203
5204#ifndef FEAT_GUI_W32
5205
5206/*
5207 * Start termcap mode
5208 */
5209 static void
5210termcap_mode_start(void)
5211{
5212 DWORD cmodein;
5213
5214 if (g_fTermcapMode)
5215 return;
5216
5217 SaveConsoleBuffer(&g_cbNonTermcap);
5218
5219 if (g_cbTermcap.IsValid)
5220 {
5221 /*
5222 * We've been in termcap mode before. Restore certain screen
5223 * characteristics, including the buffer size and the window
5224 * size. Since we will be redrawing the screen, we don't need
5225 * to restore the actual contents of the buffer.
5226 */
5227 RestoreConsoleBuffer(&g_cbTermcap, FALSE);
5228 SetConsoleWindowInfo(g_hConOut, TRUE, &g_cbTermcap.Info.srWindow);
5229 Rows = g_cbTermcap.Info.dwSize.Y;
5230 Columns = g_cbTermcap.Info.dwSize.X;
5231 }
5232 else
5233 {
5234 /*
5235 * This is our first time entering termcap mode. Clear the console
5236 * screen buffer, and resize the buffer to match the current window
5237 * size. We will use this as the size of our editing environment.
5238 */
5239 ClearConsoleBuffer(g_attrCurrent);
5240 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
5241 }
5242
5243#ifdef FEAT_TITLE
5244 resettitle();
5245#endif
5246
5247 GetConsoleMode(g_hConIn, &cmodein);
5248#ifdef FEAT_MOUSE
5249 if (g_fMouseActive)
5250 cmodein |= ENABLE_MOUSE_INPUT;
5251 else
5252 cmodein &= ~ENABLE_MOUSE_INPUT;
5253#endif
5254 cmodein |= ENABLE_WINDOW_INPUT;
5255 SetConsoleMode(g_hConIn, cmodein);
5256
5257 redraw_later_clear();
5258 g_fTermcapMode = TRUE;
5259}
5260
5261
5262/*
5263 * End termcap mode
5264 */
5265 static void
5266termcap_mode_end(void)
5267{
5268 DWORD cmodein;
5269 ConsoleBuffer *cb;
5270 COORD coord;
5271 DWORD dwDummy;
5272
5273 if (!g_fTermcapMode)
5274 return;
5275
5276 SaveConsoleBuffer(&g_cbTermcap);
5277
5278 GetConsoleMode(g_hConIn, &cmodein);
5279 cmodein &= ~(ENABLE_MOUSE_INPUT | ENABLE_WINDOW_INPUT);
5280 SetConsoleMode(g_hConIn, cmodein);
5281
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01005282#ifdef FEAT_RESTORE_ORIG_SCREEN
5283 cb = exiting ? &g_cbOrig : &g_cbNonTermcap;
5284#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00005285 cb = &g_cbNonTermcap;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01005286#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005287 RestoreConsoleBuffer(cb, p_rs);
5288 SetConsoleCursorInfo(g_hConOut, &g_cci);
5289
5290 if (p_rs || exiting)
5291 {
5292 /*
5293 * Clear anything that happens to be on the current line.
5294 */
5295 coord.X = 0;
5296 coord.Y = (SHORT) (p_rs ? cb->Info.dwCursorPosition.Y : (Rows - 1));
5297 FillConsoleOutputCharacter(g_hConOut, ' ',
5298 cb->Info.dwSize.X, coord, &dwDummy);
5299 /*
5300 * The following is just for aesthetics. If we are exiting without
5301 * restoring the screen, then we want to have a prompt string
5302 * appear at the bottom line. However, the command interpreter
5303 * seems to always advance the cursor one line before displaying
5304 * the prompt string, which causes the screen to scroll. To
5305 * counter this, move the cursor up one line before exiting.
5306 */
5307 if (exiting && !p_rs)
5308 coord.Y--;
5309 /*
5310 * Position the cursor at the leftmost column of the desired row.
5311 */
5312 SetConsoleCursorPosition(g_hConOut, coord);
5313 }
5314
5315 g_fTermcapMode = FALSE;
5316}
5317#endif /* FEAT_GUI_W32 */
5318
5319
5320#ifdef FEAT_GUI_W32
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00005321/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00005322 void
5323mch_write(
5324 char_u *s,
5325 int len)
5326{
5327 /* never used */
5328}
5329
5330#else
5331
5332/*
5333 * clear `n' chars, starting from `coord'
5334 */
5335 static void
5336clear_chars(
5337 COORD coord,
5338 DWORD n)
5339{
5340 DWORD dwDummy;
5341
5342 FillConsoleOutputCharacter(g_hConOut, ' ', n, coord, &dwDummy);
5343 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, n, coord, &dwDummy);
5344}
5345
5346
5347/*
5348 * Clear the screen
5349 */
5350 static void
5351clear_screen(void)
5352{
5353 g_coord.X = g_coord.Y = 0;
5354 clear_chars(g_coord, Rows * Columns);
5355}
5356
5357
5358/*
5359 * Clear to end of display
5360 */
5361 static void
5362clear_to_end_of_display(void)
5363{
5364 clear_chars(g_coord, (Rows - g_coord.Y - 1)
5365 * Columns + (Columns - g_coord.X));
5366}
5367
5368
5369/*
5370 * Clear to end of line
5371 */
5372 static void
5373clear_to_end_of_line(void)
5374{
5375 clear_chars(g_coord, Columns - g_coord.X);
5376}
5377
5378
5379/*
5380 * Scroll the scroll region up by `cLines' lines
5381 */
5382 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005383scroll(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005384{
5385 COORD oldcoord = g_coord;
5386
5387 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
5388 delete_lines(cLines);
5389
5390 g_coord = oldcoord;
5391}
5392
5393
5394/*
5395 * Set the scroll region
5396 */
5397 static void
5398set_scroll_region(
5399 unsigned left,
5400 unsigned top,
5401 unsigned right,
5402 unsigned bottom)
5403{
5404 if (left >= right
5405 || top >= bottom
5406 || right > (unsigned) Columns - 1
5407 || bottom > (unsigned) Rows - 1)
5408 return;
5409
5410 g_srScrollRegion.Left = left;
5411 g_srScrollRegion.Top = top;
5412 g_srScrollRegion.Right = right;
5413 g_srScrollRegion.Bottom = bottom;
5414}
5415
5416
5417/*
5418 * Insert `cLines' lines at the current cursor position
5419 */
5420 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005421insert_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005422{
5423 SMALL_RECT source;
5424 COORD dest;
5425 CHAR_INFO fill;
5426
5427 dest.X = 0;
5428 dest.Y = g_coord.Y + cLines;
5429
5430 source.Left = 0;
5431 source.Top = g_coord.Y;
5432 source.Right = g_srScrollRegion.Right;
5433 source.Bottom = g_srScrollRegion.Bottom - cLines;
5434
5435 fill.Char.AsciiChar = ' ';
5436 fill.Attributes = g_attrCurrent;
5437
5438 ScrollConsoleScreenBuffer(g_hConOut, &source, NULL, dest, &fill);
5439
5440 /* Here we have to deal with a win32 console flake: If the scroll
5441 * region looks like abc and we scroll c to a and fill with d we get
5442 * cbd... if we scroll block c one line at a time to a, we get cdd...
5443 * vim expects cdd consistently... So we have to deal with that
5444 * here... (this also occurs scrolling the same way in the other
5445 * direction). */
5446
5447 if (source.Bottom < dest.Y)
5448 {
5449 COORD coord;
5450
5451 coord.X = 0;
5452 coord.Y = source.Bottom;
5453 clear_chars(coord, Columns * (dest.Y - source.Bottom));
5454 }
5455}
5456
5457
5458/*
5459 * Delete `cLines' lines at the current cursor position
5460 */
5461 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005462delete_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005463{
5464 SMALL_RECT source;
5465 COORD dest;
5466 CHAR_INFO fill;
5467 int nb;
5468
5469 dest.X = 0;
5470 dest.Y = g_coord.Y;
5471
5472 source.Left = 0;
5473 source.Top = g_coord.Y + cLines;
5474 source.Right = g_srScrollRegion.Right;
5475 source.Bottom = g_srScrollRegion.Bottom;
5476
5477 fill.Char.AsciiChar = ' ';
5478 fill.Attributes = g_attrCurrent;
5479
5480 ScrollConsoleScreenBuffer(g_hConOut, &source, NULL, dest, &fill);
5481
5482 /* Here we have to deal with a win32 console flake: If the scroll
5483 * region looks like abc and we scroll c to a and fill with d we get
5484 * cbd... if we scroll block c one line at a time to a, we get cdd...
5485 * vim expects cdd consistently... So we have to deal with that
5486 * here... (this also occurs scrolling the same way in the other
5487 * direction). */
5488
5489 nb = dest.Y + (source.Bottom - source.Top) + 1;
5490
5491 if (nb < source.Top)
5492 {
5493 COORD coord;
5494
5495 coord.X = 0;
5496 coord.Y = nb;
5497 clear_chars(coord, Columns * (source.Top - nb));
5498 }
5499}
5500
5501
5502/*
5503 * Set the cursor position
5504 */
5505 static void
5506gotoxy(
5507 unsigned x,
5508 unsigned y)
5509{
5510 if (x < 1 || x > (unsigned)Columns || y < 1 || y > (unsigned)Rows)
5511 return;
5512
5513 /* external cursor coords are 1-based; internal are 0-based */
5514 g_coord.X = x - 1;
5515 g_coord.Y = y - 1;
5516 SetConsoleCursorPosition(g_hConOut, g_coord);
5517}
5518
5519
5520/*
5521 * Set the current text attribute = (foreground | background)
5522 * See ../doc/os_win32.txt for the numbers.
5523 */
5524 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005525textattr(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005526{
Bram Moolenaar6383b922015-03-24 17:12:19 +01005527 g_attrCurrent = wAttr & 0xff;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005528
5529 SetConsoleTextAttribute(g_hConOut, wAttr);
5530}
5531
5532
5533 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005534textcolor(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005535{
Bram Moolenaar6383b922015-03-24 17:12:19 +01005536 g_attrCurrent = (g_attrCurrent & 0xf0) + (wAttr & 0x0f);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005537
5538 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
5539}
5540
5541
5542 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005543textbackground(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005544{
Bram Moolenaar6383b922015-03-24 17:12:19 +01005545 g_attrCurrent = (g_attrCurrent & 0x0f) + ((wAttr & 0x0f) << 4);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005546
5547 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
5548}
5549
5550
5551/*
5552 * restore the default text attribute (whatever we started with)
5553 */
5554 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005555normvideo(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005556{
5557 textattr(g_attrDefault);
5558}
5559
5560
5561static WORD g_attrPreStandout = 0;
5562
5563/*
5564 * Make the text standout, by brightening it
5565 */
5566 static void
5567standout(void)
5568{
5569 g_attrPreStandout = g_attrCurrent;
5570 textattr((WORD) (g_attrCurrent|FOREGROUND_INTENSITY|BACKGROUND_INTENSITY));
5571}
5572
5573
5574/*
5575 * Turn off standout mode
5576 */
5577 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005578standend(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005579{
5580 if (g_attrPreStandout)
5581 {
5582 textattr(g_attrPreStandout);
5583 g_attrPreStandout = 0;
5584 }
5585}
5586
5587
5588/*
Bram Moolenaarff1d0d42007-05-10 17:24:16 +00005589 * Set normal fg/bg color, based on T_ME. Called when t_me has been set.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005590 */
5591 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005592mch_set_normal_colors(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005593{
5594 char_u *p;
5595 int n;
5596
5597 cterm_normal_fg_color = (g_attrDefault & 0xf) + 1;
5598 cterm_normal_bg_color = ((g_attrDefault >> 4) & 0xf) + 1;
5599 if (T_ME[0] == ESC && T_ME[1] == '|')
5600 {
5601 p = T_ME + 2;
5602 n = getdigits(&p);
5603 if (*p == 'm' && n > 0)
5604 {
5605 cterm_normal_fg_color = (n & 0xf) + 1;
5606 cterm_normal_bg_color = ((n >> 4) & 0xf) + 1;
5607 }
5608 }
5609}
5610
5611
5612/*
5613 * visual bell: flash the screen
5614 */
5615 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005616visual_bell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005617{
5618 COORD coordOrigin = {0, 0};
5619 WORD attrFlash = ~g_attrCurrent & 0xff;
5620
5621 DWORD dwDummy;
5622 LPWORD oldattrs = (LPWORD)alloc(Rows * Columns * sizeof(WORD));
5623
5624 if (oldattrs == NULL)
5625 return;
5626 ReadConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
5627 coordOrigin, &dwDummy);
5628 FillConsoleOutputAttribute(g_hConOut, attrFlash, Rows * Columns,
5629 coordOrigin, &dwDummy);
5630
5631 Sleep(15); /* wait for 15 msec */
5632 WriteConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
5633 coordOrigin, &dwDummy);
5634 vim_free(oldattrs);
5635}
5636
5637
5638/*
5639 * Make the cursor visible or invisible
5640 */
5641 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005642cursor_visible(BOOL fVisible)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005643{
5644 s_cursor_visible = fVisible;
5645#ifdef MCH_CURSOR_SHAPE
5646 mch_update_cursor();
5647#endif
5648}
5649
5650
5651/*
Bram Moolenaarac360bf2015-09-01 20:31:20 +02005652 * write `cbToWrite' bytes in `pchBuf' to the screen
5653 * Returns the number of bytes actually written (at least one).
Bram Moolenaar071d4272004-06-13 20:20:40 +00005654 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02005655 static DWORD
Bram Moolenaar071d4272004-06-13 20:20:40 +00005656write_chars(
Bram Moolenaarac360bf2015-09-01 20:31:20 +02005657 char_u *pchBuf,
5658 DWORD cbToWrite)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005659{
5660 COORD coord = g_coord;
5661 DWORD written;
5662
Bram Moolenaarac360bf2015-09-01 20:31:20 +02005663#ifdef FEAT_MBYTE
5664 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
5665 {
5666 static WCHAR *unicodebuf = NULL;
5667 static int unibuflen = 0;
5668 int length;
5669 DWORD n, cchwritten, cells;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005670
Bram Moolenaarac360bf2015-09-01 20:31:20 +02005671 length = MultiByteToWideChar(CP_UTF8, 0, (LPCSTR)pchBuf, cbToWrite, 0, 0);
5672 if (unicodebuf == NULL || length > unibuflen)
5673 {
5674 vim_free(unicodebuf);
5675 unicodebuf = (WCHAR *)lalloc(length * sizeof(WCHAR), FALSE);
5676 unibuflen = length;
5677 }
5678 MultiByteToWideChar(CP_UTF8, 0, (LPCSTR)pchBuf, cbToWrite,
5679 unicodebuf, unibuflen);
5680
5681 cells = mb_string2cells(pchBuf, cbToWrite);
5682 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, cells,
5683 coord, &written);
5684 /* When writing fails or didn't write a single character, pretend one
5685 * character was written, otherwise we get stuck. */
5686 if (WriteConsoleOutputCharacterW(g_hConOut, unicodebuf, length,
5687 coord, &cchwritten) == 0
5688 || cchwritten == 0)
5689 cchwritten = 1;
5690
5691 if (cchwritten == length)
5692 {
5693 written = cbToWrite;
5694 g_coord.X += (SHORT)cells;
5695 }
5696 else
5697 {
5698 char_u *p = pchBuf;
5699 for (n = 0; n < cchwritten; n++)
5700 mb_cptr_adv(p);
5701 written = p - pchBuf;
5702 g_coord.X += (SHORT)mb_string2cells(pchBuf, written);
5703 }
5704 }
5705 else
5706#endif
5707 {
5708 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, cbToWrite,
5709 coord, &written);
5710 /* When writing fails or didn't write a single character, pretend one
5711 * character was written, otherwise we get stuck. */
5712 if (WriteConsoleOutputCharacter(g_hConOut, (LPCSTR)pchBuf, cbToWrite,
5713 coord, &written) == 0
5714 || written == 0)
5715 written = 1;
5716
5717 g_coord.X += (SHORT) written;
5718 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005719
5720 while (g_coord.X > g_srScrollRegion.Right)
5721 {
5722 g_coord.X -= (SHORT) Columns;
5723 if (g_coord.Y < g_srScrollRegion.Bottom)
5724 g_coord.Y++;
5725 }
5726
5727 gotoxy(g_coord.X + 1, g_coord.Y + 1);
5728
5729 return written;
5730}
5731
5732
5733/*
5734 * mch_write(): write the output buffer to the screen, translating ESC
5735 * sequences into calls to console output routines.
5736 */
5737 void
5738mch_write(
5739 char_u *s,
5740 int len)
5741{
5742 s[len] = NUL;
5743
5744 if (!term_console)
5745 {
5746 write(1, s, (unsigned)len);
5747 return;
5748 }
5749
5750 /* translate ESC | sequences into faked bios calls */
5751 while (len--)
5752 {
5753 /* optimization: use one single write_chars for runs of text,
5754 * rather than once per character It ain't curses, but it helps. */
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01005755 DWORD prefix = (DWORD)strcspn((char *)s, "\n\r\b\a\033");
Bram Moolenaar071d4272004-06-13 20:20:40 +00005756
5757 if (p_wd)
5758 {
5759 WaitForChar(p_wd);
5760 if (prefix != 0)
5761 prefix = 1;
5762 }
5763
5764 if (prefix != 0)
5765 {
5766 DWORD nWritten;
5767
5768 nWritten = write_chars(s, prefix);
5769#ifdef MCH_WRITE_DUMP
5770 if (fdDump)
5771 {
5772 fputc('>', fdDump);
5773 fwrite(s, sizeof(char_u), nWritten, fdDump);
5774 fputs("<\n", fdDump);
5775 }
5776#endif
5777 len -= (nWritten - 1);
5778 s += nWritten;
5779 }
5780 else if (s[0] == '\n')
5781 {
5782 /* \n, newline: go to the beginning of the next line or scroll */
5783 if (g_coord.Y == g_srScrollRegion.Bottom)
5784 {
5785 scroll(1);
5786 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Bottom + 1);
5787 }
5788 else
5789 {
5790 gotoxy(g_srScrollRegion.Left + 1, g_coord.Y + 2);
5791 }
5792#ifdef MCH_WRITE_DUMP
5793 if (fdDump)
5794 fputs("\\n\n", fdDump);
5795#endif
5796 s++;
5797 }
5798 else if (s[0] == '\r')
5799 {
5800 /* \r, carriage return: go to beginning of line */
5801 gotoxy(g_srScrollRegion.Left+1, g_coord.Y + 1);
5802#ifdef MCH_WRITE_DUMP
5803 if (fdDump)
5804 fputs("\\r\n", fdDump);
5805#endif
5806 s++;
5807 }
5808 else if (s[0] == '\b')
5809 {
5810 /* \b, backspace: move cursor one position left */
5811 if (g_coord.X > g_srScrollRegion.Left)
5812 g_coord.X--;
5813 else if (g_coord.Y > g_srScrollRegion.Top)
5814 {
5815 g_coord.X = g_srScrollRegion.Right;
5816 g_coord.Y--;
5817 }
5818 gotoxy(g_coord.X + 1, g_coord.Y + 1);
5819#ifdef MCH_WRITE_DUMP
5820 if (fdDump)
5821 fputs("\\b\n", fdDump);
5822#endif
5823 s++;
5824 }
5825 else if (s[0] == '\a')
5826 {
5827 /* \a, bell */
5828 MessageBeep(0xFFFFFFFF);
5829#ifdef MCH_WRITE_DUMP
5830 if (fdDump)
5831 fputs("\\a\n", fdDump);
5832#endif
5833 s++;
5834 }
5835 else if (s[0] == ESC && len >= 3-1 && s[1] == '|')
5836 {
5837#ifdef MCH_WRITE_DUMP
Bram Moolenaarc0197e22004-09-13 20:26:32 +00005838 char_u *old_s = s;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005839#endif
Bram Moolenaarc0197e22004-09-13 20:26:32 +00005840 char_u *p;
5841 int arg1 = 0, arg2 = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005842
5843 switch (s[2])
5844 {
5845 /* one or two numeric arguments, separated by ';' */
5846
5847 case '0': case '1': case '2': case '3': case '4':
5848 case '5': case '6': case '7': case '8': case '9':
5849 p = s + 2;
5850 arg1 = getdigits(&p); /* no check for length! */
5851 if (p > s + len)
5852 break;
5853
5854 if (*p == ';')
5855 {
5856 ++p;
5857 arg2 = getdigits(&p); /* no check for length! */
5858 if (p > s + len)
5859 break;
5860
5861 if (*p == 'H')
5862 gotoxy(arg2, arg1);
5863 else if (*p == 'r')
5864 set_scroll_region(0, arg1 - 1, Columns - 1, arg2 - 1);
5865 }
5866 else if (*p == 'A')
5867 {
5868 /* move cursor up arg1 lines in same column */
5869 gotoxy(g_coord.X + 1,
5870 max(g_srScrollRegion.Top, g_coord.Y - arg1) + 1);
5871 }
5872 else if (*p == 'C')
5873 {
5874 /* move cursor right arg1 columns in same line */
5875 gotoxy(min(g_srScrollRegion.Right, g_coord.X + arg1) + 1,
5876 g_coord.Y + 1);
5877 }
5878 else if (*p == 'H')
5879 {
5880 gotoxy(1, arg1);
5881 }
5882 else if (*p == 'L')
5883 {
5884 insert_lines(arg1);
5885 }
5886 else if (*p == 'm')
5887 {
5888 if (arg1 == 0)
5889 normvideo();
5890 else
5891 textattr((WORD) arg1);
5892 }
5893 else if (*p == 'f')
5894 {
5895 textcolor((WORD) arg1);
5896 }
5897 else if (*p == 'b')
5898 {
5899 textbackground((WORD) arg1);
5900 }
5901 else if (*p == 'M')
5902 {
5903 delete_lines(arg1);
5904 }
5905
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005906 len -= (int)(p - s);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005907 s = p + 1;
5908 break;
5909
5910
5911 /* Three-character escape sequences */
5912
5913 case 'A':
5914 /* move cursor up one line in same column */
5915 gotoxy(g_coord.X + 1,
5916 max(g_srScrollRegion.Top, g_coord.Y - 1) + 1);
5917 goto got3;
5918
5919 case 'B':
5920 visual_bell();
5921 goto got3;
5922
5923 case 'C':
5924 /* move cursor right one column in same line */
5925 gotoxy(min(g_srScrollRegion.Right, g_coord.X + 1) + 1,
5926 g_coord.Y + 1);
5927 goto got3;
5928
5929 case 'E':
5930 termcap_mode_end();
5931 goto got3;
5932
5933 case 'F':
5934 standout();
5935 goto got3;
5936
5937 case 'f':
5938 standend();
5939 goto got3;
5940
5941 case 'H':
5942 gotoxy(1, 1);
5943 goto got3;
5944
5945 case 'j':
5946 clear_to_end_of_display();
5947 goto got3;
5948
5949 case 'J':
5950 clear_screen();
5951 goto got3;
5952
5953 case 'K':
5954 clear_to_end_of_line();
5955 goto got3;
5956
5957 case 'L':
5958 insert_lines(1);
5959 goto got3;
5960
5961 case 'M':
5962 delete_lines(1);
5963 goto got3;
5964
5965 case 'S':
5966 termcap_mode_start();
5967 goto got3;
5968
5969 case 'V':
5970 cursor_visible(TRUE);
5971 goto got3;
5972
5973 case 'v':
5974 cursor_visible(FALSE);
5975 goto got3;
5976
5977 got3:
5978 s += 3;
5979 len -= 2;
5980 }
5981
5982#ifdef MCH_WRITE_DUMP
5983 if (fdDump)
5984 {
5985 fputs("ESC | ", fdDump);
5986 fwrite(old_s + 2, sizeof(char_u), s - old_s - 2, fdDump);
5987 fputc('\n', fdDump);
5988 }
5989#endif
5990 }
5991 else
5992 {
5993 /* Write a single character */
5994 DWORD nWritten;
5995
5996 nWritten = write_chars(s, 1);
5997#ifdef MCH_WRITE_DUMP
5998 if (fdDump)
5999 {
6000 fputc('>', fdDump);
6001 fwrite(s, sizeof(char_u), nWritten, fdDump);
6002 fputs("<\n", fdDump);
6003 }
6004#endif
6005
6006 len -= (nWritten - 1);
6007 s += nWritten;
6008 }
6009 }
6010
6011#ifdef MCH_WRITE_DUMP
6012 if (fdDump)
6013 fflush(fdDump);
6014#endif
6015}
6016
6017#endif /* FEAT_GUI_W32 */
6018
6019
6020/*
6021 * Delay for half a second.
6022 */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00006023/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00006024 void
6025mch_delay(
6026 long msec,
6027 int ignoreinput)
6028{
6029#ifdef FEAT_GUI_W32
6030 Sleep((int)msec); /* never wait for input */
Bram Moolenaar325b7a22004-07-05 15:58:32 +00006031#else /* Console */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006032 if (ignoreinput)
Bram Moolenaar325b7a22004-07-05 15:58:32 +00006033# ifdef FEAT_MZSCHEME
6034 if (mzthreads_allowed() && p_mzq > 0 && msec > p_mzq)
6035 {
6036 int towait = p_mzq;
6037
6038 /* if msec is large enough, wait by portions in p_mzq */
6039 while (msec > 0)
6040 {
6041 mzvim_check_threads();
6042 if (msec < towait)
6043 towait = msec;
6044 Sleep(towait);
6045 msec -= towait;
6046 }
6047 }
6048 else
6049# endif
6050 Sleep((int)msec);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006051 else
6052 WaitForChar(msec);
6053#endif
6054}
6055
6056
6057/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01006058 * This version of remove is not scared by a readonly (backup) file.
6059 * This can also remove a symbolic link like Unix.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006060 * Return 0 for success, -1 for failure.
6061 */
6062 int
6063mch_remove(char_u *name)
6064{
6065#ifdef FEAT_MBYTE
6066 WCHAR *wn = NULL;
6067 int n;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02006068#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006069
Bram Moolenaar203258c2016-01-17 22:15:16 +01006070 /*
6071 * On Windows, deleting a directory's symbolic link is done by
6072 * RemoveDirectory(): mch_rmdir. It seems unnatural, but it is fact.
6073 */
6074 if (mch_isdir(name) && mch_is_symbolic_link(name))
6075 return mch_rmdir(name);
6076
Bram Moolenaar12b559e2013-06-12 22:41:37 +02006077 win32_setattrs(name, FILE_ATTRIBUTE_NORMAL);
6078
6079#ifdef FEAT_MBYTE
Bram Moolenaar071d4272004-06-13 20:20:40 +00006080 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
6081 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006082 wn = enc_to_utf16(name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006083 if (wn != NULL)
6084 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006085 n = DeleteFileW(wn) ? 0 : -1;
6086 vim_free(wn);
6087 if (n == 0 || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
6088 return n;
6089 /* Retry with non-wide function (for Windows 98). */
6090 }
6091 }
6092#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006093 return DeleteFile((LPCSTR)name) ? 0 : -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006094}
6095
6096
6097/*
6098 * check for an "interrupt signal": CTRL-break or CTRL-C
6099 */
6100 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006101mch_breakcheck(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006102{
6103#ifndef FEAT_GUI_W32 /* never used */
6104 if (g_fCtrlCPressed || g_fCBrkPressed)
6105 {
6106 g_fCtrlCPressed = g_fCBrkPressed = FALSE;
6107 got_int = TRUE;
6108 }
6109#endif
6110}
6111
Bram Moolenaaree273972016-01-02 21:11:51 +01006112/* physical RAM to leave for the OS */
6113#define WINNT_RESERVE_BYTES (256*1024*1024)
6114#define WIN95_RESERVE_BYTES (8*1024*1024)
6115
6116/*
6117 * How much main memory in KiB that can be used by VIM.
6118 */
6119/*ARGSUSED*/
6120 long_u
6121mch_total_mem(int special)
6122{
6123 PlatformId();
6124#if (defined(_MSC_VER) && (WINVER > 0x0400)) || defined(MEMORYSTATUSEX)
6125 if (g_PlatformId == VER_PLATFORM_WIN32_NT)
6126 {
6127 MEMORYSTATUSEX ms;
6128
6129 /* Need to use GlobalMemoryStatusEx() when there is more memory than
6130 * what fits in 32 bits. But it's not always available. */
6131 ms.dwLength = sizeof(MEMORYSTATUSEX);
6132 GlobalMemoryStatusEx(&ms);
6133 if (ms.ullAvailVirtual < ms.ullTotalPhys)
6134 {
6135 /* Process address space fits in physical RAM, use all of it. */
6136 return (long_u)(ms.ullAvailVirtual / 1024);
6137 }
6138 if (ms.ullTotalPhys <= WINNT_RESERVE_BYTES)
6139 {
6140 /* Catch old NT box or perverse hardware setup. */
6141 return (long_u)((ms.ullTotalPhys / 2) / 1024);
6142 }
6143 /* Use physical RAM less reserve for OS + data. */
6144 return (long_u)((ms.ullTotalPhys - WINNT_RESERVE_BYTES) / 1024);
6145 }
6146 else
6147#endif
6148 {
6149 /* Pre-XP or 95 OS handling. */
6150 MEMORYSTATUS ms;
6151 long_u os_reserve_bytes;
6152
6153 ms.dwLength = sizeof(MEMORYSTATUS);
6154 GlobalMemoryStatus(&ms);
6155 if (ms.dwAvailVirtual < ms.dwTotalPhys)
6156 {
6157 /* Process address space fits in physical RAM, use all of it. */
6158 return (long_u)(ms.dwAvailVirtual / 1024);
6159 }
6160 os_reserve_bytes = (g_PlatformId == VER_PLATFORM_WIN32_NT)
6161 ? WINNT_RESERVE_BYTES
6162 : WIN95_RESERVE_BYTES;
6163 if (ms.dwTotalPhys <= os_reserve_bytes)
6164 {
6165 /* Catch old boxes or perverse hardware setup. */
6166 return (long_u)((ms.dwTotalPhys / 2) / 1024);
6167 }
6168 /* Use physical RAM less reserve for OS + data. */
6169 return (long_u)((ms.dwTotalPhys - os_reserve_bytes) / 1024);
6170 }
6171}
Bram Moolenaar071d4272004-06-13 20:20:40 +00006172
Bram Moolenaar071d4272004-06-13 20:20:40 +00006173#ifdef FEAT_MBYTE
6174/*
6175 * Same code as below, but with wide functions and no comments.
6176 * Return 0 for success, non-zero for failure.
6177 */
6178 int
6179mch_wrename(WCHAR *wold, WCHAR *wnew)
6180{
6181 WCHAR *p;
6182 int i;
6183 WCHAR szTempFile[_MAX_PATH + 1];
6184 WCHAR szNewPath[_MAX_PATH + 1];
6185 HANDLE hf;
6186
6187 if (!mch_windows95())
6188 {
6189 p = wold;
6190 for (i = 0; wold[i] != NUL; ++i)
6191 if ((wold[i] == '/' || wold[i] == '\\' || wold[i] == ':')
6192 && wold[i + 1] != 0)
6193 p = wold + i + 1;
6194 if ((int)(wold + i - p) < 8 || p[6] != '~')
6195 return (MoveFileW(wold, wnew) == 0);
6196 }
6197
6198 if (GetFullPathNameW(wnew, _MAX_PATH, szNewPath, &p) == 0 || p == NULL)
6199 return -1;
6200 *p = NUL;
6201
6202 if (GetTempFileNameW(szNewPath, L"VIM", 0, szTempFile) == 0)
6203 return -2;
6204
6205 if (!DeleteFileW(szTempFile))
6206 return -3;
6207
6208 if (!MoveFileW(wold, szTempFile))
6209 return -4;
6210
6211 if ((hf = CreateFileW(wold, GENERIC_WRITE, 0, NULL, CREATE_NEW,
6212 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
6213 return -5;
6214 if (!CloseHandle(hf))
6215 return -6;
6216
6217 if (!MoveFileW(szTempFile, wnew))
6218 {
6219 (void)MoveFileW(szTempFile, wold);
6220 return -7;
6221 }
6222
6223 DeleteFileW(szTempFile);
6224
6225 if (!DeleteFileW(wold))
6226 return -8;
6227
6228 return 0;
6229}
6230#endif
6231
6232
6233/*
6234 * mch_rename() works around a bug in rename (aka MoveFile) in
6235 * Windows 95: rename("foo.bar", "foo.bar~") will generate a
6236 * file whose short file name is "FOO.BAR" (its long file name will
6237 * be correct: "foo.bar~"). Because a file can be accessed by
6238 * either its SFN or its LFN, "foo.bar" has effectively been
6239 * renamed to "foo.bar", which is not at all what was wanted. This
6240 * seems to happen only when renaming files with three-character
6241 * extensions by appending a suffix that does not include ".".
6242 * Windows NT gets it right, however, with an SFN of "FOO~1.BAR".
6243 *
6244 * There is another problem, which isn't really a bug but isn't right either:
6245 * When renaming "abcdef~1.txt" to "abcdef~1.txt~", the short name can be
6246 * "abcdef~1.txt" again. This has been reported on Windows NT 4.0 with
6247 * service pack 6. Doesn't seem to happen on Windows 98.
6248 *
6249 * Like rename(), returns 0 upon success, non-zero upon failure.
6250 * Should probably set errno appropriately when errors occur.
6251 */
6252 int
6253mch_rename(
6254 const char *pszOldFile,
6255 const char *pszNewFile)
6256{
6257 char szTempFile[_MAX_PATH+1];
6258 char szNewPath[_MAX_PATH+1];
6259 char *pszFilePart;
6260 HANDLE hf;
6261#ifdef FEAT_MBYTE
6262 WCHAR *wold = NULL;
6263 WCHAR *wnew = NULL;
6264 int retval = -1;
6265
6266 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
6267 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006268 wold = enc_to_utf16((char_u *)pszOldFile, NULL);
6269 wnew = enc_to_utf16((char_u *)pszNewFile, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006270 if (wold != NULL && wnew != NULL)
6271 retval = mch_wrename(wold, wnew);
6272 vim_free(wold);
6273 vim_free(wnew);
6274 if (retval == 0 || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
6275 return retval;
6276 /* Retry with non-wide function (for Windows 98). */
6277 }
6278#endif
6279
6280 /*
6281 * No need to play tricks if not running Windows 95, unless the file name
6282 * contains a "~" as the seventh character.
6283 */
6284 if (!mch_windows95())
6285 {
6286 pszFilePart = (char *)gettail((char_u *)pszOldFile);
6287 if (STRLEN(pszFilePart) < 8 || pszFilePart[6] != '~')
6288 return rename(pszOldFile, pszNewFile);
6289 }
6290
6291 /* Get base path of new file name. Undocumented feature: If pszNewFile is
6292 * a directory, no error is returned and pszFilePart will be NULL. */
6293 if (GetFullPathName(pszNewFile, _MAX_PATH, szNewPath, &pszFilePart) == 0
6294 || pszFilePart == NULL)
6295 return -1;
6296 *pszFilePart = NUL;
6297
6298 /* Get (and create) a unique temporary file name in directory of new file */
6299 if (GetTempFileName(szNewPath, "VIM", 0, szTempFile) == 0)
6300 return -2;
6301
6302 /* blow the temp file away */
6303 if (!DeleteFile(szTempFile))
6304 return -3;
6305
6306 /* rename old file to the temp file */
6307 if (!MoveFile(pszOldFile, szTempFile))
6308 return -4;
6309
6310 /* now create an empty file called pszOldFile; this prevents the operating
6311 * system using pszOldFile as an alias (SFN) if we're renaming within the
6312 * same directory. For example, we're editing a file called
6313 * filename.asc.txt by its SFN, filena~1.txt. If we rename filena~1.txt
6314 * to filena~1.txt~ (i.e., we're making a backup while writing it), the
6315 * SFN for filena~1.txt~ will be filena~1.txt, by default, which will
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006316 * cause all sorts of problems later in buf_write(). So, we create an
6317 * empty file called filena~1.txt and the system will have to find some
6318 * other SFN for filena~1.txt~, such as filena~2.txt
Bram Moolenaar071d4272004-06-13 20:20:40 +00006319 */
6320 if ((hf = CreateFile(pszOldFile, GENERIC_WRITE, 0, NULL, CREATE_NEW,
6321 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
6322 return -5;
6323 if (!CloseHandle(hf))
6324 return -6;
6325
6326 /* rename the temp file to the new file */
6327 if (!MoveFile(szTempFile, pszNewFile))
6328 {
6329 /* Renaming failed. Rename the file back to its old name, so that it
6330 * looks like nothing happened. */
6331 (void)MoveFile(szTempFile, pszOldFile);
6332
6333 return -7;
6334 }
6335
6336 /* Seems to be left around on Novell filesystems */
6337 DeleteFile(szTempFile);
6338
6339 /* finally, remove the empty old file */
6340 if (!DeleteFile(pszOldFile))
6341 return -8;
6342
6343 return 0; /* success */
6344}
6345
6346/*
6347 * Get the default shell for the current hardware platform
6348 */
6349 char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006350default_shell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006351{
6352 char* psz = NULL;
6353
6354 PlatformId();
6355
6356 if (g_PlatformId == VER_PLATFORM_WIN32_NT) /* Windows NT */
6357 psz = "cmd.exe";
6358 else if (g_PlatformId == VER_PLATFORM_WIN32_WINDOWS) /* Windows 95 */
6359 psz = "command.com";
6360
6361 return psz;
6362}
6363
6364/*
6365 * mch_access() extends access() to do more detailed check on network drives.
6366 * Returns 0 if file "n" has access rights according to "p", -1 otherwise.
6367 */
6368 int
6369mch_access(char *n, int p)
6370{
6371 HANDLE hFile;
6372 DWORD am;
6373 int retval = -1; /* default: fail */
6374#ifdef FEAT_MBYTE
6375 WCHAR *wn = NULL;
6376
6377 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006378 wn = enc_to_utf16((char_u *)n, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006379#endif
6380
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006381 if (mch_isdir((char_u *)n))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006382 {
6383 char TempName[_MAX_PATH + 16] = "";
6384#ifdef FEAT_MBYTE
6385 WCHAR TempNameW[_MAX_PATH + 16] = L"";
6386#endif
6387
6388 if (p & R_OK)
6389 {
6390 /* Read check is performed by seeing if we can do a find file on
6391 * the directory for any file. */
6392#ifdef FEAT_MBYTE
6393 if (wn != NULL)
6394 {
6395 int i;
6396 WIN32_FIND_DATAW d;
6397
6398 for (i = 0; i < _MAX_PATH && wn[i] != 0; ++i)
6399 TempNameW[i] = wn[i];
6400 if (TempNameW[i - 1] != '\\' && TempNameW[i - 1] != '/')
6401 TempNameW[i++] = '\\';
6402 TempNameW[i++] = '*';
6403 TempNameW[i++] = 0;
6404
6405 hFile = FindFirstFileW(TempNameW, &d);
6406 if (hFile == INVALID_HANDLE_VALUE)
6407 {
6408 if (GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
6409 goto getout;
6410
6411 /* Retry with non-wide function (for Windows 98). */
6412 vim_free(wn);
6413 wn = NULL;
6414 }
6415 else
6416 (void)FindClose(hFile);
6417 }
6418 if (wn == NULL)
6419#endif
6420 {
6421 char *pch;
6422 WIN32_FIND_DATA d;
6423
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006424 vim_strncpy((char_u *)TempName, (char_u *)n, _MAX_PATH);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006425 pch = TempName + STRLEN(TempName) - 1;
6426 if (*pch != '\\' && *pch != '/')
6427 *++pch = '\\';
6428 *++pch = '*';
6429 *++pch = NUL;
6430
6431 hFile = FindFirstFile(TempName, &d);
6432 if (hFile == INVALID_HANDLE_VALUE)
6433 goto getout;
6434 (void)FindClose(hFile);
6435 }
6436 }
6437
6438 if (p & W_OK)
6439 {
6440 /* Trying to create a temporary file in the directory should catch
6441 * directories on read-only network shares. However, in
6442 * directories whose ACL allows writes but denies deletes will end
6443 * up keeping the temporary file :-(. */
6444#ifdef FEAT_MBYTE
6445 if (wn != NULL)
6446 {
6447 if (!GetTempFileNameW(wn, L"VIM", 0, TempNameW))
6448 {
6449 if (GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
6450 goto getout;
6451
6452 /* Retry with non-wide function (for Windows 98). */
6453 vim_free(wn);
6454 wn = NULL;
6455 }
6456 else
6457 DeleteFileW(TempNameW);
6458 }
6459 if (wn == NULL)
6460#endif
6461 {
6462 if (!GetTempFileName(n, "VIM", 0, TempName))
6463 goto getout;
6464 mch_remove((char_u *)TempName);
6465 }
6466 }
6467 }
6468 else
6469 {
6470 /* Trying to open the file for the required access does ACL, read-only
6471 * network share, and file attribute checks. */
6472 am = ((p & W_OK) ? GENERIC_WRITE : 0)
6473 | ((p & R_OK) ? GENERIC_READ : 0);
6474#ifdef FEAT_MBYTE
6475 if (wn != NULL)
6476 {
6477 hFile = CreateFileW(wn, am, 0, NULL, OPEN_EXISTING, 0, NULL);
6478 if (hFile == INVALID_HANDLE_VALUE
6479 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
6480 {
6481 /* Retry with non-wide function (for Windows 98). */
6482 vim_free(wn);
6483 wn = NULL;
6484 }
6485 }
6486 if (wn == NULL)
6487#endif
6488 hFile = CreateFile(n, am, 0, NULL, OPEN_EXISTING, 0, NULL);
6489 if (hFile == INVALID_HANDLE_VALUE)
6490 goto getout;
6491 CloseHandle(hFile);
6492 }
6493
6494 retval = 0; /* success */
6495getout:
6496#ifdef FEAT_MBYTE
6497 vim_free(wn);
6498#endif
6499 return retval;
6500}
6501
6502#if defined(FEAT_MBYTE) || defined(PROTO)
6503/*
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006504 * Version of open() that may use UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006505 */
6506 int
6507mch_open(char *name, int flags, int mode)
6508{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006509 /* _wopen() does not work with Borland C 5.5: creates a read-only file. */
6510# ifndef __BORLANDC__
Bram Moolenaar071d4272004-06-13 20:20:40 +00006511 WCHAR *wn;
6512 int f;
6513
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006514 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006515 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006516 wn = enc_to_utf16((char_u *)name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006517 if (wn != NULL)
6518 {
6519 f = _wopen(wn, flags, mode);
6520 vim_free(wn);
Bram Moolenaarcd981f22014-02-11 17:06:00 +01006521 if (f >= 0 || g_PlatformId == VER_PLATFORM_WIN32_NT)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006522 return f;
6523 /* Retry with non-wide function (for Windows 98). Can't use
6524 * GetLastError() here and it's unclear what errno gets set to if
6525 * the _wopen() fails for missing wide functions. */
6526 }
6527 }
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006528# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006529
Bram Moolenaarf9e6c3b2014-11-05 18:36:03 +01006530 /* open() can open a file which name is longer than _MAX_PATH bytes
6531 * and shorter than _MAX_PATH characters successfully, but sometimes it
6532 * causes unexpected error in another part. We make it an error explicitly
6533 * here. */
6534 if (strlen(name) >= _MAX_PATH)
6535 return -1;
6536
Bram Moolenaar071d4272004-06-13 20:20:40 +00006537 return open(name, flags, mode);
6538}
6539
6540/*
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006541 * Version of fopen() that may use UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006542 */
6543 FILE *
6544mch_fopen(char *name, char *mode)
6545{
6546 WCHAR *wn, *wm;
6547 FILE *f = NULL;
6548
6549 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage
6550# ifdef __BORLANDC__
6551 /* Wide functions of Borland C 5.5 do not work on Windows 98. */
6552 && g_PlatformId == VER_PLATFORM_WIN32_NT
6553# endif
6554 )
6555 {
Bram Moolenaare6a91fd2008-07-24 18:51:11 +00006556# if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0fde2902008-03-16 13:54:13 +00006557 /* Work around an annoying assertion in the Microsoft debug CRT
6558 * when mode's text/binary setting doesn't match _get_fmode(). */
6559 char newMode = mode[strlen(mode) - 1];
6560 int oldMode = 0;
6561
6562 _get_fmode(&oldMode);
6563 if (newMode == 't')
6564 _set_fmode(_O_TEXT);
6565 else if (newMode == 'b')
6566 _set_fmode(_O_BINARY);
6567# endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006568 wn = enc_to_utf16((char_u *)name, NULL);
6569 wm = enc_to_utf16((char_u *)mode, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006570 if (wn != NULL && wm != NULL)
6571 f = _wfopen(wn, wm);
6572 vim_free(wn);
6573 vim_free(wm);
Bram Moolenaar0fde2902008-03-16 13:54:13 +00006574
Bram Moolenaare6a91fd2008-07-24 18:51:11 +00006575# if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0fde2902008-03-16 13:54:13 +00006576 _set_fmode(oldMode);
6577# endif
6578
Bram Moolenaarcd981f22014-02-11 17:06:00 +01006579 if (f != NULL || g_PlatformId == VER_PLATFORM_WIN32_NT)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006580 return f;
6581 /* Retry with non-wide function (for Windows 98). Can't use
6582 * GetLastError() here and it's unclear what errno gets set to if
6583 * the _wfopen() fails for missing wide functions. */
6584 }
6585
Bram Moolenaarf9e6c3b2014-11-05 18:36:03 +01006586 /* fopen() can open a file which name is longer than _MAX_PATH bytes
6587 * and shorter than _MAX_PATH characters successfully, but sometimes it
6588 * causes unexpected error in another part. We make it an error explicitly
6589 * here. */
6590 if (strlen(name) >= _MAX_PATH)
6591 return NULL;
6592
Bram Moolenaar071d4272004-06-13 20:20:40 +00006593 return fopen(name, mode);
6594}
6595#endif
6596
6597#ifdef FEAT_MBYTE
6598/*
6599 * SUB STREAM (aka info stream) handling:
6600 *
6601 * NTFS can have sub streams for each file. Normal contents of file is
6602 * stored in the main stream, and extra contents (author information and
6603 * title and so on) can be stored in sub stream. After Windows 2000, user
6604 * can access and store those informations in sub streams via explorer's
6605 * property menuitem in right click menu. Those informations in sub streams
6606 * were lost when copying only the main stream. So we have to copy sub
6607 * streams.
6608 *
6609 * Incomplete explanation:
6610 * http://msdn.microsoft.com/library/en-us/dnw2k/html/ntfs5.asp
6611 * More useful info and an example:
6612 * http://www.sysinternals.com/ntw2k/source/misc.shtml#streams
6613 */
6614
6615/*
6616 * Copy info stream data "substream". Read from the file with BackupRead(sh)
6617 * and write to stream "substream" of file "to".
6618 * Errors are ignored.
6619 */
6620 static void
6621copy_substream(HANDLE sh, void *context, WCHAR *to, WCHAR *substream, long len)
6622{
6623 HANDLE hTo;
6624 WCHAR *to_name;
6625
6626 to_name = malloc((wcslen(to) + wcslen(substream) + 1) * sizeof(WCHAR));
6627 wcscpy(to_name, to);
6628 wcscat(to_name, substream);
6629
6630 hTo = CreateFileW(to_name, GENERIC_WRITE, 0, NULL, OPEN_ALWAYS,
6631 FILE_ATTRIBUTE_NORMAL, NULL);
6632 if (hTo != INVALID_HANDLE_VALUE)
6633 {
6634 long done;
6635 DWORD todo;
6636 DWORD readcnt, written;
6637 char buf[4096];
6638
6639 /* Copy block of bytes at a time. Abort when something goes wrong. */
6640 for (done = 0; done < len; done += written)
6641 {
6642 /* (size_t) cast for Borland C 5.5 */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006643 todo = (DWORD)((size_t)(len - done) > sizeof(buf) ? sizeof(buf)
6644 : (size_t)(len - done));
Bram Moolenaar071d4272004-06-13 20:20:40 +00006645 if (!BackupRead(sh, (LPBYTE)buf, todo, &readcnt,
6646 FALSE, FALSE, context)
6647 || readcnt != todo
6648 || !WriteFile(hTo, buf, todo, &written, NULL)
6649 || written != todo)
6650 break;
6651 }
6652 CloseHandle(hTo);
6653 }
6654
6655 free(to_name);
6656}
6657
6658/*
6659 * Copy info streams from file "from" to file "to".
6660 */
6661 static void
6662copy_infostreams(char_u *from, char_u *to)
6663{
6664 WCHAR *fromw;
6665 WCHAR *tow;
6666 HANDLE sh;
6667 WIN32_STREAM_ID sid;
6668 int headersize;
6669 WCHAR streamname[_MAX_PATH];
6670 DWORD readcount;
6671 void *context = NULL;
6672 DWORD lo, hi;
6673 int len;
6674
6675 /* Convert the file names to wide characters. */
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006676 fromw = enc_to_utf16(from, NULL);
6677 tow = enc_to_utf16(to, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006678 if (fromw != NULL && tow != NULL)
6679 {
6680 /* Open the file for reading. */
6681 sh = CreateFileW(fromw, GENERIC_READ, FILE_SHARE_READ, NULL,
6682 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
6683 if (sh != INVALID_HANDLE_VALUE)
6684 {
6685 /* Use BackupRead() to find the info streams. Repeat until we
6686 * have done them all.*/
6687 for (;;)
6688 {
6689 /* Get the header to find the length of the stream name. If
6690 * the "readcount" is zero we have done all info streams. */
6691 ZeroMemory(&sid, sizeof(WIN32_STREAM_ID));
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006692 headersize = (int)((char *)&sid.cStreamName - (char *)&sid.dwStreamId);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006693 if (!BackupRead(sh, (LPBYTE)&sid, headersize,
6694 &readcount, FALSE, FALSE, &context)
6695 || readcount == 0)
6696 break;
6697
6698 /* We only deal with streams that have a name. The normal
6699 * file data appears to be without a name, even though docs
6700 * suggest it is called "::$DATA". */
6701 if (sid.dwStreamNameSize > 0)
6702 {
6703 /* Read the stream name. */
6704 if (!BackupRead(sh, (LPBYTE)streamname,
6705 sid.dwStreamNameSize,
6706 &readcount, FALSE, FALSE, &context))
6707 break;
6708
6709 /* Copy an info stream with a name ":anything:$DATA".
6710 * Skip "::$DATA", it has no stream name (examples suggest
6711 * it might be used for the normal file contents).
6712 * Note that BackupRead() counts bytes, but the name is in
6713 * wide characters. */
6714 len = readcount / sizeof(WCHAR);
6715 streamname[len] = 0;
6716 if (len > 7 && wcsicmp(streamname + len - 6,
6717 L":$DATA") == 0)
6718 {
6719 streamname[len - 6] = 0;
6720 copy_substream(sh, &context, tow, streamname,
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00006721 (long)sid.Size.u.LowPart);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006722 }
6723 }
6724
6725 /* Advance to the next stream. We might try seeking too far,
6726 * but BackupSeek() doesn't skip over stream borders, thus
6727 * that's OK. */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00006728 (void)BackupSeek(sh, sid.Size.u.LowPart, sid.Size.u.HighPart,
Bram Moolenaar071d4272004-06-13 20:20:40 +00006729 &lo, &hi, &context);
6730 }
6731
6732 /* Clear the context. */
6733 (void)BackupRead(sh, NULL, 0, &readcount, TRUE, FALSE, &context);
6734
6735 CloseHandle(sh);
6736 }
6737 }
6738 vim_free(fromw);
6739 vim_free(tow);
6740}
6741#endif
6742
6743/*
6744 * Copy file attributes from file "from" to file "to".
6745 * For Windows NT and later we copy info streams.
6746 * Always returns zero, errors are ignored.
6747 */
6748 int
6749mch_copy_file_attribute(char_u *from, char_u *to)
6750{
6751#ifdef FEAT_MBYTE
6752 /* File streams only work on Windows NT and later. */
6753 PlatformId();
6754 if (g_PlatformId == VER_PLATFORM_WIN32_NT)
6755 copy_infostreams(from, to);
6756#endif
6757 return 0;
6758}
6759
6760#if defined(MYRESETSTKOFLW) || defined(PROTO)
6761/*
6762 * Recreate a destroyed stack guard page in win32.
6763 * Written by Benjamin Peterson.
6764 */
6765
6766/* These magic numbers are from the MS header files */
6767#define MIN_STACK_WIN9X 17
6768#define MIN_STACK_WINNT 2
6769
6770/*
6771 * This function does the same thing as _resetstkoflw(), which is only
6772 * available in DevStudio .net and later.
6773 * Returns 0 for failure, 1 for success.
6774 */
6775 int
6776myresetstkoflw(void)
6777{
6778 BYTE *pStackPtr;
6779 BYTE *pGuardPage;
6780 BYTE *pStackBase;
6781 BYTE *pLowestPossiblePage;
6782 MEMORY_BASIC_INFORMATION mbi;
6783 SYSTEM_INFO si;
6784 DWORD nPageSize;
6785 DWORD dummy;
6786
6787 /* This code will not work on win32s. */
6788 PlatformId();
6789 if (g_PlatformId == VER_PLATFORM_WIN32s)
6790 return 0;
6791
6792 /* We need to know the system page size. */
6793 GetSystemInfo(&si);
6794 nPageSize = si.dwPageSize;
6795
6796 /* ...and the current stack pointer */
6797 pStackPtr = (BYTE*)_alloca(1);
6798
6799 /* ...and the base of the stack. */
6800 if (VirtualQuery(pStackPtr, &mbi, sizeof mbi) == 0)
6801 return 0;
6802 pStackBase = (BYTE*)mbi.AllocationBase;
6803
6804 /* ...and the page thats min_stack_req pages away from stack base; this is
6805 * the lowest page we could use. */
6806 pLowestPossiblePage = pStackBase + ((g_PlatformId == VER_PLATFORM_WIN32_NT)
6807 ? MIN_STACK_WINNT : MIN_STACK_WIN9X) * nPageSize;
6808
6809 /* On Win95, we want the next page down from the end of the stack. */
6810 if (g_PlatformId == VER_PLATFORM_WIN32_WINDOWS)
6811 {
6812 /* Find the page that's only 1 page down from the page that the stack
6813 * ptr is in. */
6814 pGuardPage = (BYTE*)((DWORD)nPageSize * (((DWORD)pStackPtr
6815 / (DWORD)nPageSize) - 1));
6816 if (pGuardPage < pLowestPossiblePage)
6817 return 0;
6818
6819 /* Apply the noaccess attribute to the page -- there's no guard
6820 * attribute in win95-type OSes. */
6821 if (!VirtualProtect(pGuardPage, nPageSize, PAGE_NOACCESS, &dummy))
6822 return 0;
6823 }
6824 else
6825 {
6826 /* On NT, however, we want the first committed page in the stack Start
6827 * at the stack base and move forward through memory until we find a
6828 * committed block. */
6829 BYTE *pBlock = pStackBase;
6830
Bram Moolenaara466c992005-07-09 21:03:22 +00006831 for (;;)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006832 {
6833 if (VirtualQuery(pBlock, &mbi, sizeof mbi) == 0)
6834 return 0;
6835
6836 pBlock += mbi.RegionSize;
6837
6838 if (mbi.State & MEM_COMMIT)
6839 break;
6840 }
6841
6842 /* mbi now describes the first committed block in the stack. */
6843 if (mbi.Protect & PAGE_GUARD)
6844 return 1;
6845
6846 /* decide where the guard page should start */
6847 if ((long_u)(mbi.BaseAddress) < (long_u)pLowestPossiblePage)
6848 pGuardPage = pLowestPossiblePage;
6849 else
6850 pGuardPage = (BYTE*)mbi.BaseAddress;
6851
6852 /* allocate the guard page */
6853 if (!VirtualAlloc(pGuardPage, nPageSize, MEM_COMMIT, PAGE_READWRITE))
6854 return 0;
6855
6856 /* apply the guard attribute to the page */
6857 if (!VirtualProtect(pGuardPage, nPageSize, PAGE_READWRITE | PAGE_GUARD,
6858 &dummy))
6859 return 0;
6860 }
6861
6862 return 1;
6863}
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006864#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006865
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006866
6867#if defined(FEAT_MBYTE) || defined(PROTO)
6868/*
6869 * The command line arguments in UCS2
6870 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00006871static int nArgsW = 0;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006872static LPWSTR *ArglistW = NULL;
6873static int global_argc = 0;
6874static char **global_argv;
6875
6876static int used_file_argc = 0; /* last argument in global_argv[] used
6877 for the argument list. */
6878static int *used_file_indexes = NULL; /* indexes in global_argv[] for
6879 command line arguments added to
6880 the argument list */
6881static int used_file_count = 0; /* nr of entries in used_file_indexes */
6882static int used_file_literal = FALSE; /* take file names literally */
6883static int used_file_full_path = FALSE; /* file name was full path */
Bram Moolenaar910f66f2006-04-05 20:41:53 +00006884static int used_file_diff_mode = FALSE; /* file name was with diff mode */
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006885static int used_alist_count = 0;
6886
6887
6888/*
6889 * Get the command line arguments. Unicode version.
6890 * Returns argc. Zero when something fails.
6891 */
6892 int
6893get_cmd_argsW(char ***argvp)
6894{
6895 char **argv = NULL;
6896 int argc = 0;
6897 int i;
6898
Bram Moolenaar14993322014-09-09 12:25:33 +02006899 free_cmd_argsW();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006900 ArglistW = CommandLineToArgvW(GetCommandLineW(), &nArgsW);
6901 if (ArglistW != NULL)
6902 {
6903 argv = malloc((nArgsW + 1) * sizeof(char *));
6904 if (argv != NULL)
6905 {
6906 argc = nArgsW;
6907 argv[argc] = NULL;
6908 for (i = 0; i < argc; ++i)
6909 {
6910 int len;
6911
6912 /* Convert each Unicode argument to the current codepage. */
6913 WideCharToMultiByte_alloc(GetACP(), 0,
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006914 ArglistW[i], (int)wcslen(ArglistW[i]) + 1,
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006915 (LPSTR *)&argv[i], &len, 0, 0);
6916 if (argv[i] == NULL)
6917 {
6918 /* Out of memory, clear everything. */
6919 while (i > 0)
6920 free(argv[--i]);
6921 free(argv);
Bram Moolenaar73c61632013-12-07 14:48:10 +01006922 argv = NULL;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006923 argc = 0;
6924 }
6925 }
6926 }
6927 }
6928
6929 global_argc = argc;
6930 global_argv = argv;
6931 if (argc > 0)
Bram Moolenaar14993322014-09-09 12:25:33 +02006932 {
6933 if (used_file_indexes != NULL)
6934 free(used_file_indexes);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006935 used_file_indexes = malloc(argc * sizeof(int));
Bram Moolenaar14993322014-09-09 12:25:33 +02006936 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006937
6938 if (argvp != NULL)
6939 *argvp = argv;
6940 return argc;
6941}
6942
6943 void
6944free_cmd_argsW(void)
6945{
6946 if (ArglistW != NULL)
6947 {
6948 GlobalFree(ArglistW);
6949 ArglistW = NULL;
6950 }
6951}
6952
6953/*
6954 * Remember "name" is an argument that was added to the argument list.
6955 * This avoids that we have to re-parse the argument list when fix_arg_enc()
6956 * is called.
6957 */
6958 void
Bram Moolenaar910f66f2006-04-05 20:41:53 +00006959used_file_arg(char *name, int literal, int full_path, int diff_mode)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006960{
6961 int i;
6962
6963 if (used_file_indexes == NULL)
6964 return;
6965 for (i = used_file_argc + 1; i < global_argc; ++i)
6966 if (STRCMP(global_argv[i], name) == 0)
6967 {
6968 used_file_argc = i;
6969 used_file_indexes[used_file_count++] = i;
6970 break;
6971 }
6972 used_file_literal = literal;
6973 used_file_full_path = full_path;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00006974 used_file_diff_mode = diff_mode;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006975}
6976
6977/*
6978 * Remember the length of the argument list as it was. If it changes then we
6979 * leave it alone when 'encoding' is set.
6980 */
6981 void
6982set_alist_count(void)
6983{
6984 used_alist_count = GARGCOUNT;
6985}
6986
6987/*
6988 * Fix the encoding of the command line arguments. Invoked when 'encoding'
6989 * has been changed while starting up. Use the UCS-2 command line arguments
6990 * and convert them to 'encoding'.
6991 */
6992 void
6993fix_arg_enc(void)
6994{
6995 int i;
6996 int idx;
6997 char_u *str;
Bram Moolenaar86b68352004-12-27 21:59:20 +00006998 int *fnum_list;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006999
7000 /* Safety checks:
7001 * - if argument count differs between the wide and non-wide argument
7002 * list, something must be wrong.
7003 * - the file name arguments must have been located.
7004 * - the length of the argument list wasn't changed by the user.
7005 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00007006 if (global_argc != nArgsW
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007007 || ArglistW == NULL
7008 || used_file_indexes == NULL
7009 || used_file_count == 0
7010 || used_alist_count != GARGCOUNT)
7011 return;
7012
Bram Moolenaar86b68352004-12-27 21:59:20 +00007013 /* Remember the buffer numbers for the arguments. */
7014 fnum_list = (int *)alloc((int)sizeof(int) * GARGCOUNT);
7015 if (fnum_list == NULL)
7016 return; /* out of memory */
7017 for (i = 0; i < GARGCOUNT; ++i)
7018 fnum_list[i] = GARGLIST[i].ae_fnum;
7019
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007020 /* Clear the argument list. Make room for the new arguments. */
7021 alist_clear(&global_alist);
7022 if (ga_grow(&global_alist.al_ga, used_file_count) == FAIL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00007023 return; /* out of memory */
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007024
7025 for (i = 0; i < used_file_count; ++i)
7026 {
7027 idx = used_file_indexes[i];
Bram Moolenaar36f692d2008-11-20 16:10:17 +00007028 str = utf16_to_enc(ArglistW[idx], NULL);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007029 if (str != NULL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00007030 {
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007031#ifdef FEAT_DIFF
7032 /* When using diff mode may need to concatenate file name to
7033 * directory name. Just like it's done in main(). */
7034 if (used_file_diff_mode && mch_isdir(str) && GARGCOUNT > 0
7035 && !mch_isdir(alist_name(&GARGLIST[0])))
7036 {
7037 char_u *r;
7038
7039 r = concat_fnames(str, gettail(alist_name(&GARGLIST[0])), TRUE);
7040 if (r != NULL)
7041 {
7042 vim_free(str);
7043 str = r;
7044 }
7045 }
7046#endif
Bram Moolenaar86b68352004-12-27 21:59:20 +00007047 /* Re-use the old buffer by renaming it. When not using literal
7048 * names it's done by alist_expand() below. */
7049 if (used_file_literal)
7050 buf_set_name(fnum_list[i], str);
7051
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007052 alist_add(&global_alist, str, used_file_literal ? 2 : 0);
Bram Moolenaar86b68352004-12-27 21:59:20 +00007053 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007054 }
7055
7056 if (!used_file_literal)
7057 {
7058 /* Now expand wildcards in the arguments. */
7059 /* Temporarily add '(' and ')' to 'isfname'. These are valid
7060 * filename characters but are excluded from 'isfname' to make
7061 * "gf" work on a file name in parenthesis (e.g.: see vim.h). */
7062 do_cmdline_cmd((char_u *)":let SaVe_ISF = &isf|set isf+=(,)");
Bram Moolenaar86b68352004-12-27 21:59:20 +00007063 alist_expand(fnum_list, used_alist_count);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007064 do_cmdline_cmd((char_u *)":let &isf = SaVe_ISF|unlet SaVe_ISF");
7065 }
7066
7067 /* If wildcard expansion failed, we are editing the first file of the
7068 * arglist and there is no file name: Edit the first argument now. */
7069 if (curwin->w_arg_idx == 0 && curbuf->b_fname == NULL)
7070 {
7071 do_cmdline_cmd((char_u *)":rewind");
7072 if (GARGCOUNT == 1 && used_file_full_path)
7073 (void)vim_chdirfile(alist_name(&GARGLIST[0]));
7074 }
Bram Moolenaar86b68352004-12-27 21:59:20 +00007075
7076 set_alist_count();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007077}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007078#endif