blob: ca1799f13138ca1eb13e07bdf4784b304bf9c195 [file] [log] [blame]
Bram Moolenaaredf3f972016-08-29 22:49:24 +02001/* vi:set ts=8 sts=4 sw=4 noet:
Bram Moolenaar071d4272004-06-13 20:20:40 +00002 *
3 * VIM - Vi IMproved by Bram Moolenaar
4 *
5 * Do ":help uganda" in Vim to read copying and usage conditions.
6 * Do ":help credits" in Vim to see a list of people who contributed.
7 * See README.txt for an overview of the Vim source code.
8 */
9/*
10 * os_win32.c
11 *
12 * Used for both the console version and the Win32 GUI. A lot of code is for
Bram Moolenaar4f974752019-02-17 17:44:42 +010013 * the console version only, so there is a lot of "#ifndef FEAT_GUI_MSWIN".
Bram Moolenaar071d4272004-06-13 20:20:40 +000014 *
15 * Win32 (Windows NT and Windows 95) system-dependent routines.
16 * Portions lifted from the Win32 SDK samples, the MSDOS-dependent code,
17 * NetHack 3.1.3, GNU Emacs 19.30, and Vile 5.5.
18 *
19 * George V. Reilly <george@reilly.org> wrote most of this.
20 * Roger Knobbe <rogerk@wonderware.com> did the initial port of Vim 3.0.
21 */
22
Bram Moolenaar071d4272004-06-13 20:20:40 +000023#include "vim.h"
24
Bram Moolenaar325b7a22004-07-05 15:58:32 +000025#ifdef FEAT_MZSCHEME
26# include "if_mzsch.h"
27#endif
28
Bram Moolenaar071d4272004-06-13 20:20:40 +000029#include <sys/types.h>
Bram Moolenaar071d4272004-06-13 20:20:40 +000030#include <signal.h>
31#include <limits.h>
Bram Moolenaar82881492012-11-20 16:53:39 +010032
Bram Moolenaar0f873732019-12-05 20:28:46 +010033// cproto fails on missing include files
Bram Moolenaar82881492012-11-20 16:53:39 +010034#ifndef PROTO
35# include <process.h>
Bram Moolenaare7bebc42021-02-01 20:50:37 +010036# include <winternl.h>
Bram Moolenaar82881492012-11-20 16:53:39 +010037#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +000038
39#undef chdir
40#ifdef __GNUC__
41# ifndef __MINGW32__
42# include <dirent.h>
43# endif
44#else
45# include <direct.h>
46#endif
47
Bram Moolenaar82881492012-11-20 16:53:39 +010048#ifndef PROTO
Bram Moolenaar651fca82021-11-29 20:39:38 +000049# if !defined(FEAT_GUI_MSWIN)
Bram Moolenaar82881492012-11-20 16:53:39 +010050# include <shellapi.h>
51# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +000052#endif
53
Bram Moolenaarfb630902016-10-29 14:55:00 +020054#ifdef FEAT_JOB_CHANNEL
55# include <tlhelp32.h>
56#endif
57
Bram Moolenaar071d4272004-06-13 20:20:40 +000058#ifdef __MINGW32__
59# ifndef FROM_LEFT_1ST_BUTTON_PRESSED
60# define FROM_LEFT_1ST_BUTTON_PRESSED 0x0001
61# endif
62# ifndef RIGHTMOST_BUTTON_PRESSED
63# define RIGHTMOST_BUTTON_PRESSED 0x0002
64# endif
65# ifndef FROM_LEFT_2ND_BUTTON_PRESSED
66# define FROM_LEFT_2ND_BUTTON_PRESSED 0x0004
67# endif
68# ifndef FROM_LEFT_3RD_BUTTON_PRESSED
69# define FROM_LEFT_3RD_BUTTON_PRESSED 0x0008
70# endif
71# ifndef FROM_LEFT_4TH_BUTTON_PRESSED
72# define FROM_LEFT_4TH_BUTTON_PRESSED 0x0010
73# endif
74
75/*
76 * EventFlags
77 */
78# ifndef MOUSE_MOVED
79# define MOUSE_MOVED 0x0001
80# endif
81# ifndef DOUBLE_CLICK
82# define DOUBLE_CLICK 0x0002
83# endif
84#endif
85
Bram Moolenaar0f873732019-12-05 20:28:46 +010086// Record all output and all keyboard & mouse input
87// #define MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +000088
89#ifdef MCH_WRITE_DUMP
90FILE* fdDump = NULL;
91#endif
92
93/*
94 * When generating prototypes for Win32 on Unix, these lines make the syntax
95 * errors disappear. They do not need to be correct.
96 */
97#ifdef PROTO
Bram Moolenaar912bc4a2019-12-01 18:58:11 +010098# define WINAPI
Bram Moolenaar071d4272004-06-13 20:20:40 +000099typedef char * LPCSTR;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000100typedef char * LPWSTR;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000101typedef int ACCESS_MASK;
102typedef int BOOL;
Paul Ollis65745772022-06-05 16:55:54 +0100103typedef int BOOLEAN;
104typedef int CALLBACK;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000105typedef int COLORREF;
106typedef int CONSOLE_CURSOR_INFO;
107typedef int COORD;
108typedef int DWORD;
109typedef int HANDLE;
Bram Moolenaaref269542016-01-19 13:22:12 +0100110typedef int LPHANDLE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000111typedef int HDC;
112typedef int HFONT;
113typedef int HICON;
114typedef int HINSTANCE;
115typedef int HWND;
116typedef int INPUT_RECORD;
Bram Moolenaare0ab9792017-08-02 23:18:25 +0200117typedef int INT;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000118typedef int KEY_EVENT_RECORD;
119typedef int LOGFONT;
120typedef int LPBOOL;
121typedef int LPCTSTR;
122typedef int LPDWORD;
123typedef int LPSTR;
124typedef int LPTSTR;
125typedef int LPVOID;
126typedef int MOUSE_EVENT_RECORD;
127typedef int PACL;
128typedef int PDWORD;
129typedef int PHANDLE;
130typedef int PRINTDLG;
131typedef int PSECURITY_DESCRIPTOR;
132typedef int PSID;
133typedef int SECURITY_INFORMATION;
134typedef int SHORT;
135typedef int SMALL_RECT;
136typedef int TEXTMETRIC;
137typedef int TOKEN_INFORMATION_CLASS;
138typedef int TRUSTEE;
139typedef int WORD;
140typedef int WCHAR;
141typedef void VOID;
Bram Moolenaar82881492012-11-20 16:53:39 +0100142typedef int BY_HANDLE_FILE_INFORMATION;
Bram Moolenaar32ac8cd2013-07-03 18:49:17 +0200143typedef int SE_OBJECT_TYPE;
144typedef int PSNSECINFO;
145typedef int PSNSECINFOW;
Bram Moolenaarb8e0bdb2014-11-12 16:10:48 +0100146typedef int STARTUPINFO;
147typedef int PROCESS_INFORMATION;
Bram Moolenaard90b6c02016-08-28 18:10:45 +0200148typedef int LPSECURITY_ATTRIBUTES;
Bram Moolenaar0f873732019-12-05 20:28:46 +0100149# define __stdcall // empty
Bram Moolenaar071d4272004-06-13 20:20:40 +0000150#endif
151
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200152#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar0f873732019-12-05 20:28:46 +0100153// Win32 Console handles for input and output
Bram Moolenaar071d4272004-06-13 20:20:40 +0000154static HANDLE g_hConIn = INVALID_HANDLE_VALUE;
155static HANDLE g_hConOut = INVALID_HANDLE_VALUE;
156
Bram Moolenaar0f873732019-12-05 20:28:46 +0100157// Win32 Screen buffer,coordinate,console I/O information
Bram Moolenaar071d4272004-06-13 20:20:40 +0000158static SMALL_RECT g_srScrollRegion;
Bram Moolenaar0f873732019-12-05 20:28:46 +0100159static COORD g_coord; // 0-based, but external coords are 1-based
Bram Moolenaar071d4272004-06-13 20:20:40 +0000160
Bram Moolenaar0f873732019-12-05 20:28:46 +0100161// The attribute of the screen when the editor was started
162static WORD g_attrDefault = 7; // lightgray text on black background
Bram Moolenaar071d4272004-06-13 20:20:40 +0000163static WORD g_attrCurrent;
164
Bram Moolenaar0f873732019-12-05 20:28:46 +0100165static int g_fCBrkPressed = FALSE; // set by ctrl-break interrupt
166static int g_fCtrlCPressed = FALSE; // set when ctrl-C or ctrl-break detected
167static int g_fForceExit = FALSE; // set when forcefully exiting
Bram Moolenaar071d4272004-06-13 20:20:40 +0000168
Bram Moolenaar071d4272004-06-13 20:20:40 +0000169static void scroll(unsigned cLines);
170static void set_scroll_region(unsigned left, unsigned top,
171 unsigned right, unsigned bottom);
Bram Moolenaar6982f422019-02-16 16:48:01 +0100172static void set_scroll_region_tb(unsigned top, unsigned bottom);
173static void set_scroll_region_lr(unsigned left, unsigned right);
174static void insert_lines(unsigned cLines);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000175static void delete_lines(unsigned cLines);
176static void gotoxy(unsigned x, unsigned y);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000177static void standout(void);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000178static int s_cursor_visible = TRUE;
179static int did_create_conin = FALSE;
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200180#endif
181#ifdef FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +0000182static int s_dont_use_vimrun = TRUE;
183static int need_vimrun_warning = FALSE;
184static char *vimrun_path = "vimrun ";
185#endif
186
Bram Moolenaar12b559e2013-06-12 22:41:37 +0200187static int win32_getattrs(char_u *name);
188static int win32_setattrs(char_u *name, int attrs);
189static int win32_set_archive(char_u *name);
190
Bram Moolenaard9ef1b82019-02-13 19:23:10 +0100191static int conpty_working = 0;
Bram Moolenaar57da6982019-09-13 22:30:11 +0200192static int conpty_type = 0;
Bram Moolenaard9ef1b82019-02-13 19:23:10 +0100193static int conpty_stable = 0;
Bram Moolenaar7ed8f592020-04-28 20:44:42 +0200194static int conpty_fix_type = 0;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100195static void vtp_flag_init();
196
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200197#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar6902c0e2019-02-16 14:07:37 +0100198static int vtp_working = 0;
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100199static void vtp_init();
200static void vtp_exit();
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100201static void vtp_sgr_bulk(int arg);
202static void vtp_sgr_bulks(int argc, int *argv);
203
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200204static int wt_working = 0;
205static void wt_init();
206
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100207static guicolor_T save_console_bg_rgb;
208static guicolor_T save_console_fg_rgb;
Bram Moolenaardf543822020-01-30 11:53:59 +0100209static guicolor_T store_console_bg_rgb;
210static guicolor_T store_console_fg_rgb;
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100211
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +0200212static int g_color_index_bg = 0;
213static int g_color_index_fg = 7;
214
215# ifdef FEAT_TERMGUICOLORS
Yasuhiro Matsumotoe42c8da2022-09-01 11:31:45 +0100216static int default_console_color_bg = 0x000000; // black
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +0200217static int default_console_color_fg = 0xc0c0c0; // white
218# endif
219
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100220# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarc5cd8852018-05-01 15:47:38 +0200221# define USE_VTP (vtp_working && is_term_win32() && (p_tgc || (!p_tgc && t_colors >= 256)))
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200222# define USE_WT (wt_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100223# else
224# define USE_VTP 0
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200225# define USE_WT 0
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100226# endif
227
228static void set_console_color_rgb(void);
229static void reset_console_color_rgb(void);
Bram Moolenaardf543822020-01-30 11:53:59 +0100230static void restore_console_color_rgb(void);
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100231#endif
232
Bram Moolenaar0f873732019-12-05 20:28:46 +0100233// This flag is newly created from Windows 10
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100234#ifndef ENABLE_VIRTUAL_TERMINAL_PROCESSING
235# define ENABLE_VIRTUAL_TERMINAL_PROCESSING 0x0004
236#endif
237
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200238#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar0f873732019-12-05 20:28:46 +0100239static int suppress_winsize = 1; // don't fiddle with console
Bram Moolenaar071d4272004-06-13 20:20:40 +0000240#endif
241
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200242static char_u *exe_path = NULL;
243
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100244static BOOL win8_or_later = FALSE;
245
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100246/*
247 * Get version number including build number
248 */
249typedef BOOL (WINAPI *PfnRtlGetVersion)(LPOSVERSIONINFOW);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100250#define MAKE_VER(major, minor, build) \
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100251 (((major) << 24) | ((minor) << 16) | (build))
252
253 static DWORD
254get_build_number(void)
255{
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +0100256 OSVERSIONINFOW osver;
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100257 HMODULE hNtdll;
258 PfnRtlGetVersion pRtlGetVersion;
259 DWORD ver = MAKE_VER(0, 0, 0);
260
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +0100261 osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFOW);
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100262 hNtdll = GetModuleHandle("ntdll.dll");
263 if (hNtdll != NULL)
264 {
265 pRtlGetVersion =
266 (PfnRtlGetVersion)GetProcAddress(hNtdll, "RtlGetVersion");
267 pRtlGetVersion(&osver);
268 ver = MAKE_VER(min(osver.dwMajorVersion, 255),
269 min(osver.dwMinorVersion, 255),
270 min(osver.dwBuildNumber, 32767));
271 }
272 return ver;
273}
274
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200275#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200276 static BOOL
277is_ambiwidth_event(
278 INPUT_RECORD *ir)
279{
280 return ir->EventType == KEY_EVENT
281 && ir->Event.KeyEvent.bKeyDown
282 && ir->Event.KeyEvent.wRepeatCount == 1
283 && ir->Event.KeyEvent.wVirtualKeyCode == 0x12
284 && ir->Event.KeyEvent.wVirtualScanCode == 0x38
K.Takata972db232022-02-04 10:45:38 +0000285 && ir->Event.KeyEvent.uChar.UnicodeChar == 0
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200286 && ir->Event.KeyEvent.dwControlKeyState == 2;
287}
288
289 static void
290make_ambiwidth_event(
291 INPUT_RECORD *down,
292 INPUT_RECORD *up)
293{
294 down->Event.KeyEvent.wVirtualKeyCode = 0;
295 down->Event.KeyEvent.wVirtualScanCode = 0;
K.Takata972db232022-02-04 10:45:38 +0000296 down->Event.KeyEvent.uChar.UnicodeChar
297 = up->Event.KeyEvent.uChar.UnicodeChar;
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200298 down->Event.KeyEvent.dwControlKeyState = 0;
299}
300
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100301/*
302 * Version of ReadConsoleInput() that works with IME.
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100303 * Works around problems on Windows 8.
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100304 */
305 static BOOL
306read_console_input(
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100307 HANDLE hInput,
308 INPUT_RECORD *lpBuffer,
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +0100309 int nLength,
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100310 LPDWORD lpEvents)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100311{
312 enum
313 {
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100314 IRSIZE = 10
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100315 };
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100316 static INPUT_RECORD s_irCache[IRSIZE];
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100317 static DWORD s_dwIndex = 0;
318 static DWORD s_dwMax = 0;
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100319 DWORD dwEvents;
Bram Moolenaardd415a62014-02-05 14:02:27 +0100320 int head;
321 int tail;
322 int i;
Bram Moolenaarbc970da2020-04-26 19:00:07 +0200323 static INPUT_RECORD s_irPseudo;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100324
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200325 if (nLength == -2)
326 return (s_dwMax > 0) ? TRUE : FALSE;
327
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100328 if (!win8_or_later)
329 {
330 if (nLength == -1)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200331 return PeekConsoleInputW(hInput, lpBuffer, 1, lpEvents);
332 return ReadConsoleInputW(hInput, lpBuffer, 1, &dwEvents);
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100333 }
334
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100335 if (s_dwMax == 0)
336 {
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200337 if (!USE_WT && nLength == -1)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200338 return PeekConsoleInputW(hInput, lpBuffer, 1, lpEvents);
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200339 GetNumberOfConsoleInputEvents(hInput, &dwEvents);
340 if (dwEvents == 0 && nLength == -1)
341 return PeekConsoleInputW(hInput, lpBuffer, 1, lpEvents);
342 ReadConsoleInputW(hInput, s_irCache, IRSIZE, &dwEvents);
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100343 s_dwIndex = 0;
344 s_dwMax = dwEvents;
345 if (dwEvents == 0)
346 {
347 *lpEvents = 0;
348 return TRUE;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100349 }
Bram Moolenaardd415a62014-02-05 14:02:27 +0100350
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200351 for (i = s_dwIndex; i < (int)s_dwMax - 1; ++i)
352 if (is_ambiwidth_event(&s_irCache[i]))
353 make_ambiwidth_event(&s_irCache[i], &s_irCache[i + 1]);
354
Bram Moolenaardd415a62014-02-05 14:02:27 +0100355 if (s_dwMax > 1)
356 {
357 head = 0;
358 tail = s_dwMax - 1;
359 while (head != tail)
360 {
361 if (s_irCache[head].EventType == WINDOW_BUFFER_SIZE_EVENT
362 && s_irCache[head + 1].EventType
363 == WINDOW_BUFFER_SIZE_EVENT)
364 {
Bram Moolenaar0f873732019-12-05 20:28:46 +0100365 // Remove duplicate event to avoid flicker.
Bram Moolenaardd415a62014-02-05 14:02:27 +0100366 for (i = head; i < tail; ++i)
367 s_irCache[i] = s_irCache[i + 1];
368 --tail;
369 continue;
370 }
371 head++;
372 }
373 s_dwMax = tail + 1;
374 }
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100375 }
Bram Moolenaardd415a62014-02-05 14:02:27 +0100376
Bram Moolenaarbc970da2020-04-26 19:00:07 +0200377 if (s_irCache[s_dwIndex].EventType == KEY_EVENT)
378 {
379 if (s_irCache[s_dwIndex].Event.KeyEvent.wRepeatCount > 1)
380 {
381 s_irPseudo = s_irCache[s_dwIndex];
382 s_irPseudo.Event.KeyEvent.wRepeatCount = 1;
383 s_irCache[s_dwIndex].Event.KeyEvent.wRepeatCount--;
384 *lpBuffer = s_irPseudo;
385 *lpEvents = 1;
386 return TRUE;
387 }
388 }
389
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100390 *lpBuffer = s_irCache[s_dwIndex];
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200391 if (!(nLength == -1 || nLength == -2) && ++s_dwIndex >= s_dwMax)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100392 s_dwMax = 0;
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100393 *lpEvents = 1;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100394 return TRUE;
395}
396
397/*
398 * Version of PeekConsoleInput() that works with IME.
399 */
400 static BOOL
401peek_console_input(
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100402 HANDLE hInput,
403 INPUT_RECORD *lpBuffer,
Bram Moolenaarbd67aac2019-09-21 23:09:04 +0200404 DWORD nLength UNUSED,
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100405 LPDWORD lpEvents)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100406{
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +0100407 return read_console_input(hInput, lpBuffer, -1, lpEvents);
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100408}
409
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100410# ifdef FEAT_CLIENTSERVER
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200411 static DWORD
412msg_wait_for_multiple_objects(
413 DWORD nCount,
414 LPHANDLE pHandles,
415 BOOL fWaitAll,
416 DWORD dwMilliseconds,
417 DWORD dwWakeMask)
418{
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +0100419 if (read_console_input(NULL, NULL, -2, NULL))
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200420 return WAIT_OBJECT_0;
421 return MsgWaitForMultipleObjects(nCount, pHandles, fWaitAll,
422 dwMilliseconds, dwWakeMask);
423}
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100424# endif
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200425
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100426# ifndef FEAT_CLIENTSERVER
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200427 static DWORD
428wait_for_single_object(
429 HANDLE hHandle,
430 DWORD dwMilliseconds)
431{
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +0100432 if (read_console_input(NULL, NULL, -2, NULL))
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200433 return WAIT_OBJECT_0;
434 return WaitForSingleObject(hHandle, dwMilliseconds);
435}
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100436# endif
437#endif
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200438
Bram Moolenaar071d4272004-06-13 20:20:40 +0000439 static void
440get_exe_name(void)
441{
Bram Moolenaar0f873732019-12-05 20:28:46 +0100442 // Maximum length of $PATH is more than MAXPATHL. 8191 is often mentioned
443 // as the maximum length that works (plus a NUL byte).
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100444#define MAX_ENV_PATH_LEN 8192
445 char temp[MAX_ENV_PATH_LEN];
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200446 char_u *p;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000447
448 if (exe_name == NULL)
449 {
Bram Moolenaar0f873732019-12-05 20:28:46 +0100450 // store the name of the executable, may be used for $VIM
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100451 GetModuleFileName(NULL, temp, MAX_ENV_PATH_LEN - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000452 if (*temp != NUL)
453 exe_name = FullName_save((char_u *)temp, FALSE);
454 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000455
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200456 if (exe_path == NULL && exe_name != NULL)
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000457 {
Bram Moolenaar71ccd032020-06-12 22:59:11 +0200458 exe_path = vim_strnsave(exe_name, gettail_sep(exe_name) - exe_name);
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200459 if (exe_path != NULL)
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000460 {
Bram Moolenaar0f873732019-12-05 20:28:46 +0100461 // Append our starting directory to $PATH, so that when doing
462 // "!xxd" it's found in our starting directory. Needed because
463 // SearchPath() also looks there.
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200464 p = mch_getenv("PATH");
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100465 if (p == NULL
466 || STRLEN(p) + STRLEN(exe_path) + 2 < MAX_ENV_PATH_LEN)
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200467 {
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100468 if (p == NULL || *p == NUL)
469 temp[0] = NUL;
470 else
471 {
472 STRCPY(temp, p);
473 STRCAT(temp, ";");
474 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200475 STRCAT(temp, exe_path);
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +0100476 vim_setenv((char_u *)"PATH", (char_u *)temp);
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200477 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000478 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000479 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000480}
481
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200482/*
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100483 * Unescape characters in "p" that appear in "escaped".
484 */
485 static void
486unescape_shellxquote(char_u *p, char_u *escaped)
487{
Bram Moolenaar4336cdf2012-02-29 13:58:47 +0100488 int l = (int)STRLEN(p);
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100489 int n;
490
491 while (*p != NUL)
492 {
493 if (*p == '^' && vim_strchr(escaped, p[1]) != NULL)
494 mch_memmove(p, p + 1, l--);
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100495 n = (*mb_ptr2len)(p);
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100496 p += n;
497 l -= n;
498 }
499}
500
501/*
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200502 * Load library "name".
503 */
504 HINSTANCE
K.Takatad68b2fc2022-02-12 11:18:37 +0000505vimLoadLib(const char *name)
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200506{
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200507 HINSTANCE dll = NULL;
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200508
Bram Moolenaar3d0e7a92021-05-01 17:46:03 +0200509 // No need to load any library when registering OLE.
510 if (found_register_arg)
511 return dll;
512
Bram Moolenaar0f873732019-12-05 20:28:46 +0100513 // NOTE: Do not use mch_dirname() and mch_chdir() here, they may call
514 // vimLoadLib() recursively, which causes a stack overflow.
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200515 if (exe_path == NULL)
516 get_exe_name();
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200517 if (exe_path != NULL)
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200518 {
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200519 WCHAR old_dirw[MAXPATHL];
520
521 if (GetCurrentDirectoryW(MAXPATHL, old_dirw) != 0)
522 {
Bram Moolenaar0f873732019-12-05 20:28:46 +0100523 // Change directory to where the executable is, both to make
524 // sure we find a .dll there and to avoid looking for a .dll
525 // in the current directory.
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +0100526 SetCurrentDirectory((LPCSTR)exe_path);
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200527 dll = LoadLibrary(name);
528 SetCurrentDirectoryW(old_dirw);
529 return dll;
530 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200531 }
532 return dll;
533}
534
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200535#if defined(VIMDLL) || defined(PROTO)
536/*
537 * Check if the current executable file is for the GUI subsystem.
538 */
539 int
540mch_is_gui_executable(void)
541{
542 PBYTE pImage = (PBYTE)GetModuleHandle(NULL);
543 PIMAGE_DOS_HEADER pDOS = (PIMAGE_DOS_HEADER)pImage;
544 PIMAGE_NT_HEADERS pPE;
545
546 if (pDOS->e_magic != IMAGE_DOS_SIGNATURE)
547 return FALSE;
548 pPE = (PIMAGE_NT_HEADERS)(pImage + pDOS->e_lfanew);
549 if (pPE->Signature != IMAGE_NT_SIGNATURE)
550 return FALSE;
551 if (pPE->OptionalHeader.Subsystem == IMAGE_SUBSYSTEM_WINDOWS_GUI)
552 return TRUE;
553 return FALSE;
554}
555#endif
556
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000557#if defined(DYNAMIC_ICONV) || defined(DYNAMIC_GETTEXT) \
558 || defined(FEAT_PYTHON3) || defined(PROTO)
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100559/*
560 * Get related information about 'funcname' which is imported by 'hInst'.
561 * If 'info' is 0, return the function address.
562 * If 'info' is 1, return the module name which the function is imported from.
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000563 * If 'info' is 2, hook the function with 'ptr', and return the original
564 * function address.
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100565 */
566 static void *
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000567get_imported_func_info(HINSTANCE hInst, const char *funcname, int info,
568 const void *ptr)
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100569{
570 PBYTE pImage = (PBYTE)hInst;
571 PIMAGE_DOS_HEADER pDOS = (PIMAGE_DOS_HEADER)hInst;
572 PIMAGE_NT_HEADERS pPE;
573 PIMAGE_IMPORT_DESCRIPTOR pImpDesc;
Bram Moolenaar0f873732019-12-05 20:28:46 +0100574 PIMAGE_THUNK_DATA pIAT; // Import Address Table
575 PIMAGE_THUNK_DATA pINT; // Import Name Table
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100576 PIMAGE_IMPORT_BY_NAME pImpName;
577
578 if (pDOS->e_magic != IMAGE_DOS_SIGNATURE)
579 return NULL;
580 pPE = (PIMAGE_NT_HEADERS)(pImage + pDOS->e_lfanew);
581 if (pPE->Signature != IMAGE_NT_SIGNATURE)
582 return NULL;
583 pImpDesc = (PIMAGE_IMPORT_DESCRIPTOR)(pImage
584 + pPE->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT]
585 .VirtualAddress);
586 for (; pImpDesc->FirstThunk; ++pImpDesc)
587 {
588 if (!pImpDesc->OriginalFirstThunk)
589 continue;
590 pIAT = (PIMAGE_THUNK_DATA)(pImage + pImpDesc->FirstThunk);
591 pINT = (PIMAGE_THUNK_DATA)(pImage + pImpDesc->OriginalFirstThunk);
592 for (; pIAT->u1.Function; ++pIAT, ++pINT)
593 {
594 if (IMAGE_SNAP_BY_ORDINAL(pINT->u1.Ordinal))
595 continue;
596 pImpName = (PIMAGE_IMPORT_BY_NAME)(pImage
597 + (UINT_PTR)(pINT->u1.AddressOfData));
598 if (strcmp((char *)pImpName->Name, funcname) == 0)
599 {
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000600 void *original;
601 DWORD old, new = PAGE_READWRITE;
602
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100603 switch (info)
604 {
605 case 0:
606 return (void *)pIAT->u1.Function;
607 case 1:
608 return (void *)(pImage + pImpDesc->Name);
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000609 case 2:
610 original = (void *)pIAT->u1.Function;
611 VirtualProtect(&pIAT->u1.Function, sizeof(void *),
612 new, &old);
613 pIAT->u1.Function = (UINT_PTR)ptr;
614 VirtualProtect(&pIAT->u1.Function, sizeof(void *),
615 old, &new);
616 return original;
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100617 default:
618 return NULL;
619 }
620 }
621 }
622 }
623 return NULL;
624}
625
626/*
627 * Get the module handle which 'funcname' in 'hInst' is imported from.
628 */
629 HINSTANCE
630find_imported_module_by_funcname(HINSTANCE hInst, const char *funcname)
631{
632 char *modulename;
633
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000634 modulename = (char *)get_imported_func_info(hInst, funcname, 1, NULL);
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100635 if (modulename != NULL)
636 return GetModuleHandleA(modulename);
637 return NULL;
638}
639
640/*
641 * Get the address of 'funcname' which is imported by 'hInst' DLL.
642 */
643 void *
644get_dll_import_func(HINSTANCE hInst, const char *funcname)
645{
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000646 return get_imported_func_info(hInst, funcname, 0, NULL);
647}
648
649/*
650 * Hook the function named 'funcname' which is imported by 'hInst' DLL,
651 * and return the original function address.
652 */
653 void *
654hook_dll_import_func(HINSTANCE hInst, const char *funcname, const void *hook)
655{
656 return get_imported_func_info(hInst, funcname, 2, hook);
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100657}
658#endif
659
Bram Moolenaar071d4272004-06-13 20:20:40 +0000660#if defined(DYNAMIC_GETTEXT) || defined(PROTO)
661# ifndef GETTEXT_DLL
662# define GETTEXT_DLL "libintl.dll"
Bram Moolenaar7554c542018-10-06 15:03:15 +0200663# define GETTEXT_DLL_ALT1 "libintl-8.dll"
664# define GETTEXT_DLL_ALT2 "intl.dll"
Bram Moolenaar071d4272004-06-13 20:20:40 +0000665# endif
Bram Moolenaar0f873732019-12-05 20:28:46 +0100666// Dummy functions
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000667static char *null_libintl_gettext(const char *);
Bram Moolenaaree695f72016-08-03 22:08:45 +0200668static char *null_libintl_ngettext(const char *, const char *, unsigned long n);
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000669static char *null_libintl_textdomain(const char *);
670static char *null_libintl_bindtextdomain(const char *, const char *);
671static char *null_libintl_bind_textdomain_codeset(const char *, const char *);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100672static int null_libintl_wputenv(const wchar_t *);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000673
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200674static HINSTANCE hLibintlDLL = NULL;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000675char *(*dyn_libintl_gettext)(const char *) = null_libintl_gettext;
Bram Moolenaaree695f72016-08-03 22:08:45 +0200676char *(*dyn_libintl_ngettext)(const char *, const char *, unsigned long n)
677 = null_libintl_ngettext;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000678char *(*dyn_libintl_textdomain)(const char *) = null_libintl_textdomain;
679char *(*dyn_libintl_bindtextdomain)(const char *, const char *)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000680 = null_libintl_bindtextdomain;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000681char *(*dyn_libintl_bind_textdomain_codeset)(const char *, const char *)
682 = null_libintl_bind_textdomain_codeset;
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100683int (*dyn_libintl_wputenv)(const wchar_t *) = null_libintl_wputenv;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000684
685 int
Bram Moolenaar05540972016-01-30 20:31:25 +0100686dyn_libintl_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000687{
688 int i;
689 static struct
690 {
691 char *name;
692 FARPROC *ptr;
693 } libintl_entry[] =
694 {
695 {"gettext", (FARPROC*)&dyn_libintl_gettext},
Bram Moolenaaree695f72016-08-03 22:08:45 +0200696 {"ngettext", (FARPROC*)&dyn_libintl_ngettext},
Bram Moolenaar071d4272004-06-13 20:20:40 +0000697 {"textdomain", (FARPROC*)&dyn_libintl_textdomain},
698 {"bindtextdomain", (FARPROC*)&dyn_libintl_bindtextdomain},
699 {NULL, NULL}
700 };
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100701 HINSTANCE hmsvcrt;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000702
Bram Moolenaar7554c542018-10-06 15:03:15 +0200703 // No need to initialize twice.
704 if (hLibintlDLL != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000705 return 1;
Bram Moolenaar7554c542018-10-06 15:03:15 +0200706 // Load gettext library (libintl.dll and other names).
Bram Moolenaar923e43b2016-01-28 15:07:38 +0100707 hLibintlDLL = vimLoadLib(GETTEXT_DLL);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100708# ifdef GETTEXT_DLL_ALT1
Bram Moolenaar286eacd2016-01-16 18:05:50 +0100709 if (!hLibintlDLL)
Bram Moolenaar7554c542018-10-06 15:03:15 +0200710 hLibintlDLL = vimLoadLib(GETTEXT_DLL_ALT1);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100711# endif
712# ifdef GETTEXT_DLL_ALT2
Bram Moolenaar7554c542018-10-06 15:03:15 +0200713 if (!hLibintlDLL)
714 hLibintlDLL = vimLoadLib(GETTEXT_DLL_ALT2);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100715# endif
Bram Moolenaar938ee832016-01-24 15:36:03 +0100716 if (!hLibintlDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000717 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200718 if (p_verbose > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000719 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200720 verbose_enter();
Bram Moolenaar460ae5d2022-01-01 14:19:49 +0000721 semsg(_(e_could_not_load_library_str_str), GETTEXT_DLL, GetWin32Error());
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200722 verbose_leave();
Bram Moolenaar071d4272004-06-13 20:20:40 +0000723 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200724 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000725 }
726 for (i = 0; libintl_entry[i].name != NULL
727 && libintl_entry[i].ptr != NULL; ++i)
728 {
K.Takata54119102022-02-03 13:33:03 +0000729 if ((*libintl_entry[i].ptr = GetProcAddress(hLibintlDLL,
Bram Moolenaar071d4272004-06-13 20:20:40 +0000730 libintl_entry[i].name)) == NULL)
731 {
732 dyn_libintl_end();
733 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +0000734 {
735 verbose_enter();
Bram Moolenaar460ae5d2022-01-01 14:19:49 +0000736 semsg(_(e_could_not_load_library_function_str), libintl_entry[i].name);
Bram Moolenaara04f10b2005-05-31 22:09:46 +0000737 verbose_leave();
738 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000739 return 0;
740 }
741 }
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000742
Bram Moolenaar0f873732019-12-05 20:28:46 +0100743 // The bind_textdomain_codeset() function is optional.
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +0100744 dyn_libintl_bind_textdomain_codeset = (char *(*)(const char *, const char *))
745 GetProcAddress(hLibintlDLL, "bind_textdomain_codeset");
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000746 if (dyn_libintl_bind_textdomain_codeset == NULL)
747 dyn_libintl_bind_textdomain_codeset =
748 null_libintl_bind_textdomain_codeset;
749
Bram Moolenaar0f873732019-12-05 20:28:46 +0100750 // _wputenv() function for the libintl.dll is optional.
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100751 hmsvcrt = find_imported_module_by_funcname(hLibintlDLL, "getenv");
752 if (hmsvcrt != NULL)
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +0100753 dyn_libintl_wputenv = (int (*)(const wchar_t *))
754 GetProcAddress(hmsvcrt, "_wputenv");
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100755 if (dyn_libintl_wputenv == NULL || dyn_libintl_wputenv == _wputenv)
756 dyn_libintl_wputenv = null_libintl_wputenv;
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100757
Bram Moolenaar071d4272004-06-13 20:20:40 +0000758 return 1;
759}
760
761 void
Bram Moolenaar05540972016-01-30 20:31:25 +0100762dyn_libintl_end(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000763{
764 if (hLibintlDLL)
765 FreeLibrary(hLibintlDLL);
766 hLibintlDLL = NULL;
767 dyn_libintl_gettext = null_libintl_gettext;
Bram Moolenaaree695f72016-08-03 22:08:45 +0200768 dyn_libintl_ngettext = null_libintl_ngettext;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000769 dyn_libintl_textdomain = null_libintl_textdomain;
770 dyn_libintl_bindtextdomain = null_libintl_bindtextdomain;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000771 dyn_libintl_bind_textdomain_codeset = null_libintl_bind_textdomain_codeset;
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100772 dyn_libintl_wputenv = null_libintl_wputenv;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000773}
774
775 static char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000776null_libintl_gettext(const char *msgid)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000777{
778 return (char*)msgid;
779}
780
781 static char *
Bram Moolenaaree695f72016-08-03 22:08:45 +0200782null_libintl_ngettext(
783 const char *msgid,
784 const char *msgid_plural,
785 unsigned long n)
786{
Bram Moolenaarc90f2ae2016-08-04 22:00:15 +0200787 return (char *)(n == 1 ? msgid : msgid_plural);
Bram Moolenaaree695f72016-08-03 22:08:45 +0200788}
789
Bram Moolenaaree695f72016-08-03 22:08:45 +0200790 static char *
Bram Moolenaar1266d672017-02-01 13:43:36 +0100791null_libintl_bindtextdomain(
792 const char *domainname UNUSED,
793 const char *dirname UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000794{
795 return NULL;
796}
797
798 static char *
Bram Moolenaar1266d672017-02-01 13:43:36 +0100799null_libintl_bind_textdomain_codeset(
800 const char *domainname UNUSED,
801 const char *codeset UNUSED)
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000802{
803 return NULL;
804}
805
806 static char *
Bram Moolenaar1266d672017-02-01 13:43:36 +0100807null_libintl_textdomain(const char *domainname UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000808{
809 return NULL;
810}
811
Bram Moolenaare0ab9792017-08-02 23:18:25 +0200812 static int
Bram Moolenaar1266d672017-02-01 13:43:36 +0100813null_libintl_wputenv(const wchar_t *envstring UNUSED)
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100814{
815 return 0;
816}
817
Bram Moolenaar0f873732019-12-05 20:28:46 +0100818#endif // DYNAMIC_GETTEXT
Bram Moolenaar071d4272004-06-13 20:20:40 +0000819
Bram Moolenaar0f873732019-12-05 20:28:46 +0100820// This symbol is not defined in older versions of the SDK or Visual C++
Bram Moolenaar071d4272004-06-13 20:20:40 +0000821
822#ifndef VER_PLATFORM_WIN32_WINDOWS
823# define VER_PLATFORM_WIN32_WINDOWS 1
824#endif
825
Bram Moolenaar071d4272004-06-13 20:20:40 +0000826#ifdef HAVE_ACL
Bram Moolenaar82881492012-11-20 16:53:39 +0100827# ifndef PROTO
828# include <aclapi.h>
829# endif
Bram Moolenaar27515922013-06-29 15:36:26 +0200830# ifndef PROTECTED_DACL_SECURITY_INFORMATION
831# define PROTECTED_DACL_SECURITY_INFORMATION 0x80000000L
832# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000833#endif
834
Bram Moolenaar27515922013-06-29 15:36:26 +0200835#ifdef HAVE_ACL
836/*
837 * Enables or disables the specified privilege.
838 */
839 static BOOL
840win32_enable_privilege(LPTSTR lpszPrivilege, BOOL bEnable)
841{
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100842 BOOL bResult;
843 LUID luid;
844 HANDLE hToken;
845 TOKEN_PRIVILEGES tokenPrivileges;
Bram Moolenaar27515922013-06-29 15:36:26 +0200846
847 if (!OpenProcessToken(GetCurrentProcess(),
848 TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
849 return FALSE;
850
851 if (!LookupPrivilegeValue(NULL, lpszPrivilege, &luid))
852 {
853 CloseHandle(hToken);
854 return FALSE;
855 }
856
Bram Moolenaar45500912014-07-09 20:51:07 +0200857 tokenPrivileges.PrivilegeCount = 1;
Bram Moolenaar27515922013-06-29 15:36:26 +0200858 tokenPrivileges.Privileges[0].Luid = luid;
859 tokenPrivileges.Privileges[0].Attributes = bEnable ?
860 SE_PRIVILEGE_ENABLED : 0;
861
862 bResult = AdjustTokenPrivileges(hToken, FALSE, &tokenPrivileges,
863 sizeof(TOKEN_PRIVILEGES), NULL, NULL);
864
865 CloseHandle(hToken);
866
867 return bResult && GetLastError() == ERROR_SUCCESS;
868}
869#endif
870
Bram Moolenaar29d2f452020-12-04 19:42:52 +0100871#ifdef _MSC_VER
872// Suppress the deprecation warning for using GetVersionEx().
873// It is needed for implementing "windowsversion()".
874# pragma warning(push)
875# pragma warning(disable: 4996)
876#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000877/*
Bram Moolenaar1e1d2e82020-05-18 20:17:02 +0200878 * Set "win8_or_later" and fill in "windowsVersion" if possible.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000879 */
880 void
881PlatformId(void)
882{
883 static int done = FALSE;
884
885 if (!done)
886 {
887 OSVERSIONINFO ovi;
888
889 ovi.dwOSVersionInfoSize = sizeof(ovi);
890 GetVersionEx(&ovi);
891
Bram Moolenaar1e1d2e82020-05-18 20:17:02 +0200892#ifdef FEAT_EVAL
Bram Moolenaar0c1e3742019-12-27 13:49:24 +0100893 vim_snprintf(windowsVersion, sizeof(windowsVersion), "%d.%d",
894 (int)ovi.dwMajorVersion, (int)ovi.dwMinorVersion);
Bram Moolenaar1e1d2e82020-05-18 20:17:02 +0200895#endif
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100896 if ((ovi.dwMajorVersion == 6 && ovi.dwMinorVersion >= 2)
897 || ovi.dwMajorVersion > 6)
898 win8_or_later = TRUE;
899
Bram Moolenaar071d4272004-06-13 20:20:40 +0000900#ifdef HAVE_ACL
Bram Moolenaar0f873732019-12-05 20:28:46 +0100901 // Enable privilege for getting or setting SACLs.
Bram Moolenaarcea912a2016-10-12 14:20:24 +0200902 win32_enable_privilege(SE_SECURITY_NAME, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000903#endif
904 done = TRUE;
905 }
906}
Bram Moolenaar29d2f452020-12-04 19:42:52 +0100907#ifdef _MSC_VER
908# pragma warning(pop)
909#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000910
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200911#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000912
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100913# define SHIFT (SHIFT_PRESSED)
914# define CTRL (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED)
915# define ALT (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED)
916# define ALT_GR (RIGHT_ALT_PRESSED | LEFT_CTRL_PRESSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000917
918
Bram Moolenaar0f873732019-12-05 20:28:46 +0100919// When uChar.AsciiChar is 0, then we need to look at wVirtualKeyCode.
920// We map function keys to their ANSI terminal equivalents, as produced
921// by ANSI.SYS, for compatibility with the MS-DOS version of Vim. Any
922// ANSI key with a value >= '\300' is nonstandard, but provided anyway
923// so that the user can have access to all SHIFT-, CTRL-, and ALT-
924// combinations of function/arrow/etc keys.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000925
Bram Moolenaard6f676d2005-06-01 21:51:55 +0000926static const struct
Bram Moolenaar071d4272004-06-13 20:20:40 +0000927{
928 WORD wVirtKey;
929 BOOL fAnsiKey;
930 int chAlone;
931 int chShift;
932 int chCtrl;
933 int chAlt;
934} VirtKeyMap[] =
935{
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200936// Key ANSI alone shift ctrl alt
Bram Moolenaar071d4272004-06-13 20:20:40 +0000937 { VK_ESCAPE,FALSE, ESC, ESC, ESC, ESC, },
938
939 { VK_F1, TRUE, ';', 'T', '^', 'h', },
940 { VK_F2, TRUE, '<', 'U', '_', 'i', },
941 { VK_F3, TRUE, '=', 'V', '`', 'j', },
942 { VK_F4, TRUE, '>', 'W', 'a', 'k', },
943 { VK_F5, TRUE, '?', 'X', 'b', 'l', },
944 { VK_F6, TRUE, '@', 'Y', 'c', 'm', },
945 { VK_F7, TRUE, 'A', 'Z', 'd', 'n', },
946 { VK_F8, TRUE, 'B', '[', 'e', 'o', },
947 { VK_F9, TRUE, 'C', '\\', 'f', 'p', },
948 { VK_F10, TRUE, 'D', ']', 'g', 'q', },
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200949 { VK_F11, TRUE, '\205', '\207', '\211', '\213', },
950 { VK_F12, TRUE, '\206', '\210', '\212', '\214', },
Bram Moolenaar071d4272004-06-13 20:20:40 +0000951
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200952 { VK_HOME, TRUE, 'G', '\302', 'w', '\303', },
953 { VK_UP, TRUE, 'H', '\304', '\305', '\306', },
954 { VK_PRIOR, TRUE, 'I', '\307', '\204', '\310', }, // PgUp
955 { VK_LEFT, TRUE, 'K', '\311', 's', '\312', },
956 { VK_RIGHT, TRUE, 'M', '\313', 't', '\314', },
957 { VK_END, TRUE, 'O', '\315', 'u', '\316', },
958 { VK_DOWN, TRUE, 'P', '\317', '\320', '\321', },
959 { VK_NEXT, TRUE, 'Q', '\322', 'v', '\323', }, // PgDn
960 { VK_INSERT,TRUE, 'R', '\324', '\325', '\326', },
961 { VK_DELETE,TRUE, 'S', '\327', '\330', '\331', },
Bram Moolenaarb70a47b2019-03-30 22:11:21 +0100962 { VK_BACK, TRUE, 'x', 'y', 'z', '{', }, // Backspace
Bram Moolenaar071d4272004-06-13 20:20:40 +0000963
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200964 { VK_SNAPSHOT,TRUE, 0, 0, 0, 'r', }, // PrtScrn
Bram Moolenaar071d4272004-06-13 20:20:40 +0000965
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100966# if 0
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200967 // Most people don't have F13-F20, but what the hell...
968 { VK_F13, TRUE, '\332', '\333', '\334', '\335', },
969 { VK_F14, TRUE, '\336', '\337', '\340', '\341', },
970 { VK_F15, TRUE, '\342', '\343', '\344', '\345', },
971 { VK_F16, TRUE, '\346', '\347', '\350', '\351', },
972 { VK_F17, TRUE, '\352', '\353', '\354', '\355', },
973 { VK_F18, TRUE, '\356', '\357', '\360', '\361', },
974 { VK_F19, TRUE, '\362', '\363', '\364', '\365', },
975 { VK_F20, TRUE, '\366', '\367', '\370', '\371', },
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100976# endif
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200977 { VK_ADD, TRUE, 'N', 'N', 'N', 'N', }, // keyp '+'
978 { VK_SUBTRACT, TRUE,'J', 'J', 'J', 'J', }, // keyp '-'
979 // { VK_DIVIDE, TRUE,'N', 'N', 'N', 'N', }, // keyp '/'
980 { VK_MULTIPLY, TRUE,'7', '7', '7', '7', }, // keyp '*'
Bram Moolenaar071d4272004-06-13 20:20:40 +0000981
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200982 { VK_NUMPAD0,TRUE, '\332', '\333', '\334', '\335', },
983 { VK_NUMPAD1,TRUE, '\336', '\337', '\340', '\341', },
984 { VK_NUMPAD2,TRUE, '\342', '\343', '\344', '\345', },
985 { VK_NUMPAD3,TRUE, '\346', '\347', '\350', '\351', },
986 { VK_NUMPAD4,TRUE, '\352', '\353', '\354', '\355', },
987 { VK_NUMPAD5,TRUE, '\356', '\357', '\360', '\361', },
988 { VK_NUMPAD6,TRUE, '\362', '\363', '\364', '\365', },
989 { VK_NUMPAD7,TRUE, '\366', '\367', '\370', '\371', },
990 { VK_NUMPAD8,TRUE, '\372', '\373', '\374', '\375', },
991 // Sorry, out of number space! <negri>
Bram Moolenaarb70a47b2019-03-30 22:11:21 +0100992 { VK_NUMPAD9,TRUE, '\376', '\377', '|', '}', },
Bram Moolenaar071d4272004-06-13 20:20:40 +0000993};
994
995
Bram Moolenaar0f873732019-12-05 20:28:46 +0100996/*
997 * The return code indicates key code size.
998 */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000999 static int
Bram Moolenaar071d4272004-06-13 20:20:40 +00001000win32_kbd_patch_key(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001001 KEY_EVENT_RECORD *pker)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001002{
1003 UINT uMods = pker->dwControlKeyState;
1004 static int s_iIsDead = 0;
1005 static WORD awAnsiCode[2];
1006 static BYTE abKeystate[256];
1007
1008
1009 if (s_iIsDead == 2)
1010 {
K.Takata972db232022-02-04 10:45:38 +00001011 pker->uChar.UnicodeChar = (WCHAR) awAnsiCode[1];
Bram Moolenaar071d4272004-06-13 20:20:40 +00001012 s_iIsDead = 0;
1013 return 1;
1014 }
1015
K.Takata972db232022-02-04 10:45:38 +00001016 if (pker->uChar.UnicodeChar != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001017 return 1;
1018
Bram Moolenaara80faa82020-04-12 19:37:17 +02001019 CLEAR_FIELD(abKeystate);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001020
Bram Moolenaar0f873732019-12-05 20:28:46 +01001021 // Clear any pending dead keys
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001022 ToUnicode(VK_SPACE, MapVirtualKey(VK_SPACE, 0), abKeystate, awAnsiCode, 2, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001023
1024 if (uMods & SHIFT_PRESSED)
1025 abKeystate[VK_SHIFT] = 0x80;
1026 if (uMods & CAPSLOCK_ON)
1027 abKeystate[VK_CAPITAL] = 1;
1028
1029 if ((uMods & ALT_GR) == ALT_GR)
1030 {
1031 abKeystate[VK_CONTROL] = abKeystate[VK_LCONTROL] =
1032 abKeystate[VK_MENU] = abKeystate[VK_RMENU] = 0x80;
1033 }
1034
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001035 s_iIsDead = ToUnicode(pker->wVirtualKeyCode, pker->wVirtualScanCode,
1036 abKeystate, awAnsiCode, 2, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001037
1038 if (s_iIsDead > 0)
K.Takata972db232022-02-04 10:45:38 +00001039 pker->uChar.UnicodeChar = (WCHAR) awAnsiCode[0];
Bram Moolenaar071d4272004-06-13 20:20:40 +00001040
1041 return s_iIsDead;
1042}
1043
Bram Moolenaar071d4272004-06-13 20:20:40 +00001044static BOOL g_fJustGotFocus = FALSE;
1045
1046/*
1047 * Decode a KEY_EVENT into one or two keystrokes
1048 */
1049 static BOOL
1050decode_key_event(
1051 KEY_EVENT_RECORD *pker,
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001052 WCHAR *pch,
1053 WCHAR *pch2,
Bram Moolenaar071d4272004-06-13 20:20:40 +00001054 int *pmodifiers,
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02001055 BOOL fDoPost UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001056{
1057 int i;
1058 const int nModifs = pker->dwControlKeyState & (SHIFT | ALT | CTRL);
1059
1060 *pch = *pch2 = NUL;
1061 g_fJustGotFocus = FALSE;
1062
Bram Moolenaar0f873732019-12-05 20:28:46 +01001063 // ignore key up events
Bram Moolenaar071d4272004-06-13 20:20:40 +00001064 if (!pker->bKeyDown)
1065 return FALSE;
1066
Bram Moolenaar0f873732019-12-05 20:28:46 +01001067 // ignore some keystrokes
Bram Moolenaar071d4272004-06-13 20:20:40 +00001068 switch (pker->wVirtualKeyCode)
1069 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001070 // modifiers
Bram Moolenaar071d4272004-06-13 20:20:40 +00001071 case VK_SHIFT:
1072 case VK_CONTROL:
Bram Moolenaar0f873732019-12-05 20:28:46 +01001073 case VK_MENU: // Alt key
Bram Moolenaar071d4272004-06-13 20:20:40 +00001074 return FALSE;
1075
1076 default:
1077 break;
1078 }
1079
Bram Moolenaar0f873732019-12-05 20:28:46 +01001080 // special cases
K.Takata972db232022-02-04 10:45:38 +00001081 if ((nModifs & CTRL) != 0 && (nModifs & ~CTRL) == 0
1082 && pker->uChar.UnicodeChar == NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001083 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001084 // Ctrl-6 is Ctrl-^
Bram Moolenaar071d4272004-06-13 20:20:40 +00001085 if (pker->wVirtualKeyCode == '6')
1086 {
1087 *pch = Ctrl_HAT;
1088 return TRUE;
1089 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01001090 // Ctrl-2 is Ctrl-@
Bram Moolenaar071d4272004-06-13 20:20:40 +00001091 else if (pker->wVirtualKeyCode == '2')
1092 {
1093 *pch = NUL;
1094 return TRUE;
1095 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01001096 // Ctrl-- is Ctrl-_
Bram Moolenaar071d4272004-06-13 20:20:40 +00001097 else if (pker->wVirtualKeyCode == 0xBD)
1098 {
1099 *pch = Ctrl__;
1100 return TRUE;
1101 }
1102 }
1103
Bram Moolenaar0f873732019-12-05 20:28:46 +01001104 // Shift-TAB
Bram Moolenaar071d4272004-06-13 20:20:40 +00001105 if (pker->wVirtualKeyCode == VK_TAB && (nModifs & SHIFT_PRESSED))
1106 {
1107 *pch = K_NUL;
1108 *pch2 = '\017';
1109 return TRUE;
1110 }
1111
K.Takataeeec2542021-06-02 13:28:16 +02001112 for (i = ARRAY_LENGTH(VirtKeyMap); --i >= 0; )
Bram Moolenaar071d4272004-06-13 20:20:40 +00001113 {
1114 if (VirtKeyMap[i].wVirtKey == pker->wVirtualKeyCode)
1115 {
1116 if (nModifs == 0)
1117 *pch = VirtKeyMap[i].chAlone;
1118 else if ((nModifs & SHIFT) != 0 && (nModifs & ~SHIFT) == 0)
1119 *pch = VirtKeyMap[i].chShift;
1120 else if ((nModifs & CTRL) != 0 && (nModifs & ~CTRL) == 0)
1121 *pch = VirtKeyMap[i].chCtrl;
1122 else if ((nModifs & ALT) != 0 && (nModifs & ~ALT) == 0)
1123 *pch = VirtKeyMap[i].chAlt;
1124
1125 if (*pch != 0)
1126 {
1127 if (VirtKeyMap[i].fAnsiKey)
1128 {
1129 *pch2 = *pch;
1130 *pch = K_NUL;
1131 }
1132
1133 return TRUE;
1134 }
1135 }
1136 }
1137
1138 i = win32_kbd_patch_key(pker);
1139
1140 if (i < 0)
1141 *pch = NUL;
1142 else
1143 {
K.Takata972db232022-02-04 10:45:38 +00001144 *pch = (i > 0) ? pker->uChar.UnicodeChar : NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001145
1146 if (pmodifiers != NULL)
1147 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001148 // Pass on the ALT key as a modifier, but only when not combined
1149 // with CTRL (which is ALTGR).
Bram Moolenaar071d4272004-06-13 20:20:40 +00001150 if ((nModifs & ALT) != 0 && (nModifs & CTRL) == 0)
1151 *pmodifiers |= MOD_MASK_ALT;
1152
Bram Moolenaar0f873732019-12-05 20:28:46 +01001153 // Pass on SHIFT only for special keys, because we don't know when
1154 // it's already included with the character.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001155 if ((nModifs & SHIFT) != 0 && *pch <= 0x20)
1156 *pmodifiers |= MOD_MASK_SHIFT;
1157
Bram Moolenaar0f873732019-12-05 20:28:46 +01001158 // Pass on CTRL only for non-special keys, because we don't know
1159 // when it's already included with the character. And not when
1160 // combined with ALT (which is ALTGR).
Bram Moolenaar071d4272004-06-13 20:20:40 +00001161 if ((nModifs & CTRL) != 0 && (nModifs & ALT) == 0
1162 && *pch >= 0x20 && *pch < 0x80)
1163 *pmodifiers |= MOD_MASK_CTRL;
1164 }
1165 }
1166
1167 return (*pch != NUL);
1168}
1169
Bram Moolenaar0f873732019-12-05 20:28:46 +01001170#endif // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00001171
1172
Bram Moolenaar071d4272004-06-13 20:20:40 +00001173/*
1174 * For the GUI the mouse handling is in gui_w32.c.
1175 */
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001176#if defined(FEAT_GUI_MSWIN) && !defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001177 void
Bram Moolenaar1266d672017-02-01 13:43:36 +01001178mch_setmouse(int on UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001179{
1180}
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001181#else
Bram Moolenaar0f873732019-12-05 20:28:46 +01001182static int g_fMouseAvail = FALSE; // mouse present
1183static int g_fMouseActive = FALSE; // mouse enabled
1184static int g_nMouseClick = -1; // mouse status
1185static int g_xMouse; // mouse x coordinate
1186static int g_yMouse; // mouse y coordinate
Bram Moolenaar9f1983d2022-05-12 20:35:35 +01001187static DWORD g_cmodein = 0; // Original console input mode
1188static DWORD g_cmodeout = 0; // Original console output mode
Bram Moolenaar071d4272004-06-13 20:20:40 +00001189
1190/*
1191 * Enable or disable mouse input
1192 */
1193 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001194mch_setmouse(int on)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001195{
1196 DWORD cmodein;
1197
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001198# ifdef VIMDLL
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001199 if (gui.in_use)
1200 return;
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001201# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001202 if (!g_fMouseAvail)
1203 return;
1204
1205 g_fMouseActive = on;
1206 GetConsoleMode(g_hConIn, &cmodein);
1207
1208 if (g_fMouseActive)
Wez Furlong6ef5ab52021-05-30 19:29:41 +02001209 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00001210 cmodein |= ENABLE_MOUSE_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02001211 cmodein &= ~ENABLE_QUICK_EDIT_MODE;
1212 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001213 else
Wez Furlong6ef5ab52021-05-30 19:29:41 +02001214 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00001215 cmodein &= ~ENABLE_MOUSE_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02001216 cmodein |= g_cmodein & ENABLE_QUICK_EDIT_MODE;
1217 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001218
Wez Furlong6ef5ab52021-05-30 19:29:41 +02001219 SetConsoleMode(g_hConIn, cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001220}
1221
Bram Moolenaar157d8132018-03-06 17:09:20 +01001222
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001223# if defined(FEAT_BEVAL_TERM) || defined(PROTO)
Bram Moolenaar157d8132018-03-06 17:09:20 +01001224/*
1225 * Called when 'balloonevalterm' changed.
1226 */
1227 void
1228mch_bevalterm_changed(void)
1229{
1230 mch_setmouse(g_fMouseActive);
1231}
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001232# endif
Bram Moolenaar157d8132018-03-06 17:09:20 +01001233
Christopher Plewright2a46f812022-10-16 19:47:45 +01001234/*
1235 * Win32 console mouse scroll event handler.
1236 * Loosely based on the _OnMouseWheel() function in gui_w32.c
1237 *
1238 * This encodes the mouse scroll direction and keyboard modifiers into
1239 * g_nMouseClick, and the mouse position into g_xMouse and g_yMouse
1240 *
1241 * The direction of the scroll is decoded from two fields of the win32 console
1242 * mouse event record;
1243 * 1. The axis - vertical or horizontal flag - from dwEventFlags, and
1244 * 2. The sign - positive or negative (aka delta flag) - from dwButtonState
1245 *
1246 * When scroll axis is HORIZONTAL
1247 * - If the high word of the dwButtonState member contains a positive
1248 * value, the wheel was rotated to the right.
1249 * - Otherwise, the wheel was rotated to the left.
1250 * When scroll axis is VERTICAL
1251 * - If the high word of the dwButtonState member contains a positive value,
1252 * the wheel was rotated forward, away from the user.
1253 * - Otherwise, the wheel was rotated backward, toward the user.
1254 */
1255 static void
1256decode_mouse_wheel(MOUSE_EVENT_RECORD *pmer)
1257{
1258 win_T *wp;
1259 int horizontal = (pmer->dwEventFlags == MOUSE_HWHEELED);
1260 int zDelta = pmer->dwButtonState;
1261
1262 g_xMouse = pmer->dwMousePosition.X;
1263 g_yMouse = pmer->dwMousePosition.Y;
1264
1265#ifdef FEAT_PROP_POPUP
Christopher Plewright605d02a2022-10-19 11:54:46 +01001266 int lcol = g_xMouse;
1267 int lrow = g_yMouse;
Christopher Plewright4c366782022-10-20 13:11:15 +01001268 wp = mouse_find_win(&lrow, &lcol, FIND_POPUP);
Christopher Plewright2a46f812022-10-16 19:47:45 +01001269 if (wp != NULL && popup_is_popup(wp))
1270 {
1271 g_nMouseClick = -1;
1272 cmdarg_T cap;
1273 oparg_T oa;
1274 CLEAR_FIELD(cap);
1275 clear_oparg(&oa);
1276 cap.oap = &oa;
1277 if (horizontal)
1278 {
1279 cap.arg = zDelta < 0 ? MSCR_LEFT : MSCR_RIGHT;
1280 cap.cmdchar = zDelta < 0 ? K_MOUSELEFT : K_MOUSERIGHT;
1281 }
1282 else
1283 {
1284 cap.cmdchar = zDelta < 0 ? K_MOUSEUP : K_MOUSEDOWN;
1285 cap.arg = zDelta < 0 ? MSCR_UP : MSCR_DOWN;
1286 }
1287
1288 // Mouse hovers over popup window, scroll it if possible.
1289 mouse_row = wp->w_winrow;
1290 mouse_col = wp->w_wincol;
1291 nv_mousescroll(&cap);
1292 update_screen(0);
1293 setcursor();
1294 out_flush();
1295 return;
1296 }
1297#endif
1298 mouse_col = g_xMouse;
1299 mouse_row = g_yMouse;
1300
1301 char_u modifiers = 0;
1302 char_u direction = 0;
1303
1304 // Decode the direction into an event that Vim can process
1305 if (horizontal)
1306 direction = zDelta >= 0 ? KE_MOUSELEFT : KE_MOUSERIGHT;
1307 else
1308 direction = zDelta >= 0 ? KE_MOUSEDOWN : KE_MOUSEUP;
1309
1310 // Decode the win32 console key modifers into Vim mouse modifers.
1311 if (pmer->dwControlKeyState & SHIFT_PRESSED)
Christopher Plewright605d02a2022-10-19 11:54:46 +01001312 modifiers |= MOD_MASK_SHIFT; // MOUSE_SHIFT;
Christopher Plewright2a46f812022-10-16 19:47:45 +01001313 if (pmer->dwControlKeyState & (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED))
Christopher Plewright605d02a2022-10-19 11:54:46 +01001314 modifiers |= MOD_MASK_CTRL; // MOUSE_CTRL;
Christopher Plewright2a46f812022-10-16 19:47:45 +01001315 if (pmer->dwControlKeyState & (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED))
1316 modifiers |= MOD_MASK_ALT; // MOUSE_ALT;
1317
1318 // add (bitwise or) the scroll direction and the key modifier chars
1319 // together.
1320 g_nMouseClick = ((direction << 8) | modifiers);
1321
1322 return;
1323}
1324
Bram Moolenaar071d4272004-06-13 20:20:40 +00001325/*
1326 * Decode a MOUSE_EVENT. If it's a valid event, return MOUSE_LEFT,
1327 * MOUSE_MIDDLE, or MOUSE_RIGHT for a click; MOUSE_DRAG for a mouse
1328 * move with a button held down; and MOUSE_RELEASE after a MOUSE_DRAG
1329 * or a MOUSE_LEFT, _MIDDLE, or _RIGHT. We encode the button type,
1330 * the number of clicks, and the Shift/Ctrl/Alt modifiers in g_nMouseClick,
1331 * and we return the mouse position in g_xMouse and g_yMouse.
1332 *
1333 * Every MOUSE_LEFT, _MIDDLE, or _RIGHT will be followed by zero or more
1334 * MOUSE_DRAGs and one MOUSE_RELEASE. MOUSE_RELEASE will be followed only
1335 * by MOUSE_LEFT, _MIDDLE, or _RIGHT.
1336 *
1337 * For multiple clicks, we send, say, MOUSE_LEFT/1 click, MOUSE_RELEASE,
1338 * MOUSE_LEFT/2 clicks, MOUSE_RELEASE, MOUSE_LEFT/3 clicks, MOUSE_RELEASE, ....
1339 *
1340 * Windows will send us MOUSE_MOVED notifications whenever the mouse
1341 * moves, even if it stays within the same character cell. We ignore
1342 * all MOUSE_MOVED messages if the position hasn't really changed, and
1343 * we ignore all MOUSE_MOVED messages where no button is held down (i.e.,
1344 * we're only interested in MOUSE_DRAG).
1345 *
1346 * All of this is complicated by the code that fakes MOUSE_MIDDLE on
1347 * 2-button mouses by pressing the left & right buttons simultaneously.
1348 * In practice, it's almost impossible to click both at the same time,
1349 * so we need to delay a little. Also, we tend not to get MOUSE_RELEASE
1350 * in such cases, if the user is clicking quickly.
1351 */
1352 static BOOL
1353decode_mouse_event(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001354 MOUSE_EVENT_RECORD *pmer)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001355{
1356 static int s_nOldButton = -1;
1357 static int s_nOldMouseClick = -1;
1358 static int s_xOldMouse = -1;
1359 static int s_yOldMouse = -1;
1360 static linenr_T s_old_topline = 0;
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001361# ifdef FEAT_DIFF
Bram Moolenaar071d4272004-06-13 20:20:40 +00001362 static int s_old_topfill = 0;
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001363# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001364 static int s_cClicks = 1;
1365 static BOOL s_fReleased = TRUE;
1366 static DWORD s_dwLastClickTime = 0;
1367 static BOOL s_fNextIsMiddle = FALSE;
1368
Bram Moolenaar0f873732019-12-05 20:28:46 +01001369 static DWORD cButtons = 0; // number of buttons supported
Bram Moolenaar071d4272004-06-13 20:20:40 +00001370
1371 const DWORD LEFT = FROM_LEFT_1ST_BUTTON_PRESSED;
1372 const DWORD MIDDLE = FROM_LEFT_2ND_BUTTON_PRESSED;
1373 const DWORD RIGHT = RIGHTMOST_BUTTON_PRESSED;
1374 const DWORD LEFT_RIGHT = LEFT | RIGHT;
1375
1376 int nButton;
1377
1378 if (cButtons == 0 && !GetNumberOfConsoleMouseButtons(&cButtons))
1379 cButtons = 2;
1380
1381 if (!g_fMouseAvail || !g_fMouseActive)
1382 {
1383 g_nMouseClick = -1;
1384 return FALSE;
1385 }
1386
Bram Moolenaar0f873732019-12-05 20:28:46 +01001387 // get a spurious MOUSE_EVENT immediately after receiving focus; ignore
Bram Moolenaar071d4272004-06-13 20:20:40 +00001388 if (g_fJustGotFocus)
1389 {
1390 g_fJustGotFocus = FALSE;
1391 return FALSE;
1392 }
1393
Christopher Plewright605d02a2022-10-19 11:54:46 +01001394 // If there is an unprocessed mouse click drop this one.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001395 if (g_nMouseClick != -1)
1396 return TRUE;
Christopher Plewright605d02a2022-10-19 11:54:46 +01001397
Christopher Plewright2a46f812022-10-16 19:47:45 +01001398 if (pmer->dwEventFlags == MOUSE_WHEELED
1399 || pmer->dwEventFlags == MOUSE_HWHEELED)
1400 {
1401 decode_mouse_wheel(pmer);
1402 return TRUE; // we now should have a mouse scroll in g_nMouseClick
1403 }
Christopher Plewright605d02a2022-10-19 11:54:46 +01001404
Bram Moolenaar071d4272004-06-13 20:20:40 +00001405 nButton = -1;
1406 g_xMouse = pmer->dwMousePosition.X;
1407 g_yMouse = pmer->dwMousePosition.Y;
1408
1409 if (pmer->dwEventFlags == MOUSE_MOVED)
1410 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001411 // Ignore MOUSE_MOVED events if (x, y) hasn't changed. (We get these
1412 // events even when the mouse moves only within a char cell.)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001413 if (s_xOldMouse == g_xMouse && s_yOldMouse == g_yMouse)
1414 return FALSE;
1415 }
1416
Bram Moolenaar0f873732019-12-05 20:28:46 +01001417 // If no buttons are pressed...
Bram Moolenaar071d4272004-06-13 20:20:40 +00001418 if ((pmer->dwButtonState & ((1 << cButtons) - 1)) == 0)
1419 {
Bram Moolenaar157d8132018-03-06 17:09:20 +01001420 nButton = MOUSE_RELEASE;
1421
Bram Moolenaar0f873732019-12-05 20:28:46 +01001422 // If the last thing returned was MOUSE_RELEASE, ignore this
Bram Moolenaar071d4272004-06-13 20:20:40 +00001423 if (s_fReleased)
Bram Moolenaar157d8132018-03-06 17:09:20 +01001424 {
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001425# ifdef FEAT_BEVAL_TERM
Bram Moolenaar0f873732019-12-05 20:28:46 +01001426 // do return mouse move events when we want them
Bram Moolenaar157d8132018-03-06 17:09:20 +01001427 if (p_bevalterm)
1428 nButton = MOUSE_DRAG;
1429 else
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001430# endif
Bram Moolenaar157d8132018-03-06 17:09:20 +01001431 return FALSE;
1432 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001433
Bram Moolenaar071d4272004-06-13 20:20:40 +00001434 s_fReleased = TRUE;
1435 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01001436 else // one or more buttons pressed
Bram Moolenaar071d4272004-06-13 20:20:40 +00001437 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001438 // on a 2-button mouse, hold down left and right buttons
1439 // simultaneously to get MIDDLE.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001440
1441 if (cButtons == 2 && s_nOldButton != MOUSE_DRAG)
1442 {
1443 DWORD dwLR = (pmer->dwButtonState & LEFT_RIGHT);
1444
Bram Moolenaar0f873732019-12-05 20:28:46 +01001445 // if either left or right button only is pressed, see if the
1446 // next mouse event has both of them pressed
Bram Moolenaar071d4272004-06-13 20:20:40 +00001447 if (dwLR == LEFT || dwLR == RIGHT)
1448 {
1449 for (;;)
1450 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001451 // wait a short time for next input event
Bram Moolenaar071d4272004-06-13 20:20:40 +00001452 if (WaitForSingleObject(g_hConIn, p_mouset / 3)
1453 != WAIT_OBJECT_0)
1454 break;
1455 else
1456 {
1457 DWORD cRecords = 0;
1458 INPUT_RECORD ir;
1459 MOUSE_EVENT_RECORD* pmer2 = &ir.Event.MouseEvent;
1460
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001461 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001462
1463 if (cRecords == 0 || ir.EventType != MOUSE_EVENT
1464 || !(pmer2->dwButtonState & LEFT_RIGHT))
1465 break;
1466 else
1467 {
1468 if (pmer2->dwEventFlags != MOUSE_MOVED)
1469 {
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001470 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001471
1472 return decode_mouse_event(pmer2);
1473 }
1474 else if (s_xOldMouse == pmer2->dwMousePosition.X &&
1475 s_yOldMouse == pmer2->dwMousePosition.Y)
1476 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001477 // throw away spurious mouse move
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001478 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001479
Bram Moolenaar0f873732019-12-05 20:28:46 +01001480 // are there any more mouse events in queue?
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001481 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001482
1483 if (cRecords==0 || ir.EventType != MOUSE_EVENT)
1484 break;
1485 }
1486 else
1487 break;
1488 }
1489 }
1490 }
1491 }
1492 }
1493
1494 if (s_fNextIsMiddle)
1495 {
1496 nButton = (pmer->dwEventFlags == MOUSE_MOVED)
1497 ? MOUSE_DRAG : MOUSE_MIDDLE;
1498 s_fNextIsMiddle = FALSE;
1499 }
1500 else if (cButtons == 2 &&
1501 ((pmer->dwButtonState & LEFT_RIGHT) == LEFT_RIGHT))
1502 {
1503 nButton = MOUSE_MIDDLE;
1504
1505 if (! s_fReleased && pmer->dwEventFlags != MOUSE_MOVED)
1506 {
1507 s_fNextIsMiddle = TRUE;
1508 nButton = MOUSE_RELEASE;
1509 }
1510 }
1511 else if ((pmer->dwButtonState & LEFT) == LEFT)
1512 nButton = MOUSE_LEFT;
1513 else if ((pmer->dwButtonState & MIDDLE) == MIDDLE)
1514 nButton = MOUSE_MIDDLE;
1515 else if ((pmer->dwButtonState & RIGHT) == RIGHT)
1516 nButton = MOUSE_RIGHT;
1517
1518 if (! s_fReleased && ! s_fNextIsMiddle
1519 && nButton != s_nOldButton && s_nOldButton != MOUSE_DRAG)
1520 return FALSE;
1521
1522 s_fReleased = s_fNextIsMiddle;
1523 }
1524
1525 if (pmer->dwEventFlags == 0 || pmer->dwEventFlags == DOUBLE_CLICK)
1526 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001527 // button pressed or released, without mouse moving
Bram Moolenaar071d4272004-06-13 20:20:40 +00001528 if (nButton != -1 && nButton != MOUSE_RELEASE)
1529 {
1530 DWORD dwCurrentTime = GetTickCount();
1531
1532 if (s_xOldMouse != g_xMouse
1533 || s_yOldMouse != g_yMouse
1534 || s_nOldButton != nButton
1535 || s_old_topline != curwin->w_topline
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001536# ifdef FEAT_DIFF
Bram Moolenaar071d4272004-06-13 20:20:40 +00001537 || s_old_topfill != curwin->w_topfill
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001538# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001539 || (int)(dwCurrentTime - s_dwLastClickTime) > p_mouset)
1540 {
1541 s_cClicks = 1;
1542 }
1543 else if (++s_cClicks > 4)
1544 {
1545 s_cClicks = 1;
1546 }
1547
1548 s_dwLastClickTime = dwCurrentTime;
1549 }
1550 }
1551 else if (pmer->dwEventFlags == MOUSE_MOVED)
1552 {
1553 if (nButton != -1 && nButton != MOUSE_RELEASE)
1554 nButton = MOUSE_DRAG;
1555
1556 s_cClicks = 1;
1557 }
1558
1559 if (nButton == -1)
1560 return FALSE;
1561
1562 if (nButton != MOUSE_RELEASE)
1563 s_nOldButton = nButton;
1564
1565 g_nMouseClick = nButton;
1566
1567 if (pmer->dwControlKeyState & SHIFT_PRESSED)
1568 g_nMouseClick |= MOUSE_SHIFT;
1569 if (pmer->dwControlKeyState & (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED))
1570 g_nMouseClick |= MOUSE_CTRL;
1571 if (pmer->dwControlKeyState & (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED))
1572 g_nMouseClick |= MOUSE_ALT;
1573
1574 if (nButton != MOUSE_DRAG && nButton != MOUSE_RELEASE)
1575 SET_NUM_MOUSE_CLICKS(g_nMouseClick, s_cClicks);
1576
Bram Moolenaar0f873732019-12-05 20:28:46 +01001577 // only pass on interesting (i.e., different) mouse events
Bram Moolenaar071d4272004-06-13 20:20:40 +00001578 if (s_xOldMouse == g_xMouse
1579 && s_yOldMouse == g_yMouse
1580 && s_nOldMouseClick == g_nMouseClick)
1581 {
1582 g_nMouseClick = -1;
1583 return FALSE;
1584 }
1585
1586 s_xOldMouse = g_xMouse;
1587 s_yOldMouse = g_yMouse;
1588 s_old_topline = curwin->w_topline;
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001589# ifdef FEAT_DIFF
Bram Moolenaar071d4272004-06-13 20:20:40 +00001590 s_old_topfill = curwin->w_topfill;
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001591# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001592 s_nOldMouseClick = g_nMouseClick;
1593
1594 return TRUE;
1595}
1596
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001597#endif // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00001598
1599
1600#ifdef MCH_CURSOR_SHAPE
1601/*
1602 * Set the shape of the cursor.
1603 * 'thickness' can be from 1 (thin) to 99 (block)
1604 */
1605 static void
1606mch_set_cursor_shape(int thickness)
1607{
K.Takatadf5320c2022-09-01 13:20:16 +01001608 if (USE_VTP || USE_WT)
1609 {
1610 if (*T_CSI == NUL)
1611 {
1612 // If 't_SI' is not set, use the default cursor styles.
1613 if (thickness < 50)
1614 vtp_printf("\033[3 q"); // underline
1615 else
1616 vtp_printf("\033[0 q"); // default
1617 }
1618 }
1619 else
1620 {
1621 CONSOLE_CURSOR_INFO ConsoleCursorInfo;
1622 ConsoleCursorInfo.dwSize = thickness;
1623 ConsoleCursorInfo.bVisible = s_cursor_visible;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001624
K.Takatadf5320c2022-09-01 13:20:16 +01001625 SetConsoleCursorInfo(g_hConOut, &ConsoleCursorInfo);
1626 if (s_cursor_visible)
1627 SetConsoleCursorPosition(g_hConOut, g_coord);
1628 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001629}
1630
1631 void
1632mch_update_cursor(void)
1633{
1634 int idx;
1635 int thickness;
1636
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001637# ifdef VIMDLL
1638 if (gui.in_use)
1639 return;
1640# endif
1641
Bram Moolenaar071d4272004-06-13 20:20:40 +00001642 /*
1643 * How the cursor is drawn depends on the current mode.
1644 */
1645 idx = get_shape_idx(FALSE);
1646
1647 if (shape_table[idx].shape == SHAPE_BLOCK)
Bram Moolenaar0f873732019-12-05 20:28:46 +01001648 thickness = 99; // 100 doesn't work on W95
Bram Moolenaar071d4272004-06-13 20:20:40 +00001649 else
1650 thickness = shape_table[idx].percentage;
1651 mch_set_cursor_shape(thickness);
1652}
1653#endif
1654
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001655#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001656/*
1657 * Handle FOCUS_EVENT.
1658 */
1659 static void
1660handle_focus_event(INPUT_RECORD ir)
1661{
1662 g_fJustGotFocus = ir.Event.FocusEvent.bSetFocus;
1663 ui_focus_change((int)g_fJustGotFocus);
1664}
1665
Bram Moolenaar78d21da2019-02-17 15:00:52 +01001666static void ResizeConBuf(HANDLE hConsole, COORD coordScreen);
1667
Bram Moolenaar071d4272004-06-13 20:20:40 +00001668/*
1669 * Wait until console input from keyboard or mouse is available,
1670 * or the time is up.
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001671 * When "ignore_input" is TRUE even wait when input is available.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001672 * Return TRUE if something is available FALSE if not.
1673 */
1674 static int
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001675WaitForChar(long msec, int ignore_input)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001676{
1677 DWORD dwNow = 0, dwEndTime = 0;
1678 INPUT_RECORD ir;
1679 DWORD cRecords;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001680 WCHAR ch, ch2;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001681# ifdef FEAT_TIMERS
Bram Moolenaar40b1b542016-04-20 20:18:23 +02001682 int tb_change_cnt = typebuf.tb_change_cnt;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001683# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001684
1685 if (msec > 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01001686 // Wait until the specified time has elapsed.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001687 dwEndTime = GetTickCount() + msec;
1688 else if (msec < 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01001689 // Wait forever.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001690 dwEndTime = INFINITE;
1691
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01001692 // We need to loop until the end of the time period, because
1693 // we might get multiple unusable mouse events in that time.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001694 for (;;)
1695 {
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001696 // Only process messages when waiting.
1697 if (msec != 0)
1698 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001699# ifdef MESSAGE_QUEUE
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001700 parse_queued_messages();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001701# endif
1702# ifdef FEAT_MZSCHEME
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001703 mzvim_check_threads();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001704# endif
1705# ifdef FEAT_CLIENTSERVER
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001706 serverProcessPendingMessages();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001707# endif
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001708 }
Bram Moolenaarf12d9832016-01-29 21:11:25 +01001709
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001710 if (g_nMouseClick != -1
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001711# ifdef FEAT_CLIENTSERVER
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001712 || (!ignore_input && input_available())
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001713# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001714 )
1715 return TRUE;
1716
1717 if (msec > 0)
1718 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001719 // If the specified wait time has passed, return. Beware that
1720 // GetTickCount() may wrap around (overflow).
Bram Moolenaar071d4272004-06-13 20:20:40 +00001721 dwNow = GetTickCount();
Bram Moolenaarb7512b72013-08-10 12:45:09 +02001722 if ((int)(dwNow - dwEndTime) >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001723 break;
1724 }
1725 if (msec != 0)
1726 {
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001727 DWORD dwWaitTime = dwEndTime - dwNow;
1728
Bram Moolenaarc478ee32020-12-01 21:27:51 +01001729 // Don't wait for more than 11 msec to avoid dropping characters,
1730 // check channel while waiting for input and handle a callback from
1731 // 'balloonexpr'.
1732 if (dwWaitTime > 11)
1733 dwWaitTime = 11;
1734
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001735# ifdef FEAT_MZSCHEME
Bram Moolenaarc478ee32020-12-01 21:27:51 +01001736 if (mzthreads_allowed() && p_mzq > 0 && (long)dwWaitTime > p_mzq)
Bram Moolenaar0f873732019-12-05 20:28:46 +01001737 dwWaitTime = p_mzq; // don't wait longer than 'mzquantum'
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001738# endif
1739# ifdef FEAT_TIMERS
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001740 // When waiting very briefly don't trigger timers.
1741 if (dwWaitTime > 10)
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001742 {
1743 long due_time;
1744
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001745 // Trigger timers and then get the time in msec until the next
1746 // one is due. Wait up to that time.
1747 due_time = check_due_timer();
1748 if (typebuf.tb_change_cnt != tb_change_cnt)
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001749 {
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001750 // timer may have used feedkeys().
1751 return FALSE;
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001752 }
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001753 if (due_time > 0 && dwWaitTime > (DWORD)due_time)
1754 dwWaitTime = due_time;
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001755 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001756# endif
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001757 if (
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001758# ifdef FEAT_CLIENTSERVER
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001759 // Wait for either an event on the console input or a
1760 // message in the client-server window.
1761 msg_wait_for_multiple_objects(1, &g_hConIn, FALSE,
1762 dwWaitTime, QS_SENDMESSAGE) != WAIT_OBJECT_0
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001763# else
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001764 wait_for_single_object(g_hConIn, dwWaitTime)
1765 != WAIT_OBJECT_0
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001766# endif
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001767 )
1768 continue;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001769 }
1770
1771 cRecords = 0;
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001772 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001773
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001774# ifdef FEAT_MBYTE_IME
matveyt4eb19142021-05-20 11:54:10 +02001775 // May have to redraw if the cursor ends up in the wrong place.
1776 // Only when not peeking.
Bram Moolenaar24959102022-05-07 20:01:16 +01001777 if (State == MODE_CMDLINE && msg_row == Rows - 1 && msec != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001778 {
1779 CONSOLE_SCREEN_BUFFER_INFO csbi;
1780
1781 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
1782 {
1783 if (csbi.dwCursorPosition.Y != msg_row)
1784 {
matveyte08795e2021-05-07 15:00:17 +02001785 // The screen is now messed up, must redraw the command
1786 // line and later all the windows.
Bram Moolenaara4d158b2022-08-14 14:17:45 +01001787 redraw_all_later(UPD_CLEAR);
matveyte08795e2021-05-07 15:00:17 +02001788 compute_cmdrow();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001789 redrawcmd();
1790 }
1791 }
1792 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001793# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001794
1795 if (cRecords > 0)
1796 {
1797 if (ir.EventType == KEY_EVENT && ir.Event.KeyEvent.bKeyDown)
1798 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001799# ifdef FEAT_MBYTE_IME
Bram Moolenaar0f873732019-12-05 20:28:46 +01001800 // Windows IME sends two '\n's with only one 'ENTER'. First:
1801 // wVirtualKeyCode == 13. second: wVirtualKeyCode == 0
K.Takata972db232022-02-04 10:45:38 +00001802 if (ir.Event.KeyEvent.uChar.UnicodeChar == 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00001803 && ir.Event.KeyEvent.wVirtualKeyCode == 13)
1804 {
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001805 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001806 continue;
1807 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001808# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001809 if (decode_key_event(&ir.Event.KeyEvent, &ch, &ch2,
1810 NULL, FALSE))
1811 return TRUE;
1812 }
1813
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001814 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001815
1816 if (ir.EventType == FOCUS_EVENT)
1817 handle_focus_event(ir);
1818 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
Bram Moolenaarc33ecb22018-02-11 16:40:45 +01001819 {
Bram Moolenaar78d21da2019-02-17 15:00:52 +01001820 COORD dwSize = ir.Event.WindowBufferSizeEvent.dwSize;
1821
Bram Moolenaar36698e32019-12-11 22:57:40 +01001822 // Only call shell_resized() when the size actually changed to
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001823 // avoid the screen is cleared.
Bram Moolenaar78d21da2019-02-17 15:00:52 +01001824 if (dwSize.X != Columns || dwSize.Y != Rows)
1825 {
1826 CONSOLE_SCREEN_BUFFER_INFO csbi;
1827 GetConsoleScreenBufferInfo(g_hConOut, &csbi);
Bram Moolenaar36698e32019-12-11 22:57:40 +01001828 dwSize.X = csbi.srWindow.Right - csbi.srWindow.Left + 1;
Bram Moolenaar78d21da2019-02-17 15:00:52 +01001829 dwSize.Y = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
Bram Moolenaar36698e32019-12-11 22:57:40 +01001830 if (dwSize.X != Columns || dwSize.Y != Rows)
1831 {
1832 ResizeConBuf(g_hConOut, dwSize);
1833 shell_resized();
1834 }
Bram Moolenaar78d21da2019-02-17 15:00:52 +01001835 }
Bram Moolenaarc33ecb22018-02-11 16:40:45 +01001836 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001837 else if (ir.EventType == MOUSE_EVENT
1838 && decode_mouse_event(&ir.Event.MouseEvent))
1839 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001840 }
1841 else if (msec == 0)
1842 break;
1843 }
1844
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001845# ifdef FEAT_CLIENTSERVER
Bram Moolenaar0f873732019-12-05 20:28:46 +01001846 // Something might have been received while we were waiting.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001847 if (input_available())
1848 return TRUE;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001849# endif
Bram Moolenaarf12d9832016-01-29 21:11:25 +01001850
Bram Moolenaar071d4272004-06-13 20:20:40 +00001851 return FALSE;
1852}
1853
Bram Moolenaar071d4272004-06-13 20:20:40 +00001854/*
1855 * return non-zero if a character is available
1856 */
1857 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001858mch_char_avail(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001859{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001860# ifdef VIMDLL
1861 if (gui.in_use)
1862 return TRUE;
1863# endif
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001864 return WaitForChar(0L, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001865}
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001866
1867# if defined(FEAT_TERMINAL) || defined(PROTO)
1868/*
1869 * Check for any pending input or messages.
1870 */
1871 int
1872mch_check_messages(void)
1873{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001874# ifdef VIMDLL
1875 if (gui.in_use)
1876 return TRUE;
1877# endif
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001878 return WaitForChar(0L, TRUE);
1879}
1880# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001881
1882/*
1883 * Create the console input. Used when reading stdin doesn't work.
1884 */
1885 static void
1886create_conin(void)
1887{
1888 g_hConIn = CreateFile("CONIN$", GENERIC_READ|GENERIC_WRITE,
1889 FILE_SHARE_READ|FILE_SHARE_WRITE,
1890 (LPSECURITY_ATTRIBUTES) NULL,
Bram Moolenaareb3593b2006-04-22 22:33:57 +00001891 OPEN_EXISTING, 0, (HANDLE)NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001892 did_create_conin = TRUE;
1893}
1894
1895/*
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001896 * Get a keystroke or a mouse event, use a blocking wait.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001897 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001898 static WCHAR
1899tgetch(int *pmodifiers, WCHAR *pch2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001900{
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001901 WCHAR ch;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001902
1903 for (;;)
1904 {
1905 INPUT_RECORD ir;
1906 DWORD cRecords = 0;
1907
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001908# ifdef FEAT_CLIENTSERVER
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001909 (void)WaitForChar(-1L, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001910 if (input_available())
1911 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001912 if (g_nMouseClick != -1)
1913 return 0;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001914# endif
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001915 if (read_console_input(g_hConIn, &ir, 1, &cRecords) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001916 {
1917 if (did_create_conin)
1918 read_error_exit();
1919 create_conin();
1920 continue;
1921 }
1922
1923 if (ir.EventType == KEY_EVENT)
1924 {
1925 if (decode_key_event(&ir.Event.KeyEvent, &ch, pch2,
1926 pmodifiers, TRUE))
1927 return ch;
1928 }
1929 else if (ir.EventType == FOCUS_EVENT)
1930 handle_focus_event(ir);
1931 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
1932 shell_resized();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001933 else if (ir.EventType == MOUSE_EVENT)
1934 {
1935 if (decode_mouse_event(&ir.Event.MouseEvent))
1936 return 0;
1937 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001938 }
1939}
Bram Moolenaar0f873732019-12-05 20:28:46 +01001940#endif // !FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00001941
1942
1943/*
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02001944 * mch_inchar(): low-level input function.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001945 * Get one or more characters from the keyboard or the mouse.
1946 * If time == 0, do not wait for characters.
1947 * If time == n, wait a short time for characters.
1948 * If time == -1, wait forever for characters.
1949 * Returns the number of characters read into buf.
1950 */
1951 int
1952mch_inchar(
Bram Moolenaar1266d672017-02-01 13:43:36 +01001953 char_u *buf UNUSED,
1954 int maxlen UNUSED,
1955 long time UNUSED,
1956 int tb_change_cnt UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001957{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001958#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001959
1960 int len;
1961 int c;
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01001962# ifdef VIMDLL
1963// Extra space for maximum three CSIs. E.g. U+1B6DB -> 0xF0 0x9B 0x9B 0x9B.
1964# define TYPEAHEADSPACE 6
1965# else
1966# define TYPEAHEADSPACE 0
1967# endif
1968# define TYPEAHEADLEN (20 + TYPEAHEADSPACE)
Bram Moolenaar0f873732019-12-05 20:28:46 +01001969 static char_u typeahead[TYPEAHEADLEN]; // previously typed bytes.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001970 static int typeaheadlen = 0;
1971
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001972# ifdef VIMDLL
1973 if (gui.in_use)
1974 return 0;
1975# endif
1976
Bram Moolenaar0f873732019-12-05 20:28:46 +01001977 // First use any typeahead that was kept because "buf" was too small.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001978 if (typeaheadlen > 0)
1979 goto theend;
1980
Bram Moolenaar071d4272004-06-13 20:20:40 +00001981 if (time >= 0)
1982 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001983 if (!WaitForChar(time, FALSE)) // no character available
Bram Moolenaar071d4272004-06-13 20:20:40 +00001984 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001985 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01001986 else // time == -1, wait forever
Bram Moolenaar071d4272004-06-13 20:20:40 +00001987 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001988 mch_set_winsize_now(); // Allow winsize changes from now on
Bram Moolenaar071d4272004-06-13 20:20:40 +00001989
Bram Moolenaar3918c952005-03-15 22:34:55 +00001990 /*
1991 * If there is no character available within 2 seconds (default)
1992 * write the autoscript file to disk. Or cause the CursorHold event
1993 * to be triggered.
1994 */
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001995 if (!WaitForChar(p_ut, FALSE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001996 {
Bram Moolenaard35f9712005-12-18 22:02:33 +00001997 if (trigger_cursorhold() && maxlen >= 3)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001998 {
Bram Moolenaar3918c952005-03-15 22:34:55 +00001999 buf[0] = K_SPECIAL;
2000 buf[1] = KS_EXTRA;
2001 buf[2] = (int)KE_CURSORHOLD;
2002 return 3;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002003 }
Bram Moolenaar702517d2005-06-27 22:34:07 +00002004 before_blocking();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002005 }
2006 }
2007
2008 /*
2009 * Try to read as many characters as there are, until the buffer is full.
2010 */
2011
Bram Moolenaar0f873732019-12-05 20:28:46 +01002012 // we will get at least one key. Get more if they are available.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002013 g_fCBrkPressed = FALSE;
2014
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002015# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00002016 if (fdDump)
2017 fputc('[', fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002018# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002019
Bram Moolenaar0f873732019-12-05 20:28:46 +01002020 // Keep looping until there is something in the typeahead buffer and more
2021 // to get and still room in the buffer (up to two bytes for a char and
2022 // three bytes for a modifier).
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02002023 while ((typeaheadlen == 0 || WaitForChar(0L, FALSE))
Bram Moolenaar9f1983d2022-05-12 20:35:35 +01002024 && typeaheadlen + 5 + TYPEAHEADSPACE <= TYPEAHEADLEN)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002025 {
2026 if (typebuf_changed(tb_change_cnt))
2027 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01002028 // "buf" may be invalid now if a client put something in the
2029 // typeahead buffer and "buf" is in the typeahead buffer.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002030 typeaheadlen = 0;
2031 break;
2032 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002033 if (g_nMouseClick != -1)
2034 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002035# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00002036 if (fdDump)
2037 fprintf(fdDump, "{%02x @ %d, %d}",
2038 g_nMouseClick, g_xMouse, g_yMouse);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002039# endif
Christopher Plewright2a46f812022-10-16 19:47:45 +01002040 char_u modifiers = ((char_u *)(&g_nMouseClick))[0];
2041 char_u scroll_dir = ((char_u *)(&g_nMouseClick))[1];
2042
2043 if (scroll_dir == KE_MOUSEDOWN
2044 || scroll_dir == KE_MOUSEUP
2045 || scroll_dir == KE_MOUSELEFT
2046 || scroll_dir == KE_MOUSERIGHT)
2047 {
2048 if (modifiers > 0)
2049 {
2050 typeahead[typeaheadlen++] = CSI;
2051 typeahead[typeaheadlen++] = KS_MODIFIER;
2052 typeahead[typeaheadlen++] = modifiers;
2053 }
2054 typeahead[typeaheadlen++] = CSI;
2055 typeahead[typeaheadlen++] = KS_EXTRA;
2056 typeahead[typeaheadlen++] = scroll_dir;
2057 g_nMouseClick = -1;
2058 }
2059 else
2060 {
2061 typeahead[typeaheadlen++] = ESC + 128;
2062 typeahead[typeaheadlen++] = 'M';
2063 typeahead[typeaheadlen++] = g_nMouseClick;
2064 typeahead[typeaheadlen++] = g_xMouse + '!';
2065 typeahead[typeaheadlen++] = g_yMouse + '!';
2066 g_nMouseClick = -1;
2067 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002068 }
2069 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00002070 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002071 WCHAR ch2 = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002072 int modifiers = 0;
2073
2074 c = tgetch(&modifiers, &ch2);
2075
2076 if (typebuf_changed(tb_change_cnt))
2077 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01002078 // "buf" may be invalid now if a client put something in the
2079 // typeahead buffer and "buf" is in the typeahead buffer.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002080 typeaheadlen = 0;
2081 break;
2082 }
2083
2084 if (c == Ctrl_C && ctrl_c_interrupts)
2085 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002086# if defined(FEAT_CLIENTSERVER)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002087 trash_input_buf();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002088# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002089 got_int = TRUE;
2090 }
2091
Bram Moolenaar071d4272004-06-13 20:20:40 +00002092 if (g_nMouseClick == -1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002093 {
2094 int n = 1;
2095
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002096 if (ch2 == NUL)
2097 {
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01002098 int i, j;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002099 char_u *p;
2100 WCHAR ch[2];
2101
2102 ch[0] = c;
Bram Moolenaar0f873732019-12-05 20:28:46 +01002103 if (c >= 0xD800 && c <= 0xDBFF) // High surrogate
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002104 {
2105 ch[1] = tgetch(&modifiers, &ch2);
2106 n++;
2107 }
2108 p = utf16_to_enc(ch, &n);
2109 if (p != NULL)
2110 {
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01002111 for (i = 0, j = 0; i < n; i++)
2112 {
2113 typeahead[typeaheadlen + j++] = p[i];
2114# ifdef VIMDLL
2115 if (p[i] == CSI)
2116 {
2117 typeahead[typeaheadlen + j++] = KS_EXTRA;
2118 typeahead[typeaheadlen + j++] = KE_CSI;
2119 }
2120# endif
2121 }
2122 n = j;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002123 vim_free(p);
2124 }
2125 }
2126 else
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01002127 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002128 typeahead[typeaheadlen] = c;
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01002129# ifdef VIMDLL
2130 if (c == CSI)
2131 {
2132 typeahead[typeaheadlen + 1] = KS_EXTRA;
2133 typeahead[typeaheadlen + 2] = KE_CSI;
2134 n = 3;
2135 }
2136# endif
2137 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002138 if (ch2 != NUL)
2139 {
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +02002140 if (c == K_NUL)
Bram Moolenaarfeeb4d02017-12-05 15:14:46 +01002141 {
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +02002142 switch (ch2)
2143 {
2144 case (WCHAR)'\324': // SHIFT+Insert
2145 case (WCHAR)'\325': // CTRL+Insert
2146 case (WCHAR)'\327': // SHIFT+Delete
2147 case (WCHAR)'\330': // CTRL+Delete
2148 typeahead[typeaheadlen + n] = (char_u)ch2;
2149 n++;
2150 break;
2151
2152 default:
2153 typeahead[typeaheadlen + n] = 3;
2154 typeahead[typeaheadlen + n + 1] = (char_u)ch2;
2155 n += 2;
2156 break;
2157 }
Bram Moolenaarfeeb4d02017-12-05 15:14:46 +01002158 }
2159 else
2160 {
2161 typeahead[typeaheadlen + n] = 3;
2162 typeahead[typeaheadlen + n + 1] = (char_u)ch2;
2163 n += 2;
2164 }
Bram Moolenaar45500912014-07-09 20:51:07 +02002165 }
2166
Bram Moolenaar0f873732019-12-05 20:28:46 +01002167 // Use the ALT key to set the 8th bit of the character
2168 // when it's one byte, the 8th bit isn't set yet and not
2169 // using a double-byte encoding (would become a lead
2170 // byte).
Bram Moolenaar071d4272004-06-13 20:20:40 +00002171 if ((modifiers & MOD_MASK_ALT)
2172 && n == 1
2173 && (typeahead[typeaheadlen] & 0x80) == 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00002174 && !enc_dbcs
Bram Moolenaar071d4272004-06-13 20:20:40 +00002175 )
2176 {
Bram Moolenaar85a3e5c2007-11-20 16:22:16 +00002177 n = (*mb_char2bytes)(typeahead[typeaheadlen] | 0x80,
2178 typeahead + typeaheadlen);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002179 modifiers &= ~MOD_MASK_ALT;
2180 }
2181
2182 if (modifiers != 0)
2183 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01002184 // Prepend modifiers to the character.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002185 mch_memmove(typeahead + typeaheadlen + 3,
2186 typeahead + typeaheadlen, n);
2187 typeahead[typeaheadlen++] = K_SPECIAL;
2188 typeahead[typeaheadlen++] = (char_u)KS_MODIFIER;
2189 typeahead[typeaheadlen++] = modifiers;
2190 }
2191
2192 typeaheadlen += n;
2193
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002194# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00002195 if (fdDump)
2196 fputc(c, fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002197# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002198 }
2199 }
2200 }
2201
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002202# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00002203 if (fdDump)
2204 {
2205 fputs("]\n", fdDump);
2206 fflush(fdDump);
2207 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002208# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002209
Bram Moolenaar071d4272004-06-13 20:20:40 +00002210theend:
Bram Moolenaar0f873732019-12-05 20:28:46 +01002211 // Move typeahead to "buf", as much as fits.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002212 len = 0;
2213 while (len < maxlen && typeaheadlen > 0)
2214 {
2215 buf[len++] = typeahead[0];
2216 mch_memmove(typeahead, typeahead + 1, --typeaheadlen);
2217 }
K.Takata6e1d31e2022-02-03 13:05:32 +00002218# ifdef FEAT_JOB_CHANNEL
Bram Moolenaar7ca86fe2020-09-03 19:25:11 +02002219 if (len > 0)
2220 {
2221 buf[len] = NUL;
2222 ch_log(NULL, "raw key input: \"%s\"", buf);
2223 }
K.Takata6e1d31e2022-02-03 13:05:32 +00002224# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002225 return len;
2226
Bram Moolenaar0f873732019-12-05 20:28:46 +01002227#else // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00002228 return 0;
Bram Moolenaar0f873732019-12-05 20:28:46 +01002229#endif // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00002230}
2231
Bram Moolenaar82881492012-11-20 16:53:39 +01002232#ifndef PROTO
2233# ifndef __MINGW32__
Bram Moolenaar0f873732019-12-05 20:28:46 +01002234# include <shellapi.h> // required for FindExecutable()
Bram Moolenaar82881492012-11-20 16:53:39 +01002235# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002236#endif
2237
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002238/*
Bram Moolenaar95da1362020-05-30 18:37:55 +02002239 * Return TRUE if "name" is an executable file, FALSE if not or it doesn't exist.
Bram Moolenaar43663192017-03-05 14:29:12 +01002240 * When returning TRUE and "path" is not NULL save the path and set "*path" to
2241 * the allocated memory.
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00002242 * TODO: Should somehow check if it's really executable.
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002243 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002244 static int
Bram Moolenaar95da1362020-05-30 18:37:55 +02002245executable_file(char *name, char_u **path)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002246{
LemonBoy40fd7e62022-05-05 20:18:16 +01002247 int attrs = win32_getattrs((char_u *)name);
2248
2249 // The file doesn't exist or is a folder.
2250 if (attrs == -1 || (attrs & FILE_ATTRIBUTE_DIRECTORY))
2251 return FALSE;
2252 // Check if the file is an AppExecLink, a special alias used by Windows
2253 // Store for its apps.
2254 if (attrs & FILE_ATTRIBUTE_REPARSE_POINT)
Bram Moolenaar43663192017-03-05 14:29:12 +01002255 {
LemonBoy40fd7e62022-05-05 20:18:16 +01002256 char_u *res = resolve_appexeclink((char_u *)name);
2257 if (res == NULL)
2258 return FALSE;
2259 // The path is already absolute.
Bram Moolenaar95da1362020-05-30 18:37:55 +02002260 if (path != NULL)
LemonBoy40fd7e62022-05-05 20:18:16 +01002261 *path = res;
2262 else
2263 vim_free(res);
Bram Moolenaar95da1362020-05-30 18:37:55 +02002264 }
LemonBoy40fd7e62022-05-05 20:18:16 +01002265 else if (path != NULL)
2266 *path = FullName_save((char_u *)name, FALSE);
2267 return TRUE;
Bram Moolenaar95da1362020-05-30 18:37:55 +02002268}
2269
2270/*
2271 * If "use_path" is TRUE: Return TRUE if "name" is in $PATH.
2272 * If "use_path" is FALSE: Return TRUE if "name" exists.
2273 * If "use_pathext" is TRUE search "name" with extensions in $PATHEXT.
2274 * When returning TRUE and "path" is not NULL save the path and set "*path" to
2275 * the allocated memory.
2276 */
2277 static int
2278executable_exists(char *name, char_u **path, int use_path, int use_pathext)
2279{
2280 // WinNT and later can use _MAX_PATH wide characters for a pathname, which
2281 // means that the maximum pathname is _MAX_PATH * 3 bytes when 'enc' is
2282 // UTF-8.
2283 char_u buf[_MAX_PATH * 3];
2284 size_t len = STRLEN(name);
2285 size_t tmplen;
2286 char_u *p, *e, *e2;
2287 char_u *pathbuf = NULL;
2288 char_u *pathext = NULL;
2289 char_u *pathextbuf = NULL;
Mike Williamsa3d1b292021-06-30 20:56:00 +02002290 char_u *shname = NULL;
Bram Moolenaar95da1362020-05-30 18:37:55 +02002291 int noext = FALSE;
2292 int retval = FALSE;
2293
2294 if (len >= sizeof(buf)) // safety check
Bram Moolenaar43663192017-03-05 14:29:12 +01002295 return FALSE;
Bram Moolenaar95da1362020-05-30 18:37:55 +02002296
2297 // Using the name directly when a Unix-shell like 'shell'.
Mike Williamsa3d1b292021-06-30 20:56:00 +02002298 shname = gettail(p_sh);
2299 if (strstr((char *)shname, "sh") != NULL &&
2300 !(strstr((char *)shname, "powershell") != NULL
2301 || strstr((char *)shname, "pwsh") != NULL))
Bram Moolenaar95da1362020-05-30 18:37:55 +02002302 noext = TRUE;
2303
2304 if (use_pathext)
2305 {
2306 pathext = mch_getenv("PATHEXT");
2307 if (pathext == NULL)
2308 pathext = (char_u *)".com;.exe;.bat;.cmd";
2309
2310 if (noext == FALSE)
2311 {
2312 /*
2313 * Loop over all extensions in $PATHEXT.
2314 * Check "name" ends with extension.
2315 */
2316 p = pathext;
2317 while (*p)
2318 {
2319 if (p[0] == ';'
2320 || (p[0] == '.' && (p[1] == NUL || p[1] == ';')))
2321 {
2322 // Skip empty or single ".".
2323 ++p;
2324 continue;
2325 }
2326 e = vim_strchr(p, ';');
2327 if (e == NULL)
2328 e = p + STRLEN(p);
2329 tmplen = e - p;
2330
2331 if (_strnicoll(name + len - tmplen, (char *)p, tmplen) == 0)
2332 {
2333 noext = TRUE;
2334 break;
2335 }
2336
2337 p = e;
2338 }
2339 }
Bram Moolenaar43663192017-03-05 14:29:12 +01002340 }
2341
Dominique Pelleaf4a61a2021-12-27 17:21:41 +00002342 // Prepend single "." to pathext, it means no extension added.
Bram Moolenaar95da1362020-05-30 18:37:55 +02002343 if (pathext == NULL)
2344 pathext = (char_u *)".";
2345 else if (noext == TRUE)
2346 {
2347 if (pathextbuf == NULL)
2348 pathextbuf = alloc(STRLEN(pathext) + 3);
2349 if (pathextbuf == NULL)
2350 {
2351 retval = FALSE;
2352 goto theend;
2353 }
2354 STRCPY(pathextbuf, ".;");
2355 STRCAT(pathextbuf, pathext);
2356 pathext = pathextbuf;
2357 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002358
Bram Moolenaar95da1362020-05-30 18:37:55 +02002359 // Use $PATH when "use_path" is TRUE and "name" is basename.
2360 if (use_path && gettail((char_u *)name) == (char_u *)name)
2361 {
2362 p = mch_getenv("PATH");
2363 if (p != NULL)
2364 {
2365 pathbuf = alloc(STRLEN(p) + 3);
2366 if (pathbuf == NULL)
2367 {
2368 retval = FALSE;
2369 goto theend;
2370 }
Yasuhiro Matsumoto05cf63e2022-05-03 11:02:28 +01002371
2372 if (mch_getenv("NoDefaultCurrentDirectoryInExePath") == NULL)
2373 STRCPY(pathbuf, ".;");
2374 else
2375 *pathbuf = NUL;
Bram Moolenaar95da1362020-05-30 18:37:55 +02002376 STRCAT(pathbuf, p);
2377 }
2378 }
2379
2380 /*
2381 * Walk through all entries in $PATH to check if "name" exists there and
2382 * is an executable file.
2383 */
2384 p = (pathbuf != NULL) ? pathbuf : (char_u *)".";
2385 while (*p)
2386 {
2387 if (*p == ';') // Skip empty entry
2388 {
2389 ++p;
2390 continue;
2391 }
2392 e = vim_strchr(p, ';');
2393 if (e == NULL)
2394 e = p + STRLEN(p);
2395
2396 if (e - p + len + 2 > sizeof(buf))
2397 {
2398 retval = FALSE;
2399 goto theend;
2400 }
2401 // A single "." that means current dir.
2402 if (e - p == 1 && *p == '.')
2403 STRCPY(buf, name);
2404 else
2405 {
2406 vim_strncpy(buf, p, e - p);
2407 add_pathsep(buf);
2408 STRCAT(buf, name);
2409 }
2410 tmplen = STRLEN(buf);
2411
2412 /*
2413 * Loop over all extensions in $PATHEXT.
2414 * Check "name" with extension added.
2415 */
2416 p = pathext;
2417 while (*p)
2418 {
2419 if (*p == ';')
2420 {
2421 // Skip empty entry
2422 ++p;
2423 continue;
2424 }
2425 e2 = vim_strchr(p, (int)';');
2426 if (e2 == NULL)
2427 e2 = p + STRLEN(p);
2428
2429 if (!(p[0] == '.' && (p[1] == NUL || p[1] == ';')))
2430 {
2431 // Not a single "." that means no extension is added.
2432 if (e2 - p + tmplen + 1 > sizeof(buf))
2433 {
2434 retval = FALSE;
2435 goto theend;
2436 }
2437 vim_strncpy(buf + tmplen, p, e2 - p);
2438 }
2439 if (executable_file((char *)buf, path))
2440 {
2441 retval = TRUE;
2442 goto theend;
2443 }
2444
2445 p = e2;
2446 }
2447
2448 p = e;
2449 }
2450
2451theend:
2452 free(pathextbuf);
2453 free(pathbuf);
2454 return retval;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002455}
2456
Bram Moolenaar1eed5322019-02-26 17:03:54 +01002457#if (defined(__MINGW32__) && __MSVCRT_VERSION__ >= 0x800) || \
2458 (defined(_MSC_VER) && _MSC_VER >= 1400)
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002459/*
2460 * Bad parameter handler.
2461 *
2462 * Certain MS CRT functions will intentionally crash when passed invalid
2463 * parameters to highlight possible security holes. Setting this function as
2464 * the bad parameter handler will prevent the crash.
2465 *
2466 * In debug builds the parameters contain CRT information that might help track
2467 * down the source of a problem, but in non-debug builds the arguments are all
2468 * NULL/0. Debug builds will also produce assert dialogs from the CRT, it is
2469 * worth allowing these to make debugging of issues easier.
2470 */
2471 static void
Yegappan Lakshmanana34b4462022-06-11 10:43:26 +01002472bad_param_handler(const wchar_t *expression UNUSED,
2473 const wchar_t *function UNUSED,
2474 const wchar_t *file UNUSED,
2475 unsigned int line UNUSED,
2476 uintptr_t pReserved UNUSED)
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002477{
2478}
2479
2480# define SET_INVALID_PARAM_HANDLER \
2481 ((void)_set_invalid_parameter_handler(bad_param_handler))
2482#else
2483# define SET_INVALID_PARAM_HANDLER
2484#endif
2485
Bram Moolenaar4f974752019-02-17 17:44:42 +01002486#ifdef FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00002487
2488/*
2489 * GUI version of mch_init().
2490 */
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002491 static void
2492mch_init_g(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002493{
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002494# ifndef __MINGW32__
Bram Moolenaar071d4272004-06-13 20:20:40 +00002495 extern int _fmode;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002496# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002497
Bram Moolenaar0f873732019-12-05 20:28:46 +01002498 // Silently handle invalid parameters to CRT functions
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002499 SET_INVALID_PARAM_HANDLER;
2500
Bram Moolenaar0f873732019-12-05 20:28:46 +01002501 // Let critical errors result in a failure, not in a dialog box. Required
2502 // for the timestamp test to work on removed floppies.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002503 SetErrorMode(SEM_FAILCRITICALERRORS);
2504
Bram Moolenaar0f873732019-12-05 20:28:46 +01002505 _fmode = O_BINARY; // we do our own CR-LF translation
Bram Moolenaar071d4272004-06-13 20:20:40 +00002506
Bram Moolenaar0f873732019-12-05 20:28:46 +01002507 // Specify window size. Is there a place to get the default from?
Bram Moolenaar071d4272004-06-13 20:20:40 +00002508 Rows = 25;
2509 Columns = 80;
2510
Bram Moolenaar0f873732019-12-05 20:28:46 +01002511 // Look for 'vimrun'
Bram Moolenaar071d4272004-06-13 20:20:40 +00002512 {
2513 char_u vimrun_location[_MAX_PATH + 4];
2514
Bram Moolenaar0f873732019-12-05 20:28:46 +01002515 // First try in same directory as gvim.exe
Bram Moolenaar071d4272004-06-13 20:20:40 +00002516 STRCPY(vimrun_location, exe_name);
2517 STRCPY(gettail(vimrun_location), "vimrun.exe");
2518 if (mch_getperm(vimrun_location) >= 0)
2519 {
2520 if (*skiptowhite(vimrun_location) != NUL)
2521 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01002522 // Enclose path with white space in double quotes.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002523 mch_memmove(vimrun_location + 1, vimrun_location,
2524 STRLEN(vimrun_location) + 1);
2525 *vimrun_location = '"';
2526 STRCPY(gettail(vimrun_location), "vimrun\" ");
2527 }
2528 else
2529 STRCPY(gettail(vimrun_location), "vimrun ");
2530
2531 vimrun_path = (char *)vim_strsave(vimrun_location);
2532 s_dont_use_vimrun = FALSE;
2533 }
Bram Moolenaar95da1362020-05-30 18:37:55 +02002534 else if (executable_exists("vimrun.exe", NULL, TRUE, FALSE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002535 s_dont_use_vimrun = FALSE;
2536
Bram Moolenaar0f873732019-12-05 20:28:46 +01002537 // Don't give the warning for a missing vimrun.exe right now, but only
2538 // when vimrun was supposed to be used. Don't bother people that do
2539 // not need vimrun.exe.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002540 if (s_dont_use_vimrun)
2541 need_vimrun_warning = TRUE;
2542 }
2543
2544 /*
2545 * If "finstr.exe" doesn't exist, use "grep -n" for 'grepprg'.
2546 * Otherwise the default "findstr /n" is used.
2547 */
Bram Moolenaar95da1362020-05-30 18:37:55 +02002548 if (!executable_exists("findstr.exe", NULL, TRUE, FALSE))
Bram Moolenaar75ab5902022-04-18 15:36:40 +01002549 set_option_value_give_err((char_u *)"grepprg",
2550 0, (char_u *)"grep -n", 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002551
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002552# ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01002553 win_clip_init();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002554# endif
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01002555
2556 vtp_flag_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002557}
2558
2559
Bram Moolenaar0f873732019-12-05 20:28:46 +01002560#endif // FEAT_GUI_MSWIN
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002561
2562#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002563
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002564# define SRWIDTH(sr) ((sr).Right - (sr).Left + 1)
2565# define SRHEIGHT(sr) ((sr).Bottom - (sr).Top + 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002566
2567/*
2568 * ClearConsoleBuffer()
2569 * Description:
2570 * Clears the entire contents of the console screen buffer, using the
2571 * specified attribute.
2572 * Returns:
2573 * TRUE on success
2574 */
2575 static BOOL
2576ClearConsoleBuffer(WORD wAttribute)
2577{
2578 CONSOLE_SCREEN_BUFFER_INFO csbi;
2579 COORD coord;
2580 DWORD NumCells, dummy;
2581
2582 if (!GetConsoleScreenBufferInfo(g_hConOut, &csbi))
2583 return FALSE;
2584
2585 NumCells = csbi.dwSize.X * csbi.dwSize.Y;
2586 coord.X = 0;
2587 coord.Y = 0;
2588 if (!FillConsoleOutputCharacter(g_hConOut, ' ', NumCells,
2589 coord, &dummy))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002590 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002591 if (!FillConsoleOutputAttribute(g_hConOut, wAttribute, NumCells,
2592 coord, &dummy))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002593 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002594
2595 return TRUE;
2596}
2597
2598/*
2599 * FitConsoleWindow()
2600 * Description:
2601 * Checks if the console window will fit within given buffer dimensions.
2602 * Also, if requested, will shrink the window to fit.
2603 * Returns:
2604 * TRUE on success
2605 */
2606 static BOOL
2607FitConsoleWindow(
2608 COORD dwBufferSize,
2609 BOOL WantAdjust)
2610{
2611 CONSOLE_SCREEN_BUFFER_INFO csbi;
2612 COORD dwWindowSize;
2613 BOOL NeedAdjust = FALSE;
2614
2615 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
2616 {
2617 /*
2618 * A buffer resize will fail if the current console window does
2619 * not lie completely within that buffer. To avoid this, we might
2620 * have to move and possibly shrink the window.
2621 */
2622 if (csbi.srWindow.Right >= dwBufferSize.X)
2623 {
2624 dwWindowSize.X = SRWIDTH(csbi.srWindow);
2625 if (dwWindowSize.X > dwBufferSize.X)
2626 dwWindowSize.X = dwBufferSize.X;
2627 csbi.srWindow.Right = dwBufferSize.X - 1;
2628 csbi.srWindow.Left = dwBufferSize.X - dwWindowSize.X;
2629 NeedAdjust = TRUE;
2630 }
2631 if (csbi.srWindow.Bottom >= dwBufferSize.Y)
2632 {
2633 dwWindowSize.Y = SRHEIGHT(csbi.srWindow);
2634 if (dwWindowSize.Y > dwBufferSize.Y)
2635 dwWindowSize.Y = dwBufferSize.Y;
2636 csbi.srWindow.Bottom = dwBufferSize.Y - 1;
2637 csbi.srWindow.Top = dwBufferSize.Y - dwWindowSize.Y;
2638 NeedAdjust = TRUE;
2639 }
2640 if (NeedAdjust && WantAdjust)
2641 {
2642 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &csbi.srWindow))
2643 return FALSE;
2644 }
2645 return TRUE;
2646 }
2647
2648 return FALSE;
2649}
2650
2651typedef struct ConsoleBufferStruct
2652{
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002653 BOOL IsValid;
2654 CONSOLE_SCREEN_BUFFER_INFO Info;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002655 PCHAR_INFO Buffer;
2656 COORD BufferSize;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002657 PSMALL_RECT Regions;
2658 int NumRegions;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002659} ConsoleBuffer;
2660
2661/*
2662 * SaveConsoleBuffer()
2663 * Description:
2664 * Saves important information about the console buffer, including the
2665 * actual buffer contents. The saved information is suitable for later
2666 * restoration by RestoreConsoleBuffer().
2667 * Returns:
2668 * TRUE if all information was saved; FALSE otherwise
2669 * If FALSE, still sets cb->IsValid if buffer characteristics were saved.
2670 */
2671 static BOOL
2672SaveConsoleBuffer(
2673 ConsoleBuffer *cb)
2674{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002675 DWORD NumCells;
2676 COORD BufferCoord;
2677 SMALL_RECT ReadRegion;
2678 WORD Y, Y_incr;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002679 int i, numregions;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002680
Bram Moolenaar071d4272004-06-13 20:20:40 +00002681 if (cb == NULL)
2682 return FALSE;
2683
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002684 if (!GetConsoleScreenBufferInfo(g_hConOut, &cb->Info))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002685 {
2686 cb->IsValid = FALSE;
2687 return FALSE;
2688 }
2689 cb->IsValid = TRUE;
2690
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002691 /*
2692 * Allocate a buffer large enough to hold the entire console screen
2693 * buffer. If this ConsoleBuffer structure has already been initialized
2694 * with a buffer of the correct size, then just use that one.
2695 */
2696 if (!cb->IsValid || cb->Buffer == NULL ||
2697 cb->BufferSize.X != cb->Info.dwSize.X ||
2698 cb->BufferSize.Y != cb->Info.dwSize.Y)
2699 {
2700 cb->BufferSize.X = cb->Info.dwSize.X;
2701 cb->BufferSize.Y = cb->Info.dwSize.Y;
2702 NumCells = cb->BufferSize.X * cb->BufferSize.Y;
2703 vim_free(cb->Buffer);
Bram Moolenaarc799fe22019-05-28 23:08:19 +02002704 cb->Buffer = ALLOC_MULT(CHAR_INFO, NumCells);
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002705 if (cb->Buffer == NULL)
2706 return FALSE;
2707 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002708
2709 /*
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002710 * We will now copy the console screen buffer into our buffer.
2711 * ReadConsoleOutput() seems to be limited as far as how much you
2712 * can read at a time. Empirically, this number seems to be about
2713 * 12000 cells (rows * columns). Start at position (0, 0) and copy
2714 * in chunks until it is all copied. The chunks will all have the
2715 * same horizontal characteristics, so initialize them now. The
2716 * height of each chunk will be (12000 / width).
Bram Moolenaar071d4272004-06-13 20:20:40 +00002717 */
Bram Moolenaar61594242015-09-01 20:23:37 +02002718 BufferCoord.X = 0;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002719 ReadRegion.Left = 0;
2720 ReadRegion.Right = cb->Info.dwSize.X - 1;
2721 Y_incr = 12000 / cb->Info.dwSize.X;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002722
2723 numregions = (cb->Info.dwSize.Y + Y_incr - 1) / Y_incr;
2724 if (cb->Regions == NULL || numregions != cb->NumRegions)
2725 {
2726 cb->NumRegions = numregions;
2727 vim_free(cb->Regions);
Bram Moolenaarc799fe22019-05-28 23:08:19 +02002728 cb->Regions = ALLOC_MULT(SMALL_RECT, cb->NumRegions);
Bram Moolenaar444fda22017-08-11 20:37:00 +02002729 if (cb->Regions == NULL)
2730 {
Bram Moolenaard23a8232018-02-10 18:45:26 +01002731 VIM_CLEAR(cb->Buffer);
Bram Moolenaar444fda22017-08-11 20:37:00 +02002732 return FALSE;
2733 }
2734 }
2735
2736 for (i = 0, Y = 0; i < cb->NumRegions; i++, Y += Y_incr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002737 {
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002738 /*
2739 * Read into position (0, Y) in our buffer.
2740 */
2741 BufferCoord.Y = Y;
2742 /*
2743 * Read the region whose top left corner is (0, Y) and whose bottom
2744 * right corner is (width - 1, Y + Y_incr - 1). This should define
2745 * a region of size width by Y_incr. Don't worry if this region is
2746 * too large for the remaining buffer; it will be cropped.
2747 */
2748 ReadRegion.Top = Y;
2749 ReadRegion.Bottom = Y + Y_incr - 1;
Bram Moolenaar0f873732019-12-05 20:28:46 +01002750 if (!ReadConsoleOutputW(g_hConOut, // output handle
2751 cb->Buffer, // our buffer
2752 cb->BufferSize, // dimensions of our buffer
2753 BufferCoord, // offset in our buffer
2754 &ReadRegion)) // region to save
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002755 {
Bram Moolenaard23a8232018-02-10 18:45:26 +01002756 VIM_CLEAR(cb->Buffer);
2757 VIM_CLEAR(cb->Regions);
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002758 return FALSE;
2759 }
Bram Moolenaar444fda22017-08-11 20:37:00 +02002760 cb->Regions[i] = ReadRegion;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002761 }
2762
2763 return TRUE;
2764}
2765
2766/*
2767 * RestoreConsoleBuffer()
2768 * Description:
2769 * Restores important information about the console buffer, including the
2770 * actual buffer contents, if desired. The information to restore is in
2771 * the same format used by SaveConsoleBuffer().
2772 * Returns:
2773 * TRUE on success
2774 */
2775 static BOOL
2776RestoreConsoleBuffer(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002777 ConsoleBuffer *cb,
2778 BOOL RestoreScreen)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002779{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002780 COORD BufferCoord;
2781 SMALL_RECT WriteRegion;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002782 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002783
2784 if (cb == NULL || !cb->IsValid)
2785 return FALSE;
2786
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002787 /*
2788 * Before restoring the buffer contents, clear the current buffer, and
2789 * restore the cursor position and window information. Doing this now
2790 * prevents old buffer contents from "flashing" onto the screen.
2791 */
2792 if (RestoreScreen)
2793 ClearConsoleBuffer(cb->Info.wAttributes);
2794
2795 FitConsoleWindow(cb->Info.dwSize, TRUE);
2796 if (!SetConsoleScreenBufferSize(g_hConOut, cb->Info.dwSize))
2797 return FALSE;
2798 if (!SetConsoleTextAttribute(g_hConOut, cb->Info.wAttributes))
2799 return FALSE;
2800
2801 if (!RestoreScreen)
2802 {
2803 /*
2804 * No need to restore the screen buffer contents, so we're done.
2805 */
2806 return TRUE;
2807 }
2808
2809 if (!SetConsoleCursorPosition(g_hConOut, cb->Info.dwCursorPosition))
2810 return FALSE;
2811 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &cb->Info.srWindow))
2812 return FALSE;
2813
2814 /*
2815 * Restore the screen buffer contents.
2816 */
2817 if (cb->Buffer != NULL)
2818 {
Bram Moolenaar444fda22017-08-11 20:37:00 +02002819 for (i = 0; i < cb->NumRegions; i++)
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002820 {
Bram Moolenaar444fda22017-08-11 20:37:00 +02002821 BufferCoord.X = cb->Regions[i].Left;
2822 BufferCoord.Y = cb->Regions[i].Top;
2823 WriteRegion = cb->Regions[i];
Bram Moolenaar0f873732019-12-05 20:28:46 +01002824 if (!WriteConsoleOutputW(g_hConOut, // output handle
2825 cb->Buffer, // our buffer
2826 cb->BufferSize, // dimensions of our buffer
2827 BufferCoord, // offset in our buffer
2828 &WriteRegion)) // region to restore
Bram Moolenaar444fda22017-08-11 20:37:00 +02002829 return FALSE;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002830 }
2831 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002832
2833 return TRUE;
2834}
2835
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002836# define FEAT_RESTORE_ORIG_SCREEN
2837# ifdef FEAT_RESTORE_ORIG_SCREEN
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002838static ConsoleBuffer g_cbOrig = { 0 };
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002839# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002840static ConsoleBuffer g_cbNonTermcap = { 0 };
2841static ConsoleBuffer g_cbTermcap = { 0 };
2842
Bram Moolenaar071d4272004-06-13 20:20:40 +00002843char g_szOrigTitle[256] = { 0 };
Bram Moolenaar0f873732019-12-05 20:28:46 +01002844HWND g_hWnd = NULL; // also used in os_mswin.c
Bram Moolenaar071d4272004-06-13 20:20:40 +00002845static HICON g_hOrigIconSmall = NULL;
2846static HICON g_hOrigIcon = NULL;
2847static HICON g_hVimIcon = NULL;
2848static BOOL g_fCanChangeIcon = FALSE;
2849
Bram Moolenaar071d4272004-06-13 20:20:40 +00002850/*
2851 * GetConsoleIcon()
2852 * Description:
2853 * Attempts to retrieve the small icon and/or the big icon currently in
2854 * use by a given window.
2855 * Returns:
2856 * TRUE on success
2857 */
2858 static BOOL
2859GetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002860 HWND hWnd,
2861 HICON *phIconSmall,
2862 HICON *phIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002863{
2864 if (hWnd == NULL)
2865 return FALSE;
2866
2867 if (phIconSmall != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002868 *phIconSmall = (HICON)SendMessage(hWnd, WM_GETICON,
2869 (WPARAM)ICON_SMALL, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002870 if (phIcon != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002871 *phIcon = (HICON)SendMessage(hWnd, WM_GETICON,
2872 (WPARAM)ICON_BIG, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002873 return TRUE;
2874}
2875
2876/*
2877 * SetConsoleIcon()
2878 * Description:
2879 * Attempts to change the small icon and/or the big icon currently in
2880 * use by a given window.
2881 * Returns:
2882 * TRUE on success
2883 */
2884 static BOOL
2885SetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002886 HWND hWnd,
2887 HICON hIconSmall,
2888 HICON hIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002889{
Bram Moolenaar071d4272004-06-13 20:20:40 +00002890 if (hWnd == NULL)
2891 return FALSE;
2892
2893 if (hIconSmall != NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002894 SendMessage(hWnd, WM_SETICON,
2895 (WPARAM)ICON_SMALL, (LPARAM)hIconSmall);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002896 if (hIcon != NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002897 SendMessage(hWnd, WM_SETICON,
2898 (WPARAM)ICON_BIG, (LPARAM) hIcon);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002899 return TRUE;
2900}
2901
2902/*
2903 * SaveConsoleTitleAndIcon()
2904 * Description:
2905 * Saves the current console window title in g_szOrigTitle, for later
2906 * restoration. Also, attempts to obtain a handle to the console window,
2907 * and use it to save the small and big icons currently in use by the
2908 * console window. This is not always possible on some versions of Windows;
2909 * nor is it possible when running Vim remotely using Telnet (since the
2910 * console window the user sees is owned by a remote process).
2911 */
2912 static void
2913SaveConsoleTitleAndIcon(void)
2914{
Bram Moolenaar0f873732019-12-05 20:28:46 +01002915 // Save the original title.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002916 if (!GetConsoleTitle(g_szOrigTitle, sizeof(g_szOrigTitle)))
2917 return;
2918
2919 /*
2920 * Obtain a handle to the console window using GetConsoleWindow() from
2921 * KERNEL32.DLL; we need to handle in order to change the window icon.
2922 * This function only exists on NT-based Windows, starting with Windows
2923 * 2000. On older operating systems, we can't change the window icon
2924 * anyway.
2925 */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02002926 g_hWnd = GetConsoleWindow();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002927 if (g_hWnd == NULL)
2928 return;
2929
Bram Moolenaar0f873732019-12-05 20:28:46 +01002930 // Save the original console window icon.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002931 GetConsoleIcon(g_hWnd, &g_hOrigIconSmall, &g_hOrigIcon);
2932 if (g_hOrigIconSmall == NULL || g_hOrigIcon == NULL)
2933 return;
2934
Bram Moolenaar0f873732019-12-05 20:28:46 +01002935 // Extract the first icon contained in the Vim executable.
K.Takata2da11a42022-09-10 13:03:12 +01002936 if (
2937# ifdef FEAT_LIBCALL
2938 mch_icon_load((HANDLE *)&g_hVimIcon) == FAIL ||
2939# endif
2940 g_hVimIcon == NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002941 g_hVimIcon = ExtractIcon(NULL, (LPCSTR)exe_name, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002942 if (g_hVimIcon != NULL)
2943 g_fCanChangeIcon = TRUE;
2944}
Bram Moolenaar071d4272004-06-13 20:20:40 +00002945
2946static int g_fWindInitCalled = FALSE;
2947static int g_fTermcapMode = FALSE;
2948static CONSOLE_CURSOR_INFO g_cci;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002949
2950/*
2951 * non-GUI version of mch_init().
2952 */
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002953 static void
2954mch_init_c(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002955{
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002956# ifndef FEAT_RESTORE_ORIG_SCREEN
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002957 CONSOLE_SCREEN_BUFFER_INFO csbi;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002958# endif
2959# ifndef __MINGW32__
Bram Moolenaar071d4272004-06-13 20:20:40 +00002960 extern int _fmode;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002961# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002962
Bram Moolenaar0f873732019-12-05 20:28:46 +01002963 // Silently handle invalid parameters to CRT functions
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002964 SET_INVALID_PARAM_HANDLER;
2965
Bram Moolenaar0f873732019-12-05 20:28:46 +01002966 // Let critical errors result in a failure, not in a dialog box. Required
2967 // for the timestamp test to work on removed floppies.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002968 SetErrorMode(SEM_FAILCRITICALERRORS);
2969
Bram Moolenaar0f873732019-12-05 20:28:46 +01002970 _fmode = O_BINARY; // we do our own CR-LF translation
Bram Moolenaar071d4272004-06-13 20:20:40 +00002971 out_flush();
2972
Bram Moolenaar0f873732019-12-05 20:28:46 +01002973 // Obtain handles for the standard Console I/O devices
Bram Moolenaar071d4272004-06-13 20:20:40 +00002974 if (read_cmd_fd == 0)
2975 g_hConIn = GetStdHandle(STD_INPUT_HANDLE);
2976 else
2977 create_conin();
2978 g_hConOut = GetStdHandle(STD_OUTPUT_HANDLE);
2979
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002980# ifdef FEAT_RESTORE_ORIG_SCREEN
Bram Moolenaar0f873732019-12-05 20:28:46 +01002981 // Save the initial console buffer for later restoration
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002982 SaveConsoleBuffer(&g_cbOrig);
2983 g_attrCurrent = g_attrDefault = g_cbOrig.Info.wAttributes;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002984# else
Bram Moolenaar0f873732019-12-05 20:28:46 +01002985 // Get current text attributes
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002986 GetConsoleScreenBufferInfo(g_hConOut, &csbi);
2987 g_attrCurrent = g_attrDefault = csbi.wAttributes;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002988# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002989 if (cterm_normal_fg_color == 0)
2990 cterm_normal_fg_color = (g_attrCurrent & 0xf) + 1;
2991 if (cterm_normal_bg_color == 0)
2992 cterm_normal_bg_color = ((g_attrCurrent >> 4) & 0xf) + 1;
2993
Bram Moolenaarbdace832019-03-02 10:13:42 +01002994 // Fg and Bg color index number at startup
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02002995 g_color_index_fg = g_attrDefault & 0xf;
2996 g_color_index_bg = (g_attrDefault >> 4) & 0xf;
2997
Bram Moolenaar0f873732019-12-05 20:28:46 +01002998 // set termcap codes to current text attributes
Bram Moolenaar071d4272004-06-13 20:20:40 +00002999 update_tcap(g_attrCurrent);
3000
3001 GetConsoleCursorInfo(g_hConOut, &g_cci);
3002 GetConsoleMode(g_hConIn, &g_cmodein);
3003 GetConsoleMode(g_hConOut, &g_cmodeout);
3004
Bram Moolenaar071d4272004-06-13 20:20:40 +00003005 SaveConsoleTitleAndIcon();
3006 /*
3007 * Set both the small and big icons of the console window to Vim's icon.
3008 * Note that Vim presently only has one size of icon (32x32), but it
3009 * automatically gets scaled down to 16x16 when setting the small icon.
3010 */
3011 if (g_fCanChangeIcon)
3012 SetConsoleIcon(g_hWnd, g_hVimIcon, g_hVimIcon);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003013
3014 ui_get_shellsize();
3015
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003016# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00003017 fdDump = fopen("dump", "wt");
3018
3019 if (fdDump)
3020 {
3021 time_t t;
3022
3023 time(&t);
3024 fputs(ctime(&t), fdDump);
3025 fflush(fdDump);
3026 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003027# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003028
3029 g_fWindInitCalled = TRUE;
3030
Bram Moolenaar071d4272004-06-13 20:20:40 +00003031 g_fMouseAvail = GetSystemMetrics(SM_MOUSEPRESENT);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003032
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003033# ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01003034 win_clip_init();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003035# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01003036
Bram Moolenaar81ccbf12020-04-15 21:05:30 +02003037 vtp_flag_init();
Bram Moolenaarcafafb32018-02-22 21:07:09 +01003038 vtp_init();
Bram Moolenaar06b7b582020-05-30 17:49:25 +02003039 wt_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00003040}
3041
3042/*
3043 * non-GUI version of mch_exit().
3044 * Shut down and exit with status `r'
3045 * Careful: mch_exit() may be called before mch_init()!
3046 */
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003047 static void
3048mch_exit_c(int r)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003049{
Bram Moolenaar955f1982017-02-05 15:10:51 +01003050 exiting = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003051
Bram Moolenaarcafafb32018-02-22 21:07:09 +01003052 vtp_exit();
3053
Bram Moolenaar955f1982017-02-05 15:10:51 +01003054 stoptermcap();
Bram Moolenaar071d4272004-06-13 20:20:40 +00003055 if (g_fWindInitCalled)
3056 settmode(TMODE_COOK);
3057
Bram Moolenaar0f873732019-12-05 20:28:46 +01003058 ml_close_all(TRUE); // remove all memfiles
Bram Moolenaar071d4272004-06-13 20:20:40 +00003059
3060 if (g_fWindInitCalled)
3061 {
Bram Moolenaar40385db2018-08-07 22:31:44 +02003062 mch_restore_title(SAVE_RESTORE_BOTH);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003063 /*
3064 * Restore both the small and big icons of the console window to
3065 * what they were at startup. Don't do this when the window is
3066 * closed, Vim would hang here.
3067 */
3068 if (g_fCanChangeIcon && !g_fForceExit)
3069 SetConsoleIcon(g_hWnd, g_hOrigIconSmall, g_hOrigIcon);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003070
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003071# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00003072 if (fdDump)
3073 {
3074 time_t t;
3075
3076 time(&t);
3077 fputs(ctime(&t), fdDump);
3078 fclose(fdDump);
3079 }
3080 fdDump = NULL;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003081# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003082 }
3083
3084 SetConsoleCursorInfo(g_hConOut, &g_cci);
Wez Furlong6ef5ab52021-05-30 19:29:41 +02003085 SetConsoleMode(g_hConIn, g_cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003086 SetConsoleMode(g_hConOut, g_cmodeout);
3087
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003088# ifdef DYNAMIC_GETTEXT
Bram Moolenaar071d4272004-06-13 20:20:40 +00003089 dyn_libintl_end();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003090# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003091
3092 exit(r);
3093}
Bram Moolenaar0f873732019-12-05 20:28:46 +01003094#endif // !FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00003095
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003096 void
3097mch_init(void)
3098{
3099#ifdef VIMDLL
3100 if (gui.starting)
3101 mch_init_g();
3102 else
3103 mch_init_c();
3104#elif defined(FEAT_GUI_MSWIN)
3105 mch_init_g();
3106#else
3107 mch_init_c();
3108#endif
3109}
3110
3111 void
3112mch_exit(int r)
3113{
Bram Moolenaar173d8412020-04-19 14:02:26 +02003114#ifdef FEAT_NETBEANS_INTG
3115 netbeans_send_disconnect();
3116#endif
3117
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003118#ifdef VIMDLL
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02003119 if (gui.in_use || gui.starting)
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003120 mch_exit_g(r);
3121 else
3122 mch_exit_c(r);
3123#elif defined(FEAT_GUI_MSWIN)
3124 mch_exit_g(r);
3125#else
3126 mch_exit_c(r);
3127#endif
3128}
3129
Bram Moolenaar071d4272004-06-13 20:20:40 +00003130/*
3131 * Do we have an interactive window?
3132 */
3133 int
3134mch_check_win(
Bram Moolenaar1266d672017-02-01 13:43:36 +01003135 int argc UNUSED,
3136 char **argv UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003137{
3138 get_exe_name();
3139
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003140#if defined(FEAT_GUI_MSWIN) && !defined(VIMDLL)
Bram Moolenaar0f873732019-12-05 20:28:46 +01003141 return OK; // GUI always has a tty
Bram Moolenaar071d4272004-06-13 20:20:40 +00003142#else
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003143# ifdef VIMDLL
3144 if (gui.in_use)
3145 return OK;
3146# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003147 if (isatty(1))
3148 return OK;
3149 return FAIL;
3150#endif
3151}
3152
Bram Moolenaar65f04f62013-08-30 17:29:16 +02003153/*
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003154 * Set the case of the file name, if it already exists.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003155 * When "len" is > 0, also expand short to long filenames.
3156 */
3157 void
3158fname_case(
3159 char_u *name,
3160 int len)
3161{
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003162 int flen;
3163 WCHAR *p;
3164 WCHAR buf[_MAX_PATH + 1];
Bram Moolenaar071d4272004-06-13 20:20:40 +00003165
Bram Moolenaara3ffd9c2005-07-21 21:03:15 +00003166 flen = (int)STRLEN(name);
Bram Moolenaar65f04f62013-08-30 17:29:16 +02003167 if (flen == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003168 return;
3169
3170 slash_adjust(name);
3171
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003172 p = enc_to_utf16(name, NULL);
3173 if (p == NULL)
Bram Moolenaar65f04f62013-08-30 17:29:16 +02003174 return;
3175
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003176 if (GetLongPathNameW(p, buf, _MAX_PATH))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003177 {
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003178 char_u *q = utf16_to_enc(buf, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003179
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003180 if (q != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003181 {
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003182 if (len > 0 || flen >= (int)STRLEN(q))
3183 vim_strncpy(name, q, (len > 0) ? len - 1 : flen);
3184 vim_free(q);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003185 }
3186 }
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003187 vim_free(p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003188}
3189
3190
3191/*
3192 * Insert user name in s[len].
3193 */
3194 int
3195mch_get_user_name(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003196 char_u *s,
3197 int len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003198{
Bram Moolenaar0f873732019-12-05 20:28:46 +01003199 WCHAR wszUserName[256 + 1]; // UNLEN is 256
K.Takataeeec2542021-06-02 13:28:16 +02003200 DWORD wcch = ARRAY_LENGTH(wszUserName);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003201
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003202 if (GetUserNameW(wszUserName, &wcch))
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003203 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003204 char_u *p = utf16_to_enc(wszUserName, NULL);
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003205
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003206 if (p != NULL)
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003207 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003208 vim_strncpy(s, p, len - 1);
3209 vim_free(p);
3210 return OK;
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003211 }
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003212 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003213 s[0] = NUL;
3214 return FAIL;
3215}
3216
3217
3218/*
3219 * Insert host name in s[len].
3220 */
3221 void
3222mch_get_host_name(
3223 char_u *s,
3224 int len)
3225{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003226 WCHAR wszHostName[256 + 1];
K.Takataeeec2542021-06-02 13:28:16 +02003227 DWORD wcch = ARRAY_LENGTH(wszHostName);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003228
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003229 if (GetComputerNameW(wszHostName, &wcch))
Bram Moolenaar2cc87382013-12-11 18:21:45 +01003230 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003231 char_u *p = utf16_to_enc(wszHostName, NULL);
Bram Moolenaar2cc87382013-12-11 18:21:45 +01003232
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003233 if (p != NULL)
Bram Moolenaar2cc87382013-12-11 18:21:45 +01003234 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003235 vim_strncpy(s, p, len - 1);
3236 vim_free(p);
3237 return;
Bram Moolenaar2cc87382013-12-11 18:21:45 +01003238 }
Bram Moolenaar2cc87382013-12-11 18:21:45 +01003239 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003240}
3241
3242
3243/*
3244 * return process ID
3245 */
3246 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003247mch_get_pid(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003248{
3249 return (long)GetCurrentProcessId();
3250}
3251
Bram Moolenaar67cf86b2019-04-28 22:25:38 +02003252/*
3253 * return TRUE if process "pid" is still running
3254 */
3255 int
Bram Moolenaar1b243ea2019-04-28 22:50:40 +02003256mch_process_running(long pid)
Bram Moolenaar67cf86b2019-04-28 22:25:38 +02003257{
3258 HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION, 0, (DWORD)pid);
3259 DWORD status = 0;
3260 int ret = FALSE;
3261
3262 if (hProcess == NULL)
3263 return FALSE; // might not have access
3264 if (GetExitCodeProcess(hProcess, &status) )
3265 ret = status == STILL_ACTIVE;
3266 CloseHandle(hProcess);
3267 return ret;
3268}
Bram Moolenaar071d4272004-06-13 20:20:40 +00003269
3270/*
3271 * Get name of current directory into buffer 'buf' of length 'len' bytes.
3272 * Return OK for success, FAIL for failure.
3273 */
3274 int
3275mch_dirname(
3276 char_u *buf,
3277 int len)
3278{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003279 WCHAR wbuf[_MAX_PATH + 1];
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02003280
Bram Moolenaar071d4272004-06-13 20:20:40 +00003281 /*
3282 * Originally this was:
3283 * return (getcwd(buf, len) != NULL ? OK : FAIL);
3284 * But the Win32s known bug list says that getcwd() doesn't work
3285 * so use the Win32 system call instead. <Negri>
3286 */
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003287 if (GetCurrentDirectoryW(_MAX_PATH, wbuf) != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003288 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003289 WCHAR wcbuf[_MAX_PATH + 1];
3290 char_u *p = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003291
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003292 if (GetLongPathNameW(wbuf, wcbuf, _MAX_PATH) != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003293 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003294 p = utf16_to_enc(wcbuf, NULL);
3295 if (STRLEN(p) >= (size_t)len)
Bram Moolenaarcea1f9e2018-08-19 14:38:42 +02003296 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003297 // long path name is too long, fall back to short one
Bram Moolenaar071d4272004-06-13 20:20:40 +00003298 vim_free(p);
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003299 p = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003300 }
3301 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003302 if (p == NULL)
3303 p = utf16_to_enc(wbuf, NULL);
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02003304
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003305 if (p != NULL)
3306 {
3307 vim_strncpy(buf, p, len - 1);
3308 vim_free(p);
3309 return OK;
3310 }
3311 }
3312 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003313}
3314
3315/*
Bram Moolenaarffa22202013-11-21 12:34:11 +01003316 * Get file permissions for "name".
3317 * Return mode_t or -1 for error.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003318 */
3319 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003320mch_getperm(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003321{
Bram Moolenaar8767f522016-07-01 17:17:39 +02003322 stat_T st;
Bram Moolenaarffa22202013-11-21 12:34:11 +01003323 int n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003324
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003325 n = mch_stat((char *)name, &st);
Bram Moolenaar78cf3f02014-01-10 18:16:07 +01003326 return n == 0 ? (long)(unsigned short)st.st_mode : -1L;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003327}
3328
3329
3330/*
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003331 * Set file permission for "name" to "perm".
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003332 *
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003333 * Return FAIL for failure, OK otherwise.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003334 */
3335 int
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003336mch_setperm(char_u *name, long perm)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003337{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003338 long n;
3339 WCHAR *p;
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003340
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003341 p = enc_to_utf16(name, NULL);
3342 if (p == NULL)
3343 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003344
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003345 n = _wchmod(p, perm);
3346 vim_free(p);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003347 if (n == -1)
3348 return FAIL;
3349
3350 win32_set_archive(name);
3351
3352 return OK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003353}
3354
3355/*
3356 * Set hidden flag for "name".
3357 */
3358 void
3359mch_hide(char_u *name)
3360{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003361 int attrs = win32_getattrs(name);
3362 if (attrs == -1)
3363 return;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003364
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003365 attrs |= FILE_ATTRIBUTE_HIDDEN;
3366 win32_setattrs(name, attrs);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003367}
3368
3369/*
Bram Moolenaar8a52ba72015-11-02 14:45:56 +01003370 * Return TRUE if file "name" exists and is hidden.
3371 */
3372 int
3373mch_ishidden(char_u *name)
3374{
3375 int f = win32_getattrs(name);
3376
3377 if (f == -1)
Bram Moolenaar0f873732019-12-05 20:28:46 +01003378 return FALSE; // file does not exist at all
Bram Moolenaar8a52ba72015-11-02 14:45:56 +01003379
3380 return (f & FILE_ATTRIBUTE_HIDDEN) != 0;
3381}
3382
3383/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003384 * return TRUE if "name" is a directory
3385 * return FALSE if "name" is not a directory or upon error
3386 */
3387 int
3388mch_isdir(char_u *name)
3389{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003390 int f = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003391
3392 if (f == -1)
Bram Moolenaar0f873732019-12-05 20:28:46 +01003393 return FALSE; // file does not exist at all
Bram Moolenaar071d4272004-06-13 20:20:40 +00003394
3395 return (f & FILE_ATTRIBUTE_DIRECTORY) != 0;
3396}
3397
3398/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01003399 * return TRUE if "name" is a directory, NOT a symlink to a directory
3400 * return FALSE if "name" is not a directory
3401 * return FALSE for error
3402 */
3403 int
3404mch_isrealdir(char_u *name)
3405{
3406 return mch_isdir(name) && !mch_is_symbolic_link(name);
3407}
3408
3409/*
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003410 * Create directory "name".
3411 * Return 0 on success, -1 on error.
3412 */
3413 int
3414mch_mkdir(char_u *name)
3415{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003416 WCHAR *p;
3417 int retval;
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003418
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003419 p = enc_to_utf16(name, NULL);
3420 if (p == NULL)
3421 return -1;
3422 retval = _wmkdir(p);
3423 vim_free(p);
3424 return retval;
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003425}
3426
3427/*
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003428 * Delete directory "name".
3429 * Return 0 on success, -1 on error.
3430 */
3431 int
3432mch_rmdir(char_u *name)
3433{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003434 WCHAR *p;
3435 int retval;
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003436
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003437 p = enc_to_utf16(name, NULL);
3438 if (p == NULL)
3439 return -1;
3440 retval = _wrmdir(p);
3441 vim_free(p);
3442 return retval;
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003443}
3444
3445/*
Bram Moolenaar03f48552006-02-28 23:52:23 +00003446 * Return TRUE if file "fname" has more than one link.
3447 */
3448 int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003449mch_is_hard_link(char_u *fname)
Bram Moolenaar03f48552006-02-28 23:52:23 +00003450{
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003451 BY_HANDLE_FILE_INFORMATION info;
3452
3453 return win32_fileinfo(fname, &info) == FILEINFO_OK
3454 && info.nNumberOfLinks > 1;
3455}
3456
3457/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01003458 * Return TRUE if "name" is a symbolic link (or a junction).
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003459 */
3460 int
Bram Moolenaar203258c2016-01-17 22:15:16 +01003461mch_is_symbolic_link(char_u *name)
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003462{
3463 HANDLE hFind;
3464 int res = FALSE;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003465 DWORD fileFlags = 0, reparseTag = 0;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003466 WCHAR *wn;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003467 WIN32_FIND_DATAW findDataW;
3468
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003469 wn = enc_to_utf16(name, NULL);
3470 if (wn == NULL)
3471 return FALSE;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003472
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003473 hFind = FindFirstFileW(wn, &findDataW);
3474 vim_free(wn);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003475 if (hFind != INVALID_HANDLE_VALUE)
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003476 {
3477 fileFlags = findDataW.dwFileAttributes;
3478 reparseTag = findDataW.dwReserved0;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003479 FindClose(hFind);
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003480 }
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003481
3482 if ((fileFlags & FILE_ATTRIBUTE_REPARSE_POINT)
Bram Moolenaar203258c2016-01-17 22:15:16 +01003483 && (reparseTag == IO_REPARSE_TAG_SYMLINK
3484 || reparseTag == IO_REPARSE_TAG_MOUNT_POINT))
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003485 res = TRUE;
3486
3487 return res;
3488}
3489
3490/*
3491 * Return TRUE if file "fname" has more than one link or if it is a symbolic
3492 * link.
3493 */
3494 int
3495mch_is_linked(char_u *fname)
3496{
3497 if (mch_is_hard_link(fname) || mch_is_symbolic_link(fname))
3498 return TRUE;
3499 return FALSE;
3500}
3501
3502/*
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003503 * Get the by-handle-file-information for "fname".
3504 * Returns FILEINFO_OK when OK.
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003505 * Returns FILEINFO_ENC_FAIL when enc_to_utf16() failed.
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003506 * Returns FILEINFO_READ_FAIL when CreateFile() failed.
3507 * Returns FILEINFO_INFO_FAIL when GetFileInformationByHandle() failed.
3508 */
3509 int
3510win32_fileinfo(char_u *fname, BY_HANDLE_FILE_INFORMATION *info)
3511{
Bram Moolenaar03f48552006-02-28 23:52:23 +00003512 HANDLE hFile;
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003513 int res = FILEINFO_READ_FAIL;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003514 WCHAR *wn;
Bram Moolenaar03f48552006-02-28 23:52:23 +00003515
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003516 wn = enc_to_utf16(fname, NULL);
3517 if (wn == NULL)
3518 return FILEINFO_ENC_FAIL;
3519
3520 hFile = CreateFileW(wn, // file name
3521 GENERIC_READ, // access mode
3522 FILE_SHARE_READ | FILE_SHARE_WRITE, // share mode
3523 NULL, // security descriptor
3524 OPEN_EXISTING, // creation disposition
3525 FILE_FLAG_BACKUP_SEMANTICS, // file attributes
3526 NULL); // handle to template file
3527 vim_free(wn);
Bram Moolenaar03f48552006-02-28 23:52:23 +00003528
3529 if (hFile != INVALID_HANDLE_VALUE)
3530 {
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003531 if (GetFileInformationByHandle(hFile, info) != 0)
3532 res = FILEINFO_OK;
3533 else
3534 res = FILEINFO_INFO_FAIL;
Bram Moolenaar03f48552006-02-28 23:52:23 +00003535 CloseHandle(hFile);
3536 }
3537
Bram Moolenaar03f48552006-02-28 23:52:23 +00003538 return res;
3539}
3540
3541/*
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003542 * get file attributes for `name'
3543 * -1 : error
3544 * else FILE_ATTRIBUTE_* defined in winnt.h
3545 */
Bram Moolenaarffa22202013-11-21 12:34:11 +01003546 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003547win32_getattrs(char_u *name)
3548{
3549 int attr;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003550 WCHAR *p;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003551
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003552 p = enc_to_utf16(name, NULL);
3553 if (p == NULL)
3554 return INVALID_FILE_ATTRIBUTES;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003555
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003556 attr = GetFileAttributesW(p);
3557 vim_free(p);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003558
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003559 return attr;
3560}
3561
3562/*
3563 * set file attributes for `name' to `attrs'
3564 *
3565 * return -1 for failure, 0 otherwise
3566 */
Bram Moolenaar6dff58f2018-09-30 21:43:26 +02003567 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003568win32_setattrs(char_u *name, int attrs)
3569{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003570 int res;
3571 WCHAR *p;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003572
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003573 p = enc_to_utf16(name, NULL);
3574 if (p == NULL)
3575 return -1;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003576
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003577 res = SetFileAttributesW(p, attrs);
3578 vim_free(p);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003579
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003580 return res ? 0 : -1;
3581}
3582
3583/*
3584 * Set archive flag for "name".
3585 */
Bram Moolenaar6dff58f2018-09-30 21:43:26 +02003586 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003587win32_set_archive(char_u *name)
3588{
3589 int attrs = win32_getattrs(name);
3590 if (attrs == -1)
3591 return -1;
3592
3593 attrs |= FILE_ATTRIBUTE_ARCHIVE;
3594 return win32_setattrs(name, attrs);
3595}
3596
3597/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003598 * Return TRUE if file or directory "name" is writable (not readonly).
3599 * Strange semantics of Win32: a readonly directory is writable, but you can't
3600 * delete a file. Let's say this means it is writable.
3601 */
3602 int
3603mch_writable(char_u *name)
3604{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003605 int attrs = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003606
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003607 return (attrs != -1 && (!(attrs & FILE_ATTRIBUTE_READONLY)
3608 || (attrs & FILE_ATTRIBUTE_DIRECTORY)));
Bram Moolenaar071d4272004-06-13 20:20:40 +00003609}
3610
Bram Moolenaar071d4272004-06-13 20:20:40 +00003611/*
Bram Moolenaar43663192017-03-05 14:29:12 +01003612 * Return TRUE if "name" can be executed, FALSE if not.
Bram Moolenaar77b77102015-03-21 22:18:41 +01003613 * If "use_path" is FALSE only check if "name" is executable.
Bram Moolenaar43663192017-03-05 14:29:12 +01003614 * When returning TRUE and "path" is not NULL save the path and set "*path" to
3615 * the allocated memory.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003616 */
3617 int
Yegappan Lakshmananebb01bd2022-06-08 15:14:09 +01003618mch_can_exe(char_u *name, char_u **path, int use_path UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003619{
Bram Moolenaar95da1362020-05-30 18:37:55 +02003620 return executable_exists((char *)name, path, TRUE, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003621}
Bram Moolenaar071d4272004-06-13 20:20:40 +00003622
3623/*
3624 * Check what "name" is:
3625 * NODE_NORMAL: file or directory (or doesn't exist)
3626 * NODE_WRITABLE: writable device, socket, fifo, etc.
3627 * NODE_OTHER: non-writable things
3628 */
3629 int
3630mch_nodetype(char_u *name)
3631{
3632 HANDLE hFile;
3633 int type;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003634 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003635
Bram Moolenaar0f873732019-12-05 20:28:46 +01003636 // We can't open a file with a name "\\.\con" or "\\.\prn" and trying to
3637 // read from it later will cause Vim to hang. Thus return NODE_WRITABLE
3638 // here.
Bram Moolenaar043545e2006-10-10 16:44:07 +00003639 if (STRNCMP(name, "\\\\.\\", 4) == 0)
3640 return NODE_WRITABLE;
3641
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003642 wn = enc_to_utf16(name, NULL);
3643 if (wn == NULL)
3644 return NODE_NORMAL;
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003645
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003646 hFile = CreateFileW(wn, // file name
3647 GENERIC_WRITE, // access mode
3648 0, // share mode
3649 NULL, // security descriptor
3650 OPEN_EXISTING, // creation disposition
3651 0, // file attributes
3652 NULL); // handle to template file
3653 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003654 if (hFile == INVALID_HANDLE_VALUE)
3655 return NODE_NORMAL;
3656
3657 type = GetFileType(hFile);
3658 CloseHandle(hFile);
3659 if (type == FILE_TYPE_CHAR)
3660 return NODE_WRITABLE;
3661 if (type == FILE_TYPE_DISK)
3662 return NODE_NORMAL;
3663 return NODE_OTHER;
3664}
3665
3666#ifdef HAVE_ACL
3667struct my_acl
3668{
3669 PSECURITY_DESCRIPTOR pSecurityDescriptor;
3670 PSID pSidOwner;
3671 PSID pSidGroup;
3672 PACL pDacl;
3673 PACL pSacl;
3674};
3675#endif
3676
3677/*
3678 * Return a pointer to the ACL of file "fname" in allocated memory.
3679 * Return NULL if the ACL is not available for whatever reason.
3680 */
3681 vim_acl_T
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003682mch_get_acl(char_u *fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003683{
3684#ifndef HAVE_ACL
3685 return (vim_acl_T)NULL;
3686#else
3687 struct my_acl *p = NULL;
Bram Moolenaar27515922013-06-29 15:36:26 +02003688 DWORD err;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003689
Bram Moolenaarc799fe22019-05-28 23:08:19 +02003690 p = ALLOC_CLEAR_ONE(struct my_acl);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003691 if (p != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003692 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003693 WCHAR *wn;
Bram Moolenaar27515922013-06-29 15:36:26 +02003694
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003695 wn = enc_to_utf16(fname, NULL);
3696 if (wn == NULL)
Bram Moolenaarbbf9f342020-11-10 22:03:40 +01003697 {
3698 vim_free(p);
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003699 return NULL;
Bram Moolenaarbbf9f342020-11-10 22:03:40 +01003700 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003701
3702 // Try to retrieve the entire security descriptor.
3703 err = GetNamedSecurityInfoW(
3704 wn, // Abstract filename
3705 SE_FILE_OBJECT, // File Object
3706 OWNER_SECURITY_INFORMATION |
3707 GROUP_SECURITY_INFORMATION |
3708 DACL_SECURITY_INFORMATION |
3709 SACL_SECURITY_INFORMATION,
3710 &p->pSidOwner, // Ownership information.
3711 &p->pSidGroup, // Group membership.
3712 &p->pDacl, // Discretionary information.
3713 &p->pSacl, // For auditing purposes.
3714 &p->pSecurityDescriptor);
3715 if (err == ERROR_ACCESS_DENIED ||
3716 err == ERROR_PRIVILEGE_NOT_HELD)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003717 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003718 // Retrieve only DACL.
3719 (void)GetNamedSecurityInfoW(
3720 wn,
3721 SE_FILE_OBJECT,
3722 DACL_SECURITY_INFORMATION,
3723 NULL,
3724 NULL,
3725 &p->pDacl,
3726 NULL,
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003727 &p->pSecurityDescriptor);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003728 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003729 if (p->pSecurityDescriptor == NULL)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003730 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003731 mch_free_acl((vim_acl_T)p);
3732 p = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003733 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003734 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003735 }
3736
3737 return (vim_acl_T)p;
3738#endif
3739}
3740
Bram Moolenaar27515922013-06-29 15:36:26 +02003741#ifdef HAVE_ACL
3742/*
3743 * Check if "acl" contains inherited ACE.
3744 */
3745 static BOOL
3746is_acl_inherited(PACL acl)
3747{
3748 DWORD i;
3749 ACL_SIZE_INFORMATION acl_info;
3750 PACCESS_ALLOWED_ACE ace;
3751
3752 acl_info.AceCount = 0;
3753 GetAclInformation(acl, &acl_info, sizeof(acl_info), AclSizeInformation);
3754 for (i = 0; i < acl_info.AceCount; i++)
3755 {
3756 GetAce(acl, i, (LPVOID *)&ace);
3757 if (ace->Header.AceFlags & INHERITED_ACE)
3758 return TRUE;
3759 }
3760 return FALSE;
3761}
3762#endif
3763
Bram Moolenaar071d4272004-06-13 20:20:40 +00003764/*
3765 * Set the ACL of file "fname" to "acl" (unless it's NULL).
3766 * Errors are ignored.
3767 * This must only be called with "acl" equal to what mch_get_acl() returned.
3768 */
3769 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003770mch_set_acl(char_u *fname, vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003771{
3772#ifdef HAVE_ACL
3773 struct my_acl *p = (struct my_acl *)acl;
Bram Moolenaar27515922013-06-29 15:36:26 +02003774 SECURITY_INFORMATION sec_info = 0;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003775 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003776
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003777 if (p == NULL)
3778 return;
3779
3780 wn = enc_to_utf16(fname, NULL);
3781 if (wn == NULL)
3782 return;
3783
3784 // Set security flags
3785 if (p->pSidOwner)
3786 sec_info |= OWNER_SECURITY_INFORMATION;
3787 if (p->pSidGroup)
3788 sec_info |= GROUP_SECURITY_INFORMATION;
3789 if (p->pDacl)
Bram Moolenaar27515922013-06-29 15:36:26 +02003790 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003791 sec_info |= DACL_SECURITY_INFORMATION;
3792 // Do not inherit its parent's DACL.
3793 // If the DACL is inherited, Cygwin permissions would be changed.
3794 if (!is_acl_inherited(p->pDacl))
3795 sec_info |= PROTECTED_DACL_SECURITY_INFORMATION;
Bram Moolenaar27515922013-06-29 15:36:26 +02003796 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003797 if (p->pSacl)
3798 sec_info |= SACL_SECURITY_INFORMATION;
3799
3800 (void)SetNamedSecurityInfoW(
3801 wn, // Abstract filename
3802 SE_FILE_OBJECT, // File Object
3803 sec_info,
3804 p->pSidOwner, // Ownership information.
3805 p->pSidGroup, // Group membership.
3806 p->pDacl, // Discretionary information.
3807 p->pSacl // For auditing purposes.
3808 );
3809 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003810#endif
3811}
3812
3813 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003814mch_free_acl(vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003815{
3816#ifdef HAVE_ACL
3817 struct my_acl *p = (struct my_acl *)acl;
3818
3819 if (p != NULL)
3820 {
3821 LocalFree(p->pSecurityDescriptor); // Free the memory just in case
3822 vim_free(p);
3823 }
3824#endif
3825}
3826
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003827#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003828
3829/*
3830 * handler for ctrl-break, ctrl-c interrupts, and fatal events.
3831 */
3832 static BOOL WINAPI
3833handler_routine(
3834 DWORD dwCtrlType)
3835{
Bram Moolenaar589b1102017-08-12 16:39:05 +02003836 INPUT_RECORD ir;
3837 DWORD out;
3838
Bram Moolenaar071d4272004-06-13 20:20:40 +00003839 switch (dwCtrlType)
3840 {
3841 case CTRL_C_EVENT:
3842 if (ctrl_c_interrupts)
3843 g_fCtrlCPressed = TRUE;
3844 return TRUE;
3845
3846 case CTRL_BREAK_EVENT:
3847 g_fCBrkPressed = TRUE;
Bram Moolenaar589b1102017-08-12 16:39:05 +02003848 ctrl_break_was_pressed = TRUE;
Bram Moolenaar0f873732019-12-05 20:28:46 +01003849 // ReadConsoleInput is blocking, send a key event to continue.
Bram Moolenaar589b1102017-08-12 16:39:05 +02003850 ir.EventType = KEY_EVENT;
3851 ir.Event.KeyEvent.bKeyDown = TRUE;
3852 ir.Event.KeyEvent.wRepeatCount = 1;
3853 ir.Event.KeyEvent.wVirtualKeyCode = VK_CANCEL;
3854 ir.Event.KeyEvent.wVirtualScanCode = 0;
3855 ir.Event.KeyEvent.dwControlKeyState = 0;
3856 ir.Event.KeyEvent.uChar.UnicodeChar = 0;
3857 WriteConsoleInput(g_hConIn, &ir, 1, &out);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003858 return TRUE;
3859
Bram Moolenaar0f873732019-12-05 20:28:46 +01003860 // fatal events: shut down gracefully
Bram Moolenaar071d4272004-06-13 20:20:40 +00003861 case CTRL_CLOSE_EVENT:
3862 case CTRL_LOGOFF_EVENT:
3863 case CTRL_SHUTDOWN_EVENT:
3864 windgoto((int)Rows - 1, 0);
3865 g_fForceExit = TRUE;
3866
Bram Moolenaar0fde2902008-03-16 13:54:13 +00003867 vim_snprintf((char *)IObuff, IOSIZE, _("Vim: Caught %s event\n"),
Bram Moolenaar071d4272004-06-13 20:20:40 +00003868 (dwCtrlType == CTRL_CLOSE_EVENT
3869 ? _("close")
3870 : dwCtrlType == CTRL_LOGOFF_EVENT
3871 ? _("logoff")
3872 : _("shutdown")));
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003873# ifdef DEBUG
Bram Moolenaar071d4272004-06-13 20:20:40 +00003874 OutputDebugString(IObuff);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003875# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003876
Bram Moolenaar0f873732019-12-05 20:28:46 +01003877 preserve_exit(); // output IObuff, preserve files and exit
Bram Moolenaar071d4272004-06-13 20:20:40 +00003878
Bram Moolenaar0f873732019-12-05 20:28:46 +01003879 return TRUE; // not reached
Bram Moolenaar071d4272004-06-13 20:20:40 +00003880
3881 default:
3882 return FALSE;
3883 }
3884}
3885
3886
3887/*
3888 * set the tty in (raw) ? "raw" : "cooked" mode
3889 */
3890 void
Bram Moolenaar26e86442020-05-17 14:06:16 +02003891mch_settmode(tmode_T tmode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003892{
3893 DWORD cmodein;
3894 DWORD cmodeout;
3895 BOOL bEnableHandler;
3896
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003897# ifdef VIMDLL
3898 if (gui.in_use)
3899 return;
3900# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003901 GetConsoleMode(g_hConIn, &cmodein);
3902 GetConsoleMode(g_hConOut, &cmodeout);
3903 if (tmode == TMODE_RAW)
3904 {
3905 cmodein &= ~(ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
3906 ENABLE_ECHO_INPUT);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003907 if (g_fMouseActive)
Wez Furlong6ef5ab52021-05-30 19:29:41 +02003908 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00003909 cmodein |= ENABLE_MOUSE_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02003910 cmodein &= ~ENABLE_QUICK_EDIT_MODE;
3911 }
3912 else
3913 {
3914 cmodein |= g_cmodein & ENABLE_QUICK_EDIT_MODE;
3915 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01003916 cmodeout &= ~(
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003917# ifdef FEAT_TERMGUICOLORS
Bram Moolenaar0f873732019-12-05 20:28:46 +01003918 // Do not turn off the ENABLE_PROCESSED_OUTPUT flag when using
3919 // VTP.
Bram Moolenaarcafafb32018-02-22 21:07:09 +01003920 ((vtp_working) ? 0 : ENABLE_PROCESSED_OUTPUT) |
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003921# else
Bram Moolenaarcafafb32018-02-22 21:07:09 +01003922 ENABLE_PROCESSED_OUTPUT |
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003923# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01003924 ENABLE_WRAP_AT_EOL_OUTPUT);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003925 bEnableHandler = TRUE;
3926 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01003927 else // cooked
Bram Moolenaar071d4272004-06-13 20:20:40 +00003928 {
3929 cmodein |= (ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
3930 ENABLE_ECHO_INPUT);
3931 cmodeout |= (ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
3932 bEnableHandler = FALSE;
3933 }
Wez Furlong6ef5ab52021-05-30 19:29:41 +02003934 SetConsoleMode(g_hConIn, cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003935 SetConsoleMode(g_hConOut, cmodeout);
3936 SetConsoleCtrlHandler(handler_routine, bEnableHandler);
3937
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003938# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00003939 if (fdDump)
3940 {
3941 fprintf(fdDump, "mch_settmode(%s, in = %x, out = %x)\n",
3942 tmode == TMODE_RAW ? "raw" :
3943 tmode == TMODE_COOK ? "cooked" : "normal",
3944 cmodein, cmodeout);
3945 fflush(fdDump);
3946 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003947# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003948}
3949
3950
3951/*
3952 * Get the size of the current window in `Rows' and `Columns'
3953 * Return OK when size could be determined, FAIL otherwise.
3954 */
3955 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003956mch_get_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003957{
3958 CONSOLE_SCREEN_BUFFER_INFO csbi;
3959
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003960# ifdef VIMDLL
3961 if (gui.in_use)
3962 return OK;
3963# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003964 if (!g_fTermcapMode && g_cbTermcap.IsValid)
3965 {
3966 /*
3967 * For some reason, we are trying to get the screen dimensions
3968 * even though we are not in termcap mode. The 'Rows' and 'Columns'
3969 * variables are really intended to mean the size of Vim screen
3970 * while in termcap mode.
3971 */
3972 Rows = g_cbTermcap.Info.dwSize.Y;
3973 Columns = g_cbTermcap.Info.dwSize.X;
3974 }
3975 else if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3976 {
3977 Rows = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
3978 Columns = csbi.srWindow.Right - csbi.srWindow.Left + 1;
3979 }
3980 else
3981 {
3982 Rows = 25;
3983 Columns = 80;
3984 }
3985 return OK;
3986}
3987
3988/*
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02003989 * Resize console buffer to 'COORD'
3990 */
3991 static void
3992ResizeConBuf(
3993 HANDLE hConsole,
3994 COORD coordScreen)
3995{
3996 if (!SetConsoleScreenBufferSize(hConsole, coordScreen))
3997 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003998# ifdef MCH_WRITE_DUMP
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02003999 if (fdDump)
4000 {
4001 fprintf(fdDump, "SetConsoleScreenBufferSize failed: %lx\n",
4002 GetLastError());
4003 fflush(fdDump);
4004 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004005# endif
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004006 }
4007}
4008
4009/*
4010 * Resize console window size to 'srWindowRect'
4011 */
4012 static void
4013ResizeWindow(
4014 HANDLE hConsole,
4015 SMALL_RECT srWindowRect)
4016{
4017 if (!SetConsoleWindowInfo(hConsole, TRUE, &srWindowRect))
4018 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004019# ifdef MCH_WRITE_DUMP
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004020 if (fdDump)
4021 {
4022 fprintf(fdDump, "SetConsoleWindowInfo failed: %lx\n",
4023 GetLastError());
4024 fflush(fdDump);
4025 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004026# endif
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004027 }
4028}
4029
4030/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00004031 * Set a console window to `xSize' * `ySize'
4032 */
4033 static void
4034ResizeConBufAndWindow(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004035 HANDLE hConsole,
4036 int xSize,
4037 int ySize)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004038{
Bram Moolenaar0f873732019-12-05 20:28:46 +01004039 CONSOLE_SCREEN_BUFFER_INFO csbi; // hold current console buffer info
4040 SMALL_RECT srWindowRect; // hold the new console size
Bram Moolenaar071d4272004-06-13 20:20:40 +00004041 COORD coordScreen;
Bram Moolenaarf49a6922019-07-15 20:37:05 +02004042 COORD cursor;
Bram Moolenaar2551c032018-08-23 22:38:31 +02004043 static int resized = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004044
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004045# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00004046 if (fdDump)
4047 {
4048 fprintf(fdDump, "ResizeConBufAndWindow(%d, %d)\n", xSize, ySize);
4049 fflush(fdDump);
4050 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004051# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004052
Bram Moolenaar0f873732019-12-05 20:28:46 +01004053 // get the largest size we can size the console window to
Bram Moolenaar071d4272004-06-13 20:20:40 +00004054 coordScreen = GetLargestConsoleWindowSize(hConsole);
4055
Bram Moolenaar0f873732019-12-05 20:28:46 +01004056 // define the new console window size and scroll position
Bram Moolenaar071d4272004-06-13 20:20:40 +00004057 srWindowRect.Left = srWindowRect.Top = (SHORT) 0;
4058 srWindowRect.Right = (SHORT) (min(xSize, coordScreen.X) - 1);
4059 srWindowRect.Bottom = (SHORT) (min(ySize, coordScreen.Y) - 1);
4060
4061 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
4062 {
4063 int sx, sy;
4064
4065 sx = csbi.srWindow.Right - csbi.srWindow.Left + 1;
4066 sy = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
4067 if (sy < ySize || sx < xSize)
4068 {
4069 /*
4070 * Increasing number of lines/columns, do buffer first.
4071 * Use the maximal size in x and y direction.
4072 */
4073 if (sy < ySize)
4074 coordScreen.Y = ySize;
4075 else
4076 coordScreen.Y = sy;
4077 if (sx < xSize)
4078 coordScreen.X = xSize;
4079 else
4080 coordScreen.X = sx;
4081 SetConsoleScreenBufferSize(hConsole, coordScreen);
4082 }
4083 }
4084
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004085 // define the new console buffer size
Bram Moolenaar071d4272004-06-13 20:20:40 +00004086 coordScreen.X = xSize;
4087 coordScreen.Y = ySize;
4088
Bram Moolenaar2551c032018-08-23 22:38:31 +02004089 // In the new console call API, only the first time in reverse order
4090 if (!vtp_working || resized)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004091 {
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004092 ResizeWindow(hConsole, srWindowRect);
4093 ResizeConBuf(hConsole, coordScreen);
4094 }
4095 else
4096 {
Bram Moolenaarf49a6922019-07-15 20:37:05 +02004097 // Workaround for a Windows 10 bug
4098 cursor.X = srWindowRect.Left;
4099 cursor.Y = srWindowRect.Top;
4100 SetConsoleCursorPosition(hConsole, cursor);
4101
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004102 ResizeConBuf(hConsole, coordScreen);
4103 ResizeWindow(hConsole, srWindowRect);
Bram Moolenaar2551c032018-08-23 22:38:31 +02004104 resized = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004105 }
4106}
4107
4108
4109/*
4110 * Set the console window to `Rows' * `Columns'
4111 */
4112 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004113mch_set_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004114{
4115 COORD coordScreen;
4116
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004117# ifdef VIMDLL
4118 if (gui.in_use)
4119 return;
4120# endif
Bram Moolenaar0f873732019-12-05 20:28:46 +01004121 // Don't change window size while still starting up
Bram Moolenaar071d4272004-06-13 20:20:40 +00004122 if (suppress_winsize != 0)
4123 {
4124 suppress_winsize = 2;
4125 return;
4126 }
4127
4128 if (term_console)
4129 {
4130 coordScreen = GetLargestConsoleWindowSize(g_hConOut);
4131
Bram Moolenaar0f873732019-12-05 20:28:46 +01004132 // Clamp Rows and Columns to reasonable values
Bram Moolenaar071d4272004-06-13 20:20:40 +00004133 if (Rows > coordScreen.Y)
4134 Rows = coordScreen.Y;
4135 if (Columns > coordScreen.X)
4136 Columns = coordScreen.X;
4137
4138 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
4139 }
4140}
4141
4142/*
4143 * Rows and/or Columns has changed.
4144 */
4145 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004146mch_new_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004147{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004148# ifdef VIMDLL
4149 if (gui.in_use)
4150 return;
4151# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004152 set_scroll_region(0, 0, Columns - 1, Rows - 1);
4153}
4154
4155
4156/*
4157 * Called when started up, to set the winsize that was delayed.
4158 */
4159 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004160mch_set_winsize_now(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004161{
4162 if (suppress_winsize == 2)
4163 {
4164 suppress_winsize = 0;
4165 mch_set_shellsize();
4166 shell_resized();
4167 }
4168 suppress_winsize = 0;
4169}
Bram Moolenaar0f873732019-12-05 20:28:46 +01004170#endif // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00004171
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004172 static BOOL
4173vim_create_process(
Bram Moolenaar36c85b22013-12-12 20:25:44 +01004174 char *cmd,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004175 BOOL inherit_handles,
Bram Moolenaar3f1138e2014-01-05 13:29:26 +01004176 DWORD flags,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004177 STARTUPINFO *si,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004178 PROCESS_INFORMATION *pi,
4179 LPVOID *env,
4180 char *cwd)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004181{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004182 BOOL ret = FALSE;
4183 WCHAR *wcmd, *wcwd = NULL;
4184
4185 wcmd = enc_to_utf16((char_u *)cmd, NULL);
4186 if (wcmd == NULL)
4187 return FALSE;
4188 if (cwd != NULL)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004189 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004190 wcwd = enc_to_utf16((char_u *)cwd, NULL);
4191 if (wcwd == NULL)
4192 goto theend;
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004193 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004194
4195 ret = CreateProcessW(
4196 NULL, // Executable name
4197 wcmd, // Command to execute
4198 NULL, // Process security attributes
4199 NULL, // Thread security attributes
4200 inherit_handles, // Inherit handles
4201 flags, // Creation flags
4202 env, // Environment
4203 wcwd, // Current directory
4204 (LPSTARTUPINFOW)si, // Startup information
4205 pi); // Process information
4206theend:
4207 vim_free(wcmd);
4208 vim_free(wcwd);
4209 return ret;
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004210}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004211
4212
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004213 static HINSTANCE
4214vim_shell_execute(
4215 char *cmd,
4216 INT n_show_cmd)
4217{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004218 HINSTANCE ret;
4219 WCHAR *wcmd;
4220
4221 wcmd = enc_to_utf16((char_u *)cmd, NULL);
4222 if (wcmd == NULL)
4223 return (HINSTANCE) 0;
4224
4225 ret = ShellExecuteW(NULL, NULL, wcmd, NULL, NULL, n_show_cmd);
4226 vim_free(wcmd);
4227 return ret;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004228}
4229
4230
Bram Moolenaar4f974752019-02-17 17:44:42 +01004231#if defined(FEAT_GUI_MSWIN) || defined(PROTO)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004232
4233/*
4234 * Specialised version of system() for Win32 GUI mode.
4235 * This version proceeds as follows:
4236 * 1. Create a console window for use by the subprocess
4237 * 2. Run the subprocess (it gets the allocated console by default)
4238 * 3. Wait for the subprocess to terminate and get its exit code
4239 * 4. Prompt the user to press a key to close the console window
4240 */
4241 static int
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004242mch_system_classic(char *cmd, int options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004243{
4244 STARTUPINFO si;
4245 PROCESS_INFORMATION pi;
4246 DWORD ret = 0;
4247 HWND hwnd = GetFocus();
4248
4249 si.cb = sizeof(si);
4250 si.lpReserved = NULL;
4251 si.lpDesktop = NULL;
4252 si.lpTitle = NULL;
4253 si.dwFlags = STARTF_USESHOWWINDOW;
4254 /*
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004255 * It's nicer to run a filter command in a minimized window.
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01004256 * Don't activate the window to keep focus on Vim.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004257 */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004258 if (options & SHELL_DOOUT)
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01004259 si.wShowWindow = SW_SHOWMINNOACTIVE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004260 else
4261 si.wShowWindow = SW_SHOWNORMAL;
4262 si.cbReserved2 = 0;
4263 si.lpReserved2 = NULL;
4264
Bram Moolenaar0f873732019-12-05 20:28:46 +01004265 // Now, run the command
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004266 vim_create_process(cmd, FALSE,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004267 CREATE_DEFAULT_ERROR_MODE | CREATE_NEW_CONSOLE,
4268 &si, &pi, NULL, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004269
Bram Moolenaar0f873732019-12-05 20:28:46 +01004270 // Wait for the command to terminate before continuing
Bram Moolenaar071d4272004-06-13 20:20:40 +00004271 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004272# ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00004273 int delay = 1;
4274
Bram Moolenaar0f873732019-12-05 20:28:46 +01004275 // Keep updating the window while waiting for the shell to finish.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004276 for (;;)
4277 {
4278 MSG msg;
4279
K.Takatab7057bd2022-01-21 11:37:07 +00004280 if (PeekMessageW(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004281 {
4282 TranslateMessage(&msg);
K.Takatab7057bd2022-01-21 11:37:07 +00004283 DispatchMessageW(&msg);
Bram Moolenaare4195c52012-08-02 12:31:44 +02004284 delay = 1;
4285 continue;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004286 }
4287 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
4288 break;
4289
Bram Moolenaar0f873732019-12-05 20:28:46 +01004290 // We start waiting for a very short time and then increase it, so
4291 // that we respond quickly when the process is quick, and don't
4292 // consume too much overhead when it's slow.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004293 if (delay < 50)
4294 delay += 10;
4295 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004296# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004297 WaitForSingleObject(pi.hProcess, INFINITE);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004298# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004299
Bram Moolenaar0f873732019-12-05 20:28:46 +01004300 // Get the command exit code
Bram Moolenaar071d4272004-06-13 20:20:40 +00004301 GetExitCodeProcess(pi.hProcess, &ret);
4302 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004303
Bram Moolenaar0f873732019-12-05 20:28:46 +01004304 // Close the handles to the subprocess, so that it goes away
Bram Moolenaar071d4272004-06-13 20:20:40 +00004305 CloseHandle(pi.hThread);
4306 CloseHandle(pi.hProcess);
4307
Bram Moolenaar0f873732019-12-05 20:28:46 +01004308 // Try to get input focus back. Doesn't always work though.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004309 PostMessage(hwnd, WM_SETFOCUS, 0, 0);
4310
4311 return ret;
4312}
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004313
4314/*
4315 * Thread launched by the gui to send the current buffer data to the
4316 * process. This way avoid to hang up vim totally if the children
4317 * process take a long time to process the lines.
4318 */
Bram Moolenaar4c38d662016-08-03 20:54:57 +02004319 static unsigned int __stdcall
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004320sub_process_writer(LPVOID param)
4321{
4322 HANDLE g_hChildStd_IN_Wr = param;
4323 linenr_T lnum = curbuf->b_op_start.lnum;
4324 DWORD len = 0;
4325 DWORD l;
4326 char_u *lp = ml_get(lnum);
4327 char_u *s;
4328 int written = 0;
4329
4330 for (;;)
4331 {
4332 l = (DWORD)STRLEN(lp + written);
4333 if (l == 0)
4334 len = 0;
4335 else if (lp[written] == NL)
4336 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004337 // NL -> NUL translation
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004338 WriteFile(g_hChildStd_IN_Wr, "", 1, &len, NULL);
4339 }
4340 else
4341 {
4342 s = vim_strchr(lp + written, NL);
4343 WriteFile(g_hChildStd_IN_Wr, (char *)lp + written,
4344 s == NULL ? l : (DWORD)(s - (lp + written)),
4345 &len, NULL);
4346 }
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +01004347 if (len == l)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004348 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004349 // Finished a line, add a NL, unless this line should not have
4350 // one.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004351 if (lnum != curbuf->b_op_end.lnum
Bram Moolenaar34d72d42015-07-17 14:18:08 +02004352 || (!curbuf->b_p_bin
4353 && curbuf->b_p_fixeol)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004354 || (lnum != curbuf->b_no_eol_lnum
4355 && (lnum != curbuf->b_ml.ml_line_count
4356 || curbuf->b_p_eol)))
4357 {
Bram Moolenaar42335f52018-09-13 15:33:43 +02004358 WriteFile(g_hChildStd_IN_Wr, "\n", 1,
4359 (LPDWORD)&vim_ignored, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004360 }
4361
4362 ++lnum;
4363 if (lnum > curbuf->b_op_end.lnum)
4364 break;
4365
4366 lp = ml_get(lnum);
4367 written = 0;
4368 }
4369 else if (len > 0)
4370 written += len;
4371 }
4372
Bram Moolenaar0f873732019-12-05 20:28:46 +01004373 // finished all the lines, close pipe
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004374 CloseHandle(g_hChildStd_IN_Wr);
Bram Moolenaar86f2cd52016-08-02 21:55:17 +02004375 return 0;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004376}
4377
4378
Bram Moolenaar0f873732019-12-05 20:28:46 +01004379# define BUFLEN 100 // length for buffer, stolen from unix version
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004380
4381/*
4382 * This function read from the children's stdout and write the
4383 * data on screen or in the buffer accordingly.
4384 */
4385 static void
4386dump_pipe(int options,
4387 HANDLE g_hChildStd_OUT_Rd,
4388 garray_T *ga,
4389 char_u buffer[],
4390 DWORD *buffer_off)
4391{
4392 DWORD availableBytes = 0;
4393 DWORD i;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004394 int ret;
4395 DWORD len;
4396 DWORD toRead;
4397 int repeatCount;
4398
Bram Moolenaar0f873732019-12-05 20:28:46 +01004399 // we query the pipe to see if there is any data to read
4400 // to avoid to perform a blocking read
4401 ret = PeekNamedPipe(g_hChildStd_OUT_Rd, // pipe to query
4402 NULL, // optional buffer
4403 0, // buffer size
4404 NULL, // number of read bytes
4405 &availableBytes, // available bytes total
4406 NULL); // byteLeft
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004407
4408 repeatCount = 0;
Bram Moolenaar0f873732019-12-05 20:28:46 +01004409 // We got real data in the pipe, read it
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02004410 while (ret != 0 && availableBytes > 0)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004411 {
4412 repeatCount++;
Bram Moolenaara12a1612019-01-24 16:39:02 +01004413 toRead = (DWORD)(BUFLEN - *buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004414 toRead = availableBytes < toRead ? availableBytes : toRead;
Bram Moolenaara12a1612019-01-24 16:39:02 +01004415 ReadFile(g_hChildStd_OUT_Rd, buffer + *buffer_off, toRead , &len, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004416
Bram Moolenaar0f873732019-12-05 20:28:46 +01004417 // If we haven't read anything, there is a problem
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004418 if (len == 0)
4419 break;
4420
4421 availableBytes -= len;
4422
4423 if (options & SHELL_READ)
4424 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004425 // Do NUL -> NL translation, append NL separated
4426 // lines to the current buffer.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004427 for (i = 0; i < len; ++i)
4428 {
4429 if (buffer[i] == NL)
4430 append_ga_line(ga);
4431 else if (buffer[i] == NUL)
4432 ga_append(ga, NL);
4433 else
4434 ga_append(ga, buffer[i]);
4435 }
4436 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004437 else if (has_mbyte)
4438 {
4439 int l;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004440 int c;
4441 char_u *p;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004442
4443 len += *buffer_off;
4444 buffer[len] = NUL;
4445
Bram Moolenaar0f873732019-12-05 20:28:46 +01004446 // Check if the last character in buffer[] is
4447 // incomplete, keep these bytes for the next
4448 // round.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004449 for (p = buffer; p < buffer + len; p += l)
4450 {
Bram Moolenaard3c907b2016-08-17 21:32:09 +02004451 l = MB_CPTR2LEN(p);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004452 if (l == 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01004453 l = 1; // NUL byte?
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004454 else if (MB_BYTE2LEN(*p) != l)
4455 break;
4456 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01004457 if (p == buffer) // no complete character
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004458 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004459 // avoid getting stuck at an illegal byte
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004460 if (len >= 12)
4461 ++p;
4462 else
4463 {
4464 *buffer_off = len;
4465 return;
4466 }
4467 }
4468 c = *p;
4469 *p = NUL;
Bram Moolenaar32526b32019-01-19 17:43:09 +01004470 msg_puts((char *)buffer);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004471 if (p < buffer + len)
4472 {
4473 *p = c;
4474 *buffer_off = (DWORD)((buffer + len) - p);
4475 mch_memmove(buffer, p, *buffer_off);
4476 return;
4477 }
4478 *buffer_off = 0;
4479 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004480 else
4481 {
4482 buffer[len] = NUL;
Bram Moolenaar32526b32019-01-19 17:43:09 +01004483 msg_puts((char *)buffer);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004484 }
4485
4486 windgoto(msg_row, msg_col);
4487 cursor_on();
4488 out_flush();
4489 }
4490}
4491
4492/*
4493 * Version of system to use for windows NT > 5.0 (Win2K), use pipe
4494 * for communication and doesn't open any new window.
4495 */
4496 static int
4497mch_system_piped(char *cmd, int options)
4498{
4499 STARTUPINFO si;
4500 PROCESS_INFORMATION pi;
4501 DWORD ret = 0;
4502
4503 HANDLE g_hChildStd_IN_Rd = NULL;
4504 HANDLE g_hChildStd_IN_Wr = NULL;
4505 HANDLE g_hChildStd_OUT_Rd = NULL;
4506 HANDLE g_hChildStd_OUT_Wr = NULL;
4507
Bram Moolenaar0f873732019-12-05 20:28:46 +01004508 char_u buffer[BUFLEN + 1]; // reading buffer + size
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004509 DWORD len;
4510
Bram Moolenaar0f873732019-12-05 20:28:46 +01004511 // buffer used to receive keys
4512 char_u ta_buf[BUFLEN + 1]; // TypeAHead
4513 int ta_len = 0; // valid bytes in ta_buf[]
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004514
4515 DWORD i;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004516 int noread_cnt = 0;
4517 garray_T ga;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004518 int delay = 1;
Bram Moolenaar0f873732019-12-05 20:28:46 +01004519 DWORD buffer_off = 0; // valid bytes in buffer[]
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004520 char *p = NULL;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004521
4522 SECURITY_ATTRIBUTES saAttr;
4523
Bram Moolenaar0f873732019-12-05 20:28:46 +01004524 // Set the bInheritHandle flag so pipe handles are inherited.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004525 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
4526 saAttr.bInheritHandle = TRUE;
4527 saAttr.lpSecurityDescriptor = NULL;
4528
4529 if ( ! CreatePipe(&g_hChildStd_OUT_Rd, &g_hChildStd_OUT_Wr, &saAttr, 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01004530 // Ensure the read handle to the pipe for STDOUT is not inherited.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004531 || ! SetHandleInformation(g_hChildStd_OUT_Rd, HANDLE_FLAG_INHERIT, 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01004532 // Create a pipe for the child process's STDIN.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004533 || ! CreatePipe(&g_hChildStd_IN_Rd, &g_hChildStd_IN_Wr, &saAttr, 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01004534 // Ensure the write handle to the pipe for STDIN is not inherited.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004535 || ! SetHandleInformation(g_hChildStd_IN_Wr, HANDLE_FLAG_INHERIT, 0) )
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004536 {
4537 CloseHandle(g_hChildStd_IN_Rd);
4538 CloseHandle(g_hChildStd_IN_Wr);
4539 CloseHandle(g_hChildStd_OUT_Rd);
4540 CloseHandle(g_hChildStd_OUT_Wr);
Bram Moolenaar32526b32019-01-19 17:43:09 +01004541 msg_puts(_("\nCannot create pipes\n"));
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004542 }
4543
4544 si.cb = sizeof(si);
4545 si.lpReserved = NULL;
4546 si.lpDesktop = NULL;
4547 si.lpTitle = NULL;
4548 si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
4549
Bram Moolenaar0f873732019-12-05 20:28:46 +01004550 // set-up our file redirection
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004551 si.hStdError = g_hChildStd_OUT_Wr;
4552 si.hStdOutput = g_hChildStd_OUT_Wr;
4553 si.hStdInput = g_hChildStd_IN_Rd;
4554 si.wShowWindow = SW_HIDE;
4555 si.cbReserved2 = 0;
4556 si.lpReserved2 = NULL;
4557
4558 if (options & SHELL_READ)
4559 ga_init2(&ga, 1, BUFLEN);
4560
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004561 if (cmd != NULL)
4562 {
4563 p = (char *)vim_strsave((char_u *)cmd);
4564 if (p != NULL)
4565 unescape_shellxquote((char_u *)p, p_sxe);
4566 else
4567 p = cmd;
4568 }
4569
Bram Moolenaar0f873732019-12-05 20:28:46 +01004570 // Now, run the command.
4571 // About "Inherit handles" being TRUE: this command can be litigious,
4572 // handle inheritance was deactivated for pending temp file, but, if we
4573 // deactivate it, the pipes don't work for some reason.
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004574 vim_create_process(p, TRUE, CREATE_DEFAULT_ERROR_MODE,
4575 &si, &pi, NULL, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004576
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004577 if (p != cmd)
4578 vim_free(p);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004579
Bram Moolenaar0f873732019-12-05 20:28:46 +01004580 // Close our unused side of the pipes
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004581 CloseHandle(g_hChildStd_IN_Rd);
4582 CloseHandle(g_hChildStd_OUT_Wr);
4583
4584 if (options & SHELL_WRITE)
4585 {
Bram Moolenaar86f2cd52016-08-02 21:55:17 +02004586 HANDLE thread = (HANDLE)
Bram Moolenaar0f873732019-12-05 20:28:46 +01004587 _beginthreadex(NULL, // security attributes
4588 0, // default stack size
4589 sub_process_writer, // function to be executed
4590 g_hChildStd_IN_Wr, // parameter
4591 0, // creation flag, start immediately
4592 NULL); // we don't care about thread id
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004593 CloseHandle(thread);
4594 g_hChildStd_IN_Wr = NULL;
4595 }
4596
Bram Moolenaar0f873732019-12-05 20:28:46 +01004597 // Keep updating the window while waiting for the shell to finish.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004598 for (;;)
4599 {
4600 MSG msg;
4601
K.Takatab7057bd2022-01-21 11:37:07 +00004602 if (PeekMessageW(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004603 {
4604 TranslateMessage(&msg);
K.Takatab7057bd2022-01-21 11:37:07 +00004605 DispatchMessageW(&msg);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004606 }
4607
Bram Moolenaar0f873732019-12-05 20:28:46 +01004608 // write pipe information in the window
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004609 if ((options & (SHELL_READ|SHELL_WRITE))
4610# ifdef FEAT_GUI
4611 || gui.in_use
4612# endif
4613 )
4614 {
4615 len = 0;
4616 if (!(options & SHELL_EXPAND)
4617 && ((options &
4618 (SHELL_READ|SHELL_WRITE|SHELL_COOKED))
4619 != (SHELL_READ|SHELL_WRITE|SHELL_COOKED)
4620# ifdef FEAT_GUI
4621 || gui.in_use
4622# endif
4623 )
4624 && (ta_len > 0 || noread_cnt > 4))
4625 {
4626 if (ta_len == 0)
4627 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004628 // Get extra characters when we don't have any. Reset the
4629 // counter and timer.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004630 noread_cnt = 0;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004631 len = ui_inchar(ta_buf, BUFLEN, 10L, 0);
4632 }
4633 if (ta_len > 0 || len > 0)
4634 {
4635 /*
4636 * For pipes: Check for CTRL-C: send interrupt signal to
4637 * child. Check for CTRL-D: EOF, close pipe to child.
4638 */
4639 if (len == 1 && cmd != NULL)
4640 {
4641 if (ta_buf[ta_len] == Ctrl_C)
4642 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004643 // Learn what exit code is expected, for
4644 // now put 9 as SIGKILL
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004645 TerminateProcess(pi.hProcess, 9);
4646 }
4647 if (ta_buf[ta_len] == Ctrl_D)
4648 {
4649 CloseHandle(g_hChildStd_IN_Wr);
4650 g_hChildStd_IN_Wr = NULL;
4651 }
4652 }
4653
Bram Moolenaar2f7e1b82022-10-04 13:17:31 +01004654 len = term_replace_keycodes(ta_buf, ta_len, len);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004655
4656 /*
4657 * For pipes: echo the typed characters. For a pty this
4658 * does not seem to work.
4659 */
4660 for (i = ta_len; i < ta_len + len; ++i)
4661 {
4662 if (ta_buf[i] == '\n' || ta_buf[i] == '\b')
4663 msg_putchar(ta_buf[i]);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004664 else if (has_mbyte)
4665 {
4666 int l = (*mb_ptr2len)(ta_buf + i);
4667
4668 msg_outtrans_len(ta_buf + i, l);
4669 i += l - 1;
4670 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004671 else
4672 msg_outtrans_len(ta_buf + i, 1);
4673 }
4674 windgoto(msg_row, msg_col);
4675 out_flush();
4676
4677 ta_len += len;
4678
4679 /*
4680 * Write the characters to the child, unless EOF has been
4681 * typed for pipes. Write one character at a time, to
4682 * avoid losing too much typeahead. When writing buffer
4683 * lines, drop the typed characters (only check for
4684 * CTRL-C).
4685 */
4686 if (options & SHELL_WRITE)
4687 ta_len = 0;
4688 else if (g_hChildStd_IN_Wr != NULL)
4689 {
4690 WriteFile(g_hChildStd_IN_Wr, (char*)ta_buf,
4691 1, &len, NULL);
4692 // if we are typing in, we want to keep things reactive
4693 delay = 1;
4694 if (len > 0)
4695 {
4696 ta_len -= len;
4697 mch_memmove(ta_buf, ta_buf + len, ta_len);
4698 }
4699 }
4700 }
4701 }
4702 }
4703
4704 if (ta_len)
4705 ui_inchar_undo(ta_buf, ta_len);
4706
4707 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
4708 {
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004709 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004710 break;
4711 }
4712
4713 ++noread_cnt;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004714 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004715
Bram Moolenaar0f873732019-12-05 20:28:46 +01004716 // We start waiting for a very short time and then increase it, so
4717 // that we respond quickly when the process is quick, and don't
4718 // consume too much overhead when it's slow.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004719 if (delay < 50)
4720 delay += 10;
4721 }
4722
Bram Moolenaar0f873732019-12-05 20:28:46 +01004723 // Close the pipe
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004724 CloseHandle(g_hChildStd_OUT_Rd);
4725 if (g_hChildStd_IN_Wr != NULL)
4726 CloseHandle(g_hChildStd_IN_Wr);
4727
4728 WaitForSingleObject(pi.hProcess, INFINITE);
4729
Bram Moolenaar0f873732019-12-05 20:28:46 +01004730 // Get the command exit code
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004731 GetExitCodeProcess(pi.hProcess, &ret);
4732
4733 if (options & SHELL_READ)
4734 {
4735 if (ga.ga_len > 0)
4736 {
4737 append_ga_line(&ga);
Bram Moolenaar0f873732019-12-05 20:28:46 +01004738 // remember that the NL was missing
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004739 curbuf->b_no_eol_lnum = curwin->w_cursor.lnum;
4740 }
4741 else
4742 curbuf->b_no_eol_lnum = 0;
4743 ga_clear(&ga);
4744 }
4745
Bram Moolenaar0f873732019-12-05 20:28:46 +01004746 // Close the handles to the subprocess, so that it goes away
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004747 CloseHandle(pi.hThread);
4748 CloseHandle(pi.hProcess);
4749
4750 return ret;
4751}
4752
4753 static int
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004754mch_system_g(char *cmd, int options)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004755{
Bram Moolenaar0f873732019-12-05 20:28:46 +01004756 // if we can pipe and the shelltemp option is off
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004757 if (!p_stmp)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004758 return mch_system_piped(cmd, options);
4759 else
4760 return mch_system_classic(cmd, options);
4761}
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004762#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004763
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004764#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004765 static int
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02004766mch_system_c(char *cmd, int options UNUSED)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004767{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004768 int ret;
4769 WCHAR *wcmd;
Bram Moolenaar2efc44b2019-10-05 12:09:32 +02004770 char_u *buf;
4771 size_t len;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004772
Bram Moolenaar2efc44b2019-10-05 12:09:32 +02004773 // If the command starts and ends with double quotes, enclose the command
4774 // in parentheses.
4775 len = STRLEN(cmd);
4776 if (len >= 2 && cmd[0] == '"' && cmd[len - 1] == '"')
4777 {
4778 len += 3;
4779 buf = alloc(len);
4780 if (buf == NULL)
4781 return -1;
4782 vim_snprintf((char *)buf, len, "(%s)", cmd);
4783 wcmd = enc_to_utf16(buf, NULL);
4784 free(buf);
4785 }
4786 else
4787 wcmd = enc_to_utf16((char_u *)cmd, NULL);
4788
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004789 if (wcmd == NULL)
4790 return -1;
4791
4792 ret = _wsystem(wcmd);
4793 vim_free(wcmd);
4794 return ret;
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004795}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004796
4797#endif
4798
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004799 static int
4800mch_system(char *cmd, int options)
4801{
4802#ifdef VIMDLL
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02004803 if (gui.in_use || gui.starting)
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004804 return mch_system_g(cmd, options);
4805 else
4806 return mch_system_c(cmd, options);
4807#elif defined(FEAT_GUI_MSWIN)
4808 return mch_system_g(cmd, options);
4809#else
4810 return mch_system_c(cmd, options);
4811#endif
4812}
4813
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004814#if defined(FEAT_GUI) && defined(FEAT_TERMINAL)
4815/*
4816 * Use a terminal window to run a shell command in.
4817 */
4818 static int
4819mch_call_shell_terminal(
4820 char_u *cmd,
Bram Moolenaar0f873732019-12-05 20:28:46 +01004821 int options UNUSED) // SHELL_*, see vim.h
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004822{
4823 jobopt_T opt;
4824 char_u *newcmd = NULL;
4825 typval_T argvar[2];
4826 long_u cmdlen;
4827 int retval = -1;
4828 buf_T *buf;
Bram Moolenaarf9c38832018-06-19 19:59:20 +02004829 job_T *job;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004830 aco_save_T aco;
Bram Moolenaar0f873732019-12-05 20:28:46 +01004831 oparg_T oa; // operator arguments
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004832
Bram Moolenaar42f652f2018-03-19 21:44:37 +01004833 if (cmd == NULL)
4834 cmdlen = STRLEN(p_sh) + 1;
4835 else
4836 cmdlen = STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10;
Bram Moolenaar18a4ba22019-05-24 19:39:03 +02004837 newcmd = alloc(cmdlen);
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004838 if (newcmd == NULL)
4839 return 255;
Bram Moolenaar42f652f2018-03-19 21:44:37 +01004840 if (cmd == NULL)
4841 {
4842 STRCPY(newcmd, p_sh);
4843 ch_log(NULL, "starting terminal to run a shell");
4844 }
4845 else
4846 {
4847 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s", p_sh, p_shcf, cmd);
4848 ch_log(NULL, "starting terminal for system command '%s'", cmd);
4849 }
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004850
4851 init_job_options(&opt);
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004852
4853 argvar[0].v_type = VAR_STRING;
4854 argvar[0].vval.v_string = newcmd;
4855 argvar[1].v_type = VAR_UNKNOWN;
4856 buf = term_start(argvar, NULL, &opt, TERM_START_SYSTEM);
Bram Moolenaar81c3c89a2018-03-20 11:41:44 +01004857 if (buf == NULL)
Bram Moolenaar9029b912019-03-21 19:58:00 +01004858 {
4859 vim_free(newcmd);
Bram Moolenaar81c3c89a2018-03-20 11:41:44 +01004860 return 255;
Bram Moolenaar9029b912019-03-21 19:58:00 +01004861 }
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004862
Bram Moolenaarf9c38832018-06-19 19:59:20 +02004863 job = term_getjob(buf->b_term);
4864 ++job->jv_refcount;
4865
Bram Moolenaar0f873732019-12-05 20:28:46 +01004866 // Find a window to make "buf" curbuf.
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004867 aucmd_prepbuf(&aco, buf);
4868
4869 clear_oparg(&oa);
4870 while (term_use_loop())
4871 {
4872 if (oa.op_type == OP_NOP && oa.regname == NUL && !VIsual_active)
4873 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004874 // If terminal_loop() returns OK we got a key that is handled
4875 // in Normal model. We don't do redrawing anyway.
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004876 if (terminal_loop(TRUE) == OK)
4877 normal_cmd(&oa, TRUE);
4878 }
4879 else
4880 normal_cmd(&oa, TRUE);
4881 }
Bram Moolenaarf9c38832018-06-19 19:59:20 +02004882 retval = job->jv_exitval;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004883 ch_log(NULL, "system command finished");
4884
Bram Moolenaarf9c38832018-06-19 19:59:20 +02004885 job_unref(job);
4886
Bram Moolenaar0f873732019-12-05 20:28:46 +01004887 // restore curwin/curbuf and a few other things
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004888 aucmd_restbuf(&aco);
4889
4890 wait_return(TRUE);
4891 do_buffer(DOBUF_WIPE, DOBUF_FIRST, FORWARD, buf->b_fnum, TRUE);
4892
4893 vim_free(newcmd);
4894 return retval;
4895}
4896#endif
4897
Bram Moolenaar071d4272004-06-13 20:20:40 +00004898/*
4899 * Either execute a command by calling the shell or start a new shell
4900 */
4901 int
4902mch_call_shell(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004903 char_u *cmd,
Bram Moolenaar0f873732019-12-05 20:28:46 +01004904 int options) // SHELL_*, see vim.h
Bram Moolenaar071d4272004-06-13 20:20:40 +00004905{
4906 int x = 0;
4907 int tmode = cur_tmode;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004908 WCHAR szShellTitle[512];
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004909
Bram Moolenaarc9a9a0a2022-04-12 15:09:23 +01004910#ifdef FEAT_JOB_CHANNEL
4911 ch_log(NULL, "executing shell command: %s", cmd);
4912#endif
Bram Moolenaar0f873732019-12-05 20:28:46 +01004913 // Change the title to reflect that we are in a subshell.
K.Takataeeec2542021-06-02 13:28:16 +02004914 if (GetConsoleTitleW(szShellTitle, ARRAY_LENGTH(szShellTitle) - 4) > 0)
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004915 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004916 if (cmd == NULL)
4917 wcscat(szShellTitle, L" :sh");
4918 else
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004919 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004920 WCHAR *wn = enc_to_utf16((char_u *)cmd, NULL);
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004921
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004922 if (wn != NULL)
4923 {
4924 wcscat(szShellTitle, L" - !");
4925 if ((wcslen(szShellTitle) + wcslen(wn) <
K.Takataeeec2542021-06-02 13:28:16 +02004926 ARRAY_LENGTH(szShellTitle)))
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004927 wcscat(szShellTitle, wn);
4928 SetConsoleTitleW(szShellTitle);
4929 vim_free(wn);
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004930 }
4931 }
4932 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004933
4934 out_flush();
4935
4936#ifdef MCH_WRITE_DUMP
4937 if (fdDump)
4938 {
4939 fprintf(fdDump, "mch_call_shell(\"%s\", %d)\n", cmd, options);
4940 fflush(fdDump);
4941 }
4942#endif
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004943#if defined(FEAT_GUI) && defined(FEAT_TERMINAL)
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004944 // TODO: make the terminal window work with input or output redirected.
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004945 if (
4946# ifdef VIMDLL
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004947 gui.in_use &&
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004948# endif
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004949 vim_strchr(p_go, GO_TERMINAL) != NULL
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004950 && (options & (SHELL_FILTER|SHELL_DOOUT|SHELL_WRITE|SHELL_READ)) == 0)
4951 {
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004952 char_u *cmdbase = cmd;
4953
Bram Moolenaar4d5c1262019-09-20 17:20:02 +02004954 if (cmdbase != NULL)
4955 // Skip a leading quote and (.
4956 while (*cmdbase == '"' || *cmdbase == '(')
4957 ++cmdbase;
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004958
4959 // Check the command does not begin with "start "
Bram Moolenaar36e7a822019-11-13 21:49:24 +01004960 if (cmdbase == NULL || STRNICMP(cmdbase, "start", 5) != 0
4961 || !VIM_ISWHITE(cmdbase[5]))
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004962 {
4963 // Use a terminal window to run the command in.
4964 x = mch_call_shell_terminal(cmd, options);
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004965 resettitle();
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004966 return x;
4967 }
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004968 }
4969#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004970
4971 /*
4972 * Catch all deadly signals while running the external command, because a
4973 * CTRL-C, Ctrl-Break or illegal instruction might otherwise kill us.
4974 */
4975 signal(SIGINT, SIG_IGN);
4976#if defined(__GNUC__) && !defined(__MINGW32__)
4977 signal(SIGKILL, SIG_IGN);
4978#else
4979 signal(SIGBREAK, SIG_IGN);
4980#endif
4981 signal(SIGILL, SIG_IGN);
4982 signal(SIGFPE, SIG_IGN);
4983 signal(SIGSEGV, SIG_IGN);
4984 signal(SIGTERM, SIG_IGN);
4985 signal(SIGABRT, SIG_IGN);
4986
4987 if (options & SHELL_COOKED)
Bram Moolenaar0f873732019-12-05 20:28:46 +01004988 settmode(TMODE_COOK); // set to normal mode
Bram Moolenaar071d4272004-06-13 20:20:40 +00004989
4990 if (cmd == NULL)
4991 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004992 x = mch_system((char *)p_sh, options);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004993 }
4994 else
4995 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004996 // we use "command" or "cmd" to start the shell; slow but easy
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004997 char_u *newcmd = NULL;
4998 char_u *cmdbase = cmd;
4999 long_u cmdlen;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005000
Bram Moolenaar0f873732019-12-05 20:28:46 +01005001 // Skip a leading ", ( and "(.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005002 if (*cmdbase == '"' )
5003 ++cmdbase;
5004 if (*cmdbase == '(')
5005 ++cmdbase;
5006
Bram Moolenaar1c465442017-03-12 20:10:05 +01005007 if ((STRNICMP(cmdbase, "start", 5) == 0) && VIM_ISWHITE(cmdbase[5]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005008 {
5009 STARTUPINFO si;
5010 PROCESS_INFORMATION pi;
5011 DWORD flags = CREATE_NEW_CONSOLE;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01005012 INT n_show_cmd = SW_SHOWNORMAL;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005013 char_u *p;
5014
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01005015 ZeroMemory(&si, sizeof(si));
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005016 si.cb = sizeof(si);
5017 si.lpReserved = NULL;
5018 si.lpDesktop = NULL;
5019 si.lpTitle = NULL;
5020 si.dwFlags = 0;
5021 si.cbReserved2 = 0;
5022 si.lpReserved2 = NULL;
5023
5024 cmdbase = skipwhite(cmdbase + 5);
5025 if ((STRNICMP(cmdbase, "/min", 4) == 0)
Bram Moolenaar1c465442017-03-12 20:10:05 +01005026 && VIM_ISWHITE(cmdbase[4]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005027 {
5028 cmdbase = skipwhite(cmdbase + 4);
5029 si.dwFlags = STARTF_USESHOWWINDOW;
5030 si.wShowWindow = SW_SHOWMINNOACTIVE;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01005031 n_show_cmd = SW_SHOWMINNOACTIVE;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005032 }
5033 else if ((STRNICMP(cmdbase, "/b", 2) == 0)
Bram Moolenaar1c465442017-03-12 20:10:05 +01005034 && VIM_ISWHITE(cmdbase[2]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005035 {
5036 cmdbase = skipwhite(cmdbase + 2);
5037 flags = CREATE_NO_WINDOW;
5038 si.dwFlags = STARTF_USESTDHANDLES;
5039 si.hStdInput = CreateFile("\\\\.\\NUL", // File name
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005040 GENERIC_READ, // Access flags
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005041 0, // Share flags
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005042 NULL, // Security att.
5043 OPEN_EXISTING, // Open flags
5044 FILE_ATTRIBUTE_NORMAL, // File att.
5045 NULL); // Temp file
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005046 si.hStdOutput = si.hStdInput;
5047 si.hStdError = si.hStdInput;
5048 }
5049
Bram Moolenaar0f873732019-12-05 20:28:46 +01005050 // Remove a trailing ", ) and )" if they have a match
5051 // at the start of the command.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005052 if (cmdbase > cmd)
5053 {
5054 p = cmdbase + STRLEN(cmdbase);
5055 if (p > cmdbase && p[-1] == '"' && *cmd == '"')
5056 *--p = NUL;
5057 if (p > cmdbase && p[-1] == ')'
5058 && (*cmd =='(' || cmd[1] == '('))
5059 *--p = NUL;
5060 }
5061
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005062 newcmd = cmdbase;
5063 unescape_shellxquote(cmdbase, p_sxe);
5064
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005065 /*
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005066 * If creating new console, arguments are passed to the
5067 * 'cmd.exe' as-is. If it's not, arguments are not treated
5068 * correctly for current 'cmd.exe'. So unescape characters in
5069 * shellxescape except '|' for avoiding to be treated as
5070 * argument to them. Pass the arguments to sub-shell.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005071 */
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005072 if (flags != CREATE_NEW_CONSOLE)
5073 {
5074 char_u *subcmd;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01005075 char_u *cmd_shell = mch_getenv("COMSPEC");
5076
5077 if (cmd_shell == NULL || *cmd_shell == NUL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01005078 cmd_shell = (char_u *)default_shell();
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005079
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01005080 subcmd = vim_strsave_escaped_ext(cmdbase,
5081 (char_u *)"|", '^', FALSE);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005082 if (subcmd != NULL)
5083 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005084 // make "cmd.exe /c arguments"
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005085 cmdlen = STRLEN(cmd_shell) + STRLEN(subcmd) + 5;
Bram Moolenaar18a4ba22019-05-24 19:39:03 +02005086 newcmd = alloc(cmdlen);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005087 if (newcmd != NULL)
5088 vim_snprintf((char *)newcmd, cmdlen, "%s /c %s",
Bram Moolenaaree7d1002012-02-22 15:34:08 +01005089 cmd_shell, subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005090 else
5091 newcmd = cmdbase;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01005092 vim_free(subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005093 }
5094 }
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005095
5096 /*
5097 * Now, start the command as a process, so that it doesn't
5098 * inherit our handles which causes unpleasant dangling swap
5099 * files if we exit before the spawned process
5100 */
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005101 if (vim_create_process((char *)newcmd, FALSE, flags,
5102 &si, &pi, NULL, NULL))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005103 x = 0;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01005104 else if (vim_shell_execute((char *)newcmd, n_show_cmd)
5105 > (HINSTANCE)32)
5106 x = 0;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005107 else
5108 {
5109 x = -1;
Bram Moolenaar4f974752019-02-17 17:44:42 +01005110#ifdef FEAT_GUI_MSWIN
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005111# ifdef VIMDLL
5112 if (gui.in_use)
5113# endif
Bram Moolenaarac78dd42022-01-02 19:25:26 +00005114 emsg(_(e_command_not_found));
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005115#endif
5116 }
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005117
5118 if (newcmd != cmdbase)
5119 vim_free(newcmd);
5120
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01005121 if (si.dwFlags == STARTF_USESTDHANDLES && si.hStdInput != NULL)
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005122 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005123 // Close the handle to \\.\NUL created above.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005124 CloseHandle(si.hStdInput);
5125 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01005126 // Close the handles to the subprocess, so that it goes away
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005127 CloseHandle(pi.hThread);
5128 CloseHandle(pi.hProcess);
5129 }
5130 else
5131 {
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005132 cmdlen =
Bram Moolenaar4f974752019-02-17 17:44:42 +01005133#ifdef FEAT_GUI_MSWIN
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02005134 ((gui.in_use || gui.starting) ?
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005135 (!s_dont_use_vimrun && p_stmp ?
5136 STRLEN(vimrun_path) : STRLEN(p_sh) + STRLEN(p_shcf))
5137 : 0) +
Bram Moolenaar071d4272004-06-13 20:20:40 +00005138#endif
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005139 STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10;
Bram Moolenaar0fde2902008-03-16 13:54:13 +00005140
Bram Moolenaar18a4ba22019-05-24 19:39:03 +02005141 newcmd = alloc(cmdlen);
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005142 if (newcmd != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005143 {
Bram Moolenaar4f974752019-02-17 17:44:42 +01005144#if defined(FEAT_GUI_MSWIN)
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005145 if (
5146# ifdef VIMDLL
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02005147 (gui.in_use || gui.starting) &&
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005148# endif
5149 need_vimrun_warning)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005150 {
Bram Moolenaar63e43442016-11-19 17:28:44 +01005151 char *msg = _("VIMRUN.EXE not found in your $PATH.\n"
5152 "External commands will not pause after completion.\n"
5153 "See :help win32-vimrun for more information.");
5154 char *title = _("Vim Warning");
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005155 WCHAR *wmsg = enc_to_utf16((char_u *)msg, NULL);
5156 WCHAR *wtitle = enc_to_utf16((char_u *)title, NULL);
Bram Moolenaar63e43442016-11-19 17:28:44 +01005157
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005158 if (wmsg != NULL && wtitle != NULL)
5159 MessageBoxW(NULL, wmsg, wtitle, MB_ICONWARNING);
5160 vim_free(wmsg);
5161 vim_free(wtitle);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005162 need_vimrun_warning = FALSE;
5163 }
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005164 if (
5165# ifdef VIMDLL
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02005166 (gui.in_use || gui.starting) &&
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005167# endif
5168 !s_dont_use_vimrun && p_stmp)
Bram Moolenaarfcc4d922019-05-24 13:32:36 +02005169 // Use vimrun to execute the command. It opens a console
5170 // window, which can be closed without killing Vim.
Bram Moolenaarcc448b32010-07-14 16:52:17 +02005171 vim_snprintf((char *)newcmd, cmdlen, "%s%s%s %s %s",
Bram Moolenaar071d4272004-06-13 20:20:40 +00005172 vimrun_path,
5173 (msg_silent != 0 || (options & SHELL_DOOUT))
5174 ? "-s " : "",
5175 p_sh, p_shcf, cmd);
Bram Moolenaarfcc4d922019-05-24 13:32:36 +02005176 else if (
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005177# ifdef VIMDLL
Bram Moolenaarfcc4d922019-05-24 13:32:36 +02005178 (gui.in_use || gui.starting) &&
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005179# endif
Bram Moolenaar0e6bfb92019-07-31 20:53:56 +02005180 s_dont_use_vimrun && STRCMP(p_shcf, "/c") == 0)
Bram Moolenaarfcc4d922019-05-24 13:32:36 +02005181 // workaround for the case that "vimrun" does not exist
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005182 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s %s %s",
5183 p_sh, p_shcf, p_sh, p_shcf, cmd);
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005184 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00005185#endif
Bram Moolenaarcc448b32010-07-14 16:52:17 +02005186 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s",
Bram Moolenaar0fde2902008-03-16 13:54:13 +00005187 p_sh, p_shcf, cmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005188 x = mch_system((char *)newcmd, options);
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005189 vim_free(newcmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005190 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005191 }
5192 }
5193
5194 if (tmode == TMODE_RAW)
Bram Moolenaar3b1f18f2020-05-16 23:15:08 +02005195 {
5196 // The shell may have messed with the mode, always set it.
5197 cur_tmode = TMODE_UNKNOWN;
Bram Moolenaar0f873732019-12-05 20:28:46 +01005198 settmode(TMODE_RAW); // set to raw mode
Bram Moolenaar3b1f18f2020-05-16 23:15:08 +02005199 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005200
Bram Moolenaar0f873732019-12-05 20:28:46 +01005201 // Print the return value, unless "vimrun" was used.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005202 if (x != 0 && !(options & SHELL_SILENT) && !emsg_silent
Bram Moolenaar4f974752019-02-17 17:44:42 +01005203#if defined(FEAT_GUI_MSWIN)
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02005204 && ((gui.in_use || gui.starting) ?
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005205 ((options & SHELL_DOOUT) || s_dont_use_vimrun || !p_stmp) : 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005206#endif
5207 )
5208 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005209 smsg(_("shell returned %d"), x);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005210 msg_putchar('\n');
5211 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005212 resettitle();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005213
5214 signal(SIGINT, SIG_DFL);
5215#if defined(__GNUC__) && !defined(__MINGW32__)
5216 signal(SIGKILL, SIG_DFL);
5217#else
5218 signal(SIGBREAK, SIG_DFL);
5219#endif
5220 signal(SIGILL, SIG_DFL);
5221 signal(SIGFPE, SIG_DFL);
5222 signal(SIGSEGV, SIG_DFL);
5223 signal(SIGTERM, SIG_DFL);
5224 signal(SIGABRT, SIG_DFL);
5225
5226 return x;
5227}
5228
Bram Moolenaar509ce2a2016-03-11 22:52:15 +01005229#if defined(FEAT_JOB_CHANNEL) || defined(PROTO)
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005230 static HANDLE
5231job_io_file_open(
Bram Moolenaar972c3b82017-01-12 21:44:49 +01005232 char_u *fname,
5233 DWORD dwDesiredAccess,
5234 DWORD dwShareMode,
5235 LPSECURITY_ATTRIBUTES lpSecurityAttributes,
5236 DWORD dwCreationDisposition,
5237 DWORD dwFlagsAndAttributes)
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005238{
5239 HANDLE h;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005240 WCHAR *wn;
Bram Moolenaara12a1612019-01-24 16:39:02 +01005241
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005242 wn = enc_to_utf16(fname, NULL);
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005243 if (wn == NULL)
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005244 return INVALID_HANDLE_VALUE;
5245
5246 h = CreateFileW(wn, dwDesiredAccess, dwShareMode,
5247 lpSecurityAttributes, dwCreationDisposition,
5248 dwFlagsAndAttributes, NULL);
5249 vim_free(wn);
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005250 return h;
5251}
5252
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005253/*
5254 * Turn the dictionary "env" into a NUL separated list that can be used as the
5255 * environment argument of vim_create_process().
5256 */
Bram Moolenaarba6febd2017-10-30 21:56:23 +01005257 void
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005258win32_build_env(dict_T *env, garray_T *gap, int is_terminal)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005259{
5260 hashitem_T *hi;
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005261 long_u todo = env != NULL ? env->dv_hashtab.ht_used : 0;
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005262 LPVOID base = GetEnvironmentStringsW();
5263
Bram Moolenaar0f873732019-12-05 20:28:46 +01005264 // for last \0
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005265 if (ga_grow(gap, 1) == FAIL)
5266 return;
5267
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005268 if (env != NULL)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005269 {
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005270 for (hi = env->dv_hashtab.ht_array; todo > 0; ++hi)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005271 {
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005272 if (!HASHITEM_EMPTY(hi))
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005273 {
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005274 typval_T *item = &dict_lookup(hi)->di_tv;
5275 WCHAR *wkey = enc_to_utf16((char_u *)hi->hi_key, NULL);
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005276 WCHAR *wval = enc_to_utf16(tv_get_string(item), NULL);
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005277 --todo;
5278 if (wkey != NULL && wval != NULL)
5279 {
5280 size_t n;
5281 size_t lkey = wcslen(wkey);
5282 size_t lval = wcslen(wval);
Bram Moolenaar60104f12017-08-14 23:25:04 +02005283
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005284 if (ga_grow(gap, (int)(lkey + lval + 2)) != OK)
5285 continue;
5286 for (n = 0; n < lkey; n++)
5287 *((WCHAR*)gap->ga_data + gap->ga_len++) = wkey[n];
5288 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'=';
5289 for (n = 0; n < lval; n++)
5290 *((WCHAR*)gap->ga_data + gap->ga_len++) = wval[n];
5291 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5292 }
Bram Moolenaarbdace832019-03-02 10:13:42 +01005293 vim_free(wkey);
5294 vim_free(wval);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005295 }
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005296 }
5297 }
5298
Bram Moolenaar355757a2020-02-10 22:06:32 +01005299 if (base)
5300 {
5301 WCHAR *p = (WCHAR*) base;
5302
5303 // for last \0
5304 if (ga_grow(gap, 1) == FAIL)
5305 return;
5306
5307 while (*p != 0 || *(p + 1) != 0)
5308 {
5309 if (ga_grow(gap, 1) == OK)
5310 *((WCHAR*)gap->ga_data + gap->ga_len++) = *p;
5311 p++;
5312 }
5313 FreeEnvironmentStrings(base);
5314 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5315 }
5316
Bram Moolenaar493359e2018-06-12 20:25:52 +02005317# if defined(FEAT_CLIENTSERVER) || defined(FEAT_TERMINAL)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005318 {
Bram Moolenaar493359e2018-06-12 20:25:52 +02005319# ifdef FEAT_CLIENTSERVER
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005320 char_u *servername = get_vim_var_str(VV_SEND_SERVER);
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005321 size_t servername_len = STRLEN(servername);
Bram Moolenaar493359e2018-06-12 20:25:52 +02005322# endif
5323# ifdef FEAT_TERMINAL
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005324 char_u *version = get_vim_var_str(VV_VERSION);
5325 size_t version_len = STRLEN(version);
Bram Moolenaar493359e2018-06-12 20:25:52 +02005326# endif
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005327 // size of "VIM_SERVERNAME=" and value,
5328 // plus "VIM_TERMINAL=" and value,
5329 // plus two terminating NULs
5330 size_t n = 0
Bram Moolenaar493359e2018-06-12 20:25:52 +02005331# ifdef FEAT_CLIENTSERVER
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005332 + 15 + servername_len
Bram Moolenaar493359e2018-06-12 20:25:52 +02005333# endif
5334# ifdef FEAT_TERMINAL
5335 + 13 + version_len + 2
5336# endif
5337 ;
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005338
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005339 if (ga_grow(gap, (int)n) == OK)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005340 {
Bram Moolenaar493359e2018-06-12 20:25:52 +02005341# ifdef FEAT_CLIENTSERVER
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005342 for (n = 0; n < 15; n++)
5343 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5344 (WCHAR)"VIM_SERVERNAME="[n];
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005345 for (n = 0; n < servername_len; n++)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005346 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5347 (WCHAR)servername[n];
5348 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
Bram Moolenaar493359e2018-06-12 20:25:52 +02005349# endif
5350# ifdef FEAT_TERMINAL
5351 if (is_terminal)
5352 {
5353 for (n = 0; n < 13; n++)
5354 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5355 (WCHAR)"VIM_TERMINAL="[n];
5356 for (n = 0; n < version_len; n++)
5357 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5358 (WCHAR)version[n];
5359 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5360 }
5361# endif
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005362 }
5363 }
Bram Moolenaar79c6b512018-06-12 21:11:12 +02005364# endif
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005365}
5366
Bram Moolenaarb091f302019-01-19 14:37:00 +01005367/*
5368 * Create a pair of pipes.
5369 * Return TRUE for success, FALSE for failure.
5370 */
5371 static BOOL
5372create_pipe_pair(HANDLE handles[2])
5373{
5374 static LONG s;
5375 char name[64];
5376 SECURITY_ATTRIBUTES sa;
5377
5378 sprintf(name, "\\\\?\\pipe\\vim-%08lx-%08lx",
5379 GetCurrentProcessId(),
5380 InterlockedIncrement(&s));
5381
5382 // Create named pipe. Max size of named pipe is 65535.
5383 handles[1] = CreateNamedPipe(
5384 name,
5385 PIPE_ACCESS_OUTBOUND | FILE_FLAG_OVERLAPPED,
5386 PIPE_TYPE_BYTE | PIPE_NOWAIT,
Bram Moolenaar24058382019-01-24 23:11:49 +01005387 1, MAX_NAMED_PIPE_SIZE, 0, 0, NULL);
Bram Moolenaarb091f302019-01-19 14:37:00 +01005388
5389 if (handles[1] == INVALID_HANDLE_VALUE)
5390 return FALSE;
5391
5392 sa.nLength = sizeof(sa);
5393 sa.bInheritHandle = TRUE;
5394 sa.lpSecurityDescriptor = NULL;
5395
5396 handles[0] = CreateFile(name,
5397 FILE_GENERIC_READ,
5398 FILE_SHARE_READ, &sa,
5399 OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
5400
5401 if (handles[0] == INVALID_HANDLE_VALUE)
5402 {
Bram Moolenaar6982f422019-02-16 16:48:01 +01005403 CloseHandle(handles[1]);
Bram Moolenaarb091f302019-01-19 14:37:00 +01005404 return FALSE;
5405 }
5406
5407 return TRUE;
5408}
5409
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005410 void
Bram Moolenaar5a1feb82017-07-22 18:04:08 +02005411mch_job_start(char *cmd, job_T *job, jobopt_T *options)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005412{
5413 STARTUPINFO si;
5414 PROCESS_INFORMATION pi;
Bram Moolenaar14207f42016-10-27 21:13:10 +02005415 HANDLE jo;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005416 SECURITY_ATTRIBUTES saAttr;
5417 channel_T *channel = NULL;
Bram Moolenaard8070362016-02-15 21:56:54 +01005418 HANDLE ifd[2];
5419 HANDLE ofd[2];
5420 HANDLE efd[2];
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005421 garray_T ga;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005422
5423 int use_null_for_in = options->jo_io[PART_IN] == JIO_NULL;
5424 int use_null_for_out = options->jo_io[PART_OUT] == JIO_NULL;
5425 int use_null_for_err = options->jo_io[PART_ERR] == JIO_NULL;
5426 int use_file_for_in = options->jo_io[PART_IN] == JIO_FILE;
5427 int use_file_for_out = options->jo_io[PART_OUT] == JIO_FILE;
5428 int use_file_for_err = options->jo_io[PART_ERR] == JIO_FILE;
5429 int use_out_for_err = options->jo_io[PART_ERR] == JIO_OUT;
5430
5431 if (use_out_for_err && use_null_for_out)
5432 use_null_for_err = TRUE;
Bram Moolenaard8070362016-02-15 21:56:54 +01005433
5434 ifd[0] = INVALID_HANDLE_VALUE;
5435 ifd[1] = INVALID_HANDLE_VALUE;
5436 ofd[0] = INVALID_HANDLE_VALUE;
5437 ofd[1] = INVALID_HANDLE_VALUE;
5438 efd[0] = INVALID_HANDLE_VALUE;
5439 efd[1] = INVALID_HANDLE_VALUE;
Bram Moolenaar04935fb2022-01-08 16:19:22 +00005440 ga_init2(&ga, sizeof(wchar_t), 500);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005441
Bram Moolenaar14207f42016-10-27 21:13:10 +02005442 jo = CreateJobObject(NULL, NULL);
5443 if (jo == NULL)
5444 {
5445 job->jv_status = JOB_FAILED;
5446 goto failed;
5447 }
5448
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005449 if (options->jo_env != NULL)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005450 win32_build_env(options->jo_env, &ga, FALSE);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005451
Bram Moolenaar76467df2016-02-12 19:30:26 +01005452 ZeroMemory(&pi, sizeof(pi));
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005453 ZeroMemory(&si, sizeof(si));
5454 si.cb = sizeof(si);
Bram Moolenaard8070362016-02-15 21:56:54 +01005455 si.dwFlags |= STARTF_USESHOWWINDOW;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005456 si.wShowWindow = SW_HIDE;
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005457
Bram Moolenaard8070362016-02-15 21:56:54 +01005458 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
5459 saAttr.bInheritHandle = TRUE;
5460 saAttr.lpSecurityDescriptor = NULL;
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005461
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005462 if (use_file_for_in)
5463 {
5464 char_u *fname = options->jo_io_name[PART_IN];
5465
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005466 ifd[0] = job_io_file_open(fname, GENERIC_READ,
5467 FILE_SHARE_READ | FILE_SHARE_WRITE,
5468 &saAttr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL);
5469 if (ifd[0] == INVALID_HANDLE_VALUE)
Bram Moolenaar94d01912016-03-08 13:48:51 +01005470 {
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00005471 semsg(_(e_cant_open_file_str), fname);
Bram Moolenaar94d01912016-03-08 13:48:51 +01005472 goto failed;
5473 }
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005474 }
Bram Moolenaarb091f302019-01-19 14:37:00 +01005475 else if (!use_null_for_in
5476 && (!create_pipe_pair(ifd)
5477 || !SetHandleInformation(ifd[1], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005478 goto failed;
5479
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005480 if (use_file_for_out)
5481 {
5482 char_u *fname = options->jo_io_name[PART_OUT];
5483
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005484 ofd[1] = job_io_file_open(fname, GENERIC_WRITE,
5485 FILE_SHARE_READ | FILE_SHARE_WRITE,
5486 &saAttr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL);
5487 if (ofd[1] == INVALID_HANDLE_VALUE)
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005488 {
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00005489 semsg(_(e_cant_open_file_str), fname);
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005490 goto failed;
5491 }
5492 }
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005493 else if (!use_null_for_out &&
5494 (!CreatePipe(&ofd[0], &ofd[1], &saAttr, 0)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005495 || !SetHandleInformation(ofd[0], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005496 goto failed;
5497
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005498 if (use_file_for_err)
5499 {
5500 char_u *fname = options->jo_io_name[PART_ERR];
5501
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005502 efd[1] = job_io_file_open(fname, GENERIC_WRITE,
5503 FILE_SHARE_READ | FILE_SHARE_WRITE,
5504 &saAttr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL);
5505 if (efd[1] == INVALID_HANDLE_VALUE)
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005506 {
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00005507 semsg(_(e_cant_open_file_str), fname);
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005508 goto failed;
5509 }
5510 }
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005511 else if (!use_out_for_err && !use_null_for_err &&
5512 (!CreatePipe(&efd[0], &efd[1], &saAttr, 0)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005513 || !SetHandleInformation(efd[0], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaard8070362016-02-15 21:56:54 +01005514 goto failed;
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005515
Bram Moolenaard8070362016-02-15 21:56:54 +01005516 si.dwFlags |= STARTF_USESTDHANDLES;
5517 si.hStdInput = ifd[0];
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005518 si.hStdOutput = ofd[1];
5519 si.hStdError = use_out_for_err ? ofd[1] : efd[1];
5520
5521 if (!use_null_for_in || !use_null_for_out || !use_null_for_err)
5522 {
Bram Moolenaarde279892016-03-11 22:19:44 +01005523 if (options->jo_set & JO_CHANNEL)
5524 {
5525 channel = options->jo_channel;
5526 if (channel != NULL)
5527 ++channel->ch_refcount;
5528 }
5529 else
5530 channel = add_channel();
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005531 if (channel == NULL)
5532 goto failed;
5533 }
Bram Moolenaard8070362016-02-15 21:56:54 +01005534
5535 if (!vim_create_process(cmd, TRUE,
Bram Moolenaar14207f42016-10-27 21:13:10 +02005536 CREATE_SUSPENDED |
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005537 CREATE_DEFAULT_ERROR_MODE |
5538 CREATE_NEW_PROCESS_GROUP |
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005539 CREATE_UNICODE_ENVIRONMENT |
Bram Moolenaar76467df2016-02-12 19:30:26 +01005540 CREATE_NEW_CONSOLE,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005541 &si, &pi,
5542 ga.ga_data,
5543 (char *)options->jo_cwd))
Bram Moolenaar76467df2016-02-12 19:30:26 +01005544 {
Bram Moolenaar14207f42016-10-27 21:13:10 +02005545 CloseHandle(jo);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005546 job->jv_status = JOB_FAILED;
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005547 goto failed;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005548 }
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005549
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005550 ga_clear(&ga);
5551
Bram Moolenaar14207f42016-10-27 21:13:10 +02005552 if (!AssignProcessToJobObject(jo, pi.hProcess))
5553 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005554 // if failing, switch the way to terminate
5555 // process with TerminateProcess.
Bram Moolenaar14207f42016-10-27 21:13:10 +02005556 CloseHandle(jo);
5557 jo = NULL;
5558 }
5559 ResumeThread(pi.hThread);
Bram Moolenaar75578a32016-03-10 16:33:31 +01005560 CloseHandle(pi.hThread);
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005561 job->jv_proc_info = pi;
Bram Moolenaar14207f42016-10-27 21:13:10 +02005562 job->jv_job_object = jo;
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005563 job->jv_status = JOB_STARTED;
5564
Bram Moolenaar641ad6c2016-09-01 18:32:11 +02005565 CloseHandle(ifd[0]);
5566 CloseHandle(ofd[1]);
5567 if (!use_out_for_err && !use_null_for_err)
Bram Moolenaarc25558b2016-03-03 21:02:23 +01005568 CloseHandle(efd[1]);
Bram Moolenaard8070362016-02-15 21:56:54 +01005569
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005570 job->jv_channel = channel;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005571 if (channel != NULL)
5572 {
5573 channel_set_pipes(channel,
5574 use_file_for_in || use_null_for_in
5575 ? INVALID_FD : (sock_T)ifd[1],
5576 use_file_for_out || use_null_for_out
5577 ? INVALID_FD : (sock_T)ofd[0],
5578 use_out_for_err || use_file_for_err || use_null_for_err
5579 ? INVALID_FD : (sock_T)efd[0]);
5580 channel_set_job(channel, job, options);
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005581 }
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005582 return;
5583
5584failed:
Bram Moolenaard8070362016-02-15 21:56:54 +01005585 CloseHandle(ifd[0]);
5586 CloseHandle(ofd[0]);
5587 CloseHandle(efd[0]);
5588 CloseHandle(ifd[1]);
5589 CloseHandle(ofd[1]);
5590 CloseHandle(efd[1]);
Bram Moolenaarde279892016-03-11 22:19:44 +01005591 channel_unref(channel);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005592 ga_clear(&ga);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005593}
5594
5595 char *
5596mch_job_status(job_T *job)
5597{
5598 DWORD dwExitCode = 0;
5599
Bram Moolenaar76467df2016-02-12 19:30:26 +01005600 if (!GetExitCodeProcess(job->jv_proc_info.hProcess, &dwExitCode)
5601 || dwExitCode != STILL_ACTIVE)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005602 {
Bram Moolenaareab089d2016-02-21 19:32:02 +01005603 job->jv_exitval = (int)dwExitCode;
Bram Moolenaar7df915d2016-11-17 17:25:32 +01005604 if (job->jv_status < JOB_ENDED)
Bram Moolenaar97792de2016-10-15 18:36:49 +02005605 {
5606 ch_log(job->jv_channel, "Job ended");
5607 job->jv_status = JOB_ENDED;
5608 }
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005609 return "dead";
5610 }
5611 return "run";
5612}
5613
Bram Moolenaar97792de2016-10-15 18:36:49 +02005614 job_T *
5615mch_detect_ended_job(job_T *job_list)
5616{
5617 HANDLE jobHandles[MAXIMUM_WAIT_OBJECTS];
5618 job_T *jobArray[MAXIMUM_WAIT_OBJECTS];
5619 job_T *job = job_list;
5620
5621 while (job != NULL)
5622 {
5623 DWORD n;
5624 DWORD result;
5625
5626 for (n = 0; n < MAXIMUM_WAIT_OBJECTS
5627 && job != NULL; job = job->jv_next)
5628 {
5629 if (job->jv_status == JOB_STARTED)
5630 {
5631 jobHandles[n] = job->jv_proc_info.hProcess;
5632 jobArray[n] = job;
5633 ++n;
5634 }
5635 }
5636 if (n == 0)
5637 continue;
5638 result = WaitForMultipleObjects(n, jobHandles, FALSE, 0);
5639 if (result >= WAIT_OBJECT_0 && result < WAIT_OBJECT_0 + n)
5640 {
5641 job_T *wait_job = jobArray[result - WAIT_OBJECT_0];
5642
5643 if (STRCMP(mch_job_status(wait_job), "dead") == 0)
5644 return wait_job;
5645 }
5646 }
5647 return NULL;
5648}
5649
Bram Moolenaarfb630902016-10-29 14:55:00 +02005650 static BOOL
5651terminate_all(HANDLE process, int code)
5652{
5653 PROCESSENTRY32 pe;
5654 HANDLE h = INVALID_HANDLE_VALUE;
5655 DWORD pid = GetProcessId(process);
5656
5657 if (pid != 0)
5658 {
5659 h = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
5660 if (h != INVALID_HANDLE_VALUE)
5661 {
5662 pe.dwSize = sizeof(PROCESSENTRY32);
5663 if (!Process32First(h, &pe))
5664 goto theend;
5665
5666 do
5667 {
5668 if (pe.th32ParentProcessID == pid)
5669 {
5670 HANDLE ph = OpenProcess(
5671 PROCESS_ALL_ACCESS, FALSE, pe.th32ProcessID);
5672 if (ph != NULL)
5673 {
5674 terminate_all(ph, code);
5675 CloseHandle(ph);
5676 }
5677 }
5678 } while (Process32Next(h, &pe));
5679
5680 CloseHandle(h);
5681 }
5682 }
5683
5684theend:
5685 return TerminateProcess(process, code);
5686}
5687
5688/*
5689 * Send a (deadly) signal to "job".
5690 * Return FAIL if it didn't work.
5691 */
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005692 int
Bram Moolenaar2d33e902017-08-11 16:31:54 +02005693mch_signal_job(job_T *job, char_u *how)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005694{
Bram Moolenaar923d9262016-02-25 20:56:01 +01005695 int ret;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005696
Bram Moolenaar923d9262016-02-25 20:56:01 +01005697 if (STRCMP(how, "term") == 0 || STRCMP(how, "kill") == 0 || *how == NUL)
Bram Moolenaar76467df2016-02-12 19:30:26 +01005698 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005699 // deadly signal
Bram Moolenaar14207f42016-10-27 21:13:10 +02005700 if (job->jv_job_object != NULL)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005701 {
5702 if (job->jv_channel != NULL && job->jv_channel->ch_anonymous_pipe)
5703 job->jv_channel->ch_killing = TRUE;
K.Takata135e1522022-01-29 15:27:58 +00005704 return TerminateJobObject(job->jv_job_object, (UINT)-1) ? OK : FAIL;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005705 }
Bram Moolenaarb3e195c2020-02-10 21:32:19 +01005706 return terminate_all(job->jv_proc_info.hProcess, -1) ? OK : FAIL;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005707 }
5708
5709 if (!AttachConsole(job->jv_proc_info.dwProcessId))
5710 return FAIL;
5711 ret = GenerateConsoleCtrlEvent(
Bram Moolenaar923d9262016-02-25 20:56:01 +01005712 STRCMP(how, "int") == 0 ? CTRL_C_EVENT : CTRL_BREAK_EVENT,
5713 job->jv_proc_info.dwProcessId)
5714 ? OK : FAIL;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005715 FreeConsole();
5716 return ret;
5717}
5718
5719/*
5720 * Clear the data related to "job".
5721 */
5722 void
5723mch_clear_job(job_T *job)
5724{
5725 if (job->jv_status != JOB_FAILED)
5726 {
Bram Moolenaar14207f42016-10-27 21:13:10 +02005727 if (job->jv_job_object != NULL)
5728 CloseHandle(job->jv_job_object);
Bram Moolenaar76467df2016-02-12 19:30:26 +01005729 CloseHandle(job->jv_proc_info.hProcess);
5730 }
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005731}
5732#endif
5733
Bram Moolenaar071d4272004-06-13 20:20:40 +00005734
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005735#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005736
5737/*
5738 * Start termcap mode
5739 */
5740 static void
5741termcap_mode_start(void)
5742{
5743 DWORD cmodein;
5744
5745 if (g_fTermcapMode)
5746 return;
5747
Bram Moolenaar81ccbf12020-04-15 21:05:30 +02005748 if (!p_rs && USE_VTP)
5749 vtp_printf("\033[?1049h");
5750
Bram Moolenaar071d4272004-06-13 20:20:40 +00005751 SaveConsoleBuffer(&g_cbNonTermcap);
5752
5753 if (g_cbTermcap.IsValid)
5754 {
5755 /*
5756 * We've been in termcap mode before. Restore certain screen
5757 * characteristics, including the buffer size and the window
5758 * size. Since we will be redrawing the screen, we don't need
5759 * to restore the actual contents of the buffer.
5760 */
5761 RestoreConsoleBuffer(&g_cbTermcap, FALSE);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005762 reset_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005763 SetConsoleWindowInfo(g_hConOut, TRUE, &g_cbTermcap.Info.srWindow);
5764 Rows = g_cbTermcap.Info.dwSize.Y;
5765 Columns = g_cbTermcap.Info.dwSize.X;
5766 }
5767 else
5768 {
5769 /*
5770 * This is our first time entering termcap mode. Clear the console
5771 * screen buffer, and resize the buffer to match the current window
5772 * size. We will use this as the size of our editing environment.
5773 */
5774 ClearConsoleBuffer(g_attrCurrent);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005775 set_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005776 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
5777 }
5778
Bram Moolenaar071d4272004-06-13 20:20:40 +00005779 resettitle();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005780
5781 GetConsoleMode(g_hConIn, &cmodein);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005782 if (g_fMouseActive)
Wez Furlong6ef5ab52021-05-30 19:29:41 +02005783 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00005784 cmodein |= ENABLE_MOUSE_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02005785 cmodein &= ~ENABLE_QUICK_EDIT_MODE;
5786 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005787 else
Wez Furlong6ef5ab52021-05-30 19:29:41 +02005788 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00005789 cmodein &= ~ENABLE_MOUSE_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02005790 cmodein |= g_cmodein & ENABLE_QUICK_EDIT_MODE;
5791 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005792 cmodein |= ENABLE_WINDOW_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02005793 SetConsoleMode(g_hConIn, cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005794
5795 redraw_later_clear();
5796 g_fTermcapMode = TRUE;
5797}
5798
5799
5800/*
5801 * End termcap mode
5802 */
5803 static void
5804termcap_mode_end(void)
5805{
5806 DWORD cmodein;
5807 ConsoleBuffer *cb;
5808 COORD coord;
5809 DWORD dwDummy;
5810
5811 if (!g_fTermcapMode)
5812 return;
5813
5814 SaveConsoleBuffer(&g_cbTermcap);
5815
5816 GetConsoleMode(g_hConIn, &cmodein);
5817 cmodein &= ~(ENABLE_MOUSE_INPUT | ENABLE_WINDOW_INPUT);
Wez Furlong6ef5ab52021-05-30 19:29:41 +02005818 cmodein |= g_cmodein & ENABLE_QUICK_EDIT_MODE;
5819 SetConsoleMode(g_hConIn, cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005820
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01005821# ifdef FEAT_RESTORE_ORIG_SCREEN
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01005822 cb = exiting ? &g_cbOrig : &g_cbNonTermcap;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01005823# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00005824 cb = &g_cbNonTermcap;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01005825# endif
Bram Moolenaar81ccbf12020-04-15 21:05:30 +02005826 RestoreConsoleBuffer(cb, p_rs);
Bram Moolenaardf543822020-01-30 11:53:59 +01005827 restore_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005828 SetConsoleCursorInfo(g_hConOut, &g_cci);
5829
5830 if (p_rs || exiting)
5831 {
5832 /*
5833 * Clear anything that happens to be on the current line.
5834 */
5835 coord.X = 0;
5836 coord.Y = (SHORT) (p_rs ? cb->Info.dwCursorPosition.Y : (Rows - 1));
5837 FillConsoleOutputCharacter(g_hConOut, ' ',
5838 cb->Info.dwSize.X, coord, &dwDummy);
5839 /*
5840 * The following is just for aesthetics. If we are exiting without
5841 * restoring the screen, then we want to have a prompt string
5842 * appear at the bottom line. However, the command interpreter
5843 * seems to always advance the cursor one line before displaying
5844 * the prompt string, which causes the screen to scroll. To
5845 * counter this, move the cursor up one line before exiting.
5846 */
5847 if (exiting && !p_rs)
5848 coord.Y--;
5849 /*
5850 * Position the cursor at the leftmost column of the desired row.
5851 */
Bram Moolenaar81ccbf12020-04-15 21:05:30 +02005852 SetConsoleCursorPosition(g_hConOut, coord);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005853 }
5854
Bram Moolenaar81ccbf12020-04-15 21:05:30 +02005855 if (!p_rs && USE_VTP)
Bram Moolenaar0afdcf82020-04-01 18:29:10 +02005856 vtp_printf("\033[?1049l");
5857
Bram Moolenaar071d4272004-06-13 20:20:40 +00005858 g_fTermcapMode = FALSE;
5859}
Bram Moolenaar0f873732019-12-05 20:28:46 +01005860#endif // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00005861
5862
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005863#if defined(FEAT_GUI_MSWIN) && !defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005864 void
5865mch_write(
Bram Moolenaar1266d672017-02-01 13:43:36 +01005866 char_u *s UNUSED,
5867 int len UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005868{
Bram Moolenaar0f873732019-12-05 20:28:46 +01005869 // never used
Bram Moolenaar071d4272004-06-13 20:20:40 +00005870}
5871
5872#else
5873
5874/*
5875 * clear `n' chars, starting from `coord'
5876 */
5877 static void
5878clear_chars(
5879 COORD coord,
5880 DWORD n)
5881{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005882 if (!USE_VTP)
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02005883 {
5884 DWORD dwDummy;
5885
5886 FillConsoleOutputCharacter(g_hConOut, ' ', n, coord, &dwDummy);
5887 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, n, coord,
5888 &dwDummy);
5889 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005890 else
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02005891 {
5892 set_console_color_rgb();
5893 gotoxy(coord.X + 1, coord.Y + 1);
5894 vtp_printf("\033[%dX", n);
5895 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005896}
5897
5898
5899/*
5900 * Clear the screen
5901 */
5902 static void
5903clear_screen(void)
5904{
5905 g_coord.X = g_coord.Y = 0;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005906
5907 if (!USE_VTP)
5908 clear_chars(g_coord, Rows * Columns);
5909 else
5910 {
5911 set_console_color_rgb();
5912 gotoxy(1, 1);
5913 vtp_printf("\033[2J");
5914 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005915}
5916
5917
5918/*
5919 * Clear to end of display
5920 */
5921 static void
5922clear_to_end_of_display(void)
5923{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005924 COORD save = g_coord;
5925
5926 if (!USE_VTP)
5927 clear_chars(g_coord, (Rows - g_coord.Y - 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005928 * Columns + (Columns - g_coord.X));
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005929 else
5930 {
5931 set_console_color_rgb();
5932 gotoxy(g_coord.X + 1, g_coord.Y + 1);
5933 vtp_printf("\033[0J");
5934
5935 gotoxy(save.X + 1, save.Y + 1);
5936 g_coord = save;
5937 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005938}
5939
5940
5941/*
5942 * Clear to end of line
5943 */
5944 static void
5945clear_to_end_of_line(void)
5946{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005947 COORD save = g_coord;
5948
5949 if (!USE_VTP)
5950 clear_chars(g_coord, Columns - g_coord.X);
5951 else
5952 {
5953 set_console_color_rgb();
5954 gotoxy(g_coord.X + 1, g_coord.Y + 1);
5955 vtp_printf("\033[0K");
5956
5957 gotoxy(save.X + 1, save.Y + 1);
5958 g_coord = save;
5959 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005960}
5961
5962
5963/*
5964 * Scroll the scroll region up by `cLines' lines
5965 */
5966 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005967scroll(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005968{
5969 COORD oldcoord = g_coord;
5970
5971 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
5972 delete_lines(cLines);
5973
5974 g_coord = oldcoord;
5975}
5976
5977
5978/*
5979 * Set the scroll region
5980 */
5981 static void
5982set_scroll_region(
5983 unsigned left,
5984 unsigned top,
5985 unsigned right,
5986 unsigned bottom)
5987{
5988 if (left >= right
5989 || top >= bottom
5990 || right > (unsigned) Columns - 1
5991 || bottom > (unsigned) Rows - 1)
5992 return;
5993
5994 g_srScrollRegion.Left = left;
5995 g_srScrollRegion.Top = top;
5996 g_srScrollRegion.Right = right;
5997 g_srScrollRegion.Bottom = bottom;
Bram Moolenaar6982f422019-02-16 16:48:01 +01005998}
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005999
Bram Moolenaar6982f422019-02-16 16:48:01 +01006000 static void
6001set_scroll_region_tb(
6002 unsigned top,
6003 unsigned bottom)
6004{
6005 if (top >= bottom || bottom > (unsigned)Rows - 1)
6006 return;
6007
6008 g_srScrollRegion.Top = top;
6009 g_srScrollRegion.Bottom = bottom;
6010}
6011
6012 static void
6013set_scroll_region_lr(
6014 unsigned left,
6015 unsigned right)
6016{
6017 if (left >= right || right > (unsigned)Columns - 1)
6018 return;
6019
6020 g_srScrollRegion.Left = left;
6021 g_srScrollRegion.Right = right;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006022}
6023
6024
6025/*
6026 * Insert `cLines' lines at the current cursor position
6027 */
6028 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006029insert_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006030{
Bram Moolenaar6982f422019-02-16 16:48:01 +01006031 SMALL_RECT source, clip;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006032 COORD dest;
6033 CHAR_INFO fill;
6034
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006035 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
6036
Bram Moolenaar6982f422019-02-16 16:48:01 +01006037 dest.X = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006038 dest.Y = g_coord.Y + cLines;
6039
Bram Moolenaar6982f422019-02-16 16:48:01 +01006040 source.Left = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006041 source.Top = g_coord.Y;
6042 source.Right = g_srScrollRegion.Right;
6043 source.Bottom = g_srScrollRegion.Bottom - cLines;
6044
Bram Moolenaar6982f422019-02-16 16:48:01 +01006045 clip.Left = g_srScrollRegion.Left;
6046 clip.Top = g_coord.Y;
6047 clip.Right = g_srScrollRegion.Right;
6048 clip.Bottom = g_srScrollRegion.Bottom;
6049
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006050 fill.Char.AsciiChar = ' ';
6051 if (!USE_VTP)
6052 fill.Attributes = g_attrCurrent;
6053 else
6054 fill.Attributes = g_attrDefault;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006055
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006056 set_console_color_rgb();
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006057
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006058 ScrollConsoleScreenBuffer(g_hConOut, &source, &clip, dest, &fill);
6059
Bram Moolenaar6982f422019-02-16 16:48:01 +01006060 // Here we have to deal with a win32 console flake: If the scroll
6061 // region looks like abc and we scroll c to a and fill with d we get
6062 // cbd... if we scroll block c one line at a time to a, we get cdd...
6063 // vim expects cdd consistently... So we have to deal with that
6064 // here... (this also occurs scrolling the same way in the other
6065 // direction).
Bram Moolenaar071d4272004-06-13 20:20:40 +00006066
6067 if (source.Bottom < dest.Y)
6068 {
6069 COORD coord;
Bram Moolenaar6982f422019-02-16 16:48:01 +01006070 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006071
Bram Moolenaar6982f422019-02-16 16:48:01 +01006072 coord.X = source.Left;
6073 for (i = clip.Top; i < dest.Y; ++i)
6074 {
6075 coord.Y = i;
6076 clear_chars(coord, source.Right - source.Left + 1);
6077 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006078 }
Bram Moolenaar06b7b582020-05-30 17:49:25 +02006079
6080 if (USE_WT)
6081 {
6082 COORD coord;
6083 int i;
6084
6085 coord.X = source.Left;
6086 for (i = source.Top; i < dest.Y; ++i)
6087 {
6088 coord.Y = i;
6089 clear_chars(coord, source.Right - source.Left + 1);
6090 }
6091 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006092}
6093
6094
6095/*
6096 * Delete `cLines' lines at the current cursor position
6097 */
6098 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006099delete_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006100{
Bram Moolenaar6982f422019-02-16 16:48:01 +01006101 SMALL_RECT source, clip;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006102 COORD dest;
6103 CHAR_INFO fill;
6104 int nb;
6105
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006106 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
6107
Bram Moolenaar6982f422019-02-16 16:48:01 +01006108 dest.X = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006109 dest.Y = g_coord.Y;
6110
Bram Moolenaar6982f422019-02-16 16:48:01 +01006111 source.Left = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006112 source.Top = g_coord.Y + cLines;
6113 source.Right = g_srScrollRegion.Right;
6114 source.Bottom = g_srScrollRegion.Bottom;
6115
Bram Moolenaar6982f422019-02-16 16:48:01 +01006116 clip.Left = g_srScrollRegion.Left;
6117 clip.Top = g_coord.Y;
6118 clip.Right = g_srScrollRegion.Right;
6119 clip.Bottom = g_srScrollRegion.Bottom;
6120
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006121 fill.Char.AsciiChar = ' ';
6122 if (!USE_VTP)
6123 fill.Attributes = g_attrCurrent;
6124 else
6125 fill.Attributes = g_attrDefault;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006126
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006127 set_console_color_rgb();
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006128
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006129 ScrollConsoleScreenBuffer(g_hConOut, &source, &clip, dest, &fill);
6130
Bram Moolenaar6982f422019-02-16 16:48:01 +01006131 // Here we have to deal with a win32 console flake; See insert_lines()
6132 // above.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006133
6134 nb = dest.Y + (source.Bottom - source.Top) + 1;
6135
6136 if (nb < source.Top)
6137 {
6138 COORD coord;
Bram Moolenaar6982f422019-02-16 16:48:01 +01006139 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006140
Bram Moolenaar6982f422019-02-16 16:48:01 +01006141 coord.X = source.Left;
6142 for (i = nb; i < clip.Bottom; ++i)
6143 {
6144 coord.Y = i;
6145 clear_chars(coord, source.Right - source.Left + 1);
6146 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006147 }
Bram Moolenaar06b7b582020-05-30 17:49:25 +02006148
6149 if (USE_WT)
6150 {
6151 COORD coord;
6152 int i;
6153
6154 coord.X = source.Left;
6155 for (i = nb; i <= source.Bottom; ++i)
6156 {
6157 coord.Y = i;
6158 clear_chars(coord, source.Right - source.Left + 1);
6159 }
6160 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006161}
6162
6163
6164/*
Bram Moolenaar2313b612019-09-27 14:14:32 +02006165 * Set the cursor position to (x,y) (1-based).
Bram Moolenaar071d4272004-06-13 20:20:40 +00006166 */
6167 static void
6168gotoxy(
6169 unsigned x,
6170 unsigned y)
6171{
6172 if (x < 1 || x > (unsigned)Columns || y < 1 || y > (unsigned)Rows)
6173 return;
6174
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006175 if (!USE_VTP)
Bram Moolenaar2313b612019-09-27 14:14:32 +02006176 {
Bram Moolenaar82e743c2020-03-26 15:39:53 +01006177 // There are reports of double-width characters not displayed
6178 // correctly. This workaround should fix it, similar to how it's done
6179 // for VTP.
6180 g_coord.X = 0;
6181 SetConsoleCursorPosition(g_hConOut, g_coord);
6182
Bram Moolenaar2313b612019-09-27 14:14:32 +02006183 // external cursor coords are 1-based; internal are 0-based
6184 g_coord.X = x - 1;
6185 g_coord.Y = y - 1;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006186 SetConsoleCursorPosition(g_hConOut, g_coord);
Bram Moolenaar2313b612019-09-27 14:14:32 +02006187 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006188 else
Bram Moolenaar2313b612019-09-27 14:14:32 +02006189 {
6190 // Move the cursor to the left edge of the screen to prevent screen
Bram Moolenaara1299742019-10-10 16:36:00 +02006191 // destruction. Insider build bug. Always enabled because it's cheap
6192 // and avoids mistakes with recognizing the build.
6193 vtp_printf("\033[%d;%dH", g_coord.Y + 1, 1);
Bram Moolenaar2313b612019-09-27 14:14:32 +02006194
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006195 vtp_printf("\033[%d;%dH", y, x);
Bram Moolenaar2313b612019-09-27 14:14:32 +02006196
6197 g_coord.X = x - 1;
6198 g_coord.Y = y - 1;
6199 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006200}
6201
6202
6203/*
6204 * Set the current text attribute = (foreground | background)
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006205 * See ../runtime/doc/os_win32.txt for the numbers.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006206 */
6207 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006208textattr(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006209{
Bram Moolenaar6383b922015-03-24 17:12:19 +01006210 g_attrCurrent = wAttr & 0xff;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006211
6212 SetConsoleTextAttribute(g_hConOut, wAttr);
6213}
6214
6215
6216 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006217textcolor(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006218{
Bram Moolenaar6383b922015-03-24 17:12:19 +01006219 g_attrCurrent = (g_attrCurrent & 0xf0) + (wAttr & 0x0f);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006220
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006221 if (!USE_VTP)
6222 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
6223 else
6224 vtp_sgr_bulk(wAttr);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006225}
6226
6227
6228 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006229textbackground(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006230{
Bram Moolenaar6383b922015-03-24 17:12:19 +01006231 g_attrCurrent = (g_attrCurrent & 0x0f) + ((wAttr & 0x0f) << 4);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006232
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006233 if (!USE_VTP)
6234 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
6235 else
6236 vtp_sgr_bulk(wAttr);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006237}
6238
6239
6240/*
6241 * restore the default text attribute (whatever we started with)
6242 */
6243 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006244normvideo(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006245{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006246 if (!USE_VTP)
6247 textattr(g_attrDefault);
6248 else
6249 vtp_sgr_bulk(0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006250}
6251
6252
6253static WORD g_attrPreStandout = 0;
6254
6255/*
6256 * Make the text standout, by brightening it
6257 */
6258 static void
6259standout(void)
6260{
6261 g_attrPreStandout = g_attrCurrent;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006262
Bram Moolenaar071d4272004-06-13 20:20:40 +00006263 textattr((WORD) (g_attrCurrent|FOREGROUND_INTENSITY|BACKGROUND_INTENSITY));
6264}
6265
6266
6267/*
6268 * Turn off standout mode
6269 */
6270 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006271standend(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006272{
6273 if (g_attrPreStandout)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006274 textattr(g_attrPreStandout);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006275
6276 g_attrPreStandout = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006277}
6278
6279
6280/*
Bram Moolenaarff1d0d42007-05-10 17:24:16 +00006281 * Set normal fg/bg color, based on T_ME. Called when t_me has been set.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006282 */
6283 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006284mch_set_normal_colors(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006285{
6286 char_u *p;
6287 int n;
6288
6289 cterm_normal_fg_color = (g_attrDefault & 0xf) + 1;
6290 cterm_normal_bg_color = ((g_attrDefault >> 4) & 0xf) + 1;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006291 if (
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006292# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006293 !p_tgc &&
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006294# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006295 T_ME[0] == ESC && T_ME[1] == '|')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006296 {
6297 p = T_ME + 2;
6298 n = getdigits(&p);
6299 if (*p == 'm' && n > 0)
6300 {
6301 cterm_normal_fg_color = (n & 0xf) + 1;
6302 cterm_normal_bg_color = ((n >> 4) & 0xf) + 1;
6303 }
6304 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006305# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006306 cterm_normal_fg_gui_color = INVALCOLOR;
6307 cterm_normal_bg_gui_color = INVALCOLOR;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006308# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006309}
6310
6311
6312/*
6313 * visual bell: flash the screen
6314 */
6315 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006316visual_bell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006317{
6318 COORD coordOrigin = {0, 0};
6319 WORD attrFlash = ~g_attrCurrent & 0xff;
6320
6321 DWORD dwDummy;
Bram Moolenaarc799fe22019-05-28 23:08:19 +02006322 LPWORD oldattrs = ALLOC_MULT(WORD, Rows * Columns);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006323
6324 if (oldattrs == NULL)
6325 return;
6326 ReadConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
6327 coordOrigin, &dwDummy);
6328 FillConsoleOutputAttribute(g_hConOut, attrFlash, Rows * Columns,
6329 coordOrigin, &dwDummy);
6330
Bram Moolenaar0f873732019-12-05 20:28:46 +01006331 Sleep(15); // wait for 15 msec
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006332 if (!USE_VTP)
6333 WriteConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
Bram Moolenaar071d4272004-06-13 20:20:40 +00006334 coordOrigin, &dwDummy);
6335 vim_free(oldattrs);
6336}
6337
6338
6339/*
6340 * Make the cursor visible or invisible
6341 */
6342 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006343cursor_visible(BOOL fVisible)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006344{
6345 s_cursor_visible = fVisible;
Bram Moolenaar2695de62020-04-17 21:13:01 +02006346
6347 if (USE_VTP)
6348 vtp_printf("\033[?25%c", fVisible ? 'h' : 'l');
6349
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006350# ifdef MCH_CURSOR_SHAPE
Bram Moolenaar071d4272004-06-13 20:20:40 +00006351 mch_update_cursor();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006352# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006353}
6354
6355
6356/*
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02006357 * Write "cbToWrite" bytes in `pchBuf' to the screen.
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006358 * Returns the number of bytes actually written (at least one).
Bram Moolenaar071d4272004-06-13 20:20:40 +00006359 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006360 static DWORD
Bram Moolenaar071d4272004-06-13 20:20:40 +00006361write_chars(
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006362 char_u *pchBuf,
6363 DWORD cbToWrite)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006364{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006365 COORD coord = g_coord;
6366 DWORD written;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006367 DWORD n, cchwritten;
6368 static DWORD cells;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006369 static WCHAR *unicodebuf = NULL;
6370 static int unibuflen = 0;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006371 static int length;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006372 int cp = enc_utf8 ? CP_UTF8 : enc_codepage;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006373 static WCHAR *utf8spbuf = NULL;
6374 static int utf8splength;
6375 static DWORD utf8spcells;
6376 static WCHAR **utf8usingbuf = &unicodebuf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006377
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006378 if (cbToWrite != 1 || *pchBuf != ' ' || !enc_utf8)
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006379 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006380 utf8usingbuf = &unicodebuf;
6381 do
6382 {
6383 length = MultiByteToWideChar(cp, 0, (LPCSTR)pchBuf, cbToWrite,
6384 unicodebuf, unibuflen);
6385 if (length && length <= unibuflen)
6386 break;
6387 vim_free(unicodebuf);
6388 unicodebuf = length ? LALLOC_MULT(WCHAR, length) : NULL;
6389 unibuflen = unibuflen ? 0 : length;
6390 } while(1);
6391 cells = mb_string2cells(pchBuf, cbToWrite);
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006392 }
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006393 else // cbToWrite == 1 && *pchBuf == ' ' && enc_utf8
6394 {
6395 if (utf8usingbuf != &utf8spbuf)
6396 {
6397 if (utf8spbuf == NULL)
6398 {
6399 cells = mb_string2cells((char_u *)" ", 1);
6400 length = MultiByteToWideChar(CP_UTF8, 0, " ", 1, NULL, 0);
6401 utf8spbuf = LALLOC_MULT(WCHAR, length);
6402 if (utf8spbuf != NULL)
6403 {
6404 MultiByteToWideChar(CP_UTF8, 0, " ", 1, utf8spbuf, length);
6405 utf8usingbuf = &utf8spbuf;
6406 utf8splength = length;
6407 utf8spcells = cells;
6408 }
6409 }
6410 else
6411 {
6412 utf8usingbuf = &utf8spbuf;
6413 length = utf8splength;
6414 cells = utf8spcells;
6415 }
6416 }
6417 }
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006418
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006419 if (!USE_VTP)
6420 {
6421 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, cells,
6422 coord, &written);
6423 // When writing fails or didn't write a single character, pretend one
6424 // character was written, otherwise we get stuck.
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006425 if (WriteConsoleOutputCharacterW(g_hConOut, *utf8usingbuf, length,
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006426 coord, &cchwritten) == 0
6427 || cchwritten == 0 || cchwritten == (DWORD)-1)
6428 cchwritten = 1;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006429 }
6430 else
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006431 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006432 if (WriteConsoleW(g_hConOut, *utf8usingbuf, length, &cchwritten,
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006433 NULL) == 0 || cchwritten == 0)
6434 cchwritten = 1;
6435 }
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006436
K.Takata135e1522022-01-29 15:27:58 +00006437 if (cchwritten == (DWORD)length)
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006438 {
6439 written = cbToWrite;
6440 g_coord.X += (SHORT)cells;
6441 }
6442 else
6443 {
6444 char_u *p = pchBuf;
6445 for (n = 0; n < cchwritten; n++)
6446 MB_CPTR_ADV(p);
6447 written = p - pchBuf;
6448 g_coord.X += (SHORT)mb_string2cells(pchBuf, written);
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006449 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006450
6451 while (g_coord.X > g_srScrollRegion.Right)
6452 {
6453 g_coord.X -= (SHORT) Columns;
6454 if (g_coord.Y < g_srScrollRegion.Bottom)
6455 g_coord.Y++;
6456 }
6457
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006458 // Cursor under VTP is always in the correct position, no need to reset.
6459 if (!USE_VTP)
6460 gotoxy(g_coord.X + 1, g_coord.Y + 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006461
6462 return written;
6463}
6464
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006465 static char_u *
6466get_seq(
6467 int *args,
6468 int *count,
6469 char_u *head)
6470{
6471 int argc;
6472 char_u *p;
6473
6474 if (head == NULL || *head != '\033')
6475 return NULL;
6476
6477 argc = 0;
6478 p = head;
6479 ++p;
6480 do
6481 {
6482 ++p;
6483 args[argc] = getdigits(&p);
6484 argc += (argc < 15) ? 1 : 0;
6485 } while (*p == ';');
6486 *count = argc;
6487
6488 return p;
6489}
6490
6491 static char_u *
6492get_sgr(
6493 int *args,
6494 int *count,
6495 char_u *head)
6496{
6497 char_u *p = get_seq(args, count, head);
6498
6499 return (p && *p == 'm') ? ++p : NULL;
6500}
6501
6502/*
6503 * Pointer to next if SGR (^[[n;2;*;*;*m), NULL otherwise.
6504 */
6505 static char_u *
6506sgrn2(
6507 char_u *head,
6508 int n)
6509{
6510 int argc;
6511 int args[16];
6512 char_u *p = get_sgr(args, &argc, head);
6513
6514 return p && argc == 5 && args[0] == n && args[1] == 2 ? p : NULL;
6515}
6516
6517/*
6518 * Pointer to next if SGR(^[[nm)<space>ESC, NULL otherwise.
6519 */
6520 static char_u *
6521sgrnc(
6522 char_u *head,
6523 int n)
6524{
6525 int argc;
6526 int args[16];
6527 char_u *p = get_sgr(args, &argc, head);
6528
6529 return p && argc == 1 && args[0] == n && (p = skipwhite(p)) && *p == '\033'
6530 ? p : NULL;
6531}
6532
6533 static char_u *
6534skipblank(char_u *q)
6535{
6536 char_u *p = q;
6537
6538 while (*p == ' ' || *p == '\t' || *p == '\n' || *p == '\r')
6539 ++p;
6540 return p;
6541}
6542
6543/*
6544 * Pointer to the next if any whitespace that may follow SGR is ESC, otherwise
6545 * NULL.
6546 */
6547 static char_u *
6548sgrn2c(
6549 char_u *head,
6550 int n)
6551{
6552 char_u *p = sgrn2(head, n);
6553
6554 return p && *p != NUL && (p = skipblank(p)) && *p == '\033' ? p : NULL;
6555}
6556
6557/*
6558 * If there is only a newline between the sequence immediately following it,
6559 * a pointer to the character following the newline is returned.
6560 * Otherwise NULL.
6561 */
6562 static char_u *
6563sgrn2cn(
6564 char_u *head,
6565 int n)
6566{
6567 char_u *p = sgrn2(head, n);
6568
6569 return p && p[0] == 0x0a && p[1] == '\033' ? ++p : NULL;
6570}
Bram Moolenaar071d4272004-06-13 20:20:40 +00006571
6572/*
6573 * mch_write(): write the output buffer to the screen, translating ESC
6574 * sequences into calls to console output routines.
6575 */
6576 void
6577mch_write(
6578 char_u *s,
6579 int len)
6580{
Bram Moolenaard23f8bd2021-04-21 11:30:48 +02006581 char_u *end = s + len;
6582
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006583# ifdef VIMDLL
6584 if (gui.in_use)
6585 return;
6586# endif
6587
Bram Moolenaar071d4272004-06-13 20:20:40 +00006588 if (!term_console)
6589 {
6590 write(1, s, (unsigned)len);
6591 return;
6592 }
6593
Bram Moolenaar0f873732019-12-05 20:28:46 +01006594 // translate ESC | sequences into faked bios calls
Bram Moolenaar071d4272004-06-13 20:20:40 +00006595 while (len--)
6596 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006597 int prefix = -1;
6598 char_u ch;
6599
6600 // While processing a sequence, on rare occasions it seems that another
6601 // sequence may be inserted asynchronously.
6602 if (len < 0)
6603 {
Bram Moolenaara4d158b2022-08-14 14:17:45 +01006604 redraw_all_later(UPD_CLEAR);
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006605 return;
6606 }
6607
Bram Moolenaard23f8bd2021-04-21 11:30:48 +02006608 while (s + ++prefix < end)
6609 {
6610 ch = s[prefix];
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006611 if (ch <= 0x1e && !(ch != '\n' && ch != '\r' && ch != '\b'
6612 && ch != '\a' && ch != '\033'))
6613 break;
Bram Moolenaard23f8bd2021-04-21 11:30:48 +02006614 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006615
6616 if (p_wd)
6617 {
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02006618 WaitForChar(p_wd, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006619 if (prefix != 0)
6620 prefix = 1;
6621 }
6622
6623 if (prefix != 0)
6624 {
6625 DWORD nWritten;
6626
6627 nWritten = write_chars(s, prefix);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006628# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006629 if (fdDump)
6630 {
6631 fputc('>', fdDump);
6632 fwrite(s, sizeof(char_u), nWritten, fdDump);
6633 fputs("<\n", fdDump);
6634 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006635# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006636 len -= (nWritten - 1);
6637 s += nWritten;
6638 }
6639 else if (s[0] == '\n')
6640 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006641 // \n, newline: go to the beginning of the next line or scroll
Bram Moolenaar071d4272004-06-13 20:20:40 +00006642 if (g_coord.Y == g_srScrollRegion.Bottom)
6643 {
6644 scroll(1);
6645 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Bottom + 1);
6646 }
6647 else
6648 {
6649 gotoxy(g_srScrollRegion.Left + 1, g_coord.Y + 2);
6650 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006651# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006652 if (fdDump)
6653 fputs("\\n\n", fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006654# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006655 s++;
6656 }
6657 else if (s[0] == '\r')
6658 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006659 // \r, carriage return: go to beginning of line
Bram Moolenaar071d4272004-06-13 20:20:40 +00006660 gotoxy(g_srScrollRegion.Left+1, g_coord.Y + 1);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006661# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006662 if (fdDump)
6663 fputs("\\r\n", fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006664# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006665 s++;
6666 }
6667 else if (s[0] == '\b')
6668 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006669 // \b, backspace: move cursor one position left
Bram Moolenaar071d4272004-06-13 20:20:40 +00006670 if (g_coord.X > g_srScrollRegion.Left)
6671 g_coord.X--;
6672 else if (g_coord.Y > g_srScrollRegion.Top)
6673 {
6674 g_coord.X = g_srScrollRegion.Right;
6675 g_coord.Y--;
6676 }
6677 gotoxy(g_coord.X + 1, g_coord.Y + 1);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006678# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006679 if (fdDump)
6680 fputs("\\b\n", fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006681# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006682 s++;
6683 }
6684 else if (s[0] == '\a')
6685 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006686 // \a, bell
Bram Moolenaar071d4272004-06-13 20:20:40 +00006687 MessageBeep(0xFFFFFFFF);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006688# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006689 if (fdDump)
6690 fputs("\\a\n", fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006691# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006692 s++;
6693 }
6694 else if (s[0] == ESC && len >= 3-1 && s[1] == '|')
6695 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006696# ifdef MCH_WRITE_DUMP
Bram Moolenaarc0197e22004-09-13 20:26:32 +00006697 char_u *old_s = s;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006698# endif
Bram Moolenaarc0197e22004-09-13 20:26:32 +00006699 char_u *p;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006700 int arg1 = 0, arg2 = 0, argc = 0, args[16];
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006701 char_u *sp;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006702
6703 switch (s[2])
6704 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006705 case '0': case '1': case '2': case '3': case '4':
6706 case '5': case '6': case '7': case '8': case '9':
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006707 if (*(p = get_seq(args, &argc, s)) != 'm')
6708 goto notsgr;
6709
6710 p = s;
6711
6712 // Handling frequent optional sequences. Output to the screen
6713 // takes too long, so do not output as much as possible.
6714
6715 // If resetFG,FG,BG,<cr>,BG,FG are connected, the preceding
6716 // resetFG,FG,BG are omitted.
6717 if (sgrn2(sgrn2(sgrn2cn(sgrn2(sgrnc(p, 39), 38), 48), 48), 38))
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006718 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006719 p = sgrn2(sgrn2(sgrnc(p, 39), 38), 48);
6720 len = len + 1 - (int)(p - s);
6721 s = p;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006722 break;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006723 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006724
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006725 // If FG,BG,BG,FG of SGR are connected, the first FG can be
6726 // omitted.
6727 if (sgrn2(sgrn2(sgrn2c((sp = sgrn2(p, 38)), 48), 48), 38))
6728 p = sp;
6729
6730 // If FG,BG,FG,BG of SGR are connected, the first FG can be
6731 // omitted.
6732 if (sgrn2(sgrn2(sgrn2c((sp = sgrn2(p, 38)), 48), 38), 48))
6733 p = sp;
6734
6735 // If BG,BG of SGR are connected, the first BG can be omitted.
6736 if (sgrn2((sp = sgrn2(p, 48)), 48))
6737 p = sp;
6738
6739 // If restoreFG and FG are connected, the restoreFG can be
Bram Moolenaar9f1983d2022-05-12 20:35:35 +01006740 // omitted.
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006741 if (sgrn2((sp = sgrnc(p, 39)), 38))
6742 p = sp;
6743
6744 p = get_seq(args, &argc, p);
6745
6746notsgr:
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006747 arg1 = args[0];
6748 arg2 = args[1];
6749 if (*p == 'm')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006750 {
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006751 if (argc == 1 && args[0] == 0)
6752 normvideo();
6753 else if (argc == 1)
6754 {
6755 if (USE_VTP)
6756 textcolor((WORD) arg1);
6757 else
6758 textattr((WORD) arg1);
6759 }
6760 else if (USE_VTP)
6761 vtp_sgr_bulks(argc, args);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006762 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006763 else if (argc == 2 && *p == 'H')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006764 {
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006765 gotoxy(arg2, arg1);
6766 }
6767 else if (argc == 2 && *p == 'r')
6768 {
6769 set_scroll_region(0, arg1 - 1, Columns - 1, arg2 - 1);
6770 }
Bram Moolenaar6982f422019-02-16 16:48:01 +01006771 else if (argc == 2 && *p == 'R')
6772 {
6773 set_scroll_region_tb(arg1, arg2);
6774 }
6775 else if (argc == 2 && *p == 'V')
6776 {
6777 set_scroll_region_lr(arg1, arg2);
6778 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006779 else if (argc == 1 && *p == 'A')
6780 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006781 gotoxy(g_coord.X + 1,
6782 max(g_srScrollRegion.Top, g_coord.Y - arg1) + 1);
6783 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006784 else if (argc == 1 && *p == 'b')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006785 {
6786 textbackground((WORD) arg1);
6787 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006788 else if (argc == 1 && *p == 'C')
6789 {
6790 gotoxy(min(g_srScrollRegion.Right, g_coord.X + arg1) + 1,
6791 g_coord.Y + 1);
6792 }
6793 else if (argc == 1 && *p == 'f')
6794 {
6795 textcolor((WORD) arg1);
6796 }
6797 else if (argc == 1 && *p == 'H')
6798 {
6799 gotoxy(1, arg1);
6800 }
6801 else if (argc == 1 && *p == 'L')
6802 {
6803 insert_lines(arg1);
6804 }
6805 else if (argc == 1 && *p == 'M')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006806 {
6807 delete_lines(arg1);
6808 }
6809
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006810 len -= (int)(p - s);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006811 s = p + 1;
6812 break;
6813
Bram Moolenaar071d4272004-06-13 20:20:40 +00006814 case 'A':
Bram Moolenaar071d4272004-06-13 20:20:40 +00006815 gotoxy(g_coord.X + 1,
6816 max(g_srScrollRegion.Top, g_coord.Y - 1) + 1);
6817 goto got3;
6818
6819 case 'B':
6820 visual_bell();
6821 goto got3;
6822
6823 case 'C':
Bram Moolenaar071d4272004-06-13 20:20:40 +00006824 gotoxy(min(g_srScrollRegion.Right, g_coord.X + 1) + 1,
6825 g_coord.Y + 1);
6826 goto got3;
6827
6828 case 'E':
6829 termcap_mode_end();
6830 goto got3;
6831
6832 case 'F':
6833 standout();
6834 goto got3;
6835
6836 case 'f':
6837 standend();
6838 goto got3;
6839
6840 case 'H':
6841 gotoxy(1, 1);
6842 goto got3;
6843
6844 case 'j':
6845 clear_to_end_of_display();
6846 goto got3;
6847
6848 case 'J':
6849 clear_screen();
6850 goto got3;
6851
6852 case 'K':
6853 clear_to_end_of_line();
6854 goto got3;
6855
6856 case 'L':
6857 insert_lines(1);
6858 goto got3;
6859
6860 case 'M':
6861 delete_lines(1);
6862 goto got3;
6863
6864 case 'S':
6865 termcap_mode_start();
6866 goto got3;
6867
6868 case 'V':
6869 cursor_visible(TRUE);
6870 goto got3;
6871
6872 case 'v':
6873 cursor_visible(FALSE);
6874 goto got3;
6875
6876 got3:
6877 s += 3;
6878 len -= 2;
6879 }
6880
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006881# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006882 if (fdDump)
6883 {
6884 fputs("ESC | ", fdDump);
6885 fwrite(old_s + 2, sizeof(char_u), s - old_s - 2, fdDump);
6886 fputc('\n', fdDump);
6887 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006888# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006889 }
K.Takatadf5320c2022-09-01 13:20:16 +01006890 else if (s[0] == ESC && len >= 3-1 && s[1] == '[')
6891 {
6892 int l = 2;
6893
6894 if (isdigit(s[l]))
6895 l++;
6896 if (s[l] == ' ' && s[l + 1] == 'q')
6897 {
6898 // DECSCUSR (cursor style) sequences
6899 if (USE_VTP || USE_WT)
6900 vtp_printf("%.*s", l + 2, s); // Pass through
6901 s += l + 2;
6902 len -= l + 1;
6903 }
6904 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006905 else
6906 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006907 // Write a single character
Bram Moolenaar071d4272004-06-13 20:20:40 +00006908 DWORD nWritten;
6909
6910 nWritten = write_chars(s, 1);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006911# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006912 if (fdDump)
6913 {
6914 fputc('>', fdDump);
6915 fwrite(s, sizeof(char_u), nWritten, fdDump);
6916 fputs("<\n", fdDump);
6917 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006918# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006919
6920 len -= (nWritten - 1);
6921 s += nWritten;
6922 }
6923 }
6924
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006925# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006926 if (fdDump)
6927 fflush(fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006928# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006929}
6930
Bram Moolenaar0f873732019-12-05 20:28:46 +01006931#endif // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00006932
6933
6934/*
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01006935 * Delay for "msec" milliseconds.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006936 */
6937 void
6938mch_delay(
6939 long msec,
Bram Moolenaar0981c872020-08-23 14:28:37 +02006940 int flags UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006941{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006942#if defined(FEAT_GUI_MSWIN) && !defined(VIMDLL)
Bram Moolenaar0f873732019-12-05 20:28:46 +01006943 Sleep((int)msec); // never wait for input
6944#else // Console
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006945# ifdef VIMDLL
6946 if (gui.in_use)
6947 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006948 Sleep((int)msec); // never wait for input
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006949 return;
6950 }
6951# endif
Bram Moolenaar0981c872020-08-23 14:28:37 +02006952 if (flags & MCH_DELAY_IGNOREINPUT)
Bram Moolenaar325b7a22004-07-05 15:58:32 +00006953# ifdef FEAT_MZSCHEME
6954 if (mzthreads_allowed() && p_mzq > 0 && msec > p_mzq)
6955 {
6956 int towait = p_mzq;
6957
Bram Moolenaar0f873732019-12-05 20:28:46 +01006958 // if msec is large enough, wait by portions in p_mzq
Bram Moolenaar325b7a22004-07-05 15:58:32 +00006959 while (msec > 0)
6960 {
6961 mzvim_check_threads();
6962 if (msec < towait)
6963 towait = msec;
6964 Sleep(towait);
6965 msec -= towait;
6966 }
6967 }
6968 else
6969# endif
6970 Sleep((int)msec);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006971 else
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02006972 WaitForChar(msec, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006973#endif
6974}
6975
6976
6977/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01006978 * This version of remove is not scared by a readonly (backup) file.
6979 * This can also remove a symbolic link like Unix.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006980 * Return 0 for success, -1 for failure.
6981 */
6982 int
6983mch_remove(char_u *name)
6984{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006985 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006986 int n;
6987
Bram Moolenaar203258c2016-01-17 22:15:16 +01006988 /*
6989 * On Windows, deleting a directory's symbolic link is done by
6990 * RemoveDirectory(): mch_rmdir. It seems unnatural, but it is fact.
6991 */
6992 if (mch_isdir(name) && mch_is_symbolic_link(name))
6993 return mch_rmdir(name);
6994
Bram Moolenaar12b559e2013-06-12 22:41:37 +02006995 win32_setattrs(name, FILE_ATTRIBUTE_NORMAL);
6996
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006997 wn = enc_to_utf16(name, NULL);
6998 if (wn == NULL)
6999 return -1;
7000
7001 n = DeleteFileW(wn) ? 0 : -1;
7002 vim_free(wn);
7003 return n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007004}
7005
7006
7007/*
Bram Moolenaarb9c31e72016-09-29 15:18:57 +02007008 * Check for an "interrupt signal": CTRL-break or CTRL-C.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007009 */
7010 void
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02007011mch_breakcheck(int force UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007012{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007013#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
7014# ifdef VIMDLL
7015 if (!gui.in_use)
7016# endif
7017 if (g_fCtrlCPressed || g_fCBrkPressed)
7018 {
7019 ctrl_break_was_pressed = g_fCBrkPressed;
7020 g_fCtrlCPressed = g_fCBrkPressed = FALSE;
7021 got_int = TRUE;
7022 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007023#endif
7024}
7025
Bram Moolenaar0f873732019-12-05 20:28:46 +01007026// physical RAM to leave for the OS
Bram Moolenaaree273972016-01-02 21:11:51 +01007027#define WINNT_RESERVE_BYTES (256*1024*1024)
Bram Moolenaaree273972016-01-02 21:11:51 +01007028
7029/*
7030 * How much main memory in KiB that can be used by VIM.
7031 */
Bram Moolenaaree273972016-01-02 21:11:51 +01007032 long_u
Bram Moolenaar1266d672017-02-01 13:43:36 +01007033mch_total_mem(int special UNUSED)
Bram Moolenaaree273972016-01-02 21:11:51 +01007034{
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007035 MEMORYSTATUSEX ms;
7036
Bram Moolenaar0f873732019-12-05 20:28:46 +01007037 // Need to use GlobalMemoryStatusEx() when there is more memory than
7038 // what fits in 32 bits.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007039 ms.dwLength = sizeof(MEMORYSTATUSEX);
7040 GlobalMemoryStatusEx(&ms);
7041 if (ms.ullAvailVirtual < ms.ullTotalPhys)
Bram Moolenaaree273972016-01-02 21:11:51 +01007042 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007043 // Process address space fits in physical RAM, use all of it.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007044 return (long_u)(ms.ullAvailVirtual / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01007045 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007046 if (ms.ullTotalPhys <= WINNT_RESERVE_BYTES)
Bram Moolenaaree273972016-01-02 21:11:51 +01007047 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007048 // Catch old NT box or perverse hardware setup.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007049 return (long_u)((ms.ullTotalPhys / 2) / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01007050 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01007051 // Use physical RAM less reserve for OS + data.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007052 return (long_u)((ms.ullTotalPhys - WINNT_RESERVE_BYTES) / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01007053}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007054
Bram Moolenaar071d4272004-06-13 20:20:40 +00007055/*
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007056 * mch_wrename() works around a bug in rename (aka MoveFile) in
Bram Moolenaar071d4272004-06-13 20:20:40 +00007057 * Windows 95: rename("foo.bar", "foo.bar~") will generate a
7058 * file whose short file name is "FOO.BAR" (its long file name will
7059 * be correct: "foo.bar~"). Because a file can be accessed by
7060 * either its SFN or its LFN, "foo.bar" has effectively been
7061 * renamed to "foo.bar", which is not at all what was wanted. This
7062 * seems to happen only when renaming files with three-character
7063 * extensions by appending a suffix that does not include ".".
7064 * Windows NT gets it right, however, with an SFN of "FOO~1.BAR".
7065 *
7066 * There is another problem, which isn't really a bug but isn't right either:
7067 * When renaming "abcdef~1.txt" to "abcdef~1.txt~", the short name can be
7068 * "abcdef~1.txt" again. This has been reported on Windows NT 4.0 with
7069 * service pack 6. Doesn't seem to happen on Windows 98.
7070 *
7071 * Like rename(), returns 0 upon success, non-zero upon failure.
7072 * Should probably set errno appropriately when errors occur.
7073 */
7074 int
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007075mch_wrename(WCHAR *wold, WCHAR *wnew)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007076{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007077 WCHAR *p;
7078 int i;
7079 WCHAR szTempFile[_MAX_PATH + 1];
7080 WCHAR szNewPath[_MAX_PATH + 1];
Bram Moolenaar071d4272004-06-13 20:20:40 +00007081 HANDLE hf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007082
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007083 // No need to play tricks unless the file name contains a "~" as the
7084 // seventh character.
7085 p = wold;
7086 for (i = 0; wold[i] != NUL; ++i)
7087 if ((wold[i] == '/' || wold[i] == '\\' || wold[i] == ':')
7088 && wold[i + 1] != 0)
7089 p = wold + i + 1;
7090 if ((int)(wold + i - p) < 8 || p[6] != '~')
7091 return (MoveFileW(wold, wnew) == 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007092
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007093 // Get base path of new file name. Undocumented feature: If pszNewFile is
7094 // a directory, no error is returned and pszFilePart will be NULL.
7095 if (GetFullPathNameW(wnew, _MAX_PATH, szNewPath, &p) == 0 || p == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007096 return -1;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007097 *p = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007098
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007099 // Get (and create) a unique temporary file name in directory of new file
7100 if (GetTempFileNameW(szNewPath, L"VIM", 0, szTempFile) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007101 return -2;
7102
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007103 // blow the temp file away
7104 if (!DeleteFileW(szTempFile))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007105 return -3;
7106
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007107 // rename old file to the temp file
7108 if (!MoveFileW(wold, szTempFile))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007109 return -4;
7110
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007111 // now create an empty file called pszOldFile; this prevents the operating
7112 // system using pszOldFile as an alias (SFN) if we're renaming within the
7113 // same directory. For example, we're editing a file called
7114 // filename.asc.txt by its SFN, filena~1.txt. If we rename filena~1.txt
7115 // to filena~1.txt~ (i.e., we're making a backup while writing it), the
7116 // SFN for filena~1.txt~ will be filena~1.txt, by default, which will
7117 // cause all sorts of problems later in buf_write(). So, we create an
7118 // empty file called filena~1.txt and the system will have to find some
7119 // other SFN for filena~1.txt~, such as filena~2.txt
7120 if ((hf = CreateFileW(wold, GENERIC_WRITE, 0, NULL, CREATE_NEW,
Bram Moolenaar071d4272004-06-13 20:20:40 +00007121 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
7122 return -5;
7123 if (!CloseHandle(hf))
7124 return -6;
7125
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007126 // rename the temp file to the new file
7127 if (!MoveFileW(szTempFile, wnew))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007128 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007129 // Renaming failed. Rename the file back to its old name, so that it
7130 // looks like nothing happened.
7131 (void)MoveFileW(szTempFile, wold);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007132 return -7;
7133 }
7134
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007135 // Seems to be left around on Novell filesystems
7136 DeleteFileW(szTempFile);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007137
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007138 // finally, remove the empty old file
7139 if (!DeleteFileW(wold))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007140 return -8;
7141
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007142 return 0;
7143}
7144
7145
7146/*
7147 * Converts the filenames to UTF-16, then call mch_wrename().
7148 * Like rename(), returns 0 upon success, non-zero upon failure.
7149 */
7150 int
7151mch_rename(
7152 const char *pszOldFile,
7153 const char *pszNewFile)
7154{
7155 WCHAR *wold = NULL;
7156 WCHAR *wnew = NULL;
7157 int retval = -1;
7158
7159 wold = enc_to_utf16((char_u *)pszOldFile, NULL);
7160 wnew = enc_to_utf16((char_u *)pszNewFile, NULL);
7161 if (wold != NULL && wnew != NULL)
7162 retval = mch_wrename(wold, wnew);
7163 vim_free(wold);
7164 vim_free(wnew);
7165 return retval;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007166}
7167
7168/*
7169 * Get the default shell for the current hardware platform
7170 */
7171 char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007172default_shell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007173{
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007174 return "cmd.exe";
Bram Moolenaar071d4272004-06-13 20:20:40 +00007175}
7176
7177/*
7178 * mch_access() extends access() to do more detailed check on network drives.
7179 * Returns 0 if file "n" has access rights according to "p", -1 otherwise.
7180 */
7181 int
7182mch_access(char *n, int p)
7183{
7184 HANDLE hFile;
Bram Moolenaar0f873732019-12-05 20:28:46 +01007185 int retval = -1; // default: fail
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007186 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007187
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007188 wn = enc_to_utf16((char_u *)n, NULL);
7189 if (wn == NULL)
7190 return -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007191
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01007192 if (mch_isdir((char_u *)n))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007193 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00007194 WCHAR TempNameW[_MAX_PATH + 16] = L"";
Bram Moolenaar071d4272004-06-13 20:20:40 +00007195
7196 if (p & R_OK)
7197 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007198 // Read check is performed by seeing if we can do a find file on
7199 // the directory for any file.
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007200 int i;
7201 WIN32_FIND_DATAW d;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007202
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007203 for (i = 0; i < _MAX_PATH && wn[i] != 0; ++i)
7204 TempNameW[i] = wn[i];
7205 if (TempNameW[i - 1] != '\\' && TempNameW[i - 1] != '/')
7206 TempNameW[i++] = '\\';
7207 TempNameW[i++] = '*';
7208 TempNameW[i++] = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007209
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007210 hFile = FindFirstFileW(TempNameW, &d);
7211 if (hFile == INVALID_HANDLE_VALUE)
7212 goto getout;
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007213 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00007214 (void)FindClose(hFile);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007215 }
7216
7217 if (p & W_OK)
7218 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007219 // Trying to create a temporary file in the directory should catch
7220 // directories on read-only network shares. However, in
7221 // directories whose ACL allows writes but denies deletes will end
7222 // up keeping the temporary file :-(.
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007223 if (!GetTempFileNameW(wn, L"VIM", 0, TempNameW))
7224 goto getout;
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007225 else
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007226 DeleteFileW(TempNameW);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007227 }
7228 }
7229 else
7230 {
Bram Moolenaar5aa98962018-05-06 17:09:38 +02007231 // Don't consider a file read-only if another process has opened it.
7232 DWORD share_mode = FILE_SHARE_READ | FILE_SHARE_WRITE;
7233
Bram Moolenaar0f873732019-12-05 20:28:46 +01007234 // Trying to open the file for the required access does ACL, read-only
7235 // network share, and file attribute checks.
Bram Moolenaar5aa98962018-05-06 17:09:38 +02007236 DWORD access_mode = ((p & W_OK) ? GENERIC_WRITE : 0)
7237 | ((p & R_OK) ? GENERIC_READ : 0);
7238
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007239 hFile = CreateFileW(wn, access_mode, share_mode,
7240 NULL, OPEN_EXISTING, 0, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007241 if (hFile == INVALID_HANDLE_VALUE)
7242 goto getout;
7243 CloseHandle(hFile);
7244 }
7245
Bram Moolenaar0f873732019-12-05 20:28:46 +01007246 retval = 0; // success
Bram Moolenaar071d4272004-06-13 20:20:40 +00007247getout:
Bram Moolenaar071d4272004-06-13 20:20:40 +00007248 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007249 return retval;
7250}
7251
Bram Moolenaar071d4272004-06-13 20:20:40 +00007252/*
Bram Moolenaar36f692d2008-11-20 16:10:17 +00007253 * Version of open() that may use UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007254 */
7255 int
Bram Moolenaarb6843a02017-08-02 22:07:12 +02007256mch_open(const char *name, int flags, int mode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007257{
7258 WCHAR *wn;
7259 int f;
7260
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007261 wn = enc_to_utf16((char_u *)name, NULL);
7262 if (wn == NULL)
7263 return -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007264
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007265 f = _wopen(wn, flags, mode);
7266 vim_free(wn);
7267 return f;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007268}
7269
7270/*
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007271 * Version of fopen() that uses UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007272 */
7273 FILE *
Bram Moolenaarb6843a02017-08-02 22:07:12 +02007274mch_fopen(const char *name, const char *mode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007275{
7276 WCHAR *wn, *wm;
7277 FILE *f = NULL;
7278
Bram Moolenaara12a1612019-01-24 16:39:02 +01007279#if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0f873732019-12-05 20:28:46 +01007280 // Work around an annoying assertion in the Microsoft debug CRT
7281 // when mode's text/binary setting doesn't match _get_fmode().
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007282 char newMode = mode[strlen(mode) - 1];
7283 int oldMode = 0;
Bram Moolenaar0fde2902008-03-16 13:54:13 +00007284
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007285 _get_fmode(&oldMode);
7286 if (newMode == 't')
7287 _set_fmode(_O_TEXT);
7288 else if (newMode == 'b')
7289 _set_fmode(_O_BINARY);
Bram Moolenaara12a1612019-01-24 16:39:02 +01007290#endif
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007291 wn = enc_to_utf16((char_u *)name, NULL);
7292 wm = enc_to_utf16((char_u *)mode, NULL);
7293 if (wn != NULL && wm != NULL)
7294 f = _wfopen(wn, wm);
7295 vim_free(wn);
7296 vim_free(wm);
Bram Moolenaar0fde2902008-03-16 13:54:13 +00007297
Bram Moolenaara12a1612019-01-24 16:39:02 +01007298#if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007299 _set_fmode(oldMode);
Bram Moolenaara12a1612019-01-24 16:39:02 +01007300#endif
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007301 return f;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007302}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007303
Bram Moolenaar071d4272004-06-13 20:20:40 +00007304/*
7305 * SUB STREAM (aka info stream) handling:
7306 *
Bram Moolenaar8e7d6222020-12-18 19:49:56 +01007307 * NTFS can have sub streams for each file. The normal contents of a file is
7308 * stored in the main stream, and extra contents (author information, title and
7309 * so on) can be stored in a sub stream. After Windows 2000, the user can
7310 * access and store this information in sub streams via an explorer's property
7311 * menu item in the right click menu. This information in sub streams was lost
7312 * when copying only the main stream. Therefore we have to copy sub streams.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007313 *
7314 * Incomplete explanation:
7315 * http://msdn.microsoft.com/library/en-us/dnw2k/html/ntfs5.asp
7316 * More useful info and an example:
7317 * http://www.sysinternals.com/ntw2k/source/misc.shtml#streams
7318 */
7319
7320/*
7321 * Copy info stream data "substream". Read from the file with BackupRead(sh)
7322 * and write to stream "substream" of file "to".
7323 * Errors are ignored.
7324 */
7325 static void
7326copy_substream(HANDLE sh, void *context, WCHAR *to, WCHAR *substream, long len)
7327{
7328 HANDLE hTo;
7329 WCHAR *to_name;
7330
7331 to_name = malloc((wcslen(to) + wcslen(substream) + 1) * sizeof(WCHAR));
7332 wcscpy(to_name, to);
7333 wcscat(to_name, substream);
7334
7335 hTo = CreateFileW(to_name, GENERIC_WRITE, 0, NULL, OPEN_ALWAYS,
7336 FILE_ATTRIBUTE_NORMAL, NULL);
7337 if (hTo != INVALID_HANDLE_VALUE)
7338 {
7339 long done;
7340 DWORD todo;
7341 DWORD readcnt, written;
7342 char buf[4096];
7343
Bram Moolenaar0f873732019-12-05 20:28:46 +01007344 // Copy block of bytes at a time. Abort when something goes wrong.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007345 for (done = 0; done < len; done += written)
7346 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007347 // (size_t) cast for Borland C 5.5
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007348 todo = (DWORD)((size_t)(len - done) > sizeof(buf) ? sizeof(buf)
7349 : (size_t)(len - done));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007350 if (!BackupRead(sh, (LPBYTE)buf, todo, &readcnt,
7351 FALSE, FALSE, context)
7352 || readcnt != todo
7353 || !WriteFile(hTo, buf, todo, &written, NULL)
7354 || written != todo)
7355 break;
7356 }
7357 CloseHandle(hTo);
7358 }
7359
7360 free(to_name);
7361}
7362
7363/*
7364 * Copy info streams from file "from" to file "to".
7365 */
7366 static void
7367copy_infostreams(char_u *from, char_u *to)
7368{
7369 WCHAR *fromw;
7370 WCHAR *tow;
7371 HANDLE sh;
7372 WIN32_STREAM_ID sid;
7373 int headersize;
7374 WCHAR streamname[_MAX_PATH];
7375 DWORD readcount;
7376 void *context = NULL;
7377 DWORD lo, hi;
7378 int len;
7379
Bram Moolenaar0f873732019-12-05 20:28:46 +01007380 // Convert the file names to wide characters.
Bram Moolenaar36f692d2008-11-20 16:10:17 +00007381 fromw = enc_to_utf16(from, NULL);
7382 tow = enc_to_utf16(to, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007383 if (fromw != NULL && tow != NULL)
7384 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007385 // Open the file for reading.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007386 sh = CreateFileW(fromw, GENERIC_READ, FILE_SHARE_READ, NULL,
7387 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
7388 if (sh != INVALID_HANDLE_VALUE)
7389 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007390 // Use BackupRead() to find the info streams. Repeat until we
7391 // have done them all.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007392 for (;;)
7393 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007394 // Get the header to find the length of the stream name. If
7395 // the "readcount" is zero we have done all info streams.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007396 ZeroMemory(&sid, sizeof(WIN32_STREAM_ID));
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007397 headersize = (int)((char *)&sid.cStreamName - (char *)&sid.dwStreamId);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007398 if (!BackupRead(sh, (LPBYTE)&sid, headersize,
7399 &readcount, FALSE, FALSE, &context)
7400 || readcount == 0)
7401 break;
7402
Bram Moolenaar0f873732019-12-05 20:28:46 +01007403 // We only deal with streams that have a name. The normal
7404 // file data appears to be without a name, even though docs
7405 // suggest it is called "::$DATA".
Bram Moolenaar071d4272004-06-13 20:20:40 +00007406 if (sid.dwStreamNameSize > 0)
7407 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007408 // Read the stream name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007409 if (!BackupRead(sh, (LPBYTE)streamname,
7410 sid.dwStreamNameSize,
7411 &readcount, FALSE, FALSE, &context))
7412 break;
7413
Bram Moolenaar0f873732019-12-05 20:28:46 +01007414 // Copy an info stream with a name ":anything:$DATA".
7415 // Skip "::$DATA", it has no stream name (examples suggest
7416 // it might be used for the normal file contents).
7417 // Note that BackupRead() counts bytes, but the name is in
7418 // wide characters.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007419 len = readcount / sizeof(WCHAR);
7420 streamname[len] = 0;
7421 if (len > 7 && wcsicmp(streamname + len - 6,
7422 L":$DATA") == 0)
7423 {
7424 streamname[len - 6] = 0;
7425 copy_substream(sh, &context, tow, streamname,
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00007426 (long)sid.Size.u.LowPart);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007427 }
7428 }
7429
Bram Moolenaar0f873732019-12-05 20:28:46 +01007430 // Advance to the next stream. We might try seeking too far,
7431 // but BackupSeek() doesn't skip over stream borders, thus
7432 // that's OK.
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00007433 (void)BackupSeek(sh, sid.Size.u.LowPart, sid.Size.u.HighPart,
Bram Moolenaar071d4272004-06-13 20:20:40 +00007434 &lo, &hi, &context);
7435 }
7436
Bram Moolenaar0f873732019-12-05 20:28:46 +01007437 // Clear the context.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007438 (void)BackupRead(sh, NULL, 0, &readcount, TRUE, FALSE, &context);
7439
7440 CloseHandle(sh);
7441 }
7442 }
7443 vim_free(fromw);
7444 vim_free(tow);
7445}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007446
7447/*
Bram Moolenaare7bebc42021-02-01 20:50:37 +01007448 * ntdll.dll definitions
7449 */
7450#define FileEaInformation 7
7451#ifndef STATUS_SUCCESS
7452# define STATUS_SUCCESS ((NTSTATUS) 0x00000000L)
7453#endif
7454
7455typedef struct _FILE_FULL_EA_INFORMATION_ {
7456 ULONG NextEntryOffset;
7457 UCHAR Flags;
7458 UCHAR EaNameLength;
7459 USHORT EaValueLength;
7460 CHAR EaName[1];
7461} FILE_FULL_EA_INFORMATION_, *PFILE_FULL_EA_INFORMATION_;
7462
7463typedef struct _FILE_EA_INFORMATION_ {
7464 ULONG EaSize;
7465} FILE_EA_INFORMATION_, *PFILE_EA_INFORMATION_;
7466
Paul Ollis65745772022-06-05 16:55:54 +01007467#ifndef PROTO
Bram Moolenaare7bebc42021-02-01 20:50:37 +01007468typedef NTSTATUS (NTAPI *PfnNtOpenFile)(
7469 PHANDLE FileHandle,
7470 ACCESS_MASK DesiredAccess,
7471 POBJECT_ATTRIBUTES ObjectAttributes,
7472 PIO_STATUS_BLOCK IoStatusBlock,
7473 ULONG ShareAccess,
7474 ULONG OpenOptions);
7475typedef NTSTATUS (NTAPI *PfnNtClose)(
7476 HANDLE Handle);
7477typedef NTSTATUS (NTAPI *PfnNtSetEaFile)(
Bram Moolenaar9f1983d2022-05-12 20:35:35 +01007478 HANDLE FileHandle,
7479 PIO_STATUS_BLOCK IoStatusBlock,
7480 PVOID Buffer,
7481 ULONG Length);
Bram Moolenaare7bebc42021-02-01 20:50:37 +01007482typedef NTSTATUS (NTAPI *PfnNtQueryEaFile)(
7483 HANDLE FileHandle,
7484 PIO_STATUS_BLOCK IoStatusBlock,
7485 PVOID Buffer,
7486 ULONG Length,
7487 BOOLEAN ReturnSingleEntry,
7488 PVOID EaList,
7489 ULONG EaListLength,
7490 PULONG EaIndex,
7491 BOOLEAN RestartScan);
7492typedef NTSTATUS (NTAPI *PfnNtQueryInformationFile)(
Bram Moolenaar9f1983d2022-05-12 20:35:35 +01007493 HANDLE FileHandle,
7494 PIO_STATUS_BLOCK IoStatusBlock,
7495 PVOID FileInformation,
7496 ULONG Length,
Bram Moolenaare7bebc42021-02-01 20:50:37 +01007497 FILE_INFORMATION_CLASS FileInformationClass);
7498typedef VOID (NTAPI *PfnRtlInitUnicodeString)(
7499 PUNICODE_STRING DestinationString,
7500 PCWSTR SourceString);
7501
7502PfnNtOpenFile pNtOpenFile = NULL;
7503PfnNtClose pNtClose = NULL;
7504PfnNtSetEaFile pNtSetEaFile = NULL;
7505PfnNtQueryEaFile pNtQueryEaFile = NULL;
7506PfnNtQueryInformationFile pNtQueryInformationFile = NULL;
7507PfnRtlInitUnicodeString pRtlInitUnicodeString = NULL;
Paul Ollis65745772022-06-05 16:55:54 +01007508#endif
Bram Moolenaare7bebc42021-02-01 20:50:37 +01007509
7510/*
7511 * Load ntdll.dll functions.
7512 */
7513 static BOOL
7514load_ntdll(void)
7515{
7516 static int loaded = -1;
7517
7518 if (loaded == -1)
7519 {
7520 HMODULE hNtdll = GetModuleHandle("ntdll.dll");
7521 if (hNtdll != NULL)
7522 {
7523 pNtOpenFile = (PfnNtOpenFile) GetProcAddress(hNtdll, "NtOpenFile");
7524 pNtClose = (PfnNtClose) GetProcAddress(hNtdll, "NtClose");
7525 pNtSetEaFile = (PfnNtSetEaFile)
7526 GetProcAddress(hNtdll, "NtSetEaFile");
7527 pNtQueryEaFile = (PfnNtQueryEaFile)
7528 GetProcAddress(hNtdll, "NtQueryEaFile");
7529 pNtQueryInformationFile = (PfnNtQueryInformationFile)
7530 GetProcAddress(hNtdll, "NtQueryInformationFile");
7531 pRtlInitUnicodeString = (PfnRtlInitUnicodeString)
7532 GetProcAddress(hNtdll, "RtlInitUnicodeString");
7533 }
7534 if (pNtOpenFile == NULL
7535 || pNtClose == NULL
7536 || pNtSetEaFile == NULL
7537 || pNtQueryEaFile == NULL
7538 || pNtQueryInformationFile == NULL
7539 || pRtlInitUnicodeString == NULL)
7540 loaded = FALSE;
7541 else
7542 loaded = TRUE;
7543 }
7544 return (BOOL) loaded;
7545}
7546
7547/*
7548 * Copy extended attributes (EA) from file "from" to file "to".
7549 */
7550 static void
7551copy_extattr(char_u *from, char_u *to)
7552{
7553 char_u *fromf = NULL;
7554 char_u *tof = NULL;
7555 WCHAR *fromw = NULL;
7556 WCHAR *tow = NULL;
7557 UNICODE_STRING u;
7558 HANDLE h;
7559 OBJECT_ATTRIBUTES oa;
7560 IO_STATUS_BLOCK iosb;
7561 FILE_EA_INFORMATION_ eainfo = {0};
7562 void *ea = NULL;
7563
7564 if (!load_ntdll())
7565 return;
7566
7567 // Convert the file names to the fully qualified object names.
7568 fromf = alloc(STRLEN(from) + 5);
7569 tof = alloc(STRLEN(to) + 5);
7570 if (fromf == NULL || tof == NULL)
7571 goto theend;
7572 STRCPY(fromf, "\\??\\");
7573 STRCAT(fromf, from);
7574 STRCPY(tof, "\\??\\");
7575 STRCAT(tof, to);
7576
7577 // Convert the names to wide characters.
7578 fromw = enc_to_utf16(fromf, NULL);
7579 tow = enc_to_utf16(tof, NULL);
7580 if (fromw == NULL || tow == NULL)
7581 goto theend;
7582
7583 // Get the EA.
7584 pRtlInitUnicodeString(&u, fromw);
7585 InitializeObjectAttributes(&oa, &u, 0, NULL, NULL);
7586 if (pNtOpenFile(&h, FILE_READ_EA, &oa, &iosb, 0,
7587 FILE_NON_DIRECTORY_FILE) != STATUS_SUCCESS)
7588 goto theend;
7589 pNtQueryInformationFile(h, &iosb, &eainfo, sizeof(eainfo),
7590 FileEaInformation);
7591 if (eainfo.EaSize != 0)
7592 {
7593 ea = alloc(eainfo.EaSize);
7594 if (ea != NULL)
7595 {
7596 if (pNtQueryEaFile(h, &iosb, ea, eainfo.EaSize, FALSE,
7597 NULL, 0, NULL, TRUE) != STATUS_SUCCESS)
7598 {
7599 vim_free(ea);
7600 ea = NULL;
7601 }
7602 }
7603 }
7604 pNtClose(h);
7605
7606 // Set the EA.
7607 if (ea != NULL)
7608 {
7609 pRtlInitUnicodeString(&u, tow);
7610 InitializeObjectAttributes(&oa, &u, 0, NULL, NULL);
7611 if (pNtOpenFile(&h, FILE_WRITE_EA, &oa, &iosb, 0,
7612 FILE_NON_DIRECTORY_FILE) != STATUS_SUCCESS)
7613 goto theend;
7614
7615 pNtSetEaFile(h, &iosb, ea, eainfo.EaSize);
7616 pNtClose(h);
7617 }
7618
7619theend:
7620 vim_free(fromf);
7621 vim_free(tof);
7622 vim_free(fromw);
7623 vim_free(tow);
7624 vim_free(ea);
7625}
7626
7627/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00007628 * Copy file attributes from file "from" to file "to".
7629 * For Windows NT and later we copy info streams.
7630 * Always returns zero, errors are ignored.
7631 */
7632 int
7633mch_copy_file_attribute(char_u *from, char_u *to)
7634{
Bram Moolenaar0f873732019-12-05 20:28:46 +01007635 // File streams only work on Windows NT and later.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007636 copy_infostreams(from, to);
Bram Moolenaare7bebc42021-02-01 20:50:37 +01007637 copy_extattr(from, to);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007638 return 0;
7639}
7640
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007641
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007642/*
K.Takatadc73b4b2021-06-08 18:32:36 +02007643 * The command line arguments in UTF-16
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007644 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00007645static int nArgsW = 0;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007646static LPWSTR *ArglistW = NULL;
7647static int global_argc = 0;
7648static char **global_argv;
7649
Bram Moolenaar0f873732019-12-05 20:28:46 +01007650static int used_file_argc = 0; // last argument in global_argv[] used
7651 // for the argument list.
7652static int *used_file_indexes = NULL; // indexes in global_argv[] for
7653 // command line arguments added to
7654 // the argument list
7655static int used_file_count = 0; // nr of entries in used_file_indexes
7656static int used_file_literal = FALSE; // take file names literally
7657static int used_file_full_path = FALSE; // file name was full path
7658static int used_file_diff_mode = FALSE; // file name was with diff mode
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007659static int used_alist_count = 0;
7660
7661
7662/*
7663 * Get the command line arguments. Unicode version.
7664 * Returns argc. Zero when something fails.
7665 */
7666 int
7667get_cmd_argsW(char ***argvp)
7668{
7669 char **argv = NULL;
7670 int argc = 0;
7671 int i;
7672
Bram Moolenaar14993322014-09-09 12:25:33 +02007673 free_cmd_argsW();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007674 ArglistW = CommandLineToArgvW(GetCommandLineW(), &nArgsW);
7675 if (ArglistW != NULL)
7676 {
7677 argv = malloc((nArgsW + 1) * sizeof(char *));
7678 if (argv != NULL)
7679 {
7680 argc = nArgsW;
7681 argv[argc] = NULL;
7682 for (i = 0; i < argc; ++i)
7683 {
7684 int len;
7685
K.Takatadc73b4b2021-06-08 18:32:36 +02007686 // Convert each Unicode argument to UTF-8.
7687 WideCharToMultiByte_alloc(CP_UTF8, 0,
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007688 ArglistW[i], (int)wcslen(ArglistW[i]) + 1,
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007689 (LPSTR *)&argv[i], &len, 0, 0);
7690 if (argv[i] == NULL)
7691 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007692 // Out of memory, clear everything.
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007693 while (i > 0)
7694 free(argv[--i]);
7695 free(argv);
Bram Moolenaar73c61632013-12-07 14:48:10 +01007696 argv = NULL;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007697 argc = 0;
7698 }
7699 }
7700 }
7701 }
7702
7703 global_argc = argc;
7704 global_argv = argv;
7705 if (argc > 0)
Bram Moolenaar14993322014-09-09 12:25:33 +02007706 {
7707 if (used_file_indexes != NULL)
7708 free(used_file_indexes);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007709 used_file_indexes = malloc(argc * sizeof(int));
Bram Moolenaar14993322014-09-09 12:25:33 +02007710 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007711
7712 if (argvp != NULL)
7713 *argvp = argv;
7714 return argc;
7715}
7716
7717 void
7718free_cmd_argsW(void)
7719{
7720 if (ArglistW != NULL)
7721 {
7722 GlobalFree(ArglistW);
7723 ArglistW = NULL;
7724 }
7725}
7726
7727/*
7728 * Remember "name" is an argument that was added to the argument list.
7729 * This avoids that we have to re-parse the argument list when fix_arg_enc()
7730 * is called.
7731 */
7732 void
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007733used_file_arg(char *name, int literal, int full_path, int diff_mode)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007734{
7735 int i;
7736
7737 if (used_file_indexes == NULL)
7738 return;
7739 for (i = used_file_argc + 1; i < global_argc; ++i)
7740 if (STRCMP(global_argv[i], name) == 0)
7741 {
7742 used_file_argc = i;
7743 used_file_indexes[used_file_count++] = i;
7744 break;
7745 }
7746 used_file_literal = literal;
7747 used_file_full_path = full_path;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007748 used_file_diff_mode = diff_mode;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007749}
7750
7751/*
7752 * Remember the length of the argument list as it was. If it changes then we
7753 * leave it alone when 'encoding' is set.
7754 */
7755 void
7756set_alist_count(void)
7757{
7758 used_alist_count = GARGCOUNT;
7759}
7760
7761/*
7762 * Fix the encoding of the command line arguments. Invoked when 'encoding'
K.Takatadc73b4b2021-06-08 18:32:36 +02007763 * has been changed while starting up. Use the UTF-16 command line arguments
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007764 * and convert them to 'encoding'.
7765 */
7766 void
7767fix_arg_enc(void)
7768{
7769 int i;
7770 int idx;
7771 char_u *str;
Bram Moolenaar86b68352004-12-27 21:59:20 +00007772 int *fnum_list;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007773
Bram Moolenaar0f873732019-12-05 20:28:46 +01007774 // Safety checks:
7775 // - if argument count differs between the wide and non-wide argument
7776 // list, something must be wrong.
7777 // - the file name arguments must have been located.
7778 // - the length of the argument list wasn't changed by the user.
Bram Moolenaard857f0e2005-06-21 22:37:39 +00007779 if (global_argc != nArgsW
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007780 || ArglistW == NULL
7781 || used_file_indexes == NULL
7782 || used_file_count == 0
7783 || used_alist_count != GARGCOUNT)
7784 return;
7785
Bram Moolenaar0f873732019-12-05 20:28:46 +01007786 // Remember the buffer numbers for the arguments.
Bram Moolenaarc799fe22019-05-28 23:08:19 +02007787 fnum_list = ALLOC_MULT(int, GARGCOUNT);
Bram Moolenaar86b68352004-12-27 21:59:20 +00007788 if (fnum_list == NULL)
Bram Moolenaar0f873732019-12-05 20:28:46 +01007789 return; // out of memory
Bram Moolenaar86b68352004-12-27 21:59:20 +00007790 for (i = 0; i < GARGCOUNT; ++i)
7791 fnum_list[i] = GARGLIST[i].ae_fnum;
7792
Bram Moolenaar0f873732019-12-05 20:28:46 +01007793 // Clear the argument list. Make room for the new arguments.
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007794 alist_clear(&global_alist);
7795 if (ga_grow(&global_alist.al_ga, used_file_count) == FAIL)
Bram Moolenaar0f873732019-12-05 20:28:46 +01007796 return; // out of memory
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007797
7798 for (i = 0; i < used_file_count; ++i)
7799 {
7800 idx = used_file_indexes[i];
Bram Moolenaar36f692d2008-11-20 16:10:17 +00007801 str = utf16_to_enc(ArglistW[idx], NULL);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007802 if (str != NULL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00007803 {
Bram Moolenaar39d21e32017-08-05 23:09:31 +02007804 int literal = used_file_literal;
7805
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007806#ifdef FEAT_DIFF
Bram Moolenaar0f873732019-12-05 20:28:46 +01007807 // When using diff mode may need to concatenate file name to
7808 // directory name. Just like it's done in main().
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007809 if (used_file_diff_mode && mch_isdir(str) && GARGCOUNT > 0
7810 && !mch_isdir(alist_name(&GARGLIST[0])))
7811 {
7812 char_u *r;
7813
7814 r = concat_fnames(str, gettail(alist_name(&GARGLIST[0])), TRUE);
7815 if (r != NULL)
7816 {
7817 vim_free(str);
7818 str = r;
7819 }
7820 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007821#endif
Bram Moolenaar0f873732019-12-05 20:28:46 +01007822 // Re-use the old buffer by renaming it. When not using literal
7823 // names it's done by alist_expand() below.
Bram Moolenaar86b68352004-12-27 21:59:20 +00007824 if (used_file_literal)
7825 buf_set_name(fnum_list[i], str);
7826
Bram Moolenaar0f873732019-12-05 20:28:46 +01007827 // Check backtick literal. backtick literal is already expanded in
7828 // main.c, so this part add str as literal.
Bram Moolenaar39d21e32017-08-05 23:09:31 +02007829 if (literal == FALSE)
7830 {
Bram Moolenaar116a0f82017-08-07 21:17:57 +02007831 size_t len = STRLEN(str);
7832
Bram Moolenaar39d21e32017-08-05 23:09:31 +02007833 if (len > 2 && *str == '`' && *(str + len - 1) == '`')
7834 literal = TRUE;
7835 }
7836 alist_add(&global_alist, str, literal ? 2 : 0);
Bram Moolenaar86b68352004-12-27 21:59:20 +00007837 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007838 }
7839
7840 if (!used_file_literal)
7841 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007842 // Now expand wildcards in the arguments.
7843 // Temporarily add '(' and ')' to 'isfname'. These are valid
7844 // filename characters but are excluded from 'isfname' to make
Dominique Pelleaf4a61a2021-12-27 17:21:41 +00007845 // "gf" work on a file name in parentheses (e.g.: see vim.h).
Bram Moolenaar0f873732019-12-05 20:28:46 +01007846 // Also, unset wildignore to not be influenced by this option.
7847 // The arguments specified in command-line should be kept even if
7848 // encoding options were changed.
Christian Brabandtfd916d62021-11-01 22:44:33 +00007849 // Use :legacy so that it also works when in Vim9 script.
7850 do_cmdline_cmd((char_u *)":legacy let g:SaVe_ISF = &isf|set isf+=(,)");
7851 do_cmdline_cmd((char_u *)":legacy let g:SaVe_WIG = &wig|set wig=");
Bram Moolenaar86b68352004-12-27 21:59:20 +00007852 alist_expand(fnum_list, used_alist_count);
Christian Brabandtfd916d62021-11-01 22:44:33 +00007853 do_cmdline_cmd(
7854 (char_u *)":legacy let &isf = g:SaVe_ISF|unlet g:SaVe_ISF");
7855 do_cmdline_cmd(
7856 (char_u *)":legacy let &wig = g:SaVe_WIG|unlet g:SaVe_WIG");
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007857 }
7858
Bram Moolenaar0f873732019-12-05 20:28:46 +01007859 // If wildcard expansion failed, we are editing the first file of the
7860 // arglist and there is no file name: Edit the first argument now.
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007861 if (curwin->w_arg_idx == 0 && curbuf->b_fname == NULL)
7862 {
7863 do_cmdline_cmd((char_u *)":rewind");
Bram Moolenaar05268152021-11-18 18:53:45 +00007864 if (GARGCOUNT == 1 && used_file_full_path
7865 && vim_chdirfile(alist_name(&GARGLIST[0]), "drop") == OK)
7866 last_chdir_reason = "drop";
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007867 }
Bram Moolenaar86b68352004-12-27 21:59:20 +00007868
7869 set_alist_count();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007870}
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007871
7872 int
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02007873mch_setenv(char *var, char *value, int x UNUSED)
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007874{
7875 char_u *envbuf;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007876 WCHAR *p;
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007877
Bram Moolenaar964b3742019-05-24 18:54:09 +02007878 envbuf = alloc(STRLEN(var) + STRLEN(value) + 2);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007879 if (envbuf == NULL)
7880 return -1;
7881
7882 sprintf((char *)envbuf, "%s=%s", var, value);
7883
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007884 p = enc_to_utf16(envbuf, NULL);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007885
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007886 vim_free(envbuf);
7887 if (p == NULL)
7888 return -1;
7889 _wputenv(p);
Bram Moolenaara12a1612019-01-24 16:39:02 +01007890#ifdef libintl_wputenv
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007891 libintl_wputenv(p);
Bram Moolenaara12a1612019-01-24 16:39:02 +01007892#endif
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007893 // Unlike Un*x systems, we can free the string for _wputenv().
7894 vim_free(p);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007895
7896 return 0;
7897}
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007898
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007899/*
7900 * Support for 256 colors and 24-bit colors was added in Windows 10
7901 * version 1703 (Creators update).
7902 */
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007903#define VTP_FIRST_SUPPORT_BUILD MAKE_VER(10, 0, 15063)
7904
7905/*
7906 * Support for pseudo-console (ConPTY) was added in windows 10
Bram Moolenaar57da6982019-09-13 22:30:11 +02007907 * version 1809 (October 2018 update).
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007908 */
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01007909#define CONPTY_FIRST_SUPPORT_BUILD MAKE_VER(10, 0, 17763)
Bram Moolenaar57da6982019-09-13 22:30:11 +02007910
7911/*
7912 * ConPTY differences between versions, need different logic.
7913 * version 1903 (May 2019 update).
7914 */
7915#define CONPTY_1903_BUILD MAKE_VER(10, 0, 18362)
7916
7917/*
Bram Moolenaar36e7a822019-11-13 21:49:24 +01007918 * version 1909 (November 2019 update).
7919 */
7920#define CONPTY_1909_BUILD MAKE_VER(10, 0, 18363)
7921
7922/*
Bram Moolenaar7ed8f592020-04-28 20:44:42 +02007923 * Stay ahead of the next update, and when it's done, fix this.
7924 * version ? (2020 update, temporarily use the build number of insider preview)
7925 */
7926#define CONPTY_NEXT_UPDATE_BUILD MAKE_VER(10, 0, 19587)
7927
7928/*
Bram Moolenaar57da6982019-09-13 22:30:11 +02007929 * Confirm until this version. Also the logic changes.
7930 * insider preview.
7931 */
Bram Moolenaar4c063dd2019-10-04 21:29:12 +02007932#define CONPTY_INSIDER_BUILD MAKE_VER(10, 0, 18995)
Bram Moolenaar57da6982019-09-13 22:30:11 +02007933
7934/*
7935 * Not stable now.
7936 */
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01007937#define CONPTY_STABLE_BUILD MAKE_VER(10, 0, 32767) // T.B.D.
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007938
7939 static void
7940vtp_flag_init(void)
7941{
7942 DWORD ver = get_build_number();
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007943#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007944 DWORD mode;
7945 HANDLE out;
7946
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007947# ifdef VIMDLL
7948 if (!gui.in_use)
7949# endif
7950 {
7951 out = GetStdHandle(STD_OUTPUT_HANDLE);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007952
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007953 vtp_working = (ver >= VTP_FIRST_SUPPORT_BUILD) ? 1 : 0;
7954 GetConsoleMode(out, &mode);
7955 mode |= (ENABLE_PROCESSED_OUTPUT | ENABLE_VIRTUAL_TERMINAL_PROCESSING);
7956 if (SetConsoleMode(out, mode) == 0)
7957 vtp_working = 0;
7958 }
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007959#endif
7960
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007961 if (ver >= CONPTY_FIRST_SUPPORT_BUILD)
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01007962 conpty_working = 1;
7963 if (ver >= CONPTY_STABLE_BUILD)
7964 conpty_stable = 1;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007965
Bram Moolenaar57da6982019-09-13 22:30:11 +02007966 if (ver <= CONPTY_INSIDER_BUILD)
7967 conpty_type = 3;
Bram Moolenaar36e7a822019-11-13 21:49:24 +01007968 if (ver <= CONPTY_1909_BUILD)
7969 conpty_type = 2;
Bram Moolenaar57da6982019-09-13 22:30:11 +02007970 if (ver <= CONPTY_1903_BUILD)
7971 conpty_type = 2;
7972 if (ver < CONPTY_FIRST_SUPPORT_BUILD)
7973 conpty_type = 1;
Bram Moolenaar7ed8f592020-04-28 20:44:42 +02007974
7975 if (ver >= CONPTY_NEXT_UPDATE_BUILD)
7976 conpty_fix_type = 1;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007977}
7978
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007979#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL) || defined(PROTO)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007980
7981 static void
7982vtp_init(void)
7983{
K.Takata27b53be2022-09-18 12:25:49 +01007984 CONSOLE_SCREEN_BUFFER_INFOEX csbi;
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007985# ifdef FEAT_TERMGUICOLORS
Yasuhiro Matsumotoaa04e1b2022-05-07 14:09:19 +01007986 COLORREF fg;
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007987# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007988
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007989 csbi.cbSize = sizeof(csbi);
K.Takata27b53be2022-09-18 12:25:49 +01007990 GetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007991 save_console_bg_rgb = (guicolor_T)csbi.ColorTable[g_color_index_bg];
7992 save_console_fg_rgb = (guicolor_T)csbi.ColorTable[g_color_index_fg];
Bram Moolenaardf543822020-01-30 11:53:59 +01007993 store_console_bg_rgb = save_console_bg_rgb;
7994 store_console_fg_rgb = save_console_fg_rgb;
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007995
7996# ifdef FEAT_TERMGUICOLORS
Yasuhiro Matsumotoe42c8da2022-09-01 11:31:45 +01007997 if (!USE_WT)
7998 {
7999 COLORREF bg;
8000 bg = (COLORREF)csbi.ColorTable[g_color_index_bg];
8001 bg = (GetRValue(bg) << 16) | (GetGValue(bg) << 8) | GetBValue(bg);
8002 default_console_color_bg = bg;
8003 }
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02008004 fg = (COLORREF)csbi.ColorTable[g_color_index_fg];
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02008005 fg = (GetRValue(fg) << 16) | (GetGValue(fg) << 8) | GetBValue(fg);
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02008006 default_console_color_fg = fg;
Bram Moolenaarc4568ab2018-11-16 16:21:05 +01008007# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008008
8009 set_console_color_rgb();
8010}
8011
8012 static void
8013vtp_exit(void)
8014{
Bram Moolenaardf543822020-01-30 11:53:59 +01008015 restore_console_color_rgb();
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008016}
8017
Bram Moolenaar06b7b582020-05-30 17:49:25 +02008018 int
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008019vtp_printf(
8020 char *format,
8021 ...)
8022{
8023 char_u buf[100];
8024 va_list list;
8025 DWORD result;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008026 int len;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008027
8028 va_start(list, format);
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008029 len = vim_vsnprintf((char *)buf, 100, (char *)format, list);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008030 va_end(list);
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008031 WriteConsoleA(g_hConOut, buf, (DWORD)len, &result, NULL);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008032 return (int)result;
8033}
8034
8035 static void
8036vtp_sgr_bulk(
8037 int arg)
8038{
8039 int args[1];
8040
8041 args[0] = arg;
8042 vtp_sgr_bulks(1, args);
8043}
8044
K.Takata6e1d31e2022-02-03 13:05:32 +00008045# define FAST256(x) \
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008046 if ((*p-- = "0123456789"[(n = x % 10)]) \
8047 && x >= 10 && (*p-- = "0123456789"[((m = x % 100) - n) / 10]) \
8048 && x >= 100 && (*p-- = "012"[((x & 0xff) - m) / 100]));
8049
K.Takata6e1d31e2022-02-03 13:05:32 +00008050# define FAST256CASE(x) \
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008051 case x: \
8052 FAST256(newargs[x - 1]);
8053
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008054 static void
8055vtp_sgr_bulks(
8056 int argc,
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008057 int *args)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008058{
K.Takata6e1d31e2022-02-03 13:05:32 +00008059# define MAXSGR 16
8060# define SGRBUFSIZE 2 + 4 * MAXSGR + 1 // '\033[' + SGR + 'm'
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008061 char_u buf[SGRBUFSIZE];
8062 char_u *p;
8063 int in, out;
8064 int newargs[16];
8065 static int sgrfgr = -1, sgrfgg, sgrfgb;
8066 static int sgrbgr = -1, sgrbgg, sgrbgb;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008067
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008068 if (argc == 0)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008069 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008070 sgrfgr = sgrbgr = -1;
K.Takatadf5320c2022-09-01 13:20:16 +01008071 vtp_printf("\033[m");
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008072 return;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008073 }
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008074
8075 in = out = 0;
8076 while (in < argc)
8077 {
8078 int s = args[in];
8079 int copylen = 1;
8080
8081 if (s == 38)
8082 {
8083 if (argc - in >= 5 && args[in + 1] == 2)
8084 {
8085 if (sgrfgr == args[in + 2] && sgrfgg == args[in + 3]
8086 && sgrfgb == args[in + 4])
8087 {
8088 in += 5;
8089 copylen = 0;
8090 }
8091 else
8092 {
8093 sgrfgr = args[in + 2];
8094 sgrfgg = args[in + 3];
8095 sgrfgb = args[in + 4];
8096 copylen = 5;
8097 }
8098 }
8099 else if (argc - in >= 3 && args[in + 1] == 5)
8100 {
8101 sgrfgr = -1;
8102 copylen = 3;
8103 }
8104 }
8105 else if (s == 48)
8106 {
8107 if (argc - in >= 5 && args[in + 1] == 2)
8108 {
8109 if (sgrbgr == args[in + 2] && sgrbgg == args[in + 3]
8110 && sgrbgb == args[in + 4])
8111 {
8112 in += 5;
8113 copylen = 0;
8114 }
8115 else
8116 {
8117 sgrbgr = args[in + 2];
8118 sgrbgg = args[in + 3];
8119 sgrbgb = args[in + 4];
8120 copylen = 5;
8121 }
8122 }
8123 else if (argc - in >= 3 && args[in + 1] == 5)
8124 {
8125 sgrbgr = -1;
8126 copylen = 3;
8127 }
8128 }
8129 else if (30 <= s && s <= 39)
8130 sgrfgr = -1;
8131 else if (90 <= s && s <= 97)
8132 sgrfgr = -1;
8133 else if (40 <= s && s <= 49)
8134 sgrbgr = -1;
8135 else if (100 <= s && s <= 107)
8136 sgrbgr = -1;
8137 else if (s == 0)
8138 sgrfgr = sgrbgr = -1;
8139
8140 while (copylen--)
8141 newargs[out++] = args[in++];
8142 }
8143
8144 p = &buf[sizeof(buf) - 1];
8145 *p-- = 'm';
8146
8147 switch (out)
8148 {
8149 int n, m;
8150 DWORD r;
8151
8152 FAST256CASE(16);
8153 *p-- = ';';
8154 FAST256CASE(15);
8155 *p-- = ';';
8156 FAST256CASE(14);
8157 *p-- = ';';
8158 FAST256CASE(13);
8159 *p-- = ';';
8160 FAST256CASE(12);
8161 *p-- = ';';
8162 FAST256CASE(11);
8163 *p-- = ';';
8164 FAST256CASE(10);
8165 *p-- = ';';
8166 FAST256CASE(9);
8167 *p-- = ';';
8168 FAST256CASE(8);
8169 *p-- = ';';
8170 FAST256CASE(7);
8171 *p-- = ';';
8172 FAST256CASE(6);
8173 *p-- = ';';
8174 FAST256CASE(5);
8175 *p-- = ';';
8176 FAST256CASE(4);
8177 *p-- = ';';
8178 FAST256CASE(3);
8179 *p-- = ';';
8180 FAST256CASE(2);
8181 *p-- = ';';
8182 FAST256CASE(1);
8183 *p-- = '[';
8184 *p = '\033';
8185 WriteConsoleA(g_hConOut, p, (DWORD)(&buf[SGRBUFSIZE] - p), &r, NULL);
8186 default:
8187 break;
8188 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008189}
8190
Bram Moolenaar06b7b582020-05-30 17:49:25 +02008191 static void
8192wt_init(void)
8193{
8194 wt_working = (mch_getenv("WT_SESSION") != NULL);
8195}
8196
8197 int
8198use_wt(void)
8199{
8200 return USE_WT;
8201}
8202
Bram Moolenaar8a938af2018-05-01 17:30:41 +02008203# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02008204 static int
8205ctermtoxterm(
8206 int cterm)
8207{
Bram Moolenaar9894e392018-05-05 14:29:06 +02008208 char_u r, g, b, idx;
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02008209
8210 cterm_color2rgb(cterm, &r, &g, &b, &idx);
8211 return (((int)r << 16) | ((int)g << 8) | (int)b);
8212}
Bram Moolenaar8a938af2018-05-01 17:30:41 +02008213# endif
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02008214
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008215 static void
8216set_console_color_rgb(void)
8217{
8218# ifdef FEAT_TERMGUICOLORS
K.Takata27b53be2022-09-18 12:25:49 +01008219 CONSOLE_SCREEN_BUFFER_INFOEX csbi;
Bram Moolenaara050b942019-12-02 21:35:31 +01008220 guicolor_T fg, bg;
8221 int ctermfg, ctermbg;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008222
8223 if (!USE_VTP)
8224 return;
8225
Bram Moolenaara050b942019-12-02 21:35:31 +01008226 get_default_console_color(&ctermfg, &ctermbg, &fg, &bg);
8227
Bram Moolenaar06b7b582020-05-30 17:49:25 +02008228 if (USE_WT)
8229 {
8230 term_fg_rgb_color(fg);
8231 term_bg_rgb_color(bg);
8232 return;
8233 }
8234
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008235 fg = (GetRValue(fg) << 16) | (GetGValue(fg) << 8) | GetBValue(fg);
8236 bg = (GetRValue(bg) << 16) | (GetGValue(bg) << 8) | GetBValue(bg);
8237
8238 csbi.cbSize = sizeof(csbi);
K.Takata27b53be2022-09-18 12:25:49 +01008239 GetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008240
8241 csbi.cbSize = sizeof(csbi);
8242 csbi.srWindow.Right += 1;
8243 csbi.srWindow.Bottom += 1;
Bram Moolenaardf543822020-01-30 11:53:59 +01008244 store_console_bg_rgb = csbi.ColorTable[g_color_index_bg];
8245 store_console_fg_rgb = csbi.ColorTable[g_color_index_fg];
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02008246 csbi.ColorTable[g_color_index_bg] = (COLORREF)bg;
8247 csbi.ColorTable[g_color_index_fg] = (COLORREF)fg;
K.Takata27b53be2022-09-18 12:25:49 +01008248 SetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008249# endif
8250}
8251
Bram Moolenaara050b942019-12-02 21:35:31 +01008252# if defined(FEAT_TERMGUICOLORS) || defined(PROTO)
8253 void
8254get_default_console_color(
8255 int *cterm_fg,
8256 int *cterm_bg,
8257 guicolor_T *gui_fg,
8258 guicolor_T *gui_bg)
8259{
8260 int id;
8261 guicolor_T guifg = INVALCOLOR;
8262 guicolor_T guibg = INVALCOLOR;
8263 int ctermfg = 0;
8264 int ctermbg = 0;
8265
8266 id = syn_name2id((char_u *)"Normal");
8267 if (id > 0 && p_tgc)
8268 syn_id2colors(id, &guifg, &guibg);
8269 if (guifg == INVALCOLOR)
8270 {
8271 ctermfg = -1;
8272 if (id > 0)
8273 syn_id2cterm_bg(id, &ctermfg, &ctermbg);
8274 guifg = ctermfg != -1 ? ctermtoxterm(ctermfg)
8275 : default_console_color_fg;
8276 cterm_normal_fg_gui_color = guifg;
8277 ctermfg = ctermfg < 0 ? 0 : ctermfg;
8278 }
8279 if (guibg == INVALCOLOR)
8280 {
8281 ctermbg = -1;
8282 if (id > 0)
8283 syn_id2cterm_bg(id, &ctermfg, &ctermbg);
K.Takatae53a0d42022-09-05 21:45:11 +01008284 if (USE_WT)
Yasuhiro Matsumotoe42c8da2022-09-01 11:31:45 +01008285 {
8286 cterm_normal_bg_gui_color = guibg =
Yasuhiro Matsumotoaa04e1b2022-05-07 14:09:19 +01008287 ctermbg != -1 ? ctermtoxterm(ctermbg) : INVALCOLOR;
Yasuhiro Matsumotoe42c8da2022-09-01 11:31:45 +01008288 if (ctermbg < 0)
8289 ctermbg = 0;
8290 }
K.Takatae53a0d42022-09-05 21:45:11 +01008291 else
8292 {
8293 guibg = ctermbg != -1 ? ctermtoxterm(ctermbg)
8294 : default_console_color_bg;
8295 cterm_normal_bg_gui_color = guibg;
8296 ctermbg = ctermbg < 0 ? 0 : ctermbg;
8297 }
Bram Moolenaara050b942019-12-02 21:35:31 +01008298 }
8299
8300 *cterm_fg = ctermfg;
8301 *cterm_bg = ctermbg;
8302 *gui_fg = guifg;
8303 *gui_bg = guibg;
8304}
8305# endif
8306
Bram Moolenaardf543822020-01-30 11:53:59 +01008307/*
8308 * Set the console colors to the original colors or the last set colors.
8309 */
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008310 static void
8311reset_console_color_rgb(void)
8312{
8313# ifdef FEAT_TERMGUICOLORS
K.Takata27b53be2022-09-18 12:25:49 +01008314 CONSOLE_SCREEN_BUFFER_INFOEX csbi;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008315
Bram Moolenaar06b7b582020-05-30 17:49:25 +02008316 if (USE_WT)
8317 return;
8318
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008319 csbi.cbSize = sizeof(csbi);
K.Takata27b53be2022-09-18 12:25:49 +01008320 GetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008321
8322 csbi.cbSize = sizeof(csbi);
8323 csbi.srWindow.Right += 1;
8324 csbi.srWindow.Bottom += 1;
Bram Moolenaardf543822020-01-30 11:53:59 +01008325 csbi.ColorTable[g_color_index_bg] = (COLORREF)store_console_bg_rgb;
8326 csbi.ColorTable[g_color_index_fg] = (COLORREF)store_console_fg_rgb;
K.Takata27b53be2022-09-18 12:25:49 +01008327 SetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaardf543822020-01-30 11:53:59 +01008328# endif
8329}
8330
8331/*
8332 * Set the console colors to the original colors.
8333 */
8334 static void
8335restore_console_color_rgb(void)
8336{
8337# ifdef FEAT_TERMGUICOLORS
K.Takata27b53be2022-09-18 12:25:49 +01008338 CONSOLE_SCREEN_BUFFER_INFOEX csbi;
Bram Moolenaardf543822020-01-30 11:53:59 +01008339
8340 csbi.cbSize = sizeof(csbi);
K.Takata27b53be2022-09-18 12:25:49 +01008341 GetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaardf543822020-01-30 11:53:59 +01008342
8343 csbi.cbSize = sizeof(csbi);
8344 csbi.srWindow.Right += 1;
8345 csbi.srWindow.Bottom += 1;
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02008346 csbi.ColorTable[g_color_index_bg] = (COLORREF)save_console_bg_rgb;
8347 csbi.ColorTable[g_color_index_fg] = (COLORREF)save_console_fg_rgb;
K.Takata27b53be2022-09-18 12:25:49 +01008348 SetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008349# endif
8350}
8351
8352 void
8353control_console_color_rgb(void)
8354{
8355 if (USE_VTP)
8356 set_console_color_rgb();
8357 else
8358 reset_console_color_rgb();
8359}
8360
8361 int
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008362use_vtp(void)
8363{
8364 return USE_VTP;
8365}
8366
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02008367 int
8368is_term_win32(void)
8369{
8370 return T_NAME != NULL && STRCMP(T_NAME, "win32") == 0;
8371}
8372
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008373 int
8374has_vtp_working(void)
8375{
8376 return vtp_working;
8377}
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01008378
Bram Moolenaar6902c0e2019-02-16 14:07:37 +01008379#endif
8380
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01008381 int
8382has_conpty_working(void)
8383{
8384 return conpty_working;
8385}
8386
8387 int
Bram Moolenaar57da6982019-09-13 22:30:11 +02008388get_conpty_type(void)
8389{
8390 return conpty_type;
8391}
8392
8393 int
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01008394is_conpty_stable(void)
8395{
8396 return conpty_stable;
8397}
Bram Moolenaar78d21da2019-02-17 15:00:52 +01008398
Bram Moolenaar7ed8f592020-04-28 20:44:42 +02008399 int
8400get_conpty_fix_type(void)
8401{
8402 return conpty_fix_type;
8403}
8404
Bram Moolenaarafde13b2019-04-28 19:46:49 +02008405#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL) || defined(PROTO)
Bram Moolenaar78d21da2019-02-17 15:00:52 +01008406 void
8407resize_console_buf(void)
8408{
8409 CONSOLE_SCREEN_BUFFER_INFO csbi;
8410 COORD coord;
8411 SMALL_RECT newsize;
8412
8413 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
8414 {
8415 coord.X = SRWIDTH(csbi.srWindow);
8416 coord.Y = SRHEIGHT(csbi.srWindow);
8417 SetConsoleScreenBufferSize(g_hConOut, coord);
8418
8419 newsize.Left = 0;
8420 newsize.Top = 0;
8421 newsize.Right = coord.X - 1;
8422 newsize.Bottom = coord.Y - 1;
8423 SetConsoleWindowInfo(g_hConOut, TRUE, &newsize);
8424
8425 SetConsoleScreenBufferSize(g_hConOut, coord);
8426 }
8427}
8428#endif
Martin Tournoij1a3e5742021-07-24 13:57:29 +02008429
8430 char *
8431GetWin32Error(void)
8432{
K.Takatad68b2fc2022-02-12 11:18:37 +00008433 static char *oldmsg = NULL;
Martin Tournoij1a3e5742021-07-24 13:57:29 +02008434 char *msg = NULL;
K.Takatad68b2fc2022-02-12 11:18:37 +00008435
Martin Tournoij1a3e5742021-07-24 13:57:29 +02008436 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER|FORMAT_MESSAGE_FROM_SYSTEM,
8437 NULL, GetLastError(), 0, (LPSTR)&msg, 0, NULL);
K.Takatad68b2fc2022-02-12 11:18:37 +00008438 if (oldmsg != NULL)
8439 LocalFree(oldmsg);
Martin Tournoij1a3e5742021-07-24 13:57:29 +02008440 if (msg != NULL)
8441 {
8442 // remove trailing \r\n
8443 char *pcrlf = strstr(msg, "\r\n");
8444 if (pcrlf != NULL)
8445 *pcrlf = '\0';
K.Takatad68b2fc2022-02-12 11:18:37 +00008446 oldmsg = msg;
Martin Tournoij1a3e5742021-07-24 13:57:29 +02008447 }
8448 return msg;
8449}
Paul Ollis65745772022-06-05 16:55:54 +01008450
8451#if defined(FEAT_RELTIME) || defined(PROTO)
8452static HANDLE timer_handle;
8453static int timer_active = FALSE;
8454
8455/*
8456 * Calls to start_timeout alternate the return value pointer between the two
8457 * entries in timeout_flags. If the previously active timeout is very close to
8458 * expiring when start_timeout() is called then a race condition means that the
8459 * set_flag() function may still be invoked after the previous timer is
8460 * deleted. Ping-ponging between the two flags prevents this causing 'fake'
8461 * timeouts.
8462 */
Bram Moolenaar155f2d12022-06-20 13:38:33 +01008463static sig_atomic_t timeout_flags[2];
8464static int timeout_flag_idx = 0;
8465static sig_atomic_t *timeout_flag = &timeout_flags[0];
Paul Ollis65745772022-06-05 16:55:54 +01008466
8467
8468 static void CALLBACK
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +01008469set_flag(void *param, BOOLEAN unused2 UNUSED)
Paul Ollis65745772022-06-05 16:55:54 +01008470{
8471 int *timeout_flag = (int *)param;
8472
8473 *timeout_flag = TRUE;
8474}
8475
8476/*
8477 * Stop any active timeout.
8478 */
8479 void
8480stop_timeout(void)
8481{
8482 if (timer_active)
8483 {
Christopher Plewright2a46f812022-10-16 19:47:45 +01008484 BOOL ret = DeleteTimerQueueTimer(NULL, timer_handle, NULL);
Paul Ollis65745772022-06-05 16:55:54 +01008485 timer_active = FALSE;
8486 if (!ret && GetLastError() != ERROR_IO_PENDING)
8487 {
8488 semsg(_(e_could_not_clear_timeout_str), GetWin32Error());
8489 }
8490 }
8491 *timeout_flag = FALSE;
8492}
8493
8494/*
8495 * Start the timeout timer.
8496 *
8497 * The period is defined in milliseconds.
8498 *
8499 * The return value is a pointer to a flag that is initialised to 0. If the
8500 * timeout expires, the flag is set to 1. This will only return pointers to
8501 * static memory; i.e. any pointer returned by this function may always be
8502 * safely dereferenced.
8503 *
8504 * This function is not expected to fail, but if it does it still returns a
8505 * valid flag pointer; the flag will remain stuck at zero.
8506 */
Bram Moolenaar155f2d12022-06-20 13:38:33 +01008507 volatile sig_atomic_t *
Paul Ollis65745772022-06-05 16:55:54 +01008508start_timeout(long msec)
8509{
Paul Ollis65745772022-06-05 16:55:54 +01008510 BOOL ret;
8511
Bram Moolenaar1f30caf2022-06-19 14:36:35 +01008512 timeout_flag = &timeout_flags[timeout_flag_idx];
Paul Ollis65745772022-06-05 16:55:54 +01008513
8514 stop_timeout();
8515 ret = CreateTimerQueueTimer(
8516 &timer_handle, NULL, set_flag, timeout_flag,
8517 (DWORD)msec, 0, WT_EXECUTEDEFAULT);
8518 if (!ret)
8519 {
8520 semsg(_(e_could_not_set_timeout_str), GetWin32Error());
8521 }
8522 else
8523 {
Bram Moolenaar1f30caf2022-06-19 14:36:35 +01008524 timeout_flag_idx = (timeout_flag_idx + 1) % 2;
Paul Ollis65745772022-06-05 16:55:54 +01008525 timer_active = TRUE;
8526 *timeout_flag = FALSE;
8527 }
8528 return timeout_flag;
8529}
8530#endif