blob: f12e75f1140a2e445eb4faaedde7a43752691f09 [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;
Christopher Plewright20b795e2022-12-20 20:01:58 +0000180// The 'input_record_buffer' is an internal dynamic fifo queue of MS-Windows
181// console INPUT_RECORD events that are normally read from the console input
182// buffer. This provides an injection point for testing the low-level handling
183// of INPUT_RECORDs.
184typedef struct input_record_buffer_node_S
185{
186 INPUT_RECORD ir;
187 struct input_record_buffer_node_S *next;
188} input_record_buffer_node_T;
189typedef struct input_record_buffer_S
190{
191 input_record_buffer_node_T *head;
192 input_record_buffer_node_T *tail;
193 int length;
194} input_record_buffer_T;
195static input_record_buffer_T input_record_buffer;
Christopher Plewright20b795e2022-12-20 20:01:58 +0000196static int read_input_record_buffer(INPUT_RECORD* irEvents, int nMaxLength);
197static int write_input_record_buffer(INPUT_RECORD* irEvents, int nLength);
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200198#endif
199#ifdef FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +0000200static int s_dont_use_vimrun = TRUE;
201static int need_vimrun_warning = FALSE;
202static char *vimrun_path = "vimrun ";
203#endif
204
Bram Moolenaar12b559e2013-06-12 22:41:37 +0200205static int win32_getattrs(char_u *name);
206static int win32_setattrs(char_u *name, int attrs);
207static int win32_set_archive(char_u *name);
208
Bram Moolenaard9ef1b82019-02-13 19:23:10 +0100209static int conpty_working = 0;
Bram Moolenaar57da6982019-09-13 22:30:11 +0200210static int conpty_type = 0;
Bram Moolenaard9ef1b82019-02-13 19:23:10 +0100211static int conpty_stable = 0;
Bram Moolenaar7ed8f592020-04-28 20:44:42 +0200212static int conpty_fix_type = 0;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100213static void vtp_flag_init();
214
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200215#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar6902c0e2019-02-16 14:07:37 +0100216static int vtp_working = 0;
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100217static void vtp_init();
218static void vtp_exit();
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100219static void vtp_sgr_bulk(int arg);
220static void vtp_sgr_bulks(int argc, int *argv);
221
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200222static int wt_working = 0;
Christopher Plewright1140b512022-11-12 18:46:05 +0000223static void wt_init(void);
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200224
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +0200225static int g_color_index_bg = 0;
226static int g_color_index_fg = 7;
227
228# ifdef FEAT_TERMGUICOLORS
Christopher Plewright38804d62022-11-09 23:55:52 +0000229static guicolor_T save_console_bg_rgb;
230static guicolor_T save_console_fg_rgb;
231static guicolor_T store_console_bg_rgb;
232static guicolor_T store_console_fg_rgb;
Yasuhiro Matsumotoe42c8da2022-09-01 11:31:45 +0100233static int default_console_color_bg = 0x000000; // black
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +0200234static int default_console_color_fg = 0xc0c0c0; // white
Christopher Plewright38804d62022-11-09 23:55:52 +0000235# define USE_VTP (vtp_working && is_term_win32())
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200236# define USE_WT (wt_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100237# else
238# define USE_VTP 0
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200239# define USE_WT 0
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100240# endif
241
242static void set_console_color_rgb(void);
243static void reset_console_color_rgb(void);
Bram Moolenaardf543822020-01-30 11:53:59 +0100244static void restore_console_color_rgb(void);
Christopher Plewright20b795e2022-12-20 20:01:58 +0000245#endif // !FEAT_GUI_MSWIN || VIMDLL
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100246
Bram Moolenaar0f873732019-12-05 20:28:46 +0100247// This flag is newly created from Windows 10
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100248#ifndef ENABLE_VIRTUAL_TERMINAL_PROCESSING
249# define ENABLE_VIRTUAL_TERMINAL_PROCESSING 0x0004
250#endif
251
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200252#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar0f873732019-12-05 20:28:46 +0100253static int suppress_winsize = 1; // don't fiddle with console
Bram Moolenaar071d4272004-06-13 20:20:40 +0000254#endif
255
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200256static char_u *exe_path = NULL;
257
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100258static BOOL win8_or_later = FALSE;
Christopher Plewrightc8b126d2022-12-22 13:45:23 +0000259static BOOL win10_22H2_or_later = FALSE;
Bram Moolenaar9fca1332022-12-22 21:06:41 +0000260#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Christopher Plewrightc8b126d2022-12-22 13:45:23 +0000261static BOOL use_alternate_screen_buffer = FALSE;
Bram Moolenaar9fca1332022-12-22 21:06:41 +0000262#endif
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100263
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100264/*
265 * Get version number including build number
266 */
267typedef BOOL (WINAPI *PfnRtlGetVersion)(LPOSVERSIONINFOW);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100268#define MAKE_VER(major, minor, build) \
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100269 (((major) << 24) | ((minor) << 16) | (build))
270
271 static DWORD
272get_build_number(void)
273{
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +0100274 OSVERSIONINFOW osver;
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100275 HMODULE hNtdll;
276 PfnRtlGetVersion pRtlGetVersion;
277 DWORD ver = MAKE_VER(0, 0, 0);
278
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +0100279 osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFOW);
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100280 hNtdll = GetModuleHandle("ntdll.dll");
281 if (hNtdll != NULL)
282 {
283 pRtlGetVersion =
284 (PfnRtlGetVersion)GetProcAddress(hNtdll, "RtlGetVersion");
285 pRtlGetVersion(&osver);
286 ver = MAKE_VER(min(osver.dwMajorVersion, 255),
287 min(osver.dwMinorVersion, 255),
288 min(osver.dwBuildNumber, 32767));
289 }
290 return ver;
291}
292
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200293#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200294 static BOOL
295is_ambiwidth_event(
296 INPUT_RECORD *ir)
297{
298 return ir->EventType == KEY_EVENT
299 && ir->Event.KeyEvent.bKeyDown
300 && ir->Event.KeyEvent.wRepeatCount == 1
301 && ir->Event.KeyEvent.wVirtualKeyCode == 0x12
302 && ir->Event.KeyEvent.wVirtualScanCode == 0x38
K.Takata972db232022-02-04 10:45:38 +0000303 && ir->Event.KeyEvent.uChar.UnicodeChar == 0
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200304 && ir->Event.KeyEvent.dwControlKeyState == 2;
305}
306
307 static void
308make_ambiwidth_event(
309 INPUT_RECORD *down,
310 INPUT_RECORD *up)
311{
312 down->Event.KeyEvent.wVirtualKeyCode = 0;
313 down->Event.KeyEvent.wVirtualScanCode = 0;
K.Takata972db232022-02-04 10:45:38 +0000314 down->Event.KeyEvent.uChar.UnicodeChar
315 = up->Event.KeyEvent.uChar.UnicodeChar;
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200316 down->Event.KeyEvent.dwControlKeyState = 0;
317}
318
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100319/*
320 * Version of ReadConsoleInput() that works with IME.
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100321 * Works around problems on Windows 8.
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100322 */
323 static BOOL
324read_console_input(
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100325 HANDLE hInput,
326 INPUT_RECORD *lpBuffer,
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +0100327 int nLength,
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100328 LPDWORD lpEvents)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100329{
330 enum
331 {
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100332 IRSIZE = 10
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100333 };
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100334 static INPUT_RECORD s_irCache[IRSIZE];
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100335 static DWORD s_dwIndex = 0;
336 static DWORD s_dwMax = 0;
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100337 DWORD dwEvents;
Bram Moolenaardd415a62014-02-05 14:02:27 +0100338 int head;
339 int tail;
340 int i;
Bram Moolenaarbc970da2020-04-26 19:00:07 +0200341 static INPUT_RECORD s_irPseudo;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100342
Christopher Plewright20b795e2022-12-20 20:01:58 +0000343 if (s_dwMax == 0 && input_record_buffer.length > 0)
344 {
345 dwEvents = read_input_record_buffer(s_irCache, IRSIZE);
346 s_dwIndex = 0;
347 s_dwMax = dwEvents;
348 }
349
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200350 if (nLength == -2)
351 return (s_dwMax > 0) ? TRUE : FALSE;
352
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100353 if (!win8_or_later)
354 {
355 if (nLength == -1)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200356 return PeekConsoleInputW(hInput, lpBuffer, 1, lpEvents);
357 return ReadConsoleInputW(hInput, lpBuffer, 1, &dwEvents);
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100358 }
359
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100360 if (s_dwMax == 0)
361 {
Christopher Plewright38804d62022-11-09 23:55:52 +0000362 if (!vtp_working && nLength == -1)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200363 return PeekConsoleInputW(hInput, lpBuffer, 1, lpEvents);
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200364 GetNumberOfConsoleInputEvents(hInput, &dwEvents);
365 if (dwEvents == 0 && nLength == -1)
366 return PeekConsoleInputW(hInput, lpBuffer, 1, lpEvents);
367 ReadConsoleInputW(hInput, s_irCache, IRSIZE, &dwEvents);
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100368 s_dwIndex = 0;
369 s_dwMax = dwEvents;
370 if (dwEvents == 0)
371 {
372 *lpEvents = 0;
373 return TRUE;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100374 }
Bram Moolenaardd415a62014-02-05 14:02:27 +0100375
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200376 for (i = s_dwIndex; i < (int)s_dwMax - 1; ++i)
377 if (is_ambiwidth_event(&s_irCache[i]))
378 make_ambiwidth_event(&s_irCache[i], &s_irCache[i + 1]);
379
Bram Moolenaardd415a62014-02-05 14:02:27 +0100380 if (s_dwMax > 1)
381 {
382 head = 0;
383 tail = s_dwMax - 1;
384 while (head != tail)
385 {
386 if (s_irCache[head].EventType == WINDOW_BUFFER_SIZE_EVENT
387 && s_irCache[head + 1].EventType
388 == WINDOW_BUFFER_SIZE_EVENT)
389 {
Bram Moolenaar0f873732019-12-05 20:28:46 +0100390 // Remove duplicate event to avoid flicker.
Bram Moolenaardd415a62014-02-05 14:02:27 +0100391 for (i = head; i < tail; ++i)
392 s_irCache[i] = s_irCache[i + 1];
393 --tail;
394 continue;
395 }
396 head++;
397 }
398 s_dwMax = tail + 1;
399 }
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100400 }
Bram Moolenaardd415a62014-02-05 14:02:27 +0100401
Bram Moolenaarbc970da2020-04-26 19:00:07 +0200402 if (s_irCache[s_dwIndex].EventType == KEY_EVENT)
403 {
404 if (s_irCache[s_dwIndex].Event.KeyEvent.wRepeatCount > 1)
405 {
406 s_irPseudo = s_irCache[s_dwIndex];
407 s_irPseudo.Event.KeyEvent.wRepeatCount = 1;
408 s_irCache[s_dwIndex].Event.KeyEvent.wRepeatCount--;
409 *lpBuffer = s_irPseudo;
410 *lpEvents = 1;
411 return TRUE;
412 }
413 }
414
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100415 *lpBuffer = s_irCache[s_dwIndex];
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200416 if (!(nLength == -1 || nLength == -2) && ++s_dwIndex >= s_dwMax)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100417 s_dwMax = 0;
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100418 *lpEvents = 1;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100419 return TRUE;
420}
421
422/*
423 * Version of PeekConsoleInput() that works with IME.
424 */
425 static BOOL
426peek_console_input(
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100427 HANDLE hInput,
428 INPUT_RECORD *lpBuffer,
Bram Moolenaarbd67aac2019-09-21 23:09:04 +0200429 DWORD nLength UNUSED,
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100430 LPDWORD lpEvents)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100431{
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +0100432 return read_console_input(hInput, lpBuffer, -1, lpEvents);
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100433}
434
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100435# ifdef FEAT_CLIENTSERVER
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200436 static DWORD
437msg_wait_for_multiple_objects(
438 DWORD nCount,
439 LPHANDLE pHandles,
440 BOOL fWaitAll,
441 DWORD dwMilliseconds,
442 DWORD dwWakeMask)
443{
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +0100444 if (read_console_input(NULL, NULL, -2, NULL))
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200445 return WAIT_OBJECT_0;
446 return MsgWaitForMultipleObjects(nCount, pHandles, fWaitAll,
447 dwMilliseconds, dwWakeMask);
448}
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100449# endif
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200450
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100451# ifndef FEAT_CLIENTSERVER
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200452 static DWORD
453wait_for_single_object(
454 HANDLE hHandle,
455 DWORD dwMilliseconds)
456{
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +0100457 if (read_console_input(NULL, NULL, -2, NULL))
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200458 return WAIT_OBJECT_0;
459 return WaitForSingleObject(hHandle, dwMilliseconds);
460}
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100461# endif
Christopher Plewright20b795e2022-12-20 20:01:58 +0000462#endif // !FEAT_GUI_MSWIN || VIMDLL
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200463
Bram Moolenaar071d4272004-06-13 20:20:40 +0000464 static void
465get_exe_name(void)
466{
Bram Moolenaar0f873732019-12-05 20:28:46 +0100467 // Maximum length of $PATH is more than MAXPATHL. 8191 is often mentioned
468 // as the maximum length that works (plus a NUL byte).
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100469#define MAX_ENV_PATH_LEN 8192
470 char temp[MAX_ENV_PATH_LEN];
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200471 char_u *p;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000472
473 if (exe_name == NULL)
474 {
Bram Moolenaar0f873732019-12-05 20:28:46 +0100475 // store the name of the executable, may be used for $VIM
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100476 GetModuleFileName(NULL, temp, MAX_ENV_PATH_LEN - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000477 if (*temp != NUL)
478 exe_name = FullName_save((char_u *)temp, FALSE);
479 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000480
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200481 if (exe_path == NULL && exe_name != NULL)
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000482 {
Bram Moolenaar71ccd032020-06-12 22:59:11 +0200483 exe_path = vim_strnsave(exe_name, gettail_sep(exe_name) - exe_name);
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200484 if (exe_path != NULL)
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000485 {
Bram Moolenaar0f873732019-12-05 20:28:46 +0100486 // Append our starting directory to $PATH, so that when doing
487 // "!xxd" it's found in our starting directory. Needed because
488 // SearchPath() also looks there.
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200489 p = mch_getenv("PATH");
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100490 if (p == NULL
491 || STRLEN(p) + STRLEN(exe_path) + 2 < MAX_ENV_PATH_LEN)
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200492 {
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100493 if (p == NULL || *p == NUL)
494 temp[0] = NUL;
495 else
496 {
497 STRCPY(temp, p);
498 STRCAT(temp, ";");
499 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200500 STRCAT(temp, exe_path);
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +0100501 vim_setenv((char_u *)"PATH", (char_u *)temp);
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200502 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000503 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000504 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000505}
506
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200507/*
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100508 * Unescape characters in "p" that appear in "escaped".
509 */
510 static void
511unescape_shellxquote(char_u *p, char_u *escaped)
512{
Bram Moolenaar4336cdf2012-02-29 13:58:47 +0100513 int l = (int)STRLEN(p);
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100514 int n;
515
516 while (*p != NUL)
517 {
518 if (*p == '^' && vim_strchr(escaped, p[1]) != NULL)
519 mch_memmove(p, p + 1, l--);
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100520 n = (*mb_ptr2len)(p);
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100521 p += n;
522 l -= n;
523 }
524}
525
526/*
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200527 * Load library "name".
528 */
529 HINSTANCE
K.Takatad68b2fc2022-02-12 11:18:37 +0000530vimLoadLib(const char *name)
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200531{
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200532 HINSTANCE dll = NULL;
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200533
Bram Moolenaar3d0e7a92021-05-01 17:46:03 +0200534 // No need to load any library when registering OLE.
535 if (found_register_arg)
536 return dll;
537
Bram Moolenaar0f873732019-12-05 20:28:46 +0100538 // NOTE: Do not use mch_dirname() and mch_chdir() here, they may call
539 // vimLoadLib() recursively, which causes a stack overflow.
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200540 if (exe_path == NULL)
541 get_exe_name();
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200542 if (exe_path != NULL)
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200543 {
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200544 WCHAR old_dirw[MAXPATHL];
545
546 if (GetCurrentDirectoryW(MAXPATHL, old_dirw) != 0)
547 {
Bram Moolenaar0f873732019-12-05 20:28:46 +0100548 // Change directory to where the executable is, both to make
549 // sure we find a .dll there and to avoid looking for a .dll
550 // in the current directory.
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +0100551 SetCurrentDirectory((LPCSTR)exe_path);
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200552 dll = LoadLibrary(name);
553 SetCurrentDirectoryW(old_dirw);
554 return dll;
555 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200556 }
557 return dll;
558}
559
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200560#if defined(VIMDLL) || defined(PROTO)
561/*
562 * Check if the current executable file is for the GUI subsystem.
563 */
564 int
565mch_is_gui_executable(void)
566{
567 PBYTE pImage = (PBYTE)GetModuleHandle(NULL);
568 PIMAGE_DOS_HEADER pDOS = (PIMAGE_DOS_HEADER)pImage;
569 PIMAGE_NT_HEADERS pPE;
570
571 if (pDOS->e_magic != IMAGE_DOS_SIGNATURE)
572 return FALSE;
573 pPE = (PIMAGE_NT_HEADERS)(pImage + pDOS->e_lfanew);
574 if (pPE->Signature != IMAGE_NT_SIGNATURE)
575 return FALSE;
576 if (pPE->OptionalHeader.Subsystem == IMAGE_SUBSYSTEM_WINDOWS_GUI)
577 return TRUE;
578 return FALSE;
579}
580#endif
581
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000582#if defined(DYNAMIC_ICONV) || defined(DYNAMIC_GETTEXT) \
583 || defined(FEAT_PYTHON3) || defined(PROTO)
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100584/*
585 * Get related information about 'funcname' which is imported by 'hInst'.
586 * If 'info' is 0, return the function address.
587 * If 'info' is 1, return the module name which the function is imported from.
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000588 * If 'info' is 2, hook the function with 'ptr', and return the original
589 * function address.
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100590 */
591 static void *
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000592get_imported_func_info(HINSTANCE hInst, const char *funcname, int info,
593 const void *ptr)
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100594{
595 PBYTE pImage = (PBYTE)hInst;
596 PIMAGE_DOS_HEADER pDOS = (PIMAGE_DOS_HEADER)hInst;
597 PIMAGE_NT_HEADERS pPE;
598 PIMAGE_IMPORT_DESCRIPTOR pImpDesc;
Bram Moolenaar0f873732019-12-05 20:28:46 +0100599 PIMAGE_THUNK_DATA pIAT; // Import Address Table
600 PIMAGE_THUNK_DATA pINT; // Import Name Table
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100601 PIMAGE_IMPORT_BY_NAME pImpName;
602
603 if (pDOS->e_magic != IMAGE_DOS_SIGNATURE)
604 return NULL;
605 pPE = (PIMAGE_NT_HEADERS)(pImage + pDOS->e_lfanew);
606 if (pPE->Signature != IMAGE_NT_SIGNATURE)
607 return NULL;
608 pImpDesc = (PIMAGE_IMPORT_DESCRIPTOR)(pImage
609 + pPE->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT]
610 .VirtualAddress);
611 for (; pImpDesc->FirstThunk; ++pImpDesc)
612 {
613 if (!pImpDesc->OriginalFirstThunk)
614 continue;
615 pIAT = (PIMAGE_THUNK_DATA)(pImage + pImpDesc->FirstThunk);
616 pINT = (PIMAGE_THUNK_DATA)(pImage + pImpDesc->OriginalFirstThunk);
617 for (; pIAT->u1.Function; ++pIAT, ++pINT)
618 {
619 if (IMAGE_SNAP_BY_ORDINAL(pINT->u1.Ordinal))
620 continue;
621 pImpName = (PIMAGE_IMPORT_BY_NAME)(pImage
622 + (UINT_PTR)(pINT->u1.AddressOfData));
623 if (strcmp((char *)pImpName->Name, funcname) == 0)
624 {
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000625 void *original;
626 DWORD old, new = PAGE_READWRITE;
627
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100628 switch (info)
629 {
630 case 0:
631 return (void *)pIAT->u1.Function;
632 case 1:
633 return (void *)(pImage + pImpDesc->Name);
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000634 case 2:
635 original = (void *)pIAT->u1.Function;
636 VirtualProtect(&pIAT->u1.Function, sizeof(void *),
637 new, &old);
638 pIAT->u1.Function = (UINT_PTR)ptr;
639 VirtualProtect(&pIAT->u1.Function, sizeof(void *),
640 old, &new);
641 return original;
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100642 default:
643 return NULL;
644 }
645 }
646 }
647 }
648 return NULL;
649}
650
651/*
652 * Get the module handle which 'funcname' in 'hInst' is imported from.
653 */
654 HINSTANCE
655find_imported_module_by_funcname(HINSTANCE hInst, const char *funcname)
656{
657 char *modulename;
658
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000659 modulename = (char *)get_imported_func_info(hInst, funcname, 1, NULL);
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100660 if (modulename != NULL)
661 return GetModuleHandleA(modulename);
662 return NULL;
663}
664
665/*
666 * Get the address of 'funcname' which is imported by 'hInst' DLL.
667 */
668 void *
669get_dll_import_func(HINSTANCE hInst, const char *funcname)
670{
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000671 return get_imported_func_info(hInst, funcname, 0, NULL);
672}
673
674/*
675 * Hook the function named 'funcname' which is imported by 'hInst' DLL,
676 * and return the original function address.
677 */
678 void *
679hook_dll_import_func(HINSTANCE hInst, const char *funcname, const void *hook)
680{
681 return get_imported_func_info(hInst, funcname, 2, hook);
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100682}
683#endif
684
Bram Moolenaar071d4272004-06-13 20:20:40 +0000685#if defined(DYNAMIC_GETTEXT) || defined(PROTO)
686# ifndef GETTEXT_DLL
687# define GETTEXT_DLL "libintl.dll"
Bram Moolenaar7554c542018-10-06 15:03:15 +0200688# define GETTEXT_DLL_ALT1 "libintl-8.dll"
689# define GETTEXT_DLL_ALT2 "intl.dll"
Bram Moolenaar071d4272004-06-13 20:20:40 +0000690# endif
Bram Moolenaar0f873732019-12-05 20:28:46 +0100691// Dummy functions
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000692static char *null_libintl_gettext(const char *);
Bram Moolenaaree695f72016-08-03 22:08:45 +0200693static char *null_libintl_ngettext(const char *, const char *, unsigned long n);
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000694static char *null_libintl_textdomain(const char *);
695static char *null_libintl_bindtextdomain(const char *, const char *);
696static char *null_libintl_bind_textdomain_codeset(const char *, const char *);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100697static int null_libintl_wputenv(const wchar_t *);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000698
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200699static HINSTANCE hLibintlDLL = NULL;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000700char *(*dyn_libintl_gettext)(const char *) = null_libintl_gettext;
Bram Moolenaaree695f72016-08-03 22:08:45 +0200701char *(*dyn_libintl_ngettext)(const char *, const char *, unsigned long n)
702 = null_libintl_ngettext;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000703char *(*dyn_libintl_textdomain)(const char *) = null_libintl_textdomain;
704char *(*dyn_libintl_bindtextdomain)(const char *, const char *)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000705 = null_libintl_bindtextdomain;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000706char *(*dyn_libintl_bind_textdomain_codeset)(const char *, const char *)
707 = null_libintl_bind_textdomain_codeset;
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100708int (*dyn_libintl_wputenv)(const wchar_t *) = null_libintl_wputenv;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000709
710 int
Bram Moolenaar05540972016-01-30 20:31:25 +0100711dyn_libintl_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000712{
713 int i;
714 static struct
715 {
716 char *name;
717 FARPROC *ptr;
718 } libintl_entry[] =
719 {
720 {"gettext", (FARPROC*)&dyn_libintl_gettext},
Bram Moolenaaree695f72016-08-03 22:08:45 +0200721 {"ngettext", (FARPROC*)&dyn_libintl_ngettext},
Bram Moolenaar071d4272004-06-13 20:20:40 +0000722 {"textdomain", (FARPROC*)&dyn_libintl_textdomain},
723 {"bindtextdomain", (FARPROC*)&dyn_libintl_bindtextdomain},
724 {NULL, NULL}
725 };
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100726 HINSTANCE hmsvcrt;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000727
Bram Moolenaar7554c542018-10-06 15:03:15 +0200728 // No need to initialize twice.
729 if (hLibintlDLL != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000730 return 1;
Bram Moolenaar7554c542018-10-06 15:03:15 +0200731 // Load gettext library (libintl.dll and other names).
Bram Moolenaar923e43b2016-01-28 15:07:38 +0100732 hLibintlDLL = vimLoadLib(GETTEXT_DLL);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100733# ifdef GETTEXT_DLL_ALT1
Bram Moolenaar286eacd2016-01-16 18:05:50 +0100734 if (!hLibintlDLL)
Bram Moolenaar7554c542018-10-06 15:03:15 +0200735 hLibintlDLL = vimLoadLib(GETTEXT_DLL_ALT1);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100736# endif
737# ifdef GETTEXT_DLL_ALT2
Bram Moolenaar7554c542018-10-06 15:03:15 +0200738 if (!hLibintlDLL)
739 hLibintlDLL = vimLoadLib(GETTEXT_DLL_ALT2);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100740# endif
Bram Moolenaar938ee832016-01-24 15:36:03 +0100741 if (!hLibintlDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000742 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200743 if (p_verbose > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000744 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200745 verbose_enter();
Bram Moolenaar460ae5d2022-01-01 14:19:49 +0000746 semsg(_(e_could_not_load_library_str_str), GETTEXT_DLL, GetWin32Error());
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200747 verbose_leave();
Bram Moolenaar071d4272004-06-13 20:20:40 +0000748 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200749 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000750 }
751 for (i = 0; libintl_entry[i].name != NULL
752 && libintl_entry[i].ptr != NULL; ++i)
753 {
K.Takata54119102022-02-03 13:33:03 +0000754 if ((*libintl_entry[i].ptr = GetProcAddress(hLibintlDLL,
Bram Moolenaar071d4272004-06-13 20:20:40 +0000755 libintl_entry[i].name)) == NULL)
756 {
757 dyn_libintl_end();
758 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +0000759 {
760 verbose_enter();
Bram Moolenaar460ae5d2022-01-01 14:19:49 +0000761 semsg(_(e_could_not_load_library_function_str), libintl_entry[i].name);
Bram Moolenaara04f10b2005-05-31 22:09:46 +0000762 verbose_leave();
763 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000764 return 0;
765 }
766 }
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000767
Bram Moolenaar0f873732019-12-05 20:28:46 +0100768 // The bind_textdomain_codeset() function is optional.
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +0100769 dyn_libintl_bind_textdomain_codeset = (char *(*)(const char *, const char *))
770 GetProcAddress(hLibintlDLL, "bind_textdomain_codeset");
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000771 if (dyn_libintl_bind_textdomain_codeset == NULL)
772 dyn_libintl_bind_textdomain_codeset =
773 null_libintl_bind_textdomain_codeset;
774
Bram Moolenaar0f873732019-12-05 20:28:46 +0100775 // _wputenv() function for the libintl.dll is optional.
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100776 hmsvcrt = find_imported_module_by_funcname(hLibintlDLL, "getenv");
777 if (hmsvcrt != NULL)
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +0100778 dyn_libintl_wputenv = (int (*)(const wchar_t *))
779 GetProcAddress(hmsvcrt, "_wputenv");
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100780 if (dyn_libintl_wputenv == NULL || dyn_libintl_wputenv == _wputenv)
781 dyn_libintl_wputenv = null_libintl_wputenv;
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100782
Bram Moolenaar071d4272004-06-13 20:20:40 +0000783 return 1;
784}
785
786 void
Bram Moolenaar05540972016-01-30 20:31:25 +0100787dyn_libintl_end(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000788{
789 if (hLibintlDLL)
790 FreeLibrary(hLibintlDLL);
791 hLibintlDLL = NULL;
792 dyn_libintl_gettext = null_libintl_gettext;
Bram Moolenaaree695f72016-08-03 22:08:45 +0200793 dyn_libintl_ngettext = null_libintl_ngettext;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000794 dyn_libintl_textdomain = null_libintl_textdomain;
795 dyn_libintl_bindtextdomain = null_libintl_bindtextdomain;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000796 dyn_libintl_bind_textdomain_codeset = null_libintl_bind_textdomain_codeset;
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100797 dyn_libintl_wputenv = null_libintl_wputenv;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000798}
799
800 static char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000801null_libintl_gettext(const char *msgid)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000802{
803 return (char*)msgid;
804}
805
806 static char *
Bram Moolenaaree695f72016-08-03 22:08:45 +0200807null_libintl_ngettext(
808 const char *msgid,
809 const char *msgid_plural,
810 unsigned long n)
811{
Bram Moolenaarc90f2ae2016-08-04 22:00:15 +0200812 return (char *)(n == 1 ? msgid : msgid_plural);
Bram Moolenaaree695f72016-08-03 22:08:45 +0200813}
814
Bram Moolenaaree695f72016-08-03 22:08:45 +0200815 static char *
Bram Moolenaar1266d672017-02-01 13:43:36 +0100816null_libintl_bindtextdomain(
817 const char *domainname UNUSED,
818 const char *dirname UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000819{
820 return NULL;
821}
822
823 static char *
Bram Moolenaar1266d672017-02-01 13:43:36 +0100824null_libintl_bind_textdomain_codeset(
825 const char *domainname UNUSED,
826 const char *codeset UNUSED)
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000827{
828 return NULL;
829}
830
831 static char *
Bram Moolenaar1266d672017-02-01 13:43:36 +0100832null_libintl_textdomain(const char *domainname UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000833{
834 return NULL;
835}
836
Bram Moolenaare0ab9792017-08-02 23:18:25 +0200837 static int
Bram Moolenaar1266d672017-02-01 13:43:36 +0100838null_libintl_wputenv(const wchar_t *envstring UNUSED)
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100839{
840 return 0;
841}
842
Bram Moolenaar0f873732019-12-05 20:28:46 +0100843#endif // DYNAMIC_GETTEXT
Bram Moolenaar071d4272004-06-13 20:20:40 +0000844
Bram Moolenaar0f873732019-12-05 20:28:46 +0100845// This symbol is not defined in older versions of the SDK or Visual C++
Bram Moolenaar071d4272004-06-13 20:20:40 +0000846
847#ifndef VER_PLATFORM_WIN32_WINDOWS
848# define VER_PLATFORM_WIN32_WINDOWS 1
849#endif
850
Bram Moolenaar071d4272004-06-13 20:20:40 +0000851#ifdef HAVE_ACL
Bram Moolenaar82881492012-11-20 16:53:39 +0100852# ifndef PROTO
853# include <aclapi.h>
854# endif
Bram Moolenaar27515922013-06-29 15:36:26 +0200855# ifndef PROTECTED_DACL_SECURITY_INFORMATION
856# define PROTECTED_DACL_SECURITY_INFORMATION 0x80000000L
857# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000858#endif
859
Bram Moolenaar27515922013-06-29 15:36:26 +0200860#ifdef HAVE_ACL
861/*
862 * Enables or disables the specified privilege.
863 */
864 static BOOL
865win32_enable_privilege(LPTSTR lpszPrivilege, BOOL bEnable)
866{
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100867 BOOL bResult;
868 LUID luid;
869 HANDLE hToken;
870 TOKEN_PRIVILEGES tokenPrivileges;
Bram Moolenaar27515922013-06-29 15:36:26 +0200871
872 if (!OpenProcessToken(GetCurrentProcess(),
873 TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
874 return FALSE;
875
876 if (!LookupPrivilegeValue(NULL, lpszPrivilege, &luid))
877 {
878 CloseHandle(hToken);
879 return FALSE;
880 }
881
Bram Moolenaar45500912014-07-09 20:51:07 +0200882 tokenPrivileges.PrivilegeCount = 1;
Bram Moolenaar27515922013-06-29 15:36:26 +0200883 tokenPrivileges.Privileges[0].Luid = luid;
884 tokenPrivileges.Privileges[0].Attributes = bEnable ?
885 SE_PRIVILEGE_ENABLED : 0;
886
887 bResult = AdjustTokenPrivileges(hToken, FALSE, &tokenPrivileges,
888 sizeof(TOKEN_PRIVILEGES), NULL, NULL);
889
890 CloseHandle(hToken);
891
892 return bResult && GetLastError() == ERROR_SUCCESS;
893}
894#endif
895
Bram Moolenaar29d2f452020-12-04 19:42:52 +0100896#ifdef _MSC_VER
897// Suppress the deprecation warning for using GetVersionEx().
898// It is needed for implementing "windowsversion()".
899# pragma warning(push)
900# pragma warning(disable: 4996)
901#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000902/*
Bram Moolenaar1e1d2e82020-05-18 20:17:02 +0200903 * Set "win8_or_later" and fill in "windowsVersion" if possible.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000904 */
905 void
906PlatformId(void)
907{
908 static int done = FALSE;
909
910 if (!done)
911 {
912 OSVERSIONINFO ovi;
913
914 ovi.dwOSVersionInfoSize = sizeof(ovi);
915 GetVersionEx(&ovi);
916
Bram Moolenaar1e1d2e82020-05-18 20:17:02 +0200917#ifdef FEAT_EVAL
Bram Moolenaar0c1e3742019-12-27 13:49:24 +0100918 vim_snprintf(windowsVersion, sizeof(windowsVersion), "%d.%d",
919 (int)ovi.dwMajorVersion, (int)ovi.dwMinorVersion);
Bram Moolenaar1e1d2e82020-05-18 20:17:02 +0200920#endif
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100921 if ((ovi.dwMajorVersion == 6 && ovi.dwMinorVersion >= 2)
922 || ovi.dwMajorVersion > 6)
923 win8_or_later = TRUE;
924
Christopher Plewrightc8b126d2022-12-22 13:45:23 +0000925 if ((ovi.dwMajorVersion == 10 && ovi.dwBuildNumber >= 19045)
Christopher Plewright1140b512022-11-12 18:46:05 +0000926 || ovi.dwMajorVersion > 10)
Christopher Plewrightc8b126d2022-12-22 13:45:23 +0000927 win10_22H2_or_later = TRUE;
Christopher Plewright1140b512022-11-12 18:46:05 +0000928
Bram Moolenaar071d4272004-06-13 20:20:40 +0000929#ifdef HAVE_ACL
Bram Moolenaar0f873732019-12-05 20:28:46 +0100930 // Enable privilege for getting or setting SACLs.
Bram Moolenaarcea912a2016-10-12 14:20:24 +0200931 win32_enable_privilege(SE_SECURITY_NAME, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000932#endif
933 done = TRUE;
934 }
935}
Bram Moolenaar29d2f452020-12-04 19:42:52 +0100936#ifdef _MSC_VER
937# pragma warning(pop)
938#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000939
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200940#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000941
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100942# define SHIFT (SHIFT_PRESSED)
943# define CTRL (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED)
944# define ALT (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED)
945# define ALT_GR (RIGHT_ALT_PRESSED | LEFT_CTRL_PRESSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000946
947
Bram Moolenaar0f873732019-12-05 20:28:46 +0100948// When uChar.AsciiChar is 0, then we need to look at wVirtualKeyCode.
949// We map function keys to their ANSI terminal equivalents, as produced
950// by ANSI.SYS, for compatibility with the MS-DOS version of Vim. Any
951// ANSI key with a value >= '\300' is nonstandard, but provided anyway
952// so that the user can have access to all SHIFT-, CTRL-, and ALT-
953// combinations of function/arrow/etc keys.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000954
Bram Moolenaard6f676d2005-06-01 21:51:55 +0000955static const struct
Bram Moolenaar071d4272004-06-13 20:20:40 +0000956{
957 WORD wVirtKey;
958 BOOL fAnsiKey;
959 int chAlone;
960 int chShift;
961 int chCtrl;
962 int chAlt;
963} VirtKeyMap[] =
964{
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200965// Key ANSI alone shift ctrl alt
Bram Moolenaar071d4272004-06-13 20:20:40 +0000966 { VK_ESCAPE,FALSE, ESC, ESC, ESC, ESC, },
967
968 { VK_F1, TRUE, ';', 'T', '^', 'h', },
969 { VK_F2, TRUE, '<', 'U', '_', 'i', },
970 { VK_F3, TRUE, '=', 'V', '`', 'j', },
971 { VK_F4, TRUE, '>', 'W', 'a', 'k', },
972 { VK_F5, TRUE, '?', 'X', 'b', 'l', },
973 { VK_F6, TRUE, '@', 'Y', 'c', 'm', },
974 { VK_F7, TRUE, 'A', 'Z', 'd', 'n', },
975 { VK_F8, TRUE, 'B', '[', 'e', 'o', },
976 { VK_F9, TRUE, 'C', '\\', 'f', 'p', },
977 { VK_F10, TRUE, 'D', ']', 'g', 'q', },
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200978 { VK_F11, TRUE, '\205', '\207', '\211', '\213', },
979 { VK_F12, TRUE, '\206', '\210', '\212', '\214', },
Bram Moolenaar071d4272004-06-13 20:20:40 +0000980
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200981 { VK_HOME, TRUE, 'G', '\302', 'w', '\303', },
982 { VK_UP, TRUE, 'H', '\304', '\305', '\306', },
983 { VK_PRIOR, TRUE, 'I', '\307', '\204', '\310', }, // PgUp
984 { VK_LEFT, TRUE, 'K', '\311', 's', '\312', },
985 { VK_RIGHT, TRUE, 'M', '\313', 't', '\314', },
986 { VK_END, TRUE, 'O', '\315', 'u', '\316', },
987 { VK_DOWN, TRUE, 'P', '\317', '\320', '\321', },
988 { VK_NEXT, TRUE, 'Q', '\322', 'v', '\323', }, // PgDn
989 { VK_INSERT,TRUE, 'R', '\324', '\325', '\326', },
990 { VK_DELETE,TRUE, 'S', '\327', '\330', '\331', },
Bram Moolenaarb70a47b2019-03-30 22:11:21 +0100991 { VK_BACK, TRUE, 'x', 'y', 'z', '{', }, // Backspace
Bram Moolenaar071d4272004-06-13 20:20:40 +0000992
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200993 { VK_SNAPSHOT,TRUE, 0, 0, 0, 'r', }, // PrtScrn
Bram Moolenaar071d4272004-06-13 20:20:40 +0000994
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100995# if 0
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200996 // Most people don't have F13-F20, but what the hell...
997 { VK_F13, TRUE, '\332', '\333', '\334', '\335', },
998 { VK_F14, TRUE, '\336', '\337', '\340', '\341', },
999 { VK_F15, TRUE, '\342', '\343', '\344', '\345', },
1000 { VK_F16, TRUE, '\346', '\347', '\350', '\351', },
1001 { VK_F17, TRUE, '\352', '\353', '\354', '\355', },
1002 { VK_F18, TRUE, '\356', '\357', '\360', '\361', },
1003 { VK_F19, TRUE, '\362', '\363', '\364', '\365', },
1004 { VK_F20, TRUE, '\366', '\367', '\370', '\371', },
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001005# endif
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +02001006 { VK_ADD, TRUE, 'N', 'N', 'N', 'N', }, // keyp '+'
1007 { VK_SUBTRACT, TRUE,'J', 'J', 'J', 'J', }, // keyp '-'
1008 // { VK_DIVIDE, TRUE,'N', 'N', 'N', 'N', }, // keyp '/'
1009 { VK_MULTIPLY, TRUE,'7', '7', '7', '7', }, // keyp '*'
Bram Moolenaar071d4272004-06-13 20:20:40 +00001010
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +02001011 { VK_NUMPAD0,TRUE, '\332', '\333', '\334', '\335', },
1012 { VK_NUMPAD1,TRUE, '\336', '\337', '\340', '\341', },
1013 { VK_NUMPAD2,TRUE, '\342', '\343', '\344', '\345', },
1014 { VK_NUMPAD3,TRUE, '\346', '\347', '\350', '\351', },
1015 { VK_NUMPAD4,TRUE, '\352', '\353', '\354', '\355', },
1016 { VK_NUMPAD5,TRUE, '\356', '\357', '\360', '\361', },
1017 { VK_NUMPAD6,TRUE, '\362', '\363', '\364', '\365', },
1018 { VK_NUMPAD7,TRUE, '\366', '\367', '\370', '\371', },
1019 { VK_NUMPAD8,TRUE, '\372', '\373', '\374', '\375', },
1020 // Sorry, out of number space! <negri>
Bram Moolenaarb70a47b2019-03-30 22:11:21 +01001021 { VK_NUMPAD9,TRUE, '\376', '\377', '|', '}', },
Bram Moolenaar071d4272004-06-13 20:20:40 +00001022};
1023
1024
Bram Moolenaar0f873732019-12-05 20:28:46 +01001025/*
1026 * The return code indicates key code size.
1027 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001028 static int
Bram Moolenaar071d4272004-06-13 20:20:40 +00001029win32_kbd_patch_key(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001030 KEY_EVENT_RECORD *pker)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001031{
1032 UINT uMods = pker->dwControlKeyState;
1033 static int s_iIsDead = 0;
1034 static WORD awAnsiCode[2];
1035 static BYTE abKeystate[256];
1036
1037
1038 if (s_iIsDead == 2)
1039 {
K.Takata972db232022-02-04 10:45:38 +00001040 pker->uChar.UnicodeChar = (WCHAR) awAnsiCode[1];
Bram Moolenaar071d4272004-06-13 20:20:40 +00001041 s_iIsDead = 0;
1042 return 1;
1043 }
1044
Christopher Plewright20b795e2022-12-20 20:01:58 +00001045 if (pker->uChar.UnicodeChar > 0 && pker->uChar.UnicodeChar < 0xfffd)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001046 return 1;
1047
Bram Moolenaara80faa82020-04-12 19:37:17 +02001048 CLEAR_FIELD(abKeystate);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001049
Bram Moolenaar0f873732019-12-05 20:28:46 +01001050 // Clear any pending dead keys
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001051 ToUnicode(VK_SPACE, MapVirtualKey(VK_SPACE, 0), abKeystate, awAnsiCode, 2, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001052
1053 if (uMods & SHIFT_PRESSED)
1054 abKeystate[VK_SHIFT] = 0x80;
1055 if (uMods & CAPSLOCK_ON)
1056 abKeystate[VK_CAPITAL] = 1;
1057
1058 if ((uMods & ALT_GR) == ALT_GR)
1059 {
1060 abKeystate[VK_CONTROL] = abKeystate[VK_LCONTROL] =
1061 abKeystate[VK_MENU] = abKeystate[VK_RMENU] = 0x80;
1062 }
1063
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001064 s_iIsDead = ToUnicode(pker->wVirtualKeyCode, pker->wVirtualScanCode,
1065 abKeystate, awAnsiCode, 2, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001066
1067 if (s_iIsDead > 0)
K.Takata972db232022-02-04 10:45:38 +00001068 pker->uChar.UnicodeChar = (WCHAR) awAnsiCode[0];
Bram Moolenaar071d4272004-06-13 20:20:40 +00001069
1070 return s_iIsDead;
1071}
1072
Bram Moolenaar071d4272004-06-13 20:20:40 +00001073static BOOL g_fJustGotFocus = FALSE;
1074
1075/*
1076 * Decode a KEY_EVENT into one or two keystrokes
1077 */
1078 static BOOL
1079decode_key_event(
1080 KEY_EVENT_RECORD *pker,
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001081 WCHAR *pch,
1082 WCHAR *pch2,
Bram Moolenaar071d4272004-06-13 20:20:40 +00001083 int *pmodifiers,
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02001084 BOOL fDoPost UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001085{
1086 int i;
1087 const int nModifs = pker->dwControlKeyState & (SHIFT | ALT | CTRL);
1088
1089 *pch = *pch2 = NUL;
1090 g_fJustGotFocus = FALSE;
1091
Bram Moolenaar0f873732019-12-05 20:28:46 +01001092 // ignore key up events
Bram Moolenaar071d4272004-06-13 20:20:40 +00001093 if (!pker->bKeyDown)
1094 return FALSE;
1095
Bram Moolenaar0f873732019-12-05 20:28:46 +01001096 // ignore some keystrokes
Bram Moolenaar071d4272004-06-13 20:20:40 +00001097 switch (pker->wVirtualKeyCode)
1098 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001099 // modifiers
Bram Moolenaar071d4272004-06-13 20:20:40 +00001100 case VK_SHIFT:
1101 case VK_CONTROL:
Bram Moolenaar0f873732019-12-05 20:28:46 +01001102 case VK_MENU: // Alt key
Bram Moolenaar071d4272004-06-13 20:20:40 +00001103 return FALSE;
1104
1105 default:
1106 break;
1107 }
1108
Bram Moolenaar0f873732019-12-05 20:28:46 +01001109 // special cases
K.Takata972db232022-02-04 10:45:38 +00001110 if ((nModifs & CTRL) != 0 && (nModifs & ~CTRL) == 0
Christopher Plewright20b795e2022-12-20 20:01:58 +00001111 && (pker->uChar.UnicodeChar == NUL
1112 || pker->uChar.UnicodeChar == 0xfffd))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001113 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001114 // Ctrl-6 is Ctrl-^
Bram Moolenaar071d4272004-06-13 20:20:40 +00001115 if (pker->wVirtualKeyCode == '6')
1116 {
1117 *pch = Ctrl_HAT;
1118 return TRUE;
1119 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01001120 // Ctrl-2 is Ctrl-@
Bram Moolenaar071d4272004-06-13 20:20:40 +00001121 else if (pker->wVirtualKeyCode == '2')
1122 {
1123 *pch = NUL;
1124 return TRUE;
1125 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01001126 // Ctrl-- is Ctrl-_
Bram Moolenaar071d4272004-06-13 20:20:40 +00001127 else if (pker->wVirtualKeyCode == 0xBD)
1128 {
1129 *pch = Ctrl__;
1130 return TRUE;
1131 }
1132 }
1133
Bram Moolenaar0f873732019-12-05 20:28:46 +01001134 // Shift-TAB
Bram Moolenaar071d4272004-06-13 20:20:40 +00001135 if (pker->wVirtualKeyCode == VK_TAB && (nModifs & SHIFT_PRESSED))
1136 {
1137 *pch = K_NUL;
1138 *pch2 = '\017';
1139 return TRUE;
1140 }
1141
K.Takataeeec2542021-06-02 13:28:16 +02001142 for (i = ARRAY_LENGTH(VirtKeyMap); --i >= 0; )
Bram Moolenaar071d4272004-06-13 20:20:40 +00001143 {
1144 if (VirtKeyMap[i].wVirtKey == pker->wVirtualKeyCode)
1145 {
1146 if (nModifs == 0)
1147 *pch = VirtKeyMap[i].chAlone;
1148 else if ((nModifs & SHIFT) != 0 && (nModifs & ~SHIFT) == 0)
1149 *pch = VirtKeyMap[i].chShift;
1150 else if ((nModifs & CTRL) != 0 && (nModifs & ~CTRL) == 0)
1151 *pch = VirtKeyMap[i].chCtrl;
1152 else if ((nModifs & ALT) != 0 && (nModifs & ~ALT) == 0)
1153 *pch = VirtKeyMap[i].chAlt;
1154
1155 if (*pch != 0)
1156 {
1157 if (VirtKeyMap[i].fAnsiKey)
1158 {
1159 *pch2 = *pch;
1160 *pch = K_NUL;
1161 }
1162
1163 return TRUE;
1164 }
1165 }
1166 }
1167
1168 i = win32_kbd_patch_key(pker);
1169
1170 if (i < 0)
1171 *pch = NUL;
1172 else
1173 {
K.Takata972db232022-02-04 10:45:38 +00001174 *pch = (i > 0) ? pker->uChar.UnicodeChar : NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001175
1176 if (pmodifiers != NULL)
1177 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001178 // Pass on the ALT key as a modifier, but only when not combined
1179 // with CTRL (which is ALTGR).
Bram Moolenaar071d4272004-06-13 20:20:40 +00001180 if ((nModifs & ALT) != 0 && (nModifs & CTRL) == 0)
1181 *pmodifiers |= MOD_MASK_ALT;
1182
Bram Moolenaar0f873732019-12-05 20:28:46 +01001183 // Pass on SHIFT only for special keys, because we don't know when
1184 // it's already included with the character.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001185 if ((nModifs & SHIFT) != 0 && *pch <= 0x20)
1186 *pmodifiers |= MOD_MASK_SHIFT;
1187
Bram Moolenaar0f873732019-12-05 20:28:46 +01001188 // Pass on CTRL only for non-special keys, because we don't know
1189 // when it's already included with the character. And not when
1190 // combined with ALT (which is ALTGR).
Bram Moolenaar071d4272004-06-13 20:20:40 +00001191 if ((nModifs & CTRL) != 0 && (nModifs & ALT) == 0
1192 && *pch >= 0x20 && *pch < 0x80)
1193 *pmodifiers |= MOD_MASK_CTRL;
1194 }
1195 }
1196
1197 return (*pch != NUL);
1198}
1199
Christopher Plewright20b795e2022-12-20 20:01:58 +00001200# if defined(FEAT_EVAL)
1201 static int
1202encode_key_event(dict_T *args, INPUT_RECORD *ir)
1203{
1204 static int s_dwMods = 0;
1205
1206 char_u *event = dict_get_string(args, "event", TRUE);
1207 if (event && (STRICMP(event, "keydown") == 0
1208 || STRICMP(event, "keyup") == 0))
1209 {
1210 WORD vkCode = dict_get_number_def(args, "keycode", 0);
1211 if (vkCode <= 0 || vkCode >= 0xFF)
1212 {
1213 semsg(_(e_invalid_argument_nr), (long)vkCode);
1214 return FALSE;
1215 }
1216
1217 ir->EventType = KEY_EVENT;
1218 KEY_EVENT_RECORD ker;
1219 ZeroMemory(&ker, sizeof(ker));
1220 ker.bKeyDown = STRICMP(event, "keydown") == 0;
1221 ker.wRepeatCount = 1;
1222 ker.wVirtualScanCode = 0;
1223 ker.dwControlKeyState = 0;
1224 int mods = (int)dict_get_number(args, "modifiers");
1225 // Encode the win32 console key modifiers from Vim keyboard modifiers.
1226 if (mods)
1227 {
1228 // If "modifiers" is explicitly set in the args, then we reset any
1229 // remembered modifer key state that may have been set from earlier
1230 // mod-key-down events, even if they are not yet unset by earlier
1231 // mod-key-up events.
1232 s_dwMods = 0;
1233 if (mods & MOD_MASK_SHIFT)
1234 ker.dwControlKeyState |= SHIFT_PRESSED;
1235 if (mods & MOD_MASK_CTRL)
1236 ker.dwControlKeyState |= LEFT_CTRL_PRESSED;
1237 if (mods & MOD_MASK_ALT)
1238 ker.dwControlKeyState |= LEFT_ALT_PRESSED;
1239 }
1240
1241 if (vkCode == VK_LSHIFT || vkCode == VK_RSHIFT || vkCode == VK_SHIFT)
1242 {
1243 if (STRICMP(event, "keydown") == 0)
1244 s_dwMods |= SHIFT_PRESSED;
1245 else
1246 s_dwMods &= ~SHIFT_PRESSED;
1247 }
1248 else if (vkCode == VK_LCONTROL || vkCode == VK_CONTROL)
1249 {
1250 if (STRICMP(event, "keydown") == 0)
1251 s_dwMods |= LEFT_CTRL_PRESSED;
1252 else
1253 s_dwMods &= ~LEFT_CTRL_PRESSED;
1254 }
1255 else if (vkCode == VK_RCONTROL)
1256 {
1257 if (STRICMP(event, "keydown") == 0)
1258 s_dwMods |= RIGHT_CTRL_PRESSED;
1259 else
1260 s_dwMods &= ~RIGHT_CTRL_PRESSED;
1261 }
1262 else if (vkCode == VK_LMENU || vkCode == VK_MENU)
1263 {
1264 if (STRICMP(event, "keydown") == 0)
1265 s_dwMods |= LEFT_ALT_PRESSED;
1266 else
1267 s_dwMods &= ~LEFT_ALT_PRESSED;
1268 }
1269 else if (vkCode == VK_RMENU)
1270 {
1271 if (STRICMP(event, "keydown") == 0)
1272 s_dwMods |= RIGHT_ALT_PRESSED;
1273 else
1274 s_dwMods &= ~RIGHT_ALT_PRESSED;
1275 }
1276 ker.dwControlKeyState |= s_dwMods;
1277 ker.wVirtualKeyCode = vkCode;
1278 win32_kbd_patch_key(&ker);
1279
1280 for (int i = ARRAY_LENGTH(VirtKeyMap);
1281 --i >= 0 && !ker.uChar.UnicodeChar; )
1282 {
1283 if (VirtKeyMap[i].wVirtKey == vkCode)
1284 ker.uChar.UnicodeChar = 0xfffd; // REPLACEMENT CHARACTER
1285 }
1286
1287 ir->Event.KeyEvent = ker;
1288 vim_free(event);
1289 }
1290 else
1291 {
1292 if (event == NULL)
1293 {
1294 semsg(_(e_missing_argument_str), "event");
1295 }
1296 else
1297 {
1298 semsg(_(e_invalid_value_for_argument_str_str), "event", event);
1299 vim_free(event);
1300 }
1301 return FALSE;
1302 }
1303 return TRUE;
1304}
1305# endif // FEAT_EVAL
1306#endif // !FEAT_GUI_MSWIN || VIMDLL
Bram Moolenaar071d4272004-06-13 20:20:40 +00001307
1308
Bram Moolenaar071d4272004-06-13 20:20:40 +00001309/*
1310 * For the GUI the mouse handling is in gui_w32.c.
1311 */
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001312#if defined(FEAT_GUI_MSWIN) && !defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001313 void
Bram Moolenaar1266d672017-02-01 13:43:36 +01001314mch_setmouse(int on UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001315{
1316}
Christopher Plewright20b795e2022-12-20 20:01:58 +00001317#else // !FEAT_GUI_MSWIN || VIMDLL
Bram Moolenaar0f873732019-12-05 20:28:46 +01001318static int g_fMouseAvail = FALSE; // mouse present
1319static int g_fMouseActive = FALSE; // mouse enabled
1320static int g_nMouseClick = -1; // mouse status
1321static int g_xMouse; // mouse x coordinate
1322static int g_yMouse; // mouse y coordinate
Bram Moolenaar9f1983d2022-05-12 20:35:35 +01001323static DWORD g_cmodein = 0; // Original console input mode
1324static DWORD g_cmodeout = 0; // Original console output mode
Bram Moolenaar071d4272004-06-13 20:20:40 +00001325
1326/*
1327 * Enable or disable mouse input
1328 */
1329 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001330mch_setmouse(int on)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001331{
1332 DWORD cmodein;
1333
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001334# ifdef VIMDLL
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001335 if (gui.in_use)
1336 return;
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001337# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001338 if (!g_fMouseAvail)
1339 return;
1340
1341 g_fMouseActive = on;
1342 GetConsoleMode(g_hConIn, &cmodein);
1343
1344 if (g_fMouseActive)
Wez Furlong6ef5ab52021-05-30 19:29:41 +02001345 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00001346 cmodein |= ENABLE_MOUSE_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02001347 cmodein &= ~ENABLE_QUICK_EDIT_MODE;
1348 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001349 else
Wez Furlong6ef5ab52021-05-30 19:29:41 +02001350 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00001351 cmodein &= ~ENABLE_MOUSE_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02001352 cmodein |= g_cmodein & ENABLE_QUICK_EDIT_MODE;
1353 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001354
Wez Furlong6ef5ab52021-05-30 19:29:41 +02001355 SetConsoleMode(g_hConIn, cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001356}
1357
Bram Moolenaar157d8132018-03-06 17:09:20 +01001358
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001359# if defined(FEAT_BEVAL_TERM) || defined(PROTO)
Bram Moolenaar157d8132018-03-06 17:09:20 +01001360/*
1361 * Called when 'balloonevalterm' changed.
1362 */
1363 void
1364mch_bevalterm_changed(void)
1365{
1366 mch_setmouse(g_fMouseActive);
1367}
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001368# endif
Bram Moolenaar157d8132018-03-06 17:09:20 +01001369
Christopher Plewright2a46f812022-10-16 19:47:45 +01001370/*
1371 * Win32 console mouse scroll event handler.
Christopher Plewright20b795e2022-12-20 20:01:58 +00001372 * Console version of the _OnMouseWheel() function in gui_w32.c
Christopher Plewright2a46f812022-10-16 19:47:45 +01001373 *
1374 * This encodes the mouse scroll direction and keyboard modifiers into
1375 * g_nMouseClick, and the mouse position into g_xMouse and g_yMouse
1376 *
1377 * The direction of the scroll is decoded from two fields of the win32 console
1378 * mouse event record;
Christopher Plewright20b795e2022-12-20 20:01:58 +00001379 * 1. The orientation - vertical or horizontal flag - from dwEventFlags
Christopher Plewright2a46f812022-10-16 19:47:45 +01001380 * 2. The sign - positive or negative (aka delta flag) - from dwButtonState
1381 *
Christopher Plewright20b795e2022-12-20 20:01:58 +00001382 * When scroll orientation is HORIZONTAL
Christopher Plewright2a46f812022-10-16 19:47:45 +01001383 * - If the high word of the dwButtonState member contains a positive
1384 * value, the wheel was rotated to the right.
1385 * - Otherwise, the wheel was rotated to the left.
Christopher Plewright20b795e2022-12-20 20:01:58 +00001386 * When scroll orientation is VERTICAL
Christopher Plewright2a46f812022-10-16 19:47:45 +01001387 * - If the high word of the dwButtonState member contains a positive value,
1388 * the wheel was rotated forward, away from the user.
1389 * - Otherwise, the wheel was rotated backward, toward the user.
1390 */
1391 static void
1392decode_mouse_wheel(MOUSE_EVENT_RECORD *pmer)
1393{
Christopher Plewright2a46f812022-10-16 19:47:45 +01001394 int horizontal = (pmer->dwEventFlags == MOUSE_HWHEELED);
1395 int zDelta = pmer->dwButtonState;
1396
1397 g_xMouse = pmer->dwMousePosition.X;
1398 g_yMouse = pmer->dwMousePosition.Y;
1399
K.Takata161b6ac2022-11-14 15:31:07 +00001400# ifdef FEAT_PROP_POPUP
Christopher Plewright605d02a2022-10-19 11:54:46 +01001401 int lcol = g_xMouse;
1402 int lrow = g_yMouse;
Christopher Plewright38804d62022-11-09 23:55:52 +00001403 win_T *wp = mouse_find_win(&lrow, &lcol, FIND_POPUP);
Christopher Plewright2a46f812022-10-16 19:47:45 +01001404 if (wp != NULL && popup_is_popup(wp))
1405 {
1406 g_nMouseClick = -1;
1407 cmdarg_T cap;
1408 oparg_T oa;
1409 CLEAR_FIELD(cap);
1410 clear_oparg(&oa);
1411 cap.oap = &oa;
1412 if (horizontal)
1413 {
1414 cap.arg = zDelta < 0 ? MSCR_LEFT : MSCR_RIGHT;
1415 cap.cmdchar = zDelta < 0 ? K_MOUSELEFT : K_MOUSERIGHT;
1416 }
1417 else
1418 {
1419 cap.cmdchar = zDelta < 0 ? K_MOUSEUP : K_MOUSEDOWN;
1420 cap.arg = zDelta < 0 ? MSCR_UP : MSCR_DOWN;
1421 }
1422
1423 // Mouse hovers over popup window, scroll it if possible.
1424 mouse_row = wp->w_winrow;
1425 mouse_col = wp->w_wincol;
1426 nv_mousescroll(&cap);
1427 update_screen(0);
1428 setcursor();
1429 out_flush();
1430 return;
1431 }
K.Takata161b6ac2022-11-14 15:31:07 +00001432# endif
Christopher Plewright2a46f812022-10-16 19:47:45 +01001433 mouse_col = g_xMouse;
1434 mouse_row = g_yMouse;
1435
1436 char_u modifiers = 0;
1437 char_u direction = 0;
1438
1439 // Decode the direction into an event that Vim can process
1440 if (horizontal)
1441 direction = zDelta >= 0 ? KE_MOUSELEFT : KE_MOUSERIGHT;
1442 else
1443 direction = zDelta >= 0 ? KE_MOUSEDOWN : KE_MOUSEUP;
1444
dundargocc57b5bc2022-11-02 13:30:51 +00001445 // Decode the win32 console key modifiers into Vim mouse modifiers.
Christopher Plewright2a46f812022-10-16 19:47:45 +01001446 if (pmer->dwControlKeyState & SHIFT_PRESSED)
Christopher Plewright605d02a2022-10-19 11:54:46 +01001447 modifiers |= MOD_MASK_SHIFT; // MOUSE_SHIFT;
Christopher Plewright2a46f812022-10-16 19:47:45 +01001448 if (pmer->dwControlKeyState & (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED))
Christopher Plewright605d02a2022-10-19 11:54:46 +01001449 modifiers |= MOD_MASK_CTRL; // MOUSE_CTRL;
Christopher Plewright2a46f812022-10-16 19:47:45 +01001450 if (pmer->dwControlKeyState & (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED))
1451 modifiers |= MOD_MASK_ALT; // MOUSE_ALT;
1452
1453 // add (bitwise or) the scroll direction and the key modifier chars
1454 // together.
1455 g_nMouseClick = ((direction << 8) | modifiers);
1456
1457 return;
1458}
1459
Bram Moolenaar071d4272004-06-13 20:20:40 +00001460/*
1461 * Decode a MOUSE_EVENT. If it's a valid event, return MOUSE_LEFT,
1462 * MOUSE_MIDDLE, or MOUSE_RIGHT for a click; MOUSE_DRAG for a mouse
1463 * move with a button held down; and MOUSE_RELEASE after a MOUSE_DRAG
1464 * or a MOUSE_LEFT, _MIDDLE, or _RIGHT. We encode the button type,
1465 * the number of clicks, and the Shift/Ctrl/Alt modifiers in g_nMouseClick,
1466 * and we return the mouse position in g_xMouse and g_yMouse.
1467 *
1468 * Every MOUSE_LEFT, _MIDDLE, or _RIGHT will be followed by zero or more
1469 * MOUSE_DRAGs and one MOUSE_RELEASE. MOUSE_RELEASE will be followed only
1470 * by MOUSE_LEFT, _MIDDLE, or _RIGHT.
1471 *
1472 * For multiple clicks, we send, say, MOUSE_LEFT/1 click, MOUSE_RELEASE,
1473 * MOUSE_LEFT/2 clicks, MOUSE_RELEASE, MOUSE_LEFT/3 clicks, MOUSE_RELEASE, ....
1474 *
1475 * Windows will send us MOUSE_MOVED notifications whenever the mouse
1476 * moves, even if it stays within the same character cell. We ignore
1477 * all MOUSE_MOVED messages if the position hasn't really changed, and
1478 * we ignore all MOUSE_MOVED messages where no button is held down (i.e.,
1479 * we're only interested in MOUSE_DRAG).
1480 *
1481 * All of this is complicated by the code that fakes MOUSE_MIDDLE on
1482 * 2-button mouses by pressing the left & right buttons simultaneously.
1483 * In practice, it's almost impossible to click both at the same time,
1484 * so we need to delay a little. Also, we tend not to get MOUSE_RELEASE
1485 * in such cases, if the user is clicking quickly.
1486 */
1487 static BOOL
1488decode_mouse_event(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001489 MOUSE_EVENT_RECORD *pmer)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001490{
1491 static int s_nOldButton = -1;
1492 static int s_nOldMouseClick = -1;
1493 static int s_xOldMouse = -1;
1494 static int s_yOldMouse = -1;
1495 static linenr_T s_old_topline = 0;
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001496# ifdef FEAT_DIFF
Bram Moolenaar071d4272004-06-13 20:20:40 +00001497 static int s_old_topfill = 0;
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001498# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001499 static int s_cClicks = 1;
1500 static BOOL s_fReleased = TRUE;
1501 static DWORD s_dwLastClickTime = 0;
1502 static BOOL s_fNextIsMiddle = FALSE;
1503
Bram Moolenaar0f873732019-12-05 20:28:46 +01001504 static DWORD cButtons = 0; // number of buttons supported
Bram Moolenaar071d4272004-06-13 20:20:40 +00001505
1506 const DWORD LEFT = FROM_LEFT_1ST_BUTTON_PRESSED;
1507 const DWORD MIDDLE = FROM_LEFT_2ND_BUTTON_PRESSED;
1508 const DWORD RIGHT = RIGHTMOST_BUTTON_PRESSED;
1509 const DWORD LEFT_RIGHT = LEFT | RIGHT;
1510
1511 int nButton;
1512
1513 if (cButtons == 0 && !GetNumberOfConsoleMouseButtons(&cButtons))
1514 cButtons = 2;
1515
1516 if (!g_fMouseAvail || !g_fMouseActive)
1517 {
1518 g_nMouseClick = -1;
1519 return FALSE;
1520 }
1521
Bram Moolenaar0f873732019-12-05 20:28:46 +01001522 // get a spurious MOUSE_EVENT immediately after receiving focus; ignore
Bram Moolenaar071d4272004-06-13 20:20:40 +00001523 if (g_fJustGotFocus)
1524 {
1525 g_fJustGotFocus = FALSE;
1526 return FALSE;
1527 }
1528
Christopher Plewright605d02a2022-10-19 11:54:46 +01001529 // If there is an unprocessed mouse click drop this one.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001530 if (g_nMouseClick != -1)
1531 return TRUE;
Christopher Plewright605d02a2022-10-19 11:54:46 +01001532
Christopher Plewright2a46f812022-10-16 19:47:45 +01001533 if (pmer->dwEventFlags == MOUSE_WHEELED
1534 || pmer->dwEventFlags == MOUSE_HWHEELED)
1535 {
1536 decode_mouse_wheel(pmer);
1537 return TRUE; // we now should have a mouse scroll in g_nMouseClick
1538 }
Christopher Plewright605d02a2022-10-19 11:54:46 +01001539
Bram Moolenaar071d4272004-06-13 20:20:40 +00001540 nButton = -1;
1541 g_xMouse = pmer->dwMousePosition.X;
1542 g_yMouse = pmer->dwMousePosition.Y;
1543
1544 if (pmer->dwEventFlags == MOUSE_MOVED)
1545 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001546 // Ignore MOUSE_MOVED events if (x, y) hasn't changed. (We get these
1547 // events even when the mouse moves only within a char cell.)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001548 if (s_xOldMouse == g_xMouse && s_yOldMouse == g_yMouse)
1549 return FALSE;
1550 }
1551
Bram Moolenaar0f873732019-12-05 20:28:46 +01001552 // If no buttons are pressed...
Bram Moolenaar071d4272004-06-13 20:20:40 +00001553 if ((pmer->dwButtonState & ((1 << cButtons) - 1)) == 0)
1554 {
Bram Moolenaar157d8132018-03-06 17:09:20 +01001555 nButton = MOUSE_RELEASE;
1556
Bram Moolenaar0f873732019-12-05 20:28:46 +01001557 // If the last thing returned was MOUSE_RELEASE, ignore this
Bram Moolenaar071d4272004-06-13 20:20:40 +00001558 if (s_fReleased)
Bram Moolenaar157d8132018-03-06 17:09:20 +01001559 {
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001560# ifdef FEAT_BEVAL_TERM
Bram Moolenaar0f873732019-12-05 20:28:46 +01001561 // do return mouse move events when we want them
Bram Moolenaar157d8132018-03-06 17:09:20 +01001562 if (p_bevalterm)
1563 nButton = MOUSE_DRAG;
1564 else
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001565# endif
Bram Moolenaar157d8132018-03-06 17:09:20 +01001566 return FALSE;
1567 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001568
Bram Moolenaar071d4272004-06-13 20:20:40 +00001569 s_fReleased = TRUE;
1570 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01001571 else // one or more buttons pressed
Bram Moolenaar071d4272004-06-13 20:20:40 +00001572 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001573 // on a 2-button mouse, hold down left and right buttons
1574 // simultaneously to get MIDDLE.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001575
1576 if (cButtons == 2 && s_nOldButton != MOUSE_DRAG)
1577 {
1578 DWORD dwLR = (pmer->dwButtonState & LEFT_RIGHT);
1579
Bram Moolenaar0f873732019-12-05 20:28:46 +01001580 // if either left or right button only is pressed, see if the
1581 // next mouse event has both of them pressed
Bram Moolenaar071d4272004-06-13 20:20:40 +00001582 if (dwLR == LEFT || dwLR == RIGHT)
1583 {
1584 for (;;)
1585 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001586 // wait a short time for next input event
Bram Moolenaar071d4272004-06-13 20:20:40 +00001587 if (WaitForSingleObject(g_hConIn, p_mouset / 3)
1588 != WAIT_OBJECT_0)
1589 break;
1590 else
1591 {
1592 DWORD cRecords = 0;
1593 INPUT_RECORD ir;
1594 MOUSE_EVENT_RECORD* pmer2 = &ir.Event.MouseEvent;
1595
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001596 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001597
1598 if (cRecords == 0 || ir.EventType != MOUSE_EVENT
1599 || !(pmer2->dwButtonState & LEFT_RIGHT))
1600 break;
1601 else
1602 {
1603 if (pmer2->dwEventFlags != MOUSE_MOVED)
1604 {
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001605 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001606
1607 return decode_mouse_event(pmer2);
1608 }
1609 else if (s_xOldMouse == pmer2->dwMousePosition.X &&
1610 s_yOldMouse == pmer2->dwMousePosition.Y)
1611 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001612 // throw away spurious mouse move
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001613 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001614
Bram Moolenaar0f873732019-12-05 20:28:46 +01001615 // are there any more mouse events in queue?
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001616 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001617
1618 if (cRecords==0 || ir.EventType != MOUSE_EVENT)
1619 break;
1620 }
1621 else
1622 break;
1623 }
1624 }
1625 }
1626 }
1627 }
1628
1629 if (s_fNextIsMiddle)
1630 {
1631 nButton = (pmer->dwEventFlags == MOUSE_MOVED)
1632 ? MOUSE_DRAG : MOUSE_MIDDLE;
1633 s_fNextIsMiddle = FALSE;
1634 }
1635 else if (cButtons == 2 &&
1636 ((pmer->dwButtonState & LEFT_RIGHT) == LEFT_RIGHT))
1637 {
1638 nButton = MOUSE_MIDDLE;
1639
1640 if (! s_fReleased && pmer->dwEventFlags != MOUSE_MOVED)
1641 {
1642 s_fNextIsMiddle = TRUE;
1643 nButton = MOUSE_RELEASE;
1644 }
1645 }
1646 else if ((pmer->dwButtonState & LEFT) == LEFT)
1647 nButton = MOUSE_LEFT;
1648 else if ((pmer->dwButtonState & MIDDLE) == MIDDLE)
1649 nButton = MOUSE_MIDDLE;
1650 else if ((pmer->dwButtonState & RIGHT) == RIGHT)
1651 nButton = MOUSE_RIGHT;
1652
1653 if (! s_fReleased && ! s_fNextIsMiddle
1654 && nButton != s_nOldButton && s_nOldButton != MOUSE_DRAG)
1655 return FALSE;
1656
1657 s_fReleased = s_fNextIsMiddle;
1658 }
1659
1660 if (pmer->dwEventFlags == 0 || pmer->dwEventFlags == DOUBLE_CLICK)
1661 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001662 // button pressed or released, without mouse moving
Bram Moolenaar071d4272004-06-13 20:20:40 +00001663 if (nButton != -1 && nButton != MOUSE_RELEASE)
1664 {
1665 DWORD dwCurrentTime = GetTickCount();
1666
1667 if (s_xOldMouse != g_xMouse
1668 || s_yOldMouse != g_yMouse
1669 || s_nOldButton != nButton
1670 || s_old_topline != curwin->w_topline
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001671# ifdef FEAT_DIFF
Bram Moolenaar071d4272004-06-13 20:20:40 +00001672 || s_old_topfill != curwin->w_topfill
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001673# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001674 || (int)(dwCurrentTime - s_dwLastClickTime) > p_mouset)
1675 {
1676 s_cClicks = 1;
1677 }
1678 else if (++s_cClicks > 4)
1679 {
1680 s_cClicks = 1;
1681 }
1682
1683 s_dwLastClickTime = dwCurrentTime;
1684 }
1685 }
1686 else if (pmer->dwEventFlags == MOUSE_MOVED)
1687 {
1688 if (nButton != -1 && nButton != MOUSE_RELEASE)
1689 nButton = MOUSE_DRAG;
1690
1691 s_cClicks = 1;
1692 }
1693
1694 if (nButton == -1)
1695 return FALSE;
1696
1697 if (nButton != MOUSE_RELEASE)
1698 s_nOldButton = nButton;
1699
1700 g_nMouseClick = nButton;
1701
1702 if (pmer->dwControlKeyState & SHIFT_PRESSED)
1703 g_nMouseClick |= MOUSE_SHIFT;
1704 if (pmer->dwControlKeyState & (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED))
1705 g_nMouseClick |= MOUSE_CTRL;
1706 if (pmer->dwControlKeyState & (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED))
1707 g_nMouseClick |= MOUSE_ALT;
1708
1709 if (nButton != MOUSE_DRAG && nButton != MOUSE_RELEASE)
1710 SET_NUM_MOUSE_CLICKS(g_nMouseClick, s_cClicks);
1711
Bram Moolenaar0f873732019-12-05 20:28:46 +01001712 // only pass on interesting (i.e., different) mouse events
Bram Moolenaar071d4272004-06-13 20:20:40 +00001713 if (s_xOldMouse == g_xMouse
1714 && s_yOldMouse == g_yMouse
1715 && s_nOldMouseClick == g_nMouseClick)
1716 {
1717 g_nMouseClick = -1;
1718 return FALSE;
1719 }
1720
1721 s_xOldMouse = g_xMouse;
1722 s_yOldMouse = g_yMouse;
1723 s_old_topline = curwin->w_topline;
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001724# ifdef FEAT_DIFF
Bram Moolenaar071d4272004-06-13 20:20:40 +00001725 s_old_topfill = curwin->w_topfill;
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001726# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001727 s_nOldMouseClick = g_nMouseClick;
1728
1729 return TRUE;
1730}
1731
Christopher Plewright20b795e2022-12-20 20:01:58 +00001732# ifdef FEAT_EVAL
1733 static int
1734encode_mouse_event(dict_T *args, INPUT_RECORD *ir)
1735{
1736 int button;
1737 int row;
1738 int col;
1739 int repeated_click;
Bram Moolenaar9b8a3652022-12-20 20:47:28 +00001740 int_u mods = 0;
Christopher Plewright20b795e2022-12-20 20:01:58 +00001741 int move;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001742
Christopher Plewright20b795e2022-12-20 20:01:58 +00001743 if (!dict_has_key(args, "row") || !dict_has_key(args, "col"))
1744 return FALSE;
1745
1746 // Note: "move" is optional, requires fewer arguments
1747 move = (int)dict_get_bool(args, "move", FALSE);
1748 if (!move && (!dict_has_key(args, "button")
1749 || !dict_has_key(args, "multiclick")
1750 || !dict_has_key(args, "modifiers")))
1751 return FALSE;
1752
1753 row = (int)dict_get_number(args, "row") - 1;
1754 col = (int)dict_get_number(args, "col") - 1;
1755
1756 ir->EventType = MOUSE_EVENT;
1757 MOUSE_EVENT_RECORD mer;
1758 ZeroMemory(&mer, sizeof(mer));
1759 mer.dwMousePosition.X = col;
1760 mer.dwMousePosition.Y = row;
1761
1762 if (move)
1763 {
1764 mer.dwButtonState = 0;
1765 mer.dwEventFlags = MOUSE_MOVED;
1766 }
1767 else
1768 {
1769 button = (int)dict_get_number(args, "button");
1770 repeated_click = (int)dict_get_number(args, "multiclick");
1771 mods = (int)dict_get_number(args, "modifiers");
1772 // Reset the scroll values to known values.
1773 // XXX: Remove this when/if the scroll step is made configurable.
1774 mouse_set_hor_scroll_step(6);
1775 mouse_set_vert_scroll_step(3);
1776
1777 switch (button)
1778 {
1779 case MOUSE_LEFT:
1780 mer.dwButtonState = FROM_LEFT_1ST_BUTTON_PRESSED;
1781 mer.dwEventFlags = repeated_click == 1 ? DOUBLE_CLICK : 0;
1782 break;
1783 case MOUSE_MIDDLE:
1784 mer.dwButtonState = FROM_LEFT_2ND_BUTTON_PRESSED;
1785 mer.dwEventFlags = repeated_click == 1 ? DOUBLE_CLICK : 0;
1786 break;
1787 case MOUSE_RIGHT:
1788 mer.dwButtonState = RIGHTMOST_BUTTON_PRESSED;
1789 mer.dwEventFlags = repeated_click == 1 ? DOUBLE_CLICK : 0;
1790 break;
1791 case MOUSE_RELEASE:
1792 // umm? Assume Left Release?
1793 mer.dwEventFlags = 0;
1794
1795 case MOUSE_MOVE:
1796 mer.dwButtonState = 0;
1797 mer.dwEventFlags = MOUSE_MOVED;
1798 break;
1799 case MOUSE_X1:
1800 mer.dwButtonState = FROM_LEFT_3RD_BUTTON_PRESSED;
1801 break;
1802 case MOUSE_X2:
1803 mer.dwButtonState = FROM_LEFT_4TH_BUTTON_PRESSED;
1804 break;
1805 case MOUSE_4: // KE_MOUSEDOWN;
1806 mer.dwButtonState = -1;
1807 mer.dwEventFlags = MOUSE_WHEELED;
1808 break;
1809 case MOUSE_5: // KE_MOUSEUP;
1810 mer.dwButtonState = +1;
1811 mer.dwEventFlags = MOUSE_WHEELED;
1812 break;
1813 case MOUSE_6: // KE_MOUSELEFT;
1814 mer.dwButtonState = -1;
1815 mer.dwEventFlags = MOUSE_HWHEELED;
1816 break;
1817 case MOUSE_7: // KE_MOUSERIGHT;
1818 mer.dwButtonState = +1;
1819 mer.dwEventFlags = MOUSE_HWHEELED;
1820 break;
1821 default:
1822 semsg(_(e_invalid_argument_str), "button");
1823 return FALSE;
1824 }
1825 }
1826
1827 mer.dwControlKeyState = 0;
1828 if (mods != 0)
1829 {
1830 // Encode the win32 console key modifiers from Vim MOUSE modifiers.
1831 if (mods & MOUSE_SHIFT)
1832 mer.dwControlKeyState |= SHIFT_PRESSED;
1833 if (mods & MOUSE_CTRL)
1834 mer.dwControlKeyState |= LEFT_CTRL_PRESSED;
1835 if (mods & MOUSE_ALT)
1836 mer.dwControlKeyState |= LEFT_ALT_PRESSED;
1837 }
1838 ir->Event.MouseEvent = mer;
1839 return TRUE;
1840}
1841# endif // FEAT_EVAL
1842
1843 static int
1844write_input_record_buffer(INPUT_RECORD* irEvents, int nLength)
1845{
1846 int nCount = 0;
1847 while (nCount < nLength)
1848 {
1849 input_record_buffer.length++;
1850 input_record_buffer_node_T *event_node =
1851 malloc(sizeof(input_record_buffer_node_T));
1852 event_node->ir = irEvents[nCount++];
1853 event_node->next = NULL;
1854 if (input_record_buffer.tail == NULL)
1855 {
1856 input_record_buffer.head = event_node;
1857 input_record_buffer.tail = event_node;
1858 }
1859 else
1860 {
1861 input_record_buffer.tail->next = event_node;
1862 input_record_buffer.tail = input_record_buffer.tail->next;
1863 }
1864 }
1865 return nCount;
1866}
1867
1868 static int
1869read_input_record_buffer(INPUT_RECORD* irEvents, int nMaxLength)
1870{
1871 int nCount = 0;
1872 while (nCount < nMaxLength && input_record_buffer.head != NULL)
1873 {
1874 input_record_buffer.length--;
1875 input_record_buffer_node_T *pop_head = input_record_buffer.head;
1876 irEvents[nCount++] = pop_head->ir;
1877 input_record_buffer.head = pop_head->next;
1878 vim_free(pop_head);
1879 if (input_record_buffer.length == 0)
1880 input_record_buffer.tail = NULL;
1881 }
1882 return nCount;
1883}
Christopher Plewright20b795e2022-12-20 20:01:58 +00001884#endif // !FEAT_GUI_MSWIN || VIMDLL
1885
1886#ifdef FEAT_EVAL
1887/*
1888 * The 'test_mswin_event' function is for testing Vim's low-level handling of
1889 * user input events. ie, this manages the encoding of INPUT_RECORD events
1890 * so that we have a way to test how Vim decodes INPUT_RECORD events in Windows
1891 * consoles.
1892 *
1893 * The 'test_mswin_event' function is based on 'test_gui_event'. In fact, when
1894 * the Windows GUI is running, the arguments; 'event' and 'args', are the same.
1895 * So, it acts as an alias for 'test_gui_event' for the Windows GUI.
1896 *
1897 * When the Windows console is running, the arguments; 'event' and 'args', are
1898 * a subset of what 'test_gui_event' handles, ie, only "key" and "mouse"
1899 * events are encoded as INPUT_RECORD events.
1900 *
1901 * Note: INPUT_RECORDs are only used by the Windows console, not the GUI. The
1902 * GUI sends MSG structs instead.
1903 */
1904 int
1905test_mswin_event(char_u *event, dict_T *args)
1906{
1907 int lpEventsWritten = 0;
1908
1909# if defined(VIMDLL) || defined(FEAT_GUI_MSWIN)
1910 if (gui.in_use)
1911 return test_gui_w32_sendevent(event, args);
1912# endif
1913
1914# if defined(VIMDLL) || !defined(FEAT_GUI_MSWIN)
1915
1916// Currently implemented event record types are; KEY_EVENT and MOUSE_EVENT
1917// Potentially could also implement: FOCUS_EVENT and WINDOW_BUFFER_SIZE_EVENT
1918// Maybe also: MENU_EVENT
1919
1920 INPUT_RECORD ir;
1921 BOOL input_encoded = FALSE;
1922 if (STRCMP(event, "key") == 0)
1923 input_encoded = encode_key_event(args, &ir);
1924 else if (STRCMP(event, "mouse") == 0)
1925 input_encoded = encode_mouse_event(args, &ir);
1926 else
1927 {
1928 semsg(_(e_invalid_value_for_argument_str_str), "event", event);
1929 return FALSE;
1930 }
1931
1932 // Ideally, WriteConsoleInput would be used to inject these low-level
1933 // events. But, this doesnt work well in the CI test environment. So
1934 // implementing an input_record_buffer instead.
1935 if (input_encoded)
1936 lpEventsWritten = write_input_record_buffer(&ir, 1);
1937
1938 if (STRCMP(event, "mouse") == 0)
1939 exec_normal(TRUE, TRUE, TRUE);
1940
1941# endif
1942 return lpEventsWritten;
1943}
1944#endif // FEAT_EVAL
Bram Moolenaar071d4272004-06-13 20:20:40 +00001945
1946#ifdef MCH_CURSOR_SHAPE
1947/*
1948 * Set the shape of the cursor.
1949 * 'thickness' can be from 1 (thin) to 99 (block)
1950 */
1951 static void
1952mch_set_cursor_shape(int thickness)
1953{
Christopher Plewright38804d62022-11-09 23:55:52 +00001954 if (vtp_working)
K.Takatadf5320c2022-09-01 13:20:16 +01001955 {
1956 if (*T_CSI == NUL)
1957 {
1958 // If 't_SI' is not set, use the default cursor styles.
1959 if (thickness < 50)
1960 vtp_printf("\033[3 q"); // underline
1961 else
1962 vtp_printf("\033[0 q"); // default
1963 }
1964 }
1965 else
1966 {
1967 CONSOLE_CURSOR_INFO ConsoleCursorInfo;
1968 ConsoleCursorInfo.dwSize = thickness;
1969 ConsoleCursorInfo.bVisible = s_cursor_visible;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001970
K.Takatadf5320c2022-09-01 13:20:16 +01001971 SetConsoleCursorInfo(g_hConOut, &ConsoleCursorInfo);
1972 if (s_cursor_visible)
1973 SetConsoleCursorPosition(g_hConOut, g_coord);
1974 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001975}
1976
1977 void
1978mch_update_cursor(void)
1979{
1980 int idx;
1981 int thickness;
1982
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001983# ifdef VIMDLL
1984 if (gui.in_use)
1985 return;
1986# endif
1987
Bram Moolenaar071d4272004-06-13 20:20:40 +00001988 /*
1989 * How the cursor is drawn depends on the current mode.
1990 */
1991 idx = get_shape_idx(FALSE);
1992
1993 if (shape_table[idx].shape == SHAPE_BLOCK)
Bram Moolenaar0f873732019-12-05 20:28:46 +01001994 thickness = 99; // 100 doesn't work on W95
Bram Moolenaar071d4272004-06-13 20:20:40 +00001995 else
1996 thickness = shape_table[idx].percentage;
1997 mch_set_cursor_shape(thickness);
1998}
1999#endif
2000
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002001#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002002/*
2003 * Handle FOCUS_EVENT.
2004 */
2005 static void
2006handle_focus_event(INPUT_RECORD ir)
2007{
2008 g_fJustGotFocus = ir.Event.FocusEvent.bSetFocus;
2009 ui_focus_change((int)g_fJustGotFocus);
2010}
2011
Bram Moolenaar78d21da2019-02-17 15:00:52 +01002012static void ResizeConBuf(HANDLE hConsole, COORD coordScreen);
2013
Bram Moolenaar071d4272004-06-13 20:20:40 +00002014/*
2015 * Wait until console input from keyboard or mouse is available,
2016 * or the time is up.
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02002017 * When "ignore_input" is TRUE even wait when input is available.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002018 * Return TRUE if something is available FALSE if not.
2019 */
2020 static int
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02002021WaitForChar(long msec, int ignore_input)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002022{
2023 DWORD dwNow = 0, dwEndTime = 0;
2024 INPUT_RECORD ir;
2025 DWORD cRecords;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002026 WCHAR ch, ch2;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002027# ifdef FEAT_TIMERS
Bram Moolenaar40b1b542016-04-20 20:18:23 +02002028 int tb_change_cnt = typebuf.tb_change_cnt;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002029# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002030
2031 if (msec > 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01002032 // Wait until the specified time has elapsed.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002033 dwEndTime = GetTickCount() + msec;
2034 else if (msec < 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01002035 // Wait forever.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002036 dwEndTime = INFINITE;
2037
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01002038 // We need to loop until the end of the time period, because
2039 // we might get multiple unusable mouse events in that time.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002040 for (;;)
2041 {
Bram Moolenaared5a9d62018-09-06 13:14:43 +02002042 // Only process messages when waiting.
2043 if (msec != 0)
2044 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002045# ifdef MESSAGE_QUEUE
Bram Moolenaared5a9d62018-09-06 13:14:43 +02002046 parse_queued_messages();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002047# endif
2048# ifdef FEAT_MZSCHEME
Bram Moolenaared5a9d62018-09-06 13:14:43 +02002049 mzvim_check_threads();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002050# endif
2051# ifdef FEAT_CLIENTSERVER
Bram Moolenaared5a9d62018-09-06 13:14:43 +02002052 serverProcessPendingMessages();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002053# endif
Bram Moolenaared5a9d62018-09-06 13:14:43 +02002054 }
Bram Moolenaarf12d9832016-01-29 21:11:25 +01002055
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02002056 if (g_nMouseClick != -1
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002057# ifdef FEAT_CLIENTSERVER
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02002058 || (!ignore_input && input_available())
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002059# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002060 )
2061 return TRUE;
2062
2063 if (msec > 0)
2064 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01002065 // If the specified wait time has passed, return. Beware that
2066 // GetTickCount() may wrap around (overflow).
Bram Moolenaar071d4272004-06-13 20:20:40 +00002067 dwNow = GetTickCount();
Bram Moolenaarb7512b72013-08-10 12:45:09 +02002068 if ((int)(dwNow - dwEndTime) >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002069 break;
2070 }
2071 if (msec != 0)
2072 {
Bram Moolenaar325b7a22004-07-05 15:58:32 +00002073 DWORD dwWaitTime = dwEndTime - dwNow;
2074
Bram Moolenaarc478ee32020-12-01 21:27:51 +01002075 // Don't wait for more than 11 msec to avoid dropping characters,
2076 // check channel while waiting for input and handle a callback from
2077 // 'balloonexpr'.
2078 if (dwWaitTime > 11)
2079 dwWaitTime = 11;
2080
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002081# ifdef FEAT_MZSCHEME
Bram Moolenaarc478ee32020-12-01 21:27:51 +01002082 if (mzthreads_allowed() && p_mzq > 0 && (long)dwWaitTime > p_mzq)
Bram Moolenaar0f873732019-12-05 20:28:46 +01002083 dwWaitTime = p_mzq; // don't wait longer than 'mzquantum'
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002084# endif
2085# ifdef FEAT_TIMERS
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01002086 // When waiting very briefly don't trigger timers.
2087 if (dwWaitTime > 10)
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01002088 {
2089 long due_time;
2090
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01002091 // Trigger timers and then get the time in msec until the next
2092 // one is due. Wait up to that time.
2093 due_time = check_due_timer();
2094 if (typebuf.tb_change_cnt != tb_change_cnt)
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01002095 {
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01002096 // timer may have used feedkeys().
2097 return FALSE;
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01002098 }
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01002099 if (due_time > 0 && dwWaitTime > (DWORD)due_time)
2100 dwWaitTime = due_time;
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01002101 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002102# endif
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01002103 if (
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002104# ifdef FEAT_CLIENTSERVER
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01002105 // Wait for either an event on the console input or a
2106 // message in the client-server window.
2107 msg_wait_for_multiple_objects(1, &g_hConIn, FALSE,
2108 dwWaitTime, QS_SENDMESSAGE) != WAIT_OBJECT_0
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002109# else
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01002110 wait_for_single_object(g_hConIn, dwWaitTime)
2111 != WAIT_OBJECT_0
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002112# endif
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01002113 )
2114 continue;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002115 }
2116
2117 cRecords = 0;
Bram Moolenaar3a69e112014-01-10 13:51:42 +01002118 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002119
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002120# ifdef FEAT_MBYTE_IME
matveyt4eb19142021-05-20 11:54:10 +02002121 // May have to redraw if the cursor ends up in the wrong place.
2122 // Only when not peeking.
Bram Moolenaar24959102022-05-07 20:01:16 +01002123 if (State == MODE_CMDLINE && msg_row == Rows - 1 && msec != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002124 {
2125 CONSOLE_SCREEN_BUFFER_INFO csbi;
2126
2127 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
2128 {
2129 if (csbi.dwCursorPosition.Y != msg_row)
2130 {
matveyte08795e2021-05-07 15:00:17 +02002131 // The screen is now messed up, must redraw the command
2132 // line and later all the windows.
Bram Moolenaara4d158b2022-08-14 14:17:45 +01002133 redraw_all_later(UPD_CLEAR);
matveyte08795e2021-05-07 15:00:17 +02002134 compute_cmdrow();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002135 redrawcmd();
2136 }
2137 }
2138 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002139# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002140
2141 if (cRecords > 0)
2142 {
2143 if (ir.EventType == KEY_EVENT && ir.Event.KeyEvent.bKeyDown)
2144 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002145# ifdef FEAT_MBYTE_IME
Bram Moolenaar0f873732019-12-05 20:28:46 +01002146 // Windows IME sends two '\n's with only one 'ENTER'. First:
2147 // wVirtualKeyCode == 13. second: wVirtualKeyCode == 0
K.Takata972db232022-02-04 10:45:38 +00002148 if (ir.Event.KeyEvent.uChar.UnicodeChar == 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00002149 && ir.Event.KeyEvent.wVirtualKeyCode == 13)
2150 {
Bram Moolenaar3a69e112014-01-10 13:51:42 +01002151 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002152 continue;
2153 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002154# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002155 if (decode_key_event(&ir.Event.KeyEvent, &ch, &ch2,
2156 NULL, FALSE))
2157 return TRUE;
2158 }
2159
Bram Moolenaar3a69e112014-01-10 13:51:42 +01002160 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002161
2162 if (ir.EventType == FOCUS_EVENT)
2163 handle_focus_event(ir);
2164 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
Bram Moolenaarc33ecb22018-02-11 16:40:45 +01002165 {
Bram Moolenaar78d21da2019-02-17 15:00:52 +01002166 COORD dwSize = ir.Event.WindowBufferSizeEvent.dwSize;
2167
Bram Moolenaar36698e32019-12-11 22:57:40 +01002168 // Only call shell_resized() when the size actually changed to
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002169 // avoid the screen is cleared.
Bram Moolenaar78d21da2019-02-17 15:00:52 +01002170 if (dwSize.X != Columns || dwSize.Y != Rows)
2171 {
2172 CONSOLE_SCREEN_BUFFER_INFO csbi;
2173 GetConsoleScreenBufferInfo(g_hConOut, &csbi);
Bram Moolenaar36698e32019-12-11 22:57:40 +01002174 dwSize.X = csbi.srWindow.Right - csbi.srWindow.Left + 1;
Bram Moolenaar78d21da2019-02-17 15:00:52 +01002175 dwSize.Y = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
Bram Moolenaar36698e32019-12-11 22:57:40 +01002176 if (dwSize.X != Columns || dwSize.Y != Rows)
2177 {
2178 ResizeConBuf(g_hConOut, dwSize);
2179 shell_resized();
2180 }
Bram Moolenaar78d21da2019-02-17 15:00:52 +01002181 }
Bram Moolenaarc33ecb22018-02-11 16:40:45 +01002182 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002183 else if (ir.EventType == MOUSE_EVENT
2184 && decode_mouse_event(&ir.Event.MouseEvent))
2185 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002186 }
2187 else if (msec == 0)
2188 break;
2189 }
2190
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002191# ifdef FEAT_CLIENTSERVER
Bram Moolenaar0f873732019-12-05 20:28:46 +01002192 // Something might have been received while we were waiting.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002193 if (input_available())
2194 return TRUE;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002195# endif
Bram Moolenaarf12d9832016-01-29 21:11:25 +01002196
Bram Moolenaar071d4272004-06-13 20:20:40 +00002197 return FALSE;
2198}
2199
Bram Moolenaar071d4272004-06-13 20:20:40 +00002200/*
2201 * return non-zero if a character is available
2202 */
2203 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002204mch_char_avail(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002205{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002206# ifdef VIMDLL
2207 if (gui.in_use)
2208 return TRUE;
2209# endif
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02002210 return WaitForChar(0L, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002211}
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02002212
2213# if defined(FEAT_TERMINAL) || defined(PROTO)
2214/*
2215 * Check for any pending input or messages.
2216 */
2217 int
2218mch_check_messages(void)
2219{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002220# ifdef VIMDLL
2221 if (gui.in_use)
2222 return TRUE;
2223# endif
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02002224 return WaitForChar(0L, TRUE);
2225}
2226# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002227
2228/*
2229 * Create the console input. Used when reading stdin doesn't work.
2230 */
2231 static void
2232create_conin(void)
2233{
2234 g_hConIn = CreateFile("CONIN$", GENERIC_READ|GENERIC_WRITE,
2235 FILE_SHARE_READ|FILE_SHARE_WRITE,
2236 (LPSECURITY_ATTRIBUTES) NULL,
Bram Moolenaareb3593b2006-04-22 22:33:57 +00002237 OPEN_EXISTING, 0, (HANDLE)NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002238 did_create_conin = TRUE;
2239}
2240
2241/*
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01002242 * Get a keystroke or a mouse event, use a blocking wait.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002243 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002244 static WCHAR
2245tgetch(int *pmodifiers, WCHAR *pch2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002246{
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002247 WCHAR ch;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002248
2249 for (;;)
2250 {
2251 INPUT_RECORD ir;
2252 DWORD cRecords = 0;
2253
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002254# ifdef FEAT_CLIENTSERVER
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02002255 (void)WaitForChar(-1L, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002256 if (input_available())
2257 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002258 if (g_nMouseClick != -1)
2259 return 0;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002260# endif
Bram Moolenaar3a69e112014-01-10 13:51:42 +01002261 if (read_console_input(g_hConIn, &ir, 1, &cRecords) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002262 {
2263 if (did_create_conin)
2264 read_error_exit();
2265 create_conin();
2266 continue;
2267 }
2268
2269 if (ir.EventType == KEY_EVENT)
2270 {
2271 if (decode_key_event(&ir.Event.KeyEvent, &ch, pch2,
2272 pmodifiers, TRUE))
2273 return ch;
2274 }
2275 else if (ir.EventType == FOCUS_EVENT)
2276 handle_focus_event(ir);
2277 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
2278 shell_resized();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002279 else if (ir.EventType == MOUSE_EVENT)
2280 {
2281 if (decode_mouse_event(&ir.Event.MouseEvent))
2282 return 0;
2283 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002284 }
2285}
Bram Moolenaar0f873732019-12-05 20:28:46 +01002286#endif // !FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00002287
2288
2289/*
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02002290 * mch_inchar(): low-level input function.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002291 * Get one or more characters from the keyboard or the mouse.
2292 * If time == 0, do not wait for characters.
2293 * If time == n, wait a short time for characters.
2294 * If time == -1, wait forever for characters.
2295 * Returns the number of characters read into buf.
2296 */
2297 int
2298mch_inchar(
Bram Moolenaar1266d672017-02-01 13:43:36 +01002299 char_u *buf UNUSED,
2300 int maxlen UNUSED,
2301 long time UNUSED,
2302 int tb_change_cnt UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002303{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002304#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002305
2306 int len;
2307 int c;
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01002308# ifdef VIMDLL
2309// Extra space for maximum three CSIs. E.g. U+1B6DB -> 0xF0 0x9B 0x9B 0x9B.
2310# define TYPEAHEADSPACE 6
2311# else
2312# define TYPEAHEADSPACE 0
2313# endif
2314# define TYPEAHEADLEN (20 + TYPEAHEADSPACE)
Bram Moolenaar0f873732019-12-05 20:28:46 +01002315 static char_u typeahead[TYPEAHEADLEN]; // previously typed bytes.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002316 static int typeaheadlen = 0;
2317
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002318# ifdef VIMDLL
2319 if (gui.in_use)
2320 return 0;
2321# endif
2322
Bram Moolenaar0f873732019-12-05 20:28:46 +01002323 // First use any typeahead that was kept because "buf" was too small.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002324 if (typeaheadlen > 0)
2325 goto theend;
2326
Bram Moolenaar071d4272004-06-13 20:20:40 +00002327 if (time >= 0)
2328 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01002329 if (!WaitForChar(time, FALSE)) // no character available
Bram Moolenaar071d4272004-06-13 20:20:40 +00002330 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002331 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01002332 else // time == -1, wait forever
Bram Moolenaar071d4272004-06-13 20:20:40 +00002333 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01002334 mch_set_winsize_now(); // Allow winsize changes from now on
Bram Moolenaar071d4272004-06-13 20:20:40 +00002335
Bram Moolenaar3918c952005-03-15 22:34:55 +00002336 /*
2337 * If there is no character available within 2 seconds (default)
2338 * write the autoscript file to disk. Or cause the CursorHold event
2339 * to be triggered.
2340 */
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02002341 if (!WaitForChar(p_ut, FALSE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002342 {
Bram Moolenaard35f9712005-12-18 22:02:33 +00002343 if (trigger_cursorhold() && maxlen >= 3)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002344 {
Bram Moolenaar3918c952005-03-15 22:34:55 +00002345 buf[0] = K_SPECIAL;
2346 buf[1] = KS_EXTRA;
2347 buf[2] = (int)KE_CURSORHOLD;
2348 return 3;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002349 }
Bram Moolenaar702517d2005-06-27 22:34:07 +00002350 before_blocking();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002351 }
2352 }
2353
2354 /*
2355 * Try to read as many characters as there are, until the buffer is full.
2356 */
2357
Bram Moolenaar0f873732019-12-05 20:28:46 +01002358 // we will get at least one key. Get more if they are available.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002359 g_fCBrkPressed = FALSE;
2360
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002361# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00002362 if (fdDump)
2363 fputc('[', fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002364# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002365
Bram Moolenaar0f873732019-12-05 20:28:46 +01002366 // Keep looping until there is something in the typeahead buffer and more
2367 // to get and still room in the buffer (up to two bytes for a char and
2368 // three bytes for a modifier).
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02002369 while ((typeaheadlen == 0 || WaitForChar(0L, FALSE))
Bram Moolenaar9f1983d2022-05-12 20:35:35 +01002370 && typeaheadlen + 5 + TYPEAHEADSPACE <= TYPEAHEADLEN)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002371 {
2372 if (typebuf_changed(tb_change_cnt))
2373 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01002374 // "buf" may be invalid now if a client put something in the
2375 // typeahead buffer and "buf" is in the typeahead buffer.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002376 typeaheadlen = 0;
2377 break;
2378 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002379 if (g_nMouseClick != -1)
2380 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002381# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00002382 if (fdDump)
2383 fprintf(fdDump, "{%02x @ %d, %d}",
2384 g_nMouseClick, g_xMouse, g_yMouse);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002385# endif
Christopher Plewright2a46f812022-10-16 19:47:45 +01002386 char_u modifiers = ((char_u *)(&g_nMouseClick))[0];
2387 char_u scroll_dir = ((char_u *)(&g_nMouseClick))[1];
2388
2389 if (scroll_dir == KE_MOUSEDOWN
2390 || scroll_dir == KE_MOUSEUP
2391 || scroll_dir == KE_MOUSELEFT
2392 || scroll_dir == KE_MOUSERIGHT)
2393 {
2394 if (modifiers > 0)
2395 {
Christopher Plewright03193062022-11-22 12:58:27 +00002396 // use K_SPECIAL instead of CSI to make mappings work
2397 typeahead[typeaheadlen++] = K_SPECIAL;
Christopher Plewright2a46f812022-10-16 19:47:45 +01002398 typeahead[typeaheadlen++] = KS_MODIFIER;
2399 typeahead[typeaheadlen++] = modifiers;
2400 }
2401 typeahead[typeaheadlen++] = CSI;
2402 typeahead[typeaheadlen++] = KS_EXTRA;
2403 typeahead[typeaheadlen++] = scroll_dir;
Christopher Plewright2a46f812022-10-16 19:47:45 +01002404 }
2405 else
2406 {
2407 typeahead[typeaheadlen++] = ESC + 128;
2408 typeahead[typeaheadlen++] = 'M';
2409 typeahead[typeaheadlen++] = g_nMouseClick;
Christopher Plewright2a46f812022-10-16 19:47:45 +01002410 }
Christopher Plewright36446bb2022-11-23 22:28:08 +00002411
2412 // Pass the pointer coordinates of the mouse event in 2 bytes,
2413 // allowing for > 223 columns. Both for click and scroll events.
2414 // This is the same as what is used for the GUI.
2415 typeahead[typeaheadlen++] = (char_u)(g_xMouse / 128 + ' ' + 1);
2416 typeahead[typeaheadlen++] = (char_u)(g_xMouse % 128 + ' ' + 1);
2417 typeahead[typeaheadlen++] = (char_u)(g_yMouse / 128 + ' ' + 1);
2418 typeahead[typeaheadlen++] = (char_u)(g_yMouse % 128 + ' ' + 1);
2419
2420 g_nMouseClick = -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002421 }
2422 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00002423 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002424 WCHAR ch2 = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002425 int modifiers = 0;
2426
2427 c = tgetch(&modifiers, &ch2);
2428
2429 if (typebuf_changed(tb_change_cnt))
2430 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01002431 // "buf" may be invalid now if a client put something in the
2432 // typeahead buffer and "buf" is in the typeahead buffer.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002433 typeaheadlen = 0;
2434 break;
2435 }
2436
2437 if (c == Ctrl_C && ctrl_c_interrupts)
2438 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002439# if defined(FEAT_CLIENTSERVER)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002440 trash_input_buf();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002441# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002442 got_int = TRUE;
2443 }
2444
Bram Moolenaar071d4272004-06-13 20:20:40 +00002445 if (g_nMouseClick == -1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002446 {
2447 int n = 1;
2448
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002449 if (ch2 == NUL)
2450 {
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01002451 int i, j;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002452 char_u *p;
2453 WCHAR ch[2];
2454
2455 ch[0] = c;
Bram Moolenaar0f873732019-12-05 20:28:46 +01002456 if (c >= 0xD800 && c <= 0xDBFF) // High surrogate
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002457 {
2458 ch[1] = tgetch(&modifiers, &ch2);
2459 n++;
2460 }
2461 p = utf16_to_enc(ch, &n);
2462 if (p != NULL)
2463 {
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01002464 for (i = 0, j = 0; i < n; i++)
2465 {
2466 typeahead[typeaheadlen + j++] = p[i];
2467# ifdef VIMDLL
2468 if (p[i] == CSI)
2469 {
2470 typeahead[typeaheadlen + j++] = KS_EXTRA;
2471 typeahead[typeaheadlen + j++] = KE_CSI;
2472 }
2473# endif
2474 }
2475 n = j;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002476 vim_free(p);
2477 }
2478 }
2479 else
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01002480 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002481 typeahead[typeaheadlen] = c;
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01002482# ifdef VIMDLL
2483 if (c == CSI)
2484 {
2485 typeahead[typeaheadlen + 1] = KS_EXTRA;
2486 typeahead[typeaheadlen + 2] = KE_CSI;
2487 n = 3;
2488 }
2489# endif
2490 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002491 if (ch2 != NUL)
2492 {
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +02002493 if (c == K_NUL)
Bram Moolenaarfeeb4d02017-12-05 15:14:46 +01002494 {
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +02002495 switch (ch2)
2496 {
2497 case (WCHAR)'\324': // SHIFT+Insert
2498 case (WCHAR)'\325': // CTRL+Insert
2499 case (WCHAR)'\327': // SHIFT+Delete
2500 case (WCHAR)'\330': // CTRL+Delete
2501 typeahead[typeaheadlen + n] = (char_u)ch2;
2502 n++;
2503 break;
2504
2505 default:
2506 typeahead[typeaheadlen + n] = 3;
2507 typeahead[typeaheadlen + n + 1] = (char_u)ch2;
2508 n += 2;
2509 break;
2510 }
Bram Moolenaarfeeb4d02017-12-05 15:14:46 +01002511 }
2512 else
2513 {
2514 typeahead[typeaheadlen + n] = 3;
2515 typeahead[typeaheadlen + n + 1] = (char_u)ch2;
2516 n += 2;
2517 }
Bram Moolenaar45500912014-07-09 20:51:07 +02002518 }
2519
Bram Moolenaar0f873732019-12-05 20:28:46 +01002520 // Use the ALT key to set the 8th bit of the character
2521 // when it's one byte, the 8th bit isn't set yet and not
2522 // using a double-byte encoding (would become a lead
2523 // byte).
Bram Moolenaar071d4272004-06-13 20:20:40 +00002524 if ((modifiers & MOD_MASK_ALT)
2525 && n == 1
2526 && (typeahead[typeaheadlen] & 0x80) == 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00002527 && !enc_dbcs
Bram Moolenaar071d4272004-06-13 20:20:40 +00002528 )
2529 {
Bram Moolenaar85a3e5c2007-11-20 16:22:16 +00002530 n = (*mb_char2bytes)(typeahead[typeaheadlen] | 0x80,
2531 typeahead + typeaheadlen);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002532 modifiers &= ~MOD_MASK_ALT;
2533 }
2534
2535 if (modifiers != 0)
2536 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01002537 // Prepend modifiers to the character.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002538 mch_memmove(typeahead + typeaheadlen + 3,
2539 typeahead + typeaheadlen, n);
2540 typeahead[typeaheadlen++] = K_SPECIAL;
2541 typeahead[typeaheadlen++] = (char_u)KS_MODIFIER;
2542 typeahead[typeaheadlen++] = modifiers;
2543 }
2544
2545 typeaheadlen += n;
2546
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002547# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00002548 if (fdDump)
2549 fputc(c, fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002550# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002551 }
2552 }
2553 }
2554
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002555# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00002556 if (fdDump)
2557 {
2558 fputs("]\n", fdDump);
2559 fflush(fdDump);
2560 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002561# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002562
Bram Moolenaar071d4272004-06-13 20:20:40 +00002563theend:
Bram Moolenaar0f873732019-12-05 20:28:46 +01002564 // Move typeahead to "buf", as much as fits.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002565 len = 0;
2566 while (len < maxlen && typeaheadlen > 0)
2567 {
2568 buf[len++] = typeahead[0];
2569 mch_memmove(typeahead, typeahead + 1, --typeaheadlen);
2570 }
Bram Moolenaar4c5678f2022-11-30 18:12:19 +00002571# ifdef FEAT_EVAL
Bram Moolenaar7ca86fe2020-09-03 19:25:11 +02002572 if (len > 0)
2573 {
2574 buf[len] = NUL;
2575 ch_log(NULL, "raw key input: \"%s\"", buf);
2576 }
K.Takata6e1d31e2022-02-03 13:05:32 +00002577# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002578 return len;
2579
Bram Moolenaar0f873732019-12-05 20:28:46 +01002580#else // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00002581 return 0;
Bram Moolenaar0f873732019-12-05 20:28:46 +01002582#endif // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00002583}
2584
Bram Moolenaar82881492012-11-20 16:53:39 +01002585#ifndef PROTO
2586# ifndef __MINGW32__
Bram Moolenaar0f873732019-12-05 20:28:46 +01002587# include <shellapi.h> // required for FindExecutable()
Bram Moolenaar82881492012-11-20 16:53:39 +01002588# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002589#endif
2590
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002591/*
Bram Moolenaar95da1362020-05-30 18:37:55 +02002592 * Return TRUE if "name" is an executable file, FALSE if not or it doesn't exist.
Bram Moolenaar43663192017-03-05 14:29:12 +01002593 * When returning TRUE and "path" is not NULL save the path and set "*path" to
2594 * the allocated memory.
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00002595 * TODO: Should somehow check if it's really executable.
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002596 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002597 static int
Bram Moolenaar95da1362020-05-30 18:37:55 +02002598executable_file(char *name, char_u **path)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002599{
LemonBoy40fd7e62022-05-05 20:18:16 +01002600 int attrs = win32_getattrs((char_u *)name);
2601
2602 // The file doesn't exist or is a folder.
2603 if (attrs == -1 || (attrs & FILE_ATTRIBUTE_DIRECTORY))
2604 return FALSE;
2605 // Check if the file is an AppExecLink, a special alias used by Windows
2606 // Store for its apps.
2607 if (attrs & FILE_ATTRIBUTE_REPARSE_POINT)
Bram Moolenaar43663192017-03-05 14:29:12 +01002608 {
LemonBoy40fd7e62022-05-05 20:18:16 +01002609 char_u *res = resolve_appexeclink((char_u *)name);
2610 if (res == NULL)
2611 return FALSE;
2612 // The path is already absolute.
Bram Moolenaar95da1362020-05-30 18:37:55 +02002613 if (path != NULL)
LemonBoy40fd7e62022-05-05 20:18:16 +01002614 *path = res;
2615 else
2616 vim_free(res);
Bram Moolenaar95da1362020-05-30 18:37:55 +02002617 }
LemonBoy40fd7e62022-05-05 20:18:16 +01002618 else if (path != NULL)
2619 *path = FullName_save((char_u *)name, FALSE);
2620 return TRUE;
Bram Moolenaar95da1362020-05-30 18:37:55 +02002621}
2622
2623/*
2624 * If "use_path" is TRUE: Return TRUE if "name" is in $PATH.
2625 * If "use_path" is FALSE: Return TRUE if "name" exists.
2626 * If "use_pathext" is TRUE search "name" with extensions in $PATHEXT.
2627 * When returning TRUE and "path" is not NULL save the path and set "*path" to
2628 * the allocated memory.
2629 */
2630 static int
2631executable_exists(char *name, char_u **path, int use_path, int use_pathext)
2632{
2633 // WinNT and later can use _MAX_PATH wide characters for a pathname, which
2634 // means that the maximum pathname is _MAX_PATH * 3 bytes when 'enc' is
2635 // UTF-8.
2636 char_u buf[_MAX_PATH * 3];
2637 size_t len = STRLEN(name);
2638 size_t tmplen;
2639 char_u *p, *e, *e2;
2640 char_u *pathbuf = NULL;
2641 char_u *pathext = NULL;
2642 char_u *pathextbuf = NULL;
Mike Williamsa3d1b292021-06-30 20:56:00 +02002643 char_u *shname = NULL;
Bram Moolenaar95da1362020-05-30 18:37:55 +02002644 int noext = FALSE;
2645 int retval = FALSE;
2646
2647 if (len >= sizeof(buf)) // safety check
Bram Moolenaar43663192017-03-05 14:29:12 +01002648 return FALSE;
Bram Moolenaar95da1362020-05-30 18:37:55 +02002649
2650 // Using the name directly when a Unix-shell like 'shell'.
Mike Williamsa3d1b292021-06-30 20:56:00 +02002651 shname = gettail(p_sh);
2652 if (strstr((char *)shname, "sh") != NULL &&
2653 !(strstr((char *)shname, "powershell") != NULL
2654 || strstr((char *)shname, "pwsh") != NULL))
Bram Moolenaar95da1362020-05-30 18:37:55 +02002655 noext = TRUE;
2656
2657 if (use_pathext)
2658 {
2659 pathext = mch_getenv("PATHEXT");
2660 if (pathext == NULL)
2661 pathext = (char_u *)".com;.exe;.bat;.cmd";
2662
2663 if (noext == FALSE)
2664 {
2665 /*
2666 * Loop over all extensions in $PATHEXT.
2667 * Check "name" ends with extension.
2668 */
2669 p = pathext;
2670 while (*p)
2671 {
2672 if (p[0] == ';'
2673 || (p[0] == '.' && (p[1] == NUL || p[1] == ';')))
2674 {
2675 // Skip empty or single ".".
2676 ++p;
2677 continue;
2678 }
2679 e = vim_strchr(p, ';');
2680 if (e == NULL)
2681 e = p + STRLEN(p);
2682 tmplen = e - p;
2683
2684 if (_strnicoll(name + len - tmplen, (char *)p, tmplen) == 0)
2685 {
2686 noext = TRUE;
2687 break;
2688 }
2689
2690 p = e;
2691 }
2692 }
Bram Moolenaar43663192017-03-05 14:29:12 +01002693 }
2694
Dominique Pelleaf4a61a2021-12-27 17:21:41 +00002695 // Prepend single "." to pathext, it means no extension added.
Bram Moolenaar95da1362020-05-30 18:37:55 +02002696 if (pathext == NULL)
2697 pathext = (char_u *)".";
2698 else if (noext == TRUE)
2699 {
2700 if (pathextbuf == NULL)
2701 pathextbuf = alloc(STRLEN(pathext) + 3);
2702 if (pathextbuf == NULL)
2703 {
2704 retval = FALSE;
2705 goto theend;
2706 }
2707 STRCPY(pathextbuf, ".;");
2708 STRCAT(pathextbuf, pathext);
2709 pathext = pathextbuf;
2710 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002711
Bram Moolenaar95da1362020-05-30 18:37:55 +02002712 // Use $PATH when "use_path" is TRUE and "name" is basename.
2713 if (use_path && gettail((char_u *)name) == (char_u *)name)
2714 {
2715 p = mch_getenv("PATH");
2716 if (p != NULL)
2717 {
2718 pathbuf = alloc(STRLEN(p) + 3);
2719 if (pathbuf == NULL)
2720 {
2721 retval = FALSE;
2722 goto theend;
2723 }
Yasuhiro Matsumoto05cf63e2022-05-03 11:02:28 +01002724
2725 if (mch_getenv("NoDefaultCurrentDirectoryInExePath") == NULL)
2726 STRCPY(pathbuf, ".;");
2727 else
2728 *pathbuf = NUL;
Bram Moolenaar95da1362020-05-30 18:37:55 +02002729 STRCAT(pathbuf, p);
2730 }
2731 }
2732
2733 /*
2734 * Walk through all entries in $PATH to check if "name" exists there and
2735 * is an executable file.
2736 */
2737 p = (pathbuf != NULL) ? pathbuf : (char_u *)".";
2738 while (*p)
2739 {
2740 if (*p == ';') // Skip empty entry
2741 {
2742 ++p;
2743 continue;
2744 }
2745 e = vim_strchr(p, ';');
2746 if (e == NULL)
2747 e = p + STRLEN(p);
2748
2749 if (e - p + len + 2 > sizeof(buf))
2750 {
2751 retval = FALSE;
2752 goto theend;
2753 }
2754 // A single "." that means current dir.
2755 if (e - p == 1 && *p == '.')
2756 STRCPY(buf, name);
2757 else
2758 {
2759 vim_strncpy(buf, p, e - p);
2760 add_pathsep(buf);
2761 STRCAT(buf, name);
2762 }
2763 tmplen = STRLEN(buf);
2764
2765 /*
2766 * Loop over all extensions in $PATHEXT.
2767 * Check "name" with extension added.
2768 */
2769 p = pathext;
2770 while (*p)
2771 {
2772 if (*p == ';')
2773 {
2774 // Skip empty entry
2775 ++p;
2776 continue;
2777 }
2778 e2 = vim_strchr(p, (int)';');
2779 if (e2 == NULL)
2780 e2 = p + STRLEN(p);
2781
2782 if (!(p[0] == '.' && (p[1] == NUL || p[1] == ';')))
2783 {
2784 // Not a single "." that means no extension is added.
2785 if (e2 - p + tmplen + 1 > sizeof(buf))
2786 {
2787 retval = FALSE;
2788 goto theend;
2789 }
2790 vim_strncpy(buf + tmplen, p, e2 - p);
2791 }
2792 if (executable_file((char *)buf, path))
2793 {
2794 retval = TRUE;
2795 goto theend;
2796 }
2797
2798 p = e2;
2799 }
2800
2801 p = e;
2802 }
2803
2804theend:
2805 free(pathextbuf);
2806 free(pathbuf);
2807 return retval;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002808}
2809
Bram Moolenaar1eed5322019-02-26 17:03:54 +01002810#if (defined(__MINGW32__) && __MSVCRT_VERSION__ >= 0x800) || \
2811 (defined(_MSC_VER) && _MSC_VER >= 1400)
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002812/*
2813 * Bad parameter handler.
2814 *
2815 * Certain MS CRT functions will intentionally crash when passed invalid
2816 * parameters to highlight possible security holes. Setting this function as
2817 * the bad parameter handler will prevent the crash.
2818 *
2819 * In debug builds the parameters contain CRT information that might help track
2820 * down the source of a problem, but in non-debug builds the arguments are all
2821 * NULL/0. Debug builds will also produce assert dialogs from the CRT, it is
2822 * worth allowing these to make debugging of issues easier.
2823 */
2824 static void
Yegappan Lakshmanana34b4462022-06-11 10:43:26 +01002825bad_param_handler(const wchar_t *expression UNUSED,
2826 const wchar_t *function UNUSED,
2827 const wchar_t *file UNUSED,
2828 unsigned int line UNUSED,
2829 uintptr_t pReserved UNUSED)
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002830{
2831}
2832
2833# define SET_INVALID_PARAM_HANDLER \
2834 ((void)_set_invalid_parameter_handler(bad_param_handler))
2835#else
2836# define SET_INVALID_PARAM_HANDLER
2837#endif
2838
Bram Moolenaar4f974752019-02-17 17:44:42 +01002839#ifdef FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00002840
2841/*
2842 * GUI version of mch_init().
2843 */
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002844 static void
2845mch_init_g(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002846{
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002847# ifndef __MINGW32__
Bram Moolenaar071d4272004-06-13 20:20:40 +00002848 extern int _fmode;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002849# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002850
Bram Moolenaar0f873732019-12-05 20:28:46 +01002851 // Silently handle invalid parameters to CRT functions
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002852 SET_INVALID_PARAM_HANDLER;
2853
Bram Moolenaar0f873732019-12-05 20:28:46 +01002854 // Let critical errors result in a failure, not in a dialog box. Required
2855 // for the timestamp test to work on removed floppies.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002856 SetErrorMode(SEM_FAILCRITICALERRORS);
2857
Bram Moolenaar0f873732019-12-05 20:28:46 +01002858 _fmode = O_BINARY; // we do our own CR-LF translation
Bram Moolenaar071d4272004-06-13 20:20:40 +00002859
Bram Moolenaar0f873732019-12-05 20:28:46 +01002860 // Specify window size. Is there a place to get the default from?
Bram Moolenaar071d4272004-06-13 20:20:40 +00002861 Rows = 25;
2862 Columns = 80;
2863
Bram Moolenaar0f873732019-12-05 20:28:46 +01002864 // Look for 'vimrun'
Bram Moolenaar071d4272004-06-13 20:20:40 +00002865 {
2866 char_u vimrun_location[_MAX_PATH + 4];
2867
Bram Moolenaar0f873732019-12-05 20:28:46 +01002868 // First try in same directory as gvim.exe
Bram Moolenaar071d4272004-06-13 20:20:40 +00002869 STRCPY(vimrun_location, exe_name);
2870 STRCPY(gettail(vimrun_location), "vimrun.exe");
2871 if (mch_getperm(vimrun_location) >= 0)
2872 {
2873 if (*skiptowhite(vimrun_location) != NUL)
2874 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01002875 // Enclose path with white space in double quotes.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002876 mch_memmove(vimrun_location + 1, vimrun_location,
2877 STRLEN(vimrun_location) + 1);
2878 *vimrun_location = '"';
2879 STRCPY(gettail(vimrun_location), "vimrun\" ");
2880 }
2881 else
2882 STRCPY(gettail(vimrun_location), "vimrun ");
2883
2884 vimrun_path = (char *)vim_strsave(vimrun_location);
2885 s_dont_use_vimrun = FALSE;
2886 }
Bram Moolenaar95da1362020-05-30 18:37:55 +02002887 else if (executable_exists("vimrun.exe", NULL, TRUE, FALSE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002888 s_dont_use_vimrun = FALSE;
2889
Bram Moolenaar0f873732019-12-05 20:28:46 +01002890 // Don't give the warning for a missing vimrun.exe right now, but only
2891 // when vimrun was supposed to be used. Don't bother people that do
2892 // not need vimrun.exe.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002893 if (s_dont_use_vimrun)
2894 need_vimrun_warning = TRUE;
2895 }
2896
2897 /*
2898 * If "finstr.exe" doesn't exist, use "grep -n" for 'grepprg'.
2899 * Otherwise the default "findstr /n" is used.
2900 */
Bram Moolenaar95da1362020-05-30 18:37:55 +02002901 if (!executable_exists("findstr.exe", NULL, TRUE, FALSE))
Bram Moolenaar75ab5902022-04-18 15:36:40 +01002902 set_option_value_give_err((char_u *)"grepprg",
2903 0, (char_u *)"grep -n", 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002904
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002905# ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01002906 win_clip_init();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002907# endif
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01002908
2909 vtp_flag_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002910}
2911
2912
Bram Moolenaar0f873732019-12-05 20:28:46 +01002913#endif // FEAT_GUI_MSWIN
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002914
2915#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002916
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002917# define SRWIDTH(sr) ((sr).Right - (sr).Left + 1)
2918# define SRHEIGHT(sr) ((sr).Bottom - (sr).Top + 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002919
2920/*
2921 * ClearConsoleBuffer()
2922 * Description:
2923 * Clears the entire contents of the console screen buffer, using the
2924 * specified attribute.
2925 * Returns:
2926 * TRUE on success
2927 */
2928 static BOOL
2929ClearConsoleBuffer(WORD wAttribute)
2930{
2931 CONSOLE_SCREEN_BUFFER_INFO csbi;
2932 COORD coord;
2933 DWORD NumCells, dummy;
2934
2935 if (!GetConsoleScreenBufferInfo(g_hConOut, &csbi))
2936 return FALSE;
2937
2938 NumCells = csbi.dwSize.X * csbi.dwSize.Y;
2939 coord.X = 0;
2940 coord.Y = 0;
2941 if (!FillConsoleOutputCharacter(g_hConOut, ' ', NumCells,
2942 coord, &dummy))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002943 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002944 if (!FillConsoleOutputAttribute(g_hConOut, wAttribute, NumCells,
2945 coord, &dummy))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002946 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002947
2948 return TRUE;
2949}
2950
2951/*
2952 * FitConsoleWindow()
2953 * Description:
2954 * Checks if the console window will fit within given buffer dimensions.
2955 * Also, if requested, will shrink the window to fit.
2956 * Returns:
2957 * TRUE on success
2958 */
2959 static BOOL
2960FitConsoleWindow(
2961 COORD dwBufferSize,
2962 BOOL WantAdjust)
2963{
2964 CONSOLE_SCREEN_BUFFER_INFO csbi;
2965 COORD dwWindowSize;
2966 BOOL NeedAdjust = FALSE;
2967
2968 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
2969 {
2970 /*
2971 * A buffer resize will fail if the current console window does
2972 * not lie completely within that buffer. To avoid this, we might
2973 * have to move and possibly shrink the window.
2974 */
2975 if (csbi.srWindow.Right >= dwBufferSize.X)
2976 {
2977 dwWindowSize.X = SRWIDTH(csbi.srWindow);
2978 if (dwWindowSize.X > dwBufferSize.X)
2979 dwWindowSize.X = dwBufferSize.X;
2980 csbi.srWindow.Right = dwBufferSize.X - 1;
2981 csbi.srWindow.Left = dwBufferSize.X - dwWindowSize.X;
2982 NeedAdjust = TRUE;
2983 }
2984 if (csbi.srWindow.Bottom >= dwBufferSize.Y)
2985 {
2986 dwWindowSize.Y = SRHEIGHT(csbi.srWindow);
2987 if (dwWindowSize.Y > dwBufferSize.Y)
2988 dwWindowSize.Y = dwBufferSize.Y;
2989 csbi.srWindow.Bottom = dwBufferSize.Y - 1;
2990 csbi.srWindow.Top = dwBufferSize.Y - dwWindowSize.Y;
2991 NeedAdjust = TRUE;
2992 }
2993 if (NeedAdjust && WantAdjust)
2994 {
2995 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &csbi.srWindow))
2996 return FALSE;
2997 }
2998 return TRUE;
2999 }
3000
3001 return FALSE;
3002}
3003
3004typedef struct ConsoleBufferStruct
3005{
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003006 BOOL IsValid;
3007 CONSOLE_SCREEN_BUFFER_INFO Info;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003008 PCHAR_INFO Buffer;
3009 COORD BufferSize;
Bram Moolenaar444fda22017-08-11 20:37:00 +02003010 PSMALL_RECT Regions;
3011 int NumRegions;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003012} ConsoleBuffer;
3013
3014/*
3015 * SaveConsoleBuffer()
3016 * Description:
3017 * Saves important information about the console buffer, including the
3018 * actual buffer contents. The saved information is suitable for later
3019 * restoration by RestoreConsoleBuffer().
3020 * Returns:
3021 * TRUE if all information was saved; FALSE otherwise
3022 * If FALSE, still sets cb->IsValid if buffer characteristics were saved.
3023 */
3024 static BOOL
3025SaveConsoleBuffer(
3026 ConsoleBuffer *cb)
3027{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003028 DWORD NumCells;
3029 COORD BufferCoord;
3030 SMALL_RECT ReadRegion;
3031 WORD Y, Y_incr;
Bram Moolenaar444fda22017-08-11 20:37:00 +02003032 int i, numregions;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003033
Bram Moolenaar071d4272004-06-13 20:20:40 +00003034 if (cb == NULL)
3035 return FALSE;
3036
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003037 if (!GetConsoleScreenBufferInfo(g_hConOut, &cb->Info))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003038 {
3039 cb->IsValid = FALSE;
3040 return FALSE;
3041 }
3042 cb->IsValid = TRUE;
3043
Christopher Plewright1140b512022-11-12 18:46:05 +00003044 // VTP uses alternate screen buffer.
3045 // No need to save buffer contents for restoration.
Christopher Plewrightc8b126d2022-12-22 13:45:23 +00003046 if (use_alternate_screen_buffer)
Christopher Plewright1140b512022-11-12 18:46:05 +00003047 return TRUE;
3048
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003049 /*
3050 * Allocate a buffer large enough to hold the entire console screen
3051 * buffer. If this ConsoleBuffer structure has already been initialized
3052 * with a buffer of the correct size, then just use that one.
3053 */
3054 if (!cb->IsValid || cb->Buffer == NULL ||
3055 cb->BufferSize.X != cb->Info.dwSize.X ||
3056 cb->BufferSize.Y != cb->Info.dwSize.Y)
3057 {
3058 cb->BufferSize.X = cb->Info.dwSize.X;
3059 cb->BufferSize.Y = cb->Info.dwSize.Y;
3060 NumCells = cb->BufferSize.X * cb->BufferSize.Y;
3061 vim_free(cb->Buffer);
Bram Moolenaarc799fe22019-05-28 23:08:19 +02003062 cb->Buffer = ALLOC_MULT(CHAR_INFO, NumCells);
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003063 if (cb->Buffer == NULL)
3064 return FALSE;
3065 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003066
3067 /*
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003068 * We will now copy the console screen buffer into our buffer.
3069 * ReadConsoleOutput() seems to be limited as far as how much you
3070 * can read at a time. Empirically, this number seems to be about
3071 * 12000 cells (rows * columns). Start at position (0, 0) and copy
3072 * in chunks until it is all copied. The chunks will all have the
3073 * same horizontal characteristics, so initialize them now. The
3074 * height of each chunk will be (12000 / width).
Bram Moolenaar071d4272004-06-13 20:20:40 +00003075 */
Bram Moolenaar61594242015-09-01 20:23:37 +02003076 BufferCoord.X = 0;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003077 ReadRegion.Left = 0;
3078 ReadRegion.Right = cb->Info.dwSize.X - 1;
3079 Y_incr = 12000 / cb->Info.dwSize.X;
Bram Moolenaar444fda22017-08-11 20:37:00 +02003080
3081 numregions = (cb->Info.dwSize.Y + Y_incr - 1) / Y_incr;
3082 if (cb->Regions == NULL || numregions != cb->NumRegions)
3083 {
3084 cb->NumRegions = numregions;
3085 vim_free(cb->Regions);
Bram Moolenaarc799fe22019-05-28 23:08:19 +02003086 cb->Regions = ALLOC_MULT(SMALL_RECT, cb->NumRegions);
Bram Moolenaar444fda22017-08-11 20:37:00 +02003087 if (cb->Regions == NULL)
3088 {
Bram Moolenaard23a8232018-02-10 18:45:26 +01003089 VIM_CLEAR(cb->Buffer);
Bram Moolenaar444fda22017-08-11 20:37:00 +02003090 return FALSE;
3091 }
3092 }
3093
3094 for (i = 0, Y = 0; i < cb->NumRegions; i++, Y += Y_incr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003095 {
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003096 /*
3097 * Read into position (0, Y) in our buffer.
3098 */
3099 BufferCoord.Y = Y;
3100 /*
3101 * Read the region whose top left corner is (0, Y) and whose bottom
3102 * right corner is (width - 1, Y + Y_incr - 1). This should define
3103 * a region of size width by Y_incr. Don't worry if this region is
3104 * too large for the remaining buffer; it will be cropped.
3105 */
3106 ReadRegion.Top = Y;
3107 ReadRegion.Bottom = Y + Y_incr - 1;
Bram Moolenaar0f873732019-12-05 20:28:46 +01003108 if (!ReadConsoleOutputW(g_hConOut, // output handle
3109 cb->Buffer, // our buffer
3110 cb->BufferSize, // dimensions of our buffer
3111 BufferCoord, // offset in our buffer
3112 &ReadRegion)) // region to save
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003113 {
Bram Moolenaard23a8232018-02-10 18:45:26 +01003114 VIM_CLEAR(cb->Buffer);
3115 VIM_CLEAR(cb->Regions);
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003116 return FALSE;
3117 }
Bram Moolenaar444fda22017-08-11 20:37:00 +02003118 cb->Regions[i] = ReadRegion;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003119 }
3120
3121 return TRUE;
3122}
3123
3124/*
3125 * RestoreConsoleBuffer()
3126 * Description:
3127 * Restores important information about the console buffer, including the
3128 * actual buffer contents, if desired. The information to restore is in
3129 * the same format used by SaveConsoleBuffer().
3130 * Returns:
3131 * TRUE on success
3132 */
3133 static BOOL
3134RestoreConsoleBuffer(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003135 ConsoleBuffer *cb,
3136 BOOL RestoreScreen)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003137{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003138 COORD BufferCoord;
3139 SMALL_RECT WriteRegion;
Bram Moolenaar444fda22017-08-11 20:37:00 +02003140 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003141
Christopher Plewright1140b512022-11-12 18:46:05 +00003142 // VTP uses alternate screen buffer.
3143 // No need to restore buffer contents.
Christopher Plewrightc8b126d2022-12-22 13:45:23 +00003144 if (use_alternate_screen_buffer)
Christopher Plewright1140b512022-11-12 18:46:05 +00003145 return TRUE;
3146
Bram Moolenaar071d4272004-06-13 20:20:40 +00003147 if (cb == NULL || !cb->IsValid)
3148 return FALSE;
3149
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003150 /*
3151 * Before restoring the buffer contents, clear the current buffer, and
3152 * restore the cursor position and window information. Doing this now
3153 * prevents old buffer contents from "flashing" onto the screen.
3154 */
3155 if (RestoreScreen)
3156 ClearConsoleBuffer(cb->Info.wAttributes);
3157
3158 FitConsoleWindow(cb->Info.dwSize, TRUE);
3159 if (!SetConsoleScreenBufferSize(g_hConOut, cb->Info.dwSize))
3160 return FALSE;
3161 if (!SetConsoleTextAttribute(g_hConOut, cb->Info.wAttributes))
3162 return FALSE;
3163
3164 if (!RestoreScreen)
3165 {
3166 /*
3167 * No need to restore the screen buffer contents, so we're done.
3168 */
3169 return TRUE;
3170 }
3171
3172 if (!SetConsoleCursorPosition(g_hConOut, cb->Info.dwCursorPosition))
3173 return FALSE;
3174 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &cb->Info.srWindow))
3175 return FALSE;
3176
3177 /*
3178 * Restore the screen buffer contents.
3179 */
3180 if (cb->Buffer != NULL)
3181 {
Bram Moolenaar444fda22017-08-11 20:37:00 +02003182 for (i = 0; i < cb->NumRegions; i++)
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003183 {
Bram Moolenaar444fda22017-08-11 20:37:00 +02003184 BufferCoord.X = cb->Regions[i].Left;
3185 BufferCoord.Y = cb->Regions[i].Top;
3186 WriteRegion = cb->Regions[i];
Bram Moolenaar0f873732019-12-05 20:28:46 +01003187 if (!WriteConsoleOutputW(g_hConOut, // output handle
3188 cb->Buffer, // our buffer
3189 cb->BufferSize, // dimensions of our buffer
3190 BufferCoord, // offset in our buffer
3191 &WriteRegion)) // region to restore
Bram Moolenaar444fda22017-08-11 20:37:00 +02003192 return FALSE;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003193 }
3194 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003195
3196 return TRUE;
3197}
3198
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003199# define FEAT_RESTORE_ORIG_SCREEN
3200# ifdef FEAT_RESTORE_ORIG_SCREEN
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003201static ConsoleBuffer g_cbOrig = { 0 };
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003202# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003203static ConsoleBuffer g_cbNonTermcap = { 0 };
3204static ConsoleBuffer g_cbTermcap = { 0 };
3205
Bram Moolenaar071d4272004-06-13 20:20:40 +00003206char g_szOrigTitle[256] = { 0 };
Bram Moolenaar0f873732019-12-05 20:28:46 +01003207HWND g_hWnd = NULL; // also used in os_mswin.c
Bram Moolenaar071d4272004-06-13 20:20:40 +00003208static HICON g_hOrigIconSmall = NULL;
3209static HICON g_hOrigIcon = NULL;
3210static HICON g_hVimIcon = NULL;
3211static BOOL g_fCanChangeIcon = FALSE;
3212
Bram Moolenaar071d4272004-06-13 20:20:40 +00003213/*
3214 * GetConsoleIcon()
3215 * Description:
3216 * Attempts to retrieve the small icon and/or the big icon currently in
3217 * use by a given window.
3218 * Returns:
3219 * TRUE on success
3220 */
3221 static BOOL
3222GetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003223 HWND hWnd,
3224 HICON *phIconSmall,
3225 HICON *phIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003226{
3227 if (hWnd == NULL)
3228 return FALSE;
3229
3230 if (phIconSmall != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003231 *phIconSmall = (HICON)SendMessage(hWnd, WM_GETICON,
3232 (WPARAM)ICON_SMALL, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003233 if (phIcon != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003234 *phIcon = (HICON)SendMessage(hWnd, WM_GETICON,
3235 (WPARAM)ICON_BIG, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003236 return TRUE;
3237}
3238
3239/*
3240 * SetConsoleIcon()
3241 * Description:
3242 * Attempts to change the small icon and/or the big icon currently in
3243 * use by a given window.
3244 * Returns:
3245 * TRUE on success
3246 */
3247 static BOOL
3248SetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003249 HWND hWnd,
3250 HICON hIconSmall,
3251 HICON hIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003252{
Bram Moolenaar071d4272004-06-13 20:20:40 +00003253 if (hWnd == NULL)
3254 return FALSE;
3255
3256 if (hIconSmall != NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003257 SendMessage(hWnd, WM_SETICON,
3258 (WPARAM)ICON_SMALL, (LPARAM)hIconSmall);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003259 if (hIcon != NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003260 SendMessage(hWnd, WM_SETICON,
3261 (WPARAM)ICON_BIG, (LPARAM) hIcon);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003262 return TRUE;
3263}
3264
3265/*
3266 * SaveConsoleTitleAndIcon()
3267 * Description:
3268 * Saves the current console window title in g_szOrigTitle, for later
3269 * restoration. Also, attempts to obtain a handle to the console window,
3270 * and use it to save the small and big icons currently in use by the
3271 * console window. This is not always possible on some versions of Windows;
3272 * nor is it possible when running Vim remotely using Telnet (since the
3273 * console window the user sees is owned by a remote process).
3274 */
3275 static void
3276SaveConsoleTitleAndIcon(void)
3277{
Bram Moolenaar0f873732019-12-05 20:28:46 +01003278 // Save the original title.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003279 if (!GetConsoleTitle(g_szOrigTitle, sizeof(g_szOrigTitle)))
3280 return;
3281
3282 /*
3283 * Obtain a handle to the console window using GetConsoleWindow() from
3284 * KERNEL32.DLL; we need to handle in order to change the window icon.
3285 * This function only exists on NT-based Windows, starting with Windows
3286 * 2000. On older operating systems, we can't change the window icon
3287 * anyway.
3288 */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003289 g_hWnd = GetConsoleWindow();
Bram Moolenaar071d4272004-06-13 20:20:40 +00003290 if (g_hWnd == NULL)
3291 return;
3292
Bram Moolenaar0f873732019-12-05 20:28:46 +01003293 // Save the original console window icon.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003294 GetConsoleIcon(g_hWnd, &g_hOrigIconSmall, &g_hOrigIcon);
3295 if (g_hOrigIconSmall == NULL || g_hOrigIcon == NULL)
3296 return;
3297
Bram Moolenaar0f873732019-12-05 20:28:46 +01003298 // Extract the first icon contained in the Vim executable.
K.Takata2da11a42022-09-10 13:03:12 +01003299 if (
3300# ifdef FEAT_LIBCALL
3301 mch_icon_load((HANDLE *)&g_hVimIcon) == FAIL ||
3302# endif
3303 g_hVimIcon == NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003304 g_hVimIcon = ExtractIcon(NULL, (LPCSTR)exe_name, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003305 if (g_hVimIcon != NULL)
3306 g_fCanChangeIcon = TRUE;
3307}
Bram Moolenaar071d4272004-06-13 20:20:40 +00003308
3309static int g_fWindInitCalled = FALSE;
3310static int g_fTermcapMode = FALSE;
3311static CONSOLE_CURSOR_INFO g_cci;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003312
3313/*
3314 * non-GUI version of mch_init().
3315 */
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003316 static void
3317mch_init_c(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003318{
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003319# ifndef FEAT_RESTORE_ORIG_SCREEN
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003320 CONSOLE_SCREEN_BUFFER_INFO csbi;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003321# endif
3322# ifndef __MINGW32__
Bram Moolenaar071d4272004-06-13 20:20:40 +00003323 extern int _fmode;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003324# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003325
Bram Moolenaar0f873732019-12-05 20:28:46 +01003326 // Silently handle invalid parameters to CRT functions
Bram Moolenaard32a99a2010-09-21 17:29:23 +02003327 SET_INVALID_PARAM_HANDLER;
3328
Bram Moolenaar0f873732019-12-05 20:28:46 +01003329 // Let critical errors result in a failure, not in a dialog box. Required
3330 // for the timestamp test to work on removed floppies.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003331 SetErrorMode(SEM_FAILCRITICALERRORS);
3332
Bram Moolenaar0f873732019-12-05 20:28:46 +01003333 _fmode = O_BINARY; // we do our own CR-LF translation
Bram Moolenaar071d4272004-06-13 20:20:40 +00003334 out_flush();
3335
Bram Moolenaar0f873732019-12-05 20:28:46 +01003336 // Obtain handles for the standard Console I/O devices
Bram Moolenaar071d4272004-06-13 20:20:40 +00003337 if (read_cmd_fd == 0)
3338 g_hConIn = GetStdHandle(STD_INPUT_HANDLE);
3339 else
3340 create_conin();
3341 g_hConOut = GetStdHandle(STD_OUTPUT_HANDLE);
3342
Christopher Plewright38804d62022-11-09 23:55:52 +00003343 wt_init();
3344 vtp_flag_init();
3345 vtp_init();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003346# ifdef FEAT_RESTORE_ORIG_SCREEN
Bram Moolenaar0f873732019-12-05 20:28:46 +01003347 // Save the initial console buffer for later restoration
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003348 SaveConsoleBuffer(&g_cbOrig);
3349 g_attrCurrent = g_attrDefault = g_cbOrig.Info.wAttributes;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003350# else
Bram Moolenaar0f873732019-12-05 20:28:46 +01003351 // Get current text attributes
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003352 GetConsoleScreenBufferInfo(g_hConOut, &csbi);
3353 g_attrCurrent = g_attrDefault = csbi.wAttributes;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003354# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003355 if (cterm_normal_fg_color == 0)
3356 cterm_normal_fg_color = (g_attrCurrent & 0xf) + 1;
3357 if (cterm_normal_bg_color == 0)
3358 cterm_normal_bg_color = ((g_attrCurrent >> 4) & 0xf) + 1;
3359
Bram Moolenaarbdace832019-03-02 10:13:42 +01003360 // Fg and Bg color index number at startup
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02003361 g_color_index_fg = g_attrDefault & 0xf;
3362 g_color_index_bg = (g_attrDefault >> 4) & 0xf;
3363
Bram Moolenaar0f873732019-12-05 20:28:46 +01003364 // set termcap codes to current text attributes
Bram Moolenaar071d4272004-06-13 20:20:40 +00003365 update_tcap(g_attrCurrent);
3366
3367 GetConsoleCursorInfo(g_hConOut, &g_cci);
3368 GetConsoleMode(g_hConIn, &g_cmodein);
3369 GetConsoleMode(g_hConOut, &g_cmodeout);
3370
Bram Moolenaar071d4272004-06-13 20:20:40 +00003371 SaveConsoleTitleAndIcon();
3372 /*
3373 * Set both the small and big icons of the console window to Vim's icon.
3374 * Note that Vim presently only has one size of icon (32x32), but it
3375 * automatically gets scaled down to 16x16 when setting the small icon.
3376 */
3377 if (g_fCanChangeIcon)
3378 SetConsoleIcon(g_hWnd, g_hVimIcon, g_hVimIcon);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003379
3380 ui_get_shellsize();
3381
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003382# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00003383 fdDump = fopen("dump", "wt");
3384
3385 if (fdDump)
3386 {
3387 time_t t;
3388
3389 time(&t);
3390 fputs(ctime(&t), fdDump);
3391 fflush(fdDump);
3392 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003393# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003394
3395 g_fWindInitCalled = TRUE;
3396
Bram Moolenaar071d4272004-06-13 20:20:40 +00003397 g_fMouseAvail = GetSystemMetrics(SM_MOUSEPRESENT);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003398
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003399# ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01003400 win_clip_init();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003401# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003402}
3403
3404/*
3405 * non-GUI version of mch_exit().
3406 * Shut down and exit with status `r'
3407 * Careful: mch_exit() may be called before mch_init()!
3408 */
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003409 static void
3410mch_exit_c(int r)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003411{
Bram Moolenaar955f1982017-02-05 15:10:51 +01003412 exiting = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003413
Bram Moolenaarcafafb32018-02-22 21:07:09 +01003414 vtp_exit();
3415
Bram Moolenaar955f1982017-02-05 15:10:51 +01003416 stoptermcap();
Bram Moolenaar071d4272004-06-13 20:20:40 +00003417 if (g_fWindInitCalled)
3418 settmode(TMODE_COOK);
3419
Bram Moolenaar0f873732019-12-05 20:28:46 +01003420 ml_close_all(TRUE); // remove all memfiles
Bram Moolenaar071d4272004-06-13 20:20:40 +00003421
3422 if (g_fWindInitCalled)
3423 {
Bram Moolenaar40385db2018-08-07 22:31:44 +02003424 mch_restore_title(SAVE_RESTORE_BOTH);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003425 /*
3426 * Restore both the small and big icons of the console window to
3427 * what they were at startup. Don't do this when the window is
3428 * closed, Vim would hang here.
3429 */
3430 if (g_fCanChangeIcon && !g_fForceExit)
3431 SetConsoleIcon(g_hWnd, g_hOrigIconSmall, g_hOrigIcon);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003432
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003433# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00003434 if (fdDump)
3435 {
3436 time_t t;
3437
3438 time(&t);
3439 fputs(ctime(&t), fdDump);
3440 fclose(fdDump);
3441 }
3442 fdDump = NULL;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003443# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003444 }
3445
3446 SetConsoleCursorInfo(g_hConOut, &g_cci);
Wez Furlong6ef5ab52021-05-30 19:29:41 +02003447 SetConsoleMode(g_hConIn, g_cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003448 SetConsoleMode(g_hConOut, g_cmodeout);
3449
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003450# ifdef DYNAMIC_GETTEXT
Bram Moolenaar071d4272004-06-13 20:20:40 +00003451 dyn_libintl_end();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003452# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003453
3454 exit(r);
3455}
Bram Moolenaar0f873732019-12-05 20:28:46 +01003456#endif // !FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00003457
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003458 void
3459mch_init(void)
3460{
3461#ifdef VIMDLL
3462 if (gui.starting)
3463 mch_init_g();
3464 else
3465 mch_init_c();
3466#elif defined(FEAT_GUI_MSWIN)
3467 mch_init_g();
3468#else
3469 mch_init_c();
3470#endif
3471}
3472
3473 void
3474mch_exit(int r)
3475{
Bram Moolenaar173d8412020-04-19 14:02:26 +02003476#ifdef FEAT_NETBEANS_INTG
3477 netbeans_send_disconnect();
3478#endif
3479
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003480#ifdef VIMDLL
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02003481 if (gui.in_use || gui.starting)
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003482 mch_exit_g(r);
3483 else
3484 mch_exit_c(r);
3485#elif defined(FEAT_GUI_MSWIN)
3486 mch_exit_g(r);
3487#else
3488 mch_exit_c(r);
3489#endif
3490}
3491
Bram Moolenaar071d4272004-06-13 20:20:40 +00003492/*
3493 * Do we have an interactive window?
3494 */
3495 int
3496mch_check_win(
Bram Moolenaar1266d672017-02-01 13:43:36 +01003497 int argc UNUSED,
3498 char **argv UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003499{
3500 get_exe_name();
3501
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003502#if defined(FEAT_GUI_MSWIN) && !defined(VIMDLL)
Bram Moolenaar0f873732019-12-05 20:28:46 +01003503 return OK; // GUI always has a tty
Bram Moolenaar071d4272004-06-13 20:20:40 +00003504#else
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003505# ifdef VIMDLL
3506 if (gui.in_use)
3507 return OK;
3508# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003509 if (isatty(1))
3510 return OK;
3511 return FAIL;
3512#endif
3513}
3514
Bram Moolenaar65f04f62013-08-30 17:29:16 +02003515/*
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003516 * Set the case of the file name, if it already exists.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003517 * When "len" is > 0, also expand short to long filenames.
3518 */
3519 void
3520fname_case(
3521 char_u *name,
3522 int len)
3523{
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003524 int flen;
3525 WCHAR *p;
3526 WCHAR buf[_MAX_PATH + 1];
Bram Moolenaar071d4272004-06-13 20:20:40 +00003527
Bram Moolenaara3ffd9c2005-07-21 21:03:15 +00003528 flen = (int)STRLEN(name);
Bram Moolenaar65f04f62013-08-30 17:29:16 +02003529 if (flen == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003530 return;
3531
3532 slash_adjust(name);
3533
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003534 p = enc_to_utf16(name, NULL);
3535 if (p == NULL)
Bram Moolenaar65f04f62013-08-30 17:29:16 +02003536 return;
3537
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003538 if (GetLongPathNameW(p, buf, _MAX_PATH))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003539 {
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003540 char_u *q = utf16_to_enc(buf, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003541
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003542 if (q != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003543 {
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003544 if (len > 0 || flen >= (int)STRLEN(q))
3545 vim_strncpy(name, q, (len > 0) ? len - 1 : flen);
3546 vim_free(q);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003547 }
3548 }
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003549 vim_free(p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003550}
3551
3552
3553/*
3554 * Insert user name in s[len].
3555 */
3556 int
3557mch_get_user_name(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003558 char_u *s,
3559 int len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003560{
Bram Moolenaar0f873732019-12-05 20:28:46 +01003561 WCHAR wszUserName[256 + 1]; // UNLEN is 256
K.Takataeeec2542021-06-02 13:28:16 +02003562 DWORD wcch = ARRAY_LENGTH(wszUserName);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003563
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003564 if (GetUserNameW(wszUserName, &wcch))
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003565 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003566 char_u *p = utf16_to_enc(wszUserName, NULL);
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003567
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003568 if (p != NULL)
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003569 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003570 vim_strncpy(s, p, len - 1);
3571 vim_free(p);
3572 return OK;
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003573 }
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003574 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003575 s[0] = NUL;
3576 return FAIL;
3577}
3578
3579
3580/*
3581 * Insert host name in s[len].
3582 */
3583 void
3584mch_get_host_name(
3585 char_u *s,
3586 int len)
3587{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003588 WCHAR wszHostName[256 + 1];
K.Takataeeec2542021-06-02 13:28:16 +02003589 DWORD wcch = ARRAY_LENGTH(wszHostName);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003590
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003591 if (GetComputerNameW(wszHostName, &wcch))
Bram Moolenaar2cc87382013-12-11 18:21:45 +01003592 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003593 char_u *p = utf16_to_enc(wszHostName, NULL);
Bram Moolenaar2cc87382013-12-11 18:21:45 +01003594
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003595 if (p != NULL)
Bram Moolenaar2cc87382013-12-11 18:21:45 +01003596 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003597 vim_strncpy(s, p, len - 1);
3598 vim_free(p);
3599 return;
Bram Moolenaar2cc87382013-12-11 18:21:45 +01003600 }
Bram Moolenaar2cc87382013-12-11 18:21:45 +01003601 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003602}
3603
3604
3605/*
3606 * return process ID
3607 */
3608 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003609mch_get_pid(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003610{
3611 return (long)GetCurrentProcessId();
3612}
3613
Bram Moolenaar67cf86b2019-04-28 22:25:38 +02003614/*
3615 * return TRUE if process "pid" is still running
3616 */
3617 int
Bram Moolenaar1b243ea2019-04-28 22:50:40 +02003618mch_process_running(long pid)
Bram Moolenaar67cf86b2019-04-28 22:25:38 +02003619{
3620 HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION, 0, (DWORD)pid);
3621 DWORD status = 0;
3622 int ret = FALSE;
3623
3624 if (hProcess == NULL)
3625 return FALSE; // might not have access
3626 if (GetExitCodeProcess(hProcess, &status) )
3627 ret = status == STILL_ACTIVE;
3628 CloseHandle(hProcess);
3629 return ret;
3630}
Bram Moolenaar071d4272004-06-13 20:20:40 +00003631
3632/*
3633 * Get name of current directory into buffer 'buf' of length 'len' bytes.
3634 * Return OK for success, FAIL for failure.
3635 */
3636 int
3637mch_dirname(
3638 char_u *buf,
3639 int len)
3640{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003641 WCHAR wbuf[_MAX_PATH + 1];
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02003642
Bram Moolenaar071d4272004-06-13 20:20:40 +00003643 /*
3644 * Originally this was:
3645 * return (getcwd(buf, len) != NULL ? OK : FAIL);
3646 * But the Win32s known bug list says that getcwd() doesn't work
3647 * so use the Win32 system call instead. <Negri>
3648 */
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003649 if (GetCurrentDirectoryW(_MAX_PATH, wbuf) != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003650 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003651 WCHAR wcbuf[_MAX_PATH + 1];
3652 char_u *p = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003653
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003654 if (GetLongPathNameW(wbuf, wcbuf, _MAX_PATH) != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003655 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003656 p = utf16_to_enc(wcbuf, NULL);
3657 if (STRLEN(p) >= (size_t)len)
Bram Moolenaarcea1f9e2018-08-19 14:38:42 +02003658 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003659 // long path name is too long, fall back to short one
Bram Moolenaar071d4272004-06-13 20:20:40 +00003660 vim_free(p);
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003661 p = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003662 }
3663 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003664 if (p == NULL)
3665 p = utf16_to_enc(wbuf, NULL);
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02003666
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003667 if (p != NULL)
3668 {
3669 vim_strncpy(buf, p, len - 1);
3670 vim_free(p);
3671 return OK;
3672 }
3673 }
3674 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003675}
3676
3677/*
Bram Moolenaarffa22202013-11-21 12:34:11 +01003678 * Get file permissions for "name".
3679 * Return mode_t or -1 for error.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003680 */
3681 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003682mch_getperm(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003683{
Bram Moolenaar8767f522016-07-01 17:17:39 +02003684 stat_T st;
Bram Moolenaarffa22202013-11-21 12:34:11 +01003685 int n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003686
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003687 n = mch_stat((char *)name, &st);
Bram Moolenaar78cf3f02014-01-10 18:16:07 +01003688 return n == 0 ? (long)(unsigned short)st.st_mode : -1L;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003689}
3690
3691
3692/*
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003693 * Set file permission for "name" to "perm".
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003694 *
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003695 * Return FAIL for failure, OK otherwise.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003696 */
3697 int
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003698mch_setperm(char_u *name, long perm)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003699{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003700 long n;
3701 WCHAR *p;
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003702
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003703 p = enc_to_utf16(name, NULL);
3704 if (p == NULL)
3705 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003706
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003707 n = _wchmod(p, perm);
3708 vim_free(p);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003709 if (n == -1)
3710 return FAIL;
3711
3712 win32_set_archive(name);
3713
3714 return OK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003715}
3716
3717/*
3718 * Set hidden flag for "name".
3719 */
3720 void
3721mch_hide(char_u *name)
3722{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003723 int attrs = win32_getattrs(name);
3724 if (attrs == -1)
3725 return;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003726
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003727 attrs |= FILE_ATTRIBUTE_HIDDEN;
3728 win32_setattrs(name, attrs);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003729}
3730
3731/*
Bram Moolenaar8a52ba72015-11-02 14:45:56 +01003732 * Return TRUE if file "name" exists and is hidden.
3733 */
3734 int
3735mch_ishidden(char_u *name)
3736{
3737 int f = win32_getattrs(name);
3738
3739 if (f == -1)
Bram Moolenaar0f873732019-12-05 20:28:46 +01003740 return FALSE; // file does not exist at all
Bram Moolenaar8a52ba72015-11-02 14:45:56 +01003741
3742 return (f & FILE_ATTRIBUTE_HIDDEN) != 0;
3743}
3744
3745/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003746 * return TRUE if "name" is a directory
3747 * return FALSE if "name" is not a directory or upon error
3748 */
3749 int
3750mch_isdir(char_u *name)
3751{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003752 int f = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003753
3754 if (f == -1)
Bram Moolenaar0f873732019-12-05 20:28:46 +01003755 return FALSE; // file does not exist at all
Bram Moolenaar071d4272004-06-13 20:20:40 +00003756
3757 return (f & FILE_ATTRIBUTE_DIRECTORY) != 0;
3758}
3759
3760/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01003761 * return TRUE if "name" is a directory, NOT a symlink to a directory
3762 * return FALSE if "name" is not a directory
3763 * return FALSE for error
3764 */
3765 int
3766mch_isrealdir(char_u *name)
3767{
3768 return mch_isdir(name) && !mch_is_symbolic_link(name);
3769}
3770
3771/*
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003772 * Create directory "name".
3773 * Return 0 on success, -1 on error.
3774 */
3775 int
3776mch_mkdir(char_u *name)
3777{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003778 WCHAR *p;
3779 int retval;
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003780
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003781 p = enc_to_utf16(name, NULL);
3782 if (p == NULL)
3783 return -1;
3784 retval = _wmkdir(p);
3785 vim_free(p);
3786 return retval;
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003787}
3788
3789/*
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003790 * Delete directory "name".
3791 * Return 0 on success, -1 on error.
3792 */
3793 int
3794mch_rmdir(char_u *name)
3795{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003796 WCHAR *p;
3797 int retval;
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003798
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003799 p = enc_to_utf16(name, NULL);
3800 if (p == NULL)
3801 return -1;
3802 retval = _wrmdir(p);
3803 vim_free(p);
3804 return retval;
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003805}
3806
3807/*
Bram Moolenaar03f48552006-02-28 23:52:23 +00003808 * Return TRUE if file "fname" has more than one link.
3809 */
3810 int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003811mch_is_hard_link(char_u *fname)
Bram Moolenaar03f48552006-02-28 23:52:23 +00003812{
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003813 BY_HANDLE_FILE_INFORMATION info;
3814
3815 return win32_fileinfo(fname, &info) == FILEINFO_OK
3816 && info.nNumberOfLinks > 1;
3817}
3818
3819/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01003820 * Return TRUE if "name" is a symbolic link (or a junction).
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003821 */
3822 int
Bram Moolenaar203258c2016-01-17 22:15:16 +01003823mch_is_symbolic_link(char_u *name)
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003824{
3825 HANDLE hFind;
3826 int res = FALSE;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003827 DWORD fileFlags = 0, reparseTag = 0;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003828 WCHAR *wn;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003829 WIN32_FIND_DATAW findDataW;
3830
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003831 wn = enc_to_utf16(name, NULL);
3832 if (wn == NULL)
3833 return FALSE;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003834
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003835 hFind = FindFirstFileW(wn, &findDataW);
3836 vim_free(wn);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003837 if (hFind != INVALID_HANDLE_VALUE)
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003838 {
3839 fileFlags = findDataW.dwFileAttributes;
3840 reparseTag = findDataW.dwReserved0;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003841 FindClose(hFind);
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003842 }
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003843
3844 if ((fileFlags & FILE_ATTRIBUTE_REPARSE_POINT)
Bram Moolenaar203258c2016-01-17 22:15:16 +01003845 && (reparseTag == IO_REPARSE_TAG_SYMLINK
3846 || reparseTag == IO_REPARSE_TAG_MOUNT_POINT))
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003847 res = TRUE;
3848
3849 return res;
3850}
3851
3852/*
3853 * Return TRUE if file "fname" has more than one link or if it is a symbolic
3854 * link.
3855 */
3856 int
3857mch_is_linked(char_u *fname)
3858{
3859 if (mch_is_hard_link(fname) || mch_is_symbolic_link(fname))
3860 return TRUE;
3861 return FALSE;
3862}
3863
3864/*
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003865 * Get the by-handle-file-information for "fname".
3866 * Returns FILEINFO_OK when OK.
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003867 * Returns FILEINFO_ENC_FAIL when enc_to_utf16() failed.
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003868 * Returns FILEINFO_READ_FAIL when CreateFile() failed.
3869 * Returns FILEINFO_INFO_FAIL when GetFileInformationByHandle() failed.
3870 */
3871 int
3872win32_fileinfo(char_u *fname, BY_HANDLE_FILE_INFORMATION *info)
3873{
Bram Moolenaar03f48552006-02-28 23:52:23 +00003874 HANDLE hFile;
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003875 int res = FILEINFO_READ_FAIL;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003876 WCHAR *wn;
Bram Moolenaar03f48552006-02-28 23:52:23 +00003877
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003878 wn = enc_to_utf16(fname, NULL);
3879 if (wn == NULL)
3880 return FILEINFO_ENC_FAIL;
3881
3882 hFile = CreateFileW(wn, // file name
3883 GENERIC_READ, // access mode
3884 FILE_SHARE_READ | FILE_SHARE_WRITE, // share mode
3885 NULL, // security descriptor
3886 OPEN_EXISTING, // creation disposition
3887 FILE_FLAG_BACKUP_SEMANTICS, // file attributes
3888 NULL); // handle to template file
3889 vim_free(wn);
Bram Moolenaar03f48552006-02-28 23:52:23 +00003890
3891 if (hFile != INVALID_HANDLE_VALUE)
3892 {
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003893 if (GetFileInformationByHandle(hFile, info) != 0)
3894 res = FILEINFO_OK;
3895 else
3896 res = FILEINFO_INFO_FAIL;
Bram Moolenaar03f48552006-02-28 23:52:23 +00003897 CloseHandle(hFile);
3898 }
3899
Bram Moolenaar03f48552006-02-28 23:52:23 +00003900 return res;
3901}
3902
3903/*
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003904 * get file attributes for `name'
3905 * -1 : error
3906 * else FILE_ATTRIBUTE_* defined in winnt.h
3907 */
Bram Moolenaarffa22202013-11-21 12:34:11 +01003908 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003909win32_getattrs(char_u *name)
3910{
3911 int attr;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003912 WCHAR *p;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003913
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003914 p = enc_to_utf16(name, NULL);
3915 if (p == NULL)
3916 return INVALID_FILE_ATTRIBUTES;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003917
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003918 attr = GetFileAttributesW(p);
3919 vim_free(p);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003920
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003921 return attr;
3922}
3923
3924/*
3925 * set file attributes for `name' to `attrs'
3926 *
3927 * return -1 for failure, 0 otherwise
3928 */
Bram Moolenaar6dff58f2018-09-30 21:43:26 +02003929 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003930win32_setattrs(char_u *name, int attrs)
3931{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003932 int res;
3933 WCHAR *p;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003934
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003935 p = enc_to_utf16(name, NULL);
3936 if (p == NULL)
3937 return -1;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003938
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003939 res = SetFileAttributesW(p, attrs);
3940 vim_free(p);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003941
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003942 return res ? 0 : -1;
3943}
3944
3945/*
3946 * Set archive flag for "name".
3947 */
Bram Moolenaar6dff58f2018-09-30 21:43:26 +02003948 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003949win32_set_archive(char_u *name)
3950{
3951 int attrs = win32_getattrs(name);
3952 if (attrs == -1)
3953 return -1;
3954
3955 attrs |= FILE_ATTRIBUTE_ARCHIVE;
3956 return win32_setattrs(name, attrs);
3957}
3958
3959/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003960 * Return TRUE if file or directory "name" is writable (not readonly).
3961 * Strange semantics of Win32: a readonly directory is writable, but you can't
3962 * delete a file. Let's say this means it is writable.
3963 */
3964 int
3965mch_writable(char_u *name)
3966{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003967 int attrs = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003968
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003969 return (attrs != -1 && (!(attrs & FILE_ATTRIBUTE_READONLY)
3970 || (attrs & FILE_ATTRIBUTE_DIRECTORY)));
Bram Moolenaar071d4272004-06-13 20:20:40 +00003971}
3972
Bram Moolenaar071d4272004-06-13 20:20:40 +00003973/*
Bram Moolenaar43663192017-03-05 14:29:12 +01003974 * Return TRUE if "name" can be executed, FALSE if not.
Bram Moolenaar77b77102015-03-21 22:18:41 +01003975 * If "use_path" is FALSE only check if "name" is executable.
Bram Moolenaar43663192017-03-05 14:29:12 +01003976 * When returning TRUE and "path" is not NULL save the path and set "*path" to
3977 * the allocated memory.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003978 */
3979 int
Yegappan Lakshmananebb01bd2022-06-08 15:14:09 +01003980mch_can_exe(char_u *name, char_u **path, int use_path UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003981{
Bram Moolenaar95da1362020-05-30 18:37:55 +02003982 return executable_exists((char *)name, path, TRUE, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003983}
Bram Moolenaar071d4272004-06-13 20:20:40 +00003984
3985/*
3986 * Check what "name" is:
3987 * NODE_NORMAL: file or directory (or doesn't exist)
3988 * NODE_WRITABLE: writable device, socket, fifo, etc.
3989 * NODE_OTHER: non-writable things
3990 */
3991 int
3992mch_nodetype(char_u *name)
3993{
3994 HANDLE hFile;
3995 int type;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003996 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003997
Bram Moolenaar0f873732019-12-05 20:28:46 +01003998 // We can't open a file with a name "\\.\con" or "\\.\prn" and trying to
3999 // read from it later will cause Vim to hang. Thus return NODE_WRITABLE
4000 // here.
Bram Moolenaar043545e2006-10-10 16:44:07 +00004001 if (STRNCMP(name, "\\\\.\\", 4) == 0)
4002 return NODE_WRITABLE;
4003
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004004 wn = enc_to_utf16(name, NULL);
4005 if (wn == NULL)
4006 return NODE_NORMAL;
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004007
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004008 hFile = CreateFileW(wn, // file name
4009 GENERIC_WRITE, // access mode
4010 0, // share mode
4011 NULL, // security descriptor
4012 OPEN_EXISTING, // creation disposition
4013 0, // file attributes
4014 NULL); // handle to template file
4015 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004016 if (hFile == INVALID_HANDLE_VALUE)
4017 return NODE_NORMAL;
4018
4019 type = GetFileType(hFile);
4020 CloseHandle(hFile);
4021 if (type == FILE_TYPE_CHAR)
4022 return NODE_WRITABLE;
4023 if (type == FILE_TYPE_DISK)
4024 return NODE_NORMAL;
4025 return NODE_OTHER;
4026}
4027
4028#ifdef HAVE_ACL
4029struct my_acl
4030{
4031 PSECURITY_DESCRIPTOR pSecurityDescriptor;
4032 PSID pSidOwner;
4033 PSID pSidGroup;
4034 PACL pDacl;
4035 PACL pSacl;
4036};
4037#endif
4038
4039/*
4040 * Return a pointer to the ACL of file "fname" in allocated memory.
4041 * Return NULL if the ACL is not available for whatever reason.
4042 */
4043 vim_acl_T
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004044mch_get_acl(char_u *fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004045{
4046#ifndef HAVE_ACL
4047 return (vim_acl_T)NULL;
4048#else
4049 struct my_acl *p = NULL;
Bram Moolenaar27515922013-06-29 15:36:26 +02004050 DWORD err;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004051
Bram Moolenaarc799fe22019-05-28 23:08:19 +02004052 p = ALLOC_CLEAR_ONE(struct my_acl);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004053 if (p != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004054 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004055 WCHAR *wn;
Bram Moolenaar27515922013-06-29 15:36:26 +02004056
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004057 wn = enc_to_utf16(fname, NULL);
4058 if (wn == NULL)
Bram Moolenaarbbf9f342020-11-10 22:03:40 +01004059 {
4060 vim_free(p);
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004061 return NULL;
Bram Moolenaarbbf9f342020-11-10 22:03:40 +01004062 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004063
4064 // Try to retrieve the entire security descriptor.
4065 err = GetNamedSecurityInfoW(
4066 wn, // Abstract filename
4067 SE_FILE_OBJECT, // File Object
4068 OWNER_SECURITY_INFORMATION |
4069 GROUP_SECURITY_INFORMATION |
4070 DACL_SECURITY_INFORMATION |
4071 SACL_SECURITY_INFORMATION,
4072 &p->pSidOwner, // Ownership information.
4073 &p->pSidGroup, // Group membership.
4074 &p->pDacl, // Discretionary information.
4075 &p->pSacl, // For auditing purposes.
4076 &p->pSecurityDescriptor);
4077 if (err == ERROR_ACCESS_DENIED ||
4078 err == ERROR_PRIVILEGE_NOT_HELD)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004079 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004080 // Retrieve only DACL.
4081 (void)GetNamedSecurityInfoW(
4082 wn,
4083 SE_FILE_OBJECT,
4084 DACL_SECURITY_INFORMATION,
4085 NULL,
4086 NULL,
4087 &p->pDacl,
4088 NULL,
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004089 &p->pSecurityDescriptor);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004090 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004091 if (p->pSecurityDescriptor == NULL)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004092 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004093 mch_free_acl((vim_acl_T)p);
4094 p = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004095 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004096 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004097 }
4098
4099 return (vim_acl_T)p;
4100#endif
4101}
4102
Bram Moolenaar27515922013-06-29 15:36:26 +02004103#ifdef HAVE_ACL
4104/*
4105 * Check if "acl" contains inherited ACE.
4106 */
4107 static BOOL
4108is_acl_inherited(PACL acl)
4109{
4110 DWORD i;
4111 ACL_SIZE_INFORMATION acl_info;
4112 PACCESS_ALLOWED_ACE ace;
4113
4114 acl_info.AceCount = 0;
4115 GetAclInformation(acl, &acl_info, sizeof(acl_info), AclSizeInformation);
4116 for (i = 0; i < acl_info.AceCount; i++)
4117 {
4118 GetAce(acl, i, (LPVOID *)&ace);
4119 if (ace->Header.AceFlags & INHERITED_ACE)
4120 return TRUE;
4121 }
4122 return FALSE;
4123}
4124#endif
4125
Bram Moolenaar071d4272004-06-13 20:20:40 +00004126/*
4127 * Set the ACL of file "fname" to "acl" (unless it's NULL).
4128 * Errors are ignored.
4129 * This must only be called with "acl" equal to what mch_get_acl() returned.
4130 */
4131 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004132mch_set_acl(char_u *fname, vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004133{
4134#ifdef HAVE_ACL
4135 struct my_acl *p = (struct my_acl *)acl;
Bram Moolenaar27515922013-06-29 15:36:26 +02004136 SECURITY_INFORMATION sec_info = 0;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004137 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004138
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004139 if (p == NULL)
4140 return;
4141
4142 wn = enc_to_utf16(fname, NULL);
4143 if (wn == NULL)
4144 return;
4145
4146 // Set security flags
4147 if (p->pSidOwner)
4148 sec_info |= OWNER_SECURITY_INFORMATION;
4149 if (p->pSidGroup)
4150 sec_info |= GROUP_SECURITY_INFORMATION;
4151 if (p->pDacl)
Bram Moolenaar27515922013-06-29 15:36:26 +02004152 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004153 sec_info |= DACL_SECURITY_INFORMATION;
4154 // Do not inherit its parent's DACL.
4155 // If the DACL is inherited, Cygwin permissions would be changed.
4156 if (!is_acl_inherited(p->pDacl))
4157 sec_info |= PROTECTED_DACL_SECURITY_INFORMATION;
Bram Moolenaar27515922013-06-29 15:36:26 +02004158 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004159 if (p->pSacl)
4160 sec_info |= SACL_SECURITY_INFORMATION;
4161
4162 (void)SetNamedSecurityInfoW(
4163 wn, // Abstract filename
4164 SE_FILE_OBJECT, // File Object
4165 sec_info,
4166 p->pSidOwner, // Ownership information.
4167 p->pSidGroup, // Group membership.
4168 p->pDacl, // Discretionary information.
4169 p->pSacl // For auditing purposes.
4170 );
4171 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004172#endif
4173}
4174
4175 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004176mch_free_acl(vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004177{
4178#ifdef HAVE_ACL
4179 struct my_acl *p = (struct my_acl *)acl;
4180
4181 if (p != NULL)
4182 {
4183 LocalFree(p->pSecurityDescriptor); // Free the memory just in case
4184 vim_free(p);
4185 }
4186#endif
4187}
4188
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004189#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004190
4191/*
4192 * handler for ctrl-break, ctrl-c interrupts, and fatal events.
4193 */
4194 static BOOL WINAPI
4195handler_routine(
4196 DWORD dwCtrlType)
4197{
Bram Moolenaar589b1102017-08-12 16:39:05 +02004198 INPUT_RECORD ir;
4199 DWORD out;
4200
Bram Moolenaar071d4272004-06-13 20:20:40 +00004201 switch (dwCtrlType)
4202 {
4203 case CTRL_C_EVENT:
4204 if (ctrl_c_interrupts)
4205 g_fCtrlCPressed = TRUE;
4206 return TRUE;
4207
4208 case CTRL_BREAK_EVENT:
4209 g_fCBrkPressed = TRUE;
Bram Moolenaar589b1102017-08-12 16:39:05 +02004210 ctrl_break_was_pressed = TRUE;
Bram Moolenaar0f873732019-12-05 20:28:46 +01004211 // ReadConsoleInput is blocking, send a key event to continue.
Bram Moolenaar589b1102017-08-12 16:39:05 +02004212 ir.EventType = KEY_EVENT;
4213 ir.Event.KeyEvent.bKeyDown = TRUE;
4214 ir.Event.KeyEvent.wRepeatCount = 1;
4215 ir.Event.KeyEvent.wVirtualKeyCode = VK_CANCEL;
4216 ir.Event.KeyEvent.wVirtualScanCode = 0;
4217 ir.Event.KeyEvent.dwControlKeyState = 0;
4218 ir.Event.KeyEvent.uChar.UnicodeChar = 0;
4219 WriteConsoleInput(g_hConIn, &ir, 1, &out);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004220 return TRUE;
4221
Bram Moolenaar0f873732019-12-05 20:28:46 +01004222 // fatal events: shut down gracefully
Bram Moolenaar071d4272004-06-13 20:20:40 +00004223 case CTRL_CLOSE_EVENT:
4224 case CTRL_LOGOFF_EVENT:
4225 case CTRL_SHUTDOWN_EVENT:
4226 windgoto((int)Rows - 1, 0);
4227 g_fForceExit = TRUE;
4228
Bram Moolenaar0fde2902008-03-16 13:54:13 +00004229 vim_snprintf((char *)IObuff, IOSIZE, _("Vim: Caught %s event\n"),
Bram Moolenaar071d4272004-06-13 20:20:40 +00004230 (dwCtrlType == CTRL_CLOSE_EVENT
4231 ? _("close")
4232 : dwCtrlType == CTRL_LOGOFF_EVENT
4233 ? _("logoff")
4234 : _("shutdown")));
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004235# ifdef DEBUG
Bram Moolenaar071d4272004-06-13 20:20:40 +00004236 OutputDebugString(IObuff);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004237# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004238
Bram Moolenaar0f873732019-12-05 20:28:46 +01004239 preserve_exit(); // output IObuff, preserve files and exit
Bram Moolenaar071d4272004-06-13 20:20:40 +00004240
Bram Moolenaar0f873732019-12-05 20:28:46 +01004241 return TRUE; // not reached
Bram Moolenaar071d4272004-06-13 20:20:40 +00004242
4243 default:
4244 return FALSE;
4245 }
4246}
4247
4248
4249/*
4250 * set the tty in (raw) ? "raw" : "cooked" mode
4251 */
4252 void
Bram Moolenaar26e86442020-05-17 14:06:16 +02004253mch_settmode(tmode_T tmode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004254{
4255 DWORD cmodein;
4256 DWORD cmodeout;
4257 BOOL bEnableHandler;
4258
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004259# ifdef VIMDLL
4260 if (gui.in_use)
4261 return;
4262# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004263 GetConsoleMode(g_hConIn, &cmodein);
4264 GetConsoleMode(g_hConOut, &cmodeout);
4265 if (tmode == TMODE_RAW)
4266 {
4267 cmodein &= ~(ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
4268 ENABLE_ECHO_INPUT);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004269 if (g_fMouseActive)
Wez Furlong6ef5ab52021-05-30 19:29:41 +02004270 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00004271 cmodein |= ENABLE_MOUSE_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02004272 cmodein &= ~ENABLE_QUICK_EDIT_MODE;
4273 }
4274 else
4275 {
4276 cmodein |= g_cmodein & ENABLE_QUICK_EDIT_MODE;
4277 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01004278 cmodeout &= ~(
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004279# ifdef FEAT_TERMGUICOLORS
Bram Moolenaar0f873732019-12-05 20:28:46 +01004280 // Do not turn off the ENABLE_PROCESSED_OUTPUT flag when using
4281 // VTP.
Bram Moolenaarcafafb32018-02-22 21:07:09 +01004282 ((vtp_working) ? 0 : ENABLE_PROCESSED_OUTPUT) |
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004283# else
Bram Moolenaarcafafb32018-02-22 21:07:09 +01004284 ENABLE_PROCESSED_OUTPUT |
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004285# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01004286 ENABLE_WRAP_AT_EOL_OUTPUT);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004287 bEnableHandler = TRUE;
4288 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01004289 else // cooked
Bram Moolenaar071d4272004-06-13 20:20:40 +00004290 {
4291 cmodein |= (ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
4292 ENABLE_ECHO_INPUT);
4293 cmodeout |= (ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
4294 bEnableHandler = FALSE;
4295 }
Wez Furlong6ef5ab52021-05-30 19:29:41 +02004296 SetConsoleMode(g_hConIn, cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004297 SetConsoleMode(g_hConOut, cmodeout);
4298 SetConsoleCtrlHandler(handler_routine, bEnableHandler);
4299
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004300# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00004301 if (fdDump)
4302 {
4303 fprintf(fdDump, "mch_settmode(%s, in = %x, out = %x)\n",
4304 tmode == TMODE_RAW ? "raw" :
4305 tmode == TMODE_COOK ? "cooked" : "normal",
4306 cmodein, cmodeout);
4307 fflush(fdDump);
4308 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004309# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004310}
4311
4312
4313/*
4314 * Get the size of the current window in `Rows' and `Columns'
4315 * Return OK when size could be determined, FAIL otherwise.
4316 */
4317 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004318mch_get_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004319{
4320 CONSOLE_SCREEN_BUFFER_INFO csbi;
4321
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004322# ifdef VIMDLL
4323 if (gui.in_use)
4324 return OK;
4325# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004326 if (!g_fTermcapMode && g_cbTermcap.IsValid)
4327 {
4328 /*
4329 * For some reason, we are trying to get the screen dimensions
4330 * even though we are not in termcap mode. The 'Rows' and 'Columns'
4331 * variables are really intended to mean the size of Vim screen
4332 * while in termcap mode.
4333 */
4334 Rows = g_cbTermcap.Info.dwSize.Y;
4335 Columns = g_cbTermcap.Info.dwSize.X;
4336 }
4337 else if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
4338 {
4339 Rows = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
4340 Columns = csbi.srWindow.Right - csbi.srWindow.Left + 1;
4341 }
4342 else
4343 {
4344 Rows = 25;
4345 Columns = 80;
4346 }
4347 return OK;
4348}
4349
4350/*
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004351 * Resize console buffer to 'COORD'
4352 */
4353 static void
4354ResizeConBuf(
4355 HANDLE hConsole,
4356 COORD coordScreen)
4357{
4358 if (!SetConsoleScreenBufferSize(hConsole, coordScreen))
4359 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004360# ifdef MCH_WRITE_DUMP
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004361 if (fdDump)
4362 {
4363 fprintf(fdDump, "SetConsoleScreenBufferSize failed: %lx\n",
4364 GetLastError());
4365 fflush(fdDump);
4366 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004367# endif
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004368 }
4369}
4370
4371/*
4372 * Resize console window size to 'srWindowRect'
4373 */
4374 static void
4375ResizeWindow(
4376 HANDLE hConsole,
4377 SMALL_RECT srWindowRect)
4378{
4379 if (!SetConsoleWindowInfo(hConsole, TRUE, &srWindowRect))
4380 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004381# ifdef MCH_WRITE_DUMP
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004382 if (fdDump)
4383 {
4384 fprintf(fdDump, "SetConsoleWindowInfo failed: %lx\n",
4385 GetLastError());
4386 fflush(fdDump);
4387 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004388# endif
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004389 }
4390}
4391
4392/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00004393 * Set a console window to `xSize' * `ySize'
4394 */
4395 static void
4396ResizeConBufAndWindow(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004397 HANDLE hConsole,
4398 int xSize,
4399 int ySize)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004400{
Bram Moolenaar0f873732019-12-05 20:28:46 +01004401 CONSOLE_SCREEN_BUFFER_INFO csbi; // hold current console buffer info
4402 SMALL_RECT srWindowRect; // hold the new console size
Bram Moolenaar071d4272004-06-13 20:20:40 +00004403 COORD coordScreen;
Bram Moolenaarf49a6922019-07-15 20:37:05 +02004404 COORD cursor;
Bram Moolenaar2551c032018-08-23 22:38:31 +02004405 static int resized = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004406
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004407# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00004408 if (fdDump)
4409 {
4410 fprintf(fdDump, "ResizeConBufAndWindow(%d, %d)\n", xSize, ySize);
4411 fflush(fdDump);
4412 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004413# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004414
Bram Moolenaar0f873732019-12-05 20:28:46 +01004415 // get the largest size we can size the console window to
Bram Moolenaar071d4272004-06-13 20:20:40 +00004416 coordScreen = GetLargestConsoleWindowSize(hConsole);
4417
Bram Moolenaar0f873732019-12-05 20:28:46 +01004418 // define the new console window size and scroll position
Bram Moolenaar071d4272004-06-13 20:20:40 +00004419 srWindowRect.Left = srWindowRect.Top = (SHORT) 0;
4420 srWindowRect.Right = (SHORT) (min(xSize, coordScreen.X) - 1);
4421 srWindowRect.Bottom = (SHORT) (min(ySize, coordScreen.Y) - 1);
4422
4423 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
4424 {
4425 int sx, sy;
4426
4427 sx = csbi.srWindow.Right - csbi.srWindow.Left + 1;
4428 sy = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
4429 if (sy < ySize || sx < xSize)
4430 {
4431 /*
4432 * Increasing number of lines/columns, do buffer first.
4433 * Use the maximal size in x and y direction.
4434 */
4435 if (sy < ySize)
4436 coordScreen.Y = ySize;
4437 else
4438 coordScreen.Y = sy;
4439 if (sx < xSize)
4440 coordScreen.X = xSize;
4441 else
4442 coordScreen.X = sx;
4443 SetConsoleScreenBufferSize(hConsole, coordScreen);
4444 }
4445 }
4446
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004447 // define the new console buffer size
Bram Moolenaar071d4272004-06-13 20:20:40 +00004448 coordScreen.X = xSize;
4449 coordScreen.Y = ySize;
4450
Bram Moolenaar2551c032018-08-23 22:38:31 +02004451 // In the new console call API, only the first time in reverse order
4452 if (!vtp_working || resized)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004453 {
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004454 ResizeWindow(hConsole, srWindowRect);
4455 ResizeConBuf(hConsole, coordScreen);
4456 }
4457 else
4458 {
Bram Moolenaarf49a6922019-07-15 20:37:05 +02004459 // Workaround for a Windows 10 bug
4460 cursor.X = srWindowRect.Left;
4461 cursor.Y = srWindowRect.Top;
4462 SetConsoleCursorPosition(hConsole, cursor);
4463
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004464 ResizeConBuf(hConsole, coordScreen);
4465 ResizeWindow(hConsole, srWindowRect);
Bram Moolenaar2551c032018-08-23 22:38:31 +02004466 resized = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004467 }
4468}
4469
4470
4471/*
4472 * Set the console window to `Rows' * `Columns'
4473 */
4474 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004475mch_set_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004476{
4477 COORD coordScreen;
4478
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004479# ifdef VIMDLL
4480 if (gui.in_use)
4481 return;
4482# endif
Bram Moolenaar0f873732019-12-05 20:28:46 +01004483 // Don't change window size while still starting up
Bram Moolenaar071d4272004-06-13 20:20:40 +00004484 if (suppress_winsize != 0)
4485 {
4486 suppress_winsize = 2;
4487 return;
4488 }
4489
4490 if (term_console)
4491 {
4492 coordScreen = GetLargestConsoleWindowSize(g_hConOut);
4493
Bram Moolenaar0f873732019-12-05 20:28:46 +01004494 // Clamp Rows and Columns to reasonable values
Bram Moolenaar071d4272004-06-13 20:20:40 +00004495 if (Rows > coordScreen.Y)
4496 Rows = coordScreen.Y;
4497 if (Columns > coordScreen.X)
4498 Columns = coordScreen.X;
4499
4500 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
4501 }
4502}
4503
4504/*
4505 * Rows and/or Columns has changed.
4506 */
4507 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004508mch_new_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004509{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004510# ifdef VIMDLL
4511 if (gui.in_use)
4512 return;
4513# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004514 set_scroll_region(0, 0, Columns - 1, Rows - 1);
4515}
4516
4517
4518/*
4519 * Called when started up, to set the winsize that was delayed.
4520 */
4521 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004522mch_set_winsize_now(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004523{
4524 if (suppress_winsize == 2)
4525 {
4526 suppress_winsize = 0;
4527 mch_set_shellsize();
4528 shell_resized();
4529 }
4530 suppress_winsize = 0;
4531}
Bram Moolenaar0f873732019-12-05 20:28:46 +01004532#endif // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00004533
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004534 static BOOL
4535vim_create_process(
Bram Moolenaar36c85b22013-12-12 20:25:44 +01004536 char *cmd,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004537 BOOL inherit_handles,
Bram Moolenaar3f1138e2014-01-05 13:29:26 +01004538 DWORD flags,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004539 STARTUPINFO *si,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004540 PROCESS_INFORMATION *pi,
4541 LPVOID *env,
4542 char *cwd)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004543{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004544 BOOL ret = FALSE;
4545 WCHAR *wcmd, *wcwd = NULL;
4546
4547 wcmd = enc_to_utf16((char_u *)cmd, NULL);
4548 if (wcmd == NULL)
4549 return FALSE;
4550 if (cwd != NULL)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004551 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004552 wcwd = enc_to_utf16((char_u *)cwd, NULL);
4553 if (wcwd == NULL)
4554 goto theend;
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004555 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004556
4557 ret = CreateProcessW(
4558 NULL, // Executable name
4559 wcmd, // Command to execute
4560 NULL, // Process security attributes
4561 NULL, // Thread security attributes
4562 inherit_handles, // Inherit handles
4563 flags, // Creation flags
4564 env, // Environment
4565 wcwd, // Current directory
4566 (LPSTARTUPINFOW)si, // Startup information
4567 pi); // Process information
4568theend:
4569 vim_free(wcmd);
4570 vim_free(wcwd);
4571 return ret;
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004572}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004573
4574
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004575 static HINSTANCE
4576vim_shell_execute(
4577 char *cmd,
4578 INT n_show_cmd)
4579{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004580 HINSTANCE ret;
4581 WCHAR *wcmd;
4582
4583 wcmd = enc_to_utf16((char_u *)cmd, NULL);
4584 if (wcmd == NULL)
4585 return (HINSTANCE) 0;
4586
4587 ret = ShellExecuteW(NULL, NULL, wcmd, NULL, NULL, n_show_cmd);
4588 vim_free(wcmd);
4589 return ret;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004590}
4591
4592
Bram Moolenaar4f974752019-02-17 17:44:42 +01004593#if defined(FEAT_GUI_MSWIN) || defined(PROTO)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004594
4595/*
4596 * Specialised version of system() for Win32 GUI mode.
4597 * This version proceeds as follows:
4598 * 1. Create a console window for use by the subprocess
4599 * 2. Run the subprocess (it gets the allocated console by default)
4600 * 3. Wait for the subprocess to terminate and get its exit code
4601 * 4. Prompt the user to press a key to close the console window
4602 */
4603 static int
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004604mch_system_classic(char *cmd, int options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004605{
4606 STARTUPINFO si;
4607 PROCESS_INFORMATION pi;
4608 DWORD ret = 0;
4609 HWND hwnd = GetFocus();
4610
4611 si.cb = sizeof(si);
4612 si.lpReserved = NULL;
4613 si.lpDesktop = NULL;
4614 si.lpTitle = NULL;
4615 si.dwFlags = STARTF_USESHOWWINDOW;
4616 /*
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004617 * It's nicer to run a filter command in a minimized window.
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01004618 * Don't activate the window to keep focus on Vim.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004619 */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004620 if (options & SHELL_DOOUT)
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01004621 si.wShowWindow = SW_SHOWMINNOACTIVE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004622 else
4623 si.wShowWindow = SW_SHOWNORMAL;
4624 si.cbReserved2 = 0;
4625 si.lpReserved2 = NULL;
4626
Bram Moolenaar0f873732019-12-05 20:28:46 +01004627 // Now, run the command
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004628 vim_create_process(cmd, FALSE,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004629 CREATE_DEFAULT_ERROR_MODE | CREATE_NEW_CONSOLE,
4630 &si, &pi, NULL, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004631
Bram Moolenaar0f873732019-12-05 20:28:46 +01004632 // Wait for the command to terminate before continuing
Bram Moolenaar071d4272004-06-13 20:20:40 +00004633 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004634# ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00004635 int delay = 1;
4636
Bram Moolenaar0f873732019-12-05 20:28:46 +01004637 // Keep updating the window while waiting for the shell to finish.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004638 for (;;)
4639 {
4640 MSG msg;
4641
K.Takatab7057bd2022-01-21 11:37:07 +00004642 if (PeekMessageW(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004643 {
4644 TranslateMessage(&msg);
K.Takatab7057bd2022-01-21 11:37:07 +00004645 DispatchMessageW(&msg);
Bram Moolenaare4195c52012-08-02 12:31:44 +02004646 delay = 1;
4647 continue;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004648 }
4649 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
4650 break;
4651
Bram Moolenaar0f873732019-12-05 20:28:46 +01004652 // We start waiting for a very short time and then increase it, so
4653 // that we respond quickly when the process is quick, and don't
4654 // consume too much overhead when it's slow.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004655 if (delay < 50)
4656 delay += 10;
4657 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004658# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004659 WaitForSingleObject(pi.hProcess, INFINITE);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004660# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004661
Bram Moolenaar0f873732019-12-05 20:28:46 +01004662 // Get the command exit code
Bram Moolenaar071d4272004-06-13 20:20:40 +00004663 GetExitCodeProcess(pi.hProcess, &ret);
4664 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004665
Bram Moolenaar0f873732019-12-05 20:28:46 +01004666 // Close the handles to the subprocess, so that it goes away
Bram Moolenaar071d4272004-06-13 20:20:40 +00004667 CloseHandle(pi.hThread);
4668 CloseHandle(pi.hProcess);
4669
Bram Moolenaar0f873732019-12-05 20:28:46 +01004670 // Try to get input focus back. Doesn't always work though.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004671 PostMessage(hwnd, WM_SETFOCUS, 0, 0);
4672
4673 return ret;
4674}
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004675
4676/*
4677 * Thread launched by the gui to send the current buffer data to the
4678 * process. This way avoid to hang up vim totally if the children
4679 * process take a long time to process the lines.
4680 */
Bram Moolenaar4c38d662016-08-03 20:54:57 +02004681 static unsigned int __stdcall
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004682sub_process_writer(LPVOID param)
4683{
4684 HANDLE g_hChildStd_IN_Wr = param;
4685 linenr_T lnum = curbuf->b_op_start.lnum;
4686 DWORD len = 0;
4687 DWORD l;
4688 char_u *lp = ml_get(lnum);
4689 char_u *s;
4690 int written = 0;
4691
4692 for (;;)
4693 {
4694 l = (DWORD)STRLEN(lp + written);
4695 if (l == 0)
4696 len = 0;
4697 else if (lp[written] == NL)
4698 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004699 // NL -> NUL translation
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004700 WriteFile(g_hChildStd_IN_Wr, "", 1, &len, NULL);
4701 }
4702 else
4703 {
4704 s = vim_strchr(lp + written, NL);
4705 WriteFile(g_hChildStd_IN_Wr, (char *)lp + written,
4706 s == NULL ? l : (DWORD)(s - (lp + written)),
4707 &len, NULL);
4708 }
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +01004709 if (len == l)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004710 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004711 // Finished a line, add a NL, unless this line should not have
4712 // one.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004713 if (lnum != curbuf->b_op_end.lnum
Bram Moolenaar34d72d42015-07-17 14:18:08 +02004714 || (!curbuf->b_p_bin
4715 && curbuf->b_p_fixeol)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004716 || (lnum != curbuf->b_no_eol_lnum
4717 && (lnum != curbuf->b_ml.ml_line_count
4718 || curbuf->b_p_eol)))
4719 {
Bram Moolenaar42335f52018-09-13 15:33:43 +02004720 WriteFile(g_hChildStd_IN_Wr, "\n", 1,
4721 (LPDWORD)&vim_ignored, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004722 }
4723
4724 ++lnum;
4725 if (lnum > curbuf->b_op_end.lnum)
4726 break;
4727
4728 lp = ml_get(lnum);
4729 written = 0;
4730 }
4731 else if (len > 0)
4732 written += len;
4733 }
4734
Bram Moolenaar0f873732019-12-05 20:28:46 +01004735 // finished all the lines, close pipe
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004736 CloseHandle(g_hChildStd_IN_Wr);
Bram Moolenaar86f2cd52016-08-02 21:55:17 +02004737 return 0;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004738}
4739
4740
Bram Moolenaar0f873732019-12-05 20:28:46 +01004741# define BUFLEN 100 // length for buffer, stolen from unix version
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004742
4743/*
4744 * This function read from the children's stdout and write the
4745 * data on screen or in the buffer accordingly.
4746 */
4747 static void
4748dump_pipe(int options,
4749 HANDLE g_hChildStd_OUT_Rd,
4750 garray_T *ga,
4751 char_u buffer[],
4752 DWORD *buffer_off)
4753{
4754 DWORD availableBytes = 0;
4755 DWORD i;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004756 int ret;
4757 DWORD len;
4758 DWORD toRead;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004759
Bram Moolenaar0f873732019-12-05 20:28:46 +01004760 // we query the pipe to see if there is any data to read
4761 // to avoid to perform a blocking read
4762 ret = PeekNamedPipe(g_hChildStd_OUT_Rd, // pipe to query
4763 NULL, // optional buffer
4764 0, // buffer size
4765 NULL, // number of read bytes
4766 &availableBytes, // available bytes total
4767 NULL); // byteLeft
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004768
Bram Moolenaar0f873732019-12-05 20:28:46 +01004769 // We got real data in the pipe, read it
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02004770 while (ret != 0 && availableBytes > 0)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004771 {
Bram Moolenaara12a1612019-01-24 16:39:02 +01004772 toRead = (DWORD)(BUFLEN - *buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004773 toRead = availableBytes < toRead ? availableBytes : toRead;
Bram Moolenaara12a1612019-01-24 16:39:02 +01004774 ReadFile(g_hChildStd_OUT_Rd, buffer + *buffer_off, toRead , &len, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004775
Bram Moolenaar0f873732019-12-05 20:28:46 +01004776 // If we haven't read anything, there is a problem
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004777 if (len == 0)
4778 break;
4779
4780 availableBytes -= len;
4781
4782 if (options & SHELL_READ)
4783 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004784 // Do NUL -> NL translation, append NL separated
4785 // lines to the current buffer.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004786 for (i = 0; i < len; ++i)
4787 {
4788 if (buffer[i] == NL)
4789 append_ga_line(ga);
4790 else if (buffer[i] == NUL)
4791 ga_append(ga, NL);
4792 else
4793 ga_append(ga, buffer[i]);
4794 }
4795 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004796 else if (has_mbyte)
4797 {
4798 int l;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004799 int c;
4800 char_u *p;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004801
4802 len += *buffer_off;
4803 buffer[len] = NUL;
4804
Bram Moolenaar0f873732019-12-05 20:28:46 +01004805 // Check if the last character in buffer[] is
4806 // incomplete, keep these bytes for the next
4807 // round.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004808 for (p = buffer; p < buffer + len; p += l)
4809 {
Bram Moolenaard3c907b2016-08-17 21:32:09 +02004810 l = MB_CPTR2LEN(p);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004811 if (l == 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01004812 l = 1; // NUL byte?
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004813 else if (MB_BYTE2LEN(*p) != l)
4814 break;
4815 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01004816 if (p == buffer) // no complete character
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004817 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004818 // avoid getting stuck at an illegal byte
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004819 if (len >= 12)
4820 ++p;
4821 else
4822 {
4823 *buffer_off = len;
4824 return;
4825 }
4826 }
4827 c = *p;
4828 *p = NUL;
Bram Moolenaar32526b32019-01-19 17:43:09 +01004829 msg_puts((char *)buffer);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004830 if (p < buffer + len)
4831 {
4832 *p = c;
4833 *buffer_off = (DWORD)((buffer + len) - p);
4834 mch_memmove(buffer, p, *buffer_off);
4835 return;
4836 }
4837 *buffer_off = 0;
4838 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004839 else
4840 {
4841 buffer[len] = NUL;
Bram Moolenaar32526b32019-01-19 17:43:09 +01004842 msg_puts((char *)buffer);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004843 }
4844
4845 windgoto(msg_row, msg_col);
4846 cursor_on();
4847 out_flush();
4848 }
4849}
4850
4851/*
4852 * Version of system to use for windows NT > 5.0 (Win2K), use pipe
4853 * for communication and doesn't open any new window.
4854 */
4855 static int
4856mch_system_piped(char *cmd, int options)
4857{
4858 STARTUPINFO si;
4859 PROCESS_INFORMATION pi;
4860 DWORD ret = 0;
4861
4862 HANDLE g_hChildStd_IN_Rd = NULL;
4863 HANDLE g_hChildStd_IN_Wr = NULL;
4864 HANDLE g_hChildStd_OUT_Rd = NULL;
4865 HANDLE g_hChildStd_OUT_Wr = NULL;
4866
Bram Moolenaar0f873732019-12-05 20:28:46 +01004867 char_u buffer[BUFLEN + 1]; // reading buffer + size
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004868 DWORD len;
4869
Bram Moolenaar0f873732019-12-05 20:28:46 +01004870 // buffer used to receive keys
4871 char_u ta_buf[BUFLEN + 1]; // TypeAHead
4872 int ta_len = 0; // valid bytes in ta_buf[]
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004873
4874 DWORD i;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004875 int noread_cnt = 0;
4876 garray_T ga;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004877 int delay = 1;
Bram Moolenaar0f873732019-12-05 20:28:46 +01004878 DWORD buffer_off = 0; // valid bytes in buffer[]
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004879 char *p = NULL;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004880
4881 SECURITY_ATTRIBUTES saAttr;
4882
Bram Moolenaar0f873732019-12-05 20:28:46 +01004883 // Set the bInheritHandle flag so pipe handles are inherited.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004884 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
4885 saAttr.bInheritHandle = TRUE;
4886 saAttr.lpSecurityDescriptor = NULL;
4887
4888 if ( ! CreatePipe(&g_hChildStd_OUT_Rd, &g_hChildStd_OUT_Wr, &saAttr, 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01004889 // Ensure the read handle to the pipe for STDOUT is not inherited.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004890 || ! SetHandleInformation(g_hChildStd_OUT_Rd, HANDLE_FLAG_INHERIT, 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01004891 // Create a pipe for the child process's STDIN.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004892 || ! CreatePipe(&g_hChildStd_IN_Rd, &g_hChildStd_IN_Wr, &saAttr, 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01004893 // Ensure the write handle to the pipe for STDIN is not inherited.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004894 || ! SetHandleInformation(g_hChildStd_IN_Wr, HANDLE_FLAG_INHERIT, 0) )
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004895 {
4896 CloseHandle(g_hChildStd_IN_Rd);
4897 CloseHandle(g_hChildStd_IN_Wr);
4898 CloseHandle(g_hChildStd_OUT_Rd);
4899 CloseHandle(g_hChildStd_OUT_Wr);
Bram Moolenaar32526b32019-01-19 17:43:09 +01004900 msg_puts(_("\nCannot create pipes\n"));
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004901 }
4902
4903 si.cb = sizeof(si);
4904 si.lpReserved = NULL;
4905 si.lpDesktop = NULL;
4906 si.lpTitle = NULL;
4907 si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
4908
Bram Moolenaar0f873732019-12-05 20:28:46 +01004909 // set-up our file redirection
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004910 si.hStdError = g_hChildStd_OUT_Wr;
4911 si.hStdOutput = g_hChildStd_OUT_Wr;
4912 si.hStdInput = g_hChildStd_IN_Rd;
4913 si.wShowWindow = SW_HIDE;
4914 si.cbReserved2 = 0;
4915 si.lpReserved2 = NULL;
4916
4917 if (options & SHELL_READ)
4918 ga_init2(&ga, 1, BUFLEN);
4919
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004920 if (cmd != NULL)
4921 {
4922 p = (char *)vim_strsave((char_u *)cmd);
4923 if (p != NULL)
4924 unescape_shellxquote((char_u *)p, p_sxe);
4925 else
4926 p = cmd;
4927 }
4928
Bram Moolenaar0f873732019-12-05 20:28:46 +01004929 // Now, run the command.
4930 // About "Inherit handles" being TRUE: this command can be litigious,
4931 // handle inheritance was deactivated for pending temp file, but, if we
4932 // deactivate it, the pipes don't work for some reason.
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004933 vim_create_process(p, TRUE, CREATE_DEFAULT_ERROR_MODE,
4934 &si, &pi, NULL, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004935
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004936 if (p != cmd)
4937 vim_free(p);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004938
Bram Moolenaar0f873732019-12-05 20:28:46 +01004939 // Close our unused side of the pipes
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004940 CloseHandle(g_hChildStd_IN_Rd);
4941 CloseHandle(g_hChildStd_OUT_Wr);
4942
4943 if (options & SHELL_WRITE)
4944 {
Bram Moolenaar86f2cd52016-08-02 21:55:17 +02004945 HANDLE thread = (HANDLE)
Bram Moolenaar0f873732019-12-05 20:28:46 +01004946 _beginthreadex(NULL, // security attributes
4947 0, // default stack size
4948 sub_process_writer, // function to be executed
4949 g_hChildStd_IN_Wr, // parameter
4950 0, // creation flag, start immediately
4951 NULL); // we don't care about thread id
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004952 CloseHandle(thread);
4953 g_hChildStd_IN_Wr = NULL;
4954 }
4955
Bram Moolenaar0f873732019-12-05 20:28:46 +01004956 // Keep updating the window while waiting for the shell to finish.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004957 for (;;)
4958 {
4959 MSG msg;
4960
K.Takatab7057bd2022-01-21 11:37:07 +00004961 if (PeekMessageW(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004962 {
4963 TranslateMessage(&msg);
K.Takatab7057bd2022-01-21 11:37:07 +00004964 DispatchMessageW(&msg);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004965 }
4966
Bram Moolenaar0f873732019-12-05 20:28:46 +01004967 // write pipe information in the window
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004968 if ((options & (SHELL_READ|SHELL_WRITE))
4969# ifdef FEAT_GUI
4970 || gui.in_use
4971# endif
4972 )
4973 {
4974 len = 0;
4975 if (!(options & SHELL_EXPAND)
4976 && ((options &
4977 (SHELL_READ|SHELL_WRITE|SHELL_COOKED))
4978 != (SHELL_READ|SHELL_WRITE|SHELL_COOKED)
4979# ifdef FEAT_GUI
4980 || gui.in_use
4981# endif
4982 )
4983 && (ta_len > 0 || noread_cnt > 4))
4984 {
4985 if (ta_len == 0)
4986 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004987 // Get extra characters when we don't have any. Reset the
4988 // counter and timer.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004989 noread_cnt = 0;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004990 len = ui_inchar(ta_buf, BUFLEN, 10L, 0);
4991 }
4992 if (ta_len > 0 || len > 0)
4993 {
4994 /*
4995 * For pipes: Check for CTRL-C: send interrupt signal to
4996 * child. Check for CTRL-D: EOF, close pipe to child.
4997 */
4998 if (len == 1 && cmd != NULL)
4999 {
5000 if (ta_buf[ta_len] == Ctrl_C)
5001 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005002 // Learn what exit code is expected, for
5003 // now put 9 as SIGKILL
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005004 TerminateProcess(pi.hProcess, 9);
5005 }
5006 if (ta_buf[ta_len] == Ctrl_D)
5007 {
5008 CloseHandle(g_hChildStd_IN_Wr);
5009 g_hChildStd_IN_Wr = NULL;
5010 }
5011 }
5012
Bram Moolenaar2f7e1b82022-10-04 13:17:31 +01005013 len = term_replace_keycodes(ta_buf, ta_len, len);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005014
5015 /*
5016 * For pipes: echo the typed characters. For a pty this
5017 * does not seem to work.
5018 */
5019 for (i = ta_len; i < ta_len + len; ++i)
5020 {
5021 if (ta_buf[i] == '\n' || ta_buf[i] == '\b')
5022 msg_putchar(ta_buf[i]);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005023 else if (has_mbyte)
5024 {
5025 int l = (*mb_ptr2len)(ta_buf + i);
5026
5027 msg_outtrans_len(ta_buf + i, l);
5028 i += l - 1;
5029 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005030 else
5031 msg_outtrans_len(ta_buf + i, 1);
5032 }
5033 windgoto(msg_row, msg_col);
5034 out_flush();
5035
5036 ta_len += len;
5037
5038 /*
5039 * Write the characters to the child, unless EOF has been
5040 * typed for pipes. Write one character at a time, to
5041 * avoid losing too much typeahead. When writing buffer
5042 * lines, drop the typed characters (only check for
5043 * CTRL-C).
5044 */
5045 if (options & SHELL_WRITE)
5046 ta_len = 0;
5047 else if (g_hChildStd_IN_Wr != NULL)
5048 {
5049 WriteFile(g_hChildStd_IN_Wr, (char*)ta_buf,
5050 1, &len, NULL);
5051 // if we are typing in, we want to keep things reactive
5052 delay = 1;
5053 if (len > 0)
5054 {
5055 ta_len -= len;
5056 mch_memmove(ta_buf, ta_buf + len, ta_len);
5057 }
5058 }
5059 }
5060 }
5061 }
5062
5063 if (ta_len)
5064 ui_inchar_undo(ta_buf, ta_len);
5065
5066 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
5067 {
Bram Moolenaar2eba1822011-08-27 15:10:04 +02005068 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005069 break;
5070 }
5071
5072 ++noread_cnt;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02005073 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005074
Bram Moolenaar0f873732019-12-05 20:28:46 +01005075 // We start waiting for a very short time and then increase it, so
5076 // that we respond quickly when the process is quick, and don't
5077 // consume too much overhead when it's slow.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005078 if (delay < 50)
5079 delay += 10;
5080 }
5081
Bram Moolenaar0f873732019-12-05 20:28:46 +01005082 // Close the pipe
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005083 CloseHandle(g_hChildStd_OUT_Rd);
5084 if (g_hChildStd_IN_Wr != NULL)
5085 CloseHandle(g_hChildStd_IN_Wr);
5086
5087 WaitForSingleObject(pi.hProcess, INFINITE);
5088
Bram Moolenaar0f873732019-12-05 20:28:46 +01005089 // Get the command exit code
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005090 GetExitCodeProcess(pi.hProcess, &ret);
5091
5092 if (options & SHELL_READ)
5093 {
5094 if (ga.ga_len > 0)
5095 {
5096 append_ga_line(&ga);
Bram Moolenaar0f873732019-12-05 20:28:46 +01005097 // remember that the NL was missing
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005098 curbuf->b_no_eol_lnum = curwin->w_cursor.lnum;
5099 }
5100 else
5101 curbuf->b_no_eol_lnum = 0;
5102 ga_clear(&ga);
5103 }
5104
Bram Moolenaar0f873732019-12-05 20:28:46 +01005105 // Close the handles to the subprocess, so that it goes away
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005106 CloseHandle(pi.hThread);
5107 CloseHandle(pi.hProcess);
5108
5109 return ret;
5110}
5111
5112 static int
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005113mch_system_g(char *cmd, int options)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005114{
Bram Moolenaar0f873732019-12-05 20:28:46 +01005115 // if we can pipe and the shelltemp option is off
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005116 if (!p_stmp)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005117 return mch_system_piped(cmd, options);
5118 else
5119 return mch_system_classic(cmd, options);
5120}
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005121#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005122
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005123#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01005124 static int
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02005125mch_system_c(char *cmd, int options UNUSED)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01005126{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005127 int ret;
5128 WCHAR *wcmd;
Bram Moolenaar2efc44b2019-10-05 12:09:32 +02005129 char_u *buf;
5130 size_t len;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005131
Bram Moolenaar2efc44b2019-10-05 12:09:32 +02005132 // If the command starts and ends with double quotes, enclose the command
5133 // in parentheses.
5134 len = STRLEN(cmd);
5135 if (len >= 2 && cmd[0] == '"' && cmd[len - 1] == '"')
5136 {
5137 len += 3;
5138 buf = alloc(len);
5139 if (buf == NULL)
5140 return -1;
5141 vim_snprintf((char *)buf, len, "(%s)", cmd);
5142 wcmd = enc_to_utf16(buf, NULL);
5143 free(buf);
5144 }
5145 else
5146 wcmd = enc_to_utf16((char_u *)cmd, NULL);
5147
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005148 if (wcmd == NULL)
5149 return -1;
5150
5151 ret = _wsystem(wcmd);
5152 vim_free(wcmd);
5153 return ret;
Bram Moolenaar910cffb2013-12-11 17:58:35 +01005154}
Bram Moolenaar071d4272004-06-13 20:20:40 +00005155
5156#endif
5157
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005158 static int
5159mch_system(char *cmd, int options)
5160{
5161#ifdef VIMDLL
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02005162 if (gui.in_use || gui.starting)
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005163 return mch_system_g(cmd, options);
5164 else
5165 return mch_system_c(cmd, options);
5166#elif defined(FEAT_GUI_MSWIN)
5167 return mch_system_g(cmd, options);
5168#else
5169 return mch_system_c(cmd, options);
5170#endif
5171}
5172
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005173#if defined(FEAT_GUI) && defined(FEAT_TERMINAL)
5174/*
5175 * Use a terminal window to run a shell command in.
5176 */
5177 static int
5178mch_call_shell_terminal(
5179 char_u *cmd,
Bram Moolenaar0f873732019-12-05 20:28:46 +01005180 int options UNUSED) // SHELL_*, see vim.h
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005181{
5182 jobopt_T opt;
5183 char_u *newcmd = NULL;
5184 typval_T argvar[2];
5185 long_u cmdlen;
5186 int retval = -1;
5187 buf_T *buf;
Bram Moolenaarf9c38832018-06-19 19:59:20 +02005188 job_T *job;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005189 aco_save_T aco;
Bram Moolenaar0f873732019-12-05 20:28:46 +01005190 oparg_T oa; // operator arguments
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005191
Bram Moolenaar42f652f2018-03-19 21:44:37 +01005192 if (cmd == NULL)
5193 cmdlen = STRLEN(p_sh) + 1;
5194 else
5195 cmdlen = STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10;
Bram Moolenaar18a4ba22019-05-24 19:39:03 +02005196 newcmd = alloc(cmdlen);
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005197 if (newcmd == NULL)
5198 return 255;
Bram Moolenaar42f652f2018-03-19 21:44:37 +01005199 if (cmd == NULL)
5200 {
5201 STRCPY(newcmd, p_sh);
5202 ch_log(NULL, "starting terminal to run a shell");
5203 }
5204 else
5205 {
5206 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s", p_sh, p_shcf, cmd);
5207 ch_log(NULL, "starting terminal for system command '%s'", cmd);
5208 }
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005209
5210 init_job_options(&opt);
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005211
5212 argvar[0].v_type = VAR_STRING;
5213 argvar[0].vval.v_string = newcmd;
5214 argvar[1].v_type = VAR_UNKNOWN;
5215 buf = term_start(argvar, NULL, &opt, TERM_START_SYSTEM);
Bram Moolenaar81c3c89a2018-03-20 11:41:44 +01005216 if (buf == NULL)
Bram Moolenaar9029b912019-03-21 19:58:00 +01005217 {
5218 vim_free(newcmd);
Bram Moolenaar81c3c89a2018-03-20 11:41:44 +01005219 return 255;
Bram Moolenaar9029b912019-03-21 19:58:00 +01005220 }
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005221
Bram Moolenaarf9c38832018-06-19 19:59:20 +02005222 job = term_getjob(buf->b_term);
5223 ++job->jv_refcount;
5224
Bram Moolenaar0f873732019-12-05 20:28:46 +01005225 // Find a window to make "buf" curbuf.
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005226 aucmd_prepbuf(&aco, buf);
Bram Moolenaare76062c2022-11-28 18:51:43 +00005227 if (curbuf == buf)
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005228 {
Bram Moolenaare76062c2022-11-28 18:51:43 +00005229 // Only do this when a window was found for "buf".
5230 clear_oparg(&oa);
5231 while (term_use_loop())
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005232 {
Bram Moolenaare76062c2022-11-28 18:51:43 +00005233 if (oa.op_type == OP_NOP && oa.regname == NUL && !VIsual_active)
5234 {
5235 // If terminal_loop() returns OK we got a key that is handled
5236 // in Normal model. We don't do redrawing anyway.
5237 if (terminal_loop(TRUE) == OK)
5238 normal_cmd(&oa, TRUE);
5239 }
5240 else
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005241 normal_cmd(&oa, TRUE);
5242 }
Bram Moolenaare76062c2022-11-28 18:51:43 +00005243 retval = job->jv_exitval;
5244 ch_log(NULL, "system command finished");
5245
5246 job_unref(job);
5247
5248 // restore curwin/curbuf and a few other things
5249 aucmd_restbuf(&aco);
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005250 }
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005251
5252 wait_return(TRUE);
5253 do_buffer(DOBUF_WIPE, DOBUF_FIRST, FORWARD, buf->b_fnum, TRUE);
5254
5255 vim_free(newcmd);
5256 return retval;
5257}
5258#endif
5259
Bram Moolenaar071d4272004-06-13 20:20:40 +00005260/*
5261 * Either execute a command by calling the shell or start a new shell
5262 */
5263 int
5264mch_call_shell(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005265 char_u *cmd,
Bram Moolenaar0f873732019-12-05 20:28:46 +01005266 int options) // SHELL_*, see vim.h
Bram Moolenaar071d4272004-06-13 20:20:40 +00005267{
5268 int x = 0;
5269 int tmode = cur_tmode;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005270 WCHAR szShellTitle[512];
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02005271
Bram Moolenaar4c5678f2022-11-30 18:12:19 +00005272#ifdef FEAT_EVAL
Bram Moolenaarc9a9a0a2022-04-12 15:09:23 +01005273 ch_log(NULL, "executing shell command: %s", cmd);
5274#endif
Bram Moolenaar0f873732019-12-05 20:28:46 +01005275 // Change the title to reflect that we are in a subshell.
K.Takataeeec2542021-06-02 13:28:16 +02005276 if (GetConsoleTitleW(szShellTitle, ARRAY_LENGTH(szShellTitle) - 4) > 0)
Bram Moolenaar1df52d72014-10-15 22:50:10 +02005277 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005278 if (cmd == NULL)
5279 wcscat(szShellTitle, L" :sh");
5280 else
Bram Moolenaar1df52d72014-10-15 22:50:10 +02005281 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005282 WCHAR *wn = enc_to_utf16((char_u *)cmd, NULL);
Bram Moolenaar1df52d72014-10-15 22:50:10 +02005283
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005284 if (wn != NULL)
5285 {
5286 wcscat(szShellTitle, L" - !");
5287 if ((wcslen(szShellTitle) + wcslen(wn) <
K.Takataeeec2542021-06-02 13:28:16 +02005288 ARRAY_LENGTH(szShellTitle)))
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005289 wcscat(szShellTitle, wn);
5290 SetConsoleTitleW(szShellTitle);
5291 vim_free(wn);
Bram Moolenaar1df52d72014-10-15 22:50:10 +02005292 }
5293 }
5294 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005295
5296 out_flush();
5297
5298#ifdef MCH_WRITE_DUMP
5299 if (fdDump)
5300 {
5301 fprintf(fdDump, "mch_call_shell(\"%s\", %d)\n", cmd, options);
5302 fflush(fdDump);
5303 }
5304#endif
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005305#if defined(FEAT_GUI) && defined(FEAT_TERMINAL)
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02005306 // TODO: make the terminal window work with input or output redirected.
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005307 if (
5308# ifdef VIMDLL
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02005309 gui.in_use &&
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005310# endif
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02005311 vim_strchr(p_go, GO_TERMINAL) != NULL
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005312 && (options & (SHELL_FILTER|SHELL_DOOUT|SHELL_WRITE|SHELL_READ)) == 0)
5313 {
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02005314 char_u *cmdbase = cmd;
5315
Bram Moolenaar4d5c1262019-09-20 17:20:02 +02005316 if (cmdbase != NULL)
5317 // Skip a leading quote and (.
5318 while (*cmdbase == '"' || *cmdbase == '(')
5319 ++cmdbase;
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02005320
5321 // Check the command does not begin with "start "
Bram Moolenaar36e7a822019-11-13 21:49:24 +01005322 if (cmdbase == NULL || STRNICMP(cmdbase, "start", 5) != 0
5323 || !VIM_ISWHITE(cmdbase[5]))
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02005324 {
5325 // Use a terminal window to run the command in.
5326 x = mch_call_shell_terminal(cmd, options);
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02005327 resettitle();
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02005328 return x;
5329 }
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005330 }
5331#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005332
5333 /*
5334 * Catch all deadly signals while running the external command, because a
5335 * CTRL-C, Ctrl-Break or illegal instruction might otherwise kill us.
5336 */
5337 signal(SIGINT, SIG_IGN);
5338#if defined(__GNUC__) && !defined(__MINGW32__)
5339 signal(SIGKILL, SIG_IGN);
5340#else
5341 signal(SIGBREAK, SIG_IGN);
5342#endif
5343 signal(SIGILL, SIG_IGN);
5344 signal(SIGFPE, SIG_IGN);
5345 signal(SIGSEGV, SIG_IGN);
5346 signal(SIGTERM, SIG_IGN);
5347 signal(SIGABRT, SIG_IGN);
5348
5349 if (options & SHELL_COOKED)
Bram Moolenaar0f873732019-12-05 20:28:46 +01005350 settmode(TMODE_COOK); // set to normal mode
Bram Moolenaar071d4272004-06-13 20:20:40 +00005351
5352 if (cmd == NULL)
5353 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01005354 x = mch_system((char *)p_sh, options);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005355 }
5356 else
5357 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005358 // we use "command" or "cmd" to start the shell; slow but easy
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005359 char_u *newcmd = NULL;
5360 char_u *cmdbase = cmd;
5361 long_u cmdlen;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005362
Bram Moolenaar0f873732019-12-05 20:28:46 +01005363 // Skip a leading ", ( and "(.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005364 if (*cmdbase == '"' )
5365 ++cmdbase;
5366 if (*cmdbase == '(')
5367 ++cmdbase;
5368
Bram Moolenaar1c465442017-03-12 20:10:05 +01005369 if ((STRNICMP(cmdbase, "start", 5) == 0) && VIM_ISWHITE(cmdbase[5]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005370 {
5371 STARTUPINFO si;
5372 PROCESS_INFORMATION pi;
5373 DWORD flags = CREATE_NEW_CONSOLE;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01005374 INT n_show_cmd = SW_SHOWNORMAL;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005375 char_u *p;
5376
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01005377 ZeroMemory(&si, sizeof(si));
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005378 si.cb = sizeof(si);
5379 si.lpReserved = NULL;
5380 si.lpDesktop = NULL;
5381 si.lpTitle = NULL;
5382 si.dwFlags = 0;
5383 si.cbReserved2 = 0;
5384 si.lpReserved2 = NULL;
5385
5386 cmdbase = skipwhite(cmdbase + 5);
5387 if ((STRNICMP(cmdbase, "/min", 4) == 0)
Bram Moolenaar1c465442017-03-12 20:10:05 +01005388 && VIM_ISWHITE(cmdbase[4]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005389 {
5390 cmdbase = skipwhite(cmdbase + 4);
5391 si.dwFlags = STARTF_USESHOWWINDOW;
5392 si.wShowWindow = SW_SHOWMINNOACTIVE;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01005393 n_show_cmd = SW_SHOWMINNOACTIVE;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005394 }
5395 else if ((STRNICMP(cmdbase, "/b", 2) == 0)
Bram Moolenaar1c465442017-03-12 20:10:05 +01005396 && VIM_ISWHITE(cmdbase[2]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005397 {
5398 cmdbase = skipwhite(cmdbase + 2);
5399 flags = CREATE_NO_WINDOW;
5400 si.dwFlags = STARTF_USESTDHANDLES;
5401 si.hStdInput = CreateFile("\\\\.\\NUL", // File name
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005402 GENERIC_READ, // Access flags
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005403 0, // Share flags
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005404 NULL, // Security att.
5405 OPEN_EXISTING, // Open flags
5406 FILE_ATTRIBUTE_NORMAL, // File att.
5407 NULL); // Temp file
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005408 si.hStdOutput = si.hStdInput;
5409 si.hStdError = si.hStdInput;
5410 }
5411
Bram Moolenaar0f873732019-12-05 20:28:46 +01005412 // Remove a trailing ", ) and )" if they have a match
5413 // at the start of the command.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005414 if (cmdbase > cmd)
5415 {
5416 p = cmdbase + STRLEN(cmdbase);
5417 if (p > cmdbase && p[-1] == '"' && *cmd == '"')
5418 *--p = NUL;
5419 if (p > cmdbase && p[-1] == ')'
5420 && (*cmd =='(' || cmd[1] == '('))
5421 *--p = NUL;
5422 }
5423
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005424 newcmd = cmdbase;
5425 unescape_shellxquote(cmdbase, p_sxe);
5426
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005427 /*
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005428 * If creating new console, arguments are passed to the
5429 * 'cmd.exe' as-is. If it's not, arguments are not treated
5430 * correctly for current 'cmd.exe'. So unescape characters in
5431 * shellxescape except '|' for avoiding to be treated as
5432 * argument to them. Pass the arguments to sub-shell.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005433 */
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005434 if (flags != CREATE_NEW_CONSOLE)
5435 {
5436 char_u *subcmd;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01005437 char_u *cmd_shell = mch_getenv("COMSPEC");
5438
5439 if (cmd_shell == NULL || *cmd_shell == NUL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01005440 cmd_shell = (char_u *)default_shell();
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005441
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01005442 subcmd = vim_strsave_escaped_ext(cmdbase,
5443 (char_u *)"|", '^', FALSE);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005444 if (subcmd != NULL)
5445 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005446 // make "cmd.exe /c arguments"
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005447 cmdlen = STRLEN(cmd_shell) + STRLEN(subcmd) + 5;
Bram Moolenaar18a4ba22019-05-24 19:39:03 +02005448 newcmd = alloc(cmdlen);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005449 if (newcmd != NULL)
5450 vim_snprintf((char *)newcmd, cmdlen, "%s /c %s",
Bram Moolenaaree7d1002012-02-22 15:34:08 +01005451 cmd_shell, subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005452 else
5453 newcmd = cmdbase;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01005454 vim_free(subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005455 }
5456 }
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005457
5458 /*
5459 * Now, start the command as a process, so that it doesn't
5460 * inherit our handles which causes unpleasant dangling swap
5461 * files if we exit before the spawned process
5462 */
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005463 if (vim_create_process((char *)newcmd, FALSE, flags,
5464 &si, &pi, NULL, NULL))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005465 x = 0;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01005466 else if (vim_shell_execute((char *)newcmd, n_show_cmd)
5467 > (HINSTANCE)32)
5468 x = 0;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005469 else
5470 {
5471 x = -1;
Bram Moolenaar4f974752019-02-17 17:44:42 +01005472#ifdef FEAT_GUI_MSWIN
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005473# ifdef VIMDLL
5474 if (gui.in_use)
5475# endif
Bram Moolenaarac78dd42022-01-02 19:25:26 +00005476 emsg(_(e_command_not_found));
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005477#endif
5478 }
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005479
5480 if (newcmd != cmdbase)
5481 vim_free(newcmd);
5482
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01005483 if (si.dwFlags == STARTF_USESTDHANDLES && si.hStdInput != NULL)
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005484 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005485 // Close the handle to \\.\NUL created above.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005486 CloseHandle(si.hStdInput);
5487 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01005488 // Close the handles to the subprocess, so that it goes away
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005489 CloseHandle(pi.hThread);
5490 CloseHandle(pi.hProcess);
5491 }
5492 else
5493 {
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005494 cmdlen =
Bram Moolenaar4f974752019-02-17 17:44:42 +01005495#ifdef FEAT_GUI_MSWIN
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02005496 ((gui.in_use || gui.starting) ?
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005497 (!s_dont_use_vimrun && p_stmp ?
5498 STRLEN(vimrun_path) : STRLEN(p_sh) + STRLEN(p_shcf))
5499 : 0) +
Bram Moolenaar071d4272004-06-13 20:20:40 +00005500#endif
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005501 STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10;
Bram Moolenaar0fde2902008-03-16 13:54:13 +00005502
Bram Moolenaar18a4ba22019-05-24 19:39:03 +02005503 newcmd = alloc(cmdlen);
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005504 if (newcmd != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005505 {
Bram Moolenaar4f974752019-02-17 17:44:42 +01005506#if defined(FEAT_GUI_MSWIN)
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005507 if (
5508# ifdef VIMDLL
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02005509 (gui.in_use || gui.starting) &&
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005510# endif
5511 need_vimrun_warning)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005512 {
Bram Moolenaar63e43442016-11-19 17:28:44 +01005513 char *msg = _("VIMRUN.EXE not found in your $PATH.\n"
5514 "External commands will not pause after completion.\n"
5515 "See :help win32-vimrun for more information.");
5516 char *title = _("Vim Warning");
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005517 WCHAR *wmsg = enc_to_utf16((char_u *)msg, NULL);
5518 WCHAR *wtitle = enc_to_utf16((char_u *)title, NULL);
Bram Moolenaar63e43442016-11-19 17:28:44 +01005519
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005520 if (wmsg != NULL && wtitle != NULL)
5521 MessageBoxW(NULL, wmsg, wtitle, MB_ICONWARNING);
5522 vim_free(wmsg);
5523 vim_free(wtitle);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005524 need_vimrun_warning = FALSE;
5525 }
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005526 if (
5527# ifdef VIMDLL
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02005528 (gui.in_use || gui.starting) &&
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005529# endif
5530 !s_dont_use_vimrun && p_stmp)
Bram Moolenaarfcc4d922019-05-24 13:32:36 +02005531 // Use vimrun to execute the command. It opens a console
5532 // window, which can be closed without killing Vim.
Bram Moolenaarcc448b32010-07-14 16:52:17 +02005533 vim_snprintf((char *)newcmd, cmdlen, "%s%s%s %s %s",
Bram Moolenaar071d4272004-06-13 20:20:40 +00005534 vimrun_path,
5535 (msg_silent != 0 || (options & SHELL_DOOUT))
5536 ? "-s " : "",
5537 p_sh, p_shcf, cmd);
Bram Moolenaarfcc4d922019-05-24 13:32:36 +02005538 else if (
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005539# ifdef VIMDLL
Bram Moolenaarfcc4d922019-05-24 13:32:36 +02005540 (gui.in_use || gui.starting) &&
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005541# endif
Bram Moolenaar0e6bfb92019-07-31 20:53:56 +02005542 s_dont_use_vimrun && STRCMP(p_shcf, "/c") == 0)
Bram Moolenaarfcc4d922019-05-24 13:32:36 +02005543 // workaround for the case that "vimrun" does not exist
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005544 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s %s %s",
5545 p_sh, p_shcf, p_sh, p_shcf, cmd);
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005546 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00005547#endif
Bram Moolenaarcc448b32010-07-14 16:52:17 +02005548 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s",
Bram Moolenaar0fde2902008-03-16 13:54:13 +00005549 p_sh, p_shcf, cmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005550 x = mch_system((char *)newcmd, options);
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005551 vim_free(newcmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005552 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005553 }
5554 }
5555
5556 if (tmode == TMODE_RAW)
Bram Moolenaar3b1f18f2020-05-16 23:15:08 +02005557 {
5558 // The shell may have messed with the mode, always set it.
5559 cur_tmode = TMODE_UNKNOWN;
Bram Moolenaar0f873732019-12-05 20:28:46 +01005560 settmode(TMODE_RAW); // set to raw mode
Bram Moolenaar3b1f18f2020-05-16 23:15:08 +02005561 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005562
Bram Moolenaar0f873732019-12-05 20:28:46 +01005563 // Print the return value, unless "vimrun" was used.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005564 if (x != 0 && !(options & SHELL_SILENT) && !emsg_silent
Bram Moolenaar4f974752019-02-17 17:44:42 +01005565#if defined(FEAT_GUI_MSWIN)
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02005566 && ((gui.in_use || gui.starting) ?
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005567 ((options & SHELL_DOOUT) || s_dont_use_vimrun || !p_stmp) : 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005568#endif
5569 )
5570 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005571 smsg(_("shell returned %d"), x);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005572 msg_putchar('\n');
5573 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005574 resettitle();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005575
5576 signal(SIGINT, SIG_DFL);
5577#if defined(__GNUC__) && !defined(__MINGW32__)
5578 signal(SIGKILL, SIG_DFL);
5579#else
5580 signal(SIGBREAK, SIG_DFL);
5581#endif
5582 signal(SIGILL, SIG_DFL);
5583 signal(SIGFPE, SIG_DFL);
5584 signal(SIGSEGV, SIG_DFL);
5585 signal(SIGTERM, SIG_DFL);
5586 signal(SIGABRT, SIG_DFL);
5587
5588 return x;
5589}
5590
Bram Moolenaar509ce2a2016-03-11 22:52:15 +01005591#if defined(FEAT_JOB_CHANNEL) || defined(PROTO)
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005592 static HANDLE
5593job_io_file_open(
Bram Moolenaar972c3b82017-01-12 21:44:49 +01005594 char_u *fname,
5595 DWORD dwDesiredAccess,
5596 DWORD dwShareMode,
5597 LPSECURITY_ATTRIBUTES lpSecurityAttributes,
5598 DWORD dwCreationDisposition,
5599 DWORD dwFlagsAndAttributes)
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005600{
5601 HANDLE h;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005602 WCHAR *wn;
Bram Moolenaara12a1612019-01-24 16:39:02 +01005603
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005604 wn = enc_to_utf16(fname, NULL);
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005605 if (wn == NULL)
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005606 return INVALID_HANDLE_VALUE;
5607
5608 h = CreateFileW(wn, dwDesiredAccess, dwShareMode,
5609 lpSecurityAttributes, dwCreationDisposition,
5610 dwFlagsAndAttributes, NULL);
5611 vim_free(wn);
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005612 return h;
5613}
5614
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005615/*
5616 * Turn the dictionary "env" into a NUL separated list that can be used as the
5617 * environment argument of vim_create_process().
5618 */
Bram Moolenaarba6febd2017-10-30 21:56:23 +01005619 void
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005620win32_build_env(dict_T *env, garray_T *gap, int is_terminal)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005621{
5622 hashitem_T *hi;
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005623 long_u todo = env != NULL ? env->dv_hashtab.ht_used : 0;
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005624 LPVOID base = GetEnvironmentStringsW();
5625
Bram Moolenaar0f873732019-12-05 20:28:46 +01005626 // for last \0
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005627 if (ga_grow(gap, 1) == FAIL)
5628 return;
5629
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005630 if (env != NULL)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005631 {
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005632 for (hi = env->dv_hashtab.ht_array; todo > 0; ++hi)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005633 {
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005634 if (!HASHITEM_EMPTY(hi))
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005635 {
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005636 typval_T *item = &dict_lookup(hi)->di_tv;
5637 WCHAR *wkey = enc_to_utf16((char_u *)hi->hi_key, NULL);
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005638 WCHAR *wval = enc_to_utf16(tv_get_string(item), NULL);
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005639 --todo;
5640 if (wkey != NULL && wval != NULL)
5641 {
5642 size_t n;
5643 size_t lkey = wcslen(wkey);
5644 size_t lval = wcslen(wval);
Bram Moolenaar60104f12017-08-14 23:25:04 +02005645
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005646 if (ga_grow(gap, (int)(lkey + lval + 2)) != OK)
5647 continue;
5648 for (n = 0; n < lkey; n++)
5649 *((WCHAR*)gap->ga_data + gap->ga_len++) = wkey[n];
5650 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'=';
5651 for (n = 0; n < lval; n++)
5652 *((WCHAR*)gap->ga_data + gap->ga_len++) = wval[n];
5653 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5654 }
Bram Moolenaarbdace832019-03-02 10:13:42 +01005655 vim_free(wkey);
5656 vim_free(wval);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005657 }
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005658 }
5659 }
5660
Bram Moolenaar355757a2020-02-10 22:06:32 +01005661 if (base)
5662 {
5663 WCHAR *p = (WCHAR*) base;
5664
5665 // for last \0
5666 if (ga_grow(gap, 1) == FAIL)
5667 return;
5668
5669 while (*p != 0 || *(p + 1) != 0)
5670 {
5671 if (ga_grow(gap, 1) == OK)
5672 *((WCHAR*)gap->ga_data + gap->ga_len++) = *p;
5673 p++;
5674 }
5675 FreeEnvironmentStrings(base);
5676 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5677 }
5678
Bram Moolenaar493359e2018-06-12 20:25:52 +02005679# if defined(FEAT_CLIENTSERVER) || defined(FEAT_TERMINAL)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005680 {
Bram Moolenaar493359e2018-06-12 20:25:52 +02005681# ifdef FEAT_CLIENTSERVER
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005682 char_u *servername = get_vim_var_str(VV_SEND_SERVER);
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005683 size_t servername_len = STRLEN(servername);
Bram Moolenaar493359e2018-06-12 20:25:52 +02005684# endif
5685# ifdef FEAT_TERMINAL
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005686 char_u *version = get_vim_var_str(VV_VERSION);
5687 size_t version_len = STRLEN(version);
Bram Moolenaar493359e2018-06-12 20:25:52 +02005688# endif
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005689 // size of "VIM_SERVERNAME=" and value,
5690 // plus "VIM_TERMINAL=" and value,
5691 // plus two terminating NULs
5692 size_t n = 0
Bram Moolenaar493359e2018-06-12 20:25:52 +02005693# ifdef FEAT_CLIENTSERVER
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005694 + 15 + servername_len
Bram Moolenaar493359e2018-06-12 20:25:52 +02005695# endif
5696# ifdef FEAT_TERMINAL
5697 + 13 + version_len + 2
5698# endif
5699 ;
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005700
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005701 if (ga_grow(gap, (int)n) == OK)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005702 {
Bram Moolenaar493359e2018-06-12 20:25:52 +02005703# ifdef FEAT_CLIENTSERVER
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005704 for (n = 0; n < 15; n++)
5705 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5706 (WCHAR)"VIM_SERVERNAME="[n];
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005707 for (n = 0; n < servername_len; n++)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005708 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5709 (WCHAR)servername[n];
5710 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
Bram Moolenaar493359e2018-06-12 20:25:52 +02005711# endif
5712# ifdef FEAT_TERMINAL
5713 if (is_terminal)
5714 {
5715 for (n = 0; n < 13; n++)
5716 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5717 (WCHAR)"VIM_TERMINAL="[n];
5718 for (n = 0; n < version_len; n++)
5719 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5720 (WCHAR)version[n];
5721 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5722 }
5723# endif
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005724 }
5725 }
Bram Moolenaar79c6b512018-06-12 21:11:12 +02005726# endif
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005727}
5728
Bram Moolenaarb091f302019-01-19 14:37:00 +01005729/*
5730 * Create a pair of pipes.
5731 * Return TRUE for success, FALSE for failure.
5732 */
5733 static BOOL
5734create_pipe_pair(HANDLE handles[2])
5735{
5736 static LONG s;
5737 char name[64];
5738 SECURITY_ATTRIBUTES sa;
5739
5740 sprintf(name, "\\\\?\\pipe\\vim-%08lx-%08lx",
5741 GetCurrentProcessId(),
5742 InterlockedIncrement(&s));
5743
5744 // Create named pipe. Max size of named pipe is 65535.
5745 handles[1] = CreateNamedPipe(
5746 name,
5747 PIPE_ACCESS_OUTBOUND | FILE_FLAG_OVERLAPPED,
5748 PIPE_TYPE_BYTE | PIPE_NOWAIT,
Bram Moolenaar24058382019-01-24 23:11:49 +01005749 1, MAX_NAMED_PIPE_SIZE, 0, 0, NULL);
Bram Moolenaarb091f302019-01-19 14:37:00 +01005750
5751 if (handles[1] == INVALID_HANDLE_VALUE)
5752 return FALSE;
5753
5754 sa.nLength = sizeof(sa);
5755 sa.bInheritHandle = TRUE;
5756 sa.lpSecurityDescriptor = NULL;
5757
5758 handles[0] = CreateFile(name,
5759 FILE_GENERIC_READ,
5760 FILE_SHARE_READ, &sa,
5761 OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
5762
5763 if (handles[0] == INVALID_HANDLE_VALUE)
5764 {
Bram Moolenaar6982f422019-02-16 16:48:01 +01005765 CloseHandle(handles[1]);
Bram Moolenaarb091f302019-01-19 14:37:00 +01005766 return FALSE;
5767 }
5768
5769 return TRUE;
5770}
5771
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005772 void
Bram Moolenaar5a1feb82017-07-22 18:04:08 +02005773mch_job_start(char *cmd, job_T *job, jobopt_T *options)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005774{
5775 STARTUPINFO si;
5776 PROCESS_INFORMATION pi;
Bram Moolenaar14207f42016-10-27 21:13:10 +02005777 HANDLE jo;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005778 SECURITY_ATTRIBUTES saAttr;
5779 channel_T *channel = NULL;
Bram Moolenaard8070362016-02-15 21:56:54 +01005780 HANDLE ifd[2];
5781 HANDLE ofd[2];
5782 HANDLE efd[2];
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005783 garray_T ga;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005784
5785 int use_null_for_in = options->jo_io[PART_IN] == JIO_NULL;
5786 int use_null_for_out = options->jo_io[PART_OUT] == JIO_NULL;
5787 int use_null_for_err = options->jo_io[PART_ERR] == JIO_NULL;
5788 int use_file_for_in = options->jo_io[PART_IN] == JIO_FILE;
5789 int use_file_for_out = options->jo_io[PART_OUT] == JIO_FILE;
5790 int use_file_for_err = options->jo_io[PART_ERR] == JIO_FILE;
5791 int use_out_for_err = options->jo_io[PART_ERR] == JIO_OUT;
5792
5793 if (use_out_for_err && use_null_for_out)
5794 use_null_for_err = TRUE;
Bram Moolenaard8070362016-02-15 21:56:54 +01005795
5796 ifd[0] = INVALID_HANDLE_VALUE;
5797 ifd[1] = INVALID_HANDLE_VALUE;
5798 ofd[0] = INVALID_HANDLE_VALUE;
5799 ofd[1] = INVALID_HANDLE_VALUE;
5800 efd[0] = INVALID_HANDLE_VALUE;
5801 efd[1] = INVALID_HANDLE_VALUE;
Bram Moolenaar04935fb2022-01-08 16:19:22 +00005802 ga_init2(&ga, sizeof(wchar_t), 500);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005803
Bram Moolenaar14207f42016-10-27 21:13:10 +02005804 jo = CreateJobObject(NULL, NULL);
5805 if (jo == NULL)
5806 {
5807 job->jv_status = JOB_FAILED;
5808 goto failed;
5809 }
5810
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005811 if (options->jo_env != NULL)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005812 win32_build_env(options->jo_env, &ga, FALSE);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005813
Bram Moolenaar76467df2016-02-12 19:30:26 +01005814 ZeroMemory(&pi, sizeof(pi));
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005815 ZeroMemory(&si, sizeof(si));
5816 si.cb = sizeof(si);
Bram Moolenaard8070362016-02-15 21:56:54 +01005817 si.dwFlags |= STARTF_USESHOWWINDOW;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005818 si.wShowWindow = SW_HIDE;
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005819
Bram Moolenaard8070362016-02-15 21:56:54 +01005820 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
5821 saAttr.bInheritHandle = TRUE;
5822 saAttr.lpSecurityDescriptor = NULL;
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005823
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005824 if (use_file_for_in)
5825 {
5826 char_u *fname = options->jo_io_name[PART_IN];
5827
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005828 ifd[0] = job_io_file_open(fname, GENERIC_READ,
5829 FILE_SHARE_READ | FILE_SHARE_WRITE,
5830 &saAttr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL);
5831 if (ifd[0] == INVALID_HANDLE_VALUE)
Bram Moolenaar94d01912016-03-08 13:48:51 +01005832 {
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00005833 semsg(_(e_cant_open_file_str), fname);
Bram Moolenaar94d01912016-03-08 13:48:51 +01005834 goto failed;
5835 }
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005836 }
Bram Moolenaarb091f302019-01-19 14:37:00 +01005837 else if (!use_null_for_in
5838 && (!create_pipe_pair(ifd)
5839 || !SetHandleInformation(ifd[1], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005840 goto failed;
5841
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005842 if (use_file_for_out)
5843 {
5844 char_u *fname = options->jo_io_name[PART_OUT];
5845
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005846 ofd[1] = job_io_file_open(fname, GENERIC_WRITE,
5847 FILE_SHARE_READ | FILE_SHARE_WRITE,
5848 &saAttr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL);
5849 if (ofd[1] == INVALID_HANDLE_VALUE)
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005850 {
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00005851 semsg(_(e_cant_open_file_str), fname);
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005852 goto failed;
5853 }
5854 }
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005855 else if (!use_null_for_out &&
5856 (!CreatePipe(&ofd[0], &ofd[1], &saAttr, 0)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005857 || !SetHandleInformation(ofd[0], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005858 goto failed;
5859
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005860 if (use_file_for_err)
5861 {
5862 char_u *fname = options->jo_io_name[PART_ERR];
5863
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005864 efd[1] = job_io_file_open(fname, GENERIC_WRITE,
5865 FILE_SHARE_READ | FILE_SHARE_WRITE,
5866 &saAttr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL);
5867 if (efd[1] == INVALID_HANDLE_VALUE)
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005868 {
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00005869 semsg(_(e_cant_open_file_str), fname);
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005870 goto failed;
5871 }
5872 }
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005873 else if (!use_out_for_err && !use_null_for_err &&
5874 (!CreatePipe(&efd[0], &efd[1], &saAttr, 0)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005875 || !SetHandleInformation(efd[0], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaard8070362016-02-15 21:56:54 +01005876 goto failed;
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005877
Bram Moolenaard8070362016-02-15 21:56:54 +01005878 si.dwFlags |= STARTF_USESTDHANDLES;
5879 si.hStdInput = ifd[0];
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005880 si.hStdOutput = ofd[1];
5881 si.hStdError = use_out_for_err ? ofd[1] : efd[1];
5882
5883 if (!use_null_for_in || !use_null_for_out || !use_null_for_err)
5884 {
Bram Moolenaarde279892016-03-11 22:19:44 +01005885 if (options->jo_set & JO_CHANNEL)
5886 {
5887 channel = options->jo_channel;
5888 if (channel != NULL)
5889 ++channel->ch_refcount;
5890 }
5891 else
5892 channel = add_channel();
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005893 if (channel == NULL)
5894 goto failed;
5895 }
Bram Moolenaard8070362016-02-15 21:56:54 +01005896
5897 if (!vim_create_process(cmd, TRUE,
Bram Moolenaar14207f42016-10-27 21:13:10 +02005898 CREATE_SUSPENDED |
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005899 CREATE_DEFAULT_ERROR_MODE |
5900 CREATE_NEW_PROCESS_GROUP |
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005901 CREATE_UNICODE_ENVIRONMENT |
Bram Moolenaar76467df2016-02-12 19:30:26 +01005902 CREATE_NEW_CONSOLE,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005903 &si, &pi,
5904 ga.ga_data,
5905 (char *)options->jo_cwd))
Bram Moolenaar76467df2016-02-12 19:30:26 +01005906 {
Bram Moolenaar14207f42016-10-27 21:13:10 +02005907 CloseHandle(jo);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005908 job->jv_status = JOB_FAILED;
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005909 goto failed;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005910 }
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005911
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005912 ga_clear(&ga);
5913
Bram Moolenaar14207f42016-10-27 21:13:10 +02005914 if (!AssignProcessToJobObject(jo, pi.hProcess))
5915 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005916 // if failing, switch the way to terminate
5917 // process with TerminateProcess.
Bram Moolenaar14207f42016-10-27 21:13:10 +02005918 CloseHandle(jo);
5919 jo = NULL;
5920 }
5921 ResumeThread(pi.hThread);
Bram Moolenaar75578a32016-03-10 16:33:31 +01005922 CloseHandle(pi.hThread);
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005923 job->jv_proc_info = pi;
Bram Moolenaar14207f42016-10-27 21:13:10 +02005924 job->jv_job_object = jo;
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005925 job->jv_status = JOB_STARTED;
5926
Bram Moolenaar641ad6c2016-09-01 18:32:11 +02005927 CloseHandle(ifd[0]);
5928 CloseHandle(ofd[1]);
5929 if (!use_out_for_err && !use_null_for_err)
Bram Moolenaarc25558b2016-03-03 21:02:23 +01005930 CloseHandle(efd[1]);
Bram Moolenaard8070362016-02-15 21:56:54 +01005931
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005932 job->jv_channel = channel;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005933 if (channel != NULL)
5934 {
5935 channel_set_pipes(channel,
5936 use_file_for_in || use_null_for_in
5937 ? INVALID_FD : (sock_T)ifd[1],
5938 use_file_for_out || use_null_for_out
5939 ? INVALID_FD : (sock_T)ofd[0],
5940 use_out_for_err || use_file_for_err || use_null_for_err
5941 ? INVALID_FD : (sock_T)efd[0]);
5942 channel_set_job(channel, job, options);
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005943 }
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005944 return;
5945
5946failed:
Bram Moolenaard8070362016-02-15 21:56:54 +01005947 CloseHandle(ifd[0]);
5948 CloseHandle(ofd[0]);
5949 CloseHandle(efd[0]);
5950 CloseHandle(ifd[1]);
5951 CloseHandle(ofd[1]);
5952 CloseHandle(efd[1]);
Bram Moolenaarde279892016-03-11 22:19:44 +01005953 channel_unref(channel);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005954 ga_clear(&ga);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005955}
5956
5957 char *
5958mch_job_status(job_T *job)
5959{
5960 DWORD dwExitCode = 0;
5961
Bram Moolenaar76467df2016-02-12 19:30:26 +01005962 if (!GetExitCodeProcess(job->jv_proc_info.hProcess, &dwExitCode)
5963 || dwExitCode != STILL_ACTIVE)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005964 {
Bram Moolenaareab089d2016-02-21 19:32:02 +01005965 job->jv_exitval = (int)dwExitCode;
Bram Moolenaar7df915d2016-11-17 17:25:32 +01005966 if (job->jv_status < JOB_ENDED)
Bram Moolenaar97792de2016-10-15 18:36:49 +02005967 {
5968 ch_log(job->jv_channel, "Job ended");
5969 job->jv_status = JOB_ENDED;
5970 }
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005971 return "dead";
5972 }
5973 return "run";
5974}
5975
Bram Moolenaar97792de2016-10-15 18:36:49 +02005976 job_T *
5977mch_detect_ended_job(job_T *job_list)
5978{
5979 HANDLE jobHandles[MAXIMUM_WAIT_OBJECTS];
5980 job_T *jobArray[MAXIMUM_WAIT_OBJECTS];
5981 job_T *job = job_list;
5982
5983 while (job != NULL)
5984 {
5985 DWORD n;
5986 DWORD result;
5987
5988 for (n = 0; n < MAXIMUM_WAIT_OBJECTS
5989 && job != NULL; job = job->jv_next)
5990 {
5991 if (job->jv_status == JOB_STARTED)
5992 {
5993 jobHandles[n] = job->jv_proc_info.hProcess;
5994 jobArray[n] = job;
5995 ++n;
5996 }
5997 }
5998 if (n == 0)
5999 continue;
6000 result = WaitForMultipleObjects(n, jobHandles, FALSE, 0);
6001 if (result >= WAIT_OBJECT_0 && result < WAIT_OBJECT_0 + n)
6002 {
6003 job_T *wait_job = jobArray[result - WAIT_OBJECT_0];
6004
6005 if (STRCMP(mch_job_status(wait_job), "dead") == 0)
6006 return wait_job;
6007 }
6008 }
6009 return NULL;
6010}
6011
Bram Moolenaarfb630902016-10-29 14:55:00 +02006012 static BOOL
6013terminate_all(HANDLE process, int code)
6014{
6015 PROCESSENTRY32 pe;
6016 HANDLE h = INVALID_HANDLE_VALUE;
6017 DWORD pid = GetProcessId(process);
6018
6019 if (pid != 0)
6020 {
6021 h = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
6022 if (h != INVALID_HANDLE_VALUE)
6023 {
6024 pe.dwSize = sizeof(PROCESSENTRY32);
6025 if (!Process32First(h, &pe))
6026 goto theend;
6027
6028 do
6029 {
6030 if (pe.th32ParentProcessID == pid)
6031 {
6032 HANDLE ph = OpenProcess(
6033 PROCESS_ALL_ACCESS, FALSE, pe.th32ProcessID);
6034 if (ph != NULL)
6035 {
6036 terminate_all(ph, code);
6037 CloseHandle(ph);
6038 }
6039 }
6040 } while (Process32Next(h, &pe));
6041
6042 CloseHandle(h);
6043 }
6044 }
6045
6046theend:
6047 return TerminateProcess(process, code);
6048}
6049
6050/*
6051 * Send a (deadly) signal to "job".
6052 * Return FAIL if it didn't work.
6053 */
Bram Moolenaar942d6b22016-02-07 19:57:16 +01006054 int
Bram Moolenaar2d33e902017-08-11 16:31:54 +02006055mch_signal_job(job_T *job, char_u *how)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01006056{
Bram Moolenaar923d9262016-02-25 20:56:01 +01006057 int ret;
Bram Moolenaar76467df2016-02-12 19:30:26 +01006058
Bram Moolenaar923d9262016-02-25 20:56:01 +01006059 if (STRCMP(how, "term") == 0 || STRCMP(how, "kill") == 0 || *how == NUL)
Bram Moolenaar76467df2016-02-12 19:30:26 +01006060 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006061 // deadly signal
Bram Moolenaar14207f42016-10-27 21:13:10 +02006062 if (job->jv_job_object != NULL)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006063 {
6064 if (job->jv_channel != NULL && job->jv_channel->ch_anonymous_pipe)
6065 job->jv_channel->ch_killing = TRUE;
K.Takata135e1522022-01-29 15:27:58 +00006066 return TerminateJobObject(job->jv_job_object, (UINT)-1) ? OK : FAIL;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006067 }
Bram Moolenaarb3e195c2020-02-10 21:32:19 +01006068 return terminate_all(job->jv_proc_info.hProcess, -1) ? OK : FAIL;
Bram Moolenaar76467df2016-02-12 19:30:26 +01006069 }
6070
6071 if (!AttachConsole(job->jv_proc_info.dwProcessId))
6072 return FAIL;
6073 ret = GenerateConsoleCtrlEvent(
Bram Moolenaar923d9262016-02-25 20:56:01 +01006074 STRCMP(how, "int") == 0 ? CTRL_C_EVENT : CTRL_BREAK_EVENT,
6075 job->jv_proc_info.dwProcessId)
6076 ? OK : FAIL;
Bram Moolenaar76467df2016-02-12 19:30:26 +01006077 FreeConsole();
6078 return ret;
6079}
6080
6081/*
6082 * Clear the data related to "job".
6083 */
6084 void
6085mch_clear_job(job_T *job)
6086{
6087 if (job->jv_status != JOB_FAILED)
6088 {
Bram Moolenaar14207f42016-10-27 21:13:10 +02006089 if (job->jv_job_object != NULL)
6090 CloseHandle(job->jv_job_object);
Bram Moolenaar76467df2016-02-12 19:30:26 +01006091 CloseHandle(job->jv_proc_info.hProcess);
6092 }
Bram Moolenaar942d6b22016-02-07 19:57:16 +01006093}
6094#endif
6095
Bram Moolenaar071d4272004-06-13 20:20:40 +00006096
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006097#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006098
6099/*
6100 * Start termcap mode
6101 */
6102 static void
6103termcap_mode_start(void)
6104{
6105 DWORD cmodein;
6106
6107 if (g_fTermcapMode)
6108 return;
6109
Christopher Plewright1140b512022-11-12 18:46:05 +00006110 // VTP uses alternate screen buffer.
6111 // Switch to a new alternate screen buffer.
Christopher Plewrightc8b126d2022-12-22 13:45:23 +00006112 // But, not if running in a nested terminal
6113 if (use_alternate_screen_buffer)
Bram Moolenaar81ccbf12020-04-15 21:05:30 +02006114 vtp_printf("\033[?1049h");
6115
Bram Moolenaar071d4272004-06-13 20:20:40 +00006116 SaveConsoleBuffer(&g_cbNonTermcap);
6117
6118 if (g_cbTermcap.IsValid)
6119 {
6120 /*
6121 * We've been in termcap mode before. Restore certain screen
6122 * characteristics, including the buffer size and the window
6123 * size. Since we will be redrawing the screen, we don't need
6124 * to restore the actual contents of the buffer.
6125 */
6126 RestoreConsoleBuffer(&g_cbTermcap, FALSE);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006127 reset_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00006128 SetConsoleWindowInfo(g_hConOut, TRUE, &g_cbTermcap.Info.srWindow);
6129 Rows = g_cbTermcap.Info.dwSize.Y;
6130 Columns = g_cbTermcap.Info.dwSize.X;
6131 }
6132 else
6133 {
6134 /*
6135 * This is our first time entering termcap mode. Clear the console
6136 * screen buffer, and resize the buffer to match the current window
6137 * size. We will use this as the size of our editing environment.
6138 */
6139 ClearConsoleBuffer(g_attrCurrent);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006140 set_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00006141 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
6142 }
6143
Bram Moolenaar071d4272004-06-13 20:20:40 +00006144 resettitle();
Bram Moolenaar071d4272004-06-13 20:20:40 +00006145
6146 GetConsoleMode(g_hConIn, &cmodein);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006147 if (g_fMouseActive)
Wez Furlong6ef5ab52021-05-30 19:29:41 +02006148 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006149 cmodein |= ENABLE_MOUSE_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02006150 cmodein &= ~ENABLE_QUICK_EDIT_MODE;
6151 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006152 else
Wez Furlong6ef5ab52021-05-30 19:29:41 +02006153 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006154 cmodein &= ~ENABLE_MOUSE_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02006155 cmodein |= g_cmodein & ENABLE_QUICK_EDIT_MODE;
6156 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006157 cmodein |= ENABLE_WINDOW_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02006158 SetConsoleMode(g_hConIn, cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006159
6160 redraw_later_clear();
6161 g_fTermcapMode = TRUE;
6162}
6163
6164
6165/*
6166 * End termcap mode
6167 */
6168 static void
6169termcap_mode_end(void)
6170{
6171 DWORD cmodein;
6172 ConsoleBuffer *cb;
6173 COORD coord;
6174 DWORD dwDummy;
6175
6176 if (!g_fTermcapMode)
6177 return;
6178
6179 SaveConsoleBuffer(&g_cbTermcap);
6180
6181 GetConsoleMode(g_hConIn, &cmodein);
6182 cmodein &= ~(ENABLE_MOUSE_INPUT | ENABLE_WINDOW_INPUT);
Wez Furlong6ef5ab52021-05-30 19:29:41 +02006183 cmodein |= g_cmodein & ENABLE_QUICK_EDIT_MODE;
6184 SetConsoleMode(g_hConIn, cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006185
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006186# ifdef FEAT_RESTORE_ORIG_SCREEN
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01006187 cb = exiting ? &g_cbOrig : &g_cbNonTermcap;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006188# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00006189 cb = &g_cbNonTermcap;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006190# endif
Bram Moolenaar81ccbf12020-04-15 21:05:30 +02006191 RestoreConsoleBuffer(cb, p_rs);
Bram Moolenaardf543822020-01-30 11:53:59 +01006192 restore_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00006193
Christopher Plewright1140b512022-11-12 18:46:05 +00006194 // VTP uses alternate screen buffer.
6195 // Switch back to main screen buffer.
Christopher Plewrightc8b126d2022-12-22 13:45:23 +00006196 if (exiting && use_alternate_screen_buffer)
Christopher Plewright1140b512022-11-12 18:46:05 +00006197 vtp_printf("\033[?1049l");
6198
6199 if (!USE_WT && (p_rs || exiting))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006200 {
6201 /*
6202 * Clear anything that happens to be on the current line.
6203 */
6204 coord.X = 0;
6205 coord.Y = (SHORT) (p_rs ? cb->Info.dwCursorPosition.Y : (Rows - 1));
Christopher Plewright1140b512022-11-12 18:46:05 +00006206 if (!vtp_working)
6207 FillConsoleOutputCharacter(g_hConOut, ' ',
6208 cb->Info.dwSize.X, coord, &dwDummy);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006209 /*
6210 * The following is just for aesthetics. If we are exiting without
6211 * restoring the screen, then we want to have a prompt string
6212 * appear at the bottom line. However, the command interpreter
6213 * seems to always advance the cursor one line before displaying
6214 * the prompt string, which causes the screen to scroll. To
6215 * counter this, move the cursor up one line before exiting.
6216 */
6217 if (exiting && !p_rs)
6218 coord.Y--;
6219 /*
6220 * Position the cursor at the leftmost column of the desired row.
6221 */
Bram Moolenaar81ccbf12020-04-15 21:05:30 +02006222 SetConsoleCursorPosition(g_hConOut, coord);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006223 }
Christopher Plewright1140b512022-11-12 18:46:05 +00006224 SetConsoleCursorInfo(g_hConOut, &g_cci);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006225 g_fTermcapMode = FALSE;
6226}
Christopher Plewright38804d62022-11-09 23:55:52 +00006227#endif // !FEAT_GUI_MSWIN || VIMDLL
Bram Moolenaar071d4272004-06-13 20:20:40 +00006228
6229
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006230#if defined(FEAT_GUI_MSWIN) && !defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006231 void
6232mch_write(
Bram Moolenaar1266d672017-02-01 13:43:36 +01006233 char_u *s UNUSED,
6234 int len UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006235{
Bram Moolenaar0f873732019-12-05 20:28:46 +01006236 // never used
Bram Moolenaar071d4272004-06-13 20:20:40 +00006237}
6238
6239#else
6240
6241/*
6242 * clear `n' chars, starting from `coord'
6243 */
6244 static void
6245clear_chars(
6246 COORD coord,
6247 DWORD n)
6248{
Christopher Plewright38804d62022-11-09 23:55:52 +00006249 if (!vtp_working)
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006250 {
6251 DWORD dwDummy;
6252
6253 FillConsoleOutputCharacter(g_hConOut, ' ', n, coord, &dwDummy);
6254 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, n, coord,
6255 &dwDummy);
6256 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006257 else
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02006258 {
6259 set_console_color_rgb();
6260 gotoxy(coord.X + 1, coord.Y + 1);
6261 vtp_printf("\033[%dX", n);
6262 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006263}
6264
6265
6266/*
6267 * Clear the screen
6268 */
6269 static void
6270clear_screen(void)
6271{
6272 g_coord.X = g_coord.Y = 0;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006273
Christopher Plewright38804d62022-11-09 23:55:52 +00006274 if (!vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006275 clear_chars(g_coord, Rows * Columns);
6276 else
6277 {
6278 set_console_color_rgb();
6279 gotoxy(1, 1);
6280 vtp_printf("\033[2J");
6281 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006282}
6283
6284
6285/*
6286 * Clear to end of display
6287 */
6288 static void
6289clear_to_end_of_display(void)
6290{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006291 COORD save = g_coord;
6292
Christopher Plewright38804d62022-11-09 23:55:52 +00006293 if (!vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006294 clear_chars(g_coord, (Rows - g_coord.Y - 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006295 * Columns + (Columns - g_coord.X));
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006296 else
6297 {
6298 set_console_color_rgb();
6299 gotoxy(g_coord.X + 1, g_coord.Y + 1);
6300 vtp_printf("\033[0J");
6301
6302 gotoxy(save.X + 1, save.Y + 1);
6303 g_coord = save;
6304 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006305}
6306
6307
6308/*
6309 * Clear to end of line
6310 */
6311 static void
6312clear_to_end_of_line(void)
6313{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006314 COORD save = g_coord;
6315
Christopher Plewright38804d62022-11-09 23:55:52 +00006316 if (!vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006317 clear_chars(g_coord, Columns - g_coord.X);
6318 else
6319 {
6320 set_console_color_rgb();
6321 gotoxy(g_coord.X + 1, g_coord.Y + 1);
6322 vtp_printf("\033[0K");
6323
6324 gotoxy(save.X + 1, save.Y + 1);
6325 g_coord = save;
6326 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006327}
6328
6329
6330/*
6331 * Scroll the scroll region up by `cLines' lines
6332 */
6333 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006334scroll(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006335{
6336 COORD oldcoord = g_coord;
6337
6338 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
6339 delete_lines(cLines);
6340
6341 g_coord = oldcoord;
6342}
6343
6344
6345/*
6346 * Set the scroll region
6347 */
6348 static void
6349set_scroll_region(
6350 unsigned left,
6351 unsigned top,
6352 unsigned right,
6353 unsigned bottom)
6354{
6355 if (left >= right
6356 || top >= bottom
6357 || right > (unsigned) Columns - 1
6358 || bottom > (unsigned) Rows - 1)
6359 return;
6360
6361 g_srScrollRegion.Left = left;
6362 g_srScrollRegion.Top = top;
6363 g_srScrollRegion.Right = right;
6364 g_srScrollRegion.Bottom = bottom;
Bram Moolenaar6982f422019-02-16 16:48:01 +01006365}
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006366
Bram Moolenaar6982f422019-02-16 16:48:01 +01006367 static void
6368set_scroll_region_tb(
6369 unsigned top,
6370 unsigned bottom)
6371{
6372 if (top >= bottom || bottom > (unsigned)Rows - 1)
6373 return;
6374
6375 g_srScrollRegion.Top = top;
6376 g_srScrollRegion.Bottom = bottom;
6377}
6378
6379 static void
6380set_scroll_region_lr(
6381 unsigned left,
6382 unsigned right)
6383{
6384 if (left >= right || right > (unsigned)Columns - 1)
6385 return;
6386
6387 g_srScrollRegion.Left = left;
6388 g_srScrollRegion.Right = right;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006389}
6390
6391
6392/*
6393 * Insert `cLines' lines at the current cursor position
6394 */
6395 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006396insert_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006397{
Bram Moolenaar6982f422019-02-16 16:48:01 +01006398 SMALL_RECT source, clip;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006399 COORD dest;
6400 CHAR_INFO fill;
6401
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006402 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
6403
Bram Moolenaar6982f422019-02-16 16:48:01 +01006404 dest.X = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006405 dest.Y = g_coord.Y + cLines;
6406
Bram Moolenaar6982f422019-02-16 16:48:01 +01006407 source.Left = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006408 source.Top = g_coord.Y;
6409 source.Right = g_srScrollRegion.Right;
6410 source.Bottom = g_srScrollRegion.Bottom - cLines;
6411
Bram Moolenaar6982f422019-02-16 16:48:01 +01006412 clip.Left = g_srScrollRegion.Left;
6413 clip.Top = g_coord.Y;
6414 clip.Right = g_srScrollRegion.Right;
6415 clip.Bottom = g_srScrollRegion.Bottom;
6416
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006417 fill.Char.AsciiChar = ' ';
Christopher Plewright38804d62022-11-09 23:55:52 +00006418 if (!(vtp_working
K.Takata161b6ac2022-11-14 15:31:07 +00006419# ifdef FEAT_TERMGUICOLORS
Christopher Plewright38804d62022-11-09 23:55:52 +00006420 && (p_tgc || t_colors >= 256)
K.Takata161b6ac2022-11-14 15:31:07 +00006421# endif
Christopher Plewright38804d62022-11-09 23:55:52 +00006422 ))
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006423 fill.Attributes = g_attrCurrent;
6424 else
6425 fill.Attributes = g_attrDefault;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006426
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006427 set_console_color_rgb();
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006428
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006429 ScrollConsoleScreenBuffer(g_hConOut, &source, &clip, dest, &fill);
6430
Bram Moolenaar6982f422019-02-16 16:48:01 +01006431 // Here we have to deal with a win32 console flake: If the scroll
6432 // region looks like abc and we scroll c to a and fill with d we get
6433 // cbd... if we scroll block c one line at a time to a, we get cdd...
6434 // vim expects cdd consistently... So we have to deal with that
6435 // here... (this also occurs scrolling the same way in the other
6436 // direction).
Bram Moolenaar071d4272004-06-13 20:20:40 +00006437
6438 if (source.Bottom < dest.Y)
6439 {
6440 COORD coord;
Bram Moolenaar6982f422019-02-16 16:48:01 +01006441 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006442
Bram Moolenaar6982f422019-02-16 16:48:01 +01006443 coord.X = source.Left;
6444 for (i = clip.Top; i < dest.Y; ++i)
6445 {
6446 coord.Y = i;
6447 clear_chars(coord, source.Right - source.Left + 1);
6448 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006449 }
Bram Moolenaar06b7b582020-05-30 17:49:25 +02006450
Christopher Plewright38804d62022-11-09 23:55:52 +00006451 if (vtp_working)
Bram Moolenaar06b7b582020-05-30 17:49:25 +02006452 {
6453 COORD coord;
6454 int i;
6455
6456 coord.X = source.Left;
6457 for (i = source.Top; i < dest.Y; ++i)
6458 {
6459 coord.Y = i;
6460 clear_chars(coord, source.Right - source.Left + 1);
6461 }
6462 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006463}
6464
6465
6466/*
6467 * Delete `cLines' lines at the current cursor position
6468 */
6469 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006470delete_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006471{
Bram Moolenaar6982f422019-02-16 16:48:01 +01006472 SMALL_RECT source, clip;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006473 COORD dest;
6474 CHAR_INFO fill;
6475 int nb;
6476
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006477 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
6478
Bram Moolenaar6982f422019-02-16 16:48:01 +01006479 dest.X = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006480 dest.Y = g_coord.Y;
6481
Bram Moolenaar6982f422019-02-16 16:48:01 +01006482 source.Left = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006483 source.Top = g_coord.Y + cLines;
6484 source.Right = g_srScrollRegion.Right;
6485 source.Bottom = g_srScrollRegion.Bottom;
6486
Bram Moolenaar6982f422019-02-16 16:48:01 +01006487 clip.Left = g_srScrollRegion.Left;
6488 clip.Top = g_coord.Y;
6489 clip.Right = g_srScrollRegion.Right;
6490 clip.Bottom = g_srScrollRegion.Bottom;
6491
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006492 fill.Char.AsciiChar = ' ';
Christopher Plewright38804d62022-11-09 23:55:52 +00006493 if (!vtp_working)
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006494 fill.Attributes = g_attrCurrent;
6495 else
6496 fill.Attributes = g_attrDefault;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006497
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006498 set_console_color_rgb();
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006499
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006500 ScrollConsoleScreenBuffer(g_hConOut, &source, &clip, dest, &fill);
6501
Bram Moolenaar6982f422019-02-16 16:48:01 +01006502 // Here we have to deal with a win32 console flake; See insert_lines()
6503 // above.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006504
6505 nb = dest.Y + (source.Bottom - source.Top) + 1;
6506
6507 if (nb < source.Top)
6508 {
6509 COORD coord;
Bram Moolenaar6982f422019-02-16 16:48:01 +01006510 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006511
Bram Moolenaar6982f422019-02-16 16:48:01 +01006512 coord.X = source.Left;
6513 for (i = nb; i < clip.Bottom; ++i)
6514 {
6515 coord.Y = i;
6516 clear_chars(coord, source.Right - source.Left + 1);
6517 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006518 }
Bram Moolenaar06b7b582020-05-30 17:49:25 +02006519
Christopher Plewright38804d62022-11-09 23:55:52 +00006520 if (vtp_working)
Bram Moolenaar06b7b582020-05-30 17:49:25 +02006521 {
6522 COORD coord;
6523 int i;
6524
6525 coord.X = source.Left;
6526 for (i = nb; i <= source.Bottom; ++i)
6527 {
6528 coord.Y = i;
6529 clear_chars(coord, source.Right - source.Left + 1);
6530 }
6531 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006532}
6533
6534
6535/*
Bram Moolenaar2313b612019-09-27 14:14:32 +02006536 * Set the cursor position to (x,y) (1-based).
Bram Moolenaar071d4272004-06-13 20:20:40 +00006537 */
6538 static void
6539gotoxy(
6540 unsigned x,
6541 unsigned y)
6542{
6543 if (x < 1 || x > (unsigned)Columns || y < 1 || y > (unsigned)Rows)
6544 return;
6545
Christopher Plewright38804d62022-11-09 23:55:52 +00006546 if (!(vtp_working
K.Takata161b6ac2022-11-14 15:31:07 +00006547# ifdef FEAT_TERMGUICOLORS
Christopher Plewright38804d62022-11-09 23:55:52 +00006548 && (p_tgc || t_colors >= 256)
K.Takata161b6ac2022-11-14 15:31:07 +00006549# endif
Christopher Plewright38804d62022-11-09 23:55:52 +00006550 ))
Bram Moolenaar2313b612019-09-27 14:14:32 +02006551 {
Bram Moolenaar82e743c2020-03-26 15:39:53 +01006552 // There are reports of double-width characters not displayed
6553 // correctly. This workaround should fix it, similar to how it's done
6554 // for VTP.
6555 g_coord.X = 0;
6556 SetConsoleCursorPosition(g_hConOut, g_coord);
6557
Bram Moolenaar2313b612019-09-27 14:14:32 +02006558 // external cursor coords are 1-based; internal are 0-based
6559 g_coord.X = x - 1;
6560 g_coord.Y = y - 1;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006561 SetConsoleCursorPosition(g_hConOut, g_coord);
Bram Moolenaar2313b612019-09-27 14:14:32 +02006562 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006563 else
Bram Moolenaar2313b612019-09-27 14:14:32 +02006564 {
6565 // Move the cursor to the left edge of the screen to prevent screen
Bram Moolenaara1299742019-10-10 16:36:00 +02006566 // destruction. Insider build bug. Always enabled because it's cheap
6567 // and avoids mistakes with recognizing the build.
6568 vtp_printf("\033[%d;%dH", g_coord.Y + 1, 1);
Bram Moolenaar2313b612019-09-27 14:14:32 +02006569
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006570 vtp_printf("\033[%d;%dH", y, x);
Bram Moolenaar2313b612019-09-27 14:14:32 +02006571
6572 g_coord.X = x - 1;
6573 g_coord.Y = y - 1;
6574 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006575}
6576
6577
6578/*
6579 * Set the current text attribute = (foreground | background)
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006580 * See ../runtime/doc/os_win32.txt for the numbers.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006581 */
6582 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006583textattr(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006584{
Bram Moolenaar6383b922015-03-24 17:12:19 +01006585 g_attrCurrent = wAttr & 0xff;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006586
6587 SetConsoleTextAttribute(g_hConOut, wAttr);
6588}
6589
6590
6591 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006592textcolor(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006593{
Bram Moolenaar6383b922015-03-24 17:12:19 +01006594 g_attrCurrent = (g_attrCurrent & 0xf0) + (wAttr & 0x0f);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006595
Christopher Plewright38804d62022-11-09 23:55:52 +00006596 if (!vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006597 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
6598 else
6599 vtp_sgr_bulk(wAttr);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006600}
6601
6602
6603 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006604textbackground(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006605{
Bram Moolenaar6383b922015-03-24 17:12:19 +01006606 g_attrCurrent = (g_attrCurrent & 0x0f) + ((wAttr & 0x0f) << 4);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006607
Christopher Plewright38804d62022-11-09 23:55:52 +00006608 if (!vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006609 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
6610 else
6611 vtp_sgr_bulk(wAttr);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006612}
6613
6614
6615/*
6616 * restore the default text attribute (whatever we started with)
6617 */
6618 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006619normvideo(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006620{
Christopher Plewright38804d62022-11-09 23:55:52 +00006621 if (!vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006622 textattr(g_attrDefault);
6623 else
6624 vtp_sgr_bulk(0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006625}
6626
6627
6628static WORD g_attrPreStandout = 0;
6629
6630/*
6631 * Make the text standout, by brightening it
6632 */
6633 static void
6634standout(void)
6635{
6636 g_attrPreStandout = g_attrCurrent;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006637
Bram Moolenaar071d4272004-06-13 20:20:40 +00006638 textattr((WORD) (g_attrCurrent|FOREGROUND_INTENSITY|BACKGROUND_INTENSITY));
6639}
6640
6641
6642/*
6643 * Turn off standout mode
6644 */
6645 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006646standend(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006647{
6648 if (g_attrPreStandout)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006649 textattr(g_attrPreStandout);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006650
6651 g_attrPreStandout = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006652}
6653
6654
6655/*
Bram Moolenaarff1d0d42007-05-10 17:24:16 +00006656 * Set normal fg/bg color, based on T_ME. Called when t_me has been set.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006657 */
6658 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006659mch_set_normal_colors(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006660{
6661 char_u *p;
6662 int n;
6663
6664 cterm_normal_fg_color = (g_attrDefault & 0xf) + 1;
6665 cterm_normal_bg_color = ((g_attrDefault >> 4) & 0xf) + 1;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006666 if (
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006667# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006668 !p_tgc &&
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006669# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006670 T_ME[0] == ESC && T_ME[1] == '|')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006671 {
6672 p = T_ME + 2;
6673 n = getdigits(&p);
6674 if (*p == 'm' && n > 0)
6675 {
6676 cterm_normal_fg_color = (n & 0xf) + 1;
6677 cterm_normal_bg_color = ((n >> 4) & 0xf) + 1;
6678 }
6679 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006680# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006681 cterm_normal_fg_gui_color = INVALCOLOR;
6682 cterm_normal_bg_gui_color = INVALCOLOR;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006683# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006684}
6685
6686
6687/*
6688 * visual bell: flash the screen
6689 */
6690 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006691visual_bell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006692{
6693 COORD coordOrigin = {0, 0};
6694 WORD attrFlash = ~g_attrCurrent & 0xff;
6695
6696 DWORD dwDummy;
Bram Moolenaarc799fe22019-05-28 23:08:19 +02006697 LPWORD oldattrs = ALLOC_MULT(WORD, Rows * Columns);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006698
6699 if (oldattrs == NULL)
6700 return;
6701 ReadConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
6702 coordOrigin, &dwDummy);
6703 FillConsoleOutputAttribute(g_hConOut, attrFlash, Rows * Columns,
6704 coordOrigin, &dwDummy);
6705
Bram Moolenaar0f873732019-12-05 20:28:46 +01006706 Sleep(15); // wait for 15 msec
Christopher Plewright38804d62022-11-09 23:55:52 +00006707 if (!vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006708 WriteConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
Bram Moolenaar071d4272004-06-13 20:20:40 +00006709 coordOrigin, &dwDummy);
6710 vim_free(oldattrs);
6711}
6712
6713
6714/*
6715 * Make the cursor visible or invisible
6716 */
6717 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006718cursor_visible(BOOL fVisible)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006719{
6720 s_cursor_visible = fVisible;
Bram Moolenaar2695de62020-04-17 21:13:01 +02006721
Christopher Plewright38804d62022-11-09 23:55:52 +00006722 if (vtp_working)
Bram Moolenaar2695de62020-04-17 21:13:01 +02006723 vtp_printf("\033[?25%c", fVisible ? 'h' : 'l');
6724
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006725# ifdef MCH_CURSOR_SHAPE
Bram Moolenaar071d4272004-06-13 20:20:40 +00006726 mch_update_cursor();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006727# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006728}
6729
6730
6731/*
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02006732 * Write "cbToWrite" bytes in `pchBuf' to the screen.
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006733 * Returns the number of bytes actually written (at least one).
Bram Moolenaar071d4272004-06-13 20:20:40 +00006734 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006735 static DWORD
Bram Moolenaar071d4272004-06-13 20:20:40 +00006736write_chars(
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006737 char_u *pchBuf,
6738 DWORD cbToWrite)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006739{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006740 COORD coord = g_coord;
6741 DWORD written;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006742 DWORD n, cchwritten;
6743 static DWORD cells;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006744 static WCHAR *unicodebuf = NULL;
6745 static int unibuflen = 0;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006746 static int length;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006747 int cp = enc_utf8 ? CP_UTF8 : enc_codepage;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006748 static WCHAR *utf8spbuf = NULL;
6749 static int utf8splength;
6750 static DWORD utf8spcells;
6751 static WCHAR **utf8usingbuf = &unicodebuf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006752
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006753 if (cbToWrite != 1 || *pchBuf != ' ' || !enc_utf8)
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006754 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006755 utf8usingbuf = &unicodebuf;
6756 do
6757 {
6758 length = MultiByteToWideChar(cp, 0, (LPCSTR)pchBuf, cbToWrite,
6759 unicodebuf, unibuflen);
6760 if (length && length <= unibuflen)
6761 break;
6762 vim_free(unicodebuf);
6763 unicodebuf = length ? LALLOC_MULT(WCHAR, length) : NULL;
6764 unibuflen = unibuflen ? 0 : length;
6765 } while(1);
6766 cells = mb_string2cells(pchBuf, cbToWrite);
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006767 }
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006768 else // cbToWrite == 1 && *pchBuf == ' ' && enc_utf8
6769 {
6770 if (utf8usingbuf != &utf8spbuf)
6771 {
6772 if (utf8spbuf == NULL)
6773 {
6774 cells = mb_string2cells((char_u *)" ", 1);
6775 length = MultiByteToWideChar(CP_UTF8, 0, " ", 1, NULL, 0);
6776 utf8spbuf = LALLOC_MULT(WCHAR, length);
6777 if (utf8spbuf != NULL)
6778 {
6779 MultiByteToWideChar(CP_UTF8, 0, " ", 1, utf8spbuf, length);
6780 utf8usingbuf = &utf8spbuf;
6781 utf8splength = length;
6782 utf8spcells = cells;
6783 }
6784 }
6785 else
6786 {
6787 utf8usingbuf = &utf8spbuf;
6788 length = utf8splength;
6789 cells = utf8spcells;
6790 }
6791 }
6792 }
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006793
Christopher Plewright38804d62022-11-09 23:55:52 +00006794 if (!(vtp_working
K.Takata161b6ac2022-11-14 15:31:07 +00006795# ifdef FEAT_TERMGUICOLORS
Christopher Plewright38804d62022-11-09 23:55:52 +00006796 && (p_tgc || t_colors >= 256)
K.Takata161b6ac2022-11-14 15:31:07 +00006797# endif
Christopher Plewright38804d62022-11-09 23:55:52 +00006798 ))
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006799 {
6800 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, cells,
6801 coord, &written);
6802 // When writing fails or didn't write a single character, pretend one
6803 // character was written, otherwise we get stuck.
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006804 if (WriteConsoleOutputCharacterW(g_hConOut, *utf8usingbuf, length,
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006805 coord, &cchwritten) == 0
6806 || cchwritten == 0 || cchwritten == (DWORD)-1)
6807 cchwritten = 1;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006808 }
6809 else
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006810 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006811 if (WriteConsoleW(g_hConOut, *utf8usingbuf, length, &cchwritten,
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006812 NULL) == 0 || cchwritten == 0)
6813 cchwritten = 1;
6814 }
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006815
K.Takata135e1522022-01-29 15:27:58 +00006816 if (cchwritten == (DWORD)length)
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006817 {
6818 written = cbToWrite;
6819 g_coord.X += (SHORT)cells;
6820 }
6821 else
6822 {
6823 char_u *p = pchBuf;
6824 for (n = 0; n < cchwritten; n++)
6825 MB_CPTR_ADV(p);
6826 written = p - pchBuf;
6827 g_coord.X += (SHORT)mb_string2cells(pchBuf, written);
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006828 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006829
6830 while (g_coord.X > g_srScrollRegion.Right)
6831 {
6832 g_coord.X -= (SHORT) Columns;
6833 if (g_coord.Y < g_srScrollRegion.Bottom)
6834 g_coord.Y++;
6835 }
6836
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006837 // Cursor under VTP is always in the correct position, no need to reset.
Christopher Plewright38804d62022-11-09 23:55:52 +00006838 if (!(vtp_working
K.Takata161b6ac2022-11-14 15:31:07 +00006839# ifdef FEAT_TERMGUICOLORS
Christopher Plewright38804d62022-11-09 23:55:52 +00006840 && (p_tgc || t_colors >= 256)
K.Takata161b6ac2022-11-14 15:31:07 +00006841# endif
Christopher Plewright38804d62022-11-09 23:55:52 +00006842 ))
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006843 gotoxy(g_coord.X + 1, g_coord.Y + 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006844
6845 return written;
6846}
6847
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006848 static char_u *
6849get_seq(
6850 int *args,
6851 int *count,
6852 char_u *head)
6853{
6854 int argc;
6855 char_u *p;
6856
6857 if (head == NULL || *head != '\033')
6858 return NULL;
6859
6860 argc = 0;
6861 p = head;
6862 ++p;
6863 do
6864 {
6865 ++p;
6866 args[argc] = getdigits(&p);
6867 argc += (argc < 15) ? 1 : 0;
6868 } while (*p == ';');
6869 *count = argc;
6870
6871 return p;
6872}
6873
6874 static char_u *
6875get_sgr(
6876 int *args,
6877 int *count,
6878 char_u *head)
6879{
6880 char_u *p = get_seq(args, count, head);
6881
6882 return (p && *p == 'm') ? ++p : NULL;
6883}
6884
6885/*
6886 * Pointer to next if SGR (^[[n;2;*;*;*m), NULL otherwise.
6887 */
6888 static char_u *
6889sgrn2(
6890 char_u *head,
6891 int n)
6892{
6893 int argc;
6894 int args[16];
6895 char_u *p = get_sgr(args, &argc, head);
6896
6897 return p && argc == 5 && args[0] == n && args[1] == 2 ? p : NULL;
6898}
6899
6900/*
6901 * Pointer to next if SGR(^[[nm)<space>ESC, NULL otherwise.
6902 */
6903 static char_u *
6904sgrnc(
6905 char_u *head,
6906 int n)
6907{
6908 int argc;
6909 int args[16];
6910 char_u *p = get_sgr(args, &argc, head);
6911
6912 return p && argc == 1 && args[0] == n && (p = skipwhite(p)) && *p == '\033'
6913 ? p : NULL;
6914}
6915
6916 static char_u *
6917skipblank(char_u *q)
6918{
6919 char_u *p = q;
6920
6921 while (*p == ' ' || *p == '\t' || *p == '\n' || *p == '\r')
6922 ++p;
6923 return p;
6924}
6925
6926/*
6927 * Pointer to the next if any whitespace that may follow SGR is ESC, otherwise
6928 * NULL.
6929 */
6930 static char_u *
6931sgrn2c(
6932 char_u *head,
6933 int n)
6934{
6935 char_u *p = sgrn2(head, n);
6936
6937 return p && *p != NUL && (p = skipblank(p)) && *p == '\033' ? p : NULL;
6938}
6939
6940/*
6941 * If there is only a newline between the sequence immediately following it,
6942 * a pointer to the character following the newline is returned.
6943 * Otherwise NULL.
6944 */
6945 static char_u *
6946sgrn2cn(
6947 char_u *head,
6948 int n)
6949{
6950 char_u *p = sgrn2(head, n);
6951
6952 return p && p[0] == 0x0a && p[1] == '\033' ? ++p : NULL;
6953}
Bram Moolenaar071d4272004-06-13 20:20:40 +00006954
6955/*
6956 * mch_write(): write the output buffer to the screen, translating ESC
6957 * sequences into calls to console output routines.
6958 */
6959 void
6960mch_write(
6961 char_u *s,
6962 int len)
6963{
Bram Moolenaard23f8bd2021-04-21 11:30:48 +02006964 char_u *end = s + len;
6965
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006966# ifdef VIMDLL
6967 if (gui.in_use)
6968 return;
6969# endif
6970
Bram Moolenaar071d4272004-06-13 20:20:40 +00006971 if (!term_console)
6972 {
6973 write(1, s, (unsigned)len);
6974 return;
6975 }
6976
Bram Moolenaar0f873732019-12-05 20:28:46 +01006977 // translate ESC | sequences into faked bios calls
Bram Moolenaar071d4272004-06-13 20:20:40 +00006978 while (len--)
6979 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006980 int prefix = -1;
6981 char_u ch;
6982
6983 // While processing a sequence, on rare occasions it seems that another
6984 // sequence may be inserted asynchronously.
6985 if (len < 0)
6986 {
Bram Moolenaara4d158b2022-08-14 14:17:45 +01006987 redraw_all_later(UPD_CLEAR);
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006988 return;
6989 }
6990
Bram Moolenaard23f8bd2021-04-21 11:30:48 +02006991 while (s + ++prefix < end)
6992 {
6993 ch = s[prefix];
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006994 if (ch <= 0x1e && !(ch != '\n' && ch != '\r' && ch != '\b'
6995 && ch != '\a' && ch != '\033'))
6996 break;
Bram Moolenaard23f8bd2021-04-21 11:30:48 +02006997 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006998
6999 if (p_wd)
7000 {
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02007001 WaitForChar(p_wd, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007002 if (prefix != 0)
7003 prefix = 1;
7004 }
7005
7006 if (prefix != 0)
7007 {
7008 DWORD nWritten;
7009
7010 nWritten = write_chars(s, prefix);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007011# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00007012 if (fdDump)
7013 {
7014 fputc('>', fdDump);
7015 fwrite(s, sizeof(char_u), nWritten, fdDump);
7016 fputs("<\n", fdDump);
7017 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007018# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007019 len -= (nWritten - 1);
7020 s += nWritten;
7021 }
7022 else if (s[0] == '\n')
7023 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007024 // \n, newline: go to the beginning of the next line or scroll
Bram Moolenaar071d4272004-06-13 20:20:40 +00007025 if (g_coord.Y == g_srScrollRegion.Bottom)
7026 {
7027 scroll(1);
7028 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Bottom + 1);
7029 }
7030 else
7031 {
7032 gotoxy(g_srScrollRegion.Left + 1, g_coord.Y + 2);
7033 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007034# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00007035 if (fdDump)
7036 fputs("\\n\n", fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007037# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007038 s++;
7039 }
7040 else if (s[0] == '\r')
7041 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007042 // \r, carriage return: go to beginning of line
Bram Moolenaar071d4272004-06-13 20:20:40 +00007043 gotoxy(g_srScrollRegion.Left+1, g_coord.Y + 1);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007044# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00007045 if (fdDump)
7046 fputs("\\r\n", fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007047# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007048 s++;
7049 }
7050 else if (s[0] == '\b')
7051 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007052 // \b, backspace: move cursor one position left
Bram Moolenaar071d4272004-06-13 20:20:40 +00007053 if (g_coord.X > g_srScrollRegion.Left)
7054 g_coord.X--;
7055 else if (g_coord.Y > g_srScrollRegion.Top)
7056 {
7057 g_coord.X = g_srScrollRegion.Right;
7058 g_coord.Y--;
7059 }
7060 gotoxy(g_coord.X + 1, g_coord.Y + 1);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007061# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00007062 if (fdDump)
7063 fputs("\\b\n", fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007064# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007065 s++;
7066 }
7067 else if (s[0] == '\a')
7068 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007069 // \a, bell
Bram Moolenaar071d4272004-06-13 20:20:40 +00007070 MessageBeep(0xFFFFFFFF);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007071# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00007072 if (fdDump)
7073 fputs("\\a\n", fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007074# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007075 s++;
7076 }
7077 else if (s[0] == ESC && len >= 3-1 && s[1] == '|')
7078 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007079# ifdef MCH_WRITE_DUMP
Bram Moolenaarc0197e22004-09-13 20:26:32 +00007080 char_u *old_s = s;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007081# endif
Bram Moolenaarc0197e22004-09-13 20:26:32 +00007082 char_u *p;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007083 int arg1 = 0, arg2 = 0, argc = 0, args[16];
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007084 char_u *sp;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007085
7086 switch (s[2])
7087 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00007088 case '0': case '1': case '2': case '3': case '4':
7089 case '5': case '6': case '7': case '8': case '9':
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007090 if (*(p = get_seq(args, &argc, s)) != 'm')
7091 goto notsgr;
7092
7093 p = s;
7094
7095 // Handling frequent optional sequences. Output to the screen
7096 // takes too long, so do not output as much as possible.
7097
7098 // If resetFG,FG,BG,<cr>,BG,FG are connected, the preceding
7099 // resetFG,FG,BG are omitted.
7100 if (sgrn2(sgrn2(sgrn2cn(sgrn2(sgrnc(p, 39), 38), 48), 48), 38))
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007101 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007102 p = sgrn2(sgrn2(sgrnc(p, 39), 38), 48);
7103 len = len + 1 - (int)(p - s);
7104 s = p;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007105 break;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007106 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007107
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007108 // If FG,BG,BG,FG of SGR are connected, the first FG can be
7109 // omitted.
7110 if (sgrn2(sgrn2(sgrn2c((sp = sgrn2(p, 38)), 48), 48), 38))
7111 p = sp;
7112
7113 // If FG,BG,FG,BG of SGR are connected, the first FG can be
7114 // omitted.
7115 if (sgrn2(sgrn2(sgrn2c((sp = sgrn2(p, 38)), 48), 38), 48))
7116 p = sp;
7117
7118 // If BG,BG of SGR are connected, the first BG can be omitted.
7119 if (sgrn2((sp = sgrn2(p, 48)), 48))
7120 p = sp;
7121
7122 // If restoreFG and FG are connected, the restoreFG can be
Bram Moolenaar9f1983d2022-05-12 20:35:35 +01007123 // omitted.
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007124 if (sgrn2((sp = sgrnc(p, 39)), 38))
7125 p = sp;
7126
7127 p = get_seq(args, &argc, p);
7128
7129notsgr:
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007130 arg1 = args[0];
7131 arg2 = args[1];
7132 if (*p == 'm')
Bram Moolenaar071d4272004-06-13 20:20:40 +00007133 {
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007134 if (argc == 1 && args[0] == 0)
7135 normvideo();
7136 else if (argc == 1)
7137 {
Christopher Plewright38804d62022-11-09 23:55:52 +00007138 if (vtp_working
7139# ifdef FEAT_TERMGUICOLORS
7140 && (p_tgc || t_colors >= 256)
7141# endif
7142 )
7143 textcolor((WORD)arg1);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007144 else
Christopher Plewright38804d62022-11-09 23:55:52 +00007145 textattr((WORD)arg1);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007146 }
Christopher Plewright38804d62022-11-09 23:55:52 +00007147 else if (vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007148 vtp_sgr_bulks(argc, args);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007149 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007150 else if (argc == 2 && *p == 'H')
Bram Moolenaar071d4272004-06-13 20:20:40 +00007151 {
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007152 gotoxy(arg2, arg1);
7153 }
7154 else if (argc == 2 && *p == 'r')
7155 {
7156 set_scroll_region(0, arg1 - 1, Columns - 1, arg2 - 1);
7157 }
Bram Moolenaar6982f422019-02-16 16:48:01 +01007158 else if (argc == 2 && *p == 'R')
7159 {
7160 set_scroll_region_tb(arg1, arg2);
7161 }
7162 else if (argc == 2 && *p == 'V')
7163 {
7164 set_scroll_region_lr(arg1, arg2);
7165 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007166 else if (argc == 1 && *p == 'A')
7167 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00007168 gotoxy(g_coord.X + 1,
7169 max(g_srScrollRegion.Top, g_coord.Y - arg1) + 1);
7170 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007171 else if (argc == 1 && *p == 'b')
Bram Moolenaar071d4272004-06-13 20:20:40 +00007172 {
7173 textbackground((WORD) arg1);
7174 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007175 else if (argc == 1 && *p == 'C')
7176 {
7177 gotoxy(min(g_srScrollRegion.Right, g_coord.X + arg1) + 1,
7178 g_coord.Y + 1);
7179 }
7180 else if (argc == 1 && *p == 'f')
7181 {
7182 textcolor((WORD) arg1);
7183 }
7184 else if (argc == 1 && *p == 'H')
7185 {
7186 gotoxy(1, arg1);
7187 }
7188 else if (argc == 1 && *p == 'L')
7189 {
7190 insert_lines(arg1);
7191 }
7192 else if (argc == 1 && *p == 'M')
Bram Moolenaar071d4272004-06-13 20:20:40 +00007193 {
7194 delete_lines(arg1);
7195 }
7196
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007197 len -= (int)(p - s);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007198 s = p + 1;
7199 break;
7200
Bram Moolenaar071d4272004-06-13 20:20:40 +00007201 case 'A':
Bram Moolenaar071d4272004-06-13 20:20:40 +00007202 gotoxy(g_coord.X + 1,
7203 max(g_srScrollRegion.Top, g_coord.Y - 1) + 1);
7204 goto got3;
7205
7206 case 'B':
7207 visual_bell();
7208 goto got3;
7209
7210 case 'C':
Bram Moolenaar071d4272004-06-13 20:20:40 +00007211 gotoxy(min(g_srScrollRegion.Right, g_coord.X + 1) + 1,
7212 g_coord.Y + 1);
7213 goto got3;
7214
7215 case 'E':
7216 termcap_mode_end();
7217 goto got3;
7218
7219 case 'F':
7220 standout();
7221 goto got3;
7222
7223 case 'f':
7224 standend();
7225 goto got3;
7226
7227 case 'H':
7228 gotoxy(1, 1);
7229 goto got3;
7230
7231 case 'j':
7232 clear_to_end_of_display();
7233 goto got3;
7234
7235 case 'J':
7236 clear_screen();
7237 goto got3;
7238
7239 case 'K':
7240 clear_to_end_of_line();
7241 goto got3;
7242
7243 case 'L':
7244 insert_lines(1);
7245 goto got3;
7246
7247 case 'M':
7248 delete_lines(1);
7249 goto got3;
7250
7251 case 'S':
7252 termcap_mode_start();
7253 goto got3;
7254
7255 case 'V':
7256 cursor_visible(TRUE);
7257 goto got3;
7258
7259 case 'v':
7260 cursor_visible(FALSE);
7261 goto got3;
7262
7263 got3:
7264 s += 3;
7265 len -= 2;
7266 }
7267
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007268# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00007269 if (fdDump)
7270 {
7271 fputs("ESC | ", fdDump);
7272 fwrite(old_s + 2, sizeof(char_u), s - old_s - 2, fdDump);
7273 fputc('\n', fdDump);
7274 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007275# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007276 }
K.Takatadf5320c2022-09-01 13:20:16 +01007277 else if (s[0] == ESC && len >= 3-1 && s[1] == '[')
7278 {
7279 int l = 2;
7280
7281 if (isdigit(s[l]))
7282 l++;
7283 if (s[l] == ' ' && s[l + 1] == 'q')
7284 {
7285 // DECSCUSR (cursor style) sequences
Christopher Plewright38804d62022-11-09 23:55:52 +00007286 if (vtp_working)
K.Takatadf5320c2022-09-01 13:20:16 +01007287 vtp_printf("%.*s", l + 2, s); // Pass through
7288 s += l + 2;
7289 len -= l + 1;
7290 }
7291 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007292 else
7293 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007294 // Write a single character
Bram Moolenaar071d4272004-06-13 20:20:40 +00007295 DWORD nWritten;
7296
7297 nWritten = write_chars(s, 1);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007298# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00007299 if (fdDump)
7300 {
7301 fputc('>', fdDump);
7302 fwrite(s, sizeof(char_u), nWritten, fdDump);
7303 fputs("<\n", fdDump);
7304 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007305# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007306
7307 len -= (nWritten - 1);
7308 s += nWritten;
7309 }
7310 }
7311
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007312# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00007313 if (fdDump)
7314 fflush(fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007315# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007316}
7317
Bram Moolenaar0f873732019-12-05 20:28:46 +01007318#endif // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00007319
7320
7321/*
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01007322 * Delay for "msec" milliseconds.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007323 */
7324 void
7325mch_delay(
7326 long msec,
Bram Moolenaar0981c872020-08-23 14:28:37 +02007327 int flags UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007328{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007329#if defined(FEAT_GUI_MSWIN) && !defined(VIMDLL)
Bram Moolenaar0f873732019-12-05 20:28:46 +01007330 Sleep((int)msec); // never wait for input
7331#else // Console
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007332# ifdef VIMDLL
7333 if (gui.in_use)
7334 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007335 Sleep((int)msec); // never wait for input
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007336 return;
7337 }
7338# endif
Bram Moolenaar0981c872020-08-23 14:28:37 +02007339 if (flags & MCH_DELAY_IGNOREINPUT)
Bram Moolenaar325b7a22004-07-05 15:58:32 +00007340# ifdef FEAT_MZSCHEME
7341 if (mzthreads_allowed() && p_mzq > 0 && msec > p_mzq)
7342 {
7343 int towait = p_mzq;
7344
Bram Moolenaar0f873732019-12-05 20:28:46 +01007345 // if msec is large enough, wait by portions in p_mzq
Bram Moolenaar325b7a22004-07-05 15:58:32 +00007346 while (msec > 0)
7347 {
7348 mzvim_check_threads();
7349 if (msec < towait)
7350 towait = msec;
7351 Sleep(towait);
7352 msec -= towait;
7353 }
7354 }
7355 else
7356# endif
7357 Sleep((int)msec);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007358 else
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02007359 WaitForChar(msec, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007360#endif
7361}
7362
7363
7364/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01007365 * This version of remove is not scared by a readonly (backup) file.
7366 * This can also remove a symbolic link like Unix.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007367 * Return 0 for success, -1 for failure.
7368 */
7369 int
7370mch_remove(char_u *name)
7371{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007372 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007373 int n;
7374
Bram Moolenaar203258c2016-01-17 22:15:16 +01007375 /*
7376 * On Windows, deleting a directory's symbolic link is done by
7377 * RemoveDirectory(): mch_rmdir. It seems unnatural, but it is fact.
7378 */
7379 if (mch_isdir(name) && mch_is_symbolic_link(name))
7380 return mch_rmdir(name);
7381
Bram Moolenaar12b559e2013-06-12 22:41:37 +02007382 win32_setattrs(name, FILE_ATTRIBUTE_NORMAL);
7383
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007384 wn = enc_to_utf16(name, NULL);
7385 if (wn == NULL)
7386 return -1;
7387
7388 n = DeleteFileW(wn) ? 0 : -1;
7389 vim_free(wn);
7390 return n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007391}
7392
7393
7394/*
Bram Moolenaarb9c31e72016-09-29 15:18:57 +02007395 * Check for an "interrupt signal": CTRL-break or CTRL-C.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007396 */
7397 void
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02007398mch_breakcheck(int force UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007399{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007400#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
7401# ifdef VIMDLL
7402 if (!gui.in_use)
7403# endif
7404 if (g_fCtrlCPressed || g_fCBrkPressed)
7405 {
7406 ctrl_break_was_pressed = g_fCBrkPressed;
7407 g_fCtrlCPressed = g_fCBrkPressed = FALSE;
7408 got_int = TRUE;
7409 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007410#endif
7411}
7412
Bram Moolenaar0f873732019-12-05 20:28:46 +01007413// physical RAM to leave for the OS
Bram Moolenaaree273972016-01-02 21:11:51 +01007414#define WINNT_RESERVE_BYTES (256*1024*1024)
Bram Moolenaaree273972016-01-02 21:11:51 +01007415
7416/*
7417 * How much main memory in KiB that can be used by VIM.
7418 */
Bram Moolenaaree273972016-01-02 21:11:51 +01007419 long_u
Bram Moolenaar1266d672017-02-01 13:43:36 +01007420mch_total_mem(int special UNUSED)
Bram Moolenaaree273972016-01-02 21:11:51 +01007421{
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007422 MEMORYSTATUSEX ms;
7423
Bram Moolenaar0f873732019-12-05 20:28:46 +01007424 // Need to use GlobalMemoryStatusEx() when there is more memory than
7425 // what fits in 32 bits.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007426 ms.dwLength = sizeof(MEMORYSTATUSEX);
7427 GlobalMemoryStatusEx(&ms);
7428 if (ms.ullAvailVirtual < ms.ullTotalPhys)
Bram Moolenaaree273972016-01-02 21:11:51 +01007429 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007430 // Process address space fits in physical RAM, use all of it.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007431 return (long_u)(ms.ullAvailVirtual / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01007432 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007433 if (ms.ullTotalPhys <= WINNT_RESERVE_BYTES)
Bram Moolenaaree273972016-01-02 21:11:51 +01007434 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007435 // Catch old NT box or perverse hardware setup.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007436 return (long_u)((ms.ullTotalPhys / 2) / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01007437 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01007438 // Use physical RAM less reserve for OS + data.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007439 return (long_u)((ms.ullTotalPhys - WINNT_RESERVE_BYTES) / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01007440}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007441
Bram Moolenaar071d4272004-06-13 20:20:40 +00007442/*
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007443 * mch_wrename() works around a bug in rename (aka MoveFile) in
Bram Moolenaar071d4272004-06-13 20:20:40 +00007444 * Windows 95: rename("foo.bar", "foo.bar~") will generate a
7445 * file whose short file name is "FOO.BAR" (its long file name will
7446 * be correct: "foo.bar~"). Because a file can be accessed by
7447 * either its SFN or its LFN, "foo.bar" has effectively been
7448 * renamed to "foo.bar", which is not at all what was wanted. This
7449 * seems to happen only when renaming files with three-character
7450 * extensions by appending a suffix that does not include ".".
7451 * Windows NT gets it right, however, with an SFN of "FOO~1.BAR".
7452 *
7453 * There is another problem, which isn't really a bug but isn't right either:
7454 * When renaming "abcdef~1.txt" to "abcdef~1.txt~", the short name can be
7455 * "abcdef~1.txt" again. This has been reported on Windows NT 4.0 with
7456 * service pack 6. Doesn't seem to happen on Windows 98.
7457 *
7458 * Like rename(), returns 0 upon success, non-zero upon failure.
7459 * Should probably set errno appropriately when errors occur.
7460 */
7461 int
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007462mch_wrename(WCHAR *wold, WCHAR *wnew)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007463{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007464 WCHAR *p;
7465 int i;
7466 WCHAR szTempFile[_MAX_PATH + 1];
7467 WCHAR szNewPath[_MAX_PATH + 1];
Bram Moolenaar071d4272004-06-13 20:20:40 +00007468 HANDLE hf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007469
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007470 // No need to play tricks unless the file name contains a "~" as the
7471 // seventh character.
7472 p = wold;
7473 for (i = 0; wold[i] != NUL; ++i)
7474 if ((wold[i] == '/' || wold[i] == '\\' || wold[i] == ':')
7475 && wold[i + 1] != 0)
7476 p = wold + i + 1;
7477 if ((int)(wold + i - p) < 8 || p[6] != '~')
7478 return (MoveFileW(wold, wnew) == 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007479
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007480 // Get base path of new file name. Undocumented feature: If pszNewFile is
7481 // a directory, no error is returned and pszFilePart will be NULL.
7482 if (GetFullPathNameW(wnew, _MAX_PATH, szNewPath, &p) == 0 || p == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007483 return -1;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007484 *p = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007485
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007486 // Get (and create) a unique temporary file name in directory of new file
7487 if (GetTempFileNameW(szNewPath, L"VIM", 0, szTempFile) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007488 return -2;
7489
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007490 // blow the temp file away
7491 if (!DeleteFileW(szTempFile))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007492 return -3;
7493
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007494 // rename old file to the temp file
7495 if (!MoveFileW(wold, szTempFile))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007496 return -4;
7497
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007498 // now create an empty file called pszOldFile; this prevents the operating
7499 // system using pszOldFile as an alias (SFN) if we're renaming within the
7500 // same directory. For example, we're editing a file called
7501 // filename.asc.txt by its SFN, filena~1.txt. If we rename filena~1.txt
7502 // to filena~1.txt~ (i.e., we're making a backup while writing it), the
7503 // SFN for filena~1.txt~ will be filena~1.txt, by default, which will
7504 // cause all sorts of problems later in buf_write(). So, we create an
7505 // empty file called filena~1.txt and the system will have to find some
7506 // other SFN for filena~1.txt~, such as filena~2.txt
7507 if ((hf = CreateFileW(wold, GENERIC_WRITE, 0, NULL, CREATE_NEW,
Bram Moolenaar071d4272004-06-13 20:20:40 +00007508 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
7509 return -5;
7510 if (!CloseHandle(hf))
7511 return -6;
7512
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007513 // rename the temp file to the new file
7514 if (!MoveFileW(szTempFile, wnew))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007515 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007516 // Renaming failed. Rename the file back to its old name, so that it
7517 // looks like nothing happened.
7518 (void)MoveFileW(szTempFile, wold);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007519 return -7;
7520 }
7521
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007522 // Seems to be left around on Novell filesystems
7523 DeleteFileW(szTempFile);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007524
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007525 // finally, remove the empty old file
7526 if (!DeleteFileW(wold))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007527 return -8;
7528
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007529 return 0;
7530}
7531
7532
7533/*
7534 * Converts the filenames to UTF-16, then call mch_wrename().
7535 * Like rename(), returns 0 upon success, non-zero upon failure.
7536 */
7537 int
7538mch_rename(
7539 const char *pszOldFile,
7540 const char *pszNewFile)
7541{
7542 WCHAR *wold = NULL;
7543 WCHAR *wnew = NULL;
7544 int retval = -1;
7545
7546 wold = enc_to_utf16((char_u *)pszOldFile, NULL);
7547 wnew = enc_to_utf16((char_u *)pszNewFile, NULL);
7548 if (wold != NULL && wnew != NULL)
7549 retval = mch_wrename(wold, wnew);
7550 vim_free(wold);
7551 vim_free(wnew);
7552 return retval;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007553}
7554
7555/*
7556 * Get the default shell for the current hardware platform
7557 */
7558 char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007559default_shell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007560{
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007561 return "cmd.exe";
Bram Moolenaar071d4272004-06-13 20:20:40 +00007562}
7563
7564/*
7565 * mch_access() extends access() to do more detailed check on network drives.
7566 * Returns 0 if file "n" has access rights according to "p", -1 otherwise.
7567 */
7568 int
7569mch_access(char *n, int p)
7570{
7571 HANDLE hFile;
Bram Moolenaar0f873732019-12-05 20:28:46 +01007572 int retval = -1; // default: fail
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007573 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007574
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007575 wn = enc_to_utf16((char_u *)n, NULL);
7576 if (wn == NULL)
7577 return -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007578
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01007579 if (mch_isdir((char_u *)n))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007580 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00007581 WCHAR TempNameW[_MAX_PATH + 16] = L"";
Bram Moolenaar071d4272004-06-13 20:20:40 +00007582
7583 if (p & R_OK)
7584 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007585 // Read check is performed by seeing if we can do a find file on
7586 // the directory for any file.
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007587 int i;
7588 WIN32_FIND_DATAW d;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007589
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007590 for (i = 0; i < _MAX_PATH && wn[i] != 0; ++i)
7591 TempNameW[i] = wn[i];
7592 if (TempNameW[i - 1] != '\\' && TempNameW[i - 1] != '/')
7593 TempNameW[i++] = '\\';
7594 TempNameW[i++] = '*';
7595 TempNameW[i++] = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007596
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007597 hFile = FindFirstFileW(TempNameW, &d);
7598 if (hFile == INVALID_HANDLE_VALUE)
7599 goto getout;
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007600 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00007601 (void)FindClose(hFile);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007602 }
7603
7604 if (p & W_OK)
7605 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007606 // Trying to create a temporary file in the directory should catch
7607 // directories on read-only network shares. However, in
7608 // directories whose ACL allows writes but denies deletes will end
7609 // up keeping the temporary file :-(.
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007610 if (!GetTempFileNameW(wn, L"VIM", 0, TempNameW))
7611 goto getout;
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007612 else
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007613 DeleteFileW(TempNameW);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007614 }
7615 }
7616 else
7617 {
Bram Moolenaar5aa98962018-05-06 17:09:38 +02007618 // Don't consider a file read-only if another process has opened it.
7619 DWORD share_mode = FILE_SHARE_READ | FILE_SHARE_WRITE;
7620
Bram Moolenaar0f873732019-12-05 20:28:46 +01007621 // Trying to open the file for the required access does ACL, read-only
7622 // network share, and file attribute checks.
Bram Moolenaar5aa98962018-05-06 17:09:38 +02007623 DWORD access_mode = ((p & W_OK) ? GENERIC_WRITE : 0)
7624 | ((p & R_OK) ? GENERIC_READ : 0);
7625
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007626 hFile = CreateFileW(wn, access_mode, share_mode,
7627 NULL, OPEN_EXISTING, 0, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007628 if (hFile == INVALID_HANDLE_VALUE)
7629 goto getout;
7630 CloseHandle(hFile);
7631 }
7632
Bram Moolenaar0f873732019-12-05 20:28:46 +01007633 retval = 0; // success
Bram Moolenaar071d4272004-06-13 20:20:40 +00007634getout:
Bram Moolenaar071d4272004-06-13 20:20:40 +00007635 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007636 return retval;
7637}
7638
Bram Moolenaar071d4272004-06-13 20:20:40 +00007639/*
Bram Moolenaar36f692d2008-11-20 16:10:17 +00007640 * Version of open() that may use UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007641 */
7642 int
Bram Moolenaarb6843a02017-08-02 22:07:12 +02007643mch_open(const char *name, int flags, int mode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007644{
7645 WCHAR *wn;
7646 int f;
7647
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007648 wn = enc_to_utf16((char_u *)name, NULL);
7649 if (wn == NULL)
7650 return -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007651
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007652 f = _wopen(wn, flags, mode);
7653 vim_free(wn);
7654 return f;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007655}
7656
7657/*
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007658 * Version of fopen() that uses UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007659 */
7660 FILE *
Bram Moolenaarb6843a02017-08-02 22:07:12 +02007661mch_fopen(const char *name, const char *mode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007662{
7663 WCHAR *wn, *wm;
7664 FILE *f = NULL;
7665
Bram Moolenaara12a1612019-01-24 16:39:02 +01007666#if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0f873732019-12-05 20:28:46 +01007667 // Work around an annoying assertion in the Microsoft debug CRT
7668 // when mode's text/binary setting doesn't match _get_fmode().
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007669 char newMode = mode[strlen(mode) - 1];
7670 int oldMode = 0;
Bram Moolenaar0fde2902008-03-16 13:54:13 +00007671
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007672 _get_fmode(&oldMode);
7673 if (newMode == 't')
7674 _set_fmode(_O_TEXT);
7675 else if (newMode == 'b')
7676 _set_fmode(_O_BINARY);
Bram Moolenaara12a1612019-01-24 16:39:02 +01007677#endif
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007678 wn = enc_to_utf16((char_u *)name, NULL);
7679 wm = enc_to_utf16((char_u *)mode, NULL);
7680 if (wn != NULL && wm != NULL)
7681 f = _wfopen(wn, wm);
7682 vim_free(wn);
7683 vim_free(wm);
Bram Moolenaar0fde2902008-03-16 13:54:13 +00007684
Bram Moolenaara12a1612019-01-24 16:39:02 +01007685#if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007686 _set_fmode(oldMode);
Bram Moolenaara12a1612019-01-24 16:39:02 +01007687#endif
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007688 return f;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007689}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007690
Bram Moolenaar071d4272004-06-13 20:20:40 +00007691/*
7692 * SUB STREAM (aka info stream) handling:
7693 *
Bram Moolenaar8e7d6222020-12-18 19:49:56 +01007694 * NTFS can have sub streams for each file. The normal contents of a file is
7695 * stored in the main stream, and extra contents (author information, title and
7696 * so on) can be stored in a sub stream. After Windows 2000, the user can
7697 * access and store this information in sub streams via an explorer's property
7698 * menu item in the right click menu. This information in sub streams was lost
7699 * when copying only the main stream. Therefore we have to copy sub streams.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007700 *
7701 * Incomplete explanation:
7702 * http://msdn.microsoft.com/library/en-us/dnw2k/html/ntfs5.asp
7703 * More useful info and an example:
7704 * http://www.sysinternals.com/ntw2k/source/misc.shtml#streams
7705 */
7706
7707/*
7708 * Copy info stream data "substream". Read from the file with BackupRead(sh)
7709 * and write to stream "substream" of file "to".
7710 * Errors are ignored.
7711 */
7712 static void
7713copy_substream(HANDLE sh, void *context, WCHAR *to, WCHAR *substream, long len)
7714{
7715 HANDLE hTo;
7716 WCHAR *to_name;
7717
7718 to_name = malloc((wcslen(to) + wcslen(substream) + 1) * sizeof(WCHAR));
7719 wcscpy(to_name, to);
7720 wcscat(to_name, substream);
7721
7722 hTo = CreateFileW(to_name, GENERIC_WRITE, 0, NULL, OPEN_ALWAYS,
7723 FILE_ATTRIBUTE_NORMAL, NULL);
7724 if (hTo != INVALID_HANDLE_VALUE)
7725 {
7726 long done;
7727 DWORD todo;
7728 DWORD readcnt, written;
7729 char buf[4096];
7730
Bram Moolenaar0f873732019-12-05 20:28:46 +01007731 // Copy block of bytes at a time. Abort when something goes wrong.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007732 for (done = 0; done < len; done += written)
7733 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007734 // (size_t) cast for Borland C 5.5
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007735 todo = (DWORD)((size_t)(len - done) > sizeof(buf) ? sizeof(buf)
7736 : (size_t)(len - done));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007737 if (!BackupRead(sh, (LPBYTE)buf, todo, &readcnt,
7738 FALSE, FALSE, context)
7739 || readcnt != todo
7740 || !WriteFile(hTo, buf, todo, &written, NULL)
7741 || written != todo)
7742 break;
7743 }
7744 CloseHandle(hTo);
7745 }
7746
7747 free(to_name);
7748}
7749
7750/*
7751 * Copy info streams from file "from" to file "to".
7752 */
7753 static void
7754copy_infostreams(char_u *from, char_u *to)
7755{
7756 WCHAR *fromw;
7757 WCHAR *tow;
7758 HANDLE sh;
7759 WIN32_STREAM_ID sid;
7760 int headersize;
7761 WCHAR streamname[_MAX_PATH];
7762 DWORD readcount;
7763 void *context = NULL;
7764 DWORD lo, hi;
7765 int len;
7766
Bram Moolenaar0f873732019-12-05 20:28:46 +01007767 // Convert the file names to wide characters.
Bram Moolenaar36f692d2008-11-20 16:10:17 +00007768 fromw = enc_to_utf16(from, NULL);
7769 tow = enc_to_utf16(to, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007770 if (fromw != NULL && tow != NULL)
7771 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007772 // Open the file for reading.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007773 sh = CreateFileW(fromw, GENERIC_READ, FILE_SHARE_READ, NULL,
7774 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
7775 if (sh != INVALID_HANDLE_VALUE)
7776 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007777 // Use BackupRead() to find the info streams. Repeat until we
7778 // have done them all.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007779 for (;;)
7780 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007781 // Get the header to find the length of the stream name. If
7782 // the "readcount" is zero we have done all info streams.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007783 ZeroMemory(&sid, sizeof(WIN32_STREAM_ID));
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007784 headersize = (int)((char *)&sid.cStreamName - (char *)&sid.dwStreamId);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007785 if (!BackupRead(sh, (LPBYTE)&sid, headersize,
7786 &readcount, FALSE, FALSE, &context)
7787 || readcount == 0)
7788 break;
7789
Bram Moolenaar0f873732019-12-05 20:28:46 +01007790 // We only deal with streams that have a name. The normal
7791 // file data appears to be without a name, even though docs
7792 // suggest it is called "::$DATA".
Bram Moolenaar071d4272004-06-13 20:20:40 +00007793 if (sid.dwStreamNameSize > 0)
7794 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007795 // Read the stream name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007796 if (!BackupRead(sh, (LPBYTE)streamname,
7797 sid.dwStreamNameSize,
7798 &readcount, FALSE, FALSE, &context))
7799 break;
7800
Bram Moolenaar0f873732019-12-05 20:28:46 +01007801 // Copy an info stream with a name ":anything:$DATA".
7802 // Skip "::$DATA", it has no stream name (examples suggest
7803 // it might be used for the normal file contents).
7804 // Note that BackupRead() counts bytes, but the name is in
7805 // wide characters.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007806 len = readcount / sizeof(WCHAR);
7807 streamname[len] = 0;
7808 if (len > 7 && wcsicmp(streamname + len - 6,
7809 L":$DATA") == 0)
7810 {
7811 streamname[len - 6] = 0;
7812 copy_substream(sh, &context, tow, streamname,
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00007813 (long)sid.Size.u.LowPart);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007814 }
7815 }
7816
Bram Moolenaar0f873732019-12-05 20:28:46 +01007817 // Advance to the next stream. We might try seeking too far,
7818 // but BackupSeek() doesn't skip over stream borders, thus
7819 // that's OK.
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00007820 (void)BackupSeek(sh, sid.Size.u.LowPart, sid.Size.u.HighPart,
Bram Moolenaar071d4272004-06-13 20:20:40 +00007821 &lo, &hi, &context);
7822 }
7823
Bram Moolenaar0f873732019-12-05 20:28:46 +01007824 // Clear the context.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007825 (void)BackupRead(sh, NULL, 0, &readcount, TRUE, FALSE, &context);
7826
7827 CloseHandle(sh);
7828 }
7829 }
7830 vim_free(fromw);
7831 vim_free(tow);
7832}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007833
7834/*
Bram Moolenaare7bebc42021-02-01 20:50:37 +01007835 * ntdll.dll definitions
7836 */
7837#define FileEaInformation 7
7838#ifndef STATUS_SUCCESS
7839# define STATUS_SUCCESS ((NTSTATUS) 0x00000000L)
7840#endif
7841
7842typedef struct _FILE_FULL_EA_INFORMATION_ {
7843 ULONG NextEntryOffset;
7844 UCHAR Flags;
7845 UCHAR EaNameLength;
7846 USHORT EaValueLength;
7847 CHAR EaName[1];
7848} FILE_FULL_EA_INFORMATION_, *PFILE_FULL_EA_INFORMATION_;
7849
7850typedef struct _FILE_EA_INFORMATION_ {
7851 ULONG EaSize;
7852} FILE_EA_INFORMATION_, *PFILE_EA_INFORMATION_;
7853
Paul Ollis65745772022-06-05 16:55:54 +01007854#ifndef PROTO
Bram Moolenaare7bebc42021-02-01 20:50:37 +01007855typedef NTSTATUS (NTAPI *PfnNtOpenFile)(
7856 PHANDLE FileHandle,
7857 ACCESS_MASK DesiredAccess,
7858 POBJECT_ATTRIBUTES ObjectAttributes,
7859 PIO_STATUS_BLOCK IoStatusBlock,
7860 ULONG ShareAccess,
7861 ULONG OpenOptions);
7862typedef NTSTATUS (NTAPI *PfnNtClose)(
7863 HANDLE Handle);
7864typedef NTSTATUS (NTAPI *PfnNtSetEaFile)(
Bram Moolenaar9f1983d2022-05-12 20:35:35 +01007865 HANDLE FileHandle,
7866 PIO_STATUS_BLOCK IoStatusBlock,
7867 PVOID Buffer,
7868 ULONG Length);
Bram Moolenaare7bebc42021-02-01 20:50:37 +01007869typedef NTSTATUS (NTAPI *PfnNtQueryEaFile)(
7870 HANDLE FileHandle,
7871 PIO_STATUS_BLOCK IoStatusBlock,
7872 PVOID Buffer,
7873 ULONG Length,
7874 BOOLEAN ReturnSingleEntry,
7875 PVOID EaList,
7876 ULONG EaListLength,
7877 PULONG EaIndex,
7878 BOOLEAN RestartScan);
7879typedef NTSTATUS (NTAPI *PfnNtQueryInformationFile)(
Bram Moolenaar9f1983d2022-05-12 20:35:35 +01007880 HANDLE FileHandle,
7881 PIO_STATUS_BLOCK IoStatusBlock,
7882 PVOID FileInformation,
7883 ULONG Length,
Bram Moolenaare7bebc42021-02-01 20:50:37 +01007884 FILE_INFORMATION_CLASS FileInformationClass);
7885typedef VOID (NTAPI *PfnRtlInitUnicodeString)(
7886 PUNICODE_STRING DestinationString,
7887 PCWSTR SourceString);
7888
7889PfnNtOpenFile pNtOpenFile = NULL;
7890PfnNtClose pNtClose = NULL;
7891PfnNtSetEaFile pNtSetEaFile = NULL;
7892PfnNtQueryEaFile pNtQueryEaFile = NULL;
7893PfnNtQueryInformationFile pNtQueryInformationFile = NULL;
7894PfnRtlInitUnicodeString pRtlInitUnicodeString = NULL;
Paul Ollis65745772022-06-05 16:55:54 +01007895#endif
Bram Moolenaare7bebc42021-02-01 20:50:37 +01007896
7897/*
7898 * Load ntdll.dll functions.
7899 */
7900 static BOOL
7901load_ntdll(void)
7902{
7903 static int loaded = -1;
7904
7905 if (loaded == -1)
7906 {
7907 HMODULE hNtdll = GetModuleHandle("ntdll.dll");
7908 if (hNtdll != NULL)
7909 {
7910 pNtOpenFile = (PfnNtOpenFile) GetProcAddress(hNtdll, "NtOpenFile");
7911 pNtClose = (PfnNtClose) GetProcAddress(hNtdll, "NtClose");
7912 pNtSetEaFile = (PfnNtSetEaFile)
7913 GetProcAddress(hNtdll, "NtSetEaFile");
7914 pNtQueryEaFile = (PfnNtQueryEaFile)
7915 GetProcAddress(hNtdll, "NtQueryEaFile");
7916 pNtQueryInformationFile = (PfnNtQueryInformationFile)
7917 GetProcAddress(hNtdll, "NtQueryInformationFile");
7918 pRtlInitUnicodeString = (PfnRtlInitUnicodeString)
7919 GetProcAddress(hNtdll, "RtlInitUnicodeString");
7920 }
7921 if (pNtOpenFile == NULL
7922 || pNtClose == NULL
7923 || pNtSetEaFile == NULL
7924 || pNtQueryEaFile == NULL
7925 || pNtQueryInformationFile == NULL
7926 || pRtlInitUnicodeString == NULL)
7927 loaded = FALSE;
7928 else
7929 loaded = TRUE;
7930 }
7931 return (BOOL) loaded;
7932}
7933
7934/*
7935 * Copy extended attributes (EA) from file "from" to file "to".
7936 */
7937 static void
7938copy_extattr(char_u *from, char_u *to)
7939{
7940 char_u *fromf = NULL;
7941 char_u *tof = NULL;
7942 WCHAR *fromw = NULL;
7943 WCHAR *tow = NULL;
7944 UNICODE_STRING u;
7945 HANDLE h;
7946 OBJECT_ATTRIBUTES oa;
7947 IO_STATUS_BLOCK iosb;
7948 FILE_EA_INFORMATION_ eainfo = {0};
7949 void *ea = NULL;
7950
7951 if (!load_ntdll())
7952 return;
7953
7954 // Convert the file names to the fully qualified object names.
7955 fromf = alloc(STRLEN(from) + 5);
7956 tof = alloc(STRLEN(to) + 5);
7957 if (fromf == NULL || tof == NULL)
7958 goto theend;
7959 STRCPY(fromf, "\\??\\");
7960 STRCAT(fromf, from);
7961 STRCPY(tof, "\\??\\");
7962 STRCAT(tof, to);
7963
7964 // Convert the names to wide characters.
7965 fromw = enc_to_utf16(fromf, NULL);
7966 tow = enc_to_utf16(tof, NULL);
7967 if (fromw == NULL || tow == NULL)
7968 goto theend;
7969
7970 // Get the EA.
7971 pRtlInitUnicodeString(&u, fromw);
7972 InitializeObjectAttributes(&oa, &u, 0, NULL, NULL);
7973 if (pNtOpenFile(&h, FILE_READ_EA, &oa, &iosb, 0,
7974 FILE_NON_DIRECTORY_FILE) != STATUS_SUCCESS)
7975 goto theend;
7976 pNtQueryInformationFile(h, &iosb, &eainfo, sizeof(eainfo),
7977 FileEaInformation);
7978 if (eainfo.EaSize != 0)
7979 {
7980 ea = alloc(eainfo.EaSize);
7981 if (ea != NULL)
7982 {
7983 if (pNtQueryEaFile(h, &iosb, ea, eainfo.EaSize, FALSE,
7984 NULL, 0, NULL, TRUE) != STATUS_SUCCESS)
7985 {
7986 vim_free(ea);
7987 ea = NULL;
7988 }
7989 }
7990 }
7991 pNtClose(h);
7992
7993 // Set the EA.
7994 if (ea != NULL)
7995 {
7996 pRtlInitUnicodeString(&u, tow);
7997 InitializeObjectAttributes(&oa, &u, 0, NULL, NULL);
7998 if (pNtOpenFile(&h, FILE_WRITE_EA, &oa, &iosb, 0,
7999 FILE_NON_DIRECTORY_FILE) != STATUS_SUCCESS)
8000 goto theend;
8001
8002 pNtSetEaFile(h, &iosb, ea, eainfo.EaSize);
8003 pNtClose(h);
8004 }
8005
8006theend:
8007 vim_free(fromf);
8008 vim_free(tof);
8009 vim_free(fromw);
8010 vim_free(tow);
8011 vim_free(ea);
8012}
8013
8014/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00008015 * Copy file attributes from file "from" to file "to".
8016 * For Windows NT and later we copy info streams.
8017 * Always returns zero, errors are ignored.
8018 */
8019 int
8020mch_copy_file_attribute(char_u *from, char_u *to)
8021{
Bram Moolenaar0f873732019-12-05 20:28:46 +01008022 // File streams only work on Windows NT and later.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02008023 copy_infostreams(from, to);
Bram Moolenaare7bebc42021-02-01 20:50:37 +01008024 copy_extattr(from, to);
Bram Moolenaar071d4272004-06-13 20:20:40 +00008025 return 0;
8026}
8027
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008028
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008029/*
K.Takatadc73b4b2021-06-08 18:32:36 +02008030 * The command line arguments in UTF-16
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008031 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00008032static int nArgsW = 0;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008033static LPWSTR *ArglistW = NULL;
8034static int global_argc = 0;
8035static char **global_argv;
8036
Bram Moolenaar0f873732019-12-05 20:28:46 +01008037static int used_file_argc = 0; // last argument in global_argv[] used
8038 // for the argument list.
8039static int *used_file_indexes = NULL; // indexes in global_argv[] for
8040 // command line arguments added to
8041 // the argument list
8042static int used_file_count = 0; // nr of entries in used_file_indexes
8043static int used_file_literal = FALSE; // take file names literally
8044static int used_file_full_path = FALSE; // file name was full path
8045static int used_file_diff_mode = FALSE; // file name was with diff mode
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008046static int used_alist_count = 0;
8047
8048
8049/*
8050 * Get the command line arguments. Unicode version.
8051 * Returns argc. Zero when something fails.
8052 */
8053 int
8054get_cmd_argsW(char ***argvp)
8055{
8056 char **argv = NULL;
8057 int argc = 0;
8058 int i;
8059
Bram Moolenaar14993322014-09-09 12:25:33 +02008060 free_cmd_argsW();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008061 ArglistW = CommandLineToArgvW(GetCommandLineW(), &nArgsW);
8062 if (ArglistW != NULL)
8063 {
8064 argv = malloc((nArgsW + 1) * sizeof(char *));
8065 if (argv != NULL)
8066 {
8067 argc = nArgsW;
8068 argv[argc] = NULL;
8069 for (i = 0; i < argc; ++i)
8070 {
8071 int len;
8072
K.Takatadc73b4b2021-06-08 18:32:36 +02008073 // Convert each Unicode argument to UTF-8.
8074 WideCharToMultiByte_alloc(CP_UTF8, 0,
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00008075 ArglistW[i], (int)wcslen(ArglistW[i]) + 1,
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008076 (LPSTR *)&argv[i], &len, 0, 0);
8077 if (argv[i] == NULL)
8078 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01008079 // Out of memory, clear everything.
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008080 while (i > 0)
8081 free(argv[--i]);
8082 free(argv);
Bram Moolenaar73c61632013-12-07 14:48:10 +01008083 argv = NULL;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008084 argc = 0;
8085 }
8086 }
8087 }
8088 }
8089
8090 global_argc = argc;
8091 global_argv = argv;
8092 if (argc > 0)
Bram Moolenaar14993322014-09-09 12:25:33 +02008093 {
8094 if (used_file_indexes != NULL)
8095 free(used_file_indexes);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008096 used_file_indexes = malloc(argc * sizeof(int));
Bram Moolenaar14993322014-09-09 12:25:33 +02008097 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008098
8099 if (argvp != NULL)
8100 *argvp = argv;
8101 return argc;
8102}
8103
8104 void
8105free_cmd_argsW(void)
8106{
8107 if (ArglistW != NULL)
8108 {
8109 GlobalFree(ArglistW);
8110 ArglistW = NULL;
8111 }
8112}
8113
8114/*
8115 * Remember "name" is an argument that was added to the argument list.
8116 * This avoids that we have to re-parse the argument list when fix_arg_enc()
8117 * is called.
8118 */
8119 void
Bram Moolenaar910f66f2006-04-05 20:41:53 +00008120used_file_arg(char *name, int literal, int full_path, int diff_mode)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008121{
8122 int i;
8123
8124 if (used_file_indexes == NULL)
8125 return;
8126 for (i = used_file_argc + 1; i < global_argc; ++i)
8127 if (STRCMP(global_argv[i], name) == 0)
8128 {
8129 used_file_argc = i;
8130 used_file_indexes[used_file_count++] = i;
8131 break;
8132 }
8133 used_file_literal = literal;
8134 used_file_full_path = full_path;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00008135 used_file_diff_mode = diff_mode;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008136}
8137
8138/*
8139 * Remember the length of the argument list as it was. If it changes then we
8140 * leave it alone when 'encoding' is set.
8141 */
8142 void
8143set_alist_count(void)
8144{
8145 used_alist_count = GARGCOUNT;
8146}
8147
8148/*
8149 * Fix the encoding of the command line arguments. Invoked when 'encoding'
K.Takatadc73b4b2021-06-08 18:32:36 +02008150 * has been changed while starting up. Use the UTF-16 command line arguments
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008151 * and convert them to 'encoding'.
8152 */
8153 void
8154fix_arg_enc(void)
8155{
8156 int i;
8157 int idx;
8158 char_u *str;
Bram Moolenaar86b68352004-12-27 21:59:20 +00008159 int *fnum_list;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008160
Bram Moolenaar0f873732019-12-05 20:28:46 +01008161 // Safety checks:
8162 // - if argument count differs between the wide and non-wide argument
8163 // list, something must be wrong.
8164 // - the file name arguments must have been located.
8165 // - the length of the argument list wasn't changed by the user.
Bram Moolenaard857f0e2005-06-21 22:37:39 +00008166 if (global_argc != nArgsW
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008167 || ArglistW == NULL
8168 || used_file_indexes == NULL
8169 || used_file_count == 0
8170 || used_alist_count != GARGCOUNT)
8171 return;
8172
Bram Moolenaar0f873732019-12-05 20:28:46 +01008173 // Remember the buffer numbers for the arguments.
Bram Moolenaarc799fe22019-05-28 23:08:19 +02008174 fnum_list = ALLOC_MULT(int, GARGCOUNT);
Bram Moolenaar86b68352004-12-27 21:59:20 +00008175 if (fnum_list == NULL)
Bram Moolenaar0f873732019-12-05 20:28:46 +01008176 return; // out of memory
Bram Moolenaar86b68352004-12-27 21:59:20 +00008177 for (i = 0; i < GARGCOUNT; ++i)
8178 fnum_list[i] = GARGLIST[i].ae_fnum;
8179
Bram Moolenaar0f873732019-12-05 20:28:46 +01008180 // Clear the argument list. Make room for the new arguments.
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008181 alist_clear(&global_alist);
8182 if (ga_grow(&global_alist.al_ga, used_file_count) == FAIL)
Bram Moolenaar0f873732019-12-05 20:28:46 +01008183 return; // out of memory
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008184
8185 for (i = 0; i < used_file_count; ++i)
8186 {
8187 idx = used_file_indexes[i];
Bram Moolenaar36f692d2008-11-20 16:10:17 +00008188 str = utf16_to_enc(ArglistW[idx], NULL);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008189 if (str != NULL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00008190 {
Bram Moolenaar39d21e32017-08-05 23:09:31 +02008191 int literal = used_file_literal;
8192
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01008193#ifdef FEAT_DIFF
Bram Moolenaar0f873732019-12-05 20:28:46 +01008194 // When using diff mode may need to concatenate file name to
8195 // directory name. Just like it's done in main().
Bram Moolenaar910f66f2006-04-05 20:41:53 +00008196 if (used_file_diff_mode && mch_isdir(str) && GARGCOUNT > 0
8197 && !mch_isdir(alist_name(&GARGLIST[0])))
8198 {
8199 char_u *r;
8200
8201 r = concat_fnames(str, gettail(alist_name(&GARGLIST[0])), TRUE);
8202 if (r != NULL)
8203 {
8204 vim_free(str);
8205 str = r;
8206 }
8207 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01008208#endif
Bram Moolenaar0f873732019-12-05 20:28:46 +01008209 // Re-use the old buffer by renaming it. When not using literal
8210 // names it's done by alist_expand() below.
Bram Moolenaar86b68352004-12-27 21:59:20 +00008211 if (used_file_literal)
8212 buf_set_name(fnum_list[i], str);
8213
Bram Moolenaar0f873732019-12-05 20:28:46 +01008214 // Check backtick literal. backtick literal is already expanded in
8215 // main.c, so this part add str as literal.
Bram Moolenaar39d21e32017-08-05 23:09:31 +02008216 if (literal == FALSE)
8217 {
Bram Moolenaar116a0f82017-08-07 21:17:57 +02008218 size_t len = STRLEN(str);
8219
Bram Moolenaar39d21e32017-08-05 23:09:31 +02008220 if (len > 2 && *str == '`' && *(str + len - 1) == '`')
8221 literal = TRUE;
8222 }
8223 alist_add(&global_alist, str, literal ? 2 : 0);
Bram Moolenaar86b68352004-12-27 21:59:20 +00008224 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008225 }
8226
8227 if (!used_file_literal)
8228 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01008229 // Now expand wildcards in the arguments.
8230 // Temporarily add '(' and ')' to 'isfname'. These are valid
8231 // filename characters but are excluded from 'isfname' to make
Dominique Pelleaf4a61a2021-12-27 17:21:41 +00008232 // "gf" work on a file name in parentheses (e.g.: see vim.h).
Bram Moolenaar0f873732019-12-05 20:28:46 +01008233 // Also, unset wildignore to not be influenced by this option.
8234 // The arguments specified in command-line should be kept even if
8235 // encoding options were changed.
Christian Brabandtfd916d62021-11-01 22:44:33 +00008236 // Use :legacy so that it also works when in Vim9 script.
8237 do_cmdline_cmd((char_u *)":legacy let g:SaVe_ISF = &isf|set isf+=(,)");
8238 do_cmdline_cmd((char_u *)":legacy let g:SaVe_WIG = &wig|set wig=");
Bram Moolenaar86b68352004-12-27 21:59:20 +00008239 alist_expand(fnum_list, used_alist_count);
Christian Brabandtfd916d62021-11-01 22:44:33 +00008240 do_cmdline_cmd(
8241 (char_u *)":legacy let &isf = g:SaVe_ISF|unlet g:SaVe_ISF");
8242 do_cmdline_cmd(
8243 (char_u *)":legacy let &wig = g:SaVe_WIG|unlet g:SaVe_WIG");
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008244 }
8245
Bram Moolenaar0f873732019-12-05 20:28:46 +01008246 // If wildcard expansion failed, we are editing the first file of the
8247 // arglist and there is no file name: Edit the first argument now.
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008248 if (curwin->w_arg_idx == 0 && curbuf->b_fname == NULL)
8249 {
8250 do_cmdline_cmd((char_u *)":rewind");
Bram Moolenaar05268152021-11-18 18:53:45 +00008251 if (GARGCOUNT == 1 && used_file_full_path
8252 && vim_chdirfile(alist_name(&GARGLIST[0]), "drop") == OK)
8253 last_chdir_reason = "drop";
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008254 }
Bram Moolenaar86b68352004-12-27 21:59:20 +00008255
8256 set_alist_count();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008257}
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01008258
8259 int
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02008260mch_setenv(char *var, char *value, int x UNUSED)
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01008261{
8262 char_u *envbuf;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02008263 WCHAR *p;
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01008264
Bram Moolenaar964b3742019-05-24 18:54:09 +02008265 envbuf = alloc(STRLEN(var) + STRLEN(value) + 2);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01008266 if (envbuf == NULL)
8267 return -1;
8268
8269 sprintf((char *)envbuf, "%s=%s", var, value);
8270
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02008271 p = enc_to_utf16(envbuf, NULL);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01008272
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02008273 vim_free(envbuf);
8274 if (p == NULL)
8275 return -1;
8276 _wputenv(p);
Bram Moolenaara12a1612019-01-24 16:39:02 +01008277#ifdef libintl_wputenv
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02008278 libintl_wputenv(p);
Bram Moolenaara12a1612019-01-24 16:39:02 +01008279#endif
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02008280 // Unlike Un*x systems, we can free the string for _wputenv().
8281 vim_free(p);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01008282
8283 return 0;
8284}
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008285
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008286/*
8287 * Support for 256 colors and 24-bit colors was added in Windows 10
8288 * version 1703 (Creators update).
8289 */
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008290#define VTP_FIRST_SUPPORT_BUILD MAKE_VER(10, 0, 15063)
8291
8292/*
8293 * Support for pseudo-console (ConPTY) was added in windows 10
Bram Moolenaar57da6982019-09-13 22:30:11 +02008294 * version 1809 (October 2018 update).
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008295 */
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01008296#define CONPTY_FIRST_SUPPORT_BUILD MAKE_VER(10, 0, 17763)
Bram Moolenaar57da6982019-09-13 22:30:11 +02008297
8298/*
8299 * ConPTY differences between versions, need different logic.
8300 * version 1903 (May 2019 update).
8301 */
8302#define CONPTY_1903_BUILD MAKE_VER(10, 0, 18362)
8303
8304/*
Bram Moolenaar36e7a822019-11-13 21:49:24 +01008305 * version 1909 (November 2019 update).
8306 */
8307#define CONPTY_1909_BUILD MAKE_VER(10, 0, 18363)
8308
8309/*
Bram Moolenaar7ed8f592020-04-28 20:44:42 +02008310 * Stay ahead of the next update, and when it's done, fix this.
8311 * version ? (2020 update, temporarily use the build number of insider preview)
8312 */
8313#define CONPTY_NEXT_UPDATE_BUILD MAKE_VER(10, 0, 19587)
8314
8315/*
Bram Moolenaar57da6982019-09-13 22:30:11 +02008316 * Confirm until this version. Also the logic changes.
8317 * insider preview.
8318 */
Bram Moolenaar4c063dd2019-10-04 21:29:12 +02008319#define CONPTY_INSIDER_BUILD MAKE_VER(10, 0, 18995)
Bram Moolenaar57da6982019-09-13 22:30:11 +02008320
8321/*
8322 * Not stable now.
8323 */
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01008324#define CONPTY_STABLE_BUILD MAKE_VER(10, 0, 32767) // T.B.D.
Christopher Plewright1140b512022-11-12 18:46:05 +00008325// Notes:
8326// Win 10 22H2 Final is build 19045, it's conpty is widely used.
8327// Strangely, 19045 is newer but is a lower build number than the 2020 insider
8328// preview which had a build 19587. And, not sure how stable that was?
8329// Win Server 2022 (May 10, 2022) is build 20348, its conpty is widely used.
8330// Win 11 starts from build 22000, even though the major version says 10!
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008331
8332 static void
8333vtp_flag_init(void)
8334{
8335 DWORD ver = get_build_number();
Bram Moolenaarafde13b2019-04-28 19:46:49 +02008336#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008337 DWORD mode;
8338 HANDLE out;
8339
Bram Moolenaarafde13b2019-04-28 19:46:49 +02008340# ifdef VIMDLL
8341 if (!gui.in_use)
8342# endif
8343 {
8344 out = GetStdHandle(STD_OUTPUT_HANDLE);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008345
Bram Moolenaarafde13b2019-04-28 19:46:49 +02008346 vtp_working = (ver >= VTP_FIRST_SUPPORT_BUILD) ? 1 : 0;
8347 GetConsoleMode(out, &mode);
8348 mode |= (ENABLE_PROCESSED_OUTPUT | ENABLE_VIRTUAL_TERMINAL_PROCESSING);
8349 if (SetConsoleMode(out, mode) == 0)
8350 vtp_working = 0;
8351 }
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008352#endif
8353
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008354 if (ver >= CONPTY_FIRST_SUPPORT_BUILD)
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01008355 conpty_working = 1;
8356 if (ver >= CONPTY_STABLE_BUILD)
8357 conpty_stable = 1;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008358
Bram Moolenaar57da6982019-09-13 22:30:11 +02008359 if (ver <= CONPTY_INSIDER_BUILD)
8360 conpty_type = 3;
Bram Moolenaar36e7a822019-11-13 21:49:24 +01008361 if (ver <= CONPTY_1909_BUILD)
8362 conpty_type = 2;
Bram Moolenaar57da6982019-09-13 22:30:11 +02008363 if (ver <= CONPTY_1903_BUILD)
8364 conpty_type = 2;
8365 if (ver < CONPTY_FIRST_SUPPORT_BUILD)
8366 conpty_type = 1;
Bram Moolenaar7ed8f592020-04-28 20:44:42 +02008367
8368 if (ver >= CONPTY_NEXT_UPDATE_BUILD)
8369 conpty_fix_type = 1;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008370}
8371
Bram Moolenaarafde13b2019-04-28 19:46:49 +02008372#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL) || defined(PROTO)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008373
8374 static void
8375vtp_init(void)
8376{
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02008377# ifdef FEAT_TERMGUICOLORS
Christopher Plewright38804d62022-11-09 23:55:52 +00008378 if (!vtp_working)
Yasuhiro Matsumotoe42c8da2022-09-01 11:31:45 +01008379 {
Christopher Plewright38804d62022-11-09 23:55:52 +00008380 CONSOLE_SCREEN_BUFFER_INFOEX csbi;
8381 csbi.cbSize = sizeof(csbi);
8382 GetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
8383 save_console_bg_rgb = (guicolor_T)csbi.ColorTable[g_color_index_bg];
8384 save_console_fg_rgb = (guicolor_T)csbi.ColorTable[g_color_index_fg];
8385 store_console_bg_rgb = save_console_bg_rgb;
8386 store_console_fg_rgb = save_console_fg_rgb;
8387
Yasuhiro Matsumotoe42c8da2022-09-01 11:31:45 +01008388 COLORREF bg;
8389 bg = (COLORREF)csbi.ColorTable[g_color_index_bg];
8390 bg = (GetRValue(bg) << 16) | (GetGValue(bg) << 8) | GetBValue(bg);
8391 default_console_color_bg = bg;
Christopher Plewright38804d62022-11-09 23:55:52 +00008392
8393 COLORREF fg;
8394 fg = (COLORREF)csbi.ColorTable[g_color_index_fg];
8395 fg = (GetRValue(fg) << 16) | (GetGValue(fg) << 8) | GetBValue(fg);
8396 default_console_color_fg = fg;
Yasuhiro Matsumotoe42c8da2022-09-01 11:31:45 +01008397 }
Bram Moolenaarc4568ab2018-11-16 16:21:05 +01008398# endif
Christopher Plewrightc8b126d2022-12-22 13:45:23 +00008399 use_alternate_screen_buffer = win10_22H2_or_later && p_rs && vtp_working
Bram Moolenaar9fca1332022-12-22 21:06:41 +00008400 && !mch_getenv("VIM_TERMINAL");
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008401 set_console_color_rgb();
8402}
8403
8404 static void
8405vtp_exit(void)
8406{
Bram Moolenaardf543822020-01-30 11:53:59 +01008407 restore_console_color_rgb();
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008408}
8409
Bram Moolenaar06b7b582020-05-30 17:49:25 +02008410 int
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008411vtp_printf(
8412 char *format,
8413 ...)
8414{
8415 char_u buf[100];
8416 va_list list;
8417 DWORD result;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008418 int len;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008419
8420 va_start(list, format);
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008421 len = vim_vsnprintf((char *)buf, 100, (char *)format, list);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008422 va_end(list);
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008423 WriteConsoleA(g_hConOut, buf, (DWORD)len, &result, NULL);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008424 return (int)result;
8425}
8426
8427 static void
8428vtp_sgr_bulk(
8429 int arg)
8430{
8431 int args[1];
8432
8433 args[0] = arg;
8434 vtp_sgr_bulks(1, args);
8435}
8436
K.Takata6e1d31e2022-02-03 13:05:32 +00008437# define FAST256(x) \
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008438 if ((*p-- = "0123456789"[(n = x % 10)]) \
8439 && x >= 10 && (*p-- = "0123456789"[((m = x % 100) - n) / 10]) \
8440 && x >= 100 && (*p-- = "012"[((x & 0xff) - m) / 100]));
8441
K.Takata6e1d31e2022-02-03 13:05:32 +00008442# define FAST256CASE(x) \
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008443 case x: \
8444 FAST256(newargs[x - 1]);
8445
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008446 static void
8447vtp_sgr_bulks(
8448 int argc,
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008449 int *args)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008450{
K.Takata6e1d31e2022-02-03 13:05:32 +00008451# define MAXSGR 16
8452# define SGRBUFSIZE 2 + 4 * MAXSGR + 1 // '\033[' + SGR + 'm'
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008453 char_u buf[SGRBUFSIZE];
8454 char_u *p;
8455 int in, out;
8456 int newargs[16];
8457 static int sgrfgr = -1, sgrfgg, sgrfgb;
8458 static int sgrbgr = -1, sgrbgg, sgrbgb;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008459
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008460 if (argc == 0)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008461 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008462 sgrfgr = sgrbgr = -1;
K.Takatadf5320c2022-09-01 13:20:16 +01008463 vtp_printf("\033[m");
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008464 return;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008465 }
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008466
8467 in = out = 0;
8468 while (in < argc)
8469 {
8470 int s = args[in];
8471 int copylen = 1;
8472
8473 if (s == 38)
8474 {
8475 if (argc - in >= 5 && args[in + 1] == 2)
8476 {
8477 if (sgrfgr == args[in + 2] && sgrfgg == args[in + 3]
8478 && sgrfgb == args[in + 4])
8479 {
8480 in += 5;
8481 copylen = 0;
8482 }
8483 else
8484 {
8485 sgrfgr = args[in + 2];
8486 sgrfgg = args[in + 3];
8487 sgrfgb = args[in + 4];
8488 copylen = 5;
8489 }
8490 }
8491 else if (argc - in >= 3 && args[in + 1] == 5)
8492 {
8493 sgrfgr = -1;
8494 copylen = 3;
8495 }
8496 }
8497 else if (s == 48)
8498 {
8499 if (argc - in >= 5 && args[in + 1] == 2)
8500 {
8501 if (sgrbgr == args[in + 2] && sgrbgg == args[in + 3]
8502 && sgrbgb == args[in + 4])
8503 {
8504 in += 5;
8505 copylen = 0;
8506 }
8507 else
8508 {
8509 sgrbgr = args[in + 2];
8510 sgrbgg = args[in + 3];
8511 sgrbgb = args[in + 4];
8512 copylen = 5;
8513 }
8514 }
8515 else if (argc - in >= 3 && args[in + 1] == 5)
8516 {
8517 sgrbgr = -1;
8518 copylen = 3;
8519 }
8520 }
8521 else if (30 <= s && s <= 39)
8522 sgrfgr = -1;
8523 else if (90 <= s && s <= 97)
8524 sgrfgr = -1;
8525 else if (40 <= s && s <= 49)
8526 sgrbgr = -1;
8527 else if (100 <= s && s <= 107)
8528 sgrbgr = -1;
8529 else if (s == 0)
8530 sgrfgr = sgrbgr = -1;
8531
8532 while (copylen--)
8533 newargs[out++] = args[in++];
8534 }
8535
8536 p = &buf[sizeof(buf) - 1];
8537 *p-- = 'm';
8538
8539 switch (out)
8540 {
8541 int n, m;
8542 DWORD r;
8543
8544 FAST256CASE(16);
8545 *p-- = ';';
8546 FAST256CASE(15);
8547 *p-- = ';';
8548 FAST256CASE(14);
8549 *p-- = ';';
8550 FAST256CASE(13);
8551 *p-- = ';';
8552 FAST256CASE(12);
8553 *p-- = ';';
8554 FAST256CASE(11);
8555 *p-- = ';';
8556 FAST256CASE(10);
8557 *p-- = ';';
8558 FAST256CASE(9);
8559 *p-- = ';';
8560 FAST256CASE(8);
8561 *p-- = ';';
8562 FAST256CASE(7);
8563 *p-- = ';';
8564 FAST256CASE(6);
8565 *p-- = ';';
8566 FAST256CASE(5);
8567 *p-- = ';';
8568 FAST256CASE(4);
8569 *p-- = ';';
8570 FAST256CASE(3);
8571 *p-- = ';';
8572 FAST256CASE(2);
8573 *p-- = ';';
8574 FAST256CASE(1);
8575 *p-- = '[';
8576 *p = '\033';
8577 WriteConsoleA(g_hConOut, p, (DWORD)(&buf[SGRBUFSIZE] - p), &r, NULL);
8578 default:
8579 break;
8580 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008581}
8582
Bram Moolenaar06b7b582020-05-30 17:49:25 +02008583 static void
8584wt_init(void)
8585{
Christopher Plewright1140b512022-11-12 18:46:05 +00008586 wt_working = mch_getenv("WT_SESSION") != NULL;
Bram Moolenaar06b7b582020-05-30 17:49:25 +02008587}
8588
Bram Moolenaar8a938af2018-05-01 17:30:41 +02008589# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02008590 static int
8591ctermtoxterm(
8592 int cterm)
8593{
Bram Moolenaar9894e392018-05-05 14:29:06 +02008594 char_u r, g, b, idx;
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02008595
8596 cterm_color2rgb(cterm, &r, &g, &b, &idx);
8597 return (((int)r << 16) | ((int)g << 8) | (int)b);
8598}
Bram Moolenaar8a938af2018-05-01 17:30:41 +02008599# endif
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02008600
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008601 static void
8602set_console_color_rgb(void)
8603{
8604# ifdef FEAT_TERMGUICOLORS
K.Takata27b53be2022-09-18 12:25:49 +01008605 CONSOLE_SCREEN_BUFFER_INFOEX csbi;
Bram Moolenaara050b942019-12-02 21:35:31 +01008606 guicolor_T fg, bg;
8607 int ctermfg, ctermbg;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008608
Christopher Plewright38804d62022-11-09 23:55:52 +00008609 if (!vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008610 return;
8611
Bram Moolenaara050b942019-12-02 21:35:31 +01008612 get_default_console_color(&ctermfg, &ctermbg, &fg, &bg);
8613
Christopher Plewright38804d62022-11-09 23:55:52 +00008614 if (p_tgc || t_colors >= 256)
Bram Moolenaar06b7b582020-05-30 17:49:25 +02008615 {
8616 term_fg_rgb_color(fg);
8617 term_bg_rgb_color(bg);
8618 return;
8619 }
8620
Christopher Plewright38804d62022-11-09 23:55:52 +00008621 if (!conpty_working)
8622 {
8623 fg = (GetRValue(fg) << 16) | (GetGValue(fg) << 8) | GetBValue(fg);
8624 bg = (GetRValue(bg) << 16) | (GetGValue(bg) << 8) | GetBValue(bg);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008625
Christopher Plewright38804d62022-11-09 23:55:52 +00008626 csbi.cbSize = sizeof(csbi);
8627 GetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008628
Christopher Plewright38804d62022-11-09 23:55:52 +00008629 csbi.cbSize = sizeof(csbi);
8630 csbi.srWindow.Right += 1;
8631 csbi.srWindow.Bottom += 1;
8632 store_console_bg_rgb = csbi.ColorTable[g_color_index_bg];
8633 store_console_fg_rgb = csbi.ColorTable[g_color_index_fg];
8634 csbi.ColorTable[g_color_index_bg] = (COLORREF)bg;
8635 csbi.ColorTable[g_color_index_fg] = (COLORREF)fg;
8636 SetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
8637 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008638# endif
8639}
8640
Bram Moolenaara050b942019-12-02 21:35:31 +01008641# if defined(FEAT_TERMGUICOLORS) || defined(PROTO)
8642 void
8643get_default_console_color(
8644 int *cterm_fg,
8645 int *cterm_bg,
8646 guicolor_T *gui_fg,
8647 guicolor_T *gui_bg)
8648{
8649 int id;
8650 guicolor_T guifg = INVALCOLOR;
8651 guicolor_T guibg = INVALCOLOR;
8652 int ctermfg = 0;
8653 int ctermbg = 0;
Christopher Plewright38804d62022-11-09 23:55:52 +00008654 int dummynull = 0;
Bram Moolenaara050b942019-12-02 21:35:31 +01008655
8656 id = syn_name2id((char_u *)"Normal");
8657 if (id > 0 && p_tgc)
8658 syn_id2colors(id, &guifg, &guibg);
8659 if (guifg == INVALCOLOR)
8660 {
8661 ctermfg = -1;
8662 if (id > 0)
Christopher Plewright38804d62022-11-09 23:55:52 +00008663 syn_id2cterm_bg(id, &ctermfg, &dummynull);
8664 if (vtp_working)
8665 {
8666 cterm_normal_fg_gui_color = guifg =
8667 ctermfg != -1 ? ctermtoxterm(ctermfg) : INVALCOLOR;
8668 ctermfg = ctermfg < 0 ? 0 : ctermfg;
8669 }
8670 else
8671 {
8672 guifg = ctermfg != -1 ? ctermtoxterm(ctermfg)
Bram Moolenaara050b942019-12-02 21:35:31 +01008673 : default_console_color_fg;
Christopher Plewright38804d62022-11-09 23:55:52 +00008674 cterm_normal_fg_gui_color = guifg;
8675 ctermfg = ctermfg < 0 ? 0 : ctermfg;
8676 }
Bram Moolenaara050b942019-12-02 21:35:31 +01008677 }
8678 if (guibg == INVALCOLOR)
8679 {
8680 ctermbg = -1;
8681 if (id > 0)
Christopher Plewright38804d62022-11-09 23:55:52 +00008682 syn_id2cterm_bg(id, &dummynull, &ctermbg);
8683 if (vtp_working)
Yasuhiro Matsumotoe42c8da2022-09-01 11:31:45 +01008684 {
8685 cterm_normal_bg_gui_color = guibg =
Yasuhiro Matsumotoaa04e1b2022-05-07 14:09:19 +01008686 ctermbg != -1 ? ctermtoxterm(ctermbg) : INVALCOLOR;
Yasuhiro Matsumotoe42c8da2022-09-01 11:31:45 +01008687 if (ctermbg < 0)
8688 ctermbg = 0;
8689 }
K.Takatae53a0d42022-09-05 21:45:11 +01008690 else
8691 {
8692 guibg = ctermbg != -1 ? ctermtoxterm(ctermbg)
8693 : default_console_color_bg;
8694 cterm_normal_bg_gui_color = guibg;
8695 ctermbg = ctermbg < 0 ? 0 : ctermbg;
8696 }
Bram Moolenaara050b942019-12-02 21:35:31 +01008697 }
8698
8699 *cterm_fg = ctermfg;
8700 *cterm_bg = ctermbg;
8701 *gui_fg = guifg;
8702 *gui_bg = guibg;
8703}
8704# endif
8705
Bram Moolenaardf543822020-01-30 11:53:59 +01008706/*
8707 * Set the console colors to the original colors or the last set colors.
8708 */
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008709 static void
8710reset_console_color_rgb(void)
8711{
8712# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008713
Christopher Plewright38804d62022-11-09 23:55:52 +00008714 if (vtp_working)
Bram Moolenaar06b7b582020-05-30 17:49:25 +02008715 return;
8716
Christopher Plewright38804d62022-11-09 23:55:52 +00008717 CONSOLE_SCREEN_BUFFER_INFOEX csbi;
8718
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008719 csbi.cbSize = sizeof(csbi);
K.Takata27b53be2022-09-18 12:25:49 +01008720 GetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008721
8722 csbi.cbSize = sizeof(csbi);
8723 csbi.srWindow.Right += 1;
8724 csbi.srWindow.Bottom += 1;
Bram Moolenaardf543822020-01-30 11:53:59 +01008725 csbi.ColorTable[g_color_index_bg] = (COLORREF)store_console_bg_rgb;
8726 csbi.ColorTable[g_color_index_fg] = (COLORREF)store_console_fg_rgb;
K.Takata27b53be2022-09-18 12:25:49 +01008727 SetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaardf543822020-01-30 11:53:59 +01008728# endif
8729}
8730
8731/*
8732 * Set the console colors to the original colors.
8733 */
8734 static void
8735restore_console_color_rgb(void)
8736{
8737# ifdef FEAT_TERMGUICOLORS
Christopher Plewright38804d62022-11-09 23:55:52 +00008738 if (vtp_working)
8739 return;
8740
K.Takata27b53be2022-09-18 12:25:49 +01008741 CONSOLE_SCREEN_BUFFER_INFOEX csbi;
Bram Moolenaardf543822020-01-30 11:53:59 +01008742
8743 csbi.cbSize = sizeof(csbi);
K.Takata27b53be2022-09-18 12:25:49 +01008744 GetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaardf543822020-01-30 11:53:59 +01008745
8746 csbi.cbSize = sizeof(csbi);
8747 csbi.srWindow.Right += 1;
8748 csbi.srWindow.Bottom += 1;
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02008749 csbi.ColorTable[g_color_index_bg] = (COLORREF)save_console_bg_rgb;
8750 csbi.ColorTable[g_color_index_fg] = (COLORREF)save_console_fg_rgb;
K.Takata27b53be2022-09-18 12:25:49 +01008751 SetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008752# endif
8753}
8754
8755 void
8756control_console_color_rgb(void)
8757{
Christopher Plewright38804d62022-11-09 23:55:52 +00008758 if (vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008759 set_console_color_rgb();
8760 else
8761 reset_console_color_rgb();
8762}
8763
8764 int
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008765use_vtp(void)
8766{
8767 return USE_VTP;
8768}
8769
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02008770 int
8771is_term_win32(void)
8772{
8773 return T_NAME != NULL && STRCMP(T_NAME, "win32") == 0;
8774}
8775
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008776 int
8777has_vtp_working(void)
8778{
8779 return vtp_working;
8780}
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01008781
Bram Moolenaar6902c0e2019-02-16 14:07:37 +01008782#endif
8783
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01008784 int
8785has_conpty_working(void)
8786{
8787 return conpty_working;
8788}
8789
8790 int
Bram Moolenaar57da6982019-09-13 22:30:11 +02008791get_conpty_type(void)
8792{
8793 return conpty_type;
8794}
8795
8796 int
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01008797is_conpty_stable(void)
8798{
8799 return conpty_stable;
8800}
Bram Moolenaar78d21da2019-02-17 15:00:52 +01008801
Bram Moolenaar7ed8f592020-04-28 20:44:42 +02008802 int
8803get_conpty_fix_type(void)
8804{
8805 return conpty_fix_type;
8806}
8807
Bram Moolenaarafde13b2019-04-28 19:46:49 +02008808#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL) || defined(PROTO)
Bram Moolenaar78d21da2019-02-17 15:00:52 +01008809 void
8810resize_console_buf(void)
8811{
8812 CONSOLE_SCREEN_BUFFER_INFO csbi;
8813 COORD coord;
8814 SMALL_RECT newsize;
8815
8816 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
8817 {
8818 coord.X = SRWIDTH(csbi.srWindow);
8819 coord.Y = SRHEIGHT(csbi.srWindow);
8820 SetConsoleScreenBufferSize(g_hConOut, coord);
8821
8822 newsize.Left = 0;
8823 newsize.Top = 0;
8824 newsize.Right = coord.X - 1;
8825 newsize.Bottom = coord.Y - 1;
8826 SetConsoleWindowInfo(g_hConOut, TRUE, &newsize);
8827
8828 SetConsoleScreenBufferSize(g_hConOut, coord);
8829 }
8830}
8831#endif
Martin Tournoij1a3e5742021-07-24 13:57:29 +02008832
8833 char *
8834GetWin32Error(void)
8835{
K.Takatad68b2fc2022-02-12 11:18:37 +00008836 static char *oldmsg = NULL;
Martin Tournoij1a3e5742021-07-24 13:57:29 +02008837 char *msg = NULL;
K.Takatad68b2fc2022-02-12 11:18:37 +00008838
Martin Tournoij1a3e5742021-07-24 13:57:29 +02008839 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER|FORMAT_MESSAGE_FROM_SYSTEM,
8840 NULL, GetLastError(), 0, (LPSTR)&msg, 0, NULL);
K.Takatad68b2fc2022-02-12 11:18:37 +00008841 if (oldmsg != NULL)
8842 LocalFree(oldmsg);
Martin Tournoij1a3e5742021-07-24 13:57:29 +02008843 if (msg != NULL)
8844 {
8845 // remove trailing \r\n
8846 char *pcrlf = strstr(msg, "\r\n");
8847 if (pcrlf != NULL)
8848 *pcrlf = '\0';
K.Takatad68b2fc2022-02-12 11:18:37 +00008849 oldmsg = msg;
Martin Tournoij1a3e5742021-07-24 13:57:29 +02008850 }
8851 return msg;
8852}
Paul Ollis65745772022-06-05 16:55:54 +01008853
8854#if defined(FEAT_RELTIME) || defined(PROTO)
8855static HANDLE timer_handle;
8856static int timer_active = FALSE;
8857
8858/*
8859 * Calls to start_timeout alternate the return value pointer between the two
8860 * entries in timeout_flags. If the previously active timeout is very close to
8861 * expiring when start_timeout() is called then a race condition means that the
8862 * set_flag() function may still be invoked after the previous timer is
8863 * deleted. Ping-ponging between the two flags prevents this causing 'fake'
8864 * timeouts.
8865 */
Bram Moolenaar155f2d12022-06-20 13:38:33 +01008866static sig_atomic_t timeout_flags[2];
8867static int timeout_flag_idx = 0;
8868static sig_atomic_t *timeout_flag = &timeout_flags[0];
Paul Ollis65745772022-06-05 16:55:54 +01008869
8870
8871 static void CALLBACK
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +01008872set_flag(void *param, BOOLEAN unused2 UNUSED)
Paul Ollis65745772022-06-05 16:55:54 +01008873{
8874 int *timeout_flag = (int *)param;
8875
8876 *timeout_flag = TRUE;
8877}
8878
8879/*
8880 * Stop any active timeout.
8881 */
8882 void
8883stop_timeout(void)
8884{
8885 if (timer_active)
8886 {
Christopher Plewright2a46f812022-10-16 19:47:45 +01008887 BOOL ret = DeleteTimerQueueTimer(NULL, timer_handle, NULL);
Paul Ollis65745772022-06-05 16:55:54 +01008888 timer_active = FALSE;
8889 if (!ret && GetLastError() != ERROR_IO_PENDING)
8890 {
8891 semsg(_(e_could_not_clear_timeout_str), GetWin32Error());
8892 }
8893 }
8894 *timeout_flag = FALSE;
8895}
8896
8897/*
8898 * Start the timeout timer.
8899 *
8900 * The period is defined in milliseconds.
8901 *
8902 * The return value is a pointer to a flag that is initialised to 0. If the
8903 * timeout expires, the flag is set to 1. This will only return pointers to
8904 * static memory; i.e. any pointer returned by this function may always be
8905 * safely dereferenced.
8906 *
8907 * This function is not expected to fail, but if it does it still returns a
8908 * valid flag pointer; the flag will remain stuck at zero.
8909 */
Bram Moolenaar155f2d12022-06-20 13:38:33 +01008910 volatile sig_atomic_t *
Paul Ollis65745772022-06-05 16:55:54 +01008911start_timeout(long msec)
8912{
Paul Ollis65745772022-06-05 16:55:54 +01008913 BOOL ret;
8914
Bram Moolenaar1f30caf2022-06-19 14:36:35 +01008915 timeout_flag = &timeout_flags[timeout_flag_idx];
Paul Ollis65745772022-06-05 16:55:54 +01008916
8917 stop_timeout();
8918 ret = CreateTimerQueueTimer(
8919 &timer_handle, NULL, set_flag, timeout_flag,
8920 (DWORD)msec, 0, WT_EXECUTEDEFAULT);
8921 if (!ret)
8922 {
8923 semsg(_(e_could_not_set_timeout_str), GetWin32Error());
8924 }
8925 else
8926 {
Bram Moolenaar1f30caf2022-06-19 14:36:35 +01008927 timeout_flag_idx = (timeout_flag_idx + 1) % 2;
Paul Ollis65745772022-06-05 16:55:54 +01008928 timer_active = TRUE;
8929 *timeout_flag = FALSE;
8930 }
8931 return timeout_flag;
8932}
8933#endif