blob: dc98d6acd24aeec776d9b046da9878b5504568d0 [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
171static void termcap_mode_start(void);
172static void termcap_mode_end(void);
173static void clear_chars(COORD coord, DWORD n);
174static void clear_screen(void);
175static void clear_to_end_of_display(void);
176static void clear_to_end_of_line(void);
177static void scroll(unsigned cLines);
178static void set_scroll_region(unsigned left, unsigned top,
179 unsigned right, unsigned bottom);
180static void insert_lines(unsigned cLines);
181static void delete_lines(unsigned cLines);
182static void gotoxy(unsigned x, unsigned y);
183static void normvideo(void);
184static void textattr(WORD wAttr);
185static void textcolor(WORD wAttr);
186static void textbackground(WORD wAttr);
187static void standout(void);
188static void standend(void);
189static void visual_bell(void);
190static void cursor_visible(BOOL fVisible);
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200191static DWORD write_chars(char_u *pchBuf, DWORD cbToWrite);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000192static void create_conin(void);
193static int s_cursor_visible = TRUE;
194static int did_create_conin = FALSE;
195#else
196static int s_dont_use_vimrun = TRUE;
197static int need_vimrun_warning = FALSE;
198static char *vimrun_path = "vimrun ";
199#endif
200
Bram Moolenaar12b559e2013-06-12 22:41:37 +0200201static int win32_getattrs(char_u *name);
202static int win32_setattrs(char_u *name, int attrs);
203static int win32_set_archive(char_u *name);
204
Bram Moolenaar071d4272004-06-13 20:20:40 +0000205#ifndef FEAT_GUI_W32
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100206static int vtp_working = 0;
207static void vtp_init();
208static void vtp_exit();
209static int vtp_printf(char *format, ...);
210static void vtp_sgr_bulk(int arg);
211static void vtp_sgr_bulks(int argc, int *argv);
212
213static guicolor_T save_console_bg_rgb;
214static guicolor_T save_console_fg_rgb;
215
216# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarc5cd8852018-05-01 15:47:38 +0200217# define USE_VTP (vtp_working && is_term_win32() && (p_tgc || (!p_tgc && t_colors >= 256)))
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100218# else
219# define USE_VTP 0
220# endif
221
222static void set_console_color_rgb(void);
223static void reset_console_color_rgb(void);
224#endif
225
226/* This flag is newly created from Windows 10 */
227#ifndef ENABLE_VIRTUAL_TERMINAL_PROCESSING
228# define ENABLE_VIRTUAL_TERMINAL_PROCESSING 0x0004
229#endif
230
231#ifndef FEAT_GUI_W32
Bram Moolenaar071d4272004-06-13 20:20:40 +0000232static int suppress_winsize = 1; /* don't fiddle with console */
233#endif
234
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200235static char_u *exe_path = NULL;
236
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100237static BOOL win8_or_later = FALSE;
238
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100239#ifndef FEAT_GUI_W32
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100240/* Dynamic loading for portability */
241typedef struct _DYN_CONSOLE_SCREEN_BUFFER_INFOEX
242{
243 ULONG cbSize;
244 COORD dwSize;
245 COORD dwCursorPosition;
246 WORD wAttributes;
247 SMALL_RECT srWindow;
248 COORD dwMaximumWindowSize;
249 WORD wPopupAttributes;
250 BOOL bFullscreenSupported;
251 COLORREF ColorTable[16];
252} DYN_CONSOLE_SCREEN_BUFFER_INFOEX, *PDYN_CONSOLE_SCREEN_BUFFER_INFOEX;
253typedef BOOL (WINAPI *PfnGetConsoleScreenBufferInfoEx)(HANDLE, PDYN_CONSOLE_SCREEN_BUFFER_INFOEX);
254static PfnGetConsoleScreenBufferInfoEx pGetConsoleScreenBufferInfoEx;
255typedef BOOL (WINAPI *PfnSetConsoleScreenBufferInfoEx)(HANDLE, PDYN_CONSOLE_SCREEN_BUFFER_INFOEX);
256static PfnSetConsoleScreenBufferInfoEx pSetConsoleScreenBufferInfoEx;
257static BOOL has_csbiex = FALSE;
258
259/*
260 * Get version number including build number
261 */
262typedef BOOL (WINAPI *PfnRtlGetVersion)(LPOSVERSIONINFOW);
263# define MAKE_VER(major, minor, build) \
264 (((major) << 24) | ((minor) << 16) | (build))
265
266 static DWORD
267get_build_number(void)
268{
269 OSVERSIONINFOW osver = {sizeof(OSVERSIONINFOW)};
270 HMODULE hNtdll;
271 PfnRtlGetVersion pRtlGetVersion;
272 DWORD ver = MAKE_VER(0, 0, 0);
273
274 hNtdll = GetModuleHandle("ntdll.dll");
275 if (hNtdll != NULL)
276 {
277 pRtlGetVersion =
278 (PfnRtlGetVersion)GetProcAddress(hNtdll, "RtlGetVersion");
279 pRtlGetVersion(&osver);
280 ver = MAKE_VER(min(osver.dwMajorVersion, 255),
281 min(osver.dwMinorVersion, 255),
282 min(osver.dwBuildNumber, 32767));
283 }
284 return ver;
285}
286
287
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100288/*
289 * Version of ReadConsoleInput() that works with IME.
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100290 * Works around problems on Windows 8.
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100291 */
292 static BOOL
293read_console_input(
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100294 HANDLE hInput,
295 INPUT_RECORD *lpBuffer,
296 DWORD nLength,
297 LPDWORD lpEvents)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100298{
299 enum
300 {
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100301 IRSIZE = 10
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100302 };
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100303 static INPUT_RECORD s_irCache[IRSIZE];
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100304 static DWORD s_dwIndex = 0;
305 static DWORD s_dwMax = 0;
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100306 DWORD dwEvents;
Bram Moolenaardd415a62014-02-05 14:02:27 +0100307 int head;
308 int tail;
309 int i;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100310
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200311 if (nLength == -2)
312 return (s_dwMax > 0) ? TRUE : FALSE;
313
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100314 if (!win8_or_later)
315 {
316 if (nLength == -1)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200317 return PeekConsoleInputW(hInput, lpBuffer, 1, lpEvents);
318 return ReadConsoleInputW(hInput, lpBuffer, 1, &dwEvents);
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100319 }
320
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100321 if (s_dwMax == 0)
322 {
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100323 if (nLength == -1)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200324 return PeekConsoleInputW(hInput, lpBuffer, 1, lpEvents);
325 if (!ReadConsoleInputW(hInput, s_irCache, IRSIZE, &dwEvents))
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100326 return FALSE;
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100327 s_dwIndex = 0;
328 s_dwMax = dwEvents;
329 if (dwEvents == 0)
330 {
331 *lpEvents = 0;
332 return TRUE;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100333 }
Bram Moolenaardd415a62014-02-05 14:02:27 +0100334
335 if (s_dwMax > 1)
336 {
337 head = 0;
338 tail = s_dwMax - 1;
339 while (head != tail)
340 {
341 if (s_irCache[head].EventType == WINDOW_BUFFER_SIZE_EVENT
342 && s_irCache[head + 1].EventType
343 == WINDOW_BUFFER_SIZE_EVENT)
344 {
345 /* Remove duplicate event to avoid flicker. */
346 for (i = head; i < tail; ++i)
347 s_irCache[i] = s_irCache[i + 1];
348 --tail;
349 continue;
350 }
351 head++;
352 }
353 s_dwMax = tail + 1;
354 }
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100355 }
Bram Moolenaardd415a62014-02-05 14:02:27 +0100356
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100357 *lpBuffer = s_irCache[s_dwIndex];
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200358 if (!(nLength == -1 || nLength == -2) && ++s_dwIndex >= s_dwMax)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100359 s_dwMax = 0;
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100360 *lpEvents = 1;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100361 return TRUE;
362}
363
364/*
365 * Version of PeekConsoleInput() that works with IME.
366 */
367 static BOOL
368peek_console_input(
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100369 HANDLE hInput,
370 INPUT_RECORD *lpBuffer,
371 DWORD nLength,
372 LPDWORD lpEvents)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100373{
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100374 return read_console_input(hInput, lpBuffer, -1, lpEvents);
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100375}
376
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100377# ifdef FEAT_CLIENTSERVER
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200378 static DWORD
379msg_wait_for_multiple_objects(
380 DWORD nCount,
381 LPHANDLE pHandles,
382 BOOL fWaitAll,
383 DWORD dwMilliseconds,
384 DWORD dwWakeMask)
385{
386 if (read_console_input(NULL, NULL, -2, NULL))
387 return WAIT_OBJECT_0;
388 return MsgWaitForMultipleObjects(nCount, pHandles, fWaitAll,
389 dwMilliseconds, dwWakeMask);
390}
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100391# endif
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200392
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100393# ifndef FEAT_CLIENTSERVER
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200394 static DWORD
395wait_for_single_object(
396 HANDLE hHandle,
397 DWORD dwMilliseconds)
398{
399 if (read_console_input(NULL, NULL, -2, NULL))
400 return WAIT_OBJECT_0;
401 return WaitForSingleObject(hHandle, dwMilliseconds);
402}
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100403# endif
404#endif
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200405
Bram Moolenaar071d4272004-06-13 20:20:40 +0000406 static void
407get_exe_name(void)
408{
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100409 /* Maximum length of $PATH is more than MAXPATHL. 8191 is often mentioned
410 * as the maximum length that works (plus a NUL byte). */
411#define MAX_ENV_PATH_LEN 8192
412 char temp[MAX_ENV_PATH_LEN];
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200413 char_u *p;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000414
415 if (exe_name == NULL)
416 {
417 /* store the name of the executable, may be used for $VIM */
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100418 GetModuleFileName(NULL, temp, MAX_ENV_PATH_LEN - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000419 if (*temp != NUL)
420 exe_name = FullName_save((char_u *)temp, FALSE);
421 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000422
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200423 if (exe_path == NULL && exe_name != NULL)
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000424 {
Bram Moolenaar6b5ef062010-10-27 12:18:00 +0200425 exe_path = vim_strnsave(exe_name,
426 (int)(gettail_sep(exe_name) - exe_name));
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200427 if (exe_path != NULL)
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000428 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200429 /* Append our starting directory to $PATH, so that when doing
430 * "!xxd" it's found in our starting directory. Needed because
431 * SearchPath() also looks there. */
432 p = mch_getenv("PATH");
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100433 if (p == NULL
434 || STRLEN(p) + STRLEN(exe_path) + 2 < MAX_ENV_PATH_LEN)
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200435 {
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100436 if (p == NULL || *p == NUL)
437 temp[0] = NUL;
438 else
439 {
440 STRCPY(temp, p);
441 STRCAT(temp, ";");
442 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200443 STRCAT(temp, exe_path);
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +0100444 vim_setenv((char_u *)"PATH", (char_u *)temp);
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200445 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000446 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000447 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000448}
449
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200450/*
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100451 * Unescape characters in "p" that appear in "escaped".
452 */
453 static void
454unescape_shellxquote(char_u *p, char_u *escaped)
455{
Bram Moolenaar4336cdf2012-02-29 13:58:47 +0100456 int l = (int)STRLEN(p);
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100457 int n;
458
459 while (*p != NUL)
460 {
461 if (*p == '^' && vim_strchr(escaped, p[1]) != NULL)
462 mch_memmove(p, p + 1, l--);
463#ifdef FEAT_MBYTE
464 n = (*mb_ptr2len)(p);
465#else
466 n = 1;
467#endif
468 p += n;
469 l -= n;
470 }
471}
472
473/*
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200474 * Load library "name".
475 */
476 HINSTANCE
477vimLoadLib(char *name)
478{
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200479 HINSTANCE dll = NULL;
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200480
Bram Moolenaarfaca8402012-10-21 02:37:10 +0200481 /* NOTE: Do not use mch_dirname() and mch_chdir() here, they may call
482 * vimLoadLib() recursively, which causes a stack overflow. */
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200483 if (exe_path == NULL)
484 get_exe_name();
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200485 if (exe_path != NULL)
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200486 {
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200487 WCHAR old_dirw[MAXPATHL];
488
489 if (GetCurrentDirectoryW(MAXPATHL, old_dirw) != 0)
490 {
491 /* Change directory to where the executable is, both to make
492 * sure we find a .dll there and to avoid looking for a .dll
493 * in the current directory. */
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +0100494 SetCurrentDirectory((LPCSTR)exe_path);
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200495 dll = LoadLibrary(name);
496 SetCurrentDirectoryW(old_dirw);
497 return dll;
498 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200499 }
500 return dll;
501}
502
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100503#if defined(DYNAMIC_ICONV) || defined(DYNAMIC_GETTEXT) || defined(PROTO)
504/*
505 * Get related information about 'funcname' which is imported by 'hInst'.
506 * If 'info' is 0, return the function address.
507 * If 'info' is 1, return the module name which the function is imported from.
508 */
509 static void *
510get_imported_func_info(HINSTANCE hInst, const char *funcname, int info)
511{
512 PBYTE pImage = (PBYTE)hInst;
513 PIMAGE_DOS_HEADER pDOS = (PIMAGE_DOS_HEADER)hInst;
514 PIMAGE_NT_HEADERS pPE;
515 PIMAGE_IMPORT_DESCRIPTOR pImpDesc;
516 PIMAGE_THUNK_DATA pIAT; /* Import Address Table */
517 PIMAGE_THUNK_DATA pINT; /* Import Name Table */
518 PIMAGE_IMPORT_BY_NAME pImpName;
519
520 if (pDOS->e_magic != IMAGE_DOS_SIGNATURE)
521 return NULL;
522 pPE = (PIMAGE_NT_HEADERS)(pImage + pDOS->e_lfanew);
523 if (pPE->Signature != IMAGE_NT_SIGNATURE)
524 return NULL;
525 pImpDesc = (PIMAGE_IMPORT_DESCRIPTOR)(pImage
526 + pPE->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT]
527 .VirtualAddress);
528 for (; pImpDesc->FirstThunk; ++pImpDesc)
529 {
530 if (!pImpDesc->OriginalFirstThunk)
531 continue;
532 pIAT = (PIMAGE_THUNK_DATA)(pImage + pImpDesc->FirstThunk);
533 pINT = (PIMAGE_THUNK_DATA)(pImage + pImpDesc->OriginalFirstThunk);
534 for (; pIAT->u1.Function; ++pIAT, ++pINT)
535 {
536 if (IMAGE_SNAP_BY_ORDINAL(pINT->u1.Ordinal))
537 continue;
538 pImpName = (PIMAGE_IMPORT_BY_NAME)(pImage
539 + (UINT_PTR)(pINT->u1.AddressOfData));
540 if (strcmp((char *)pImpName->Name, funcname) == 0)
541 {
542 switch (info)
543 {
544 case 0:
545 return (void *)pIAT->u1.Function;
546 case 1:
547 return (void *)(pImage + pImpDesc->Name);
548 default:
549 return NULL;
550 }
551 }
552 }
553 }
554 return NULL;
555}
556
557/*
558 * Get the module handle which 'funcname' in 'hInst' is imported from.
559 */
560 HINSTANCE
561find_imported_module_by_funcname(HINSTANCE hInst, const char *funcname)
562{
563 char *modulename;
564
565 modulename = (char *)get_imported_func_info(hInst, funcname, 1);
566 if (modulename != NULL)
567 return GetModuleHandleA(modulename);
568 return NULL;
569}
570
571/*
572 * Get the address of 'funcname' which is imported by 'hInst' DLL.
573 */
574 void *
575get_dll_import_func(HINSTANCE hInst, const char *funcname)
576{
577 return get_imported_func_info(hInst, funcname, 0);
578}
579#endif
580
Bram Moolenaar071d4272004-06-13 20:20:40 +0000581#if defined(DYNAMIC_GETTEXT) || defined(PROTO)
582# ifndef GETTEXT_DLL
583# define GETTEXT_DLL "libintl.dll"
Bram Moolenaar286eacd2016-01-16 18:05:50 +0100584# define GETTEXT_DLL_ALT "libintl-8.dll"
Bram Moolenaar071d4272004-06-13 20:20:40 +0000585# endif
Bram Moolenaarf6a2b082012-06-29 13:14:03 +0200586/* Dummy functions */
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000587static char *null_libintl_gettext(const char *);
Bram Moolenaaree695f72016-08-03 22:08:45 +0200588static char *null_libintl_ngettext(const char *, const char *, unsigned long n);
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000589static char *null_libintl_textdomain(const char *);
590static char *null_libintl_bindtextdomain(const char *, const char *);
591static char *null_libintl_bind_textdomain_codeset(const char *, const char *);
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100592static int null_libintl_putenv(const char *);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100593static int null_libintl_wputenv(const wchar_t *);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000594
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200595static HINSTANCE hLibintlDLL = NULL;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000596char *(*dyn_libintl_gettext)(const char *) = null_libintl_gettext;
Bram Moolenaaree695f72016-08-03 22:08:45 +0200597char *(*dyn_libintl_ngettext)(const char *, const char *, unsigned long n)
598 = null_libintl_ngettext;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000599char *(*dyn_libintl_textdomain)(const char *) = null_libintl_textdomain;
600char *(*dyn_libintl_bindtextdomain)(const char *, const char *)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000601 = null_libintl_bindtextdomain;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000602char *(*dyn_libintl_bind_textdomain_codeset)(const char *, const char *)
603 = null_libintl_bind_textdomain_codeset;
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100604int (*dyn_libintl_putenv)(const char *) = null_libintl_putenv;
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100605int (*dyn_libintl_wputenv)(const wchar_t *) = null_libintl_wputenv;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000606
607 int
Bram Moolenaar05540972016-01-30 20:31:25 +0100608dyn_libintl_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000609{
610 int i;
611 static struct
612 {
613 char *name;
614 FARPROC *ptr;
615 } libintl_entry[] =
616 {
617 {"gettext", (FARPROC*)&dyn_libintl_gettext},
Bram Moolenaaree695f72016-08-03 22:08:45 +0200618 {"ngettext", (FARPROC*)&dyn_libintl_ngettext},
Bram Moolenaar071d4272004-06-13 20:20:40 +0000619 {"textdomain", (FARPROC*)&dyn_libintl_textdomain},
620 {"bindtextdomain", (FARPROC*)&dyn_libintl_bindtextdomain},
621 {NULL, NULL}
622 };
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100623 HINSTANCE hmsvcrt;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000624
625 /* No need to initialize twice. */
626 if (hLibintlDLL)
627 return 1;
628 /* Load gettext library (libintl.dll) */
Bram Moolenaar923e43b2016-01-28 15:07:38 +0100629 hLibintlDLL = vimLoadLib(GETTEXT_DLL);
Bram Moolenaar938ee832016-01-24 15:36:03 +0100630#ifdef GETTEXT_DLL_ALT
Bram Moolenaar286eacd2016-01-16 18:05:50 +0100631 if (!hLibintlDLL)
632 hLibintlDLL = vimLoadLib(GETTEXT_DLL_ALT);
Bram Moolenaar938ee832016-01-24 15:36:03 +0100633#endif
634 if (!hLibintlDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000635 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200636 if (p_verbose > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000637 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200638 verbose_enter();
639 EMSG2(_(e_loadlib), GETTEXT_DLL);
640 verbose_leave();
Bram Moolenaar071d4272004-06-13 20:20:40 +0000641 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200642 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000643 }
644 for (i = 0; libintl_entry[i].name != NULL
645 && libintl_entry[i].ptr != NULL; ++i)
646 {
647 if ((*libintl_entry[i].ptr = (FARPROC)GetProcAddress(hLibintlDLL,
648 libintl_entry[i].name)) == NULL)
649 {
650 dyn_libintl_end();
651 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +0000652 {
653 verbose_enter();
Bram Moolenaar071d4272004-06-13 20:20:40 +0000654 EMSG2(_(e_loadfunc), libintl_entry[i].name);
Bram Moolenaara04f10b2005-05-31 22:09:46 +0000655 verbose_leave();
656 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000657 return 0;
658 }
659 }
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000660
661 /* The bind_textdomain_codeset() function is optional. */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000662 dyn_libintl_bind_textdomain_codeset = (void *)GetProcAddress(hLibintlDLL,
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000663 "bind_textdomain_codeset");
664 if (dyn_libintl_bind_textdomain_codeset == NULL)
665 dyn_libintl_bind_textdomain_codeset =
666 null_libintl_bind_textdomain_codeset;
667
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100668 /* _putenv() function for the libintl.dll is optional. */
669 hmsvcrt = find_imported_module_by_funcname(hLibintlDLL, "getenv");
670 if (hmsvcrt != NULL)
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100671 {
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100672 dyn_libintl_putenv = (void *)GetProcAddress(hmsvcrt, "_putenv");
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100673 dyn_libintl_wputenv = (void *)GetProcAddress(hmsvcrt, "_wputenv");
674 }
675 if (dyn_libintl_putenv == NULL || dyn_libintl_putenv == _putenv)
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100676 dyn_libintl_putenv = null_libintl_putenv;
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100677 if (dyn_libintl_wputenv == NULL || dyn_libintl_wputenv == _wputenv)
678 dyn_libintl_wputenv = null_libintl_wputenv;
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100679
Bram Moolenaar071d4272004-06-13 20:20:40 +0000680 return 1;
681}
682
683 void
Bram Moolenaar05540972016-01-30 20:31:25 +0100684dyn_libintl_end(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000685{
686 if (hLibintlDLL)
687 FreeLibrary(hLibintlDLL);
688 hLibintlDLL = NULL;
689 dyn_libintl_gettext = null_libintl_gettext;
Bram Moolenaaree695f72016-08-03 22:08:45 +0200690 dyn_libintl_ngettext = null_libintl_ngettext;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000691 dyn_libintl_textdomain = null_libintl_textdomain;
692 dyn_libintl_bindtextdomain = null_libintl_bindtextdomain;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000693 dyn_libintl_bind_textdomain_codeset = null_libintl_bind_textdomain_codeset;
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100694 dyn_libintl_putenv = null_libintl_putenv;
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100695 dyn_libintl_wputenv = null_libintl_wputenv;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000696}
697
698 static char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000699null_libintl_gettext(const char *msgid)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000700{
701 return (char*)msgid;
702}
703
704 static char *
Bram Moolenaaree695f72016-08-03 22:08:45 +0200705null_libintl_ngettext(
706 const char *msgid,
707 const char *msgid_plural,
708 unsigned long n)
709{
Bram Moolenaarc90f2ae2016-08-04 22:00:15 +0200710 return (char *)(n == 1 ? msgid : msgid_plural);
Bram Moolenaaree695f72016-08-03 22:08:45 +0200711}
712
Bram Moolenaaree695f72016-08-03 22:08:45 +0200713 static char *
Bram Moolenaar1266d672017-02-01 13:43:36 +0100714null_libintl_bindtextdomain(
715 const char *domainname UNUSED,
716 const char *dirname UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000717{
718 return NULL;
719}
720
721 static char *
Bram Moolenaar1266d672017-02-01 13:43:36 +0100722null_libintl_bind_textdomain_codeset(
723 const char *domainname UNUSED,
724 const char *codeset UNUSED)
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000725{
726 return NULL;
727}
728
729 static char *
Bram Moolenaar1266d672017-02-01 13:43:36 +0100730null_libintl_textdomain(const char *domainname UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000731{
732 return NULL;
733}
734
Bram Moolenaare0ab9792017-08-02 23:18:25 +0200735 static int
Bram Moolenaar1266d672017-02-01 13:43:36 +0100736null_libintl_putenv(const char *envstring UNUSED)
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100737{
738 return 0;
739}
740
Bram Moolenaare0ab9792017-08-02 23:18:25 +0200741 static int
Bram Moolenaar1266d672017-02-01 13:43:36 +0100742null_libintl_wputenv(const wchar_t *envstring UNUSED)
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100743{
744 return 0;
745}
746
Bram Moolenaar071d4272004-06-13 20:20:40 +0000747#endif /* DYNAMIC_GETTEXT */
748
749/* This symbol is not defined in older versions of the SDK or Visual C++ */
750
751#ifndef VER_PLATFORM_WIN32_WINDOWS
752# define VER_PLATFORM_WIN32_WINDOWS 1
753#endif
754
755DWORD g_PlatformId;
756
757#ifdef HAVE_ACL
Bram Moolenaar82881492012-11-20 16:53:39 +0100758# ifndef PROTO
759# include <aclapi.h>
760# endif
Bram Moolenaar27515922013-06-29 15:36:26 +0200761# ifndef PROTECTED_DACL_SECURITY_INFORMATION
762# define PROTECTED_DACL_SECURITY_INFORMATION 0x80000000L
763# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000764#endif
765
Bram Moolenaar27515922013-06-29 15:36:26 +0200766#ifdef HAVE_ACL
767/*
768 * Enables or disables the specified privilege.
769 */
770 static BOOL
771win32_enable_privilege(LPTSTR lpszPrivilege, BOOL bEnable)
772{
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100773 BOOL bResult;
774 LUID luid;
775 HANDLE hToken;
776 TOKEN_PRIVILEGES tokenPrivileges;
Bram Moolenaar27515922013-06-29 15:36:26 +0200777
778 if (!OpenProcessToken(GetCurrentProcess(),
779 TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
780 return FALSE;
781
782 if (!LookupPrivilegeValue(NULL, lpszPrivilege, &luid))
783 {
784 CloseHandle(hToken);
785 return FALSE;
786 }
787
Bram Moolenaar45500912014-07-09 20:51:07 +0200788 tokenPrivileges.PrivilegeCount = 1;
Bram Moolenaar27515922013-06-29 15:36:26 +0200789 tokenPrivileges.Privileges[0].Luid = luid;
790 tokenPrivileges.Privileges[0].Attributes = bEnable ?
791 SE_PRIVILEGE_ENABLED : 0;
792
793 bResult = AdjustTokenPrivileges(hToken, FALSE, &tokenPrivileges,
794 sizeof(TOKEN_PRIVILEGES), NULL, NULL);
795
796 CloseHandle(hToken);
797
798 return bResult && GetLastError() == ERROR_SUCCESS;
799}
800#endif
801
Bram Moolenaar071d4272004-06-13 20:20:40 +0000802/*
803 * Set g_PlatformId to VER_PLATFORM_WIN32_NT (NT) or
804 * VER_PLATFORM_WIN32_WINDOWS (Win95).
805 */
806 void
807PlatformId(void)
808{
809 static int done = FALSE;
810
811 if (!done)
812 {
813 OSVERSIONINFO ovi;
814
815 ovi.dwOSVersionInfoSize = sizeof(ovi);
816 GetVersionEx(&ovi);
817
818 g_PlatformId = ovi.dwPlatformId;
819
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100820 if ((ovi.dwMajorVersion == 6 && ovi.dwMinorVersion >= 2)
821 || ovi.dwMajorVersion > 6)
822 win8_or_later = TRUE;
823
Bram Moolenaar071d4272004-06-13 20:20:40 +0000824#ifdef HAVE_ACL
Bram Moolenaarcea912a2016-10-12 14:20:24 +0200825 /* Enable privilege for getting or setting SACLs. */
826 win32_enable_privilege(SE_SECURITY_NAME, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000827#endif
828 done = TRUE;
829 }
830}
831
Bram Moolenaar071d4272004-06-13 20:20:40 +0000832#ifndef FEAT_GUI_W32
833
834#define SHIFT (SHIFT_PRESSED)
835#define CTRL (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED)
836#define ALT (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED)
837#define ALT_GR (RIGHT_ALT_PRESSED | LEFT_CTRL_PRESSED)
838
839
840/* When uChar.AsciiChar is 0, then we need to look at wVirtualKeyCode.
841 * We map function keys to their ANSI terminal equivalents, as produced
842 * by ANSI.SYS, for compatibility with the MS-DOS version of Vim. Any
843 * ANSI key with a value >= '\300' is nonstandard, but provided anyway
844 * so that the user can have access to all SHIFT-, CTRL-, and ALT-
845 * combinations of function/arrow/etc keys.
846 */
847
Bram Moolenaard6f676d2005-06-01 21:51:55 +0000848static const struct
Bram Moolenaar071d4272004-06-13 20:20:40 +0000849{
850 WORD wVirtKey;
851 BOOL fAnsiKey;
852 int chAlone;
853 int chShift;
854 int chCtrl;
855 int chAlt;
856} VirtKeyMap[] =
857{
858
859/* Key ANSI alone shift ctrl alt */
860 { VK_ESCAPE,FALSE, ESC, ESC, ESC, ESC, },
861
862 { VK_F1, TRUE, ';', 'T', '^', 'h', },
863 { VK_F2, TRUE, '<', 'U', '_', 'i', },
864 { VK_F3, TRUE, '=', 'V', '`', 'j', },
865 { VK_F4, TRUE, '>', 'W', 'a', 'k', },
866 { VK_F5, TRUE, '?', 'X', 'b', 'l', },
867 { VK_F6, TRUE, '@', 'Y', 'c', 'm', },
868 { VK_F7, TRUE, 'A', 'Z', 'd', 'n', },
869 { VK_F8, TRUE, 'B', '[', 'e', 'o', },
870 { VK_F9, TRUE, 'C', '\\', 'f', 'p', },
871 { VK_F10, TRUE, 'D', ']', 'g', 'q', },
872 { VK_F11, TRUE, '\205', '\207', '\211', '\213', },
873 { VK_F12, TRUE, '\206', '\210', '\212', '\214', },
874
875 { VK_HOME, TRUE, 'G', '\302', 'w', '\303', },
876 { VK_UP, TRUE, 'H', '\304', '\305', '\306', },
877 { VK_PRIOR, TRUE, 'I', '\307', '\204', '\310', }, /*PgUp*/
878 { VK_LEFT, TRUE, 'K', '\311', 's', '\312', },
879 { VK_RIGHT, TRUE, 'M', '\313', 't', '\314', },
880 { VK_END, TRUE, 'O', '\315', 'u', '\316', },
881 { VK_DOWN, TRUE, 'P', '\317', '\320', '\321', },
882 { VK_NEXT, TRUE, 'Q', '\322', 'v', '\323', }, /*PgDn*/
883 { VK_INSERT,TRUE, 'R', '\324', '\325', '\326', },
884 { VK_DELETE,TRUE, 'S', '\327', '\330', '\331', },
885
886 { VK_SNAPSHOT,TRUE, 0, 0, 0, 'r', }, /*PrtScrn*/
887
888#if 0
889 /* Most people don't have F13-F20, but what the hell... */
890 { VK_F13, TRUE, '\332', '\333', '\334', '\335', },
891 { VK_F14, TRUE, '\336', '\337', '\340', '\341', },
892 { VK_F15, TRUE, '\342', '\343', '\344', '\345', },
893 { VK_F16, TRUE, '\346', '\347', '\350', '\351', },
894 { VK_F17, TRUE, '\352', '\353', '\354', '\355', },
895 { VK_F18, TRUE, '\356', '\357', '\360', '\361', },
896 { VK_F19, TRUE, '\362', '\363', '\364', '\365', },
897 { VK_F20, TRUE, '\366', '\367', '\370', '\371', },
898#endif
899 { VK_ADD, TRUE, 'N', 'N', 'N', 'N', }, /* keyp '+' */
900 { VK_SUBTRACT, TRUE,'J', 'J', 'J', 'J', }, /* keyp '-' */
901 /* { VK_DIVIDE, TRUE,'N', 'N', 'N', 'N', }, keyp '/' */
902 { VK_MULTIPLY, TRUE,'7', '7', '7', '7', }, /* keyp '*' */
903
904 { VK_NUMPAD0,TRUE, '\332', '\333', '\334', '\335', },
905 { VK_NUMPAD1,TRUE, '\336', '\337', '\340', '\341', },
906 { VK_NUMPAD2,TRUE, '\342', '\343', '\344', '\345', },
907 { VK_NUMPAD3,TRUE, '\346', '\347', '\350', '\351', },
908 { VK_NUMPAD4,TRUE, '\352', '\353', '\354', '\355', },
909 { VK_NUMPAD5,TRUE, '\356', '\357', '\360', '\361', },
910 { VK_NUMPAD6,TRUE, '\362', '\363', '\364', '\365', },
911 { VK_NUMPAD7,TRUE, '\366', '\367', '\370', '\371', },
912 { VK_NUMPAD8,TRUE, '\372', '\373', '\374', '\375', },
913 /* Sorry, out of number space! <negri>*/
914 { VK_NUMPAD9,TRUE, '\376', '\377', '\377', '\367', },
915
916};
917
918
919#ifdef _MSC_VER
920// The ToAscii bug destroys several registers. Need to turn off optimization
921// or the GetConsoleKeyboardLayoutName hack will fail in non-debug versions
Bram Moolenaar7b5f8322006-03-23 22:47:08 +0000922# pragma warning(push)
923# pragma warning(disable: 4748)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000924# pragma optimize("", off)
925#endif
926
927#if defined(__GNUC__) && !defined(__MINGW32__) && !defined(__CYGWIN__)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200928# define UChar UnicodeChar
Bram Moolenaar071d4272004-06-13 20:20:40 +0000929#else
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200930# define UChar uChar.UnicodeChar
Bram Moolenaar071d4272004-06-13 20:20:40 +0000931#endif
932
933/* The return code indicates key code size. */
934 static int
935#ifdef __BORLANDC__
936 __stdcall
937#endif
938win32_kbd_patch_key(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000939 KEY_EVENT_RECORD *pker)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000940{
941 UINT uMods = pker->dwControlKeyState;
942 static int s_iIsDead = 0;
943 static WORD awAnsiCode[2];
944 static BYTE abKeystate[256];
945
946
947 if (s_iIsDead == 2)
948 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200949 pker->UChar = (WCHAR) awAnsiCode[1];
Bram Moolenaar071d4272004-06-13 20:20:40 +0000950 s_iIsDead = 0;
951 return 1;
952 }
953
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200954 if (pker->UChar != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000955 return 1;
956
Bram Moolenaar7db5fc82010-05-24 11:59:29 +0200957 vim_memset(abKeystate, 0, sizeof (abKeystate));
Bram Moolenaar071d4272004-06-13 20:20:40 +0000958
Bram Moolenaar071d4272004-06-13 20:20:40 +0000959 /* Clear any pending dead keys */
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200960 ToUnicode(VK_SPACE, MapVirtualKey(VK_SPACE, 0), abKeystate, awAnsiCode, 2, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000961
962 if (uMods & SHIFT_PRESSED)
963 abKeystate[VK_SHIFT] = 0x80;
964 if (uMods & CAPSLOCK_ON)
965 abKeystate[VK_CAPITAL] = 1;
966
967 if ((uMods & ALT_GR) == ALT_GR)
968 {
969 abKeystate[VK_CONTROL] = abKeystate[VK_LCONTROL] =
970 abKeystate[VK_MENU] = abKeystate[VK_RMENU] = 0x80;
971 }
972
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200973 s_iIsDead = ToUnicode(pker->wVirtualKeyCode, pker->wVirtualScanCode,
974 abKeystate, awAnsiCode, 2, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000975
976 if (s_iIsDead > 0)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200977 pker->UChar = (WCHAR) awAnsiCode[0];
Bram Moolenaar071d4272004-06-13 20:20:40 +0000978
979 return s_iIsDead;
980}
981
982#ifdef _MSC_VER
983/* MUST switch optimization on again here, otherwise a call to
984 * decode_key_event() may crash (e.g. when hitting caps-lock) */
985# pragma optimize("", on)
Bram Moolenaar7b5f8322006-03-23 22:47:08 +0000986# pragma warning(pop)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000987
988# if (_MSC_VER < 1100)
989/* MUST turn off global optimisation for this next function, or
990 * pressing ctrl-minus in insert mode crashes Vim when built with
991 * VC4.1. -- negri. */
992# pragma optimize("g", off)
993# endif
994#endif
995
996static BOOL g_fJustGotFocus = FALSE;
997
998/*
999 * Decode a KEY_EVENT into one or two keystrokes
1000 */
1001 static BOOL
1002decode_key_event(
1003 KEY_EVENT_RECORD *pker,
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001004 WCHAR *pch,
1005 WCHAR *pch2,
Bram Moolenaar071d4272004-06-13 20:20:40 +00001006 int *pmodifiers,
1007 BOOL fDoPost)
1008{
1009 int i;
1010 const int nModifs = pker->dwControlKeyState & (SHIFT | ALT | CTRL);
1011
1012 *pch = *pch2 = NUL;
1013 g_fJustGotFocus = FALSE;
1014
1015 /* ignore key up events */
1016 if (!pker->bKeyDown)
1017 return FALSE;
1018
1019 /* ignore some keystrokes */
1020 switch (pker->wVirtualKeyCode)
1021 {
1022 /* modifiers */
1023 case VK_SHIFT:
1024 case VK_CONTROL:
1025 case VK_MENU: /* Alt key */
1026 return FALSE;
1027
1028 default:
1029 break;
1030 }
1031
1032 /* special cases */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001033 if ((nModifs & CTRL) != 0 && (nModifs & ~CTRL) == 0 && pker->UChar == NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001034 {
1035 /* Ctrl-6 is Ctrl-^ */
1036 if (pker->wVirtualKeyCode == '6')
1037 {
1038 *pch = Ctrl_HAT;
1039 return TRUE;
1040 }
1041 /* Ctrl-2 is Ctrl-@ */
1042 else if (pker->wVirtualKeyCode == '2')
1043 {
1044 *pch = NUL;
1045 return TRUE;
1046 }
1047 /* Ctrl-- is Ctrl-_ */
1048 else if (pker->wVirtualKeyCode == 0xBD)
1049 {
1050 *pch = Ctrl__;
1051 return TRUE;
1052 }
1053 }
1054
1055 /* Shift-TAB */
1056 if (pker->wVirtualKeyCode == VK_TAB && (nModifs & SHIFT_PRESSED))
1057 {
1058 *pch = K_NUL;
1059 *pch2 = '\017';
1060 return TRUE;
1061 }
1062
1063 for (i = sizeof(VirtKeyMap) / sizeof(VirtKeyMap[0]); --i >= 0; )
1064 {
1065 if (VirtKeyMap[i].wVirtKey == pker->wVirtualKeyCode)
1066 {
1067 if (nModifs == 0)
1068 *pch = VirtKeyMap[i].chAlone;
1069 else if ((nModifs & SHIFT) != 0 && (nModifs & ~SHIFT) == 0)
1070 *pch = VirtKeyMap[i].chShift;
1071 else if ((nModifs & CTRL) != 0 && (nModifs & ~CTRL) == 0)
1072 *pch = VirtKeyMap[i].chCtrl;
1073 else if ((nModifs & ALT) != 0 && (nModifs & ~ALT) == 0)
1074 *pch = VirtKeyMap[i].chAlt;
1075
1076 if (*pch != 0)
1077 {
1078 if (VirtKeyMap[i].fAnsiKey)
1079 {
1080 *pch2 = *pch;
1081 *pch = K_NUL;
1082 }
1083
1084 return TRUE;
1085 }
1086 }
1087 }
1088
1089 i = win32_kbd_patch_key(pker);
1090
1091 if (i < 0)
1092 *pch = NUL;
1093 else
1094 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001095 *pch = (i > 0) ? pker->UChar : NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001096
1097 if (pmodifiers != NULL)
1098 {
1099 /* Pass on the ALT key as a modifier, but only when not combined
1100 * with CTRL (which is ALTGR). */
1101 if ((nModifs & ALT) != 0 && (nModifs & CTRL) == 0)
1102 *pmodifiers |= MOD_MASK_ALT;
1103
1104 /* Pass on SHIFT only for special keys, because we don't know when
1105 * it's already included with the character. */
1106 if ((nModifs & SHIFT) != 0 && *pch <= 0x20)
1107 *pmodifiers |= MOD_MASK_SHIFT;
1108
1109 /* Pass on CTRL only for non-special keys, because we don't know
1110 * when it's already included with the character. And not when
1111 * combined with ALT (which is ALTGR). */
1112 if ((nModifs & CTRL) != 0 && (nModifs & ALT) == 0
1113 && *pch >= 0x20 && *pch < 0x80)
1114 *pmodifiers |= MOD_MASK_CTRL;
1115 }
1116 }
1117
1118 return (*pch != NUL);
1119}
1120
1121#ifdef _MSC_VER
1122# pragma optimize("", on)
1123#endif
1124
1125#endif /* FEAT_GUI_W32 */
1126
1127
1128#ifdef FEAT_MOUSE
1129
1130/*
1131 * For the GUI the mouse handling is in gui_w32.c.
1132 */
1133# ifdef FEAT_GUI_W32
1134 void
Bram Moolenaar1266d672017-02-01 13:43:36 +01001135mch_setmouse(int on UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001136{
1137}
1138# else
1139static int g_fMouseAvail = FALSE; /* mouse present */
1140static int g_fMouseActive = FALSE; /* mouse enabled */
1141static int g_nMouseClick = -1; /* mouse status */
1142static int g_xMouse; /* mouse x coordinate */
1143static int g_yMouse; /* mouse y coordinate */
1144
1145/*
1146 * Enable or disable mouse input
1147 */
1148 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001149mch_setmouse(int on)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001150{
1151 DWORD cmodein;
1152
1153 if (!g_fMouseAvail)
1154 return;
1155
1156 g_fMouseActive = on;
1157 GetConsoleMode(g_hConIn, &cmodein);
1158
1159 if (g_fMouseActive)
1160 cmodein |= ENABLE_MOUSE_INPUT;
1161 else
1162 cmodein &= ~ENABLE_MOUSE_INPUT;
1163
1164 SetConsoleMode(g_hConIn, cmodein);
1165}
1166
Bram Moolenaar157d8132018-03-06 17:09:20 +01001167
1168#if defined(FEAT_BEVAL_TERM) || defined(PROTO)
1169/*
1170 * Called when 'balloonevalterm' changed.
1171 */
1172 void
1173mch_bevalterm_changed(void)
1174{
1175 mch_setmouse(g_fMouseActive);
1176}
1177#endif
1178
Bram Moolenaar071d4272004-06-13 20:20:40 +00001179/*
1180 * Decode a MOUSE_EVENT. If it's a valid event, return MOUSE_LEFT,
1181 * MOUSE_MIDDLE, or MOUSE_RIGHT for a click; MOUSE_DRAG for a mouse
1182 * move with a button held down; and MOUSE_RELEASE after a MOUSE_DRAG
1183 * or a MOUSE_LEFT, _MIDDLE, or _RIGHT. We encode the button type,
1184 * the number of clicks, and the Shift/Ctrl/Alt modifiers in g_nMouseClick,
1185 * and we return the mouse position in g_xMouse and g_yMouse.
1186 *
1187 * Every MOUSE_LEFT, _MIDDLE, or _RIGHT will be followed by zero or more
1188 * MOUSE_DRAGs and one MOUSE_RELEASE. MOUSE_RELEASE will be followed only
1189 * by MOUSE_LEFT, _MIDDLE, or _RIGHT.
1190 *
1191 * For multiple clicks, we send, say, MOUSE_LEFT/1 click, MOUSE_RELEASE,
1192 * MOUSE_LEFT/2 clicks, MOUSE_RELEASE, MOUSE_LEFT/3 clicks, MOUSE_RELEASE, ....
1193 *
1194 * Windows will send us MOUSE_MOVED notifications whenever the mouse
1195 * moves, even if it stays within the same character cell. We ignore
1196 * all MOUSE_MOVED messages if the position hasn't really changed, and
1197 * we ignore all MOUSE_MOVED messages where no button is held down (i.e.,
1198 * we're only interested in MOUSE_DRAG).
1199 *
1200 * All of this is complicated by the code that fakes MOUSE_MIDDLE on
1201 * 2-button mouses by pressing the left & right buttons simultaneously.
1202 * In practice, it's almost impossible to click both at the same time,
1203 * so we need to delay a little. Also, we tend not to get MOUSE_RELEASE
1204 * in such cases, if the user is clicking quickly.
1205 */
1206 static BOOL
1207decode_mouse_event(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001208 MOUSE_EVENT_RECORD *pmer)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001209{
1210 static int s_nOldButton = -1;
1211 static int s_nOldMouseClick = -1;
1212 static int s_xOldMouse = -1;
1213 static int s_yOldMouse = -1;
1214 static linenr_T s_old_topline = 0;
1215#ifdef FEAT_DIFF
1216 static int s_old_topfill = 0;
1217#endif
1218 static int s_cClicks = 1;
1219 static BOOL s_fReleased = TRUE;
1220 static DWORD s_dwLastClickTime = 0;
1221 static BOOL s_fNextIsMiddle = FALSE;
1222
1223 static DWORD cButtons = 0; /* number of buttons supported */
1224
1225 const DWORD LEFT = FROM_LEFT_1ST_BUTTON_PRESSED;
1226 const DWORD MIDDLE = FROM_LEFT_2ND_BUTTON_PRESSED;
1227 const DWORD RIGHT = RIGHTMOST_BUTTON_PRESSED;
1228 const DWORD LEFT_RIGHT = LEFT | RIGHT;
1229
1230 int nButton;
1231
1232 if (cButtons == 0 && !GetNumberOfConsoleMouseButtons(&cButtons))
1233 cButtons = 2;
1234
1235 if (!g_fMouseAvail || !g_fMouseActive)
1236 {
1237 g_nMouseClick = -1;
1238 return FALSE;
1239 }
1240
1241 /* get a spurious MOUSE_EVENT immediately after receiving focus; ignore */
1242 if (g_fJustGotFocus)
1243 {
1244 g_fJustGotFocus = FALSE;
1245 return FALSE;
1246 }
1247
1248 /* unprocessed mouse click? */
1249 if (g_nMouseClick != -1)
1250 return TRUE;
1251
1252 nButton = -1;
1253 g_xMouse = pmer->dwMousePosition.X;
1254 g_yMouse = pmer->dwMousePosition.Y;
1255
1256 if (pmer->dwEventFlags == MOUSE_MOVED)
1257 {
Bram Moolenaar157d8132018-03-06 17:09:20 +01001258 /* Ignore MOUSE_MOVED events if (x, y) hasn't changed. (We get these
Bram Moolenaar071d4272004-06-13 20:20:40 +00001259 * events even when the mouse moves only within a char cell.) */
1260 if (s_xOldMouse == g_xMouse && s_yOldMouse == g_yMouse)
1261 return FALSE;
1262 }
1263
1264 /* If no buttons are pressed... */
1265 if ((pmer->dwButtonState & ((1 << cButtons) - 1)) == 0)
1266 {
Bram Moolenaar157d8132018-03-06 17:09:20 +01001267 nButton = MOUSE_RELEASE;
1268
Bram Moolenaar071d4272004-06-13 20:20:40 +00001269 /* If the last thing returned was MOUSE_RELEASE, ignore this */
1270 if (s_fReleased)
Bram Moolenaar157d8132018-03-06 17:09:20 +01001271 {
1272#ifdef FEAT_BEVAL_TERM
1273 /* do return mouse move events when we want them */
1274 if (p_bevalterm)
1275 nButton = MOUSE_DRAG;
1276 else
1277#endif
1278 return FALSE;
1279 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001280
Bram Moolenaar071d4272004-06-13 20:20:40 +00001281 s_fReleased = TRUE;
1282 }
1283 else /* one or more buttons pressed */
1284 {
1285 /* on a 2-button mouse, hold down left and right buttons
1286 * simultaneously to get MIDDLE. */
1287
1288 if (cButtons == 2 && s_nOldButton != MOUSE_DRAG)
1289 {
1290 DWORD dwLR = (pmer->dwButtonState & LEFT_RIGHT);
1291
1292 /* if either left or right button only is pressed, see if the
Bram Moolenaar84a05ac2013-05-06 04:24:17 +02001293 * next mouse event has both of them pressed */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001294 if (dwLR == LEFT || dwLR == RIGHT)
1295 {
1296 for (;;)
1297 {
1298 /* wait a short time for next input event */
1299 if (WaitForSingleObject(g_hConIn, p_mouset / 3)
1300 != WAIT_OBJECT_0)
1301 break;
1302 else
1303 {
1304 DWORD cRecords = 0;
1305 INPUT_RECORD ir;
1306 MOUSE_EVENT_RECORD* pmer2 = &ir.Event.MouseEvent;
1307
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001308 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001309
1310 if (cRecords == 0 || ir.EventType != MOUSE_EVENT
1311 || !(pmer2->dwButtonState & LEFT_RIGHT))
1312 break;
1313 else
1314 {
1315 if (pmer2->dwEventFlags != MOUSE_MOVED)
1316 {
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001317 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001318
1319 return decode_mouse_event(pmer2);
1320 }
1321 else if (s_xOldMouse == pmer2->dwMousePosition.X &&
1322 s_yOldMouse == pmer2->dwMousePosition.Y)
1323 {
1324 /* throw away spurious mouse move */
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001325 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001326
1327 /* are there any more mouse events in queue? */
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001328 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001329
1330 if (cRecords==0 || ir.EventType != MOUSE_EVENT)
1331 break;
1332 }
1333 else
1334 break;
1335 }
1336 }
1337 }
1338 }
1339 }
1340
1341 if (s_fNextIsMiddle)
1342 {
1343 nButton = (pmer->dwEventFlags == MOUSE_MOVED)
1344 ? MOUSE_DRAG : MOUSE_MIDDLE;
1345 s_fNextIsMiddle = FALSE;
1346 }
1347 else if (cButtons == 2 &&
1348 ((pmer->dwButtonState & LEFT_RIGHT) == LEFT_RIGHT))
1349 {
1350 nButton = MOUSE_MIDDLE;
1351
1352 if (! s_fReleased && pmer->dwEventFlags != MOUSE_MOVED)
1353 {
1354 s_fNextIsMiddle = TRUE;
1355 nButton = MOUSE_RELEASE;
1356 }
1357 }
1358 else if ((pmer->dwButtonState & LEFT) == LEFT)
1359 nButton = MOUSE_LEFT;
1360 else if ((pmer->dwButtonState & MIDDLE) == MIDDLE)
1361 nButton = MOUSE_MIDDLE;
1362 else if ((pmer->dwButtonState & RIGHT) == RIGHT)
1363 nButton = MOUSE_RIGHT;
1364
1365 if (! s_fReleased && ! s_fNextIsMiddle
1366 && nButton != s_nOldButton && s_nOldButton != MOUSE_DRAG)
1367 return FALSE;
1368
1369 s_fReleased = s_fNextIsMiddle;
1370 }
1371
1372 if (pmer->dwEventFlags == 0 || pmer->dwEventFlags == DOUBLE_CLICK)
1373 {
1374 /* button pressed or released, without mouse moving */
1375 if (nButton != -1 && nButton != MOUSE_RELEASE)
1376 {
1377 DWORD dwCurrentTime = GetTickCount();
1378
1379 if (s_xOldMouse != g_xMouse
1380 || s_yOldMouse != g_yMouse
1381 || s_nOldButton != nButton
1382 || s_old_topline != curwin->w_topline
1383#ifdef FEAT_DIFF
1384 || s_old_topfill != curwin->w_topfill
1385#endif
1386 || (int)(dwCurrentTime - s_dwLastClickTime) > p_mouset)
1387 {
1388 s_cClicks = 1;
1389 }
1390 else if (++s_cClicks > 4)
1391 {
1392 s_cClicks = 1;
1393 }
1394
1395 s_dwLastClickTime = dwCurrentTime;
1396 }
1397 }
1398 else if (pmer->dwEventFlags == MOUSE_MOVED)
1399 {
1400 if (nButton != -1 && nButton != MOUSE_RELEASE)
1401 nButton = MOUSE_DRAG;
1402
1403 s_cClicks = 1;
1404 }
1405
1406 if (nButton == -1)
1407 return FALSE;
1408
1409 if (nButton != MOUSE_RELEASE)
1410 s_nOldButton = nButton;
1411
1412 g_nMouseClick = nButton;
1413
1414 if (pmer->dwControlKeyState & SHIFT_PRESSED)
1415 g_nMouseClick |= MOUSE_SHIFT;
1416 if (pmer->dwControlKeyState & (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED))
1417 g_nMouseClick |= MOUSE_CTRL;
1418 if (pmer->dwControlKeyState & (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED))
1419 g_nMouseClick |= MOUSE_ALT;
1420
1421 if (nButton != MOUSE_DRAG && nButton != MOUSE_RELEASE)
1422 SET_NUM_MOUSE_CLICKS(g_nMouseClick, s_cClicks);
1423
1424 /* only pass on interesting (i.e., different) mouse events */
1425 if (s_xOldMouse == g_xMouse
1426 && s_yOldMouse == g_yMouse
1427 && s_nOldMouseClick == g_nMouseClick)
1428 {
1429 g_nMouseClick = -1;
1430 return FALSE;
1431 }
1432
1433 s_xOldMouse = g_xMouse;
1434 s_yOldMouse = g_yMouse;
1435 s_old_topline = curwin->w_topline;
1436#ifdef FEAT_DIFF
1437 s_old_topfill = curwin->w_topfill;
1438#endif
1439 s_nOldMouseClick = g_nMouseClick;
1440
1441 return TRUE;
1442}
1443
1444# endif /* FEAT_GUI_W32 */
1445#endif /* FEAT_MOUSE */
1446
1447
1448#ifdef MCH_CURSOR_SHAPE
1449/*
1450 * Set the shape of the cursor.
1451 * 'thickness' can be from 1 (thin) to 99 (block)
1452 */
1453 static void
1454mch_set_cursor_shape(int thickness)
1455{
1456 CONSOLE_CURSOR_INFO ConsoleCursorInfo;
1457 ConsoleCursorInfo.dwSize = thickness;
1458 ConsoleCursorInfo.bVisible = s_cursor_visible;
1459
1460 SetConsoleCursorInfo(g_hConOut, &ConsoleCursorInfo);
1461 if (s_cursor_visible)
1462 SetConsoleCursorPosition(g_hConOut, g_coord);
1463}
1464
1465 void
1466mch_update_cursor(void)
1467{
1468 int idx;
1469 int thickness;
1470
1471 /*
1472 * How the cursor is drawn depends on the current mode.
1473 */
1474 idx = get_shape_idx(FALSE);
1475
1476 if (shape_table[idx].shape == SHAPE_BLOCK)
1477 thickness = 99; /* 100 doesn't work on W95 */
1478 else
1479 thickness = shape_table[idx].percentage;
1480 mch_set_cursor_shape(thickness);
1481}
1482#endif
1483
1484#ifndef FEAT_GUI_W32 /* this isn't used for the GUI */
1485/*
1486 * Handle FOCUS_EVENT.
1487 */
1488 static void
1489handle_focus_event(INPUT_RECORD ir)
1490{
1491 g_fJustGotFocus = ir.Event.FocusEvent.bSetFocus;
1492 ui_focus_change((int)g_fJustGotFocus);
1493}
1494
1495/*
1496 * Wait until console input from keyboard or mouse is available,
1497 * or the time is up.
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001498 * When "ignore_input" is TRUE even wait when input is available.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001499 * Return TRUE if something is available FALSE if not.
1500 */
1501 static int
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001502WaitForChar(long msec, int ignore_input)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001503{
1504 DWORD dwNow = 0, dwEndTime = 0;
1505 INPUT_RECORD ir;
1506 DWORD cRecords;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001507 WCHAR ch, ch2;
Bram Moolenaar4445f7e2016-04-20 20:55:56 +02001508#ifdef FEAT_TIMERS
Bram Moolenaar40b1b542016-04-20 20:18:23 +02001509 int tb_change_cnt = typebuf.tb_change_cnt;
Bram Moolenaar4445f7e2016-04-20 20:55:56 +02001510#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001511
1512 if (msec > 0)
1513 /* Wait until the specified time has elapsed. */
1514 dwEndTime = GetTickCount() + msec;
1515 else if (msec < 0)
1516 /* Wait forever. */
1517 dwEndTime = INFINITE;
1518
1519 /* We need to loop until the end of the time period, because
1520 * we might get multiple unusable mouse events in that time.
1521 */
1522 for (;;)
1523 {
Bram Moolenaarca568ae2016-02-01 21:32:58 +01001524#ifdef MESSAGE_QUEUE
1525 parse_queued_messages();
1526#endif
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001527#ifdef FEAT_MZSCHEME
1528 mzvim_check_threads();
1529#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001530#ifdef FEAT_CLIENTSERVER
1531 serverProcessPendingMessages();
1532#endif
Bram Moolenaarf12d9832016-01-29 21:11:25 +01001533
Bram Moolenaar071d4272004-06-13 20:20:40 +00001534 if (0
1535#ifdef FEAT_MOUSE
1536 || g_nMouseClick != -1
1537#endif
1538#ifdef FEAT_CLIENTSERVER
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001539 || (!ignore_input && input_available())
Bram Moolenaar071d4272004-06-13 20:20:40 +00001540#endif
1541 )
1542 return TRUE;
1543
1544 if (msec > 0)
1545 {
Bram Moolenaarb7512b72013-08-10 12:45:09 +02001546 /* If the specified wait time has passed, return. Beware that
1547 * GetTickCount() may wrap around (overflow). */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001548 dwNow = GetTickCount();
Bram Moolenaarb7512b72013-08-10 12:45:09 +02001549 if ((int)(dwNow - dwEndTime) >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001550 break;
1551 }
1552 if (msec != 0)
1553 {
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001554 DWORD dwWaitTime = dwEndTime - dwNow;
1555
Bram Moolenaar509ce2a2016-03-11 22:52:15 +01001556#ifdef FEAT_JOB_CHANNEL
Bram Moolenaar8a8199e2016-11-26 15:13:33 +01001557 /* Check channel while waiting for input. */
Bram Moolenaar9186a272016-02-23 19:34:01 +01001558 if (dwWaitTime > 100)
Bram Moolenaar8a8199e2016-11-26 15:13:33 +01001559 {
Bram Moolenaar9186a272016-02-23 19:34:01 +01001560 dwWaitTime = 100;
Bram Moolenaar8a8199e2016-11-26 15:13:33 +01001561 /* If there is readahead then parse_queued_messages() timed out
1562 * and we should call it again soon. */
1563 if (channel_any_readahead())
1564 dwWaitTime = 10;
1565 }
Bram Moolenaar9186a272016-02-23 19:34:01 +01001566#endif
Bram Moolenaarc3719bd2017-11-18 22:13:31 +01001567#ifdef FEAT_BEVAL_GUI
Bram Moolenaar59716a22017-03-01 20:32:44 +01001568 if (p_beval && dwWaitTime > 100)
1569 /* The 'balloonexpr' may indirectly invoke a callback while
1570 * waiting for a character, need to check often. */
1571 dwWaitTime = 100;
1572#endif
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001573#ifdef FEAT_MZSCHEME
1574 if (mzthreads_allowed() && p_mzq > 0
1575 && (msec < 0 || (long)dwWaitTime > p_mzq))
1576 dwWaitTime = p_mzq; /* don't wait longer than 'mzquantum' */
1577#endif
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001578#ifdef FEAT_TIMERS
1579 {
1580 long due_time;
1581
1582 /* When waiting very briefly don't trigger timers. */
1583 if (dwWaitTime > 10)
1584 {
1585 /* Trigger timers and then get the time in msec until the
1586 * next one is due. Wait up to that time. */
1587 due_time = check_due_timer();
Bram Moolenaar40b1b542016-04-20 20:18:23 +02001588 if (typebuf.tb_change_cnt != tb_change_cnt)
1589 {
1590 /* timer may have used feedkeys() */
1591 return FALSE;
1592 }
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001593 if (due_time > 0 && dwWaitTime > (DWORD)due_time)
1594 dwWaitTime = due_time;
1595 }
1596 }
1597#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001598#ifdef FEAT_CLIENTSERVER
1599 /* Wait for either an event on the console input or a message in
1600 * the client-server window. */
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +02001601 if (msg_wait_for_multiple_objects(1, &g_hConIn, FALSE,
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001602 dwWaitTime, QS_SENDMESSAGE) != WAIT_OBJECT_0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001603#else
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +02001604 if (wait_for_single_object(g_hConIn, dwWaitTime) != WAIT_OBJECT_0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001605#endif
1606 continue;
1607 }
1608
1609 cRecords = 0;
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001610 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001611
1612#ifdef FEAT_MBYTE_IME
1613 if (State & CMDLINE && msg_row == Rows - 1)
1614 {
1615 CONSOLE_SCREEN_BUFFER_INFO csbi;
1616
1617 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
1618 {
1619 if (csbi.dwCursorPosition.Y != msg_row)
1620 {
1621 /* The screen is now messed up, must redraw the
1622 * command line and later all the windows. */
1623 redraw_all_later(CLEAR);
1624 cmdline_row -= (msg_row - csbi.dwCursorPosition.Y);
1625 redrawcmd();
1626 }
1627 }
1628 }
1629#endif
1630
1631 if (cRecords > 0)
1632 {
1633 if (ir.EventType == KEY_EVENT && ir.Event.KeyEvent.bKeyDown)
1634 {
1635#ifdef FEAT_MBYTE_IME
1636 /* Windows IME sends two '\n's with only one 'ENTER'. First:
1637 * wVirtualKeyCode == 13. second: wVirtualKeyCode == 0 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001638 if (ir.Event.KeyEvent.UChar == 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00001639 && ir.Event.KeyEvent.wVirtualKeyCode == 13)
1640 {
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001641 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001642 continue;
1643 }
1644#endif
1645 if (decode_key_event(&ir.Event.KeyEvent, &ch, &ch2,
1646 NULL, FALSE))
1647 return TRUE;
1648 }
1649
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001650 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001651
1652 if (ir.EventType == FOCUS_EVENT)
1653 handle_focus_event(ir);
1654 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
Bram Moolenaarc33ecb22018-02-11 16:40:45 +01001655 {
1656 /* Only call shell_resized() when the size actually change to
1657 * avoid the screen is cleard. */
1658 if (ir.Event.WindowBufferSizeEvent.dwSize.X != Columns
1659 || ir.Event.WindowBufferSizeEvent.dwSize.Y != Rows)
1660 shell_resized();
1661 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001662#ifdef FEAT_MOUSE
1663 else if (ir.EventType == MOUSE_EVENT
1664 && decode_mouse_event(&ir.Event.MouseEvent))
1665 return TRUE;
1666#endif
1667 }
1668 else if (msec == 0)
1669 break;
1670 }
1671
1672#ifdef FEAT_CLIENTSERVER
1673 /* Something might have been received while we were waiting. */
1674 if (input_available())
1675 return TRUE;
1676#endif
Bram Moolenaarf12d9832016-01-29 21:11:25 +01001677
Bram Moolenaar071d4272004-06-13 20:20:40 +00001678 return FALSE;
1679}
1680
1681#ifndef FEAT_GUI_MSWIN
1682/*
1683 * return non-zero if a character is available
1684 */
1685 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001686mch_char_avail(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001687{
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001688 return WaitForChar(0L, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001689}
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001690
1691# if defined(FEAT_TERMINAL) || defined(PROTO)
1692/*
1693 * Check for any pending input or messages.
1694 */
1695 int
1696mch_check_messages(void)
1697{
1698 return WaitForChar(0L, TRUE);
1699}
1700# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001701#endif
1702
1703/*
1704 * Create the console input. Used when reading stdin doesn't work.
1705 */
1706 static void
1707create_conin(void)
1708{
1709 g_hConIn = CreateFile("CONIN$", GENERIC_READ|GENERIC_WRITE,
1710 FILE_SHARE_READ|FILE_SHARE_WRITE,
1711 (LPSECURITY_ATTRIBUTES) NULL,
Bram Moolenaareb3593b2006-04-22 22:33:57 +00001712 OPEN_EXISTING, 0, (HANDLE)NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001713 did_create_conin = TRUE;
1714}
1715
1716/*
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001717 * Get a keystroke or a mouse event, use a blocking wait.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001718 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001719 static WCHAR
1720tgetch(int *pmodifiers, WCHAR *pch2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001721{
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001722 WCHAR ch;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001723
1724 for (;;)
1725 {
1726 INPUT_RECORD ir;
1727 DWORD cRecords = 0;
1728
1729#ifdef FEAT_CLIENTSERVER
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001730 (void)WaitForChar(-1L, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001731 if (input_available())
1732 return 0;
1733# ifdef FEAT_MOUSE
1734 if (g_nMouseClick != -1)
1735 return 0;
1736# endif
1737#endif
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001738 if (read_console_input(g_hConIn, &ir, 1, &cRecords) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001739 {
1740 if (did_create_conin)
1741 read_error_exit();
1742 create_conin();
1743 continue;
1744 }
1745
1746 if (ir.EventType == KEY_EVENT)
1747 {
1748 if (decode_key_event(&ir.Event.KeyEvent, &ch, pch2,
1749 pmodifiers, TRUE))
1750 return ch;
1751 }
1752 else if (ir.EventType == FOCUS_EVENT)
1753 handle_focus_event(ir);
1754 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
1755 shell_resized();
1756#ifdef FEAT_MOUSE
1757 else if (ir.EventType == MOUSE_EVENT)
1758 {
1759 if (decode_mouse_event(&ir.Event.MouseEvent))
1760 return 0;
1761 }
1762#endif
1763 }
1764}
1765#endif /* !FEAT_GUI_W32 */
1766
1767
1768/*
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02001769 * mch_inchar(): low-level input function.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001770 * Get one or more characters from the keyboard or the mouse.
1771 * If time == 0, do not wait for characters.
1772 * If time == n, wait a short time for characters.
1773 * If time == -1, wait forever for characters.
1774 * Returns the number of characters read into buf.
1775 */
1776 int
1777mch_inchar(
Bram Moolenaar1266d672017-02-01 13:43:36 +01001778 char_u *buf UNUSED,
1779 int maxlen UNUSED,
1780 long time UNUSED,
1781 int tb_change_cnt UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001782{
1783#ifndef FEAT_GUI_W32 /* this isn't used for the GUI */
1784
1785 int len;
1786 int c;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001787#define TYPEAHEADLEN 20
1788 static char_u typeahead[TYPEAHEADLEN]; /* previously typed bytes. */
1789 static int typeaheadlen = 0;
1790
1791 /* First use any typeahead that was kept because "buf" was too small. */
1792 if (typeaheadlen > 0)
1793 goto theend;
1794
Bram Moolenaar071d4272004-06-13 20:20:40 +00001795 if (time >= 0)
1796 {
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001797 if (!WaitForChar(time, FALSE)) /* no character available */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001798 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001799 }
1800 else /* time == -1, wait forever */
1801 {
1802 mch_set_winsize_now(); /* Allow winsize changes from now on */
1803
Bram Moolenaar3918c952005-03-15 22:34:55 +00001804 /*
1805 * If there is no character available within 2 seconds (default)
1806 * write the autoscript file to disk. Or cause the CursorHold event
1807 * to be triggered.
1808 */
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001809 if (!WaitForChar(p_ut, FALSE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001810 {
Bram Moolenaard35f9712005-12-18 22:02:33 +00001811 if (trigger_cursorhold() && maxlen >= 3)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001812 {
Bram Moolenaar3918c952005-03-15 22:34:55 +00001813 buf[0] = K_SPECIAL;
1814 buf[1] = KS_EXTRA;
1815 buf[2] = (int)KE_CURSORHOLD;
1816 return 3;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001817 }
Bram Moolenaar702517d2005-06-27 22:34:07 +00001818 before_blocking();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001819 }
1820 }
1821
1822 /*
1823 * Try to read as many characters as there are, until the buffer is full.
1824 */
1825
1826 /* we will get at least one key. Get more if they are available. */
1827 g_fCBrkPressed = FALSE;
1828
1829#ifdef MCH_WRITE_DUMP
1830 if (fdDump)
1831 fputc('[', fdDump);
1832#endif
1833
1834 /* Keep looping until there is something in the typeahead buffer and more
1835 * to get and still room in the buffer (up to two bytes for a char and
1836 * three bytes for a modifier). */
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001837 while ((typeaheadlen == 0 || WaitForChar(0L, FALSE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001838 && typeaheadlen + 5 <= TYPEAHEADLEN)
1839 {
1840 if (typebuf_changed(tb_change_cnt))
1841 {
1842 /* "buf" may be invalid now if a client put something in the
1843 * typeahead buffer and "buf" is in the typeahead buffer. */
1844 typeaheadlen = 0;
1845 break;
1846 }
1847#ifdef FEAT_MOUSE
1848 if (g_nMouseClick != -1)
1849 {
1850# ifdef MCH_WRITE_DUMP
1851 if (fdDump)
1852 fprintf(fdDump, "{%02x @ %d, %d}",
1853 g_nMouseClick, g_xMouse, g_yMouse);
1854# endif
1855 typeahead[typeaheadlen++] = ESC + 128;
1856 typeahead[typeaheadlen++] = 'M';
1857 typeahead[typeaheadlen++] = g_nMouseClick;
1858 typeahead[typeaheadlen++] = g_xMouse + '!';
1859 typeahead[typeaheadlen++] = g_yMouse + '!';
1860 g_nMouseClick = -1;
1861 }
1862 else
1863#endif
1864 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001865 WCHAR ch2 = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001866 int modifiers = 0;
1867
1868 c = tgetch(&modifiers, &ch2);
1869
1870 if (typebuf_changed(tb_change_cnt))
1871 {
1872 /* "buf" may be invalid now if a client put something in the
1873 * typeahead buffer and "buf" is in the typeahead buffer. */
1874 typeaheadlen = 0;
1875 break;
1876 }
1877
1878 if (c == Ctrl_C && ctrl_c_interrupts)
1879 {
1880#if defined(FEAT_CLIENTSERVER)
1881 trash_input_buf();
1882#endif
1883 got_int = TRUE;
1884 }
1885
1886#ifdef FEAT_MOUSE
1887 if (g_nMouseClick == -1)
1888#endif
1889 {
1890 int n = 1;
1891
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001892#ifdef FEAT_MBYTE
1893 if (ch2 == NUL)
1894 {
1895 int i;
1896 char_u *p;
1897 WCHAR ch[2];
1898
1899 ch[0] = c;
1900 if (c >= 0xD800 && c <= 0xDBFF) /* High surrogate */
1901 {
1902 ch[1] = tgetch(&modifiers, &ch2);
1903 n++;
1904 }
1905 p = utf16_to_enc(ch, &n);
1906 if (p != NULL)
1907 {
1908 for (i = 0; i < n; i++)
1909 typeahead[typeaheadlen + i] = p[i];
1910 vim_free(p);
1911 }
1912 }
1913 else
1914#endif
1915 typeahead[typeaheadlen] = c;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001916 if (ch2 != NUL)
1917 {
Bram Moolenaarfeeb4d02017-12-05 15:14:46 +01001918 if (c == K_NUL && (ch2 & 0xff00) != 0)
1919 {
1920 /* fAnsiKey with modifier keys */
1921 typeahead[typeaheadlen + n] = (char_u)ch2;
1922 n++;
1923 }
1924 else
1925 {
1926 typeahead[typeaheadlen + n] = 3;
1927 typeahead[typeaheadlen + n + 1] = (char_u)ch2;
1928 n += 2;
1929 }
Bram Moolenaar45500912014-07-09 20:51:07 +02001930 }
1931
Bram Moolenaar071d4272004-06-13 20:20:40 +00001932 /* Use the ALT key to set the 8th bit of the character
1933 * when it's one byte, the 8th bit isn't set yet and not
1934 * using a double-byte encoding (would become a lead
1935 * byte). */
1936 if ((modifiers & MOD_MASK_ALT)
1937 && n == 1
1938 && (typeahead[typeaheadlen] & 0x80) == 0
1939#ifdef FEAT_MBYTE
1940 && !enc_dbcs
1941#endif
1942 )
1943 {
Bram Moolenaar85a3e5c2007-11-20 16:22:16 +00001944#ifdef FEAT_MBYTE
1945 n = (*mb_char2bytes)(typeahead[typeaheadlen] | 0x80,
1946 typeahead + typeaheadlen);
1947#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00001948 typeahead[typeaheadlen] |= 0x80;
Bram Moolenaar85a3e5c2007-11-20 16:22:16 +00001949#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001950 modifiers &= ~MOD_MASK_ALT;
1951 }
1952
1953 if (modifiers != 0)
1954 {
1955 /* Prepend modifiers to the character. */
1956 mch_memmove(typeahead + typeaheadlen + 3,
1957 typeahead + typeaheadlen, n);
1958 typeahead[typeaheadlen++] = K_SPECIAL;
1959 typeahead[typeaheadlen++] = (char_u)KS_MODIFIER;
1960 typeahead[typeaheadlen++] = modifiers;
1961 }
1962
1963 typeaheadlen += n;
1964
1965#ifdef MCH_WRITE_DUMP
1966 if (fdDump)
1967 fputc(c, fdDump);
1968#endif
1969 }
1970 }
1971 }
1972
1973#ifdef MCH_WRITE_DUMP
1974 if (fdDump)
1975 {
1976 fputs("]\n", fdDump);
1977 fflush(fdDump);
1978 }
1979#endif
1980
Bram Moolenaar071d4272004-06-13 20:20:40 +00001981theend:
1982 /* Move typeahead to "buf", as much as fits. */
1983 len = 0;
1984 while (len < maxlen && typeaheadlen > 0)
1985 {
1986 buf[len++] = typeahead[0];
1987 mch_memmove(typeahead, typeahead + 1, --typeaheadlen);
1988 }
1989 return len;
1990
1991#else /* FEAT_GUI_W32 */
1992 return 0;
1993#endif /* FEAT_GUI_W32 */
1994}
1995
Bram Moolenaar82881492012-11-20 16:53:39 +01001996#ifndef PROTO
1997# ifndef __MINGW32__
1998# include <shellapi.h> /* required for FindExecutable() */
1999# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002000#endif
2001
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002002/*
Bram Moolenaar43663192017-03-05 14:29:12 +01002003 * If "use_path" is TRUE: Return TRUE if "name" is in $PATH.
2004 * If "use_path" is FALSE: Return TRUE if "name" exists.
2005 * When returning TRUE and "path" is not NULL save the path and set "*path" to
2006 * the allocated memory.
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00002007 * TODO: Should somehow check if it's really executable.
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002008 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002009 static int
Bram Moolenaar43663192017-03-05 14:29:12 +01002010executable_exists(char *name, char_u **path, int use_path)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002011{
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002012 char *dum;
2013 char fname[_MAX_PATH];
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02002014 char *curpath, *newpath;
2015 long n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002016
Bram Moolenaar43663192017-03-05 14:29:12 +01002017 if (!use_path)
2018 {
Bram Moolenaarf7e894d2017-03-05 19:49:13 +01002019 if (mch_getperm((char_u *)name) != -1 && !mch_isdir((char_u *)name))
Bram Moolenaar43663192017-03-05 14:29:12 +01002020 {
2021 if (path != NULL)
Bram Moolenaar066029e2017-03-05 15:19:32 +01002022 {
Bram Moolenaarf7e894d2017-03-05 19:49:13 +01002023 if (mch_isFullName((char_u *)name))
Bram Moolenaar066029e2017-03-05 15:19:32 +01002024 *path = vim_strsave((char_u *)name);
2025 else
2026 *path = FullName_save((char_u *)name, FALSE);
2027 }
Bram Moolenaar43663192017-03-05 14:29:12 +01002028 return TRUE;
2029 }
2030 return FALSE;
2031 }
2032
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002033#ifdef FEAT_MBYTE
2034 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002035 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002036 WCHAR *p = enc_to_utf16((char_u *)name, NULL);
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002037 WCHAR fnamew[_MAX_PATH];
2038 WCHAR *dumw;
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02002039 WCHAR *wcurpath, *wnewpath;
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002040
2041 if (p != NULL)
2042 {
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02002043 wcurpath = _wgetenv(L"PATH");
2044 wnewpath = (WCHAR*)alloc((unsigned)(wcslen(wcurpath) + 3)
2045 * sizeof(WCHAR));
2046 if (wnewpath == NULL)
2047 return FALSE;
2048 wcscpy(wnewpath, L".;");
2049 wcscat(wnewpath, wcurpath);
2050 n = (long)SearchPathW(wnewpath, p, NULL, _MAX_PATH, fnamew, &dumw);
2051 vim_free(wnewpath);
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002052 vim_free(p);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02002053 if (n == 0)
2054 return FALSE;
2055 if (GetFileAttributesW(fnamew) & FILE_ATTRIBUTE_DIRECTORY)
2056 return FALSE;
2057 if (path != NULL)
2058 *path = utf16_to_enc(fnamew, NULL);
2059 return TRUE;
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002060 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002061 }
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002062#endif
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02002063
2064 curpath = getenv("PATH");
2065 newpath = (char*)alloc((unsigned)(STRLEN(curpath) + 3));
2066 if (newpath == NULL)
2067 return FALSE;
2068 STRCPY(newpath, ".;");
2069 STRCAT(newpath, curpath);
2070 n = (long)SearchPath(newpath, name, NULL, _MAX_PATH, fname, &dum);
2071 vim_free(newpath);
2072 if (n == 0)
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002073 return FALSE;
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002074 if (mch_isdir((char_u *)fname))
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002075 return FALSE;
Bram Moolenaarc7f02552014-04-01 21:00:59 +02002076 if (path != NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002077 *path = vim_strsave((char_u *)fname);
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002078 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002079}
2080
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002081#if ((defined(__MINGW32__) || defined (__CYGWIN32__)) && \
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02002082 __MSVCRT_VERSION__ >= 0x800) || (defined(_MSC_VER) && _MSC_VER >= 1400)
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002083/*
2084 * Bad parameter handler.
2085 *
2086 * Certain MS CRT functions will intentionally crash when passed invalid
2087 * parameters to highlight possible security holes. Setting this function as
2088 * the bad parameter handler will prevent the crash.
2089 *
2090 * In debug builds the parameters contain CRT information that might help track
2091 * down the source of a problem, but in non-debug builds the arguments are all
2092 * NULL/0. Debug builds will also produce assert dialogs from the CRT, it is
2093 * worth allowing these to make debugging of issues easier.
2094 */
2095 static void
2096bad_param_handler(const wchar_t *expression,
2097 const wchar_t *function,
2098 const wchar_t *file,
2099 unsigned int line,
2100 uintptr_t pReserved)
2101{
2102}
2103
2104# define SET_INVALID_PARAM_HANDLER \
2105 ((void)_set_invalid_parameter_handler(bad_param_handler))
2106#else
2107# define SET_INVALID_PARAM_HANDLER
2108#endif
2109
Bram Moolenaar071d4272004-06-13 20:20:40 +00002110#ifdef FEAT_GUI_W32
2111
2112/*
2113 * GUI version of mch_init().
2114 */
2115 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002116mch_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002117{
2118#ifndef __MINGW32__
2119 extern int _fmode;
2120#endif
2121
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002122 /* Silently handle invalid parameters to CRT functions */
2123 SET_INVALID_PARAM_HANDLER;
2124
Bram Moolenaar071d4272004-06-13 20:20:40 +00002125 /* Let critical errors result in a failure, not in a dialog box. Required
2126 * for the timestamp test to work on removed floppies. */
2127 SetErrorMode(SEM_FAILCRITICALERRORS);
2128
2129 _fmode = O_BINARY; /* we do our own CR-LF translation */
2130
2131 /* Specify window size. Is there a place to get the default from? */
2132 Rows = 25;
2133 Columns = 80;
2134
2135 /* Look for 'vimrun' */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002136 {
2137 char_u vimrun_location[_MAX_PATH + 4];
2138
2139 /* First try in same directory as gvim.exe */
2140 STRCPY(vimrun_location, exe_name);
2141 STRCPY(gettail(vimrun_location), "vimrun.exe");
2142 if (mch_getperm(vimrun_location) >= 0)
2143 {
2144 if (*skiptowhite(vimrun_location) != NUL)
2145 {
2146 /* Enclose path with white space in double quotes. */
2147 mch_memmove(vimrun_location + 1, vimrun_location,
2148 STRLEN(vimrun_location) + 1);
2149 *vimrun_location = '"';
2150 STRCPY(gettail(vimrun_location), "vimrun\" ");
2151 }
2152 else
2153 STRCPY(gettail(vimrun_location), "vimrun ");
2154
2155 vimrun_path = (char *)vim_strsave(vimrun_location);
2156 s_dont_use_vimrun = FALSE;
2157 }
Bram Moolenaar43663192017-03-05 14:29:12 +01002158 else if (executable_exists("vimrun.exe", NULL, TRUE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002159 s_dont_use_vimrun = FALSE;
2160
2161 /* Don't give the warning for a missing vimrun.exe right now, but only
2162 * when vimrun was supposed to be used. Don't bother people that do
2163 * not need vimrun.exe. */
2164 if (s_dont_use_vimrun)
2165 need_vimrun_warning = TRUE;
2166 }
2167
2168 /*
2169 * If "finstr.exe" doesn't exist, use "grep -n" for 'grepprg'.
2170 * Otherwise the default "findstr /n" is used.
2171 */
Bram Moolenaar43663192017-03-05 14:29:12 +01002172 if (!executable_exists("findstr.exe", NULL, TRUE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002173 set_option_value((char_u *)"grepprg", 0, (char_u *)"grep -n", 0);
2174
2175#ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01002176 win_clip_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002177#endif
2178}
2179
2180
2181#else /* FEAT_GUI_W32 */
2182
2183#define SRWIDTH(sr) ((sr).Right - (sr).Left + 1)
2184#define SRHEIGHT(sr) ((sr).Bottom - (sr).Top + 1)
2185
2186/*
2187 * ClearConsoleBuffer()
2188 * Description:
2189 * Clears the entire contents of the console screen buffer, using the
2190 * specified attribute.
2191 * Returns:
2192 * TRUE on success
2193 */
2194 static BOOL
2195ClearConsoleBuffer(WORD wAttribute)
2196{
2197 CONSOLE_SCREEN_BUFFER_INFO csbi;
2198 COORD coord;
2199 DWORD NumCells, dummy;
2200
2201 if (!GetConsoleScreenBufferInfo(g_hConOut, &csbi))
2202 return FALSE;
2203
2204 NumCells = csbi.dwSize.X * csbi.dwSize.Y;
2205 coord.X = 0;
2206 coord.Y = 0;
2207 if (!FillConsoleOutputCharacter(g_hConOut, ' ', NumCells,
2208 coord, &dummy))
2209 {
2210 return FALSE;
2211 }
2212 if (!FillConsoleOutputAttribute(g_hConOut, wAttribute, NumCells,
2213 coord, &dummy))
2214 {
2215 return FALSE;
2216 }
2217
2218 return TRUE;
2219}
2220
2221/*
2222 * FitConsoleWindow()
2223 * Description:
2224 * Checks if the console window will fit within given buffer dimensions.
2225 * Also, if requested, will shrink the window to fit.
2226 * Returns:
2227 * TRUE on success
2228 */
2229 static BOOL
2230FitConsoleWindow(
2231 COORD dwBufferSize,
2232 BOOL WantAdjust)
2233{
2234 CONSOLE_SCREEN_BUFFER_INFO csbi;
2235 COORD dwWindowSize;
2236 BOOL NeedAdjust = FALSE;
2237
2238 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
2239 {
2240 /*
2241 * A buffer resize will fail if the current console window does
2242 * not lie completely within that buffer. To avoid this, we might
2243 * have to move and possibly shrink the window.
2244 */
2245 if (csbi.srWindow.Right >= dwBufferSize.X)
2246 {
2247 dwWindowSize.X = SRWIDTH(csbi.srWindow);
2248 if (dwWindowSize.X > dwBufferSize.X)
2249 dwWindowSize.X = dwBufferSize.X;
2250 csbi.srWindow.Right = dwBufferSize.X - 1;
2251 csbi.srWindow.Left = dwBufferSize.X - dwWindowSize.X;
2252 NeedAdjust = TRUE;
2253 }
2254 if (csbi.srWindow.Bottom >= dwBufferSize.Y)
2255 {
2256 dwWindowSize.Y = SRHEIGHT(csbi.srWindow);
2257 if (dwWindowSize.Y > dwBufferSize.Y)
2258 dwWindowSize.Y = dwBufferSize.Y;
2259 csbi.srWindow.Bottom = dwBufferSize.Y - 1;
2260 csbi.srWindow.Top = dwBufferSize.Y - dwWindowSize.Y;
2261 NeedAdjust = TRUE;
2262 }
2263 if (NeedAdjust && WantAdjust)
2264 {
2265 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &csbi.srWindow))
2266 return FALSE;
2267 }
2268 return TRUE;
2269 }
2270
2271 return FALSE;
2272}
2273
2274typedef struct ConsoleBufferStruct
2275{
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002276 BOOL IsValid;
2277 CONSOLE_SCREEN_BUFFER_INFO Info;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002278 PCHAR_INFO Buffer;
2279 COORD BufferSize;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002280 PSMALL_RECT Regions;
2281 int NumRegions;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002282} ConsoleBuffer;
2283
2284/*
2285 * SaveConsoleBuffer()
2286 * Description:
2287 * Saves important information about the console buffer, including the
2288 * actual buffer contents. The saved information is suitable for later
2289 * restoration by RestoreConsoleBuffer().
2290 * Returns:
2291 * TRUE if all information was saved; FALSE otherwise
2292 * If FALSE, still sets cb->IsValid if buffer characteristics were saved.
2293 */
2294 static BOOL
2295SaveConsoleBuffer(
2296 ConsoleBuffer *cb)
2297{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002298 DWORD NumCells;
2299 COORD BufferCoord;
2300 SMALL_RECT ReadRegion;
2301 WORD Y, Y_incr;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002302 int i, numregions;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002303
Bram Moolenaar071d4272004-06-13 20:20:40 +00002304 if (cb == NULL)
2305 return FALSE;
2306
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002307 if (!GetConsoleScreenBufferInfo(g_hConOut, &cb->Info))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002308 {
2309 cb->IsValid = FALSE;
2310 return FALSE;
2311 }
2312 cb->IsValid = TRUE;
2313
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002314 /*
2315 * Allocate a buffer large enough to hold the entire console screen
2316 * buffer. If this ConsoleBuffer structure has already been initialized
2317 * with a buffer of the correct size, then just use that one.
2318 */
2319 if (!cb->IsValid || cb->Buffer == NULL ||
2320 cb->BufferSize.X != cb->Info.dwSize.X ||
2321 cb->BufferSize.Y != cb->Info.dwSize.Y)
2322 {
2323 cb->BufferSize.X = cb->Info.dwSize.X;
2324 cb->BufferSize.Y = cb->Info.dwSize.Y;
2325 NumCells = cb->BufferSize.X * cb->BufferSize.Y;
2326 vim_free(cb->Buffer);
2327 cb->Buffer = (PCHAR_INFO)alloc(NumCells * sizeof(CHAR_INFO));
2328 if (cb->Buffer == NULL)
2329 return FALSE;
2330 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002331
2332 /*
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002333 * We will now copy the console screen buffer into our buffer.
2334 * ReadConsoleOutput() seems to be limited as far as how much you
2335 * can read at a time. Empirically, this number seems to be about
2336 * 12000 cells (rows * columns). Start at position (0, 0) and copy
2337 * in chunks until it is all copied. The chunks will all have the
2338 * same horizontal characteristics, so initialize them now. The
2339 * height of each chunk will be (12000 / width).
Bram Moolenaar071d4272004-06-13 20:20:40 +00002340 */
Bram Moolenaar61594242015-09-01 20:23:37 +02002341 BufferCoord.X = 0;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002342 ReadRegion.Left = 0;
2343 ReadRegion.Right = cb->Info.dwSize.X - 1;
2344 Y_incr = 12000 / cb->Info.dwSize.X;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002345
2346 numregions = (cb->Info.dwSize.Y + Y_incr - 1) / Y_incr;
2347 if (cb->Regions == NULL || numregions != cb->NumRegions)
2348 {
2349 cb->NumRegions = numregions;
2350 vim_free(cb->Regions);
2351 cb->Regions = (PSMALL_RECT)alloc(cb->NumRegions * sizeof(SMALL_RECT));
2352 if (cb->Regions == NULL)
2353 {
Bram Moolenaard23a8232018-02-10 18:45:26 +01002354 VIM_CLEAR(cb->Buffer);
Bram Moolenaar444fda22017-08-11 20:37:00 +02002355 return FALSE;
2356 }
2357 }
2358
2359 for (i = 0, Y = 0; i < cb->NumRegions; i++, Y += Y_incr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002360 {
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002361 /*
2362 * Read into position (0, Y) in our buffer.
2363 */
2364 BufferCoord.Y = Y;
2365 /*
2366 * Read the region whose top left corner is (0, Y) and whose bottom
2367 * right corner is (width - 1, Y + Y_incr - 1). This should define
2368 * a region of size width by Y_incr. Don't worry if this region is
2369 * too large for the remaining buffer; it will be cropped.
2370 */
2371 ReadRegion.Top = Y;
2372 ReadRegion.Bottom = Y + Y_incr - 1;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002373 if (!ReadConsoleOutputW(g_hConOut, /* output handle */
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002374 cb->Buffer, /* our buffer */
2375 cb->BufferSize, /* dimensions of our buffer */
2376 BufferCoord, /* offset in our buffer */
2377 &ReadRegion)) /* region to save */
2378 {
Bram Moolenaard23a8232018-02-10 18:45:26 +01002379 VIM_CLEAR(cb->Buffer);
2380 VIM_CLEAR(cb->Regions);
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002381 return FALSE;
2382 }
Bram Moolenaar444fda22017-08-11 20:37:00 +02002383 cb->Regions[i] = ReadRegion;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002384 }
2385
2386 return TRUE;
2387}
2388
2389/*
2390 * RestoreConsoleBuffer()
2391 * Description:
2392 * Restores important information about the console buffer, including the
2393 * actual buffer contents, if desired. The information to restore is in
2394 * the same format used by SaveConsoleBuffer().
2395 * Returns:
2396 * TRUE on success
2397 */
2398 static BOOL
2399RestoreConsoleBuffer(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002400 ConsoleBuffer *cb,
2401 BOOL RestoreScreen)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002402{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002403 COORD BufferCoord;
2404 SMALL_RECT WriteRegion;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002405 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002406
2407 if (cb == NULL || !cb->IsValid)
2408 return FALSE;
2409
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002410 /*
2411 * Before restoring the buffer contents, clear the current buffer, and
2412 * restore the cursor position and window information. Doing this now
2413 * prevents old buffer contents from "flashing" onto the screen.
2414 */
2415 if (RestoreScreen)
2416 ClearConsoleBuffer(cb->Info.wAttributes);
2417
2418 FitConsoleWindow(cb->Info.dwSize, TRUE);
2419 if (!SetConsoleScreenBufferSize(g_hConOut, cb->Info.dwSize))
2420 return FALSE;
2421 if (!SetConsoleTextAttribute(g_hConOut, cb->Info.wAttributes))
2422 return FALSE;
2423
2424 if (!RestoreScreen)
2425 {
2426 /*
2427 * No need to restore the screen buffer contents, so we're done.
2428 */
2429 return TRUE;
2430 }
2431
2432 if (!SetConsoleCursorPosition(g_hConOut, cb->Info.dwCursorPosition))
2433 return FALSE;
2434 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &cb->Info.srWindow))
2435 return FALSE;
2436
2437 /*
2438 * Restore the screen buffer contents.
2439 */
2440 if (cb->Buffer != NULL)
2441 {
Bram Moolenaar444fda22017-08-11 20:37:00 +02002442 for (i = 0; i < cb->NumRegions; i++)
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002443 {
Bram Moolenaar444fda22017-08-11 20:37:00 +02002444 BufferCoord.X = cb->Regions[i].Left;
2445 BufferCoord.Y = cb->Regions[i].Top;
2446 WriteRegion = cb->Regions[i];
2447 if (!WriteConsoleOutputW(g_hConOut, /* output handle */
2448 cb->Buffer, /* our buffer */
2449 cb->BufferSize, /* dimensions of our buffer */
2450 BufferCoord, /* offset in our buffer */
2451 &WriteRegion)) /* region to restore */
2452 {
2453 return FALSE;
2454 }
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002455 }
2456 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002457
2458 return TRUE;
2459}
2460
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002461#define FEAT_RESTORE_ORIG_SCREEN
2462#ifdef FEAT_RESTORE_ORIG_SCREEN
2463static ConsoleBuffer g_cbOrig = { 0 };
2464#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002465static ConsoleBuffer g_cbNonTermcap = { 0 };
2466static ConsoleBuffer g_cbTermcap = { 0 };
2467
2468#ifdef FEAT_TITLE
2469#ifdef __BORLANDC__
2470typedef HWND (__stdcall *GETCONSOLEWINDOWPROC)(VOID);
2471#else
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002472typedef HWND (WINAPI *GETCONSOLEWINDOWPROC)(VOID);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002473#endif
2474char g_szOrigTitle[256] = { 0 };
2475HWND g_hWnd = NULL; /* also used in os_mswin.c */
2476static HICON g_hOrigIconSmall = NULL;
2477static HICON g_hOrigIcon = NULL;
2478static HICON g_hVimIcon = NULL;
2479static BOOL g_fCanChangeIcon = FALSE;
2480
2481/* ICON* are not defined in VC++ 4.0 */
2482#ifndef ICON_SMALL
2483#define ICON_SMALL 0
2484#endif
2485#ifndef ICON_BIG
2486#define ICON_BIG 1
2487#endif
2488/*
2489 * GetConsoleIcon()
2490 * Description:
2491 * Attempts to retrieve the small icon and/or the big icon currently in
2492 * use by a given window.
2493 * Returns:
2494 * TRUE on success
2495 */
2496 static BOOL
2497GetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002498 HWND hWnd,
2499 HICON *phIconSmall,
2500 HICON *phIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002501{
2502 if (hWnd == NULL)
2503 return FALSE;
2504
2505 if (phIconSmall != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002506 *phIconSmall = (HICON)SendMessage(hWnd, WM_GETICON,
2507 (WPARAM)ICON_SMALL, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002508 if (phIcon != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002509 *phIcon = (HICON)SendMessage(hWnd, WM_GETICON,
2510 (WPARAM)ICON_BIG, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002511 return TRUE;
2512}
2513
2514/*
2515 * SetConsoleIcon()
2516 * Description:
2517 * Attempts to change the small icon and/or the big icon currently in
2518 * use by a given window.
2519 * Returns:
2520 * TRUE on success
2521 */
2522 static BOOL
2523SetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002524 HWND hWnd,
2525 HICON hIconSmall,
2526 HICON hIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002527{
Bram Moolenaar071d4272004-06-13 20:20:40 +00002528 if (hWnd == NULL)
2529 return FALSE;
2530
2531 if (hIconSmall != NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002532 SendMessage(hWnd, WM_SETICON,
2533 (WPARAM)ICON_SMALL, (LPARAM)hIconSmall);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002534 if (hIcon != NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002535 SendMessage(hWnd, WM_SETICON,
2536 (WPARAM)ICON_BIG, (LPARAM) hIcon);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002537 return TRUE;
2538}
2539
2540/*
2541 * SaveConsoleTitleAndIcon()
2542 * Description:
2543 * Saves the current console window title in g_szOrigTitle, for later
2544 * restoration. Also, attempts to obtain a handle to the console window,
2545 * and use it to save the small and big icons currently in use by the
2546 * console window. This is not always possible on some versions of Windows;
2547 * nor is it possible when running Vim remotely using Telnet (since the
2548 * console window the user sees is owned by a remote process).
2549 */
2550 static void
2551SaveConsoleTitleAndIcon(void)
2552{
Bram Moolenaar071d4272004-06-13 20:20:40 +00002553 /* Save the original title. */
2554 if (!GetConsoleTitle(g_szOrigTitle, sizeof(g_szOrigTitle)))
2555 return;
2556
2557 /*
2558 * Obtain a handle to the console window using GetConsoleWindow() from
2559 * KERNEL32.DLL; we need to handle in order to change the window icon.
2560 * This function only exists on NT-based Windows, starting with Windows
2561 * 2000. On older operating systems, we can't change the window icon
2562 * anyway.
2563 */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02002564 g_hWnd = GetConsoleWindow();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002565 if (g_hWnd == NULL)
2566 return;
2567
2568 /* Save the original console window icon. */
2569 GetConsoleIcon(g_hWnd, &g_hOrigIconSmall, &g_hOrigIcon);
2570 if (g_hOrigIconSmall == NULL || g_hOrigIcon == NULL)
2571 return;
2572
2573 /* Extract the first icon contained in the Vim executable. */
Bram Moolenaarcddc91c2014-09-23 21:53:41 +02002574 if (mch_icon_load((HANDLE *)&g_hVimIcon) == FAIL || g_hVimIcon == NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002575 g_hVimIcon = ExtractIcon(NULL, (LPCSTR)exe_name, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002576 if (g_hVimIcon != NULL)
2577 g_fCanChangeIcon = TRUE;
2578}
2579#endif
2580
2581static int g_fWindInitCalled = FALSE;
2582static int g_fTermcapMode = FALSE;
2583static CONSOLE_CURSOR_INFO g_cci;
2584static DWORD g_cmodein = 0;
2585static DWORD g_cmodeout = 0;
2586
2587/*
2588 * non-GUI version of mch_init().
2589 */
2590 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002591mch_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002592{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002593#ifndef FEAT_RESTORE_ORIG_SCREEN
2594 CONSOLE_SCREEN_BUFFER_INFO csbi;
2595#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002596#ifndef __MINGW32__
2597 extern int _fmode;
2598#endif
2599
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002600 /* Silently handle invalid parameters to CRT functions */
2601 SET_INVALID_PARAM_HANDLER;
2602
Bram Moolenaar071d4272004-06-13 20:20:40 +00002603 /* Let critical errors result in a failure, not in a dialog box. Required
2604 * for the timestamp test to work on removed floppies. */
2605 SetErrorMode(SEM_FAILCRITICALERRORS);
2606
2607 _fmode = O_BINARY; /* we do our own CR-LF translation */
2608 out_flush();
2609
2610 /* Obtain handles for the standard Console I/O devices */
2611 if (read_cmd_fd == 0)
2612 g_hConIn = GetStdHandle(STD_INPUT_HANDLE);
2613 else
2614 create_conin();
2615 g_hConOut = GetStdHandle(STD_OUTPUT_HANDLE);
2616
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002617#ifdef FEAT_RESTORE_ORIG_SCREEN
2618 /* Save the initial console buffer for later restoration */
2619 SaveConsoleBuffer(&g_cbOrig);
2620 g_attrCurrent = g_attrDefault = g_cbOrig.Info.wAttributes;
2621#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00002622 /* Get current text attributes */
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002623 GetConsoleScreenBufferInfo(g_hConOut, &csbi);
2624 g_attrCurrent = g_attrDefault = csbi.wAttributes;
2625#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002626 if (cterm_normal_fg_color == 0)
2627 cterm_normal_fg_color = (g_attrCurrent & 0xf) + 1;
2628 if (cterm_normal_bg_color == 0)
2629 cterm_normal_bg_color = ((g_attrCurrent >> 4) & 0xf) + 1;
2630
2631 /* set termcap codes to current text attributes */
2632 update_tcap(g_attrCurrent);
2633
2634 GetConsoleCursorInfo(g_hConOut, &g_cci);
2635 GetConsoleMode(g_hConIn, &g_cmodein);
2636 GetConsoleMode(g_hConOut, &g_cmodeout);
2637
2638#ifdef FEAT_TITLE
2639 SaveConsoleTitleAndIcon();
2640 /*
2641 * Set both the small and big icons of the console window to Vim's icon.
2642 * Note that Vim presently only has one size of icon (32x32), but it
2643 * automatically gets scaled down to 16x16 when setting the small icon.
2644 */
2645 if (g_fCanChangeIcon)
2646 SetConsoleIcon(g_hWnd, g_hVimIcon, g_hVimIcon);
2647#endif
2648
2649 ui_get_shellsize();
2650
2651#ifdef MCH_WRITE_DUMP
2652 fdDump = fopen("dump", "wt");
2653
2654 if (fdDump)
2655 {
2656 time_t t;
2657
2658 time(&t);
2659 fputs(ctime(&t), fdDump);
2660 fflush(fdDump);
2661 }
2662#endif
2663
2664 g_fWindInitCalled = TRUE;
2665
2666#ifdef FEAT_MOUSE
2667 g_fMouseAvail = GetSystemMetrics(SM_MOUSEPRESENT);
2668#endif
2669
2670#ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01002671 win_clip_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002672#endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01002673
2674 vtp_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002675}
2676
2677/*
2678 * non-GUI version of mch_exit().
2679 * Shut down and exit with status `r'
2680 * Careful: mch_exit() may be called before mch_init()!
2681 */
2682 void
2683mch_exit(int r)
2684{
Bram Moolenaar955f1982017-02-05 15:10:51 +01002685 exiting = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002686
Bram Moolenaarcafafb32018-02-22 21:07:09 +01002687 vtp_exit();
2688
Bram Moolenaar955f1982017-02-05 15:10:51 +01002689 stoptermcap();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002690 if (g_fWindInitCalled)
2691 settmode(TMODE_COOK);
2692
2693 ml_close_all(TRUE); /* remove all memfiles */
2694
2695 if (g_fWindInitCalled)
2696 {
2697#ifdef FEAT_TITLE
Bram Moolenaar40385db2018-08-07 22:31:44 +02002698 mch_restore_title(SAVE_RESTORE_BOTH);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002699 /*
2700 * Restore both the small and big icons of the console window to
2701 * what they were at startup. Don't do this when the window is
2702 * closed, Vim would hang here.
2703 */
2704 if (g_fCanChangeIcon && !g_fForceExit)
2705 SetConsoleIcon(g_hWnd, g_hOrigIconSmall, g_hOrigIcon);
2706#endif
2707
2708#ifdef MCH_WRITE_DUMP
2709 if (fdDump)
2710 {
2711 time_t t;
2712
2713 time(&t);
2714 fputs(ctime(&t), fdDump);
2715 fclose(fdDump);
2716 }
2717 fdDump = NULL;
2718#endif
2719 }
2720
2721 SetConsoleCursorInfo(g_hConOut, &g_cci);
2722 SetConsoleMode(g_hConIn, g_cmodein);
2723 SetConsoleMode(g_hConOut, g_cmodeout);
2724
2725#ifdef DYNAMIC_GETTEXT
2726 dyn_libintl_end();
2727#endif
2728
2729 exit(r);
2730}
2731#endif /* !FEAT_GUI_W32 */
2732
Bram Moolenaar071d4272004-06-13 20:20:40 +00002733/*
2734 * Do we have an interactive window?
2735 */
2736 int
2737mch_check_win(
Bram Moolenaar1266d672017-02-01 13:43:36 +01002738 int argc UNUSED,
2739 char **argv UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002740{
2741 get_exe_name();
2742
2743#ifdef FEAT_GUI_W32
2744 return OK; /* GUI always has a tty */
2745#else
2746 if (isatty(1))
2747 return OK;
2748 return FAIL;
2749#endif
2750}
2751
2752
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002753#ifdef FEAT_MBYTE
2754/*
2755 * fname_casew(): Wide version of fname_case(). Set the case of the file name,
2756 * if it already exists. When "len" is > 0, also expand short to long
2757 * filenames.
2758 * Return FAIL if wide functions are not available, OK otherwise.
2759 * NOTE: much of this is identical to fname_case(), keep in sync!
2760 */
2761 static int
2762fname_casew(
2763 WCHAR *name,
2764 int len)
2765{
2766 WCHAR szTrueName[_MAX_PATH + 2];
2767 WCHAR szTrueNameTemp[_MAX_PATH + 2];
2768 WCHAR *ptrue, *ptruePrev;
2769 WCHAR *porig, *porigPrev;
2770 int flen;
2771 WIN32_FIND_DATAW fb;
Bram Moolenaar73c61632013-12-07 14:48:10 +01002772 HANDLE hFind = INVALID_HANDLE_VALUE;
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002773 int c;
2774 int slen;
2775
2776 flen = (int)wcslen(name);
2777 if (flen > _MAX_PATH)
2778 return OK;
2779
2780 /* slash_adjust(name) not needed, already adjusted by fname_case(). */
2781
2782 /* Build the new name in szTrueName[] one component at a time. */
2783 porig = name;
2784 ptrue = szTrueName;
2785
2786 if (iswalpha(porig[0]) && porig[1] == L':')
2787 {
2788 /* copy leading drive letter */
2789 *ptrue++ = *porig++;
2790 *ptrue++ = *porig++;
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002791 }
Bram Moolenaar73c61632013-12-07 14:48:10 +01002792 *ptrue = NUL; /* in case nothing follows */
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002793
2794 while (*porig != NUL)
2795 {
2796 /* copy \ characters */
2797 while (*porig == psepc)
2798 *ptrue++ = *porig++;
2799
2800 ptruePrev = ptrue;
2801 porigPrev = porig;
2802 while (*porig != NUL && *porig != psepc)
2803 {
2804 *ptrue++ = *porig++;
2805 }
2806 *ptrue = NUL;
2807
2808 /* To avoid a slow failure append "\*" when searching a directory,
2809 * server or network share. */
2810 wcscpy(szTrueNameTemp, szTrueName);
2811 slen = (int)wcslen(szTrueNameTemp);
2812 if (*porig == psepc && slen + 2 < _MAX_PATH)
2813 wcscpy(szTrueNameTemp + slen, L"\\*");
2814
2815 /* Skip "", "." and "..". */
2816 if (ptrue > ptruePrev
2817 && (ptruePrev[0] != L'.'
2818 || (ptruePrev[1] != NUL
2819 && (ptruePrev[1] != L'.' || ptruePrev[2] != NUL)))
2820 && (hFind = FindFirstFileW(szTrueNameTemp, &fb))
2821 != INVALID_HANDLE_VALUE)
2822 {
2823 c = *porig;
2824 *porig = NUL;
2825
2826 /* Only use the match when it's the same name (ignoring case) or
2827 * expansion is allowed and there is a match with the short name
2828 * and there is enough room. */
2829 if (_wcsicoll(porigPrev, fb.cFileName) == 0
2830 || (len > 0
2831 && (_wcsicoll(porigPrev, fb.cAlternateFileName) == 0
2832 && (int)(ptruePrev - szTrueName)
2833 + (int)wcslen(fb.cFileName) < len)))
2834 {
2835 wcscpy(ptruePrev, fb.cFileName);
2836
2837 /* Look for exact match and prefer it if found. Must be a
2838 * long name, otherwise there would be only one match. */
2839 while (FindNextFileW(hFind, &fb))
2840 {
2841 if (*fb.cAlternateFileName != NUL
2842 && (wcscoll(porigPrev, fb.cFileName) == 0
2843 || (len > 0
2844 && (_wcsicoll(porigPrev,
2845 fb.cAlternateFileName) == 0
2846 && (int)(ptruePrev - szTrueName)
2847 + (int)wcslen(fb.cFileName) < len))))
2848 {
2849 wcscpy(ptruePrev, fb.cFileName);
2850 break;
2851 }
2852 }
2853 }
2854 FindClose(hFind);
2855 *porig = c;
2856 ptrue = ptruePrev + wcslen(ptruePrev);
2857 }
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002858 }
2859
2860 wcscpy(name, szTrueName);
2861 return OK;
2862}
2863#endif
2864
Bram Moolenaar071d4272004-06-13 20:20:40 +00002865/*
2866 * fname_case(): Set the case of the file name, if it already exists.
2867 * When "len" is > 0, also expand short to long filenames.
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002868 * NOTE: much of this is identical to fname_casew(), keep in sync!
Bram Moolenaar071d4272004-06-13 20:20:40 +00002869 */
2870 void
2871fname_case(
2872 char_u *name,
2873 int len)
2874{
2875 char szTrueName[_MAX_PATH + 2];
Bram Moolenaar464c9252010-10-13 20:37:41 +02002876 char szTrueNameTemp[_MAX_PATH + 2];
Bram Moolenaar071d4272004-06-13 20:20:40 +00002877 char *ptrue, *ptruePrev;
2878 char *porig, *porigPrev;
2879 int flen;
2880 WIN32_FIND_DATA fb;
2881 HANDLE hFind;
2882 int c;
Bram Moolenaar464c9252010-10-13 20:37:41 +02002883 int slen;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002884
Bram Moolenaara3ffd9c2005-07-21 21:03:15 +00002885 flen = (int)STRLEN(name);
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002886 if (flen == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002887 return;
2888
2889 slash_adjust(name);
2890
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002891#ifdef FEAT_MBYTE
2892 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2893 {
2894 WCHAR *p = enc_to_utf16(name, NULL);
2895
2896 if (p != NULL)
2897 {
2898 char_u *q;
Bram Moolenaar21d89b62014-10-07 10:38:40 +02002899 WCHAR buf[_MAX_PATH + 1];
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002900
Bram Moolenaar21d89b62014-10-07 10:38:40 +02002901 wcsncpy(buf, p, _MAX_PATH);
2902 buf[_MAX_PATH] = L'\0';
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002903 vim_free(p);
2904
2905 if (fname_casew(buf, (len > 0) ? _MAX_PATH : 0) == OK)
2906 {
2907 q = utf16_to_enc(buf, NULL);
2908 if (q != NULL)
2909 {
2910 vim_strncpy(name, q, (len > 0) ? len - 1 : flen);
2911 vim_free(q);
2912 return;
2913 }
2914 }
2915 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02002916 return;
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002917 }
2918#endif
2919
2920 /* If 'enc' is utf-8, flen can be larger than _MAX_PATH.
2921 * So we should check this after calling wide function. */
2922 if (flen > _MAX_PATH)
2923 return;
2924
Bram Moolenaar071d4272004-06-13 20:20:40 +00002925 /* Build the new name in szTrueName[] one component at a time. */
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002926 porig = (char *)name;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002927 ptrue = szTrueName;
2928
2929 if (isalpha(porig[0]) && porig[1] == ':')
2930 {
2931 /* copy leading drive letter */
2932 *ptrue++ = *porig++;
2933 *ptrue++ = *porig++;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002934 }
Bram Moolenaar73c61632013-12-07 14:48:10 +01002935 *ptrue = NUL; /* in case nothing follows */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002936
2937 while (*porig != NUL)
2938 {
2939 /* copy \ characters */
2940 while (*porig == psepc)
2941 *ptrue++ = *porig++;
2942
2943 ptruePrev = ptrue;
2944 porigPrev = porig;
2945 while (*porig != NUL && *porig != psepc)
2946 {
2947#ifdef FEAT_MBYTE
2948 int l;
2949
2950 if (enc_dbcs)
2951 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002952 l = (*mb_ptr2len)((char_u *)porig);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002953 while (--l >= 0)
2954 *ptrue++ = *porig++;
2955 }
2956 else
2957#endif
2958 *ptrue++ = *porig++;
2959 }
2960 *ptrue = NUL;
2961
Bram Moolenaar464c9252010-10-13 20:37:41 +02002962 /* To avoid a slow failure append "\*" when searching a directory,
2963 * server or network share. */
2964 STRCPY(szTrueNameTemp, szTrueName);
Bram Moolenaar6b5ef062010-10-27 12:18:00 +02002965 slen = (int)strlen(szTrueNameTemp);
Bram Moolenaar464c9252010-10-13 20:37:41 +02002966 if (*porig == psepc && slen + 2 < _MAX_PATH)
2967 STRCPY(szTrueNameTemp + slen, "\\*");
2968
Bram Moolenaar071d4272004-06-13 20:20:40 +00002969 /* Skip "", "." and "..". */
2970 if (ptrue > ptruePrev
2971 && (ptruePrev[0] != '.'
2972 || (ptruePrev[1] != NUL
2973 && (ptruePrev[1] != '.' || ptruePrev[2] != NUL)))
Bram Moolenaar464c9252010-10-13 20:37:41 +02002974 && (hFind = FindFirstFile(szTrueNameTemp, &fb))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002975 != INVALID_HANDLE_VALUE)
2976 {
2977 c = *porig;
2978 *porig = NUL;
2979
2980 /* Only use the match when it's the same name (ignoring case) or
2981 * expansion is allowed and there is a match with the short name
2982 * and there is enough room. */
2983 if (_stricoll(porigPrev, fb.cFileName) == 0
2984 || (len > 0
2985 && (_stricoll(porigPrev, fb.cAlternateFileName) == 0
2986 && (int)(ptruePrev - szTrueName)
2987 + (int)strlen(fb.cFileName) < len)))
2988 {
2989 STRCPY(ptruePrev, fb.cFileName);
2990
2991 /* Look for exact match and prefer it if found. Must be a
2992 * long name, otherwise there would be only one match. */
2993 while (FindNextFile(hFind, &fb))
2994 {
2995 if (*fb.cAlternateFileName != NUL
2996 && (strcoll(porigPrev, fb.cFileName) == 0
2997 || (len > 0
2998 && (_stricoll(porigPrev,
2999 fb.cAlternateFileName) == 0
3000 && (int)(ptruePrev - szTrueName)
3001 + (int)strlen(fb.cFileName) < len))))
3002 {
3003 STRCPY(ptruePrev, fb.cFileName);
3004 break;
3005 }
3006 }
3007 }
3008 FindClose(hFind);
3009 *porig = c;
3010 ptrue = ptruePrev + strlen(ptruePrev);
3011 }
3012 }
3013
3014 STRCPY(name, szTrueName);
3015}
3016
3017
3018/*
3019 * Insert user name in s[len].
3020 */
3021 int
3022mch_get_user_name(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003023 char_u *s,
3024 int len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003025{
Bram Moolenaar41a09032007-10-01 18:34:34 +00003026 char szUserName[256 + 1]; /* UNLEN is 256 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003027 DWORD cch = sizeof szUserName;
3028
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003029#ifdef FEAT_MBYTE
3030 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3031 {
3032 WCHAR wszUserName[256 + 1]; /* UNLEN is 256 */
3033 DWORD wcch = sizeof(wszUserName) / sizeof(WCHAR);
3034
3035 if (GetUserNameW(wszUserName, &wcch))
3036 {
3037 char_u *p = utf16_to_enc(wszUserName, NULL);
3038
3039 if (p != NULL)
3040 {
3041 vim_strncpy(s, p, len - 1);
3042 vim_free(p);
3043 return OK;
3044 }
3045 }
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003046 }
3047#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003048 if (GetUserName(szUserName, &cch))
3049 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003050 vim_strncpy(s, (char_u *)szUserName, len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003051 return OK;
3052 }
3053 s[0] = NUL;
3054 return FAIL;
3055}
3056
3057
3058/*
3059 * Insert host name in s[len].
3060 */
3061 void
3062mch_get_host_name(
3063 char_u *s,
3064 int len)
3065{
3066 DWORD cch = len;
3067
Bram Moolenaar2cc87382013-12-11 18:21:45 +01003068#ifdef FEAT_MBYTE
3069 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3070 {
3071 WCHAR wszHostName[256 + 1];
3072 DWORD wcch = sizeof(wszHostName) / sizeof(WCHAR);
3073
3074 if (GetComputerNameW(wszHostName, &wcch))
3075 {
3076 char_u *p = utf16_to_enc(wszHostName, NULL);
3077
3078 if (p != NULL)
3079 {
3080 vim_strncpy(s, p, len - 1);
3081 vim_free(p);
3082 return;
3083 }
3084 }
Bram Moolenaar2cc87382013-12-11 18:21:45 +01003085 }
3086#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003087 if (!GetComputerName((LPSTR)s, &cch))
3088 vim_strncpy(s, (char_u *)"PC (Win32 Vim)", len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003089}
3090
3091
3092/*
3093 * return process ID
3094 */
3095 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003096mch_get_pid(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003097{
3098 return (long)GetCurrentProcessId();
3099}
3100
3101
3102/*
3103 * Get name of current directory into buffer 'buf' of length 'len' bytes.
3104 * Return OK for success, FAIL for failure.
3105 */
3106 int
3107mch_dirname(
3108 char_u *buf,
3109 int len)
3110{
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02003111 char_u abuf[_MAX_PATH + 1];
Bram Moolenaarcea1f9e2018-08-19 14:38:42 +02003112 DWORD lfnlen;
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02003113
Bram Moolenaar071d4272004-06-13 20:20:40 +00003114 /*
3115 * Originally this was:
3116 * return (getcwd(buf, len) != NULL ? OK : FAIL);
3117 * But the Win32s known bug list says that getcwd() doesn't work
3118 * so use the Win32 system call instead. <Negri>
3119 */
3120#ifdef FEAT_MBYTE
3121 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3122 {
3123 WCHAR wbuf[_MAX_PATH + 1];
3124
3125 if (GetCurrentDirectoryW(_MAX_PATH, wbuf) != 0)
3126 {
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02003127 WCHAR wcbuf[_MAX_PATH + 1];
Bram Moolenaarcea1f9e2018-08-19 14:38:42 +02003128 char_u *p = NULL;
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02003129
3130 if (GetLongPathNameW(wbuf, wcbuf, _MAX_PATH) != 0)
Bram Moolenaarcea1f9e2018-08-19 14:38:42 +02003131 {
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02003132 p = utf16_to_enc(wcbuf, NULL);
Bram Moolenaarcea1f9e2018-08-19 14:38:42 +02003133 if (STRLEN(p) >= (size_t)len)
3134 {
3135 // long path name is too long, fall back to short one
3136 vim_free(p);
3137 p = NULL;
3138 }
3139 }
3140 if (p == NULL)
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02003141 p = utf16_to_enc(wbuf, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003142
3143 if (p != NULL)
3144 {
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00003145 vim_strncpy(buf, p, len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003146 vim_free(p);
3147 return OK;
3148 }
3149 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003150 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003151 }
3152#endif
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02003153 if (GetCurrentDirectory(len, (LPSTR)buf) == 0)
3154 return FAIL;
Bram Moolenaarcea1f9e2018-08-19 14:38:42 +02003155 lfnlen = GetLongPathNameA((LPCSTR)buf, (LPSTR)abuf, _MAX_PATH);
3156 if (lfnlen == 0 || lfnlen >= (DWORD)len)
3157 // Failed to get long path name or it's too long: fall back to the
3158 // short path name.
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02003159 return OK;
3160
Bram Moolenaarcea1f9e2018-08-19 14:38:42 +02003161 STRCPY(buf, abuf);
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02003162 return OK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003163}
3164
3165/*
Bram Moolenaarffa22202013-11-21 12:34:11 +01003166 * Get file permissions for "name".
3167 * Return mode_t or -1 for error.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003168 */
3169 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003170mch_getperm(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003171{
Bram Moolenaar8767f522016-07-01 17:17:39 +02003172 stat_T st;
Bram Moolenaarffa22202013-11-21 12:34:11 +01003173 int n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003174
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003175 n = mch_stat((char *)name, &st);
Bram Moolenaar78cf3f02014-01-10 18:16:07 +01003176 return n == 0 ? (long)(unsigned short)st.st_mode : -1L;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003177}
3178
3179
3180/*
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003181 * Set file permission for "name" to "perm".
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003182 *
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003183 * Return FAIL for failure, OK otherwise.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003184 */
3185 int
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003186mch_setperm(char_u *name, long perm)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003187{
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003188 long n = -1;
3189
Bram Moolenaar071d4272004-06-13 20:20:40 +00003190#ifdef FEAT_MBYTE
3191 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3192 {
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003193 WCHAR *p = enc_to_utf16(name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003194
3195 if (p != NULL)
3196 {
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003197 n = _wchmod(p, perm);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003198 vim_free(p);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003199 if (n == -1)
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003200 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003201 }
3202 }
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003203 if (n == -1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003204#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003205 n = _chmod((const char *)name, perm);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003206 if (n == -1)
3207 return FAIL;
3208
3209 win32_set_archive(name);
3210
3211 return OK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003212}
3213
3214/*
3215 * Set hidden flag for "name".
3216 */
3217 void
3218mch_hide(char_u *name)
3219{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003220 int attrs = win32_getattrs(name);
3221 if (attrs == -1)
3222 return;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003223
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003224 attrs |= FILE_ATTRIBUTE_HIDDEN;
3225 win32_setattrs(name, attrs);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003226}
3227
3228/*
Bram Moolenaar8a52ba72015-11-02 14:45:56 +01003229 * Return TRUE if file "name" exists and is hidden.
3230 */
3231 int
3232mch_ishidden(char_u *name)
3233{
3234 int f = win32_getattrs(name);
3235
3236 if (f == -1)
3237 return FALSE; /* file does not exist at all */
3238
3239 return (f & FILE_ATTRIBUTE_HIDDEN) != 0;
3240}
3241
3242/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003243 * return TRUE if "name" is a directory
3244 * return FALSE if "name" is not a directory or upon error
3245 */
3246 int
3247mch_isdir(char_u *name)
3248{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003249 int f = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003250
3251 if (f == -1)
3252 return FALSE; /* file does not exist at all */
3253
3254 return (f & FILE_ATTRIBUTE_DIRECTORY) != 0;
3255}
3256
3257/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01003258 * return TRUE if "name" is a directory, NOT a symlink to a directory
3259 * return FALSE if "name" is not a directory
3260 * return FALSE for error
3261 */
3262 int
3263mch_isrealdir(char_u *name)
3264{
3265 return mch_isdir(name) && !mch_is_symbolic_link(name);
3266}
3267
3268/*
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003269 * Create directory "name".
3270 * Return 0 on success, -1 on error.
3271 */
3272 int
3273mch_mkdir(char_u *name)
3274{
3275#ifdef FEAT_MBYTE
3276 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3277 {
3278 WCHAR *p;
3279 int retval;
3280
3281 p = enc_to_utf16(name, NULL);
3282 if (p == NULL)
3283 return -1;
3284 retval = _wmkdir(p);
3285 vim_free(p);
3286 return retval;
3287 }
3288#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003289 return _mkdir((const char *)name);
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003290}
3291
3292/*
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003293 * Delete directory "name".
3294 * Return 0 on success, -1 on error.
3295 */
3296 int
3297mch_rmdir(char_u *name)
3298{
3299#ifdef FEAT_MBYTE
3300 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3301 {
3302 WCHAR *p;
3303 int retval;
3304
3305 p = enc_to_utf16(name, NULL);
3306 if (p == NULL)
3307 return -1;
3308 retval = _wrmdir(p);
3309 vim_free(p);
3310 return retval;
3311 }
3312#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003313 return _rmdir((const char *)name);
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003314}
3315
3316/*
Bram Moolenaar03f48552006-02-28 23:52:23 +00003317 * Return TRUE if file "fname" has more than one link.
3318 */
3319 int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003320mch_is_hard_link(char_u *fname)
Bram Moolenaar03f48552006-02-28 23:52:23 +00003321{
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003322 BY_HANDLE_FILE_INFORMATION info;
3323
3324 return win32_fileinfo(fname, &info) == FILEINFO_OK
3325 && info.nNumberOfLinks > 1;
3326}
3327
3328/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01003329 * Return TRUE if "name" is a symbolic link (or a junction).
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003330 */
3331 int
Bram Moolenaar203258c2016-01-17 22:15:16 +01003332mch_is_symbolic_link(char_u *name)
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003333{
3334 HANDLE hFind;
3335 int res = FALSE;
3336 WIN32_FIND_DATAA findDataA;
3337 DWORD fileFlags = 0, reparseTag = 0;
3338#ifdef FEAT_MBYTE
3339 WCHAR *wn = NULL;
3340 WIN32_FIND_DATAW findDataW;
3341
3342 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar203258c2016-01-17 22:15:16 +01003343 wn = enc_to_utf16(name, NULL);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003344 if (wn != NULL)
3345 {
3346 hFind = FindFirstFileW(wn, &findDataW);
3347 vim_free(wn);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003348 if (hFind != INVALID_HANDLE_VALUE)
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003349 {
3350 fileFlags = findDataW.dwFileAttributes;
3351 reparseTag = findDataW.dwReserved0;
3352 }
3353 }
Bram Moolenaar03e114b2013-06-16 16:34:56 +02003354 else
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003355#endif
Bram Moolenaar03e114b2013-06-16 16:34:56 +02003356 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003357 hFind = FindFirstFile((LPCSTR)name, &findDataA);
Bram Moolenaar03e114b2013-06-16 16:34:56 +02003358 if (hFind != INVALID_HANDLE_VALUE)
3359 {
3360 fileFlags = findDataA.dwFileAttributes;
3361 reparseTag = findDataA.dwReserved0;
3362 }
3363 }
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003364
3365 if (hFind != INVALID_HANDLE_VALUE)
3366 FindClose(hFind);
3367
3368 if ((fileFlags & FILE_ATTRIBUTE_REPARSE_POINT)
Bram Moolenaar203258c2016-01-17 22:15:16 +01003369 && (reparseTag == IO_REPARSE_TAG_SYMLINK
3370 || reparseTag == IO_REPARSE_TAG_MOUNT_POINT))
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003371 res = TRUE;
3372
3373 return res;
3374}
3375
3376/*
3377 * Return TRUE if file "fname" has more than one link or if it is a symbolic
3378 * link.
3379 */
3380 int
3381mch_is_linked(char_u *fname)
3382{
3383 if (mch_is_hard_link(fname) || mch_is_symbolic_link(fname))
3384 return TRUE;
3385 return FALSE;
3386}
3387
3388/*
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003389 * Get the by-handle-file-information for "fname".
3390 * Returns FILEINFO_OK when OK.
3391 * returns FILEINFO_ENC_FAIL when enc_to_utf16() failed.
3392 * Returns FILEINFO_READ_FAIL when CreateFile() failed.
3393 * Returns FILEINFO_INFO_FAIL when GetFileInformationByHandle() failed.
3394 */
3395 int
3396win32_fileinfo(char_u *fname, BY_HANDLE_FILE_INFORMATION *info)
3397{
Bram Moolenaar03f48552006-02-28 23:52:23 +00003398 HANDLE hFile;
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003399 int res = FILEINFO_READ_FAIL;
Bram Moolenaar03f48552006-02-28 23:52:23 +00003400#ifdef FEAT_MBYTE
3401 WCHAR *wn = NULL;
3402
3403 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003404 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00003405 wn = enc_to_utf16(fname, NULL);
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003406 if (wn == NULL)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003407 return FILEINFO_ENC_FAIL;
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003408 }
Bram Moolenaar03f48552006-02-28 23:52:23 +00003409 if (wn != NULL)
3410 {
3411 hFile = CreateFileW(wn, /* file name */
3412 GENERIC_READ, /* access mode */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003413 FILE_SHARE_READ | FILE_SHARE_WRITE, /* share mode */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003414 NULL, /* security descriptor */
3415 OPEN_EXISTING, /* creation disposition */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003416 FILE_FLAG_BACKUP_SEMANTICS, /* file attributes */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003417 NULL); /* handle to template file */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003418 vim_free(wn);
Bram Moolenaar03f48552006-02-28 23:52:23 +00003419 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003420 else
Bram Moolenaar03f48552006-02-28 23:52:23 +00003421#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003422 hFile = CreateFile((LPCSTR)fname, /* file name */
3423 GENERIC_READ, /* access mode */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003424 FILE_SHARE_READ | FILE_SHARE_WRITE, /* share mode */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003425 NULL, /* security descriptor */
3426 OPEN_EXISTING, /* creation disposition */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003427 FILE_FLAG_BACKUP_SEMANTICS, /* file attributes */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003428 NULL); /* handle to template file */
3429
3430 if (hFile != INVALID_HANDLE_VALUE)
3431 {
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003432 if (GetFileInformationByHandle(hFile, info) != 0)
3433 res = FILEINFO_OK;
3434 else
3435 res = FILEINFO_INFO_FAIL;
Bram Moolenaar03f48552006-02-28 23:52:23 +00003436 CloseHandle(hFile);
3437 }
3438
Bram Moolenaar03f48552006-02-28 23:52:23 +00003439 return res;
3440}
3441
3442/*
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003443 * get file attributes for `name'
3444 * -1 : error
3445 * else FILE_ATTRIBUTE_* defined in winnt.h
3446 */
Bram Moolenaarffa22202013-11-21 12:34:11 +01003447 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003448win32_getattrs(char_u *name)
3449{
3450 int attr;
3451#ifdef FEAT_MBYTE
3452 WCHAR *p = NULL;
3453
3454 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3455 p = enc_to_utf16(name, NULL);
3456
3457 if (p != NULL)
3458 {
3459 attr = GetFileAttributesW(p);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003460 vim_free(p);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003461 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003462 else
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003463#endif
3464 attr = GetFileAttributes((char *)name);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003465
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003466 return attr;
3467}
3468
3469/*
3470 * set file attributes for `name' to `attrs'
3471 *
3472 * return -1 for failure, 0 otherwise
3473 */
3474 static
3475 int
3476win32_setattrs(char_u *name, int attrs)
3477{
3478 int res;
3479#ifdef FEAT_MBYTE
3480 WCHAR *p = NULL;
3481
3482 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3483 p = enc_to_utf16(name, NULL);
3484
3485 if (p != NULL)
3486 {
3487 res = SetFileAttributesW(p, attrs);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003488 vim_free(p);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003489 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003490 else
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003491#endif
3492 res = SetFileAttributes((char *)name, attrs);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003493
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003494 return res ? 0 : -1;
3495}
3496
3497/*
3498 * Set archive flag for "name".
3499 */
3500 static
3501 int
3502win32_set_archive(char_u *name)
3503{
3504 int attrs = win32_getattrs(name);
3505 if (attrs == -1)
3506 return -1;
3507
3508 attrs |= FILE_ATTRIBUTE_ARCHIVE;
3509 return win32_setattrs(name, attrs);
3510}
3511
3512/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003513 * Return TRUE if file or directory "name" is writable (not readonly).
3514 * Strange semantics of Win32: a readonly directory is writable, but you can't
3515 * delete a file. Let's say this means it is writable.
3516 */
3517 int
3518mch_writable(char_u *name)
3519{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003520 int attrs = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003521
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003522 return (attrs != -1 && (!(attrs & FILE_ATTRIBUTE_READONLY)
3523 || (attrs & FILE_ATTRIBUTE_DIRECTORY)));
Bram Moolenaar071d4272004-06-13 20:20:40 +00003524}
3525
Bram Moolenaar071d4272004-06-13 20:20:40 +00003526/*
Bram Moolenaar43663192017-03-05 14:29:12 +01003527 * Return TRUE if "name" can be executed, FALSE if not.
Bram Moolenaar77b77102015-03-21 22:18:41 +01003528 * If "use_path" is FALSE only check if "name" is executable.
Bram Moolenaar43663192017-03-05 14:29:12 +01003529 * When returning TRUE and "path" is not NULL save the path and set "*path" to
3530 * the allocated memory.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003531 */
3532 int
Bram Moolenaar77b77102015-03-21 22:18:41 +01003533mch_can_exe(char_u *name, char_u **path, int use_path)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003534{
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003535 char_u buf[_MAX_PATH];
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00003536 int len = (int)STRLEN(name);
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003537 char_u *p;
3538
3539 if (len >= _MAX_PATH) /* safety check */
3540 return FALSE;
3541
3542 /* If there already is an extension try using the name directly. Also do
3543 * this with a Unix-shell like 'shell'. */
3544 if (vim_strchr(gettail(name), '.') != NULL
3545 || strstr((char *)gettail(p_sh), "sh") != NULL)
Bram Moolenaar43663192017-03-05 14:29:12 +01003546 if (executable_exists((char *)name, path, use_path))
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003547 return TRUE;
3548
3549 /*
3550 * Loop over all extensions in $PATHEXT.
3551 */
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00003552 vim_strncpy(buf, name, _MAX_PATH - 1);
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003553 p = mch_getenv("PATHEXT");
3554 if (p == NULL)
3555 p = (char_u *)".com;.exe;.bat;.cmd";
3556 while (*p)
3557 {
3558 if (p[0] == '.' && (p[1] == NUL || p[1] == ';'))
3559 {
3560 /* A single "." means no extension is added. */
3561 buf[len] = NUL;
3562 ++p;
3563 if (*p)
3564 ++p;
3565 }
3566 else
3567 copy_option_part(&p, buf + len, _MAX_PATH - len, ";");
Bram Moolenaar43663192017-03-05 14:29:12 +01003568 if (executable_exists((char *)buf, path, use_path))
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003569 return TRUE;
3570 }
3571 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003572}
Bram Moolenaar071d4272004-06-13 20:20:40 +00003573
3574/*
3575 * Check what "name" is:
3576 * NODE_NORMAL: file or directory (or doesn't exist)
3577 * NODE_WRITABLE: writable device, socket, fifo, etc.
3578 * NODE_OTHER: non-writable things
3579 */
3580 int
3581mch_nodetype(char_u *name)
3582{
3583 HANDLE hFile;
3584 int type;
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003585#ifdef FEAT_MBYTE
3586 WCHAR *wn = NULL;
3587#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003588
Bram Moolenaar043545e2006-10-10 16:44:07 +00003589 /* We can't open a file with a name "\\.\con" or "\\.\prn" and trying to
3590 * read from it later will cause Vim to hang. Thus return NODE_WRITABLE
3591 * here. */
3592 if (STRNCMP(name, "\\\\.\\", 4) == 0)
3593 return NODE_WRITABLE;
3594
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003595#ifdef FEAT_MBYTE
3596 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003597 wn = enc_to_utf16(name, NULL);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003598
3599 if (wn != NULL)
3600 {
3601 hFile = CreateFileW(wn, /* file name */
3602 GENERIC_WRITE, /* access mode */
3603 0, /* share mode */
3604 NULL, /* security descriptor */
3605 OPEN_EXISTING, /* creation disposition */
3606 0, /* file attributes */
3607 NULL); /* handle to template file */
3608 vim_free(wn);
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003609 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003610 else
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003611#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003612 hFile = CreateFile((LPCSTR)name, /* file name */
3613 GENERIC_WRITE, /* access mode */
3614 0, /* share mode */
3615 NULL, /* security descriptor */
3616 OPEN_EXISTING, /* creation disposition */
3617 0, /* file attributes */
3618 NULL); /* handle to template file */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003619
3620 if (hFile == INVALID_HANDLE_VALUE)
3621 return NODE_NORMAL;
3622
3623 type = GetFileType(hFile);
3624 CloseHandle(hFile);
3625 if (type == FILE_TYPE_CHAR)
3626 return NODE_WRITABLE;
3627 if (type == FILE_TYPE_DISK)
3628 return NODE_NORMAL;
3629 return NODE_OTHER;
3630}
3631
3632#ifdef HAVE_ACL
3633struct my_acl
3634{
3635 PSECURITY_DESCRIPTOR pSecurityDescriptor;
3636 PSID pSidOwner;
3637 PSID pSidGroup;
3638 PACL pDacl;
3639 PACL pSacl;
3640};
3641#endif
3642
3643/*
3644 * Return a pointer to the ACL of file "fname" in allocated memory.
3645 * Return NULL if the ACL is not available for whatever reason.
3646 */
3647 vim_acl_T
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003648mch_get_acl(char_u *fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003649{
3650#ifndef HAVE_ACL
3651 return (vim_acl_T)NULL;
3652#else
3653 struct my_acl *p = NULL;
Bram Moolenaar27515922013-06-29 15:36:26 +02003654 DWORD err;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003655
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003656 p = (struct my_acl *)alloc_clear((unsigned)sizeof(struct my_acl));
3657 if (p != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003658 {
Bram Moolenaar27515922013-06-29 15:36:26 +02003659# ifdef FEAT_MBYTE
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003660 WCHAR *wn = NULL;
Bram Moolenaar27515922013-06-29 15:36:26 +02003661
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003662 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3663 wn = enc_to_utf16(fname, NULL);
3664 if (wn != NULL)
3665 {
3666 /* Try to retrieve the entire security descriptor. */
3667 err = GetNamedSecurityInfoW(
3668 wn, // Abstract filename
3669 SE_FILE_OBJECT, // File Object
3670 OWNER_SECURITY_INFORMATION |
3671 GROUP_SECURITY_INFORMATION |
3672 DACL_SECURITY_INFORMATION |
3673 SACL_SECURITY_INFORMATION,
3674 &p->pSidOwner, // Ownership information.
3675 &p->pSidGroup, // Group membership.
3676 &p->pDacl, // Discretionary information.
3677 &p->pSacl, // For auditing purposes.
3678 &p->pSecurityDescriptor);
3679 if (err == ERROR_ACCESS_DENIED ||
3680 err == ERROR_PRIVILEGE_NOT_HELD)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003681 {
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003682 /* Retrieve only DACL. */
3683 (void)GetNamedSecurityInfoW(
3684 wn,
3685 SE_FILE_OBJECT,
3686 DACL_SECURITY_INFORMATION,
3687 NULL,
3688 NULL,
3689 &p->pDacl,
3690 NULL,
3691 &p->pSecurityDescriptor);
Bram Moolenaar27515922013-06-29 15:36:26 +02003692 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003693 if (p->pSecurityDescriptor == NULL)
Bram Moolenaar27515922013-06-29 15:36:26 +02003694 {
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003695 mch_free_acl((vim_acl_T)p);
3696 p = NULL;
3697 }
3698 vim_free(wn);
3699 }
3700 else
3701# endif
3702 {
3703 /* Try to retrieve the entire security descriptor. */
3704 err = GetNamedSecurityInfo(
3705 (LPSTR)fname, // Abstract filename
3706 SE_FILE_OBJECT, // File Object
3707 OWNER_SECURITY_INFORMATION |
3708 GROUP_SECURITY_INFORMATION |
3709 DACL_SECURITY_INFORMATION |
3710 SACL_SECURITY_INFORMATION,
3711 &p->pSidOwner, // Ownership information.
3712 &p->pSidGroup, // Group membership.
3713 &p->pDacl, // Discretionary information.
3714 &p->pSacl, // For auditing purposes.
3715 &p->pSecurityDescriptor);
3716 if (err == ERROR_ACCESS_DENIED ||
3717 err == ERROR_PRIVILEGE_NOT_HELD)
3718 {
3719 /* Retrieve only DACL. */
3720 (void)GetNamedSecurityInfo(
3721 (LPSTR)fname,
3722 SE_FILE_OBJECT,
3723 DACL_SECURITY_INFORMATION,
3724 NULL,
3725 NULL,
3726 &p->pDacl,
3727 NULL,
3728 &p->pSecurityDescriptor);
3729 }
3730 if (p->pSecurityDescriptor == NULL)
3731 {
3732 mch_free_acl((vim_acl_T)p);
3733 p = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003734 }
3735 }
3736 }
3737
3738 return (vim_acl_T)p;
3739#endif
3740}
3741
Bram Moolenaar27515922013-06-29 15:36:26 +02003742#ifdef HAVE_ACL
3743/*
3744 * Check if "acl" contains inherited ACE.
3745 */
3746 static BOOL
3747is_acl_inherited(PACL acl)
3748{
3749 DWORD i;
3750 ACL_SIZE_INFORMATION acl_info;
3751 PACCESS_ALLOWED_ACE ace;
3752
3753 acl_info.AceCount = 0;
3754 GetAclInformation(acl, &acl_info, sizeof(acl_info), AclSizeInformation);
3755 for (i = 0; i < acl_info.AceCount; i++)
3756 {
3757 GetAce(acl, i, (LPVOID *)&ace);
3758 if (ace->Header.AceFlags & INHERITED_ACE)
3759 return TRUE;
3760 }
3761 return FALSE;
3762}
3763#endif
3764
Bram Moolenaar071d4272004-06-13 20:20:40 +00003765/*
3766 * Set the ACL of file "fname" to "acl" (unless it's NULL).
3767 * Errors are ignored.
3768 * This must only be called with "acl" equal to what mch_get_acl() returned.
3769 */
3770 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003771mch_set_acl(char_u *fname, vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003772{
3773#ifdef HAVE_ACL
3774 struct my_acl *p = (struct my_acl *)acl;
Bram Moolenaar27515922013-06-29 15:36:26 +02003775 SECURITY_INFORMATION sec_info = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003776
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003777 if (p != NULL)
Bram Moolenaar27515922013-06-29 15:36:26 +02003778 {
3779# ifdef FEAT_MBYTE
3780 WCHAR *wn = NULL;
3781# endif
3782
3783 /* Set security flags */
3784 if (p->pSidOwner)
3785 sec_info |= OWNER_SECURITY_INFORMATION;
3786 if (p->pSidGroup)
3787 sec_info |= GROUP_SECURITY_INFORMATION;
3788 if (p->pDacl)
3789 {
3790 sec_info |= DACL_SECURITY_INFORMATION;
3791 /* Do not inherit its parent's DACL.
3792 * If the DACL is inherited, Cygwin permissions would be changed.
3793 */
3794 if (!is_acl_inherited(p->pDacl))
3795 sec_info |= PROTECTED_DACL_SECURITY_INFORMATION;
3796 }
3797 if (p->pSacl)
3798 sec_info |= SACL_SECURITY_INFORMATION;
3799
3800# ifdef FEAT_MBYTE
3801 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3802 wn = enc_to_utf16(fname, NULL);
3803 if (wn != NULL)
3804 {
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003805 (void)SetNamedSecurityInfoW(
Bram Moolenaar27515922013-06-29 15:36:26 +02003806 wn, // Abstract filename
3807 SE_FILE_OBJECT, // File Object
3808 sec_info,
3809 p->pSidOwner, // Ownership information.
3810 p->pSidGroup, // Group membership.
3811 p->pDacl, // Discretionary information.
3812 p->pSacl // For auditing purposes.
3813 );
3814 vim_free(wn);
3815 }
3816 else
3817# endif
3818 {
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003819 (void)SetNamedSecurityInfo(
Bram Moolenaar27515922013-06-29 15:36:26 +02003820 (LPSTR)fname, // Abstract filename
3821 SE_FILE_OBJECT, // File Object
3822 sec_info,
3823 p->pSidOwner, // Ownership information.
3824 p->pSidGroup, // Group membership.
3825 p->pDacl, // Discretionary information.
3826 p->pSacl // For auditing purposes.
3827 );
3828 }
3829 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003830#endif
3831}
3832
3833 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003834mch_free_acl(vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003835{
3836#ifdef HAVE_ACL
3837 struct my_acl *p = (struct my_acl *)acl;
3838
3839 if (p != NULL)
3840 {
3841 LocalFree(p->pSecurityDescriptor); // Free the memory just in case
3842 vim_free(p);
3843 }
3844#endif
3845}
3846
3847#ifndef FEAT_GUI_W32
3848
3849/*
3850 * handler for ctrl-break, ctrl-c interrupts, and fatal events.
3851 */
3852 static BOOL WINAPI
3853handler_routine(
3854 DWORD dwCtrlType)
3855{
Bram Moolenaar589b1102017-08-12 16:39:05 +02003856 INPUT_RECORD ir;
3857 DWORD out;
3858
Bram Moolenaar071d4272004-06-13 20:20:40 +00003859 switch (dwCtrlType)
3860 {
3861 case CTRL_C_EVENT:
3862 if (ctrl_c_interrupts)
3863 g_fCtrlCPressed = TRUE;
3864 return TRUE;
3865
3866 case CTRL_BREAK_EVENT:
3867 g_fCBrkPressed = TRUE;
Bram Moolenaar589b1102017-08-12 16:39:05 +02003868 ctrl_break_was_pressed = TRUE;
3869 /* ReadConsoleInput is blocking, send a key event to continue. */
3870 ir.EventType = KEY_EVENT;
3871 ir.Event.KeyEvent.bKeyDown = TRUE;
3872 ir.Event.KeyEvent.wRepeatCount = 1;
3873 ir.Event.KeyEvent.wVirtualKeyCode = VK_CANCEL;
3874 ir.Event.KeyEvent.wVirtualScanCode = 0;
3875 ir.Event.KeyEvent.dwControlKeyState = 0;
3876 ir.Event.KeyEvent.uChar.UnicodeChar = 0;
3877 WriteConsoleInput(g_hConIn, &ir, 1, &out);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003878 return TRUE;
3879
3880 /* fatal events: shut down gracefully */
3881 case CTRL_CLOSE_EVENT:
3882 case CTRL_LOGOFF_EVENT:
3883 case CTRL_SHUTDOWN_EVENT:
3884 windgoto((int)Rows - 1, 0);
3885 g_fForceExit = TRUE;
3886
Bram Moolenaar0fde2902008-03-16 13:54:13 +00003887 vim_snprintf((char *)IObuff, IOSIZE, _("Vim: Caught %s event\n"),
Bram Moolenaar071d4272004-06-13 20:20:40 +00003888 (dwCtrlType == CTRL_CLOSE_EVENT
3889 ? _("close")
3890 : dwCtrlType == CTRL_LOGOFF_EVENT
3891 ? _("logoff")
3892 : _("shutdown")));
3893#ifdef DEBUG
3894 OutputDebugString(IObuff);
3895#endif
3896
3897 preserve_exit(); /* output IObuff, preserve files and exit */
3898
3899 return TRUE; /* not reached */
3900
3901 default:
3902 return FALSE;
3903 }
3904}
3905
3906
3907/*
3908 * set the tty in (raw) ? "raw" : "cooked" mode
3909 */
3910 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003911mch_settmode(int tmode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003912{
3913 DWORD cmodein;
3914 DWORD cmodeout;
3915 BOOL bEnableHandler;
3916
3917 GetConsoleMode(g_hConIn, &cmodein);
3918 GetConsoleMode(g_hConOut, &cmodeout);
3919 if (tmode == TMODE_RAW)
3920 {
3921 cmodein &= ~(ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
3922 ENABLE_ECHO_INPUT);
3923#ifdef FEAT_MOUSE
3924 if (g_fMouseActive)
3925 cmodein |= ENABLE_MOUSE_INPUT;
3926#endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01003927 cmodeout &= ~(
3928#ifdef FEAT_TERMGUICOLORS
3929 /* Do not turn off the ENABLE_PROCESSRD_OUTPUT flag when using
3930 * VTP. */
3931 ((vtp_working) ? 0 : ENABLE_PROCESSED_OUTPUT) |
3932#else
3933 ENABLE_PROCESSED_OUTPUT |
3934#endif
3935 ENABLE_WRAP_AT_EOL_OUTPUT);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003936 bEnableHandler = TRUE;
3937 }
3938 else /* cooked */
3939 {
3940 cmodein |= (ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
3941 ENABLE_ECHO_INPUT);
3942 cmodeout |= (ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
3943 bEnableHandler = FALSE;
3944 }
3945 SetConsoleMode(g_hConIn, cmodein);
3946 SetConsoleMode(g_hConOut, cmodeout);
3947 SetConsoleCtrlHandler(handler_routine, bEnableHandler);
3948
3949#ifdef MCH_WRITE_DUMP
3950 if (fdDump)
3951 {
3952 fprintf(fdDump, "mch_settmode(%s, in = %x, out = %x)\n",
3953 tmode == TMODE_RAW ? "raw" :
3954 tmode == TMODE_COOK ? "cooked" : "normal",
3955 cmodein, cmodeout);
3956 fflush(fdDump);
3957 }
3958#endif
3959}
3960
3961
3962/*
3963 * Get the size of the current window in `Rows' and `Columns'
3964 * Return OK when size could be determined, FAIL otherwise.
3965 */
3966 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003967mch_get_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003968{
3969 CONSOLE_SCREEN_BUFFER_INFO csbi;
3970
3971 if (!g_fTermcapMode && g_cbTermcap.IsValid)
3972 {
3973 /*
3974 * For some reason, we are trying to get the screen dimensions
3975 * even though we are not in termcap mode. The 'Rows' and 'Columns'
3976 * variables are really intended to mean the size of Vim screen
3977 * while in termcap mode.
3978 */
3979 Rows = g_cbTermcap.Info.dwSize.Y;
3980 Columns = g_cbTermcap.Info.dwSize.X;
3981 }
3982 else if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3983 {
3984 Rows = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
3985 Columns = csbi.srWindow.Right - csbi.srWindow.Left + 1;
3986 }
3987 else
3988 {
3989 Rows = 25;
3990 Columns = 80;
3991 }
3992 return OK;
3993}
3994
3995/*
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02003996 * Resize console buffer to 'COORD'
3997 */
3998 static void
3999ResizeConBuf(
4000 HANDLE hConsole,
4001 COORD coordScreen)
4002{
4003 if (!SetConsoleScreenBufferSize(hConsole, coordScreen))
4004 {
4005#ifdef MCH_WRITE_DUMP
4006 if (fdDump)
4007 {
4008 fprintf(fdDump, "SetConsoleScreenBufferSize failed: %lx\n",
4009 GetLastError());
4010 fflush(fdDump);
4011 }
4012#endif
4013 }
4014}
4015
4016/*
4017 * Resize console window size to 'srWindowRect'
4018 */
4019 static void
4020ResizeWindow(
4021 HANDLE hConsole,
4022 SMALL_RECT srWindowRect)
4023{
4024 if (!SetConsoleWindowInfo(hConsole, TRUE, &srWindowRect))
4025 {
4026#ifdef MCH_WRITE_DUMP
4027 if (fdDump)
4028 {
4029 fprintf(fdDump, "SetConsoleWindowInfo failed: %lx\n",
4030 GetLastError());
4031 fflush(fdDump);
4032 }
4033#endif
4034 }
4035}
4036
4037/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00004038 * Set a console window to `xSize' * `ySize'
4039 */
4040 static void
4041ResizeConBufAndWindow(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004042 HANDLE hConsole,
4043 int xSize,
4044 int ySize)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004045{
4046 CONSOLE_SCREEN_BUFFER_INFO csbi; /* hold current console buffer info */
4047 SMALL_RECT srWindowRect; /* hold the new console size */
4048 COORD coordScreen;
4049
4050#ifdef MCH_WRITE_DUMP
4051 if (fdDump)
4052 {
4053 fprintf(fdDump, "ResizeConBufAndWindow(%d, %d)\n", xSize, ySize);
4054 fflush(fdDump);
4055 }
4056#endif
4057
4058 /* get the largest size we can size the console window to */
4059 coordScreen = GetLargestConsoleWindowSize(hConsole);
4060
4061 /* define the new console window size and scroll position */
4062 srWindowRect.Left = srWindowRect.Top = (SHORT) 0;
4063 srWindowRect.Right = (SHORT) (min(xSize, coordScreen.X) - 1);
4064 srWindowRect.Bottom = (SHORT) (min(ySize, coordScreen.Y) - 1);
4065
4066 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
4067 {
4068 int sx, sy;
4069
4070 sx = csbi.srWindow.Right - csbi.srWindow.Left + 1;
4071 sy = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
4072 if (sy < ySize || sx < xSize)
4073 {
4074 /*
4075 * Increasing number of lines/columns, do buffer first.
4076 * Use the maximal size in x and y direction.
4077 */
4078 if (sy < ySize)
4079 coordScreen.Y = ySize;
4080 else
4081 coordScreen.Y = sy;
4082 if (sx < xSize)
4083 coordScreen.X = xSize;
4084 else
4085 coordScreen.X = sx;
4086 SetConsoleScreenBufferSize(hConsole, coordScreen);
4087 }
4088 }
4089
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004090 // define the new console buffer size
Bram Moolenaar071d4272004-06-13 20:20:40 +00004091 coordScreen.X = xSize;
4092 coordScreen.Y = ySize;
4093
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004094 // In the new console call API in reverse order
4095 if (!vtp_working)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004096 {
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004097 ResizeWindow(hConsole, srWindowRect);
4098 ResizeConBuf(hConsole, coordScreen);
4099 }
4100 else
4101 {
4102 ResizeConBuf(hConsole, coordScreen);
4103 ResizeWindow(hConsole, srWindowRect);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004104 }
4105}
4106
4107
4108/*
4109 * Set the console window to `Rows' * `Columns'
4110 */
4111 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004112mch_set_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004113{
4114 COORD coordScreen;
4115
4116 /* Don't change window size while still starting up */
4117 if (suppress_winsize != 0)
4118 {
4119 suppress_winsize = 2;
4120 return;
4121 }
4122
4123 if (term_console)
4124 {
4125 coordScreen = GetLargestConsoleWindowSize(g_hConOut);
4126
4127 /* Clamp Rows and Columns to reasonable values */
4128 if (Rows > coordScreen.Y)
4129 Rows = coordScreen.Y;
4130 if (Columns > coordScreen.X)
4131 Columns = coordScreen.X;
4132
4133 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
4134 }
4135}
4136
4137/*
4138 * Rows and/or Columns has changed.
4139 */
4140 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004141mch_new_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004142{
4143 set_scroll_region(0, 0, Columns - 1, Rows - 1);
4144}
4145
4146
4147/*
4148 * Called when started up, to set the winsize that was delayed.
4149 */
4150 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004151mch_set_winsize_now(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004152{
4153 if (suppress_winsize == 2)
4154 {
4155 suppress_winsize = 0;
4156 mch_set_shellsize();
4157 shell_resized();
4158 }
4159 suppress_winsize = 0;
4160}
4161#endif /* FEAT_GUI_W32 */
4162
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004163 static BOOL
4164vim_create_process(
Bram Moolenaar36c85b22013-12-12 20:25:44 +01004165 char *cmd,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004166 BOOL inherit_handles,
Bram Moolenaar3f1138e2014-01-05 13:29:26 +01004167 DWORD flags,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004168 STARTUPINFO *si,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004169 PROCESS_INFORMATION *pi,
4170 LPVOID *env,
4171 char *cwd)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004172{
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004173#ifdef FEAT_MBYTE
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004174 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4175 {
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004176 BOOL ret;
4177 WCHAR *wcmd, *wcwd = NULL;
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004178
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004179 wcmd = enc_to_utf16((char_u *)cmd, NULL);
4180 if (wcmd == NULL)
4181 goto fallback;
4182 if (cwd != NULL)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004183 {
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004184 wcwd = enc_to_utf16((char_u *)cwd, NULL);
4185 if (wcwd == NULL)
4186 {
4187 vim_free(wcmd);
4188 goto fallback;
4189 }
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004190 }
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004191
4192 ret = CreateProcessW(
4193 NULL, /* Executable name */
4194 wcmd, /* Command to execute */
4195 NULL, /* Process security attributes */
4196 NULL, /* Thread security attributes */
4197 inherit_handles, /* Inherit handles */
4198 flags, /* Creation flags */
4199 env, /* Environment */
4200 wcwd, /* Current directory */
4201 (LPSTARTUPINFOW)si, /* Startup information */
4202 pi); /* Process information */
4203 vim_free(wcmd);
4204 if (wcwd != NULL)
4205 vim_free(wcwd);
4206 return ret;
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004207 }
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004208fallback:
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004209#endif
4210 return CreateProcess(
4211 NULL, /* Executable name */
4212 cmd, /* Command to execute */
4213 NULL, /* Process security attributes */
4214 NULL, /* Thread security attributes */
4215 inherit_handles, /* Inherit handles */
4216 flags, /* Creation flags */
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004217 env, /* Environment */
4218 cwd, /* Current directory */
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004219 si, /* Startup information */
4220 pi); /* Process information */
4221}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004222
4223
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004224 static HINSTANCE
4225vim_shell_execute(
4226 char *cmd,
4227 INT n_show_cmd)
4228{
4229#ifdef FEAT_MBYTE
4230 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4231 {
4232 WCHAR *wcmd = enc_to_utf16((char_u *)cmd, NULL);
4233 if (wcmd != NULL)
4234 {
4235 HINSTANCE ret;
4236 ret = ShellExecuteW(NULL, NULL, wcmd, NULL, NULL, n_show_cmd);
4237 vim_free(wcmd);
4238 return ret;
4239 }
4240 }
4241#endif
4242 return ShellExecute(NULL, NULL, cmd, NULL, NULL, n_show_cmd);
4243}
4244
4245
Bram Moolenaar071d4272004-06-13 20:20:40 +00004246#if defined(FEAT_GUI_W32) || defined(PROTO)
4247
4248/*
4249 * Specialised version of system() for Win32 GUI mode.
4250 * This version proceeds as follows:
4251 * 1. Create a console window for use by the subprocess
4252 * 2. Run the subprocess (it gets the allocated console by default)
4253 * 3. Wait for the subprocess to terminate and get its exit code
4254 * 4. Prompt the user to press a key to close the console window
4255 */
4256 static int
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004257mch_system_classic(char *cmd, int options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004258{
4259 STARTUPINFO si;
4260 PROCESS_INFORMATION pi;
4261 DWORD ret = 0;
4262 HWND hwnd = GetFocus();
4263
4264 si.cb = sizeof(si);
4265 si.lpReserved = NULL;
4266 si.lpDesktop = NULL;
4267 si.lpTitle = NULL;
4268 si.dwFlags = STARTF_USESHOWWINDOW;
4269 /*
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004270 * It's nicer to run a filter command in a minimized window.
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01004271 * Don't activate the window to keep focus on Vim.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004272 */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004273 if (options & SHELL_DOOUT)
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01004274 si.wShowWindow = SW_SHOWMINNOACTIVE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004275 else
4276 si.wShowWindow = SW_SHOWNORMAL;
4277 si.cbReserved2 = 0;
4278 si.lpReserved2 = NULL;
4279
Bram Moolenaar071d4272004-06-13 20:20:40 +00004280 /* Now, run the command */
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004281 vim_create_process(cmd, FALSE,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004282 CREATE_DEFAULT_ERROR_MODE | CREATE_NEW_CONSOLE,
4283 &si, &pi, NULL, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004284
4285 /* Wait for the command to terminate before continuing */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004286 {
4287#ifdef FEAT_GUI
4288 int delay = 1;
4289
4290 /* Keep updating the window while waiting for the shell to finish. */
4291 for (;;)
4292 {
4293 MSG msg;
4294
Bram Moolenaar8c85fa32011-08-10 17:08:03 +02004295 if (pPeekMessage(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004296 {
4297 TranslateMessage(&msg);
Bram Moolenaar8c85fa32011-08-10 17:08:03 +02004298 pDispatchMessage(&msg);
Bram Moolenaare4195c52012-08-02 12:31:44 +02004299 delay = 1;
4300 continue;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004301 }
4302 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
4303 break;
4304
4305 /* We start waiting for a very short time and then increase it, so
4306 * that we respond quickly when the process is quick, and don't
4307 * consume too much overhead when it's slow. */
4308 if (delay < 50)
4309 delay += 10;
4310 }
4311#else
4312 WaitForSingleObject(pi.hProcess, INFINITE);
4313#endif
4314
4315 /* Get the command exit code */
4316 GetExitCodeProcess(pi.hProcess, &ret);
4317 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004318
4319 /* Close the handles to the subprocess, so that it goes away */
4320 CloseHandle(pi.hThread);
4321 CloseHandle(pi.hProcess);
4322
4323 /* Try to get input focus back. Doesn't always work though. */
4324 PostMessage(hwnd, WM_SETFOCUS, 0, 0);
4325
4326 return ret;
4327}
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004328
4329/*
4330 * Thread launched by the gui to send the current buffer data to the
4331 * process. This way avoid to hang up vim totally if the children
4332 * process take a long time to process the lines.
4333 */
Bram Moolenaar4c38d662016-08-03 20:54:57 +02004334 static unsigned int __stdcall
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004335sub_process_writer(LPVOID param)
4336{
4337 HANDLE g_hChildStd_IN_Wr = param;
4338 linenr_T lnum = curbuf->b_op_start.lnum;
4339 DWORD len = 0;
4340 DWORD l;
4341 char_u *lp = ml_get(lnum);
4342 char_u *s;
4343 int written = 0;
4344
4345 for (;;)
4346 {
4347 l = (DWORD)STRLEN(lp + written);
4348 if (l == 0)
4349 len = 0;
4350 else if (lp[written] == NL)
4351 {
4352 /* NL -> NUL translation */
4353 WriteFile(g_hChildStd_IN_Wr, "", 1, &len, NULL);
4354 }
4355 else
4356 {
4357 s = vim_strchr(lp + written, NL);
4358 WriteFile(g_hChildStd_IN_Wr, (char *)lp + written,
4359 s == NULL ? l : (DWORD)(s - (lp + written)),
4360 &len, NULL);
4361 }
4362 if (len == (int)l)
4363 {
4364 /* Finished a line, add a NL, unless this line should not have
4365 * one. */
4366 if (lnum != curbuf->b_op_end.lnum
Bram Moolenaar34d72d42015-07-17 14:18:08 +02004367 || (!curbuf->b_p_bin
4368 && curbuf->b_p_fixeol)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004369 || (lnum != curbuf->b_no_eol_lnum
4370 && (lnum != curbuf->b_ml.ml_line_count
4371 || curbuf->b_p_eol)))
4372 {
Bram Moolenaaraf62ff32013-03-19 14:48:29 +01004373 WriteFile(g_hChildStd_IN_Wr, "\n", 1, (LPDWORD)&ignored, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004374 }
4375
4376 ++lnum;
4377 if (lnum > curbuf->b_op_end.lnum)
4378 break;
4379
4380 lp = ml_get(lnum);
4381 written = 0;
4382 }
4383 else if (len > 0)
4384 written += len;
4385 }
4386
4387 /* finished all the lines, close pipe */
4388 CloseHandle(g_hChildStd_IN_Wr);
Bram Moolenaar86f2cd52016-08-02 21:55:17 +02004389 return 0;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004390}
4391
4392
4393# define BUFLEN 100 /* length for buffer, stolen from unix version */
4394
4395/*
4396 * This function read from the children's stdout and write the
4397 * data on screen or in the buffer accordingly.
4398 */
4399 static void
4400dump_pipe(int options,
4401 HANDLE g_hChildStd_OUT_Rd,
4402 garray_T *ga,
4403 char_u buffer[],
4404 DWORD *buffer_off)
4405{
4406 DWORD availableBytes = 0;
4407 DWORD i;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004408 int ret;
4409 DWORD len;
4410 DWORD toRead;
4411 int repeatCount;
4412
4413 /* we query the pipe to see if there is any data to read
4414 * to avoid to perform a blocking read */
4415 ret = PeekNamedPipe(g_hChildStd_OUT_Rd, /* pipe to query */
4416 NULL, /* optional buffer */
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02004417 0, /* buffer size */
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004418 NULL, /* number of read bytes */
4419 &availableBytes, /* available bytes total */
4420 NULL); /* byteLeft */
4421
4422 repeatCount = 0;
4423 /* We got real data in the pipe, read it */
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02004424 while (ret != 0 && availableBytes > 0)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004425 {
4426 repeatCount++;
4427 toRead =
4428# ifdef FEAT_MBYTE
4429 (DWORD)(BUFLEN - *buffer_off);
4430# else
4431 (DWORD)BUFLEN;
4432# endif
4433 toRead = availableBytes < toRead ? availableBytes : toRead;
4434 ReadFile(g_hChildStd_OUT_Rd, buffer
4435# ifdef FEAT_MBYTE
4436 + *buffer_off, toRead
4437# else
4438 , toRead
4439# endif
4440 , &len, NULL);
4441
4442 /* If we haven't read anything, there is a problem */
4443 if (len == 0)
4444 break;
4445
4446 availableBytes -= len;
4447
4448 if (options & SHELL_READ)
4449 {
4450 /* Do NUL -> NL translation, append NL separated
4451 * lines to the current buffer. */
4452 for (i = 0; i < len; ++i)
4453 {
4454 if (buffer[i] == NL)
4455 append_ga_line(ga);
4456 else if (buffer[i] == NUL)
4457 ga_append(ga, NL);
4458 else
4459 ga_append(ga, buffer[i]);
4460 }
4461 }
4462# ifdef FEAT_MBYTE
4463 else if (has_mbyte)
4464 {
4465 int l;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004466 int c;
4467 char_u *p;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004468
4469 len += *buffer_off;
4470 buffer[len] = NUL;
4471
4472 /* Check if the last character in buffer[] is
4473 * incomplete, keep these bytes for the next
4474 * round. */
4475 for (p = buffer; p < buffer + len; p += l)
4476 {
Bram Moolenaard3c907b2016-08-17 21:32:09 +02004477 l = MB_CPTR2LEN(p);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004478 if (l == 0)
4479 l = 1; /* NUL byte? */
4480 else if (MB_BYTE2LEN(*p) != l)
4481 break;
4482 }
4483 if (p == buffer) /* no complete character */
4484 {
4485 /* avoid getting stuck at an illegal byte */
4486 if (len >= 12)
4487 ++p;
4488 else
4489 {
4490 *buffer_off = len;
4491 return;
4492 }
4493 }
4494 c = *p;
4495 *p = NUL;
4496 msg_puts(buffer);
4497 if (p < buffer + len)
4498 {
4499 *p = c;
4500 *buffer_off = (DWORD)((buffer + len) - p);
4501 mch_memmove(buffer, p, *buffer_off);
4502 return;
4503 }
4504 *buffer_off = 0;
4505 }
4506# endif /* FEAT_MBYTE */
4507 else
4508 {
4509 buffer[len] = NUL;
4510 msg_puts(buffer);
4511 }
4512
4513 windgoto(msg_row, msg_col);
4514 cursor_on();
4515 out_flush();
4516 }
4517}
4518
4519/*
4520 * Version of system to use for windows NT > 5.0 (Win2K), use pipe
4521 * for communication and doesn't open any new window.
4522 */
4523 static int
4524mch_system_piped(char *cmd, int options)
4525{
4526 STARTUPINFO si;
4527 PROCESS_INFORMATION pi;
4528 DWORD ret = 0;
4529
4530 HANDLE g_hChildStd_IN_Rd = NULL;
4531 HANDLE g_hChildStd_IN_Wr = NULL;
4532 HANDLE g_hChildStd_OUT_Rd = NULL;
4533 HANDLE g_hChildStd_OUT_Wr = NULL;
4534
4535 char_u buffer[BUFLEN + 1]; /* reading buffer + size */
4536 DWORD len;
4537
4538 /* buffer used to receive keys */
4539 char_u ta_buf[BUFLEN + 1]; /* TypeAHead */
4540 int ta_len = 0; /* valid bytes in ta_buf[] */
4541
4542 DWORD i;
4543 int c;
4544 int noread_cnt = 0;
4545 garray_T ga;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004546 int delay = 1;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004547 DWORD buffer_off = 0; /* valid bytes in buffer[] */
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004548 char *p = NULL;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004549
4550 SECURITY_ATTRIBUTES saAttr;
4551
4552 /* Set the bInheritHandle flag so pipe handles are inherited. */
4553 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
4554 saAttr.bInheritHandle = TRUE;
4555 saAttr.lpSecurityDescriptor = NULL;
4556
4557 if ( ! CreatePipe(&g_hChildStd_OUT_Rd, &g_hChildStd_OUT_Wr, &saAttr, 0)
4558 /* Ensure the read handle to the pipe for STDOUT is not inherited. */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004559 || ! SetHandleInformation(g_hChildStd_OUT_Rd, HANDLE_FLAG_INHERIT, 0)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004560 /* Create a pipe for the child process's STDIN. */
4561 || ! CreatePipe(&g_hChildStd_IN_Rd, &g_hChildStd_IN_Wr, &saAttr, 0)
4562 /* Ensure the write handle to the pipe for STDIN is not inherited. */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004563 || ! SetHandleInformation(g_hChildStd_IN_Wr, HANDLE_FLAG_INHERIT, 0) )
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004564 {
4565 CloseHandle(g_hChildStd_IN_Rd);
4566 CloseHandle(g_hChildStd_IN_Wr);
4567 CloseHandle(g_hChildStd_OUT_Rd);
4568 CloseHandle(g_hChildStd_OUT_Wr);
4569 MSG_PUTS(_("\nCannot create pipes\n"));
4570 }
4571
4572 si.cb = sizeof(si);
4573 si.lpReserved = NULL;
4574 si.lpDesktop = NULL;
4575 si.lpTitle = NULL;
4576 si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
4577
4578 /* set-up our file redirection */
4579 si.hStdError = g_hChildStd_OUT_Wr;
4580 si.hStdOutput = g_hChildStd_OUT_Wr;
4581 si.hStdInput = g_hChildStd_IN_Rd;
4582 si.wShowWindow = SW_HIDE;
4583 si.cbReserved2 = 0;
4584 si.lpReserved2 = NULL;
4585
4586 if (options & SHELL_READ)
4587 ga_init2(&ga, 1, BUFLEN);
4588
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004589 if (cmd != NULL)
4590 {
4591 p = (char *)vim_strsave((char_u *)cmd);
4592 if (p != NULL)
4593 unescape_shellxquote((char_u *)p, p_sxe);
4594 else
4595 p = cmd;
4596 }
4597
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004598 /* Now, run the command.
4599 * About "Inherit handles" being TRUE: this command can be litigious,
4600 * handle inheritance was deactivated for pending temp file, but, if we
4601 * deactivate it, the pipes don't work for some reason. */
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004602 vim_create_process(p, TRUE, CREATE_DEFAULT_ERROR_MODE,
4603 &si, &pi, NULL, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004604
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004605 if (p != cmd)
4606 vim_free(p);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004607
4608 /* Close our unused side of the pipes */
4609 CloseHandle(g_hChildStd_IN_Rd);
4610 CloseHandle(g_hChildStd_OUT_Wr);
4611
4612 if (options & SHELL_WRITE)
4613 {
Bram Moolenaar86f2cd52016-08-02 21:55:17 +02004614 HANDLE thread = (HANDLE)
4615 _beginthreadex(NULL, /* security attributes */
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004616 0, /* default stack size */
4617 sub_process_writer, /* function to be executed */
4618 g_hChildStd_IN_Wr, /* parameter */
4619 0, /* creation flag, start immediately */
4620 NULL); /* we don't care about thread id */
4621 CloseHandle(thread);
4622 g_hChildStd_IN_Wr = NULL;
4623 }
4624
4625 /* Keep updating the window while waiting for the shell to finish. */
4626 for (;;)
4627 {
4628 MSG msg;
4629
Bram Moolenaar175d0702013-12-11 18:36:33 +01004630 if (pPeekMessage(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004631 {
4632 TranslateMessage(&msg);
Bram Moolenaar175d0702013-12-11 18:36:33 +01004633 pDispatchMessage(&msg);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004634 }
4635
4636 /* write pipe information in the window */
4637 if ((options & (SHELL_READ|SHELL_WRITE))
4638# ifdef FEAT_GUI
4639 || gui.in_use
4640# endif
4641 )
4642 {
4643 len = 0;
4644 if (!(options & SHELL_EXPAND)
4645 && ((options &
4646 (SHELL_READ|SHELL_WRITE|SHELL_COOKED))
4647 != (SHELL_READ|SHELL_WRITE|SHELL_COOKED)
4648# ifdef FEAT_GUI
4649 || gui.in_use
4650# endif
4651 )
4652 && (ta_len > 0 || noread_cnt > 4))
4653 {
4654 if (ta_len == 0)
4655 {
4656 /* Get extra characters when we don't have any. Reset the
4657 * counter and timer. */
4658 noread_cnt = 0;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004659 len = ui_inchar(ta_buf, BUFLEN, 10L, 0);
4660 }
4661 if (ta_len > 0 || len > 0)
4662 {
4663 /*
4664 * For pipes: Check for CTRL-C: send interrupt signal to
4665 * child. Check for CTRL-D: EOF, close pipe to child.
4666 */
4667 if (len == 1 && cmd != NULL)
4668 {
4669 if (ta_buf[ta_len] == Ctrl_C)
4670 {
4671 /* Learn what exit code is expected, for
4672 * now put 9 as SIGKILL */
4673 TerminateProcess(pi.hProcess, 9);
4674 }
4675 if (ta_buf[ta_len] == Ctrl_D)
4676 {
4677 CloseHandle(g_hChildStd_IN_Wr);
4678 g_hChildStd_IN_Wr = NULL;
4679 }
4680 }
4681
4682 /* replace K_BS by <BS> and K_DEL by <DEL> */
4683 for (i = ta_len; i < ta_len + len; ++i)
4684 {
4685 if (ta_buf[i] == CSI && len - i > 2)
4686 {
4687 c = TERMCAP2KEY(ta_buf[i + 1], ta_buf[i + 2]);
4688 if (c == K_DEL || c == K_KDEL || c == K_BS)
4689 {
4690 mch_memmove(ta_buf + i + 1, ta_buf + i + 3,
4691 (size_t)(len - i - 2));
4692 if (c == K_DEL || c == K_KDEL)
4693 ta_buf[i] = DEL;
4694 else
4695 ta_buf[i] = Ctrl_H;
4696 len -= 2;
4697 }
4698 }
4699 else if (ta_buf[i] == '\r')
4700 ta_buf[i] = '\n';
4701# ifdef FEAT_MBYTE
4702 if (has_mbyte)
4703 i += (*mb_ptr2len_len)(ta_buf + i,
4704 ta_len + len - i) - 1;
4705# endif
4706 }
4707
4708 /*
4709 * For pipes: echo the typed characters. For a pty this
4710 * does not seem to work.
4711 */
4712 for (i = ta_len; i < ta_len + len; ++i)
4713 {
4714 if (ta_buf[i] == '\n' || ta_buf[i] == '\b')
4715 msg_putchar(ta_buf[i]);
4716# ifdef FEAT_MBYTE
4717 else if (has_mbyte)
4718 {
4719 int l = (*mb_ptr2len)(ta_buf + i);
4720
4721 msg_outtrans_len(ta_buf + i, l);
4722 i += l - 1;
4723 }
4724# endif
4725 else
4726 msg_outtrans_len(ta_buf + i, 1);
4727 }
4728 windgoto(msg_row, msg_col);
4729 out_flush();
4730
4731 ta_len += len;
4732
4733 /*
4734 * Write the characters to the child, unless EOF has been
4735 * typed for pipes. Write one character at a time, to
4736 * avoid losing too much typeahead. When writing buffer
4737 * lines, drop the typed characters (only check for
4738 * CTRL-C).
4739 */
4740 if (options & SHELL_WRITE)
4741 ta_len = 0;
4742 else if (g_hChildStd_IN_Wr != NULL)
4743 {
4744 WriteFile(g_hChildStd_IN_Wr, (char*)ta_buf,
4745 1, &len, NULL);
4746 // if we are typing in, we want to keep things reactive
4747 delay = 1;
4748 if (len > 0)
4749 {
4750 ta_len -= len;
4751 mch_memmove(ta_buf, ta_buf + len, ta_len);
4752 }
4753 }
4754 }
4755 }
4756 }
4757
4758 if (ta_len)
4759 ui_inchar_undo(ta_buf, ta_len);
4760
4761 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
4762 {
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004763 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004764 break;
4765 }
4766
4767 ++noread_cnt;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004768 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004769
4770 /* We start waiting for a very short time and then increase it, so
4771 * that we respond quickly when the process is quick, and don't
4772 * consume too much overhead when it's slow. */
4773 if (delay < 50)
4774 delay += 10;
4775 }
4776
4777 /* Close the pipe */
4778 CloseHandle(g_hChildStd_OUT_Rd);
4779 if (g_hChildStd_IN_Wr != NULL)
4780 CloseHandle(g_hChildStd_IN_Wr);
4781
4782 WaitForSingleObject(pi.hProcess, INFINITE);
4783
4784 /* Get the command exit code */
4785 GetExitCodeProcess(pi.hProcess, &ret);
4786
4787 if (options & SHELL_READ)
4788 {
4789 if (ga.ga_len > 0)
4790 {
4791 append_ga_line(&ga);
4792 /* remember that the NL was missing */
4793 curbuf->b_no_eol_lnum = curwin->w_cursor.lnum;
4794 }
4795 else
4796 curbuf->b_no_eol_lnum = 0;
4797 ga_clear(&ga);
4798 }
4799
4800 /* Close the handles to the subprocess, so that it goes away */
4801 CloseHandle(pi.hThread);
4802 CloseHandle(pi.hProcess);
4803
4804 return ret;
4805}
4806
4807 static int
4808mch_system(char *cmd, int options)
4809{
4810 /* if we can pipe and the shelltemp option is off */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004811 if (!p_stmp)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004812 return mch_system_piped(cmd, options);
4813 else
4814 return mch_system_classic(cmd, options);
4815}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004816#else
4817
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004818# ifdef FEAT_MBYTE
4819 static int
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01004820mch_system(char *cmd, int options)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004821{
4822 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4823 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004824 WCHAR *wcmd = enc_to_utf16((char_u *)cmd, NULL);
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004825 if (wcmd != NULL)
4826 {
4827 int ret = _wsystem(wcmd);
4828 vim_free(wcmd);
4829 return ret;
4830 }
4831 }
4832 return system(cmd);
4833}
4834# else
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01004835# define mch_system(c, o) system(c)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004836# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004837
4838#endif
4839
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004840#if defined(FEAT_GUI) && defined(FEAT_TERMINAL)
4841/*
4842 * Use a terminal window to run a shell command in.
4843 */
4844 static int
4845mch_call_shell_terminal(
4846 char_u *cmd,
4847 int options UNUSED) /* SHELL_*, see vim.h */
4848{
4849 jobopt_T opt;
4850 char_u *newcmd = NULL;
4851 typval_T argvar[2];
4852 long_u cmdlen;
4853 int retval = -1;
4854 buf_T *buf;
Bram Moolenaarf9c38832018-06-19 19:59:20 +02004855 job_T *job;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004856 aco_save_T aco;
4857 oparg_T oa; /* operator arguments */
4858
Bram Moolenaar42f652f2018-03-19 21:44:37 +01004859 if (cmd == NULL)
4860 cmdlen = STRLEN(p_sh) + 1;
4861 else
4862 cmdlen = STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004863 newcmd = lalloc(cmdlen, TRUE);
4864 if (newcmd == NULL)
4865 return 255;
Bram Moolenaar42f652f2018-03-19 21:44:37 +01004866 if (cmd == NULL)
4867 {
4868 STRCPY(newcmd, p_sh);
4869 ch_log(NULL, "starting terminal to run a shell");
4870 }
4871 else
4872 {
4873 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s", p_sh, p_shcf, cmd);
4874 ch_log(NULL, "starting terminal for system command '%s'", cmd);
4875 }
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004876
4877 init_job_options(&opt);
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004878
4879 argvar[0].v_type = VAR_STRING;
4880 argvar[0].vval.v_string = newcmd;
4881 argvar[1].v_type = VAR_UNKNOWN;
4882 buf = term_start(argvar, NULL, &opt, TERM_START_SYSTEM);
Bram Moolenaar81c3c89a2018-03-20 11:41:44 +01004883 if (buf == NULL)
4884 return 255;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004885
Bram Moolenaarf9c38832018-06-19 19:59:20 +02004886 job = term_getjob(buf->b_term);
4887 ++job->jv_refcount;
4888
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004889 /* Find a window to make "buf" curbuf. */
4890 aucmd_prepbuf(&aco, buf);
4891
4892 clear_oparg(&oa);
4893 while (term_use_loop())
4894 {
4895 if (oa.op_type == OP_NOP && oa.regname == NUL && !VIsual_active)
4896 {
4897 /* If terminal_loop() returns OK we got a key that is handled
4898 * in Normal model. We don't do redrawing anyway. */
4899 if (terminal_loop(TRUE) == OK)
4900 normal_cmd(&oa, TRUE);
4901 }
4902 else
4903 normal_cmd(&oa, TRUE);
4904 }
Bram Moolenaarf9c38832018-06-19 19:59:20 +02004905 retval = job->jv_exitval;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004906 ch_log(NULL, "system command finished");
4907
Bram Moolenaarf9c38832018-06-19 19:59:20 +02004908 job_unref(job);
4909
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004910 /* restore curwin/curbuf and a few other things */
4911 aucmd_restbuf(&aco);
4912
4913 wait_return(TRUE);
4914 do_buffer(DOBUF_WIPE, DOBUF_FIRST, FORWARD, buf->b_fnum, TRUE);
4915
4916 vim_free(newcmd);
4917 return retval;
4918}
4919#endif
4920
Bram Moolenaar071d4272004-06-13 20:20:40 +00004921/*
4922 * Either execute a command by calling the shell or start a new shell
4923 */
4924 int
4925mch_call_shell(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004926 char_u *cmd,
4927 int options) /* SHELL_*, see vim.h */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004928{
4929 int x = 0;
4930 int tmode = cur_tmode;
4931#ifdef FEAT_TITLE
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004932 char szShellTitle[512];
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004933# ifdef FEAT_MBYTE
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004934 int did_set_title = FALSE;
4935
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004936 /* Change the title to reflect that we are in a subshell. */
4937 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4938 {
4939 WCHAR szShellTitle[512];
4940
4941 if (GetConsoleTitleW(szShellTitle,
4942 sizeof(szShellTitle)/sizeof(WCHAR) - 4) > 0)
4943 {
4944 if (cmd == NULL)
4945 wcscat(szShellTitle, L" :sh");
4946 else
4947 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004948 WCHAR *wn = enc_to_utf16((char_u *)cmd, NULL);
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004949
4950 if (wn != NULL)
4951 {
4952 wcscat(szShellTitle, L" - !");
4953 if ((wcslen(szShellTitle) + wcslen(wn) <
4954 sizeof(szShellTitle)/sizeof(WCHAR)))
4955 wcscat(szShellTitle, wn);
4956 SetConsoleTitleW(szShellTitle);
4957 vim_free(wn);
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004958 did_set_title = TRUE;
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004959 }
4960 }
4961 }
4962 }
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004963 if (!did_set_title)
4964# endif
4965 /* Change the title to reflect that we are in a subshell. */
4966 if (GetConsoleTitle(szShellTitle, sizeof(szShellTitle) - 4) > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004967 {
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004968 if (cmd == NULL)
4969 strcat(szShellTitle, " :sh");
4970 else
4971 {
4972 strcat(szShellTitle, " - !");
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004973 if ((strlen(szShellTitle) + strlen((char *)cmd)
4974 < sizeof(szShellTitle)))
4975 strcat(szShellTitle, (char *)cmd);
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004976 }
4977 SetConsoleTitle(szShellTitle);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004978 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004979#endif
4980
4981 out_flush();
4982
4983#ifdef MCH_WRITE_DUMP
4984 if (fdDump)
4985 {
4986 fprintf(fdDump, "mch_call_shell(\"%s\", %d)\n", cmd, options);
4987 fflush(fdDump);
4988 }
4989#endif
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004990#if defined(FEAT_GUI) && defined(FEAT_TERMINAL)
4991 /* TODO: make the terminal window work with input or output redirected. */
4992 if (vim_strchr(p_go, GO_TERMINAL) != NULL
4993 && (options & (SHELL_FILTER|SHELL_DOOUT|SHELL_WRITE|SHELL_READ)) == 0)
4994 {
4995 /* Use a terminal window to run the command in. */
4996 x = mch_call_shell_terminal(cmd, options);
4997#ifdef FEAT_TITLE
4998 resettitle();
4999#endif
5000 return x;
5001 }
5002#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005003
5004 /*
5005 * Catch all deadly signals while running the external command, because a
5006 * CTRL-C, Ctrl-Break or illegal instruction might otherwise kill us.
5007 */
5008 signal(SIGINT, SIG_IGN);
5009#if defined(__GNUC__) && !defined(__MINGW32__)
5010 signal(SIGKILL, SIG_IGN);
5011#else
5012 signal(SIGBREAK, SIG_IGN);
5013#endif
5014 signal(SIGILL, SIG_IGN);
5015 signal(SIGFPE, SIG_IGN);
5016 signal(SIGSEGV, SIG_IGN);
5017 signal(SIGTERM, SIG_IGN);
5018 signal(SIGABRT, SIG_IGN);
5019
5020 if (options & SHELL_COOKED)
5021 settmode(TMODE_COOK); /* set to normal mode */
5022
5023 if (cmd == NULL)
5024 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01005025 x = mch_system((char *)p_sh, options);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005026 }
5027 else
5028 {
5029 /* we use "command" or "cmd" to start the shell; slow but easy */
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005030 char_u *newcmd = NULL;
5031 char_u *cmdbase = cmd;
5032 long_u cmdlen;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005033
5034 /* Skip a leading ", ( and "(. */
5035 if (*cmdbase == '"' )
5036 ++cmdbase;
5037 if (*cmdbase == '(')
5038 ++cmdbase;
5039
Bram Moolenaar1c465442017-03-12 20:10:05 +01005040 if ((STRNICMP(cmdbase, "start", 5) == 0) && VIM_ISWHITE(cmdbase[5]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005041 {
5042 STARTUPINFO si;
5043 PROCESS_INFORMATION pi;
5044 DWORD flags = CREATE_NEW_CONSOLE;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01005045 INT n_show_cmd = SW_SHOWNORMAL;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005046 char_u *p;
5047
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01005048 ZeroMemory(&si, sizeof(si));
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005049 si.cb = sizeof(si);
5050 si.lpReserved = NULL;
5051 si.lpDesktop = NULL;
5052 si.lpTitle = NULL;
5053 si.dwFlags = 0;
5054 si.cbReserved2 = 0;
5055 si.lpReserved2 = NULL;
5056
5057 cmdbase = skipwhite(cmdbase + 5);
5058 if ((STRNICMP(cmdbase, "/min", 4) == 0)
Bram Moolenaar1c465442017-03-12 20:10:05 +01005059 && VIM_ISWHITE(cmdbase[4]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005060 {
5061 cmdbase = skipwhite(cmdbase + 4);
5062 si.dwFlags = STARTF_USESHOWWINDOW;
5063 si.wShowWindow = SW_SHOWMINNOACTIVE;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01005064 n_show_cmd = SW_SHOWMINNOACTIVE;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005065 }
5066 else if ((STRNICMP(cmdbase, "/b", 2) == 0)
Bram Moolenaar1c465442017-03-12 20:10:05 +01005067 && VIM_ISWHITE(cmdbase[2]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005068 {
5069 cmdbase = skipwhite(cmdbase + 2);
5070 flags = CREATE_NO_WINDOW;
5071 si.dwFlags = STARTF_USESTDHANDLES;
5072 si.hStdInput = CreateFile("\\\\.\\NUL", // File name
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005073 GENERIC_READ, // Access flags
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005074 0, // Share flags
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005075 NULL, // Security att.
5076 OPEN_EXISTING, // Open flags
5077 FILE_ATTRIBUTE_NORMAL, // File att.
5078 NULL); // Temp file
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005079 si.hStdOutput = si.hStdInput;
5080 si.hStdError = si.hStdInput;
5081 }
5082
5083 /* Remove a trailing ", ) and )" if they have a match
5084 * at the start of the command. */
5085 if (cmdbase > cmd)
5086 {
5087 p = cmdbase + STRLEN(cmdbase);
5088 if (p > cmdbase && p[-1] == '"' && *cmd == '"')
5089 *--p = NUL;
5090 if (p > cmdbase && p[-1] == ')'
5091 && (*cmd =='(' || cmd[1] == '('))
5092 *--p = NUL;
5093 }
5094
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005095 newcmd = cmdbase;
5096 unescape_shellxquote(cmdbase, p_sxe);
5097
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005098 /*
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005099 * If creating new console, arguments are passed to the
5100 * 'cmd.exe' as-is. If it's not, arguments are not treated
5101 * correctly for current 'cmd.exe'. So unescape characters in
5102 * shellxescape except '|' for avoiding to be treated as
5103 * argument to them. Pass the arguments to sub-shell.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005104 */
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005105 if (flags != CREATE_NEW_CONSOLE)
5106 {
5107 char_u *subcmd;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01005108 char_u *cmd_shell = mch_getenv("COMSPEC");
5109
5110 if (cmd_shell == NULL || *cmd_shell == NUL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01005111 cmd_shell = (char_u *)default_shell();
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005112
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01005113 subcmd = vim_strsave_escaped_ext(cmdbase,
5114 (char_u *)"|", '^', FALSE);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005115 if (subcmd != NULL)
5116 {
5117 /* make "cmd.exe /c arguments" */
5118 cmdlen = STRLEN(cmd_shell) + STRLEN(subcmd) + 5;
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005119 newcmd = lalloc(cmdlen, TRUE);
5120 if (newcmd != NULL)
5121 vim_snprintf((char *)newcmd, cmdlen, "%s /c %s",
Bram Moolenaaree7d1002012-02-22 15:34:08 +01005122 cmd_shell, subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005123 else
5124 newcmd = cmdbase;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01005125 vim_free(subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005126 }
5127 }
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005128
5129 /*
5130 * Now, start the command as a process, so that it doesn't
5131 * inherit our handles which causes unpleasant dangling swap
5132 * files if we exit before the spawned process
5133 */
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005134 if (vim_create_process((char *)newcmd, FALSE, flags,
5135 &si, &pi, NULL, NULL))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005136 x = 0;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01005137 else if (vim_shell_execute((char *)newcmd, n_show_cmd)
5138 > (HINSTANCE)32)
5139 x = 0;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005140 else
5141 {
5142 x = -1;
5143#ifdef FEAT_GUI_W32
5144 EMSG(_("E371: Command not found"));
5145#endif
5146 }
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005147
5148 if (newcmd != cmdbase)
5149 vim_free(newcmd);
5150
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01005151 if (si.dwFlags == STARTF_USESTDHANDLES && si.hStdInput != NULL)
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005152 {
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01005153 /* Close the handle to \\.\NUL created above. */
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005154 CloseHandle(si.hStdInput);
5155 }
5156 /* Close the handles to the subprocess, so that it goes away */
5157 CloseHandle(pi.hThread);
5158 CloseHandle(pi.hProcess);
5159 }
5160 else
5161 {
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005162 cmdlen = (
Bram Moolenaar071d4272004-06-13 20:20:40 +00005163#ifdef FEAT_GUI_W32
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005164 (!p_stmp ? 0 : STRLEN(vimrun_path)) +
Bram Moolenaar071d4272004-06-13 20:20:40 +00005165#endif
Bram Moolenaar0fde2902008-03-16 13:54:13 +00005166 STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10);
5167
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005168 newcmd = lalloc(cmdlen, TRUE);
5169 if (newcmd != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005170 {
5171#if defined(FEAT_GUI_W32)
5172 if (need_vimrun_warning)
5173 {
Bram Moolenaar63e43442016-11-19 17:28:44 +01005174 char *msg = _("VIMRUN.EXE not found in your $PATH.\n"
5175 "External commands will not pause after completion.\n"
5176 "See :help win32-vimrun for more information.");
5177 char *title = _("Vim Warning");
5178# ifdef FEAT_MBYTE
5179 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
5180 {
5181 WCHAR *wmsg = enc_to_utf16((char_u *)msg, NULL);
5182 WCHAR *wtitle = enc_to_utf16((char_u *)title, NULL);
5183
5184 if (wmsg != NULL && wtitle != NULL)
5185 MessageBoxW(NULL, wmsg, wtitle, MB_ICONWARNING);
5186 vim_free(wmsg);
5187 vim_free(wtitle);
5188 }
5189 else
5190# endif
5191 MessageBox(NULL, msg, title, MB_ICONWARNING);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005192 need_vimrun_warning = FALSE;
5193 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005194 if (!s_dont_use_vimrun && p_stmp)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005195 /* Use vimrun to execute the command. It opens a console
5196 * window, which can be closed without killing Vim. */
Bram Moolenaarcc448b32010-07-14 16:52:17 +02005197 vim_snprintf((char *)newcmd, cmdlen, "%s%s%s %s %s",
Bram Moolenaar071d4272004-06-13 20:20:40 +00005198 vimrun_path,
5199 (msg_silent != 0 || (options & SHELL_DOOUT))
5200 ? "-s " : "",
5201 p_sh, p_shcf, cmd);
5202 else
5203#endif
Bram Moolenaarcc448b32010-07-14 16:52:17 +02005204 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s",
Bram Moolenaar0fde2902008-03-16 13:54:13 +00005205 p_sh, p_shcf, cmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005206 x = mch_system((char *)newcmd, options);
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005207 vim_free(newcmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005208 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005209 }
5210 }
5211
5212 if (tmode == TMODE_RAW)
5213 settmode(TMODE_RAW); /* set to raw mode */
5214
5215 /* Print the return value, unless "vimrun" was used. */
5216 if (x != 0 && !(options & SHELL_SILENT) && !emsg_silent
5217#if defined(FEAT_GUI_W32)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005218 && ((options & SHELL_DOOUT) || s_dont_use_vimrun || !p_stmp)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005219#endif
5220 )
5221 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01005222 smsg((char_u *)_("shell returned %d"), x);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005223 msg_putchar('\n');
5224 }
5225#ifdef FEAT_TITLE
5226 resettitle();
5227#endif
5228
5229 signal(SIGINT, SIG_DFL);
5230#if defined(__GNUC__) && !defined(__MINGW32__)
5231 signal(SIGKILL, SIG_DFL);
5232#else
5233 signal(SIGBREAK, SIG_DFL);
5234#endif
5235 signal(SIGILL, SIG_DFL);
5236 signal(SIGFPE, SIG_DFL);
5237 signal(SIGSEGV, SIG_DFL);
5238 signal(SIGTERM, SIG_DFL);
5239 signal(SIGABRT, SIG_DFL);
5240
5241 return x;
5242}
5243
Bram Moolenaar509ce2a2016-03-11 22:52:15 +01005244#if defined(FEAT_JOB_CHANNEL) || defined(PROTO)
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005245 static HANDLE
5246job_io_file_open(
Bram Moolenaar972c3b82017-01-12 21:44:49 +01005247 char_u *fname,
5248 DWORD dwDesiredAccess,
5249 DWORD dwShareMode,
5250 LPSECURITY_ATTRIBUTES lpSecurityAttributes,
5251 DWORD dwCreationDisposition,
5252 DWORD dwFlagsAndAttributes)
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005253{
5254 HANDLE h;
5255# ifdef FEAT_MBYTE
5256 WCHAR *wn = NULL;
5257 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
5258 {
Bram Moolenaar972c3b82017-01-12 21:44:49 +01005259 wn = enc_to_utf16(fname, NULL);
5260 if (wn != NULL)
5261 {
5262 h = CreateFileW(wn, dwDesiredAccess, dwShareMode,
5263 lpSecurityAttributes, dwCreationDisposition,
5264 dwFlagsAndAttributes, NULL);
5265 vim_free(wn);
5266 }
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005267 }
5268 if (wn == NULL)
5269# endif
Bram Moolenaar972c3b82017-01-12 21:44:49 +01005270 h = CreateFile((LPCSTR)fname, dwDesiredAccess, dwShareMode,
5271 lpSecurityAttributes, dwCreationDisposition,
5272 dwFlagsAndAttributes, NULL);
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005273 return h;
5274}
5275
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005276/*
5277 * Turn the dictionary "env" into a NUL separated list that can be used as the
5278 * environment argument of vim_create_process().
5279 */
Bram Moolenaarba6febd2017-10-30 21:56:23 +01005280 void
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005281win32_build_env(dict_T *env, garray_T *gap, int is_terminal)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005282{
5283 hashitem_T *hi;
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005284 long_u todo = env != NULL ? env->dv_hashtab.ht_used : 0;
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005285 LPVOID base = GetEnvironmentStringsW();
5286
5287 /* for last \0 */
5288 if (ga_grow(gap, 1) == FAIL)
5289 return;
5290
5291 if (base)
5292 {
5293 WCHAR *p = (WCHAR*) base;
5294
5295 /* for last \0 */
5296 if (ga_grow(gap, 1) == FAIL)
5297 return;
5298
5299 while (*p != 0 || *(p + 1) != 0)
5300 {
5301 if (ga_grow(gap, 1) == OK)
5302 *((WCHAR*)gap->ga_data + gap->ga_len++) = *p;
5303 p++;
5304 }
5305 FreeEnvironmentStrings(base);
5306 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5307 }
5308
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005309 if (env != NULL)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005310 {
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005311 for (hi = env->dv_hashtab.ht_array; todo > 0; ++hi)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005312 {
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005313 if (!HASHITEM_EMPTY(hi))
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005314 {
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005315 typval_T *item = &dict_lookup(hi)->di_tv;
5316 WCHAR *wkey = enc_to_utf16((char_u *)hi->hi_key, NULL);
5317 WCHAR *wval = enc_to_utf16(get_tv_string(item), NULL);
5318 --todo;
5319 if (wkey != NULL && wval != NULL)
5320 {
5321 size_t n;
5322 size_t lkey = wcslen(wkey);
5323 size_t lval = wcslen(wval);
Bram Moolenaar60104f12017-08-14 23:25:04 +02005324
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005325 if (ga_grow(gap, (int)(lkey + lval + 2)) != OK)
5326 continue;
5327 for (n = 0; n < lkey; n++)
5328 *((WCHAR*)gap->ga_data + gap->ga_len++) = wkey[n];
5329 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'=';
5330 for (n = 0; n < lval; n++)
5331 *((WCHAR*)gap->ga_data + gap->ga_len++) = wval[n];
5332 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5333 }
5334 if (wkey != NULL) vim_free(wkey);
5335 if (wval != NULL) vim_free(wval);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005336 }
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005337 }
5338 }
5339
Bram Moolenaar493359e2018-06-12 20:25:52 +02005340# if defined(FEAT_CLIENTSERVER) || defined(FEAT_TERMINAL)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005341 {
Bram Moolenaar493359e2018-06-12 20:25:52 +02005342# ifdef FEAT_CLIENTSERVER
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005343 char_u *servername = get_vim_var_str(VV_SEND_SERVER);
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005344 size_t servername_len = STRLEN(servername);
Bram Moolenaar493359e2018-06-12 20:25:52 +02005345# endif
5346# ifdef FEAT_TERMINAL
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005347 char_u *version = get_vim_var_str(VV_VERSION);
5348 size_t version_len = STRLEN(version);
Bram Moolenaar493359e2018-06-12 20:25:52 +02005349# endif
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005350 // size of "VIM_SERVERNAME=" and value,
5351 // plus "VIM_TERMINAL=" and value,
5352 // plus two terminating NULs
5353 size_t n = 0
Bram Moolenaar493359e2018-06-12 20:25:52 +02005354# ifdef FEAT_CLIENTSERVER
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005355 + 15 + servername_len
Bram Moolenaar493359e2018-06-12 20:25:52 +02005356# endif
5357# ifdef FEAT_TERMINAL
5358 + 13 + version_len + 2
5359# endif
5360 ;
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005361
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005362 if (ga_grow(gap, (int)n) == OK)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005363 {
Bram Moolenaar493359e2018-06-12 20:25:52 +02005364# ifdef FEAT_CLIENTSERVER
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005365 for (n = 0; n < 15; n++)
5366 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5367 (WCHAR)"VIM_SERVERNAME="[n];
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005368 for (n = 0; n < servername_len; n++)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005369 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5370 (WCHAR)servername[n];
5371 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
Bram Moolenaar493359e2018-06-12 20:25:52 +02005372# endif
5373# ifdef FEAT_TERMINAL
5374 if (is_terminal)
5375 {
5376 for (n = 0; n < 13; n++)
5377 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5378 (WCHAR)"VIM_TERMINAL="[n];
5379 for (n = 0; n < version_len; n++)
5380 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5381 (WCHAR)version[n];
5382 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5383 }
5384# endif
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005385 }
5386 }
Bram Moolenaar79c6b512018-06-12 21:11:12 +02005387# endif
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005388}
5389
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005390 void
Bram Moolenaar5a1feb82017-07-22 18:04:08 +02005391mch_job_start(char *cmd, job_T *job, jobopt_T *options)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005392{
5393 STARTUPINFO si;
5394 PROCESS_INFORMATION pi;
Bram Moolenaar14207f42016-10-27 21:13:10 +02005395 HANDLE jo;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005396 SECURITY_ATTRIBUTES saAttr;
5397 channel_T *channel = NULL;
Bram Moolenaard8070362016-02-15 21:56:54 +01005398 HANDLE ifd[2];
5399 HANDLE ofd[2];
5400 HANDLE efd[2];
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005401 garray_T ga;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005402
5403 int use_null_for_in = options->jo_io[PART_IN] == JIO_NULL;
5404 int use_null_for_out = options->jo_io[PART_OUT] == JIO_NULL;
5405 int use_null_for_err = options->jo_io[PART_ERR] == JIO_NULL;
5406 int use_file_for_in = options->jo_io[PART_IN] == JIO_FILE;
5407 int use_file_for_out = options->jo_io[PART_OUT] == JIO_FILE;
5408 int use_file_for_err = options->jo_io[PART_ERR] == JIO_FILE;
5409 int use_out_for_err = options->jo_io[PART_ERR] == JIO_OUT;
5410
5411 if (use_out_for_err && use_null_for_out)
5412 use_null_for_err = TRUE;
Bram Moolenaard8070362016-02-15 21:56:54 +01005413
5414 ifd[0] = INVALID_HANDLE_VALUE;
5415 ifd[1] = INVALID_HANDLE_VALUE;
5416 ofd[0] = INVALID_HANDLE_VALUE;
5417 ofd[1] = INVALID_HANDLE_VALUE;
5418 efd[0] = INVALID_HANDLE_VALUE;
5419 efd[1] = INVALID_HANDLE_VALUE;
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005420 ga_init2(&ga, (int)sizeof(wchar_t), 500);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005421
Bram Moolenaar14207f42016-10-27 21:13:10 +02005422 jo = CreateJobObject(NULL, NULL);
5423 if (jo == NULL)
5424 {
5425 job->jv_status = JOB_FAILED;
5426 goto failed;
5427 }
5428
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005429 if (options->jo_env != NULL)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005430 win32_build_env(options->jo_env, &ga, FALSE);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005431
Bram Moolenaar76467df2016-02-12 19:30:26 +01005432 ZeroMemory(&pi, sizeof(pi));
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005433 ZeroMemory(&si, sizeof(si));
5434 si.cb = sizeof(si);
Bram Moolenaard8070362016-02-15 21:56:54 +01005435 si.dwFlags |= STARTF_USESHOWWINDOW;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005436 si.wShowWindow = SW_HIDE;
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005437
Bram Moolenaard8070362016-02-15 21:56:54 +01005438 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
5439 saAttr.bInheritHandle = TRUE;
5440 saAttr.lpSecurityDescriptor = NULL;
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005441
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005442 if (use_file_for_in)
5443 {
5444 char_u *fname = options->jo_io_name[PART_IN];
5445
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005446 ifd[0] = job_io_file_open(fname, GENERIC_READ,
5447 FILE_SHARE_READ | FILE_SHARE_WRITE,
5448 &saAttr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL);
5449 if (ifd[0] == INVALID_HANDLE_VALUE)
Bram Moolenaar94d01912016-03-08 13:48:51 +01005450 {
5451 EMSG2(_(e_notopen), fname);
5452 goto failed;
5453 }
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005454 }
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005455 else if (!use_null_for_in &&
5456 (!CreatePipe(&ifd[0], &ifd[1], &saAttr, 0)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005457 || !SetHandleInformation(ifd[1], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005458 goto failed;
5459
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005460 if (use_file_for_out)
5461 {
5462 char_u *fname = options->jo_io_name[PART_OUT];
5463
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005464 ofd[1] = job_io_file_open(fname, GENERIC_WRITE,
5465 FILE_SHARE_READ | FILE_SHARE_WRITE,
5466 &saAttr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL);
5467 if (ofd[1] == INVALID_HANDLE_VALUE)
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005468 {
5469 EMSG2(_(e_notopen), fname);
5470 goto failed;
5471 }
5472 }
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005473 else if (!use_null_for_out &&
5474 (!CreatePipe(&ofd[0], &ofd[1], &saAttr, 0)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005475 || !SetHandleInformation(ofd[0], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005476 goto failed;
5477
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005478 if (use_file_for_err)
5479 {
5480 char_u *fname = options->jo_io_name[PART_ERR];
5481
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005482 efd[1] = job_io_file_open(fname, GENERIC_WRITE,
5483 FILE_SHARE_READ | FILE_SHARE_WRITE,
5484 &saAttr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL);
5485 if (efd[1] == INVALID_HANDLE_VALUE)
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005486 {
5487 EMSG2(_(e_notopen), fname);
5488 goto failed;
5489 }
5490 }
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005491 else if (!use_out_for_err && !use_null_for_err &&
5492 (!CreatePipe(&efd[0], &efd[1], &saAttr, 0)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005493 || !SetHandleInformation(efd[0], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaard8070362016-02-15 21:56:54 +01005494 goto failed;
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005495
Bram Moolenaard8070362016-02-15 21:56:54 +01005496 si.dwFlags |= STARTF_USESTDHANDLES;
5497 si.hStdInput = ifd[0];
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005498 si.hStdOutput = ofd[1];
5499 si.hStdError = use_out_for_err ? ofd[1] : efd[1];
5500
5501 if (!use_null_for_in || !use_null_for_out || !use_null_for_err)
5502 {
Bram Moolenaarde279892016-03-11 22:19:44 +01005503 if (options->jo_set & JO_CHANNEL)
5504 {
5505 channel = options->jo_channel;
5506 if (channel != NULL)
5507 ++channel->ch_refcount;
5508 }
5509 else
5510 channel = add_channel();
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005511 if (channel == NULL)
5512 goto failed;
5513 }
Bram Moolenaard8070362016-02-15 21:56:54 +01005514
5515 if (!vim_create_process(cmd, TRUE,
Bram Moolenaar14207f42016-10-27 21:13:10 +02005516 CREATE_SUSPENDED |
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005517 CREATE_DEFAULT_ERROR_MODE |
5518 CREATE_NEW_PROCESS_GROUP |
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005519 CREATE_UNICODE_ENVIRONMENT |
Bram Moolenaar76467df2016-02-12 19:30:26 +01005520 CREATE_NEW_CONSOLE,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005521 &si, &pi,
5522 ga.ga_data,
5523 (char *)options->jo_cwd))
Bram Moolenaar76467df2016-02-12 19:30:26 +01005524 {
Bram Moolenaar14207f42016-10-27 21:13:10 +02005525 CloseHandle(jo);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005526 job->jv_status = JOB_FAILED;
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005527 goto failed;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005528 }
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005529
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005530 ga_clear(&ga);
5531
Bram Moolenaar14207f42016-10-27 21:13:10 +02005532 if (!AssignProcessToJobObject(jo, pi.hProcess))
5533 {
5534 /* if failing, switch the way to terminate
5535 * process with TerminateProcess. */
5536 CloseHandle(jo);
5537 jo = NULL;
5538 }
5539 ResumeThread(pi.hThread);
Bram Moolenaar75578a32016-03-10 16:33:31 +01005540 CloseHandle(pi.hThread);
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005541 job->jv_proc_info = pi;
Bram Moolenaar14207f42016-10-27 21:13:10 +02005542 job->jv_job_object = jo;
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005543 job->jv_status = JOB_STARTED;
5544
Bram Moolenaar641ad6c2016-09-01 18:32:11 +02005545 CloseHandle(ifd[0]);
5546 CloseHandle(ofd[1]);
5547 if (!use_out_for_err && !use_null_for_err)
Bram Moolenaarc25558b2016-03-03 21:02:23 +01005548 CloseHandle(efd[1]);
Bram Moolenaard8070362016-02-15 21:56:54 +01005549
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005550 job->jv_channel = channel;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005551 if (channel != NULL)
5552 {
5553 channel_set_pipes(channel,
5554 use_file_for_in || use_null_for_in
5555 ? INVALID_FD : (sock_T)ifd[1],
5556 use_file_for_out || use_null_for_out
5557 ? INVALID_FD : (sock_T)ofd[0],
5558 use_out_for_err || use_file_for_err || use_null_for_err
5559 ? INVALID_FD : (sock_T)efd[0]);
5560 channel_set_job(channel, job, options);
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005561 }
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005562 return;
5563
5564failed:
Bram Moolenaard8070362016-02-15 21:56:54 +01005565 CloseHandle(ifd[0]);
5566 CloseHandle(ofd[0]);
5567 CloseHandle(efd[0]);
5568 CloseHandle(ifd[1]);
5569 CloseHandle(ofd[1]);
5570 CloseHandle(efd[1]);
Bram Moolenaarde279892016-03-11 22:19:44 +01005571 channel_unref(channel);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005572 ga_clear(&ga);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005573}
5574
5575 char *
5576mch_job_status(job_T *job)
5577{
5578 DWORD dwExitCode = 0;
5579
Bram Moolenaar76467df2016-02-12 19:30:26 +01005580 if (!GetExitCodeProcess(job->jv_proc_info.hProcess, &dwExitCode)
5581 || dwExitCode != STILL_ACTIVE)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005582 {
Bram Moolenaareab089d2016-02-21 19:32:02 +01005583 job->jv_exitval = (int)dwExitCode;
Bram Moolenaar7df915d2016-11-17 17:25:32 +01005584 if (job->jv_status < JOB_ENDED)
Bram Moolenaar97792de2016-10-15 18:36:49 +02005585 {
5586 ch_log(job->jv_channel, "Job ended");
5587 job->jv_status = JOB_ENDED;
5588 }
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005589 return "dead";
5590 }
5591 return "run";
5592}
5593
Bram Moolenaar97792de2016-10-15 18:36:49 +02005594 job_T *
5595mch_detect_ended_job(job_T *job_list)
5596{
5597 HANDLE jobHandles[MAXIMUM_WAIT_OBJECTS];
5598 job_T *jobArray[MAXIMUM_WAIT_OBJECTS];
5599 job_T *job = job_list;
5600
5601 while (job != NULL)
5602 {
5603 DWORD n;
5604 DWORD result;
5605
5606 for (n = 0; n < MAXIMUM_WAIT_OBJECTS
5607 && job != NULL; job = job->jv_next)
5608 {
5609 if (job->jv_status == JOB_STARTED)
5610 {
5611 jobHandles[n] = job->jv_proc_info.hProcess;
5612 jobArray[n] = job;
5613 ++n;
5614 }
5615 }
5616 if (n == 0)
5617 continue;
5618 result = WaitForMultipleObjects(n, jobHandles, FALSE, 0);
5619 if (result >= WAIT_OBJECT_0 && result < WAIT_OBJECT_0 + n)
5620 {
5621 job_T *wait_job = jobArray[result - WAIT_OBJECT_0];
5622
5623 if (STRCMP(mch_job_status(wait_job), "dead") == 0)
5624 return wait_job;
5625 }
5626 }
5627 return NULL;
5628}
5629
Bram Moolenaarfb630902016-10-29 14:55:00 +02005630 static BOOL
5631terminate_all(HANDLE process, int code)
5632{
5633 PROCESSENTRY32 pe;
5634 HANDLE h = INVALID_HANDLE_VALUE;
5635 DWORD pid = GetProcessId(process);
5636
5637 if (pid != 0)
5638 {
5639 h = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
5640 if (h != INVALID_HANDLE_VALUE)
5641 {
5642 pe.dwSize = sizeof(PROCESSENTRY32);
5643 if (!Process32First(h, &pe))
5644 goto theend;
5645
5646 do
5647 {
5648 if (pe.th32ParentProcessID == pid)
5649 {
5650 HANDLE ph = OpenProcess(
5651 PROCESS_ALL_ACCESS, FALSE, pe.th32ProcessID);
5652 if (ph != NULL)
5653 {
5654 terminate_all(ph, code);
5655 CloseHandle(ph);
5656 }
5657 }
5658 } while (Process32Next(h, &pe));
5659
5660 CloseHandle(h);
5661 }
5662 }
5663
5664theend:
5665 return TerminateProcess(process, code);
5666}
5667
5668/*
5669 * Send a (deadly) signal to "job".
5670 * Return FAIL if it didn't work.
5671 */
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005672 int
Bram Moolenaar2d33e902017-08-11 16:31:54 +02005673mch_signal_job(job_T *job, char_u *how)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005674{
Bram Moolenaar923d9262016-02-25 20:56:01 +01005675 int ret;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005676
Bram Moolenaar923d9262016-02-25 20:56:01 +01005677 if (STRCMP(how, "term") == 0 || STRCMP(how, "kill") == 0 || *how == NUL)
Bram Moolenaar76467df2016-02-12 19:30:26 +01005678 {
Bram Moolenaarfb630902016-10-29 14:55:00 +02005679 /* deadly signal */
Bram Moolenaar14207f42016-10-27 21:13:10 +02005680 if (job->jv_job_object != NULL)
5681 return TerminateJobObject(job->jv_job_object, 0) ? OK : FAIL;
Bram Moolenaarfb630902016-10-29 14:55:00 +02005682 return terminate_all(job->jv_proc_info.hProcess, 0) ? OK : FAIL;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005683 }
5684
5685 if (!AttachConsole(job->jv_proc_info.dwProcessId))
5686 return FAIL;
5687 ret = GenerateConsoleCtrlEvent(
Bram Moolenaar923d9262016-02-25 20:56:01 +01005688 STRCMP(how, "int") == 0 ? CTRL_C_EVENT : CTRL_BREAK_EVENT,
5689 job->jv_proc_info.dwProcessId)
5690 ? OK : FAIL;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005691 FreeConsole();
5692 return ret;
5693}
5694
5695/*
5696 * Clear the data related to "job".
5697 */
5698 void
5699mch_clear_job(job_T *job)
5700{
5701 if (job->jv_status != JOB_FAILED)
5702 {
Bram Moolenaar14207f42016-10-27 21:13:10 +02005703 if (job->jv_job_object != NULL)
5704 CloseHandle(job->jv_job_object);
Bram Moolenaar76467df2016-02-12 19:30:26 +01005705 CloseHandle(job->jv_proc_info.hProcess);
5706 }
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005707}
5708#endif
5709
Bram Moolenaar071d4272004-06-13 20:20:40 +00005710
5711#ifndef FEAT_GUI_W32
5712
5713/*
5714 * Start termcap mode
5715 */
5716 static void
5717termcap_mode_start(void)
5718{
5719 DWORD cmodein;
5720
5721 if (g_fTermcapMode)
5722 return;
5723
5724 SaveConsoleBuffer(&g_cbNonTermcap);
5725
5726 if (g_cbTermcap.IsValid)
5727 {
5728 /*
5729 * We've been in termcap mode before. Restore certain screen
5730 * characteristics, including the buffer size and the window
5731 * size. Since we will be redrawing the screen, we don't need
5732 * to restore the actual contents of the buffer.
5733 */
5734 RestoreConsoleBuffer(&g_cbTermcap, FALSE);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005735 reset_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005736 SetConsoleWindowInfo(g_hConOut, TRUE, &g_cbTermcap.Info.srWindow);
5737 Rows = g_cbTermcap.Info.dwSize.Y;
5738 Columns = g_cbTermcap.Info.dwSize.X;
5739 }
5740 else
5741 {
5742 /*
5743 * This is our first time entering termcap mode. Clear the console
5744 * screen buffer, and resize the buffer to match the current window
5745 * size. We will use this as the size of our editing environment.
5746 */
5747 ClearConsoleBuffer(g_attrCurrent);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005748 set_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005749 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
5750 }
5751
5752#ifdef FEAT_TITLE
5753 resettitle();
5754#endif
5755
5756 GetConsoleMode(g_hConIn, &cmodein);
5757#ifdef FEAT_MOUSE
5758 if (g_fMouseActive)
5759 cmodein |= ENABLE_MOUSE_INPUT;
5760 else
5761 cmodein &= ~ENABLE_MOUSE_INPUT;
5762#endif
5763 cmodein |= ENABLE_WINDOW_INPUT;
5764 SetConsoleMode(g_hConIn, cmodein);
5765
5766 redraw_later_clear();
5767 g_fTermcapMode = TRUE;
5768}
5769
5770
5771/*
5772 * End termcap mode
5773 */
5774 static void
5775termcap_mode_end(void)
5776{
5777 DWORD cmodein;
5778 ConsoleBuffer *cb;
5779 COORD coord;
5780 DWORD dwDummy;
5781
5782 if (!g_fTermcapMode)
5783 return;
5784
5785 SaveConsoleBuffer(&g_cbTermcap);
5786
5787 GetConsoleMode(g_hConIn, &cmodein);
5788 cmodein &= ~(ENABLE_MOUSE_INPUT | ENABLE_WINDOW_INPUT);
5789 SetConsoleMode(g_hConIn, cmodein);
5790
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01005791#ifdef FEAT_RESTORE_ORIG_SCREEN
5792 cb = exiting ? &g_cbOrig : &g_cbNonTermcap;
5793#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00005794 cb = &g_cbNonTermcap;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01005795#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005796 RestoreConsoleBuffer(cb, p_rs);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005797 reset_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005798 SetConsoleCursorInfo(g_hConOut, &g_cci);
5799
5800 if (p_rs || exiting)
5801 {
5802 /*
5803 * Clear anything that happens to be on the current line.
5804 */
5805 coord.X = 0;
5806 coord.Y = (SHORT) (p_rs ? cb->Info.dwCursorPosition.Y : (Rows - 1));
5807 FillConsoleOutputCharacter(g_hConOut, ' ',
5808 cb->Info.dwSize.X, coord, &dwDummy);
5809 /*
5810 * The following is just for aesthetics. If we are exiting without
5811 * restoring the screen, then we want to have a prompt string
5812 * appear at the bottom line. However, the command interpreter
5813 * seems to always advance the cursor one line before displaying
5814 * the prompt string, which causes the screen to scroll. To
5815 * counter this, move the cursor up one line before exiting.
5816 */
5817 if (exiting && !p_rs)
5818 coord.Y--;
5819 /*
5820 * Position the cursor at the leftmost column of the desired row.
5821 */
5822 SetConsoleCursorPosition(g_hConOut, coord);
5823 }
5824
5825 g_fTermcapMode = FALSE;
5826}
5827#endif /* FEAT_GUI_W32 */
5828
5829
5830#ifdef FEAT_GUI_W32
5831 void
5832mch_write(
Bram Moolenaar1266d672017-02-01 13:43:36 +01005833 char_u *s UNUSED,
5834 int len UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005835{
5836 /* never used */
5837}
5838
5839#else
5840
5841/*
5842 * clear `n' chars, starting from `coord'
5843 */
5844 static void
5845clear_chars(
5846 COORD coord,
5847 DWORD n)
5848{
5849 DWORD dwDummy;
5850
5851 FillConsoleOutputCharacter(g_hConOut, ' ', n, coord, &dwDummy);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005852
5853 if (!USE_VTP)
5854 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, n, coord, &dwDummy);
5855 else
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02005856 {
5857 set_console_color_rgb();
5858 gotoxy(coord.X + 1, coord.Y + 1);
5859 vtp_printf("\033[%dX", n);
5860 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005861}
5862
5863
5864/*
5865 * Clear the screen
5866 */
5867 static void
5868clear_screen(void)
5869{
5870 g_coord.X = g_coord.Y = 0;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005871
5872 if (!USE_VTP)
5873 clear_chars(g_coord, Rows * Columns);
5874 else
5875 {
5876 set_console_color_rgb();
5877 gotoxy(1, 1);
5878 vtp_printf("\033[2J");
5879 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005880}
5881
5882
5883/*
5884 * Clear to end of display
5885 */
5886 static void
5887clear_to_end_of_display(void)
5888{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005889 COORD save = g_coord;
5890
5891 if (!USE_VTP)
5892 clear_chars(g_coord, (Rows - g_coord.Y - 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005893 * Columns + (Columns - g_coord.X));
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005894 else
5895 {
5896 set_console_color_rgb();
5897 gotoxy(g_coord.X + 1, g_coord.Y + 1);
5898 vtp_printf("\033[0J");
5899
5900 gotoxy(save.X + 1, save.Y + 1);
5901 g_coord = save;
5902 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005903}
5904
5905
5906/*
5907 * Clear to end of line
5908 */
5909 static void
5910clear_to_end_of_line(void)
5911{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005912 COORD save = g_coord;
5913
5914 if (!USE_VTP)
5915 clear_chars(g_coord, Columns - g_coord.X);
5916 else
5917 {
5918 set_console_color_rgb();
5919 gotoxy(g_coord.X + 1, g_coord.Y + 1);
5920 vtp_printf("\033[0K");
5921
5922 gotoxy(save.X + 1, save.Y + 1);
5923 g_coord = save;
5924 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005925}
5926
5927
5928/*
5929 * Scroll the scroll region up by `cLines' lines
5930 */
5931 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005932scroll(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005933{
5934 COORD oldcoord = g_coord;
5935
5936 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
5937 delete_lines(cLines);
5938
5939 g_coord = oldcoord;
5940}
5941
5942
5943/*
5944 * Set the scroll region
5945 */
5946 static void
5947set_scroll_region(
5948 unsigned left,
5949 unsigned top,
5950 unsigned right,
5951 unsigned bottom)
5952{
5953 if (left >= right
5954 || top >= bottom
5955 || right > (unsigned) Columns - 1
5956 || bottom > (unsigned) Rows - 1)
5957 return;
5958
5959 g_srScrollRegion.Left = left;
5960 g_srScrollRegion.Top = top;
5961 g_srScrollRegion.Right = right;
5962 g_srScrollRegion.Bottom = bottom;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005963
5964 if (USE_VTP)
5965 vtp_printf("\033[%d;%dr", top + 1, bottom + 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005966}
5967
5968
5969/*
5970 * Insert `cLines' lines at the current cursor position
5971 */
5972 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005973insert_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005974{
5975 SMALL_RECT source;
5976 COORD dest;
5977 CHAR_INFO fill;
5978
5979 dest.X = 0;
5980 dest.Y = g_coord.Y + cLines;
5981
5982 source.Left = 0;
5983 source.Top = g_coord.Y;
5984 source.Right = g_srScrollRegion.Right;
5985 source.Bottom = g_srScrollRegion.Bottom - cLines;
5986
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005987 if (!USE_VTP)
5988 {
5989 fill.Char.AsciiChar = ' ';
5990 fill.Attributes = g_attrCurrent;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005991
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005992 ScrollConsoleScreenBuffer(g_hConOut, &source, NULL, dest, &fill);
5993 }
5994 else
5995 {
5996 set_console_color_rgb();
5997
5998 gotoxy(1, source.Top + 1);
5999 vtp_printf("\033[%dT", cLines);
6000 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006001
6002 /* Here we have to deal with a win32 console flake: If the scroll
6003 * region looks like abc and we scroll c to a and fill with d we get
6004 * cbd... if we scroll block c one line at a time to a, we get cdd...
6005 * vim expects cdd consistently... So we have to deal with that
6006 * here... (this also occurs scrolling the same way in the other
6007 * direction). */
6008
6009 if (source.Bottom < dest.Y)
6010 {
6011 COORD coord;
6012
6013 coord.X = 0;
6014 coord.Y = source.Bottom;
6015 clear_chars(coord, Columns * (dest.Y - source.Bottom));
6016 }
6017}
6018
6019
6020/*
6021 * Delete `cLines' lines at the current cursor position
6022 */
6023 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006024delete_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006025{
6026 SMALL_RECT source;
6027 COORD dest;
6028 CHAR_INFO fill;
6029 int nb;
6030
6031 dest.X = 0;
6032 dest.Y = g_coord.Y;
6033
6034 source.Left = 0;
6035 source.Top = g_coord.Y + cLines;
6036 source.Right = g_srScrollRegion.Right;
6037 source.Bottom = g_srScrollRegion.Bottom;
6038
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006039 if (!USE_VTP)
6040 {
6041 fill.Char.AsciiChar = ' ';
6042 fill.Attributes = g_attrCurrent;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006043
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006044 ScrollConsoleScreenBuffer(g_hConOut, &source, NULL, dest, &fill);
6045 }
6046 else
6047 {
6048 set_console_color_rgb();
6049
6050 gotoxy(1, source.Top + 1);
6051 vtp_printf("\033[%dS", cLines);
6052 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006053
6054 /* Here we have to deal with a win32 console flake: If the scroll
6055 * region looks like abc and we scroll c to a and fill with d we get
6056 * cbd... if we scroll block c one line at a time to a, we get cdd...
6057 * vim expects cdd consistently... So we have to deal with that
6058 * here... (this also occurs scrolling the same way in the other
6059 * direction). */
6060
6061 nb = dest.Y + (source.Bottom - source.Top) + 1;
6062
6063 if (nb < source.Top)
6064 {
6065 COORD coord;
6066
6067 coord.X = 0;
6068 coord.Y = nb;
6069 clear_chars(coord, Columns * (source.Top - nb));
6070 }
6071}
6072
6073
6074/*
6075 * Set the cursor position
6076 */
6077 static void
6078gotoxy(
6079 unsigned x,
6080 unsigned y)
6081{
6082 if (x < 1 || x > (unsigned)Columns || y < 1 || y > (unsigned)Rows)
6083 return;
6084
6085 /* external cursor coords are 1-based; internal are 0-based */
6086 g_coord.X = x - 1;
6087 g_coord.Y = y - 1;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006088
6089 if (!USE_VTP)
6090 SetConsoleCursorPosition(g_hConOut, g_coord);
6091 else
6092 vtp_printf("\033[%d;%dH", y, x);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006093}
6094
6095
6096/*
6097 * Set the current text attribute = (foreground | background)
6098 * See ../doc/os_win32.txt for the numbers.
6099 */
6100 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006101textattr(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006102{
Bram Moolenaar6383b922015-03-24 17:12:19 +01006103 g_attrCurrent = wAttr & 0xff;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006104
6105 SetConsoleTextAttribute(g_hConOut, wAttr);
6106}
6107
6108
6109 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006110textcolor(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006111{
Bram Moolenaar6383b922015-03-24 17:12:19 +01006112 g_attrCurrent = (g_attrCurrent & 0xf0) + (wAttr & 0x0f);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006113
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006114 if (!USE_VTP)
6115 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
6116 else
6117 vtp_sgr_bulk(wAttr);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006118}
6119
6120
6121 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006122textbackground(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006123{
Bram Moolenaar6383b922015-03-24 17:12:19 +01006124 g_attrCurrent = (g_attrCurrent & 0x0f) + ((wAttr & 0x0f) << 4);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006125
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006126 if (!USE_VTP)
6127 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
6128 else
6129 vtp_sgr_bulk(wAttr);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006130}
6131
6132
6133/*
6134 * restore the default text attribute (whatever we started with)
6135 */
6136 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006137normvideo(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006138{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006139 if (!USE_VTP)
6140 textattr(g_attrDefault);
6141 else
6142 vtp_sgr_bulk(0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006143}
6144
6145
6146static WORD g_attrPreStandout = 0;
6147
6148/*
6149 * Make the text standout, by brightening it
6150 */
6151 static void
6152standout(void)
6153{
6154 g_attrPreStandout = g_attrCurrent;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006155
Bram Moolenaar071d4272004-06-13 20:20:40 +00006156 textattr((WORD) (g_attrCurrent|FOREGROUND_INTENSITY|BACKGROUND_INTENSITY));
6157}
6158
6159
6160/*
6161 * Turn off standout mode
6162 */
6163 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006164standend(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006165{
6166 if (g_attrPreStandout)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006167 textattr(g_attrPreStandout);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006168
6169 g_attrPreStandout = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006170}
6171
6172
6173/*
Bram Moolenaarff1d0d42007-05-10 17:24:16 +00006174 * Set normal fg/bg color, based on T_ME. Called when t_me has been set.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006175 */
6176 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006177mch_set_normal_colors(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006178{
6179 char_u *p;
6180 int n;
6181
6182 cterm_normal_fg_color = (g_attrDefault & 0xf) + 1;
6183 cterm_normal_bg_color = ((g_attrDefault >> 4) & 0xf) + 1;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006184 if (
6185#ifdef FEAT_TERMGUICOLORS
6186 !p_tgc &&
6187#endif
6188 T_ME[0] == ESC && T_ME[1] == '|')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006189 {
6190 p = T_ME + 2;
6191 n = getdigits(&p);
6192 if (*p == 'm' && n > 0)
6193 {
6194 cterm_normal_fg_color = (n & 0xf) + 1;
6195 cterm_normal_bg_color = ((n >> 4) & 0xf) + 1;
6196 }
6197 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006198#ifdef FEAT_TERMGUICOLORS
6199 cterm_normal_fg_gui_color = INVALCOLOR;
6200 cterm_normal_bg_gui_color = INVALCOLOR;
6201#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006202}
6203
6204
6205/*
6206 * visual bell: flash the screen
6207 */
6208 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006209visual_bell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006210{
6211 COORD coordOrigin = {0, 0};
6212 WORD attrFlash = ~g_attrCurrent & 0xff;
6213
6214 DWORD dwDummy;
6215 LPWORD oldattrs = (LPWORD)alloc(Rows * Columns * sizeof(WORD));
6216
6217 if (oldattrs == NULL)
6218 return;
6219 ReadConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
6220 coordOrigin, &dwDummy);
6221 FillConsoleOutputAttribute(g_hConOut, attrFlash, Rows * Columns,
6222 coordOrigin, &dwDummy);
6223
6224 Sleep(15); /* wait for 15 msec */
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006225 if (!USE_VTP)
6226 WriteConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
Bram Moolenaar071d4272004-06-13 20:20:40 +00006227 coordOrigin, &dwDummy);
6228 vim_free(oldattrs);
6229}
6230
6231
6232/*
6233 * Make the cursor visible or invisible
6234 */
6235 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006236cursor_visible(BOOL fVisible)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006237{
6238 s_cursor_visible = fVisible;
6239#ifdef MCH_CURSOR_SHAPE
6240 mch_update_cursor();
6241#endif
6242}
6243
6244
6245/*
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02006246 * Write "cbToWrite" bytes in `pchBuf' to the screen.
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006247 * Returns the number of bytes actually written (at least one).
Bram Moolenaar071d4272004-06-13 20:20:40 +00006248 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006249 static DWORD
Bram Moolenaar071d4272004-06-13 20:20:40 +00006250write_chars(
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006251 char_u *pchBuf,
6252 DWORD cbToWrite)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006253{
6254 COORD coord = g_coord;
6255 DWORD written;
6256
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006257#ifdef FEAT_MBYTE
6258 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
6259 {
6260 static WCHAR *unicodebuf = NULL;
6261 static int unibuflen = 0;
6262 int length;
6263 DWORD n, cchwritten, cells;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006264
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006265 length = MultiByteToWideChar(CP_UTF8, 0, (LPCSTR)pchBuf, cbToWrite, 0, 0);
6266 if (unicodebuf == NULL || length > unibuflen)
6267 {
6268 vim_free(unicodebuf);
6269 unicodebuf = (WCHAR *)lalloc(length * sizeof(WCHAR), FALSE);
6270 unibuflen = length;
6271 }
6272 MultiByteToWideChar(CP_UTF8, 0, (LPCSTR)pchBuf, cbToWrite,
6273 unicodebuf, unibuflen);
6274
6275 cells = mb_string2cells(pchBuf, cbToWrite);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006276
6277 if (!USE_VTP)
6278 {
6279 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, cells,
6280 coord, &written);
6281 /* When writing fails or didn't write a single character, pretend one
6282 * character was written, otherwise we get stuck. */
6283 if (WriteConsoleOutputCharacterW(g_hConOut, unicodebuf, length,
6284 coord, &cchwritten) == 0
6285 || cchwritten == 0)
6286 cchwritten = 1;
6287 }
6288 else
6289 {
6290 if (WriteConsoleW(g_hConOut, unicodebuf, length, &cchwritten,
6291 NULL) == 0 || cchwritten == 0)
6292 cchwritten = 1;
6293 }
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006294
6295 if (cchwritten == length)
6296 {
6297 written = cbToWrite;
6298 g_coord.X += (SHORT)cells;
6299 }
6300 else
6301 {
6302 char_u *p = pchBuf;
6303 for (n = 0; n < cchwritten; n++)
Bram Moolenaar91acfff2017-03-12 19:22:36 +01006304 MB_CPTR_ADV(p);
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006305 written = p - pchBuf;
6306 g_coord.X += (SHORT)mb_string2cells(pchBuf, written);
6307 }
6308 }
6309 else
6310#endif
6311 {
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006312 if (!USE_VTP)
6313 {
6314 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, cbToWrite,
6315 coord, &written);
6316 /* When writing fails or didn't write a single character, pretend one
6317 * character was written, otherwise we get stuck. */
6318 if (WriteConsoleOutputCharacter(g_hConOut, (LPCSTR)pchBuf, cbToWrite,
6319 coord, &written) == 0
6320 || written == 0)
6321 written = 1;
6322 }
6323 else
6324 {
6325 if (WriteConsole(g_hConOut, (LPCSTR)pchBuf, cbToWrite, &written,
6326 NULL) == 0 || written == 0)
6327 written = 1;
6328 }
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006329
6330 g_coord.X += (SHORT) written;
6331 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006332
6333 while (g_coord.X > g_srScrollRegion.Right)
6334 {
6335 g_coord.X -= (SHORT) Columns;
6336 if (g_coord.Y < g_srScrollRegion.Bottom)
6337 g_coord.Y++;
6338 }
6339
6340 gotoxy(g_coord.X + 1, g_coord.Y + 1);
6341
6342 return written;
6343}
6344
6345
6346/*
6347 * mch_write(): write the output buffer to the screen, translating ESC
6348 * sequences into calls to console output routines.
6349 */
6350 void
6351mch_write(
6352 char_u *s,
6353 int len)
6354{
6355 s[len] = NUL;
6356
6357 if (!term_console)
6358 {
6359 write(1, s, (unsigned)len);
6360 return;
6361 }
6362
6363 /* translate ESC | sequences into faked bios calls */
6364 while (len--)
6365 {
6366 /* optimization: use one single write_chars for runs of text,
6367 * rather than once per character It ain't curses, but it helps. */
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006368 DWORD prefix = (DWORD)strcspn((char *)s, "\n\r\b\a\033");
Bram Moolenaar071d4272004-06-13 20:20:40 +00006369
6370 if (p_wd)
6371 {
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02006372 WaitForChar(p_wd, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006373 if (prefix != 0)
6374 prefix = 1;
6375 }
6376
6377 if (prefix != 0)
6378 {
6379 DWORD nWritten;
6380
6381 nWritten = write_chars(s, prefix);
6382#ifdef MCH_WRITE_DUMP
6383 if (fdDump)
6384 {
6385 fputc('>', fdDump);
6386 fwrite(s, sizeof(char_u), nWritten, fdDump);
6387 fputs("<\n", fdDump);
6388 }
6389#endif
6390 len -= (nWritten - 1);
6391 s += nWritten;
6392 }
6393 else if (s[0] == '\n')
6394 {
6395 /* \n, newline: go to the beginning of the next line or scroll */
6396 if (g_coord.Y == g_srScrollRegion.Bottom)
6397 {
6398 scroll(1);
6399 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Bottom + 1);
6400 }
6401 else
6402 {
6403 gotoxy(g_srScrollRegion.Left + 1, g_coord.Y + 2);
6404 }
6405#ifdef MCH_WRITE_DUMP
6406 if (fdDump)
6407 fputs("\\n\n", fdDump);
6408#endif
6409 s++;
6410 }
6411 else if (s[0] == '\r')
6412 {
6413 /* \r, carriage return: go to beginning of line */
6414 gotoxy(g_srScrollRegion.Left+1, g_coord.Y + 1);
6415#ifdef MCH_WRITE_DUMP
6416 if (fdDump)
6417 fputs("\\r\n", fdDump);
6418#endif
6419 s++;
6420 }
6421 else if (s[0] == '\b')
6422 {
6423 /* \b, backspace: move cursor one position left */
6424 if (g_coord.X > g_srScrollRegion.Left)
6425 g_coord.X--;
6426 else if (g_coord.Y > g_srScrollRegion.Top)
6427 {
6428 g_coord.X = g_srScrollRegion.Right;
6429 g_coord.Y--;
6430 }
6431 gotoxy(g_coord.X + 1, g_coord.Y + 1);
6432#ifdef MCH_WRITE_DUMP
6433 if (fdDump)
6434 fputs("\\b\n", fdDump);
6435#endif
6436 s++;
6437 }
6438 else if (s[0] == '\a')
6439 {
6440 /* \a, bell */
6441 MessageBeep(0xFFFFFFFF);
6442#ifdef MCH_WRITE_DUMP
6443 if (fdDump)
6444 fputs("\\a\n", fdDump);
6445#endif
6446 s++;
6447 }
6448 else if (s[0] == ESC && len >= 3-1 && s[1] == '|')
6449 {
6450#ifdef MCH_WRITE_DUMP
Bram Moolenaarc0197e22004-09-13 20:26:32 +00006451 char_u *old_s = s;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006452#endif
Bram Moolenaarc0197e22004-09-13 20:26:32 +00006453 char_u *p;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006454 int arg1 = 0, arg2 = 0, argc = 0, args[16];
Bram Moolenaar071d4272004-06-13 20:20:40 +00006455
6456 switch (s[2])
6457 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006458 case '0': case '1': case '2': case '3': case '4':
6459 case '5': case '6': case '7': case '8': case '9':
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006460 p = s + 1;
6461 do
6462 {
6463 ++p;
6464 args[argc] = getdigits(&p);
6465 argc += (argc < 15) ? 1 : 0;
6466 if (p > s + len)
6467 break;
6468 } while (*p == ';');
6469
Bram Moolenaar071d4272004-06-13 20:20:40 +00006470 if (p > s + len)
6471 break;
6472
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006473 arg1 = args[0];
6474 arg2 = args[1];
6475 if (*p == 'm')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006476 {
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006477 if (argc == 1 && args[0] == 0)
6478 normvideo();
6479 else if (argc == 1)
6480 {
6481 if (USE_VTP)
6482 textcolor((WORD) arg1);
6483 else
6484 textattr((WORD) arg1);
6485 }
6486 else if (USE_VTP)
6487 vtp_sgr_bulks(argc, args);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006488 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006489 else if (argc == 2 && *p == 'H')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006490 {
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006491 gotoxy(arg2, arg1);
6492 }
6493 else if (argc == 2 && *p == 'r')
6494 {
6495 set_scroll_region(0, arg1 - 1, Columns - 1, arg2 - 1);
6496 }
6497 else if (argc == 1 && *p == 'A')
6498 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006499 gotoxy(g_coord.X + 1,
6500 max(g_srScrollRegion.Top, g_coord.Y - arg1) + 1);
6501 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006502 else if (argc == 1 && *p == 'b')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006503 {
6504 textbackground((WORD) arg1);
6505 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006506 else if (argc == 1 && *p == 'C')
6507 {
6508 gotoxy(min(g_srScrollRegion.Right, g_coord.X + arg1) + 1,
6509 g_coord.Y + 1);
6510 }
6511 else if (argc == 1 && *p == 'f')
6512 {
6513 textcolor((WORD) arg1);
6514 }
6515 else if (argc == 1 && *p == 'H')
6516 {
6517 gotoxy(1, arg1);
6518 }
6519 else if (argc == 1 && *p == 'L')
6520 {
6521 insert_lines(arg1);
6522 }
6523 else if (argc == 1 && *p == 'M')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006524 {
6525 delete_lines(arg1);
6526 }
6527
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006528 len -= (int)(p - s);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006529 s = p + 1;
6530 break;
6531
Bram Moolenaar071d4272004-06-13 20:20:40 +00006532 case 'A':
Bram Moolenaar071d4272004-06-13 20:20:40 +00006533 gotoxy(g_coord.X + 1,
6534 max(g_srScrollRegion.Top, g_coord.Y - 1) + 1);
6535 goto got3;
6536
6537 case 'B':
6538 visual_bell();
6539 goto got3;
6540
6541 case 'C':
Bram Moolenaar071d4272004-06-13 20:20:40 +00006542 gotoxy(min(g_srScrollRegion.Right, g_coord.X + 1) + 1,
6543 g_coord.Y + 1);
6544 goto got3;
6545
6546 case 'E':
6547 termcap_mode_end();
6548 goto got3;
6549
6550 case 'F':
6551 standout();
6552 goto got3;
6553
6554 case 'f':
6555 standend();
6556 goto got3;
6557
6558 case 'H':
6559 gotoxy(1, 1);
6560 goto got3;
6561
6562 case 'j':
6563 clear_to_end_of_display();
6564 goto got3;
6565
6566 case 'J':
6567 clear_screen();
6568 goto got3;
6569
6570 case 'K':
6571 clear_to_end_of_line();
6572 goto got3;
6573
6574 case 'L':
6575 insert_lines(1);
6576 goto got3;
6577
6578 case 'M':
6579 delete_lines(1);
6580 goto got3;
6581
6582 case 'S':
6583 termcap_mode_start();
6584 goto got3;
6585
6586 case 'V':
6587 cursor_visible(TRUE);
6588 goto got3;
6589
6590 case 'v':
6591 cursor_visible(FALSE);
6592 goto got3;
6593
6594 got3:
6595 s += 3;
6596 len -= 2;
6597 }
6598
6599#ifdef MCH_WRITE_DUMP
6600 if (fdDump)
6601 {
6602 fputs("ESC | ", fdDump);
6603 fwrite(old_s + 2, sizeof(char_u), s - old_s - 2, fdDump);
6604 fputc('\n', fdDump);
6605 }
6606#endif
6607 }
6608 else
6609 {
6610 /* Write a single character */
6611 DWORD nWritten;
6612
6613 nWritten = write_chars(s, 1);
6614#ifdef MCH_WRITE_DUMP
6615 if (fdDump)
6616 {
6617 fputc('>', fdDump);
6618 fwrite(s, sizeof(char_u), nWritten, fdDump);
6619 fputs("<\n", fdDump);
6620 }
6621#endif
6622
6623 len -= (nWritten - 1);
6624 s += nWritten;
6625 }
6626 }
6627
6628#ifdef MCH_WRITE_DUMP
6629 if (fdDump)
6630 fflush(fdDump);
6631#endif
6632}
6633
6634#endif /* FEAT_GUI_W32 */
6635
6636
6637/*
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01006638 * Delay for "msec" milliseconds.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006639 */
6640 void
6641mch_delay(
6642 long msec,
Bram Moolenaar1266d672017-02-01 13:43:36 +01006643 int ignoreinput UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006644{
6645#ifdef FEAT_GUI_W32
6646 Sleep((int)msec); /* never wait for input */
Bram Moolenaar325b7a22004-07-05 15:58:32 +00006647#else /* Console */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006648 if (ignoreinput)
Bram Moolenaar325b7a22004-07-05 15:58:32 +00006649# ifdef FEAT_MZSCHEME
6650 if (mzthreads_allowed() && p_mzq > 0 && msec > p_mzq)
6651 {
6652 int towait = p_mzq;
6653
6654 /* if msec is large enough, wait by portions in p_mzq */
6655 while (msec > 0)
6656 {
6657 mzvim_check_threads();
6658 if (msec < towait)
6659 towait = msec;
6660 Sleep(towait);
6661 msec -= towait;
6662 }
6663 }
6664 else
6665# endif
6666 Sleep((int)msec);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006667 else
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02006668 WaitForChar(msec, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006669#endif
6670}
6671
6672
6673/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01006674 * This version of remove is not scared by a readonly (backup) file.
6675 * This can also remove a symbolic link like Unix.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006676 * Return 0 for success, -1 for failure.
6677 */
6678 int
6679mch_remove(char_u *name)
6680{
6681#ifdef FEAT_MBYTE
6682 WCHAR *wn = NULL;
6683 int n;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02006684#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006685
Bram Moolenaar203258c2016-01-17 22:15:16 +01006686 /*
6687 * On Windows, deleting a directory's symbolic link is done by
6688 * RemoveDirectory(): mch_rmdir. It seems unnatural, but it is fact.
6689 */
6690 if (mch_isdir(name) && mch_is_symbolic_link(name))
6691 return mch_rmdir(name);
6692
Bram Moolenaar12b559e2013-06-12 22:41:37 +02006693 win32_setattrs(name, FILE_ATTRIBUTE_NORMAL);
6694
6695#ifdef FEAT_MBYTE
Bram Moolenaar071d4272004-06-13 20:20:40 +00006696 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
6697 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006698 wn = enc_to_utf16(name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006699 if (wn != NULL)
6700 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006701 n = DeleteFileW(wn) ? 0 : -1;
6702 vim_free(wn);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006703 return n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006704 }
6705 }
6706#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006707 return DeleteFile((LPCSTR)name) ? 0 : -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006708}
6709
6710
6711/*
Bram Moolenaarb9c31e72016-09-29 15:18:57 +02006712 * Check for an "interrupt signal": CTRL-break or CTRL-C.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006713 */
6714 void
Bram Moolenaarb9c31e72016-09-29 15:18:57 +02006715mch_breakcheck(int force)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006716{
6717#ifndef FEAT_GUI_W32 /* never used */
6718 if (g_fCtrlCPressed || g_fCBrkPressed)
6719 {
Bram Moolenaar9698ad72017-08-12 14:52:15 +02006720 ctrl_break_was_pressed = g_fCBrkPressed;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006721 g_fCtrlCPressed = g_fCBrkPressed = FALSE;
6722 got_int = TRUE;
6723 }
6724#endif
6725}
6726
Bram Moolenaaree273972016-01-02 21:11:51 +01006727/* physical RAM to leave for the OS */
6728#define WINNT_RESERVE_BYTES (256*1024*1024)
Bram Moolenaaree273972016-01-02 21:11:51 +01006729
6730/*
6731 * How much main memory in KiB that can be used by VIM.
6732 */
Bram Moolenaaree273972016-01-02 21:11:51 +01006733 long_u
Bram Moolenaar1266d672017-02-01 13:43:36 +01006734mch_total_mem(int special UNUSED)
Bram Moolenaaree273972016-01-02 21:11:51 +01006735{
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006736 MEMORYSTATUSEX ms;
6737
Bram Moolenaaree273972016-01-02 21:11:51 +01006738 PlatformId();
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006739 /* Need to use GlobalMemoryStatusEx() when there is more memory than
6740 * what fits in 32 bits. But it's not always available. */
6741 ms.dwLength = sizeof(MEMORYSTATUSEX);
6742 GlobalMemoryStatusEx(&ms);
6743 if (ms.ullAvailVirtual < ms.ullTotalPhys)
Bram Moolenaaree273972016-01-02 21:11:51 +01006744 {
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006745 /* Process address space fits in physical RAM, use all of it. */
6746 return (long_u)(ms.ullAvailVirtual / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01006747 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006748 if (ms.ullTotalPhys <= WINNT_RESERVE_BYTES)
Bram Moolenaaree273972016-01-02 21:11:51 +01006749 {
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006750 /* Catch old NT box or perverse hardware setup. */
6751 return (long_u)((ms.ullTotalPhys / 2) / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01006752 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006753 /* Use physical RAM less reserve for OS + data. */
6754 return (long_u)((ms.ullTotalPhys - WINNT_RESERVE_BYTES) / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01006755}
Bram Moolenaar071d4272004-06-13 20:20:40 +00006756
Bram Moolenaar071d4272004-06-13 20:20:40 +00006757#ifdef FEAT_MBYTE
6758/*
6759 * Same code as below, but with wide functions and no comments.
6760 * Return 0 for success, non-zero for failure.
6761 */
6762 int
6763mch_wrename(WCHAR *wold, WCHAR *wnew)
6764{
6765 WCHAR *p;
6766 int i;
6767 WCHAR szTempFile[_MAX_PATH + 1];
6768 WCHAR szNewPath[_MAX_PATH + 1];
6769 HANDLE hf;
6770
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006771 p = wold;
6772 for (i = 0; wold[i] != NUL; ++i)
6773 if ((wold[i] == '/' || wold[i] == '\\' || wold[i] == ':')
6774 && wold[i + 1] != 0)
6775 p = wold + i + 1;
6776 if ((int)(wold + i - p) < 8 || p[6] != '~')
6777 return (MoveFileW(wold, wnew) == 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006778
6779 if (GetFullPathNameW(wnew, _MAX_PATH, szNewPath, &p) == 0 || p == NULL)
6780 return -1;
6781 *p = NUL;
6782
6783 if (GetTempFileNameW(szNewPath, L"VIM", 0, szTempFile) == 0)
6784 return -2;
6785
6786 if (!DeleteFileW(szTempFile))
6787 return -3;
6788
6789 if (!MoveFileW(wold, szTempFile))
6790 return -4;
6791
6792 if ((hf = CreateFileW(wold, GENERIC_WRITE, 0, NULL, CREATE_NEW,
6793 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
6794 return -5;
6795 if (!CloseHandle(hf))
6796 return -6;
6797
6798 if (!MoveFileW(szTempFile, wnew))
6799 {
6800 (void)MoveFileW(szTempFile, wold);
6801 return -7;
6802 }
6803
6804 DeleteFileW(szTempFile);
6805
6806 if (!DeleteFileW(wold))
6807 return -8;
6808
6809 return 0;
6810}
6811#endif
6812
6813
6814/*
6815 * mch_rename() works around a bug in rename (aka MoveFile) in
6816 * Windows 95: rename("foo.bar", "foo.bar~") will generate a
6817 * file whose short file name is "FOO.BAR" (its long file name will
6818 * be correct: "foo.bar~"). Because a file can be accessed by
6819 * either its SFN or its LFN, "foo.bar" has effectively been
6820 * renamed to "foo.bar", which is not at all what was wanted. This
6821 * seems to happen only when renaming files with three-character
6822 * extensions by appending a suffix that does not include ".".
6823 * Windows NT gets it right, however, with an SFN of "FOO~1.BAR".
6824 *
6825 * There is another problem, which isn't really a bug but isn't right either:
6826 * When renaming "abcdef~1.txt" to "abcdef~1.txt~", the short name can be
6827 * "abcdef~1.txt" again. This has been reported on Windows NT 4.0 with
6828 * service pack 6. Doesn't seem to happen on Windows 98.
6829 *
6830 * Like rename(), returns 0 upon success, non-zero upon failure.
6831 * Should probably set errno appropriately when errors occur.
6832 */
6833 int
6834mch_rename(
6835 const char *pszOldFile,
6836 const char *pszNewFile)
6837{
6838 char szTempFile[_MAX_PATH+1];
6839 char szNewPath[_MAX_PATH+1];
6840 char *pszFilePart;
6841 HANDLE hf;
6842#ifdef FEAT_MBYTE
6843 WCHAR *wold = NULL;
6844 WCHAR *wnew = NULL;
6845 int retval = -1;
6846
6847 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
6848 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006849 wold = enc_to_utf16((char_u *)pszOldFile, NULL);
6850 wnew = enc_to_utf16((char_u *)pszNewFile, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006851 if (wold != NULL && wnew != NULL)
6852 retval = mch_wrename(wold, wnew);
6853 vim_free(wold);
6854 vim_free(wnew);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006855 return retval;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006856 }
6857#endif
6858
6859 /*
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006860 * No need to play tricks unless the file name contains a "~" as the
6861 * seventh character.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006862 */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006863 pszFilePart = (char *)gettail((char_u *)pszOldFile);
6864 if (STRLEN(pszFilePart) < 8 || pszFilePart[6] != '~')
6865 return rename(pszOldFile, pszNewFile);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006866
6867 /* Get base path of new file name. Undocumented feature: If pszNewFile is
6868 * a directory, no error is returned and pszFilePart will be NULL. */
6869 if (GetFullPathName(pszNewFile, _MAX_PATH, szNewPath, &pszFilePart) == 0
6870 || pszFilePart == NULL)
6871 return -1;
6872 *pszFilePart = NUL;
6873
6874 /* Get (and create) a unique temporary file name in directory of new file */
6875 if (GetTempFileName(szNewPath, "VIM", 0, szTempFile) == 0)
6876 return -2;
6877
6878 /* blow the temp file away */
6879 if (!DeleteFile(szTempFile))
6880 return -3;
6881
6882 /* rename old file to the temp file */
6883 if (!MoveFile(pszOldFile, szTempFile))
6884 return -4;
6885
6886 /* now create an empty file called pszOldFile; this prevents the operating
6887 * system using pszOldFile as an alias (SFN) if we're renaming within the
6888 * same directory. For example, we're editing a file called
6889 * filename.asc.txt by its SFN, filena~1.txt. If we rename filena~1.txt
6890 * to filena~1.txt~ (i.e., we're making a backup while writing it), the
6891 * SFN for filena~1.txt~ will be filena~1.txt, by default, which will
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006892 * cause all sorts of problems later in buf_write(). So, we create an
6893 * empty file called filena~1.txt and the system will have to find some
6894 * other SFN for filena~1.txt~, such as filena~2.txt
Bram Moolenaar071d4272004-06-13 20:20:40 +00006895 */
6896 if ((hf = CreateFile(pszOldFile, GENERIC_WRITE, 0, NULL, CREATE_NEW,
6897 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
6898 return -5;
6899 if (!CloseHandle(hf))
6900 return -6;
6901
6902 /* rename the temp file to the new file */
6903 if (!MoveFile(szTempFile, pszNewFile))
6904 {
6905 /* Renaming failed. Rename the file back to its old name, so that it
6906 * looks like nothing happened. */
6907 (void)MoveFile(szTempFile, pszOldFile);
6908
6909 return -7;
6910 }
6911
6912 /* Seems to be left around on Novell filesystems */
6913 DeleteFile(szTempFile);
6914
6915 /* finally, remove the empty old file */
6916 if (!DeleteFile(pszOldFile))
6917 return -8;
6918
6919 return 0; /* success */
6920}
6921
6922/*
6923 * Get the default shell for the current hardware platform
6924 */
6925 char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006926default_shell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006927{
Bram Moolenaar071d4272004-06-13 20:20:40 +00006928 PlatformId();
6929
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006930 return "cmd.exe";
Bram Moolenaar071d4272004-06-13 20:20:40 +00006931}
6932
6933/*
6934 * mch_access() extends access() to do more detailed check on network drives.
6935 * Returns 0 if file "n" has access rights according to "p", -1 otherwise.
6936 */
6937 int
6938mch_access(char *n, int p)
6939{
6940 HANDLE hFile;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006941 int retval = -1; /* default: fail */
6942#ifdef FEAT_MBYTE
6943 WCHAR *wn = NULL;
6944
6945 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006946 wn = enc_to_utf16((char_u *)n, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006947#endif
6948
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006949 if (mch_isdir((char_u *)n))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006950 {
6951 char TempName[_MAX_PATH + 16] = "";
6952#ifdef FEAT_MBYTE
6953 WCHAR TempNameW[_MAX_PATH + 16] = L"";
6954#endif
6955
6956 if (p & R_OK)
6957 {
6958 /* Read check is performed by seeing if we can do a find file on
6959 * the directory for any file. */
6960#ifdef FEAT_MBYTE
6961 if (wn != NULL)
6962 {
6963 int i;
6964 WIN32_FIND_DATAW d;
6965
6966 for (i = 0; i < _MAX_PATH && wn[i] != 0; ++i)
6967 TempNameW[i] = wn[i];
6968 if (TempNameW[i - 1] != '\\' && TempNameW[i - 1] != '/')
6969 TempNameW[i++] = '\\';
6970 TempNameW[i++] = '*';
6971 TempNameW[i++] = 0;
6972
6973 hFile = FindFirstFileW(TempNameW, &d);
6974 if (hFile == INVALID_HANDLE_VALUE)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006975 goto getout;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006976 else
6977 (void)FindClose(hFile);
6978 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006979 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00006980#endif
6981 {
6982 char *pch;
6983 WIN32_FIND_DATA d;
6984
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006985 vim_strncpy((char_u *)TempName, (char_u *)n, _MAX_PATH);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006986 pch = TempName + STRLEN(TempName) - 1;
6987 if (*pch != '\\' && *pch != '/')
6988 *++pch = '\\';
6989 *++pch = '*';
6990 *++pch = NUL;
6991
6992 hFile = FindFirstFile(TempName, &d);
6993 if (hFile == INVALID_HANDLE_VALUE)
6994 goto getout;
6995 (void)FindClose(hFile);
6996 }
6997 }
6998
6999 if (p & W_OK)
7000 {
7001 /* Trying to create a temporary file in the directory should catch
7002 * directories on read-only network shares. However, in
7003 * directories whose ACL allows writes but denies deletes will end
7004 * up keeping the temporary file :-(. */
7005#ifdef FEAT_MBYTE
7006 if (wn != NULL)
7007 {
7008 if (!GetTempFileNameW(wn, L"VIM", 0, TempNameW))
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007009 goto getout;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007010 else
7011 DeleteFileW(TempNameW);
7012 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007013 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00007014#endif
7015 {
7016 if (!GetTempFileName(n, "VIM", 0, TempName))
7017 goto getout;
7018 mch_remove((char_u *)TempName);
7019 }
7020 }
7021 }
7022 else
7023 {
Bram Moolenaar5aa98962018-05-06 17:09:38 +02007024 // Don't consider a file read-only if another process has opened it.
7025 DWORD share_mode = FILE_SHARE_READ | FILE_SHARE_WRITE;
7026
Bram Moolenaar071d4272004-06-13 20:20:40 +00007027 /* Trying to open the file for the required access does ACL, read-only
7028 * network share, and file attribute checks. */
Bram Moolenaar5aa98962018-05-06 17:09:38 +02007029 DWORD access_mode = ((p & W_OK) ? GENERIC_WRITE : 0)
7030 | ((p & R_OK) ? GENERIC_READ : 0);
7031
Bram Moolenaar071d4272004-06-13 20:20:40 +00007032#ifdef FEAT_MBYTE
7033 if (wn != NULL)
Bram Moolenaar5aa98962018-05-06 17:09:38 +02007034 hFile = CreateFileW(wn, access_mode, share_mode,
7035 NULL, OPEN_EXISTING, 0, NULL);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007036 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00007037#endif
Bram Moolenaar5aa98962018-05-06 17:09:38 +02007038 hFile = CreateFile(n, access_mode, share_mode,
7039 NULL, OPEN_EXISTING, 0, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007040 if (hFile == INVALID_HANDLE_VALUE)
7041 goto getout;
7042 CloseHandle(hFile);
7043 }
7044
7045 retval = 0; /* success */
7046getout:
7047#ifdef FEAT_MBYTE
7048 vim_free(wn);
7049#endif
7050 return retval;
7051}
7052
7053#if defined(FEAT_MBYTE) || defined(PROTO)
7054/*
Bram Moolenaar36f692d2008-11-20 16:10:17 +00007055 * Version of open() that may use UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007056 */
7057 int
Bram Moolenaarb6843a02017-08-02 22:07:12 +02007058mch_open(const char *name, int flags, int mode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007059{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00007060 /* _wopen() does not work with Borland C 5.5: creates a read-only file. */
7061# ifndef __BORLANDC__
Bram Moolenaar071d4272004-06-13 20:20:40 +00007062 WCHAR *wn;
7063 int f;
7064
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00007065 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007066 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01007067 wn = enc_to_utf16((char_u *)name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007068 if (wn != NULL)
7069 {
7070 f = _wopen(wn, flags, mode);
7071 vim_free(wn);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007072 return f;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007073 }
7074 }
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00007075# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007076
Bram Moolenaarf9e6c3b2014-11-05 18:36:03 +01007077 /* open() can open a file which name is longer than _MAX_PATH bytes
7078 * and shorter than _MAX_PATH characters successfully, but sometimes it
7079 * causes unexpected error in another part. We make it an error explicitly
7080 * here. */
7081 if (strlen(name) >= _MAX_PATH)
7082 return -1;
7083
Bram Moolenaar071d4272004-06-13 20:20:40 +00007084 return open(name, flags, mode);
7085}
7086
7087/*
Bram Moolenaar36f692d2008-11-20 16:10:17 +00007088 * Version of fopen() that may use UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007089 */
7090 FILE *
Bram Moolenaarb6843a02017-08-02 22:07:12 +02007091mch_fopen(const char *name, const char *mode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007092{
7093 WCHAR *wn, *wm;
7094 FILE *f = NULL;
7095
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007096 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007097 {
Bram Moolenaare6a91fd2008-07-24 18:51:11 +00007098# if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0fde2902008-03-16 13:54:13 +00007099 /* Work around an annoying assertion in the Microsoft debug CRT
7100 * when mode's text/binary setting doesn't match _get_fmode(). */
7101 char newMode = mode[strlen(mode) - 1];
7102 int oldMode = 0;
7103
7104 _get_fmode(&oldMode);
7105 if (newMode == 't')
7106 _set_fmode(_O_TEXT);
7107 else if (newMode == 'b')
7108 _set_fmode(_O_BINARY);
7109# endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01007110 wn = enc_to_utf16((char_u *)name, NULL);
7111 wm = enc_to_utf16((char_u *)mode, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007112 if (wn != NULL && wm != NULL)
7113 f = _wfopen(wn, wm);
7114 vim_free(wn);
7115 vim_free(wm);
Bram Moolenaar0fde2902008-03-16 13:54:13 +00007116
Bram Moolenaare6a91fd2008-07-24 18:51:11 +00007117# if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0fde2902008-03-16 13:54:13 +00007118 _set_fmode(oldMode);
7119# endif
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007120 return f;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007121 }
7122
Bram Moolenaarf9e6c3b2014-11-05 18:36:03 +01007123 /* fopen() can open a file which name is longer than _MAX_PATH bytes
7124 * and shorter than _MAX_PATH characters successfully, but sometimes it
7125 * causes unexpected error in another part. We make it an error explicitly
7126 * here. */
7127 if (strlen(name) >= _MAX_PATH)
7128 return NULL;
7129
Bram Moolenaar071d4272004-06-13 20:20:40 +00007130 return fopen(name, mode);
7131}
7132#endif
7133
7134#ifdef FEAT_MBYTE
7135/*
7136 * SUB STREAM (aka info stream) handling:
7137 *
7138 * NTFS can have sub streams for each file. Normal contents of file is
7139 * stored in the main stream, and extra contents (author information and
7140 * title and so on) can be stored in sub stream. After Windows 2000, user
7141 * can access and store those informations in sub streams via explorer's
7142 * property menuitem in right click menu. Those informations in sub streams
7143 * were lost when copying only the main stream. So we have to copy sub
7144 * streams.
7145 *
7146 * Incomplete explanation:
7147 * http://msdn.microsoft.com/library/en-us/dnw2k/html/ntfs5.asp
7148 * More useful info and an example:
7149 * http://www.sysinternals.com/ntw2k/source/misc.shtml#streams
7150 */
7151
7152/*
7153 * Copy info stream data "substream". Read from the file with BackupRead(sh)
7154 * and write to stream "substream" of file "to".
7155 * Errors are ignored.
7156 */
7157 static void
7158copy_substream(HANDLE sh, void *context, WCHAR *to, WCHAR *substream, long len)
7159{
7160 HANDLE hTo;
7161 WCHAR *to_name;
7162
7163 to_name = malloc((wcslen(to) + wcslen(substream) + 1) * sizeof(WCHAR));
7164 wcscpy(to_name, to);
7165 wcscat(to_name, substream);
7166
7167 hTo = CreateFileW(to_name, GENERIC_WRITE, 0, NULL, OPEN_ALWAYS,
7168 FILE_ATTRIBUTE_NORMAL, NULL);
7169 if (hTo != INVALID_HANDLE_VALUE)
7170 {
7171 long done;
7172 DWORD todo;
7173 DWORD readcnt, written;
7174 char buf[4096];
7175
7176 /* Copy block of bytes at a time. Abort when something goes wrong. */
7177 for (done = 0; done < len; done += written)
7178 {
7179 /* (size_t) cast for Borland C 5.5 */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007180 todo = (DWORD)((size_t)(len - done) > sizeof(buf) ? sizeof(buf)
7181 : (size_t)(len - done));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007182 if (!BackupRead(sh, (LPBYTE)buf, todo, &readcnt,
7183 FALSE, FALSE, context)
7184 || readcnt != todo
7185 || !WriteFile(hTo, buf, todo, &written, NULL)
7186 || written != todo)
7187 break;
7188 }
7189 CloseHandle(hTo);
7190 }
7191
7192 free(to_name);
7193}
7194
7195/*
7196 * Copy info streams from file "from" to file "to".
7197 */
7198 static void
7199copy_infostreams(char_u *from, char_u *to)
7200{
7201 WCHAR *fromw;
7202 WCHAR *tow;
7203 HANDLE sh;
7204 WIN32_STREAM_ID sid;
7205 int headersize;
7206 WCHAR streamname[_MAX_PATH];
7207 DWORD readcount;
7208 void *context = NULL;
7209 DWORD lo, hi;
7210 int len;
7211
7212 /* Convert the file names to wide characters. */
Bram Moolenaar36f692d2008-11-20 16:10:17 +00007213 fromw = enc_to_utf16(from, NULL);
7214 tow = enc_to_utf16(to, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007215 if (fromw != NULL && tow != NULL)
7216 {
7217 /* Open the file for reading. */
7218 sh = CreateFileW(fromw, GENERIC_READ, FILE_SHARE_READ, NULL,
7219 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
7220 if (sh != INVALID_HANDLE_VALUE)
7221 {
7222 /* Use BackupRead() to find the info streams. Repeat until we
7223 * have done them all.*/
7224 for (;;)
7225 {
7226 /* Get the header to find the length of the stream name. If
7227 * the "readcount" is zero we have done all info streams. */
7228 ZeroMemory(&sid, sizeof(WIN32_STREAM_ID));
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007229 headersize = (int)((char *)&sid.cStreamName - (char *)&sid.dwStreamId);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007230 if (!BackupRead(sh, (LPBYTE)&sid, headersize,
7231 &readcount, FALSE, FALSE, &context)
7232 || readcount == 0)
7233 break;
7234
7235 /* We only deal with streams that have a name. The normal
7236 * file data appears to be without a name, even though docs
7237 * suggest it is called "::$DATA". */
7238 if (sid.dwStreamNameSize > 0)
7239 {
7240 /* Read the stream name. */
7241 if (!BackupRead(sh, (LPBYTE)streamname,
7242 sid.dwStreamNameSize,
7243 &readcount, FALSE, FALSE, &context))
7244 break;
7245
7246 /* Copy an info stream with a name ":anything:$DATA".
7247 * Skip "::$DATA", it has no stream name (examples suggest
7248 * it might be used for the normal file contents).
7249 * Note that BackupRead() counts bytes, but the name is in
7250 * wide characters. */
7251 len = readcount / sizeof(WCHAR);
7252 streamname[len] = 0;
7253 if (len > 7 && wcsicmp(streamname + len - 6,
7254 L":$DATA") == 0)
7255 {
7256 streamname[len - 6] = 0;
7257 copy_substream(sh, &context, tow, streamname,
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00007258 (long)sid.Size.u.LowPart);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007259 }
7260 }
7261
7262 /* Advance to the next stream. We might try seeking too far,
7263 * but BackupSeek() doesn't skip over stream borders, thus
7264 * that's OK. */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00007265 (void)BackupSeek(sh, sid.Size.u.LowPart, sid.Size.u.HighPart,
Bram Moolenaar071d4272004-06-13 20:20:40 +00007266 &lo, &hi, &context);
7267 }
7268
7269 /* Clear the context. */
7270 (void)BackupRead(sh, NULL, 0, &readcount, TRUE, FALSE, &context);
7271
7272 CloseHandle(sh);
7273 }
7274 }
7275 vim_free(fromw);
7276 vim_free(tow);
7277}
7278#endif
7279
7280/*
7281 * Copy file attributes from file "from" to file "to".
7282 * For Windows NT and later we copy info streams.
7283 * Always returns zero, errors are ignored.
7284 */
7285 int
7286mch_copy_file_attribute(char_u *from, char_u *to)
7287{
7288#ifdef FEAT_MBYTE
7289 /* File streams only work on Windows NT and later. */
7290 PlatformId();
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007291 copy_infostreams(from, to);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007292#endif
7293 return 0;
7294}
7295
7296#if defined(MYRESETSTKOFLW) || defined(PROTO)
7297/*
7298 * Recreate a destroyed stack guard page in win32.
7299 * Written by Benjamin Peterson.
7300 */
7301
7302/* These magic numbers are from the MS header files */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007303#define MIN_STACK_WINNT 2
7304
7305/*
7306 * This function does the same thing as _resetstkoflw(), which is only
7307 * available in DevStudio .net and later.
7308 * Returns 0 for failure, 1 for success.
7309 */
7310 int
7311myresetstkoflw(void)
7312{
7313 BYTE *pStackPtr;
7314 BYTE *pGuardPage;
7315 BYTE *pStackBase;
7316 BYTE *pLowestPossiblePage;
7317 MEMORY_BASIC_INFORMATION mbi;
7318 SYSTEM_INFO si;
7319 DWORD nPageSize;
7320 DWORD dummy;
7321
Bram Moolenaar071d4272004-06-13 20:20:40 +00007322 PlatformId();
Bram Moolenaar071d4272004-06-13 20:20:40 +00007323
7324 /* We need to know the system page size. */
7325 GetSystemInfo(&si);
7326 nPageSize = si.dwPageSize;
7327
7328 /* ...and the current stack pointer */
7329 pStackPtr = (BYTE*)_alloca(1);
7330
7331 /* ...and the base of the stack. */
7332 if (VirtualQuery(pStackPtr, &mbi, sizeof mbi) == 0)
7333 return 0;
7334 pStackBase = (BYTE*)mbi.AllocationBase;
7335
7336 /* ...and the page thats min_stack_req pages away from stack base; this is
7337 * the lowest page we could use. */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007338 pLowestPossiblePage = pStackBase + MIN_STACK_WINNT * nPageSize;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007339
Bram Moolenaar071d4272004-06-13 20:20:40 +00007340 {
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007341 /* We want the first committed page in the stack Start at the stack
7342 * base and move forward through memory until we find a committed block.
7343 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007344 BYTE *pBlock = pStackBase;
7345
Bram Moolenaara466c992005-07-09 21:03:22 +00007346 for (;;)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007347 {
7348 if (VirtualQuery(pBlock, &mbi, sizeof mbi) == 0)
7349 return 0;
7350
7351 pBlock += mbi.RegionSize;
7352
7353 if (mbi.State & MEM_COMMIT)
7354 break;
7355 }
7356
7357 /* mbi now describes the first committed block in the stack. */
7358 if (mbi.Protect & PAGE_GUARD)
7359 return 1;
7360
7361 /* decide where the guard page should start */
7362 if ((long_u)(mbi.BaseAddress) < (long_u)pLowestPossiblePage)
7363 pGuardPage = pLowestPossiblePage;
7364 else
7365 pGuardPage = (BYTE*)mbi.BaseAddress;
7366
7367 /* allocate the guard page */
7368 if (!VirtualAlloc(pGuardPage, nPageSize, MEM_COMMIT, PAGE_READWRITE))
7369 return 0;
7370
7371 /* apply the guard attribute to the page */
7372 if (!VirtualProtect(pGuardPage, nPageSize, PAGE_READWRITE | PAGE_GUARD,
7373 &dummy))
7374 return 0;
7375 }
7376
7377 return 1;
7378}
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007379#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007380
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007381
7382#if defined(FEAT_MBYTE) || defined(PROTO)
7383/*
7384 * The command line arguments in UCS2
7385 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00007386static int nArgsW = 0;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007387static LPWSTR *ArglistW = NULL;
7388static int global_argc = 0;
7389static char **global_argv;
7390
7391static int used_file_argc = 0; /* last argument in global_argv[] used
7392 for the argument list. */
7393static int *used_file_indexes = NULL; /* indexes in global_argv[] for
7394 command line arguments added to
7395 the argument list */
7396static int used_file_count = 0; /* nr of entries in used_file_indexes */
7397static int used_file_literal = FALSE; /* take file names literally */
7398static int used_file_full_path = FALSE; /* file name was full path */
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007399static int used_file_diff_mode = FALSE; /* file name was with diff mode */
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007400static int used_alist_count = 0;
7401
7402
7403/*
7404 * Get the command line arguments. Unicode version.
7405 * Returns argc. Zero when something fails.
7406 */
7407 int
7408get_cmd_argsW(char ***argvp)
7409{
7410 char **argv = NULL;
7411 int argc = 0;
7412 int i;
7413
Bram Moolenaar14993322014-09-09 12:25:33 +02007414 free_cmd_argsW();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007415 ArglistW = CommandLineToArgvW(GetCommandLineW(), &nArgsW);
7416 if (ArglistW != NULL)
7417 {
7418 argv = malloc((nArgsW + 1) * sizeof(char *));
7419 if (argv != NULL)
7420 {
7421 argc = nArgsW;
7422 argv[argc] = NULL;
7423 for (i = 0; i < argc; ++i)
7424 {
7425 int len;
7426
7427 /* Convert each Unicode argument to the current codepage. */
7428 WideCharToMultiByte_alloc(GetACP(), 0,
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007429 ArglistW[i], (int)wcslen(ArglistW[i]) + 1,
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007430 (LPSTR *)&argv[i], &len, 0, 0);
7431 if (argv[i] == NULL)
7432 {
7433 /* Out of memory, clear everything. */
7434 while (i > 0)
7435 free(argv[--i]);
7436 free(argv);
Bram Moolenaar73c61632013-12-07 14:48:10 +01007437 argv = NULL;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007438 argc = 0;
7439 }
7440 }
7441 }
7442 }
7443
7444 global_argc = argc;
7445 global_argv = argv;
7446 if (argc > 0)
Bram Moolenaar14993322014-09-09 12:25:33 +02007447 {
7448 if (used_file_indexes != NULL)
7449 free(used_file_indexes);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007450 used_file_indexes = malloc(argc * sizeof(int));
Bram Moolenaar14993322014-09-09 12:25:33 +02007451 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007452
7453 if (argvp != NULL)
7454 *argvp = argv;
7455 return argc;
7456}
7457
7458 void
7459free_cmd_argsW(void)
7460{
7461 if (ArglistW != NULL)
7462 {
7463 GlobalFree(ArglistW);
7464 ArglistW = NULL;
7465 }
7466}
7467
7468/*
7469 * Remember "name" is an argument that was added to the argument list.
7470 * This avoids that we have to re-parse the argument list when fix_arg_enc()
7471 * is called.
7472 */
7473 void
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007474used_file_arg(char *name, int literal, int full_path, int diff_mode)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007475{
7476 int i;
7477
7478 if (used_file_indexes == NULL)
7479 return;
7480 for (i = used_file_argc + 1; i < global_argc; ++i)
7481 if (STRCMP(global_argv[i], name) == 0)
7482 {
7483 used_file_argc = i;
7484 used_file_indexes[used_file_count++] = i;
7485 break;
7486 }
7487 used_file_literal = literal;
7488 used_file_full_path = full_path;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007489 used_file_diff_mode = diff_mode;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007490}
7491
7492/*
7493 * Remember the length of the argument list as it was. If it changes then we
7494 * leave it alone when 'encoding' is set.
7495 */
7496 void
7497set_alist_count(void)
7498{
7499 used_alist_count = GARGCOUNT;
7500}
7501
7502/*
7503 * Fix the encoding of the command line arguments. Invoked when 'encoding'
7504 * has been changed while starting up. Use the UCS-2 command line arguments
7505 * and convert them to 'encoding'.
7506 */
7507 void
7508fix_arg_enc(void)
7509{
7510 int i;
7511 int idx;
7512 char_u *str;
Bram Moolenaar86b68352004-12-27 21:59:20 +00007513 int *fnum_list;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007514
7515 /* Safety checks:
7516 * - if argument count differs between the wide and non-wide argument
7517 * list, something must be wrong.
7518 * - the file name arguments must have been located.
7519 * - the length of the argument list wasn't changed by the user.
7520 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00007521 if (global_argc != nArgsW
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007522 || ArglistW == NULL
7523 || used_file_indexes == NULL
7524 || used_file_count == 0
7525 || used_alist_count != GARGCOUNT)
7526 return;
7527
Bram Moolenaar86b68352004-12-27 21:59:20 +00007528 /* Remember the buffer numbers for the arguments. */
7529 fnum_list = (int *)alloc((int)sizeof(int) * GARGCOUNT);
7530 if (fnum_list == NULL)
7531 return; /* out of memory */
7532 for (i = 0; i < GARGCOUNT; ++i)
7533 fnum_list[i] = GARGLIST[i].ae_fnum;
7534
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007535 /* Clear the argument list. Make room for the new arguments. */
7536 alist_clear(&global_alist);
7537 if (ga_grow(&global_alist.al_ga, used_file_count) == FAIL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00007538 return; /* out of memory */
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007539
7540 for (i = 0; i < used_file_count; ++i)
7541 {
7542 idx = used_file_indexes[i];
Bram Moolenaar36f692d2008-11-20 16:10:17 +00007543 str = utf16_to_enc(ArglistW[idx], NULL);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007544 if (str != NULL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00007545 {
Bram Moolenaar39d21e32017-08-05 23:09:31 +02007546 int literal = used_file_literal;
7547
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007548#ifdef FEAT_DIFF
7549 /* When using diff mode may need to concatenate file name to
7550 * directory name. Just like it's done in main(). */
7551 if (used_file_diff_mode && mch_isdir(str) && GARGCOUNT > 0
7552 && !mch_isdir(alist_name(&GARGLIST[0])))
7553 {
7554 char_u *r;
7555
7556 r = concat_fnames(str, gettail(alist_name(&GARGLIST[0])), TRUE);
7557 if (r != NULL)
7558 {
7559 vim_free(str);
7560 str = r;
7561 }
7562 }
7563#endif
Bram Moolenaar86b68352004-12-27 21:59:20 +00007564 /* Re-use the old buffer by renaming it. When not using literal
7565 * names it's done by alist_expand() below. */
7566 if (used_file_literal)
7567 buf_set_name(fnum_list[i], str);
7568
Bram Moolenaar39d21e32017-08-05 23:09:31 +02007569 /* Check backtick literal. backtick literal is already expanded in
7570 * main.c, so this part add str as literal. */
7571 if (literal == FALSE)
7572 {
Bram Moolenaar116a0f82017-08-07 21:17:57 +02007573 size_t len = STRLEN(str);
7574
Bram Moolenaar39d21e32017-08-05 23:09:31 +02007575 if (len > 2 && *str == '`' && *(str + len - 1) == '`')
7576 literal = TRUE;
7577 }
7578 alist_add(&global_alist, str, literal ? 2 : 0);
Bram Moolenaar86b68352004-12-27 21:59:20 +00007579 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007580 }
7581
7582 if (!used_file_literal)
7583 {
7584 /* Now expand wildcards in the arguments. */
7585 /* Temporarily add '(' and ')' to 'isfname'. These are valid
7586 * filename characters but are excluded from 'isfname' to make
Bram Moolenaar20586cb2018-03-08 22:03:14 +01007587 * "gf" work on a file name in parenthesis (e.g.: see vim.h).
7588 * Also, unset wildignore to not be influenced by this option.
7589 * The arguments specified in command-line should be kept even if
7590 * encoding options were changed. */
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007591 do_cmdline_cmd((char_u *)":let SaVe_ISF = &isf|set isf+=(,)");
Bram Moolenaar20586cb2018-03-08 22:03:14 +01007592 do_cmdline_cmd((char_u *)":let SaVe_WIG = &wig|set wig=");
Bram Moolenaar86b68352004-12-27 21:59:20 +00007593 alist_expand(fnum_list, used_alist_count);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007594 do_cmdline_cmd((char_u *)":let &isf = SaVe_ISF|unlet SaVe_ISF");
Bram Moolenaar20586cb2018-03-08 22:03:14 +01007595 do_cmdline_cmd((char_u *)":let &wig = SaVe_WIG|unlet SaVe_WIG");
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007596 }
7597
7598 /* If wildcard expansion failed, we are editing the first file of the
7599 * arglist and there is no file name: Edit the first argument now. */
7600 if (curwin->w_arg_idx == 0 && curbuf->b_fname == NULL)
7601 {
7602 do_cmdline_cmd((char_u *)":rewind");
7603 if (GARGCOUNT == 1 && used_file_full_path)
Bram Moolenaarb7407d32018-02-03 17:36:27 +01007604 (void)vim_chdirfile(alist_name(&GARGLIST[0]), "drop");
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007605 }
Bram Moolenaar86b68352004-12-27 21:59:20 +00007606
7607 set_alist_count();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007608}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007609#endif
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007610
7611 int
7612mch_setenv(char *var, char *value, int x)
7613{
7614 char_u *envbuf;
7615
7616 envbuf = alloc((unsigned)(STRLEN(var) + STRLEN(value) + 2));
7617 if (envbuf == NULL)
7618 return -1;
7619
7620 sprintf((char *)envbuf, "%s=%s", var, value);
7621
7622#ifdef FEAT_MBYTE
7623 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
7624 {
7625 WCHAR *p = enc_to_utf16(envbuf, NULL);
7626
7627 vim_free(envbuf);
7628 if (p == NULL)
7629 return -1;
7630 _wputenv(p);
7631# ifdef libintl_wputenv
7632 libintl_wputenv(p);
7633# endif
7634 /* Unlike Un*x systems, we can free the string for _wputenv(). */
7635 vim_free(p);
7636 }
7637 else
7638#endif
7639 {
7640 _putenv((char *)envbuf);
7641# ifdef libintl_putenv
7642 libintl_putenv((char *)envbuf);
7643# endif
7644 /* Unlike Un*x systems, we can free the string for _putenv(). */
7645 vim_free(envbuf);
7646 }
7647
7648 return 0;
7649}
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007650
7651#ifndef FEAT_GUI_W32
7652
7653/*
7654 * Support for 256 colors and 24-bit colors was added in Windows 10
7655 * version 1703 (Creators update).
7656 */
7657# define VTP_FIRST_SUPPORT_BUILD MAKE_VER(10, 0, 15063)
7658
7659 static void
7660vtp_init(void)
7661{
7662 DWORD ver, mode;
7663 HMODULE hKerneldll;
7664 DYN_CONSOLE_SCREEN_BUFFER_INFOEX csbi;
7665
7666 ver = get_build_number();
7667 vtp_working = (ver >= VTP_FIRST_SUPPORT_BUILD) ? 1 : 0;
7668 GetConsoleMode(g_hConOut, &mode);
7669 mode |= (ENABLE_PROCESSED_OUTPUT | ENABLE_VIRTUAL_TERMINAL_PROCESSING);
7670 if (SetConsoleMode(g_hConOut, mode) == 0)
7671 vtp_working = 0;
7672
7673 /* Use functions supported from Vista */
7674 hKerneldll = GetModuleHandle("kernel32.dll");
7675 if (hKerneldll != NULL)
7676 {
7677 pGetConsoleScreenBufferInfoEx =
7678 (PfnGetConsoleScreenBufferInfoEx)GetProcAddress(
7679 hKerneldll, "GetConsoleScreenBufferInfoEx");
7680 pSetConsoleScreenBufferInfoEx =
7681 (PfnSetConsoleScreenBufferInfoEx)GetProcAddress(
7682 hKerneldll, "SetConsoleScreenBufferInfoEx");
7683 if (pGetConsoleScreenBufferInfoEx != NULL
7684 && pSetConsoleScreenBufferInfoEx != NULL)
7685 has_csbiex = TRUE;
7686 }
7687
7688 csbi.cbSize = sizeof(csbi);
7689 if (has_csbiex)
7690 pGetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
7691 save_console_bg_rgb = (guicolor_T)csbi.ColorTable[0];
7692 save_console_fg_rgb = (guicolor_T)csbi.ColorTable[7];
7693
7694 set_console_color_rgb();
7695}
7696
7697 static void
7698vtp_exit(void)
7699{
7700 reset_console_color_rgb();
7701}
7702
7703 static int
7704vtp_printf(
7705 char *format,
7706 ...)
7707{
7708 char_u buf[100];
7709 va_list list;
7710 DWORD result;
7711
7712 va_start(list, format);
7713 vim_vsnprintf((char *)buf, 100, (char *)format, list);
7714 va_end(list);
7715 WriteConsoleA(g_hConOut, buf, (DWORD)STRLEN(buf), &result, NULL);
7716 return (int)result;
7717}
7718
7719 static void
7720vtp_sgr_bulk(
7721 int arg)
7722{
7723 int args[1];
7724
7725 args[0] = arg;
7726 vtp_sgr_bulks(1, args);
7727}
7728
7729 static void
7730vtp_sgr_bulks(
7731 int argc,
7732 int *args
7733)
7734{
7735 /* 2('\033[') + 4('255.') * 16 + NUL */
7736 char_u buf[2 + (4 * 16) + 1];
7737 char_u *p;
7738 int i;
7739
7740 p = buf;
7741 *p++ = '\033';
7742 *p++ = '[';
7743
7744 for (i = 0; i < argc; ++i)
7745 {
7746 p += vim_snprintf((char *)p, 4, "%d", args[i] & 0xff);
7747 *p++ = ';';
7748 }
7749 p--;
7750 *p++ = 'm';
7751 *p = NUL;
7752 vtp_printf((char *)buf);
7753}
7754
Bram Moolenaar8a938af2018-05-01 17:30:41 +02007755# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007756 static int
7757ctermtoxterm(
7758 int cterm)
7759{
Bram Moolenaar9894e392018-05-05 14:29:06 +02007760 char_u r, g, b, idx;
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007761
7762 cterm_color2rgb(cterm, &r, &g, &b, &idx);
7763 return (((int)r << 16) | ((int)g << 8) | (int)b);
7764}
Bram Moolenaar8a938af2018-05-01 17:30:41 +02007765# endif
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007766
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007767 static void
7768set_console_color_rgb(void)
7769{
7770# ifdef FEAT_TERMGUICOLORS
7771 DYN_CONSOLE_SCREEN_BUFFER_INFOEX csbi;
7772 int id;
7773 guicolor_T fg = INVALCOLOR;
7774 guicolor_T bg = INVALCOLOR;
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007775 int ctermfg;
7776 int ctermbg;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007777
7778 if (!USE_VTP)
7779 return;
7780
7781 id = syn_name2id((char_u *)"Normal");
7782 if (id > 0)
7783 syn_id2colors(id, &fg, &bg);
7784 if (fg == INVALCOLOR)
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007785 {
7786 ctermfg = -1;
7787 if (id > 0)
7788 syn_id2cterm_bg(id, &ctermfg, &ctermbg);
7789 fg = ctermfg != -1 ? ctermtoxterm(ctermfg) : 0xc0c0c0; /* white */
7790 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007791 if (bg == INVALCOLOR)
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007792 {
7793 ctermbg = -1;
7794 if (id > 0)
7795 syn_id2cterm_bg(id, &ctermfg, &ctermbg);
7796 bg = ctermbg != -1 ? ctermtoxterm(ctermbg) : 0x000000; /* black */
7797 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007798 fg = (GetRValue(fg) << 16) | (GetGValue(fg) << 8) | GetBValue(fg);
7799 bg = (GetRValue(bg) << 16) | (GetGValue(bg) << 8) | GetBValue(bg);
7800
7801 csbi.cbSize = sizeof(csbi);
7802 if (has_csbiex)
7803 pGetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
7804
7805 csbi.cbSize = sizeof(csbi);
7806 csbi.srWindow.Right += 1;
7807 csbi.srWindow.Bottom += 1;
7808 csbi.ColorTable[0] = (COLORREF)bg;
7809 csbi.ColorTable[7] = (COLORREF)fg;
7810 if (has_csbiex)
7811 pSetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
7812# endif
7813}
7814
7815 static void
7816reset_console_color_rgb(void)
7817{
7818# ifdef FEAT_TERMGUICOLORS
7819 DYN_CONSOLE_SCREEN_BUFFER_INFOEX csbi;
7820
7821 csbi.cbSize = sizeof(csbi);
7822 if (has_csbiex)
7823 pGetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
7824
7825 csbi.cbSize = sizeof(csbi);
7826 csbi.srWindow.Right += 1;
7827 csbi.srWindow.Bottom += 1;
7828 csbi.ColorTable[0] = (COLORREF)save_console_bg_rgb;
7829 csbi.ColorTable[7] = (COLORREF)save_console_fg_rgb;
7830 if (has_csbiex)
7831 pSetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
7832# endif
7833}
7834
7835 void
7836control_console_color_rgb(void)
7837{
7838 if (USE_VTP)
7839 set_console_color_rgb();
7840 else
7841 reset_console_color_rgb();
7842}
7843
7844 int
7845has_vtp_working(void)
7846{
7847 return vtp_working;
7848}
7849
7850 int
7851use_vtp(void)
7852{
7853 return USE_VTP;
7854}
7855
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007856 int
7857is_term_win32(void)
7858{
7859 return T_NAME != NULL && STRCMP(T_NAME, "win32") == 0;
7860}
7861
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007862#endif