blob: af2622caeb5012cea07042c08ae52eb81f839eac [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 Moolenaar651fca82021-11-29 20:39:38 +000049# if !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;
Paul Ollis65745772022-06-05 16:55:54 +0100103typedef int BOOLEAN;
104typedef int CALLBACK;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000105typedef int COLORREF;
106typedef int CONSOLE_CURSOR_INFO;
107typedef int COORD;
108typedef int DWORD;
109typedef int HANDLE;
Bram Moolenaaref269542016-01-19 13:22:12 +0100110typedef int LPHANDLE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000111typedef int HDC;
112typedef int HFONT;
113typedef int HICON;
114typedef int HINSTANCE;
115typedef int HWND;
116typedef int INPUT_RECORD;
Bram Moolenaare0ab9792017-08-02 23:18:25 +0200117typedef int INT;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000118typedef int KEY_EVENT_RECORD;
119typedef int LOGFONT;
120typedef int LPBOOL;
121typedef int LPCTSTR;
122typedef int LPDWORD;
123typedef int LPSTR;
124typedef int LPTSTR;
125typedef int LPVOID;
126typedef int MOUSE_EVENT_RECORD;
127typedef int PACL;
128typedef int PDWORD;
129typedef int PHANDLE;
130typedef int PRINTDLG;
131typedef int PSECURITY_DESCRIPTOR;
132typedef int PSID;
133typedef int SECURITY_INFORMATION;
134typedef int SHORT;
135typedef int SMALL_RECT;
136typedef int TEXTMETRIC;
137typedef int TOKEN_INFORMATION_CLASS;
138typedef int TRUSTEE;
139typedef int WORD;
140typedef int WCHAR;
141typedef void VOID;
Bram Moolenaar82881492012-11-20 16:53:39 +0100142typedef int BY_HANDLE_FILE_INFORMATION;
Bram Moolenaar32ac8cd2013-07-03 18:49:17 +0200143typedef int SE_OBJECT_TYPE;
144typedef int PSNSECINFO;
145typedef int PSNSECINFOW;
Bram Moolenaarb8e0bdb2014-11-12 16:10:48 +0100146typedef int STARTUPINFO;
147typedef int PROCESS_INFORMATION;
Bram Moolenaard90b6c02016-08-28 18:10:45 +0200148typedef int LPSECURITY_ATTRIBUTES;
Bram Moolenaar0f873732019-12-05 20:28:46 +0100149# define __stdcall // empty
Bram Moolenaar071d4272004-06-13 20:20:40 +0000150#endif
151
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200152#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar0f873732019-12-05 20:28:46 +0100153// Win32 Console handles for input and output
Bram Moolenaar071d4272004-06-13 20:20:40 +0000154static HANDLE g_hConIn = INVALID_HANDLE_VALUE;
155static HANDLE g_hConOut = INVALID_HANDLE_VALUE;
156
Bram Moolenaar0f873732019-12-05 20:28:46 +0100157// Win32 Screen buffer,coordinate,console I/O information
Bram Moolenaar071d4272004-06-13 20:20:40 +0000158static SMALL_RECT g_srScrollRegion;
Bram Moolenaar0f873732019-12-05 20:28:46 +0100159static COORD g_coord; // 0-based, but external coords are 1-based
Bram Moolenaar071d4272004-06-13 20:20:40 +0000160
Bram Moolenaar0f873732019-12-05 20:28:46 +0100161// The attribute of the screen when the editor was started
162static WORD g_attrDefault = 7; // lightgray text on black background
Bram Moolenaar071d4272004-06-13 20:20:40 +0000163static WORD g_attrCurrent;
164
Bram Moolenaar0f873732019-12-05 20:28:46 +0100165static int g_fCBrkPressed = FALSE; // set by ctrl-break interrupt
166static int g_fCtrlCPressed = FALSE; // set when ctrl-C or ctrl-break detected
167static int g_fForceExit = FALSE; // set when forcefully exiting
Bram Moolenaar071d4272004-06-13 20:20:40 +0000168
Bram Moolenaar071d4272004-06-13 20:20:40 +0000169static void scroll(unsigned cLines);
170static void set_scroll_region(unsigned left, unsigned top,
171 unsigned right, unsigned bottom);
Bram Moolenaar6982f422019-02-16 16:48:01 +0100172static void set_scroll_region_tb(unsigned top, unsigned bottom);
173static void set_scroll_region_lr(unsigned left, unsigned right);
174static void insert_lines(unsigned cLines);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000175static void delete_lines(unsigned cLines);
176static void gotoxy(unsigned x, unsigned y);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000177static void standout(void);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000178static int s_cursor_visible = TRUE;
179static int did_create_conin = FALSE;
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200180#endif
181#ifdef FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +0000182static int s_dont_use_vimrun = TRUE;
183static int need_vimrun_warning = FALSE;
184static char *vimrun_path = "vimrun ";
185#endif
186
Bram Moolenaar12b559e2013-06-12 22:41:37 +0200187static int win32_getattrs(char_u *name);
188static int win32_setattrs(char_u *name, int attrs);
189static int win32_set_archive(char_u *name);
190
Bram Moolenaard9ef1b82019-02-13 19:23:10 +0100191static int conpty_working = 0;
Bram Moolenaar57da6982019-09-13 22:30:11 +0200192static int conpty_type = 0;
Bram Moolenaard9ef1b82019-02-13 19:23:10 +0100193static int conpty_stable = 0;
Bram Moolenaar7ed8f592020-04-28 20:44:42 +0200194static int conpty_fix_type = 0;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100195static void vtp_flag_init();
196
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200197#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar6902c0e2019-02-16 14:07:37 +0100198static int vtp_working = 0;
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100199static void vtp_init();
200static void vtp_exit();
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100201static void vtp_sgr_bulk(int arg);
202static void vtp_sgr_bulks(int argc, int *argv);
203
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200204static int wt_working = 0;
205static void wt_init();
206
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100207static guicolor_T save_console_bg_rgb;
208static guicolor_T save_console_fg_rgb;
Bram Moolenaardf543822020-01-30 11:53:59 +0100209static guicolor_T store_console_bg_rgb;
210static guicolor_T store_console_fg_rgb;
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100211
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +0200212static int g_color_index_bg = 0;
213static int g_color_index_fg = 7;
214
215# ifdef FEAT_TERMGUICOLORS
Yasuhiro Matsumotoe42c8da2022-09-01 11:31:45 +0100216static int default_console_color_bg = 0x000000; // black
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +0200217static int default_console_color_fg = 0xc0c0c0; // white
218# endif
219
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100220# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarc5cd8852018-05-01 15:47:38 +0200221# define USE_VTP (vtp_working && is_term_win32() && (p_tgc || (!p_tgc && t_colors >= 256)))
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200222# define USE_WT (wt_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100223# else
224# define USE_VTP 0
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200225# define USE_WT 0
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100226# endif
227
228static void set_console_color_rgb(void);
229static void reset_console_color_rgb(void);
Bram Moolenaardf543822020-01-30 11:53:59 +0100230static void restore_console_color_rgb(void);
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100231#endif
232
Bram Moolenaar0f873732019-12-05 20:28:46 +0100233// This flag is newly created from Windows 10
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100234#ifndef ENABLE_VIRTUAL_TERMINAL_PROCESSING
235# define ENABLE_VIRTUAL_TERMINAL_PROCESSING 0x0004
236#endif
237
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200238#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar0f873732019-12-05 20:28:46 +0100239static int suppress_winsize = 1; // don't fiddle with console
Bram Moolenaar071d4272004-06-13 20:20:40 +0000240#endif
241
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200242static char_u *exe_path = NULL;
243
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100244static BOOL win8_or_later = FALSE;
245
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200246#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar0f873732019-12-05 20:28:46 +0100247// Dynamic loading for portability
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100248typedef struct _DYN_CONSOLE_SCREEN_BUFFER_INFOEX
249{
250 ULONG cbSize;
251 COORD dwSize;
252 COORD dwCursorPosition;
253 WORD wAttributes;
254 SMALL_RECT srWindow;
255 COORD dwMaximumWindowSize;
256 WORD wPopupAttributes;
257 BOOL bFullscreenSupported;
258 COLORREF ColorTable[16];
259} DYN_CONSOLE_SCREEN_BUFFER_INFOEX, *PDYN_CONSOLE_SCREEN_BUFFER_INFOEX;
260typedef BOOL (WINAPI *PfnGetConsoleScreenBufferInfoEx)(HANDLE, PDYN_CONSOLE_SCREEN_BUFFER_INFOEX);
261static PfnGetConsoleScreenBufferInfoEx pGetConsoleScreenBufferInfoEx;
262typedef BOOL (WINAPI *PfnSetConsoleScreenBufferInfoEx)(HANDLE, PDYN_CONSOLE_SCREEN_BUFFER_INFOEX);
263static PfnSetConsoleScreenBufferInfoEx pSetConsoleScreenBufferInfoEx;
264static BOOL has_csbiex = FALSE;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100265#endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100266
267/*
268 * Get version number including build number
269 */
270typedef BOOL (WINAPI *PfnRtlGetVersion)(LPOSVERSIONINFOW);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100271#define MAKE_VER(major, minor, build) \
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100272 (((major) << 24) | ((minor) << 16) | (build))
273
274 static DWORD
275get_build_number(void)
276{
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +0100277 OSVERSIONINFOW osver;
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100278 HMODULE hNtdll;
279 PfnRtlGetVersion pRtlGetVersion;
280 DWORD ver = MAKE_VER(0, 0, 0);
281
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +0100282 osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFOW);
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100283 hNtdll = GetModuleHandle("ntdll.dll");
284 if (hNtdll != NULL)
285 {
286 pRtlGetVersion =
287 (PfnRtlGetVersion)GetProcAddress(hNtdll, "RtlGetVersion");
288 pRtlGetVersion(&osver);
289 ver = MAKE_VER(min(osver.dwMajorVersion, 255),
290 min(osver.dwMinorVersion, 255),
291 min(osver.dwBuildNumber, 32767));
292 }
293 return ver;
294}
295
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200296#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200297 static BOOL
298is_ambiwidth_event(
299 INPUT_RECORD *ir)
300{
301 return ir->EventType == KEY_EVENT
302 && ir->Event.KeyEvent.bKeyDown
303 && ir->Event.KeyEvent.wRepeatCount == 1
304 && ir->Event.KeyEvent.wVirtualKeyCode == 0x12
305 && ir->Event.KeyEvent.wVirtualScanCode == 0x38
K.Takata972db232022-02-04 10:45:38 +0000306 && ir->Event.KeyEvent.uChar.UnicodeChar == 0
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200307 && ir->Event.KeyEvent.dwControlKeyState == 2;
308}
309
310 static void
311make_ambiwidth_event(
312 INPUT_RECORD *down,
313 INPUT_RECORD *up)
314{
315 down->Event.KeyEvent.wVirtualKeyCode = 0;
316 down->Event.KeyEvent.wVirtualScanCode = 0;
K.Takata972db232022-02-04 10:45:38 +0000317 down->Event.KeyEvent.uChar.UnicodeChar
318 = up->Event.KeyEvent.uChar.UnicodeChar;
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200319 down->Event.KeyEvent.dwControlKeyState = 0;
320}
321
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100322/*
323 * Version of ReadConsoleInput() that works with IME.
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100324 * Works around problems on Windows 8.
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100325 */
326 static BOOL
327read_console_input(
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100328 HANDLE hInput,
329 INPUT_RECORD *lpBuffer,
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +0100330 int nLength,
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100331 LPDWORD lpEvents)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100332{
333 enum
334 {
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100335 IRSIZE = 10
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100336 };
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100337 static INPUT_RECORD s_irCache[IRSIZE];
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100338 static DWORD s_dwIndex = 0;
339 static DWORD s_dwMax = 0;
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100340 DWORD dwEvents;
Bram Moolenaardd415a62014-02-05 14:02:27 +0100341 int head;
342 int tail;
343 int i;
Bram Moolenaarbc970da2020-04-26 19:00:07 +0200344 static INPUT_RECORD s_irPseudo;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100345
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200346 if (nLength == -2)
347 return (s_dwMax > 0) ? TRUE : FALSE;
348
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100349 if (!win8_or_later)
350 {
351 if (nLength == -1)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200352 return PeekConsoleInputW(hInput, lpBuffer, 1, lpEvents);
353 return ReadConsoleInputW(hInput, lpBuffer, 1, &dwEvents);
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100354 }
355
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100356 if (s_dwMax == 0)
357 {
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200358 if (!USE_WT && nLength == -1)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200359 return PeekConsoleInputW(hInput, lpBuffer, 1, lpEvents);
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200360 GetNumberOfConsoleInputEvents(hInput, &dwEvents);
361 if (dwEvents == 0 && nLength == -1)
362 return PeekConsoleInputW(hInput, lpBuffer, 1, lpEvents);
363 ReadConsoleInputW(hInput, s_irCache, IRSIZE, &dwEvents);
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100364 s_dwIndex = 0;
365 s_dwMax = dwEvents;
366 if (dwEvents == 0)
367 {
368 *lpEvents = 0;
369 return TRUE;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100370 }
Bram Moolenaardd415a62014-02-05 14:02:27 +0100371
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200372 for (i = s_dwIndex; i < (int)s_dwMax - 1; ++i)
373 if (is_ambiwidth_event(&s_irCache[i]))
374 make_ambiwidth_event(&s_irCache[i], &s_irCache[i + 1]);
375
Bram Moolenaardd415a62014-02-05 14:02:27 +0100376 if (s_dwMax > 1)
377 {
378 head = 0;
379 tail = s_dwMax - 1;
380 while (head != tail)
381 {
382 if (s_irCache[head].EventType == WINDOW_BUFFER_SIZE_EVENT
383 && s_irCache[head + 1].EventType
384 == WINDOW_BUFFER_SIZE_EVENT)
385 {
Bram Moolenaar0f873732019-12-05 20:28:46 +0100386 // Remove duplicate event to avoid flicker.
Bram Moolenaardd415a62014-02-05 14:02:27 +0100387 for (i = head; i < tail; ++i)
388 s_irCache[i] = s_irCache[i + 1];
389 --tail;
390 continue;
391 }
392 head++;
393 }
394 s_dwMax = tail + 1;
395 }
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100396 }
Bram Moolenaardd415a62014-02-05 14:02:27 +0100397
Bram Moolenaarbc970da2020-04-26 19:00:07 +0200398 if (s_irCache[s_dwIndex].EventType == KEY_EVENT)
399 {
400 if (s_irCache[s_dwIndex].Event.KeyEvent.wRepeatCount > 1)
401 {
402 s_irPseudo = s_irCache[s_dwIndex];
403 s_irPseudo.Event.KeyEvent.wRepeatCount = 1;
404 s_irCache[s_dwIndex].Event.KeyEvent.wRepeatCount--;
405 *lpBuffer = s_irPseudo;
406 *lpEvents = 1;
407 return TRUE;
408 }
409 }
410
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100411 *lpBuffer = s_irCache[s_dwIndex];
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200412 if (!(nLength == -1 || nLength == -2) && ++s_dwIndex >= s_dwMax)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100413 s_dwMax = 0;
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100414 *lpEvents = 1;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100415 return TRUE;
416}
417
418/*
419 * Version of PeekConsoleInput() that works with IME.
420 */
421 static BOOL
422peek_console_input(
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100423 HANDLE hInput,
424 INPUT_RECORD *lpBuffer,
Bram Moolenaarbd67aac2019-09-21 23:09:04 +0200425 DWORD nLength UNUSED,
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100426 LPDWORD lpEvents)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100427{
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +0100428 return read_console_input(hInput, lpBuffer, -1, lpEvents);
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100429}
430
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100431# ifdef FEAT_CLIENTSERVER
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200432 static DWORD
433msg_wait_for_multiple_objects(
434 DWORD nCount,
435 LPHANDLE pHandles,
436 BOOL fWaitAll,
437 DWORD dwMilliseconds,
438 DWORD dwWakeMask)
439{
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +0100440 if (read_console_input(NULL, NULL, -2, NULL))
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200441 return WAIT_OBJECT_0;
442 return MsgWaitForMultipleObjects(nCount, pHandles, fWaitAll,
443 dwMilliseconds, dwWakeMask);
444}
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100445# endif
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200446
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100447# ifndef FEAT_CLIENTSERVER
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200448 static DWORD
449wait_for_single_object(
450 HANDLE hHandle,
451 DWORD dwMilliseconds)
452{
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +0100453 if (read_console_input(NULL, NULL, -2, NULL))
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200454 return WAIT_OBJECT_0;
455 return WaitForSingleObject(hHandle, dwMilliseconds);
456}
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100457# endif
458#endif
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200459
Bram Moolenaar071d4272004-06-13 20:20:40 +0000460 static void
461get_exe_name(void)
462{
Bram Moolenaar0f873732019-12-05 20:28:46 +0100463 // Maximum length of $PATH is more than MAXPATHL. 8191 is often mentioned
464 // as the maximum length that works (plus a NUL byte).
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100465#define MAX_ENV_PATH_LEN 8192
466 char temp[MAX_ENV_PATH_LEN];
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200467 char_u *p;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000468
469 if (exe_name == NULL)
470 {
Bram Moolenaar0f873732019-12-05 20:28:46 +0100471 // store the name of the executable, may be used for $VIM
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100472 GetModuleFileName(NULL, temp, MAX_ENV_PATH_LEN - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000473 if (*temp != NUL)
474 exe_name = FullName_save((char_u *)temp, FALSE);
475 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000476
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200477 if (exe_path == NULL && exe_name != NULL)
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000478 {
Bram Moolenaar71ccd032020-06-12 22:59:11 +0200479 exe_path = vim_strnsave(exe_name, gettail_sep(exe_name) - exe_name);
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200480 if (exe_path != NULL)
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000481 {
Bram Moolenaar0f873732019-12-05 20:28:46 +0100482 // Append our starting directory to $PATH, so that when doing
483 // "!xxd" it's found in our starting directory. Needed because
484 // SearchPath() also looks there.
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200485 p = mch_getenv("PATH");
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100486 if (p == NULL
487 || STRLEN(p) + STRLEN(exe_path) + 2 < MAX_ENV_PATH_LEN)
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200488 {
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100489 if (p == NULL || *p == NUL)
490 temp[0] = NUL;
491 else
492 {
493 STRCPY(temp, p);
494 STRCAT(temp, ";");
495 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200496 STRCAT(temp, exe_path);
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +0100497 vim_setenv((char_u *)"PATH", (char_u *)temp);
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200498 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000499 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000500 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000501}
502
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200503/*
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100504 * Unescape characters in "p" that appear in "escaped".
505 */
506 static void
507unescape_shellxquote(char_u *p, char_u *escaped)
508{
Bram Moolenaar4336cdf2012-02-29 13:58:47 +0100509 int l = (int)STRLEN(p);
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100510 int n;
511
512 while (*p != NUL)
513 {
514 if (*p == '^' && vim_strchr(escaped, p[1]) != NULL)
515 mch_memmove(p, p + 1, l--);
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100516 n = (*mb_ptr2len)(p);
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100517 p += n;
518 l -= n;
519 }
520}
521
522/*
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200523 * Load library "name".
524 */
525 HINSTANCE
K.Takatad68b2fc2022-02-12 11:18:37 +0000526vimLoadLib(const char *name)
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200527{
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200528 HINSTANCE dll = NULL;
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200529
Bram Moolenaar3d0e7a92021-05-01 17:46:03 +0200530 // No need to load any library when registering OLE.
531 if (found_register_arg)
532 return dll;
533
Bram Moolenaar0f873732019-12-05 20:28:46 +0100534 // NOTE: Do not use mch_dirname() and mch_chdir() here, they may call
535 // vimLoadLib() recursively, which causes a stack overflow.
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200536 if (exe_path == NULL)
537 get_exe_name();
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200538 if (exe_path != NULL)
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200539 {
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200540 WCHAR old_dirw[MAXPATHL];
541
542 if (GetCurrentDirectoryW(MAXPATHL, old_dirw) != 0)
543 {
Bram Moolenaar0f873732019-12-05 20:28:46 +0100544 // Change directory to where the executable is, both to make
545 // sure we find a .dll there and to avoid looking for a .dll
546 // in the current directory.
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +0100547 SetCurrentDirectory((LPCSTR)exe_path);
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200548 dll = LoadLibrary(name);
549 SetCurrentDirectoryW(old_dirw);
550 return dll;
551 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200552 }
553 return dll;
554}
555
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200556#if defined(VIMDLL) || defined(PROTO)
557/*
558 * Check if the current executable file is for the GUI subsystem.
559 */
560 int
561mch_is_gui_executable(void)
562{
563 PBYTE pImage = (PBYTE)GetModuleHandle(NULL);
564 PIMAGE_DOS_HEADER pDOS = (PIMAGE_DOS_HEADER)pImage;
565 PIMAGE_NT_HEADERS pPE;
566
567 if (pDOS->e_magic != IMAGE_DOS_SIGNATURE)
568 return FALSE;
569 pPE = (PIMAGE_NT_HEADERS)(pImage + pDOS->e_lfanew);
570 if (pPE->Signature != IMAGE_NT_SIGNATURE)
571 return FALSE;
572 if (pPE->OptionalHeader.Subsystem == IMAGE_SUBSYSTEM_WINDOWS_GUI)
573 return TRUE;
574 return FALSE;
575}
576#endif
577
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000578#if defined(DYNAMIC_ICONV) || defined(DYNAMIC_GETTEXT) \
579 || defined(FEAT_PYTHON3) || defined(PROTO)
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100580/*
581 * Get related information about 'funcname' which is imported by 'hInst'.
582 * If 'info' is 0, return the function address.
583 * If 'info' is 1, return the module name which the function is imported from.
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000584 * If 'info' is 2, hook the function with 'ptr', and return the original
585 * function address.
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100586 */
587 static void *
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000588get_imported_func_info(HINSTANCE hInst, const char *funcname, int info,
589 const void *ptr)
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100590{
591 PBYTE pImage = (PBYTE)hInst;
592 PIMAGE_DOS_HEADER pDOS = (PIMAGE_DOS_HEADER)hInst;
593 PIMAGE_NT_HEADERS pPE;
594 PIMAGE_IMPORT_DESCRIPTOR pImpDesc;
Bram Moolenaar0f873732019-12-05 20:28:46 +0100595 PIMAGE_THUNK_DATA pIAT; // Import Address Table
596 PIMAGE_THUNK_DATA pINT; // Import Name Table
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100597 PIMAGE_IMPORT_BY_NAME pImpName;
598
599 if (pDOS->e_magic != IMAGE_DOS_SIGNATURE)
600 return NULL;
601 pPE = (PIMAGE_NT_HEADERS)(pImage + pDOS->e_lfanew);
602 if (pPE->Signature != IMAGE_NT_SIGNATURE)
603 return NULL;
604 pImpDesc = (PIMAGE_IMPORT_DESCRIPTOR)(pImage
605 + pPE->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT]
606 .VirtualAddress);
607 for (; pImpDesc->FirstThunk; ++pImpDesc)
608 {
609 if (!pImpDesc->OriginalFirstThunk)
610 continue;
611 pIAT = (PIMAGE_THUNK_DATA)(pImage + pImpDesc->FirstThunk);
612 pINT = (PIMAGE_THUNK_DATA)(pImage + pImpDesc->OriginalFirstThunk);
613 for (; pIAT->u1.Function; ++pIAT, ++pINT)
614 {
615 if (IMAGE_SNAP_BY_ORDINAL(pINT->u1.Ordinal))
616 continue;
617 pImpName = (PIMAGE_IMPORT_BY_NAME)(pImage
618 + (UINT_PTR)(pINT->u1.AddressOfData));
619 if (strcmp((char *)pImpName->Name, funcname) == 0)
620 {
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000621 void *original;
622 DWORD old, new = PAGE_READWRITE;
623
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100624 switch (info)
625 {
626 case 0:
627 return (void *)pIAT->u1.Function;
628 case 1:
629 return (void *)(pImage + pImpDesc->Name);
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000630 case 2:
631 original = (void *)pIAT->u1.Function;
632 VirtualProtect(&pIAT->u1.Function, sizeof(void *),
633 new, &old);
634 pIAT->u1.Function = (UINT_PTR)ptr;
635 VirtualProtect(&pIAT->u1.Function, sizeof(void *),
636 old, &new);
637 return original;
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100638 default:
639 return NULL;
640 }
641 }
642 }
643 }
644 return NULL;
645}
646
647/*
648 * Get the module handle which 'funcname' in 'hInst' is imported from.
649 */
650 HINSTANCE
651find_imported_module_by_funcname(HINSTANCE hInst, const char *funcname)
652{
653 char *modulename;
654
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000655 modulename = (char *)get_imported_func_info(hInst, funcname, 1, NULL);
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100656 if (modulename != NULL)
657 return GetModuleHandleA(modulename);
658 return NULL;
659}
660
661/*
662 * Get the address of 'funcname' which is imported by 'hInst' DLL.
663 */
664 void *
665get_dll_import_func(HINSTANCE hInst, const char *funcname)
666{
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000667 return get_imported_func_info(hInst, funcname, 0, NULL);
668}
669
670/*
671 * Hook the function named 'funcname' which is imported by 'hInst' DLL,
672 * and return the original function address.
673 */
674 void *
675hook_dll_import_func(HINSTANCE hInst, const char *funcname, const void *hook)
676{
677 return get_imported_func_info(hInst, funcname, 2, hook);
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100678}
679#endif
680
Bram Moolenaar071d4272004-06-13 20:20:40 +0000681#if defined(DYNAMIC_GETTEXT) || defined(PROTO)
682# ifndef GETTEXT_DLL
683# define GETTEXT_DLL "libintl.dll"
Bram Moolenaar7554c542018-10-06 15:03:15 +0200684# define GETTEXT_DLL_ALT1 "libintl-8.dll"
685# define GETTEXT_DLL_ALT2 "intl.dll"
Bram Moolenaar071d4272004-06-13 20:20:40 +0000686# endif
Bram Moolenaar0f873732019-12-05 20:28:46 +0100687// Dummy functions
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000688static char *null_libintl_gettext(const char *);
Bram Moolenaaree695f72016-08-03 22:08:45 +0200689static char *null_libintl_ngettext(const char *, const char *, unsigned long n);
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000690static char *null_libintl_textdomain(const char *);
691static char *null_libintl_bindtextdomain(const char *, const char *);
692static char *null_libintl_bind_textdomain_codeset(const char *, const char *);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100693static int null_libintl_wputenv(const wchar_t *);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000694
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200695static HINSTANCE hLibintlDLL = NULL;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000696char *(*dyn_libintl_gettext)(const char *) = null_libintl_gettext;
Bram Moolenaaree695f72016-08-03 22:08:45 +0200697char *(*dyn_libintl_ngettext)(const char *, const char *, unsigned long n)
698 = null_libintl_ngettext;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000699char *(*dyn_libintl_textdomain)(const char *) = null_libintl_textdomain;
700char *(*dyn_libintl_bindtextdomain)(const char *, const char *)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000701 = null_libintl_bindtextdomain;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000702char *(*dyn_libintl_bind_textdomain_codeset)(const char *, const char *)
703 = null_libintl_bind_textdomain_codeset;
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100704int (*dyn_libintl_wputenv)(const wchar_t *) = null_libintl_wputenv;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000705
706 int
Bram Moolenaar05540972016-01-30 20:31:25 +0100707dyn_libintl_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000708{
709 int i;
710 static struct
711 {
712 char *name;
713 FARPROC *ptr;
714 } libintl_entry[] =
715 {
716 {"gettext", (FARPROC*)&dyn_libintl_gettext},
Bram Moolenaaree695f72016-08-03 22:08:45 +0200717 {"ngettext", (FARPROC*)&dyn_libintl_ngettext},
Bram Moolenaar071d4272004-06-13 20:20:40 +0000718 {"textdomain", (FARPROC*)&dyn_libintl_textdomain},
719 {"bindtextdomain", (FARPROC*)&dyn_libintl_bindtextdomain},
720 {NULL, NULL}
721 };
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100722 HINSTANCE hmsvcrt;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000723
Bram Moolenaar7554c542018-10-06 15:03:15 +0200724 // No need to initialize twice.
725 if (hLibintlDLL != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000726 return 1;
Bram Moolenaar7554c542018-10-06 15:03:15 +0200727 // Load gettext library (libintl.dll and other names).
Bram Moolenaar923e43b2016-01-28 15:07:38 +0100728 hLibintlDLL = vimLoadLib(GETTEXT_DLL);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100729# ifdef GETTEXT_DLL_ALT1
Bram Moolenaar286eacd2016-01-16 18:05:50 +0100730 if (!hLibintlDLL)
Bram Moolenaar7554c542018-10-06 15:03:15 +0200731 hLibintlDLL = vimLoadLib(GETTEXT_DLL_ALT1);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100732# endif
733# ifdef GETTEXT_DLL_ALT2
Bram Moolenaar7554c542018-10-06 15:03:15 +0200734 if (!hLibintlDLL)
735 hLibintlDLL = vimLoadLib(GETTEXT_DLL_ALT2);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100736# endif
Bram Moolenaar938ee832016-01-24 15:36:03 +0100737 if (!hLibintlDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000738 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200739 if (p_verbose > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000740 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200741 verbose_enter();
Bram Moolenaar460ae5d2022-01-01 14:19:49 +0000742 semsg(_(e_could_not_load_library_str_str), GETTEXT_DLL, GetWin32Error());
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200743 verbose_leave();
Bram Moolenaar071d4272004-06-13 20:20:40 +0000744 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200745 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000746 }
747 for (i = 0; libintl_entry[i].name != NULL
748 && libintl_entry[i].ptr != NULL; ++i)
749 {
K.Takata54119102022-02-03 13:33:03 +0000750 if ((*libintl_entry[i].ptr = GetProcAddress(hLibintlDLL,
Bram Moolenaar071d4272004-06-13 20:20:40 +0000751 libintl_entry[i].name)) == NULL)
752 {
753 dyn_libintl_end();
754 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +0000755 {
756 verbose_enter();
Bram Moolenaar460ae5d2022-01-01 14:19:49 +0000757 semsg(_(e_could_not_load_library_function_str), libintl_entry[i].name);
Bram Moolenaara04f10b2005-05-31 22:09:46 +0000758 verbose_leave();
759 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000760 return 0;
761 }
762 }
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000763
Bram Moolenaar0f873732019-12-05 20:28:46 +0100764 // The bind_textdomain_codeset() function is optional.
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +0100765 dyn_libintl_bind_textdomain_codeset = (char *(*)(const char *, const char *))
766 GetProcAddress(hLibintlDLL, "bind_textdomain_codeset");
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000767 if (dyn_libintl_bind_textdomain_codeset == NULL)
768 dyn_libintl_bind_textdomain_codeset =
769 null_libintl_bind_textdomain_codeset;
770
Bram Moolenaar0f873732019-12-05 20:28:46 +0100771 // _wputenv() function for the libintl.dll is optional.
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100772 hmsvcrt = find_imported_module_by_funcname(hLibintlDLL, "getenv");
773 if (hmsvcrt != NULL)
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +0100774 dyn_libintl_wputenv = (int (*)(const wchar_t *))
775 GetProcAddress(hmsvcrt, "_wputenv");
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100776 if (dyn_libintl_wputenv == NULL || dyn_libintl_wputenv == _wputenv)
777 dyn_libintl_wputenv = null_libintl_wputenv;
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100778
Bram Moolenaar071d4272004-06-13 20:20:40 +0000779 return 1;
780}
781
782 void
Bram Moolenaar05540972016-01-30 20:31:25 +0100783dyn_libintl_end(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000784{
785 if (hLibintlDLL)
786 FreeLibrary(hLibintlDLL);
787 hLibintlDLL = NULL;
788 dyn_libintl_gettext = null_libintl_gettext;
Bram Moolenaaree695f72016-08-03 22:08:45 +0200789 dyn_libintl_ngettext = null_libintl_ngettext;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000790 dyn_libintl_textdomain = null_libintl_textdomain;
791 dyn_libintl_bindtextdomain = null_libintl_bindtextdomain;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000792 dyn_libintl_bind_textdomain_codeset = null_libintl_bind_textdomain_codeset;
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100793 dyn_libintl_wputenv = null_libintl_wputenv;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000794}
795
796 static char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000797null_libintl_gettext(const char *msgid)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000798{
799 return (char*)msgid;
800}
801
802 static char *
Bram Moolenaaree695f72016-08-03 22:08:45 +0200803null_libintl_ngettext(
804 const char *msgid,
805 const char *msgid_plural,
806 unsigned long n)
807{
Bram Moolenaarc90f2ae2016-08-04 22:00:15 +0200808 return (char *)(n == 1 ? msgid : msgid_plural);
Bram Moolenaaree695f72016-08-03 22:08:45 +0200809}
810
Bram Moolenaaree695f72016-08-03 22:08:45 +0200811 static char *
Bram Moolenaar1266d672017-02-01 13:43:36 +0100812null_libintl_bindtextdomain(
813 const char *domainname UNUSED,
814 const char *dirname UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000815{
816 return NULL;
817}
818
819 static char *
Bram Moolenaar1266d672017-02-01 13:43:36 +0100820null_libintl_bind_textdomain_codeset(
821 const char *domainname UNUSED,
822 const char *codeset UNUSED)
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000823{
824 return NULL;
825}
826
827 static char *
Bram Moolenaar1266d672017-02-01 13:43:36 +0100828null_libintl_textdomain(const char *domainname UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000829{
830 return NULL;
831}
832
Bram Moolenaare0ab9792017-08-02 23:18:25 +0200833 static int
Bram Moolenaar1266d672017-02-01 13:43:36 +0100834null_libintl_wputenv(const wchar_t *envstring UNUSED)
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100835{
836 return 0;
837}
838
Bram Moolenaar0f873732019-12-05 20:28:46 +0100839#endif // DYNAMIC_GETTEXT
Bram Moolenaar071d4272004-06-13 20:20:40 +0000840
Bram Moolenaar0f873732019-12-05 20:28:46 +0100841// This symbol is not defined in older versions of the SDK or Visual C++
Bram Moolenaar071d4272004-06-13 20:20:40 +0000842
843#ifndef VER_PLATFORM_WIN32_WINDOWS
844# define VER_PLATFORM_WIN32_WINDOWS 1
845#endif
846
Bram Moolenaar071d4272004-06-13 20:20:40 +0000847#ifdef HAVE_ACL
Bram Moolenaar82881492012-11-20 16:53:39 +0100848# ifndef PROTO
849# include <aclapi.h>
850# endif
Bram Moolenaar27515922013-06-29 15:36:26 +0200851# ifndef PROTECTED_DACL_SECURITY_INFORMATION
852# define PROTECTED_DACL_SECURITY_INFORMATION 0x80000000L
853# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000854#endif
855
Bram Moolenaar27515922013-06-29 15:36:26 +0200856#ifdef HAVE_ACL
857/*
858 * Enables or disables the specified privilege.
859 */
860 static BOOL
861win32_enable_privilege(LPTSTR lpszPrivilege, BOOL bEnable)
862{
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100863 BOOL bResult;
864 LUID luid;
865 HANDLE hToken;
866 TOKEN_PRIVILEGES tokenPrivileges;
Bram Moolenaar27515922013-06-29 15:36:26 +0200867
868 if (!OpenProcessToken(GetCurrentProcess(),
869 TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
870 return FALSE;
871
872 if (!LookupPrivilegeValue(NULL, lpszPrivilege, &luid))
873 {
874 CloseHandle(hToken);
875 return FALSE;
876 }
877
Bram Moolenaar45500912014-07-09 20:51:07 +0200878 tokenPrivileges.PrivilegeCount = 1;
Bram Moolenaar27515922013-06-29 15:36:26 +0200879 tokenPrivileges.Privileges[0].Luid = luid;
880 tokenPrivileges.Privileges[0].Attributes = bEnable ?
881 SE_PRIVILEGE_ENABLED : 0;
882
883 bResult = AdjustTokenPrivileges(hToken, FALSE, &tokenPrivileges,
884 sizeof(TOKEN_PRIVILEGES), NULL, NULL);
885
886 CloseHandle(hToken);
887
888 return bResult && GetLastError() == ERROR_SUCCESS;
889}
890#endif
891
Bram Moolenaar29d2f452020-12-04 19:42:52 +0100892#ifdef _MSC_VER
893// Suppress the deprecation warning for using GetVersionEx().
894// It is needed for implementing "windowsversion()".
895# pragma warning(push)
896# pragma warning(disable: 4996)
897#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000898/*
Bram Moolenaar1e1d2e82020-05-18 20:17:02 +0200899 * Set "win8_or_later" and fill in "windowsVersion" if possible.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000900 */
901 void
902PlatformId(void)
903{
904 static int done = FALSE;
905
906 if (!done)
907 {
908 OSVERSIONINFO ovi;
909
910 ovi.dwOSVersionInfoSize = sizeof(ovi);
911 GetVersionEx(&ovi);
912
Bram Moolenaar1e1d2e82020-05-18 20:17:02 +0200913#ifdef FEAT_EVAL
Bram Moolenaar0c1e3742019-12-27 13:49:24 +0100914 vim_snprintf(windowsVersion, sizeof(windowsVersion), "%d.%d",
915 (int)ovi.dwMajorVersion, (int)ovi.dwMinorVersion);
Bram Moolenaar1e1d2e82020-05-18 20:17:02 +0200916#endif
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100917 if ((ovi.dwMajorVersion == 6 && ovi.dwMinorVersion >= 2)
918 || ovi.dwMajorVersion > 6)
919 win8_or_later = TRUE;
920
Bram Moolenaar071d4272004-06-13 20:20:40 +0000921#ifdef HAVE_ACL
Bram Moolenaar0f873732019-12-05 20:28:46 +0100922 // Enable privilege for getting or setting SACLs.
Bram Moolenaarcea912a2016-10-12 14:20:24 +0200923 win32_enable_privilege(SE_SECURITY_NAME, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000924#endif
925 done = TRUE;
926 }
927}
Bram Moolenaar29d2f452020-12-04 19:42:52 +0100928#ifdef _MSC_VER
929# pragma warning(pop)
930#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000931
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200932#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000933
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100934# define SHIFT (SHIFT_PRESSED)
935# define CTRL (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED)
936# define ALT (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED)
937# define ALT_GR (RIGHT_ALT_PRESSED | LEFT_CTRL_PRESSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000938
939
Bram Moolenaar0f873732019-12-05 20:28:46 +0100940// When uChar.AsciiChar is 0, then we need to look at wVirtualKeyCode.
941// We map function keys to their ANSI terminal equivalents, as produced
942// by ANSI.SYS, for compatibility with the MS-DOS version of Vim. Any
943// ANSI key with a value >= '\300' is nonstandard, but provided anyway
944// so that the user can have access to all SHIFT-, CTRL-, and ALT-
945// combinations of function/arrow/etc keys.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000946
Bram Moolenaard6f676d2005-06-01 21:51:55 +0000947static const struct
Bram Moolenaar071d4272004-06-13 20:20:40 +0000948{
949 WORD wVirtKey;
950 BOOL fAnsiKey;
951 int chAlone;
952 int chShift;
953 int chCtrl;
954 int chAlt;
955} VirtKeyMap[] =
956{
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200957// Key ANSI alone shift ctrl alt
Bram Moolenaar071d4272004-06-13 20:20:40 +0000958 { VK_ESCAPE,FALSE, ESC, ESC, ESC, ESC, },
959
960 { VK_F1, TRUE, ';', 'T', '^', 'h', },
961 { VK_F2, TRUE, '<', 'U', '_', 'i', },
962 { VK_F3, TRUE, '=', 'V', '`', 'j', },
963 { VK_F4, TRUE, '>', 'W', 'a', 'k', },
964 { VK_F5, TRUE, '?', 'X', 'b', 'l', },
965 { VK_F6, TRUE, '@', 'Y', 'c', 'm', },
966 { VK_F7, TRUE, 'A', 'Z', 'd', 'n', },
967 { VK_F8, TRUE, 'B', '[', 'e', 'o', },
968 { VK_F9, TRUE, 'C', '\\', 'f', 'p', },
969 { VK_F10, TRUE, 'D', ']', 'g', 'q', },
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200970 { VK_F11, TRUE, '\205', '\207', '\211', '\213', },
971 { VK_F12, TRUE, '\206', '\210', '\212', '\214', },
Bram Moolenaar071d4272004-06-13 20:20:40 +0000972
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200973 { VK_HOME, TRUE, 'G', '\302', 'w', '\303', },
974 { VK_UP, TRUE, 'H', '\304', '\305', '\306', },
975 { VK_PRIOR, TRUE, 'I', '\307', '\204', '\310', }, // PgUp
976 { VK_LEFT, TRUE, 'K', '\311', 's', '\312', },
977 { VK_RIGHT, TRUE, 'M', '\313', 't', '\314', },
978 { VK_END, TRUE, 'O', '\315', 'u', '\316', },
979 { VK_DOWN, TRUE, 'P', '\317', '\320', '\321', },
980 { VK_NEXT, TRUE, 'Q', '\322', 'v', '\323', }, // PgDn
981 { VK_INSERT,TRUE, 'R', '\324', '\325', '\326', },
982 { VK_DELETE,TRUE, 'S', '\327', '\330', '\331', },
Bram Moolenaarb70a47b2019-03-30 22:11:21 +0100983 { VK_BACK, TRUE, 'x', 'y', 'z', '{', }, // Backspace
Bram Moolenaar071d4272004-06-13 20:20:40 +0000984
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200985 { VK_SNAPSHOT,TRUE, 0, 0, 0, 'r', }, // PrtScrn
Bram Moolenaar071d4272004-06-13 20:20:40 +0000986
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100987# if 0
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200988 // Most people don't have F13-F20, but what the hell...
989 { VK_F13, TRUE, '\332', '\333', '\334', '\335', },
990 { VK_F14, TRUE, '\336', '\337', '\340', '\341', },
991 { VK_F15, TRUE, '\342', '\343', '\344', '\345', },
992 { VK_F16, TRUE, '\346', '\347', '\350', '\351', },
993 { VK_F17, TRUE, '\352', '\353', '\354', '\355', },
994 { VK_F18, TRUE, '\356', '\357', '\360', '\361', },
995 { VK_F19, TRUE, '\362', '\363', '\364', '\365', },
996 { VK_F20, TRUE, '\366', '\367', '\370', '\371', },
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100997# endif
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200998 { VK_ADD, TRUE, 'N', 'N', 'N', 'N', }, // keyp '+'
999 { VK_SUBTRACT, TRUE,'J', 'J', 'J', 'J', }, // keyp '-'
1000 // { VK_DIVIDE, TRUE,'N', 'N', 'N', 'N', }, // keyp '/'
1001 { VK_MULTIPLY, TRUE,'7', '7', '7', '7', }, // keyp '*'
Bram Moolenaar071d4272004-06-13 20:20:40 +00001002
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +02001003 { VK_NUMPAD0,TRUE, '\332', '\333', '\334', '\335', },
1004 { VK_NUMPAD1,TRUE, '\336', '\337', '\340', '\341', },
1005 { VK_NUMPAD2,TRUE, '\342', '\343', '\344', '\345', },
1006 { VK_NUMPAD3,TRUE, '\346', '\347', '\350', '\351', },
1007 { VK_NUMPAD4,TRUE, '\352', '\353', '\354', '\355', },
1008 { VK_NUMPAD5,TRUE, '\356', '\357', '\360', '\361', },
1009 { VK_NUMPAD6,TRUE, '\362', '\363', '\364', '\365', },
1010 { VK_NUMPAD7,TRUE, '\366', '\367', '\370', '\371', },
1011 { VK_NUMPAD8,TRUE, '\372', '\373', '\374', '\375', },
1012 // Sorry, out of number space! <negri>
Bram Moolenaarb70a47b2019-03-30 22:11:21 +01001013 { VK_NUMPAD9,TRUE, '\376', '\377', '|', '}', },
Bram Moolenaar071d4272004-06-13 20:20:40 +00001014};
1015
1016
Bram Moolenaar0f873732019-12-05 20:28:46 +01001017/*
1018 * The return code indicates key code size.
1019 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001020 static int
Bram Moolenaar071d4272004-06-13 20:20:40 +00001021win32_kbd_patch_key(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001022 KEY_EVENT_RECORD *pker)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001023{
1024 UINT uMods = pker->dwControlKeyState;
1025 static int s_iIsDead = 0;
1026 static WORD awAnsiCode[2];
1027 static BYTE abKeystate[256];
1028
1029
1030 if (s_iIsDead == 2)
1031 {
K.Takata972db232022-02-04 10:45:38 +00001032 pker->uChar.UnicodeChar = (WCHAR) awAnsiCode[1];
Bram Moolenaar071d4272004-06-13 20:20:40 +00001033 s_iIsDead = 0;
1034 return 1;
1035 }
1036
K.Takata972db232022-02-04 10:45:38 +00001037 if (pker->uChar.UnicodeChar != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001038 return 1;
1039
Bram Moolenaara80faa82020-04-12 19:37:17 +02001040 CLEAR_FIELD(abKeystate);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001041
Bram Moolenaar0f873732019-12-05 20:28:46 +01001042 // Clear any pending dead keys
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001043 ToUnicode(VK_SPACE, MapVirtualKey(VK_SPACE, 0), abKeystate, awAnsiCode, 2, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001044
1045 if (uMods & SHIFT_PRESSED)
1046 abKeystate[VK_SHIFT] = 0x80;
1047 if (uMods & CAPSLOCK_ON)
1048 abKeystate[VK_CAPITAL] = 1;
1049
1050 if ((uMods & ALT_GR) == ALT_GR)
1051 {
1052 abKeystate[VK_CONTROL] = abKeystate[VK_LCONTROL] =
1053 abKeystate[VK_MENU] = abKeystate[VK_RMENU] = 0x80;
1054 }
1055
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001056 s_iIsDead = ToUnicode(pker->wVirtualKeyCode, pker->wVirtualScanCode,
1057 abKeystate, awAnsiCode, 2, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001058
1059 if (s_iIsDead > 0)
K.Takata972db232022-02-04 10:45:38 +00001060 pker->uChar.UnicodeChar = (WCHAR) awAnsiCode[0];
Bram Moolenaar071d4272004-06-13 20:20:40 +00001061
1062 return s_iIsDead;
1063}
1064
Bram Moolenaar071d4272004-06-13 20:20:40 +00001065static BOOL g_fJustGotFocus = FALSE;
1066
1067/*
1068 * Decode a KEY_EVENT into one or two keystrokes
1069 */
1070 static BOOL
1071decode_key_event(
1072 KEY_EVENT_RECORD *pker,
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001073 WCHAR *pch,
1074 WCHAR *pch2,
Bram Moolenaar071d4272004-06-13 20:20:40 +00001075 int *pmodifiers,
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02001076 BOOL fDoPost UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001077{
1078 int i;
1079 const int nModifs = pker->dwControlKeyState & (SHIFT | ALT | CTRL);
1080
1081 *pch = *pch2 = NUL;
1082 g_fJustGotFocus = FALSE;
1083
Bram Moolenaar0f873732019-12-05 20:28:46 +01001084 // ignore key up events
Bram Moolenaar071d4272004-06-13 20:20:40 +00001085 if (!pker->bKeyDown)
1086 return FALSE;
1087
Bram Moolenaar0f873732019-12-05 20:28:46 +01001088 // ignore some keystrokes
Bram Moolenaar071d4272004-06-13 20:20:40 +00001089 switch (pker->wVirtualKeyCode)
1090 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001091 // modifiers
Bram Moolenaar071d4272004-06-13 20:20:40 +00001092 case VK_SHIFT:
1093 case VK_CONTROL:
Bram Moolenaar0f873732019-12-05 20:28:46 +01001094 case VK_MENU: // Alt key
Bram Moolenaar071d4272004-06-13 20:20:40 +00001095 return FALSE;
1096
1097 default:
1098 break;
1099 }
1100
Bram Moolenaar0f873732019-12-05 20:28:46 +01001101 // special cases
K.Takata972db232022-02-04 10:45:38 +00001102 if ((nModifs & CTRL) != 0 && (nModifs & ~CTRL) == 0
1103 && pker->uChar.UnicodeChar == NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001104 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001105 // Ctrl-6 is Ctrl-^
Bram Moolenaar071d4272004-06-13 20:20:40 +00001106 if (pker->wVirtualKeyCode == '6')
1107 {
1108 *pch = Ctrl_HAT;
1109 return TRUE;
1110 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01001111 // Ctrl-2 is Ctrl-@
Bram Moolenaar071d4272004-06-13 20:20:40 +00001112 else if (pker->wVirtualKeyCode == '2')
1113 {
1114 *pch = NUL;
1115 return TRUE;
1116 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01001117 // Ctrl-- is Ctrl-_
Bram Moolenaar071d4272004-06-13 20:20:40 +00001118 else if (pker->wVirtualKeyCode == 0xBD)
1119 {
1120 *pch = Ctrl__;
1121 return TRUE;
1122 }
1123 }
1124
Bram Moolenaar0f873732019-12-05 20:28:46 +01001125 // Shift-TAB
Bram Moolenaar071d4272004-06-13 20:20:40 +00001126 if (pker->wVirtualKeyCode == VK_TAB && (nModifs & SHIFT_PRESSED))
1127 {
1128 *pch = K_NUL;
1129 *pch2 = '\017';
1130 return TRUE;
1131 }
1132
K.Takataeeec2542021-06-02 13:28:16 +02001133 for (i = ARRAY_LENGTH(VirtKeyMap); --i >= 0; )
Bram Moolenaar071d4272004-06-13 20:20:40 +00001134 {
1135 if (VirtKeyMap[i].wVirtKey == pker->wVirtualKeyCode)
1136 {
1137 if (nModifs == 0)
1138 *pch = VirtKeyMap[i].chAlone;
1139 else if ((nModifs & SHIFT) != 0 && (nModifs & ~SHIFT) == 0)
1140 *pch = VirtKeyMap[i].chShift;
1141 else if ((nModifs & CTRL) != 0 && (nModifs & ~CTRL) == 0)
1142 *pch = VirtKeyMap[i].chCtrl;
1143 else if ((nModifs & ALT) != 0 && (nModifs & ~ALT) == 0)
1144 *pch = VirtKeyMap[i].chAlt;
1145
1146 if (*pch != 0)
1147 {
1148 if (VirtKeyMap[i].fAnsiKey)
1149 {
1150 *pch2 = *pch;
1151 *pch = K_NUL;
1152 }
1153
1154 return TRUE;
1155 }
1156 }
1157 }
1158
1159 i = win32_kbd_patch_key(pker);
1160
1161 if (i < 0)
1162 *pch = NUL;
1163 else
1164 {
K.Takata972db232022-02-04 10:45:38 +00001165 *pch = (i > 0) ? pker->uChar.UnicodeChar : NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001166
1167 if (pmodifiers != NULL)
1168 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001169 // Pass on the ALT key as a modifier, but only when not combined
1170 // with CTRL (which is ALTGR).
Bram Moolenaar071d4272004-06-13 20:20:40 +00001171 if ((nModifs & ALT) != 0 && (nModifs & CTRL) == 0)
1172 *pmodifiers |= MOD_MASK_ALT;
1173
Bram Moolenaar0f873732019-12-05 20:28:46 +01001174 // Pass on SHIFT only for special keys, because we don't know when
1175 // it's already included with the character.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001176 if ((nModifs & SHIFT) != 0 && *pch <= 0x20)
1177 *pmodifiers |= MOD_MASK_SHIFT;
1178
Bram Moolenaar0f873732019-12-05 20:28:46 +01001179 // Pass on CTRL only for non-special keys, because we don't know
1180 // when it's already included with the character. And not when
1181 // combined with ALT (which is ALTGR).
Bram Moolenaar071d4272004-06-13 20:20:40 +00001182 if ((nModifs & CTRL) != 0 && (nModifs & ALT) == 0
1183 && *pch >= 0x20 && *pch < 0x80)
1184 *pmodifiers |= MOD_MASK_CTRL;
1185 }
1186 }
1187
1188 return (*pch != NUL);
1189}
1190
Bram Moolenaar0f873732019-12-05 20:28:46 +01001191#endif // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00001192
1193
Bram Moolenaar071d4272004-06-13 20:20:40 +00001194/*
1195 * For the GUI the mouse handling is in gui_w32.c.
1196 */
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001197#if defined(FEAT_GUI_MSWIN) && !defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001198 void
Bram Moolenaar1266d672017-02-01 13:43:36 +01001199mch_setmouse(int on UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001200{
1201}
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001202#else
Bram Moolenaar0f873732019-12-05 20:28:46 +01001203static int g_fMouseAvail = FALSE; // mouse present
1204static int g_fMouseActive = FALSE; // mouse enabled
1205static int g_nMouseClick = -1; // mouse status
1206static int g_xMouse; // mouse x coordinate
1207static int g_yMouse; // mouse y coordinate
Bram Moolenaar9f1983d2022-05-12 20:35:35 +01001208static DWORD g_cmodein = 0; // Original console input mode
1209static DWORD g_cmodeout = 0; // Original console output mode
Bram Moolenaar071d4272004-06-13 20:20:40 +00001210
1211/*
1212 * Enable or disable mouse input
1213 */
1214 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001215mch_setmouse(int on)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001216{
1217 DWORD cmodein;
1218
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001219# ifdef VIMDLL
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001220 if (gui.in_use)
1221 return;
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001222# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001223 if (!g_fMouseAvail)
1224 return;
1225
1226 g_fMouseActive = on;
1227 GetConsoleMode(g_hConIn, &cmodein);
1228
1229 if (g_fMouseActive)
Wez Furlong6ef5ab52021-05-30 19:29:41 +02001230 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00001231 cmodein |= ENABLE_MOUSE_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02001232 cmodein &= ~ENABLE_QUICK_EDIT_MODE;
1233 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001234 else
Wez Furlong6ef5ab52021-05-30 19:29:41 +02001235 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00001236 cmodein &= ~ENABLE_MOUSE_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02001237 cmodein |= g_cmodein & ENABLE_QUICK_EDIT_MODE;
1238 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001239
Wez Furlong6ef5ab52021-05-30 19:29:41 +02001240 SetConsoleMode(g_hConIn, cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001241}
1242
Bram Moolenaar157d8132018-03-06 17:09:20 +01001243
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001244# if defined(FEAT_BEVAL_TERM) || defined(PROTO)
Bram Moolenaar157d8132018-03-06 17:09:20 +01001245/*
1246 * Called when 'balloonevalterm' changed.
1247 */
1248 void
1249mch_bevalterm_changed(void)
1250{
1251 mch_setmouse(g_fMouseActive);
1252}
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001253# endif
Bram Moolenaar157d8132018-03-06 17:09:20 +01001254
Bram Moolenaar071d4272004-06-13 20:20:40 +00001255/*
1256 * Decode a MOUSE_EVENT. If it's a valid event, return MOUSE_LEFT,
1257 * MOUSE_MIDDLE, or MOUSE_RIGHT for a click; MOUSE_DRAG for a mouse
1258 * move with a button held down; and MOUSE_RELEASE after a MOUSE_DRAG
1259 * or a MOUSE_LEFT, _MIDDLE, or _RIGHT. We encode the button type,
1260 * the number of clicks, and the Shift/Ctrl/Alt modifiers in g_nMouseClick,
1261 * and we return the mouse position in g_xMouse and g_yMouse.
1262 *
1263 * Every MOUSE_LEFT, _MIDDLE, or _RIGHT will be followed by zero or more
1264 * MOUSE_DRAGs and one MOUSE_RELEASE. MOUSE_RELEASE will be followed only
1265 * by MOUSE_LEFT, _MIDDLE, or _RIGHT.
1266 *
1267 * For multiple clicks, we send, say, MOUSE_LEFT/1 click, MOUSE_RELEASE,
1268 * MOUSE_LEFT/2 clicks, MOUSE_RELEASE, MOUSE_LEFT/3 clicks, MOUSE_RELEASE, ....
1269 *
1270 * Windows will send us MOUSE_MOVED notifications whenever the mouse
1271 * moves, even if it stays within the same character cell. We ignore
1272 * all MOUSE_MOVED messages if the position hasn't really changed, and
1273 * we ignore all MOUSE_MOVED messages where no button is held down (i.e.,
1274 * we're only interested in MOUSE_DRAG).
1275 *
1276 * All of this is complicated by the code that fakes MOUSE_MIDDLE on
1277 * 2-button mouses by pressing the left & right buttons simultaneously.
1278 * In practice, it's almost impossible to click both at the same time,
1279 * so we need to delay a little. Also, we tend not to get MOUSE_RELEASE
1280 * in such cases, if the user is clicking quickly.
1281 */
1282 static BOOL
1283decode_mouse_event(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001284 MOUSE_EVENT_RECORD *pmer)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001285{
1286 static int s_nOldButton = -1;
1287 static int s_nOldMouseClick = -1;
1288 static int s_xOldMouse = -1;
1289 static int s_yOldMouse = -1;
1290 static linenr_T s_old_topline = 0;
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001291# ifdef FEAT_DIFF
Bram Moolenaar071d4272004-06-13 20:20:40 +00001292 static int s_old_topfill = 0;
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001293# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001294 static int s_cClicks = 1;
1295 static BOOL s_fReleased = TRUE;
1296 static DWORD s_dwLastClickTime = 0;
1297 static BOOL s_fNextIsMiddle = FALSE;
1298
Bram Moolenaar0f873732019-12-05 20:28:46 +01001299 static DWORD cButtons = 0; // number of buttons supported
Bram Moolenaar071d4272004-06-13 20:20:40 +00001300
1301 const DWORD LEFT = FROM_LEFT_1ST_BUTTON_PRESSED;
1302 const DWORD MIDDLE = FROM_LEFT_2ND_BUTTON_PRESSED;
1303 const DWORD RIGHT = RIGHTMOST_BUTTON_PRESSED;
1304 const DWORD LEFT_RIGHT = LEFT | RIGHT;
1305
1306 int nButton;
1307
1308 if (cButtons == 0 && !GetNumberOfConsoleMouseButtons(&cButtons))
1309 cButtons = 2;
1310
1311 if (!g_fMouseAvail || !g_fMouseActive)
1312 {
1313 g_nMouseClick = -1;
1314 return FALSE;
1315 }
1316
Bram Moolenaar0f873732019-12-05 20:28:46 +01001317 // get a spurious MOUSE_EVENT immediately after receiving focus; ignore
Bram Moolenaar071d4272004-06-13 20:20:40 +00001318 if (g_fJustGotFocus)
1319 {
1320 g_fJustGotFocus = FALSE;
1321 return FALSE;
1322 }
1323
Bram Moolenaar0f873732019-12-05 20:28:46 +01001324 // unprocessed mouse click?
Bram Moolenaar071d4272004-06-13 20:20:40 +00001325 if (g_nMouseClick != -1)
1326 return TRUE;
1327
1328 nButton = -1;
1329 g_xMouse = pmer->dwMousePosition.X;
1330 g_yMouse = pmer->dwMousePosition.Y;
1331
1332 if (pmer->dwEventFlags == MOUSE_MOVED)
1333 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001334 // Ignore MOUSE_MOVED events if (x, y) hasn't changed. (We get these
1335 // events even when the mouse moves only within a char cell.)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001336 if (s_xOldMouse == g_xMouse && s_yOldMouse == g_yMouse)
1337 return FALSE;
1338 }
1339
Bram Moolenaar0f873732019-12-05 20:28:46 +01001340 // If no buttons are pressed...
Bram Moolenaar071d4272004-06-13 20:20:40 +00001341 if ((pmer->dwButtonState & ((1 << cButtons) - 1)) == 0)
1342 {
Bram Moolenaar157d8132018-03-06 17:09:20 +01001343 nButton = MOUSE_RELEASE;
1344
Bram Moolenaar0f873732019-12-05 20:28:46 +01001345 // If the last thing returned was MOUSE_RELEASE, ignore this
Bram Moolenaar071d4272004-06-13 20:20:40 +00001346 if (s_fReleased)
Bram Moolenaar157d8132018-03-06 17:09:20 +01001347 {
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001348# ifdef FEAT_BEVAL_TERM
Bram Moolenaar0f873732019-12-05 20:28:46 +01001349 // do return mouse move events when we want them
Bram Moolenaar157d8132018-03-06 17:09:20 +01001350 if (p_bevalterm)
1351 nButton = MOUSE_DRAG;
1352 else
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001353# endif
Bram Moolenaar157d8132018-03-06 17:09:20 +01001354 return FALSE;
1355 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001356
Bram Moolenaar071d4272004-06-13 20:20:40 +00001357 s_fReleased = TRUE;
1358 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01001359 else // one or more buttons pressed
Bram Moolenaar071d4272004-06-13 20:20:40 +00001360 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001361 // on a 2-button mouse, hold down left and right buttons
1362 // simultaneously to get MIDDLE.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001363
1364 if (cButtons == 2 && s_nOldButton != MOUSE_DRAG)
1365 {
1366 DWORD dwLR = (pmer->dwButtonState & LEFT_RIGHT);
1367
Bram Moolenaar0f873732019-12-05 20:28:46 +01001368 // if either left or right button only is pressed, see if the
1369 // next mouse event has both of them pressed
Bram Moolenaar071d4272004-06-13 20:20:40 +00001370 if (dwLR == LEFT || dwLR == RIGHT)
1371 {
1372 for (;;)
1373 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001374 // wait a short time for next input event
Bram Moolenaar071d4272004-06-13 20:20:40 +00001375 if (WaitForSingleObject(g_hConIn, p_mouset / 3)
1376 != WAIT_OBJECT_0)
1377 break;
1378 else
1379 {
1380 DWORD cRecords = 0;
1381 INPUT_RECORD ir;
1382 MOUSE_EVENT_RECORD* pmer2 = &ir.Event.MouseEvent;
1383
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001384 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001385
1386 if (cRecords == 0 || ir.EventType != MOUSE_EVENT
1387 || !(pmer2->dwButtonState & LEFT_RIGHT))
1388 break;
1389 else
1390 {
1391 if (pmer2->dwEventFlags != MOUSE_MOVED)
1392 {
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001393 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001394
1395 return decode_mouse_event(pmer2);
1396 }
1397 else if (s_xOldMouse == pmer2->dwMousePosition.X &&
1398 s_yOldMouse == pmer2->dwMousePosition.Y)
1399 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001400 // throw away spurious mouse move
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001401 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001402
Bram Moolenaar0f873732019-12-05 20:28:46 +01001403 // are there any more mouse events in queue?
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001404 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001405
1406 if (cRecords==0 || ir.EventType != MOUSE_EVENT)
1407 break;
1408 }
1409 else
1410 break;
1411 }
1412 }
1413 }
1414 }
1415 }
1416
1417 if (s_fNextIsMiddle)
1418 {
1419 nButton = (pmer->dwEventFlags == MOUSE_MOVED)
1420 ? MOUSE_DRAG : MOUSE_MIDDLE;
1421 s_fNextIsMiddle = FALSE;
1422 }
1423 else if (cButtons == 2 &&
1424 ((pmer->dwButtonState & LEFT_RIGHT) == LEFT_RIGHT))
1425 {
1426 nButton = MOUSE_MIDDLE;
1427
1428 if (! s_fReleased && pmer->dwEventFlags != MOUSE_MOVED)
1429 {
1430 s_fNextIsMiddle = TRUE;
1431 nButton = MOUSE_RELEASE;
1432 }
1433 }
1434 else if ((pmer->dwButtonState & LEFT) == LEFT)
1435 nButton = MOUSE_LEFT;
1436 else if ((pmer->dwButtonState & MIDDLE) == MIDDLE)
1437 nButton = MOUSE_MIDDLE;
1438 else if ((pmer->dwButtonState & RIGHT) == RIGHT)
1439 nButton = MOUSE_RIGHT;
1440
1441 if (! s_fReleased && ! s_fNextIsMiddle
1442 && nButton != s_nOldButton && s_nOldButton != MOUSE_DRAG)
1443 return FALSE;
1444
1445 s_fReleased = s_fNextIsMiddle;
1446 }
1447
1448 if (pmer->dwEventFlags == 0 || pmer->dwEventFlags == DOUBLE_CLICK)
1449 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001450 // button pressed or released, without mouse moving
Bram Moolenaar071d4272004-06-13 20:20:40 +00001451 if (nButton != -1 && nButton != MOUSE_RELEASE)
1452 {
1453 DWORD dwCurrentTime = GetTickCount();
1454
1455 if (s_xOldMouse != g_xMouse
1456 || s_yOldMouse != g_yMouse
1457 || s_nOldButton != nButton
1458 || s_old_topline != curwin->w_topline
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001459# ifdef FEAT_DIFF
Bram Moolenaar071d4272004-06-13 20:20:40 +00001460 || s_old_topfill != curwin->w_topfill
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001461# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001462 || (int)(dwCurrentTime - s_dwLastClickTime) > p_mouset)
1463 {
1464 s_cClicks = 1;
1465 }
1466 else if (++s_cClicks > 4)
1467 {
1468 s_cClicks = 1;
1469 }
1470
1471 s_dwLastClickTime = dwCurrentTime;
1472 }
1473 }
1474 else if (pmer->dwEventFlags == MOUSE_MOVED)
1475 {
1476 if (nButton != -1 && nButton != MOUSE_RELEASE)
1477 nButton = MOUSE_DRAG;
1478
1479 s_cClicks = 1;
1480 }
1481
1482 if (nButton == -1)
1483 return FALSE;
1484
1485 if (nButton != MOUSE_RELEASE)
1486 s_nOldButton = nButton;
1487
1488 g_nMouseClick = nButton;
1489
1490 if (pmer->dwControlKeyState & SHIFT_PRESSED)
1491 g_nMouseClick |= MOUSE_SHIFT;
1492 if (pmer->dwControlKeyState & (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED))
1493 g_nMouseClick |= MOUSE_CTRL;
1494 if (pmer->dwControlKeyState & (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED))
1495 g_nMouseClick |= MOUSE_ALT;
1496
1497 if (nButton != MOUSE_DRAG && nButton != MOUSE_RELEASE)
1498 SET_NUM_MOUSE_CLICKS(g_nMouseClick, s_cClicks);
1499
Bram Moolenaar0f873732019-12-05 20:28:46 +01001500 // only pass on interesting (i.e., different) mouse events
Bram Moolenaar071d4272004-06-13 20:20:40 +00001501 if (s_xOldMouse == g_xMouse
1502 && s_yOldMouse == g_yMouse
1503 && s_nOldMouseClick == g_nMouseClick)
1504 {
1505 g_nMouseClick = -1;
1506 return FALSE;
1507 }
1508
1509 s_xOldMouse = g_xMouse;
1510 s_yOldMouse = g_yMouse;
1511 s_old_topline = curwin->w_topline;
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001512# ifdef FEAT_DIFF
Bram Moolenaar071d4272004-06-13 20:20:40 +00001513 s_old_topfill = curwin->w_topfill;
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001514# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001515 s_nOldMouseClick = g_nMouseClick;
1516
1517 return TRUE;
1518}
1519
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001520#endif // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00001521
1522
1523#ifdef MCH_CURSOR_SHAPE
1524/*
1525 * Set the shape of the cursor.
1526 * 'thickness' can be from 1 (thin) to 99 (block)
1527 */
1528 static void
1529mch_set_cursor_shape(int thickness)
1530{
K.Takatadf5320c2022-09-01 13:20:16 +01001531 if (USE_VTP || USE_WT)
1532 {
1533 if (*T_CSI == NUL)
1534 {
1535 // If 't_SI' is not set, use the default cursor styles.
1536 if (thickness < 50)
1537 vtp_printf("\033[3 q"); // underline
1538 else
1539 vtp_printf("\033[0 q"); // default
1540 }
1541 }
1542 else
1543 {
1544 CONSOLE_CURSOR_INFO ConsoleCursorInfo;
1545 ConsoleCursorInfo.dwSize = thickness;
1546 ConsoleCursorInfo.bVisible = s_cursor_visible;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001547
K.Takatadf5320c2022-09-01 13:20:16 +01001548 SetConsoleCursorInfo(g_hConOut, &ConsoleCursorInfo);
1549 if (s_cursor_visible)
1550 SetConsoleCursorPosition(g_hConOut, g_coord);
1551 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001552}
1553
1554 void
1555mch_update_cursor(void)
1556{
1557 int idx;
1558 int thickness;
1559
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001560# ifdef VIMDLL
1561 if (gui.in_use)
1562 return;
1563# endif
1564
Bram Moolenaar071d4272004-06-13 20:20:40 +00001565 /*
1566 * How the cursor is drawn depends on the current mode.
1567 */
1568 idx = get_shape_idx(FALSE);
1569
1570 if (shape_table[idx].shape == SHAPE_BLOCK)
Bram Moolenaar0f873732019-12-05 20:28:46 +01001571 thickness = 99; // 100 doesn't work on W95
Bram Moolenaar071d4272004-06-13 20:20:40 +00001572 else
1573 thickness = shape_table[idx].percentage;
1574 mch_set_cursor_shape(thickness);
1575}
1576#endif
1577
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001578#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001579/*
1580 * Handle FOCUS_EVENT.
1581 */
1582 static void
1583handle_focus_event(INPUT_RECORD ir)
1584{
1585 g_fJustGotFocus = ir.Event.FocusEvent.bSetFocus;
1586 ui_focus_change((int)g_fJustGotFocus);
1587}
1588
Bram Moolenaar78d21da2019-02-17 15:00:52 +01001589static void ResizeConBuf(HANDLE hConsole, COORD coordScreen);
1590
Bram Moolenaar071d4272004-06-13 20:20:40 +00001591/*
1592 * Wait until console input from keyboard or mouse is available,
1593 * or the time is up.
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001594 * When "ignore_input" is TRUE even wait when input is available.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001595 * Return TRUE if something is available FALSE if not.
1596 */
1597 static int
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001598WaitForChar(long msec, int ignore_input)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001599{
1600 DWORD dwNow = 0, dwEndTime = 0;
1601 INPUT_RECORD ir;
1602 DWORD cRecords;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001603 WCHAR ch, ch2;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001604# ifdef FEAT_TIMERS
Bram Moolenaar40b1b542016-04-20 20:18:23 +02001605 int tb_change_cnt = typebuf.tb_change_cnt;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001606# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001607
1608 if (msec > 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01001609 // Wait until the specified time has elapsed.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001610 dwEndTime = GetTickCount() + msec;
1611 else if (msec < 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01001612 // Wait forever.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001613 dwEndTime = INFINITE;
1614
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01001615 // We need to loop until the end of the time period, because
1616 // we might get multiple unusable mouse events in that time.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001617 for (;;)
1618 {
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001619 // Only process messages when waiting.
1620 if (msec != 0)
1621 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001622# ifdef MESSAGE_QUEUE
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001623 parse_queued_messages();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001624# endif
1625# ifdef FEAT_MZSCHEME
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001626 mzvim_check_threads();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001627# endif
1628# ifdef FEAT_CLIENTSERVER
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001629 serverProcessPendingMessages();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001630# endif
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001631 }
Bram Moolenaarf12d9832016-01-29 21:11:25 +01001632
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001633 if (g_nMouseClick != -1
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001634# ifdef FEAT_CLIENTSERVER
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001635 || (!ignore_input && input_available())
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001636# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001637 )
1638 return TRUE;
1639
1640 if (msec > 0)
1641 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001642 // If the specified wait time has passed, return. Beware that
1643 // GetTickCount() may wrap around (overflow).
Bram Moolenaar071d4272004-06-13 20:20:40 +00001644 dwNow = GetTickCount();
Bram Moolenaarb7512b72013-08-10 12:45:09 +02001645 if ((int)(dwNow - dwEndTime) >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001646 break;
1647 }
1648 if (msec != 0)
1649 {
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001650 DWORD dwWaitTime = dwEndTime - dwNow;
1651
Bram Moolenaarc478ee32020-12-01 21:27:51 +01001652 // Don't wait for more than 11 msec to avoid dropping characters,
1653 // check channel while waiting for input and handle a callback from
1654 // 'balloonexpr'.
1655 if (dwWaitTime > 11)
1656 dwWaitTime = 11;
1657
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001658# ifdef FEAT_MZSCHEME
Bram Moolenaarc478ee32020-12-01 21:27:51 +01001659 if (mzthreads_allowed() && p_mzq > 0 && (long)dwWaitTime > p_mzq)
Bram Moolenaar0f873732019-12-05 20:28:46 +01001660 dwWaitTime = p_mzq; // don't wait longer than 'mzquantum'
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001661# endif
1662# ifdef FEAT_TIMERS
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001663 // When waiting very briefly don't trigger timers.
1664 if (dwWaitTime > 10)
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001665 {
1666 long due_time;
1667
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001668 // Trigger timers and then get the time in msec until the next
1669 // one is due. Wait up to that time.
1670 due_time = check_due_timer();
1671 if (typebuf.tb_change_cnt != tb_change_cnt)
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001672 {
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001673 // timer may have used feedkeys().
1674 return FALSE;
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001675 }
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001676 if (due_time > 0 && dwWaitTime > (DWORD)due_time)
1677 dwWaitTime = due_time;
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001678 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001679# endif
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001680 if (
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001681# ifdef FEAT_CLIENTSERVER
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001682 // Wait for either an event on the console input or a
1683 // message in the client-server window.
1684 msg_wait_for_multiple_objects(1, &g_hConIn, FALSE,
1685 dwWaitTime, QS_SENDMESSAGE) != WAIT_OBJECT_0
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001686# else
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001687 wait_for_single_object(g_hConIn, dwWaitTime)
1688 != WAIT_OBJECT_0
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001689# endif
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001690 )
1691 continue;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001692 }
1693
1694 cRecords = 0;
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001695 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001696
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001697# ifdef FEAT_MBYTE_IME
matveyt4eb19142021-05-20 11:54:10 +02001698 // May have to redraw if the cursor ends up in the wrong place.
1699 // Only when not peeking.
Bram Moolenaar24959102022-05-07 20:01:16 +01001700 if (State == MODE_CMDLINE && msg_row == Rows - 1 && msec != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001701 {
1702 CONSOLE_SCREEN_BUFFER_INFO csbi;
1703
1704 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
1705 {
1706 if (csbi.dwCursorPosition.Y != msg_row)
1707 {
matveyte08795e2021-05-07 15:00:17 +02001708 // The screen is now messed up, must redraw the command
1709 // line and later all the windows.
Bram Moolenaara4d158b2022-08-14 14:17:45 +01001710 redraw_all_later(UPD_CLEAR);
matveyte08795e2021-05-07 15:00:17 +02001711 compute_cmdrow();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001712 redrawcmd();
1713 }
1714 }
1715 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001716# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001717
1718 if (cRecords > 0)
1719 {
1720 if (ir.EventType == KEY_EVENT && ir.Event.KeyEvent.bKeyDown)
1721 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001722# ifdef FEAT_MBYTE_IME
Bram Moolenaar0f873732019-12-05 20:28:46 +01001723 // Windows IME sends two '\n's with only one 'ENTER'. First:
1724 // wVirtualKeyCode == 13. second: wVirtualKeyCode == 0
K.Takata972db232022-02-04 10:45:38 +00001725 if (ir.Event.KeyEvent.uChar.UnicodeChar == 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00001726 && ir.Event.KeyEvent.wVirtualKeyCode == 13)
1727 {
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001728 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001729 continue;
1730 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001731# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001732 if (decode_key_event(&ir.Event.KeyEvent, &ch, &ch2,
1733 NULL, FALSE))
1734 return TRUE;
1735 }
1736
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001737 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001738
1739 if (ir.EventType == FOCUS_EVENT)
1740 handle_focus_event(ir);
1741 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
Bram Moolenaarc33ecb22018-02-11 16:40:45 +01001742 {
Bram Moolenaar78d21da2019-02-17 15:00:52 +01001743 COORD dwSize = ir.Event.WindowBufferSizeEvent.dwSize;
1744
Bram Moolenaar36698e32019-12-11 22:57:40 +01001745 // Only call shell_resized() when the size actually changed to
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001746 // avoid the screen is cleared.
Bram Moolenaar78d21da2019-02-17 15:00:52 +01001747 if (dwSize.X != Columns || dwSize.Y != Rows)
1748 {
1749 CONSOLE_SCREEN_BUFFER_INFO csbi;
1750 GetConsoleScreenBufferInfo(g_hConOut, &csbi);
Bram Moolenaar36698e32019-12-11 22:57:40 +01001751 dwSize.X = csbi.srWindow.Right - csbi.srWindow.Left + 1;
Bram Moolenaar78d21da2019-02-17 15:00:52 +01001752 dwSize.Y = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
Bram Moolenaar36698e32019-12-11 22:57:40 +01001753 if (dwSize.X != Columns || dwSize.Y != Rows)
1754 {
1755 ResizeConBuf(g_hConOut, dwSize);
1756 shell_resized();
1757 }
Bram Moolenaar78d21da2019-02-17 15:00:52 +01001758 }
Bram Moolenaarc33ecb22018-02-11 16:40:45 +01001759 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001760 else if (ir.EventType == MOUSE_EVENT
1761 && decode_mouse_event(&ir.Event.MouseEvent))
1762 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001763 }
1764 else if (msec == 0)
1765 break;
1766 }
1767
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001768# ifdef FEAT_CLIENTSERVER
Bram Moolenaar0f873732019-12-05 20:28:46 +01001769 // Something might have been received while we were waiting.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001770 if (input_available())
1771 return TRUE;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001772# endif
Bram Moolenaarf12d9832016-01-29 21:11:25 +01001773
Bram Moolenaar071d4272004-06-13 20:20:40 +00001774 return FALSE;
1775}
1776
Bram Moolenaar071d4272004-06-13 20:20:40 +00001777/*
1778 * return non-zero if a character is available
1779 */
1780 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001781mch_char_avail(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001782{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001783# ifdef VIMDLL
1784 if (gui.in_use)
1785 return TRUE;
1786# endif
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001787 return WaitForChar(0L, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001788}
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001789
1790# if defined(FEAT_TERMINAL) || defined(PROTO)
1791/*
1792 * Check for any pending input or messages.
1793 */
1794 int
1795mch_check_messages(void)
1796{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001797# ifdef VIMDLL
1798 if (gui.in_use)
1799 return TRUE;
1800# endif
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001801 return WaitForChar(0L, TRUE);
1802}
1803# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001804
1805/*
1806 * Create the console input. Used when reading stdin doesn't work.
1807 */
1808 static void
1809create_conin(void)
1810{
1811 g_hConIn = CreateFile("CONIN$", GENERIC_READ|GENERIC_WRITE,
1812 FILE_SHARE_READ|FILE_SHARE_WRITE,
1813 (LPSECURITY_ATTRIBUTES) NULL,
Bram Moolenaareb3593b2006-04-22 22:33:57 +00001814 OPEN_EXISTING, 0, (HANDLE)NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001815 did_create_conin = TRUE;
1816}
1817
1818/*
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001819 * Get a keystroke or a mouse event, use a blocking wait.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001820 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001821 static WCHAR
1822tgetch(int *pmodifiers, WCHAR *pch2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001823{
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001824 WCHAR ch;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001825
1826 for (;;)
1827 {
1828 INPUT_RECORD ir;
1829 DWORD cRecords = 0;
1830
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001831# ifdef FEAT_CLIENTSERVER
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001832 (void)WaitForChar(-1L, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001833 if (input_available())
1834 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001835 if (g_nMouseClick != -1)
1836 return 0;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001837# endif
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001838 if (read_console_input(g_hConIn, &ir, 1, &cRecords) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001839 {
1840 if (did_create_conin)
1841 read_error_exit();
1842 create_conin();
1843 continue;
1844 }
1845
1846 if (ir.EventType == KEY_EVENT)
1847 {
1848 if (decode_key_event(&ir.Event.KeyEvent, &ch, pch2,
1849 pmodifiers, TRUE))
1850 return ch;
1851 }
1852 else if (ir.EventType == FOCUS_EVENT)
1853 handle_focus_event(ir);
1854 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
1855 shell_resized();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001856 else if (ir.EventType == MOUSE_EVENT)
1857 {
1858 if (decode_mouse_event(&ir.Event.MouseEvent))
1859 return 0;
1860 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001861 }
1862}
Bram Moolenaar0f873732019-12-05 20:28:46 +01001863#endif // !FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00001864
1865
1866/*
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02001867 * mch_inchar(): low-level input function.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001868 * Get one or more characters from the keyboard or the mouse.
1869 * If time == 0, do not wait for characters.
1870 * If time == n, wait a short time for characters.
1871 * If time == -1, wait forever for characters.
1872 * Returns the number of characters read into buf.
1873 */
1874 int
1875mch_inchar(
Bram Moolenaar1266d672017-02-01 13:43:36 +01001876 char_u *buf UNUSED,
1877 int maxlen UNUSED,
1878 long time UNUSED,
1879 int tb_change_cnt UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001880{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001881#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001882
1883 int len;
1884 int c;
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01001885# ifdef VIMDLL
1886// Extra space for maximum three CSIs. E.g. U+1B6DB -> 0xF0 0x9B 0x9B 0x9B.
1887# define TYPEAHEADSPACE 6
1888# else
1889# define TYPEAHEADSPACE 0
1890# endif
1891# define TYPEAHEADLEN (20 + TYPEAHEADSPACE)
Bram Moolenaar0f873732019-12-05 20:28:46 +01001892 static char_u typeahead[TYPEAHEADLEN]; // previously typed bytes.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001893 static int typeaheadlen = 0;
1894
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001895# ifdef VIMDLL
1896 if (gui.in_use)
1897 return 0;
1898# endif
1899
Bram Moolenaar0f873732019-12-05 20:28:46 +01001900 // First use any typeahead that was kept because "buf" was too small.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001901 if (typeaheadlen > 0)
1902 goto theend;
1903
Bram Moolenaar071d4272004-06-13 20:20:40 +00001904 if (time >= 0)
1905 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001906 if (!WaitForChar(time, FALSE)) // no character available
Bram Moolenaar071d4272004-06-13 20:20:40 +00001907 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001908 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01001909 else // time == -1, wait forever
Bram Moolenaar071d4272004-06-13 20:20:40 +00001910 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001911 mch_set_winsize_now(); // Allow winsize changes from now on
Bram Moolenaar071d4272004-06-13 20:20:40 +00001912
Bram Moolenaar3918c952005-03-15 22:34:55 +00001913 /*
1914 * If there is no character available within 2 seconds (default)
1915 * write the autoscript file to disk. Or cause the CursorHold event
1916 * to be triggered.
1917 */
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001918 if (!WaitForChar(p_ut, FALSE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001919 {
Bram Moolenaard35f9712005-12-18 22:02:33 +00001920 if (trigger_cursorhold() && maxlen >= 3)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001921 {
Bram Moolenaar3918c952005-03-15 22:34:55 +00001922 buf[0] = K_SPECIAL;
1923 buf[1] = KS_EXTRA;
1924 buf[2] = (int)KE_CURSORHOLD;
1925 return 3;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001926 }
Bram Moolenaar702517d2005-06-27 22:34:07 +00001927 before_blocking();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001928 }
1929 }
1930
1931 /*
1932 * Try to read as many characters as there are, until the buffer is full.
1933 */
1934
Bram Moolenaar0f873732019-12-05 20:28:46 +01001935 // we will get at least one key. Get more if they are available.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001936 g_fCBrkPressed = FALSE;
1937
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001938# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00001939 if (fdDump)
1940 fputc('[', fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001941# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001942
Bram Moolenaar0f873732019-12-05 20:28:46 +01001943 // Keep looping until there is something in the typeahead buffer and more
1944 // to get and still room in the buffer (up to two bytes for a char and
1945 // three bytes for a modifier).
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001946 while ((typeaheadlen == 0 || WaitForChar(0L, FALSE))
Bram Moolenaar9f1983d2022-05-12 20:35:35 +01001947 && typeaheadlen + 5 + TYPEAHEADSPACE <= TYPEAHEADLEN)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001948 {
1949 if (typebuf_changed(tb_change_cnt))
1950 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001951 // "buf" may be invalid now if a client put something in the
1952 // typeahead buffer and "buf" is in the typeahead buffer.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001953 typeaheadlen = 0;
1954 break;
1955 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001956 if (g_nMouseClick != -1)
1957 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001958# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00001959 if (fdDump)
1960 fprintf(fdDump, "{%02x @ %d, %d}",
1961 g_nMouseClick, g_xMouse, g_yMouse);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001962# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001963 typeahead[typeaheadlen++] = ESC + 128;
1964 typeahead[typeaheadlen++] = 'M';
1965 typeahead[typeaheadlen++] = g_nMouseClick;
1966 typeahead[typeaheadlen++] = g_xMouse + '!';
1967 typeahead[typeaheadlen++] = g_yMouse + '!';
1968 g_nMouseClick = -1;
1969 }
1970 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00001971 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001972 WCHAR ch2 = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001973 int modifiers = 0;
1974
1975 c = tgetch(&modifiers, &ch2);
1976
1977 if (typebuf_changed(tb_change_cnt))
1978 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001979 // "buf" may be invalid now if a client put something in the
1980 // typeahead buffer and "buf" is in the typeahead buffer.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001981 typeaheadlen = 0;
1982 break;
1983 }
1984
1985 if (c == Ctrl_C && ctrl_c_interrupts)
1986 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001987# if defined(FEAT_CLIENTSERVER)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001988 trash_input_buf();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001989# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001990 got_int = TRUE;
1991 }
1992
Bram Moolenaar071d4272004-06-13 20:20:40 +00001993 if (g_nMouseClick == -1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001994 {
1995 int n = 1;
1996
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001997 if (ch2 == NUL)
1998 {
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01001999 int i, j;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002000 char_u *p;
2001 WCHAR ch[2];
2002
2003 ch[0] = c;
Bram Moolenaar0f873732019-12-05 20:28:46 +01002004 if (c >= 0xD800 && c <= 0xDBFF) // High surrogate
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002005 {
2006 ch[1] = tgetch(&modifiers, &ch2);
2007 n++;
2008 }
2009 p = utf16_to_enc(ch, &n);
2010 if (p != NULL)
2011 {
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01002012 for (i = 0, j = 0; i < n; i++)
2013 {
2014 typeahead[typeaheadlen + j++] = p[i];
2015# ifdef VIMDLL
2016 if (p[i] == CSI)
2017 {
2018 typeahead[typeaheadlen + j++] = KS_EXTRA;
2019 typeahead[typeaheadlen + j++] = KE_CSI;
2020 }
2021# endif
2022 }
2023 n = j;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002024 vim_free(p);
2025 }
2026 }
2027 else
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01002028 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002029 typeahead[typeaheadlen] = c;
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01002030# ifdef VIMDLL
2031 if (c == CSI)
2032 {
2033 typeahead[typeaheadlen + 1] = KS_EXTRA;
2034 typeahead[typeaheadlen + 2] = KE_CSI;
2035 n = 3;
2036 }
2037# endif
2038 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002039 if (ch2 != NUL)
2040 {
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +02002041 if (c == K_NUL)
Bram Moolenaarfeeb4d02017-12-05 15:14:46 +01002042 {
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +02002043 switch (ch2)
2044 {
2045 case (WCHAR)'\324': // SHIFT+Insert
2046 case (WCHAR)'\325': // CTRL+Insert
2047 case (WCHAR)'\327': // SHIFT+Delete
2048 case (WCHAR)'\330': // CTRL+Delete
2049 typeahead[typeaheadlen + n] = (char_u)ch2;
2050 n++;
2051 break;
2052
2053 default:
2054 typeahead[typeaheadlen + n] = 3;
2055 typeahead[typeaheadlen + n + 1] = (char_u)ch2;
2056 n += 2;
2057 break;
2058 }
Bram Moolenaarfeeb4d02017-12-05 15:14:46 +01002059 }
2060 else
2061 {
2062 typeahead[typeaheadlen + n] = 3;
2063 typeahead[typeaheadlen + n + 1] = (char_u)ch2;
2064 n += 2;
2065 }
Bram Moolenaar45500912014-07-09 20:51:07 +02002066 }
2067
Bram Moolenaar0f873732019-12-05 20:28:46 +01002068 // Use the ALT key to set the 8th bit of the character
2069 // when it's one byte, the 8th bit isn't set yet and not
2070 // using a double-byte encoding (would become a lead
2071 // byte).
Bram Moolenaar071d4272004-06-13 20:20:40 +00002072 if ((modifiers & MOD_MASK_ALT)
2073 && n == 1
2074 && (typeahead[typeaheadlen] & 0x80) == 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00002075 && !enc_dbcs
Bram Moolenaar071d4272004-06-13 20:20:40 +00002076 )
2077 {
Bram Moolenaar85a3e5c2007-11-20 16:22:16 +00002078 n = (*mb_char2bytes)(typeahead[typeaheadlen] | 0x80,
2079 typeahead + typeaheadlen);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002080 modifiers &= ~MOD_MASK_ALT;
2081 }
2082
2083 if (modifiers != 0)
2084 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01002085 // Prepend modifiers to the character.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002086 mch_memmove(typeahead + typeaheadlen + 3,
2087 typeahead + typeaheadlen, n);
2088 typeahead[typeaheadlen++] = K_SPECIAL;
2089 typeahead[typeaheadlen++] = (char_u)KS_MODIFIER;
2090 typeahead[typeaheadlen++] = modifiers;
2091 }
2092
2093 typeaheadlen += n;
2094
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002095# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00002096 if (fdDump)
2097 fputc(c, fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002098# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002099 }
2100 }
2101 }
2102
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002103# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00002104 if (fdDump)
2105 {
2106 fputs("]\n", fdDump);
2107 fflush(fdDump);
2108 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002109# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002110
Bram Moolenaar071d4272004-06-13 20:20:40 +00002111theend:
Bram Moolenaar0f873732019-12-05 20:28:46 +01002112 // Move typeahead to "buf", as much as fits.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002113 len = 0;
2114 while (len < maxlen && typeaheadlen > 0)
2115 {
2116 buf[len++] = typeahead[0];
2117 mch_memmove(typeahead, typeahead + 1, --typeaheadlen);
2118 }
K.Takata6e1d31e2022-02-03 13:05:32 +00002119# ifdef FEAT_JOB_CHANNEL
Bram Moolenaar7ca86fe2020-09-03 19:25:11 +02002120 if (len > 0)
2121 {
2122 buf[len] = NUL;
2123 ch_log(NULL, "raw key input: \"%s\"", buf);
2124 }
K.Takata6e1d31e2022-02-03 13:05:32 +00002125# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002126 return len;
2127
Bram Moolenaar0f873732019-12-05 20:28:46 +01002128#else // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00002129 return 0;
Bram Moolenaar0f873732019-12-05 20:28:46 +01002130#endif // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00002131}
2132
Bram Moolenaar82881492012-11-20 16:53:39 +01002133#ifndef PROTO
2134# ifndef __MINGW32__
Bram Moolenaar0f873732019-12-05 20:28:46 +01002135# include <shellapi.h> // required for FindExecutable()
Bram Moolenaar82881492012-11-20 16:53:39 +01002136# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002137#endif
2138
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002139/*
Bram Moolenaar95da1362020-05-30 18:37:55 +02002140 * Return TRUE if "name" is an executable file, FALSE if not or it doesn't exist.
Bram Moolenaar43663192017-03-05 14:29:12 +01002141 * When returning TRUE and "path" is not NULL save the path and set "*path" to
2142 * the allocated memory.
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00002143 * TODO: Should somehow check if it's really executable.
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002144 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002145 static int
Bram Moolenaar95da1362020-05-30 18:37:55 +02002146executable_file(char *name, char_u **path)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002147{
LemonBoy40fd7e62022-05-05 20:18:16 +01002148 int attrs = win32_getattrs((char_u *)name);
2149
2150 // The file doesn't exist or is a folder.
2151 if (attrs == -1 || (attrs & FILE_ATTRIBUTE_DIRECTORY))
2152 return FALSE;
2153 // Check if the file is an AppExecLink, a special alias used by Windows
2154 // Store for its apps.
2155 if (attrs & FILE_ATTRIBUTE_REPARSE_POINT)
Bram Moolenaar43663192017-03-05 14:29:12 +01002156 {
LemonBoy40fd7e62022-05-05 20:18:16 +01002157 char_u *res = resolve_appexeclink((char_u *)name);
2158 if (res == NULL)
2159 return FALSE;
2160 // The path is already absolute.
Bram Moolenaar95da1362020-05-30 18:37:55 +02002161 if (path != NULL)
LemonBoy40fd7e62022-05-05 20:18:16 +01002162 *path = res;
2163 else
2164 vim_free(res);
Bram Moolenaar95da1362020-05-30 18:37:55 +02002165 }
LemonBoy40fd7e62022-05-05 20:18:16 +01002166 else if (path != NULL)
2167 *path = FullName_save((char_u *)name, FALSE);
2168 return TRUE;
Bram Moolenaar95da1362020-05-30 18:37:55 +02002169}
2170
2171/*
2172 * If "use_path" is TRUE: Return TRUE if "name" is in $PATH.
2173 * If "use_path" is FALSE: Return TRUE if "name" exists.
2174 * If "use_pathext" is TRUE search "name" with extensions in $PATHEXT.
2175 * When returning TRUE and "path" is not NULL save the path and set "*path" to
2176 * the allocated memory.
2177 */
2178 static int
2179executable_exists(char *name, char_u **path, int use_path, int use_pathext)
2180{
2181 // WinNT and later can use _MAX_PATH wide characters for a pathname, which
2182 // means that the maximum pathname is _MAX_PATH * 3 bytes when 'enc' is
2183 // UTF-8.
2184 char_u buf[_MAX_PATH * 3];
2185 size_t len = STRLEN(name);
2186 size_t tmplen;
2187 char_u *p, *e, *e2;
2188 char_u *pathbuf = NULL;
2189 char_u *pathext = NULL;
2190 char_u *pathextbuf = NULL;
Mike Williamsa3d1b292021-06-30 20:56:00 +02002191 char_u *shname = NULL;
Bram Moolenaar95da1362020-05-30 18:37:55 +02002192 int noext = FALSE;
2193 int retval = FALSE;
2194
2195 if (len >= sizeof(buf)) // safety check
Bram Moolenaar43663192017-03-05 14:29:12 +01002196 return FALSE;
Bram Moolenaar95da1362020-05-30 18:37:55 +02002197
2198 // Using the name directly when a Unix-shell like 'shell'.
Mike Williamsa3d1b292021-06-30 20:56:00 +02002199 shname = gettail(p_sh);
2200 if (strstr((char *)shname, "sh") != NULL &&
2201 !(strstr((char *)shname, "powershell") != NULL
2202 || strstr((char *)shname, "pwsh") != NULL))
Bram Moolenaar95da1362020-05-30 18:37:55 +02002203 noext = TRUE;
2204
2205 if (use_pathext)
2206 {
2207 pathext = mch_getenv("PATHEXT");
2208 if (pathext == NULL)
2209 pathext = (char_u *)".com;.exe;.bat;.cmd";
2210
2211 if (noext == FALSE)
2212 {
2213 /*
2214 * Loop over all extensions in $PATHEXT.
2215 * Check "name" ends with extension.
2216 */
2217 p = pathext;
2218 while (*p)
2219 {
2220 if (p[0] == ';'
2221 || (p[0] == '.' && (p[1] == NUL || p[1] == ';')))
2222 {
2223 // Skip empty or single ".".
2224 ++p;
2225 continue;
2226 }
2227 e = vim_strchr(p, ';');
2228 if (e == NULL)
2229 e = p + STRLEN(p);
2230 tmplen = e - p;
2231
2232 if (_strnicoll(name + len - tmplen, (char *)p, tmplen) == 0)
2233 {
2234 noext = TRUE;
2235 break;
2236 }
2237
2238 p = e;
2239 }
2240 }
Bram Moolenaar43663192017-03-05 14:29:12 +01002241 }
2242
Dominique Pelleaf4a61a2021-12-27 17:21:41 +00002243 // Prepend single "." to pathext, it means no extension added.
Bram Moolenaar95da1362020-05-30 18:37:55 +02002244 if (pathext == NULL)
2245 pathext = (char_u *)".";
2246 else if (noext == TRUE)
2247 {
2248 if (pathextbuf == NULL)
2249 pathextbuf = alloc(STRLEN(pathext) + 3);
2250 if (pathextbuf == NULL)
2251 {
2252 retval = FALSE;
2253 goto theend;
2254 }
2255 STRCPY(pathextbuf, ".;");
2256 STRCAT(pathextbuf, pathext);
2257 pathext = pathextbuf;
2258 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002259
Bram Moolenaar95da1362020-05-30 18:37:55 +02002260 // Use $PATH when "use_path" is TRUE and "name" is basename.
2261 if (use_path && gettail((char_u *)name) == (char_u *)name)
2262 {
2263 p = mch_getenv("PATH");
2264 if (p != NULL)
2265 {
2266 pathbuf = alloc(STRLEN(p) + 3);
2267 if (pathbuf == NULL)
2268 {
2269 retval = FALSE;
2270 goto theend;
2271 }
Yasuhiro Matsumoto05cf63e2022-05-03 11:02:28 +01002272
2273 if (mch_getenv("NoDefaultCurrentDirectoryInExePath") == NULL)
2274 STRCPY(pathbuf, ".;");
2275 else
2276 *pathbuf = NUL;
Bram Moolenaar95da1362020-05-30 18:37:55 +02002277 STRCAT(pathbuf, p);
2278 }
2279 }
2280
2281 /*
2282 * Walk through all entries in $PATH to check if "name" exists there and
2283 * is an executable file.
2284 */
2285 p = (pathbuf != NULL) ? pathbuf : (char_u *)".";
2286 while (*p)
2287 {
2288 if (*p == ';') // Skip empty entry
2289 {
2290 ++p;
2291 continue;
2292 }
2293 e = vim_strchr(p, ';');
2294 if (e == NULL)
2295 e = p + STRLEN(p);
2296
2297 if (e - p + len + 2 > sizeof(buf))
2298 {
2299 retval = FALSE;
2300 goto theend;
2301 }
2302 // A single "." that means current dir.
2303 if (e - p == 1 && *p == '.')
2304 STRCPY(buf, name);
2305 else
2306 {
2307 vim_strncpy(buf, p, e - p);
2308 add_pathsep(buf);
2309 STRCAT(buf, name);
2310 }
2311 tmplen = STRLEN(buf);
2312
2313 /*
2314 * Loop over all extensions in $PATHEXT.
2315 * Check "name" with extension added.
2316 */
2317 p = pathext;
2318 while (*p)
2319 {
2320 if (*p == ';')
2321 {
2322 // Skip empty entry
2323 ++p;
2324 continue;
2325 }
2326 e2 = vim_strchr(p, (int)';');
2327 if (e2 == NULL)
2328 e2 = p + STRLEN(p);
2329
2330 if (!(p[0] == '.' && (p[1] == NUL || p[1] == ';')))
2331 {
2332 // Not a single "." that means no extension is added.
2333 if (e2 - p + tmplen + 1 > sizeof(buf))
2334 {
2335 retval = FALSE;
2336 goto theend;
2337 }
2338 vim_strncpy(buf + tmplen, p, e2 - p);
2339 }
2340 if (executable_file((char *)buf, path))
2341 {
2342 retval = TRUE;
2343 goto theend;
2344 }
2345
2346 p = e2;
2347 }
2348
2349 p = e;
2350 }
2351
2352theend:
2353 free(pathextbuf);
2354 free(pathbuf);
2355 return retval;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002356}
2357
Bram Moolenaar1eed5322019-02-26 17:03:54 +01002358#if (defined(__MINGW32__) && __MSVCRT_VERSION__ >= 0x800) || \
2359 (defined(_MSC_VER) && _MSC_VER >= 1400)
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002360/*
2361 * Bad parameter handler.
2362 *
2363 * Certain MS CRT functions will intentionally crash when passed invalid
2364 * parameters to highlight possible security holes. Setting this function as
2365 * the bad parameter handler will prevent the crash.
2366 *
2367 * In debug builds the parameters contain CRT information that might help track
2368 * down the source of a problem, but in non-debug builds the arguments are all
2369 * NULL/0. Debug builds will also produce assert dialogs from the CRT, it is
2370 * worth allowing these to make debugging of issues easier.
2371 */
2372 static void
Yegappan Lakshmanana34b4462022-06-11 10:43:26 +01002373bad_param_handler(const wchar_t *expression UNUSED,
2374 const wchar_t *function UNUSED,
2375 const wchar_t *file UNUSED,
2376 unsigned int line UNUSED,
2377 uintptr_t pReserved UNUSED)
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002378{
2379}
2380
2381# define SET_INVALID_PARAM_HANDLER \
2382 ((void)_set_invalid_parameter_handler(bad_param_handler))
2383#else
2384# define SET_INVALID_PARAM_HANDLER
2385#endif
2386
Bram Moolenaar4f974752019-02-17 17:44:42 +01002387#ifdef FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00002388
2389/*
2390 * GUI version of mch_init().
2391 */
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002392 static void
2393mch_init_g(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002394{
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002395# ifndef __MINGW32__
Bram Moolenaar071d4272004-06-13 20:20:40 +00002396 extern int _fmode;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002397# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002398
Bram Moolenaar0f873732019-12-05 20:28:46 +01002399 // Silently handle invalid parameters to CRT functions
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002400 SET_INVALID_PARAM_HANDLER;
2401
Bram Moolenaar0f873732019-12-05 20:28:46 +01002402 // Let critical errors result in a failure, not in a dialog box. Required
2403 // for the timestamp test to work on removed floppies.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002404 SetErrorMode(SEM_FAILCRITICALERRORS);
2405
Bram Moolenaar0f873732019-12-05 20:28:46 +01002406 _fmode = O_BINARY; // we do our own CR-LF translation
Bram Moolenaar071d4272004-06-13 20:20:40 +00002407
Bram Moolenaar0f873732019-12-05 20:28:46 +01002408 // Specify window size. Is there a place to get the default from?
Bram Moolenaar071d4272004-06-13 20:20:40 +00002409 Rows = 25;
2410 Columns = 80;
2411
Bram Moolenaar0f873732019-12-05 20:28:46 +01002412 // Look for 'vimrun'
Bram Moolenaar071d4272004-06-13 20:20:40 +00002413 {
2414 char_u vimrun_location[_MAX_PATH + 4];
2415
Bram Moolenaar0f873732019-12-05 20:28:46 +01002416 // First try in same directory as gvim.exe
Bram Moolenaar071d4272004-06-13 20:20:40 +00002417 STRCPY(vimrun_location, exe_name);
2418 STRCPY(gettail(vimrun_location), "vimrun.exe");
2419 if (mch_getperm(vimrun_location) >= 0)
2420 {
2421 if (*skiptowhite(vimrun_location) != NUL)
2422 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01002423 // Enclose path with white space in double quotes.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002424 mch_memmove(vimrun_location + 1, vimrun_location,
2425 STRLEN(vimrun_location) + 1);
2426 *vimrun_location = '"';
2427 STRCPY(gettail(vimrun_location), "vimrun\" ");
2428 }
2429 else
2430 STRCPY(gettail(vimrun_location), "vimrun ");
2431
2432 vimrun_path = (char *)vim_strsave(vimrun_location);
2433 s_dont_use_vimrun = FALSE;
2434 }
Bram Moolenaar95da1362020-05-30 18:37:55 +02002435 else if (executable_exists("vimrun.exe", NULL, TRUE, FALSE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002436 s_dont_use_vimrun = FALSE;
2437
Bram Moolenaar0f873732019-12-05 20:28:46 +01002438 // Don't give the warning for a missing vimrun.exe right now, but only
2439 // when vimrun was supposed to be used. Don't bother people that do
2440 // not need vimrun.exe.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002441 if (s_dont_use_vimrun)
2442 need_vimrun_warning = TRUE;
2443 }
2444
2445 /*
2446 * If "finstr.exe" doesn't exist, use "grep -n" for 'grepprg'.
2447 * Otherwise the default "findstr /n" is used.
2448 */
Bram Moolenaar95da1362020-05-30 18:37:55 +02002449 if (!executable_exists("findstr.exe", NULL, TRUE, FALSE))
Bram Moolenaar75ab5902022-04-18 15:36:40 +01002450 set_option_value_give_err((char_u *)"grepprg",
2451 0, (char_u *)"grep -n", 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002452
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002453# ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01002454 win_clip_init();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002455# endif
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01002456
2457 vtp_flag_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002458}
2459
2460
Bram Moolenaar0f873732019-12-05 20:28:46 +01002461#endif // FEAT_GUI_MSWIN
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002462
2463#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002464
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002465# define SRWIDTH(sr) ((sr).Right - (sr).Left + 1)
2466# define SRHEIGHT(sr) ((sr).Bottom - (sr).Top + 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002467
2468/*
2469 * ClearConsoleBuffer()
2470 * Description:
2471 * Clears the entire contents of the console screen buffer, using the
2472 * specified attribute.
2473 * Returns:
2474 * TRUE on success
2475 */
2476 static BOOL
2477ClearConsoleBuffer(WORD wAttribute)
2478{
2479 CONSOLE_SCREEN_BUFFER_INFO csbi;
2480 COORD coord;
2481 DWORD NumCells, dummy;
2482
2483 if (!GetConsoleScreenBufferInfo(g_hConOut, &csbi))
2484 return FALSE;
2485
2486 NumCells = csbi.dwSize.X * csbi.dwSize.Y;
2487 coord.X = 0;
2488 coord.Y = 0;
2489 if (!FillConsoleOutputCharacter(g_hConOut, ' ', NumCells,
2490 coord, &dummy))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002491 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002492 if (!FillConsoleOutputAttribute(g_hConOut, wAttribute, NumCells,
2493 coord, &dummy))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002494 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002495
2496 return TRUE;
2497}
2498
2499/*
2500 * FitConsoleWindow()
2501 * Description:
2502 * Checks if the console window will fit within given buffer dimensions.
2503 * Also, if requested, will shrink the window to fit.
2504 * Returns:
2505 * TRUE on success
2506 */
2507 static BOOL
2508FitConsoleWindow(
2509 COORD dwBufferSize,
2510 BOOL WantAdjust)
2511{
2512 CONSOLE_SCREEN_BUFFER_INFO csbi;
2513 COORD dwWindowSize;
2514 BOOL NeedAdjust = FALSE;
2515
2516 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
2517 {
2518 /*
2519 * A buffer resize will fail if the current console window does
2520 * not lie completely within that buffer. To avoid this, we might
2521 * have to move and possibly shrink the window.
2522 */
2523 if (csbi.srWindow.Right >= dwBufferSize.X)
2524 {
2525 dwWindowSize.X = SRWIDTH(csbi.srWindow);
2526 if (dwWindowSize.X > dwBufferSize.X)
2527 dwWindowSize.X = dwBufferSize.X;
2528 csbi.srWindow.Right = dwBufferSize.X - 1;
2529 csbi.srWindow.Left = dwBufferSize.X - dwWindowSize.X;
2530 NeedAdjust = TRUE;
2531 }
2532 if (csbi.srWindow.Bottom >= dwBufferSize.Y)
2533 {
2534 dwWindowSize.Y = SRHEIGHT(csbi.srWindow);
2535 if (dwWindowSize.Y > dwBufferSize.Y)
2536 dwWindowSize.Y = dwBufferSize.Y;
2537 csbi.srWindow.Bottom = dwBufferSize.Y - 1;
2538 csbi.srWindow.Top = dwBufferSize.Y - dwWindowSize.Y;
2539 NeedAdjust = TRUE;
2540 }
2541 if (NeedAdjust && WantAdjust)
2542 {
2543 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &csbi.srWindow))
2544 return FALSE;
2545 }
2546 return TRUE;
2547 }
2548
2549 return FALSE;
2550}
2551
2552typedef struct ConsoleBufferStruct
2553{
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002554 BOOL IsValid;
2555 CONSOLE_SCREEN_BUFFER_INFO Info;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002556 PCHAR_INFO Buffer;
2557 COORD BufferSize;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002558 PSMALL_RECT Regions;
2559 int NumRegions;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002560} ConsoleBuffer;
2561
2562/*
2563 * SaveConsoleBuffer()
2564 * Description:
2565 * Saves important information about the console buffer, including the
2566 * actual buffer contents. The saved information is suitable for later
2567 * restoration by RestoreConsoleBuffer().
2568 * Returns:
2569 * TRUE if all information was saved; FALSE otherwise
2570 * If FALSE, still sets cb->IsValid if buffer characteristics were saved.
2571 */
2572 static BOOL
2573SaveConsoleBuffer(
2574 ConsoleBuffer *cb)
2575{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002576 DWORD NumCells;
2577 COORD BufferCoord;
2578 SMALL_RECT ReadRegion;
2579 WORD Y, Y_incr;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002580 int i, numregions;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002581
Bram Moolenaar071d4272004-06-13 20:20:40 +00002582 if (cb == NULL)
2583 return FALSE;
2584
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002585 if (!GetConsoleScreenBufferInfo(g_hConOut, &cb->Info))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002586 {
2587 cb->IsValid = FALSE;
2588 return FALSE;
2589 }
2590 cb->IsValid = TRUE;
2591
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002592 /*
2593 * Allocate a buffer large enough to hold the entire console screen
2594 * buffer. If this ConsoleBuffer structure has already been initialized
2595 * with a buffer of the correct size, then just use that one.
2596 */
2597 if (!cb->IsValid || cb->Buffer == NULL ||
2598 cb->BufferSize.X != cb->Info.dwSize.X ||
2599 cb->BufferSize.Y != cb->Info.dwSize.Y)
2600 {
2601 cb->BufferSize.X = cb->Info.dwSize.X;
2602 cb->BufferSize.Y = cb->Info.dwSize.Y;
2603 NumCells = cb->BufferSize.X * cb->BufferSize.Y;
2604 vim_free(cb->Buffer);
Bram Moolenaarc799fe22019-05-28 23:08:19 +02002605 cb->Buffer = ALLOC_MULT(CHAR_INFO, NumCells);
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002606 if (cb->Buffer == NULL)
2607 return FALSE;
2608 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002609
2610 /*
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002611 * We will now copy the console screen buffer into our buffer.
2612 * ReadConsoleOutput() seems to be limited as far as how much you
2613 * can read at a time. Empirically, this number seems to be about
2614 * 12000 cells (rows * columns). Start at position (0, 0) and copy
2615 * in chunks until it is all copied. The chunks will all have the
2616 * same horizontal characteristics, so initialize them now. The
2617 * height of each chunk will be (12000 / width).
Bram Moolenaar071d4272004-06-13 20:20:40 +00002618 */
Bram Moolenaar61594242015-09-01 20:23:37 +02002619 BufferCoord.X = 0;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002620 ReadRegion.Left = 0;
2621 ReadRegion.Right = cb->Info.dwSize.X - 1;
2622 Y_incr = 12000 / cb->Info.dwSize.X;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002623
2624 numregions = (cb->Info.dwSize.Y + Y_incr - 1) / Y_incr;
2625 if (cb->Regions == NULL || numregions != cb->NumRegions)
2626 {
2627 cb->NumRegions = numregions;
2628 vim_free(cb->Regions);
Bram Moolenaarc799fe22019-05-28 23:08:19 +02002629 cb->Regions = ALLOC_MULT(SMALL_RECT, cb->NumRegions);
Bram Moolenaar444fda22017-08-11 20:37:00 +02002630 if (cb->Regions == NULL)
2631 {
Bram Moolenaard23a8232018-02-10 18:45:26 +01002632 VIM_CLEAR(cb->Buffer);
Bram Moolenaar444fda22017-08-11 20:37:00 +02002633 return FALSE;
2634 }
2635 }
2636
2637 for (i = 0, Y = 0; i < cb->NumRegions; i++, Y += Y_incr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002638 {
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002639 /*
2640 * Read into position (0, Y) in our buffer.
2641 */
2642 BufferCoord.Y = Y;
2643 /*
2644 * Read the region whose top left corner is (0, Y) and whose bottom
2645 * right corner is (width - 1, Y + Y_incr - 1). This should define
2646 * a region of size width by Y_incr. Don't worry if this region is
2647 * too large for the remaining buffer; it will be cropped.
2648 */
2649 ReadRegion.Top = Y;
2650 ReadRegion.Bottom = Y + Y_incr - 1;
Bram Moolenaar0f873732019-12-05 20:28:46 +01002651 if (!ReadConsoleOutputW(g_hConOut, // output handle
2652 cb->Buffer, // our buffer
2653 cb->BufferSize, // dimensions of our buffer
2654 BufferCoord, // offset in our buffer
2655 &ReadRegion)) // region to save
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002656 {
Bram Moolenaard23a8232018-02-10 18:45:26 +01002657 VIM_CLEAR(cb->Buffer);
2658 VIM_CLEAR(cb->Regions);
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002659 return FALSE;
2660 }
Bram Moolenaar444fda22017-08-11 20:37:00 +02002661 cb->Regions[i] = ReadRegion;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002662 }
2663
2664 return TRUE;
2665}
2666
2667/*
2668 * RestoreConsoleBuffer()
2669 * Description:
2670 * Restores important information about the console buffer, including the
2671 * actual buffer contents, if desired. The information to restore is in
2672 * the same format used by SaveConsoleBuffer().
2673 * Returns:
2674 * TRUE on success
2675 */
2676 static BOOL
2677RestoreConsoleBuffer(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002678 ConsoleBuffer *cb,
2679 BOOL RestoreScreen)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002680{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002681 COORD BufferCoord;
2682 SMALL_RECT WriteRegion;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002683 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002684
2685 if (cb == NULL || !cb->IsValid)
2686 return FALSE;
2687
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002688 /*
2689 * Before restoring the buffer contents, clear the current buffer, and
2690 * restore the cursor position and window information. Doing this now
2691 * prevents old buffer contents from "flashing" onto the screen.
2692 */
2693 if (RestoreScreen)
2694 ClearConsoleBuffer(cb->Info.wAttributes);
2695
2696 FitConsoleWindow(cb->Info.dwSize, TRUE);
2697 if (!SetConsoleScreenBufferSize(g_hConOut, cb->Info.dwSize))
2698 return FALSE;
2699 if (!SetConsoleTextAttribute(g_hConOut, cb->Info.wAttributes))
2700 return FALSE;
2701
2702 if (!RestoreScreen)
2703 {
2704 /*
2705 * No need to restore the screen buffer contents, so we're done.
2706 */
2707 return TRUE;
2708 }
2709
2710 if (!SetConsoleCursorPosition(g_hConOut, cb->Info.dwCursorPosition))
2711 return FALSE;
2712 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &cb->Info.srWindow))
2713 return FALSE;
2714
2715 /*
2716 * Restore the screen buffer contents.
2717 */
2718 if (cb->Buffer != NULL)
2719 {
Bram Moolenaar444fda22017-08-11 20:37:00 +02002720 for (i = 0; i < cb->NumRegions; i++)
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002721 {
Bram Moolenaar444fda22017-08-11 20:37:00 +02002722 BufferCoord.X = cb->Regions[i].Left;
2723 BufferCoord.Y = cb->Regions[i].Top;
2724 WriteRegion = cb->Regions[i];
Bram Moolenaar0f873732019-12-05 20:28:46 +01002725 if (!WriteConsoleOutputW(g_hConOut, // output handle
2726 cb->Buffer, // our buffer
2727 cb->BufferSize, // dimensions of our buffer
2728 BufferCoord, // offset in our buffer
2729 &WriteRegion)) // region to restore
Bram Moolenaar444fda22017-08-11 20:37:00 +02002730 return FALSE;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002731 }
2732 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002733
2734 return TRUE;
2735}
2736
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002737# define FEAT_RESTORE_ORIG_SCREEN
2738# ifdef FEAT_RESTORE_ORIG_SCREEN
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002739static ConsoleBuffer g_cbOrig = { 0 };
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002740# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002741static ConsoleBuffer g_cbNonTermcap = { 0 };
2742static ConsoleBuffer g_cbTermcap = { 0 };
2743
Bram Moolenaar071d4272004-06-13 20:20:40 +00002744char g_szOrigTitle[256] = { 0 };
Bram Moolenaar0f873732019-12-05 20:28:46 +01002745HWND g_hWnd = NULL; // also used in os_mswin.c
Bram Moolenaar071d4272004-06-13 20:20:40 +00002746static HICON g_hOrigIconSmall = NULL;
2747static HICON g_hOrigIcon = NULL;
2748static HICON g_hVimIcon = NULL;
2749static BOOL g_fCanChangeIcon = FALSE;
2750
Bram Moolenaar071d4272004-06-13 20:20:40 +00002751/*
2752 * GetConsoleIcon()
2753 * Description:
2754 * Attempts to retrieve the small icon and/or the big icon currently in
2755 * use by a given window.
2756 * Returns:
2757 * TRUE on success
2758 */
2759 static BOOL
2760GetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002761 HWND hWnd,
2762 HICON *phIconSmall,
2763 HICON *phIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002764{
2765 if (hWnd == NULL)
2766 return FALSE;
2767
2768 if (phIconSmall != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002769 *phIconSmall = (HICON)SendMessage(hWnd, WM_GETICON,
2770 (WPARAM)ICON_SMALL, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002771 if (phIcon != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002772 *phIcon = (HICON)SendMessage(hWnd, WM_GETICON,
2773 (WPARAM)ICON_BIG, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002774 return TRUE;
2775}
2776
2777/*
2778 * SetConsoleIcon()
2779 * Description:
2780 * Attempts to change the small icon and/or the big icon currently in
2781 * use by a given window.
2782 * Returns:
2783 * TRUE on success
2784 */
2785 static BOOL
2786SetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002787 HWND hWnd,
2788 HICON hIconSmall,
2789 HICON hIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002790{
Bram Moolenaar071d4272004-06-13 20:20:40 +00002791 if (hWnd == NULL)
2792 return FALSE;
2793
2794 if (hIconSmall != NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002795 SendMessage(hWnd, WM_SETICON,
2796 (WPARAM)ICON_SMALL, (LPARAM)hIconSmall);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002797 if (hIcon != NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002798 SendMessage(hWnd, WM_SETICON,
2799 (WPARAM)ICON_BIG, (LPARAM) hIcon);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002800 return TRUE;
2801}
2802
2803/*
2804 * SaveConsoleTitleAndIcon()
2805 * Description:
2806 * Saves the current console window title in g_szOrigTitle, for later
2807 * restoration. Also, attempts to obtain a handle to the console window,
2808 * and use it to save the small and big icons currently in use by the
2809 * console window. This is not always possible on some versions of Windows;
2810 * nor is it possible when running Vim remotely using Telnet (since the
2811 * console window the user sees is owned by a remote process).
2812 */
2813 static void
2814SaveConsoleTitleAndIcon(void)
2815{
Bram Moolenaar0f873732019-12-05 20:28:46 +01002816 // Save the original title.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002817 if (!GetConsoleTitle(g_szOrigTitle, sizeof(g_szOrigTitle)))
2818 return;
2819
2820 /*
2821 * Obtain a handle to the console window using GetConsoleWindow() from
2822 * KERNEL32.DLL; we need to handle in order to change the window icon.
2823 * This function only exists on NT-based Windows, starting with Windows
2824 * 2000. On older operating systems, we can't change the window icon
2825 * anyway.
2826 */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02002827 g_hWnd = GetConsoleWindow();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002828 if (g_hWnd == NULL)
2829 return;
2830
Bram Moolenaar0f873732019-12-05 20:28:46 +01002831 // Save the original console window icon.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002832 GetConsoleIcon(g_hWnd, &g_hOrigIconSmall, &g_hOrigIcon);
2833 if (g_hOrigIconSmall == NULL || g_hOrigIcon == NULL)
2834 return;
2835
Bram Moolenaar0f873732019-12-05 20:28:46 +01002836 // Extract the first icon contained in the Vim executable.
K.Takata2da11a42022-09-10 13:03:12 +01002837 if (
2838# ifdef FEAT_LIBCALL
2839 mch_icon_load((HANDLE *)&g_hVimIcon) == FAIL ||
2840# endif
2841 g_hVimIcon == NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002842 g_hVimIcon = ExtractIcon(NULL, (LPCSTR)exe_name, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002843 if (g_hVimIcon != NULL)
2844 g_fCanChangeIcon = TRUE;
2845}
Bram Moolenaar071d4272004-06-13 20:20:40 +00002846
2847static int g_fWindInitCalled = FALSE;
2848static int g_fTermcapMode = FALSE;
2849static CONSOLE_CURSOR_INFO g_cci;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002850
2851/*
2852 * non-GUI version of mch_init().
2853 */
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002854 static void
2855mch_init_c(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002856{
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002857# ifndef FEAT_RESTORE_ORIG_SCREEN
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002858 CONSOLE_SCREEN_BUFFER_INFO csbi;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002859# endif
2860# ifndef __MINGW32__
Bram Moolenaar071d4272004-06-13 20:20:40 +00002861 extern int _fmode;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002862# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002863
Bram Moolenaar0f873732019-12-05 20:28:46 +01002864 // Silently handle invalid parameters to CRT functions
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002865 SET_INVALID_PARAM_HANDLER;
2866
Bram Moolenaar0f873732019-12-05 20:28:46 +01002867 // Let critical errors result in a failure, not in a dialog box. Required
2868 // for the timestamp test to work on removed floppies.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002869 SetErrorMode(SEM_FAILCRITICALERRORS);
2870
Bram Moolenaar0f873732019-12-05 20:28:46 +01002871 _fmode = O_BINARY; // we do our own CR-LF translation
Bram Moolenaar071d4272004-06-13 20:20:40 +00002872 out_flush();
2873
Bram Moolenaar0f873732019-12-05 20:28:46 +01002874 // Obtain handles for the standard Console I/O devices
Bram Moolenaar071d4272004-06-13 20:20:40 +00002875 if (read_cmd_fd == 0)
2876 g_hConIn = GetStdHandle(STD_INPUT_HANDLE);
2877 else
2878 create_conin();
2879 g_hConOut = GetStdHandle(STD_OUTPUT_HANDLE);
2880
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002881# ifdef FEAT_RESTORE_ORIG_SCREEN
Bram Moolenaar0f873732019-12-05 20:28:46 +01002882 // Save the initial console buffer for later restoration
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002883 SaveConsoleBuffer(&g_cbOrig);
2884 g_attrCurrent = g_attrDefault = g_cbOrig.Info.wAttributes;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002885# else
Bram Moolenaar0f873732019-12-05 20:28:46 +01002886 // Get current text attributes
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002887 GetConsoleScreenBufferInfo(g_hConOut, &csbi);
2888 g_attrCurrent = g_attrDefault = csbi.wAttributes;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002889# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002890 if (cterm_normal_fg_color == 0)
2891 cterm_normal_fg_color = (g_attrCurrent & 0xf) + 1;
2892 if (cterm_normal_bg_color == 0)
2893 cterm_normal_bg_color = ((g_attrCurrent >> 4) & 0xf) + 1;
2894
Bram Moolenaarbdace832019-03-02 10:13:42 +01002895 // Fg and Bg color index number at startup
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02002896 g_color_index_fg = g_attrDefault & 0xf;
2897 g_color_index_bg = (g_attrDefault >> 4) & 0xf;
2898
Bram Moolenaar0f873732019-12-05 20:28:46 +01002899 // set termcap codes to current text attributes
Bram Moolenaar071d4272004-06-13 20:20:40 +00002900 update_tcap(g_attrCurrent);
2901
2902 GetConsoleCursorInfo(g_hConOut, &g_cci);
2903 GetConsoleMode(g_hConIn, &g_cmodein);
2904 GetConsoleMode(g_hConOut, &g_cmodeout);
2905
Bram Moolenaar071d4272004-06-13 20:20:40 +00002906 SaveConsoleTitleAndIcon();
2907 /*
2908 * Set both the small and big icons of the console window to Vim's icon.
2909 * Note that Vim presently only has one size of icon (32x32), but it
2910 * automatically gets scaled down to 16x16 when setting the small icon.
2911 */
2912 if (g_fCanChangeIcon)
2913 SetConsoleIcon(g_hWnd, g_hVimIcon, g_hVimIcon);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002914
2915 ui_get_shellsize();
2916
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002917# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00002918 fdDump = fopen("dump", "wt");
2919
2920 if (fdDump)
2921 {
2922 time_t t;
2923
2924 time(&t);
2925 fputs(ctime(&t), fdDump);
2926 fflush(fdDump);
2927 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002928# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002929
2930 g_fWindInitCalled = TRUE;
2931
Bram Moolenaar071d4272004-06-13 20:20:40 +00002932 g_fMouseAvail = GetSystemMetrics(SM_MOUSEPRESENT);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002933
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002934# ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01002935 win_clip_init();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002936# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01002937
Bram Moolenaar81ccbf12020-04-15 21:05:30 +02002938 vtp_flag_init();
Bram Moolenaarcafafb32018-02-22 21:07:09 +01002939 vtp_init();
Bram Moolenaar06b7b582020-05-30 17:49:25 +02002940 wt_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002941}
2942
2943/*
2944 * non-GUI version of mch_exit().
2945 * Shut down and exit with status `r'
2946 * Careful: mch_exit() may be called before mch_init()!
2947 */
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002948 static void
2949mch_exit_c(int r)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002950{
Bram Moolenaar955f1982017-02-05 15:10:51 +01002951 exiting = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002952
Bram Moolenaarcafafb32018-02-22 21:07:09 +01002953 vtp_exit();
2954
Bram Moolenaar955f1982017-02-05 15:10:51 +01002955 stoptermcap();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002956 if (g_fWindInitCalled)
2957 settmode(TMODE_COOK);
2958
Bram Moolenaar0f873732019-12-05 20:28:46 +01002959 ml_close_all(TRUE); // remove all memfiles
Bram Moolenaar071d4272004-06-13 20:20:40 +00002960
2961 if (g_fWindInitCalled)
2962 {
Bram Moolenaar40385db2018-08-07 22:31:44 +02002963 mch_restore_title(SAVE_RESTORE_BOTH);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002964 /*
2965 * Restore both the small and big icons of the console window to
2966 * what they were at startup. Don't do this when the window is
2967 * closed, Vim would hang here.
2968 */
2969 if (g_fCanChangeIcon && !g_fForceExit)
2970 SetConsoleIcon(g_hWnd, g_hOrigIconSmall, g_hOrigIcon);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002971
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002972# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00002973 if (fdDump)
2974 {
2975 time_t t;
2976
2977 time(&t);
2978 fputs(ctime(&t), fdDump);
2979 fclose(fdDump);
2980 }
2981 fdDump = NULL;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002982# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002983 }
2984
2985 SetConsoleCursorInfo(g_hConOut, &g_cci);
Wez Furlong6ef5ab52021-05-30 19:29:41 +02002986 SetConsoleMode(g_hConIn, g_cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002987 SetConsoleMode(g_hConOut, g_cmodeout);
2988
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002989# ifdef DYNAMIC_GETTEXT
Bram Moolenaar071d4272004-06-13 20:20:40 +00002990 dyn_libintl_end();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002991# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002992
2993 exit(r);
2994}
Bram Moolenaar0f873732019-12-05 20:28:46 +01002995#endif // !FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00002996
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002997 void
2998mch_init(void)
2999{
3000#ifdef VIMDLL
3001 if (gui.starting)
3002 mch_init_g();
3003 else
3004 mch_init_c();
3005#elif defined(FEAT_GUI_MSWIN)
3006 mch_init_g();
3007#else
3008 mch_init_c();
3009#endif
3010}
3011
3012 void
3013mch_exit(int r)
3014{
Bram Moolenaar173d8412020-04-19 14:02:26 +02003015#ifdef FEAT_NETBEANS_INTG
3016 netbeans_send_disconnect();
3017#endif
3018
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003019#ifdef VIMDLL
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02003020 if (gui.in_use || gui.starting)
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003021 mch_exit_g(r);
3022 else
3023 mch_exit_c(r);
3024#elif defined(FEAT_GUI_MSWIN)
3025 mch_exit_g(r);
3026#else
3027 mch_exit_c(r);
3028#endif
3029}
3030
Bram Moolenaar071d4272004-06-13 20:20:40 +00003031/*
3032 * Do we have an interactive window?
3033 */
3034 int
3035mch_check_win(
Bram Moolenaar1266d672017-02-01 13:43:36 +01003036 int argc UNUSED,
3037 char **argv UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003038{
3039 get_exe_name();
3040
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003041#if defined(FEAT_GUI_MSWIN) && !defined(VIMDLL)
Bram Moolenaar0f873732019-12-05 20:28:46 +01003042 return OK; // GUI always has a tty
Bram Moolenaar071d4272004-06-13 20:20:40 +00003043#else
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003044# ifdef VIMDLL
3045 if (gui.in_use)
3046 return OK;
3047# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003048 if (isatty(1))
3049 return OK;
3050 return FAIL;
3051#endif
3052}
3053
Bram Moolenaar65f04f62013-08-30 17:29:16 +02003054/*
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003055 * Set the case of the file name, if it already exists.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003056 * When "len" is > 0, also expand short to long filenames.
3057 */
3058 void
3059fname_case(
3060 char_u *name,
3061 int len)
3062{
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003063 int flen;
3064 WCHAR *p;
3065 WCHAR buf[_MAX_PATH + 1];
Bram Moolenaar071d4272004-06-13 20:20:40 +00003066
Bram Moolenaara3ffd9c2005-07-21 21:03:15 +00003067 flen = (int)STRLEN(name);
Bram Moolenaar65f04f62013-08-30 17:29:16 +02003068 if (flen == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003069 return;
3070
3071 slash_adjust(name);
3072
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003073 p = enc_to_utf16(name, NULL);
3074 if (p == NULL)
Bram Moolenaar65f04f62013-08-30 17:29:16 +02003075 return;
3076
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003077 if (GetLongPathNameW(p, buf, _MAX_PATH))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003078 {
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003079 char_u *q = utf16_to_enc(buf, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003080
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003081 if (q != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003082 {
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003083 if (len > 0 || flen >= (int)STRLEN(q))
3084 vim_strncpy(name, q, (len > 0) ? len - 1 : flen);
3085 vim_free(q);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003086 }
3087 }
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003088 vim_free(p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003089}
3090
3091
3092/*
3093 * Insert user name in s[len].
3094 */
3095 int
3096mch_get_user_name(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003097 char_u *s,
3098 int len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003099{
Bram Moolenaar0f873732019-12-05 20:28:46 +01003100 WCHAR wszUserName[256 + 1]; // UNLEN is 256
K.Takataeeec2542021-06-02 13:28:16 +02003101 DWORD wcch = ARRAY_LENGTH(wszUserName);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003102
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003103 if (GetUserNameW(wszUserName, &wcch))
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003104 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003105 char_u *p = utf16_to_enc(wszUserName, NULL);
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003106
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003107 if (p != NULL)
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003108 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003109 vim_strncpy(s, p, len - 1);
3110 vim_free(p);
3111 return OK;
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003112 }
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003113 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003114 s[0] = NUL;
3115 return FAIL;
3116}
3117
3118
3119/*
3120 * Insert host name in s[len].
3121 */
3122 void
3123mch_get_host_name(
3124 char_u *s,
3125 int len)
3126{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003127 WCHAR wszHostName[256 + 1];
K.Takataeeec2542021-06-02 13:28:16 +02003128 DWORD wcch = ARRAY_LENGTH(wszHostName);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003129
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003130 if (GetComputerNameW(wszHostName, &wcch))
Bram Moolenaar2cc87382013-12-11 18:21:45 +01003131 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003132 char_u *p = utf16_to_enc(wszHostName, NULL);
Bram Moolenaar2cc87382013-12-11 18:21:45 +01003133
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003134 if (p != NULL)
Bram Moolenaar2cc87382013-12-11 18:21:45 +01003135 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003136 vim_strncpy(s, p, len - 1);
3137 vim_free(p);
3138 return;
Bram Moolenaar2cc87382013-12-11 18:21:45 +01003139 }
Bram Moolenaar2cc87382013-12-11 18:21:45 +01003140 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003141}
3142
3143
3144/*
3145 * return process ID
3146 */
3147 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003148mch_get_pid(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003149{
3150 return (long)GetCurrentProcessId();
3151}
3152
Bram Moolenaar67cf86b2019-04-28 22:25:38 +02003153/*
3154 * return TRUE if process "pid" is still running
3155 */
3156 int
Bram Moolenaar1b243ea2019-04-28 22:50:40 +02003157mch_process_running(long pid)
Bram Moolenaar67cf86b2019-04-28 22:25:38 +02003158{
3159 HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION, 0, (DWORD)pid);
3160 DWORD status = 0;
3161 int ret = FALSE;
3162
3163 if (hProcess == NULL)
3164 return FALSE; // might not have access
3165 if (GetExitCodeProcess(hProcess, &status) )
3166 ret = status == STILL_ACTIVE;
3167 CloseHandle(hProcess);
3168 return ret;
3169}
Bram Moolenaar071d4272004-06-13 20:20:40 +00003170
3171/*
3172 * Get name of current directory into buffer 'buf' of length 'len' bytes.
3173 * Return OK for success, FAIL for failure.
3174 */
3175 int
3176mch_dirname(
3177 char_u *buf,
3178 int len)
3179{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003180 WCHAR wbuf[_MAX_PATH + 1];
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02003181
Bram Moolenaar071d4272004-06-13 20:20:40 +00003182 /*
3183 * Originally this was:
3184 * return (getcwd(buf, len) != NULL ? OK : FAIL);
3185 * But the Win32s known bug list says that getcwd() doesn't work
3186 * so use the Win32 system call instead. <Negri>
3187 */
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003188 if (GetCurrentDirectoryW(_MAX_PATH, wbuf) != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003189 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003190 WCHAR wcbuf[_MAX_PATH + 1];
3191 char_u *p = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003192
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003193 if (GetLongPathNameW(wbuf, wcbuf, _MAX_PATH) != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003194 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003195 p = utf16_to_enc(wcbuf, NULL);
3196 if (STRLEN(p) >= (size_t)len)
Bram Moolenaarcea1f9e2018-08-19 14:38:42 +02003197 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003198 // long path name is too long, fall back to short one
Bram Moolenaar071d4272004-06-13 20:20:40 +00003199 vim_free(p);
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003200 p = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003201 }
3202 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003203 if (p == NULL)
3204 p = utf16_to_enc(wbuf, NULL);
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02003205
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003206 if (p != NULL)
3207 {
3208 vim_strncpy(buf, p, len - 1);
3209 vim_free(p);
3210 return OK;
3211 }
3212 }
3213 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003214}
3215
3216/*
Bram Moolenaarffa22202013-11-21 12:34:11 +01003217 * Get file permissions for "name".
3218 * Return mode_t or -1 for error.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003219 */
3220 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003221mch_getperm(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003222{
Bram Moolenaar8767f522016-07-01 17:17:39 +02003223 stat_T st;
Bram Moolenaarffa22202013-11-21 12:34:11 +01003224 int n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003225
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003226 n = mch_stat((char *)name, &st);
Bram Moolenaar78cf3f02014-01-10 18:16:07 +01003227 return n == 0 ? (long)(unsigned short)st.st_mode : -1L;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003228}
3229
3230
3231/*
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003232 * Set file permission for "name" to "perm".
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003233 *
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003234 * Return FAIL for failure, OK otherwise.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003235 */
3236 int
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003237mch_setperm(char_u *name, long perm)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003238{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003239 long n;
3240 WCHAR *p;
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003241
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003242 p = enc_to_utf16(name, NULL);
3243 if (p == NULL)
3244 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003245
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003246 n = _wchmod(p, perm);
3247 vim_free(p);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003248 if (n == -1)
3249 return FAIL;
3250
3251 win32_set_archive(name);
3252
3253 return OK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003254}
3255
3256/*
3257 * Set hidden flag for "name".
3258 */
3259 void
3260mch_hide(char_u *name)
3261{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003262 int attrs = win32_getattrs(name);
3263 if (attrs == -1)
3264 return;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003265
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003266 attrs |= FILE_ATTRIBUTE_HIDDEN;
3267 win32_setattrs(name, attrs);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003268}
3269
3270/*
Bram Moolenaar8a52ba72015-11-02 14:45:56 +01003271 * Return TRUE if file "name" exists and is hidden.
3272 */
3273 int
3274mch_ishidden(char_u *name)
3275{
3276 int f = win32_getattrs(name);
3277
3278 if (f == -1)
Bram Moolenaar0f873732019-12-05 20:28:46 +01003279 return FALSE; // file does not exist at all
Bram Moolenaar8a52ba72015-11-02 14:45:56 +01003280
3281 return (f & FILE_ATTRIBUTE_HIDDEN) != 0;
3282}
3283
3284/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003285 * return TRUE if "name" is a directory
3286 * return FALSE if "name" is not a directory or upon error
3287 */
3288 int
3289mch_isdir(char_u *name)
3290{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003291 int f = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003292
3293 if (f == -1)
Bram Moolenaar0f873732019-12-05 20:28:46 +01003294 return FALSE; // file does not exist at all
Bram Moolenaar071d4272004-06-13 20:20:40 +00003295
3296 return (f & FILE_ATTRIBUTE_DIRECTORY) != 0;
3297}
3298
3299/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01003300 * return TRUE if "name" is a directory, NOT a symlink to a directory
3301 * return FALSE if "name" is not a directory
3302 * return FALSE for error
3303 */
3304 int
3305mch_isrealdir(char_u *name)
3306{
3307 return mch_isdir(name) && !mch_is_symbolic_link(name);
3308}
3309
3310/*
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003311 * Create directory "name".
3312 * Return 0 on success, -1 on error.
3313 */
3314 int
3315mch_mkdir(char_u *name)
3316{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003317 WCHAR *p;
3318 int retval;
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003319
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003320 p = enc_to_utf16(name, NULL);
3321 if (p == NULL)
3322 return -1;
3323 retval = _wmkdir(p);
3324 vim_free(p);
3325 return retval;
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003326}
3327
3328/*
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003329 * Delete directory "name".
3330 * Return 0 on success, -1 on error.
3331 */
3332 int
3333mch_rmdir(char_u *name)
3334{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003335 WCHAR *p;
3336 int retval;
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003337
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003338 p = enc_to_utf16(name, NULL);
3339 if (p == NULL)
3340 return -1;
3341 retval = _wrmdir(p);
3342 vim_free(p);
3343 return retval;
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003344}
3345
3346/*
Bram Moolenaar03f48552006-02-28 23:52:23 +00003347 * Return TRUE if file "fname" has more than one link.
3348 */
3349 int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003350mch_is_hard_link(char_u *fname)
Bram Moolenaar03f48552006-02-28 23:52:23 +00003351{
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003352 BY_HANDLE_FILE_INFORMATION info;
3353
3354 return win32_fileinfo(fname, &info) == FILEINFO_OK
3355 && info.nNumberOfLinks > 1;
3356}
3357
3358/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01003359 * Return TRUE if "name" is a symbolic link (or a junction).
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003360 */
3361 int
Bram Moolenaar203258c2016-01-17 22:15:16 +01003362mch_is_symbolic_link(char_u *name)
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003363{
3364 HANDLE hFind;
3365 int res = FALSE;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003366 DWORD fileFlags = 0, reparseTag = 0;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003367 WCHAR *wn;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003368 WIN32_FIND_DATAW findDataW;
3369
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003370 wn = enc_to_utf16(name, NULL);
3371 if (wn == NULL)
3372 return FALSE;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003373
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003374 hFind = FindFirstFileW(wn, &findDataW);
3375 vim_free(wn);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003376 if (hFind != INVALID_HANDLE_VALUE)
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003377 {
3378 fileFlags = findDataW.dwFileAttributes;
3379 reparseTag = findDataW.dwReserved0;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003380 FindClose(hFind);
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003381 }
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003382
3383 if ((fileFlags & FILE_ATTRIBUTE_REPARSE_POINT)
Bram Moolenaar203258c2016-01-17 22:15:16 +01003384 && (reparseTag == IO_REPARSE_TAG_SYMLINK
3385 || reparseTag == IO_REPARSE_TAG_MOUNT_POINT))
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003386 res = TRUE;
3387
3388 return res;
3389}
3390
3391/*
3392 * Return TRUE if file "fname" has more than one link or if it is a symbolic
3393 * link.
3394 */
3395 int
3396mch_is_linked(char_u *fname)
3397{
3398 if (mch_is_hard_link(fname) || mch_is_symbolic_link(fname))
3399 return TRUE;
3400 return FALSE;
3401}
3402
3403/*
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003404 * Get the by-handle-file-information for "fname".
3405 * Returns FILEINFO_OK when OK.
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003406 * Returns FILEINFO_ENC_FAIL when enc_to_utf16() failed.
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003407 * Returns FILEINFO_READ_FAIL when CreateFile() failed.
3408 * Returns FILEINFO_INFO_FAIL when GetFileInformationByHandle() failed.
3409 */
3410 int
3411win32_fileinfo(char_u *fname, BY_HANDLE_FILE_INFORMATION *info)
3412{
Bram Moolenaar03f48552006-02-28 23:52:23 +00003413 HANDLE hFile;
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003414 int res = FILEINFO_READ_FAIL;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003415 WCHAR *wn;
Bram Moolenaar03f48552006-02-28 23:52:23 +00003416
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003417 wn = enc_to_utf16(fname, NULL);
3418 if (wn == NULL)
3419 return FILEINFO_ENC_FAIL;
3420
3421 hFile = CreateFileW(wn, // file name
3422 GENERIC_READ, // access mode
3423 FILE_SHARE_READ | FILE_SHARE_WRITE, // share mode
3424 NULL, // security descriptor
3425 OPEN_EXISTING, // creation disposition
3426 FILE_FLAG_BACKUP_SEMANTICS, // file attributes
3427 NULL); // handle to template file
3428 vim_free(wn);
Bram Moolenaar03f48552006-02-28 23:52:23 +00003429
3430 if (hFile != INVALID_HANDLE_VALUE)
3431 {
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003432 if (GetFileInformationByHandle(hFile, info) != 0)
3433 res = FILEINFO_OK;
3434 else
3435 res = FILEINFO_INFO_FAIL;
Bram Moolenaar03f48552006-02-28 23:52:23 +00003436 CloseHandle(hFile);
3437 }
3438
Bram Moolenaar03f48552006-02-28 23:52:23 +00003439 return res;
3440}
3441
3442/*
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003443 * get file attributes for `name'
3444 * -1 : error
3445 * else FILE_ATTRIBUTE_* defined in winnt.h
3446 */
Bram Moolenaarffa22202013-11-21 12:34:11 +01003447 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003448win32_getattrs(char_u *name)
3449{
3450 int attr;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003451 WCHAR *p;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003452
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003453 p = enc_to_utf16(name, NULL);
3454 if (p == NULL)
3455 return INVALID_FILE_ATTRIBUTES;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003456
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003457 attr = GetFileAttributesW(p);
3458 vim_free(p);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003459
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003460 return attr;
3461}
3462
3463/*
3464 * set file attributes for `name' to `attrs'
3465 *
3466 * return -1 for failure, 0 otherwise
3467 */
Bram Moolenaar6dff58f2018-09-30 21:43:26 +02003468 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003469win32_setattrs(char_u *name, int attrs)
3470{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003471 int res;
3472 WCHAR *p;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003473
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003474 p = enc_to_utf16(name, NULL);
3475 if (p == NULL)
3476 return -1;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003477
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003478 res = SetFileAttributesW(p, attrs);
3479 vim_free(p);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003480
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003481 return res ? 0 : -1;
3482}
3483
3484/*
3485 * Set archive flag for "name".
3486 */
Bram Moolenaar6dff58f2018-09-30 21:43:26 +02003487 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003488win32_set_archive(char_u *name)
3489{
3490 int attrs = win32_getattrs(name);
3491 if (attrs == -1)
3492 return -1;
3493
3494 attrs |= FILE_ATTRIBUTE_ARCHIVE;
3495 return win32_setattrs(name, attrs);
3496}
3497
3498/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003499 * Return TRUE if file or directory "name" is writable (not readonly).
3500 * Strange semantics of Win32: a readonly directory is writable, but you can't
3501 * delete a file. Let's say this means it is writable.
3502 */
3503 int
3504mch_writable(char_u *name)
3505{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003506 int attrs = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003507
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003508 return (attrs != -1 && (!(attrs & FILE_ATTRIBUTE_READONLY)
3509 || (attrs & FILE_ATTRIBUTE_DIRECTORY)));
Bram Moolenaar071d4272004-06-13 20:20:40 +00003510}
3511
Bram Moolenaar071d4272004-06-13 20:20:40 +00003512/*
Bram Moolenaar43663192017-03-05 14:29:12 +01003513 * Return TRUE if "name" can be executed, FALSE if not.
Bram Moolenaar77b77102015-03-21 22:18:41 +01003514 * If "use_path" is FALSE only check if "name" is executable.
Bram Moolenaar43663192017-03-05 14:29:12 +01003515 * When returning TRUE and "path" is not NULL save the path and set "*path" to
3516 * the allocated memory.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003517 */
3518 int
Yegappan Lakshmananebb01bd2022-06-08 15:14:09 +01003519mch_can_exe(char_u *name, char_u **path, int use_path UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003520{
Bram Moolenaar95da1362020-05-30 18:37:55 +02003521 return executable_exists((char *)name, path, TRUE, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003522}
Bram Moolenaar071d4272004-06-13 20:20:40 +00003523
3524/*
3525 * Check what "name" is:
3526 * NODE_NORMAL: file or directory (or doesn't exist)
3527 * NODE_WRITABLE: writable device, socket, fifo, etc.
3528 * NODE_OTHER: non-writable things
3529 */
3530 int
3531mch_nodetype(char_u *name)
3532{
3533 HANDLE hFile;
3534 int type;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003535 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003536
Bram Moolenaar0f873732019-12-05 20:28:46 +01003537 // We can't open a file with a name "\\.\con" or "\\.\prn" and trying to
3538 // read from it later will cause Vim to hang. Thus return NODE_WRITABLE
3539 // here.
Bram Moolenaar043545e2006-10-10 16:44:07 +00003540 if (STRNCMP(name, "\\\\.\\", 4) == 0)
3541 return NODE_WRITABLE;
3542
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003543 wn = enc_to_utf16(name, NULL);
3544 if (wn == NULL)
3545 return NODE_NORMAL;
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003546
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003547 hFile = CreateFileW(wn, // file name
3548 GENERIC_WRITE, // access mode
3549 0, // share mode
3550 NULL, // security descriptor
3551 OPEN_EXISTING, // creation disposition
3552 0, // file attributes
3553 NULL); // handle to template file
3554 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003555 if (hFile == INVALID_HANDLE_VALUE)
3556 return NODE_NORMAL;
3557
3558 type = GetFileType(hFile);
3559 CloseHandle(hFile);
3560 if (type == FILE_TYPE_CHAR)
3561 return NODE_WRITABLE;
3562 if (type == FILE_TYPE_DISK)
3563 return NODE_NORMAL;
3564 return NODE_OTHER;
3565}
3566
3567#ifdef HAVE_ACL
3568struct my_acl
3569{
3570 PSECURITY_DESCRIPTOR pSecurityDescriptor;
3571 PSID pSidOwner;
3572 PSID pSidGroup;
3573 PACL pDacl;
3574 PACL pSacl;
3575};
3576#endif
3577
3578/*
3579 * Return a pointer to the ACL of file "fname" in allocated memory.
3580 * Return NULL if the ACL is not available for whatever reason.
3581 */
3582 vim_acl_T
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003583mch_get_acl(char_u *fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003584{
3585#ifndef HAVE_ACL
3586 return (vim_acl_T)NULL;
3587#else
3588 struct my_acl *p = NULL;
Bram Moolenaar27515922013-06-29 15:36:26 +02003589 DWORD err;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003590
Bram Moolenaarc799fe22019-05-28 23:08:19 +02003591 p = ALLOC_CLEAR_ONE(struct my_acl);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003592 if (p != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003593 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003594 WCHAR *wn;
Bram Moolenaar27515922013-06-29 15:36:26 +02003595
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003596 wn = enc_to_utf16(fname, NULL);
3597 if (wn == NULL)
Bram Moolenaarbbf9f342020-11-10 22:03:40 +01003598 {
3599 vim_free(p);
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003600 return NULL;
Bram Moolenaarbbf9f342020-11-10 22:03:40 +01003601 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003602
3603 // Try to retrieve the entire security descriptor.
3604 err = GetNamedSecurityInfoW(
3605 wn, // Abstract filename
3606 SE_FILE_OBJECT, // File Object
3607 OWNER_SECURITY_INFORMATION |
3608 GROUP_SECURITY_INFORMATION |
3609 DACL_SECURITY_INFORMATION |
3610 SACL_SECURITY_INFORMATION,
3611 &p->pSidOwner, // Ownership information.
3612 &p->pSidGroup, // Group membership.
3613 &p->pDacl, // Discretionary information.
3614 &p->pSacl, // For auditing purposes.
3615 &p->pSecurityDescriptor);
3616 if (err == ERROR_ACCESS_DENIED ||
3617 err == ERROR_PRIVILEGE_NOT_HELD)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003618 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003619 // Retrieve only DACL.
3620 (void)GetNamedSecurityInfoW(
3621 wn,
3622 SE_FILE_OBJECT,
3623 DACL_SECURITY_INFORMATION,
3624 NULL,
3625 NULL,
3626 &p->pDacl,
3627 NULL,
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003628 &p->pSecurityDescriptor);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003629 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003630 if (p->pSecurityDescriptor == NULL)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003631 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003632 mch_free_acl((vim_acl_T)p);
3633 p = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003634 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003635 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003636 }
3637
3638 return (vim_acl_T)p;
3639#endif
3640}
3641
Bram Moolenaar27515922013-06-29 15:36:26 +02003642#ifdef HAVE_ACL
3643/*
3644 * Check if "acl" contains inherited ACE.
3645 */
3646 static BOOL
3647is_acl_inherited(PACL acl)
3648{
3649 DWORD i;
3650 ACL_SIZE_INFORMATION acl_info;
3651 PACCESS_ALLOWED_ACE ace;
3652
3653 acl_info.AceCount = 0;
3654 GetAclInformation(acl, &acl_info, sizeof(acl_info), AclSizeInformation);
3655 for (i = 0; i < acl_info.AceCount; i++)
3656 {
3657 GetAce(acl, i, (LPVOID *)&ace);
3658 if (ace->Header.AceFlags & INHERITED_ACE)
3659 return TRUE;
3660 }
3661 return FALSE;
3662}
3663#endif
3664
Bram Moolenaar071d4272004-06-13 20:20:40 +00003665/*
3666 * Set the ACL of file "fname" to "acl" (unless it's NULL).
3667 * Errors are ignored.
3668 * This must only be called with "acl" equal to what mch_get_acl() returned.
3669 */
3670 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003671mch_set_acl(char_u *fname, vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003672{
3673#ifdef HAVE_ACL
3674 struct my_acl *p = (struct my_acl *)acl;
Bram Moolenaar27515922013-06-29 15:36:26 +02003675 SECURITY_INFORMATION sec_info = 0;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003676 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003677
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003678 if (p == NULL)
3679 return;
3680
3681 wn = enc_to_utf16(fname, NULL);
3682 if (wn == NULL)
3683 return;
3684
3685 // Set security flags
3686 if (p->pSidOwner)
3687 sec_info |= OWNER_SECURITY_INFORMATION;
3688 if (p->pSidGroup)
3689 sec_info |= GROUP_SECURITY_INFORMATION;
3690 if (p->pDacl)
Bram Moolenaar27515922013-06-29 15:36:26 +02003691 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003692 sec_info |= DACL_SECURITY_INFORMATION;
3693 // Do not inherit its parent's DACL.
3694 // If the DACL is inherited, Cygwin permissions would be changed.
3695 if (!is_acl_inherited(p->pDacl))
3696 sec_info |= PROTECTED_DACL_SECURITY_INFORMATION;
Bram Moolenaar27515922013-06-29 15:36:26 +02003697 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003698 if (p->pSacl)
3699 sec_info |= SACL_SECURITY_INFORMATION;
3700
3701 (void)SetNamedSecurityInfoW(
3702 wn, // Abstract filename
3703 SE_FILE_OBJECT, // File Object
3704 sec_info,
3705 p->pSidOwner, // Ownership information.
3706 p->pSidGroup, // Group membership.
3707 p->pDacl, // Discretionary information.
3708 p->pSacl // For auditing purposes.
3709 );
3710 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003711#endif
3712}
3713
3714 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003715mch_free_acl(vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003716{
3717#ifdef HAVE_ACL
3718 struct my_acl *p = (struct my_acl *)acl;
3719
3720 if (p != NULL)
3721 {
3722 LocalFree(p->pSecurityDescriptor); // Free the memory just in case
3723 vim_free(p);
3724 }
3725#endif
3726}
3727
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003728#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003729
3730/*
3731 * handler for ctrl-break, ctrl-c interrupts, and fatal events.
3732 */
3733 static BOOL WINAPI
3734handler_routine(
3735 DWORD dwCtrlType)
3736{
Bram Moolenaar589b1102017-08-12 16:39:05 +02003737 INPUT_RECORD ir;
3738 DWORD out;
3739
Bram Moolenaar071d4272004-06-13 20:20:40 +00003740 switch (dwCtrlType)
3741 {
3742 case CTRL_C_EVENT:
3743 if (ctrl_c_interrupts)
3744 g_fCtrlCPressed = TRUE;
3745 return TRUE;
3746
3747 case CTRL_BREAK_EVENT:
3748 g_fCBrkPressed = TRUE;
Bram Moolenaar589b1102017-08-12 16:39:05 +02003749 ctrl_break_was_pressed = TRUE;
Bram Moolenaar0f873732019-12-05 20:28:46 +01003750 // ReadConsoleInput is blocking, send a key event to continue.
Bram Moolenaar589b1102017-08-12 16:39:05 +02003751 ir.EventType = KEY_EVENT;
3752 ir.Event.KeyEvent.bKeyDown = TRUE;
3753 ir.Event.KeyEvent.wRepeatCount = 1;
3754 ir.Event.KeyEvent.wVirtualKeyCode = VK_CANCEL;
3755 ir.Event.KeyEvent.wVirtualScanCode = 0;
3756 ir.Event.KeyEvent.dwControlKeyState = 0;
3757 ir.Event.KeyEvent.uChar.UnicodeChar = 0;
3758 WriteConsoleInput(g_hConIn, &ir, 1, &out);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003759 return TRUE;
3760
Bram Moolenaar0f873732019-12-05 20:28:46 +01003761 // fatal events: shut down gracefully
Bram Moolenaar071d4272004-06-13 20:20:40 +00003762 case CTRL_CLOSE_EVENT:
3763 case CTRL_LOGOFF_EVENT:
3764 case CTRL_SHUTDOWN_EVENT:
3765 windgoto((int)Rows - 1, 0);
3766 g_fForceExit = TRUE;
3767
Bram Moolenaar0fde2902008-03-16 13:54:13 +00003768 vim_snprintf((char *)IObuff, IOSIZE, _("Vim: Caught %s event\n"),
Bram Moolenaar071d4272004-06-13 20:20:40 +00003769 (dwCtrlType == CTRL_CLOSE_EVENT
3770 ? _("close")
3771 : dwCtrlType == CTRL_LOGOFF_EVENT
3772 ? _("logoff")
3773 : _("shutdown")));
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003774# ifdef DEBUG
Bram Moolenaar071d4272004-06-13 20:20:40 +00003775 OutputDebugString(IObuff);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003776# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003777
Bram Moolenaar0f873732019-12-05 20:28:46 +01003778 preserve_exit(); // output IObuff, preserve files and exit
Bram Moolenaar071d4272004-06-13 20:20:40 +00003779
Bram Moolenaar0f873732019-12-05 20:28:46 +01003780 return TRUE; // not reached
Bram Moolenaar071d4272004-06-13 20:20:40 +00003781
3782 default:
3783 return FALSE;
3784 }
3785}
3786
3787
3788/*
3789 * set the tty in (raw) ? "raw" : "cooked" mode
3790 */
3791 void
Bram Moolenaar26e86442020-05-17 14:06:16 +02003792mch_settmode(tmode_T tmode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003793{
3794 DWORD cmodein;
3795 DWORD cmodeout;
3796 BOOL bEnableHandler;
3797
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003798# ifdef VIMDLL
3799 if (gui.in_use)
3800 return;
3801# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003802 GetConsoleMode(g_hConIn, &cmodein);
3803 GetConsoleMode(g_hConOut, &cmodeout);
3804 if (tmode == TMODE_RAW)
3805 {
3806 cmodein &= ~(ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
3807 ENABLE_ECHO_INPUT);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003808 if (g_fMouseActive)
Wez Furlong6ef5ab52021-05-30 19:29:41 +02003809 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00003810 cmodein |= ENABLE_MOUSE_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02003811 cmodein &= ~ENABLE_QUICK_EDIT_MODE;
3812 }
3813 else
3814 {
3815 cmodein |= g_cmodein & ENABLE_QUICK_EDIT_MODE;
3816 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01003817 cmodeout &= ~(
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003818# ifdef FEAT_TERMGUICOLORS
Bram Moolenaar0f873732019-12-05 20:28:46 +01003819 // Do not turn off the ENABLE_PROCESSED_OUTPUT flag when using
3820 // VTP.
Bram Moolenaarcafafb32018-02-22 21:07:09 +01003821 ((vtp_working) ? 0 : ENABLE_PROCESSED_OUTPUT) |
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003822# else
Bram Moolenaarcafafb32018-02-22 21:07:09 +01003823 ENABLE_PROCESSED_OUTPUT |
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003824# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01003825 ENABLE_WRAP_AT_EOL_OUTPUT);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003826 bEnableHandler = TRUE;
3827 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01003828 else // cooked
Bram Moolenaar071d4272004-06-13 20:20:40 +00003829 {
3830 cmodein |= (ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
3831 ENABLE_ECHO_INPUT);
3832 cmodeout |= (ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
3833 bEnableHandler = FALSE;
3834 }
Wez Furlong6ef5ab52021-05-30 19:29:41 +02003835 SetConsoleMode(g_hConIn, cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003836 SetConsoleMode(g_hConOut, cmodeout);
3837 SetConsoleCtrlHandler(handler_routine, bEnableHandler);
3838
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003839# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00003840 if (fdDump)
3841 {
3842 fprintf(fdDump, "mch_settmode(%s, in = %x, out = %x)\n",
3843 tmode == TMODE_RAW ? "raw" :
3844 tmode == TMODE_COOK ? "cooked" : "normal",
3845 cmodein, cmodeout);
3846 fflush(fdDump);
3847 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003848# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003849}
3850
3851
3852/*
3853 * Get the size of the current window in `Rows' and `Columns'
3854 * Return OK when size could be determined, FAIL otherwise.
3855 */
3856 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003857mch_get_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003858{
3859 CONSOLE_SCREEN_BUFFER_INFO csbi;
3860
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003861# ifdef VIMDLL
3862 if (gui.in_use)
3863 return OK;
3864# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003865 if (!g_fTermcapMode && g_cbTermcap.IsValid)
3866 {
3867 /*
3868 * For some reason, we are trying to get the screen dimensions
3869 * even though we are not in termcap mode. The 'Rows' and 'Columns'
3870 * variables are really intended to mean the size of Vim screen
3871 * while in termcap mode.
3872 */
3873 Rows = g_cbTermcap.Info.dwSize.Y;
3874 Columns = g_cbTermcap.Info.dwSize.X;
3875 }
3876 else if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3877 {
3878 Rows = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
3879 Columns = csbi.srWindow.Right - csbi.srWindow.Left + 1;
3880 }
3881 else
3882 {
3883 Rows = 25;
3884 Columns = 80;
3885 }
3886 return OK;
3887}
3888
3889/*
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02003890 * Resize console buffer to 'COORD'
3891 */
3892 static void
3893ResizeConBuf(
3894 HANDLE hConsole,
3895 COORD coordScreen)
3896{
3897 if (!SetConsoleScreenBufferSize(hConsole, coordScreen))
3898 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003899# ifdef MCH_WRITE_DUMP
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02003900 if (fdDump)
3901 {
3902 fprintf(fdDump, "SetConsoleScreenBufferSize failed: %lx\n",
3903 GetLastError());
3904 fflush(fdDump);
3905 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003906# endif
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02003907 }
3908}
3909
3910/*
3911 * Resize console window size to 'srWindowRect'
3912 */
3913 static void
3914ResizeWindow(
3915 HANDLE hConsole,
3916 SMALL_RECT srWindowRect)
3917{
3918 if (!SetConsoleWindowInfo(hConsole, TRUE, &srWindowRect))
3919 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003920# ifdef MCH_WRITE_DUMP
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02003921 if (fdDump)
3922 {
3923 fprintf(fdDump, "SetConsoleWindowInfo failed: %lx\n",
3924 GetLastError());
3925 fflush(fdDump);
3926 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003927# endif
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02003928 }
3929}
3930
3931/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003932 * Set a console window to `xSize' * `ySize'
3933 */
3934 static void
3935ResizeConBufAndWindow(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003936 HANDLE hConsole,
3937 int xSize,
3938 int ySize)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003939{
Bram Moolenaar0f873732019-12-05 20:28:46 +01003940 CONSOLE_SCREEN_BUFFER_INFO csbi; // hold current console buffer info
3941 SMALL_RECT srWindowRect; // hold the new console size
Bram Moolenaar071d4272004-06-13 20:20:40 +00003942 COORD coordScreen;
Bram Moolenaarf49a6922019-07-15 20:37:05 +02003943 COORD cursor;
Bram Moolenaar2551c032018-08-23 22:38:31 +02003944 static int resized = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003945
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003946# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00003947 if (fdDump)
3948 {
3949 fprintf(fdDump, "ResizeConBufAndWindow(%d, %d)\n", xSize, ySize);
3950 fflush(fdDump);
3951 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003952# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003953
Bram Moolenaar0f873732019-12-05 20:28:46 +01003954 // get the largest size we can size the console window to
Bram Moolenaar071d4272004-06-13 20:20:40 +00003955 coordScreen = GetLargestConsoleWindowSize(hConsole);
3956
Bram Moolenaar0f873732019-12-05 20:28:46 +01003957 // define the new console window size and scroll position
Bram Moolenaar071d4272004-06-13 20:20:40 +00003958 srWindowRect.Left = srWindowRect.Top = (SHORT) 0;
3959 srWindowRect.Right = (SHORT) (min(xSize, coordScreen.X) - 1);
3960 srWindowRect.Bottom = (SHORT) (min(ySize, coordScreen.Y) - 1);
3961
3962 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3963 {
3964 int sx, sy;
3965
3966 sx = csbi.srWindow.Right - csbi.srWindow.Left + 1;
3967 sy = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
3968 if (sy < ySize || sx < xSize)
3969 {
3970 /*
3971 * Increasing number of lines/columns, do buffer first.
3972 * Use the maximal size in x and y direction.
3973 */
3974 if (sy < ySize)
3975 coordScreen.Y = ySize;
3976 else
3977 coordScreen.Y = sy;
3978 if (sx < xSize)
3979 coordScreen.X = xSize;
3980 else
3981 coordScreen.X = sx;
3982 SetConsoleScreenBufferSize(hConsole, coordScreen);
3983 }
3984 }
3985
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02003986 // define the new console buffer size
Bram Moolenaar071d4272004-06-13 20:20:40 +00003987 coordScreen.X = xSize;
3988 coordScreen.Y = ySize;
3989
Bram Moolenaar2551c032018-08-23 22:38:31 +02003990 // In the new console call API, only the first time in reverse order
3991 if (!vtp_working || resized)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003992 {
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02003993 ResizeWindow(hConsole, srWindowRect);
3994 ResizeConBuf(hConsole, coordScreen);
3995 }
3996 else
3997 {
Bram Moolenaarf49a6922019-07-15 20:37:05 +02003998 // Workaround for a Windows 10 bug
3999 cursor.X = srWindowRect.Left;
4000 cursor.Y = srWindowRect.Top;
4001 SetConsoleCursorPosition(hConsole, cursor);
4002
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004003 ResizeConBuf(hConsole, coordScreen);
4004 ResizeWindow(hConsole, srWindowRect);
Bram Moolenaar2551c032018-08-23 22:38:31 +02004005 resized = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004006 }
4007}
4008
4009
4010/*
4011 * Set the console window to `Rows' * `Columns'
4012 */
4013 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004014mch_set_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004015{
4016 COORD coordScreen;
4017
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004018# ifdef VIMDLL
4019 if (gui.in_use)
4020 return;
4021# endif
Bram Moolenaar0f873732019-12-05 20:28:46 +01004022 // Don't change window size while still starting up
Bram Moolenaar071d4272004-06-13 20:20:40 +00004023 if (suppress_winsize != 0)
4024 {
4025 suppress_winsize = 2;
4026 return;
4027 }
4028
4029 if (term_console)
4030 {
4031 coordScreen = GetLargestConsoleWindowSize(g_hConOut);
4032
Bram Moolenaar0f873732019-12-05 20:28:46 +01004033 // Clamp Rows and Columns to reasonable values
Bram Moolenaar071d4272004-06-13 20:20:40 +00004034 if (Rows > coordScreen.Y)
4035 Rows = coordScreen.Y;
4036 if (Columns > coordScreen.X)
4037 Columns = coordScreen.X;
4038
4039 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
4040 }
4041}
4042
4043/*
4044 * Rows and/or Columns has changed.
4045 */
4046 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004047mch_new_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004048{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004049# ifdef VIMDLL
4050 if (gui.in_use)
4051 return;
4052# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004053 set_scroll_region(0, 0, Columns - 1, Rows - 1);
4054}
4055
4056
4057/*
4058 * Called when started up, to set the winsize that was delayed.
4059 */
4060 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004061mch_set_winsize_now(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004062{
4063 if (suppress_winsize == 2)
4064 {
4065 suppress_winsize = 0;
4066 mch_set_shellsize();
4067 shell_resized();
4068 }
4069 suppress_winsize = 0;
4070}
Bram Moolenaar0f873732019-12-05 20:28:46 +01004071#endif // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00004072
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004073 static BOOL
4074vim_create_process(
Bram Moolenaar36c85b22013-12-12 20:25:44 +01004075 char *cmd,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004076 BOOL inherit_handles,
Bram Moolenaar3f1138e2014-01-05 13:29:26 +01004077 DWORD flags,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004078 STARTUPINFO *si,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004079 PROCESS_INFORMATION *pi,
4080 LPVOID *env,
4081 char *cwd)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004082{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004083 BOOL ret = FALSE;
4084 WCHAR *wcmd, *wcwd = NULL;
4085
4086 wcmd = enc_to_utf16((char_u *)cmd, NULL);
4087 if (wcmd == NULL)
4088 return FALSE;
4089 if (cwd != NULL)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004090 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004091 wcwd = enc_to_utf16((char_u *)cwd, NULL);
4092 if (wcwd == NULL)
4093 goto theend;
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004094 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004095
4096 ret = CreateProcessW(
4097 NULL, // Executable name
4098 wcmd, // Command to execute
4099 NULL, // Process security attributes
4100 NULL, // Thread security attributes
4101 inherit_handles, // Inherit handles
4102 flags, // Creation flags
4103 env, // Environment
4104 wcwd, // Current directory
4105 (LPSTARTUPINFOW)si, // Startup information
4106 pi); // Process information
4107theend:
4108 vim_free(wcmd);
4109 vim_free(wcwd);
4110 return ret;
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004111}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004112
4113
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004114 static HINSTANCE
4115vim_shell_execute(
4116 char *cmd,
4117 INT n_show_cmd)
4118{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004119 HINSTANCE ret;
4120 WCHAR *wcmd;
4121
4122 wcmd = enc_to_utf16((char_u *)cmd, NULL);
4123 if (wcmd == NULL)
4124 return (HINSTANCE) 0;
4125
4126 ret = ShellExecuteW(NULL, NULL, wcmd, NULL, NULL, n_show_cmd);
4127 vim_free(wcmd);
4128 return ret;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004129}
4130
4131
Bram Moolenaar4f974752019-02-17 17:44:42 +01004132#if defined(FEAT_GUI_MSWIN) || defined(PROTO)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004133
4134/*
4135 * Specialised version of system() for Win32 GUI mode.
4136 * This version proceeds as follows:
4137 * 1. Create a console window for use by the subprocess
4138 * 2. Run the subprocess (it gets the allocated console by default)
4139 * 3. Wait for the subprocess to terminate and get its exit code
4140 * 4. Prompt the user to press a key to close the console window
4141 */
4142 static int
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004143mch_system_classic(char *cmd, int options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004144{
4145 STARTUPINFO si;
4146 PROCESS_INFORMATION pi;
4147 DWORD ret = 0;
4148 HWND hwnd = GetFocus();
4149
4150 si.cb = sizeof(si);
4151 si.lpReserved = NULL;
4152 si.lpDesktop = NULL;
4153 si.lpTitle = NULL;
4154 si.dwFlags = STARTF_USESHOWWINDOW;
4155 /*
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004156 * It's nicer to run a filter command in a minimized window.
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01004157 * Don't activate the window to keep focus on Vim.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004158 */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004159 if (options & SHELL_DOOUT)
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01004160 si.wShowWindow = SW_SHOWMINNOACTIVE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004161 else
4162 si.wShowWindow = SW_SHOWNORMAL;
4163 si.cbReserved2 = 0;
4164 si.lpReserved2 = NULL;
4165
Bram Moolenaar0f873732019-12-05 20:28:46 +01004166 // Now, run the command
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004167 vim_create_process(cmd, FALSE,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004168 CREATE_DEFAULT_ERROR_MODE | CREATE_NEW_CONSOLE,
4169 &si, &pi, NULL, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004170
Bram Moolenaar0f873732019-12-05 20:28:46 +01004171 // Wait for the command to terminate before continuing
Bram Moolenaar071d4272004-06-13 20:20:40 +00004172 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004173# ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00004174 int delay = 1;
4175
Bram Moolenaar0f873732019-12-05 20:28:46 +01004176 // Keep updating the window while waiting for the shell to finish.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004177 for (;;)
4178 {
4179 MSG msg;
4180
K.Takatab7057bd2022-01-21 11:37:07 +00004181 if (PeekMessageW(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004182 {
4183 TranslateMessage(&msg);
K.Takatab7057bd2022-01-21 11:37:07 +00004184 DispatchMessageW(&msg);
Bram Moolenaare4195c52012-08-02 12:31:44 +02004185 delay = 1;
4186 continue;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004187 }
4188 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
4189 break;
4190
Bram Moolenaar0f873732019-12-05 20:28:46 +01004191 // We start waiting for a very short time and then increase it, so
4192 // that we respond quickly when the process is quick, and don't
4193 // consume too much overhead when it's slow.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004194 if (delay < 50)
4195 delay += 10;
4196 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004197# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004198 WaitForSingleObject(pi.hProcess, INFINITE);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004199# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004200
Bram Moolenaar0f873732019-12-05 20:28:46 +01004201 // Get the command exit code
Bram Moolenaar071d4272004-06-13 20:20:40 +00004202 GetExitCodeProcess(pi.hProcess, &ret);
4203 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004204
Bram Moolenaar0f873732019-12-05 20:28:46 +01004205 // Close the handles to the subprocess, so that it goes away
Bram Moolenaar071d4272004-06-13 20:20:40 +00004206 CloseHandle(pi.hThread);
4207 CloseHandle(pi.hProcess);
4208
Bram Moolenaar0f873732019-12-05 20:28:46 +01004209 // Try to get input focus back. Doesn't always work though.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004210 PostMessage(hwnd, WM_SETFOCUS, 0, 0);
4211
4212 return ret;
4213}
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004214
4215/*
4216 * Thread launched by the gui to send the current buffer data to the
4217 * process. This way avoid to hang up vim totally if the children
4218 * process take a long time to process the lines.
4219 */
Bram Moolenaar4c38d662016-08-03 20:54:57 +02004220 static unsigned int __stdcall
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004221sub_process_writer(LPVOID param)
4222{
4223 HANDLE g_hChildStd_IN_Wr = param;
4224 linenr_T lnum = curbuf->b_op_start.lnum;
4225 DWORD len = 0;
4226 DWORD l;
4227 char_u *lp = ml_get(lnum);
4228 char_u *s;
4229 int written = 0;
4230
4231 for (;;)
4232 {
4233 l = (DWORD)STRLEN(lp + written);
4234 if (l == 0)
4235 len = 0;
4236 else if (lp[written] == NL)
4237 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004238 // NL -> NUL translation
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004239 WriteFile(g_hChildStd_IN_Wr, "", 1, &len, NULL);
4240 }
4241 else
4242 {
4243 s = vim_strchr(lp + written, NL);
4244 WriteFile(g_hChildStd_IN_Wr, (char *)lp + written,
4245 s == NULL ? l : (DWORD)(s - (lp + written)),
4246 &len, NULL);
4247 }
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +01004248 if (len == l)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004249 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004250 // Finished a line, add a NL, unless this line should not have
4251 // one.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004252 if (lnum != curbuf->b_op_end.lnum
Bram Moolenaar34d72d42015-07-17 14:18:08 +02004253 || (!curbuf->b_p_bin
4254 && curbuf->b_p_fixeol)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004255 || (lnum != curbuf->b_no_eol_lnum
4256 && (lnum != curbuf->b_ml.ml_line_count
4257 || curbuf->b_p_eol)))
4258 {
Bram Moolenaar42335f52018-09-13 15:33:43 +02004259 WriteFile(g_hChildStd_IN_Wr, "\n", 1,
4260 (LPDWORD)&vim_ignored, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004261 }
4262
4263 ++lnum;
4264 if (lnum > curbuf->b_op_end.lnum)
4265 break;
4266
4267 lp = ml_get(lnum);
4268 written = 0;
4269 }
4270 else if (len > 0)
4271 written += len;
4272 }
4273
Bram Moolenaar0f873732019-12-05 20:28:46 +01004274 // finished all the lines, close pipe
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004275 CloseHandle(g_hChildStd_IN_Wr);
Bram Moolenaar86f2cd52016-08-02 21:55:17 +02004276 return 0;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004277}
4278
4279
Bram Moolenaar0f873732019-12-05 20:28:46 +01004280# define BUFLEN 100 // length for buffer, stolen from unix version
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004281
4282/*
4283 * This function read from the children's stdout and write the
4284 * data on screen or in the buffer accordingly.
4285 */
4286 static void
4287dump_pipe(int options,
4288 HANDLE g_hChildStd_OUT_Rd,
4289 garray_T *ga,
4290 char_u buffer[],
4291 DWORD *buffer_off)
4292{
4293 DWORD availableBytes = 0;
4294 DWORD i;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004295 int ret;
4296 DWORD len;
4297 DWORD toRead;
4298 int repeatCount;
4299
Bram Moolenaar0f873732019-12-05 20:28:46 +01004300 // we query the pipe to see if there is any data to read
4301 // to avoid to perform a blocking read
4302 ret = PeekNamedPipe(g_hChildStd_OUT_Rd, // pipe to query
4303 NULL, // optional buffer
4304 0, // buffer size
4305 NULL, // number of read bytes
4306 &availableBytes, // available bytes total
4307 NULL); // byteLeft
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004308
4309 repeatCount = 0;
Bram Moolenaar0f873732019-12-05 20:28:46 +01004310 // We got real data in the pipe, read it
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02004311 while (ret != 0 && availableBytes > 0)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004312 {
4313 repeatCount++;
Bram Moolenaara12a1612019-01-24 16:39:02 +01004314 toRead = (DWORD)(BUFLEN - *buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004315 toRead = availableBytes < toRead ? availableBytes : toRead;
Bram Moolenaara12a1612019-01-24 16:39:02 +01004316 ReadFile(g_hChildStd_OUT_Rd, buffer + *buffer_off, toRead , &len, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004317
Bram Moolenaar0f873732019-12-05 20:28:46 +01004318 // If we haven't read anything, there is a problem
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004319 if (len == 0)
4320 break;
4321
4322 availableBytes -= len;
4323
4324 if (options & SHELL_READ)
4325 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004326 // Do NUL -> NL translation, append NL separated
4327 // lines to the current buffer.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004328 for (i = 0; i < len; ++i)
4329 {
4330 if (buffer[i] == NL)
4331 append_ga_line(ga);
4332 else if (buffer[i] == NUL)
4333 ga_append(ga, NL);
4334 else
4335 ga_append(ga, buffer[i]);
4336 }
4337 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004338 else if (has_mbyte)
4339 {
4340 int l;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004341 int c;
4342 char_u *p;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004343
4344 len += *buffer_off;
4345 buffer[len] = NUL;
4346
Bram Moolenaar0f873732019-12-05 20:28:46 +01004347 // Check if the last character in buffer[] is
4348 // incomplete, keep these bytes for the next
4349 // round.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004350 for (p = buffer; p < buffer + len; p += l)
4351 {
Bram Moolenaard3c907b2016-08-17 21:32:09 +02004352 l = MB_CPTR2LEN(p);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004353 if (l == 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01004354 l = 1; // NUL byte?
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004355 else if (MB_BYTE2LEN(*p) != l)
4356 break;
4357 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01004358 if (p == buffer) // no complete character
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004359 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004360 // avoid getting stuck at an illegal byte
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004361 if (len >= 12)
4362 ++p;
4363 else
4364 {
4365 *buffer_off = len;
4366 return;
4367 }
4368 }
4369 c = *p;
4370 *p = NUL;
Bram Moolenaar32526b32019-01-19 17:43:09 +01004371 msg_puts((char *)buffer);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004372 if (p < buffer + len)
4373 {
4374 *p = c;
4375 *buffer_off = (DWORD)((buffer + len) - p);
4376 mch_memmove(buffer, p, *buffer_off);
4377 return;
4378 }
4379 *buffer_off = 0;
4380 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004381 else
4382 {
4383 buffer[len] = NUL;
Bram Moolenaar32526b32019-01-19 17:43:09 +01004384 msg_puts((char *)buffer);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004385 }
4386
4387 windgoto(msg_row, msg_col);
4388 cursor_on();
4389 out_flush();
4390 }
4391}
4392
4393/*
4394 * Version of system to use for windows NT > 5.0 (Win2K), use pipe
4395 * for communication and doesn't open any new window.
4396 */
4397 static int
4398mch_system_piped(char *cmd, int options)
4399{
4400 STARTUPINFO si;
4401 PROCESS_INFORMATION pi;
4402 DWORD ret = 0;
4403
4404 HANDLE g_hChildStd_IN_Rd = NULL;
4405 HANDLE g_hChildStd_IN_Wr = NULL;
4406 HANDLE g_hChildStd_OUT_Rd = NULL;
4407 HANDLE g_hChildStd_OUT_Wr = NULL;
4408
Bram Moolenaar0f873732019-12-05 20:28:46 +01004409 char_u buffer[BUFLEN + 1]; // reading buffer + size
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004410 DWORD len;
4411
Bram Moolenaar0f873732019-12-05 20:28:46 +01004412 // buffer used to receive keys
4413 char_u ta_buf[BUFLEN + 1]; // TypeAHead
4414 int ta_len = 0; // valid bytes in ta_buf[]
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004415
4416 DWORD i;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004417 int noread_cnt = 0;
4418 garray_T ga;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004419 int delay = 1;
Bram Moolenaar0f873732019-12-05 20:28:46 +01004420 DWORD buffer_off = 0; // valid bytes in buffer[]
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004421 char *p = NULL;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004422
4423 SECURITY_ATTRIBUTES saAttr;
4424
Bram Moolenaar0f873732019-12-05 20:28:46 +01004425 // Set the bInheritHandle flag so pipe handles are inherited.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004426 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
4427 saAttr.bInheritHandle = TRUE;
4428 saAttr.lpSecurityDescriptor = NULL;
4429
4430 if ( ! CreatePipe(&g_hChildStd_OUT_Rd, &g_hChildStd_OUT_Wr, &saAttr, 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01004431 // Ensure the read handle to the pipe for STDOUT is not inherited.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004432 || ! SetHandleInformation(g_hChildStd_OUT_Rd, HANDLE_FLAG_INHERIT, 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01004433 // Create a pipe for the child process's STDIN.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004434 || ! CreatePipe(&g_hChildStd_IN_Rd, &g_hChildStd_IN_Wr, &saAttr, 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01004435 // Ensure the write handle to the pipe for STDIN is not inherited.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004436 || ! SetHandleInformation(g_hChildStd_IN_Wr, HANDLE_FLAG_INHERIT, 0) )
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004437 {
4438 CloseHandle(g_hChildStd_IN_Rd);
4439 CloseHandle(g_hChildStd_IN_Wr);
4440 CloseHandle(g_hChildStd_OUT_Rd);
4441 CloseHandle(g_hChildStd_OUT_Wr);
Bram Moolenaar32526b32019-01-19 17:43:09 +01004442 msg_puts(_("\nCannot create pipes\n"));
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004443 }
4444
4445 si.cb = sizeof(si);
4446 si.lpReserved = NULL;
4447 si.lpDesktop = NULL;
4448 si.lpTitle = NULL;
4449 si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
4450
Bram Moolenaar0f873732019-12-05 20:28:46 +01004451 // set-up our file redirection
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004452 si.hStdError = g_hChildStd_OUT_Wr;
4453 si.hStdOutput = g_hChildStd_OUT_Wr;
4454 si.hStdInput = g_hChildStd_IN_Rd;
4455 si.wShowWindow = SW_HIDE;
4456 si.cbReserved2 = 0;
4457 si.lpReserved2 = NULL;
4458
4459 if (options & SHELL_READ)
4460 ga_init2(&ga, 1, BUFLEN);
4461
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004462 if (cmd != NULL)
4463 {
4464 p = (char *)vim_strsave((char_u *)cmd);
4465 if (p != NULL)
4466 unescape_shellxquote((char_u *)p, p_sxe);
4467 else
4468 p = cmd;
4469 }
4470
Bram Moolenaar0f873732019-12-05 20:28:46 +01004471 // Now, run the command.
4472 // About "Inherit handles" being TRUE: this command can be litigious,
4473 // handle inheritance was deactivated for pending temp file, but, if we
4474 // deactivate it, the pipes don't work for some reason.
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004475 vim_create_process(p, TRUE, CREATE_DEFAULT_ERROR_MODE,
4476 &si, &pi, NULL, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004477
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004478 if (p != cmd)
4479 vim_free(p);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004480
Bram Moolenaar0f873732019-12-05 20:28:46 +01004481 // Close our unused side of the pipes
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004482 CloseHandle(g_hChildStd_IN_Rd);
4483 CloseHandle(g_hChildStd_OUT_Wr);
4484
4485 if (options & SHELL_WRITE)
4486 {
Bram Moolenaar86f2cd52016-08-02 21:55:17 +02004487 HANDLE thread = (HANDLE)
Bram Moolenaar0f873732019-12-05 20:28:46 +01004488 _beginthreadex(NULL, // security attributes
4489 0, // default stack size
4490 sub_process_writer, // function to be executed
4491 g_hChildStd_IN_Wr, // parameter
4492 0, // creation flag, start immediately
4493 NULL); // we don't care about thread id
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004494 CloseHandle(thread);
4495 g_hChildStd_IN_Wr = NULL;
4496 }
4497
Bram Moolenaar0f873732019-12-05 20:28:46 +01004498 // Keep updating the window while waiting for the shell to finish.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004499 for (;;)
4500 {
4501 MSG msg;
4502
K.Takatab7057bd2022-01-21 11:37:07 +00004503 if (PeekMessageW(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004504 {
4505 TranslateMessage(&msg);
K.Takatab7057bd2022-01-21 11:37:07 +00004506 DispatchMessageW(&msg);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004507 }
4508
Bram Moolenaar0f873732019-12-05 20:28:46 +01004509 // write pipe information in the window
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004510 if ((options & (SHELL_READ|SHELL_WRITE))
4511# ifdef FEAT_GUI
4512 || gui.in_use
4513# endif
4514 )
4515 {
4516 len = 0;
4517 if (!(options & SHELL_EXPAND)
4518 && ((options &
4519 (SHELL_READ|SHELL_WRITE|SHELL_COOKED))
4520 != (SHELL_READ|SHELL_WRITE|SHELL_COOKED)
4521# ifdef FEAT_GUI
4522 || gui.in_use
4523# endif
4524 )
4525 && (ta_len > 0 || noread_cnt > 4))
4526 {
4527 if (ta_len == 0)
4528 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004529 // Get extra characters when we don't have any. Reset the
4530 // counter and timer.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004531 noread_cnt = 0;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004532 len = ui_inchar(ta_buf, BUFLEN, 10L, 0);
4533 }
4534 if (ta_len > 0 || len > 0)
4535 {
4536 /*
4537 * For pipes: Check for CTRL-C: send interrupt signal to
4538 * child. Check for CTRL-D: EOF, close pipe to child.
4539 */
4540 if (len == 1 && cmd != NULL)
4541 {
4542 if (ta_buf[ta_len] == Ctrl_C)
4543 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004544 // Learn what exit code is expected, for
4545 // now put 9 as SIGKILL
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004546 TerminateProcess(pi.hProcess, 9);
4547 }
4548 if (ta_buf[ta_len] == Ctrl_D)
4549 {
4550 CloseHandle(g_hChildStd_IN_Wr);
4551 g_hChildStd_IN_Wr = NULL;
4552 }
4553 }
4554
Bram Moolenaarf4140482020-02-15 23:06:45 +01004555 term_replace_bs_del_keycode(ta_buf, ta_len, len);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004556
4557 /*
4558 * For pipes: echo the typed characters. For a pty this
4559 * does not seem to work.
4560 */
4561 for (i = ta_len; i < ta_len + len; ++i)
4562 {
4563 if (ta_buf[i] == '\n' || ta_buf[i] == '\b')
4564 msg_putchar(ta_buf[i]);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004565 else if (has_mbyte)
4566 {
4567 int l = (*mb_ptr2len)(ta_buf + i);
4568
4569 msg_outtrans_len(ta_buf + i, l);
4570 i += l - 1;
4571 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004572 else
4573 msg_outtrans_len(ta_buf + i, 1);
4574 }
4575 windgoto(msg_row, msg_col);
4576 out_flush();
4577
4578 ta_len += len;
4579
4580 /*
4581 * Write the characters to the child, unless EOF has been
4582 * typed for pipes. Write one character at a time, to
4583 * avoid losing too much typeahead. When writing buffer
4584 * lines, drop the typed characters (only check for
4585 * CTRL-C).
4586 */
4587 if (options & SHELL_WRITE)
4588 ta_len = 0;
4589 else if (g_hChildStd_IN_Wr != NULL)
4590 {
4591 WriteFile(g_hChildStd_IN_Wr, (char*)ta_buf,
4592 1, &len, NULL);
4593 // if we are typing in, we want to keep things reactive
4594 delay = 1;
4595 if (len > 0)
4596 {
4597 ta_len -= len;
4598 mch_memmove(ta_buf, ta_buf + len, ta_len);
4599 }
4600 }
4601 }
4602 }
4603 }
4604
4605 if (ta_len)
4606 ui_inchar_undo(ta_buf, ta_len);
4607
4608 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
4609 {
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004610 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004611 break;
4612 }
4613
4614 ++noread_cnt;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004615 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004616
Bram Moolenaar0f873732019-12-05 20:28:46 +01004617 // We start waiting for a very short time and then increase it, so
4618 // that we respond quickly when the process is quick, and don't
4619 // consume too much overhead when it's slow.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004620 if (delay < 50)
4621 delay += 10;
4622 }
4623
Bram Moolenaar0f873732019-12-05 20:28:46 +01004624 // Close the pipe
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004625 CloseHandle(g_hChildStd_OUT_Rd);
4626 if (g_hChildStd_IN_Wr != NULL)
4627 CloseHandle(g_hChildStd_IN_Wr);
4628
4629 WaitForSingleObject(pi.hProcess, INFINITE);
4630
Bram Moolenaar0f873732019-12-05 20:28:46 +01004631 // Get the command exit code
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004632 GetExitCodeProcess(pi.hProcess, &ret);
4633
4634 if (options & SHELL_READ)
4635 {
4636 if (ga.ga_len > 0)
4637 {
4638 append_ga_line(&ga);
Bram Moolenaar0f873732019-12-05 20:28:46 +01004639 // remember that the NL was missing
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004640 curbuf->b_no_eol_lnum = curwin->w_cursor.lnum;
4641 }
4642 else
4643 curbuf->b_no_eol_lnum = 0;
4644 ga_clear(&ga);
4645 }
4646
Bram Moolenaar0f873732019-12-05 20:28:46 +01004647 // Close the handles to the subprocess, so that it goes away
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004648 CloseHandle(pi.hThread);
4649 CloseHandle(pi.hProcess);
4650
4651 return ret;
4652}
4653
4654 static int
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004655mch_system_g(char *cmd, int options)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004656{
Bram Moolenaar0f873732019-12-05 20:28:46 +01004657 // if we can pipe and the shelltemp option is off
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004658 if (!p_stmp)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004659 return mch_system_piped(cmd, options);
4660 else
4661 return mch_system_classic(cmd, options);
4662}
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004663#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004664
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004665#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004666 static int
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02004667mch_system_c(char *cmd, int options UNUSED)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004668{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004669 int ret;
4670 WCHAR *wcmd;
Bram Moolenaar2efc44b2019-10-05 12:09:32 +02004671 char_u *buf;
4672 size_t len;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004673
Bram Moolenaar2efc44b2019-10-05 12:09:32 +02004674 // If the command starts and ends with double quotes, enclose the command
4675 // in parentheses.
4676 len = STRLEN(cmd);
4677 if (len >= 2 && cmd[0] == '"' && cmd[len - 1] == '"')
4678 {
4679 len += 3;
4680 buf = alloc(len);
4681 if (buf == NULL)
4682 return -1;
4683 vim_snprintf((char *)buf, len, "(%s)", cmd);
4684 wcmd = enc_to_utf16(buf, NULL);
4685 free(buf);
4686 }
4687 else
4688 wcmd = enc_to_utf16((char_u *)cmd, NULL);
4689
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004690 if (wcmd == NULL)
4691 return -1;
4692
4693 ret = _wsystem(wcmd);
4694 vim_free(wcmd);
4695 return ret;
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004696}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004697
4698#endif
4699
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004700 static int
4701mch_system(char *cmd, int options)
4702{
4703#ifdef VIMDLL
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02004704 if (gui.in_use || gui.starting)
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004705 return mch_system_g(cmd, options);
4706 else
4707 return mch_system_c(cmd, options);
4708#elif defined(FEAT_GUI_MSWIN)
4709 return mch_system_g(cmd, options);
4710#else
4711 return mch_system_c(cmd, options);
4712#endif
4713}
4714
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004715#if defined(FEAT_GUI) && defined(FEAT_TERMINAL)
4716/*
4717 * Use a terminal window to run a shell command in.
4718 */
4719 static int
4720mch_call_shell_terminal(
4721 char_u *cmd,
Bram Moolenaar0f873732019-12-05 20:28:46 +01004722 int options UNUSED) // SHELL_*, see vim.h
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004723{
4724 jobopt_T opt;
4725 char_u *newcmd = NULL;
4726 typval_T argvar[2];
4727 long_u cmdlen;
4728 int retval = -1;
4729 buf_T *buf;
Bram Moolenaarf9c38832018-06-19 19:59:20 +02004730 job_T *job;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004731 aco_save_T aco;
Bram Moolenaar0f873732019-12-05 20:28:46 +01004732 oparg_T oa; // operator arguments
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004733
Bram Moolenaar42f652f2018-03-19 21:44:37 +01004734 if (cmd == NULL)
4735 cmdlen = STRLEN(p_sh) + 1;
4736 else
4737 cmdlen = STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10;
Bram Moolenaar18a4ba22019-05-24 19:39:03 +02004738 newcmd = alloc(cmdlen);
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004739 if (newcmd == NULL)
4740 return 255;
Bram Moolenaar42f652f2018-03-19 21:44:37 +01004741 if (cmd == NULL)
4742 {
4743 STRCPY(newcmd, p_sh);
4744 ch_log(NULL, "starting terminal to run a shell");
4745 }
4746 else
4747 {
4748 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s", p_sh, p_shcf, cmd);
4749 ch_log(NULL, "starting terminal for system command '%s'", cmd);
4750 }
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004751
4752 init_job_options(&opt);
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004753
4754 argvar[0].v_type = VAR_STRING;
4755 argvar[0].vval.v_string = newcmd;
4756 argvar[1].v_type = VAR_UNKNOWN;
4757 buf = term_start(argvar, NULL, &opt, TERM_START_SYSTEM);
Bram Moolenaar81c3c89a2018-03-20 11:41:44 +01004758 if (buf == NULL)
Bram Moolenaar9029b912019-03-21 19:58:00 +01004759 {
4760 vim_free(newcmd);
Bram Moolenaar81c3c89a2018-03-20 11:41:44 +01004761 return 255;
Bram Moolenaar9029b912019-03-21 19:58:00 +01004762 }
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004763
Bram Moolenaarf9c38832018-06-19 19:59:20 +02004764 job = term_getjob(buf->b_term);
4765 ++job->jv_refcount;
4766
Bram Moolenaar0f873732019-12-05 20:28:46 +01004767 // Find a window to make "buf" curbuf.
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004768 aucmd_prepbuf(&aco, buf);
4769
4770 clear_oparg(&oa);
4771 while (term_use_loop())
4772 {
4773 if (oa.op_type == OP_NOP && oa.regname == NUL && !VIsual_active)
4774 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004775 // If terminal_loop() returns OK we got a key that is handled
4776 // in Normal model. We don't do redrawing anyway.
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004777 if (terminal_loop(TRUE) == OK)
4778 normal_cmd(&oa, TRUE);
4779 }
4780 else
4781 normal_cmd(&oa, TRUE);
4782 }
Bram Moolenaarf9c38832018-06-19 19:59:20 +02004783 retval = job->jv_exitval;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004784 ch_log(NULL, "system command finished");
4785
Bram Moolenaarf9c38832018-06-19 19:59:20 +02004786 job_unref(job);
4787
Bram Moolenaar0f873732019-12-05 20:28:46 +01004788 // restore curwin/curbuf and a few other things
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004789 aucmd_restbuf(&aco);
4790
4791 wait_return(TRUE);
4792 do_buffer(DOBUF_WIPE, DOBUF_FIRST, FORWARD, buf->b_fnum, TRUE);
4793
4794 vim_free(newcmd);
4795 return retval;
4796}
4797#endif
4798
Bram Moolenaar071d4272004-06-13 20:20:40 +00004799/*
4800 * Either execute a command by calling the shell or start a new shell
4801 */
4802 int
4803mch_call_shell(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004804 char_u *cmd,
Bram Moolenaar0f873732019-12-05 20:28:46 +01004805 int options) // SHELL_*, see vim.h
Bram Moolenaar071d4272004-06-13 20:20:40 +00004806{
4807 int x = 0;
4808 int tmode = cur_tmode;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004809 WCHAR szShellTitle[512];
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004810
Bram Moolenaarc9a9a0a2022-04-12 15:09:23 +01004811#ifdef FEAT_JOB_CHANNEL
4812 ch_log(NULL, "executing shell command: %s", cmd);
4813#endif
Bram Moolenaar0f873732019-12-05 20:28:46 +01004814 // Change the title to reflect that we are in a subshell.
K.Takataeeec2542021-06-02 13:28:16 +02004815 if (GetConsoleTitleW(szShellTitle, ARRAY_LENGTH(szShellTitle) - 4) > 0)
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004816 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004817 if (cmd == NULL)
4818 wcscat(szShellTitle, L" :sh");
4819 else
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004820 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004821 WCHAR *wn = enc_to_utf16((char_u *)cmd, NULL);
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004822
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004823 if (wn != NULL)
4824 {
4825 wcscat(szShellTitle, L" - !");
4826 if ((wcslen(szShellTitle) + wcslen(wn) <
K.Takataeeec2542021-06-02 13:28:16 +02004827 ARRAY_LENGTH(szShellTitle)))
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004828 wcscat(szShellTitle, wn);
4829 SetConsoleTitleW(szShellTitle);
4830 vim_free(wn);
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004831 }
4832 }
4833 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004834
4835 out_flush();
4836
4837#ifdef MCH_WRITE_DUMP
4838 if (fdDump)
4839 {
4840 fprintf(fdDump, "mch_call_shell(\"%s\", %d)\n", cmd, options);
4841 fflush(fdDump);
4842 }
4843#endif
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004844#if defined(FEAT_GUI) && defined(FEAT_TERMINAL)
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004845 // TODO: make the terminal window work with input or output redirected.
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004846 if (
4847# ifdef VIMDLL
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004848 gui.in_use &&
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004849# endif
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004850 vim_strchr(p_go, GO_TERMINAL) != NULL
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004851 && (options & (SHELL_FILTER|SHELL_DOOUT|SHELL_WRITE|SHELL_READ)) == 0)
4852 {
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004853 char_u *cmdbase = cmd;
4854
Bram Moolenaar4d5c1262019-09-20 17:20:02 +02004855 if (cmdbase != NULL)
4856 // Skip a leading quote and (.
4857 while (*cmdbase == '"' || *cmdbase == '(')
4858 ++cmdbase;
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004859
4860 // Check the command does not begin with "start "
Bram Moolenaar36e7a822019-11-13 21:49:24 +01004861 if (cmdbase == NULL || STRNICMP(cmdbase, "start", 5) != 0
4862 || !VIM_ISWHITE(cmdbase[5]))
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004863 {
4864 // Use a terminal window to run the command in.
4865 x = mch_call_shell_terminal(cmd, options);
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004866 resettitle();
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004867 return x;
4868 }
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004869 }
4870#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004871
4872 /*
4873 * Catch all deadly signals while running the external command, because a
4874 * CTRL-C, Ctrl-Break or illegal instruction might otherwise kill us.
4875 */
4876 signal(SIGINT, SIG_IGN);
4877#if defined(__GNUC__) && !defined(__MINGW32__)
4878 signal(SIGKILL, SIG_IGN);
4879#else
4880 signal(SIGBREAK, SIG_IGN);
4881#endif
4882 signal(SIGILL, SIG_IGN);
4883 signal(SIGFPE, SIG_IGN);
4884 signal(SIGSEGV, SIG_IGN);
4885 signal(SIGTERM, SIG_IGN);
4886 signal(SIGABRT, SIG_IGN);
4887
4888 if (options & SHELL_COOKED)
Bram Moolenaar0f873732019-12-05 20:28:46 +01004889 settmode(TMODE_COOK); // set to normal mode
Bram Moolenaar071d4272004-06-13 20:20:40 +00004890
4891 if (cmd == NULL)
4892 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004893 x = mch_system((char *)p_sh, options);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004894 }
4895 else
4896 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004897 // we use "command" or "cmd" to start the shell; slow but easy
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004898 char_u *newcmd = NULL;
4899 char_u *cmdbase = cmd;
4900 long_u cmdlen;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004901
Bram Moolenaar0f873732019-12-05 20:28:46 +01004902 // Skip a leading ", ( and "(.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004903 if (*cmdbase == '"' )
4904 ++cmdbase;
4905 if (*cmdbase == '(')
4906 ++cmdbase;
4907
Bram Moolenaar1c465442017-03-12 20:10:05 +01004908 if ((STRNICMP(cmdbase, "start", 5) == 0) && VIM_ISWHITE(cmdbase[5]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004909 {
4910 STARTUPINFO si;
4911 PROCESS_INFORMATION pi;
4912 DWORD flags = CREATE_NEW_CONSOLE;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004913 INT n_show_cmd = SW_SHOWNORMAL;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004914 char_u *p;
4915
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01004916 ZeroMemory(&si, sizeof(si));
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004917 si.cb = sizeof(si);
4918 si.lpReserved = NULL;
4919 si.lpDesktop = NULL;
4920 si.lpTitle = NULL;
4921 si.dwFlags = 0;
4922 si.cbReserved2 = 0;
4923 si.lpReserved2 = NULL;
4924
4925 cmdbase = skipwhite(cmdbase + 5);
4926 if ((STRNICMP(cmdbase, "/min", 4) == 0)
Bram Moolenaar1c465442017-03-12 20:10:05 +01004927 && VIM_ISWHITE(cmdbase[4]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004928 {
4929 cmdbase = skipwhite(cmdbase + 4);
4930 si.dwFlags = STARTF_USESHOWWINDOW;
4931 si.wShowWindow = SW_SHOWMINNOACTIVE;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004932 n_show_cmd = SW_SHOWMINNOACTIVE;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004933 }
4934 else if ((STRNICMP(cmdbase, "/b", 2) == 0)
Bram Moolenaar1c465442017-03-12 20:10:05 +01004935 && VIM_ISWHITE(cmdbase[2]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004936 {
4937 cmdbase = skipwhite(cmdbase + 2);
4938 flags = CREATE_NO_WINDOW;
4939 si.dwFlags = STARTF_USESTDHANDLES;
4940 si.hStdInput = CreateFile("\\\\.\\NUL", // File name
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004941 GENERIC_READ, // Access flags
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004942 0, // Share flags
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004943 NULL, // Security att.
4944 OPEN_EXISTING, // Open flags
4945 FILE_ATTRIBUTE_NORMAL, // File att.
4946 NULL); // Temp file
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004947 si.hStdOutput = si.hStdInput;
4948 si.hStdError = si.hStdInput;
4949 }
4950
Bram Moolenaar0f873732019-12-05 20:28:46 +01004951 // Remove a trailing ", ) and )" if they have a match
4952 // at the start of the command.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004953 if (cmdbase > cmd)
4954 {
4955 p = cmdbase + STRLEN(cmdbase);
4956 if (p > cmdbase && p[-1] == '"' && *cmd == '"')
4957 *--p = NUL;
4958 if (p > cmdbase && p[-1] == ')'
4959 && (*cmd =='(' || cmd[1] == '('))
4960 *--p = NUL;
4961 }
4962
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004963 newcmd = cmdbase;
4964 unescape_shellxquote(cmdbase, p_sxe);
4965
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004966 /*
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004967 * If creating new console, arguments are passed to the
4968 * 'cmd.exe' as-is. If it's not, arguments are not treated
4969 * correctly for current 'cmd.exe'. So unescape characters in
4970 * shellxescape except '|' for avoiding to be treated as
4971 * argument to them. Pass the arguments to sub-shell.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004972 */
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004973 if (flags != CREATE_NEW_CONSOLE)
4974 {
4975 char_u *subcmd;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004976 char_u *cmd_shell = mch_getenv("COMSPEC");
4977
4978 if (cmd_shell == NULL || *cmd_shell == NUL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004979 cmd_shell = (char_u *)default_shell();
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004980
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004981 subcmd = vim_strsave_escaped_ext(cmdbase,
4982 (char_u *)"|", '^', FALSE);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004983 if (subcmd != NULL)
4984 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004985 // make "cmd.exe /c arguments"
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004986 cmdlen = STRLEN(cmd_shell) + STRLEN(subcmd) + 5;
Bram Moolenaar18a4ba22019-05-24 19:39:03 +02004987 newcmd = alloc(cmdlen);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004988 if (newcmd != NULL)
4989 vim_snprintf((char *)newcmd, cmdlen, "%s /c %s",
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004990 cmd_shell, subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004991 else
4992 newcmd = cmdbase;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004993 vim_free(subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004994 }
4995 }
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004996
4997 /*
4998 * Now, start the command as a process, so that it doesn't
4999 * inherit our handles which causes unpleasant dangling swap
5000 * files if we exit before the spawned process
5001 */
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005002 if (vim_create_process((char *)newcmd, FALSE, flags,
5003 &si, &pi, NULL, NULL))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005004 x = 0;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01005005 else if (vim_shell_execute((char *)newcmd, n_show_cmd)
5006 > (HINSTANCE)32)
5007 x = 0;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005008 else
5009 {
5010 x = -1;
Bram Moolenaar4f974752019-02-17 17:44:42 +01005011#ifdef FEAT_GUI_MSWIN
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005012# ifdef VIMDLL
5013 if (gui.in_use)
5014# endif
Bram Moolenaarac78dd42022-01-02 19:25:26 +00005015 emsg(_(e_command_not_found));
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005016#endif
5017 }
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005018
5019 if (newcmd != cmdbase)
5020 vim_free(newcmd);
5021
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01005022 if (si.dwFlags == STARTF_USESTDHANDLES && si.hStdInput != NULL)
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005023 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005024 // Close the handle to \\.\NUL created above.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005025 CloseHandle(si.hStdInput);
5026 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01005027 // Close the handles to the subprocess, so that it goes away
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005028 CloseHandle(pi.hThread);
5029 CloseHandle(pi.hProcess);
5030 }
5031 else
5032 {
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005033 cmdlen =
Bram Moolenaar4f974752019-02-17 17:44:42 +01005034#ifdef FEAT_GUI_MSWIN
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02005035 ((gui.in_use || gui.starting) ?
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005036 (!s_dont_use_vimrun && p_stmp ?
5037 STRLEN(vimrun_path) : STRLEN(p_sh) + STRLEN(p_shcf))
5038 : 0) +
Bram Moolenaar071d4272004-06-13 20:20:40 +00005039#endif
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005040 STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10;
Bram Moolenaar0fde2902008-03-16 13:54:13 +00005041
Bram Moolenaar18a4ba22019-05-24 19:39:03 +02005042 newcmd = alloc(cmdlen);
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005043 if (newcmd != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005044 {
Bram Moolenaar4f974752019-02-17 17:44:42 +01005045#if defined(FEAT_GUI_MSWIN)
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005046 if (
5047# ifdef VIMDLL
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02005048 (gui.in_use || gui.starting) &&
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005049# endif
5050 need_vimrun_warning)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005051 {
Bram Moolenaar63e43442016-11-19 17:28:44 +01005052 char *msg = _("VIMRUN.EXE not found in your $PATH.\n"
5053 "External commands will not pause after completion.\n"
5054 "See :help win32-vimrun for more information.");
5055 char *title = _("Vim Warning");
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005056 WCHAR *wmsg = enc_to_utf16((char_u *)msg, NULL);
5057 WCHAR *wtitle = enc_to_utf16((char_u *)title, NULL);
Bram Moolenaar63e43442016-11-19 17:28:44 +01005058
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005059 if (wmsg != NULL && wtitle != NULL)
5060 MessageBoxW(NULL, wmsg, wtitle, MB_ICONWARNING);
5061 vim_free(wmsg);
5062 vim_free(wtitle);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005063 need_vimrun_warning = FALSE;
5064 }
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005065 if (
5066# ifdef VIMDLL
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02005067 (gui.in_use || gui.starting) &&
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005068# endif
5069 !s_dont_use_vimrun && p_stmp)
Bram Moolenaarfcc4d922019-05-24 13:32:36 +02005070 // Use vimrun to execute the command. It opens a console
5071 // window, which can be closed without killing Vim.
Bram Moolenaarcc448b32010-07-14 16:52:17 +02005072 vim_snprintf((char *)newcmd, cmdlen, "%s%s%s %s %s",
Bram Moolenaar071d4272004-06-13 20:20:40 +00005073 vimrun_path,
5074 (msg_silent != 0 || (options & SHELL_DOOUT))
5075 ? "-s " : "",
5076 p_sh, p_shcf, cmd);
Bram Moolenaarfcc4d922019-05-24 13:32:36 +02005077 else if (
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005078# ifdef VIMDLL
Bram Moolenaarfcc4d922019-05-24 13:32:36 +02005079 (gui.in_use || gui.starting) &&
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005080# endif
Bram Moolenaar0e6bfb92019-07-31 20:53:56 +02005081 s_dont_use_vimrun && STRCMP(p_shcf, "/c") == 0)
Bram Moolenaarfcc4d922019-05-24 13:32:36 +02005082 // workaround for the case that "vimrun" does not exist
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005083 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s %s %s",
5084 p_sh, p_shcf, p_sh, p_shcf, cmd);
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005085 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00005086#endif
Bram Moolenaarcc448b32010-07-14 16:52:17 +02005087 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s",
Bram Moolenaar0fde2902008-03-16 13:54:13 +00005088 p_sh, p_shcf, cmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005089 x = mch_system((char *)newcmd, options);
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005090 vim_free(newcmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005091 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005092 }
5093 }
5094
5095 if (tmode == TMODE_RAW)
Bram Moolenaar3b1f18f2020-05-16 23:15:08 +02005096 {
5097 // The shell may have messed with the mode, always set it.
5098 cur_tmode = TMODE_UNKNOWN;
Bram Moolenaar0f873732019-12-05 20:28:46 +01005099 settmode(TMODE_RAW); // set to raw mode
Bram Moolenaar3b1f18f2020-05-16 23:15:08 +02005100 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005101
Bram Moolenaar0f873732019-12-05 20:28:46 +01005102 // Print the return value, unless "vimrun" was used.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005103 if (x != 0 && !(options & SHELL_SILENT) && !emsg_silent
Bram Moolenaar4f974752019-02-17 17:44:42 +01005104#if defined(FEAT_GUI_MSWIN)
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02005105 && ((gui.in_use || gui.starting) ?
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005106 ((options & SHELL_DOOUT) || s_dont_use_vimrun || !p_stmp) : 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005107#endif
5108 )
5109 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005110 smsg(_("shell returned %d"), x);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005111 msg_putchar('\n');
5112 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005113 resettitle();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005114
5115 signal(SIGINT, SIG_DFL);
5116#if defined(__GNUC__) && !defined(__MINGW32__)
5117 signal(SIGKILL, SIG_DFL);
5118#else
5119 signal(SIGBREAK, SIG_DFL);
5120#endif
5121 signal(SIGILL, SIG_DFL);
5122 signal(SIGFPE, SIG_DFL);
5123 signal(SIGSEGV, SIG_DFL);
5124 signal(SIGTERM, SIG_DFL);
5125 signal(SIGABRT, SIG_DFL);
5126
5127 return x;
5128}
5129
Bram Moolenaar509ce2a2016-03-11 22:52:15 +01005130#if defined(FEAT_JOB_CHANNEL) || defined(PROTO)
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005131 static HANDLE
5132job_io_file_open(
Bram Moolenaar972c3b82017-01-12 21:44:49 +01005133 char_u *fname,
5134 DWORD dwDesiredAccess,
5135 DWORD dwShareMode,
5136 LPSECURITY_ATTRIBUTES lpSecurityAttributes,
5137 DWORD dwCreationDisposition,
5138 DWORD dwFlagsAndAttributes)
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005139{
5140 HANDLE h;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005141 WCHAR *wn;
Bram Moolenaara12a1612019-01-24 16:39:02 +01005142
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005143 wn = enc_to_utf16(fname, NULL);
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005144 if (wn == NULL)
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005145 return INVALID_HANDLE_VALUE;
5146
5147 h = CreateFileW(wn, dwDesiredAccess, dwShareMode,
5148 lpSecurityAttributes, dwCreationDisposition,
5149 dwFlagsAndAttributes, NULL);
5150 vim_free(wn);
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005151 return h;
5152}
5153
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005154/*
5155 * Turn the dictionary "env" into a NUL separated list that can be used as the
5156 * environment argument of vim_create_process().
5157 */
Bram Moolenaarba6febd2017-10-30 21:56:23 +01005158 void
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005159win32_build_env(dict_T *env, garray_T *gap, int is_terminal)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005160{
5161 hashitem_T *hi;
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005162 long_u todo = env != NULL ? env->dv_hashtab.ht_used : 0;
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005163 LPVOID base = GetEnvironmentStringsW();
5164
Bram Moolenaar0f873732019-12-05 20:28:46 +01005165 // for last \0
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005166 if (ga_grow(gap, 1) == FAIL)
5167 return;
5168
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005169 if (env != NULL)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005170 {
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005171 for (hi = env->dv_hashtab.ht_array; todo > 0; ++hi)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005172 {
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005173 if (!HASHITEM_EMPTY(hi))
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005174 {
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005175 typval_T *item = &dict_lookup(hi)->di_tv;
5176 WCHAR *wkey = enc_to_utf16((char_u *)hi->hi_key, NULL);
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005177 WCHAR *wval = enc_to_utf16(tv_get_string(item), NULL);
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005178 --todo;
5179 if (wkey != NULL && wval != NULL)
5180 {
5181 size_t n;
5182 size_t lkey = wcslen(wkey);
5183 size_t lval = wcslen(wval);
Bram Moolenaar60104f12017-08-14 23:25:04 +02005184
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005185 if (ga_grow(gap, (int)(lkey + lval + 2)) != OK)
5186 continue;
5187 for (n = 0; n < lkey; n++)
5188 *((WCHAR*)gap->ga_data + gap->ga_len++) = wkey[n];
5189 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'=';
5190 for (n = 0; n < lval; n++)
5191 *((WCHAR*)gap->ga_data + gap->ga_len++) = wval[n];
5192 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5193 }
Bram Moolenaarbdace832019-03-02 10:13:42 +01005194 vim_free(wkey);
5195 vim_free(wval);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005196 }
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005197 }
5198 }
5199
Bram Moolenaar355757a2020-02-10 22:06:32 +01005200 if (base)
5201 {
5202 WCHAR *p = (WCHAR*) base;
5203
5204 // for last \0
5205 if (ga_grow(gap, 1) == FAIL)
5206 return;
5207
5208 while (*p != 0 || *(p + 1) != 0)
5209 {
5210 if (ga_grow(gap, 1) == OK)
5211 *((WCHAR*)gap->ga_data + gap->ga_len++) = *p;
5212 p++;
5213 }
5214 FreeEnvironmentStrings(base);
5215 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5216 }
5217
Bram Moolenaar493359e2018-06-12 20:25:52 +02005218# if defined(FEAT_CLIENTSERVER) || defined(FEAT_TERMINAL)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005219 {
Bram Moolenaar493359e2018-06-12 20:25:52 +02005220# ifdef FEAT_CLIENTSERVER
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005221 char_u *servername = get_vim_var_str(VV_SEND_SERVER);
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005222 size_t servername_len = STRLEN(servername);
Bram Moolenaar493359e2018-06-12 20:25:52 +02005223# endif
5224# ifdef FEAT_TERMINAL
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005225 char_u *version = get_vim_var_str(VV_VERSION);
5226 size_t version_len = STRLEN(version);
Bram Moolenaar493359e2018-06-12 20:25:52 +02005227# endif
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005228 // size of "VIM_SERVERNAME=" and value,
5229 // plus "VIM_TERMINAL=" and value,
5230 // plus two terminating NULs
5231 size_t n = 0
Bram Moolenaar493359e2018-06-12 20:25:52 +02005232# ifdef FEAT_CLIENTSERVER
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005233 + 15 + servername_len
Bram Moolenaar493359e2018-06-12 20:25:52 +02005234# endif
5235# ifdef FEAT_TERMINAL
5236 + 13 + version_len + 2
5237# endif
5238 ;
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005239
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005240 if (ga_grow(gap, (int)n) == OK)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005241 {
Bram Moolenaar493359e2018-06-12 20:25:52 +02005242# ifdef FEAT_CLIENTSERVER
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005243 for (n = 0; n < 15; n++)
5244 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5245 (WCHAR)"VIM_SERVERNAME="[n];
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005246 for (n = 0; n < servername_len; n++)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005247 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5248 (WCHAR)servername[n];
5249 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
Bram Moolenaar493359e2018-06-12 20:25:52 +02005250# endif
5251# ifdef FEAT_TERMINAL
5252 if (is_terminal)
5253 {
5254 for (n = 0; n < 13; n++)
5255 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5256 (WCHAR)"VIM_TERMINAL="[n];
5257 for (n = 0; n < version_len; n++)
5258 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5259 (WCHAR)version[n];
5260 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5261 }
5262# endif
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005263 }
5264 }
Bram Moolenaar79c6b512018-06-12 21:11:12 +02005265# endif
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005266}
5267
Bram Moolenaarb091f302019-01-19 14:37:00 +01005268/*
5269 * Create a pair of pipes.
5270 * Return TRUE for success, FALSE for failure.
5271 */
5272 static BOOL
5273create_pipe_pair(HANDLE handles[2])
5274{
5275 static LONG s;
5276 char name[64];
5277 SECURITY_ATTRIBUTES sa;
5278
5279 sprintf(name, "\\\\?\\pipe\\vim-%08lx-%08lx",
5280 GetCurrentProcessId(),
5281 InterlockedIncrement(&s));
5282
5283 // Create named pipe. Max size of named pipe is 65535.
5284 handles[1] = CreateNamedPipe(
5285 name,
5286 PIPE_ACCESS_OUTBOUND | FILE_FLAG_OVERLAPPED,
5287 PIPE_TYPE_BYTE | PIPE_NOWAIT,
Bram Moolenaar24058382019-01-24 23:11:49 +01005288 1, MAX_NAMED_PIPE_SIZE, 0, 0, NULL);
Bram Moolenaarb091f302019-01-19 14:37:00 +01005289
5290 if (handles[1] == INVALID_HANDLE_VALUE)
5291 return FALSE;
5292
5293 sa.nLength = sizeof(sa);
5294 sa.bInheritHandle = TRUE;
5295 sa.lpSecurityDescriptor = NULL;
5296
5297 handles[0] = CreateFile(name,
5298 FILE_GENERIC_READ,
5299 FILE_SHARE_READ, &sa,
5300 OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
5301
5302 if (handles[0] == INVALID_HANDLE_VALUE)
5303 {
Bram Moolenaar6982f422019-02-16 16:48:01 +01005304 CloseHandle(handles[1]);
Bram Moolenaarb091f302019-01-19 14:37:00 +01005305 return FALSE;
5306 }
5307
5308 return TRUE;
5309}
5310
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005311 void
Bram Moolenaar5a1feb82017-07-22 18:04:08 +02005312mch_job_start(char *cmd, job_T *job, jobopt_T *options)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005313{
5314 STARTUPINFO si;
5315 PROCESS_INFORMATION pi;
Bram Moolenaar14207f42016-10-27 21:13:10 +02005316 HANDLE jo;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005317 SECURITY_ATTRIBUTES saAttr;
5318 channel_T *channel = NULL;
Bram Moolenaard8070362016-02-15 21:56:54 +01005319 HANDLE ifd[2];
5320 HANDLE ofd[2];
5321 HANDLE efd[2];
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005322 garray_T ga;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005323
5324 int use_null_for_in = options->jo_io[PART_IN] == JIO_NULL;
5325 int use_null_for_out = options->jo_io[PART_OUT] == JIO_NULL;
5326 int use_null_for_err = options->jo_io[PART_ERR] == JIO_NULL;
5327 int use_file_for_in = options->jo_io[PART_IN] == JIO_FILE;
5328 int use_file_for_out = options->jo_io[PART_OUT] == JIO_FILE;
5329 int use_file_for_err = options->jo_io[PART_ERR] == JIO_FILE;
5330 int use_out_for_err = options->jo_io[PART_ERR] == JIO_OUT;
5331
5332 if (use_out_for_err && use_null_for_out)
5333 use_null_for_err = TRUE;
Bram Moolenaard8070362016-02-15 21:56:54 +01005334
5335 ifd[0] = INVALID_HANDLE_VALUE;
5336 ifd[1] = INVALID_HANDLE_VALUE;
5337 ofd[0] = INVALID_HANDLE_VALUE;
5338 ofd[1] = INVALID_HANDLE_VALUE;
5339 efd[0] = INVALID_HANDLE_VALUE;
5340 efd[1] = INVALID_HANDLE_VALUE;
Bram Moolenaar04935fb2022-01-08 16:19:22 +00005341 ga_init2(&ga, sizeof(wchar_t), 500);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005342
Bram Moolenaar14207f42016-10-27 21:13:10 +02005343 jo = CreateJobObject(NULL, NULL);
5344 if (jo == NULL)
5345 {
5346 job->jv_status = JOB_FAILED;
5347 goto failed;
5348 }
5349
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005350 if (options->jo_env != NULL)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005351 win32_build_env(options->jo_env, &ga, FALSE);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005352
Bram Moolenaar76467df2016-02-12 19:30:26 +01005353 ZeroMemory(&pi, sizeof(pi));
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005354 ZeroMemory(&si, sizeof(si));
5355 si.cb = sizeof(si);
Bram Moolenaard8070362016-02-15 21:56:54 +01005356 si.dwFlags |= STARTF_USESHOWWINDOW;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005357 si.wShowWindow = SW_HIDE;
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005358
Bram Moolenaard8070362016-02-15 21:56:54 +01005359 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
5360 saAttr.bInheritHandle = TRUE;
5361 saAttr.lpSecurityDescriptor = NULL;
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005362
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005363 if (use_file_for_in)
5364 {
5365 char_u *fname = options->jo_io_name[PART_IN];
5366
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005367 ifd[0] = job_io_file_open(fname, GENERIC_READ,
5368 FILE_SHARE_READ | FILE_SHARE_WRITE,
5369 &saAttr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL);
5370 if (ifd[0] == INVALID_HANDLE_VALUE)
Bram Moolenaar94d01912016-03-08 13:48:51 +01005371 {
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00005372 semsg(_(e_cant_open_file_str), fname);
Bram Moolenaar94d01912016-03-08 13:48:51 +01005373 goto failed;
5374 }
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005375 }
Bram Moolenaarb091f302019-01-19 14:37:00 +01005376 else if (!use_null_for_in
5377 && (!create_pipe_pair(ifd)
5378 || !SetHandleInformation(ifd[1], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005379 goto failed;
5380
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005381 if (use_file_for_out)
5382 {
5383 char_u *fname = options->jo_io_name[PART_OUT];
5384
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005385 ofd[1] = job_io_file_open(fname, GENERIC_WRITE,
5386 FILE_SHARE_READ | FILE_SHARE_WRITE,
5387 &saAttr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL);
5388 if (ofd[1] == INVALID_HANDLE_VALUE)
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005389 {
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00005390 semsg(_(e_cant_open_file_str), fname);
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005391 goto failed;
5392 }
5393 }
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005394 else if (!use_null_for_out &&
5395 (!CreatePipe(&ofd[0], &ofd[1], &saAttr, 0)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005396 || !SetHandleInformation(ofd[0], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005397 goto failed;
5398
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005399 if (use_file_for_err)
5400 {
5401 char_u *fname = options->jo_io_name[PART_ERR];
5402
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005403 efd[1] = job_io_file_open(fname, GENERIC_WRITE,
5404 FILE_SHARE_READ | FILE_SHARE_WRITE,
5405 &saAttr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL);
5406 if (efd[1] == INVALID_HANDLE_VALUE)
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005407 {
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00005408 semsg(_(e_cant_open_file_str), fname);
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005409 goto failed;
5410 }
5411 }
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005412 else if (!use_out_for_err && !use_null_for_err &&
5413 (!CreatePipe(&efd[0], &efd[1], &saAttr, 0)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005414 || !SetHandleInformation(efd[0], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaard8070362016-02-15 21:56:54 +01005415 goto failed;
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005416
Bram Moolenaard8070362016-02-15 21:56:54 +01005417 si.dwFlags |= STARTF_USESTDHANDLES;
5418 si.hStdInput = ifd[0];
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005419 si.hStdOutput = ofd[1];
5420 si.hStdError = use_out_for_err ? ofd[1] : efd[1];
5421
5422 if (!use_null_for_in || !use_null_for_out || !use_null_for_err)
5423 {
Bram Moolenaarde279892016-03-11 22:19:44 +01005424 if (options->jo_set & JO_CHANNEL)
5425 {
5426 channel = options->jo_channel;
5427 if (channel != NULL)
5428 ++channel->ch_refcount;
5429 }
5430 else
5431 channel = add_channel();
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005432 if (channel == NULL)
5433 goto failed;
5434 }
Bram Moolenaard8070362016-02-15 21:56:54 +01005435
5436 if (!vim_create_process(cmd, TRUE,
Bram Moolenaar14207f42016-10-27 21:13:10 +02005437 CREATE_SUSPENDED |
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005438 CREATE_DEFAULT_ERROR_MODE |
5439 CREATE_NEW_PROCESS_GROUP |
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005440 CREATE_UNICODE_ENVIRONMENT |
Bram Moolenaar76467df2016-02-12 19:30:26 +01005441 CREATE_NEW_CONSOLE,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005442 &si, &pi,
5443 ga.ga_data,
5444 (char *)options->jo_cwd))
Bram Moolenaar76467df2016-02-12 19:30:26 +01005445 {
Bram Moolenaar14207f42016-10-27 21:13:10 +02005446 CloseHandle(jo);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005447 job->jv_status = JOB_FAILED;
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005448 goto failed;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005449 }
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005450
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005451 ga_clear(&ga);
5452
Bram Moolenaar14207f42016-10-27 21:13:10 +02005453 if (!AssignProcessToJobObject(jo, pi.hProcess))
5454 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005455 // if failing, switch the way to terminate
5456 // process with TerminateProcess.
Bram Moolenaar14207f42016-10-27 21:13:10 +02005457 CloseHandle(jo);
5458 jo = NULL;
5459 }
5460 ResumeThread(pi.hThread);
Bram Moolenaar75578a32016-03-10 16:33:31 +01005461 CloseHandle(pi.hThread);
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005462 job->jv_proc_info = pi;
Bram Moolenaar14207f42016-10-27 21:13:10 +02005463 job->jv_job_object = jo;
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005464 job->jv_status = JOB_STARTED;
5465
Bram Moolenaar641ad6c2016-09-01 18:32:11 +02005466 CloseHandle(ifd[0]);
5467 CloseHandle(ofd[1]);
5468 if (!use_out_for_err && !use_null_for_err)
Bram Moolenaarc25558b2016-03-03 21:02:23 +01005469 CloseHandle(efd[1]);
Bram Moolenaard8070362016-02-15 21:56:54 +01005470
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005471 job->jv_channel = channel;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005472 if (channel != NULL)
5473 {
5474 channel_set_pipes(channel,
5475 use_file_for_in || use_null_for_in
5476 ? INVALID_FD : (sock_T)ifd[1],
5477 use_file_for_out || use_null_for_out
5478 ? INVALID_FD : (sock_T)ofd[0],
5479 use_out_for_err || use_file_for_err || use_null_for_err
5480 ? INVALID_FD : (sock_T)efd[0]);
5481 channel_set_job(channel, job, options);
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005482 }
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005483 return;
5484
5485failed:
Bram Moolenaard8070362016-02-15 21:56:54 +01005486 CloseHandle(ifd[0]);
5487 CloseHandle(ofd[0]);
5488 CloseHandle(efd[0]);
5489 CloseHandle(ifd[1]);
5490 CloseHandle(ofd[1]);
5491 CloseHandle(efd[1]);
Bram Moolenaarde279892016-03-11 22:19:44 +01005492 channel_unref(channel);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005493 ga_clear(&ga);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005494}
5495
5496 char *
5497mch_job_status(job_T *job)
5498{
5499 DWORD dwExitCode = 0;
5500
Bram Moolenaar76467df2016-02-12 19:30:26 +01005501 if (!GetExitCodeProcess(job->jv_proc_info.hProcess, &dwExitCode)
5502 || dwExitCode != STILL_ACTIVE)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005503 {
Bram Moolenaareab089d2016-02-21 19:32:02 +01005504 job->jv_exitval = (int)dwExitCode;
Bram Moolenaar7df915d2016-11-17 17:25:32 +01005505 if (job->jv_status < JOB_ENDED)
Bram Moolenaar97792de2016-10-15 18:36:49 +02005506 {
5507 ch_log(job->jv_channel, "Job ended");
5508 job->jv_status = JOB_ENDED;
5509 }
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005510 return "dead";
5511 }
5512 return "run";
5513}
5514
Bram Moolenaar97792de2016-10-15 18:36:49 +02005515 job_T *
5516mch_detect_ended_job(job_T *job_list)
5517{
5518 HANDLE jobHandles[MAXIMUM_WAIT_OBJECTS];
5519 job_T *jobArray[MAXIMUM_WAIT_OBJECTS];
5520 job_T *job = job_list;
5521
5522 while (job != NULL)
5523 {
5524 DWORD n;
5525 DWORD result;
5526
5527 for (n = 0; n < MAXIMUM_WAIT_OBJECTS
5528 && job != NULL; job = job->jv_next)
5529 {
5530 if (job->jv_status == JOB_STARTED)
5531 {
5532 jobHandles[n] = job->jv_proc_info.hProcess;
5533 jobArray[n] = job;
5534 ++n;
5535 }
5536 }
5537 if (n == 0)
5538 continue;
5539 result = WaitForMultipleObjects(n, jobHandles, FALSE, 0);
5540 if (result >= WAIT_OBJECT_0 && result < WAIT_OBJECT_0 + n)
5541 {
5542 job_T *wait_job = jobArray[result - WAIT_OBJECT_0];
5543
5544 if (STRCMP(mch_job_status(wait_job), "dead") == 0)
5545 return wait_job;
5546 }
5547 }
5548 return NULL;
5549}
5550
Bram Moolenaarfb630902016-10-29 14:55:00 +02005551 static BOOL
5552terminate_all(HANDLE process, int code)
5553{
5554 PROCESSENTRY32 pe;
5555 HANDLE h = INVALID_HANDLE_VALUE;
5556 DWORD pid = GetProcessId(process);
5557
5558 if (pid != 0)
5559 {
5560 h = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
5561 if (h != INVALID_HANDLE_VALUE)
5562 {
5563 pe.dwSize = sizeof(PROCESSENTRY32);
5564 if (!Process32First(h, &pe))
5565 goto theend;
5566
5567 do
5568 {
5569 if (pe.th32ParentProcessID == pid)
5570 {
5571 HANDLE ph = OpenProcess(
5572 PROCESS_ALL_ACCESS, FALSE, pe.th32ProcessID);
5573 if (ph != NULL)
5574 {
5575 terminate_all(ph, code);
5576 CloseHandle(ph);
5577 }
5578 }
5579 } while (Process32Next(h, &pe));
5580
5581 CloseHandle(h);
5582 }
5583 }
5584
5585theend:
5586 return TerminateProcess(process, code);
5587}
5588
5589/*
5590 * Send a (deadly) signal to "job".
5591 * Return FAIL if it didn't work.
5592 */
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005593 int
Bram Moolenaar2d33e902017-08-11 16:31:54 +02005594mch_signal_job(job_T *job, char_u *how)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005595{
Bram Moolenaar923d9262016-02-25 20:56:01 +01005596 int ret;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005597
Bram Moolenaar923d9262016-02-25 20:56:01 +01005598 if (STRCMP(how, "term") == 0 || STRCMP(how, "kill") == 0 || *how == NUL)
Bram Moolenaar76467df2016-02-12 19:30:26 +01005599 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005600 // deadly signal
Bram Moolenaar14207f42016-10-27 21:13:10 +02005601 if (job->jv_job_object != NULL)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005602 {
5603 if (job->jv_channel != NULL && job->jv_channel->ch_anonymous_pipe)
5604 job->jv_channel->ch_killing = TRUE;
K.Takata135e1522022-01-29 15:27:58 +00005605 return TerminateJobObject(job->jv_job_object, (UINT)-1) ? OK : FAIL;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005606 }
Bram Moolenaarb3e195c2020-02-10 21:32:19 +01005607 return terminate_all(job->jv_proc_info.hProcess, -1) ? OK : FAIL;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005608 }
5609
5610 if (!AttachConsole(job->jv_proc_info.dwProcessId))
5611 return FAIL;
5612 ret = GenerateConsoleCtrlEvent(
Bram Moolenaar923d9262016-02-25 20:56:01 +01005613 STRCMP(how, "int") == 0 ? CTRL_C_EVENT : CTRL_BREAK_EVENT,
5614 job->jv_proc_info.dwProcessId)
5615 ? OK : FAIL;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005616 FreeConsole();
5617 return ret;
5618}
5619
5620/*
5621 * Clear the data related to "job".
5622 */
5623 void
5624mch_clear_job(job_T *job)
5625{
5626 if (job->jv_status != JOB_FAILED)
5627 {
Bram Moolenaar14207f42016-10-27 21:13:10 +02005628 if (job->jv_job_object != NULL)
5629 CloseHandle(job->jv_job_object);
Bram Moolenaar76467df2016-02-12 19:30:26 +01005630 CloseHandle(job->jv_proc_info.hProcess);
5631 }
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005632}
5633#endif
5634
Bram Moolenaar071d4272004-06-13 20:20:40 +00005635
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005636#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005637
5638/*
5639 * Start termcap mode
5640 */
5641 static void
5642termcap_mode_start(void)
5643{
5644 DWORD cmodein;
5645
5646 if (g_fTermcapMode)
5647 return;
5648
Bram Moolenaar81ccbf12020-04-15 21:05:30 +02005649 if (!p_rs && USE_VTP)
5650 vtp_printf("\033[?1049h");
5651
Bram Moolenaar071d4272004-06-13 20:20:40 +00005652 SaveConsoleBuffer(&g_cbNonTermcap);
5653
5654 if (g_cbTermcap.IsValid)
5655 {
5656 /*
5657 * We've been in termcap mode before. Restore certain screen
5658 * characteristics, including the buffer size and the window
5659 * size. Since we will be redrawing the screen, we don't need
5660 * to restore the actual contents of the buffer.
5661 */
5662 RestoreConsoleBuffer(&g_cbTermcap, FALSE);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005663 reset_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005664 SetConsoleWindowInfo(g_hConOut, TRUE, &g_cbTermcap.Info.srWindow);
5665 Rows = g_cbTermcap.Info.dwSize.Y;
5666 Columns = g_cbTermcap.Info.dwSize.X;
5667 }
5668 else
5669 {
5670 /*
5671 * This is our first time entering termcap mode. Clear the console
5672 * screen buffer, and resize the buffer to match the current window
5673 * size. We will use this as the size of our editing environment.
5674 */
5675 ClearConsoleBuffer(g_attrCurrent);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005676 set_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005677 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
5678 }
5679
Bram Moolenaar071d4272004-06-13 20:20:40 +00005680 resettitle();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005681
5682 GetConsoleMode(g_hConIn, &cmodein);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005683 if (g_fMouseActive)
Wez Furlong6ef5ab52021-05-30 19:29:41 +02005684 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00005685 cmodein |= ENABLE_MOUSE_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02005686 cmodein &= ~ENABLE_QUICK_EDIT_MODE;
5687 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005688 else
Wez Furlong6ef5ab52021-05-30 19:29:41 +02005689 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00005690 cmodein &= ~ENABLE_MOUSE_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02005691 cmodein |= g_cmodein & ENABLE_QUICK_EDIT_MODE;
5692 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005693 cmodein |= ENABLE_WINDOW_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02005694 SetConsoleMode(g_hConIn, cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005695
5696 redraw_later_clear();
5697 g_fTermcapMode = TRUE;
5698}
5699
5700
5701/*
5702 * End termcap mode
5703 */
5704 static void
5705termcap_mode_end(void)
5706{
5707 DWORD cmodein;
5708 ConsoleBuffer *cb;
5709 COORD coord;
5710 DWORD dwDummy;
5711
5712 if (!g_fTermcapMode)
5713 return;
5714
5715 SaveConsoleBuffer(&g_cbTermcap);
5716
5717 GetConsoleMode(g_hConIn, &cmodein);
5718 cmodein &= ~(ENABLE_MOUSE_INPUT | ENABLE_WINDOW_INPUT);
Wez Furlong6ef5ab52021-05-30 19:29:41 +02005719 cmodein |= g_cmodein & ENABLE_QUICK_EDIT_MODE;
5720 SetConsoleMode(g_hConIn, cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005721
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01005722# ifdef FEAT_RESTORE_ORIG_SCREEN
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01005723 cb = exiting ? &g_cbOrig : &g_cbNonTermcap;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01005724# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00005725 cb = &g_cbNonTermcap;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01005726# endif
Bram Moolenaar81ccbf12020-04-15 21:05:30 +02005727 RestoreConsoleBuffer(cb, p_rs);
Bram Moolenaardf543822020-01-30 11:53:59 +01005728 restore_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005729 SetConsoleCursorInfo(g_hConOut, &g_cci);
5730
5731 if (p_rs || exiting)
5732 {
5733 /*
5734 * Clear anything that happens to be on the current line.
5735 */
5736 coord.X = 0;
5737 coord.Y = (SHORT) (p_rs ? cb->Info.dwCursorPosition.Y : (Rows - 1));
5738 FillConsoleOutputCharacter(g_hConOut, ' ',
5739 cb->Info.dwSize.X, coord, &dwDummy);
5740 /*
5741 * The following is just for aesthetics. If we are exiting without
5742 * restoring the screen, then we want to have a prompt string
5743 * appear at the bottom line. However, the command interpreter
5744 * seems to always advance the cursor one line before displaying
5745 * the prompt string, which causes the screen to scroll. To
5746 * counter this, move the cursor up one line before exiting.
5747 */
5748 if (exiting && !p_rs)
5749 coord.Y--;
5750 /*
5751 * Position the cursor at the leftmost column of the desired row.
5752 */
Bram Moolenaar81ccbf12020-04-15 21:05:30 +02005753 SetConsoleCursorPosition(g_hConOut, coord);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005754 }
5755
Bram Moolenaar81ccbf12020-04-15 21:05:30 +02005756 if (!p_rs && USE_VTP)
Bram Moolenaar0afdcf82020-04-01 18:29:10 +02005757 vtp_printf("\033[?1049l");
5758
Bram Moolenaar071d4272004-06-13 20:20:40 +00005759 g_fTermcapMode = FALSE;
5760}
Bram Moolenaar0f873732019-12-05 20:28:46 +01005761#endif // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00005762
5763
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005764#if defined(FEAT_GUI_MSWIN) && !defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005765 void
5766mch_write(
Bram Moolenaar1266d672017-02-01 13:43:36 +01005767 char_u *s UNUSED,
5768 int len UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005769{
Bram Moolenaar0f873732019-12-05 20:28:46 +01005770 // never used
Bram Moolenaar071d4272004-06-13 20:20:40 +00005771}
5772
5773#else
5774
5775/*
5776 * clear `n' chars, starting from `coord'
5777 */
5778 static void
5779clear_chars(
5780 COORD coord,
5781 DWORD n)
5782{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005783 if (!USE_VTP)
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02005784 {
5785 DWORD dwDummy;
5786
5787 FillConsoleOutputCharacter(g_hConOut, ' ', n, coord, &dwDummy);
5788 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, n, coord,
5789 &dwDummy);
5790 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005791 else
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02005792 {
5793 set_console_color_rgb();
5794 gotoxy(coord.X + 1, coord.Y + 1);
5795 vtp_printf("\033[%dX", n);
5796 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005797}
5798
5799
5800/*
5801 * Clear the screen
5802 */
5803 static void
5804clear_screen(void)
5805{
5806 g_coord.X = g_coord.Y = 0;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005807
5808 if (!USE_VTP)
5809 clear_chars(g_coord, Rows * Columns);
5810 else
5811 {
5812 set_console_color_rgb();
5813 gotoxy(1, 1);
5814 vtp_printf("\033[2J");
5815 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005816}
5817
5818
5819/*
5820 * Clear to end of display
5821 */
5822 static void
5823clear_to_end_of_display(void)
5824{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005825 COORD save = g_coord;
5826
5827 if (!USE_VTP)
5828 clear_chars(g_coord, (Rows - g_coord.Y - 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005829 * Columns + (Columns - g_coord.X));
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005830 else
5831 {
5832 set_console_color_rgb();
5833 gotoxy(g_coord.X + 1, g_coord.Y + 1);
5834 vtp_printf("\033[0J");
5835
5836 gotoxy(save.X + 1, save.Y + 1);
5837 g_coord = save;
5838 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005839}
5840
5841
5842/*
5843 * Clear to end of line
5844 */
5845 static void
5846clear_to_end_of_line(void)
5847{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005848 COORD save = g_coord;
5849
5850 if (!USE_VTP)
5851 clear_chars(g_coord, Columns - g_coord.X);
5852 else
5853 {
5854 set_console_color_rgb();
5855 gotoxy(g_coord.X + 1, g_coord.Y + 1);
5856 vtp_printf("\033[0K");
5857
5858 gotoxy(save.X + 1, save.Y + 1);
5859 g_coord = save;
5860 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005861}
5862
5863
5864/*
5865 * Scroll the scroll region up by `cLines' lines
5866 */
5867 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005868scroll(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005869{
5870 COORD oldcoord = g_coord;
5871
5872 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
5873 delete_lines(cLines);
5874
5875 g_coord = oldcoord;
5876}
5877
5878
5879/*
5880 * Set the scroll region
5881 */
5882 static void
5883set_scroll_region(
5884 unsigned left,
5885 unsigned top,
5886 unsigned right,
5887 unsigned bottom)
5888{
5889 if (left >= right
5890 || top >= bottom
5891 || right > (unsigned) Columns - 1
5892 || bottom > (unsigned) Rows - 1)
5893 return;
5894
5895 g_srScrollRegion.Left = left;
5896 g_srScrollRegion.Top = top;
5897 g_srScrollRegion.Right = right;
5898 g_srScrollRegion.Bottom = bottom;
Bram Moolenaar6982f422019-02-16 16:48:01 +01005899}
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005900
Bram Moolenaar6982f422019-02-16 16:48:01 +01005901 static void
5902set_scroll_region_tb(
5903 unsigned top,
5904 unsigned bottom)
5905{
5906 if (top >= bottom || bottom > (unsigned)Rows - 1)
5907 return;
5908
5909 g_srScrollRegion.Top = top;
5910 g_srScrollRegion.Bottom = bottom;
5911}
5912
5913 static void
5914set_scroll_region_lr(
5915 unsigned left,
5916 unsigned right)
5917{
5918 if (left >= right || right > (unsigned)Columns - 1)
5919 return;
5920
5921 g_srScrollRegion.Left = left;
5922 g_srScrollRegion.Right = right;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005923}
5924
5925
5926/*
5927 * Insert `cLines' lines at the current cursor position
5928 */
5929 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005930insert_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005931{
Bram Moolenaar6982f422019-02-16 16:48:01 +01005932 SMALL_RECT source, clip;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005933 COORD dest;
5934 CHAR_INFO fill;
5935
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01005936 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
5937
Bram Moolenaar6982f422019-02-16 16:48:01 +01005938 dest.X = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005939 dest.Y = g_coord.Y + cLines;
5940
Bram Moolenaar6982f422019-02-16 16:48:01 +01005941 source.Left = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005942 source.Top = g_coord.Y;
5943 source.Right = g_srScrollRegion.Right;
5944 source.Bottom = g_srScrollRegion.Bottom - cLines;
5945
Bram Moolenaar6982f422019-02-16 16:48:01 +01005946 clip.Left = g_srScrollRegion.Left;
5947 clip.Top = g_coord.Y;
5948 clip.Right = g_srScrollRegion.Right;
5949 clip.Bottom = g_srScrollRegion.Bottom;
5950
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01005951 fill.Char.AsciiChar = ' ';
5952 if (!USE_VTP)
5953 fill.Attributes = g_attrCurrent;
5954 else
5955 fill.Attributes = g_attrDefault;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005956
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01005957 set_console_color_rgb();
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005958
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01005959 ScrollConsoleScreenBuffer(g_hConOut, &source, &clip, dest, &fill);
5960
Bram Moolenaar6982f422019-02-16 16:48:01 +01005961 // Here we have to deal with a win32 console flake: If the scroll
5962 // region looks like abc and we scroll c to a and fill with d we get
5963 // cbd... if we scroll block c one line at a time to a, we get cdd...
5964 // vim expects cdd consistently... So we have to deal with that
5965 // here... (this also occurs scrolling the same way in the other
5966 // direction).
Bram Moolenaar071d4272004-06-13 20:20:40 +00005967
5968 if (source.Bottom < dest.Y)
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 = clip.Top; i < dest.Y; ++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 = source.Top; i < dest.Y; ++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/*
5997 * Delete `cLines' lines at the current cursor position
5998 */
5999 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006000delete_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006001{
Bram Moolenaar6982f422019-02-16 16:48:01 +01006002 SMALL_RECT source, clip;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006003 COORD dest;
6004 CHAR_INFO fill;
6005 int nb;
6006
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006007 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
6008
Bram Moolenaar6982f422019-02-16 16:48:01 +01006009 dest.X = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006010 dest.Y = g_coord.Y;
6011
Bram Moolenaar6982f422019-02-16 16:48:01 +01006012 source.Left = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006013 source.Top = g_coord.Y + cLines;
6014 source.Right = g_srScrollRegion.Right;
6015 source.Bottom = g_srScrollRegion.Bottom;
6016
Bram Moolenaar6982f422019-02-16 16:48:01 +01006017 clip.Left = g_srScrollRegion.Left;
6018 clip.Top = g_coord.Y;
6019 clip.Right = g_srScrollRegion.Right;
6020 clip.Bottom = g_srScrollRegion.Bottom;
6021
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006022 fill.Char.AsciiChar = ' ';
6023 if (!USE_VTP)
6024 fill.Attributes = g_attrCurrent;
6025 else
6026 fill.Attributes = g_attrDefault;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006027
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006028 set_console_color_rgb();
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006029
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006030 ScrollConsoleScreenBuffer(g_hConOut, &source, &clip, dest, &fill);
6031
Bram Moolenaar6982f422019-02-16 16:48:01 +01006032 // Here we have to deal with a win32 console flake; See insert_lines()
6033 // above.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006034
6035 nb = dest.Y + (source.Bottom - source.Top) + 1;
6036
6037 if (nb < source.Top)
6038 {
6039 COORD coord;
Bram Moolenaar6982f422019-02-16 16:48:01 +01006040 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006041
Bram Moolenaar6982f422019-02-16 16:48:01 +01006042 coord.X = source.Left;
6043 for (i = nb; i < clip.Bottom; ++i)
6044 {
6045 coord.Y = i;
6046 clear_chars(coord, source.Right - source.Left + 1);
6047 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006048 }
Bram Moolenaar06b7b582020-05-30 17:49:25 +02006049
6050 if (USE_WT)
6051 {
6052 COORD coord;
6053 int i;
6054
6055 coord.X = source.Left;
6056 for (i = nb; i <= source.Bottom; ++i)
6057 {
6058 coord.Y = i;
6059 clear_chars(coord, source.Right - source.Left + 1);
6060 }
6061 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006062}
6063
6064
6065/*
Bram Moolenaar2313b612019-09-27 14:14:32 +02006066 * Set the cursor position to (x,y) (1-based).
Bram Moolenaar071d4272004-06-13 20:20:40 +00006067 */
6068 static void
6069gotoxy(
6070 unsigned x,
6071 unsigned y)
6072{
6073 if (x < 1 || x > (unsigned)Columns || y < 1 || y > (unsigned)Rows)
6074 return;
6075
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006076 if (!USE_VTP)
Bram Moolenaar2313b612019-09-27 14:14:32 +02006077 {
Bram Moolenaar82e743c2020-03-26 15:39:53 +01006078 // There are reports of double-width characters not displayed
6079 // correctly. This workaround should fix it, similar to how it's done
6080 // for VTP.
6081 g_coord.X = 0;
6082 SetConsoleCursorPosition(g_hConOut, g_coord);
6083
Bram Moolenaar2313b612019-09-27 14:14:32 +02006084 // external cursor coords are 1-based; internal are 0-based
6085 g_coord.X = x - 1;
6086 g_coord.Y = y - 1;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006087 SetConsoleCursorPosition(g_hConOut, g_coord);
Bram Moolenaar2313b612019-09-27 14:14:32 +02006088 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006089 else
Bram Moolenaar2313b612019-09-27 14:14:32 +02006090 {
6091 // Move the cursor to the left edge of the screen to prevent screen
Bram Moolenaara1299742019-10-10 16:36:00 +02006092 // destruction. Insider build bug. Always enabled because it's cheap
6093 // and avoids mistakes with recognizing the build.
6094 vtp_printf("\033[%d;%dH", g_coord.Y + 1, 1);
Bram Moolenaar2313b612019-09-27 14:14:32 +02006095
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006096 vtp_printf("\033[%d;%dH", y, x);
Bram Moolenaar2313b612019-09-27 14:14:32 +02006097
6098 g_coord.X = x - 1;
6099 g_coord.Y = y - 1;
6100 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006101}
6102
6103
6104/*
6105 * Set the current text attribute = (foreground | background)
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006106 * See ../runtime/doc/os_win32.txt for the numbers.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006107 */
6108 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006109textattr(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006110{
Bram Moolenaar6383b922015-03-24 17:12:19 +01006111 g_attrCurrent = wAttr & 0xff;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006112
6113 SetConsoleTextAttribute(g_hConOut, wAttr);
6114}
6115
6116
6117 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006118textcolor(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006119{
Bram Moolenaar6383b922015-03-24 17:12:19 +01006120 g_attrCurrent = (g_attrCurrent & 0xf0) + (wAttr & 0x0f);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006121
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006122 if (!USE_VTP)
6123 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
6124 else
6125 vtp_sgr_bulk(wAttr);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006126}
6127
6128
6129 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006130textbackground(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006131{
Bram Moolenaar6383b922015-03-24 17:12:19 +01006132 g_attrCurrent = (g_attrCurrent & 0x0f) + ((wAttr & 0x0f) << 4);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006133
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006134 if (!USE_VTP)
6135 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
6136 else
6137 vtp_sgr_bulk(wAttr);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006138}
6139
6140
6141/*
6142 * restore the default text attribute (whatever we started with)
6143 */
6144 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006145normvideo(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006146{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006147 if (!USE_VTP)
6148 textattr(g_attrDefault);
6149 else
6150 vtp_sgr_bulk(0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006151}
6152
6153
6154static WORD g_attrPreStandout = 0;
6155
6156/*
6157 * Make the text standout, by brightening it
6158 */
6159 static void
6160standout(void)
6161{
6162 g_attrPreStandout = g_attrCurrent;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006163
Bram Moolenaar071d4272004-06-13 20:20:40 +00006164 textattr((WORD) (g_attrCurrent|FOREGROUND_INTENSITY|BACKGROUND_INTENSITY));
6165}
6166
6167
6168/*
6169 * Turn off standout mode
6170 */
6171 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006172standend(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006173{
6174 if (g_attrPreStandout)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006175 textattr(g_attrPreStandout);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006176
6177 g_attrPreStandout = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006178}
6179
6180
6181/*
Bram Moolenaarff1d0d42007-05-10 17:24:16 +00006182 * Set normal fg/bg color, based on T_ME. Called when t_me has been set.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006183 */
6184 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006185mch_set_normal_colors(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006186{
6187 char_u *p;
6188 int n;
6189
6190 cterm_normal_fg_color = (g_attrDefault & 0xf) + 1;
6191 cterm_normal_bg_color = ((g_attrDefault >> 4) & 0xf) + 1;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006192 if (
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006193# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006194 !p_tgc &&
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006195# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006196 T_ME[0] == ESC && T_ME[1] == '|')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006197 {
6198 p = T_ME + 2;
6199 n = getdigits(&p);
6200 if (*p == 'm' && n > 0)
6201 {
6202 cterm_normal_fg_color = (n & 0xf) + 1;
6203 cterm_normal_bg_color = ((n >> 4) & 0xf) + 1;
6204 }
6205 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006206# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006207 cterm_normal_fg_gui_color = INVALCOLOR;
6208 cterm_normal_bg_gui_color = INVALCOLOR;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006209# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006210}
6211
6212
6213/*
6214 * visual bell: flash the screen
6215 */
6216 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006217visual_bell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006218{
6219 COORD coordOrigin = {0, 0};
6220 WORD attrFlash = ~g_attrCurrent & 0xff;
6221
6222 DWORD dwDummy;
Bram Moolenaarc799fe22019-05-28 23:08:19 +02006223 LPWORD oldattrs = ALLOC_MULT(WORD, Rows * Columns);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006224
6225 if (oldattrs == NULL)
6226 return;
6227 ReadConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
6228 coordOrigin, &dwDummy);
6229 FillConsoleOutputAttribute(g_hConOut, attrFlash, Rows * Columns,
6230 coordOrigin, &dwDummy);
6231
Bram Moolenaar0f873732019-12-05 20:28:46 +01006232 Sleep(15); // wait for 15 msec
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006233 if (!USE_VTP)
6234 WriteConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
Bram Moolenaar071d4272004-06-13 20:20:40 +00006235 coordOrigin, &dwDummy);
6236 vim_free(oldattrs);
6237}
6238
6239
6240/*
6241 * Make the cursor visible or invisible
6242 */
6243 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006244cursor_visible(BOOL fVisible)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006245{
6246 s_cursor_visible = fVisible;
Bram Moolenaar2695de62020-04-17 21:13:01 +02006247
6248 if (USE_VTP)
6249 vtp_printf("\033[?25%c", fVisible ? 'h' : 'l');
6250
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006251# ifdef MCH_CURSOR_SHAPE
Bram Moolenaar071d4272004-06-13 20:20:40 +00006252 mch_update_cursor();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006253# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006254}
6255
6256
6257/*
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02006258 * Write "cbToWrite" bytes in `pchBuf' to the screen.
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006259 * Returns the number of bytes actually written (at least one).
Bram Moolenaar071d4272004-06-13 20:20:40 +00006260 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006261 static DWORD
Bram Moolenaar071d4272004-06-13 20:20:40 +00006262write_chars(
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006263 char_u *pchBuf,
6264 DWORD cbToWrite)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006265{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006266 COORD coord = g_coord;
6267 DWORD written;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006268 DWORD n, cchwritten;
6269 static DWORD cells;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006270 static WCHAR *unicodebuf = NULL;
6271 static int unibuflen = 0;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006272 static int length;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006273 int cp = enc_utf8 ? CP_UTF8 : enc_codepage;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006274 static WCHAR *utf8spbuf = NULL;
6275 static int utf8splength;
6276 static DWORD utf8spcells;
6277 static WCHAR **utf8usingbuf = &unicodebuf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006278
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006279 if (cbToWrite != 1 || *pchBuf != ' ' || !enc_utf8)
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006280 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006281 utf8usingbuf = &unicodebuf;
6282 do
6283 {
6284 length = MultiByteToWideChar(cp, 0, (LPCSTR)pchBuf, cbToWrite,
6285 unicodebuf, unibuflen);
6286 if (length && length <= unibuflen)
6287 break;
6288 vim_free(unicodebuf);
6289 unicodebuf = length ? LALLOC_MULT(WCHAR, length) : NULL;
6290 unibuflen = unibuflen ? 0 : length;
6291 } while(1);
6292 cells = mb_string2cells(pchBuf, cbToWrite);
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006293 }
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006294 else // cbToWrite == 1 && *pchBuf == ' ' && enc_utf8
6295 {
6296 if (utf8usingbuf != &utf8spbuf)
6297 {
6298 if (utf8spbuf == NULL)
6299 {
6300 cells = mb_string2cells((char_u *)" ", 1);
6301 length = MultiByteToWideChar(CP_UTF8, 0, " ", 1, NULL, 0);
6302 utf8spbuf = LALLOC_MULT(WCHAR, length);
6303 if (utf8spbuf != NULL)
6304 {
6305 MultiByteToWideChar(CP_UTF8, 0, " ", 1, utf8spbuf, length);
6306 utf8usingbuf = &utf8spbuf;
6307 utf8splength = length;
6308 utf8spcells = cells;
6309 }
6310 }
6311 else
6312 {
6313 utf8usingbuf = &utf8spbuf;
6314 length = utf8splength;
6315 cells = utf8spcells;
6316 }
6317 }
6318 }
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006319
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006320 if (!USE_VTP)
6321 {
6322 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, cells,
6323 coord, &written);
6324 // When writing fails or didn't write a single character, pretend one
6325 // character was written, otherwise we get stuck.
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006326 if (WriteConsoleOutputCharacterW(g_hConOut, *utf8usingbuf, length,
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006327 coord, &cchwritten) == 0
6328 || cchwritten == 0 || cchwritten == (DWORD)-1)
6329 cchwritten = 1;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006330 }
6331 else
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006332 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006333 if (WriteConsoleW(g_hConOut, *utf8usingbuf, length, &cchwritten,
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006334 NULL) == 0 || cchwritten == 0)
6335 cchwritten = 1;
6336 }
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006337
K.Takata135e1522022-01-29 15:27:58 +00006338 if (cchwritten == (DWORD)length)
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006339 {
6340 written = cbToWrite;
6341 g_coord.X += (SHORT)cells;
6342 }
6343 else
6344 {
6345 char_u *p = pchBuf;
6346 for (n = 0; n < cchwritten; n++)
6347 MB_CPTR_ADV(p);
6348 written = p - pchBuf;
6349 g_coord.X += (SHORT)mb_string2cells(pchBuf, written);
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006350 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006351
6352 while (g_coord.X > g_srScrollRegion.Right)
6353 {
6354 g_coord.X -= (SHORT) Columns;
6355 if (g_coord.Y < g_srScrollRegion.Bottom)
6356 g_coord.Y++;
6357 }
6358
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006359 // Cursor under VTP is always in the correct position, no need to reset.
6360 if (!USE_VTP)
6361 gotoxy(g_coord.X + 1, g_coord.Y + 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006362
6363 return written;
6364}
6365
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006366 static char_u *
6367get_seq(
6368 int *args,
6369 int *count,
6370 char_u *head)
6371{
6372 int argc;
6373 char_u *p;
6374
6375 if (head == NULL || *head != '\033')
6376 return NULL;
6377
6378 argc = 0;
6379 p = head;
6380 ++p;
6381 do
6382 {
6383 ++p;
6384 args[argc] = getdigits(&p);
6385 argc += (argc < 15) ? 1 : 0;
6386 } while (*p == ';');
6387 *count = argc;
6388
6389 return p;
6390}
6391
6392 static char_u *
6393get_sgr(
6394 int *args,
6395 int *count,
6396 char_u *head)
6397{
6398 char_u *p = get_seq(args, count, head);
6399
6400 return (p && *p == 'm') ? ++p : NULL;
6401}
6402
6403/*
6404 * Pointer to next if SGR (^[[n;2;*;*;*m), NULL otherwise.
6405 */
6406 static char_u *
6407sgrn2(
6408 char_u *head,
6409 int n)
6410{
6411 int argc;
6412 int args[16];
6413 char_u *p = get_sgr(args, &argc, head);
6414
6415 return p && argc == 5 && args[0] == n && args[1] == 2 ? p : NULL;
6416}
6417
6418/*
6419 * Pointer to next if SGR(^[[nm)<space>ESC, NULL otherwise.
6420 */
6421 static char_u *
6422sgrnc(
6423 char_u *head,
6424 int n)
6425{
6426 int argc;
6427 int args[16];
6428 char_u *p = get_sgr(args, &argc, head);
6429
6430 return p && argc == 1 && args[0] == n && (p = skipwhite(p)) && *p == '\033'
6431 ? p : NULL;
6432}
6433
6434 static char_u *
6435skipblank(char_u *q)
6436{
6437 char_u *p = q;
6438
6439 while (*p == ' ' || *p == '\t' || *p == '\n' || *p == '\r')
6440 ++p;
6441 return p;
6442}
6443
6444/*
6445 * Pointer to the next if any whitespace that may follow SGR is ESC, otherwise
6446 * NULL.
6447 */
6448 static char_u *
6449sgrn2c(
6450 char_u *head,
6451 int n)
6452{
6453 char_u *p = sgrn2(head, n);
6454
6455 return p && *p != NUL && (p = skipblank(p)) && *p == '\033' ? p : NULL;
6456}
6457
6458/*
6459 * If there is only a newline between the sequence immediately following it,
6460 * a pointer to the character following the newline is returned.
6461 * Otherwise NULL.
6462 */
6463 static char_u *
6464sgrn2cn(
6465 char_u *head,
6466 int n)
6467{
6468 char_u *p = sgrn2(head, n);
6469
6470 return p && p[0] == 0x0a && p[1] == '\033' ? ++p : NULL;
6471}
Bram Moolenaar071d4272004-06-13 20:20:40 +00006472
6473/*
6474 * mch_write(): write the output buffer to the screen, translating ESC
6475 * sequences into calls to console output routines.
6476 */
6477 void
6478mch_write(
6479 char_u *s,
6480 int len)
6481{
Bram Moolenaard23f8bd2021-04-21 11:30:48 +02006482 char_u *end = s + len;
6483
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006484# ifdef VIMDLL
6485 if (gui.in_use)
6486 return;
6487# endif
6488
Bram Moolenaar071d4272004-06-13 20:20:40 +00006489 if (!term_console)
6490 {
6491 write(1, s, (unsigned)len);
6492 return;
6493 }
6494
Bram Moolenaar0f873732019-12-05 20:28:46 +01006495 // translate ESC | sequences into faked bios calls
Bram Moolenaar071d4272004-06-13 20:20:40 +00006496 while (len--)
6497 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006498 int prefix = -1;
6499 char_u ch;
6500
6501 // While processing a sequence, on rare occasions it seems that another
6502 // sequence may be inserted asynchronously.
6503 if (len < 0)
6504 {
Bram Moolenaara4d158b2022-08-14 14:17:45 +01006505 redraw_all_later(UPD_CLEAR);
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006506 return;
6507 }
6508
Bram Moolenaard23f8bd2021-04-21 11:30:48 +02006509 while (s + ++prefix < end)
6510 {
6511 ch = s[prefix];
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006512 if (ch <= 0x1e && !(ch != '\n' && ch != '\r' && ch != '\b'
6513 && ch != '\a' && ch != '\033'))
6514 break;
Bram Moolenaard23f8bd2021-04-21 11:30:48 +02006515 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006516
6517 if (p_wd)
6518 {
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02006519 WaitForChar(p_wd, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006520 if (prefix != 0)
6521 prefix = 1;
6522 }
6523
6524 if (prefix != 0)
6525 {
6526 DWORD nWritten;
6527
6528 nWritten = write_chars(s, prefix);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006529# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006530 if (fdDump)
6531 {
6532 fputc('>', fdDump);
6533 fwrite(s, sizeof(char_u), nWritten, fdDump);
6534 fputs("<\n", fdDump);
6535 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006536# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006537 len -= (nWritten - 1);
6538 s += nWritten;
6539 }
6540 else if (s[0] == '\n')
6541 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006542 // \n, newline: go to the beginning of the next line or scroll
Bram Moolenaar071d4272004-06-13 20:20:40 +00006543 if (g_coord.Y == g_srScrollRegion.Bottom)
6544 {
6545 scroll(1);
6546 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Bottom + 1);
6547 }
6548 else
6549 {
6550 gotoxy(g_srScrollRegion.Left + 1, g_coord.Y + 2);
6551 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006552# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006553 if (fdDump)
6554 fputs("\\n\n", fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006555# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006556 s++;
6557 }
6558 else if (s[0] == '\r')
6559 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006560 // \r, carriage return: go to beginning of line
Bram Moolenaar071d4272004-06-13 20:20:40 +00006561 gotoxy(g_srScrollRegion.Left+1, g_coord.Y + 1);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006562# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006563 if (fdDump)
6564 fputs("\\r\n", fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006565# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006566 s++;
6567 }
6568 else if (s[0] == '\b')
6569 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006570 // \b, backspace: move cursor one position left
Bram Moolenaar071d4272004-06-13 20:20:40 +00006571 if (g_coord.X > g_srScrollRegion.Left)
6572 g_coord.X--;
6573 else if (g_coord.Y > g_srScrollRegion.Top)
6574 {
6575 g_coord.X = g_srScrollRegion.Right;
6576 g_coord.Y--;
6577 }
6578 gotoxy(g_coord.X + 1, g_coord.Y + 1);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006579# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006580 if (fdDump)
6581 fputs("\\b\n", fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006582# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006583 s++;
6584 }
6585 else if (s[0] == '\a')
6586 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006587 // \a, bell
Bram Moolenaar071d4272004-06-13 20:20:40 +00006588 MessageBeep(0xFFFFFFFF);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006589# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006590 if (fdDump)
6591 fputs("\\a\n", fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006592# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006593 s++;
6594 }
6595 else if (s[0] == ESC && len >= 3-1 && s[1] == '|')
6596 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006597# ifdef MCH_WRITE_DUMP
Bram Moolenaarc0197e22004-09-13 20:26:32 +00006598 char_u *old_s = s;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006599# endif
Bram Moolenaarc0197e22004-09-13 20:26:32 +00006600 char_u *p;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006601 int arg1 = 0, arg2 = 0, argc = 0, args[16];
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006602 char_u *sp;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006603
6604 switch (s[2])
6605 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006606 case '0': case '1': case '2': case '3': case '4':
6607 case '5': case '6': case '7': case '8': case '9':
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006608 if (*(p = get_seq(args, &argc, s)) != 'm')
6609 goto notsgr;
6610
6611 p = s;
6612
6613 // Handling frequent optional sequences. Output to the screen
6614 // takes too long, so do not output as much as possible.
6615
6616 // If resetFG,FG,BG,<cr>,BG,FG are connected, the preceding
6617 // resetFG,FG,BG are omitted.
6618 if (sgrn2(sgrn2(sgrn2cn(sgrn2(sgrnc(p, 39), 38), 48), 48), 38))
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006619 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006620 p = sgrn2(sgrn2(sgrnc(p, 39), 38), 48);
6621 len = len + 1 - (int)(p - s);
6622 s = p;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006623 break;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006624 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006625
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006626 // If FG,BG,BG,FG of SGR are connected, the first FG can be
6627 // omitted.
6628 if (sgrn2(sgrn2(sgrn2c((sp = sgrn2(p, 38)), 48), 48), 38))
6629 p = sp;
6630
6631 // If FG,BG,FG,BG of SGR are connected, the first FG can be
6632 // omitted.
6633 if (sgrn2(sgrn2(sgrn2c((sp = sgrn2(p, 38)), 48), 38), 48))
6634 p = sp;
6635
6636 // If BG,BG of SGR are connected, the first BG can be omitted.
6637 if (sgrn2((sp = sgrn2(p, 48)), 48))
6638 p = sp;
6639
6640 // If restoreFG and FG are connected, the restoreFG can be
Bram Moolenaar9f1983d2022-05-12 20:35:35 +01006641 // omitted.
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006642 if (sgrn2((sp = sgrnc(p, 39)), 38))
6643 p = sp;
6644
6645 p = get_seq(args, &argc, p);
6646
6647notsgr:
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006648 arg1 = args[0];
6649 arg2 = args[1];
6650 if (*p == 'm')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006651 {
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006652 if (argc == 1 && args[0] == 0)
6653 normvideo();
6654 else if (argc == 1)
6655 {
6656 if (USE_VTP)
6657 textcolor((WORD) arg1);
6658 else
6659 textattr((WORD) arg1);
6660 }
6661 else if (USE_VTP)
6662 vtp_sgr_bulks(argc, args);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006663 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006664 else if (argc == 2 && *p == 'H')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006665 {
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006666 gotoxy(arg2, arg1);
6667 }
6668 else if (argc == 2 && *p == 'r')
6669 {
6670 set_scroll_region(0, arg1 - 1, Columns - 1, arg2 - 1);
6671 }
Bram Moolenaar6982f422019-02-16 16:48:01 +01006672 else if (argc == 2 && *p == 'R')
6673 {
6674 set_scroll_region_tb(arg1, arg2);
6675 }
6676 else if (argc == 2 && *p == 'V')
6677 {
6678 set_scroll_region_lr(arg1, arg2);
6679 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006680 else if (argc == 1 && *p == 'A')
6681 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006682 gotoxy(g_coord.X + 1,
6683 max(g_srScrollRegion.Top, g_coord.Y - arg1) + 1);
6684 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006685 else if (argc == 1 && *p == 'b')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006686 {
6687 textbackground((WORD) arg1);
6688 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006689 else if (argc == 1 && *p == 'C')
6690 {
6691 gotoxy(min(g_srScrollRegion.Right, g_coord.X + arg1) + 1,
6692 g_coord.Y + 1);
6693 }
6694 else if (argc == 1 && *p == 'f')
6695 {
6696 textcolor((WORD) arg1);
6697 }
6698 else if (argc == 1 && *p == 'H')
6699 {
6700 gotoxy(1, arg1);
6701 }
6702 else if (argc == 1 && *p == 'L')
6703 {
6704 insert_lines(arg1);
6705 }
6706 else if (argc == 1 && *p == 'M')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006707 {
6708 delete_lines(arg1);
6709 }
6710
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006711 len -= (int)(p - s);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006712 s = p + 1;
6713 break;
6714
Bram Moolenaar071d4272004-06-13 20:20:40 +00006715 case 'A':
Bram Moolenaar071d4272004-06-13 20:20:40 +00006716 gotoxy(g_coord.X + 1,
6717 max(g_srScrollRegion.Top, g_coord.Y - 1) + 1);
6718 goto got3;
6719
6720 case 'B':
6721 visual_bell();
6722 goto got3;
6723
6724 case 'C':
Bram Moolenaar071d4272004-06-13 20:20:40 +00006725 gotoxy(min(g_srScrollRegion.Right, g_coord.X + 1) + 1,
6726 g_coord.Y + 1);
6727 goto got3;
6728
6729 case 'E':
6730 termcap_mode_end();
6731 goto got3;
6732
6733 case 'F':
6734 standout();
6735 goto got3;
6736
6737 case 'f':
6738 standend();
6739 goto got3;
6740
6741 case 'H':
6742 gotoxy(1, 1);
6743 goto got3;
6744
6745 case 'j':
6746 clear_to_end_of_display();
6747 goto got3;
6748
6749 case 'J':
6750 clear_screen();
6751 goto got3;
6752
6753 case 'K':
6754 clear_to_end_of_line();
6755 goto got3;
6756
6757 case 'L':
6758 insert_lines(1);
6759 goto got3;
6760
6761 case 'M':
6762 delete_lines(1);
6763 goto got3;
6764
6765 case 'S':
6766 termcap_mode_start();
6767 goto got3;
6768
6769 case 'V':
6770 cursor_visible(TRUE);
6771 goto got3;
6772
6773 case 'v':
6774 cursor_visible(FALSE);
6775 goto got3;
6776
6777 got3:
6778 s += 3;
6779 len -= 2;
6780 }
6781
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006782# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006783 if (fdDump)
6784 {
6785 fputs("ESC | ", fdDump);
6786 fwrite(old_s + 2, sizeof(char_u), s - old_s - 2, fdDump);
6787 fputc('\n', fdDump);
6788 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006789# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006790 }
K.Takatadf5320c2022-09-01 13:20:16 +01006791 else if (s[0] == ESC && len >= 3-1 && s[1] == '[')
6792 {
6793 int l = 2;
6794
6795 if (isdigit(s[l]))
6796 l++;
6797 if (s[l] == ' ' && s[l + 1] == 'q')
6798 {
6799 // DECSCUSR (cursor style) sequences
6800 if (USE_VTP || USE_WT)
6801 vtp_printf("%.*s", l + 2, s); // Pass through
6802 s += l + 2;
6803 len -= l + 1;
6804 }
6805 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006806 else
6807 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006808 // Write a single character
Bram Moolenaar071d4272004-06-13 20:20:40 +00006809 DWORD nWritten;
6810
6811 nWritten = write_chars(s, 1);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006812# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006813 if (fdDump)
6814 {
6815 fputc('>', fdDump);
6816 fwrite(s, sizeof(char_u), nWritten, fdDump);
6817 fputs("<\n", fdDump);
6818 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006819# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006820
6821 len -= (nWritten - 1);
6822 s += nWritten;
6823 }
6824 }
6825
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006826# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006827 if (fdDump)
6828 fflush(fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006829# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006830}
6831
Bram Moolenaar0f873732019-12-05 20:28:46 +01006832#endif // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00006833
6834
6835/*
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01006836 * Delay for "msec" milliseconds.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006837 */
6838 void
6839mch_delay(
6840 long msec,
Bram Moolenaar0981c872020-08-23 14:28:37 +02006841 int flags UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006842{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006843#if defined(FEAT_GUI_MSWIN) && !defined(VIMDLL)
Bram Moolenaar0f873732019-12-05 20:28:46 +01006844 Sleep((int)msec); // never wait for input
6845#else // Console
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006846# ifdef VIMDLL
6847 if (gui.in_use)
6848 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006849 Sleep((int)msec); // never wait for input
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006850 return;
6851 }
6852# endif
Bram Moolenaar0981c872020-08-23 14:28:37 +02006853 if (flags & MCH_DELAY_IGNOREINPUT)
Bram Moolenaar325b7a22004-07-05 15:58:32 +00006854# ifdef FEAT_MZSCHEME
6855 if (mzthreads_allowed() && p_mzq > 0 && msec > p_mzq)
6856 {
6857 int towait = p_mzq;
6858
Bram Moolenaar0f873732019-12-05 20:28:46 +01006859 // if msec is large enough, wait by portions in p_mzq
Bram Moolenaar325b7a22004-07-05 15:58:32 +00006860 while (msec > 0)
6861 {
6862 mzvim_check_threads();
6863 if (msec < towait)
6864 towait = msec;
6865 Sleep(towait);
6866 msec -= towait;
6867 }
6868 }
6869 else
6870# endif
6871 Sleep((int)msec);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006872 else
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02006873 WaitForChar(msec, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006874#endif
6875}
6876
6877
6878/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01006879 * This version of remove is not scared by a readonly (backup) file.
6880 * This can also remove a symbolic link like Unix.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006881 * Return 0 for success, -1 for failure.
6882 */
6883 int
6884mch_remove(char_u *name)
6885{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006886 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006887 int n;
6888
Bram Moolenaar203258c2016-01-17 22:15:16 +01006889 /*
6890 * On Windows, deleting a directory's symbolic link is done by
6891 * RemoveDirectory(): mch_rmdir. It seems unnatural, but it is fact.
6892 */
6893 if (mch_isdir(name) && mch_is_symbolic_link(name))
6894 return mch_rmdir(name);
6895
Bram Moolenaar12b559e2013-06-12 22:41:37 +02006896 win32_setattrs(name, FILE_ATTRIBUTE_NORMAL);
6897
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006898 wn = enc_to_utf16(name, NULL);
6899 if (wn == NULL)
6900 return -1;
6901
6902 n = DeleteFileW(wn) ? 0 : -1;
6903 vim_free(wn);
6904 return n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006905}
6906
6907
6908/*
Bram Moolenaarb9c31e72016-09-29 15:18:57 +02006909 * Check for an "interrupt signal": CTRL-break or CTRL-C.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006910 */
6911 void
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02006912mch_breakcheck(int force UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006913{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006914#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
6915# ifdef VIMDLL
6916 if (!gui.in_use)
6917# endif
6918 if (g_fCtrlCPressed || g_fCBrkPressed)
6919 {
6920 ctrl_break_was_pressed = g_fCBrkPressed;
6921 g_fCtrlCPressed = g_fCBrkPressed = FALSE;
6922 got_int = TRUE;
6923 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006924#endif
6925}
6926
Bram Moolenaar0f873732019-12-05 20:28:46 +01006927// physical RAM to leave for the OS
Bram Moolenaaree273972016-01-02 21:11:51 +01006928#define WINNT_RESERVE_BYTES (256*1024*1024)
Bram Moolenaaree273972016-01-02 21:11:51 +01006929
6930/*
6931 * How much main memory in KiB that can be used by VIM.
6932 */
Bram Moolenaaree273972016-01-02 21:11:51 +01006933 long_u
Bram Moolenaar1266d672017-02-01 13:43:36 +01006934mch_total_mem(int special UNUSED)
Bram Moolenaaree273972016-01-02 21:11:51 +01006935{
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006936 MEMORYSTATUSEX ms;
6937
Bram Moolenaar0f873732019-12-05 20:28:46 +01006938 // Need to use GlobalMemoryStatusEx() when there is more memory than
6939 // what fits in 32 bits.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006940 ms.dwLength = sizeof(MEMORYSTATUSEX);
6941 GlobalMemoryStatusEx(&ms);
6942 if (ms.ullAvailVirtual < ms.ullTotalPhys)
Bram Moolenaaree273972016-01-02 21:11:51 +01006943 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006944 // Process address space fits in physical RAM, use all of it.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006945 return (long_u)(ms.ullAvailVirtual / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01006946 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006947 if (ms.ullTotalPhys <= WINNT_RESERVE_BYTES)
Bram Moolenaaree273972016-01-02 21:11:51 +01006948 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006949 // Catch old NT box or perverse hardware setup.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006950 return (long_u)((ms.ullTotalPhys / 2) / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01006951 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01006952 // Use physical RAM less reserve for OS + data.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006953 return (long_u)((ms.ullTotalPhys - WINNT_RESERVE_BYTES) / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01006954}
Bram Moolenaar071d4272004-06-13 20:20:40 +00006955
Bram Moolenaar071d4272004-06-13 20:20:40 +00006956/*
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006957 * mch_wrename() works around a bug in rename (aka MoveFile) in
Bram Moolenaar071d4272004-06-13 20:20:40 +00006958 * Windows 95: rename("foo.bar", "foo.bar~") will generate a
6959 * file whose short file name is "FOO.BAR" (its long file name will
6960 * be correct: "foo.bar~"). Because a file can be accessed by
6961 * either its SFN or its LFN, "foo.bar" has effectively been
6962 * renamed to "foo.bar", which is not at all what was wanted. This
6963 * seems to happen only when renaming files with three-character
6964 * extensions by appending a suffix that does not include ".".
6965 * Windows NT gets it right, however, with an SFN of "FOO~1.BAR".
6966 *
6967 * There is another problem, which isn't really a bug but isn't right either:
6968 * When renaming "abcdef~1.txt" to "abcdef~1.txt~", the short name can be
6969 * "abcdef~1.txt" again. This has been reported on Windows NT 4.0 with
6970 * service pack 6. Doesn't seem to happen on Windows 98.
6971 *
6972 * Like rename(), returns 0 upon success, non-zero upon failure.
6973 * Should probably set errno appropriately when errors occur.
6974 */
6975 int
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006976mch_wrename(WCHAR *wold, WCHAR *wnew)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006977{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006978 WCHAR *p;
6979 int i;
6980 WCHAR szTempFile[_MAX_PATH + 1];
6981 WCHAR szNewPath[_MAX_PATH + 1];
Bram Moolenaar071d4272004-06-13 20:20:40 +00006982 HANDLE hf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006983
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006984 // No need to play tricks unless the file name contains a "~" as the
6985 // seventh character.
6986 p = wold;
6987 for (i = 0; wold[i] != NUL; ++i)
6988 if ((wold[i] == '/' || wold[i] == '\\' || wold[i] == ':')
6989 && wold[i + 1] != 0)
6990 p = wold + i + 1;
6991 if ((int)(wold + i - p) < 8 || p[6] != '~')
6992 return (MoveFileW(wold, wnew) == 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006993
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006994 // Get base path of new file name. Undocumented feature: If pszNewFile is
6995 // a directory, no error is returned and pszFilePart will be NULL.
6996 if (GetFullPathNameW(wnew, _MAX_PATH, szNewPath, &p) == 0 || p == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006997 return -1;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006998 *p = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006999
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007000 // Get (and create) a unique temporary file name in directory of new file
7001 if (GetTempFileNameW(szNewPath, L"VIM", 0, szTempFile) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007002 return -2;
7003
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007004 // blow the temp file away
7005 if (!DeleteFileW(szTempFile))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007006 return -3;
7007
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007008 // rename old file to the temp file
7009 if (!MoveFileW(wold, szTempFile))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007010 return -4;
7011
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007012 // now create an empty file called pszOldFile; this prevents the operating
7013 // system using pszOldFile as an alias (SFN) if we're renaming within the
7014 // same directory. For example, we're editing a file called
7015 // filename.asc.txt by its SFN, filena~1.txt. If we rename filena~1.txt
7016 // to filena~1.txt~ (i.e., we're making a backup while writing it), the
7017 // SFN for filena~1.txt~ will be filena~1.txt, by default, which will
7018 // cause all sorts of problems later in buf_write(). So, we create an
7019 // empty file called filena~1.txt and the system will have to find some
7020 // other SFN for filena~1.txt~, such as filena~2.txt
7021 if ((hf = CreateFileW(wold, GENERIC_WRITE, 0, NULL, CREATE_NEW,
Bram Moolenaar071d4272004-06-13 20:20:40 +00007022 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
7023 return -5;
7024 if (!CloseHandle(hf))
7025 return -6;
7026
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007027 // rename the temp file to the new file
7028 if (!MoveFileW(szTempFile, wnew))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007029 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007030 // Renaming failed. Rename the file back to its old name, so that it
7031 // looks like nothing happened.
7032 (void)MoveFileW(szTempFile, wold);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007033 return -7;
7034 }
7035
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007036 // Seems to be left around on Novell filesystems
7037 DeleteFileW(szTempFile);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007038
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007039 // finally, remove the empty old file
7040 if (!DeleteFileW(wold))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007041 return -8;
7042
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007043 return 0;
7044}
7045
7046
7047/*
7048 * Converts the filenames to UTF-16, then call mch_wrename().
7049 * Like rename(), returns 0 upon success, non-zero upon failure.
7050 */
7051 int
7052mch_rename(
7053 const char *pszOldFile,
7054 const char *pszNewFile)
7055{
7056 WCHAR *wold = NULL;
7057 WCHAR *wnew = NULL;
7058 int retval = -1;
7059
7060 wold = enc_to_utf16((char_u *)pszOldFile, NULL);
7061 wnew = enc_to_utf16((char_u *)pszNewFile, NULL);
7062 if (wold != NULL && wnew != NULL)
7063 retval = mch_wrename(wold, wnew);
7064 vim_free(wold);
7065 vim_free(wnew);
7066 return retval;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007067}
7068
7069/*
7070 * Get the default shell for the current hardware platform
7071 */
7072 char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007073default_shell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007074{
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007075 return "cmd.exe";
Bram Moolenaar071d4272004-06-13 20:20:40 +00007076}
7077
7078/*
7079 * mch_access() extends access() to do more detailed check on network drives.
7080 * Returns 0 if file "n" has access rights according to "p", -1 otherwise.
7081 */
7082 int
7083mch_access(char *n, int p)
7084{
7085 HANDLE hFile;
Bram Moolenaar0f873732019-12-05 20:28:46 +01007086 int retval = -1; // default: fail
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007087 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007088
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007089 wn = enc_to_utf16((char_u *)n, NULL);
7090 if (wn == NULL)
7091 return -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007092
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01007093 if (mch_isdir((char_u *)n))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007094 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00007095 WCHAR TempNameW[_MAX_PATH + 16] = L"";
Bram Moolenaar071d4272004-06-13 20:20:40 +00007096
7097 if (p & R_OK)
7098 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007099 // Read check is performed by seeing if we can do a find file on
7100 // the directory for any file.
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007101 int i;
7102 WIN32_FIND_DATAW d;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007103
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007104 for (i = 0; i < _MAX_PATH && wn[i] != 0; ++i)
7105 TempNameW[i] = wn[i];
7106 if (TempNameW[i - 1] != '\\' && TempNameW[i - 1] != '/')
7107 TempNameW[i++] = '\\';
7108 TempNameW[i++] = '*';
7109 TempNameW[i++] = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007110
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007111 hFile = FindFirstFileW(TempNameW, &d);
7112 if (hFile == INVALID_HANDLE_VALUE)
7113 goto getout;
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007114 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00007115 (void)FindClose(hFile);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007116 }
7117
7118 if (p & W_OK)
7119 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007120 // Trying to create a temporary file in the directory should catch
7121 // directories on read-only network shares. However, in
7122 // directories whose ACL allows writes but denies deletes will end
7123 // up keeping the temporary file :-(.
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007124 if (!GetTempFileNameW(wn, L"VIM", 0, TempNameW))
7125 goto getout;
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007126 else
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007127 DeleteFileW(TempNameW);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007128 }
7129 }
7130 else
7131 {
Bram Moolenaar5aa98962018-05-06 17:09:38 +02007132 // Don't consider a file read-only if another process has opened it.
7133 DWORD share_mode = FILE_SHARE_READ | FILE_SHARE_WRITE;
7134
Bram Moolenaar0f873732019-12-05 20:28:46 +01007135 // Trying to open the file for the required access does ACL, read-only
7136 // network share, and file attribute checks.
Bram Moolenaar5aa98962018-05-06 17:09:38 +02007137 DWORD access_mode = ((p & W_OK) ? GENERIC_WRITE : 0)
7138 | ((p & R_OK) ? GENERIC_READ : 0);
7139
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007140 hFile = CreateFileW(wn, access_mode, share_mode,
7141 NULL, OPEN_EXISTING, 0, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007142 if (hFile == INVALID_HANDLE_VALUE)
7143 goto getout;
7144 CloseHandle(hFile);
7145 }
7146
Bram Moolenaar0f873732019-12-05 20:28:46 +01007147 retval = 0; // success
Bram Moolenaar071d4272004-06-13 20:20:40 +00007148getout:
Bram Moolenaar071d4272004-06-13 20:20:40 +00007149 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007150 return retval;
7151}
7152
Bram Moolenaar071d4272004-06-13 20:20:40 +00007153/*
Bram Moolenaar36f692d2008-11-20 16:10:17 +00007154 * Version of open() that may use UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007155 */
7156 int
Bram Moolenaarb6843a02017-08-02 22:07:12 +02007157mch_open(const char *name, int flags, int mode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007158{
7159 WCHAR *wn;
7160 int f;
7161
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007162 wn = enc_to_utf16((char_u *)name, NULL);
7163 if (wn == NULL)
7164 return -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007165
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007166 f = _wopen(wn, flags, mode);
7167 vim_free(wn);
7168 return f;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007169}
7170
7171/*
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007172 * Version of fopen() that uses UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007173 */
7174 FILE *
Bram Moolenaarb6843a02017-08-02 22:07:12 +02007175mch_fopen(const char *name, const char *mode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007176{
7177 WCHAR *wn, *wm;
7178 FILE *f = NULL;
7179
Bram Moolenaara12a1612019-01-24 16:39:02 +01007180#if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0f873732019-12-05 20:28:46 +01007181 // Work around an annoying assertion in the Microsoft debug CRT
7182 // when mode's text/binary setting doesn't match _get_fmode().
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007183 char newMode = mode[strlen(mode) - 1];
7184 int oldMode = 0;
Bram Moolenaar0fde2902008-03-16 13:54:13 +00007185
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007186 _get_fmode(&oldMode);
7187 if (newMode == 't')
7188 _set_fmode(_O_TEXT);
7189 else if (newMode == 'b')
7190 _set_fmode(_O_BINARY);
Bram Moolenaara12a1612019-01-24 16:39:02 +01007191#endif
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007192 wn = enc_to_utf16((char_u *)name, NULL);
7193 wm = enc_to_utf16((char_u *)mode, NULL);
7194 if (wn != NULL && wm != NULL)
7195 f = _wfopen(wn, wm);
7196 vim_free(wn);
7197 vim_free(wm);
Bram Moolenaar0fde2902008-03-16 13:54:13 +00007198
Bram Moolenaara12a1612019-01-24 16:39:02 +01007199#if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007200 _set_fmode(oldMode);
Bram Moolenaara12a1612019-01-24 16:39:02 +01007201#endif
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007202 return f;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007203}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007204
Bram Moolenaar071d4272004-06-13 20:20:40 +00007205/*
7206 * SUB STREAM (aka info stream) handling:
7207 *
Bram Moolenaar8e7d6222020-12-18 19:49:56 +01007208 * NTFS can have sub streams for each file. The normal contents of a file is
7209 * stored in the main stream, and extra contents (author information, title and
7210 * so on) can be stored in a sub stream. After Windows 2000, the user can
7211 * access and store this information in sub streams via an explorer's property
7212 * menu item in the right click menu. This information in sub streams was lost
7213 * when copying only the main stream. Therefore we have to copy sub streams.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007214 *
7215 * Incomplete explanation:
7216 * http://msdn.microsoft.com/library/en-us/dnw2k/html/ntfs5.asp
7217 * More useful info and an example:
7218 * http://www.sysinternals.com/ntw2k/source/misc.shtml#streams
7219 */
7220
7221/*
7222 * Copy info stream data "substream". Read from the file with BackupRead(sh)
7223 * and write to stream "substream" of file "to".
7224 * Errors are ignored.
7225 */
7226 static void
7227copy_substream(HANDLE sh, void *context, WCHAR *to, WCHAR *substream, long len)
7228{
7229 HANDLE hTo;
7230 WCHAR *to_name;
7231
7232 to_name = malloc((wcslen(to) + wcslen(substream) + 1) * sizeof(WCHAR));
7233 wcscpy(to_name, to);
7234 wcscat(to_name, substream);
7235
7236 hTo = CreateFileW(to_name, GENERIC_WRITE, 0, NULL, OPEN_ALWAYS,
7237 FILE_ATTRIBUTE_NORMAL, NULL);
7238 if (hTo != INVALID_HANDLE_VALUE)
7239 {
7240 long done;
7241 DWORD todo;
7242 DWORD readcnt, written;
7243 char buf[4096];
7244
Bram Moolenaar0f873732019-12-05 20:28:46 +01007245 // Copy block of bytes at a time. Abort when something goes wrong.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007246 for (done = 0; done < len; done += written)
7247 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007248 // (size_t) cast for Borland C 5.5
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007249 todo = (DWORD)((size_t)(len - done) > sizeof(buf) ? sizeof(buf)
7250 : (size_t)(len - done));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007251 if (!BackupRead(sh, (LPBYTE)buf, todo, &readcnt,
7252 FALSE, FALSE, context)
7253 || readcnt != todo
7254 || !WriteFile(hTo, buf, todo, &written, NULL)
7255 || written != todo)
7256 break;
7257 }
7258 CloseHandle(hTo);
7259 }
7260
7261 free(to_name);
7262}
7263
7264/*
7265 * Copy info streams from file "from" to file "to".
7266 */
7267 static void
7268copy_infostreams(char_u *from, char_u *to)
7269{
7270 WCHAR *fromw;
7271 WCHAR *tow;
7272 HANDLE sh;
7273 WIN32_STREAM_ID sid;
7274 int headersize;
7275 WCHAR streamname[_MAX_PATH];
7276 DWORD readcount;
7277 void *context = NULL;
7278 DWORD lo, hi;
7279 int len;
7280
Bram Moolenaar0f873732019-12-05 20:28:46 +01007281 // Convert the file names to wide characters.
Bram Moolenaar36f692d2008-11-20 16:10:17 +00007282 fromw = enc_to_utf16(from, NULL);
7283 tow = enc_to_utf16(to, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007284 if (fromw != NULL && tow != NULL)
7285 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007286 // Open the file for reading.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007287 sh = CreateFileW(fromw, GENERIC_READ, FILE_SHARE_READ, NULL,
7288 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
7289 if (sh != INVALID_HANDLE_VALUE)
7290 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007291 // Use BackupRead() to find the info streams. Repeat until we
7292 // have done them all.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007293 for (;;)
7294 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007295 // Get the header to find the length of the stream name. If
7296 // the "readcount" is zero we have done all info streams.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007297 ZeroMemory(&sid, sizeof(WIN32_STREAM_ID));
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007298 headersize = (int)((char *)&sid.cStreamName - (char *)&sid.dwStreamId);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007299 if (!BackupRead(sh, (LPBYTE)&sid, headersize,
7300 &readcount, FALSE, FALSE, &context)
7301 || readcount == 0)
7302 break;
7303
Bram Moolenaar0f873732019-12-05 20:28:46 +01007304 // We only deal with streams that have a name. The normal
7305 // file data appears to be without a name, even though docs
7306 // suggest it is called "::$DATA".
Bram Moolenaar071d4272004-06-13 20:20:40 +00007307 if (sid.dwStreamNameSize > 0)
7308 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007309 // Read the stream name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007310 if (!BackupRead(sh, (LPBYTE)streamname,
7311 sid.dwStreamNameSize,
7312 &readcount, FALSE, FALSE, &context))
7313 break;
7314
Bram Moolenaar0f873732019-12-05 20:28:46 +01007315 // Copy an info stream with a name ":anything:$DATA".
7316 // Skip "::$DATA", it has no stream name (examples suggest
7317 // it might be used for the normal file contents).
7318 // Note that BackupRead() counts bytes, but the name is in
7319 // wide characters.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007320 len = readcount / sizeof(WCHAR);
7321 streamname[len] = 0;
7322 if (len > 7 && wcsicmp(streamname + len - 6,
7323 L":$DATA") == 0)
7324 {
7325 streamname[len - 6] = 0;
7326 copy_substream(sh, &context, tow, streamname,
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00007327 (long)sid.Size.u.LowPart);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007328 }
7329 }
7330
Bram Moolenaar0f873732019-12-05 20:28:46 +01007331 // Advance to the next stream. We might try seeking too far,
7332 // but BackupSeek() doesn't skip over stream borders, thus
7333 // that's OK.
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00007334 (void)BackupSeek(sh, sid.Size.u.LowPart, sid.Size.u.HighPart,
Bram Moolenaar071d4272004-06-13 20:20:40 +00007335 &lo, &hi, &context);
7336 }
7337
Bram Moolenaar0f873732019-12-05 20:28:46 +01007338 // Clear the context.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007339 (void)BackupRead(sh, NULL, 0, &readcount, TRUE, FALSE, &context);
7340
7341 CloseHandle(sh);
7342 }
7343 }
7344 vim_free(fromw);
7345 vim_free(tow);
7346}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007347
7348/*
Bram Moolenaare7bebc42021-02-01 20:50:37 +01007349 * ntdll.dll definitions
7350 */
7351#define FileEaInformation 7
7352#ifndef STATUS_SUCCESS
7353# define STATUS_SUCCESS ((NTSTATUS) 0x00000000L)
7354#endif
7355
7356typedef struct _FILE_FULL_EA_INFORMATION_ {
7357 ULONG NextEntryOffset;
7358 UCHAR Flags;
7359 UCHAR EaNameLength;
7360 USHORT EaValueLength;
7361 CHAR EaName[1];
7362} FILE_FULL_EA_INFORMATION_, *PFILE_FULL_EA_INFORMATION_;
7363
7364typedef struct _FILE_EA_INFORMATION_ {
7365 ULONG EaSize;
7366} FILE_EA_INFORMATION_, *PFILE_EA_INFORMATION_;
7367
Paul Ollis65745772022-06-05 16:55:54 +01007368#ifndef PROTO
Bram Moolenaare7bebc42021-02-01 20:50:37 +01007369typedef NTSTATUS (NTAPI *PfnNtOpenFile)(
7370 PHANDLE FileHandle,
7371 ACCESS_MASK DesiredAccess,
7372 POBJECT_ATTRIBUTES ObjectAttributes,
7373 PIO_STATUS_BLOCK IoStatusBlock,
7374 ULONG ShareAccess,
7375 ULONG OpenOptions);
7376typedef NTSTATUS (NTAPI *PfnNtClose)(
7377 HANDLE Handle);
7378typedef NTSTATUS (NTAPI *PfnNtSetEaFile)(
Bram Moolenaar9f1983d2022-05-12 20:35:35 +01007379 HANDLE FileHandle,
7380 PIO_STATUS_BLOCK IoStatusBlock,
7381 PVOID Buffer,
7382 ULONG Length);
Bram Moolenaare7bebc42021-02-01 20:50:37 +01007383typedef NTSTATUS (NTAPI *PfnNtQueryEaFile)(
7384 HANDLE FileHandle,
7385 PIO_STATUS_BLOCK IoStatusBlock,
7386 PVOID Buffer,
7387 ULONG Length,
7388 BOOLEAN ReturnSingleEntry,
7389 PVOID EaList,
7390 ULONG EaListLength,
7391 PULONG EaIndex,
7392 BOOLEAN RestartScan);
7393typedef NTSTATUS (NTAPI *PfnNtQueryInformationFile)(
Bram Moolenaar9f1983d2022-05-12 20:35:35 +01007394 HANDLE FileHandle,
7395 PIO_STATUS_BLOCK IoStatusBlock,
7396 PVOID FileInformation,
7397 ULONG Length,
Bram Moolenaare7bebc42021-02-01 20:50:37 +01007398 FILE_INFORMATION_CLASS FileInformationClass);
7399typedef VOID (NTAPI *PfnRtlInitUnicodeString)(
7400 PUNICODE_STRING DestinationString,
7401 PCWSTR SourceString);
7402
7403PfnNtOpenFile pNtOpenFile = NULL;
7404PfnNtClose pNtClose = NULL;
7405PfnNtSetEaFile pNtSetEaFile = NULL;
7406PfnNtQueryEaFile pNtQueryEaFile = NULL;
7407PfnNtQueryInformationFile pNtQueryInformationFile = NULL;
7408PfnRtlInitUnicodeString pRtlInitUnicodeString = NULL;
Paul Ollis65745772022-06-05 16:55:54 +01007409#endif
Bram Moolenaare7bebc42021-02-01 20:50:37 +01007410
7411/*
7412 * Load ntdll.dll functions.
7413 */
7414 static BOOL
7415load_ntdll(void)
7416{
7417 static int loaded = -1;
7418
7419 if (loaded == -1)
7420 {
7421 HMODULE hNtdll = GetModuleHandle("ntdll.dll");
7422 if (hNtdll != NULL)
7423 {
7424 pNtOpenFile = (PfnNtOpenFile) GetProcAddress(hNtdll, "NtOpenFile");
7425 pNtClose = (PfnNtClose) GetProcAddress(hNtdll, "NtClose");
7426 pNtSetEaFile = (PfnNtSetEaFile)
7427 GetProcAddress(hNtdll, "NtSetEaFile");
7428 pNtQueryEaFile = (PfnNtQueryEaFile)
7429 GetProcAddress(hNtdll, "NtQueryEaFile");
7430 pNtQueryInformationFile = (PfnNtQueryInformationFile)
7431 GetProcAddress(hNtdll, "NtQueryInformationFile");
7432 pRtlInitUnicodeString = (PfnRtlInitUnicodeString)
7433 GetProcAddress(hNtdll, "RtlInitUnicodeString");
7434 }
7435 if (pNtOpenFile == NULL
7436 || pNtClose == NULL
7437 || pNtSetEaFile == NULL
7438 || pNtQueryEaFile == NULL
7439 || pNtQueryInformationFile == NULL
7440 || pRtlInitUnicodeString == NULL)
7441 loaded = FALSE;
7442 else
7443 loaded = TRUE;
7444 }
7445 return (BOOL) loaded;
7446}
7447
7448/*
7449 * Copy extended attributes (EA) from file "from" to file "to".
7450 */
7451 static void
7452copy_extattr(char_u *from, char_u *to)
7453{
7454 char_u *fromf = NULL;
7455 char_u *tof = NULL;
7456 WCHAR *fromw = NULL;
7457 WCHAR *tow = NULL;
7458 UNICODE_STRING u;
7459 HANDLE h;
7460 OBJECT_ATTRIBUTES oa;
7461 IO_STATUS_BLOCK iosb;
7462 FILE_EA_INFORMATION_ eainfo = {0};
7463 void *ea = NULL;
7464
7465 if (!load_ntdll())
7466 return;
7467
7468 // Convert the file names to the fully qualified object names.
7469 fromf = alloc(STRLEN(from) + 5);
7470 tof = alloc(STRLEN(to) + 5);
7471 if (fromf == NULL || tof == NULL)
7472 goto theend;
7473 STRCPY(fromf, "\\??\\");
7474 STRCAT(fromf, from);
7475 STRCPY(tof, "\\??\\");
7476 STRCAT(tof, to);
7477
7478 // Convert the names to wide characters.
7479 fromw = enc_to_utf16(fromf, NULL);
7480 tow = enc_to_utf16(tof, NULL);
7481 if (fromw == NULL || tow == NULL)
7482 goto theend;
7483
7484 // Get the EA.
7485 pRtlInitUnicodeString(&u, fromw);
7486 InitializeObjectAttributes(&oa, &u, 0, NULL, NULL);
7487 if (pNtOpenFile(&h, FILE_READ_EA, &oa, &iosb, 0,
7488 FILE_NON_DIRECTORY_FILE) != STATUS_SUCCESS)
7489 goto theend;
7490 pNtQueryInformationFile(h, &iosb, &eainfo, sizeof(eainfo),
7491 FileEaInformation);
7492 if (eainfo.EaSize != 0)
7493 {
7494 ea = alloc(eainfo.EaSize);
7495 if (ea != NULL)
7496 {
7497 if (pNtQueryEaFile(h, &iosb, ea, eainfo.EaSize, FALSE,
7498 NULL, 0, NULL, TRUE) != STATUS_SUCCESS)
7499 {
7500 vim_free(ea);
7501 ea = NULL;
7502 }
7503 }
7504 }
7505 pNtClose(h);
7506
7507 // Set the EA.
7508 if (ea != NULL)
7509 {
7510 pRtlInitUnicodeString(&u, tow);
7511 InitializeObjectAttributes(&oa, &u, 0, NULL, NULL);
7512 if (pNtOpenFile(&h, FILE_WRITE_EA, &oa, &iosb, 0,
7513 FILE_NON_DIRECTORY_FILE) != STATUS_SUCCESS)
7514 goto theend;
7515
7516 pNtSetEaFile(h, &iosb, ea, eainfo.EaSize);
7517 pNtClose(h);
7518 }
7519
7520theend:
7521 vim_free(fromf);
7522 vim_free(tof);
7523 vim_free(fromw);
7524 vim_free(tow);
7525 vim_free(ea);
7526}
7527
7528/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00007529 * Copy file attributes from file "from" to file "to".
7530 * For Windows NT and later we copy info streams.
7531 * Always returns zero, errors are ignored.
7532 */
7533 int
7534mch_copy_file_attribute(char_u *from, char_u *to)
7535{
Bram Moolenaar0f873732019-12-05 20:28:46 +01007536 // File streams only work on Windows NT and later.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007537 copy_infostreams(from, to);
Bram Moolenaare7bebc42021-02-01 20:50:37 +01007538 copy_extattr(from, to);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007539 return 0;
7540}
7541
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007542
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007543/*
K.Takatadc73b4b2021-06-08 18:32:36 +02007544 * The command line arguments in UTF-16
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007545 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00007546static int nArgsW = 0;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007547static LPWSTR *ArglistW = NULL;
7548static int global_argc = 0;
7549static char **global_argv;
7550
Bram Moolenaar0f873732019-12-05 20:28:46 +01007551static int used_file_argc = 0; // last argument in global_argv[] used
7552 // for the argument list.
7553static int *used_file_indexes = NULL; // indexes in global_argv[] for
7554 // command line arguments added to
7555 // the argument list
7556static int used_file_count = 0; // nr of entries in used_file_indexes
7557static int used_file_literal = FALSE; // take file names literally
7558static int used_file_full_path = FALSE; // file name was full path
7559static int used_file_diff_mode = FALSE; // file name was with diff mode
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007560static int used_alist_count = 0;
7561
7562
7563/*
7564 * Get the command line arguments. Unicode version.
7565 * Returns argc. Zero when something fails.
7566 */
7567 int
7568get_cmd_argsW(char ***argvp)
7569{
7570 char **argv = NULL;
7571 int argc = 0;
7572 int i;
7573
Bram Moolenaar14993322014-09-09 12:25:33 +02007574 free_cmd_argsW();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007575 ArglistW = CommandLineToArgvW(GetCommandLineW(), &nArgsW);
7576 if (ArglistW != NULL)
7577 {
7578 argv = malloc((nArgsW + 1) * sizeof(char *));
7579 if (argv != NULL)
7580 {
7581 argc = nArgsW;
7582 argv[argc] = NULL;
7583 for (i = 0; i < argc; ++i)
7584 {
7585 int len;
7586
K.Takatadc73b4b2021-06-08 18:32:36 +02007587 // Convert each Unicode argument to UTF-8.
7588 WideCharToMultiByte_alloc(CP_UTF8, 0,
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007589 ArglistW[i], (int)wcslen(ArglistW[i]) + 1,
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007590 (LPSTR *)&argv[i], &len, 0, 0);
7591 if (argv[i] == NULL)
7592 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007593 // Out of memory, clear everything.
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007594 while (i > 0)
7595 free(argv[--i]);
7596 free(argv);
Bram Moolenaar73c61632013-12-07 14:48:10 +01007597 argv = NULL;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007598 argc = 0;
7599 }
7600 }
7601 }
7602 }
7603
7604 global_argc = argc;
7605 global_argv = argv;
7606 if (argc > 0)
Bram Moolenaar14993322014-09-09 12:25:33 +02007607 {
7608 if (used_file_indexes != NULL)
7609 free(used_file_indexes);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007610 used_file_indexes = malloc(argc * sizeof(int));
Bram Moolenaar14993322014-09-09 12:25:33 +02007611 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007612
7613 if (argvp != NULL)
7614 *argvp = argv;
7615 return argc;
7616}
7617
7618 void
7619free_cmd_argsW(void)
7620{
7621 if (ArglistW != NULL)
7622 {
7623 GlobalFree(ArglistW);
7624 ArglistW = NULL;
7625 }
7626}
7627
7628/*
7629 * Remember "name" is an argument that was added to the argument list.
7630 * This avoids that we have to re-parse the argument list when fix_arg_enc()
7631 * is called.
7632 */
7633 void
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007634used_file_arg(char *name, int literal, int full_path, int diff_mode)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007635{
7636 int i;
7637
7638 if (used_file_indexes == NULL)
7639 return;
7640 for (i = used_file_argc + 1; i < global_argc; ++i)
7641 if (STRCMP(global_argv[i], name) == 0)
7642 {
7643 used_file_argc = i;
7644 used_file_indexes[used_file_count++] = i;
7645 break;
7646 }
7647 used_file_literal = literal;
7648 used_file_full_path = full_path;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007649 used_file_diff_mode = diff_mode;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007650}
7651
7652/*
7653 * Remember the length of the argument list as it was. If it changes then we
7654 * leave it alone when 'encoding' is set.
7655 */
7656 void
7657set_alist_count(void)
7658{
7659 used_alist_count = GARGCOUNT;
7660}
7661
7662/*
7663 * Fix the encoding of the command line arguments. Invoked when 'encoding'
K.Takatadc73b4b2021-06-08 18:32:36 +02007664 * has been changed while starting up. Use the UTF-16 command line arguments
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007665 * and convert them to 'encoding'.
7666 */
7667 void
7668fix_arg_enc(void)
7669{
7670 int i;
7671 int idx;
7672 char_u *str;
Bram Moolenaar86b68352004-12-27 21:59:20 +00007673 int *fnum_list;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007674
Bram Moolenaar0f873732019-12-05 20:28:46 +01007675 // Safety checks:
7676 // - if argument count differs between the wide and non-wide argument
7677 // list, something must be wrong.
7678 // - the file name arguments must have been located.
7679 // - the length of the argument list wasn't changed by the user.
Bram Moolenaard857f0e2005-06-21 22:37:39 +00007680 if (global_argc != nArgsW
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007681 || ArglistW == NULL
7682 || used_file_indexes == NULL
7683 || used_file_count == 0
7684 || used_alist_count != GARGCOUNT)
7685 return;
7686
Bram Moolenaar0f873732019-12-05 20:28:46 +01007687 // Remember the buffer numbers for the arguments.
Bram Moolenaarc799fe22019-05-28 23:08:19 +02007688 fnum_list = ALLOC_MULT(int, GARGCOUNT);
Bram Moolenaar86b68352004-12-27 21:59:20 +00007689 if (fnum_list == NULL)
Bram Moolenaar0f873732019-12-05 20:28:46 +01007690 return; // out of memory
Bram Moolenaar86b68352004-12-27 21:59:20 +00007691 for (i = 0; i < GARGCOUNT; ++i)
7692 fnum_list[i] = GARGLIST[i].ae_fnum;
7693
Bram Moolenaar0f873732019-12-05 20:28:46 +01007694 // Clear the argument list. Make room for the new arguments.
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007695 alist_clear(&global_alist);
7696 if (ga_grow(&global_alist.al_ga, used_file_count) == FAIL)
Bram Moolenaar0f873732019-12-05 20:28:46 +01007697 return; // out of memory
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007698
7699 for (i = 0; i < used_file_count; ++i)
7700 {
7701 idx = used_file_indexes[i];
Bram Moolenaar36f692d2008-11-20 16:10:17 +00007702 str = utf16_to_enc(ArglistW[idx], NULL);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007703 if (str != NULL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00007704 {
Bram Moolenaar39d21e32017-08-05 23:09:31 +02007705 int literal = used_file_literal;
7706
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007707#ifdef FEAT_DIFF
Bram Moolenaar0f873732019-12-05 20:28:46 +01007708 // When using diff mode may need to concatenate file name to
7709 // directory name. Just like it's done in main().
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007710 if (used_file_diff_mode && mch_isdir(str) && GARGCOUNT > 0
7711 && !mch_isdir(alist_name(&GARGLIST[0])))
7712 {
7713 char_u *r;
7714
7715 r = concat_fnames(str, gettail(alist_name(&GARGLIST[0])), TRUE);
7716 if (r != NULL)
7717 {
7718 vim_free(str);
7719 str = r;
7720 }
7721 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007722#endif
Bram Moolenaar0f873732019-12-05 20:28:46 +01007723 // Re-use the old buffer by renaming it. When not using literal
7724 // names it's done by alist_expand() below.
Bram Moolenaar86b68352004-12-27 21:59:20 +00007725 if (used_file_literal)
7726 buf_set_name(fnum_list[i], str);
7727
Bram Moolenaar0f873732019-12-05 20:28:46 +01007728 // Check backtick literal. backtick literal is already expanded in
7729 // main.c, so this part add str as literal.
Bram Moolenaar39d21e32017-08-05 23:09:31 +02007730 if (literal == FALSE)
7731 {
Bram Moolenaar116a0f82017-08-07 21:17:57 +02007732 size_t len = STRLEN(str);
7733
Bram Moolenaar39d21e32017-08-05 23:09:31 +02007734 if (len > 2 && *str == '`' && *(str + len - 1) == '`')
7735 literal = TRUE;
7736 }
7737 alist_add(&global_alist, str, literal ? 2 : 0);
Bram Moolenaar86b68352004-12-27 21:59:20 +00007738 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007739 }
7740
7741 if (!used_file_literal)
7742 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007743 // Now expand wildcards in the arguments.
7744 // Temporarily add '(' and ')' to 'isfname'. These are valid
7745 // filename characters but are excluded from 'isfname' to make
Dominique Pelleaf4a61a2021-12-27 17:21:41 +00007746 // "gf" work on a file name in parentheses (e.g.: see vim.h).
Bram Moolenaar0f873732019-12-05 20:28:46 +01007747 // Also, unset wildignore to not be influenced by this option.
7748 // The arguments specified in command-line should be kept even if
7749 // encoding options were changed.
Christian Brabandtfd916d62021-11-01 22:44:33 +00007750 // Use :legacy so that it also works when in Vim9 script.
7751 do_cmdline_cmd((char_u *)":legacy let g:SaVe_ISF = &isf|set isf+=(,)");
7752 do_cmdline_cmd((char_u *)":legacy let g:SaVe_WIG = &wig|set wig=");
Bram Moolenaar86b68352004-12-27 21:59:20 +00007753 alist_expand(fnum_list, used_alist_count);
Christian Brabandtfd916d62021-11-01 22:44:33 +00007754 do_cmdline_cmd(
7755 (char_u *)":legacy let &isf = g:SaVe_ISF|unlet g:SaVe_ISF");
7756 do_cmdline_cmd(
7757 (char_u *)":legacy let &wig = g:SaVe_WIG|unlet g:SaVe_WIG");
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007758 }
7759
Bram Moolenaar0f873732019-12-05 20:28:46 +01007760 // If wildcard expansion failed, we are editing the first file of the
7761 // arglist and there is no file name: Edit the first argument now.
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007762 if (curwin->w_arg_idx == 0 && curbuf->b_fname == NULL)
7763 {
7764 do_cmdline_cmd((char_u *)":rewind");
Bram Moolenaar05268152021-11-18 18:53:45 +00007765 if (GARGCOUNT == 1 && used_file_full_path
7766 && vim_chdirfile(alist_name(&GARGLIST[0]), "drop") == OK)
7767 last_chdir_reason = "drop";
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007768 }
Bram Moolenaar86b68352004-12-27 21:59:20 +00007769
7770 set_alist_count();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007771}
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007772
7773 int
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02007774mch_setenv(char *var, char *value, int x UNUSED)
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007775{
7776 char_u *envbuf;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007777 WCHAR *p;
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007778
Bram Moolenaar964b3742019-05-24 18:54:09 +02007779 envbuf = alloc(STRLEN(var) + STRLEN(value) + 2);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007780 if (envbuf == NULL)
7781 return -1;
7782
7783 sprintf((char *)envbuf, "%s=%s", var, value);
7784
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007785 p = enc_to_utf16(envbuf, NULL);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007786
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007787 vim_free(envbuf);
7788 if (p == NULL)
7789 return -1;
7790 _wputenv(p);
Bram Moolenaara12a1612019-01-24 16:39:02 +01007791#ifdef libintl_wputenv
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007792 libintl_wputenv(p);
Bram Moolenaara12a1612019-01-24 16:39:02 +01007793#endif
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007794 // Unlike Un*x systems, we can free the string for _wputenv().
7795 vim_free(p);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007796
7797 return 0;
7798}
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007799
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007800/*
7801 * Support for 256 colors and 24-bit colors was added in Windows 10
7802 * version 1703 (Creators update).
7803 */
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007804#define VTP_FIRST_SUPPORT_BUILD MAKE_VER(10, 0, 15063)
7805
7806/*
7807 * Support for pseudo-console (ConPTY) was added in windows 10
Bram Moolenaar57da6982019-09-13 22:30:11 +02007808 * version 1809 (October 2018 update).
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007809 */
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01007810#define CONPTY_FIRST_SUPPORT_BUILD MAKE_VER(10, 0, 17763)
Bram Moolenaar57da6982019-09-13 22:30:11 +02007811
7812/*
7813 * ConPTY differences between versions, need different logic.
7814 * version 1903 (May 2019 update).
7815 */
7816#define CONPTY_1903_BUILD MAKE_VER(10, 0, 18362)
7817
7818/*
Bram Moolenaar36e7a822019-11-13 21:49:24 +01007819 * version 1909 (November 2019 update).
7820 */
7821#define CONPTY_1909_BUILD MAKE_VER(10, 0, 18363)
7822
7823/*
Bram Moolenaar7ed8f592020-04-28 20:44:42 +02007824 * Stay ahead of the next update, and when it's done, fix this.
7825 * version ? (2020 update, temporarily use the build number of insider preview)
7826 */
7827#define CONPTY_NEXT_UPDATE_BUILD MAKE_VER(10, 0, 19587)
7828
7829/*
Bram Moolenaar57da6982019-09-13 22:30:11 +02007830 * Confirm until this version. Also the logic changes.
7831 * insider preview.
7832 */
Bram Moolenaar4c063dd2019-10-04 21:29:12 +02007833#define CONPTY_INSIDER_BUILD MAKE_VER(10, 0, 18995)
Bram Moolenaar57da6982019-09-13 22:30:11 +02007834
7835/*
7836 * Not stable now.
7837 */
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01007838#define CONPTY_STABLE_BUILD MAKE_VER(10, 0, 32767) // T.B.D.
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007839
7840 static void
7841vtp_flag_init(void)
7842{
7843 DWORD ver = get_build_number();
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007844#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007845 DWORD mode;
7846 HANDLE out;
7847
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007848# ifdef VIMDLL
7849 if (!gui.in_use)
7850# endif
7851 {
7852 out = GetStdHandle(STD_OUTPUT_HANDLE);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007853
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007854 vtp_working = (ver >= VTP_FIRST_SUPPORT_BUILD) ? 1 : 0;
7855 GetConsoleMode(out, &mode);
7856 mode |= (ENABLE_PROCESSED_OUTPUT | ENABLE_VIRTUAL_TERMINAL_PROCESSING);
7857 if (SetConsoleMode(out, mode) == 0)
7858 vtp_working = 0;
7859 }
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007860#endif
7861
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007862 if (ver >= CONPTY_FIRST_SUPPORT_BUILD)
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01007863 conpty_working = 1;
7864 if (ver >= CONPTY_STABLE_BUILD)
7865 conpty_stable = 1;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007866
Bram Moolenaar57da6982019-09-13 22:30:11 +02007867 if (ver <= CONPTY_INSIDER_BUILD)
7868 conpty_type = 3;
Bram Moolenaar36e7a822019-11-13 21:49:24 +01007869 if (ver <= CONPTY_1909_BUILD)
7870 conpty_type = 2;
Bram Moolenaar57da6982019-09-13 22:30:11 +02007871 if (ver <= CONPTY_1903_BUILD)
7872 conpty_type = 2;
7873 if (ver < CONPTY_FIRST_SUPPORT_BUILD)
7874 conpty_type = 1;
Bram Moolenaar7ed8f592020-04-28 20:44:42 +02007875
7876 if (ver >= CONPTY_NEXT_UPDATE_BUILD)
7877 conpty_fix_type = 1;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007878}
7879
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007880#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL) || defined(PROTO)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007881
7882 static void
7883vtp_init(void)
7884{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007885 HMODULE hKerneldll;
7886 DYN_CONSOLE_SCREEN_BUFFER_INFOEX csbi;
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007887# ifdef FEAT_TERMGUICOLORS
Yasuhiro Matsumotoaa04e1b2022-05-07 14:09:19 +01007888 COLORREF fg;
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007889# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007890
Bram Moolenaar0f873732019-12-05 20:28:46 +01007891 // Use functions supported from Vista
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007892 hKerneldll = GetModuleHandle("kernel32.dll");
7893 if (hKerneldll != NULL)
7894 {
7895 pGetConsoleScreenBufferInfoEx =
7896 (PfnGetConsoleScreenBufferInfoEx)GetProcAddress(
7897 hKerneldll, "GetConsoleScreenBufferInfoEx");
7898 pSetConsoleScreenBufferInfoEx =
7899 (PfnSetConsoleScreenBufferInfoEx)GetProcAddress(
7900 hKerneldll, "SetConsoleScreenBufferInfoEx");
7901 if (pGetConsoleScreenBufferInfoEx != NULL
7902 && pSetConsoleScreenBufferInfoEx != NULL)
7903 has_csbiex = TRUE;
7904 }
7905
7906 csbi.cbSize = sizeof(csbi);
7907 if (has_csbiex)
7908 pGetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007909 save_console_bg_rgb = (guicolor_T)csbi.ColorTable[g_color_index_bg];
7910 save_console_fg_rgb = (guicolor_T)csbi.ColorTable[g_color_index_fg];
Bram Moolenaardf543822020-01-30 11:53:59 +01007911 store_console_bg_rgb = save_console_bg_rgb;
7912 store_console_fg_rgb = save_console_fg_rgb;
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007913
7914# ifdef FEAT_TERMGUICOLORS
Yasuhiro Matsumotoe42c8da2022-09-01 11:31:45 +01007915 if (!USE_WT)
7916 {
7917 COLORREF bg;
7918 bg = (COLORREF)csbi.ColorTable[g_color_index_bg];
7919 bg = (GetRValue(bg) << 16) | (GetGValue(bg) << 8) | GetBValue(bg);
7920 default_console_color_bg = bg;
7921 }
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007922 fg = (COLORREF)csbi.ColorTable[g_color_index_fg];
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007923 fg = (GetRValue(fg) << 16) | (GetGValue(fg) << 8) | GetBValue(fg);
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007924 default_console_color_fg = fg;
Bram Moolenaarc4568ab2018-11-16 16:21:05 +01007925# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007926
7927 set_console_color_rgb();
7928}
7929
7930 static void
7931vtp_exit(void)
7932{
Bram Moolenaardf543822020-01-30 11:53:59 +01007933 restore_console_color_rgb();
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007934}
7935
Bram Moolenaar06b7b582020-05-30 17:49:25 +02007936 int
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007937vtp_printf(
7938 char *format,
7939 ...)
7940{
7941 char_u buf[100];
7942 va_list list;
7943 DWORD result;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007944 int len;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007945
7946 va_start(list, format);
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007947 len = vim_vsnprintf((char *)buf, 100, (char *)format, list);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007948 va_end(list);
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007949 WriteConsoleA(g_hConOut, buf, (DWORD)len, &result, NULL);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007950 return (int)result;
7951}
7952
7953 static void
7954vtp_sgr_bulk(
7955 int arg)
7956{
7957 int args[1];
7958
7959 args[0] = arg;
7960 vtp_sgr_bulks(1, args);
7961}
7962
K.Takata6e1d31e2022-02-03 13:05:32 +00007963# define FAST256(x) \
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007964 if ((*p-- = "0123456789"[(n = x % 10)]) \
7965 && x >= 10 && (*p-- = "0123456789"[((m = x % 100) - n) / 10]) \
7966 && x >= 100 && (*p-- = "012"[((x & 0xff) - m) / 100]));
7967
K.Takata6e1d31e2022-02-03 13:05:32 +00007968# define FAST256CASE(x) \
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007969 case x: \
7970 FAST256(newargs[x - 1]);
7971
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007972 static void
7973vtp_sgr_bulks(
7974 int argc,
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007975 int *args)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007976{
K.Takata6e1d31e2022-02-03 13:05:32 +00007977# define MAXSGR 16
7978# define SGRBUFSIZE 2 + 4 * MAXSGR + 1 // '\033[' + SGR + 'm'
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007979 char_u buf[SGRBUFSIZE];
7980 char_u *p;
7981 int in, out;
7982 int newargs[16];
7983 static int sgrfgr = -1, sgrfgg, sgrfgb;
7984 static int sgrbgr = -1, sgrbgg, sgrbgb;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007985
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007986 if (argc == 0)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007987 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007988 sgrfgr = sgrbgr = -1;
K.Takatadf5320c2022-09-01 13:20:16 +01007989 vtp_printf("\033[m");
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007990 return;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007991 }
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007992
7993 in = out = 0;
7994 while (in < argc)
7995 {
7996 int s = args[in];
7997 int copylen = 1;
7998
7999 if (s == 38)
8000 {
8001 if (argc - in >= 5 && args[in + 1] == 2)
8002 {
8003 if (sgrfgr == args[in + 2] && sgrfgg == args[in + 3]
8004 && sgrfgb == args[in + 4])
8005 {
8006 in += 5;
8007 copylen = 0;
8008 }
8009 else
8010 {
8011 sgrfgr = args[in + 2];
8012 sgrfgg = args[in + 3];
8013 sgrfgb = args[in + 4];
8014 copylen = 5;
8015 }
8016 }
8017 else if (argc - in >= 3 && args[in + 1] == 5)
8018 {
8019 sgrfgr = -1;
8020 copylen = 3;
8021 }
8022 }
8023 else if (s == 48)
8024 {
8025 if (argc - in >= 5 && args[in + 1] == 2)
8026 {
8027 if (sgrbgr == args[in + 2] && sgrbgg == args[in + 3]
8028 && sgrbgb == args[in + 4])
8029 {
8030 in += 5;
8031 copylen = 0;
8032 }
8033 else
8034 {
8035 sgrbgr = args[in + 2];
8036 sgrbgg = args[in + 3];
8037 sgrbgb = args[in + 4];
8038 copylen = 5;
8039 }
8040 }
8041 else if (argc - in >= 3 && args[in + 1] == 5)
8042 {
8043 sgrbgr = -1;
8044 copylen = 3;
8045 }
8046 }
8047 else if (30 <= s && s <= 39)
8048 sgrfgr = -1;
8049 else if (90 <= s && s <= 97)
8050 sgrfgr = -1;
8051 else if (40 <= s && s <= 49)
8052 sgrbgr = -1;
8053 else if (100 <= s && s <= 107)
8054 sgrbgr = -1;
8055 else if (s == 0)
8056 sgrfgr = sgrbgr = -1;
8057
8058 while (copylen--)
8059 newargs[out++] = args[in++];
8060 }
8061
8062 p = &buf[sizeof(buf) - 1];
8063 *p-- = 'm';
8064
8065 switch (out)
8066 {
8067 int n, m;
8068 DWORD r;
8069
8070 FAST256CASE(16);
8071 *p-- = ';';
8072 FAST256CASE(15);
8073 *p-- = ';';
8074 FAST256CASE(14);
8075 *p-- = ';';
8076 FAST256CASE(13);
8077 *p-- = ';';
8078 FAST256CASE(12);
8079 *p-- = ';';
8080 FAST256CASE(11);
8081 *p-- = ';';
8082 FAST256CASE(10);
8083 *p-- = ';';
8084 FAST256CASE(9);
8085 *p-- = ';';
8086 FAST256CASE(8);
8087 *p-- = ';';
8088 FAST256CASE(7);
8089 *p-- = ';';
8090 FAST256CASE(6);
8091 *p-- = ';';
8092 FAST256CASE(5);
8093 *p-- = ';';
8094 FAST256CASE(4);
8095 *p-- = ';';
8096 FAST256CASE(3);
8097 *p-- = ';';
8098 FAST256CASE(2);
8099 *p-- = ';';
8100 FAST256CASE(1);
8101 *p-- = '[';
8102 *p = '\033';
8103 WriteConsoleA(g_hConOut, p, (DWORD)(&buf[SGRBUFSIZE] - p), &r, NULL);
8104 default:
8105 break;
8106 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008107}
8108
Bram Moolenaar06b7b582020-05-30 17:49:25 +02008109 static void
8110wt_init(void)
8111{
8112 wt_working = (mch_getenv("WT_SESSION") != NULL);
8113}
8114
8115 int
8116use_wt(void)
8117{
8118 return USE_WT;
8119}
8120
Bram Moolenaar8a938af2018-05-01 17:30:41 +02008121# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02008122 static int
8123ctermtoxterm(
8124 int cterm)
8125{
Bram Moolenaar9894e392018-05-05 14:29:06 +02008126 char_u r, g, b, idx;
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02008127
8128 cterm_color2rgb(cterm, &r, &g, &b, &idx);
8129 return (((int)r << 16) | ((int)g << 8) | (int)b);
8130}
Bram Moolenaar8a938af2018-05-01 17:30:41 +02008131# endif
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02008132
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008133 static void
8134set_console_color_rgb(void)
8135{
8136# ifdef FEAT_TERMGUICOLORS
8137 DYN_CONSOLE_SCREEN_BUFFER_INFOEX csbi;
Bram Moolenaara050b942019-12-02 21:35:31 +01008138 guicolor_T fg, bg;
8139 int ctermfg, ctermbg;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008140
8141 if (!USE_VTP)
8142 return;
8143
Bram Moolenaara050b942019-12-02 21:35:31 +01008144 get_default_console_color(&ctermfg, &ctermbg, &fg, &bg);
8145
Bram Moolenaar06b7b582020-05-30 17:49:25 +02008146 if (USE_WT)
8147 {
8148 term_fg_rgb_color(fg);
8149 term_bg_rgb_color(bg);
8150 return;
8151 }
8152
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008153 fg = (GetRValue(fg) << 16) | (GetGValue(fg) << 8) | GetBValue(fg);
8154 bg = (GetRValue(bg) << 16) | (GetGValue(bg) << 8) | GetBValue(bg);
8155
8156 csbi.cbSize = sizeof(csbi);
8157 if (has_csbiex)
8158 pGetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
8159
8160 csbi.cbSize = sizeof(csbi);
8161 csbi.srWindow.Right += 1;
8162 csbi.srWindow.Bottom += 1;
Bram Moolenaardf543822020-01-30 11:53:59 +01008163 store_console_bg_rgb = csbi.ColorTable[g_color_index_bg];
8164 store_console_fg_rgb = csbi.ColorTable[g_color_index_fg];
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02008165 csbi.ColorTable[g_color_index_bg] = (COLORREF)bg;
8166 csbi.ColorTable[g_color_index_fg] = (COLORREF)fg;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008167 if (has_csbiex)
8168 pSetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
8169# endif
8170}
8171
Bram Moolenaara050b942019-12-02 21:35:31 +01008172# if defined(FEAT_TERMGUICOLORS) || defined(PROTO)
8173 void
8174get_default_console_color(
8175 int *cterm_fg,
8176 int *cterm_bg,
8177 guicolor_T *gui_fg,
8178 guicolor_T *gui_bg)
8179{
8180 int id;
8181 guicolor_T guifg = INVALCOLOR;
8182 guicolor_T guibg = INVALCOLOR;
8183 int ctermfg = 0;
8184 int ctermbg = 0;
8185
8186 id = syn_name2id((char_u *)"Normal");
8187 if (id > 0 && p_tgc)
8188 syn_id2colors(id, &guifg, &guibg);
8189 if (guifg == INVALCOLOR)
8190 {
8191 ctermfg = -1;
8192 if (id > 0)
8193 syn_id2cterm_bg(id, &ctermfg, &ctermbg);
8194 guifg = ctermfg != -1 ? ctermtoxterm(ctermfg)
8195 : default_console_color_fg;
8196 cterm_normal_fg_gui_color = guifg;
8197 ctermfg = ctermfg < 0 ? 0 : ctermfg;
8198 }
8199 if (guibg == INVALCOLOR)
8200 {
8201 ctermbg = -1;
8202 if (id > 0)
8203 syn_id2cterm_bg(id, &ctermfg, &ctermbg);
K.Takatae53a0d42022-09-05 21:45:11 +01008204 if (USE_WT)
Yasuhiro Matsumotoe42c8da2022-09-01 11:31:45 +01008205 {
8206 cterm_normal_bg_gui_color = guibg =
Yasuhiro Matsumotoaa04e1b2022-05-07 14:09:19 +01008207 ctermbg != -1 ? ctermtoxterm(ctermbg) : INVALCOLOR;
Yasuhiro Matsumotoe42c8da2022-09-01 11:31:45 +01008208 if (ctermbg < 0)
8209 ctermbg = 0;
8210 }
K.Takatae53a0d42022-09-05 21:45:11 +01008211 else
8212 {
8213 guibg = ctermbg != -1 ? ctermtoxterm(ctermbg)
8214 : default_console_color_bg;
8215 cterm_normal_bg_gui_color = guibg;
8216 ctermbg = ctermbg < 0 ? 0 : ctermbg;
8217 }
Bram Moolenaara050b942019-12-02 21:35:31 +01008218 }
8219
8220 *cterm_fg = ctermfg;
8221 *cterm_bg = ctermbg;
8222 *gui_fg = guifg;
8223 *gui_bg = guibg;
8224}
8225# endif
8226
Bram Moolenaardf543822020-01-30 11:53:59 +01008227/*
8228 * Set the console colors to the original colors or the last set colors.
8229 */
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008230 static void
8231reset_console_color_rgb(void)
8232{
8233# ifdef FEAT_TERMGUICOLORS
8234 DYN_CONSOLE_SCREEN_BUFFER_INFOEX csbi;
8235
Bram Moolenaar06b7b582020-05-30 17:49:25 +02008236 if (USE_WT)
8237 return;
8238
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008239 csbi.cbSize = sizeof(csbi);
8240 if (has_csbiex)
8241 pGetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
8242
8243 csbi.cbSize = sizeof(csbi);
8244 csbi.srWindow.Right += 1;
8245 csbi.srWindow.Bottom += 1;
Bram Moolenaardf543822020-01-30 11:53:59 +01008246 csbi.ColorTable[g_color_index_bg] = (COLORREF)store_console_bg_rgb;
8247 csbi.ColorTable[g_color_index_fg] = (COLORREF)store_console_fg_rgb;
8248 if (has_csbiex)
8249 pSetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
8250# endif
8251}
8252
8253/*
8254 * Set the console colors to the original colors.
8255 */
8256 static void
8257restore_console_color_rgb(void)
8258{
8259# ifdef FEAT_TERMGUICOLORS
8260 DYN_CONSOLE_SCREEN_BUFFER_INFOEX csbi;
8261
8262 csbi.cbSize = sizeof(csbi);
8263 if (has_csbiex)
8264 pGetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
8265
8266 csbi.cbSize = sizeof(csbi);
8267 csbi.srWindow.Right += 1;
8268 csbi.srWindow.Bottom += 1;
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02008269 csbi.ColorTable[g_color_index_bg] = (COLORREF)save_console_bg_rgb;
8270 csbi.ColorTable[g_color_index_fg] = (COLORREF)save_console_fg_rgb;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008271 if (has_csbiex)
8272 pSetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
8273# endif
8274}
8275
8276 void
8277control_console_color_rgb(void)
8278{
8279 if (USE_VTP)
8280 set_console_color_rgb();
8281 else
8282 reset_console_color_rgb();
8283}
8284
8285 int
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008286use_vtp(void)
8287{
8288 return USE_VTP;
8289}
8290
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02008291 int
8292is_term_win32(void)
8293{
8294 return T_NAME != NULL && STRCMP(T_NAME, "win32") == 0;
8295}
8296
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008297 int
8298has_vtp_working(void)
8299{
8300 return vtp_working;
8301}
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01008302
Bram Moolenaar6902c0e2019-02-16 14:07:37 +01008303#endif
8304
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01008305 int
8306has_conpty_working(void)
8307{
8308 return conpty_working;
8309}
8310
8311 int
Bram Moolenaar57da6982019-09-13 22:30:11 +02008312get_conpty_type(void)
8313{
8314 return conpty_type;
8315}
8316
8317 int
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01008318is_conpty_stable(void)
8319{
8320 return conpty_stable;
8321}
Bram Moolenaar78d21da2019-02-17 15:00:52 +01008322
Bram Moolenaar7ed8f592020-04-28 20:44:42 +02008323 int
8324get_conpty_fix_type(void)
8325{
8326 return conpty_fix_type;
8327}
8328
Bram Moolenaarafde13b2019-04-28 19:46:49 +02008329#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL) || defined(PROTO)
Bram Moolenaar78d21da2019-02-17 15:00:52 +01008330 void
8331resize_console_buf(void)
8332{
8333 CONSOLE_SCREEN_BUFFER_INFO csbi;
8334 COORD coord;
8335 SMALL_RECT newsize;
8336
8337 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
8338 {
8339 coord.X = SRWIDTH(csbi.srWindow);
8340 coord.Y = SRHEIGHT(csbi.srWindow);
8341 SetConsoleScreenBufferSize(g_hConOut, coord);
8342
8343 newsize.Left = 0;
8344 newsize.Top = 0;
8345 newsize.Right = coord.X - 1;
8346 newsize.Bottom = coord.Y - 1;
8347 SetConsoleWindowInfo(g_hConOut, TRUE, &newsize);
8348
8349 SetConsoleScreenBufferSize(g_hConOut, coord);
8350 }
8351}
8352#endif
Martin Tournoij1a3e5742021-07-24 13:57:29 +02008353
8354 char *
8355GetWin32Error(void)
8356{
K.Takatad68b2fc2022-02-12 11:18:37 +00008357 static char *oldmsg = NULL;
Martin Tournoij1a3e5742021-07-24 13:57:29 +02008358 char *msg = NULL;
K.Takatad68b2fc2022-02-12 11:18:37 +00008359
Martin Tournoij1a3e5742021-07-24 13:57:29 +02008360 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER|FORMAT_MESSAGE_FROM_SYSTEM,
8361 NULL, GetLastError(), 0, (LPSTR)&msg, 0, NULL);
K.Takatad68b2fc2022-02-12 11:18:37 +00008362 if (oldmsg != NULL)
8363 LocalFree(oldmsg);
Martin Tournoij1a3e5742021-07-24 13:57:29 +02008364 if (msg != NULL)
8365 {
8366 // remove trailing \r\n
8367 char *pcrlf = strstr(msg, "\r\n");
8368 if (pcrlf != NULL)
8369 *pcrlf = '\0';
K.Takatad68b2fc2022-02-12 11:18:37 +00008370 oldmsg = msg;
Martin Tournoij1a3e5742021-07-24 13:57:29 +02008371 }
8372 return msg;
8373}
Paul Ollis65745772022-06-05 16:55:54 +01008374
8375#if defined(FEAT_RELTIME) || defined(PROTO)
8376static HANDLE timer_handle;
8377static int timer_active = FALSE;
8378
8379/*
8380 * Calls to start_timeout alternate the return value pointer between the two
8381 * entries in timeout_flags. If the previously active timeout is very close to
8382 * expiring when start_timeout() is called then a race condition means that the
8383 * set_flag() function may still be invoked after the previous timer is
8384 * deleted. Ping-ponging between the two flags prevents this causing 'fake'
8385 * timeouts.
8386 */
Bram Moolenaar155f2d12022-06-20 13:38:33 +01008387static sig_atomic_t timeout_flags[2];
8388static int timeout_flag_idx = 0;
8389static sig_atomic_t *timeout_flag = &timeout_flags[0];
Paul Ollis65745772022-06-05 16:55:54 +01008390
8391
8392 static void CALLBACK
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +01008393set_flag(void *param, BOOLEAN unused2 UNUSED)
Paul Ollis65745772022-06-05 16:55:54 +01008394{
8395 int *timeout_flag = (int *)param;
8396
8397 *timeout_flag = TRUE;
8398}
8399
8400/*
8401 * Stop any active timeout.
8402 */
8403 void
8404stop_timeout(void)
8405{
8406 if (timer_active)
8407 {
8408 BOOL ret = DeleteTimerQueueTimer(NULL, timer_handle, NULL);
8409 timer_active = FALSE;
8410 if (!ret && GetLastError() != ERROR_IO_PENDING)
8411 {
8412 semsg(_(e_could_not_clear_timeout_str), GetWin32Error());
8413 }
8414 }
8415 *timeout_flag = FALSE;
8416}
8417
8418/*
8419 * Start the timeout timer.
8420 *
8421 * The period is defined in milliseconds.
8422 *
8423 * The return value is a pointer to a flag that is initialised to 0. If the
8424 * timeout expires, the flag is set to 1. This will only return pointers to
8425 * static memory; i.e. any pointer returned by this function may always be
8426 * safely dereferenced.
8427 *
8428 * This function is not expected to fail, but if it does it still returns a
8429 * valid flag pointer; the flag will remain stuck at zero.
8430 */
Bram Moolenaar155f2d12022-06-20 13:38:33 +01008431 volatile sig_atomic_t *
Paul Ollis65745772022-06-05 16:55:54 +01008432start_timeout(long msec)
8433{
Paul Ollis65745772022-06-05 16:55:54 +01008434 BOOL ret;
8435
Bram Moolenaar1f30caf2022-06-19 14:36:35 +01008436 timeout_flag = &timeout_flags[timeout_flag_idx];
Paul Ollis65745772022-06-05 16:55:54 +01008437
8438 stop_timeout();
8439 ret = CreateTimerQueueTimer(
8440 &timer_handle, NULL, set_flag, timeout_flag,
8441 (DWORD)msec, 0, WT_EXECUTEDEFAULT);
8442 if (!ret)
8443 {
8444 semsg(_(e_could_not_set_timeout_str), GetWin32Error());
8445 }
8446 else
8447 {
Bram Moolenaar1f30caf2022-06-19 14:36:35 +01008448 timeout_flag_idx = (timeout_flag_idx + 1) % 2;
Paul Ollis65745772022-06-05 16:55:54 +01008449 timer_active = TRUE;
8450 *timeout_flag = FALSE;
8451 }
8452 return timeout_flag;
8453}
8454#endif