blob: 003fdea1b9a73a806645fe243d016e4a7e1a99c2 [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/*
1236 * Win32 console mouse scroll event handler.
1237 * Loosely based on the _OnMouseWheel() function in gui_w32.c
1238 *
1239 * This encodes the mouse scroll direction and keyboard modifiers into
1240 * g_nMouseClick, and the mouse position into g_xMouse and g_yMouse
1241 *
1242 * The direction of the scroll is decoded from two fields of the win32 console
1243 * mouse event record;
1244 * 1. The axis - vertical or horizontal flag - from dwEventFlags, and
1245 * 2. The sign - positive or negative (aka delta flag) - from dwButtonState
1246 *
1247 * When scroll axis is HORIZONTAL
1248 * - If the high word of the dwButtonState member contains a positive
1249 * value, the wheel was rotated to the right.
1250 * - Otherwise, the wheel was rotated to the left.
1251 * When scroll axis is VERTICAL
1252 * - If the high word of the dwButtonState member contains a positive value,
1253 * the wheel was rotated forward, away from the user.
1254 * - Otherwise, the wheel was rotated backward, toward the user.
1255 */
1256 static void
1257decode_mouse_wheel(MOUSE_EVENT_RECORD *pmer)
1258{
1259 win_T *wp;
1260 int horizontal = (pmer->dwEventFlags == MOUSE_HWHEELED);
1261 int zDelta = pmer->dwButtonState;
1262
1263 g_xMouse = pmer->dwMousePosition.X;
1264 g_yMouse = pmer->dwMousePosition.Y;
1265
1266#ifdef FEAT_PROP_POPUP
1267 int lcol;
1268 int lrow;
1269 lcol = g_xMouse;
1270 lrow = g_yMouse;
1271 wp = mouse_find_win(&lrow, &lcol, FAIL_POPUP);
1272 if (wp != NULL && popup_is_popup(wp))
1273 {
1274 g_nMouseClick = -1;
1275 cmdarg_T cap;
1276 oparg_T oa;
1277 CLEAR_FIELD(cap);
1278 clear_oparg(&oa);
1279 cap.oap = &oa;
1280 if (horizontal)
1281 {
1282 cap.arg = zDelta < 0 ? MSCR_LEFT : MSCR_RIGHT;
1283 cap.cmdchar = zDelta < 0 ? K_MOUSELEFT : K_MOUSERIGHT;
1284 }
1285 else
1286 {
1287 cap.cmdchar = zDelta < 0 ? K_MOUSEUP : K_MOUSEDOWN;
1288 cap.arg = zDelta < 0 ? MSCR_UP : MSCR_DOWN;
1289 }
1290
1291 // Mouse hovers over popup window, scroll it if possible.
1292 mouse_row = wp->w_winrow;
1293 mouse_col = wp->w_wincol;
1294 nv_mousescroll(&cap);
1295 update_screen(0);
1296 setcursor();
1297 out_flush();
1298 return;
1299 }
1300#endif
1301 mouse_col = g_xMouse;
1302 mouse_row = g_yMouse;
1303
1304 char_u modifiers = 0;
1305 char_u direction = 0;
1306
1307 // Decode the direction into an event that Vim can process
1308 if (horizontal)
1309 direction = zDelta >= 0 ? KE_MOUSELEFT : KE_MOUSERIGHT;
1310 else
1311 direction = zDelta >= 0 ? KE_MOUSEDOWN : KE_MOUSEUP;
1312
1313 // Decode the win32 console key modifers into Vim mouse modifers.
1314 if (pmer->dwControlKeyState & SHIFT_PRESSED)
1315 modifiers |= MOD_MASK_SHIFT; //MOUSE_SHIFT;
1316 if (pmer->dwControlKeyState & (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED))
1317 modifiers |= MOD_MASK_CTRL; //MOUSE_CTRL;
1318 if (pmer->dwControlKeyState & (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED))
1319 modifiers |= MOD_MASK_ALT; // MOUSE_ALT;
1320
1321 // add (bitwise or) the scroll direction and the key modifier chars
1322 // together.
1323 g_nMouseClick = ((direction << 8) | modifiers);
1324
1325 return;
1326}
1327
Bram Moolenaar071d4272004-06-13 20:20:40 +00001328/*
1329 * Decode a MOUSE_EVENT. If it's a valid event, return MOUSE_LEFT,
1330 * MOUSE_MIDDLE, or MOUSE_RIGHT for a click; MOUSE_DRAG for a mouse
1331 * move with a button held down; and MOUSE_RELEASE after a MOUSE_DRAG
1332 * or a MOUSE_LEFT, _MIDDLE, or _RIGHT. We encode the button type,
1333 * the number of clicks, and the Shift/Ctrl/Alt modifiers in g_nMouseClick,
1334 * and we return the mouse position in g_xMouse and g_yMouse.
1335 *
1336 * Every MOUSE_LEFT, _MIDDLE, or _RIGHT will be followed by zero or more
1337 * MOUSE_DRAGs and one MOUSE_RELEASE. MOUSE_RELEASE will be followed only
1338 * by MOUSE_LEFT, _MIDDLE, or _RIGHT.
1339 *
1340 * For multiple clicks, we send, say, MOUSE_LEFT/1 click, MOUSE_RELEASE,
1341 * MOUSE_LEFT/2 clicks, MOUSE_RELEASE, MOUSE_LEFT/3 clicks, MOUSE_RELEASE, ....
1342 *
1343 * Windows will send us MOUSE_MOVED notifications whenever the mouse
1344 * moves, even if it stays within the same character cell. We ignore
1345 * all MOUSE_MOVED messages if the position hasn't really changed, and
1346 * we ignore all MOUSE_MOVED messages where no button is held down (i.e.,
1347 * we're only interested in MOUSE_DRAG).
1348 *
1349 * All of this is complicated by the code that fakes MOUSE_MIDDLE on
1350 * 2-button mouses by pressing the left & right buttons simultaneously.
1351 * In practice, it's almost impossible to click both at the same time,
1352 * so we need to delay a little. Also, we tend not to get MOUSE_RELEASE
1353 * in such cases, if the user is clicking quickly.
1354 */
1355 static BOOL
1356decode_mouse_event(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001357 MOUSE_EVENT_RECORD *pmer)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001358{
1359 static int s_nOldButton = -1;
1360 static int s_nOldMouseClick = -1;
1361 static int s_xOldMouse = -1;
1362 static int s_yOldMouse = -1;
1363 static linenr_T s_old_topline = 0;
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001364# ifdef FEAT_DIFF
Bram Moolenaar071d4272004-06-13 20:20:40 +00001365 static int s_old_topfill = 0;
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001366# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001367 static int s_cClicks = 1;
1368 static BOOL s_fReleased = TRUE;
1369 static DWORD s_dwLastClickTime = 0;
1370 static BOOL s_fNextIsMiddle = FALSE;
1371
Bram Moolenaar0f873732019-12-05 20:28:46 +01001372 static DWORD cButtons = 0; // number of buttons supported
Bram Moolenaar071d4272004-06-13 20:20:40 +00001373
1374 const DWORD LEFT = FROM_LEFT_1ST_BUTTON_PRESSED;
1375 const DWORD MIDDLE = FROM_LEFT_2ND_BUTTON_PRESSED;
1376 const DWORD RIGHT = RIGHTMOST_BUTTON_PRESSED;
1377 const DWORD LEFT_RIGHT = LEFT | RIGHT;
1378
1379 int nButton;
1380
1381 if (cButtons == 0 && !GetNumberOfConsoleMouseButtons(&cButtons))
1382 cButtons = 2;
1383
1384 if (!g_fMouseAvail || !g_fMouseActive)
1385 {
1386 g_nMouseClick = -1;
1387 return FALSE;
1388 }
1389
Bram Moolenaar0f873732019-12-05 20:28:46 +01001390 // get a spurious MOUSE_EVENT immediately after receiving focus; ignore
Bram Moolenaar071d4272004-06-13 20:20:40 +00001391 if (g_fJustGotFocus)
1392 {
1393 g_fJustGotFocus = FALSE;
1394 return FALSE;
1395 }
1396
Bram Moolenaar0f873732019-12-05 20:28:46 +01001397 // unprocessed mouse click?
Bram Moolenaar071d4272004-06-13 20:20:40 +00001398 if (g_nMouseClick != -1)
1399 return TRUE;
1400
Christopher Plewright2a46f812022-10-16 19:47:45 +01001401 if (pmer->dwEventFlags == MOUSE_WHEELED
1402 || pmer->dwEventFlags == MOUSE_HWHEELED)
1403 {
1404 decode_mouse_wheel(pmer);
1405 return TRUE; // we now should have a mouse scroll in g_nMouseClick
1406 }
1407
Bram Moolenaar071d4272004-06-13 20:20:40 +00001408 nButton = -1;
1409 g_xMouse = pmer->dwMousePosition.X;
1410 g_yMouse = pmer->dwMousePosition.Y;
1411
1412 if (pmer->dwEventFlags == MOUSE_MOVED)
1413 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001414 // Ignore MOUSE_MOVED events if (x, y) hasn't changed. (We get these
1415 // events even when the mouse moves only within a char cell.)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001416 if (s_xOldMouse == g_xMouse && s_yOldMouse == g_yMouse)
1417 return FALSE;
1418 }
1419
Bram Moolenaar0f873732019-12-05 20:28:46 +01001420 // If no buttons are pressed...
Bram Moolenaar071d4272004-06-13 20:20:40 +00001421 if ((pmer->dwButtonState & ((1 << cButtons) - 1)) == 0)
1422 {
Bram Moolenaar157d8132018-03-06 17:09:20 +01001423 nButton = MOUSE_RELEASE;
1424
Bram Moolenaar0f873732019-12-05 20:28:46 +01001425 // If the last thing returned was MOUSE_RELEASE, ignore this
Bram Moolenaar071d4272004-06-13 20:20:40 +00001426 if (s_fReleased)
Bram Moolenaar157d8132018-03-06 17:09:20 +01001427 {
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001428# ifdef FEAT_BEVAL_TERM
Bram Moolenaar0f873732019-12-05 20:28:46 +01001429 // do return mouse move events when we want them
Bram Moolenaar157d8132018-03-06 17:09:20 +01001430 if (p_bevalterm)
1431 nButton = MOUSE_DRAG;
1432 else
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001433# endif
Bram Moolenaar157d8132018-03-06 17:09:20 +01001434 return FALSE;
1435 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001436
Bram Moolenaar071d4272004-06-13 20:20:40 +00001437 s_fReleased = TRUE;
1438 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01001439 else // one or more buttons pressed
Bram Moolenaar071d4272004-06-13 20:20:40 +00001440 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001441 // on a 2-button mouse, hold down left and right buttons
1442 // simultaneously to get MIDDLE.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001443
1444 if (cButtons == 2 && s_nOldButton != MOUSE_DRAG)
1445 {
1446 DWORD dwLR = (pmer->dwButtonState & LEFT_RIGHT);
1447
Bram Moolenaar0f873732019-12-05 20:28:46 +01001448 // if either left or right button only is pressed, see if the
1449 // next mouse event has both of them pressed
Bram Moolenaar071d4272004-06-13 20:20:40 +00001450 if (dwLR == LEFT || dwLR == RIGHT)
1451 {
1452 for (;;)
1453 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001454 // wait a short time for next input event
Bram Moolenaar071d4272004-06-13 20:20:40 +00001455 if (WaitForSingleObject(g_hConIn, p_mouset / 3)
1456 != WAIT_OBJECT_0)
1457 break;
1458 else
1459 {
1460 DWORD cRecords = 0;
1461 INPUT_RECORD ir;
1462 MOUSE_EVENT_RECORD* pmer2 = &ir.Event.MouseEvent;
1463
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001464 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001465
1466 if (cRecords == 0 || ir.EventType != MOUSE_EVENT
1467 || !(pmer2->dwButtonState & LEFT_RIGHT))
1468 break;
1469 else
1470 {
1471 if (pmer2->dwEventFlags != MOUSE_MOVED)
1472 {
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001473 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001474
1475 return decode_mouse_event(pmer2);
1476 }
1477 else if (s_xOldMouse == pmer2->dwMousePosition.X &&
1478 s_yOldMouse == pmer2->dwMousePosition.Y)
1479 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001480 // throw away spurious mouse move
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001481 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001482
Bram Moolenaar0f873732019-12-05 20:28:46 +01001483 // are there any more mouse events in queue?
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001484 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001485
1486 if (cRecords==0 || ir.EventType != MOUSE_EVENT)
1487 break;
1488 }
1489 else
1490 break;
1491 }
1492 }
1493 }
1494 }
1495 }
1496
1497 if (s_fNextIsMiddle)
1498 {
1499 nButton = (pmer->dwEventFlags == MOUSE_MOVED)
1500 ? MOUSE_DRAG : MOUSE_MIDDLE;
1501 s_fNextIsMiddle = FALSE;
1502 }
1503 else if (cButtons == 2 &&
1504 ((pmer->dwButtonState & LEFT_RIGHT) == LEFT_RIGHT))
1505 {
1506 nButton = MOUSE_MIDDLE;
1507
1508 if (! s_fReleased && pmer->dwEventFlags != MOUSE_MOVED)
1509 {
1510 s_fNextIsMiddle = TRUE;
1511 nButton = MOUSE_RELEASE;
1512 }
1513 }
1514 else if ((pmer->dwButtonState & LEFT) == LEFT)
1515 nButton = MOUSE_LEFT;
1516 else if ((pmer->dwButtonState & MIDDLE) == MIDDLE)
1517 nButton = MOUSE_MIDDLE;
1518 else if ((pmer->dwButtonState & RIGHT) == RIGHT)
1519 nButton = MOUSE_RIGHT;
1520
1521 if (! s_fReleased && ! s_fNextIsMiddle
1522 && nButton != s_nOldButton && s_nOldButton != MOUSE_DRAG)
1523 return FALSE;
1524
1525 s_fReleased = s_fNextIsMiddle;
1526 }
1527
1528 if (pmer->dwEventFlags == 0 || pmer->dwEventFlags == DOUBLE_CLICK)
1529 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001530 // button pressed or released, without mouse moving
Bram Moolenaar071d4272004-06-13 20:20:40 +00001531 if (nButton != -1 && nButton != MOUSE_RELEASE)
1532 {
1533 DWORD dwCurrentTime = GetTickCount();
1534
1535 if (s_xOldMouse != g_xMouse
1536 || s_yOldMouse != g_yMouse
1537 || s_nOldButton != nButton
1538 || s_old_topline != curwin->w_topline
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001539# ifdef FEAT_DIFF
Bram Moolenaar071d4272004-06-13 20:20:40 +00001540 || s_old_topfill != curwin->w_topfill
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001541# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001542 || (int)(dwCurrentTime - s_dwLastClickTime) > p_mouset)
1543 {
1544 s_cClicks = 1;
1545 }
1546 else if (++s_cClicks > 4)
1547 {
1548 s_cClicks = 1;
1549 }
1550
1551 s_dwLastClickTime = dwCurrentTime;
1552 }
1553 }
1554 else if (pmer->dwEventFlags == MOUSE_MOVED)
1555 {
1556 if (nButton != -1 && nButton != MOUSE_RELEASE)
1557 nButton = MOUSE_DRAG;
1558
1559 s_cClicks = 1;
1560 }
1561
1562 if (nButton == -1)
1563 return FALSE;
1564
1565 if (nButton != MOUSE_RELEASE)
1566 s_nOldButton = nButton;
1567
1568 g_nMouseClick = nButton;
1569
1570 if (pmer->dwControlKeyState & SHIFT_PRESSED)
1571 g_nMouseClick |= MOUSE_SHIFT;
1572 if (pmer->dwControlKeyState & (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED))
1573 g_nMouseClick |= MOUSE_CTRL;
1574 if (pmer->dwControlKeyState & (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED))
1575 g_nMouseClick |= MOUSE_ALT;
1576
1577 if (nButton != MOUSE_DRAG && nButton != MOUSE_RELEASE)
1578 SET_NUM_MOUSE_CLICKS(g_nMouseClick, s_cClicks);
1579
Bram Moolenaar0f873732019-12-05 20:28:46 +01001580 // only pass on interesting (i.e., different) mouse events
Bram Moolenaar071d4272004-06-13 20:20:40 +00001581 if (s_xOldMouse == g_xMouse
1582 && s_yOldMouse == g_yMouse
1583 && s_nOldMouseClick == g_nMouseClick)
1584 {
1585 g_nMouseClick = -1;
1586 return FALSE;
1587 }
1588
1589 s_xOldMouse = g_xMouse;
1590 s_yOldMouse = g_yMouse;
1591 s_old_topline = curwin->w_topline;
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001592# ifdef FEAT_DIFF
Bram Moolenaar071d4272004-06-13 20:20:40 +00001593 s_old_topfill = curwin->w_topfill;
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001594# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001595 s_nOldMouseClick = g_nMouseClick;
1596
1597 return TRUE;
1598}
1599
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001600#endif // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00001601
1602
1603#ifdef MCH_CURSOR_SHAPE
1604/*
1605 * Set the shape of the cursor.
1606 * 'thickness' can be from 1 (thin) to 99 (block)
1607 */
1608 static void
1609mch_set_cursor_shape(int thickness)
1610{
K.Takatadf5320c2022-09-01 13:20:16 +01001611 if (USE_VTP || USE_WT)
1612 {
1613 if (*T_CSI == NUL)
1614 {
1615 // If 't_SI' is not set, use the default cursor styles.
1616 if (thickness < 50)
1617 vtp_printf("\033[3 q"); // underline
1618 else
1619 vtp_printf("\033[0 q"); // default
1620 }
1621 }
1622 else
1623 {
1624 CONSOLE_CURSOR_INFO ConsoleCursorInfo;
1625 ConsoleCursorInfo.dwSize = thickness;
1626 ConsoleCursorInfo.bVisible = s_cursor_visible;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001627
K.Takatadf5320c2022-09-01 13:20:16 +01001628 SetConsoleCursorInfo(g_hConOut, &ConsoleCursorInfo);
1629 if (s_cursor_visible)
1630 SetConsoleCursorPosition(g_hConOut, g_coord);
1631 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001632}
1633
1634 void
1635mch_update_cursor(void)
1636{
1637 int idx;
1638 int thickness;
1639
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001640# ifdef VIMDLL
1641 if (gui.in_use)
1642 return;
1643# endif
1644
Bram Moolenaar071d4272004-06-13 20:20:40 +00001645 /*
1646 * How the cursor is drawn depends on the current mode.
1647 */
1648 idx = get_shape_idx(FALSE);
1649
1650 if (shape_table[idx].shape == SHAPE_BLOCK)
Bram Moolenaar0f873732019-12-05 20:28:46 +01001651 thickness = 99; // 100 doesn't work on W95
Bram Moolenaar071d4272004-06-13 20:20:40 +00001652 else
1653 thickness = shape_table[idx].percentage;
1654 mch_set_cursor_shape(thickness);
1655}
1656#endif
1657
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001658#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001659/*
1660 * Handle FOCUS_EVENT.
1661 */
1662 static void
1663handle_focus_event(INPUT_RECORD ir)
1664{
1665 g_fJustGotFocus = ir.Event.FocusEvent.bSetFocus;
1666 ui_focus_change((int)g_fJustGotFocus);
1667}
1668
Bram Moolenaar78d21da2019-02-17 15:00:52 +01001669static void ResizeConBuf(HANDLE hConsole, COORD coordScreen);
1670
Bram Moolenaar071d4272004-06-13 20:20:40 +00001671/*
1672 * Wait until console input from keyboard or mouse is available,
1673 * or the time is up.
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001674 * When "ignore_input" is TRUE even wait when input is available.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001675 * Return TRUE if something is available FALSE if not.
1676 */
1677 static int
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001678WaitForChar(long msec, int ignore_input)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001679{
1680 DWORD dwNow = 0, dwEndTime = 0;
1681 INPUT_RECORD ir;
1682 DWORD cRecords;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001683 WCHAR ch, ch2;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001684# ifdef FEAT_TIMERS
Bram Moolenaar40b1b542016-04-20 20:18:23 +02001685 int tb_change_cnt = typebuf.tb_change_cnt;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001686# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001687
1688 if (msec > 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01001689 // Wait until the specified time has elapsed.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001690 dwEndTime = GetTickCount() + msec;
1691 else if (msec < 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01001692 // Wait forever.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001693 dwEndTime = INFINITE;
1694
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01001695 // We need to loop until the end of the time period, because
1696 // we might get multiple unusable mouse events in that time.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001697 for (;;)
1698 {
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001699 // Only process messages when waiting.
1700 if (msec != 0)
1701 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001702# ifdef MESSAGE_QUEUE
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001703 parse_queued_messages();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001704# endif
1705# ifdef FEAT_MZSCHEME
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001706 mzvim_check_threads();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001707# endif
1708# ifdef FEAT_CLIENTSERVER
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001709 serverProcessPendingMessages();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001710# endif
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001711 }
Bram Moolenaarf12d9832016-01-29 21:11:25 +01001712
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001713 if (g_nMouseClick != -1
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001714# ifdef FEAT_CLIENTSERVER
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001715 || (!ignore_input && input_available())
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001716# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001717 )
1718 return TRUE;
1719
1720 if (msec > 0)
1721 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001722 // If the specified wait time has passed, return. Beware that
1723 // GetTickCount() may wrap around (overflow).
Bram Moolenaar071d4272004-06-13 20:20:40 +00001724 dwNow = GetTickCount();
Bram Moolenaarb7512b72013-08-10 12:45:09 +02001725 if ((int)(dwNow - dwEndTime) >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001726 break;
1727 }
1728 if (msec != 0)
1729 {
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001730 DWORD dwWaitTime = dwEndTime - dwNow;
1731
Bram Moolenaarc478ee32020-12-01 21:27:51 +01001732 // Don't wait for more than 11 msec to avoid dropping characters,
1733 // check channel while waiting for input and handle a callback from
1734 // 'balloonexpr'.
1735 if (dwWaitTime > 11)
1736 dwWaitTime = 11;
1737
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001738# ifdef FEAT_MZSCHEME
Bram Moolenaarc478ee32020-12-01 21:27:51 +01001739 if (mzthreads_allowed() && p_mzq > 0 && (long)dwWaitTime > p_mzq)
Bram Moolenaar0f873732019-12-05 20:28:46 +01001740 dwWaitTime = p_mzq; // don't wait longer than 'mzquantum'
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001741# endif
1742# ifdef FEAT_TIMERS
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001743 // When waiting very briefly don't trigger timers.
1744 if (dwWaitTime > 10)
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001745 {
1746 long due_time;
1747
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001748 // Trigger timers and then get the time in msec until the next
1749 // one is due. Wait up to that time.
1750 due_time = check_due_timer();
1751 if (typebuf.tb_change_cnt != tb_change_cnt)
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001752 {
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001753 // timer may have used feedkeys().
1754 return FALSE;
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001755 }
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001756 if (due_time > 0 && dwWaitTime > (DWORD)due_time)
1757 dwWaitTime = due_time;
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001758 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001759# endif
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001760 if (
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001761# ifdef FEAT_CLIENTSERVER
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001762 // Wait for either an event on the console input or a
1763 // message in the client-server window.
1764 msg_wait_for_multiple_objects(1, &g_hConIn, FALSE,
1765 dwWaitTime, QS_SENDMESSAGE) != WAIT_OBJECT_0
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001766# else
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001767 wait_for_single_object(g_hConIn, dwWaitTime)
1768 != WAIT_OBJECT_0
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001769# endif
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001770 )
1771 continue;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001772 }
1773
1774 cRecords = 0;
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001775 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001776
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001777# ifdef FEAT_MBYTE_IME
matveyt4eb19142021-05-20 11:54:10 +02001778 // May have to redraw if the cursor ends up in the wrong place.
1779 // Only when not peeking.
Bram Moolenaar24959102022-05-07 20:01:16 +01001780 if (State == MODE_CMDLINE && msg_row == Rows - 1 && msec != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001781 {
1782 CONSOLE_SCREEN_BUFFER_INFO csbi;
1783
1784 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
1785 {
1786 if (csbi.dwCursorPosition.Y != msg_row)
1787 {
matveyte08795e2021-05-07 15:00:17 +02001788 // The screen is now messed up, must redraw the command
1789 // line and later all the windows.
Bram Moolenaara4d158b2022-08-14 14:17:45 +01001790 redraw_all_later(UPD_CLEAR);
matveyte08795e2021-05-07 15:00:17 +02001791 compute_cmdrow();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001792 redrawcmd();
1793 }
1794 }
1795 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001796# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001797
1798 if (cRecords > 0)
1799 {
1800 if (ir.EventType == KEY_EVENT && ir.Event.KeyEvent.bKeyDown)
1801 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001802# ifdef FEAT_MBYTE_IME
Bram Moolenaar0f873732019-12-05 20:28:46 +01001803 // Windows IME sends two '\n's with only one 'ENTER'. First:
1804 // wVirtualKeyCode == 13. second: wVirtualKeyCode == 0
K.Takata972db232022-02-04 10:45:38 +00001805 if (ir.Event.KeyEvent.uChar.UnicodeChar == 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00001806 && ir.Event.KeyEvent.wVirtualKeyCode == 13)
1807 {
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001808 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001809 continue;
1810 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001811# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001812 if (decode_key_event(&ir.Event.KeyEvent, &ch, &ch2,
1813 NULL, FALSE))
1814 return TRUE;
1815 }
1816
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001817 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001818
1819 if (ir.EventType == FOCUS_EVENT)
1820 handle_focus_event(ir);
1821 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
Bram Moolenaarc33ecb22018-02-11 16:40:45 +01001822 {
Bram Moolenaar78d21da2019-02-17 15:00:52 +01001823 COORD dwSize = ir.Event.WindowBufferSizeEvent.dwSize;
1824
Bram Moolenaar36698e32019-12-11 22:57:40 +01001825 // Only call shell_resized() when the size actually changed to
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001826 // avoid the screen is cleared.
Bram Moolenaar78d21da2019-02-17 15:00:52 +01001827 if (dwSize.X != Columns || dwSize.Y != Rows)
1828 {
1829 CONSOLE_SCREEN_BUFFER_INFO csbi;
1830 GetConsoleScreenBufferInfo(g_hConOut, &csbi);
Bram Moolenaar36698e32019-12-11 22:57:40 +01001831 dwSize.X = csbi.srWindow.Right - csbi.srWindow.Left + 1;
Bram Moolenaar78d21da2019-02-17 15:00:52 +01001832 dwSize.Y = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
Bram Moolenaar36698e32019-12-11 22:57:40 +01001833 if (dwSize.X != Columns || dwSize.Y != Rows)
1834 {
1835 ResizeConBuf(g_hConOut, dwSize);
1836 shell_resized();
1837 }
Bram Moolenaar78d21da2019-02-17 15:00:52 +01001838 }
Bram Moolenaarc33ecb22018-02-11 16:40:45 +01001839 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001840 else if (ir.EventType == MOUSE_EVENT
1841 && decode_mouse_event(&ir.Event.MouseEvent))
1842 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001843 }
1844 else if (msec == 0)
1845 break;
1846 }
1847
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001848# ifdef FEAT_CLIENTSERVER
Bram Moolenaar0f873732019-12-05 20:28:46 +01001849 // Something might have been received while we were waiting.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001850 if (input_available())
1851 return TRUE;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001852# endif
Bram Moolenaarf12d9832016-01-29 21:11:25 +01001853
Bram Moolenaar071d4272004-06-13 20:20:40 +00001854 return FALSE;
1855}
1856
Bram Moolenaar071d4272004-06-13 20:20:40 +00001857/*
1858 * return non-zero if a character is available
1859 */
1860 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001861mch_char_avail(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001862{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001863# ifdef VIMDLL
1864 if (gui.in_use)
1865 return TRUE;
1866# endif
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001867 return WaitForChar(0L, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001868}
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001869
1870# if defined(FEAT_TERMINAL) || defined(PROTO)
1871/*
1872 * Check for any pending input or messages.
1873 */
1874 int
1875mch_check_messages(void)
1876{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001877# ifdef VIMDLL
1878 if (gui.in_use)
1879 return TRUE;
1880# endif
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001881 return WaitForChar(0L, TRUE);
1882}
1883# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001884
1885/*
1886 * Create the console input. Used when reading stdin doesn't work.
1887 */
1888 static void
1889create_conin(void)
1890{
1891 g_hConIn = CreateFile("CONIN$", GENERIC_READ|GENERIC_WRITE,
1892 FILE_SHARE_READ|FILE_SHARE_WRITE,
1893 (LPSECURITY_ATTRIBUTES) NULL,
Bram Moolenaareb3593b2006-04-22 22:33:57 +00001894 OPEN_EXISTING, 0, (HANDLE)NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001895 did_create_conin = TRUE;
1896}
1897
1898/*
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001899 * Get a keystroke or a mouse event, use a blocking wait.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001900 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001901 static WCHAR
1902tgetch(int *pmodifiers, WCHAR *pch2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001903{
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001904 WCHAR ch;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001905
1906 for (;;)
1907 {
1908 INPUT_RECORD ir;
1909 DWORD cRecords = 0;
1910
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001911# ifdef FEAT_CLIENTSERVER
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001912 (void)WaitForChar(-1L, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001913 if (input_available())
1914 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001915 if (g_nMouseClick != -1)
1916 return 0;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001917# endif
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001918 if (read_console_input(g_hConIn, &ir, 1, &cRecords) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001919 {
1920 if (did_create_conin)
1921 read_error_exit();
1922 create_conin();
1923 continue;
1924 }
1925
1926 if (ir.EventType == KEY_EVENT)
1927 {
1928 if (decode_key_event(&ir.Event.KeyEvent, &ch, pch2,
1929 pmodifiers, TRUE))
1930 return ch;
1931 }
1932 else if (ir.EventType == FOCUS_EVENT)
1933 handle_focus_event(ir);
1934 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
1935 shell_resized();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001936 else if (ir.EventType == MOUSE_EVENT)
1937 {
1938 if (decode_mouse_event(&ir.Event.MouseEvent))
1939 return 0;
1940 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001941 }
1942}
Bram Moolenaar0f873732019-12-05 20:28:46 +01001943#endif // !FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00001944
1945
1946/*
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02001947 * mch_inchar(): low-level input function.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001948 * Get one or more characters from the keyboard or the mouse.
1949 * If time == 0, do not wait for characters.
1950 * If time == n, wait a short time for characters.
1951 * If time == -1, wait forever for characters.
1952 * Returns the number of characters read into buf.
1953 */
1954 int
1955mch_inchar(
Bram Moolenaar1266d672017-02-01 13:43:36 +01001956 char_u *buf UNUSED,
1957 int maxlen UNUSED,
1958 long time UNUSED,
1959 int tb_change_cnt UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001960{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001961#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001962
1963 int len;
1964 int c;
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01001965# ifdef VIMDLL
1966// Extra space for maximum three CSIs. E.g. U+1B6DB -> 0xF0 0x9B 0x9B 0x9B.
1967# define TYPEAHEADSPACE 6
1968# else
1969# define TYPEAHEADSPACE 0
1970# endif
1971# define TYPEAHEADLEN (20 + TYPEAHEADSPACE)
Bram Moolenaar0f873732019-12-05 20:28:46 +01001972 static char_u typeahead[TYPEAHEADLEN]; // previously typed bytes.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001973 static int typeaheadlen = 0;
1974
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001975# ifdef VIMDLL
1976 if (gui.in_use)
1977 return 0;
1978# endif
1979
Bram Moolenaar0f873732019-12-05 20:28:46 +01001980 // First use any typeahead that was kept because "buf" was too small.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001981 if (typeaheadlen > 0)
1982 goto theend;
1983
Bram Moolenaar071d4272004-06-13 20:20:40 +00001984 if (time >= 0)
1985 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001986 if (!WaitForChar(time, FALSE)) // no character available
Bram Moolenaar071d4272004-06-13 20:20:40 +00001987 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001988 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01001989 else // time == -1, wait forever
Bram Moolenaar071d4272004-06-13 20:20:40 +00001990 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001991 mch_set_winsize_now(); // Allow winsize changes from now on
Bram Moolenaar071d4272004-06-13 20:20:40 +00001992
Bram Moolenaar3918c952005-03-15 22:34:55 +00001993 /*
1994 * If there is no character available within 2 seconds (default)
1995 * write the autoscript file to disk. Or cause the CursorHold event
1996 * to be triggered.
1997 */
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001998 if (!WaitForChar(p_ut, FALSE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001999 {
Bram Moolenaard35f9712005-12-18 22:02:33 +00002000 if (trigger_cursorhold() && maxlen >= 3)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002001 {
Bram Moolenaar3918c952005-03-15 22:34:55 +00002002 buf[0] = K_SPECIAL;
2003 buf[1] = KS_EXTRA;
2004 buf[2] = (int)KE_CURSORHOLD;
2005 return 3;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002006 }
Bram Moolenaar702517d2005-06-27 22:34:07 +00002007 before_blocking();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002008 }
2009 }
2010
2011 /*
2012 * Try to read as many characters as there are, until the buffer is full.
2013 */
2014
Bram Moolenaar0f873732019-12-05 20:28:46 +01002015 // we will get at least one key. Get more if they are available.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002016 g_fCBrkPressed = FALSE;
2017
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002018# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00002019 if (fdDump)
2020 fputc('[', fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002021# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002022
Bram Moolenaar0f873732019-12-05 20:28:46 +01002023 // Keep looping until there is something in the typeahead buffer and more
2024 // to get and still room in the buffer (up to two bytes for a char and
2025 // three bytes for a modifier).
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02002026 while ((typeaheadlen == 0 || WaitForChar(0L, FALSE))
Bram Moolenaar9f1983d2022-05-12 20:35:35 +01002027 && typeaheadlen + 5 + TYPEAHEADSPACE <= TYPEAHEADLEN)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002028 {
2029 if (typebuf_changed(tb_change_cnt))
2030 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01002031 // "buf" may be invalid now if a client put something in the
2032 // typeahead buffer and "buf" is in the typeahead buffer.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002033 typeaheadlen = 0;
2034 break;
2035 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002036 if (g_nMouseClick != -1)
2037 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002038# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00002039 if (fdDump)
2040 fprintf(fdDump, "{%02x @ %d, %d}",
2041 g_nMouseClick, g_xMouse, g_yMouse);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002042# endif
Christopher Plewright2a46f812022-10-16 19:47:45 +01002043 char_u modifiers = ((char_u *)(&g_nMouseClick))[0];
2044 char_u scroll_dir = ((char_u *)(&g_nMouseClick))[1];
2045
2046 if (scroll_dir == KE_MOUSEDOWN
2047 || scroll_dir == KE_MOUSEUP
2048 || scroll_dir == KE_MOUSELEFT
2049 || scroll_dir == KE_MOUSERIGHT)
2050 {
2051 if (modifiers > 0)
2052 {
2053 typeahead[typeaheadlen++] = CSI;
2054 typeahead[typeaheadlen++] = KS_MODIFIER;
2055 typeahead[typeaheadlen++] = modifiers;
2056 }
2057 typeahead[typeaheadlen++] = CSI;
2058 typeahead[typeaheadlen++] = KS_EXTRA;
2059 typeahead[typeaheadlen++] = scroll_dir;
2060 g_nMouseClick = -1;
2061 }
2062 else
2063 {
2064 typeahead[typeaheadlen++] = ESC + 128;
2065 typeahead[typeaheadlen++] = 'M';
2066 typeahead[typeaheadlen++] = g_nMouseClick;
2067 typeahead[typeaheadlen++] = g_xMouse + '!';
2068 typeahead[typeaheadlen++] = g_yMouse + '!';
2069 g_nMouseClick = -1;
2070 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002071 }
2072 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00002073 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002074 WCHAR ch2 = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002075 int modifiers = 0;
2076
2077 c = tgetch(&modifiers, &ch2);
2078
2079 if (typebuf_changed(tb_change_cnt))
2080 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01002081 // "buf" may be invalid now if a client put something in the
2082 // typeahead buffer and "buf" is in the typeahead buffer.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002083 typeaheadlen = 0;
2084 break;
2085 }
2086
2087 if (c == Ctrl_C && ctrl_c_interrupts)
2088 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002089# if defined(FEAT_CLIENTSERVER)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002090 trash_input_buf();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002091# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002092 got_int = TRUE;
2093 }
2094
Bram Moolenaar071d4272004-06-13 20:20:40 +00002095 if (g_nMouseClick == -1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002096 {
2097 int n = 1;
2098
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002099 if (ch2 == NUL)
2100 {
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01002101 int i, j;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002102 char_u *p;
2103 WCHAR ch[2];
2104
2105 ch[0] = c;
Bram Moolenaar0f873732019-12-05 20:28:46 +01002106 if (c >= 0xD800 && c <= 0xDBFF) // High surrogate
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002107 {
2108 ch[1] = tgetch(&modifiers, &ch2);
2109 n++;
2110 }
2111 p = utf16_to_enc(ch, &n);
2112 if (p != NULL)
2113 {
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01002114 for (i = 0, j = 0; i < n; i++)
2115 {
2116 typeahead[typeaheadlen + j++] = p[i];
2117# ifdef VIMDLL
2118 if (p[i] == CSI)
2119 {
2120 typeahead[typeaheadlen + j++] = KS_EXTRA;
2121 typeahead[typeaheadlen + j++] = KE_CSI;
2122 }
2123# endif
2124 }
2125 n = j;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002126 vim_free(p);
2127 }
2128 }
2129 else
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01002130 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002131 typeahead[typeaheadlen] = c;
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01002132# ifdef VIMDLL
2133 if (c == CSI)
2134 {
2135 typeahead[typeaheadlen + 1] = KS_EXTRA;
2136 typeahead[typeaheadlen + 2] = KE_CSI;
2137 n = 3;
2138 }
2139# endif
2140 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002141 if (ch2 != NUL)
2142 {
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +02002143 if (c == K_NUL)
Bram Moolenaarfeeb4d02017-12-05 15:14:46 +01002144 {
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +02002145 switch (ch2)
2146 {
2147 case (WCHAR)'\324': // SHIFT+Insert
2148 case (WCHAR)'\325': // CTRL+Insert
2149 case (WCHAR)'\327': // SHIFT+Delete
2150 case (WCHAR)'\330': // CTRL+Delete
2151 typeahead[typeaheadlen + n] = (char_u)ch2;
2152 n++;
2153 break;
2154
2155 default:
2156 typeahead[typeaheadlen + n] = 3;
2157 typeahead[typeaheadlen + n + 1] = (char_u)ch2;
2158 n += 2;
2159 break;
2160 }
Bram Moolenaarfeeb4d02017-12-05 15:14:46 +01002161 }
2162 else
2163 {
2164 typeahead[typeaheadlen + n] = 3;
2165 typeahead[typeaheadlen + n + 1] = (char_u)ch2;
2166 n += 2;
2167 }
Bram Moolenaar45500912014-07-09 20:51:07 +02002168 }
2169
Bram Moolenaar0f873732019-12-05 20:28:46 +01002170 // Use the ALT key to set the 8th bit of the character
2171 // when it's one byte, the 8th bit isn't set yet and not
2172 // using a double-byte encoding (would become a lead
2173 // byte).
Bram Moolenaar071d4272004-06-13 20:20:40 +00002174 if ((modifiers & MOD_MASK_ALT)
2175 && n == 1
2176 && (typeahead[typeaheadlen] & 0x80) == 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00002177 && !enc_dbcs
Bram Moolenaar071d4272004-06-13 20:20:40 +00002178 )
2179 {
Bram Moolenaar85a3e5c2007-11-20 16:22:16 +00002180 n = (*mb_char2bytes)(typeahead[typeaheadlen] | 0x80,
2181 typeahead + typeaheadlen);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002182 modifiers &= ~MOD_MASK_ALT;
2183 }
2184
2185 if (modifiers != 0)
2186 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01002187 // Prepend modifiers to the character.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002188 mch_memmove(typeahead + typeaheadlen + 3,
2189 typeahead + typeaheadlen, n);
2190 typeahead[typeaheadlen++] = K_SPECIAL;
2191 typeahead[typeaheadlen++] = (char_u)KS_MODIFIER;
2192 typeahead[typeaheadlen++] = modifiers;
2193 }
2194
2195 typeaheadlen += n;
2196
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002197# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00002198 if (fdDump)
2199 fputc(c, fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002200# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002201 }
2202 }
2203 }
2204
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002205# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00002206 if (fdDump)
2207 {
2208 fputs("]\n", fdDump);
2209 fflush(fdDump);
2210 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002211# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002212
Bram Moolenaar071d4272004-06-13 20:20:40 +00002213theend:
Bram Moolenaar0f873732019-12-05 20:28:46 +01002214 // Move typeahead to "buf", as much as fits.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002215 len = 0;
2216 while (len < maxlen && typeaheadlen > 0)
2217 {
2218 buf[len++] = typeahead[0];
2219 mch_memmove(typeahead, typeahead + 1, --typeaheadlen);
2220 }
K.Takata6e1d31e2022-02-03 13:05:32 +00002221# ifdef FEAT_JOB_CHANNEL
Bram Moolenaar7ca86fe2020-09-03 19:25:11 +02002222 if (len > 0)
2223 {
2224 buf[len] = NUL;
2225 ch_log(NULL, "raw key input: \"%s\"", buf);
2226 }
K.Takata6e1d31e2022-02-03 13:05:32 +00002227# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002228 return len;
2229
Bram Moolenaar0f873732019-12-05 20:28:46 +01002230#else // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00002231 return 0;
Bram Moolenaar0f873732019-12-05 20:28:46 +01002232#endif // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00002233}
2234
Bram Moolenaar82881492012-11-20 16:53:39 +01002235#ifndef PROTO
2236# ifndef __MINGW32__
Bram Moolenaar0f873732019-12-05 20:28:46 +01002237# include <shellapi.h> // required for FindExecutable()
Bram Moolenaar82881492012-11-20 16:53:39 +01002238# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002239#endif
2240
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002241/*
Bram Moolenaar95da1362020-05-30 18:37:55 +02002242 * Return TRUE if "name" is an executable file, FALSE if not or it doesn't exist.
Bram Moolenaar43663192017-03-05 14:29:12 +01002243 * When returning TRUE and "path" is not NULL save the path and set "*path" to
2244 * the allocated memory.
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00002245 * TODO: Should somehow check if it's really executable.
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002246 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002247 static int
Bram Moolenaar95da1362020-05-30 18:37:55 +02002248executable_file(char *name, char_u **path)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002249{
LemonBoy40fd7e62022-05-05 20:18:16 +01002250 int attrs = win32_getattrs((char_u *)name);
2251
2252 // The file doesn't exist or is a folder.
2253 if (attrs == -1 || (attrs & FILE_ATTRIBUTE_DIRECTORY))
2254 return FALSE;
2255 // Check if the file is an AppExecLink, a special alias used by Windows
2256 // Store for its apps.
2257 if (attrs & FILE_ATTRIBUTE_REPARSE_POINT)
Bram Moolenaar43663192017-03-05 14:29:12 +01002258 {
LemonBoy40fd7e62022-05-05 20:18:16 +01002259 char_u *res = resolve_appexeclink((char_u *)name);
2260 if (res == NULL)
2261 return FALSE;
2262 // The path is already absolute.
Bram Moolenaar95da1362020-05-30 18:37:55 +02002263 if (path != NULL)
LemonBoy40fd7e62022-05-05 20:18:16 +01002264 *path = res;
2265 else
2266 vim_free(res);
Bram Moolenaar95da1362020-05-30 18:37:55 +02002267 }
LemonBoy40fd7e62022-05-05 20:18:16 +01002268 else if (path != NULL)
2269 *path = FullName_save((char_u *)name, FALSE);
2270 return TRUE;
Bram Moolenaar95da1362020-05-30 18:37:55 +02002271}
2272
2273/*
2274 * If "use_path" is TRUE: Return TRUE if "name" is in $PATH.
2275 * If "use_path" is FALSE: Return TRUE if "name" exists.
2276 * If "use_pathext" is TRUE search "name" with extensions in $PATHEXT.
2277 * When returning TRUE and "path" is not NULL save the path and set "*path" to
2278 * the allocated memory.
2279 */
2280 static int
2281executable_exists(char *name, char_u **path, int use_path, int use_pathext)
2282{
2283 // WinNT and later can use _MAX_PATH wide characters for a pathname, which
2284 // means that the maximum pathname is _MAX_PATH * 3 bytes when 'enc' is
2285 // UTF-8.
2286 char_u buf[_MAX_PATH * 3];
2287 size_t len = STRLEN(name);
2288 size_t tmplen;
2289 char_u *p, *e, *e2;
2290 char_u *pathbuf = NULL;
2291 char_u *pathext = NULL;
2292 char_u *pathextbuf = NULL;
Mike Williamsa3d1b292021-06-30 20:56:00 +02002293 char_u *shname = NULL;
Bram Moolenaar95da1362020-05-30 18:37:55 +02002294 int noext = FALSE;
2295 int retval = FALSE;
2296
2297 if (len >= sizeof(buf)) // safety check
Bram Moolenaar43663192017-03-05 14:29:12 +01002298 return FALSE;
Bram Moolenaar95da1362020-05-30 18:37:55 +02002299
2300 // Using the name directly when a Unix-shell like 'shell'.
Mike Williamsa3d1b292021-06-30 20:56:00 +02002301 shname = gettail(p_sh);
2302 if (strstr((char *)shname, "sh") != NULL &&
2303 !(strstr((char *)shname, "powershell") != NULL
2304 || strstr((char *)shname, "pwsh") != NULL))
Bram Moolenaar95da1362020-05-30 18:37:55 +02002305 noext = TRUE;
2306
2307 if (use_pathext)
2308 {
2309 pathext = mch_getenv("PATHEXT");
2310 if (pathext == NULL)
2311 pathext = (char_u *)".com;.exe;.bat;.cmd";
2312
2313 if (noext == FALSE)
2314 {
2315 /*
2316 * Loop over all extensions in $PATHEXT.
2317 * Check "name" ends with extension.
2318 */
2319 p = pathext;
2320 while (*p)
2321 {
2322 if (p[0] == ';'
2323 || (p[0] == '.' && (p[1] == NUL || p[1] == ';')))
2324 {
2325 // Skip empty or single ".".
2326 ++p;
2327 continue;
2328 }
2329 e = vim_strchr(p, ';');
2330 if (e == NULL)
2331 e = p + STRLEN(p);
2332 tmplen = e - p;
2333
2334 if (_strnicoll(name + len - tmplen, (char *)p, tmplen) == 0)
2335 {
2336 noext = TRUE;
2337 break;
2338 }
2339
2340 p = e;
2341 }
2342 }
Bram Moolenaar43663192017-03-05 14:29:12 +01002343 }
2344
Dominique Pelleaf4a61a2021-12-27 17:21:41 +00002345 // Prepend single "." to pathext, it means no extension added.
Bram Moolenaar95da1362020-05-30 18:37:55 +02002346 if (pathext == NULL)
2347 pathext = (char_u *)".";
2348 else if (noext == TRUE)
2349 {
2350 if (pathextbuf == NULL)
2351 pathextbuf = alloc(STRLEN(pathext) + 3);
2352 if (pathextbuf == NULL)
2353 {
2354 retval = FALSE;
2355 goto theend;
2356 }
2357 STRCPY(pathextbuf, ".;");
2358 STRCAT(pathextbuf, pathext);
2359 pathext = pathextbuf;
2360 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002361
Bram Moolenaar95da1362020-05-30 18:37:55 +02002362 // Use $PATH when "use_path" is TRUE and "name" is basename.
2363 if (use_path && gettail((char_u *)name) == (char_u *)name)
2364 {
2365 p = mch_getenv("PATH");
2366 if (p != NULL)
2367 {
2368 pathbuf = alloc(STRLEN(p) + 3);
2369 if (pathbuf == NULL)
2370 {
2371 retval = FALSE;
2372 goto theend;
2373 }
Yasuhiro Matsumoto05cf63e2022-05-03 11:02:28 +01002374
2375 if (mch_getenv("NoDefaultCurrentDirectoryInExePath") == NULL)
2376 STRCPY(pathbuf, ".;");
2377 else
2378 *pathbuf = NUL;
Bram Moolenaar95da1362020-05-30 18:37:55 +02002379 STRCAT(pathbuf, p);
2380 }
2381 }
2382
2383 /*
2384 * Walk through all entries in $PATH to check if "name" exists there and
2385 * is an executable file.
2386 */
2387 p = (pathbuf != NULL) ? pathbuf : (char_u *)".";
2388 while (*p)
2389 {
2390 if (*p == ';') // Skip empty entry
2391 {
2392 ++p;
2393 continue;
2394 }
2395 e = vim_strchr(p, ';');
2396 if (e == NULL)
2397 e = p + STRLEN(p);
2398
2399 if (e - p + len + 2 > sizeof(buf))
2400 {
2401 retval = FALSE;
2402 goto theend;
2403 }
2404 // A single "." that means current dir.
2405 if (e - p == 1 && *p == '.')
2406 STRCPY(buf, name);
2407 else
2408 {
2409 vim_strncpy(buf, p, e - p);
2410 add_pathsep(buf);
2411 STRCAT(buf, name);
2412 }
2413 tmplen = STRLEN(buf);
2414
2415 /*
2416 * Loop over all extensions in $PATHEXT.
2417 * Check "name" with extension added.
2418 */
2419 p = pathext;
2420 while (*p)
2421 {
2422 if (*p == ';')
2423 {
2424 // Skip empty entry
2425 ++p;
2426 continue;
2427 }
2428 e2 = vim_strchr(p, (int)';');
2429 if (e2 == NULL)
2430 e2 = p + STRLEN(p);
2431
2432 if (!(p[0] == '.' && (p[1] == NUL || p[1] == ';')))
2433 {
2434 // Not a single "." that means no extension is added.
2435 if (e2 - p + tmplen + 1 > sizeof(buf))
2436 {
2437 retval = FALSE;
2438 goto theend;
2439 }
2440 vim_strncpy(buf + tmplen, p, e2 - p);
2441 }
2442 if (executable_file((char *)buf, path))
2443 {
2444 retval = TRUE;
2445 goto theend;
2446 }
2447
2448 p = e2;
2449 }
2450
2451 p = e;
2452 }
2453
2454theend:
2455 free(pathextbuf);
2456 free(pathbuf);
2457 return retval;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002458}
2459
Bram Moolenaar1eed5322019-02-26 17:03:54 +01002460#if (defined(__MINGW32__) && __MSVCRT_VERSION__ >= 0x800) || \
2461 (defined(_MSC_VER) && _MSC_VER >= 1400)
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002462/*
2463 * Bad parameter handler.
2464 *
2465 * Certain MS CRT functions will intentionally crash when passed invalid
2466 * parameters to highlight possible security holes. Setting this function as
2467 * the bad parameter handler will prevent the crash.
2468 *
2469 * In debug builds the parameters contain CRT information that might help track
2470 * down the source of a problem, but in non-debug builds the arguments are all
2471 * NULL/0. Debug builds will also produce assert dialogs from the CRT, it is
2472 * worth allowing these to make debugging of issues easier.
2473 */
2474 static void
Yegappan Lakshmanana34b4462022-06-11 10:43:26 +01002475bad_param_handler(const wchar_t *expression UNUSED,
2476 const wchar_t *function UNUSED,
2477 const wchar_t *file UNUSED,
2478 unsigned int line UNUSED,
2479 uintptr_t pReserved UNUSED)
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002480{
2481}
2482
2483# define SET_INVALID_PARAM_HANDLER \
2484 ((void)_set_invalid_parameter_handler(bad_param_handler))
2485#else
2486# define SET_INVALID_PARAM_HANDLER
2487#endif
2488
Bram Moolenaar4f974752019-02-17 17:44:42 +01002489#ifdef FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00002490
2491/*
2492 * GUI version of mch_init().
2493 */
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002494 static void
2495mch_init_g(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002496{
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002497# ifndef __MINGW32__
Bram Moolenaar071d4272004-06-13 20:20:40 +00002498 extern int _fmode;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002499# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002500
Bram Moolenaar0f873732019-12-05 20:28:46 +01002501 // Silently handle invalid parameters to CRT functions
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002502 SET_INVALID_PARAM_HANDLER;
2503
Bram Moolenaar0f873732019-12-05 20:28:46 +01002504 // Let critical errors result in a failure, not in a dialog box. Required
2505 // for the timestamp test to work on removed floppies.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002506 SetErrorMode(SEM_FAILCRITICALERRORS);
2507
Bram Moolenaar0f873732019-12-05 20:28:46 +01002508 _fmode = O_BINARY; // we do our own CR-LF translation
Bram Moolenaar071d4272004-06-13 20:20:40 +00002509
Bram Moolenaar0f873732019-12-05 20:28:46 +01002510 // Specify window size. Is there a place to get the default from?
Bram Moolenaar071d4272004-06-13 20:20:40 +00002511 Rows = 25;
2512 Columns = 80;
2513
Bram Moolenaar0f873732019-12-05 20:28:46 +01002514 // Look for 'vimrun'
Bram Moolenaar071d4272004-06-13 20:20:40 +00002515 {
2516 char_u vimrun_location[_MAX_PATH + 4];
2517
Bram Moolenaar0f873732019-12-05 20:28:46 +01002518 // First try in same directory as gvim.exe
Bram Moolenaar071d4272004-06-13 20:20:40 +00002519 STRCPY(vimrun_location, exe_name);
2520 STRCPY(gettail(vimrun_location), "vimrun.exe");
2521 if (mch_getperm(vimrun_location) >= 0)
2522 {
2523 if (*skiptowhite(vimrun_location) != NUL)
2524 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01002525 // Enclose path with white space in double quotes.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002526 mch_memmove(vimrun_location + 1, vimrun_location,
2527 STRLEN(vimrun_location) + 1);
2528 *vimrun_location = '"';
2529 STRCPY(gettail(vimrun_location), "vimrun\" ");
2530 }
2531 else
2532 STRCPY(gettail(vimrun_location), "vimrun ");
2533
2534 vimrun_path = (char *)vim_strsave(vimrun_location);
2535 s_dont_use_vimrun = FALSE;
2536 }
Bram Moolenaar95da1362020-05-30 18:37:55 +02002537 else if (executable_exists("vimrun.exe", NULL, TRUE, FALSE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002538 s_dont_use_vimrun = FALSE;
2539
Bram Moolenaar0f873732019-12-05 20:28:46 +01002540 // Don't give the warning for a missing vimrun.exe right now, but only
2541 // when vimrun was supposed to be used. Don't bother people that do
2542 // not need vimrun.exe.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002543 if (s_dont_use_vimrun)
2544 need_vimrun_warning = TRUE;
2545 }
2546
2547 /*
2548 * If "finstr.exe" doesn't exist, use "grep -n" for 'grepprg'.
2549 * Otherwise the default "findstr /n" is used.
2550 */
Bram Moolenaar95da1362020-05-30 18:37:55 +02002551 if (!executable_exists("findstr.exe", NULL, TRUE, FALSE))
Bram Moolenaar75ab5902022-04-18 15:36:40 +01002552 set_option_value_give_err((char_u *)"grepprg",
2553 0, (char_u *)"grep -n", 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002554
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002555# ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01002556 win_clip_init();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002557# endif
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01002558
2559 vtp_flag_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002560}
2561
2562
Bram Moolenaar0f873732019-12-05 20:28:46 +01002563#endif // FEAT_GUI_MSWIN
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002564
2565#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002566
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002567# define SRWIDTH(sr) ((sr).Right - (sr).Left + 1)
2568# define SRHEIGHT(sr) ((sr).Bottom - (sr).Top + 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002569
2570/*
2571 * ClearConsoleBuffer()
2572 * Description:
2573 * Clears the entire contents of the console screen buffer, using the
2574 * specified attribute.
2575 * Returns:
2576 * TRUE on success
2577 */
2578 static BOOL
2579ClearConsoleBuffer(WORD wAttribute)
2580{
2581 CONSOLE_SCREEN_BUFFER_INFO csbi;
2582 COORD coord;
2583 DWORD NumCells, dummy;
2584
2585 if (!GetConsoleScreenBufferInfo(g_hConOut, &csbi))
2586 return FALSE;
2587
2588 NumCells = csbi.dwSize.X * csbi.dwSize.Y;
2589 coord.X = 0;
2590 coord.Y = 0;
2591 if (!FillConsoleOutputCharacter(g_hConOut, ' ', NumCells,
2592 coord, &dummy))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002593 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002594 if (!FillConsoleOutputAttribute(g_hConOut, wAttribute, NumCells,
2595 coord, &dummy))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002596 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002597
2598 return TRUE;
2599}
2600
2601/*
2602 * FitConsoleWindow()
2603 * Description:
2604 * Checks if the console window will fit within given buffer dimensions.
2605 * Also, if requested, will shrink the window to fit.
2606 * Returns:
2607 * TRUE on success
2608 */
2609 static BOOL
2610FitConsoleWindow(
2611 COORD dwBufferSize,
2612 BOOL WantAdjust)
2613{
2614 CONSOLE_SCREEN_BUFFER_INFO csbi;
2615 COORD dwWindowSize;
2616 BOOL NeedAdjust = FALSE;
2617
2618 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
2619 {
2620 /*
2621 * A buffer resize will fail if the current console window does
2622 * not lie completely within that buffer. To avoid this, we might
2623 * have to move and possibly shrink the window.
2624 */
2625 if (csbi.srWindow.Right >= dwBufferSize.X)
2626 {
2627 dwWindowSize.X = SRWIDTH(csbi.srWindow);
2628 if (dwWindowSize.X > dwBufferSize.X)
2629 dwWindowSize.X = dwBufferSize.X;
2630 csbi.srWindow.Right = dwBufferSize.X - 1;
2631 csbi.srWindow.Left = dwBufferSize.X - dwWindowSize.X;
2632 NeedAdjust = TRUE;
2633 }
2634 if (csbi.srWindow.Bottom >= dwBufferSize.Y)
2635 {
2636 dwWindowSize.Y = SRHEIGHT(csbi.srWindow);
2637 if (dwWindowSize.Y > dwBufferSize.Y)
2638 dwWindowSize.Y = dwBufferSize.Y;
2639 csbi.srWindow.Bottom = dwBufferSize.Y - 1;
2640 csbi.srWindow.Top = dwBufferSize.Y - dwWindowSize.Y;
2641 NeedAdjust = TRUE;
2642 }
2643 if (NeedAdjust && WantAdjust)
2644 {
2645 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &csbi.srWindow))
2646 return FALSE;
2647 }
2648 return TRUE;
2649 }
2650
2651 return FALSE;
2652}
2653
2654typedef struct ConsoleBufferStruct
2655{
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002656 BOOL IsValid;
2657 CONSOLE_SCREEN_BUFFER_INFO Info;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002658 PCHAR_INFO Buffer;
2659 COORD BufferSize;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002660 PSMALL_RECT Regions;
2661 int NumRegions;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002662} ConsoleBuffer;
2663
2664/*
2665 * SaveConsoleBuffer()
2666 * Description:
2667 * Saves important information about the console buffer, including the
2668 * actual buffer contents. The saved information is suitable for later
2669 * restoration by RestoreConsoleBuffer().
2670 * Returns:
2671 * TRUE if all information was saved; FALSE otherwise
2672 * If FALSE, still sets cb->IsValid if buffer characteristics were saved.
2673 */
2674 static BOOL
2675SaveConsoleBuffer(
2676 ConsoleBuffer *cb)
2677{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002678 DWORD NumCells;
2679 COORD BufferCoord;
2680 SMALL_RECT ReadRegion;
2681 WORD Y, Y_incr;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002682 int i, numregions;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002683
Bram Moolenaar071d4272004-06-13 20:20:40 +00002684 if (cb == NULL)
2685 return FALSE;
2686
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002687 if (!GetConsoleScreenBufferInfo(g_hConOut, &cb->Info))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002688 {
2689 cb->IsValid = FALSE;
2690 return FALSE;
2691 }
2692 cb->IsValid = TRUE;
2693
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002694 /*
2695 * Allocate a buffer large enough to hold the entire console screen
2696 * buffer. If this ConsoleBuffer structure has already been initialized
2697 * with a buffer of the correct size, then just use that one.
2698 */
2699 if (!cb->IsValid || cb->Buffer == NULL ||
2700 cb->BufferSize.X != cb->Info.dwSize.X ||
2701 cb->BufferSize.Y != cb->Info.dwSize.Y)
2702 {
2703 cb->BufferSize.X = cb->Info.dwSize.X;
2704 cb->BufferSize.Y = cb->Info.dwSize.Y;
2705 NumCells = cb->BufferSize.X * cb->BufferSize.Y;
2706 vim_free(cb->Buffer);
Bram Moolenaarc799fe22019-05-28 23:08:19 +02002707 cb->Buffer = ALLOC_MULT(CHAR_INFO, NumCells);
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002708 if (cb->Buffer == NULL)
2709 return FALSE;
2710 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002711
2712 /*
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002713 * We will now copy the console screen buffer into our buffer.
2714 * ReadConsoleOutput() seems to be limited as far as how much you
2715 * can read at a time. Empirically, this number seems to be about
2716 * 12000 cells (rows * columns). Start at position (0, 0) and copy
2717 * in chunks until it is all copied. The chunks will all have the
2718 * same horizontal characteristics, so initialize them now. The
2719 * height of each chunk will be (12000 / width).
Bram Moolenaar071d4272004-06-13 20:20:40 +00002720 */
Bram Moolenaar61594242015-09-01 20:23:37 +02002721 BufferCoord.X = 0;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002722 ReadRegion.Left = 0;
2723 ReadRegion.Right = cb->Info.dwSize.X - 1;
2724 Y_incr = 12000 / cb->Info.dwSize.X;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002725
2726 numregions = (cb->Info.dwSize.Y + Y_incr - 1) / Y_incr;
2727 if (cb->Regions == NULL || numregions != cb->NumRegions)
2728 {
2729 cb->NumRegions = numregions;
2730 vim_free(cb->Regions);
Bram Moolenaarc799fe22019-05-28 23:08:19 +02002731 cb->Regions = ALLOC_MULT(SMALL_RECT, cb->NumRegions);
Bram Moolenaar444fda22017-08-11 20:37:00 +02002732 if (cb->Regions == NULL)
2733 {
Bram Moolenaard23a8232018-02-10 18:45:26 +01002734 VIM_CLEAR(cb->Buffer);
Bram Moolenaar444fda22017-08-11 20:37:00 +02002735 return FALSE;
2736 }
2737 }
2738
2739 for (i = 0, Y = 0; i < cb->NumRegions; i++, Y += Y_incr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002740 {
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002741 /*
2742 * Read into position (0, Y) in our buffer.
2743 */
2744 BufferCoord.Y = Y;
2745 /*
2746 * Read the region whose top left corner is (0, Y) and whose bottom
2747 * right corner is (width - 1, Y + Y_incr - 1). This should define
2748 * a region of size width by Y_incr. Don't worry if this region is
2749 * too large for the remaining buffer; it will be cropped.
2750 */
2751 ReadRegion.Top = Y;
2752 ReadRegion.Bottom = Y + Y_incr - 1;
Bram Moolenaar0f873732019-12-05 20:28:46 +01002753 if (!ReadConsoleOutputW(g_hConOut, // output handle
2754 cb->Buffer, // our buffer
2755 cb->BufferSize, // dimensions of our buffer
2756 BufferCoord, // offset in our buffer
2757 &ReadRegion)) // region to save
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002758 {
Bram Moolenaard23a8232018-02-10 18:45:26 +01002759 VIM_CLEAR(cb->Buffer);
2760 VIM_CLEAR(cb->Regions);
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002761 return FALSE;
2762 }
Bram Moolenaar444fda22017-08-11 20:37:00 +02002763 cb->Regions[i] = ReadRegion;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002764 }
2765
2766 return TRUE;
2767}
2768
2769/*
2770 * RestoreConsoleBuffer()
2771 * Description:
2772 * Restores important information about the console buffer, including the
2773 * actual buffer contents, if desired. The information to restore is in
2774 * the same format used by SaveConsoleBuffer().
2775 * Returns:
2776 * TRUE on success
2777 */
2778 static BOOL
2779RestoreConsoleBuffer(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002780 ConsoleBuffer *cb,
2781 BOOL RestoreScreen)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002782{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002783 COORD BufferCoord;
2784 SMALL_RECT WriteRegion;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002785 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002786
2787 if (cb == NULL || !cb->IsValid)
2788 return FALSE;
2789
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002790 /*
2791 * Before restoring the buffer contents, clear the current buffer, and
2792 * restore the cursor position and window information. Doing this now
2793 * prevents old buffer contents from "flashing" onto the screen.
2794 */
2795 if (RestoreScreen)
2796 ClearConsoleBuffer(cb->Info.wAttributes);
2797
2798 FitConsoleWindow(cb->Info.dwSize, TRUE);
2799 if (!SetConsoleScreenBufferSize(g_hConOut, cb->Info.dwSize))
2800 return FALSE;
2801 if (!SetConsoleTextAttribute(g_hConOut, cb->Info.wAttributes))
2802 return FALSE;
2803
2804 if (!RestoreScreen)
2805 {
2806 /*
2807 * No need to restore the screen buffer contents, so we're done.
2808 */
2809 return TRUE;
2810 }
2811
2812 if (!SetConsoleCursorPosition(g_hConOut, cb->Info.dwCursorPosition))
2813 return FALSE;
2814 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &cb->Info.srWindow))
2815 return FALSE;
2816
2817 /*
2818 * Restore the screen buffer contents.
2819 */
2820 if (cb->Buffer != NULL)
2821 {
Bram Moolenaar444fda22017-08-11 20:37:00 +02002822 for (i = 0; i < cb->NumRegions; i++)
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002823 {
Bram Moolenaar444fda22017-08-11 20:37:00 +02002824 BufferCoord.X = cb->Regions[i].Left;
2825 BufferCoord.Y = cb->Regions[i].Top;
2826 WriteRegion = cb->Regions[i];
Bram Moolenaar0f873732019-12-05 20:28:46 +01002827 if (!WriteConsoleOutputW(g_hConOut, // output handle
2828 cb->Buffer, // our buffer
2829 cb->BufferSize, // dimensions of our buffer
2830 BufferCoord, // offset in our buffer
2831 &WriteRegion)) // region to restore
Bram Moolenaar444fda22017-08-11 20:37:00 +02002832 return FALSE;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002833 }
2834 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002835
2836 return TRUE;
2837}
2838
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002839# define FEAT_RESTORE_ORIG_SCREEN
2840# ifdef FEAT_RESTORE_ORIG_SCREEN
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002841static ConsoleBuffer g_cbOrig = { 0 };
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002842# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002843static ConsoleBuffer g_cbNonTermcap = { 0 };
2844static ConsoleBuffer g_cbTermcap = { 0 };
2845
Bram Moolenaar071d4272004-06-13 20:20:40 +00002846char g_szOrigTitle[256] = { 0 };
Bram Moolenaar0f873732019-12-05 20:28:46 +01002847HWND g_hWnd = NULL; // also used in os_mswin.c
Bram Moolenaar071d4272004-06-13 20:20:40 +00002848static HICON g_hOrigIconSmall = NULL;
2849static HICON g_hOrigIcon = NULL;
2850static HICON g_hVimIcon = NULL;
2851static BOOL g_fCanChangeIcon = FALSE;
2852
Bram Moolenaar071d4272004-06-13 20:20:40 +00002853/*
2854 * GetConsoleIcon()
2855 * Description:
2856 * Attempts to retrieve the small icon and/or the big icon currently in
2857 * use by a given window.
2858 * Returns:
2859 * TRUE on success
2860 */
2861 static BOOL
2862GetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002863 HWND hWnd,
2864 HICON *phIconSmall,
2865 HICON *phIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002866{
2867 if (hWnd == NULL)
2868 return FALSE;
2869
2870 if (phIconSmall != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002871 *phIconSmall = (HICON)SendMessage(hWnd, WM_GETICON,
2872 (WPARAM)ICON_SMALL, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002873 if (phIcon != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002874 *phIcon = (HICON)SendMessage(hWnd, WM_GETICON,
2875 (WPARAM)ICON_BIG, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002876 return TRUE;
2877}
2878
2879/*
2880 * SetConsoleIcon()
2881 * Description:
2882 * Attempts to change the small icon and/or the big icon currently in
2883 * use by a given window.
2884 * Returns:
2885 * TRUE on success
2886 */
2887 static BOOL
2888SetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002889 HWND hWnd,
2890 HICON hIconSmall,
2891 HICON hIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002892{
Bram Moolenaar071d4272004-06-13 20:20:40 +00002893 if (hWnd == NULL)
2894 return FALSE;
2895
2896 if (hIconSmall != NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002897 SendMessage(hWnd, WM_SETICON,
2898 (WPARAM)ICON_SMALL, (LPARAM)hIconSmall);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002899 if (hIcon != NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002900 SendMessage(hWnd, WM_SETICON,
2901 (WPARAM)ICON_BIG, (LPARAM) hIcon);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002902 return TRUE;
2903}
2904
2905/*
2906 * SaveConsoleTitleAndIcon()
2907 * Description:
2908 * Saves the current console window title in g_szOrigTitle, for later
2909 * restoration. Also, attempts to obtain a handle to the console window,
2910 * and use it to save the small and big icons currently in use by the
2911 * console window. This is not always possible on some versions of Windows;
2912 * nor is it possible when running Vim remotely using Telnet (since the
2913 * console window the user sees is owned by a remote process).
2914 */
2915 static void
2916SaveConsoleTitleAndIcon(void)
2917{
Bram Moolenaar0f873732019-12-05 20:28:46 +01002918 // Save the original title.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002919 if (!GetConsoleTitle(g_szOrigTitle, sizeof(g_szOrigTitle)))
2920 return;
2921
2922 /*
2923 * Obtain a handle to the console window using GetConsoleWindow() from
2924 * KERNEL32.DLL; we need to handle in order to change the window icon.
2925 * This function only exists on NT-based Windows, starting with Windows
2926 * 2000. On older operating systems, we can't change the window icon
2927 * anyway.
2928 */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02002929 g_hWnd = GetConsoleWindow();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002930 if (g_hWnd == NULL)
2931 return;
2932
Bram Moolenaar0f873732019-12-05 20:28:46 +01002933 // Save the original console window icon.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002934 GetConsoleIcon(g_hWnd, &g_hOrigIconSmall, &g_hOrigIcon);
2935 if (g_hOrigIconSmall == NULL || g_hOrigIcon == NULL)
2936 return;
2937
Bram Moolenaar0f873732019-12-05 20:28:46 +01002938 // Extract the first icon contained in the Vim executable.
K.Takata2da11a42022-09-10 13:03:12 +01002939 if (
2940# ifdef FEAT_LIBCALL
2941 mch_icon_load((HANDLE *)&g_hVimIcon) == FAIL ||
2942# endif
2943 g_hVimIcon == NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002944 g_hVimIcon = ExtractIcon(NULL, (LPCSTR)exe_name, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002945 if (g_hVimIcon != NULL)
2946 g_fCanChangeIcon = TRUE;
2947}
Bram Moolenaar071d4272004-06-13 20:20:40 +00002948
2949static int g_fWindInitCalled = FALSE;
2950static int g_fTermcapMode = FALSE;
2951static CONSOLE_CURSOR_INFO g_cci;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002952
2953/*
2954 * non-GUI version of mch_init().
2955 */
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002956 static void
2957mch_init_c(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002958{
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002959# ifndef FEAT_RESTORE_ORIG_SCREEN
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002960 CONSOLE_SCREEN_BUFFER_INFO csbi;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002961# endif
2962# ifndef __MINGW32__
Bram Moolenaar071d4272004-06-13 20:20:40 +00002963 extern int _fmode;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002964# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002965
Bram Moolenaar0f873732019-12-05 20:28:46 +01002966 // Silently handle invalid parameters to CRT functions
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002967 SET_INVALID_PARAM_HANDLER;
2968
Bram Moolenaar0f873732019-12-05 20:28:46 +01002969 // Let critical errors result in a failure, not in a dialog box. Required
2970 // for the timestamp test to work on removed floppies.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002971 SetErrorMode(SEM_FAILCRITICALERRORS);
2972
Bram Moolenaar0f873732019-12-05 20:28:46 +01002973 _fmode = O_BINARY; // we do our own CR-LF translation
Bram Moolenaar071d4272004-06-13 20:20:40 +00002974 out_flush();
2975
Bram Moolenaar0f873732019-12-05 20:28:46 +01002976 // Obtain handles for the standard Console I/O devices
Bram Moolenaar071d4272004-06-13 20:20:40 +00002977 if (read_cmd_fd == 0)
2978 g_hConIn = GetStdHandle(STD_INPUT_HANDLE);
2979 else
2980 create_conin();
2981 g_hConOut = GetStdHandle(STD_OUTPUT_HANDLE);
2982
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002983# ifdef FEAT_RESTORE_ORIG_SCREEN
Bram Moolenaar0f873732019-12-05 20:28:46 +01002984 // Save the initial console buffer for later restoration
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002985 SaveConsoleBuffer(&g_cbOrig);
2986 g_attrCurrent = g_attrDefault = g_cbOrig.Info.wAttributes;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002987# else
Bram Moolenaar0f873732019-12-05 20:28:46 +01002988 // Get current text attributes
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002989 GetConsoleScreenBufferInfo(g_hConOut, &csbi);
2990 g_attrCurrent = g_attrDefault = csbi.wAttributes;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002991# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002992 if (cterm_normal_fg_color == 0)
2993 cterm_normal_fg_color = (g_attrCurrent & 0xf) + 1;
2994 if (cterm_normal_bg_color == 0)
2995 cterm_normal_bg_color = ((g_attrCurrent >> 4) & 0xf) + 1;
2996
Bram Moolenaarbdace832019-03-02 10:13:42 +01002997 // Fg and Bg color index number at startup
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02002998 g_color_index_fg = g_attrDefault & 0xf;
2999 g_color_index_bg = (g_attrDefault >> 4) & 0xf;
3000
Bram Moolenaar0f873732019-12-05 20:28:46 +01003001 // set termcap codes to current text attributes
Bram Moolenaar071d4272004-06-13 20:20:40 +00003002 update_tcap(g_attrCurrent);
3003
3004 GetConsoleCursorInfo(g_hConOut, &g_cci);
3005 GetConsoleMode(g_hConIn, &g_cmodein);
3006 GetConsoleMode(g_hConOut, &g_cmodeout);
3007
Bram Moolenaar071d4272004-06-13 20:20:40 +00003008 SaveConsoleTitleAndIcon();
3009 /*
3010 * Set both the small and big icons of the console window to Vim's icon.
3011 * Note that Vim presently only has one size of icon (32x32), but it
3012 * automatically gets scaled down to 16x16 when setting the small icon.
3013 */
3014 if (g_fCanChangeIcon)
3015 SetConsoleIcon(g_hWnd, g_hVimIcon, g_hVimIcon);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003016
3017 ui_get_shellsize();
3018
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003019# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00003020 fdDump = fopen("dump", "wt");
3021
3022 if (fdDump)
3023 {
3024 time_t t;
3025
3026 time(&t);
3027 fputs(ctime(&t), fdDump);
3028 fflush(fdDump);
3029 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003030# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003031
3032 g_fWindInitCalled = TRUE;
3033
Bram Moolenaar071d4272004-06-13 20:20:40 +00003034 g_fMouseAvail = GetSystemMetrics(SM_MOUSEPRESENT);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003035
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003036# ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01003037 win_clip_init();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003038# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01003039
Bram Moolenaar81ccbf12020-04-15 21:05:30 +02003040 vtp_flag_init();
Bram Moolenaarcafafb32018-02-22 21:07:09 +01003041 vtp_init();
Bram Moolenaar06b7b582020-05-30 17:49:25 +02003042 wt_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00003043}
3044
3045/*
3046 * non-GUI version of mch_exit().
3047 * Shut down and exit with status `r'
3048 * Careful: mch_exit() may be called before mch_init()!
3049 */
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003050 static void
3051mch_exit_c(int r)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003052{
Bram Moolenaar955f1982017-02-05 15:10:51 +01003053 exiting = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003054
Bram Moolenaarcafafb32018-02-22 21:07:09 +01003055 vtp_exit();
3056
Bram Moolenaar955f1982017-02-05 15:10:51 +01003057 stoptermcap();
Bram Moolenaar071d4272004-06-13 20:20:40 +00003058 if (g_fWindInitCalled)
3059 settmode(TMODE_COOK);
3060
Bram Moolenaar0f873732019-12-05 20:28:46 +01003061 ml_close_all(TRUE); // remove all memfiles
Bram Moolenaar071d4272004-06-13 20:20:40 +00003062
3063 if (g_fWindInitCalled)
3064 {
Bram Moolenaar40385db2018-08-07 22:31:44 +02003065 mch_restore_title(SAVE_RESTORE_BOTH);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003066 /*
3067 * Restore both the small and big icons of the console window to
3068 * what they were at startup. Don't do this when the window is
3069 * closed, Vim would hang here.
3070 */
3071 if (g_fCanChangeIcon && !g_fForceExit)
3072 SetConsoleIcon(g_hWnd, g_hOrigIconSmall, g_hOrigIcon);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003073
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003074# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00003075 if (fdDump)
3076 {
3077 time_t t;
3078
3079 time(&t);
3080 fputs(ctime(&t), fdDump);
3081 fclose(fdDump);
3082 }
3083 fdDump = NULL;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003084# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003085 }
3086
3087 SetConsoleCursorInfo(g_hConOut, &g_cci);
Wez Furlong6ef5ab52021-05-30 19:29:41 +02003088 SetConsoleMode(g_hConIn, g_cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003089 SetConsoleMode(g_hConOut, g_cmodeout);
3090
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003091# ifdef DYNAMIC_GETTEXT
Bram Moolenaar071d4272004-06-13 20:20:40 +00003092 dyn_libintl_end();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003093# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003094
3095 exit(r);
3096}
Bram Moolenaar0f873732019-12-05 20:28:46 +01003097#endif // !FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00003098
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003099 void
3100mch_init(void)
3101{
3102#ifdef VIMDLL
3103 if (gui.starting)
3104 mch_init_g();
3105 else
3106 mch_init_c();
3107#elif defined(FEAT_GUI_MSWIN)
3108 mch_init_g();
3109#else
3110 mch_init_c();
3111#endif
3112}
3113
3114 void
3115mch_exit(int r)
3116{
Bram Moolenaar173d8412020-04-19 14:02:26 +02003117#ifdef FEAT_NETBEANS_INTG
3118 netbeans_send_disconnect();
3119#endif
3120
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003121#ifdef VIMDLL
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02003122 if (gui.in_use || gui.starting)
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003123 mch_exit_g(r);
3124 else
3125 mch_exit_c(r);
3126#elif defined(FEAT_GUI_MSWIN)
3127 mch_exit_g(r);
3128#else
3129 mch_exit_c(r);
3130#endif
3131}
3132
Bram Moolenaar071d4272004-06-13 20:20:40 +00003133/*
3134 * Do we have an interactive window?
3135 */
3136 int
3137mch_check_win(
Bram Moolenaar1266d672017-02-01 13:43:36 +01003138 int argc UNUSED,
3139 char **argv UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003140{
3141 get_exe_name();
3142
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003143#if defined(FEAT_GUI_MSWIN) && !defined(VIMDLL)
Bram Moolenaar0f873732019-12-05 20:28:46 +01003144 return OK; // GUI always has a tty
Bram Moolenaar071d4272004-06-13 20:20:40 +00003145#else
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003146# ifdef VIMDLL
3147 if (gui.in_use)
3148 return OK;
3149# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003150 if (isatty(1))
3151 return OK;
3152 return FAIL;
3153#endif
3154}
3155
Bram Moolenaar65f04f62013-08-30 17:29:16 +02003156/*
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003157 * Set the case of the file name, if it already exists.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003158 * When "len" is > 0, also expand short to long filenames.
3159 */
3160 void
3161fname_case(
3162 char_u *name,
3163 int len)
3164{
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003165 int flen;
3166 WCHAR *p;
3167 WCHAR buf[_MAX_PATH + 1];
Bram Moolenaar071d4272004-06-13 20:20:40 +00003168
Bram Moolenaara3ffd9c2005-07-21 21:03:15 +00003169 flen = (int)STRLEN(name);
Bram Moolenaar65f04f62013-08-30 17:29:16 +02003170 if (flen == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003171 return;
3172
3173 slash_adjust(name);
3174
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003175 p = enc_to_utf16(name, NULL);
3176 if (p == NULL)
Bram Moolenaar65f04f62013-08-30 17:29:16 +02003177 return;
3178
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003179 if (GetLongPathNameW(p, buf, _MAX_PATH))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003180 {
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003181 char_u *q = utf16_to_enc(buf, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003182
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003183 if (q != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003184 {
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003185 if (len > 0 || flen >= (int)STRLEN(q))
3186 vim_strncpy(name, q, (len > 0) ? len - 1 : flen);
3187 vim_free(q);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003188 }
3189 }
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003190 vim_free(p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003191}
3192
3193
3194/*
3195 * Insert user name in s[len].
3196 */
3197 int
3198mch_get_user_name(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003199 char_u *s,
3200 int len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003201{
Bram Moolenaar0f873732019-12-05 20:28:46 +01003202 WCHAR wszUserName[256 + 1]; // UNLEN is 256
K.Takataeeec2542021-06-02 13:28:16 +02003203 DWORD wcch = ARRAY_LENGTH(wszUserName);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003204
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003205 if (GetUserNameW(wszUserName, &wcch))
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003206 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003207 char_u *p = utf16_to_enc(wszUserName, NULL);
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003208
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003209 if (p != NULL)
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003210 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003211 vim_strncpy(s, p, len - 1);
3212 vim_free(p);
3213 return OK;
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003214 }
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003215 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003216 s[0] = NUL;
3217 return FAIL;
3218}
3219
3220
3221/*
3222 * Insert host name in s[len].
3223 */
3224 void
3225mch_get_host_name(
3226 char_u *s,
3227 int len)
3228{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003229 WCHAR wszHostName[256 + 1];
K.Takataeeec2542021-06-02 13:28:16 +02003230 DWORD wcch = ARRAY_LENGTH(wszHostName);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003231
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003232 if (GetComputerNameW(wszHostName, &wcch))
Bram Moolenaar2cc87382013-12-11 18:21:45 +01003233 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003234 char_u *p = utf16_to_enc(wszHostName, NULL);
Bram Moolenaar2cc87382013-12-11 18:21:45 +01003235
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003236 if (p != NULL)
Bram Moolenaar2cc87382013-12-11 18:21:45 +01003237 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003238 vim_strncpy(s, p, len - 1);
3239 vim_free(p);
3240 return;
Bram Moolenaar2cc87382013-12-11 18:21:45 +01003241 }
Bram Moolenaar2cc87382013-12-11 18:21:45 +01003242 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003243}
3244
3245
3246/*
3247 * return process ID
3248 */
3249 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003250mch_get_pid(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003251{
3252 return (long)GetCurrentProcessId();
3253}
3254
Bram Moolenaar67cf86b2019-04-28 22:25:38 +02003255/*
3256 * return TRUE if process "pid" is still running
3257 */
3258 int
Bram Moolenaar1b243ea2019-04-28 22:50:40 +02003259mch_process_running(long pid)
Bram Moolenaar67cf86b2019-04-28 22:25:38 +02003260{
3261 HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION, 0, (DWORD)pid);
3262 DWORD status = 0;
3263 int ret = FALSE;
3264
3265 if (hProcess == NULL)
3266 return FALSE; // might not have access
3267 if (GetExitCodeProcess(hProcess, &status) )
3268 ret = status == STILL_ACTIVE;
3269 CloseHandle(hProcess);
3270 return ret;
3271}
Bram Moolenaar071d4272004-06-13 20:20:40 +00003272
3273/*
3274 * Get name of current directory into buffer 'buf' of length 'len' bytes.
3275 * Return OK for success, FAIL for failure.
3276 */
3277 int
3278mch_dirname(
3279 char_u *buf,
3280 int len)
3281{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003282 WCHAR wbuf[_MAX_PATH + 1];
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02003283
Bram Moolenaar071d4272004-06-13 20:20:40 +00003284 /*
3285 * Originally this was:
3286 * return (getcwd(buf, len) != NULL ? OK : FAIL);
3287 * But the Win32s known bug list says that getcwd() doesn't work
3288 * so use the Win32 system call instead. <Negri>
3289 */
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003290 if (GetCurrentDirectoryW(_MAX_PATH, wbuf) != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003291 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003292 WCHAR wcbuf[_MAX_PATH + 1];
3293 char_u *p = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003294
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003295 if (GetLongPathNameW(wbuf, wcbuf, _MAX_PATH) != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003296 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003297 p = utf16_to_enc(wcbuf, NULL);
3298 if (STRLEN(p) >= (size_t)len)
Bram Moolenaarcea1f9e2018-08-19 14:38:42 +02003299 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003300 // long path name is too long, fall back to short one
Bram Moolenaar071d4272004-06-13 20:20:40 +00003301 vim_free(p);
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003302 p = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003303 }
3304 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003305 if (p == NULL)
3306 p = utf16_to_enc(wbuf, NULL);
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02003307
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003308 if (p != NULL)
3309 {
3310 vim_strncpy(buf, p, len - 1);
3311 vim_free(p);
3312 return OK;
3313 }
3314 }
3315 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003316}
3317
3318/*
Bram Moolenaarffa22202013-11-21 12:34:11 +01003319 * Get file permissions for "name".
3320 * Return mode_t or -1 for error.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003321 */
3322 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003323mch_getperm(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003324{
Bram Moolenaar8767f522016-07-01 17:17:39 +02003325 stat_T st;
Bram Moolenaarffa22202013-11-21 12:34:11 +01003326 int n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003327
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003328 n = mch_stat((char *)name, &st);
Bram Moolenaar78cf3f02014-01-10 18:16:07 +01003329 return n == 0 ? (long)(unsigned short)st.st_mode : -1L;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003330}
3331
3332
3333/*
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003334 * Set file permission for "name" to "perm".
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003335 *
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003336 * Return FAIL for failure, OK otherwise.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003337 */
3338 int
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003339mch_setperm(char_u *name, long perm)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003340{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003341 long n;
3342 WCHAR *p;
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003343
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003344 p = enc_to_utf16(name, NULL);
3345 if (p == NULL)
3346 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003347
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003348 n = _wchmod(p, perm);
3349 vim_free(p);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003350 if (n == -1)
3351 return FAIL;
3352
3353 win32_set_archive(name);
3354
3355 return OK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003356}
3357
3358/*
3359 * Set hidden flag for "name".
3360 */
3361 void
3362mch_hide(char_u *name)
3363{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003364 int attrs = win32_getattrs(name);
3365 if (attrs == -1)
3366 return;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003367
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003368 attrs |= FILE_ATTRIBUTE_HIDDEN;
3369 win32_setattrs(name, attrs);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003370}
3371
3372/*
Bram Moolenaar8a52ba72015-11-02 14:45:56 +01003373 * Return TRUE if file "name" exists and is hidden.
3374 */
3375 int
3376mch_ishidden(char_u *name)
3377{
3378 int f = win32_getattrs(name);
3379
3380 if (f == -1)
Bram Moolenaar0f873732019-12-05 20:28:46 +01003381 return FALSE; // file does not exist at all
Bram Moolenaar8a52ba72015-11-02 14:45:56 +01003382
3383 return (f & FILE_ATTRIBUTE_HIDDEN) != 0;
3384}
3385
3386/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003387 * return TRUE if "name" is a directory
3388 * return FALSE if "name" is not a directory or upon error
3389 */
3390 int
3391mch_isdir(char_u *name)
3392{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003393 int f = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003394
3395 if (f == -1)
Bram Moolenaar0f873732019-12-05 20:28:46 +01003396 return FALSE; // file does not exist at all
Bram Moolenaar071d4272004-06-13 20:20:40 +00003397
3398 return (f & FILE_ATTRIBUTE_DIRECTORY) != 0;
3399}
3400
3401/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01003402 * return TRUE if "name" is a directory, NOT a symlink to a directory
3403 * return FALSE if "name" is not a directory
3404 * return FALSE for error
3405 */
3406 int
3407mch_isrealdir(char_u *name)
3408{
3409 return mch_isdir(name) && !mch_is_symbolic_link(name);
3410}
3411
3412/*
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003413 * Create directory "name".
3414 * Return 0 on success, -1 on error.
3415 */
3416 int
3417mch_mkdir(char_u *name)
3418{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003419 WCHAR *p;
3420 int retval;
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003421
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003422 p = enc_to_utf16(name, NULL);
3423 if (p == NULL)
3424 return -1;
3425 retval = _wmkdir(p);
3426 vim_free(p);
3427 return retval;
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003428}
3429
3430/*
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003431 * Delete directory "name".
3432 * Return 0 on success, -1 on error.
3433 */
3434 int
3435mch_rmdir(char_u *name)
3436{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003437 WCHAR *p;
3438 int retval;
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003439
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003440 p = enc_to_utf16(name, NULL);
3441 if (p == NULL)
3442 return -1;
3443 retval = _wrmdir(p);
3444 vim_free(p);
3445 return retval;
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003446}
3447
3448/*
Bram Moolenaar03f48552006-02-28 23:52:23 +00003449 * Return TRUE if file "fname" has more than one link.
3450 */
3451 int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003452mch_is_hard_link(char_u *fname)
Bram Moolenaar03f48552006-02-28 23:52:23 +00003453{
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003454 BY_HANDLE_FILE_INFORMATION info;
3455
3456 return win32_fileinfo(fname, &info) == FILEINFO_OK
3457 && info.nNumberOfLinks > 1;
3458}
3459
3460/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01003461 * Return TRUE if "name" is a symbolic link (or a junction).
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003462 */
3463 int
Bram Moolenaar203258c2016-01-17 22:15:16 +01003464mch_is_symbolic_link(char_u *name)
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003465{
3466 HANDLE hFind;
3467 int res = FALSE;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003468 DWORD fileFlags = 0, reparseTag = 0;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003469 WCHAR *wn;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003470 WIN32_FIND_DATAW findDataW;
3471
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003472 wn = enc_to_utf16(name, NULL);
3473 if (wn == NULL)
3474 return FALSE;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003475
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003476 hFind = FindFirstFileW(wn, &findDataW);
3477 vim_free(wn);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003478 if (hFind != INVALID_HANDLE_VALUE)
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003479 {
3480 fileFlags = findDataW.dwFileAttributes;
3481 reparseTag = findDataW.dwReserved0;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003482 FindClose(hFind);
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003483 }
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003484
3485 if ((fileFlags & FILE_ATTRIBUTE_REPARSE_POINT)
Bram Moolenaar203258c2016-01-17 22:15:16 +01003486 && (reparseTag == IO_REPARSE_TAG_SYMLINK
3487 || reparseTag == IO_REPARSE_TAG_MOUNT_POINT))
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003488 res = TRUE;
3489
3490 return res;
3491}
3492
3493/*
3494 * Return TRUE if file "fname" has more than one link or if it is a symbolic
3495 * link.
3496 */
3497 int
3498mch_is_linked(char_u *fname)
3499{
3500 if (mch_is_hard_link(fname) || mch_is_symbolic_link(fname))
3501 return TRUE;
3502 return FALSE;
3503}
3504
3505/*
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003506 * Get the by-handle-file-information for "fname".
3507 * Returns FILEINFO_OK when OK.
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003508 * Returns FILEINFO_ENC_FAIL when enc_to_utf16() failed.
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003509 * Returns FILEINFO_READ_FAIL when CreateFile() failed.
3510 * Returns FILEINFO_INFO_FAIL when GetFileInformationByHandle() failed.
3511 */
3512 int
3513win32_fileinfo(char_u *fname, BY_HANDLE_FILE_INFORMATION *info)
3514{
Bram Moolenaar03f48552006-02-28 23:52:23 +00003515 HANDLE hFile;
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003516 int res = FILEINFO_READ_FAIL;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003517 WCHAR *wn;
Bram Moolenaar03f48552006-02-28 23:52:23 +00003518
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003519 wn = enc_to_utf16(fname, NULL);
3520 if (wn == NULL)
3521 return FILEINFO_ENC_FAIL;
3522
3523 hFile = CreateFileW(wn, // file name
3524 GENERIC_READ, // access mode
3525 FILE_SHARE_READ | FILE_SHARE_WRITE, // share mode
3526 NULL, // security descriptor
3527 OPEN_EXISTING, // creation disposition
3528 FILE_FLAG_BACKUP_SEMANTICS, // file attributes
3529 NULL); // handle to template file
3530 vim_free(wn);
Bram Moolenaar03f48552006-02-28 23:52:23 +00003531
3532 if (hFile != INVALID_HANDLE_VALUE)
3533 {
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003534 if (GetFileInformationByHandle(hFile, info) != 0)
3535 res = FILEINFO_OK;
3536 else
3537 res = FILEINFO_INFO_FAIL;
Bram Moolenaar03f48552006-02-28 23:52:23 +00003538 CloseHandle(hFile);
3539 }
3540
Bram Moolenaar03f48552006-02-28 23:52:23 +00003541 return res;
3542}
3543
3544/*
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003545 * get file attributes for `name'
3546 * -1 : error
3547 * else FILE_ATTRIBUTE_* defined in winnt.h
3548 */
Bram Moolenaarffa22202013-11-21 12:34:11 +01003549 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003550win32_getattrs(char_u *name)
3551{
3552 int attr;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003553 WCHAR *p;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003554
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003555 p = enc_to_utf16(name, NULL);
3556 if (p == NULL)
3557 return INVALID_FILE_ATTRIBUTES;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003558
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003559 attr = GetFileAttributesW(p);
3560 vim_free(p);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003561
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003562 return attr;
3563}
3564
3565/*
3566 * set file attributes for `name' to `attrs'
3567 *
3568 * return -1 for failure, 0 otherwise
3569 */
Bram Moolenaar6dff58f2018-09-30 21:43:26 +02003570 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003571win32_setattrs(char_u *name, int attrs)
3572{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003573 int res;
3574 WCHAR *p;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003575
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003576 p = enc_to_utf16(name, NULL);
3577 if (p == NULL)
3578 return -1;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003579
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003580 res = SetFileAttributesW(p, attrs);
3581 vim_free(p);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003582
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003583 return res ? 0 : -1;
3584}
3585
3586/*
3587 * Set archive flag for "name".
3588 */
Bram Moolenaar6dff58f2018-09-30 21:43:26 +02003589 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003590win32_set_archive(char_u *name)
3591{
3592 int attrs = win32_getattrs(name);
3593 if (attrs == -1)
3594 return -1;
3595
3596 attrs |= FILE_ATTRIBUTE_ARCHIVE;
3597 return win32_setattrs(name, attrs);
3598}
3599
3600/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003601 * Return TRUE if file or directory "name" is writable (not readonly).
3602 * Strange semantics of Win32: a readonly directory is writable, but you can't
3603 * delete a file. Let's say this means it is writable.
3604 */
3605 int
3606mch_writable(char_u *name)
3607{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003608 int attrs = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003609
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003610 return (attrs != -1 && (!(attrs & FILE_ATTRIBUTE_READONLY)
3611 || (attrs & FILE_ATTRIBUTE_DIRECTORY)));
Bram Moolenaar071d4272004-06-13 20:20:40 +00003612}
3613
Bram Moolenaar071d4272004-06-13 20:20:40 +00003614/*
Bram Moolenaar43663192017-03-05 14:29:12 +01003615 * Return TRUE if "name" can be executed, FALSE if not.
Bram Moolenaar77b77102015-03-21 22:18:41 +01003616 * If "use_path" is FALSE only check if "name" is executable.
Bram Moolenaar43663192017-03-05 14:29:12 +01003617 * When returning TRUE and "path" is not NULL save the path and set "*path" to
3618 * the allocated memory.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003619 */
3620 int
Yegappan Lakshmananebb01bd2022-06-08 15:14:09 +01003621mch_can_exe(char_u *name, char_u **path, int use_path UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003622{
Bram Moolenaar95da1362020-05-30 18:37:55 +02003623 return executable_exists((char *)name, path, TRUE, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003624}
Bram Moolenaar071d4272004-06-13 20:20:40 +00003625
3626/*
3627 * Check what "name" is:
3628 * NODE_NORMAL: file or directory (or doesn't exist)
3629 * NODE_WRITABLE: writable device, socket, fifo, etc.
3630 * NODE_OTHER: non-writable things
3631 */
3632 int
3633mch_nodetype(char_u *name)
3634{
3635 HANDLE hFile;
3636 int type;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003637 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003638
Bram Moolenaar0f873732019-12-05 20:28:46 +01003639 // We can't open a file with a name "\\.\con" or "\\.\prn" and trying to
3640 // read from it later will cause Vim to hang. Thus return NODE_WRITABLE
3641 // here.
Bram Moolenaar043545e2006-10-10 16:44:07 +00003642 if (STRNCMP(name, "\\\\.\\", 4) == 0)
3643 return NODE_WRITABLE;
3644
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003645 wn = enc_to_utf16(name, NULL);
3646 if (wn == NULL)
3647 return NODE_NORMAL;
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003648
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003649 hFile = CreateFileW(wn, // file name
3650 GENERIC_WRITE, // access mode
3651 0, // share mode
3652 NULL, // security descriptor
3653 OPEN_EXISTING, // creation disposition
3654 0, // file attributes
3655 NULL); // handle to template file
3656 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003657 if (hFile == INVALID_HANDLE_VALUE)
3658 return NODE_NORMAL;
3659
3660 type = GetFileType(hFile);
3661 CloseHandle(hFile);
3662 if (type == FILE_TYPE_CHAR)
3663 return NODE_WRITABLE;
3664 if (type == FILE_TYPE_DISK)
3665 return NODE_NORMAL;
3666 return NODE_OTHER;
3667}
3668
3669#ifdef HAVE_ACL
3670struct my_acl
3671{
3672 PSECURITY_DESCRIPTOR pSecurityDescriptor;
3673 PSID pSidOwner;
3674 PSID pSidGroup;
3675 PACL pDacl;
3676 PACL pSacl;
3677};
3678#endif
3679
3680/*
3681 * Return a pointer to the ACL of file "fname" in allocated memory.
3682 * Return NULL if the ACL is not available for whatever reason.
3683 */
3684 vim_acl_T
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003685mch_get_acl(char_u *fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003686{
3687#ifndef HAVE_ACL
3688 return (vim_acl_T)NULL;
3689#else
3690 struct my_acl *p = NULL;
Bram Moolenaar27515922013-06-29 15:36:26 +02003691 DWORD err;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003692
Bram Moolenaarc799fe22019-05-28 23:08:19 +02003693 p = ALLOC_CLEAR_ONE(struct my_acl);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003694 if (p != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003695 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003696 WCHAR *wn;
Bram Moolenaar27515922013-06-29 15:36:26 +02003697
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003698 wn = enc_to_utf16(fname, NULL);
3699 if (wn == NULL)
Bram Moolenaarbbf9f342020-11-10 22:03:40 +01003700 {
3701 vim_free(p);
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003702 return NULL;
Bram Moolenaarbbf9f342020-11-10 22:03:40 +01003703 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003704
3705 // Try to retrieve the entire security descriptor.
3706 err = GetNamedSecurityInfoW(
3707 wn, // Abstract filename
3708 SE_FILE_OBJECT, // File Object
3709 OWNER_SECURITY_INFORMATION |
3710 GROUP_SECURITY_INFORMATION |
3711 DACL_SECURITY_INFORMATION |
3712 SACL_SECURITY_INFORMATION,
3713 &p->pSidOwner, // Ownership information.
3714 &p->pSidGroup, // Group membership.
3715 &p->pDacl, // Discretionary information.
3716 &p->pSacl, // For auditing purposes.
3717 &p->pSecurityDescriptor);
3718 if (err == ERROR_ACCESS_DENIED ||
3719 err == ERROR_PRIVILEGE_NOT_HELD)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003720 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003721 // Retrieve only DACL.
3722 (void)GetNamedSecurityInfoW(
3723 wn,
3724 SE_FILE_OBJECT,
3725 DACL_SECURITY_INFORMATION,
3726 NULL,
3727 NULL,
3728 &p->pDacl,
3729 NULL,
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003730 &p->pSecurityDescriptor);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003731 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003732 if (p->pSecurityDescriptor == NULL)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003733 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003734 mch_free_acl((vim_acl_T)p);
3735 p = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003736 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003737 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003738 }
3739
3740 return (vim_acl_T)p;
3741#endif
3742}
3743
Bram Moolenaar27515922013-06-29 15:36:26 +02003744#ifdef HAVE_ACL
3745/*
3746 * Check if "acl" contains inherited ACE.
3747 */
3748 static BOOL
3749is_acl_inherited(PACL acl)
3750{
3751 DWORD i;
3752 ACL_SIZE_INFORMATION acl_info;
3753 PACCESS_ALLOWED_ACE ace;
3754
3755 acl_info.AceCount = 0;
3756 GetAclInformation(acl, &acl_info, sizeof(acl_info), AclSizeInformation);
3757 for (i = 0; i < acl_info.AceCount; i++)
3758 {
3759 GetAce(acl, i, (LPVOID *)&ace);
3760 if (ace->Header.AceFlags & INHERITED_ACE)
3761 return TRUE;
3762 }
3763 return FALSE;
3764}
3765#endif
3766
Bram Moolenaar071d4272004-06-13 20:20:40 +00003767/*
3768 * Set the ACL of file "fname" to "acl" (unless it's NULL).
3769 * Errors are ignored.
3770 * This must only be called with "acl" equal to what mch_get_acl() returned.
3771 */
3772 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003773mch_set_acl(char_u *fname, vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003774{
3775#ifdef HAVE_ACL
3776 struct my_acl *p = (struct my_acl *)acl;
Bram Moolenaar27515922013-06-29 15:36:26 +02003777 SECURITY_INFORMATION sec_info = 0;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003778 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003779
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003780 if (p == NULL)
3781 return;
3782
3783 wn = enc_to_utf16(fname, NULL);
3784 if (wn == NULL)
3785 return;
3786
3787 // Set security flags
3788 if (p->pSidOwner)
3789 sec_info |= OWNER_SECURITY_INFORMATION;
3790 if (p->pSidGroup)
3791 sec_info |= GROUP_SECURITY_INFORMATION;
3792 if (p->pDacl)
Bram Moolenaar27515922013-06-29 15:36:26 +02003793 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003794 sec_info |= DACL_SECURITY_INFORMATION;
3795 // Do not inherit its parent's DACL.
3796 // If the DACL is inherited, Cygwin permissions would be changed.
3797 if (!is_acl_inherited(p->pDacl))
3798 sec_info |= PROTECTED_DACL_SECURITY_INFORMATION;
Bram Moolenaar27515922013-06-29 15:36:26 +02003799 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003800 if (p->pSacl)
3801 sec_info |= SACL_SECURITY_INFORMATION;
3802
3803 (void)SetNamedSecurityInfoW(
3804 wn, // Abstract filename
3805 SE_FILE_OBJECT, // File Object
3806 sec_info,
3807 p->pSidOwner, // Ownership information.
3808 p->pSidGroup, // Group membership.
3809 p->pDacl, // Discretionary information.
3810 p->pSacl // For auditing purposes.
3811 );
3812 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003813#endif
3814}
3815
3816 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003817mch_free_acl(vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003818{
3819#ifdef HAVE_ACL
3820 struct my_acl *p = (struct my_acl *)acl;
3821
3822 if (p != NULL)
3823 {
3824 LocalFree(p->pSecurityDescriptor); // Free the memory just in case
3825 vim_free(p);
3826 }
3827#endif
3828}
3829
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003830#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003831
3832/*
3833 * handler for ctrl-break, ctrl-c interrupts, and fatal events.
3834 */
3835 static BOOL WINAPI
3836handler_routine(
3837 DWORD dwCtrlType)
3838{
Bram Moolenaar589b1102017-08-12 16:39:05 +02003839 INPUT_RECORD ir;
3840 DWORD out;
3841
Bram Moolenaar071d4272004-06-13 20:20:40 +00003842 switch (dwCtrlType)
3843 {
3844 case CTRL_C_EVENT:
3845 if (ctrl_c_interrupts)
3846 g_fCtrlCPressed = TRUE;
3847 return TRUE;
3848
3849 case CTRL_BREAK_EVENT:
3850 g_fCBrkPressed = TRUE;
Bram Moolenaar589b1102017-08-12 16:39:05 +02003851 ctrl_break_was_pressed = TRUE;
Bram Moolenaar0f873732019-12-05 20:28:46 +01003852 // ReadConsoleInput is blocking, send a key event to continue.
Bram Moolenaar589b1102017-08-12 16:39:05 +02003853 ir.EventType = KEY_EVENT;
3854 ir.Event.KeyEvent.bKeyDown = TRUE;
3855 ir.Event.KeyEvent.wRepeatCount = 1;
3856 ir.Event.KeyEvent.wVirtualKeyCode = VK_CANCEL;
3857 ir.Event.KeyEvent.wVirtualScanCode = 0;
3858 ir.Event.KeyEvent.dwControlKeyState = 0;
3859 ir.Event.KeyEvent.uChar.UnicodeChar = 0;
3860 WriteConsoleInput(g_hConIn, &ir, 1, &out);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003861 return TRUE;
3862
Bram Moolenaar0f873732019-12-05 20:28:46 +01003863 // fatal events: shut down gracefully
Bram Moolenaar071d4272004-06-13 20:20:40 +00003864 case CTRL_CLOSE_EVENT:
3865 case CTRL_LOGOFF_EVENT:
3866 case CTRL_SHUTDOWN_EVENT:
3867 windgoto((int)Rows - 1, 0);
3868 g_fForceExit = TRUE;
3869
Bram Moolenaar0fde2902008-03-16 13:54:13 +00003870 vim_snprintf((char *)IObuff, IOSIZE, _("Vim: Caught %s event\n"),
Bram Moolenaar071d4272004-06-13 20:20:40 +00003871 (dwCtrlType == CTRL_CLOSE_EVENT
3872 ? _("close")
3873 : dwCtrlType == CTRL_LOGOFF_EVENT
3874 ? _("logoff")
3875 : _("shutdown")));
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003876# ifdef DEBUG
Bram Moolenaar071d4272004-06-13 20:20:40 +00003877 OutputDebugString(IObuff);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003878# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003879
Bram Moolenaar0f873732019-12-05 20:28:46 +01003880 preserve_exit(); // output IObuff, preserve files and exit
Bram Moolenaar071d4272004-06-13 20:20:40 +00003881
Bram Moolenaar0f873732019-12-05 20:28:46 +01003882 return TRUE; // not reached
Bram Moolenaar071d4272004-06-13 20:20:40 +00003883
3884 default:
3885 return FALSE;
3886 }
3887}
3888
3889
3890/*
3891 * set the tty in (raw) ? "raw" : "cooked" mode
3892 */
3893 void
Bram Moolenaar26e86442020-05-17 14:06:16 +02003894mch_settmode(tmode_T tmode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003895{
3896 DWORD cmodein;
3897 DWORD cmodeout;
3898 BOOL bEnableHandler;
3899
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003900# ifdef VIMDLL
3901 if (gui.in_use)
3902 return;
3903# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003904 GetConsoleMode(g_hConIn, &cmodein);
3905 GetConsoleMode(g_hConOut, &cmodeout);
3906 if (tmode == TMODE_RAW)
3907 {
3908 cmodein &= ~(ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
3909 ENABLE_ECHO_INPUT);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003910 if (g_fMouseActive)
Wez Furlong6ef5ab52021-05-30 19:29:41 +02003911 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00003912 cmodein |= ENABLE_MOUSE_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02003913 cmodein &= ~ENABLE_QUICK_EDIT_MODE;
3914 }
3915 else
3916 {
3917 cmodein |= g_cmodein & ENABLE_QUICK_EDIT_MODE;
3918 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01003919 cmodeout &= ~(
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003920# ifdef FEAT_TERMGUICOLORS
Bram Moolenaar0f873732019-12-05 20:28:46 +01003921 // Do not turn off the ENABLE_PROCESSED_OUTPUT flag when using
3922 // VTP.
Bram Moolenaarcafafb32018-02-22 21:07:09 +01003923 ((vtp_working) ? 0 : ENABLE_PROCESSED_OUTPUT) |
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003924# else
Bram Moolenaarcafafb32018-02-22 21:07:09 +01003925 ENABLE_PROCESSED_OUTPUT |
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003926# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01003927 ENABLE_WRAP_AT_EOL_OUTPUT);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003928 bEnableHandler = TRUE;
3929 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01003930 else // cooked
Bram Moolenaar071d4272004-06-13 20:20:40 +00003931 {
3932 cmodein |= (ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
3933 ENABLE_ECHO_INPUT);
3934 cmodeout |= (ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
3935 bEnableHandler = FALSE;
3936 }
Wez Furlong6ef5ab52021-05-30 19:29:41 +02003937 SetConsoleMode(g_hConIn, cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003938 SetConsoleMode(g_hConOut, cmodeout);
3939 SetConsoleCtrlHandler(handler_routine, bEnableHandler);
3940
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003941# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00003942 if (fdDump)
3943 {
3944 fprintf(fdDump, "mch_settmode(%s, in = %x, out = %x)\n",
3945 tmode == TMODE_RAW ? "raw" :
3946 tmode == TMODE_COOK ? "cooked" : "normal",
3947 cmodein, cmodeout);
3948 fflush(fdDump);
3949 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003950# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003951}
3952
3953
3954/*
3955 * Get the size of the current window in `Rows' and `Columns'
3956 * Return OK when size could be determined, FAIL otherwise.
3957 */
3958 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003959mch_get_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003960{
3961 CONSOLE_SCREEN_BUFFER_INFO csbi;
3962
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003963# ifdef VIMDLL
3964 if (gui.in_use)
3965 return OK;
3966# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003967 if (!g_fTermcapMode && g_cbTermcap.IsValid)
3968 {
3969 /*
3970 * For some reason, we are trying to get the screen dimensions
3971 * even though we are not in termcap mode. The 'Rows' and 'Columns'
3972 * variables are really intended to mean the size of Vim screen
3973 * while in termcap mode.
3974 */
3975 Rows = g_cbTermcap.Info.dwSize.Y;
3976 Columns = g_cbTermcap.Info.dwSize.X;
3977 }
3978 else if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3979 {
3980 Rows = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
3981 Columns = csbi.srWindow.Right - csbi.srWindow.Left + 1;
3982 }
3983 else
3984 {
3985 Rows = 25;
3986 Columns = 80;
3987 }
3988 return OK;
3989}
3990
3991/*
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02003992 * Resize console buffer to 'COORD'
3993 */
3994 static void
3995ResizeConBuf(
3996 HANDLE hConsole,
3997 COORD coordScreen)
3998{
3999 if (!SetConsoleScreenBufferSize(hConsole, coordScreen))
4000 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004001# ifdef MCH_WRITE_DUMP
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004002 if (fdDump)
4003 {
4004 fprintf(fdDump, "SetConsoleScreenBufferSize failed: %lx\n",
4005 GetLastError());
4006 fflush(fdDump);
4007 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004008# endif
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004009 }
4010}
4011
4012/*
4013 * Resize console window size to 'srWindowRect'
4014 */
4015 static void
4016ResizeWindow(
4017 HANDLE hConsole,
4018 SMALL_RECT srWindowRect)
4019{
4020 if (!SetConsoleWindowInfo(hConsole, TRUE, &srWindowRect))
4021 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004022# ifdef MCH_WRITE_DUMP
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004023 if (fdDump)
4024 {
4025 fprintf(fdDump, "SetConsoleWindowInfo failed: %lx\n",
4026 GetLastError());
4027 fflush(fdDump);
4028 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004029# endif
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004030 }
4031}
4032
4033/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00004034 * Set a console window to `xSize' * `ySize'
4035 */
4036 static void
4037ResizeConBufAndWindow(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004038 HANDLE hConsole,
4039 int xSize,
4040 int ySize)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004041{
Bram Moolenaar0f873732019-12-05 20:28:46 +01004042 CONSOLE_SCREEN_BUFFER_INFO csbi; // hold current console buffer info
4043 SMALL_RECT srWindowRect; // hold the new console size
Bram Moolenaar071d4272004-06-13 20:20:40 +00004044 COORD coordScreen;
Bram Moolenaarf49a6922019-07-15 20:37:05 +02004045 COORD cursor;
Bram Moolenaar2551c032018-08-23 22:38:31 +02004046 static int resized = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004047
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004048# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00004049 if (fdDump)
4050 {
4051 fprintf(fdDump, "ResizeConBufAndWindow(%d, %d)\n", xSize, ySize);
4052 fflush(fdDump);
4053 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004054# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004055
Bram Moolenaar0f873732019-12-05 20:28:46 +01004056 // get the largest size we can size the console window to
Bram Moolenaar071d4272004-06-13 20:20:40 +00004057 coordScreen = GetLargestConsoleWindowSize(hConsole);
4058
Bram Moolenaar0f873732019-12-05 20:28:46 +01004059 // define the new console window size and scroll position
Bram Moolenaar071d4272004-06-13 20:20:40 +00004060 srWindowRect.Left = srWindowRect.Top = (SHORT) 0;
4061 srWindowRect.Right = (SHORT) (min(xSize, coordScreen.X) - 1);
4062 srWindowRect.Bottom = (SHORT) (min(ySize, coordScreen.Y) - 1);
4063
4064 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
4065 {
4066 int sx, sy;
4067
4068 sx = csbi.srWindow.Right - csbi.srWindow.Left + 1;
4069 sy = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
4070 if (sy < ySize || sx < xSize)
4071 {
4072 /*
4073 * Increasing number of lines/columns, do buffer first.
4074 * Use the maximal size in x and y direction.
4075 */
4076 if (sy < ySize)
4077 coordScreen.Y = ySize;
4078 else
4079 coordScreen.Y = sy;
4080 if (sx < xSize)
4081 coordScreen.X = xSize;
4082 else
4083 coordScreen.X = sx;
4084 SetConsoleScreenBufferSize(hConsole, coordScreen);
4085 }
4086 }
4087
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004088 // define the new console buffer size
Bram Moolenaar071d4272004-06-13 20:20:40 +00004089 coordScreen.X = xSize;
4090 coordScreen.Y = ySize;
4091
Bram Moolenaar2551c032018-08-23 22:38:31 +02004092 // In the new console call API, only the first time in reverse order
4093 if (!vtp_working || resized)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004094 {
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004095 ResizeWindow(hConsole, srWindowRect);
4096 ResizeConBuf(hConsole, coordScreen);
4097 }
4098 else
4099 {
Bram Moolenaarf49a6922019-07-15 20:37:05 +02004100 // Workaround for a Windows 10 bug
4101 cursor.X = srWindowRect.Left;
4102 cursor.Y = srWindowRect.Top;
4103 SetConsoleCursorPosition(hConsole, cursor);
4104
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004105 ResizeConBuf(hConsole, coordScreen);
4106 ResizeWindow(hConsole, srWindowRect);
Bram Moolenaar2551c032018-08-23 22:38:31 +02004107 resized = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004108 }
4109}
4110
4111
4112/*
4113 * Set the console window to `Rows' * `Columns'
4114 */
4115 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004116mch_set_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004117{
4118 COORD coordScreen;
4119
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004120# ifdef VIMDLL
4121 if (gui.in_use)
4122 return;
4123# endif
Bram Moolenaar0f873732019-12-05 20:28:46 +01004124 // Don't change window size while still starting up
Bram Moolenaar071d4272004-06-13 20:20:40 +00004125 if (suppress_winsize != 0)
4126 {
4127 suppress_winsize = 2;
4128 return;
4129 }
4130
4131 if (term_console)
4132 {
4133 coordScreen = GetLargestConsoleWindowSize(g_hConOut);
4134
Bram Moolenaar0f873732019-12-05 20:28:46 +01004135 // Clamp Rows and Columns to reasonable values
Bram Moolenaar071d4272004-06-13 20:20:40 +00004136 if (Rows > coordScreen.Y)
4137 Rows = coordScreen.Y;
4138 if (Columns > coordScreen.X)
4139 Columns = coordScreen.X;
4140
4141 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
4142 }
4143}
4144
4145/*
4146 * Rows and/or Columns has changed.
4147 */
4148 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004149mch_new_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004150{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004151# ifdef VIMDLL
4152 if (gui.in_use)
4153 return;
4154# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004155 set_scroll_region(0, 0, Columns - 1, Rows - 1);
4156}
4157
4158
4159/*
4160 * Called when started up, to set the winsize that was delayed.
4161 */
4162 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004163mch_set_winsize_now(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004164{
4165 if (suppress_winsize == 2)
4166 {
4167 suppress_winsize = 0;
4168 mch_set_shellsize();
4169 shell_resized();
4170 }
4171 suppress_winsize = 0;
4172}
Bram Moolenaar0f873732019-12-05 20:28:46 +01004173#endif // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00004174
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004175 static BOOL
4176vim_create_process(
Bram Moolenaar36c85b22013-12-12 20:25:44 +01004177 char *cmd,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004178 BOOL inherit_handles,
Bram Moolenaar3f1138e2014-01-05 13:29:26 +01004179 DWORD flags,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004180 STARTUPINFO *si,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004181 PROCESS_INFORMATION *pi,
4182 LPVOID *env,
4183 char *cwd)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004184{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004185 BOOL ret = FALSE;
4186 WCHAR *wcmd, *wcwd = NULL;
4187
4188 wcmd = enc_to_utf16((char_u *)cmd, NULL);
4189 if (wcmd == NULL)
4190 return FALSE;
4191 if (cwd != NULL)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004192 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004193 wcwd = enc_to_utf16((char_u *)cwd, NULL);
4194 if (wcwd == NULL)
4195 goto theend;
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004196 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004197
4198 ret = CreateProcessW(
4199 NULL, // Executable name
4200 wcmd, // Command to execute
4201 NULL, // Process security attributes
4202 NULL, // Thread security attributes
4203 inherit_handles, // Inherit handles
4204 flags, // Creation flags
4205 env, // Environment
4206 wcwd, // Current directory
4207 (LPSTARTUPINFOW)si, // Startup information
4208 pi); // Process information
4209theend:
4210 vim_free(wcmd);
4211 vim_free(wcwd);
4212 return ret;
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004213}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004214
4215
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004216 static HINSTANCE
4217vim_shell_execute(
4218 char *cmd,
4219 INT n_show_cmd)
4220{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004221 HINSTANCE ret;
4222 WCHAR *wcmd;
4223
4224 wcmd = enc_to_utf16((char_u *)cmd, NULL);
4225 if (wcmd == NULL)
4226 return (HINSTANCE) 0;
4227
4228 ret = ShellExecuteW(NULL, NULL, wcmd, NULL, NULL, n_show_cmd);
4229 vim_free(wcmd);
4230 return ret;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004231}
4232
4233
Bram Moolenaar4f974752019-02-17 17:44:42 +01004234#if defined(FEAT_GUI_MSWIN) || defined(PROTO)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004235
4236/*
4237 * Specialised version of system() for Win32 GUI mode.
4238 * This version proceeds as follows:
4239 * 1. Create a console window for use by the subprocess
4240 * 2. Run the subprocess (it gets the allocated console by default)
4241 * 3. Wait for the subprocess to terminate and get its exit code
4242 * 4. Prompt the user to press a key to close the console window
4243 */
4244 static int
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004245mch_system_classic(char *cmd, int options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004246{
4247 STARTUPINFO si;
4248 PROCESS_INFORMATION pi;
4249 DWORD ret = 0;
4250 HWND hwnd = GetFocus();
4251
4252 si.cb = sizeof(si);
4253 si.lpReserved = NULL;
4254 si.lpDesktop = NULL;
4255 si.lpTitle = NULL;
4256 si.dwFlags = STARTF_USESHOWWINDOW;
4257 /*
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004258 * It's nicer to run a filter command in a minimized window.
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01004259 * Don't activate the window to keep focus on Vim.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004260 */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004261 if (options & SHELL_DOOUT)
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01004262 si.wShowWindow = SW_SHOWMINNOACTIVE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004263 else
4264 si.wShowWindow = SW_SHOWNORMAL;
4265 si.cbReserved2 = 0;
4266 si.lpReserved2 = NULL;
4267
Bram Moolenaar0f873732019-12-05 20:28:46 +01004268 // Now, run the command
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004269 vim_create_process(cmd, FALSE,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004270 CREATE_DEFAULT_ERROR_MODE | CREATE_NEW_CONSOLE,
4271 &si, &pi, NULL, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004272
Bram Moolenaar0f873732019-12-05 20:28:46 +01004273 // Wait for the command to terminate before continuing
Bram Moolenaar071d4272004-06-13 20:20:40 +00004274 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004275# ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00004276 int delay = 1;
4277
Bram Moolenaar0f873732019-12-05 20:28:46 +01004278 // Keep updating the window while waiting for the shell to finish.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004279 for (;;)
4280 {
4281 MSG msg;
4282
K.Takatab7057bd2022-01-21 11:37:07 +00004283 if (PeekMessageW(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004284 {
4285 TranslateMessage(&msg);
K.Takatab7057bd2022-01-21 11:37:07 +00004286 DispatchMessageW(&msg);
Bram Moolenaare4195c52012-08-02 12:31:44 +02004287 delay = 1;
4288 continue;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004289 }
4290 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
4291 break;
4292
Bram Moolenaar0f873732019-12-05 20:28:46 +01004293 // We start waiting for a very short time and then increase it, so
4294 // that we respond quickly when the process is quick, and don't
4295 // consume too much overhead when it's slow.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004296 if (delay < 50)
4297 delay += 10;
4298 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004299# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004300 WaitForSingleObject(pi.hProcess, INFINITE);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004301# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004302
Bram Moolenaar0f873732019-12-05 20:28:46 +01004303 // Get the command exit code
Bram Moolenaar071d4272004-06-13 20:20:40 +00004304 GetExitCodeProcess(pi.hProcess, &ret);
4305 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004306
Bram Moolenaar0f873732019-12-05 20:28:46 +01004307 // Close the handles to the subprocess, so that it goes away
Bram Moolenaar071d4272004-06-13 20:20:40 +00004308 CloseHandle(pi.hThread);
4309 CloseHandle(pi.hProcess);
4310
Bram Moolenaar0f873732019-12-05 20:28:46 +01004311 // Try to get input focus back. Doesn't always work though.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004312 PostMessage(hwnd, WM_SETFOCUS, 0, 0);
4313
4314 return ret;
4315}
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004316
4317/*
4318 * Thread launched by the gui to send the current buffer data to the
4319 * process. This way avoid to hang up vim totally if the children
4320 * process take a long time to process the lines.
4321 */
Bram Moolenaar4c38d662016-08-03 20:54:57 +02004322 static unsigned int __stdcall
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004323sub_process_writer(LPVOID param)
4324{
4325 HANDLE g_hChildStd_IN_Wr = param;
4326 linenr_T lnum = curbuf->b_op_start.lnum;
4327 DWORD len = 0;
4328 DWORD l;
4329 char_u *lp = ml_get(lnum);
4330 char_u *s;
4331 int written = 0;
4332
4333 for (;;)
4334 {
4335 l = (DWORD)STRLEN(lp + written);
4336 if (l == 0)
4337 len = 0;
4338 else if (lp[written] == NL)
4339 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004340 // NL -> NUL translation
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004341 WriteFile(g_hChildStd_IN_Wr, "", 1, &len, NULL);
4342 }
4343 else
4344 {
4345 s = vim_strchr(lp + written, NL);
4346 WriteFile(g_hChildStd_IN_Wr, (char *)lp + written,
4347 s == NULL ? l : (DWORD)(s - (lp + written)),
4348 &len, NULL);
4349 }
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +01004350 if (len == l)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004351 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004352 // Finished a line, add a NL, unless this line should not have
4353 // one.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004354 if (lnum != curbuf->b_op_end.lnum
Bram Moolenaar34d72d42015-07-17 14:18:08 +02004355 || (!curbuf->b_p_bin
4356 && curbuf->b_p_fixeol)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004357 || (lnum != curbuf->b_no_eol_lnum
4358 && (lnum != curbuf->b_ml.ml_line_count
4359 || curbuf->b_p_eol)))
4360 {
Bram Moolenaar42335f52018-09-13 15:33:43 +02004361 WriteFile(g_hChildStd_IN_Wr, "\n", 1,
4362 (LPDWORD)&vim_ignored, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004363 }
4364
4365 ++lnum;
4366 if (lnum > curbuf->b_op_end.lnum)
4367 break;
4368
4369 lp = ml_get(lnum);
4370 written = 0;
4371 }
4372 else if (len > 0)
4373 written += len;
4374 }
4375
Bram Moolenaar0f873732019-12-05 20:28:46 +01004376 // finished all the lines, close pipe
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004377 CloseHandle(g_hChildStd_IN_Wr);
Bram Moolenaar86f2cd52016-08-02 21:55:17 +02004378 return 0;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004379}
4380
4381
Bram Moolenaar0f873732019-12-05 20:28:46 +01004382# define BUFLEN 100 // length for buffer, stolen from unix version
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004383
4384/*
4385 * This function read from the children's stdout and write the
4386 * data on screen or in the buffer accordingly.
4387 */
4388 static void
4389dump_pipe(int options,
4390 HANDLE g_hChildStd_OUT_Rd,
4391 garray_T *ga,
4392 char_u buffer[],
4393 DWORD *buffer_off)
4394{
4395 DWORD availableBytes = 0;
4396 DWORD i;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004397 int ret;
4398 DWORD len;
4399 DWORD toRead;
4400 int repeatCount;
4401
Bram Moolenaar0f873732019-12-05 20:28:46 +01004402 // we query the pipe to see if there is any data to read
4403 // to avoid to perform a blocking read
4404 ret = PeekNamedPipe(g_hChildStd_OUT_Rd, // pipe to query
4405 NULL, // optional buffer
4406 0, // buffer size
4407 NULL, // number of read bytes
4408 &availableBytes, // available bytes total
4409 NULL); // byteLeft
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004410
4411 repeatCount = 0;
Bram Moolenaar0f873732019-12-05 20:28:46 +01004412 // We got real data in the pipe, read it
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02004413 while (ret != 0 && availableBytes > 0)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004414 {
4415 repeatCount++;
Bram Moolenaara12a1612019-01-24 16:39:02 +01004416 toRead = (DWORD)(BUFLEN - *buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004417 toRead = availableBytes < toRead ? availableBytes : toRead;
Bram Moolenaara12a1612019-01-24 16:39:02 +01004418 ReadFile(g_hChildStd_OUT_Rd, buffer + *buffer_off, toRead , &len, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004419
Bram Moolenaar0f873732019-12-05 20:28:46 +01004420 // If we haven't read anything, there is a problem
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004421 if (len == 0)
4422 break;
4423
4424 availableBytes -= len;
4425
4426 if (options & SHELL_READ)
4427 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004428 // Do NUL -> NL translation, append NL separated
4429 // lines to the current buffer.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004430 for (i = 0; i < len; ++i)
4431 {
4432 if (buffer[i] == NL)
4433 append_ga_line(ga);
4434 else if (buffer[i] == NUL)
4435 ga_append(ga, NL);
4436 else
4437 ga_append(ga, buffer[i]);
4438 }
4439 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004440 else if (has_mbyte)
4441 {
4442 int l;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004443 int c;
4444 char_u *p;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004445
4446 len += *buffer_off;
4447 buffer[len] = NUL;
4448
Bram Moolenaar0f873732019-12-05 20:28:46 +01004449 // Check if the last character in buffer[] is
4450 // incomplete, keep these bytes for the next
4451 // round.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004452 for (p = buffer; p < buffer + len; p += l)
4453 {
Bram Moolenaard3c907b2016-08-17 21:32:09 +02004454 l = MB_CPTR2LEN(p);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004455 if (l == 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01004456 l = 1; // NUL byte?
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004457 else if (MB_BYTE2LEN(*p) != l)
4458 break;
4459 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01004460 if (p == buffer) // no complete character
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004461 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004462 // avoid getting stuck at an illegal byte
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004463 if (len >= 12)
4464 ++p;
4465 else
4466 {
4467 *buffer_off = len;
4468 return;
4469 }
4470 }
4471 c = *p;
4472 *p = NUL;
Bram Moolenaar32526b32019-01-19 17:43:09 +01004473 msg_puts((char *)buffer);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004474 if (p < buffer + len)
4475 {
4476 *p = c;
4477 *buffer_off = (DWORD)((buffer + len) - p);
4478 mch_memmove(buffer, p, *buffer_off);
4479 return;
4480 }
4481 *buffer_off = 0;
4482 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004483 else
4484 {
4485 buffer[len] = NUL;
Bram Moolenaar32526b32019-01-19 17:43:09 +01004486 msg_puts((char *)buffer);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004487 }
4488
4489 windgoto(msg_row, msg_col);
4490 cursor_on();
4491 out_flush();
4492 }
4493}
4494
4495/*
4496 * Version of system to use for windows NT > 5.0 (Win2K), use pipe
4497 * for communication and doesn't open any new window.
4498 */
4499 static int
4500mch_system_piped(char *cmd, int options)
4501{
4502 STARTUPINFO si;
4503 PROCESS_INFORMATION pi;
4504 DWORD ret = 0;
4505
4506 HANDLE g_hChildStd_IN_Rd = NULL;
4507 HANDLE g_hChildStd_IN_Wr = NULL;
4508 HANDLE g_hChildStd_OUT_Rd = NULL;
4509 HANDLE g_hChildStd_OUT_Wr = NULL;
4510
Bram Moolenaar0f873732019-12-05 20:28:46 +01004511 char_u buffer[BUFLEN + 1]; // reading buffer + size
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004512 DWORD len;
4513
Bram Moolenaar0f873732019-12-05 20:28:46 +01004514 // buffer used to receive keys
4515 char_u ta_buf[BUFLEN + 1]; // TypeAHead
4516 int ta_len = 0; // valid bytes in ta_buf[]
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004517
4518 DWORD i;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004519 int noread_cnt = 0;
4520 garray_T ga;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004521 int delay = 1;
Bram Moolenaar0f873732019-12-05 20:28:46 +01004522 DWORD buffer_off = 0; // valid bytes in buffer[]
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004523 char *p = NULL;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004524
4525 SECURITY_ATTRIBUTES saAttr;
4526
Bram Moolenaar0f873732019-12-05 20:28:46 +01004527 // Set the bInheritHandle flag so pipe handles are inherited.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004528 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
4529 saAttr.bInheritHandle = TRUE;
4530 saAttr.lpSecurityDescriptor = NULL;
4531
4532 if ( ! CreatePipe(&g_hChildStd_OUT_Rd, &g_hChildStd_OUT_Wr, &saAttr, 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01004533 // Ensure the read handle to the pipe for STDOUT is not inherited.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004534 || ! SetHandleInformation(g_hChildStd_OUT_Rd, HANDLE_FLAG_INHERIT, 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01004535 // Create a pipe for the child process's STDIN.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004536 || ! CreatePipe(&g_hChildStd_IN_Rd, &g_hChildStd_IN_Wr, &saAttr, 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01004537 // Ensure the write handle to the pipe for STDIN is not inherited.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004538 || ! SetHandleInformation(g_hChildStd_IN_Wr, HANDLE_FLAG_INHERIT, 0) )
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004539 {
4540 CloseHandle(g_hChildStd_IN_Rd);
4541 CloseHandle(g_hChildStd_IN_Wr);
4542 CloseHandle(g_hChildStd_OUT_Rd);
4543 CloseHandle(g_hChildStd_OUT_Wr);
Bram Moolenaar32526b32019-01-19 17:43:09 +01004544 msg_puts(_("\nCannot create pipes\n"));
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004545 }
4546
4547 si.cb = sizeof(si);
4548 si.lpReserved = NULL;
4549 si.lpDesktop = NULL;
4550 si.lpTitle = NULL;
4551 si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
4552
Bram Moolenaar0f873732019-12-05 20:28:46 +01004553 // set-up our file redirection
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004554 si.hStdError = g_hChildStd_OUT_Wr;
4555 si.hStdOutput = g_hChildStd_OUT_Wr;
4556 si.hStdInput = g_hChildStd_IN_Rd;
4557 si.wShowWindow = SW_HIDE;
4558 si.cbReserved2 = 0;
4559 si.lpReserved2 = NULL;
4560
4561 if (options & SHELL_READ)
4562 ga_init2(&ga, 1, BUFLEN);
4563
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004564 if (cmd != NULL)
4565 {
4566 p = (char *)vim_strsave((char_u *)cmd);
4567 if (p != NULL)
4568 unescape_shellxquote((char_u *)p, p_sxe);
4569 else
4570 p = cmd;
4571 }
4572
Bram Moolenaar0f873732019-12-05 20:28:46 +01004573 // Now, run the command.
4574 // About "Inherit handles" being TRUE: this command can be litigious,
4575 // handle inheritance was deactivated for pending temp file, but, if we
4576 // deactivate it, the pipes don't work for some reason.
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004577 vim_create_process(p, TRUE, CREATE_DEFAULT_ERROR_MODE,
4578 &si, &pi, NULL, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004579
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004580 if (p != cmd)
4581 vim_free(p);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004582
Bram Moolenaar0f873732019-12-05 20:28:46 +01004583 // Close our unused side of the pipes
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004584 CloseHandle(g_hChildStd_IN_Rd);
4585 CloseHandle(g_hChildStd_OUT_Wr);
4586
4587 if (options & SHELL_WRITE)
4588 {
Bram Moolenaar86f2cd52016-08-02 21:55:17 +02004589 HANDLE thread = (HANDLE)
Bram Moolenaar0f873732019-12-05 20:28:46 +01004590 _beginthreadex(NULL, // security attributes
4591 0, // default stack size
4592 sub_process_writer, // function to be executed
4593 g_hChildStd_IN_Wr, // parameter
4594 0, // creation flag, start immediately
4595 NULL); // we don't care about thread id
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004596 CloseHandle(thread);
4597 g_hChildStd_IN_Wr = NULL;
4598 }
4599
Bram Moolenaar0f873732019-12-05 20:28:46 +01004600 // Keep updating the window while waiting for the shell to finish.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004601 for (;;)
4602 {
4603 MSG msg;
4604
K.Takatab7057bd2022-01-21 11:37:07 +00004605 if (PeekMessageW(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004606 {
4607 TranslateMessage(&msg);
K.Takatab7057bd2022-01-21 11:37:07 +00004608 DispatchMessageW(&msg);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004609 }
4610
Bram Moolenaar0f873732019-12-05 20:28:46 +01004611 // write pipe information in the window
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004612 if ((options & (SHELL_READ|SHELL_WRITE))
4613# ifdef FEAT_GUI
4614 || gui.in_use
4615# endif
4616 )
4617 {
4618 len = 0;
4619 if (!(options & SHELL_EXPAND)
4620 && ((options &
4621 (SHELL_READ|SHELL_WRITE|SHELL_COOKED))
4622 != (SHELL_READ|SHELL_WRITE|SHELL_COOKED)
4623# ifdef FEAT_GUI
4624 || gui.in_use
4625# endif
4626 )
4627 && (ta_len > 0 || noread_cnt > 4))
4628 {
4629 if (ta_len == 0)
4630 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004631 // Get extra characters when we don't have any. Reset the
4632 // counter and timer.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004633 noread_cnt = 0;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004634 len = ui_inchar(ta_buf, BUFLEN, 10L, 0);
4635 }
4636 if (ta_len > 0 || len > 0)
4637 {
4638 /*
4639 * For pipes: Check for CTRL-C: send interrupt signal to
4640 * child. Check for CTRL-D: EOF, close pipe to child.
4641 */
4642 if (len == 1 && cmd != NULL)
4643 {
4644 if (ta_buf[ta_len] == Ctrl_C)
4645 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004646 // Learn what exit code is expected, for
4647 // now put 9 as SIGKILL
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004648 TerminateProcess(pi.hProcess, 9);
4649 }
4650 if (ta_buf[ta_len] == Ctrl_D)
4651 {
4652 CloseHandle(g_hChildStd_IN_Wr);
4653 g_hChildStd_IN_Wr = NULL;
4654 }
4655 }
4656
Bram Moolenaar2f7e1b82022-10-04 13:17:31 +01004657 len = term_replace_keycodes(ta_buf, ta_len, len);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004658
4659 /*
4660 * For pipes: echo the typed characters. For a pty this
4661 * does not seem to work.
4662 */
4663 for (i = ta_len; i < ta_len + len; ++i)
4664 {
4665 if (ta_buf[i] == '\n' || ta_buf[i] == '\b')
4666 msg_putchar(ta_buf[i]);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004667 else if (has_mbyte)
4668 {
4669 int l = (*mb_ptr2len)(ta_buf + i);
4670
4671 msg_outtrans_len(ta_buf + i, l);
4672 i += l - 1;
4673 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004674 else
4675 msg_outtrans_len(ta_buf + i, 1);
4676 }
4677 windgoto(msg_row, msg_col);
4678 out_flush();
4679
4680 ta_len += len;
4681
4682 /*
4683 * Write the characters to the child, unless EOF has been
4684 * typed for pipes. Write one character at a time, to
4685 * avoid losing too much typeahead. When writing buffer
4686 * lines, drop the typed characters (only check for
4687 * CTRL-C).
4688 */
4689 if (options & SHELL_WRITE)
4690 ta_len = 0;
4691 else if (g_hChildStd_IN_Wr != NULL)
4692 {
4693 WriteFile(g_hChildStd_IN_Wr, (char*)ta_buf,
4694 1, &len, NULL);
4695 // if we are typing in, we want to keep things reactive
4696 delay = 1;
4697 if (len > 0)
4698 {
4699 ta_len -= len;
4700 mch_memmove(ta_buf, ta_buf + len, ta_len);
4701 }
4702 }
4703 }
4704 }
4705 }
4706
4707 if (ta_len)
4708 ui_inchar_undo(ta_buf, ta_len);
4709
4710 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
4711 {
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004712 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004713 break;
4714 }
4715
4716 ++noread_cnt;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004717 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004718
Bram Moolenaar0f873732019-12-05 20:28:46 +01004719 // We start waiting for a very short time and then increase it, so
4720 // that we respond quickly when the process is quick, and don't
4721 // consume too much overhead when it's slow.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004722 if (delay < 50)
4723 delay += 10;
4724 }
4725
Bram Moolenaar0f873732019-12-05 20:28:46 +01004726 // Close the pipe
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004727 CloseHandle(g_hChildStd_OUT_Rd);
4728 if (g_hChildStd_IN_Wr != NULL)
4729 CloseHandle(g_hChildStd_IN_Wr);
4730
4731 WaitForSingleObject(pi.hProcess, INFINITE);
4732
Bram Moolenaar0f873732019-12-05 20:28:46 +01004733 // Get the command exit code
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004734 GetExitCodeProcess(pi.hProcess, &ret);
4735
4736 if (options & SHELL_READ)
4737 {
4738 if (ga.ga_len > 0)
4739 {
4740 append_ga_line(&ga);
Bram Moolenaar0f873732019-12-05 20:28:46 +01004741 // remember that the NL was missing
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004742 curbuf->b_no_eol_lnum = curwin->w_cursor.lnum;
4743 }
4744 else
4745 curbuf->b_no_eol_lnum = 0;
4746 ga_clear(&ga);
4747 }
4748
Bram Moolenaar0f873732019-12-05 20:28:46 +01004749 // Close the handles to the subprocess, so that it goes away
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004750 CloseHandle(pi.hThread);
4751 CloseHandle(pi.hProcess);
4752
4753 return ret;
4754}
4755
4756 static int
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004757mch_system_g(char *cmd, int options)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004758{
Bram Moolenaar0f873732019-12-05 20:28:46 +01004759 // if we can pipe and the shelltemp option is off
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004760 if (!p_stmp)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004761 return mch_system_piped(cmd, options);
4762 else
4763 return mch_system_classic(cmd, options);
4764}
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004765#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004766
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004767#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004768 static int
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02004769mch_system_c(char *cmd, int options UNUSED)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004770{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004771 int ret;
4772 WCHAR *wcmd;
Bram Moolenaar2efc44b2019-10-05 12:09:32 +02004773 char_u *buf;
4774 size_t len;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004775
Bram Moolenaar2efc44b2019-10-05 12:09:32 +02004776 // If the command starts and ends with double quotes, enclose the command
4777 // in parentheses.
4778 len = STRLEN(cmd);
4779 if (len >= 2 && cmd[0] == '"' && cmd[len - 1] == '"')
4780 {
4781 len += 3;
4782 buf = alloc(len);
4783 if (buf == NULL)
4784 return -1;
4785 vim_snprintf((char *)buf, len, "(%s)", cmd);
4786 wcmd = enc_to_utf16(buf, NULL);
4787 free(buf);
4788 }
4789 else
4790 wcmd = enc_to_utf16((char_u *)cmd, NULL);
4791
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004792 if (wcmd == NULL)
4793 return -1;
4794
4795 ret = _wsystem(wcmd);
4796 vim_free(wcmd);
4797 return ret;
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004798}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004799
4800#endif
4801
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004802 static int
4803mch_system(char *cmd, int options)
4804{
4805#ifdef VIMDLL
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02004806 if (gui.in_use || gui.starting)
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004807 return mch_system_g(cmd, options);
4808 else
4809 return mch_system_c(cmd, options);
4810#elif defined(FEAT_GUI_MSWIN)
4811 return mch_system_g(cmd, options);
4812#else
4813 return mch_system_c(cmd, options);
4814#endif
4815}
4816
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004817#if defined(FEAT_GUI) && defined(FEAT_TERMINAL)
4818/*
4819 * Use a terminal window to run a shell command in.
4820 */
4821 static int
4822mch_call_shell_terminal(
4823 char_u *cmd,
Bram Moolenaar0f873732019-12-05 20:28:46 +01004824 int options UNUSED) // SHELL_*, see vim.h
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004825{
4826 jobopt_T opt;
4827 char_u *newcmd = NULL;
4828 typval_T argvar[2];
4829 long_u cmdlen;
4830 int retval = -1;
4831 buf_T *buf;
Bram Moolenaarf9c38832018-06-19 19:59:20 +02004832 job_T *job;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004833 aco_save_T aco;
Bram Moolenaar0f873732019-12-05 20:28:46 +01004834 oparg_T oa; // operator arguments
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004835
Bram Moolenaar42f652f2018-03-19 21:44:37 +01004836 if (cmd == NULL)
4837 cmdlen = STRLEN(p_sh) + 1;
4838 else
4839 cmdlen = STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10;
Bram Moolenaar18a4ba22019-05-24 19:39:03 +02004840 newcmd = alloc(cmdlen);
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004841 if (newcmd == NULL)
4842 return 255;
Bram Moolenaar42f652f2018-03-19 21:44:37 +01004843 if (cmd == NULL)
4844 {
4845 STRCPY(newcmd, p_sh);
4846 ch_log(NULL, "starting terminal to run a shell");
4847 }
4848 else
4849 {
4850 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s", p_sh, p_shcf, cmd);
4851 ch_log(NULL, "starting terminal for system command '%s'", cmd);
4852 }
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004853
4854 init_job_options(&opt);
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004855
4856 argvar[0].v_type = VAR_STRING;
4857 argvar[0].vval.v_string = newcmd;
4858 argvar[1].v_type = VAR_UNKNOWN;
4859 buf = term_start(argvar, NULL, &opt, TERM_START_SYSTEM);
Bram Moolenaar81c3c89a2018-03-20 11:41:44 +01004860 if (buf == NULL)
Bram Moolenaar9029b912019-03-21 19:58:00 +01004861 {
4862 vim_free(newcmd);
Bram Moolenaar81c3c89a2018-03-20 11:41:44 +01004863 return 255;
Bram Moolenaar9029b912019-03-21 19:58:00 +01004864 }
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004865
Bram Moolenaarf9c38832018-06-19 19:59:20 +02004866 job = term_getjob(buf->b_term);
4867 ++job->jv_refcount;
4868
Bram Moolenaar0f873732019-12-05 20:28:46 +01004869 // Find a window to make "buf" curbuf.
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004870 aucmd_prepbuf(&aco, buf);
4871
4872 clear_oparg(&oa);
4873 while (term_use_loop())
4874 {
4875 if (oa.op_type == OP_NOP && oa.regname == NUL && !VIsual_active)
4876 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004877 // If terminal_loop() returns OK we got a key that is handled
4878 // in Normal model. We don't do redrawing anyway.
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004879 if (terminal_loop(TRUE) == OK)
4880 normal_cmd(&oa, TRUE);
4881 }
4882 else
4883 normal_cmd(&oa, TRUE);
4884 }
Bram Moolenaarf9c38832018-06-19 19:59:20 +02004885 retval = job->jv_exitval;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004886 ch_log(NULL, "system command finished");
4887
Bram Moolenaarf9c38832018-06-19 19:59:20 +02004888 job_unref(job);
4889
Bram Moolenaar0f873732019-12-05 20:28:46 +01004890 // restore curwin/curbuf and a few other things
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004891 aucmd_restbuf(&aco);
4892
4893 wait_return(TRUE);
4894 do_buffer(DOBUF_WIPE, DOBUF_FIRST, FORWARD, buf->b_fnum, TRUE);
4895
4896 vim_free(newcmd);
4897 return retval;
4898}
4899#endif
4900
Bram Moolenaar071d4272004-06-13 20:20:40 +00004901/*
4902 * Either execute a command by calling the shell or start a new shell
4903 */
4904 int
4905mch_call_shell(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004906 char_u *cmd,
Bram Moolenaar0f873732019-12-05 20:28:46 +01004907 int options) // SHELL_*, see vim.h
Bram Moolenaar071d4272004-06-13 20:20:40 +00004908{
4909 int x = 0;
4910 int tmode = cur_tmode;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004911 WCHAR szShellTitle[512];
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004912
Bram Moolenaarc9a9a0a2022-04-12 15:09:23 +01004913#ifdef FEAT_JOB_CHANNEL
4914 ch_log(NULL, "executing shell command: %s", cmd);
4915#endif
Bram Moolenaar0f873732019-12-05 20:28:46 +01004916 // Change the title to reflect that we are in a subshell.
K.Takataeeec2542021-06-02 13:28:16 +02004917 if (GetConsoleTitleW(szShellTitle, ARRAY_LENGTH(szShellTitle) - 4) > 0)
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004918 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004919 if (cmd == NULL)
4920 wcscat(szShellTitle, L" :sh");
4921 else
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004922 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004923 WCHAR *wn = enc_to_utf16((char_u *)cmd, NULL);
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004924
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004925 if (wn != NULL)
4926 {
4927 wcscat(szShellTitle, L" - !");
4928 if ((wcslen(szShellTitle) + wcslen(wn) <
K.Takataeeec2542021-06-02 13:28:16 +02004929 ARRAY_LENGTH(szShellTitle)))
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004930 wcscat(szShellTitle, wn);
4931 SetConsoleTitleW(szShellTitle);
4932 vim_free(wn);
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004933 }
4934 }
4935 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004936
4937 out_flush();
4938
4939#ifdef MCH_WRITE_DUMP
4940 if (fdDump)
4941 {
4942 fprintf(fdDump, "mch_call_shell(\"%s\", %d)\n", cmd, options);
4943 fflush(fdDump);
4944 }
4945#endif
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004946#if defined(FEAT_GUI) && defined(FEAT_TERMINAL)
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004947 // TODO: make the terminal window work with input or output redirected.
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004948 if (
4949# ifdef VIMDLL
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004950 gui.in_use &&
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004951# endif
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004952 vim_strchr(p_go, GO_TERMINAL) != NULL
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004953 && (options & (SHELL_FILTER|SHELL_DOOUT|SHELL_WRITE|SHELL_READ)) == 0)
4954 {
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004955 char_u *cmdbase = cmd;
4956
Bram Moolenaar4d5c1262019-09-20 17:20:02 +02004957 if (cmdbase != NULL)
4958 // Skip a leading quote and (.
4959 while (*cmdbase == '"' || *cmdbase == '(')
4960 ++cmdbase;
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004961
4962 // Check the command does not begin with "start "
Bram Moolenaar36e7a822019-11-13 21:49:24 +01004963 if (cmdbase == NULL || STRNICMP(cmdbase, "start", 5) != 0
4964 || !VIM_ISWHITE(cmdbase[5]))
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004965 {
4966 // Use a terminal window to run the command in.
4967 x = mch_call_shell_terminal(cmd, options);
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004968 resettitle();
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004969 return x;
4970 }
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004971 }
4972#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004973
4974 /*
4975 * Catch all deadly signals while running the external command, because a
4976 * CTRL-C, Ctrl-Break or illegal instruction might otherwise kill us.
4977 */
4978 signal(SIGINT, SIG_IGN);
4979#if defined(__GNUC__) && !defined(__MINGW32__)
4980 signal(SIGKILL, SIG_IGN);
4981#else
4982 signal(SIGBREAK, SIG_IGN);
4983#endif
4984 signal(SIGILL, SIG_IGN);
4985 signal(SIGFPE, SIG_IGN);
4986 signal(SIGSEGV, SIG_IGN);
4987 signal(SIGTERM, SIG_IGN);
4988 signal(SIGABRT, SIG_IGN);
4989
4990 if (options & SHELL_COOKED)
Bram Moolenaar0f873732019-12-05 20:28:46 +01004991 settmode(TMODE_COOK); // set to normal mode
Bram Moolenaar071d4272004-06-13 20:20:40 +00004992
4993 if (cmd == NULL)
4994 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004995 x = mch_system((char *)p_sh, options);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004996 }
4997 else
4998 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004999 // we use "command" or "cmd" to start the shell; slow but easy
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005000 char_u *newcmd = NULL;
5001 char_u *cmdbase = cmd;
5002 long_u cmdlen;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005003
Bram Moolenaar0f873732019-12-05 20:28:46 +01005004 // Skip a leading ", ( and "(.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005005 if (*cmdbase == '"' )
5006 ++cmdbase;
5007 if (*cmdbase == '(')
5008 ++cmdbase;
5009
Bram Moolenaar1c465442017-03-12 20:10:05 +01005010 if ((STRNICMP(cmdbase, "start", 5) == 0) && VIM_ISWHITE(cmdbase[5]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005011 {
5012 STARTUPINFO si;
5013 PROCESS_INFORMATION pi;
5014 DWORD flags = CREATE_NEW_CONSOLE;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01005015 INT n_show_cmd = SW_SHOWNORMAL;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005016 char_u *p;
5017
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01005018 ZeroMemory(&si, sizeof(si));
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005019 si.cb = sizeof(si);
5020 si.lpReserved = NULL;
5021 si.lpDesktop = NULL;
5022 si.lpTitle = NULL;
5023 si.dwFlags = 0;
5024 si.cbReserved2 = 0;
5025 si.lpReserved2 = NULL;
5026
5027 cmdbase = skipwhite(cmdbase + 5);
5028 if ((STRNICMP(cmdbase, "/min", 4) == 0)
Bram Moolenaar1c465442017-03-12 20:10:05 +01005029 && VIM_ISWHITE(cmdbase[4]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005030 {
5031 cmdbase = skipwhite(cmdbase + 4);
5032 si.dwFlags = STARTF_USESHOWWINDOW;
5033 si.wShowWindow = SW_SHOWMINNOACTIVE;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01005034 n_show_cmd = SW_SHOWMINNOACTIVE;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005035 }
5036 else if ((STRNICMP(cmdbase, "/b", 2) == 0)
Bram Moolenaar1c465442017-03-12 20:10:05 +01005037 && VIM_ISWHITE(cmdbase[2]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005038 {
5039 cmdbase = skipwhite(cmdbase + 2);
5040 flags = CREATE_NO_WINDOW;
5041 si.dwFlags = STARTF_USESTDHANDLES;
5042 si.hStdInput = CreateFile("\\\\.\\NUL", // File name
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005043 GENERIC_READ, // Access flags
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005044 0, // Share flags
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005045 NULL, // Security att.
5046 OPEN_EXISTING, // Open flags
5047 FILE_ATTRIBUTE_NORMAL, // File att.
5048 NULL); // Temp file
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005049 si.hStdOutput = si.hStdInput;
5050 si.hStdError = si.hStdInput;
5051 }
5052
Bram Moolenaar0f873732019-12-05 20:28:46 +01005053 // Remove a trailing ", ) and )" if they have a match
5054 // at the start of the command.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005055 if (cmdbase > cmd)
5056 {
5057 p = cmdbase + STRLEN(cmdbase);
5058 if (p > cmdbase && p[-1] == '"' && *cmd == '"')
5059 *--p = NUL;
5060 if (p > cmdbase && p[-1] == ')'
5061 && (*cmd =='(' || cmd[1] == '('))
5062 *--p = NUL;
5063 }
5064
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005065 newcmd = cmdbase;
5066 unescape_shellxquote(cmdbase, p_sxe);
5067
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005068 /*
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005069 * If creating new console, arguments are passed to the
5070 * 'cmd.exe' as-is. If it's not, arguments are not treated
5071 * correctly for current 'cmd.exe'. So unescape characters in
5072 * shellxescape except '|' for avoiding to be treated as
5073 * argument to them. Pass the arguments to sub-shell.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005074 */
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005075 if (flags != CREATE_NEW_CONSOLE)
5076 {
5077 char_u *subcmd;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01005078 char_u *cmd_shell = mch_getenv("COMSPEC");
5079
5080 if (cmd_shell == NULL || *cmd_shell == NUL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01005081 cmd_shell = (char_u *)default_shell();
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005082
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01005083 subcmd = vim_strsave_escaped_ext(cmdbase,
5084 (char_u *)"|", '^', FALSE);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005085 if (subcmd != NULL)
5086 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005087 // make "cmd.exe /c arguments"
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005088 cmdlen = STRLEN(cmd_shell) + STRLEN(subcmd) + 5;
Bram Moolenaar18a4ba22019-05-24 19:39:03 +02005089 newcmd = alloc(cmdlen);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005090 if (newcmd != NULL)
5091 vim_snprintf((char *)newcmd, cmdlen, "%s /c %s",
Bram Moolenaaree7d1002012-02-22 15:34:08 +01005092 cmd_shell, subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005093 else
5094 newcmd = cmdbase;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01005095 vim_free(subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005096 }
5097 }
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005098
5099 /*
5100 * Now, start the command as a process, so that it doesn't
5101 * inherit our handles which causes unpleasant dangling swap
5102 * files if we exit before the spawned process
5103 */
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005104 if (vim_create_process((char *)newcmd, FALSE, flags,
5105 &si, &pi, NULL, NULL))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005106 x = 0;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01005107 else if (vim_shell_execute((char *)newcmd, n_show_cmd)
5108 > (HINSTANCE)32)
5109 x = 0;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005110 else
5111 {
5112 x = -1;
Bram Moolenaar4f974752019-02-17 17:44:42 +01005113#ifdef FEAT_GUI_MSWIN
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005114# ifdef VIMDLL
5115 if (gui.in_use)
5116# endif
Bram Moolenaarac78dd42022-01-02 19:25:26 +00005117 emsg(_(e_command_not_found));
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005118#endif
5119 }
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005120
5121 if (newcmd != cmdbase)
5122 vim_free(newcmd);
5123
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01005124 if (si.dwFlags == STARTF_USESTDHANDLES && si.hStdInput != NULL)
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005125 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005126 // Close the handle to \\.\NUL created above.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005127 CloseHandle(si.hStdInput);
5128 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01005129 // Close the handles to the subprocess, so that it goes away
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005130 CloseHandle(pi.hThread);
5131 CloseHandle(pi.hProcess);
5132 }
5133 else
5134 {
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005135 cmdlen =
Bram Moolenaar4f974752019-02-17 17:44:42 +01005136#ifdef FEAT_GUI_MSWIN
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02005137 ((gui.in_use || gui.starting) ?
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005138 (!s_dont_use_vimrun && p_stmp ?
5139 STRLEN(vimrun_path) : STRLEN(p_sh) + STRLEN(p_shcf))
5140 : 0) +
Bram Moolenaar071d4272004-06-13 20:20:40 +00005141#endif
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005142 STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10;
Bram Moolenaar0fde2902008-03-16 13:54:13 +00005143
Bram Moolenaar18a4ba22019-05-24 19:39:03 +02005144 newcmd = alloc(cmdlen);
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005145 if (newcmd != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005146 {
Bram Moolenaar4f974752019-02-17 17:44:42 +01005147#if defined(FEAT_GUI_MSWIN)
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005148 if (
5149# ifdef VIMDLL
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02005150 (gui.in_use || gui.starting) &&
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005151# endif
5152 need_vimrun_warning)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005153 {
Bram Moolenaar63e43442016-11-19 17:28:44 +01005154 char *msg = _("VIMRUN.EXE not found in your $PATH.\n"
5155 "External commands will not pause after completion.\n"
5156 "See :help win32-vimrun for more information.");
5157 char *title = _("Vim Warning");
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005158 WCHAR *wmsg = enc_to_utf16((char_u *)msg, NULL);
5159 WCHAR *wtitle = enc_to_utf16((char_u *)title, NULL);
Bram Moolenaar63e43442016-11-19 17:28:44 +01005160
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005161 if (wmsg != NULL && wtitle != NULL)
5162 MessageBoxW(NULL, wmsg, wtitle, MB_ICONWARNING);
5163 vim_free(wmsg);
5164 vim_free(wtitle);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005165 need_vimrun_warning = FALSE;
5166 }
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005167 if (
5168# ifdef VIMDLL
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02005169 (gui.in_use || gui.starting) &&
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005170# endif
5171 !s_dont_use_vimrun && p_stmp)
Bram Moolenaarfcc4d922019-05-24 13:32:36 +02005172 // Use vimrun to execute the command. It opens a console
5173 // window, which can be closed without killing Vim.
Bram Moolenaarcc448b32010-07-14 16:52:17 +02005174 vim_snprintf((char *)newcmd, cmdlen, "%s%s%s %s %s",
Bram Moolenaar071d4272004-06-13 20:20:40 +00005175 vimrun_path,
5176 (msg_silent != 0 || (options & SHELL_DOOUT))
5177 ? "-s " : "",
5178 p_sh, p_shcf, cmd);
Bram Moolenaarfcc4d922019-05-24 13:32:36 +02005179 else if (
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005180# ifdef VIMDLL
Bram Moolenaarfcc4d922019-05-24 13:32:36 +02005181 (gui.in_use || gui.starting) &&
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005182# endif
Bram Moolenaar0e6bfb92019-07-31 20:53:56 +02005183 s_dont_use_vimrun && STRCMP(p_shcf, "/c") == 0)
Bram Moolenaarfcc4d922019-05-24 13:32:36 +02005184 // workaround for the case that "vimrun" does not exist
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005185 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s %s %s",
5186 p_sh, p_shcf, p_sh, p_shcf, cmd);
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005187 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00005188#endif
Bram Moolenaarcc448b32010-07-14 16:52:17 +02005189 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s",
Bram Moolenaar0fde2902008-03-16 13:54:13 +00005190 p_sh, p_shcf, cmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005191 x = mch_system((char *)newcmd, options);
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005192 vim_free(newcmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005193 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005194 }
5195 }
5196
5197 if (tmode == TMODE_RAW)
Bram Moolenaar3b1f18f2020-05-16 23:15:08 +02005198 {
5199 // The shell may have messed with the mode, always set it.
5200 cur_tmode = TMODE_UNKNOWN;
Bram Moolenaar0f873732019-12-05 20:28:46 +01005201 settmode(TMODE_RAW); // set to raw mode
Bram Moolenaar3b1f18f2020-05-16 23:15:08 +02005202 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005203
Bram Moolenaar0f873732019-12-05 20:28:46 +01005204 // Print the return value, unless "vimrun" was used.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005205 if (x != 0 && !(options & SHELL_SILENT) && !emsg_silent
Bram Moolenaar4f974752019-02-17 17:44:42 +01005206#if defined(FEAT_GUI_MSWIN)
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02005207 && ((gui.in_use || gui.starting) ?
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005208 ((options & SHELL_DOOUT) || s_dont_use_vimrun || !p_stmp) : 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005209#endif
5210 )
5211 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005212 smsg(_("shell returned %d"), x);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005213 msg_putchar('\n');
5214 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005215 resettitle();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005216
5217 signal(SIGINT, SIG_DFL);
5218#if defined(__GNUC__) && !defined(__MINGW32__)
5219 signal(SIGKILL, SIG_DFL);
5220#else
5221 signal(SIGBREAK, SIG_DFL);
5222#endif
5223 signal(SIGILL, SIG_DFL);
5224 signal(SIGFPE, SIG_DFL);
5225 signal(SIGSEGV, SIG_DFL);
5226 signal(SIGTERM, SIG_DFL);
5227 signal(SIGABRT, SIG_DFL);
5228
5229 return x;
5230}
5231
Bram Moolenaar509ce2a2016-03-11 22:52:15 +01005232#if defined(FEAT_JOB_CHANNEL) || defined(PROTO)
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005233 static HANDLE
5234job_io_file_open(
Bram Moolenaar972c3b82017-01-12 21:44:49 +01005235 char_u *fname,
5236 DWORD dwDesiredAccess,
5237 DWORD dwShareMode,
5238 LPSECURITY_ATTRIBUTES lpSecurityAttributes,
5239 DWORD dwCreationDisposition,
5240 DWORD dwFlagsAndAttributes)
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005241{
5242 HANDLE h;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005243 WCHAR *wn;
Bram Moolenaara12a1612019-01-24 16:39:02 +01005244
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005245 wn = enc_to_utf16(fname, NULL);
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005246 if (wn == NULL)
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005247 return INVALID_HANDLE_VALUE;
5248
5249 h = CreateFileW(wn, dwDesiredAccess, dwShareMode,
5250 lpSecurityAttributes, dwCreationDisposition,
5251 dwFlagsAndAttributes, NULL);
5252 vim_free(wn);
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005253 return h;
5254}
5255
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005256/*
5257 * Turn the dictionary "env" into a NUL separated list that can be used as the
5258 * environment argument of vim_create_process().
5259 */
Bram Moolenaarba6febd2017-10-30 21:56:23 +01005260 void
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005261win32_build_env(dict_T *env, garray_T *gap, int is_terminal)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005262{
5263 hashitem_T *hi;
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005264 long_u todo = env != NULL ? env->dv_hashtab.ht_used : 0;
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005265 LPVOID base = GetEnvironmentStringsW();
5266
Bram Moolenaar0f873732019-12-05 20:28:46 +01005267 // for last \0
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005268 if (ga_grow(gap, 1) == FAIL)
5269 return;
5270
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005271 if (env != NULL)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005272 {
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005273 for (hi = env->dv_hashtab.ht_array; todo > 0; ++hi)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005274 {
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005275 if (!HASHITEM_EMPTY(hi))
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005276 {
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005277 typval_T *item = &dict_lookup(hi)->di_tv;
5278 WCHAR *wkey = enc_to_utf16((char_u *)hi->hi_key, NULL);
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005279 WCHAR *wval = enc_to_utf16(tv_get_string(item), NULL);
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005280 --todo;
5281 if (wkey != NULL && wval != NULL)
5282 {
5283 size_t n;
5284 size_t lkey = wcslen(wkey);
5285 size_t lval = wcslen(wval);
Bram Moolenaar60104f12017-08-14 23:25:04 +02005286
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005287 if (ga_grow(gap, (int)(lkey + lval + 2)) != OK)
5288 continue;
5289 for (n = 0; n < lkey; n++)
5290 *((WCHAR*)gap->ga_data + gap->ga_len++) = wkey[n];
5291 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'=';
5292 for (n = 0; n < lval; n++)
5293 *((WCHAR*)gap->ga_data + gap->ga_len++) = wval[n];
5294 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5295 }
Bram Moolenaarbdace832019-03-02 10:13:42 +01005296 vim_free(wkey);
5297 vim_free(wval);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005298 }
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005299 }
5300 }
5301
Bram Moolenaar355757a2020-02-10 22:06:32 +01005302 if (base)
5303 {
5304 WCHAR *p = (WCHAR*) base;
5305
5306 // for last \0
5307 if (ga_grow(gap, 1) == FAIL)
5308 return;
5309
5310 while (*p != 0 || *(p + 1) != 0)
5311 {
5312 if (ga_grow(gap, 1) == OK)
5313 *((WCHAR*)gap->ga_data + gap->ga_len++) = *p;
5314 p++;
5315 }
5316 FreeEnvironmentStrings(base);
5317 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5318 }
5319
Bram Moolenaar493359e2018-06-12 20:25:52 +02005320# if defined(FEAT_CLIENTSERVER) || defined(FEAT_TERMINAL)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005321 {
Bram Moolenaar493359e2018-06-12 20:25:52 +02005322# ifdef FEAT_CLIENTSERVER
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005323 char_u *servername = get_vim_var_str(VV_SEND_SERVER);
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005324 size_t servername_len = STRLEN(servername);
Bram Moolenaar493359e2018-06-12 20:25:52 +02005325# endif
5326# ifdef FEAT_TERMINAL
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005327 char_u *version = get_vim_var_str(VV_VERSION);
5328 size_t version_len = STRLEN(version);
Bram Moolenaar493359e2018-06-12 20:25:52 +02005329# endif
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005330 // size of "VIM_SERVERNAME=" and value,
5331 // plus "VIM_TERMINAL=" and value,
5332 // plus two terminating NULs
5333 size_t n = 0
Bram Moolenaar493359e2018-06-12 20:25:52 +02005334# ifdef FEAT_CLIENTSERVER
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005335 + 15 + servername_len
Bram Moolenaar493359e2018-06-12 20:25:52 +02005336# endif
5337# ifdef FEAT_TERMINAL
5338 + 13 + version_len + 2
5339# endif
5340 ;
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005341
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005342 if (ga_grow(gap, (int)n) == OK)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005343 {
Bram Moolenaar493359e2018-06-12 20:25:52 +02005344# ifdef FEAT_CLIENTSERVER
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005345 for (n = 0; n < 15; n++)
5346 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5347 (WCHAR)"VIM_SERVERNAME="[n];
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005348 for (n = 0; n < servername_len; n++)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005349 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5350 (WCHAR)servername[n];
5351 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
Bram Moolenaar493359e2018-06-12 20:25:52 +02005352# endif
5353# ifdef FEAT_TERMINAL
5354 if (is_terminal)
5355 {
5356 for (n = 0; n < 13; n++)
5357 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5358 (WCHAR)"VIM_TERMINAL="[n];
5359 for (n = 0; n < version_len; n++)
5360 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5361 (WCHAR)version[n];
5362 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5363 }
5364# endif
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005365 }
5366 }
Bram Moolenaar79c6b512018-06-12 21:11:12 +02005367# endif
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005368}
5369
Bram Moolenaarb091f302019-01-19 14:37:00 +01005370/*
5371 * Create a pair of pipes.
5372 * Return TRUE for success, FALSE for failure.
5373 */
5374 static BOOL
5375create_pipe_pair(HANDLE handles[2])
5376{
5377 static LONG s;
5378 char name[64];
5379 SECURITY_ATTRIBUTES sa;
5380
5381 sprintf(name, "\\\\?\\pipe\\vim-%08lx-%08lx",
5382 GetCurrentProcessId(),
5383 InterlockedIncrement(&s));
5384
5385 // Create named pipe. Max size of named pipe is 65535.
5386 handles[1] = CreateNamedPipe(
5387 name,
5388 PIPE_ACCESS_OUTBOUND | FILE_FLAG_OVERLAPPED,
5389 PIPE_TYPE_BYTE | PIPE_NOWAIT,
Bram Moolenaar24058382019-01-24 23:11:49 +01005390 1, MAX_NAMED_PIPE_SIZE, 0, 0, NULL);
Bram Moolenaarb091f302019-01-19 14:37:00 +01005391
5392 if (handles[1] == INVALID_HANDLE_VALUE)
5393 return FALSE;
5394
5395 sa.nLength = sizeof(sa);
5396 sa.bInheritHandle = TRUE;
5397 sa.lpSecurityDescriptor = NULL;
5398
5399 handles[0] = CreateFile(name,
5400 FILE_GENERIC_READ,
5401 FILE_SHARE_READ, &sa,
5402 OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
5403
5404 if (handles[0] == INVALID_HANDLE_VALUE)
5405 {
Bram Moolenaar6982f422019-02-16 16:48:01 +01005406 CloseHandle(handles[1]);
Bram Moolenaarb091f302019-01-19 14:37:00 +01005407 return FALSE;
5408 }
5409
5410 return TRUE;
5411}
5412
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005413 void
Bram Moolenaar5a1feb82017-07-22 18:04:08 +02005414mch_job_start(char *cmd, job_T *job, jobopt_T *options)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005415{
5416 STARTUPINFO si;
5417 PROCESS_INFORMATION pi;
Bram Moolenaar14207f42016-10-27 21:13:10 +02005418 HANDLE jo;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005419 SECURITY_ATTRIBUTES saAttr;
5420 channel_T *channel = NULL;
Bram Moolenaard8070362016-02-15 21:56:54 +01005421 HANDLE ifd[2];
5422 HANDLE ofd[2];
5423 HANDLE efd[2];
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005424 garray_T ga;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005425
5426 int use_null_for_in = options->jo_io[PART_IN] == JIO_NULL;
5427 int use_null_for_out = options->jo_io[PART_OUT] == JIO_NULL;
5428 int use_null_for_err = options->jo_io[PART_ERR] == JIO_NULL;
5429 int use_file_for_in = options->jo_io[PART_IN] == JIO_FILE;
5430 int use_file_for_out = options->jo_io[PART_OUT] == JIO_FILE;
5431 int use_file_for_err = options->jo_io[PART_ERR] == JIO_FILE;
5432 int use_out_for_err = options->jo_io[PART_ERR] == JIO_OUT;
5433
5434 if (use_out_for_err && use_null_for_out)
5435 use_null_for_err = TRUE;
Bram Moolenaard8070362016-02-15 21:56:54 +01005436
5437 ifd[0] = INVALID_HANDLE_VALUE;
5438 ifd[1] = INVALID_HANDLE_VALUE;
5439 ofd[0] = INVALID_HANDLE_VALUE;
5440 ofd[1] = INVALID_HANDLE_VALUE;
5441 efd[0] = INVALID_HANDLE_VALUE;
5442 efd[1] = INVALID_HANDLE_VALUE;
Bram Moolenaar04935fb2022-01-08 16:19:22 +00005443 ga_init2(&ga, sizeof(wchar_t), 500);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005444
Bram Moolenaar14207f42016-10-27 21:13:10 +02005445 jo = CreateJobObject(NULL, NULL);
5446 if (jo == NULL)
5447 {
5448 job->jv_status = JOB_FAILED;
5449 goto failed;
5450 }
5451
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005452 if (options->jo_env != NULL)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005453 win32_build_env(options->jo_env, &ga, FALSE);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005454
Bram Moolenaar76467df2016-02-12 19:30:26 +01005455 ZeroMemory(&pi, sizeof(pi));
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005456 ZeroMemory(&si, sizeof(si));
5457 si.cb = sizeof(si);
Bram Moolenaard8070362016-02-15 21:56:54 +01005458 si.dwFlags |= STARTF_USESHOWWINDOW;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005459 si.wShowWindow = SW_HIDE;
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005460
Bram Moolenaard8070362016-02-15 21:56:54 +01005461 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
5462 saAttr.bInheritHandle = TRUE;
5463 saAttr.lpSecurityDescriptor = NULL;
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005464
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005465 if (use_file_for_in)
5466 {
5467 char_u *fname = options->jo_io_name[PART_IN];
5468
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005469 ifd[0] = job_io_file_open(fname, GENERIC_READ,
5470 FILE_SHARE_READ | FILE_SHARE_WRITE,
5471 &saAttr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL);
5472 if (ifd[0] == INVALID_HANDLE_VALUE)
Bram Moolenaar94d01912016-03-08 13:48:51 +01005473 {
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00005474 semsg(_(e_cant_open_file_str), fname);
Bram Moolenaar94d01912016-03-08 13:48:51 +01005475 goto failed;
5476 }
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005477 }
Bram Moolenaarb091f302019-01-19 14:37:00 +01005478 else if (!use_null_for_in
5479 && (!create_pipe_pair(ifd)
5480 || !SetHandleInformation(ifd[1], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005481 goto failed;
5482
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005483 if (use_file_for_out)
5484 {
5485 char_u *fname = options->jo_io_name[PART_OUT];
5486
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005487 ofd[1] = job_io_file_open(fname, GENERIC_WRITE,
5488 FILE_SHARE_READ | FILE_SHARE_WRITE,
5489 &saAttr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL);
5490 if (ofd[1] == INVALID_HANDLE_VALUE)
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005491 {
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00005492 semsg(_(e_cant_open_file_str), fname);
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005493 goto failed;
5494 }
5495 }
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005496 else if (!use_null_for_out &&
5497 (!CreatePipe(&ofd[0], &ofd[1], &saAttr, 0)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005498 || !SetHandleInformation(ofd[0], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005499 goto failed;
5500
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005501 if (use_file_for_err)
5502 {
5503 char_u *fname = options->jo_io_name[PART_ERR];
5504
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005505 efd[1] = job_io_file_open(fname, GENERIC_WRITE,
5506 FILE_SHARE_READ | FILE_SHARE_WRITE,
5507 &saAttr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL);
5508 if (efd[1] == INVALID_HANDLE_VALUE)
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005509 {
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00005510 semsg(_(e_cant_open_file_str), fname);
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005511 goto failed;
5512 }
5513 }
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005514 else if (!use_out_for_err && !use_null_for_err &&
5515 (!CreatePipe(&efd[0], &efd[1], &saAttr, 0)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005516 || !SetHandleInformation(efd[0], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaard8070362016-02-15 21:56:54 +01005517 goto failed;
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005518
Bram Moolenaard8070362016-02-15 21:56:54 +01005519 si.dwFlags |= STARTF_USESTDHANDLES;
5520 si.hStdInput = ifd[0];
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005521 si.hStdOutput = ofd[1];
5522 si.hStdError = use_out_for_err ? ofd[1] : efd[1];
5523
5524 if (!use_null_for_in || !use_null_for_out || !use_null_for_err)
5525 {
Bram Moolenaarde279892016-03-11 22:19:44 +01005526 if (options->jo_set & JO_CHANNEL)
5527 {
5528 channel = options->jo_channel;
5529 if (channel != NULL)
5530 ++channel->ch_refcount;
5531 }
5532 else
5533 channel = add_channel();
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005534 if (channel == NULL)
5535 goto failed;
5536 }
Bram Moolenaard8070362016-02-15 21:56:54 +01005537
5538 if (!vim_create_process(cmd, TRUE,
Bram Moolenaar14207f42016-10-27 21:13:10 +02005539 CREATE_SUSPENDED |
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005540 CREATE_DEFAULT_ERROR_MODE |
5541 CREATE_NEW_PROCESS_GROUP |
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005542 CREATE_UNICODE_ENVIRONMENT |
Bram Moolenaar76467df2016-02-12 19:30:26 +01005543 CREATE_NEW_CONSOLE,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005544 &si, &pi,
5545 ga.ga_data,
5546 (char *)options->jo_cwd))
Bram Moolenaar76467df2016-02-12 19:30:26 +01005547 {
Bram Moolenaar14207f42016-10-27 21:13:10 +02005548 CloseHandle(jo);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005549 job->jv_status = JOB_FAILED;
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005550 goto failed;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005551 }
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005552
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005553 ga_clear(&ga);
5554
Bram Moolenaar14207f42016-10-27 21:13:10 +02005555 if (!AssignProcessToJobObject(jo, pi.hProcess))
5556 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005557 // if failing, switch the way to terminate
5558 // process with TerminateProcess.
Bram Moolenaar14207f42016-10-27 21:13:10 +02005559 CloseHandle(jo);
5560 jo = NULL;
5561 }
5562 ResumeThread(pi.hThread);
Bram Moolenaar75578a32016-03-10 16:33:31 +01005563 CloseHandle(pi.hThread);
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005564 job->jv_proc_info = pi;
Bram Moolenaar14207f42016-10-27 21:13:10 +02005565 job->jv_job_object = jo;
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005566 job->jv_status = JOB_STARTED;
5567
Bram Moolenaar641ad6c2016-09-01 18:32:11 +02005568 CloseHandle(ifd[0]);
5569 CloseHandle(ofd[1]);
5570 if (!use_out_for_err && !use_null_for_err)
Bram Moolenaarc25558b2016-03-03 21:02:23 +01005571 CloseHandle(efd[1]);
Bram Moolenaard8070362016-02-15 21:56:54 +01005572
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005573 job->jv_channel = channel;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005574 if (channel != NULL)
5575 {
5576 channel_set_pipes(channel,
5577 use_file_for_in || use_null_for_in
5578 ? INVALID_FD : (sock_T)ifd[1],
5579 use_file_for_out || use_null_for_out
5580 ? INVALID_FD : (sock_T)ofd[0],
5581 use_out_for_err || use_file_for_err || use_null_for_err
5582 ? INVALID_FD : (sock_T)efd[0]);
5583 channel_set_job(channel, job, options);
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005584 }
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005585 return;
5586
5587failed:
Bram Moolenaard8070362016-02-15 21:56:54 +01005588 CloseHandle(ifd[0]);
5589 CloseHandle(ofd[0]);
5590 CloseHandle(efd[0]);
5591 CloseHandle(ifd[1]);
5592 CloseHandle(ofd[1]);
5593 CloseHandle(efd[1]);
Bram Moolenaarde279892016-03-11 22:19:44 +01005594 channel_unref(channel);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005595 ga_clear(&ga);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005596}
5597
5598 char *
5599mch_job_status(job_T *job)
5600{
5601 DWORD dwExitCode = 0;
5602
Bram Moolenaar76467df2016-02-12 19:30:26 +01005603 if (!GetExitCodeProcess(job->jv_proc_info.hProcess, &dwExitCode)
5604 || dwExitCode != STILL_ACTIVE)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005605 {
Bram Moolenaareab089d2016-02-21 19:32:02 +01005606 job->jv_exitval = (int)dwExitCode;
Bram Moolenaar7df915d2016-11-17 17:25:32 +01005607 if (job->jv_status < JOB_ENDED)
Bram Moolenaar97792de2016-10-15 18:36:49 +02005608 {
5609 ch_log(job->jv_channel, "Job ended");
5610 job->jv_status = JOB_ENDED;
5611 }
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005612 return "dead";
5613 }
5614 return "run";
5615}
5616
Bram Moolenaar97792de2016-10-15 18:36:49 +02005617 job_T *
5618mch_detect_ended_job(job_T *job_list)
5619{
5620 HANDLE jobHandles[MAXIMUM_WAIT_OBJECTS];
5621 job_T *jobArray[MAXIMUM_WAIT_OBJECTS];
5622 job_T *job = job_list;
5623
5624 while (job != NULL)
5625 {
5626 DWORD n;
5627 DWORD result;
5628
5629 for (n = 0; n < MAXIMUM_WAIT_OBJECTS
5630 && job != NULL; job = job->jv_next)
5631 {
5632 if (job->jv_status == JOB_STARTED)
5633 {
5634 jobHandles[n] = job->jv_proc_info.hProcess;
5635 jobArray[n] = job;
5636 ++n;
5637 }
5638 }
5639 if (n == 0)
5640 continue;
5641 result = WaitForMultipleObjects(n, jobHandles, FALSE, 0);
5642 if (result >= WAIT_OBJECT_0 && result < WAIT_OBJECT_0 + n)
5643 {
5644 job_T *wait_job = jobArray[result - WAIT_OBJECT_0];
5645
5646 if (STRCMP(mch_job_status(wait_job), "dead") == 0)
5647 return wait_job;
5648 }
5649 }
5650 return NULL;
5651}
5652
Bram Moolenaarfb630902016-10-29 14:55:00 +02005653 static BOOL
5654terminate_all(HANDLE process, int code)
5655{
5656 PROCESSENTRY32 pe;
5657 HANDLE h = INVALID_HANDLE_VALUE;
5658 DWORD pid = GetProcessId(process);
5659
5660 if (pid != 0)
5661 {
5662 h = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
5663 if (h != INVALID_HANDLE_VALUE)
5664 {
5665 pe.dwSize = sizeof(PROCESSENTRY32);
5666 if (!Process32First(h, &pe))
5667 goto theend;
5668
5669 do
5670 {
5671 if (pe.th32ParentProcessID == pid)
5672 {
5673 HANDLE ph = OpenProcess(
5674 PROCESS_ALL_ACCESS, FALSE, pe.th32ProcessID);
5675 if (ph != NULL)
5676 {
5677 terminate_all(ph, code);
5678 CloseHandle(ph);
5679 }
5680 }
5681 } while (Process32Next(h, &pe));
5682
5683 CloseHandle(h);
5684 }
5685 }
5686
5687theend:
5688 return TerminateProcess(process, code);
5689}
5690
5691/*
5692 * Send a (deadly) signal to "job".
5693 * Return FAIL if it didn't work.
5694 */
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005695 int
Bram Moolenaar2d33e902017-08-11 16:31:54 +02005696mch_signal_job(job_T *job, char_u *how)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005697{
Bram Moolenaar923d9262016-02-25 20:56:01 +01005698 int ret;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005699
Bram Moolenaar923d9262016-02-25 20:56:01 +01005700 if (STRCMP(how, "term") == 0 || STRCMP(how, "kill") == 0 || *how == NUL)
Bram Moolenaar76467df2016-02-12 19:30:26 +01005701 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005702 // deadly signal
Bram Moolenaar14207f42016-10-27 21:13:10 +02005703 if (job->jv_job_object != NULL)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005704 {
5705 if (job->jv_channel != NULL && job->jv_channel->ch_anonymous_pipe)
5706 job->jv_channel->ch_killing = TRUE;
K.Takata135e1522022-01-29 15:27:58 +00005707 return TerminateJobObject(job->jv_job_object, (UINT)-1) ? OK : FAIL;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005708 }
Bram Moolenaarb3e195c2020-02-10 21:32:19 +01005709 return terminate_all(job->jv_proc_info.hProcess, -1) ? OK : FAIL;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005710 }
5711
5712 if (!AttachConsole(job->jv_proc_info.dwProcessId))
5713 return FAIL;
5714 ret = GenerateConsoleCtrlEvent(
Bram Moolenaar923d9262016-02-25 20:56:01 +01005715 STRCMP(how, "int") == 0 ? CTRL_C_EVENT : CTRL_BREAK_EVENT,
5716 job->jv_proc_info.dwProcessId)
5717 ? OK : FAIL;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005718 FreeConsole();
5719 return ret;
5720}
5721
5722/*
5723 * Clear the data related to "job".
5724 */
5725 void
5726mch_clear_job(job_T *job)
5727{
5728 if (job->jv_status != JOB_FAILED)
5729 {
Bram Moolenaar14207f42016-10-27 21:13:10 +02005730 if (job->jv_job_object != NULL)
5731 CloseHandle(job->jv_job_object);
Bram Moolenaar76467df2016-02-12 19:30:26 +01005732 CloseHandle(job->jv_proc_info.hProcess);
5733 }
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005734}
5735#endif
5736
Bram Moolenaar071d4272004-06-13 20:20:40 +00005737
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005738#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005739
5740/*
5741 * Start termcap mode
5742 */
5743 static void
5744termcap_mode_start(void)
5745{
5746 DWORD cmodein;
5747
5748 if (g_fTermcapMode)
5749 return;
5750
Bram Moolenaar81ccbf12020-04-15 21:05:30 +02005751 if (!p_rs && USE_VTP)
5752 vtp_printf("\033[?1049h");
5753
Bram Moolenaar071d4272004-06-13 20:20:40 +00005754 SaveConsoleBuffer(&g_cbNonTermcap);
5755
5756 if (g_cbTermcap.IsValid)
5757 {
5758 /*
5759 * We've been in termcap mode before. Restore certain screen
5760 * characteristics, including the buffer size and the window
5761 * size. Since we will be redrawing the screen, we don't need
5762 * to restore the actual contents of the buffer.
5763 */
5764 RestoreConsoleBuffer(&g_cbTermcap, FALSE);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005765 reset_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005766 SetConsoleWindowInfo(g_hConOut, TRUE, &g_cbTermcap.Info.srWindow);
5767 Rows = g_cbTermcap.Info.dwSize.Y;
5768 Columns = g_cbTermcap.Info.dwSize.X;
5769 }
5770 else
5771 {
5772 /*
5773 * This is our first time entering termcap mode. Clear the console
5774 * screen buffer, and resize the buffer to match the current window
5775 * size. We will use this as the size of our editing environment.
5776 */
5777 ClearConsoleBuffer(g_attrCurrent);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005778 set_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005779 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
5780 }
5781
Bram Moolenaar071d4272004-06-13 20:20:40 +00005782 resettitle();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005783
5784 GetConsoleMode(g_hConIn, &cmodein);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005785 if (g_fMouseActive)
Wez Furlong6ef5ab52021-05-30 19:29:41 +02005786 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00005787 cmodein |= ENABLE_MOUSE_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02005788 cmodein &= ~ENABLE_QUICK_EDIT_MODE;
5789 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005790 else
Wez Furlong6ef5ab52021-05-30 19:29:41 +02005791 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00005792 cmodein &= ~ENABLE_MOUSE_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02005793 cmodein |= g_cmodein & ENABLE_QUICK_EDIT_MODE;
5794 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005795 cmodein |= ENABLE_WINDOW_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02005796 SetConsoleMode(g_hConIn, cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005797
5798 redraw_later_clear();
5799 g_fTermcapMode = TRUE;
5800}
5801
5802
5803/*
5804 * End termcap mode
5805 */
5806 static void
5807termcap_mode_end(void)
5808{
5809 DWORD cmodein;
5810 ConsoleBuffer *cb;
5811 COORD coord;
5812 DWORD dwDummy;
5813
5814 if (!g_fTermcapMode)
5815 return;
5816
5817 SaveConsoleBuffer(&g_cbTermcap);
5818
5819 GetConsoleMode(g_hConIn, &cmodein);
5820 cmodein &= ~(ENABLE_MOUSE_INPUT | ENABLE_WINDOW_INPUT);
Wez Furlong6ef5ab52021-05-30 19:29:41 +02005821 cmodein |= g_cmodein & ENABLE_QUICK_EDIT_MODE;
5822 SetConsoleMode(g_hConIn, cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005823
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01005824# ifdef FEAT_RESTORE_ORIG_SCREEN
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01005825 cb = exiting ? &g_cbOrig : &g_cbNonTermcap;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01005826# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00005827 cb = &g_cbNonTermcap;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01005828# endif
Bram Moolenaar81ccbf12020-04-15 21:05:30 +02005829 RestoreConsoleBuffer(cb, p_rs);
Bram Moolenaardf543822020-01-30 11:53:59 +01005830 restore_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005831 SetConsoleCursorInfo(g_hConOut, &g_cci);
5832
5833 if (p_rs || exiting)
5834 {
5835 /*
5836 * Clear anything that happens to be on the current line.
5837 */
5838 coord.X = 0;
5839 coord.Y = (SHORT) (p_rs ? cb->Info.dwCursorPosition.Y : (Rows - 1));
5840 FillConsoleOutputCharacter(g_hConOut, ' ',
5841 cb->Info.dwSize.X, coord, &dwDummy);
5842 /*
5843 * The following is just for aesthetics. If we are exiting without
5844 * restoring the screen, then we want to have a prompt string
5845 * appear at the bottom line. However, the command interpreter
5846 * seems to always advance the cursor one line before displaying
5847 * the prompt string, which causes the screen to scroll. To
5848 * counter this, move the cursor up one line before exiting.
5849 */
5850 if (exiting && !p_rs)
5851 coord.Y--;
5852 /*
5853 * Position the cursor at the leftmost column of the desired row.
5854 */
Bram Moolenaar81ccbf12020-04-15 21:05:30 +02005855 SetConsoleCursorPosition(g_hConOut, coord);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005856 }
5857
Bram Moolenaar81ccbf12020-04-15 21:05:30 +02005858 if (!p_rs && USE_VTP)
Bram Moolenaar0afdcf82020-04-01 18:29:10 +02005859 vtp_printf("\033[?1049l");
5860
Bram Moolenaar071d4272004-06-13 20:20:40 +00005861 g_fTermcapMode = FALSE;
5862}
Bram Moolenaar0f873732019-12-05 20:28:46 +01005863#endif // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00005864
5865
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005866#if defined(FEAT_GUI_MSWIN) && !defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005867 void
5868mch_write(
Bram Moolenaar1266d672017-02-01 13:43:36 +01005869 char_u *s UNUSED,
5870 int len UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005871{
Bram Moolenaar0f873732019-12-05 20:28:46 +01005872 // never used
Bram Moolenaar071d4272004-06-13 20:20:40 +00005873}
5874
5875#else
5876
5877/*
5878 * clear `n' chars, starting from `coord'
5879 */
5880 static void
5881clear_chars(
5882 COORD coord,
5883 DWORD n)
5884{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005885 if (!USE_VTP)
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02005886 {
5887 DWORD dwDummy;
5888
5889 FillConsoleOutputCharacter(g_hConOut, ' ', n, coord, &dwDummy);
5890 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, n, coord,
5891 &dwDummy);
5892 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005893 else
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02005894 {
5895 set_console_color_rgb();
5896 gotoxy(coord.X + 1, coord.Y + 1);
5897 vtp_printf("\033[%dX", n);
5898 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005899}
5900
5901
5902/*
5903 * Clear the screen
5904 */
5905 static void
5906clear_screen(void)
5907{
5908 g_coord.X = g_coord.Y = 0;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005909
5910 if (!USE_VTP)
5911 clear_chars(g_coord, Rows * Columns);
5912 else
5913 {
5914 set_console_color_rgb();
5915 gotoxy(1, 1);
5916 vtp_printf("\033[2J");
5917 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005918}
5919
5920
5921/*
5922 * Clear to end of display
5923 */
5924 static void
5925clear_to_end_of_display(void)
5926{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005927 COORD save = g_coord;
5928
5929 if (!USE_VTP)
5930 clear_chars(g_coord, (Rows - g_coord.Y - 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005931 * Columns + (Columns - g_coord.X));
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005932 else
5933 {
5934 set_console_color_rgb();
5935 gotoxy(g_coord.X + 1, g_coord.Y + 1);
5936 vtp_printf("\033[0J");
5937
5938 gotoxy(save.X + 1, save.Y + 1);
5939 g_coord = save;
5940 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005941}
5942
5943
5944/*
5945 * Clear to end of line
5946 */
5947 static void
5948clear_to_end_of_line(void)
5949{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005950 COORD save = g_coord;
5951
5952 if (!USE_VTP)
5953 clear_chars(g_coord, Columns - g_coord.X);
5954 else
5955 {
5956 set_console_color_rgb();
5957 gotoxy(g_coord.X + 1, g_coord.Y + 1);
5958 vtp_printf("\033[0K");
5959
5960 gotoxy(save.X + 1, save.Y + 1);
5961 g_coord = save;
5962 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005963}
5964
5965
5966/*
5967 * Scroll the scroll region up by `cLines' lines
5968 */
5969 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005970scroll(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005971{
5972 COORD oldcoord = g_coord;
5973
5974 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
5975 delete_lines(cLines);
5976
5977 g_coord = oldcoord;
5978}
5979
5980
5981/*
5982 * Set the scroll region
5983 */
5984 static void
5985set_scroll_region(
5986 unsigned left,
5987 unsigned top,
5988 unsigned right,
5989 unsigned bottom)
5990{
5991 if (left >= right
5992 || top >= bottom
5993 || right > (unsigned) Columns - 1
5994 || bottom > (unsigned) Rows - 1)
5995 return;
5996
5997 g_srScrollRegion.Left = left;
5998 g_srScrollRegion.Top = top;
5999 g_srScrollRegion.Right = right;
6000 g_srScrollRegion.Bottom = bottom;
Bram Moolenaar6982f422019-02-16 16:48:01 +01006001}
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006002
Bram Moolenaar6982f422019-02-16 16:48:01 +01006003 static void
6004set_scroll_region_tb(
6005 unsigned top,
6006 unsigned bottom)
6007{
6008 if (top >= bottom || bottom > (unsigned)Rows - 1)
6009 return;
6010
6011 g_srScrollRegion.Top = top;
6012 g_srScrollRegion.Bottom = bottom;
6013}
6014
6015 static void
6016set_scroll_region_lr(
6017 unsigned left,
6018 unsigned right)
6019{
6020 if (left >= right || right > (unsigned)Columns - 1)
6021 return;
6022
6023 g_srScrollRegion.Left = left;
6024 g_srScrollRegion.Right = right;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006025}
6026
6027
6028/*
6029 * Insert `cLines' lines at the current cursor position
6030 */
6031 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006032insert_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006033{
Bram Moolenaar6982f422019-02-16 16:48:01 +01006034 SMALL_RECT source, clip;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006035 COORD dest;
6036 CHAR_INFO fill;
6037
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006038 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
6039
Bram Moolenaar6982f422019-02-16 16:48:01 +01006040 dest.X = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006041 dest.Y = g_coord.Y + cLines;
6042
Bram Moolenaar6982f422019-02-16 16:48:01 +01006043 source.Left = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006044 source.Top = g_coord.Y;
6045 source.Right = g_srScrollRegion.Right;
6046 source.Bottom = g_srScrollRegion.Bottom - cLines;
6047
Bram Moolenaar6982f422019-02-16 16:48:01 +01006048 clip.Left = g_srScrollRegion.Left;
6049 clip.Top = g_coord.Y;
6050 clip.Right = g_srScrollRegion.Right;
6051 clip.Bottom = g_srScrollRegion.Bottom;
6052
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006053 fill.Char.AsciiChar = ' ';
6054 if (!USE_VTP)
6055 fill.Attributes = g_attrCurrent;
6056 else
6057 fill.Attributes = g_attrDefault;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006058
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006059 set_console_color_rgb();
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006060
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006061 ScrollConsoleScreenBuffer(g_hConOut, &source, &clip, dest, &fill);
6062
Bram Moolenaar6982f422019-02-16 16:48:01 +01006063 // Here we have to deal with a win32 console flake: If the scroll
6064 // region looks like abc and we scroll c to a and fill with d we get
6065 // cbd... if we scroll block c one line at a time to a, we get cdd...
6066 // vim expects cdd consistently... So we have to deal with that
6067 // here... (this also occurs scrolling the same way in the other
6068 // direction).
Bram Moolenaar071d4272004-06-13 20:20:40 +00006069
6070 if (source.Bottom < dest.Y)
6071 {
6072 COORD coord;
Bram Moolenaar6982f422019-02-16 16:48:01 +01006073 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006074
Bram Moolenaar6982f422019-02-16 16:48:01 +01006075 coord.X = source.Left;
6076 for (i = clip.Top; i < dest.Y; ++i)
6077 {
6078 coord.Y = i;
6079 clear_chars(coord, source.Right - source.Left + 1);
6080 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006081 }
Bram Moolenaar06b7b582020-05-30 17:49:25 +02006082
6083 if (USE_WT)
6084 {
6085 COORD coord;
6086 int i;
6087
6088 coord.X = source.Left;
6089 for (i = source.Top; i < dest.Y; ++i)
6090 {
6091 coord.Y = i;
6092 clear_chars(coord, source.Right - source.Left + 1);
6093 }
6094 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006095}
6096
6097
6098/*
6099 * Delete `cLines' lines at the current cursor position
6100 */
6101 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006102delete_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006103{
Bram Moolenaar6982f422019-02-16 16:48:01 +01006104 SMALL_RECT source, clip;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006105 COORD dest;
6106 CHAR_INFO fill;
6107 int nb;
6108
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006109 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
6110
Bram Moolenaar6982f422019-02-16 16:48:01 +01006111 dest.X = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006112 dest.Y = g_coord.Y;
6113
Bram Moolenaar6982f422019-02-16 16:48:01 +01006114 source.Left = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006115 source.Top = g_coord.Y + cLines;
6116 source.Right = g_srScrollRegion.Right;
6117 source.Bottom = g_srScrollRegion.Bottom;
6118
Bram Moolenaar6982f422019-02-16 16:48:01 +01006119 clip.Left = g_srScrollRegion.Left;
6120 clip.Top = g_coord.Y;
6121 clip.Right = g_srScrollRegion.Right;
6122 clip.Bottom = g_srScrollRegion.Bottom;
6123
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006124 fill.Char.AsciiChar = ' ';
6125 if (!USE_VTP)
6126 fill.Attributes = g_attrCurrent;
6127 else
6128 fill.Attributes = g_attrDefault;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006129
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006130 set_console_color_rgb();
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006131
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006132 ScrollConsoleScreenBuffer(g_hConOut, &source, &clip, dest, &fill);
6133
Bram Moolenaar6982f422019-02-16 16:48:01 +01006134 // Here we have to deal with a win32 console flake; See insert_lines()
6135 // above.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006136
6137 nb = dest.Y + (source.Bottom - source.Top) + 1;
6138
6139 if (nb < source.Top)
6140 {
6141 COORD coord;
Bram Moolenaar6982f422019-02-16 16:48:01 +01006142 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006143
Bram Moolenaar6982f422019-02-16 16:48:01 +01006144 coord.X = source.Left;
6145 for (i = nb; i < clip.Bottom; ++i)
6146 {
6147 coord.Y = i;
6148 clear_chars(coord, source.Right - source.Left + 1);
6149 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006150 }
Bram Moolenaar06b7b582020-05-30 17:49:25 +02006151
6152 if (USE_WT)
6153 {
6154 COORD coord;
6155 int i;
6156
6157 coord.X = source.Left;
6158 for (i = nb; i <= source.Bottom; ++i)
6159 {
6160 coord.Y = i;
6161 clear_chars(coord, source.Right - source.Left + 1);
6162 }
6163 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006164}
6165
6166
6167/*
Bram Moolenaar2313b612019-09-27 14:14:32 +02006168 * Set the cursor position to (x,y) (1-based).
Bram Moolenaar071d4272004-06-13 20:20:40 +00006169 */
6170 static void
6171gotoxy(
6172 unsigned x,
6173 unsigned y)
6174{
6175 if (x < 1 || x > (unsigned)Columns || y < 1 || y > (unsigned)Rows)
6176 return;
6177
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006178 if (!USE_VTP)
Bram Moolenaar2313b612019-09-27 14:14:32 +02006179 {
Bram Moolenaar82e743c2020-03-26 15:39:53 +01006180 // There are reports of double-width characters not displayed
6181 // correctly. This workaround should fix it, similar to how it's done
6182 // for VTP.
6183 g_coord.X = 0;
6184 SetConsoleCursorPosition(g_hConOut, g_coord);
6185
Bram Moolenaar2313b612019-09-27 14:14:32 +02006186 // external cursor coords are 1-based; internal are 0-based
6187 g_coord.X = x - 1;
6188 g_coord.Y = y - 1;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006189 SetConsoleCursorPosition(g_hConOut, g_coord);
Bram Moolenaar2313b612019-09-27 14:14:32 +02006190 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006191 else
Bram Moolenaar2313b612019-09-27 14:14:32 +02006192 {
6193 // Move the cursor to the left edge of the screen to prevent screen
Bram Moolenaara1299742019-10-10 16:36:00 +02006194 // destruction. Insider build bug. Always enabled because it's cheap
6195 // and avoids mistakes with recognizing the build.
6196 vtp_printf("\033[%d;%dH", g_coord.Y + 1, 1);
Bram Moolenaar2313b612019-09-27 14:14:32 +02006197
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006198 vtp_printf("\033[%d;%dH", y, x);
Bram Moolenaar2313b612019-09-27 14:14:32 +02006199
6200 g_coord.X = x - 1;
6201 g_coord.Y = y - 1;
6202 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006203}
6204
6205
6206/*
6207 * Set the current text attribute = (foreground | background)
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006208 * See ../runtime/doc/os_win32.txt for the numbers.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006209 */
6210 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006211textattr(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006212{
Bram Moolenaar6383b922015-03-24 17:12:19 +01006213 g_attrCurrent = wAttr & 0xff;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006214
6215 SetConsoleTextAttribute(g_hConOut, wAttr);
6216}
6217
6218
6219 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006220textcolor(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006221{
Bram Moolenaar6383b922015-03-24 17:12:19 +01006222 g_attrCurrent = (g_attrCurrent & 0xf0) + (wAttr & 0x0f);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006223
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006224 if (!USE_VTP)
6225 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
6226 else
6227 vtp_sgr_bulk(wAttr);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006228}
6229
6230
6231 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006232textbackground(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006233{
Bram Moolenaar6383b922015-03-24 17:12:19 +01006234 g_attrCurrent = (g_attrCurrent & 0x0f) + ((wAttr & 0x0f) << 4);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006235
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006236 if (!USE_VTP)
6237 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
6238 else
6239 vtp_sgr_bulk(wAttr);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006240}
6241
6242
6243/*
6244 * restore the default text attribute (whatever we started with)
6245 */
6246 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006247normvideo(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006248{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006249 if (!USE_VTP)
6250 textattr(g_attrDefault);
6251 else
6252 vtp_sgr_bulk(0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006253}
6254
6255
6256static WORD g_attrPreStandout = 0;
6257
6258/*
6259 * Make the text standout, by brightening it
6260 */
6261 static void
6262standout(void)
6263{
6264 g_attrPreStandout = g_attrCurrent;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006265
Bram Moolenaar071d4272004-06-13 20:20:40 +00006266 textattr((WORD) (g_attrCurrent|FOREGROUND_INTENSITY|BACKGROUND_INTENSITY));
6267}
6268
6269
6270/*
6271 * Turn off standout mode
6272 */
6273 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006274standend(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006275{
6276 if (g_attrPreStandout)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006277 textattr(g_attrPreStandout);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006278
6279 g_attrPreStandout = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006280}
6281
6282
6283/*
Bram Moolenaarff1d0d42007-05-10 17:24:16 +00006284 * Set normal fg/bg color, based on T_ME. Called when t_me has been set.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006285 */
6286 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006287mch_set_normal_colors(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006288{
6289 char_u *p;
6290 int n;
6291
6292 cterm_normal_fg_color = (g_attrDefault & 0xf) + 1;
6293 cterm_normal_bg_color = ((g_attrDefault >> 4) & 0xf) + 1;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006294 if (
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006295# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006296 !p_tgc &&
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006297# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006298 T_ME[0] == ESC && T_ME[1] == '|')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006299 {
6300 p = T_ME + 2;
6301 n = getdigits(&p);
6302 if (*p == 'm' && n > 0)
6303 {
6304 cterm_normal_fg_color = (n & 0xf) + 1;
6305 cterm_normal_bg_color = ((n >> 4) & 0xf) + 1;
6306 }
6307 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006308# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006309 cterm_normal_fg_gui_color = INVALCOLOR;
6310 cterm_normal_bg_gui_color = INVALCOLOR;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006311# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006312}
6313
6314
6315/*
6316 * visual bell: flash the screen
6317 */
6318 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006319visual_bell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006320{
6321 COORD coordOrigin = {0, 0};
6322 WORD attrFlash = ~g_attrCurrent & 0xff;
6323
6324 DWORD dwDummy;
Bram Moolenaarc799fe22019-05-28 23:08:19 +02006325 LPWORD oldattrs = ALLOC_MULT(WORD, Rows * Columns);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006326
6327 if (oldattrs == NULL)
6328 return;
6329 ReadConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
6330 coordOrigin, &dwDummy);
6331 FillConsoleOutputAttribute(g_hConOut, attrFlash, Rows * Columns,
6332 coordOrigin, &dwDummy);
6333
Bram Moolenaar0f873732019-12-05 20:28:46 +01006334 Sleep(15); // wait for 15 msec
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006335 if (!USE_VTP)
6336 WriteConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
Bram Moolenaar071d4272004-06-13 20:20:40 +00006337 coordOrigin, &dwDummy);
6338 vim_free(oldattrs);
6339}
6340
6341
6342/*
6343 * Make the cursor visible or invisible
6344 */
6345 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006346cursor_visible(BOOL fVisible)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006347{
6348 s_cursor_visible = fVisible;
Bram Moolenaar2695de62020-04-17 21:13:01 +02006349
6350 if (USE_VTP)
6351 vtp_printf("\033[?25%c", fVisible ? 'h' : 'l');
6352
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006353# ifdef MCH_CURSOR_SHAPE
Bram Moolenaar071d4272004-06-13 20:20:40 +00006354 mch_update_cursor();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006355# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006356}
6357
6358
6359/*
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02006360 * Write "cbToWrite" bytes in `pchBuf' to the screen.
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006361 * Returns the number of bytes actually written (at least one).
Bram Moolenaar071d4272004-06-13 20:20:40 +00006362 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006363 static DWORD
Bram Moolenaar071d4272004-06-13 20:20:40 +00006364write_chars(
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006365 char_u *pchBuf,
6366 DWORD cbToWrite)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006367{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006368 COORD coord = g_coord;
6369 DWORD written;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006370 DWORD n, cchwritten;
6371 static DWORD cells;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006372 static WCHAR *unicodebuf = NULL;
6373 static int unibuflen = 0;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006374 static int length;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006375 int cp = enc_utf8 ? CP_UTF8 : enc_codepage;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006376 static WCHAR *utf8spbuf = NULL;
6377 static int utf8splength;
6378 static DWORD utf8spcells;
6379 static WCHAR **utf8usingbuf = &unicodebuf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006380
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006381 if (cbToWrite != 1 || *pchBuf != ' ' || !enc_utf8)
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006382 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006383 utf8usingbuf = &unicodebuf;
6384 do
6385 {
6386 length = MultiByteToWideChar(cp, 0, (LPCSTR)pchBuf, cbToWrite,
6387 unicodebuf, unibuflen);
6388 if (length && length <= unibuflen)
6389 break;
6390 vim_free(unicodebuf);
6391 unicodebuf = length ? LALLOC_MULT(WCHAR, length) : NULL;
6392 unibuflen = unibuflen ? 0 : length;
6393 } while(1);
6394 cells = mb_string2cells(pchBuf, cbToWrite);
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006395 }
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006396 else // cbToWrite == 1 && *pchBuf == ' ' && enc_utf8
6397 {
6398 if (utf8usingbuf != &utf8spbuf)
6399 {
6400 if (utf8spbuf == NULL)
6401 {
6402 cells = mb_string2cells((char_u *)" ", 1);
6403 length = MultiByteToWideChar(CP_UTF8, 0, " ", 1, NULL, 0);
6404 utf8spbuf = LALLOC_MULT(WCHAR, length);
6405 if (utf8spbuf != NULL)
6406 {
6407 MultiByteToWideChar(CP_UTF8, 0, " ", 1, utf8spbuf, length);
6408 utf8usingbuf = &utf8spbuf;
6409 utf8splength = length;
6410 utf8spcells = cells;
6411 }
6412 }
6413 else
6414 {
6415 utf8usingbuf = &utf8spbuf;
6416 length = utf8splength;
6417 cells = utf8spcells;
6418 }
6419 }
6420 }
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006421
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006422 if (!USE_VTP)
6423 {
6424 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, cells,
6425 coord, &written);
6426 // When writing fails or didn't write a single character, pretend one
6427 // character was written, otherwise we get stuck.
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006428 if (WriteConsoleOutputCharacterW(g_hConOut, *utf8usingbuf, length,
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006429 coord, &cchwritten) == 0
6430 || cchwritten == 0 || cchwritten == (DWORD)-1)
6431 cchwritten = 1;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006432 }
6433 else
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006434 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006435 if (WriteConsoleW(g_hConOut, *utf8usingbuf, length, &cchwritten,
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006436 NULL) == 0 || cchwritten == 0)
6437 cchwritten = 1;
6438 }
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006439
K.Takata135e1522022-01-29 15:27:58 +00006440 if (cchwritten == (DWORD)length)
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006441 {
6442 written = cbToWrite;
6443 g_coord.X += (SHORT)cells;
6444 }
6445 else
6446 {
6447 char_u *p = pchBuf;
6448 for (n = 0; n < cchwritten; n++)
6449 MB_CPTR_ADV(p);
6450 written = p - pchBuf;
6451 g_coord.X += (SHORT)mb_string2cells(pchBuf, written);
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006452 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006453
6454 while (g_coord.X > g_srScrollRegion.Right)
6455 {
6456 g_coord.X -= (SHORT) Columns;
6457 if (g_coord.Y < g_srScrollRegion.Bottom)
6458 g_coord.Y++;
6459 }
6460
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006461 // Cursor under VTP is always in the correct position, no need to reset.
6462 if (!USE_VTP)
6463 gotoxy(g_coord.X + 1, g_coord.Y + 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006464
6465 return written;
6466}
6467
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006468 static char_u *
6469get_seq(
6470 int *args,
6471 int *count,
6472 char_u *head)
6473{
6474 int argc;
6475 char_u *p;
6476
6477 if (head == NULL || *head != '\033')
6478 return NULL;
6479
6480 argc = 0;
6481 p = head;
6482 ++p;
6483 do
6484 {
6485 ++p;
6486 args[argc] = getdigits(&p);
6487 argc += (argc < 15) ? 1 : 0;
6488 } while (*p == ';');
6489 *count = argc;
6490
6491 return p;
6492}
6493
6494 static char_u *
6495get_sgr(
6496 int *args,
6497 int *count,
6498 char_u *head)
6499{
6500 char_u *p = get_seq(args, count, head);
6501
6502 return (p && *p == 'm') ? ++p : NULL;
6503}
6504
6505/*
6506 * Pointer to next if SGR (^[[n;2;*;*;*m), NULL otherwise.
6507 */
6508 static char_u *
6509sgrn2(
6510 char_u *head,
6511 int n)
6512{
6513 int argc;
6514 int args[16];
6515 char_u *p = get_sgr(args, &argc, head);
6516
6517 return p && argc == 5 && args[0] == n && args[1] == 2 ? p : NULL;
6518}
6519
6520/*
6521 * Pointer to next if SGR(^[[nm)<space>ESC, NULL otherwise.
6522 */
6523 static char_u *
6524sgrnc(
6525 char_u *head,
6526 int n)
6527{
6528 int argc;
6529 int args[16];
6530 char_u *p = get_sgr(args, &argc, head);
6531
6532 return p && argc == 1 && args[0] == n && (p = skipwhite(p)) && *p == '\033'
6533 ? p : NULL;
6534}
6535
6536 static char_u *
6537skipblank(char_u *q)
6538{
6539 char_u *p = q;
6540
6541 while (*p == ' ' || *p == '\t' || *p == '\n' || *p == '\r')
6542 ++p;
6543 return p;
6544}
6545
6546/*
6547 * Pointer to the next if any whitespace that may follow SGR is ESC, otherwise
6548 * NULL.
6549 */
6550 static char_u *
6551sgrn2c(
6552 char_u *head,
6553 int n)
6554{
6555 char_u *p = sgrn2(head, n);
6556
6557 return p && *p != NUL && (p = skipblank(p)) && *p == '\033' ? p : NULL;
6558}
6559
6560/*
6561 * If there is only a newline between the sequence immediately following it,
6562 * a pointer to the character following the newline is returned.
6563 * Otherwise NULL.
6564 */
6565 static char_u *
6566sgrn2cn(
6567 char_u *head,
6568 int n)
6569{
6570 char_u *p = sgrn2(head, n);
6571
6572 return p && p[0] == 0x0a && p[1] == '\033' ? ++p : NULL;
6573}
Bram Moolenaar071d4272004-06-13 20:20:40 +00006574
6575/*
6576 * mch_write(): write the output buffer to the screen, translating ESC
6577 * sequences into calls to console output routines.
6578 */
6579 void
6580mch_write(
6581 char_u *s,
6582 int len)
6583{
Bram Moolenaard23f8bd2021-04-21 11:30:48 +02006584 char_u *end = s + len;
6585
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006586# ifdef VIMDLL
6587 if (gui.in_use)
6588 return;
6589# endif
6590
Bram Moolenaar071d4272004-06-13 20:20:40 +00006591 if (!term_console)
6592 {
6593 write(1, s, (unsigned)len);
6594 return;
6595 }
6596
Bram Moolenaar0f873732019-12-05 20:28:46 +01006597 // translate ESC | sequences into faked bios calls
Bram Moolenaar071d4272004-06-13 20:20:40 +00006598 while (len--)
6599 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006600 int prefix = -1;
6601 char_u ch;
6602
6603 // While processing a sequence, on rare occasions it seems that another
6604 // sequence may be inserted asynchronously.
6605 if (len < 0)
6606 {
Bram Moolenaara4d158b2022-08-14 14:17:45 +01006607 redraw_all_later(UPD_CLEAR);
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006608 return;
6609 }
6610
Bram Moolenaard23f8bd2021-04-21 11:30:48 +02006611 while (s + ++prefix < end)
6612 {
6613 ch = s[prefix];
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006614 if (ch <= 0x1e && !(ch != '\n' && ch != '\r' && ch != '\b'
6615 && ch != '\a' && ch != '\033'))
6616 break;
Bram Moolenaard23f8bd2021-04-21 11:30:48 +02006617 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006618
6619 if (p_wd)
6620 {
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02006621 WaitForChar(p_wd, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006622 if (prefix != 0)
6623 prefix = 1;
6624 }
6625
6626 if (prefix != 0)
6627 {
6628 DWORD nWritten;
6629
6630 nWritten = write_chars(s, prefix);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006631# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006632 if (fdDump)
6633 {
6634 fputc('>', fdDump);
6635 fwrite(s, sizeof(char_u), nWritten, fdDump);
6636 fputs("<\n", fdDump);
6637 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006638# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006639 len -= (nWritten - 1);
6640 s += nWritten;
6641 }
6642 else if (s[0] == '\n')
6643 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006644 // \n, newline: go to the beginning of the next line or scroll
Bram Moolenaar071d4272004-06-13 20:20:40 +00006645 if (g_coord.Y == g_srScrollRegion.Bottom)
6646 {
6647 scroll(1);
6648 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Bottom + 1);
6649 }
6650 else
6651 {
6652 gotoxy(g_srScrollRegion.Left + 1, g_coord.Y + 2);
6653 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006654# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006655 if (fdDump)
6656 fputs("\\n\n", fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006657# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006658 s++;
6659 }
6660 else if (s[0] == '\r')
6661 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006662 // \r, carriage return: go to beginning of line
Bram Moolenaar071d4272004-06-13 20:20:40 +00006663 gotoxy(g_srScrollRegion.Left+1, g_coord.Y + 1);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006664# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006665 if (fdDump)
6666 fputs("\\r\n", fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006667# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006668 s++;
6669 }
6670 else if (s[0] == '\b')
6671 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006672 // \b, backspace: move cursor one position left
Bram Moolenaar071d4272004-06-13 20:20:40 +00006673 if (g_coord.X > g_srScrollRegion.Left)
6674 g_coord.X--;
6675 else if (g_coord.Y > g_srScrollRegion.Top)
6676 {
6677 g_coord.X = g_srScrollRegion.Right;
6678 g_coord.Y--;
6679 }
6680 gotoxy(g_coord.X + 1, g_coord.Y + 1);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006681# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006682 if (fdDump)
6683 fputs("\\b\n", fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006684# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006685 s++;
6686 }
6687 else if (s[0] == '\a')
6688 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006689 // \a, bell
Bram Moolenaar071d4272004-06-13 20:20:40 +00006690 MessageBeep(0xFFFFFFFF);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006691# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006692 if (fdDump)
6693 fputs("\\a\n", fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006694# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006695 s++;
6696 }
6697 else if (s[0] == ESC && len >= 3-1 && s[1] == '|')
6698 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006699# ifdef MCH_WRITE_DUMP
Bram Moolenaarc0197e22004-09-13 20:26:32 +00006700 char_u *old_s = s;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006701# endif
Bram Moolenaarc0197e22004-09-13 20:26:32 +00006702 char_u *p;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006703 int arg1 = 0, arg2 = 0, argc = 0, args[16];
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006704 char_u *sp;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006705
6706 switch (s[2])
6707 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006708 case '0': case '1': case '2': case '3': case '4':
6709 case '5': case '6': case '7': case '8': case '9':
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006710 if (*(p = get_seq(args, &argc, s)) != 'm')
6711 goto notsgr;
6712
6713 p = s;
6714
6715 // Handling frequent optional sequences. Output to the screen
6716 // takes too long, so do not output as much as possible.
6717
6718 // If resetFG,FG,BG,<cr>,BG,FG are connected, the preceding
6719 // resetFG,FG,BG are omitted.
6720 if (sgrn2(sgrn2(sgrn2cn(sgrn2(sgrnc(p, 39), 38), 48), 48), 38))
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006721 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006722 p = sgrn2(sgrn2(sgrnc(p, 39), 38), 48);
6723 len = len + 1 - (int)(p - s);
6724 s = p;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006725 break;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006726 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006727
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006728 // If FG,BG,BG,FG of SGR are connected, the first FG can be
6729 // omitted.
6730 if (sgrn2(sgrn2(sgrn2c((sp = sgrn2(p, 38)), 48), 48), 38))
6731 p = sp;
6732
6733 // If FG,BG,FG,BG of SGR are connected, the first FG can be
6734 // omitted.
6735 if (sgrn2(sgrn2(sgrn2c((sp = sgrn2(p, 38)), 48), 38), 48))
6736 p = sp;
6737
6738 // If BG,BG of SGR are connected, the first BG can be omitted.
6739 if (sgrn2((sp = sgrn2(p, 48)), 48))
6740 p = sp;
6741
6742 // If restoreFG and FG are connected, the restoreFG can be
Bram Moolenaar9f1983d2022-05-12 20:35:35 +01006743 // omitted.
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006744 if (sgrn2((sp = sgrnc(p, 39)), 38))
6745 p = sp;
6746
6747 p = get_seq(args, &argc, p);
6748
6749notsgr:
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006750 arg1 = args[0];
6751 arg2 = args[1];
6752 if (*p == 'm')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006753 {
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006754 if (argc == 1 && args[0] == 0)
6755 normvideo();
6756 else if (argc == 1)
6757 {
6758 if (USE_VTP)
6759 textcolor((WORD) arg1);
6760 else
6761 textattr((WORD) arg1);
6762 }
6763 else if (USE_VTP)
6764 vtp_sgr_bulks(argc, args);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006765 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006766 else if (argc == 2 && *p == 'H')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006767 {
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006768 gotoxy(arg2, arg1);
6769 }
6770 else if (argc == 2 && *p == 'r')
6771 {
6772 set_scroll_region(0, arg1 - 1, Columns - 1, arg2 - 1);
6773 }
Bram Moolenaar6982f422019-02-16 16:48:01 +01006774 else if (argc == 2 && *p == 'R')
6775 {
6776 set_scroll_region_tb(arg1, arg2);
6777 }
6778 else if (argc == 2 && *p == 'V')
6779 {
6780 set_scroll_region_lr(arg1, arg2);
6781 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006782 else if (argc == 1 && *p == 'A')
6783 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006784 gotoxy(g_coord.X + 1,
6785 max(g_srScrollRegion.Top, g_coord.Y - arg1) + 1);
6786 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006787 else if (argc == 1 && *p == 'b')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006788 {
6789 textbackground((WORD) arg1);
6790 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006791 else if (argc == 1 && *p == 'C')
6792 {
6793 gotoxy(min(g_srScrollRegion.Right, g_coord.X + arg1) + 1,
6794 g_coord.Y + 1);
6795 }
6796 else if (argc == 1 && *p == 'f')
6797 {
6798 textcolor((WORD) arg1);
6799 }
6800 else if (argc == 1 && *p == 'H')
6801 {
6802 gotoxy(1, arg1);
6803 }
6804 else if (argc == 1 && *p == 'L')
6805 {
6806 insert_lines(arg1);
6807 }
6808 else if (argc == 1 && *p == 'M')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006809 {
6810 delete_lines(arg1);
6811 }
6812
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006813 len -= (int)(p - s);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006814 s = p + 1;
6815 break;
6816
Bram Moolenaar071d4272004-06-13 20:20:40 +00006817 case 'A':
Bram Moolenaar071d4272004-06-13 20:20:40 +00006818 gotoxy(g_coord.X + 1,
6819 max(g_srScrollRegion.Top, g_coord.Y - 1) + 1);
6820 goto got3;
6821
6822 case 'B':
6823 visual_bell();
6824 goto got3;
6825
6826 case 'C':
Bram Moolenaar071d4272004-06-13 20:20:40 +00006827 gotoxy(min(g_srScrollRegion.Right, g_coord.X + 1) + 1,
6828 g_coord.Y + 1);
6829 goto got3;
6830
6831 case 'E':
6832 termcap_mode_end();
6833 goto got3;
6834
6835 case 'F':
6836 standout();
6837 goto got3;
6838
6839 case 'f':
6840 standend();
6841 goto got3;
6842
6843 case 'H':
6844 gotoxy(1, 1);
6845 goto got3;
6846
6847 case 'j':
6848 clear_to_end_of_display();
6849 goto got3;
6850
6851 case 'J':
6852 clear_screen();
6853 goto got3;
6854
6855 case 'K':
6856 clear_to_end_of_line();
6857 goto got3;
6858
6859 case 'L':
6860 insert_lines(1);
6861 goto got3;
6862
6863 case 'M':
6864 delete_lines(1);
6865 goto got3;
6866
6867 case 'S':
6868 termcap_mode_start();
6869 goto got3;
6870
6871 case 'V':
6872 cursor_visible(TRUE);
6873 goto got3;
6874
6875 case 'v':
6876 cursor_visible(FALSE);
6877 goto got3;
6878
6879 got3:
6880 s += 3;
6881 len -= 2;
6882 }
6883
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006884# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006885 if (fdDump)
6886 {
6887 fputs("ESC | ", fdDump);
6888 fwrite(old_s + 2, sizeof(char_u), s - old_s - 2, fdDump);
6889 fputc('\n', fdDump);
6890 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006891# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006892 }
K.Takatadf5320c2022-09-01 13:20:16 +01006893 else if (s[0] == ESC && len >= 3-1 && s[1] == '[')
6894 {
6895 int l = 2;
6896
6897 if (isdigit(s[l]))
6898 l++;
6899 if (s[l] == ' ' && s[l + 1] == 'q')
6900 {
6901 // DECSCUSR (cursor style) sequences
6902 if (USE_VTP || USE_WT)
6903 vtp_printf("%.*s", l + 2, s); // Pass through
6904 s += l + 2;
6905 len -= l + 1;
6906 }
6907 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006908 else
6909 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006910 // Write a single character
Bram Moolenaar071d4272004-06-13 20:20:40 +00006911 DWORD nWritten;
6912
6913 nWritten = write_chars(s, 1);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006914# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006915 if (fdDump)
6916 {
6917 fputc('>', fdDump);
6918 fwrite(s, sizeof(char_u), nWritten, fdDump);
6919 fputs("<\n", fdDump);
6920 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006921# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006922
6923 len -= (nWritten - 1);
6924 s += nWritten;
6925 }
6926 }
6927
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006928# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006929 if (fdDump)
6930 fflush(fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006931# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006932}
6933
Bram Moolenaar0f873732019-12-05 20:28:46 +01006934#endif // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00006935
6936
6937/*
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01006938 * Delay for "msec" milliseconds.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006939 */
6940 void
6941mch_delay(
6942 long msec,
Bram Moolenaar0981c872020-08-23 14:28:37 +02006943 int flags UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006944{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006945#if defined(FEAT_GUI_MSWIN) && !defined(VIMDLL)
Bram Moolenaar0f873732019-12-05 20:28:46 +01006946 Sleep((int)msec); // never wait for input
6947#else // Console
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006948# ifdef VIMDLL
6949 if (gui.in_use)
6950 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006951 Sleep((int)msec); // never wait for input
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006952 return;
6953 }
6954# endif
Bram Moolenaar0981c872020-08-23 14:28:37 +02006955 if (flags & MCH_DELAY_IGNOREINPUT)
Bram Moolenaar325b7a22004-07-05 15:58:32 +00006956# ifdef FEAT_MZSCHEME
6957 if (mzthreads_allowed() && p_mzq > 0 && msec > p_mzq)
6958 {
6959 int towait = p_mzq;
6960
Bram Moolenaar0f873732019-12-05 20:28:46 +01006961 // if msec is large enough, wait by portions in p_mzq
Bram Moolenaar325b7a22004-07-05 15:58:32 +00006962 while (msec > 0)
6963 {
6964 mzvim_check_threads();
6965 if (msec < towait)
6966 towait = msec;
6967 Sleep(towait);
6968 msec -= towait;
6969 }
6970 }
6971 else
6972# endif
6973 Sleep((int)msec);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006974 else
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02006975 WaitForChar(msec, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006976#endif
6977}
6978
6979
6980/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01006981 * This version of remove is not scared by a readonly (backup) file.
6982 * This can also remove a symbolic link like Unix.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006983 * Return 0 for success, -1 for failure.
6984 */
6985 int
6986mch_remove(char_u *name)
6987{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006988 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006989 int n;
6990
Bram Moolenaar203258c2016-01-17 22:15:16 +01006991 /*
6992 * On Windows, deleting a directory's symbolic link is done by
6993 * RemoveDirectory(): mch_rmdir. It seems unnatural, but it is fact.
6994 */
6995 if (mch_isdir(name) && mch_is_symbolic_link(name))
6996 return mch_rmdir(name);
6997
Bram Moolenaar12b559e2013-06-12 22:41:37 +02006998 win32_setattrs(name, FILE_ATTRIBUTE_NORMAL);
6999
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007000 wn = enc_to_utf16(name, NULL);
7001 if (wn == NULL)
7002 return -1;
7003
7004 n = DeleteFileW(wn) ? 0 : -1;
7005 vim_free(wn);
7006 return n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007007}
7008
7009
7010/*
Bram Moolenaarb9c31e72016-09-29 15:18:57 +02007011 * Check for an "interrupt signal": CTRL-break or CTRL-C.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007012 */
7013 void
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02007014mch_breakcheck(int force UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007015{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007016#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
7017# ifdef VIMDLL
7018 if (!gui.in_use)
7019# endif
7020 if (g_fCtrlCPressed || g_fCBrkPressed)
7021 {
7022 ctrl_break_was_pressed = g_fCBrkPressed;
7023 g_fCtrlCPressed = g_fCBrkPressed = FALSE;
7024 got_int = TRUE;
7025 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007026#endif
7027}
7028
Bram Moolenaar0f873732019-12-05 20:28:46 +01007029// physical RAM to leave for the OS
Bram Moolenaaree273972016-01-02 21:11:51 +01007030#define WINNT_RESERVE_BYTES (256*1024*1024)
Bram Moolenaaree273972016-01-02 21:11:51 +01007031
7032/*
7033 * How much main memory in KiB that can be used by VIM.
7034 */
Bram Moolenaaree273972016-01-02 21:11:51 +01007035 long_u
Bram Moolenaar1266d672017-02-01 13:43:36 +01007036mch_total_mem(int special UNUSED)
Bram Moolenaaree273972016-01-02 21:11:51 +01007037{
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007038 MEMORYSTATUSEX ms;
7039
Bram Moolenaar0f873732019-12-05 20:28:46 +01007040 // Need to use GlobalMemoryStatusEx() when there is more memory than
7041 // what fits in 32 bits.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007042 ms.dwLength = sizeof(MEMORYSTATUSEX);
7043 GlobalMemoryStatusEx(&ms);
7044 if (ms.ullAvailVirtual < ms.ullTotalPhys)
Bram Moolenaaree273972016-01-02 21:11:51 +01007045 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007046 // Process address space fits in physical RAM, use all of it.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007047 return (long_u)(ms.ullAvailVirtual / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01007048 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007049 if (ms.ullTotalPhys <= WINNT_RESERVE_BYTES)
Bram Moolenaaree273972016-01-02 21:11:51 +01007050 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007051 // Catch old NT box or perverse hardware setup.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007052 return (long_u)((ms.ullTotalPhys / 2) / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01007053 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01007054 // Use physical RAM less reserve for OS + data.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007055 return (long_u)((ms.ullTotalPhys - WINNT_RESERVE_BYTES) / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01007056}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007057
Bram Moolenaar071d4272004-06-13 20:20:40 +00007058/*
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007059 * mch_wrename() works around a bug in rename (aka MoveFile) in
Bram Moolenaar071d4272004-06-13 20:20:40 +00007060 * Windows 95: rename("foo.bar", "foo.bar~") will generate a
7061 * file whose short file name is "FOO.BAR" (its long file name will
7062 * be correct: "foo.bar~"). Because a file can be accessed by
7063 * either its SFN or its LFN, "foo.bar" has effectively been
7064 * renamed to "foo.bar", which is not at all what was wanted. This
7065 * seems to happen only when renaming files with three-character
7066 * extensions by appending a suffix that does not include ".".
7067 * Windows NT gets it right, however, with an SFN of "FOO~1.BAR".
7068 *
7069 * There is another problem, which isn't really a bug but isn't right either:
7070 * When renaming "abcdef~1.txt" to "abcdef~1.txt~", the short name can be
7071 * "abcdef~1.txt" again. This has been reported on Windows NT 4.0 with
7072 * service pack 6. Doesn't seem to happen on Windows 98.
7073 *
7074 * Like rename(), returns 0 upon success, non-zero upon failure.
7075 * Should probably set errno appropriately when errors occur.
7076 */
7077 int
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007078mch_wrename(WCHAR *wold, WCHAR *wnew)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007079{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007080 WCHAR *p;
7081 int i;
7082 WCHAR szTempFile[_MAX_PATH + 1];
7083 WCHAR szNewPath[_MAX_PATH + 1];
Bram Moolenaar071d4272004-06-13 20:20:40 +00007084 HANDLE hf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007085
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007086 // No need to play tricks unless the file name contains a "~" as the
7087 // seventh character.
7088 p = wold;
7089 for (i = 0; wold[i] != NUL; ++i)
7090 if ((wold[i] == '/' || wold[i] == '\\' || wold[i] == ':')
7091 && wold[i + 1] != 0)
7092 p = wold + i + 1;
7093 if ((int)(wold + i - p) < 8 || p[6] != '~')
7094 return (MoveFileW(wold, wnew) == 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007095
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007096 // Get base path of new file name. Undocumented feature: If pszNewFile is
7097 // a directory, no error is returned and pszFilePart will be NULL.
7098 if (GetFullPathNameW(wnew, _MAX_PATH, szNewPath, &p) == 0 || p == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007099 return -1;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007100 *p = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007101
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007102 // Get (and create) a unique temporary file name in directory of new file
7103 if (GetTempFileNameW(szNewPath, L"VIM", 0, szTempFile) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007104 return -2;
7105
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007106 // blow the temp file away
7107 if (!DeleteFileW(szTempFile))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007108 return -3;
7109
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007110 // rename old file to the temp file
7111 if (!MoveFileW(wold, szTempFile))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007112 return -4;
7113
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007114 // now create an empty file called pszOldFile; this prevents the operating
7115 // system using pszOldFile as an alias (SFN) if we're renaming within the
7116 // same directory. For example, we're editing a file called
7117 // filename.asc.txt by its SFN, filena~1.txt. If we rename filena~1.txt
7118 // to filena~1.txt~ (i.e., we're making a backup while writing it), the
7119 // SFN for filena~1.txt~ will be filena~1.txt, by default, which will
7120 // cause all sorts of problems later in buf_write(). So, we create an
7121 // empty file called filena~1.txt and the system will have to find some
7122 // other SFN for filena~1.txt~, such as filena~2.txt
7123 if ((hf = CreateFileW(wold, GENERIC_WRITE, 0, NULL, CREATE_NEW,
Bram Moolenaar071d4272004-06-13 20:20:40 +00007124 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
7125 return -5;
7126 if (!CloseHandle(hf))
7127 return -6;
7128
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007129 // rename the temp file to the new file
7130 if (!MoveFileW(szTempFile, wnew))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007131 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007132 // Renaming failed. Rename the file back to its old name, so that it
7133 // looks like nothing happened.
7134 (void)MoveFileW(szTempFile, wold);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007135 return -7;
7136 }
7137
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007138 // Seems to be left around on Novell filesystems
7139 DeleteFileW(szTempFile);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007140
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007141 // finally, remove the empty old file
7142 if (!DeleteFileW(wold))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007143 return -8;
7144
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007145 return 0;
7146}
7147
7148
7149/*
7150 * Converts the filenames to UTF-16, then call mch_wrename().
7151 * Like rename(), returns 0 upon success, non-zero upon failure.
7152 */
7153 int
7154mch_rename(
7155 const char *pszOldFile,
7156 const char *pszNewFile)
7157{
7158 WCHAR *wold = NULL;
7159 WCHAR *wnew = NULL;
7160 int retval = -1;
7161
7162 wold = enc_to_utf16((char_u *)pszOldFile, NULL);
7163 wnew = enc_to_utf16((char_u *)pszNewFile, NULL);
7164 if (wold != NULL && wnew != NULL)
7165 retval = mch_wrename(wold, wnew);
7166 vim_free(wold);
7167 vim_free(wnew);
7168 return retval;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007169}
7170
7171/*
7172 * Get the default shell for the current hardware platform
7173 */
7174 char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007175default_shell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007176{
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007177 return "cmd.exe";
Bram Moolenaar071d4272004-06-13 20:20:40 +00007178}
7179
7180/*
7181 * mch_access() extends access() to do more detailed check on network drives.
7182 * Returns 0 if file "n" has access rights according to "p", -1 otherwise.
7183 */
7184 int
7185mch_access(char *n, int p)
7186{
7187 HANDLE hFile;
Bram Moolenaar0f873732019-12-05 20:28:46 +01007188 int retval = -1; // default: fail
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007189 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007190
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007191 wn = enc_to_utf16((char_u *)n, NULL);
7192 if (wn == NULL)
7193 return -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007194
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01007195 if (mch_isdir((char_u *)n))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007196 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00007197 WCHAR TempNameW[_MAX_PATH + 16] = L"";
Bram Moolenaar071d4272004-06-13 20:20:40 +00007198
7199 if (p & R_OK)
7200 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007201 // Read check is performed by seeing if we can do a find file on
7202 // the directory for any file.
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007203 int i;
7204 WIN32_FIND_DATAW d;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007205
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007206 for (i = 0; i < _MAX_PATH && wn[i] != 0; ++i)
7207 TempNameW[i] = wn[i];
7208 if (TempNameW[i - 1] != '\\' && TempNameW[i - 1] != '/')
7209 TempNameW[i++] = '\\';
7210 TempNameW[i++] = '*';
7211 TempNameW[i++] = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007212
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007213 hFile = FindFirstFileW(TempNameW, &d);
7214 if (hFile == INVALID_HANDLE_VALUE)
7215 goto getout;
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007216 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00007217 (void)FindClose(hFile);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007218 }
7219
7220 if (p & W_OK)
7221 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007222 // Trying to create a temporary file in the directory should catch
7223 // directories on read-only network shares. However, in
7224 // directories whose ACL allows writes but denies deletes will end
7225 // up keeping the temporary file :-(.
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007226 if (!GetTempFileNameW(wn, L"VIM", 0, TempNameW))
7227 goto getout;
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007228 else
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007229 DeleteFileW(TempNameW);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007230 }
7231 }
7232 else
7233 {
Bram Moolenaar5aa98962018-05-06 17:09:38 +02007234 // Don't consider a file read-only if another process has opened it.
7235 DWORD share_mode = FILE_SHARE_READ | FILE_SHARE_WRITE;
7236
Bram Moolenaar0f873732019-12-05 20:28:46 +01007237 // Trying to open the file for the required access does ACL, read-only
7238 // network share, and file attribute checks.
Bram Moolenaar5aa98962018-05-06 17:09:38 +02007239 DWORD access_mode = ((p & W_OK) ? GENERIC_WRITE : 0)
7240 | ((p & R_OK) ? GENERIC_READ : 0);
7241
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007242 hFile = CreateFileW(wn, access_mode, share_mode,
7243 NULL, OPEN_EXISTING, 0, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007244 if (hFile == INVALID_HANDLE_VALUE)
7245 goto getout;
7246 CloseHandle(hFile);
7247 }
7248
Bram Moolenaar0f873732019-12-05 20:28:46 +01007249 retval = 0; // success
Bram Moolenaar071d4272004-06-13 20:20:40 +00007250getout:
Bram Moolenaar071d4272004-06-13 20:20:40 +00007251 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007252 return retval;
7253}
7254
Bram Moolenaar071d4272004-06-13 20:20:40 +00007255/*
Bram Moolenaar36f692d2008-11-20 16:10:17 +00007256 * Version of open() that may use UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007257 */
7258 int
Bram Moolenaarb6843a02017-08-02 22:07:12 +02007259mch_open(const char *name, int flags, int mode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007260{
7261 WCHAR *wn;
7262 int f;
7263
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007264 wn = enc_to_utf16((char_u *)name, NULL);
7265 if (wn == NULL)
7266 return -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007267
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007268 f = _wopen(wn, flags, mode);
7269 vim_free(wn);
7270 return f;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007271}
7272
7273/*
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007274 * Version of fopen() that uses UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007275 */
7276 FILE *
Bram Moolenaarb6843a02017-08-02 22:07:12 +02007277mch_fopen(const char *name, const char *mode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007278{
7279 WCHAR *wn, *wm;
7280 FILE *f = NULL;
7281
Bram Moolenaara12a1612019-01-24 16:39:02 +01007282#if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0f873732019-12-05 20:28:46 +01007283 // Work around an annoying assertion in the Microsoft debug CRT
7284 // when mode's text/binary setting doesn't match _get_fmode().
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007285 char newMode = mode[strlen(mode) - 1];
7286 int oldMode = 0;
Bram Moolenaar0fde2902008-03-16 13:54:13 +00007287
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007288 _get_fmode(&oldMode);
7289 if (newMode == 't')
7290 _set_fmode(_O_TEXT);
7291 else if (newMode == 'b')
7292 _set_fmode(_O_BINARY);
Bram Moolenaara12a1612019-01-24 16:39:02 +01007293#endif
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007294 wn = enc_to_utf16((char_u *)name, NULL);
7295 wm = enc_to_utf16((char_u *)mode, NULL);
7296 if (wn != NULL && wm != NULL)
7297 f = _wfopen(wn, wm);
7298 vim_free(wn);
7299 vim_free(wm);
Bram Moolenaar0fde2902008-03-16 13:54:13 +00007300
Bram Moolenaara12a1612019-01-24 16:39:02 +01007301#if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007302 _set_fmode(oldMode);
Bram Moolenaara12a1612019-01-24 16:39:02 +01007303#endif
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007304 return f;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007305}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007306
Bram Moolenaar071d4272004-06-13 20:20:40 +00007307/*
7308 * SUB STREAM (aka info stream) handling:
7309 *
Bram Moolenaar8e7d6222020-12-18 19:49:56 +01007310 * NTFS can have sub streams for each file. The normal contents of a file is
7311 * stored in the main stream, and extra contents (author information, title and
7312 * so on) can be stored in a sub stream. After Windows 2000, the user can
7313 * access and store this information in sub streams via an explorer's property
7314 * menu item in the right click menu. This information in sub streams was lost
7315 * when copying only the main stream. Therefore we have to copy sub streams.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007316 *
7317 * Incomplete explanation:
7318 * http://msdn.microsoft.com/library/en-us/dnw2k/html/ntfs5.asp
7319 * More useful info and an example:
7320 * http://www.sysinternals.com/ntw2k/source/misc.shtml#streams
7321 */
7322
7323/*
7324 * Copy info stream data "substream". Read from the file with BackupRead(sh)
7325 * and write to stream "substream" of file "to".
7326 * Errors are ignored.
7327 */
7328 static void
7329copy_substream(HANDLE sh, void *context, WCHAR *to, WCHAR *substream, long len)
7330{
7331 HANDLE hTo;
7332 WCHAR *to_name;
7333
7334 to_name = malloc((wcslen(to) + wcslen(substream) + 1) * sizeof(WCHAR));
7335 wcscpy(to_name, to);
7336 wcscat(to_name, substream);
7337
7338 hTo = CreateFileW(to_name, GENERIC_WRITE, 0, NULL, OPEN_ALWAYS,
7339 FILE_ATTRIBUTE_NORMAL, NULL);
7340 if (hTo != INVALID_HANDLE_VALUE)
7341 {
7342 long done;
7343 DWORD todo;
7344 DWORD readcnt, written;
7345 char buf[4096];
7346
Bram Moolenaar0f873732019-12-05 20:28:46 +01007347 // Copy block of bytes at a time. Abort when something goes wrong.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007348 for (done = 0; done < len; done += written)
7349 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007350 // (size_t) cast for Borland C 5.5
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007351 todo = (DWORD)((size_t)(len - done) > sizeof(buf) ? sizeof(buf)
7352 : (size_t)(len - done));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007353 if (!BackupRead(sh, (LPBYTE)buf, todo, &readcnt,
7354 FALSE, FALSE, context)
7355 || readcnt != todo
7356 || !WriteFile(hTo, buf, todo, &written, NULL)
7357 || written != todo)
7358 break;
7359 }
7360 CloseHandle(hTo);
7361 }
7362
7363 free(to_name);
7364}
7365
7366/*
7367 * Copy info streams from file "from" to file "to".
7368 */
7369 static void
7370copy_infostreams(char_u *from, char_u *to)
7371{
7372 WCHAR *fromw;
7373 WCHAR *tow;
7374 HANDLE sh;
7375 WIN32_STREAM_ID sid;
7376 int headersize;
7377 WCHAR streamname[_MAX_PATH];
7378 DWORD readcount;
7379 void *context = NULL;
7380 DWORD lo, hi;
7381 int len;
7382
Bram Moolenaar0f873732019-12-05 20:28:46 +01007383 // Convert the file names to wide characters.
Bram Moolenaar36f692d2008-11-20 16:10:17 +00007384 fromw = enc_to_utf16(from, NULL);
7385 tow = enc_to_utf16(to, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007386 if (fromw != NULL && tow != NULL)
7387 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007388 // Open the file for reading.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007389 sh = CreateFileW(fromw, GENERIC_READ, FILE_SHARE_READ, NULL,
7390 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
7391 if (sh != INVALID_HANDLE_VALUE)
7392 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007393 // Use BackupRead() to find the info streams. Repeat until we
7394 // have done them all.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007395 for (;;)
7396 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007397 // Get the header to find the length of the stream name. If
7398 // the "readcount" is zero we have done all info streams.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007399 ZeroMemory(&sid, sizeof(WIN32_STREAM_ID));
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007400 headersize = (int)((char *)&sid.cStreamName - (char *)&sid.dwStreamId);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007401 if (!BackupRead(sh, (LPBYTE)&sid, headersize,
7402 &readcount, FALSE, FALSE, &context)
7403 || readcount == 0)
7404 break;
7405
Bram Moolenaar0f873732019-12-05 20:28:46 +01007406 // We only deal with streams that have a name. The normal
7407 // file data appears to be without a name, even though docs
7408 // suggest it is called "::$DATA".
Bram Moolenaar071d4272004-06-13 20:20:40 +00007409 if (sid.dwStreamNameSize > 0)
7410 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007411 // Read the stream name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007412 if (!BackupRead(sh, (LPBYTE)streamname,
7413 sid.dwStreamNameSize,
7414 &readcount, FALSE, FALSE, &context))
7415 break;
7416
Bram Moolenaar0f873732019-12-05 20:28:46 +01007417 // Copy an info stream with a name ":anything:$DATA".
7418 // Skip "::$DATA", it has no stream name (examples suggest
7419 // it might be used for the normal file contents).
7420 // Note that BackupRead() counts bytes, but the name is in
7421 // wide characters.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007422 len = readcount / sizeof(WCHAR);
7423 streamname[len] = 0;
7424 if (len > 7 && wcsicmp(streamname + len - 6,
7425 L":$DATA") == 0)
7426 {
7427 streamname[len - 6] = 0;
7428 copy_substream(sh, &context, tow, streamname,
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00007429 (long)sid.Size.u.LowPart);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007430 }
7431 }
7432
Bram Moolenaar0f873732019-12-05 20:28:46 +01007433 // Advance to the next stream. We might try seeking too far,
7434 // but BackupSeek() doesn't skip over stream borders, thus
7435 // that's OK.
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00007436 (void)BackupSeek(sh, sid.Size.u.LowPart, sid.Size.u.HighPart,
Bram Moolenaar071d4272004-06-13 20:20:40 +00007437 &lo, &hi, &context);
7438 }
7439
Bram Moolenaar0f873732019-12-05 20:28:46 +01007440 // Clear the context.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007441 (void)BackupRead(sh, NULL, 0, &readcount, TRUE, FALSE, &context);
7442
7443 CloseHandle(sh);
7444 }
7445 }
7446 vim_free(fromw);
7447 vim_free(tow);
7448}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007449
7450/*
Bram Moolenaare7bebc42021-02-01 20:50:37 +01007451 * ntdll.dll definitions
7452 */
7453#define FileEaInformation 7
7454#ifndef STATUS_SUCCESS
7455# define STATUS_SUCCESS ((NTSTATUS) 0x00000000L)
7456#endif
7457
7458typedef struct _FILE_FULL_EA_INFORMATION_ {
7459 ULONG NextEntryOffset;
7460 UCHAR Flags;
7461 UCHAR EaNameLength;
7462 USHORT EaValueLength;
7463 CHAR EaName[1];
7464} FILE_FULL_EA_INFORMATION_, *PFILE_FULL_EA_INFORMATION_;
7465
7466typedef struct _FILE_EA_INFORMATION_ {
7467 ULONG EaSize;
7468} FILE_EA_INFORMATION_, *PFILE_EA_INFORMATION_;
7469
Paul Ollis65745772022-06-05 16:55:54 +01007470#ifndef PROTO
Bram Moolenaare7bebc42021-02-01 20:50:37 +01007471typedef NTSTATUS (NTAPI *PfnNtOpenFile)(
7472 PHANDLE FileHandle,
7473 ACCESS_MASK DesiredAccess,
7474 POBJECT_ATTRIBUTES ObjectAttributes,
7475 PIO_STATUS_BLOCK IoStatusBlock,
7476 ULONG ShareAccess,
7477 ULONG OpenOptions);
7478typedef NTSTATUS (NTAPI *PfnNtClose)(
7479 HANDLE Handle);
7480typedef NTSTATUS (NTAPI *PfnNtSetEaFile)(
Bram Moolenaar9f1983d2022-05-12 20:35:35 +01007481 HANDLE FileHandle,
7482 PIO_STATUS_BLOCK IoStatusBlock,
7483 PVOID Buffer,
7484 ULONG Length);
Bram Moolenaare7bebc42021-02-01 20:50:37 +01007485typedef NTSTATUS (NTAPI *PfnNtQueryEaFile)(
7486 HANDLE FileHandle,
7487 PIO_STATUS_BLOCK IoStatusBlock,
7488 PVOID Buffer,
7489 ULONG Length,
7490 BOOLEAN ReturnSingleEntry,
7491 PVOID EaList,
7492 ULONG EaListLength,
7493 PULONG EaIndex,
7494 BOOLEAN RestartScan);
7495typedef NTSTATUS (NTAPI *PfnNtQueryInformationFile)(
Bram Moolenaar9f1983d2022-05-12 20:35:35 +01007496 HANDLE FileHandle,
7497 PIO_STATUS_BLOCK IoStatusBlock,
7498 PVOID FileInformation,
7499 ULONG Length,
Bram Moolenaare7bebc42021-02-01 20:50:37 +01007500 FILE_INFORMATION_CLASS FileInformationClass);
7501typedef VOID (NTAPI *PfnRtlInitUnicodeString)(
7502 PUNICODE_STRING DestinationString,
7503 PCWSTR SourceString);
7504
7505PfnNtOpenFile pNtOpenFile = NULL;
7506PfnNtClose pNtClose = NULL;
7507PfnNtSetEaFile pNtSetEaFile = NULL;
7508PfnNtQueryEaFile pNtQueryEaFile = NULL;
7509PfnNtQueryInformationFile pNtQueryInformationFile = NULL;
7510PfnRtlInitUnicodeString pRtlInitUnicodeString = NULL;
Paul Ollis65745772022-06-05 16:55:54 +01007511#endif
Bram Moolenaare7bebc42021-02-01 20:50:37 +01007512
7513/*
7514 * Load ntdll.dll functions.
7515 */
7516 static BOOL
7517load_ntdll(void)
7518{
7519 static int loaded = -1;
7520
7521 if (loaded == -1)
7522 {
7523 HMODULE hNtdll = GetModuleHandle("ntdll.dll");
7524 if (hNtdll != NULL)
7525 {
7526 pNtOpenFile = (PfnNtOpenFile) GetProcAddress(hNtdll, "NtOpenFile");
7527 pNtClose = (PfnNtClose) GetProcAddress(hNtdll, "NtClose");
7528 pNtSetEaFile = (PfnNtSetEaFile)
7529 GetProcAddress(hNtdll, "NtSetEaFile");
7530 pNtQueryEaFile = (PfnNtQueryEaFile)
7531 GetProcAddress(hNtdll, "NtQueryEaFile");
7532 pNtQueryInformationFile = (PfnNtQueryInformationFile)
7533 GetProcAddress(hNtdll, "NtQueryInformationFile");
7534 pRtlInitUnicodeString = (PfnRtlInitUnicodeString)
7535 GetProcAddress(hNtdll, "RtlInitUnicodeString");
7536 }
7537 if (pNtOpenFile == NULL
7538 || pNtClose == NULL
7539 || pNtSetEaFile == NULL
7540 || pNtQueryEaFile == NULL
7541 || pNtQueryInformationFile == NULL
7542 || pRtlInitUnicodeString == NULL)
7543 loaded = FALSE;
7544 else
7545 loaded = TRUE;
7546 }
7547 return (BOOL) loaded;
7548}
7549
7550/*
7551 * Copy extended attributes (EA) from file "from" to file "to".
7552 */
7553 static void
7554copy_extattr(char_u *from, char_u *to)
7555{
7556 char_u *fromf = NULL;
7557 char_u *tof = NULL;
7558 WCHAR *fromw = NULL;
7559 WCHAR *tow = NULL;
7560 UNICODE_STRING u;
7561 HANDLE h;
7562 OBJECT_ATTRIBUTES oa;
7563 IO_STATUS_BLOCK iosb;
7564 FILE_EA_INFORMATION_ eainfo = {0};
7565 void *ea = NULL;
7566
7567 if (!load_ntdll())
7568 return;
7569
7570 // Convert the file names to the fully qualified object names.
7571 fromf = alloc(STRLEN(from) + 5);
7572 tof = alloc(STRLEN(to) + 5);
7573 if (fromf == NULL || tof == NULL)
7574 goto theend;
7575 STRCPY(fromf, "\\??\\");
7576 STRCAT(fromf, from);
7577 STRCPY(tof, "\\??\\");
7578 STRCAT(tof, to);
7579
7580 // Convert the names to wide characters.
7581 fromw = enc_to_utf16(fromf, NULL);
7582 tow = enc_to_utf16(tof, NULL);
7583 if (fromw == NULL || tow == NULL)
7584 goto theend;
7585
7586 // Get the EA.
7587 pRtlInitUnicodeString(&u, fromw);
7588 InitializeObjectAttributes(&oa, &u, 0, NULL, NULL);
7589 if (pNtOpenFile(&h, FILE_READ_EA, &oa, &iosb, 0,
7590 FILE_NON_DIRECTORY_FILE) != STATUS_SUCCESS)
7591 goto theend;
7592 pNtQueryInformationFile(h, &iosb, &eainfo, sizeof(eainfo),
7593 FileEaInformation);
7594 if (eainfo.EaSize != 0)
7595 {
7596 ea = alloc(eainfo.EaSize);
7597 if (ea != NULL)
7598 {
7599 if (pNtQueryEaFile(h, &iosb, ea, eainfo.EaSize, FALSE,
7600 NULL, 0, NULL, TRUE) != STATUS_SUCCESS)
7601 {
7602 vim_free(ea);
7603 ea = NULL;
7604 }
7605 }
7606 }
7607 pNtClose(h);
7608
7609 // Set the EA.
7610 if (ea != NULL)
7611 {
7612 pRtlInitUnicodeString(&u, tow);
7613 InitializeObjectAttributes(&oa, &u, 0, NULL, NULL);
7614 if (pNtOpenFile(&h, FILE_WRITE_EA, &oa, &iosb, 0,
7615 FILE_NON_DIRECTORY_FILE) != STATUS_SUCCESS)
7616 goto theend;
7617
7618 pNtSetEaFile(h, &iosb, ea, eainfo.EaSize);
7619 pNtClose(h);
7620 }
7621
7622theend:
7623 vim_free(fromf);
7624 vim_free(tof);
7625 vim_free(fromw);
7626 vim_free(tow);
7627 vim_free(ea);
7628}
7629
7630/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00007631 * Copy file attributes from file "from" to file "to".
7632 * For Windows NT and later we copy info streams.
7633 * Always returns zero, errors are ignored.
7634 */
7635 int
7636mch_copy_file_attribute(char_u *from, char_u *to)
7637{
Bram Moolenaar0f873732019-12-05 20:28:46 +01007638 // File streams only work on Windows NT and later.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007639 copy_infostreams(from, to);
Bram Moolenaare7bebc42021-02-01 20:50:37 +01007640 copy_extattr(from, to);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007641 return 0;
7642}
7643
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007644
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007645/*
K.Takatadc73b4b2021-06-08 18:32:36 +02007646 * The command line arguments in UTF-16
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007647 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00007648static int nArgsW = 0;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007649static LPWSTR *ArglistW = NULL;
7650static int global_argc = 0;
7651static char **global_argv;
7652
Bram Moolenaar0f873732019-12-05 20:28:46 +01007653static int used_file_argc = 0; // last argument in global_argv[] used
7654 // for the argument list.
7655static int *used_file_indexes = NULL; // indexes in global_argv[] for
7656 // command line arguments added to
7657 // the argument list
7658static int used_file_count = 0; // nr of entries in used_file_indexes
7659static int used_file_literal = FALSE; // take file names literally
7660static int used_file_full_path = FALSE; // file name was full path
7661static int used_file_diff_mode = FALSE; // file name was with diff mode
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007662static int used_alist_count = 0;
7663
7664
7665/*
7666 * Get the command line arguments. Unicode version.
7667 * Returns argc. Zero when something fails.
7668 */
7669 int
7670get_cmd_argsW(char ***argvp)
7671{
7672 char **argv = NULL;
7673 int argc = 0;
7674 int i;
7675
Bram Moolenaar14993322014-09-09 12:25:33 +02007676 free_cmd_argsW();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007677 ArglistW = CommandLineToArgvW(GetCommandLineW(), &nArgsW);
7678 if (ArglistW != NULL)
7679 {
7680 argv = malloc((nArgsW + 1) * sizeof(char *));
7681 if (argv != NULL)
7682 {
7683 argc = nArgsW;
7684 argv[argc] = NULL;
7685 for (i = 0; i < argc; ++i)
7686 {
7687 int len;
7688
K.Takatadc73b4b2021-06-08 18:32:36 +02007689 // Convert each Unicode argument to UTF-8.
7690 WideCharToMultiByte_alloc(CP_UTF8, 0,
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007691 ArglistW[i], (int)wcslen(ArglistW[i]) + 1,
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007692 (LPSTR *)&argv[i], &len, 0, 0);
7693 if (argv[i] == NULL)
7694 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007695 // Out of memory, clear everything.
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007696 while (i > 0)
7697 free(argv[--i]);
7698 free(argv);
Bram Moolenaar73c61632013-12-07 14:48:10 +01007699 argv = NULL;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007700 argc = 0;
7701 }
7702 }
7703 }
7704 }
7705
7706 global_argc = argc;
7707 global_argv = argv;
7708 if (argc > 0)
Bram Moolenaar14993322014-09-09 12:25:33 +02007709 {
7710 if (used_file_indexes != NULL)
7711 free(used_file_indexes);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007712 used_file_indexes = malloc(argc * sizeof(int));
Bram Moolenaar14993322014-09-09 12:25:33 +02007713 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007714
7715 if (argvp != NULL)
7716 *argvp = argv;
7717 return argc;
7718}
7719
7720 void
7721free_cmd_argsW(void)
7722{
7723 if (ArglistW != NULL)
7724 {
7725 GlobalFree(ArglistW);
7726 ArglistW = NULL;
7727 }
7728}
7729
7730/*
7731 * Remember "name" is an argument that was added to the argument list.
7732 * This avoids that we have to re-parse the argument list when fix_arg_enc()
7733 * is called.
7734 */
7735 void
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007736used_file_arg(char *name, int literal, int full_path, int diff_mode)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007737{
7738 int i;
7739
7740 if (used_file_indexes == NULL)
7741 return;
7742 for (i = used_file_argc + 1; i < global_argc; ++i)
7743 if (STRCMP(global_argv[i], name) == 0)
7744 {
7745 used_file_argc = i;
7746 used_file_indexes[used_file_count++] = i;
7747 break;
7748 }
7749 used_file_literal = literal;
7750 used_file_full_path = full_path;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007751 used_file_diff_mode = diff_mode;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007752}
7753
7754/*
7755 * Remember the length of the argument list as it was. If it changes then we
7756 * leave it alone when 'encoding' is set.
7757 */
7758 void
7759set_alist_count(void)
7760{
7761 used_alist_count = GARGCOUNT;
7762}
7763
7764/*
7765 * Fix the encoding of the command line arguments. Invoked when 'encoding'
K.Takatadc73b4b2021-06-08 18:32:36 +02007766 * has been changed while starting up. Use the UTF-16 command line arguments
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007767 * and convert them to 'encoding'.
7768 */
7769 void
7770fix_arg_enc(void)
7771{
7772 int i;
7773 int idx;
7774 char_u *str;
Bram Moolenaar86b68352004-12-27 21:59:20 +00007775 int *fnum_list;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007776
Bram Moolenaar0f873732019-12-05 20:28:46 +01007777 // Safety checks:
7778 // - if argument count differs between the wide and non-wide argument
7779 // list, something must be wrong.
7780 // - the file name arguments must have been located.
7781 // - the length of the argument list wasn't changed by the user.
Bram Moolenaard857f0e2005-06-21 22:37:39 +00007782 if (global_argc != nArgsW
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007783 || ArglistW == NULL
7784 || used_file_indexes == NULL
7785 || used_file_count == 0
7786 || used_alist_count != GARGCOUNT)
7787 return;
7788
Bram Moolenaar0f873732019-12-05 20:28:46 +01007789 // Remember the buffer numbers for the arguments.
Bram Moolenaarc799fe22019-05-28 23:08:19 +02007790 fnum_list = ALLOC_MULT(int, GARGCOUNT);
Bram Moolenaar86b68352004-12-27 21:59:20 +00007791 if (fnum_list == NULL)
Bram Moolenaar0f873732019-12-05 20:28:46 +01007792 return; // out of memory
Bram Moolenaar86b68352004-12-27 21:59:20 +00007793 for (i = 0; i < GARGCOUNT; ++i)
7794 fnum_list[i] = GARGLIST[i].ae_fnum;
7795
Bram Moolenaar0f873732019-12-05 20:28:46 +01007796 // Clear the argument list. Make room for the new arguments.
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007797 alist_clear(&global_alist);
7798 if (ga_grow(&global_alist.al_ga, used_file_count) == FAIL)
Bram Moolenaar0f873732019-12-05 20:28:46 +01007799 return; // out of memory
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007800
7801 for (i = 0; i < used_file_count; ++i)
7802 {
7803 idx = used_file_indexes[i];
Bram Moolenaar36f692d2008-11-20 16:10:17 +00007804 str = utf16_to_enc(ArglistW[idx], NULL);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007805 if (str != NULL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00007806 {
Bram Moolenaar39d21e32017-08-05 23:09:31 +02007807 int literal = used_file_literal;
7808
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007809#ifdef FEAT_DIFF
Bram Moolenaar0f873732019-12-05 20:28:46 +01007810 // When using diff mode may need to concatenate file name to
7811 // directory name. Just like it's done in main().
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007812 if (used_file_diff_mode && mch_isdir(str) && GARGCOUNT > 0
7813 && !mch_isdir(alist_name(&GARGLIST[0])))
7814 {
7815 char_u *r;
7816
7817 r = concat_fnames(str, gettail(alist_name(&GARGLIST[0])), TRUE);
7818 if (r != NULL)
7819 {
7820 vim_free(str);
7821 str = r;
7822 }
7823 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007824#endif
Bram Moolenaar0f873732019-12-05 20:28:46 +01007825 // Re-use the old buffer by renaming it. When not using literal
7826 // names it's done by alist_expand() below.
Bram Moolenaar86b68352004-12-27 21:59:20 +00007827 if (used_file_literal)
7828 buf_set_name(fnum_list[i], str);
7829
Bram Moolenaar0f873732019-12-05 20:28:46 +01007830 // Check backtick literal. backtick literal is already expanded in
7831 // main.c, so this part add str as literal.
Bram Moolenaar39d21e32017-08-05 23:09:31 +02007832 if (literal == FALSE)
7833 {
Bram Moolenaar116a0f82017-08-07 21:17:57 +02007834 size_t len = STRLEN(str);
7835
Bram Moolenaar39d21e32017-08-05 23:09:31 +02007836 if (len > 2 && *str == '`' && *(str + len - 1) == '`')
7837 literal = TRUE;
7838 }
7839 alist_add(&global_alist, str, literal ? 2 : 0);
Bram Moolenaar86b68352004-12-27 21:59:20 +00007840 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007841 }
7842
7843 if (!used_file_literal)
7844 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007845 // Now expand wildcards in the arguments.
7846 // Temporarily add '(' and ')' to 'isfname'. These are valid
7847 // filename characters but are excluded from 'isfname' to make
Dominique Pelleaf4a61a2021-12-27 17:21:41 +00007848 // "gf" work on a file name in parentheses (e.g.: see vim.h).
Bram Moolenaar0f873732019-12-05 20:28:46 +01007849 // Also, unset wildignore to not be influenced by this option.
7850 // The arguments specified in command-line should be kept even if
7851 // encoding options were changed.
Christian Brabandtfd916d62021-11-01 22:44:33 +00007852 // Use :legacy so that it also works when in Vim9 script.
7853 do_cmdline_cmd((char_u *)":legacy let g:SaVe_ISF = &isf|set isf+=(,)");
7854 do_cmdline_cmd((char_u *)":legacy let g:SaVe_WIG = &wig|set wig=");
Bram Moolenaar86b68352004-12-27 21:59:20 +00007855 alist_expand(fnum_list, used_alist_count);
Christian Brabandtfd916d62021-11-01 22:44:33 +00007856 do_cmdline_cmd(
7857 (char_u *)":legacy let &isf = g:SaVe_ISF|unlet g:SaVe_ISF");
7858 do_cmdline_cmd(
7859 (char_u *)":legacy let &wig = g:SaVe_WIG|unlet g:SaVe_WIG");
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007860 }
7861
Bram Moolenaar0f873732019-12-05 20:28:46 +01007862 // If wildcard expansion failed, we are editing the first file of the
7863 // arglist and there is no file name: Edit the first argument now.
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007864 if (curwin->w_arg_idx == 0 && curbuf->b_fname == NULL)
7865 {
7866 do_cmdline_cmd((char_u *)":rewind");
Bram Moolenaar05268152021-11-18 18:53:45 +00007867 if (GARGCOUNT == 1 && used_file_full_path
7868 && vim_chdirfile(alist_name(&GARGLIST[0]), "drop") == OK)
7869 last_chdir_reason = "drop";
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007870 }
Bram Moolenaar86b68352004-12-27 21:59:20 +00007871
7872 set_alist_count();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007873}
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007874
7875 int
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02007876mch_setenv(char *var, char *value, int x UNUSED)
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007877{
7878 char_u *envbuf;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007879 WCHAR *p;
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007880
Bram Moolenaar964b3742019-05-24 18:54:09 +02007881 envbuf = alloc(STRLEN(var) + STRLEN(value) + 2);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007882 if (envbuf == NULL)
7883 return -1;
7884
7885 sprintf((char *)envbuf, "%s=%s", var, value);
7886
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007887 p = enc_to_utf16(envbuf, NULL);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007888
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007889 vim_free(envbuf);
7890 if (p == NULL)
7891 return -1;
7892 _wputenv(p);
Bram Moolenaara12a1612019-01-24 16:39:02 +01007893#ifdef libintl_wputenv
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007894 libintl_wputenv(p);
Bram Moolenaara12a1612019-01-24 16:39:02 +01007895#endif
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007896 // Unlike Un*x systems, we can free the string for _wputenv().
7897 vim_free(p);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007898
7899 return 0;
7900}
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007901
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007902/*
7903 * Support for 256 colors and 24-bit colors was added in Windows 10
7904 * version 1703 (Creators update).
7905 */
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007906#define VTP_FIRST_SUPPORT_BUILD MAKE_VER(10, 0, 15063)
7907
7908/*
7909 * Support for pseudo-console (ConPTY) was added in windows 10
Bram Moolenaar57da6982019-09-13 22:30:11 +02007910 * version 1809 (October 2018 update).
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007911 */
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01007912#define CONPTY_FIRST_SUPPORT_BUILD MAKE_VER(10, 0, 17763)
Bram Moolenaar57da6982019-09-13 22:30:11 +02007913
7914/*
7915 * ConPTY differences between versions, need different logic.
7916 * version 1903 (May 2019 update).
7917 */
7918#define CONPTY_1903_BUILD MAKE_VER(10, 0, 18362)
7919
7920/*
Bram Moolenaar36e7a822019-11-13 21:49:24 +01007921 * version 1909 (November 2019 update).
7922 */
7923#define CONPTY_1909_BUILD MAKE_VER(10, 0, 18363)
7924
7925/*
Bram Moolenaar7ed8f592020-04-28 20:44:42 +02007926 * Stay ahead of the next update, and when it's done, fix this.
7927 * version ? (2020 update, temporarily use the build number of insider preview)
7928 */
7929#define CONPTY_NEXT_UPDATE_BUILD MAKE_VER(10, 0, 19587)
7930
7931/*
Bram Moolenaar57da6982019-09-13 22:30:11 +02007932 * Confirm until this version. Also the logic changes.
7933 * insider preview.
7934 */
Bram Moolenaar4c063dd2019-10-04 21:29:12 +02007935#define CONPTY_INSIDER_BUILD MAKE_VER(10, 0, 18995)
Bram Moolenaar57da6982019-09-13 22:30:11 +02007936
7937/*
7938 * Not stable now.
7939 */
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01007940#define CONPTY_STABLE_BUILD MAKE_VER(10, 0, 32767) // T.B.D.
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007941
7942 static void
7943vtp_flag_init(void)
7944{
7945 DWORD ver = get_build_number();
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007946#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007947 DWORD mode;
7948 HANDLE out;
7949
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007950# ifdef VIMDLL
7951 if (!gui.in_use)
7952# endif
7953 {
7954 out = GetStdHandle(STD_OUTPUT_HANDLE);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007955
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007956 vtp_working = (ver >= VTP_FIRST_SUPPORT_BUILD) ? 1 : 0;
7957 GetConsoleMode(out, &mode);
7958 mode |= (ENABLE_PROCESSED_OUTPUT | ENABLE_VIRTUAL_TERMINAL_PROCESSING);
7959 if (SetConsoleMode(out, mode) == 0)
7960 vtp_working = 0;
7961 }
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007962#endif
7963
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007964 if (ver >= CONPTY_FIRST_SUPPORT_BUILD)
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01007965 conpty_working = 1;
7966 if (ver >= CONPTY_STABLE_BUILD)
7967 conpty_stable = 1;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007968
Bram Moolenaar57da6982019-09-13 22:30:11 +02007969 if (ver <= CONPTY_INSIDER_BUILD)
7970 conpty_type = 3;
Bram Moolenaar36e7a822019-11-13 21:49:24 +01007971 if (ver <= CONPTY_1909_BUILD)
7972 conpty_type = 2;
Bram Moolenaar57da6982019-09-13 22:30:11 +02007973 if (ver <= CONPTY_1903_BUILD)
7974 conpty_type = 2;
7975 if (ver < CONPTY_FIRST_SUPPORT_BUILD)
7976 conpty_type = 1;
Bram Moolenaar7ed8f592020-04-28 20:44:42 +02007977
7978 if (ver >= CONPTY_NEXT_UPDATE_BUILD)
7979 conpty_fix_type = 1;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007980}
7981
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007982#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL) || defined(PROTO)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007983
7984 static void
7985vtp_init(void)
7986{
K.Takata27b53be2022-09-18 12:25:49 +01007987 CONSOLE_SCREEN_BUFFER_INFOEX csbi;
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007988# ifdef FEAT_TERMGUICOLORS
Yasuhiro Matsumotoaa04e1b2022-05-07 14:09:19 +01007989 COLORREF fg;
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007990# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007991
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007992 csbi.cbSize = sizeof(csbi);
K.Takata27b53be2022-09-18 12:25:49 +01007993 GetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007994 save_console_bg_rgb = (guicolor_T)csbi.ColorTable[g_color_index_bg];
7995 save_console_fg_rgb = (guicolor_T)csbi.ColorTable[g_color_index_fg];
Bram Moolenaardf543822020-01-30 11:53:59 +01007996 store_console_bg_rgb = save_console_bg_rgb;
7997 store_console_fg_rgb = save_console_fg_rgb;
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007998
7999# ifdef FEAT_TERMGUICOLORS
Yasuhiro Matsumotoe42c8da2022-09-01 11:31:45 +01008000 if (!USE_WT)
8001 {
8002 COLORREF bg;
8003 bg = (COLORREF)csbi.ColorTable[g_color_index_bg];
8004 bg = (GetRValue(bg) << 16) | (GetGValue(bg) << 8) | GetBValue(bg);
8005 default_console_color_bg = bg;
8006 }
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02008007 fg = (COLORREF)csbi.ColorTable[g_color_index_fg];
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02008008 fg = (GetRValue(fg) << 16) | (GetGValue(fg) << 8) | GetBValue(fg);
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02008009 default_console_color_fg = fg;
Bram Moolenaarc4568ab2018-11-16 16:21:05 +01008010# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008011
8012 set_console_color_rgb();
8013}
8014
8015 static void
8016vtp_exit(void)
8017{
Bram Moolenaardf543822020-01-30 11:53:59 +01008018 restore_console_color_rgb();
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008019}
8020
Bram Moolenaar06b7b582020-05-30 17:49:25 +02008021 int
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008022vtp_printf(
8023 char *format,
8024 ...)
8025{
8026 char_u buf[100];
8027 va_list list;
8028 DWORD result;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008029 int len;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008030
8031 va_start(list, format);
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008032 len = vim_vsnprintf((char *)buf, 100, (char *)format, list);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008033 va_end(list);
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008034 WriteConsoleA(g_hConOut, buf, (DWORD)len, &result, NULL);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008035 return (int)result;
8036}
8037
8038 static void
8039vtp_sgr_bulk(
8040 int arg)
8041{
8042 int args[1];
8043
8044 args[0] = arg;
8045 vtp_sgr_bulks(1, args);
8046}
8047
K.Takata6e1d31e2022-02-03 13:05:32 +00008048# define FAST256(x) \
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008049 if ((*p-- = "0123456789"[(n = x % 10)]) \
8050 && x >= 10 && (*p-- = "0123456789"[((m = x % 100) - n) / 10]) \
8051 && x >= 100 && (*p-- = "012"[((x & 0xff) - m) / 100]));
8052
K.Takata6e1d31e2022-02-03 13:05:32 +00008053# define FAST256CASE(x) \
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008054 case x: \
8055 FAST256(newargs[x - 1]);
8056
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008057 static void
8058vtp_sgr_bulks(
8059 int argc,
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008060 int *args)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008061{
K.Takata6e1d31e2022-02-03 13:05:32 +00008062# define MAXSGR 16
8063# define SGRBUFSIZE 2 + 4 * MAXSGR + 1 // '\033[' + SGR + 'm'
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008064 char_u buf[SGRBUFSIZE];
8065 char_u *p;
8066 int in, out;
8067 int newargs[16];
8068 static int sgrfgr = -1, sgrfgg, sgrfgb;
8069 static int sgrbgr = -1, sgrbgg, sgrbgb;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008070
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008071 if (argc == 0)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008072 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008073 sgrfgr = sgrbgr = -1;
K.Takatadf5320c2022-09-01 13:20:16 +01008074 vtp_printf("\033[m");
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008075 return;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008076 }
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008077
8078 in = out = 0;
8079 while (in < argc)
8080 {
8081 int s = args[in];
8082 int copylen = 1;
8083
8084 if (s == 38)
8085 {
8086 if (argc - in >= 5 && args[in + 1] == 2)
8087 {
8088 if (sgrfgr == args[in + 2] && sgrfgg == args[in + 3]
8089 && sgrfgb == args[in + 4])
8090 {
8091 in += 5;
8092 copylen = 0;
8093 }
8094 else
8095 {
8096 sgrfgr = args[in + 2];
8097 sgrfgg = args[in + 3];
8098 sgrfgb = args[in + 4];
8099 copylen = 5;
8100 }
8101 }
8102 else if (argc - in >= 3 && args[in + 1] == 5)
8103 {
8104 sgrfgr = -1;
8105 copylen = 3;
8106 }
8107 }
8108 else if (s == 48)
8109 {
8110 if (argc - in >= 5 && args[in + 1] == 2)
8111 {
8112 if (sgrbgr == args[in + 2] && sgrbgg == args[in + 3]
8113 && sgrbgb == args[in + 4])
8114 {
8115 in += 5;
8116 copylen = 0;
8117 }
8118 else
8119 {
8120 sgrbgr = args[in + 2];
8121 sgrbgg = args[in + 3];
8122 sgrbgb = args[in + 4];
8123 copylen = 5;
8124 }
8125 }
8126 else if (argc - in >= 3 && args[in + 1] == 5)
8127 {
8128 sgrbgr = -1;
8129 copylen = 3;
8130 }
8131 }
8132 else if (30 <= s && s <= 39)
8133 sgrfgr = -1;
8134 else if (90 <= s && s <= 97)
8135 sgrfgr = -1;
8136 else if (40 <= s && s <= 49)
8137 sgrbgr = -1;
8138 else if (100 <= s && s <= 107)
8139 sgrbgr = -1;
8140 else if (s == 0)
8141 sgrfgr = sgrbgr = -1;
8142
8143 while (copylen--)
8144 newargs[out++] = args[in++];
8145 }
8146
8147 p = &buf[sizeof(buf) - 1];
8148 *p-- = 'm';
8149
8150 switch (out)
8151 {
8152 int n, m;
8153 DWORD r;
8154
8155 FAST256CASE(16);
8156 *p-- = ';';
8157 FAST256CASE(15);
8158 *p-- = ';';
8159 FAST256CASE(14);
8160 *p-- = ';';
8161 FAST256CASE(13);
8162 *p-- = ';';
8163 FAST256CASE(12);
8164 *p-- = ';';
8165 FAST256CASE(11);
8166 *p-- = ';';
8167 FAST256CASE(10);
8168 *p-- = ';';
8169 FAST256CASE(9);
8170 *p-- = ';';
8171 FAST256CASE(8);
8172 *p-- = ';';
8173 FAST256CASE(7);
8174 *p-- = ';';
8175 FAST256CASE(6);
8176 *p-- = ';';
8177 FAST256CASE(5);
8178 *p-- = ';';
8179 FAST256CASE(4);
8180 *p-- = ';';
8181 FAST256CASE(3);
8182 *p-- = ';';
8183 FAST256CASE(2);
8184 *p-- = ';';
8185 FAST256CASE(1);
8186 *p-- = '[';
8187 *p = '\033';
8188 WriteConsoleA(g_hConOut, p, (DWORD)(&buf[SGRBUFSIZE] - p), &r, NULL);
8189 default:
8190 break;
8191 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008192}
8193
Bram Moolenaar06b7b582020-05-30 17:49:25 +02008194 static void
8195wt_init(void)
8196{
8197 wt_working = (mch_getenv("WT_SESSION") != NULL);
8198}
8199
8200 int
8201use_wt(void)
8202{
8203 return USE_WT;
8204}
8205
Bram Moolenaar8a938af2018-05-01 17:30:41 +02008206# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02008207 static int
8208ctermtoxterm(
8209 int cterm)
8210{
Bram Moolenaar9894e392018-05-05 14:29:06 +02008211 char_u r, g, b, idx;
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02008212
8213 cterm_color2rgb(cterm, &r, &g, &b, &idx);
8214 return (((int)r << 16) | ((int)g << 8) | (int)b);
8215}
Bram Moolenaar8a938af2018-05-01 17:30:41 +02008216# endif
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02008217
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008218 static void
8219set_console_color_rgb(void)
8220{
8221# ifdef FEAT_TERMGUICOLORS
K.Takata27b53be2022-09-18 12:25:49 +01008222 CONSOLE_SCREEN_BUFFER_INFOEX csbi;
Bram Moolenaara050b942019-12-02 21:35:31 +01008223 guicolor_T fg, bg;
8224 int ctermfg, ctermbg;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008225
8226 if (!USE_VTP)
8227 return;
8228
Bram Moolenaara050b942019-12-02 21:35:31 +01008229 get_default_console_color(&ctermfg, &ctermbg, &fg, &bg);
8230
Bram Moolenaar06b7b582020-05-30 17:49:25 +02008231 if (USE_WT)
8232 {
8233 term_fg_rgb_color(fg);
8234 term_bg_rgb_color(bg);
8235 return;
8236 }
8237
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008238 fg = (GetRValue(fg) << 16) | (GetGValue(fg) << 8) | GetBValue(fg);
8239 bg = (GetRValue(bg) << 16) | (GetGValue(bg) << 8) | GetBValue(bg);
8240
8241 csbi.cbSize = sizeof(csbi);
K.Takata27b53be2022-09-18 12:25:49 +01008242 GetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008243
8244 csbi.cbSize = sizeof(csbi);
8245 csbi.srWindow.Right += 1;
8246 csbi.srWindow.Bottom += 1;
Bram Moolenaardf543822020-01-30 11:53:59 +01008247 store_console_bg_rgb = csbi.ColorTable[g_color_index_bg];
8248 store_console_fg_rgb = csbi.ColorTable[g_color_index_fg];
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02008249 csbi.ColorTable[g_color_index_bg] = (COLORREF)bg;
8250 csbi.ColorTable[g_color_index_fg] = (COLORREF)fg;
K.Takata27b53be2022-09-18 12:25:49 +01008251 SetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008252# endif
8253}
8254
Bram Moolenaara050b942019-12-02 21:35:31 +01008255# if defined(FEAT_TERMGUICOLORS) || defined(PROTO)
8256 void
8257get_default_console_color(
8258 int *cterm_fg,
8259 int *cterm_bg,
8260 guicolor_T *gui_fg,
8261 guicolor_T *gui_bg)
8262{
8263 int id;
8264 guicolor_T guifg = INVALCOLOR;
8265 guicolor_T guibg = INVALCOLOR;
8266 int ctermfg = 0;
8267 int ctermbg = 0;
8268
8269 id = syn_name2id((char_u *)"Normal");
8270 if (id > 0 && p_tgc)
8271 syn_id2colors(id, &guifg, &guibg);
8272 if (guifg == INVALCOLOR)
8273 {
8274 ctermfg = -1;
8275 if (id > 0)
8276 syn_id2cterm_bg(id, &ctermfg, &ctermbg);
8277 guifg = ctermfg != -1 ? ctermtoxterm(ctermfg)
8278 : default_console_color_fg;
8279 cterm_normal_fg_gui_color = guifg;
8280 ctermfg = ctermfg < 0 ? 0 : ctermfg;
8281 }
8282 if (guibg == INVALCOLOR)
8283 {
8284 ctermbg = -1;
8285 if (id > 0)
8286 syn_id2cterm_bg(id, &ctermfg, &ctermbg);
K.Takatae53a0d42022-09-05 21:45:11 +01008287 if (USE_WT)
Yasuhiro Matsumotoe42c8da2022-09-01 11:31:45 +01008288 {
8289 cterm_normal_bg_gui_color = guibg =
Yasuhiro Matsumotoaa04e1b2022-05-07 14:09:19 +01008290 ctermbg != -1 ? ctermtoxterm(ctermbg) : INVALCOLOR;
Yasuhiro Matsumotoe42c8da2022-09-01 11:31:45 +01008291 if (ctermbg < 0)
8292 ctermbg = 0;
8293 }
K.Takatae53a0d42022-09-05 21:45:11 +01008294 else
8295 {
8296 guibg = ctermbg != -1 ? ctermtoxterm(ctermbg)
8297 : default_console_color_bg;
8298 cterm_normal_bg_gui_color = guibg;
8299 ctermbg = ctermbg < 0 ? 0 : ctermbg;
8300 }
Bram Moolenaara050b942019-12-02 21:35:31 +01008301 }
8302
8303 *cterm_fg = ctermfg;
8304 *cterm_bg = ctermbg;
8305 *gui_fg = guifg;
8306 *gui_bg = guibg;
8307}
8308# endif
8309
Bram Moolenaardf543822020-01-30 11:53:59 +01008310/*
8311 * Set the console colors to the original colors or the last set colors.
8312 */
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008313 static void
8314reset_console_color_rgb(void)
8315{
8316# ifdef FEAT_TERMGUICOLORS
K.Takata27b53be2022-09-18 12:25:49 +01008317 CONSOLE_SCREEN_BUFFER_INFOEX csbi;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008318
Bram Moolenaar06b7b582020-05-30 17:49:25 +02008319 if (USE_WT)
8320 return;
8321
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008322 csbi.cbSize = sizeof(csbi);
K.Takata27b53be2022-09-18 12:25:49 +01008323 GetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008324
8325 csbi.cbSize = sizeof(csbi);
8326 csbi.srWindow.Right += 1;
8327 csbi.srWindow.Bottom += 1;
Bram Moolenaardf543822020-01-30 11:53:59 +01008328 csbi.ColorTable[g_color_index_bg] = (COLORREF)store_console_bg_rgb;
8329 csbi.ColorTable[g_color_index_fg] = (COLORREF)store_console_fg_rgb;
K.Takata27b53be2022-09-18 12:25:49 +01008330 SetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaardf543822020-01-30 11:53:59 +01008331# endif
8332}
8333
8334/*
8335 * Set the console colors to the original colors.
8336 */
8337 static void
8338restore_console_color_rgb(void)
8339{
8340# ifdef FEAT_TERMGUICOLORS
K.Takata27b53be2022-09-18 12:25:49 +01008341 CONSOLE_SCREEN_BUFFER_INFOEX csbi;
Bram Moolenaardf543822020-01-30 11:53:59 +01008342
8343 csbi.cbSize = sizeof(csbi);
K.Takata27b53be2022-09-18 12:25:49 +01008344 GetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaardf543822020-01-30 11:53:59 +01008345
8346 csbi.cbSize = sizeof(csbi);
8347 csbi.srWindow.Right += 1;
8348 csbi.srWindow.Bottom += 1;
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02008349 csbi.ColorTable[g_color_index_bg] = (COLORREF)save_console_bg_rgb;
8350 csbi.ColorTable[g_color_index_fg] = (COLORREF)save_console_fg_rgb;
K.Takata27b53be2022-09-18 12:25:49 +01008351 SetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008352# endif
8353}
8354
8355 void
8356control_console_color_rgb(void)
8357{
8358 if (USE_VTP)
8359 set_console_color_rgb();
8360 else
8361 reset_console_color_rgb();
8362}
8363
8364 int
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008365use_vtp(void)
8366{
8367 return USE_VTP;
8368}
8369
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02008370 int
8371is_term_win32(void)
8372{
8373 return T_NAME != NULL && STRCMP(T_NAME, "win32") == 0;
8374}
8375
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008376 int
8377has_vtp_working(void)
8378{
8379 return vtp_working;
8380}
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01008381
Bram Moolenaar6902c0e2019-02-16 14:07:37 +01008382#endif
8383
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01008384 int
8385has_conpty_working(void)
8386{
8387 return conpty_working;
8388}
8389
8390 int
Bram Moolenaar57da6982019-09-13 22:30:11 +02008391get_conpty_type(void)
8392{
8393 return conpty_type;
8394}
8395
8396 int
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01008397is_conpty_stable(void)
8398{
8399 return conpty_stable;
8400}
Bram Moolenaar78d21da2019-02-17 15:00:52 +01008401
Bram Moolenaar7ed8f592020-04-28 20:44:42 +02008402 int
8403get_conpty_fix_type(void)
8404{
8405 return conpty_fix_type;
8406}
8407
Bram Moolenaarafde13b2019-04-28 19:46:49 +02008408#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL) || defined(PROTO)
Bram Moolenaar78d21da2019-02-17 15:00:52 +01008409 void
8410resize_console_buf(void)
8411{
8412 CONSOLE_SCREEN_BUFFER_INFO csbi;
8413 COORD coord;
8414 SMALL_RECT newsize;
8415
8416 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
8417 {
8418 coord.X = SRWIDTH(csbi.srWindow);
8419 coord.Y = SRHEIGHT(csbi.srWindow);
8420 SetConsoleScreenBufferSize(g_hConOut, coord);
8421
8422 newsize.Left = 0;
8423 newsize.Top = 0;
8424 newsize.Right = coord.X - 1;
8425 newsize.Bottom = coord.Y - 1;
8426 SetConsoleWindowInfo(g_hConOut, TRUE, &newsize);
8427
8428 SetConsoleScreenBufferSize(g_hConOut, coord);
8429 }
8430}
8431#endif
Martin Tournoij1a3e5742021-07-24 13:57:29 +02008432
8433 char *
8434GetWin32Error(void)
8435{
K.Takatad68b2fc2022-02-12 11:18:37 +00008436 static char *oldmsg = NULL;
Martin Tournoij1a3e5742021-07-24 13:57:29 +02008437 char *msg = NULL;
K.Takatad68b2fc2022-02-12 11:18:37 +00008438
Martin Tournoij1a3e5742021-07-24 13:57:29 +02008439 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER|FORMAT_MESSAGE_FROM_SYSTEM,
8440 NULL, GetLastError(), 0, (LPSTR)&msg, 0, NULL);
K.Takatad68b2fc2022-02-12 11:18:37 +00008441 if (oldmsg != NULL)
8442 LocalFree(oldmsg);
Martin Tournoij1a3e5742021-07-24 13:57:29 +02008443 if (msg != NULL)
8444 {
8445 // remove trailing \r\n
8446 char *pcrlf = strstr(msg, "\r\n");
8447 if (pcrlf != NULL)
8448 *pcrlf = '\0';
K.Takatad68b2fc2022-02-12 11:18:37 +00008449 oldmsg = msg;
Martin Tournoij1a3e5742021-07-24 13:57:29 +02008450 }
8451 return msg;
8452}
Paul Ollis65745772022-06-05 16:55:54 +01008453
8454#if defined(FEAT_RELTIME) || defined(PROTO)
8455static HANDLE timer_handle;
8456static int timer_active = FALSE;
8457
8458/*
8459 * Calls to start_timeout alternate the return value pointer between the two
8460 * entries in timeout_flags. If the previously active timeout is very close to
8461 * expiring when start_timeout() is called then a race condition means that the
8462 * set_flag() function may still be invoked after the previous timer is
8463 * deleted. Ping-ponging between the two flags prevents this causing 'fake'
8464 * timeouts.
8465 */
Bram Moolenaar155f2d12022-06-20 13:38:33 +01008466static sig_atomic_t timeout_flags[2];
8467static int timeout_flag_idx = 0;
8468static sig_atomic_t *timeout_flag = &timeout_flags[0];
Paul Ollis65745772022-06-05 16:55:54 +01008469
8470
8471 static void CALLBACK
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +01008472set_flag(void *param, BOOLEAN unused2 UNUSED)
Paul Ollis65745772022-06-05 16:55:54 +01008473{
8474 int *timeout_flag = (int *)param;
8475
8476 *timeout_flag = TRUE;
8477}
8478
8479/*
8480 * Stop any active timeout.
8481 */
8482 void
8483stop_timeout(void)
8484{
8485 if (timer_active)
8486 {
Christopher Plewright2a46f812022-10-16 19:47:45 +01008487 BOOL ret = DeleteTimerQueueTimer(NULL, timer_handle, NULL);
Paul Ollis65745772022-06-05 16:55:54 +01008488 timer_active = FALSE;
8489 if (!ret && GetLastError() != ERROR_IO_PENDING)
8490 {
8491 semsg(_(e_could_not_clear_timeout_str), GetWin32Error());
8492 }
8493 }
8494 *timeout_flag = FALSE;
8495}
8496
8497/*
8498 * Start the timeout timer.
8499 *
8500 * The period is defined in milliseconds.
8501 *
8502 * The return value is a pointer to a flag that is initialised to 0. If the
8503 * timeout expires, the flag is set to 1. This will only return pointers to
8504 * static memory; i.e. any pointer returned by this function may always be
8505 * safely dereferenced.
8506 *
8507 * This function is not expected to fail, but if it does it still returns a
8508 * valid flag pointer; the flag will remain stuck at zero.
8509 */
Bram Moolenaar155f2d12022-06-20 13:38:33 +01008510 volatile sig_atomic_t *
Paul Ollis65745772022-06-05 16:55:54 +01008511start_timeout(long msec)
8512{
Paul Ollis65745772022-06-05 16:55:54 +01008513 BOOL ret;
8514
Bram Moolenaar1f30caf2022-06-19 14:36:35 +01008515 timeout_flag = &timeout_flags[timeout_flag_idx];
Paul Ollis65745772022-06-05 16:55:54 +01008516
8517 stop_timeout();
8518 ret = CreateTimerQueueTimer(
8519 &timer_handle, NULL, set_flag, timeout_flag,
8520 (DWORD)msec, 0, WT_EXECUTEDEFAULT);
8521 if (!ret)
8522 {
8523 semsg(_(e_could_not_set_timeout_str), GetWin32Error());
8524 }
8525 else
8526 {
Bram Moolenaar1f30caf2022-06-19 14:36:35 +01008527 timeout_flag_idx = (timeout_flag_idx + 1) % 2;
Paul Ollis65745772022-06-05 16:55:54 +01008528 timer_active = TRUE;
8529 *timeout_flag = FALSE;
8530 }
8531 return timeout_flag;
8532}
8533#endif