blob: ae1f0d8afc198cdb4924236c23298dbef862333d [file] [log] [blame]
Bram Moolenaar071d4272004-06-13 20:20:40 +00001/* vi:set ts=8 sts=4 sw=4:
2 *
3 * VIM - Vi IMproved by Bram Moolenaar
4 *
5 * Do ":help uganda" in Vim to read copying and usage conditions.
6 * Do ":help credits" in Vim to see a list of people who contributed.
7 * See README.txt for an overview of the Vim source code.
8 */
9/*
10 * os_win32.c
11 *
12 * Used for both the console version and the Win32 GUI. A lot of code is for
13 * the console version only, so there is a lot of "#ifndef FEAT_GUI_W32".
14 *
15 * Win32 (Windows NT and Windows 95) system-dependent routines.
16 * Portions lifted from the Win32 SDK samples, the MSDOS-dependent code,
17 * NetHack 3.1.3, GNU Emacs 19.30, and Vile 5.5.
18 *
19 * George V. Reilly <george@reilly.org> wrote most of this.
20 * Roger Knobbe <rogerk@wonderware.com> did the initial port of Vim 3.0.
21 */
22
Bram Moolenaar071d4272004-06-13 20:20:40 +000023#include "vim.h"
24
Bram Moolenaar325b7a22004-07-05 15:58:32 +000025#ifdef FEAT_MZSCHEME
26# include "if_mzsch.h"
27#endif
28
Bram Moolenaar071d4272004-06-13 20:20:40 +000029#include <sys/types.h>
Bram Moolenaar071d4272004-06-13 20:20:40 +000030#include <signal.h>
31#include <limits.h>
Bram Moolenaar82881492012-11-20 16:53:39 +010032
33/* cproto fails on missing include files */
34#ifndef PROTO
35# include <process.h>
36#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +000037
38#undef chdir
39#ifdef __GNUC__
40# ifndef __MINGW32__
41# include <dirent.h>
42# endif
43#else
44# include <direct.h>
45#endif
46
Bram Moolenaar82881492012-11-20 16:53:39 +010047#ifndef PROTO
48# if defined(FEAT_TITLE) && !defined(FEAT_GUI_W32)
49# include <shellapi.h>
50# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +000051#endif
52
53#ifdef __MINGW32__
54# ifndef FROM_LEFT_1ST_BUTTON_PRESSED
55# define FROM_LEFT_1ST_BUTTON_PRESSED 0x0001
56# endif
57# ifndef RIGHTMOST_BUTTON_PRESSED
58# define RIGHTMOST_BUTTON_PRESSED 0x0002
59# endif
60# ifndef FROM_LEFT_2ND_BUTTON_PRESSED
61# define FROM_LEFT_2ND_BUTTON_PRESSED 0x0004
62# endif
63# ifndef FROM_LEFT_3RD_BUTTON_PRESSED
64# define FROM_LEFT_3RD_BUTTON_PRESSED 0x0008
65# endif
66# ifndef FROM_LEFT_4TH_BUTTON_PRESSED
67# define FROM_LEFT_4TH_BUTTON_PRESSED 0x0010
68# endif
69
70/*
71 * EventFlags
72 */
73# ifndef MOUSE_MOVED
74# define MOUSE_MOVED 0x0001
75# endif
76# ifndef DOUBLE_CLICK
77# define DOUBLE_CLICK 0x0002
78# endif
79#endif
80
81/* Record all output and all keyboard & mouse input */
82/* #define MCH_WRITE_DUMP */
83
84#ifdef MCH_WRITE_DUMP
85FILE* fdDump = NULL;
86#endif
87
88/*
89 * When generating prototypes for Win32 on Unix, these lines make the syntax
90 * errors disappear. They do not need to be correct.
91 */
92#ifdef PROTO
93#define WINAPI
Bram Moolenaar071d4272004-06-13 20:20:40 +000094typedef char * LPCSTR;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +000095typedef char * LPWSTR;
Bram Moolenaar071d4272004-06-13 20:20:40 +000096typedef int ACCESS_MASK;
97typedef int BOOL;
98typedef int COLORREF;
99typedef int CONSOLE_CURSOR_INFO;
100typedef int COORD;
101typedef int DWORD;
102typedef int HANDLE;
Bram Moolenaaref269542016-01-19 13:22:12 +0100103typedef int LPHANDLE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000104typedef int HDC;
105typedef int HFONT;
106typedef int HICON;
107typedef int HINSTANCE;
108typedef int HWND;
109typedef int INPUT_RECORD;
110typedef int KEY_EVENT_RECORD;
111typedef int LOGFONT;
112typedef int LPBOOL;
113typedef int LPCTSTR;
114typedef int LPDWORD;
115typedef int LPSTR;
116typedef int LPTSTR;
117typedef int LPVOID;
118typedef int MOUSE_EVENT_RECORD;
119typedef int PACL;
120typedef int PDWORD;
121typedef int PHANDLE;
122typedef int PRINTDLG;
123typedef int PSECURITY_DESCRIPTOR;
124typedef int PSID;
125typedef int SECURITY_INFORMATION;
126typedef int SHORT;
127typedef int SMALL_RECT;
128typedef int TEXTMETRIC;
129typedef int TOKEN_INFORMATION_CLASS;
130typedef int TRUSTEE;
131typedef int WORD;
132typedef int WCHAR;
133typedef void VOID;
Bram Moolenaar82881492012-11-20 16:53:39 +0100134typedef int BY_HANDLE_FILE_INFORMATION;
Bram Moolenaar32ac8cd2013-07-03 18:49:17 +0200135typedef int SE_OBJECT_TYPE;
136typedef int PSNSECINFO;
137typedef int PSNSECINFOW;
Bram Moolenaarb8e0bdb2014-11-12 16:10:48 +0100138typedef int STARTUPINFO;
139typedef int PROCESS_INFORMATION;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000140#endif
141
142#ifndef FEAT_GUI_W32
143/* Undocumented API in kernel32.dll needed to work around dead key bug in
144 * console-mode applications in NT 4.0. If you switch keyboard layouts
145 * in a console app to a layout that includes dead keys and then hit a
146 * dead key, a call to ToAscii will trash the stack. My thanks to Ian James
147 * and Michael Dietrich for helping me figure out this workaround.
148 */
149
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +0100150/* WINAPI BOOL WINAPI GetConsoleKeyboardLayoutNameA(LPSTR); */
151#ifndef WINAPI
152# define WINAPI __stdcall
Bram Moolenaar071d4272004-06-13 20:20:40 +0000153#endif
154#if defined(__BORLANDC__)
155typedef BOOL (__stdcall *PFNGCKLN)(LPSTR);
156#else
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +0100157typedef BOOL (WINAPI *PFNGCKLN)(LPSTR);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000158#endif
Bram Moolenaard6f676d2005-06-01 21:51:55 +0000159static PFNGCKLN s_pfnGetConsoleKeyboardLayoutName = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000160#endif
161
162#if defined(__BORLANDC__)
163/* Strangely Borland uses a non-standard name. */
164# define wcsicmp(a, b) wcscmpi((a), (b))
165#endif
166
Bram Moolenaar82881492012-11-20 16:53:39 +0100167#ifndef PROTO
168
Bram Moolenaar84a05ac2013-05-06 04:24:17 +0200169/* Enable common dialogs input unicode from IME if possible. */
Bram Moolenaar8c85fa32011-08-10 17:08:03 +0200170#ifdef FEAT_MBYTE
Bram Moolenaaraf62ff32013-03-19 14:48:29 +0100171LRESULT (WINAPI *pDispatchMessage)(CONST MSG *) = DispatchMessage;
Bram Moolenaar8c85fa32011-08-10 17:08:03 +0200172BOOL (WINAPI *pGetMessage)(LPMSG, HWND, UINT, UINT) = GetMessage;
173BOOL (WINAPI *pIsDialogMessage)(HWND, LPMSG) = IsDialogMessage;
174BOOL (WINAPI *pPeekMessage)(LPMSG, HWND, UINT, UINT, UINT) = PeekMessage;
175#endif
176
Bram Moolenaar82881492012-11-20 16:53:39 +0100177#endif /* PROTO */
178
Bram Moolenaar071d4272004-06-13 20:20:40 +0000179#ifndef FEAT_GUI_W32
180/* Win32 Console handles for input and output */
181static HANDLE g_hConIn = INVALID_HANDLE_VALUE;
182static HANDLE g_hConOut = INVALID_HANDLE_VALUE;
183
184/* Win32 Screen buffer,coordinate,console I/O information */
185static SMALL_RECT g_srScrollRegion;
186static COORD g_coord; /* 0-based, but external coords are 1-based */
187
188/* The attribute of the screen when the editor was started */
189static WORD g_attrDefault = 7; /* lightgray text on black background */
190static WORD g_attrCurrent;
191
192static int g_fCBrkPressed = FALSE; /* set by ctrl-break interrupt */
193static int g_fCtrlCPressed = FALSE; /* set when ctrl-C or ctrl-break detected */
194static int g_fForceExit = FALSE; /* set when forcefully exiting */
195
196static void termcap_mode_start(void);
197static void termcap_mode_end(void);
198static void clear_chars(COORD coord, DWORD n);
199static void clear_screen(void);
200static void clear_to_end_of_display(void);
201static void clear_to_end_of_line(void);
202static void scroll(unsigned cLines);
203static void set_scroll_region(unsigned left, unsigned top,
204 unsigned right, unsigned bottom);
205static void insert_lines(unsigned cLines);
206static void delete_lines(unsigned cLines);
207static void gotoxy(unsigned x, unsigned y);
208static void normvideo(void);
209static void textattr(WORD wAttr);
210static void textcolor(WORD wAttr);
211static void textbackground(WORD wAttr);
212static void standout(void);
213static void standend(void);
214static void visual_bell(void);
215static void cursor_visible(BOOL fVisible);
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200216static DWORD write_chars(char_u *pchBuf, DWORD cbToWrite);
217static WCHAR tgetch(int *pmodifiers, WCHAR *pch2);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000218static void create_conin(void);
219static int s_cursor_visible = TRUE;
220static int did_create_conin = FALSE;
221#else
222static int s_dont_use_vimrun = TRUE;
223static int need_vimrun_warning = FALSE;
224static char *vimrun_path = "vimrun ";
225#endif
226
Bram Moolenaar12b559e2013-06-12 22:41:37 +0200227static int win32_getattrs(char_u *name);
228static int win32_setattrs(char_u *name, int attrs);
229static int win32_set_archive(char_u *name);
230
Bram Moolenaar071d4272004-06-13 20:20:40 +0000231#ifndef FEAT_GUI_W32
232static int suppress_winsize = 1; /* don't fiddle with console */
233#endif
234
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200235static char_u *exe_path = NULL;
236
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100237static BOOL win8_or_later = FALSE;
238
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100239#ifndef FEAT_GUI_W32
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100240/*
241 * Version of ReadConsoleInput() that works with IME.
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100242 * Works around problems on Windows 8.
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100243 */
244 static BOOL
245read_console_input(
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100246 HANDLE hInput,
247 INPUT_RECORD *lpBuffer,
248 DWORD nLength,
249 LPDWORD lpEvents)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100250{
251 enum
252 {
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100253 IRSIZE = 10
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100254 };
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100255 static INPUT_RECORD s_irCache[IRSIZE];
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100256 static DWORD s_dwIndex = 0;
257 static DWORD s_dwMax = 0;
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100258 DWORD dwEvents;
Bram Moolenaardd415a62014-02-05 14:02:27 +0100259 int head;
260 int tail;
261 int i;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100262
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200263 if (nLength == -2)
264 return (s_dwMax > 0) ? TRUE : FALSE;
265
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100266 if (!win8_or_later)
267 {
268 if (nLength == -1)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200269 return PeekConsoleInputW(hInput, lpBuffer, 1, lpEvents);
270 return ReadConsoleInputW(hInput, lpBuffer, 1, &dwEvents);
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100271 }
272
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100273 if (s_dwMax == 0)
274 {
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100275 if (nLength == -1)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200276 return PeekConsoleInputW(hInput, lpBuffer, 1, lpEvents);
277 if (!ReadConsoleInputW(hInput, s_irCache, IRSIZE, &dwEvents))
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100278 return FALSE;
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100279 s_dwIndex = 0;
280 s_dwMax = dwEvents;
281 if (dwEvents == 0)
282 {
283 *lpEvents = 0;
284 return TRUE;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100285 }
Bram Moolenaardd415a62014-02-05 14:02:27 +0100286
287 if (s_dwMax > 1)
288 {
289 head = 0;
290 tail = s_dwMax - 1;
291 while (head != tail)
292 {
293 if (s_irCache[head].EventType == WINDOW_BUFFER_SIZE_EVENT
294 && s_irCache[head + 1].EventType
295 == WINDOW_BUFFER_SIZE_EVENT)
296 {
297 /* Remove duplicate event to avoid flicker. */
298 for (i = head; i < tail; ++i)
299 s_irCache[i] = s_irCache[i + 1];
300 --tail;
301 continue;
302 }
303 head++;
304 }
305 s_dwMax = tail + 1;
306 }
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100307 }
Bram Moolenaardd415a62014-02-05 14:02:27 +0100308
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100309 *lpBuffer = s_irCache[s_dwIndex];
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200310 if (!(nLength == -1 || nLength == -2) && ++s_dwIndex >= s_dwMax)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100311 s_dwMax = 0;
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100312 *lpEvents = 1;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100313 return TRUE;
314}
315
316/*
317 * Version of PeekConsoleInput() that works with IME.
318 */
319 static BOOL
320peek_console_input(
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100321 HANDLE hInput,
322 INPUT_RECORD *lpBuffer,
323 DWORD nLength,
324 LPDWORD lpEvents)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100325{
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100326 return read_console_input(hInput, lpBuffer, -1, lpEvents);
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100327}
328
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100329# ifdef FEAT_CLIENTSERVER
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200330 static DWORD
331msg_wait_for_multiple_objects(
332 DWORD nCount,
333 LPHANDLE pHandles,
334 BOOL fWaitAll,
335 DWORD dwMilliseconds,
336 DWORD dwWakeMask)
337{
338 if (read_console_input(NULL, NULL, -2, NULL))
339 return WAIT_OBJECT_0;
340 return MsgWaitForMultipleObjects(nCount, pHandles, fWaitAll,
341 dwMilliseconds, dwWakeMask);
342}
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100343# endif
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200344
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100345# ifndef FEAT_CLIENTSERVER
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200346 static DWORD
347wait_for_single_object(
348 HANDLE hHandle,
349 DWORD dwMilliseconds)
350{
351 if (read_console_input(NULL, NULL, -2, NULL))
352 return WAIT_OBJECT_0;
353 return WaitForSingleObject(hHandle, dwMilliseconds);
354}
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100355# endif
356#endif
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200357
Bram Moolenaar071d4272004-06-13 20:20:40 +0000358 static void
359get_exe_name(void)
360{
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100361 /* Maximum length of $PATH is more than MAXPATHL. 8191 is often mentioned
362 * as the maximum length that works (plus a NUL byte). */
363#define MAX_ENV_PATH_LEN 8192
364 char temp[MAX_ENV_PATH_LEN];
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200365 char_u *p;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000366
367 if (exe_name == NULL)
368 {
369 /* store the name of the executable, may be used for $VIM */
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100370 GetModuleFileName(NULL, temp, MAX_ENV_PATH_LEN - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000371 if (*temp != NUL)
372 exe_name = FullName_save((char_u *)temp, FALSE);
373 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000374
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200375 if (exe_path == NULL && exe_name != NULL)
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000376 {
Bram Moolenaar6b5ef062010-10-27 12:18:00 +0200377 exe_path = vim_strnsave(exe_name,
378 (int)(gettail_sep(exe_name) - exe_name));
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200379 if (exe_path != NULL)
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000380 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200381 /* Append our starting directory to $PATH, so that when doing
382 * "!xxd" it's found in our starting directory. Needed because
383 * SearchPath() also looks there. */
384 p = mch_getenv("PATH");
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100385 if (p == NULL
386 || STRLEN(p) + STRLEN(exe_path) + 2 < MAX_ENV_PATH_LEN)
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200387 {
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100388 if (p == NULL || *p == NUL)
389 temp[0] = NUL;
390 else
391 {
392 STRCPY(temp, p);
393 STRCAT(temp, ";");
394 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200395 STRCAT(temp, exe_path);
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +0100396 vim_setenv((char_u *)"PATH", (char_u *)temp);
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200397 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000398 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000399 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000400}
401
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200402/*
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100403 * Unescape characters in "p" that appear in "escaped".
404 */
405 static void
406unescape_shellxquote(char_u *p, char_u *escaped)
407{
Bram Moolenaar4336cdf2012-02-29 13:58:47 +0100408 int l = (int)STRLEN(p);
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100409 int n;
410
411 while (*p != NUL)
412 {
413 if (*p == '^' && vim_strchr(escaped, p[1]) != NULL)
414 mch_memmove(p, p + 1, l--);
415#ifdef FEAT_MBYTE
416 n = (*mb_ptr2len)(p);
417#else
418 n = 1;
419#endif
420 p += n;
421 l -= n;
422 }
423}
424
425/*
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200426 * Load library "name".
427 */
428 HINSTANCE
429vimLoadLib(char *name)
430{
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200431 HINSTANCE dll = NULL;
432 char old_dir[MAXPATHL];
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200433
Bram Moolenaarfaca8402012-10-21 02:37:10 +0200434 /* NOTE: Do not use mch_dirname() and mch_chdir() here, they may call
435 * vimLoadLib() recursively, which causes a stack overflow. */
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200436 if (exe_path == NULL)
437 get_exe_name();
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200438 if (exe_path != NULL)
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200439 {
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200440#ifdef FEAT_MBYTE
441 WCHAR old_dirw[MAXPATHL];
442
443 if (GetCurrentDirectoryW(MAXPATHL, old_dirw) != 0)
444 {
445 /* Change directory to where the executable is, both to make
446 * sure we find a .dll there and to avoid looking for a .dll
447 * in the current directory. */
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +0100448 SetCurrentDirectory((LPCSTR)exe_path);
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200449 dll = LoadLibrary(name);
450 SetCurrentDirectoryW(old_dirw);
451 return dll;
452 }
453 /* Retry with non-wide function (for Windows 98). */
454 if (GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
455#endif
456 if (GetCurrentDirectory(MAXPATHL, old_dir) != 0)
457 {
458 /* Change directory to where the executable is, both to make
459 * sure we find a .dll there and to avoid looking for a .dll
460 * in the current directory. */
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +0100461 SetCurrentDirectory((LPCSTR)exe_path);
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200462 dll = LoadLibrary(name);
463 SetCurrentDirectory(old_dir);
464 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200465 }
466 return dll;
467}
468
Bram Moolenaar071d4272004-06-13 20:20:40 +0000469#if defined(DYNAMIC_GETTEXT) || defined(PROTO)
470# ifndef GETTEXT_DLL
471# define GETTEXT_DLL "libintl.dll"
Bram Moolenaar286eacd2016-01-16 18:05:50 +0100472# define GETTEXT_DLL_ALT "libintl-8.dll"
Bram Moolenaar071d4272004-06-13 20:20:40 +0000473# endif
Bram Moolenaarf6a2b082012-06-29 13:14:03 +0200474/* Dummy functions */
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000475static char *null_libintl_gettext(const char *);
476static char *null_libintl_textdomain(const char *);
477static char *null_libintl_bindtextdomain(const char *, const char *);
478static char *null_libintl_bind_textdomain_codeset(const char *, const char *);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000479
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200480static HINSTANCE hLibintlDLL = NULL;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000481char *(*dyn_libintl_gettext)(const char *) = null_libintl_gettext;
482char *(*dyn_libintl_textdomain)(const char *) = null_libintl_textdomain;
483char *(*dyn_libintl_bindtextdomain)(const char *, const char *)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000484 = null_libintl_bindtextdomain;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000485char *(*dyn_libintl_bind_textdomain_codeset)(const char *, const char *)
486 = null_libintl_bind_textdomain_codeset;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000487
488 int
Bram Moolenaar05540972016-01-30 20:31:25 +0100489dyn_libintl_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000490{
491 int i;
492 static struct
493 {
494 char *name;
495 FARPROC *ptr;
496 } libintl_entry[] =
497 {
498 {"gettext", (FARPROC*)&dyn_libintl_gettext},
499 {"textdomain", (FARPROC*)&dyn_libintl_textdomain},
500 {"bindtextdomain", (FARPROC*)&dyn_libintl_bindtextdomain},
501 {NULL, NULL}
502 };
503
504 /* No need to initialize twice. */
505 if (hLibintlDLL)
506 return 1;
507 /* Load gettext library (libintl.dll) */
Bram Moolenaar923e43b2016-01-28 15:07:38 +0100508 hLibintlDLL = vimLoadLib(GETTEXT_DLL);
Bram Moolenaar938ee832016-01-24 15:36:03 +0100509#ifdef GETTEXT_DLL_ALT
Bram Moolenaar286eacd2016-01-16 18:05:50 +0100510 if (!hLibintlDLL)
511 hLibintlDLL = vimLoadLib(GETTEXT_DLL_ALT);
Bram Moolenaar938ee832016-01-24 15:36:03 +0100512#endif
513 if (!hLibintlDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000514 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200515 if (p_verbose > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000516 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200517 verbose_enter();
518 EMSG2(_(e_loadlib), GETTEXT_DLL);
519 verbose_leave();
Bram Moolenaar071d4272004-06-13 20:20:40 +0000520 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200521 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000522 }
523 for (i = 0; libintl_entry[i].name != NULL
524 && libintl_entry[i].ptr != NULL; ++i)
525 {
526 if ((*libintl_entry[i].ptr = (FARPROC)GetProcAddress(hLibintlDLL,
527 libintl_entry[i].name)) == NULL)
528 {
529 dyn_libintl_end();
530 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +0000531 {
532 verbose_enter();
Bram Moolenaar071d4272004-06-13 20:20:40 +0000533 EMSG2(_(e_loadfunc), libintl_entry[i].name);
Bram Moolenaara04f10b2005-05-31 22:09:46 +0000534 verbose_leave();
535 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000536 return 0;
537 }
538 }
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000539
540 /* The bind_textdomain_codeset() function is optional. */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000541 dyn_libintl_bind_textdomain_codeset = (void *)GetProcAddress(hLibintlDLL,
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000542 "bind_textdomain_codeset");
543 if (dyn_libintl_bind_textdomain_codeset == NULL)
544 dyn_libintl_bind_textdomain_codeset =
545 null_libintl_bind_textdomain_codeset;
546
Bram Moolenaar071d4272004-06-13 20:20:40 +0000547 return 1;
548}
549
550 void
Bram Moolenaar05540972016-01-30 20:31:25 +0100551dyn_libintl_end(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000552{
553 if (hLibintlDLL)
554 FreeLibrary(hLibintlDLL);
555 hLibintlDLL = NULL;
556 dyn_libintl_gettext = null_libintl_gettext;
557 dyn_libintl_textdomain = null_libintl_textdomain;
558 dyn_libintl_bindtextdomain = null_libintl_bindtextdomain;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000559 dyn_libintl_bind_textdomain_codeset = null_libintl_bind_textdomain_codeset;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000560}
561
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000562/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +0000563 static char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000564null_libintl_gettext(const char *msgid)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000565{
566 return (char*)msgid;
567}
568
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000569/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +0000570 static char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000571null_libintl_bindtextdomain(const char *domainname, const char *dirname)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000572{
573 return NULL;
574}
575
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000576/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +0000577 static char *
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000578null_libintl_bind_textdomain_codeset(const char *domainname,
579 const char *codeset)
580{
581 return NULL;
582}
583
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000584/*ARGSUSED*/
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000585 static char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000586null_libintl_textdomain(const char *domainname)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000587{
588 return NULL;
589}
590
591#endif /* DYNAMIC_GETTEXT */
592
593/* This symbol is not defined in older versions of the SDK or Visual C++ */
594
595#ifndef VER_PLATFORM_WIN32_WINDOWS
596# define VER_PLATFORM_WIN32_WINDOWS 1
597#endif
598
599DWORD g_PlatformId;
600
601#ifdef HAVE_ACL
Bram Moolenaar82881492012-11-20 16:53:39 +0100602# ifndef PROTO
603# include <aclapi.h>
604# endif
Bram Moolenaar27515922013-06-29 15:36:26 +0200605# ifndef PROTECTED_DACL_SECURITY_INFORMATION
606# define PROTECTED_DACL_SECURITY_INFORMATION 0x80000000L
607# endif
Bram Moolenaar82881492012-11-20 16:53:39 +0100608
Bram Moolenaar071d4272004-06-13 20:20:40 +0000609/*
610 * These are needed to dynamically load the ADVAPI DLL, which is not
611 * implemented under Windows 95 (and causes VIM to crash)
612 */
Bram Moolenaar39efa892013-06-29 15:40:04 +0200613typedef DWORD (WINAPI *PSNSECINFO) (LPSTR, SE_OBJECT_TYPE,
Bram Moolenaar071d4272004-06-13 20:20:40 +0000614 SECURITY_INFORMATION, PSID, PSID, PACL, PACL);
Bram Moolenaar39efa892013-06-29 15:40:04 +0200615typedef DWORD (WINAPI *PGNSECINFO) (LPSTR, SE_OBJECT_TYPE,
Bram Moolenaar071d4272004-06-13 20:20:40 +0000616 SECURITY_INFORMATION, PSID *, PSID *, PACL *, PACL *,
617 PSECURITY_DESCRIPTOR *);
Bram Moolenaar27515922013-06-29 15:36:26 +0200618# ifdef FEAT_MBYTE
Bram Moolenaar39efa892013-06-29 15:40:04 +0200619typedef DWORD (WINAPI *PSNSECINFOW) (LPWSTR, SE_OBJECT_TYPE,
Bram Moolenaar27515922013-06-29 15:36:26 +0200620 SECURITY_INFORMATION, PSID, PSID, PACL, PACL);
Bram Moolenaar39efa892013-06-29 15:40:04 +0200621typedef DWORD (WINAPI *PGNSECINFOW) (LPWSTR, SE_OBJECT_TYPE,
Bram Moolenaar27515922013-06-29 15:36:26 +0200622 SECURITY_INFORMATION, PSID *, PSID *, PACL *, PACL *,
623 PSECURITY_DESCRIPTOR *);
624# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000625
626static HANDLE advapi_lib = NULL; /* Handle for ADVAPI library */
627static PSNSECINFO pSetNamedSecurityInfo;
628static PGNSECINFO pGetNamedSecurityInfo;
Bram Moolenaar27515922013-06-29 15:36:26 +0200629# ifdef FEAT_MBYTE
630static PSNSECINFOW pSetNamedSecurityInfoW;
631static PGNSECINFOW pGetNamedSecurityInfoW;
632# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000633#endif
634
Bram Moolenaar4b9669f2011-07-07 16:20:52 +0200635typedef BOOL (WINAPI *PSETHANDLEINFORMATION)(HANDLE, DWORD, DWORD);
636
637static BOOL allowPiping = FALSE;
638static PSETHANDLEINFORMATION pSetHandleInformation;
639
Bram Moolenaar27515922013-06-29 15:36:26 +0200640#ifdef HAVE_ACL
641/*
642 * Enables or disables the specified privilege.
643 */
644 static BOOL
645win32_enable_privilege(LPTSTR lpszPrivilege, BOOL bEnable)
646{
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100647 BOOL bResult;
648 LUID luid;
649 HANDLE hToken;
650 TOKEN_PRIVILEGES tokenPrivileges;
Bram Moolenaar27515922013-06-29 15:36:26 +0200651
652 if (!OpenProcessToken(GetCurrentProcess(),
653 TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
654 return FALSE;
655
656 if (!LookupPrivilegeValue(NULL, lpszPrivilege, &luid))
657 {
658 CloseHandle(hToken);
659 return FALSE;
660 }
661
Bram Moolenaar45500912014-07-09 20:51:07 +0200662 tokenPrivileges.PrivilegeCount = 1;
Bram Moolenaar27515922013-06-29 15:36:26 +0200663 tokenPrivileges.Privileges[0].Luid = luid;
664 tokenPrivileges.Privileges[0].Attributes = bEnable ?
665 SE_PRIVILEGE_ENABLED : 0;
666
667 bResult = AdjustTokenPrivileges(hToken, FALSE, &tokenPrivileges,
668 sizeof(TOKEN_PRIVILEGES), NULL, NULL);
669
670 CloseHandle(hToken);
671
672 return bResult && GetLastError() == ERROR_SUCCESS;
673}
674#endif
675
Bram Moolenaar071d4272004-06-13 20:20:40 +0000676/*
677 * Set g_PlatformId to VER_PLATFORM_WIN32_NT (NT) or
678 * VER_PLATFORM_WIN32_WINDOWS (Win95).
679 */
680 void
681PlatformId(void)
682{
683 static int done = FALSE;
684
685 if (!done)
686 {
687 OSVERSIONINFO ovi;
688
689 ovi.dwOSVersionInfoSize = sizeof(ovi);
690 GetVersionEx(&ovi);
691
692 g_PlatformId = ovi.dwPlatformId;
693
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100694 if ((ovi.dwMajorVersion == 6 && ovi.dwMinorVersion >= 2)
695 || ovi.dwMajorVersion > 6)
696 win8_or_later = TRUE;
697
Bram Moolenaar071d4272004-06-13 20:20:40 +0000698#ifdef HAVE_ACL
699 /*
700 * Load the ADVAPI runtime if we are on anything
701 * other than Windows 95
702 */
703 if (g_PlatformId == VER_PLATFORM_WIN32_NT)
704 {
705 /*
706 * do this load. Problems: Doesn't unload at end of run (this is
707 * theoretically okay, since Windows should unload it when VIM
708 * terminates). Should we be using the 'mch_libcall' routines?
709 * Seems like a lot of overhead to load/unload ADVAPI32.DLL each
710 * time we verify security...
711 */
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200712 advapi_lib = vimLoadLib("ADVAPI32.DLL");
Bram Moolenaar071d4272004-06-13 20:20:40 +0000713 if (advapi_lib != NULL)
714 {
715 pSetNamedSecurityInfo = (PSNSECINFO)GetProcAddress(advapi_lib,
716 "SetNamedSecurityInfoA");
717 pGetNamedSecurityInfo = (PGNSECINFO)GetProcAddress(advapi_lib,
718 "GetNamedSecurityInfoA");
Bram Moolenaar27515922013-06-29 15:36:26 +0200719# ifdef FEAT_MBYTE
720 pSetNamedSecurityInfoW = (PSNSECINFOW)GetProcAddress(advapi_lib,
721 "SetNamedSecurityInfoW");
722 pGetNamedSecurityInfoW = (PGNSECINFOW)GetProcAddress(advapi_lib,
723 "GetNamedSecurityInfoW");
724# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000725 if (pSetNamedSecurityInfo == NULL
Bram Moolenaar27515922013-06-29 15:36:26 +0200726 || pGetNamedSecurityInfo == NULL
727# ifdef FEAT_MBYTE
728 || pSetNamedSecurityInfoW == NULL
729 || pGetNamedSecurityInfoW == NULL
730# endif
731 )
Bram Moolenaar071d4272004-06-13 20:20:40 +0000732 {
733 /* If we can't get the function addresses, set advapi_lib
734 * to NULL so that we don't use them. */
735 FreeLibrary(advapi_lib);
736 advapi_lib = NULL;
737 }
Bram Moolenaar27515922013-06-29 15:36:26 +0200738 /* Enable privilege for getting or setting SACLs. */
739 win32_enable_privilege(SE_SECURITY_NAME, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000740 }
741 }
742#endif
Bram Moolenaar4b9669f2011-07-07 16:20:52 +0200743 /*
744 * If we are on windows NT, try to load the pipe functions, only
745 * available from Win2K.
746 */
747 if (g_PlatformId == VER_PLATFORM_WIN32_NT)
748 {
749 HANDLE kernel32 = GetModuleHandle("kernel32");
750 pSetHandleInformation = (PSETHANDLEINFORMATION)GetProcAddress(
751 kernel32, "SetHandleInformation");
752
753 allowPiping = pSetHandleInformation != NULL;
754 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000755 done = TRUE;
756 }
757}
758
759/*
760 * Return TRUE when running on Windows 95 (or 98 or ME).
761 * Only to be used after mch_init().
762 */
763 int
764mch_windows95(void)
765{
766 return g_PlatformId == VER_PLATFORM_WIN32_WINDOWS;
767}
768
769#ifdef FEAT_GUI_W32
770/*
771 * Used to work around the "can't do synchronous spawn"
772 * problem on Win32s, without resorting to Universal Thunk.
773 */
774static int old_num_windows;
775static int num_windows;
776
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000777/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +0000778 static BOOL CALLBACK
779win32ssynch_cb(HWND hwnd, LPARAM lparam)
780{
781 num_windows++;
782 return TRUE;
783}
784#endif
785
786#ifndef FEAT_GUI_W32
787
788#define SHIFT (SHIFT_PRESSED)
789#define CTRL (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED)
790#define ALT (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED)
791#define ALT_GR (RIGHT_ALT_PRESSED | LEFT_CTRL_PRESSED)
792
793
794/* When uChar.AsciiChar is 0, then we need to look at wVirtualKeyCode.
795 * We map function keys to their ANSI terminal equivalents, as produced
796 * by ANSI.SYS, for compatibility with the MS-DOS version of Vim. Any
797 * ANSI key with a value >= '\300' is nonstandard, but provided anyway
798 * so that the user can have access to all SHIFT-, CTRL-, and ALT-
799 * combinations of function/arrow/etc keys.
800 */
801
Bram Moolenaard6f676d2005-06-01 21:51:55 +0000802static const struct
Bram Moolenaar071d4272004-06-13 20:20:40 +0000803{
804 WORD wVirtKey;
805 BOOL fAnsiKey;
806 int chAlone;
807 int chShift;
808 int chCtrl;
809 int chAlt;
810} VirtKeyMap[] =
811{
812
813/* Key ANSI alone shift ctrl alt */
814 { VK_ESCAPE,FALSE, ESC, ESC, ESC, ESC, },
815
816 { VK_F1, TRUE, ';', 'T', '^', 'h', },
817 { VK_F2, TRUE, '<', 'U', '_', 'i', },
818 { VK_F3, TRUE, '=', 'V', '`', 'j', },
819 { VK_F4, TRUE, '>', 'W', 'a', 'k', },
820 { VK_F5, TRUE, '?', 'X', 'b', 'l', },
821 { VK_F6, TRUE, '@', 'Y', 'c', 'm', },
822 { VK_F7, TRUE, 'A', 'Z', 'd', 'n', },
823 { VK_F8, TRUE, 'B', '[', 'e', 'o', },
824 { VK_F9, TRUE, 'C', '\\', 'f', 'p', },
825 { VK_F10, TRUE, 'D', ']', 'g', 'q', },
826 { VK_F11, TRUE, '\205', '\207', '\211', '\213', },
827 { VK_F12, TRUE, '\206', '\210', '\212', '\214', },
828
829 { VK_HOME, TRUE, 'G', '\302', 'w', '\303', },
830 { VK_UP, TRUE, 'H', '\304', '\305', '\306', },
831 { VK_PRIOR, TRUE, 'I', '\307', '\204', '\310', }, /*PgUp*/
832 { VK_LEFT, TRUE, 'K', '\311', 's', '\312', },
833 { VK_RIGHT, TRUE, 'M', '\313', 't', '\314', },
834 { VK_END, TRUE, 'O', '\315', 'u', '\316', },
835 { VK_DOWN, TRUE, 'P', '\317', '\320', '\321', },
836 { VK_NEXT, TRUE, 'Q', '\322', 'v', '\323', }, /*PgDn*/
837 { VK_INSERT,TRUE, 'R', '\324', '\325', '\326', },
838 { VK_DELETE,TRUE, 'S', '\327', '\330', '\331', },
839
840 { VK_SNAPSHOT,TRUE, 0, 0, 0, 'r', }, /*PrtScrn*/
841
842#if 0
843 /* Most people don't have F13-F20, but what the hell... */
844 { VK_F13, TRUE, '\332', '\333', '\334', '\335', },
845 { VK_F14, TRUE, '\336', '\337', '\340', '\341', },
846 { VK_F15, TRUE, '\342', '\343', '\344', '\345', },
847 { VK_F16, TRUE, '\346', '\347', '\350', '\351', },
848 { VK_F17, TRUE, '\352', '\353', '\354', '\355', },
849 { VK_F18, TRUE, '\356', '\357', '\360', '\361', },
850 { VK_F19, TRUE, '\362', '\363', '\364', '\365', },
851 { VK_F20, TRUE, '\366', '\367', '\370', '\371', },
852#endif
853 { VK_ADD, TRUE, 'N', 'N', 'N', 'N', }, /* keyp '+' */
854 { VK_SUBTRACT, TRUE,'J', 'J', 'J', 'J', }, /* keyp '-' */
855 /* { VK_DIVIDE, TRUE,'N', 'N', 'N', 'N', }, keyp '/' */
856 { VK_MULTIPLY, TRUE,'7', '7', '7', '7', }, /* keyp '*' */
857
858 { VK_NUMPAD0,TRUE, '\332', '\333', '\334', '\335', },
859 { VK_NUMPAD1,TRUE, '\336', '\337', '\340', '\341', },
860 { VK_NUMPAD2,TRUE, '\342', '\343', '\344', '\345', },
861 { VK_NUMPAD3,TRUE, '\346', '\347', '\350', '\351', },
862 { VK_NUMPAD4,TRUE, '\352', '\353', '\354', '\355', },
863 { VK_NUMPAD5,TRUE, '\356', '\357', '\360', '\361', },
864 { VK_NUMPAD6,TRUE, '\362', '\363', '\364', '\365', },
865 { VK_NUMPAD7,TRUE, '\366', '\367', '\370', '\371', },
866 { VK_NUMPAD8,TRUE, '\372', '\373', '\374', '\375', },
867 /* Sorry, out of number space! <negri>*/
868 { VK_NUMPAD9,TRUE, '\376', '\377', '\377', '\367', },
869
870};
871
872
873#ifdef _MSC_VER
874// The ToAscii bug destroys several registers. Need to turn off optimization
875// or the GetConsoleKeyboardLayoutName hack will fail in non-debug versions
Bram Moolenaar7b5f8322006-03-23 22:47:08 +0000876# pragma warning(push)
877# pragma warning(disable: 4748)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000878# pragma optimize("", off)
879#endif
880
881#if defined(__GNUC__) && !defined(__MINGW32__) && !defined(__CYGWIN__)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200882# define UChar UnicodeChar
Bram Moolenaar071d4272004-06-13 20:20:40 +0000883#else
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200884# define UChar uChar.UnicodeChar
Bram Moolenaar071d4272004-06-13 20:20:40 +0000885#endif
886
887/* The return code indicates key code size. */
888 static int
889#ifdef __BORLANDC__
890 __stdcall
891#endif
892win32_kbd_patch_key(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000893 KEY_EVENT_RECORD *pker)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000894{
895 UINT uMods = pker->dwControlKeyState;
896 static int s_iIsDead = 0;
897 static WORD awAnsiCode[2];
898 static BYTE abKeystate[256];
899
900
901 if (s_iIsDead == 2)
902 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200903 pker->UChar = (WCHAR) awAnsiCode[1];
Bram Moolenaar071d4272004-06-13 20:20:40 +0000904 s_iIsDead = 0;
905 return 1;
906 }
907
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200908 if (pker->UChar != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000909 return 1;
910
Bram Moolenaar7db5fc82010-05-24 11:59:29 +0200911 vim_memset(abKeystate, 0, sizeof (abKeystate));
Bram Moolenaar071d4272004-06-13 20:20:40 +0000912
913 // Should only be non-NULL on NT 4.0
914 if (s_pfnGetConsoleKeyboardLayoutName != NULL)
915 {
916 CHAR szKLID[KL_NAMELENGTH];
917
918 if ((*s_pfnGetConsoleKeyboardLayoutName)(szKLID))
919 (void)LoadKeyboardLayout(szKLID, KLF_ACTIVATE);
920 }
921
922 /* Clear any pending dead keys */
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200923 ToUnicode(VK_SPACE, MapVirtualKey(VK_SPACE, 0), abKeystate, awAnsiCode, 2, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000924
925 if (uMods & SHIFT_PRESSED)
926 abKeystate[VK_SHIFT] = 0x80;
927 if (uMods & CAPSLOCK_ON)
928 abKeystate[VK_CAPITAL] = 1;
929
930 if ((uMods & ALT_GR) == ALT_GR)
931 {
932 abKeystate[VK_CONTROL] = abKeystate[VK_LCONTROL] =
933 abKeystate[VK_MENU] = abKeystate[VK_RMENU] = 0x80;
934 }
935
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200936 s_iIsDead = ToUnicode(pker->wVirtualKeyCode, pker->wVirtualScanCode,
937 abKeystate, awAnsiCode, 2, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000938
939 if (s_iIsDead > 0)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200940 pker->UChar = (WCHAR) awAnsiCode[0];
Bram Moolenaar071d4272004-06-13 20:20:40 +0000941
942 return s_iIsDead;
943}
944
945#ifdef _MSC_VER
946/* MUST switch optimization on again here, otherwise a call to
947 * decode_key_event() may crash (e.g. when hitting caps-lock) */
948# pragma optimize("", on)
Bram Moolenaar7b5f8322006-03-23 22:47:08 +0000949# pragma warning(pop)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000950
951# if (_MSC_VER < 1100)
952/* MUST turn off global optimisation for this next function, or
953 * pressing ctrl-minus in insert mode crashes Vim when built with
954 * VC4.1. -- negri. */
955# pragma optimize("g", off)
956# endif
957#endif
958
959static BOOL g_fJustGotFocus = FALSE;
960
961/*
962 * Decode a KEY_EVENT into one or two keystrokes
963 */
964 static BOOL
965decode_key_event(
966 KEY_EVENT_RECORD *pker,
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200967 WCHAR *pch,
968 WCHAR *pch2,
Bram Moolenaar071d4272004-06-13 20:20:40 +0000969 int *pmodifiers,
970 BOOL fDoPost)
971{
972 int i;
973 const int nModifs = pker->dwControlKeyState & (SHIFT | ALT | CTRL);
974
975 *pch = *pch2 = NUL;
976 g_fJustGotFocus = FALSE;
977
978 /* ignore key up events */
979 if (!pker->bKeyDown)
980 return FALSE;
981
982 /* ignore some keystrokes */
983 switch (pker->wVirtualKeyCode)
984 {
985 /* modifiers */
986 case VK_SHIFT:
987 case VK_CONTROL:
988 case VK_MENU: /* Alt key */
989 return FALSE;
990
991 default:
992 break;
993 }
994
995 /* special cases */
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200996 if ((nModifs & CTRL) != 0 && (nModifs & ~CTRL) == 0 && pker->UChar == NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000997 {
998 /* Ctrl-6 is Ctrl-^ */
999 if (pker->wVirtualKeyCode == '6')
1000 {
1001 *pch = Ctrl_HAT;
1002 return TRUE;
1003 }
1004 /* Ctrl-2 is Ctrl-@ */
1005 else if (pker->wVirtualKeyCode == '2')
1006 {
1007 *pch = NUL;
1008 return TRUE;
1009 }
1010 /* Ctrl-- is Ctrl-_ */
1011 else if (pker->wVirtualKeyCode == 0xBD)
1012 {
1013 *pch = Ctrl__;
1014 return TRUE;
1015 }
1016 }
1017
1018 /* Shift-TAB */
1019 if (pker->wVirtualKeyCode == VK_TAB && (nModifs & SHIFT_PRESSED))
1020 {
1021 *pch = K_NUL;
1022 *pch2 = '\017';
1023 return TRUE;
1024 }
1025
1026 for (i = sizeof(VirtKeyMap) / sizeof(VirtKeyMap[0]); --i >= 0; )
1027 {
1028 if (VirtKeyMap[i].wVirtKey == pker->wVirtualKeyCode)
1029 {
1030 if (nModifs == 0)
1031 *pch = VirtKeyMap[i].chAlone;
1032 else if ((nModifs & SHIFT) != 0 && (nModifs & ~SHIFT) == 0)
1033 *pch = VirtKeyMap[i].chShift;
1034 else if ((nModifs & CTRL) != 0 && (nModifs & ~CTRL) == 0)
1035 *pch = VirtKeyMap[i].chCtrl;
1036 else if ((nModifs & ALT) != 0 && (nModifs & ~ALT) == 0)
1037 *pch = VirtKeyMap[i].chAlt;
1038
1039 if (*pch != 0)
1040 {
1041 if (VirtKeyMap[i].fAnsiKey)
1042 {
1043 *pch2 = *pch;
1044 *pch = K_NUL;
1045 }
1046
1047 return TRUE;
1048 }
1049 }
1050 }
1051
1052 i = win32_kbd_patch_key(pker);
1053
1054 if (i < 0)
1055 *pch = NUL;
1056 else
1057 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001058 *pch = (i > 0) ? pker->UChar : NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001059
1060 if (pmodifiers != NULL)
1061 {
1062 /* Pass on the ALT key as a modifier, but only when not combined
1063 * with CTRL (which is ALTGR). */
1064 if ((nModifs & ALT) != 0 && (nModifs & CTRL) == 0)
1065 *pmodifiers |= MOD_MASK_ALT;
1066
1067 /* Pass on SHIFT only for special keys, because we don't know when
1068 * it's already included with the character. */
1069 if ((nModifs & SHIFT) != 0 && *pch <= 0x20)
1070 *pmodifiers |= MOD_MASK_SHIFT;
1071
1072 /* Pass on CTRL only for non-special keys, because we don't know
1073 * when it's already included with the character. And not when
1074 * combined with ALT (which is ALTGR). */
1075 if ((nModifs & CTRL) != 0 && (nModifs & ALT) == 0
1076 && *pch >= 0x20 && *pch < 0x80)
1077 *pmodifiers |= MOD_MASK_CTRL;
1078 }
1079 }
1080
1081 return (*pch != NUL);
1082}
1083
1084#ifdef _MSC_VER
1085# pragma optimize("", on)
1086#endif
1087
1088#endif /* FEAT_GUI_W32 */
1089
1090
1091#ifdef FEAT_MOUSE
1092
1093/*
1094 * For the GUI the mouse handling is in gui_w32.c.
1095 */
1096# ifdef FEAT_GUI_W32
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00001097/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00001098 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001099mch_setmouse(int on)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001100{
1101}
1102# else
1103static int g_fMouseAvail = FALSE; /* mouse present */
1104static int g_fMouseActive = FALSE; /* mouse enabled */
1105static int g_nMouseClick = -1; /* mouse status */
1106static int g_xMouse; /* mouse x coordinate */
1107static int g_yMouse; /* mouse y coordinate */
1108
1109/*
1110 * Enable or disable mouse input
1111 */
1112 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001113mch_setmouse(int on)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001114{
1115 DWORD cmodein;
1116
1117 if (!g_fMouseAvail)
1118 return;
1119
1120 g_fMouseActive = on;
1121 GetConsoleMode(g_hConIn, &cmodein);
1122
1123 if (g_fMouseActive)
1124 cmodein |= ENABLE_MOUSE_INPUT;
1125 else
1126 cmodein &= ~ENABLE_MOUSE_INPUT;
1127
1128 SetConsoleMode(g_hConIn, cmodein);
1129}
1130
Bram Moolenaar071d4272004-06-13 20:20:40 +00001131/*
1132 * Decode a MOUSE_EVENT. If it's a valid event, return MOUSE_LEFT,
1133 * MOUSE_MIDDLE, or MOUSE_RIGHT for a click; MOUSE_DRAG for a mouse
1134 * move with a button held down; and MOUSE_RELEASE after a MOUSE_DRAG
1135 * or a MOUSE_LEFT, _MIDDLE, or _RIGHT. We encode the button type,
1136 * the number of clicks, and the Shift/Ctrl/Alt modifiers in g_nMouseClick,
1137 * and we return the mouse position in g_xMouse and g_yMouse.
1138 *
1139 * Every MOUSE_LEFT, _MIDDLE, or _RIGHT will be followed by zero or more
1140 * MOUSE_DRAGs and one MOUSE_RELEASE. MOUSE_RELEASE will be followed only
1141 * by MOUSE_LEFT, _MIDDLE, or _RIGHT.
1142 *
1143 * For multiple clicks, we send, say, MOUSE_LEFT/1 click, MOUSE_RELEASE,
1144 * MOUSE_LEFT/2 clicks, MOUSE_RELEASE, MOUSE_LEFT/3 clicks, MOUSE_RELEASE, ....
1145 *
1146 * Windows will send us MOUSE_MOVED notifications whenever the mouse
1147 * moves, even if it stays within the same character cell. We ignore
1148 * all MOUSE_MOVED messages if the position hasn't really changed, and
1149 * we ignore all MOUSE_MOVED messages where no button is held down (i.e.,
1150 * we're only interested in MOUSE_DRAG).
1151 *
1152 * All of this is complicated by the code that fakes MOUSE_MIDDLE on
1153 * 2-button mouses by pressing the left & right buttons simultaneously.
1154 * In practice, it's almost impossible to click both at the same time,
1155 * so we need to delay a little. Also, we tend not to get MOUSE_RELEASE
1156 * in such cases, if the user is clicking quickly.
1157 */
1158 static BOOL
1159decode_mouse_event(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001160 MOUSE_EVENT_RECORD *pmer)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001161{
1162 static int s_nOldButton = -1;
1163 static int s_nOldMouseClick = -1;
1164 static int s_xOldMouse = -1;
1165 static int s_yOldMouse = -1;
1166 static linenr_T s_old_topline = 0;
1167#ifdef FEAT_DIFF
1168 static int s_old_topfill = 0;
1169#endif
1170 static int s_cClicks = 1;
1171 static BOOL s_fReleased = TRUE;
1172 static DWORD s_dwLastClickTime = 0;
1173 static BOOL s_fNextIsMiddle = FALSE;
1174
1175 static DWORD cButtons = 0; /* number of buttons supported */
1176
1177 const DWORD LEFT = FROM_LEFT_1ST_BUTTON_PRESSED;
1178 const DWORD MIDDLE = FROM_LEFT_2ND_BUTTON_PRESSED;
1179 const DWORD RIGHT = RIGHTMOST_BUTTON_PRESSED;
1180 const DWORD LEFT_RIGHT = LEFT | RIGHT;
1181
1182 int nButton;
1183
1184 if (cButtons == 0 && !GetNumberOfConsoleMouseButtons(&cButtons))
1185 cButtons = 2;
1186
1187 if (!g_fMouseAvail || !g_fMouseActive)
1188 {
1189 g_nMouseClick = -1;
1190 return FALSE;
1191 }
1192
1193 /* get a spurious MOUSE_EVENT immediately after receiving focus; ignore */
1194 if (g_fJustGotFocus)
1195 {
1196 g_fJustGotFocus = FALSE;
1197 return FALSE;
1198 }
1199
1200 /* unprocessed mouse click? */
1201 if (g_nMouseClick != -1)
1202 return TRUE;
1203
1204 nButton = -1;
1205 g_xMouse = pmer->dwMousePosition.X;
1206 g_yMouse = pmer->dwMousePosition.Y;
1207
1208 if (pmer->dwEventFlags == MOUSE_MOVED)
1209 {
1210 /* ignore MOUSE_MOVED events if (x, y) hasn't changed. (We get these
1211 * events even when the mouse moves only within a char cell.) */
1212 if (s_xOldMouse == g_xMouse && s_yOldMouse == g_yMouse)
1213 return FALSE;
1214 }
1215
1216 /* If no buttons are pressed... */
1217 if ((pmer->dwButtonState & ((1 << cButtons) - 1)) == 0)
1218 {
1219 /* If the last thing returned was MOUSE_RELEASE, ignore this */
1220 if (s_fReleased)
1221 return FALSE;
1222
1223 nButton = MOUSE_RELEASE;
1224 s_fReleased = TRUE;
1225 }
1226 else /* one or more buttons pressed */
1227 {
1228 /* on a 2-button mouse, hold down left and right buttons
1229 * simultaneously to get MIDDLE. */
1230
1231 if (cButtons == 2 && s_nOldButton != MOUSE_DRAG)
1232 {
1233 DWORD dwLR = (pmer->dwButtonState & LEFT_RIGHT);
1234
1235 /* if either left or right button only is pressed, see if the
Bram Moolenaar84a05ac2013-05-06 04:24:17 +02001236 * next mouse event has both of them pressed */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001237 if (dwLR == LEFT || dwLR == RIGHT)
1238 {
1239 for (;;)
1240 {
1241 /* wait a short time for next input event */
1242 if (WaitForSingleObject(g_hConIn, p_mouset / 3)
1243 != WAIT_OBJECT_0)
1244 break;
1245 else
1246 {
1247 DWORD cRecords = 0;
1248 INPUT_RECORD ir;
1249 MOUSE_EVENT_RECORD* pmer2 = &ir.Event.MouseEvent;
1250
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001251 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001252
1253 if (cRecords == 0 || ir.EventType != MOUSE_EVENT
1254 || !(pmer2->dwButtonState & LEFT_RIGHT))
1255 break;
1256 else
1257 {
1258 if (pmer2->dwEventFlags != MOUSE_MOVED)
1259 {
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001260 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001261
1262 return decode_mouse_event(pmer2);
1263 }
1264 else if (s_xOldMouse == pmer2->dwMousePosition.X &&
1265 s_yOldMouse == pmer2->dwMousePosition.Y)
1266 {
1267 /* throw away spurious mouse move */
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001268 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001269
1270 /* are there any more mouse events in queue? */
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001271 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001272
1273 if (cRecords==0 || ir.EventType != MOUSE_EVENT)
1274 break;
1275 }
1276 else
1277 break;
1278 }
1279 }
1280 }
1281 }
1282 }
1283
1284 if (s_fNextIsMiddle)
1285 {
1286 nButton = (pmer->dwEventFlags == MOUSE_MOVED)
1287 ? MOUSE_DRAG : MOUSE_MIDDLE;
1288 s_fNextIsMiddle = FALSE;
1289 }
1290 else if (cButtons == 2 &&
1291 ((pmer->dwButtonState & LEFT_RIGHT) == LEFT_RIGHT))
1292 {
1293 nButton = MOUSE_MIDDLE;
1294
1295 if (! s_fReleased && pmer->dwEventFlags != MOUSE_MOVED)
1296 {
1297 s_fNextIsMiddle = TRUE;
1298 nButton = MOUSE_RELEASE;
1299 }
1300 }
1301 else if ((pmer->dwButtonState & LEFT) == LEFT)
1302 nButton = MOUSE_LEFT;
1303 else if ((pmer->dwButtonState & MIDDLE) == MIDDLE)
1304 nButton = MOUSE_MIDDLE;
1305 else if ((pmer->dwButtonState & RIGHT) == RIGHT)
1306 nButton = MOUSE_RIGHT;
1307
1308 if (! s_fReleased && ! s_fNextIsMiddle
1309 && nButton != s_nOldButton && s_nOldButton != MOUSE_DRAG)
1310 return FALSE;
1311
1312 s_fReleased = s_fNextIsMiddle;
1313 }
1314
1315 if (pmer->dwEventFlags == 0 || pmer->dwEventFlags == DOUBLE_CLICK)
1316 {
1317 /* button pressed or released, without mouse moving */
1318 if (nButton != -1 && nButton != MOUSE_RELEASE)
1319 {
1320 DWORD dwCurrentTime = GetTickCount();
1321
1322 if (s_xOldMouse != g_xMouse
1323 || s_yOldMouse != g_yMouse
1324 || s_nOldButton != nButton
1325 || s_old_topline != curwin->w_topline
1326#ifdef FEAT_DIFF
1327 || s_old_topfill != curwin->w_topfill
1328#endif
1329 || (int)(dwCurrentTime - s_dwLastClickTime) > p_mouset)
1330 {
1331 s_cClicks = 1;
1332 }
1333 else if (++s_cClicks > 4)
1334 {
1335 s_cClicks = 1;
1336 }
1337
1338 s_dwLastClickTime = dwCurrentTime;
1339 }
1340 }
1341 else if (pmer->dwEventFlags == MOUSE_MOVED)
1342 {
1343 if (nButton != -1 && nButton != MOUSE_RELEASE)
1344 nButton = MOUSE_DRAG;
1345
1346 s_cClicks = 1;
1347 }
1348
1349 if (nButton == -1)
1350 return FALSE;
1351
1352 if (nButton != MOUSE_RELEASE)
1353 s_nOldButton = nButton;
1354
1355 g_nMouseClick = nButton;
1356
1357 if (pmer->dwControlKeyState & SHIFT_PRESSED)
1358 g_nMouseClick |= MOUSE_SHIFT;
1359 if (pmer->dwControlKeyState & (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED))
1360 g_nMouseClick |= MOUSE_CTRL;
1361 if (pmer->dwControlKeyState & (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED))
1362 g_nMouseClick |= MOUSE_ALT;
1363
1364 if (nButton != MOUSE_DRAG && nButton != MOUSE_RELEASE)
1365 SET_NUM_MOUSE_CLICKS(g_nMouseClick, s_cClicks);
1366
1367 /* only pass on interesting (i.e., different) mouse events */
1368 if (s_xOldMouse == g_xMouse
1369 && s_yOldMouse == g_yMouse
1370 && s_nOldMouseClick == g_nMouseClick)
1371 {
1372 g_nMouseClick = -1;
1373 return FALSE;
1374 }
1375
1376 s_xOldMouse = g_xMouse;
1377 s_yOldMouse = g_yMouse;
1378 s_old_topline = curwin->w_topline;
1379#ifdef FEAT_DIFF
1380 s_old_topfill = curwin->w_topfill;
1381#endif
1382 s_nOldMouseClick = g_nMouseClick;
1383
1384 return TRUE;
1385}
1386
1387# endif /* FEAT_GUI_W32 */
1388#endif /* FEAT_MOUSE */
1389
1390
1391#ifdef MCH_CURSOR_SHAPE
1392/*
1393 * Set the shape of the cursor.
1394 * 'thickness' can be from 1 (thin) to 99 (block)
1395 */
1396 static void
1397mch_set_cursor_shape(int thickness)
1398{
1399 CONSOLE_CURSOR_INFO ConsoleCursorInfo;
1400 ConsoleCursorInfo.dwSize = thickness;
1401 ConsoleCursorInfo.bVisible = s_cursor_visible;
1402
1403 SetConsoleCursorInfo(g_hConOut, &ConsoleCursorInfo);
1404 if (s_cursor_visible)
1405 SetConsoleCursorPosition(g_hConOut, g_coord);
1406}
1407
1408 void
1409mch_update_cursor(void)
1410{
1411 int idx;
1412 int thickness;
1413
1414 /*
1415 * How the cursor is drawn depends on the current mode.
1416 */
1417 idx = get_shape_idx(FALSE);
1418
1419 if (shape_table[idx].shape == SHAPE_BLOCK)
1420 thickness = 99; /* 100 doesn't work on W95 */
1421 else
1422 thickness = shape_table[idx].percentage;
1423 mch_set_cursor_shape(thickness);
1424}
1425#endif
1426
1427#ifndef FEAT_GUI_W32 /* this isn't used for the GUI */
1428/*
1429 * Handle FOCUS_EVENT.
1430 */
1431 static void
1432handle_focus_event(INPUT_RECORD ir)
1433{
1434 g_fJustGotFocus = ir.Event.FocusEvent.bSetFocus;
1435 ui_focus_change((int)g_fJustGotFocus);
1436}
1437
1438/*
1439 * Wait until console input from keyboard or mouse is available,
1440 * or the time is up.
1441 * Return TRUE if something is available FALSE if not.
1442 */
1443 static int
1444WaitForChar(long msec)
1445{
1446 DWORD dwNow = 0, dwEndTime = 0;
1447 INPUT_RECORD ir;
1448 DWORD cRecords;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001449 WCHAR ch, ch2;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001450
1451 if (msec > 0)
1452 /* Wait until the specified time has elapsed. */
1453 dwEndTime = GetTickCount() + msec;
1454 else if (msec < 0)
1455 /* Wait forever. */
1456 dwEndTime = INFINITE;
1457
1458 /* We need to loop until the end of the time period, because
1459 * we might get multiple unusable mouse events in that time.
1460 */
1461 for (;;)
1462 {
Bram Moolenaarca568ae2016-02-01 21:32:58 +01001463#ifdef MESSAGE_QUEUE
1464 parse_queued_messages();
1465#endif
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001466#ifdef FEAT_MZSCHEME
1467 mzvim_check_threads();
1468#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001469#ifdef FEAT_CLIENTSERVER
1470 serverProcessPendingMessages();
1471#endif
Bram Moolenaarf12d9832016-01-29 21:11:25 +01001472
1473#ifdef FEAT_CHANNEL
Bram Moolenaared5a78e2016-02-19 21:05:03 +01001474 channel_handle_events();
Bram Moolenaarf12d9832016-01-29 21:11:25 +01001475#endif
1476
Bram Moolenaar071d4272004-06-13 20:20:40 +00001477 if (0
1478#ifdef FEAT_MOUSE
1479 || g_nMouseClick != -1
1480#endif
1481#ifdef FEAT_CLIENTSERVER
1482 || input_available()
1483#endif
1484 )
1485 return TRUE;
1486
1487 if (msec > 0)
1488 {
Bram Moolenaarb7512b72013-08-10 12:45:09 +02001489 /* If the specified wait time has passed, return. Beware that
1490 * GetTickCount() may wrap around (overflow). */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001491 dwNow = GetTickCount();
Bram Moolenaarb7512b72013-08-10 12:45:09 +02001492 if ((int)(dwNow - dwEndTime) >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001493 break;
1494 }
1495 if (msec != 0)
1496 {
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001497 DWORD dwWaitTime = dwEndTime - dwNow;
1498
1499#ifdef FEAT_MZSCHEME
1500 if (mzthreads_allowed() && p_mzq > 0
1501 && (msec < 0 || (long)dwWaitTime > p_mzq))
1502 dwWaitTime = p_mzq; /* don't wait longer than 'mzquantum' */
1503#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001504#ifdef FEAT_CLIENTSERVER
1505 /* Wait for either an event on the console input or a message in
1506 * the client-server window. */
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +02001507 if (msg_wait_for_multiple_objects(1, &g_hConIn, FALSE,
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001508 dwWaitTime, QS_SENDMESSAGE) != WAIT_OBJECT_0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001509#else
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +02001510 if (wait_for_single_object(g_hConIn, dwWaitTime) != WAIT_OBJECT_0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001511#endif
1512 continue;
1513 }
1514
1515 cRecords = 0;
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001516 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001517
1518#ifdef FEAT_MBYTE_IME
1519 if (State & CMDLINE && msg_row == Rows - 1)
1520 {
1521 CONSOLE_SCREEN_BUFFER_INFO csbi;
1522
1523 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
1524 {
1525 if (csbi.dwCursorPosition.Y != msg_row)
1526 {
1527 /* The screen is now messed up, must redraw the
1528 * command line and later all the windows. */
1529 redraw_all_later(CLEAR);
1530 cmdline_row -= (msg_row - csbi.dwCursorPosition.Y);
1531 redrawcmd();
1532 }
1533 }
1534 }
1535#endif
1536
1537 if (cRecords > 0)
1538 {
1539 if (ir.EventType == KEY_EVENT && ir.Event.KeyEvent.bKeyDown)
1540 {
1541#ifdef FEAT_MBYTE_IME
1542 /* Windows IME sends two '\n's with only one 'ENTER'. First:
1543 * wVirtualKeyCode == 13. second: wVirtualKeyCode == 0 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001544 if (ir.Event.KeyEvent.UChar == 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00001545 && ir.Event.KeyEvent.wVirtualKeyCode == 13)
1546 {
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001547 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001548 continue;
1549 }
1550#endif
1551 if (decode_key_event(&ir.Event.KeyEvent, &ch, &ch2,
1552 NULL, FALSE))
1553 return TRUE;
1554 }
1555
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001556 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001557
1558 if (ir.EventType == FOCUS_EVENT)
1559 handle_focus_event(ir);
1560 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
1561 shell_resized();
1562#ifdef FEAT_MOUSE
1563 else if (ir.EventType == MOUSE_EVENT
1564 && decode_mouse_event(&ir.Event.MouseEvent))
1565 return TRUE;
1566#endif
1567 }
1568 else if (msec == 0)
1569 break;
1570 }
1571
1572#ifdef FEAT_CLIENTSERVER
1573 /* Something might have been received while we were waiting. */
1574 if (input_available())
1575 return TRUE;
1576#endif
Bram Moolenaarf12d9832016-01-29 21:11:25 +01001577
Bram Moolenaar071d4272004-06-13 20:20:40 +00001578 return FALSE;
1579}
1580
1581#ifndef FEAT_GUI_MSWIN
1582/*
1583 * return non-zero if a character is available
1584 */
1585 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001586mch_char_avail(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001587{
1588 return WaitForChar(0L);
1589}
1590#endif
1591
1592/*
1593 * Create the console input. Used when reading stdin doesn't work.
1594 */
1595 static void
1596create_conin(void)
1597{
1598 g_hConIn = CreateFile("CONIN$", GENERIC_READ|GENERIC_WRITE,
1599 FILE_SHARE_READ|FILE_SHARE_WRITE,
1600 (LPSECURITY_ATTRIBUTES) NULL,
Bram Moolenaareb3593b2006-04-22 22:33:57 +00001601 OPEN_EXISTING, 0, (HANDLE)NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001602 did_create_conin = TRUE;
1603}
1604
1605/*
1606 * Get a keystroke or a mouse event
1607 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001608 static WCHAR
1609tgetch(int *pmodifiers, WCHAR *pch2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001610{
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001611 WCHAR ch;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001612
1613 for (;;)
1614 {
1615 INPUT_RECORD ir;
1616 DWORD cRecords = 0;
1617
1618#ifdef FEAT_CLIENTSERVER
1619 (void)WaitForChar(-1L);
1620 if (input_available())
1621 return 0;
1622# ifdef FEAT_MOUSE
1623 if (g_nMouseClick != -1)
1624 return 0;
1625# endif
1626#endif
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001627 if (read_console_input(g_hConIn, &ir, 1, &cRecords) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001628 {
1629 if (did_create_conin)
1630 read_error_exit();
1631 create_conin();
1632 continue;
1633 }
1634
1635 if (ir.EventType == KEY_EVENT)
1636 {
1637 if (decode_key_event(&ir.Event.KeyEvent, &ch, pch2,
1638 pmodifiers, TRUE))
1639 return ch;
1640 }
1641 else if (ir.EventType == FOCUS_EVENT)
1642 handle_focus_event(ir);
1643 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
1644 shell_resized();
1645#ifdef FEAT_MOUSE
1646 else if (ir.EventType == MOUSE_EVENT)
1647 {
1648 if (decode_mouse_event(&ir.Event.MouseEvent))
1649 return 0;
1650 }
1651#endif
1652 }
1653}
1654#endif /* !FEAT_GUI_W32 */
1655
1656
1657/*
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02001658 * mch_inchar(): low-level input function.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001659 * Get one or more characters from the keyboard or the mouse.
1660 * If time == 0, do not wait for characters.
1661 * If time == n, wait a short time for characters.
1662 * If time == -1, wait forever for characters.
1663 * Returns the number of characters read into buf.
1664 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00001665/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00001666 int
1667mch_inchar(
1668 char_u *buf,
1669 int maxlen,
1670 long time,
1671 int tb_change_cnt)
1672{
1673#ifndef FEAT_GUI_W32 /* this isn't used for the GUI */
1674
1675 int len;
1676 int c;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001677#define TYPEAHEADLEN 20
1678 static char_u typeahead[TYPEAHEADLEN]; /* previously typed bytes. */
1679 static int typeaheadlen = 0;
1680
1681 /* First use any typeahead that was kept because "buf" was too small. */
1682 if (typeaheadlen > 0)
1683 goto theend;
1684
1685#ifdef FEAT_SNIFF
1686 if (want_sniff_request)
1687 {
1688 if (sniff_request_waiting)
1689 {
1690 /* return K_SNIFF */
1691 typeahead[typeaheadlen++] = CSI;
1692 typeahead[typeaheadlen++] = (char_u)KS_EXTRA;
1693 typeahead[typeaheadlen++] = (char_u)KE_SNIFF;
1694 sniff_request_waiting = 0;
1695 want_sniff_request = 0;
1696 goto theend;
1697 }
1698 else if (time < 0 || time > 250)
1699 {
1700 /* don't wait too long, a request might be pending */
1701 time = 250;
1702 }
1703 }
1704#endif
1705
1706 if (time >= 0)
1707 {
1708 if (!WaitForChar(time)) /* no character available */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001709 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001710 }
1711 else /* time == -1, wait forever */
1712 {
1713 mch_set_winsize_now(); /* Allow winsize changes from now on */
1714
Bram Moolenaar3918c952005-03-15 22:34:55 +00001715 /*
1716 * If there is no character available within 2 seconds (default)
1717 * write the autoscript file to disk. Or cause the CursorHold event
1718 * to be triggered.
1719 */
1720 if (!WaitForChar(p_ut))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001721 {
1722#ifdef FEAT_AUTOCMD
Bram Moolenaard35f9712005-12-18 22:02:33 +00001723 if (trigger_cursorhold() && maxlen >= 3)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001724 {
Bram Moolenaar3918c952005-03-15 22:34:55 +00001725 buf[0] = K_SPECIAL;
1726 buf[1] = KS_EXTRA;
1727 buf[2] = (int)KE_CURSORHOLD;
1728 return 3;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001729 }
1730#endif
Bram Moolenaar702517d2005-06-27 22:34:07 +00001731 before_blocking();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001732 }
1733 }
1734
1735 /*
1736 * Try to read as many characters as there are, until the buffer is full.
1737 */
1738
1739 /* we will get at least one key. Get more if they are available. */
1740 g_fCBrkPressed = FALSE;
1741
1742#ifdef MCH_WRITE_DUMP
1743 if (fdDump)
1744 fputc('[', fdDump);
1745#endif
1746
1747 /* Keep looping until there is something in the typeahead buffer and more
1748 * to get and still room in the buffer (up to two bytes for a char and
1749 * three bytes for a modifier). */
1750 while ((typeaheadlen == 0 || WaitForChar(0L))
1751 && typeaheadlen + 5 <= TYPEAHEADLEN)
1752 {
1753 if (typebuf_changed(tb_change_cnt))
1754 {
1755 /* "buf" may be invalid now if a client put something in the
1756 * typeahead buffer and "buf" is in the typeahead buffer. */
1757 typeaheadlen = 0;
1758 break;
1759 }
1760#ifdef FEAT_MOUSE
1761 if (g_nMouseClick != -1)
1762 {
1763# ifdef MCH_WRITE_DUMP
1764 if (fdDump)
1765 fprintf(fdDump, "{%02x @ %d, %d}",
1766 g_nMouseClick, g_xMouse, g_yMouse);
1767# endif
1768 typeahead[typeaheadlen++] = ESC + 128;
1769 typeahead[typeaheadlen++] = 'M';
1770 typeahead[typeaheadlen++] = g_nMouseClick;
1771 typeahead[typeaheadlen++] = g_xMouse + '!';
1772 typeahead[typeaheadlen++] = g_yMouse + '!';
1773 g_nMouseClick = -1;
1774 }
1775 else
1776#endif
1777 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001778 WCHAR ch2 = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001779 int modifiers = 0;
1780
1781 c = tgetch(&modifiers, &ch2);
1782
1783 if (typebuf_changed(tb_change_cnt))
1784 {
1785 /* "buf" may be invalid now if a client put something in the
1786 * typeahead buffer and "buf" is in the typeahead buffer. */
1787 typeaheadlen = 0;
1788 break;
1789 }
1790
1791 if (c == Ctrl_C && ctrl_c_interrupts)
1792 {
1793#if defined(FEAT_CLIENTSERVER)
1794 trash_input_buf();
1795#endif
1796 got_int = TRUE;
1797 }
1798
1799#ifdef FEAT_MOUSE
1800 if (g_nMouseClick == -1)
1801#endif
1802 {
1803 int n = 1;
Bram Moolenaar45500912014-07-09 20:51:07 +02001804 int conv = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001805
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001806#ifdef FEAT_MBYTE
1807 if (ch2 == NUL)
1808 {
1809 int i;
1810 char_u *p;
1811 WCHAR ch[2];
1812
1813 ch[0] = c;
1814 if (c >= 0xD800 && c <= 0xDBFF) /* High surrogate */
1815 {
1816 ch[1] = tgetch(&modifiers, &ch2);
1817 n++;
1818 }
1819 p = utf16_to_enc(ch, &n);
1820 if (p != NULL)
1821 {
1822 for (i = 0; i < n; i++)
1823 typeahead[typeaheadlen + i] = p[i];
1824 vim_free(p);
1825 }
1826 }
1827 else
1828#endif
1829 typeahead[typeaheadlen] = c;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001830 if (ch2 != NUL)
1831 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001832 typeahead[typeaheadlen + n] = 3;
1833 typeahead[typeaheadlen + n + 1] = (char_u)ch2;
Bram Moolenaar45500912014-07-09 20:51:07 +02001834 n += 2;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001835 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001836
Bram Moolenaar45500912014-07-09 20:51:07 +02001837 if (conv)
1838 {
1839 char_u *p = typeahead + typeaheadlen;
Bram Moolenaar45500912014-07-09 20:51:07 +02001840
Bram Moolenaar1ec4dd42015-01-20 19:39:35 +01001841 if (*p != K_NUL)
Bram Moolenaar45500912014-07-09 20:51:07 +02001842 {
Bram Moolenaar1ec4dd42015-01-20 19:39:35 +01001843 char_u *e = typeahead + TYPEAHEADLEN;
1844
1845 while (*p && p < e)
Bram Moolenaar45500912014-07-09 20:51:07 +02001846 {
Bram Moolenaar1ec4dd42015-01-20 19:39:35 +01001847 if (*p == K_NUL)
1848 {
1849 ++p;
1850 mch_memmove(p + 1, p, ((size_t)(e - p)) - 1);
1851 *p = 3;
1852 ++n;
1853 }
Bram Moolenaar45500912014-07-09 20:51:07 +02001854 ++p;
Bram Moolenaar45500912014-07-09 20:51:07 +02001855 }
Bram Moolenaar45500912014-07-09 20:51:07 +02001856 }
1857 }
1858
Bram Moolenaar071d4272004-06-13 20:20:40 +00001859 /* Use the ALT key to set the 8th bit of the character
1860 * when it's one byte, the 8th bit isn't set yet and not
1861 * using a double-byte encoding (would become a lead
1862 * byte). */
1863 if ((modifiers & MOD_MASK_ALT)
1864 && n == 1
1865 && (typeahead[typeaheadlen] & 0x80) == 0
1866#ifdef FEAT_MBYTE
1867 && !enc_dbcs
1868#endif
1869 )
1870 {
Bram Moolenaar85a3e5c2007-11-20 16:22:16 +00001871#ifdef FEAT_MBYTE
1872 n = (*mb_char2bytes)(typeahead[typeaheadlen] | 0x80,
1873 typeahead + typeaheadlen);
1874#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00001875 typeahead[typeaheadlen] |= 0x80;
Bram Moolenaar85a3e5c2007-11-20 16:22:16 +00001876#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001877 modifiers &= ~MOD_MASK_ALT;
1878 }
1879
1880 if (modifiers != 0)
1881 {
1882 /* Prepend modifiers to the character. */
1883 mch_memmove(typeahead + typeaheadlen + 3,
1884 typeahead + typeaheadlen, n);
1885 typeahead[typeaheadlen++] = K_SPECIAL;
1886 typeahead[typeaheadlen++] = (char_u)KS_MODIFIER;
1887 typeahead[typeaheadlen++] = modifiers;
1888 }
1889
1890 typeaheadlen += n;
1891
1892#ifdef MCH_WRITE_DUMP
1893 if (fdDump)
1894 fputc(c, fdDump);
1895#endif
1896 }
1897 }
1898 }
1899
1900#ifdef MCH_WRITE_DUMP
1901 if (fdDump)
1902 {
1903 fputs("]\n", fdDump);
1904 fflush(fdDump);
1905 }
1906#endif
1907
Bram Moolenaar071d4272004-06-13 20:20:40 +00001908theend:
1909 /* Move typeahead to "buf", as much as fits. */
1910 len = 0;
1911 while (len < maxlen && typeaheadlen > 0)
1912 {
1913 buf[len++] = typeahead[0];
1914 mch_memmove(typeahead, typeahead + 1, --typeaheadlen);
1915 }
1916 return len;
1917
1918#else /* FEAT_GUI_W32 */
1919 return 0;
1920#endif /* FEAT_GUI_W32 */
1921}
1922
Bram Moolenaar82881492012-11-20 16:53:39 +01001923#ifndef PROTO
1924# ifndef __MINGW32__
1925# include <shellapi.h> /* required for FindExecutable() */
1926# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001927#endif
1928
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001929/*
1930 * Return TRUE if "name" is in $PATH.
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00001931 * TODO: Should somehow check if it's really executable.
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001932 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001933 static int
Bram Moolenaarc7f02552014-04-01 21:00:59 +02001934executable_exists(char *name, char_u **path)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001935{
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001936 char *dum;
1937 char fname[_MAX_PATH];
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02001938 char *curpath, *newpath;
1939 long n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001940
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001941#ifdef FEAT_MBYTE
1942 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001943 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01001944 WCHAR *p = enc_to_utf16((char_u *)name, NULL);
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001945 WCHAR fnamew[_MAX_PATH];
1946 WCHAR *dumw;
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02001947 WCHAR *wcurpath, *wnewpath;
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001948
1949 if (p != NULL)
1950 {
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02001951 wcurpath = _wgetenv(L"PATH");
1952 wnewpath = (WCHAR*)alloc((unsigned)(wcslen(wcurpath) + 3)
1953 * sizeof(WCHAR));
1954 if (wnewpath == NULL)
1955 return FALSE;
1956 wcscpy(wnewpath, L".;");
1957 wcscat(wnewpath, wcurpath);
1958 n = (long)SearchPathW(wnewpath, p, NULL, _MAX_PATH, fnamew, &dumw);
1959 vim_free(wnewpath);
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001960 vim_free(p);
1961 if (n > 0 || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
1962 {
1963 if (n == 0)
1964 return FALSE;
1965 if (GetFileAttributesW(fnamew) & FILE_ATTRIBUTE_DIRECTORY)
1966 return FALSE;
Bram Moolenaarc7f02552014-04-01 21:00:59 +02001967 if (path != NULL)
1968 *path = utf16_to_enc(fnamew, NULL);
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001969 return TRUE;
1970 }
1971 /* Retry with non-wide function (for Windows 98). */
1972 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001973 }
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001974#endif
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02001975
1976 curpath = getenv("PATH");
1977 newpath = (char*)alloc((unsigned)(STRLEN(curpath) + 3));
1978 if (newpath == NULL)
1979 return FALSE;
1980 STRCPY(newpath, ".;");
1981 STRCAT(newpath, curpath);
1982 n = (long)SearchPath(newpath, name, NULL, _MAX_PATH, fname, &dum);
1983 vim_free(newpath);
1984 if (n == 0)
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001985 return FALSE;
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01001986 if (mch_isdir((char_u *)fname))
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001987 return FALSE;
Bram Moolenaarc7f02552014-04-01 21:00:59 +02001988 if (path != NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01001989 *path = vim_strsave((char_u *)fname);
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001990 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001991}
1992
Bram Moolenaard32a99a2010-09-21 17:29:23 +02001993#if ((defined(__MINGW32__) || defined (__CYGWIN32__)) && \
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02001994 __MSVCRT_VERSION__ >= 0x800) || (defined(_MSC_VER) && _MSC_VER >= 1400)
Bram Moolenaard32a99a2010-09-21 17:29:23 +02001995/*
1996 * Bad parameter handler.
1997 *
1998 * Certain MS CRT functions will intentionally crash when passed invalid
1999 * parameters to highlight possible security holes. Setting this function as
2000 * the bad parameter handler will prevent the crash.
2001 *
2002 * In debug builds the parameters contain CRT information that might help track
2003 * down the source of a problem, but in non-debug builds the arguments are all
2004 * NULL/0. Debug builds will also produce assert dialogs from the CRT, it is
2005 * worth allowing these to make debugging of issues easier.
2006 */
2007 static void
2008bad_param_handler(const wchar_t *expression,
2009 const wchar_t *function,
2010 const wchar_t *file,
2011 unsigned int line,
2012 uintptr_t pReserved)
2013{
2014}
2015
2016# define SET_INVALID_PARAM_HANDLER \
2017 ((void)_set_invalid_parameter_handler(bad_param_handler))
2018#else
2019# define SET_INVALID_PARAM_HANDLER
2020#endif
2021
Bram Moolenaar071d4272004-06-13 20:20:40 +00002022#ifdef FEAT_GUI_W32
2023
2024/*
2025 * GUI version of mch_init().
2026 */
2027 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002028mch_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002029{
2030#ifndef __MINGW32__
2031 extern int _fmode;
2032#endif
2033
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002034 /* Silently handle invalid parameters to CRT functions */
2035 SET_INVALID_PARAM_HANDLER;
2036
Bram Moolenaar071d4272004-06-13 20:20:40 +00002037 /* Let critical errors result in a failure, not in a dialog box. Required
2038 * for the timestamp test to work on removed floppies. */
2039 SetErrorMode(SEM_FAILCRITICALERRORS);
2040
2041 _fmode = O_BINARY; /* we do our own CR-LF translation */
2042
2043 /* Specify window size. Is there a place to get the default from? */
2044 Rows = 25;
2045 Columns = 80;
2046
2047 /* Look for 'vimrun' */
2048 if (!gui_is_win32s())
2049 {
2050 char_u vimrun_location[_MAX_PATH + 4];
2051
2052 /* First try in same directory as gvim.exe */
2053 STRCPY(vimrun_location, exe_name);
2054 STRCPY(gettail(vimrun_location), "vimrun.exe");
2055 if (mch_getperm(vimrun_location) >= 0)
2056 {
2057 if (*skiptowhite(vimrun_location) != NUL)
2058 {
2059 /* Enclose path with white space in double quotes. */
2060 mch_memmove(vimrun_location + 1, vimrun_location,
2061 STRLEN(vimrun_location) + 1);
2062 *vimrun_location = '"';
2063 STRCPY(gettail(vimrun_location), "vimrun\" ");
2064 }
2065 else
2066 STRCPY(gettail(vimrun_location), "vimrun ");
2067
2068 vimrun_path = (char *)vim_strsave(vimrun_location);
2069 s_dont_use_vimrun = FALSE;
2070 }
Bram Moolenaarc7f02552014-04-01 21:00:59 +02002071 else if (executable_exists("vimrun.exe", NULL))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002072 s_dont_use_vimrun = FALSE;
2073
2074 /* Don't give the warning for a missing vimrun.exe right now, but only
2075 * when vimrun was supposed to be used. Don't bother people that do
2076 * not need vimrun.exe. */
2077 if (s_dont_use_vimrun)
2078 need_vimrun_warning = TRUE;
2079 }
2080
2081 /*
2082 * If "finstr.exe" doesn't exist, use "grep -n" for 'grepprg'.
2083 * Otherwise the default "findstr /n" is used.
2084 */
Bram Moolenaarc7f02552014-04-01 21:00:59 +02002085 if (!executable_exists("findstr.exe", NULL))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002086 set_option_value((char_u *)"grepprg", 0, (char_u *)"grep -n", 0);
2087
2088#ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01002089 win_clip_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002090#endif
2091}
2092
2093
2094#else /* FEAT_GUI_W32 */
2095
2096#define SRWIDTH(sr) ((sr).Right - (sr).Left + 1)
2097#define SRHEIGHT(sr) ((sr).Bottom - (sr).Top + 1)
2098
2099/*
2100 * ClearConsoleBuffer()
2101 * Description:
2102 * Clears the entire contents of the console screen buffer, using the
2103 * specified attribute.
2104 * Returns:
2105 * TRUE on success
2106 */
2107 static BOOL
2108ClearConsoleBuffer(WORD wAttribute)
2109{
2110 CONSOLE_SCREEN_BUFFER_INFO csbi;
2111 COORD coord;
2112 DWORD NumCells, dummy;
2113
2114 if (!GetConsoleScreenBufferInfo(g_hConOut, &csbi))
2115 return FALSE;
2116
2117 NumCells = csbi.dwSize.X * csbi.dwSize.Y;
2118 coord.X = 0;
2119 coord.Y = 0;
2120 if (!FillConsoleOutputCharacter(g_hConOut, ' ', NumCells,
2121 coord, &dummy))
2122 {
2123 return FALSE;
2124 }
2125 if (!FillConsoleOutputAttribute(g_hConOut, wAttribute, NumCells,
2126 coord, &dummy))
2127 {
2128 return FALSE;
2129 }
2130
2131 return TRUE;
2132}
2133
2134/*
2135 * FitConsoleWindow()
2136 * Description:
2137 * Checks if the console window will fit within given buffer dimensions.
2138 * Also, if requested, will shrink the window to fit.
2139 * Returns:
2140 * TRUE on success
2141 */
2142 static BOOL
2143FitConsoleWindow(
2144 COORD dwBufferSize,
2145 BOOL WantAdjust)
2146{
2147 CONSOLE_SCREEN_BUFFER_INFO csbi;
2148 COORD dwWindowSize;
2149 BOOL NeedAdjust = FALSE;
2150
2151 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
2152 {
2153 /*
2154 * A buffer resize will fail if the current console window does
2155 * not lie completely within that buffer. To avoid this, we might
2156 * have to move and possibly shrink the window.
2157 */
2158 if (csbi.srWindow.Right >= dwBufferSize.X)
2159 {
2160 dwWindowSize.X = SRWIDTH(csbi.srWindow);
2161 if (dwWindowSize.X > dwBufferSize.X)
2162 dwWindowSize.X = dwBufferSize.X;
2163 csbi.srWindow.Right = dwBufferSize.X - 1;
2164 csbi.srWindow.Left = dwBufferSize.X - dwWindowSize.X;
2165 NeedAdjust = TRUE;
2166 }
2167 if (csbi.srWindow.Bottom >= dwBufferSize.Y)
2168 {
2169 dwWindowSize.Y = SRHEIGHT(csbi.srWindow);
2170 if (dwWindowSize.Y > dwBufferSize.Y)
2171 dwWindowSize.Y = dwBufferSize.Y;
2172 csbi.srWindow.Bottom = dwBufferSize.Y - 1;
2173 csbi.srWindow.Top = dwBufferSize.Y - dwWindowSize.Y;
2174 NeedAdjust = TRUE;
2175 }
2176 if (NeedAdjust && WantAdjust)
2177 {
2178 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &csbi.srWindow))
2179 return FALSE;
2180 }
2181 return TRUE;
2182 }
2183
2184 return FALSE;
2185}
2186
2187typedef struct ConsoleBufferStruct
2188{
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002189 BOOL IsValid;
2190 CONSOLE_SCREEN_BUFFER_INFO Info;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002191 PCHAR_INFO Buffer;
2192 COORD BufferSize;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002193} ConsoleBuffer;
2194
2195/*
2196 * SaveConsoleBuffer()
2197 * Description:
2198 * Saves important information about the console buffer, including the
2199 * actual buffer contents. The saved information is suitable for later
2200 * restoration by RestoreConsoleBuffer().
2201 * Returns:
2202 * TRUE if all information was saved; FALSE otherwise
2203 * If FALSE, still sets cb->IsValid if buffer characteristics were saved.
2204 */
2205 static BOOL
2206SaveConsoleBuffer(
2207 ConsoleBuffer *cb)
2208{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002209 DWORD NumCells;
2210 COORD BufferCoord;
2211 SMALL_RECT ReadRegion;
2212 WORD Y, Y_incr;
2213
Bram Moolenaar071d4272004-06-13 20:20:40 +00002214 if (cb == NULL)
2215 return FALSE;
2216
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002217 if (!GetConsoleScreenBufferInfo(g_hConOut, &cb->Info))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002218 {
2219 cb->IsValid = FALSE;
2220 return FALSE;
2221 }
2222 cb->IsValid = TRUE;
2223
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002224 /*
2225 * Allocate a buffer large enough to hold the entire console screen
2226 * buffer. If this ConsoleBuffer structure has already been initialized
2227 * with a buffer of the correct size, then just use that one.
2228 */
2229 if (!cb->IsValid || cb->Buffer == NULL ||
2230 cb->BufferSize.X != cb->Info.dwSize.X ||
2231 cb->BufferSize.Y != cb->Info.dwSize.Y)
2232 {
2233 cb->BufferSize.X = cb->Info.dwSize.X;
2234 cb->BufferSize.Y = cb->Info.dwSize.Y;
2235 NumCells = cb->BufferSize.X * cb->BufferSize.Y;
2236 vim_free(cb->Buffer);
2237 cb->Buffer = (PCHAR_INFO)alloc(NumCells * sizeof(CHAR_INFO));
2238 if (cb->Buffer == NULL)
2239 return FALSE;
2240 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002241
2242 /*
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002243 * We will now copy the console screen buffer into our buffer.
2244 * ReadConsoleOutput() seems to be limited as far as how much you
2245 * can read at a time. Empirically, this number seems to be about
2246 * 12000 cells (rows * columns). Start at position (0, 0) and copy
2247 * in chunks until it is all copied. The chunks will all have the
2248 * same horizontal characteristics, so initialize them now. The
2249 * height of each chunk will be (12000 / width).
Bram Moolenaar071d4272004-06-13 20:20:40 +00002250 */
Bram Moolenaar61594242015-09-01 20:23:37 +02002251 BufferCoord.X = 0;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002252 ReadRegion.Left = 0;
2253 ReadRegion.Right = cb->Info.dwSize.X - 1;
2254 Y_incr = 12000 / cb->Info.dwSize.X;
2255 for (Y = 0; Y < cb->BufferSize.Y; Y += Y_incr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002256 {
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002257 /*
2258 * Read into position (0, Y) in our buffer.
2259 */
2260 BufferCoord.Y = Y;
2261 /*
2262 * Read the region whose top left corner is (0, Y) and whose bottom
2263 * right corner is (width - 1, Y + Y_incr - 1). This should define
2264 * a region of size width by Y_incr. Don't worry if this region is
2265 * too large for the remaining buffer; it will be cropped.
2266 */
2267 ReadRegion.Top = Y;
2268 ReadRegion.Bottom = Y + Y_incr - 1;
2269 if (!ReadConsoleOutput(g_hConOut, /* output handle */
2270 cb->Buffer, /* our buffer */
2271 cb->BufferSize, /* dimensions of our buffer */
2272 BufferCoord, /* offset in our buffer */
2273 &ReadRegion)) /* region to save */
2274 {
2275 vim_free(cb->Buffer);
2276 cb->Buffer = NULL;
2277 return FALSE;
2278 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002279 }
2280
2281 return TRUE;
2282}
2283
2284/*
2285 * RestoreConsoleBuffer()
2286 * Description:
2287 * Restores important information about the console buffer, including the
2288 * actual buffer contents, if desired. The information to restore is in
2289 * the same format used by SaveConsoleBuffer().
2290 * Returns:
2291 * TRUE on success
2292 */
2293 static BOOL
2294RestoreConsoleBuffer(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002295 ConsoleBuffer *cb,
2296 BOOL RestoreScreen)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002297{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002298 COORD BufferCoord;
2299 SMALL_RECT WriteRegion;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002300
2301 if (cb == NULL || !cb->IsValid)
2302 return FALSE;
2303
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002304 /*
2305 * Before restoring the buffer contents, clear the current buffer, and
2306 * restore the cursor position and window information. Doing this now
2307 * prevents old buffer contents from "flashing" onto the screen.
2308 */
2309 if (RestoreScreen)
2310 ClearConsoleBuffer(cb->Info.wAttributes);
2311
2312 FitConsoleWindow(cb->Info.dwSize, TRUE);
2313 if (!SetConsoleScreenBufferSize(g_hConOut, cb->Info.dwSize))
2314 return FALSE;
2315 if (!SetConsoleTextAttribute(g_hConOut, cb->Info.wAttributes))
2316 return FALSE;
2317
2318 if (!RestoreScreen)
2319 {
2320 /*
2321 * No need to restore the screen buffer contents, so we're done.
2322 */
2323 return TRUE;
2324 }
2325
2326 if (!SetConsoleCursorPosition(g_hConOut, cb->Info.dwCursorPosition))
2327 return FALSE;
2328 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &cb->Info.srWindow))
2329 return FALSE;
2330
2331 /*
2332 * Restore the screen buffer contents.
2333 */
2334 if (cb->Buffer != NULL)
2335 {
2336 BufferCoord.X = 0;
2337 BufferCoord.Y = 0;
2338 WriteRegion.Left = 0;
2339 WriteRegion.Top = 0;
2340 WriteRegion.Right = cb->Info.dwSize.X - 1;
2341 WriteRegion.Bottom = cb->Info.dwSize.Y - 1;
2342 if (!WriteConsoleOutput(g_hConOut, /* output handle */
2343 cb->Buffer, /* our buffer */
2344 cb->BufferSize, /* dimensions of our buffer */
2345 BufferCoord, /* offset in our buffer */
2346 &WriteRegion)) /* region to restore */
2347 {
2348 return FALSE;
2349 }
2350 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002351
2352 return TRUE;
2353}
2354
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002355#define FEAT_RESTORE_ORIG_SCREEN
2356#ifdef FEAT_RESTORE_ORIG_SCREEN
2357static ConsoleBuffer g_cbOrig = { 0 };
2358#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002359static ConsoleBuffer g_cbNonTermcap = { 0 };
2360static ConsoleBuffer g_cbTermcap = { 0 };
2361
2362#ifdef FEAT_TITLE
2363#ifdef __BORLANDC__
2364typedef HWND (__stdcall *GETCONSOLEWINDOWPROC)(VOID);
2365#else
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002366typedef HWND (WINAPI *GETCONSOLEWINDOWPROC)(VOID);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002367#endif
2368char g_szOrigTitle[256] = { 0 };
2369HWND g_hWnd = NULL; /* also used in os_mswin.c */
2370static HICON g_hOrigIconSmall = NULL;
2371static HICON g_hOrigIcon = NULL;
2372static HICON g_hVimIcon = NULL;
2373static BOOL g_fCanChangeIcon = FALSE;
2374
2375/* ICON* are not defined in VC++ 4.0 */
2376#ifndef ICON_SMALL
2377#define ICON_SMALL 0
2378#endif
2379#ifndef ICON_BIG
2380#define ICON_BIG 1
2381#endif
2382/*
2383 * GetConsoleIcon()
2384 * Description:
2385 * Attempts to retrieve the small icon and/or the big icon currently in
2386 * use by a given window.
2387 * Returns:
2388 * TRUE on success
2389 */
2390 static BOOL
2391GetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002392 HWND hWnd,
2393 HICON *phIconSmall,
2394 HICON *phIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002395{
2396 if (hWnd == NULL)
2397 return FALSE;
2398
2399 if (phIconSmall != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002400 *phIconSmall = (HICON)SendMessage(hWnd, WM_GETICON,
2401 (WPARAM)ICON_SMALL, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002402 if (phIcon != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002403 *phIcon = (HICON)SendMessage(hWnd, WM_GETICON,
2404 (WPARAM)ICON_BIG, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002405 return TRUE;
2406}
2407
2408/*
2409 * SetConsoleIcon()
2410 * Description:
2411 * Attempts to change the small icon and/or the big icon currently in
2412 * use by a given window.
2413 * Returns:
2414 * TRUE on success
2415 */
2416 static BOOL
2417SetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002418 HWND hWnd,
2419 HICON hIconSmall,
2420 HICON hIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002421{
Bram Moolenaar071d4272004-06-13 20:20:40 +00002422 if (hWnd == NULL)
2423 return FALSE;
2424
2425 if (hIconSmall != NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002426 SendMessage(hWnd, WM_SETICON,
2427 (WPARAM)ICON_SMALL, (LPARAM)hIconSmall);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002428 if (hIcon != NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002429 SendMessage(hWnd, WM_SETICON,
2430 (WPARAM)ICON_BIG, (LPARAM) hIcon);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002431 return TRUE;
2432}
2433
2434/*
2435 * SaveConsoleTitleAndIcon()
2436 * Description:
2437 * Saves the current console window title in g_szOrigTitle, for later
2438 * restoration. Also, attempts to obtain a handle to the console window,
2439 * and use it to save the small and big icons currently in use by the
2440 * console window. This is not always possible on some versions of Windows;
2441 * nor is it possible when running Vim remotely using Telnet (since the
2442 * console window the user sees is owned by a remote process).
2443 */
2444 static void
2445SaveConsoleTitleAndIcon(void)
2446{
2447 GETCONSOLEWINDOWPROC GetConsoleWindowProc;
2448
2449 /* Save the original title. */
2450 if (!GetConsoleTitle(g_szOrigTitle, sizeof(g_szOrigTitle)))
2451 return;
2452
2453 /*
2454 * Obtain a handle to the console window using GetConsoleWindow() from
2455 * KERNEL32.DLL; we need to handle in order to change the window icon.
2456 * This function only exists on NT-based Windows, starting with Windows
2457 * 2000. On older operating systems, we can't change the window icon
2458 * anyway.
2459 */
2460 if ((GetConsoleWindowProc = (GETCONSOLEWINDOWPROC)
2461 GetProcAddress(GetModuleHandle("KERNEL32.DLL"),
2462 "GetConsoleWindow")) != NULL)
2463 {
2464 g_hWnd = (*GetConsoleWindowProc)();
2465 }
2466 if (g_hWnd == NULL)
2467 return;
2468
2469 /* Save the original console window icon. */
2470 GetConsoleIcon(g_hWnd, &g_hOrigIconSmall, &g_hOrigIcon);
2471 if (g_hOrigIconSmall == NULL || g_hOrigIcon == NULL)
2472 return;
2473
2474 /* Extract the first icon contained in the Vim executable. */
Bram Moolenaarcddc91c2014-09-23 21:53:41 +02002475 if (mch_icon_load((HANDLE *)&g_hVimIcon) == FAIL || g_hVimIcon == NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002476 g_hVimIcon = ExtractIcon(NULL, (LPCSTR)exe_name, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002477 if (g_hVimIcon != NULL)
2478 g_fCanChangeIcon = TRUE;
2479}
2480#endif
2481
2482static int g_fWindInitCalled = FALSE;
2483static int g_fTermcapMode = FALSE;
2484static CONSOLE_CURSOR_INFO g_cci;
2485static DWORD g_cmodein = 0;
2486static DWORD g_cmodeout = 0;
2487
2488/*
2489 * non-GUI version of mch_init().
2490 */
2491 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002492mch_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002493{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002494#ifndef FEAT_RESTORE_ORIG_SCREEN
2495 CONSOLE_SCREEN_BUFFER_INFO csbi;
2496#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002497#ifndef __MINGW32__
2498 extern int _fmode;
2499#endif
2500
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002501 /* Silently handle invalid parameters to CRT functions */
2502 SET_INVALID_PARAM_HANDLER;
2503
Bram Moolenaar071d4272004-06-13 20:20:40 +00002504 /* Let critical errors result in a failure, not in a dialog box. Required
2505 * for the timestamp test to work on removed floppies. */
2506 SetErrorMode(SEM_FAILCRITICALERRORS);
2507
2508 _fmode = O_BINARY; /* we do our own CR-LF translation */
2509 out_flush();
2510
2511 /* Obtain handles for the standard Console I/O devices */
2512 if (read_cmd_fd == 0)
2513 g_hConIn = GetStdHandle(STD_INPUT_HANDLE);
2514 else
2515 create_conin();
2516 g_hConOut = GetStdHandle(STD_OUTPUT_HANDLE);
2517
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002518#ifdef FEAT_RESTORE_ORIG_SCREEN
2519 /* Save the initial console buffer for later restoration */
2520 SaveConsoleBuffer(&g_cbOrig);
2521 g_attrCurrent = g_attrDefault = g_cbOrig.Info.wAttributes;
2522#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00002523 /* Get current text attributes */
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002524 GetConsoleScreenBufferInfo(g_hConOut, &csbi);
2525 g_attrCurrent = g_attrDefault = csbi.wAttributes;
2526#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002527 if (cterm_normal_fg_color == 0)
2528 cterm_normal_fg_color = (g_attrCurrent & 0xf) + 1;
2529 if (cterm_normal_bg_color == 0)
2530 cterm_normal_bg_color = ((g_attrCurrent >> 4) & 0xf) + 1;
2531
2532 /* set termcap codes to current text attributes */
2533 update_tcap(g_attrCurrent);
2534
2535 GetConsoleCursorInfo(g_hConOut, &g_cci);
2536 GetConsoleMode(g_hConIn, &g_cmodein);
2537 GetConsoleMode(g_hConOut, &g_cmodeout);
2538
2539#ifdef FEAT_TITLE
2540 SaveConsoleTitleAndIcon();
2541 /*
2542 * Set both the small and big icons of the console window to Vim's icon.
2543 * Note that Vim presently only has one size of icon (32x32), but it
2544 * automatically gets scaled down to 16x16 when setting the small icon.
2545 */
2546 if (g_fCanChangeIcon)
2547 SetConsoleIcon(g_hWnd, g_hVimIcon, g_hVimIcon);
2548#endif
2549
2550 ui_get_shellsize();
2551
2552#ifdef MCH_WRITE_DUMP
2553 fdDump = fopen("dump", "wt");
2554
2555 if (fdDump)
2556 {
2557 time_t t;
2558
2559 time(&t);
2560 fputs(ctime(&t), fdDump);
2561 fflush(fdDump);
2562 }
2563#endif
2564
2565 g_fWindInitCalled = TRUE;
2566
2567#ifdef FEAT_MOUSE
2568 g_fMouseAvail = GetSystemMetrics(SM_MOUSEPRESENT);
2569#endif
2570
2571#ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01002572 win_clip_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002573#endif
2574
2575 /* This will be NULL on anything but NT 4.0 */
2576 s_pfnGetConsoleKeyboardLayoutName =
2577 (PFNGCKLN) GetProcAddress(GetModuleHandle("kernel32.dll"),
2578 "GetConsoleKeyboardLayoutNameA");
2579}
2580
2581/*
2582 * non-GUI version of mch_exit().
2583 * Shut down and exit with status `r'
2584 * Careful: mch_exit() may be called before mch_init()!
2585 */
2586 void
2587mch_exit(int r)
2588{
2589 stoptermcap();
2590
2591 if (g_fWindInitCalled)
2592 settmode(TMODE_COOK);
2593
2594 ml_close_all(TRUE); /* remove all memfiles */
2595
2596 if (g_fWindInitCalled)
2597 {
2598#ifdef FEAT_TITLE
2599 mch_restore_title(3);
2600 /*
2601 * Restore both the small and big icons of the console window to
2602 * what they were at startup. Don't do this when the window is
2603 * closed, Vim would hang here.
2604 */
2605 if (g_fCanChangeIcon && !g_fForceExit)
2606 SetConsoleIcon(g_hWnd, g_hOrigIconSmall, g_hOrigIcon);
2607#endif
2608
2609#ifdef MCH_WRITE_DUMP
2610 if (fdDump)
2611 {
2612 time_t t;
2613
2614 time(&t);
2615 fputs(ctime(&t), fdDump);
2616 fclose(fdDump);
2617 }
2618 fdDump = NULL;
2619#endif
2620 }
2621
2622 SetConsoleCursorInfo(g_hConOut, &g_cci);
2623 SetConsoleMode(g_hConIn, g_cmodein);
2624 SetConsoleMode(g_hConOut, g_cmodeout);
2625
2626#ifdef DYNAMIC_GETTEXT
2627 dyn_libintl_end();
2628#endif
2629
2630 exit(r);
2631}
2632#endif /* !FEAT_GUI_W32 */
2633
Bram Moolenaar071d4272004-06-13 20:20:40 +00002634/*
2635 * Do we have an interactive window?
2636 */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00002637/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00002638 int
2639mch_check_win(
2640 int argc,
2641 char **argv)
2642{
2643 get_exe_name();
2644
2645#ifdef FEAT_GUI_W32
2646 return OK; /* GUI always has a tty */
2647#else
2648 if (isatty(1))
2649 return OK;
2650 return FAIL;
2651#endif
2652}
2653
2654
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002655#ifdef FEAT_MBYTE
2656/*
2657 * fname_casew(): Wide version of fname_case(). Set the case of the file name,
2658 * if it already exists. When "len" is > 0, also expand short to long
2659 * filenames.
2660 * Return FAIL if wide functions are not available, OK otherwise.
2661 * NOTE: much of this is identical to fname_case(), keep in sync!
2662 */
2663 static int
2664fname_casew(
2665 WCHAR *name,
2666 int len)
2667{
2668 WCHAR szTrueName[_MAX_PATH + 2];
2669 WCHAR szTrueNameTemp[_MAX_PATH + 2];
2670 WCHAR *ptrue, *ptruePrev;
2671 WCHAR *porig, *porigPrev;
2672 int flen;
2673 WIN32_FIND_DATAW fb;
Bram Moolenaar73c61632013-12-07 14:48:10 +01002674 HANDLE hFind = INVALID_HANDLE_VALUE;
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002675 int c;
2676 int slen;
2677
2678 flen = (int)wcslen(name);
2679 if (flen > _MAX_PATH)
2680 return OK;
2681
2682 /* slash_adjust(name) not needed, already adjusted by fname_case(). */
2683
2684 /* Build the new name in szTrueName[] one component at a time. */
2685 porig = name;
2686 ptrue = szTrueName;
2687
2688 if (iswalpha(porig[0]) && porig[1] == L':')
2689 {
2690 /* copy leading drive letter */
2691 *ptrue++ = *porig++;
2692 *ptrue++ = *porig++;
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002693 }
Bram Moolenaar73c61632013-12-07 14:48:10 +01002694 *ptrue = NUL; /* in case nothing follows */
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002695
2696 while (*porig != NUL)
2697 {
2698 /* copy \ characters */
2699 while (*porig == psepc)
2700 *ptrue++ = *porig++;
2701
2702 ptruePrev = ptrue;
2703 porigPrev = porig;
2704 while (*porig != NUL && *porig != psepc)
2705 {
2706 *ptrue++ = *porig++;
2707 }
2708 *ptrue = NUL;
2709
2710 /* To avoid a slow failure append "\*" when searching a directory,
2711 * server or network share. */
2712 wcscpy(szTrueNameTemp, szTrueName);
2713 slen = (int)wcslen(szTrueNameTemp);
2714 if (*porig == psepc && slen + 2 < _MAX_PATH)
2715 wcscpy(szTrueNameTemp + slen, L"\\*");
2716
2717 /* Skip "", "." and "..". */
2718 if (ptrue > ptruePrev
2719 && (ptruePrev[0] != L'.'
2720 || (ptruePrev[1] != NUL
2721 && (ptruePrev[1] != L'.' || ptruePrev[2] != NUL)))
2722 && (hFind = FindFirstFileW(szTrueNameTemp, &fb))
2723 != INVALID_HANDLE_VALUE)
2724 {
2725 c = *porig;
2726 *porig = NUL;
2727
2728 /* Only use the match when it's the same name (ignoring case) or
2729 * expansion is allowed and there is a match with the short name
2730 * and there is enough room. */
2731 if (_wcsicoll(porigPrev, fb.cFileName) == 0
2732 || (len > 0
2733 && (_wcsicoll(porigPrev, fb.cAlternateFileName) == 0
2734 && (int)(ptruePrev - szTrueName)
2735 + (int)wcslen(fb.cFileName) < len)))
2736 {
2737 wcscpy(ptruePrev, fb.cFileName);
2738
2739 /* Look for exact match and prefer it if found. Must be a
2740 * long name, otherwise there would be only one match. */
2741 while (FindNextFileW(hFind, &fb))
2742 {
2743 if (*fb.cAlternateFileName != NUL
2744 && (wcscoll(porigPrev, fb.cFileName) == 0
2745 || (len > 0
2746 && (_wcsicoll(porigPrev,
2747 fb.cAlternateFileName) == 0
2748 && (int)(ptruePrev - szTrueName)
2749 + (int)wcslen(fb.cFileName) < len))))
2750 {
2751 wcscpy(ptruePrev, fb.cFileName);
2752 break;
2753 }
2754 }
2755 }
2756 FindClose(hFind);
2757 *porig = c;
2758 ptrue = ptruePrev + wcslen(ptruePrev);
2759 }
2760 else if (hFind == INVALID_HANDLE_VALUE
2761 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
2762 return FAIL;
2763 }
2764
2765 wcscpy(name, szTrueName);
2766 return OK;
2767}
2768#endif
2769
Bram Moolenaar071d4272004-06-13 20:20:40 +00002770/*
2771 * fname_case(): Set the case of the file name, if it already exists.
2772 * When "len" is > 0, also expand short to long filenames.
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002773 * NOTE: much of this is identical to fname_casew(), keep in sync!
Bram Moolenaar071d4272004-06-13 20:20:40 +00002774 */
2775 void
2776fname_case(
2777 char_u *name,
2778 int len)
2779{
2780 char szTrueName[_MAX_PATH + 2];
Bram Moolenaar464c9252010-10-13 20:37:41 +02002781 char szTrueNameTemp[_MAX_PATH + 2];
Bram Moolenaar071d4272004-06-13 20:20:40 +00002782 char *ptrue, *ptruePrev;
2783 char *porig, *porigPrev;
2784 int flen;
2785 WIN32_FIND_DATA fb;
2786 HANDLE hFind;
2787 int c;
Bram Moolenaar464c9252010-10-13 20:37:41 +02002788 int slen;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002789
Bram Moolenaara3ffd9c2005-07-21 21:03:15 +00002790 flen = (int)STRLEN(name);
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002791 if (flen == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002792 return;
2793
2794 slash_adjust(name);
2795
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002796#ifdef FEAT_MBYTE
2797 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2798 {
2799 WCHAR *p = enc_to_utf16(name, NULL);
2800
2801 if (p != NULL)
2802 {
2803 char_u *q;
Bram Moolenaar21d89b62014-10-07 10:38:40 +02002804 WCHAR buf[_MAX_PATH + 1];
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002805
Bram Moolenaar21d89b62014-10-07 10:38:40 +02002806 wcsncpy(buf, p, _MAX_PATH);
2807 buf[_MAX_PATH] = L'\0';
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002808 vim_free(p);
2809
2810 if (fname_casew(buf, (len > 0) ? _MAX_PATH : 0) == OK)
2811 {
2812 q = utf16_to_enc(buf, NULL);
2813 if (q != NULL)
2814 {
2815 vim_strncpy(name, q, (len > 0) ? len - 1 : flen);
2816 vim_free(q);
2817 return;
2818 }
2819 }
2820 }
2821 /* Retry with non-wide function (for Windows 98). */
2822 }
2823#endif
2824
2825 /* If 'enc' is utf-8, flen can be larger than _MAX_PATH.
2826 * So we should check this after calling wide function. */
2827 if (flen > _MAX_PATH)
2828 return;
2829
Bram Moolenaar071d4272004-06-13 20:20:40 +00002830 /* Build the new name in szTrueName[] one component at a time. */
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002831 porig = (char *)name;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002832 ptrue = szTrueName;
2833
2834 if (isalpha(porig[0]) && porig[1] == ':')
2835 {
2836 /* copy leading drive letter */
2837 *ptrue++ = *porig++;
2838 *ptrue++ = *porig++;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002839 }
Bram Moolenaar73c61632013-12-07 14:48:10 +01002840 *ptrue = NUL; /* in case nothing follows */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002841
2842 while (*porig != NUL)
2843 {
2844 /* copy \ characters */
2845 while (*porig == psepc)
2846 *ptrue++ = *porig++;
2847
2848 ptruePrev = ptrue;
2849 porigPrev = porig;
2850 while (*porig != NUL && *porig != psepc)
2851 {
2852#ifdef FEAT_MBYTE
2853 int l;
2854
2855 if (enc_dbcs)
2856 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002857 l = (*mb_ptr2len)((char_u *)porig);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002858 while (--l >= 0)
2859 *ptrue++ = *porig++;
2860 }
2861 else
2862#endif
2863 *ptrue++ = *porig++;
2864 }
2865 *ptrue = NUL;
2866
Bram Moolenaar464c9252010-10-13 20:37:41 +02002867 /* To avoid a slow failure append "\*" when searching a directory,
2868 * server or network share. */
2869 STRCPY(szTrueNameTemp, szTrueName);
Bram Moolenaar6b5ef062010-10-27 12:18:00 +02002870 slen = (int)strlen(szTrueNameTemp);
Bram Moolenaar464c9252010-10-13 20:37:41 +02002871 if (*porig == psepc && slen + 2 < _MAX_PATH)
2872 STRCPY(szTrueNameTemp + slen, "\\*");
2873
Bram Moolenaar071d4272004-06-13 20:20:40 +00002874 /* Skip "", "." and "..". */
2875 if (ptrue > ptruePrev
2876 && (ptruePrev[0] != '.'
2877 || (ptruePrev[1] != NUL
2878 && (ptruePrev[1] != '.' || ptruePrev[2] != NUL)))
Bram Moolenaar464c9252010-10-13 20:37:41 +02002879 && (hFind = FindFirstFile(szTrueNameTemp, &fb))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002880 != INVALID_HANDLE_VALUE)
2881 {
2882 c = *porig;
2883 *porig = NUL;
2884
2885 /* Only use the match when it's the same name (ignoring case) or
2886 * expansion is allowed and there is a match with the short name
2887 * and there is enough room. */
2888 if (_stricoll(porigPrev, fb.cFileName) == 0
2889 || (len > 0
2890 && (_stricoll(porigPrev, fb.cAlternateFileName) == 0
2891 && (int)(ptruePrev - szTrueName)
2892 + (int)strlen(fb.cFileName) < len)))
2893 {
2894 STRCPY(ptruePrev, fb.cFileName);
2895
2896 /* Look for exact match and prefer it if found. Must be a
2897 * long name, otherwise there would be only one match. */
2898 while (FindNextFile(hFind, &fb))
2899 {
2900 if (*fb.cAlternateFileName != NUL
2901 && (strcoll(porigPrev, fb.cFileName) == 0
2902 || (len > 0
2903 && (_stricoll(porigPrev,
2904 fb.cAlternateFileName) == 0
2905 && (int)(ptruePrev - szTrueName)
2906 + (int)strlen(fb.cFileName) < len))))
2907 {
2908 STRCPY(ptruePrev, fb.cFileName);
2909 break;
2910 }
2911 }
2912 }
2913 FindClose(hFind);
2914 *porig = c;
2915 ptrue = ptruePrev + strlen(ptruePrev);
2916 }
2917 }
2918
2919 STRCPY(name, szTrueName);
2920}
2921
2922
2923/*
2924 * Insert user name in s[len].
2925 */
2926 int
2927mch_get_user_name(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002928 char_u *s,
2929 int len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002930{
Bram Moolenaar41a09032007-10-01 18:34:34 +00002931 char szUserName[256 + 1]; /* UNLEN is 256 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002932 DWORD cch = sizeof szUserName;
2933
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01002934#ifdef FEAT_MBYTE
2935 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2936 {
2937 WCHAR wszUserName[256 + 1]; /* UNLEN is 256 */
2938 DWORD wcch = sizeof(wszUserName) / sizeof(WCHAR);
2939
2940 if (GetUserNameW(wszUserName, &wcch))
2941 {
2942 char_u *p = utf16_to_enc(wszUserName, NULL);
2943
2944 if (p != NULL)
2945 {
2946 vim_strncpy(s, p, len - 1);
2947 vim_free(p);
2948 return OK;
2949 }
2950 }
Bram Moolenaarcd981f22014-02-11 17:06:00 +01002951 else if (GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
2952 return FAIL;
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01002953 /* Retry with non-wide function (for Windows 98). */
2954 }
2955#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002956 if (GetUserName(szUserName, &cch))
2957 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002958 vim_strncpy(s, (char_u *)szUserName, len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002959 return OK;
2960 }
2961 s[0] = NUL;
2962 return FAIL;
2963}
2964
2965
2966/*
2967 * Insert host name in s[len].
2968 */
2969 void
2970mch_get_host_name(
2971 char_u *s,
2972 int len)
2973{
2974 DWORD cch = len;
2975
Bram Moolenaar2cc87382013-12-11 18:21:45 +01002976#ifdef FEAT_MBYTE
2977 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2978 {
2979 WCHAR wszHostName[256 + 1];
2980 DWORD wcch = sizeof(wszHostName) / sizeof(WCHAR);
2981
2982 if (GetComputerNameW(wszHostName, &wcch))
2983 {
2984 char_u *p = utf16_to_enc(wszHostName, NULL);
2985
2986 if (p != NULL)
2987 {
2988 vim_strncpy(s, p, len - 1);
2989 vim_free(p);
2990 return;
2991 }
2992 }
Bram Moolenaarcd981f22014-02-11 17:06:00 +01002993 else if (GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
2994 return;
Bram Moolenaar2cc87382013-12-11 18:21:45 +01002995 /* Retry with non-wide function (for Windows 98). */
2996 }
2997#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002998 if (!GetComputerName((LPSTR)s, &cch))
2999 vim_strncpy(s, (char_u *)"PC (Win32 Vim)", len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003000}
3001
3002
3003/*
3004 * return process ID
3005 */
3006 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003007mch_get_pid(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003008{
3009 return (long)GetCurrentProcessId();
3010}
3011
3012
3013/*
3014 * Get name of current directory into buffer 'buf' of length 'len' bytes.
3015 * Return OK for success, FAIL for failure.
3016 */
3017 int
3018mch_dirname(
3019 char_u *buf,
3020 int len)
3021{
3022 /*
3023 * Originally this was:
3024 * return (getcwd(buf, len) != NULL ? OK : FAIL);
3025 * But the Win32s known bug list says that getcwd() doesn't work
3026 * so use the Win32 system call instead. <Negri>
3027 */
3028#ifdef FEAT_MBYTE
3029 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3030 {
3031 WCHAR wbuf[_MAX_PATH + 1];
3032
3033 if (GetCurrentDirectoryW(_MAX_PATH, wbuf) != 0)
3034 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00003035 char_u *p = utf16_to_enc(wbuf, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003036
3037 if (p != NULL)
3038 {
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00003039 vim_strncpy(buf, p, len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003040 vim_free(p);
3041 return OK;
3042 }
3043 }
Bram Moolenaarcd981f22014-02-11 17:06:00 +01003044 else if (GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
3045 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003046 /* Retry with non-wide function (for Windows 98). */
3047 }
3048#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003049 return (GetCurrentDirectory(len, (LPSTR)buf) != 0 ? OK : FAIL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003050}
3051
3052/*
Bram Moolenaarffa22202013-11-21 12:34:11 +01003053 * Get file permissions for "name".
3054 * Return mode_t or -1 for error.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003055 */
3056 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003057mch_getperm(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003058{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003059 struct stat st;
Bram Moolenaarffa22202013-11-21 12:34:11 +01003060 int n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003061
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003062 n = mch_stat((char *)name, &st);
Bram Moolenaar78cf3f02014-01-10 18:16:07 +01003063 return n == 0 ? (long)(unsigned short)st.st_mode : -1L;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003064}
3065
3066
3067/*
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003068 * Set file permission for "name" to "perm".
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003069 *
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003070 * Return FAIL for failure, OK otherwise.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003071 */
3072 int
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003073mch_setperm(char_u *name, long perm)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003074{
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003075 long n = -1;
3076
Bram Moolenaar071d4272004-06-13 20:20:40 +00003077#ifdef FEAT_MBYTE
3078 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3079 {
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003080 WCHAR *p = enc_to_utf16(name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003081
3082 if (p != NULL)
3083 {
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003084 n = _wchmod(p, perm);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003085 vim_free(p);
Bram Moolenaarcd981f22014-02-11 17:06:00 +01003086 if (n == -1 && g_PlatformId == VER_PLATFORM_WIN32_NT)
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003087 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003088 /* Retry with non-wide function (for Windows 98). */
3089 }
3090 }
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003091 if (n == -1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003092#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003093 n = _chmod((const char *)name, perm);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003094 if (n == -1)
3095 return FAIL;
3096
3097 win32_set_archive(name);
3098
3099 return OK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003100}
3101
3102/*
3103 * Set hidden flag for "name".
3104 */
3105 void
3106mch_hide(char_u *name)
3107{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003108 int attrs = win32_getattrs(name);
3109 if (attrs == -1)
3110 return;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003111
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003112 attrs |= FILE_ATTRIBUTE_HIDDEN;
3113 win32_setattrs(name, attrs);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003114}
3115
3116/*
Bram Moolenaar8a52ba72015-11-02 14:45:56 +01003117 * Return TRUE if file "name" exists and is hidden.
3118 */
3119 int
3120mch_ishidden(char_u *name)
3121{
3122 int f = win32_getattrs(name);
3123
3124 if (f == -1)
3125 return FALSE; /* file does not exist at all */
3126
3127 return (f & FILE_ATTRIBUTE_HIDDEN) != 0;
3128}
3129
3130/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003131 * return TRUE if "name" is a directory
3132 * return FALSE if "name" is not a directory or upon error
3133 */
3134 int
3135mch_isdir(char_u *name)
3136{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003137 int f = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003138
3139 if (f == -1)
3140 return FALSE; /* file does not exist at all */
3141
3142 return (f & FILE_ATTRIBUTE_DIRECTORY) != 0;
3143}
3144
3145/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01003146 * return TRUE if "name" is a directory, NOT a symlink to a directory
3147 * return FALSE if "name" is not a directory
3148 * return FALSE for error
3149 */
3150 int
3151mch_isrealdir(char_u *name)
3152{
3153 return mch_isdir(name) && !mch_is_symbolic_link(name);
3154}
3155
3156/*
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003157 * Create directory "name".
3158 * Return 0 on success, -1 on error.
3159 */
3160 int
3161mch_mkdir(char_u *name)
3162{
3163#ifdef FEAT_MBYTE
3164 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3165 {
3166 WCHAR *p;
3167 int retval;
3168
3169 p = enc_to_utf16(name, NULL);
3170 if (p == NULL)
3171 return -1;
3172 retval = _wmkdir(p);
3173 vim_free(p);
3174 return retval;
3175 }
3176#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003177 return _mkdir((const char *)name);
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003178}
3179
3180/*
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003181 * Delete directory "name".
3182 * Return 0 on success, -1 on error.
3183 */
3184 int
3185mch_rmdir(char_u *name)
3186{
3187#ifdef FEAT_MBYTE
3188 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3189 {
3190 WCHAR *p;
3191 int retval;
3192
3193 p = enc_to_utf16(name, NULL);
3194 if (p == NULL)
3195 return -1;
3196 retval = _wrmdir(p);
3197 vim_free(p);
3198 return retval;
3199 }
3200#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003201 return _rmdir((const char *)name);
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003202}
3203
3204/*
Bram Moolenaar03f48552006-02-28 23:52:23 +00003205 * Return TRUE if file "fname" has more than one link.
3206 */
3207 int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003208mch_is_hard_link(char_u *fname)
Bram Moolenaar03f48552006-02-28 23:52:23 +00003209{
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003210 BY_HANDLE_FILE_INFORMATION info;
3211
3212 return win32_fileinfo(fname, &info) == FILEINFO_OK
3213 && info.nNumberOfLinks > 1;
3214}
3215
3216/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01003217 * Return TRUE if "name" is a symbolic link (or a junction).
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003218 */
3219 int
Bram Moolenaar203258c2016-01-17 22:15:16 +01003220mch_is_symbolic_link(char_u *name)
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003221{
3222 HANDLE hFind;
3223 int res = FALSE;
3224 WIN32_FIND_DATAA findDataA;
3225 DWORD fileFlags = 0, reparseTag = 0;
3226#ifdef FEAT_MBYTE
3227 WCHAR *wn = NULL;
3228 WIN32_FIND_DATAW findDataW;
3229
3230 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar203258c2016-01-17 22:15:16 +01003231 wn = enc_to_utf16(name, NULL);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003232 if (wn != NULL)
3233 {
3234 hFind = FindFirstFileW(wn, &findDataW);
3235 vim_free(wn);
3236 if (hFind == INVALID_HANDLE_VALUE
3237 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
3238 {
3239 /* Retry with non-wide function (for Windows 98). */
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003240 hFind = FindFirstFile((LPCSTR)name, &findDataA);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003241 if (hFind != INVALID_HANDLE_VALUE)
3242 {
3243 fileFlags = findDataA.dwFileAttributes;
3244 reparseTag = findDataA.dwReserved0;
3245 }
3246 }
3247 else
3248 {
3249 fileFlags = findDataW.dwFileAttributes;
3250 reparseTag = findDataW.dwReserved0;
3251 }
3252 }
Bram Moolenaar03e114b2013-06-16 16:34:56 +02003253 else
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003254#endif
Bram Moolenaar03e114b2013-06-16 16:34:56 +02003255 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003256 hFind = FindFirstFile((LPCSTR)name, &findDataA);
Bram Moolenaar03e114b2013-06-16 16:34:56 +02003257 if (hFind != INVALID_HANDLE_VALUE)
3258 {
3259 fileFlags = findDataA.dwFileAttributes;
3260 reparseTag = findDataA.dwReserved0;
3261 }
3262 }
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003263
3264 if (hFind != INVALID_HANDLE_VALUE)
3265 FindClose(hFind);
3266
3267 if ((fileFlags & FILE_ATTRIBUTE_REPARSE_POINT)
Bram Moolenaar203258c2016-01-17 22:15:16 +01003268 && (reparseTag == IO_REPARSE_TAG_SYMLINK
3269 || reparseTag == IO_REPARSE_TAG_MOUNT_POINT))
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003270 res = TRUE;
3271
3272 return res;
3273}
3274
3275/*
3276 * Return TRUE if file "fname" has more than one link or if it is a symbolic
3277 * link.
3278 */
3279 int
3280mch_is_linked(char_u *fname)
3281{
3282 if (mch_is_hard_link(fname) || mch_is_symbolic_link(fname))
3283 return TRUE;
3284 return FALSE;
3285}
3286
3287/*
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003288 * Get the by-handle-file-information for "fname".
3289 * Returns FILEINFO_OK when OK.
3290 * returns FILEINFO_ENC_FAIL when enc_to_utf16() failed.
3291 * Returns FILEINFO_READ_FAIL when CreateFile() failed.
3292 * Returns FILEINFO_INFO_FAIL when GetFileInformationByHandle() failed.
3293 */
3294 int
3295win32_fileinfo(char_u *fname, BY_HANDLE_FILE_INFORMATION *info)
3296{
Bram Moolenaar03f48552006-02-28 23:52:23 +00003297 HANDLE hFile;
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003298 int res = FILEINFO_READ_FAIL;
Bram Moolenaar03f48552006-02-28 23:52:23 +00003299#ifdef FEAT_MBYTE
3300 WCHAR *wn = NULL;
3301
3302 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003303 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00003304 wn = enc_to_utf16(fname, NULL);
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003305 if (wn == NULL)
3306 res = FILEINFO_ENC_FAIL;
3307 }
Bram Moolenaar03f48552006-02-28 23:52:23 +00003308 if (wn != NULL)
3309 {
3310 hFile = CreateFileW(wn, /* file name */
3311 GENERIC_READ, /* access mode */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003312 FILE_SHARE_READ | FILE_SHARE_WRITE, /* share mode */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003313 NULL, /* security descriptor */
3314 OPEN_EXISTING, /* creation disposition */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003315 FILE_FLAG_BACKUP_SEMANTICS, /* file attributes */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003316 NULL); /* handle to template file */
3317 if (hFile == INVALID_HANDLE_VALUE
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003318 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
Bram Moolenaar03f48552006-02-28 23:52:23 +00003319 {
3320 /* Retry with non-wide function (for Windows 98). */
3321 vim_free(wn);
3322 wn = NULL;
3323 }
3324 }
3325 if (wn == NULL)
3326#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003327 hFile = CreateFile((LPCSTR)fname, /* file name */
3328 GENERIC_READ, /* access mode */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003329 FILE_SHARE_READ | FILE_SHARE_WRITE, /* share mode */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003330 NULL, /* security descriptor */
3331 OPEN_EXISTING, /* creation disposition */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003332 FILE_FLAG_BACKUP_SEMANTICS, /* file attributes */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003333 NULL); /* handle to template file */
3334
3335 if (hFile != INVALID_HANDLE_VALUE)
3336 {
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003337 if (GetFileInformationByHandle(hFile, info) != 0)
3338 res = FILEINFO_OK;
3339 else
3340 res = FILEINFO_INFO_FAIL;
Bram Moolenaar03f48552006-02-28 23:52:23 +00003341 CloseHandle(hFile);
3342 }
3343
3344#ifdef FEAT_MBYTE
3345 vim_free(wn);
3346#endif
3347 return res;
3348}
3349
3350/*
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003351 * get file attributes for `name'
3352 * -1 : error
3353 * else FILE_ATTRIBUTE_* defined in winnt.h
3354 */
Bram Moolenaarffa22202013-11-21 12:34:11 +01003355 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003356win32_getattrs(char_u *name)
3357{
3358 int attr;
3359#ifdef FEAT_MBYTE
3360 WCHAR *p = NULL;
3361
3362 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3363 p = enc_to_utf16(name, NULL);
3364
3365 if (p != NULL)
3366 {
3367 attr = GetFileAttributesW(p);
3368 if (attr < 0 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
3369 {
3370 /* Retry with non-wide function (for Windows 98). */
3371 vim_free(p);
3372 p = NULL;
3373 }
3374 }
3375 if (p == NULL)
3376#endif
3377 attr = GetFileAttributes((char *)name);
3378#ifdef FEAT_MBYTE
3379 vim_free(p);
3380#endif
3381 return attr;
3382}
3383
3384/*
3385 * set file attributes for `name' to `attrs'
3386 *
3387 * return -1 for failure, 0 otherwise
3388 */
3389 static
3390 int
3391win32_setattrs(char_u *name, int attrs)
3392{
3393 int res;
3394#ifdef FEAT_MBYTE
3395 WCHAR *p = NULL;
3396
3397 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3398 p = enc_to_utf16(name, NULL);
3399
3400 if (p != NULL)
3401 {
3402 res = SetFileAttributesW(p, attrs);
3403 if (res == FALSE
3404 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
3405 {
3406 /* Retry with non-wide function (for Windows 98). */
3407 vim_free(p);
3408 p = NULL;
3409 }
3410 }
3411 if (p == NULL)
3412#endif
3413 res = SetFileAttributes((char *)name, attrs);
3414#ifdef FEAT_MBYTE
3415 vim_free(p);
3416#endif
3417 return res ? 0 : -1;
3418}
3419
3420/*
3421 * Set archive flag for "name".
3422 */
3423 static
3424 int
3425win32_set_archive(char_u *name)
3426{
3427 int attrs = win32_getattrs(name);
3428 if (attrs == -1)
3429 return -1;
3430
3431 attrs |= FILE_ATTRIBUTE_ARCHIVE;
3432 return win32_setattrs(name, attrs);
3433}
3434
3435/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003436 * Return TRUE if file or directory "name" is writable (not readonly).
3437 * Strange semantics of Win32: a readonly directory is writable, but you can't
3438 * delete a file. Let's say this means it is writable.
3439 */
3440 int
3441mch_writable(char_u *name)
3442{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003443 int attrs = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003444
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003445 return (attrs != -1 && (!(attrs & FILE_ATTRIBUTE_READONLY)
3446 || (attrs & FILE_ATTRIBUTE_DIRECTORY)));
Bram Moolenaar071d4272004-06-13 20:20:40 +00003447}
3448
Bram Moolenaar071d4272004-06-13 20:20:40 +00003449/*
3450 * Return 1 if "name" can be executed, 0 if not.
Bram Moolenaar77b77102015-03-21 22:18:41 +01003451 * If "use_path" is FALSE only check if "name" is executable.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003452 * Return -1 if unknown.
3453 */
3454 int
Bram Moolenaar77b77102015-03-21 22:18:41 +01003455mch_can_exe(char_u *name, char_u **path, int use_path)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003456{
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003457 char_u buf[_MAX_PATH];
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00003458 int len = (int)STRLEN(name);
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003459 char_u *p;
3460
3461 if (len >= _MAX_PATH) /* safety check */
3462 return FALSE;
Bram Moolenaar77b77102015-03-21 22:18:41 +01003463 if (!use_path)
3464 {
3465 /* TODO: check if file is really executable. */
3466 return mch_getperm(name) != -1 && !mch_isdir(name);
3467 }
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003468
3469 /* If there already is an extension try using the name directly. Also do
3470 * this with a Unix-shell like 'shell'. */
3471 if (vim_strchr(gettail(name), '.') != NULL
3472 || strstr((char *)gettail(p_sh), "sh") != NULL)
Bram Moolenaarc7f02552014-04-01 21:00:59 +02003473 if (executable_exists((char *)name, path))
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003474 return TRUE;
3475
3476 /*
3477 * Loop over all extensions in $PATHEXT.
3478 */
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00003479 vim_strncpy(buf, name, _MAX_PATH - 1);
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003480 p = mch_getenv("PATHEXT");
3481 if (p == NULL)
3482 p = (char_u *)".com;.exe;.bat;.cmd";
3483 while (*p)
3484 {
3485 if (p[0] == '.' && (p[1] == NUL || p[1] == ';'))
3486 {
3487 /* A single "." means no extension is added. */
3488 buf[len] = NUL;
3489 ++p;
3490 if (*p)
3491 ++p;
3492 }
3493 else
3494 copy_option_part(&p, buf + len, _MAX_PATH - len, ";");
Bram Moolenaarc7f02552014-04-01 21:00:59 +02003495 if (executable_exists((char *)buf, path))
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003496 return TRUE;
3497 }
3498 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003499}
Bram Moolenaar071d4272004-06-13 20:20:40 +00003500
3501/*
3502 * Check what "name" is:
3503 * NODE_NORMAL: file or directory (or doesn't exist)
3504 * NODE_WRITABLE: writable device, socket, fifo, etc.
3505 * NODE_OTHER: non-writable things
3506 */
3507 int
3508mch_nodetype(char_u *name)
3509{
3510 HANDLE hFile;
3511 int type;
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003512#ifdef FEAT_MBYTE
3513 WCHAR *wn = NULL;
3514#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003515
Bram Moolenaar043545e2006-10-10 16:44:07 +00003516 /* We can't open a file with a name "\\.\con" or "\\.\prn" and trying to
3517 * read from it later will cause Vim to hang. Thus return NODE_WRITABLE
3518 * here. */
3519 if (STRNCMP(name, "\\\\.\\", 4) == 0)
3520 return NODE_WRITABLE;
3521
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003522#ifdef FEAT_MBYTE
3523 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3524 {
3525 wn = enc_to_utf16(name, NULL);
3526 if (wn != NULL)
3527 {
3528 hFile = CreateFileW(wn, /* file name */
3529 GENERIC_WRITE, /* access mode */
3530 0, /* share mode */
3531 NULL, /* security descriptor */
3532 OPEN_EXISTING, /* creation disposition */
3533 0, /* file attributes */
3534 NULL); /* handle to template file */
3535 if (hFile == INVALID_HANDLE_VALUE
3536 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
3537 {
3538 /* Retry with non-wide function (for Windows 98). */
3539 vim_free(wn);
3540 wn = NULL;
3541 }
3542 }
3543 }
3544 if (wn == NULL)
3545#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003546 hFile = CreateFile((LPCSTR)name, /* file name */
3547 GENERIC_WRITE, /* access mode */
3548 0, /* share mode */
3549 NULL, /* security descriptor */
3550 OPEN_EXISTING, /* creation disposition */
3551 0, /* file attributes */
3552 NULL); /* handle to template file */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003553
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003554#ifdef FEAT_MBYTE
3555 vim_free(wn);
3556#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003557 if (hFile == INVALID_HANDLE_VALUE)
3558 return NODE_NORMAL;
3559
3560 type = GetFileType(hFile);
3561 CloseHandle(hFile);
3562 if (type == FILE_TYPE_CHAR)
3563 return NODE_WRITABLE;
3564 if (type == FILE_TYPE_DISK)
3565 return NODE_NORMAL;
3566 return NODE_OTHER;
3567}
3568
3569#ifdef HAVE_ACL
3570struct my_acl
3571{
3572 PSECURITY_DESCRIPTOR pSecurityDescriptor;
3573 PSID pSidOwner;
3574 PSID pSidGroup;
3575 PACL pDacl;
3576 PACL pSacl;
3577};
3578#endif
3579
3580/*
3581 * Return a pointer to the ACL of file "fname" in allocated memory.
3582 * Return NULL if the ACL is not available for whatever reason.
3583 */
3584 vim_acl_T
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003585mch_get_acl(char_u *fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003586{
3587#ifndef HAVE_ACL
3588 return (vim_acl_T)NULL;
3589#else
3590 struct my_acl *p = NULL;
Bram Moolenaar27515922013-06-29 15:36:26 +02003591 DWORD err;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003592
3593 /* This only works on Windows NT and 2000. */
3594 if (g_PlatformId == VER_PLATFORM_WIN32_NT && advapi_lib != NULL)
3595 {
3596 p = (struct my_acl *)alloc_clear((unsigned)sizeof(struct my_acl));
3597 if (p != NULL)
3598 {
Bram Moolenaar27515922013-06-29 15:36:26 +02003599# ifdef FEAT_MBYTE
3600 WCHAR *wn = NULL;
3601
3602 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3603 wn = enc_to_utf16(fname, NULL);
3604 if (wn != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003605 {
Bram Moolenaar27515922013-06-29 15:36:26 +02003606 /* Try to retrieve the entire security descriptor. */
3607 err = pGetNamedSecurityInfoW(
3608 wn, // Abstract filename
3609 SE_FILE_OBJECT, // File Object
3610 OWNER_SECURITY_INFORMATION |
3611 GROUP_SECURITY_INFORMATION |
3612 DACL_SECURITY_INFORMATION |
3613 SACL_SECURITY_INFORMATION,
3614 &p->pSidOwner, // Ownership information.
3615 &p->pSidGroup, // Group membership.
3616 &p->pDacl, // Discretionary information.
3617 &p->pSacl, // For auditing purposes.
3618 &p->pSecurityDescriptor);
3619 if (err == ERROR_ACCESS_DENIED ||
3620 err == ERROR_PRIVILEGE_NOT_HELD)
3621 {
3622 /* Retrieve only DACL. */
3623 (void)pGetNamedSecurityInfoW(
3624 wn,
3625 SE_FILE_OBJECT,
3626 DACL_SECURITY_INFORMATION,
3627 NULL,
3628 NULL,
3629 &p->pDacl,
3630 NULL,
3631 &p->pSecurityDescriptor);
3632 }
3633 if (p->pSecurityDescriptor == NULL)
3634 {
3635 mch_free_acl((vim_acl_T)p);
3636 p = NULL;
3637 }
3638 vim_free(wn);
3639 }
3640 else
3641# endif
3642 {
3643 /* Try to retrieve the entire security descriptor. */
3644 err = pGetNamedSecurityInfo(
3645 (LPSTR)fname, // Abstract filename
3646 SE_FILE_OBJECT, // File Object
3647 OWNER_SECURITY_INFORMATION |
3648 GROUP_SECURITY_INFORMATION |
3649 DACL_SECURITY_INFORMATION |
3650 SACL_SECURITY_INFORMATION,
3651 &p->pSidOwner, // Ownership information.
3652 &p->pSidGroup, // Group membership.
3653 &p->pDacl, // Discretionary information.
3654 &p->pSacl, // For auditing purposes.
3655 &p->pSecurityDescriptor);
3656 if (err == ERROR_ACCESS_DENIED ||
3657 err == ERROR_PRIVILEGE_NOT_HELD)
3658 {
3659 /* Retrieve only DACL. */
3660 (void)pGetNamedSecurityInfo(
3661 (LPSTR)fname,
3662 SE_FILE_OBJECT,
3663 DACL_SECURITY_INFORMATION,
3664 NULL,
3665 NULL,
3666 &p->pDacl,
3667 NULL,
3668 &p->pSecurityDescriptor);
3669 }
3670 if (p->pSecurityDescriptor == NULL)
3671 {
3672 mch_free_acl((vim_acl_T)p);
3673 p = NULL;
3674 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003675 }
3676 }
3677 }
3678
3679 return (vim_acl_T)p;
3680#endif
3681}
3682
Bram Moolenaar27515922013-06-29 15:36:26 +02003683#ifdef HAVE_ACL
3684/*
3685 * Check if "acl" contains inherited ACE.
3686 */
3687 static BOOL
3688is_acl_inherited(PACL acl)
3689{
3690 DWORD i;
3691 ACL_SIZE_INFORMATION acl_info;
3692 PACCESS_ALLOWED_ACE ace;
3693
3694 acl_info.AceCount = 0;
3695 GetAclInformation(acl, &acl_info, sizeof(acl_info), AclSizeInformation);
3696 for (i = 0; i < acl_info.AceCount; i++)
3697 {
3698 GetAce(acl, i, (LPVOID *)&ace);
3699 if (ace->Header.AceFlags & INHERITED_ACE)
3700 return TRUE;
3701 }
3702 return FALSE;
3703}
3704#endif
3705
Bram Moolenaar071d4272004-06-13 20:20:40 +00003706/*
3707 * Set the ACL of file "fname" to "acl" (unless it's NULL).
3708 * Errors are ignored.
3709 * This must only be called with "acl" equal to what mch_get_acl() returned.
3710 */
3711 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003712mch_set_acl(char_u *fname, vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003713{
3714#ifdef HAVE_ACL
3715 struct my_acl *p = (struct my_acl *)acl;
Bram Moolenaar27515922013-06-29 15:36:26 +02003716 SECURITY_INFORMATION sec_info = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003717
3718 if (p != NULL && advapi_lib != NULL)
Bram Moolenaar27515922013-06-29 15:36:26 +02003719 {
3720# ifdef FEAT_MBYTE
3721 WCHAR *wn = NULL;
3722# endif
3723
3724 /* Set security flags */
3725 if (p->pSidOwner)
3726 sec_info |= OWNER_SECURITY_INFORMATION;
3727 if (p->pSidGroup)
3728 sec_info |= GROUP_SECURITY_INFORMATION;
3729 if (p->pDacl)
3730 {
3731 sec_info |= DACL_SECURITY_INFORMATION;
3732 /* Do not inherit its parent's DACL.
3733 * If the DACL is inherited, Cygwin permissions would be changed.
3734 */
3735 if (!is_acl_inherited(p->pDacl))
3736 sec_info |= PROTECTED_DACL_SECURITY_INFORMATION;
3737 }
3738 if (p->pSacl)
3739 sec_info |= SACL_SECURITY_INFORMATION;
3740
3741# ifdef FEAT_MBYTE
3742 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3743 wn = enc_to_utf16(fname, NULL);
3744 if (wn != NULL)
3745 {
3746 (void)pSetNamedSecurityInfoW(
3747 wn, // Abstract filename
3748 SE_FILE_OBJECT, // File Object
3749 sec_info,
3750 p->pSidOwner, // Ownership information.
3751 p->pSidGroup, // Group membership.
3752 p->pDacl, // Discretionary information.
3753 p->pSacl // For auditing purposes.
3754 );
3755 vim_free(wn);
3756 }
3757 else
3758# endif
3759 {
3760 (void)pSetNamedSecurityInfo(
3761 (LPSTR)fname, // Abstract filename
3762 SE_FILE_OBJECT, // File Object
3763 sec_info,
3764 p->pSidOwner, // Ownership information.
3765 p->pSidGroup, // Group membership.
3766 p->pDacl, // Discretionary information.
3767 p->pSacl // For auditing purposes.
3768 );
3769 }
3770 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003771#endif
3772}
3773
3774 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003775mch_free_acl(vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003776{
3777#ifdef HAVE_ACL
3778 struct my_acl *p = (struct my_acl *)acl;
3779
3780 if (p != NULL)
3781 {
3782 LocalFree(p->pSecurityDescriptor); // Free the memory just in case
3783 vim_free(p);
3784 }
3785#endif
3786}
3787
3788#ifndef FEAT_GUI_W32
3789
3790/*
3791 * handler for ctrl-break, ctrl-c interrupts, and fatal events.
3792 */
3793 static BOOL WINAPI
3794handler_routine(
3795 DWORD dwCtrlType)
3796{
3797 switch (dwCtrlType)
3798 {
3799 case CTRL_C_EVENT:
3800 if (ctrl_c_interrupts)
3801 g_fCtrlCPressed = TRUE;
3802 return TRUE;
3803
3804 case CTRL_BREAK_EVENT:
3805 g_fCBrkPressed = TRUE;
3806 return TRUE;
3807
3808 /* fatal events: shut down gracefully */
3809 case CTRL_CLOSE_EVENT:
3810 case CTRL_LOGOFF_EVENT:
3811 case CTRL_SHUTDOWN_EVENT:
3812 windgoto((int)Rows - 1, 0);
3813 g_fForceExit = TRUE;
3814
Bram Moolenaar0fde2902008-03-16 13:54:13 +00003815 vim_snprintf((char *)IObuff, IOSIZE, _("Vim: Caught %s event\n"),
Bram Moolenaar071d4272004-06-13 20:20:40 +00003816 (dwCtrlType == CTRL_CLOSE_EVENT
3817 ? _("close")
3818 : dwCtrlType == CTRL_LOGOFF_EVENT
3819 ? _("logoff")
3820 : _("shutdown")));
3821#ifdef DEBUG
3822 OutputDebugString(IObuff);
3823#endif
3824
3825 preserve_exit(); /* output IObuff, preserve files and exit */
3826
3827 return TRUE; /* not reached */
3828
3829 default:
3830 return FALSE;
3831 }
3832}
3833
3834
3835/*
3836 * set the tty in (raw) ? "raw" : "cooked" mode
3837 */
3838 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003839mch_settmode(int tmode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003840{
3841 DWORD cmodein;
3842 DWORD cmodeout;
3843 BOOL bEnableHandler;
3844
3845 GetConsoleMode(g_hConIn, &cmodein);
3846 GetConsoleMode(g_hConOut, &cmodeout);
3847 if (tmode == TMODE_RAW)
3848 {
3849 cmodein &= ~(ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
3850 ENABLE_ECHO_INPUT);
3851#ifdef FEAT_MOUSE
3852 if (g_fMouseActive)
3853 cmodein |= ENABLE_MOUSE_INPUT;
3854#endif
3855 cmodeout &= ~(ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
3856 bEnableHandler = TRUE;
3857 }
3858 else /* cooked */
3859 {
3860 cmodein |= (ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
3861 ENABLE_ECHO_INPUT);
3862 cmodeout |= (ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
3863 bEnableHandler = FALSE;
3864 }
3865 SetConsoleMode(g_hConIn, cmodein);
3866 SetConsoleMode(g_hConOut, cmodeout);
3867 SetConsoleCtrlHandler(handler_routine, bEnableHandler);
3868
3869#ifdef MCH_WRITE_DUMP
3870 if (fdDump)
3871 {
3872 fprintf(fdDump, "mch_settmode(%s, in = %x, out = %x)\n",
3873 tmode == TMODE_RAW ? "raw" :
3874 tmode == TMODE_COOK ? "cooked" : "normal",
3875 cmodein, cmodeout);
3876 fflush(fdDump);
3877 }
3878#endif
3879}
3880
3881
3882/*
3883 * Get the size of the current window in `Rows' and `Columns'
3884 * Return OK when size could be determined, FAIL otherwise.
3885 */
3886 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003887mch_get_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003888{
3889 CONSOLE_SCREEN_BUFFER_INFO csbi;
3890
3891 if (!g_fTermcapMode && g_cbTermcap.IsValid)
3892 {
3893 /*
3894 * For some reason, we are trying to get the screen dimensions
3895 * even though we are not in termcap mode. The 'Rows' and 'Columns'
3896 * variables are really intended to mean the size of Vim screen
3897 * while in termcap mode.
3898 */
3899 Rows = g_cbTermcap.Info.dwSize.Y;
3900 Columns = g_cbTermcap.Info.dwSize.X;
3901 }
3902 else if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3903 {
3904 Rows = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
3905 Columns = csbi.srWindow.Right - csbi.srWindow.Left + 1;
3906 }
3907 else
3908 {
3909 Rows = 25;
3910 Columns = 80;
3911 }
3912 return OK;
3913}
3914
3915/*
3916 * Set a console window to `xSize' * `ySize'
3917 */
3918 static void
3919ResizeConBufAndWindow(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003920 HANDLE hConsole,
3921 int xSize,
3922 int ySize)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003923{
3924 CONSOLE_SCREEN_BUFFER_INFO csbi; /* hold current console buffer info */
3925 SMALL_RECT srWindowRect; /* hold the new console size */
3926 COORD coordScreen;
3927
3928#ifdef MCH_WRITE_DUMP
3929 if (fdDump)
3930 {
3931 fprintf(fdDump, "ResizeConBufAndWindow(%d, %d)\n", xSize, ySize);
3932 fflush(fdDump);
3933 }
3934#endif
3935
3936 /* get the largest size we can size the console window to */
3937 coordScreen = GetLargestConsoleWindowSize(hConsole);
3938
3939 /* define the new console window size and scroll position */
3940 srWindowRect.Left = srWindowRect.Top = (SHORT) 0;
3941 srWindowRect.Right = (SHORT) (min(xSize, coordScreen.X) - 1);
3942 srWindowRect.Bottom = (SHORT) (min(ySize, coordScreen.Y) - 1);
3943
3944 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3945 {
3946 int sx, sy;
3947
3948 sx = csbi.srWindow.Right - csbi.srWindow.Left + 1;
3949 sy = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
3950 if (sy < ySize || sx < xSize)
3951 {
3952 /*
3953 * Increasing number of lines/columns, do buffer first.
3954 * Use the maximal size in x and y direction.
3955 */
3956 if (sy < ySize)
3957 coordScreen.Y = ySize;
3958 else
3959 coordScreen.Y = sy;
3960 if (sx < xSize)
3961 coordScreen.X = xSize;
3962 else
3963 coordScreen.X = sx;
3964 SetConsoleScreenBufferSize(hConsole, coordScreen);
3965 }
3966 }
3967
3968 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &srWindowRect))
3969 {
3970#ifdef MCH_WRITE_DUMP
3971 if (fdDump)
3972 {
3973 fprintf(fdDump, "SetConsoleWindowInfo failed: %lx\n",
3974 GetLastError());
3975 fflush(fdDump);
3976 }
3977#endif
3978 }
3979
3980 /* define the new console buffer size */
3981 coordScreen.X = xSize;
3982 coordScreen.Y = ySize;
3983
3984 if (!SetConsoleScreenBufferSize(hConsole, coordScreen))
3985 {
3986#ifdef MCH_WRITE_DUMP
3987 if (fdDump)
3988 {
3989 fprintf(fdDump, "SetConsoleScreenBufferSize failed: %lx\n",
3990 GetLastError());
3991 fflush(fdDump);
3992 }
3993#endif
3994 }
3995}
3996
3997
3998/*
3999 * Set the console window to `Rows' * `Columns'
4000 */
4001 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004002mch_set_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004003{
4004 COORD coordScreen;
4005
4006 /* Don't change window size while still starting up */
4007 if (suppress_winsize != 0)
4008 {
4009 suppress_winsize = 2;
4010 return;
4011 }
4012
4013 if (term_console)
4014 {
4015 coordScreen = GetLargestConsoleWindowSize(g_hConOut);
4016
4017 /* Clamp Rows and Columns to reasonable values */
4018 if (Rows > coordScreen.Y)
4019 Rows = coordScreen.Y;
4020 if (Columns > coordScreen.X)
4021 Columns = coordScreen.X;
4022
4023 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
4024 }
4025}
4026
4027/*
4028 * Rows and/or Columns has changed.
4029 */
4030 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004031mch_new_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004032{
4033 set_scroll_region(0, 0, Columns - 1, Rows - 1);
4034}
4035
4036
4037/*
4038 * Called when started up, to set the winsize that was delayed.
4039 */
4040 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004041mch_set_winsize_now(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004042{
4043 if (suppress_winsize == 2)
4044 {
4045 suppress_winsize = 0;
4046 mch_set_shellsize();
4047 shell_resized();
4048 }
4049 suppress_winsize = 0;
4050}
4051#endif /* FEAT_GUI_W32 */
4052
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004053 static BOOL
4054vim_create_process(
Bram Moolenaar36c85b22013-12-12 20:25:44 +01004055 char *cmd,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004056 BOOL inherit_handles,
Bram Moolenaar3f1138e2014-01-05 13:29:26 +01004057 DWORD flags,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004058 STARTUPINFO *si,
4059 PROCESS_INFORMATION *pi)
4060{
4061# ifdef FEAT_MBYTE
4062 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4063 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004064 WCHAR *wcmd = enc_to_utf16((char_u *)cmd, NULL);
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004065
4066 if (wcmd != NULL)
4067 {
4068 BOOL ret;
4069 ret = CreateProcessW(
4070 NULL, /* Executable name */
4071 wcmd, /* Command to execute */
4072 NULL, /* Process security attributes */
4073 NULL, /* Thread security attributes */
4074 inherit_handles, /* Inherit handles */
4075 flags, /* Creation flags */
4076 NULL, /* Environment */
4077 NULL, /* Current directory */
Bram Moolenaar36c85b22013-12-12 20:25:44 +01004078 (LPSTARTUPINFOW)si, /* Startup information */
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004079 pi); /* Process information */
4080 vim_free(wcmd);
4081 return ret;
4082 }
4083 }
4084#endif
4085 return CreateProcess(
4086 NULL, /* Executable name */
4087 cmd, /* Command to execute */
4088 NULL, /* Process security attributes */
4089 NULL, /* Thread security attributes */
4090 inherit_handles, /* Inherit handles */
4091 flags, /* Creation flags */
4092 NULL, /* Environment */
4093 NULL, /* Current directory */
4094 si, /* Startup information */
4095 pi); /* Process information */
4096}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004097
4098
4099#if defined(FEAT_GUI_W32) || defined(PROTO)
4100
4101/*
4102 * Specialised version of system() for Win32 GUI mode.
4103 * This version proceeds as follows:
4104 * 1. Create a console window for use by the subprocess
4105 * 2. Run the subprocess (it gets the allocated console by default)
4106 * 3. Wait for the subprocess to terminate and get its exit code
4107 * 4. Prompt the user to press a key to close the console window
4108 */
4109 static int
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004110mch_system_classic(char *cmd, int options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004111{
4112 STARTUPINFO si;
4113 PROCESS_INFORMATION pi;
4114 DWORD ret = 0;
4115 HWND hwnd = GetFocus();
4116
4117 si.cb = sizeof(si);
4118 si.lpReserved = NULL;
4119 si.lpDesktop = NULL;
4120 si.lpTitle = NULL;
4121 si.dwFlags = STARTF_USESHOWWINDOW;
4122 /*
4123 * It's nicer to run a filter command in a minimized window, but in
4124 * Windows 95 this makes the command MUCH slower. We can't do it under
4125 * Win32s either as it stops the synchronous spawn workaround working.
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01004126 * Don't activate the window to keep focus on Vim.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004127 */
4128 if ((options & SHELL_DOOUT) && !mch_windows95() && !gui_is_win32s())
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01004129 si.wShowWindow = SW_SHOWMINNOACTIVE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004130 else
4131 si.wShowWindow = SW_SHOWNORMAL;
4132 si.cbReserved2 = 0;
4133 si.lpReserved2 = NULL;
4134
Bram Moolenaar942d6b22016-02-07 19:57:16 +01004135 /* There is a strange error on Windows 95 when using "c:\command.com".
Bram Moolenaar071d4272004-06-13 20:20:40 +00004136 * When the "c:\\" is left out it works OK...? */
4137 if (mch_windows95()
4138 && (STRNICMP(cmd, "c:/command.com", 14) == 0
4139 || STRNICMP(cmd, "c:\\command.com", 14) == 0))
4140 cmd += 3;
4141
4142 /* Now, run the command */
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004143 vim_create_process(cmd, FALSE,
4144 CREATE_DEFAULT_ERROR_MODE | CREATE_NEW_CONSOLE, &si, &pi);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004145
4146 /* Wait for the command to terminate before continuing */
4147 if (g_PlatformId != VER_PLATFORM_WIN32s)
4148 {
4149#ifdef FEAT_GUI
4150 int delay = 1;
4151
4152 /* Keep updating the window while waiting for the shell to finish. */
4153 for (;;)
4154 {
4155 MSG msg;
4156
Bram Moolenaar8c85fa32011-08-10 17:08:03 +02004157 if (pPeekMessage(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004158 {
4159 TranslateMessage(&msg);
Bram Moolenaar8c85fa32011-08-10 17:08:03 +02004160 pDispatchMessage(&msg);
Bram Moolenaare4195c52012-08-02 12:31:44 +02004161 delay = 1;
4162 continue;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004163 }
4164 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
4165 break;
4166
4167 /* We start waiting for a very short time and then increase it, so
4168 * that we respond quickly when the process is quick, and don't
4169 * consume too much overhead when it's slow. */
4170 if (delay < 50)
4171 delay += 10;
4172 }
4173#else
4174 WaitForSingleObject(pi.hProcess, INFINITE);
4175#endif
4176
4177 /* Get the command exit code */
4178 GetExitCodeProcess(pi.hProcess, &ret);
4179 }
4180 else
4181 {
4182 /*
4183 * This ugly code is the only quick way of performing
4184 * a synchronous spawn under Win32s. Yuk.
4185 */
4186 num_windows = 0;
4187 EnumWindows(win32ssynch_cb, 0);
4188 old_num_windows = num_windows;
4189 do
4190 {
4191 Sleep(1000);
4192 num_windows = 0;
4193 EnumWindows(win32ssynch_cb, 0);
4194 } while (num_windows == old_num_windows);
4195 ret = 0;
4196 }
4197
4198 /* Close the handles to the subprocess, so that it goes away */
4199 CloseHandle(pi.hThread);
4200 CloseHandle(pi.hProcess);
4201
4202 /* Try to get input focus back. Doesn't always work though. */
4203 PostMessage(hwnd, WM_SETFOCUS, 0, 0);
4204
4205 return ret;
4206}
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004207
4208/*
4209 * Thread launched by the gui to send the current buffer data to the
4210 * process. This way avoid to hang up vim totally if the children
4211 * process take a long time to process the lines.
4212 */
4213 static DWORD WINAPI
4214sub_process_writer(LPVOID param)
4215{
4216 HANDLE g_hChildStd_IN_Wr = param;
4217 linenr_T lnum = curbuf->b_op_start.lnum;
4218 DWORD len = 0;
4219 DWORD l;
4220 char_u *lp = ml_get(lnum);
4221 char_u *s;
4222 int written = 0;
4223
4224 for (;;)
4225 {
4226 l = (DWORD)STRLEN(lp + written);
4227 if (l == 0)
4228 len = 0;
4229 else if (lp[written] == NL)
4230 {
4231 /* NL -> NUL translation */
4232 WriteFile(g_hChildStd_IN_Wr, "", 1, &len, NULL);
4233 }
4234 else
4235 {
4236 s = vim_strchr(lp + written, NL);
4237 WriteFile(g_hChildStd_IN_Wr, (char *)lp + written,
4238 s == NULL ? l : (DWORD)(s - (lp + written)),
4239 &len, NULL);
4240 }
4241 if (len == (int)l)
4242 {
4243 /* Finished a line, add a NL, unless this line should not have
4244 * one. */
4245 if (lnum != curbuf->b_op_end.lnum
Bram Moolenaar34d72d42015-07-17 14:18:08 +02004246 || (!curbuf->b_p_bin
4247 && curbuf->b_p_fixeol)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004248 || (lnum != curbuf->b_no_eol_lnum
4249 && (lnum != curbuf->b_ml.ml_line_count
4250 || curbuf->b_p_eol)))
4251 {
Bram Moolenaaraf62ff32013-03-19 14:48:29 +01004252 WriteFile(g_hChildStd_IN_Wr, "\n", 1, (LPDWORD)&ignored, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004253 }
4254
4255 ++lnum;
4256 if (lnum > curbuf->b_op_end.lnum)
4257 break;
4258
4259 lp = ml_get(lnum);
4260 written = 0;
4261 }
4262 else if (len > 0)
4263 written += len;
4264 }
4265
4266 /* finished all the lines, close pipe */
4267 CloseHandle(g_hChildStd_IN_Wr);
4268 ExitThread(0);
4269}
4270
4271
4272# define BUFLEN 100 /* length for buffer, stolen from unix version */
4273
4274/*
4275 * This function read from the children's stdout and write the
4276 * data on screen or in the buffer accordingly.
4277 */
4278 static void
4279dump_pipe(int options,
4280 HANDLE g_hChildStd_OUT_Rd,
4281 garray_T *ga,
4282 char_u buffer[],
4283 DWORD *buffer_off)
4284{
4285 DWORD availableBytes = 0;
4286 DWORD i;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004287 int ret;
4288 DWORD len;
4289 DWORD toRead;
4290 int repeatCount;
4291
4292 /* we query the pipe to see if there is any data to read
4293 * to avoid to perform a blocking read */
4294 ret = PeekNamedPipe(g_hChildStd_OUT_Rd, /* pipe to query */
4295 NULL, /* optional buffer */
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02004296 0, /* buffer size */
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004297 NULL, /* number of read bytes */
4298 &availableBytes, /* available bytes total */
4299 NULL); /* byteLeft */
4300
4301 repeatCount = 0;
4302 /* We got real data in the pipe, read it */
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02004303 while (ret != 0 && availableBytes > 0)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004304 {
4305 repeatCount++;
4306 toRead =
4307# ifdef FEAT_MBYTE
4308 (DWORD)(BUFLEN - *buffer_off);
4309# else
4310 (DWORD)BUFLEN;
4311# endif
4312 toRead = availableBytes < toRead ? availableBytes : toRead;
4313 ReadFile(g_hChildStd_OUT_Rd, buffer
4314# ifdef FEAT_MBYTE
4315 + *buffer_off, toRead
4316# else
4317 , toRead
4318# endif
4319 , &len, NULL);
4320
4321 /* If we haven't read anything, there is a problem */
4322 if (len == 0)
4323 break;
4324
4325 availableBytes -= len;
4326
4327 if (options & SHELL_READ)
4328 {
4329 /* Do NUL -> NL translation, append NL separated
4330 * lines to the current buffer. */
4331 for (i = 0; i < len; ++i)
4332 {
4333 if (buffer[i] == NL)
4334 append_ga_line(ga);
4335 else if (buffer[i] == NUL)
4336 ga_append(ga, NL);
4337 else
4338 ga_append(ga, buffer[i]);
4339 }
4340 }
4341# ifdef FEAT_MBYTE
4342 else if (has_mbyte)
4343 {
4344 int l;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004345 int c;
4346 char_u *p;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004347
4348 len += *buffer_off;
4349 buffer[len] = NUL;
4350
4351 /* Check if the last character in buffer[] is
4352 * incomplete, keep these bytes for the next
4353 * round. */
4354 for (p = buffer; p < buffer + len; p += l)
4355 {
4356 l = mb_cptr2len(p);
4357 if (l == 0)
4358 l = 1; /* NUL byte? */
4359 else if (MB_BYTE2LEN(*p) != l)
4360 break;
4361 }
4362 if (p == buffer) /* no complete character */
4363 {
4364 /* avoid getting stuck at an illegal byte */
4365 if (len >= 12)
4366 ++p;
4367 else
4368 {
4369 *buffer_off = len;
4370 return;
4371 }
4372 }
4373 c = *p;
4374 *p = NUL;
4375 msg_puts(buffer);
4376 if (p < buffer + len)
4377 {
4378 *p = c;
4379 *buffer_off = (DWORD)((buffer + len) - p);
4380 mch_memmove(buffer, p, *buffer_off);
4381 return;
4382 }
4383 *buffer_off = 0;
4384 }
4385# endif /* FEAT_MBYTE */
4386 else
4387 {
4388 buffer[len] = NUL;
4389 msg_puts(buffer);
4390 }
4391
4392 windgoto(msg_row, msg_col);
4393 cursor_on();
4394 out_flush();
4395 }
4396}
4397
4398/*
4399 * Version of system to use for windows NT > 5.0 (Win2K), use pipe
4400 * for communication and doesn't open any new window.
4401 */
4402 static int
4403mch_system_piped(char *cmd, int options)
4404{
4405 STARTUPINFO si;
4406 PROCESS_INFORMATION pi;
4407 DWORD ret = 0;
4408
4409 HANDLE g_hChildStd_IN_Rd = NULL;
4410 HANDLE g_hChildStd_IN_Wr = NULL;
4411 HANDLE g_hChildStd_OUT_Rd = NULL;
4412 HANDLE g_hChildStd_OUT_Wr = NULL;
4413
4414 char_u buffer[BUFLEN + 1]; /* reading buffer + size */
4415 DWORD len;
4416
4417 /* buffer used to receive keys */
4418 char_u ta_buf[BUFLEN + 1]; /* TypeAHead */
4419 int ta_len = 0; /* valid bytes in ta_buf[] */
4420
4421 DWORD i;
4422 int c;
4423 int noread_cnt = 0;
4424 garray_T ga;
4425 int delay = 1;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004426 DWORD buffer_off = 0; /* valid bytes in buffer[] */
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004427 char *p = NULL;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004428
4429 SECURITY_ATTRIBUTES saAttr;
4430
4431 /* Set the bInheritHandle flag so pipe handles are inherited. */
4432 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
4433 saAttr.bInheritHandle = TRUE;
4434 saAttr.lpSecurityDescriptor = NULL;
4435
4436 if ( ! CreatePipe(&g_hChildStd_OUT_Rd, &g_hChildStd_OUT_Wr, &saAttr, 0)
4437 /* Ensure the read handle to the pipe for STDOUT is not inherited. */
4438 || ! pSetHandleInformation(g_hChildStd_OUT_Rd, HANDLE_FLAG_INHERIT, 0)
4439 /* Create a pipe for the child process's STDIN. */
4440 || ! CreatePipe(&g_hChildStd_IN_Rd, &g_hChildStd_IN_Wr, &saAttr, 0)
4441 /* Ensure the write handle to the pipe for STDIN is not inherited. */
4442 || ! pSetHandleInformation(g_hChildStd_IN_Wr, HANDLE_FLAG_INHERIT, 0) )
4443 {
4444 CloseHandle(g_hChildStd_IN_Rd);
4445 CloseHandle(g_hChildStd_IN_Wr);
4446 CloseHandle(g_hChildStd_OUT_Rd);
4447 CloseHandle(g_hChildStd_OUT_Wr);
4448 MSG_PUTS(_("\nCannot create pipes\n"));
4449 }
4450
4451 si.cb = sizeof(si);
4452 si.lpReserved = NULL;
4453 si.lpDesktop = NULL;
4454 si.lpTitle = NULL;
4455 si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
4456
4457 /* set-up our file redirection */
4458 si.hStdError = g_hChildStd_OUT_Wr;
4459 si.hStdOutput = g_hChildStd_OUT_Wr;
4460 si.hStdInput = g_hChildStd_IN_Rd;
4461 si.wShowWindow = SW_HIDE;
4462 si.cbReserved2 = 0;
4463 si.lpReserved2 = NULL;
4464
4465 if (options & SHELL_READ)
4466 ga_init2(&ga, 1, BUFLEN);
4467
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004468 if (cmd != NULL)
4469 {
4470 p = (char *)vim_strsave((char_u *)cmd);
4471 if (p != NULL)
4472 unescape_shellxquote((char_u *)p, p_sxe);
4473 else
4474 p = cmd;
4475 }
4476
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004477 /* Now, run the command.
4478 * About "Inherit handles" being TRUE: this command can be litigious,
4479 * handle inheritance was deactivated for pending temp file, but, if we
4480 * deactivate it, the pipes don't work for some reason. */
4481 vim_create_process(p, TRUE, CREATE_DEFAULT_ERROR_MODE, &si, &pi);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004482
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004483 if (p != cmd)
4484 vim_free(p);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004485
4486 /* Close our unused side of the pipes */
4487 CloseHandle(g_hChildStd_IN_Rd);
4488 CloseHandle(g_hChildStd_OUT_Wr);
4489
4490 if (options & SHELL_WRITE)
4491 {
4492 HANDLE thread =
4493 CreateThread(NULL, /* security attributes */
4494 0, /* default stack size */
4495 sub_process_writer, /* function to be executed */
4496 g_hChildStd_IN_Wr, /* parameter */
4497 0, /* creation flag, start immediately */
4498 NULL); /* we don't care about thread id */
4499 CloseHandle(thread);
4500 g_hChildStd_IN_Wr = NULL;
4501 }
4502
4503 /* Keep updating the window while waiting for the shell to finish. */
4504 for (;;)
4505 {
4506 MSG msg;
4507
Bram Moolenaar175d0702013-12-11 18:36:33 +01004508 if (pPeekMessage(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004509 {
4510 TranslateMessage(&msg);
Bram Moolenaar175d0702013-12-11 18:36:33 +01004511 pDispatchMessage(&msg);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004512 }
4513
4514 /* write pipe information in the window */
4515 if ((options & (SHELL_READ|SHELL_WRITE))
4516# ifdef FEAT_GUI
4517 || gui.in_use
4518# endif
4519 )
4520 {
4521 len = 0;
4522 if (!(options & SHELL_EXPAND)
4523 && ((options &
4524 (SHELL_READ|SHELL_WRITE|SHELL_COOKED))
4525 != (SHELL_READ|SHELL_WRITE|SHELL_COOKED)
4526# ifdef FEAT_GUI
4527 || gui.in_use
4528# endif
4529 )
4530 && (ta_len > 0 || noread_cnt > 4))
4531 {
4532 if (ta_len == 0)
4533 {
4534 /* Get extra characters when we don't have any. Reset the
4535 * counter and timer. */
4536 noread_cnt = 0;
4537# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
4538 gettimeofday(&start_tv, NULL);
4539# endif
4540 len = ui_inchar(ta_buf, BUFLEN, 10L, 0);
4541 }
4542 if (ta_len > 0 || len > 0)
4543 {
4544 /*
4545 * For pipes: Check for CTRL-C: send interrupt signal to
4546 * child. Check for CTRL-D: EOF, close pipe to child.
4547 */
4548 if (len == 1 && cmd != NULL)
4549 {
4550 if (ta_buf[ta_len] == Ctrl_C)
4551 {
4552 /* Learn what exit code is expected, for
4553 * now put 9 as SIGKILL */
4554 TerminateProcess(pi.hProcess, 9);
4555 }
4556 if (ta_buf[ta_len] == Ctrl_D)
4557 {
4558 CloseHandle(g_hChildStd_IN_Wr);
4559 g_hChildStd_IN_Wr = NULL;
4560 }
4561 }
4562
4563 /* replace K_BS by <BS> and K_DEL by <DEL> */
4564 for (i = ta_len; i < ta_len + len; ++i)
4565 {
4566 if (ta_buf[i] == CSI && len - i > 2)
4567 {
4568 c = TERMCAP2KEY(ta_buf[i + 1], ta_buf[i + 2]);
4569 if (c == K_DEL || c == K_KDEL || c == K_BS)
4570 {
4571 mch_memmove(ta_buf + i + 1, ta_buf + i + 3,
4572 (size_t)(len - i - 2));
4573 if (c == K_DEL || c == K_KDEL)
4574 ta_buf[i] = DEL;
4575 else
4576 ta_buf[i] = Ctrl_H;
4577 len -= 2;
4578 }
4579 }
4580 else if (ta_buf[i] == '\r')
4581 ta_buf[i] = '\n';
4582# ifdef FEAT_MBYTE
4583 if (has_mbyte)
4584 i += (*mb_ptr2len_len)(ta_buf + i,
4585 ta_len + len - i) - 1;
4586# endif
4587 }
4588
4589 /*
4590 * For pipes: echo the typed characters. For a pty this
4591 * does not seem to work.
4592 */
4593 for (i = ta_len; i < ta_len + len; ++i)
4594 {
4595 if (ta_buf[i] == '\n' || ta_buf[i] == '\b')
4596 msg_putchar(ta_buf[i]);
4597# ifdef FEAT_MBYTE
4598 else if (has_mbyte)
4599 {
4600 int l = (*mb_ptr2len)(ta_buf + i);
4601
4602 msg_outtrans_len(ta_buf + i, l);
4603 i += l - 1;
4604 }
4605# endif
4606 else
4607 msg_outtrans_len(ta_buf + i, 1);
4608 }
4609 windgoto(msg_row, msg_col);
4610 out_flush();
4611
4612 ta_len += len;
4613
4614 /*
4615 * Write the characters to the child, unless EOF has been
4616 * typed for pipes. Write one character at a time, to
4617 * avoid losing too much typeahead. When writing buffer
4618 * lines, drop the typed characters (only check for
4619 * CTRL-C).
4620 */
4621 if (options & SHELL_WRITE)
4622 ta_len = 0;
4623 else if (g_hChildStd_IN_Wr != NULL)
4624 {
4625 WriteFile(g_hChildStd_IN_Wr, (char*)ta_buf,
4626 1, &len, NULL);
4627 // if we are typing in, we want to keep things reactive
4628 delay = 1;
4629 if (len > 0)
4630 {
4631 ta_len -= len;
4632 mch_memmove(ta_buf, ta_buf + len, ta_len);
4633 }
4634 }
4635 }
4636 }
4637 }
4638
4639 if (ta_len)
4640 ui_inchar_undo(ta_buf, ta_len);
4641
4642 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
4643 {
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004644 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004645 break;
4646 }
4647
4648 ++noread_cnt;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004649 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004650
4651 /* We start waiting for a very short time and then increase it, so
4652 * that we respond quickly when the process is quick, and don't
4653 * consume too much overhead when it's slow. */
4654 if (delay < 50)
4655 delay += 10;
4656 }
4657
4658 /* Close the pipe */
4659 CloseHandle(g_hChildStd_OUT_Rd);
4660 if (g_hChildStd_IN_Wr != NULL)
4661 CloseHandle(g_hChildStd_IN_Wr);
4662
4663 WaitForSingleObject(pi.hProcess, INFINITE);
4664
4665 /* Get the command exit code */
4666 GetExitCodeProcess(pi.hProcess, &ret);
4667
4668 if (options & SHELL_READ)
4669 {
4670 if (ga.ga_len > 0)
4671 {
4672 append_ga_line(&ga);
4673 /* remember that the NL was missing */
4674 curbuf->b_no_eol_lnum = curwin->w_cursor.lnum;
4675 }
4676 else
4677 curbuf->b_no_eol_lnum = 0;
4678 ga_clear(&ga);
4679 }
4680
4681 /* Close the handles to the subprocess, so that it goes away */
4682 CloseHandle(pi.hThread);
4683 CloseHandle(pi.hProcess);
4684
4685 return ret;
4686}
4687
4688 static int
4689mch_system(char *cmd, int options)
4690{
4691 /* if we can pipe and the shelltemp option is off */
4692 if (allowPiping && !p_stmp)
4693 return mch_system_piped(cmd, options);
4694 else
4695 return mch_system_classic(cmd, options);
4696}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004697#else
4698
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004699# ifdef FEAT_MBYTE
4700 static int
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01004701mch_system(char *cmd, int options)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004702{
4703 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4704 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004705 WCHAR *wcmd = enc_to_utf16((char_u *)cmd, NULL);
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004706 if (wcmd != NULL)
4707 {
4708 int ret = _wsystem(wcmd);
4709 vim_free(wcmd);
4710 return ret;
4711 }
4712 }
4713 return system(cmd);
4714}
4715# else
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01004716# define mch_system(c, o) system(c)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004717# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004718
4719#endif
4720
4721/*
4722 * Either execute a command by calling the shell or start a new shell
4723 */
4724 int
4725mch_call_shell(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004726 char_u *cmd,
4727 int options) /* SHELL_*, see vim.h */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004728{
4729 int x = 0;
4730 int tmode = cur_tmode;
4731#ifdef FEAT_TITLE
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004732 char szShellTitle[512];
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004733# ifdef FEAT_MBYTE
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004734 int did_set_title = FALSE;
4735
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004736 /* Change the title to reflect that we are in a subshell. */
4737 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4738 {
4739 WCHAR szShellTitle[512];
4740
4741 if (GetConsoleTitleW(szShellTitle,
4742 sizeof(szShellTitle)/sizeof(WCHAR) - 4) > 0)
4743 {
4744 if (cmd == NULL)
4745 wcscat(szShellTitle, L" :sh");
4746 else
4747 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004748 WCHAR *wn = enc_to_utf16((char_u *)cmd, NULL);
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004749
4750 if (wn != NULL)
4751 {
4752 wcscat(szShellTitle, L" - !");
4753 if ((wcslen(szShellTitle) + wcslen(wn) <
4754 sizeof(szShellTitle)/sizeof(WCHAR)))
4755 wcscat(szShellTitle, wn);
4756 SetConsoleTitleW(szShellTitle);
4757 vim_free(wn);
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004758 did_set_title = TRUE;
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004759 }
4760 }
4761 }
4762 }
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004763 if (!did_set_title)
4764# endif
4765 /* Change the title to reflect that we are in a subshell. */
4766 if (GetConsoleTitle(szShellTitle, sizeof(szShellTitle) - 4) > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004767 {
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004768 if (cmd == NULL)
4769 strcat(szShellTitle, " :sh");
4770 else
4771 {
4772 strcat(szShellTitle, " - !");
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004773 if ((strlen(szShellTitle) + strlen((char *)cmd)
4774 < sizeof(szShellTitle)))
4775 strcat(szShellTitle, (char *)cmd);
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004776 }
4777 SetConsoleTitle(szShellTitle);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004778 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004779#endif
4780
4781 out_flush();
4782
4783#ifdef MCH_WRITE_DUMP
4784 if (fdDump)
4785 {
4786 fprintf(fdDump, "mch_call_shell(\"%s\", %d)\n", cmd, options);
4787 fflush(fdDump);
4788 }
4789#endif
4790
4791 /*
4792 * Catch all deadly signals while running the external command, because a
4793 * CTRL-C, Ctrl-Break or illegal instruction might otherwise kill us.
4794 */
4795 signal(SIGINT, SIG_IGN);
4796#if defined(__GNUC__) && !defined(__MINGW32__)
4797 signal(SIGKILL, SIG_IGN);
4798#else
4799 signal(SIGBREAK, SIG_IGN);
4800#endif
4801 signal(SIGILL, SIG_IGN);
4802 signal(SIGFPE, SIG_IGN);
4803 signal(SIGSEGV, SIG_IGN);
4804 signal(SIGTERM, SIG_IGN);
4805 signal(SIGABRT, SIG_IGN);
4806
4807 if (options & SHELL_COOKED)
4808 settmode(TMODE_COOK); /* set to normal mode */
4809
4810 if (cmd == NULL)
4811 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004812 x = mch_system((char *)p_sh, options);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004813 }
4814 else
4815 {
4816 /* we use "command" or "cmd" to start the shell; slow but easy */
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004817 char_u *newcmd = NULL;
4818 char_u *cmdbase = cmd;
4819 long_u cmdlen;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004820
4821 /* Skip a leading ", ( and "(. */
4822 if (*cmdbase == '"' )
4823 ++cmdbase;
4824 if (*cmdbase == '(')
4825 ++cmdbase;
4826
4827 if ((STRNICMP(cmdbase, "start", 5) == 0) && vim_iswhite(cmdbase[5]))
4828 {
4829 STARTUPINFO si;
4830 PROCESS_INFORMATION pi;
4831 DWORD flags = CREATE_NEW_CONSOLE;
4832 char_u *p;
4833
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01004834 ZeroMemory(&si, sizeof(si));
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004835 si.cb = sizeof(si);
4836 si.lpReserved = NULL;
4837 si.lpDesktop = NULL;
4838 si.lpTitle = NULL;
4839 si.dwFlags = 0;
4840 si.cbReserved2 = 0;
4841 si.lpReserved2 = NULL;
4842
4843 cmdbase = skipwhite(cmdbase + 5);
4844 if ((STRNICMP(cmdbase, "/min", 4) == 0)
4845 && vim_iswhite(cmdbase[4]))
4846 {
4847 cmdbase = skipwhite(cmdbase + 4);
4848 si.dwFlags = STARTF_USESHOWWINDOW;
4849 si.wShowWindow = SW_SHOWMINNOACTIVE;
4850 }
4851 else if ((STRNICMP(cmdbase, "/b", 2) == 0)
4852 && vim_iswhite(cmdbase[2]))
4853 {
4854 cmdbase = skipwhite(cmdbase + 2);
4855 flags = CREATE_NO_WINDOW;
4856 si.dwFlags = STARTF_USESTDHANDLES;
4857 si.hStdInput = CreateFile("\\\\.\\NUL", // File name
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004858 GENERIC_READ, // Access flags
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004859 0, // Share flags
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004860 NULL, // Security att.
4861 OPEN_EXISTING, // Open flags
4862 FILE_ATTRIBUTE_NORMAL, // File att.
4863 NULL); // Temp file
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004864 si.hStdOutput = si.hStdInput;
4865 si.hStdError = si.hStdInput;
4866 }
4867
4868 /* Remove a trailing ", ) and )" if they have a match
4869 * at the start of the command. */
4870 if (cmdbase > cmd)
4871 {
4872 p = cmdbase + STRLEN(cmdbase);
4873 if (p > cmdbase && p[-1] == '"' && *cmd == '"')
4874 *--p = NUL;
4875 if (p > cmdbase && p[-1] == ')'
4876 && (*cmd =='(' || cmd[1] == '('))
4877 *--p = NUL;
4878 }
4879
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004880 newcmd = cmdbase;
4881 unescape_shellxquote(cmdbase, p_sxe);
4882
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004883 /*
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004884 * If creating new console, arguments are passed to the
4885 * 'cmd.exe' as-is. If it's not, arguments are not treated
4886 * correctly for current 'cmd.exe'. So unescape characters in
4887 * shellxescape except '|' for avoiding to be treated as
4888 * argument to them. Pass the arguments to sub-shell.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004889 */
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004890 if (flags != CREATE_NEW_CONSOLE)
4891 {
4892 char_u *subcmd;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004893 char_u *cmd_shell = mch_getenv("COMSPEC");
4894
4895 if (cmd_shell == NULL || *cmd_shell == NUL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004896 cmd_shell = (char_u *)default_shell();
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004897
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004898 subcmd = vim_strsave_escaped_ext(cmdbase,
4899 (char_u *)"|", '^', FALSE);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004900 if (subcmd != NULL)
4901 {
4902 /* make "cmd.exe /c arguments" */
4903 cmdlen = STRLEN(cmd_shell) + STRLEN(subcmd) + 5;
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004904 newcmd = lalloc(cmdlen, TRUE);
4905 if (newcmd != NULL)
4906 vim_snprintf((char *)newcmd, cmdlen, "%s /c %s",
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004907 cmd_shell, subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004908 else
4909 newcmd = cmdbase;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004910 vim_free(subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004911 }
4912 }
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004913
4914 /*
4915 * Now, start the command as a process, so that it doesn't
4916 * inherit our handles which causes unpleasant dangling swap
4917 * files if we exit before the spawned process
4918 */
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004919 if (vim_create_process((char *)newcmd, FALSE, flags, &si, &pi))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004920 x = 0;
4921 else
4922 {
4923 x = -1;
4924#ifdef FEAT_GUI_W32
4925 EMSG(_("E371: Command not found"));
4926#endif
4927 }
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004928
4929 if (newcmd != cmdbase)
4930 vim_free(newcmd);
4931
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01004932 if (si.dwFlags == STARTF_USESTDHANDLES && si.hStdInput != NULL)
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004933 {
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01004934 /* Close the handle to \\.\NUL created above. */
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004935 CloseHandle(si.hStdInput);
4936 }
4937 /* Close the handles to the subprocess, so that it goes away */
4938 CloseHandle(pi.hThread);
4939 CloseHandle(pi.hProcess);
4940 }
4941 else
4942 {
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004943 cmdlen = (
Bram Moolenaar071d4272004-06-13 20:20:40 +00004944#ifdef FEAT_GUI_W32
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004945 (allowPiping && !p_stmp ? 0 : STRLEN(vimrun_path)) +
Bram Moolenaar071d4272004-06-13 20:20:40 +00004946#endif
Bram Moolenaar0fde2902008-03-16 13:54:13 +00004947 STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10);
4948
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004949 newcmd = lalloc(cmdlen, TRUE);
4950 if (newcmd != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004951 {
4952#if defined(FEAT_GUI_W32)
4953 if (need_vimrun_warning)
4954 {
4955 MessageBox(NULL,
4956 _("VIMRUN.EXE not found in your $PATH.\n"
4957 "External commands will not pause after completion.\n"
4958 "See :help win32-vimrun for more information."),
4959 _("Vim Warning"),
4960 MB_ICONWARNING);
4961 need_vimrun_warning = FALSE;
4962 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004963 if (!s_dont_use_vimrun && (!allowPiping || p_stmp))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004964 /* Use vimrun to execute the command. It opens a console
4965 * window, which can be closed without killing Vim. */
Bram Moolenaarcc448b32010-07-14 16:52:17 +02004966 vim_snprintf((char *)newcmd, cmdlen, "%s%s%s %s %s",
Bram Moolenaar071d4272004-06-13 20:20:40 +00004967 vimrun_path,
4968 (msg_silent != 0 || (options & SHELL_DOOUT))
4969 ? "-s " : "",
4970 p_sh, p_shcf, cmd);
4971 else
4972#endif
Bram Moolenaarcc448b32010-07-14 16:52:17 +02004973 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s",
Bram Moolenaar0fde2902008-03-16 13:54:13 +00004974 p_sh, p_shcf, cmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004975 x = mch_system((char *)newcmd, options);
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004976 vim_free(newcmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004977 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004978 }
4979 }
4980
4981 if (tmode == TMODE_RAW)
4982 settmode(TMODE_RAW); /* set to raw mode */
4983
4984 /* Print the return value, unless "vimrun" was used. */
4985 if (x != 0 && !(options & SHELL_SILENT) && !emsg_silent
4986#if defined(FEAT_GUI_W32)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004987 && ((options & SHELL_DOOUT) || s_dont_use_vimrun
4988 || (allowPiping && !p_stmp))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004989#endif
4990 )
4991 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004992 smsg((char_u *)_("shell returned %d"), x);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004993 msg_putchar('\n');
4994 }
4995#ifdef FEAT_TITLE
4996 resettitle();
4997#endif
4998
4999 signal(SIGINT, SIG_DFL);
5000#if defined(__GNUC__) && !defined(__MINGW32__)
5001 signal(SIGKILL, SIG_DFL);
5002#else
5003 signal(SIGBREAK, SIG_DFL);
5004#endif
5005 signal(SIGILL, SIG_DFL);
5006 signal(SIGFPE, SIG_DFL);
5007 signal(SIGSEGV, SIG_DFL);
5008 signal(SIGTERM, SIG_DFL);
5009 signal(SIGABRT, SIG_DFL);
5010
5011 return x;
5012}
5013
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005014#if defined(FEAT_JOB) || defined(PROTO)
5015 void
Bram Moolenaar9a6e33a2016-02-16 19:25:12 +01005016mch_start_job(char *cmd, job_T *job, jobopt_T *options)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005017{
5018 STARTUPINFO si;
5019 PROCESS_INFORMATION pi;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005020 HANDLE jo;
Bram Moolenaar16eb4f82016-02-14 23:02:34 +01005021# ifdef FEAT_CHANNEL
5022 channel_T *channel;
Bram Moolenaard8070362016-02-15 21:56:54 +01005023 HANDLE ifd[2];
5024 HANDLE ofd[2];
5025 HANDLE efd[2];
5026 SECURITY_ATTRIBUTES saAttr;
5027
5028 ifd[0] = INVALID_HANDLE_VALUE;
5029 ifd[1] = INVALID_HANDLE_VALUE;
5030 ofd[0] = INVALID_HANDLE_VALUE;
5031 ofd[1] = INVALID_HANDLE_VALUE;
5032 efd[0] = INVALID_HANDLE_VALUE;
5033 efd[1] = INVALID_HANDLE_VALUE;
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005034
5035 channel = add_channel();
5036 if (channel == NULL)
5037 return;
Bram Moolenaar16eb4f82016-02-14 23:02:34 +01005038# endif
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005039
Bram Moolenaar76467df2016-02-12 19:30:26 +01005040 jo = CreateJobObject(NULL, NULL);
5041 if (jo == NULL)
5042 {
5043 job->jv_status = JOB_FAILED;
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005044 goto failed;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005045 }
5046
5047 ZeroMemory(&pi, sizeof(pi));
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005048 ZeroMemory(&si, sizeof(si));
5049 si.cb = sizeof(si);
Bram Moolenaard8070362016-02-15 21:56:54 +01005050 si.dwFlags |= STARTF_USESHOWWINDOW;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005051 si.wShowWindow = SW_HIDE;
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005052
Bram Moolenaar5d54a042016-02-16 16:39:51 +01005053# ifdef FEAT_CHANNEL
Bram Moolenaard8070362016-02-15 21:56:54 +01005054 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
5055 saAttr.bInheritHandle = TRUE;
5056 saAttr.lpSecurityDescriptor = NULL;
5057 if (!CreatePipe(&ifd[0], &ifd[1], &saAttr, 0)
5058 || !pSetHandleInformation(ifd[1], HANDLE_FLAG_INHERIT, 0)
5059 || !CreatePipe(&ofd[0], &ofd[1], &saAttr, 0)
5060 || !pSetHandleInformation(ofd[0], HANDLE_FLAG_INHERIT, 0)
5061 || !CreatePipe(&efd[0], &efd[1], &saAttr, 0)
5062 || !pSetHandleInformation(efd[0], HANDLE_FLAG_INHERIT, 0))
5063 goto failed;
5064 si.dwFlags |= STARTF_USESTDHANDLES;
5065 si.hStdInput = ifd[0];
5066 si.hStdOutput = ofd[1];
5067 si.hStdError = efd[1];
Bram Moolenaar5d54a042016-02-16 16:39:51 +01005068# endif
Bram Moolenaard8070362016-02-15 21:56:54 +01005069
5070 if (!vim_create_process(cmd, TRUE,
Bram Moolenaar76467df2016-02-12 19:30:26 +01005071 CREATE_SUSPENDED |
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005072 CREATE_DEFAULT_ERROR_MODE |
5073 CREATE_NEW_PROCESS_GROUP |
Bram Moolenaar76467df2016-02-12 19:30:26 +01005074 CREATE_NEW_CONSOLE,
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005075 &si, &pi))
Bram Moolenaar76467df2016-02-12 19:30:26 +01005076 {
5077 CloseHandle(jo);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005078 job->jv_status = JOB_FAILED;
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005079 goto failed;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005080 }
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005081
5082 if (!AssignProcessToJobObject(jo, pi.hProcess))
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005083 {
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005084 /* if failing, switch the way to terminate
5085 * process with TerminateProcess. */
5086 CloseHandle(jo);
5087 jo = NULL;
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005088 }
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005089 ResumeThread(pi.hThread);
5090 CloseHandle(job->jv_proc_info.hThread);
5091 job->jv_proc_info = pi;
5092 job->jv_job_object = jo;
5093 job->jv_status = JOB_STARTED;
5094
Bram Moolenaar5d54a042016-02-16 16:39:51 +01005095# ifdef FEAT_CHANNEL
Bram Moolenaard8070362016-02-15 21:56:54 +01005096 CloseHandle(ifd[0]);
5097 CloseHandle(ofd[1]);
5098 CloseHandle(efd[1]);
5099
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005100 job->jv_channel = channel;
Bram Moolenaard8070362016-02-15 21:56:54 +01005101 channel_set_pipes(channel, (sock_T)ifd[1], (sock_T)ofd[0], (sock_T)efd[0]);
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005102 channel_set_job(channel, job);
Bram Moolenaar910b8aa2016-02-16 21:03:07 +01005103 channel_set_options(channel, options);
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005104
Bram Moolenaar16eb4f82016-02-14 23:02:34 +01005105# ifdef FEAT_GUI
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005106 channel_gui_register(channel);
Bram Moolenaar16eb4f82016-02-14 23:02:34 +01005107# endif
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005108# endif
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005109 return;
5110
5111failed:
Bram Moolenaar16eb4f82016-02-14 23:02:34 +01005112# ifdef FEAT_CHANNEL
Bram Moolenaard8070362016-02-15 21:56:54 +01005113 CloseHandle(ifd[0]);
5114 CloseHandle(ofd[0]);
5115 CloseHandle(efd[0]);
5116 CloseHandle(ifd[1]);
5117 CloseHandle(ofd[1]);
5118 CloseHandle(efd[1]);
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005119 channel_free(channel);
Bram Moolenaar71b0f7b2016-02-15 12:44:20 +01005120# else
5121 ; /* make compiler happy */
Bram Moolenaar16eb4f82016-02-14 23:02:34 +01005122# endif
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005123}
5124
5125 char *
5126mch_job_status(job_T *job)
5127{
5128 DWORD dwExitCode = 0;
5129
Bram Moolenaar76467df2016-02-12 19:30:26 +01005130 if (!GetExitCodeProcess(job->jv_proc_info.hProcess, &dwExitCode)
5131 || dwExitCode != STILL_ACTIVE)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005132 {
Bram Moolenaar76467df2016-02-12 19:30:26 +01005133 job->jv_status = JOB_ENDED;
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005134 return "dead";
5135 }
5136 return "run";
5137}
5138
5139 int
5140mch_stop_job(job_T *job, char_u *how)
5141{
Bram Moolenaar76467df2016-02-12 19:30:26 +01005142 int ret = 0;
5143 int ctrl_c = STRCMP(how, "int") == 0;
5144
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005145 if (STRCMP(how, "kill") == 0)
Bram Moolenaar76467df2016-02-12 19:30:26 +01005146 {
5147 if (job->jv_job_object != NULL)
5148 return TerminateJobObject(job->jv_job_object, 0) ? OK : FAIL;
5149 else
5150 return TerminateProcess(job->jv_proc_info.hProcess, 0) ? OK : FAIL;
5151 }
5152
5153 if (!AttachConsole(job->jv_proc_info.dwProcessId))
5154 return FAIL;
5155 ret = GenerateConsoleCtrlEvent(
5156 ctrl_c ? CTRL_C_EVENT : CTRL_BREAK_EVENT,
5157 job->jv_proc_info.dwProcessId)
5158 ? OK : FAIL;
5159 FreeConsole();
5160 return ret;
5161}
5162
5163/*
5164 * Clear the data related to "job".
5165 */
5166 void
5167mch_clear_job(job_T *job)
5168{
5169 if (job->jv_status != JOB_FAILED)
5170 {
5171 if (job->jv_job_object != NULL)
5172 CloseHandle(job->jv_job_object);
5173 CloseHandle(job->jv_proc_info.hProcess);
5174 }
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005175}
5176#endif
5177
Bram Moolenaar071d4272004-06-13 20:20:40 +00005178
5179#ifndef FEAT_GUI_W32
5180
5181/*
5182 * Start termcap mode
5183 */
5184 static void
5185termcap_mode_start(void)
5186{
5187 DWORD cmodein;
5188
5189 if (g_fTermcapMode)
5190 return;
5191
5192 SaveConsoleBuffer(&g_cbNonTermcap);
5193
5194 if (g_cbTermcap.IsValid)
5195 {
5196 /*
5197 * We've been in termcap mode before. Restore certain screen
5198 * characteristics, including the buffer size and the window
5199 * size. Since we will be redrawing the screen, we don't need
5200 * to restore the actual contents of the buffer.
5201 */
5202 RestoreConsoleBuffer(&g_cbTermcap, FALSE);
5203 SetConsoleWindowInfo(g_hConOut, TRUE, &g_cbTermcap.Info.srWindow);
5204 Rows = g_cbTermcap.Info.dwSize.Y;
5205 Columns = g_cbTermcap.Info.dwSize.X;
5206 }
5207 else
5208 {
5209 /*
5210 * This is our first time entering termcap mode. Clear the console
5211 * screen buffer, and resize the buffer to match the current window
5212 * size. We will use this as the size of our editing environment.
5213 */
5214 ClearConsoleBuffer(g_attrCurrent);
5215 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
5216 }
5217
5218#ifdef FEAT_TITLE
5219 resettitle();
5220#endif
5221
5222 GetConsoleMode(g_hConIn, &cmodein);
5223#ifdef FEAT_MOUSE
5224 if (g_fMouseActive)
5225 cmodein |= ENABLE_MOUSE_INPUT;
5226 else
5227 cmodein &= ~ENABLE_MOUSE_INPUT;
5228#endif
5229 cmodein |= ENABLE_WINDOW_INPUT;
5230 SetConsoleMode(g_hConIn, cmodein);
5231
5232 redraw_later_clear();
5233 g_fTermcapMode = TRUE;
5234}
5235
5236
5237/*
5238 * End termcap mode
5239 */
5240 static void
5241termcap_mode_end(void)
5242{
5243 DWORD cmodein;
5244 ConsoleBuffer *cb;
5245 COORD coord;
5246 DWORD dwDummy;
5247
5248 if (!g_fTermcapMode)
5249 return;
5250
5251 SaveConsoleBuffer(&g_cbTermcap);
5252
5253 GetConsoleMode(g_hConIn, &cmodein);
5254 cmodein &= ~(ENABLE_MOUSE_INPUT | ENABLE_WINDOW_INPUT);
5255 SetConsoleMode(g_hConIn, cmodein);
5256
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01005257#ifdef FEAT_RESTORE_ORIG_SCREEN
5258 cb = exiting ? &g_cbOrig : &g_cbNonTermcap;
5259#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00005260 cb = &g_cbNonTermcap;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01005261#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005262 RestoreConsoleBuffer(cb, p_rs);
5263 SetConsoleCursorInfo(g_hConOut, &g_cci);
5264
5265 if (p_rs || exiting)
5266 {
5267 /*
5268 * Clear anything that happens to be on the current line.
5269 */
5270 coord.X = 0;
5271 coord.Y = (SHORT) (p_rs ? cb->Info.dwCursorPosition.Y : (Rows - 1));
5272 FillConsoleOutputCharacter(g_hConOut, ' ',
5273 cb->Info.dwSize.X, coord, &dwDummy);
5274 /*
5275 * The following is just for aesthetics. If we are exiting without
5276 * restoring the screen, then we want to have a prompt string
5277 * appear at the bottom line. However, the command interpreter
5278 * seems to always advance the cursor one line before displaying
5279 * the prompt string, which causes the screen to scroll. To
5280 * counter this, move the cursor up one line before exiting.
5281 */
5282 if (exiting && !p_rs)
5283 coord.Y--;
5284 /*
5285 * Position the cursor at the leftmost column of the desired row.
5286 */
5287 SetConsoleCursorPosition(g_hConOut, coord);
5288 }
5289
5290 g_fTermcapMode = FALSE;
5291}
5292#endif /* FEAT_GUI_W32 */
5293
5294
5295#ifdef FEAT_GUI_W32
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00005296/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00005297 void
5298mch_write(
5299 char_u *s,
5300 int len)
5301{
5302 /* never used */
5303}
5304
5305#else
5306
5307/*
5308 * clear `n' chars, starting from `coord'
5309 */
5310 static void
5311clear_chars(
5312 COORD coord,
5313 DWORD n)
5314{
5315 DWORD dwDummy;
5316
5317 FillConsoleOutputCharacter(g_hConOut, ' ', n, coord, &dwDummy);
5318 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, n, coord, &dwDummy);
5319}
5320
5321
5322/*
5323 * Clear the screen
5324 */
5325 static void
5326clear_screen(void)
5327{
5328 g_coord.X = g_coord.Y = 0;
5329 clear_chars(g_coord, Rows * Columns);
5330}
5331
5332
5333/*
5334 * Clear to end of display
5335 */
5336 static void
5337clear_to_end_of_display(void)
5338{
5339 clear_chars(g_coord, (Rows - g_coord.Y - 1)
5340 * Columns + (Columns - g_coord.X));
5341}
5342
5343
5344/*
5345 * Clear to end of line
5346 */
5347 static void
5348clear_to_end_of_line(void)
5349{
5350 clear_chars(g_coord, Columns - g_coord.X);
5351}
5352
5353
5354/*
5355 * Scroll the scroll region up by `cLines' lines
5356 */
5357 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005358scroll(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005359{
5360 COORD oldcoord = g_coord;
5361
5362 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
5363 delete_lines(cLines);
5364
5365 g_coord = oldcoord;
5366}
5367
5368
5369/*
5370 * Set the scroll region
5371 */
5372 static void
5373set_scroll_region(
5374 unsigned left,
5375 unsigned top,
5376 unsigned right,
5377 unsigned bottom)
5378{
5379 if (left >= right
5380 || top >= bottom
5381 || right > (unsigned) Columns - 1
5382 || bottom > (unsigned) Rows - 1)
5383 return;
5384
5385 g_srScrollRegion.Left = left;
5386 g_srScrollRegion.Top = top;
5387 g_srScrollRegion.Right = right;
5388 g_srScrollRegion.Bottom = bottom;
5389}
5390
5391
5392/*
5393 * Insert `cLines' lines at the current cursor position
5394 */
5395 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005396insert_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005397{
5398 SMALL_RECT source;
5399 COORD dest;
5400 CHAR_INFO fill;
5401
5402 dest.X = 0;
5403 dest.Y = g_coord.Y + cLines;
5404
5405 source.Left = 0;
5406 source.Top = g_coord.Y;
5407 source.Right = g_srScrollRegion.Right;
5408 source.Bottom = g_srScrollRegion.Bottom - cLines;
5409
5410 fill.Char.AsciiChar = ' ';
5411 fill.Attributes = g_attrCurrent;
5412
5413 ScrollConsoleScreenBuffer(g_hConOut, &source, NULL, dest, &fill);
5414
5415 /* Here we have to deal with a win32 console flake: If the scroll
5416 * region looks like abc and we scroll c to a and fill with d we get
5417 * cbd... if we scroll block c one line at a time to a, we get cdd...
5418 * vim expects cdd consistently... So we have to deal with that
5419 * here... (this also occurs scrolling the same way in the other
5420 * direction). */
5421
5422 if (source.Bottom < dest.Y)
5423 {
5424 COORD coord;
5425
5426 coord.X = 0;
5427 coord.Y = source.Bottom;
5428 clear_chars(coord, Columns * (dest.Y - source.Bottom));
5429 }
5430}
5431
5432
5433/*
5434 * Delete `cLines' lines at the current cursor position
5435 */
5436 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005437delete_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005438{
5439 SMALL_RECT source;
5440 COORD dest;
5441 CHAR_INFO fill;
5442 int nb;
5443
5444 dest.X = 0;
5445 dest.Y = g_coord.Y;
5446
5447 source.Left = 0;
5448 source.Top = g_coord.Y + cLines;
5449 source.Right = g_srScrollRegion.Right;
5450 source.Bottom = g_srScrollRegion.Bottom;
5451
5452 fill.Char.AsciiChar = ' ';
5453 fill.Attributes = g_attrCurrent;
5454
5455 ScrollConsoleScreenBuffer(g_hConOut, &source, NULL, dest, &fill);
5456
5457 /* Here we have to deal with a win32 console flake: If the scroll
5458 * region looks like abc and we scroll c to a and fill with d we get
5459 * cbd... if we scroll block c one line at a time to a, we get cdd...
5460 * vim expects cdd consistently... So we have to deal with that
5461 * here... (this also occurs scrolling the same way in the other
5462 * direction). */
5463
5464 nb = dest.Y + (source.Bottom - source.Top) + 1;
5465
5466 if (nb < source.Top)
5467 {
5468 COORD coord;
5469
5470 coord.X = 0;
5471 coord.Y = nb;
5472 clear_chars(coord, Columns * (source.Top - nb));
5473 }
5474}
5475
5476
5477/*
5478 * Set the cursor position
5479 */
5480 static void
5481gotoxy(
5482 unsigned x,
5483 unsigned y)
5484{
5485 if (x < 1 || x > (unsigned)Columns || y < 1 || y > (unsigned)Rows)
5486 return;
5487
5488 /* external cursor coords are 1-based; internal are 0-based */
5489 g_coord.X = x - 1;
5490 g_coord.Y = y - 1;
5491 SetConsoleCursorPosition(g_hConOut, g_coord);
5492}
5493
5494
5495/*
5496 * Set the current text attribute = (foreground | background)
5497 * See ../doc/os_win32.txt for the numbers.
5498 */
5499 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005500textattr(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005501{
Bram Moolenaar6383b922015-03-24 17:12:19 +01005502 g_attrCurrent = wAttr & 0xff;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005503
5504 SetConsoleTextAttribute(g_hConOut, wAttr);
5505}
5506
5507
5508 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005509textcolor(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005510{
Bram Moolenaar6383b922015-03-24 17:12:19 +01005511 g_attrCurrent = (g_attrCurrent & 0xf0) + (wAttr & 0x0f);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005512
5513 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
5514}
5515
5516
5517 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005518textbackground(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005519{
Bram Moolenaar6383b922015-03-24 17:12:19 +01005520 g_attrCurrent = (g_attrCurrent & 0x0f) + ((wAttr & 0x0f) << 4);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005521
5522 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
5523}
5524
5525
5526/*
5527 * restore the default text attribute (whatever we started with)
5528 */
5529 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005530normvideo(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005531{
5532 textattr(g_attrDefault);
5533}
5534
5535
5536static WORD g_attrPreStandout = 0;
5537
5538/*
5539 * Make the text standout, by brightening it
5540 */
5541 static void
5542standout(void)
5543{
5544 g_attrPreStandout = g_attrCurrent;
5545 textattr((WORD) (g_attrCurrent|FOREGROUND_INTENSITY|BACKGROUND_INTENSITY));
5546}
5547
5548
5549/*
5550 * Turn off standout mode
5551 */
5552 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005553standend(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005554{
5555 if (g_attrPreStandout)
5556 {
5557 textattr(g_attrPreStandout);
5558 g_attrPreStandout = 0;
5559 }
5560}
5561
5562
5563/*
Bram Moolenaarff1d0d42007-05-10 17:24:16 +00005564 * Set normal fg/bg color, based on T_ME. Called when t_me has been set.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005565 */
5566 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005567mch_set_normal_colors(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005568{
5569 char_u *p;
5570 int n;
5571
5572 cterm_normal_fg_color = (g_attrDefault & 0xf) + 1;
5573 cterm_normal_bg_color = ((g_attrDefault >> 4) & 0xf) + 1;
5574 if (T_ME[0] == ESC && T_ME[1] == '|')
5575 {
5576 p = T_ME + 2;
5577 n = getdigits(&p);
5578 if (*p == 'm' && n > 0)
5579 {
5580 cterm_normal_fg_color = (n & 0xf) + 1;
5581 cterm_normal_bg_color = ((n >> 4) & 0xf) + 1;
5582 }
5583 }
5584}
5585
5586
5587/*
5588 * visual bell: flash the screen
5589 */
5590 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005591visual_bell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005592{
5593 COORD coordOrigin = {0, 0};
5594 WORD attrFlash = ~g_attrCurrent & 0xff;
5595
5596 DWORD dwDummy;
5597 LPWORD oldattrs = (LPWORD)alloc(Rows * Columns * sizeof(WORD));
5598
5599 if (oldattrs == NULL)
5600 return;
5601 ReadConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
5602 coordOrigin, &dwDummy);
5603 FillConsoleOutputAttribute(g_hConOut, attrFlash, Rows * Columns,
5604 coordOrigin, &dwDummy);
5605
5606 Sleep(15); /* wait for 15 msec */
5607 WriteConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
5608 coordOrigin, &dwDummy);
5609 vim_free(oldattrs);
5610}
5611
5612
5613/*
5614 * Make the cursor visible or invisible
5615 */
5616 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005617cursor_visible(BOOL fVisible)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005618{
5619 s_cursor_visible = fVisible;
5620#ifdef MCH_CURSOR_SHAPE
5621 mch_update_cursor();
5622#endif
5623}
5624
5625
5626/*
Bram Moolenaarac360bf2015-09-01 20:31:20 +02005627 * write `cbToWrite' bytes in `pchBuf' to the screen
5628 * Returns the number of bytes actually written (at least one).
Bram Moolenaar071d4272004-06-13 20:20:40 +00005629 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02005630 static DWORD
Bram Moolenaar071d4272004-06-13 20:20:40 +00005631write_chars(
Bram Moolenaarac360bf2015-09-01 20:31:20 +02005632 char_u *pchBuf,
5633 DWORD cbToWrite)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005634{
5635 COORD coord = g_coord;
5636 DWORD written;
5637
Bram Moolenaarac360bf2015-09-01 20:31:20 +02005638#ifdef FEAT_MBYTE
5639 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
5640 {
5641 static WCHAR *unicodebuf = NULL;
5642 static int unibuflen = 0;
5643 int length;
5644 DWORD n, cchwritten, cells;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005645
Bram Moolenaarac360bf2015-09-01 20:31:20 +02005646 length = MultiByteToWideChar(CP_UTF8, 0, (LPCSTR)pchBuf, cbToWrite, 0, 0);
5647 if (unicodebuf == NULL || length > unibuflen)
5648 {
5649 vim_free(unicodebuf);
5650 unicodebuf = (WCHAR *)lalloc(length * sizeof(WCHAR), FALSE);
5651 unibuflen = length;
5652 }
5653 MultiByteToWideChar(CP_UTF8, 0, (LPCSTR)pchBuf, cbToWrite,
5654 unicodebuf, unibuflen);
5655
5656 cells = mb_string2cells(pchBuf, cbToWrite);
5657 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, cells,
5658 coord, &written);
5659 /* When writing fails or didn't write a single character, pretend one
5660 * character was written, otherwise we get stuck. */
5661 if (WriteConsoleOutputCharacterW(g_hConOut, unicodebuf, length,
5662 coord, &cchwritten) == 0
5663 || cchwritten == 0)
5664 cchwritten = 1;
5665
5666 if (cchwritten == length)
5667 {
5668 written = cbToWrite;
5669 g_coord.X += (SHORT)cells;
5670 }
5671 else
5672 {
5673 char_u *p = pchBuf;
5674 for (n = 0; n < cchwritten; n++)
5675 mb_cptr_adv(p);
5676 written = p - pchBuf;
5677 g_coord.X += (SHORT)mb_string2cells(pchBuf, written);
5678 }
5679 }
5680 else
5681#endif
5682 {
5683 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, cbToWrite,
5684 coord, &written);
5685 /* When writing fails or didn't write a single character, pretend one
5686 * character was written, otherwise we get stuck. */
5687 if (WriteConsoleOutputCharacter(g_hConOut, (LPCSTR)pchBuf, cbToWrite,
5688 coord, &written) == 0
5689 || written == 0)
5690 written = 1;
5691
5692 g_coord.X += (SHORT) written;
5693 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005694
5695 while (g_coord.X > g_srScrollRegion.Right)
5696 {
5697 g_coord.X -= (SHORT) Columns;
5698 if (g_coord.Y < g_srScrollRegion.Bottom)
5699 g_coord.Y++;
5700 }
5701
5702 gotoxy(g_coord.X + 1, g_coord.Y + 1);
5703
5704 return written;
5705}
5706
5707
5708/*
5709 * mch_write(): write the output buffer to the screen, translating ESC
5710 * sequences into calls to console output routines.
5711 */
5712 void
5713mch_write(
5714 char_u *s,
5715 int len)
5716{
5717 s[len] = NUL;
5718
5719 if (!term_console)
5720 {
5721 write(1, s, (unsigned)len);
5722 return;
5723 }
5724
5725 /* translate ESC | sequences into faked bios calls */
5726 while (len--)
5727 {
5728 /* optimization: use one single write_chars for runs of text,
5729 * rather than once per character It ain't curses, but it helps. */
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01005730 DWORD prefix = (DWORD)strcspn((char *)s, "\n\r\b\a\033");
Bram Moolenaar071d4272004-06-13 20:20:40 +00005731
5732 if (p_wd)
5733 {
5734 WaitForChar(p_wd);
5735 if (prefix != 0)
5736 prefix = 1;
5737 }
5738
5739 if (prefix != 0)
5740 {
5741 DWORD nWritten;
5742
5743 nWritten = write_chars(s, prefix);
5744#ifdef MCH_WRITE_DUMP
5745 if (fdDump)
5746 {
5747 fputc('>', fdDump);
5748 fwrite(s, sizeof(char_u), nWritten, fdDump);
5749 fputs("<\n", fdDump);
5750 }
5751#endif
5752 len -= (nWritten - 1);
5753 s += nWritten;
5754 }
5755 else if (s[0] == '\n')
5756 {
5757 /* \n, newline: go to the beginning of the next line or scroll */
5758 if (g_coord.Y == g_srScrollRegion.Bottom)
5759 {
5760 scroll(1);
5761 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Bottom + 1);
5762 }
5763 else
5764 {
5765 gotoxy(g_srScrollRegion.Left + 1, g_coord.Y + 2);
5766 }
5767#ifdef MCH_WRITE_DUMP
5768 if (fdDump)
5769 fputs("\\n\n", fdDump);
5770#endif
5771 s++;
5772 }
5773 else if (s[0] == '\r')
5774 {
5775 /* \r, carriage return: go to beginning of line */
5776 gotoxy(g_srScrollRegion.Left+1, g_coord.Y + 1);
5777#ifdef MCH_WRITE_DUMP
5778 if (fdDump)
5779 fputs("\\r\n", fdDump);
5780#endif
5781 s++;
5782 }
5783 else if (s[0] == '\b')
5784 {
5785 /* \b, backspace: move cursor one position left */
5786 if (g_coord.X > g_srScrollRegion.Left)
5787 g_coord.X--;
5788 else if (g_coord.Y > g_srScrollRegion.Top)
5789 {
5790 g_coord.X = g_srScrollRegion.Right;
5791 g_coord.Y--;
5792 }
5793 gotoxy(g_coord.X + 1, g_coord.Y + 1);
5794#ifdef MCH_WRITE_DUMP
5795 if (fdDump)
5796 fputs("\\b\n", fdDump);
5797#endif
5798 s++;
5799 }
5800 else if (s[0] == '\a')
5801 {
5802 /* \a, bell */
5803 MessageBeep(0xFFFFFFFF);
5804#ifdef MCH_WRITE_DUMP
5805 if (fdDump)
5806 fputs("\\a\n", fdDump);
5807#endif
5808 s++;
5809 }
5810 else if (s[0] == ESC && len >= 3-1 && s[1] == '|')
5811 {
5812#ifdef MCH_WRITE_DUMP
Bram Moolenaarc0197e22004-09-13 20:26:32 +00005813 char_u *old_s = s;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005814#endif
Bram Moolenaarc0197e22004-09-13 20:26:32 +00005815 char_u *p;
5816 int arg1 = 0, arg2 = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005817
5818 switch (s[2])
5819 {
5820 /* one or two numeric arguments, separated by ';' */
5821
5822 case '0': case '1': case '2': case '3': case '4':
5823 case '5': case '6': case '7': case '8': case '9':
5824 p = s + 2;
5825 arg1 = getdigits(&p); /* no check for length! */
5826 if (p > s + len)
5827 break;
5828
5829 if (*p == ';')
5830 {
5831 ++p;
5832 arg2 = getdigits(&p); /* no check for length! */
5833 if (p > s + len)
5834 break;
5835
5836 if (*p == 'H')
5837 gotoxy(arg2, arg1);
5838 else if (*p == 'r')
5839 set_scroll_region(0, arg1 - 1, Columns - 1, arg2 - 1);
5840 }
5841 else if (*p == 'A')
5842 {
5843 /* move cursor up arg1 lines in same column */
5844 gotoxy(g_coord.X + 1,
5845 max(g_srScrollRegion.Top, g_coord.Y - arg1) + 1);
5846 }
5847 else if (*p == 'C')
5848 {
5849 /* move cursor right arg1 columns in same line */
5850 gotoxy(min(g_srScrollRegion.Right, g_coord.X + arg1) + 1,
5851 g_coord.Y + 1);
5852 }
5853 else if (*p == 'H')
5854 {
5855 gotoxy(1, arg1);
5856 }
5857 else if (*p == 'L')
5858 {
5859 insert_lines(arg1);
5860 }
5861 else if (*p == 'm')
5862 {
5863 if (arg1 == 0)
5864 normvideo();
5865 else
5866 textattr((WORD) arg1);
5867 }
5868 else if (*p == 'f')
5869 {
5870 textcolor((WORD) arg1);
5871 }
5872 else if (*p == 'b')
5873 {
5874 textbackground((WORD) arg1);
5875 }
5876 else if (*p == 'M')
5877 {
5878 delete_lines(arg1);
5879 }
5880
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005881 len -= (int)(p - s);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005882 s = p + 1;
5883 break;
5884
5885
5886 /* Three-character escape sequences */
5887
5888 case 'A':
5889 /* move cursor up one line in same column */
5890 gotoxy(g_coord.X + 1,
5891 max(g_srScrollRegion.Top, g_coord.Y - 1) + 1);
5892 goto got3;
5893
5894 case 'B':
5895 visual_bell();
5896 goto got3;
5897
5898 case 'C':
5899 /* move cursor right one column in same line */
5900 gotoxy(min(g_srScrollRegion.Right, g_coord.X + 1) + 1,
5901 g_coord.Y + 1);
5902 goto got3;
5903
5904 case 'E':
5905 termcap_mode_end();
5906 goto got3;
5907
5908 case 'F':
5909 standout();
5910 goto got3;
5911
5912 case 'f':
5913 standend();
5914 goto got3;
5915
5916 case 'H':
5917 gotoxy(1, 1);
5918 goto got3;
5919
5920 case 'j':
5921 clear_to_end_of_display();
5922 goto got3;
5923
5924 case 'J':
5925 clear_screen();
5926 goto got3;
5927
5928 case 'K':
5929 clear_to_end_of_line();
5930 goto got3;
5931
5932 case 'L':
5933 insert_lines(1);
5934 goto got3;
5935
5936 case 'M':
5937 delete_lines(1);
5938 goto got3;
5939
5940 case 'S':
5941 termcap_mode_start();
5942 goto got3;
5943
5944 case 'V':
5945 cursor_visible(TRUE);
5946 goto got3;
5947
5948 case 'v':
5949 cursor_visible(FALSE);
5950 goto got3;
5951
5952 got3:
5953 s += 3;
5954 len -= 2;
5955 }
5956
5957#ifdef MCH_WRITE_DUMP
5958 if (fdDump)
5959 {
5960 fputs("ESC | ", fdDump);
5961 fwrite(old_s + 2, sizeof(char_u), s - old_s - 2, fdDump);
5962 fputc('\n', fdDump);
5963 }
5964#endif
5965 }
5966 else
5967 {
5968 /* Write a single character */
5969 DWORD nWritten;
5970
5971 nWritten = write_chars(s, 1);
5972#ifdef MCH_WRITE_DUMP
5973 if (fdDump)
5974 {
5975 fputc('>', fdDump);
5976 fwrite(s, sizeof(char_u), nWritten, fdDump);
5977 fputs("<\n", fdDump);
5978 }
5979#endif
5980
5981 len -= (nWritten - 1);
5982 s += nWritten;
5983 }
5984 }
5985
5986#ifdef MCH_WRITE_DUMP
5987 if (fdDump)
5988 fflush(fdDump);
5989#endif
5990}
5991
5992#endif /* FEAT_GUI_W32 */
5993
5994
5995/*
5996 * Delay for half a second.
5997 */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00005998/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00005999 void
6000mch_delay(
6001 long msec,
6002 int ignoreinput)
6003{
6004#ifdef FEAT_GUI_W32
6005 Sleep((int)msec); /* never wait for input */
Bram Moolenaar325b7a22004-07-05 15:58:32 +00006006#else /* Console */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006007 if (ignoreinput)
Bram Moolenaar325b7a22004-07-05 15:58:32 +00006008# ifdef FEAT_MZSCHEME
6009 if (mzthreads_allowed() && p_mzq > 0 && msec > p_mzq)
6010 {
6011 int towait = p_mzq;
6012
6013 /* if msec is large enough, wait by portions in p_mzq */
6014 while (msec > 0)
6015 {
6016 mzvim_check_threads();
6017 if (msec < towait)
6018 towait = msec;
6019 Sleep(towait);
6020 msec -= towait;
6021 }
6022 }
6023 else
6024# endif
6025 Sleep((int)msec);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006026 else
6027 WaitForChar(msec);
6028#endif
6029}
6030
6031
6032/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01006033 * This version of remove is not scared by a readonly (backup) file.
6034 * This can also remove a symbolic link like Unix.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006035 * Return 0 for success, -1 for failure.
6036 */
6037 int
6038mch_remove(char_u *name)
6039{
6040#ifdef FEAT_MBYTE
6041 WCHAR *wn = NULL;
6042 int n;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02006043#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006044
Bram Moolenaar203258c2016-01-17 22:15:16 +01006045 /*
6046 * On Windows, deleting a directory's symbolic link is done by
6047 * RemoveDirectory(): mch_rmdir. It seems unnatural, but it is fact.
6048 */
6049 if (mch_isdir(name) && mch_is_symbolic_link(name))
6050 return mch_rmdir(name);
6051
Bram Moolenaar12b559e2013-06-12 22:41:37 +02006052 win32_setattrs(name, FILE_ATTRIBUTE_NORMAL);
6053
6054#ifdef FEAT_MBYTE
Bram Moolenaar071d4272004-06-13 20:20:40 +00006055 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
6056 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006057 wn = enc_to_utf16(name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006058 if (wn != NULL)
6059 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006060 n = DeleteFileW(wn) ? 0 : -1;
6061 vim_free(wn);
6062 if (n == 0 || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
6063 return n;
6064 /* Retry with non-wide function (for Windows 98). */
6065 }
6066 }
6067#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006068 return DeleteFile((LPCSTR)name) ? 0 : -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006069}
6070
6071
6072/*
6073 * check for an "interrupt signal": CTRL-break or CTRL-C
6074 */
6075 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006076mch_breakcheck(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006077{
6078#ifndef FEAT_GUI_W32 /* never used */
6079 if (g_fCtrlCPressed || g_fCBrkPressed)
6080 {
6081 g_fCtrlCPressed = g_fCBrkPressed = FALSE;
6082 got_int = TRUE;
6083 }
6084#endif
6085}
6086
Bram Moolenaaree273972016-01-02 21:11:51 +01006087/* physical RAM to leave for the OS */
6088#define WINNT_RESERVE_BYTES (256*1024*1024)
6089#define WIN95_RESERVE_BYTES (8*1024*1024)
6090
6091/*
6092 * How much main memory in KiB that can be used by VIM.
6093 */
6094/*ARGSUSED*/
6095 long_u
6096mch_total_mem(int special)
6097{
6098 PlatformId();
6099#if (defined(_MSC_VER) && (WINVER > 0x0400)) || defined(MEMORYSTATUSEX)
6100 if (g_PlatformId == VER_PLATFORM_WIN32_NT)
6101 {
6102 MEMORYSTATUSEX ms;
6103
6104 /* Need to use GlobalMemoryStatusEx() when there is more memory than
6105 * what fits in 32 bits. But it's not always available. */
6106 ms.dwLength = sizeof(MEMORYSTATUSEX);
6107 GlobalMemoryStatusEx(&ms);
6108 if (ms.ullAvailVirtual < ms.ullTotalPhys)
6109 {
6110 /* Process address space fits in physical RAM, use all of it. */
6111 return (long_u)(ms.ullAvailVirtual / 1024);
6112 }
6113 if (ms.ullTotalPhys <= WINNT_RESERVE_BYTES)
6114 {
6115 /* Catch old NT box or perverse hardware setup. */
6116 return (long_u)((ms.ullTotalPhys / 2) / 1024);
6117 }
6118 /* Use physical RAM less reserve for OS + data. */
6119 return (long_u)((ms.ullTotalPhys - WINNT_RESERVE_BYTES) / 1024);
6120 }
6121 else
6122#endif
6123 {
6124 /* Pre-XP or 95 OS handling. */
6125 MEMORYSTATUS ms;
6126 long_u os_reserve_bytes;
6127
6128 ms.dwLength = sizeof(MEMORYSTATUS);
6129 GlobalMemoryStatus(&ms);
6130 if (ms.dwAvailVirtual < ms.dwTotalPhys)
6131 {
6132 /* Process address space fits in physical RAM, use all of it. */
6133 return (long_u)(ms.dwAvailVirtual / 1024);
6134 }
6135 os_reserve_bytes = (g_PlatformId == VER_PLATFORM_WIN32_NT)
6136 ? WINNT_RESERVE_BYTES
6137 : WIN95_RESERVE_BYTES;
6138 if (ms.dwTotalPhys <= os_reserve_bytes)
6139 {
6140 /* Catch old boxes or perverse hardware setup. */
6141 return (long_u)((ms.dwTotalPhys / 2) / 1024);
6142 }
6143 /* Use physical RAM less reserve for OS + data. */
6144 return (long_u)((ms.dwTotalPhys - os_reserve_bytes) / 1024);
6145 }
6146}
Bram Moolenaar071d4272004-06-13 20:20:40 +00006147
Bram Moolenaar071d4272004-06-13 20:20:40 +00006148#ifdef FEAT_MBYTE
6149/*
6150 * Same code as below, but with wide functions and no comments.
6151 * Return 0 for success, non-zero for failure.
6152 */
6153 int
6154mch_wrename(WCHAR *wold, WCHAR *wnew)
6155{
6156 WCHAR *p;
6157 int i;
6158 WCHAR szTempFile[_MAX_PATH + 1];
6159 WCHAR szNewPath[_MAX_PATH + 1];
6160 HANDLE hf;
6161
6162 if (!mch_windows95())
6163 {
6164 p = wold;
6165 for (i = 0; wold[i] != NUL; ++i)
6166 if ((wold[i] == '/' || wold[i] == '\\' || wold[i] == ':')
6167 && wold[i + 1] != 0)
6168 p = wold + i + 1;
6169 if ((int)(wold + i - p) < 8 || p[6] != '~')
6170 return (MoveFileW(wold, wnew) == 0);
6171 }
6172
6173 if (GetFullPathNameW(wnew, _MAX_PATH, szNewPath, &p) == 0 || p == NULL)
6174 return -1;
6175 *p = NUL;
6176
6177 if (GetTempFileNameW(szNewPath, L"VIM", 0, szTempFile) == 0)
6178 return -2;
6179
6180 if (!DeleteFileW(szTempFile))
6181 return -3;
6182
6183 if (!MoveFileW(wold, szTempFile))
6184 return -4;
6185
6186 if ((hf = CreateFileW(wold, GENERIC_WRITE, 0, NULL, CREATE_NEW,
6187 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
6188 return -5;
6189 if (!CloseHandle(hf))
6190 return -6;
6191
6192 if (!MoveFileW(szTempFile, wnew))
6193 {
6194 (void)MoveFileW(szTempFile, wold);
6195 return -7;
6196 }
6197
6198 DeleteFileW(szTempFile);
6199
6200 if (!DeleteFileW(wold))
6201 return -8;
6202
6203 return 0;
6204}
6205#endif
6206
6207
6208/*
6209 * mch_rename() works around a bug in rename (aka MoveFile) in
6210 * Windows 95: rename("foo.bar", "foo.bar~") will generate a
6211 * file whose short file name is "FOO.BAR" (its long file name will
6212 * be correct: "foo.bar~"). Because a file can be accessed by
6213 * either its SFN or its LFN, "foo.bar" has effectively been
6214 * renamed to "foo.bar", which is not at all what was wanted. This
6215 * seems to happen only when renaming files with three-character
6216 * extensions by appending a suffix that does not include ".".
6217 * Windows NT gets it right, however, with an SFN of "FOO~1.BAR".
6218 *
6219 * There is another problem, which isn't really a bug but isn't right either:
6220 * When renaming "abcdef~1.txt" to "abcdef~1.txt~", the short name can be
6221 * "abcdef~1.txt" again. This has been reported on Windows NT 4.0 with
6222 * service pack 6. Doesn't seem to happen on Windows 98.
6223 *
6224 * Like rename(), returns 0 upon success, non-zero upon failure.
6225 * Should probably set errno appropriately when errors occur.
6226 */
6227 int
6228mch_rename(
6229 const char *pszOldFile,
6230 const char *pszNewFile)
6231{
6232 char szTempFile[_MAX_PATH+1];
6233 char szNewPath[_MAX_PATH+1];
6234 char *pszFilePart;
6235 HANDLE hf;
6236#ifdef FEAT_MBYTE
6237 WCHAR *wold = NULL;
6238 WCHAR *wnew = NULL;
6239 int retval = -1;
6240
6241 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
6242 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006243 wold = enc_to_utf16((char_u *)pszOldFile, NULL);
6244 wnew = enc_to_utf16((char_u *)pszNewFile, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006245 if (wold != NULL && wnew != NULL)
6246 retval = mch_wrename(wold, wnew);
6247 vim_free(wold);
6248 vim_free(wnew);
6249 if (retval == 0 || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
6250 return retval;
6251 /* Retry with non-wide function (for Windows 98). */
6252 }
6253#endif
6254
6255 /*
6256 * No need to play tricks if not running Windows 95, unless the file name
6257 * contains a "~" as the seventh character.
6258 */
6259 if (!mch_windows95())
6260 {
6261 pszFilePart = (char *)gettail((char_u *)pszOldFile);
6262 if (STRLEN(pszFilePart) < 8 || pszFilePart[6] != '~')
6263 return rename(pszOldFile, pszNewFile);
6264 }
6265
6266 /* Get base path of new file name. Undocumented feature: If pszNewFile is
6267 * a directory, no error is returned and pszFilePart will be NULL. */
6268 if (GetFullPathName(pszNewFile, _MAX_PATH, szNewPath, &pszFilePart) == 0
6269 || pszFilePart == NULL)
6270 return -1;
6271 *pszFilePart = NUL;
6272
6273 /* Get (and create) a unique temporary file name in directory of new file */
6274 if (GetTempFileName(szNewPath, "VIM", 0, szTempFile) == 0)
6275 return -2;
6276
6277 /* blow the temp file away */
6278 if (!DeleteFile(szTempFile))
6279 return -3;
6280
6281 /* rename old file to the temp file */
6282 if (!MoveFile(pszOldFile, szTempFile))
6283 return -4;
6284
6285 /* now create an empty file called pszOldFile; this prevents the operating
6286 * system using pszOldFile as an alias (SFN) if we're renaming within the
6287 * same directory. For example, we're editing a file called
6288 * filename.asc.txt by its SFN, filena~1.txt. If we rename filena~1.txt
6289 * to filena~1.txt~ (i.e., we're making a backup while writing it), the
6290 * SFN for filena~1.txt~ will be filena~1.txt, by default, which will
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006291 * cause all sorts of problems later in buf_write(). So, we create an
6292 * empty file called filena~1.txt and the system will have to find some
6293 * other SFN for filena~1.txt~, such as filena~2.txt
Bram Moolenaar071d4272004-06-13 20:20:40 +00006294 */
6295 if ((hf = CreateFile(pszOldFile, GENERIC_WRITE, 0, NULL, CREATE_NEW,
6296 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
6297 return -5;
6298 if (!CloseHandle(hf))
6299 return -6;
6300
6301 /* rename the temp file to the new file */
6302 if (!MoveFile(szTempFile, pszNewFile))
6303 {
6304 /* Renaming failed. Rename the file back to its old name, so that it
6305 * looks like nothing happened. */
6306 (void)MoveFile(szTempFile, pszOldFile);
6307
6308 return -7;
6309 }
6310
6311 /* Seems to be left around on Novell filesystems */
6312 DeleteFile(szTempFile);
6313
6314 /* finally, remove the empty old file */
6315 if (!DeleteFile(pszOldFile))
6316 return -8;
6317
6318 return 0; /* success */
6319}
6320
6321/*
6322 * Get the default shell for the current hardware platform
6323 */
6324 char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006325default_shell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006326{
6327 char* psz = NULL;
6328
6329 PlatformId();
6330
6331 if (g_PlatformId == VER_PLATFORM_WIN32_NT) /* Windows NT */
6332 psz = "cmd.exe";
6333 else if (g_PlatformId == VER_PLATFORM_WIN32_WINDOWS) /* Windows 95 */
6334 psz = "command.com";
6335
6336 return psz;
6337}
6338
6339/*
6340 * mch_access() extends access() to do more detailed check on network drives.
6341 * Returns 0 if file "n" has access rights according to "p", -1 otherwise.
6342 */
6343 int
6344mch_access(char *n, int p)
6345{
6346 HANDLE hFile;
6347 DWORD am;
6348 int retval = -1; /* default: fail */
6349#ifdef FEAT_MBYTE
6350 WCHAR *wn = NULL;
6351
6352 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006353 wn = enc_to_utf16((char_u *)n, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006354#endif
6355
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006356 if (mch_isdir((char_u *)n))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006357 {
6358 char TempName[_MAX_PATH + 16] = "";
6359#ifdef FEAT_MBYTE
6360 WCHAR TempNameW[_MAX_PATH + 16] = L"";
6361#endif
6362
6363 if (p & R_OK)
6364 {
6365 /* Read check is performed by seeing if we can do a find file on
6366 * the directory for any file. */
6367#ifdef FEAT_MBYTE
6368 if (wn != NULL)
6369 {
6370 int i;
6371 WIN32_FIND_DATAW d;
6372
6373 for (i = 0; i < _MAX_PATH && wn[i] != 0; ++i)
6374 TempNameW[i] = wn[i];
6375 if (TempNameW[i - 1] != '\\' && TempNameW[i - 1] != '/')
6376 TempNameW[i++] = '\\';
6377 TempNameW[i++] = '*';
6378 TempNameW[i++] = 0;
6379
6380 hFile = FindFirstFileW(TempNameW, &d);
6381 if (hFile == INVALID_HANDLE_VALUE)
6382 {
6383 if (GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
6384 goto getout;
6385
6386 /* Retry with non-wide function (for Windows 98). */
6387 vim_free(wn);
6388 wn = NULL;
6389 }
6390 else
6391 (void)FindClose(hFile);
6392 }
6393 if (wn == NULL)
6394#endif
6395 {
6396 char *pch;
6397 WIN32_FIND_DATA d;
6398
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006399 vim_strncpy((char_u *)TempName, (char_u *)n, _MAX_PATH);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006400 pch = TempName + STRLEN(TempName) - 1;
6401 if (*pch != '\\' && *pch != '/')
6402 *++pch = '\\';
6403 *++pch = '*';
6404 *++pch = NUL;
6405
6406 hFile = FindFirstFile(TempName, &d);
6407 if (hFile == INVALID_HANDLE_VALUE)
6408 goto getout;
6409 (void)FindClose(hFile);
6410 }
6411 }
6412
6413 if (p & W_OK)
6414 {
6415 /* Trying to create a temporary file in the directory should catch
6416 * directories on read-only network shares. However, in
6417 * directories whose ACL allows writes but denies deletes will end
6418 * up keeping the temporary file :-(. */
6419#ifdef FEAT_MBYTE
6420 if (wn != NULL)
6421 {
6422 if (!GetTempFileNameW(wn, L"VIM", 0, TempNameW))
6423 {
6424 if (GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
6425 goto getout;
6426
6427 /* Retry with non-wide function (for Windows 98). */
6428 vim_free(wn);
6429 wn = NULL;
6430 }
6431 else
6432 DeleteFileW(TempNameW);
6433 }
6434 if (wn == NULL)
6435#endif
6436 {
6437 if (!GetTempFileName(n, "VIM", 0, TempName))
6438 goto getout;
6439 mch_remove((char_u *)TempName);
6440 }
6441 }
6442 }
6443 else
6444 {
6445 /* Trying to open the file for the required access does ACL, read-only
6446 * network share, and file attribute checks. */
6447 am = ((p & W_OK) ? GENERIC_WRITE : 0)
6448 | ((p & R_OK) ? GENERIC_READ : 0);
6449#ifdef FEAT_MBYTE
6450 if (wn != NULL)
6451 {
6452 hFile = CreateFileW(wn, am, 0, NULL, OPEN_EXISTING, 0, NULL);
6453 if (hFile == INVALID_HANDLE_VALUE
6454 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
6455 {
6456 /* Retry with non-wide function (for Windows 98). */
6457 vim_free(wn);
6458 wn = NULL;
6459 }
6460 }
6461 if (wn == NULL)
6462#endif
6463 hFile = CreateFile(n, am, 0, NULL, OPEN_EXISTING, 0, NULL);
6464 if (hFile == INVALID_HANDLE_VALUE)
6465 goto getout;
6466 CloseHandle(hFile);
6467 }
6468
6469 retval = 0; /* success */
6470getout:
6471#ifdef FEAT_MBYTE
6472 vim_free(wn);
6473#endif
6474 return retval;
6475}
6476
6477#if defined(FEAT_MBYTE) || defined(PROTO)
6478/*
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006479 * Version of open() that may use UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006480 */
6481 int
6482mch_open(char *name, int flags, int mode)
6483{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006484 /* _wopen() does not work with Borland C 5.5: creates a read-only file. */
6485# ifndef __BORLANDC__
Bram Moolenaar071d4272004-06-13 20:20:40 +00006486 WCHAR *wn;
6487 int f;
6488
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006489 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006490 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006491 wn = enc_to_utf16((char_u *)name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006492 if (wn != NULL)
6493 {
6494 f = _wopen(wn, flags, mode);
6495 vim_free(wn);
Bram Moolenaarcd981f22014-02-11 17:06:00 +01006496 if (f >= 0 || g_PlatformId == VER_PLATFORM_WIN32_NT)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006497 return f;
6498 /* Retry with non-wide function (for Windows 98). Can't use
6499 * GetLastError() here and it's unclear what errno gets set to if
6500 * the _wopen() fails for missing wide functions. */
6501 }
6502 }
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006503# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006504
Bram Moolenaarf9e6c3b2014-11-05 18:36:03 +01006505 /* open() can open a file which name is longer than _MAX_PATH bytes
6506 * and shorter than _MAX_PATH characters successfully, but sometimes it
6507 * causes unexpected error in another part. We make it an error explicitly
6508 * here. */
6509 if (strlen(name) >= _MAX_PATH)
6510 return -1;
6511
Bram Moolenaar071d4272004-06-13 20:20:40 +00006512 return open(name, flags, mode);
6513}
6514
6515/*
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006516 * Version of fopen() that may use UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006517 */
6518 FILE *
6519mch_fopen(char *name, char *mode)
6520{
6521 WCHAR *wn, *wm;
6522 FILE *f = NULL;
6523
6524 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage
6525# ifdef __BORLANDC__
6526 /* Wide functions of Borland C 5.5 do not work on Windows 98. */
6527 && g_PlatformId == VER_PLATFORM_WIN32_NT
6528# endif
6529 )
6530 {
Bram Moolenaare6a91fd2008-07-24 18:51:11 +00006531# if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0fde2902008-03-16 13:54:13 +00006532 /* Work around an annoying assertion in the Microsoft debug CRT
6533 * when mode's text/binary setting doesn't match _get_fmode(). */
6534 char newMode = mode[strlen(mode) - 1];
6535 int oldMode = 0;
6536
6537 _get_fmode(&oldMode);
6538 if (newMode == 't')
6539 _set_fmode(_O_TEXT);
6540 else if (newMode == 'b')
6541 _set_fmode(_O_BINARY);
6542# endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006543 wn = enc_to_utf16((char_u *)name, NULL);
6544 wm = enc_to_utf16((char_u *)mode, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006545 if (wn != NULL && wm != NULL)
6546 f = _wfopen(wn, wm);
6547 vim_free(wn);
6548 vim_free(wm);
Bram Moolenaar0fde2902008-03-16 13:54:13 +00006549
Bram Moolenaare6a91fd2008-07-24 18:51:11 +00006550# if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0fde2902008-03-16 13:54:13 +00006551 _set_fmode(oldMode);
6552# endif
6553
Bram Moolenaarcd981f22014-02-11 17:06:00 +01006554 if (f != NULL || g_PlatformId == VER_PLATFORM_WIN32_NT)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006555 return f;
6556 /* Retry with non-wide function (for Windows 98). Can't use
6557 * GetLastError() here and it's unclear what errno gets set to if
6558 * the _wfopen() fails for missing wide functions. */
6559 }
6560
Bram Moolenaarf9e6c3b2014-11-05 18:36:03 +01006561 /* fopen() can open a file which name is longer than _MAX_PATH bytes
6562 * and shorter than _MAX_PATH characters successfully, but sometimes it
6563 * causes unexpected error in another part. We make it an error explicitly
6564 * here. */
6565 if (strlen(name) >= _MAX_PATH)
6566 return NULL;
6567
Bram Moolenaar071d4272004-06-13 20:20:40 +00006568 return fopen(name, mode);
6569}
6570#endif
6571
6572#ifdef FEAT_MBYTE
6573/*
6574 * SUB STREAM (aka info stream) handling:
6575 *
6576 * NTFS can have sub streams for each file. Normal contents of file is
6577 * stored in the main stream, and extra contents (author information and
6578 * title and so on) can be stored in sub stream. After Windows 2000, user
6579 * can access and store those informations in sub streams via explorer's
6580 * property menuitem in right click menu. Those informations in sub streams
6581 * were lost when copying only the main stream. So we have to copy sub
6582 * streams.
6583 *
6584 * Incomplete explanation:
6585 * http://msdn.microsoft.com/library/en-us/dnw2k/html/ntfs5.asp
6586 * More useful info and an example:
6587 * http://www.sysinternals.com/ntw2k/source/misc.shtml#streams
6588 */
6589
6590/*
6591 * Copy info stream data "substream". Read from the file with BackupRead(sh)
6592 * and write to stream "substream" of file "to".
6593 * Errors are ignored.
6594 */
6595 static void
6596copy_substream(HANDLE sh, void *context, WCHAR *to, WCHAR *substream, long len)
6597{
6598 HANDLE hTo;
6599 WCHAR *to_name;
6600
6601 to_name = malloc((wcslen(to) + wcslen(substream) + 1) * sizeof(WCHAR));
6602 wcscpy(to_name, to);
6603 wcscat(to_name, substream);
6604
6605 hTo = CreateFileW(to_name, GENERIC_WRITE, 0, NULL, OPEN_ALWAYS,
6606 FILE_ATTRIBUTE_NORMAL, NULL);
6607 if (hTo != INVALID_HANDLE_VALUE)
6608 {
6609 long done;
6610 DWORD todo;
6611 DWORD readcnt, written;
6612 char buf[4096];
6613
6614 /* Copy block of bytes at a time. Abort when something goes wrong. */
6615 for (done = 0; done < len; done += written)
6616 {
6617 /* (size_t) cast for Borland C 5.5 */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006618 todo = (DWORD)((size_t)(len - done) > sizeof(buf) ? sizeof(buf)
6619 : (size_t)(len - done));
Bram Moolenaar071d4272004-06-13 20:20:40 +00006620 if (!BackupRead(sh, (LPBYTE)buf, todo, &readcnt,
6621 FALSE, FALSE, context)
6622 || readcnt != todo
6623 || !WriteFile(hTo, buf, todo, &written, NULL)
6624 || written != todo)
6625 break;
6626 }
6627 CloseHandle(hTo);
6628 }
6629
6630 free(to_name);
6631}
6632
6633/*
6634 * Copy info streams from file "from" to file "to".
6635 */
6636 static void
6637copy_infostreams(char_u *from, char_u *to)
6638{
6639 WCHAR *fromw;
6640 WCHAR *tow;
6641 HANDLE sh;
6642 WIN32_STREAM_ID sid;
6643 int headersize;
6644 WCHAR streamname[_MAX_PATH];
6645 DWORD readcount;
6646 void *context = NULL;
6647 DWORD lo, hi;
6648 int len;
6649
6650 /* Convert the file names to wide characters. */
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006651 fromw = enc_to_utf16(from, NULL);
6652 tow = enc_to_utf16(to, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006653 if (fromw != NULL && tow != NULL)
6654 {
6655 /* Open the file for reading. */
6656 sh = CreateFileW(fromw, GENERIC_READ, FILE_SHARE_READ, NULL,
6657 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
6658 if (sh != INVALID_HANDLE_VALUE)
6659 {
6660 /* Use BackupRead() to find the info streams. Repeat until we
6661 * have done them all.*/
6662 for (;;)
6663 {
6664 /* Get the header to find the length of the stream name. If
6665 * the "readcount" is zero we have done all info streams. */
6666 ZeroMemory(&sid, sizeof(WIN32_STREAM_ID));
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006667 headersize = (int)((char *)&sid.cStreamName - (char *)&sid.dwStreamId);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006668 if (!BackupRead(sh, (LPBYTE)&sid, headersize,
6669 &readcount, FALSE, FALSE, &context)
6670 || readcount == 0)
6671 break;
6672
6673 /* We only deal with streams that have a name. The normal
6674 * file data appears to be without a name, even though docs
6675 * suggest it is called "::$DATA". */
6676 if (sid.dwStreamNameSize > 0)
6677 {
6678 /* Read the stream name. */
6679 if (!BackupRead(sh, (LPBYTE)streamname,
6680 sid.dwStreamNameSize,
6681 &readcount, FALSE, FALSE, &context))
6682 break;
6683
6684 /* Copy an info stream with a name ":anything:$DATA".
6685 * Skip "::$DATA", it has no stream name (examples suggest
6686 * it might be used for the normal file contents).
6687 * Note that BackupRead() counts bytes, but the name is in
6688 * wide characters. */
6689 len = readcount / sizeof(WCHAR);
6690 streamname[len] = 0;
6691 if (len > 7 && wcsicmp(streamname + len - 6,
6692 L":$DATA") == 0)
6693 {
6694 streamname[len - 6] = 0;
6695 copy_substream(sh, &context, tow, streamname,
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00006696 (long)sid.Size.u.LowPart);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006697 }
6698 }
6699
6700 /* Advance to the next stream. We might try seeking too far,
6701 * but BackupSeek() doesn't skip over stream borders, thus
6702 * that's OK. */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00006703 (void)BackupSeek(sh, sid.Size.u.LowPart, sid.Size.u.HighPart,
Bram Moolenaar071d4272004-06-13 20:20:40 +00006704 &lo, &hi, &context);
6705 }
6706
6707 /* Clear the context. */
6708 (void)BackupRead(sh, NULL, 0, &readcount, TRUE, FALSE, &context);
6709
6710 CloseHandle(sh);
6711 }
6712 }
6713 vim_free(fromw);
6714 vim_free(tow);
6715}
6716#endif
6717
6718/*
6719 * Copy file attributes from file "from" to file "to".
6720 * For Windows NT and later we copy info streams.
6721 * Always returns zero, errors are ignored.
6722 */
6723 int
6724mch_copy_file_attribute(char_u *from, char_u *to)
6725{
6726#ifdef FEAT_MBYTE
6727 /* File streams only work on Windows NT and later. */
6728 PlatformId();
6729 if (g_PlatformId == VER_PLATFORM_WIN32_NT)
6730 copy_infostreams(from, to);
6731#endif
6732 return 0;
6733}
6734
6735#if defined(MYRESETSTKOFLW) || defined(PROTO)
6736/*
6737 * Recreate a destroyed stack guard page in win32.
6738 * Written by Benjamin Peterson.
6739 */
6740
6741/* These magic numbers are from the MS header files */
6742#define MIN_STACK_WIN9X 17
6743#define MIN_STACK_WINNT 2
6744
6745/*
6746 * This function does the same thing as _resetstkoflw(), which is only
6747 * available in DevStudio .net and later.
6748 * Returns 0 for failure, 1 for success.
6749 */
6750 int
6751myresetstkoflw(void)
6752{
6753 BYTE *pStackPtr;
6754 BYTE *pGuardPage;
6755 BYTE *pStackBase;
6756 BYTE *pLowestPossiblePage;
6757 MEMORY_BASIC_INFORMATION mbi;
6758 SYSTEM_INFO si;
6759 DWORD nPageSize;
6760 DWORD dummy;
6761
6762 /* This code will not work on win32s. */
6763 PlatformId();
6764 if (g_PlatformId == VER_PLATFORM_WIN32s)
6765 return 0;
6766
6767 /* We need to know the system page size. */
6768 GetSystemInfo(&si);
6769 nPageSize = si.dwPageSize;
6770
6771 /* ...and the current stack pointer */
6772 pStackPtr = (BYTE*)_alloca(1);
6773
6774 /* ...and the base of the stack. */
6775 if (VirtualQuery(pStackPtr, &mbi, sizeof mbi) == 0)
6776 return 0;
6777 pStackBase = (BYTE*)mbi.AllocationBase;
6778
6779 /* ...and the page thats min_stack_req pages away from stack base; this is
6780 * the lowest page we could use. */
6781 pLowestPossiblePage = pStackBase + ((g_PlatformId == VER_PLATFORM_WIN32_NT)
6782 ? MIN_STACK_WINNT : MIN_STACK_WIN9X) * nPageSize;
6783
6784 /* On Win95, we want the next page down from the end of the stack. */
6785 if (g_PlatformId == VER_PLATFORM_WIN32_WINDOWS)
6786 {
6787 /* Find the page that's only 1 page down from the page that the stack
6788 * ptr is in. */
6789 pGuardPage = (BYTE*)((DWORD)nPageSize * (((DWORD)pStackPtr
6790 / (DWORD)nPageSize) - 1));
6791 if (pGuardPage < pLowestPossiblePage)
6792 return 0;
6793
6794 /* Apply the noaccess attribute to the page -- there's no guard
6795 * attribute in win95-type OSes. */
6796 if (!VirtualProtect(pGuardPage, nPageSize, PAGE_NOACCESS, &dummy))
6797 return 0;
6798 }
6799 else
6800 {
6801 /* On NT, however, we want the first committed page in the stack Start
6802 * at the stack base and move forward through memory until we find a
6803 * committed block. */
6804 BYTE *pBlock = pStackBase;
6805
Bram Moolenaara466c992005-07-09 21:03:22 +00006806 for (;;)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006807 {
6808 if (VirtualQuery(pBlock, &mbi, sizeof mbi) == 0)
6809 return 0;
6810
6811 pBlock += mbi.RegionSize;
6812
6813 if (mbi.State & MEM_COMMIT)
6814 break;
6815 }
6816
6817 /* mbi now describes the first committed block in the stack. */
6818 if (mbi.Protect & PAGE_GUARD)
6819 return 1;
6820
6821 /* decide where the guard page should start */
6822 if ((long_u)(mbi.BaseAddress) < (long_u)pLowestPossiblePage)
6823 pGuardPage = pLowestPossiblePage;
6824 else
6825 pGuardPage = (BYTE*)mbi.BaseAddress;
6826
6827 /* allocate the guard page */
6828 if (!VirtualAlloc(pGuardPage, nPageSize, MEM_COMMIT, PAGE_READWRITE))
6829 return 0;
6830
6831 /* apply the guard attribute to the page */
6832 if (!VirtualProtect(pGuardPage, nPageSize, PAGE_READWRITE | PAGE_GUARD,
6833 &dummy))
6834 return 0;
6835 }
6836
6837 return 1;
6838}
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006839#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006840
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006841
6842#if defined(FEAT_MBYTE) || defined(PROTO)
6843/*
6844 * The command line arguments in UCS2
6845 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00006846static int nArgsW = 0;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006847static LPWSTR *ArglistW = NULL;
6848static int global_argc = 0;
6849static char **global_argv;
6850
6851static int used_file_argc = 0; /* last argument in global_argv[] used
6852 for the argument list. */
6853static int *used_file_indexes = NULL; /* indexes in global_argv[] for
6854 command line arguments added to
6855 the argument list */
6856static int used_file_count = 0; /* nr of entries in used_file_indexes */
6857static int used_file_literal = FALSE; /* take file names literally */
6858static int used_file_full_path = FALSE; /* file name was full path */
Bram Moolenaar910f66f2006-04-05 20:41:53 +00006859static int used_file_diff_mode = FALSE; /* file name was with diff mode */
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006860static int used_alist_count = 0;
6861
6862
6863/*
6864 * Get the command line arguments. Unicode version.
6865 * Returns argc. Zero when something fails.
6866 */
6867 int
6868get_cmd_argsW(char ***argvp)
6869{
6870 char **argv = NULL;
6871 int argc = 0;
6872 int i;
6873
Bram Moolenaar14993322014-09-09 12:25:33 +02006874 free_cmd_argsW();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006875 ArglistW = CommandLineToArgvW(GetCommandLineW(), &nArgsW);
6876 if (ArglistW != NULL)
6877 {
6878 argv = malloc((nArgsW + 1) * sizeof(char *));
6879 if (argv != NULL)
6880 {
6881 argc = nArgsW;
6882 argv[argc] = NULL;
6883 for (i = 0; i < argc; ++i)
6884 {
6885 int len;
6886
6887 /* Convert each Unicode argument to the current codepage. */
6888 WideCharToMultiByte_alloc(GetACP(), 0,
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006889 ArglistW[i], (int)wcslen(ArglistW[i]) + 1,
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006890 (LPSTR *)&argv[i], &len, 0, 0);
6891 if (argv[i] == NULL)
6892 {
6893 /* Out of memory, clear everything. */
6894 while (i > 0)
6895 free(argv[--i]);
6896 free(argv);
Bram Moolenaar73c61632013-12-07 14:48:10 +01006897 argv = NULL;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006898 argc = 0;
6899 }
6900 }
6901 }
6902 }
6903
6904 global_argc = argc;
6905 global_argv = argv;
6906 if (argc > 0)
Bram Moolenaar14993322014-09-09 12:25:33 +02006907 {
6908 if (used_file_indexes != NULL)
6909 free(used_file_indexes);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006910 used_file_indexes = malloc(argc * sizeof(int));
Bram Moolenaar14993322014-09-09 12:25:33 +02006911 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006912
6913 if (argvp != NULL)
6914 *argvp = argv;
6915 return argc;
6916}
6917
6918 void
6919free_cmd_argsW(void)
6920{
6921 if (ArglistW != NULL)
6922 {
6923 GlobalFree(ArglistW);
6924 ArglistW = NULL;
6925 }
6926}
6927
6928/*
6929 * Remember "name" is an argument that was added to the argument list.
6930 * This avoids that we have to re-parse the argument list when fix_arg_enc()
6931 * is called.
6932 */
6933 void
Bram Moolenaar910f66f2006-04-05 20:41:53 +00006934used_file_arg(char *name, int literal, int full_path, int diff_mode)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006935{
6936 int i;
6937
6938 if (used_file_indexes == NULL)
6939 return;
6940 for (i = used_file_argc + 1; i < global_argc; ++i)
6941 if (STRCMP(global_argv[i], name) == 0)
6942 {
6943 used_file_argc = i;
6944 used_file_indexes[used_file_count++] = i;
6945 break;
6946 }
6947 used_file_literal = literal;
6948 used_file_full_path = full_path;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00006949 used_file_diff_mode = diff_mode;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006950}
6951
6952/*
6953 * Remember the length of the argument list as it was. If it changes then we
6954 * leave it alone when 'encoding' is set.
6955 */
6956 void
6957set_alist_count(void)
6958{
6959 used_alist_count = GARGCOUNT;
6960}
6961
6962/*
6963 * Fix the encoding of the command line arguments. Invoked when 'encoding'
6964 * has been changed while starting up. Use the UCS-2 command line arguments
6965 * and convert them to 'encoding'.
6966 */
6967 void
6968fix_arg_enc(void)
6969{
6970 int i;
6971 int idx;
6972 char_u *str;
Bram Moolenaar86b68352004-12-27 21:59:20 +00006973 int *fnum_list;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006974
6975 /* Safety checks:
6976 * - if argument count differs between the wide and non-wide argument
6977 * list, something must be wrong.
6978 * - the file name arguments must have been located.
6979 * - the length of the argument list wasn't changed by the user.
6980 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00006981 if (global_argc != nArgsW
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006982 || ArglistW == NULL
6983 || used_file_indexes == NULL
6984 || used_file_count == 0
6985 || used_alist_count != GARGCOUNT)
6986 return;
6987
Bram Moolenaar86b68352004-12-27 21:59:20 +00006988 /* Remember the buffer numbers for the arguments. */
6989 fnum_list = (int *)alloc((int)sizeof(int) * GARGCOUNT);
6990 if (fnum_list == NULL)
6991 return; /* out of memory */
6992 for (i = 0; i < GARGCOUNT; ++i)
6993 fnum_list[i] = GARGLIST[i].ae_fnum;
6994
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006995 /* Clear the argument list. Make room for the new arguments. */
6996 alist_clear(&global_alist);
6997 if (ga_grow(&global_alist.al_ga, used_file_count) == FAIL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00006998 return; /* out of memory */
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006999
7000 for (i = 0; i < used_file_count; ++i)
7001 {
7002 idx = used_file_indexes[i];
Bram Moolenaar36f692d2008-11-20 16:10:17 +00007003 str = utf16_to_enc(ArglistW[idx], NULL);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007004 if (str != NULL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00007005 {
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007006#ifdef FEAT_DIFF
7007 /* When using diff mode may need to concatenate file name to
7008 * directory name. Just like it's done in main(). */
7009 if (used_file_diff_mode && mch_isdir(str) && GARGCOUNT > 0
7010 && !mch_isdir(alist_name(&GARGLIST[0])))
7011 {
7012 char_u *r;
7013
7014 r = concat_fnames(str, gettail(alist_name(&GARGLIST[0])), TRUE);
7015 if (r != NULL)
7016 {
7017 vim_free(str);
7018 str = r;
7019 }
7020 }
7021#endif
Bram Moolenaar86b68352004-12-27 21:59:20 +00007022 /* Re-use the old buffer by renaming it. When not using literal
7023 * names it's done by alist_expand() below. */
7024 if (used_file_literal)
7025 buf_set_name(fnum_list[i], str);
7026
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007027 alist_add(&global_alist, str, used_file_literal ? 2 : 0);
Bram Moolenaar86b68352004-12-27 21:59:20 +00007028 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007029 }
7030
7031 if (!used_file_literal)
7032 {
7033 /* Now expand wildcards in the arguments. */
7034 /* Temporarily add '(' and ')' to 'isfname'. These are valid
7035 * filename characters but are excluded from 'isfname' to make
7036 * "gf" work on a file name in parenthesis (e.g.: see vim.h). */
7037 do_cmdline_cmd((char_u *)":let SaVe_ISF = &isf|set isf+=(,)");
Bram Moolenaar86b68352004-12-27 21:59:20 +00007038 alist_expand(fnum_list, used_alist_count);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007039 do_cmdline_cmd((char_u *)":let &isf = SaVe_ISF|unlet SaVe_ISF");
7040 }
7041
7042 /* If wildcard expansion failed, we are editing the first file of the
7043 * arglist and there is no file name: Edit the first argument now. */
7044 if (curwin->w_arg_idx == 0 && curbuf->b_fname == NULL)
7045 {
7046 do_cmdline_cmd((char_u *)":rewind");
7047 if (GARGCOUNT == 1 && used_file_full_path)
7048 (void)vim_chdirfile(alist_name(&GARGLIST[0]));
7049 }
Bram Moolenaar86b68352004-12-27 21:59:20 +00007050
7051 set_alist_count();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007052}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007053#endif