blob: 9d1d8cbc2202d5b76ba91baceb5e32ca96247335 [file] [log] [blame]
Bram Moolenaaredf3f972016-08-29 22:49:24 +02001/* vi:set ts=8 sts=4 sw=4 noet:
Bram Moolenaar071d4272004-06-13 20:20:40 +00002 *
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
Bram Moolenaarfb630902016-10-29 14:55:00 +020053#ifdef FEAT_JOB_CHANNEL
54# include <tlhelp32.h>
55#endif
56
Bram Moolenaar071d4272004-06-13 20:20:40 +000057#ifdef __MINGW32__
58# ifndef FROM_LEFT_1ST_BUTTON_PRESSED
59# define FROM_LEFT_1ST_BUTTON_PRESSED 0x0001
60# endif
61# ifndef RIGHTMOST_BUTTON_PRESSED
62# define RIGHTMOST_BUTTON_PRESSED 0x0002
63# endif
64# ifndef FROM_LEFT_2ND_BUTTON_PRESSED
65# define FROM_LEFT_2ND_BUTTON_PRESSED 0x0004
66# endif
67# ifndef FROM_LEFT_3RD_BUTTON_PRESSED
68# define FROM_LEFT_3RD_BUTTON_PRESSED 0x0008
69# endif
70# ifndef FROM_LEFT_4TH_BUTTON_PRESSED
71# define FROM_LEFT_4TH_BUTTON_PRESSED 0x0010
72# endif
73
74/*
75 * EventFlags
76 */
77# ifndef MOUSE_MOVED
78# define MOUSE_MOVED 0x0001
79# endif
80# ifndef DOUBLE_CLICK
81# define DOUBLE_CLICK 0x0002
82# endif
83#endif
84
85/* Record all output and all keyboard & mouse input */
86/* #define MCH_WRITE_DUMP */
87
88#ifdef MCH_WRITE_DUMP
89FILE* fdDump = NULL;
90#endif
91
92/*
93 * When generating prototypes for Win32 on Unix, these lines make the syntax
94 * errors disappear. They do not need to be correct.
95 */
96#ifdef PROTO
97#define WINAPI
Bram Moolenaar071d4272004-06-13 20:20:40 +000098typedef char * LPCSTR;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +000099typedef char * LPWSTR;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000100typedef int ACCESS_MASK;
101typedef int BOOL;
102typedef int COLORREF;
103typedef int CONSOLE_CURSOR_INFO;
104typedef int COORD;
105typedef int DWORD;
106typedef int HANDLE;
Bram Moolenaaref269542016-01-19 13:22:12 +0100107typedef int LPHANDLE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000108typedef int HDC;
109typedef int HFONT;
110typedef int HICON;
111typedef int HINSTANCE;
112typedef int HWND;
113typedef int INPUT_RECORD;
Bram Moolenaare0ab9792017-08-02 23:18:25 +0200114typedef int INT;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000115typedef int KEY_EVENT_RECORD;
116typedef int LOGFONT;
117typedef int LPBOOL;
118typedef int LPCTSTR;
119typedef int LPDWORD;
120typedef int LPSTR;
121typedef int LPTSTR;
122typedef int LPVOID;
123typedef int MOUSE_EVENT_RECORD;
124typedef int PACL;
125typedef int PDWORD;
126typedef int PHANDLE;
127typedef int PRINTDLG;
128typedef int PSECURITY_DESCRIPTOR;
129typedef int PSID;
130typedef int SECURITY_INFORMATION;
131typedef int SHORT;
132typedef int SMALL_RECT;
133typedef int TEXTMETRIC;
134typedef int TOKEN_INFORMATION_CLASS;
135typedef int TRUSTEE;
136typedef int WORD;
137typedef int WCHAR;
138typedef void VOID;
Bram Moolenaar82881492012-11-20 16:53:39 +0100139typedef int BY_HANDLE_FILE_INFORMATION;
Bram Moolenaar32ac8cd2013-07-03 18:49:17 +0200140typedef int SE_OBJECT_TYPE;
141typedef int PSNSECINFO;
142typedef int PSNSECINFOW;
Bram Moolenaarb8e0bdb2014-11-12 16:10:48 +0100143typedef int STARTUPINFO;
144typedef int PROCESS_INFORMATION;
Bram Moolenaard90b6c02016-08-28 18:10:45 +0200145typedef int LPSECURITY_ATTRIBUTES;
146# define __stdcall /* empty */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000147#endif
148
Bram Moolenaar071d4272004-06-13 20:20:40 +0000149#if defined(__BORLANDC__)
150/* Strangely Borland uses a non-standard name. */
151# define wcsicmp(a, b) wcscmpi((a), (b))
152#endif
153
154#ifndef FEAT_GUI_W32
155/* Win32 Console handles for input and output */
156static HANDLE g_hConIn = INVALID_HANDLE_VALUE;
157static HANDLE g_hConOut = INVALID_HANDLE_VALUE;
158
159/* Win32 Screen buffer,coordinate,console I/O information */
160static SMALL_RECT g_srScrollRegion;
161static COORD g_coord; /* 0-based, but external coords are 1-based */
162
163/* The attribute of the screen when the editor was started */
164static WORD g_attrDefault = 7; /* lightgray text on black background */
165static WORD g_attrCurrent;
166
167static int g_fCBrkPressed = FALSE; /* set by ctrl-break interrupt */
168static int g_fCtrlCPressed = FALSE; /* set when ctrl-C or ctrl-break detected */
169static int g_fForceExit = FALSE; /* set when forcefully exiting */
170
Bram Moolenaar071d4272004-06-13 20:20:40 +0000171static void scroll(unsigned cLines);
172static void set_scroll_region(unsigned left, unsigned top,
173 unsigned right, unsigned bottom);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000174static void delete_lines(unsigned cLines);
175static void gotoxy(unsigned x, unsigned y);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000176static void standout(void);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000177static int s_cursor_visible = TRUE;
178static int did_create_conin = FALSE;
179#else
180static int s_dont_use_vimrun = TRUE;
181static int need_vimrun_warning = FALSE;
182static char *vimrun_path = "vimrun ";
183#endif
184
Bram Moolenaar12b559e2013-06-12 22:41:37 +0200185static int win32_getattrs(char_u *name);
186static int win32_setattrs(char_u *name, int attrs);
187static int win32_set_archive(char_u *name);
188
Bram Moolenaar071d4272004-06-13 20:20:40 +0000189#ifndef FEAT_GUI_W32
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100190static int vtp_working = 0;
191static void vtp_init();
192static void vtp_exit();
193static int vtp_printf(char *format, ...);
194static void vtp_sgr_bulk(int arg);
195static void vtp_sgr_bulks(int argc, int *argv);
196
197static guicolor_T save_console_bg_rgb;
198static guicolor_T save_console_fg_rgb;
199
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +0200200static int g_color_index_bg = 0;
201static int g_color_index_fg = 7;
202
203# ifdef FEAT_TERMGUICOLORS
204static int default_console_color_bg = 0x000000; // black
205static int default_console_color_fg = 0xc0c0c0; // white
206# endif
207
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100208# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarc5cd8852018-05-01 15:47:38 +0200209# define USE_VTP (vtp_working && is_term_win32() && (p_tgc || (!p_tgc && t_colors >= 256)))
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100210# else
211# define USE_VTP 0
212# endif
213
214static void set_console_color_rgb(void);
215static void reset_console_color_rgb(void);
216#endif
217
218/* This flag is newly created from Windows 10 */
219#ifndef ENABLE_VIRTUAL_TERMINAL_PROCESSING
220# define ENABLE_VIRTUAL_TERMINAL_PROCESSING 0x0004
221#endif
222
223#ifndef FEAT_GUI_W32
Bram Moolenaar071d4272004-06-13 20:20:40 +0000224static int suppress_winsize = 1; /* don't fiddle with console */
225#endif
226
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200227static char_u *exe_path = NULL;
228
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100229static BOOL win8_or_later = FALSE;
230
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100231#ifndef FEAT_GUI_W32
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100232/* Dynamic loading for portability */
233typedef struct _DYN_CONSOLE_SCREEN_BUFFER_INFOEX
234{
235 ULONG cbSize;
236 COORD dwSize;
237 COORD dwCursorPosition;
238 WORD wAttributes;
239 SMALL_RECT srWindow;
240 COORD dwMaximumWindowSize;
241 WORD wPopupAttributes;
242 BOOL bFullscreenSupported;
243 COLORREF ColorTable[16];
244} DYN_CONSOLE_SCREEN_BUFFER_INFOEX, *PDYN_CONSOLE_SCREEN_BUFFER_INFOEX;
245typedef BOOL (WINAPI *PfnGetConsoleScreenBufferInfoEx)(HANDLE, PDYN_CONSOLE_SCREEN_BUFFER_INFOEX);
246static PfnGetConsoleScreenBufferInfoEx pGetConsoleScreenBufferInfoEx;
247typedef BOOL (WINAPI *PfnSetConsoleScreenBufferInfoEx)(HANDLE, PDYN_CONSOLE_SCREEN_BUFFER_INFOEX);
248static PfnSetConsoleScreenBufferInfoEx pSetConsoleScreenBufferInfoEx;
249static BOOL has_csbiex = FALSE;
250
251/*
252 * Get version number including build number
253 */
254typedef BOOL (WINAPI *PfnRtlGetVersion)(LPOSVERSIONINFOW);
255# define MAKE_VER(major, minor, build) \
256 (((major) << 24) | ((minor) << 16) | (build))
257
258 static DWORD
259get_build_number(void)
260{
261 OSVERSIONINFOW osver = {sizeof(OSVERSIONINFOW)};
262 HMODULE hNtdll;
263 PfnRtlGetVersion pRtlGetVersion;
264 DWORD ver = MAKE_VER(0, 0, 0);
265
266 hNtdll = GetModuleHandle("ntdll.dll");
267 if (hNtdll != NULL)
268 {
269 pRtlGetVersion =
270 (PfnRtlGetVersion)GetProcAddress(hNtdll, "RtlGetVersion");
271 pRtlGetVersion(&osver);
272 ver = MAKE_VER(min(osver.dwMajorVersion, 255),
273 min(osver.dwMinorVersion, 255),
274 min(osver.dwBuildNumber, 32767));
275 }
276 return ver;
277}
278
279
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100280/*
281 * Version of ReadConsoleInput() that works with IME.
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100282 * Works around problems on Windows 8.
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100283 */
284 static BOOL
285read_console_input(
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100286 HANDLE hInput,
287 INPUT_RECORD *lpBuffer,
288 DWORD nLength,
289 LPDWORD lpEvents)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100290{
291 enum
292 {
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100293 IRSIZE = 10
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100294 };
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100295 static INPUT_RECORD s_irCache[IRSIZE];
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100296 static DWORD s_dwIndex = 0;
297 static DWORD s_dwMax = 0;
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100298 DWORD dwEvents;
Bram Moolenaardd415a62014-02-05 14:02:27 +0100299 int head;
300 int tail;
301 int i;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100302
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200303 if (nLength == -2)
304 return (s_dwMax > 0) ? TRUE : FALSE;
305
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100306 if (!win8_or_later)
307 {
308 if (nLength == -1)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200309 return PeekConsoleInputW(hInput, lpBuffer, 1, lpEvents);
310 return ReadConsoleInputW(hInput, lpBuffer, 1, &dwEvents);
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100311 }
312
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100313 if (s_dwMax == 0)
314 {
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100315 if (nLength == -1)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200316 return PeekConsoleInputW(hInput, lpBuffer, 1, lpEvents);
317 if (!ReadConsoleInputW(hInput, s_irCache, IRSIZE, &dwEvents))
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100318 return FALSE;
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100319 s_dwIndex = 0;
320 s_dwMax = dwEvents;
321 if (dwEvents == 0)
322 {
323 *lpEvents = 0;
324 return TRUE;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100325 }
Bram Moolenaardd415a62014-02-05 14:02:27 +0100326
327 if (s_dwMax > 1)
328 {
329 head = 0;
330 tail = s_dwMax - 1;
331 while (head != tail)
332 {
333 if (s_irCache[head].EventType == WINDOW_BUFFER_SIZE_EVENT
334 && s_irCache[head + 1].EventType
335 == WINDOW_BUFFER_SIZE_EVENT)
336 {
337 /* Remove duplicate event to avoid flicker. */
338 for (i = head; i < tail; ++i)
339 s_irCache[i] = s_irCache[i + 1];
340 --tail;
341 continue;
342 }
343 head++;
344 }
345 s_dwMax = tail + 1;
346 }
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100347 }
Bram Moolenaardd415a62014-02-05 14:02:27 +0100348
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100349 *lpBuffer = s_irCache[s_dwIndex];
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200350 if (!(nLength == -1 || nLength == -2) && ++s_dwIndex >= s_dwMax)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100351 s_dwMax = 0;
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100352 *lpEvents = 1;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100353 return TRUE;
354}
355
356/*
357 * Version of PeekConsoleInput() that works with IME.
358 */
359 static BOOL
360peek_console_input(
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100361 HANDLE hInput,
362 INPUT_RECORD *lpBuffer,
363 DWORD nLength,
364 LPDWORD lpEvents)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100365{
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100366 return read_console_input(hInput, lpBuffer, -1, lpEvents);
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100367}
368
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100369# ifdef FEAT_CLIENTSERVER
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200370 static DWORD
371msg_wait_for_multiple_objects(
372 DWORD nCount,
373 LPHANDLE pHandles,
374 BOOL fWaitAll,
375 DWORD dwMilliseconds,
376 DWORD dwWakeMask)
377{
378 if (read_console_input(NULL, NULL, -2, NULL))
379 return WAIT_OBJECT_0;
380 return MsgWaitForMultipleObjects(nCount, pHandles, fWaitAll,
381 dwMilliseconds, dwWakeMask);
382}
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100383# endif
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200384
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100385# ifndef FEAT_CLIENTSERVER
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200386 static DWORD
387wait_for_single_object(
388 HANDLE hHandle,
389 DWORD dwMilliseconds)
390{
391 if (read_console_input(NULL, NULL, -2, NULL))
392 return WAIT_OBJECT_0;
393 return WaitForSingleObject(hHandle, dwMilliseconds);
394}
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100395# endif
396#endif
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200397
Bram Moolenaar071d4272004-06-13 20:20:40 +0000398 static void
399get_exe_name(void)
400{
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100401 /* Maximum length of $PATH is more than MAXPATHL. 8191 is often mentioned
402 * as the maximum length that works (plus a NUL byte). */
403#define MAX_ENV_PATH_LEN 8192
404 char temp[MAX_ENV_PATH_LEN];
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200405 char_u *p;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000406
407 if (exe_name == NULL)
408 {
409 /* store the name of the executable, may be used for $VIM */
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100410 GetModuleFileName(NULL, temp, MAX_ENV_PATH_LEN - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000411 if (*temp != NUL)
412 exe_name = FullName_save((char_u *)temp, FALSE);
413 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000414
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200415 if (exe_path == NULL && exe_name != NULL)
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000416 {
Bram Moolenaar6b5ef062010-10-27 12:18:00 +0200417 exe_path = vim_strnsave(exe_name,
418 (int)(gettail_sep(exe_name) - exe_name));
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200419 if (exe_path != NULL)
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000420 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200421 /* Append our starting directory to $PATH, so that when doing
422 * "!xxd" it's found in our starting directory. Needed because
423 * SearchPath() also looks there. */
424 p = mch_getenv("PATH");
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100425 if (p == NULL
426 || STRLEN(p) + STRLEN(exe_path) + 2 < MAX_ENV_PATH_LEN)
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200427 {
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100428 if (p == NULL || *p == NUL)
429 temp[0] = NUL;
430 else
431 {
432 STRCPY(temp, p);
433 STRCAT(temp, ";");
434 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200435 STRCAT(temp, exe_path);
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +0100436 vim_setenv((char_u *)"PATH", (char_u *)temp);
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200437 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000438 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000439 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000440}
441
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200442/*
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100443 * Unescape characters in "p" that appear in "escaped".
444 */
445 static void
446unescape_shellxquote(char_u *p, char_u *escaped)
447{
Bram Moolenaar4336cdf2012-02-29 13:58:47 +0100448 int l = (int)STRLEN(p);
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100449 int n;
450
451 while (*p != NUL)
452 {
453 if (*p == '^' && vim_strchr(escaped, p[1]) != NULL)
454 mch_memmove(p, p + 1, l--);
455#ifdef FEAT_MBYTE
456 n = (*mb_ptr2len)(p);
457#else
458 n = 1;
459#endif
460 p += n;
461 l -= n;
462 }
463}
464
465/*
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200466 * Load library "name".
467 */
468 HINSTANCE
469vimLoadLib(char *name)
470{
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200471 HINSTANCE dll = NULL;
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200472
Bram Moolenaarfaca8402012-10-21 02:37:10 +0200473 /* NOTE: Do not use mch_dirname() and mch_chdir() here, they may call
474 * vimLoadLib() recursively, which causes a stack overflow. */
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200475 if (exe_path == NULL)
476 get_exe_name();
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200477 if (exe_path != NULL)
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200478 {
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200479 WCHAR old_dirw[MAXPATHL];
480
481 if (GetCurrentDirectoryW(MAXPATHL, old_dirw) != 0)
482 {
483 /* Change directory to where the executable is, both to make
484 * sure we find a .dll there and to avoid looking for a .dll
485 * in the current directory. */
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +0100486 SetCurrentDirectory((LPCSTR)exe_path);
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200487 dll = LoadLibrary(name);
488 SetCurrentDirectoryW(old_dirw);
489 return dll;
490 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200491 }
492 return dll;
493}
494
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100495#if defined(DYNAMIC_ICONV) || defined(DYNAMIC_GETTEXT) || defined(PROTO)
496/*
497 * Get related information about 'funcname' which is imported by 'hInst'.
498 * If 'info' is 0, return the function address.
499 * If 'info' is 1, return the module name which the function is imported from.
500 */
501 static void *
502get_imported_func_info(HINSTANCE hInst, const char *funcname, int info)
503{
504 PBYTE pImage = (PBYTE)hInst;
505 PIMAGE_DOS_HEADER pDOS = (PIMAGE_DOS_HEADER)hInst;
506 PIMAGE_NT_HEADERS pPE;
507 PIMAGE_IMPORT_DESCRIPTOR pImpDesc;
508 PIMAGE_THUNK_DATA pIAT; /* Import Address Table */
509 PIMAGE_THUNK_DATA pINT; /* Import Name Table */
510 PIMAGE_IMPORT_BY_NAME pImpName;
511
512 if (pDOS->e_magic != IMAGE_DOS_SIGNATURE)
513 return NULL;
514 pPE = (PIMAGE_NT_HEADERS)(pImage + pDOS->e_lfanew);
515 if (pPE->Signature != IMAGE_NT_SIGNATURE)
516 return NULL;
517 pImpDesc = (PIMAGE_IMPORT_DESCRIPTOR)(pImage
518 + pPE->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT]
519 .VirtualAddress);
520 for (; pImpDesc->FirstThunk; ++pImpDesc)
521 {
522 if (!pImpDesc->OriginalFirstThunk)
523 continue;
524 pIAT = (PIMAGE_THUNK_DATA)(pImage + pImpDesc->FirstThunk);
525 pINT = (PIMAGE_THUNK_DATA)(pImage + pImpDesc->OriginalFirstThunk);
526 for (; pIAT->u1.Function; ++pIAT, ++pINT)
527 {
528 if (IMAGE_SNAP_BY_ORDINAL(pINT->u1.Ordinal))
529 continue;
530 pImpName = (PIMAGE_IMPORT_BY_NAME)(pImage
531 + (UINT_PTR)(pINT->u1.AddressOfData));
532 if (strcmp((char *)pImpName->Name, funcname) == 0)
533 {
534 switch (info)
535 {
536 case 0:
537 return (void *)pIAT->u1.Function;
538 case 1:
539 return (void *)(pImage + pImpDesc->Name);
540 default:
541 return NULL;
542 }
543 }
544 }
545 }
546 return NULL;
547}
548
549/*
550 * Get the module handle which 'funcname' in 'hInst' is imported from.
551 */
552 HINSTANCE
553find_imported_module_by_funcname(HINSTANCE hInst, const char *funcname)
554{
555 char *modulename;
556
557 modulename = (char *)get_imported_func_info(hInst, funcname, 1);
558 if (modulename != NULL)
559 return GetModuleHandleA(modulename);
560 return NULL;
561}
562
563/*
564 * Get the address of 'funcname' which is imported by 'hInst' DLL.
565 */
566 void *
567get_dll_import_func(HINSTANCE hInst, const char *funcname)
568{
569 return get_imported_func_info(hInst, funcname, 0);
570}
571#endif
572
Bram Moolenaar071d4272004-06-13 20:20:40 +0000573#if defined(DYNAMIC_GETTEXT) || defined(PROTO)
574# ifndef GETTEXT_DLL
575# define GETTEXT_DLL "libintl.dll"
Bram Moolenaar7554c542018-10-06 15:03:15 +0200576# define GETTEXT_DLL_ALT1 "libintl-8.dll"
577# define GETTEXT_DLL_ALT2 "intl.dll"
Bram Moolenaar071d4272004-06-13 20:20:40 +0000578# endif
Bram Moolenaarf6a2b082012-06-29 13:14:03 +0200579/* Dummy functions */
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000580static char *null_libintl_gettext(const char *);
Bram Moolenaaree695f72016-08-03 22:08:45 +0200581static char *null_libintl_ngettext(const char *, const char *, unsigned long n);
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000582static char *null_libintl_textdomain(const char *);
583static char *null_libintl_bindtextdomain(const char *, const char *);
584static char *null_libintl_bind_textdomain_codeset(const char *, const char *);
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100585static int null_libintl_putenv(const char *);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100586static int null_libintl_wputenv(const wchar_t *);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000587
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200588static HINSTANCE hLibintlDLL = NULL;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000589char *(*dyn_libintl_gettext)(const char *) = null_libintl_gettext;
Bram Moolenaaree695f72016-08-03 22:08:45 +0200590char *(*dyn_libintl_ngettext)(const char *, const char *, unsigned long n)
591 = null_libintl_ngettext;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000592char *(*dyn_libintl_textdomain)(const char *) = null_libintl_textdomain;
593char *(*dyn_libintl_bindtextdomain)(const char *, const char *)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000594 = null_libintl_bindtextdomain;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000595char *(*dyn_libintl_bind_textdomain_codeset)(const char *, const char *)
596 = null_libintl_bind_textdomain_codeset;
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100597int (*dyn_libintl_putenv)(const char *) = null_libintl_putenv;
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100598int (*dyn_libintl_wputenv)(const wchar_t *) = null_libintl_wputenv;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000599
600 int
Bram Moolenaar05540972016-01-30 20:31:25 +0100601dyn_libintl_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000602{
603 int i;
604 static struct
605 {
606 char *name;
607 FARPROC *ptr;
608 } libintl_entry[] =
609 {
610 {"gettext", (FARPROC*)&dyn_libintl_gettext},
Bram Moolenaaree695f72016-08-03 22:08:45 +0200611 {"ngettext", (FARPROC*)&dyn_libintl_ngettext},
Bram Moolenaar071d4272004-06-13 20:20:40 +0000612 {"textdomain", (FARPROC*)&dyn_libintl_textdomain},
613 {"bindtextdomain", (FARPROC*)&dyn_libintl_bindtextdomain},
614 {NULL, NULL}
615 };
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100616 HINSTANCE hmsvcrt;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000617
Bram Moolenaar7554c542018-10-06 15:03:15 +0200618 // No need to initialize twice.
619 if (hLibintlDLL != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000620 return 1;
Bram Moolenaar7554c542018-10-06 15:03:15 +0200621 // Load gettext library (libintl.dll and other names).
Bram Moolenaar923e43b2016-01-28 15:07:38 +0100622 hLibintlDLL = vimLoadLib(GETTEXT_DLL);
Bram Moolenaar7554c542018-10-06 15:03:15 +0200623#ifdef GETTEXT_DLL_ALT1
Bram Moolenaar286eacd2016-01-16 18:05:50 +0100624 if (!hLibintlDLL)
Bram Moolenaar7554c542018-10-06 15:03:15 +0200625 hLibintlDLL = vimLoadLib(GETTEXT_DLL_ALT1);
626#endif
627#ifdef GETTEXT_DLL_ALT2
628 if (!hLibintlDLL)
629 hLibintlDLL = vimLoadLib(GETTEXT_DLL_ALT2);
Bram Moolenaar938ee832016-01-24 15:36:03 +0100630#endif
631 if (!hLibintlDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000632 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200633 if (p_verbose > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000634 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200635 verbose_enter();
636 EMSG2(_(e_loadlib), GETTEXT_DLL);
637 verbose_leave();
Bram Moolenaar071d4272004-06-13 20:20:40 +0000638 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200639 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000640 }
641 for (i = 0; libintl_entry[i].name != NULL
642 && libintl_entry[i].ptr != NULL; ++i)
643 {
644 if ((*libintl_entry[i].ptr = (FARPROC)GetProcAddress(hLibintlDLL,
645 libintl_entry[i].name)) == NULL)
646 {
647 dyn_libintl_end();
648 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +0000649 {
650 verbose_enter();
Bram Moolenaar071d4272004-06-13 20:20:40 +0000651 EMSG2(_(e_loadfunc), libintl_entry[i].name);
Bram Moolenaara04f10b2005-05-31 22:09:46 +0000652 verbose_leave();
653 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000654 return 0;
655 }
656 }
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000657
658 /* The bind_textdomain_codeset() function is optional. */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000659 dyn_libintl_bind_textdomain_codeset = (void *)GetProcAddress(hLibintlDLL,
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000660 "bind_textdomain_codeset");
661 if (dyn_libintl_bind_textdomain_codeset == NULL)
662 dyn_libintl_bind_textdomain_codeset =
663 null_libintl_bind_textdomain_codeset;
664
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100665 /* _putenv() function for the libintl.dll is optional. */
666 hmsvcrt = find_imported_module_by_funcname(hLibintlDLL, "getenv");
667 if (hmsvcrt != NULL)
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100668 {
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100669 dyn_libintl_putenv = (void *)GetProcAddress(hmsvcrt, "_putenv");
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100670 dyn_libintl_wputenv = (void *)GetProcAddress(hmsvcrt, "_wputenv");
671 }
672 if (dyn_libintl_putenv == NULL || dyn_libintl_putenv == _putenv)
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100673 dyn_libintl_putenv = null_libintl_putenv;
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100674 if (dyn_libintl_wputenv == NULL || dyn_libintl_wputenv == _wputenv)
675 dyn_libintl_wputenv = null_libintl_wputenv;
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100676
Bram Moolenaar071d4272004-06-13 20:20:40 +0000677 return 1;
678}
679
680 void
Bram Moolenaar05540972016-01-30 20:31:25 +0100681dyn_libintl_end(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000682{
683 if (hLibintlDLL)
684 FreeLibrary(hLibintlDLL);
685 hLibintlDLL = NULL;
686 dyn_libintl_gettext = null_libintl_gettext;
Bram Moolenaaree695f72016-08-03 22:08:45 +0200687 dyn_libintl_ngettext = null_libintl_ngettext;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000688 dyn_libintl_textdomain = null_libintl_textdomain;
689 dyn_libintl_bindtextdomain = null_libintl_bindtextdomain;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000690 dyn_libintl_bind_textdomain_codeset = null_libintl_bind_textdomain_codeset;
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100691 dyn_libintl_putenv = null_libintl_putenv;
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100692 dyn_libintl_wputenv = null_libintl_wputenv;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000693}
694
695 static char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000696null_libintl_gettext(const char *msgid)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000697{
698 return (char*)msgid;
699}
700
701 static char *
Bram Moolenaaree695f72016-08-03 22:08:45 +0200702null_libintl_ngettext(
703 const char *msgid,
704 const char *msgid_plural,
705 unsigned long n)
706{
Bram Moolenaarc90f2ae2016-08-04 22:00:15 +0200707 return (char *)(n == 1 ? msgid : msgid_plural);
Bram Moolenaaree695f72016-08-03 22:08:45 +0200708}
709
Bram Moolenaaree695f72016-08-03 22:08:45 +0200710 static char *
Bram Moolenaar1266d672017-02-01 13:43:36 +0100711null_libintl_bindtextdomain(
712 const char *domainname UNUSED,
713 const char *dirname UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000714{
715 return NULL;
716}
717
718 static char *
Bram Moolenaar1266d672017-02-01 13:43:36 +0100719null_libintl_bind_textdomain_codeset(
720 const char *domainname UNUSED,
721 const char *codeset UNUSED)
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000722{
723 return NULL;
724}
725
726 static char *
Bram Moolenaar1266d672017-02-01 13:43:36 +0100727null_libintl_textdomain(const char *domainname UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000728{
729 return NULL;
730}
731
Bram Moolenaare0ab9792017-08-02 23:18:25 +0200732 static int
Bram Moolenaar1266d672017-02-01 13:43:36 +0100733null_libintl_putenv(const char *envstring UNUSED)
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100734{
735 return 0;
736}
737
Bram Moolenaare0ab9792017-08-02 23:18:25 +0200738 static int
Bram Moolenaar1266d672017-02-01 13:43:36 +0100739null_libintl_wputenv(const wchar_t *envstring UNUSED)
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100740{
741 return 0;
742}
743
Bram Moolenaar071d4272004-06-13 20:20:40 +0000744#endif /* DYNAMIC_GETTEXT */
745
746/* This symbol is not defined in older versions of the SDK or Visual C++ */
747
748#ifndef VER_PLATFORM_WIN32_WINDOWS
749# define VER_PLATFORM_WIN32_WINDOWS 1
750#endif
751
752DWORD g_PlatformId;
753
754#ifdef HAVE_ACL
Bram Moolenaar82881492012-11-20 16:53:39 +0100755# ifndef PROTO
756# include <aclapi.h>
757# endif
Bram Moolenaar27515922013-06-29 15:36:26 +0200758# ifndef PROTECTED_DACL_SECURITY_INFORMATION
759# define PROTECTED_DACL_SECURITY_INFORMATION 0x80000000L
760# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000761#endif
762
Bram Moolenaar27515922013-06-29 15:36:26 +0200763#ifdef HAVE_ACL
764/*
765 * Enables or disables the specified privilege.
766 */
767 static BOOL
768win32_enable_privilege(LPTSTR lpszPrivilege, BOOL bEnable)
769{
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100770 BOOL bResult;
771 LUID luid;
772 HANDLE hToken;
773 TOKEN_PRIVILEGES tokenPrivileges;
Bram Moolenaar27515922013-06-29 15:36:26 +0200774
775 if (!OpenProcessToken(GetCurrentProcess(),
776 TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
777 return FALSE;
778
779 if (!LookupPrivilegeValue(NULL, lpszPrivilege, &luid))
780 {
781 CloseHandle(hToken);
782 return FALSE;
783 }
784
Bram Moolenaar45500912014-07-09 20:51:07 +0200785 tokenPrivileges.PrivilegeCount = 1;
Bram Moolenaar27515922013-06-29 15:36:26 +0200786 tokenPrivileges.Privileges[0].Luid = luid;
787 tokenPrivileges.Privileges[0].Attributes = bEnable ?
788 SE_PRIVILEGE_ENABLED : 0;
789
790 bResult = AdjustTokenPrivileges(hToken, FALSE, &tokenPrivileges,
791 sizeof(TOKEN_PRIVILEGES), NULL, NULL);
792
793 CloseHandle(hToken);
794
795 return bResult && GetLastError() == ERROR_SUCCESS;
796}
797#endif
798
Bram Moolenaar071d4272004-06-13 20:20:40 +0000799/*
800 * Set g_PlatformId to VER_PLATFORM_WIN32_NT (NT) or
801 * VER_PLATFORM_WIN32_WINDOWS (Win95).
802 */
803 void
804PlatformId(void)
805{
806 static int done = FALSE;
807
808 if (!done)
809 {
810 OSVERSIONINFO ovi;
811
812 ovi.dwOSVersionInfoSize = sizeof(ovi);
813 GetVersionEx(&ovi);
814
815 g_PlatformId = ovi.dwPlatformId;
816
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100817 if ((ovi.dwMajorVersion == 6 && ovi.dwMinorVersion >= 2)
818 || ovi.dwMajorVersion > 6)
819 win8_or_later = TRUE;
820
Bram Moolenaar071d4272004-06-13 20:20:40 +0000821#ifdef HAVE_ACL
Bram Moolenaarcea912a2016-10-12 14:20:24 +0200822 /* Enable privilege for getting or setting SACLs. */
823 win32_enable_privilege(SE_SECURITY_NAME, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000824#endif
825 done = TRUE;
826 }
827}
828
Bram Moolenaar071d4272004-06-13 20:20:40 +0000829#ifndef FEAT_GUI_W32
830
831#define SHIFT (SHIFT_PRESSED)
832#define CTRL (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED)
833#define ALT (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED)
834#define ALT_GR (RIGHT_ALT_PRESSED | LEFT_CTRL_PRESSED)
835
836
837/* When uChar.AsciiChar is 0, then we need to look at wVirtualKeyCode.
838 * We map function keys to their ANSI terminal equivalents, as produced
839 * by ANSI.SYS, for compatibility with the MS-DOS version of Vim. Any
840 * ANSI key with a value >= '\300' is nonstandard, but provided anyway
841 * so that the user can have access to all SHIFT-, CTRL-, and ALT-
842 * combinations of function/arrow/etc keys.
843 */
844
Bram Moolenaard6f676d2005-06-01 21:51:55 +0000845static const struct
Bram Moolenaar071d4272004-06-13 20:20:40 +0000846{
847 WORD wVirtKey;
848 BOOL fAnsiKey;
849 int chAlone;
850 int chShift;
851 int chCtrl;
852 int chAlt;
853} VirtKeyMap[] =
854{
Bram Moolenaar071d4272004-06-13 20:20:40 +0000855/* Key ANSI alone shift ctrl alt */
856 { VK_ESCAPE,FALSE, ESC, ESC, ESC, ESC, },
857
858 { VK_F1, TRUE, ';', 'T', '^', 'h', },
859 { VK_F2, TRUE, '<', 'U', '_', 'i', },
860 { VK_F3, TRUE, '=', 'V', '`', 'j', },
861 { VK_F4, TRUE, '>', 'W', 'a', 'k', },
862 { VK_F5, TRUE, '?', 'X', 'b', 'l', },
863 { VK_F6, TRUE, '@', 'Y', 'c', 'm', },
864 { VK_F7, TRUE, 'A', 'Z', 'd', 'n', },
865 { VK_F8, TRUE, 'B', '[', 'e', 'o', },
866 { VK_F9, TRUE, 'C', '\\', 'f', 'p', },
867 { VK_F10, TRUE, 'D', ']', 'g', 'q', },
Bram Moolenaar2bc152a2018-10-03 20:44:20 +0200868 { VK_F11, TRUE, 0x85, 0x87, 0x89, 0x8B, },
869 { VK_F12, TRUE, 0x86, 0x88, 0x8a, 0x8c, },
Bram Moolenaar071d4272004-06-13 20:20:40 +0000870
Bram Moolenaar2bc152a2018-10-03 20:44:20 +0200871 { VK_HOME, TRUE, 'G', 0xc2, 'w', 0xc3, },
872 { VK_UP, TRUE, 'H', 0xc4, 0xc5, 0xc6, },
873 { VK_PRIOR, TRUE, 'I', 0xc7, 0x84, 0xc8, }, /*PgUp*/
874 { VK_LEFT, TRUE, 'K', 0xc9, 's', 0xca, },
875 { VK_RIGHT, TRUE, 'M', 0xcb, 't', 0xcc, },
876 { VK_END, TRUE, 'O', 0xcd, 'u', 0xce, },
877 { VK_DOWN, TRUE, 'P', 0xcf, 0xd0, 0xd1, },
878 { VK_NEXT, TRUE, 'Q', 0xd2, 'v', 0xd3, }, /*PgDn*/
879 { VK_INSERT,TRUE, 'R', 0xd4, 0xd5, 0xd6, },
880 { VK_DELETE,TRUE, 'S', 0xd7, 0xd8, 0xd9, },
Bram Moolenaar071d4272004-06-13 20:20:40 +0000881
882 { VK_SNAPSHOT,TRUE, 0, 0, 0, 'r', }, /*PrtScrn*/
883
884#if 0
885 /* Most people don't have F13-F20, but what the hell... */
Bram Moolenaar2bc152a2018-10-03 20:44:20 +0200886 { VK_F13, TRUE, 0xda, 0xdb, 0xdc, 0xdd, },
887 { VK_F14, TRUE, 0xde, 0xdf, 0xe0, 0xe1, },
888 { VK_F15, TRUE, 0xe2, 0xe3, 0xe4, 0xe5, },
889 { VK_F16, TRUE, 0xe6, 0xe7, 0xe8, 0xe9, },
890 { VK_F17, TRUE, 0xea, 0xeb, 0xec, 0xed, },
891 { VK_F18, TRUE, 0xee, 0xef, 0xf0, 0xf1, },
892 { VK_F19, TRUE, 0xf2, 0xf3, 0xf4, 0xf5, },
893 { VK_F20, TRUE, 0xf6, 0xf7, 0xf8, 0xf9, },
Bram Moolenaar071d4272004-06-13 20:20:40 +0000894#endif
895 { VK_ADD, TRUE, 'N', 'N', 'N', 'N', }, /* keyp '+' */
896 { VK_SUBTRACT, TRUE,'J', 'J', 'J', 'J', }, /* keyp '-' */
897 /* { VK_DIVIDE, TRUE,'N', 'N', 'N', 'N', }, keyp '/' */
898 { VK_MULTIPLY, TRUE,'7', '7', '7', '7', }, /* keyp '*' */
899
Bram Moolenaar2bc152a2018-10-03 20:44:20 +0200900 { VK_NUMPAD0,TRUE, 0xda, 0xdb, 0xdc, 0xdd, },
901 { VK_NUMPAD1,TRUE, 0xde, 0xdf, 0xe0, 0xe1, },
902 { VK_NUMPAD2,TRUE, 0xe2, 0xe3, 0xe4, 0xe5, },
903 { VK_NUMPAD3,TRUE, 0xe6, 0xe7, 0xe8, 0xe9, },
904 { VK_NUMPAD4,TRUE, 0xea, 0xeb, 0xec, 0xed, },
905 { VK_NUMPAD5,TRUE, 0xee, 0xef, 0xf0, 0xf1, },
906 { VK_NUMPAD6,TRUE, 0xf2, 0xf3, 0xf4, 0xf5, },
907 { VK_NUMPAD7,TRUE, 0xf6, 0xf7, 0xf8, 0xf9, },
908 { VK_NUMPAD8,TRUE, 0xfa, 0xfb, 0xfc, 0xfd, },
Bram Moolenaar071d4272004-06-13 20:20:40 +0000909 /* Sorry, out of number space! <negri>*/
Bram Moolenaar2bc152a2018-10-03 20:44:20 +0200910 { VK_NUMPAD9,TRUE, 0xfe, 0xff, 0xff, 0xf7, },
Bram Moolenaar071d4272004-06-13 20:20:40 +0000911};
912
913
914#ifdef _MSC_VER
915// The ToAscii bug destroys several registers. Need to turn off optimization
916// or the GetConsoleKeyboardLayoutName hack will fail in non-debug versions
Bram Moolenaar7b5f8322006-03-23 22:47:08 +0000917# pragma warning(push)
918# pragma warning(disable: 4748)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000919# pragma optimize("", off)
920#endif
921
922#if defined(__GNUC__) && !defined(__MINGW32__) && !defined(__CYGWIN__)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200923# define UChar UnicodeChar
Bram Moolenaar071d4272004-06-13 20:20:40 +0000924#else
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200925# define UChar uChar.UnicodeChar
Bram Moolenaar071d4272004-06-13 20:20:40 +0000926#endif
927
928/* The return code indicates key code size. */
929 static int
930#ifdef __BORLANDC__
931 __stdcall
932#endif
933win32_kbd_patch_key(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000934 KEY_EVENT_RECORD *pker)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000935{
936 UINT uMods = pker->dwControlKeyState;
937 static int s_iIsDead = 0;
938 static WORD awAnsiCode[2];
939 static BYTE abKeystate[256];
940
941
942 if (s_iIsDead == 2)
943 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200944 pker->UChar = (WCHAR) awAnsiCode[1];
Bram Moolenaar071d4272004-06-13 20:20:40 +0000945 s_iIsDead = 0;
946 return 1;
947 }
948
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200949 if (pker->UChar != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000950 return 1;
951
Bram Moolenaar7db5fc82010-05-24 11:59:29 +0200952 vim_memset(abKeystate, 0, sizeof (abKeystate));
Bram Moolenaar071d4272004-06-13 20:20:40 +0000953
Bram Moolenaar071d4272004-06-13 20:20:40 +0000954 /* Clear any pending dead keys */
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200955 ToUnicode(VK_SPACE, MapVirtualKey(VK_SPACE, 0), abKeystate, awAnsiCode, 2, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000956
957 if (uMods & SHIFT_PRESSED)
958 abKeystate[VK_SHIFT] = 0x80;
959 if (uMods & CAPSLOCK_ON)
960 abKeystate[VK_CAPITAL] = 1;
961
962 if ((uMods & ALT_GR) == ALT_GR)
963 {
964 abKeystate[VK_CONTROL] = abKeystate[VK_LCONTROL] =
965 abKeystate[VK_MENU] = abKeystate[VK_RMENU] = 0x80;
966 }
967
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200968 s_iIsDead = ToUnicode(pker->wVirtualKeyCode, pker->wVirtualScanCode,
969 abKeystate, awAnsiCode, 2, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000970
971 if (s_iIsDead > 0)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200972 pker->UChar = (WCHAR) awAnsiCode[0];
Bram Moolenaar071d4272004-06-13 20:20:40 +0000973
974 return s_iIsDead;
975}
976
977#ifdef _MSC_VER
978/* MUST switch optimization on again here, otherwise a call to
979 * decode_key_event() may crash (e.g. when hitting caps-lock) */
980# pragma optimize("", on)
Bram Moolenaar7b5f8322006-03-23 22:47:08 +0000981# pragma warning(pop)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000982
983# if (_MSC_VER < 1100)
984/* MUST turn off global optimisation for this next function, or
985 * pressing ctrl-minus in insert mode crashes Vim when built with
986 * VC4.1. -- negri. */
987# pragma optimize("g", off)
988# endif
989#endif
990
991static BOOL g_fJustGotFocus = FALSE;
992
993/*
994 * Decode a KEY_EVENT into one or two keystrokes
995 */
996 static BOOL
997decode_key_event(
998 KEY_EVENT_RECORD *pker,
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200999 WCHAR *pch,
1000 WCHAR *pch2,
Bram Moolenaar071d4272004-06-13 20:20:40 +00001001 int *pmodifiers,
1002 BOOL fDoPost)
1003{
1004 int i;
1005 const int nModifs = pker->dwControlKeyState & (SHIFT | ALT | CTRL);
1006
1007 *pch = *pch2 = NUL;
1008 g_fJustGotFocus = FALSE;
1009
1010 /* ignore key up events */
1011 if (!pker->bKeyDown)
1012 return FALSE;
1013
1014 /* ignore some keystrokes */
1015 switch (pker->wVirtualKeyCode)
1016 {
1017 /* modifiers */
1018 case VK_SHIFT:
1019 case VK_CONTROL:
1020 case VK_MENU: /* Alt key */
1021 return FALSE;
1022
1023 default:
1024 break;
1025 }
1026
1027 /* special cases */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001028 if ((nModifs & CTRL) != 0 && (nModifs & ~CTRL) == 0 && pker->UChar == NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001029 {
1030 /* Ctrl-6 is Ctrl-^ */
1031 if (pker->wVirtualKeyCode == '6')
1032 {
1033 *pch = Ctrl_HAT;
1034 return TRUE;
1035 }
1036 /* Ctrl-2 is Ctrl-@ */
1037 else if (pker->wVirtualKeyCode == '2')
1038 {
1039 *pch = NUL;
1040 return TRUE;
1041 }
1042 /* Ctrl-- is Ctrl-_ */
1043 else if (pker->wVirtualKeyCode == 0xBD)
1044 {
1045 *pch = Ctrl__;
1046 return TRUE;
1047 }
1048 }
1049
1050 /* Shift-TAB */
1051 if (pker->wVirtualKeyCode == VK_TAB && (nModifs & SHIFT_PRESSED))
1052 {
1053 *pch = K_NUL;
1054 *pch2 = '\017';
1055 return TRUE;
1056 }
1057
1058 for (i = sizeof(VirtKeyMap) / sizeof(VirtKeyMap[0]); --i >= 0; )
1059 {
1060 if (VirtKeyMap[i].wVirtKey == pker->wVirtualKeyCode)
1061 {
1062 if (nModifs == 0)
1063 *pch = VirtKeyMap[i].chAlone;
1064 else if ((nModifs & SHIFT) != 0 && (nModifs & ~SHIFT) == 0)
1065 *pch = VirtKeyMap[i].chShift;
1066 else if ((nModifs & CTRL) != 0 && (nModifs & ~CTRL) == 0)
1067 *pch = VirtKeyMap[i].chCtrl;
1068 else if ((nModifs & ALT) != 0 && (nModifs & ~ALT) == 0)
1069 *pch = VirtKeyMap[i].chAlt;
1070
1071 if (*pch != 0)
1072 {
1073 if (VirtKeyMap[i].fAnsiKey)
1074 {
1075 *pch2 = *pch;
1076 *pch = K_NUL;
1077 }
1078
1079 return TRUE;
1080 }
1081 }
1082 }
1083
1084 i = win32_kbd_patch_key(pker);
1085
1086 if (i < 0)
1087 *pch = NUL;
1088 else
1089 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001090 *pch = (i > 0) ? pker->UChar : NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001091
1092 if (pmodifiers != NULL)
1093 {
1094 /* Pass on the ALT key as a modifier, but only when not combined
1095 * with CTRL (which is ALTGR). */
1096 if ((nModifs & ALT) != 0 && (nModifs & CTRL) == 0)
1097 *pmodifiers |= MOD_MASK_ALT;
1098
1099 /* Pass on SHIFT only for special keys, because we don't know when
1100 * it's already included with the character. */
1101 if ((nModifs & SHIFT) != 0 && *pch <= 0x20)
1102 *pmodifiers |= MOD_MASK_SHIFT;
1103
1104 /* Pass on CTRL only for non-special keys, because we don't know
1105 * when it's already included with the character. And not when
1106 * combined with ALT (which is ALTGR). */
1107 if ((nModifs & CTRL) != 0 && (nModifs & ALT) == 0
1108 && *pch >= 0x20 && *pch < 0x80)
1109 *pmodifiers |= MOD_MASK_CTRL;
1110 }
1111 }
1112
1113 return (*pch != NUL);
1114}
1115
1116#ifdef _MSC_VER
1117# pragma optimize("", on)
1118#endif
1119
1120#endif /* FEAT_GUI_W32 */
1121
1122
1123#ifdef FEAT_MOUSE
1124
1125/*
1126 * For the GUI the mouse handling is in gui_w32.c.
1127 */
1128# ifdef FEAT_GUI_W32
1129 void
Bram Moolenaar1266d672017-02-01 13:43:36 +01001130mch_setmouse(int on UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001131{
1132}
1133# else
1134static int g_fMouseAvail = FALSE; /* mouse present */
1135static int g_fMouseActive = FALSE; /* mouse enabled */
1136static int g_nMouseClick = -1; /* mouse status */
1137static int g_xMouse; /* mouse x coordinate */
1138static int g_yMouse; /* mouse y coordinate */
1139
1140/*
1141 * Enable or disable mouse input
1142 */
1143 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001144mch_setmouse(int on)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001145{
1146 DWORD cmodein;
1147
1148 if (!g_fMouseAvail)
1149 return;
1150
1151 g_fMouseActive = on;
1152 GetConsoleMode(g_hConIn, &cmodein);
1153
1154 if (g_fMouseActive)
1155 cmodein |= ENABLE_MOUSE_INPUT;
1156 else
1157 cmodein &= ~ENABLE_MOUSE_INPUT;
1158
1159 SetConsoleMode(g_hConIn, cmodein);
1160}
1161
Bram Moolenaar157d8132018-03-06 17:09:20 +01001162
1163#if defined(FEAT_BEVAL_TERM) || defined(PROTO)
1164/*
1165 * Called when 'balloonevalterm' changed.
1166 */
1167 void
1168mch_bevalterm_changed(void)
1169{
1170 mch_setmouse(g_fMouseActive);
1171}
1172#endif
1173
Bram Moolenaar071d4272004-06-13 20:20:40 +00001174/*
1175 * Decode a MOUSE_EVENT. If it's a valid event, return MOUSE_LEFT,
1176 * MOUSE_MIDDLE, or MOUSE_RIGHT for a click; MOUSE_DRAG for a mouse
1177 * move with a button held down; and MOUSE_RELEASE after a MOUSE_DRAG
1178 * or a MOUSE_LEFT, _MIDDLE, or _RIGHT. We encode the button type,
1179 * the number of clicks, and the Shift/Ctrl/Alt modifiers in g_nMouseClick,
1180 * and we return the mouse position in g_xMouse and g_yMouse.
1181 *
1182 * Every MOUSE_LEFT, _MIDDLE, or _RIGHT will be followed by zero or more
1183 * MOUSE_DRAGs and one MOUSE_RELEASE. MOUSE_RELEASE will be followed only
1184 * by MOUSE_LEFT, _MIDDLE, or _RIGHT.
1185 *
1186 * For multiple clicks, we send, say, MOUSE_LEFT/1 click, MOUSE_RELEASE,
1187 * MOUSE_LEFT/2 clicks, MOUSE_RELEASE, MOUSE_LEFT/3 clicks, MOUSE_RELEASE, ....
1188 *
1189 * Windows will send us MOUSE_MOVED notifications whenever the mouse
1190 * moves, even if it stays within the same character cell. We ignore
1191 * all MOUSE_MOVED messages if the position hasn't really changed, and
1192 * we ignore all MOUSE_MOVED messages where no button is held down (i.e.,
1193 * we're only interested in MOUSE_DRAG).
1194 *
1195 * All of this is complicated by the code that fakes MOUSE_MIDDLE on
1196 * 2-button mouses by pressing the left & right buttons simultaneously.
1197 * In practice, it's almost impossible to click both at the same time,
1198 * so we need to delay a little. Also, we tend not to get MOUSE_RELEASE
1199 * in such cases, if the user is clicking quickly.
1200 */
1201 static BOOL
1202decode_mouse_event(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001203 MOUSE_EVENT_RECORD *pmer)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001204{
1205 static int s_nOldButton = -1;
1206 static int s_nOldMouseClick = -1;
1207 static int s_xOldMouse = -1;
1208 static int s_yOldMouse = -1;
1209 static linenr_T s_old_topline = 0;
1210#ifdef FEAT_DIFF
1211 static int s_old_topfill = 0;
1212#endif
1213 static int s_cClicks = 1;
1214 static BOOL s_fReleased = TRUE;
1215 static DWORD s_dwLastClickTime = 0;
1216 static BOOL s_fNextIsMiddle = FALSE;
1217
1218 static DWORD cButtons = 0; /* number of buttons supported */
1219
1220 const DWORD LEFT = FROM_LEFT_1ST_BUTTON_PRESSED;
1221 const DWORD MIDDLE = FROM_LEFT_2ND_BUTTON_PRESSED;
1222 const DWORD RIGHT = RIGHTMOST_BUTTON_PRESSED;
1223 const DWORD LEFT_RIGHT = LEFT | RIGHT;
1224
1225 int nButton;
1226
1227 if (cButtons == 0 && !GetNumberOfConsoleMouseButtons(&cButtons))
1228 cButtons = 2;
1229
1230 if (!g_fMouseAvail || !g_fMouseActive)
1231 {
1232 g_nMouseClick = -1;
1233 return FALSE;
1234 }
1235
1236 /* get a spurious MOUSE_EVENT immediately after receiving focus; ignore */
1237 if (g_fJustGotFocus)
1238 {
1239 g_fJustGotFocus = FALSE;
1240 return FALSE;
1241 }
1242
1243 /* unprocessed mouse click? */
1244 if (g_nMouseClick != -1)
1245 return TRUE;
1246
1247 nButton = -1;
1248 g_xMouse = pmer->dwMousePosition.X;
1249 g_yMouse = pmer->dwMousePosition.Y;
1250
1251 if (pmer->dwEventFlags == MOUSE_MOVED)
1252 {
Bram Moolenaar157d8132018-03-06 17:09:20 +01001253 /* Ignore MOUSE_MOVED events if (x, y) hasn't changed. (We get these
Bram Moolenaar071d4272004-06-13 20:20:40 +00001254 * events even when the mouse moves only within a char cell.) */
1255 if (s_xOldMouse == g_xMouse && s_yOldMouse == g_yMouse)
1256 return FALSE;
1257 }
1258
1259 /* If no buttons are pressed... */
1260 if ((pmer->dwButtonState & ((1 << cButtons) - 1)) == 0)
1261 {
Bram Moolenaar157d8132018-03-06 17:09:20 +01001262 nButton = MOUSE_RELEASE;
1263
Bram Moolenaar071d4272004-06-13 20:20:40 +00001264 /* If the last thing returned was MOUSE_RELEASE, ignore this */
1265 if (s_fReleased)
Bram Moolenaar157d8132018-03-06 17:09:20 +01001266 {
1267#ifdef FEAT_BEVAL_TERM
1268 /* do return mouse move events when we want them */
1269 if (p_bevalterm)
1270 nButton = MOUSE_DRAG;
1271 else
1272#endif
1273 return FALSE;
1274 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001275
Bram Moolenaar071d4272004-06-13 20:20:40 +00001276 s_fReleased = TRUE;
1277 }
1278 else /* one or more buttons pressed */
1279 {
1280 /* on a 2-button mouse, hold down left and right buttons
1281 * simultaneously to get MIDDLE. */
1282
1283 if (cButtons == 2 && s_nOldButton != MOUSE_DRAG)
1284 {
1285 DWORD dwLR = (pmer->dwButtonState & LEFT_RIGHT);
1286
1287 /* if either left or right button only is pressed, see if the
Bram Moolenaar84a05ac2013-05-06 04:24:17 +02001288 * next mouse event has both of them pressed */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001289 if (dwLR == LEFT || dwLR == RIGHT)
1290 {
1291 for (;;)
1292 {
1293 /* wait a short time for next input event */
1294 if (WaitForSingleObject(g_hConIn, p_mouset / 3)
1295 != WAIT_OBJECT_0)
1296 break;
1297 else
1298 {
1299 DWORD cRecords = 0;
1300 INPUT_RECORD ir;
1301 MOUSE_EVENT_RECORD* pmer2 = &ir.Event.MouseEvent;
1302
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001303 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001304
1305 if (cRecords == 0 || ir.EventType != MOUSE_EVENT
1306 || !(pmer2->dwButtonState & LEFT_RIGHT))
1307 break;
1308 else
1309 {
1310 if (pmer2->dwEventFlags != MOUSE_MOVED)
1311 {
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001312 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001313
1314 return decode_mouse_event(pmer2);
1315 }
1316 else if (s_xOldMouse == pmer2->dwMousePosition.X &&
1317 s_yOldMouse == pmer2->dwMousePosition.Y)
1318 {
1319 /* throw away spurious mouse move */
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001320 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001321
1322 /* are there any more mouse events in queue? */
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001323 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001324
1325 if (cRecords==0 || ir.EventType != MOUSE_EVENT)
1326 break;
1327 }
1328 else
1329 break;
1330 }
1331 }
1332 }
1333 }
1334 }
1335
1336 if (s_fNextIsMiddle)
1337 {
1338 nButton = (pmer->dwEventFlags == MOUSE_MOVED)
1339 ? MOUSE_DRAG : MOUSE_MIDDLE;
1340 s_fNextIsMiddle = FALSE;
1341 }
1342 else if (cButtons == 2 &&
1343 ((pmer->dwButtonState & LEFT_RIGHT) == LEFT_RIGHT))
1344 {
1345 nButton = MOUSE_MIDDLE;
1346
1347 if (! s_fReleased && pmer->dwEventFlags != MOUSE_MOVED)
1348 {
1349 s_fNextIsMiddle = TRUE;
1350 nButton = MOUSE_RELEASE;
1351 }
1352 }
1353 else if ((pmer->dwButtonState & LEFT) == LEFT)
1354 nButton = MOUSE_LEFT;
1355 else if ((pmer->dwButtonState & MIDDLE) == MIDDLE)
1356 nButton = MOUSE_MIDDLE;
1357 else if ((pmer->dwButtonState & RIGHT) == RIGHT)
1358 nButton = MOUSE_RIGHT;
1359
1360 if (! s_fReleased && ! s_fNextIsMiddle
1361 && nButton != s_nOldButton && s_nOldButton != MOUSE_DRAG)
1362 return FALSE;
1363
1364 s_fReleased = s_fNextIsMiddle;
1365 }
1366
1367 if (pmer->dwEventFlags == 0 || pmer->dwEventFlags == DOUBLE_CLICK)
1368 {
1369 /* button pressed or released, without mouse moving */
1370 if (nButton != -1 && nButton != MOUSE_RELEASE)
1371 {
1372 DWORD dwCurrentTime = GetTickCount();
1373
1374 if (s_xOldMouse != g_xMouse
1375 || s_yOldMouse != g_yMouse
1376 || s_nOldButton != nButton
1377 || s_old_topline != curwin->w_topline
1378#ifdef FEAT_DIFF
1379 || s_old_topfill != curwin->w_topfill
1380#endif
1381 || (int)(dwCurrentTime - s_dwLastClickTime) > p_mouset)
1382 {
1383 s_cClicks = 1;
1384 }
1385 else if (++s_cClicks > 4)
1386 {
1387 s_cClicks = 1;
1388 }
1389
1390 s_dwLastClickTime = dwCurrentTime;
1391 }
1392 }
1393 else if (pmer->dwEventFlags == MOUSE_MOVED)
1394 {
1395 if (nButton != -1 && nButton != MOUSE_RELEASE)
1396 nButton = MOUSE_DRAG;
1397
1398 s_cClicks = 1;
1399 }
1400
1401 if (nButton == -1)
1402 return FALSE;
1403
1404 if (nButton != MOUSE_RELEASE)
1405 s_nOldButton = nButton;
1406
1407 g_nMouseClick = nButton;
1408
1409 if (pmer->dwControlKeyState & SHIFT_PRESSED)
1410 g_nMouseClick |= MOUSE_SHIFT;
1411 if (pmer->dwControlKeyState & (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED))
1412 g_nMouseClick |= MOUSE_CTRL;
1413 if (pmer->dwControlKeyState & (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED))
1414 g_nMouseClick |= MOUSE_ALT;
1415
1416 if (nButton != MOUSE_DRAG && nButton != MOUSE_RELEASE)
1417 SET_NUM_MOUSE_CLICKS(g_nMouseClick, s_cClicks);
1418
1419 /* only pass on interesting (i.e., different) mouse events */
1420 if (s_xOldMouse == g_xMouse
1421 && s_yOldMouse == g_yMouse
1422 && s_nOldMouseClick == g_nMouseClick)
1423 {
1424 g_nMouseClick = -1;
1425 return FALSE;
1426 }
1427
1428 s_xOldMouse = g_xMouse;
1429 s_yOldMouse = g_yMouse;
1430 s_old_topline = curwin->w_topline;
1431#ifdef FEAT_DIFF
1432 s_old_topfill = curwin->w_topfill;
1433#endif
1434 s_nOldMouseClick = g_nMouseClick;
1435
1436 return TRUE;
1437}
1438
1439# endif /* FEAT_GUI_W32 */
1440#endif /* FEAT_MOUSE */
1441
1442
1443#ifdef MCH_CURSOR_SHAPE
1444/*
1445 * Set the shape of the cursor.
1446 * 'thickness' can be from 1 (thin) to 99 (block)
1447 */
1448 static void
1449mch_set_cursor_shape(int thickness)
1450{
1451 CONSOLE_CURSOR_INFO ConsoleCursorInfo;
1452 ConsoleCursorInfo.dwSize = thickness;
1453 ConsoleCursorInfo.bVisible = s_cursor_visible;
1454
1455 SetConsoleCursorInfo(g_hConOut, &ConsoleCursorInfo);
1456 if (s_cursor_visible)
1457 SetConsoleCursorPosition(g_hConOut, g_coord);
1458}
1459
1460 void
1461mch_update_cursor(void)
1462{
1463 int idx;
1464 int thickness;
1465
1466 /*
1467 * How the cursor is drawn depends on the current mode.
1468 */
1469 idx = get_shape_idx(FALSE);
1470
1471 if (shape_table[idx].shape == SHAPE_BLOCK)
1472 thickness = 99; /* 100 doesn't work on W95 */
1473 else
1474 thickness = shape_table[idx].percentage;
1475 mch_set_cursor_shape(thickness);
1476}
1477#endif
1478
1479#ifndef FEAT_GUI_W32 /* this isn't used for the GUI */
1480/*
1481 * Handle FOCUS_EVENT.
1482 */
1483 static void
1484handle_focus_event(INPUT_RECORD ir)
1485{
1486 g_fJustGotFocus = ir.Event.FocusEvent.bSetFocus;
1487 ui_focus_change((int)g_fJustGotFocus);
1488}
1489
1490/*
1491 * Wait until console input from keyboard or mouse is available,
1492 * or the time is up.
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001493 * When "ignore_input" is TRUE even wait when input is available.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001494 * Return TRUE if something is available FALSE if not.
1495 */
1496 static int
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001497WaitForChar(long msec, int ignore_input)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001498{
1499 DWORD dwNow = 0, dwEndTime = 0;
1500 INPUT_RECORD ir;
1501 DWORD cRecords;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001502 WCHAR ch, ch2;
Bram Moolenaar4445f7e2016-04-20 20:55:56 +02001503#ifdef FEAT_TIMERS
Bram Moolenaar40b1b542016-04-20 20:18:23 +02001504 int tb_change_cnt = typebuf.tb_change_cnt;
Bram Moolenaar4445f7e2016-04-20 20:55:56 +02001505#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001506
1507 if (msec > 0)
1508 /* Wait until the specified time has elapsed. */
1509 dwEndTime = GetTickCount() + msec;
1510 else if (msec < 0)
1511 /* Wait forever. */
1512 dwEndTime = INFINITE;
1513
1514 /* We need to loop until the end of the time period, because
1515 * we might get multiple unusable mouse events in that time.
1516 */
1517 for (;;)
1518 {
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001519 // Only process messages when waiting.
1520 if (msec != 0)
1521 {
Bram Moolenaarca568ae2016-02-01 21:32:58 +01001522#ifdef MESSAGE_QUEUE
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001523 parse_queued_messages();
Bram Moolenaarca568ae2016-02-01 21:32:58 +01001524#endif
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001525#ifdef FEAT_MZSCHEME
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001526 mzvim_check_threads();
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001527#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001528#ifdef FEAT_CLIENTSERVER
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001529 serverProcessPendingMessages();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001530#endif
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001531 }
Bram Moolenaarf12d9832016-01-29 21:11:25 +01001532
Bram Moolenaar071d4272004-06-13 20:20:40 +00001533 if (0
1534#ifdef FEAT_MOUSE
1535 || g_nMouseClick != -1
1536#endif
1537#ifdef FEAT_CLIENTSERVER
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001538 || (!ignore_input && input_available())
Bram Moolenaar071d4272004-06-13 20:20:40 +00001539#endif
1540 )
1541 return TRUE;
1542
1543 if (msec > 0)
1544 {
Bram Moolenaarb7512b72013-08-10 12:45:09 +02001545 /* If the specified wait time has passed, return. Beware that
1546 * GetTickCount() may wrap around (overflow). */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001547 dwNow = GetTickCount();
Bram Moolenaarb7512b72013-08-10 12:45:09 +02001548 if ((int)(dwNow - dwEndTime) >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001549 break;
1550 }
1551 if (msec != 0)
1552 {
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001553 DWORD dwWaitTime = dwEndTime - dwNow;
1554
Bram Moolenaar509ce2a2016-03-11 22:52:15 +01001555#ifdef FEAT_JOB_CHANNEL
Bram Moolenaar8a8199e2016-11-26 15:13:33 +01001556 /* Check channel while waiting for input. */
Bram Moolenaar9186a272016-02-23 19:34:01 +01001557 if (dwWaitTime > 100)
Bram Moolenaar8a8199e2016-11-26 15:13:33 +01001558 {
Bram Moolenaar9186a272016-02-23 19:34:01 +01001559 dwWaitTime = 100;
Bram Moolenaar8a8199e2016-11-26 15:13:33 +01001560 /* If there is readahead then parse_queued_messages() timed out
1561 * and we should call it again soon. */
1562 if (channel_any_readahead())
1563 dwWaitTime = 10;
1564 }
Bram Moolenaar9186a272016-02-23 19:34:01 +01001565#endif
Bram Moolenaarc3719bd2017-11-18 22:13:31 +01001566#ifdef FEAT_BEVAL_GUI
Bram Moolenaar59716a22017-03-01 20:32:44 +01001567 if (p_beval && dwWaitTime > 100)
1568 /* The 'balloonexpr' may indirectly invoke a callback while
1569 * waiting for a character, need to check often. */
1570 dwWaitTime = 100;
1571#endif
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001572#ifdef FEAT_MZSCHEME
1573 if (mzthreads_allowed() && p_mzq > 0
1574 && (msec < 0 || (long)dwWaitTime > p_mzq))
1575 dwWaitTime = p_mzq; /* don't wait longer than 'mzquantum' */
1576#endif
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001577#ifdef FEAT_TIMERS
1578 {
1579 long due_time;
1580
1581 /* When waiting very briefly don't trigger timers. */
1582 if (dwWaitTime > 10)
1583 {
1584 /* Trigger timers and then get the time in msec until the
1585 * next one is due. Wait up to that time. */
1586 due_time = check_due_timer();
Bram Moolenaar40b1b542016-04-20 20:18:23 +02001587 if (typebuf.tb_change_cnt != tb_change_cnt)
1588 {
1589 /* timer may have used feedkeys() */
1590 return FALSE;
1591 }
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001592 if (due_time > 0 && dwWaitTime > (DWORD)due_time)
1593 dwWaitTime = due_time;
1594 }
1595 }
1596#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001597#ifdef FEAT_CLIENTSERVER
1598 /* Wait for either an event on the console input or a message in
1599 * the client-server window. */
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +02001600 if (msg_wait_for_multiple_objects(1, &g_hConIn, FALSE,
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001601 dwWaitTime, QS_SENDMESSAGE) != WAIT_OBJECT_0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001602#else
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +02001603 if (wait_for_single_object(g_hConIn, dwWaitTime) != WAIT_OBJECT_0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001604#endif
1605 continue;
1606 }
1607
1608 cRecords = 0;
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001609 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001610
1611#ifdef FEAT_MBYTE_IME
1612 if (State & CMDLINE && msg_row == Rows - 1)
1613 {
1614 CONSOLE_SCREEN_BUFFER_INFO csbi;
1615
1616 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
1617 {
1618 if (csbi.dwCursorPosition.Y != msg_row)
1619 {
1620 /* The screen is now messed up, must redraw the
1621 * command line and later all the windows. */
1622 redraw_all_later(CLEAR);
1623 cmdline_row -= (msg_row - csbi.dwCursorPosition.Y);
1624 redrawcmd();
1625 }
1626 }
1627 }
1628#endif
1629
1630 if (cRecords > 0)
1631 {
1632 if (ir.EventType == KEY_EVENT && ir.Event.KeyEvent.bKeyDown)
1633 {
1634#ifdef FEAT_MBYTE_IME
1635 /* Windows IME sends two '\n's with only one 'ENTER'. First:
1636 * wVirtualKeyCode == 13. second: wVirtualKeyCode == 0 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001637 if (ir.Event.KeyEvent.UChar == 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00001638 && ir.Event.KeyEvent.wVirtualKeyCode == 13)
1639 {
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001640 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001641 continue;
1642 }
1643#endif
1644 if (decode_key_event(&ir.Event.KeyEvent, &ch, &ch2,
1645 NULL, FALSE))
1646 return TRUE;
1647 }
1648
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001649 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001650
1651 if (ir.EventType == FOCUS_EVENT)
1652 handle_focus_event(ir);
1653 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
Bram Moolenaarc33ecb22018-02-11 16:40:45 +01001654 {
1655 /* Only call shell_resized() when the size actually change to
1656 * avoid the screen is cleard. */
1657 if (ir.Event.WindowBufferSizeEvent.dwSize.X != Columns
1658 || ir.Event.WindowBufferSizeEvent.dwSize.Y != Rows)
1659 shell_resized();
1660 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001661#ifdef FEAT_MOUSE
1662 else if (ir.EventType == MOUSE_EVENT
1663 && decode_mouse_event(&ir.Event.MouseEvent))
1664 return TRUE;
1665#endif
1666 }
1667 else if (msec == 0)
1668 break;
1669 }
1670
1671#ifdef FEAT_CLIENTSERVER
1672 /* Something might have been received while we were waiting. */
1673 if (input_available())
1674 return TRUE;
1675#endif
Bram Moolenaarf12d9832016-01-29 21:11:25 +01001676
Bram Moolenaar071d4272004-06-13 20:20:40 +00001677 return FALSE;
1678}
1679
1680#ifndef FEAT_GUI_MSWIN
1681/*
1682 * return non-zero if a character is available
1683 */
1684 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001685mch_char_avail(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001686{
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001687 return WaitForChar(0L, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001688}
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001689
1690# if defined(FEAT_TERMINAL) || defined(PROTO)
1691/*
1692 * Check for any pending input or messages.
1693 */
1694 int
1695mch_check_messages(void)
1696{
1697 return WaitForChar(0L, TRUE);
1698}
1699# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001700#endif
1701
1702/*
1703 * Create the console input. Used when reading stdin doesn't work.
1704 */
1705 static void
1706create_conin(void)
1707{
1708 g_hConIn = CreateFile("CONIN$", GENERIC_READ|GENERIC_WRITE,
1709 FILE_SHARE_READ|FILE_SHARE_WRITE,
1710 (LPSECURITY_ATTRIBUTES) NULL,
Bram Moolenaareb3593b2006-04-22 22:33:57 +00001711 OPEN_EXISTING, 0, (HANDLE)NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001712 did_create_conin = TRUE;
1713}
1714
1715/*
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001716 * Get a keystroke or a mouse event, use a blocking wait.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001717 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001718 static WCHAR
1719tgetch(int *pmodifiers, WCHAR *pch2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001720{
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001721 WCHAR ch;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001722
1723 for (;;)
1724 {
1725 INPUT_RECORD ir;
1726 DWORD cRecords = 0;
1727
1728#ifdef FEAT_CLIENTSERVER
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001729 (void)WaitForChar(-1L, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001730 if (input_available())
1731 return 0;
1732# ifdef FEAT_MOUSE
1733 if (g_nMouseClick != -1)
1734 return 0;
1735# endif
1736#endif
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001737 if (read_console_input(g_hConIn, &ir, 1, &cRecords) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001738 {
1739 if (did_create_conin)
1740 read_error_exit();
1741 create_conin();
1742 continue;
1743 }
1744
1745 if (ir.EventType == KEY_EVENT)
1746 {
1747 if (decode_key_event(&ir.Event.KeyEvent, &ch, pch2,
1748 pmodifiers, TRUE))
1749 return ch;
1750 }
1751 else if (ir.EventType == FOCUS_EVENT)
1752 handle_focus_event(ir);
1753 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
1754 shell_resized();
1755#ifdef FEAT_MOUSE
1756 else if (ir.EventType == MOUSE_EVENT)
1757 {
1758 if (decode_mouse_event(&ir.Event.MouseEvent))
1759 return 0;
1760 }
1761#endif
1762 }
1763}
1764#endif /* !FEAT_GUI_W32 */
1765
1766
1767/*
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02001768 * mch_inchar(): low-level input function.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001769 * Get one or more characters from the keyboard or the mouse.
1770 * If time == 0, do not wait for characters.
1771 * If time == n, wait a short time for characters.
1772 * If time == -1, wait forever for characters.
1773 * Returns the number of characters read into buf.
1774 */
1775 int
1776mch_inchar(
Bram Moolenaar1266d672017-02-01 13:43:36 +01001777 char_u *buf UNUSED,
1778 int maxlen UNUSED,
1779 long time UNUSED,
1780 int tb_change_cnt UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001781{
1782#ifndef FEAT_GUI_W32 /* this isn't used for the GUI */
1783
1784 int len;
1785 int c;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001786#define TYPEAHEADLEN 20
1787 static char_u typeahead[TYPEAHEADLEN]; /* previously typed bytes. */
1788 static int typeaheadlen = 0;
1789
1790 /* First use any typeahead that was kept because "buf" was too small. */
1791 if (typeaheadlen > 0)
1792 goto theend;
1793
Bram Moolenaar071d4272004-06-13 20:20:40 +00001794 if (time >= 0)
1795 {
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001796 if (!WaitForChar(time, FALSE)) /* no character available */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001797 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001798 }
1799 else /* time == -1, wait forever */
1800 {
1801 mch_set_winsize_now(); /* Allow winsize changes from now on */
1802
Bram Moolenaar3918c952005-03-15 22:34:55 +00001803 /*
1804 * If there is no character available within 2 seconds (default)
1805 * write the autoscript file to disk. Or cause the CursorHold event
1806 * to be triggered.
1807 */
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001808 if (!WaitForChar(p_ut, FALSE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001809 {
Bram Moolenaard35f9712005-12-18 22:02:33 +00001810 if (trigger_cursorhold() && maxlen >= 3)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001811 {
Bram Moolenaar3918c952005-03-15 22:34:55 +00001812 buf[0] = K_SPECIAL;
1813 buf[1] = KS_EXTRA;
1814 buf[2] = (int)KE_CURSORHOLD;
1815 return 3;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001816 }
Bram Moolenaar702517d2005-06-27 22:34:07 +00001817 before_blocking();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001818 }
1819 }
1820
1821 /*
1822 * Try to read as many characters as there are, until the buffer is full.
1823 */
1824
1825 /* we will get at least one key. Get more if they are available. */
1826 g_fCBrkPressed = FALSE;
1827
1828#ifdef MCH_WRITE_DUMP
1829 if (fdDump)
1830 fputc('[', fdDump);
1831#endif
1832
1833 /* Keep looping until there is something in the typeahead buffer and more
1834 * to get and still room in the buffer (up to two bytes for a char and
1835 * three bytes for a modifier). */
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001836 while ((typeaheadlen == 0 || WaitForChar(0L, FALSE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001837 && typeaheadlen + 5 <= TYPEAHEADLEN)
1838 {
1839 if (typebuf_changed(tb_change_cnt))
1840 {
1841 /* "buf" may be invalid now if a client put something in the
1842 * typeahead buffer and "buf" is in the typeahead buffer. */
1843 typeaheadlen = 0;
1844 break;
1845 }
1846#ifdef FEAT_MOUSE
1847 if (g_nMouseClick != -1)
1848 {
1849# ifdef MCH_WRITE_DUMP
1850 if (fdDump)
1851 fprintf(fdDump, "{%02x @ %d, %d}",
1852 g_nMouseClick, g_xMouse, g_yMouse);
1853# endif
1854 typeahead[typeaheadlen++] = ESC + 128;
1855 typeahead[typeaheadlen++] = 'M';
1856 typeahead[typeaheadlen++] = g_nMouseClick;
1857 typeahead[typeaheadlen++] = g_xMouse + '!';
1858 typeahead[typeaheadlen++] = g_yMouse + '!';
1859 g_nMouseClick = -1;
1860 }
1861 else
1862#endif
1863 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001864 WCHAR ch2 = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001865 int modifiers = 0;
1866
1867 c = tgetch(&modifiers, &ch2);
1868
1869 if (typebuf_changed(tb_change_cnt))
1870 {
1871 /* "buf" may be invalid now if a client put something in the
1872 * typeahead buffer and "buf" is in the typeahead buffer. */
1873 typeaheadlen = 0;
1874 break;
1875 }
1876
1877 if (c == Ctrl_C && ctrl_c_interrupts)
1878 {
1879#if defined(FEAT_CLIENTSERVER)
1880 trash_input_buf();
1881#endif
1882 got_int = TRUE;
1883 }
1884
1885#ifdef FEAT_MOUSE
1886 if (g_nMouseClick == -1)
1887#endif
1888 {
1889 int n = 1;
1890
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001891#ifdef FEAT_MBYTE
1892 if (ch2 == NUL)
1893 {
1894 int i;
1895 char_u *p;
1896 WCHAR ch[2];
1897
1898 ch[0] = c;
1899 if (c >= 0xD800 && c <= 0xDBFF) /* High surrogate */
1900 {
1901 ch[1] = tgetch(&modifiers, &ch2);
1902 n++;
1903 }
1904 p = utf16_to_enc(ch, &n);
1905 if (p != NULL)
1906 {
1907 for (i = 0; i < n; i++)
1908 typeahead[typeaheadlen + i] = p[i];
1909 vim_free(p);
1910 }
1911 }
1912 else
1913#endif
1914 typeahead[typeaheadlen] = c;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001915 if (ch2 != NUL)
1916 {
Bram Moolenaarfeeb4d02017-12-05 15:14:46 +01001917 if (c == K_NUL && (ch2 & 0xff00) != 0)
1918 {
1919 /* fAnsiKey with modifier keys */
1920 typeahead[typeaheadlen + n] = (char_u)ch2;
1921 n++;
1922 }
1923 else
1924 {
1925 typeahead[typeaheadlen + n] = 3;
1926 typeahead[typeaheadlen + n + 1] = (char_u)ch2;
1927 n += 2;
1928 }
Bram Moolenaar45500912014-07-09 20:51:07 +02001929 }
1930
Bram Moolenaar071d4272004-06-13 20:20:40 +00001931 /* Use the ALT key to set the 8th bit of the character
1932 * when it's one byte, the 8th bit isn't set yet and not
1933 * using a double-byte encoding (would become a lead
1934 * byte). */
1935 if ((modifiers & MOD_MASK_ALT)
1936 && n == 1
1937 && (typeahead[typeaheadlen] & 0x80) == 0
1938#ifdef FEAT_MBYTE
1939 && !enc_dbcs
1940#endif
1941 )
1942 {
Bram Moolenaar85a3e5c2007-11-20 16:22:16 +00001943#ifdef FEAT_MBYTE
1944 n = (*mb_char2bytes)(typeahead[typeaheadlen] | 0x80,
1945 typeahead + typeaheadlen);
1946#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00001947 typeahead[typeaheadlen] |= 0x80;
Bram Moolenaar85a3e5c2007-11-20 16:22:16 +00001948#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001949 modifiers &= ~MOD_MASK_ALT;
1950 }
1951
1952 if (modifiers != 0)
1953 {
1954 /* Prepend modifiers to the character. */
1955 mch_memmove(typeahead + typeaheadlen + 3,
1956 typeahead + typeaheadlen, n);
1957 typeahead[typeaheadlen++] = K_SPECIAL;
1958 typeahead[typeaheadlen++] = (char_u)KS_MODIFIER;
1959 typeahead[typeaheadlen++] = modifiers;
1960 }
1961
1962 typeaheadlen += n;
1963
1964#ifdef MCH_WRITE_DUMP
1965 if (fdDump)
1966 fputc(c, fdDump);
1967#endif
1968 }
1969 }
1970 }
1971
1972#ifdef MCH_WRITE_DUMP
1973 if (fdDump)
1974 {
1975 fputs("]\n", fdDump);
1976 fflush(fdDump);
1977 }
1978#endif
1979
Bram Moolenaar071d4272004-06-13 20:20:40 +00001980theend:
1981 /* Move typeahead to "buf", as much as fits. */
1982 len = 0;
1983 while (len < maxlen && typeaheadlen > 0)
1984 {
1985 buf[len++] = typeahead[0];
1986 mch_memmove(typeahead, typeahead + 1, --typeaheadlen);
1987 }
1988 return len;
1989
1990#else /* FEAT_GUI_W32 */
1991 return 0;
1992#endif /* FEAT_GUI_W32 */
1993}
1994
Bram Moolenaar82881492012-11-20 16:53:39 +01001995#ifndef PROTO
1996# ifndef __MINGW32__
1997# include <shellapi.h> /* required for FindExecutable() */
1998# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001999#endif
2000
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002001/*
Bram Moolenaar43663192017-03-05 14:29:12 +01002002 * If "use_path" is TRUE: Return TRUE if "name" is in $PATH.
2003 * If "use_path" is FALSE: Return TRUE if "name" exists.
2004 * When returning TRUE and "path" is not NULL save the path and set "*path" to
2005 * the allocated memory.
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00002006 * TODO: Should somehow check if it's really executable.
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002007 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002008 static int
Bram Moolenaar43663192017-03-05 14:29:12 +01002009executable_exists(char *name, char_u **path, int use_path)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002010{
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002011 char *dum;
2012 char fname[_MAX_PATH];
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02002013 char *curpath, *newpath;
2014 long n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002015
Bram Moolenaar43663192017-03-05 14:29:12 +01002016 if (!use_path)
2017 {
Bram Moolenaarf7e894d2017-03-05 19:49:13 +01002018 if (mch_getperm((char_u *)name) != -1 && !mch_isdir((char_u *)name))
Bram Moolenaar43663192017-03-05 14:29:12 +01002019 {
2020 if (path != NULL)
Bram Moolenaar066029e2017-03-05 15:19:32 +01002021 {
Bram Moolenaarf7e894d2017-03-05 19:49:13 +01002022 if (mch_isFullName((char_u *)name))
Bram Moolenaar066029e2017-03-05 15:19:32 +01002023 *path = vim_strsave((char_u *)name);
2024 else
2025 *path = FullName_save((char_u *)name, FALSE);
2026 }
Bram Moolenaar43663192017-03-05 14:29:12 +01002027 return TRUE;
2028 }
2029 return FALSE;
2030 }
2031
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002032#ifdef FEAT_MBYTE
2033 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002034 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002035 WCHAR *p = enc_to_utf16((char_u *)name, NULL);
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002036 WCHAR fnamew[_MAX_PATH];
2037 WCHAR *dumw;
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02002038 WCHAR *wcurpath, *wnewpath;
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002039
2040 if (p != NULL)
2041 {
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02002042 wcurpath = _wgetenv(L"PATH");
2043 wnewpath = (WCHAR*)alloc((unsigned)(wcslen(wcurpath) + 3)
2044 * sizeof(WCHAR));
2045 if (wnewpath == NULL)
2046 return FALSE;
2047 wcscpy(wnewpath, L".;");
2048 wcscat(wnewpath, wcurpath);
2049 n = (long)SearchPathW(wnewpath, p, NULL, _MAX_PATH, fnamew, &dumw);
2050 vim_free(wnewpath);
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002051 vim_free(p);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02002052 if (n == 0)
2053 return FALSE;
2054 if (GetFileAttributesW(fnamew) & FILE_ATTRIBUTE_DIRECTORY)
2055 return FALSE;
2056 if (path != NULL)
2057 *path = utf16_to_enc(fnamew, NULL);
2058 return TRUE;
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002059 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002060 }
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002061#endif
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02002062
2063 curpath = getenv("PATH");
2064 newpath = (char*)alloc((unsigned)(STRLEN(curpath) + 3));
2065 if (newpath == NULL)
2066 return FALSE;
2067 STRCPY(newpath, ".;");
2068 STRCAT(newpath, curpath);
2069 n = (long)SearchPath(newpath, name, NULL, _MAX_PATH, fname, &dum);
2070 vim_free(newpath);
2071 if (n == 0)
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002072 return FALSE;
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002073 if (mch_isdir((char_u *)fname))
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002074 return FALSE;
Bram Moolenaarc7f02552014-04-01 21:00:59 +02002075 if (path != NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002076 *path = vim_strsave((char_u *)fname);
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002077 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002078}
2079
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002080#if ((defined(__MINGW32__) || defined (__CYGWIN32__)) && \
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02002081 __MSVCRT_VERSION__ >= 0x800) || (defined(_MSC_VER) && _MSC_VER >= 1400)
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002082/*
2083 * Bad parameter handler.
2084 *
2085 * Certain MS CRT functions will intentionally crash when passed invalid
2086 * parameters to highlight possible security holes. Setting this function as
2087 * the bad parameter handler will prevent the crash.
2088 *
2089 * In debug builds the parameters contain CRT information that might help track
2090 * down the source of a problem, but in non-debug builds the arguments are all
2091 * NULL/0. Debug builds will also produce assert dialogs from the CRT, it is
2092 * worth allowing these to make debugging of issues easier.
2093 */
2094 static void
2095bad_param_handler(const wchar_t *expression,
2096 const wchar_t *function,
2097 const wchar_t *file,
2098 unsigned int line,
2099 uintptr_t pReserved)
2100{
2101}
2102
2103# define SET_INVALID_PARAM_HANDLER \
2104 ((void)_set_invalid_parameter_handler(bad_param_handler))
2105#else
2106# define SET_INVALID_PARAM_HANDLER
2107#endif
2108
Bram Moolenaar071d4272004-06-13 20:20:40 +00002109#ifdef FEAT_GUI_W32
2110
2111/*
2112 * GUI version of mch_init().
2113 */
2114 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002115mch_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002116{
2117#ifndef __MINGW32__
2118 extern int _fmode;
2119#endif
2120
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002121 /* Silently handle invalid parameters to CRT functions */
2122 SET_INVALID_PARAM_HANDLER;
2123
Bram Moolenaar071d4272004-06-13 20:20:40 +00002124 /* Let critical errors result in a failure, not in a dialog box. Required
2125 * for the timestamp test to work on removed floppies. */
2126 SetErrorMode(SEM_FAILCRITICALERRORS);
2127
2128 _fmode = O_BINARY; /* we do our own CR-LF translation */
2129
2130 /* Specify window size. Is there a place to get the default from? */
2131 Rows = 25;
2132 Columns = 80;
2133
2134 /* Look for 'vimrun' */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002135 {
2136 char_u vimrun_location[_MAX_PATH + 4];
2137
2138 /* First try in same directory as gvim.exe */
2139 STRCPY(vimrun_location, exe_name);
2140 STRCPY(gettail(vimrun_location), "vimrun.exe");
2141 if (mch_getperm(vimrun_location) >= 0)
2142 {
2143 if (*skiptowhite(vimrun_location) != NUL)
2144 {
2145 /* Enclose path with white space in double quotes. */
2146 mch_memmove(vimrun_location + 1, vimrun_location,
2147 STRLEN(vimrun_location) + 1);
2148 *vimrun_location = '"';
2149 STRCPY(gettail(vimrun_location), "vimrun\" ");
2150 }
2151 else
2152 STRCPY(gettail(vimrun_location), "vimrun ");
2153
2154 vimrun_path = (char *)vim_strsave(vimrun_location);
2155 s_dont_use_vimrun = FALSE;
2156 }
Bram Moolenaar43663192017-03-05 14:29:12 +01002157 else if (executable_exists("vimrun.exe", NULL, TRUE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002158 s_dont_use_vimrun = FALSE;
2159
2160 /* Don't give the warning for a missing vimrun.exe right now, but only
2161 * when vimrun was supposed to be used. Don't bother people that do
2162 * not need vimrun.exe. */
2163 if (s_dont_use_vimrun)
2164 need_vimrun_warning = TRUE;
2165 }
2166
2167 /*
2168 * If "finstr.exe" doesn't exist, use "grep -n" for 'grepprg'.
2169 * Otherwise the default "findstr /n" is used.
2170 */
Bram Moolenaar43663192017-03-05 14:29:12 +01002171 if (!executable_exists("findstr.exe", NULL, TRUE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002172 set_option_value((char_u *)"grepprg", 0, (char_u *)"grep -n", 0);
2173
2174#ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01002175 win_clip_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002176#endif
2177}
2178
2179
2180#else /* FEAT_GUI_W32 */
2181
2182#define SRWIDTH(sr) ((sr).Right - (sr).Left + 1)
2183#define SRHEIGHT(sr) ((sr).Bottom - (sr).Top + 1)
2184
2185/*
2186 * ClearConsoleBuffer()
2187 * Description:
2188 * Clears the entire contents of the console screen buffer, using the
2189 * specified attribute.
2190 * Returns:
2191 * TRUE on success
2192 */
2193 static BOOL
2194ClearConsoleBuffer(WORD wAttribute)
2195{
2196 CONSOLE_SCREEN_BUFFER_INFO csbi;
2197 COORD coord;
2198 DWORD NumCells, dummy;
2199
2200 if (!GetConsoleScreenBufferInfo(g_hConOut, &csbi))
2201 return FALSE;
2202
2203 NumCells = csbi.dwSize.X * csbi.dwSize.Y;
2204 coord.X = 0;
2205 coord.Y = 0;
2206 if (!FillConsoleOutputCharacter(g_hConOut, ' ', NumCells,
2207 coord, &dummy))
2208 {
2209 return FALSE;
2210 }
2211 if (!FillConsoleOutputAttribute(g_hConOut, wAttribute, NumCells,
2212 coord, &dummy))
2213 {
2214 return FALSE;
2215 }
2216
2217 return TRUE;
2218}
2219
2220/*
2221 * FitConsoleWindow()
2222 * Description:
2223 * Checks if the console window will fit within given buffer dimensions.
2224 * Also, if requested, will shrink the window to fit.
2225 * Returns:
2226 * TRUE on success
2227 */
2228 static BOOL
2229FitConsoleWindow(
2230 COORD dwBufferSize,
2231 BOOL WantAdjust)
2232{
2233 CONSOLE_SCREEN_BUFFER_INFO csbi;
2234 COORD dwWindowSize;
2235 BOOL NeedAdjust = FALSE;
2236
2237 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
2238 {
2239 /*
2240 * A buffer resize will fail if the current console window does
2241 * not lie completely within that buffer. To avoid this, we might
2242 * have to move and possibly shrink the window.
2243 */
2244 if (csbi.srWindow.Right >= dwBufferSize.X)
2245 {
2246 dwWindowSize.X = SRWIDTH(csbi.srWindow);
2247 if (dwWindowSize.X > dwBufferSize.X)
2248 dwWindowSize.X = dwBufferSize.X;
2249 csbi.srWindow.Right = dwBufferSize.X - 1;
2250 csbi.srWindow.Left = dwBufferSize.X - dwWindowSize.X;
2251 NeedAdjust = TRUE;
2252 }
2253 if (csbi.srWindow.Bottom >= dwBufferSize.Y)
2254 {
2255 dwWindowSize.Y = SRHEIGHT(csbi.srWindow);
2256 if (dwWindowSize.Y > dwBufferSize.Y)
2257 dwWindowSize.Y = dwBufferSize.Y;
2258 csbi.srWindow.Bottom = dwBufferSize.Y - 1;
2259 csbi.srWindow.Top = dwBufferSize.Y - dwWindowSize.Y;
2260 NeedAdjust = TRUE;
2261 }
2262 if (NeedAdjust && WantAdjust)
2263 {
2264 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &csbi.srWindow))
2265 return FALSE;
2266 }
2267 return TRUE;
2268 }
2269
2270 return FALSE;
2271}
2272
2273typedef struct ConsoleBufferStruct
2274{
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002275 BOOL IsValid;
2276 CONSOLE_SCREEN_BUFFER_INFO Info;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002277 PCHAR_INFO Buffer;
2278 COORD BufferSize;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002279 PSMALL_RECT Regions;
2280 int NumRegions;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002281} ConsoleBuffer;
2282
2283/*
2284 * SaveConsoleBuffer()
2285 * Description:
2286 * Saves important information about the console buffer, including the
2287 * actual buffer contents. The saved information is suitable for later
2288 * restoration by RestoreConsoleBuffer().
2289 * Returns:
2290 * TRUE if all information was saved; FALSE otherwise
2291 * If FALSE, still sets cb->IsValid if buffer characteristics were saved.
2292 */
2293 static BOOL
2294SaveConsoleBuffer(
2295 ConsoleBuffer *cb)
2296{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002297 DWORD NumCells;
2298 COORD BufferCoord;
2299 SMALL_RECT ReadRegion;
2300 WORD Y, Y_incr;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002301 int i, numregions;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002302
Bram Moolenaar071d4272004-06-13 20:20:40 +00002303 if (cb == NULL)
2304 return FALSE;
2305
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002306 if (!GetConsoleScreenBufferInfo(g_hConOut, &cb->Info))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002307 {
2308 cb->IsValid = FALSE;
2309 return FALSE;
2310 }
2311 cb->IsValid = TRUE;
2312
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002313 /*
2314 * Allocate a buffer large enough to hold the entire console screen
2315 * buffer. If this ConsoleBuffer structure has already been initialized
2316 * with a buffer of the correct size, then just use that one.
2317 */
2318 if (!cb->IsValid || cb->Buffer == NULL ||
2319 cb->BufferSize.X != cb->Info.dwSize.X ||
2320 cb->BufferSize.Y != cb->Info.dwSize.Y)
2321 {
2322 cb->BufferSize.X = cb->Info.dwSize.X;
2323 cb->BufferSize.Y = cb->Info.dwSize.Y;
2324 NumCells = cb->BufferSize.X * cb->BufferSize.Y;
2325 vim_free(cb->Buffer);
2326 cb->Buffer = (PCHAR_INFO)alloc(NumCells * sizeof(CHAR_INFO));
2327 if (cb->Buffer == NULL)
2328 return FALSE;
2329 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002330
2331 /*
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002332 * We will now copy the console screen buffer into our buffer.
2333 * ReadConsoleOutput() seems to be limited as far as how much you
2334 * can read at a time. Empirically, this number seems to be about
2335 * 12000 cells (rows * columns). Start at position (0, 0) and copy
2336 * in chunks until it is all copied. The chunks will all have the
2337 * same horizontal characteristics, so initialize them now. The
2338 * height of each chunk will be (12000 / width).
Bram Moolenaar071d4272004-06-13 20:20:40 +00002339 */
Bram Moolenaar61594242015-09-01 20:23:37 +02002340 BufferCoord.X = 0;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002341 ReadRegion.Left = 0;
2342 ReadRegion.Right = cb->Info.dwSize.X - 1;
2343 Y_incr = 12000 / cb->Info.dwSize.X;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002344
2345 numregions = (cb->Info.dwSize.Y + Y_incr - 1) / Y_incr;
2346 if (cb->Regions == NULL || numregions != cb->NumRegions)
2347 {
2348 cb->NumRegions = numregions;
2349 vim_free(cb->Regions);
2350 cb->Regions = (PSMALL_RECT)alloc(cb->NumRegions * sizeof(SMALL_RECT));
2351 if (cb->Regions == NULL)
2352 {
Bram Moolenaard23a8232018-02-10 18:45:26 +01002353 VIM_CLEAR(cb->Buffer);
Bram Moolenaar444fda22017-08-11 20:37:00 +02002354 return FALSE;
2355 }
2356 }
2357
2358 for (i = 0, Y = 0; i < cb->NumRegions; i++, Y += Y_incr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002359 {
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002360 /*
2361 * Read into position (0, Y) in our buffer.
2362 */
2363 BufferCoord.Y = Y;
2364 /*
2365 * Read the region whose top left corner is (0, Y) and whose bottom
2366 * right corner is (width - 1, Y + Y_incr - 1). This should define
2367 * a region of size width by Y_incr. Don't worry if this region is
2368 * too large for the remaining buffer; it will be cropped.
2369 */
2370 ReadRegion.Top = Y;
2371 ReadRegion.Bottom = Y + Y_incr - 1;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002372 if (!ReadConsoleOutputW(g_hConOut, /* output handle */
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002373 cb->Buffer, /* our buffer */
2374 cb->BufferSize, /* dimensions of our buffer */
2375 BufferCoord, /* offset in our buffer */
2376 &ReadRegion)) /* region to save */
2377 {
Bram Moolenaard23a8232018-02-10 18:45:26 +01002378 VIM_CLEAR(cb->Buffer);
2379 VIM_CLEAR(cb->Regions);
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002380 return FALSE;
2381 }
Bram Moolenaar444fda22017-08-11 20:37:00 +02002382 cb->Regions[i] = ReadRegion;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002383 }
2384
2385 return TRUE;
2386}
2387
2388/*
2389 * RestoreConsoleBuffer()
2390 * Description:
2391 * Restores important information about the console buffer, including the
2392 * actual buffer contents, if desired. The information to restore is in
2393 * the same format used by SaveConsoleBuffer().
2394 * Returns:
2395 * TRUE on success
2396 */
2397 static BOOL
2398RestoreConsoleBuffer(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002399 ConsoleBuffer *cb,
2400 BOOL RestoreScreen)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002401{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002402 COORD BufferCoord;
2403 SMALL_RECT WriteRegion;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002404 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002405
2406 if (cb == NULL || !cb->IsValid)
2407 return FALSE;
2408
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002409 /*
2410 * Before restoring the buffer contents, clear the current buffer, and
2411 * restore the cursor position and window information. Doing this now
2412 * prevents old buffer contents from "flashing" onto the screen.
2413 */
2414 if (RestoreScreen)
2415 ClearConsoleBuffer(cb->Info.wAttributes);
2416
2417 FitConsoleWindow(cb->Info.dwSize, TRUE);
2418 if (!SetConsoleScreenBufferSize(g_hConOut, cb->Info.dwSize))
2419 return FALSE;
2420 if (!SetConsoleTextAttribute(g_hConOut, cb->Info.wAttributes))
2421 return FALSE;
2422
2423 if (!RestoreScreen)
2424 {
2425 /*
2426 * No need to restore the screen buffer contents, so we're done.
2427 */
2428 return TRUE;
2429 }
2430
2431 if (!SetConsoleCursorPosition(g_hConOut, cb->Info.dwCursorPosition))
2432 return FALSE;
2433 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &cb->Info.srWindow))
2434 return FALSE;
2435
2436 /*
2437 * Restore the screen buffer contents.
2438 */
2439 if (cb->Buffer != NULL)
2440 {
Bram Moolenaar444fda22017-08-11 20:37:00 +02002441 for (i = 0; i < cb->NumRegions; i++)
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002442 {
Bram Moolenaar444fda22017-08-11 20:37:00 +02002443 BufferCoord.X = cb->Regions[i].Left;
2444 BufferCoord.Y = cb->Regions[i].Top;
2445 WriteRegion = cb->Regions[i];
2446 if (!WriteConsoleOutputW(g_hConOut, /* output handle */
2447 cb->Buffer, /* our buffer */
2448 cb->BufferSize, /* dimensions of our buffer */
2449 BufferCoord, /* offset in our buffer */
2450 &WriteRegion)) /* region to restore */
2451 {
2452 return FALSE;
2453 }
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002454 }
2455 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002456
2457 return TRUE;
2458}
2459
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002460#define FEAT_RESTORE_ORIG_SCREEN
2461#ifdef FEAT_RESTORE_ORIG_SCREEN
2462static ConsoleBuffer g_cbOrig = { 0 };
2463#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002464static ConsoleBuffer g_cbNonTermcap = { 0 };
2465static ConsoleBuffer g_cbTermcap = { 0 };
2466
2467#ifdef FEAT_TITLE
2468#ifdef __BORLANDC__
2469typedef HWND (__stdcall *GETCONSOLEWINDOWPROC)(VOID);
2470#else
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002471typedef HWND (WINAPI *GETCONSOLEWINDOWPROC)(VOID);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002472#endif
2473char g_szOrigTitle[256] = { 0 };
2474HWND g_hWnd = NULL; /* also used in os_mswin.c */
2475static HICON g_hOrigIconSmall = NULL;
2476static HICON g_hOrigIcon = NULL;
2477static HICON g_hVimIcon = NULL;
2478static BOOL g_fCanChangeIcon = FALSE;
2479
2480/* ICON* are not defined in VC++ 4.0 */
2481#ifndef ICON_SMALL
2482#define ICON_SMALL 0
2483#endif
2484#ifndef ICON_BIG
2485#define ICON_BIG 1
2486#endif
2487/*
2488 * GetConsoleIcon()
2489 * Description:
2490 * Attempts to retrieve the small icon and/or the big icon currently in
2491 * use by a given window.
2492 * Returns:
2493 * TRUE on success
2494 */
2495 static BOOL
2496GetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002497 HWND hWnd,
2498 HICON *phIconSmall,
2499 HICON *phIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002500{
2501 if (hWnd == NULL)
2502 return FALSE;
2503
2504 if (phIconSmall != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002505 *phIconSmall = (HICON)SendMessage(hWnd, WM_GETICON,
2506 (WPARAM)ICON_SMALL, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002507 if (phIcon != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002508 *phIcon = (HICON)SendMessage(hWnd, WM_GETICON,
2509 (WPARAM)ICON_BIG, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002510 return TRUE;
2511}
2512
2513/*
2514 * SetConsoleIcon()
2515 * Description:
2516 * Attempts to change the small icon and/or the big icon currently in
2517 * use by a given window.
2518 * Returns:
2519 * TRUE on success
2520 */
2521 static BOOL
2522SetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002523 HWND hWnd,
2524 HICON hIconSmall,
2525 HICON hIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002526{
Bram Moolenaar071d4272004-06-13 20:20:40 +00002527 if (hWnd == NULL)
2528 return FALSE;
2529
2530 if (hIconSmall != NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002531 SendMessage(hWnd, WM_SETICON,
2532 (WPARAM)ICON_SMALL, (LPARAM)hIconSmall);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002533 if (hIcon != NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002534 SendMessage(hWnd, WM_SETICON,
2535 (WPARAM)ICON_BIG, (LPARAM) hIcon);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002536 return TRUE;
2537}
2538
2539/*
2540 * SaveConsoleTitleAndIcon()
2541 * Description:
2542 * Saves the current console window title in g_szOrigTitle, for later
2543 * restoration. Also, attempts to obtain a handle to the console window,
2544 * and use it to save the small and big icons currently in use by the
2545 * console window. This is not always possible on some versions of Windows;
2546 * nor is it possible when running Vim remotely using Telnet (since the
2547 * console window the user sees is owned by a remote process).
2548 */
2549 static void
2550SaveConsoleTitleAndIcon(void)
2551{
Bram Moolenaar071d4272004-06-13 20:20:40 +00002552 /* Save the original title. */
2553 if (!GetConsoleTitle(g_szOrigTitle, sizeof(g_szOrigTitle)))
2554 return;
2555
2556 /*
2557 * Obtain a handle to the console window using GetConsoleWindow() from
2558 * KERNEL32.DLL; we need to handle in order to change the window icon.
2559 * This function only exists on NT-based Windows, starting with Windows
2560 * 2000. On older operating systems, we can't change the window icon
2561 * anyway.
2562 */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02002563 g_hWnd = GetConsoleWindow();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002564 if (g_hWnd == NULL)
2565 return;
2566
2567 /* Save the original console window icon. */
2568 GetConsoleIcon(g_hWnd, &g_hOrigIconSmall, &g_hOrigIcon);
2569 if (g_hOrigIconSmall == NULL || g_hOrigIcon == NULL)
2570 return;
2571
2572 /* Extract the first icon contained in the Vim executable. */
Bram Moolenaarcddc91c2014-09-23 21:53:41 +02002573 if (mch_icon_load((HANDLE *)&g_hVimIcon) == FAIL || g_hVimIcon == NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002574 g_hVimIcon = ExtractIcon(NULL, (LPCSTR)exe_name, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002575 if (g_hVimIcon != NULL)
2576 g_fCanChangeIcon = TRUE;
2577}
2578#endif
2579
2580static int g_fWindInitCalled = FALSE;
2581static int g_fTermcapMode = FALSE;
2582static CONSOLE_CURSOR_INFO g_cci;
2583static DWORD g_cmodein = 0;
2584static DWORD g_cmodeout = 0;
2585
2586/*
2587 * non-GUI version of mch_init().
2588 */
2589 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002590mch_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002591{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002592#ifndef FEAT_RESTORE_ORIG_SCREEN
2593 CONSOLE_SCREEN_BUFFER_INFO csbi;
2594#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002595#ifndef __MINGW32__
2596 extern int _fmode;
2597#endif
2598
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002599 /* Silently handle invalid parameters to CRT functions */
2600 SET_INVALID_PARAM_HANDLER;
2601
Bram Moolenaar071d4272004-06-13 20:20:40 +00002602 /* Let critical errors result in a failure, not in a dialog box. Required
2603 * for the timestamp test to work on removed floppies. */
2604 SetErrorMode(SEM_FAILCRITICALERRORS);
2605
2606 _fmode = O_BINARY; /* we do our own CR-LF translation */
2607 out_flush();
2608
2609 /* Obtain handles for the standard Console I/O devices */
2610 if (read_cmd_fd == 0)
2611 g_hConIn = GetStdHandle(STD_INPUT_HANDLE);
2612 else
2613 create_conin();
2614 g_hConOut = GetStdHandle(STD_OUTPUT_HANDLE);
2615
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002616#ifdef FEAT_RESTORE_ORIG_SCREEN
2617 /* Save the initial console buffer for later restoration */
2618 SaveConsoleBuffer(&g_cbOrig);
2619 g_attrCurrent = g_attrDefault = g_cbOrig.Info.wAttributes;
2620#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00002621 /* Get current text attributes */
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002622 GetConsoleScreenBufferInfo(g_hConOut, &csbi);
2623 g_attrCurrent = g_attrDefault = csbi.wAttributes;
2624#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002625 if (cterm_normal_fg_color == 0)
2626 cterm_normal_fg_color = (g_attrCurrent & 0xf) + 1;
2627 if (cterm_normal_bg_color == 0)
2628 cterm_normal_bg_color = ((g_attrCurrent >> 4) & 0xf) + 1;
2629
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02002630 // Fg and Bg color index nunmber at startup
2631 g_color_index_fg = g_attrDefault & 0xf;
2632 g_color_index_bg = (g_attrDefault >> 4) & 0xf;
2633
Bram Moolenaar071d4272004-06-13 20:20:40 +00002634 /* set termcap codes to current text attributes */
2635 update_tcap(g_attrCurrent);
2636
2637 GetConsoleCursorInfo(g_hConOut, &g_cci);
2638 GetConsoleMode(g_hConIn, &g_cmodein);
2639 GetConsoleMode(g_hConOut, &g_cmodeout);
2640
2641#ifdef FEAT_TITLE
2642 SaveConsoleTitleAndIcon();
2643 /*
2644 * Set both the small and big icons of the console window to Vim's icon.
2645 * Note that Vim presently only has one size of icon (32x32), but it
2646 * automatically gets scaled down to 16x16 when setting the small icon.
2647 */
2648 if (g_fCanChangeIcon)
2649 SetConsoleIcon(g_hWnd, g_hVimIcon, g_hVimIcon);
2650#endif
2651
2652 ui_get_shellsize();
2653
2654#ifdef MCH_WRITE_DUMP
2655 fdDump = fopen("dump", "wt");
2656
2657 if (fdDump)
2658 {
2659 time_t t;
2660
2661 time(&t);
2662 fputs(ctime(&t), fdDump);
2663 fflush(fdDump);
2664 }
2665#endif
2666
2667 g_fWindInitCalled = TRUE;
2668
2669#ifdef FEAT_MOUSE
2670 g_fMouseAvail = GetSystemMetrics(SM_MOUSEPRESENT);
2671#endif
2672
2673#ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01002674 win_clip_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002675#endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01002676
2677 vtp_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002678}
2679
2680/*
2681 * non-GUI version of mch_exit().
2682 * Shut down and exit with status `r'
2683 * Careful: mch_exit() may be called before mch_init()!
2684 */
2685 void
2686mch_exit(int r)
2687{
Bram Moolenaar955f1982017-02-05 15:10:51 +01002688 exiting = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002689
Bram Moolenaarcafafb32018-02-22 21:07:09 +01002690 vtp_exit();
2691
Bram Moolenaar955f1982017-02-05 15:10:51 +01002692 stoptermcap();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002693 if (g_fWindInitCalled)
2694 settmode(TMODE_COOK);
2695
2696 ml_close_all(TRUE); /* remove all memfiles */
2697
2698 if (g_fWindInitCalled)
2699 {
2700#ifdef FEAT_TITLE
Bram Moolenaar40385db2018-08-07 22:31:44 +02002701 mch_restore_title(SAVE_RESTORE_BOTH);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002702 /*
2703 * Restore both the small and big icons of the console window to
2704 * what they were at startup. Don't do this when the window is
2705 * closed, Vim would hang here.
2706 */
2707 if (g_fCanChangeIcon && !g_fForceExit)
2708 SetConsoleIcon(g_hWnd, g_hOrigIconSmall, g_hOrigIcon);
2709#endif
2710
2711#ifdef MCH_WRITE_DUMP
2712 if (fdDump)
2713 {
2714 time_t t;
2715
2716 time(&t);
2717 fputs(ctime(&t), fdDump);
2718 fclose(fdDump);
2719 }
2720 fdDump = NULL;
2721#endif
2722 }
2723
2724 SetConsoleCursorInfo(g_hConOut, &g_cci);
2725 SetConsoleMode(g_hConIn, g_cmodein);
2726 SetConsoleMode(g_hConOut, g_cmodeout);
2727
2728#ifdef DYNAMIC_GETTEXT
2729 dyn_libintl_end();
2730#endif
2731
2732 exit(r);
2733}
2734#endif /* !FEAT_GUI_W32 */
2735
Bram Moolenaar071d4272004-06-13 20:20:40 +00002736/*
2737 * Do we have an interactive window?
2738 */
2739 int
2740mch_check_win(
Bram Moolenaar1266d672017-02-01 13:43:36 +01002741 int argc UNUSED,
2742 char **argv UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002743{
2744 get_exe_name();
2745
2746#ifdef FEAT_GUI_W32
2747 return OK; /* GUI always has a tty */
2748#else
2749 if (isatty(1))
2750 return OK;
2751 return FAIL;
2752#endif
2753}
2754
2755
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002756#ifdef FEAT_MBYTE
2757/*
2758 * fname_casew(): Wide version of fname_case(). Set the case of the file name,
2759 * if it already exists. When "len" is > 0, also expand short to long
2760 * filenames.
2761 * Return FAIL if wide functions are not available, OK otherwise.
2762 * NOTE: much of this is identical to fname_case(), keep in sync!
2763 */
2764 static int
2765fname_casew(
2766 WCHAR *name,
2767 int len)
2768{
2769 WCHAR szTrueName[_MAX_PATH + 2];
2770 WCHAR szTrueNameTemp[_MAX_PATH + 2];
2771 WCHAR *ptrue, *ptruePrev;
2772 WCHAR *porig, *porigPrev;
2773 int flen;
2774 WIN32_FIND_DATAW fb;
Bram Moolenaar73c61632013-12-07 14:48:10 +01002775 HANDLE hFind = INVALID_HANDLE_VALUE;
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002776 int c;
2777 int slen;
2778
2779 flen = (int)wcslen(name);
2780 if (flen > _MAX_PATH)
2781 return OK;
2782
2783 /* slash_adjust(name) not needed, already adjusted by fname_case(). */
2784
2785 /* Build the new name in szTrueName[] one component at a time. */
2786 porig = name;
2787 ptrue = szTrueName;
2788
2789 if (iswalpha(porig[0]) && porig[1] == L':')
2790 {
2791 /* copy leading drive letter */
2792 *ptrue++ = *porig++;
2793 *ptrue++ = *porig++;
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002794 }
Bram Moolenaar73c61632013-12-07 14:48:10 +01002795 *ptrue = NUL; /* in case nothing follows */
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002796
2797 while (*porig != NUL)
2798 {
2799 /* copy \ characters */
2800 while (*porig == psepc)
2801 *ptrue++ = *porig++;
2802
2803 ptruePrev = ptrue;
2804 porigPrev = porig;
2805 while (*porig != NUL && *porig != psepc)
2806 {
2807 *ptrue++ = *porig++;
2808 }
2809 *ptrue = NUL;
2810
2811 /* To avoid a slow failure append "\*" when searching a directory,
2812 * server or network share. */
2813 wcscpy(szTrueNameTemp, szTrueName);
2814 slen = (int)wcslen(szTrueNameTemp);
2815 if (*porig == psepc && slen + 2 < _MAX_PATH)
2816 wcscpy(szTrueNameTemp + slen, L"\\*");
2817
2818 /* Skip "", "." and "..". */
2819 if (ptrue > ptruePrev
2820 && (ptruePrev[0] != L'.'
2821 || (ptruePrev[1] != NUL
2822 && (ptruePrev[1] != L'.' || ptruePrev[2] != NUL)))
2823 && (hFind = FindFirstFileW(szTrueNameTemp, &fb))
2824 != INVALID_HANDLE_VALUE)
2825 {
2826 c = *porig;
2827 *porig = NUL;
2828
2829 /* Only use the match when it's the same name (ignoring case) or
2830 * expansion is allowed and there is a match with the short name
2831 * and there is enough room. */
2832 if (_wcsicoll(porigPrev, fb.cFileName) == 0
2833 || (len > 0
2834 && (_wcsicoll(porigPrev, fb.cAlternateFileName) == 0
2835 && (int)(ptruePrev - szTrueName)
2836 + (int)wcslen(fb.cFileName) < len)))
2837 {
2838 wcscpy(ptruePrev, fb.cFileName);
2839
2840 /* Look for exact match and prefer it if found. Must be a
2841 * long name, otherwise there would be only one match. */
2842 while (FindNextFileW(hFind, &fb))
2843 {
2844 if (*fb.cAlternateFileName != NUL
2845 && (wcscoll(porigPrev, fb.cFileName) == 0
2846 || (len > 0
2847 && (_wcsicoll(porigPrev,
2848 fb.cAlternateFileName) == 0
2849 && (int)(ptruePrev - szTrueName)
2850 + (int)wcslen(fb.cFileName) < len))))
2851 {
2852 wcscpy(ptruePrev, fb.cFileName);
2853 break;
2854 }
2855 }
2856 }
2857 FindClose(hFind);
2858 *porig = c;
2859 ptrue = ptruePrev + wcslen(ptruePrev);
2860 }
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002861 }
2862
2863 wcscpy(name, szTrueName);
2864 return OK;
2865}
2866#endif
2867
Bram Moolenaar071d4272004-06-13 20:20:40 +00002868/*
2869 * fname_case(): Set the case of the file name, if it already exists.
2870 * When "len" is > 0, also expand short to long filenames.
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002871 * NOTE: much of this is identical to fname_casew(), keep in sync!
Bram Moolenaar071d4272004-06-13 20:20:40 +00002872 */
2873 void
2874fname_case(
2875 char_u *name,
2876 int len)
2877{
2878 char szTrueName[_MAX_PATH + 2];
Bram Moolenaar464c9252010-10-13 20:37:41 +02002879 char szTrueNameTemp[_MAX_PATH + 2];
Bram Moolenaar071d4272004-06-13 20:20:40 +00002880 char *ptrue, *ptruePrev;
2881 char *porig, *porigPrev;
2882 int flen;
2883 WIN32_FIND_DATA fb;
2884 HANDLE hFind;
2885 int c;
Bram Moolenaar464c9252010-10-13 20:37:41 +02002886 int slen;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002887
Bram Moolenaara3ffd9c2005-07-21 21:03:15 +00002888 flen = (int)STRLEN(name);
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002889 if (flen == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002890 return;
2891
2892 slash_adjust(name);
2893
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002894#ifdef FEAT_MBYTE
2895 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2896 {
2897 WCHAR *p = enc_to_utf16(name, NULL);
2898
2899 if (p != NULL)
2900 {
2901 char_u *q;
Bram Moolenaar21d89b62014-10-07 10:38:40 +02002902 WCHAR buf[_MAX_PATH + 1];
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002903
Bram Moolenaar21d89b62014-10-07 10:38:40 +02002904 wcsncpy(buf, p, _MAX_PATH);
2905 buf[_MAX_PATH] = L'\0';
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002906 vim_free(p);
2907
2908 if (fname_casew(buf, (len > 0) ? _MAX_PATH : 0) == OK)
2909 {
2910 q = utf16_to_enc(buf, NULL);
2911 if (q != NULL)
2912 {
2913 vim_strncpy(name, q, (len > 0) ? len - 1 : flen);
2914 vim_free(q);
2915 return;
2916 }
2917 }
2918 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02002919 return;
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002920 }
2921#endif
2922
2923 /* If 'enc' is utf-8, flen can be larger than _MAX_PATH.
2924 * So we should check this after calling wide function. */
2925 if (flen > _MAX_PATH)
2926 return;
2927
Bram Moolenaar071d4272004-06-13 20:20:40 +00002928 /* Build the new name in szTrueName[] one component at a time. */
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002929 porig = (char *)name;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002930 ptrue = szTrueName;
2931
2932 if (isalpha(porig[0]) && porig[1] == ':')
2933 {
2934 /* copy leading drive letter */
2935 *ptrue++ = *porig++;
2936 *ptrue++ = *porig++;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002937 }
Bram Moolenaar73c61632013-12-07 14:48:10 +01002938 *ptrue = NUL; /* in case nothing follows */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002939
2940 while (*porig != NUL)
2941 {
2942 /* copy \ characters */
2943 while (*porig == psepc)
2944 *ptrue++ = *porig++;
2945
2946 ptruePrev = ptrue;
2947 porigPrev = porig;
2948 while (*porig != NUL && *porig != psepc)
2949 {
2950#ifdef FEAT_MBYTE
2951 int l;
2952
2953 if (enc_dbcs)
2954 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002955 l = (*mb_ptr2len)((char_u *)porig);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002956 while (--l >= 0)
2957 *ptrue++ = *porig++;
2958 }
2959 else
2960#endif
2961 *ptrue++ = *porig++;
2962 }
2963 *ptrue = NUL;
2964
Bram Moolenaar464c9252010-10-13 20:37:41 +02002965 /* To avoid a slow failure append "\*" when searching a directory,
2966 * server or network share. */
2967 STRCPY(szTrueNameTemp, szTrueName);
Bram Moolenaar6b5ef062010-10-27 12:18:00 +02002968 slen = (int)strlen(szTrueNameTemp);
Bram Moolenaar464c9252010-10-13 20:37:41 +02002969 if (*porig == psepc && slen + 2 < _MAX_PATH)
2970 STRCPY(szTrueNameTemp + slen, "\\*");
2971
Bram Moolenaar071d4272004-06-13 20:20:40 +00002972 /* Skip "", "." and "..". */
2973 if (ptrue > ptruePrev
2974 && (ptruePrev[0] != '.'
2975 || (ptruePrev[1] != NUL
2976 && (ptruePrev[1] != '.' || ptruePrev[2] != NUL)))
Bram Moolenaar464c9252010-10-13 20:37:41 +02002977 && (hFind = FindFirstFile(szTrueNameTemp, &fb))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002978 != INVALID_HANDLE_VALUE)
2979 {
2980 c = *porig;
2981 *porig = NUL;
2982
2983 /* Only use the match when it's the same name (ignoring case) or
2984 * expansion is allowed and there is a match with the short name
2985 * and there is enough room. */
2986 if (_stricoll(porigPrev, fb.cFileName) == 0
2987 || (len > 0
2988 && (_stricoll(porigPrev, fb.cAlternateFileName) == 0
2989 && (int)(ptruePrev - szTrueName)
2990 + (int)strlen(fb.cFileName) < len)))
2991 {
2992 STRCPY(ptruePrev, fb.cFileName);
2993
2994 /* Look for exact match and prefer it if found. Must be a
2995 * long name, otherwise there would be only one match. */
2996 while (FindNextFile(hFind, &fb))
2997 {
2998 if (*fb.cAlternateFileName != NUL
2999 && (strcoll(porigPrev, fb.cFileName) == 0
3000 || (len > 0
3001 && (_stricoll(porigPrev,
3002 fb.cAlternateFileName) == 0
3003 && (int)(ptruePrev - szTrueName)
3004 + (int)strlen(fb.cFileName) < len))))
3005 {
3006 STRCPY(ptruePrev, fb.cFileName);
3007 break;
3008 }
3009 }
3010 }
3011 FindClose(hFind);
3012 *porig = c;
3013 ptrue = ptruePrev + strlen(ptruePrev);
3014 }
3015 }
3016
3017 STRCPY(name, szTrueName);
3018}
3019
3020
3021/*
3022 * Insert user name in s[len].
3023 */
3024 int
3025mch_get_user_name(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003026 char_u *s,
3027 int len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003028{
Bram Moolenaar41a09032007-10-01 18:34:34 +00003029 char szUserName[256 + 1]; /* UNLEN is 256 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003030 DWORD cch = sizeof szUserName;
3031
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003032#ifdef FEAT_MBYTE
3033 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3034 {
3035 WCHAR wszUserName[256 + 1]; /* UNLEN is 256 */
3036 DWORD wcch = sizeof(wszUserName) / sizeof(WCHAR);
3037
3038 if (GetUserNameW(wszUserName, &wcch))
3039 {
3040 char_u *p = utf16_to_enc(wszUserName, NULL);
3041
3042 if (p != NULL)
3043 {
3044 vim_strncpy(s, p, len - 1);
3045 vim_free(p);
3046 return OK;
3047 }
3048 }
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003049 }
3050#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003051 if (GetUserName(szUserName, &cch))
3052 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003053 vim_strncpy(s, (char_u *)szUserName, len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003054 return OK;
3055 }
3056 s[0] = NUL;
3057 return FAIL;
3058}
3059
3060
3061/*
3062 * Insert host name in s[len].
3063 */
3064 void
3065mch_get_host_name(
3066 char_u *s,
3067 int len)
3068{
3069 DWORD cch = len;
3070
Bram Moolenaar2cc87382013-12-11 18:21:45 +01003071#ifdef FEAT_MBYTE
3072 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3073 {
3074 WCHAR wszHostName[256 + 1];
3075 DWORD wcch = sizeof(wszHostName) / sizeof(WCHAR);
3076
3077 if (GetComputerNameW(wszHostName, &wcch))
3078 {
3079 char_u *p = utf16_to_enc(wszHostName, NULL);
3080
3081 if (p != NULL)
3082 {
3083 vim_strncpy(s, p, len - 1);
3084 vim_free(p);
3085 return;
3086 }
3087 }
Bram Moolenaar2cc87382013-12-11 18:21:45 +01003088 }
3089#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003090 if (!GetComputerName((LPSTR)s, &cch))
3091 vim_strncpy(s, (char_u *)"PC (Win32 Vim)", len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003092}
3093
3094
3095/*
3096 * return process ID
3097 */
3098 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003099mch_get_pid(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003100{
3101 return (long)GetCurrentProcessId();
3102}
3103
3104
3105/*
3106 * Get name of current directory into buffer 'buf' of length 'len' bytes.
3107 * Return OK for success, FAIL for failure.
3108 */
3109 int
3110mch_dirname(
3111 char_u *buf,
3112 int len)
3113{
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02003114 char_u abuf[_MAX_PATH + 1];
Bram Moolenaarcea1f9e2018-08-19 14:38:42 +02003115 DWORD lfnlen;
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02003116
Bram Moolenaar071d4272004-06-13 20:20:40 +00003117 /*
3118 * Originally this was:
3119 * return (getcwd(buf, len) != NULL ? OK : FAIL);
3120 * But the Win32s known bug list says that getcwd() doesn't work
3121 * so use the Win32 system call instead. <Negri>
3122 */
3123#ifdef FEAT_MBYTE
3124 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3125 {
3126 WCHAR wbuf[_MAX_PATH + 1];
3127
3128 if (GetCurrentDirectoryW(_MAX_PATH, wbuf) != 0)
3129 {
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02003130 WCHAR wcbuf[_MAX_PATH + 1];
Bram Moolenaarcea1f9e2018-08-19 14:38:42 +02003131 char_u *p = NULL;
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02003132
3133 if (GetLongPathNameW(wbuf, wcbuf, _MAX_PATH) != 0)
Bram Moolenaarcea1f9e2018-08-19 14:38:42 +02003134 {
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02003135 p = utf16_to_enc(wcbuf, NULL);
Bram Moolenaarcea1f9e2018-08-19 14:38:42 +02003136 if (STRLEN(p) >= (size_t)len)
3137 {
3138 // long path name is too long, fall back to short one
3139 vim_free(p);
3140 p = NULL;
3141 }
3142 }
3143 if (p == NULL)
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02003144 p = utf16_to_enc(wbuf, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003145
3146 if (p != NULL)
3147 {
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00003148 vim_strncpy(buf, p, len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003149 vim_free(p);
3150 return OK;
3151 }
3152 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003153 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003154 }
3155#endif
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02003156 if (GetCurrentDirectory(len, (LPSTR)buf) == 0)
3157 return FAIL;
Bram Moolenaarcea1f9e2018-08-19 14:38:42 +02003158 lfnlen = GetLongPathNameA((LPCSTR)buf, (LPSTR)abuf, _MAX_PATH);
3159 if (lfnlen == 0 || lfnlen >= (DWORD)len)
3160 // Failed to get long path name or it's too long: fall back to the
3161 // short path name.
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02003162 return OK;
3163
Bram Moolenaarcea1f9e2018-08-19 14:38:42 +02003164 STRCPY(buf, abuf);
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02003165 return OK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003166}
3167
3168/*
Bram Moolenaarffa22202013-11-21 12:34:11 +01003169 * Get file permissions for "name".
3170 * Return mode_t or -1 for error.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003171 */
3172 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003173mch_getperm(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003174{
Bram Moolenaar8767f522016-07-01 17:17:39 +02003175 stat_T st;
Bram Moolenaarffa22202013-11-21 12:34:11 +01003176 int n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003177
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003178 n = mch_stat((char *)name, &st);
Bram Moolenaar78cf3f02014-01-10 18:16:07 +01003179 return n == 0 ? (long)(unsigned short)st.st_mode : -1L;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003180}
3181
3182
3183/*
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003184 * Set file permission for "name" to "perm".
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003185 *
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003186 * Return FAIL for failure, OK otherwise.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003187 */
3188 int
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003189mch_setperm(char_u *name, long perm)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003190{
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003191 long n = -1;
3192
Bram Moolenaar071d4272004-06-13 20:20:40 +00003193#ifdef FEAT_MBYTE
3194 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3195 {
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003196 WCHAR *p = enc_to_utf16(name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003197
3198 if (p != NULL)
3199 {
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003200 n = _wchmod(p, perm);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003201 vim_free(p);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003202 if (n == -1)
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003203 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003204 }
3205 }
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003206 if (n == -1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003207#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003208 n = _chmod((const char *)name, perm);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003209 if (n == -1)
3210 return FAIL;
3211
3212 win32_set_archive(name);
3213
3214 return OK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003215}
3216
3217/*
3218 * Set hidden flag for "name".
3219 */
3220 void
3221mch_hide(char_u *name)
3222{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003223 int attrs = win32_getattrs(name);
3224 if (attrs == -1)
3225 return;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003226
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003227 attrs |= FILE_ATTRIBUTE_HIDDEN;
3228 win32_setattrs(name, attrs);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003229}
3230
3231/*
Bram Moolenaar8a52ba72015-11-02 14:45:56 +01003232 * Return TRUE if file "name" exists and is hidden.
3233 */
3234 int
3235mch_ishidden(char_u *name)
3236{
3237 int f = win32_getattrs(name);
3238
3239 if (f == -1)
3240 return FALSE; /* file does not exist at all */
3241
3242 return (f & FILE_ATTRIBUTE_HIDDEN) != 0;
3243}
3244
3245/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003246 * return TRUE if "name" is a directory
3247 * return FALSE if "name" is not a directory or upon error
3248 */
3249 int
3250mch_isdir(char_u *name)
3251{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003252 int f = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003253
3254 if (f == -1)
3255 return FALSE; /* file does not exist at all */
3256
3257 return (f & FILE_ATTRIBUTE_DIRECTORY) != 0;
3258}
3259
3260/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01003261 * return TRUE if "name" is a directory, NOT a symlink to a directory
3262 * return FALSE if "name" is not a directory
3263 * return FALSE for error
3264 */
3265 int
3266mch_isrealdir(char_u *name)
3267{
3268 return mch_isdir(name) && !mch_is_symbolic_link(name);
3269}
3270
3271/*
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003272 * Create directory "name".
3273 * Return 0 on success, -1 on error.
3274 */
3275 int
3276mch_mkdir(char_u *name)
3277{
3278#ifdef FEAT_MBYTE
3279 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3280 {
3281 WCHAR *p;
3282 int retval;
3283
3284 p = enc_to_utf16(name, NULL);
3285 if (p == NULL)
3286 return -1;
3287 retval = _wmkdir(p);
3288 vim_free(p);
3289 return retval;
3290 }
3291#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003292 return _mkdir((const char *)name);
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003293}
3294
3295/*
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003296 * Delete directory "name".
3297 * Return 0 on success, -1 on error.
3298 */
3299 int
3300mch_rmdir(char_u *name)
3301{
3302#ifdef FEAT_MBYTE
3303 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3304 {
3305 WCHAR *p;
3306 int retval;
3307
3308 p = enc_to_utf16(name, NULL);
3309 if (p == NULL)
3310 return -1;
3311 retval = _wrmdir(p);
3312 vim_free(p);
3313 return retval;
3314 }
3315#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003316 return _rmdir((const char *)name);
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003317}
3318
3319/*
Bram Moolenaar03f48552006-02-28 23:52:23 +00003320 * Return TRUE if file "fname" has more than one link.
3321 */
3322 int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003323mch_is_hard_link(char_u *fname)
Bram Moolenaar03f48552006-02-28 23:52:23 +00003324{
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003325 BY_HANDLE_FILE_INFORMATION info;
3326
3327 return win32_fileinfo(fname, &info) == FILEINFO_OK
3328 && info.nNumberOfLinks > 1;
3329}
3330
3331/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01003332 * Return TRUE if "name" is a symbolic link (or a junction).
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003333 */
3334 int
Bram Moolenaar203258c2016-01-17 22:15:16 +01003335mch_is_symbolic_link(char_u *name)
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003336{
3337 HANDLE hFind;
3338 int res = FALSE;
3339 WIN32_FIND_DATAA findDataA;
3340 DWORD fileFlags = 0, reparseTag = 0;
3341#ifdef FEAT_MBYTE
3342 WCHAR *wn = NULL;
3343 WIN32_FIND_DATAW findDataW;
3344
3345 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar203258c2016-01-17 22:15:16 +01003346 wn = enc_to_utf16(name, NULL);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003347 if (wn != NULL)
3348 {
3349 hFind = FindFirstFileW(wn, &findDataW);
3350 vim_free(wn);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003351 if (hFind != INVALID_HANDLE_VALUE)
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003352 {
3353 fileFlags = findDataW.dwFileAttributes;
3354 reparseTag = findDataW.dwReserved0;
3355 }
3356 }
Bram Moolenaar03e114b2013-06-16 16:34:56 +02003357 else
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003358#endif
Bram Moolenaar03e114b2013-06-16 16:34:56 +02003359 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003360 hFind = FindFirstFile((LPCSTR)name, &findDataA);
Bram Moolenaar03e114b2013-06-16 16:34:56 +02003361 if (hFind != INVALID_HANDLE_VALUE)
3362 {
3363 fileFlags = findDataA.dwFileAttributes;
3364 reparseTag = findDataA.dwReserved0;
3365 }
3366 }
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003367
3368 if (hFind != INVALID_HANDLE_VALUE)
3369 FindClose(hFind);
3370
3371 if ((fileFlags & FILE_ATTRIBUTE_REPARSE_POINT)
Bram Moolenaar203258c2016-01-17 22:15:16 +01003372 && (reparseTag == IO_REPARSE_TAG_SYMLINK
3373 || reparseTag == IO_REPARSE_TAG_MOUNT_POINT))
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003374 res = TRUE;
3375
3376 return res;
3377}
3378
3379/*
3380 * Return TRUE if file "fname" has more than one link or if it is a symbolic
3381 * link.
3382 */
3383 int
3384mch_is_linked(char_u *fname)
3385{
3386 if (mch_is_hard_link(fname) || mch_is_symbolic_link(fname))
3387 return TRUE;
3388 return FALSE;
3389}
3390
3391/*
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003392 * Get the by-handle-file-information for "fname".
3393 * Returns FILEINFO_OK when OK.
3394 * returns FILEINFO_ENC_FAIL when enc_to_utf16() failed.
3395 * Returns FILEINFO_READ_FAIL when CreateFile() failed.
3396 * Returns FILEINFO_INFO_FAIL when GetFileInformationByHandle() failed.
3397 */
3398 int
3399win32_fileinfo(char_u *fname, BY_HANDLE_FILE_INFORMATION *info)
3400{
Bram Moolenaar03f48552006-02-28 23:52:23 +00003401 HANDLE hFile;
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003402 int res = FILEINFO_READ_FAIL;
Bram Moolenaar03f48552006-02-28 23:52:23 +00003403#ifdef FEAT_MBYTE
3404 WCHAR *wn = NULL;
3405
3406 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003407 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00003408 wn = enc_to_utf16(fname, NULL);
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003409 if (wn == NULL)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003410 return FILEINFO_ENC_FAIL;
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003411 }
Bram Moolenaar03f48552006-02-28 23:52:23 +00003412 if (wn != NULL)
3413 {
3414 hFile = CreateFileW(wn, /* file name */
3415 GENERIC_READ, /* access mode */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003416 FILE_SHARE_READ | FILE_SHARE_WRITE, /* share mode */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003417 NULL, /* security descriptor */
3418 OPEN_EXISTING, /* creation disposition */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003419 FILE_FLAG_BACKUP_SEMANTICS, /* file attributes */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003420 NULL); /* handle to template file */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003421 vim_free(wn);
Bram Moolenaar03f48552006-02-28 23:52:23 +00003422 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003423 else
Bram Moolenaar03f48552006-02-28 23:52:23 +00003424#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003425 hFile = CreateFile((LPCSTR)fname, /* file name */
3426 GENERIC_READ, /* access mode */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003427 FILE_SHARE_READ | FILE_SHARE_WRITE, /* share mode */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003428 NULL, /* security descriptor */
3429 OPEN_EXISTING, /* creation disposition */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003430 FILE_FLAG_BACKUP_SEMANTICS, /* file attributes */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003431 NULL); /* handle to template file */
3432
3433 if (hFile != INVALID_HANDLE_VALUE)
3434 {
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003435 if (GetFileInformationByHandle(hFile, info) != 0)
3436 res = FILEINFO_OK;
3437 else
3438 res = FILEINFO_INFO_FAIL;
Bram Moolenaar03f48552006-02-28 23:52:23 +00003439 CloseHandle(hFile);
3440 }
3441
Bram Moolenaar03f48552006-02-28 23:52:23 +00003442 return res;
3443}
3444
3445/*
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003446 * get file attributes for `name'
3447 * -1 : error
3448 * else FILE_ATTRIBUTE_* defined in winnt.h
3449 */
Bram Moolenaarffa22202013-11-21 12:34:11 +01003450 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003451win32_getattrs(char_u *name)
3452{
3453 int attr;
3454#ifdef FEAT_MBYTE
3455 WCHAR *p = NULL;
3456
3457 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3458 p = enc_to_utf16(name, NULL);
3459
3460 if (p != NULL)
3461 {
3462 attr = GetFileAttributesW(p);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003463 vim_free(p);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003464 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003465 else
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003466#endif
3467 attr = GetFileAttributes((char *)name);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003468
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003469 return attr;
3470}
3471
3472/*
3473 * set file attributes for `name' to `attrs'
3474 *
3475 * return -1 for failure, 0 otherwise
3476 */
Bram Moolenaar6dff58f2018-09-30 21:43:26 +02003477 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003478win32_setattrs(char_u *name, int attrs)
3479{
3480 int res;
3481#ifdef FEAT_MBYTE
3482 WCHAR *p = NULL;
3483
3484 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3485 p = enc_to_utf16(name, NULL);
3486
3487 if (p != NULL)
3488 {
3489 res = SetFileAttributesW(p, attrs);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003490 vim_free(p);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003491 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003492 else
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003493#endif
3494 res = SetFileAttributes((char *)name, attrs);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003495
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003496 return res ? 0 : -1;
3497}
3498
3499/*
3500 * Set archive flag for "name".
3501 */
Bram Moolenaar6dff58f2018-09-30 21:43:26 +02003502 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003503win32_set_archive(char_u *name)
3504{
3505 int attrs = win32_getattrs(name);
3506 if (attrs == -1)
3507 return -1;
3508
3509 attrs |= FILE_ATTRIBUTE_ARCHIVE;
3510 return win32_setattrs(name, attrs);
3511}
3512
3513/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003514 * Return TRUE if file or directory "name" is writable (not readonly).
3515 * Strange semantics of Win32: a readonly directory is writable, but you can't
3516 * delete a file. Let's say this means it is writable.
3517 */
3518 int
3519mch_writable(char_u *name)
3520{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003521 int attrs = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003522
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003523 return (attrs != -1 && (!(attrs & FILE_ATTRIBUTE_READONLY)
3524 || (attrs & FILE_ATTRIBUTE_DIRECTORY)));
Bram Moolenaar071d4272004-06-13 20:20:40 +00003525}
3526
Bram Moolenaar071d4272004-06-13 20:20:40 +00003527/*
Bram Moolenaar43663192017-03-05 14:29:12 +01003528 * Return TRUE if "name" can be executed, FALSE if not.
Bram Moolenaar77b77102015-03-21 22:18:41 +01003529 * If "use_path" is FALSE only check if "name" is executable.
Bram Moolenaar43663192017-03-05 14:29:12 +01003530 * When returning TRUE and "path" is not NULL save the path and set "*path" to
3531 * the allocated memory.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003532 */
3533 int
Bram Moolenaar77b77102015-03-21 22:18:41 +01003534mch_can_exe(char_u *name, char_u **path, int use_path)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003535{
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003536 char_u buf[_MAX_PATH];
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00003537 int len = (int)STRLEN(name);
Bram Moolenaar82956662018-10-06 15:18:45 +02003538 char_u *p, *saved;
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003539
3540 if (len >= _MAX_PATH) /* safety check */
3541 return FALSE;
3542
Bram Moolenaar82956662018-10-06 15:18:45 +02003543 /* Ty using the name directly when a Unix-shell like 'shell'. */
3544 if (strstr((char *)gettail(p_sh), "sh") != NULL)
Bram Moolenaar43663192017-03-05 14:29:12 +01003545 if (executable_exists((char *)name, path, use_path))
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003546 return TRUE;
3547
3548 /*
3549 * Loop over all extensions in $PATHEXT.
3550 */
Bram Moolenaar82956662018-10-06 15:18:45 +02003551 p = mch_getenv("PATHEXT");
3552 if (p == NULL)
3553 p = (char_u *)".com;.exe;.bat;.cmd";
3554 saved = vim_strsave(p);
3555 if (saved == NULL)
3556 return FALSE;
3557 p = saved;
3558 while (*p)
3559 {
3560 char_u *tmp = vim_strchr(p, ';');
3561
3562 if (tmp != NULL)
3563 *tmp = NUL;
3564 if (_stricoll((char *)name + len - STRLEN(p), (char *)p) == 0
3565 && executable_exists((char *)name, path, use_path))
3566 {
3567 vim_free(saved);
3568 return TRUE;
3569 }
3570 if (tmp == NULL)
3571 break;
3572 p = tmp + 1;
3573 }
3574 vim_free(saved);
3575
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00003576 vim_strncpy(buf, name, _MAX_PATH - 1);
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003577 p = mch_getenv("PATHEXT");
3578 if (p == NULL)
3579 p = (char_u *)".com;.exe;.bat;.cmd";
3580 while (*p)
3581 {
3582 if (p[0] == '.' && (p[1] == NUL || p[1] == ';'))
3583 {
3584 /* A single "." means no extension is added. */
3585 buf[len] = NUL;
3586 ++p;
3587 if (*p)
3588 ++p;
3589 }
3590 else
3591 copy_option_part(&p, buf + len, _MAX_PATH - len, ";");
Bram Moolenaar43663192017-03-05 14:29:12 +01003592 if (executable_exists((char *)buf, path, use_path))
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003593 return TRUE;
3594 }
3595 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003596}
Bram Moolenaar071d4272004-06-13 20:20:40 +00003597
3598/*
3599 * Check what "name" is:
3600 * NODE_NORMAL: file or directory (or doesn't exist)
3601 * NODE_WRITABLE: writable device, socket, fifo, etc.
3602 * NODE_OTHER: non-writable things
3603 */
3604 int
3605mch_nodetype(char_u *name)
3606{
3607 HANDLE hFile;
3608 int type;
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003609#ifdef FEAT_MBYTE
3610 WCHAR *wn = NULL;
3611#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003612
Bram Moolenaar043545e2006-10-10 16:44:07 +00003613 /* We can't open a file with a name "\\.\con" or "\\.\prn" and trying to
3614 * read from it later will cause Vim to hang. Thus return NODE_WRITABLE
3615 * here. */
3616 if (STRNCMP(name, "\\\\.\\", 4) == 0)
3617 return NODE_WRITABLE;
3618
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003619#ifdef FEAT_MBYTE
3620 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003621 wn = enc_to_utf16(name, NULL);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003622
3623 if (wn != NULL)
3624 {
3625 hFile = CreateFileW(wn, /* file name */
3626 GENERIC_WRITE, /* access mode */
3627 0, /* share mode */
3628 NULL, /* security descriptor */
3629 OPEN_EXISTING, /* creation disposition */
3630 0, /* file attributes */
3631 NULL); /* handle to template file */
3632 vim_free(wn);
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003633 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003634 else
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003635#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003636 hFile = CreateFile((LPCSTR)name, /* file name */
3637 GENERIC_WRITE, /* access mode */
3638 0, /* share mode */
3639 NULL, /* security descriptor */
3640 OPEN_EXISTING, /* creation disposition */
3641 0, /* file attributes */
3642 NULL); /* handle to template file */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003643
3644 if (hFile == INVALID_HANDLE_VALUE)
3645 return NODE_NORMAL;
3646
3647 type = GetFileType(hFile);
3648 CloseHandle(hFile);
3649 if (type == FILE_TYPE_CHAR)
3650 return NODE_WRITABLE;
3651 if (type == FILE_TYPE_DISK)
3652 return NODE_NORMAL;
3653 return NODE_OTHER;
3654}
3655
3656#ifdef HAVE_ACL
3657struct my_acl
3658{
3659 PSECURITY_DESCRIPTOR pSecurityDescriptor;
3660 PSID pSidOwner;
3661 PSID pSidGroup;
3662 PACL pDacl;
3663 PACL pSacl;
3664};
3665#endif
3666
3667/*
3668 * Return a pointer to the ACL of file "fname" in allocated memory.
3669 * Return NULL if the ACL is not available for whatever reason.
3670 */
3671 vim_acl_T
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003672mch_get_acl(char_u *fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003673{
3674#ifndef HAVE_ACL
3675 return (vim_acl_T)NULL;
3676#else
3677 struct my_acl *p = NULL;
Bram Moolenaar27515922013-06-29 15:36:26 +02003678 DWORD err;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003679
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003680 p = (struct my_acl *)alloc_clear((unsigned)sizeof(struct my_acl));
3681 if (p != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003682 {
Bram Moolenaar27515922013-06-29 15:36:26 +02003683# ifdef FEAT_MBYTE
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003684 WCHAR *wn = NULL;
Bram Moolenaar27515922013-06-29 15:36:26 +02003685
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003686 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3687 wn = enc_to_utf16(fname, NULL);
3688 if (wn != NULL)
3689 {
3690 /* Try to retrieve the entire security descriptor. */
3691 err = GetNamedSecurityInfoW(
3692 wn, // Abstract filename
3693 SE_FILE_OBJECT, // File Object
3694 OWNER_SECURITY_INFORMATION |
3695 GROUP_SECURITY_INFORMATION |
3696 DACL_SECURITY_INFORMATION |
3697 SACL_SECURITY_INFORMATION,
3698 &p->pSidOwner, // Ownership information.
3699 &p->pSidGroup, // Group membership.
3700 &p->pDacl, // Discretionary information.
3701 &p->pSacl, // For auditing purposes.
3702 &p->pSecurityDescriptor);
3703 if (err == ERROR_ACCESS_DENIED ||
3704 err == ERROR_PRIVILEGE_NOT_HELD)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003705 {
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003706 /* Retrieve only DACL. */
3707 (void)GetNamedSecurityInfoW(
3708 wn,
3709 SE_FILE_OBJECT,
3710 DACL_SECURITY_INFORMATION,
3711 NULL,
3712 NULL,
3713 &p->pDacl,
3714 NULL,
3715 &p->pSecurityDescriptor);
Bram Moolenaar27515922013-06-29 15:36:26 +02003716 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003717 if (p->pSecurityDescriptor == NULL)
Bram Moolenaar27515922013-06-29 15:36:26 +02003718 {
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003719 mch_free_acl((vim_acl_T)p);
3720 p = NULL;
3721 }
3722 vim_free(wn);
3723 }
3724 else
3725# endif
3726 {
3727 /* Try to retrieve the entire security descriptor. */
3728 err = GetNamedSecurityInfo(
3729 (LPSTR)fname, // Abstract filename
3730 SE_FILE_OBJECT, // File Object
3731 OWNER_SECURITY_INFORMATION |
3732 GROUP_SECURITY_INFORMATION |
3733 DACL_SECURITY_INFORMATION |
3734 SACL_SECURITY_INFORMATION,
3735 &p->pSidOwner, // Ownership information.
3736 &p->pSidGroup, // Group membership.
3737 &p->pDacl, // Discretionary information.
3738 &p->pSacl, // For auditing purposes.
3739 &p->pSecurityDescriptor);
3740 if (err == ERROR_ACCESS_DENIED ||
3741 err == ERROR_PRIVILEGE_NOT_HELD)
3742 {
3743 /* Retrieve only DACL. */
3744 (void)GetNamedSecurityInfo(
3745 (LPSTR)fname,
3746 SE_FILE_OBJECT,
3747 DACL_SECURITY_INFORMATION,
3748 NULL,
3749 NULL,
3750 &p->pDacl,
3751 NULL,
3752 &p->pSecurityDescriptor);
3753 }
3754 if (p->pSecurityDescriptor == NULL)
3755 {
3756 mch_free_acl((vim_acl_T)p);
3757 p = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003758 }
3759 }
3760 }
3761
3762 return (vim_acl_T)p;
3763#endif
3764}
3765
Bram Moolenaar27515922013-06-29 15:36:26 +02003766#ifdef HAVE_ACL
3767/*
3768 * Check if "acl" contains inherited ACE.
3769 */
3770 static BOOL
3771is_acl_inherited(PACL acl)
3772{
3773 DWORD i;
3774 ACL_SIZE_INFORMATION acl_info;
3775 PACCESS_ALLOWED_ACE ace;
3776
3777 acl_info.AceCount = 0;
3778 GetAclInformation(acl, &acl_info, sizeof(acl_info), AclSizeInformation);
3779 for (i = 0; i < acl_info.AceCount; i++)
3780 {
3781 GetAce(acl, i, (LPVOID *)&ace);
3782 if (ace->Header.AceFlags & INHERITED_ACE)
3783 return TRUE;
3784 }
3785 return FALSE;
3786}
3787#endif
3788
Bram Moolenaar071d4272004-06-13 20:20:40 +00003789/*
3790 * Set the ACL of file "fname" to "acl" (unless it's NULL).
3791 * Errors are ignored.
3792 * This must only be called with "acl" equal to what mch_get_acl() returned.
3793 */
3794 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003795mch_set_acl(char_u *fname, vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003796{
3797#ifdef HAVE_ACL
3798 struct my_acl *p = (struct my_acl *)acl;
Bram Moolenaar27515922013-06-29 15:36:26 +02003799 SECURITY_INFORMATION sec_info = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003800
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003801 if (p != NULL)
Bram Moolenaar27515922013-06-29 15:36:26 +02003802 {
3803# ifdef FEAT_MBYTE
3804 WCHAR *wn = NULL;
3805# endif
3806
3807 /* Set security flags */
3808 if (p->pSidOwner)
3809 sec_info |= OWNER_SECURITY_INFORMATION;
3810 if (p->pSidGroup)
3811 sec_info |= GROUP_SECURITY_INFORMATION;
3812 if (p->pDacl)
3813 {
3814 sec_info |= DACL_SECURITY_INFORMATION;
3815 /* Do not inherit its parent's DACL.
3816 * If the DACL is inherited, Cygwin permissions would be changed.
3817 */
3818 if (!is_acl_inherited(p->pDacl))
3819 sec_info |= PROTECTED_DACL_SECURITY_INFORMATION;
3820 }
3821 if (p->pSacl)
3822 sec_info |= SACL_SECURITY_INFORMATION;
3823
3824# ifdef FEAT_MBYTE
3825 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3826 wn = enc_to_utf16(fname, NULL);
3827 if (wn != NULL)
3828 {
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003829 (void)SetNamedSecurityInfoW(
Bram Moolenaar27515922013-06-29 15:36:26 +02003830 wn, // Abstract filename
3831 SE_FILE_OBJECT, // File Object
3832 sec_info,
3833 p->pSidOwner, // Ownership information.
3834 p->pSidGroup, // Group membership.
3835 p->pDacl, // Discretionary information.
3836 p->pSacl // For auditing purposes.
3837 );
3838 vim_free(wn);
3839 }
3840 else
3841# endif
3842 {
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003843 (void)SetNamedSecurityInfo(
Bram Moolenaar27515922013-06-29 15:36:26 +02003844 (LPSTR)fname, // Abstract filename
3845 SE_FILE_OBJECT, // File Object
3846 sec_info,
3847 p->pSidOwner, // Ownership information.
3848 p->pSidGroup, // Group membership.
3849 p->pDacl, // Discretionary information.
3850 p->pSacl // For auditing purposes.
3851 );
3852 }
3853 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003854#endif
3855}
3856
3857 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003858mch_free_acl(vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003859{
3860#ifdef HAVE_ACL
3861 struct my_acl *p = (struct my_acl *)acl;
3862
3863 if (p != NULL)
3864 {
3865 LocalFree(p->pSecurityDescriptor); // Free the memory just in case
3866 vim_free(p);
3867 }
3868#endif
3869}
3870
3871#ifndef FEAT_GUI_W32
3872
3873/*
3874 * handler for ctrl-break, ctrl-c interrupts, and fatal events.
3875 */
3876 static BOOL WINAPI
3877handler_routine(
3878 DWORD dwCtrlType)
3879{
Bram Moolenaar589b1102017-08-12 16:39:05 +02003880 INPUT_RECORD ir;
3881 DWORD out;
3882
Bram Moolenaar071d4272004-06-13 20:20:40 +00003883 switch (dwCtrlType)
3884 {
3885 case CTRL_C_EVENT:
3886 if (ctrl_c_interrupts)
3887 g_fCtrlCPressed = TRUE;
3888 return TRUE;
3889
3890 case CTRL_BREAK_EVENT:
3891 g_fCBrkPressed = TRUE;
Bram Moolenaar589b1102017-08-12 16:39:05 +02003892 ctrl_break_was_pressed = TRUE;
3893 /* ReadConsoleInput is blocking, send a key event to continue. */
3894 ir.EventType = KEY_EVENT;
3895 ir.Event.KeyEvent.bKeyDown = TRUE;
3896 ir.Event.KeyEvent.wRepeatCount = 1;
3897 ir.Event.KeyEvent.wVirtualKeyCode = VK_CANCEL;
3898 ir.Event.KeyEvent.wVirtualScanCode = 0;
3899 ir.Event.KeyEvent.dwControlKeyState = 0;
3900 ir.Event.KeyEvent.uChar.UnicodeChar = 0;
3901 WriteConsoleInput(g_hConIn, &ir, 1, &out);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003902 return TRUE;
3903
3904 /* fatal events: shut down gracefully */
3905 case CTRL_CLOSE_EVENT:
3906 case CTRL_LOGOFF_EVENT:
3907 case CTRL_SHUTDOWN_EVENT:
3908 windgoto((int)Rows - 1, 0);
3909 g_fForceExit = TRUE;
3910
Bram Moolenaar0fde2902008-03-16 13:54:13 +00003911 vim_snprintf((char *)IObuff, IOSIZE, _("Vim: Caught %s event\n"),
Bram Moolenaar071d4272004-06-13 20:20:40 +00003912 (dwCtrlType == CTRL_CLOSE_EVENT
3913 ? _("close")
3914 : dwCtrlType == CTRL_LOGOFF_EVENT
3915 ? _("logoff")
3916 : _("shutdown")));
3917#ifdef DEBUG
3918 OutputDebugString(IObuff);
3919#endif
3920
3921 preserve_exit(); /* output IObuff, preserve files and exit */
3922
3923 return TRUE; /* not reached */
3924
3925 default:
3926 return FALSE;
3927 }
3928}
3929
3930
3931/*
3932 * set the tty in (raw) ? "raw" : "cooked" mode
3933 */
3934 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003935mch_settmode(int tmode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003936{
3937 DWORD cmodein;
3938 DWORD cmodeout;
3939 BOOL bEnableHandler;
3940
3941 GetConsoleMode(g_hConIn, &cmodein);
3942 GetConsoleMode(g_hConOut, &cmodeout);
3943 if (tmode == TMODE_RAW)
3944 {
3945 cmodein &= ~(ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
3946 ENABLE_ECHO_INPUT);
3947#ifdef FEAT_MOUSE
3948 if (g_fMouseActive)
3949 cmodein |= ENABLE_MOUSE_INPUT;
3950#endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01003951 cmodeout &= ~(
3952#ifdef FEAT_TERMGUICOLORS
3953 /* Do not turn off the ENABLE_PROCESSRD_OUTPUT flag when using
3954 * VTP. */
3955 ((vtp_working) ? 0 : ENABLE_PROCESSED_OUTPUT) |
3956#else
3957 ENABLE_PROCESSED_OUTPUT |
3958#endif
3959 ENABLE_WRAP_AT_EOL_OUTPUT);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003960 bEnableHandler = TRUE;
3961 }
3962 else /* cooked */
3963 {
3964 cmodein |= (ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
3965 ENABLE_ECHO_INPUT);
3966 cmodeout |= (ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
3967 bEnableHandler = FALSE;
3968 }
3969 SetConsoleMode(g_hConIn, cmodein);
3970 SetConsoleMode(g_hConOut, cmodeout);
3971 SetConsoleCtrlHandler(handler_routine, bEnableHandler);
3972
3973#ifdef MCH_WRITE_DUMP
3974 if (fdDump)
3975 {
3976 fprintf(fdDump, "mch_settmode(%s, in = %x, out = %x)\n",
3977 tmode == TMODE_RAW ? "raw" :
3978 tmode == TMODE_COOK ? "cooked" : "normal",
3979 cmodein, cmodeout);
3980 fflush(fdDump);
3981 }
3982#endif
3983}
3984
3985
3986/*
3987 * Get the size of the current window in `Rows' and `Columns'
3988 * Return OK when size could be determined, FAIL otherwise.
3989 */
3990 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003991mch_get_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003992{
3993 CONSOLE_SCREEN_BUFFER_INFO csbi;
3994
3995 if (!g_fTermcapMode && g_cbTermcap.IsValid)
3996 {
3997 /*
3998 * For some reason, we are trying to get the screen dimensions
3999 * even though we are not in termcap mode. The 'Rows' and 'Columns'
4000 * variables are really intended to mean the size of Vim screen
4001 * while in termcap mode.
4002 */
4003 Rows = g_cbTermcap.Info.dwSize.Y;
4004 Columns = g_cbTermcap.Info.dwSize.X;
4005 }
4006 else if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
4007 {
4008 Rows = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
4009 Columns = csbi.srWindow.Right - csbi.srWindow.Left + 1;
4010 }
4011 else
4012 {
4013 Rows = 25;
4014 Columns = 80;
4015 }
4016 return OK;
4017}
4018
4019/*
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004020 * Resize console buffer to 'COORD'
4021 */
4022 static void
4023ResizeConBuf(
4024 HANDLE hConsole,
4025 COORD coordScreen)
4026{
4027 if (!SetConsoleScreenBufferSize(hConsole, coordScreen))
4028 {
4029#ifdef MCH_WRITE_DUMP
4030 if (fdDump)
4031 {
4032 fprintf(fdDump, "SetConsoleScreenBufferSize failed: %lx\n",
4033 GetLastError());
4034 fflush(fdDump);
4035 }
4036#endif
4037 }
4038}
4039
4040/*
4041 * Resize console window size to 'srWindowRect'
4042 */
4043 static void
4044ResizeWindow(
4045 HANDLE hConsole,
4046 SMALL_RECT srWindowRect)
4047{
4048 if (!SetConsoleWindowInfo(hConsole, TRUE, &srWindowRect))
4049 {
4050#ifdef MCH_WRITE_DUMP
4051 if (fdDump)
4052 {
4053 fprintf(fdDump, "SetConsoleWindowInfo failed: %lx\n",
4054 GetLastError());
4055 fflush(fdDump);
4056 }
4057#endif
4058 }
4059}
4060
4061/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00004062 * Set a console window to `xSize' * `ySize'
4063 */
4064 static void
4065ResizeConBufAndWindow(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004066 HANDLE hConsole,
4067 int xSize,
4068 int ySize)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004069{
4070 CONSOLE_SCREEN_BUFFER_INFO csbi; /* hold current console buffer info */
4071 SMALL_RECT srWindowRect; /* hold the new console size */
4072 COORD coordScreen;
Bram Moolenaar2551c032018-08-23 22:38:31 +02004073 static int resized = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004074
4075#ifdef MCH_WRITE_DUMP
4076 if (fdDump)
4077 {
4078 fprintf(fdDump, "ResizeConBufAndWindow(%d, %d)\n", xSize, ySize);
4079 fflush(fdDump);
4080 }
4081#endif
4082
4083 /* get the largest size we can size the console window to */
4084 coordScreen = GetLargestConsoleWindowSize(hConsole);
4085
4086 /* define the new console window size and scroll position */
4087 srWindowRect.Left = srWindowRect.Top = (SHORT) 0;
4088 srWindowRect.Right = (SHORT) (min(xSize, coordScreen.X) - 1);
4089 srWindowRect.Bottom = (SHORT) (min(ySize, coordScreen.Y) - 1);
4090
4091 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
4092 {
4093 int sx, sy;
4094
4095 sx = csbi.srWindow.Right - csbi.srWindow.Left + 1;
4096 sy = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
4097 if (sy < ySize || sx < xSize)
4098 {
4099 /*
4100 * Increasing number of lines/columns, do buffer first.
4101 * Use the maximal size in x and y direction.
4102 */
4103 if (sy < ySize)
4104 coordScreen.Y = ySize;
4105 else
4106 coordScreen.Y = sy;
4107 if (sx < xSize)
4108 coordScreen.X = xSize;
4109 else
4110 coordScreen.X = sx;
4111 SetConsoleScreenBufferSize(hConsole, coordScreen);
4112 }
4113 }
4114
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004115 // define the new console buffer size
Bram Moolenaar071d4272004-06-13 20:20:40 +00004116 coordScreen.X = xSize;
4117 coordScreen.Y = ySize;
4118
Bram Moolenaar2551c032018-08-23 22:38:31 +02004119 // In the new console call API, only the first time in reverse order
4120 if (!vtp_working || resized)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004121 {
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004122 ResizeWindow(hConsole, srWindowRect);
4123 ResizeConBuf(hConsole, coordScreen);
4124 }
4125 else
4126 {
4127 ResizeConBuf(hConsole, coordScreen);
4128 ResizeWindow(hConsole, srWindowRect);
Bram Moolenaar2551c032018-08-23 22:38:31 +02004129 resized = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004130 }
4131}
4132
4133
4134/*
4135 * Set the console window to `Rows' * `Columns'
4136 */
4137 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004138mch_set_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004139{
4140 COORD coordScreen;
4141
4142 /* Don't change window size while still starting up */
4143 if (suppress_winsize != 0)
4144 {
4145 suppress_winsize = 2;
4146 return;
4147 }
4148
4149 if (term_console)
4150 {
4151 coordScreen = GetLargestConsoleWindowSize(g_hConOut);
4152
4153 /* Clamp Rows and Columns to reasonable values */
4154 if (Rows > coordScreen.Y)
4155 Rows = coordScreen.Y;
4156 if (Columns > coordScreen.X)
4157 Columns = coordScreen.X;
4158
4159 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
4160 }
4161}
4162
4163/*
4164 * Rows and/or Columns has changed.
4165 */
4166 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004167mch_new_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004168{
4169 set_scroll_region(0, 0, Columns - 1, Rows - 1);
4170}
4171
4172
4173/*
4174 * Called when started up, to set the winsize that was delayed.
4175 */
4176 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004177mch_set_winsize_now(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004178{
4179 if (suppress_winsize == 2)
4180 {
4181 suppress_winsize = 0;
4182 mch_set_shellsize();
4183 shell_resized();
4184 }
4185 suppress_winsize = 0;
4186}
4187#endif /* FEAT_GUI_W32 */
4188
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004189 static BOOL
4190vim_create_process(
Bram Moolenaar36c85b22013-12-12 20:25:44 +01004191 char *cmd,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004192 BOOL inherit_handles,
Bram Moolenaar3f1138e2014-01-05 13:29:26 +01004193 DWORD flags,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004194 STARTUPINFO *si,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004195 PROCESS_INFORMATION *pi,
4196 LPVOID *env,
4197 char *cwd)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004198{
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004199#ifdef FEAT_MBYTE
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004200 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4201 {
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004202 BOOL ret;
4203 WCHAR *wcmd, *wcwd = NULL;
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004204
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004205 wcmd = enc_to_utf16((char_u *)cmd, NULL);
4206 if (wcmd == NULL)
4207 goto fallback;
4208 if (cwd != NULL)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004209 {
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004210 wcwd = enc_to_utf16((char_u *)cwd, NULL);
4211 if (wcwd == NULL)
4212 {
4213 vim_free(wcmd);
4214 goto fallback;
4215 }
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004216 }
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004217
4218 ret = CreateProcessW(
4219 NULL, /* Executable name */
4220 wcmd, /* Command to execute */
4221 NULL, /* Process security attributes */
4222 NULL, /* Thread security attributes */
4223 inherit_handles, /* Inherit handles */
4224 flags, /* Creation flags */
4225 env, /* Environment */
4226 wcwd, /* Current directory */
4227 (LPSTARTUPINFOW)si, /* Startup information */
4228 pi); /* Process information */
4229 vim_free(wcmd);
4230 if (wcwd != NULL)
4231 vim_free(wcwd);
4232 return ret;
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004233 }
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004234fallback:
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004235#endif
4236 return CreateProcess(
4237 NULL, /* Executable name */
4238 cmd, /* Command to execute */
4239 NULL, /* Process security attributes */
4240 NULL, /* Thread security attributes */
4241 inherit_handles, /* Inherit handles */
4242 flags, /* Creation flags */
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004243 env, /* Environment */
4244 cwd, /* Current directory */
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004245 si, /* Startup information */
4246 pi); /* Process information */
4247}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004248
4249
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004250 static HINSTANCE
4251vim_shell_execute(
4252 char *cmd,
4253 INT n_show_cmd)
4254{
4255#ifdef FEAT_MBYTE
4256 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4257 {
4258 WCHAR *wcmd = enc_to_utf16((char_u *)cmd, NULL);
4259 if (wcmd != NULL)
4260 {
4261 HINSTANCE ret;
4262 ret = ShellExecuteW(NULL, NULL, wcmd, NULL, NULL, n_show_cmd);
4263 vim_free(wcmd);
4264 return ret;
4265 }
4266 }
4267#endif
4268 return ShellExecute(NULL, NULL, cmd, NULL, NULL, n_show_cmd);
4269}
4270
4271
Bram Moolenaar071d4272004-06-13 20:20:40 +00004272#if defined(FEAT_GUI_W32) || defined(PROTO)
4273
4274/*
4275 * Specialised version of system() for Win32 GUI mode.
4276 * This version proceeds as follows:
4277 * 1. Create a console window for use by the subprocess
4278 * 2. Run the subprocess (it gets the allocated console by default)
4279 * 3. Wait for the subprocess to terminate and get its exit code
4280 * 4. Prompt the user to press a key to close the console window
4281 */
4282 static int
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004283mch_system_classic(char *cmd, int options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004284{
4285 STARTUPINFO si;
4286 PROCESS_INFORMATION pi;
4287 DWORD ret = 0;
4288 HWND hwnd = GetFocus();
4289
4290 si.cb = sizeof(si);
4291 si.lpReserved = NULL;
4292 si.lpDesktop = NULL;
4293 si.lpTitle = NULL;
4294 si.dwFlags = STARTF_USESHOWWINDOW;
4295 /*
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004296 * It's nicer to run a filter command in a minimized window.
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01004297 * Don't activate the window to keep focus on Vim.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004298 */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004299 if (options & SHELL_DOOUT)
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01004300 si.wShowWindow = SW_SHOWMINNOACTIVE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004301 else
4302 si.wShowWindow = SW_SHOWNORMAL;
4303 si.cbReserved2 = 0;
4304 si.lpReserved2 = NULL;
4305
Bram Moolenaar071d4272004-06-13 20:20:40 +00004306 /* Now, run the command */
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004307 vim_create_process(cmd, FALSE,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004308 CREATE_DEFAULT_ERROR_MODE | CREATE_NEW_CONSOLE,
4309 &si, &pi, NULL, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004310
4311 /* Wait for the command to terminate before continuing */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004312 {
4313#ifdef FEAT_GUI
4314 int delay = 1;
4315
4316 /* Keep updating the window while waiting for the shell to finish. */
4317 for (;;)
4318 {
4319 MSG msg;
4320
Bram Moolenaar8c85fa32011-08-10 17:08:03 +02004321 if (pPeekMessage(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004322 {
4323 TranslateMessage(&msg);
Bram Moolenaar8c85fa32011-08-10 17:08:03 +02004324 pDispatchMessage(&msg);
Bram Moolenaare4195c52012-08-02 12:31:44 +02004325 delay = 1;
4326 continue;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004327 }
4328 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
4329 break;
4330
4331 /* We start waiting for a very short time and then increase it, so
4332 * that we respond quickly when the process is quick, and don't
4333 * consume too much overhead when it's slow. */
4334 if (delay < 50)
4335 delay += 10;
4336 }
4337#else
4338 WaitForSingleObject(pi.hProcess, INFINITE);
4339#endif
4340
4341 /* Get the command exit code */
4342 GetExitCodeProcess(pi.hProcess, &ret);
4343 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004344
4345 /* Close the handles to the subprocess, so that it goes away */
4346 CloseHandle(pi.hThread);
4347 CloseHandle(pi.hProcess);
4348
4349 /* Try to get input focus back. Doesn't always work though. */
4350 PostMessage(hwnd, WM_SETFOCUS, 0, 0);
4351
4352 return ret;
4353}
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004354
4355/*
4356 * Thread launched by the gui to send the current buffer data to the
4357 * process. This way avoid to hang up vim totally if the children
4358 * process take a long time to process the lines.
4359 */
Bram Moolenaar4c38d662016-08-03 20:54:57 +02004360 static unsigned int __stdcall
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004361sub_process_writer(LPVOID param)
4362{
4363 HANDLE g_hChildStd_IN_Wr = param;
4364 linenr_T lnum = curbuf->b_op_start.lnum;
4365 DWORD len = 0;
4366 DWORD l;
4367 char_u *lp = ml_get(lnum);
4368 char_u *s;
4369 int written = 0;
4370
4371 for (;;)
4372 {
4373 l = (DWORD)STRLEN(lp + written);
4374 if (l == 0)
4375 len = 0;
4376 else if (lp[written] == NL)
4377 {
4378 /* NL -> NUL translation */
4379 WriteFile(g_hChildStd_IN_Wr, "", 1, &len, NULL);
4380 }
4381 else
4382 {
4383 s = vim_strchr(lp + written, NL);
4384 WriteFile(g_hChildStd_IN_Wr, (char *)lp + written,
4385 s == NULL ? l : (DWORD)(s - (lp + written)),
4386 &len, NULL);
4387 }
4388 if (len == (int)l)
4389 {
4390 /* Finished a line, add a NL, unless this line should not have
4391 * one. */
4392 if (lnum != curbuf->b_op_end.lnum
Bram Moolenaar34d72d42015-07-17 14:18:08 +02004393 || (!curbuf->b_p_bin
4394 && curbuf->b_p_fixeol)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004395 || (lnum != curbuf->b_no_eol_lnum
4396 && (lnum != curbuf->b_ml.ml_line_count
4397 || curbuf->b_p_eol)))
4398 {
Bram Moolenaar42335f52018-09-13 15:33:43 +02004399 WriteFile(g_hChildStd_IN_Wr, "\n", 1,
4400 (LPDWORD)&vim_ignored, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004401 }
4402
4403 ++lnum;
4404 if (lnum > curbuf->b_op_end.lnum)
4405 break;
4406
4407 lp = ml_get(lnum);
4408 written = 0;
4409 }
4410 else if (len > 0)
4411 written += len;
4412 }
4413
4414 /* finished all the lines, close pipe */
4415 CloseHandle(g_hChildStd_IN_Wr);
Bram Moolenaar86f2cd52016-08-02 21:55:17 +02004416 return 0;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004417}
4418
4419
4420# define BUFLEN 100 /* length for buffer, stolen from unix version */
4421
4422/*
4423 * This function read from the children's stdout and write the
4424 * data on screen or in the buffer accordingly.
4425 */
4426 static void
4427dump_pipe(int options,
4428 HANDLE g_hChildStd_OUT_Rd,
4429 garray_T *ga,
4430 char_u buffer[],
4431 DWORD *buffer_off)
4432{
4433 DWORD availableBytes = 0;
4434 DWORD i;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004435 int ret;
4436 DWORD len;
4437 DWORD toRead;
4438 int repeatCount;
4439
4440 /* we query the pipe to see if there is any data to read
4441 * to avoid to perform a blocking read */
4442 ret = PeekNamedPipe(g_hChildStd_OUT_Rd, /* pipe to query */
4443 NULL, /* optional buffer */
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02004444 0, /* buffer size */
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004445 NULL, /* number of read bytes */
4446 &availableBytes, /* available bytes total */
4447 NULL); /* byteLeft */
4448
4449 repeatCount = 0;
4450 /* We got real data in the pipe, read it */
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02004451 while (ret != 0 && availableBytes > 0)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004452 {
4453 repeatCount++;
4454 toRead =
4455# ifdef FEAT_MBYTE
4456 (DWORD)(BUFLEN - *buffer_off);
4457# else
4458 (DWORD)BUFLEN;
4459# endif
4460 toRead = availableBytes < toRead ? availableBytes : toRead;
4461 ReadFile(g_hChildStd_OUT_Rd, buffer
4462# ifdef FEAT_MBYTE
4463 + *buffer_off, toRead
4464# else
4465 , toRead
4466# endif
4467 , &len, NULL);
4468
4469 /* If we haven't read anything, there is a problem */
4470 if (len == 0)
4471 break;
4472
4473 availableBytes -= len;
4474
4475 if (options & SHELL_READ)
4476 {
4477 /* Do NUL -> NL translation, append NL separated
4478 * lines to the current buffer. */
4479 for (i = 0; i < len; ++i)
4480 {
4481 if (buffer[i] == NL)
4482 append_ga_line(ga);
4483 else if (buffer[i] == NUL)
4484 ga_append(ga, NL);
4485 else
4486 ga_append(ga, buffer[i]);
4487 }
4488 }
4489# ifdef FEAT_MBYTE
4490 else if (has_mbyte)
4491 {
4492 int l;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004493 int c;
4494 char_u *p;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004495
4496 len += *buffer_off;
4497 buffer[len] = NUL;
4498
4499 /* Check if the last character in buffer[] is
4500 * incomplete, keep these bytes for the next
4501 * round. */
4502 for (p = buffer; p < buffer + len; p += l)
4503 {
Bram Moolenaard3c907b2016-08-17 21:32:09 +02004504 l = MB_CPTR2LEN(p);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004505 if (l == 0)
4506 l = 1; /* NUL byte? */
4507 else if (MB_BYTE2LEN(*p) != l)
4508 break;
4509 }
4510 if (p == buffer) /* no complete character */
4511 {
4512 /* avoid getting stuck at an illegal byte */
4513 if (len >= 12)
4514 ++p;
4515 else
4516 {
4517 *buffer_off = len;
4518 return;
4519 }
4520 }
4521 c = *p;
4522 *p = NUL;
4523 msg_puts(buffer);
4524 if (p < buffer + len)
4525 {
4526 *p = c;
4527 *buffer_off = (DWORD)((buffer + len) - p);
4528 mch_memmove(buffer, p, *buffer_off);
4529 return;
4530 }
4531 *buffer_off = 0;
4532 }
4533# endif /* FEAT_MBYTE */
4534 else
4535 {
4536 buffer[len] = NUL;
4537 msg_puts(buffer);
4538 }
4539
4540 windgoto(msg_row, msg_col);
4541 cursor_on();
4542 out_flush();
4543 }
4544}
4545
4546/*
4547 * Version of system to use for windows NT > 5.0 (Win2K), use pipe
4548 * for communication and doesn't open any new window.
4549 */
4550 static int
4551mch_system_piped(char *cmd, int options)
4552{
4553 STARTUPINFO si;
4554 PROCESS_INFORMATION pi;
4555 DWORD ret = 0;
4556
4557 HANDLE g_hChildStd_IN_Rd = NULL;
4558 HANDLE g_hChildStd_IN_Wr = NULL;
4559 HANDLE g_hChildStd_OUT_Rd = NULL;
4560 HANDLE g_hChildStd_OUT_Wr = NULL;
4561
4562 char_u buffer[BUFLEN + 1]; /* reading buffer + size */
4563 DWORD len;
4564
4565 /* buffer used to receive keys */
4566 char_u ta_buf[BUFLEN + 1]; /* TypeAHead */
4567 int ta_len = 0; /* valid bytes in ta_buf[] */
4568
4569 DWORD i;
4570 int c;
4571 int noread_cnt = 0;
4572 garray_T ga;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004573 int delay = 1;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004574 DWORD buffer_off = 0; /* valid bytes in buffer[] */
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004575 char *p = NULL;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004576
4577 SECURITY_ATTRIBUTES saAttr;
4578
4579 /* Set the bInheritHandle flag so pipe handles are inherited. */
4580 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
4581 saAttr.bInheritHandle = TRUE;
4582 saAttr.lpSecurityDescriptor = NULL;
4583
4584 if ( ! CreatePipe(&g_hChildStd_OUT_Rd, &g_hChildStd_OUT_Wr, &saAttr, 0)
4585 /* Ensure the read handle to the pipe for STDOUT is not inherited. */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004586 || ! SetHandleInformation(g_hChildStd_OUT_Rd, HANDLE_FLAG_INHERIT, 0)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004587 /* Create a pipe for the child process's STDIN. */
4588 || ! CreatePipe(&g_hChildStd_IN_Rd, &g_hChildStd_IN_Wr, &saAttr, 0)
4589 /* Ensure the write handle to the pipe for STDIN is not inherited. */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004590 || ! SetHandleInformation(g_hChildStd_IN_Wr, HANDLE_FLAG_INHERIT, 0) )
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004591 {
4592 CloseHandle(g_hChildStd_IN_Rd);
4593 CloseHandle(g_hChildStd_IN_Wr);
4594 CloseHandle(g_hChildStd_OUT_Rd);
4595 CloseHandle(g_hChildStd_OUT_Wr);
4596 MSG_PUTS(_("\nCannot create pipes\n"));
4597 }
4598
4599 si.cb = sizeof(si);
4600 si.lpReserved = NULL;
4601 si.lpDesktop = NULL;
4602 si.lpTitle = NULL;
4603 si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
4604
4605 /* set-up our file redirection */
4606 si.hStdError = g_hChildStd_OUT_Wr;
4607 si.hStdOutput = g_hChildStd_OUT_Wr;
4608 si.hStdInput = g_hChildStd_IN_Rd;
4609 si.wShowWindow = SW_HIDE;
4610 si.cbReserved2 = 0;
4611 si.lpReserved2 = NULL;
4612
4613 if (options & SHELL_READ)
4614 ga_init2(&ga, 1, BUFLEN);
4615
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004616 if (cmd != NULL)
4617 {
4618 p = (char *)vim_strsave((char_u *)cmd);
4619 if (p != NULL)
4620 unescape_shellxquote((char_u *)p, p_sxe);
4621 else
4622 p = cmd;
4623 }
4624
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004625 /* Now, run the command.
4626 * About "Inherit handles" being TRUE: this command can be litigious,
4627 * handle inheritance was deactivated for pending temp file, but, if we
4628 * deactivate it, the pipes don't work for some reason. */
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004629 vim_create_process(p, TRUE, CREATE_DEFAULT_ERROR_MODE,
4630 &si, &pi, NULL, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004631
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004632 if (p != cmd)
4633 vim_free(p);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004634
4635 /* Close our unused side of the pipes */
4636 CloseHandle(g_hChildStd_IN_Rd);
4637 CloseHandle(g_hChildStd_OUT_Wr);
4638
4639 if (options & SHELL_WRITE)
4640 {
Bram Moolenaar86f2cd52016-08-02 21:55:17 +02004641 HANDLE thread = (HANDLE)
4642 _beginthreadex(NULL, /* security attributes */
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004643 0, /* default stack size */
4644 sub_process_writer, /* function to be executed */
4645 g_hChildStd_IN_Wr, /* parameter */
4646 0, /* creation flag, start immediately */
4647 NULL); /* we don't care about thread id */
4648 CloseHandle(thread);
4649 g_hChildStd_IN_Wr = NULL;
4650 }
4651
4652 /* Keep updating the window while waiting for the shell to finish. */
4653 for (;;)
4654 {
4655 MSG msg;
4656
Bram Moolenaar175d0702013-12-11 18:36:33 +01004657 if (pPeekMessage(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004658 {
4659 TranslateMessage(&msg);
Bram Moolenaar175d0702013-12-11 18:36:33 +01004660 pDispatchMessage(&msg);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004661 }
4662
4663 /* write pipe information in the window */
4664 if ((options & (SHELL_READ|SHELL_WRITE))
4665# ifdef FEAT_GUI
4666 || gui.in_use
4667# endif
4668 )
4669 {
4670 len = 0;
4671 if (!(options & SHELL_EXPAND)
4672 && ((options &
4673 (SHELL_READ|SHELL_WRITE|SHELL_COOKED))
4674 != (SHELL_READ|SHELL_WRITE|SHELL_COOKED)
4675# ifdef FEAT_GUI
4676 || gui.in_use
4677# endif
4678 )
4679 && (ta_len > 0 || noread_cnt > 4))
4680 {
4681 if (ta_len == 0)
4682 {
4683 /* Get extra characters when we don't have any. Reset the
4684 * counter and timer. */
4685 noread_cnt = 0;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004686 len = ui_inchar(ta_buf, BUFLEN, 10L, 0);
4687 }
4688 if (ta_len > 0 || len > 0)
4689 {
4690 /*
4691 * For pipes: Check for CTRL-C: send interrupt signal to
4692 * child. Check for CTRL-D: EOF, close pipe to child.
4693 */
4694 if (len == 1 && cmd != NULL)
4695 {
4696 if (ta_buf[ta_len] == Ctrl_C)
4697 {
4698 /* Learn what exit code is expected, for
4699 * now put 9 as SIGKILL */
4700 TerminateProcess(pi.hProcess, 9);
4701 }
4702 if (ta_buf[ta_len] == Ctrl_D)
4703 {
4704 CloseHandle(g_hChildStd_IN_Wr);
4705 g_hChildStd_IN_Wr = NULL;
4706 }
4707 }
4708
4709 /* replace K_BS by <BS> and K_DEL by <DEL> */
4710 for (i = ta_len; i < ta_len + len; ++i)
4711 {
4712 if (ta_buf[i] == CSI && len - i > 2)
4713 {
4714 c = TERMCAP2KEY(ta_buf[i + 1], ta_buf[i + 2]);
4715 if (c == K_DEL || c == K_KDEL || c == K_BS)
4716 {
4717 mch_memmove(ta_buf + i + 1, ta_buf + i + 3,
4718 (size_t)(len - i - 2));
4719 if (c == K_DEL || c == K_KDEL)
4720 ta_buf[i] = DEL;
4721 else
4722 ta_buf[i] = Ctrl_H;
4723 len -= 2;
4724 }
4725 }
4726 else if (ta_buf[i] == '\r')
4727 ta_buf[i] = '\n';
4728# ifdef FEAT_MBYTE
4729 if (has_mbyte)
4730 i += (*mb_ptr2len_len)(ta_buf + i,
4731 ta_len + len - i) - 1;
4732# endif
4733 }
4734
4735 /*
4736 * For pipes: echo the typed characters. For a pty this
4737 * does not seem to work.
4738 */
4739 for (i = ta_len; i < ta_len + len; ++i)
4740 {
4741 if (ta_buf[i] == '\n' || ta_buf[i] == '\b')
4742 msg_putchar(ta_buf[i]);
4743# ifdef FEAT_MBYTE
4744 else if (has_mbyte)
4745 {
4746 int l = (*mb_ptr2len)(ta_buf + i);
4747
4748 msg_outtrans_len(ta_buf + i, l);
4749 i += l - 1;
4750 }
4751# endif
4752 else
4753 msg_outtrans_len(ta_buf + i, 1);
4754 }
4755 windgoto(msg_row, msg_col);
4756 out_flush();
4757
4758 ta_len += len;
4759
4760 /*
4761 * Write the characters to the child, unless EOF has been
4762 * typed for pipes. Write one character at a time, to
4763 * avoid losing too much typeahead. When writing buffer
4764 * lines, drop the typed characters (only check for
4765 * CTRL-C).
4766 */
4767 if (options & SHELL_WRITE)
4768 ta_len = 0;
4769 else if (g_hChildStd_IN_Wr != NULL)
4770 {
4771 WriteFile(g_hChildStd_IN_Wr, (char*)ta_buf,
4772 1, &len, NULL);
4773 // if we are typing in, we want to keep things reactive
4774 delay = 1;
4775 if (len > 0)
4776 {
4777 ta_len -= len;
4778 mch_memmove(ta_buf, ta_buf + len, ta_len);
4779 }
4780 }
4781 }
4782 }
4783 }
4784
4785 if (ta_len)
4786 ui_inchar_undo(ta_buf, ta_len);
4787
4788 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
4789 {
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004790 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004791 break;
4792 }
4793
4794 ++noread_cnt;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004795 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004796
4797 /* We start waiting for a very short time and then increase it, so
4798 * that we respond quickly when the process is quick, and don't
4799 * consume too much overhead when it's slow. */
4800 if (delay < 50)
4801 delay += 10;
4802 }
4803
4804 /* Close the pipe */
4805 CloseHandle(g_hChildStd_OUT_Rd);
4806 if (g_hChildStd_IN_Wr != NULL)
4807 CloseHandle(g_hChildStd_IN_Wr);
4808
4809 WaitForSingleObject(pi.hProcess, INFINITE);
4810
4811 /* Get the command exit code */
4812 GetExitCodeProcess(pi.hProcess, &ret);
4813
4814 if (options & SHELL_READ)
4815 {
4816 if (ga.ga_len > 0)
4817 {
4818 append_ga_line(&ga);
4819 /* remember that the NL was missing */
4820 curbuf->b_no_eol_lnum = curwin->w_cursor.lnum;
4821 }
4822 else
4823 curbuf->b_no_eol_lnum = 0;
4824 ga_clear(&ga);
4825 }
4826
4827 /* Close the handles to the subprocess, so that it goes away */
4828 CloseHandle(pi.hThread);
4829 CloseHandle(pi.hProcess);
4830
4831 return ret;
4832}
4833
4834 static int
4835mch_system(char *cmd, int options)
4836{
4837 /* if we can pipe and the shelltemp option is off */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004838 if (!p_stmp)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004839 return mch_system_piped(cmd, options);
4840 else
4841 return mch_system_classic(cmd, options);
4842}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004843#else
4844
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004845# ifdef FEAT_MBYTE
4846 static int
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01004847mch_system(char *cmd, int options)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004848{
4849 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4850 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004851 WCHAR *wcmd = enc_to_utf16((char_u *)cmd, NULL);
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004852 if (wcmd != NULL)
4853 {
4854 int ret = _wsystem(wcmd);
4855 vim_free(wcmd);
4856 return ret;
4857 }
4858 }
4859 return system(cmd);
4860}
4861# else
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01004862# define mch_system(c, o) system(c)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004863# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004864
4865#endif
4866
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004867#if defined(FEAT_GUI) && defined(FEAT_TERMINAL)
4868/*
4869 * Use a terminal window to run a shell command in.
4870 */
4871 static int
4872mch_call_shell_terminal(
4873 char_u *cmd,
4874 int options UNUSED) /* SHELL_*, see vim.h */
4875{
4876 jobopt_T opt;
4877 char_u *newcmd = NULL;
4878 typval_T argvar[2];
4879 long_u cmdlen;
4880 int retval = -1;
4881 buf_T *buf;
Bram Moolenaarf9c38832018-06-19 19:59:20 +02004882 job_T *job;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004883 aco_save_T aco;
4884 oparg_T oa; /* operator arguments */
4885
Bram Moolenaar42f652f2018-03-19 21:44:37 +01004886 if (cmd == NULL)
4887 cmdlen = STRLEN(p_sh) + 1;
4888 else
4889 cmdlen = STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004890 newcmd = lalloc(cmdlen, TRUE);
4891 if (newcmd == NULL)
4892 return 255;
Bram Moolenaar42f652f2018-03-19 21:44:37 +01004893 if (cmd == NULL)
4894 {
4895 STRCPY(newcmd, p_sh);
4896 ch_log(NULL, "starting terminal to run a shell");
4897 }
4898 else
4899 {
4900 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s", p_sh, p_shcf, cmd);
4901 ch_log(NULL, "starting terminal for system command '%s'", cmd);
4902 }
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004903
4904 init_job_options(&opt);
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004905
4906 argvar[0].v_type = VAR_STRING;
4907 argvar[0].vval.v_string = newcmd;
4908 argvar[1].v_type = VAR_UNKNOWN;
4909 buf = term_start(argvar, NULL, &opt, TERM_START_SYSTEM);
Bram Moolenaar81c3c89a2018-03-20 11:41:44 +01004910 if (buf == NULL)
4911 return 255;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004912
Bram Moolenaarf9c38832018-06-19 19:59:20 +02004913 job = term_getjob(buf->b_term);
4914 ++job->jv_refcount;
4915
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004916 /* Find a window to make "buf" curbuf. */
4917 aucmd_prepbuf(&aco, buf);
4918
4919 clear_oparg(&oa);
4920 while (term_use_loop())
4921 {
4922 if (oa.op_type == OP_NOP && oa.regname == NUL && !VIsual_active)
4923 {
4924 /* If terminal_loop() returns OK we got a key that is handled
4925 * in Normal model. We don't do redrawing anyway. */
4926 if (terminal_loop(TRUE) == OK)
4927 normal_cmd(&oa, TRUE);
4928 }
4929 else
4930 normal_cmd(&oa, TRUE);
4931 }
Bram Moolenaarf9c38832018-06-19 19:59:20 +02004932 retval = job->jv_exitval;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004933 ch_log(NULL, "system command finished");
4934
Bram Moolenaarf9c38832018-06-19 19:59:20 +02004935 job_unref(job);
4936
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004937 /* restore curwin/curbuf and a few other things */
4938 aucmd_restbuf(&aco);
4939
4940 wait_return(TRUE);
4941 do_buffer(DOBUF_WIPE, DOBUF_FIRST, FORWARD, buf->b_fnum, TRUE);
4942
4943 vim_free(newcmd);
4944 return retval;
4945}
4946#endif
4947
Bram Moolenaar071d4272004-06-13 20:20:40 +00004948/*
4949 * Either execute a command by calling the shell or start a new shell
4950 */
4951 int
4952mch_call_shell(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004953 char_u *cmd,
4954 int options) /* SHELL_*, see vim.h */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004955{
4956 int x = 0;
4957 int tmode = cur_tmode;
4958#ifdef FEAT_TITLE
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004959 char szShellTitle[512];
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004960# ifdef FEAT_MBYTE
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004961 int did_set_title = FALSE;
4962
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004963 /* Change the title to reflect that we are in a subshell. */
4964 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4965 {
4966 WCHAR szShellTitle[512];
4967
4968 if (GetConsoleTitleW(szShellTitle,
4969 sizeof(szShellTitle)/sizeof(WCHAR) - 4) > 0)
4970 {
4971 if (cmd == NULL)
4972 wcscat(szShellTitle, L" :sh");
4973 else
4974 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004975 WCHAR *wn = enc_to_utf16((char_u *)cmd, NULL);
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004976
4977 if (wn != NULL)
4978 {
4979 wcscat(szShellTitle, L" - !");
4980 if ((wcslen(szShellTitle) + wcslen(wn) <
4981 sizeof(szShellTitle)/sizeof(WCHAR)))
4982 wcscat(szShellTitle, wn);
4983 SetConsoleTitleW(szShellTitle);
4984 vim_free(wn);
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004985 did_set_title = TRUE;
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004986 }
4987 }
4988 }
4989 }
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004990 if (!did_set_title)
4991# endif
4992 /* Change the title to reflect that we are in a subshell. */
4993 if (GetConsoleTitle(szShellTitle, sizeof(szShellTitle) - 4) > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004994 {
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004995 if (cmd == NULL)
4996 strcat(szShellTitle, " :sh");
4997 else
4998 {
4999 strcat(szShellTitle, " - !");
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01005000 if ((strlen(szShellTitle) + strlen((char *)cmd)
5001 < sizeof(szShellTitle)))
5002 strcat(szShellTitle, (char *)cmd);
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02005003 }
5004 SetConsoleTitle(szShellTitle);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005005 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005006#endif
5007
5008 out_flush();
5009
5010#ifdef MCH_WRITE_DUMP
5011 if (fdDump)
5012 {
5013 fprintf(fdDump, "mch_call_shell(\"%s\", %d)\n", cmd, options);
5014 fflush(fdDump);
5015 }
5016#endif
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005017#if defined(FEAT_GUI) && defined(FEAT_TERMINAL)
5018 /* TODO: make the terminal window work with input or output redirected. */
5019 if (vim_strchr(p_go, GO_TERMINAL) != NULL
5020 && (options & (SHELL_FILTER|SHELL_DOOUT|SHELL_WRITE|SHELL_READ)) == 0)
5021 {
5022 /* Use a terminal window to run the command in. */
5023 x = mch_call_shell_terminal(cmd, options);
5024#ifdef FEAT_TITLE
5025 resettitle();
5026#endif
5027 return x;
5028 }
5029#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005030
5031 /*
5032 * Catch all deadly signals while running the external command, because a
5033 * CTRL-C, Ctrl-Break or illegal instruction might otherwise kill us.
5034 */
5035 signal(SIGINT, SIG_IGN);
5036#if defined(__GNUC__) && !defined(__MINGW32__)
5037 signal(SIGKILL, SIG_IGN);
5038#else
5039 signal(SIGBREAK, SIG_IGN);
5040#endif
5041 signal(SIGILL, SIG_IGN);
5042 signal(SIGFPE, SIG_IGN);
5043 signal(SIGSEGV, SIG_IGN);
5044 signal(SIGTERM, SIG_IGN);
5045 signal(SIGABRT, SIG_IGN);
5046
5047 if (options & SHELL_COOKED)
5048 settmode(TMODE_COOK); /* set to normal mode */
5049
5050 if (cmd == NULL)
5051 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01005052 x = mch_system((char *)p_sh, options);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005053 }
5054 else
5055 {
5056 /* we use "command" or "cmd" to start the shell; slow but easy */
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005057 char_u *newcmd = NULL;
5058 char_u *cmdbase = cmd;
5059 long_u cmdlen;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005060
5061 /* Skip a leading ", ( and "(. */
5062 if (*cmdbase == '"' )
5063 ++cmdbase;
5064 if (*cmdbase == '(')
5065 ++cmdbase;
5066
Bram Moolenaar1c465442017-03-12 20:10:05 +01005067 if ((STRNICMP(cmdbase, "start", 5) == 0) && VIM_ISWHITE(cmdbase[5]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005068 {
5069 STARTUPINFO si;
5070 PROCESS_INFORMATION pi;
5071 DWORD flags = CREATE_NEW_CONSOLE;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01005072 INT n_show_cmd = SW_SHOWNORMAL;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005073 char_u *p;
5074
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01005075 ZeroMemory(&si, sizeof(si));
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005076 si.cb = sizeof(si);
5077 si.lpReserved = NULL;
5078 si.lpDesktop = NULL;
5079 si.lpTitle = NULL;
5080 si.dwFlags = 0;
5081 si.cbReserved2 = 0;
5082 si.lpReserved2 = NULL;
5083
5084 cmdbase = skipwhite(cmdbase + 5);
5085 if ((STRNICMP(cmdbase, "/min", 4) == 0)
Bram Moolenaar1c465442017-03-12 20:10:05 +01005086 && VIM_ISWHITE(cmdbase[4]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005087 {
5088 cmdbase = skipwhite(cmdbase + 4);
5089 si.dwFlags = STARTF_USESHOWWINDOW;
5090 si.wShowWindow = SW_SHOWMINNOACTIVE;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01005091 n_show_cmd = SW_SHOWMINNOACTIVE;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005092 }
5093 else if ((STRNICMP(cmdbase, "/b", 2) == 0)
Bram Moolenaar1c465442017-03-12 20:10:05 +01005094 && VIM_ISWHITE(cmdbase[2]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005095 {
5096 cmdbase = skipwhite(cmdbase + 2);
5097 flags = CREATE_NO_WINDOW;
5098 si.dwFlags = STARTF_USESTDHANDLES;
5099 si.hStdInput = CreateFile("\\\\.\\NUL", // File name
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005100 GENERIC_READ, // Access flags
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005101 0, // Share flags
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005102 NULL, // Security att.
5103 OPEN_EXISTING, // Open flags
5104 FILE_ATTRIBUTE_NORMAL, // File att.
5105 NULL); // Temp file
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005106 si.hStdOutput = si.hStdInput;
5107 si.hStdError = si.hStdInput;
5108 }
5109
5110 /* Remove a trailing ", ) and )" if they have a match
5111 * at the start of the command. */
5112 if (cmdbase > cmd)
5113 {
5114 p = cmdbase + STRLEN(cmdbase);
5115 if (p > cmdbase && p[-1] == '"' && *cmd == '"')
5116 *--p = NUL;
5117 if (p > cmdbase && p[-1] == ')'
5118 && (*cmd =='(' || cmd[1] == '('))
5119 *--p = NUL;
5120 }
5121
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005122 newcmd = cmdbase;
5123 unescape_shellxquote(cmdbase, p_sxe);
5124
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005125 /*
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005126 * If creating new console, arguments are passed to the
5127 * 'cmd.exe' as-is. If it's not, arguments are not treated
5128 * correctly for current 'cmd.exe'. So unescape characters in
5129 * shellxescape except '|' for avoiding to be treated as
5130 * argument to them. Pass the arguments to sub-shell.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005131 */
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005132 if (flags != CREATE_NEW_CONSOLE)
5133 {
5134 char_u *subcmd;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01005135 char_u *cmd_shell = mch_getenv("COMSPEC");
5136
5137 if (cmd_shell == NULL || *cmd_shell == NUL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01005138 cmd_shell = (char_u *)default_shell();
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005139
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01005140 subcmd = vim_strsave_escaped_ext(cmdbase,
5141 (char_u *)"|", '^', FALSE);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005142 if (subcmd != NULL)
5143 {
5144 /* make "cmd.exe /c arguments" */
5145 cmdlen = STRLEN(cmd_shell) + STRLEN(subcmd) + 5;
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005146 newcmd = lalloc(cmdlen, TRUE);
5147 if (newcmd != NULL)
5148 vim_snprintf((char *)newcmd, cmdlen, "%s /c %s",
Bram Moolenaaree7d1002012-02-22 15:34:08 +01005149 cmd_shell, subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005150 else
5151 newcmd = cmdbase;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01005152 vim_free(subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005153 }
5154 }
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005155
5156 /*
5157 * Now, start the command as a process, so that it doesn't
5158 * inherit our handles which causes unpleasant dangling swap
5159 * files if we exit before the spawned process
5160 */
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005161 if (vim_create_process((char *)newcmd, FALSE, flags,
5162 &si, &pi, NULL, NULL))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005163 x = 0;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01005164 else if (vim_shell_execute((char *)newcmd, n_show_cmd)
5165 > (HINSTANCE)32)
5166 x = 0;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005167 else
5168 {
5169 x = -1;
5170#ifdef FEAT_GUI_W32
5171 EMSG(_("E371: Command not found"));
5172#endif
5173 }
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005174
5175 if (newcmd != cmdbase)
5176 vim_free(newcmd);
5177
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01005178 if (si.dwFlags == STARTF_USESTDHANDLES && si.hStdInput != NULL)
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005179 {
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01005180 /* Close the handle to \\.\NUL created above. */
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005181 CloseHandle(si.hStdInput);
5182 }
5183 /* Close the handles to the subprocess, so that it goes away */
5184 CloseHandle(pi.hThread);
5185 CloseHandle(pi.hProcess);
5186 }
5187 else
5188 {
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005189 cmdlen = (
Bram Moolenaar071d4272004-06-13 20:20:40 +00005190#ifdef FEAT_GUI_W32
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005191 (!p_stmp ? 0 : STRLEN(vimrun_path)) +
Bram Moolenaar071d4272004-06-13 20:20:40 +00005192#endif
Bram Moolenaar0fde2902008-03-16 13:54:13 +00005193 STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10);
5194
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005195 newcmd = lalloc(cmdlen, TRUE);
5196 if (newcmd != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005197 {
5198#if defined(FEAT_GUI_W32)
5199 if (need_vimrun_warning)
5200 {
Bram Moolenaar63e43442016-11-19 17:28:44 +01005201 char *msg = _("VIMRUN.EXE not found in your $PATH.\n"
5202 "External commands will not pause after completion.\n"
5203 "See :help win32-vimrun for more information.");
5204 char *title = _("Vim Warning");
5205# ifdef FEAT_MBYTE
5206 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
5207 {
5208 WCHAR *wmsg = enc_to_utf16((char_u *)msg, NULL);
5209 WCHAR *wtitle = enc_to_utf16((char_u *)title, NULL);
5210
5211 if (wmsg != NULL && wtitle != NULL)
5212 MessageBoxW(NULL, wmsg, wtitle, MB_ICONWARNING);
5213 vim_free(wmsg);
5214 vim_free(wtitle);
5215 }
5216 else
5217# endif
5218 MessageBox(NULL, msg, title, MB_ICONWARNING);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005219 need_vimrun_warning = FALSE;
5220 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005221 if (!s_dont_use_vimrun && p_stmp)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005222 /* Use vimrun to execute the command. It opens a console
5223 * window, which can be closed without killing Vim. */
Bram Moolenaarcc448b32010-07-14 16:52:17 +02005224 vim_snprintf((char *)newcmd, cmdlen, "%s%s%s %s %s",
Bram Moolenaar071d4272004-06-13 20:20:40 +00005225 vimrun_path,
5226 (msg_silent != 0 || (options & SHELL_DOOUT))
5227 ? "-s " : "",
5228 p_sh, p_shcf, cmd);
5229 else
5230#endif
Bram Moolenaarcc448b32010-07-14 16:52:17 +02005231 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s",
Bram Moolenaar0fde2902008-03-16 13:54:13 +00005232 p_sh, p_shcf, cmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005233 x = mch_system((char *)newcmd, options);
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005234 vim_free(newcmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005235 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005236 }
5237 }
5238
5239 if (tmode == TMODE_RAW)
5240 settmode(TMODE_RAW); /* set to raw mode */
5241
5242 /* Print the return value, unless "vimrun" was used. */
5243 if (x != 0 && !(options & SHELL_SILENT) && !emsg_silent
5244#if defined(FEAT_GUI_W32)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005245 && ((options & SHELL_DOOUT) || s_dont_use_vimrun || !p_stmp)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005246#endif
5247 )
5248 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01005249 smsg((char_u *)_("shell returned %d"), x);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005250 msg_putchar('\n');
5251 }
5252#ifdef FEAT_TITLE
5253 resettitle();
5254#endif
5255
5256 signal(SIGINT, SIG_DFL);
5257#if defined(__GNUC__) && !defined(__MINGW32__)
5258 signal(SIGKILL, SIG_DFL);
5259#else
5260 signal(SIGBREAK, SIG_DFL);
5261#endif
5262 signal(SIGILL, SIG_DFL);
5263 signal(SIGFPE, SIG_DFL);
5264 signal(SIGSEGV, SIG_DFL);
5265 signal(SIGTERM, SIG_DFL);
5266 signal(SIGABRT, SIG_DFL);
5267
5268 return x;
5269}
5270
Bram Moolenaar509ce2a2016-03-11 22:52:15 +01005271#if defined(FEAT_JOB_CHANNEL) || defined(PROTO)
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005272 static HANDLE
5273job_io_file_open(
Bram Moolenaar972c3b82017-01-12 21:44:49 +01005274 char_u *fname,
5275 DWORD dwDesiredAccess,
5276 DWORD dwShareMode,
5277 LPSECURITY_ATTRIBUTES lpSecurityAttributes,
5278 DWORD dwCreationDisposition,
5279 DWORD dwFlagsAndAttributes)
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005280{
5281 HANDLE h;
5282# ifdef FEAT_MBYTE
5283 WCHAR *wn = NULL;
5284 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
5285 {
Bram Moolenaar972c3b82017-01-12 21:44:49 +01005286 wn = enc_to_utf16(fname, NULL);
5287 if (wn != NULL)
5288 {
5289 h = CreateFileW(wn, dwDesiredAccess, dwShareMode,
5290 lpSecurityAttributes, dwCreationDisposition,
5291 dwFlagsAndAttributes, NULL);
5292 vim_free(wn);
5293 }
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005294 }
5295 if (wn == NULL)
5296# endif
Bram Moolenaar972c3b82017-01-12 21:44:49 +01005297 h = CreateFile((LPCSTR)fname, dwDesiredAccess, dwShareMode,
5298 lpSecurityAttributes, dwCreationDisposition,
5299 dwFlagsAndAttributes, NULL);
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005300 return h;
5301}
5302
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005303/*
5304 * Turn the dictionary "env" into a NUL separated list that can be used as the
5305 * environment argument of vim_create_process().
5306 */
Bram Moolenaarba6febd2017-10-30 21:56:23 +01005307 void
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005308win32_build_env(dict_T *env, garray_T *gap, int is_terminal)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005309{
5310 hashitem_T *hi;
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005311 long_u todo = env != NULL ? env->dv_hashtab.ht_used : 0;
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005312 LPVOID base = GetEnvironmentStringsW();
5313
5314 /* for last \0 */
5315 if (ga_grow(gap, 1) == FAIL)
5316 return;
5317
5318 if (base)
5319 {
5320 WCHAR *p = (WCHAR*) base;
5321
5322 /* for last \0 */
5323 if (ga_grow(gap, 1) == FAIL)
5324 return;
5325
5326 while (*p != 0 || *(p + 1) != 0)
5327 {
5328 if (ga_grow(gap, 1) == OK)
5329 *((WCHAR*)gap->ga_data + gap->ga_len++) = *p;
5330 p++;
5331 }
5332 FreeEnvironmentStrings(base);
5333 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5334 }
5335
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005336 if (env != NULL)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005337 {
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005338 for (hi = env->dv_hashtab.ht_array; todo > 0; ++hi)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005339 {
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005340 if (!HASHITEM_EMPTY(hi))
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005341 {
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005342 typval_T *item = &dict_lookup(hi)->di_tv;
5343 WCHAR *wkey = enc_to_utf16((char_u *)hi->hi_key, NULL);
5344 WCHAR *wval = enc_to_utf16(get_tv_string(item), NULL);
5345 --todo;
5346 if (wkey != NULL && wval != NULL)
5347 {
5348 size_t n;
5349 size_t lkey = wcslen(wkey);
5350 size_t lval = wcslen(wval);
Bram Moolenaar60104f12017-08-14 23:25:04 +02005351
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005352 if (ga_grow(gap, (int)(lkey + lval + 2)) != OK)
5353 continue;
5354 for (n = 0; n < lkey; n++)
5355 *((WCHAR*)gap->ga_data + gap->ga_len++) = wkey[n];
5356 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'=';
5357 for (n = 0; n < lval; n++)
5358 *((WCHAR*)gap->ga_data + gap->ga_len++) = wval[n];
5359 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5360 }
5361 if (wkey != NULL) vim_free(wkey);
5362 if (wval != NULL) vim_free(wval);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005363 }
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005364 }
5365 }
5366
Bram Moolenaar493359e2018-06-12 20:25:52 +02005367# if defined(FEAT_CLIENTSERVER) || defined(FEAT_TERMINAL)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005368 {
Bram Moolenaar493359e2018-06-12 20:25:52 +02005369# ifdef FEAT_CLIENTSERVER
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005370 char_u *servername = get_vim_var_str(VV_SEND_SERVER);
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005371 size_t servername_len = STRLEN(servername);
Bram Moolenaar493359e2018-06-12 20:25:52 +02005372# endif
5373# ifdef FEAT_TERMINAL
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005374 char_u *version = get_vim_var_str(VV_VERSION);
5375 size_t version_len = STRLEN(version);
Bram Moolenaar493359e2018-06-12 20:25:52 +02005376# endif
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005377 // size of "VIM_SERVERNAME=" and value,
5378 // plus "VIM_TERMINAL=" and value,
5379 // plus two terminating NULs
5380 size_t n = 0
Bram Moolenaar493359e2018-06-12 20:25:52 +02005381# ifdef FEAT_CLIENTSERVER
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005382 + 15 + servername_len
Bram Moolenaar493359e2018-06-12 20:25:52 +02005383# endif
5384# ifdef FEAT_TERMINAL
5385 + 13 + version_len + 2
5386# endif
5387 ;
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005388
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005389 if (ga_grow(gap, (int)n) == OK)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005390 {
Bram Moolenaar493359e2018-06-12 20:25:52 +02005391# ifdef FEAT_CLIENTSERVER
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005392 for (n = 0; n < 15; n++)
5393 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5394 (WCHAR)"VIM_SERVERNAME="[n];
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005395 for (n = 0; n < servername_len; n++)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005396 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5397 (WCHAR)servername[n];
5398 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
Bram Moolenaar493359e2018-06-12 20:25:52 +02005399# endif
5400# ifdef FEAT_TERMINAL
5401 if (is_terminal)
5402 {
5403 for (n = 0; n < 13; n++)
5404 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5405 (WCHAR)"VIM_TERMINAL="[n];
5406 for (n = 0; n < version_len; n++)
5407 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5408 (WCHAR)version[n];
5409 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5410 }
5411# endif
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005412 }
5413 }
Bram Moolenaar79c6b512018-06-12 21:11:12 +02005414# endif
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005415}
5416
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005417 void
Bram Moolenaar5a1feb82017-07-22 18:04:08 +02005418mch_job_start(char *cmd, job_T *job, jobopt_T *options)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005419{
5420 STARTUPINFO si;
5421 PROCESS_INFORMATION pi;
Bram Moolenaar14207f42016-10-27 21:13:10 +02005422 HANDLE jo;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005423 SECURITY_ATTRIBUTES saAttr;
5424 channel_T *channel = NULL;
Bram Moolenaard8070362016-02-15 21:56:54 +01005425 HANDLE ifd[2];
5426 HANDLE ofd[2];
5427 HANDLE efd[2];
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005428 garray_T ga;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005429
5430 int use_null_for_in = options->jo_io[PART_IN] == JIO_NULL;
5431 int use_null_for_out = options->jo_io[PART_OUT] == JIO_NULL;
5432 int use_null_for_err = options->jo_io[PART_ERR] == JIO_NULL;
5433 int use_file_for_in = options->jo_io[PART_IN] == JIO_FILE;
5434 int use_file_for_out = options->jo_io[PART_OUT] == JIO_FILE;
5435 int use_file_for_err = options->jo_io[PART_ERR] == JIO_FILE;
5436 int use_out_for_err = options->jo_io[PART_ERR] == JIO_OUT;
5437
5438 if (use_out_for_err && use_null_for_out)
5439 use_null_for_err = TRUE;
Bram Moolenaard8070362016-02-15 21:56:54 +01005440
5441 ifd[0] = INVALID_HANDLE_VALUE;
5442 ifd[1] = INVALID_HANDLE_VALUE;
5443 ofd[0] = INVALID_HANDLE_VALUE;
5444 ofd[1] = INVALID_HANDLE_VALUE;
5445 efd[0] = INVALID_HANDLE_VALUE;
5446 efd[1] = INVALID_HANDLE_VALUE;
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005447 ga_init2(&ga, (int)sizeof(wchar_t), 500);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005448
Bram Moolenaar14207f42016-10-27 21:13:10 +02005449 jo = CreateJobObject(NULL, NULL);
5450 if (jo == NULL)
5451 {
5452 job->jv_status = JOB_FAILED;
5453 goto failed;
5454 }
5455
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005456 if (options->jo_env != NULL)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005457 win32_build_env(options->jo_env, &ga, FALSE);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005458
Bram Moolenaar76467df2016-02-12 19:30:26 +01005459 ZeroMemory(&pi, sizeof(pi));
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005460 ZeroMemory(&si, sizeof(si));
5461 si.cb = sizeof(si);
Bram Moolenaard8070362016-02-15 21:56:54 +01005462 si.dwFlags |= STARTF_USESHOWWINDOW;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005463 si.wShowWindow = SW_HIDE;
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005464
Bram Moolenaard8070362016-02-15 21:56:54 +01005465 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
5466 saAttr.bInheritHandle = TRUE;
5467 saAttr.lpSecurityDescriptor = NULL;
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005468
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005469 if (use_file_for_in)
5470 {
5471 char_u *fname = options->jo_io_name[PART_IN];
5472
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005473 ifd[0] = job_io_file_open(fname, GENERIC_READ,
5474 FILE_SHARE_READ | FILE_SHARE_WRITE,
5475 &saAttr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL);
5476 if (ifd[0] == INVALID_HANDLE_VALUE)
Bram Moolenaar94d01912016-03-08 13:48:51 +01005477 {
5478 EMSG2(_(e_notopen), fname);
5479 goto failed;
5480 }
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005481 }
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005482 else if (!use_null_for_in &&
5483 (!CreatePipe(&ifd[0], &ifd[1], &saAttr, 0)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005484 || !SetHandleInformation(ifd[1], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005485 goto failed;
5486
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005487 if (use_file_for_out)
5488 {
5489 char_u *fname = options->jo_io_name[PART_OUT];
5490
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005491 ofd[1] = job_io_file_open(fname, GENERIC_WRITE,
5492 FILE_SHARE_READ | FILE_SHARE_WRITE,
5493 &saAttr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL);
5494 if (ofd[1] == INVALID_HANDLE_VALUE)
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005495 {
5496 EMSG2(_(e_notopen), fname);
5497 goto failed;
5498 }
5499 }
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005500 else if (!use_null_for_out &&
5501 (!CreatePipe(&ofd[0], &ofd[1], &saAttr, 0)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005502 || !SetHandleInformation(ofd[0], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005503 goto failed;
5504
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005505 if (use_file_for_err)
5506 {
5507 char_u *fname = options->jo_io_name[PART_ERR];
5508
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005509 efd[1] = job_io_file_open(fname, GENERIC_WRITE,
5510 FILE_SHARE_READ | FILE_SHARE_WRITE,
5511 &saAttr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL);
5512 if (efd[1] == INVALID_HANDLE_VALUE)
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005513 {
5514 EMSG2(_(e_notopen), fname);
5515 goto failed;
5516 }
5517 }
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005518 else if (!use_out_for_err && !use_null_for_err &&
5519 (!CreatePipe(&efd[0], &efd[1], &saAttr, 0)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005520 || !SetHandleInformation(efd[0], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaard8070362016-02-15 21:56:54 +01005521 goto failed;
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005522
Bram Moolenaard8070362016-02-15 21:56:54 +01005523 si.dwFlags |= STARTF_USESTDHANDLES;
5524 si.hStdInput = ifd[0];
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005525 si.hStdOutput = ofd[1];
5526 si.hStdError = use_out_for_err ? ofd[1] : efd[1];
5527
5528 if (!use_null_for_in || !use_null_for_out || !use_null_for_err)
5529 {
Bram Moolenaarde279892016-03-11 22:19:44 +01005530 if (options->jo_set & JO_CHANNEL)
5531 {
5532 channel = options->jo_channel;
5533 if (channel != NULL)
5534 ++channel->ch_refcount;
5535 }
5536 else
5537 channel = add_channel();
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005538 if (channel == NULL)
5539 goto failed;
5540 }
Bram Moolenaard8070362016-02-15 21:56:54 +01005541
5542 if (!vim_create_process(cmd, TRUE,
Bram Moolenaar14207f42016-10-27 21:13:10 +02005543 CREATE_SUSPENDED |
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005544 CREATE_DEFAULT_ERROR_MODE |
5545 CREATE_NEW_PROCESS_GROUP |
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005546 CREATE_UNICODE_ENVIRONMENT |
Bram Moolenaar76467df2016-02-12 19:30:26 +01005547 CREATE_NEW_CONSOLE,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005548 &si, &pi,
5549 ga.ga_data,
5550 (char *)options->jo_cwd))
Bram Moolenaar76467df2016-02-12 19:30:26 +01005551 {
Bram Moolenaar14207f42016-10-27 21:13:10 +02005552 CloseHandle(jo);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005553 job->jv_status = JOB_FAILED;
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005554 goto failed;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005555 }
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005556
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005557 ga_clear(&ga);
5558
Bram Moolenaar14207f42016-10-27 21:13:10 +02005559 if (!AssignProcessToJobObject(jo, pi.hProcess))
5560 {
5561 /* if failing, switch the way to terminate
5562 * process with TerminateProcess. */
5563 CloseHandle(jo);
5564 jo = NULL;
5565 }
5566 ResumeThread(pi.hThread);
Bram Moolenaar75578a32016-03-10 16:33:31 +01005567 CloseHandle(pi.hThread);
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005568 job->jv_proc_info = pi;
Bram Moolenaar14207f42016-10-27 21:13:10 +02005569 job->jv_job_object = jo;
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005570 job->jv_status = JOB_STARTED;
5571
Bram Moolenaar641ad6c2016-09-01 18:32:11 +02005572 CloseHandle(ifd[0]);
5573 CloseHandle(ofd[1]);
5574 if (!use_out_for_err && !use_null_for_err)
Bram Moolenaarc25558b2016-03-03 21:02:23 +01005575 CloseHandle(efd[1]);
Bram Moolenaard8070362016-02-15 21:56:54 +01005576
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005577 job->jv_channel = channel;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005578 if (channel != NULL)
5579 {
5580 channel_set_pipes(channel,
5581 use_file_for_in || use_null_for_in
5582 ? INVALID_FD : (sock_T)ifd[1],
5583 use_file_for_out || use_null_for_out
5584 ? INVALID_FD : (sock_T)ofd[0],
5585 use_out_for_err || use_file_for_err || use_null_for_err
5586 ? INVALID_FD : (sock_T)efd[0]);
5587 channel_set_job(channel, job, options);
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005588 }
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005589 return;
5590
5591failed:
Bram Moolenaard8070362016-02-15 21:56:54 +01005592 CloseHandle(ifd[0]);
5593 CloseHandle(ofd[0]);
5594 CloseHandle(efd[0]);
5595 CloseHandle(ifd[1]);
5596 CloseHandle(ofd[1]);
5597 CloseHandle(efd[1]);
Bram Moolenaarde279892016-03-11 22:19:44 +01005598 channel_unref(channel);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005599 ga_clear(&ga);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005600}
5601
5602 char *
5603mch_job_status(job_T *job)
5604{
5605 DWORD dwExitCode = 0;
5606
Bram Moolenaar76467df2016-02-12 19:30:26 +01005607 if (!GetExitCodeProcess(job->jv_proc_info.hProcess, &dwExitCode)
5608 || dwExitCode != STILL_ACTIVE)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005609 {
Bram Moolenaareab089d2016-02-21 19:32:02 +01005610 job->jv_exitval = (int)dwExitCode;
Bram Moolenaar7df915d2016-11-17 17:25:32 +01005611 if (job->jv_status < JOB_ENDED)
Bram Moolenaar97792de2016-10-15 18:36:49 +02005612 {
5613 ch_log(job->jv_channel, "Job ended");
5614 job->jv_status = JOB_ENDED;
5615 }
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005616 return "dead";
5617 }
5618 return "run";
5619}
5620
Bram Moolenaar97792de2016-10-15 18:36:49 +02005621 job_T *
5622mch_detect_ended_job(job_T *job_list)
5623{
5624 HANDLE jobHandles[MAXIMUM_WAIT_OBJECTS];
5625 job_T *jobArray[MAXIMUM_WAIT_OBJECTS];
5626 job_T *job = job_list;
5627
5628 while (job != NULL)
5629 {
5630 DWORD n;
5631 DWORD result;
5632
5633 for (n = 0; n < MAXIMUM_WAIT_OBJECTS
5634 && job != NULL; job = job->jv_next)
5635 {
5636 if (job->jv_status == JOB_STARTED)
5637 {
5638 jobHandles[n] = job->jv_proc_info.hProcess;
5639 jobArray[n] = job;
5640 ++n;
5641 }
5642 }
5643 if (n == 0)
5644 continue;
5645 result = WaitForMultipleObjects(n, jobHandles, FALSE, 0);
5646 if (result >= WAIT_OBJECT_0 && result < WAIT_OBJECT_0 + n)
5647 {
5648 job_T *wait_job = jobArray[result - WAIT_OBJECT_0];
5649
5650 if (STRCMP(mch_job_status(wait_job), "dead") == 0)
5651 return wait_job;
5652 }
5653 }
5654 return NULL;
5655}
5656
Bram Moolenaarfb630902016-10-29 14:55:00 +02005657 static BOOL
5658terminate_all(HANDLE process, int code)
5659{
5660 PROCESSENTRY32 pe;
5661 HANDLE h = INVALID_HANDLE_VALUE;
5662 DWORD pid = GetProcessId(process);
5663
5664 if (pid != 0)
5665 {
5666 h = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
5667 if (h != INVALID_HANDLE_VALUE)
5668 {
5669 pe.dwSize = sizeof(PROCESSENTRY32);
5670 if (!Process32First(h, &pe))
5671 goto theend;
5672
5673 do
5674 {
5675 if (pe.th32ParentProcessID == pid)
5676 {
5677 HANDLE ph = OpenProcess(
5678 PROCESS_ALL_ACCESS, FALSE, pe.th32ProcessID);
5679 if (ph != NULL)
5680 {
5681 terminate_all(ph, code);
5682 CloseHandle(ph);
5683 }
5684 }
5685 } while (Process32Next(h, &pe));
5686
5687 CloseHandle(h);
5688 }
5689 }
5690
5691theend:
5692 return TerminateProcess(process, code);
5693}
5694
5695/*
5696 * Send a (deadly) signal to "job".
5697 * Return FAIL if it didn't work.
5698 */
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005699 int
Bram Moolenaar2d33e902017-08-11 16:31:54 +02005700mch_signal_job(job_T *job, char_u *how)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005701{
Bram Moolenaar923d9262016-02-25 20:56:01 +01005702 int ret;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005703
Bram Moolenaar923d9262016-02-25 20:56:01 +01005704 if (STRCMP(how, "term") == 0 || STRCMP(how, "kill") == 0 || *how == NUL)
Bram Moolenaar76467df2016-02-12 19:30:26 +01005705 {
Bram Moolenaarfb630902016-10-29 14:55:00 +02005706 /* deadly signal */
Bram Moolenaar14207f42016-10-27 21:13:10 +02005707 if (job->jv_job_object != NULL)
5708 return TerminateJobObject(job->jv_job_object, 0) ? OK : FAIL;
Bram Moolenaarfb630902016-10-29 14:55:00 +02005709 return terminate_all(job->jv_proc_info.hProcess, 0) ? OK : FAIL;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005710 }
5711
5712 if (!AttachConsole(job->jv_proc_info.dwProcessId))
5713 return FAIL;
5714 ret = GenerateConsoleCtrlEvent(
Bram Moolenaar923d9262016-02-25 20:56:01 +01005715 STRCMP(how, "int") == 0 ? CTRL_C_EVENT : CTRL_BREAK_EVENT,
5716 job->jv_proc_info.dwProcessId)
5717 ? OK : FAIL;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005718 FreeConsole();
5719 return ret;
5720}
5721
5722/*
5723 * Clear the data related to "job".
5724 */
5725 void
5726mch_clear_job(job_T *job)
5727{
5728 if (job->jv_status != JOB_FAILED)
5729 {
Bram Moolenaar14207f42016-10-27 21:13:10 +02005730 if (job->jv_job_object != NULL)
5731 CloseHandle(job->jv_job_object);
Bram Moolenaar76467df2016-02-12 19:30:26 +01005732 CloseHandle(job->jv_proc_info.hProcess);
5733 }
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005734}
5735#endif
5736
Bram Moolenaar071d4272004-06-13 20:20:40 +00005737
5738#ifndef FEAT_GUI_W32
5739
5740/*
5741 * Start termcap mode
5742 */
5743 static void
5744termcap_mode_start(void)
5745{
5746 DWORD cmodein;
5747
5748 if (g_fTermcapMode)
5749 return;
5750
5751 SaveConsoleBuffer(&g_cbNonTermcap);
5752
5753 if (g_cbTermcap.IsValid)
5754 {
5755 /*
5756 * We've been in termcap mode before. Restore certain screen
5757 * characteristics, including the buffer size and the window
5758 * size. Since we will be redrawing the screen, we don't need
5759 * to restore the actual contents of the buffer.
5760 */
5761 RestoreConsoleBuffer(&g_cbTermcap, FALSE);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005762 reset_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005763 SetConsoleWindowInfo(g_hConOut, TRUE, &g_cbTermcap.Info.srWindow);
5764 Rows = g_cbTermcap.Info.dwSize.Y;
5765 Columns = g_cbTermcap.Info.dwSize.X;
5766 }
5767 else
5768 {
5769 /*
5770 * This is our first time entering termcap mode. Clear the console
5771 * screen buffer, and resize the buffer to match the current window
5772 * size. We will use this as the size of our editing environment.
5773 */
5774 ClearConsoleBuffer(g_attrCurrent);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005775 set_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005776 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
5777 }
5778
5779#ifdef FEAT_TITLE
5780 resettitle();
5781#endif
5782
5783 GetConsoleMode(g_hConIn, &cmodein);
5784#ifdef FEAT_MOUSE
5785 if (g_fMouseActive)
5786 cmodein |= ENABLE_MOUSE_INPUT;
5787 else
5788 cmodein &= ~ENABLE_MOUSE_INPUT;
5789#endif
5790 cmodein |= ENABLE_WINDOW_INPUT;
5791 SetConsoleMode(g_hConIn, cmodein);
5792
5793 redraw_later_clear();
5794 g_fTermcapMode = TRUE;
5795}
5796
5797
5798/*
5799 * End termcap mode
5800 */
5801 static void
5802termcap_mode_end(void)
5803{
5804 DWORD cmodein;
5805 ConsoleBuffer *cb;
5806 COORD coord;
5807 DWORD dwDummy;
5808
5809 if (!g_fTermcapMode)
5810 return;
5811
5812 SaveConsoleBuffer(&g_cbTermcap);
5813
5814 GetConsoleMode(g_hConIn, &cmodein);
5815 cmodein &= ~(ENABLE_MOUSE_INPUT | ENABLE_WINDOW_INPUT);
5816 SetConsoleMode(g_hConIn, cmodein);
5817
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01005818#ifdef FEAT_RESTORE_ORIG_SCREEN
5819 cb = exiting ? &g_cbOrig : &g_cbNonTermcap;
5820#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00005821 cb = &g_cbNonTermcap;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01005822#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005823 RestoreConsoleBuffer(cb, p_rs);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005824 reset_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005825 SetConsoleCursorInfo(g_hConOut, &g_cci);
5826
5827 if (p_rs || exiting)
5828 {
5829 /*
5830 * Clear anything that happens to be on the current line.
5831 */
5832 coord.X = 0;
5833 coord.Y = (SHORT) (p_rs ? cb->Info.dwCursorPosition.Y : (Rows - 1));
5834 FillConsoleOutputCharacter(g_hConOut, ' ',
5835 cb->Info.dwSize.X, coord, &dwDummy);
5836 /*
5837 * The following is just for aesthetics. If we are exiting without
5838 * restoring the screen, then we want to have a prompt string
5839 * appear at the bottom line. However, the command interpreter
5840 * seems to always advance the cursor one line before displaying
5841 * the prompt string, which causes the screen to scroll. To
5842 * counter this, move the cursor up one line before exiting.
5843 */
5844 if (exiting && !p_rs)
5845 coord.Y--;
5846 /*
5847 * Position the cursor at the leftmost column of the desired row.
5848 */
5849 SetConsoleCursorPosition(g_hConOut, coord);
5850 }
5851
5852 g_fTermcapMode = FALSE;
5853}
5854#endif /* FEAT_GUI_W32 */
5855
5856
5857#ifdef FEAT_GUI_W32
5858 void
5859mch_write(
Bram Moolenaar1266d672017-02-01 13:43:36 +01005860 char_u *s UNUSED,
5861 int len UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005862{
5863 /* never used */
5864}
5865
5866#else
5867
5868/*
5869 * clear `n' chars, starting from `coord'
5870 */
5871 static void
5872clear_chars(
5873 COORD coord,
5874 DWORD n)
5875{
5876 DWORD dwDummy;
5877
5878 FillConsoleOutputCharacter(g_hConOut, ' ', n, coord, &dwDummy);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005879
5880 if (!USE_VTP)
5881 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, n, coord, &dwDummy);
5882 else
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02005883 {
5884 set_console_color_rgb();
5885 gotoxy(coord.X + 1, coord.Y + 1);
5886 vtp_printf("\033[%dX", n);
5887 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005888}
5889
5890
5891/*
5892 * Clear the screen
5893 */
5894 static void
5895clear_screen(void)
5896{
5897 g_coord.X = g_coord.Y = 0;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005898
5899 if (!USE_VTP)
5900 clear_chars(g_coord, Rows * Columns);
5901 else
5902 {
5903 set_console_color_rgb();
5904 gotoxy(1, 1);
5905 vtp_printf("\033[2J");
5906 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005907}
5908
5909
5910/*
5911 * Clear to end of display
5912 */
5913 static void
5914clear_to_end_of_display(void)
5915{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005916 COORD save = g_coord;
5917
5918 if (!USE_VTP)
5919 clear_chars(g_coord, (Rows - g_coord.Y - 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005920 * Columns + (Columns - g_coord.X));
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005921 else
5922 {
5923 set_console_color_rgb();
5924 gotoxy(g_coord.X + 1, g_coord.Y + 1);
5925 vtp_printf("\033[0J");
5926
5927 gotoxy(save.X + 1, save.Y + 1);
5928 g_coord = save;
5929 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005930}
5931
5932
5933/*
5934 * Clear to end of line
5935 */
5936 static void
5937clear_to_end_of_line(void)
5938{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005939 COORD save = g_coord;
5940
5941 if (!USE_VTP)
5942 clear_chars(g_coord, Columns - g_coord.X);
5943 else
5944 {
5945 set_console_color_rgb();
5946 gotoxy(g_coord.X + 1, g_coord.Y + 1);
5947 vtp_printf("\033[0K");
5948
5949 gotoxy(save.X + 1, save.Y + 1);
5950 g_coord = save;
5951 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005952}
5953
5954
5955/*
5956 * Scroll the scroll region up by `cLines' lines
5957 */
5958 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005959scroll(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005960{
5961 COORD oldcoord = g_coord;
5962
5963 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
5964 delete_lines(cLines);
5965
5966 g_coord = oldcoord;
5967}
5968
5969
5970/*
5971 * Set the scroll region
5972 */
5973 static void
5974set_scroll_region(
5975 unsigned left,
5976 unsigned top,
5977 unsigned right,
5978 unsigned bottom)
5979{
5980 if (left >= right
5981 || top >= bottom
5982 || right > (unsigned) Columns - 1
5983 || bottom > (unsigned) Rows - 1)
5984 return;
5985
5986 g_srScrollRegion.Left = left;
5987 g_srScrollRegion.Top = top;
5988 g_srScrollRegion.Right = right;
5989 g_srScrollRegion.Bottom = bottom;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005990
5991 if (USE_VTP)
5992 vtp_printf("\033[%d;%dr", top + 1, bottom + 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005993}
5994
5995
5996/*
5997 * Insert `cLines' lines at the current cursor position
5998 */
5999 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006000insert_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006001{
6002 SMALL_RECT source;
6003 COORD dest;
6004 CHAR_INFO fill;
6005
6006 dest.X = 0;
6007 dest.Y = g_coord.Y + cLines;
6008
6009 source.Left = 0;
6010 source.Top = g_coord.Y;
6011 source.Right = g_srScrollRegion.Right;
6012 source.Bottom = g_srScrollRegion.Bottom - cLines;
6013
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006014 if (!USE_VTP)
6015 {
6016 fill.Char.AsciiChar = ' ';
6017 fill.Attributes = g_attrCurrent;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006018
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006019 ScrollConsoleScreenBuffer(g_hConOut, &source, NULL, dest, &fill);
6020 }
6021 else
6022 {
6023 set_console_color_rgb();
6024
6025 gotoxy(1, source.Top + 1);
6026 vtp_printf("\033[%dT", cLines);
6027 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006028
6029 /* Here we have to deal with a win32 console flake: If the scroll
6030 * region looks like abc and we scroll c to a and fill with d we get
6031 * cbd... if we scroll block c one line at a time to a, we get cdd...
6032 * vim expects cdd consistently... So we have to deal with that
6033 * here... (this also occurs scrolling the same way in the other
6034 * direction). */
6035
6036 if (source.Bottom < dest.Y)
6037 {
6038 COORD coord;
6039
6040 coord.X = 0;
6041 coord.Y = source.Bottom;
6042 clear_chars(coord, Columns * (dest.Y - source.Bottom));
6043 }
6044}
6045
6046
6047/*
6048 * Delete `cLines' lines at the current cursor position
6049 */
6050 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006051delete_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006052{
6053 SMALL_RECT source;
6054 COORD dest;
6055 CHAR_INFO fill;
6056 int nb;
6057
6058 dest.X = 0;
6059 dest.Y = g_coord.Y;
6060
6061 source.Left = 0;
6062 source.Top = g_coord.Y + cLines;
6063 source.Right = g_srScrollRegion.Right;
6064 source.Bottom = g_srScrollRegion.Bottom;
6065
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006066 if (!USE_VTP)
6067 {
6068 fill.Char.AsciiChar = ' ';
6069 fill.Attributes = g_attrCurrent;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006070
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006071 ScrollConsoleScreenBuffer(g_hConOut, &source, NULL, dest, &fill);
6072 }
6073 else
6074 {
6075 set_console_color_rgb();
6076
6077 gotoxy(1, source.Top + 1);
6078 vtp_printf("\033[%dS", cLines);
6079 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006080
6081 /* Here we have to deal with a win32 console flake: If the scroll
6082 * region looks like abc and we scroll c to a and fill with d we get
6083 * cbd... if we scroll block c one line at a time to a, we get cdd...
6084 * vim expects cdd consistently... So we have to deal with that
6085 * here... (this also occurs scrolling the same way in the other
6086 * direction). */
6087
6088 nb = dest.Y + (source.Bottom - source.Top) + 1;
6089
6090 if (nb < source.Top)
6091 {
6092 COORD coord;
6093
6094 coord.X = 0;
6095 coord.Y = nb;
6096 clear_chars(coord, Columns * (source.Top - nb));
6097 }
6098}
6099
6100
6101/*
6102 * Set the cursor position
6103 */
6104 static void
6105gotoxy(
6106 unsigned x,
6107 unsigned y)
6108{
6109 if (x < 1 || x > (unsigned)Columns || y < 1 || y > (unsigned)Rows)
6110 return;
6111
6112 /* external cursor coords are 1-based; internal are 0-based */
6113 g_coord.X = x - 1;
6114 g_coord.Y = y - 1;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006115
6116 if (!USE_VTP)
6117 SetConsoleCursorPosition(g_hConOut, g_coord);
6118 else
6119 vtp_printf("\033[%d;%dH", y, x);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006120}
6121
6122
6123/*
6124 * Set the current text attribute = (foreground | background)
6125 * See ../doc/os_win32.txt for the numbers.
6126 */
6127 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006128textattr(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006129{
Bram Moolenaar6383b922015-03-24 17:12:19 +01006130 g_attrCurrent = wAttr & 0xff;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006131
6132 SetConsoleTextAttribute(g_hConOut, wAttr);
6133}
6134
6135
6136 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006137textcolor(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006138{
Bram Moolenaar6383b922015-03-24 17:12:19 +01006139 g_attrCurrent = (g_attrCurrent & 0xf0) + (wAttr & 0x0f);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006140
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006141 if (!USE_VTP)
6142 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
6143 else
6144 vtp_sgr_bulk(wAttr);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006145}
6146
6147
6148 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006149textbackground(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006150{
Bram Moolenaar6383b922015-03-24 17:12:19 +01006151 g_attrCurrent = (g_attrCurrent & 0x0f) + ((wAttr & 0x0f) << 4);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006152
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006153 if (!USE_VTP)
6154 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
6155 else
6156 vtp_sgr_bulk(wAttr);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006157}
6158
6159
6160/*
6161 * restore the default text attribute (whatever we started with)
6162 */
6163 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006164normvideo(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006165{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006166 if (!USE_VTP)
6167 textattr(g_attrDefault);
6168 else
6169 vtp_sgr_bulk(0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006170}
6171
6172
6173static WORD g_attrPreStandout = 0;
6174
6175/*
6176 * Make the text standout, by brightening it
6177 */
6178 static void
6179standout(void)
6180{
6181 g_attrPreStandout = g_attrCurrent;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006182
Bram Moolenaar071d4272004-06-13 20:20:40 +00006183 textattr((WORD) (g_attrCurrent|FOREGROUND_INTENSITY|BACKGROUND_INTENSITY));
6184}
6185
6186
6187/*
6188 * Turn off standout mode
6189 */
6190 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006191standend(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006192{
6193 if (g_attrPreStandout)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006194 textattr(g_attrPreStandout);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006195
6196 g_attrPreStandout = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006197}
6198
6199
6200/*
Bram Moolenaarff1d0d42007-05-10 17:24:16 +00006201 * Set normal fg/bg color, based on T_ME. Called when t_me has been set.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006202 */
6203 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006204mch_set_normal_colors(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006205{
6206 char_u *p;
6207 int n;
6208
6209 cterm_normal_fg_color = (g_attrDefault & 0xf) + 1;
6210 cterm_normal_bg_color = ((g_attrDefault >> 4) & 0xf) + 1;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006211 if (
6212#ifdef FEAT_TERMGUICOLORS
6213 !p_tgc &&
6214#endif
6215 T_ME[0] == ESC && T_ME[1] == '|')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006216 {
6217 p = T_ME + 2;
6218 n = getdigits(&p);
6219 if (*p == 'm' && n > 0)
6220 {
6221 cterm_normal_fg_color = (n & 0xf) + 1;
6222 cterm_normal_bg_color = ((n >> 4) & 0xf) + 1;
6223 }
6224 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006225#ifdef FEAT_TERMGUICOLORS
6226 cterm_normal_fg_gui_color = INVALCOLOR;
6227 cterm_normal_bg_gui_color = INVALCOLOR;
6228#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006229}
6230
6231
6232/*
6233 * visual bell: flash the screen
6234 */
6235 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006236visual_bell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006237{
6238 COORD coordOrigin = {0, 0};
6239 WORD attrFlash = ~g_attrCurrent & 0xff;
6240
6241 DWORD dwDummy;
6242 LPWORD oldattrs = (LPWORD)alloc(Rows * Columns * sizeof(WORD));
6243
6244 if (oldattrs == NULL)
6245 return;
6246 ReadConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
6247 coordOrigin, &dwDummy);
6248 FillConsoleOutputAttribute(g_hConOut, attrFlash, Rows * Columns,
6249 coordOrigin, &dwDummy);
6250
6251 Sleep(15); /* wait for 15 msec */
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006252 if (!USE_VTP)
6253 WriteConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
Bram Moolenaar071d4272004-06-13 20:20:40 +00006254 coordOrigin, &dwDummy);
6255 vim_free(oldattrs);
6256}
6257
6258
6259/*
6260 * Make the cursor visible or invisible
6261 */
6262 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006263cursor_visible(BOOL fVisible)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006264{
6265 s_cursor_visible = fVisible;
6266#ifdef MCH_CURSOR_SHAPE
6267 mch_update_cursor();
6268#endif
6269}
6270
6271
6272/*
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02006273 * Write "cbToWrite" bytes in `pchBuf' to the screen.
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006274 * Returns the number of bytes actually written (at least one).
Bram Moolenaar071d4272004-06-13 20:20:40 +00006275 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006276 static DWORD
Bram Moolenaar071d4272004-06-13 20:20:40 +00006277write_chars(
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006278 char_u *pchBuf,
6279 DWORD cbToWrite)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006280{
6281 COORD coord = g_coord;
6282 DWORD written;
6283
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006284#ifdef FEAT_MBYTE
6285 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
6286 {
6287 static WCHAR *unicodebuf = NULL;
6288 static int unibuflen = 0;
6289 int length;
6290 DWORD n, cchwritten, cells;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006291
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006292 length = MultiByteToWideChar(CP_UTF8, 0, (LPCSTR)pchBuf, cbToWrite, 0, 0);
6293 if (unicodebuf == NULL || length > unibuflen)
6294 {
6295 vim_free(unicodebuf);
6296 unicodebuf = (WCHAR *)lalloc(length * sizeof(WCHAR), FALSE);
6297 unibuflen = length;
6298 }
6299 MultiByteToWideChar(CP_UTF8, 0, (LPCSTR)pchBuf, cbToWrite,
6300 unicodebuf, unibuflen);
6301
6302 cells = mb_string2cells(pchBuf, cbToWrite);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006303
6304 if (!USE_VTP)
6305 {
6306 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, cells,
6307 coord, &written);
6308 /* When writing fails or didn't write a single character, pretend one
6309 * character was written, otherwise we get stuck. */
6310 if (WriteConsoleOutputCharacterW(g_hConOut, unicodebuf, length,
6311 coord, &cchwritten) == 0
6312 || cchwritten == 0)
6313 cchwritten = 1;
6314 }
6315 else
6316 {
6317 if (WriteConsoleW(g_hConOut, unicodebuf, length, &cchwritten,
6318 NULL) == 0 || cchwritten == 0)
6319 cchwritten = 1;
6320 }
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006321
6322 if (cchwritten == length)
6323 {
6324 written = cbToWrite;
6325 g_coord.X += (SHORT)cells;
6326 }
6327 else
6328 {
6329 char_u *p = pchBuf;
6330 for (n = 0; n < cchwritten; n++)
Bram Moolenaar91acfff2017-03-12 19:22:36 +01006331 MB_CPTR_ADV(p);
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006332 written = p - pchBuf;
6333 g_coord.X += (SHORT)mb_string2cells(pchBuf, written);
6334 }
6335 }
6336 else
6337#endif
6338 {
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006339 if (!USE_VTP)
6340 {
6341 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, cbToWrite,
6342 coord, &written);
6343 /* When writing fails or didn't write a single character, pretend one
6344 * character was written, otherwise we get stuck. */
6345 if (WriteConsoleOutputCharacter(g_hConOut, (LPCSTR)pchBuf, cbToWrite,
6346 coord, &written) == 0
6347 || written == 0)
6348 written = 1;
6349 }
6350 else
6351 {
6352 if (WriteConsole(g_hConOut, (LPCSTR)pchBuf, cbToWrite, &written,
6353 NULL) == 0 || written == 0)
6354 written = 1;
6355 }
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006356
6357 g_coord.X += (SHORT) written;
6358 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006359
6360 while (g_coord.X > g_srScrollRegion.Right)
6361 {
6362 g_coord.X -= (SHORT) Columns;
6363 if (g_coord.Y < g_srScrollRegion.Bottom)
6364 g_coord.Y++;
6365 }
6366
6367 gotoxy(g_coord.X + 1, g_coord.Y + 1);
6368
6369 return written;
6370}
6371
6372
6373/*
6374 * mch_write(): write the output buffer to the screen, translating ESC
6375 * sequences into calls to console output routines.
6376 */
6377 void
6378mch_write(
6379 char_u *s,
6380 int len)
6381{
6382 s[len] = NUL;
6383
6384 if (!term_console)
6385 {
6386 write(1, s, (unsigned)len);
6387 return;
6388 }
6389
6390 /* translate ESC | sequences into faked bios calls */
6391 while (len--)
6392 {
6393 /* optimization: use one single write_chars for runs of text,
6394 * rather than once per character It ain't curses, but it helps. */
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006395 DWORD prefix = (DWORD)strcspn((char *)s, "\n\r\b\a\033");
Bram Moolenaar071d4272004-06-13 20:20:40 +00006396
6397 if (p_wd)
6398 {
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02006399 WaitForChar(p_wd, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006400 if (prefix != 0)
6401 prefix = 1;
6402 }
6403
6404 if (prefix != 0)
6405 {
6406 DWORD nWritten;
6407
6408 nWritten = write_chars(s, prefix);
6409#ifdef MCH_WRITE_DUMP
6410 if (fdDump)
6411 {
6412 fputc('>', fdDump);
6413 fwrite(s, sizeof(char_u), nWritten, fdDump);
6414 fputs("<\n", fdDump);
6415 }
6416#endif
6417 len -= (nWritten - 1);
6418 s += nWritten;
6419 }
6420 else if (s[0] == '\n')
6421 {
6422 /* \n, newline: go to the beginning of the next line or scroll */
6423 if (g_coord.Y == g_srScrollRegion.Bottom)
6424 {
6425 scroll(1);
6426 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Bottom + 1);
6427 }
6428 else
6429 {
6430 gotoxy(g_srScrollRegion.Left + 1, g_coord.Y + 2);
6431 }
6432#ifdef MCH_WRITE_DUMP
6433 if (fdDump)
6434 fputs("\\n\n", fdDump);
6435#endif
6436 s++;
6437 }
6438 else if (s[0] == '\r')
6439 {
6440 /* \r, carriage return: go to beginning of line */
6441 gotoxy(g_srScrollRegion.Left+1, g_coord.Y + 1);
6442#ifdef MCH_WRITE_DUMP
6443 if (fdDump)
6444 fputs("\\r\n", fdDump);
6445#endif
6446 s++;
6447 }
6448 else if (s[0] == '\b')
6449 {
6450 /* \b, backspace: move cursor one position left */
6451 if (g_coord.X > g_srScrollRegion.Left)
6452 g_coord.X--;
6453 else if (g_coord.Y > g_srScrollRegion.Top)
6454 {
6455 g_coord.X = g_srScrollRegion.Right;
6456 g_coord.Y--;
6457 }
6458 gotoxy(g_coord.X + 1, g_coord.Y + 1);
6459#ifdef MCH_WRITE_DUMP
6460 if (fdDump)
6461 fputs("\\b\n", fdDump);
6462#endif
6463 s++;
6464 }
6465 else if (s[0] == '\a')
6466 {
6467 /* \a, bell */
6468 MessageBeep(0xFFFFFFFF);
6469#ifdef MCH_WRITE_DUMP
6470 if (fdDump)
6471 fputs("\\a\n", fdDump);
6472#endif
6473 s++;
6474 }
6475 else if (s[0] == ESC && len >= 3-1 && s[1] == '|')
6476 {
6477#ifdef MCH_WRITE_DUMP
Bram Moolenaarc0197e22004-09-13 20:26:32 +00006478 char_u *old_s = s;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006479#endif
Bram Moolenaarc0197e22004-09-13 20:26:32 +00006480 char_u *p;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006481 int arg1 = 0, arg2 = 0, argc = 0, args[16];
Bram Moolenaar071d4272004-06-13 20:20:40 +00006482
6483 switch (s[2])
6484 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006485 case '0': case '1': case '2': case '3': case '4':
6486 case '5': case '6': case '7': case '8': case '9':
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006487 p = s + 1;
6488 do
6489 {
6490 ++p;
6491 args[argc] = getdigits(&p);
6492 argc += (argc < 15) ? 1 : 0;
6493 if (p > s + len)
6494 break;
6495 } while (*p == ';');
6496
Bram Moolenaar071d4272004-06-13 20:20:40 +00006497 if (p > s + len)
6498 break;
6499
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006500 arg1 = args[0];
6501 arg2 = args[1];
6502 if (*p == 'm')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006503 {
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006504 if (argc == 1 && args[0] == 0)
6505 normvideo();
6506 else if (argc == 1)
6507 {
6508 if (USE_VTP)
6509 textcolor((WORD) arg1);
6510 else
6511 textattr((WORD) arg1);
6512 }
6513 else if (USE_VTP)
6514 vtp_sgr_bulks(argc, args);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006515 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006516 else if (argc == 2 && *p == 'H')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006517 {
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006518 gotoxy(arg2, arg1);
6519 }
6520 else if (argc == 2 && *p == 'r')
6521 {
6522 set_scroll_region(0, arg1 - 1, Columns - 1, arg2 - 1);
6523 }
6524 else if (argc == 1 && *p == 'A')
6525 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006526 gotoxy(g_coord.X + 1,
6527 max(g_srScrollRegion.Top, g_coord.Y - arg1) + 1);
6528 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006529 else if (argc == 1 && *p == 'b')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006530 {
6531 textbackground((WORD) arg1);
6532 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006533 else if (argc == 1 && *p == 'C')
6534 {
6535 gotoxy(min(g_srScrollRegion.Right, g_coord.X + arg1) + 1,
6536 g_coord.Y + 1);
6537 }
6538 else if (argc == 1 && *p == 'f')
6539 {
6540 textcolor((WORD) arg1);
6541 }
6542 else if (argc == 1 && *p == 'H')
6543 {
6544 gotoxy(1, arg1);
6545 }
6546 else if (argc == 1 && *p == 'L')
6547 {
6548 insert_lines(arg1);
6549 }
6550 else if (argc == 1 && *p == 'M')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006551 {
6552 delete_lines(arg1);
6553 }
6554
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006555 len -= (int)(p - s);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006556 s = p + 1;
6557 break;
6558
Bram Moolenaar071d4272004-06-13 20:20:40 +00006559 case 'A':
Bram Moolenaar071d4272004-06-13 20:20:40 +00006560 gotoxy(g_coord.X + 1,
6561 max(g_srScrollRegion.Top, g_coord.Y - 1) + 1);
6562 goto got3;
6563
6564 case 'B':
6565 visual_bell();
6566 goto got3;
6567
6568 case 'C':
Bram Moolenaar071d4272004-06-13 20:20:40 +00006569 gotoxy(min(g_srScrollRegion.Right, g_coord.X + 1) + 1,
6570 g_coord.Y + 1);
6571 goto got3;
6572
6573 case 'E':
6574 termcap_mode_end();
6575 goto got3;
6576
6577 case 'F':
6578 standout();
6579 goto got3;
6580
6581 case 'f':
6582 standend();
6583 goto got3;
6584
6585 case 'H':
6586 gotoxy(1, 1);
6587 goto got3;
6588
6589 case 'j':
6590 clear_to_end_of_display();
6591 goto got3;
6592
6593 case 'J':
6594 clear_screen();
6595 goto got3;
6596
6597 case 'K':
6598 clear_to_end_of_line();
6599 goto got3;
6600
6601 case 'L':
6602 insert_lines(1);
6603 goto got3;
6604
6605 case 'M':
6606 delete_lines(1);
6607 goto got3;
6608
6609 case 'S':
6610 termcap_mode_start();
6611 goto got3;
6612
6613 case 'V':
6614 cursor_visible(TRUE);
6615 goto got3;
6616
6617 case 'v':
6618 cursor_visible(FALSE);
6619 goto got3;
6620
6621 got3:
6622 s += 3;
6623 len -= 2;
6624 }
6625
6626#ifdef MCH_WRITE_DUMP
6627 if (fdDump)
6628 {
6629 fputs("ESC | ", fdDump);
6630 fwrite(old_s + 2, sizeof(char_u), s - old_s - 2, fdDump);
6631 fputc('\n', fdDump);
6632 }
6633#endif
6634 }
6635 else
6636 {
6637 /* Write a single character */
6638 DWORD nWritten;
6639
6640 nWritten = write_chars(s, 1);
6641#ifdef MCH_WRITE_DUMP
6642 if (fdDump)
6643 {
6644 fputc('>', fdDump);
6645 fwrite(s, sizeof(char_u), nWritten, fdDump);
6646 fputs("<\n", fdDump);
6647 }
6648#endif
6649
6650 len -= (nWritten - 1);
6651 s += nWritten;
6652 }
6653 }
6654
6655#ifdef MCH_WRITE_DUMP
6656 if (fdDump)
6657 fflush(fdDump);
6658#endif
6659}
6660
6661#endif /* FEAT_GUI_W32 */
6662
6663
6664/*
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01006665 * Delay for "msec" milliseconds.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006666 */
6667 void
6668mch_delay(
6669 long msec,
Bram Moolenaar1266d672017-02-01 13:43:36 +01006670 int ignoreinput UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006671{
6672#ifdef FEAT_GUI_W32
6673 Sleep((int)msec); /* never wait for input */
Bram Moolenaar325b7a22004-07-05 15:58:32 +00006674#else /* Console */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006675 if (ignoreinput)
Bram Moolenaar325b7a22004-07-05 15:58:32 +00006676# ifdef FEAT_MZSCHEME
6677 if (mzthreads_allowed() && p_mzq > 0 && msec > p_mzq)
6678 {
6679 int towait = p_mzq;
6680
6681 /* if msec is large enough, wait by portions in p_mzq */
6682 while (msec > 0)
6683 {
6684 mzvim_check_threads();
6685 if (msec < towait)
6686 towait = msec;
6687 Sleep(towait);
6688 msec -= towait;
6689 }
6690 }
6691 else
6692# endif
6693 Sleep((int)msec);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006694 else
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02006695 WaitForChar(msec, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006696#endif
6697}
6698
6699
6700/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01006701 * This version of remove is not scared by a readonly (backup) file.
6702 * This can also remove a symbolic link like Unix.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006703 * Return 0 for success, -1 for failure.
6704 */
6705 int
6706mch_remove(char_u *name)
6707{
6708#ifdef FEAT_MBYTE
6709 WCHAR *wn = NULL;
6710 int n;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02006711#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006712
Bram Moolenaar203258c2016-01-17 22:15:16 +01006713 /*
6714 * On Windows, deleting a directory's symbolic link is done by
6715 * RemoveDirectory(): mch_rmdir. It seems unnatural, but it is fact.
6716 */
6717 if (mch_isdir(name) && mch_is_symbolic_link(name))
6718 return mch_rmdir(name);
6719
Bram Moolenaar12b559e2013-06-12 22:41:37 +02006720 win32_setattrs(name, FILE_ATTRIBUTE_NORMAL);
6721
6722#ifdef FEAT_MBYTE
Bram Moolenaar071d4272004-06-13 20:20:40 +00006723 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
6724 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006725 wn = enc_to_utf16(name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006726 if (wn != NULL)
6727 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006728 n = DeleteFileW(wn) ? 0 : -1;
6729 vim_free(wn);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006730 return n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006731 }
6732 }
6733#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006734 return DeleteFile((LPCSTR)name) ? 0 : -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006735}
6736
6737
6738/*
Bram Moolenaarb9c31e72016-09-29 15:18:57 +02006739 * Check for an "interrupt signal": CTRL-break or CTRL-C.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006740 */
6741 void
Bram Moolenaarb9c31e72016-09-29 15:18:57 +02006742mch_breakcheck(int force)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006743{
6744#ifndef FEAT_GUI_W32 /* never used */
6745 if (g_fCtrlCPressed || g_fCBrkPressed)
6746 {
Bram Moolenaar9698ad72017-08-12 14:52:15 +02006747 ctrl_break_was_pressed = g_fCBrkPressed;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006748 g_fCtrlCPressed = g_fCBrkPressed = FALSE;
6749 got_int = TRUE;
6750 }
6751#endif
6752}
6753
Bram Moolenaaree273972016-01-02 21:11:51 +01006754/* physical RAM to leave for the OS */
6755#define WINNT_RESERVE_BYTES (256*1024*1024)
Bram Moolenaaree273972016-01-02 21:11:51 +01006756
6757/*
6758 * How much main memory in KiB that can be used by VIM.
6759 */
Bram Moolenaaree273972016-01-02 21:11:51 +01006760 long_u
Bram Moolenaar1266d672017-02-01 13:43:36 +01006761mch_total_mem(int special UNUSED)
Bram Moolenaaree273972016-01-02 21:11:51 +01006762{
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006763 MEMORYSTATUSEX ms;
6764
Bram Moolenaaree273972016-01-02 21:11:51 +01006765 PlatformId();
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006766 /* Need to use GlobalMemoryStatusEx() when there is more memory than
6767 * what fits in 32 bits. But it's not always available. */
6768 ms.dwLength = sizeof(MEMORYSTATUSEX);
6769 GlobalMemoryStatusEx(&ms);
6770 if (ms.ullAvailVirtual < ms.ullTotalPhys)
Bram Moolenaaree273972016-01-02 21:11:51 +01006771 {
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006772 /* Process address space fits in physical RAM, use all of it. */
6773 return (long_u)(ms.ullAvailVirtual / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01006774 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006775 if (ms.ullTotalPhys <= WINNT_RESERVE_BYTES)
Bram Moolenaaree273972016-01-02 21:11:51 +01006776 {
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006777 /* Catch old NT box or perverse hardware setup. */
6778 return (long_u)((ms.ullTotalPhys / 2) / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01006779 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006780 /* Use physical RAM less reserve for OS + data. */
6781 return (long_u)((ms.ullTotalPhys - WINNT_RESERVE_BYTES) / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01006782}
Bram Moolenaar071d4272004-06-13 20:20:40 +00006783
Bram Moolenaar071d4272004-06-13 20:20:40 +00006784#ifdef FEAT_MBYTE
6785/*
6786 * Same code as below, but with wide functions and no comments.
6787 * Return 0 for success, non-zero for failure.
6788 */
6789 int
6790mch_wrename(WCHAR *wold, WCHAR *wnew)
6791{
6792 WCHAR *p;
6793 int i;
6794 WCHAR szTempFile[_MAX_PATH + 1];
6795 WCHAR szNewPath[_MAX_PATH + 1];
6796 HANDLE hf;
6797
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006798 p = wold;
6799 for (i = 0; wold[i] != NUL; ++i)
6800 if ((wold[i] == '/' || wold[i] == '\\' || wold[i] == ':')
6801 && wold[i + 1] != 0)
6802 p = wold + i + 1;
6803 if ((int)(wold + i - p) < 8 || p[6] != '~')
6804 return (MoveFileW(wold, wnew) == 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006805
6806 if (GetFullPathNameW(wnew, _MAX_PATH, szNewPath, &p) == 0 || p == NULL)
6807 return -1;
6808 *p = NUL;
6809
6810 if (GetTempFileNameW(szNewPath, L"VIM", 0, szTempFile) == 0)
6811 return -2;
6812
6813 if (!DeleteFileW(szTempFile))
6814 return -3;
6815
6816 if (!MoveFileW(wold, szTempFile))
6817 return -4;
6818
6819 if ((hf = CreateFileW(wold, GENERIC_WRITE, 0, NULL, CREATE_NEW,
6820 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
6821 return -5;
6822 if (!CloseHandle(hf))
6823 return -6;
6824
6825 if (!MoveFileW(szTempFile, wnew))
6826 {
6827 (void)MoveFileW(szTempFile, wold);
6828 return -7;
6829 }
6830
6831 DeleteFileW(szTempFile);
6832
6833 if (!DeleteFileW(wold))
6834 return -8;
6835
6836 return 0;
6837}
6838#endif
6839
6840
6841/*
6842 * mch_rename() works around a bug in rename (aka MoveFile) in
6843 * Windows 95: rename("foo.bar", "foo.bar~") will generate a
6844 * file whose short file name is "FOO.BAR" (its long file name will
6845 * be correct: "foo.bar~"). Because a file can be accessed by
6846 * either its SFN or its LFN, "foo.bar" has effectively been
6847 * renamed to "foo.bar", which is not at all what was wanted. This
6848 * seems to happen only when renaming files with three-character
6849 * extensions by appending a suffix that does not include ".".
6850 * Windows NT gets it right, however, with an SFN of "FOO~1.BAR".
6851 *
6852 * There is another problem, which isn't really a bug but isn't right either:
6853 * When renaming "abcdef~1.txt" to "abcdef~1.txt~", the short name can be
6854 * "abcdef~1.txt" again. This has been reported on Windows NT 4.0 with
6855 * service pack 6. Doesn't seem to happen on Windows 98.
6856 *
6857 * Like rename(), returns 0 upon success, non-zero upon failure.
6858 * Should probably set errno appropriately when errors occur.
6859 */
6860 int
6861mch_rename(
6862 const char *pszOldFile,
6863 const char *pszNewFile)
6864{
6865 char szTempFile[_MAX_PATH+1];
6866 char szNewPath[_MAX_PATH+1];
6867 char *pszFilePart;
6868 HANDLE hf;
6869#ifdef FEAT_MBYTE
6870 WCHAR *wold = NULL;
6871 WCHAR *wnew = NULL;
6872 int retval = -1;
6873
6874 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
6875 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006876 wold = enc_to_utf16((char_u *)pszOldFile, NULL);
6877 wnew = enc_to_utf16((char_u *)pszNewFile, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006878 if (wold != NULL && wnew != NULL)
6879 retval = mch_wrename(wold, wnew);
6880 vim_free(wold);
6881 vim_free(wnew);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006882 return retval;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006883 }
6884#endif
6885
6886 /*
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006887 * No need to play tricks unless the file name contains a "~" as the
6888 * seventh character.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006889 */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006890 pszFilePart = (char *)gettail((char_u *)pszOldFile);
6891 if (STRLEN(pszFilePart) < 8 || pszFilePart[6] != '~')
6892 return rename(pszOldFile, pszNewFile);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006893
6894 /* Get base path of new file name. Undocumented feature: If pszNewFile is
6895 * a directory, no error is returned and pszFilePart will be NULL. */
6896 if (GetFullPathName(pszNewFile, _MAX_PATH, szNewPath, &pszFilePart) == 0
6897 || pszFilePart == NULL)
6898 return -1;
6899 *pszFilePart = NUL;
6900
6901 /* Get (and create) a unique temporary file name in directory of new file */
6902 if (GetTempFileName(szNewPath, "VIM", 0, szTempFile) == 0)
6903 return -2;
6904
6905 /* blow the temp file away */
6906 if (!DeleteFile(szTempFile))
6907 return -3;
6908
6909 /* rename old file to the temp file */
6910 if (!MoveFile(pszOldFile, szTempFile))
6911 return -4;
6912
6913 /* now create an empty file called pszOldFile; this prevents the operating
6914 * system using pszOldFile as an alias (SFN) if we're renaming within the
6915 * same directory. For example, we're editing a file called
6916 * filename.asc.txt by its SFN, filena~1.txt. If we rename filena~1.txt
6917 * to filena~1.txt~ (i.e., we're making a backup while writing it), the
6918 * SFN for filena~1.txt~ will be filena~1.txt, by default, which will
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006919 * cause all sorts of problems later in buf_write(). So, we create an
6920 * empty file called filena~1.txt and the system will have to find some
6921 * other SFN for filena~1.txt~, such as filena~2.txt
Bram Moolenaar071d4272004-06-13 20:20:40 +00006922 */
6923 if ((hf = CreateFile(pszOldFile, GENERIC_WRITE, 0, NULL, CREATE_NEW,
6924 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
6925 return -5;
6926 if (!CloseHandle(hf))
6927 return -6;
6928
6929 /* rename the temp file to the new file */
6930 if (!MoveFile(szTempFile, pszNewFile))
6931 {
6932 /* Renaming failed. Rename the file back to its old name, so that it
6933 * looks like nothing happened. */
6934 (void)MoveFile(szTempFile, pszOldFile);
6935
6936 return -7;
6937 }
6938
6939 /* Seems to be left around on Novell filesystems */
6940 DeleteFile(szTempFile);
6941
6942 /* finally, remove the empty old file */
6943 if (!DeleteFile(pszOldFile))
6944 return -8;
6945
6946 return 0; /* success */
6947}
6948
6949/*
6950 * Get the default shell for the current hardware platform
6951 */
6952 char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006953default_shell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006954{
Bram Moolenaar071d4272004-06-13 20:20:40 +00006955 PlatformId();
6956
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006957 return "cmd.exe";
Bram Moolenaar071d4272004-06-13 20:20:40 +00006958}
6959
6960/*
6961 * mch_access() extends access() to do more detailed check on network drives.
6962 * Returns 0 if file "n" has access rights according to "p", -1 otherwise.
6963 */
6964 int
6965mch_access(char *n, int p)
6966{
6967 HANDLE hFile;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006968 int retval = -1; /* default: fail */
6969#ifdef FEAT_MBYTE
6970 WCHAR *wn = NULL;
6971
6972 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006973 wn = enc_to_utf16((char_u *)n, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006974#endif
6975
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006976 if (mch_isdir((char_u *)n))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006977 {
6978 char TempName[_MAX_PATH + 16] = "";
6979#ifdef FEAT_MBYTE
6980 WCHAR TempNameW[_MAX_PATH + 16] = L"";
6981#endif
6982
6983 if (p & R_OK)
6984 {
6985 /* Read check is performed by seeing if we can do a find file on
6986 * the directory for any file. */
6987#ifdef FEAT_MBYTE
6988 if (wn != NULL)
6989 {
6990 int i;
6991 WIN32_FIND_DATAW d;
6992
6993 for (i = 0; i < _MAX_PATH && wn[i] != 0; ++i)
6994 TempNameW[i] = wn[i];
6995 if (TempNameW[i - 1] != '\\' && TempNameW[i - 1] != '/')
6996 TempNameW[i++] = '\\';
6997 TempNameW[i++] = '*';
6998 TempNameW[i++] = 0;
6999
7000 hFile = FindFirstFileW(TempNameW, &d);
7001 if (hFile == INVALID_HANDLE_VALUE)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007002 goto getout;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007003 else
7004 (void)FindClose(hFile);
7005 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007006 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00007007#endif
7008 {
7009 char *pch;
7010 WIN32_FIND_DATA d;
7011
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01007012 vim_strncpy((char_u *)TempName, (char_u *)n, _MAX_PATH);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007013 pch = TempName + STRLEN(TempName) - 1;
7014 if (*pch != '\\' && *pch != '/')
7015 *++pch = '\\';
7016 *++pch = '*';
7017 *++pch = NUL;
7018
7019 hFile = FindFirstFile(TempName, &d);
7020 if (hFile == INVALID_HANDLE_VALUE)
7021 goto getout;
7022 (void)FindClose(hFile);
7023 }
7024 }
7025
7026 if (p & W_OK)
7027 {
7028 /* Trying to create a temporary file in the directory should catch
7029 * directories on read-only network shares. However, in
7030 * directories whose ACL allows writes but denies deletes will end
7031 * up keeping the temporary file :-(. */
7032#ifdef FEAT_MBYTE
7033 if (wn != NULL)
7034 {
7035 if (!GetTempFileNameW(wn, L"VIM", 0, TempNameW))
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007036 goto getout;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007037 else
7038 DeleteFileW(TempNameW);
7039 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007040 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00007041#endif
7042 {
7043 if (!GetTempFileName(n, "VIM", 0, TempName))
7044 goto getout;
7045 mch_remove((char_u *)TempName);
7046 }
7047 }
7048 }
7049 else
7050 {
Bram Moolenaar5aa98962018-05-06 17:09:38 +02007051 // Don't consider a file read-only if another process has opened it.
7052 DWORD share_mode = FILE_SHARE_READ | FILE_SHARE_WRITE;
7053
Bram Moolenaar071d4272004-06-13 20:20:40 +00007054 /* Trying to open the file for the required access does ACL, read-only
7055 * network share, and file attribute checks. */
Bram Moolenaar5aa98962018-05-06 17:09:38 +02007056 DWORD access_mode = ((p & W_OK) ? GENERIC_WRITE : 0)
7057 | ((p & R_OK) ? GENERIC_READ : 0);
7058
Bram Moolenaar071d4272004-06-13 20:20:40 +00007059#ifdef FEAT_MBYTE
7060 if (wn != NULL)
Bram Moolenaar5aa98962018-05-06 17:09:38 +02007061 hFile = CreateFileW(wn, access_mode, share_mode,
7062 NULL, OPEN_EXISTING, 0, NULL);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007063 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00007064#endif
Bram Moolenaar5aa98962018-05-06 17:09:38 +02007065 hFile = CreateFile(n, access_mode, share_mode,
7066 NULL, OPEN_EXISTING, 0, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007067 if (hFile == INVALID_HANDLE_VALUE)
7068 goto getout;
7069 CloseHandle(hFile);
7070 }
7071
7072 retval = 0; /* success */
7073getout:
7074#ifdef FEAT_MBYTE
7075 vim_free(wn);
7076#endif
7077 return retval;
7078}
7079
7080#if defined(FEAT_MBYTE) || defined(PROTO)
7081/*
Bram Moolenaar36f692d2008-11-20 16:10:17 +00007082 * Version of open() that may use UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007083 */
7084 int
Bram Moolenaarb6843a02017-08-02 22:07:12 +02007085mch_open(const char *name, int flags, int mode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007086{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00007087 /* _wopen() does not work with Borland C 5.5: creates a read-only file. */
7088# ifndef __BORLANDC__
Bram Moolenaar071d4272004-06-13 20:20:40 +00007089 WCHAR *wn;
7090 int f;
7091
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00007092 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007093 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01007094 wn = enc_to_utf16((char_u *)name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007095 if (wn != NULL)
7096 {
7097 f = _wopen(wn, flags, mode);
7098 vim_free(wn);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007099 return f;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007100 }
7101 }
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00007102# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007103
Bram Moolenaarf9e6c3b2014-11-05 18:36:03 +01007104 /* open() can open a file which name is longer than _MAX_PATH bytes
7105 * and shorter than _MAX_PATH characters successfully, but sometimes it
7106 * causes unexpected error in another part. We make it an error explicitly
7107 * here. */
7108 if (strlen(name) >= _MAX_PATH)
7109 return -1;
7110
Bram Moolenaar071d4272004-06-13 20:20:40 +00007111 return open(name, flags, mode);
7112}
7113
7114/*
Bram Moolenaar36f692d2008-11-20 16:10:17 +00007115 * Version of fopen() that may use UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007116 */
7117 FILE *
Bram Moolenaarb6843a02017-08-02 22:07:12 +02007118mch_fopen(const char *name, const char *mode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007119{
7120 WCHAR *wn, *wm;
7121 FILE *f = NULL;
7122
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007123 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007124 {
Bram Moolenaare6a91fd2008-07-24 18:51:11 +00007125# if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0fde2902008-03-16 13:54:13 +00007126 /* Work around an annoying assertion in the Microsoft debug CRT
7127 * when mode's text/binary setting doesn't match _get_fmode(). */
7128 char newMode = mode[strlen(mode) - 1];
7129 int oldMode = 0;
7130
7131 _get_fmode(&oldMode);
7132 if (newMode == 't')
7133 _set_fmode(_O_TEXT);
7134 else if (newMode == 'b')
7135 _set_fmode(_O_BINARY);
7136# endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01007137 wn = enc_to_utf16((char_u *)name, NULL);
7138 wm = enc_to_utf16((char_u *)mode, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007139 if (wn != NULL && wm != NULL)
7140 f = _wfopen(wn, wm);
7141 vim_free(wn);
7142 vim_free(wm);
Bram Moolenaar0fde2902008-03-16 13:54:13 +00007143
Bram Moolenaare6a91fd2008-07-24 18:51:11 +00007144# if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0fde2902008-03-16 13:54:13 +00007145 _set_fmode(oldMode);
7146# endif
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007147 return f;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007148 }
7149
Bram Moolenaarf9e6c3b2014-11-05 18:36:03 +01007150 /* fopen() can open a file which name is longer than _MAX_PATH bytes
7151 * and shorter than _MAX_PATH characters successfully, but sometimes it
7152 * causes unexpected error in another part. We make it an error explicitly
7153 * here. */
7154 if (strlen(name) >= _MAX_PATH)
7155 return NULL;
7156
Bram Moolenaar071d4272004-06-13 20:20:40 +00007157 return fopen(name, mode);
7158}
7159#endif
7160
7161#ifdef FEAT_MBYTE
7162/*
7163 * SUB STREAM (aka info stream) handling:
7164 *
7165 * NTFS can have sub streams for each file. Normal contents of file is
7166 * stored in the main stream, and extra contents (author information and
7167 * title and so on) can be stored in sub stream. After Windows 2000, user
7168 * can access and store those informations in sub streams via explorer's
7169 * property menuitem in right click menu. Those informations in sub streams
7170 * were lost when copying only the main stream. So we have to copy sub
7171 * streams.
7172 *
7173 * Incomplete explanation:
7174 * http://msdn.microsoft.com/library/en-us/dnw2k/html/ntfs5.asp
7175 * More useful info and an example:
7176 * http://www.sysinternals.com/ntw2k/source/misc.shtml#streams
7177 */
7178
7179/*
7180 * Copy info stream data "substream". Read from the file with BackupRead(sh)
7181 * and write to stream "substream" of file "to".
7182 * Errors are ignored.
7183 */
7184 static void
7185copy_substream(HANDLE sh, void *context, WCHAR *to, WCHAR *substream, long len)
7186{
7187 HANDLE hTo;
7188 WCHAR *to_name;
7189
7190 to_name = malloc((wcslen(to) + wcslen(substream) + 1) * sizeof(WCHAR));
7191 wcscpy(to_name, to);
7192 wcscat(to_name, substream);
7193
7194 hTo = CreateFileW(to_name, GENERIC_WRITE, 0, NULL, OPEN_ALWAYS,
7195 FILE_ATTRIBUTE_NORMAL, NULL);
7196 if (hTo != INVALID_HANDLE_VALUE)
7197 {
7198 long done;
7199 DWORD todo;
7200 DWORD readcnt, written;
7201 char buf[4096];
7202
7203 /* Copy block of bytes at a time. Abort when something goes wrong. */
7204 for (done = 0; done < len; done += written)
7205 {
7206 /* (size_t) cast for Borland C 5.5 */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007207 todo = (DWORD)((size_t)(len - done) > sizeof(buf) ? sizeof(buf)
7208 : (size_t)(len - done));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007209 if (!BackupRead(sh, (LPBYTE)buf, todo, &readcnt,
7210 FALSE, FALSE, context)
7211 || readcnt != todo
7212 || !WriteFile(hTo, buf, todo, &written, NULL)
7213 || written != todo)
7214 break;
7215 }
7216 CloseHandle(hTo);
7217 }
7218
7219 free(to_name);
7220}
7221
7222/*
7223 * Copy info streams from file "from" to file "to".
7224 */
7225 static void
7226copy_infostreams(char_u *from, char_u *to)
7227{
7228 WCHAR *fromw;
7229 WCHAR *tow;
7230 HANDLE sh;
7231 WIN32_STREAM_ID sid;
7232 int headersize;
7233 WCHAR streamname[_MAX_PATH];
7234 DWORD readcount;
7235 void *context = NULL;
7236 DWORD lo, hi;
7237 int len;
7238
7239 /* Convert the file names to wide characters. */
Bram Moolenaar36f692d2008-11-20 16:10:17 +00007240 fromw = enc_to_utf16(from, NULL);
7241 tow = enc_to_utf16(to, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007242 if (fromw != NULL && tow != NULL)
7243 {
7244 /* Open the file for reading. */
7245 sh = CreateFileW(fromw, GENERIC_READ, FILE_SHARE_READ, NULL,
7246 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
7247 if (sh != INVALID_HANDLE_VALUE)
7248 {
7249 /* Use BackupRead() to find the info streams. Repeat until we
7250 * have done them all.*/
7251 for (;;)
7252 {
7253 /* Get the header to find the length of the stream name. If
7254 * the "readcount" is zero we have done all info streams. */
7255 ZeroMemory(&sid, sizeof(WIN32_STREAM_ID));
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007256 headersize = (int)((char *)&sid.cStreamName - (char *)&sid.dwStreamId);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007257 if (!BackupRead(sh, (LPBYTE)&sid, headersize,
7258 &readcount, FALSE, FALSE, &context)
7259 || readcount == 0)
7260 break;
7261
7262 /* We only deal with streams that have a name. The normal
7263 * file data appears to be without a name, even though docs
7264 * suggest it is called "::$DATA". */
7265 if (sid.dwStreamNameSize > 0)
7266 {
7267 /* Read the stream name. */
7268 if (!BackupRead(sh, (LPBYTE)streamname,
7269 sid.dwStreamNameSize,
7270 &readcount, FALSE, FALSE, &context))
7271 break;
7272
7273 /* Copy an info stream with a name ":anything:$DATA".
7274 * Skip "::$DATA", it has no stream name (examples suggest
7275 * it might be used for the normal file contents).
7276 * Note that BackupRead() counts bytes, but the name is in
7277 * wide characters. */
7278 len = readcount / sizeof(WCHAR);
7279 streamname[len] = 0;
7280 if (len > 7 && wcsicmp(streamname + len - 6,
7281 L":$DATA") == 0)
7282 {
7283 streamname[len - 6] = 0;
7284 copy_substream(sh, &context, tow, streamname,
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00007285 (long)sid.Size.u.LowPart);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007286 }
7287 }
7288
7289 /* Advance to the next stream. We might try seeking too far,
7290 * but BackupSeek() doesn't skip over stream borders, thus
7291 * that's OK. */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00007292 (void)BackupSeek(sh, sid.Size.u.LowPart, sid.Size.u.HighPart,
Bram Moolenaar071d4272004-06-13 20:20:40 +00007293 &lo, &hi, &context);
7294 }
7295
7296 /* Clear the context. */
7297 (void)BackupRead(sh, NULL, 0, &readcount, TRUE, FALSE, &context);
7298
7299 CloseHandle(sh);
7300 }
7301 }
7302 vim_free(fromw);
7303 vim_free(tow);
7304}
7305#endif
7306
7307/*
7308 * Copy file attributes from file "from" to file "to".
7309 * For Windows NT and later we copy info streams.
7310 * Always returns zero, errors are ignored.
7311 */
7312 int
7313mch_copy_file_attribute(char_u *from, char_u *to)
7314{
7315#ifdef FEAT_MBYTE
7316 /* File streams only work on Windows NT and later. */
7317 PlatformId();
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007318 copy_infostreams(from, to);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007319#endif
7320 return 0;
7321}
7322
7323#if defined(MYRESETSTKOFLW) || defined(PROTO)
7324/*
7325 * Recreate a destroyed stack guard page in win32.
7326 * Written by Benjamin Peterson.
7327 */
7328
7329/* These magic numbers are from the MS header files */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007330#define MIN_STACK_WINNT 2
7331
7332/*
7333 * This function does the same thing as _resetstkoflw(), which is only
7334 * available in DevStudio .net and later.
7335 * Returns 0 for failure, 1 for success.
7336 */
7337 int
7338myresetstkoflw(void)
7339{
7340 BYTE *pStackPtr;
7341 BYTE *pGuardPage;
7342 BYTE *pStackBase;
7343 BYTE *pLowestPossiblePage;
7344 MEMORY_BASIC_INFORMATION mbi;
7345 SYSTEM_INFO si;
7346 DWORD nPageSize;
7347 DWORD dummy;
7348
Bram Moolenaar071d4272004-06-13 20:20:40 +00007349 PlatformId();
Bram Moolenaar071d4272004-06-13 20:20:40 +00007350
7351 /* We need to know the system page size. */
7352 GetSystemInfo(&si);
7353 nPageSize = si.dwPageSize;
7354
7355 /* ...and the current stack pointer */
7356 pStackPtr = (BYTE*)_alloca(1);
7357
7358 /* ...and the base of the stack. */
7359 if (VirtualQuery(pStackPtr, &mbi, sizeof mbi) == 0)
7360 return 0;
7361 pStackBase = (BYTE*)mbi.AllocationBase;
7362
7363 /* ...and the page thats min_stack_req pages away from stack base; this is
7364 * the lowest page we could use. */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007365 pLowestPossiblePage = pStackBase + MIN_STACK_WINNT * nPageSize;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007366
Bram Moolenaar071d4272004-06-13 20:20:40 +00007367 {
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007368 /* We want the first committed page in the stack Start at the stack
7369 * base and move forward through memory until we find a committed block.
7370 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007371 BYTE *pBlock = pStackBase;
7372
Bram Moolenaara466c992005-07-09 21:03:22 +00007373 for (;;)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007374 {
7375 if (VirtualQuery(pBlock, &mbi, sizeof mbi) == 0)
7376 return 0;
7377
7378 pBlock += mbi.RegionSize;
7379
7380 if (mbi.State & MEM_COMMIT)
7381 break;
7382 }
7383
7384 /* mbi now describes the first committed block in the stack. */
7385 if (mbi.Protect & PAGE_GUARD)
7386 return 1;
7387
7388 /* decide where the guard page should start */
7389 if ((long_u)(mbi.BaseAddress) < (long_u)pLowestPossiblePage)
7390 pGuardPage = pLowestPossiblePage;
7391 else
7392 pGuardPage = (BYTE*)mbi.BaseAddress;
7393
7394 /* allocate the guard page */
7395 if (!VirtualAlloc(pGuardPage, nPageSize, MEM_COMMIT, PAGE_READWRITE))
7396 return 0;
7397
7398 /* apply the guard attribute to the page */
7399 if (!VirtualProtect(pGuardPage, nPageSize, PAGE_READWRITE | PAGE_GUARD,
7400 &dummy))
7401 return 0;
7402 }
7403
7404 return 1;
7405}
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007406#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007407
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007408
7409#if defined(FEAT_MBYTE) || defined(PROTO)
7410/*
7411 * The command line arguments in UCS2
7412 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00007413static int nArgsW = 0;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007414static LPWSTR *ArglistW = NULL;
7415static int global_argc = 0;
7416static char **global_argv;
7417
7418static int used_file_argc = 0; /* last argument in global_argv[] used
7419 for the argument list. */
7420static int *used_file_indexes = NULL; /* indexes in global_argv[] for
7421 command line arguments added to
7422 the argument list */
7423static int used_file_count = 0; /* nr of entries in used_file_indexes */
7424static int used_file_literal = FALSE; /* take file names literally */
7425static int used_file_full_path = FALSE; /* file name was full path */
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007426static int used_file_diff_mode = FALSE; /* file name was with diff mode */
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007427static int used_alist_count = 0;
7428
7429
7430/*
7431 * Get the command line arguments. Unicode version.
7432 * Returns argc. Zero when something fails.
7433 */
7434 int
7435get_cmd_argsW(char ***argvp)
7436{
7437 char **argv = NULL;
7438 int argc = 0;
7439 int i;
7440
Bram Moolenaar14993322014-09-09 12:25:33 +02007441 free_cmd_argsW();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007442 ArglistW = CommandLineToArgvW(GetCommandLineW(), &nArgsW);
7443 if (ArglistW != NULL)
7444 {
7445 argv = malloc((nArgsW + 1) * sizeof(char *));
7446 if (argv != NULL)
7447 {
7448 argc = nArgsW;
7449 argv[argc] = NULL;
7450 for (i = 0; i < argc; ++i)
7451 {
7452 int len;
7453
7454 /* Convert each Unicode argument to the current codepage. */
7455 WideCharToMultiByte_alloc(GetACP(), 0,
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007456 ArglistW[i], (int)wcslen(ArglistW[i]) + 1,
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007457 (LPSTR *)&argv[i], &len, 0, 0);
7458 if (argv[i] == NULL)
7459 {
7460 /* Out of memory, clear everything. */
7461 while (i > 0)
7462 free(argv[--i]);
7463 free(argv);
Bram Moolenaar73c61632013-12-07 14:48:10 +01007464 argv = NULL;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007465 argc = 0;
7466 }
7467 }
7468 }
7469 }
7470
7471 global_argc = argc;
7472 global_argv = argv;
7473 if (argc > 0)
Bram Moolenaar14993322014-09-09 12:25:33 +02007474 {
7475 if (used_file_indexes != NULL)
7476 free(used_file_indexes);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007477 used_file_indexes = malloc(argc * sizeof(int));
Bram Moolenaar14993322014-09-09 12:25:33 +02007478 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007479
7480 if (argvp != NULL)
7481 *argvp = argv;
7482 return argc;
7483}
7484
7485 void
7486free_cmd_argsW(void)
7487{
7488 if (ArglistW != NULL)
7489 {
7490 GlobalFree(ArglistW);
7491 ArglistW = NULL;
7492 }
7493}
7494
7495/*
7496 * Remember "name" is an argument that was added to the argument list.
7497 * This avoids that we have to re-parse the argument list when fix_arg_enc()
7498 * is called.
7499 */
7500 void
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007501used_file_arg(char *name, int literal, int full_path, int diff_mode)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007502{
7503 int i;
7504
7505 if (used_file_indexes == NULL)
7506 return;
7507 for (i = used_file_argc + 1; i < global_argc; ++i)
7508 if (STRCMP(global_argv[i], name) == 0)
7509 {
7510 used_file_argc = i;
7511 used_file_indexes[used_file_count++] = i;
7512 break;
7513 }
7514 used_file_literal = literal;
7515 used_file_full_path = full_path;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007516 used_file_diff_mode = diff_mode;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007517}
7518
7519/*
7520 * Remember the length of the argument list as it was. If it changes then we
7521 * leave it alone when 'encoding' is set.
7522 */
7523 void
7524set_alist_count(void)
7525{
7526 used_alist_count = GARGCOUNT;
7527}
7528
7529/*
7530 * Fix the encoding of the command line arguments. Invoked when 'encoding'
7531 * has been changed while starting up. Use the UCS-2 command line arguments
7532 * and convert them to 'encoding'.
7533 */
7534 void
7535fix_arg_enc(void)
7536{
7537 int i;
7538 int idx;
7539 char_u *str;
Bram Moolenaar86b68352004-12-27 21:59:20 +00007540 int *fnum_list;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007541
7542 /* Safety checks:
7543 * - if argument count differs between the wide and non-wide argument
7544 * list, something must be wrong.
7545 * - the file name arguments must have been located.
7546 * - the length of the argument list wasn't changed by the user.
7547 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00007548 if (global_argc != nArgsW
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007549 || ArglistW == NULL
7550 || used_file_indexes == NULL
7551 || used_file_count == 0
7552 || used_alist_count != GARGCOUNT)
7553 return;
7554
Bram Moolenaar86b68352004-12-27 21:59:20 +00007555 /* Remember the buffer numbers for the arguments. */
7556 fnum_list = (int *)alloc((int)sizeof(int) * GARGCOUNT);
7557 if (fnum_list == NULL)
7558 return; /* out of memory */
7559 for (i = 0; i < GARGCOUNT; ++i)
7560 fnum_list[i] = GARGLIST[i].ae_fnum;
7561
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007562 /* Clear the argument list. Make room for the new arguments. */
7563 alist_clear(&global_alist);
7564 if (ga_grow(&global_alist.al_ga, used_file_count) == FAIL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00007565 return; /* out of memory */
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007566
7567 for (i = 0; i < used_file_count; ++i)
7568 {
7569 idx = used_file_indexes[i];
Bram Moolenaar36f692d2008-11-20 16:10:17 +00007570 str = utf16_to_enc(ArglistW[idx], NULL);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007571 if (str != NULL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00007572 {
Bram Moolenaar39d21e32017-08-05 23:09:31 +02007573 int literal = used_file_literal;
7574
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007575#ifdef FEAT_DIFF
7576 /* When using diff mode may need to concatenate file name to
7577 * directory name. Just like it's done in main(). */
7578 if (used_file_diff_mode && mch_isdir(str) && GARGCOUNT > 0
7579 && !mch_isdir(alist_name(&GARGLIST[0])))
7580 {
7581 char_u *r;
7582
7583 r = concat_fnames(str, gettail(alist_name(&GARGLIST[0])), TRUE);
7584 if (r != NULL)
7585 {
7586 vim_free(str);
7587 str = r;
7588 }
7589 }
7590#endif
Bram Moolenaar86b68352004-12-27 21:59:20 +00007591 /* Re-use the old buffer by renaming it. When not using literal
7592 * names it's done by alist_expand() below. */
7593 if (used_file_literal)
7594 buf_set_name(fnum_list[i], str);
7595
Bram Moolenaar39d21e32017-08-05 23:09:31 +02007596 /* Check backtick literal. backtick literal is already expanded in
7597 * main.c, so this part add str as literal. */
7598 if (literal == FALSE)
7599 {
Bram Moolenaar116a0f82017-08-07 21:17:57 +02007600 size_t len = STRLEN(str);
7601
Bram Moolenaar39d21e32017-08-05 23:09:31 +02007602 if (len > 2 && *str == '`' && *(str + len - 1) == '`')
7603 literal = TRUE;
7604 }
7605 alist_add(&global_alist, str, literal ? 2 : 0);
Bram Moolenaar86b68352004-12-27 21:59:20 +00007606 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007607 }
7608
7609 if (!used_file_literal)
7610 {
7611 /* Now expand wildcards in the arguments. */
7612 /* Temporarily add '(' and ')' to 'isfname'. These are valid
7613 * filename characters but are excluded from 'isfname' to make
Bram Moolenaar20586cb2018-03-08 22:03:14 +01007614 * "gf" work on a file name in parenthesis (e.g.: see vim.h).
7615 * Also, unset wildignore to not be influenced by this option.
7616 * The arguments specified in command-line should be kept even if
7617 * encoding options were changed. */
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007618 do_cmdline_cmd((char_u *)":let SaVe_ISF = &isf|set isf+=(,)");
Bram Moolenaar20586cb2018-03-08 22:03:14 +01007619 do_cmdline_cmd((char_u *)":let SaVe_WIG = &wig|set wig=");
Bram Moolenaar86b68352004-12-27 21:59:20 +00007620 alist_expand(fnum_list, used_alist_count);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007621 do_cmdline_cmd((char_u *)":let &isf = SaVe_ISF|unlet SaVe_ISF");
Bram Moolenaar20586cb2018-03-08 22:03:14 +01007622 do_cmdline_cmd((char_u *)":let &wig = SaVe_WIG|unlet SaVe_WIG");
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007623 }
7624
7625 /* If wildcard expansion failed, we are editing the first file of the
7626 * arglist and there is no file name: Edit the first argument now. */
7627 if (curwin->w_arg_idx == 0 && curbuf->b_fname == NULL)
7628 {
7629 do_cmdline_cmd((char_u *)":rewind");
7630 if (GARGCOUNT == 1 && used_file_full_path)
Bram Moolenaarb7407d32018-02-03 17:36:27 +01007631 (void)vim_chdirfile(alist_name(&GARGLIST[0]), "drop");
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007632 }
Bram Moolenaar86b68352004-12-27 21:59:20 +00007633
7634 set_alist_count();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007635}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007636#endif
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007637
7638 int
7639mch_setenv(char *var, char *value, int x)
7640{
7641 char_u *envbuf;
7642
7643 envbuf = alloc((unsigned)(STRLEN(var) + STRLEN(value) + 2));
7644 if (envbuf == NULL)
7645 return -1;
7646
7647 sprintf((char *)envbuf, "%s=%s", var, value);
7648
7649#ifdef FEAT_MBYTE
7650 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
7651 {
7652 WCHAR *p = enc_to_utf16(envbuf, NULL);
7653
7654 vim_free(envbuf);
7655 if (p == NULL)
7656 return -1;
7657 _wputenv(p);
7658# ifdef libintl_wputenv
7659 libintl_wputenv(p);
7660# endif
7661 /* Unlike Un*x systems, we can free the string for _wputenv(). */
7662 vim_free(p);
7663 }
7664 else
7665#endif
7666 {
7667 _putenv((char *)envbuf);
7668# ifdef libintl_putenv
7669 libintl_putenv((char *)envbuf);
7670# endif
7671 /* Unlike Un*x systems, we can free the string for _putenv(). */
7672 vim_free(envbuf);
7673 }
7674
7675 return 0;
7676}
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007677
7678#ifndef FEAT_GUI_W32
7679
7680/*
7681 * Support for 256 colors and 24-bit colors was added in Windows 10
7682 * version 1703 (Creators update).
7683 */
7684# define VTP_FIRST_SUPPORT_BUILD MAKE_VER(10, 0, 15063)
7685
7686 static void
7687vtp_init(void)
7688{
7689 DWORD ver, mode;
7690 HMODULE hKerneldll;
7691 DYN_CONSOLE_SCREEN_BUFFER_INFOEX csbi;
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007692# ifdef FEAT_TERMGUICOLORS
7693 COLORREF fg, bg;
7694# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007695
7696 ver = get_build_number();
7697 vtp_working = (ver >= VTP_FIRST_SUPPORT_BUILD) ? 1 : 0;
7698 GetConsoleMode(g_hConOut, &mode);
7699 mode |= (ENABLE_PROCESSED_OUTPUT | ENABLE_VIRTUAL_TERMINAL_PROCESSING);
7700 if (SetConsoleMode(g_hConOut, mode) == 0)
7701 vtp_working = 0;
7702
7703 /* Use functions supported from Vista */
7704 hKerneldll = GetModuleHandle("kernel32.dll");
7705 if (hKerneldll != NULL)
7706 {
7707 pGetConsoleScreenBufferInfoEx =
7708 (PfnGetConsoleScreenBufferInfoEx)GetProcAddress(
7709 hKerneldll, "GetConsoleScreenBufferInfoEx");
7710 pSetConsoleScreenBufferInfoEx =
7711 (PfnSetConsoleScreenBufferInfoEx)GetProcAddress(
7712 hKerneldll, "SetConsoleScreenBufferInfoEx");
7713 if (pGetConsoleScreenBufferInfoEx != NULL
7714 && pSetConsoleScreenBufferInfoEx != NULL)
7715 has_csbiex = TRUE;
7716 }
7717
7718 csbi.cbSize = sizeof(csbi);
7719 if (has_csbiex)
7720 pGetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007721 save_console_bg_rgb = (guicolor_T)csbi.ColorTable[g_color_index_bg];
7722 save_console_fg_rgb = (guicolor_T)csbi.ColorTable[g_color_index_fg];
7723
7724# ifdef FEAT_TERMGUICOLORS
7725 bg = (COLORREF)csbi.ColorTable[g_color_index_bg];
7726 fg = (COLORREF)csbi.ColorTable[g_color_index_fg];
7727 bg = (GetRValue(bg) << 16) | (GetGValue(bg) << 8) | GetBValue(bg);
7728 fg = (GetRValue(fg) << 16) | (GetGValue(fg) << 8) | GetBValue(fg);
7729 default_console_color_bg = bg;
7730 default_console_color_fg = fg;
7731#endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007732
7733 set_console_color_rgb();
7734}
7735
7736 static void
7737vtp_exit(void)
7738{
7739 reset_console_color_rgb();
7740}
7741
7742 static int
7743vtp_printf(
7744 char *format,
7745 ...)
7746{
7747 char_u buf[100];
7748 va_list list;
7749 DWORD result;
7750
7751 va_start(list, format);
7752 vim_vsnprintf((char *)buf, 100, (char *)format, list);
7753 va_end(list);
7754 WriteConsoleA(g_hConOut, buf, (DWORD)STRLEN(buf), &result, NULL);
7755 return (int)result;
7756}
7757
7758 static void
7759vtp_sgr_bulk(
7760 int arg)
7761{
7762 int args[1];
7763
7764 args[0] = arg;
7765 vtp_sgr_bulks(1, args);
7766}
7767
7768 static void
7769vtp_sgr_bulks(
7770 int argc,
7771 int *args
7772)
7773{
7774 /* 2('\033[') + 4('255.') * 16 + NUL */
7775 char_u buf[2 + (4 * 16) + 1];
7776 char_u *p;
7777 int i;
7778
7779 p = buf;
7780 *p++ = '\033';
7781 *p++ = '[';
7782
7783 for (i = 0; i < argc; ++i)
7784 {
7785 p += vim_snprintf((char *)p, 4, "%d", args[i] & 0xff);
7786 *p++ = ';';
7787 }
7788 p--;
7789 *p++ = 'm';
7790 *p = NUL;
7791 vtp_printf((char *)buf);
7792}
7793
Bram Moolenaar8a938af2018-05-01 17:30:41 +02007794# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007795 static int
7796ctermtoxterm(
7797 int cterm)
7798{
Bram Moolenaar9894e392018-05-05 14:29:06 +02007799 char_u r, g, b, idx;
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007800
7801 cterm_color2rgb(cterm, &r, &g, &b, &idx);
7802 return (((int)r << 16) | ((int)g << 8) | (int)b);
7803}
Bram Moolenaar8a938af2018-05-01 17:30:41 +02007804# endif
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007805
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007806 static void
7807set_console_color_rgb(void)
7808{
7809# ifdef FEAT_TERMGUICOLORS
7810 DYN_CONSOLE_SCREEN_BUFFER_INFOEX csbi;
7811 int id;
7812 guicolor_T fg = INVALCOLOR;
7813 guicolor_T bg = INVALCOLOR;
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007814 int ctermfg;
7815 int ctermbg;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007816
7817 if (!USE_VTP)
7818 return;
7819
7820 id = syn_name2id((char_u *)"Normal");
7821 if (id > 0)
7822 syn_id2colors(id, &fg, &bg);
7823 if (fg == INVALCOLOR)
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007824 {
7825 ctermfg = -1;
7826 if (id > 0)
7827 syn_id2cterm_bg(id, &ctermfg, &ctermbg);
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007828 fg = ctermfg != -1 ? ctermtoxterm(ctermfg) : default_console_color_fg;
7829 cterm_normal_fg_gui_color = fg;
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007830 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007831 if (bg == INVALCOLOR)
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007832 {
7833 ctermbg = -1;
7834 if (id > 0)
7835 syn_id2cterm_bg(id, &ctermfg, &ctermbg);
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007836 bg = ctermbg != -1 ? ctermtoxterm(ctermbg) : default_console_color_bg;
7837 cterm_normal_bg_gui_color = bg;
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007838 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007839 fg = (GetRValue(fg) << 16) | (GetGValue(fg) << 8) | GetBValue(fg);
7840 bg = (GetRValue(bg) << 16) | (GetGValue(bg) << 8) | GetBValue(bg);
7841
7842 csbi.cbSize = sizeof(csbi);
7843 if (has_csbiex)
7844 pGetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
7845
7846 csbi.cbSize = sizeof(csbi);
7847 csbi.srWindow.Right += 1;
7848 csbi.srWindow.Bottom += 1;
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007849 csbi.ColorTable[g_color_index_bg] = (COLORREF)bg;
7850 csbi.ColorTable[g_color_index_fg] = (COLORREF)fg;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007851 if (has_csbiex)
7852 pSetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
7853# endif
7854}
7855
7856 static void
7857reset_console_color_rgb(void)
7858{
7859# ifdef FEAT_TERMGUICOLORS
7860 DYN_CONSOLE_SCREEN_BUFFER_INFOEX csbi;
7861
7862 csbi.cbSize = sizeof(csbi);
7863 if (has_csbiex)
7864 pGetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
7865
7866 csbi.cbSize = sizeof(csbi);
7867 csbi.srWindow.Right += 1;
7868 csbi.srWindow.Bottom += 1;
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007869 csbi.ColorTable[g_color_index_bg] = (COLORREF)save_console_bg_rgb;
7870 csbi.ColorTable[g_color_index_fg] = (COLORREF)save_console_fg_rgb;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007871 if (has_csbiex)
7872 pSetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
7873# endif
7874}
7875
7876 void
7877control_console_color_rgb(void)
7878{
7879 if (USE_VTP)
7880 set_console_color_rgb();
7881 else
7882 reset_console_color_rgb();
7883}
7884
7885 int
7886has_vtp_working(void)
7887{
7888 return vtp_working;
7889}
7890
7891 int
7892use_vtp(void)
7893{
7894 return USE_VTP;
7895}
7896
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007897 int
7898is_term_win32(void)
7899{
7900 return T_NAME != NULL && STRCMP(T_NAME, "win32") == 0;
7901}
7902
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007903#endif