blob: b5ded95d597fc61cbe8b7b28483cd81cf77cbb94 [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 Moolenaarcafafb32018-02-22 21:07:09 +0100246/*
247 * Get version number including build number
248 */
249typedef BOOL (WINAPI *PfnRtlGetVersion)(LPOSVERSIONINFOW);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100250#define MAKE_VER(major, minor, build) \
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100251 (((major) << 24) | ((minor) << 16) | (build))
252
253 static DWORD
254get_build_number(void)
255{
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +0100256 OSVERSIONINFOW osver;
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100257 HMODULE hNtdll;
258 PfnRtlGetVersion pRtlGetVersion;
259 DWORD ver = MAKE_VER(0, 0, 0);
260
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +0100261 osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFOW);
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100262 hNtdll = GetModuleHandle("ntdll.dll");
263 if (hNtdll != NULL)
264 {
265 pRtlGetVersion =
266 (PfnRtlGetVersion)GetProcAddress(hNtdll, "RtlGetVersion");
267 pRtlGetVersion(&osver);
268 ver = MAKE_VER(min(osver.dwMajorVersion, 255),
269 min(osver.dwMinorVersion, 255),
270 min(osver.dwBuildNumber, 32767));
271 }
272 return ver;
273}
274
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200275#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200276 static BOOL
277is_ambiwidth_event(
278 INPUT_RECORD *ir)
279{
280 return ir->EventType == KEY_EVENT
281 && ir->Event.KeyEvent.bKeyDown
282 && ir->Event.KeyEvent.wRepeatCount == 1
283 && ir->Event.KeyEvent.wVirtualKeyCode == 0x12
284 && ir->Event.KeyEvent.wVirtualScanCode == 0x38
K.Takata972db232022-02-04 10:45:38 +0000285 && ir->Event.KeyEvent.uChar.UnicodeChar == 0
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200286 && ir->Event.KeyEvent.dwControlKeyState == 2;
287}
288
289 static void
290make_ambiwidth_event(
291 INPUT_RECORD *down,
292 INPUT_RECORD *up)
293{
294 down->Event.KeyEvent.wVirtualKeyCode = 0;
295 down->Event.KeyEvent.wVirtualScanCode = 0;
K.Takata972db232022-02-04 10:45:38 +0000296 down->Event.KeyEvent.uChar.UnicodeChar
297 = up->Event.KeyEvent.uChar.UnicodeChar;
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200298 down->Event.KeyEvent.dwControlKeyState = 0;
299}
300
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100301/*
302 * Version of ReadConsoleInput() that works with IME.
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100303 * Works around problems on Windows 8.
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100304 */
305 static BOOL
306read_console_input(
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100307 HANDLE hInput,
308 INPUT_RECORD *lpBuffer,
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +0100309 int nLength,
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100310 LPDWORD lpEvents)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100311{
312 enum
313 {
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100314 IRSIZE = 10
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100315 };
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100316 static INPUT_RECORD s_irCache[IRSIZE];
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100317 static DWORD s_dwIndex = 0;
318 static DWORD s_dwMax = 0;
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100319 DWORD dwEvents;
Bram Moolenaardd415a62014-02-05 14:02:27 +0100320 int head;
321 int tail;
322 int i;
Bram Moolenaarbc970da2020-04-26 19:00:07 +0200323 static INPUT_RECORD s_irPseudo;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100324
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200325 if (nLength == -2)
326 return (s_dwMax > 0) ? TRUE : FALSE;
327
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100328 if (!win8_or_later)
329 {
330 if (nLength == -1)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200331 return PeekConsoleInputW(hInput, lpBuffer, 1, lpEvents);
332 return ReadConsoleInputW(hInput, lpBuffer, 1, &dwEvents);
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100333 }
334
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100335 if (s_dwMax == 0)
336 {
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200337 if (!USE_WT && nLength == -1)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200338 return PeekConsoleInputW(hInput, lpBuffer, 1, lpEvents);
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200339 GetNumberOfConsoleInputEvents(hInput, &dwEvents);
340 if (dwEvents == 0 && nLength == -1)
341 return PeekConsoleInputW(hInput, lpBuffer, 1, lpEvents);
342 ReadConsoleInputW(hInput, s_irCache, IRSIZE, &dwEvents);
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100343 s_dwIndex = 0;
344 s_dwMax = dwEvents;
345 if (dwEvents == 0)
346 {
347 *lpEvents = 0;
348 return TRUE;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100349 }
Bram Moolenaardd415a62014-02-05 14:02:27 +0100350
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200351 for (i = s_dwIndex; i < (int)s_dwMax - 1; ++i)
352 if (is_ambiwidth_event(&s_irCache[i]))
353 make_ambiwidth_event(&s_irCache[i], &s_irCache[i + 1]);
354
Bram Moolenaardd415a62014-02-05 14:02:27 +0100355 if (s_dwMax > 1)
356 {
357 head = 0;
358 tail = s_dwMax - 1;
359 while (head != tail)
360 {
361 if (s_irCache[head].EventType == WINDOW_BUFFER_SIZE_EVENT
362 && s_irCache[head + 1].EventType
363 == WINDOW_BUFFER_SIZE_EVENT)
364 {
Bram Moolenaar0f873732019-12-05 20:28:46 +0100365 // Remove duplicate event to avoid flicker.
Bram Moolenaardd415a62014-02-05 14:02:27 +0100366 for (i = head; i < tail; ++i)
367 s_irCache[i] = s_irCache[i + 1];
368 --tail;
369 continue;
370 }
371 head++;
372 }
373 s_dwMax = tail + 1;
374 }
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100375 }
Bram Moolenaardd415a62014-02-05 14:02:27 +0100376
Bram Moolenaarbc970da2020-04-26 19:00:07 +0200377 if (s_irCache[s_dwIndex].EventType == KEY_EVENT)
378 {
379 if (s_irCache[s_dwIndex].Event.KeyEvent.wRepeatCount > 1)
380 {
381 s_irPseudo = s_irCache[s_dwIndex];
382 s_irPseudo.Event.KeyEvent.wRepeatCount = 1;
383 s_irCache[s_dwIndex].Event.KeyEvent.wRepeatCount--;
384 *lpBuffer = s_irPseudo;
385 *lpEvents = 1;
386 return TRUE;
387 }
388 }
389
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100390 *lpBuffer = s_irCache[s_dwIndex];
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200391 if (!(nLength == -1 || nLength == -2) && ++s_dwIndex >= s_dwMax)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100392 s_dwMax = 0;
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100393 *lpEvents = 1;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100394 return TRUE;
395}
396
397/*
398 * Version of PeekConsoleInput() that works with IME.
399 */
400 static BOOL
401peek_console_input(
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100402 HANDLE hInput,
403 INPUT_RECORD *lpBuffer,
Bram Moolenaarbd67aac2019-09-21 23:09:04 +0200404 DWORD nLength UNUSED,
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100405 LPDWORD lpEvents)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100406{
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +0100407 return read_console_input(hInput, lpBuffer, -1, lpEvents);
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100408}
409
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100410# ifdef FEAT_CLIENTSERVER
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200411 static DWORD
412msg_wait_for_multiple_objects(
413 DWORD nCount,
414 LPHANDLE pHandles,
415 BOOL fWaitAll,
416 DWORD dwMilliseconds,
417 DWORD dwWakeMask)
418{
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +0100419 if (read_console_input(NULL, NULL, -2, NULL))
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200420 return WAIT_OBJECT_0;
421 return MsgWaitForMultipleObjects(nCount, pHandles, fWaitAll,
422 dwMilliseconds, dwWakeMask);
423}
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100424# endif
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200425
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100426# ifndef FEAT_CLIENTSERVER
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200427 static DWORD
428wait_for_single_object(
429 HANDLE hHandle,
430 DWORD dwMilliseconds)
431{
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +0100432 if (read_console_input(NULL, NULL, -2, NULL))
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200433 return WAIT_OBJECT_0;
434 return WaitForSingleObject(hHandle, dwMilliseconds);
435}
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100436# endif
437#endif
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200438
Bram Moolenaar071d4272004-06-13 20:20:40 +0000439 static void
440get_exe_name(void)
441{
Bram Moolenaar0f873732019-12-05 20:28:46 +0100442 // Maximum length of $PATH is more than MAXPATHL. 8191 is often mentioned
443 // as the maximum length that works (plus a NUL byte).
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100444#define MAX_ENV_PATH_LEN 8192
445 char temp[MAX_ENV_PATH_LEN];
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200446 char_u *p;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000447
448 if (exe_name == NULL)
449 {
Bram Moolenaar0f873732019-12-05 20:28:46 +0100450 // store the name of the executable, may be used for $VIM
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100451 GetModuleFileName(NULL, temp, MAX_ENV_PATH_LEN - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000452 if (*temp != NUL)
453 exe_name = FullName_save((char_u *)temp, FALSE);
454 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000455
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200456 if (exe_path == NULL && exe_name != NULL)
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000457 {
Bram Moolenaar71ccd032020-06-12 22:59:11 +0200458 exe_path = vim_strnsave(exe_name, gettail_sep(exe_name) - exe_name);
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200459 if (exe_path != NULL)
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000460 {
Bram Moolenaar0f873732019-12-05 20:28:46 +0100461 // Append our starting directory to $PATH, so that when doing
462 // "!xxd" it's found in our starting directory. Needed because
463 // SearchPath() also looks there.
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200464 p = mch_getenv("PATH");
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100465 if (p == NULL
466 || STRLEN(p) + STRLEN(exe_path) + 2 < MAX_ENV_PATH_LEN)
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200467 {
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100468 if (p == NULL || *p == NUL)
469 temp[0] = NUL;
470 else
471 {
472 STRCPY(temp, p);
473 STRCAT(temp, ";");
474 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200475 STRCAT(temp, exe_path);
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +0100476 vim_setenv((char_u *)"PATH", (char_u *)temp);
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200477 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000478 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000479 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000480}
481
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200482/*
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100483 * Unescape characters in "p" that appear in "escaped".
484 */
485 static void
486unescape_shellxquote(char_u *p, char_u *escaped)
487{
Bram Moolenaar4336cdf2012-02-29 13:58:47 +0100488 int l = (int)STRLEN(p);
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100489 int n;
490
491 while (*p != NUL)
492 {
493 if (*p == '^' && vim_strchr(escaped, p[1]) != NULL)
494 mch_memmove(p, p + 1, l--);
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100495 n = (*mb_ptr2len)(p);
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100496 p += n;
497 l -= n;
498 }
499}
500
501/*
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200502 * Load library "name".
503 */
504 HINSTANCE
K.Takatad68b2fc2022-02-12 11:18:37 +0000505vimLoadLib(const char *name)
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200506{
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200507 HINSTANCE dll = NULL;
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200508
Bram Moolenaar3d0e7a92021-05-01 17:46:03 +0200509 // No need to load any library when registering OLE.
510 if (found_register_arg)
511 return dll;
512
Bram Moolenaar0f873732019-12-05 20:28:46 +0100513 // NOTE: Do not use mch_dirname() and mch_chdir() here, they may call
514 // vimLoadLib() recursively, which causes a stack overflow.
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200515 if (exe_path == NULL)
516 get_exe_name();
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200517 if (exe_path != NULL)
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200518 {
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200519 WCHAR old_dirw[MAXPATHL];
520
521 if (GetCurrentDirectoryW(MAXPATHL, old_dirw) != 0)
522 {
Bram Moolenaar0f873732019-12-05 20:28:46 +0100523 // Change directory to where the executable is, both to make
524 // sure we find a .dll there and to avoid looking for a .dll
525 // in the current directory.
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +0100526 SetCurrentDirectory((LPCSTR)exe_path);
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200527 dll = LoadLibrary(name);
528 SetCurrentDirectoryW(old_dirw);
529 return dll;
530 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200531 }
532 return dll;
533}
534
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200535#if defined(VIMDLL) || defined(PROTO)
536/*
537 * Check if the current executable file is for the GUI subsystem.
538 */
539 int
540mch_is_gui_executable(void)
541{
542 PBYTE pImage = (PBYTE)GetModuleHandle(NULL);
543 PIMAGE_DOS_HEADER pDOS = (PIMAGE_DOS_HEADER)pImage;
544 PIMAGE_NT_HEADERS pPE;
545
546 if (pDOS->e_magic != IMAGE_DOS_SIGNATURE)
547 return FALSE;
548 pPE = (PIMAGE_NT_HEADERS)(pImage + pDOS->e_lfanew);
549 if (pPE->Signature != IMAGE_NT_SIGNATURE)
550 return FALSE;
551 if (pPE->OptionalHeader.Subsystem == IMAGE_SUBSYSTEM_WINDOWS_GUI)
552 return TRUE;
553 return FALSE;
554}
555#endif
556
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000557#if defined(DYNAMIC_ICONV) || defined(DYNAMIC_GETTEXT) \
558 || defined(FEAT_PYTHON3) || defined(PROTO)
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100559/*
560 * Get related information about 'funcname' which is imported by 'hInst'.
561 * If 'info' is 0, return the function address.
562 * If 'info' is 1, return the module name which the function is imported from.
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000563 * If 'info' is 2, hook the function with 'ptr', and return the original
564 * function address.
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100565 */
566 static void *
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000567get_imported_func_info(HINSTANCE hInst, const char *funcname, int info,
568 const void *ptr)
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100569{
570 PBYTE pImage = (PBYTE)hInst;
571 PIMAGE_DOS_HEADER pDOS = (PIMAGE_DOS_HEADER)hInst;
572 PIMAGE_NT_HEADERS pPE;
573 PIMAGE_IMPORT_DESCRIPTOR pImpDesc;
Bram Moolenaar0f873732019-12-05 20:28:46 +0100574 PIMAGE_THUNK_DATA pIAT; // Import Address Table
575 PIMAGE_THUNK_DATA pINT; // Import Name Table
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100576 PIMAGE_IMPORT_BY_NAME pImpName;
577
578 if (pDOS->e_magic != IMAGE_DOS_SIGNATURE)
579 return NULL;
580 pPE = (PIMAGE_NT_HEADERS)(pImage + pDOS->e_lfanew);
581 if (pPE->Signature != IMAGE_NT_SIGNATURE)
582 return NULL;
583 pImpDesc = (PIMAGE_IMPORT_DESCRIPTOR)(pImage
584 + pPE->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT]
585 .VirtualAddress);
586 for (; pImpDesc->FirstThunk; ++pImpDesc)
587 {
588 if (!pImpDesc->OriginalFirstThunk)
589 continue;
590 pIAT = (PIMAGE_THUNK_DATA)(pImage + pImpDesc->FirstThunk);
591 pINT = (PIMAGE_THUNK_DATA)(pImage + pImpDesc->OriginalFirstThunk);
592 for (; pIAT->u1.Function; ++pIAT, ++pINT)
593 {
594 if (IMAGE_SNAP_BY_ORDINAL(pINT->u1.Ordinal))
595 continue;
596 pImpName = (PIMAGE_IMPORT_BY_NAME)(pImage
597 + (UINT_PTR)(pINT->u1.AddressOfData));
598 if (strcmp((char *)pImpName->Name, funcname) == 0)
599 {
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000600 void *original;
601 DWORD old, new = PAGE_READWRITE;
602
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100603 switch (info)
604 {
605 case 0:
606 return (void *)pIAT->u1.Function;
607 case 1:
608 return (void *)(pImage + pImpDesc->Name);
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000609 case 2:
610 original = (void *)pIAT->u1.Function;
611 VirtualProtect(&pIAT->u1.Function, sizeof(void *),
612 new, &old);
613 pIAT->u1.Function = (UINT_PTR)ptr;
614 VirtualProtect(&pIAT->u1.Function, sizeof(void *),
615 old, &new);
616 return original;
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100617 default:
618 return NULL;
619 }
620 }
621 }
622 }
623 return NULL;
624}
625
626/*
627 * Get the module handle which 'funcname' in 'hInst' is imported from.
628 */
629 HINSTANCE
630find_imported_module_by_funcname(HINSTANCE hInst, const char *funcname)
631{
632 char *modulename;
633
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000634 modulename = (char *)get_imported_func_info(hInst, funcname, 1, NULL);
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100635 if (modulename != NULL)
636 return GetModuleHandleA(modulename);
637 return NULL;
638}
639
640/*
641 * Get the address of 'funcname' which is imported by 'hInst' DLL.
642 */
643 void *
644get_dll_import_func(HINSTANCE hInst, const char *funcname)
645{
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000646 return get_imported_func_info(hInst, funcname, 0, NULL);
647}
648
649/*
650 * Hook the function named 'funcname' which is imported by 'hInst' DLL,
651 * and return the original function address.
652 */
653 void *
654hook_dll_import_func(HINSTANCE hInst, const char *funcname, const void *hook)
655{
656 return get_imported_func_info(hInst, funcname, 2, hook);
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100657}
658#endif
659
Bram Moolenaar071d4272004-06-13 20:20:40 +0000660#if defined(DYNAMIC_GETTEXT) || defined(PROTO)
661# ifndef GETTEXT_DLL
662# define GETTEXT_DLL "libintl.dll"
Bram Moolenaar7554c542018-10-06 15:03:15 +0200663# define GETTEXT_DLL_ALT1 "libintl-8.dll"
664# define GETTEXT_DLL_ALT2 "intl.dll"
Bram Moolenaar071d4272004-06-13 20:20:40 +0000665# endif
Bram Moolenaar0f873732019-12-05 20:28:46 +0100666// Dummy functions
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000667static char *null_libintl_gettext(const char *);
Bram Moolenaaree695f72016-08-03 22:08:45 +0200668static char *null_libintl_ngettext(const char *, const char *, unsigned long n);
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000669static char *null_libintl_textdomain(const char *);
670static char *null_libintl_bindtextdomain(const char *, const char *);
671static char *null_libintl_bind_textdomain_codeset(const char *, const char *);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100672static int null_libintl_wputenv(const wchar_t *);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000673
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200674static HINSTANCE hLibintlDLL = NULL;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000675char *(*dyn_libintl_gettext)(const char *) = null_libintl_gettext;
Bram Moolenaaree695f72016-08-03 22:08:45 +0200676char *(*dyn_libintl_ngettext)(const char *, const char *, unsigned long n)
677 = null_libintl_ngettext;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000678char *(*dyn_libintl_textdomain)(const char *) = null_libintl_textdomain;
679char *(*dyn_libintl_bindtextdomain)(const char *, const char *)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000680 = null_libintl_bindtextdomain;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000681char *(*dyn_libintl_bind_textdomain_codeset)(const char *, const char *)
682 = null_libintl_bind_textdomain_codeset;
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100683int (*dyn_libintl_wputenv)(const wchar_t *) = null_libintl_wputenv;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000684
685 int
Bram Moolenaar05540972016-01-30 20:31:25 +0100686dyn_libintl_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000687{
688 int i;
689 static struct
690 {
691 char *name;
692 FARPROC *ptr;
693 } libintl_entry[] =
694 {
695 {"gettext", (FARPROC*)&dyn_libintl_gettext},
Bram Moolenaaree695f72016-08-03 22:08:45 +0200696 {"ngettext", (FARPROC*)&dyn_libintl_ngettext},
Bram Moolenaar071d4272004-06-13 20:20:40 +0000697 {"textdomain", (FARPROC*)&dyn_libintl_textdomain},
698 {"bindtextdomain", (FARPROC*)&dyn_libintl_bindtextdomain},
699 {NULL, NULL}
700 };
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100701 HINSTANCE hmsvcrt;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000702
Bram Moolenaar7554c542018-10-06 15:03:15 +0200703 // No need to initialize twice.
704 if (hLibintlDLL != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000705 return 1;
Bram Moolenaar7554c542018-10-06 15:03:15 +0200706 // Load gettext library (libintl.dll and other names).
Bram Moolenaar923e43b2016-01-28 15:07:38 +0100707 hLibintlDLL = vimLoadLib(GETTEXT_DLL);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100708# ifdef GETTEXT_DLL_ALT1
Bram Moolenaar286eacd2016-01-16 18:05:50 +0100709 if (!hLibintlDLL)
Bram Moolenaar7554c542018-10-06 15:03:15 +0200710 hLibintlDLL = vimLoadLib(GETTEXT_DLL_ALT1);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100711# endif
712# ifdef GETTEXT_DLL_ALT2
Bram Moolenaar7554c542018-10-06 15:03:15 +0200713 if (!hLibintlDLL)
714 hLibintlDLL = vimLoadLib(GETTEXT_DLL_ALT2);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100715# endif
Bram Moolenaar938ee832016-01-24 15:36:03 +0100716 if (!hLibintlDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000717 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200718 if (p_verbose > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000719 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200720 verbose_enter();
Bram Moolenaar460ae5d2022-01-01 14:19:49 +0000721 semsg(_(e_could_not_load_library_str_str), GETTEXT_DLL, GetWin32Error());
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200722 verbose_leave();
Bram Moolenaar071d4272004-06-13 20:20:40 +0000723 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200724 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000725 }
726 for (i = 0; libintl_entry[i].name != NULL
727 && libintl_entry[i].ptr != NULL; ++i)
728 {
K.Takata54119102022-02-03 13:33:03 +0000729 if ((*libintl_entry[i].ptr = GetProcAddress(hLibintlDLL,
Bram Moolenaar071d4272004-06-13 20:20:40 +0000730 libintl_entry[i].name)) == NULL)
731 {
732 dyn_libintl_end();
733 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +0000734 {
735 verbose_enter();
Bram Moolenaar460ae5d2022-01-01 14:19:49 +0000736 semsg(_(e_could_not_load_library_function_str), libintl_entry[i].name);
Bram Moolenaara04f10b2005-05-31 22:09:46 +0000737 verbose_leave();
738 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000739 return 0;
740 }
741 }
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000742
Bram Moolenaar0f873732019-12-05 20:28:46 +0100743 // The bind_textdomain_codeset() function is optional.
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +0100744 dyn_libintl_bind_textdomain_codeset = (char *(*)(const char *, const char *))
745 GetProcAddress(hLibintlDLL, "bind_textdomain_codeset");
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000746 if (dyn_libintl_bind_textdomain_codeset == NULL)
747 dyn_libintl_bind_textdomain_codeset =
748 null_libintl_bind_textdomain_codeset;
749
Bram Moolenaar0f873732019-12-05 20:28:46 +0100750 // _wputenv() function for the libintl.dll is optional.
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100751 hmsvcrt = find_imported_module_by_funcname(hLibintlDLL, "getenv");
752 if (hmsvcrt != NULL)
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +0100753 dyn_libintl_wputenv = (int (*)(const wchar_t *))
754 GetProcAddress(hmsvcrt, "_wputenv");
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100755 if (dyn_libintl_wputenv == NULL || dyn_libintl_wputenv == _wputenv)
756 dyn_libintl_wputenv = null_libintl_wputenv;
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100757
Bram Moolenaar071d4272004-06-13 20:20:40 +0000758 return 1;
759}
760
761 void
Bram Moolenaar05540972016-01-30 20:31:25 +0100762dyn_libintl_end(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000763{
764 if (hLibintlDLL)
765 FreeLibrary(hLibintlDLL);
766 hLibintlDLL = NULL;
767 dyn_libintl_gettext = null_libintl_gettext;
Bram Moolenaaree695f72016-08-03 22:08:45 +0200768 dyn_libintl_ngettext = null_libintl_ngettext;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000769 dyn_libintl_textdomain = null_libintl_textdomain;
770 dyn_libintl_bindtextdomain = null_libintl_bindtextdomain;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000771 dyn_libintl_bind_textdomain_codeset = null_libintl_bind_textdomain_codeset;
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100772 dyn_libintl_wputenv = null_libintl_wputenv;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000773}
774
775 static char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000776null_libintl_gettext(const char *msgid)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000777{
778 return (char*)msgid;
779}
780
781 static char *
Bram Moolenaaree695f72016-08-03 22:08:45 +0200782null_libintl_ngettext(
783 const char *msgid,
784 const char *msgid_plural,
785 unsigned long n)
786{
Bram Moolenaarc90f2ae2016-08-04 22:00:15 +0200787 return (char *)(n == 1 ? msgid : msgid_plural);
Bram Moolenaaree695f72016-08-03 22:08:45 +0200788}
789
Bram Moolenaaree695f72016-08-03 22:08:45 +0200790 static char *
Bram Moolenaar1266d672017-02-01 13:43:36 +0100791null_libintl_bindtextdomain(
792 const char *domainname UNUSED,
793 const char *dirname UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000794{
795 return NULL;
796}
797
798 static char *
Bram Moolenaar1266d672017-02-01 13:43:36 +0100799null_libintl_bind_textdomain_codeset(
800 const char *domainname UNUSED,
801 const char *codeset UNUSED)
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000802{
803 return NULL;
804}
805
806 static char *
Bram Moolenaar1266d672017-02-01 13:43:36 +0100807null_libintl_textdomain(const char *domainname UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000808{
809 return NULL;
810}
811
Bram Moolenaare0ab9792017-08-02 23:18:25 +0200812 static int
Bram Moolenaar1266d672017-02-01 13:43:36 +0100813null_libintl_wputenv(const wchar_t *envstring UNUSED)
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100814{
815 return 0;
816}
817
Bram Moolenaar0f873732019-12-05 20:28:46 +0100818#endif // DYNAMIC_GETTEXT
Bram Moolenaar071d4272004-06-13 20:20:40 +0000819
Bram Moolenaar0f873732019-12-05 20:28:46 +0100820// This symbol is not defined in older versions of the SDK or Visual C++
Bram Moolenaar071d4272004-06-13 20:20:40 +0000821
822#ifndef VER_PLATFORM_WIN32_WINDOWS
823# define VER_PLATFORM_WIN32_WINDOWS 1
824#endif
825
Bram Moolenaar071d4272004-06-13 20:20:40 +0000826#ifdef HAVE_ACL
Bram Moolenaar82881492012-11-20 16:53:39 +0100827# ifndef PROTO
828# include <aclapi.h>
829# endif
Bram Moolenaar27515922013-06-29 15:36:26 +0200830# ifndef PROTECTED_DACL_SECURITY_INFORMATION
831# define PROTECTED_DACL_SECURITY_INFORMATION 0x80000000L
832# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000833#endif
834
Bram Moolenaar27515922013-06-29 15:36:26 +0200835#ifdef HAVE_ACL
836/*
837 * Enables or disables the specified privilege.
838 */
839 static BOOL
840win32_enable_privilege(LPTSTR lpszPrivilege, BOOL bEnable)
841{
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100842 BOOL bResult;
843 LUID luid;
844 HANDLE hToken;
845 TOKEN_PRIVILEGES tokenPrivileges;
Bram Moolenaar27515922013-06-29 15:36:26 +0200846
847 if (!OpenProcessToken(GetCurrentProcess(),
848 TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
849 return FALSE;
850
851 if (!LookupPrivilegeValue(NULL, lpszPrivilege, &luid))
852 {
853 CloseHandle(hToken);
854 return FALSE;
855 }
856
Bram Moolenaar45500912014-07-09 20:51:07 +0200857 tokenPrivileges.PrivilegeCount = 1;
Bram Moolenaar27515922013-06-29 15:36:26 +0200858 tokenPrivileges.Privileges[0].Luid = luid;
859 tokenPrivileges.Privileges[0].Attributes = bEnable ?
860 SE_PRIVILEGE_ENABLED : 0;
861
862 bResult = AdjustTokenPrivileges(hToken, FALSE, &tokenPrivileges,
863 sizeof(TOKEN_PRIVILEGES), NULL, NULL);
864
865 CloseHandle(hToken);
866
867 return bResult && GetLastError() == ERROR_SUCCESS;
868}
869#endif
870
Bram Moolenaar29d2f452020-12-04 19:42:52 +0100871#ifdef _MSC_VER
872// Suppress the deprecation warning for using GetVersionEx().
873// It is needed for implementing "windowsversion()".
874# pragma warning(push)
875# pragma warning(disable: 4996)
876#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000877/*
Bram Moolenaar1e1d2e82020-05-18 20:17:02 +0200878 * Set "win8_or_later" and fill in "windowsVersion" if possible.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000879 */
880 void
881PlatformId(void)
882{
883 static int done = FALSE;
884
885 if (!done)
886 {
887 OSVERSIONINFO ovi;
888
889 ovi.dwOSVersionInfoSize = sizeof(ovi);
890 GetVersionEx(&ovi);
891
Bram Moolenaar1e1d2e82020-05-18 20:17:02 +0200892#ifdef FEAT_EVAL
Bram Moolenaar0c1e3742019-12-27 13:49:24 +0100893 vim_snprintf(windowsVersion, sizeof(windowsVersion), "%d.%d",
894 (int)ovi.dwMajorVersion, (int)ovi.dwMinorVersion);
Bram Moolenaar1e1d2e82020-05-18 20:17:02 +0200895#endif
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100896 if ((ovi.dwMajorVersion == 6 && ovi.dwMinorVersion >= 2)
897 || ovi.dwMajorVersion > 6)
898 win8_or_later = TRUE;
899
Bram Moolenaar071d4272004-06-13 20:20:40 +0000900#ifdef HAVE_ACL
Bram Moolenaar0f873732019-12-05 20:28:46 +0100901 // Enable privilege for getting or setting SACLs.
Bram Moolenaarcea912a2016-10-12 14:20:24 +0200902 win32_enable_privilege(SE_SECURITY_NAME, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000903#endif
904 done = TRUE;
905 }
906}
Bram Moolenaar29d2f452020-12-04 19:42:52 +0100907#ifdef _MSC_VER
908# pragma warning(pop)
909#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000910
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200911#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000912
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100913# define SHIFT (SHIFT_PRESSED)
914# define CTRL (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED)
915# define ALT (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED)
916# define ALT_GR (RIGHT_ALT_PRESSED | LEFT_CTRL_PRESSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000917
918
Bram Moolenaar0f873732019-12-05 20:28:46 +0100919// When uChar.AsciiChar is 0, then we need to look at wVirtualKeyCode.
920// We map function keys to their ANSI terminal equivalents, as produced
921// by ANSI.SYS, for compatibility with the MS-DOS version of Vim. Any
922// ANSI key with a value >= '\300' is nonstandard, but provided anyway
923// so that the user can have access to all SHIFT-, CTRL-, and ALT-
924// combinations of function/arrow/etc keys.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000925
Bram Moolenaard6f676d2005-06-01 21:51:55 +0000926static const struct
Bram Moolenaar071d4272004-06-13 20:20:40 +0000927{
928 WORD wVirtKey;
929 BOOL fAnsiKey;
930 int chAlone;
931 int chShift;
932 int chCtrl;
933 int chAlt;
934} VirtKeyMap[] =
935{
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200936// Key ANSI alone shift ctrl alt
Bram Moolenaar071d4272004-06-13 20:20:40 +0000937 { VK_ESCAPE,FALSE, ESC, ESC, ESC, ESC, },
938
939 { VK_F1, TRUE, ';', 'T', '^', 'h', },
940 { VK_F2, TRUE, '<', 'U', '_', 'i', },
941 { VK_F3, TRUE, '=', 'V', '`', 'j', },
942 { VK_F4, TRUE, '>', 'W', 'a', 'k', },
943 { VK_F5, TRUE, '?', 'X', 'b', 'l', },
944 { VK_F6, TRUE, '@', 'Y', 'c', 'm', },
945 { VK_F7, TRUE, 'A', 'Z', 'd', 'n', },
946 { VK_F8, TRUE, 'B', '[', 'e', 'o', },
947 { VK_F9, TRUE, 'C', '\\', 'f', 'p', },
948 { VK_F10, TRUE, 'D', ']', 'g', 'q', },
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200949 { VK_F11, TRUE, '\205', '\207', '\211', '\213', },
950 { VK_F12, TRUE, '\206', '\210', '\212', '\214', },
Bram Moolenaar071d4272004-06-13 20:20:40 +0000951
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200952 { VK_HOME, TRUE, 'G', '\302', 'w', '\303', },
953 { VK_UP, TRUE, 'H', '\304', '\305', '\306', },
954 { VK_PRIOR, TRUE, 'I', '\307', '\204', '\310', }, // PgUp
955 { VK_LEFT, TRUE, 'K', '\311', 's', '\312', },
956 { VK_RIGHT, TRUE, 'M', '\313', 't', '\314', },
957 { VK_END, TRUE, 'O', '\315', 'u', '\316', },
958 { VK_DOWN, TRUE, 'P', '\317', '\320', '\321', },
959 { VK_NEXT, TRUE, 'Q', '\322', 'v', '\323', }, // PgDn
960 { VK_INSERT,TRUE, 'R', '\324', '\325', '\326', },
961 { VK_DELETE,TRUE, 'S', '\327', '\330', '\331', },
Bram Moolenaarb70a47b2019-03-30 22:11:21 +0100962 { VK_BACK, TRUE, 'x', 'y', 'z', '{', }, // Backspace
Bram Moolenaar071d4272004-06-13 20:20:40 +0000963
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200964 { VK_SNAPSHOT,TRUE, 0, 0, 0, 'r', }, // PrtScrn
Bram Moolenaar071d4272004-06-13 20:20:40 +0000965
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100966# if 0
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200967 // Most people don't have F13-F20, but what the hell...
968 { VK_F13, TRUE, '\332', '\333', '\334', '\335', },
969 { VK_F14, TRUE, '\336', '\337', '\340', '\341', },
970 { VK_F15, TRUE, '\342', '\343', '\344', '\345', },
971 { VK_F16, TRUE, '\346', '\347', '\350', '\351', },
972 { VK_F17, TRUE, '\352', '\353', '\354', '\355', },
973 { VK_F18, TRUE, '\356', '\357', '\360', '\361', },
974 { VK_F19, TRUE, '\362', '\363', '\364', '\365', },
975 { VK_F20, TRUE, '\366', '\367', '\370', '\371', },
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100976# endif
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200977 { VK_ADD, TRUE, 'N', 'N', 'N', 'N', }, // keyp '+'
978 { VK_SUBTRACT, TRUE,'J', 'J', 'J', 'J', }, // keyp '-'
979 // { VK_DIVIDE, TRUE,'N', 'N', 'N', 'N', }, // keyp '/'
980 { VK_MULTIPLY, TRUE,'7', '7', '7', '7', }, // keyp '*'
Bram Moolenaar071d4272004-06-13 20:20:40 +0000981
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200982 { VK_NUMPAD0,TRUE, '\332', '\333', '\334', '\335', },
983 { VK_NUMPAD1,TRUE, '\336', '\337', '\340', '\341', },
984 { VK_NUMPAD2,TRUE, '\342', '\343', '\344', '\345', },
985 { VK_NUMPAD3,TRUE, '\346', '\347', '\350', '\351', },
986 { VK_NUMPAD4,TRUE, '\352', '\353', '\354', '\355', },
987 { VK_NUMPAD5,TRUE, '\356', '\357', '\360', '\361', },
988 { VK_NUMPAD6,TRUE, '\362', '\363', '\364', '\365', },
989 { VK_NUMPAD7,TRUE, '\366', '\367', '\370', '\371', },
990 { VK_NUMPAD8,TRUE, '\372', '\373', '\374', '\375', },
991 // Sorry, out of number space! <negri>
Bram Moolenaarb70a47b2019-03-30 22:11:21 +0100992 { VK_NUMPAD9,TRUE, '\376', '\377', '|', '}', },
Bram Moolenaar071d4272004-06-13 20:20:40 +0000993};
994
995
Bram Moolenaar0f873732019-12-05 20:28:46 +0100996/*
997 * The return code indicates key code size.
998 */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000999 static int
Bram Moolenaar071d4272004-06-13 20:20:40 +00001000win32_kbd_patch_key(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001001 KEY_EVENT_RECORD *pker)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001002{
1003 UINT uMods = pker->dwControlKeyState;
1004 static int s_iIsDead = 0;
1005 static WORD awAnsiCode[2];
1006 static BYTE abKeystate[256];
1007
1008
1009 if (s_iIsDead == 2)
1010 {
K.Takata972db232022-02-04 10:45:38 +00001011 pker->uChar.UnicodeChar = (WCHAR) awAnsiCode[1];
Bram Moolenaar071d4272004-06-13 20:20:40 +00001012 s_iIsDead = 0;
1013 return 1;
1014 }
1015
K.Takata972db232022-02-04 10:45:38 +00001016 if (pker->uChar.UnicodeChar != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001017 return 1;
1018
Bram Moolenaara80faa82020-04-12 19:37:17 +02001019 CLEAR_FIELD(abKeystate);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001020
Bram Moolenaar0f873732019-12-05 20:28:46 +01001021 // Clear any pending dead keys
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001022 ToUnicode(VK_SPACE, MapVirtualKey(VK_SPACE, 0), abKeystate, awAnsiCode, 2, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001023
1024 if (uMods & SHIFT_PRESSED)
1025 abKeystate[VK_SHIFT] = 0x80;
1026 if (uMods & CAPSLOCK_ON)
1027 abKeystate[VK_CAPITAL] = 1;
1028
1029 if ((uMods & ALT_GR) == ALT_GR)
1030 {
1031 abKeystate[VK_CONTROL] = abKeystate[VK_LCONTROL] =
1032 abKeystate[VK_MENU] = abKeystate[VK_RMENU] = 0x80;
1033 }
1034
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001035 s_iIsDead = ToUnicode(pker->wVirtualKeyCode, pker->wVirtualScanCode,
1036 abKeystate, awAnsiCode, 2, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001037
1038 if (s_iIsDead > 0)
K.Takata972db232022-02-04 10:45:38 +00001039 pker->uChar.UnicodeChar = (WCHAR) awAnsiCode[0];
Bram Moolenaar071d4272004-06-13 20:20:40 +00001040
1041 return s_iIsDead;
1042}
1043
Bram Moolenaar071d4272004-06-13 20:20:40 +00001044static BOOL g_fJustGotFocus = FALSE;
1045
1046/*
1047 * Decode a KEY_EVENT into one or two keystrokes
1048 */
1049 static BOOL
1050decode_key_event(
1051 KEY_EVENT_RECORD *pker,
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001052 WCHAR *pch,
1053 WCHAR *pch2,
Bram Moolenaar071d4272004-06-13 20:20:40 +00001054 int *pmodifiers,
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02001055 BOOL fDoPost UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001056{
1057 int i;
1058 const int nModifs = pker->dwControlKeyState & (SHIFT | ALT | CTRL);
1059
1060 *pch = *pch2 = NUL;
1061 g_fJustGotFocus = FALSE;
1062
Bram Moolenaar0f873732019-12-05 20:28:46 +01001063 // ignore key up events
Bram Moolenaar071d4272004-06-13 20:20:40 +00001064 if (!pker->bKeyDown)
1065 return FALSE;
1066
Bram Moolenaar0f873732019-12-05 20:28:46 +01001067 // ignore some keystrokes
Bram Moolenaar071d4272004-06-13 20:20:40 +00001068 switch (pker->wVirtualKeyCode)
1069 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001070 // modifiers
Bram Moolenaar071d4272004-06-13 20:20:40 +00001071 case VK_SHIFT:
1072 case VK_CONTROL:
Bram Moolenaar0f873732019-12-05 20:28:46 +01001073 case VK_MENU: // Alt key
Bram Moolenaar071d4272004-06-13 20:20:40 +00001074 return FALSE;
1075
1076 default:
1077 break;
1078 }
1079
Bram Moolenaar0f873732019-12-05 20:28:46 +01001080 // special cases
K.Takata972db232022-02-04 10:45:38 +00001081 if ((nModifs & CTRL) != 0 && (nModifs & ~CTRL) == 0
1082 && pker->uChar.UnicodeChar == NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001083 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001084 // Ctrl-6 is Ctrl-^
Bram Moolenaar071d4272004-06-13 20:20:40 +00001085 if (pker->wVirtualKeyCode == '6')
1086 {
1087 *pch = Ctrl_HAT;
1088 return TRUE;
1089 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01001090 // Ctrl-2 is Ctrl-@
Bram Moolenaar071d4272004-06-13 20:20:40 +00001091 else if (pker->wVirtualKeyCode == '2')
1092 {
1093 *pch = NUL;
1094 return TRUE;
1095 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01001096 // Ctrl-- is Ctrl-_
Bram Moolenaar071d4272004-06-13 20:20:40 +00001097 else if (pker->wVirtualKeyCode == 0xBD)
1098 {
1099 *pch = Ctrl__;
1100 return TRUE;
1101 }
1102 }
1103
Bram Moolenaar0f873732019-12-05 20:28:46 +01001104 // Shift-TAB
Bram Moolenaar071d4272004-06-13 20:20:40 +00001105 if (pker->wVirtualKeyCode == VK_TAB && (nModifs & SHIFT_PRESSED))
1106 {
1107 *pch = K_NUL;
1108 *pch2 = '\017';
1109 return TRUE;
1110 }
1111
K.Takataeeec2542021-06-02 13:28:16 +02001112 for (i = ARRAY_LENGTH(VirtKeyMap); --i >= 0; )
Bram Moolenaar071d4272004-06-13 20:20:40 +00001113 {
1114 if (VirtKeyMap[i].wVirtKey == pker->wVirtualKeyCode)
1115 {
1116 if (nModifs == 0)
1117 *pch = VirtKeyMap[i].chAlone;
1118 else if ((nModifs & SHIFT) != 0 && (nModifs & ~SHIFT) == 0)
1119 *pch = VirtKeyMap[i].chShift;
1120 else if ((nModifs & CTRL) != 0 && (nModifs & ~CTRL) == 0)
1121 *pch = VirtKeyMap[i].chCtrl;
1122 else if ((nModifs & ALT) != 0 && (nModifs & ~ALT) == 0)
1123 *pch = VirtKeyMap[i].chAlt;
1124
1125 if (*pch != 0)
1126 {
1127 if (VirtKeyMap[i].fAnsiKey)
1128 {
1129 *pch2 = *pch;
1130 *pch = K_NUL;
1131 }
1132
1133 return TRUE;
1134 }
1135 }
1136 }
1137
1138 i = win32_kbd_patch_key(pker);
1139
1140 if (i < 0)
1141 *pch = NUL;
1142 else
1143 {
K.Takata972db232022-02-04 10:45:38 +00001144 *pch = (i > 0) ? pker->uChar.UnicodeChar : NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001145
1146 if (pmodifiers != NULL)
1147 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001148 // Pass on the ALT key as a modifier, but only when not combined
1149 // with CTRL (which is ALTGR).
Bram Moolenaar071d4272004-06-13 20:20:40 +00001150 if ((nModifs & ALT) != 0 && (nModifs & CTRL) == 0)
1151 *pmodifiers |= MOD_MASK_ALT;
1152
Bram Moolenaar0f873732019-12-05 20:28:46 +01001153 // Pass on SHIFT only for special keys, because we don't know when
1154 // it's already included with the character.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001155 if ((nModifs & SHIFT) != 0 && *pch <= 0x20)
1156 *pmodifiers |= MOD_MASK_SHIFT;
1157
Bram Moolenaar0f873732019-12-05 20:28:46 +01001158 // Pass on CTRL only for non-special keys, because we don't know
1159 // when it's already included with the character. And not when
1160 // combined with ALT (which is ALTGR).
Bram Moolenaar071d4272004-06-13 20:20:40 +00001161 if ((nModifs & CTRL) != 0 && (nModifs & ALT) == 0
1162 && *pch >= 0x20 && *pch < 0x80)
1163 *pmodifiers |= MOD_MASK_CTRL;
1164 }
1165 }
1166
1167 return (*pch != NUL);
1168}
1169
Bram Moolenaar0f873732019-12-05 20:28:46 +01001170#endif // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00001171
1172
Bram Moolenaar071d4272004-06-13 20:20:40 +00001173/*
1174 * For the GUI the mouse handling is in gui_w32.c.
1175 */
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001176#if defined(FEAT_GUI_MSWIN) && !defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001177 void
Bram Moolenaar1266d672017-02-01 13:43:36 +01001178mch_setmouse(int on UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001179{
1180}
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001181#else
Bram Moolenaar0f873732019-12-05 20:28:46 +01001182static int g_fMouseAvail = FALSE; // mouse present
1183static int g_fMouseActive = FALSE; // mouse enabled
1184static int g_nMouseClick = -1; // mouse status
1185static int g_xMouse; // mouse x coordinate
1186static int g_yMouse; // mouse y coordinate
Bram Moolenaar9f1983d2022-05-12 20:35:35 +01001187static DWORD g_cmodein = 0; // Original console input mode
1188static DWORD g_cmodeout = 0; // Original console output mode
Bram Moolenaar071d4272004-06-13 20:20:40 +00001189
1190/*
1191 * Enable or disable mouse input
1192 */
1193 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001194mch_setmouse(int on)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001195{
1196 DWORD cmodein;
1197
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001198# ifdef VIMDLL
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001199 if (gui.in_use)
1200 return;
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001201# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001202 if (!g_fMouseAvail)
1203 return;
1204
1205 g_fMouseActive = on;
1206 GetConsoleMode(g_hConIn, &cmodein);
1207
1208 if (g_fMouseActive)
Wez Furlong6ef5ab52021-05-30 19:29:41 +02001209 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00001210 cmodein |= ENABLE_MOUSE_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02001211 cmodein &= ~ENABLE_QUICK_EDIT_MODE;
1212 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001213 else
Wez Furlong6ef5ab52021-05-30 19:29:41 +02001214 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00001215 cmodein &= ~ENABLE_MOUSE_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02001216 cmodein |= g_cmodein & ENABLE_QUICK_EDIT_MODE;
1217 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001218
Wez Furlong6ef5ab52021-05-30 19:29:41 +02001219 SetConsoleMode(g_hConIn, cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001220}
1221
Bram Moolenaar157d8132018-03-06 17:09:20 +01001222
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001223# if defined(FEAT_BEVAL_TERM) || defined(PROTO)
Bram Moolenaar157d8132018-03-06 17:09:20 +01001224/*
1225 * Called when 'balloonevalterm' changed.
1226 */
1227 void
1228mch_bevalterm_changed(void)
1229{
1230 mch_setmouse(g_fMouseActive);
1231}
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001232# endif
Bram Moolenaar157d8132018-03-06 17:09:20 +01001233
Christopher Plewright2a46f812022-10-16 19:47:45 +01001234/*
1235 * Win32 console mouse scroll event handler.
1236 * Loosely based on the _OnMouseWheel() function in gui_w32.c
1237 *
1238 * This encodes the mouse scroll direction and keyboard modifiers into
1239 * g_nMouseClick, and the mouse position into g_xMouse and g_yMouse
1240 *
1241 * The direction of the scroll is decoded from two fields of the win32 console
1242 * mouse event record;
1243 * 1. The axis - vertical or horizontal flag - from dwEventFlags, and
1244 * 2. The sign - positive or negative (aka delta flag) - from dwButtonState
1245 *
1246 * When scroll axis is HORIZONTAL
1247 * - If the high word of the dwButtonState member contains a positive
1248 * value, the wheel was rotated to the right.
1249 * - Otherwise, the wheel was rotated to the left.
1250 * When scroll axis is VERTICAL
1251 * - If the high word of the dwButtonState member contains a positive value,
1252 * the wheel was rotated forward, away from the user.
1253 * - Otherwise, the wheel was rotated backward, toward the user.
1254 */
1255 static void
1256decode_mouse_wheel(MOUSE_EVENT_RECORD *pmer)
1257{
1258 win_T *wp;
1259 int horizontal = (pmer->dwEventFlags == MOUSE_HWHEELED);
1260 int zDelta = pmer->dwButtonState;
1261
1262 g_xMouse = pmer->dwMousePosition.X;
1263 g_yMouse = pmer->dwMousePosition.Y;
1264
1265#ifdef FEAT_PROP_POPUP
Christopher Plewright605d02a2022-10-19 11:54:46 +01001266 int lcol = g_xMouse;
1267 int lrow = g_yMouse;
Christopher Plewright4c366782022-10-20 13:11:15 +01001268 wp = mouse_find_win(&lrow, &lcol, FIND_POPUP);
Christopher Plewright2a46f812022-10-16 19:47:45 +01001269 if (wp != NULL && popup_is_popup(wp))
1270 {
1271 g_nMouseClick = -1;
1272 cmdarg_T cap;
1273 oparg_T oa;
1274 CLEAR_FIELD(cap);
1275 clear_oparg(&oa);
1276 cap.oap = &oa;
1277 if (horizontal)
1278 {
1279 cap.arg = zDelta < 0 ? MSCR_LEFT : MSCR_RIGHT;
1280 cap.cmdchar = zDelta < 0 ? K_MOUSELEFT : K_MOUSERIGHT;
1281 }
1282 else
1283 {
1284 cap.cmdchar = zDelta < 0 ? K_MOUSEUP : K_MOUSEDOWN;
1285 cap.arg = zDelta < 0 ? MSCR_UP : MSCR_DOWN;
1286 }
1287
1288 // Mouse hovers over popup window, scroll it if possible.
1289 mouse_row = wp->w_winrow;
1290 mouse_col = wp->w_wincol;
1291 nv_mousescroll(&cap);
1292 update_screen(0);
1293 setcursor();
1294 out_flush();
1295 return;
1296 }
1297#endif
1298 mouse_col = g_xMouse;
1299 mouse_row = g_yMouse;
1300
1301 char_u modifiers = 0;
1302 char_u direction = 0;
1303
1304 // Decode the direction into an event that Vim can process
1305 if (horizontal)
1306 direction = zDelta >= 0 ? KE_MOUSELEFT : KE_MOUSERIGHT;
1307 else
1308 direction = zDelta >= 0 ? KE_MOUSEDOWN : KE_MOUSEUP;
1309
dundargocc57b5bc2022-11-02 13:30:51 +00001310 // Decode the win32 console key modifiers into Vim mouse modifiers.
Christopher Plewright2a46f812022-10-16 19:47:45 +01001311 if (pmer->dwControlKeyState & SHIFT_PRESSED)
Christopher Plewright605d02a2022-10-19 11:54:46 +01001312 modifiers |= MOD_MASK_SHIFT; // MOUSE_SHIFT;
Christopher Plewright2a46f812022-10-16 19:47:45 +01001313 if (pmer->dwControlKeyState & (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED))
Christopher Plewright605d02a2022-10-19 11:54:46 +01001314 modifiers |= MOD_MASK_CTRL; // MOUSE_CTRL;
Christopher Plewright2a46f812022-10-16 19:47:45 +01001315 if (pmer->dwControlKeyState & (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED))
1316 modifiers |= MOD_MASK_ALT; // MOUSE_ALT;
1317
1318 // add (bitwise or) the scroll direction and the key modifier chars
1319 // together.
1320 g_nMouseClick = ((direction << 8) | modifiers);
1321
1322 return;
1323}
1324
Bram Moolenaar071d4272004-06-13 20:20:40 +00001325/*
1326 * Decode a MOUSE_EVENT. If it's a valid event, return MOUSE_LEFT,
1327 * MOUSE_MIDDLE, or MOUSE_RIGHT for a click; MOUSE_DRAG for a mouse
1328 * move with a button held down; and MOUSE_RELEASE after a MOUSE_DRAG
1329 * or a MOUSE_LEFT, _MIDDLE, or _RIGHT. We encode the button type,
1330 * the number of clicks, and the Shift/Ctrl/Alt modifiers in g_nMouseClick,
1331 * and we return the mouse position in g_xMouse and g_yMouse.
1332 *
1333 * Every MOUSE_LEFT, _MIDDLE, or _RIGHT will be followed by zero or more
1334 * MOUSE_DRAGs and one MOUSE_RELEASE. MOUSE_RELEASE will be followed only
1335 * by MOUSE_LEFT, _MIDDLE, or _RIGHT.
1336 *
1337 * For multiple clicks, we send, say, MOUSE_LEFT/1 click, MOUSE_RELEASE,
1338 * MOUSE_LEFT/2 clicks, MOUSE_RELEASE, MOUSE_LEFT/3 clicks, MOUSE_RELEASE, ....
1339 *
1340 * Windows will send us MOUSE_MOVED notifications whenever the mouse
1341 * moves, even if it stays within the same character cell. We ignore
1342 * all MOUSE_MOVED messages if the position hasn't really changed, and
1343 * we ignore all MOUSE_MOVED messages where no button is held down (i.e.,
1344 * we're only interested in MOUSE_DRAG).
1345 *
1346 * All of this is complicated by the code that fakes MOUSE_MIDDLE on
1347 * 2-button mouses by pressing the left & right buttons simultaneously.
1348 * In practice, it's almost impossible to click both at the same time,
1349 * so we need to delay a little. Also, we tend not to get MOUSE_RELEASE
1350 * in such cases, if the user is clicking quickly.
1351 */
1352 static BOOL
1353decode_mouse_event(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001354 MOUSE_EVENT_RECORD *pmer)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001355{
1356 static int s_nOldButton = -1;
1357 static int s_nOldMouseClick = -1;
1358 static int s_xOldMouse = -1;
1359 static int s_yOldMouse = -1;
1360 static linenr_T s_old_topline = 0;
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001361# ifdef FEAT_DIFF
Bram Moolenaar071d4272004-06-13 20:20:40 +00001362 static int s_old_topfill = 0;
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001363# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001364 static int s_cClicks = 1;
1365 static BOOL s_fReleased = TRUE;
1366 static DWORD s_dwLastClickTime = 0;
1367 static BOOL s_fNextIsMiddle = FALSE;
1368
Bram Moolenaar0f873732019-12-05 20:28:46 +01001369 static DWORD cButtons = 0; // number of buttons supported
Bram Moolenaar071d4272004-06-13 20:20:40 +00001370
1371 const DWORD LEFT = FROM_LEFT_1ST_BUTTON_PRESSED;
1372 const DWORD MIDDLE = FROM_LEFT_2ND_BUTTON_PRESSED;
1373 const DWORD RIGHT = RIGHTMOST_BUTTON_PRESSED;
1374 const DWORD LEFT_RIGHT = LEFT | RIGHT;
1375
1376 int nButton;
1377
1378 if (cButtons == 0 && !GetNumberOfConsoleMouseButtons(&cButtons))
1379 cButtons = 2;
1380
1381 if (!g_fMouseAvail || !g_fMouseActive)
1382 {
1383 g_nMouseClick = -1;
1384 return FALSE;
1385 }
1386
Bram Moolenaar0f873732019-12-05 20:28:46 +01001387 // get a spurious MOUSE_EVENT immediately after receiving focus; ignore
Bram Moolenaar071d4272004-06-13 20:20:40 +00001388 if (g_fJustGotFocus)
1389 {
1390 g_fJustGotFocus = FALSE;
1391 return FALSE;
1392 }
1393
Christopher Plewright605d02a2022-10-19 11:54:46 +01001394 // If there is an unprocessed mouse click drop this one.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001395 if (g_nMouseClick != -1)
1396 return TRUE;
Christopher Plewright605d02a2022-10-19 11:54:46 +01001397
Christopher Plewright2a46f812022-10-16 19:47:45 +01001398 if (pmer->dwEventFlags == MOUSE_WHEELED
1399 || pmer->dwEventFlags == MOUSE_HWHEELED)
1400 {
1401 decode_mouse_wheel(pmer);
1402 return TRUE; // we now should have a mouse scroll in g_nMouseClick
1403 }
Christopher Plewright605d02a2022-10-19 11:54:46 +01001404
Bram Moolenaar071d4272004-06-13 20:20:40 +00001405 nButton = -1;
1406 g_xMouse = pmer->dwMousePosition.X;
1407 g_yMouse = pmer->dwMousePosition.Y;
1408
1409 if (pmer->dwEventFlags == MOUSE_MOVED)
1410 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001411 // Ignore MOUSE_MOVED events if (x, y) hasn't changed. (We get these
1412 // events even when the mouse moves only within a char cell.)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001413 if (s_xOldMouse == g_xMouse && s_yOldMouse == g_yMouse)
1414 return FALSE;
1415 }
1416
Bram Moolenaar0f873732019-12-05 20:28:46 +01001417 // If no buttons are pressed...
Bram Moolenaar071d4272004-06-13 20:20:40 +00001418 if ((pmer->dwButtonState & ((1 << cButtons) - 1)) == 0)
1419 {
Bram Moolenaar157d8132018-03-06 17:09:20 +01001420 nButton = MOUSE_RELEASE;
1421
Bram Moolenaar0f873732019-12-05 20:28:46 +01001422 // If the last thing returned was MOUSE_RELEASE, ignore this
Bram Moolenaar071d4272004-06-13 20:20:40 +00001423 if (s_fReleased)
Bram Moolenaar157d8132018-03-06 17:09:20 +01001424 {
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001425# ifdef FEAT_BEVAL_TERM
Bram Moolenaar0f873732019-12-05 20:28:46 +01001426 // do return mouse move events when we want them
Bram Moolenaar157d8132018-03-06 17:09:20 +01001427 if (p_bevalterm)
1428 nButton = MOUSE_DRAG;
1429 else
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001430# endif
Bram Moolenaar157d8132018-03-06 17:09:20 +01001431 return FALSE;
1432 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001433
Bram Moolenaar071d4272004-06-13 20:20:40 +00001434 s_fReleased = TRUE;
1435 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01001436 else // one or more buttons pressed
Bram Moolenaar071d4272004-06-13 20:20:40 +00001437 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001438 // on a 2-button mouse, hold down left and right buttons
1439 // simultaneously to get MIDDLE.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001440
1441 if (cButtons == 2 && s_nOldButton != MOUSE_DRAG)
1442 {
1443 DWORD dwLR = (pmer->dwButtonState & LEFT_RIGHT);
1444
Bram Moolenaar0f873732019-12-05 20:28:46 +01001445 // if either left or right button only is pressed, see if the
1446 // next mouse event has both of them pressed
Bram Moolenaar071d4272004-06-13 20:20:40 +00001447 if (dwLR == LEFT || dwLR == RIGHT)
1448 {
1449 for (;;)
1450 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001451 // wait a short time for next input event
Bram Moolenaar071d4272004-06-13 20:20:40 +00001452 if (WaitForSingleObject(g_hConIn, p_mouset / 3)
1453 != WAIT_OBJECT_0)
1454 break;
1455 else
1456 {
1457 DWORD cRecords = 0;
1458 INPUT_RECORD ir;
1459 MOUSE_EVENT_RECORD* pmer2 = &ir.Event.MouseEvent;
1460
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001461 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001462
1463 if (cRecords == 0 || ir.EventType != MOUSE_EVENT
1464 || !(pmer2->dwButtonState & LEFT_RIGHT))
1465 break;
1466 else
1467 {
1468 if (pmer2->dwEventFlags != MOUSE_MOVED)
1469 {
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001470 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001471
1472 return decode_mouse_event(pmer2);
1473 }
1474 else if (s_xOldMouse == pmer2->dwMousePosition.X &&
1475 s_yOldMouse == pmer2->dwMousePosition.Y)
1476 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001477 // throw away spurious mouse move
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001478 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001479
Bram Moolenaar0f873732019-12-05 20:28:46 +01001480 // are there any more mouse events in queue?
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001481 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001482
1483 if (cRecords==0 || ir.EventType != MOUSE_EVENT)
1484 break;
1485 }
1486 else
1487 break;
1488 }
1489 }
1490 }
1491 }
1492 }
1493
1494 if (s_fNextIsMiddle)
1495 {
1496 nButton = (pmer->dwEventFlags == MOUSE_MOVED)
1497 ? MOUSE_DRAG : MOUSE_MIDDLE;
1498 s_fNextIsMiddle = FALSE;
1499 }
1500 else if (cButtons == 2 &&
1501 ((pmer->dwButtonState & LEFT_RIGHT) == LEFT_RIGHT))
1502 {
1503 nButton = MOUSE_MIDDLE;
1504
1505 if (! s_fReleased && pmer->dwEventFlags != MOUSE_MOVED)
1506 {
1507 s_fNextIsMiddle = TRUE;
1508 nButton = MOUSE_RELEASE;
1509 }
1510 }
1511 else if ((pmer->dwButtonState & LEFT) == LEFT)
1512 nButton = MOUSE_LEFT;
1513 else if ((pmer->dwButtonState & MIDDLE) == MIDDLE)
1514 nButton = MOUSE_MIDDLE;
1515 else if ((pmer->dwButtonState & RIGHT) == RIGHT)
1516 nButton = MOUSE_RIGHT;
1517
1518 if (! s_fReleased && ! s_fNextIsMiddle
1519 && nButton != s_nOldButton && s_nOldButton != MOUSE_DRAG)
1520 return FALSE;
1521
1522 s_fReleased = s_fNextIsMiddle;
1523 }
1524
1525 if (pmer->dwEventFlags == 0 || pmer->dwEventFlags == DOUBLE_CLICK)
1526 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001527 // button pressed or released, without mouse moving
Bram Moolenaar071d4272004-06-13 20:20:40 +00001528 if (nButton != -1 && nButton != MOUSE_RELEASE)
1529 {
1530 DWORD dwCurrentTime = GetTickCount();
1531
1532 if (s_xOldMouse != g_xMouse
1533 || s_yOldMouse != g_yMouse
1534 || s_nOldButton != nButton
1535 || s_old_topline != curwin->w_topline
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001536# ifdef FEAT_DIFF
Bram Moolenaar071d4272004-06-13 20:20:40 +00001537 || s_old_topfill != curwin->w_topfill
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001538# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001539 || (int)(dwCurrentTime - s_dwLastClickTime) > p_mouset)
1540 {
1541 s_cClicks = 1;
1542 }
1543 else if (++s_cClicks > 4)
1544 {
1545 s_cClicks = 1;
1546 }
1547
1548 s_dwLastClickTime = dwCurrentTime;
1549 }
1550 }
1551 else if (pmer->dwEventFlags == MOUSE_MOVED)
1552 {
1553 if (nButton != -1 && nButton != MOUSE_RELEASE)
1554 nButton = MOUSE_DRAG;
1555
1556 s_cClicks = 1;
1557 }
1558
1559 if (nButton == -1)
1560 return FALSE;
1561
1562 if (nButton != MOUSE_RELEASE)
1563 s_nOldButton = nButton;
1564
1565 g_nMouseClick = nButton;
1566
1567 if (pmer->dwControlKeyState & SHIFT_PRESSED)
1568 g_nMouseClick |= MOUSE_SHIFT;
1569 if (pmer->dwControlKeyState & (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED))
1570 g_nMouseClick |= MOUSE_CTRL;
1571 if (pmer->dwControlKeyState & (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED))
1572 g_nMouseClick |= MOUSE_ALT;
1573
1574 if (nButton != MOUSE_DRAG && nButton != MOUSE_RELEASE)
1575 SET_NUM_MOUSE_CLICKS(g_nMouseClick, s_cClicks);
1576
Bram Moolenaar0f873732019-12-05 20:28:46 +01001577 // only pass on interesting (i.e., different) mouse events
Bram Moolenaar071d4272004-06-13 20:20:40 +00001578 if (s_xOldMouse == g_xMouse
1579 && s_yOldMouse == g_yMouse
1580 && s_nOldMouseClick == g_nMouseClick)
1581 {
1582 g_nMouseClick = -1;
1583 return FALSE;
1584 }
1585
1586 s_xOldMouse = g_xMouse;
1587 s_yOldMouse = g_yMouse;
1588 s_old_topline = curwin->w_topline;
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001589# ifdef FEAT_DIFF
Bram Moolenaar071d4272004-06-13 20:20:40 +00001590 s_old_topfill = curwin->w_topfill;
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001591# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001592 s_nOldMouseClick = g_nMouseClick;
1593
1594 return TRUE;
1595}
1596
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001597#endif // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00001598
1599
1600#ifdef MCH_CURSOR_SHAPE
1601/*
1602 * Set the shape of the cursor.
1603 * 'thickness' can be from 1 (thin) to 99 (block)
1604 */
1605 static void
1606mch_set_cursor_shape(int thickness)
1607{
K.Takatadf5320c2022-09-01 13:20:16 +01001608 if (USE_VTP || USE_WT)
1609 {
1610 if (*T_CSI == NUL)
1611 {
1612 // If 't_SI' is not set, use the default cursor styles.
1613 if (thickness < 50)
1614 vtp_printf("\033[3 q"); // underline
1615 else
1616 vtp_printf("\033[0 q"); // default
1617 }
1618 }
1619 else
1620 {
1621 CONSOLE_CURSOR_INFO ConsoleCursorInfo;
1622 ConsoleCursorInfo.dwSize = thickness;
1623 ConsoleCursorInfo.bVisible = s_cursor_visible;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001624
K.Takatadf5320c2022-09-01 13:20:16 +01001625 SetConsoleCursorInfo(g_hConOut, &ConsoleCursorInfo);
1626 if (s_cursor_visible)
1627 SetConsoleCursorPosition(g_hConOut, g_coord);
1628 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001629}
1630
1631 void
1632mch_update_cursor(void)
1633{
1634 int idx;
1635 int thickness;
1636
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001637# ifdef VIMDLL
1638 if (gui.in_use)
1639 return;
1640# endif
1641
Bram Moolenaar071d4272004-06-13 20:20:40 +00001642 /*
1643 * How the cursor is drawn depends on the current mode.
1644 */
1645 idx = get_shape_idx(FALSE);
1646
1647 if (shape_table[idx].shape == SHAPE_BLOCK)
Bram Moolenaar0f873732019-12-05 20:28:46 +01001648 thickness = 99; // 100 doesn't work on W95
Bram Moolenaar071d4272004-06-13 20:20:40 +00001649 else
1650 thickness = shape_table[idx].percentage;
1651 mch_set_cursor_shape(thickness);
1652}
1653#endif
1654
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001655#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001656/*
1657 * Handle FOCUS_EVENT.
1658 */
1659 static void
1660handle_focus_event(INPUT_RECORD ir)
1661{
1662 g_fJustGotFocus = ir.Event.FocusEvent.bSetFocus;
1663 ui_focus_change((int)g_fJustGotFocus);
1664}
1665
Bram Moolenaar78d21da2019-02-17 15:00:52 +01001666static void ResizeConBuf(HANDLE hConsole, COORD coordScreen);
1667
Bram Moolenaar071d4272004-06-13 20:20:40 +00001668/*
1669 * Wait until console input from keyboard or mouse is available,
1670 * or the time is up.
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001671 * When "ignore_input" is TRUE even wait when input is available.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001672 * Return TRUE if something is available FALSE if not.
1673 */
1674 static int
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001675WaitForChar(long msec, int ignore_input)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001676{
1677 DWORD dwNow = 0, dwEndTime = 0;
1678 INPUT_RECORD ir;
1679 DWORD cRecords;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001680 WCHAR ch, ch2;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001681# ifdef FEAT_TIMERS
Bram Moolenaar40b1b542016-04-20 20:18:23 +02001682 int tb_change_cnt = typebuf.tb_change_cnt;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001683# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001684
1685 if (msec > 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01001686 // Wait until the specified time has elapsed.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001687 dwEndTime = GetTickCount() + msec;
1688 else if (msec < 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01001689 // Wait forever.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001690 dwEndTime = INFINITE;
1691
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01001692 // We need to loop until the end of the time period, because
1693 // we might get multiple unusable mouse events in that time.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001694 for (;;)
1695 {
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001696 // Only process messages when waiting.
1697 if (msec != 0)
1698 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001699# ifdef MESSAGE_QUEUE
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001700 parse_queued_messages();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001701# endif
1702# ifdef FEAT_MZSCHEME
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001703 mzvim_check_threads();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001704# endif
1705# ifdef FEAT_CLIENTSERVER
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001706 serverProcessPendingMessages();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001707# endif
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001708 }
Bram Moolenaarf12d9832016-01-29 21:11:25 +01001709
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001710 if (g_nMouseClick != -1
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001711# ifdef FEAT_CLIENTSERVER
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001712 || (!ignore_input && input_available())
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001713# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001714 )
1715 return TRUE;
1716
1717 if (msec > 0)
1718 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001719 // If the specified wait time has passed, return. Beware that
1720 // GetTickCount() may wrap around (overflow).
Bram Moolenaar071d4272004-06-13 20:20:40 +00001721 dwNow = GetTickCount();
Bram Moolenaarb7512b72013-08-10 12:45:09 +02001722 if ((int)(dwNow - dwEndTime) >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001723 break;
1724 }
1725 if (msec != 0)
1726 {
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001727 DWORD dwWaitTime = dwEndTime - dwNow;
1728
Bram Moolenaarc478ee32020-12-01 21:27:51 +01001729 // Don't wait for more than 11 msec to avoid dropping characters,
1730 // check channel while waiting for input and handle a callback from
1731 // 'balloonexpr'.
1732 if (dwWaitTime > 11)
1733 dwWaitTime = 11;
1734
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001735# ifdef FEAT_MZSCHEME
Bram Moolenaarc478ee32020-12-01 21:27:51 +01001736 if (mzthreads_allowed() && p_mzq > 0 && (long)dwWaitTime > p_mzq)
Bram Moolenaar0f873732019-12-05 20:28:46 +01001737 dwWaitTime = p_mzq; // don't wait longer than 'mzquantum'
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001738# endif
1739# ifdef FEAT_TIMERS
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001740 // When waiting very briefly don't trigger timers.
1741 if (dwWaitTime > 10)
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001742 {
1743 long due_time;
1744
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001745 // Trigger timers and then get the time in msec until the next
1746 // one is due. Wait up to that time.
1747 due_time = check_due_timer();
1748 if (typebuf.tb_change_cnt != tb_change_cnt)
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001749 {
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001750 // timer may have used feedkeys().
1751 return FALSE;
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001752 }
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001753 if (due_time > 0 && dwWaitTime > (DWORD)due_time)
1754 dwWaitTime = due_time;
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001755 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001756# endif
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001757 if (
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001758# ifdef FEAT_CLIENTSERVER
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001759 // Wait for either an event on the console input or a
1760 // message in the client-server window.
1761 msg_wait_for_multiple_objects(1, &g_hConIn, FALSE,
1762 dwWaitTime, QS_SENDMESSAGE) != WAIT_OBJECT_0
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001763# else
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001764 wait_for_single_object(g_hConIn, dwWaitTime)
1765 != WAIT_OBJECT_0
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001766# endif
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001767 )
1768 continue;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001769 }
1770
1771 cRecords = 0;
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001772 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001773
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001774# ifdef FEAT_MBYTE_IME
matveyt4eb19142021-05-20 11:54:10 +02001775 // May have to redraw if the cursor ends up in the wrong place.
1776 // Only when not peeking.
Bram Moolenaar24959102022-05-07 20:01:16 +01001777 if (State == MODE_CMDLINE && msg_row == Rows - 1 && msec != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001778 {
1779 CONSOLE_SCREEN_BUFFER_INFO csbi;
1780
1781 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
1782 {
1783 if (csbi.dwCursorPosition.Y != msg_row)
1784 {
matveyte08795e2021-05-07 15:00:17 +02001785 // The screen is now messed up, must redraw the command
1786 // line and later all the windows.
Bram Moolenaara4d158b2022-08-14 14:17:45 +01001787 redraw_all_later(UPD_CLEAR);
matveyte08795e2021-05-07 15:00:17 +02001788 compute_cmdrow();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001789 redrawcmd();
1790 }
1791 }
1792 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001793# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001794
1795 if (cRecords > 0)
1796 {
1797 if (ir.EventType == KEY_EVENT && ir.Event.KeyEvent.bKeyDown)
1798 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001799# ifdef FEAT_MBYTE_IME
Bram Moolenaar0f873732019-12-05 20:28:46 +01001800 // Windows IME sends two '\n's with only one 'ENTER'. First:
1801 // wVirtualKeyCode == 13. second: wVirtualKeyCode == 0
K.Takata972db232022-02-04 10:45:38 +00001802 if (ir.Event.KeyEvent.uChar.UnicodeChar == 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00001803 && ir.Event.KeyEvent.wVirtualKeyCode == 13)
1804 {
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001805 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001806 continue;
1807 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001808# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001809 if (decode_key_event(&ir.Event.KeyEvent, &ch, &ch2,
1810 NULL, FALSE))
1811 return TRUE;
1812 }
1813
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001814 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001815
1816 if (ir.EventType == FOCUS_EVENT)
1817 handle_focus_event(ir);
1818 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
Bram Moolenaarc33ecb22018-02-11 16:40:45 +01001819 {
Bram Moolenaar78d21da2019-02-17 15:00:52 +01001820 COORD dwSize = ir.Event.WindowBufferSizeEvent.dwSize;
1821
Bram Moolenaar36698e32019-12-11 22:57:40 +01001822 // Only call shell_resized() when the size actually changed to
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001823 // avoid the screen is cleared.
Bram Moolenaar78d21da2019-02-17 15:00:52 +01001824 if (dwSize.X != Columns || dwSize.Y != Rows)
1825 {
1826 CONSOLE_SCREEN_BUFFER_INFO csbi;
1827 GetConsoleScreenBufferInfo(g_hConOut, &csbi);
Bram Moolenaar36698e32019-12-11 22:57:40 +01001828 dwSize.X = csbi.srWindow.Right - csbi.srWindow.Left + 1;
Bram Moolenaar78d21da2019-02-17 15:00:52 +01001829 dwSize.Y = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
Bram Moolenaar36698e32019-12-11 22:57:40 +01001830 if (dwSize.X != Columns || dwSize.Y != Rows)
1831 {
1832 ResizeConBuf(g_hConOut, dwSize);
1833 shell_resized();
1834 }
Bram Moolenaar78d21da2019-02-17 15:00:52 +01001835 }
Bram Moolenaarc33ecb22018-02-11 16:40:45 +01001836 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001837 else if (ir.EventType == MOUSE_EVENT
1838 && decode_mouse_event(&ir.Event.MouseEvent))
1839 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001840 }
1841 else if (msec == 0)
1842 break;
1843 }
1844
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001845# ifdef FEAT_CLIENTSERVER
Bram Moolenaar0f873732019-12-05 20:28:46 +01001846 // Something might have been received while we were waiting.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001847 if (input_available())
1848 return TRUE;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001849# endif
Bram Moolenaarf12d9832016-01-29 21:11:25 +01001850
Bram Moolenaar071d4272004-06-13 20:20:40 +00001851 return FALSE;
1852}
1853
Bram Moolenaar071d4272004-06-13 20:20:40 +00001854/*
1855 * return non-zero if a character is available
1856 */
1857 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001858mch_char_avail(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001859{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001860# ifdef VIMDLL
1861 if (gui.in_use)
1862 return TRUE;
1863# endif
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001864 return WaitForChar(0L, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001865}
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001866
1867# if defined(FEAT_TERMINAL) || defined(PROTO)
1868/*
1869 * Check for any pending input or messages.
1870 */
1871 int
1872mch_check_messages(void)
1873{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001874# ifdef VIMDLL
1875 if (gui.in_use)
1876 return TRUE;
1877# endif
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001878 return WaitForChar(0L, TRUE);
1879}
1880# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001881
1882/*
1883 * Create the console input. Used when reading stdin doesn't work.
1884 */
1885 static void
1886create_conin(void)
1887{
1888 g_hConIn = CreateFile("CONIN$", GENERIC_READ|GENERIC_WRITE,
1889 FILE_SHARE_READ|FILE_SHARE_WRITE,
1890 (LPSECURITY_ATTRIBUTES) NULL,
Bram Moolenaareb3593b2006-04-22 22:33:57 +00001891 OPEN_EXISTING, 0, (HANDLE)NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001892 did_create_conin = TRUE;
1893}
1894
1895/*
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001896 * Get a keystroke or a mouse event, use a blocking wait.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001897 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001898 static WCHAR
1899tgetch(int *pmodifiers, WCHAR *pch2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001900{
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001901 WCHAR ch;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001902
1903 for (;;)
1904 {
1905 INPUT_RECORD ir;
1906 DWORD cRecords = 0;
1907
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001908# ifdef FEAT_CLIENTSERVER
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001909 (void)WaitForChar(-1L, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001910 if (input_available())
1911 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001912 if (g_nMouseClick != -1)
1913 return 0;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001914# endif
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001915 if (read_console_input(g_hConIn, &ir, 1, &cRecords) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001916 {
1917 if (did_create_conin)
1918 read_error_exit();
1919 create_conin();
1920 continue;
1921 }
1922
1923 if (ir.EventType == KEY_EVENT)
1924 {
1925 if (decode_key_event(&ir.Event.KeyEvent, &ch, pch2,
1926 pmodifiers, TRUE))
1927 return ch;
1928 }
1929 else if (ir.EventType == FOCUS_EVENT)
1930 handle_focus_event(ir);
1931 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
1932 shell_resized();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001933 else if (ir.EventType == MOUSE_EVENT)
1934 {
1935 if (decode_mouse_event(&ir.Event.MouseEvent))
1936 return 0;
1937 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001938 }
1939}
Bram Moolenaar0f873732019-12-05 20:28:46 +01001940#endif // !FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00001941
1942
1943/*
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02001944 * mch_inchar(): low-level input function.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001945 * Get one or more characters from the keyboard or the mouse.
1946 * If time == 0, do not wait for characters.
1947 * If time == n, wait a short time for characters.
1948 * If time == -1, wait forever for characters.
1949 * Returns the number of characters read into buf.
1950 */
1951 int
1952mch_inchar(
Bram Moolenaar1266d672017-02-01 13:43:36 +01001953 char_u *buf UNUSED,
1954 int maxlen UNUSED,
1955 long time UNUSED,
1956 int tb_change_cnt UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001957{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001958#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001959
1960 int len;
1961 int c;
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01001962# ifdef VIMDLL
1963// Extra space for maximum three CSIs. E.g. U+1B6DB -> 0xF0 0x9B 0x9B 0x9B.
1964# define TYPEAHEADSPACE 6
1965# else
1966# define TYPEAHEADSPACE 0
1967# endif
1968# define TYPEAHEADLEN (20 + TYPEAHEADSPACE)
Bram Moolenaar0f873732019-12-05 20:28:46 +01001969 static char_u typeahead[TYPEAHEADLEN]; // previously typed bytes.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001970 static int typeaheadlen = 0;
1971
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001972# ifdef VIMDLL
1973 if (gui.in_use)
1974 return 0;
1975# endif
1976
Bram Moolenaar0f873732019-12-05 20:28:46 +01001977 // First use any typeahead that was kept because "buf" was too small.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001978 if (typeaheadlen > 0)
1979 goto theend;
1980
Bram Moolenaar071d4272004-06-13 20:20:40 +00001981 if (time >= 0)
1982 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001983 if (!WaitForChar(time, FALSE)) // no character available
Bram Moolenaar071d4272004-06-13 20:20:40 +00001984 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001985 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01001986 else // time == -1, wait forever
Bram Moolenaar071d4272004-06-13 20:20:40 +00001987 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001988 mch_set_winsize_now(); // Allow winsize changes from now on
Bram Moolenaar071d4272004-06-13 20:20:40 +00001989
Bram Moolenaar3918c952005-03-15 22:34:55 +00001990 /*
1991 * If there is no character available within 2 seconds (default)
1992 * write the autoscript file to disk. Or cause the CursorHold event
1993 * to be triggered.
1994 */
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001995 if (!WaitForChar(p_ut, FALSE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001996 {
Bram Moolenaard35f9712005-12-18 22:02:33 +00001997 if (trigger_cursorhold() && maxlen >= 3)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001998 {
Bram Moolenaar3918c952005-03-15 22:34:55 +00001999 buf[0] = K_SPECIAL;
2000 buf[1] = KS_EXTRA;
2001 buf[2] = (int)KE_CURSORHOLD;
2002 return 3;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002003 }
Bram Moolenaar702517d2005-06-27 22:34:07 +00002004 before_blocking();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002005 }
2006 }
2007
2008 /*
2009 * Try to read as many characters as there are, until the buffer is full.
2010 */
2011
Bram Moolenaar0f873732019-12-05 20:28:46 +01002012 // we will get at least one key. Get more if they are available.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002013 g_fCBrkPressed = FALSE;
2014
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002015# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00002016 if (fdDump)
2017 fputc('[', fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002018# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002019
Bram Moolenaar0f873732019-12-05 20:28:46 +01002020 // Keep looping until there is something in the typeahead buffer and more
2021 // to get and still room in the buffer (up to two bytes for a char and
2022 // three bytes for a modifier).
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02002023 while ((typeaheadlen == 0 || WaitForChar(0L, FALSE))
Bram Moolenaar9f1983d2022-05-12 20:35:35 +01002024 && typeaheadlen + 5 + TYPEAHEADSPACE <= TYPEAHEADLEN)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002025 {
2026 if (typebuf_changed(tb_change_cnt))
2027 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01002028 // "buf" may be invalid now if a client put something in the
2029 // typeahead buffer and "buf" is in the typeahead buffer.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002030 typeaheadlen = 0;
2031 break;
2032 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002033 if (g_nMouseClick != -1)
2034 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002035# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00002036 if (fdDump)
2037 fprintf(fdDump, "{%02x @ %d, %d}",
2038 g_nMouseClick, g_xMouse, g_yMouse);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002039# endif
Christopher Plewright2a46f812022-10-16 19:47:45 +01002040 char_u modifiers = ((char_u *)(&g_nMouseClick))[0];
2041 char_u scroll_dir = ((char_u *)(&g_nMouseClick))[1];
2042
2043 if (scroll_dir == KE_MOUSEDOWN
2044 || scroll_dir == KE_MOUSEUP
2045 || scroll_dir == KE_MOUSELEFT
2046 || scroll_dir == KE_MOUSERIGHT)
2047 {
2048 if (modifiers > 0)
2049 {
2050 typeahead[typeaheadlen++] = CSI;
2051 typeahead[typeaheadlen++] = KS_MODIFIER;
2052 typeahead[typeaheadlen++] = modifiers;
2053 }
2054 typeahead[typeaheadlen++] = CSI;
2055 typeahead[typeaheadlen++] = KS_EXTRA;
2056 typeahead[typeaheadlen++] = scroll_dir;
2057 g_nMouseClick = -1;
2058 }
2059 else
2060 {
2061 typeahead[typeaheadlen++] = ESC + 128;
2062 typeahead[typeaheadlen++] = 'M';
2063 typeahead[typeaheadlen++] = g_nMouseClick;
2064 typeahead[typeaheadlen++] = g_xMouse + '!';
2065 typeahead[typeaheadlen++] = g_yMouse + '!';
2066 g_nMouseClick = -1;
2067 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002068 }
2069 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00002070 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002071 WCHAR ch2 = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002072 int modifiers = 0;
2073
2074 c = tgetch(&modifiers, &ch2);
2075
2076 if (typebuf_changed(tb_change_cnt))
2077 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01002078 // "buf" may be invalid now if a client put something in the
2079 // typeahead buffer and "buf" is in the typeahead buffer.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002080 typeaheadlen = 0;
2081 break;
2082 }
2083
2084 if (c == Ctrl_C && ctrl_c_interrupts)
2085 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002086# if defined(FEAT_CLIENTSERVER)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002087 trash_input_buf();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002088# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002089 got_int = TRUE;
2090 }
2091
Bram Moolenaar071d4272004-06-13 20:20:40 +00002092 if (g_nMouseClick == -1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002093 {
2094 int n = 1;
2095
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002096 if (ch2 == NUL)
2097 {
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01002098 int i, j;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002099 char_u *p;
2100 WCHAR ch[2];
2101
2102 ch[0] = c;
Bram Moolenaar0f873732019-12-05 20:28:46 +01002103 if (c >= 0xD800 && c <= 0xDBFF) // High surrogate
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002104 {
2105 ch[1] = tgetch(&modifiers, &ch2);
2106 n++;
2107 }
2108 p = utf16_to_enc(ch, &n);
2109 if (p != NULL)
2110 {
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01002111 for (i = 0, j = 0; i < n; i++)
2112 {
2113 typeahead[typeaheadlen + j++] = p[i];
2114# ifdef VIMDLL
2115 if (p[i] == CSI)
2116 {
2117 typeahead[typeaheadlen + j++] = KS_EXTRA;
2118 typeahead[typeaheadlen + j++] = KE_CSI;
2119 }
2120# endif
2121 }
2122 n = j;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002123 vim_free(p);
2124 }
2125 }
2126 else
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01002127 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002128 typeahead[typeaheadlen] = c;
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01002129# ifdef VIMDLL
2130 if (c == CSI)
2131 {
2132 typeahead[typeaheadlen + 1] = KS_EXTRA;
2133 typeahead[typeaheadlen + 2] = KE_CSI;
2134 n = 3;
2135 }
2136# endif
2137 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002138 if (ch2 != NUL)
2139 {
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +02002140 if (c == K_NUL)
Bram Moolenaarfeeb4d02017-12-05 15:14:46 +01002141 {
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +02002142 switch (ch2)
2143 {
2144 case (WCHAR)'\324': // SHIFT+Insert
2145 case (WCHAR)'\325': // CTRL+Insert
2146 case (WCHAR)'\327': // SHIFT+Delete
2147 case (WCHAR)'\330': // CTRL+Delete
2148 typeahead[typeaheadlen + n] = (char_u)ch2;
2149 n++;
2150 break;
2151
2152 default:
2153 typeahead[typeaheadlen + n] = 3;
2154 typeahead[typeaheadlen + n + 1] = (char_u)ch2;
2155 n += 2;
2156 break;
2157 }
Bram Moolenaarfeeb4d02017-12-05 15:14:46 +01002158 }
2159 else
2160 {
2161 typeahead[typeaheadlen + n] = 3;
2162 typeahead[typeaheadlen + n + 1] = (char_u)ch2;
2163 n += 2;
2164 }
Bram Moolenaar45500912014-07-09 20:51:07 +02002165 }
2166
Bram Moolenaar0f873732019-12-05 20:28:46 +01002167 // Use the ALT key to set the 8th bit of the character
2168 // when it's one byte, the 8th bit isn't set yet and not
2169 // using a double-byte encoding (would become a lead
2170 // byte).
Bram Moolenaar071d4272004-06-13 20:20:40 +00002171 if ((modifiers & MOD_MASK_ALT)
2172 && n == 1
2173 && (typeahead[typeaheadlen] & 0x80) == 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00002174 && !enc_dbcs
Bram Moolenaar071d4272004-06-13 20:20:40 +00002175 )
2176 {
Bram Moolenaar85a3e5c2007-11-20 16:22:16 +00002177 n = (*mb_char2bytes)(typeahead[typeaheadlen] | 0x80,
2178 typeahead + typeaheadlen);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002179 modifiers &= ~MOD_MASK_ALT;
2180 }
2181
2182 if (modifiers != 0)
2183 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01002184 // Prepend modifiers to the character.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002185 mch_memmove(typeahead + typeaheadlen + 3,
2186 typeahead + typeaheadlen, n);
2187 typeahead[typeaheadlen++] = K_SPECIAL;
2188 typeahead[typeaheadlen++] = (char_u)KS_MODIFIER;
2189 typeahead[typeaheadlen++] = modifiers;
2190 }
2191
2192 typeaheadlen += n;
2193
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002194# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00002195 if (fdDump)
2196 fputc(c, fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002197# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002198 }
2199 }
2200 }
2201
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002202# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00002203 if (fdDump)
2204 {
2205 fputs("]\n", fdDump);
2206 fflush(fdDump);
2207 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002208# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002209
Bram Moolenaar071d4272004-06-13 20:20:40 +00002210theend:
Bram Moolenaar0f873732019-12-05 20:28:46 +01002211 // Move typeahead to "buf", as much as fits.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002212 len = 0;
2213 while (len < maxlen && typeaheadlen > 0)
2214 {
2215 buf[len++] = typeahead[0];
2216 mch_memmove(typeahead, typeahead + 1, --typeaheadlen);
2217 }
K.Takata6e1d31e2022-02-03 13:05:32 +00002218# ifdef FEAT_JOB_CHANNEL
Bram Moolenaar7ca86fe2020-09-03 19:25:11 +02002219 if (len > 0)
2220 {
2221 buf[len] = NUL;
2222 ch_log(NULL, "raw key input: \"%s\"", buf);
2223 }
K.Takata6e1d31e2022-02-03 13:05:32 +00002224# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002225 return len;
2226
Bram Moolenaar0f873732019-12-05 20:28:46 +01002227#else // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00002228 return 0;
Bram Moolenaar0f873732019-12-05 20:28:46 +01002229#endif // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00002230}
2231
Bram Moolenaar82881492012-11-20 16:53:39 +01002232#ifndef PROTO
2233# ifndef __MINGW32__
Bram Moolenaar0f873732019-12-05 20:28:46 +01002234# include <shellapi.h> // required for FindExecutable()
Bram Moolenaar82881492012-11-20 16:53:39 +01002235# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002236#endif
2237
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002238/*
Bram Moolenaar95da1362020-05-30 18:37:55 +02002239 * Return TRUE if "name" is an executable file, FALSE if not or it doesn't exist.
Bram Moolenaar43663192017-03-05 14:29:12 +01002240 * When returning TRUE and "path" is not NULL save the path and set "*path" to
2241 * the allocated memory.
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00002242 * TODO: Should somehow check if it's really executable.
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002243 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002244 static int
Bram Moolenaar95da1362020-05-30 18:37:55 +02002245executable_file(char *name, char_u **path)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002246{
LemonBoy40fd7e62022-05-05 20:18:16 +01002247 int attrs = win32_getattrs((char_u *)name);
2248
2249 // The file doesn't exist or is a folder.
2250 if (attrs == -1 || (attrs & FILE_ATTRIBUTE_DIRECTORY))
2251 return FALSE;
2252 // Check if the file is an AppExecLink, a special alias used by Windows
2253 // Store for its apps.
2254 if (attrs & FILE_ATTRIBUTE_REPARSE_POINT)
Bram Moolenaar43663192017-03-05 14:29:12 +01002255 {
LemonBoy40fd7e62022-05-05 20:18:16 +01002256 char_u *res = resolve_appexeclink((char_u *)name);
2257 if (res == NULL)
2258 return FALSE;
2259 // The path is already absolute.
Bram Moolenaar95da1362020-05-30 18:37:55 +02002260 if (path != NULL)
LemonBoy40fd7e62022-05-05 20:18:16 +01002261 *path = res;
2262 else
2263 vim_free(res);
Bram Moolenaar95da1362020-05-30 18:37:55 +02002264 }
LemonBoy40fd7e62022-05-05 20:18:16 +01002265 else if (path != NULL)
2266 *path = FullName_save((char_u *)name, FALSE);
2267 return TRUE;
Bram Moolenaar95da1362020-05-30 18:37:55 +02002268}
2269
2270/*
2271 * If "use_path" is TRUE: Return TRUE if "name" is in $PATH.
2272 * If "use_path" is FALSE: Return TRUE if "name" exists.
2273 * If "use_pathext" is TRUE search "name" with extensions in $PATHEXT.
2274 * When returning TRUE and "path" is not NULL save the path and set "*path" to
2275 * the allocated memory.
2276 */
2277 static int
2278executable_exists(char *name, char_u **path, int use_path, int use_pathext)
2279{
2280 // WinNT and later can use _MAX_PATH wide characters for a pathname, which
2281 // means that the maximum pathname is _MAX_PATH * 3 bytes when 'enc' is
2282 // UTF-8.
2283 char_u buf[_MAX_PATH * 3];
2284 size_t len = STRLEN(name);
2285 size_t tmplen;
2286 char_u *p, *e, *e2;
2287 char_u *pathbuf = NULL;
2288 char_u *pathext = NULL;
2289 char_u *pathextbuf = NULL;
Mike Williamsa3d1b292021-06-30 20:56:00 +02002290 char_u *shname = NULL;
Bram Moolenaar95da1362020-05-30 18:37:55 +02002291 int noext = FALSE;
2292 int retval = FALSE;
2293
2294 if (len >= sizeof(buf)) // safety check
Bram Moolenaar43663192017-03-05 14:29:12 +01002295 return FALSE;
Bram Moolenaar95da1362020-05-30 18:37:55 +02002296
2297 // Using the name directly when a Unix-shell like 'shell'.
Mike Williamsa3d1b292021-06-30 20:56:00 +02002298 shname = gettail(p_sh);
2299 if (strstr((char *)shname, "sh") != NULL &&
2300 !(strstr((char *)shname, "powershell") != NULL
2301 || strstr((char *)shname, "pwsh") != NULL))
Bram Moolenaar95da1362020-05-30 18:37:55 +02002302 noext = TRUE;
2303
2304 if (use_pathext)
2305 {
2306 pathext = mch_getenv("PATHEXT");
2307 if (pathext == NULL)
2308 pathext = (char_u *)".com;.exe;.bat;.cmd";
2309
2310 if (noext == FALSE)
2311 {
2312 /*
2313 * Loop over all extensions in $PATHEXT.
2314 * Check "name" ends with extension.
2315 */
2316 p = pathext;
2317 while (*p)
2318 {
2319 if (p[0] == ';'
2320 || (p[0] == '.' && (p[1] == NUL || p[1] == ';')))
2321 {
2322 // Skip empty or single ".".
2323 ++p;
2324 continue;
2325 }
2326 e = vim_strchr(p, ';');
2327 if (e == NULL)
2328 e = p + STRLEN(p);
2329 tmplen = e - p;
2330
2331 if (_strnicoll(name + len - tmplen, (char *)p, tmplen) == 0)
2332 {
2333 noext = TRUE;
2334 break;
2335 }
2336
2337 p = e;
2338 }
2339 }
Bram Moolenaar43663192017-03-05 14:29:12 +01002340 }
2341
Dominique Pelleaf4a61a2021-12-27 17:21:41 +00002342 // Prepend single "." to pathext, it means no extension added.
Bram Moolenaar95da1362020-05-30 18:37:55 +02002343 if (pathext == NULL)
2344 pathext = (char_u *)".";
2345 else if (noext == TRUE)
2346 {
2347 if (pathextbuf == NULL)
2348 pathextbuf = alloc(STRLEN(pathext) + 3);
2349 if (pathextbuf == NULL)
2350 {
2351 retval = FALSE;
2352 goto theend;
2353 }
2354 STRCPY(pathextbuf, ".;");
2355 STRCAT(pathextbuf, pathext);
2356 pathext = pathextbuf;
2357 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002358
Bram Moolenaar95da1362020-05-30 18:37:55 +02002359 // Use $PATH when "use_path" is TRUE and "name" is basename.
2360 if (use_path && gettail((char_u *)name) == (char_u *)name)
2361 {
2362 p = mch_getenv("PATH");
2363 if (p != NULL)
2364 {
2365 pathbuf = alloc(STRLEN(p) + 3);
2366 if (pathbuf == NULL)
2367 {
2368 retval = FALSE;
2369 goto theend;
2370 }
Yasuhiro Matsumoto05cf63e2022-05-03 11:02:28 +01002371
2372 if (mch_getenv("NoDefaultCurrentDirectoryInExePath") == NULL)
2373 STRCPY(pathbuf, ".;");
2374 else
2375 *pathbuf = NUL;
Bram Moolenaar95da1362020-05-30 18:37:55 +02002376 STRCAT(pathbuf, p);
2377 }
2378 }
2379
2380 /*
2381 * Walk through all entries in $PATH to check if "name" exists there and
2382 * is an executable file.
2383 */
2384 p = (pathbuf != NULL) ? pathbuf : (char_u *)".";
2385 while (*p)
2386 {
2387 if (*p == ';') // Skip empty entry
2388 {
2389 ++p;
2390 continue;
2391 }
2392 e = vim_strchr(p, ';');
2393 if (e == NULL)
2394 e = p + STRLEN(p);
2395
2396 if (e - p + len + 2 > sizeof(buf))
2397 {
2398 retval = FALSE;
2399 goto theend;
2400 }
2401 // A single "." that means current dir.
2402 if (e - p == 1 && *p == '.')
2403 STRCPY(buf, name);
2404 else
2405 {
2406 vim_strncpy(buf, p, e - p);
2407 add_pathsep(buf);
2408 STRCAT(buf, name);
2409 }
2410 tmplen = STRLEN(buf);
2411
2412 /*
2413 * Loop over all extensions in $PATHEXT.
2414 * Check "name" with extension added.
2415 */
2416 p = pathext;
2417 while (*p)
2418 {
2419 if (*p == ';')
2420 {
2421 // Skip empty entry
2422 ++p;
2423 continue;
2424 }
2425 e2 = vim_strchr(p, (int)';');
2426 if (e2 == NULL)
2427 e2 = p + STRLEN(p);
2428
2429 if (!(p[0] == '.' && (p[1] == NUL || p[1] == ';')))
2430 {
2431 // Not a single "." that means no extension is added.
2432 if (e2 - p + tmplen + 1 > sizeof(buf))
2433 {
2434 retval = FALSE;
2435 goto theend;
2436 }
2437 vim_strncpy(buf + tmplen, p, e2 - p);
2438 }
2439 if (executable_file((char *)buf, path))
2440 {
2441 retval = TRUE;
2442 goto theend;
2443 }
2444
2445 p = e2;
2446 }
2447
2448 p = e;
2449 }
2450
2451theend:
2452 free(pathextbuf);
2453 free(pathbuf);
2454 return retval;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002455}
2456
Bram Moolenaar1eed5322019-02-26 17:03:54 +01002457#if (defined(__MINGW32__) && __MSVCRT_VERSION__ >= 0x800) || \
2458 (defined(_MSC_VER) && _MSC_VER >= 1400)
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002459/*
2460 * Bad parameter handler.
2461 *
2462 * Certain MS CRT functions will intentionally crash when passed invalid
2463 * parameters to highlight possible security holes. Setting this function as
2464 * the bad parameter handler will prevent the crash.
2465 *
2466 * In debug builds the parameters contain CRT information that might help track
2467 * down the source of a problem, but in non-debug builds the arguments are all
2468 * NULL/0. Debug builds will also produce assert dialogs from the CRT, it is
2469 * worth allowing these to make debugging of issues easier.
2470 */
2471 static void
Yegappan Lakshmanana34b4462022-06-11 10:43:26 +01002472bad_param_handler(const wchar_t *expression UNUSED,
2473 const wchar_t *function UNUSED,
2474 const wchar_t *file UNUSED,
2475 unsigned int line UNUSED,
2476 uintptr_t pReserved UNUSED)
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002477{
2478}
2479
2480# define SET_INVALID_PARAM_HANDLER \
2481 ((void)_set_invalid_parameter_handler(bad_param_handler))
2482#else
2483# define SET_INVALID_PARAM_HANDLER
2484#endif
2485
Bram Moolenaar4f974752019-02-17 17:44:42 +01002486#ifdef FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00002487
2488/*
2489 * GUI version of mch_init().
2490 */
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002491 static void
2492mch_init_g(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002493{
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002494# ifndef __MINGW32__
Bram Moolenaar071d4272004-06-13 20:20:40 +00002495 extern int _fmode;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002496# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002497
Bram Moolenaar0f873732019-12-05 20:28:46 +01002498 // Silently handle invalid parameters to CRT functions
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002499 SET_INVALID_PARAM_HANDLER;
2500
Bram Moolenaar0f873732019-12-05 20:28:46 +01002501 // Let critical errors result in a failure, not in a dialog box. Required
2502 // for the timestamp test to work on removed floppies.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002503 SetErrorMode(SEM_FAILCRITICALERRORS);
2504
Bram Moolenaar0f873732019-12-05 20:28:46 +01002505 _fmode = O_BINARY; // we do our own CR-LF translation
Bram Moolenaar071d4272004-06-13 20:20:40 +00002506
Bram Moolenaar0f873732019-12-05 20:28:46 +01002507 // Specify window size. Is there a place to get the default from?
Bram Moolenaar071d4272004-06-13 20:20:40 +00002508 Rows = 25;
2509 Columns = 80;
2510
Bram Moolenaar0f873732019-12-05 20:28:46 +01002511 // Look for 'vimrun'
Bram Moolenaar071d4272004-06-13 20:20:40 +00002512 {
2513 char_u vimrun_location[_MAX_PATH + 4];
2514
Bram Moolenaar0f873732019-12-05 20:28:46 +01002515 // First try in same directory as gvim.exe
Bram Moolenaar071d4272004-06-13 20:20:40 +00002516 STRCPY(vimrun_location, exe_name);
2517 STRCPY(gettail(vimrun_location), "vimrun.exe");
2518 if (mch_getperm(vimrun_location) >= 0)
2519 {
2520 if (*skiptowhite(vimrun_location) != NUL)
2521 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01002522 // Enclose path with white space in double quotes.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002523 mch_memmove(vimrun_location + 1, vimrun_location,
2524 STRLEN(vimrun_location) + 1);
2525 *vimrun_location = '"';
2526 STRCPY(gettail(vimrun_location), "vimrun\" ");
2527 }
2528 else
2529 STRCPY(gettail(vimrun_location), "vimrun ");
2530
2531 vimrun_path = (char *)vim_strsave(vimrun_location);
2532 s_dont_use_vimrun = FALSE;
2533 }
Bram Moolenaar95da1362020-05-30 18:37:55 +02002534 else if (executable_exists("vimrun.exe", NULL, TRUE, FALSE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002535 s_dont_use_vimrun = FALSE;
2536
Bram Moolenaar0f873732019-12-05 20:28:46 +01002537 // Don't give the warning for a missing vimrun.exe right now, but only
2538 // when vimrun was supposed to be used. Don't bother people that do
2539 // not need vimrun.exe.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002540 if (s_dont_use_vimrun)
2541 need_vimrun_warning = TRUE;
2542 }
2543
2544 /*
2545 * If "finstr.exe" doesn't exist, use "grep -n" for 'grepprg'.
2546 * Otherwise the default "findstr /n" is used.
2547 */
Bram Moolenaar95da1362020-05-30 18:37:55 +02002548 if (!executable_exists("findstr.exe", NULL, TRUE, FALSE))
Bram Moolenaar75ab5902022-04-18 15:36:40 +01002549 set_option_value_give_err((char_u *)"grepprg",
2550 0, (char_u *)"grep -n", 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002551
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002552# ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01002553 win_clip_init();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002554# endif
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01002555
2556 vtp_flag_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002557}
2558
2559
Bram Moolenaar0f873732019-12-05 20:28:46 +01002560#endif // FEAT_GUI_MSWIN
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002561
2562#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002563
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002564# define SRWIDTH(sr) ((sr).Right - (sr).Left + 1)
2565# define SRHEIGHT(sr) ((sr).Bottom - (sr).Top + 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002566
2567/*
2568 * ClearConsoleBuffer()
2569 * Description:
2570 * Clears the entire contents of the console screen buffer, using the
2571 * specified attribute.
2572 * Returns:
2573 * TRUE on success
2574 */
2575 static BOOL
2576ClearConsoleBuffer(WORD wAttribute)
2577{
2578 CONSOLE_SCREEN_BUFFER_INFO csbi;
2579 COORD coord;
2580 DWORD NumCells, dummy;
2581
2582 if (!GetConsoleScreenBufferInfo(g_hConOut, &csbi))
2583 return FALSE;
2584
2585 NumCells = csbi.dwSize.X * csbi.dwSize.Y;
2586 coord.X = 0;
2587 coord.Y = 0;
2588 if (!FillConsoleOutputCharacter(g_hConOut, ' ', NumCells,
2589 coord, &dummy))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002590 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002591 if (!FillConsoleOutputAttribute(g_hConOut, wAttribute, NumCells,
2592 coord, &dummy))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002593 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002594
2595 return TRUE;
2596}
2597
2598/*
2599 * FitConsoleWindow()
2600 * Description:
2601 * Checks if the console window will fit within given buffer dimensions.
2602 * Also, if requested, will shrink the window to fit.
2603 * Returns:
2604 * TRUE on success
2605 */
2606 static BOOL
2607FitConsoleWindow(
2608 COORD dwBufferSize,
2609 BOOL WantAdjust)
2610{
2611 CONSOLE_SCREEN_BUFFER_INFO csbi;
2612 COORD dwWindowSize;
2613 BOOL NeedAdjust = FALSE;
2614
2615 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
2616 {
2617 /*
2618 * A buffer resize will fail if the current console window does
2619 * not lie completely within that buffer. To avoid this, we might
2620 * have to move and possibly shrink the window.
2621 */
2622 if (csbi.srWindow.Right >= dwBufferSize.X)
2623 {
2624 dwWindowSize.X = SRWIDTH(csbi.srWindow);
2625 if (dwWindowSize.X > dwBufferSize.X)
2626 dwWindowSize.X = dwBufferSize.X;
2627 csbi.srWindow.Right = dwBufferSize.X - 1;
2628 csbi.srWindow.Left = dwBufferSize.X - dwWindowSize.X;
2629 NeedAdjust = TRUE;
2630 }
2631 if (csbi.srWindow.Bottom >= dwBufferSize.Y)
2632 {
2633 dwWindowSize.Y = SRHEIGHT(csbi.srWindow);
2634 if (dwWindowSize.Y > dwBufferSize.Y)
2635 dwWindowSize.Y = dwBufferSize.Y;
2636 csbi.srWindow.Bottom = dwBufferSize.Y - 1;
2637 csbi.srWindow.Top = dwBufferSize.Y - dwWindowSize.Y;
2638 NeedAdjust = TRUE;
2639 }
2640 if (NeedAdjust && WantAdjust)
2641 {
2642 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &csbi.srWindow))
2643 return FALSE;
2644 }
2645 return TRUE;
2646 }
2647
2648 return FALSE;
2649}
2650
2651typedef struct ConsoleBufferStruct
2652{
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002653 BOOL IsValid;
2654 CONSOLE_SCREEN_BUFFER_INFO Info;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002655 PCHAR_INFO Buffer;
2656 COORD BufferSize;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002657 PSMALL_RECT Regions;
2658 int NumRegions;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002659} ConsoleBuffer;
2660
2661/*
2662 * SaveConsoleBuffer()
2663 * Description:
2664 * Saves important information about the console buffer, including the
2665 * actual buffer contents. The saved information is suitable for later
2666 * restoration by RestoreConsoleBuffer().
2667 * Returns:
2668 * TRUE if all information was saved; FALSE otherwise
2669 * If FALSE, still sets cb->IsValid if buffer characteristics were saved.
2670 */
2671 static BOOL
2672SaveConsoleBuffer(
2673 ConsoleBuffer *cb)
2674{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002675 DWORD NumCells;
2676 COORD BufferCoord;
2677 SMALL_RECT ReadRegion;
2678 WORD Y, Y_incr;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002679 int i, numregions;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002680
Bram Moolenaar071d4272004-06-13 20:20:40 +00002681 if (cb == NULL)
2682 return FALSE;
2683
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002684 if (!GetConsoleScreenBufferInfo(g_hConOut, &cb->Info))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002685 {
2686 cb->IsValid = FALSE;
2687 return FALSE;
2688 }
2689 cb->IsValid = TRUE;
2690
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002691 /*
2692 * Allocate a buffer large enough to hold the entire console screen
2693 * buffer. If this ConsoleBuffer structure has already been initialized
2694 * with a buffer of the correct size, then just use that one.
2695 */
2696 if (!cb->IsValid || cb->Buffer == NULL ||
2697 cb->BufferSize.X != cb->Info.dwSize.X ||
2698 cb->BufferSize.Y != cb->Info.dwSize.Y)
2699 {
2700 cb->BufferSize.X = cb->Info.dwSize.X;
2701 cb->BufferSize.Y = cb->Info.dwSize.Y;
2702 NumCells = cb->BufferSize.X * cb->BufferSize.Y;
2703 vim_free(cb->Buffer);
Bram Moolenaarc799fe22019-05-28 23:08:19 +02002704 cb->Buffer = ALLOC_MULT(CHAR_INFO, NumCells);
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002705 if (cb->Buffer == NULL)
2706 return FALSE;
2707 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002708
2709 /*
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002710 * We will now copy the console screen buffer into our buffer.
2711 * ReadConsoleOutput() seems to be limited as far as how much you
2712 * can read at a time. Empirically, this number seems to be about
2713 * 12000 cells (rows * columns). Start at position (0, 0) and copy
2714 * in chunks until it is all copied. The chunks will all have the
2715 * same horizontal characteristics, so initialize them now. The
2716 * height of each chunk will be (12000 / width).
Bram Moolenaar071d4272004-06-13 20:20:40 +00002717 */
Bram Moolenaar61594242015-09-01 20:23:37 +02002718 BufferCoord.X = 0;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002719 ReadRegion.Left = 0;
2720 ReadRegion.Right = cb->Info.dwSize.X - 1;
2721 Y_incr = 12000 / cb->Info.dwSize.X;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002722
2723 numregions = (cb->Info.dwSize.Y + Y_incr - 1) / Y_incr;
2724 if (cb->Regions == NULL || numregions != cb->NumRegions)
2725 {
2726 cb->NumRegions = numregions;
2727 vim_free(cb->Regions);
Bram Moolenaarc799fe22019-05-28 23:08:19 +02002728 cb->Regions = ALLOC_MULT(SMALL_RECT, cb->NumRegions);
Bram Moolenaar444fda22017-08-11 20:37:00 +02002729 if (cb->Regions == NULL)
2730 {
Bram Moolenaard23a8232018-02-10 18:45:26 +01002731 VIM_CLEAR(cb->Buffer);
Bram Moolenaar444fda22017-08-11 20:37:00 +02002732 return FALSE;
2733 }
2734 }
2735
2736 for (i = 0, Y = 0; i < cb->NumRegions; i++, Y += Y_incr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002737 {
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002738 /*
2739 * Read into position (0, Y) in our buffer.
2740 */
2741 BufferCoord.Y = Y;
2742 /*
2743 * Read the region whose top left corner is (0, Y) and whose bottom
2744 * right corner is (width - 1, Y + Y_incr - 1). This should define
2745 * a region of size width by Y_incr. Don't worry if this region is
2746 * too large for the remaining buffer; it will be cropped.
2747 */
2748 ReadRegion.Top = Y;
2749 ReadRegion.Bottom = Y + Y_incr - 1;
Bram Moolenaar0f873732019-12-05 20:28:46 +01002750 if (!ReadConsoleOutputW(g_hConOut, // output handle
2751 cb->Buffer, // our buffer
2752 cb->BufferSize, // dimensions of our buffer
2753 BufferCoord, // offset in our buffer
2754 &ReadRegion)) // region to save
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002755 {
Bram Moolenaard23a8232018-02-10 18:45:26 +01002756 VIM_CLEAR(cb->Buffer);
2757 VIM_CLEAR(cb->Regions);
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002758 return FALSE;
2759 }
Bram Moolenaar444fda22017-08-11 20:37:00 +02002760 cb->Regions[i] = ReadRegion;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002761 }
2762
2763 return TRUE;
2764}
2765
2766/*
2767 * RestoreConsoleBuffer()
2768 * Description:
2769 * Restores important information about the console buffer, including the
2770 * actual buffer contents, if desired. The information to restore is in
2771 * the same format used by SaveConsoleBuffer().
2772 * Returns:
2773 * TRUE on success
2774 */
2775 static BOOL
2776RestoreConsoleBuffer(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002777 ConsoleBuffer *cb,
2778 BOOL RestoreScreen)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002779{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002780 COORD BufferCoord;
2781 SMALL_RECT WriteRegion;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002782 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002783
2784 if (cb == NULL || !cb->IsValid)
2785 return FALSE;
2786
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002787 /*
2788 * Before restoring the buffer contents, clear the current buffer, and
2789 * restore the cursor position and window information. Doing this now
2790 * prevents old buffer contents from "flashing" onto the screen.
2791 */
2792 if (RestoreScreen)
2793 ClearConsoleBuffer(cb->Info.wAttributes);
2794
2795 FitConsoleWindow(cb->Info.dwSize, TRUE);
2796 if (!SetConsoleScreenBufferSize(g_hConOut, cb->Info.dwSize))
2797 return FALSE;
2798 if (!SetConsoleTextAttribute(g_hConOut, cb->Info.wAttributes))
2799 return FALSE;
2800
2801 if (!RestoreScreen)
2802 {
2803 /*
2804 * No need to restore the screen buffer contents, so we're done.
2805 */
2806 return TRUE;
2807 }
2808
2809 if (!SetConsoleCursorPosition(g_hConOut, cb->Info.dwCursorPosition))
2810 return FALSE;
2811 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &cb->Info.srWindow))
2812 return FALSE;
2813
2814 /*
2815 * Restore the screen buffer contents.
2816 */
2817 if (cb->Buffer != NULL)
2818 {
Bram Moolenaar444fda22017-08-11 20:37:00 +02002819 for (i = 0; i < cb->NumRegions; i++)
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002820 {
Bram Moolenaar444fda22017-08-11 20:37:00 +02002821 BufferCoord.X = cb->Regions[i].Left;
2822 BufferCoord.Y = cb->Regions[i].Top;
2823 WriteRegion = cb->Regions[i];
Bram Moolenaar0f873732019-12-05 20:28:46 +01002824 if (!WriteConsoleOutputW(g_hConOut, // output handle
2825 cb->Buffer, // our buffer
2826 cb->BufferSize, // dimensions of our buffer
2827 BufferCoord, // offset in our buffer
2828 &WriteRegion)) // region to restore
Bram Moolenaar444fda22017-08-11 20:37:00 +02002829 return FALSE;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002830 }
2831 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002832
2833 return TRUE;
2834}
2835
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002836# define FEAT_RESTORE_ORIG_SCREEN
2837# ifdef FEAT_RESTORE_ORIG_SCREEN
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002838static ConsoleBuffer g_cbOrig = { 0 };
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002839# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002840static ConsoleBuffer g_cbNonTermcap = { 0 };
2841static ConsoleBuffer g_cbTermcap = { 0 };
2842
Bram Moolenaar071d4272004-06-13 20:20:40 +00002843char g_szOrigTitle[256] = { 0 };
Bram Moolenaar0f873732019-12-05 20:28:46 +01002844HWND g_hWnd = NULL; // also used in os_mswin.c
Bram Moolenaar071d4272004-06-13 20:20:40 +00002845static HICON g_hOrigIconSmall = NULL;
2846static HICON g_hOrigIcon = NULL;
2847static HICON g_hVimIcon = NULL;
2848static BOOL g_fCanChangeIcon = FALSE;
2849
Bram Moolenaar071d4272004-06-13 20:20:40 +00002850/*
2851 * GetConsoleIcon()
2852 * Description:
2853 * Attempts to retrieve the small icon and/or the big icon currently in
2854 * use by a given window.
2855 * Returns:
2856 * TRUE on success
2857 */
2858 static BOOL
2859GetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002860 HWND hWnd,
2861 HICON *phIconSmall,
2862 HICON *phIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002863{
2864 if (hWnd == NULL)
2865 return FALSE;
2866
2867 if (phIconSmall != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002868 *phIconSmall = (HICON)SendMessage(hWnd, WM_GETICON,
2869 (WPARAM)ICON_SMALL, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002870 if (phIcon != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002871 *phIcon = (HICON)SendMessage(hWnd, WM_GETICON,
2872 (WPARAM)ICON_BIG, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002873 return TRUE;
2874}
2875
2876/*
2877 * SetConsoleIcon()
2878 * Description:
2879 * Attempts to change the small icon and/or the big icon currently in
2880 * use by a given window.
2881 * Returns:
2882 * TRUE on success
2883 */
2884 static BOOL
2885SetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002886 HWND hWnd,
2887 HICON hIconSmall,
2888 HICON hIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002889{
Bram Moolenaar071d4272004-06-13 20:20:40 +00002890 if (hWnd == NULL)
2891 return FALSE;
2892
2893 if (hIconSmall != NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002894 SendMessage(hWnd, WM_SETICON,
2895 (WPARAM)ICON_SMALL, (LPARAM)hIconSmall);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002896 if (hIcon != NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002897 SendMessage(hWnd, WM_SETICON,
2898 (WPARAM)ICON_BIG, (LPARAM) hIcon);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002899 return TRUE;
2900}
2901
2902/*
2903 * SaveConsoleTitleAndIcon()
2904 * Description:
2905 * Saves the current console window title in g_szOrigTitle, for later
2906 * restoration. Also, attempts to obtain a handle to the console window,
2907 * and use it to save the small and big icons currently in use by the
2908 * console window. This is not always possible on some versions of Windows;
2909 * nor is it possible when running Vim remotely using Telnet (since the
2910 * console window the user sees is owned by a remote process).
2911 */
2912 static void
2913SaveConsoleTitleAndIcon(void)
2914{
Bram Moolenaar0f873732019-12-05 20:28:46 +01002915 // Save the original title.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002916 if (!GetConsoleTitle(g_szOrigTitle, sizeof(g_szOrigTitle)))
2917 return;
2918
2919 /*
2920 * Obtain a handle to the console window using GetConsoleWindow() from
2921 * KERNEL32.DLL; we need to handle in order to change the window icon.
2922 * This function only exists on NT-based Windows, starting with Windows
2923 * 2000. On older operating systems, we can't change the window icon
2924 * anyway.
2925 */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02002926 g_hWnd = GetConsoleWindow();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002927 if (g_hWnd == NULL)
2928 return;
2929
Bram Moolenaar0f873732019-12-05 20:28:46 +01002930 // Save the original console window icon.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002931 GetConsoleIcon(g_hWnd, &g_hOrigIconSmall, &g_hOrigIcon);
2932 if (g_hOrigIconSmall == NULL || g_hOrigIcon == NULL)
2933 return;
2934
Bram Moolenaar0f873732019-12-05 20:28:46 +01002935 // Extract the first icon contained in the Vim executable.
K.Takata2da11a42022-09-10 13:03:12 +01002936 if (
2937# ifdef FEAT_LIBCALL
2938 mch_icon_load((HANDLE *)&g_hVimIcon) == FAIL ||
2939# endif
2940 g_hVimIcon == NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002941 g_hVimIcon = ExtractIcon(NULL, (LPCSTR)exe_name, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002942 if (g_hVimIcon != NULL)
2943 g_fCanChangeIcon = TRUE;
2944}
Bram Moolenaar071d4272004-06-13 20:20:40 +00002945
2946static int g_fWindInitCalled = FALSE;
2947static int g_fTermcapMode = FALSE;
2948static CONSOLE_CURSOR_INFO g_cci;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002949
2950/*
2951 * non-GUI version of mch_init().
2952 */
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002953 static void
2954mch_init_c(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002955{
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002956# ifndef FEAT_RESTORE_ORIG_SCREEN
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002957 CONSOLE_SCREEN_BUFFER_INFO csbi;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002958# endif
2959# ifndef __MINGW32__
Bram Moolenaar071d4272004-06-13 20:20:40 +00002960 extern int _fmode;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002961# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002962
Bram Moolenaar0f873732019-12-05 20:28:46 +01002963 // Silently handle invalid parameters to CRT functions
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002964 SET_INVALID_PARAM_HANDLER;
2965
Bram Moolenaar0f873732019-12-05 20:28:46 +01002966 // Let critical errors result in a failure, not in a dialog box. Required
2967 // for the timestamp test to work on removed floppies.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002968 SetErrorMode(SEM_FAILCRITICALERRORS);
2969
Bram Moolenaar0f873732019-12-05 20:28:46 +01002970 _fmode = O_BINARY; // we do our own CR-LF translation
Bram Moolenaar071d4272004-06-13 20:20:40 +00002971 out_flush();
2972
Bram Moolenaar0f873732019-12-05 20:28:46 +01002973 // Obtain handles for the standard Console I/O devices
Bram Moolenaar071d4272004-06-13 20:20:40 +00002974 if (read_cmd_fd == 0)
2975 g_hConIn = GetStdHandle(STD_INPUT_HANDLE);
2976 else
2977 create_conin();
2978 g_hConOut = GetStdHandle(STD_OUTPUT_HANDLE);
2979
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002980# ifdef FEAT_RESTORE_ORIG_SCREEN
Bram Moolenaar0f873732019-12-05 20:28:46 +01002981 // Save the initial console buffer for later restoration
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002982 SaveConsoleBuffer(&g_cbOrig);
2983 g_attrCurrent = g_attrDefault = g_cbOrig.Info.wAttributes;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002984# else
Bram Moolenaar0f873732019-12-05 20:28:46 +01002985 // Get current text attributes
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002986 GetConsoleScreenBufferInfo(g_hConOut, &csbi);
2987 g_attrCurrent = g_attrDefault = csbi.wAttributes;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002988# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002989 if (cterm_normal_fg_color == 0)
2990 cterm_normal_fg_color = (g_attrCurrent & 0xf) + 1;
2991 if (cterm_normal_bg_color == 0)
2992 cterm_normal_bg_color = ((g_attrCurrent >> 4) & 0xf) + 1;
2993
Bram Moolenaarbdace832019-03-02 10:13:42 +01002994 // Fg and Bg color index number at startup
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02002995 g_color_index_fg = g_attrDefault & 0xf;
2996 g_color_index_bg = (g_attrDefault >> 4) & 0xf;
2997
Bram Moolenaar0f873732019-12-05 20:28:46 +01002998 // set termcap codes to current text attributes
Bram Moolenaar071d4272004-06-13 20:20:40 +00002999 update_tcap(g_attrCurrent);
3000
3001 GetConsoleCursorInfo(g_hConOut, &g_cci);
3002 GetConsoleMode(g_hConIn, &g_cmodein);
3003 GetConsoleMode(g_hConOut, &g_cmodeout);
3004
Bram Moolenaar071d4272004-06-13 20:20:40 +00003005 SaveConsoleTitleAndIcon();
3006 /*
3007 * Set both the small and big icons of the console window to Vim's icon.
3008 * Note that Vim presently only has one size of icon (32x32), but it
3009 * automatically gets scaled down to 16x16 when setting the small icon.
3010 */
3011 if (g_fCanChangeIcon)
3012 SetConsoleIcon(g_hWnd, g_hVimIcon, g_hVimIcon);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003013
3014 ui_get_shellsize();
3015
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003016# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00003017 fdDump = fopen("dump", "wt");
3018
3019 if (fdDump)
3020 {
3021 time_t t;
3022
3023 time(&t);
3024 fputs(ctime(&t), fdDump);
3025 fflush(fdDump);
3026 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003027# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003028
3029 g_fWindInitCalled = TRUE;
3030
Bram Moolenaar071d4272004-06-13 20:20:40 +00003031 g_fMouseAvail = GetSystemMetrics(SM_MOUSEPRESENT);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003032
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003033# ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01003034 win_clip_init();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003035# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01003036
Bram Moolenaar81ccbf12020-04-15 21:05:30 +02003037 vtp_flag_init();
Bram Moolenaarcafafb32018-02-22 21:07:09 +01003038 vtp_init();
Bram Moolenaar06b7b582020-05-30 17:49:25 +02003039 wt_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00003040}
3041
3042/*
3043 * non-GUI version of mch_exit().
3044 * Shut down and exit with status `r'
3045 * Careful: mch_exit() may be called before mch_init()!
3046 */
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003047 static void
3048mch_exit_c(int r)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003049{
Bram Moolenaar955f1982017-02-05 15:10:51 +01003050 exiting = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003051
Bram Moolenaarcafafb32018-02-22 21:07:09 +01003052 vtp_exit();
3053
Bram Moolenaar955f1982017-02-05 15:10:51 +01003054 stoptermcap();
Bram Moolenaar071d4272004-06-13 20:20:40 +00003055 if (g_fWindInitCalled)
3056 settmode(TMODE_COOK);
3057
Bram Moolenaar0f873732019-12-05 20:28:46 +01003058 ml_close_all(TRUE); // remove all memfiles
Bram Moolenaar071d4272004-06-13 20:20:40 +00003059
3060 if (g_fWindInitCalled)
3061 {
Bram Moolenaar40385db2018-08-07 22:31:44 +02003062 mch_restore_title(SAVE_RESTORE_BOTH);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003063 /*
3064 * Restore both the small and big icons of the console window to
3065 * what they were at startup. Don't do this when the window is
3066 * closed, Vim would hang here.
3067 */
3068 if (g_fCanChangeIcon && !g_fForceExit)
3069 SetConsoleIcon(g_hWnd, g_hOrigIconSmall, g_hOrigIcon);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003070
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003071# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00003072 if (fdDump)
3073 {
3074 time_t t;
3075
3076 time(&t);
3077 fputs(ctime(&t), fdDump);
3078 fclose(fdDump);
3079 }
3080 fdDump = NULL;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003081# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003082 }
3083
3084 SetConsoleCursorInfo(g_hConOut, &g_cci);
Wez Furlong6ef5ab52021-05-30 19:29:41 +02003085 SetConsoleMode(g_hConIn, g_cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003086 SetConsoleMode(g_hConOut, g_cmodeout);
3087
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003088# ifdef DYNAMIC_GETTEXT
Bram Moolenaar071d4272004-06-13 20:20:40 +00003089 dyn_libintl_end();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003090# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003091
3092 exit(r);
3093}
Bram Moolenaar0f873732019-12-05 20:28:46 +01003094#endif // !FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00003095
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003096 void
3097mch_init(void)
3098{
3099#ifdef VIMDLL
3100 if (gui.starting)
3101 mch_init_g();
3102 else
3103 mch_init_c();
3104#elif defined(FEAT_GUI_MSWIN)
3105 mch_init_g();
3106#else
3107 mch_init_c();
3108#endif
3109}
3110
3111 void
3112mch_exit(int r)
3113{
Bram Moolenaar173d8412020-04-19 14:02:26 +02003114#ifdef FEAT_NETBEANS_INTG
3115 netbeans_send_disconnect();
3116#endif
3117
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003118#ifdef VIMDLL
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02003119 if (gui.in_use || gui.starting)
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003120 mch_exit_g(r);
3121 else
3122 mch_exit_c(r);
3123#elif defined(FEAT_GUI_MSWIN)
3124 mch_exit_g(r);
3125#else
3126 mch_exit_c(r);
3127#endif
3128}
3129
Bram Moolenaar071d4272004-06-13 20:20:40 +00003130/*
3131 * Do we have an interactive window?
3132 */
3133 int
3134mch_check_win(
Bram Moolenaar1266d672017-02-01 13:43:36 +01003135 int argc UNUSED,
3136 char **argv UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003137{
3138 get_exe_name();
3139
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003140#if defined(FEAT_GUI_MSWIN) && !defined(VIMDLL)
Bram Moolenaar0f873732019-12-05 20:28:46 +01003141 return OK; // GUI always has a tty
Bram Moolenaar071d4272004-06-13 20:20:40 +00003142#else
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003143# ifdef VIMDLL
3144 if (gui.in_use)
3145 return OK;
3146# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003147 if (isatty(1))
3148 return OK;
3149 return FAIL;
3150#endif
3151}
3152
Bram Moolenaar65f04f62013-08-30 17:29:16 +02003153/*
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003154 * Set the case of the file name, if it already exists.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003155 * When "len" is > 0, also expand short to long filenames.
3156 */
3157 void
3158fname_case(
3159 char_u *name,
3160 int len)
3161{
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003162 int flen;
3163 WCHAR *p;
3164 WCHAR buf[_MAX_PATH + 1];
Bram Moolenaar071d4272004-06-13 20:20:40 +00003165
Bram Moolenaara3ffd9c2005-07-21 21:03:15 +00003166 flen = (int)STRLEN(name);
Bram Moolenaar65f04f62013-08-30 17:29:16 +02003167 if (flen == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003168 return;
3169
3170 slash_adjust(name);
3171
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003172 p = enc_to_utf16(name, NULL);
3173 if (p == NULL)
Bram Moolenaar65f04f62013-08-30 17:29:16 +02003174 return;
3175
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003176 if (GetLongPathNameW(p, buf, _MAX_PATH))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003177 {
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003178 char_u *q = utf16_to_enc(buf, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003179
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003180 if (q != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003181 {
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003182 if (len > 0 || flen >= (int)STRLEN(q))
3183 vim_strncpy(name, q, (len > 0) ? len - 1 : flen);
3184 vim_free(q);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003185 }
3186 }
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003187 vim_free(p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003188}
3189
3190
3191/*
3192 * Insert user name in s[len].
3193 */
3194 int
3195mch_get_user_name(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003196 char_u *s,
3197 int len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003198{
Bram Moolenaar0f873732019-12-05 20:28:46 +01003199 WCHAR wszUserName[256 + 1]; // UNLEN is 256
K.Takataeeec2542021-06-02 13:28:16 +02003200 DWORD wcch = ARRAY_LENGTH(wszUserName);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003201
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003202 if (GetUserNameW(wszUserName, &wcch))
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003203 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003204 char_u *p = utf16_to_enc(wszUserName, NULL);
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003205
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003206 if (p != NULL)
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003207 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003208 vim_strncpy(s, p, len - 1);
3209 vim_free(p);
3210 return OK;
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003211 }
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003212 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003213 s[0] = NUL;
3214 return FAIL;
3215}
3216
3217
3218/*
3219 * Insert host name in s[len].
3220 */
3221 void
3222mch_get_host_name(
3223 char_u *s,
3224 int len)
3225{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003226 WCHAR wszHostName[256 + 1];
K.Takataeeec2542021-06-02 13:28:16 +02003227 DWORD wcch = ARRAY_LENGTH(wszHostName);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003228
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003229 if (GetComputerNameW(wszHostName, &wcch))
Bram Moolenaar2cc87382013-12-11 18:21:45 +01003230 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003231 char_u *p = utf16_to_enc(wszHostName, NULL);
Bram Moolenaar2cc87382013-12-11 18:21:45 +01003232
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003233 if (p != NULL)
Bram Moolenaar2cc87382013-12-11 18:21:45 +01003234 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003235 vim_strncpy(s, p, len - 1);
3236 vim_free(p);
3237 return;
Bram Moolenaar2cc87382013-12-11 18:21:45 +01003238 }
Bram Moolenaar2cc87382013-12-11 18:21:45 +01003239 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003240}
3241
3242
3243/*
3244 * return process ID
3245 */
3246 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003247mch_get_pid(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003248{
3249 return (long)GetCurrentProcessId();
3250}
3251
Bram Moolenaar67cf86b2019-04-28 22:25:38 +02003252/*
3253 * return TRUE if process "pid" is still running
3254 */
3255 int
Bram Moolenaar1b243ea2019-04-28 22:50:40 +02003256mch_process_running(long pid)
Bram Moolenaar67cf86b2019-04-28 22:25:38 +02003257{
3258 HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION, 0, (DWORD)pid);
3259 DWORD status = 0;
3260 int ret = FALSE;
3261
3262 if (hProcess == NULL)
3263 return FALSE; // might not have access
3264 if (GetExitCodeProcess(hProcess, &status) )
3265 ret = status == STILL_ACTIVE;
3266 CloseHandle(hProcess);
3267 return ret;
3268}
Bram Moolenaar071d4272004-06-13 20:20:40 +00003269
3270/*
3271 * Get name of current directory into buffer 'buf' of length 'len' bytes.
3272 * Return OK for success, FAIL for failure.
3273 */
3274 int
3275mch_dirname(
3276 char_u *buf,
3277 int len)
3278{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003279 WCHAR wbuf[_MAX_PATH + 1];
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02003280
Bram Moolenaar071d4272004-06-13 20:20:40 +00003281 /*
3282 * Originally this was:
3283 * return (getcwd(buf, len) != NULL ? OK : FAIL);
3284 * But the Win32s known bug list says that getcwd() doesn't work
3285 * so use the Win32 system call instead. <Negri>
3286 */
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003287 if (GetCurrentDirectoryW(_MAX_PATH, wbuf) != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003288 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003289 WCHAR wcbuf[_MAX_PATH + 1];
3290 char_u *p = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003291
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003292 if (GetLongPathNameW(wbuf, wcbuf, _MAX_PATH) != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003293 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003294 p = utf16_to_enc(wcbuf, NULL);
3295 if (STRLEN(p) >= (size_t)len)
Bram Moolenaarcea1f9e2018-08-19 14:38:42 +02003296 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003297 // long path name is too long, fall back to short one
Bram Moolenaar071d4272004-06-13 20:20:40 +00003298 vim_free(p);
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003299 p = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003300 }
3301 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003302 if (p == NULL)
3303 p = utf16_to_enc(wbuf, NULL);
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02003304
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003305 if (p != NULL)
3306 {
3307 vim_strncpy(buf, p, len - 1);
3308 vim_free(p);
3309 return OK;
3310 }
3311 }
3312 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003313}
3314
3315/*
Bram Moolenaarffa22202013-11-21 12:34:11 +01003316 * Get file permissions for "name".
3317 * Return mode_t or -1 for error.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003318 */
3319 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003320mch_getperm(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003321{
Bram Moolenaar8767f522016-07-01 17:17:39 +02003322 stat_T st;
Bram Moolenaarffa22202013-11-21 12:34:11 +01003323 int n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003324
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003325 n = mch_stat((char *)name, &st);
Bram Moolenaar78cf3f02014-01-10 18:16:07 +01003326 return n == 0 ? (long)(unsigned short)st.st_mode : -1L;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003327}
3328
3329
3330/*
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003331 * Set file permission for "name" to "perm".
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003332 *
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003333 * Return FAIL for failure, OK otherwise.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003334 */
3335 int
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003336mch_setperm(char_u *name, long perm)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003337{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003338 long n;
3339 WCHAR *p;
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003340
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003341 p = enc_to_utf16(name, NULL);
3342 if (p == NULL)
3343 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003344
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003345 n = _wchmod(p, perm);
3346 vim_free(p);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003347 if (n == -1)
3348 return FAIL;
3349
3350 win32_set_archive(name);
3351
3352 return OK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003353}
3354
3355/*
3356 * Set hidden flag for "name".
3357 */
3358 void
3359mch_hide(char_u *name)
3360{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003361 int attrs = win32_getattrs(name);
3362 if (attrs == -1)
3363 return;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003364
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003365 attrs |= FILE_ATTRIBUTE_HIDDEN;
3366 win32_setattrs(name, attrs);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003367}
3368
3369/*
Bram Moolenaar8a52ba72015-11-02 14:45:56 +01003370 * Return TRUE if file "name" exists and is hidden.
3371 */
3372 int
3373mch_ishidden(char_u *name)
3374{
3375 int f = win32_getattrs(name);
3376
3377 if (f == -1)
Bram Moolenaar0f873732019-12-05 20:28:46 +01003378 return FALSE; // file does not exist at all
Bram Moolenaar8a52ba72015-11-02 14:45:56 +01003379
3380 return (f & FILE_ATTRIBUTE_HIDDEN) != 0;
3381}
3382
3383/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003384 * return TRUE if "name" is a directory
3385 * return FALSE if "name" is not a directory or upon error
3386 */
3387 int
3388mch_isdir(char_u *name)
3389{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003390 int f = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003391
3392 if (f == -1)
Bram Moolenaar0f873732019-12-05 20:28:46 +01003393 return FALSE; // file does not exist at all
Bram Moolenaar071d4272004-06-13 20:20:40 +00003394
3395 return (f & FILE_ATTRIBUTE_DIRECTORY) != 0;
3396}
3397
3398/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01003399 * return TRUE if "name" is a directory, NOT a symlink to a directory
3400 * return FALSE if "name" is not a directory
3401 * return FALSE for error
3402 */
3403 int
3404mch_isrealdir(char_u *name)
3405{
3406 return mch_isdir(name) && !mch_is_symbolic_link(name);
3407}
3408
3409/*
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003410 * Create directory "name".
3411 * Return 0 on success, -1 on error.
3412 */
3413 int
3414mch_mkdir(char_u *name)
3415{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003416 WCHAR *p;
3417 int retval;
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003418
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003419 p = enc_to_utf16(name, NULL);
3420 if (p == NULL)
3421 return -1;
3422 retval = _wmkdir(p);
3423 vim_free(p);
3424 return retval;
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003425}
3426
3427/*
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003428 * Delete directory "name".
3429 * Return 0 on success, -1 on error.
3430 */
3431 int
3432mch_rmdir(char_u *name)
3433{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003434 WCHAR *p;
3435 int retval;
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003436
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003437 p = enc_to_utf16(name, NULL);
3438 if (p == NULL)
3439 return -1;
3440 retval = _wrmdir(p);
3441 vim_free(p);
3442 return retval;
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003443}
3444
3445/*
Bram Moolenaar03f48552006-02-28 23:52:23 +00003446 * Return TRUE if file "fname" has more than one link.
3447 */
3448 int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003449mch_is_hard_link(char_u *fname)
Bram Moolenaar03f48552006-02-28 23:52:23 +00003450{
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003451 BY_HANDLE_FILE_INFORMATION info;
3452
3453 return win32_fileinfo(fname, &info) == FILEINFO_OK
3454 && info.nNumberOfLinks > 1;
3455}
3456
3457/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01003458 * Return TRUE if "name" is a symbolic link (or a junction).
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003459 */
3460 int
Bram Moolenaar203258c2016-01-17 22:15:16 +01003461mch_is_symbolic_link(char_u *name)
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003462{
3463 HANDLE hFind;
3464 int res = FALSE;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003465 DWORD fileFlags = 0, reparseTag = 0;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003466 WCHAR *wn;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003467 WIN32_FIND_DATAW findDataW;
3468
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003469 wn = enc_to_utf16(name, NULL);
3470 if (wn == NULL)
3471 return FALSE;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003472
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003473 hFind = FindFirstFileW(wn, &findDataW);
3474 vim_free(wn);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003475 if (hFind != INVALID_HANDLE_VALUE)
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003476 {
3477 fileFlags = findDataW.dwFileAttributes;
3478 reparseTag = findDataW.dwReserved0;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003479 FindClose(hFind);
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003480 }
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003481
3482 if ((fileFlags & FILE_ATTRIBUTE_REPARSE_POINT)
Bram Moolenaar203258c2016-01-17 22:15:16 +01003483 && (reparseTag == IO_REPARSE_TAG_SYMLINK
3484 || reparseTag == IO_REPARSE_TAG_MOUNT_POINT))
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003485 res = TRUE;
3486
3487 return res;
3488}
3489
3490/*
3491 * Return TRUE if file "fname" has more than one link or if it is a symbolic
3492 * link.
3493 */
3494 int
3495mch_is_linked(char_u *fname)
3496{
3497 if (mch_is_hard_link(fname) || mch_is_symbolic_link(fname))
3498 return TRUE;
3499 return FALSE;
3500}
3501
3502/*
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003503 * Get the by-handle-file-information for "fname".
3504 * Returns FILEINFO_OK when OK.
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003505 * Returns FILEINFO_ENC_FAIL when enc_to_utf16() failed.
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003506 * Returns FILEINFO_READ_FAIL when CreateFile() failed.
3507 * Returns FILEINFO_INFO_FAIL when GetFileInformationByHandle() failed.
3508 */
3509 int
3510win32_fileinfo(char_u *fname, BY_HANDLE_FILE_INFORMATION *info)
3511{
Bram Moolenaar03f48552006-02-28 23:52:23 +00003512 HANDLE hFile;
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003513 int res = FILEINFO_READ_FAIL;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003514 WCHAR *wn;
Bram Moolenaar03f48552006-02-28 23:52:23 +00003515
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003516 wn = enc_to_utf16(fname, NULL);
3517 if (wn == NULL)
3518 return FILEINFO_ENC_FAIL;
3519
3520 hFile = CreateFileW(wn, // file name
3521 GENERIC_READ, // access mode
3522 FILE_SHARE_READ | FILE_SHARE_WRITE, // share mode
3523 NULL, // security descriptor
3524 OPEN_EXISTING, // creation disposition
3525 FILE_FLAG_BACKUP_SEMANTICS, // file attributes
3526 NULL); // handle to template file
3527 vim_free(wn);
Bram Moolenaar03f48552006-02-28 23:52:23 +00003528
3529 if (hFile != INVALID_HANDLE_VALUE)
3530 {
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003531 if (GetFileInformationByHandle(hFile, info) != 0)
3532 res = FILEINFO_OK;
3533 else
3534 res = FILEINFO_INFO_FAIL;
Bram Moolenaar03f48552006-02-28 23:52:23 +00003535 CloseHandle(hFile);
3536 }
3537
Bram Moolenaar03f48552006-02-28 23:52:23 +00003538 return res;
3539}
3540
3541/*
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003542 * get file attributes for `name'
3543 * -1 : error
3544 * else FILE_ATTRIBUTE_* defined in winnt.h
3545 */
Bram Moolenaarffa22202013-11-21 12:34:11 +01003546 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003547win32_getattrs(char_u *name)
3548{
3549 int attr;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003550 WCHAR *p;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003551
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003552 p = enc_to_utf16(name, NULL);
3553 if (p == NULL)
3554 return INVALID_FILE_ATTRIBUTES;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003555
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003556 attr = GetFileAttributesW(p);
3557 vim_free(p);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003558
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003559 return attr;
3560}
3561
3562/*
3563 * set file attributes for `name' to `attrs'
3564 *
3565 * return -1 for failure, 0 otherwise
3566 */
Bram Moolenaar6dff58f2018-09-30 21:43:26 +02003567 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003568win32_setattrs(char_u *name, int attrs)
3569{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003570 int res;
3571 WCHAR *p;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003572
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003573 p = enc_to_utf16(name, NULL);
3574 if (p == NULL)
3575 return -1;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003576
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003577 res = SetFileAttributesW(p, attrs);
3578 vim_free(p);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003579
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003580 return res ? 0 : -1;
3581}
3582
3583/*
3584 * Set archive flag for "name".
3585 */
Bram Moolenaar6dff58f2018-09-30 21:43:26 +02003586 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003587win32_set_archive(char_u *name)
3588{
3589 int attrs = win32_getattrs(name);
3590 if (attrs == -1)
3591 return -1;
3592
3593 attrs |= FILE_ATTRIBUTE_ARCHIVE;
3594 return win32_setattrs(name, attrs);
3595}
3596
3597/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003598 * Return TRUE if file or directory "name" is writable (not readonly).
3599 * Strange semantics of Win32: a readonly directory is writable, but you can't
3600 * delete a file. Let's say this means it is writable.
3601 */
3602 int
3603mch_writable(char_u *name)
3604{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003605 int attrs = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003606
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003607 return (attrs != -1 && (!(attrs & FILE_ATTRIBUTE_READONLY)
3608 || (attrs & FILE_ATTRIBUTE_DIRECTORY)));
Bram Moolenaar071d4272004-06-13 20:20:40 +00003609}
3610
Bram Moolenaar071d4272004-06-13 20:20:40 +00003611/*
Bram Moolenaar43663192017-03-05 14:29:12 +01003612 * Return TRUE if "name" can be executed, FALSE if not.
Bram Moolenaar77b77102015-03-21 22:18:41 +01003613 * If "use_path" is FALSE only check if "name" is executable.
Bram Moolenaar43663192017-03-05 14:29:12 +01003614 * When returning TRUE and "path" is not NULL save the path and set "*path" to
3615 * the allocated memory.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003616 */
3617 int
Yegappan Lakshmananebb01bd2022-06-08 15:14:09 +01003618mch_can_exe(char_u *name, char_u **path, int use_path UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003619{
Bram Moolenaar95da1362020-05-30 18:37:55 +02003620 return executable_exists((char *)name, path, TRUE, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003621}
Bram Moolenaar071d4272004-06-13 20:20:40 +00003622
3623/*
3624 * Check what "name" is:
3625 * NODE_NORMAL: file or directory (or doesn't exist)
3626 * NODE_WRITABLE: writable device, socket, fifo, etc.
3627 * NODE_OTHER: non-writable things
3628 */
3629 int
3630mch_nodetype(char_u *name)
3631{
3632 HANDLE hFile;
3633 int type;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003634 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003635
Bram Moolenaar0f873732019-12-05 20:28:46 +01003636 // We can't open a file with a name "\\.\con" or "\\.\prn" and trying to
3637 // read from it later will cause Vim to hang. Thus return NODE_WRITABLE
3638 // here.
Bram Moolenaar043545e2006-10-10 16:44:07 +00003639 if (STRNCMP(name, "\\\\.\\", 4) == 0)
3640 return NODE_WRITABLE;
3641
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003642 wn = enc_to_utf16(name, NULL);
3643 if (wn == NULL)
3644 return NODE_NORMAL;
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003645
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003646 hFile = CreateFileW(wn, // file name
3647 GENERIC_WRITE, // access mode
3648 0, // share mode
3649 NULL, // security descriptor
3650 OPEN_EXISTING, // creation disposition
3651 0, // file attributes
3652 NULL); // handle to template file
3653 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003654 if (hFile == INVALID_HANDLE_VALUE)
3655 return NODE_NORMAL;
3656
3657 type = GetFileType(hFile);
3658 CloseHandle(hFile);
3659 if (type == FILE_TYPE_CHAR)
3660 return NODE_WRITABLE;
3661 if (type == FILE_TYPE_DISK)
3662 return NODE_NORMAL;
3663 return NODE_OTHER;
3664}
3665
3666#ifdef HAVE_ACL
3667struct my_acl
3668{
3669 PSECURITY_DESCRIPTOR pSecurityDescriptor;
3670 PSID pSidOwner;
3671 PSID pSidGroup;
3672 PACL pDacl;
3673 PACL pSacl;
3674};
3675#endif
3676
3677/*
3678 * Return a pointer to the ACL of file "fname" in allocated memory.
3679 * Return NULL if the ACL is not available for whatever reason.
3680 */
3681 vim_acl_T
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003682mch_get_acl(char_u *fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003683{
3684#ifndef HAVE_ACL
3685 return (vim_acl_T)NULL;
3686#else
3687 struct my_acl *p = NULL;
Bram Moolenaar27515922013-06-29 15:36:26 +02003688 DWORD err;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003689
Bram Moolenaarc799fe22019-05-28 23:08:19 +02003690 p = ALLOC_CLEAR_ONE(struct my_acl);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003691 if (p != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003692 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003693 WCHAR *wn;
Bram Moolenaar27515922013-06-29 15:36:26 +02003694
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003695 wn = enc_to_utf16(fname, NULL);
3696 if (wn == NULL)
Bram Moolenaarbbf9f342020-11-10 22:03:40 +01003697 {
3698 vim_free(p);
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003699 return NULL;
Bram Moolenaarbbf9f342020-11-10 22:03:40 +01003700 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003701
3702 // Try to retrieve the entire security descriptor.
3703 err = GetNamedSecurityInfoW(
3704 wn, // Abstract filename
3705 SE_FILE_OBJECT, // File Object
3706 OWNER_SECURITY_INFORMATION |
3707 GROUP_SECURITY_INFORMATION |
3708 DACL_SECURITY_INFORMATION |
3709 SACL_SECURITY_INFORMATION,
3710 &p->pSidOwner, // Ownership information.
3711 &p->pSidGroup, // Group membership.
3712 &p->pDacl, // Discretionary information.
3713 &p->pSacl, // For auditing purposes.
3714 &p->pSecurityDescriptor);
3715 if (err == ERROR_ACCESS_DENIED ||
3716 err == ERROR_PRIVILEGE_NOT_HELD)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003717 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003718 // Retrieve only DACL.
3719 (void)GetNamedSecurityInfoW(
3720 wn,
3721 SE_FILE_OBJECT,
3722 DACL_SECURITY_INFORMATION,
3723 NULL,
3724 NULL,
3725 &p->pDacl,
3726 NULL,
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003727 &p->pSecurityDescriptor);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003728 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003729 if (p->pSecurityDescriptor == NULL)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003730 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003731 mch_free_acl((vim_acl_T)p);
3732 p = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003733 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003734 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003735 }
3736
3737 return (vim_acl_T)p;
3738#endif
3739}
3740
Bram Moolenaar27515922013-06-29 15:36:26 +02003741#ifdef HAVE_ACL
3742/*
3743 * Check if "acl" contains inherited ACE.
3744 */
3745 static BOOL
3746is_acl_inherited(PACL acl)
3747{
3748 DWORD i;
3749 ACL_SIZE_INFORMATION acl_info;
3750 PACCESS_ALLOWED_ACE ace;
3751
3752 acl_info.AceCount = 0;
3753 GetAclInformation(acl, &acl_info, sizeof(acl_info), AclSizeInformation);
3754 for (i = 0; i < acl_info.AceCount; i++)
3755 {
3756 GetAce(acl, i, (LPVOID *)&ace);
3757 if (ace->Header.AceFlags & INHERITED_ACE)
3758 return TRUE;
3759 }
3760 return FALSE;
3761}
3762#endif
3763
Bram Moolenaar071d4272004-06-13 20:20:40 +00003764/*
3765 * Set the ACL of file "fname" to "acl" (unless it's NULL).
3766 * Errors are ignored.
3767 * This must only be called with "acl" equal to what mch_get_acl() returned.
3768 */
3769 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003770mch_set_acl(char_u *fname, vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003771{
3772#ifdef HAVE_ACL
3773 struct my_acl *p = (struct my_acl *)acl;
Bram Moolenaar27515922013-06-29 15:36:26 +02003774 SECURITY_INFORMATION sec_info = 0;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003775 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003776
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003777 if (p == NULL)
3778 return;
3779
3780 wn = enc_to_utf16(fname, NULL);
3781 if (wn == NULL)
3782 return;
3783
3784 // Set security flags
3785 if (p->pSidOwner)
3786 sec_info |= OWNER_SECURITY_INFORMATION;
3787 if (p->pSidGroup)
3788 sec_info |= GROUP_SECURITY_INFORMATION;
3789 if (p->pDacl)
Bram Moolenaar27515922013-06-29 15:36:26 +02003790 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003791 sec_info |= DACL_SECURITY_INFORMATION;
3792 // Do not inherit its parent's DACL.
3793 // If the DACL is inherited, Cygwin permissions would be changed.
3794 if (!is_acl_inherited(p->pDacl))
3795 sec_info |= PROTECTED_DACL_SECURITY_INFORMATION;
Bram Moolenaar27515922013-06-29 15:36:26 +02003796 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003797 if (p->pSacl)
3798 sec_info |= SACL_SECURITY_INFORMATION;
3799
3800 (void)SetNamedSecurityInfoW(
3801 wn, // Abstract filename
3802 SE_FILE_OBJECT, // File Object
3803 sec_info,
3804 p->pSidOwner, // Ownership information.
3805 p->pSidGroup, // Group membership.
3806 p->pDacl, // Discretionary information.
3807 p->pSacl // For auditing purposes.
3808 );
3809 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003810#endif
3811}
3812
3813 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003814mch_free_acl(vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003815{
3816#ifdef HAVE_ACL
3817 struct my_acl *p = (struct my_acl *)acl;
3818
3819 if (p != NULL)
3820 {
3821 LocalFree(p->pSecurityDescriptor); // Free the memory just in case
3822 vim_free(p);
3823 }
3824#endif
3825}
3826
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003827#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003828
3829/*
3830 * handler for ctrl-break, ctrl-c interrupts, and fatal events.
3831 */
3832 static BOOL WINAPI
3833handler_routine(
3834 DWORD dwCtrlType)
3835{
Bram Moolenaar589b1102017-08-12 16:39:05 +02003836 INPUT_RECORD ir;
3837 DWORD out;
3838
Bram Moolenaar071d4272004-06-13 20:20:40 +00003839 switch (dwCtrlType)
3840 {
3841 case CTRL_C_EVENT:
3842 if (ctrl_c_interrupts)
3843 g_fCtrlCPressed = TRUE;
3844 return TRUE;
3845
3846 case CTRL_BREAK_EVENT:
3847 g_fCBrkPressed = TRUE;
Bram Moolenaar589b1102017-08-12 16:39:05 +02003848 ctrl_break_was_pressed = TRUE;
Bram Moolenaar0f873732019-12-05 20:28:46 +01003849 // ReadConsoleInput is blocking, send a key event to continue.
Bram Moolenaar589b1102017-08-12 16:39:05 +02003850 ir.EventType = KEY_EVENT;
3851 ir.Event.KeyEvent.bKeyDown = TRUE;
3852 ir.Event.KeyEvent.wRepeatCount = 1;
3853 ir.Event.KeyEvent.wVirtualKeyCode = VK_CANCEL;
3854 ir.Event.KeyEvent.wVirtualScanCode = 0;
3855 ir.Event.KeyEvent.dwControlKeyState = 0;
3856 ir.Event.KeyEvent.uChar.UnicodeChar = 0;
3857 WriteConsoleInput(g_hConIn, &ir, 1, &out);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003858 return TRUE;
3859
Bram Moolenaar0f873732019-12-05 20:28:46 +01003860 // fatal events: shut down gracefully
Bram Moolenaar071d4272004-06-13 20:20:40 +00003861 case CTRL_CLOSE_EVENT:
3862 case CTRL_LOGOFF_EVENT:
3863 case CTRL_SHUTDOWN_EVENT:
3864 windgoto((int)Rows - 1, 0);
3865 g_fForceExit = TRUE;
3866
Bram Moolenaar0fde2902008-03-16 13:54:13 +00003867 vim_snprintf((char *)IObuff, IOSIZE, _("Vim: Caught %s event\n"),
Bram Moolenaar071d4272004-06-13 20:20:40 +00003868 (dwCtrlType == CTRL_CLOSE_EVENT
3869 ? _("close")
3870 : dwCtrlType == CTRL_LOGOFF_EVENT
3871 ? _("logoff")
3872 : _("shutdown")));
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003873# ifdef DEBUG
Bram Moolenaar071d4272004-06-13 20:20:40 +00003874 OutputDebugString(IObuff);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003875# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003876
Bram Moolenaar0f873732019-12-05 20:28:46 +01003877 preserve_exit(); // output IObuff, preserve files and exit
Bram Moolenaar071d4272004-06-13 20:20:40 +00003878
Bram Moolenaar0f873732019-12-05 20:28:46 +01003879 return TRUE; // not reached
Bram Moolenaar071d4272004-06-13 20:20:40 +00003880
3881 default:
3882 return FALSE;
3883 }
3884}
3885
3886
3887/*
3888 * set the tty in (raw) ? "raw" : "cooked" mode
3889 */
3890 void
Bram Moolenaar26e86442020-05-17 14:06:16 +02003891mch_settmode(tmode_T tmode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003892{
3893 DWORD cmodein;
3894 DWORD cmodeout;
3895 BOOL bEnableHandler;
3896
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003897# ifdef VIMDLL
3898 if (gui.in_use)
3899 return;
3900# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003901 GetConsoleMode(g_hConIn, &cmodein);
3902 GetConsoleMode(g_hConOut, &cmodeout);
3903 if (tmode == TMODE_RAW)
3904 {
3905 cmodein &= ~(ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
3906 ENABLE_ECHO_INPUT);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003907 if (g_fMouseActive)
Wez Furlong6ef5ab52021-05-30 19:29:41 +02003908 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00003909 cmodein |= ENABLE_MOUSE_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02003910 cmodein &= ~ENABLE_QUICK_EDIT_MODE;
3911 }
3912 else
3913 {
3914 cmodein |= g_cmodein & ENABLE_QUICK_EDIT_MODE;
3915 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01003916 cmodeout &= ~(
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003917# ifdef FEAT_TERMGUICOLORS
Bram Moolenaar0f873732019-12-05 20:28:46 +01003918 // Do not turn off the ENABLE_PROCESSED_OUTPUT flag when using
3919 // VTP.
Bram Moolenaarcafafb32018-02-22 21:07:09 +01003920 ((vtp_working) ? 0 : ENABLE_PROCESSED_OUTPUT) |
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003921# else
Bram Moolenaarcafafb32018-02-22 21:07:09 +01003922 ENABLE_PROCESSED_OUTPUT |
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003923# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01003924 ENABLE_WRAP_AT_EOL_OUTPUT);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003925 bEnableHandler = TRUE;
3926 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01003927 else // cooked
Bram Moolenaar071d4272004-06-13 20:20:40 +00003928 {
3929 cmodein |= (ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
3930 ENABLE_ECHO_INPUT);
3931 cmodeout |= (ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
3932 bEnableHandler = FALSE;
3933 }
Wez Furlong6ef5ab52021-05-30 19:29:41 +02003934 SetConsoleMode(g_hConIn, cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003935 SetConsoleMode(g_hConOut, cmodeout);
3936 SetConsoleCtrlHandler(handler_routine, bEnableHandler);
3937
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003938# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00003939 if (fdDump)
3940 {
3941 fprintf(fdDump, "mch_settmode(%s, in = %x, out = %x)\n",
3942 tmode == TMODE_RAW ? "raw" :
3943 tmode == TMODE_COOK ? "cooked" : "normal",
3944 cmodein, cmodeout);
3945 fflush(fdDump);
3946 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003947# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003948}
3949
3950
3951/*
3952 * Get the size of the current window in `Rows' and `Columns'
3953 * Return OK when size could be determined, FAIL otherwise.
3954 */
3955 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003956mch_get_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003957{
3958 CONSOLE_SCREEN_BUFFER_INFO csbi;
3959
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003960# ifdef VIMDLL
3961 if (gui.in_use)
3962 return OK;
3963# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003964 if (!g_fTermcapMode && g_cbTermcap.IsValid)
3965 {
3966 /*
3967 * For some reason, we are trying to get the screen dimensions
3968 * even though we are not in termcap mode. The 'Rows' and 'Columns'
3969 * variables are really intended to mean the size of Vim screen
3970 * while in termcap mode.
3971 */
3972 Rows = g_cbTermcap.Info.dwSize.Y;
3973 Columns = g_cbTermcap.Info.dwSize.X;
3974 }
3975 else if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3976 {
3977 Rows = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
3978 Columns = csbi.srWindow.Right - csbi.srWindow.Left + 1;
3979 }
3980 else
3981 {
3982 Rows = 25;
3983 Columns = 80;
3984 }
3985 return OK;
3986}
3987
3988/*
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02003989 * Resize console buffer to 'COORD'
3990 */
3991 static void
3992ResizeConBuf(
3993 HANDLE hConsole,
3994 COORD coordScreen)
3995{
3996 if (!SetConsoleScreenBufferSize(hConsole, coordScreen))
3997 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003998# ifdef MCH_WRITE_DUMP
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02003999 if (fdDump)
4000 {
4001 fprintf(fdDump, "SetConsoleScreenBufferSize failed: %lx\n",
4002 GetLastError());
4003 fflush(fdDump);
4004 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004005# endif
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004006 }
4007}
4008
4009/*
4010 * Resize console window size to 'srWindowRect'
4011 */
4012 static void
4013ResizeWindow(
4014 HANDLE hConsole,
4015 SMALL_RECT srWindowRect)
4016{
4017 if (!SetConsoleWindowInfo(hConsole, TRUE, &srWindowRect))
4018 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004019# ifdef MCH_WRITE_DUMP
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004020 if (fdDump)
4021 {
4022 fprintf(fdDump, "SetConsoleWindowInfo failed: %lx\n",
4023 GetLastError());
4024 fflush(fdDump);
4025 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004026# endif
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004027 }
4028}
4029
4030/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00004031 * Set a console window to `xSize' * `ySize'
4032 */
4033 static void
4034ResizeConBufAndWindow(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004035 HANDLE hConsole,
4036 int xSize,
4037 int ySize)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004038{
Bram Moolenaar0f873732019-12-05 20:28:46 +01004039 CONSOLE_SCREEN_BUFFER_INFO csbi; // hold current console buffer info
4040 SMALL_RECT srWindowRect; // hold the new console size
Bram Moolenaar071d4272004-06-13 20:20:40 +00004041 COORD coordScreen;
Bram Moolenaarf49a6922019-07-15 20:37:05 +02004042 COORD cursor;
Bram Moolenaar2551c032018-08-23 22:38:31 +02004043 static int resized = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004044
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004045# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00004046 if (fdDump)
4047 {
4048 fprintf(fdDump, "ResizeConBufAndWindow(%d, %d)\n", xSize, ySize);
4049 fflush(fdDump);
4050 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004051# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004052
Bram Moolenaar0f873732019-12-05 20:28:46 +01004053 // get the largest size we can size the console window to
Bram Moolenaar071d4272004-06-13 20:20:40 +00004054 coordScreen = GetLargestConsoleWindowSize(hConsole);
4055
Bram Moolenaar0f873732019-12-05 20:28:46 +01004056 // define the new console window size and scroll position
Bram Moolenaar071d4272004-06-13 20:20:40 +00004057 srWindowRect.Left = srWindowRect.Top = (SHORT) 0;
4058 srWindowRect.Right = (SHORT) (min(xSize, coordScreen.X) - 1);
4059 srWindowRect.Bottom = (SHORT) (min(ySize, coordScreen.Y) - 1);
4060
4061 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
4062 {
4063 int sx, sy;
4064
4065 sx = csbi.srWindow.Right - csbi.srWindow.Left + 1;
4066 sy = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
4067 if (sy < ySize || sx < xSize)
4068 {
4069 /*
4070 * Increasing number of lines/columns, do buffer first.
4071 * Use the maximal size in x and y direction.
4072 */
4073 if (sy < ySize)
4074 coordScreen.Y = ySize;
4075 else
4076 coordScreen.Y = sy;
4077 if (sx < xSize)
4078 coordScreen.X = xSize;
4079 else
4080 coordScreen.X = sx;
4081 SetConsoleScreenBufferSize(hConsole, coordScreen);
4082 }
4083 }
4084
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004085 // define the new console buffer size
Bram Moolenaar071d4272004-06-13 20:20:40 +00004086 coordScreen.X = xSize;
4087 coordScreen.Y = ySize;
4088
Bram Moolenaar2551c032018-08-23 22:38:31 +02004089 // In the new console call API, only the first time in reverse order
4090 if (!vtp_working || resized)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004091 {
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004092 ResizeWindow(hConsole, srWindowRect);
4093 ResizeConBuf(hConsole, coordScreen);
4094 }
4095 else
4096 {
Bram Moolenaarf49a6922019-07-15 20:37:05 +02004097 // Workaround for a Windows 10 bug
4098 cursor.X = srWindowRect.Left;
4099 cursor.Y = srWindowRect.Top;
4100 SetConsoleCursorPosition(hConsole, cursor);
4101
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004102 ResizeConBuf(hConsole, coordScreen);
4103 ResizeWindow(hConsole, srWindowRect);
Bram Moolenaar2551c032018-08-23 22:38:31 +02004104 resized = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004105 }
4106}
4107
4108
4109/*
4110 * Set the console window to `Rows' * `Columns'
4111 */
4112 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004113mch_set_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004114{
4115 COORD coordScreen;
4116
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004117# ifdef VIMDLL
4118 if (gui.in_use)
4119 return;
4120# endif
Bram Moolenaar0f873732019-12-05 20:28:46 +01004121 // Don't change window size while still starting up
Bram Moolenaar071d4272004-06-13 20:20:40 +00004122 if (suppress_winsize != 0)
4123 {
4124 suppress_winsize = 2;
4125 return;
4126 }
4127
4128 if (term_console)
4129 {
4130 coordScreen = GetLargestConsoleWindowSize(g_hConOut);
4131
Bram Moolenaar0f873732019-12-05 20:28:46 +01004132 // Clamp Rows and Columns to reasonable values
Bram Moolenaar071d4272004-06-13 20:20:40 +00004133 if (Rows > coordScreen.Y)
4134 Rows = coordScreen.Y;
4135 if (Columns > coordScreen.X)
4136 Columns = coordScreen.X;
4137
4138 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
4139 }
4140}
4141
4142/*
4143 * Rows and/or Columns has changed.
4144 */
4145 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004146mch_new_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004147{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004148# ifdef VIMDLL
4149 if (gui.in_use)
4150 return;
4151# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004152 set_scroll_region(0, 0, Columns - 1, Rows - 1);
4153}
4154
4155
4156/*
4157 * Called when started up, to set the winsize that was delayed.
4158 */
4159 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004160mch_set_winsize_now(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004161{
4162 if (suppress_winsize == 2)
4163 {
4164 suppress_winsize = 0;
4165 mch_set_shellsize();
4166 shell_resized();
4167 }
4168 suppress_winsize = 0;
4169}
Bram Moolenaar0f873732019-12-05 20:28:46 +01004170#endif // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00004171
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004172 static BOOL
4173vim_create_process(
Bram Moolenaar36c85b22013-12-12 20:25:44 +01004174 char *cmd,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004175 BOOL inherit_handles,
Bram Moolenaar3f1138e2014-01-05 13:29:26 +01004176 DWORD flags,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004177 STARTUPINFO *si,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004178 PROCESS_INFORMATION *pi,
4179 LPVOID *env,
4180 char *cwd)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004181{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004182 BOOL ret = FALSE;
4183 WCHAR *wcmd, *wcwd = NULL;
4184
4185 wcmd = enc_to_utf16((char_u *)cmd, NULL);
4186 if (wcmd == NULL)
4187 return FALSE;
4188 if (cwd != NULL)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004189 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004190 wcwd = enc_to_utf16((char_u *)cwd, NULL);
4191 if (wcwd == NULL)
4192 goto theend;
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004193 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004194
4195 ret = CreateProcessW(
4196 NULL, // Executable name
4197 wcmd, // Command to execute
4198 NULL, // Process security attributes
4199 NULL, // Thread security attributes
4200 inherit_handles, // Inherit handles
4201 flags, // Creation flags
4202 env, // Environment
4203 wcwd, // Current directory
4204 (LPSTARTUPINFOW)si, // Startup information
4205 pi); // Process information
4206theend:
4207 vim_free(wcmd);
4208 vim_free(wcwd);
4209 return ret;
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004210}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004211
4212
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004213 static HINSTANCE
4214vim_shell_execute(
4215 char *cmd,
4216 INT n_show_cmd)
4217{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004218 HINSTANCE ret;
4219 WCHAR *wcmd;
4220
4221 wcmd = enc_to_utf16((char_u *)cmd, NULL);
4222 if (wcmd == NULL)
4223 return (HINSTANCE) 0;
4224
4225 ret = ShellExecuteW(NULL, NULL, wcmd, NULL, NULL, n_show_cmd);
4226 vim_free(wcmd);
4227 return ret;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004228}
4229
4230
Bram Moolenaar4f974752019-02-17 17:44:42 +01004231#if defined(FEAT_GUI_MSWIN) || defined(PROTO)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004232
4233/*
4234 * Specialised version of system() for Win32 GUI mode.
4235 * This version proceeds as follows:
4236 * 1. Create a console window for use by the subprocess
4237 * 2. Run the subprocess (it gets the allocated console by default)
4238 * 3. Wait for the subprocess to terminate and get its exit code
4239 * 4. Prompt the user to press a key to close the console window
4240 */
4241 static int
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004242mch_system_classic(char *cmd, int options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004243{
4244 STARTUPINFO si;
4245 PROCESS_INFORMATION pi;
4246 DWORD ret = 0;
4247 HWND hwnd = GetFocus();
4248
4249 si.cb = sizeof(si);
4250 si.lpReserved = NULL;
4251 si.lpDesktop = NULL;
4252 si.lpTitle = NULL;
4253 si.dwFlags = STARTF_USESHOWWINDOW;
4254 /*
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004255 * It's nicer to run a filter command in a minimized window.
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01004256 * Don't activate the window to keep focus on Vim.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004257 */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004258 if (options & SHELL_DOOUT)
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01004259 si.wShowWindow = SW_SHOWMINNOACTIVE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004260 else
4261 si.wShowWindow = SW_SHOWNORMAL;
4262 si.cbReserved2 = 0;
4263 si.lpReserved2 = NULL;
4264
Bram Moolenaar0f873732019-12-05 20:28:46 +01004265 // Now, run the command
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004266 vim_create_process(cmd, FALSE,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004267 CREATE_DEFAULT_ERROR_MODE | CREATE_NEW_CONSOLE,
4268 &si, &pi, NULL, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004269
Bram Moolenaar0f873732019-12-05 20:28:46 +01004270 // Wait for the command to terminate before continuing
Bram Moolenaar071d4272004-06-13 20:20:40 +00004271 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004272# ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00004273 int delay = 1;
4274
Bram Moolenaar0f873732019-12-05 20:28:46 +01004275 // Keep updating the window while waiting for the shell to finish.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004276 for (;;)
4277 {
4278 MSG msg;
4279
K.Takatab7057bd2022-01-21 11:37:07 +00004280 if (PeekMessageW(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004281 {
4282 TranslateMessage(&msg);
K.Takatab7057bd2022-01-21 11:37:07 +00004283 DispatchMessageW(&msg);
Bram Moolenaare4195c52012-08-02 12:31:44 +02004284 delay = 1;
4285 continue;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004286 }
4287 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
4288 break;
4289
Bram Moolenaar0f873732019-12-05 20:28:46 +01004290 // We start waiting for a very short time and then increase it, so
4291 // that we respond quickly when the process is quick, and don't
4292 // consume too much overhead when it's slow.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004293 if (delay < 50)
4294 delay += 10;
4295 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004296# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004297 WaitForSingleObject(pi.hProcess, INFINITE);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004298# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004299
Bram Moolenaar0f873732019-12-05 20:28:46 +01004300 // Get the command exit code
Bram Moolenaar071d4272004-06-13 20:20:40 +00004301 GetExitCodeProcess(pi.hProcess, &ret);
4302 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004303
Bram Moolenaar0f873732019-12-05 20:28:46 +01004304 // Close the handles to the subprocess, so that it goes away
Bram Moolenaar071d4272004-06-13 20:20:40 +00004305 CloseHandle(pi.hThread);
4306 CloseHandle(pi.hProcess);
4307
Bram Moolenaar0f873732019-12-05 20:28:46 +01004308 // Try to get input focus back. Doesn't always work though.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004309 PostMessage(hwnd, WM_SETFOCUS, 0, 0);
4310
4311 return ret;
4312}
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004313
4314/*
4315 * Thread launched by the gui to send the current buffer data to the
4316 * process. This way avoid to hang up vim totally if the children
4317 * process take a long time to process the lines.
4318 */
Bram Moolenaar4c38d662016-08-03 20:54:57 +02004319 static unsigned int __stdcall
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004320sub_process_writer(LPVOID param)
4321{
4322 HANDLE g_hChildStd_IN_Wr = param;
4323 linenr_T lnum = curbuf->b_op_start.lnum;
4324 DWORD len = 0;
4325 DWORD l;
4326 char_u *lp = ml_get(lnum);
4327 char_u *s;
4328 int written = 0;
4329
4330 for (;;)
4331 {
4332 l = (DWORD)STRLEN(lp + written);
4333 if (l == 0)
4334 len = 0;
4335 else if (lp[written] == NL)
4336 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004337 // NL -> NUL translation
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004338 WriteFile(g_hChildStd_IN_Wr, "", 1, &len, NULL);
4339 }
4340 else
4341 {
4342 s = vim_strchr(lp + written, NL);
4343 WriteFile(g_hChildStd_IN_Wr, (char *)lp + written,
4344 s == NULL ? l : (DWORD)(s - (lp + written)),
4345 &len, NULL);
4346 }
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +01004347 if (len == l)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004348 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004349 // Finished a line, add a NL, unless this line should not have
4350 // one.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004351 if (lnum != curbuf->b_op_end.lnum
Bram Moolenaar34d72d42015-07-17 14:18:08 +02004352 || (!curbuf->b_p_bin
4353 && curbuf->b_p_fixeol)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004354 || (lnum != curbuf->b_no_eol_lnum
4355 && (lnum != curbuf->b_ml.ml_line_count
4356 || curbuf->b_p_eol)))
4357 {
Bram Moolenaar42335f52018-09-13 15:33:43 +02004358 WriteFile(g_hChildStd_IN_Wr, "\n", 1,
4359 (LPDWORD)&vim_ignored, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004360 }
4361
4362 ++lnum;
4363 if (lnum > curbuf->b_op_end.lnum)
4364 break;
4365
4366 lp = ml_get(lnum);
4367 written = 0;
4368 }
4369 else if (len > 0)
4370 written += len;
4371 }
4372
Bram Moolenaar0f873732019-12-05 20:28:46 +01004373 // finished all the lines, close pipe
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004374 CloseHandle(g_hChildStd_IN_Wr);
Bram Moolenaar86f2cd52016-08-02 21:55:17 +02004375 return 0;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004376}
4377
4378
Bram Moolenaar0f873732019-12-05 20:28:46 +01004379# define BUFLEN 100 // length for buffer, stolen from unix version
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004380
4381/*
4382 * This function read from the children's stdout and write the
4383 * data on screen or in the buffer accordingly.
4384 */
4385 static void
4386dump_pipe(int options,
4387 HANDLE g_hChildStd_OUT_Rd,
4388 garray_T *ga,
4389 char_u buffer[],
4390 DWORD *buffer_off)
4391{
4392 DWORD availableBytes = 0;
4393 DWORD i;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004394 int ret;
4395 DWORD len;
4396 DWORD toRead;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004397
Bram Moolenaar0f873732019-12-05 20:28:46 +01004398 // we query the pipe to see if there is any data to read
4399 // to avoid to perform a blocking read
4400 ret = PeekNamedPipe(g_hChildStd_OUT_Rd, // pipe to query
4401 NULL, // optional buffer
4402 0, // buffer size
4403 NULL, // number of read bytes
4404 &availableBytes, // available bytes total
4405 NULL); // byteLeft
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004406
Bram Moolenaar0f873732019-12-05 20:28:46 +01004407 // We got real data in the pipe, read it
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02004408 while (ret != 0 && availableBytes > 0)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004409 {
Bram Moolenaara12a1612019-01-24 16:39:02 +01004410 toRead = (DWORD)(BUFLEN - *buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004411 toRead = availableBytes < toRead ? availableBytes : toRead;
Bram Moolenaara12a1612019-01-24 16:39:02 +01004412 ReadFile(g_hChildStd_OUT_Rd, buffer + *buffer_off, toRead , &len, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004413
Bram Moolenaar0f873732019-12-05 20:28:46 +01004414 // If we haven't read anything, there is a problem
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004415 if (len == 0)
4416 break;
4417
4418 availableBytes -= len;
4419
4420 if (options & SHELL_READ)
4421 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004422 // Do NUL -> NL translation, append NL separated
4423 // lines to the current buffer.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004424 for (i = 0; i < len; ++i)
4425 {
4426 if (buffer[i] == NL)
4427 append_ga_line(ga);
4428 else if (buffer[i] == NUL)
4429 ga_append(ga, NL);
4430 else
4431 ga_append(ga, buffer[i]);
4432 }
4433 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004434 else if (has_mbyte)
4435 {
4436 int l;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004437 int c;
4438 char_u *p;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004439
4440 len += *buffer_off;
4441 buffer[len] = NUL;
4442
Bram Moolenaar0f873732019-12-05 20:28:46 +01004443 // Check if the last character in buffer[] is
4444 // incomplete, keep these bytes for the next
4445 // round.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004446 for (p = buffer; p < buffer + len; p += l)
4447 {
Bram Moolenaard3c907b2016-08-17 21:32:09 +02004448 l = MB_CPTR2LEN(p);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004449 if (l == 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01004450 l = 1; // NUL byte?
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004451 else if (MB_BYTE2LEN(*p) != l)
4452 break;
4453 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01004454 if (p == buffer) // no complete character
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004455 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004456 // avoid getting stuck at an illegal byte
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004457 if (len >= 12)
4458 ++p;
4459 else
4460 {
4461 *buffer_off = len;
4462 return;
4463 }
4464 }
4465 c = *p;
4466 *p = NUL;
Bram Moolenaar32526b32019-01-19 17:43:09 +01004467 msg_puts((char *)buffer);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004468 if (p < buffer + len)
4469 {
4470 *p = c;
4471 *buffer_off = (DWORD)((buffer + len) - p);
4472 mch_memmove(buffer, p, *buffer_off);
4473 return;
4474 }
4475 *buffer_off = 0;
4476 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004477 else
4478 {
4479 buffer[len] = NUL;
Bram Moolenaar32526b32019-01-19 17:43:09 +01004480 msg_puts((char *)buffer);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004481 }
4482
4483 windgoto(msg_row, msg_col);
4484 cursor_on();
4485 out_flush();
4486 }
4487}
4488
4489/*
4490 * Version of system to use for windows NT > 5.0 (Win2K), use pipe
4491 * for communication and doesn't open any new window.
4492 */
4493 static int
4494mch_system_piped(char *cmd, int options)
4495{
4496 STARTUPINFO si;
4497 PROCESS_INFORMATION pi;
4498 DWORD ret = 0;
4499
4500 HANDLE g_hChildStd_IN_Rd = NULL;
4501 HANDLE g_hChildStd_IN_Wr = NULL;
4502 HANDLE g_hChildStd_OUT_Rd = NULL;
4503 HANDLE g_hChildStd_OUT_Wr = NULL;
4504
Bram Moolenaar0f873732019-12-05 20:28:46 +01004505 char_u buffer[BUFLEN + 1]; // reading buffer + size
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004506 DWORD len;
4507
Bram Moolenaar0f873732019-12-05 20:28:46 +01004508 // buffer used to receive keys
4509 char_u ta_buf[BUFLEN + 1]; // TypeAHead
4510 int ta_len = 0; // valid bytes in ta_buf[]
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004511
4512 DWORD i;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004513 int noread_cnt = 0;
4514 garray_T ga;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004515 int delay = 1;
Bram Moolenaar0f873732019-12-05 20:28:46 +01004516 DWORD buffer_off = 0; // valid bytes in buffer[]
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004517 char *p = NULL;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004518
4519 SECURITY_ATTRIBUTES saAttr;
4520
Bram Moolenaar0f873732019-12-05 20:28:46 +01004521 // Set the bInheritHandle flag so pipe handles are inherited.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004522 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
4523 saAttr.bInheritHandle = TRUE;
4524 saAttr.lpSecurityDescriptor = NULL;
4525
4526 if ( ! CreatePipe(&g_hChildStd_OUT_Rd, &g_hChildStd_OUT_Wr, &saAttr, 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01004527 // Ensure the read handle to the pipe for STDOUT is not inherited.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004528 || ! SetHandleInformation(g_hChildStd_OUT_Rd, HANDLE_FLAG_INHERIT, 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01004529 // Create a pipe for the child process's STDIN.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004530 || ! CreatePipe(&g_hChildStd_IN_Rd, &g_hChildStd_IN_Wr, &saAttr, 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01004531 // Ensure the write handle to the pipe for STDIN is not inherited.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004532 || ! SetHandleInformation(g_hChildStd_IN_Wr, HANDLE_FLAG_INHERIT, 0) )
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004533 {
4534 CloseHandle(g_hChildStd_IN_Rd);
4535 CloseHandle(g_hChildStd_IN_Wr);
4536 CloseHandle(g_hChildStd_OUT_Rd);
4537 CloseHandle(g_hChildStd_OUT_Wr);
Bram Moolenaar32526b32019-01-19 17:43:09 +01004538 msg_puts(_("\nCannot create pipes\n"));
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004539 }
4540
4541 si.cb = sizeof(si);
4542 si.lpReserved = NULL;
4543 si.lpDesktop = NULL;
4544 si.lpTitle = NULL;
4545 si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
4546
Bram Moolenaar0f873732019-12-05 20:28:46 +01004547 // set-up our file redirection
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004548 si.hStdError = g_hChildStd_OUT_Wr;
4549 si.hStdOutput = g_hChildStd_OUT_Wr;
4550 si.hStdInput = g_hChildStd_IN_Rd;
4551 si.wShowWindow = SW_HIDE;
4552 si.cbReserved2 = 0;
4553 si.lpReserved2 = NULL;
4554
4555 if (options & SHELL_READ)
4556 ga_init2(&ga, 1, BUFLEN);
4557
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004558 if (cmd != NULL)
4559 {
4560 p = (char *)vim_strsave((char_u *)cmd);
4561 if (p != NULL)
4562 unescape_shellxquote((char_u *)p, p_sxe);
4563 else
4564 p = cmd;
4565 }
4566
Bram Moolenaar0f873732019-12-05 20:28:46 +01004567 // Now, run the command.
4568 // About "Inherit handles" being TRUE: this command can be litigious,
4569 // handle inheritance was deactivated for pending temp file, but, if we
4570 // deactivate it, the pipes don't work for some reason.
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004571 vim_create_process(p, TRUE, CREATE_DEFAULT_ERROR_MODE,
4572 &si, &pi, NULL, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004573
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004574 if (p != cmd)
4575 vim_free(p);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004576
Bram Moolenaar0f873732019-12-05 20:28:46 +01004577 // Close our unused side of the pipes
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004578 CloseHandle(g_hChildStd_IN_Rd);
4579 CloseHandle(g_hChildStd_OUT_Wr);
4580
4581 if (options & SHELL_WRITE)
4582 {
Bram Moolenaar86f2cd52016-08-02 21:55:17 +02004583 HANDLE thread = (HANDLE)
Bram Moolenaar0f873732019-12-05 20:28:46 +01004584 _beginthreadex(NULL, // security attributes
4585 0, // default stack size
4586 sub_process_writer, // function to be executed
4587 g_hChildStd_IN_Wr, // parameter
4588 0, // creation flag, start immediately
4589 NULL); // we don't care about thread id
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004590 CloseHandle(thread);
4591 g_hChildStd_IN_Wr = NULL;
4592 }
4593
Bram Moolenaar0f873732019-12-05 20:28:46 +01004594 // Keep updating the window while waiting for the shell to finish.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004595 for (;;)
4596 {
4597 MSG msg;
4598
K.Takatab7057bd2022-01-21 11:37:07 +00004599 if (PeekMessageW(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004600 {
4601 TranslateMessage(&msg);
K.Takatab7057bd2022-01-21 11:37:07 +00004602 DispatchMessageW(&msg);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004603 }
4604
Bram Moolenaar0f873732019-12-05 20:28:46 +01004605 // write pipe information in the window
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004606 if ((options & (SHELL_READ|SHELL_WRITE))
4607# ifdef FEAT_GUI
4608 || gui.in_use
4609# endif
4610 )
4611 {
4612 len = 0;
4613 if (!(options & SHELL_EXPAND)
4614 && ((options &
4615 (SHELL_READ|SHELL_WRITE|SHELL_COOKED))
4616 != (SHELL_READ|SHELL_WRITE|SHELL_COOKED)
4617# ifdef FEAT_GUI
4618 || gui.in_use
4619# endif
4620 )
4621 && (ta_len > 0 || noread_cnt > 4))
4622 {
4623 if (ta_len == 0)
4624 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004625 // Get extra characters when we don't have any. Reset the
4626 // counter and timer.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004627 noread_cnt = 0;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004628 len = ui_inchar(ta_buf, BUFLEN, 10L, 0);
4629 }
4630 if (ta_len > 0 || len > 0)
4631 {
4632 /*
4633 * For pipes: Check for CTRL-C: send interrupt signal to
4634 * child. Check for CTRL-D: EOF, close pipe to child.
4635 */
4636 if (len == 1 && cmd != NULL)
4637 {
4638 if (ta_buf[ta_len] == Ctrl_C)
4639 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004640 // Learn what exit code is expected, for
4641 // now put 9 as SIGKILL
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004642 TerminateProcess(pi.hProcess, 9);
4643 }
4644 if (ta_buf[ta_len] == Ctrl_D)
4645 {
4646 CloseHandle(g_hChildStd_IN_Wr);
4647 g_hChildStd_IN_Wr = NULL;
4648 }
4649 }
4650
Bram Moolenaar2f7e1b82022-10-04 13:17:31 +01004651 len = term_replace_keycodes(ta_buf, ta_len, len);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004652
4653 /*
4654 * For pipes: echo the typed characters. For a pty this
4655 * does not seem to work.
4656 */
4657 for (i = ta_len; i < ta_len + len; ++i)
4658 {
4659 if (ta_buf[i] == '\n' || ta_buf[i] == '\b')
4660 msg_putchar(ta_buf[i]);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004661 else if (has_mbyte)
4662 {
4663 int l = (*mb_ptr2len)(ta_buf + i);
4664
4665 msg_outtrans_len(ta_buf + i, l);
4666 i += l - 1;
4667 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004668 else
4669 msg_outtrans_len(ta_buf + i, 1);
4670 }
4671 windgoto(msg_row, msg_col);
4672 out_flush();
4673
4674 ta_len += len;
4675
4676 /*
4677 * Write the characters to the child, unless EOF has been
4678 * typed for pipes. Write one character at a time, to
4679 * avoid losing too much typeahead. When writing buffer
4680 * lines, drop the typed characters (only check for
4681 * CTRL-C).
4682 */
4683 if (options & SHELL_WRITE)
4684 ta_len = 0;
4685 else if (g_hChildStd_IN_Wr != NULL)
4686 {
4687 WriteFile(g_hChildStd_IN_Wr, (char*)ta_buf,
4688 1, &len, NULL);
4689 // if we are typing in, we want to keep things reactive
4690 delay = 1;
4691 if (len > 0)
4692 {
4693 ta_len -= len;
4694 mch_memmove(ta_buf, ta_buf + len, ta_len);
4695 }
4696 }
4697 }
4698 }
4699 }
4700
4701 if (ta_len)
4702 ui_inchar_undo(ta_buf, ta_len);
4703
4704 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
4705 {
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004706 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004707 break;
4708 }
4709
4710 ++noread_cnt;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004711 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004712
Bram Moolenaar0f873732019-12-05 20:28:46 +01004713 // We start waiting for a very short time and then increase it, so
4714 // that we respond quickly when the process is quick, and don't
4715 // consume too much overhead when it's slow.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004716 if (delay < 50)
4717 delay += 10;
4718 }
4719
Bram Moolenaar0f873732019-12-05 20:28:46 +01004720 // Close the pipe
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004721 CloseHandle(g_hChildStd_OUT_Rd);
4722 if (g_hChildStd_IN_Wr != NULL)
4723 CloseHandle(g_hChildStd_IN_Wr);
4724
4725 WaitForSingleObject(pi.hProcess, INFINITE);
4726
Bram Moolenaar0f873732019-12-05 20:28:46 +01004727 // Get the command exit code
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004728 GetExitCodeProcess(pi.hProcess, &ret);
4729
4730 if (options & SHELL_READ)
4731 {
4732 if (ga.ga_len > 0)
4733 {
4734 append_ga_line(&ga);
Bram Moolenaar0f873732019-12-05 20:28:46 +01004735 // remember that the NL was missing
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004736 curbuf->b_no_eol_lnum = curwin->w_cursor.lnum;
4737 }
4738 else
4739 curbuf->b_no_eol_lnum = 0;
4740 ga_clear(&ga);
4741 }
4742
Bram Moolenaar0f873732019-12-05 20:28:46 +01004743 // Close the handles to the subprocess, so that it goes away
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004744 CloseHandle(pi.hThread);
4745 CloseHandle(pi.hProcess);
4746
4747 return ret;
4748}
4749
4750 static int
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004751mch_system_g(char *cmd, int options)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004752{
Bram Moolenaar0f873732019-12-05 20:28:46 +01004753 // if we can pipe and the shelltemp option is off
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004754 if (!p_stmp)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004755 return mch_system_piped(cmd, options);
4756 else
4757 return mch_system_classic(cmd, options);
4758}
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004759#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004760
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004761#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004762 static int
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02004763mch_system_c(char *cmd, int options UNUSED)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004764{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004765 int ret;
4766 WCHAR *wcmd;
Bram Moolenaar2efc44b2019-10-05 12:09:32 +02004767 char_u *buf;
4768 size_t len;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004769
Bram Moolenaar2efc44b2019-10-05 12:09:32 +02004770 // If the command starts and ends with double quotes, enclose the command
4771 // in parentheses.
4772 len = STRLEN(cmd);
4773 if (len >= 2 && cmd[0] == '"' && cmd[len - 1] == '"')
4774 {
4775 len += 3;
4776 buf = alloc(len);
4777 if (buf == NULL)
4778 return -1;
4779 vim_snprintf((char *)buf, len, "(%s)", cmd);
4780 wcmd = enc_to_utf16(buf, NULL);
4781 free(buf);
4782 }
4783 else
4784 wcmd = enc_to_utf16((char_u *)cmd, NULL);
4785
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004786 if (wcmd == NULL)
4787 return -1;
4788
4789 ret = _wsystem(wcmd);
4790 vim_free(wcmd);
4791 return ret;
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004792}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004793
4794#endif
4795
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004796 static int
4797mch_system(char *cmd, int options)
4798{
4799#ifdef VIMDLL
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02004800 if (gui.in_use || gui.starting)
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004801 return mch_system_g(cmd, options);
4802 else
4803 return mch_system_c(cmd, options);
4804#elif defined(FEAT_GUI_MSWIN)
4805 return mch_system_g(cmd, options);
4806#else
4807 return mch_system_c(cmd, options);
4808#endif
4809}
4810
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004811#if defined(FEAT_GUI) && defined(FEAT_TERMINAL)
4812/*
4813 * Use a terminal window to run a shell command in.
4814 */
4815 static int
4816mch_call_shell_terminal(
4817 char_u *cmd,
Bram Moolenaar0f873732019-12-05 20:28:46 +01004818 int options UNUSED) // SHELL_*, see vim.h
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004819{
4820 jobopt_T opt;
4821 char_u *newcmd = NULL;
4822 typval_T argvar[2];
4823 long_u cmdlen;
4824 int retval = -1;
4825 buf_T *buf;
Bram Moolenaarf9c38832018-06-19 19:59:20 +02004826 job_T *job;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004827 aco_save_T aco;
Bram Moolenaar0f873732019-12-05 20:28:46 +01004828 oparg_T oa; // operator arguments
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004829
Bram Moolenaar42f652f2018-03-19 21:44:37 +01004830 if (cmd == NULL)
4831 cmdlen = STRLEN(p_sh) + 1;
4832 else
4833 cmdlen = STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10;
Bram Moolenaar18a4ba22019-05-24 19:39:03 +02004834 newcmd = alloc(cmdlen);
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004835 if (newcmd == NULL)
4836 return 255;
Bram Moolenaar42f652f2018-03-19 21:44:37 +01004837 if (cmd == NULL)
4838 {
4839 STRCPY(newcmd, p_sh);
4840 ch_log(NULL, "starting terminal to run a shell");
4841 }
4842 else
4843 {
4844 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s", p_sh, p_shcf, cmd);
4845 ch_log(NULL, "starting terminal for system command '%s'", cmd);
4846 }
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004847
4848 init_job_options(&opt);
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004849
4850 argvar[0].v_type = VAR_STRING;
4851 argvar[0].vval.v_string = newcmd;
4852 argvar[1].v_type = VAR_UNKNOWN;
4853 buf = term_start(argvar, NULL, &opt, TERM_START_SYSTEM);
Bram Moolenaar81c3c89a2018-03-20 11:41:44 +01004854 if (buf == NULL)
Bram Moolenaar9029b912019-03-21 19:58:00 +01004855 {
4856 vim_free(newcmd);
Bram Moolenaar81c3c89a2018-03-20 11:41:44 +01004857 return 255;
Bram Moolenaar9029b912019-03-21 19:58:00 +01004858 }
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004859
Bram Moolenaarf9c38832018-06-19 19:59:20 +02004860 job = term_getjob(buf->b_term);
4861 ++job->jv_refcount;
4862
Bram Moolenaar0f873732019-12-05 20:28:46 +01004863 // Find a window to make "buf" curbuf.
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004864 aucmd_prepbuf(&aco, buf);
4865
4866 clear_oparg(&oa);
4867 while (term_use_loop())
4868 {
4869 if (oa.op_type == OP_NOP && oa.regname == NUL && !VIsual_active)
4870 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004871 // If terminal_loop() returns OK we got a key that is handled
4872 // in Normal model. We don't do redrawing anyway.
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004873 if (terminal_loop(TRUE) == OK)
4874 normal_cmd(&oa, TRUE);
4875 }
4876 else
4877 normal_cmd(&oa, TRUE);
4878 }
Bram Moolenaarf9c38832018-06-19 19:59:20 +02004879 retval = job->jv_exitval;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004880 ch_log(NULL, "system command finished");
4881
Bram Moolenaarf9c38832018-06-19 19:59:20 +02004882 job_unref(job);
4883
Bram Moolenaar0f873732019-12-05 20:28:46 +01004884 // restore curwin/curbuf and a few other things
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004885 aucmd_restbuf(&aco);
4886
4887 wait_return(TRUE);
4888 do_buffer(DOBUF_WIPE, DOBUF_FIRST, FORWARD, buf->b_fnum, TRUE);
4889
4890 vim_free(newcmd);
4891 return retval;
4892}
4893#endif
4894
Bram Moolenaar071d4272004-06-13 20:20:40 +00004895/*
4896 * Either execute a command by calling the shell or start a new shell
4897 */
4898 int
4899mch_call_shell(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004900 char_u *cmd,
Bram Moolenaar0f873732019-12-05 20:28:46 +01004901 int options) // SHELL_*, see vim.h
Bram Moolenaar071d4272004-06-13 20:20:40 +00004902{
4903 int x = 0;
4904 int tmode = cur_tmode;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004905 WCHAR szShellTitle[512];
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004906
Bram Moolenaarc9a9a0a2022-04-12 15:09:23 +01004907#ifdef FEAT_JOB_CHANNEL
4908 ch_log(NULL, "executing shell command: %s", cmd);
4909#endif
Bram Moolenaar0f873732019-12-05 20:28:46 +01004910 // Change the title to reflect that we are in a subshell.
K.Takataeeec2542021-06-02 13:28:16 +02004911 if (GetConsoleTitleW(szShellTitle, ARRAY_LENGTH(szShellTitle) - 4) > 0)
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004912 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004913 if (cmd == NULL)
4914 wcscat(szShellTitle, L" :sh");
4915 else
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004916 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004917 WCHAR *wn = enc_to_utf16((char_u *)cmd, NULL);
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004918
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004919 if (wn != NULL)
4920 {
4921 wcscat(szShellTitle, L" - !");
4922 if ((wcslen(szShellTitle) + wcslen(wn) <
K.Takataeeec2542021-06-02 13:28:16 +02004923 ARRAY_LENGTH(szShellTitle)))
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004924 wcscat(szShellTitle, wn);
4925 SetConsoleTitleW(szShellTitle);
4926 vim_free(wn);
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004927 }
4928 }
4929 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004930
4931 out_flush();
4932
4933#ifdef MCH_WRITE_DUMP
4934 if (fdDump)
4935 {
4936 fprintf(fdDump, "mch_call_shell(\"%s\", %d)\n", cmd, options);
4937 fflush(fdDump);
4938 }
4939#endif
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004940#if defined(FEAT_GUI) && defined(FEAT_TERMINAL)
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004941 // TODO: make the terminal window work with input or output redirected.
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004942 if (
4943# ifdef VIMDLL
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004944 gui.in_use &&
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004945# endif
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004946 vim_strchr(p_go, GO_TERMINAL) != NULL
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004947 && (options & (SHELL_FILTER|SHELL_DOOUT|SHELL_WRITE|SHELL_READ)) == 0)
4948 {
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004949 char_u *cmdbase = cmd;
4950
Bram Moolenaar4d5c1262019-09-20 17:20:02 +02004951 if (cmdbase != NULL)
4952 // Skip a leading quote and (.
4953 while (*cmdbase == '"' || *cmdbase == '(')
4954 ++cmdbase;
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004955
4956 // Check the command does not begin with "start "
Bram Moolenaar36e7a822019-11-13 21:49:24 +01004957 if (cmdbase == NULL || STRNICMP(cmdbase, "start", 5) != 0
4958 || !VIM_ISWHITE(cmdbase[5]))
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004959 {
4960 // Use a terminal window to run the command in.
4961 x = mch_call_shell_terminal(cmd, options);
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004962 resettitle();
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004963 return x;
4964 }
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004965 }
4966#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004967
4968 /*
4969 * Catch all deadly signals while running the external command, because a
4970 * CTRL-C, Ctrl-Break or illegal instruction might otherwise kill us.
4971 */
4972 signal(SIGINT, SIG_IGN);
4973#if defined(__GNUC__) && !defined(__MINGW32__)
4974 signal(SIGKILL, SIG_IGN);
4975#else
4976 signal(SIGBREAK, SIG_IGN);
4977#endif
4978 signal(SIGILL, SIG_IGN);
4979 signal(SIGFPE, SIG_IGN);
4980 signal(SIGSEGV, SIG_IGN);
4981 signal(SIGTERM, SIG_IGN);
4982 signal(SIGABRT, SIG_IGN);
4983
4984 if (options & SHELL_COOKED)
Bram Moolenaar0f873732019-12-05 20:28:46 +01004985 settmode(TMODE_COOK); // set to normal mode
Bram Moolenaar071d4272004-06-13 20:20:40 +00004986
4987 if (cmd == NULL)
4988 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004989 x = mch_system((char *)p_sh, options);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004990 }
4991 else
4992 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004993 // we use "command" or "cmd" to start the shell; slow but easy
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004994 char_u *newcmd = NULL;
4995 char_u *cmdbase = cmd;
4996 long_u cmdlen;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004997
Bram Moolenaar0f873732019-12-05 20:28:46 +01004998 // Skip a leading ", ( and "(.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004999 if (*cmdbase == '"' )
5000 ++cmdbase;
5001 if (*cmdbase == '(')
5002 ++cmdbase;
5003
Bram Moolenaar1c465442017-03-12 20:10:05 +01005004 if ((STRNICMP(cmdbase, "start", 5) == 0) && VIM_ISWHITE(cmdbase[5]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005005 {
5006 STARTUPINFO si;
5007 PROCESS_INFORMATION pi;
5008 DWORD flags = CREATE_NEW_CONSOLE;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01005009 INT n_show_cmd = SW_SHOWNORMAL;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005010 char_u *p;
5011
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01005012 ZeroMemory(&si, sizeof(si));
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005013 si.cb = sizeof(si);
5014 si.lpReserved = NULL;
5015 si.lpDesktop = NULL;
5016 si.lpTitle = NULL;
5017 si.dwFlags = 0;
5018 si.cbReserved2 = 0;
5019 si.lpReserved2 = NULL;
5020
5021 cmdbase = skipwhite(cmdbase + 5);
5022 if ((STRNICMP(cmdbase, "/min", 4) == 0)
Bram Moolenaar1c465442017-03-12 20:10:05 +01005023 && VIM_ISWHITE(cmdbase[4]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005024 {
5025 cmdbase = skipwhite(cmdbase + 4);
5026 si.dwFlags = STARTF_USESHOWWINDOW;
5027 si.wShowWindow = SW_SHOWMINNOACTIVE;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01005028 n_show_cmd = SW_SHOWMINNOACTIVE;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005029 }
5030 else if ((STRNICMP(cmdbase, "/b", 2) == 0)
Bram Moolenaar1c465442017-03-12 20:10:05 +01005031 && VIM_ISWHITE(cmdbase[2]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005032 {
5033 cmdbase = skipwhite(cmdbase + 2);
5034 flags = CREATE_NO_WINDOW;
5035 si.dwFlags = STARTF_USESTDHANDLES;
5036 si.hStdInput = CreateFile("\\\\.\\NUL", // File name
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005037 GENERIC_READ, // Access flags
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005038 0, // Share flags
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005039 NULL, // Security att.
5040 OPEN_EXISTING, // Open flags
5041 FILE_ATTRIBUTE_NORMAL, // File att.
5042 NULL); // Temp file
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005043 si.hStdOutput = si.hStdInput;
5044 si.hStdError = si.hStdInput;
5045 }
5046
Bram Moolenaar0f873732019-12-05 20:28:46 +01005047 // Remove a trailing ", ) and )" if they have a match
5048 // at the start of the command.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005049 if (cmdbase > cmd)
5050 {
5051 p = cmdbase + STRLEN(cmdbase);
5052 if (p > cmdbase && p[-1] == '"' && *cmd == '"')
5053 *--p = NUL;
5054 if (p > cmdbase && p[-1] == ')'
5055 && (*cmd =='(' || cmd[1] == '('))
5056 *--p = NUL;
5057 }
5058
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005059 newcmd = cmdbase;
5060 unescape_shellxquote(cmdbase, p_sxe);
5061
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005062 /*
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005063 * If creating new console, arguments are passed to the
5064 * 'cmd.exe' as-is. If it's not, arguments are not treated
5065 * correctly for current 'cmd.exe'. So unescape characters in
5066 * shellxescape except '|' for avoiding to be treated as
5067 * argument to them. Pass the arguments to sub-shell.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005068 */
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005069 if (flags != CREATE_NEW_CONSOLE)
5070 {
5071 char_u *subcmd;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01005072 char_u *cmd_shell = mch_getenv("COMSPEC");
5073
5074 if (cmd_shell == NULL || *cmd_shell == NUL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01005075 cmd_shell = (char_u *)default_shell();
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005076
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01005077 subcmd = vim_strsave_escaped_ext(cmdbase,
5078 (char_u *)"|", '^', FALSE);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005079 if (subcmd != NULL)
5080 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005081 // make "cmd.exe /c arguments"
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005082 cmdlen = STRLEN(cmd_shell) + STRLEN(subcmd) + 5;
Bram Moolenaar18a4ba22019-05-24 19:39:03 +02005083 newcmd = alloc(cmdlen);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005084 if (newcmd != NULL)
5085 vim_snprintf((char *)newcmd, cmdlen, "%s /c %s",
Bram Moolenaaree7d1002012-02-22 15:34:08 +01005086 cmd_shell, subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005087 else
5088 newcmd = cmdbase;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01005089 vim_free(subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005090 }
5091 }
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005092
5093 /*
5094 * Now, start the command as a process, so that it doesn't
5095 * inherit our handles which causes unpleasant dangling swap
5096 * files if we exit before the spawned process
5097 */
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005098 if (vim_create_process((char *)newcmd, FALSE, flags,
5099 &si, &pi, NULL, NULL))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005100 x = 0;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01005101 else if (vim_shell_execute((char *)newcmd, n_show_cmd)
5102 > (HINSTANCE)32)
5103 x = 0;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005104 else
5105 {
5106 x = -1;
Bram Moolenaar4f974752019-02-17 17:44:42 +01005107#ifdef FEAT_GUI_MSWIN
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005108# ifdef VIMDLL
5109 if (gui.in_use)
5110# endif
Bram Moolenaarac78dd42022-01-02 19:25:26 +00005111 emsg(_(e_command_not_found));
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005112#endif
5113 }
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005114
5115 if (newcmd != cmdbase)
5116 vim_free(newcmd);
5117
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01005118 if (si.dwFlags == STARTF_USESTDHANDLES && si.hStdInput != NULL)
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005119 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005120 // Close the handle to \\.\NUL created above.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005121 CloseHandle(si.hStdInput);
5122 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01005123 // Close the handles to the subprocess, so that it goes away
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005124 CloseHandle(pi.hThread);
5125 CloseHandle(pi.hProcess);
5126 }
5127 else
5128 {
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005129 cmdlen =
Bram Moolenaar4f974752019-02-17 17:44:42 +01005130#ifdef FEAT_GUI_MSWIN
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02005131 ((gui.in_use || gui.starting) ?
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005132 (!s_dont_use_vimrun && p_stmp ?
5133 STRLEN(vimrun_path) : STRLEN(p_sh) + STRLEN(p_shcf))
5134 : 0) +
Bram Moolenaar071d4272004-06-13 20:20:40 +00005135#endif
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005136 STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10;
Bram Moolenaar0fde2902008-03-16 13:54:13 +00005137
Bram Moolenaar18a4ba22019-05-24 19:39:03 +02005138 newcmd = alloc(cmdlen);
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005139 if (newcmd != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005140 {
Bram Moolenaar4f974752019-02-17 17:44:42 +01005141#if defined(FEAT_GUI_MSWIN)
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005142 if (
5143# ifdef VIMDLL
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02005144 (gui.in_use || gui.starting) &&
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005145# endif
5146 need_vimrun_warning)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005147 {
Bram Moolenaar63e43442016-11-19 17:28:44 +01005148 char *msg = _("VIMRUN.EXE not found in your $PATH.\n"
5149 "External commands will not pause after completion.\n"
5150 "See :help win32-vimrun for more information.");
5151 char *title = _("Vim Warning");
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005152 WCHAR *wmsg = enc_to_utf16((char_u *)msg, NULL);
5153 WCHAR *wtitle = enc_to_utf16((char_u *)title, NULL);
Bram Moolenaar63e43442016-11-19 17:28:44 +01005154
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005155 if (wmsg != NULL && wtitle != NULL)
5156 MessageBoxW(NULL, wmsg, wtitle, MB_ICONWARNING);
5157 vim_free(wmsg);
5158 vim_free(wtitle);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005159 need_vimrun_warning = FALSE;
5160 }
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005161 if (
5162# ifdef VIMDLL
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02005163 (gui.in_use || gui.starting) &&
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005164# endif
5165 !s_dont_use_vimrun && p_stmp)
Bram Moolenaarfcc4d922019-05-24 13:32:36 +02005166 // Use vimrun to execute the command. It opens a console
5167 // window, which can be closed without killing Vim.
Bram Moolenaarcc448b32010-07-14 16:52:17 +02005168 vim_snprintf((char *)newcmd, cmdlen, "%s%s%s %s %s",
Bram Moolenaar071d4272004-06-13 20:20:40 +00005169 vimrun_path,
5170 (msg_silent != 0 || (options & SHELL_DOOUT))
5171 ? "-s " : "",
5172 p_sh, p_shcf, cmd);
Bram Moolenaarfcc4d922019-05-24 13:32:36 +02005173 else if (
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005174# ifdef VIMDLL
Bram Moolenaarfcc4d922019-05-24 13:32:36 +02005175 (gui.in_use || gui.starting) &&
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005176# endif
Bram Moolenaar0e6bfb92019-07-31 20:53:56 +02005177 s_dont_use_vimrun && STRCMP(p_shcf, "/c") == 0)
Bram Moolenaarfcc4d922019-05-24 13:32:36 +02005178 // workaround for the case that "vimrun" does not exist
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005179 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s %s %s",
5180 p_sh, p_shcf, p_sh, p_shcf, cmd);
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005181 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00005182#endif
Bram Moolenaarcc448b32010-07-14 16:52:17 +02005183 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s",
Bram Moolenaar0fde2902008-03-16 13:54:13 +00005184 p_sh, p_shcf, cmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005185 x = mch_system((char *)newcmd, options);
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005186 vim_free(newcmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005187 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005188 }
5189 }
5190
5191 if (tmode == TMODE_RAW)
Bram Moolenaar3b1f18f2020-05-16 23:15:08 +02005192 {
5193 // The shell may have messed with the mode, always set it.
5194 cur_tmode = TMODE_UNKNOWN;
Bram Moolenaar0f873732019-12-05 20:28:46 +01005195 settmode(TMODE_RAW); // set to raw mode
Bram Moolenaar3b1f18f2020-05-16 23:15:08 +02005196 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005197
Bram Moolenaar0f873732019-12-05 20:28:46 +01005198 // Print the return value, unless "vimrun" was used.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005199 if (x != 0 && !(options & SHELL_SILENT) && !emsg_silent
Bram Moolenaar4f974752019-02-17 17:44:42 +01005200#if defined(FEAT_GUI_MSWIN)
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02005201 && ((gui.in_use || gui.starting) ?
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005202 ((options & SHELL_DOOUT) || s_dont_use_vimrun || !p_stmp) : 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005203#endif
5204 )
5205 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005206 smsg(_("shell returned %d"), x);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005207 msg_putchar('\n');
5208 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005209 resettitle();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005210
5211 signal(SIGINT, SIG_DFL);
5212#if defined(__GNUC__) && !defined(__MINGW32__)
5213 signal(SIGKILL, SIG_DFL);
5214#else
5215 signal(SIGBREAK, SIG_DFL);
5216#endif
5217 signal(SIGILL, SIG_DFL);
5218 signal(SIGFPE, SIG_DFL);
5219 signal(SIGSEGV, SIG_DFL);
5220 signal(SIGTERM, SIG_DFL);
5221 signal(SIGABRT, SIG_DFL);
5222
5223 return x;
5224}
5225
Bram Moolenaar509ce2a2016-03-11 22:52:15 +01005226#if defined(FEAT_JOB_CHANNEL) || defined(PROTO)
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005227 static HANDLE
5228job_io_file_open(
Bram Moolenaar972c3b82017-01-12 21:44:49 +01005229 char_u *fname,
5230 DWORD dwDesiredAccess,
5231 DWORD dwShareMode,
5232 LPSECURITY_ATTRIBUTES lpSecurityAttributes,
5233 DWORD dwCreationDisposition,
5234 DWORD dwFlagsAndAttributes)
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005235{
5236 HANDLE h;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005237 WCHAR *wn;
Bram Moolenaara12a1612019-01-24 16:39:02 +01005238
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005239 wn = enc_to_utf16(fname, NULL);
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005240 if (wn == NULL)
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005241 return INVALID_HANDLE_VALUE;
5242
5243 h = CreateFileW(wn, dwDesiredAccess, dwShareMode,
5244 lpSecurityAttributes, dwCreationDisposition,
5245 dwFlagsAndAttributes, NULL);
5246 vim_free(wn);
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005247 return h;
5248}
5249
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005250/*
5251 * Turn the dictionary "env" into a NUL separated list that can be used as the
5252 * environment argument of vim_create_process().
5253 */
Bram Moolenaarba6febd2017-10-30 21:56:23 +01005254 void
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005255win32_build_env(dict_T *env, garray_T *gap, int is_terminal)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005256{
5257 hashitem_T *hi;
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005258 long_u todo = env != NULL ? env->dv_hashtab.ht_used : 0;
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005259 LPVOID base = GetEnvironmentStringsW();
5260
Bram Moolenaar0f873732019-12-05 20:28:46 +01005261 // for last \0
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005262 if (ga_grow(gap, 1) == FAIL)
5263 return;
5264
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005265 if (env != NULL)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005266 {
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005267 for (hi = env->dv_hashtab.ht_array; todo > 0; ++hi)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005268 {
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005269 if (!HASHITEM_EMPTY(hi))
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005270 {
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005271 typval_T *item = &dict_lookup(hi)->di_tv;
5272 WCHAR *wkey = enc_to_utf16((char_u *)hi->hi_key, NULL);
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005273 WCHAR *wval = enc_to_utf16(tv_get_string(item), NULL);
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005274 --todo;
5275 if (wkey != NULL && wval != NULL)
5276 {
5277 size_t n;
5278 size_t lkey = wcslen(wkey);
5279 size_t lval = wcslen(wval);
Bram Moolenaar60104f12017-08-14 23:25:04 +02005280
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005281 if (ga_grow(gap, (int)(lkey + lval + 2)) != OK)
5282 continue;
5283 for (n = 0; n < lkey; n++)
5284 *((WCHAR*)gap->ga_data + gap->ga_len++) = wkey[n];
5285 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'=';
5286 for (n = 0; n < lval; n++)
5287 *((WCHAR*)gap->ga_data + gap->ga_len++) = wval[n];
5288 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5289 }
Bram Moolenaarbdace832019-03-02 10:13:42 +01005290 vim_free(wkey);
5291 vim_free(wval);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005292 }
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005293 }
5294 }
5295
Bram Moolenaar355757a2020-02-10 22:06:32 +01005296 if (base)
5297 {
5298 WCHAR *p = (WCHAR*) base;
5299
5300 // for last \0
5301 if (ga_grow(gap, 1) == FAIL)
5302 return;
5303
5304 while (*p != 0 || *(p + 1) != 0)
5305 {
5306 if (ga_grow(gap, 1) == OK)
5307 *((WCHAR*)gap->ga_data + gap->ga_len++) = *p;
5308 p++;
5309 }
5310 FreeEnvironmentStrings(base);
5311 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5312 }
5313
Bram Moolenaar493359e2018-06-12 20:25:52 +02005314# if defined(FEAT_CLIENTSERVER) || defined(FEAT_TERMINAL)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005315 {
Bram Moolenaar493359e2018-06-12 20:25:52 +02005316# ifdef FEAT_CLIENTSERVER
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005317 char_u *servername = get_vim_var_str(VV_SEND_SERVER);
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005318 size_t servername_len = STRLEN(servername);
Bram Moolenaar493359e2018-06-12 20:25:52 +02005319# endif
5320# ifdef FEAT_TERMINAL
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005321 char_u *version = get_vim_var_str(VV_VERSION);
5322 size_t version_len = STRLEN(version);
Bram Moolenaar493359e2018-06-12 20:25:52 +02005323# endif
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005324 // size of "VIM_SERVERNAME=" and value,
5325 // plus "VIM_TERMINAL=" and value,
5326 // plus two terminating NULs
5327 size_t n = 0
Bram Moolenaar493359e2018-06-12 20:25:52 +02005328# ifdef FEAT_CLIENTSERVER
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005329 + 15 + servername_len
Bram Moolenaar493359e2018-06-12 20:25:52 +02005330# endif
5331# ifdef FEAT_TERMINAL
5332 + 13 + version_len + 2
5333# endif
5334 ;
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005335
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005336 if (ga_grow(gap, (int)n) == OK)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005337 {
Bram Moolenaar493359e2018-06-12 20:25:52 +02005338# ifdef FEAT_CLIENTSERVER
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005339 for (n = 0; n < 15; n++)
5340 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5341 (WCHAR)"VIM_SERVERNAME="[n];
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005342 for (n = 0; n < servername_len; n++)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005343 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5344 (WCHAR)servername[n];
5345 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
Bram Moolenaar493359e2018-06-12 20:25:52 +02005346# endif
5347# ifdef FEAT_TERMINAL
5348 if (is_terminal)
5349 {
5350 for (n = 0; n < 13; n++)
5351 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5352 (WCHAR)"VIM_TERMINAL="[n];
5353 for (n = 0; n < version_len; n++)
5354 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5355 (WCHAR)version[n];
5356 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5357 }
5358# endif
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005359 }
5360 }
Bram Moolenaar79c6b512018-06-12 21:11:12 +02005361# endif
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005362}
5363
Bram Moolenaarb091f302019-01-19 14:37:00 +01005364/*
5365 * Create a pair of pipes.
5366 * Return TRUE for success, FALSE for failure.
5367 */
5368 static BOOL
5369create_pipe_pair(HANDLE handles[2])
5370{
5371 static LONG s;
5372 char name[64];
5373 SECURITY_ATTRIBUTES sa;
5374
5375 sprintf(name, "\\\\?\\pipe\\vim-%08lx-%08lx",
5376 GetCurrentProcessId(),
5377 InterlockedIncrement(&s));
5378
5379 // Create named pipe. Max size of named pipe is 65535.
5380 handles[1] = CreateNamedPipe(
5381 name,
5382 PIPE_ACCESS_OUTBOUND | FILE_FLAG_OVERLAPPED,
5383 PIPE_TYPE_BYTE | PIPE_NOWAIT,
Bram Moolenaar24058382019-01-24 23:11:49 +01005384 1, MAX_NAMED_PIPE_SIZE, 0, 0, NULL);
Bram Moolenaarb091f302019-01-19 14:37:00 +01005385
5386 if (handles[1] == INVALID_HANDLE_VALUE)
5387 return FALSE;
5388
5389 sa.nLength = sizeof(sa);
5390 sa.bInheritHandle = TRUE;
5391 sa.lpSecurityDescriptor = NULL;
5392
5393 handles[0] = CreateFile(name,
5394 FILE_GENERIC_READ,
5395 FILE_SHARE_READ, &sa,
5396 OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
5397
5398 if (handles[0] == INVALID_HANDLE_VALUE)
5399 {
Bram Moolenaar6982f422019-02-16 16:48:01 +01005400 CloseHandle(handles[1]);
Bram Moolenaarb091f302019-01-19 14:37:00 +01005401 return FALSE;
5402 }
5403
5404 return TRUE;
5405}
5406
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005407 void
Bram Moolenaar5a1feb82017-07-22 18:04:08 +02005408mch_job_start(char *cmd, job_T *job, jobopt_T *options)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005409{
5410 STARTUPINFO si;
5411 PROCESS_INFORMATION pi;
Bram Moolenaar14207f42016-10-27 21:13:10 +02005412 HANDLE jo;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005413 SECURITY_ATTRIBUTES saAttr;
5414 channel_T *channel = NULL;
Bram Moolenaard8070362016-02-15 21:56:54 +01005415 HANDLE ifd[2];
5416 HANDLE ofd[2];
5417 HANDLE efd[2];
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005418 garray_T ga;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005419
5420 int use_null_for_in = options->jo_io[PART_IN] == JIO_NULL;
5421 int use_null_for_out = options->jo_io[PART_OUT] == JIO_NULL;
5422 int use_null_for_err = options->jo_io[PART_ERR] == JIO_NULL;
5423 int use_file_for_in = options->jo_io[PART_IN] == JIO_FILE;
5424 int use_file_for_out = options->jo_io[PART_OUT] == JIO_FILE;
5425 int use_file_for_err = options->jo_io[PART_ERR] == JIO_FILE;
5426 int use_out_for_err = options->jo_io[PART_ERR] == JIO_OUT;
5427
5428 if (use_out_for_err && use_null_for_out)
5429 use_null_for_err = TRUE;
Bram Moolenaard8070362016-02-15 21:56:54 +01005430
5431 ifd[0] = INVALID_HANDLE_VALUE;
5432 ifd[1] = INVALID_HANDLE_VALUE;
5433 ofd[0] = INVALID_HANDLE_VALUE;
5434 ofd[1] = INVALID_HANDLE_VALUE;
5435 efd[0] = INVALID_HANDLE_VALUE;
5436 efd[1] = INVALID_HANDLE_VALUE;
Bram Moolenaar04935fb2022-01-08 16:19:22 +00005437 ga_init2(&ga, sizeof(wchar_t), 500);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005438
Bram Moolenaar14207f42016-10-27 21:13:10 +02005439 jo = CreateJobObject(NULL, NULL);
5440 if (jo == NULL)
5441 {
5442 job->jv_status = JOB_FAILED;
5443 goto failed;
5444 }
5445
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005446 if (options->jo_env != NULL)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005447 win32_build_env(options->jo_env, &ga, FALSE);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005448
Bram Moolenaar76467df2016-02-12 19:30:26 +01005449 ZeroMemory(&pi, sizeof(pi));
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005450 ZeroMemory(&si, sizeof(si));
5451 si.cb = sizeof(si);
Bram Moolenaard8070362016-02-15 21:56:54 +01005452 si.dwFlags |= STARTF_USESHOWWINDOW;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005453 si.wShowWindow = SW_HIDE;
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005454
Bram Moolenaard8070362016-02-15 21:56:54 +01005455 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
5456 saAttr.bInheritHandle = TRUE;
5457 saAttr.lpSecurityDescriptor = NULL;
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005458
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005459 if (use_file_for_in)
5460 {
5461 char_u *fname = options->jo_io_name[PART_IN];
5462
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005463 ifd[0] = job_io_file_open(fname, GENERIC_READ,
5464 FILE_SHARE_READ | FILE_SHARE_WRITE,
5465 &saAttr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL);
5466 if (ifd[0] == INVALID_HANDLE_VALUE)
Bram Moolenaar94d01912016-03-08 13:48:51 +01005467 {
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00005468 semsg(_(e_cant_open_file_str), fname);
Bram Moolenaar94d01912016-03-08 13:48:51 +01005469 goto failed;
5470 }
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005471 }
Bram Moolenaarb091f302019-01-19 14:37:00 +01005472 else if (!use_null_for_in
5473 && (!create_pipe_pair(ifd)
5474 || !SetHandleInformation(ifd[1], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005475 goto failed;
5476
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005477 if (use_file_for_out)
5478 {
5479 char_u *fname = options->jo_io_name[PART_OUT];
5480
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005481 ofd[1] = job_io_file_open(fname, GENERIC_WRITE,
5482 FILE_SHARE_READ | FILE_SHARE_WRITE,
5483 &saAttr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL);
5484 if (ofd[1] == INVALID_HANDLE_VALUE)
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005485 {
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00005486 semsg(_(e_cant_open_file_str), fname);
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005487 goto failed;
5488 }
5489 }
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005490 else if (!use_null_for_out &&
5491 (!CreatePipe(&ofd[0], &ofd[1], &saAttr, 0)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005492 || !SetHandleInformation(ofd[0], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005493 goto failed;
5494
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005495 if (use_file_for_err)
5496 {
5497 char_u *fname = options->jo_io_name[PART_ERR];
5498
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005499 efd[1] = job_io_file_open(fname, GENERIC_WRITE,
5500 FILE_SHARE_READ | FILE_SHARE_WRITE,
5501 &saAttr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL);
5502 if (efd[1] == INVALID_HANDLE_VALUE)
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005503 {
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00005504 semsg(_(e_cant_open_file_str), fname);
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005505 goto failed;
5506 }
5507 }
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005508 else if (!use_out_for_err && !use_null_for_err &&
5509 (!CreatePipe(&efd[0], &efd[1], &saAttr, 0)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005510 || !SetHandleInformation(efd[0], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaard8070362016-02-15 21:56:54 +01005511 goto failed;
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005512
Bram Moolenaard8070362016-02-15 21:56:54 +01005513 si.dwFlags |= STARTF_USESTDHANDLES;
5514 si.hStdInput = ifd[0];
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005515 si.hStdOutput = ofd[1];
5516 si.hStdError = use_out_for_err ? ofd[1] : efd[1];
5517
5518 if (!use_null_for_in || !use_null_for_out || !use_null_for_err)
5519 {
Bram Moolenaarde279892016-03-11 22:19:44 +01005520 if (options->jo_set & JO_CHANNEL)
5521 {
5522 channel = options->jo_channel;
5523 if (channel != NULL)
5524 ++channel->ch_refcount;
5525 }
5526 else
5527 channel = add_channel();
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005528 if (channel == NULL)
5529 goto failed;
5530 }
Bram Moolenaard8070362016-02-15 21:56:54 +01005531
5532 if (!vim_create_process(cmd, TRUE,
Bram Moolenaar14207f42016-10-27 21:13:10 +02005533 CREATE_SUSPENDED |
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005534 CREATE_DEFAULT_ERROR_MODE |
5535 CREATE_NEW_PROCESS_GROUP |
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005536 CREATE_UNICODE_ENVIRONMENT |
Bram Moolenaar76467df2016-02-12 19:30:26 +01005537 CREATE_NEW_CONSOLE,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005538 &si, &pi,
5539 ga.ga_data,
5540 (char *)options->jo_cwd))
Bram Moolenaar76467df2016-02-12 19:30:26 +01005541 {
Bram Moolenaar14207f42016-10-27 21:13:10 +02005542 CloseHandle(jo);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005543 job->jv_status = JOB_FAILED;
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005544 goto failed;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005545 }
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005546
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005547 ga_clear(&ga);
5548
Bram Moolenaar14207f42016-10-27 21:13:10 +02005549 if (!AssignProcessToJobObject(jo, pi.hProcess))
5550 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005551 // if failing, switch the way to terminate
5552 // process with TerminateProcess.
Bram Moolenaar14207f42016-10-27 21:13:10 +02005553 CloseHandle(jo);
5554 jo = NULL;
5555 }
5556 ResumeThread(pi.hThread);
Bram Moolenaar75578a32016-03-10 16:33:31 +01005557 CloseHandle(pi.hThread);
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005558 job->jv_proc_info = pi;
Bram Moolenaar14207f42016-10-27 21:13:10 +02005559 job->jv_job_object = jo;
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005560 job->jv_status = JOB_STARTED;
5561
Bram Moolenaar641ad6c2016-09-01 18:32:11 +02005562 CloseHandle(ifd[0]);
5563 CloseHandle(ofd[1]);
5564 if (!use_out_for_err && !use_null_for_err)
Bram Moolenaarc25558b2016-03-03 21:02:23 +01005565 CloseHandle(efd[1]);
Bram Moolenaard8070362016-02-15 21:56:54 +01005566
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005567 job->jv_channel = channel;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005568 if (channel != NULL)
5569 {
5570 channel_set_pipes(channel,
5571 use_file_for_in || use_null_for_in
5572 ? INVALID_FD : (sock_T)ifd[1],
5573 use_file_for_out || use_null_for_out
5574 ? INVALID_FD : (sock_T)ofd[0],
5575 use_out_for_err || use_file_for_err || use_null_for_err
5576 ? INVALID_FD : (sock_T)efd[0]);
5577 channel_set_job(channel, job, options);
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005578 }
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005579 return;
5580
5581failed:
Bram Moolenaard8070362016-02-15 21:56:54 +01005582 CloseHandle(ifd[0]);
5583 CloseHandle(ofd[0]);
5584 CloseHandle(efd[0]);
5585 CloseHandle(ifd[1]);
5586 CloseHandle(ofd[1]);
5587 CloseHandle(efd[1]);
Bram Moolenaarde279892016-03-11 22:19:44 +01005588 channel_unref(channel);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005589 ga_clear(&ga);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005590}
5591
5592 char *
5593mch_job_status(job_T *job)
5594{
5595 DWORD dwExitCode = 0;
5596
Bram Moolenaar76467df2016-02-12 19:30:26 +01005597 if (!GetExitCodeProcess(job->jv_proc_info.hProcess, &dwExitCode)
5598 || dwExitCode != STILL_ACTIVE)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005599 {
Bram Moolenaareab089d2016-02-21 19:32:02 +01005600 job->jv_exitval = (int)dwExitCode;
Bram Moolenaar7df915d2016-11-17 17:25:32 +01005601 if (job->jv_status < JOB_ENDED)
Bram Moolenaar97792de2016-10-15 18:36:49 +02005602 {
5603 ch_log(job->jv_channel, "Job ended");
5604 job->jv_status = JOB_ENDED;
5605 }
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005606 return "dead";
5607 }
5608 return "run";
5609}
5610
Bram Moolenaar97792de2016-10-15 18:36:49 +02005611 job_T *
5612mch_detect_ended_job(job_T *job_list)
5613{
5614 HANDLE jobHandles[MAXIMUM_WAIT_OBJECTS];
5615 job_T *jobArray[MAXIMUM_WAIT_OBJECTS];
5616 job_T *job = job_list;
5617
5618 while (job != NULL)
5619 {
5620 DWORD n;
5621 DWORD result;
5622
5623 for (n = 0; n < MAXIMUM_WAIT_OBJECTS
5624 && job != NULL; job = job->jv_next)
5625 {
5626 if (job->jv_status == JOB_STARTED)
5627 {
5628 jobHandles[n] = job->jv_proc_info.hProcess;
5629 jobArray[n] = job;
5630 ++n;
5631 }
5632 }
5633 if (n == 0)
5634 continue;
5635 result = WaitForMultipleObjects(n, jobHandles, FALSE, 0);
5636 if (result >= WAIT_OBJECT_0 && result < WAIT_OBJECT_0 + n)
5637 {
5638 job_T *wait_job = jobArray[result - WAIT_OBJECT_0];
5639
5640 if (STRCMP(mch_job_status(wait_job), "dead") == 0)
5641 return wait_job;
5642 }
5643 }
5644 return NULL;
5645}
5646
Bram Moolenaarfb630902016-10-29 14:55:00 +02005647 static BOOL
5648terminate_all(HANDLE process, int code)
5649{
5650 PROCESSENTRY32 pe;
5651 HANDLE h = INVALID_HANDLE_VALUE;
5652 DWORD pid = GetProcessId(process);
5653
5654 if (pid != 0)
5655 {
5656 h = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
5657 if (h != INVALID_HANDLE_VALUE)
5658 {
5659 pe.dwSize = sizeof(PROCESSENTRY32);
5660 if (!Process32First(h, &pe))
5661 goto theend;
5662
5663 do
5664 {
5665 if (pe.th32ParentProcessID == pid)
5666 {
5667 HANDLE ph = OpenProcess(
5668 PROCESS_ALL_ACCESS, FALSE, pe.th32ProcessID);
5669 if (ph != NULL)
5670 {
5671 terminate_all(ph, code);
5672 CloseHandle(ph);
5673 }
5674 }
5675 } while (Process32Next(h, &pe));
5676
5677 CloseHandle(h);
5678 }
5679 }
5680
5681theend:
5682 return TerminateProcess(process, code);
5683}
5684
5685/*
5686 * Send a (deadly) signal to "job".
5687 * Return FAIL if it didn't work.
5688 */
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005689 int
Bram Moolenaar2d33e902017-08-11 16:31:54 +02005690mch_signal_job(job_T *job, char_u *how)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005691{
Bram Moolenaar923d9262016-02-25 20:56:01 +01005692 int ret;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005693
Bram Moolenaar923d9262016-02-25 20:56:01 +01005694 if (STRCMP(how, "term") == 0 || STRCMP(how, "kill") == 0 || *how == NUL)
Bram Moolenaar76467df2016-02-12 19:30:26 +01005695 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005696 // deadly signal
Bram Moolenaar14207f42016-10-27 21:13:10 +02005697 if (job->jv_job_object != NULL)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005698 {
5699 if (job->jv_channel != NULL && job->jv_channel->ch_anonymous_pipe)
5700 job->jv_channel->ch_killing = TRUE;
K.Takata135e1522022-01-29 15:27:58 +00005701 return TerminateJobObject(job->jv_job_object, (UINT)-1) ? OK : FAIL;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005702 }
Bram Moolenaarb3e195c2020-02-10 21:32:19 +01005703 return terminate_all(job->jv_proc_info.hProcess, -1) ? OK : FAIL;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005704 }
5705
5706 if (!AttachConsole(job->jv_proc_info.dwProcessId))
5707 return FAIL;
5708 ret = GenerateConsoleCtrlEvent(
Bram Moolenaar923d9262016-02-25 20:56:01 +01005709 STRCMP(how, "int") == 0 ? CTRL_C_EVENT : CTRL_BREAK_EVENT,
5710 job->jv_proc_info.dwProcessId)
5711 ? OK : FAIL;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005712 FreeConsole();
5713 return ret;
5714}
5715
5716/*
5717 * Clear the data related to "job".
5718 */
5719 void
5720mch_clear_job(job_T *job)
5721{
5722 if (job->jv_status != JOB_FAILED)
5723 {
Bram Moolenaar14207f42016-10-27 21:13:10 +02005724 if (job->jv_job_object != NULL)
5725 CloseHandle(job->jv_job_object);
Bram Moolenaar76467df2016-02-12 19:30:26 +01005726 CloseHandle(job->jv_proc_info.hProcess);
5727 }
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005728}
5729#endif
5730
Bram Moolenaar071d4272004-06-13 20:20:40 +00005731
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005732#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005733
5734/*
5735 * Start termcap mode
5736 */
5737 static void
5738termcap_mode_start(void)
5739{
5740 DWORD cmodein;
5741
5742 if (g_fTermcapMode)
5743 return;
5744
Bram Moolenaar81ccbf12020-04-15 21:05:30 +02005745 if (!p_rs && USE_VTP)
5746 vtp_printf("\033[?1049h");
5747
Bram Moolenaar071d4272004-06-13 20:20:40 +00005748 SaveConsoleBuffer(&g_cbNonTermcap);
5749
5750 if (g_cbTermcap.IsValid)
5751 {
5752 /*
5753 * We've been in termcap mode before. Restore certain screen
5754 * characteristics, including the buffer size and the window
5755 * size. Since we will be redrawing the screen, we don't need
5756 * to restore the actual contents of the buffer.
5757 */
5758 RestoreConsoleBuffer(&g_cbTermcap, FALSE);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005759 reset_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005760 SetConsoleWindowInfo(g_hConOut, TRUE, &g_cbTermcap.Info.srWindow);
5761 Rows = g_cbTermcap.Info.dwSize.Y;
5762 Columns = g_cbTermcap.Info.dwSize.X;
5763 }
5764 else
5765 {
5766 /*
5767 * This is our first time entering termcap mode. Clear the console
5768 * screen buffer, and resize the buffer to match the current window
5769 * size. We will use this as the size of our editing environment.
5770 */
5771 ClearConsoleBuffer(g_attrCurrent);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005772 set_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005773 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
5774 }
5775
Bram Moolenaar071d4272004-06-13 20:20:40 +00005776 resettitle();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005777
5778 GetConsoleMode(g_hConIn, &cmodein);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005779 if (g_fMouseActive)
Wez Furlong6ef5ab52021-05-30 19:29:41 +02005780 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00005781 cmodein |= ENABLE_MOUSE_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02005782 cmodein &= ~ENABLE_QUICK_EDIT_MODE;
5783 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005784 else
Wez Furlong6ef5ab52021-05-30 19:29:41 +02005785 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00005786 cmodein &= ~ENABLE_MOUSE_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02005787 cmodein |= g_cmodein & ENABLE_QUICK_EDIT_MODE;
5788 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005789 cmodein |= ENABLE_WINDOW_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02005790 SetConsoleMode(g_hConIn, cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005791
5792 redraw_later_clear();
5793 g_fTermcapMode = TRUE;
5794}
5795
5796
5797/*
5798 * End termcap mode
5799 */
5800 static void
5801termcap_mode_end(void)
5802{
5803 DWORD cmodein;
5804 ConsoleBuffer *cb;
5805 COORD coord;
5806 DWORD dwDummy;
5807
5808 if (!g_fTermcapMode)
5809 return;
5810
5811 SaveConsoleBuffer(&g_cbTermcap);
5812
5813 GetConsoleMode(g_hConIn, &cmodein);
5814 cmodein &= ~(ENABLE_MOUSE_INPUT | ENABLE_WINDOW_INPUT);
Wez Furlong6ef5ab52021-05-30 19:29:41 +02005815 cmodein |= g_cmodein & ENABLE_QUICK_EDIT_MODE;
5816 SetConsoleMode(g_hConIn, cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005817
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01005818# ifdef FEAT_RESTORE_ORIG_SCREEN
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01005819 cb = exiting ? &g_cbOrig : &g_cbNonTermcap;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01005820# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00005821 cb = &g_cbNonTermcap;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01005822# endif
Bram Moolenaar81ccbf12020-04-15 21:05:30 +02005823 RestoreConsoleBuffer(cb, p_rs);
Bram Moolenaardf543822020-01-30 11:53:59 +01005824 restore_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005825 SetConsoleCursorInfo(g_hConOut, &g_cci);
5826
5827 if (p_rs || exiting)
5828 {
5829 /*
5830 * Clear anything that happens to be on the current line.
5831 */
5832 coord.X = 0;
5833 coord.Y = (SHORT) (p_rs ? cb->Info.dwCursorPosition.Y : (Rows - 1));
5834 FillConsoleOutputCharacter(g_hConOut, ' ',
5835 cb->Info.dwSize.X, coord, &dwDummy);
5836 /*
5837 * The following is just for aesthetics. If we are exiting without
5838 * restoring the screen, then we want to have a prompt string
5839 * appear at the bottom line. However, the command interpreter
5840 * seems to always advance the cursor one line before displaying
5841 * the prompt string, which causes the screen to scroll. To
5842 * counter this, move the cursor up one line before exiting.
5843 */
5844 if (exiting && !p_rs)
5845 coord.Y--;
5846 /*
5847 * Position the cursor at the leftmost column of the desired row.
5848 */
Bram Moolenaar81ccbf12020-04-15 21:05:30 +02005849 SetConsoleCursorPosition(g_hConOut, coord);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005850 }
5851
Bram Moolenaar81ccbf12020-04-15 21:05:30 +02005852 if (!p_rs && USE_VTP)
Bram Moolenaar0afdcf82020-04-01 18:29:10 +02005853 vtp_printf("\033[?1049l");
5854
Bram Moolenaar071d4272004-06-13 20:20:40 +00005855 g_fTermcapMode = FALSE;
5856}
Bram Moolenaar0f873732019-12-05 20:28:46 +01005857#endif // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00005858
5859
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005860#if defined(FEAT_GUI_MSWIN) && !defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005861 void
5862mch_write(
Bram Moolenaar1266d672017-02-01 13:43:36 +01005863 char_u *s UNUSED,
5864 int len UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005865{
Bram Moolenaar0f873732019-12-05 20:28:46 +01005866 // never used
Bram Moolenaar071d4272004-06-13 20:20:40 +00005867}
5868
5869#else
5870
5871/*
5872 * clear `n' chars, starting from `coord'
5873 */
5874 static void
5875clear_chars(
5876 COORD coord,
5877 DWORD n)
5878{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005879 if (!USE_VTP)
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02005880 {
5881 DWORD dwDummy;
5882
5883 FillConsoleOutputCharacter(g_hConOut, ' ', n, coord, &dwDummy);
5884 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, n, coord,
5885 &dwDummy);
5886 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005887 else
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02005888 {
5889 set_console_color_rgb();
5890 gotoxy(coord.X + 1, coord.Y + 1);
5891 vtp_printf("\033[%dX", n);
5892 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005893}
5894
5895
5896/*
5897 * Clear the screen
5898 */
5899 static void
5900clear_screen(void)
5901{
5902 g_coord.X = g_coord.Y = 0;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005903
5904 if (!USE_VTP)
5905 clear_chars(g_coord, Rows * Columns);
5906 else
5907 {
5908 set_console_color_rgb();
5909 gotoxy(1, 1);
5910 vtp_printf("\033[2J");
5911 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005912}
5913
5914
5915/*
5916 * Clear to end of display
5917 */
5918 static void
5919clear_to_end_of_display(void)
5920{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005921 COORD save = g_coord;
5922
5923 if (!USE_VTP)
5924 clear_chars(g_coord, (Rows - g_coord.Y - 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005925 * Columns + (Columns - g_coord.X));
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005926 else
5927 {
5928 set_console_color_rgb();
5929 gotoxy(g_coord.X + 1, g_coord.Y + 1);
5930 vtp_printf("\033[0J");
5931
5932 gotoxy(save.X + 1, save.Y + 1);
5933 g_coord = save;
5934 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005935}
5936
5937
5938/*
5939 * Clear to end of line
5940 */
5941 static void
5942clear_to_end_of_line(void)
5943{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005944 COORD save = g_coord;
5945
5946 if (!USE_VTP)
5947 clear_chars(g_coord, Columns - g_coord.X);
5948 else
5949 {
5950 set_console_color_rgb();
5951 gotoxy(g_coord.X + 1, g_coord.Y + 1);
5952 vtp_printf("\033[0K");
5953
5954 gotoxy(save.X + 1, save.Y + 1);
5955 g_coord = save;
5956 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005957}
5958
5959
5960/*
5961 * Scroll the scroll region up by `cLines' lines
5962 */
5963 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005964scroll(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005965{
5966 COORD oldcoord = g_coord;
5967
5968 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
5969 delete_lines(cLines);
5970
5971 g_coord = oldcoord;
5972}
5973
5974
5975/*
5976 * Set the scroll region
5977 */
5978 static void
5979set_scroll_region(
5980 unsigned left,
5981 unsigned top,
5982 unsigned right,
5983 unsigned bottom)
5984{
5985 if (left >= right
5986 || top >= bottom
5987 || right > (unsigned) Columns - 1
5988 || bottom > (unsigned) Rows - 1)
5989 return;
5990
5991 g_srScrollRegion.Left = left;
5992 g_srScrollRegion.Top = top;
5993 g_srScrollRegion.Right = right;
5994 g_srScrollRegion.Bottom = bottom;
Bram Moolenaar6982f422019-02-16 16:48:01 +01005995}
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005996
Bram Moolenaar6982f422019-02-16 16:48:01 +01005997 static void
5998set_scroll_region_tb(
5999 unsigned top,
6000 unsigned bottom)
6001{
6002 if (top >= bottom || bottom > (unsigned)Rows - 1)
6003 return;
6004
6005 g_srScrollRegion.Top = top;
6006 g_srScrollRegion.Bottom = bottom;
6007}
6008
6009 static void
6010set_scroll_region_lr(
6011 unsigned left,
6012 unsigned right)
6013{
6014 if (left >= right || right > (unsigned)Columns - 1)
6015 return;
6016
6017 g_srScrollRegion.Left = left;
6018 g_srScrollRegion.Right = right;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006019}
6020
6021
6022/*
6023 * Insert `cLines' lines at the current cursor position
6024 */
6025 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006026insert_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006027{
Bram Moolenaar6982f422019-02-16 16:48:01 +01006028 SMALL_RECT source, clip;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006029 COORD dest;
6030 CHAR_INFO fill;
6031
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006032 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
6033
Bram Moolenaar6982f422019-02-16 16:48:01 +01006034 dest.X = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006035 dest.Y = g_coord.Y + cLines;
6036
Bram Moolenaar6982f422019-02-16 16:48:01 +01006037 source.Left = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006038 source.Top = g_coord.Y;
6039 source.Right = g_srScrollRegion.Right;
6040 source.Bottom = g_srScrollRegion.Bottom - cLines;
6041
Bram Moolenaar6982f422019-02-16 16:48:01 +01006042 clip.Left = g_srScrollRegion.Left;
6043 clip.Top = g_coord.Y;
6044 clip.Right = g_srScrollRegion.Right;
6045 clip.Bottom = g_srScrollRegion.Bottom;
6046
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006047 fill.Char.AsciiChar = ' ';
6048 if (!USE_VTP)
6049 fill.Attributes = g_attrCurrent;
6050 else
6051 fill.Attributes = g_attrDefault;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006052
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006053 set_console_color_rgb();
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006054
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006055 ScrollConsoleScreenBuffer(g_hConOut, &source, &clip, dest, &fill);
6056
Bram Moolenaar6982f422019-02-16 16:48:01 +01006057 // Here we have to deal with a win32 console flake: If the scroll
6058 // region looks like abc and we scroll c to a and fill with d we get
6059 // cbd... if we scroll block c one line at a time to a, we get cdd...
6060 // vim expects cdd consistently... So we have to deal with that
6061 // here... (this also occurs scrolling the same way in the other
6062 // direction).
Bram Moolenaar071d4272004-06-13 20:20:40 +00006063
6064 if (source.Bottom < dest.Y)
6065 {
6066 COORD coord;
Bram Moolenaar6982f422019-02-16 16:48:01 +01006067 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006068
Bram Moolenaar6982f422019-02-16 16:48:01 +01006069 coord.X = source.Left;
6070 for (i = clip.Top; i < dest.Y; ++i)
6071 {
6072 coord.Y = i;
6073 clear_chars(coord, source.Right - source.Left + 1);
6074 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006075 }
Bram Moolenaar06b7b582020-05-30 17:49:25 +02006076
6077 if (USE_WT)
6078 {
6079 COORD coord;
6080 int i;
6081
6082 coord.X = source.Left;
6083 for (i = source.Top; i < dest.Y; ++i)
6084 {
6085 coord.Y = i;
6086 clear_chars(coord, source.Right - source.Left + 1);
6087 }
6088 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006089}
6090
6091
6092/*
6093 * Delete `cLines' lines at the current cursor position
6094 */
6095 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006096delete_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006097{
Bram Moolenaar6982f422019-02-16 16:48:01 +01006098 SMALL_RECT source, clip;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006099 COORD dest;
6100 CHAR_INFO fill;
6101 int nb;
6102
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006103 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
6104
Bram Moolenaar6982f422019-02-16 16:48:01 +01006105 dest.X = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006106 dest.Y = g_coord.Y;
6107
Bram Moolenaar6982f422019-02-16 16:48:01 +01006108 source.Left = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006109 source.Top = g_coord.Y + cLines;
6110 source.Right = g_srScrollRegion.Right;
6111 source.Bottom = g_srScrollRegion.Bottom;
6112
Bram Moolenaar6982f422019-02-16 16:48:01 +01006113 clip.Left = g_srScrollRegion.Left;
6114 clip.Top = g_coord.Y;
6115 clip.Right = g_srScrollRegion.Right;
6116 clip.Bottom = g_srScrollRegion.Bottom;
6117
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006118 fill.Char.AsciiChar = ' ';
6119 if (!USE_VTP)
6120 fill.Attributes = g_attrCurrent;
6121 else
6122 fill.Attributes = g_attrDefault;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006123
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006124 set_console_color_rgb();
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006125
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006126 ScrollConsoleScreenBuffer(g_hConOut, &source, &clip, dest, &fill);
6127
Bram Moolenaar6982f422019-02-16 16:48:01 +01006128 // Here we have to deal with a win32 console flake; See insert_lines()
6129 // above.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006130
6131 nb = dest.Y + (source.Bottom - source.Top) + 1;
6132
6133 if (nb < source.Top)
6134 {
6135 COORD coord;
Bram Moolenaar6982f422019-02-16 16:48:01 +01006136 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006137
Bram Moolenaar6982f422019-02-16 16:48:01 +01006138 coord.X = source.Left;
6139 for (i = nb; i < clip.Bottom; ++i)
6140 {
6141 coord.Y = i;
6142 clear_chars(coord, source.Right - source.Left + 1);
6143 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006144 }
Bram Moolenaar06b7b582020-05-30 17:49:25 +02006145
6146 if (USE_WT)
6147 {
6148 COORD coord;
6149 int i;
6150
6151 coord.X = source.Left;
6152 for (i = nb; i <= source.Bottom; ++i)
6153 {
6154 coord.Y = i;
6155 clear_chars(coord, source.Right - source.Left + 1);
6156 }
6157 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006158}
6159
6160
6161/*
Bram Moolenaar2313b612019-09-27 14:14:32 +02006162 * Set the cursor position to (x,y) (1-based).
Bram Moolenaar071d4272004-06-13 20:20:40 +00006163 */
6164 static void
6165gotoxy(
6166 unsigned x,
6167 unsigned y)
6168{
6169 if (x < 1 || x > (unsigned)Columns || y < 1 || y > (unsigned)Rows)
6170 return;
6171
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006172 if (!USE_VTP)
Bram Moolenaar2313b612019-09-27 14:14:32 +02006173 {
Bram Moolenaar82e743c2020-03-26 15:39:53 +01006174 // There are reports of double-width characters not displayed
6175 // correctly. This workaround should fix it, similar to how it's done
6176 // for VTP.
6177 g_coord.X = 0;
6178 SetConsoleCursorPosition(g_hConOut, g_coord);
6179
Bram Moolenaar2313b612019-09-27 14:14:32 +02006180 // external cursor coords are 1-based; internal are 0-based
6181 g_coord.X = x - 1;
6182 g_coord.Y = y - 1;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006183 SetConsoleCursorPosition(g_hConOut, g_coord);
Bram Moolenaar2313b612019-09-27 14:14:32 +02006184 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006185 else
Bram Moolenaar2313b612019-09-27 14:14:32 +02006186 {
6187 // Move the cursor to the left edge of the screen to prevent screen
Bram Moolenaara1299742019-10-10 16:36:00 +02006188 // destruction. Insider build bug. Always enabled because it's cheap
6189 // and avoids mistakes with recognizing the build.
6190 vtp_printf("\033[%d;%dH", g_coord.Y + 1, 1);
Bram Moolenaar2313b612019-09-27 14:14:32 +02006191
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006192 vtp_printf("\033[%d;%dH", y, x);
Bram Moolenaar2313b612019-09-27 14:14:32 +02006193
6194 g_coord.X = x - 1;
6195 g_coord.Y = y - 1;
6196 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006197}
6198
6199
6200/*
6201 * Set the current text attribute = (foreground | background)
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006202 * See ../runtime/doc/os_win32.txt for the numbers.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006203 */
6204 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006205textattr(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006206{
Bram Moolenaar6383b922015-03-24 17:12:19 +01006207 g_attrCurrent = wAttr & 0xff;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006208
6209 SetConsoleTextAttribute(g_hConOut, wAttr);
6210}
6211
6212
6213 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006214textcolor(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006215{
Bram Moolenaar6383b922015-03-24 17:12:19 +01006216 g_attrCurrent = (g_attrCurrent & 0xf0) + (wAttr & 0x0f);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006217
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006218 if (!USE_VTP)
6219 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
6220 else
6221 vtp_sgr_bulk(wAttr);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006222}
6223
6224
6225 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006226textbackground(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006227{
Bram Moolenaar6383b922015-03-24 17:12:19 +01006228 g_attrCurrent = (g_attrCurrent & 0x0f) + ((wAttr & 0x0f) << 4);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006229
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006230 if (!USE_VTP)
6231 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
6232 else
6233 vtp_sgr_bulk(wAttr);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006234}
6235
6236
6237/*
6238 * restore the default text attribute (whatever we started with)
6239 */
6240 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006241normvideo(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006242{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006243 if (!USE_VTP)
6244 textattr(g_attrDefault);
6245 else
6246 vtp_sgr_bulk(0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006247}
6248
6249
6250static WORD g_attrPreStandout = 0;
6251
6252/*
6253 * Make the text standout, by brightening it
6254 */
6255 static void
6256standout(void)
6257{
6258 g_attrPreStandout = g_attrCurrent;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006259
Bram Moolenaar071d4272004-06-13 20:20:40 +00006260 textattr((WORD) (g_attrCurrent|FOREGROUND_INTENSITY|BACKGROUND_INTENSITY));
6261}
6262
6263
6264/*
6265 * Turn off standout mode
6266 */
6267 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006268standend(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006269{
6270 if (g_attrPreStandout)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006271 textattr(g_attrPreStandout);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006272
6273 g_attrPreStandout = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006274}
6275
6276
6277/*
Bram Moolenaarff1d0d42007-05-10 17:24:16 +00006278 * Set normal fg/bg color, based on T_ME. Called when t_me has been set.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006279 */
6280 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006281mch_set_normal_colors(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006282{
6283 char_u *p;
6284 int n;
6285
6286 cterm_normal_fg_color = (g_attrDefault & 0xf) + 1;
6287 cterm_normal_bg_color = ((g_attrDefault >> 4) & 0xf) + 1;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006288 if (
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006289# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006290 !p_tgc &&
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006291# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006292 T_ME[0] == ESC && T_ME[1] == '|')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006293 {
6294 p = T_ME + 2;
6295 n = getdigits(&p);
6296 if (*p == 'm' && n > 0)
6297 {
6298 cterm_normal_fg_color = (n & 0xf) + 1;
6299 cterm_normal_bg_color = ((n >> 4) & 0xf) + 1;
6300 }
6301 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006302# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006303 cterm_normal_fg_gui_color = INVALCOLOR;
6304 cterm_normal_bg_gui_color = INVALCOLOR;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006305# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006306}
6307
6308
6309/*
6310 * visual bell: flash the screen
6311 */
6312 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006313visual_bell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006314{
6315 COORD coordOrigin = {0, 0};
6316 WORD attrFlash = ~g_attrCurrent & 0xff;
6317
6318 DWORD dwDummy;
Bram Moolenaarc799fe22019-05-28 23:08:19 +02006319 LPWORD oldattrs = ALLOC_MULT(WORD, Rows * Columns);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006320
6321 if (oldattrs == NULL)
6322 return;
6323 ReadConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
6324 coordOrigin, &dwDummy);
6325 FillConsoleOutputAttribute(g_hConOut, attrFlash, Rows * Columns,
6326 coordOrigin, &dwDummy);
6327
Bram Moolenaar0f873732019-12-05 20:28:46 +01006328 Sleep(15); // wait for 15 msec
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006329 if (!USE_VTP)
6330 WriteConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
Bram Moolenaar071d4272004-06-13 20:20:40 +00006331 coordOrigin, &dwDummy);
6332 vim_free(oldattrs);
6333}
6334
6335
6336/*
6337 * Make the cursor visible or invisible
6338 */
6339 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006340cursor_visible(BOOL fVisible)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006341{
6342 s_cursor_visible = fVisible;
Bram Moolenaar2695de62020-04-17 21:13:01 +02006343
6344 if (USE_VTP)
6345 vtp_printf("\033[?25%c", fVisible ? 'h' : 'l');
6346
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006347# ifdef MCH_CURSOR_SHAPE
Bram Moolenaar071d4272004-06-13 20:20:40 +00006348 mch_update_cursor();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006349# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006350}
6351
6352
6353/*
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02006354 * Write "cbToWrite" bytes in `pchBuf' to the screen.
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006355 * Returns the number of bytes actually written (at least one).
Bram Moolenaar071d4272004-06-13 20:20:40 +00006356 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006357 static DWORD
Bram Moolenaar071d4272004-06-13 20:20:40 +00006358write_chars(
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006359 char_u *pchBuf,
6360 DWORD cbToWrite)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006361{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006362 COORD coord = g_coord;
6363 DWORD written;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006364 DWORD n, cchwritten;
6365 static DWORD cells;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006366 static WCHAR *unicodebuf = NULL;
6367 static int unibuflen = 0;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006368 static int length;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006369 int cp = enc_utf8 ? CP_UTF8 : enc_codepage;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006370 static WCHAR *utf8spbuf = NULL;
6371 static int utf8splength;
6372 static DWORD utf8spcells;
6373 static WCHAR **utf8usingbuf = &unicodebuf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006374
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006375 if (cbToWrite != 1 || *pchBuf != ' ' || !enc_utf8)
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006376 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006377 utf8usingbuf = &unicodebuf;
6378 do
6379 {
6380 length = MultiByteToWideChar(cp, 0, (LPCSTR)pchBuf, cbToWrite,
6381 unicodebuf, unibuflen);
6382 if (length && length <= unibuflen)
6383 break;
6384 vim_free(unicodebuf);
6385 unicodebuf = length ? LALLOC_MULT(WCHAR, length) : NULL;
6386 unibuflen = unibuflen ? 0 : length;
6387 } while(1);
6388 cells = mb_string2cells(pchBuf, cbToWrite);
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006389 }
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006390 else // cbToWrite == 1 && *pchBuf == ' ' && enc_utf8
6391 {
6392 if (utf8usingbuf != &utf8spbuf)
6393 {
6394 if (utf8spbuf == NULL)
6395 {
6396 cells = mb_string2cells((char_u *)" ", 1);
6397 length = MultiByteToWideChar(CP_UTF8, 0, " ", 1, NULL, 0);
6398 utf8spbuf = LALLOC_MULT(WCHAR, length);
6399 if (utf8spbuf != NULL)
6400 {
6401 MultiByteToWideChar(CP_UTF8, 0, " ", 1, utf8spbuf, length);
6402 utf8usingbuf = &utf8spbuf;
6403 utf8splength = length;
6404 utf8spcells = cells;
6405 }
6406 }
6407 else
6408 {
6409 utf8usingbuf = &utf8spbuf;
6410 length = utf8splength;
6411 cells = utf8spcells;
6412 }
6413 }
6414 }
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006415
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006416 if (!USE_VTP)
6417 {
6418 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, cells,
6419 coord, &written);
6420 // When writing fails or didn't write a single character, pretend one
6421 // character was written, otherwise we get stuck.
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006422 if (WriteConsoleOutputCharacterW(g_hConOut, *utf8usingbuf, length,
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006423 coord, &cchwritten) == 0
6424 || cchwritten == 0 || cchwritten == (DWORD)-1)
6425 cchwritten = 1;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006426 }
6427 else
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006428 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006429 if (WriteConsoleW(g_hConOut, *utf8usingbuf, length, &cchwritten,
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006430 NULL) == 0 || cchwritten == 0)
6431 cchwritten = 1;
6432 }
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006433
K.Takata135e1522022-01-29 15:27:58 +00006434 if (cchwritten == (DWORD)length)
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006435 {
6436 written = cbToWrite;
6437 g_coord.X += (SHORT)cells;
6438 }
6439 else
6440 {
6441 char_u *p = pchBuf;
6442 for (n = 0; n < cchwritten; n++)
6443 MB_CPTR_ADV(p);
6444 written = p - pchBuf;
6445 g_coord.X += (SHORT)mb_string2cells(pchBuf, written);
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006446 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006447
6448 while (g_coord.X > g_srScrollRegion.Right)
6449 {
6450 g_coord.X -= (SHORT) Columns;
6451 if (g_coord.Y < g_srScrollRegion.Bottom)
6452 g_coord.Y++;
6453 }
6454
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006455 // Cursor under VTP is always in the correct position, no need to reset.
6456 if (!USE_VTP)
6457 gotoxy(g_coord.X + 1, g_coord.Y + 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006458
6459 return written;
6460}
6461
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006462 static char_u *
6463get_seq(
6464 int *args,
6465 int *count,
6466 char_u *head)
6467{
6468 int argc;
6469 char_u *p;
6470
6471 if (head == NULL || *head != '\033')
6472 return NULL;
6473
6474 argc = 0;
6475 p = head;
6476 ++p;
6477 do
6478 {
6479 ++p;
6480 args[argc] = getdigits(&p);
6481 argc += (argc < 15) ? 1 : 0;
6482 } while (*p == ';');
6483 *count = argc;
6484
6485 return p;
6486}
6487
6488 static char_u *
6489get_sgr(
6490 int *args,
6491 int *count,
6492 char_u *head)
6493{
6494 char_u *p = get_seq(args, count, head);
6495
6496 return (p && *p == 'm') ? ++p : NULL;
6497}
6498
6499/*
6500 * Pointer to next if SGR (^[[n;2;*;*;*m), NULL otherwise.
6501 */
6502 static char_u *
6503sgrn2(
6504 char_u *head,
6505 int n)
6506{
6507 int argc;
6508 int args[16];
6509 char_u *p = get_sgr(args, &argc, head);
6510
6511 return p && argc == 5 && args[0] == n && args[1] == 2 ? p : NULL;
6512}
6513
6514/*
6515 * Pointer to next if SGR(^[[nm)<space>ESC, NULL otherwise.
6516 */
6517 static char_u *
6518sgrnc(
6519 char_u *head,
6520 int n)
6521{
6522 int argc;
6523 int args[16];
6524 char_u *p = get_sgr(args, &argc, head);
6525
6526 return p && argc == 1 && args[0] == n && (p = skipwhite(p)) && *p == '\033'
6527 ? p : NULL;
6528}
6529
6530 static char_u *
6531skipblank(char_u *q)
6532{
6533 char_u *p = q;
6534
6535 while (*p == ' ' || *p == '\t' || *p == '\n' || *p == '\r')
6536 ++p;
6537 return p;
6538}
6539
6540/*
6541 * Pointer to the next if any whitespace that may follow SGR is ESC, otherwise
6542 * NULL.
6543 */
6544 static char_u *
6545sgrn2c(
6546 char_u *head,
6547 int n)
6548{
6549 char_u *p = sgrn2(head, n);
6550
6551 return p && *p != NUL && (p = skipblank(p)) && *p == '\033' ? p : NULL;
6552}
6553
6554/*
6555 * If there is only a newline between the sequence immediately following it,
6556 * a pointer to the character following the newline is returned.
6557 * Otherwise NULL.
6558 */
6559 static char_u *
6560sgrn2cn(
6561 char_u *head,
6562 int n)
6563{
6564 char_u *p = sgrn2(head, n);
6565
6566 return p && p[0] == 0x0a && p[1] == '\033' ? ++p : NULL;
6567}
Bram Moolenaar071d4272004-06-13 20:20:40 +00006568
6569/*
6570 * mch_write(): write the output buffer to the screen, translating ESC
6571 * sequences into calls to console output routines.
6572 */
6573 void
6574mch_write(
6575 char_u *s,
6576 int len)
6577{
Bram Moolenaard23f8bd2021-04-21 11:30:48 +02006578 char_u *end = s + len;
6579
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006580# ifdef VIMDLL
6581 if (gui.in_use)
6582 return;
6583# endif
6584
Bram Moolenaar071d4272004-06-13 20:20:40 +00006585 if (!term_console)
6586 {
6587 write(1, s, (unsigned)len);
6588 return;
6589 }
6590
Bram Moolenaar0f873732019-12-05 20:28:46 +01006591 // translate ESC | sequences into faked bios calls
Bram Moolenaar071d4272004-06-13 20:20:40 +00006592 while (len--)
6593 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006594 int prefix = -1;
6595 char_u ch;
6596
6597 // While processing a sequence, on rare occasions it seems that another
6598 // sequence may be inserted asynchronously.
6599 if (len < 0)
6600 {
Bram Moolenaara4d158b2022-08-14 14:17:45 +01006601 redraw_all_later(UPD_CLEAR);
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006602 return;
6603 }
6604
Bram Moolenaard23f8bd2021-04-21 11:30:48 +02006605 while (s + ++prefix < end)
6606 {
6607 ch = s[prefix];
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006608 if (ch <= 0x1e && !(ch != '\n' && ch != '\r' && ch != '\b'
6609 && ch != '\a' && ch != '\033'))
6610 break;
Bram Moolenaard23f8bd2021-04-21 11:30:48 +02006611 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006612
6613 if (p_wd)
6614 {
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02006615 WaitForChar(p_wd, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006616 if (prefix != 0)
6617 prefix = 1;
6618 }
6619
6620 if (prefix != 0)
6621 {
6622 DWORD nWritten;
6623
6624 nWritten = write_chars(s, prefix);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006625# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006626 if (fdDump)
6627 {
6628 fputc('>', fdDump);
6629 fwrite(s, sizeof(char_u), nWritten, fdDump);
6630 fputs("<\n", fdDump);
6631 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006632# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006633 len -= (nWritten - 1);
6634 s += nWritten;
6635 }
6636 else if (s[0] == '\n')
6637 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006638 // \n, newline: go to the beginning of the next line or scroll
Bram Moolenaar071d4272004-06-13 20:20:40 +00006639 if (g_coord.Y == g_srScrollRegion.Bottom)
6640 {
6641 scroll(1);
6642 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Bottom + 1);
6643 }
6644 else
6645 {
6646 gotoxy(g_srScrollRegion.Left + 1, g_coord.Y + 2);
6647 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006648# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006649 if (fdDump)
6650 fputs("\\n\n", fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006651# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006652 s++;
6653 }
6654 else if (s[0] == '\r')
6655 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006656 // \r, carriage return: go to beginning of line
Bram Moolenaar071d4272004-06-13 20:20:40 +00006657 gotoxy(g_srScrollRegion.Left+1, g_coord.Y + 1);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006658# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006659 if (fdDump)
6660 fputs("\\r\n", fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006661# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006662 s++;
6663 }
6664 else if (s[0] == '\b')
6665 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006666 // \b, backspace: move cursor one position left
Bram Moolenaar071d4272004-06-13 20:20:40 +00006667 if (g_coord.X > g_srScrollRegion.Left)
6668 g_coord.X--;
6669 else if (g_coord.Y > g_srScrollRegion.Top)
6670 {
6671 g_coord.X = g_srScrollRegion.Right;
6672 g_coord.Y--;
6673 }
6674 gotoxy(g_coord.X + 1, g_coord.Y + 1);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006675# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006676 if (fdDump)
6677 fputs("\\b\n", fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006678# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006679 s++;
6680 }
6681 else if (s[0] == '\a')
6682 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006683 // \a, bell
Bram Moolenaar071d4272004-06-13 20:20:40 +00006684 MessageBeep(0xFFFFFFFF);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006685# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006686 if (fdDump)
6687 fputs("\\a\n", fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006688# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006689 s++;
6690 }
6691 else if (s[0] == ESC && len >= 3-1 && s[1] == '|')
6692 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006693# ifdef MCH_WRITE_DUMP
Bram Moolenaarc0197e22004-09-13 20:26:32 +00006694 char_u *old_s = s;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006695# endif
Bram Moolenaarc0197e22004-09-13 20:26:32 +00006696 char_u *p;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006697 int arg1 = 0, arg2 = 0, argc = 0, args[16];
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006698 char_u *sp;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006699
6700 switch (s[2])
6701 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006702 case '0': case '1': case '2': case '3': case '4':
6703 case '5': case '6': case '7': case '8': case '9':
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006704 if (*(p = get_seq(args, &argc, s)) != 'm')
6705 goto notsgr;
6706
6707 p = s;
6708
6709 // Handling frequent optional sequences. Output to the screen
6710 // takes too long, so do not output as much as possible.
6711
6712 // If resetFG,FG,BG,<cr>,BG,FG are connected, the preceding
6713 // resetFG,FG,BG are omitted.
6714 if (sgrn2(sgrn2(sgrn2cn(sgrn2(sgrnc(p, 39), 38), 48), 48), 38))
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006715 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006716 p = sgrn2(sgrn2(sgrnc(p, 39), 38), 48);
6717 len = len + 1 - (int)(p - s);
6718 s = p;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006719 break;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006720 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006721
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006722 // If FG,BG,BG,FG of SGR are connected, the first FG can be
6723 // omitted.
6724 if (sgrn2(sgrn2(sgrn2c((sp = sgrn2(p, 38)), 48), 48), 38))
6725 p = sp;
6726
6727 // If FG,BG,FG,BG of SGR are connected, the first FG can be
6728 // omitted.
6729 if (sgrn2(sgrn2(sgrn2c((sp = sgrn2(p, 38)), 48), 38), 48))
6730 p = sp;
6731
6732 // If BG,BG of SGR are connected, the first BG can be omitted.
6733 if (sgrn2((sp = sgrn2(p, 48)), 48))
6734 p = sp;
6735
6736 // If restoreFG and FG are connected, the restoreFG can be
Bram Moolenaar9f1983d2022-05-12 20:35:35 +01006737 // omitted.
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006738 if (sgrn2((sp = sgrnc(p, 39)), 38))
6739 p = sp;
6740
6741 p = get_seq(args, &argc, p);
6742
6743notsgr:
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006744 arg1 = args[0];
6745 arg2 = args[1];
6746 if (*p == 'm')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006747 {
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006748 if (argc == 1 && args[0] == 0)
6749 normvideo();
6750 else if (argc == 1)
6751 {
6752 if (USE_VTP)
6753 textcolor((WORD) arg1);
6754 else
6755 textattr((WORD) arg1);
6756 }
6757 else if (USE_VTP)
6758 vtp_sgr_bulks(argc, args);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006759 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006760 else if (argc == 2 && *p == 'H')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006761 {
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006762 gotoxy(arg2, arg1);
6763 }
6764 else if (argc == 2 && *p == 'r')
6765 {
6766 set_scroll_region(0, arg1 - 1, Columns - 1, arg2 - 1);
6767 }
Bram Moolenaar6982f422019-02-16 16:48:01 +01006768 else if (argc == 2 && *p == 'R')
6769 {
6770 set_scroll_region_tb(arg1, arg2);
6771 }
6772 else if (argc == 2 && *p == 'V')
6773 {
6774 set_scroll_region_lr(arg1, arg2);
6775 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006776 else if (argc == 1 && *p == 'A')
6777 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006778 gotoxy(g_coord.X + 1,
6779 max(g_srScrollRegion.Top, g_coord.Y - arg1) + 1);
6780 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006781 else if (argc == 1 && *p == 'b')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006782 {
6783 textbackground((WORD) arg1);
6784 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006785 else if (argc == 1 && *p == 'C')
6786 {
6787 gotoxy(min(g_srScrollRegion.Right, g_coord.X + arg1) + 1,
6788 g_coord.Y + 1);
6789 }
6790 else if (argc == 1 && *p == 'f')
6791 {
6792 textcolor((WORD) arg1);
6793 }
6794 else if (argc == 1 && *p == 'H')
6795 {
6796 gotoxy(1, arg1);
6797 }
6798 else if (argc == 1 && *p == 'L')
6799 {
6800 insert_lines(arg1);
6801 }
6802 else if (argc == 1 && *p == 'M')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006803 {
6804 delete_lines(arg1);
6805 }
6806
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006807 len -= (int)(p - s);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006808 s = p + 1;
6809 break;
6810
Bram Moolenaar071d4272004-06-13 20:20:40 +00006811 case 'A':
Bram Moolenaar071d4272004-06-13 20:20:40 +00006812 gotoxy(g_coord.X + 1,
6813 max(g_srScrollRegion.Top, g_coord.Y - 1) + 1);
6814 goto got3;
6815
6816 case 'B':
6817 visual_bell();
6818 goto got3;
6819
6820 case 'C':
Bram Moolenaar071d4272004-06-13 20:20:40 +00006821 gotoxy(min(g_srScrollRegion.Right, g_coord.X + 1) + 1,
6822 g_coord.Y + 1);
6823 goto got3;
6824
6825 case 'E':
6826 termcap_mode_end();
6827 goto got3;
6828
6829 case 'F':
6830 standout();
6831 goto got3;
6832
6833 case 'f':
6834 standend();
6835 goto got3;
6836
6837 case 'H':
6838 gotoxy(1, 1);
6839 goto got3;
6840
6841 case 'j':
6842 clear_to_end_of_display();
6843 goto got3;
6844
6845 case 'J':
6846 clear_screen();
6847 goto got3;
6848
6849 case 'K':
6850 clear_to_end_of_line();
6851 goto got3;
6852
6853 case 'L':
6854 insert_lines(1);
6855 goto got3;
6856
6857 case 'M':
6858 delete_lines(1);
6859 goto got3;
6860
6861 case 'S':
6862 termcap_mode_start();
6863 goto got3;
6864
6865 case 'V':
6866 cursor_visible(TRUE);
6867 goto got3;
6868
6869 case 'v':
6870 cursor_visible(FALSE);
6871 goto got3;
6872
6873 got3:
6874 s += 3;
6875 len -= 2;
6876 }
6877
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006878# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006879 if (fdDump)
6880 {
6881 fputs("ESC | ", fdDump);
6882 fwrite(old_s + 2, sizeof(char_u), s - old_s - 2, fdDump);
6883 fputc('\n', fdDump);
6884 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006885# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006886 }
K.Takatadf5320c2022-09-01 13:20:16 +01006887 else if (s[0] == ESC && len >= 3-1 && s[1] == '[')
6888 {
6889 int l = 2;
6890
6891 if (isdigit(s[l]))
6892 l++;
6893 if (s[l] == ' ' && s[l + 1] == 'q')
6894 {
6895 // DECSCUSR (cursor style) sequences
6896 if (USE_VTP || USE_WT)
6897 vtp_printf("%.*s", l + 2, s); // Pass through
6898 s += l + 2;
6899 len -= l + 1;
6900 }
6901 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006902 else
6903 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006904 // Write a single character
Bram Moolenaar071d4272004-06-13 20:20:40 +00006905 DWORD nWritten;
6906
6907 nWritten = write_chars(s, 1);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006908# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006909 if (fdDump)
6910 {
6911 fputc('>', fdDump);
6912 fwrite(s, sizeof(char_u), nWritten, fdDump);
6913 fputs("<\n", fdDump);
6914 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006915# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006916
6917 len -= (nWritten - 1);
6918 s += nWritten;
6919 }
6920 }
6921
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006922# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006923 if (fdDump)
6924 fflush(fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006925# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006926}
6927
Bram Moolenaar0f873732019-12-05 20:28:46 +01006928#endif // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00006929
6930
6931/*
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01006932 * Delay for "msec" milliseconds.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006933 */
6934 void
6935mch_delay(
6936 long msec,
Bram Moolenaar0981c872020-08-23 14:28:37 +02006937 int flags UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006938{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006939#if defined(FEAT_GUI_MSWIN) && !defined(VIMDLL)
Bram Moolenaar0f873732019-12-05 20:28:46 +01006940 Sleep((int)msec); // never wait for input
6941#else // Console
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006942# ifdef VIMDLL
6943 if (gui.in_use)
6944 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006945 Sleep((int)msec); // never wait for input
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006946 return;
6947 }
6948# endif
Bram Moolenaar0981c872020-08-23 14:28:37 +02006949 if (flags & MCH_DELAY_IGNOREINPUT)
Bram Moolenaar325b7a22004-07-05 15:58:32 +00006950# ifdef FEAT_MZSCHEME
6951 if (mzthreads_allowed() && p_mzq > 0 && msec > p_mzq)
6952 {
6953 int towait = p_mzq;
6954
Bram Moolenaar0f873732019-12-05 20:28:46 +01006955 // if msec is large enough, wait by portions in p_mzq
Bram Moolenaar325b7a22004-07-05 15:58:32 +00006956 while (msec > 0)
6957 {
6958 mzvim_check_threads();
6959 if (msec < towait)
6960 towait = msec;
6961 Sleep(towait);
6962 msec -= towait;
6963 }
6964 }
6965 else
6966# endif
6967 Sleep((int)msec);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006968 else
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02006969 WaitForChar(msec, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006970#endif
6971}
6972
6973
6974/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01006975 * This version of remove is not scared by a readonly (backup) file.
6976 * This can also remove a symbolic link like Unix.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006977 * Return 0 for success, -1 for failure.
6978 */
6979 int
6980mch_remove(char_u *name)
6981{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006982 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006983 int n;
6984
Bram Moolenaar203258c2016-01-17 22:15:16 +01006985 /*
6986 * On Windows, deleting a directory's symbolic link is done by
6987 * RemoveDirectory(): mch_rmdir. It seems unnatural, but it is fact.
6988 */
6989 if (mch_isdir(name) && mch_is_symbolic_link(name))
6990 return mch_rmdir(name);
6991
Bram Moolenaar12b559e2013-06-12 22:41:37 +02006992 win32_setattrs(name, FILE_ATTRIBUTE_NORMAL);
6993
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006994 wn = enc_to_utf16(name, NULL);
6995 if (wn == NULL)
6996 return -1;
6997
6998 n = DeleteFileW(wn) ? 0 : -1;
6999 vim_free(wn);
7000 return n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007001}
7002
7003
7004/*
Bram Moolenaarb9c31e72016-09-29 15:18:57 +02007005 * Check for an "interrupt signal": CTRL-break or CTRL-C.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007006 */
7007 void
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02007008mch_breakcheck(int force UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007009{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007010#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
7011# ifdef VIMDLL
7012 if (!gui.in_use)
7013# endif
7014 if (g_fCtrlCPressed || g_fCBrkPressed)
7015 {
7016 ctrl_break_was_pressed = g_fCBrkPressed;
7017 g_fCtrlCPressed = g_fCBrkPressed = FALSE;
7018 got_int = TRUE;
7019 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007020#endif
7021}
7022
Bram Moolenaar0f873732019-12-05 20:28:46 +01007023// physical RAM to leave for the OS
Bram Moolenaaree273972016-01-02 21:11:51 +01007024#define WINNT_RESERVE_BYTES (256*1024*1024)
Bram Moolenaaree273972016-01-02 21:11:51 +01007025
7026/*
7027 * How much main memory in KiB that can be used by VIM.
7028 */
Bram Moolenaaree273972016-01-02 21:11:51 +01007029 long_u
Bram Moolenaar1266d672017-02-01 13:43:36 +01007030mch_total_mem(int special UNUSED)
Bram Moolenaaree273972016-01-02 21:11:51 +01007031{
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007032 MEMORYSTATUSEX ms;
7033
Bram Moolenaar0f873732019-12-05 20:28:46 +01007034 // Need to use GlobalMemoryStatusEx() when there is more memory than
7035 // what fits in 32 bits.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007036 ms.dwLength = sizeof(MEMORYSTATUSEX);
7037 GlobalMemoryStatusEx(&ms);
7038 if (ms.ullAvailVirtual < ms.ullTotalPhys)
Bram Moolenaaree273972016-01-02 21:11:51 +01007039 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007040 // Process address space fits in physical RAM, use all of it.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007041 return (long_u)(ms.ullAvailVirtual / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01007042 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007043 if (ms.ullTotalPhys <= WINNT_RESERVE_BYTES)
Bram Moolenaaree273972016-01-02 21:11:51 +01007044 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007045 // Catch old NT box or perverse hardware setup.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007046 return (long_u)((ms.ullTotalPhys / 2) / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01007047 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01007048 // Use physical RAM less reserve for OS + data.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007049 return (long_u)((ms.ullTotalPhys - WINNT_RESERVE_BYTES) / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01007050}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007051
Bram Moolenaar071d4272004-06-13 20:20:40 +00007052/*
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007053 * mch_wrename() works around a bug in rename (aka MoveFile) in
Bram Moolenaar071d4272004-06-13 20:20:40 +00007054 * Windows 95: rename("foo.bar", "foo.bar~") will generate a
7055 * file whose short file name is "FOO.BAR" (its long file name will
7056 * be correct: "foo.bar~"). Because a file can be accessed by
7057 * either its SFN or its LFN, "foo.bar" has effectively been
7058 * renamed to "foo.bar", which is not at all what was wanted. This
7059 * seems to happen only when renaming files with three-character
7060 * extensions by appending a suffix that does not include ".".
7061 * Windows NT gets it right, however, with an SFN of "FOO~1.BAR".
7062 *
7063 * There is another problem, which isn't really a bug but isn't right either:
7064 * When renaming "abcdef~1.txt" to "abcdef~1.txt~", the short name can be
7065 * "abcdef~1.txt" again. This has been reported on Windows NT 4.0 with
7066 * service pack 6. Doesn't seem to happen on Windows 98.
7067 *
7068 * Like rename(), returns 0 upon success, non-zero upon failure.
7069 * Should probably set errno appropriately when errors occur.
7070 */
7071 int
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007072mch_wrename(WCHAR *wold, WCHAR *wnew)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007073{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007074 WCHAR *p;
7075 int i;
7076 WCHAR szTempFile[_MAX_PATH + 1];
7077 WCHAR szNewPath[_MAX_PATH + 1];
Bram Moolenaar071d4272004-06-13 20:20:40 +00007078 HANDLE hf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007079
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007080 // No need to play tricks unless the file name contains a "~" as the
7081 // seventh character.
7082 p = wold;
7083 for (i = 0; wold[i] != NUL; ++i)
7084 if ((wold[i] == '/' || wold[i] == '\\' || wold[i] == ':')
7085 && wold[i + 1] != 0)
7086 p = wold + i + 1;
7087 if ((int)(wold + i - p) < 8 || p[6] != '~')
7088 return (MoveFileW(wold, wnew) == 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007089
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007090 // Get base path of new file name. Undocumented feature: If pszNewFile is
7091 // a directory, no error is returned and pszFilePart will be NULL.
7092 if (GetFullPathNameW(wnew, _MAX_PATH, szNewPath, &p) == 0 || p == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007093 return -1;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007094 *p = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007095
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007096 // Get (and create) a unique temporary file name in directory of new file
7097 if (GetTempFileNameW(szNewPath, L"VIM", 0, szTempFile) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007098 return -2;
7099
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007100 // blow the temp file away
7101 if (!DeleteFileW(szTempFile))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007102 return -3;
7103
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007104 // rename old file to the temp file
7105 if (!MoveFileW(wold, szTempFile))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007106 return -4;
7107
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007108 // now create an empty file called pszOldFile; this prevents the operating
7109 // system using pszOldFile as an alias (SFN) if we're renaming within the
7110 // same directory. For example, we're editing a file called
7111 // filename.asc.txt by its SFN, filena~1.txt. If we rename filena~1.txt
7112 // to filena~1.txt~ (i.e., we're making a backup while writing it), the
7113 // SFN for filena~1.txt~ will be filena~1.txt, by default, which will
7114 // cause all sorts of problems later in buf_write(). So, we create an
7115 // empty file called filena~1.txt and the system will have to find some
7116 // other SFN for filena~1.txt~, such as filena~2.txt
7117 if ((hf = CreateFileW(wold, GENERIC_WRITE, 0, NULL, CREATE_NEW,
Bram Moolenaar071d4272004-06-13 20:20:40 +00007118 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
7119 return -5;
7120 if (!CloseHandle(hf))
7121 return -6;
7122
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007123 // rename the temp file to the new file
7124 if (!MoveFileW(szTempFile, wnew))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007125 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007126 // Renaming failed. Rename the file back to its old name, so that it
7127 // looks like nothing happened.
7128 (void)MoveFileW(szTempFile, wold);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007129 return -7;
7130 }
7131
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007132 // Seems to be left around on Novell filesystems
7133 DeleteFileW(szTempFile);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007134
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007135 // finally, remove the empty old file
7136 if (!DeleteFileW(wold))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007137 return -8;
7138
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007139 return 0;
7140}
7141
7142
7143/*
7144 * Converts the filenames to UTF-16, then call mch_wrename().
7145 * Like rename(), returns 0 upon success, non-zero upon failure.
7146 */
7147 int
7148mch_rename(
7149 const char *pszOldFile,
7150 const char *pszNewFile)
7151{
7152 WCHAR *wold = NULL;
7153 WCHAR *wnew = NULL;
7154 int retval = -1;
7155
7156 wold = enc_to_utf16((char_u *)pszOldFile, NULL);
7157 wnew = enc_to_utf16((char_u *)pszNewFile, NULL);
7158 if (wold != NULL && wnew != NULL)
7159 retval = mch_wrename(wold, wnew);
7160 vim_free(wold);
7161 vim_free(wnew);
7162 return retval;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007163}
7164
7165/*
7166 * Get the default shell for the current hardware platform
7167 */
7168 char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007169default_shell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007170{
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007171 return "cmd.exe";
Bram Moolenaar071d4272004-06-13 20:20:40 +00007172}
7173
7174/*
7175 * mch_access() extends access() to do more detailed check on network drives.
7176 * Returns 0 if file "n" has access rights according to "p", -1 otherwise.
7177 */
7178 int
7179mch_access(char *n, int p)
7180{
7181 HANDLE hFile;
Bram Moolenaar0f873732019-12-05 20:28:46 +01007182 int retval = -1; // default: fail
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007183 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007184
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007185 wn = enc_to_utf16((char_u *)n, NULL);
7186 if (wn == NULL)
7187 return -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007188
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01007189 if (mch_isdir((char_u *)n))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007190 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00007191 WCHAR TempNameW[_MAX_PATH + 16] = L"";
Bram Moolenaar071d4272004-06-13 20:20:40 +00007192
7193 if (p & R_OK)
7194 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007195 // Read check is performed by seeing if we can do a find file on
7196 // the directory for any file.
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007197 int i;
7198 WIN32_FIND_DATAW d;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007199
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007200 for (i = 0; i < _MAX_PATH && wn[i] != 0; ++i)
7201 TempNameW[i] = wn[i];
7202 if (TempNameW[i - 1] != '\\' && TempNameW[i - 1] != '/')
7203 TempNameW[i++] = '\\';
7204 TempNameW[i++] = '*';
7205 TempNameW[i++] = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007206
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007207 hFile = FindFirstFileW(TempNameW, &d);
7208 if (hFile == INVALID_HANDLE_VALUE)
7209 goto getout;
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007210 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00007211 (void)FindClose(hFile);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007212 }
7213
7214 if (p & W_OK)
7215 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007216 // Trying to create a temporary file in the directory should catch
7217 // directories on read-only network shares. However, in
7218 // directories whose ACL allows writes but denies deletes will end
7219 // up keeping the temporary file :-(.
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007220 if (!GetTempFileNameW(wn, L"VIM", 0, TempNameW))
7221 goto getout;
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007222 else
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007223 DeleteFileW(TempNameW);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007224 }
7225 }
7226 else
7227 {
Bram Moolenaar5aa98962018-05-06 17:09:38 +02007228 // Don't consider a file read-only if another process has opened it.
7229 DWORD share_mode = FILE_SHARE_READ | FILE_SHARE_WRITE;
7230
Bram Moolenaar0f873732019-12-05 20:28:46 +01007231 // Trying to open the file for the required access does ACL, read-only
7232 // network share, and file attribute checks.
Bram Moolenaar5aa98962018-05-06 17:09:38 +02007233 DWORD access_mode = ((p & W_OK) ? GENERIC_WRITE : 0)
7234 | ((p & R_OK) ? GENERIC_READ : 0);
7235
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007236 hFile = CreateFileW(wn, access_mode, share_mode,
7237 NULL, OPEN_EXISTING, 0, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007238 if (hFile == INVALID_HANDLE_VALUE)
7239 goto getout;
7240 CloseHandle(hFile);
7241 }
7242
Bram Moolenaar0f873732019-12-05 20:28:46 +01007243 retval = 0; // success
Bram Moolenaar071d4272004-06-13 20:20:40 +00007244getout:
Bram Moolenaar071d4272004-06-13 20:20:40 +00007245 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007246 return retval;
7247}
7248
Bram Moolenaar071d4272004-06-13 20:20:40 +00007249/*
Bram Moolenaar36f692d2008-11-20 16:10:17 +00007250 * Version of open() that may use UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007251 */
7252 int
Bram Moolenaarb6843a02017-08-02 22:07:12 +02007253mch_open(const char *name, int flags, int mode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007254{
7255 WCHAR *wn;
7256 int f;
7257
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007258 wn = enc_to_utf16((char_u *)name, NULL);
7259 if (wn == NULL)
7260 return -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007261
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007262 f = _wopen(wn, flags, mode);
7263 vim_free(wn);
7264 return f;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007265}
7266
7267/*
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007268 * Version of fopen() that uses UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007269 */
7270 FILE *
Bram Moolenaarb6843a02017-08-02 22:07:12 +02007271mch_fopen(const char *name, const char *mode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007272{
7273 WCHAR *wn, *wm;
7274 FILE *f = NULL;
7275
Bram Moolenaara12a1612019-01-24 16:39:02 +01007276#if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0f873732019-12-05 20:28:46 +01007277 // Work around an annoying assertion in the Microsoft debug CRT
7278 // when mode's text/binary setting doesn't match _get_fmode().
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007279 char newMode = mode[strlen(mode) - 1];
7280 int oldMode = 0;
Bram Moolenaar0fde2902008-03-16 13:54:13 +00007281
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007282 _get_fmode(&oldMode);
7283 if (newMode == 't')
7284 _set_fmode(_O_TEXT);
7285 else if (newMode == 'b')
7286 _set_fmode(_O_BINARY);
Bram Moolenaara12a1612019-01-24 16:39:02 +01007287#endif
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007288 wn = enc_to_utf16((char_u *)name, NULL);
7289 wm = enc_to_utf16((char_u *)mode, NULL);
7290 if (wn != NULL && wm != NULL)
7291 f = _wfopen(wn, wm);
7292 vim_free(wn);
7293 vim_free(wm);
Bram Moolenaar0fde2902008-03-16 13:54:13 +00007294
Bram Moolenaara12a1612019-01-24 16:39:02 +01007295#if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007296 _set_fmode(oldMode);
Bram Moolenaara12a1612019-01-24 16:39:02 +01007297#endif
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007298 return f;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007299}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007300
Bram Moolenaar071d4272004-06-13 20:20:40 +00007301/*
7302 * SUB STREAM (aka info stream) handling:
7303 *
Bram Moolenaar8e7d6222020-12-18 19:49:56 +01007304 * NTFS can have sub streams for each file. The normal contents of a file is
7305 * stored in the main stream, and extra contents (author information, title and
7306 * so on) can be stored in a sub stream. After Windows 2000, the user can
7307 * access and store this information in sub streams via an explorer's property
7308 * menu item in the right click menu. This information in sub streams was lost
7309 * when copying only the main stream. Therefore we have to copy sub streams.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007310 *
7311 * Incomplete explanation:
7312 * http://msdn.microsoft.com/library/en-us/dnw2k/html/ntfs5.asp
7313 * More useful info and an example:
7314 * http://www.sysinternals.com/ntw2k/source/misc.shtml#streams
7315 */
7316
7317/*
7318 * Copy info stream data "substream". Read from the file with BackupRead(sh)
7319 * and write to stream "substream" of file "to".
7320 * Errors are ignored.
7321 */
7322 static void
7323copy_substream(HANDLE sh, void *context, WCHAR *to, WCHAR *substream, long len)
7324{
7325 HANDLE hTo;
7326 WCHAR *to_name;
7327
7328 to_name = malloc((wcslen(to) + wcslen(substream) + 1) * sizeof(WCHAR));
7329 wcscpy(to_name, to);
7330 wcscat(to_name, substream);
7331
7332 hTo = CreateFileW(to_name, GENERIC_WRITE, 0, NULL, OPEN_ALWAYS,
7333 FILE_ATTRIBUTE_NORMAL, NULL);
7334 if (hTo != INVALID_HANDLE_VALUE)
7335 {
7336 long done;
7337 DWORD todo;
7338 DWORD readcnt, written;
7339 char buf[4096];
7340
Bram Moolenaar0f873732019-12-05 20:28:46 +01007341 // Copy block of bytes at a time. Abort when something goes wrong.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007342 for (done = 0; done < len; done += written)
7343 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007344 // (size_t) cast for Borland C 5.5
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007345 todo = (DWORD)((size_t)(len - done) > sizeof(buf) ? sizeof(buf)
7346 : (size_t)(len - done));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007347 if (!BackupRead(sh, (LPBYTE)buf, todo, &readcnt,
7348 FALSE, FALSE, context)
7349 || readcnt != todo
7350 || !WriteFile(hTo, buf, todo, &written, NULL)
7351 || written != todo)
7352 break;
7353 }
7354 CloseHandle(hTo);
7355 }
7356
7357 free(to_name);
7358}
7359
7360/*
7361 * Copy info streams from file "from" to file "to".
7362 */
7363 static void
7364copy_infostreams(char_u *from, char_u *to)
7365{
7366 WCHAR *fromw;
7367 WCHAR *tow;
7368 HANDLE sh;
7369 WIN32_STREAM_ID sid;
7370 int headersize;
7371 WCHAR streamname[_MAX_PATH];
7372 DWORD readcount;
7373 void *context = NULL;
7374 DWORD lo, hi;
7375 int len;
7376
Bram Moolenaar0f873732019-12-05 20:28:46 +01007377 // Convert the file names to wide characters.
Bram Moolenaar36f692d2008-11-20 16:10:17 +00007378 fromw = enc_to_utf16(from, NULL);
7379 tow = enc_to_utf16(to, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007380 if (fromw != NULL && tow != NULL)
7381 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007382 // Open the file for reading.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007383 sh = CreateFileW(fromw, GENERIC_READ, FILE_SHARE_READ, NULL,
7384 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
7385 if (sh != INVALID_HANDLE_VALUE)
7386 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007387 // Use BackupRead() to find the info streams. Repeat until we
7388 // have done them all.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007389 for (;;)
7390 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007391 // Get the header to find the length of the stream name. If
7392 // the "readcount" is zero we have done all info streams.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007393 ZeroMemory(&sid, sizeof(WIN32_STREAM_ID));
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007394 headersize = (int)((char *)&sid.cStreamName - (char *)&sid.dwStreamId);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007395 if (!BackupRead(sh, (LPBYTE)&sid, headersize,
7396 &readcount, FALSE, FALSE, &context)
7397 || readcount == 0)
7398 break;
7399
Bram Moolenaar0f873732019-12-05 20:28:46 +01007400 // We only deal with streams that have a name. The normal
7401 // file data appears to be without a name, even though docs
7402 // suggest it is called "::$DATA".
Bram Moolenaar071d4272004-06-13 20:20:40 +00007403 if (sid.dwStreamNameSize > 0)
7404 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007405 // Read the stream name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007406 if (!BackupRead(sh, (LPBYTE)streamname,
7407 sid.dwStreamNameSize,
7408 &readcount, FALSE, FALSE, &context))
7409 break;
7410
Bram Moolenaar0f873732019-12-05 20:28:46 +01007411 // Copy an info stream with a name ":anything:$DATA".
7412 // Skip "::$DATA", it has no stream name (examples suggest
7413 // it might be used for the normal file contents).
7414 // Note that BackupRead() counts bytes, but the name is in
7415 // wide characters.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007416 len = readcount / sizeof(WCHAR);
7417 streamname[len] = 0;
7418 if (len > 7 && wcsicmp(streamname + len - 6,
7419 L":$DATA") == 0)
7420 {
7421 streamname[len - 6] = 0;
7422 copy_substream(sh, &context, tow, streamname,
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00007423 (long)sid.Size.u.LowPart);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007424 }
7425 }
7426
Bram Moolenaar0f873732019-12-05 20:28:46 +01007427 // Advance to the next stream. We might try seeking too far,
7428 // but BackupSeek() doesn't skip over stream borders, thus
7429 // that's OK.
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00007430 (void)BackupSeek(sh, sid.Size.u.LowPart, sid.Size.u.HighPart,
Bram Moolenaar071d4272004-06-13 20:20:40 +00007431 &lo, &hi, &context);
7432 }
7433
Bram Moolenaar0f873732019-12-05 20:28:46 +01007434 // Clear the context.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007435 (void)BackupRead(sh, NULL, 0, &readcount, TRUE, FALSE, &context);
7436
7437 CloseHandle(sh);
7438 }
7439 }
7440 vim_free(fromw);
7441 vim_free(tow);
7442}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007443
7444/*
Bram Moolenaare7bebc42021-02-01 20:50:37 +01007445 * ntdll.dll definitions
7446 */
7447#define FileEaInformation 7
7448#ifndef STATUS_SUCCESS
7449# define STATUS_SUCCESS ((NTSTATUS) 0x00000000L)
7450#endif
7451
7452typedef struct _FILE_FULL_EA_INFORMATION_ {
7453 ULONG NextEntryOffset;
7454 UCHAR Flags;
7455 UCHAR EaNameLength;
7456 USHORT EaValueLength;
7457 CHAR EaName[1];
7458} FILE_FULL_EA_INFORMATION_, *PFILE_FULL_EA_INFORMATION_;
7459
7460typedef struct _FILE_EA_INFORMATION_ {
7461 ULONG EaSize;
7462} FILE_EA_INFORMATION_, *PFILE_EA_INFORMATION_;
7463
Paul Ollis65745772022-06-05 16:55:54 +01007464#ifndef PROTO
Bram Moolenaare7bebc42021-02-01 20:50:37 +01007465typedef NTSTATUS (NTAPI *PfnNtOpenFile)(
7466 PHANDLE FileHandle,
7467 ACCESS_MASK DesiredAccess,
7468 POBJECT_ATTRIBUTES ObjectAttributes,
7469 PIO_STATUS_BLOCK IoStatusBlock,
7470 ULONG ShareAccess,
7471 ULONG OpenOptions);
7472typedef NTSTATUS (NTAPI *PfnNtClose)(
7473 HANDLE Handle);
7474typedef NTSTATUS (NTAPI *PfnNtSetEaFile)(
Bram Moolenaar9f1983d2022-05-12 20:35:35 +01007475 HANDLE FileHandle,
7476 PIO_STATUS_BLOCK IoStatusBlock,
7477 PVOID Buffer,
7478 ULONG Length);
Bram Moolenaare7bebc42021-02-01 20:50:37 +01007479typedef NTSTATUS (NTAPI *PfnNtQueryEaFile)(
7480 HANDLE FileHandle,
7481 PIO_STATUS_BLOCK IoStatusBlock,
7482 PVOID Buffer,
7483 ULONG Length,
7484 BOOLEAN ReturnSingleEntry,
7485 PVOID EaList,
7486 ULONG EaListLength,
7487 PULONG EaIndex,
7488 BOOLEAN RestartScan);
7489typedef NTSTATUS (NTAPI *PfnNtQueryInformationFile)(
Bram Moolenaar9f1983d2022-05-12 20:35:35 +01007490 HANDLE FileHandle,
7491 PIO_STATUS_BLOCK IoStatusBlock,
7492 PVOID FileInformation,
7493 ULONG Length,
Bram Moolenaare7bebc42021-02-01 20:50:37 +01007494 FILE_INFORMATION_CLASS FileInformationClass);
7495typedef VOID (NTAPI *PfnRtlInitUnicodeString)(
7496 PUNICODE_STRING DestinationString,
7497 PCWSTR SourceString);
7498
7499PfnNtOpenFile pNtOpenFile = NULL;
7500PfnNtClose pNtClose = NULL;
7501PfnNtSetEaFile pNtSetEaFile = NULL;
7502PfnNtQueryEaFile pNtQueryEaFile = NULL;
7503PfnNtQueryInformationFile pNtQueryInformationFile = NULL;
7504PfnRtlInitUnicodeString pRtlInitUnicodeString = NULL;
Paul Ollis65745772022-06-05 16:55:54 +01007505#endif
Bram Moolenaare7bebc42021-02-01 20:50:37 +01007506
7507/*
7508 * Load ntdll.dll functions.
7509 */
7510 static BOOL
7511load_ntdll(void)
7512{
7513 static int loaded = -1;
7514
7515 if (loaded == -1)
7516 {
7517 HMODULE hNtdll = GetModuleHandle("ntdll.dll");
7518 if (hNtdll != NULL)
7519 {
7520 pNtOpenFile = (PfnNtOpenFile) GetProcAddress(hNtdll, "NtOpenFile");
7521 pNtClose = (PfnNtClose) GetProcAddress(hNtdll, "NtClose");
7522 pNtSetEaFile = (PfnNtSetEaFile)
7523 GetProcAddress(hNtdll, "NtSetEaFile");
7524 pNtQueryEaFile = (PfnNtQueryEaFile)
7525 GetProcAddress(hNtdll, "NtQueryEaFile");
7526 pNtQueryInformationFile = (PfnNtQueryInformationFile)
7527 GetProcAddress(hNtdll, "NtQueryInformationFile");
7528 pRtlInitUnicodeString = (PfnRtlInitUnicodeString)
7529 GetProcAddress(hNtdll, "RtlInitUnicodeString");
7530 }
7531 if (pNtOpenFile == NULL
7532 || pNtClose == NULL
7533 || pNtSetEaFile == NULL
7534 || pNtQueryEaFile == NULL
7535 || pNtQueryInformationFile == NULL
7536 || pRtlInitUnicodeString == NULL)
7537 loaded = FALSE;
7538 else
7539 loaded = TRUE;
7540 }
7541 return (BOOL) loaded;
7542}
7543
7544/*
7545 * Copy extended attributes (EA) from file "from" to file "to".
7546 */
7547 static void
7548copy_extattr(char_u *from, char_u *to)
7549{
7550 char_u *fromf = NULL;
7551 char_u *tof = NULL;
7552 WCHAR *fromw = NULL;
7553 WCHAR *tow = NULL;
7554 UNICODE_STRING u;
7555 HANDLE h;
7556 OBJECT_ATTRIBUTES oa;
7557 IO_STATUS_BLOCK iosb;
7558 FILE_EA_INFORMATION_ eainfo = {0};
7559 void *ea = NULL;
7560
7561 if (!load_ntdll())
7562 return;
7563
7564 // Convert the file names to the fully qualified object names.
7565 fromf = alloc(STRLEN(from) + 5);
7566 tof = alloc(STRLEN(to) + 5);
7567 if (fromf == NULL || tof == NULL)
7568 goto theend;
7569 STRCPY(fromf, "\\??\\");
7570 STRCAT(fromf, from);
7571 STRCPY(tof, "\\??\\");
7572 STRCAT(tof, to);
7573
7574 // Convert the names to wide characters.
7575 fromw = enc_to_utf16(fromf, NULL);
7576 tow = enc_to_utf16(tof, NULL);
7577 if (fromw == NULL || tow == NULL)
7578 goto theend;
7579
7580 // Get the EA.
7581 pRtlInitUnicodeString(&u, fromw);
7582 InitializeObjectAttributes(&oa, &u, 0, NULL, NULL);
7583 if (pNtOpenFile(&h, FILE_READ_EA, &oa, &iosb, 0,
7584 FILE_NON_DIRECTORY_FILE) != STATUS_SUCCESS)
7585 goto theend;
7586 pNtQueryInformationFile(h, &iosb, &eainfo, sizeof(eainfo),
7587 FileEaInformation);
7588 if (eainfo.EaSize != 0)
7589 {
7590 ea = alloc(eainfo.EaSize);
7591 if (ea != NULL)
7592 {
7593 if (pNtQueryEaFile(h, &iosb, ea, eainfo.EaSize, FALSE,
7594 NULL, 0, NULL, TRUE) != STATUS_SUCCESS)
7595 {
7596 vim_free(ea);
7597 ea = NULL;
7598 }
7599 }
7600 }
7601 pNtClose(h);
7602
7603 // Set the EA.
7604 if (ea != NULL)
7605 {
7606 pRtlInitUnicodeString(&u, tow);
7607 InitializeObjectAttributes(&oa, &u, 0, NULL, NULL);
7608 if (pNtOpenFile(&h, FILE_WRITE_EA, &oa, &iosb, 0,
7609 FILE_NON_DIRECTORY_FILE) != STATUS_SUCCESS)
7610 goto theend;
7611
7612 pNtSetEaFile(h, &iosb, ea, eainfo.EaSize);
7613 pNtClose(h);
7614 }
7615
7616theend:
7617 vim_free(fromf);
7618 vim_free(tof);
7619 vim_free(fromw);
7620 vim_free(tow);
7621 vim_free(ea);
7622}
7623
7624/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00007625 * Copy file attributes from file "from" to file "to".
7626 * For Windows NT and later we copy info streams.
7627 * Always returns zero, errors are ignored.
7628 */
7629 int
7630mch_copy_file_attribute(char_u *from, char_u *to)
7631{
Bram Moolenaar0f873732019-12-05 20:28:46 +01007632 // File streams only work on Windows NT and later.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007633 copy_infostreams(from, to);
Bram Moolenaare7bebc42021-02-01 20:50:37 +01007634 copy_extattr(from, to);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007635 return 0;
7636}
7637
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007638
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007639/*
K.Takatadc73b4b2021-06-08 18:32:36 +02007640 * The command line arguments in UTF-16
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007641 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00007642static int nArgsW = 0;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007643static LPWSTR *ArglistW = NULL;
7644static int global_argc = 0;
7645static char **global_argv;
7646
Bram Moolenaar0f873732019-12-05 20:28:46 +01007647static int used_file_argc = 0; // last argument in global_argv[] used
7648 // for the argument list.
7649static int *used_file_indexes = NULL; // indexes in global_argv[] for
7650 // command line arguments added to
7651 // the argument list
7652static int used_file_count = 0; // nr of entries in used_file_indexes
7653static int used_file_literal = FALSE; // take file names literally
7654static int used_file_full_path = FALSE; // file name was full path
7655static int used_file_diff_mode = FALSE; // file name was with diff mode
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007656static int used_alist_count = 0;
7657
7658
7659/*
7660 * Get the command line arguments. Unicode version.
7661 * Returns argc. Zero when something fails.
7662 */
7663 int
7664get_cmd_argsW(char ***argvp)
7665{
7666 char **argv = NULL;
7667 int argc = 0;
7668 int i;
7669
Bram Moolenaar14993322014-09-09 12:25:33 +02007670 free_cmd_argsW();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007671 ArglistW = CommandLineToArgvW(GetCommandLineW(), &nArgsW);
7672 if (ArglistW != NULL)
7673 {
7674 argv = malloc((nArgsW + 1) * sizeof(char *));
7675 if (argv != NULL)
7676 {
7677 argc = nArgsW;
7678 argv[argc] = NULL;
7679 for (i = 0; i < argc; ++i)
7680 {
7681 int len;
7682
K.Takatadc73b4b2021-06-08 18:32:36 +02007683 // Convert each Unicode argument to UTF-8.
7684 WideCharToMultiByte_alloc(CP_UTF8, 0,
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007685 ArglistW[i], (int)wcslen(ArglistW[i]) + 1,
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007686 (LPSTR *)&argv[i], &len, 0, 0);
7687 if (argv[i] == NULL)
7688 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007689 // Out of memory, clear everything.
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007690 while (i > 0)
7691 free(argv[--i]);
7692 free(argv);
Bram Moolenaar73c61632013-12-07 14:48:10 +01007693 argv = NULL;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007694 argc = 0;
7695 }
7696 }
7697 }
7698 }
7699
7700 global_argc = argc;
7701 global_argv = argv;
7702 if (argc > 0)
Bram Moolenaar14993322014-09-09 12:25:33 +02007703 {
7704 if (used_file_indexes != NULL)
7705 free(used_file_indexes);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007706 used_file_indexes = malloc(argc * sizeof(int));
Bram Moolenaar14993322014-09-09 12:25:33 +02007707 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007708
7709 if (argvp != NULL)
7710 *argvp = argv;
7711 return argc;
7712}
7713
7714 void
7715free_cmd_argsW(void)
7716{
7717 if (ArglistW != NULL)
7718 {
7719 GlobalFree(ArglistW);
7720 ArglistW = NULL;
7721 }
7722}
7723
7724/*
7725 * Remember "name" is an argument that was added to the argument list.
7726 * This avoids that we have to re-parse the argument list when fix_arg_enc()
7727 * is called.
7728 */
7729 void
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007730used_file_arg(char *name, int literal, int full_path, int diff_mode)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007731{
7732 int i;
7733
7734 if (used_file_indexes == NULL)
7735 return;
7736 for (i = used_file_argc + 1; i < global_argc; ++i)
7737 if (STRCMP(global_argv[i], name) == 0)
7738 {
7739 used_file_argc = i;
7740 used_file_indexes[used_file_count++] = i;
7741 break;
7742 }
7743 used_file_literal = literal;
7744 used_file_full_path = full_path;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007745 used_file_diff_mode = diff_mode;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007746}
7747
7748/*
7749 * Remember the length of the argument list as it was. If it changes then we
7750 * leave it alone when 'encoding' is set.
7751 */
7752 void
7753set_alist_count(void)
7754{
7755 used_alist_count = GARGCOUNT;
7756}
7757
7758/*
7759 * Fix the encoding of the command line arguments. Invoked when 'encoding'
K.Takatadc73b4b2021-06-08 18:32:36 +02007760 * has been changed while starting up. Use the UTF-16 command line arguments
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007761 * and convert them to 'encoding'.
7762 */
7763 void
7764fix_arg_enc(void)
7765{
7766 int i;
7767 int idx;
7768 char_u *str;
Bram Moolenaar86b68352004-12-27 21:59:20 +00007769 int *fnum_list;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007770
Bram Moolenaar0f873732019-12-05 20:28:46 +01007771 // Safety checks:
7772 // - if argument count differs between the wide and non-wide argument
7773 // list, something must be wrong.
7774 // - the file name arguments must have been located.
7775 // - the length of the argument list wasn't changed by the user.
Bram Moolenaard857f0e2005-06-21 22:37:39 +00007776 if (global_argc != nArgsW
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007777 || ArglistW == NULL
7778 || used_file_indexes == NULL
7779 || used_file_count == 0
7780 || used_alist_count != GARGCOUNT)
7781 return;
7782
Bram Moolenaar0f873732019-12-05 20:28:46 +01007783 // Remember the buffer numbers for the arguments.
Bram Moolenaarc799fe22019-05-28 23:08:19 +02007784 fnum_list = ALLOC_MULT(int, GARGCOUNT);
Bram Moolenaar86b68352004-12-27 21:59:20 +00007785 if (fnum_list == NULL)
Bram Moolenaar0f873732019-12-05 20:28:46 +01007786 return; // out of memory
Bram Moolenaar86b68352004-12-27 21:59:20 +00007787 for (i = 0; i < GARGCOUNT; ++i)
7788 fnum_list[i] = GARGLIST[i].ae_fnum;
7789
Bram Moolenaar0f873732019-12-05 20:28:46 +01007790 // Clear the argument list. Make room for the new arguments.
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007791 alist_clear(&global_alist);
7792 if (ga_grow(&global_alist.al_ga, used_file_count) == FAIL)
Bram Moolenaar0f873732019-12-05 20:28:46 +01007793 return; // out of memory
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007794
7795 for (i = 0; i < used_file_count; ++i)
7796 {
7797 idx = used_file_indexes[i];
Bram Moolenaar36f692d2008-11-20 16:10:17 +00007798 str = utf16_to_enc(ArglistW[idx], NULL);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007799 if (str != NULL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00007800 {
Bram Moolenaar39d21e32017-08-05 23:09:31 +02007801 int literal = used_file_literal;
7802
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007803#ifdef FEAT_DIFF
Bram Moolenaar0f873732019-12-05 20:28:46 +01007804 // When using diff mode may need to concatenate file name to
7805 // directory name. Just like it's done in main().
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007806 if (used_file_diff_mode && mch_isdir(str) && GARGCOUNT > 0
7807 && !mch_isdir(alist_name(&GARGLIST[0])))
7808 {
7809 char_u *r;
7810
7811 r = concat_fnames(str, gettail(alist_name(&GARGLIST[0])), TRUE);
7812 if (r != NULL)
7813 {
7814 vim_free(str);
7815 str = r;
7816 }
7817 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007818#endif
Bram Moolenaar0f873732019-12-05 20:28:46 +01007819 // Re-use the old buffer by renaming it. When not using literal
7820 // names it's done by alist_expand() below.
Bram Moolenaar86b68352004-12-27 21:59:20 +00007821 if (used_file_literal)
7822 buf_set_name(fnum_list[i], str);
7823
Bram Moolenaar0f873732019-12-05 20:28:46 +01007824 // Check backtick literal. backtick literal is already expanded in
7825 // main.c, so this part add str as literal.
Bram Moolenaar39d21e32017-08-05 23:09:31 +02007826 if (literal == FALSE)
7827 {
Bram Moolenaar116a0f82017-08-07 21:17:57 +02007828 size_t len = STRLEN(str);
7829
Bram Moolenaar39d21e32017-08-05 23:09:31 +02007830 if (len > 2 && *str == '`' && *(str + len - 1) == '`')
7831 literal = TRUE;
7832 }
7833 alist_add(&global_alist, str, literal ? 2 : 0);
Bram Moolenaar86b68352004-12-27 21:59:20 +00007834 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007835 }
7836
7837 if (!used_file_literal)
7838 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007839 // Now expand wildcards in the arguments.
7840 // Temporarily add '(' and ')' to 'isfname'. These are valid
7841 // filename characters but are excluded from 'isfname' to make
Dominique Pelleaf4a61a2021-12-27 17:21:41 +00007842 // "gf" work on a file name in parentheses (e.g.: see vim.h).
Bram Moolenaar0f873732019-12-05 20:28:46 +01007843 // Also, unset wildignore to not be influenced by this option.
7844 // The arguments specified in command-line should be kept even if
7845 // encoding options were changed.
Christian Brabandtfd916d62021-11-01 22:44:33 +00007846 // Use :legacy so that it also works when in Vim9 script.
7847 do_cmdline_cmd((char_u *)":legacy let g:SaVe_ISF = &isf|set isf+=(,)");
7848 do_cmdline_cmd((char_u *)":legacy let g:SaVe_WIG = &wig|set wig=");
Bram Moolenaar86b68352004-12-27 21:59:20 +00007849 alist_expand(fnum_list, used_alist_count);
Christian Brabandtfd916d62021-11-01 22:44:33 +00007850 do_cmdline_cmd(
7851 (char_u *)":legacy let &isf = g:SaVe_ISF|unlet g:SaVe_ISF");
7852 do_cmdline_cmd(
7853 (char_u *)":legacy let &wig = g:SaVe_WIG|unlet g:SaVe_WIG");
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007854 }
7855
Bram Moolenaar0f873732019-12-05 20:28:46 +01007856 // If wildcard expansion failed, we are editing the first file of the
7857 // arglist and there is no file name: Edit the first argument now.
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007858 if (curwin->w_arg_idx == 0 && curbuf->b_fname == NULL)
7859 {
7860 do_cmdline_cmd((char_u *)":rewind");
Bram Moolenaar05268152021-11-18 18:53:45 +00007861 if (GARGCOUNT == 1 && used_file_full_path
7862 && vim_chdirfile(alist_name(&GARGLIST[0]), "drop") == OK)
7863 last_chdir_reason = "drop";
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007864 }
Bram Moolenaar86b68352004-12-27 21:59:20 +00007865
7866 set_alist_count();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007867}
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007868
7869 int
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02007870mch_setenv(char *var, char *value, int x UNUSED)
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007871{
7872 char_u *envbuf;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007873 WCHAR *p;
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007874
Bram Moolenaar964b3742019-05-24 18:54:09 +02007875 envbuf = alloc(STRLEN(var) + STRLEN(value) + 2);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007876 if (envbuf == NULL)
7877 return -1;
7878
7879 sprintf((char *)envbuf, "%s=%s", var, value);
7880
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007881 p = enc_to_utf16(envbuf, NULL);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007882
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007883 vim_free(envbuf);
7884 if (p == NULL)
7885 return -1;
7886 _wputenv(p);
Bram Moolenaara12a1612019-01-24 16:39:02 +01007887#ifdef libintl_wputenv
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007888 libintl_wputenv(p);
Bram Moolenaara12a1612019-01-24 16:39:02 +01007889#endif
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007890 // Unlike Un*x systems, we can free the string for _wputenv().
7891 vim_free(p);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007892
7893 return 0;
7894}
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007895
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007896/*
7897 * Support for 256 colors and 24-bit colors was added in Windows 10
7898 * version 1703 (Creators update).
7899 */
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007900#define VTP_FIRST_SUPPORT_BUILD MAKE_VER(10, 0, 15063)
7901
7902/*
7903 * Support for pseudo-console (ConPTY) was added in windows 10
Bram Moolenaar57da6982019-09-13 22:30:11 +02007904 * version 1809 (October 2018 update).
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007905 */
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01007906#define CONPTY_FIRST_SUPPORT_BUILD MAKE_VER(10, 0, 17763)
Bram Moolenaar57da6982019-09-13 22:30:11 +02007907
7908/*
7909 * ConPTY differences between versions, need different logic.
7910 * version 1903 (May 2019 update).
7911 */
7912#define CONPTY_1903_BUILD MAKE_VER(10, 0, 18362)
7913
7914/*
Bram Moolenaar36e7a822019-11-13 21:49:24 +01007915 * version 1909 (November 2019 update).
7916 */
7917#define CONPTY_1909_BUILD MAKE_VER(10, 0, 18363)
7918
7919/*
Bram Moolenaar7ed8f592020-04-28 20:44:42 +02007920 * Stay ahead of the next update, and when it's done, fix this.
7921 * version ? (2020 update, temporarily use the build number of insider preview)
7922 */
7923#define CONPTY_NEXT_UPDATE_BUILD MAKE_VER(10, 0, 19587)
7924
7925/*
Bram Moolenaar57da6982019-09-13 22:30:11 +02007926 * Confirm until this version. Also the logic changes.
7927 * insider preview.
7928 */
Bram Moolenaar4c063dd2019-10-04 21:29:12 +02007929#define CONPTY_INSIDER_BUILD MAKE_VER(10, 0, 18995)
Bram Moolenaar57da6982019-09-13 22:30:11 +02007930
7931/*
7932 * Not stable now.
7933 */
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01007934#define CONPTY_STABLE_BUILD MAKE_VER(10, 0, 32767) // T.B.D.
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007935
7936 static void
7937vtp_flag_init(void)
7938{
7939 DWORD ver = get_build_number();
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007940#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007941 DWORD mode;
7942 HANDLE out;
7943
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007944# ifdef VIMDLL
7945 if (!gui.in_use)
7946# endif
7947 {
7948 out = GetStdHandle(STD_OUTPUT_HANDLE);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007949
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007950 vtp_working = (ver >= VTP_FIRST_SUPPORT_BUILD) ? 1 : 0;
7951 GetConsoleMode(out, &mode);
7952 mode |= (ENABLE_PROCESSED_OUTPUT | ENABLE_VIRTUAL_TERMINAL_PROCESSING);
7953 if (SetConsoleMode(out, mode) == 0)
7954 vtp_working = 0;
7955 }
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007956#endif
7957
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007958 if (ver >= CONPTY_FIRST_SUPPORT_BUILD)
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01007959 conpty_working = 1;
7960 if (ver >= CONPTY_STABLE_BUILD)
7961 conpty_stable = 1;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007962
Bram Moolenaar57da6982019-09-13 22:30:11 +02007963 if (ver <= CONPTY_INSIDER_BUILD)
7964 conpty_type = 3;
Bram Moolenaar36e7a822019-11-13 21:49:24 +01007965 if (ver <= CONPTY_1909_BUILD)
7966 conpty_type = 2;
Bram Moolenaar57da6982019-09-13 22:30:11 +02007967 if (ver <= CONPTY_1903_BUILD)
7968 conpty_type = 2;
7969 if (ver < CONPTY_FIRST_SUPPORT_BUILD)
7970 conpty_type = 1;
Bram Moolenaar7ed8f592020-04-28 20:44:42 +02007971
7972 if (ver >= CONPTY_NEXT_UPDATE_BUILD)
7973 conpty_fix_type = 1;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007974}
7975
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007976#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL) || defined(PROTO)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007977
7978 static void
7979vtp_init(void)
7980{
K.Takata27b53be2022-09-18 12:25:49 +01007981 CONSOLE_SCREEN_BUFFER_INFOEX csbi;
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007982# ifdef FEAT_TERMGUICOLORS
Yasuhiro Matsumotoaa04e1b2022-05-07 14:09:19 +01007983 COLORREF fg;
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007984# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007985
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007986 csbi.cbSize = sizeof(csbi);
K.Takata27b53be2022-09-18 12:25:49 +01007987 GetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007988 save_console_bg_rgb = (guicolor_T)csbi.ColorTable[g_color_index_bg];
7989 save_console_fg_rgb = (guicolor_T)csbi.ColorTable[g_color_index_fg];
Bram Moolenaardf543822020-01-30 11:53:59 +01007990 store_console_bg_rgb = save_console_bg_rgb;
7991 store_console_fg_rgb = save_console_fg_rgb;
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007992
7993# ifdef FEAT_TERMGUICOLORS
Yasuhiro Matsumotoe42c8da2022-09-01 11:31:45 +01007994 if (!USE_WT)
7995 {
7996 COLORREF bg;
7997 bg = (COLORREF)csbi.ColorTable[g_color_index_bg];
7998 bg = (GetRValue(bg) << 16) | (GetGValue(bg) << 8) | GetBValue(bg);
7999 default_console_color_bg = bg;
8000 }
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02008001 fg = (COLORREF)csbi.ColorTable[g_color_index_fg];
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02008002 fg = (GetRValue(fg) << 16) | (GetGValue(fg) << 8) | GetBValue(fg);
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02008003 default_console_color_fg = fg;
Bram Moolenaarc4568ab2018-11-16 16:21:05 +01008004# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008005
8006 set_console_color_rgb();
8007}
8008
8009 static void
8010vtp_exit(void)
8011{
Bram Moolenaardf543822020-01-30 11:53:59 +01008012 restore_console_color_rgb();
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008013}
8014
Bram Moolenaar06b7b582020-05-30 17:49:25 +02008015 int
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008016vtp_printf(
8017 char *format,
8018 ...)
8019{
8020 char_u buf[100];
8021 va_list list;
8022 DWORD result;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008023 int len;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008024
8025 va_start(list, format);
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008026 len = vim_vsnprintf((char *)buf, 100, (char *)format, list);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008027 va_end(list);
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008028 WriteConsoleA(g_hConOut, buf, (DWORD)len, &result, NULL);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008029 return (int)result;
8030}
8031
8032 static void
8033vtp_sgr_bulk(
8034 int arg)
8035{
8036 int args[1];
8037
8038 args[0] = arg;
8039 vtp_sgr_bulks(1, args);
8040}
8041
K.Takata6e1d31e2022-02-03 13:05:32 +00008042# define FAST256(x) \
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008043 if ((*p-- = "0123456789"[(n = x % 10)]) \
8044 && x >= 10 && (*p-- = "0123456789"[((m = x % 100) - n) / 10]) \
8045 && x >= 100 && (*p-- = "012"[((x & 0xff) - m) / 100]));
8046
K.Takata6e1d31e2022-02-03 13:05:32 +00008047# define FAST256CASE(x) \
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008048 case x: \
8049 FAST256(newargs[x - 1]);
8050
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008051 static void
8052vtp_sgr_bulks(
8053 int argc,
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008054 int *args)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008055{
K.Takata6e1d31e2022-02-03 13:05:32 +00008056# define MAXSGR 16
8057# define SGRBUFSIZE 2 + 4 * MAXSGR + 1 // '\033[' + SGR + 'm'
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008058 char_u buf[SGRBUFSIZE];
8059 char_u *p;
8060 int in, out;
8061 int newargs[16];
8062 static int sgrfgr = -1, sgrfgg, sgrfgb;
8063 static int sgrbgr = -1, sgrbgg, sgrbgb;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008064
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008065 if (argc == 0)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008066 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008067 sgrfgr = sgrbgr = -1;
K.Takatadf5320c2022-09-01 13:20:16 +01008068 vtp_printf("\033[m");
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008069 return;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008070 }
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008071
8072 in = out = 0;
8073 while (in < argc)
8074 {
8075 int s = args[in];
8076 int copylen = 1;
8077
8078 if (s == 38)
8079 {
8080 if (argc - in >= 5 && args[in + 1] == 2)
8081 {
8082 if (sgrfgr == args[in + 2] && sgrfgg == args[in + 3]
8083 && sgrfgb == args[in + 4])
8084 {
8085 in += 5;
8086 copylen = 0;
8087 }
8088 else
8089 {
8090 sgrfgr = args[in + 2];
8091 sgrfgg = args[in + 3];
8092 sgrfgb = args[in + 4];
8093 copylen = 5;
8094 }
8095 }
8096 else if (argc - in >= 3 && args[in + 1] == 5)
8097 {
8098 sgrfgr = -1;
8099 copylen = 3;
8100 }
8101 }
8102 else if (s == 48)
8103 {
8104 if (argc - in >= 5 && args[in + 1] == 2)
8105 {
8106 if (sgrbgr == args[in + 2] && sgrbgg == args[in + 3]
8107 && sgrbgb == args[in + 4])
8108 {
8109 in += 5;
8110 copylen = 0;
8111 }
8112 else
8113 {
8114 sgrbgr = args[in + 2];
8115 sgrbgg = args[in + 3];
8116 sgrbgb = args[in + 4];
8117 copylen = 5;
8118 }
8119 }
8120 else if (argc - in >= 3 && args[in + 1] == 5)
8121 {
8122 sgrbgr = -1;
8123 copylen = 3;
8124 }
8125 }
8126 else if (30 <= s && s <= 39)
8127 sgrfgr = -1;
8128 else if (90 <= s && s <= 97)
8129 sgrfgr = -1;
8130 else if (40 <= s && s <= 49)
8131 sgrbgr = -1;
8132 else if (100 <= s && s <= 107)
8133 sgrbgr = -1;
8134 else if (s == 0)
8135 sgrfgr = sgrbgr = -1;
8136
8137 while (copylen--)
8138 newargs[out++] = args[in++];
8139 }
8140
8141 p = &buf[sizeof(buf) - 1];
8142 *p-- = 'm';
8143
8144 switch (out)
8145 {
8146 int n, m;
8147 DWORD r;
8148
8149 FAST256CASE(16);
8150 *p-- = ';';
8151 FAST256CASE(15);
8152 *p-- = ';';
8153 FAST256CASE(14);
8154 *p-- = ';';
8155 FAST256CASE(13);
8156 *p-- = ';';
8157 FAST256CASE(12);
8158 *p-- = ';';
8159 FAST256CASE(11);
8160 *p-- = ';';
8161 FAST256CASE(10);
8162 *p-- = ';';
8163 FAST256CASE(9);
8164 *p-- = ';';
8165 FAST256CASE(8);
8166 *p-- = ';';
8167 FAST256CASE(7);
8168 *p-- = ';';
8169 FAST256CASE(6);
8170 *p-- = ';';
8171 FAST256CASE(5);
8172 *p-- = ';';
8173 FAST256CASE(4);
8174 *p-- = ';';
8175 FAST256CASE(3);
8176 *p-- = ';';
8177 FAST256CASE(2);
8178 *p-- = ';';
8179 FAST256CASE(1);
8180 *p-- = '[';
8181 *p = '\033';
8182 WriteConsoleA(g_hConOut, p, (DWORD)(&buf[SGRBUFSIZE] - p), &r, NULL);
8183 default:
8184 break;
8185 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008186}
8187
Bram Moolenaar06b7b582020-05-30 17:49:25 +02008188 static void
8189wt_init(void)
8190{
8191 wt_working = (mch_getenv("WT_SESSION") != NULL);
8192}
8193
8194 int
8195use_wt(void)
8196{
8197 return USE_WT;
8198}
8199
Bram Moolenaar8a938af2018-05-01 17:30:41 +02008200# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02008201 static int
8202ctermtoxterm(
8203 int cterm)
8204{
Bram Moolenaar9894e392018-05-05 14:29:06 +02008205 char_u r, g, b, idx;
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02008206
8207 cterm_color2rgb(cterm, &r, &g, &b, &idx);
8208 return (((int)r << 16) | ((int)g << 8) | (int)b);
8209}
Bram Moolenaar8a938af2018-05-01 17:30:41 +02008210# endif
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02008211
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008212 static void
8213set_console_color_rgb(void)
8214{
8215# ifdef FEAT_TERMGUICOLORS
K.Takata27b53be2022-09-18 12:25:49 +01008216 CONSOLE_SCREEN_BUFFER_INFOEX csbi;
Bram Moolenaara050b942019-12-02 21:35:31 +01008217 guicolor_T fg, bg;
8218 int ctermfg, ctermbg;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008219
8220 if (!USE_VTP)
8221 return;
8222
Bram Moolenaara050b942019-12-02 21:35:31 +01008223 get_default_console_color(&ctermfg, &ctermbg, &fg, &bg);
8224
Bram Moolenaar06b7b582020-05-30 17:49:25 +02008225 if (USE_WT)
8226 {
8227 term_fg_rgb_color(fg);
8228 term_bg_rgb_color(bg);
8229 return;
8230 }
8231
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008232 fg = (GetRValue(fg) << 16) | (GetGValue(fg) << 8) | GetBValue(fg);
8233 bg = (GetRValue(bg) << 16) | (GetGValue(bg) << 8) | GetBValue(bg);
8234
8235 csbi.cbSize = sizeof(csbi);
K.Takata27b53be2022-09-18 12:25:49 +01008236 GetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008237
8238 csbi.cbSize = sizeof(csbi);
8239 csbi.srWindow.Right += 1;
8240 csbi.srWindow.Bottom += 1;
Bram Moolenaardf543822020-01-30 11:53:59 +01008241 store_console_bg_rgb = csbi.ColorTable[g_color_index_bg];
8242 store_console_fg_rgb = csbi.ColorTable[g_color_index_fg];
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02008243 csbi.ColorTable[g_color_index_bg] = (COLORREF)bg;
8244 csbi.ColorTable[g_color_index_fg] = (COLORREF)fg;
K.Takata27b53be2022-09-18 12:25:49 +01008245 SetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008246# endif
8247}
8248
Bram Moolenaara050b942019-12-02 21:35:31 +01008249# if defined(FEAT_TERMGUICOLORS) || defined(PROTO)
8250 void
8251get_default_console_color(
8252 int *cterm_fg,
8253 int *cterm_bg,
8254 guicolor_T *gui_fg,
8255 guicolor_T *gui_bg)
8256{
8257 int id;
8258 guicolor_T guifg = INVALCOLOR;
8259 guicolor_T guibg = INVALCOLOR;
8260 int ctermfg = 0;
8261 int ctermbg = 0;
8262
8263 id = syn_name2id((char_u *)"Normal");
8264 if (id > 0 && p_tgc)
8265 syn_id2colors(id, &guifg, &guibg);
8266 if (guifg == INVALCOLOR)
8267 {
8268 ctermfg = -1;
8269 if (id > 0)
8270 syn_id2cterm_bg(id, &ctermfg, &ctermbg);
8271 guifg = ctermfg != -1 ? ctermtoxterm(ctermfg)
8272 : default_console_color_fg;
8273 cterm_normal_fg_gui_color = guifg;
8274 ctermfg = ctermfg < 0 ? 0 : ctermfg;
8275 }
8276 if (guibg == INVALCOLOR)
8277 {
8278 ctermbg = -1;
8279 if (id > 0)
8280 syn_id2cterm_bg(id, &ctermfg, &ctermbg);
K.Takatae53a0d42022-09-05 21:45:11 +01008281 if (USE_WT)
Yasuhiro Matsumotoe42c8da2022-09-01 11:31:45 +01008282 {
8283 cterm_normal_bg_gui_color = guibg =
Yasuhiro Matsumotoaa04e1b2022-05-07 14:09:19 +01008284 ctermbg != -1 ? ctermtoxterm(ctermbg) : INVALCOLOR;
Yasuhiro Matsumotoe42c8da2022-09-01 11:31:45 +01008285 if (ctermbg < 0)
8286 ctermbg = 0;
8287 }
K.Takatae53a0d42022-09-05 21:45:11 +01008288 else
8289 {
8290 guibg = ctermbg != -1 ? ctermtoxterm(ctermbg)
8291 : default_console_color_bg;
8292 cterm_normal_bg_gui_color = guibg;
8293 ctermbg = ctermbg < 0 ? 0 : ctermbg;
8294 }
Bram Moolenaara050b942019-12-02 21:35:31 +01008295 }
8296
8297 *cterm_fg = ctermfg;
8298 *cterm_bg = ctermbg;
8299 *gui_fg = guifg;
8300 *gui_bg = guibg;
8301}
8302# endif
8303
Bram Moolenaardf543822020-01-30 11:53:59 +01008304/*
8305 * Set the console colors to the original colors or the last set colors.
8306 */
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008307 static void
8308reset_console_color_rgb(void)
8309{
8310# ifdef FEAT_TERMGUICOLORS
K.Takata27b53be2022-09-18 12:25:49 +01008311 CONSOLE_SCREEN_BUFFER_INFOEX csbi;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008312
Bram Moolenaar06b7b582020-05-30 17:49:25 +02008313 if (USE_WT)
8314 return;
8315
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008316 csbi.cbSize = sizeof(csbi);
K.Takata27b53be2022-09-18 12:25:49 +01008317 GetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008318
8319 csbi.cbSize = sizeof(csbi);
8320 csbi.srWindow.Right += 1;
8321 csbi.srWindow.Bottom += 1;
Bram Moolenaardf543822020-01-30 11:53:59 +01008322 csbi.ColorTable[g_color_index_bg] = (COLORREF)store_console_bg_rgb;
8323 csbi.ColorTable[g_color_index_fg] = (COLORREF)store_console_fg_rgb;
K.Takata27b53be2022-09-18 12:25:49 +01008324 SetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaardf543822020-01-30 11:53:59 +01008325# endif
8326}
8327
8328/*
8329 * Set the console colors to the original colors.
8330 */
8331 static void
8332restore_console_color_rgb(void)
8333{
8334# ifdef FEAT_TERMGUICOLORS
K.Takata27b53be2022-09-18 12:25:49 +01008335 CONSOLE_SCREEN_BUFFER_INFOEX csbi;
Bram Moolenaardf543822020-01-30 11:53:59 +01008336
8337 csbi.cbSize = sizeof(csbi);
K.Takata27b53be2022-09-18 12:25:49 +01008338 GetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaardf543822020-01-30 11:53:59 +01008339
8340 csbi.cbSize = sizeof(csbi);
8341 csbi.srWindow.Right += 1;
8342 csbi.srWindow.Bottom += 1;
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02008343 csbi.ColorTable[g_color_index_bg] = (COLORREF)save_console_bg_rgb;
8344 csbi.ColorTable[g_color_index_fg] = (COLORREF)save_console_fg_rgb;
K.Takata27b53be2022-09-18 12:25:49 +01008345 SetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008346# endif
8347}
8348
8349 void
8350control_console_color_rgb(void)
8351{
8352 if (USE_VTP)
8353 set_console_color_rgb();
8354 else
8355 reset_console_color_rgb();
8356}
8357
8358 int
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008359use_vtp(void)
8360{
8361 return USE_VTP;
8362}
8363
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02008364 int
8365is_term_win32(void)
8366{
8367 return T_NAME != NULL && STRCMP(T_NAME, "win32") == 0;
8368}
8369
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008370 int
8371has_vtp_working(void)
8372{
8373 return vtp_working;
8374}
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01008375
Bram Moolenaar6902c0e2019-02-16 14:07:37 +01008376#endif
8377
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01008378 int
8379has_conpty_working(void)
8380{
8381 return conpty_working;
8382}
8383
8384 int
Bram Moolenaar57da6982019-09-13 22:30:11 +02008385get_conpty_type(void)
8386{
8387 return conpty_type;
8388}
8389
8390 int
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01008391is_conpty_stable(void)
8392{
8393 return conpty_stable;
8394}
Bram Moolenaar78d21da2019-02-17 15:00:52 +01008395
Bram Moolenaar7ed8f592020-04-28 20:44:42 +02008396 int
8397get_conpty_fix_type(void)
8398{
8399 return conpty_fix_type;
8400}
8401
Bram Moolenaarafde13b2019-04-28 19:46:49 +02008402#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL) || defined(PROTO)
Bram Moolenaar78d21da2019-02-17 15:00:52 +01008403 void
8404resize_console_buf(void)
8405{
8406 CONSOLE_SCREEN_BUFFER_INFO csbi;
8407 COORD coord;
8408 SMALL_RECT newsize;
8409
8410 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
8411 {
8412 coord.X = SRWIDTH(csbi.srWindow);
8413 coord.Y = SRHEIGHT(csbi.srWindow);
8414 SetConsoleScreenBufferSize(g_hConOut, coord);
8415
8416 newsize.Left = 0;
8417 newsize.Top = 0;
8418 newsize.Right = coord.X - 1;
8419 newsize.Bottom = coord.Y - 1;
8420 SetConsoleWindowInfo(g_hConOut, TRUE, &newsize);
8421
8422 SetConsoleScreenBufferSize(g_hConOut, coord);
8423 }
8424}
8425#endif
Martin Tournoij1a3e5742021-07-24 13:57:29 +02008426
8427 char *
8428GetWin32Error(void)
8429{
K.Takatad68b2fc2022-02-12 11:18:37 +00008430 static char *oldmsg = NULL;
Martin Tournoij1a3e5742021-07-24 13:57:29 +02008431 char *msg = NULL;
K.Takatad68b2fc2022-02-12 11:18:37 +00008432
Martin Tournoij1a3e5742021-07-24 13:57:29 +02008433 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER|FORMAT_MESSAGE_FROM_SYSTEM,
8434 NULL, GetLastError(), 0, (LPSTR)&msg, 0, NULL);
K.Takatad68b2fc2022-02-12 11:18:37 +00008435 if (oldmsg != NULL)
8436 LocalFree(oldmsg);
Martin Tournoij1a3e5742021-07-24 13:57:29 +02008437 if (msg != NULL)
8438 {
8439 // remove trailing \r\n
8440 char *pcrlf = strstr(msg, "\r\n");
8441 if (pcrlf != NULL)
8442 *pcrlf = '\0';
K.Takatad68b2fc2022-02-12 11:18:37 +00008443 oldmsg = msg;
Martin Tournoij1a3e5742021-07-24 13:57:29 +02008444 }
8445 return msg;
8446}
Paul Ollis65745772022-06-05 16:55:54 +01008447
8448#if defined(FEAT_RELTIME) || defined(PROTO)
8449static HANDLE timer_handle;
8450static int timer_active = FALSE;
8451
8452/*
8453 * Calls to start_timeout alternate the return value pointer between the two
8454 * entries in timeout_flags. If the previously active timeout is very close to
8455 * expiring when start_timeout() is called then a race condition means that the
8456 * set_flag() function may still be invoked after the previous timer is
8457 * deleted. Ping-ponging between the two flags prevents this causing 'fake'
8458 * timeouts.
8459 */
Bram Moolenaar155f2d12022-06-20 13:38:33 +01008460static sig_atomic_t timeout_flags[2];
8461static int timeout_flag_idx = 0;
8462static sig_atomic_t *timeout_flag = &timeout_flags[0];
Paul Ollis65745772022-06-05 16:55:54 +01008463
8464
8465 static void CALLBACK
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +01008466set_flag(void *param, BOOLEAN unused2 UNUSED)
Paul Ollis65745772022-06-05 16:55:54 +01008467{
8468 int *timeout_flag = (int *)param;
8469
8470 *timeout_flag = TRUE;
8471}
8472
8473/*
8474 * Stop any active timeout.
8475 */
8476 void
8477stop_timeout(void)
8478{
8479 if (timer_active)
8480 {
Christopher Plewright2a46f812022-10-16 19:47:45 +01008481 BOOL ret = DeleteTimerQueueTimer(NULL, timer_handle, NULL);
Paul Ollis65745772022-06-05 16:55:54 +01008482 timer_active = FALSE;
8483 if (!ret && GetLastError() != ERROR_IO_PENDING)
8484 {
8485 semsg(_(e_could_not_clear_timeout_str), GetWin32Error());
8486 }
8487 }
8488 *timeout_flag = FALSE;
8489}
8490
8491/*
8492 * Start the timeout timer.
8493 *
8494 * The period is defined in milliseconds.
8495 *
8496 * The return value is a pointer to a flag that is initialised to 0. If the
8497 * timeout expires, the flag is set to 1. This will only return pointers to
8498 * static memory; i.e. any pointer returned by this function may always be
8499 * safely dereferenced.
8500 *
8501 * This function is not expected to fail, but if it does it still returns a
8502 * valid flag pointer; the flag will remain stuck at zero.
8503 */
Bram Moolenaar155f2d12022-06-20 13:38:33 +01008504 volatile sig_atomic_t *
Paul Ollis65745772022-06-05 16:55:54 +01008505start_timeout(long msec)
8506{
Paul Ollis65745772022-06-05 16:55:54 +01008507 BOOL ret;
8508
Bram Moolenaar1f30caf2022-06-19 14:36:35 +01008509 timeout_flag = &timeout_flags[timeout_flag_idx];
Paul Ollis65745772022-06-05 16:55:54 +01008510
8511 stop_timeout();
8512 ret = CreateTimerQueueTimer(
8513 &timer_handle, NULL, set_flag, timeout_flag,
8514 (DWORD)msec, 0, WT_EXECUTEDEFAULT);
8515 if (!ret)
8516 {
8517 semsg(_(e_could_not_set_timeout_str), GetWin32Error());
8518 }
8519 else
8520 {
Bram Moolenaar1f30caf2022-06-19 14:36:35 +01008521 timeout_flag_idx = (timeout_flag_idx + 1) % 2;
Paul Ollis65745772022-06-05 16:55:54 +01008522 timer_active = TRUE;
8523 *timeout_flag = FALSE;
8524 }
8525 return timeout_flag;
8526}
8527#endif