blob: 3bfeee66ec8ba6323dd2c246a407b63aa0fe9abd [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
Bram Moolenaar4f974752019-02-17 17:44:42 +010013 * the console version only, so there is a lot of "#ifndef FEAT_GUI_MSWIN".
Bram Moolenaar071d4272004-06-13 20:20:40 +000014 *
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
Bram Moolenaar0f873732019-12-05 20:28:46 +010033// cproto fails on missing include files
Bram Moolenaar82881492012-11-20 16:53:39 +010034#ifndef PROTO
35# include <process.h>
Bram Moolenaare7bebc42021-02-01 20:50:37 +010036# include <winternl.h>
Bram Moolenaar82881492012-11-20 16:53:39 +010037#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +000038
39#undef chdir
40#ifdef __GNUC__
41# ifndef __MINGW32__
42# include <dirent.h>
43# endif
44#else
45# include <direct.h>
46#endif
47
Bram Moolenaar82881492012-11-20 16:53:39 +010048#ifndef PROTO
Bram Moolenaar4f974752019-02-17 17:44:42 +010049# if defined(FEAT_TITLE) && !defined(FEAT_GUI_MSWIN)
Bram Moolenaar82881492012-11-20 16:53:39 +010050# include <shellapi.h>
51# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +000052#endif
53
Bram Moolenaarfb630902016-10-29 14:55:00 +020054#ifdef FEAT_JOB_CHANNEL
55# include <tlhelp32.h>
56#endif
57
Bram Moolenaar071d4272004-06-13 20:20:40 +000058#ifdef __MINGW32__
59# ifndef FROM_LEFT_1ST_BUTTON_PRESSED
60# define FROM_LEFT_1ST_BUTTON_PRESSED 0x0001
61# endif
62# ifndef RIGHTMOST_BUTTON_PRESSED
63# define RIGHTMOST_BUTTON_PRESSED 0x0002
64# endif
65# ifndef FROM_LEFT_2ND_BUTTON_PRESSED
66# define FROM_LEFT_2ND_BUTTON_PRESSED 0x0004
67# endif
68# ifndef FROM_LEFT_3RD_BUTTON_PRESSED
69# define FROM_LEFT_3RD_BUTTON_PRESSED 0x0008
70# endif
71# ifndef FROM_LEFT_4TH_BUTTON_PRESSED
72# define FROM_LEFT_4TH_BUTTON_PRESSED 0x0010
73# endif
74
75/*
76 * EventFlags
77 */
78# ifndef MOUSE_MOVED
79# define MOUSE_MOVED 0x0001
80# endif
81# ifndef DOUBLE_CLICK
82# define DOUBLE_CLICK 0x0002
83# endif
84#endif
85
Bram Moolenaar0f873732019-12-05 20:28:46 +010086// Record all output and all keyboard & mouse input
87// #define MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +000088
89#ifdef MCH_WRITE_DUMP
90FILE* fdDump = NULL;
91#endif
92
93/*
94 * When generating prototypes for Win32 on Unix, these lines make the syntax
95 * errors disappear. They do not need to be correct.
96 */
97#ifdef PROTO
Bram Moolenaar912bc4a2019-12-01 18:58:11 +010098# define WINAPI
Bram Moolenaar071d4272004-06-13 20:20:40 +000099typedef char * LPCSTR;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000100typedef char * LPWSTR;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000101typedef int ACCESS_MASK;
102typedef int BOOL;
103typedef int COLORREF;
104typedef int CONSOLE_CURSOR_INFO;
105typedef int COORD;
106typedef int DWORD;
107typedef int HANDLE;
Bram Moolenaaref269542016-01-19 13:22:12 +0100108typedef int LPHANDLE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000109typedef int HDC;
110typedef int HFONT;
111typedef int HICON;
112typedef int HINSTANCE;
113typedef int HWND;
114typedef int INPUT_RECORD;
Bram Moolenaare0ab9792017-08-02 23:18:25 +0200115typedef int INT;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000116typedef int KEY_EVENT_RECORD;
117typedef int LOGFONT;
118typedef int LPBOOL;
119typedef int LPCTSTR;
120typedef int LPDWORD;
121typedef int LPSTR;
122typedef int LPTSTR;
123typedef int LPVOID;
124typedef int MOUSE_EVENT_RECORD;
125typedef int PACL;
126typedef int PDWORD;
127typedef int PHANDLE;
128typedef int PRINTDLG;
129typedef int PSECURITY_DESCRIPTOR;
130typedef int PSID;
131typedef int SECURITY_INFORMATION;
132typedef int SHORT;
133typedef int SMALL_RECT;
134typedef int TEXTMETRIC;
135typedef int TOKEN_INFORMATION_CLASS;
136typedef int TRUSTEE;
137typedef int WORD;
138typedef int WCHAR;
139typedef void VOID;
Bram Moolenaar82881492012-11-20 16:53:39 +0100140typedef int BY_HANDLE_FILE_INFORMATION;
Bram Moolenaar32ac8cd2013-07-03 18:49:17 +0200141typedef int SE_OBJECT_TYPE;
142typedef int PSNSECINFO;
143typedef int PSNSECINFOW;
Bram Moolenaarb8e0bdb2014-11-12 16:10:48 +0100144typedef int STARTUPINFO;
145typedef int PROCESS_INFORMATION;
Bram Moolenaard90b6c02016-08-28 18:10:45 +0200146typedef int LPSECURITY_ATTRIBUTES;
Bram Moolenaar0f873732019-12-05 20:28:46 +0100147# define __stdcall // empty
Bram Moolenaar071d4272004-06-13 20:20:40 +0000148#endif
149
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200150#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar0f873732019-12-05 20:28:46 +0100151// Win32 Console handles for input and output
Bram Moolenaar071d4272004-06-13 20:20:40 +0000152static HANDLE g_hConIn = INVALID_HANDLE_VALUE;
153static HANDLE g_hConOut = INVALID_HANDLE_VALUE;
154
Bram Moolenaar0f873732019-12-05 20:28:46 +0100155// Win32 Screen buffer,coordinate,console I/O information
Bram Moolenaar071d4272004-06-13 20:20:40 +0000156static SMALL_RECT g_srScrollRegion;
Bram Moolenaar0f873732019-12-05 20:28:46 +0100157static COORD g_coord; // 0-based, but external coords are 1-based
Bram Moolenaar071d4272004-06-13 20:20:40 +0000158
Bram Moolenaar0f873732019-12-05 20:28:46 +0100159// The attribute of the screen when the editor was started
160static WORD g_attrDefault = 7; // lightgray text on black background
Bram Moolenaar071d4272004-06-13 20:20:40 +0000161static WORD g_attrCurrent;
162
Bram Moolenaar0f873732019-12-05 20:28:46 +0100163static int g_fCBrkPressed = FALSE; // set by ctrl-break interrupt
164static int g_fCtrlCPressed = FALSE; // set when ctrl-C or ctrl-break detected
165static int g_fForceExit = FALSE; // set when forcefully exiting
Bram Moolenaar071d4272004-06-13 20:20:40 +0000166
Bram Moolenaar071d4272004-06-13 20:20:40 +0000167static void scroll(unsigned cLines);
168static void set_scroll_region(unsigned left, unsigned top,
169 unsigned right, unsigned bottom);
Bram Moolenaar6982f422019-02-16 16:48:01 +0100170static void set_scroll_region_tb(unsigned top, unsigned bottom);
171static void set_scroll_region_lr(unsigned left, unsigned right);
172static void insert_lines(unsigned cLines);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000173static void delete_lines(unsigned cLines);
174static void gotoxy(unsigned x, unsigned y);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000175static void standout(void);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000176static int s_cursor_visible = TRUE;
177static int did_create_conin = FALSE;
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200178#endif
179#ifdef FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +0000180static int s_dont_use_vimrun = TRUE;
181static int need_vimrun_warning = FALSE;
182static char *vimrun_path = "vimrun ";
183#endif
184
Bram Moolenaar12b559e2013-06-12 22:41:37 +0200185static int win32_getattrs(char_u *name);
186static int win32_setattrs(char_u *name, int attrs);
187static int win32_set_archive(char_u *name);
188
Bram Moolenaard9ef1b82019-02-13 19:23:10 +0100189static int conpty_working = 0;
Bram Moolenaar57da6982019-09-13 22:30:11 +0200190static int conpty_type = 0;
Bram Moolenaard9ef1b82019-02-13 19:23:10 +0100191static int conpty_stable = 0;
Bram Moolenaar7ed8f592020-04-28 20:44:42 +0200192static int conpty_fix_type = 0;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100193static void vtp_flag_init();
194
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200195#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar6902c0e2019-02-16 14:07:37 +0100196static int vtp_working = 0;
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100197static void vtp_init();
198static void vtp_exit();
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100199static void vtp_sgr_bulk(int arg);
200static void vtp_sgr_bulks(int argc, int *argv);
201
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200202static int wt_working = 0;
203static void wt_init();
204
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100205static guicolor_T save_console_bg_rgb;
206static guicolor_T save_console_fg_rgb;
Bram Moolenaardf543822020-01-30 11:53:59 +0100207static guicolor_T store_console_bg_rgb;
208static guicolor_T store_console_fg_rgb;
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100209
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +0200210static int g_color_index_bg = 0;
211static int g_color_index_fg = 7;
212
213# ifdef FEAT_TERMGUICOLORS
214static int default_console_color_bg = 0x000000; // black
215static int default_console_color_fg = 0xc0c0c0; // white
216# endif
217
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100218# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarc5cd8852018-05-01 15:47:38 +0200219# define USE_VTP (vtp_working && is_term_win32() && (p_tgc || (!p_tgc && t_colors >= 256)))
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200220# define USE_WT (wt_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100221# else
222# define USE_VTP 0
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200223# define USE_WT 0
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100224# endif
225
226static void set_console_color_rgb(void);
227static void reset_console_color_rgb(void);
Bram Moolenaardf543822020-01-30 11:53:59 +0100228static void restore_console_color_rgb(void);
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100229#endif
230
Bram Moolenaar0f873732019-12-05 20:28:46 +0100231// This flag is newly created from Windows 10
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100232#ifndef ENABLE_VIRTUAL_TERMINAL_PROCESSING
233# define ENABLE_VIRTUAL_TERMINAL_PROCESSING 0x0004
234#endif
235
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200236#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar0f873732019-12-05 20:28:46 +0100237static int suppress_winsize = 1; // don't fiddle with console
Bram Moolenaar071d4272004-06-13 20:20:40 +0000238#endif
239
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200240static char_u *exe_path = NULL;
241
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100242static BOOL win8_or_later = FALSE;
243
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200244# if defined(__GNUC__) && !defined(__MINGW32__) && !defined(__CYGWIN__)
245# define UChar UnicodeChar
246# else
247# define UChar uChar.UnicodeChar
248# endif
249
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200250#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar0f873732019-12-05 20:28:46 +0100251// Dynamic loading for portability
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100252typedef struct _DYN_CONSOLE_SCREEN_BUFFER_INFOEX
253{
254 ULONG cbSize;
255 COORD dwSize;
256 COORD dwCursorPosition;
257 WORD wAttributes;
258 SMALL_RECT srWindow;
259 COORD dwMaximumWindowSize;
260 WORD wPopupAttributes;
261 BOOL bFullscreenSupported;
262 COLORREF ColorTable[16];
263} DYN_CONSOLE_SCREEN_BUFFER_INFOEX, *PDYN_CONSOLE_SCREEN_BUFFER_INFOEX;
264typedef BOOL (WINAPI *PfnGetConsoleScreenBufferInfoEx)(HANDLE, PDYN_CONSOLE_SCREEN_BUFFER_INFOEX);
265static PfnGetConsoleScreenBufferInfoEx pGetConsoleScreenBufferInfoEx;
266typedef BOOL (WINAPI *PfnSetConsoleScreenBufferInfoEx)(HANDLE, PDYN_CONSOLE_SCREEN_BUFFER_INFOEX);
267static PfnSetConsoleScreenBufferInfoEx pSetConsoleScreenBufferInfoEx;
268static BOOL has_csbiex = FALSE;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100269#endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100270
271/*
272 * Get version number including build number
273 */
274typedef BOOL (WINAPI *PfnRtlGetVersion)(LPOSVERSIONINFOW);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100275#define MAKE_VER(major, minor, build) \
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100276 (((major) << 24) | ((minor) << 16) | (build))
277
278 static DWORD
279get_build_number(void)
280{
281 OSVERSIONINFOW osver = {sizeof(OSVERSIONINFOW)};
282 HMODULE hNtdll;
283 PfnRtlGetVersion pRtlGetVersion;
284 DWORD ver = MAKE_VER(0, 0, 0);
285
286 hNtdll = GetModuleHandle("ntdll.dll");
287 if (hNtdll != NULL)
288 {
289 pRtlGetVersion =
290 (PfnRtlGetVersion)GetProcAddress(hNtdll, "RtlGetVersion");
291 pRtlGetVersion(&osver);
292 ver = MAKE_VER(min(osver.dwMajorVersion, 255),
293 min(osver.dwMinorVersion, 255),
294 min(osver.dwBuildNumber, 32767));
295 }
296 return ver;
297}
298
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200299#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200300 static BOOL
301is_ambiwidth_event(
302 INPUT_RECORD *ir)
303{
304 return ir->EventType == KEY_EVENT
305 && ir->Event.KeyEvent.bKeyDown
306 && ir->Event.KeyEvent.wRepeatCount == 1
307 && ir->Event.KeyEvent.wVirtualKeyCode == 0x12
308 && ir->Event.KeyEvent.wVirtualScanCode == 0x38
309 && ir->Event.KeyEvent.UChar == 0
310 && ir->Event.KeyEvent.dwControlKeyState == 2;
311}
312
313 static void
314make_ambiwidth_event(
315 INPUT_RECORD *down,
316 INPUT_RECORD *up)
317{
318 down->Event.KeyEvent.wVirtualKeyCode = 0;
319 down->Event.KeyEvent.wVirtualScanCode = 0;
320 down->Event.KeyEvent.UChar = up->Event.KeyEvent.UChar;
321 down->Event.KeyEvent.dwControlKeyState = 0;
322}
323
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100324/*
325 * Version of ReadConsoleInput() that works with IME.
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100326 * Works around problems on Windows 8.
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100327 */
328 static BOOL
329read_console_input(
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100330 HANDLE hInput,
331 INPUT_RECORD *lpBuffer,
332 DWORD nLength,
333 LPDWORD lpEvents)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100334{
335 enum
336 {
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100337 IRSIZE = 10
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100338 };
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100339 static INPUT_RECORD s_irCache[IRSIZE];
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100340 static DWORD s_dwIndex = 0;
341 static DWORD s_dwMax = 0;
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100342 DWORD dwEvents;
Bram Moolenaardd415a62014-02-05 14:02:27 +0100343 int head;
344 int tail;
345 int i;
Bram Moolenaarbc970da2020-04-26 19:00:07 +0200346 static INPUT_RECORD s_irPseudo;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100347
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200348 if (nLength == -2)
349 return (s_dwMax > 0) ? TRUE : FALSE;
350
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100351 if (!win8_or_later)
352 {
353 if (nLength == -1)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200354 return PeekConsoleInputW(hInput, lpBuffer, 1, lpEvents);
355 return ReadConsoleInputW(hInput, lpBuffer, 1, &dwEvents);
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100356 }
357
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100358 if (s_dwMax == 0)
359 {
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200360 if (!USE_WT && nLength == -1)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200361 return PeekConsoleInputW(hInput, lpBuffer, 1, lpEvents);
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200362 GetNumberOfConsoleInputEvents(hInput, &dwEvents);
363 if (dwEvents == 0 && nLength == -1)
364 return PeekConsoleInputW(hInput, lpBuffer, 1, lpEvents);
365 ReadConsoleInputW(hInput, s_irCache, IRSIZE, &dwEvents);
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100366 s_dwIndex = 0;
367 s_dwMax = dwEvents;
368 if (dwEvents == 0)
369 {
370 *lpEvents = 0;
371 return TRUE;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100372 }
Bram Moolenaardd415a62014-02-05 14:02:27 +0100373
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200374 for (i = s_dwIndex; i < (int)s_dwMax - 1; ++i)
375 if (is_ambiwidth_event(&s_irCache[i]))
376 make_ambiwidth_event(&s_irCache[i], &s_irCache[i + 1]);
377
Bram Moolenaardd415a62014-02-05 14:02:27 +0100378 if (s_dwMax > 1)
379 {
380 head = 0;
381 tail = s_dwMax - 1;
382 while (head != tail)
383 {
384 if (s_irCache[head].EventType == WINDOW_BUFFER_SIZE_EVENT
385 && s_irCache[head + 1].EventType
386 == WINDOW_BUFFER_SIZE_EVENT)
387 {
Bram Moolenaar0f873732019-12-05 20:28:46 +0100388 // Remove duplicate event to avoid flicker.
Bram Moolenaardd415a62014-02-05 14:02:27 +0100389 for (i = head; i < tail; ++i)
390 s_irCache[i] = s_irCache[i + 1];
391 --tail;
392 continue;
393 }
394 head++;
395 }
396 s_dwMax = tail + 1;
397 }
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100398 }
Bram Moolenaardd415a62014-02-05 14:02:27 +0100399
Bram Moolenaarbc970da2020-04-26 19:00:07 +0200400 if (s_irCache[s_dwIndex].EventType == KEY_EVENT)
401 {
402 if (s_irCache[s_dwIndex].Event.KeyEvent.wRepeatCount > 1)
403 {
404 s_irPseudo = s_irCache[s_dwIndex];
405 s_irPseudo.Event.KeyEvent.wRepeatCount = 1;
406 s_irCache[s_dwIndex].Event.KeyEvent.wRepeatCount--;
407 *lpBuffer = s_irPseudo;
408 *lpEvents = 1;
409 return TRUE;
410 }
411 }
412
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100413 *lpBuffer = s_irCache[s_dwIndex];
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200414 if (!(nLength == -1 || nLength == -2) && ++s_dwIndex >= s_dwMax)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100415 s_dwMax = 0;
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100416 *lpEvents = 1;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100417 return TRUE;
418}
419
420/*
421 * Version of PeekConsoleInput() that works with IME.
422 */
423 static BOOL
424peek_console_input(
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100425 HANDLE hInput,
426 INPUT_RECORD *lpBuffer,
Bram Moolenaarbd67aac2019-09-21 23:09:04 +0200427 DWORD nLength UNUSED,
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100428 LPDWORD lpEvents)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100429{
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100430 return read_console_input(hInput, lpBuffer, -1, lpEvents);
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100431}
432
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100433# ifdef FEAT_CLIENTSERVER
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200434 static DWORD
435msg_wait_for_multiple_objects(
436 DWORD nCount,
437 LPHANDLE pHandles,
438 BOOL fWaitAll,
439 DWORD dwMilliseconds,
440 DWORD dwWakeMask)
441{
442 if (read_console_input(NULL, NULL, -2, NULL))
443 return WAIT_OBJECT_0;
444 return MsgWaitForMultipleObjects(nCount, pHandles, fWaitAll,
445 dwMilliseconds, dwWakeMask);
446}
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100447# endif
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200448
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100449# ifndef FEAT_CLIENTSERVER
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200450 static DWORD
451wait_for_single_object(
452 HANDLE hHandle,
453 DWORD dwMilliseconds)
454{
455 if (read_console_input(NULL, NULL, -2, NULL))
456 return WAIT_OBJECT_0;
457 return WaitForSingleObject(hHandle, dwMilliseconds);
458}
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100459# endif
460#endif
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200461
Bram Moolenaar071d4272004-06-13 20:20:40 +0000462 static void
463get_exe_name(void)
464{
Bram Moolenaar0f873732019-12-05 20:28:46 +0100465 // Maximum length of $PATH is more than MAXPATHL. 8191 is often mentioned
466 // as the maximum length that works (plus a NUL byte).
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100467#define MAX_ENV_PATH_LEN 8192
468 char temp[MAX_ENV_PATH_LEN];
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200469 char_u *p;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000470
471 if (exe_name == NULL)
472 {
Bram Moolenaar0f873732019-12-05 20:28:46 +0100473 // store the name of the executable, may be used for $VIM
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100474 GetModuleFileName(NULL, temp, MAX_ENV_PATH_LEN - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000475 if (*temp != NUL)
476 exe_name = FullName_save((char_u *)temp, FALSE);
477 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000478
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200479 if (exe_path == NULL && exe_name != NULL)
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000480 {
Bram Moolenaar71ccd032020-06-12 22:59:11 +0200481 exe_path = vim_strnsave(exe_name, gettail_sep(exe_name) - exe_name);
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200482 if (exe_path != NULL)
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000483 {
Bram Moolenaar0f873732019-12-05 20:28:46 +0100484 // Append our starting directory to $PATH, so that when doing
485 // "!xxd" it's found in our starting directory. Needed because
486 // SearchPath() also looks there.
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200487 p = mch_getenv("PATH");
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100488 if (p == NULL
489 || STRLEN(p) + STRLEN(exe_path) + 2 < MAX_ENV_PATH_LEN)
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200490 {
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100491 if (p == NULL || *p == NUL)
492 temp[0] = NUL;
493 else
494 {
495 STRCPY(temp, p);
496 STRCAT(temp, ";");
497 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200498 STRCAT(temp, exe_path);
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +0100499 vim_setenv((char_u *)"PATH", (char_u *)temp);
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200500 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000501 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000502 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000503}
504
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200505/*
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100506 * Unescape characters in "p" that appear in "escaped".
507 */
508 static void
509unescape_shellxquote(char_u *p, char_u *escaped)
510{
Bram Moolenaar4336cdf2012-02-29 13:58:47 +0100511 int l = (int)STRLEN(p);
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100512 int n;
513
514 while (*p != NUL)
515 {
516 if (*p == '^' && vim_strchr(escaped, p[1]) != NULL)
517 mch_memmove(p, p + 1, l--);
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100518 n = (*mb_ptr2len)(p);
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100519 p += n;
520 l -= n;
521 }
522}
523
524/*
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200525 * Load library "name".
526 */
527 HINSTANCE
528vimLoadLib(char *name)
529{
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200530 HINSTANCE dll = NULL;
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200531
Bram Moolenaar3d0e7a92021-05-01 17:46:03 +0200532 // No need to load any library when registering OLE.
533 if (found_register_arg)
534 return dll;
535
Bram Moolenaar0f873732019-12-05 20:28:46 +0100536 // NOTE: Do not use mch_dirname() and mch_chdir() here, they may call
537 // vimLoadLib() recursively, which causes a stack overflow.
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200538 if (exe_path == NULL)
539 get_exe_name();
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200540 if (exe_path != NULL)
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200541 {
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200542 WCHAR old_dirw[MAXPATHL];
543
544 if (GetCurrentDirectoryW(MAXPATHL, old_dirw) != 0)
545 {
Bram Moolenaar0f873732019-12-05 20:28:46 +0100546 // Change directory to where the executable is, both to make
547 // sure we find a .dll there and to avoid looking for a .dll
548 // in the current directory.
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +0100549 SetCurrentDirectory((LPCSTR)exe_path);
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200550 dll = LoadLibrary(name);
551 SetCurrentDirectoryW(old_dirw);
552 return dll;
553 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200554 }
555 return dll;
556}
557
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200558#if defined(VIMDLL) || defined(PROTO)
559/*
560 * Check if the current executable file is for the GUI subsystem.
561 */
562 int
563mch_is_gui_executable(void)
564{
565 PBYTE pImage = (PBYTE)GetModuleHandle(NULL);
566 PIMAGE_DOS_HEADER pDOS = (PIMAGE_DOS_HEADER)pImage;
567 PIMAGE_NT_HEADERS pPE;
568
569 if (pDOS->e_magic != IMAGE_DOS_SIGNATURE)
570 return FALSE;
571 pPE = (PIMAGE_NT_HEADERS)(pImage + pDOS->e_lfanew);
572 if (pPE->Signature != IMAGE_NT_SIGNATURE)
573 return FALSE;
574 if (pPE->OptionalHeader.Subsystem == IMAGE_SUBSYSTEM_WINDOWS_GUI)
575 return TRUE;
576 return FALSE;
577}
578#endif
579
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100580#if defined(DYNAMIC_ICONV) || defined(DYNAMIC_GETTEXT) || defined(PROTO)
581/*
582 * Get related information about 'funcname' which is imported by 'hInst'.
583 * If 'info' is 0, return the function address.
584 * If 'info' is 1, return the module name which the function is imported from.
585 */
586 static void *
587get_imported_func_info(HINSTANCE hInst, const char *funcname, int info)
588{
589 PBYTE pImage = (PBYTE)hInst;
590 PIMAGE_DOS_HEADER pDOS = (PIMAGE_DOS_HEADER)hInst;
591 PIMAGE_NT_HEADERS pPE;
592 PIMAGE_IMPORT_DESCRIPTOR pImpDesc;
Bram Moolenaar0f873732019-12-05 20:28:46 +0100593 PIMAGE_THUNK_DATA pIAT; // Import Address Table
594 PIMAGE_THUNK_DATA pINT; // Import Name Table
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100595 PIMAGE_IMPORT_BY_NAME pImpName;
596
597 if (pDOS->e_magic != IMAGE_DOS_SIGNATURE)
598 return NULL;
599 pPE = (PIMAGE_NT_HEADERS)(pImage + pDOS->e_lfanew);
600 if (pPE->Signature != IMAGE_NT_SIGNATURE)
601 return NULL;
602 pImpDesc = (PIMAGE_IMPORT_DESCRIPTOR)(pImage
603 + pPE->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT]
604 .VirtualAddress);
605 for (; pImpDesc->FirstThunk; ++pImpDesc)
606 {
607 if (!pImpDesc->OriginalFirstThunk)
608 continue;
609 pIAT = (PIMAGE_THUNK_DATA)(pImage + pImpDesc->FirstThunk);
610 pINT = (PIMAGE_THUNK_DATA)(pImage + pImpDesc->OriginalFirstThunk);
611 for (; pIAT->u1.Function; ++pIAT, ++pINT)
612 {
613 if (IMAGE_SNAP_BY_ORDINAL(pINT->u1.Ordinal))
614 continue;
615 pImpName = (PIMAGE_IMPORT_BY_NAME)(pImage
616 + (UINT_PTR)(pINT->u1.AddressOfData));
617 if (strcmp((char *)pImpName->Name, funcname) == 0)
618 {
619 switch (info)
620 {
621 case 0:
622 return (void *)pIAT->u1.Function;
623 case 1:
624 return (void *)(pImage + pImpDesc->Name);
625 default:
626 return NULL;
627 }
628 }
629 }
630 }
631 return NULL;
632}
633
634/*
635 * Get the module handle which 'funcname' in 'hInst' is imported from.
636 */
637 HINSTANCE
638find_imported_module_by_funcname(HINSTANCE hInst, const char *funcname)
639{
640 char *modulename;
641
642 modulename = (char *)get_imported_func_info(hInst, funcname, 1);
643 if (modulename != NULL)
644 return GetModuleHandleA(modulename);
645 return NULL;
646}
647
648/*
649 * Get the address of 'funcname' which is imported by 'hInst' DLL.
650 */
651 void *
652get_dll_import_func(HINSTANCE hInst, const char *funcname)
653{
654 return get_imported_func_info(hInst, funcname, 0);
655}
656#endif
657
Bram Moolenaar071d4272004-06-13 20:20:40 +0000658#if defined(DYNAMIC_GETTEXT) || defined(PROTO)
659# ifndef GETTEXT_DLL
660# define GETTEXT_DLL "libintl.dll"
Bram Moolenaar7554c542018-10-06 15:03:15 +0200661# define GETTEXT_DLL_ALT1 "libintl-8.dll"
662# define GETTEXT_DLL_ALT2 "intl.dll"
Bram Moolenaar071d4272004-06-13 20:20:40 +0000663# endif
Bram Moolenaar0f873732019-12-05 20:28:46 +0100664// Dummy functions
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000665static char *null_libintl_gettext(const char *);
Bram Moolenaaree695f72016-08-03 22:08:45 +0200666static char *null_libintl_ngettext(const char *, const char *, unsigned long n);
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000667static char *null_libintl_textdomain(const char *);
668static char *null_libintl_bindtextdomain(const char *, const char *);
669static char *null_libintl_bind_textdomain_codeset(const char *, const char *);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100670static int null_libintl_wputenv(const wchar_t *);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000671
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200672static HINSTANCE hLibintlDLL = NULL;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000673char *(*dyn_libintl_gettext)(const char *) = null_libintl_gettext;
Bram Moolenaaree695f72016-08-03 22:08:45 +0200674char *(*dyn_libintl_ngettext)(const char *, const char *, unsigned long n)
675 = null_libintl_ngettext;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000676char *(*dyn_libintl_textdomain)(const char *) = null_libintl_textdomain;
677char *(*dyn_libintl_bindtextdomain)(const char *, const char *)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000678 = null_libintl_bindtextdomain;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000679char *(*dyn_libintl_bind_textdomain_codeset)(const char *, const char *)
680 = null_libintl_bind_textdomain_codeset;
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100681int (*dyn_libintl_wputenv)(const wchar_t *) = null_libintl_wputenv;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000682
683 int
Bram Moolenaar05540972016-01-30 20:31:25 +0100684dyn_libintl_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000685{
686 int i;
687 static struct
688 {
689 char *name;
690 FARPROC *ptr;
691 } libintl_entry[] =
692 {
693 {"gettext", (FARPROC*)&dyn_libintl_gettext},
Bram Moolenaaree695f72016-08-03 22:08:45 +0200694 {"ngettext", (FARPROC*)&dyn_libintl_ngettext},
Bram Moolenaar071d4272004-06-13 20:20:40 +0000695 {"textdomain", (FARPROC*)&dyn_libintl_textdomain},
696 {"bindtextdomain", (FARPROC*)&dyn_libintl_bindtextdomain},
697 {NULL, NULL}
698 };
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100699 HINSTANCE hmsvcrt;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000700
Bram Moolenaar7554c542018-10-06 15:03:15 +0200701 // No need to initialize twice.
702 if (hLibintlDLL != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000703 return 1;
Bram Moolenaar7554c542018-10-06 15:03:15 +0200704 // Load gettext library (libintl.dll and other names).
Bram Moolenaar923e43b2016-01-28 15:07:38 +0100705 hLibintlDLL = vimLoadLib(GETTEXT_DLL);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100706# ifdef GETTEXT_DLL_ALT1
Bram Moolenaar286eacd2016-01-16 18:05:50 +0100707 if (!hLibintlDLL)
Bram Moolenaar7554c542018-10-06 15:03:15 +0200708 hLibintlDLL = vimLoadLib(GETTEXT_DLL_ALT1);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100709# endif
710# ifdef GETTEXT_DLL_ALT2
Bram Moolenaar7554c542018-10-06 15:03:15 +0200711 if (!hLibintlDLL)
712 hLibintlDLL = vimLoadLib(GETTEXT_DLL_ALT2);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100713# endif
Bram Moolenaar938ee832016-01-24 15:36:03 +0100714 if (!hLibintlDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000715 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200716 if (p_verbose > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000717 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200718 verbose_enter();
Bram Moolenaarf9e3e092019-01-13 23:38:42 +0100719 semsg(_(e_loadlib), GETTEXT_DLL);
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200720 verbose_leave();
Bram Moolenaar071d4272004-06-13 20:20:40 +0000721 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200722 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000723 }
724 for (i = 0; libintl_entry[i].name != NULL
725 && libintl_entry[i].ptr != NULL; ++i)
726 {
727 if ((*libintl_entry[i].ptr = (FARPROC)GetProcAddress(hLibintlDLL,
728 libintl_entry[i].name)) == NULL)
729 {
730 dyn_libintl_end();
731 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +0000732 {
733 verbose_enter();
Bram Moolenaarf9e3e092019-01-13 23:38:42 +0100734 semsg(_(e_loadfunc), libintl_entry[i].name);
Bram Moolenaara04f10b2005-05-31 22:09:46 +0000735 verbose_leave();
736 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000737 return 0;
738 }
739 }
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000740
Bram Moolenaar0f873732019-12-05 20:28:46 +0100741 // The bind_textdomain_codeset() function is optional.
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000742 dyn_libintl_bind_textdomain_codeset = (void *)GetProcAddress(hLibintlDLL,
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000743 "bind_textdomain_codeset");
744 if (dyn_libintl_bind_textdomain_codeset == NULL)
745 dyn_libintl_bind_textdomain_codeset =
746 null_libintl_bind_textdomain_codeset;
747
Bram Moolenaar0f873732019-12-05 20:28:46 +0100748 // _wputenv() function for the libintl.dll is optional.
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100749 hmsvcrt = find_imported_module_by_funcname(hLibintlDLL, "getenv");
750 if (hmsvcrt != NULL)
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100751 dyn_libintl_wputenv = (void *)GetProcAddress(hmsvcrt, "_wputenv");
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100752 if (dyn_libintl_wputenv == NULL || dyn_libintl_wputenv == _wputenv)
753 dyn_libintl_wputenv = null_libintl_wputenv;
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100754
Bram Moolenaar071d4272004-06-13 20:20:40 +0000755 return 1;
756}
757
758 void
Bram Moolenaar05540972016-01-30 20:31:25 +0100759dyn_libintl_end(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000760{
761 if (hLibintlDLL)
762 FreeLibrary(hLibintlDLL);
763 hLibintlDLL = NULL;
764 dyn_libintl_gettext = null_libintl_gettext;
Bram Moolenaaree695f72016-08-03 22:08:45 +0200765 dyn_libintl_ngettext = null_libintl_ngettext;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000766 dyn_libintl_textdomain = null_libintl_textdomain;
767 dyn_libintl_bindtextdomain = null_libintl_bindtextdomain;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000768 dyn_libintl_bind_textdomain_codeset = null_libintl_bind_textdomain_codeset;
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100769 dyn_libintl_wputenv = null_libintl_wputenv;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000770}
771
772 static char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000773null_libintl_gettext(const char *msgid)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000774{
775 return (char*)msgid;
776}
777
778 static char *
Bram Moolenaaree695f72016-08-03 22:08:45 +0200779null_libintl_ngettext(
780 const char *msgid,
781 const char *msgid_plural,
782 unsigned long n)
783{
Bram Moolenaarc90f2ae2016-08-04 22:00:15 +0200784 return (char *)(n == 1 ? msgid : msgid_plural);
Bram Moolenaaree695f72016-08-03 22:08:45 +0200785}
786
Bram Moolenaaree695f72016-08-03 22:08:45 +0200787 static char *
Bram Moolenaar1266d672017-02-01 13:43:36 +0100788null_libintl_bindtextdomain(
789 const char *domainname UNUSED,
790 const char *dirname UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000791{
792 return NULL;
793}
794
795 static char *
Bram Moolenaar1266d672017-02-01 13:43:36 +0100796null_libintl_bind_textdomain_codeset(
797 const char *domainname UNUSED,
798 const char *codeset UNUSED)
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000799{
800 return NULL;
801}
802
803 static char *
Bram Moolenaar1266d672017-02-01 13:43:36 +0100804null_libintl_textdomain(const char *domainname UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000805{
806 return NULL;
807}
808
Bram Moolenaare0ab9792017-08-02 23:18:25 +0200809 static int
Bram Moolenaar1266d672017-02-01 13:43:36 +0100810null_libintl_wputenv(const wchar_t *envstring UNUSED)
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100811{
812 return 0;
813}
814
Bram Moolenaar0f873732019-12-05 20:28:46 +0100815#endif // DYNAMIC_GETTEXT
Bram Moolenaar071d4272004-06-13 20:20:40 +0000816
Bram Moolenaar0f873732019-12-05 20:28:46 +0100817// This symbol is not defined in older versions of the SDK or Visual C++
Bram Moolenaar071d4272004-06-13 20:20:40 +0000818
819#ifndef VER_PLATFORM_WIN32_WINDOWS
820# define VER_PLATFORM_WIN32_WINDOWS 1
821#endif
822
Bram Moolenaar071d4272004-06-13 20:20:40 +0000823#ifdef HAVE_ACL
Bram Moolenaar82881492012-11-20 16:53:39 +0100824# ifndef PROTO
825# include <aclapi.h>
826# endif
Bram Moolenaar27515922013-06-29 15:36:26 +0200827# ifndef PROTECTED_DACL_SECURITY_INFORMATION
828# define PROTECTED_DACL_SECURITY_INFORMATION 0x80000000L
829# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000830#endif
831
Bram Moolenaar27515922013-06-29 15:36:26 +0200832#ifdef HAVE_ACL
833/*
834 * Enables or disables the specified privilege.
835 */
836 static BOOL
837win32_enable_privilege(LPTSTR lpszPrivilege, BOOL bEnable)
838{
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100839 BOOL bResult;
840 LUID luid;
841 HANDLE hToken;
842 TOKEN_PRIVILEGES tokenPrivileges;
Bram Moolenaar27515922013-06-29 15:36:26 +0200843
844 if (!OpenProcessToken(GetCurrentProcess(),
845 TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
846 return FALSE;
847
848 if (!LookupPrivilegeValue(NULL, lpszPrivilege, &luid))
849 {
850 CloseHandle(hToken);
851 return FALSE;
852 }
853
Bram Moolenaar45500912014-07-09 20:51:07 +0200854 tokenPrivileges.PrivilegeCount = 1;
Bram Moolenaar27515922013-06-29 15:36:26 +0200855 tokenPrivileges.Privileges[0].Luid = luid;
856 tokenPrivileges.Privileges[0].Attributes = bEnable ?
857 SE_PRIVILEGE_ENABLED : 0;
858
859 bResult = AdjustTokenPrivileges(hToken, FALSE, &tokenPrivileges,
860 sizeof(TOKEN_PRIVILEGES), NULL, NULL);
861
862 CloseHandle(hToken);
863
864 return bResult && GetLastError() == ERROR_SUCCESS;
865}
866#endif
867
Bram Moolenaar29d2f452020-12-04 19:42:52 +0100868#ifdef _MSC_VER
869// Suppress the deprecation warning for using GetVersionEx().
870// It is needed for implementing "windowsversion()".
871# pragma warning(push)
872# pragma warning(disable: 4996)
873#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000874/*
Bram Moolenaar1e1d2e82020-05-18 20:17:02 +0200875 * Set "win8_or_later" and fill in "windowsVersion" if possible.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000876 */
877 void
878PlatformId(void)
879{
880 static int done = FALSE;
881
882 if (!done)
883 {
884 OSVERSIONINFO ovi;
885
886 ovi.dwOSVersionInfoSize = sizeof(ovi);
887 GetVersionEx(&ovi);
888
Bram Moolenaar1e1d2e82020-05-18 20:17:02 +0200889#ifdef FEAT_EVAL
Bram Moolenaar0c1e3742019-12-27 13:49:24 +0100890 vim_snprintf(windowsVersion, sizeof(windowsVersion), "%d.%d",
891 (int)ovi.dwMajorVersion, (int)ovi.dwMinorVersion);
Bram Moolenaar1e1d2e82020-05-18 20:17:02 +0200892#endif
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100893 if ((ovi.dwMajorVersion == 6 && ovi.dwMinorVersion >= 2)
894 || ovi.dwMajorVersion > 6)
895 win8_or_later = TRUE;
896
Bram Moolenaar071d4272004-06-13 20:20:40 +0000897#ifdef HAVE_ACL
Bram Moolenaar0f873732019-12-05 20:28:46 +0100898 // Enable privilege for getting or setting SACLs.
Bram Moolenaarcea912a2016-10-12 14:20:24 +0200899 win32_enable_privilege(SE_SECURITY_NAME, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000900#endif
901 done = TRUE;
902 }
903}
Bram Moolenaar29d2f452020-12-04 19:42:52 +0100904#ifdef _MSC_VER
905# pragma warning(pop)
906#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000907
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200908#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000909
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100910# define SHIFT (SHIFT_PRESSED)
911# define CTRL (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED)
912# define ALT (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED)
913# define ALT_GR (RIGHT_ALT_PRESSED | LEFT_CTRL_PRESSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000914
915
Bram Moolenaar0f873732019-12-05 20:28:46 +0100916// When uChar.AsciiChar is 0, then we need to look at wVirtualKeyCode.
917// We map function keys to their ANSI terminal equivalents, as produced
918// by ANSI.SYS, for compatibility with the MS-DOS version of Vim. Any
919// ANSI key with a value >= '\300' is nonstandard, but provided anyway
920// so that the user can have access to all SHIFT-, CTRL-, and ALT-
921// combinations of function/arrow/etc keys.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000922
Bram Moolenaard6f676d2005-06-01 21:51:55 +0000923static const struct
Bram Moolenaar071d4272004-06-13 20:20:40 +0000924{
925 WORD wVirtKey;
926 BOOL fAnsiKey;
927 int chAlone;
928 int chShift;
929 int chCtrl;
930 int chAlt;
931} VirtKeyMap[] =
932{
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200933// Key ANSI alone shift ctrl alt
Bram Moolenaar071d4272004-06-13 20:20:40 +0000934 { VK_ESCAPE,FALSE, ESC, ESC, ESC, ESC, },
935
936 { VK_F1, TRUE, ';', 'T', '^', 'h', },
937 { VK_F2, TRUE, '<', 'U', '_', 'i', },
938 { VK_F3, TRUE, '=', 'V', '`', 'j', },
939 { VK_F4, TRUE, '>', 'W', 'a', 'k', },
940 { VK_F5, TRUE, '?', 'X', 'b', 'l', },
941 { VK_F6, TRUE, '@', 'Y', 'c', 'm', },
942 { VK_F7, TRUE, 'A', 'Z', 'd', 'n', },
943 { VK_F8, TRUE, 'B', '[', 'e', 'o', },
944 { VK_F9, TRUE, 'C', '\\', 'f', 'p', },
945 { VK_F10, TRUE, 'D', ']', 'g', 'q', },
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200946 { VK_F11, TRUE, '\205', '\207', '\211', '\213', },
947 { VK_F12, TRUE, '\206', '\210', '\212', '\214', },
Bram Moolenaar071d4272004-06-13 20:20:40 +0000948
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200949 { VK_HOME, TRUE, 'G', '\302', 'w', '\303', },
950 { VK_UP, TRUE, 'H', '\304', '\305', '\306', },
951 { VK_PRIOR, TRUE, 'I', '\307', '\204', '\310', }, // PgUp
952 { VK_LEFT, TRUE, 'K', '\311', 's', '\312', },
953 { VK_RIGHT, TRUE, 'M', '\313', 't', '\314', },
954 { VK_END, TRUE, 'O', '\315', 'u', '\316', },
955 { VK_DOWN, TRUE, 'P', '\317', '\320', '\321', },
956 { VK_NEXT, TRUE, 'Q', '\322', 'v', '\323', }, // PgDn
957 { VK_INSERT,TRUE, 'R', '\324', '\325', '\326', },
958 { VK_DELETE,TRUE, 'S', '\327', '\330', '\331', },
Bram Moolenaarb70a47b2019-03-30 22:11:21 +0100959 { VK_BACK, TRUE, 'x', 'y', 'z', '{', }, // Backspace
Bram Moolenaar071d4272004-06-13 20:20:40 +0000960
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200961 { VK_SNAPSHOT,TRUE, 0, 0, 0, 'r', }, // PrtScrn
Bram Moolenaar071d4272004-06-13 20:20:40 +0000962
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100963# if 0
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200964 // Most people don't have F13-F20, but what the hell...
965 { VK_F13, TRUE, '\332', '\333', '\334', '\335', },
966 { VK_F14, TRUE, '\336', '\337', '\340', '\341', },
967 { VK_F15, TRUE, '\342', '\343', '\344', '\345', },
968 { VK_F16, TRUE, '\346', '\347', '\350', '\351', },
969 { VK_F17, TRUE, '\352', '\353', '\354', '\355', },
970 { VK_F18, TRUE, '\356', '\357', '\360', '\361', },
971 { VK_F19, TRUE, '\362', '\363', '\364', '\365', },
972 { VK_F20, TRUE, '\366', '\367', '\370', '\371', },
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100973# endif
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200974 { VK_ADD, TRUE, 'N', 'N', 'N', 'N', }, // keyp '+'
975 { VK_SUBTRACT, TRUE,'J', 'J', 'J', 'J', }, // keyp '-'
976 // { VK_DIVIDE, TRUE,'N', 'N', 'N', 'N', }, // keyp '/'
977 { VK_MULTIPLY, TRUE,'7', '7', '7', '7', }, // keyp '*'
Bram Moolenaar071d4272004-06-13 20:20:40 +0000978
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200979 { VK_NUMPAD0,TRUE, '\332', '\333', '\334', '\335', },
980 { VK_NUMPAD1,TRUE, '\336', '\337', '\340', '\341', },
981 { VK_NUMPAD2,TRUE, '\342', '\343', '\344', '\345', },
982 { VK_NUMPAD3,TRUE, '\346', '\347', '\350', '\351', },
983 { VK_NUMPAD4,TRUE, '\352', '\353', '\354', '\355', },
984 { VK_NUMPAD5,TRUE, '\356', '\357', '\360', '\361', },
985 { VK_NUMPAD6,TRUE, '\362', '\363', '\364', '\365', },
986 { VK_NUMPAD7,TRUE, '\366', '\367', '\370', '\371', },
987 { VK_NUMPAD8,TRUE, '\372', '\373', '\374', '\375', },
988 // Sorry, out of number space! <negri>
Bram Moolenaarb70a47b2019-03-30 22:11:21 +0100989 { VK_NUMPAD9,TRUE, '\376', '\377', '|', '}', },
Bram Moolenaar071d4272004-06-13 20:20:40 +0000990};
991
992
Bram Moolenaar0f873732019-12-05 20:28:46 +0100993/*
994 * The return code indicates key code size.
995 */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000996 static int
Bram Moolenaar071d4272004-06-13 20:20:40 +0000997win32_kbd_patch_key(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000998 KEY_EVENT_RECORD *pker)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000999{
1000 UINT uMods = pker->dwControlKeyState;
1001 static int s_iIsDead = 0;
1002 static WORD awAnsiCode[2];
1003 static BYTE abKeystate[256];
1004
1005
1006 if (s_iIsDead == 2)
1007 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001008 pker->UChar = (WCHAR) awAnsiCode[1];
Bram Moolenaar071d4272004-06-13 20:20:40 +00001009 s_iIsDead = 0;
1010 return 1;
1011 }
1012
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001013 if (pker->UChar != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001014 return 1;
1015
Bram Moolenaara80faa82020-04-12 19:37:17 +02001016 CLEAR_FIELD(abKeystate);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001017
Bram Moolenaar0f873732019-12-05 20:28:46 +01001018 // Clear any pending dead keys
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001019 ToUnicode(VK_SPACE, MapVirtualKey(VK_SPACE, 0), abKeystate, awAnsiCode, 2, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001020
1021 if (uMods & SHIFT_PRESSED)
1022 abKeystate[VK_SHIFT] = 0x80;
1023 if (uMods & CAPSLOCK_ON)
1024 abKeystate[VK_CAPITAL] = 1;
1025
1026 if ((uMods & ALT_GR) == ALT_GR)
1027 {
1028 abKeystate[VK_CONTROL] = abKeystate[VK_LCONTROL] =
1029 abKeystate[VK_MENU] = abKeystate[VK_RMENU] = 0x80;
1030 }
1031
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001032 s_iIsDead = ToUnicode(pker->wVirtualKeyCode, pker->wVirtualScanCode,
1033 abKeystate, awAnsiCode, 2, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001034
1035 if (s_iIsDead > 0)
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001036 pker->UChar = (WCHAR) awAnsiCode[0];
Bram Moolenaar071d4272004-06-13 20:20:40 +00001037
1038 return s_iIsDead;
1039}
1040
Bram Moolenaar071d4272004-06-13 20:20:40 +00001041static BOOL g_fJustGotFocus = FALSE;
1042
1043/*
1044 * Decode a KEY_EVENT into one or two keystrokes
1045 */
1046 static BOOL
1047decode_key_event(
1048 KEY_EVENT_RECORD *pker,
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001049 WCHAR *pch,
1050 WCHAR *pch2,
Bram Moolenaar071d4272004-06-13 20:20:40 +00001051 int *pmodifiers,
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02001052 BOOL fDoPost UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001053{
1054 int i;
1055 const int nModifs = pker->dwControlKeyState & (SHIFT | ALT | CTRL);
1056
1057 *pch = *pch2 = NUL;
1058 g_fJustGotFocus = FALSE;
1059
Bram Moolenaar0f873732019-12-05 20:28:46 +01001060 // ignore key up events
Bram Moolenaar071d4272004-06-13 20:20:40 +00001061 if (!pker->bKeyDown)
1062 return FALSE;
1063
Bram Moolenaar0f873732019-12-05 20:28:46 +01001064 // ignore some keystrokes
Bram Moolenaar071d4272004-06-13 20:20:40 +00001065 switch (pker->wVirtualKeyCode)
1066 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001067 // modifiers
Bram Moolenaar071d4272004-06-13 20:20:40 +00001068 case VK_SHIFT:
1069 case VK_CONTROL:
Bram Moolenaar0f873732019-12-05 20:28:46 +01001070 case VK_MENU: // Alt key
Bram Moolenaar071d4272004-06-13 20:20:40 +00001071 return FALSE;
1072
1073 default:
1074 break;
1075 }
1076
Bram Moolenaar0f873732019-12-05 20:28:46 +01001077 // special cases
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001078 if ((nModifs & CTRL) != 0 && (nModifs & ~CTRL) == 0 && pker->UChar == NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001079 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001080 // Ctrl-6 is Ctrl-^
Bram Moolenaar071d4272004-06-13 20:20:40 +00001081 if (pker->wVirtualKeyCode == '6')
1082 {
1083 *pch = Ctrl_HAT;
1084 return TRUE;
1085 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01001086 // Ctrl-2 is Ctrl-@
Bram Moolenaar071d4272004-06-13 20:20:40 +00001087 else if (pker->wVirtualKeyCode == '2')
1088 {
1089 *pch = NUL;
1090 return TRUE;
1091 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01001092 // Ctrl-- is Ctrl-_
Bram Moolenaar071d4272004-06-13 20:20:40 +00001093 else if (pker->wVirtualKeyCode == 0xBD)
1094 {
1095 *pch = Ctrl__;
1096 return TRUE;
1097 }
1098 }
1099
Bram Moolenaar0f873732019-12-05 20:28:46 +01001100 // Shift-TAB
Bram Moolenaar071d4272004-06-13 20:20:40 +00001101 if (pker->wVirtualKeyCode == VK_TAB && (nModifs & SHIFT_PRESSED))
1102 {
1103 *pch = K_NUL;
1104 *pch2 = '\017';
1105 return TRUE;
1106 }
1107
1108 for (i = sizeof(VirtKeyMap) / sizeof(VirtKeyMap[0]); --i >= 0; )
1109 {
1110 if (VirtKeyMap[i].wVirtKey == pker->wVirtualKeyCode)
1111 {
1112 if (nModifs == 0)
1113 *pch = VirtKeyMap[i].chAlone;
1114 else if ((nModifs & SHIFT) != 0 && (nModifs & ~SHIFT) == 0)
1115 *pch = VirtKeyMap[i].chShift;
1116 else if ((nModifs & CTRL) != 0 && (nModifs & ~CTRL) == 0)
1117 *pch = VirtKeyMap[i].chCtrl;
1118 else if ((nModifs & ALT) != 0 && (nModifs & ~ALT) == 0)
1119 *pch = VirtKeyMap[i].chAlt;
1120
1121 if (*pch != 0)
1122 {
1123 if (VirtKeyMap[i].fAnsiKey)
1124 {
1125 *pch2 = *pch;
1126 *pch = K_NUL;
1127 }
1128
1129 return TRUE;
1130 }
1131 }
1132 }
1133
1134 i = win32_kbd_patch_key(pker);
1135
1136 if (i < 0)
1137 *pch = NUL;
1138 else
1139 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001140 *pch = (i > 0) ? pker->UChar : NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001141
1142 if (pmodifiers != NULL)
1143 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001144 // Pass on the ALT key as a modifier, but only when not combined
1145 // with CTRL (which is ALTGR).
Bram Moolenaar071d4272004-06-13 20:20:40 +00001146 if ((nModifs & ALT) != 0 && (nModifs & CTRL) == 0)
1147 *pmodifiers |= MOD_MASK_ALT;
1148
Bram Moolenaar0f873732019-12-05 20:28:46 +01001149 // Pass on SHIFT only for special keys, because we don't know when
1150 // it's already included with the character.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001151 if ((nModifs & SHIFT) != 0 && *pch <= 0x20)
1152 *pmodifiers |= MOD_MASK_SHIFT;
1153
Bram Moolenaar0f873732019-12-05 20:28:46 +01001154 // Pass on CTRL only for non-special keys, because we don't know
1155 // when it's already included with the character. And not when
1156 // combined with ALT (which is ALTGR).
Bram Moolenaar071d4272004-06-13 20:20:40 +00001157 if ((nModifs & CTRL) != 0 && (nModifs & ALT) == 0
1158 && *pch >= 0x20 && *pch < 0x80)
1159 *pmodifiers |= MOD_MASK_CTRL;
1160 }
1161 }
1162
1163 return (*pch != NUL);
1164}
1165
Bram Moolenaar0f873732019-12-05 20:28:46 +01001166#endif // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00001167
1168
Bram Moolenaar071d4272004-06-13 20:20:40 +00001169/*
1170 * For the GUI the mouse handling is in gui_w32.c.
1171 */
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001172#if defined(FEAT_GUI_MSWIN) && !defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001173 void
Bram Moolenaar1266d672017-02-01 13:43:36 +01001174mch_setmouse(int on UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001175{
1176}
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001177#else
Bram Moolenaar0f873732019-12-05 20:28:46 +01001178static int g_fMouseAvail = FALSE; // mouse present
1179static int g_fMouseActive = FALSE; // mouse enabled
1180static int g_nMouseClick = -1; // mouse status
1181static int g_xMouse; // mouse x coordinate
1182static int g_yMouse; // mouse y coordinate
Bram Moolenaar071d4272004-06-13 20:20:40 +00001183
1184/*
1185 * Enable or disable mouse input
1186 */
1187 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001188mch_setmouse(int on)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001189{
1190 DWORD cmodein;
1191
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001192# ifdef VIMDLL
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001193 if (gui.in_use)
1194 return;
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001195# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001196 if (!g_fMouseAvail)
1197 return;
1198
1199 g_fMouseActive = on;
1200 GetConsoleMode(g_hConIn, &cmodein);
1201
1202 if (g_fMouseActive)
1203 cmodein |= ENABLE_MOUSE_INPUT;
1204 else
1205 cmodein &= ~ENABLE_MOUSE_INPUT;
1206
1207 SetConsoleMode(g_hConIn, cmodein);
1208}
1209
Bram Moolenaar157d8132018-03-06 17:09:20 +01001210
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001211# if defined(FEAT_BEVAL_TERM) || defined(PROTO)
Bram Moolenaar157d8132018-03-06 17:09:20 +01001212/*
1213 * Called when 'balloonevalterm' changed.
1214 */
1215 void
1216mch_bevalterm_changed(void)
1217{
1218 mch_setmouse(g_fMouseActive);
1219}
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001220# endif
Bram Moolenaar157d8132018-03-06 17:09:20 +01001221
Bram Moolenaar071d4272004-06-13 20:20:40 +00001222/*
1223 * Decode a MOUSE_EVENT. If it's a valid event, return MOUSE_LEFT,
1224 * MOUSE_MIDDLE, or MOUSE_RIGHT for a click; MOUSE_DRAG for a mouse
1225 * move with a button held down; and MOUSE_RELEASE after a MOUSE_DRAG
1226 * or a MOUSE_LEFT, _MIDDLE, or _RIGHT. We encode the button type,
1227 * the number of clicks, and the Shift/Ctrl/Alt modifiers in g_nMouseClick,
1228 * and we return the mouse position in g_xMouse and g_yMouse.
1229 *
1230 * Every MOUSE_LEFT, _MIDDLE, or _RIGHT will be followed by zero or more
1231 * MOUSE_DRAGs and one MOUSE_RELEASE. MOUSE_RELEASE will be followed only
1232 * by MOUSE_LEFT, _MIDDLE, or _RIGHT.
1233 *
1234 * For multiple clicks, we send, say, MOUSE_LEFT/1 click, MOUSE_RELEASE,
1235 * MOUSE_LEFT/2 clicks, MOUSE_RELEASE, MOUSE_LEFT/3 clicks, MOUSE_RELEASE, ....
1236 *
1237 * Windows will send us MOUSE_MOVED notifications whenever the mouse
1238 * moves, even if it stays within the same character cell. We ignore
1239 * all MOUSE_MOVED messages if the position hasn't really changed, and
1240 * we ignore all MOUSE_MOVED messages where no button is held down (i.e.,
1241 * we're only interested in MOUSE_DRAG).
1242 *
1243 * All of this is complicated by the code that fakes MOUSE_MIDDLE on
1244 * 2-button mouses by pressing the left & right buttons simultaneously.
1245 * In practice, it's almost impossible to click both at the same time,
1246 * so we need to delay a little. Also, we tend not to get MOUSE_RELEASE
1247 * in such cases, if the user is clicking quickly.
1248 */
1249 static BOOL
1250decode_mouse_event(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001251 MOUSE_EVENT_RECORD *pmer)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001252{
1253 static int s_nOldButton = -1;
1254 static int s_nOldMouseClick = -1;
1255 static int s_xOldMouse = -1;
1256 static int s_yOldMouse = -1;
1257 static linenr_T s_old_topline = 0;
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001258# ifdef FEAT_DIFF
Bram Moolenaar071d4272004-06-13 20:20:40 +00001259 static int s_old_topfill = 0;
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001260# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001261 static int s_cClicks = 1;
1262 static BOOL s_fReleased = TRUE;
1263 static DWORD s_dwLastClickTime = 0;
1264 static BOOL s_fNextIsMiddle = FALSE;
1265
Bram Moolenaar0f873732019-12-05 20:28:46 +01001266 static DWORD cButtons = 0; // number of buttons supported
Bram Moolenaar071d4272004-06-13 20:20:40 +00001267
1268 const DWORD LEFT = FROM_LEFT_1ST_BUTTON_PRESSED;
1269 const DWORD MIDDLE = FROM_LEFT_2ND_BUTTON_PRESSED;
1270 const DWORD RIGHT = RIGHTMOST_BUTTON_PRESSED;
1271 const DWORD LEFT_RIGHT = LEFT | RIGHT;
1272
1273 int nButton;
1274
1275 if (cButtons == 0 && !GetNumberOfConsoleMouseButtons(&cButtons))
1276 cButtons = 2;
1277
1278 if (!g_fMouseAvail || !g_fMouseActive)
1279 {
1280 g_nMouseClick = -1;
1281 return FALSE;
1282 }
1283
Bram Moolenaar0f873732019-12-05 20:28:46 +01001284 // get a spurious MOUSE_EVENT immediately after receiving focus; ignore
Bram Moolenaar071d4272004-06-13 20:20:40 +00001285 if (g_fJustGotFocus)
1286 {
1287 g_fJustGotFocus = FALSE;
1288 return FALSE;
1289 }
1290
Bram Moolenaar0f873732019-12-05 20:28:46 +01001291 // unprocessed mouse click?
Bram Moolenaar071d4272004-06-13 20:20:40 +00001292 if (g_nMouseClick != -1)
1293 return TRUE;
1294
1295 nButton = -1;
1296 g_xMouse = pmer->dwMousePosition.X;
1297 g_yMouse = pmer->dwMousePosition.Y;
1298
1299 if (pmer->dwEventFlags == MOUSE_MOVED)
1300 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001301 // Ignore MOUSE_MOVED events if (x, y) hasn't changed. (We get these
1302 // events even when the mouse moves only within a char cell.)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001303 if (s_xOldMouse == g_xMouse && s_yOldMouse == g_yMouse)
1304 return FALSE;
1305 }
1306
Bram Moolenaar0f873732019-12-05 20:28:46 +01001307 // If no buttons are pressed...
Bram Moolenaar071d4272004-06-13 20:20:40 +00001308 if ((pmer->dwButtonState & ((1 << cButtons) - 1)) == 0)
1309 {
Bram Moolenaar157d8132018-03-06 17:09:20 +01001310 nButton = MOUSE_RELEASE;
1311
Bram Moolenaar0f873732019-12-05 20:28:46 +01001312 // If the last thing returned was MOUSE_RELEASE, ignore this
Bram Moolenaar071d4272004-06-13 20:20:40 +00001313 if (s_fReleased)
Bram Moolenaar157d8132018-03-06 17:09:20 +01001314 {
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001315# ifdef FEAT_BEVAL_TERM
Bram Moolenaar0f873732019-12-05 20:28:46 +01001316 // do return mouse move events when we want them
Bram Moolenaar157d8132018-03-06 17:09:20 +01001317 if (p_bevalterm)
1318 nButton = MOUSE_DRAG;
1319 else
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001320# endif
Bram Moolenaar157d8132018-03-06 17:09:20 +01001321 return FALSE;
1322 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001323
Bram Moolenaar071d4272004-06-13 20:20:40 +00001324 s_fReleased = TRUE;
1325 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01001326 else // one or more buttons pressed
Bram Moolenaar071d4272004-06-13 20:20:40 +00001327 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001328 // on a 2-button mouse, hold down left and right buttons
1329 // simultaneously to get MIDDLE.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001330
1331 if (cButtons == 2 && s_nOldButton != MOUSE_DRAG)
1332 {
1333 DWORD dwLR = (pmer->dwButtonState & LEFT_RIGHT);
1334
Bram Moolenaar0f873732019-12-05 20:28:46 +01001335 // if either left or right button only is pressed, see if the
1336 // next mouse event has both of them pressed
Bram Moolenaar071d4272004-06-13 20:20:40 +00001337 if (dwLR == LEFT || dwLR == RIGHT)
1338 {
1339 for (;;)
1340 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001341 // wait a short time for next input event
Bram Moolenaar071d4272004-06-13 20:20:40 +00001342 if (WaitForSingleObject(g_hConIn, p_mouset / 3)
1343 != WAIT_OBJECT_0)
1344 break;
1345 else
1346 {
1347 DWORD cRecords = 0;
1348 INPUT_RECORD ir;
1349 MOUSE_EVENT_RECORD* pmer2 = &ir.Event.MouseEvent;
1350
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001351 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001352
1353 if (cRecords == 0 || ir.EventType != MOUSE_EVENT
1354 || !(pmer2->dwButtonState & LEFT_RIGHT))
1355 break;
1356 else
1357 {
1358 if (pmer2->dwEventFlags != MOUSE_MOVED)
1359 {
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001360 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001361
1362 return decode_mouse_event(pmer2);
1363 }
1364 else if (s_xOldMouse == pmer2->dwMousePosition.X &&
1365 s_yOldMouse == pmer2->dwMousePosition.Y)
1366 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001367 // throw away spurious mouse move
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001368 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001369
Bram Moolenaar0f873732019-12-05 20:28:46 +01001370 // are there any more mouse events in queue?
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001371 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001372
1373 if (cRecords==0 || ir.EventType != MOUSE_EVENT)
1374 break;
1375 }
1376 else
1377 break;
1378 }
1379 }
1380 }
1381 }
1382 }
1383
1384 if (s_fNextIsMiddle)
1385 {
1386 nButton = (pmer->dwEventFlags == MOUSE_MOVED)
1387 ? MOUSE_DRAG : MOUSE_MIDDLE;
1388 s_fNextIsMiddle = FALSE;
1389 }
1390 else if (cButtons == 2 &&
1391 ((pmer->dwButtonState & LEFT_RIGHT) == LEFT_RIGHT))
1392 {
1393 nButton = MOUSE_MIDDLE;
1394
1395 if (! s_fReleased && pmer->dwEventFlags != MOUSE_MOVED)
1396 {
1397 s_fNextIsMiddle = TRUE;
1398 nButton = MOUSE_RELEASE;
1399 }
1400 }
1401 else if ((pmer->dwButtonState & LEFT) == LEFT)
1402 nButton = MOUSE_LEFT;
1403 else if ((pmer->dwButtonState & MIDDLE) == MIDDLE)
1404 nButton = MOUSE_MIDDLE;
1405 else if ((pmer->dwButtonState & RIGHT) == RIGHT)
1406 nButton = MOUSE_RIGHT;
1407
1408 if (! s_fReleased && ! s_fNextIsMiddle
1409 && nButton != s_nOldButton && s_nOldButton != MOUSE_DRAG)
1410 return FALSE;
1411
1412 s_fReleased = s_fNextIsMiddle;
1413 }
1414
1415 if (pmer->dwEventFlags == 0 || pmer->dwEventFlags == DOUBLE_CLICK)
1416 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001417 // button pressed or released, without mouse moving
Bram Moolenaar071d4272004-06-13 20:20:40 +00001418 if (nButton != -1 && nButton != MOUSE_RELEASE)
1419 {
1420 DWORD dwCurrentTime = GetTickCount();
1421
1422 if (s_xOldMouse != g_xMouse
1423 || s_yOldMouse != g_yMouse
1424 || s_nOldButton != nButton
1425 || s_old_topline != curwin->w_topline
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001426# ifdef FEAT_DIFF
Bram Moolenaar071d4272004-06-13 20:20:40 +00001427 || s_old_topfill != curwin->w_topfill
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001428# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001429 || (int)(dwCurrentTime - s_dwLastClickTime) > p_mouset)
1430 {
1431 s_cClicks = 1;
1432 }
1433 else if (++s_cClicks > 4)
1434 {
1435 s_cClicks = 1;
1436 }
1437
1438 s_dwLastClickTime = dwCurrentTime;
1439 }
1440 }
1441 else if (pmer->dwEventFlags == MOUSE_MOVED)
1442 {
1443 if (nButton != -1 && nButton != MOUSE_RELEASE)
1444 nButton = MOUSE_DRAG;
1445
1446 s_cClicks = 1;
1447 }
1448
1449 if (nButton == -1)
1450 return FALSE;
1451
1452 if (nButton != MOUSE_RELEASE)
1453 s_nOldButton = nButton;
1454
1455 g_nMouseClick = nButton;
1456
1457 if (pmer->dwControlKeyState & SHIFT_PRESSED)
1458 g_nMouseClick |= MOUSE_SHIFT;
1459 if (pmer->dwControlKeyState & (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED))
1460 g_nMouseClick |= MOUSE_CTRL;
1461 if (pmer->dwControlKeyState & (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED))
1462 g_nMouseClick |= MOUSE_ALT;
1463
1464 if (nButton != MOUSE_DRAG && nButton != MOUSE_RELEASE)
1465 SET_NUM_MOUSE_CLICKS(g_nMouseClick, s_cClicks);
1466
Bram Moolenaar0f873732019-12-05 20:28:46 +01001467 // only pass on interesting (i.e., different) mouse events
Bram Moolenaar071d4272004-06-13 20:20:40 +00001468 if (s_xOldMouse == g_xMouse
1469 && s_yOldMouse == g_yMouse
1470 && s_nOldMouseClick == g_nMouseClick)
1471 {
1472 g_nMouseClick = -1;
1473 return FALSE;
1474 }
1475
1476 s_xOldMouse = g_xMouse;
1477 s_yOldMouse = g_yMouse;
1478 s_old_topline = curwin->w_topline;
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001479# ifdef FEAT_DIFF
Bram Moolenaar071d4272004-06-13 20:20:40 +00001480 s_old_topfill = curwin->w_topfill;
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001481# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001482 s_nOldMouseClick = g_nMouseClick;
1483
1484 return TRUE;
1485}
1486
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001487#endif // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00001488
1489
1490#ifdef MCH_CURSOR_SHAPE
1491/*
1492 * Set the shape of the cursor.
1493 * 'thickness' can be from 1 (thin) to 99 (block)
1494 */
1495 static void
1496mch_set_cursor_shape(int thickness)
1497{
1498 CONSOLE_CURSOR_INFO ConsoleCursorInfo;
1499 ConsoleCursorInfo.dwSize = thickness;
1500 ConsoleCursorInfo.bVisible = s_cursor_visible;
1501
1502 SetConsoleCursorInfo(g_hConOut, &ConsoleCursorInfo);
1503 if (s_cursor_visible)
1504 SetConsoleCursorPosition(g_hConOut, g_coord);
1505}
1506
1507 void
1508mch_update_cursor(void)
1509{
1510 int idx;
1511 int thickness;
1512
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001513# ifdef VIMDLL
1514 if (gui.in_use)
1515 return;
1516# endif
1517
Bram Moolenaar071d4272004-06-13 20:20:40 +00001518 /*
1519 * How the cursor is drawn depends on the current mode.
1520 */
1521 idx = get_shape_idx(FALSE);
1522
1523 if (shape_table[idx].shape == SHAPE_BLOCK)
Bram Moolenaar0f873732019-12-05 20:28:46 +01001524 thickness = 99; // 100 doesn't work on W95
Bram Moolenaar071d4272004-06-13 20:20:40 +00001525 else
1526 thickness = shape_table[idx].percentage;
1527 mch_set_cursor_shape(thickness);
1528}
1529#endif
1530
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001531#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001532/*
1533 * Handle FOCUS_EVENT.
1534 */
1535 static void
1536handle_focus_event(INPUT_RECORD ir)
1537{
1538 g_fJustGotFocus = ir.Event.FocusEvent.bSetFocus;
1539 ui_focus_change((int)g_fJustGotFocus);
1540}
1541
Bram Moolenaar78d21da2019-02-17 15:00:52 +01001542static void ResizeConBuf(HANDLE hConsole, COORD coordScreen);
1543
Bram Moolenaar071d4272004-06-13 20:20:40 +00001544/*
1545 * Wait until console input from keyboard or mouse is available,
1546 * or the time is up.
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001547 * When "ignore_input" is TRUE even wait when input is available.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001548 * Return TRUE if something is available FALSE if not.
1549 */
1550 static int
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001551WaitForChar(long msec, int ignore_input)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001552{
1553 DWORD dwNow = 0, dwEndTime = 0;
1554 INPUT_RECORD ir;
1555 DWORD cRecords;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001556 WCHAR ch, ch2;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001557# ifdef FEAT_TIMERS
Bram Moolenaar40b1b542016-04-20 20:18:23 +02001558 int tb_change_cnt = typebuf.tb_change_cnt;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001559# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001560
1561 if (msec > 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01001562 // Wait until the specified time has elapsed.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001563 dwEndTime = GetTickCount() + msec;
1564 else if (msec < 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01001565 // Wait forever.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001566 dwEndTime = INFINITE;
1567
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01001568 // We need to loop until the end of the time period, because
1569 // we might get multiple unusable mouse events in that time.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001570 for (;;)
1571 {
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001572 // Only process messages when waiting.
1573 if (msec != 0)
1574 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001575# ifdef MESSAGE_QUEUE
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001576 parse_queued_messages();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001577# endif
1578# ifdef FEAT_MZSCHEME
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001579 mzvim_check_threads();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001580# endif
1581# ifdef FEAT_CLIENTSERVER
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001582 serverProcessPendingMessages();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001583# endif
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001584 }
Bram Moolenaarf12d9832016-01-29 21:11:25 +01001585
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001586 if (g_nMouseClick != -1
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001587# ifdef FEAT_CLIENTSERVER
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001588 || (!ignore_input && input_available())
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001589# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001590 )
1591 return TRUE;
1592
1593 if (msec > 0)
1594 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001595 // If the specified wait time has passed, return. Beware that
1596 // GetTickCount() may wrap around (overflow).
Bram Moolenaar071d4272004-06-13 20:20:40 +00001597 dwNow = GetTickCount();
Bram Moolenaarb7512b72013-08-10 12:45:09 +02001598 if ((int)(dwNow - dwEndTime) >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001599 break;
1600 }
1601 if (msec != 0)
1602 {
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001603 DWORD dwWaitTime = dwEndTime - dwNow;
1604
Bram Moolenaarc478ee32020-12-01 21:27:51 +01001605 // Don't wait for more than 11 msec to avoid dropping characters,
1606 // check channel while waiting for input and handle a callback from
1607 // 'balloonexpr'.
1608 if (dwWaitTime > 11)
1609 dwWaitTime = 11;
1610
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001611# ifdef FEAT_MZSCHEME
Bram Moolenaarc478ee32020-12-01 21:27:51 +01001612 if (mzthreads_allowed() && p_mzq > 0 && (long)dwWaitTime > p_mzq)
Bram Moolenaar0f873732019-12-05 20:28:46 +01001613 dwWaitTime = p_mzq; // don't wait longer than 'mzquantum'
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001614# endif
1615# ifdef FEAT_TIMERS
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001616 // When waiting very briefly don't trigger timers.
1617 if (dwWaitTime > 10)
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001618 {
1619 long due_time;
1620
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001621 // Trigger timers and then get the time in msec until the next
1622 // one is due. Wait up to that time.
1623 due_time = check_due_timer();
1624 if (typebuf.tb_change_cnt != tb_change_cnt)
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001625 {
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001626 // timer may have used feedkeys().
1627 return FALSE;
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001628 }
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001629 if (due_time > 0 && dwWaitTime > (DWORD)due_time)
1630 dwWaitTime = due_time;
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001631 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001632# endif
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001633 if (
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001634# ifdef FEAT_CLIENTSERVER
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001635 // Wait for either an event on the console input or a
1636 // message in the client-server window.
1637 msg_wait_for_multiple_objects(1, &g_hConIn, FALSE,
1638 dwWaitTime, QS_SENDMESSAGE) != WAIT_OBJECT_0
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001639# else
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001640 wait_for_single_object(g_hConIn, dwWaitTime)
1641 != WAIT_OBJECT_0
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001642# endif
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001643 )
1644 continue;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001645 }
1646
1647 cRecords = 0;
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001648 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001649
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001650# ifdef FEAT_MBYTE_IME
Bram Moolenaar071d4272004-06-13 20:20:40 +00001651 if (State & CMDLINE && msg_row == Rows - 1)
1652 {
1653 CONSOLE_SCREEN_BUFFER_INFO csbi;
1654
1655 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
1656 {
1657 if (csbi.dwCursorPosition.Y != msg_row)
1658 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001659 // The screen is now messed up, must redraw the
1660 // command line and later all the windows.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001661 redraw_all_later(CLEAR);
1662 cmdline_row -= (msg_row - csbi.dwCursorPosition.Y);
1663 redrawcmd();
1664 }
1665 }
1666 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001667# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001668
1669 if (cRecords > 0)
1670 {
1671 if (ir.EventType == KEY_EVENT && ir.Event.KeyEvent.bKeyDown)
1672 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001673# ifdef FEAT_MBYTE_IME
Bram Moolenaar0f873732019-12-05 20:28:46 +01001674 // Windows IME sends two '\n's with only one 'ENTER'. First:
1675 // wVirtualKeyCode == 13. second: wVirtualKeyCode == 0
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001676 if (ir.Event.KeyEvent.UChar == 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00001677 && ir.Event.KeyEvent.wVirtualKeyCode == 13)
1678 {
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001679 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001680 continue;
1681 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001682# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001683 if (decode_key_event(&ir.Event.KeyEvent, &ch, &ch2,
1684 NULL, FALSE))
1685 return TRUE;
1686 }
1687
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001688 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001689
1690 if (ir.EventType == FOCUS_EVENT)
1691 handle_focus_event(ir);
1692 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
Bram Moolenaarc33ecb22018-02-11 16:40:45 +01001693 {
Bram Moolenaar78d21da2019-02-17 15:00:52 +01001694 COORD dwSize = ir.Event.WindowBufferSizeEvent.dwSize;
1695
Bram Moolenaar36698e32019-12-11 22:57:40 +01001696 // Only call shell_resized() when the size actually changed to
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001697 // avoid the screen is cleared.
Bram Moolenaar78d21da2019-02-17 15:00:52 +01001698 if (dwSize.X != Columns || dwSize.Y != Rows)
1699 {
1700 CONSOLE_SCREEN_BUFFER_INFO csbi;
1701 GetConsoleScreenBufferInfo(g_hConOut, &csbi);
Bram Moolenaar36698e32019-12-11 22:57:40 +01001702 dwSize.X = csbi.srWindow.Right - csbi.srWindow.Left + 1;
Bram Moolenaar78d21da2019-02-17 15:00:52 +01001703 dwSize.Y = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
Bram Moolenaar36698e32019-12-11 22:57:40 +01001704 if (dwSize.X != Columns || dwSize.Y != Rows)
1705 {
1706 ResizeConBuf(g_hConOut, dwSize);
1707 shell_resized();
1708 }
Bram Moolenaar78d21da2019-02-17 15:00:52 +01001709 }
Bram Moolenaarc33ecb22018-02-11 16:40:45 +01001710 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001711 else if (ir.EventType == MOUSE_EVENT
1712 && decode_mouse_event(&ir.Event.MouseEvent))
1713 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001714 }
1715 else if (msec == 0)
1716 break;
1717 }
1718
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001719# ifdef FEAT_CLIENTSERVER
Bram Moolenaar0f873732019-12-05 20:28:46 +01001720 // Something might have been received while we were waiting.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001721 if (input_available())
1722 return TRUE;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001723# endif
Bram Moolenaarf12d9832016-01-29 21:11:25 +01001724
Bram Moolenaar071d4272004-06-13 20:20:40 +00001725 return FALSE;
1726}
1727
Bram Moolenaar071d4272004-06-13 20:20:40 +00001728/*
1729 * return non-zero if a character is available
1730 */
1731 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001732mch_char_avail(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001733{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001734# ifdef VIMDLL
1735 if (gui.in_use)
1736 return TRUE;
1737# endif
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001738 return WaitForChar(0L, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001739}
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001740
1741# if defined(FEAT_TERMINAL) || defined(PROTO)
1742/*
1743 * Check for any pending input or messages.
1744 */
1745 int
1746mch_check_messages(void)
1747{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001748# ifdef VIMDLL
1749 if (gui.in_use)
1750 return TRUE;
1751# endif
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001752 return WaitForChar(0L, TRUE);
1753}
1754# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001755
1756/*
1757 * Create the console input. Used when reading stdin doesn't work.
1758 */
1759 static void
1760create_conin(void)
1761{
1762 g_hConIn = CreateFile("CONIN$", GENERIC_READ|GENERIC_WRITE,
1763 FILE_SHARE_READ|FILE_SHARE_WRITE,
1764 (LPSECURITY_ATTRIBUTES) NULL,
Bram Moolenaareb3593b2006-04-22 22:33:57 +00001765 OPEN_EXISTING, 0, (HANDLE)NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001766 did_create_conin = TRUE;
1767}
1768
1769/*
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001770 * Get a keystroke or a mouse event, use a blocking wait.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001771 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001772 static WCHAR
1773tgetch(int *pmodifiers, WCHAR *pch2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001774{
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001775 WCHAR ch;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001776
1777 for (;;)
1778 {
1779 INPUT_RECORD ir;
1780 DWORD cRecords = 0;
1781
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001782# ifdef FEAT_CLIENTSERVER
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001783 (void)WaitForChar(-1L, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001784 if (input_available())
1785 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001786 if (g_nMouseClick != -1)
1787 return 0;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001788# endif
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001789 if (read_console_input(g_hConIn, &ir, 1, &cRecords) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001790 {
1791 if (did_create_conin)
1792 read_error_exit();
1793 create_conin();
1794 continue;
1795 }
1796
1797 if (ir.EventType == KEY_EVENT)
1798 {
1799 if (decode_key_event(&ir.Event.KeyEvent, &ch, pch2,
1800 pmodifiers, TRUE))
1801 return ch;
1802 }
1803 else if (ir.EventType == FOCUS_EVENT)
1804 handle_focus_event(ir);
1805 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
1806 shell_resized();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001807 else if (ir.EventType == MOUSE_EVENT)
1808 {
1809 if (decode_mouse_event(&ir.Event.MouseEvent))
1810 return 0;
1811 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001812 }
1813}
Bram Moolenaar0f873732019-12-05 20:28:46 +01001814#endif // !FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00001815
1816
1817/*
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02001818 * mch_inchar(): low-level input function.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001819 * Get one or more characters from the keyboard or the mouse.
1820 * If time == 0, do not wait for characters.
1821 * If time == n, wait a short time for characters.
1822 * If time == -1, wait forever for characters.
1823 * Returns the number of characters read into buf.
1824 */
1825 int
1826mch_inchar(
Bram Moolenaar1266d672017-02-01 13:43:36 +01001827 char_u *buf UNUSED,
1828 int maxlen UNUSED,
1829 long time UNUSED,
1830 int tb_change_cnt UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001831{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001832#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001833
1834 int len;
1835 int c;
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01001836# ifdef VIMDLL
1837// Extra space for maximum three CSIs. E.g. U+1B6DB -> 0xF0 0x9B 0x9B 0x9B.
1838# define TYPEAHEADSPACE 6
1839# else
1840# define TYPEAHEADSPACE 0
1841# endif
1842# define TYPEAHEADLEN (20 + TYPEAHEADSPACE)
Bram Moolenaar0f873732019-12-05 20:28:46 +01001843 static char_u typeahead[TYPEAHEADLEN]; // previously typed bytes.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001844 static int typeaheadlen = 0;
1845
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001846# ifdef VIMDLL
1847 if (gui.in_use)
1848 return 0;
1849# endif
1850
Bram Moolenaar0f873732019-12-05 20:28:46 +01001851 // First use any typeahead that was kept because "buf" was too small.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001852 if (typeaheadlen > 0)
1853 goto theend;
1854
Bram Moolenaar071d4272004-06-13 20:20:40 +00001855 if (time >= 0)
1856 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001857 if (!WaitForChar(time, FALSE)) // no character available
Bram Moolenaar071d4272004-06-13 20:20:40 +00001858 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001859 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01001860 else // time == -1, wait forever
Bram Moolenaar071d4272004-06-13 20:20:40 +00001861 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001862 mch_set_winsize_now(); // Allow winsize changes from now on
Bram Moolenaar071d4272004-06-13 20:20:40 +00001863
Bram Moolenaar3918c952005-03-15 22:34:55 +00001864 /*
1865 * If there is no character available within 2 seconds (default)
1866 * write the autoscript file to disk. Or cause the CursorHold event
1867 * to be triggered.
1868 */
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001869 if (!WaitForChar(p_ut, FALSE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001870 {
Bram Moolenaard35f9712005-12-18 22:02:33 +00001871 if (trigger_cursorhold() && maxlen >= 3)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001872 {
Bram Moolenaar3918c952005-03-15 22:34:55 +00001873 buf[0] = K_SPECIAL;
1874 buf[1] = KS_EXTRA;
1875 buf[2] = (int)KE_CURSORHOLD;
1876 return 3;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001877 }
Bram Moolenaar702517d2005-06-27 22:34:07 +00001878 before_blocking();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001879 }
1880 }
1881
1882 /*
1883 * Try to read as many characters as there are, until the buffer is full.
1884 */
1885
Bram Moolenaar0f873732019-12-05 20:28:46 +01001886 // we will get at least one key. Get more if they are available.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001887 g_fCBrkPressed = FALSE;
1888
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001889# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00001890 if (fdDump)
1891 fputc('[', fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001892# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001893
Bram Moolenaar0f873732019-12-05 20:28:46 +01001894 // Keep looping until there is something in the typeahead buffer and more
1895 // to get and still room in the buffer (up to two bytes for a char and
1896 // three bytes for a modifier).
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001897 while ((typeaheadlen == 0 || WaitForChar(0L, FALSE))
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01001898 && typeaheadlen + 5 + TYPEAHEADSPACE <= TYPEAHEADLEN)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001899 {
1900 if (typebuf_changed(tb_change_cnt))
1901 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001902 // "buf" may be invalid now if a client put something in the
1903 // typeahead buffer and "buf" is in the typeahead buffer.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001904 typeaheadlen = 0;
1905 break;
1906 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001907 if (g_nMouseClick != -1)
1908 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001909# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00001910 if (fdDump)
1911 fprintf(fdDump, "{%02x @ %d, %d}",
1912 g_nMouseClick, g_xMouse, g_yMouse);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001913# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001914 typeahead[typeaheadlen++] = ESC + 128;
1915 typeahead[typeaheadlen++] = 'M';
1916 typeahead[typeaheadlen++] = g_nMouseClick;
1917 typeahead[typeaheadlen++] = g_xMouse + '!';
1918 typeahead[typeaheadlen++] = g_yMouse + '!';
1919 g_nMouseClick = -1;
1920 }
1921 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00001922 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001923 WCHAR ch2 = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001924 int modifiers = 0;
1925
1926 c = tgetch(&modifiers, &ch2);
1927
1928 if (typebuf_changed(tb_change_cnt))
1929 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001930 // "buf" may be invalid now if a client put something in the
1931 // typeahead buffer and "buf" is in the typeahead buffer.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001932 typeaheadlen = 0;
1933 break;
1934 }
1935
1936 if (c == Ctrl_C && ctrl_c_interrupts)
1937 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001938# if defined(FEAT_CLIENTSERVER)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001939 trash_input_buf();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001940# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001941 got_int = TRUE;
1942 }
1943
Bram Moolenaar071d4272004-06-13 20:20:40 +00001944 if (g_nMouseClick == -1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001945 {
1946 int n = 1;
1947
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001948 if (ch2 == NUL)
1949 {
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01001950 int i, j;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001951 char_u *p;
1952 WCHAR ch[2];
1953
1954 ch[0] = c;
Bram Moolenaar0f873732019-12-05 20:28:46 +01001955 if (c >= 0xD800 && c <= 0xDBFF) // High surrogate
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001956 {
1957 ch[1] = tgetch(&modifiers, &ch2);
1958 n++;
1959 }
1960 p = utf16_to_enc(ch, &n);
1961 if (p != NULL)
1962 {
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01001963 for (i = 0, j = 0; i < n; i++)
1964 {
1965 typeahead[typeaheadlen + j++] = p[i];
1966# ifdef VIMDLL
1967 if (p[i] == CSI)
1968 {
1969 typeahead[typeaheadlen + j++] = KS_EXTRA;
1970 typeahead[typeaheadlen + j++] = KE_CSI;
1971 }
1972# endif
1973 }
1974 n = j;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001975 vim_free(p);
1976 }
1977 }
1978 else
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01001979 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001980 typeahead[typeaheadlen] = c;
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01001981# ifdef VIMDLL
1982 if (c == CSI)
1983 {
1984 typeahead[typeaheadlen + 1] = KS_EXTRA;
1985 typeahead[typeaheadlen + 2] = KE_CSI;
1986 n = 3;
1987 }
1988# endif
1989 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001990 if (ch2 != NUL)
1991 {
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +02001992 if (c == K_NUL)
Bram Moolenaarfeeb4d02017-12-05 15:14:46 +01001993 {
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +02001994 switch (ch2)
1995 {
1996 case (WCHAR)'\324': // SHIFT+Insert
1997 case (WCHAR)'\325': // CTRL+Insert
1998 case (WCHAR)'\327': // SHIFT+Delete
1999 case (WCHAR)'\330': // CTRL+Delete
2000 typeahead[typeaheadlen + n] = (char_u)ch2;
2001 n++;
2002 break;
2003
2004 default:
2005 typeahead[typeaheadlen + n] = 3;
2006 typeahead[typeaheadlen + n + 1] = (char_u)ch2;
2007 n += 2;
2008 break;
2009 }
Bram Moolenaarfeeb4d02017-12-05 15:14:46 +01002010 }
2011 else
2012 {
2013 typeahead[typeaheadlen + n] = 3;
2014 typeahead[typeaheadlen + n + 1] = (char_u)ch2;
2015 n += 2;
2016 }
Bram Moolenaar45500912014-07-09 20:51:07 +02002017 }
2018
Bram Moolenaar0f873732019-12-05 20:28:46 +01002019 // Use the ALT key to set the 8th bit of the character
2020 // when it's one byte, the 8th bit isn't set yet and not
2021 // using a double-byte encoding (would become a lead
2022 // byte).
Bram Moolenaar071d4272004-06-13 20:20:40 +00002023 if ((modifiers & MOD_MASK_ALT)
2024 && n == 1
2025 && (typeahead[typeaheadlen] & 0x80) == 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00002026 && !enc_dbcs
Bram Moolenaar071d4272004-06-13 20:20:40 +00002027 )
2028 {
Bram Moolenaar85a3e5c2007-11-20 16:22:16 +00002029 n = (*mb_char2bytes)(typeahead[typeaheadlen] | 0x80,
2030 typeahead + typeaheadlen);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002031 modifiers &= ~MOD_MASK_ALT;
2032 }
2033
2034 if (modifiers != 0)
2035 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01002036 // Prepend modifiers to the character.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002037 mch_memmove(typeahead + typeaheadlen + 3,
2038 typeahead + typeaheadlen, n);
2039 typeahead[typeaheadlen++] = K_SPECIAL;
2040 typeahead[typeaheadlen++] = (char_u)KS_MODIFIER;
2041 typeahead[typeaheadlen++] = modifiers;
2042 }
2043
2044 typeaheadlen += n;
2045
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002046# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00002047 if (fdDump)
2048 fputc(c, fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002049# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002050 }
2051 }
2052 }
2053
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002054# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00002055 if (fdDump)
2056 {
2057 fputs("]\n", fdDump);
2058 fflush(fdDump);
2059 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002060# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002061
Bram Moolenaar071d4272004-06-13 20:20:40 +00002062theend:
Bram Moolenaar0f873732019-12-05 20:28:46 +01002063 // Move typeahead to "buf", as much as fits.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002064 len = 0;
2065 while (len < maxlen && typeaheadlen > 0)
2066 {
2067 buf[len++] = typeahead[0];
2068 mch_memmove(typeahead, typeahead + 1, --typeaheadlen);
2069 }
Bram Moolenaar7ca86fe2020-09-03 19:25:11 +02002070# ifdef FEAT_JOB_CHANNEL
2071 if (len > 0)
2072 {
2073 buf[len] = NUL;
2074 ch_log(NULL, "raw key input: \"%s\"", buf);
2075 }
2076# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002077 return len;
2078
Bram Moolenaar0f873732019-12-05 20:28:46 +01002079#else // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00002080 return 0;
Bram Moolenaar0f873732019-12-05 20:28:46 +01002081#endif // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00002082}
2083
Bram Moolenaar82881492012-11-20 16:53:39 +01002084#ifndef PROTO
2085# ifndef __MINGW32__
Bram Moolenaar0f873732019-12-05 20:28:46 +01002086# include <shellapi.h> // required for FindExecutable()
Bram Moolenaar82881492012-11-20 16:53:39 +01002087# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002088#endif
2089
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002090/*
Bram Moolenaar95da1362020-05-30 18:37:55 +02002091 * Return TRUE if "name" is an executable file, FALSE if not or it doesn't exist.
Bram Moolenaar43663192017-03-05 14:29:12 +01002092 * When returning TRUE and "path" is not NULL save the path and set "*path" to
2093 * the allocated memory.
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00002094 * TODO: Should somehow check if it's really executable.
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002095 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002096 static int
Bram Moolenaar95da1362020-05-30 18:37:55 +02002097executable_file(char *name, char_u **path)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002098{
Bram Moolenaar95da1362020-05-30 18:37:55 +02002099 if (mch_getperm((char_u *)name) != -1 && !mch_isdir((char_u *)name))
Bram Moolenaar43663192017-03-05 14:29:12 +01002100 {
Bram Moolenaar95da1362020-05-30 18:37:55 +02002101 if (path != NULL)
2102 *path = FullName_save((char_u *)name, FALSE);
2103 return TRUE;
2104 }
2105 return FALSE;
2106}
2107
2108/*
2109 * If "use_path" is TRUE: Return TRUE if "name" is in $PATH.
2110 * If "use_path" is FALSE: Return TRUE if "name" exists.
2111 * If "use_pathext" is TRUE search "name" with extensions in $PATHEXT.
2112 * When returning TRUE and "path" is not NULL save the path and set "*path" to
2113 * the allocated memory.
2114 */
2115 static int
2116executable_exists(char *name, char_u **path, int use_path, int use_pathext)
2117{
2118 // WinNT and later can use _MAX_PATH wide characters for a pathname, which
2119 // means that the maximum pathname is _MAX_PATH * 3 bytes when 'enc' is
2120 // UTF-8.
2121 char_u buf[_MAX_PATH * 3];
2122 size_t len = STRLEN(name);
2123 size_t tmplen;
2124 char_u *p, *e, *e2;
2125 char_u *pathbuf = NULL;
2126 char_u *pathext = NULL;
2127 char_u *pathextbuf = NULL;
2128 int noext = FALSE;
2129 int retval = FALSE;
2130
2131 if (len >= sizeof(buf)) // safety check
Bram Moolenaar43663192017-03-05 14:29:12 +01002132 return FALSE;
Bram Moolenaar95da1362020-05-30 18:37:55 +02002133
2134 // Using the name directly when a Unix-shell like 'shell'.
2135 if (strstr((char *)gettail(p_sh), "sh") != NULL)
2136 noext = TRUE;
2137
2138 if (use_pathext)
2139 {
2140 pathext = mch_getenv("PATHEXT");
2141 if (pathext == NULL)
2142 pathext = (char_u *)".com;.exe;.bat;.cmd";
2143
2144 if (noext == FALSE)
2145 {
2146 /*
2147 * Loop over all extensions in $PATHEXT.
2148 * Check "name" ends with extension.
2149 */
2150 p = pathext;
2151 while (*p)
2152 {
2153 if (p[0] == ';'
2154 || (p[0] == '.' && (p[1] == NUL || p[1] == ';')))
2155 {
2156 // Skip empty or single ".".
2157 ++p;
2158 continue;
2159 }
2160 e = vim_strchr(p, ';');
2161 if (e == NULL)
2162 e = p + STRLEN(p);
2163 tmplen = e - p;
2164
2165 if (_strnicoll(name + len - tmplen, (char *)p, tmplen) == 0)
2166 {
2167 noext = TRUE;
2168 break;
2169 }
2170
2171 p = e;
2172 }
2173 }
Bram Moolenaar43663192017-03-05 14:29:12 +01002174 }
2175
Bram Moolenaar95da1362020-05-30 18:37:55 +02002176 // Prepend single "." to pathext, it's means no extension added.
2177 if (pathext == NULL)
2178 pathext = (char_u *)".";
2179 else if (noext == TRUE)
2180 {
2181 if (pathextbuf == NULL)
2182 pathextbuf = alloc(STRLEN(pathext) + 3);
2183 if (pathextbuf == NULL)
2184 {
2185 retval = FALSE;
2186 goto theend;
2187 }
2188 STRCPY(pathextbuf, ".;");
2189 STRCAT(pathextbuf, pathext);
2190 pathext = pathextbuf;
2191 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002192
Bram Moolenaar95da1362020-05-30 18:37:55 +02002193 // Use $PATH when "use_path" is TRUE and "name" is basename.
2194 if (use_path && gettail((char_u *)name) == (char_u *)name)
2195 {
2196 p = mch_getenv("PATH");
2197 if (p != NULL)
2198 {
2199 pathbuf = alloc(STRLEN(p) + 3);
2200 if (pathbuf == NULL)
2201 {
2202 retval = FALSE;
2203 goto theend;
2204 }
2205 STRCPY(pathbuf, ".;");
2206 STRCAT(pathbuf, p);
2207 }
2208 }
2209
2210 /*
2211 * Walk through all entries in $PATH to check if "name" exists there and
2212 * is an executable file.
2213 */
2214 p = (pathbuf != NULL) ? pathbuf : (char_u *)".";
2215 while (*p)
2216 {
2217 if (*p == ';') // Skip empty entry
2218 {
2219 ++p;
2220 continue;
2221 }
2222 e = vim_strchr(p, ';');
2223 if (e == NULL)
2224 e = p + STRLEN(p);
2225
2226 if (e - p + len + 2 > sizeof(buf))
2227 {
2228 retval = FALSE;
2229 goto theend;
2230 }
2231 // A single "." that means current dir.
2232 if (e - p == 1 && *p == '.')
2233 STRCPY(buf, name);
2234 else
2235 {
2236 vim_strncpy(buf, p, e - p);
2237 add_pathsep(buf);
2238 STRCAT(buf, name);
2239 }
2240 tmplen = STRLEN(buf);
2241
2242 /*
2243 * Loop over all extensions in $PATHEXT.
2244 * Check "name" with extension added.
2245 */
2246 p = pathext;
2247 while (*p)
2248 {
2249 if (*p == ';')
2250 {
2251 // Skip empty entry
2252 ++p;
2253 continue;
2254 }
2255 e2 = vim_strchr(p, (int)';');
2256 if (e2 == NULL)
2257 e2 = p + STRLEN(p);
2258
2259 if (!(p[0] == '.' && (p[1] == NUL || p[1] == ';')))
2260 {
2261 // Not a single "." that means no extension is added.
2262 if (e2 - p + tmplen + 1 > sizeof(buf))
2263 {
2264 retval = FALSE;
2265 goto theend;
2266 }
2267 vim_strncpy(buf + tmplen, p, e2 - p);
2268 }
2269 if (executable_file((char *)buf, path))
2270 {
2271 retval = TRUE;
2272 goto theend;
2273 }
2274
2275 p = e2;
2276 }
2277
2278 p = e;
2279 }
2280
2281theend:
2282 free(pathextbuf);
2283 free(pathbuf);
2284 return retval;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002285}
2286
Bram Moolenaar1eed5322019-02-26 17:03:54 +01002287#if (defined(__MINGW32__) && __MSVCRT_VERSION__ >= 0x800) || \
2288 (defined(_MSC_VER) && _MSC_VER >= 1400)
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002289/*
2290 * Bad parameter handler.
2291 *
2292 * Certain MS CRT functions will intentionally crash when passed invalid
2293 * parameters to highlight possible security holes. Setting this function as
2294 * the bad parameter handler will prevent the crash.
2295 *
2296 * In debug builds the parameters contain CRT information that might help track
2297 * down the source of a problem, but in non-debug builds the arguments are all
2298 * NULL/0. Debug builds will also produce assert dialogs from the CRT, it is
2299 * worth allowing these to make debugging of issues easier.
2300 */
2301 static void
2302bad_param_handler(const wchar_t *expression,
2303 const wchar_t *function,
2304 const wchar_t *file,
2305 unsigned int line,
2306 uintptr_t pReserved)
2307{
2308}
2309
2310# define SET_INVALID_PARAM_HANDLER \
2311 ((void)_set_invalid_parameter_handler(bad_param_handler))
2312#else
2313# define SET_INVALID_PARAM_HANDLER
2314#endif
2315
Bram Moolenaar4f974752019-02-17 17:44:42 +01002316#ifdef FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00002317
2318/*
2319 * GUI version of mch_init().
2320 */
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002321 static void
2322mch_init_g(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002323{
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002324# ifndef __MINGW32__
Bram Moolenaar071d4272004-06-13 20:20:40 +00002325 extern int _fmode;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002326# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002327
Bram Moolenaar0f873732019-12-05 20:28:46 +01002328 // Silently handle invalid parameters to CRT functions
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002329 SET_INVALID_PARAM_HANDLER;
2330
Bram Moolenaar0f873732019-12-05 20:28:46 +01002331 // Let critical errors result in a failure, not in a dialog box. Required
2332 // for the timestamp test to work on removed floppies.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002333 SetErrorMode(SEM_FAILCRITICALERRORS);
2334
Bram Moolenaar0f873732019-12-05 20:28:46 +01002335 _fmode = O_BINARY; // we do our own CR-LF translation
Bram Moolenaar071d4272004-06-13 20:20:40 +00002336
Bram Moolenaar0f873732019-12-05 20:28:46 +01002337 // Specify window size. Is there a place to get the default from?
Bram Moolenaar071d4272004-06-13 20:20:40 +00002338 Rows = 25;
2339 Columns = 80;
2340
Bram Moolenaar0f873732019-12-05 20:28:46 +01002341 // Look for 'vimrun'
Bram Moolenaar071d4272004-06-13 20:20:40 +00002342 {
2343 char_u vimrun_location[_MAX_PATH + 4];
2344
Bram Moolenaar0f873732019-12-05 20:28:46 +01002345 // First try in same directory as gvim.exe
Bram Moolenaar071d4272004-06-13 20:20:40 +00002346 STRCPY(vimrun_location, exe_name);
2347 STRCPY(gettail(vimrun_location), "vimrun.exe");
2348 if (mch_getperm(vimrun_location) >= 0)
2349 {
2350 if (*skiptowhite(vimrun_location) != NUL)
2351 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01002352 // Enclose path with white space in double quotes.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002353 mch_memmove(vimrun_location + 1, vimrun_location,
2354 STRLEN(vimrun_location) + 1);
2355 *vimrun_location = '"';
2356 STRCPY(gettail(vimrun_location), "vimrun\" ");
2357 }
2358 else
2359 STRCPY(gettail(vimrun_location), "vimrun ");
2360
2361 vimrun_path = (char *)vim_strsave(vimrun_location);
2362 s_dont_use_vimrun = FALSE;
2363 }
Bram Moolenaar95da1362020-05-30 18:37:55 +02002364 else if (executable_exists("vimrun.exe", NULL, TRUE, FALSE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002365 s_dont_use_vimrun = FALSE;
2366
Bram Moolenaar0f873732019-12-05 20:28:46 +01002367 // Don't give the warning for a missing vimrun.exe right now, but only
2368 // when vimrun was supposed to be used. Don't bother people that do
2369 // not need vimrun.exe.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002370 if (s_dont_use_vimrun)
2371 need_vimrun_warning = TRUE;
2372 }
2373
2374 /*
2375 * If "finstr.exe" doesn't exist, use "grep -n" for 'grepprg'.
2376 * Otherwise the default "findstr /n" is used.
2377 */
Bram Moolenaar95da1362020-05-30 18:37:55 +02002378 if (!executable_exists("findstr.exe", NULL, TRUE, FALSE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002379 set_option_value((char_u *)"grepprg", 0, (char_u *)"grep -n", 0);
2380
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002381# ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01002382 win_clip_init();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002383# endif
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01002384
2385 vtp_flag_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002386}
2387
2388
Bram Moolenaar0f873732019-12-05 20:28:46 +01002389#endif // FEAT_GUI_MSWIN
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002390
2391#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002392
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002393# define SRWIDTH(sr) ((sr).Right - (sr).Left + 1)
2394# define SRHEIGHT(sr) ((sr).Bottom - (sr).Top + 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002395
2396/*
2397 * ClearConsoleBuffer()
2398 * Description:
2399 * Clears the entire contents of the console screen buffer, using the
2400 * specified attribute.
2401 * Returns:
2402 * TRUE on success
2403 */
2404 static BOOL
2405ClearConsoleBuffer(WORD wAttribute)
2406{
2407 CONSOLE_SCREEN_BUFFER_INFO csbi;
2408 COORD coord;
2409 DWORD NumCells, dummy;
2410
2411 if (!GetConsoleScreenBufferInfo(g_hConOut, &csbi))
2412 return FALSE;
2413
2414 NumCells = csbi.dwSize.X * csbi.dwSize.Y;
2415 coord.X = 0;
2416 coord.Y = 0;
2417 if (!FillConsoleOutputCharacter(g_hConOut, ' ', NumCells,
2418 coord, &dummy))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002419 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002420 if (!FillConsoleOutputAttribute(g_hConOut, wAttribute, NumCells,
2421 coord, &dummy))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002422 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002423
2424 return TRUE;
2425}
2426
2427/*
2428 * FitConsoleWindow()
2429 * Description:
2430 * Checks if the console window will fit within given buffer dimensions.
2431 * Also, if requested, will shrink the window to fit.
2432 * Returns:
2433 * TRUE on success
2434 */
2435 static BOOL
2436FitConsoleWindow(
2437 COORD dwBufferSize,
2438 BOOL WantAdjust)
2439{
2440 CONSOLE_SCREEN_BUFFER_INFO csbi;
2441 COORD dwWindowSize;
2442 BOOL NeedAdjust = FALSE;
2443
2444 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
2445 {
2446 /*
2447 * A buffer resize will fail if the current console window does
2448 * not lie completely within that buffer. To avoid this, we might
2449 * have to move and possibly shrink the window.
2450 */
2451 if (csbi.srWindow.Right >= dwBufferSize.X)
2452 {
2453 dwWindowSize.X = SRWIDTH(csbi.srWindow);
2454 if (dwWindowSize.X > dwBufferSize.X)
2455 dwWindowSize.X = dwBufferSize.X;
2456 csbi.srWindow.Right = dwBufferSize.X - 1;
2457 csbi.srWindow.Left = dwBufferSize.X - dwWindowSize.X;
2458 NeedAdjust = TRUE;
2459 }
2460 if (csbi.srWindow.Bottom >= dwBufferSize.Y)
2461 {
2462 dwWindowSize.Y = SRHEIGHT(csbi.srWindow);
2463 if (dwWindowSize.Y > dwBufferSize.Y)
2464 dwWindowSize.Y = dwBufferSize.Y;
2465 csbi.srWindow.Bottom = dwBufferSize.Y - 1;
2466 csbi.srWindow.Top = dwBufferSize.Y - dwWindowSize.Y;
2467 NeedAdjust = TRUE;
2468 }
2469 if (NeedAdjust && WantAdjust)
2470 {
2471 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &csbi.srWindow))
2472 return FALSE;
2473 }
2474 return TRUE;
2475 }
2476
2477 return FALSE;
2478}
2479
2480typedef struct ConsoleBufferStruct
2481{
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002482 BOOL IsValid;
2483 CONSOLE_SCREEN_BUFFER_INFO Info;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002484 PCHAR_INFO Buffer;
2485 COORD BufferSize;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002486 PSMALL_RECT Regions;
2487 int NumRegions;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002488} ConsoleBuffer;
2489
2490/*
2491 * SaveConsoleBuffer()
2492 * Description:
2493 * Saves important information about the console buffer, including the
2494 * actual buffer contents. The saved information is suitable for later
2495 * restoration by RestoreConsoleBuffer().
2496 * Returns:
2497 * TRUE if all information was saved; FALSE otherwise
2498 * If FALSE, still sets cb->IsValid if buffer characteristics were saved.
2499 */
2500 static BOOL
2501SaveConsoleBuffer(
2502 ConsoleBuffer *cb)
2503{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002504 DWORD NumCells;
2505 COORD BufferCoord;
2506 SMALL_RECT ReadRegion;
2507 WORD Y, Y_incr;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002508 int i, numregions;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002509
Bram Moolenaar071d4272004-06-13 20:20:40 +00002510 if (cb == NULL)
2511 return FALSE;
2512
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002513 if (!GetConsoleScreenBufferInfo(g_hConOut, &cb->Info))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002514 {
2515 cb->IsValid = FALSE;
2516 return FALSE;
2517 }
2518 cb->IsValid = TRUE;
2519
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002520 /*
2521 * Allocate a buffer large enough to hold the entire console screen
2522 * buffer. If this ConsoleBuffer structure has already been initialized
2523 * with a buffer of the correct size, then just use that one.
2524 */
2525 if (!cb->IsValid || cb->Buffer == NULL ||
2526 cb->BufferSize.X != cb->Info.dwSize.X ||
2527 cb->BufferSize.Y != cb->Info.dwSize.Y)
2528 {
2529 cb->BufferSize.X = cb->Info.dwSize.X;
2530 cb->BufferSize.Y = cb->Info.dwSize.Y;
2531 NumCells = cb->BufferSize.X * cb->BufferSize.Y;
2532 vim_free(cb->Buffer);
Bram Moolenaarc799fe22019-05-28 23:08:19 +02002533 cb->Buffer = ALLOC_MULT(CHAR_INFO, NumCells);
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002534 if (cb->Buffer == NULL)
2535 return FALSE;
2536 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002537
2538 /*
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002539 * We will now copy the console screen buffer into our buffer.
2540 * ReadConsoleOutput() seems to be limited as far as how much you
2541 * can read at a time. Empirically, this number seems to be about
2542 * 12000 cells (rows * columns). Start at position (0, 0) and copy
2543 * in chunks until it is all copied. The chunks will all have the
2544 * same horizontal characteristics, so initialize them now. The
2545 * height of each chunk will be (12000 / width).
Bram Moolenaar071d4272004-06-13 20:20:40 +00002546 */
Bram Moolenaar61594242015-09-01 20:23:37 +02002547 BufferCoord.X = 0;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002548 ReadRegion.Left = 0;
2549 ReadRegion.Right = cb->Info.dwSize.X - 1;
2550 Y_incr = 12000 / cb->Info.dwSize.X;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002551
2552 numregions = (cb->Info.dwSize.Y + Y_incr - 1) / Y_incr;
2553 if (cb->Regions == NULL || numregions != cb->NumRegions)
2554 {
2555 cb->NumRegions = numregions;
2556 vim_free(cb->Regions);
Bram Moolenaarc799fe22019-05-28 23:08:19 +02002557 cb->Regions = ALLOC_MULT(SMALL_RECT, cb->NumRegions);
Bram Moolenaar444fda22017-08-11 20:37:00 +02002558 if (cb->Regions == NULL)
2559 {
Bram Moolenaard23a8232018-02-10 18:45:26 +01002560 VIM_CLEAR(cb->Buffer);
Bram Moolenaar444fda22017-08-11 20:37:00 +02002561 return FALSE;
2562 }
2563 }
2564
2565 for (i = 0, Y = 0; i < cb->NumRegions; i++, Y += Y_incr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002566 {
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002567 /*
2568 * Read into position (0, Y) in our buffer.
2569 */
2570 BufferCoord.Y = Y;
2571 /*
2572 * Read the region whose top left corner is (0, Y) and whose bottom
2573 * right corner is (width - 1, Y + Y_incr - 1). This should define
2574 * a region of size width by Y_incr. Don't worry if this region is
2575 * too large for the remaining buffer; it will be cropped.
2576 */
2577 ReadRegion.Top = Y;
2578 ReadRegion.Bottom = Y + Y_incr - 1;
Bram Moolenaar0f873732019-12-05 20:28:46 +01002579 if (!ReadConsoleOutputW(g_hConOut, // output handle
2580 cb->Buffer, // our buffer
2581 cb->BufferSize, // dimensions of our buffer
2582 BufferCoord, // offset in our buffer
2583 &ReadRegion)) // region to save
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002584 {
Bram Moolenaard23a8232018-02-10 18:45:26 +01002585 VIM_CLEAR(cb->Buffer);
2586 VIM_CLEAR(cb->Regions);
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002587 return FALSE;
2588 }
Bram Moolenaar444fda22017-08-11 20:37:00 +02002589 cb->Regions[i] = ReadRegion;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002590 }
2591
2592 return TRUE;
2593}
2594
2595/*
2596 * RestoreConsoleBuffer()
2597 * Description:
2598 * Restores important information about the console buffer, including the
2599 * actual buffer contents, if desired. The information to restore is in
2600 * the same format used by SaveConsoleBuffer().
2601 * Returns:
2602 * TRUE on success
2603 */
2604 static BOOL
2605RestoreConsoleBuffer(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002606 ConsoleBuffer *cb,
2607 BOOL RestoreScreen)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002608{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002609 COORD BufferCoord;
2610 SMALL_RECT WriteRegion;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002611 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002612
2613 if (cb == NULL || !cb->IsValid)
2614 return FALSE;
2615
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002616 /*
2617 * Before restoring the buffer contents, clear the current buffer, and
2618 * restore the cursor position and window information. Doing this now
2619 * prevents old buffer contents from "flashing" onto the screen.
2620 */
2621 if (RestoreScreen)
2622 ClearConsoleBuffer(cb->Info.wAttributes);
2623
2624 FitConsoleWindow(cb->Info.dwSize, TRUE);
2625 if (!SetConsoleScreenBufferSize(g_hConOut, cb->Info.dwSize))
2626 return FALSE;
2627 if (!SetConsoleTextAttribute(g_hConOut, cb->Info.wAttributes))
2628 return FALSE;
2629
2630 if (!RestoreScreen)
2631 {
2632 /*
2633 * No need to restore the screen buffer contents, so we're done.
2634 */
2635 return TRUE;
2636 }
2637
2638 if (!SetConsoleCursorPosition(g_hConOut, cb->Info.dwCursorPosition))
2639 return FALSE;
2640 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &cb->Info.srWindow))
2641 return FALSE;
2642
2643 /*
2644 * Restore the screen buffer contents.
2645 */
2646 if (cb->Buffer != NULL)
2647 {
Bram Moolenaar444fda22017-08-11 20:37:00 +02002648 for (i = 0; i < cb->NumRegions; i++)
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002649 {
Bram Moolenaar444fda22017-08-11 20:37:00 +02002650 BufferCoord.X = cb->Regions[i].Left;
2651 BufferCoord.Y = cb->Regions[i].Top;
2652 WriteRegion = cb->Regions[i];
Bram Moolenaar0f873732019-12-05 20:28:46 +01002653 if (!WriteConsoleOutputW(g_hConOut, // output handle
2654 cb->Buffer, // our buffer
2655 cb->BufferSize, // dimensions of our buffer
2656 BufferCoord, // offset in our buffer
2657 &WriteRegion)) // region to restore
Bram Moolenaar444fda22017-08-11 20:37:00 +02002658 return FALSE;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002659 }
2660 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002661
2662 return TRUE;
2663}
2664
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002665# define FEAT_RESTORE_ORIG_SCREEN
2666# ifdef FEAT_RESTORE_ORIG_SCREEN
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002667static ConsoleBuffer g_cbOrig = { 0 };
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002668# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002669static ConsoleBuffer g_cbNonTermcap = { 0 };
2670static ConsoleBuffer g_cbTermcap = { 0 };
2671
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002672# ifdef FEAT_TITLE
Bram Moolenaar071d4272004-06-13 20:20:40 +00002673char g_szOrigTitle[256] = { 0 };
Bram Moolenaar0f873732019-12-05 20:28:46 +01002674HWND g_hWnd = NULL; // also used in os_mswin.c
Bram Moolenaar071d4272004-06-13 20:20:40 +00002675static HICON g_hOrigIconSmall = NULL;
2676static HICON g_hOrigIcon = NULL;
2677static HICON g_hVimIcon = NULL;
2678static BOOL g_fCanChangeIcon = FALSE;
2679
Bram Moolenaar0f873732019-12-05 20:28:46 +01002680// ICON* are not defined in VC++ 4.0
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002681# ifndef ICON_SMALL
2682# define ICON_SMALL 0
2683# endif
2684# ifndef ICON_BIG
2685# define ICON_BIG 1
2686# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002687/*
2688 * GetConsoleIcon()
2689 * Description:
2690 * Attempts to retrieve the small icon and/or the big icon currently in
2691 * use by a given window.
2692 * Returns:
2693 * TRUE on success
2694 */
2695 static BOOL
2696GetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002697 HWND hWnd,
2698 HICON *phIconSmall,
2699 HICON *phIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002700{
2701 if (hWnd == NULL)
2702 return FALSE;
2703
2704 if (phIconSmall != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002705 *phIconSmall = (HICON)SendMessage(hWnd, WM_GETICON,
2706 (WPARAM)ICON_SMALL, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002707 if (phIcon != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002708 *phIcon = (HICON)SendMessage(hWnd, WM_GETICON,
2709 (WPARAM)ICON_BIG, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002710 return TRUE;
2711}
2712
2713/*
2714 * SetConsoleIcon()
2715 * Description:
2716 * Attempts to change the small icon and/or the big icon currently in
2717 * use by a given window.
2718 * Returns:
2719 * TRUE on success
2720 */
2721 static BOOL
2722SetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002723 HWND hWnd,
2724 HICON hIconSmall,
2725 HICON hIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002726{
Bram Moolenaar071d4272004-06-13 20:20:40 +00002727 if (hWnd == NULL)
2728 return FALSE;
2729
2730 if (hIconSmall != NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002731 SendMessage(hWnd, WM_SETICON,
2732 (WPARAM)ICON_SMALL, (LPARAM)hIconSmall);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002733 if (hIcon != NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002734 SendMessage(hWnd, WM_SETICON,
2735 (WPARAM)ICON_BIG, (LPARAM) hIcon);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002736 return TRUE;
2737}
2738
2739/*
2740 * SaveConsoleTitleAndIcon()
2741 * Description:
2742 * Saves the current console window title in g_szOrigTitle, for later
2743 * restoration. Also, attempts to obtain a handle to the console window,
2744 * and use it to save the small and big icons currently in use by the
2745 * console window. This is not always possible on some versions of Windows;
2746 * nor is it possible when running Vim remotely using Telnet (since the
2747 * console window the user sees is owned by a remote process).
2748 */
2749 static void
2750SaveConsoleTitleAndIcon(void)
2751{
Bram Moolenaar0f873732019-12-05 20:28:46 +01002752 // Save the original title.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002753 if (!GetConsoleTitle(g_szOrigTitle, sizeof(g_szOrigTitle)))
2754 return;
2755
2756 /*
2757 * Obtain a handle to the console window using GetConsoleWindow() from
2758 * KERNEL32.DLL; we need to handle in order to change the window icon.
2759 * This function only exists on NT-based Windows, starting with Windows
2760 * 2000. On older operating systems, we can't change the window icon
2761 * anyway.
2762 */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02002763 g_hWnd = GetConsoleWindow();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002764 if (g_hWnd == NULL)
2765 return;
2766
Bram Moolenaar0f873732019-12-05 20:28:46 +01002767 // Save the original console window icon.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002768 GetConsoleIcon(g_hWnd, &g_hOrigIconSmall, &g_hOrigIcon);
2769 if (g_hOrigIconSmall == NULL || g_hOrigIcon == NULL)
2770 return;
2771
Bram Moolenaar0f873732019-12-05 20:28:46 +01002772 // Extract the first icon contained in the Vim executable.
Bram Moolenaarcddc91c2014-09-23 21:53:41 +02002773 if (mch_icon_load((HANDLE *)&g_hVimIcon) == FAIL || g_hVimIcon == NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002774 g_hVimIcon = ExtractIcon(NULL, (LPCSTR)exe_name, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002775 if (g_hVimIcon != NULL)
2776 g_fCanChangeIcon = TRUE;
2777}
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002778# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002779
2780static int g_fWindInitCalled = FALSE;
2781static int g_fTermcapMode = FALSE;
2782static CONSOLE_CURSOR_INFO g_cci;
2783static DWORD g_cmodein = 0;
2784static DWORD g_cmodeout = 0;
2785
2786/*
2787 * non-GUI version of mch_init().
2788 */
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002789 static void
2790mch_init_c(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002791{
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002792# ifndef FEAT_RESTORE_ORIG_SCREEN
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002793 CONSOLE_SCREEN_BUFFER_INFO csbi;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002794# endif
2795# ifndef __MINGW32__
Bram Moolenaar071d4272004-06-13 20:20:40 +00002796 extern int _fmode;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002797# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002798
Bram Moolenaar0f873732019-12-05 20:28:46 +01002799 // Silently handle invalid parameters to CRT functions
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002800 SET_INVALID_PARAM_HANDLER;
2801
Bram Moolenaar0f873732019-12-05 20:28:46 +01002802 // Let critical errors result in a failure, not in a dialog box. Required
2803 // for the timestamp test to work on removed floppies.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002804 SetErrorMode(SEM_FAILCRITICALERRORS);
2805
Bram Moolenaar0f873732019-12-05 20:28:46 +01002806 _fmode = O_BINARY; // we do our own CR-LF translation
Bram Moolenaar071d4272004-06-13 20:20:40 +00002807 out_flush();
2808
Bram Moolenaar0f873732019-12-05 20:28:46 +01002809 // Obtain handles for the standard Console I/O devices
Bram Moolenaar071d4272004-06-13 20:20:40 +00002810 if (read_cmd_fd == 0)
2811 g_hConIn = GetStdHandle(STD_INPUT_HANDLE);
2812 else
2813 create_conin();
2814 g_hConOut = GetStdHandle(STD_OUTPUT_HANDLE);
2815
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002816# ifdef FEAT_RESTORE_ORIG_SCREEN
Bram Moolenaar0f873732019-12-05 20:28:46 +01002817 // Save the initial console buffer for later restoration
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002818 SaveConsoleBuffer(&g_cbOrig);
2819 g_attrCurrent = g_attrDefault = g_cbOrig.Info.wAttributes;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002820# else
Bram Moolenaar0f873732019-12-05 20:28:46 +01002821 // Get current text attributes
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002822 GetConsoleScreenBufferInfo(g_hConOut, &csbi);
2823 g_attrCurrent = g_attrDefault = csbi.wAttributes;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002824# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002825 if (cterm_normal_fg_color == 0)
2826 cterm_normal_fg_color = (g_attrCurrent & 0xf) + 1;
2827 if (cterm_normal_bg_color == 0)
2828 cterm_normal_bg_color = ((g_attrCurrent >> 4) & 0xf) + 1;
2829
Bram Moolenaarbdace832019-03-02 10:13:42 +01002830 // Fg and Bg color index number at startup
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02002831 g_color_index_fg = g_attrDefault & 0xf;
2832 g_color_index_bg = (g_attrDefault >> 4) & 0xf;
2833
Bram Moolenaar0f873732019-12-05 20:28:46 +01002834 // set termcap codes to current text attributes
Bram Moolenaar071d4272004-06-13 20:20:40 +00002835 update_tcap(g_attrCurrent);
2836
2837 GetConsoleCursorInfo(g_hConOut, &g_cci);
2838 GetConsoleMode(g_hConIn, &g_cmodein);
2839 GetConsoleMode(g_hConOut, &g_cmodeout);
2840
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002841# ifdef FEAT_TITLE
Bram Moolenaar071d4272004-06-13 20:20:40 +00002842 SaveConsoleTitleAndIcon();
2843 /*
2844 * Set both the small and big icons of the console window to Vim's icon.
2845 * Note that Vim presently only has one size of icon (32x32), but it
2846 * automatically gets scaled down to 16x16 when setting the small icon.
2847 */
2848 if (g_fCanChangeIcon)
2849 SetConsoleIcon(g_hWnd, g_hVimIcon, g_hVimIcon);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002850# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002851
2852 ui_get_shellsize();
2853
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002854# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00002855 fdDump = fopen("dump", "wt");
2856
2857 if (fdDump)
2858 {
2859 time_t t;
2860
2861 time(&t);
2862 fputs(ctime(&t), fdDump);
2863 fflush(fdDump);
2864 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002865# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002866
2867 g_fWindInitCalled = TRUE;
2868
Bram Moolenaar071d4272004-06-13 20:20:40 +00002869 g_fMouseAvail = GetSystemMetrics(SM_MOUSEPRESENT);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002870
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002871# ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01002872 win_clip_init();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002873# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01002874
Bram Moolenaar81ccbf12020-04-15 21:05:30 +02002875 vtp_flag_init();
Bram Moolenaarcafafb32018-02-22 21:07:09 +01002876 vtp_init();
Bram Moolenaar06b7b582020-05-30 17:49:25 +02002877 wt_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002878}
2879
2880/*
2881 * non-GUI version of mch_exit().
2882 * Shut down and exit with status `r'
2883 * Careful: mch_exit() may be called before mch_init()!
2884 */
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002885 static void
2886mch_exit_c(int r)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002887{
Bram Moolenaar955f1982017-02-05 15:10:51 +01002888 exiting = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002889
Bram Moolenaarcafafb32018-02-22 21:07:09 +01002890 vtp_exit();
2891
Bram Moolenaar955f1982017-02-05 15:10:51 +01002892 stoptermcap();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002893 if (g_fWindInitCalled)
2894 settmode(TMODE_COOK);
2895
Bram Moolenaar0f873732019-12-05 20:28:46 +01002896 ml_close_all(TRUE); // remove all memfiles
Bram Moolenaar071d4272004-06-13 20:20:40 +00002897
2898 if (g_fWindInitCalled)
2899 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002900# ifdef FEAT_TITLE
Bram Moolenaar40385db2018-08-07 22:31:44 +02002901 mch_restore_title(SAVE_RESTORE_BOTH);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002902 /*
2903 * Restore both the small and big icons of the console window to
2904 * what they were at startup. Don't do this when the window is
2905 * closed, Vim would hang here.
2906 */
2907 if (g_fCanChangeIcon && !g_fForceExit)
2908 SetConsoleIcon(g_hWnd, g_hOrigIconSmall, g_hOrigIcon);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002909# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002910
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002911# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00002912 if (fdDump)
2913 {
2914 time_t t;
2915
2916 time(&t);
2917 fputs(ctime(&t), fdDump);
2918 fclose(fdDump);
2919 }
2920 fdDump = NULL;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002921# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002922 }
2923
2924 SetConsoleCursorInfo(g_hConOut, &g_cci);
2925 SetConsoleMode(g_hConIn, g_cmodein);
2926 SetConsoleMode(g_hConOut, g_cmodeout);
2927
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002928# ifdef DYNAMIC_GETTEXT
Bram Moolenaar071d4272004-06-13 20:20:40 +00002929 dyn_libintl_end();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002930# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002931
2932 exit(r);
2933}
Bram Moolenaar0f873732019-12-05 20:28:46 +01002934#endif // !FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00002935
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002936 void
2937mch_init(void)
2938{
2939#ifdef VIMDLL
2940 if (gui.starting)
2941 mch_init_g();
2942 else
2943 mch_init_c();
2944#elif defined(FEAT_GUI_MSWIN)
2945 mch_init_g();
2946#else
2947 mch_init_c();
2948#endif
2949}
2950
2951 void
2952mch_exit(int r)
2953{
Bram Moolenaar173d8412020-04-19 14:02:26 +02002954#ifdef FEAT_NETBEANS_INTG
2955 netbeans_send_disconnect();
2956#endif
2957
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002958#ifdef VIMDLL
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02002959 if (gui.in_use || gui.starting)
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002960 mch_exit_g(r);
2961 else
2962 mch_exit_c(r);
2963#elif defined(FEAT_GUI_MSWIN)
2964 mch_exit_g(r);
2965#else
2966 mch_exit_c(r);
2967#endif
2968}
2969
Bram Moolenaar071d4272004-06-13 20:20:40 +00002970/*
2971 * Do we have an interactive window?
2972 */
2973 int
2974mch_check_win(
Bram Moolenaar1266d672017-02-01 13:43:36 +01002975 int argc UNUSED,
2976 char **argv UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002977{
2978 get_exe_name();
2979
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002980#if defined(FEAT_GUI_MSWIN) && !defined(VIMDLL)
Bram Moolenaar0f873732019-12-05 20:28:46 +01002981 return OK; // GUI always has a tty
Bram Moolenaar071d4272004-06-13 20:20:40 +00002982#else
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002983# ifdef VIMDLL
2984 if (gui.in_use)
2985 return OK;
2986# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002987 if (isatty(1))
2988 return OK;
2989 return FAIL;
2990#endif
2991}
2992
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002993/*
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01002994 * Set the case of the file name, if it already exists.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002995 * When "len" is > 0, also expand short to long filenames.
2996 */
2997 void
2998fname_case(
2999 char_u *name,
3000 int len)
3001{
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003002 int flen;
3003 WCHAR *p;
3004 WCHAR buf[_MAX_PATH + 1];
Bram Moolenaar071d4272004-06-13 20:20:40 +00003005
Bram Moolenaara3ffd9c2005-07-21 21:03:15 +00003006 flen = (int)STRLEN(name);
Bram Moolenaar65f04f62013-08-30 17:29:16 +02003007 if (flen == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003008 return;
3009
3010 slash_adjust(name);
3011
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003012 p = enc_to_utf16(name, NULL);
3013 if (p == NULL)
Bram Moolenaar65f04f62013-08-30 17:29:16 +02003014 return;
3015
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003016 if (GetLongPathNameW(p, buf, _MAX_PATH))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003017 {
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003018 char_u *q = utf16_to_enc(buf, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003019
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003020 if (q != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003021 {
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003022 if (len > 0 || flen >= (int)STRLEN(q))
3023 vim_strncpy(name, q, (len > 0) ? len - 1 : flen);
3024 vim_free(q);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003025 }
3026 }
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003027 vim_free(p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003028}
3029
3030
3031/*
3032 * Insert user name in s[len].
3033 */
3034 int
3035mch_get_user_name(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003036 char_u *s,
3037 int len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003038{
Bram Moolenaar0f873732019-12-05 20:28:46 +01003039 WCHAR wszUserName[256 + 1]; // UNLEN is 256
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003040 DWORD wcch = sizeof(wszUserName) / sizeof(WCHAR);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003041
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003042 if (GetUserNameW(wszUserName, &wcch))
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003043 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003044 char_u *p = utf16_to_enc(wszUserName, NULL);
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003045
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003046 if (p != NULL)
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003047 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003048 vim_strncpy(s, p, len - 1);
3049 vim_free(p);
3050 return OK;
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003051 }
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003052 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003053 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{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003066 WCHAR wszHostName[256 + 1];
3067 DWORD wcch = sizeof(wszHostName) / sizeof(WCHAR);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003068
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003069 if (GetComputerNameW(wszHostName, &wcch))
Bram Moolenaar2cc87382013-12-11 18:21:45 +01003070 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003071 char_u *p = utf16_to_enc(wszHostName, NULL);
Bram Moolenaar2cc87382013-12-11 18:21:45 +01003072
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003073 if (p != NULL)
Bram Moolenaar2cc87382013-12-11 18:21:45 +01003074 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003075 vim_strncpy(s, p, len - 1);
3076 vim_free(p);
3077 return;
Bram Moolenaar2cc87382013-12-11 18:21:45 +01003078 }
Bram Moolenaar2cc87382013-12-11 18:21:45 +01003079 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003080}
3081
3082
3083/*
3084 * return process ID
3085 */
3086 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003087mch_get_pid(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003088{
3089 return (long)GetCurrentProcessId();
3090}
3091
Bram Moolenaar67cf86b2019-04-28 22:25:38 +02003092/*
3093 * return TRUE if process "pid" is still running
3094 */
3095 int
Bram Moolenaar1b243ea2019-04-28 22:50:40 +02003096mch_process_running(long pid)
Bram Moolenaar67cf86b2019-04-28 22:25:38 +02003097{
3098 HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION, 0, (DWORD)pid);
3099 DWORD status = 0;
3100 int ret = FALSE;
3101
3102 if (hProcess == NULL)
3103 return FALSE; // might not have access
3104 if (GetExitCodeProcess(hProcess, &status) )
3105 ret = status == STILL_ACTIVE;
3106 CloseHandle(hProcess);
3107 return ret;
3108}
Bram Moolenaar071d4272004-06-13 20:20:40 +00003109
3110/*
3111 * Get name of current directory into buffer 'buf' of length 'len' bytes.
3112 * Return OK for success, FAIL for failure.
3113 */
3114 int
3115mch_dirname(
3116 char_u *buf,
3117 int len)
3118{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003119 WCHAR wbuf[_MAX_PATH + 1];
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02003120
Bram Moolenaar071d4272004-06-13 20:20:40 +00003121 /*
3122 * Originally this was:
3123 * return (getcwd(buf, len) != NULL ? OK : FAIL);
3124 * But the Win32s known bug list says that getcwd() doesn't work
3125 * so use the Win32 system call instead. <Negri>
3126 */
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003127 if (GetCurrentDirectoryW(_MAX_PATH, wbuf) != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003128 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003129 WCHAR wcbuf[_MAX_PATH + 1];
3130 char_u *p = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003131
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003132 if (GetLongPathNameW(wbuf, wcbuf, _MAX_PATH) != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003133 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003134 p = utf16_to_enc(wcbuf, NULL);
3135 if (STRLEN(p) >= (size_t)len)
Bram Moolenaarcea1f9e2018-08-19 14:38:42 +02003136 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003137 // long path name is too long, fall back to short one
Bram Moolenaar071d4272004-06-13 20:20:40 +00003138 vim_free(p);
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003139 p = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003140 }
3141 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003142 if (p == NULL)
3143 p = utf16_to_enc(wbuf, NULL);
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02003144
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003145 if (p != NULL)
3146 {
3147 vim_strncpy(buf, p, len - 1);
3148 vim_free(p);
3149 return OK;
3150 }
3151 }
3152 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003153}
3154
3155/*
Bram Moolenaarffa22202013-11-21 12:34:11 +01003156 * Get file permissions for "name".
3157 * Return mode_t or -1 for error.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003158 */
3159 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003160mch_getperm(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003161{
Bram Moolenaar8767f522016-07-01 17:17:39 +02003162 stat_T st;
Bram Moolenaarffa22202013-11-21 12:34:11 +01003163 int n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003164
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003165 n = mch_stat((char *)name, &st);
Bram Moolenaar78cf3f02014-01-10 18:16:07 +01003166 return n == 0 ? (long)(unsigned short)st.st_mode : -1L;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003167}
3168
3169
3170/*
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003171 * Set file permission for "name" to "perm".
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003172 *
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003173 * Return FAIL for failure, OK otherwise.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003174 */
3175 int
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003176mch_setperm(char_u *name, long perm)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003177{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003178 long n;
3179 WCHAR *p;
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003180
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003181 p = enc_to_utf16(name, NULL);
3182 if (p == NULL)
3183 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003184
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003185 n = _wchmod(p, perm);
3186 vim_free(p);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003187 if (n == -1)
3188 return FAIL;
3189
3190 win32_set_archive(name);
3191
3192 return OK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003193}
3194
3195/*
3196 * Set hidden flag for "name".
3197 */
3198 void
3199mch_hide(char_u *name)
3200{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003201 int attrs = win32_getattrs(name);
3202 if (attrs == -1)
3203 return;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003204
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003205 attrs |= FILE_ATTRIBUTE_HIDDEN;
3206 win32_setattrs(name, attrs);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003207}
3208
3209/*
Bram Moolenaar8a52ba72015-11-02 14:45:56 +01003210 * Return TRUE if file "name" exists and is hidden.
3211 */
3212 int
3213mch_ishidden(char_u *name)
3214{
3215 int f = win32_getattrs(name);
3216
3217 if (f == -1)
Bram Moolenaar0f873732019-12-05 20:28:46 +01003218 return FALSE; // file does not exist at all
Bram Moolenaar8a52ba72015-11-02 14:45:56 +01003219
3220 return (f & FILE_ATTRIBUTE_HIDDEN) != 0;
3221}
3222
3223/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003224 * return TRUE if "name" is a directory
3225 * return FALSE if "name" is not a directory or upon error
3226 */
3227 int
3228mch_isdir(char_u *name)
3229{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003230 int f = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003231
3232 if (f == -1)
Bram Moolenaar0f873732019-12-05 20:28:46 +01003233 return FALSE; // file does not exist at all
Bram Moolenaar071d4272004-06-13 20:20:40 +00003234
3235 return (f & FILE_ATTRIBUTE_DIRECTORY) != 0;
3236}
3237
3238/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01003239 * return TRUE if "name" is a directory, NOT a symlink to a directory
3240 * return FALSE if "name" is not a directory
3241 * return FALSE for error
3242 */
3243 int
3244mch_isrealdir(char_u *name)
3245{
3246 return mch_isdir(name) && !mch_is_symbolic_link(name);
3247}
3248
3249/*
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003250 * Create directory "name".
3251 * Return 0 on success, -1 on error.
3252 */
3253 int
3254mch_mkdir(char_u *name)
3255{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003256 WCHAR *p;
3257 int retval;
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003258
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003259 p = enc_to_utf16(name, NULL);
3260 if (p == NULL)
3261 return -1;
3262 retval = _wmkdir(p);
3263 vim_free(p);
3264 return retval;
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003265}
3266
3267/*
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003268 * Delete directory "name".
3269 * Return 0 on success, -1 on error.
3270 */
3271 int
3272mch_rmdir(char_u *name)
3273{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003274 WCHAR *p;
3275 int retval;
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003276
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003277 p = enc_to_utf16(name, NULL);
3278 if (p == NULL)
3279 return -1;
3280 retval = _wrmdir(p);
3281 vim_free(p);
3282 return retval;
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003283}
3284
3285/*
Bram Moolenaar03f48552006-02-28 23:52:23 +00003286 * Return TRUE if file "fname" has more than one link.
3287 */
3288 int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003289mch_is_hard_link(char_u *fname)
Bram Moolenaar03f48552006-02-28 23:52:23 +00003290{
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003291 BY_HANDLE_FILE_INFORMATION info;
3292
3293 return win32_fileinfo(fname, &info) == FILEINFO_OK
3294 && info.nNumberOfLinks > 1;
3295}
3296
3297/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01003298 * Return TRUE if "name" is a symbolic link (or a junction).
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003299 */
3300 int
Bram Moolenaar203258c2016-01-17 22:15:16 +01003301mch_is_symbolic_link(char_u *name)
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003302{
3303 HANDLE hFind;
3304 int res = FALSE;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003305 DWORD fileFlags = 0, reparseTag = 0;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003306 WCHAR *wn;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003307 WIN32_FIND_DATAW findDataW;
3308
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003309 wn = enc_to_utf16(name, NULL);
3310 if (wn == NULL)
3311 return FALSE;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003312
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003313 hFind = FindFirstFileW(wn, &findDataW);
3314 vim_free(wn);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003315 if (hFind != INVALID_HANDLE_VALUE)
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003316 {
3317 fileFlags = findDataW.dwFileAttributes;
3318 reparseTag = findDataW.dwReserved0;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003319 FindClose(hFind);
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003320 }
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003321
3322 if ((fileFlags & FILE_ATTRIBUTE_REPARSE_POINT)
Bram Moolenaar203258c2016-01-17 22:15:16 +01003323 && (reparseTag == IO_REPARSE_TAG_SYMLINK
3324 || reparseTag == IO_REPARSE_TAG_MOUNT_POINT))
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003325 res = TRUE;
3326
3327 return res;
3328}
3329
3330/*
3331 * Return TRUE if file "fname" has more than one link or if it is a symbolic
3332 * link.
3333 */
3334 int
3335mch_is_linked(char_u *fname)
3336{
3337 if (mch_is_hard_link(fname) || mch_is_symbolic_link(fname))
3338 return TRUE;
3339 return FALSE;
3340}
3341
3342/*
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003343 * Get the by-handle-file-information for "fname".
3344 * Returns FILEINFO_OK when OK.
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003345 * Returns FILEINFO_ENC_FAIL when enc_to_utf16() failed.
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003346 * Returns FILEINFO_READ_FAIL when CreateFile() failed.
3347 * Returns FILEINFO_INFO_FAIL when GetFileInformationByHandle() failed.
3348 */
3349 int
3350win32_fileinfo(char_u *fname, BY_HANDLE_FILE_INFORMATION *info)
3351{
Bram Moolenaar03f48552006-02-28 23:52:23 +00003352 HANDLE hFile;
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003353 int res = FILEINFO_READ_FAIL;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003354 WCHAR *wn;
Bram Moolenaar03f48552006-02-28 23:52:23 +00003355
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003356 wn = enc_to_utf16(fname, NULL);
3357 if (wn == NULL)
3358 return FILEINFO_ENC_FAIL;
3359
3360 hFile = CreateFileW(wn, // file name
3361 GENERIC_READ, // access mode
3362 FILE_SHARE_READ | FILE_SHARE_WRITE, // share mode
3363 NULL, // security descriptor
3364 OPEN_EXISTING, // creation disposition
3365 FILE_FLAG_BACKUP_SEMANTICS, // file attributes
3366 NULL); // handle to template file
3367 vim_free(wn);
Bram Moolenaar03f48552006-02-28 23:52:23 +00003368
3369 if (hFile != INVALID_HANDLE_VALUE)
3370 {
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003371 if (GetFileInformationByHandle(hFile, info) != 0)
3372 res = FILEINFO_OK;
3373 else
3374 res = FILEINFO_INFO_FAIL;
Bram Moolenaar03f48552006-02-28 23:52:23 +00003375 CloseHandle(hFile);
3376 }
3377
Bram Moolenaar03f48552006-02-28 23:52:23 +00003378 return res;
3379}
3380
3381/*
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003382 * get file attributes for `name'
3383 * -1 : error
3384 * else FILE_ATTRIBUTE_* defined in winnt.h
3385 */
Bram Moolenaarffa22202013-11-21 12:34:11 +01003386 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003387win32_getattrs(char_u *name)
3388{
3389 int attr;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003390 WCHAR *p;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003391
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003392 p = enc_to_utf16(name, NULL);
3393 if (p == NULL)
3394 return INVALID_FILE_ATTRIBUTES;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003395
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003396 attr = GetFileAttributesW(p);
3397 vim_free(p);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003398
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003399 return attr;
3400}
3401
3402/*
3403 * set file attributes for `name' to `attrs'
3404 *
3405 * return -1 for failure, 0 otherwise
3406 */
Bram Moolenaar6dff58f2018-09-30 21:43:26 +02003407 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003408win32_setattrs(char_u *name, int attrs)
3409{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003410 int res;
3411 WCHAR *p;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003412
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003413 p = enc_to_utf16(name, NULL);
3414 if (p == NULL)
3415 return -1;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003416
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003417 res = SetFileAttributesW(p, attrs);
3418 vim_free(p);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003419
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003420 return res ? 0 : -1;
3421}
3422
3423/*
3424 * Set archive flag for "name".
3425 */
Bram Moolenaar6dff58f2018-09-30 21:43:26 +02003426 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003427win32_set_archive(char_u *name)
3428{
3429 int attrs = win32_getattrs(name);
3430 if (attrs == -1)
3431 return -1;
3432
3433 attrs |= FILE_ATTRIBUTE_ARCHIVE;
3434 return win32_setattrs(name, attrs);
3435}
3436
3437/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003438 * Return TRUE if file or directory "name" is writable (not readonly).
3439 * Strange semantics of Win32: a readonly directory is writable, but you can't
3440 * delete a file. Let's say this means it is writable.
3441 */
3442 int
3443mch_writable(char_u *name)
3444{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003445 int attrs = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003446
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003447 return (attrs != -1 && (!(attrs & FILE_ATTRIBUTE_READONLY)
3448 || (attrs & FILE_ATTRIBUTE_DIRECTORY)));
Bram Moolenaar071d4272004-06-13 20:20:40 +00003449}
3450
Bram Moolenaar071d4272004-06-13 20:20:40 +00003451/*
Bram Moolenaar43663192017-03-05 14:29:12 +01003452 * Return TRUE if "name" can be executed, FALSE if not.
Bram Moolenaar77b77102015-03-21 22:18:41 +01003453 * If "use_path" is FALSE only check if "name" is executable.
Bram Moolenaar43663192017-03-05 14:29:12 +01003454 * When returning TRUE and "path" is not NULL save the path and set "*path" to
3455 * the allocated memory.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003456 */
3457 int
Bram Moolenaar77b77102015-03-21 22:18:41 +01003458mch_can_exe(char_u *name, char_u **path, int use_path)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003459{
Bram Moolenaar95da1362020-05-30 18:37:55 +02003460 return executable_exists((char *)name, path, TRUE, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003461}
Bram Moolenaar071d4272004-06-13 20:20:40 +00003462
3463/*
3464 * Check what "name" is:
3465 * NODE_NORMAL: file or directory (or doesn't exist)
3466 * NODE_WRITABLE: writable device, socket, fifo, etc.
3467 * NODE_OTHER: non-writable things
3468 */
3469 int
3470mch_nodetype(char_u *name)
3471{
3472 HANDLE hFile;
3473 int type;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003474 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003475
Bram Moolenaar0f873732019-12-05 20:28:46 +01003476 // We can't open a file with a name "\\.\con" or "\\.\prn" and trying to
3477 // read from it later will cause Vim to hang. Thus return NODE_WRITABLE
3478 // here.
Bram Moolenaar043545e2006-10-10 16:44:07 +00003479 if (STRNCMP(name, "\\\\.\\", 4) == 0)
3480 return NODE_WRITABLE;
3481
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003482 wn = enc_to_utf16(name, NULL);
3483 if (wn == NULL)
3484 return NODE_NORMAL;
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003485
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003486 hFile = CreateFileW(wn, // file name
3487 GENERIC_WRITE, // access mode
3488 0, // share mode
3489 NULL, // security descriptor
3490 OPEN_EXISTING, // creation disposition
3491 0, // file attributes
3492 NULL); // handle to template file
3493 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003494 if (hFile == INVALID_HANDLE_VALUE)
3495 return NODE_NORMAL;
3496
3497 type = GetFileType(hFile);
3498 CloseHandle(hFile);
3499 if (type == FILE_TYPE_CHAR)
3500 return NODE_WRITABLE;
3501 if (type == FILE_TYPE_DISK)
3502 return NODE_NORMAL;
3503 return NODE_OTHER;
3504}
3505
3506#ifdef HAVE_ACL
3507struct my_acl
3508{
3509 PSECURITY_DESCRIPTOR pSecurityDescriptor;
3510 PSID pSidOwner;
3511 PSID pSidGroup;
3512 PACL pDacl;
3513 PACL pSacl;
3514};
3515#endif
3516
3517/*
3518 * Return a pointer to the ACL of file "fname" in allocated memory.
3519 * Return NULL if the ACL is not available for whatever reason.
3520 */
3521 vim_acl_T
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003522mch_get_acl(char_u *fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003523{
3524#ifndef HAVE_ACL
3525 return (vim_acl_T)NULL;
3526#else
3527 struct my_acl *p = NULL;
Bram Moolenaar27515922013-06-29 15:36:26 +02003528 DWORD err;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003529
Bram Moolenaarc799fe22019-05-28 23:08:19 +02003530 p = ALLOC_CLEAR_ONE(struct my_acl);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003531 if (p != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003532 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003533 WCHAR *wn;
Bram Moolenaar27515922013-06-29 15:36:26 +02003534
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003535 wn = enc_to_utf16(fname, NULL);
3536 if (wn == NULL)
Bram Moolenaarbbf9f342020-11-10 22:03:40 +01003537 {
3538 vim_free(p);
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003539 return NULL;
Bram Moolenaarbbf9f342020-11-10 22:03:40 +01003540 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003541
3542 // Try to retrieve the entire security descriptor.
3543 err = GetNamedSecurityInfoW(
3544 wn, // Abstract filename
3545 SE_FILE_OBJECT, // File Object
3546 OWNER_SECURITY_INFORMATION |
3547 GROUP_SECURITY_INFORMATION |
3548 DACL_SECURITY_INFORMATION |
3549 SACL_SECURITY_INFORMATION,
3550 &p->pSidOwner, // Ownership information.
3551 &p->pSidGroup, // Group membership.
3552 &p->pDacl, // Discretionary information.
3553 &p->pSacl, // For auditing purposes.
3554 &p->pSecurityDescriptor);
3555 if (err == ERROR_ACCESS_DENIED ||
3556 err == ERROR_PRIVILEGE_NOT_HELD)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003557 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003558 // Retrieve only DACL.
3559 (void)GetNamedSecurityInfoW(
3560 wn,
3561 SE_FILE_OBJECT,
3562 DACL_SECURITY_INFORMATION,
3563 NULL,
3564 NULL,
3565 &p->pDacl,
3566 NULL,
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003567 &p->pSecurityDescriptor);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003568 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003569 if (p->pSecurityDescriptor == NULL)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003570 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003571 mch_free_acl((vim_acl_T)p);
3572 p = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003573 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003574 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003575 }
3576
3577 return (vim_acl_T)p;
3578#endif
3579}
3580
Bram Moolenaar27515922013-06-29 15:36:26 +02003581#ifdef HAVE_ACL
3582/*
3583 * Check if "acl" contains inherited ACE.
3584 */
3585 static BOOL
3586is_acl_inherited(PACL acl)
3587{
3588 DWORD i;
3589 ACL_SIZE_INFORMATION acl_info;
3590 PACCESS_ALLOWED_ACE ace;
3591
3592 acl_info.AceCount = 0;
3593 GetAclInformation(acl, &acl_info, sizeof(acl_info), AclSizeInformation);
3594 for (i = 0; i < acl_info.AceCount; i++)
3595 {
3596 GetAce(acl, i, (LPVOID *)&ace);
3597 if (ace->Header.AceFlags & INHERITED_ACE)
3598 return TRUE;
3599 }
3600 return FALSE;
3601}
3602#endif
3603
Bram Moolenaar071d4272004-06-13 20:20:40 +00003604/*
3605 * Set the ACL of file "fname" to "acl" (unless it's NULL).
3606 * Errors are ignored.
3607 * This must only be called with "acl" equal to what mch_get_acl() returned.
3608 */
3609 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003610mch_set_acl(char_u *fname, vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003611{
3612#ifdef HAVE_ACL
3613 struct my_acl *p = (struct my_acl *)acl;
Bram Moolenaar27515922013-06-29 15:36:26 +02003614 SECURITY_INFORMATION sec_info = 0;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003615 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003616
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003617 if (p == NULL)
3618 return;
3619
3620 wn = enc_to_utf16(fname, NULL);
3621 if (wn == NULL)
3622 return;
3623
3624 // Set security flags
3625 if (p->pSidOwner)
3626 sec_info |= OWNER_SECURITY_INFORMATION;
3627 if (p->pSidGroup)
3628 sec_info |= GROUP_SECURITY_INFORMATION;
3629 if (p->pDacl)
Bram Moolenaar27515922013-06-29 15:36:26 +02003630 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003631 sec_info |= DACL_SECURITY_INFORMATION;
3632 // Do not inherit its parent's DACL.
3633 // If the DACL is inherited, Cygwin permissions would be changed.
3634 if (!is_acl_inherited(p->pDacl))
3635 sec_info |= PROTECTED_DACL_SECURITY_INFORMATION;
Bram Moolenaar27515922013-06-29 15:36:26 +02003636 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003637 if (p->pSacl)
3638 sec_info |= SACL_SECURITY_INFORMATION;
3639
3640 (void)SetNamedSecurityInfoW(
3641 wn, // Abstract filename
3642 SE_FILE_OBJECT, // File Object
3643 sec_info,
3644 p->pSidOwner, // Ownership information.
3645 p->pSidGroup, // Group membership.
3646 p->pDacl, // Discretionary information.
3647 p->pSacl // For auditing purposes.
3648 );
3649 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003650#endif
3651}
3652
3653 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003654mch_free_acl(vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003655{
3656#ifdef HAVE_ACL
3657 struct my_acl *p = (struct my_acl *)acl;
3658
3659 if (p != NULL)
3660 {
3661 LocalFree(p->pSecurityDescriptor); // Free the memory just in case
3662 vim_free(p);
3663 }
3664#endif
3665}
3666
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003667#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003668
3669/*
3670 * handler for ctrl-break, ctrl-c interrupts, and fatal events.
3671 */
3672 static BOOL WINAPI
3673handler_routine(
3674 DWORD dwCtrlType)
3675{
Bram Moolenaar589b1102017-08-12 16:39:05 +02003676 INPUT_RECORD ir;
3677 DWORD out;
3678
Bram Moolenaar071d4272004-06-13 20:20:40 +00003679 switch (dwCtrlType)
3680 {
3681 case CTRL_C_EVENT:
3682 if (ctrl_c_interrupts)
3683 g_fCtrlCPressed = TRUE;
3684 return TRUE;
3685
3686 case CTRL_BREAK_EVENT:
3687 g_fCBrkPressed = TRUE;
Bram Moolenaar589b1102017-08-12 16:39:05 +02003688 ctrl_break_was_pressed = TRUE;
Bram Moolenaar0f873732019-12-05 20:28:46 +01003689 // ReadConsoleInput is blocking, send a key event to continue.
Bram Moolenaar589b1102017-08-12 16:39:05 +02003690 ir.EventType = KEY_EVENT;
3691 ir.Event.KeyEvent.bKeyDown = TRUE;
3692 ir.Event.KeyEvent.wRepeatCount = 1;
3693 ir.Event.KeyEvent.wVirtualKeyCode = VK_CANCEL;
3694 ir.Event.KeyEvent.wVirtualScanCode = 0;
3695 ir.Event.KeyEvent.dwControlKeyState = 0;
3696 ir.Event.KeyEvent.uChar.UnicodeChar = 0;
3697 WriteConsoleInput(g_hConIn, &ir, 1, &out);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003698 return TRUE;
3699
Bram Moolenaar0f873732019-12-05 20:28:46 +01003700 // fatal events: shut down gracefully
Bram Moolenaar071d4272004-06-13 20:20:40 +00003701 case CTRL_CLOSE_EVENT:
3702 case CTRL_LOGOFF_EVENT:
3703 case CTRL_SHUTDOWN_EVENT:
3704 windgoto((int)Rows - 1, 0);
3705 g_fForceExit = TRUE;
3706
Bram Moolenaar0fde2902008-03-16 13:54:13 +00003707 vim_snprintf((char *)IObuff, IOSIZE, _("Vim: Caught %s event\n"),
Bram Moolenaar071d4272004-06-13 20:20:40 +00003708 (dwCtrlType == CTRL_CLOSE_EVENT
3709 ? _("close")
3710 : dwCtrlType == CTRL_LOGOFF_EVENT
3711 ? _("logoff")
3712 : _("shutdown")));
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003713# ifdef DEBUG
Bram Moolenaar071d4272004-06-13 20:20:40 +00003714 OutputDebugString(IObuff);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003715# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003716
Bram Moolenaar0f873732019-12-05 20:28:46 +01003717 preserve_exit(); // output IObuff, preserve files and exit
Bram Moolenaar071d4272004-06-13 20:20:40 +00003718
Bram Moolenaar0f873732019-12-05 20:28:46 +01003719 return TRUE; // not reached
Bram Moolenaar071d4272004-06-13 20:20:40 +00003720
3721 default:
3722 return FALSE;
3723 }
3724}
3725
3726
3727/*
3728 * set the tty in (raw) ? "raw" : "cooked" mode
3729 */
3730 void
Bram Moolenaar26e86442020-05-17 14:06:16 +02003731mch_settmode(tmode_T tmode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003732{
3733 DWORD cmodein;
3734 DWORD cmodeout;
3735 BOOL bEnableHandler;
3736
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003737# ifdef VIMDLL
3738 if (gui.in_use)
3739 return;
3740# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003741 GetConsoleMode(g_hConIn, &cmodein);
3742 GetConsoleMode(g_hConOut, &cmodeout);
3743 if (tmode == TMODE_RAW)
3744 {
3745 cmodein &= ~(ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
3746 ENABLE_ECHO_INPUT);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003747 if (g_fMouseActive)
3748 cmodein |= ENABLE_MOUSE_INPUT;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01003749 cmodeout &= ~(
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003750# ifdef FEAT_TERMGUICOLORS
Bram Moolenaar0f873732019-12-05 20:28:46 +01003751 // Do not turn off the ENABLE_PROCESSED_OUTPUT flag when using
3752 // VTP.
Bram Moolenaarcafafb32018-02-22 21:07:09 +01003753 ((vtp_working) ? 0 : ENABLE_PROCESSED_OUTPUT) |
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003754# else
Bram Moolenaarcafafb32018-02-22 21:07:09 +01003755 ENABLE_PROCESSED_OUTPUT |
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003756# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01003757 ENABLE_WRAP_AT_EOL_OUTPUT);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003758 bEnableHandler = TRUE;
3759 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01003760 else // cooked
Bram Moolenaar071d4272004-06-13 20:20:40 +00003761 {
3762 cmodein |= (ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
3763 ENABLE_ECHO_INPUT);
3764 cmodeout |= (ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
3765 bEnableHandler = FALSE;
3766 }
3767 SetConsoleMode(g_hConIn, cmodein);
3768 SetConsoleMode(g_hConOut, cmodeout);
3769 SetConsoleCtrlHandler(handler_routine, bEnableHandler);
3770
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003771# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00003772 if (fdDump)
3773 {
3774 fprintf(fdDump, "mch_settmode(%s, in = %x, out = %x)\n",
3775 tmode == TMODE_RAW ? "raw" :
3776 tmode == TMODE_COOK ? "cooked" : "normal",
3777 cmodein, cmodeout);
3778 fflush(fdDump);
3779 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003780# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003781}
3782
3783
3784/*
3785 * Get the size of the current window in `Rows' and `Columns'
3786 * Return OK when size could be determined, FAIL otherwise.
3787 */
3788 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003789mch_get_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003790{
3791 CONSOLE_SCREEN_BUFFER_INFO csbi;
3792
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003793# ifdef VIMDLL
3794 if (gui.in_use)
3795 return OK;
3796# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003797 if (!g_fTermcapMode && g_cbTermcap.IsValid)
3798 {
3799 /*
3800 * For some reason, we are trying to get the screen dimensions
3801 * even though we are not in termcap mode. The 'Rows' and 'Columns'
3802 * variables are really intended to mean the size of Vim screen
3803 * while in termcap mode.
3804 */
3805 Rows = g_cbTermcap.Info.dwSize.Y;
3806 Columns = g_cbTermcap.Info.dwSize.X;
3807 }
3808 else if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3809 {
3810 Rows = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
3811 Columns = csbi.srWindow.Right - csbi.srWindow.Left + 1;
3812 }
3813 else
3814 {
3815 Rows = 25;
3816 Columns = 80;
3817 }
3818 return OK;
3819}
3820
3821/*
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02003822 * Resize console buffer to 'COORD'
3823 */
3824 static void
3825ResizeConBuf(
3826 HANDLE hConsole,
3827 COORD coordScreen)
3828{
3829 if (!SetConsoleScreenBufferSize(hConsole, coordScreen))
3830 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003831# ifdef MCH_WRITE_DUMP
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02003832 if (fdDump)
3833 {
3834 fprintf(fdDump, "SetConsoleScreenBufferSize failed: %lx\n",
3835 GetLastError());
3836 fflush(fdDump);
3837 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003838# endif
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02003839 }
3840}
3841
3842/*
3843 * Resize console window size to 'srWindowRect'
3844 */
3845 static void
3846ResizeWindow(
3847 HANDLE hConsole,
3848 SMALL_RECT srWindowRect)
3849{
3850 if (!SetConsoleWindowInfo(hConsole, TRUE, &srWindowRect))
3851 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003852# ifdef MCH_WRITE_DUMP
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02003853 if (fdDump)
3854 {
3855 fprintf(fdDump, "SetConsoleWindowInfo failed: %lx\n",
3856 GetLastError());
3857 fflush(fdDump);
3858 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003859# endif
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02003860 }
3861}
3862
3863/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003864 * Set a console window to `xSize' * `ySize'
3865 */
3866 static void
3867ResizeConBufAndWindow(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003868 HANDLE hConsole,
3869 int xSize,
3870 int ySize)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003871{
Bram Moolenaar0f873732019-12-05 20:28:46 +01003872 CONSOLE_SCREEN_BUFFER_INFO csbi; // hold current console buffer info
3873 SMALL_RECT srWindowRect; // hold the new console size
Bram Moolenaar071d4272004-06-13 20:20:40 +00003874 COORD coordScreen;
Bram Moolenaarf49a6922019-07-15 20:37:05 +02003875 COORD cursor;
Bram Moolenaar2551c032018-08-23 22:38:31 +02003876 static int resized = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003877
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003878# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00003879 if (fdDump)
3880 {
3881 fprintf(fdDump, "ResizeConBufAndWindow(%d, %d)\n", xSize, ySize);
3882 fflush(fdDump);
3883 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003884# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003885
Bram Moolenaar0f873732019-12-05 20:28:46 +01003886 // get the largest size we can size the console window to
Bram Moolenaar071d4272004-06-13 20:20:40 +00003887 coordScreen = GetLargestConsoleWindowSize(hConsole);
3888
Bram Moolenaar0f873732019-12-05 20:28:46 +01003889 // define the new console window size and scroll position
Bram Moolenaar071d4272004-06-13 20:20:40 +00003890 srWindowRect.Left = srWindowRect.Top = (SHORT) 0;
3891 srWindowRect.Right = (SHORT) (min(xSize, coordScreen.X) - 1);
3892 srWindowRect.Bottom = (SHORT) (min(ySize, coordScreen.Y) - 1);
3893
3894 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3895 {
3896 int sx, sy;
3897
3898 sx = csbi.srWindow.Right - csbi.srWindow.Left + 1;
3899 sy = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
3900 if (sy < ySize || sx < xSize)
3901 {
3902 /*
3903 * Increasing number of lines/columns, do buffer first.
3904 * Use the maximal size in x and y direction.
3905 */
3906 if (sy < ySize)
3907 coordScreen.Y = ySize;
3908 else
3909 coordScreen.Y = sy;
3910 if (sx < xSize)
3911 coordScreen.X = xSize;
3912 else
3913 coordScreen.X = sx;
3914 SetConsoleScreenBufferSize(hConsole, coordScreen);
3915 }
3916 }
3917
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02003918 // define the new console buffer size
Bram Moolenaar071d4272004-06-13 20:20:40 +00003919 coordScreen.X = xSize;
3920 coordScreen.Y = ySize;
3921
Bram Moolenaar2551c032018-08-23 22:38:31 +02003922 // In the new console call API, only the first time in reverse order
3923 if (!vtp_working || resized)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003924 {
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02003925 ResizeWindow(hConsole, srWindowRect);
3926 ResizeConBuf(hConsole, coordScreen);
3927 }
3928 else
3929 {
Bram Moolenaarf49a6922019-07-15 20:37:05 +02003930 // Workaround for a Windows 10 bug
3931 cursor.X = srWindowRect.Left;
3932 cursor.Y = srWindowRect.Top;
3933 SetConsoleCursorPosition(hConsole, cursor);
3934
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02003935 ResizeConBuf(hConsole, coordScreen);
3936 ResizeWindow(hConsole, srWindowRect);
Bram Moolenaar2551c032018-08-23 22:38:31 +02003937 resized = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003938 }
3939}
3940
3941
3942/*
3943 * Set the console window to `Rows' * `Columns'
3944 */
3945 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003946mch_set_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003947{
3948 COORD coordScreen;
3949
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003950# ifdef VIMDLL
3951 if (gui.in_use)
3952 return;
3953# endif
Bram Moolenaar0f873732019-12-05 20:28:46 +01003954 // Don't change window size while still starting up
Bram Moolenaar071d4272004-06-13 20:20:40 +00003955 if (suppress_winsize != 0)
3956 {
3957 suppress_winsize = 2;
3958 return;
3959 }
3960
3961 if (term_console)
3962 {
3963 coordScreen = GetLargestConsoleWindowSize(g_hConOut);
3964
Bram Moolenaar0f873732019-12-05 20:28:46 +01003965 // Clamp Rows and Columns to reasonable values
Bram Moolenaar071d4272004-06-13 20:20:40 +00003966 if (Rows > coordScreen.Y)
3967 Rows = coordScreen.Y;
3968 if (Columns > coordScreen.X)
3969 Columns = coordScreen.X;
3970
3971 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
3972 }
3973}
3974
3975/*
3976 * Rows and/or Columns has changed.
3977 */
3978 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003979mch_new_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003980{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003981# ifdef VIMDLL
3982 if (gui.in_use)
3983 return;
3984# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003985 set_scroll_region(0, 0, Columns - 1, Rows - 1);
3986}
3987
3988
3989/*
3990 * Called when started up, to set the winsize that was delayed.
3991 */
3992 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003993mch_set_winsize_now(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003994{
3995 if (suppress_winsize == 2)
3996 {
3997 suppress_winsize = 0;
3998 mch_set_shellsize();
3999 shell_resized();
4000 }
4001 suppress_winsize = 0;
4002}
Bram Moolenaar0f873732019-12-05 20:28:46 +01004003#endif // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00004004
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004005 static BOOL
4006vim_create_process(
Bram Moolenaar36c85b22013-12-12 20:25:44 +01004007 char *cmd,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004008 BOOL inherit_handles,
Bram Moolenaar3f1138e2014-01-05 13:29:26 +01004009 DWORD flags,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004010 STARTUPINFO *si,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004011 PROCESS_INFORMATION *pi,
4012 LPVOID *env,
4013 char *cwd)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004014{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004015 BOOL ret = FALSE;
4016 WCHAR *wcmd, *wcwd = NULL;
4017
4018 wcmd = enc_to_utf16((char_u *)cmd, NULL);
4019 if (wcmd == NULL)
4020 return FALSE;
4021 if (cwd != NULL)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004022 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004023 wcwd = enc_to_utf16((char_u *)cwd, NULL);
4024 if (wcwd == NULL)
4025 goto theend;
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004026 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004027
4028 ret = CreateProcessW(
4029 NULL, // Executable name
4030 wcmd, // Command to execute
4031 NULL, // Process security attributes
4032 NULL, // Thread security attributes
4033 inherit_handles, // Inherit handles
4034 flags, // Creation flags
4035 env, // Environment
4036 wcwd, // Current directory
4037 (LPSTARTUPINFOW)si, // Startup information
4038 pi); // Process information
4039theend:
4040 vim_free(wcmd);
4041 vim_free(wcwd);
4042 return ret;
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004043}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004044
4045
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004046 static HINSTANCE
4047vim_shell_execute(
4048 char *cmd,
4049 INT n_show_cmd)
4050{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004051 HINSTANCE ret;
4052 WCHAR *wcmd;
4053
4054 wcmd = enc_to_utf16((char_u *)cmd, NULL);
4055 if (wcmd == NULL)
4056 return (HINSTANCE) 0;
4057
4058 ret = ShellExecuteW(NULL, NULL, wcmd, NULL, NULL, n_show_cmd);
4059 vim_free(wcmd);
4060 return ret;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004061}
4062
4063
Bram Moolenaar4f974752019-02-17 17:44:42 +01004064#if defined(FEAT_GUI_MSWIN) || defined(PROTO)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004065
4066/*
4067 * Specialised version of system() for Win32 GUI mode.
4068 * This version proceeds as follows:
4069 * 1. Create a console window for use by the subprocess
4070 * 2. Run the subprocess (it gets the allocated console by default)
4071 * 3. Wait for the subprocess to terminate and get its exit code
4072 * 4. Prompt the user to press a key to close the console window
4073 */
4074 static int
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004075mch_system_classic(char *cmd, int options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004076{
4077 STARTUPINFO si;
4078 PROCESS_INFORMATION pi;
4079 DWORD ret = 0;
4080 HWND hwnd = GetFocus();
4081
4082 si.cb = sizeof(si);
4083 si.lpReserved = NULL;
4084 si.lpDesktop = NULL;
4085 si.lpTitle = NULL;
4086 si.dwFlags = STARTF_USESHOWWINDOW;
4087 /*
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004088 * It's nicer to run a filter command in a minimized window.
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01004089 * Don't activate the window to keep focus on Vim.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004090 */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004091 if (options & SHELL_DOOUT)
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01004092 si.wShowWindow = SW_SHOWMINNOACTIVE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004093 else
4094 si.wShowWindow = SW_SHOWNORMAL;
4095 si.cbReserved2 = 0;
4096 si.lpReserved2 = NULL;
4097
Bram Moolenaar0f873732019-12-05 20:28:46 +01004098 // Now, run the command
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004099 vim_create_process(cmd, FALSE,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004100 CREATE_DEFAULT_ERROR_MODE | CREATE_NEW_CONSOLE,
4101 &si, &pi, NULL, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004102
Bram Moolenaar0f873732019-12-05 20:28:46 +01004103 // Wait for the command to terminate before continuing
Bram Moolenaar071d4272004-06-13 20:20:40 +00004104 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004105# ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00004106 int delay = 1;
4107
Bram Moolenaar0f873732019-12-05 20:28:46 +01004108 // Keep updating the window while waiting for the shell to finish.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004109 for (;;)
4110 {
4111 MSG msg;
4112
Bram Moolenaar8c85fa32011-08-10 17:08:03 +02004113 if (pPeekMessage(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004114 {
4115 TranslateMessage(&msg);
Bram Moolenaar8c85fa32011-08-10 17:08:03 +02004116 pDispatchMessage(&msg);
Bram Moolenaare4195c52012-08-02 12:31:44 +02004117 delay = 1;
4118 continue;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004119 }
4120 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
4121 break;
4122
Bram Moolenaar0f873732019-12-05 20:28:46 +01004123 // We start waiting for a very short time and then increase it, so
4124 // that we respond quickly when the process is quick, and don't
4125 // consume too much overhead when it's slow.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004126 if (delay < 50)
4127 delay += 10;
4128 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004129# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004130 WaitForSingleObject(pi.hProcess, INFINITE);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004131# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004132
Bram Moolenaar0f873732019-12-05 20:28:46 +01004133 // Get the command exit code
Bram Moolenaar071d4272004-06-13 20:20:40 +00004134 GetExitCodeProcess(pi.hProcess, &ret);
4135 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004136
Bram Moolenaar0f873732019-12-05 20:28:46 +01004137 // Close the handles to the subprocess, so that it goes away
Bram Moolenaar071d4272004-06-13 20:20:40 +00004138 CloseHandle(pi.hThread);
4139 CloseHandle(pi.hProcess);
4140
Bram Moolenaar0f873732019-12-05 20:28:46 +01004141 // Try to get input focus back. Doesn't always work though.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004142 PostMessage(hwnd, WM_SETFOCUS, 0, 0);
4143
4144 return ret;
4145}
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004146
4147/*
4148 * Thread launched by the gui to send the current buffer data to the
4149 * process. This way avoid to hang up vim totally if the children
4150 * process take a long time to process the lines.
4151 */
Bram Moolenaar4c38d662016-08-03 20:54:57 +02004152 static unsigned int __stdcall
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004153sub_process_writer(LPVOID param)
4154{
4155 HANDLE g_hChildStd_IN_Wr = param;
4156 linenr_T lnum = curbuf->b_op_start.lnum;
4157 DWORD len = 0;
4158 DWORD l;
4159 char_u *lp = ml_get(lnum);
4160 char_u *s;
4161 int written = 0;
4162
4163 for (;;)
4164 {
4165 l = (DWORD)STRLEN(lp + written);
4166 if (l == 0)
4167 len = 0;
4168 else if (lp[written] == NL)
4169 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004170 // NL -> NUL translation
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004171 WriteFile(g_hChildStd_IN_Wr, "", 1, &len, NULL);
4172 }
4173 else
4174 {
4175 s = vim_strchr(lp + written, NL);
4176 WriteFile(g_hChildStd_IN_Wr, (char *)lp + written,
4177 s == NULL ? l : (DWORD)(s - (lp + written)),
4178 &len, NULL);
4179 }
4180 if (len == (int)l)
4181 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004182 // Finished a line, add a NL, unless this line should not have
4183 // one.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004184 if (lnum != curbuf->b_op_end.lnum
Bram Moolenaar34d72d42015-07-17 14:18:08 +02004185 || (!curbuf->b_p_bin
4186 && curbuf->b_p_fixeol)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004187 || (lnum != curbuf->b_no_eol_lnum
4188 && (lnum != curbuf->b_ml.ml_line_count
4189 || curbuf->b_p_eol)))
4190 {
Bram Moolenaar42335f52018-09-13 15:33:43 +02004191 WriteFile(g_hChildStd_IN_Wr, "\n", 1,
4192 (LPDWORD)&vim_ignored, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004193 }
4194
4195 ++lnum;
4196 if (lnum > curbuf->b_op_end.lnum)
4197 break;
4198
4199 lp = ml_get(lnum);
4200 written = 0;
4201 }
4202 else if (len > 0)
4203 written += len;
4204 }
4205
Bram Moolenaar0f873732019-12-05 20:28:46 +01004206 // finished all the lines, close pipe
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004207 CloseHandle(g_hChildStd_IN_Wr);
Bram Moolenaar86f2cd52016-08-02 21:55:17 +02004208 return 0;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004209}
4210
4211
Bram Moolenaar0f873732019-12-05 20:28:46 +01004212# define BUFLEN 100 // length for buffer, stolen from unix version
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004213
4214/*
4215 * This function read from the children's stdout and write the
4216 * data on screen or in the buffer accordingly.
4217 */
4218 static void
4219dump_pipe(int options,
4220 HANDLE g_hChildStd_OUT_Rd,
4221 garray_T *ga,
4222 char_u buffer[],
4223 DWORD *buffer_off)
4224{
4225 DWORD availableBytes = 0;
4226 DWORD i;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004227 int ret;
4228 DWORD len;
4229 DWORD toRead;
4230 int repeatCount;
4231
Bram Moolenaar0f873732019-12-05 20:28:46 +01004232 // we query the pipe to see if there is any data to read
4233 // to avoid to perform a blocking read
4234 ret = PeekNamedPipe(g_hChildStd_OUT_Rd, // pipe to query
4235 NULL, // optional buffer
4236 0, // buffer size
4237 NULL, // number of read bytes
4238 &availableBytes, // available bytes total
4239 NULL); // byteLeft
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004240
4241 repeatCount = 0;
Bram Moolenaar0f873732019-12-05 20:28:46 +01004242 // We got real data in the pipe, read it
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02004243 while (ret != 0 && availableBytes > 0)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004244 {
4245 repeatCount++;
Bram Moolenaara12a1612019-01-24 16:39:02 +01004246 toRead = (DWORD)(BUFLEN - *buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004247 toRead = availableBytes < toRead ? availableBytes : toRead;
Bram Moolenaara12a1612019-01-24 16:39:02 +01004248 ReadFile(g_hChildStd_OUT_Rd, buffer + *buffer_off, toRead , &len, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004249
Bram Moolenaar0f873732019-12-05 20:28:46 +01004250 // If we haven't read anything, there is a problem
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004251 if (len == 0)
4252 break;
4253
4254 availableBytes -= len;
4255
4256 if (options & SHELL_READ)
4257 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004258 // Do NUL -> NL translation, append NL separated
4259 // lines to the current buffer.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004260 for (i = 0; i < len; ++i)
4261 {
4262 if (buffer[i] == NL)
4263 append_ga_line(ga);
4264 else if (buffer[i] == NUL)
4265 ga_append(ga, NL);
4266 else
4267 ga_append(ga, buffer[i]);
4268 }
4269 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004270 else if (has_mbyte)
4271 {
4272 int l;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004273 int c;
4274 char_u *p;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004275
4276 len += *buffer_off;
4277 buffer[len] = NUL;
4278
Bram Moolenaar0f873732019-12-05 20:28:46 +01004279 // Check if the last character in buffer[] is
4280 // incomplete, keep these bytes for the next
4281 // round.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004282 for (p = buffer; p < buffer + len; p += l)
4283 {
Bram Moolenaard3c907b2016-08-17 21:32:09 +02004284 l = MB_CPTR2LEN(p);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004285 if (l == 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01004286 l = 1; // NUL byte?
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004287 else if (MB_BYTE2LEN(*p) != l)
4288 break;
4289 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01004290 if (p == buffer) // no complete character
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004291 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004292 // avoid getting stuck at an illegal byte
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004293 if (len >= 12)
4294 ++p;
4295 else
4296 {
4297 *buffer_off = len;
4298 return;
4299 }
4300 }
4301 c = *p;
4302 *p = NUL;
Bram Moolenaar32526b32019-01-19 17:43:09 +01004303 msg_puts((char *)buffer);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004304 if (p < buffer + len)
4305 {
4306 *p = c;
4307 *buffer_off = (DWORD)((buffer + len) - p);
4308 mch_memmove(buffer, p, *buffer_off);
4309 return;
4310 }
4311 *buffer_off = 0;
4312 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004313 else
4314 {
4315 buffer[len] = NUL;
Bram Moolenaar32526b32019-01-19 17:43:09 +01004316 msg_puts((char *)buffer);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004317 }
4318
4319 windgoto(msg_row, msg_col);
4320 cursor_on();
4321 out_flush();
4322 }
4323}
4324
4325/*
4326 * Version of system to use for windows NT > 5.0 (Win2K), use pipe
4327 * for communication and doesn't open any new window.
4328 */
4329 static int
4330mch_system_piped(char *cmd, int options)
4331{
4332 STARTUPINFO si;
4333 PROCESS_INFORMATION pi;
4334 DWORD ret = 0;
4335
4336 HANDLE g_hChildStd_IN_Rd = NULL;
4337 HANDLE g_hChildStd_IN_Wr = NULL;
4338 HANDLE g_hChildStd_OUT_Rd = NULL;
4339 HANDLE g_hChildStd_OUT_Wr = NULL;
4340
Bram Moolenaar0f873732019-12-05 20:28:46 +01004341 char_u buffer[BUFLEN + 1]; // reading buffer + size
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004342 DWORD len;
4343
Bram Moolenaar0f873732019-12-05 20:28:46 +01004344 // buffer used to receive keys
4345 char_u ta_buf[BUFLEN + 1]; // TypeAHead
4346 int ta_len = 0; // valid bytes in ta_buf[]
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004347
4348 DWORD i;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004349 int noread_cnt = 0;
4350 garray_T ga;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004351 int delay = 1;
Bram Moolenaar0f873732019-12-05 20:28:46 +01004352 DWORD buffer_off = 0; // valid bytes in buffer[]
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004353 char *p = NULL;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004354
4355 SECURITY_ATTRIBUTES saAttr;
4356
Bram Moolenaar0f873732019-12-05 20:28:46 +01004357 // Set the bInheritHandle flag so pipe handles are inherited.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004358 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
4359 saAttr.bInheritHandle = TRUE;
4360 saAttr.lpSecurityDescriptor = NULL;
4361
4362 if ( ! CreatePipe(&g_hChildStd_OUT_Rd, &g_hChildStd_OUT_Wr, &saAttr, 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01004363 // Ensure the read handle to the pipe for STDOUT is not inherited.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004364 || ! SetHandleInformation(g_hChildStd_OUT_Rd, HANDLE_FLAG_INHERIT, 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01004365 // Create a pipe for the child process's STDIN.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004366 || ! CreatePipe(&g_hChildStd_IN_Rd, &g_hChildStd_IN_Wr, &saAttr, 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01004367 // Ensure the write handle to the pipe for STDIN is not inherited.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004368 || ! SetHandleInformation(g_hChildStd_IN_Wr, HANDLE_FLAG_INHERIT, 0) )
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004369 {
4370 CloseHandle(g_hChildStd_IN_Rd);
4371 CloseHandle(g_hChildStd_IN_Wr);
4372 CloseHandle(g_hChildStd_OUT_Rd);
4373 CloseHandle(g_hChildStd_OUT_Wr);
Bram Moolenaar32526b32019-01-19 17:43:09 +01004374 msg_puts(_("\nCannot create pipes\n"));
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004375 }
4376
4377 si.cb = sizeof(si);
4378 si.lpReserved = NULL;
4379 si.lpDesktop = NULL;
4380 si.lpTitle = NULL;
4381 si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
4382
Bram Moolenaar0f873732019-12-05 20:28:46 +01004383 // set-up our file redirection
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004384 si.hStdError = g_hChildStd_OUT_Wr;
4385 si.hStdOutput = g_hChildStd_OUT_Wr;
4386 si.hStdInput = g_hChildStd_IN_Rd;
4387 si.wShowWindow = SW_HIDE;
4388 si.cbReserved2 = 0;
4389 si.lpReserved2 = NULL;
4390
4391 if (options & SHELL_READ)
4392 ga_init2(&ga, 1, BUFLEN);
4393
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004394 if (cmd != NULL)
4395 {
4396 p = (char *)vim_strsave((char_u *)cmd);
4397 if (p != NULL)
4398 unescape_shellxquote((char_u *)p, p_sxe);
4399 else
4400 p = cmd;
4401 }
4402
Bram Moolenaar0f873732019-12-05 20:28:46 +01004403 // Now, run the command.
4404 // About "Inherit handles" being TRUE: this command can be litigious,
4405 // handle inheritance was deactivated for pending temp file, but, if we
4406 // deactivate it, the pipes don't work for some reason.
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004407 vim_create_process(p, TRUE, CREATE_DEFAULT_ERROR_MODE,
4408 &si, &pi, NULL, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004409
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004410 if (p != cmd)
4411 vim_free(p);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004412
Bram Moolenaar0f873732019-12-05 20:28:46 +01004413 // Close our unused side of the pipes
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004414 CloseHandle(g_hChildStd_IN_Rd);
4415 CloseHandle(g_hChildStd_OUT_Wr);
4416
4417 if (options & SHELL_WRITE)
4418 {
Bram Moolenaar86f2cd52016-08-02 21:55:17 +02004419 HANDLE thread = (HANDLE)
Bram Moolenaar0f873732019-12-05 20:28:46 +01004420 _beginthreadex(NULL, // security attributes
4421 0, // default stack size
4422 sub_process_writer, // function to be executed
4423 g_hChildStd_IN_Wr, // parameter
4424 0, // creation flag, start immediately
4425 NULL); // we don't care about thread id
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004426 CloseHandle(thread);
4427 g_hChildStd_IN_Wr = NULL;
4428 }
4429
Bram Moolenaar0f873732019-12-05 20:28:46 +01004430 // Keep updating the window while waiting for the shell to finish.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004431 for (;;)
4432 {
4433 MSG msg;
4434
Bram Moolenaar175d0702013-12-11 18:36:33 +01004435 if (pPeekMessage(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004436 {
4437 TranslateMessage(&msg);
Bram Moolenaar175d0702013-12-11 18:36:33 +01004438 pDispatchMessage(&msg);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004439 }
4440
Bram Moolenaar0f873732019-12-05 20:28:46 +01004441 // write pipe information in the window
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004442 if ((options & (SHELL_READ|SHELL_WRITE))
4443# ifdef FEAT_GUI
4444 || gui.in_use
4445# endif
4446 )
4447 {
4448 len = 0;
4449 if (!(options & SHELL_EXPAND)
4450 && ((options &
4451 (SHELL_READ|SHELL_WRITE|SHELL_COOKED))
4452 != (SHELL_READ|SHELL_WRITE|SHELL_COOKED)
4453# ifdef FEAT_GUI
4454 || gui.in_use
4455# endif
4456 )
4457 && (ta_len > 0 || noread_cnt > 4))
4458 {
4459 if (ta_len == 0)
4460 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004461 // Get extra characters when we don't have any. Reset the
4462 // counter and timer.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004463 noread_cnt = 0;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004464 len = ui_inchar(ta_buf, BUFLEN, 10L, 0);
4465 }
4466 if (ta_len > 0 || len > 0)
4467 {
4468 /*
4469 * For pipes: Check for CTRL-C: send interrupt signal to
4470 * child. Check for CTRL-D: EOF, close pipe to child.
4471 */
4472 if (len == 1 && cmd != NULL)
4473 {
4474 if (ta_buf[ta_len] == Ctrl_C)
4475 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004476 // Learn what exit code is expected, for
4477 // now put 9 as SIGKILL
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004478 TerminateProcess(pi.hProcess, 9);
4479 }
4480 if (ta_buf[ta_len] == Ctrl_D)
4481 {
4482 CloseHandle(g_hChildStd_IN_Wr);
4483 g_hChildStd_IN_Wr = NULL;
4484 }
4485 }
4486
Bram Moolenaarf4140482020-02-15 23:06:45 +01004487 term_replace_bs_del_keycode(ta_buf, ta_len, len);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004488
4489 /*
4490 * For pipes: echo the typed characters. For a pty this
4491 * does not seem to work.
4492 */
4493 for (i = ta_len; i < ta_len + len; ++i)
4494 {
4495 if (ta_buf[i] == '\n' || ta_buf[i] == '\b')
4496 msg_putchar(ta_buf[i]);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004497 else if (has_mbyte)
4498 {
4499 int l = (*mb_ptr2len)(ta_buf + i);
4500
4501 msg_outtrans_len(ta_buf + i, l);
4502 i += l - 1;
4503 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004504 else
4505 msg_outtrans_len(ta_buf + i, 1);
4506 }
4507 windgoto(msg_row, msg_col);
4508 out_flush();
4509
4510 ta_len += len;
4511
4512 /*
4513 * Write the characters to the child, unless EOF has been
4514 * typed for pipes. Write one character at a time, to
4515 * avoid losing too much typeahead. When writing buffer
4516 * lines, drop the typed characters (only check for
4517 * CTRL-C).
4518 */
4519 if (options & SHELL_WRITE)
4520 ta_len = 0;
4521 else if (g_hChildStd_IN_Wr != NULL)
4522 {
4523 WriteFile(g_hChildStd_IN_Wr, (char*)ta_buf,
4524 1, &len, NULL);
4525 // if we are typing in, we want to keep things reactive
4526 delay = 1;
4527 if (len > 0)
4528 {
4529 ta_len -= len;
4530 mch_memmove(ta_buf, ta_buf + len, ta_len);
4531 }
4532 }
4533 }
4534 }
4535 }
4536
4537 if (ta_len)
4538 ui_inchar_undo(ta_buf, ta_len);
4539
4540 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
4541 {
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004542 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004543 break;
4544 }
4545
4546 ++noread_cnt;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004547 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004548
Bram Moolenaar0f873732019-12-05 20:28:46 +01004549 // We start waiting for a very short time and then increase it, so
4550 // that we respond quickly when the process is quick, and don't
4551 // consume too much overhead when it's slow.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004552 if (delay < 50)
4553 delay += 10;
4554 }
4555
Bram Moolenaar0f873732019-12-05 20:28:46 +01004556 // Close the pipe
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004557 CloseHandle(g_hChildStd_OUT_Rd);
4558 if (g_hChildStd_IN_Wr != NULL)
4559 CloseHandle(g_hChildStd_IN_Wr);
4560
4561 WaitForSingleObject(pi.hProcess, INFINITE);
4562
Bram Moolenaar0f873732019-12-05 20:28:46 +01004563 // Get the command exit code
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004564 GetExitCodeProcess(pi.hProcess, &ret);
4565
4566 if (options & SHELL_READ)
4567 {
4568 if (ga.ga_len > 0)
4569 {
4570 append_ga_line(&ga);
Bram Moolenaar0f873732019-12-05 20:28:46 +01004571 // remember that the NL was missing
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004572 curbuf->b_no_eol_lnum = curwin->w_cursor.lnum;
4573 }
4574 else
4575 curbuf->b_no_eol_lnum = 0;
4576 ga_clear(&ga);
4577 }
4578
Bram Moolenaar0f873732019-12-05 20:28:46 +01004579 // Close the handles to the subprocess, so that it goes away
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004580 CloseHandle(pi.hThread);
4581 CloseHandle(pi.hProcess);
4582
4583 return ret;
4584}
4585
4586 static int
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004587mch_system_g(char *cmd, int options)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004588{
Bram Moolenaar0f873732019-12-05 20:28:46 +01004589 // if we can pipe and the shelltemp option is off
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004590 if (!p_stmp)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004591 return mch_system_piped(cmd, options);
4592 else
4593 return mch_system_classic(cmd, options);
4594}
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004595#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004596
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004597#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004598 static int
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02004599mch_system_c(char *cmd, int options UNUSED)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004600{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004601 int ret;
4602 WCHAR *wcmd;
Bram Moolenaar2efc44b2019-10-05 12:09:32 +02004603 char_u *buf;
4604 size_t len;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004605
Bram Moolenaar2efc44b2019-10-05 12:09:32 +02004606 // If the command starts and ends with double quotes, enclose the command
4607 // in parentheses.
4608 len = STRLEN(cmd);
4609 if (len >= 2 && cmd[0] == '"' && cmd[len - 1] == '"')
4610 {
4611 len += 3;
4612 buf = alloc(len);
4613 if (buf == NULL)
4614 return -1;
4615 vim_snprintf((char *)buf, len, "(%s)", cmd);
4616 wcmd = enc_to_utf16(buf, NULL);
4617 free(buf);
4618 }
4619 else
4620 wcmd = enc_to_utf16((char_u *)cmd, NULL);
4621
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004622 if (wcmd == NULL)
4623 return -1;
4624
4625 ret = _wsystem(wcmd);
4626 vim_free(wcmd);
4627 return ret;
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004628}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004629
4630#endif
4631
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004632 static int
4633mch_system(char *cmd, int options)
4634{
4635#ifdef VIMDLL
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02004636 if (gui.in_use || gui.starting)
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004637 return mch_system_g(cmd, options);
4638 else
4639 return mch_system_c(cmd, options);
4640#elif defined(FEAT_GUI_MSWIN)
4641 return mch_system_g(cmd, options);
4642#else
4643 return mch_system_c(cmd, options);
4644#endif
4645}
4646
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004647#if defined(FEAT_GUI) && defined(FEAT_TERMINAL)
4648/*
4649 * Use a terminal window to run a shell command in.
4650 */
4651 static int
4652mch_call_shell_terminal(
4653 char_u *cmd,
Bram Moolenaar0f873732019-12-05 20:28:46 +01004654 int options UNUSED) // SHELL_*, see vim.h
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004655{
4656 jobopt_T opt;
4657 char_u *newcmd = NULL;
4658 typval_T argvar[2];
4659 long_u cmdlen;
4660 int retval = -1;
4661 buf_T *buf;
Bram Moolenaarf9c38832018-06-19 19:59:20 +02004662 job_T *job;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004663 aco_save_T aco;
Bram Moolenaar0f873732019-12-05 20:28:46 +01004664 oparg_T oa; // operator arguments
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004665
Bram Moolenaar42f652f2018-03-19 21:44:37 +01004666 if (cmd == NULL)
4667 cmdlen = STRLEN(p_sh) + 1;
4668 else
4669 cmdlen = STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10;
Bram Moolenaar18a4ba22019-05-24 19:39:03 +02004670 newcmd = alloc(cmdlen);
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004671 if (newcmd == NULL)
4672 return 255;
Bram Moolenaar42f652f2018-03-19 21:44:37 +01004673 if (cmd == NULL)
4674 {
4675 STRCPY(newcmd, p_sh);
4676 ch_log(NULL, "starting terminal to run a shell");
4677 }
4678 else
4679 {
4680 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s", p_sh, p_shcf, cmd);
4681 ch_log(NULL, "starting terminal for system command '%s'", cmd);
4682 }
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004683
4684 init_job_options(&opt);
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004685
4686 argvar[0].v_type = VAR_STRING;
4687 argvar[0].vval.v_string = newcmd;
4688 argvar[1].v_type = VAR_UNKNOWN;
4689 buf = term_start(argvar, NULL, &opt, TERM_START_SYSTEM);
Bram Moolenaar81c3c89a2018-03-20 11:41:44 +01004690 if (buf == NULL)
Bram Moolenaar9029b912019-03-21 19:58:00 +01004691 {
4692 vim_free(newcmd);
Bram Moolenaar81c3c89a2018-03-20 11:41:44 +01004693 return 255;
Bram Moolenaar9029b912019-03-21 19:58:00 +01004694 }
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004695
Bram Moolenaarf9c38832018-06-19 19:59:20 +02004696 job = term_getjob(buf->b_term);
4697 ++job->jv_refcount;
4698
Bram Moolenaar0f873732019-12-05 20:28:46 +01004699 // Find a window to make "buf" curbuf.
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004700 aucmd_prepbuf(&aco, buf);
4701
4702 clear_oparg(&oa);
4703 while (term_use_loop())
4704 {
4705 if (oa.op_type == OP_NOP && oa.regname == NUL && !VIsual_active)
4706 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004707 // If terminal_loop() returns OK we got a key that is handled
4708 // in Normal model. We don't do redrawing anyway.
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004709 if (terminal_loop(TRUE) == OK)
4710 normal_cmd(&oa, TRUE);
4711 }
4712 else
4713 normal_cmd(&oa, TRUE);
4714 }
Bram Moolenaarf9c38832018-06-19 19:59:20 +02004715 retval = job->jv_exitval;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004716 ch_log(NULL, "system command finished");
4717
Bram Moolenaarf9c38832018-06-19 19:59:20 +02004718 job_unref(job);
4719
Bram Moolenaar0f873732019-12-05 20:28:46 +01004720 // restore curwin/curbuf and a few other things
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004721 aucmd_restbuf(&aco);
4722
4723 wait_return(TRUE);
4724 do_buffer(DOBUF_WIPE, DOBUF_FIRST, FORWARD, buf->b_fnum, TRUE);
4725
4726 vim_free(newcmd);
4727 return retval;
4728}
4729#endif
4730
Bram Moolenaar071d4272004-06-13 20:20:40 +00004731/*
4732 * Either execute a command by calling the shell or start a new shell
4733 */
4734 int
4735mch_call_shell(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004736 char_u *cmd,
Bram Moolenaar0f873732019-12-05 20:28:46 +01004737 int options) // SHELL_*, see vim.h
Bram Moolenaar071d4272004-06-13 20:20:40 +00004738{
4739 int x = 0;
4740 int tmode = cur_tmode;
4741#ifdef FEAT_TITLE
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004742 WCHAR szShellTitle[512];
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004743
Bram Moolenaar0f873732019-12-05 20:28:46 +01004744 // Change the title to reflect that we are in a subshell.
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004745 if (GetConsoleTitleW(szShellTitle,
4746 sizeof(szShellTitle)/sizeof(WCHAR) - 4) > 0)
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004747 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004748 if (cmd == NULL)
4749 wcscat(szShellTitle, L" :sh");
4750 else
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004751 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004752 WCHAR *wn = enc_to_utf16((char_u *)cmd, NULL);
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004753
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004754 if (wn != NULL)
4755 {
4756 wcscat(szShellTitle, L" - !");
4757 if ((wcslen(szShellTitle) + wcslen(wn) <
4758 sizeof(szShellTitle)/sizeof(WCHAR)))
4759 wcscat(szShellTitle, wn);
4760 SetConsoleTitleW(szShellTitle);
4761 vim_free(wn);
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004762 }
4763 }
4764 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004765#endif
4766
4767 out_flush();
4768
4769#ifdef MCH_WRITE_DUMP
4770 if (fdDump)
4771 {
4772 fprintf(fdDump, "mch_call_shell(\"%s\", %d)\n", cmd, options);
4773 fflush(fdDump);
4774 }
4775#endif
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004776#if defined(FEAT_GUI) && defined(FEAT_TERMINAL)
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004777 // TODO: make the terminal window work with input or output redirected.
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004778 if (
4779# ifdef VIMDLL
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004780 gui.in_use &&
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004781# endif
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004782 vim_strchr(p_go, GO_TERMINAL) != NULL
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004783 && (options & (SHELL_FILTER|SHELL_DOOUT|SHELL_WRITE|SHELL_READ)) == 0)
4784 {
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004785 char_u *cmdbase = cmd;
4786
Bram Moolenaar4d5c1262019-09-20 17:20:02 +02004787 if (cmdbase != NULL)
4788 // Skip a leading quote and (.
4789 while (*cmdbase == '"' || *cmdbase == '(')
4790 ++cmdbase;
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004791
4792 // Check the command does not begin with "start "
Bram Moolenaar36e7a822019-11-13 21:49:24 +01004793 if (cmdbase == NULL || STRNICMP(cmdbase, "start", 5) != 0
4794 || !VIM_ISWHITE(cmdbase[5]))
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004795 {
4796 // Use a terminal window to run the command in.
4797 x = mch_call_shell_terminal(cmd, options);
Bram Moolenaarc4568ab2018-11-16 16:21:05 +01004798# ifdef FEAT_TITLE
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004799 resettitle();
Bram Moolenaarc4568ab2018-11-16 16:21:05 +01004800# endif
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004801 return x;
4802 }
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004803 }
4804#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004805
4806 /*
4807 * Catch all deadly signals while running the external command, because a
4808 * CTRL-C, Ctrl-Break or illegal instruction might otherwise kill us.
4809 */
4810 signal(SIGINT, SIG_IGN);
4811#if defined(__GNUC__) && !defined(__MINGW32__)
4812 signal(SIGKILL, SIG_IGN);
4813#else
4814 signal(SIGBREAK, SIG_IGN);
4815#endif
4816 signal(SIGILL, SIG_IGN);
4817 signal(SIGFPE, SIG_IGN);
4818 signal(SIGSEGV, SIG_IGN);
4819 signal(SIGTERM, SIG_IGN);
4820 signal(SIGABRT, SIG_IGN);
4821
4822 if (options & SHELL_COOKED)
Bram Moolenaar0f873732019-12-05 20:28:46 +01004823 settmode(TMODE_COOK); // set to normal mode
Bram Moolenaar071d4272004-06-13 20:20:40 +00004824
4825 if (cmd == NULL)
4826 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004827 x = mch_system((char *)p_sh, options);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004828 }
4829 else
4830 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004831 // we use "command" or "cmd" to start the shell; slow but easy
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004832 char_u *newcmd = NULL;
4833 char_u *cmdbase = cmd;
4834 long_u cmdlen;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004835
Bram Moolenaar0f873732019-12-05 20:28:46 +01004836 // Skip a leading ", ( and "(.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004837 if (*cmdbase == '"' )
4838 ++cmdbase;
4839 if (*cmdbase == '(')
4840 ++cmdbase;
4841
Bram Moolenaar1c465442017-03-12 20:10:05 +01004842 if ((STRNICMP(cmdbase, "start", 5) == 0) && VIM_ISWHITE(cmdbase[5]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004843 {
4844 STARTUPINFO si;
4845 PROCESS_INFORMATION pi;
4846 DWORD flags = CREATE_NEW_CONSOLE;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004847 INT n_show_cmd = SW_SHOWNORMAL;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004848 char_u *p;
4849
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01004850 ZeroMemory(&si, sizeof(si));
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004851 si.cb = sizeof(si);
4852 si.lpReserved = NULL;
4853 si.lpDesktop = NULL;
4854 si.lpTitle = NULL;
4855 si.dwFlags = 0;
4856 si.cbReserved2 = 0;
4857 si.lpReserved2 = NULL;
4858
4859 cmdbase = skipwhite(cmdbase + 5);
4860 if ((STRNICMP(cmdbase, "/min", 4) == 0)
Bram Moolenaar1c465442017-03-12 20:10:05 +01004861 && VIM_ISWHITE(cmdbase[4]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004862 {
4863 cmdbase = skipwhite(cmdbase + 4);
4864 si.dwFlags = STARTF_USESHOWWINDOW;
4865 si.wShowWindow = SW_SHOWMINNOACTIVE;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004866 n_show_cmd = SW_SHOWMINNOACTIVE;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004867 }
4868 else if ((STRNICMP(cmdbase, "/b", 2) == 0)
Bram Moolenaar1c465442017-03-12 20:10:05 +01004869 && VIM_ISWHITE(cmdbase[2]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004870 {
4871 cmdbase = skipwhite(cmdbase + 2);
4872 flags = CREATE_NO_WINDOW;
4873 si.dwFlags = STARTF_USESTDHANDLES;
4874 si.hStdInput = CreateFile("\\\\.\\NUL", // File name
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004875 GENERIC_READ, // Access flags
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004876 0, // Share flags
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004877 NULL, // Security att.
4878 OPEN_EXISTING, // Open flags
4879 FILE_ATTRIBUTE_NORMAL, // File att.
4880 NULL); // Temp file
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004881 si.hStdOutput = si.hStdInput;
4882 si.hStdError = si.hStdInput;
4883 }
4884
Bram Moolenaar0f873732019-12-05 20:28:46 +01004885 // Remove a trailing ", ) and )" if they have a match
4886 // at the start of the command.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004887 if (cmdbase > cmd)
4888 {
4889 p = cmdbase + STRLEN(cmdbase);
4890 if (p > cmdbase && p[-1] == '"' && *cmd == '"')
4891 *--p = NUL;
4892 if (p > cmdbase && p[-1] == ')'
4893 && (*cmd =='(' || cmd[1] == '('))
4894 *--p = NUL;
4895 }
4896
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004897 newcmd = cmdbase;
4898 unescape_shellxquote(cmdbase, p_sxe);
4899
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004900 /*
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004901 * If creating new console, arguments are passed to the
4902 * 'cmd.exe' as-is. If it's not, arguments are not treated
4903 * correctly for current 'cmd.exe'. So unescape characters in
4904 * shellxescape except '|' for avoiding to be treated as
4905 * argument to them. Pass the arguments to sub-shell.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004906 */
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004907 if (flags != CREATE_NEW_CONSOLE)
4908 {
4909 char_u *subcmd;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004910 char_u *cmd_shell = mch_getenv("COMSPEC");
4911
4912 if (cmd_shell == NULL || *cmd_shell == NUL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004913 cmd_shell = (char_u *)default_shell();
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004914
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004915 subcmd = vim_strsave_escaped_ext(cmdbase,
4916 (char_u *)"|", '^', FALSE);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004917 if (subcmd != NULL)
4918 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004919 // make "cmd.exe /c arguments"
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004920 cmdlen = STRLEN(cmd_shell) + STRLEN(subcmd) + 5;
Bram Moolenaar18a4ba22019-05-24 19:39:03 +02004921 newcmd = alloc(cmdlen);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004922 if (newcmd != NULL)
4923 vim_snprintf((char *)newcmd, cmdlen, "%s /c %s",
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004924 cmd_shell, subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004925 else
4926 newcmd = cmdbase;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004927 vim_free(subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004928 }
4929 }
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004930
4931 /*
4932 * Now, start the command as a process, so that it doesn't
4933 * inherit our handles which causes unpleasant dangling swap
4934 * files if we exit before the spawned process
4935 */
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004936 if (vim_create_process((char *)newcmd, FALSE, flags,
4937 &si, &pi, NULL, NULL))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004938 x = 0;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004939 else if (vim_shell_execute((char *)newcmd, n_show_cmd)
4940 > (HINSTANCE)32)
4941 x = 0;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004942 else
4943 {
4944 x = -1;
Bram Moolenaar4f974752019-02-17 17:44:42 +01004945#ifdef FEAT_GUI_MSWIN
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004946# ifdef VIMDLL
4947 if (gui.in_use)
4948# endif
4949 emsg(_("E371: Command not found"));
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004950#endif
4951 }
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004952
4953 if (newcmd != cmdbase)
4954 vim_free(newcmd);
4955
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01004956 if (si.dwFlags == STARTF_USESTDHANDLES && si.hStdInput != NULL)
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004957 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004958 // Close the handle to \\.\NUL created above.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004959 CloseHandle(si.hStdInput);
4960 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01004961 // Close the handles to the subprocess, so that it goes away
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004962 CloseHandle(pi.hThread);
4963 CloseHandle(pi.hProcess);
4964 }
4965 else
4966 {
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02004967 cmdlen =
Bram Moolenaar4f974752019-02-17 17:44:42 +01004968#ifdef FEAT_GUI_MSWIN
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02004969 ((gui.in_use || gui.starting) ?
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02004970 (!s_dont_use_vimrun && p_stmp ?
4971 STRLEN(vimrun_path) : STRLEN(p_sh) + STRLEN(p_shcf))
4972 : 0) +
Bram Moolenaar071d4272004-06-13 20:20:40 +00004973#endif
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02004974 STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10;
Bram Moolenaar0fde2902008-03-16 13:54:13 +00004975
Bram Moolenaar18a4ba22019-05-24 19:39:03 +02004976 newcmd = alloc(cmdlen);
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004977 if (newcmd != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004978 {
Bram Moolenaar4f974752019-02-17 17:44:42 +01004979#if defined(FEAT_GUI_MSWIN)
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004980 if (
4981# ifdef VIMDLL
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02004982 (gui.in_use || gui.starting) &&
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004983# endif
4984 need_vimrun_warning)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004985 {
Bram Moolenaar63e43442016-11-19 17:28:44 +01004986 char *msg = _("VIMRUN.EXE not found in your $PATH.\n"
4987 "External commands will not pause after completion.\n"
4988 "See :help win32-vimrun for more information.");
4989 char *title = _("Vim Warning");
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004990 WCHAR *wmsg = enc_to_utf16((char_u *)msg, NULL);
4991 WCHAR *wtitle = enc_to_utf16((char_u *)title, NULL);
Bram Moolenaar63e43442016-11-19 17:28:44 +01004992
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004993 if (wmsg != NULL && wtitle != NULL)
4994 MessageBoxW(NULL, wmsg, wtitle, MB_ICONWARNING);
4995 vim_free(wmsg);
4996 vim_free(wtitle);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004997 need_vimrun_warning = FALSE;
4998 }
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004999 if (
5000# ifdef VIMDLL
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02005001 (gui.in_use || gui.starting) &&
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005002# endif
5003 !s_dont_use_vimrun && p_stmp)
Bram Moolenaarfcc4d922019-05-24 13:32:36 +02005004 // Use vimrun to execute the command. It opens a console
5005 // window, which can be closed without killing Vim.
Bram Moolenaarcc448b32010-07-14 16:52:17 +02005006 vim_snprintf((char *)newcmd, cmdlen, "%s%s%s %s %s",
Bram Moolenaar071d4272004-06-13 20:20:40 +00005007 vimrun_path,
5008 (msg_silent != 0 || (options & SHELL_DOOUT))
5009 ? "-s " : "",
5010 p_sh, p_shcf, cmd);
Bram Moolenaarfcc4d922019-05-24 13:32:36 +02005011 else if (
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005012# ifdef VIMDLL
Bram Moolenaarfcc4d922019-05-24 13:32:36 +02005013 (gui.in_use || gui.starting) &&
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005014# endif
Bram Moolenaar0e6bfb92019-07-31 20:53:56 +02005015 s_dont_use_vimrun && STRCMP(p_shcf, "/c") == 0)
Bram Moolenaarfcc4d922019-05-24 13:32:36 +02005016 // workaround for the case that "vimrun" does not exist
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005017 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s %s %s",
5018 p_sh, p_shcf, p_sh, p_shcf, cmd);
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005019 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00005020#endif
Bram Moolenaarcc448b32010-07-14 16:52:17 +02005021 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s",
Bram Moolenaar0fde2902008-03-16 13:54:13 +00005022 p_sh, p_shcf, cmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005023 x = mch_system((char *)newcmd, options);
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005024 vim_free(newcmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005025 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005026 }
5027 }
5028
5029 if (tmode == TMODE_RAW)
Bram Moolenaar3b1f18f2020-05-16 23:15:08 +02005030 {
5031 // The shell may have messed with the mode, always set it.
5032 cur_tmode = TMODE_UNKNOWN;
Bram Moolenaar0f873732019-12-05 20:28:46 +01005033 settmode(TMODE_RAW); // set to raw mode
Bram Moolenaar3b1f18f2020-05-16 23:15:08 +02005034 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005035
Bram Moolenaar0f873732019-12-05 20:28:46 +01005036 // Print the return value, unless "vimrun" was used.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005037 if (x != 0 && !(options & SHELL_SILENT) && !emsg_silent
Bram Moolenaar4f974752019-02-17 17:44:42 +01005038#if defined(FEAT_GUI_MSWIN)
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02005039 && ((gui.in_use || gui.starting) ?
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005040 ((options & SHELL_DOOUT) || s_dont_use_vimrun || !p_stmp) : 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005041#endif
5042 )
5043 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005044 smsg(_("shell returned %d"), x);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005045 msg_putchar('\n');
5046 }
5047#ifdef FEAT_TITLE
5048 resettitle();
5049#endif
5050
5051 signal(SIGINT, SIG_DFL);
5052#if defined(__GNUC__) && !defined(__MINGW32__)
5053 signal(SIGKILL, SIG_DFL);
5054#else
5055 signal(SIGBREAK, SIG_DFL);
5056#endif
5057 signal(SIGILL, SIG_DFL);
5058 signal(SIGFPE, SIG_DFL);
5059 signal(SIGSEGV, SIG_DFL);
5060 signal(SIGTERM, SIG_DFL);
5061 signal(SIGABRT, SIG_DFL);
5062
5063 return x;
5064}
5065
Bram Moolenaar509ce2a2016-03-11 22:52:15 +01005066#if defined(FEAT_JOB_CHANNEL) || defined(PROTO)
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005067 static HANDLE
5068job_io_file_open(
Bram Moolenaar972c3b82017-01-12 21:44:49 +01005069 char_u *fname,
5070 DWORD dwDesiredAccess,
5071 DWORD dwShareMode,
5072 LPSECURITY_ATTRIBUTES lpSecurityAttributes,
5073 DWORD dwCreationDisposition,
5074 DWORD dwFlagsAndAttributes)
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005075{
5076 HANDLE h;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005077 WCHAR *wn;
Bram Moolenaara12a1612019-01-24 16:39:02 +01005078
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005079 wn = enc_to_utf16(fname, NULL);
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005080 if (wn == NULL)
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005081 return INVALID_HANDLE_VALUE;
5082
5083 h = CreateFileW(wn, dwDesiredAccess, dwShareMode,
5084 lpSecurityAttributes, dwCreationDisposition,
5085 dwFlagsAndAttributes, NULL);
5086 vim_free(wn);
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005087 return h;
5088}
5089
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005090/*
5091 * Turn the dictionary "env" into a NUL separated list that can be used as the
5092 * environment argument of vim_create_process().
5093 */
Bram Moolenaarba6febd2017-10-30 21:56:23 +01005094 void
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005095win32_build_env(dict_T *env, garray_T *gap, int is_terminal)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005096{
5097 hashitem_T *hi;
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005098 long_u todo = env != NULL ? env->dv_hashtab.ht_used : 0;
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005099 LPVOID base = GetEnvironmentStringsW();
5100
Bram Moolenaar0f873732019-12-05 20:28:46 +01005101 // for last \0
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005102 if (ga_grow(gap, 1) == FAIL)
5103 return;
5104
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005105 if (env != NULL)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005106 {
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005107 for (hi = env->dv_hashtab.ht_array; todo > 0; ++hi)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005108 {
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005109 if (!HASHITEM_EMPTY(hi))
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005110 {
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005111 typval_T *item = &dict_lookup(hi)->di_tv;
5112 WCHAR *wkey = enc_to_utf16((char_u *)hi->hi_key, NULL);
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005113 WCHAR *wval = enc_to_utf16(tv_get_string(item), NULL);
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005114 --todo;
5115 if (wkey != NULL && wval != NULL)
5116 {
5117 size_t n;
5118 size_t lkey = wcslen(wkey);
5119 size_t lval = wcslen(wval);
Bram Moolenaar60104f12017-08-14 23:25:04 +02005120
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005121 if (ga_grow(gap, (int)(lkey + lval + 2)) != OK)
5122 continue;
5123 for (n = 0; n < lkey; n++)
5124 *((WCHAR*)gap->ga_data + gap->ga_len++) = wkey[n];
5125 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'=';
5126 for (n = 0; n < lval; n++)
5127 *((WCHAR*)gap->ga_data + gap->ga_len++) = wval[n];
5128 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5129 }
Bram Moolenaarbdace832019-03-02 10:13:42 +01005130 vim_free(wkey);
5131 vim_free(wval);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005132 }
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005133 }
5134 }
5135
Bram Moolenaar355757a2020-02-10 22:06:32 +01005136 if (base)
5137 {
5138 WCHAR *p = (WCHAR*) base;
5139
5140 // for last \0
5141 if (ga_grow(gap, 1) == FAIL)
5142 return;
5143
5144 while (*p != 0 || *(p + 1) != 0)
5145 {
5146 if (ga_grow(gap, 1) == OK)
5147 *((WCHAR*)gap->ga_data + gap->ga_len++) = *p;
5148 p++;
5149 }
5150 FreeEnvironmentStrings(base);
5151 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5152 }
5153
Bram Moolenaar493359e2018-06-12 20:25:52 +02005154# if defined(FEAT_CLIENTSERVER) || defined(FEAT_TERMINAL)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005155 {
Bram Moolenaar493359e2018-06-12 20:25:52 +02005156# ifdef FEAT_CLIENTSERVER
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005157 char_u *servername = get_vim_var_str(VV_SEND_SERVER);
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005158 size_t servername_len = STRLEN(servername);
Bram Moolenaar493359e2018-06-12 20:25:52 +02005159# endif
5160# ifdef FEAT_TERMINAL
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005161 char_u *version = get_vim_var_str(VV_VERSION);
5162 size_t version_len = STRLEN(version);
Bram Moolenaar493359e2018-06-12 20:25:52 +02005163# endif
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005164 // size of "VIM_SERVERNAME=" and value,
5165 // plus "VIM_TERMINAL=" and value,
5166 // plus two terminating NULs
5167 size_t n = 0
Bram Moolenaar493359e2018-06-12 20:25:52 +02005168# ifdef FEAT_CLIENTSERVER
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005169 + 15 + servername_len
Bram Moolenaar493359e2018-06-12 20:25:52 +02005170# endif
5171# ifdef FEAT_TERMINAL
5172 + 13 + version_len + 2
5173# endif
5174 ;
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005175
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005176 if (ga_grow(gap, (int)n) == OK)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005177 {
Bram Moolenaar493359e2018-06-12 20:25:52 +02005178# ifdef FEAT_CLIENTSERVER
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005179 for (n = 0; n < 15; n++)
5180 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5181 (WCHAR)"VIM_SERVERNAME="[n];
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005182 for (n = 0; n < servername_len; n++)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005183 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5184 (WCHAR)servername[n];
5185 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
Bram Moolenaar493359e2018-06-12 20:25:52 +02005186# endif
5187# ifdef FEAT_TERMINAL
5188 if (is_terminal)
5189 {
5190 for (n = 0; n < 13; n++)
5191 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5192 (WCHAR)"VIM_TERMINAL="[n];
5193 for (n = 0; n < version_len; n++)
5194 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5195 (WCHAR)version[n];
5196 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5197 }
5198# endif
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005199 }
5200 }
Bram Moolenaar79c6b512018-06-12 21:11:12 +02005201# endif
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005202}
5203
Bram Moolenaarb091f302019-01-19 14:37:00 +01005204/*
5205 * Create a pair of pipes.
5206 * Return TRUE for success, FALSE for failure.
5207 */
5208 static BOOL
5209create_pipe_pair(HANDLE handles[2])
5210{
5211 static LONG s;
5212 char name[64];
5213 SECURITY_ATTRIBUTES sa;
5214
5215 sprintf(name, "\\\\?\\pipe\\vim-%08lx-%08lx",
5216 GetCurrentProcessId(),
5217 InterlockedIncrement(&s));
5218
5219 // Create named pipe. Max size of named pipe is 65535.
5220 handles[1] = CreateNamedPipe(
5221 name,
5222 PIPE_ACCESS_OUTBOUND | FILE_FLAG_OVERLAPPED,
5223 PIPE_TYPE_BYTE | PIPE_NOWAIT,
Bram Moolenaar24058382019-01-24 23:11:49 +01005224 1, MAX_NAMED_PIPE_SIZE, 0, 0, NULL);
Bram Moolenaarb091f302019-01-19 14:37:00 +01005225
5226 if (handles[1] == INVALID_HANDLE_VALUE)
5227 return FALSE;
5228
5229 sa.nLength = sizeof(sa);
5230 sa.bInheritHandle = TRUE;
5231 sa.lpSecurityDescriptor = NULL;
5232
5233 handles[0] = CreateFile(name,
5234 FILE_GENERIC_READ,
5235 FILE_SHARE_READ, &sa,
5236 OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
5237
5238 if (handles[0] == INVALID_HANDLE_VALUE)
5239 {
Bram Moolenaar6982f422019-02-16 16:48:01 +01005240 CloseHandle(handles[1]);
Bram Moolenaarb091f302019-01-19 14:37:00 +01005241 return FALSE;
5242 }
5243
5244 return TRUE;
5245}
5246
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005247 void
Bram Moolenaar5a1feb82017-07-22 18:04:08 +02005248mch_job_start(char *cmd, job_T *job, jobopt_T *options)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005249{
5250 STARTUPINFO si;
5251 PROCESS_INFORMATION pi;
Bram Moolenaar14207f42016-10-27 21:13:10 +02005252 HANDLE jo;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005253 SECURITY_ATTRIBUTES saAttr;
5254 channel_T *channel = NULL;
Bram Moolenaard8070362016-02-15 21:56:54 +01005255 HANDLE ifd[2];
5256 HANDLE ofd[2];
5257 HANDLE efd[2];
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005258 garray_T ga;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005259
5260 int use_null_for_in = options->jo_io[PART_IN] == JIO_NULL;
5261 int use_null_for_out = options->jo_io[PART_OUT] == JIO_NULL;
5262 int use_null_for_err = options->jo_io[PART_ERR] == JIO_NULL;
5263 int use_file_for_in = options->jo_io[PART_IN] == JIO_FILE;
5264 int use_file_for_out = options->jo_io[PART_OUT] == JIO_FILE;
5265 int use_file_for_err = options->jo_io[PART_ERR] == JIO_FILE;
5266 int use_out_for_err = options->jo_io[PART_ERR] == JIO_OUT;
5267
5268 if (use_out_for_err && use_null_for_out)
5269 use_null_for_err = TRUE;
Bram Moolenaard8070362016-02-15 21:56:54 +01005270
5271 ifd[0] = INVALID_HANDLE_VALUE;
5272 ifd[1] = INVALID_HANDLE_VALUE;
5273 ofd[0] = INVALID_HANDLE_VALUE;
5274 ofd[1] = INVALID_HANDLE_VALUE;
5275 efd[0] = INVALID_HANDLE_VALUE;
5276 efd[1] = INVALID_HANDLE_VALUE;
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005277 ga_init2(&ga, (int)sizeof(wchar_t), 500);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005278
Bram Moolenaar14207f42016-10-27 21:13:10 +02005279 jo = CreateJobObject(NULL, NULL);
5280 if (jo == NULL)
5281 {
5282 job->jv_status = JOB_FAILED;
5283 goto failed;
5284 }
5285
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005286 if (options->jo_env != NULL)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005287 win32_build_env(options->jo_env, &ga, FALSE);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005288
Bram Moolenaar76467df2016-02-12 19:30:26 +01005289 ZeroMemory(&pi, sizeof(pi));
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005290 ZeroMemory(&si, sizeof(si));
5291 si.cb = sizeof(si);
Bram Moolenaard8070362016-02-15 21:56:54 +01005292 si.dwFlags |= STARTF_USESHOWWINDOW;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005293 si.wShowWindow = SW_HIDE;
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005294
Bram Moolenaard8070362016-02-15 21:56:54 +01005295 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
5296 saAttr.bInheritHandle = TRUE;
5297 saAttr.lpSecurityDescriptor = NULL;
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005298
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005299 if (use_file_for_in)
5300 {
5301 char_u *fname = options->jo_io_name[PART_IN];
5302
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005303 ifd[0] = job_io_file_open(fname, GENERIC_READ,
5304 FILE_SHARE_READ | FILE_SHARE_WRITE,
5305 &saAttr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL);
5306 if (ifd[0] == INVALID_HANDLE_VALUE)
Bram Moolenaar94d01912016-03-08 13:48:51 +01005307 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005308 semsg(_(e_notopen), fname);
Bram Moolenaar94d01912016-03-08 13:48:51 +01005309 goto failed;
5310 }
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005311 }
Bram Moolenaarb091f302019-01-19 14:37:00 +01005312 else if (!use_null_for_in
5313 && (!create_pipe_pair(ifd)
5314 || !SetHandleInformation(ifd[1], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005315 goto failed;
5316
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005317 if (use_file_for_out)
5318 {
5319 char_u *fname = options->jo_io_name[PART_OUT];
5320
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005321 ofd[1] = job_io_file_open(fname, GENERIC_WRITE,
5322 FILE_SHARE_READ | FILE_SHARE_WRITE,
5323 &saAttr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL);
5324 if (ofd[1] == INVALID_HANDLE_VALUE)
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005325 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005326 semsg(_(e_notopen), fname);
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005327 goto failed;
5328 }
5329 }
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005330 else if (!use_null_for_out &&
5331 (!CreatePipe(&ofd[0], &ofd[1], &saAttr, 0)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005332 || !SetHandleInformation(ofd[0], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005333 goto failed;
5334
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005335 if (use_file_for_err)
5336 {
5337 char_u *fname = options->jo_io_name[PART_ERR];
5338
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005339 efd[1] = job_io_file_open(fname, GENERIC_WRITE,
5340 FILE_SHARE_READ | FILE_SHARE_WRITE,
5341 &saAttr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL);
5342 if (efd[1] == INVALID_HANDLE_VALUE)
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005343 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005344 semsg(_(e_notopen), fname);
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005345 goto failed;
5346 }
5347 }
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005348 else if (!use_out_for_err && !use_null_for_err &&
5349 (!CreatePipe(&efd[0], &efd[1], &saAttr, 0)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005350 || !SetHandleInformation(efd[0], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaard8070362016-02-15 21:56:54 +01005351 goto failed;
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005352
Bram Moolenaard8070362016-02-15 21:56:54 +01005353 si.dwFlags |= STARTF_USESTDHANDLES;
5354 si.hStdInput = ifd[0];
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005355 si.hStdOutput = ofd[1];
5356 si.hStdError = use_out_for_err ? ofd[1] : efd[1];
5357
5358 if (!use_null_for_in || !use_null_for_out || !use_null_for_err)
5359 {
Bram Moolenaarde279892016-03-11 22:19:44 +01005360 if (options->jo_set & JO_CHANNEL)
5361 {
5362 channel = options->jo_channel;
5363 if (channel != NULL)
5364 ++channel->ch_refcount;
5365 }
5366 else
5367 channel = add_channel();
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005368 if (channel == NULL)
5369 goto failed;
5370 }
Bram Moolenaard8070362016-02-15 21:56:54 +01005371
5372 if (!vim_create_process(cmd, TRUE,
Bram Moolenaar14207f42016-10-27 21:13:10 +02005373 CREATE_SUSPENDED |
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005374 CREATE_DEFAULT_ERROR_MODE |
5375 CREATE_NEW_PROCESS_GROUP |
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005376 CREATE_UNICODE_ENVIRONMENT |
Bram Moolenaar76467df2016-02-12 19:30:26 +01005377 CREATE_NEW_CONSOLE,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005378 &si, &pi,
5379 ga.ga_data,
5380 (char *)options->jo_cwd))
Bram Moolenaar76467df2016-02-12 19:30:26 +01005381 {
Bram Moolenaar14207f42016-10-27 21:13:10 +02005382 CloseHandle(jo);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005383 job->jv_status = JOB_FAILED;
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005384 goto failed;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005385 }
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005386
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005387 ga_clear(&ga);
5388
Bram Moolenaar14207f42016-10-27 21:13:10 +02005389 if (!AssignProcessToJobObject(jo, pi.hProcess))
5390 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005391 // if failing, switch the way to terminate
5392 // process with TerminateProcess.
Bram Moolenaar14207f42016-10-27 21:13:10 +02005393 CloseHandle(jo);
5394 jo = NULL;
5395 }
5396 ResumeThread(pi.hThread);
Bram Moolenaar75578a32016-03-10 16:33:31 +01005397 CloseHandle(pi.hThread);
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005398 job->jv_proc_info = pi;
Bram Moolenaar14207f42016-10-27 21:13:10 +02005399 job->jv_job_object = jo;
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005400 job->jv_status = JOB_STARTED;
5401
Bram Moolenaar641ad6c2016-09-01 18:32:11 +02005402 CloseHandle(ifd[0]);
5403 CloseHandle(ofd[1]);
5404 if (!use_out_for_err && !use_null_for_err)
Bram Moolenaarc25558b2016-03-03 21:02:23 +01005405 CloseHandle(efd[1]);
Bram Moolenaard8070362016-02-15 21:56:54 +01005406
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005407 job->jv_channel = channel;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005408 if (channel != NULL)
5409 {
5410 channel_set_pipes(channel,
5411 use_file_for_in || use_null_for_in
5412 ? INVALID_FD : (sock_T)ifd[1],
5413 use_file_for_out || use_null_for_out
5414 ? INVALID_FD : (sock_T)ofd[0],
5415 use_out_for_err || use_file_for_err || use_null_for_err
5416 ? INVALID_FD : (sock_T)efd[0]);
5417 channel_set_job(channel, job, options);
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005418 }
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005419 return;
5420
5421failed:
Bram Moolenaard8070362016-02-15 21:56:54 +01005422 CloseHandle(ifd[0]);
5423 CloseHandle(ofd[0]);
5424 CloseHandle(efd[0]);
5425 CloseHandle(ifd[1]);
5426 CloseHandle(ofd[1]);
5427 CloseHandle(efd[1]);
Bram Moolenaarde279892016-03-11 22:19:44 +01005428 channel_unref(channel);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005429 ga_clear(&ga);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005430}
5431
5432 char *
5433mch_job_status(job_T *job)
5434{
5435 DWORD dwExitCode = 0;
5436
Bram Moolenaar76467df2016-02-12 19:30:26 +01005437 if (!GetExitCodeProcess(job->jv_proc_info.hProcess, &dwExitCode)
5438 || dwExitCode != STILL_ACTIVE)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005439 {
Bram Moolenaareab089d2016-02-21 19:32:02 +01005440 job->jv_exitval = (int)dwExitCode;
Bram Moolenaar7df915d2016-11-17 17:25:32 +01005441 if (job->jv_status < JOB_ENDED)
Bram Moolenaar97792de2016-10-15 18:36:49 +02005442 {
5443 ch_log(job->jv_channel, "Job ended");
5444 job->jv_status = JOB_ENDED;
5445 }
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005446 return "dead";
5447 }
5448 return "run";
5449}
5450
Bram Moolenaar97792de2016-10-15 18:36:49 +02005451 job_T *
5452mch_detect_ended_job(job_T *job_list)
5453{
5454 HANDLE jobHandles[MAXIMUM_WAIT_OBJECTS];
5455 job_T *jobArray[MAXIMUM_WAIT_OBJECTS];
5456 job_T *job = job_list;
5457
5458 while (job != NULL)
5459 {
5460 DWORD n;
5461 DWORD result;
5462
5463 for (n = 0; n < MAXIMUM_WAIT_OBJECTS
5464 && job != NULL; job = job->jv_next)
5465 {
5466 if (job->jv_status == JOB_STARTED)
5467 {
5468 jobHandles[n] = job->jv_proc_info.hProcess;
5469 jobArray[n] = job;
5470 ++n;
5471 }
5472 }
5473 if (n == 0)
5474 continue;
5475 result = WaitForMultipleObjects(n, jobHandles, FALSE, 0);
5476 if (result >= WAIT_OBJECT_0 && result < WAIT_OBJECT_0 + n)
5477 {
5478 job_T *wait_job = jobArray[result - WAIT_OBJECT_0];
5479
5480 if (STRCMP(mch_job_status(wait_job), "dead") == 0)
5481 return wait_job;
5482 }
5483 }
5484 return NULL;
5485}
5486
Bram Moolenaarfb630902016-10-29 14:55:00 +02005487 static BOOL
5488terminate_all(HANDLE process, int code)
5489{
5490 PROCESSENTRY32 pe;
5491 HANDLE h = INVALID_HANDLE_VALUE;
5492 DWORD pid = GetProcessId(process);
5493
5494 if (pid != 0)
5495 {
5496 h = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
5497 if (h != INVALID_HANDLE_VALUE)
5498 {
5499 pe.dwSize = sizeof(PROCESSENTRY32);
5500 if (!Process32First(h, &pe))
5501 goto theend;
5502
5503 do
5504 {
5505 if (pe.th32ParentProcessID == pid)
5506 {
5507 HANDLE ph = OpenProcess(
5508 PROCESS_ALL_ACCESS, FALSE, pe.th32ProcessID);
5509 if (ph != NULL)
5510 {
5511 terminate_all(ph, code);
5512 CloseHandle(ph);
5513 }
5514 }
5515 } while (Process32Next(h, &pe));
5516
5517 CloseHandle(h);
5518 }
5519 }
5520
5521theend:
5522 return TerminateProcess(process, code);
5523}
5524
5525/*
5526 * Send a (deadly) signal to "job".
5527 * Return FAIL if it didn't work.
5528 */
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005529 int
Bram Moolenaar2d33e902017-08-11 16:31:54 +02005530mch_signal_job(job_T *job, char_u *how)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005531{
Bram Moolenaar923d9262016-02-25 20:56:01 +01005532 int ret;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005533
Bram Moolenaar923d9262016-02-25 20:56:01 +01005534 if (STRCMP(how, "term") == 0 || STRCMP(how, "kill") == 0 || *how == NUL)
Bram Moolenaar76467df2016-02-12 19:30:26 +01005535 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005536 // deadly signal
Bram Moolenaar14207f42016-10-27 21:13:10 +02005537 if (job->jv_job_object != NULL)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005538 {
5539 if (job->jv_channel != NULL && job->jv_channel->ch_anonymous_pipe)
5540 job->jv_channel->ch_killing = TRUE;
Bram Moolenaarb3e195c2020-02-10 21:32:19 +01005541 return TerminateJobObject(job->jv_job_object, -1) ? OK : FAIL;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005542 }
Bram Moolenaarb3e195c2020-02-10 21:32:19 +01005543 return terminate_all(job->jv_proc_info.hProcess, -1) ? OK : FAIL;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005544 }
5545
5546 if (!AttachConsole(job->jv_proc_info.dwProcessId))
5547 return FAIL;
5548 ret = GenerateConsoleCtrlEvent(
Bram Moolenaar923d9262016-02-25 20:56:01 +01005549 STRCMP(how, "int") == 0 ? CTRL_C_EVENT : CTRL_BREAK_EVENT,
5550 job->jv_proc_info.dwProcessId)
5551 ? OK : FAIL;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005552 FreeConsole();
5553 return ret;
5554}
5555
5556/*
5557 * Clear the data related to "job".
5558 */
5559 void
5560mch_clear_job(job_T *job)
5561{
5562 if (job->jv_status != JOB_FAILED)
5563 {
Bram Moolenaar14207f42016-10-27 21:13:10 +02005564 if (job->jv_job_object != NULL)
5565 CloseHandle(job->jv_job_object);
Bram Moolenaar76467df2016-02-12 19:30:26 +01005566 CloseHandle(job->jv_proc_info.hProcess);
5567 }
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005568}
5569#endif
5570
Bram Moolenaar071d4272004-06-13 20:20:40 +00005571
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005572#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005573
5574/*
5575 * Start termcap mode
5576 */
5577 static void
5578termcap_mode_start(void)
5579{
5580 DWORD cmodein;
5581
5582 if (g_fTermcapMode)
5583 return;
5584
Bram Moolenaar81ccbf12020-04-15 21:05:30 +02005585 if (!p_rs && USE_VTP)
5586 vtp_printf("\033[?1049h");
5587
Bram Moolenaar071d4272004-06-13 20:20:40 +00005588 SaveConsoleBuffer(&g_cbNonTermcap);
5589
5590 if (g_cbTermcap.IsValid)
5591 {
5592 /*
5593 * We've been in termcap mode before. Restore certain screen
5594 * characteristics, including the buffer size and the window
5595 * size. Since we will be redrawing the screen, we don't need
5596 * to restore the actual contents of the buffer.
5597 */
5598 RestoreConsoleBuffer(&g_cbTermcap, FALSE);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005599 reset_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005600 SetConsoleWindowInfo(g_hConOut, TRUE, &g_cbTermcap.Info.srWindow);
5601 Rows = g_cbTermcap.Info.dwSize.Y;
5602 Columns = g_cbTermcap.Info.dwSize.X;
5603 }
5604 else
5605 {
5606 /*
5607 * This is our first time entering termcap mode. Clear the console
5608 * screen buffer, and resize the buffer to match the current window
5609 * size. We will use this as the size of our editing environment.
5610 */
5611 ClearConsoleBuffer(g_attrCurrent);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005612 set_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005613 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
5614 }
5615
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01005616# ifdef FEAT_TITLE
Bram Moolenaar071d4272004-06-13 20:20:40 +00005617 resettitle();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01005618# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005619
5620 GetConsoleMode(g_hConIn, &cmodein);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005621 if (g_fMouseActive)
5622 cmodein |= ENABLE_MOUSE_INPUT;
5623 else
5624 cmodein &= ~ENABLE_MOUSE_INPUT;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005625 cmodein |= ENABLE_WINDOW_INPUT;
5626 SetConsoleMode(g_hConIn, cmodein);
5627
5628 redraw_later_clear();
5629 g_fTermcapMode = TRUE;
5630}
5631
5632
5633/*
5634 * End termcap mode
5635 */
5636 static void
5637termcap_mode_end(void)
5638{
5639 DWORD cmodein;
5640 ConsoleBuffer *cb;
5641 COORD coord;
5642 DWORD dwDummy;
5643
5644 if (!g_fTermcapMode)
5645 return;
5646
5647 SaveConsoleBuffer(&g_cbTermcap);
5648
5649 GetConsoleMode(g_hConIn, &cmodein);
5650 cmodein &= ~(ENABLE_MOUSE_INPUT | ENABLE_WINDOW_INPUT);
5651 SetConsoleMode(g_hConIn, cmodein);
5652
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01005653# ifdef FEAT_RESTORE_ORIG_SCREEN
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01005654 cb = exiting ? &g_cbOrig : &g_cbNonTermcap;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01005655# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00005656 cb = &g_cbNonTermcap;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01005657# endif
Bram Moolenaar81ccbf12020-04-15 21:05:30 +02005658 RestoreConsoleBuffer(cb, p_rs);
Bram Moolenaardf543822020-01-30 11:53:59 +01005659 restore_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005660 SetConsoleCursorInfo(g_hConOut, &g_cci);
5661
5662 if (p_rs || exiting)
5663 {
5664 /*
5665 * Clear anything that happens to be on the current line.
5666 */
5667 coord.X = 0;
5668 coord.Y = (SHORT) (p_rs ? cb->Info.dwCursorPosition.Y : (Rows - 1));
5669 FillConsoleOutputCharacter(g_hConOut, ' ',
5670 cb->Info.dwSize.X, coord, &dwDummy);
5671 /*
5672 * The following is just for aesthetics. If we are exiting without
5673 * restoring the screen, then we want to have a prompt string
5674 * appear at the bottom line. However, the command interpreter
5675 * seems to always advance the cursor one line before displaying
5676 * the prompt string, which causes the screen to scroll. To
5677 * counter this, move the cursor up one line before exiting.
5678 */
5679 if (exiting && !p_rs)
5680 coord.Y--;
5681 /*
5682 * Position the cursor at the leftmost column of the desired row.
5683 */
Bram Moolenaar81ccbf12020-04-15 21:05:30 +02005684 SetConsoleCursorPosition(g_hConOut, coord);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005685 }
5686
Bram Moolenaar81ccbf12020-04-15 21:05:30 +02005687 if (!p_rs && USE_VTP)
Bram Moolenaar0afdcf82020-04-01 18:29:10 +02005688 vtp_printf("\033[?1049l");
5689
Bram Moolenaar071d4272004-06-13 20:20:40 +00005690 g_fTermcapMode = FALSE;
5691}
Bram Moolenaar0f873732019-12-05 20:28:46 +01005692#endif // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00005693
5694
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005695#if defined(FEAT_GUI_MSWIN) && !defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005696 void
5697mch_write(
Bram Moolenaar1266d672017-02-01 13:43:36 +01005698 char_u *s UNUSED,
5699 int len UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005700{
Bram Moolenaar0f873732019-12-05 20:28:46 +01005701 // never used
Bram Moolenaar071d4272004-06-13 20:20:40 +00005702}
5703
5704#else
5705
5706/*
5707 * clear `n' chars, starting from `coord'
5708 */
5709 static void
5710clear_chars(
5711 COORD coord,
5712 DWORD n)
5713{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005714 if (!USE_VTP)
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02005715 {
5716 DWORD dwDummy;
5717
5718 FillConsoleOutputCharacter(g_hConOut, ' ', n, coord, &dwDummy);
5719 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, n, coord,
5720 &dwDummy);
5721 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005722 else
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02005723 {
5724 set_console_color_rgb();
5725 gotoxy(coord.X + 1, coord.Y + 1);
5726 vtp_printf("\033[%dX", n);
5727 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005728}
5729
5730
5731/*
5732 * Clear the screen
5733 */
5734 static void
5735clear_screen(void)
5736{
5737 g_coord.X = g_coord.Y = 0;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005738
5739 if (!USE_VTP)
5740 clear_chars(g_coord, Rows * Columns);
5741 else
5742 {
5743 set_console_color_rgb();
5744 gotoxy(1, 1);
5745 vtp_printf("\033[2J");
5746 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005747}
5748
5749
5750/*
5751 * Clear to end of display
5752 */
5753 static void
5754clear_to_end_of_display(void)
5755{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005756 COORD save = g_coord;
5757
5758 if (!USE_VTP)
5759 clear_chars(g_coord, (Rows - g_coord.Y - 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005760 * Columns + (Columns - g_coord.X));
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005761 else
5762 {
5763 set_console_color_rgb();
5764 gotoxy(g_coord.X + 1, g_coord.Y + 1);
5765 vtp_printf("\033[0J");
5766
5767 gotoxy(save.X + 1, save.Y + 1);
5768 g_coord = save;
5769 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005770}
5771
5772
5773/*
5774 * Clear to end of line
5775 */
5776 static void
5777clear_to_end_of_line(void)
5778{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005779 COORD save = g_coord;
5780
5781 if (!USE_VTP)
5782 clear_chars(g_coord, Columns - g_coord.X);
5783 else
5784 {
5785 set_console_color_rgb();
5786 gotoxy(g_coord.X + 1, g_coord.Y + 1);
5787 vtp_printf("\033[0K");
5788
5789 gotoxy(save.X + 1, save.Y + 1);
5790 g_coord = save;
5791 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005792}
5793
5794
5795/*
5796 * Scroll the scroll region up by `cLines' lines
5797 */
5798 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005799scroll(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005800{
5801 COORD oldcoord = g_coord;
5802
5803 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
5804 delete_lines(cLines);
5805
5806 g_coord = oldcoord;
5807}
5808
5809
5810/*
5811 * Set the scroll region
5812 */
5813 static void
5814set_scroll_region(
5815 unsigned left,
5816 unsigned top,
5817 unsigned right,
5818 unsigned bottom)
5819{
5820 if (left >= right
5821 || top >= bottom
5822 || right > (unsigned) Columns - 1
5823 || bottom > (unsigned) Rows - 1)
5824 return;
5825
5826 g_srScrollRegion.Left = left;
5827 g_srScrollRegion.Top = top;
5828 g_srScrollRegion.Right = right;
5829 g_srScrollRegion.Bottom = bottom;
Bram Moolenaar6982f422019-02-16 16:48:01 +01005830}
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005831
Bram Moolenaar6982f422019-02-16 16:48:01 +01005832 static void
5833set_scroll_region_tb(
5834 unsigned top,
5835 unsigned bottom)
5836{
5837 if (top >= bottom || bottom > (unsigned)Rows - 1)
5838 return;
5839
5840 g_srScrollRegion.Top = top;
5841 g_srScrollRegion.Bottom = bottom;
5842}
5843
5844 static void
5845set_scroll_region_lr(
5846 unsigned left,
5847 unsigned right)
5848{
5849 if (left >= right || right > (unsigned)Columns - 1)
5850 return;
5851
5852 g_srScrollRegion.Left = left;
5853 g_srScrollRegion.Right = right;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005854}
5855
5856
5857/*
5858 * Insert `cLines' lines at the current cursor position
5859 */
5860 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005861insert_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005862{
Bram Moolenaar6982f422019-02-16 16:48:01 +01005863 SMALL_RECT source, clip;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005864 COORD dest;
5865 CHAR_INFO fill;
5866
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01005867 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
5868
Bram Moolenaar6982f422019-02-16 16:48:01 +01005869 dest.X = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005870 dest.Y = g_coord.Y + cLines;
5871
Bram Moolenaar6982f422019-02-16 16:48:01 +01005872 source.Left = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005873 source.Top = g_coord.Y;
5874 source.Right = g_srScrollRegion.Right;
5875 source.Bottom = g_srScrollRegion.Bottom - cLines;
5876
Bram Moolenaar6982f422019-02-16 16:48:01 +01005877 clip.Left = g_srScrollRegion.Left;
5878 clip.Top = g_coord.Y;
5879 clip.Right = g_srScrollRegion.Right;
5880 clip.Bottom = g_srScrollRegion.Bottom;
5881
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01005882 fill.Char.AsciiChar = ' ';
5883 if (!USE_VTP)
5884 fill.Attributes = g_attrCurrent;
5885 else
5886 fill.Attributes = g_attrDefault;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005887
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01005888 set_console_color_rgb();
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005889
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01005890 ScrollConsoleScreenBuffer(g_hConOut, &source, &clip, dest, &fill);
5891
Bram Moolenaar6982f422019-02-16 16:48:01 +01005892 // Here we have to deal with a win32 console flake: If the scroll
5893 // region looks like abc and we scroll c to a and fill with d we get
5894 // cbd... if we scroll block c one line at a time to a, we get cdd...
5895 // vim expects cdd consistently... So we have to deal with that
5896 // here... (this also occurs scrolling the same way in the other
5897 // direction).
Bram Moolenaar071d4272004-06-13 20:20:40 +00005898
5899 if (source.Bottom < dest.Y)
5900 {
5901 COORD coord;
Bram Moolenaar6982f422019-02-16 16:48:01 +01005902 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005903
Bram Moolenaar6982f422019-02-16 16:48:01 +01005904 coord.X = source.Left;
5905 for (i = clip.Top; i < dest.Y; ++i)
5906 {
5907 coord.Y = i;
5908 clear_chars(coord, source.Right - source.Left + 1);
5909 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005910 }
Bram Moolenaar06b7b582020-05-30 17:49:25 +02005911
5912 if (USE_WT)
5913 {
5914 COORD coord;
5915 int i;
5916
5917 coord.X = source.Left;
5918 for (i = source.Top; i < dest.Y; ++i)
5919 {
5920 coord.Y = i;
5921 clear_chars(coord, source.Right - source.Left + 1);
5922 }
5923 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005924}
5925
5926
5927/*
5928 * Delete `cLines' lines at the current cursor position
5929 */
5930 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005931delete_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005932{
Bram Moolenaar6982f422019-02-16 16:48:01 +01005933 SMALL_RECT source, clip;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005934 COORD dest;
5935 CHAR_INFO fill;
5936 int nb;
5937
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01005938 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
5939
Bram Moolenaar6982f422019-02-16 16:48:01 +01005940 dest.X = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005941 dest.Y = g_coord.Y;
5942
Bram Moolenaar6982f422019-02-16 16:48:01 +01005943 source.Left = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005944 source.Top = g_coord.Y + cLines;
5945 source.Right = g_srScrollRegion.Right;
5946 source.Bottom = g_srScrollRegion.Bottom;
5947
Bram Moolenaar6982f422019-02-16 16:48:01 +01005948 clip.Left = g_srScrollRegion.Left;
5949 clip.Top = g_coord.Y;
5950 clip.Right = g_srScrollRegion.Right;
5951 clip.Bottom = g_srScrollRegion.Bottom;
5952
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01005953 fill.Char.AsciiChar = ' ';
5954 if (!USE_VTP)
5955 fill.Attributes = g_attrCurrent;
5956 else
5957 fill.Attributes = g_attrDefault;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005958
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01005959 set_console_color_rgb();
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005960
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01005961 ScrollConsoleScreenBuffer(g_hConOut, &source, &clip, dest, &fill);
5962
Bram Moolenaar6982f422019-02-16 16:48:01 +01005963 // Here we have to deal with a win32 console flake; See insert_lines()
5964 // above.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005965
5966 nb = dest.Y + (source.Bottom - source.Top) + 1;
5967
5968 if (nb < source.Top)
5969 {
5970 COORD coord;
Bram Moolenaar6982f422019-02-16 16:48:01 +01005971 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005972
Bram Moolenaar6982f422019-02-16 16:48:01 +01005973 coord.X = source.Left;
5974 for (i = nb; i < clip.Bottom; ++i)
5975 {
5976 coord.Y = i;
5977 clear_chars(coord, source.Right - source.Left + 1);
5978 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005979 }
Bram Moolenaar06b7b582020-05-30 17:49:25 +02005980
5981 if (USE_WT)
5982 {
5983 COORD coord;
5984 int i;
5985
5986 coord.X = source.Left;
5987 for (i = nb; i <= source.Bottom; ++i)
5988 {
5989 coord.Y = i;
5990 clear_chars(coord, source.Right - source.Left + 1);
5991 }
5992 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005993}
5994
5995
5996/*
Bram Moolenaar2313b612019-09-27 14:14:32 +02005997 * Set the cursor position to (x,y) (1-based).
Bram Moolenaar071d4272004-06-13 20:20:40 +00005998 */
5999 static void
6000gotoxy(
6001 unsigned x,
6002 unsigned y)
6003{
6004 if (x < 1 || x > (unsigned)Columns || y < 1 || y > (unsigned)Rows)
6005 return;
6006
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006007 if (!USE_VTP)
Bram Moolenaar2313b612019-09-27 14:14:32 +02006008 {
Bram Moolenaar82e743c2020-03-26 15:39:53 +01006009 // There are reports of double-width characters not displayed
6010 // correctly. This workaround should fix it, similar to how it's done
6011 // for VTP.
6012 g_coord.X = 0;
6013 SetConsoleCursorPosition(g_hConOut, g_coord);
6014
Bram Moolenaar2313b612019-09-27 14:14:32 +02006015 // external cursor coords are 1-based; internal are 0-based
6016 g_coord.X = x - 1;
6017 g_coord.Y = y - 1;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006018 SetConsoleCursorPosition(g_hConOut, g_coord);
Bram Moolenaar2313b612019-09-27 14:14:32 +02006019 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006020 else
Bram Moolenaar2313b612019-09-27 14:14:32 +02006021 {
6022 // Move the cursor to the left edge of the screen to prevent screen
Bram Moolenaara1299742019-10-10 16:36:00 +02006023 // destruction. Insider build bug. Always enabled because it's cheap
6024 // and avoids mistakes with recognizing the build.
6025 vtp_printf("\033[%d;%dH", g_coord.Y + 1, 1);
Bram Moolenaar2313b612019-09-27 14:14:32 +02006026
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006027 vtp_printf("\033[%d;%dH", y, x);
Bram Moolenaar2313b612019-09-27 14:14:32 +02006028
6029 g_coord.X = x - 1;
6030 g_coord.Y = y - 1;
6031 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006032}
6033
6034
6035/*
6036 * Set the current text attribute = (foreground | background)
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006037 * See ../runtime/doc/os_win32.txt for the numbers.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006038 */
6039 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006040textattr(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006041{
Bram Moolenaar6383b922015-03-24 17:12:19 +01006042 g_attrCurrent = wAttr & 0xff;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006043
6044 SetConsoleTextAttribute(g_hConOut, wAttr);
6045}
6046
6047
6048 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006049textcolor(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006050{
Bram Moolenaar6383b922015-03-24 17:12:19 +01006051 g_attrCurrent = (g_attrCurrent & 0xf0) + (wAttr & 0x0f);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006052
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006053 if (!USE_VTP)
6054 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
6055 else
6056 vtp_sgr_bulk(wAttr);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006057}
6058
6059
6060 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006061textbackground(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006062{
Bram Moolenaar6383b922015-03-24 17:12:19 +01006063 g_attrCurrent = (g_attrCurrent & 0x0f) + ((wAttr & 0x0f) << 4);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006064
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006065 if (!USE_VTP)
6066 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
6067 else
6068 vtp_sgr_bulk(wAttr);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006069}
6070
6071
6072/*
6073 * restore the default text attribute (whatever we started with)
6074 */
6075 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006076normvideo(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006077{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006078 if (!USE_VTP)
6079 textattr(g_attrDefault);
6080 else
6081 vtp_sgr_bulk(0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006082}
6083
6084
6085static WORD g_attrPreStandout = 0;
6086
6087/*
6088 * Make the text standout, by brightening it
6089 */
6090 static void
6091standout(void)
6092{
6093 g_attrPreStandout = g_attrCurrent;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006094
Bram Moolenaar071d4272004-06-13 20:20:40 +00006095 textattr((WORD) (g_attrCurrent|FOREGROUND_INTENSITY|BACKGROUND_INTENSITY));
6096}
6097
6098
6099/*
6100 * Turn off standout mode
6101 */
6102 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006103standend(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006104{
6105 if (g_attrPreStandout)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006106 textattr(g_attrPreStandout);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006107
6108 g_attrPreStandout = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006109}
6110
6111
6112/*
Bram Moolenaarff1d0d42007-05-10 17:24:16 +00006113 * Set normal fg/bg color, based on T_ME. Called when t_me has been set.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006114 */
6115 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006116mch_set_normal_colors(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006117{
6118 char_u *p;
6119 int n;
6120
6121 cterm_normal_fg_color = (g_attrDefault & 0xf) + 1;
6122 cterm_normal_bg_color = ((g_attrDefault >> 4) & 0xf) + 1;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006123 if (
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006124# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006125 !p_tgc &&
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006126# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006127 T_ME[0] == ESC && T_ME[1] == '|')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006128 {
6129 p = T_ME + 2;
6130 n = getdigits(&p);
6131 if (*p == 'm' && n > 0)
6132 {
6133 cterm_normal_fg_color = (n & 0xf) + 1;
6134 cterm_normal_bg_color = ((n >> 4) & 0xf) + 1;
6135 }
6136 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006137# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006138 cterm_normal_fg_gui_color = INVALCOLOR;
6139 cterm_normal_bg_gui_color = INVALCOLOR;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006140# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006141}
6142
6143
6144/*
6145 * visual bell: flash the screen
6146 */
6147 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006148visual_bell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006149{
6150 COORD coordOrigin = {0, 0};
6151 WORD attrFlash = ~g_attrCurrent & 0xff;
6152
6153 DWORD dwDummy;
Bram Moolenaarc799fe22019-05-28 23:08:19 +02006154 LPWORD oldattrs = ALLOC_MULT(WORD, Rows * Columns);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006155
6156 if (oldattrs == NULL)
6157 return;
6158 ReadConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
6159 coordOrigin, &dwDummy);
6160 FillConsoleOutputAttribute(g_hConOut, attrFlash, Rows * Columns,
6161 coordOrigin, &dwDummy);
6162
Bram Moolenaar0f873732019-12-05 20:28:46 +01006163 Sleep(15); // wait for 15 msec
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006164 if (!USE_VTP)
6165 WriteConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
Bram Moolenaar071d4272004-06-13 20:20:40 +00006166 coordOrigin, &dwDummy);
6167 vim_free(oldattrs);
6168}
6169
6170
6171/*
6172 * Make the cursor visible or invisible
6173 */
6174 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006175cursor_visible(BOOL fVisible)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006176{
6177 s_cursor_visible = fVisible;
Bram Moolenaar2695de62020-04-17 21:13:01 +02006178
6179 if (USE_VTP)
6180 vtp_printf("\033[?25%c", fVisible ? 'h' : 'l');
6181
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006182# ifdef MCH_CURSOR_SHAPE
Bram Moolenaar071d4272004-06-13 20:20:40 +00006183 mch_update_cursor();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006184# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006185}
6186
6187
6188/*
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02006189 * Write "cbToWrite" bytes in `pchBuf' to the screen.
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006190 * Returns the number of bytes actually written (at least one).
Bram Moolenaar071d4272004-06-13 20:20:40 +00006191 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006192 static DWORD
Bram Moolenaar071d4272004-06-13 20:20:40 +00006193write_chars(
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006194 char_u *pchBuf,
6195 DWORD cbToWrite)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006196{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006197 COORD coord = g_coord;
6198 DWORD written;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006199 DWORD n, cchwritten;
6200 static DWORD cells;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006201 static WCHAR *unicodebuf = NULL;
6202 static int unibuflen = 0;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006203 static int length;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006204 int cp = enc_utf8 ? CP_UTF8 : enc_codepage;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006205 static WCHAR *utf8spbuf = NULL;
6206 static int utf8splength;
6207 static DWORD utf8spcells;
6208 static WCHAR **utf8usingbuf = &unicodebuf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006209
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006210 if (cbToWrite != 1 || *pchBuf != ' ' || !enc_utf8)
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006211 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006212 utf8usingbuf = &unicodebuf;
6213 do
6214 {
6215 length = MultiByteToWideChar(cp, 0, (LPCSTR)pchBuf, cbToWrite,
6216 unicodebuf, unibuflen);
6217 if (length && length <= unibuflen)
6218 break;
6219 vim_free(unicodebuf);
6220 unicodebuf = length ? LALLOC_MULT(WCHAR, length) : NULL;
6221 unibuflen = unibuflen ? 0 : length;
6222 } while(1);
6223 cells = mb_string2cells(pchBuf, cbToWrite);
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006224 }
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006225 else // cbToWrite == 1 && *pchBuf == ' ' && enc_utf8
6226 {
6227 if (utf8usingbuf != &utf8spbuf)
6228 {
6229 if (utf8spbuf == NULL)
6230 {
6231 cells = mb_string2cells((char_u *)" ", 1);
6232 length = MultiByteToWideChar(CP_UTF8, 0, " ", 1, NULL, 0);
6233 utf8spbuf = LALLOC_MULT(WCHAR, length);
6234 if (utf8spbuf != NULL)
6235 {
6236 MultiByteToWideChar(CP_UTF8, 0, " ", 1, utf8spbuf, length);
6237 utf8usingbuf = &utf8spbuf;
6238 utf8splength = length;
6239 utf8spcells = cells;
6240 }
6241 }
6242 else
6243 {
6244 utf8usingbuf = &utf8spbuf;
6245 length = utf8splength;
6246 cells = utf8spcells;
6247 }
6248 }
6249 }
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006250
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006251 if (!USE_VTP)
6252 {
6253 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, cells,
6254 coord, &written);
6255 // When writing fails or didn't write a single character, pretend one
6256 // character was written, otherwise we get stuck.
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006257 if (WriteConsoleOutputCharacterW(g_hConOut, *utf8usingbuf, length,
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006258 coord, &cchwritten) == 0
6259 || cchwritten == 0 || cchwritten == (DWORD)-1)
6260 cchwritten = 1;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006261 }
6262 else
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006263 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006264 if (WriteConsoleW(g_hConOut, *utf8usingbuf, length, &cchwritten,
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006265 NULL) == 0 || cchwritten == 0)
6266 cchwritten = 1;
6267 }
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006268
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006269 if (cchwritten == length)
6270 {
6271 written = cbToWrite;
6272 g_coord.X += (SHORT)cells;
6273 }
6274 else
6275 {
6276 char_u *p = pchBuf;
6277 for (n = 0; n < cchwritten; n++)
6278 MB_CPTR_ADV(p);
6279 written = p - pchBuf;
6280 g_coord.X += (SHORT)mb_string2cells(pchBuf, written);
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006281 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006282
6283 while (g_coord.X > g_srScrollRegion.Right)
6284 {
6285 g_coord.X -= (SHORT) Columns;
6286 if (g_coord.Y < g_srScrollRegion.Bottom)
6287 g_coord.Y++;
6288 }
6289
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006290 // Cursor under VTP is always in the correct position, no need to reset.
6291 if (!USE_VTP)
6292 gotoxy(g_coord.X + 1, g_coord.Y + 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006293
6294 return written;
6295}
6296
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006297 static char_u *
6298get_seq(
6299 int *args,
6300 int *count,
6301 char_u *head)
6302{
6303 int argc;
6304 char_u *p;
6305
6306 if (head == NULL || *head != '\033')
6307 return NULL;
6308
6309 argc = 0;
6310 p = head;
6311 ++p;
6312 do
6313 {
6314 ++p;
6315 args[argc] = getdigits(&p);
6316 argc += (argc < 15) ? 1 : 0;
6317 } while (*p == ';');
6318 *count = argc;
6319
6320 return p;
6321}
6322
6323 static char_u *
6324get_sgr(
6325 int *args,
6326 int *count,
6327 char_u *head)
6328{
6329 char_u *p = get_seq(args, count, head);
6330
6331 return (p && *p == 'm') ? ++p : NULL;
6332}
6333
6334/*
6335 * Pointer to next if SGR (^[[n;2;*;*;*m), NULL otherwise.
6336 */
6337 static char_u *
6338sgrn2(
6339 char_u *head,
6340 int n)
6341{
6342 int argc;
6343 int args[16];
6344 char_u *p = get_sgr(args, &argc, head);
6345
6346 return p && argc == 5 && args[0] == n && args[1] == 2 ? p : NULL;
6347}
6348
6349/*
6350 * Pointer to next if SGR(^[[nm)<space>ESC, NULL otherwise.
6351 */
6352 static char_u *
6353sgrnc(
6354 char_u *head,
6355 int n)
6356{
6357 int argc;
6358 int args[16];
6359 char_u *p = get_sgr(args, &argc, head);
6360
6361 return p && argc == 1 && args[0] == n && (p = skipwhite(p)) && *p == '\033'
6362 ? p : NULL;
6363}
6364
6365 static char_u *
6366skipblank(char_u *q)
6367{
6368 char_u *p = q;
6369
6370 while (*p == ' ' || *p == '\t' || *p == '\n' || *p == '\r')
6371 ++p;
6372 return p;
6373}
6374
6375/*
6376 * Pointer to the next if any whitespace that may follow SGR is ESC, otherwise
6377 * NULL.
6378 */
6379 static char_u *
6380sgrn2c(
6381 char_u *head,
6382 int n)
6383{
6384 char_u *p = sgrn2(head, n);
6385
6386 return p && *p != NUL && (p = skipblank(p)) && *p == '\033' ? p : NULL;
6387}
6388
6389/*
6390 * If there is only a newline between the sequence immediately following it,
6391 * a pointer to the character following the newline is returned.
6392 * Otherwise NULL.
6393 */
6394 static char_u *
6395sgrn2cn(
6396 char_u *head,
6397 int n)
6398{
6399 char_u *p = sgrn2(head, n);
6400
6401 return p && p[0] == 0x0a && p[1] == '\033' ? ++p : NULL;
6402}
Bram Moolenaar071d4272004-06-13 20:20:40 +00006403
6404/*
6405 * mch_write(): write the output buffer to the screen, translating ESC
6406 * sequences into calls to console output routines.
6407 */
6408 void
6409mch_write(
6410 char_u *s,
6411 int len)
6412{
Bram Moolenaard23f8bd2021-04-21 11:30:48 +02006413 char_u *end = s + len;
6414
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006415# ifdef VIMDLL
6416 if (gui.in_use)
6417 return;
6418# endif
6419
Bram Moolenaar071d4272004-06-13 20:20:40 +00006420 if (!term_console)
6421 {
6422 write(1, s, (unsigned)len);
6423 return;
6424 }
6425
Bram Moolenaar0f873732019-12-05 20:28:46 +01006426 // translate ESC | sequences into faked bios calls
Bram Moolenaar071d4272004-06-13 20:20:40 +00006427 while (len--)
6428 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006429 int prefix = -1;
6430 char_u ch;
6431
6432 // While processing a sequence, on rare occasions it seems that another
6433 // sequence may be inserted asynchronously.
6434 if (len < 0)
6435 {
6436 redraw_all_later(CLEAR);
6437 return;
6438 }
6439
Bram Moolenaard23f8bd2021-04-21 11:30:48 +02006440 while (s + ++prefix < end)
6441 {
6442 ch = s[prefix];
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006443 if (ch <= 0x1e && !(ch != '\n' && ch != '\r' && ch != '\b'
6444 && ch != '\a' && ch != '\033'))
6445 break;
Bram Moolenaard23f8bd2021-04-21 11:30:48 +02006446 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006447
6448 if (p_wd)
6449 {
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02006450 WaitForChar(p_wd, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006451 if (prefix != 0)
6452 prefix = 1;
6453 }
6454
6455 if (prefix != 0)
6456 {
6457 DWORD nWritten;
6458
6459 nWritten = write_chars(s, prefix);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006460# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006461 if (fdDump)
6462 {
6463 fputc('>', fdDump);
6464 fwrite(s, sizeof(char_u), nWritten, fdDump);
6465 fputs("<\n", fdDump);
6466 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006467# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006468 len -= (nWritten - 1);
6469 s += nWritten;
6470 }
6471 else if (s[0] == '\n')
6472 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006473 // \n, newline: go to the beginning of the next line or scroll
Bram Moolenaar071d4272004-06-13 20:20:40 +00006474 if (g_coord.Y == g_srScrollRegion.Bottom)
6475 {
6476 scroll(1);
6477 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Bottom + 1);
6478 }
6479 else
6480 {
6481 gotoxy(g_srScrollRegion.Left + 1, g_coord.Y + 2);
6482 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006483# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006484 if (fdDump)
6485 fputs("\\n\n", fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006486# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006487 s++;
6488 }
6489 else if (s[0] == '\r')
6490 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006491 // \r, carriage return: go to beginning of line
Bram Moolenaar071d4272004-06-13 20:20:40 +00006492 gotoxy(g_srScrollRegion.Left+1, g_coord.Y + 1);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006493# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006494 if (fdDump)
6495 fputs("\\r\n", fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006496# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006497 s++;
6498 }
6499 else if (s[0] == '\b')
6500 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006501 // \b, backspace: move cursor one position left
Bram Moolenaar071d4272004-06-13 20:20:40 +00006502 if (g_coord.X > g_srScrollRegion.Left)
6503 g_coord.X--;
6504 else if (g_coord.Y > g_srScrollRegion.Top)
6505 {
6506 g_coord.X = g_srScrollRegion.Right;
6507 g_coord.Y--;
6508 }
6509 gotoxy(g_coord.X + 1, g_coord.Y + 1);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006510# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006511 if (fdDump)
6512 fputs("\\b\n", fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006513# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006514 s++;
6515 }
6516 else if (s[0] == '\a')
6517 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006518 // \a, bell
Bram Moolenaar071d4272004-06-13 20:20:40 +00006519 MessageBeep(0xFFFFFFFF);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006520# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006521 if (fdDump)
6522 fputs("\\a\n", fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006523# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006524 s++;
6525 }
6526 else if (s[0] == ESC && len >= 3-1 && s[1] == '|')
6527 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006528# ifdef MCH_WRITE_DUMP
Bram Moolenaarc0197e22004-09-13 20:26:32 +00006529 char_u *old_s = s;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006530# endif
Bram Moolenaarc0197e22004-09-13 20:26:32 +00006531 char_u *p;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006532 int arg1 = 0, arg2 = 0, argc = 0, args[16];
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006533 char_u *sp;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006534
6535 switch (s[2])
6536 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006537 case '0': case '1': case '2': case '3': case '4':
6538 case '5': case '6': case '7': case '8': case '9':
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006539 if (*(p = get_seq(args, &argc, s)) != 'm')
6540 goto notsgr;
6541
6542 p = s;
6543
6544 // Handling frequent optional sequences. Output to the screen
6545 // takes too long, so do not output as much as possible.
6546
6547 // If resetFG,FG,BG,<cr>,BG,FG are connected, the preceding
6548 // resetFG,FG,BG are omitted.
6549 if (sgrn2(sgrn2(sgrn2cn(sgrn2(sgrnc(p, 39), 38), 48), 48), 38))
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006550 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006551 p = sgrn2(sgrn2(sgrnc(p, 39), 38), 48);
6552 len = len + 1 - (int)(p - s);
6553 s = p;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006554 break;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006555 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006556
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006557 // If FG,BG,BG,FG of SGR are connected, the first FG can be
6558 // omitted.
6559 if (sgrn2(sgrn2(sgrn2c((sp = sgrn2(p, 38)), 48), 48), 38))
6560 p = sp;
6561
6562 // If FG,BG,FG,BG of SGR are connected, the first FG can be
6563 // omitted.
6564 if (sgrn2(sgrn2(sgrn2c((sp = sgrn2(p, 38)), 48), 38), 48))
6565 p = sp;
6566
6567 // If BG,BG of SGR are connected, the first BG can be omitted.
6568 if (sgrn2((sp = sgrn2(p, 48)), 48))
6569 p = sp;
6570
6571 // If restoreFG and FG are connected, the restoreFG can be
6572 // omitted.
6573 if (sgrn2((sp = sgrnc(p, 39)), 38))
6574 p = sp;
6575
6576 p = get_seq(args, &argc, p);
6577
6578notsgr:
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006579 arg1 = args[0];
6580 arg2 = args[1];
6581 if (*p == 'm')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006582 {
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006583 if (argc == 1 && args[0] == 0)
6584 normvideo();
6585 else if (argc == 1)
6586 {
6587 if (USE_VTP)
6588 textcolor((WORD) arg1);
6589 else
6590 textattr((WORD) arg1);
6591 }
6592 else if (USE_VTP)
6593 vtp_sgr_bulks(argc, args);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006594 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006595 else if (argc == 2 && *p == 'H')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006596 {
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006597 gotoxy(arg2, arg1);
6598 }
6599 else if (argc == 2 && *p == 'r')
6600 {
6601 set_scroll_region(0, arg1 - 1, Columns - 1, arg2 - 1);
6602 }
Bram Moolenaar6982f422019-02-16 16:48:01 +01006603 else if (argc == 2 && *p == 'R')
6604 {
6605 set_scroll_region_tb(arg1, arg2);
6606 }
6607 else if (argc == 2 && *p == 'V')
6608 {
6609 set_scroll_region_lr(arg1, arg2);
6610 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006611 else if (argc == 1 && *p == 'A')
6612 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006613 gotoxy(g_coord.X + 1,
6614 max(g_srScrollRegion.Top, g_coord.Y - arg1) + 1);
6615 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006616 else if (argc == 1 && *p == 'b')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006617 {
6618 textbackground((WORD) arg1);
6619 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006620 else if (argc == 1 && *p == 'C')
6621 {
6622 gotoxy(min(g_srScrollRegion.Right, g_coord.X + arg1) + 1,
6623 g_coord.Y + 1);
6624 }
6625 else if (argc == 1 && *p == 'f')
6626 {
6627 textcolor((WORD) arg1);
6628 }
6629 else if (argc == 1 && *p == 'H')
6630 {
6631 gotoxy(1, arg1);
6632 }
6633 else if (argc == 1 && *p == 'L')
6634 {
6635 insert_lines(arg1);
6636 }
6637 else if (argc == 1 && *p == 'M')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006638 {
6639 delete_lines(arg1);
6640 }
6641
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006642 len -= (int)(p - s);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006643 s = p + 1;
6644 break;
6645
Bram Moolenaar071d4272004-06-13 20:20:40 +00006646 case 'A':
Bram Moolenaar071d4272004-06-13 20:20:40 +00006647 gotoxy(g_coord.X + 1,
6648 max(g_srScrollRegion.Top, g_coord.Y - 1) + 1);
6649 goto got3;
6650
6651 case 'B':
6652 visual_bell();
6653 goto got3;
6654
6655 case 'C':
Bram Moolenaar071d4272004-06-13 20:20:40 +00006656 gotoxy(min(g_srScrollRegion.Right, g_coord.X + 1) + 1,
6657 g_coord.Y + 1);
6658 goto got3;
6659
6660 case 'E':
6661 termcap_mode_end();
6662 goto got3;
6663
6664 case 'F':
6665 standout();
6666 goto got3;
6667
6668 case 'f':
6669 standend();
6670 goto got3;
6671
6672 case 'H':
6673 gotoxy(1, 1);
6674 goto got3;
6675
6676 case 'j':
6677 clear_to_end_of_display();
6678 goto got3;
6679
6680 case 'J':
6681 clear_screen();
6682 goto got3;
6683
6684 case 'K':
6685 clear_to_end_of_line();
6686 goto got3;
6687
6688 case 'L':
6689 insert_lines(1);
6690 goto got3;
6691
6692 case 'M':
6693 delete_lines(1);
6694 goto got3;
6695
6696 case 'S':
6697 termcap_mode_start();
6698 goto got3;
6699
6700 case 'V':
6701 cursor_visible(TRUE);
6702 goto got3;
6703
6704 case 'v':
6705 cursor_visible(FALSE);
6706 goto got3;
6707
6708 got3:
6709 s += 3;
6710 len -= 2;
6711 }
6712
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006713# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006714 if (fdDump)
6715 {
6716 fputs("ESC | ", fdDump);
6717 fwrite(old_s + 2, sizeof(char_u), s - old_s - 2, fdDump);
6718 fputc('\n', fdDump);
6719 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006720# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006721 }
6722 else
6723 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006724 // Write a single character
Bram Moolenaar071d4272004-06-13 20:20:40 +00006725 DWORD nWritten;
6726
6727 nWritten = write_chars(s, 1);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006728# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006729 if (fdDump)
6730 {
6731 fputc('>', fdDump);
6732 fwrite(s, sizeof(char_u), nWritten, fdDump);
6733 fputs("<\n", fdDump);
6734 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006735# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006736
6737 len -= (nWritten - 1);
6738 s += nWritten;
6739 }
6740 }
6741
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006742# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006743 if (fdDump)
6744 fflush(fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006745# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006746}
6747
Bram Moolenaar0f873732019-12-05 20:28:46 +01006748#endif // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00006749
6750
6751/*
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01006752 * Delay for "msec" milliseconds.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006753 */
6754 void
6755mch_delay(
6756 long msec,
Bram Moolenaar0981c872020-08-23 14:28:37 +02006757 int flags UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006758{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006759#if defined(FEAT_GUI_MSWIN) && !defined(VIMDLL)
Bram Moolenaar0f873732019-12-05 20:28:46 +01006760 Sleep((int)msec); // never wait for input
6761#else // Console
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006762# ifdef VIMDLL
6763 if (gui.in_use)
6764 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006765 Sleep((int)msec); // never wait for input
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006766 return;
6767 }
6768# endif
Bram Moolenaar0981c872020-08-23 14:28:37 +02006769 if (flags & MCH_DELAY_IGNOREINPUT)
Bram Moolenaar325b7a22004-07-05 15:58:32 +00006770# ifdef FEAT_MZSCHEME
6771 if (mzthreads_allowed() && p_mzq > 0 && msec > p_mzq)
6772 {
6773 int towait = p_mzq;
6774
Bram Moolenaar0f873732019-12-05 20:28:46 +01006775 // if msec is large enough, wait by portions in p_mzq
Bram Moolenaar325b7a22004-07-05 15:58:32 +00006776 while (msec > 0)
6777 {
6778 mzvim_check_threads();
6779 if (msec < towait)
6780 towait = msec;
6781 Sleep(towait);
6782 msec -= towait;
6783 }
6784 }
6785 else
6786# endif
6787 Sleep((int)msec);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006788 else
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02006789 WaitForChar(msec, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006790#endif
6791}
6792
6793
6794/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01006795 * This version of remove is not scared by a readonly (backup) file.
6796 * This can also remove a symbolic link like Unix.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006797 * Return 0 for success, -1 for failure.
6798 */
6799 int
6800mch_remove(char_u *name)
6801{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006802 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006803 int n;
6804
Bram Moolenaar203258c2016-01-17 22:15:16 +01006805 /*
6806 * On Windows, deleting a directory's symbolic link is done by
6807 * RemoveDirectory(): mch_rmdir. It seems unnatural, but it is fact.
6808 */
6809 if (mch_isdir(name) && mch_is_symbolic_link(name))
6810 return mch_rmdir(name);
6811
Bram Moolenaar12b559e2013-06-12 22:41:37 +02006812 win32_setattrs(name, FILE_ATTRIBUTE_NORMAL);
6813
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006814 wn = enc_to_utf16(name, NULL);
6815 if (wn == NULL)
6816 return -1;
6817
6818 n = DeleteFileW(wn) ? 0 : -1;
6819 vim_free(wn);
6820 return n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006821}
6822
6823
6824/*
Bram Moolenaarb9c31e72016-09-29 15:18:57 +02006825 * Check for an "interrupt signal": CTRL-break or CTRL-C.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006826 */
6827 void
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02006828mch_breakcheck(int force UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006829{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006830#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
6831# ifdef VIMDLL
6832 if (!gui.in_use)
6833# endif
6834 if (g_fCtrlCPressed || g_fCBrkPressed)
6835 {
6836 ctrl_break_was_pressed = g_fCBrkPressed;
6837 g_fCtrlCPressed = g_fCBrkPressed = FALSE;
6838 got_int = TRUE;
6839 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006840#endif
6841}
6842
Bram Moolenaar0f873732019-12-05 20:28:46 +01006843// physical RAM to leave for the OS
Bram Moolenaaree273972016-01-02 21:11:51 +01006844#define WINNT_RESERVE_BYTES (256*1024*1024)
Bram Moolenaaree273972016-01-02 21:11:51 +01006845
6846/*
6847 * How much main memory in KiB that can be used by VIM.
6848 */
Bram Moolenaaree273972016-01-02 21:11:51 +01006849 long_u
Bram Moolenaar1266d672017-02-01 13:43:36 +01006850mch_total_mem(int special UNUSED)
Bram Moolenaaree273972016-01-02 21:11:51 +01006851{
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006852 MEMORYSTATUSEX ms;
6853
Bram Moolenaar0f873732019-12-05 20:28:46 +01006854 // Need to use GlobalMemoryStatusEx() when there is more memory than
6855 // what fits in 32 bits.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006856 ms.dwLength = sizeof(MEMORYSTATUSEX);
6857 GlobalMemoryStatusEx(&ms);
6858 if (ms.ullAvailVirtual < ms.ullTotalPhys)
Bram Moolenaaree273972016-01-02 21:11:51 +01006859 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006860 // Process address space fits in physical RAM, use all of it.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006861 return (long_u)(ms.ullAvailVirtual / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01006862 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006863 if (ms.ullTotalPhys <= WINNT_RESERVE_BYTES)
Bram Moolenaaree273972016-01-02 21:11:51 +01006864 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006865 // Catch old NT box or perverse hardware setup.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006866 return (long_u)((ms.ullTotalPhys / 2) / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01006867 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01006868 // Use physical RAM less reserve for OS + data.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006869 return (long_u)((ms.ullTotalPhys - WINNT_RESERVE_BYTES) / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01006870}
Bram Moolenaar071d4272004-06-13 20:20:40 +00006871
Bram Moolenaar071d4272004-06-13 20:20:40 +00006872/*
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006873 * mch_wrename() works around a bug in rename (aka MoveFile) in
Bram Moolenaar071d4272004-06-13 20:20:40 +00006874 * Windows 95: rename("foo.bar", "foo.bar~") will generate a
6875 * file whose short file name is "FOO.BAR" (its long file name will
6876 * be correct: "foo.bar~"). Because a file can be accessed by
6877 * either its SFN or its LFN, "foo.bar" has effectively been
6878 * renamed to "foo.bar", which is not at all what was wanted. This
6879 * seems to happen only when renaming files with three-character
6880 * extensions by appending a suffix that does not include ".".
6881 * Windows NT gets it right, however, with an SFN of "FOO~1.BAR".
6882 *
6883 * There is another problem, which isn't really a bug but isn't right either:
6884 * When renaming "abcdef~1.txt" to "abcdef~1.txt~", the short name can be
6885 * "abcdef~1.txt" again. This has been reported on Windows NT 4.0 with
6886 * service pack 6. Doesn't seem to happen on Windows 98.
6887 *
6888 * Like rename(), returns 0 upon success, non-zero upon failure.
6889 * Should probably set errno appropriately when errors occur.
6890 */
6891 int
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006892mch_wrename(WCHAR *wold, WCHAR *wnew)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006893{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006894 WCHAR *p;
6895 int i;
6896 WCHAR szTempFile[_MAX_PATH + 1];
6897 WCHAR szNewPath[_MAX_PATH + 1];
Bram Moolenaar071d4272004-06-13 20:20:40 +00006898 HANDLE hf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006899
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006900 // No need to play tricks unless the file name contains a "~" as the
6901 // seventh character.
6902 p = wold;
6903 for (i = 0; wold[i] != NUL; ++i)
6904 if ((wold[i] == '/' || wold[i] == '\\' || wold[i] == ':')
6905 && wold[i + 1] != 0)
6906 p = wold + i + 1;
6907 if ((int)(wold + i - p) < 8 || p[6] != '~')
6908 return (MoveFileW(wold, wnew) == 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006909
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006910 // Get base path of new file name. Undocumented feature: If pszNewFile is
6911 // a directory, no error is returned and pszFilePart will be NULL.
6912 if (GetFullPathNameW(wnew, _MAX_PATH, szNewPath, &p) == 0 || p == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006913 return -1;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006914 *p = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006915
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006916 // Get (and create) a unique temporary file name in directory of new file
6917 if (GetTempFileNameW(szNewPath, L"VIM", 0, szTempFile) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006918 return -2;
6919
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006920 // blow the temp file away
6921 if (!DeleteFileW(szTempFile))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006922 return -3;
6923
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006924 // rename old file to the temp file
6925 if (!MoveFileW(wold, szTempFile))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006926 return -4;
6927
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006928 // now create an empty file called pszOldFile; this prevents the operating
6929 // system using pszOldFile as an alias (SFN) if we're renaming within the
6930 // same directory. For example, we're editing a file called
6931 // filename.asc.txt by its SFN, filena~1.txt. If we rename filena~1.txt
6932 // to filena~1.txt~ (i.e., we're making a backup while writing it), the
6933 // SFN for filena~1.txt~ will be filena~1.txt, by default, which will
6934 // cause all sorts of problems later in buf_write(). So, we create an
6935 // empty file called filena~1.txt and the system will have to find some
6936 // other SFN for filena~1.txt~, such as filena~2.txt
6937 if ((hf = CreateFileW(wold, GENERIC_WRITE, 0, NULL, CREATE_NEW,
Bram Moolenaar071d4272004-06-13 20:20:40 +00006938 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
6939 return -5;
6940 if (!CloseHandle(hf))
6941 return -6;
6942
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006943 // rename the temp file to the new file
6944 if (!MoveFileW(szTempFile, wnew))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006945 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006946 // Renaming failed. Rename the file back to its old name, so that it
6947 // looks like nothing happened.
6948 (void)MoveFileW(szTempFile, wold);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006949 return -7;
6950 }
6951
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006952 // Seems to be left around on Novell filesystems
6953 DeleteFileW(szTempFile);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006954
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006955 // finally, remove the empty old file
6956 if (!DeleteFileW(wold))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006957 return -8;
6958
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006959 return 0;
6960}
6961
6962
6963/*
6964 * Converts the filenames to UTF-16, then call mch_wrename().
6965 * Like rename(), returns 0 upon success, non-zero upon failure.
6966 */
6967 int
6968mch_rename(
6969 const char *pszOldFile,
6970 const char *pszNewFile)
6971{
6972 WCHAR *wold = NULL;
6973 WCHAR *wnew = NULL;
6974 int retval = -1;
6975
6976 wold = enc_to_utf16((char_u *)pszOldFile, NULL);
6977 wnew = enc_to_utf16((char_u *)pszNewFile, NULL);
6978 if (wold != NULL && wnew != NULL)
6979 retval = mch_wrename(wold, wnew);
6980 vim_free(wold);
6981 vim_free(wnew);
6982 return retval;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006983}
6984
6985/*
6986 * Get the default shell for the current hardware platform
6987 */
6988 char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006989default_shell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006990{
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006991 return "cmd.exe";
Bram Moolenaar071d4272004-06-13 20:20:40 +00006992}
6993
6994/*
6995 * mch_access() extends access() to do more detailed check on network drives.
6996 * Returns 0 if file "n" has access rights according to "p", -1 otherwise.
6997 */
6998 int
6999mch_access(char *n, int p)
7000{
7001 HANDLE hFile;
Bram Moolenaar0f873732019-12-05 20:28:46 +01007002 int retval = -1; // default: fail
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007003 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007004
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007005 wn = enc_to_utf16((char_u *)n, NULL);
7006 if (wn == NULL)
7007 return -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007008
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01007009 if (mch_isdir((char_u *)n))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007010 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00007011 WCHAR TempNameW[_MAX_PATH + 16] = L"";
Bram Moolenaar071d4272004-06-13 20:20:40 +00007012
7013 if (p & R_OK)
7014 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007015 // Read check is performed by seeing if we can do a find file on
7016 // the directory for any file.
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007017 int i;
7018 WIN32_FIND_DATAW d;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007019
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007020 for (i = 0; i < _MAX_PATH && wn[i] != 0; ++i)
7021 TempNameW[i] = wn[i];
7022 if (TempNameW[i - 1] != '\\' && TempNameW[i - 1] != '/')
7023 TempNameW[i++] = '\\';
7024 TempNameW[i++] = '*';
7025 TempNameW[i++] = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007026
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007027 hFile = FindFirstFileW(TempNameW, &d);
7028 if (hFile == INVALID_HANDLE_VALUE)
7029 goto getout;
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007030 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00007031 (void)FindClose(hFile);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007032 }
7033
7034 if (p & W_OK)
7035 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007036 // Trying to create a temporary file in the directory should catch
7037 // directories on read-only network shares. However, in
7038 // directories whose ACL allows writes but denies deletes will end
7039 // up keeping the temporary file :-(.
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007040 if (!GetTempFileNameW(wn, L"VIM", 0, TempNameW))
7041 goto getout;
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007042 else
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007043 DeleteFileW(TempNameW);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007044 }
7045 }
7046 else
7047 {
Bram Moolenaar5aa98962018-05-06 17:09:38 +02007048 // Don't consider a file read-only if another process has opened it.
7049 DWORD share_mode = FILE_SHARE_READ | FILE_SHARE_WRITE;
7050
Bram Moolenaar0f873732019-12-05 20:28:46 +01007051 // Trying to open the file for the required access does ACL, read-only
7052 // network share, and file attribute checks.
Bram Moolenaar5aa98962018-05-06 17:09:38 +02007053 DWORD access_mode = ((p & W_OK) ? GENERIC_WRITE : 0)
7054 | ((p & R_OK) ? GENERIC_READ : 0);
7055
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007056 hFile = CreateFileW(wn, access_mode, share_mode,
7057 NULL, OPEN_EXISTING, 0, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007058 if (hFile == INVALID_HANDLE_VALUE)
7059 goto getout;
7060 CloseHandle(hFile);
7061 }
7062
Bram Moolenaar0f873732019-12-05 20:28:46 +01007063 retval = 0; // success
Bram Moolenaar071d4272004-06-13 20:20:40 +00007064getout:
Bram Moolenaar071d4272004-06-13 20:20:40 +00007065 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007066 return retval;
7067}
7068
Bram Moolenaar071d4272004-06-13 20:20:40 +00007069/*
Bram Moolenaar36f692d2008-11-20 16:10:17 +00007070 * Version of open() that may use UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007071 */
7072 int
Bram Moolenaarb6843a02017-08-02 22:07:12 +02007073mch_open(const char *name, int flags, int mode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007074{
7075 WCHAR *wn;
7076 int f;
7077
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007078 wn = enc_to_utf16((char_u *)name, NULL);
7079 if (wn == NULL)
7080 return -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007081
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007082 f = _wopen(wn, flags, mode);
7083 vim_free(wn);
7084 return f;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007085}
7086
7087/*
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007088 * Version of fopen() that uses 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 Moolenaara12a1612019-01-24 16:39:02 +01007096#if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0f873732019-12-05 20:28:46 +01007097 // Work around an annoying assertion in the Microsoft debug CRT
7098 // when mode's text/binary setting doesn't match _get_fmode().
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007099 char newMode = mode[strlen(mode) - 1];
7100 int oldMode = 0;
Bram Moolenaar0fde2902008-03-16 13:54:13 +00007101
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007102 _get_fmode(&oldMode);
7103 if (newMode == 't')
7104 _set_fmode(_O_TEXT);
7105 else if (newMode == 'b')
7106 _set_fmode(_O_BINARY);
Bram Moolenaara12a1612019-01-24 16:39:02 +01007107#endif
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007108 wn = enc_to_utf16((char_u *)name, NULL);
7109 wm = enc_to_utf16((char_u *)mode, NULL);
7110 if (wn != NULL && wm != NULL)
7111 f = _wfopen(wn, wm);
7112 vim_free(wn);
7113 vim_free(wm);
Bram Moolenaar0fde2902008-03-16 13:54:13 +00007114
Bram Moolenaara12a1612019-01-24 16:39:02 +01007115#if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007116 _set_fmode(oldMode);
Bram Moolenaara12a1612019-01-24 16:39:02 +01007117#endif
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007118 return f;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007119}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007120
Bram Moolenaar071d4272004-06-13 20:20:40 +00007121/*
7122 * SUB STREAM (aka info stream) handling:
7123 *
Bram Moolenaar8e7d6222020-12-18 19:49:56 +01007124 * NTFS can have sub streams for each file. The normal contents of a file is
7125 * stored in the main stream, and extra contents (author information, title and
7126 * so on) can be stored in a sub stream. After Windows 2000, the user can
7127 * access and store this information in sub streams via an explorer's property
7128 * menu item in the right click menu. This information in sub streams was lost
7129 * when copying only the main stream. Therefore we have to copy sub streams.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007130 *
7131 * Incomplete explanation:
7132 * http://msdn.microsoft.com/library/en-us/dnw2k/html/ntfs5.asp
7133 * More useful info and an example:
7134 * http://www.sysinternals.com/ntw2k/source/misc.shtml#streams
7135 */
7136
7137/*
7138 * Copy info stream data "substream". Read from the file with BackupRead(sh)
7139 * and write to stream "substream" of file "to".
7140 * Errors are ignored.
7141 */
7142 static void
7143copy_substream(HANDLE sh, void *context, WCHAR *to, WCHAR *substream, long len)
7144{
7145 HANDLE hTo;
7146 WCHAR *to_name;
7147
7148 to_name = malloc((wcslen(to) + wcslen(substream) + 1) * sizeof(WCHAR));
7149 wcscpy(to_name, to);
7150 wcscat(to_name, substream);
7151
7152 hTo = CreateFileW(to_name, GENERIC_WRITE, 0, NULL, OPEN_ALWAYS,
7153 FILE_ATTRIBUTE_NORMAL, NULL);
7154 if (hTo != INVALID_HANDLE_VALUE)
7155 {
7156 long done;
7157 DWORD todo;
7158 DWORD readcnt, written;
7159 char buf[4096];
7160
Bram Moolenaar0f873732019-12-05 20:28:46 +01007161 // Copy block of bytes at a time. Abort when something goes wrong.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007162 for (done = 0; done < len; done += written)
7163 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007164 // (size_t) cast for Borland C 5.5
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007165 todo = (DWORD)((size_t)(len - done) > sizeof(buf) ? sizeof(buf)
7166 : (size_t)(len - done));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007167 if (!BackupRead(sh, (LPBYTE)buf, todo, &readcnt,
7168 FALSE, FALSE, context)
7169 || readcnt != todo
7170 || !WriteFile(hTo, buf, todo, &written, NULL)
7171 || written != todo)
7172 break;
7173 }
7174 CloseHandle(hTo);
7175 }
7176
7177 free(to_name);
7178}
7179
7180/*
7181 * Copy info streams from file "from" to file "to".
7182 */
7183 static void
7184copy_infostreams(char_u *from, char_u *to)
7185{
7186 WCHAR *fromw;
7187 WCHAR *tow;
7188 HANDLE sh;
7189 WIN32_STREAM_ID sid;
7190 int headersize;
7191 WCHAR streamname[_MAX_PATH];
7192 DWORD readcount;
7193 void *context = NULL;
7194 DWORD lo, hi;
7195 int len;
7196
Bram Moolenaar0f873732019-12-05 20:28:46 +01007197 // Convert the file names to wide characters.
Bram Moolenaar36f692d2008-11-20 16:10:17 +00007198 fromw = enc_to_utf16(from, NULL);
7199 tow = enc_to_utf16(to, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007200 if (fromw != NULL && tow != NULL)
7201 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007202 // Open the file for reading.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007203 sh = CreateFileW(fromw, GENERIC_READ, FILE_SHARE_READ, NULL,
7204 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
7205 if (sh != INVALID_HANDLE_VALUE)
7206 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007207 // Use BackupRead() to find the info streams. Repeat until we
7208 // have done them all.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007209 for (;;)
7210 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007211 // Get the header to find the length of the stream name. If
7212 // the "readcount" is zero we have done all info streams.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007213 ZeroMemory(&sid, sizeof(WIN32_STREAM_ID));
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007214 headersize = (int)((char *)&sid.cStreamName - (char *)&sid.dwStreamId);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007215 if (!BackupRead(sh, (LPBYTE)&sid, headersize,
7216 &readcount, FALSE, FALSE, &context)
7217 || readcount == 0)
7218 break;
7219
Bram Moolenaar0f873732019-12-05 20:28:46 +01007220 // We only deal with streams that have a name. The normal
7221 // file data appears to be without a name, even though docs
7222 // suggest it is called "::$DATA".
Bram Moolenaar071d4272004-06-13 20:20:40 +00007223 if (sid.dwStreamNameSize > 0)
7224 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007225 // Read the stream name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007226 if (!BackupRead(sh, (LPBYTE)streamname,
7227 sid.dwStreamNameSize,
7228 &readcount, FALSE, FALSE, &context))
7229 break;
7230
Bram Moolenaar0f873732019-12-05 20:28:46 +01007231 // Copy an info stream with a name ":anything:$DATA".
7232 // Skip "::$DATA", it has no stream name (examples suggest
7233 // it might be used for the normal file contents).
7234 // Note that BackupRead() counts bytes, but the name is in
7235 // wide characters.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007236 len = readcount / sizeof(WCHAR);
7237 streamname[len] = 0;
7238 if (len > 7 && wcsicmp(streamname + len - 6,
7239 L":$DATA") == 0)
7240 {
7241 streamname[len - 6] = 0;
7242 copy_substream(sh, &context, tow, streamname,
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00007243 (long)sid.Size.u.LowPart);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007244 }
7245 }
7246
Bram Moolenaar0f873732019-12-05 20:28:46 +01007247 // Advance to the next stream. We might try seeking too far,
7248 // but BackupSeek() doesn't skip over stream borders, thus
7249 // that's OK.
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00007250 (void)BackupSeek(sh, sid.Size.u.LowPart, sid.Size.u.HighPart,
Bram Moolenaar071d4272004-06-13 20:20:40 +00007251 &lo, &hi, &context);
7252 }
7253
Bram Moolenaar0f873732019-12-05 20:28:46 +01007254 // Clear the context.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007255 (void)BackupRead(sh, NULL, 0, &readcount, TRUE, FALSE, &context);
7256
7257 CloseHandle(sh);
7258 }
7259 }
7260 vim_free(fromw);
7261 vim_free(tow);
7262}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007263
7264/*
Bram Moolenaare7bebc42021-02-01 20:50:37 +01007265 * ntdll.dll definitions
7266 */
7267#define FileEaInformation 7
7268#ifndef STATUS_SUCCESS
7269# define STATUS_SUCCESS ((NTSTATUS) 0x00000000L)
7270#endif
7271
7272typedef struct _FILE_FULL_EA_INFORMATION_ {
7273 ULONG NextEntryOffset;
7274 UCHAR Flags;
7275 UCHAR EaNameLength;
7276 USHORT EaValueLength;
7277 CHAR EaName[1];
7278} FILE_FULL_EA_INFORMATION_, *PFILE_FULL_EA_INFORMATION_;
7279
7280typedef struct _FILE_EA_INFORMATION_ {
7281 ULONG EaSize;
7282} FILE_EA_INFORMATION_, *PFILE_EA_INFORMATION_;
7283
7284typedef NTSTATUS (NTAPI *PfnNtOpenFile)(
7285 PHANDLE FileHandle,
7286 ACCESS_MASK DesiredAccess,
7287 POBJECT_ATTRIBUTES ObjectAttributes,
7288 PIO_STATUS_BLOCK IoStatusBlock,
7289 ULONG ShareAccess,
7290 ULONG OpenOptions);
7291typedef NTSTATUS (NTAPI *PfnNtClose)(
7292 HANDLE Handle);
7293typedef NTSTATUS (NTAPI *PfnNtSetEaFile)(
7294 HANDLE FileHandle,
7295 PIO_STATUS_BLOCK IoStatusBlock,
7296 PVOID Buffer,
7297 ULONG Length);
7298typedef NTSTATUS (NTAPI *PfnNtQueryEaFile)(
7299 HANDLE FileHandle,
7300 PIO_STATUS_BLOCK IoStatusBlock,
7301 PVOID Buffer,
7302 ULONG Length,
7303 BOOLEAN ReturnSingleEntry,
7304 PVOID EaList,
7305 ULONG EaListLength,
7306 PULONG EaIndex,
7307 BOOLEAN RestartScan);
7308typedef NTSTATUS (NTAPI *PfnNtQueryInformationFile)(
7309 HANDLE FileHandle,
7310 PIO_STATUS_BLOCK IoStatusBlock,
7311 PVOID FileInformation,
7312 ULONG Length,
7313 FILE_INFORMATION_CLASS FileInformationClass);
7314typedef VOID (NTAPI *PfnRtlInitUnicodeString)(
7315 PUNICODE_STRING DestinationString,
7316 PCWSTR SourceString);
7317
7318PfnNtOpenFile pNtOpenFile = NULL;
7319PfnNtClose pNtClose = NULL;
7320PfnNtSetEaFile pNtSetEaFile = NULL;
7321PfnNtQueryEaFile pNtQueryEaFile = NULL;
7322PfnNtQueryInformationFile pNtQueryInformationFile = NULL;
7323PfnRtlInitUnicodeString pRtlInitUnicodeString = NULL;
7324
7325/*
7326 * Load ntdll.dll functions.
7327 */
7328 static BOOL
7329load_ntdll(void)
7330{
7331 static int loaded = -1;
7332
7333 if (loaded == -1)
7334 {
7335 HMODULE hNtdll = GetModuleHandle("ntdll.dll");
7336 if (hNtdll != NULL)
7337 {
7338 pNtOpenFile = (PfnNtOpenFile) GetProcAddress(hNtdll, "NtOpenFile");
7339 pNtClose = (PfnNtClose) GetProcAddress(hNtdll, "NtClose");
7340 pNtSetEaFile = (PfnNtSetEaFile)
7341 GetProcAddress(hNtdll, "NtSetEaFile");
7342 pNtQueryEaFile = (PfnNtQueryEaFile)
7343 GetProcAddress(hNtdll, "NtQueryEaFile");
7344 pNtQueryInformationFile = (PfnNtQueryInformationFile)
7345 GetProcAddress(hNtdll, "NtQueryInformationFile");
7346 pRtlInitUnicodeString = (PfnRtlInitUnicodeString)
7347 GetProcAddress(hNtdll, "RtlInitUnicodeString");
7348 }
7349 if (pNtOpenFile == NULL
7350 || pNtClose == NULL
7351 || pNtSetEaFile == NULL
7352 || pNtQueryEaFile == NULL
7353 || pNtQueryInformationFile == NULL
7354 || pRtlInitUnicodeString == NULL)
7355 loaded = FALSE;
7356 else
7357 loaded = TRUE;
7358 }
7359 return (BOOL) loaded;
7360}
7361
7362/*
7363 * Copy extended attributes (EA) from file "from" to file "to".
7364 */
7365 static void
7366copy_extattr(char_u *from, char_u *to)
7367{
7368 char_u *fromf = NULL;
7369 char_u *tof = NULL;
7370 WCHAR *fromw = NULL;
7371 WCHAR *tow = NULL;
7372 UNICODE_STRING u;
7373 HANDLE h;
7374 OBJECT_ATTRIBUTES oa;
7375 IO_STATUS_BLOCK iosb;
7376 FILE_EA_INFORMATION_ eainfo = {0};
7377 void *ea = NULL;
7378
7379 if (!load_ntdll())
7380 return;
7381
7382 // Convert the file names to the fully qualified object names.
7383 fromf = alloc(STRLEN(from) + 5);
7384 tof = alloc(STRLEN(to) + 5);
7385 if (fromf == NULL || tof == NULL)
7386 goto theend;
7387 STRCPY(fromf, "\\??\\");
7388 STRCAT(fromf, from);
7389 STRCPY(tof, "\\??\\");
7390 STRCAT(tof, to);
7391
7392 // Convert the names to wide characters.
7393 fromw = enc_to_utf16(fromf, NULL);
7394 tow = enc_to_utf16(tof, NULL);
7395 if (fromw == NULL || tow == NULL)
7396 goto theend;
7397
7398 // Get the EA.
7399 pRtlInitUnicodeString(&u, fromw);
7400 InitializeObjectAttributes(&oa, &u, 0, NULL, NULL);
7401 if (pNtOpenFile(&h, FILE_READ_EA, &oa, &iosb, 0,
7402 FILE_NON_DIRECTORY_FILE) != STATUS_SUCCESS)
7403 goto theend;
7404 pNtQueryInformationFile(h, &iosb, &eainfo, sizeof(eainfo),
7405 FileEaInformation);
7406 if (eainfo.EaSize != 0)
7407 {
7408 ea = alloc(eainfo.EaSize);
7409 if (ea != NULL)
7410 {
7411 if (pNtQueryEaFile(h, &iosb, ea, eainfo.EaSize, FALSE,
7412 NULL, 0, NULL, TRUE) != STATUS_SUCCESS)
7413 {
7414 vim_free(ea);
7415 ea = NULL;
7416 }
7417 }
7418 }
7419 pNtClose(h);
7420
7421 // Set the EA.
7422 if (ea != NULL)
7423 {
7424 pRtlInitUnicodeString(&u, tow);
7425 InitializeObjectAttributes(&oa, &u, 0, NULL, NULL);
7426 if (pNtOpenFile(&h, FILE_WRITE_EA, &oa, &iosb, 0,
7427 FILE_NON_DIRECTORY_FILE) != STATUS_SUCCESS)
7428 goto theend;
7429
7430 pNtSetEaFile(h, &iosb, ea, eainfo.EaSize);
7431 pNtClose(h);
7432 }
7433
7434theend:
7435 vim_free(fromf);
7436 vim_free(tof);
7437 vim_free(fromw);
7438 vim_free(tow);
7439 vim_free(ea);
7440}
7441
7442/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00007443 * Copy file attributes from file "from" to file "to".
7444 * For Windows NT and later we copy info streams.
7445 * Always returns zero, errors are ignored.
7446 */
7447 int
7448mch_copy_file_attribute(char_u *from, char_u *to)
7449{
Bram Moolenaar0f873732019-12-05 20:28:46 +01007450 // File streams only work on Windows NT and later.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007451 copy_infostreams(from, to);
Bram Moolenaare7bebc42021-02-01 20:50:37 +01007452 copy_extattr(from, to);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007453 return 0;
7454}
7455
7456#if defined(MYRESETSTKOFLW) || defined(PROTO)
7457/*
7458 * Recreate a destroyed stack guard page in win32.
7459 * Written by Benjamin Peterson.
7460 */
7461
Bram Moolenaar0f873732019-12-05 20:28:46 +01007462// These magic numbers are from the MS header files
Bram Moolenaarc4568ab2018-11-16 16:21:05 +01007463# define MIN_STACK_WINNT 2
Bram Moolenaar071d4272004-06-13 20:20:40 +00007464
7465/*
7466 * This function does the same thing as _resetstkoflw(), which is only
7467 * available in DevStudio .net and later.
7468 * Returns 0 for failure, 1 for success.
7469 */
7470 int
7471myresetstkoflw(void)
7472{
7473 BYTE *pStackPtr;
7474 BYTE *pGuardPage;
7475 BYTE *pStackBase;
7476 BYTE *pLowestPossiblePage;
7477 MEMORY_BASIC_INFORMATION mbi;
7478 SYSTEM_INFO si;
7479 DWORD nPageSize;
7480 DWORD dummy;
7481
Bram Moolenaar0f873732019-12-05 20:28:46 +01007482 // We need to know the system page size.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007483 GetSystemInfo(&si);
7484 nPageSize = si.dwPageSize;
7485
Bram Moolenaar0f873732019-12-05 20:28:46 +01007486 // ...and the current stack pointer
Bram Moolenaar071d4272004-06-13 20:20:40 +00007487 pStackPtr = (BYTE*)_alloca(1);
7488
Bram Moolenaar0f873732019-12-05 20:28:46 +01007489 // ...and the base of the stack.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007490 if (VirtualQuery(pStackPtr, &mbi, sizeof mbi) == 0)
7491 return 0;
7492 pStackBase = (BYTE*)mbi.AllocationBase;
7493
Bram Moolenaar4b96df52020-01-26 22:00:26 +01007494 // ...and the page that's min_stack_req pages away from stack base; this is
Bram Moolenaar0f873732019-12-05 20:28:46 +01007495 // the lowest page we could use.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007496 pLowestPossiblePage = pStackBase + MIN_STACK_WINNT * nPageSize;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007497
Bram Moolenaar071d4272004-06-13 20:20:40 +00007498 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007499 // We want the first committed page in the stack Start at the stack
7500 // base and move forward through memory until we find a committed block.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007501 BYTE *pBlock = pStackBase;
7502
Bram Moolenaara466c992005-07-09 21:03:22 +00007503 for (;;)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007504 {
7505 if (VirtualQuery(pBlock, &mbi, sizeof mbi) == 0)
7506 return 0;
7507
7508 pBlock += mbi.RegionSize;
7509
7510 if (mbi.State & MEM_COMMIT)
7511 break;
7512 }
7513
Bram Moolenaar0f873732019-12-05 20:28:46 +01007514 // mbi now describes the first committed block in the stack.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007515 if (mbi.Protect & PAGE_GUARD)
7516 return 1;
7517
Bram Moolenaar0f873732019-12-05 20:28:46 +01007518 // decide where the guard page should start
Bram Moolenaar071d4272004-06-13 20:20:40 +00007519 if ((long_u)(mbi.BaseAddress) < (long_u)pLowestPossiblePage)
7520 pGuardPage = pLowestPossiblePage;
7521 else
7522 pGuardPage = (BYTE*)mbi.BaseAddress;
7523
Bram Moolenaar0f873732019-12-05 20:28:46 +01007524 // allocate the guard page
Bram Moolenaar071d4272004-06-13 20:20:40 +00007525 if (!VirtualAlloc(pGuardPage, nPageSize, MEM_COMMIT, PAGE_READWRITE))
7526 return 0;
7527
Bram Moolenaar0f873732019-12-05 20:28:46 +01007528 // apply the guard attribute to the page
Bram Moolenaar071d4272004-06-13 20:20:40 +00007529 if (!VirtualProtect(pGuardPage, nPageSize, PAGE_READWRITE | PAGE_GUARD,
7530 &dummy))
7531 return 0;
7532 }
7533
7534 return 1;
7535}
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007536#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007537
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007538
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007539/*
7540 * The command line arguments in UCS2
7541 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00007542static int nArgsW = 0;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007543static LPWSTR *ArglistW = NULL;
7544static int global_argc = 0;
7545static char **global_argv;
7546
Bram Moolenaar0f873732019-12-05 20:28:46 +01007547static int used_file_argc = 0; // last argument in global_argv[] used
7548 // for the argument list.
7549static int *used_file_indexes = NULL; // indexes in global_argv[] for
7550 // command line arguments added to
7551 // the argument list
7552static int used_file_count = 0; // nr of entries in used_file_indexes
7553static int used_file_literal = FALSE; // take file names literally
7554static int used_file_full_path = FALSE; // file name was full path
7555static int used_file_diff_mode = FALSE; // file name was with diff mode
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007556static int used_alist_count = 0;
7557
7558
7559/*
7560 * Get the command line arguments. Unicode version.
7561 * Returns argc. Zero when something fails.
7562 */
7563 int
7564get_cmd_argsW(char ***argvp)
7565{
7566 char **argv = NULL;
7567 int argc = 0;
7568 int i;
7569
Bram Moolenaar14993322014-09-09 12:25:33 +02007570 free_cmd_argsW();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007571 ArglistW = CommandLineToArgvW(GetCommandLineW(), &nArgsW);
7572 if (ArglistW != NULL)
7573 {
7574 argv = malloc((nArgsW + 1) * sizeof(char *));
7575 if (argv != NULL)
7576 {
7577 argc = nArgsW;
7578 argv[argc] = NULL;
7579 for (i = 0; i < argc; ++i)
7580 {
7581 int len;
7582
Bram Moolenaar0f873732019-12-05 20:28:46 +01007583 // Convert each Unicode argument to the current codepage.
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007584 WideCharToMultiByte_alloc(GetACP(), 0,
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007585 ArglistW[i], (int)wcslen(ArglistW[i]) + 1,
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007586 (LPSTR *)&argv[i], &len, 0, 0);
7587 if (argv[i] == NULL)
7588 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007589 // Out of memory, clear everything.
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007590 while (i > 0)
7591 free(argv[--i]);
7592 free(argv);
Bram Moolenaar73c61632013-12-07 14:48:10 +01007593 argv = NULL;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007594 argc = 0;
7595 }
7596 }
7597 }
7598 }
7599
7600 global_argc = argc;
7601 global_argv = argv;
7602 if (argc > 0)
Bram Moolenaar14993322014-09-09 12:25:33 +02007603 {
7604 if (used_file_indexes != NULL)
7605 free(used_file_indexes);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007606 used_file_indexes = malloc(argc * sizeof(int));
Bram Moolenaar14993322014-09-09 12:25:33 +02007607 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007608
7609 if (argvp != NULL)
7610 *argvp = argv;
7611 return argc;
7612}
7613
7614 void
7615free_cmd_argsW(void)
7616{
7617 if (ArglistW != NULL)
7618 {
7619 GlobalFree(ArglistW);
7620 ArglistW = NULL;
7621 }
7622}
7623
7624/*
7625 * Remember "name" is an argument that was added to the argument list.
7626 * This avoids that we have to re-parse the argument list when fix_arg_enc()
7627 * is called.
7628 */
7629 void
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007630used_file_arg(char *name, int literal, int full_path, int diff_mode)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007631{
7632 int i;
7633
7634 if (used_file_indexes == NULL)
7635 return;
7636 for (i = used_file_argc + 1; i < global_argc; ++i)
7637 if (STRCMP(global_argv[i], name) == 0)
7638 {
7639 used_file_argc = i;
7640 used_file_indexes[used_file_count++] = i;
7641 break;
7642 }
7643 used_file_literal = literal;
7644 used_file_full_path = full_path;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007645 used_file_diff_mode = diff_mode;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007646}
7647
7648/*
7649 * Remember the length of the argument list as it was. If it changes then we
7650 * leave it alone when 'encoding' is set.
7651 */
7652 void
7653set_alist_count(void)
7654{
7655 used_alist_count = GARGCOUNT;
7656}
7657
7658/*
7659 * Fix the encoding of the command line arguments. Invoked when 'encoding'
7660 * has been changed while starting up. Use the UCS-2 command line arguments
7661 * and convert them to 'encoding'.
7662 */
7663 void
7664fix_arg_enc(void)
7665{
7666 int i;
7667 int idx;
7668 char_u *str;
Bram Moolenaar86b68352004-12-27 21:59:20 +00007669 int *fnum_list;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007670
Bram Moolenaar0f873732019-12-05 20:28:46 +01007671 // Safety checks:
7672 // - if argument count differs between the wide and non-wide argument
7673 // list, something must be wrong.
7674 // - the file name arguments must have been located.
7675 // - the length of the argument list wasn't changed by the user.
Bram Moolenaard857f0e2005-06-21 22:37:39 +00007676 if (global_argc != nArgsW
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007677 || ArglistW == NULL
7678 || used_file_indexes == NULL
7679 || used_file_count == 0
7680 || used_alist_count != GARGCOUNT)
7681 return;
7682
Bram Moolenaar0f873732019-12-05 20:28:46 +01007683 // Remember the buffer numbers for the arguments.
Bram Moolenaarc799fe22019-05-28 23:08:19 +02007684 fnum_list = ALLOC_MULT(int, GARGCOUNT);
Bram Moolenaar86b68352004-12-27 21:59:20 +00007685 if (fnum_list == NULL)
Bram Moolenaar0f873732019-12-05 20:28:46 +01007686 return; // out of memory
Bram Moolenaar86b68352004-12-27 21:59:20 +00007687 for (i = 0; i < GARGCOUNT; ++i)
7688 fnum_list[i] = GARGLIST[i].ae_fnum;
7689
Bram Moolenaar0f873732019-12-05 20:28:46 +01007690 // Clear the argument list. Make room for the new arguments.
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007691 alist_clear(&global_alist);
7692 if (ga_grow(&global_alist.al_ga, used_file_count) == FAIL)
Bram Moolenaar0f873732019-12-05 20:28:46 +01007693 return; // out of memory
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007694
7695 for (i = 0; i < used_file_count; ++i)
7696 {
7697 idx = used_file_indexes[i];
Bram Moolenaar36f692d2008-11-20 16:10:17 +00007698 str = utf16_to_enc(ArglistW[idx], NULL);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007699 if (str != NULL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00007700 {
Bram Moolenaar39d21e32017-08-05 23:09:31 +02007701 int literal = used_file_literal;
7702
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007703#ifdef FEAT_DIFF
Bram Moolenaar0f873732019-12-05 20:28:46 +01007704 // When using diff mode may need to concatenate file name to
7705 // directory name. Just like it's done in main().
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007706 if (used_file_diff_mode && mch_isdir(str) && GARGCOUNT > 0
7707 && !mch_isdir(alist_name(&GARGLIST[0])))
7708 {
7709 char_u *r;
7710
7711 r = concat_fnames(str, gettail(alist_name(&GARGLIST[0])), TRUE);
7712 if (r != NULL)
7713 {
7714 vim_free(str);
7715 str = r;
7716 }
7717 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007718#endif
Bram Moolenaar0f873732019-12-05 20:28:46 +01007719 // Re-use the old buffer by renaming it. When not using literal
7720 // names it's done by alist_expand() below.
Bram Moolenaar86b68352004-12-27 21:59:20 +00007721 if (used_file_literal)
7722 buf_set_name(fnum_list[i], str);
7723
Bram Moolenaar0f873732019-12-05 20:28:46 +01007724 // Check backtick literal. backtick literal is already expanded in
7725 // main.c, so this part add str as literal.
Bram Moolenaar39d21e32017-08-05 23:09:31 +02007726 if (literal == FALSE)
7727 {
Bram Moolenaar116a0f82017-08-07 21:17:57 +02007728 size_t len = STRLEN(str);
7729
Bram Moolenaar39d21e32017-08-05 23:09:31 +02007730 if (len > 2 && *str == '`' && *(str + len - 1) == '`')
7731 literal = TRUE;
7732 }
7733 alist_add(&global_alist, str, literal ? 2 : 0);
Bram Moolenaar86b68352004-12-27 21:59:20 +00007734 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007735 }
7736
7737 if (!used_file_literal)
7738 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007739 // Now expand wildcards in the arguments.
7740 // Temporarily add '(' and ')' to 'isfname'. These are valid
7741 // filename characters but are excluded from 'isfname' to make
7742 // "gf" work on a file name in parenthesis (e.g.: see vim.h).
7743 // Also, unset wildignore to not be influenced by this option.
7744 // The arguments specified in command-line should be kept even if
7745 // encoding options were changed.
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007746 do_cmdline_cmd((char_u *)":let SaVe_ISF = &isf|set isf+=(,)");
Bram Moolenaar20586cb2018-03-08 22:03:14 +01007747 do_cmdline_cmd((char_u *)":let SaVe_WIG = &wig|set wig=");
Bram Moolenaar86b68352004-12-27 21:59:20 +00007748 alist_expand(fnum_list, used_alist_count);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007749 do_cmdline_cmd((char_u *)":let &isf = SaVe_ISF|unlet SaVe_ISF");
Bram Moolenaar20586cb2018-03-08 22:03:14 +01007750 do_cmdline_cmd((char_u *)":let &wig = SaVe_WIG|unlet SaVe_WIG");
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007751 }
7752
Bram Moolenaar0f873732019-12-05 20:28:46 +01007753 // If wildcard expansion failed, we are editing the first file of the
7754 // arglist and there is no file name: Edit the first argument now.
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007755 if (curwin->w_arg_idx == 0 && curbuf->b_fname == NULL)
7756 {
7757 do_cmdline_cmd((char_u *)":rewind");
7758 if (GARGCOUNT == 1 && used_file_full_path)
Bram Moolenaarb7407d32018-02-03 17:36:27 +01007759 (void)vim_chdirfile(alist_name(&GARGLIST[0]), "drop");
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007760 }
Bram Moolenaar86b68352004-12-27 21:59:20 +00007761
7762 set_alist_count();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007763}
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007764
7765 int
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02007766mch_setenv(char *var, char *value, int x UNUSED)
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007767{
7768 char_u *envbuf;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007769 WCHAR *p;
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007770
Bram Moolenaar964b3742019-05-24 18:54:09 +02007771 envbuf = alloc(STRLEN(var) + STRLEN(value) + 2);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007772 if (envbuf == NULL)
7773 return -1;
7774
7775 sprintf((char *)envbuf, "%s=%s", var, value);
7776
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007777 p = enc_to_utf16(envbuf, NULL);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007778
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007779 vim_free(envbuf);
7780 if (p == NULL)
7781 return -1;
7782 _wputenv(p);
Bram Moolenaara12a1612019-01-24 16:39:02 +01007783#ifdef libintl_wputenv
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007784 libintl_wputenv(p);
Bram Moolenaara12a1612019-01-24 16:39:02 +01007785#endif
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007786 // Unlike Un*x systems, we can free the string for _wputenv().
7787 vim_free(p);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007788
7789 return 0;
7790}
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007791
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007792/*
7793 * Support for 256 colors and 24-bit colors was added in Windows 10
7794 * version 1703 (Creators update).
7795 */
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007796#define VTP_FIRST_SUPPORT_BUILD MAKE_VER(10, 0, 15063)
7797
7798/*
7799 * Support for pseudo-console (ConPTY) was added in windows 10
Bram Moolenaar57da6982019-09-13 22:30:11 +02007800 * version 1809 (October 2018 update).
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007801 */
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01007802#define CONPTY_FIRST_SUPPORT_BUILD MAKE_VER(10, 0, 17763)
Bram Moolenaar57da6982019-09-13 22:30:11 +02007803
7804/*
7805 * ConPTY differences between versions, need different logic.
7806 * version 1903 (May 2019 update).
7807 */
7808#define CONPTY_1903_BUILD MAKE_VER(10, 0, 18362)
7809
7810/*
Bram Moolenaar36e7a822019-11-13 21:49:24 +01007811 * version 1909 (November 2019 update).
7812 */
7813#define CONPTY_1909_BUILD MAKE_VER(10, 0, 18363)
7814
7815/*
Bram Moolenaar7ed8f592020-04-28 20:44:42 +02007816 * Stay ahead of the next update, and when it's done, fix this.
7817 * version ? (2020 update, temporarily use the build number of insider preview)
7818 */
7819#define CONPTY_NEXT_UPDATE_BUILD MAKE_VER(10, 0, 19587)
7820
7821/*
Bram Moolenaar57da6982019-09-13 22:30:11 +02007822 * Confirm until this version. Also the logic changes.
7823 * insider preview.
7824 */
Bram Moolenaar4c063dd2019-10-04 21:29:12 +02007825#define CONPTY_INSIDER_BUILD MAKE_VER(10, 0, 18995)
Bram Moolenaar57da6982019-09-13 22:30:11 +02007826
7827/*
7828 * Not stable now.
7829 */
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01007830#define CONPTY_STABLE_BUILD MAKE_VER(10, 0, 32767) // T.B.D.
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007831
7832 static void
7833vtp_flag_init(void)
7834{
7835 DWORD ver = get_build_number();
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007836#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007837 DWORD mode;
7838 HANDLE out;
7839
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007840# ifdef VIMDLL
7841 if (!gui.in_use)
7842# endif
7843 {
7844 out = GetStdHandle(STD_OUTPUT_HANDLE);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007845
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007846 vtp_working = (ver >= VTP_FIRST_SUPPORT_BUILD) ? 1 : 0;
7847 GetConsoleMode(out, &mode);
7848 mode |= (ENABLE_PROCESSED_OUTPUT | ENABLE_VIRTUAL_TERMINAL_PROCESSING);
7849 if (SetConsoleMode(out, mode) == 0)
7850 vtp_working = 0;
7851 }
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007852#endif
7853
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007854 if (ver >= CONPTY_FIRST_SUPPORT_BUILD)
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01007855 conpty_working = 1;
7856 if (ver >= CONPTY_STABLE_BUILD)
7857 conpty_stable = 1;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007858
Bram Moolenaar57da6982019-09-13 22:30:11 +02007859 if (ver <= CONPTY_INSIDER_BUILD)
7860 conpty_type = 3;
Bram Moolenaar36e7a822019-11-13 21:49:24 +01007861 if (ver <= CONPTY_1909_BUILD)
7862 conpty_type = 2;
Bram Moolenaar57da6982019-09-13 22:30:11 +02007863 if (ver <= CONPTY_1903_BUILD)
7864 conpty_type = 2;
7865 if (ver < CONPTY_FIRST_SUPPORT_BUILD)
7866 conpty_type = 1;
Bram Moolenaar7ed8f592020-04-28 20:44:42 +02007867
7868 if (ver >= CONPTY_NEXT_UPDATE_BUILD)
7869 conpty_fix_type = 1;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007870}
7871
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007872#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL) || defined(PROTO)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007873
7874 static void
7875vtp_init(void)
7876{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007877 HMODULE hKerneldll;
7878 DYN_CONSOLE_SCREEN_BUFFER_INFOEX csbi;
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007879# ifdef FEAT_TERMGUICOLORS
7880 COLORREF fg, bg;
7881# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007882
Bram Moolenaar0f873732019-12-05 20:28:46 +01007883 // Use functions supported from Vista
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007884 hKerneldll = GetModuleHandle("kernel32.dll");
7885 if (hKerneldll != NULL)
7886 {
7887 pGetConsoleScreenBufferInfoEx =
7888 (PfnGetConsoleScreenBufferInfoEx)GetProcAddress(
7889 hKerneldll, "GetConsoleScreenBufferInfoEx");
7890 pSetConsoleScreenBufferInfoEx =
7891 (PfnSetConsoleScreenBufferInfoEx)GetProcAddress(
7892 hKerneldll, "SetConsoleScreenBufferInfoEx");
7893 if (pGetConsoleScreenBufferInfoEx != NULL
7894 && pSetConsoleScreenBufferInfoEx != NULL)
7895 has_csbiex = TRUE;
7896 }
7897
7898 csbi.cbSize = sizeof(csbi);
7899 if (has_csbiex)
7900 pGetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007901 save_console_bg_rgb = (guicolor_T)csbi.ColorTable[g_color_index_bg];
7902 save_console_fg_rgb = (guicolor_T)csbi.ColorTable[g_color_index_fg];
Bram Moolenaardf543822020-01-30 11:53:59 +01007903 store_console_bg_rgb = save_console_bg_rgb;
7904 store_console_fg_rgb = save_console_fg_rgb;
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007905
7906# ifdef FEAT_TERMGUICOLORS
7907 bg = (COLORREF)csbi.ColorTable[g_color_index_bg];
7908 fg = (COLORREF)csbi.ColorTable[g_color_index_fg];
7909 bg = (GetRValue(bg) << 16) | (GetGValue(bg) << 8) | GetBValue(bg);
7910 fg = (GetRValue(fg) << 16) | (GetGValue(fg) << 8) | GetBValue(fg);
7911 default_console_color_bg = bg;
7912 default_console_color_fg = fg;
Bram Moolenaarc4568ab2018-11-16 16:21:05 +01007913# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007914
7915 set_console_color_rgb();
7916}
7917
7918 static void
7919vtp_exit(void)
7920{
Bram Moolenaardf543822020-01-30 11:53:59 +01007921 restore_console_color_rgb();
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007922}
7923
Bram Moolenaar06b7b582020-05-30 17:49:25 +02007924 int
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007925vtp_printf(
7926 char *format,
7927 ...)
7928{
7929 char_u buf[100];
7930 va_list list;
7931 DWORD result;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007932 int len;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007933
7934 va_start(list, format);
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007935 len = vim_vsnprintf((char *)buf, 100, (char *)format, list);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007936 va_end(list);
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007937 WriteConsoleA(g_hConOut, buf, (DWORD)len, &result, NULL);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007938 return (int)result;
7939}
7940
7941 static void
7942vtp_sgr_bulk(
7943 int arg)
7944{
7945 int args[1];
7946
7947 args[0] = arg;
7948 vtp_sgr_bulks(1, args);
7949}
7950
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007951#define FAST256(x) \
7952 if ((*p-- = "0123456789"[(n = x % 10)]) \
7953 && x >= 10 && (*p-- = "0123456789"[((m = x % 100) - n) / 10]) \
7954 && x >= 100 && (*p-- = "012"[((x & 0xff) - m) / 100]));
7955
7956#define FAST256CASE(x) \
7957 case x: \
7958 FAST256(newargs[x - 1]);
7959
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007960 static void
7961vtp_sgr_bulks(
7962 int argc,
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007963 int *args)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007964{
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007965#define MAXSGR 16
7966#define SGRBUFSIZE 2 + 4 * MAXSGR + 1 // '\033[' + SGR + 'm'
7967 char_u buf[SGRBUFSIZE];
7968 char_u *p;
7969 int in, out;
7970 int newargs[16];
7971 static int sgrfgr = -1, sgrfgg, sgrfgb;
7972 static int sgrbgr = -1, sgrbgg, sgrbgb;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007973
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007974 if (argc == 0)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007975 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007976 sgrfgr = sgrbgr = -1;
7977 vtp_printf("033[m");
7978 return;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007979 }
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007980
7981 in = out = 0;
7982 while (in < argc)
7983 {
7984 int s = args[in];
7985 int copylen = 1;
7986
7987 if (s == 38)
7988 {
7989 if (argc - in >= 5 && args[in + 1] == 2)
7990 {
7991 if (sgrfgr == args[in + 2] && sgrfgg == args[in + 3]
7992 && sgrfgb == args[in + 4])
7993 {
7994 in += 5;
7995 copylen = 0;
7996 }
7997 else
7998 {
7999 sgrfgr = args[in + 2];
8000 sgrfgg = args[in + 3];
8001 sgrfgb = args[in + 4];
8002 copylen = 5;
8003 }
8004 }
8005 else if (argc - in >= 3 && args[in + 1] == 5)
8006 {
8007 sgrfgr = -1;
8008 copylen = 3;
8009 }
8010 }
8011 else if (s == 48)
8012 {
8013 if (argc - in >= 5 && args[in + 1] == 2)
8014 {
8015 if (sgrbgr == args[in + 2] && sgrbgg == args[in + 3]
8016 && sgrbgb == args[in + 4])
8017 {
8018 in += 5;
8019 copylen = 0;
8020 }
8021 else
8022 {
8023 sgrbgr = args[in + 2];
8024 sgrbgg = args[in + 3];
8025 sgrbgb = args[in + 4];
8026 copylen = 5;
8027 }
8028 }
8029 else if (argc - in >= 3 && args[in + 1] == 5)
8030 {
8031 sgrbgr = -1;
8032 copylen = 3;
8033 }
8034 }
8035 else if (30 <= s && s <= 39)
8036 sgrfgr = -1;
8037 else if (90 <= s && s <= 97)
8038 sgrfgr = -1;
8039 else if (40 <= s && s <= 49)
8040 sgrbgr = -1;
8041 else if (100 <= s && s <= 107)
8042 sgrbgr = -1;
8043 else if (s == 0)
8044 sgrfgr = sgrbgr = -1;
8045
8046 while (copylen--)
8047 newargs[out++] = args[in++];
8048 }
8049
8050 p = &buf[sizeof(buf) - 1];
8051 *p-- = 'm';
8052
8053 switch (out)
8054 {
8055 int n, m;
8056 DWORD r;
8057
8058 FAST256CASE(16);
8059 *p-- = ';';
8060 FAST256CASE(15);
8061 *p-- = ';';
8062 FAST256CASE(14);
8063 *p-- = ';';
8064 FAST256CASE(13);
8065 *p-- = ';';
8066 FAST256CASE(12);
8067 *p-- = ';';
8068 FAST256CASE(11);
8069 *p-- = ';';
8070 FAST256CASE(10);
8071 *p-- = ';';
8072 FAST256CASE(9);
8073 *p-- = ';';
8074 FAST256CASE(8);
8075 *p-- = ';';
8076 FAST256CASE(7);
8077 *p-- = ';';
8078 FAST256CASE(6);
8079 *p-- = ';';
8080 FAST256CASE(5);
8081 *p-- = ';';
8082 FAST256CASE(4);
8083 *p-- = ';';
8084 FAST256CASE(3);
8085 *p-- = ';';
8086 FAST256CASE(2);
8087 *p-- = ';';
8088 FAST256CASE(1);
8089 *p-- = '[';
8090 *p = '\033';
8091 WriteConsoleA(g_hConOut, p, (DWORD)(&buf[SGRBUFSIZE] - p), &r, NULL);
8092 default:
8093 break;
8094 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008095}
8096
Bram Moolenaar06b7b582020-05-30 17:49:25 +02008097 static void
8098wt_init(void)
8099{
8100 wt_working = (mch_getenv("WT_SESSION") != NULL);
8101}
8102
8103 int
8104use_wt(void)
8105{
8106 return USE_WT;
8107}
8108
Bram Moolenaar8a938af2018-05-01 17:30:41 +02008109# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02008110 static int
8111ctermtoxterm(
8112 int cterm)
8113{
Bram Moolenaar9894e392018-05-05 14:29:06 +02008114 char_u r, g, b, idx;
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02008115
8116 cterm_color2rgb(cterm, &r, &g, &b, &idx);
8117 return (((int)r << 16) | ((int)g << 8) | (int)b);
8118}
Bram Moolenaar8a938af2018-05-01 17:30:41 +02008119# endif
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02008120
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008121 static void
8122set_console_color_rgb(void)
8123{
8124# ifdef FEAT_TERMGUICOLORS
8125 DYN_CONSOLE_SCREEN_BUFFER_INFOEX csbi;
Bram Moolenaara050b942019-12-02 21:35:31 +01008126 guicolor_T fg, bg;
8127 int ctermfg, ctermbg;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008128
8129 if (!USE_VTP)
8130 return;
8131
Bram Moolenaara050b942019-12-02 21:35:31 +01008132 get_default_console_color(&ctermfg, &ctermbg, &fg, &bg);
8133
Bram Moolenaar06b7b582020-05-30 17:49:25 +02008134 if (USE_WT)
8135 {
8136 term_fg_rgb_color(fg);
8137 term_bg_rgb_color(bg);
8138 return;
8139 }
8140
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008141 fg = (GetRValue(fg) << 16) | (GetGValue(fg) << 8) | GetBValue(fg);
8142 bg = (GetRValue(bg) << 16) | (GetGValue(bg) << 8) | GetBValue(bg);
8143
8144 csbi.cbSize = sizeof(csbi);
8145 if (has_csbiex)
8146 pGetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
8147
8148 csbi.cbSize = sizeof(csbi);
8149 csbi.srWindow.Right += 1;
8150 csbi.srWindow.Bottom += 1;
Bram Moolenaardf543822020-01-30 11:53:59 +01008151 store_console_bg_rgb = csbi.ColorTable[g_color_index_bg];
8152 store_console_fg_rgb = csbi.ColorTable[g_color_index_fg];
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02008153 csbi.ColorTable[g_color_index_bg] = (COLORREF)bg;
8154 csbi.ColorTable[g_color_index_fg] = (COLORREF)fg;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008155 if (has_csbiex)
8156 pSetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
8157# endif
8158}
8159
Bram Moolenaara050b942019-12-02 21:35:31 +01008160# if defined(FEAT_TERMGUICOLORS) || defined(PROTO)
8161 void
8162get_default_console_color(
8163 int *cterm_fg,
8164 int *cterm_bg,
8165 guicolor_T *gui_fg,
8166 guicolor_T *gui_bg)
8167{
8168 int id;
8169 guicolor_T guifg = INVALCOLOR;
8170 guicolor_T guibg = INVALCOLOR;
8171 int ctermfg = 0;
8172 int ctermbg = 0;
8173
8174 id = syn_name2id((char_u *)"Normal");
8175 if (id > 0 && p_tgc)
8176 syn_id2colors(id, &guifg, &guibg);
8177 if (guifg == INVALCOLOR)
8178 {
8179 ctermfg = -1;
8180 if (id > 0)
8181 syn_id2cterm_bg(id, &ctermfg, &ctermbg);
8182 guifg = ctermfg != -1 ? ctermtoxterm(ctermfg)
8183 : default_console_color_fg;
8184 cterm_normal_fg_gui_color = guifg;
8185 ctermfg = ctermfg < 0 ? 0 : ctermfg;
8186 }
8187 if (guibg == INVALCOLOR)
8188 {
8189 ctermbg = -1;
8190 if (id > 0)
8191 syn_id2cterm_bg(id, &ctermfg, &ctermbg);
8192 guibg = ctermbg != -1 ? ctermtoxterm(ctermbg)
8193 : default_console_color_bg;
8194 cterm_normal_bg_gui_color = guibg;
8195 ctermbg = ctermbg < 0 ? 0 : ctermbg;
8196 }
8197
8198 *cterm_fg = ctermfg;
8199 *cterm_bg = ctermbg;
8200 *gui_fg = guifg;
8201 *gui_bg = guibg;
8202}
8203# endif
8204
Bram Moolenaardf543822020-01-30 11:53:59 +01008205/*
8206 * Set the console colors to the original colors or the last set colors.
8207 */
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008208 static void
8209reset_console_color_rgb(void)
8210{
8211# ifdef FEAT_TERMGUICOLORS
8212 DYN_CONSOLE_SCREEN_BUFFER_INFOEX csbi;
8213
Bram Moolenaar06b7b582020-05-30 17:49:25 +02008214 if (USE_WT)
8215 return;
8216
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008217 csbi.cbSize = sizeof(csbi);
8218 if (has_csbiex)
8219 pGetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
8220
8221 csbi.cbSize = sizeof(csbi);
8222 csbi.srWindow.Right += 1;
8223 csbi.srWindow.Bottom += 1;
Bram Moolenaardf543822020-01-30 11:53:59 +01008224 csbi.ColorTable[g_color_index_bg] = (COLORREF)store_console_bg_rgb;
8225 csbi.ColorTable[g_color_index_fg] = (COLORREF)store_console_fg_rgb;
8226 if (has_csbiex)
8227 pSetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
8228# endif
8229}
8230
8231/*
8232 * Set the console colors to the original colors.
8233 */
8234 static void
8235restore_console_color_rgb(void)
8236{
8237# ifdef FEAT_TERMGUICOLORS
8238 DYN_CONSOLE_SCREEN_BUFFER_INFOEX csbi;
8239
8240 csbi.cbSize = sizeof(csbi);
8241 if (has_csbiex)
8242 pGetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
8243
8244 csbi.cbSize = sizeof(csbi);
8245 csbi.srWindow.Right += 1;
8246 csbi.srWindow.Bottom += 1;
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02008247 csbi.ColorTable[g_color_index_bg] = (COLORREF)save_console_bg_rgb;
8248 csbi.ColorTable[g_color_index_fg] = (COLORREF)save_console_fg_rgb;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008249 if (has_csbiex)
8250 pSetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
8251# endif
8252}
8253
8254 void
8255control_console_color_rgb(void)
8256{
8257 if (USE_VTP)
8258 set_console_color_rgb();
8259 else
8260 reset_console_color_rgb();
8261}
8262
8263 int
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008264use_vtp(void)
8265{
8266 return USE_VTP;
8267}
8268
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02008269 int
8270is_term_win32(void)
8271{
8272 return T_NAME != NULL && STRCMP(T_NAME, "win32") == 0;
8273}
8274
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008275 int
8276has_vtp_working(void)
8277{
8278 return vtp_working;
8279}
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01008280
Bram Moolenaar6902c0e2019-02-16 14:07:37 +01008281#endif
8282
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01008283 int
8284has_conpty_working(void)
8285{
8286 return conpty_working;
8287}
8288
8289 int
Bram Moolenaar57da6982019-09-13 22:30:11 +02008290get_conpty_type(void)
8291{
8292 return conpty_type;
8293}
8294
8295 int
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01008296is_conpty_stable(void)
8297{
8298 return conpty_stable;
8299}
Bram Moolenaar78d21da2019-02-17 15:00:52 +01008300
Bram Moolenaar7ed8f592020-04-28 20:44:42 +02008301 int
8302get_conpty_fix_type(void)
8303{
8304 return conpty_fix_type;
8305}
8306
Bram Moolenaarafde13b2019-04-28 19:46:49 +02008307#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL) || defined(PROTO)
Bram Moolenaar78d21da2019-02-17 15:00:52 +01008308 void
8309resize_console_buf(void)
8310{
8311 CONSOLE_SCREEN_BUFFER_INFO csbi;
8312 COORD coord;
8313 SMALL_RECT newsize;
8314
8315 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
8316 {
8317 coord.X = SRWIDTH(csbi.srWindow);
8318 coord.Y = SRHEIGHT(csbi.srWindow);
8319 SetConsoleScreenBufferSize(g_hConOut, coord);
8320
8321 newsize.Left = 0;
8322 newsize.Top = 0;
8323 newsize.Right = coord.X - 1;
8324 newsize.Bottom = coord.Y - 1;
8325 SetConsoleWindowInfo(g_hConOut, TRUE, &newsize);
8326
8327 SetConsoleScreenBufferSize(g_hConOut, coord);
8328 }
8329}
8330#endif