blob: 3f2de6485155685fefa90fb26da9d6626039235b [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 Plewrightc8b20492023-01-04 18:06:00 +00001045 // check if it already has a valid unicode character.
1046 if (pker->uChar.UnicodeChar > 0 && pker->uChar.UnicodeChar < 0xFFFD)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001047 return 1;
1048
Bram Moolenaara80faa82020-04-12 19:37:17 +02001049 CLEAR_FIELD(abKeystate);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001050
Bram Moolenaar0f873732019-12-05 20:28:46 +01001051 // Clear any pending dead keys
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001052 ToUnicode(VK_SPACE, MapVirtualKey(VK_SPACE, 0), abKeystate, awAnsiCode, 2, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001053
1054 if (uMods & SHIFT_PRESSED)
1055 abKeystate[VK_SHIFT] = 0x80;
1056 if (uMods & CAPSLOCK_ON)
1057 abKeystate[VK_CAPITAL] = 1;
1058
1059 if ((uMods & ALT_GR) == ALT_GR)
1060 {
1061 abKeystate[VK_CONTROL] = abKeystate[VK_LCONTROL] =
1062 abKeystate[VK_MENU] = abKeystate[VK_RMENU] = 0x80;
1063 }
1064
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001065 s_iIsDead = ToUnicode(pker->wVirtualKeyCode, pker->wVirtualScanCode,
1066 abKeystate, awAnsiCode, 2, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001067
1068 if (s_iIsDead > 0)
K.Takata972db232022-02-04 10:45:38 +00001069 pker->uChar.UnicodeChar = (WCHAR) awAnsiCode[0];
Bram Moolenaar071d4272004-06-13 20:20:40 +00001070
1071 return s_iIsDead;
1072}
1073
Bram Moolenaar071d4272004-06-13 20:20:40 +00001074static BOOL g_fJustGotFocus = FALSE;
1075
1076/*
1077 * Decode a KEY_EVENT into one or two keystrokes
1078 */
1079 static BOOL
1080decode_key_event(
1081 KEY_EVENT_RECORD *pker,
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001082 WCHAR *pch,
1083 WCHAR *pch2,
Bram Moolenaar071d4272004-06-13 20:20:40 +00001084 int *pmodifiers,
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02001085 BOOL fDoPost UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001086{
1087 int i;
1088 const int nModifs = pker->dwControlKeyState & (SHIFT | ALT | CTRL);
1089
1090 *pch = *pch2 = NUL;
1091 g_fJustGotFocus = FALSE;
1092
Bram Moolenaar0f873732019-12-05 20:28:46 +01001093 // ignore key up events
Bram Moolenaar071d4272004-06-13 20:20:40 +00001094 if (!pker->bKeyDown)
1095 return FALSE;
1096
Bram Moolenaar0f873732019-12-05 20:28:46 +01001097 // ignore some keystrokes
Bram Moolenaar071d4272004-06-13 20:20:40 +00001098 switch (pker->wVirtualKeyCode)
1099 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001100 // modifiers
Bram Moolenaar071d4272004-06-13 20:20:40 +00001101 case VK_SHIFT:
1102 case VK_CONTROL:
Bram Moolenaar0f873732019-12-05 20:28:46 +01001103 case VK_MENU: // Alt key
Bram Moolenaar071d4272004-06-13 20:20:40 +00001104 return FALSE;
1105
1106 default:
1107 break;
1108 }
1109
Bram Moolenaar0f873732019-12-05 20:28:46 +01001110 // Shift-TAB
Bram Moolenaar071d4272004-06-13 20:20:40 +00001111 if (pker->wVirtualKeyCode == VK_TAB && (nModifs & SHIFT_PRESSED))
1112 {
1113 *pch = K_NUL;
1114 *pch2 = '\017';
1115 return TRUE;
1116 }
1117
K.Takataeeec2542021-06-02 13:28:16 +02001118 for (i = ARRAY_LENGTH(VirtKeyMap); --i >= 0; )
Bram Moolenaar071d4272004-06-13 20:20:40 +00001119 {
1120 if (VirtKeyMap[i].wVirtKey == pker->wVirtualKeyCode)
1121 {
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001122 *pch = VirtKeyMap[i].chAlone;
1123 if ((nModifs & SHIFT) != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001124 *pch = VirtKeyMap[i].chShift;
1125 else if ((nModifs & CTRL) != 0 && (nModifs & ~CTRL) == 0)
1126 *pch = VirtKeyMap[i].chCtrl;
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001127 else if ((nModifs & ALT) != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001128 *pch = VirtKeyMap[i].chAlt;
1129
1130 if (*pch != 0)
1131 {
1132 if (VirtKeyMap[i].fAnsiKey)
1133 {
1134 *pch2 = *pch;
1135 *pch = K_NUL;
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001136 if (pmodifiers)
1137 {
1138 if (pker->wVirtualKeyCode >= VK_F1
1139 && pker->wVirtualKeyCode <= VK_F12)
1140 {
1141 if ((nModifs & ALT) != 0)
1142 {
1143 *pmodifiers |= MOD_MASK_ALT;
1144 if ((nModifs & SHIFT) == 0)
1145 *pch2 = VirtKeyMap[i].chAlone;
1146 }
1147 if ((nModifs & CTRL) != 0)
1148 {
1149 *pmodifiers |= MOD_MASK_CTRL;
1150 if ((nModifs & SHIFT) == 0)
1151 *pch2 = VirtKeyMap[i].chAlone;
1152 }
1153 }
1154 else if (pker->wVirtualKeyCode >= VK_END
1155 && pker->wVirtualKeyCode <= VK_DOWN)
1156 {
1157 // VK_END 0x23
1158 // VK_HOME 0x24
1159 // VK_LEFT 0x25
1160 // VK_UP 0x26
1161 // VK_RIGHT 0x27
1162 // VK_DOWN 0x28
1163 *pmodifiers = 0;
1164 *pch2 = VirtKeyMap[i].chAlone;
1165 if ((nModifs & SHIFT) != 0
1166 && (nModifs & ~SHIFT) == 0)
1167 {
1168 *pch2 = VirtKeyMap[i].chShift;
1169 }
1170 else if ((nModifs & CTRL) != 0
1171 && (nModifs & ~CTRL) == 0)
1172 {
1173 *pch2 = VirtKeyMap[i].chCtrl;
1174 if (pker->wVirtualKeyCode == VK_UP
1175 || pker->wVirtualKeyCode == VK_DOWN)
1176 {
1177 *pmodifiers |= MOD_MASK_CTRL;
1178 *pch2 = VirtKeyMap[i].chAlone;
1179 }
1180 }
1181 else if ((nModifs & ALT) != 0
1182 && (nModifs & ~ALT) == 0)
1183 {
1184 *pch2 = VirtKeyMap[i].chAlt;
1185 }
1186 else if ((nModifs & SHIFT) != 0
1187 && (nModifs & CTRL) != 0)
1188 {
1189 *pmodifiers |= MOD_MASK_CTRL;
1190 *pch2 = VirtKeyMap[i].chShift;
1191 }
1192 }
1193 else
1194 {
1195 *pch2 = VirtKeyMap[i].chAlone;
1196 if ((nModifs & SHIFT) != 0)
1197 *pmodifiers |= MOD_MASK_SHIFT;
1198 if ((nModifs & CTRL) != 0)
1199 *pmodifiers |= MOD_MASK_CTRL;
1200 if ((nModifs & ALT) != 0)
1201 *pmodifiers |= MOD_MASK_ALT;
1202 }
1203 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001204 }
1205
1206 return TRUE;
1207 }
1208 }
1209 }
1210
1211 i = win32_kbd_patch_key(pker);
1212
1213 if (i < 0)
1214 *pch = NUL;
1215 else
1216 {
K.Takata972db232022-02-04 10:45:38 +00001217 *pch = (i > 0) ? pker->uChar.UnicodeChar : NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001218
1219 if (pmodifiers != NULL)
1220 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001221 // Pass on the ALT key as a modifier, but only when not combined
1222 // with CTRL (which is ALTGR).
Bram Moolenaar071d4272004-06-13 20:20:40 +00001223 if ((nModifs & ALT) != 0 && (nModifs & CTRL) == 0)
1224 *pmodifiers |= MOD_MASK_ALT;
1225
Bram Moolenaar0f873732019-12-05 20:28:46 +01001226 // Pass on SHIFT only for special keys, because we don't know when
1227 // it's already included with the character.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001228 if ((nModifs & SHIFT) != 0 && *pch <= 0x20)
1229 *pmodifiers |= MOD_MASK_SHIFT;
1230
Bram Moolenaar0f873732019-12-05 20:28:46 +01001231 // Pass on CTRL only for non-special keys, because we don't know
1232 // when it's already included with the character. And not when
1233 // combined with ALT (which is ALTGR).
Bram Moolenaar071d4272004-06-13 20:20:40 +00001234 if ((nModifs & CTRL) != 0 && (nModifs & ALT) == 0
1235 && *pch >= 0x20 && *pch < 0x80)
1236 *pmodifiers |= MOD_MASK_CTRL;
1237 }
1238 }
1239
1240 return (*pch != NUL);
1241}
1242
Christopher Plewright20b795e2022-12-20 20:01:58 +00001243# if defined(FEAT_EVAL)
1244 static int
1245encode_key_event(dict_T *args, INPUT_RECORD *ir)
1246{
1247 static int s_dwMods = 0;
1248
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001249 char_u *action = dict_get_string(args, "event", TRUE);
1250 if (action && (STRICMP(action, "keydown") == 0
1251 || STRICMP(action, "keyup") == 0))
Christopher Plewright20b795e2022-12-20 20:01:58 +00001252 {
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001253 BOOL isKeyDown = STRICMP(action, "keydown") == 0;
Christopher Plewright20b795e2022-12-20 20:01:58 +00001254 WORD vkCode = dict_get_number_def(args, "keycode", 0);
1255 if (vkCode <= 0 || vkCode >= 0xFF)
1256 {
1257 semsg(_(e_invalid_argument_nr), (long)vkCode);
1258 return FALSE;
1259 }
1260
1261 ir->EventType = KEY_EVENT;
1262 KEY_EVENT_RECORD ker;
1263 ZeroMemory(&ker, sizeof(ker));
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001264 ker.bKeyDown = isKeyDown;
Christopher Plewright20b795e2022-12-20 20:01:58 +00001265 ker.wRepeatCount = 1;
1266 ker.wVirtualScanCode = 0;
1267 ker.dwControlKeyState = 0;
1268 int mods = (int)dict_get_number(args, "modifiers");
1269 // Encode the win32 console key modifiers from Vim keyboard modifiers.
1270 if (mods)
1271 {
1272 // If "modifiers" is explicitly set in the args, then we reset any
1273 // remembered modifer key state that may have been set from earlier
1274 // mod-key-down events, even if they are not yet unset by earlier
1275 // mod-key-up events.
1276 s_dwMods = 0;
1277 if (mods & MOD_MASK_SHIFT)
1278 ker.dwControlKeyState |= SHIFT_PRESSED;
1279 if (mods & MOD_MASK_CTRL)
1280 ker.dwControlKeyState |= LEFT_CTRL_PRESSED;
1281 if (mods & MOD_MASK_ALT)
1282 ker.dwControlKeyState |= LEFT_ALT_PRESSED;
1283 }
1284
1285 if (vkCode == VK_LSHIFT || vkCode == VK_RSHIFT || vkCode == VK_SHIFT)
1286 {
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001287 if (isKeyDown)
Christopher Plewright20b795e2022-12-20 20:01:58 +00001288 s_dwMods |= SHIFT_PRESSED;
1289 else
1290 s_dwMods &= ~SHIFT_PRESSED;
1291 }
1292 else if (vkCode == VK_LCONTROL || vkCode == VK_CONTROL)
1293 {
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001294 if (isKeyDown)
Christopher Plewright20b795e2022-12-20 20:01:58 +00001295 s_dwMods |= LEFT_CTRL_PRESSED;
1296 else
1297 s_dwMods &= ~LEFT_CTRL_PRESSED;
1298 }
1299 else if (vkCode == VK_RCONTROL)
1300 {
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001301 if (isKeyDown)
Christopher Plewright20b795e2022-12-20 20:01:58 +00001302 s_dwMods |= RIGHT_CTRL_PRESSED;
1303 else
1304 s_dwMods &= ~RIGHT_CTRL_PRESSED;
1305 }
1306 else if (vkCode == VK_LMENU || vkCode == VK_MENU)
1307 {
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001308 if (isKeyDown)
Christopher Plewright20b795e2022-12-20 20:01:58 +00001309 s_dwMods |= LEFT_ALT_PRESSED;
1310 else
1311 s_dwMods &= ~LEFT_ALT_PRESSED;
1312 }
1313 else if (vkCode == VK_RMENU)
1314 {
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001315 if (isKeyDown)
Christopher Plewright20b795e2022-12-20 20:01:58 +00001316 s_dwMods |= RIGHT_ALT_PRESSED;
1317 else
1318 s_dwMods &= ~RIGHT_ALT_PRESSED;
1319 }
1320 ker.dwControlKeyState |= s_dwMods;
1321 ker.wVirtualKeyCode = vkCode;
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001322 ker.uChar.UnicodeChar = 0xFFFD; // UNICODE REPLACEMENT CHARACTER
Christopher Plewright20b795e2022-12-20 20:01:58 +00001323 ir->Event.KeyEvent = ker;
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001324 vim_free(action);
Christopher Plewright20b795e2022-12-20 20:01:58 +00001325 }
1326 else
1327 {
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001328 if (action == NULL)
Christopher Plewright20b795e2022-12-20 20:01:58 +00001329 {
1330 semsg(_(e_missing_argument_str), "event");
1331 }
1332 else
1333 {
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001334 semsg(_(e_invalid_value_for_argument_str_str), "event", action);
1335 vim_free(action);
Christopher Plewright20b795e2022-12-20 20:01:58 +00001336 }
1337 return FALSE;
1338 }
1339 return TRUE;
1340}
1341# endif // FEAT_EVAL
1342#endif // !FEAT_GUI_MSWIN || VIMDLL
Bram Moolenaar071d4272004-06-13 20:20:40 +00001343
1344
Bram Moolenaar071d4272004-06-13 20:20:40 +00001345/*
1346 * For the GUI the mouse handling is in gui_w32.c.
1347 */
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001348#if defined(FEAT_GUI_MSWIN) && !defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001349 void
Bram Moolenaar1266d672017-02-01 13:43:36 +01001350mch_setmouse(int on UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001351{
1352}
Christopher Plewright20b795e2022-12-20 20:01:58 +00001353#else // !FEAT_GUI_MSWIN || VIMDLL
Bram Moolenaar0f873732019-12-05 20:28:46 +01001354static int g_fMouseAvail = FALSE; // mouse present
1355static int g_fMouseActive = FALSE; // mouse enabled
1356static int g_nMouseClick = -1; // mouse status
1357static int g_xMouse; // mouse x coordinate
1358static int g_yMouse; // mouse y coordinate
Bram Moolenaar9f1983d2022-05-12 20:35:35 +01001359static DWORD g_cmodein = 0; // Original console input mode
1360static DWORD g_cmodeout = 0; // Original console output mode
Bram Moolenaar071d4272004-06-13 20:20:40 +00001361
1362/*
1363 * Enable or disable mouse input
1364 */
1365 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001366mch_setmouse(int on)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001367{
1368 DWORD cmodein;
1369
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001370# ifdef VIMDLL
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001371 if (gui.in_use)
1372 return;
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001373# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001374 if (!g_fMouseAvail)
1375 return;
1376
1377 g_fMouseActive = on;
1378 GetConsoleMode(g_hConIn, &cmodein);
1379
1380 if (g_fMouseActive)
Wez Furlong6ef5ab52021-05-30 19:29:41 +02001381 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00001382 cmodein |= ENABLE_MOUSE_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02001383 cmodein &= ~ENABLE_QUICK_EDIT_MODE;
1384 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001385 else
Wez Furlong6ef5ab52021-05-30 19:29:41 +02001386 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00001387 cmodein &= ~ENABLE_MOUSE_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02001388 cmodein |= g_cmodein & ENABLE_QUICK_EDIT_MODE;
1389 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001390
Wez Furlong6ef5ab52021-05-30 19:29:41 +02001391 SetConsoleMode(g_hConIn, cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001392}
1393
Bram Moolenaar157d8132018-03-06 17:09:20 +01001394
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001395# if defined(FEAT_BEVAL_TERM) || defined(PROTO)
Bram Moolenaar157d8132018-03-06 17:09:20 +01001396/*
1397 * Called when 'balloonevalterm' changed.
1398 */
1399 void
1400mch_bevalterm_changed(void)
1401{
1402 mch_setmouse(g_fMouseActive);
1403}
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001404# endif
Bram Moolenaar157d8132018-03-06 17:09:20 +01001405
Christopher Plewright2a46f812022-10-16 19:47:45 +01001406/*
1407 * Win32 console mouse scroll event handler.
Christopher Plewright20b795e2022-12-20 20:01:58 +00001408 * Console version of the _OnMouseWheel() function in gui_w32.c
Christopher Plewright2a46f812022-10-16 19:47:45 +01001409 *
1410 * This encodes the mouse scroll direction and keyboard modifiers into
1411 * g_nMouseClick, and the mouse position into g_xMouse and g_yMouse
1412 *
1413 * The direction of the scroll is decoded from two fields of the win32 console
1414 * mouse event record;
Christopher Plewright20b795e2022-12-20 20:01:58 +00001415 * 1. The orientation - vertical or horizontal flag - from dwEventFlags
Christopher Plewright2a46f812022-10-16 19:47:45 +01001416 * 2. The sign - positive or negative (aka delta flag) - from dwButtonState
1417 *
Christopher Plewright20b795e2022-12-20 20:01:58 +00001418 * When scroll orientation is HORIZONTAL
Christopher Plewright2a46f812022-10-16 19:47:45 +01001419 * - If the high word of the dwButtonState member contains a positive
1420 * value, the wheel was rotated to the right.
1421 * - Otherwise, the wheel was rotated to the left.
Christopher Plewright20b795e2022-12-20 20:01:58 +00001422 * When scroll orientation is VERTICAL
Christopher Plewright2a46f812022-10-16 19:47:45 +01001423 * - If the high word of the dwButtonState member contains a positive value,
1424 * the wheel was rotated forward, away from the user.
1425 * - Otherwise, the wheel was rotated backward, toward the user.
1426 */
1427 static void
1428decode_mouse_wheel(MOUSE_EVENT_RECORD *pmer)
1429{
Christopher Plewright2a46f812022-10-16 19:47:45 +01001430 int horizontal = (pmer->dwEventFlags == MOUSE_HWHEELED);
1431 int zDelta = pmer->dwButtonState;
1432
1433 g_xMouse = pmer->dwMousePosition.X;
1434 g_yMouse = pmer->dwMousePosition.Y;
1435
K.Takata161b6ac2022-11-14 15:31:07 +00001436# ifdef FEAT_PROP_POPUP
Christopher Plewright605d02a2022-10-19 11:54:46 +01001437 int lcol = g_xMouse;
1438 int lrow = g_yMouse;
Christopher Plewright38804d62022-11-09 23:55:52 +00001439 win_T *wp = mouse_find_win(&lrow, &lcol, FIND_POPUP);
Christopher Plewright2a46f812022-10-16 19:47:45 +01001440 if (wp != NULL && popup_is_popup(wp))
1441 {
1442 g_nMouseClick = -1;
1443 cmdarg_T cap;
1444 oparg_T oa;
1445 CLEAR_FIELD(cap);
1446 clear_oparg(&oa);
1447 cap.oap = &oa;
1448 if (horizontal)
1449 {
1450 cap.arg = zDelta < 0 ? MSCR_LEFT : MSCR_RIGHT;
1451 cap.cmdchar = zDelta < 0 ? K_MOUSELEFT : K_MOUSERIGHT;
1452 }
1453 else
1454 {
1455 cap.cmdchar = zDelta < 0 ? K_MOUSEUP : K_MOUSEDOWN;
1456 cap.arg = zDelta < 0 ? MSCR_UP : MSCR_DOWN;
1457 }
1458
1459 // Mouse hovers over popup window, scroll it if possible.
1460 mouse_row = wp->w_winrow;
1461 mouse_col = wp->w_wincol;
1462 nv_mousescroll(&cap);
1463 update_screen(0);
1464 setcursor();
1465 out_flush();
1466 return;
1467 }
K.Takata161b6ac2022-11-14 15:31:07 +00001468# endif
Christopher Plewright2a46f812022-10-16 19:47:45 +01001469 mouse_col = g_xMouse;
1470 mouse_row = g_yMouse;
1471
1472 char_u modifiers = 0;
1473 char_u direction = 0;
1474
1475 // Decode the direction into an event that Vim can process
1476 if (horizontal)
1477 direction = zDelta >= 0 ? KE_MOUSELEFT : KE_MOUSERIGHT;
1478 else
1479 direction = zDelta >= 0 ? KE_MOUSEDOWN : KE_MOUSEUP;
1480
dundargocc57b5bc2022-11-02 13:30:51 +00001481 // Decode the win32 console key modifiers into Vim mouse modifiers.
Christopher Plewright2a46f812022-10-16 19:47:45 +01001482 if (pmer->dwControlKeyState & SHIFT_PRESSED)
Christopher Plewright605d02a2022-10-19 11:54:46 +01001483 modifiers |= MOD_MASK_SHIFT; // MOUSE_SHIFT;
Christopher Plewright2a46f812022-10-16 19:47:45 +01001484 if (pmer->dwControlKeyState & (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED))
Christopher Plewright605d02a2022-10-19 11:54:46 +01001485 modifiers |= MOD_MASK_CTRL; // MOUSE_CTRL;
Christopher Plewright2a46f812022-10-16 19:47:45 +01001486 if (pmer->dwControlKeyState & (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED))
1487 modifiers |= MOD_MASK_ALT; // MOUSE_ALT;
1488
1489 // add (bitwise or) the scroll direction and the key modifier chars
1490 // together.
1491 g_nMouseClick = ((direction << 8) | modifiers);
1492
1493 return;
1494}
1495
Bram Moolenaar071d4272004-06-13 20:20:40 +00001496/*
1497 * Decode a MOUSE_EVENT. If it's a valid event, return MOUSE_LEFT,
1498 * MOUSE_MIDDLE, or MOUSE_RIGHT for a click; MOUSE_DRAG for a mouse
1499 * move with a button held down; and MOUSE_RELEASE after a MOUSE_DRAG
1500 * or a MOUSE_LEFT, _MIDDLE, or _RIGHT. We encode the button type,
1501 * the number of clicks, and the Shift/Ctrl/Alt modifiers in g_nMouseClick,
1502 * and we return the mouse position in g_xMouse and g_yMouse.
1503 *
1504 * Every MOUSE_LEFT, _MIDDLE, or _RIGHT will be followed by zero or more
1505 * MOUSE_DRAGs and one MOUSE_RELEASE. MOUSE_RELEASE will be followed only
1506 * by MOUSE_LEFT, _MIDDLE, or _RIGHT.
1507 *
1508 * For multiple clicks, we send, say, MOUSE_LEFT/1 click, MOUSE_RELEASE,
1509 * MOUSE_LEFT/2 clicks, MOUSE_RELEASE, MOUSE_LEFT/3 clicks, MOUSE_RELEASE, ....
1510 *
1511 * Windows will send us MOUSE_MOVED notifications whenever the mouse
1512 * moves, even if it stays within the same character cell. We ignore
1513 * all MOUSE_MOVED messages if the position hasn't really changed, and
1514 * we ignore all MOUSE_MOVED messages where no button is held down (i.e.,
1515 * we're only interested in MOUSE_DRAG).
1516 *
1517 * All of this is complicated by the code that fakes MOUSE_MIDDLE on
1518 * 2-button mouses by pressing the left & right buttons simultaneously.
1519 * In practice, it's almost impossible to click both at the same time,
1520 * so we need to delay a little. Also, we tend not to get MOUSE_RELEASE
1521 * in such cases, if the user is clicking quickly.
1522 */
1523 static BOOL
1524decode_mouse_event(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001525 MOUSE_EVENT_RECORD *pmer)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001526{
1527 static int s_nOldButton = -1;
1528 static int s_nOldMouseClick = -1;
1529 static int s_xOldMouse = -1;
1530 static int s_yOldMouse = -1;
1531 static linenr_T s_old_topline = 0;
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001532# ifdef FEAT_DIFF
Bram Moolenaar071d4272004-06-13 20:20:40 +00001533 static int s_old_topfill = 0;
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001534# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001535 static int s_cClicks = 1;
1536 static BOOL s_fReleased = TRUE;
1537 static DWORD s_dwLastClickTime = 0;
1538 static BOOL s_fNextIsMiddle = FALSE;
1539
Bram Moolenaar0f873732019-12-05 20:28:46 +01001540 static DWORD cButtons = 0; // number of buttons supported
Bram Moolenaar071d4272004-06-13 20:20:40 +00001541
1542 const DWORD LEFT = FROM_LEFT_1ST_BUTTON_PRESSED;
1543 const DWORD MIDDLE = FROM_LEFT_2ND_BUTTON_PRESSED;
1544 const DWORD RIGHT = RIGHTMOST_BUTTON_PRESSED;
1545 const DWORD LEFT_RIGHT = LEFT | RIGHT;
1546
1547 int nButton;
1548
1549 if (cButtons == 0 && !GetNumberOfConsoleMouseButtons(&cButtons))
1550 cButtons = 2;
1551
1552 if (!g_fMouseAvail || !g_fMouseActive)
1553 {
1554 g_nMouseClick = -1;
1555 return FALSE;
1556 }
1557
Bram Moolenaar0f873732019-12-05 20:28:46 +01001558 // get a spurious MOUSE_EVENT immediately after receiving focus; ignore
Bram Moolenaar071d4272004-06-13 20:20:40 +00001559 if (g_fJustGotFocus)
1560 {
1561 g_fJustGotFocus = FALSE;
1562 return FALSE;
1563 }
1564
Christopher Plewright605d02a2022-10-19 11:54:46 +01001565 // If there is an unprocessed mouse click drop this one.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001566 if (g_nMouseClick != -1)
1567 return TRUE;
Christopher Plewright605d02a2022-10-19 11:54:46 +01001568
Christopher Plewright2a46f812022-10-16 19:47:45 +01001569 if (pmer->dwEventFlags == MOUSE_WHEELED
1570 || pmer->dwEventFlags == MOUSE_HWHEELED)
1571 {
1572 decode_mouse_wheel(pmer);
1573 return TRUE; // we now should have a mouse scroll in g_nMouseClick
1574 }
Christopher Plewright605d02a2022-10-19 11:54:46 +01001575
Bram Moolenaar071d4272004-06-13 20:20:40 +00001576 nButton = -1;
1577 g_xMouse = pmer->dwMousePosition.X;
1578 g_yMouse = pmer->dwMousePosition.Y;
1579
1580 if (pmer->dwEventFlags == MOUSE_MOVED)
1581 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001582 // Ignore MOUSE_MOVED events if (x, y) hasn't changed. (We get these
1583 // events even when the mouse moves only within a char cell.)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001584 if (s_xOldMouse == g_xMouse && s_yOldMouse == g_yMouse)
1585 return FALSE;
1586 }
1587
Bram Moolenaar0f873732019-12-05 20:28:46 +01001588 // If no buttons are pressed...
Bram Moolenaar071d4272004-06-13 20:20:40 +00001589 if ((pmer->dwButtonState & ((1 << cButtons) - 1)) == 0)
1590 {
Bram Moolenaar157d8132018-03-06 17:09:20 +01001591 nButton = MOUSE_RELEASE;
1592
Bram Moolenaar0f873732019-12-05 20:28:46 +01001593 // If the last thing returned was MOUSE_RELEASE, ignore this
Bram Moolenaar071d4272004-06-13 20:20:40 +00001594 if (s_fReleased)
Bram Moolenaar157d8132018-03-06 17:09:20 +01001595 {
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001596# ifdef FEAT_BEVAL_TERM
Bram Moolenaar0f873732019-12-05 20:28:46 +01001597 // do return mouse move events when we want them
Bram Moolenaar157d8132018-03-06 17:09:20 +01001598 if (p_bevalterm)
1599 nButton = MOUSE_DRAG;
1600 else
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001601# endif
Bram Moolenaar157d8132018-03-06 17:09:20 +01001602 return FALSE;
1603 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001604
Bram Moolenaar071d4272004-06-13 20:20:40 +00001605 s_fReleased = TRUE;
1606 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01001607 else // one or more buttons pressed
Bram Moolenaar071d4272004-06-13 20:20:40 +00001608 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001609 // on a 2-button mouse, hold down left and right buttons
1610 // simultaneously to get MIDDLE.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001611
1612 if (cButtons == 2 && s_nOldButton != MOUSE_DRAG)
1613 {
1614 DWORD dwLR = (pmer->dwButtonState & LEFT_RIGHT);
1615
Bram Moolenaar0f873732019-12-05 20:28:46 +01001616 // if either left or right button only is pressed, see if the
1617 // next mouse event has both of them pressed
Bram Moolenaar071d4272004-06-13 20:20:40 +00001618 if (dwLR == LEFT || dwLR == RIGHT)
1619 {
1620 for (;;)
1621 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001622 // wait a short time for next input event
Bram Moolenaar071d4272004-06-13 20:20:40 +00001623 if (WaitForSingleObject(g_hConIn, p_mouset / 3)
1624 != WAIT_OBJECT_0)
1625 break;
1626 else
1627 {
1628 DWORD cRecords = 0;
1629 INPUT_RECORD ir;
1630 MOUSE_EVENT_RECORD* pmer2 = &ir.Event.MouseEvent;
1631
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001632 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001633
1634 if (cRecords == 0 || ir.EventType != MOUSE_EVENT
1635 || !(pmer2->dwButtonState & LEFT_RIGHT))
1636 break;
1637 else
1638 {
1639 if (pmer2->dwEventFlags != MOUSE_MOVED)
1640 {
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001641 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001642
1643 return decode_mouse_event(pmer2);
1644 }
1645 else if (s_xOldMouse == pmer2->dwMousePosition.X &&
1646 s_yOldMouse == pmer2->dwMousePosition.Y)
1647 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001648 // throw away spurious mouse move
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001649 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001650
Bram Moolenaar0f873732019-12-05 20:28:46 +01001651 // are there any more mouse events in queue?
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001652 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001653
1654 if (cRecords==0 || ir.EventType != MOUSE_EVENT)
1655 break;
1656 }
1657 else
1658 break;
1659 }
1660 }
1661 }
1662 }
1663 }
1664
1665 if (s_fNextIsMiddle)
1666 {
1667 nButton = (pmer->dwEventFlags == MOUSE_MOVED)
1668 ? MOUSE_DRAG : MOUSE_MIDDLE;
1669 s_fNextIsMiddle = FALSE;
1670 }
1671 else if (cButtons == 2 &&
1672 ((pmer->dwButtonState & LEFT_RIGHT) == LEFT_RIGHT))
1673 {
1674 nButton = MOUSE_MIDDLE;
1675
1676 if (! s_fReleased && pmer->dwEventFlags != MOUSE_MOVED)
1677 {
1678 s_fNextIsMiddle = TRUE;
1679 nButton = MOUSE_RELEASE;
1680 }
1681 }
1682 else if ((pmer->dwButtonState & LEFT) == LEFT)
1683 nButton = MOUSE_LEFT;
1684 else if ((pmer->dwButtonState & MIDDLE) == MIDDLE)
1685 nButton = MOUSE_MIDDLE;
1686 else if ((pmer->dwButtonState & RIGHT) == RIGHT)
1687 nButton = MOUSE_RIGHT;
1688
1689 if (! s_fReleased && ! s_fNextIsMiddle
1690 && nButton != s_nOldButton && s_nOldButton != MOUSE_DRAG)
1691 return FALSE;
1692
1693 s_fReleased = s_fNextIsMiddle;
1694 }
1695
1696 if (pmer->dwEventFlags == 0 || pmer->dwEventFlags == DOUBLE_CLICK)
1697 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001698 // button pressed or released, without mouse moving
Bram Moolenaar071d4272004-06-13 20:20:40 +00001699 if (nButton != -1 && nButton != MOUSE_RELEASE)
1700 {
1701 DWORD dwCurrentTime = GetTickCount();
1702
1703 if (s_xOldMouse != g_xMouse
1704 || s_yOldMouse != g_yMouse
1705 || s_nOldButton != nButton
1706 || s_old_topline != curwin->w_topline
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001707# ifdef FEAT_DIFF
Bram Moolenaar071d4272004-06-13 20:20:40 +00001708 || s_old_topfill != curwin->w_topfill
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001709# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001710 || (int)(dwCurrentTime - s_dwLastClickTime) > p_mouset)
1711 {
1712 s_cClicks = 1;
1713 }
1714 else if (++s_cClicks > 4)
1715 {
1716 s_cClicks = 1;
1717 }
1718
1719 s_dwLastClickTime = dwCurrentTime;
1720 }
1721 }
1722 else if (pmer->dwEventFlags == MOUSE_MOVED)
1723 {
1724 if (nButton != -1 && nButton != MOUSE_RELEASE)
1725 nButton = MOUSE_DRAG;
1726
1727 s_cClicks = 1;
1728 }
1729
1730 if (nButton == -1)
1731 return FALSE;
1732
1733 if (nButton != MOUSE_RELEASE)
1734 s_nOldButton = nButton;
1735
1736 g_nMouseClick = nButton;
1737
1738 if (pmer->dwControlKeyState & SHIFT_PRESSED)
1739 g_nMouseClick |= MOUSE_SHIFT;
1740 if (pmer->dwControlKeyState & (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED))
1741 g_nMouseClick |= MOUSE_CTRL;
1742 if (pmer->dwControlKeyState & (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED))
1743 g_nMouseClick |= MOUSE_ALT;
1744
1745 if (nButton != MOUSE_DRAG && nButton != MOUSE_RELEASE)
1746 SET_NUM_MOUSE_CLICKS(g_nMouseClick, s_cClicks);
1747
Bram Moolenaar0f873732019-12-05 20:28:46 +01001748 // only pass on interesting (i.e., different) mouse events
Bram Moolenaar071d4272004-06-13 20:20:40 +00001749 if (s_xOldMouse == g_xMouse
1750 && s_yOldMouse == g_yMouse
1751 && s_nOldMouseClick == g_nMouseClick)
1752 {
1753 g_nMouseClick = -1;
1754 return FALSE;
1755 }
1756
1757 s_xOldMouse = g_xMouse;
1758 s_yOldMouse = g_yMouse;
1759 s_old_topline = curwin->w_topline;
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001760# ifdef FEAT_DIFF
Bram Moolenaar071d4272004-06-13 20:20:40 +00001761 s_old_topfill = curwin->w_topfill;
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001762# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001763 s_nOldMouseClick = g_nMouseClick;
1764
1765 return TRUE;
1766}
1767
Christopher Plewright20b795e2022-12-20 20:01:58 +00001768# ifdef FEAT_EVAL
1769 static int
1770encode_mouse_event(dict_T *args, INPUT_RECORD *ir)
1771{
1772 int button;
1773 int row;
1774 int col;
1775 int repeated_click;
Bram Moolenaar9b8a3652022-12-20 20:47:28 +00001776 int_u mods = 0;
Christopher Plewright20b795e2022-12-20 20:01:58 +00001777 int move;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001778
Christopher Plewright20b795e2022-12-20 20:01:58 +00001779 if (!dict_has_key(args, "row") || !dict_has_key(args, "col"))
1780 return FALSE;
1781
1782 // Note: "move" is optional, requires fewer arguments
1783 move = (int)dict_get_bool(args, "move", FALSE);
1784 if (!move && (!dict_has_key(args, "button")
1785 || !dict_has_key(args, "multiclick")
1786 || !dict_has_key(args, "modifiers")))
1787 return FALSE;
1788
1789 row = (int)dict_get_number(args, "row") - 1;
1790 col = (int)dict_get_number(args, "col") - 1;
1791
1792 ir->EventType = MOUSE_EVENT;
1793 MOUSE_EVENT_RECORD mer;
1794 ZeroMemory(&mer, sizeof(mer));
1795 mer.dwMousePosition.X = col;
1796 mer.dwMousePosition.Y = row;
1797
1798 if (move)
1799 {
1800 mer.dwButtonState = 0;
1801 mer.dwEventFlags = MOUSE_MOVED;
1802 }
1803 else
1804 {
1805 button = (int)dict_get_number(args, "button");
1806 repeated_click = (int)dict_get_number(args, "multiclick");
1807 mods = (int)dict_get_number(args, "modifiers");
1808 // Reset the scroll values to known values.
1809 // XXX: Remove this when/if the scroll step is made configurable.
1810 mouse_set_hor_scroll_step(6);
1811 mouse_set_vert_scroll_step(3);
1812
1813 switch (button)
1814 {
1815 case MOUSE_LEFT:
1816 mer.dwButtonState = FROM_LEFT_1ST_BUTTON_PRESSED;
1817 mer.dwEventFlags = repeated_click == 1 ? DOUBLE_CLICK : 0;
1818 break;
1819 case MOUSE_MIDDLE:
1820 mer.dwButtonState = FROM_LEFT_2ND_BUTTON_PRESSED;
1821 mer.dwEventFlags = repeated_click == 1 ? DOUBLE_CLICK : 0;
1822 break;
1823 case MOUSE_RIGHT:
1824 mer.dwButtonState = RIGHTMOST_BUTTON_PRESSED;
1825 mer.dwEventFlags = repeated_click == 1 ? DOUBLE_CLICK : 0;
1826 break;
1827 case MOUSE_RELEASE:
1828 // umm? Assume Left Release?
1829 mer.dwEventFlags = 0;
1830
1831 case MOUSE_MOVE:
1832 mer.dwButtonState = 0;
1833 mer.dwEventFlags = MOUSE_MOVED;
1834 break;
1835 case MOUSE_X1:
1836 mer.dwButtonState = FROM_LEFT_3RD_BUTTON_PRESSED;
1837 break;
1838 case MOUSE_X2:
1839 mer.dwButtonState = FROM_LEFT_4TH_BUTTON_PRESSED;
1840 break;
1841 case MOUSE_4: // KE_MOUSEDOWN;
1842 mer.dwButtonState = -1;
1843 mer.dwEventFlags = MOUSE_WHEELED;
1844 break;
1845 case MOUSE_5: // KE_MOUSEUP;
1846 mer.dwButtonState = +1;
1847 mer.dwEventFlags = MOUSE_WHEELED;
1848 break;
1849 case MOUSE_6: // KE_MOUSELEFT;
1850 mer.dwButtonState = -1;
1851 mer.dwEventFlags = MOUSE_HWHEELED;
1852 break;
1853 case MOUSE_7: // KE_MOUSERIGHT;
1854 mer.dwButtonState = +1;
1855 mer.dwEventFlags = MOUSE_HWHEELED;
1856 break;
1857 default:
1858 semsg(_(e_invalid_argument_str), "button");
1859 return FALSE;
1860 }
1861 }
1862
1863 mer.dwControlKeyState = 0;
1864 if (mods != 0)
1865 {
1866 // Encode the win32 console key modifiers from Vim MOUSE modifiers.
1867 if (mods & MOUSE_SHIFT)
1868 mer.dwControlKeyState |= SHIFT_PRESSED;
1869 if (mods & MOUSE_CTRL)
1870 mer.dwControlKeyState |= LEFT_CTRL_PRESSED;
1871 if (mods & MOUSE_ALT)
1872 mer.dwControlKeyState |= LEFT_ALT_PRESSED;
1873 }
1874 ir->Event.MouseEvent = mer;
1875 return TRUE;
1876}
1877# endif // FEAT_EVAL
1878
1879 static int
1880write_input_record_buffer(INPUT_RECORD* irEvents, int nLength)
1881{
1882 int nCount = 0;
1883 while (nCount < nLength)
1884 {
1885 input_record_buffer.length++;
1886 input_record_buffer_node_T *event_node =
1887 malloc(sizeof(input_record_buffer_node_T));
1888 event_node->ir = irEvents[nCount++];
1889 event_node->next = NULL;
1890 if (input_record_buffer.tail == NULL)
1891 {
1892 input_record_buffer.head = event_node;
1893 input_record_buffer.tail = event_node;
1894 }
1895 else
1896 {
1897 input_record_buffer.tail->next = event_node;
1898 input_record_buffer.tail = input_record_buffer.tail->next;
1899 }
1900 }
1901 return nCount;
1902}
1903
1904 static int
1905read_input_record_buffer(INPUT_RECORD* irEvents, int nMaxLength)
1906{
1907 int nCount = 0;
1908 while (nCount < nMaxLength && input_record_buffer.head != NULL)
1909 {
1910 input_record_buffer.length--;
1911 input_record_buffer_node_T *pop_head = input_record_buffer.head;
1912 irEvents[nCount++] = pop_head->ir;
1913 input_record_buffer.head = pop_head->next;
1914 vim_free(pop_head);
1915 if (input_record_buffer.length == 0)
1916 input_record_buffer.tail = NULL;
1917 }
1918 return nCount;
1919}
Christopher Plewright20b795e2022-12-20 20:01:58 +00001920#endif // !FEAT_GUI_MSWIN || VIMDLL
1921
1922#ifdef FEAT_EVAL
1923/*
1924 * The 'test_mswin_event' function is for testing Vim's low-level handling of
1925 * user input events. ie, this manages the encoding of INPUT_RECORD events
1926 * so that we have a way to test how Vim decodes INPUT_RECORD events in Windows
1927 * consoles.
1928 *
1929 * The 'test_mswin_event' function is based on 'test_gui_event'. In fact, when
1930 * the Windows GUI is running, the arguments; 'event' and 'args', are the same.
1931 * So, it acts as an alias for 'test_gui_event' for the Windows GUI.
1932 *
1933 * When the Windows console is running, the arguments; 'event' and 'args', are
1934 * a subset of what 'test_gui_event' handles, ie, only "key" and "mouse"
1935 * events are encoded as INPUT_RECORD events.
1936 *
1937 * Note: INPUT_RECORDs are only used by the Windows console, not the GUI. The
1938 * GUI sends MSG structs instead.
1939 */
1940 int
1941test_mswin_event(char_u *event, dict_T *args)
1942{
1943 int lpEventsWritten = 0;
1944
1945# if defined(VIMDLL) || defined(FEAT_GUI_MSWIN)
1946 if (gui.in_use)
1947 return test_gui_w32_sendevent(event, args);
1948# endif
1949
1950# if defined(VIMDLL) || !defined(FEAT_GUI_MSWIN)
1951
1952// Currently implemented event record types are; KEY_EVENT and MOUSE_EVENT
1953// Potentially could also implement: FOCUS_EVENT and WINDOW_BUFFER_SIZE_EVENT
1954// Maybe also: MENU_EVENT
1955
1956 INPUT_RECORD ir;
1957 BOOL input_encoded = FALSE;
Christopher Plewright7b0afc12022-12-30 16:54:58 +00001958 BOOL execute = FALSE;
Christopher Plewright20b795e2022-12-20 20:01:58 +00001959 if (STRCMP(event, "key") == 0)
Christopher Plewright7b0afc12022-12-30 16:54:58 +00001960 {
1961 execute = dict_get_bool(args, "execute", FALSE);
1962 if (dict_has_key(args, "event"))
1963 input_encoded = encode_key_event(args, &ir);
1964 else if (!execute)
1965 {
1966 semsg(_(e_missing_argument_str), "event");
1967 return FALSE;
1968 }
1969 }
Christopher Plewright20b795e2022-12-20 20:01:58 +00001970 else if (STRCMP(event, "mouse") == 0)
Christopher Plewright7b0afc12022-12-30 16:54:58 +00001971 {
1972 execute = TRUE;
Christopher Plewright20b795e2022-12-20 20:01:58 +00001973 input_encoded = encode_mouse_event(args, &ir);
Christopher Plewright7b0afc12022-12-30 16:54:58 +00001974 }
Christopher Plewright20b795e2022-12-20 20:01:58 +00001975 else
1976 {
1977 semsg(_(e_invalid_value_for_argument_str_str), "event", event);
1978 return FALSE;
1979 }
1980
1981 // Ideally, WriteConsoleInput would be used to inject these low-level
1982 // events. But, this doesnt work well in the CI test environment. So
1983 // implementing an input_record_buffer instead.
1984 if (input_encoded)
1985 lpEventsWritten = write_input_record_buffer(&ir, 1);
1986
Christopher Plewright7b0afc12022-12-30 16:54:58 +00001987 // Set flags to execute the event, ie. like feedkeys mode X.
1988 if (execute)
1989 {
1990 int save_msg_scroll = msg_scroll;
1991 // Avoid a 1 second delay when the keys start Insert mode.
1992 msg_scroll = FALSE;
1993 ch_log(NULL, "test_mswin_event() executing");
Christopher Plewright20b795e2022-12-20 20:01:58 +00001994 exec_normal(TRUE, TRUE, TRUE);
Christopher Plewright7b0afc12022-12-30 16:54:58 +00001995 msg_scroll |= save_msg_scroll;
1996 }
Christopher Plewright20b795e2022-12-20 20:01:58 +00001997
1998# endif
1999 return lpEventsWritten;
2000}
2001#endif // FEAT_EVAL
Bram Moolenaar071d4272004-06-13 20:20:40 +00002002
2003#ifdef MCH_CURSOR_SHAPE
2004/*
2005 * Set the shape of the cursor.
2006 * 'thickness' can be from 1 (thin) to 99 (block)
2007 */
2008 static void
2009mch_set_cursor_shape(int thickness)
2010{
Christopher Plewright38804d62022-11-09 23:55:52 +00002011 if (vtp_working)
K.Takatadf5320c2022-09-01 13:20:16 +01002012 {
2013 if (*T_CSI == NUL)
2014 {
2015 // If 't_SI' is not set, use the default cursor styles.
2016 if (thickness < 50)
2017 vtp_printf("\033[3 q"); // underline
2018 else
2019 vtp_printf("\033[0 q"); // default
2020 }
2021 }
2022 else
2023 {
2024 CONSOLE_CURSOR_INFO ConsoleCursorInfo;
2025 ConsoleCursorInfo.dwSize = thickness;
2026 ConsoleCursorInfo.bVisible = s_cursor_visible;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002027
K.Takatadf5320c2022-09-01 13:20:16 +01002028 SetConsoleCursorInfo(g_hConOut, &ConsoleCursorInfo);
2029 if (s_cursor_visible)
2030 SetConsoleCursorPosition(g_hConOut, g_coord);
2031 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002032}
2033
2034 void
2035mch_update_cursor(void)
2036{
2037 int idx;
2038 int thickness;
2039
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002040# ifdef VIMDLL
2041 if (gui.in_use)
2042 return;
2043# endif
2044
Bram Moolenaar071d4272004-06-13 20:20:40 +00002045 /*
2046 * How the cursor is drawn depends on the current mode.
2047 */
2048 idx = get_shape_idx(FALSE);
2049
2050 if (shape_table[idx].shape == SHAPE_BLOCK)
Bram Moolenaar0f873732019-12-05 20:28:46 +01002051 thickness = 99; // 100 doesn't work on W95
Bram Moolenaar071d4272004-06-13 20:20:40 +00002052 else
2053 thickness = shape_table[idx].percentage;
2054 mch_set_cursor_shape(thickness);
2055}
2056#endif
2057
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002058#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002059/*
2060 * Handle FOCUS_EVENT.
2061 */
2062 static void
2063handle_focus_event(INPUT_RECORD ir)
2064{
2065 g_fJustGotFocus = ir.Event.FocusEvent.bSetFocus;
2066 ui_focus_change((int)g_fJustGotFocus);
2067}
2068
Bram Moolenaar78d21da2019-02-17 15:00:52 +01002069static void ResizeConBuf(HANDLE hConsole, COORD coordScreen);
2070
Bram Moolenaar071d4272004-06-13 20:20:40 +00002071/*
2072 * Wait until console input from keyboard or mouse is available,
2073 * or the time is up.
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02002074 * When "ignore_input" is TRUE even wait when input is available.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002075 * Return TRUE if something is available FALSE if not.
2076 */
2077 static int
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02002078WaitForChar(long msec, int ignore_input)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002079{
2080 DWORD dwNow = 0, dwEndTime = 0;
2081 INPUT_RECORD ir;
2082 DWORD cRecords;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002083 WCHAR ch, ch2;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002084# ifdef FEAT_TIMERS
Bram Moolenaar40b1b542016-04-20 20:18:23 +02002085 int tb_change_cnt = typebuf.tb_change_cnt;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002086# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002087
2088 if (msec > 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01002089 // Wait until the specified time has elapsed.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002090 dwEndTime = GetTickCount() + msec;
2091 else if (msec < 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01002092 // Wait forever.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002093 dwEndTime = INFINITE;
2094
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01002095 // We need to loop until the end of the time period, because
2096 // we might get multiple unusable mouse events in that time.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002097 for (;;)
2098 {
Bram Moolenaared5a9d62018-09-06 13:14:43 +02002099 // Only process messages when waiting.
2100 if (msec != 0)
2101 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002102# ifdef MESSAGE_QUEUE
Bram Moolenaared5a9d62018-09-06 13:14:43 +02002103 parse_queued_messages();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002104# endif
2105# ifdef FEAT_MZSCHEME
Bram Moolenaared5a9d62018-09-06 13:14:43 +02002106 mzvim_check_threads();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002107# endif
2108# ifdef FEAT_CLIENTSERVER
Bram Moolenaared5a9d62018-09-06 13:14:43 +02002109 serverProcessPendingMessages();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002110# endif
Bram Moolenaared5a9d62018-09-06 13:14:43 +02002111 }
Bram Moolenaarf12d9832016-01-29 21:11:25 +01002112
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02002113 if (g_nMouseClick != -1
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002114# ifdef FEAT_CLIENTSERVER
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02002115 || (!ignore_input && input_available())
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002116# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002117 )
2118 return TRUE;
2119
2120 if (msec > 0)
2121 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01002122 // If the specified wait time has passed, return. Beware that
2123 // GetTickCount() may wrap around (overflow).
Bram Moolenaar071d4272004-06-13 20:20:40 +00002124 dwNow = GetTickCount();
Bram Moolenaarb7512b72013-08-10 12:45:09 +02002125 if ((int)(dwNow - dwEndTime) >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002126 break;
2127 }
2128 if (msec != 0)
2129 {
Bram Moolenaar325b7a22004-07-05 15:58:32 +00002130 DWORD dwWaitTime = dwEndTime - dwNow;
2131
Bram Moolenaarc478ee32020-12-01 21:27:51 +01002132 // Don't wait for more than 11 msec to avoid dropping characters,
2133 // check channel while waiting for input and handle a callback from
2134 // 'balloonexpr'.
2135 if (dwWaitTime > 11)
2136 dwWaitTime = 11;
2137
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002138# ifdef FEAT_MZSCHEME
Bram Moolenaarc478ee32020-12-01 21:27:51 +01002139 if (mzthreads_allowed() && p_mzq > 0 && (long)dwWaitTime > p_mzq)
Bram Moolenaar0f873732019-12-05 20:28:46 +01002140 dwWaitTime = p_mzq; // don't wait longer than 'mzquantum'
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002141# endif
2142# ifdef FEAT_TIMERS
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01002143 // When waiting very briefly don't trigger timers.
2144 if (dwWaitTime > 10)
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01002145 {
2146 long due_time;
2147
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01002148 // Trigger timers and then get the time in msec until the next
2149 // one is due. Wait up to that time.
2150 due_time = check_due_timer();
2151 if (typebuf.tb_change_cnt != tb_change_cnt)
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01002152 {
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01002153 // timer may have used feedkeys().
2154 return FALSE;
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01002155 }
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01002156 if (due_time > 0 && dwWaitTime > (DWORD)due_time)
2157 dwWaitTime = due_time;
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01002158 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002159# endif
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01002160 if (
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002161# ifdef FEAT_CLIENTSERVER
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01002162 // Wait for either an event on the console input or a
2163 // message in the client-server window.
2164 msg_wait_for_multiple_objects(1, &g_hConIn, FALSE,
2165 dwWaitTime, QS_SENDMESSAGE) != WAIT_OBJECT_0
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002166# else
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01002167 wait_for_single_object(g_hConIn, dwWaitTime)
2168 != WAIT_OBJECT_0
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002169# endif
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01002170 )
2171 continue;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002172 }
2173
2174 cRecords = 0;
Bram Moolenaar3a69e112014-01-10 13:51:42 +01002175 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002176
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002177# ifdef FEAT_MBYTE_IME
matveyt4eb19142021-05-20 11:54:10 +02002178 // May have to redraw if the cursor ends up in the wrong place.
2179 // Only when not peeking.
Bram Moolenaar24959102022-05-07 20:01:16 +01002180 if (State == MODE_CMDLINE && msg_row == Rows - 1 && msec != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002181 {
2182 CONSOLE_SCREEN_BUFFER_INFO csbi;
2183
2184 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
2185 {
2186 if (csbi.dwCursorPosition.Y != msg_row)
2187 {
matveyte08795e2021-05-07 15:00:17 +02002188 // The screen is now messed up, must redraw the command
2189 // line and later all the windows.
Bram Moolenaara4d158b2022-08-14 14:17:45 +01002190 redraw_all_later(UPD_CLEAR);
matveyte08795e2021-05-07 15:00:17 +02002191 compute_cmdrow();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002192 redrawcmd();
2193 }
2194 }
2195 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002196# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002197
2198 if (cRecords > 0)
2199 {
2200 if (ir.EventType == KEY_EVENT && ir.Event.KeyEvent.bKeyDown)
2201 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002202# ifdef FEAT_MBYTE_IME
Bram Moolenaar0f873732019-12-05 20:28:46 +01002203 // Windows IME sends two '\n's with only one 'ENTER'. First:
2204 // wVirtualKeyCode == 13. second: wVirtualKeyCode == 0
K.Takata972db232022-02-04 10:45:38 +00002205 if (ir.Event.KeyEvent.uChar.UnicodeChar == 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00002206 && ir.Event.KeyEvent.wVirtualKeyCode == 13)
2207 {
Bram Moolenaar3a69e112014-01-10 13:51:42 +01002208 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002209 continue;
2210 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002211# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002212 if (decode_key_event(&ir.Event.KeyEvent, &ch, &ch2,
2213 NULL, FALSE))
2214 return TRUE;
2215 }
2216
Bram Moolenaar3a69e112014-01-10 13:51:42 +01002217 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002218
2219 if (ir.EventType == FOCUS_EVENT)
2220 handle_focus_event(ir);
2221 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
Bram Moolenaarc33ecb22018-02-11 16:40:45 +01002222 {
Bram Moolenaar78d21da2019-02-17 15:00:52 +01002223 COORD dwSize = ir.Event.WindowBufferSizeEvent.dwSize;
2224
Bram Moolenaar36698e32019-12-11 22:57:40 +01002225 // Only call shell_resized() when the size actually changed to
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002226 // avoid the screen is cleared.
Bram Moolenaar78d21da2019-02-17 15:00:52 +01002227 if (dwSize.X != Columns || dwSize.Y != Rows)
2228 {
2229 CONSOLE_SCREEN_BUFFER_INFO csbi;
2230 GetConsoleScreenBufferInfo(g_hConOut, &csbi);
Bram Moolenaar36698e32019-12-11 22:57:40 +01002231 dwSize.X = csbi.srWindow.Right - csbi.srWindow.Left + 1;
Bram Moolenaar78d21da2019-02-17 15:00:52 +01002232 dwSize.Y = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
Bram Moolenaar36698e32019-12-11 22:57:40 +01002233 if (dwSize.X != Columns || dwSize.Y != Rows)
2234 {
2235 ResizeConBuf(g_hConOut, dwSize);
2236 shell_resized();
2237 }
Bram Moolenaar78d21da2019-02-17 15:00:52 +01002238 }
Bram Moolenaarc33ecb22018-02-11 16:40:45 +01002239 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002240 else if (ir.EventType == MOUSE_EVENT
2241 && decode_mouse_event(&ir.Event.MouseEvent))
2242 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002243 }
2244 else if (msec == 0)
2245 break;
2246 }
2247
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002248# ifdef FEAT_CLIENTSERVER
Bram Moolenaar0f873732019-12-05 20:28:46 +01002249 // Something might have been received while we were waiting.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002250 if (input_available())
2251 return TRUE;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002252# endif
Bram Moolenaarf12d9832016-01-29 21:11:25 +01002253
Bram Moolenaar071d4272004-06-13 20:20:40 +00002254 return FALSE;
2255}
2256
Bram Moolenaar071d4272004-06-13 20:20:40 +00002257/*
2258 * return non-zero if a character is available
2259 */
2260 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002261mch_char_avail(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002262{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002263# ifdef VIMDLL
2264 if (gui.in_use)
2265 return TRUE;
2266# endif
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02002267 return WaitForChar(0L, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002268}
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02002269
2270# if defined(FEAT_TERMINAL) || defined(PROTO)
2271/*
2272 * Check for any pending input or messages.
2273 */
2274 int
2275mch_check_messages(void)
2276{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002277# ifdef VIMDLL
2278 if (gui.in_use)
2279 return TRUE;
2280# endif
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02002281 return WaitForChar(0L, TRUE);
2282}
2283# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002284
2285/*
2286 * Create the console input. Used when reading stdin doesn't work.
2287 */
2288 static void
2289create_conin(void)
2290{
2291 g_hConIn = CreateFile("CONIN$", GENERIC_READ|GENERIC_WRITE,
2292 FILE_SHARE_READ|FILE_SHARE_WRITE,
2293 (LPSECURITY_ATTRIBUTES) NULL,
Bram Moolenaareb3593b2006-04-22 22:33:57 +00002294 OPEN_EXISTING, 0, (HANDLE)NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002295 did_create_conin = TRUE;
2296}
2297
2298/*
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01002299 * Get a keystroke or a mouse event, use a blocking wait.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002300 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002301 static WCHAR
2302tgetch(int *pmodifiers, WCHAR *pch2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002303{
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002304 WCHAR ch;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002305
2306 for (;;)
2307 {
2308 INPUT_RECORD ir;
2309 DWORD cRecords = 0;
2310
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002311# ifdef FEAT_CLIENTSERVER
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02002312 (void)WaitForChar(-1L, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002313 if (input_available())
2314 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002315 if (g_nMouseClick != -1)
2316 return 0;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002317# endif
Bram Moolenaar3a69e112014-01-10 13:51:42 +01002318 if (read_console_input(g_hConIn, &ir, 1, &cRecords) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002319 {
2320 if (did_create_conin)
2321 read_error_exit();
2322 create_conin();
2323 continue;
2324 }
2325
2326 if (ir.EventType == KEY_EVENT)
2327 {
2328 if (decode_key_event(&ir.Event.KeyEvent, &ch, pch2,
2329 pmodifiers, TRUE))
2330 return ch;
2331 }
2332 else if (ir.EventType == FOCUS_EVENT)
2333 handle_focus_event(ir);
2334 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
2335 shell_resized();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002336 else if (ir.EventType == MOUSE_EVENT)
2337 {
2338 if (decode_mouse_event(&ir.Event.MouseEvent))
2339 return 0;
2340 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002341 }
2342}
Bram Moolenaar0f873732019-12-05 20:28:46 +01002343#endif // !FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00002344
2345
2346/*
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02002347 * mch_inchar(): low-level input function.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002348 * Get one or more characters from the keyboard or the mouse.
2349 * If time == 0, do not wait for characters.
2350 * If time == n, wait a short time for characters.
2351 * If time == -1, wait forever for characters.
2352 * Returns the number of characters read into buf.
2353 */
2354 int
2355mch_inchar(
Bram Moolenaar1266d672017-02-01 13:43:36 +01002356 char_u *buf UNUSED,
2357 int maxlen UNUSED,
2358 long time UNUSED,
2359 int tb_change_cnt UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002360{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002361#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002362
2363 int len;
2364 int c;
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01002365# ifdef VIMDLL
2366// Extra space for maximum three CSIs. E.g. U+1B6DB -> 0xF0 0x9B 0x9B 0x9B.
2367# define TYPEAHEADSPACE 6
2368# else
2369# define TYPEAHEADSPACE 0
2370# endif
2371# define TYPEAHEADLEN (20 + TYPEAHEADSPACE)
Bram Moolenaar0f873732019-12-05 20:28:46 +01002372 static char_u typeahead[TYPEAHEADLEN]; // previously typed bytes.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002373 static int typeaheadlen = 0;
2374
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002375# ifdef VIMDLL
2376 if (gui.in_use)
2377 return 0;
2378# endif
2379
Bram Moolenaar0f873732019-12-05 20:28:46 +01002380 // First use any typeahead that was kept because "buf" was too small.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002381 if (typeaheadlen > 0)
2382 goto theend;
2383
Bram Moolenaar071d4272004-06-13 20:20:40 +00002384 if (time >= 0)
2385 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01002386 if (!WaitForChar(time, FALSE)) // no character available
Bram Moolenaar071d4272004-06-13 20:20:40 +00002387 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002388 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01002389 else // time == -1, wait forever
Bram Moolenaar071d4272004-06-13 20:20:40 +00002390 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01002391 mch_set_winsize_now(); // Allow winsize changes from now on
Bram Moolenaar071d4272004-06-13 20:20:40 +00002392
Bram Moolenaar3918c952005-03-15 22:34:55 +00002393 /*
2394 * If there is no character available within 2 seconds (default)
2395 * write the autoscript file to disk. Or cause the CursorHold event
2396 * to be triggered.
2397 */
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02002398 if (!WaitForChar(p_ut, FALSE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002399 {
Bram Moolenaard35f9712005-12-18 22:02:33 +00002400 if (trigger_cursorhold() && maxlen >= 3)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002401 {
Bram Moolenaar3918c952005-03-15 22:34:55 +00002402 buf[0] = K_SPECIAL;
2403 buf[1] = KS_EXTRA;
2404 buf[2] = (int)KE_CURSORHOLD;
2405 return 3;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002406 }
Bram Moolenaar702517d2005-06-27 22:34:07 +00002407 before_blocking();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002408 }
2409 }
2410
2411 /*
2412 * Try to read as many characters as there are, until the buffer is full.
2413 */
2414
Bram Moolenaar0f873732019-12-05 20:28:46 +01002415 // we will get at least one key. Get more if they are available.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002416 g_fCBrkPressed = FALSE;
2417
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002418# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00002419 if (fdDump)
2420 fputc('[', fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002421# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002422
Bram Moolenaar0f873732019-12-05 20:28:46 +01002423 // Keep looping until there is something in the typeahead buffer and more
2424 // to get and still room in the buffer (up to two bytes for a char and
2425 // three bytes for a modifier).
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02002426 while ((typeaheadlen == 0 || WaitForChar(0L, FALSE))
Bram Moolenaar9f1983d2022-05-12 20:35:35 +01002427 && typeaheadlen + 5 + TYPEAHEADSPACE <= TYPEAHEADLEN)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002428 {
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 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002436 if (g_nMouseClick != -1)
2437 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002438# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00002439 if (fdDump)
2440 fprintf(fdDump, "{%02x @ %d, %d}",
2441 g_nMouseClick, g_xMouse, g_yMouse);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002442# endif
Christopher Plewright2a46f812022-10-16 19:47:45 +01002443 char_u modifiers = ((char_u *)(&g_nMouseClick))[0];
2444 char_u scroll_dir = ((char_u *)(&g_nMouseClick))[1];
2445
2446 if (scroll_dir == KE_MOUSEDOWN
2447 || scroll_dir == KE_MOUSEUP
2448 || scroll_dir == KE_MOUSELEFT
2449 || scroll_dir == KE_MOUSERIGHT)
2450 {
2451 if (modifiers > 0)
2452 {
Christopher Plewright03193062022-11-22 12:58:27 +00002453 // use K_SPECIAL instead of CSI to make mappings work
2454 typeahead[typeaheadlen++] = K_SPECIAL;
Christopher Plewright2a46f812022-10-16 19:47:45 +01002455 typeahead[typeaheadlen++] = KS_MODIFIER;
2456 typeahead[typeaheadlen++] = modifiers;
2457 }
2458 typeahead[typeaheadlen++] = CSI;
2459 typeahead[typeaheadlen++] = KS_EXTRA;
2460 typeahead[typeaheadlen++] = scroll_dir;
Christopher Plewright2a46f812022-10-16 19:47:45 +01002461 }
2462 else
2463 {
2464 typeahead[typeaheadlen++] = ESC + 128;
2465 typeahead[typeaheadlen++] = 'M';
2466 typeahead[typeaheadlen++] = g_nMouseClick;
Christopher Plewright2a46f812022-10-16 19:47:45 +01002467 }
Christopher Plewright36446bb2022-11-23 22:28:08 +00002468
2469 // Pass the pointer coordinates of the mouse event in 2 bytes,
2470 // allowing for > 223 columns. Both for click and scroll events.
2471 // This is the same as what is used for the GUI.
2472 typeahead[typeaheadlen++] = (char_u)(g_xMouse / 128 + ' ' + 1);
2473 typeahead[typeaheadlen++] = (char_u)(g_xMouse % 128 + ' ' + 1);
2474 typeahead[typeaheadlen++] = (char_u)(g_yMouse / 128 + ' ' + 1);
2475 typeahead[typeaheadlen++] = (char_u)(g_yMouse % 128 + ' ' + 1);
2476
2477 g_nMouseClick = -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002478 }
2479 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00002480 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002481 WCHAR ch2 = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002482 int modifiers = 0;
2483
2484 c = tgetch(&modifiers, &ch2);
2485
Christopher Plewrightc8b20492023-01-04 18:06:00 +00002486 c = simplify_key(c, &modifiers);
2487
Christopher Plewright7b0afc12022-12-30 16:54:58 +00002488 // Some chars need adjustment when the Ctrl modifier is used.
2489 ++no_reduce_keys;
2490 c = may_adjust_key_for_ctrl(modifiers, c);
2491 --no_reduce_keys;
2492
2493 // remove the SHIFT modifier for keys where it's already included,
2494 // e.g., '(' and '*'
2495 modifiers = may_remove_shift_modifier(modifiers, c);
2496
Bram Moolenaar071d4272004-06-13 20:20:40 +00002497 if (typebuf_changed(tb_change_cnt))
2498 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01002499 // "buf" may be invalid now if a client put something in the
2500 // typeahead buffer and "buf" is in the typeahead buffer.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002501 typeaheadlen = 0;
2502 break;
2503 }
2504
2505 if (c == Ctrl_C && ctrl_c_interrupts)
2506 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002507# if defined(FEAT_CLIENTSERVER)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002508 trash_input_buf();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002509# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002510 got_int = TRUE;
2511 }
2512
Bram Moolenaar071d4272004-06-13 20:20:40 +00002513 if (g_nMouseClick == -1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002514 {
2515 int n = 1;
2516
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002517 if (ch2 == NUL)
2518 {
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01002519 int i, j;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002520 char_u *p;
2521 WCHAR ch[2];
2522
2523 ch[0] = c;
Bram Moolenaar0f873732019-12-05 20:28:46 +01002524 if (c >= 0xD800 && c <= 0xDBFF) // High surrogate
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002525 {
2526 ch[1] = tgetch(&modifiers, &ch2);
2527 n++;
2528 }
2529 p = utf16_to_enc(ch, &n);
2530 if (p != NULL)
2531 {
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01002532 for (i = 0, j = 0; i < n; i++)
2533 {
2534 typeahead[typeaheadlen + j++] = p[i];
2535# ifdef VIMDLL
2536 if (p[i] == CSI)
2537 {
2538 typeahead[typeaheadlen + j++] = KS_EXTRA;
2539 typeahead[typeaheadlen + j++] = KE_CSI;
2540 }
2541# endif
2542 }
2543 n = j;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002544 vim_free(p);
2545 }
2546 }
2547 else
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01002548 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002549 typeahead[typeaheadlen] = c;
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01002550# ifdef VIMDLL
2551 if (c == CSI)
2552 {
2553 typeahead[typeaheadlen + 1] = KS_EXTRA;
2554 typeahead[typeaheadlen + 2] = KE_CSI;
2555 n = 3;
2556 }
2557# endif
2558 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002559 if (ch2 != NUL)
2560 {
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +02002561 if (c == K_NUL)
Bram Moolenaarfeeb4d02017-12-05 15:14:46 +01002562 {
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +02002563 switch (ch2)
2564 {
2565 case (WCHAR)'\324': // SHIFT+Insert
2566 case (WCHAR)'\325': // CTRL+Insert
2567 case (WCHAR)'\327': // SHIFT+Delete
2568 case (WCHAR)'\330': // CTRL+Delete
2569 typeahead[typeaheadlen + n] = (char_u)ch2;
2570 n++;
2571 break;
2572
2573 default:
2574 typeahead[typeaheadlen + n] = 3;
2575 typeahead[typeaheadlen + n + 1] = (char_u)ch2;
2576 n += 2;
2577 break;
2578 }
Bram Moolenaarfeeb4d02017-12-05 15:14:46 +01002579 }
2580 else
2581 {
2582 typeahead[typeaheadlen + n] = 3;
2583 typeahead[typeaheadlen + n + 1] = (char_u)ch2;
2584 n += 2;
2585 }
Bram Moolenaar45500912014-07-09 20:51:07 +02002586 }
2587
Bram Moolenaar0f873732019-12-05 20:28:46 +01002588 // Use the ALT key to set the 8th bit of the character
2589 // when it's one byte, the 8th bit isn't set yet and not
2590 // using a double-byte encoding (would become a lead
2591 // byte).
Bram Moolenaar071d4272004-06-13 20:20:40 +00002592 if ((modifiers & MOD_MASK_ALT)
2593 && n == 1
2594 && (typeahead[typeaheadlen] & 0x80) == 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00002595 && !enc_dbcs
Bram Moolenaar071d4272004-06-13 20:20:40 +00002596 )
2597 {
Bram Moolenaar85a3e5c2007-11-20 16:22:16 +00002598 n = (*mb_char2bytes)(typeahead[typeaheadlen] | 0x80,
2599 typeahead + typeaheadlen);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002600 modifiers &= ~MOD_MASK_ALT;
2601 }
2602
2603 if (modifiers != 0)
2604 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01002605 // Prepend modifiers to the character.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002606 mch_memmove(typeahead + typeaheadlen + 3,
2607 typeahead + typeaheadlen, n);
2608 typeahead[typeaheadlen++] = K_SPECIAL;
2609 typeahead[typeaheadlen++] = (char_u)KS_MODIFIER;
2610 typeahead[typeaheadlen++] = modifiers;
2611 }
2612
2613 typeaheadlen += n;
2614
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002615# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00002616 if (fdDump)
2617 fputc(c, fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002618# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002619 }
2620 }
2621 }
2622
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002623# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00002624 if (fdDump)
2625 {
2626 fputs("]\n", fdDump);
2627 fflush(fdDump);
2628 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002629# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002630
Bram Moolenaar071d4272004-06-13 20:20:40 +00002631theend:
Bram Moolenaar0f873732019-12-05 20:28:46 +01002632 // Move typeahead to "buf", as much as fits.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002633 len = 0;
2634 while (len < maxlen && typeaheadlen > 0)
2635 {
2636 buf[len++] = typeahead[0];
2637 mch_memmove(typeahead, typeahead + 1, --typeaheadlen);
2638 }
Bram Moolenaar4c5678f2022-11-30 18:12:19 +00002639# ifdef FEAT_EVAL
Bram Moolenaar7ca86fe2020-09-03 19:25:11 +02002640 if (len > 0)
2641 {
2642 buf[len] = NUL;
2643 ch_log(NULL, "raw key input: \"%s\"", buf);
2644 }
K.Takata6e1d31e2022-02-03 13:05:32 +00002645# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002646 return len;
2647
Bram Moolenaar0f873732019-12-05 20:28:46 +01002648#else // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00002649 return 0;
Bram Moolenaar0f873732019-12-05 20:28:46 +01002650#endif // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00002651}
2652
Bram Moolenaar82881492012-11-20 16:53:39 +01002653#ifndef PROTO
2654# ifndef __MINGW32__
Bram Moolenaar0f873732019-12-05 20:28:46 +01002655# include <shellapi.h> // required for FindExecutable()
Bram Moolenaar82881492012-11-20 16:53:39 +01002656# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002657#endif
2658
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002659/*
Bram Moolenaar95da1362020-05-30 18:37:55 +02002660 * Return TRUE if "name" is an executable file, FALSE if not or it doesn't exist.
Bram Moolenaar43663192017-03-05 14:29:12 +01002661 * When returning TRUE and "path" is not NULL save the path and set "*path" to
2662 * the allocated memory.
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00002663 * TODO: Should somehow check if it's really executable.
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002664 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002665 static int
Bram Moolenaar95da1362020-05-30 18:37:55 +02002666executable_file(char *name, char_u **path)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002667{
LemonBoy40fd7e62022-05-05 20:18:16 +01002668 int attrs = win32_getattrs((char_u *)name);
2669
2670 // The file doesn't exist or is a folder.
2671 if (attrs == -1 || (attrs & FILE_ATTRIBUTE_DIRECTORY))
2672 return FALSE;
2673 // Check if the file is an AppExecLink, a special alias used by Windows
2674 // Store for its apps.
2675 if (attrs & FILE_ATTRIBUTE_REPARSE_POINT)
Bram Moolenaar43663192017-03-05 14:29:12 +01002676 {
LemonBoy40fd7e62022-05-05 20:18:16 +01002677 char_u *res = resolve_appexeclink((char_u *)name);
2678 if (res == NULL)
2679 return FALSE;
2680 // The path is already absolute.
Bram Moolenaar95da1362020-05-30 18:37:55 +02002681 if (path != NULL)
LemonBoy40fd7e62022-05-05 20:18:16 +01002682 *path = res;
2683 else
2684 vim_free(res);
Bram Moolenaar95da1362020-05-30 18:37:55 +02002685 }
LemonBoy40fd7e62022-05-05 20:18:16 +01002686 else if (path != NULL)
2687 *path = FullName_save((char_u *)name, FALSE);
2688 return TRUE;
Bram Moolenaar95da1362020-05-30 18:37:55 +02002689}
2690
2691/*
2692 * If "use_path" is TRUE: Return TRUE if "name" is in $PATH.
2693 * If "use_path" is FALSE: Return TRUE if "name" exists.
2694 * If "use_pathext" is TRUE search "name" with extensions in $PATHEXT.
2695 * When returning TRUE and "path" is not NULL save the path and set "*path" to
2696 * the allocated memory.
2697 */
2698 static int
2699executable_exists(char *name, char_u **path, int use_path, int use_pathext)
2700{
2701 // WinNT and later can use _MAX_PATH wide characters for a pathname, which
2702 // means that the maximum pathname is _MAX_PATH * 3 bytes when 'enc' is
2703 // UTF-8.
2704 char_u buf[_MAX_PATH * 3];
2705 size_t len = STRLEN(name);
2706 size_t tmplen;
2707 char_u *p, *e, *e2;
2708 char_u *pathbuf = NULL;
2709 char_u *pathext = NULL;
2710 char_u *pathextbuf = NULL;
Mike Williamsa3d1b292021-06-30 20:56:00 +02002711 char_u *shname = NULL;
Bram Moolenaar95da1362020-05-30 18:37:55 +02002712 int noext = FALSE;
2713 int retval = FALSE;
2714
2715 if (len >= sizeof(buf)) // safety check
Bram Moolenaar43663192017-03-05 14:29:12 +01002716 return FALSE;
Bram Moolenaar95da1362020-05-30 18:37:55 +02002717
2718 // Using the name directly when a Unix-shell like 'shell'.
Mike Williamsa3d1b292021-06-30 20:56:00 +02002719 shname = gettail(p_sh);
2720 if (strstr((char *)shname, "sh") != NULL &&
2721 !(strstr((char *)shname, "powershell") != NULL
2722 || strstr((char *)shname, "pwsh") != NULL))
Bram Moolenaar95da1362020-05-30 18:37:55 +02002723 noext = TRUE;
2724
2725 if (use_pathext)
2726 {
2727 pathext = mch_getenv("PATHEXT");
2728 if (pathext == NULL)
2729 pathext = (char_u *)".com;.exe;.bat;.cmd";
2730
2731 if (noext == FALSE)
2732 {
2733 /*
2734 * Loop over all extensions in $PATHEXT.
2735 * Check "name" ends with extension.
2736 */
2737 p = pathext;
2738 while (*p)
2739 {
2740 if (p[0] == ';'
2741 || (p[0] == '.' && (p[1] == NUL || p[1] == ';')))
2742 {
2743 // Skip empty or single ".".
2744 ++p;
2745 continue;
2746 }
2747 e = vim_strchr(p, ';');
2748 if (e == NULL)
2749 e = p + STRLEN(p);
2750 tmplen = e - p;
2751
2752 if (_strnicoll(name + len - tmplen, (char *)p, tmplen) == 0)
2753 {
2754 noext = TRUE;
2755 break;
2756 }
2757
2758 p = e;
2759 }
2760 }
Bram Moolenaar43663192017-03-05 14:29:12 +01002761 }
2762
Dominique Pelleaf4a61a2021-12-27 17:21:41 +00002763 // Prepend single "." to pathext, it means no extension added.
Bram Moolenaar95da1362020-05-30 18:37:55 +02002764 if (pathext == NULL)
2765 pathext = (char_u *)".";
2766 else if (noext == TRUE)
2767 {
2768 if (pathextbuf == NULL)
2769 pathextbuf = alloc(STRLEN(pathext) + 3);
2770 if (pathextbuf == NULL)
2771 {
2772 retval = FALSE;
2773 goto theend;
2774 }
2775 STRCPY(pathextbuf, ".;");
2776 STRCAT(pathextbuf, pathext);
2777 pathext = pathextbuf;
2778 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002779
Bram Moolenaar95da1362020-05-30 18:37:55 +02002780 // Use $PATH when "use_path" is TRUE and "name" is basename.
2781 if (use_path && gettail((char_u *)name) == (char_u *)name)
2782 {
2783 p = mch_getenv("PATH");
2784 if (p != NULL)
2785 {
2786 pathbuf = alloc(STRLEN(p) + 3);
2787 if (pathbuf == NULL)
2788 {
2789 retval = FALSE;
2790 goto theend;
2791 }
Yasuhiro Matsumoto05cf63e2022-05-03 11:02:28 +01002792
2793 if (mch_getenv("NoDefaultCurrentDirectoryInExePath") == NULL)
2794 STRCPY(pathbuf, ".;");
2795 else
2796 *pathbuf = NUL;
Bram Moolenaar95da1362020-05-30 18:37:55 +02002797 STRCAT(pathbuf, p);
2798 }
2799 }
2800
2801 /*
2802 * Walk through all entries in $PATH to check if "name" exists there and
2803 * is an executable file.
2804 */
2805 p = (pathbuf != NULL) ? pathbuf : (char_u *)".";
2806 while (*p)
2807 {
2808 if (*p == ';') // Skip empty entry
2809 {
2810 ++p;
2811 continue;
2812 }
2813 e = vim_strchr(p, ';');
2814 if (e == NULL)
2815 e = p + STRLEN(p);
2816
2817 if (e - p + len + 2 > sizeof(buf))
2818 {
2819 retval = FALSE;
2820 goto theend;
2821 }
2822 // A single "." that means current dir.
2823 if (e - p == 1 && *p == '.')
2824 STRCPY(buf, name);
2825 else
2826 {
2827 vim_strncpy(buf, p, e - p);
2828 add_pathsep(buf);
2829 STRCAT(buf, name);
2830 }
2831 tmplen = STRLEN(buf);
2832
2833 /*
2834 * Loop over all extensions in $PATHEXT.
2835 * Check "name" with extension added.
2836 */
2837 p = pathext;
2838 while (*p)
2839 {
2840 if (*p == ';')
2841 {
2842 // Skip empty entry
2843 ++p;
2844 continue;
2845 }
2846 e2 = vim_strchr(p, (int)';');
2847 if (e2 == NULL)
2848 e2 = p + STRLEN(p);
2849
2850 if (!(p[0] == '.' && (p[1] == NUL || p[1] == ';')))
2851 {
2852 // Not a single "." that means no extension is added.
2853 if (e2 - p + tmplen + 1 > sizeof(buf))
2854 {
2855 retval = FALSE;
2856 goto theend;
2857 }
2858 vim_strncpy(buf + tmplen, p, e2 - p);
2859 }
2860 if (executable_file((char *)buf, path))
2861 {
2862 retval = TRUE;
2863 goto theend;
2864 }
2865
2866 p = e2;
2867 }
2868
2869 p = e;
2870 }
2871
2872theend:
2873 free(pathextbuf);
2874 free(pathbuf);
2875 return retval;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002876}
2877
Bram Moolenaar1eed5322019-02-26 17:03:54 +01002878#if (defined(__MINGW32__) && __MSVCRT_VERSION__ >= 0x800) || \
2879 (defined(_MSC_VER) && _MSC_VER >= 1400)
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002880/*
2881 * Bad parameter handler.
2882 *
2883 * Certain MS CRT functions will intentionally crash when passed invalid
2884 * parameters to highlight possible security holes. Setting this function as
2885 * the bad parameter handler will prevent the crash.
2886 *
2887 * In debug builds the parameters contain CRT information that might help track
2888 * down the source of a problem, but in non-debug builds the arguments are all
2889 * NULL/0. Debug builds will also produce assert dialogs from the CRT, it is
2890 * worth allowing these to make debugging of issues easier.
2891 */
2892 static void
Yegappan Lakshmanana34b4462022-06-11 10:43:26 +01002893bad_param_handler(const wchar_t *expression UNUSED,
2894 const wchar_t *function UNUSED,
2895 const wchar_t *file UNUSED,
2896 unsigned int line UNUSED,
2897 uintptr_t pReserved UNUSED)
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002898{
2899}
2900
2901# define SET_INVALID_PARAM_HANDLER \
2902 ((void)_set_invalid_parameter_handler(bad_param_handler))
2903#else
2904# define SET_INVALID_PARAM_HANDLER
2905#endif
2906
Bram Moolenaar4f974752019-02-17 17:44:42 +01002907#ifdef FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00002908
2909/*
2910 * GUI version of mch_init().
2911 */
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002912 static void
2913mch_init_g(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002914{
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002915# ifndef __MINGW32__
Bram Moolenaar071d4272004-06-13 20:20:40 +00002916 extern int _fmode;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002917# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002918
Bram Moolenaar0f873732019-12-05 20:28:46 +01002919 // Silently handle invalid parameters to CRT functions
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002920 SET_INVALID_PARAM_HANDLER;
2921
Bram Moolenaar0f873732019-12-05 20:28:46 +01002922 // Let critical errors result in a failure, not in a dialog box. Required
2923 // for the timestamp test to work on removed floppies.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002924 SetErrorMode(SEM_FAILCRITICALERRORS);
2925
Bram Moolenaar0f873732019-12-05 20:28:46 +01002926 _fmode = O_BINARY; // we do our own CR-LF translation
Bram Moolenaar071d4272004-06-13 20:20:40 +00002927
Bram Moolenaar0f873732019-12-05 20:28:46 +01002928 // Specify window size. Is there a place to get the default from?
Bram Moolenaar071d4272004-06-13 20:20:40 +00002929 Rows = 25;
2930 Columns = 80;
2931
Bram Moolenaar0f873732019-12-05 20:28:46 +01002932 // Look for 'vimrun'
Bram Moolenaar071d4272004-06-13 20:20:40 +00002933 {
2934 char_u vimrun_location[_MAX_PATH + 4];
2935
Bram Moolenaar0f873732019-12-05 20:28:46 +01002936 // First try in same directory as gvim.exe
Bram Moolenaar071d4272004-06-13 20:20:40 +00002937 STRCPY(vimrun_location, exe_name);
2938 STRCPY(gettail(vimrun_location), "vimrun.exe");
2939 if (mch_getperm(vimrun_location) >= 0)
2940 {
2941 if (*skiptowhite(vimrun_location) != NUL)
2942 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01002943 // Enclose path with white space in double quotes.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002944 mch_memmove(vimrun_location + 1, vimrun_location,
2945 STRLEN(vimrun_location) + 1);
2946 *vimrun_location = '"';
2947 STRCPY(gettail(vimrun_location), "vimrun\" ");
2948 }
2949 else
2950 STRCPY(gettail(vimrun_location), "vimrun ");
2951
2952 vimrun_path = (char *)vim_strsave(vimrun_location);
2953 s_dont_use_vimrun = FALSE;
2954 }
Bram Moolenaar95da1362020-05-30 18:37:55 +02002955 else if (executable_exists("vimrun.exe", NULL, TRUE, FALSE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002956 s_dont_use_vimrun = FALSE;
2957
Bram Moolenaar0f873732019-12-05 20:28:46 +01002958 // Don't give the warning for a missing vimrun.exe right now, but only
2959 // when vimrun was supposed to be used. Don't bother people that do
2960 // not need vimrun.exe.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002961 if (s_dont_use_vimrun)
2962 need_vimrun_warning = TRUE;
2963 }
2964
2965 /*
2966 * If "finstr.exe" doesn't exist, use "grep -n" for 'grepprg'.
2967 * Otherwise the default "findstr /n" is used.
2968 */
Bram Moolenaar95da1362020-05-30 18:37:55 +02002969 if (!executable_exists("findstr.exe", NULL, TRUE, FALSE))
Bram Moolenaar75ab5902022-04-18 15:36:40 +01002970 set_option_value_give_err((char_u *)"grepprg",
2971 0, (char_u *)"grep -n", 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002972
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002973# ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01002974 win_clip_init();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002975# endif
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01002976
2977 vtp_flag_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002978}
2979
2980
Bram Moolenaar0f873732019-12-05 20:28:46 +01002981#endif // FEAT_GUI_MSWIN
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002982
2983#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002984
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002985# define SRWIDTH(sr) ((sr).Right - (sr).Left + 1)
2986# define SRHEIGHT(sr) ((sr).Bottom - (sr).Top + 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002987
2988/*
2989 * ClearConsoleBuffer()
2990 * Description:
2991 * Clears the entire contents of the console screen buffer, using the
2992 * specified attribute.
2993 * Returns:
2994 * TRUE on success
2995 */
2996 static BOOL
2997ClearConsoleBuffer(WORD wAttribute)
2998{
2999 CONSOLE_SCREEN_BUFFER_INFO csbi;
3000 COORD coord;
3001 DWORD NumCells, dummy;
3002
3003 if (!GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3004 return FALSE;
3005
3006 NumCells = csbi.dwSize.X * csbi.dwSize.Y;
3007 coord.X = 0;
3008 coord.Y = 0;
3009 if (!FillConsoleOutputCharacter(g_hConOut, ' ', NumCells,
3010 coord, &dummy))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003011 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003012 if (!FillConsoleOutputAttribute(g_hConOut, wAttribute, NumCells,
3013 coord, &dummy))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003014 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003015
3016 return TRUE;
3017}
3018
3019/*
3020 * FitConsoleWindow()
3021 * Description:
3022 * Checks if the console window will fit within given buffer dimensions.
3023 * Also, if requested, will shrink the window to fit.
3024 * Returns:
3025 * TRUE on success
3026 */
3027 static BOOL
3028FitConsoleWindow(
3029 COORD dwBufferSize,
3030 BOOL WantAdjust)
3031{
3032 CONSOLE_SCREEN_BUFFER_INFO csbi;
3033 COORD dwWindowSize;
3034 BOOL NeedAdjust = FALSE;
3035
3036 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3037 {
3038 /*
3039 * A buffer resize will fail if the current console window does
3040 * not lie completely within that buffer. To avoid this, we might
3041 * have to move and possibly shrink the window.
3042 */
3043 if (csbi.srWindow.Right >= dwBufferSize.X)
3044 {
3045 dwWindowSize.X = SRWIDTH(csbi.srWindow);
3046 if (dwWindowSize.X > dwBufferSize.X)
3047 dwWindowSize.X = dwBufferSize.X;
3048 csbi.srWindow.Right = dwBufferSize.X - 1;
3049 csbi.srWindow.Left = dwBufferSize.X - dwWindowSize.X;
3050 NeedAdjust = TRUE;
3051 }
3052 if (csbi.srWindow.Bottom >= dwBufferSize.Y)
3053 {
3054 dwWindowSize.Y = SRHEIGHT(csbi.srWindow);
3055 if (dwWindowSize.Y > dwBufferSize.Y)
3056 dwWindowSize.Y = dwBufferSize.Y;
3057 csbi.srWindow.Bottom = dwBufferSize.Y - 1;
3058 csbi.srWindow.Top = dwBufferSize.Y - dwWindowSize.Y;
3059 NeedAdjust = TRUE;
3060 }
3061 if (NeedAdjust && WantAdjust)
3062 {
3063 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &csbi.srWindow))
3064 return FALSE;
3065 }
3066 return TRUE;
3067 }
3068
3069 return FALSE;
3070}
3071
3072typedef struct ConsoleBufferStruct
3073{
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003074 BOOL IsValid;
3075 CONSOLE_SCREEN_BUFFER_INFO Info;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003076 PCHAR_INFO Buffer;
3077 COORD BufferSize;
Bram Moolenaar444fda22017-08-11 20:37:00 +02003078 PSMALL_RECT Regions;
3079 int NumRegions;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003080} ConsoleBuffer;
3081
3082/*
3083 * SaveConsoleBuffer()
3084 * Description:
3085 * Saves important information about the console buffer, including the
3086 * actual buffer contents. The saved information is suitable for later
3087 * restoration by RestoreConsoleBuffer().
3088 * Returns:
3089 * TRUE if all information was saved; FALSE otherwise
3090 * If FALSE, still sets cb->IsValid if buffer characteristics were saved.
3091 */
3092 static BOOL
3093SaveConsoleBuffer(
3094 ConsoleBuffer *cb)
3095{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003096 DWORD NumCells;
3097 COORD BufferCoord;
3098 SMALL_RECT ReadRegion;
3099 WORD Y, Y_incr;
Bram Moolenaar444fda22017-08-11 20:37:00 +02003100 int i, numregions;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003101
Bram Moolenaar071d4272004-06-13 20:20:40 +00003102 if (cb == NULL)
3103 return FALSE;
3104
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003105 if (!GetConsoleScreenBufferInfo(g_hConOut, &cb->Info))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003106 {
3107 cb->IsValid = FALSE;
3108 return FALSE;
3109 }
3110 cb->IsValid = TRUE;
3111
Christopher Plewright1140b512022-11-12 18:46:05 +00003112 // VTP uses alternate screen buffer.
3113 // No need to save buffer contents for restoration.
Christopher Plewrightc8b126d2022-12-22 13:45:23 +00003114 if (use_alternate_screen_buffer)
Christopher Plewright1140b512022-11-12 18:46:05 +00003115 return TRUE;
3116
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003117 /*
3118 * Allocate a buffer large enough to hold the entire console screen
3119 * buffer. If this ConsoleBuffer structure has already been initialized
3120 * with a buffer of the correct size, then just use that one.
3121 */
3122 if (!cb->IsValid || cb->Buffer == NULL ||
3123 cb->BufferSize.X != cb->Info.dwSize.X ||
3124 cb->BufferSize.Y != cb->Info.dwSize.Y)
3125 {
3126 cb->BufferSize.X = cb->Info.dwSize.X;
3127 cb->BufferSize.Y = cb->Info.dwSize.Y;
3128 NumCells = cb->BufferSize.X * cb->BufferSize.Y;
3129 vim_free(cb->Buffer);
Bram Moolenaarc799fe22019-05-28 23:08:19 +02003130 cb->Buffer = ALLOC_MULT(CHAR_INFO, NumCells);
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003131 if (cb->Buffer == NULL)
3132 return FALSE;
3133 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003134
3135 /*
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003136 * We will now copy the console screen buffer into our buffer.
3137 * ReadConsoleOutput() seems to be limited as far as how much you
3138 * can read at a time. Empirically, this number seems to be about
3139 * 12000 cells (rows * columns). Start at position (0, 0) and copy
3140 * in chunks until it is all copied. The chunks will all have the
3141 * same horizontal characteristics, so initialize them now. The
3142 * height of each chunk will be (12000 / width).
Bram Moolenaar071d4272004-06-13 20:20:40 +00003143 */
Bram Moolenaar61594242015-09-01 20:23:37 +02003144 BufferCoord.X = 0;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003145 ReadRegion.Left = 0;
3146 ReadRegion.Right = cb->Info.dwSize.X - 1;
3147 Y_incr = 12000 / cb->Info.dwSize.X;
Bram Moolenaar444fda22017-08-11 20:37:00 +02003148
3149 numregions = (cb->Info.dwSize.Y + Y_incr - 1) / Y_incr;
3150 if (cb->Regions == NULL || numregions != cb->NumRegions)
3151 {
3152 cb->NumRegions = numregions;
3153 vim_free(cb->Regions);
Bram Moolenaarc799fe22019-05-28 23:08:19 +02003154 cb->Regions = ALLOC_MULT(SMALL_RECT, cb->NumRegions);
Bram Moolenaar444fda22017-08-11 20:37:00 +02003155 if (cb->Regions == NULL)
3156 {
Bram Moolenaard23a8232018-02-10 18:45:26 +01003157 VIM_CLEAR(cb->Buffer);
Bram Moolenaar444fda22017-08-11 20:37:00 +02003158 return FALSE;
3159 }
3160 }
3161
3162 for (i = 0, Y = 0; i < cb->NumRegions; i++, Y += Y_incr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003163 {
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003164 /*
3165 * Read into position (0, Y) in our buffer.
3166 */
3167 BufferCoord.Y = Y;
3168 /*
3169 * Read the region whose top left corner is (0, Y) and whose bottom
3170 * right corner is (width - 1, Y + Y_incr - 1). This should define
3171 * a region of size width by Y_incr. Don't worry if this region is
3172 * too large for the remaining buffer; it will be cropped.
3173 */
3174 ReadRegion.Top = Y;
3175 ReadRegion.Bottom = Y + Y_incr - 1;
Bram Moolenaar0f873732019-12-05 20:28:46 +01003176 if (!ReadConsoleOutputW(g_hConOut, // output handle
3177 cb->Buffer, // our buffer
3178 cb->BufferSize, // dimensions of our buffer
3179 BufferCoord, // offset in our buffer
3180 &ReadRegion)) // region to save
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003181 {
Bram Moolenaard23a8232018-02-10 18:45:26 +01003182 VIM_CLEAR(cb->Buffer);
3183 VIM_CLEAR(cb->Regions);
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003184 return FALSE;
3185 }
Bram Moolenaar444fda22017-08-11 20:37:00 +02003186 cb->Regions[i] = ReadRegion;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003187 }
3188
3189 return TRUE;
3190}
3191
3192/*
3193 * RestoreConsoleBuffer()
3194 * Description:
3195 * Restores important information about the console buffer, including the
3196 * actual buffer contents, if desired. The information to restore is in
3197 * the same format used by SaveConsoleBuffer().
3198 * Returns:
3199 * TRUE on success
3200 */
3201 static BOOL
3202RestoreConsoleBuffer(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003203 ConsoleBuffer *cb,
3204 BOOL RestoreScreen)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003205{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003206 COORD BufferCoord;
3207 SMALL_RECT WriteRegion;
Bram Moolenaar444fda22017-08-11 20:37:00 +02003208 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003209
Christopher Plewright1140b512022-11-12 18:46:05 +00003210 // VTP uses alternate screen buffer.
3211 // No need to restore buffer contents.
Christopher Plewrightc8b126d2022-12-22 13:45:23 +00003212 if (use_alternate_screen_buffer)
Christopher Plewright1140b512022-11-12 18:46:05 +00003213 return TRUE;
3214
Bram Moolenaar071d4272004-06-13 20:20:40 +00003215 if (cb == NULL || !cb->IsValid)
3216 return FALSE;
3217
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003218 /*
3219 * Before restoring the buffer contents, clear the current buffer, and
3220 * restore the cursor position and window information. Doing this now
3221 * prevents old buffer contents from "flashing" onto the screen.
3222 */
3223 if (RestoreScreen)
3224 ClearConsoleBuffer(cb->Info.wAttributes);
3225
3226 FitConsoleWindow(cb->Info.dwSize, TRUE);
3227 if (!SetConsoleScreenBufferSize(g_hConOut, cb->Info.dwSize))
3228 return FALSE;
3229 if (!SetConsoleTextAttribute(g_hConOut, cb->Info.wAttributes))
3230 return FALSE;
3231
3232 if (!RestoreScreen)
3233 {
3234 /*
3235 * No need to restore the screen buffer contents, so we're done.
3236 */
3237 return TRUE;
3238 }
3239
3240 if (!SetConsoleCursorPosition(g_hConOut, cb->Info.dwCursorPosition))
3241 return FALSE;
3242 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &cb->Info.srWindow))
3243 return FALSE;
3244
3245 /*
3246 * Restore the screen buffer contents.
3247 */
3248 if (cb->Buffer != NULL)
3249 {
Bram Moolenaar444fda22017-08-11 20:37:00 +02003250 for (i = 0; i < cb->NumRegions; i++)
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003251 {
Bram Moolenaar444fda22017-08-11 20:37:00 +02003252 BufferCoord.X = cb->Regions[i].Left;
3253 BufferCoord.Y = cb->Regions[i].Top;
3254 WriteRegion = cb->Regions[i];
Bram Moolenaar0f873732019-12-05 20:28:46 +01003255 if (!WriteConsoleOutputW(g_hConOut, // output handle
3256 cb->Buffer, // our buffer
3257 cb->BufferSize, // dimensions of our buffer
3258 BufferCoord, // offset in our buffer
3259 &WriteRegion)) // region to restore
Bram Moolenaar444fda22017-08-11 20:37:00 +02003260 return FALSE;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003261 }
3262 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003263
3264 return TRUE;
3265}
3266
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003267# define FEAT_RESTORE_ORIG_SCREEN
3268# ifdef FEAT_RESTORE_ORIG_SCREEN
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003269static ConsoleBuffer g_cbOrig = { 0 };
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003270# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003271static ConsoleBuffer g_cbNonTermcap = { 0 };
3272static ConsoleBuffer g_cbTermcap = { 0 };
3273
Bram Moolenaar071d4272004-06-13 20:20:40 +00003274char g_szOrigTitle[256] = { 0 };
Bram Moolenaar0f873732019-12-05 20:28:46 +01003275HWND g_hWnd = NULL; // also used in os_mswin.c
Bram Moolenaar071d4272004-06-13 20:20:40 +00003276static HICON g_hOrigIconSmall = NULL;
3277static HICON g_hOrigIcon = NULL;
3278static HICON g_hVimIcon = NULL;
3279static BOOL g_fCanChangeIcon = FALSE;
3280
Bram Moolenaar071d4272004-06-13 20:20:40 +00003281/*
3282 * GetConsoleIcon()
3283 * Description:
3284 * Attempts to retrieve the small icon and/or the big icon currently in
3285 * use by a given window.
3286 * Returns:
3287 * TRUE on success
3288 */
3289 static BOOL
3290GetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003291 HWND hWnd,
3292 HICON *phIconSmall,
3293 HICON *phIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003294{
3295 if (hWnd == NULL)
3296 return FALSE;
3297
3298 if (phIconSmall != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003299 *phIconSmall = (HICON)SendMessage(hWnd, WM_GETICON,
3300 (WPARAM)ICON_SMALL, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003301 if (phIcon != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003302 *phIcon = (HICON)SendMessage(hWnd, WM_GETICON,
3303 (WPARAM)ICON_BIG, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003304 return TRUE;
3305}
3306
3307/*
3308 * SetConsoleIcon()
3309 * Description:
3310 * Attempts to change the small icon and/or the big icon currently in
3311 * use by a given window.
3312 * Returns:
3313 * TRUE on success
3314 */
3315 static BOOL
3316SetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003317 HWND hWnd,
3318 HICON hIconSmall,
3319 HICON hIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003320{
Bram Moolenaar071d4272004-06-13 20:20:40 +00003321 if (hWnd == NULL)
3322 return FALSE;
3323
3324 if (hIconSmall != NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003325 SendMessage(hWnd, WM_SETICON,
3326 (WPARAM)ICON_SMALL, (LPARAM)hIconSmall);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003327 if (hIcon != NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003328 SendMessage(hWnd, WM_SETICON,
3329 (WPARAM)ICON_BIG, (LPARAM) hIcon);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003330 return TRUE;
3331}
3332
3333/*
3334 * SaveConsoleTitleAndIcon()
3335 * Description:
3336 * Saves the current console window title in g_szOrigTitle, for later
3337 * restoration. Also, attempts to obtain a handle to the console window,
3338 * and use it to save the small and big icons currently in use by the
3339 * console window. This is not always possible on some versions of Windows;
3340 * nor is it possible when running Vim remotely using Telnet (since the
3341 * console window the user sees is owned by a remote process).
3342 */
3343 static void
3344SaveConsoleTitleAndIcon(void)
3345{
Bram Moolenaar0f873732019-12-05 20:28:46 +01003346 // Save the original title.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003347 if (!GetConsoleTitle(g_szOrigTitle, sizeof(g_szOrigTitle)))
3348 return;
3349
3350 /*
3351 * Obtain a handle to the console window using GetConsoleWindow() from
3352 * KERNEL32.DLL; we need to handle in order to change the window icon.
3353 * This function only exists on NT-based Windows, starting with Windows
3354 * 2000. On older operating systems, we can't change the window icon
3355 * anyway.
3356 */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003357 g_hWnd = GetConsoleWindow();
Bram Moolenaar071d4272004-06-13 20:20:40 +00003358 if (g_hWnd == NULL)
3359 return;
3360
Bram Moolenaar0f873732019-12-05 20:28:46 +01003361 // Save the original console window icon.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003362 GetConsoleIcon(g_hWnd, &g_hOrigIconSmall, &g_hOrigIcon);
3363 if (g_hOrigIconSmall == NULL || g_hOrigIcon == NULL)
3364 return;
3365
Bram Moolenaar0f873732019-12-05 20:28:46 +01003366 // Extract the first icon contained in the Vim executable.
K.Takata2da11a42022-09-10 13:03:12 +01003367 if (
3368# ifdef FEAT_LIBCALL
3369 mch_icon_load((HANDLE *)&g_hVimIcon) == FAIL ||
3370# endif
3371 g_hVimIcon == NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003372 g_hVimIcon = ExtractIcon(NULL, (LPCSTR)exe_name, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003373 if (g_hVimIcon != NULL)
3374 g_fCanChangeIcon = TRUE;
3375}
Bram Moolenaar071d4272004-06-13 20:20:40 +00003376
3377static int g_fWindInitCalled = FALSE;
3378static int g_fTermcapMode = FALSE;
3379static CONSOLE_CURSOR_INFO g_cci;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003380
3381/*
3382 * non-GUI version of mch_init().
3383 */
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003384 static void
3385mch_init_c(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003386{
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003387# ifndef FEAT_RESTORE_ORIG_SCREEN
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003388 CONSOLE_SCREEN_BUFFER_INFO csbi;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003389# endif
3390# ifndef __MINGW32__
Bram Moolenaar071d4272004-06-13 20:20:40 +00003391 extern int _fmode;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003392# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003393
Bram Moolenaar0f873732019-12-05 20:28:46 +01003394 // Silently handle invalid parameters to CRT functions
Bram Moolenaard32a99a2010-09-21 17:29:23 +02003395 SET_INVALID_PARAM_HANDLER;
3396
Bram Moolenaar0f873732019-12-05 20:28:46 +01003397 // Let critical errors result in a failure, not in a dialog box. Required
3398 // for the timestamp test to work on removed floppies.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003399 SetErrorMode(SEM_FAILCRITICALERRORS);
3400
Bram Moolenaar0f873732019-12-05 20:28:46 +01003401 _fmode = O_BINARY; // we do our own CR-LF translation
Bram Moolenaar071d4272004-06-13 20:20:40 +00003402 out_flush();
3403
Bram Moolenaar0f873732019-12-05 20:28:46 +01003404 // Obtain handles for the standard Console I/O devices
Bram Moolenaar071d4272004-06-13 20:20:40 +00003405 if (read_cmd_fd == 0)
3406 g_hConIn = GetStdHandle(STD_INPUT_HANDLE);
3407 else
3408 create_conin();
3409 g_hConOut = GetStdHandle(STD_OUTPUT_HANDLE);
3410
Christopher Plewright38804d62022-11-09 23:55:52 +00003411 wt_init();
3412 vtp_flag_init();
3413 vtp_init();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003414# ifdef FEAT_RESTORE_ORIG_SCREEN
Bram Moolenaar0f873732019-12-05 20:28:46 +01003415 // Save the initial console buffer for later restoration
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003416 SaveConsoleBuffer(&g_cbOrig);
3417 g_attrCurrent = g_attrDefault = g_cbOrig.Info.wAttributes;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003418# else
Bram Moolenaar0f873732019-12-05 20:28:46 +01003419 // Get current text attributes
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003420 GetConsoleScreenBufferInfo(g_hConOut, &csbi);
3421 g_attrCurrent = g_attrDefault = csbi.wAttributes;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003422# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003423 if (cterm_normal_fg_color == 0)
3424 cterm_normal_fg_color = (g_attrCurrent & 0xf) + 1;
3425 if (cterm_normal_bg_color == 0)
3426 cterm_normal_bg_color = ((g_attrCurrent >> 4) & 0xf) + 1;
3427
Bram Moolenaarbdace832019-03-02 10:13:42 +01003428 // Fg and Bg color index number at startup
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02003429 g_color_index_fg = g_attrDefault & 0xf;
3430 g_color_index_bg = (g_attrDefault >> 4) & 0xf;
3431
Bram Moolenaar0f873732019-12-05 20:28:46 +01003432 // set termcap codes to current text attributes
Bram Moolenaar071d4272004-06-13 20:20:40 +00003433 update_tcap(g_attrCurrent);
3434
3435 GetConsoleCursorInfo(g_hConOut, &g_cci);
3436 GetConsoleMode(g_hConIn, &g_cmodein);
3437 GetConsoleMode(g_hConOut, &g_cmodeout);
3438
Bram Moolenaar071d4272004-06-13 20:20:40 +00003439 SaveConsoleTitleAndIcon();
3440 /*
3441 * Set both the small and big icons of the console window to Vim's icon.
3442 * Note that Vim presently only has one size of icon (32x32), but it
3443 * automatically gets scaled down to 16x16 when setting the small icon.
3444 */
3445 if (g_fCanChangeIcon)
3446 SetConsoleIcon(g_hWnd, g_hVimIcon, g_hVimIcon);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003447
3448 ui_get_shellsize();
3449
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003450# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00003451 fdDump = fopen("dump", "wt");
3452
3453 if (fdDump)
3454 {
3455 time_t t;
3456
3457 time(&t);
3458 fputs(ctime(&t), fdDump);
3459 fflush(fdDump);
3460 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003461# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003462
3463 g_fWindInitCalled = TRUE;
3464
Bram Moolenaar071d4272004-06-13 20:20:40 +00003465 g_fMouseAvail = GetSystemMetrics(SM_MOUSEPRESENT);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003466
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003467# ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01003468 win_clip_init();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003469# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003470}
3471
3472/*
3473 * non-GUI version of mch_exit().
3474 * Shut down and exit with status `r'
3475 * Careful: mch_exit() may be called before mch_init()!
3476 */
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003477 static void
3478mch_exit_c(int r)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003479{
Bram Moolenaar955f1982017-02-05 15:10:51 +01003480 exiting = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003481
Bram Moolenaarcafafb32018-02-22 21:07:09 +01003482 vtp_exit();
3483
Bram Moolenaar955f1982017-02-05 15:10:51 +01003484 stoptermcap();
Bram Moolenaar071d4272004-06-13 20:20:40 +00003485 if (g_fWindInitCalled)
3486 settmode(TMODE_COOK);
3487
Bram Moolenaar0f873732019-12-05 20:28:46 +01003488 ml_close_all(TRUE); // remove all memfiles
Bram Moolenaar071d4272004-06-13 20:20:40 +00003489
3490 if (g_fWindInitCalled)
3491 {
Bram Moolenaar40385db2018-08-07 22:31:44 +02003492 mch_restore_title(SAVE_RESTORE_BOTH);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003493 /*
3494 * Restore both the small and big icons of the console window to
3495 * what they were at startup. Don't do this when the window is
3496 * closed, Vim would hang here.
3497 */
3498 if (g_fCanChangeIcon && !g_fForceExit)
3499 SetConsoleIcon(g_hWnd, g_hOrigIconSmall, g_hOrigIcon);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003500
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003501# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00003502 if (fdDump)
3503 {
3504 time_t t;
3505
3506 time(&t);
3507 fputs(ctime(&t), fdDump);
3508 fclose(fdDump);
3509 }
3510 fdDump = NULL;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003511# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003512 }
3513
3514 SetConsoleCursorInfo(g_hConOut, &g_cci);
Wez Furlong6ef5ab52021-05-30 19:29:41 +02003515 SetConsoleMode(g_hConIn, g_cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003516 SetConsoleMode(g_hConOut, g_cmodeout);
3517
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003518# ifdef DYNAMIC_GETTEXT
Bram Moolenaar071d4272004-06-13 20:20:40 +00003519 dyn_libintl_end();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003520# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003521
3522 exit(r);
3523}
Bram Moolenaar0f873732019-12-05 20:28:46 +01003524#endif // !FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00003525
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003526 void
3527mch_init(void)
3528{
3529#ifdef VIMDLL
3530 if (gui.starting)
3531 mch_init_g();
3532 else
3533 mch_init_c();
3534#elif defined(FEAT_GUI_MSWIN)
3535 mch_init_g();
3536#else
3537 mch_init_c();
3538#endif
3539}
3540
3541 void
3542mch_exit(int r)
3543{
Bram Moolenaar173d8412020-04-19 14:02:26 +02003544#ifdef FEAT_NETBEANS_INTG
3545 netbeans_send_disconnect();
3546#endif
3547
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003548#ifdef VIMDLL
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02003549 if (gui.in_use || gui.starting)
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003550 mch_exit_g(r);
3551 else
3552 mch_exit_c(r);
3553#elif defined(FEAT_GUI_MSWIN)
3554 mch_exit_g(r);
3555#else
3556 mch_exit_c(r);
3557#endif
3558}
3559
Bram Moolenaar071d4272004-06-13 20:20:40 +00003560/*
3561 * Do we have an interactive window?
3562 */
3563 int
3564mch_check_win(
Bram Moolenaar1266d672017-02-01 13:43:36 +01003565 int argc UNUSED,
3566 char **argv UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003567{
3568 get_exe_name();
3569
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003570#if defined(FEAT_GUI_MSWIN) && !defined(VIMDLL)
Bram Moolenaar0f873732019-12-05 20:28:46 +01003571 return OK; // GUI always has a tty
Bram Moolenaar071d4272004-06-13 20:20:40 +00003572#else
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003573# ifdef VIMDLL
3574 if (gui.in_use)
3575 return OK;
3576# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003577 if (isatty(1))
3578 return OK;
3579 return FAIL;
3580#endif
3581}
3582
Bram Moolenaar65f04f62013-08-30 17:29:16 +02003583/*
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003584 * Set the case of the file name, if it already exists.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003585 * When "len" is > 0, also expand short to long filenames.
3586 */
3587 void
3588fname_case(
3589 char_u *name,
3590 int len)
3591{
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003592 int flen;
3593 WCHAR *p;
3594 WCHAR buf[_MAX_PATH + 1];
Bram Moolenaar071d4272004-06-13 20:20:40 +00003595
Bram Moolenaara3ffd9c2005-07-21 21:03:15 +00003596 flen = (int)STRLEN(name);
Bram Moolenaar65f04f62013-08-30 17:29:16 +02003597 if (flen == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003598 return;
3599
3600 slash_adjust(name);
3601
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003602 p = enc_to_utf16(name, NULL);
3603 if (p == NULL)
Bram Moolenaar65f04f62013-08-30 17:29:16 +02003604 return;
3605
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003606 if (GetLongPathNameW(p, buf, _MAX_PATH))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003607 {
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003608 char_u *q = utf16_to_enc(buf, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003609
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003610 if (q != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003611 {
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003612 if (len > 0 || flen >= (int)STRLEN(q))
3613 vim_strncpy(name, q, (len > 0) ? len - 1 : flen);
3614 vim_free(q);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003615 }
3616 }
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003617 vim_free(p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003618}
3619
3620
3621/*
3622 * Insert user name in s[len].
3623 */
3624 int
3625mch_get_user_name(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003626 char_u *s,
3627 int len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003628{
Bram Moolenaar0f873732019-12-05 20:28:46 +01003629 WCHAR wszUserName[256 + 1]; // UNLEN is 256
K.Takataeeec2542021-06-02 13:28:16 +02003630 DWORD wcch = ARRAY_LENGTH(wszUserName);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003631
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003632 if (GetUserNameW(wszUserName, &wcch))
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003633 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003634 char_u *p = utf16_to_enc(wszUserName, NULL);
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003635
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003636 if (p != NULL)
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003637 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003638 vim_strncpy(s, p, len - 1);
3639 vim_free(p);
3640 return OK;
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003641 }
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003642 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003643 s[0] = NUL;
3644 return FAIL;
3645}
3646
3647
3648/*
3649 * Insert host name in s[len].
3650 */
3651 void
3652mch_get_host_name(
3653 char_u *s,
3654 int len)
3655{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003656 WCHAR wszHostName[256 + 1];
K.Takataeeec2542021-06-02 13:28:16 +02003657 DWORD wcch = ARRAY_LENGTH(wszHostName);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003658
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003659 if (GetComputerNameW(wszHostName, &wcch))
Bram Moolenaar2cc87382013-12-11 18:21:45 +01003660 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003661 char_u *p = utf16_to_enc(wszHostName, NULL);
Bram Moolenaar2cc87382013-12-11 18:21:45 +01003662
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003663 if (p != NULL)
Bram Moolenaar2cc87382013-12-11 18:21:45 +01003664 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003665 vim_strncpy(s, p, len - 1);
3666 vim_free(p);
3667 return;
Bram Moolenaar2cc87382013-12-11 18:21:45 +01003668 }
Bram Moolenaar2cc87382013-12-11 18:21:45 +01003669 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003670}
3671
3672
3673/*
3674 * return process ID
3675 */
3676 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003677mch_get_pid(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003678{
3679 return (long)GetCurrentProcessId();
3680}
3681
Bram Moolenaar67cf86b2019-04-28 22:25:38 +02003682/*
3683 * return TRUE if process "pid" is still running
3684 */
3685 int
Bram Moolenaar1b243ea2019-04-28 22:50:40 +02003686mch_process_running(long pid)
Bram Moolenaar67cf86b2019-04-28 22:25:38 +02003687{
3688 HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION, 0, (DWORD)pid);
3689 DWORD status = 0;
3690 int ret = FALSE;
3691
3692 if (hProcess == NULL)
3693 return FALSE; // might not have access
3694 if (GetExitCodeProcess(hProcess, &status) )
3695 ret = status == STILL_ACTIVE;
3696 CloseHandle(hProcess);
3697 return ret;
3698}
Bram Moolenaar071d4272004-06-13 20:20:40 +00003699
3700/*
3701 * Get name of current directory into buffer 'buf' of length 'len' bytes.
3702 * Return OK for success, FAIL for failure.
3703 */
3704 int
3705mch_dirname(
3706 char_u *buf,
3707 int len)
3708{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003709 WCHAR wbuf[_MAX_PATH + 1];
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02003710
Bram Moolenaar071d4272004-06-13 20:20:40 +00003711 /*
3712 * Originally this was:
3713 * return (getcwd(buf, len) != NULL ? OK : FAIL);
3714 * But the Win32s known bug list says that getcwd() doesn't work
3715 * so use the Win32 system call instead. <Negri>
3716 */
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003717 if (GetCurrentDirectoryW(_MAX_PATH, wbuf) != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003718 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003719 WCHAR wcbuf[_MAX_PATH + 1];
3720 char_u *p = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003721
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003722 if (GetLongPathNameW(wbuf, wcbuf, _MAX_PATH) != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003723 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003724 p = utf16_to_enc(wcbuf, NULL);
3725 if (STRLEN(p) >= (size_t)len)
Bram Moolenaarcea1f9e2018-08-19 14:38:42 +02003726 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003727 // long path name is too long, fall back to short one
Bram Moolenaar071d4272004-06-13 20:20:40 +00003728 vim_free(p);
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003729 p = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003730 }
3731 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003732 if (p == NULL)
3733 p = utf16_to_enc(wbuf, NULL);
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02003734
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003735 if (p != NULL)
3736 {
3737 vim_strncpy(buf, p, len - 1);
3738 vim_free(p);
3739 return OK;
3740 }
3741 }
3742 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003743}
3744
3745/*
Bram Moolenaarffa22202013-11-21 12:34:11 +01003746 * Get file permissions for "name".
3747 * Return mode_t or -1 for error.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003748 */
3749 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003750mch_getperm(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003751{
Bram Moolenaar8767f522016-07-01 17:17:39 +02003752 stat_T st;
Bram Moolenaarffa22202013-11-21 12:34:11 +01003753 int n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003754
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003755 n = mch_stat((char *)name, &st);
Bram Moolenaar78cf3f02014-01-10 18:16:07 +01003756 return n == 0 ? (long)(unsigned short)st.st_mode : -1L;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003757}
3758
3759
3760/*
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003761 * Set file permission for "name" to "perm".
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003762 *
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003763 * Return FAIL for failure, OK otherwise.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003764 */
3765 int
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003766mch_setperm(char_u *name, long perm)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003767{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003768 long n;
3769 WCHAR *p;
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003770
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003771 p = enc_to_utf16(name, NULL);
3772 if (p == NULL)
3773 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003774
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003775 n = _wchmod(p, perm);
3776 vim_free(p);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003777 if (n == -1)
3778 return FAIL;
3779
3780 win32_set_archive(name);
3781
3782 return OK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003783}
3784
3785/*
3786 * Set hidden flag for "name".
3787 */
3788 void
3789mch_hide(char_u *name)
3790{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003791 int attrs = win32_getattrs(name);
3792 if (attrs == -1)
3793 return;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003794
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003795 attrs |= FILE_ATTRIBUTE_HIDDEN;
3796 win32_setattrs(name, attrs);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003797}
3798
3799/*
Bram Moolenaar8a52ba72015-11-02 14:45:56 +01003800 * Return TRUE if file "name" exists and is hidden.
3801 */
3802 int
3803mch_ishidden(char_u *name)
3804{
3805 int f = win32_getattrs(name);
3806
3807 if (f == -1)
Bram Moolenaar0f873732019-12-05 20:28:46 +01003808 return FALSE; // file does not exist at all
Bram Moolenaar8a52ba72015-11-02 14:45:56 +01003809
3810 return (f & FILE_ATTRIBUTE_HIDDEN) != 0;
3811}
3812
3813/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003814 * return TRUE if "name" is a directory
3815 * return FALSE if "name" is not a directory or upon error
3816 */
3817 int
3818mch_isdir(char_u *name)
3819{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003820 int f = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003821
3822 if (f == -1)
Bram Moolenaar0f873732019-12-05 20:28:46 +01003823 return FALSE; // file does not exist at all
Bram Moolenaar071d4272004-06-13 20:20:40 +00003824
3825 return (f & FILE_ATTRIBUTE_DIRECTORY) != 0;
3826}
3827
3828/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01003829 * return TRUE if "name" is a directory, NOT a symlink to a directory
3830 * return FALSE if "name" is not a directory
3831 * return FALSE for error
3832 */
3833 int
3834mch_isrealdir(char_u *name)
3835{
3836 return mch_isdir(name) && !mch_is_symbolic_link(name);
3837}
3838
3839/*
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003840 * Create directory "name".
3841 * Return 0 on success, -1 on error.
3842 */
3843 int
3844mch_mkdir(char_u *name)
3845{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003846 WCHAR *p;
3847 int retval;
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003848
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003849 p = enc_to_utf16(name, NULL);
3850 if (p == NULL)
3851 return -1;
3852 retval = _wmkdir(p);
3853 vim_free(p);
3854 return retval;
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003855}
3856
3857/*
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003858 * Delete directory "name".
3859 * Return 0 on success, -1 on error.
3860 */
3861 int
3862mch_rmdir(char_u *name)
3863{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003864 WCHAR *p;
3865 int retval;
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003866
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003867 p = enc_to_utf16(name, NULL);
3868 if (p == NULL)
3869 return -1;
3870 retval = _wrmdir(p);
3871 vim_free(p);
3872 return retval;
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003873}
3874
3875/*
Bram Moolenaar03f48552006-02-28 23:52:23 +00003876 * Return TRUE if file "fname" has more than one link.
3877 */
3878 int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003879mch_is_hard_link(char_u *fname)
Bram Moolenaar03f48552006-02-28 23:52:23 +00003880{
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003881 BY_HANDLE_FILE_INFORMATION info;
3882
3883 return win32_fileinfo(fname, &info) == FILEINFO_OK
3884 && info.nNumberOfLinks > 1;
3885}
3886
3887/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01003888 * Return TRUE if "name" is a symbolic link (or a junction).
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003889 */
3890 int
Bram Moolenaar203258c2016-01-17 22:15:16 +01003891mch_is_symbolic_link(char_u *name)
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003892{
3893 HANDLE hFind;
3894 int res = FALSE;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003895 DWORD fileFlags = 0, reparseTag = 0;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003896 WCHAR *wn;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003897 WIN32_FIND_DATAW findDataW;
3898
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003899 wn = enc_to_utf16(name, NULL);
3900 if (wn == NULL)
3901 return FALSE;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003902
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003903 hFind = FindFirstFileW(wn, &findDataW);
3904 vim_free(wn);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003905 if (hFind != INVALID_HANDLE_VALUE)
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003906 {
3907 fileFlags = findDataW.dwFileAttributes;
3908 reparseTag = findDataW.dwReserved0;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003909 FindClose(hFind);
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003910 }
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003911
3912 if ((fileFlags & FILE_ATTRIBUTE_REPARSE_POINT)
Bram Moolenaar203258c2016-01-17 22:15:16 +01003913 && (reparseTag == IO_REPARSE_TAG_SYMLINK
3914 || reparseTag == IO_REPARSE_TAG_MOUNT_POINT))
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003915 res = TRUE;
3916
3917 return res;
3918}
3919
3920/*
3921 * Return TRUE if file "fname" has more than one link or if it is a symbolic
3922 * link.
3923 */
3924 int
3925mch_is_linked(char_u *fname)
3926{
3927 if (mch_is_hard_link(fname) || mch_is_symbolic_link(fname))
3928 return TRUE;
3929 return FALSE;
3930}
3931
3932/*
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003933 * Get the by-handle-file-information for "fname".
3934 * Returns FILEINFO_OK when OK.
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003935 * Returns FILEINFO_ENC_FAIL when enc_to_utf16() failed.
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003936 * Returns FILEINFO_READ_FAIL when CreateFile() failed.
3937 * Returns FILEINFO_INFO_FAIL when GetFileInformationByHandle() failed.
3938 */
3939 int
3940win32_fileinfo(char_u *fname, BY_HANDLE_FILE_INFORMATION *info)
3941{
Bram Moolenaar03f48552006-02-28 23:52:23 +00003942 HANDLE hFile;
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003943 int res = FILEINFO_READ_FAIL;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003944 WCHAR *wn;
Bram Moolenaar03f48552006-02-28 23:52:23 +00003945
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003946 wn = enc_to_utf16(fname, NULL);
3947 if (wn == NULL)
3948 return FILEINFO_ENC_FAIL;
3949
3950 hFile = CreateFileW(wn, // file name
3951 GENERIC_READ, // access mode
3952 FILE_SHARE_READ | FILE_SHARE_WRITE, // share mode
3953 NULL, // security descriptor
3954 OPEN_EXISTING, // creation disposition
3955 FILE_FLAG_BACKUP_SEMANTICS, // file attributes
3956 NULL); // handle to template file
3957 vim_free(wn);
Bram Moolenaar03f48552006-02-28 23:52:23 +00003958
3959 if (hFile != INVALID_HANDLE_VALUE)
3960 {
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003961 if (GetFileInformationByHandle(hFile, info) != 0)
3962 res = FILEINFO_OK;
3963 else
3964 res = FILEINFO_INFO_FAIL;
Bram Moolenaar03f48552006-02-28 23:52:23 +00003965 CloseHandle(hFile);
3966 }
3967
Bram Moolenaar03f48552006-02-28 23:52:23 +00003968 return res;
3969}
3970
3971/*
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003972 * get file attributes for `name'
3973 * -1 : error
3974 * else FILE_ATTRIBUTE_* defined in winnt.h
3975 */
Bram Moolenaarffa22202013-11-21 12:34:11 +01003976 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003977win32_getattrs(char_u *name)
3978{
3979 int attr;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003980 WCHAR *p;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003981
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003982 p = enc_to_utf16(name, NULL);
3983 if (p == NULL)
3984 return INVALID_FILE_ATTRIBUTES;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003985
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003986 attr = GetFileAttributesW(p);
3987 vim_free(p);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003988
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003989 return attr;
3990}
3991
3992/*
3993 * set file attributes for `name' to `attrs'
3994 *
3995 * return -1 for failure, 0 otherwise
3996 */
Bram Moolenaar6dff58f2018-09-30 21:43:26 +02003997 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003998win32_setattrs(char_u *name, int attrs)
3999{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004000 int res;
4001 WCHAR *p;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004002
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004003 p = enc_to_utf16(name, NULL);
4004 if (p == NULL)
4005 return -1;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004006
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004007 res = SetFileAttributesW(p, attrs);
4008 vim_free(p);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004009
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004010 return res ? 0 : -1;
4011}
4012
4013/*
4014 * Set archive flag for "name".
4015 */
Bram Moolenaar6dff58f2018-09-30 21:43:26 +02004016 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004017win32_set_archive(char_u *name)
4018{
4019 int attrs = win32_getattrs(name);
4020 if (attrs == -1)
4021 return -1;
4022
4023 attrs |= FILE_ATTRIBUTE_ARCHIVE;
4024 return win32_setattrs(name, attrs);
4025}
4026
4027/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00004028 * Return TRUE if file or directory "name" is writable (not readonly).
4029 * Strange semantics of Win32: a readonly directory is writable, but you can't
4030 * delete a file. Let's say this means it is writable.
4031 */
4032 int
4033mch_writable(char_u *name)
4034{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004035 int attrs = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004036
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004037 return (attrs != -1 && (!(attrs & FILE_ATTRIBUTE_READONLY)
4038 || (attrs & FILE_ATTRIBUTE_DIRECTORY)));
Bram Moolenaar071d4272004-06-13 20:20:40 +00004039}
4040
Bram Moolenaar071d4272004-06-13 20:20:40 +00004041/*
Bram Moolenaar43663192017-03-05 14:29:12 +01004042 * Return TRUE if "name" can be executed, FALSE if not.
Bram Moolenaar77b77102015-03-21 22:18:41 +01004043 * If "use_path" is FALSE only check if "name" is executable.
Bram Moolenaar43663192017-03-05 14:29:12 +01004044 * When returning TRUE and "path" is not NULL save the path and set "*path" to
4045 * the allocated memory.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004046 */
4047 int
Yegappan Lakshmananebb01bd2022-06-08 15:14:09 +01004048mch_can_exe(char_u *name, char_u **path, int use_path UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004049{
Bram Moolenaar95da1362020-05-30 18:37:55 +02004050 return executable_exists((char *)name, path, TRUE, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004051}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004052
4053/*
4054 * Check what "name" is:
4055 * NODE_NORMAL: file or directory (or doesn't exist)
4056 * NODE_WRITABLE: writable device, socket, fifo, etc.
4057 * NODE_OTHER: non-writable things
4058 */
4059 int
4060mch_nodetype(char_u *name)
4061{
4062 HANDLE hFile;
4063 int type;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004064 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004065
Bram Moolenaar0f873732019-12-05 20:28:46 +01004066 // We can't open a file with a name "\\.\con" or "\\.\prn" and trying to
4067 // read from it later will cause Vim to hang. Thus return NODE_WRITABLE
4068 // here.
Bram Moolenaar043545e2006-10-10 16:44:07 +00004069 if (STRNCMP(name, "\\\\.\\", 4) == 0)
4070 return NODE_WRITABLE;
4071
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004072 wn = enc_to_utf16(name, NULL);
4073 if (wn == NULL)
4074 return NODE_NORMAL;
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004075
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004076 hFile = CreateFileW(wn, // file name
4077 GENERIC_WRITE, // access mode
4078 0, // share mode
4079 NULL, // security descriptor
4080 OPEN_EXISTING, // creation disposition
4081 0, // file attributes
4082 NULL); // handle to template file
4083 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004084 if (hFile == INVALID_HANDLE_VALUE)
4085 return NODE_NORMAL;
4086
4087 type = GetFileType(hFile);
4088 CloseHandle(hFile);
4089 if (type == FILE_TYPE_CHAR)
4090 return NODE_WRITABLE;
4091 if (type == FILE_TYPE_DISK)
4092 return NODE_NORMAL;
4093 return NODE_OTHER;
4094}
4095
4096#ifdef HAVE_ACL
4097struct my_acl
4098{
4099 PSECURITY_DESCRIPTOR pSecurityDescriptor;
4100 PSID pSidOwner;
4101 PSID pSidGroup;
4102 PACL pDacl;
4103 PACL pSacl;
4104};
4105#endif
4106
4107/*
4108 * Return a pointer to the ACL of file "fname" in allocated memory.
4109 * Return NULL if the ACL is not available for whatever reason.
4110 */
4111 vim_acl_T
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004112mch_get_acl(char_u *fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004113{
4114#ifndef HAVE_ACL
4115 return (vim_acl_T)NULL;
4116#else
4117 struct my_acl *p = NULL;
Bram Moolenaar27515922013-06-29 15:36:26 +02004118 DWORD err;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004119
Bram Moolenaarc799fe22019-05-28 23:08:19 +02004120 p = ALLOC_CLEAR_ONE(struct my_acl);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004121 if (p != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004122 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004123 WCHAR *wn;
Bram Moolenaar27515922013-06-29 15:36:26 +02004124
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004125 wn = enc_to_utf16(fname, NULL);
4126 if (wn == NULL)
Bram Moolenaarbbf9f342020-11-10 22:03:40 +01004127 {
4128 vim_free(p);
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004129 return NULL;
Bram Moolenaarbbf9f342020-11-10 22:03:40 +01004130 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004131
4132 // Try to retrieve the entire security descriptor.
4133 err = GetNamedSecurityInfoW(
4134 wn, // Abstract filename
4135 SE_FILE_OBJECT, // File Object
4136 OWNER_SECURITY_INFORMATION |
4137 GROUP_SECURITY_INFORMATION |
4138 DACL_SECURITY_INFORMATION |
4139 SACL_SECURITY_INFORMATION,
4140 &p->pSidOwner, // Ownership information.
4141 &p->pSidGroup, // Group membership.
4142 &p->pDacl, // Discretionary information.
4143 &p->pSacl, // For auditing purposes.
4144 &p->pSecurityDescriptor);
4145 if (err == ERROR_ACCESS_DENIED ||
4146 err == ERROR_PRIVILEGE_NOT_HELD)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004147 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004148 // Retrieve only DACL.
4149 (void)GetNamedSecurityInfoW(
4150 wn,
4151 SE_FILE_OBJECT,
4152 DACL_SECURITY_INFORMATION,
4153 NULL,
4154 NULL,
4155 &p->pDacl,
4156 NULL,
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004157 &p->pSecurityDescriptor);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004158 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004159 if (p->pSecurityDescriptor == NULL)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004160 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004161 mch_free_acl((vim_acl_T)p);
4162 p = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004163 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004164 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004165 }
4166
4167 return (vim_acl_T)p;
4168#endif
4169}
4170
Bram Moolenaar27515922013-06-29 15:36:26 +02004171#ifdef HAVE_ACL
4172/*
4173 * Check if "acl" contains inherited ACE.
4174 */
4175 static BOOL
4176is_acl_inherited(PACL acl)
4177{
4178 DWORD i;
4179 ACL_SIZE_INFORMATION acl_info;
4180 PACCESS_ALLOWED_ACE ace;
4181
4182 acl_info.AceCount = 0;
4183 GetAclInformation(acl, &acl_info, sizeof(acl_info), AclSizeInformation);
4184 for (i = 0; i < acl_info.AceCount; i++)
4185 {
4186 GetAce(acl, i, (LPVOID *)&ace);
4187 if (ace->Header.AceFlags & INHERITED_ACE)
4188 return TRUE;
4189 }
4190 return FALSE;
4191}
4192#endif
4193
Bram Moolenaar071d4272004-06-13 20:20:40 +00004194/*
4195 * Set the ACL of file "fname" to "acl" (unless it's NULL).
4196 * Errors are ignored.
4197 * This must only be called with "acl" equal to what mch_get_acl() returned.
4198 */
4199 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004200mch_set_acl(char_u *fname, vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004201{
4202#ifdef HAVE_ACL
4203 struct my_acl *p = (struct my_acl *)acl;
Bram Moolenaar27515922013-06-29 15:36:26 +02004204 SECURITY_INFORMATION sec_info = 0;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004205 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004206
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004207 if (p == NULL)
4208 return;
4209
4210 wn = enc_to_utf16(fname, NULL);
4211 if (wn == NULL)
4212 return;
4213
4214 // Set security flags
4215 if (p->pSidOwner)
4216 sec_info |= OWNER_SECURITY_INFORMATION;
4217 if (p->pSidGroup)
4218 sec_info |= GROUP_SECURITY_INFORMATION;
4219 if (p->pDacl)
Bram Moolenaar27515922013-06-29 15:36:26 +02004220 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004221 sec_info |= DACL_SECURITY_INFORMATION;
4222 // Do not inherit its parent's DACL.
4223 // If the DACL is inherited, Cygwin permissions would be changed.
4224 if (!is_acl_inherited(p->pDacl))
4225 sec_info |= PROTECTED_DACL_SECURITY_INFORMATION;
Bram Moolenaar27515922013-06-29 15:36:26 +02004226 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004227 if (p->pSacl)
4228 sec_info |= SACL_SECURITY_INFORMATION;
4229
4230 (void)SetNamedSecurityInfoW(
4231 wn, // Abstract filename
4232 SE_FILE_OBJECT, // File Object
4233 sec_info,
4234 p->pSidOwner, // Ownership information.
4235 p->pSidGroup, // Group membership.
4236 p->pDacl, // Discretionary information.
4237 p->pSacl // For auditing purposes.
4238 );
4239 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004240#endif
4241}
4242
4243 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004244mch_free_acl(vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004245{
4246#ifdef HAVE_ACL
4247 struct my_acl *p = (struct my_acl *)acl;
4248
4249 if (p != NULL)
4250 {
4251 LocalFree(p->pSecurityDescriptor); // Free the memory just in case
4252 vim_free(p);
4253 }
4254#endif
4255}
4256
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004257#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004258
4259/*
4260 * handler for ctrl-break, ctrl-c interrupts, and fatal events.
4261 */
4262 static BOOL WINAPI
4263handler_routine(
4264 DWORD dwCtrlType)
4265{
Bram Moolenaar589b1102017-08-12 16:39:05 +02004266 INPUT_RECORD ir;
4267 DWORD out;
4268
Bram Moolenaar071d4272004-06-13 20:20:40 +00004269 switch (dwCtrlType)
4270 {
4271 case CTRL_C_EVENT:
4272 if (ctrl_c_interrupts)
4273 g_fCtrlCPressed = TRUE;
4274 return TRUE;
4275
4276 case CTRL_BREAK_EVENT:
4277 g_fCBrkPressed = TRUE;
Bram Moolenaar589b1102017-08-12 16:39:05 +02004278 ctrl_break_was_pressed = TRUE;
Bram Moolenaar0f873732019-12-05 20:28:46 +01004279 // ReadConsoleInput is blocking, send a key event to continue.
Bram Moolenaar589b1102017-08-12 16:39:05 +02004280 ir.EventType = KEY_EVENT;
4281 ir.Event.KeyEvent.bKeyDown = TRUE;
4282 ir.Event.KeyEvent.wRepeatCount = 1;
4283 ir.Event.KeyEvent.wVirtualKeyCode = VK_CANCEL;
4284 ir.Event.KeyEvent.wVirtualScanCode = 0;
4285 ir.Event.KeyEvent.dwControlKeyState = 0;
4286 ir.Event.KeyEvent.uChar.UnicodeChar = 0;
4287 WriteConsoleInput(g_hConIn, &ir, 1, &out);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004288 return TRUE;
4289
Bram Moolenaar0f873732019-12-05 20:28:46 +01004290 // fatal events: shut down gracefully
Bram Moolenaar071d4272004-06-13 20:20:40 +00004291 case CTRL_CLOSE_EVENT:
4292 case CTRL_LOGOFF_EVENT:
4293 case CTRL_SHUTDOWN_EVENT:
4294 windgoto((int)Rows - 1, 0);
4295 g_fForceExit = TRUE;
4296
Bram Moolenaar0fde2902008-03-16 13:54:13 +00004297 vim_snprintf((char *)IObuff, IOSIZE, _("Vim: Caught %s event\n"),
Bram Moolenaar071d4272004-06-13 20:20:40 +00004298 (dwCtrlType == CTRL_CLOSE_EVENT
4299 ? _("close")
4300 : dwCtrlType == CTRL_LOGOFF_EVENT
4301 ? _("logoff")
4302 : _("shutdown")));
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004303# ifdef DEBUG
Bram Moolenaar071d4272004-06-13 20:20:40 +00004304 OutputDebugString(IObuff);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004305# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004306
Bram Moolenaar0f873732019-12-05 20:28:46 +01004307 preserve_exit(); // output IObuff, preserve files and exit
Bram Moolenaar071d4272004-06-13 20:20:40 +00004308
Bram Moolenaar0f873732019-12-05 20:28:46 +01004309 return TRUE; // not reached
Bram Moolenaar071d4272004-06-13 20:20:40 +00004310
4311 default:
4312 return FALSE;
4313 }
4314}
4315
4316
4317/*
4318 * set the tty in (raw) ? "raw" : "cooked" mode
4319 */
4320 void
Bram Moolenaar26e86442020-05-17 14:06:16 +02004321mch_settmode(tmode_T tmode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004322{
4323 DWORD cmodein;
4324 DWORD cmodeout;
4325 BOOL bEnableHandler;
4326
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004327# ifdef VIMDLL
4328 if (gui.in_use)
4329 return;
4330# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004331 GetConsoleMode(g_hConIn, &cmodein);
4332 GetConsoleMode(g_hConOut, &cmodeout);
4333 if (tmode == TMODE_RAW)
4334 {
4335 cmodein &= ~(ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
4336 ENABLE_ECHO_INPUT);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004337 if (g_fMouseActive)
Wez Furlong6ef5ab52021-05-30 19:29:41 +02004338 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00004339 cmodein |= ENABLE_MOUSE_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02004340 cmodein &= ~ENABLE_QUICK_EDIT_MODE;
4341 }
4342 else
4343 {
4344 cmodein |= g_cmodein & ENABLE_QUICK_EDIT_MODE;
4345 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01004346 cmodeout &= ~(
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004347# ifdef FEAT_TERMGUICOLORS
Bram Moolenaar0f873732019-12-05 20:28:46 +01004348 // Do not turn off the ENABLE_PROCESSED_OUTPUT flag when using
4349 // VTP.
Bram Moolenaarcafafb32018-02-22 21:07:09 +01004350 ((vtp_working) ? 0 : ENABLE_PROCESSED_OUTPUT) |
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004351# else
Bram Moolenaarcafafb32018-02-22 21:07:09 +01004352 ENABLE_PROCESSED_OUTPUT |
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004353# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01004354 ENABLE_WRAP_AT_EOL_OUTPUT);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004355 bEnableHandler = TRUE;
4356 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01004357 else // cooked
Bram Moolenaar071d4272004-06-13 20:20:40 +00004358 {
4359 cmodein |= (ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
4360 ENABLE_ECHO_INPUT);
4361 cmodeout |= (ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
4362 bEnableHandler = FALSE;
4363 }
Wez Furlong6ef5ab52021-05-30 19:29:41 +02004364 SetConsoleMode(g_hConIn, cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004365 SetConsoleMode(g_hConOut, cmodeout);
4366 SetConsoleCtrlHandler(handler_routine, bEnableHandler);
4367
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004368# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00004369 if (fdDump)
4370 {
4371 fprintf(fdDump, "mch_settmode(%s, in = %x, out = %x)\n",
4372 tmode == TMODE_RAW ? "raw" :
4373 tmode == TMODE_COOK ? "cooked" : "normal",
4374 cmodein, cmodeout);
4375 fflush(fdDump);
4376 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004377# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004378}
4379
4380
4381/*
4382 * Get the size of the current window in `Rows' and `Columns'
4383 * Return OK when size could be determined, FAIL otherwise.
4384 */
4385 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004386mch_get_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004387{
4388 CONSOLE_SCREEN_BUFFER_INFO csbi;
4389
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004390# ifdef VIMDLL
4391 if (gui.in_use)
4392 return OK;
4393# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004394 if (!g_fTermcapMode && g_cbTermcap.IsValid)
4395 {
4396 /*
4397 * For some reason, we are trying to get the screen dimensions
4398 * even though we are not in termcap mode. The 'Rows' and 'Columns'
4399 * variables are really intended to mean the size of Vim screen
4400 * while in termcap mode.
4401 */
4402 Rows = g_cbTermcap.Info.dwSize.Y;
4403 Columns = g_cbTermcap.Info.dwSize.X;
4404 }
4405 else if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
4406 {
4407 Rows = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
4408 Columns = csbi.srWindow.Right - csbi.srWindow.Left + 1;
4409 }
4410 else
4411 {
4412 Rows = 25;
4413 Columns = 80;
4414 }
4415 return OK;
4416}
4417
4418/*
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004419 * Resize console buffer to 'COORD'
4420 */
4421 static void
4422ResizeConBuf(
4423 HANDLE hConsole,
4424 COORD coordScreen)
4425{
4426 if (!SetConsoleScreenBufferSize(hConsole, coordScreen))
4427 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004428# ifdef MCH_WRITE_DUMP
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004429 if (fdDump)
4430 {
4431 fprintf(fdDump, "SetConsoleScreenBufferSize failed: %lx\n",
4432 GetLastError());
4433 fflush(fdDump);
4434 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004435# endif
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004436 }
4437}
4438
4439/*
4440 * Resize console window size to 'srWindowRect'
4441 */
4442 static void
4443ResizeWindow(
4444 HANDLE hConsole,
4445 SMALL_RECT srWindowRect)
4446{
4447 if (!SetConsoleWindowInfo(hConsole, TRUE, &srWindowRect))
4448 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004449# ifdef MCH_WRITE_DUMP
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004450 if (fdDump)
4451 {
4452 fprintf(fdDump, "SetConsoleWindowInfo failed: %lx\n",
4453 GetLastError());
4454 fflush(fdDump);
4455 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004456# endif
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004457 }
4458}
4459
4460/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00004461 * Set a console window to `xSize' * `ySize'
4462 */
4463 static void
4464ResizeConBufAndWindow(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004465 HANDLE hConsole,
4466 int xSize,
4467 int ySize)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004468{
Bram Moolenaar0f873732019-12-05 20:28:46 +01004469 CONSOLE_SCREEN_BUFFER_INFO csbi; // hold current console buffer info
4470 SMALL_RECT srWindowRect; // hold the new console size
Bram Moolenaar071d4272004-06-13 20:20:40 +00004471 COORD coordScreen;
Bram Moolenaarf49a6922019-07-15 20:37:05 +02004472 COORD cursor;
Bram Moolenaar2551c032018-08-23 22:38:31 +02004473 static int resized = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004474
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004475# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00004476 if (fdDump)
4477 {
4478 fprintf(fdDump, "ResizeConBufAndWindow(%d, %d)\n", xSize, ySize);
4479 fflush(fdDump);
4480 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004481# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004482
Bram Moolenaar0f873732019-12-05 20:28:46 +01004483 // get the largest size we can size the console window to
Bram Moolenaar071d4272004-06-13 20:20:40 +00004484 coordScreen = GetLargestConsoleWindowSize(hConsole);
4485
Bram Moolenaar0f873732019-12-05 20:28:46 +01004486 // define the new console window size and scroll position
Bram Moolenaar071d4272004-06-13 20:20:40 +00004487 srWindowRect.Left = srWindowRect.Top = (SHORT) 0;
4488 srWindowRect.Right = (SHORT) (min(xSize, coordScreen.X) - 1);
4489 srWindowRect.Bottom = (SHORT) (min(ySize, coordScreen.Y) - 1);
4490
4491 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
4492 {
4493 int sx, sy;
4494
4495 sx = csbi.srWindow.Right - csbi.srWindow.Left + 1;
4496 sy = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
4497 if (sy < ySize || sx < xSize)
4498 {
4499 /*
4500 * Increasing number of lines/columns, do buffer first.
4501 * Use the maximal size in x and y direction.
4502 */
4503 if (sy < ySize)
4504 coordScreen.Y = ySize;
4505 else
4506 coordScreen.Y = sy;
4507 if (sx < xSize)
4508 coordScreen.X = xSize;
4509 else
4510 coordScreen.X = sx;
4511 SetConsoleScreenBufferSize(hConsole, coordScreen);
4512 }
4513 }
4514
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004515 // define the new console buffer size
Bram Moolenaar071d4272004-06-13 20:20:40 +00004516 coordScreen.X = xSize;
4517 coordScreen.Y = ySize;
4518
Bram Moolenaar2551c032018-08-23 22:38:31 +02004519 // In the new console call API, only the first time in reverse order
4520 if (!vtp_working || resized)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004521 {
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004522 ResizeWindow(hConsole, srWindowRect);
4523 ResizeConBuf(hConsole, coordScreen);
4524 }
4525 else
4526 {
Bram Moolenaarf49a6922019-07-15 20:37:05 +02004527 // Workaround for a Windows 10 bug
4528 cursor.X = srWindowRect.Left;
4529 cursor.Y = srWindowRect.Top;
4530 SetConsoleCursorPosition(hConsole, cursor);
4531
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004532 ResizeConBuf(hConsole, coordScreen);
4533 ResizeWindow(hConsole, srWindowRect);
Bram Moolenaar2551c032018-08-23 22:38:31 +02004534 resized = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004535 }
4536}
4537
4538
4539/*
4540 * Set the console window to `Rows' * `Columns'
4541 */
4542 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004543mch_set_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004544{
4545 COORD coordScreen;
4546
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004547# ifdef VIMDLL
4548 if (gui.in_use)
4549 return;
4550# endif
Bram Moolenaar0f873732019-12-05 20:28:46 +01004551 // Don't change window size while still starting up
Bram Moolenaar071d4272004-06-13 20:20:40 +00004552 if (suppress_winsize != 0)
4553 {
4554 suppress_winsize = 2;
4555 return;
4556 }
4557
4558 if (term_console)
4559 {
4560 coordScreen = GetLargestConsoleWindowSize(g_hConOut);
4561
Bram Moolenaar0f873732019-12-05 20:28:46 +01004562 // Clamp Rows and Columns to reasonable values
Bram Moolenaar071d4272004-06-13 20:20:40 +00004563 if (Rows > coordScreen.Y)
4564 Rows = coordScreen.Y;
4565 if (Columns > coordScreen.X)
4566 Columns = coordScreen.X;
4567
4568 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
4569 }
4570}
4571
4572/*
4573 * Rows and/or Columns has changed.
4574 */
4575 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004576mch_new_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004577{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004578# ifdef VIMDLL
4579 if (gui.in_use)
4580 return;
4581# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004582 set_scroll_region(0, 0, Columns - 1, Rows - 1);
4583}
4584
4585
4586/*
4587 * Called when started up, to set the winsize that was delayed.
4588 */
4589 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004590mch_set_winsize_now(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004591{
4592 if (suppress_winsize == 2)
4593 {
4594 suppress_winsize = 0;
4595 mch_set_shellsize();
4596 shell_resized();
4597 }
4598 suppress_winsize = 0;
4599}
Bram Moolenaar0f873732019-12-05 20:28:46 +01004600#endif // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00004601
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004602 static BOOL
4603vim_create_process(
Bram Moolenaar36c85b22013-12-12 20:25:44 +01004604 char *cmd,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004605 BOOL inherit_handles,
Bram Moolenaar3f1138e2014-01-05 13:29:26 +01004606 DWORD flags,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004607 STARTUPINFO *si,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004608 PROCESS_INFORMATION *pi,
4609 LPVOID *env,
4610 char *cwd)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004611{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004612 BOOL ret = FALSE;
4613 WCHAR *wcmd, *wcwd = NULL;
4614
4615 wcmd = enc_to_utf16((char_u *)cmd, NULL);
4616 if (wcmd == NULL)
4617 return FALSE;
4618 if (cwd != NULL)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004619 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004620 wcwd = enc_to_utf16((char_u *)cwd, NULL);
4621 if (wcwd == NULL)
4622 goto theend;
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004623 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004624
4625 ret = CreateProcessW(
4626 NULL, // Executable name
4627 wcmd, // Command to execute
4628 NULL, // Process security attributes
4629 NULL, // Thread security attributes
4630 inherit_handles, // Inherit handles
4631 flags, // Creation flags
4632 env, // Environment
4633 wcwd, // Current directory
4634 (LPSTARTUPINFOW)si, // Startup information
4635 pi); // Process information
4636theend:
4637 vim_free(wcmd);
4638 vim_free(wcwd);
4639 return ret;
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004640}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004641
4642
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004643 static HINSTANCE
4644vim_shell_execute(
4645 char *cmd,
4646 INT n_show_cmd)
4647{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004648 HINSTANCE ret;
4649 WCHAR *wcmd;
4650
4651 wcmd = enc_to_utf16((char_u *)cmd, NULL);
4652 if (wcmd == NULL)
4653 return (HINSTANCE) 0;
4654
4655 ret = ShellExecuteW(NULL, NULL, wcmd, NULL, NULL, n_show_cmd);
4656 vim_free(wcmd);
4657 return ret;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004658}
4659
4660
Bram Moolenaar4f974752019-02-17 17:44:42 +01004661#if defined(FEAT_GUI_MSWIN) || defined(PROTO)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004662
4663/*
4664 * Specialised version of system() for Win32 GUI mode.
4665 * This version proceeds as follows:
4666 * 1. Create a console window for use by the subprocess
4667 * 2. Run the subprocess (it gets the allocated console by default)
4668 * 3. Wait for the subprocess to terminate and get its exit code
4669 * 4. Prompt the user to press a key to close the console window
4670 */
4671 static int
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004672mch_system_classic(char *cmd, int options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004673{
4674 STARTUPINFO si;
4675 PROCESS_INFORMATION pi;
4676 DWORD ret = 0;
4677 HWND hwnd = GetFocus();
4678
4679 si.cb = sizeof(si);
4680 si.lpReserved = NULL;
4681 si.lpDesktop = NULL;
4682 si.lpTitle = NULL;
4683 si.dwFlags = STARTF_USESHOWWINDOW;
4684 /*
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004685 * It's nicer to run a filter command in a minimized window.
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01004686 * Don't activate the window to keep focus on Vim.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004687 */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004688 if (options & SHELL_DOOUT)
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01004689 si.wShowWindow = SW_SHOWMINNOACTIVE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004690 else
4691 si.wShowWindow = SW_SHOWNORMAL;
4692 si.cbReserved2 = 0;
4693 si.lpReserved2 = NULL;
4694
Bram Moolenaar0f873732019-12-05 20:28:46 +01004695 // Now, run the command
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004696 vim_create_process(cmd, FALSE,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004697 CREATE_DEFAULT_ERROR_MODE | CREATE_NEW_CONSOLE,
4698 &si, &pi, NULL, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004699
Bram Moolenaar0f873732019-12-05 20:28:46 +01004700 // Wait for the command to terminate before continuing
Bram Moolenaar071d4272004-06-13 20:20:40 +00004701 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004702# ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00004703 int delay = 1;
4704
Bram Moolenaar0f873732019-12-05 20:28:46 +01004705 // Keep updating the window while waiting for the shell to finish.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004706 for (;;)
4707 {
4708 MSG msg;
4709
K.Takatab7057bd2022-01-21 11:37:07 +00004710 if (PeekMessageW(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004711 {
4712 TranslateMessage(&msg);
K.Takatab7057bd2022-01-21 11:37:07 +00004713 DispatchMessageW(&msg);
Bram Moolenaare4195c52012-08-02 12:31:44 +02004714 delay = 1;
4715 continue;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004716 }
4717 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
4718 break;
4719
Bram Moolenaar0f873732019-12-05 20:28:46 +01004720 // We start waiting for a very short time and then increase it, so
4721 // that we respond quickly when the process is quick, and don't
4722 // consume too much overhead when it's slow.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004723 if (delay < 50)
4724 delay += 10;
4725 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004726# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004727 WaitForSingleObject(pi.hProcess, INFINITE);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004728# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004729
Bram Moolenaar0f873732019-12-05 20:28:46 +01004730 // Get the command exit code
Bram Moolenaar071d4272004-06-13 20:20:40 +00004731 GetExitCodeProcess(pi.hProcess, &ret);
4732 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004733
Bram Moolenaar0f873732019-12-05 20:28:46 +01004734 // Close the handles to the subprocess, so that it goes away
Bram Moolenaar071d4272004-06-13 20:20:40 +00004735 CloseHandle(pi.hThread);
4736 CloseHandle(pi.hProcess);
4737
Bram Moolenaar0f873732019-12-05 20:28:46 +01004738 // Try to get input focus back. Doesn't always work though.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004739 PostMessage(hwnd, WM_SETFOCUS, 0, 0);
4740
4741 return ret;
4742}
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004743
4744/*
4745 * Thread launched by the gui to send the current buffer data to the
4746 * process. This way avoid to hang up vim totally if the children
4747 * process take a long time to process the lines.
4748 */
Bram Moolenaar4c38d662016-08-03 20:54:57 +02004749 static unsigned int __stdcall
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004750sub_process_writer(LPVOID param)
4751{
4752 HANDLE g_hChildStd_IN_Wr = param;
4753 linenr_T lnum = curbuf->b_op_start.lnum;
4754 DWORD len = 0;
4755 DWORD l;
4756 char_u *lp = ml_get(lnum);
4757 char_u *s;
4758 int written = 0;
4759
4760 for (;;)
4761 {
4762 l = (DWORD)STRLEN(lp + written);
4763 if (l == 0)
4764 len = 0;
4765 else if (lp[written] == NL)
4766 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004767 // NL -> NUL translation
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004768 WriteFile(g_hChildStd_IN_Wr, "", 1, &len, NULL);
4769 }
4770 else
4771 {
4772 s = vim_strchr(lp + written, NL);
4773 WriteFile(g_hChildStd_IN_Wr, (char *)lp + written,
4774 s == NULL ? l : (DWORD)(s - (lp + written)),
4775 &len, NULL);
4776 }
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +01004777 if (len == l)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004778 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004779 // Finished a line, add a NL, unless this line should not have
4780 // one.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004781 if (lnum != curbuf->b_op_end.lnum
Bram Moolenaar34d72d42015-07-17 14:18:08 +02004782 || (!curbuf->b_p_bin
4783 && curbuf->b_p_fixeol)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004784 || (lnum != curbuf->b_no_eol_lnum
4785 && (lnum != curbuf->b_ml.ml_line_count
4786 || curbuf->b_p_eol)))
4787 {
Bram Moolenaar42335f52018-09-13 15:33:43 +02004788 WriteFile(g_hChildStd_IN_Wr, "\n", 1,
4789 (LPDWORD)&vim_ignored, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004790 }
4791
4792 ++lnum;
4793 if (lnum > curbuf->b_op_end.lnum)
4794 break;
4795
4796 lp = ml_get(lnum);
4797 written = 0;
4798 }
4799 else if (len > 0)
4800 written += len;
4801 }
4802
Bram Moolenaar0f873732019-12-05 20:28:46 +01004803 // finished all the lines, close pipe
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004804 CloseHandle(g_hChildStd_IN_Wr);
Bram Moolenaar86f2cd52016-08-02 21:55:17 +02004805 return 0;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004806}
4807
4808
Bram Moolenaar0f873732019-12-05 20:28:46 +01004809# define BUFLEN 100 // length for buffer, stolen from unix version
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004810
4811/*
4812 * This function read from the children's stdout and write the
4813 * data on screen or in the buffer accordingly.
4814 */
4815 static void
4816dump_pipe(int options,
4817 HANDLE g_hChildStd_OUT_Rd,
4818 garray_T *ga,
4819 char_u buffer[],
4820 DWORD *buffer_off)
4821{
4822 DWORD availableBytes = 0;
4823 DWORD i;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004824 int ret;
4825 DWORD len;
4826 DWORD toRead;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004827
Bram Moolenaar0f873732019-12-05 20:28:46 +01004828 // we query the pipe to see if there is any data to read
4829 // to avoid to perform a blocking read
4830 ret = PeekNamedPipe(g_hChildStd_OUT_Rd, // pipe to query
4831 NULL, // optional buffer
4832 0, // buffer size
4833 NULL, // number of read bytes
4834 &availableBytes, // available bytes total
4835 NULL); // byteLeft
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004836
Bram Moolenaar0f873732019-12-05 20:28:46 +01004837 // We got real data in the pipe, read it
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02004838 while (ret != 0 && availableBytes > 0)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004839 {
Bram Moolenaara12a1612019-01-24 16:39:02 +01004840 toRead = (DWORD)(BUFLEN - *buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004841 toRead = availableBytes < toRead ? availableBytes : toRead;
Bram Moolenaara12a1612019-01-24 16:39:02 +01004842 ReadFile(g_hChildStd_OUT_Rd, buffer + *buffer_off, toRead , &len, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004843
Bram Moolenaar0f873732019-12-05 20:28:46 +01004844 // If we haven't read anything, there is a problem
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004845 if (len == 0)
4846 break;
4847
4848 availableBytes -= len;
4849
4850 if (options & SHELL_READ)
4851 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004852 // Do NUL -> NL translation, append NL separated
4853 // lines to the current buffer.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004854 for (i = 0; i < len; ++i)
4855 {
4856 if (buffer[i] == NL)
4857 append_ga_line(ga);
4858 else if (buffer[i] == NUL)
4859 ga_append(ga, NL);
4860 else
4861 ga_append(ga, buffer[i]);
4862 }
4863 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004864 else if (has_mbyte)
4865 {
4866 int l;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004867 int c;
4868 char_u *p;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004869
4870 len += *buffer_off;
4871 buffer[len] = NUL;
4872
Bram Moolenaar0f873732019-12-05 20:28:46 +01004873 // Check if the last character in buffer[] is
4874 // incomplete, keep these bytes for the next
4875 // round.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004876 for (p = buffer; p < buffer + len; p += l)
4877 {
Bram Moolenaard3c907b2016-08-17 21:32:09 +02004878 l = MB_CPTR2LEN(p);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004879 if (l == 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01004880 l = 1; // NUL byte?
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004881 else if (MB_BYTE2LEN(*p) != l)
4882 break;
4883 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01004884 if (p == buffer) // no complete character
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004885 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004886 // avoid getting stuck at an illegal byte
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004887 if (len >= 12)
4888 ++p;
4889 else
4890 {
4891 *buffer_off = len;
4892 return;
4893 }
4894 }
4895 c = *p;
4896 *p = NUL;
Bram Moolenaar32526b32019-01-19 17:43:09 +01004897 msg_puts((char *)buffer);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004898 if (p < buffer + len)
4899 {
4900 *p = c;
4901 *buffer_off = (DWORD)((buffer + len) - p);
4902 mch_memmove(buffer, p, *buffer_off);
4903 return;
4904 }
4905 *buffer_off = 0;
4906 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004907 else
4908 {
4909 buffer[len] = NUL;
Bram Moolenaar32526b32019-01-19 17:43:09 +01004910 msg_puts((char *)buffer);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004911 }
4912
4913 windgoto(msg_row, msg_col);
4914 cursor_on();
4915 out_flush();
4916 }
4917}
4918
4919/*
4920 * Version of system to use for windows NT > 5.0 (Win2K), use pipe
4921 * for communication and doesn't open any new window.
4922 */
4923 static int
4924mch_system_piped(char *cmd, int options)
4925{
4926 STARTUPINFO si;
4927 PROCESS_INFORMATION pi;
4928 DWORD ret = 0;
4929
4930 HANDLE g_hChildStd_IN_Rd = NULL;
4931 HANDLE g_hChildStd_IN_Wr = NULL;
4932 HANDLE g_hChildStd_OUT_Rd = NULL;
4933 HANDLE g_hChildStd_OUT_Wr = NULL;
4934
Bram Moolenaar0f873732019-12-05 20:28:46 +01004935 char_u buffer[BUFLEN + 1]; // reading buffer + size
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004936 DWORD len;
4937
Bram Moolenaar0f873732019-12-05 20:28:46 +01004938 // buffer used to receive keys
4939 char_u ta_buf[BUFLEN + 1]; // TypeAHead
4940 int ta_len = 0; // valid bytes in ta_buf[]
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004941
4942 DWORD i;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004943 int noread_cnt = 0;
4944 garray_T ga;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004945 int delay = 1;
Bram Moolenaar0f873732019-12-05 20:28:46 +01004946 DWORD buffer_off = 0; // valid bytes in buffer[]
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004947 char *p = NULL;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004948
4949 SECURITY_ATTRIBUTES saAttr;
4950
Bram Moolenaar0f873732019-12-05 20:28:46 +01004951 // Set the bInheritHandle flag so pipe handles are inherited.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004952 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
4953 saAttr.bInheritHandle = TRUE;
4954 saAttr.lpSecurityDescriptor = NULL;
4955
4956 if ( ! CreatePipe(&g_hChildStd_OUT_Rd, &g_hChildStd_OUT_Wr, &saAttr, 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01004957 // Ensure the read handle to the pipe for STDOUT is not inherited.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004958 || ! SetHandleInformation(g_hChildStd_OUT_Rd, HANDLE_FLAG_INHERIT, 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01004959 // Create a pipe for the child process's STDIN.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004960 || ! CreatePipe(&g_hChildStd_IN_Rd, &g_hChildStd_IN_Wr, &saAttr, 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01004961 // Ensure the write handle to the pipe for STDIN is not inherited.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004962 || ! SetHandleInformation(g_hChildStd_IN_Wr, HANDLE_FLAG_INHERIT, 0) )
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004963 {
4964 CloseHandle(g_hChildStd_IN_Rd);
4965 CloseHandle(g_hChildStd_IN_Wr);
4966 CloseHandle(g_hChildStd_OUT_Rd);
4967 CloseHandle(g_hChildStd_OUT_Wr);
Bram Moolenaar32526b32019-01-19 17:43:09 +01004968 msg_puts(_("\nCannot create pipes\n"));
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004969 }
4970
4971 si.cb = sizeof(si);
4972 si.lpReserved = NULL;
4973 si.lpDesktop = NULL;
4974 si.lpTitle = NULL;
4975 si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
4976
Bram Moolenaar0f873732019-12-05 20:28:46 +01004977 // set-up our file redirection
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004978 si.hStdError = g_hChildStd_OUT_Wr;
4979 si.hStdOutput = g_hChildStd_OUT_Wr;
4980 si.hStdInput = g_hChildStd_IN_Rd;
4981 si.wShowWindow = SW_HIDE;
4982 si.cbReserved2 = 0;
4983 si.lpReserved2 = NULL;
4984
4985 if (options & SHELL_READ)
4986 ga_init2(&ga, 1, BUFLEN);
4987
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004988 if (cmd != NULL)
4989 {
4990 p = (char *)vim_strsave((char_u *)cmd);
4991 if (p != NULL)
4992 unescape_shellxquote((char_u *)p, p_sxe);
4993 else
4994 p = cmd;
4995 }
4996
Bram Moolenaar0f873732019-12-05 20:28:46 +01004997 // Now, run the command.
4998 // About "Inherit handles" being TRUE: this command can be litigious,
4999 // handle inheritance was deactivated for pending temp file, but, if we
5000 // deactivate it, the pipes don't work for some reason.
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005001 vim_create_process(p, TRUE, CREATE_DEFAULT_ERROR_MODE,
5002 &si, &pi, NULL, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005003
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005004 if (p != cmd)
5005 vim_free(p);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005006
Bram Moolenaar0f873732019-12-05 20:28:46 +01005007 // Close our unused side of the pipes
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005008 CloseHandle(g_hChildStd_IN_Rd);
5009 CloseHandle(g_hChildStd_OUT_Wr);
5010
5011 if (options & SHELL_WRITE)
5012 {
Bram Moolenaar86f2cd52016-08-02 21:55:17 +02005013 HANDLE thread = (HANDLE)
Bram Moolenaar0f873732019-12-05 20:28:46 +01005014 _beginthreadex(NULL, // security attributes
5015 0, // default stack size
5016 sub_process_writer, // function to be executed
5017 g_hChildStd_IN_Wr, // parameter
5018 0, // creation flag, start immediately
5019 NULL); // we don't care about thread id
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005020 CloseHandle(thread);
5021 g_hChildStd_IN_Wr = NULL;
5022 }
5023
Bram Moolenaar0f873732019-12-05 20:28:46 +01005024 // Keep updating the window while waiting for the shell to finish.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005025 for (;;)
5026 {
5027 MSG msg;
5028
K.Takatab7057bd2022-01-21 11:37:07 +00005029 if (PeekMessageW(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005030 {
5031 TranslateMessage(&msg);
K.Takatab7057bd2022-01-21 11:37:07 +00005032 DispatchMessageW(&msg);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005033 }
5034
Bram Moolenaar0f873732019-12-05 20:28:46 +01005035 // write pipe information in the window
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005036 if ((options & (SHELL_READ|SHELL_WRITE))
5037# ifdef FEAT_GUI
5038 || gui.in_use
5039# endif
5040 )
5041 {
5042 len = 0;
5043 if (!(options & SHELL_EXPAND)
5044 && ((options &
5045 (SHELL_READ|SHELL_WRITE|SHELL_COOKED))
5046 != (SHELL_READ|SHELL_WRITE|SHELL_COOKED)
5047# ifdef FEAT_GUI
5048 || gui.in_use
5049# endif
5050 )
5051 && (ta_len > 0 || noread_cnt > 4))
5052 {
5053 if (ta_len == 0)
5054 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005055 // Get extra characters when we don't have any. Reset the
5056 // counter and timer.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005057 noread_cnt = 0;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005058 len = ui_inchar(ta_buf, BUFLEN, 10L, 0);
5059 }
5060 if (ta_len > 0 || len > 0)
5061 {
5062 /*
5063 * For pipes: Check for CTRL-C: send interrupt signal to
5064 * child. Check for CTRL-D: EOF, close pipe to child.
5065 */
5066 if (len == 1 && cmd != NULL)
5067 {
5068 if (ta_buf[ta_len] == Ctrl_C)
5069 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005070 // Learn what exit code is expected, for
5071 // now put 9 as SIGKILL
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005072 TerminateProcess(pi.hProcess, 9);
5073 }
5074 if (ta_buf[ta_len] == Ctrl_D)
5075 {
5076 CloseHandle(g_hChildStd_IN_Wr);
5077 g_hChildStd_IN_Wr = NULL;
5078 }
5079 }
5080
Bram Moolenaar2f7e1b82022-10-04 13:17:31 +01005081 len = term_replace_keycodes(ta_buf, ta_len, len);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005082
5083 /*
5084 * For pipes: echo the typed characters. For a pty this
5085 * does not seem to work.
5086 */
5087 for (i = ta_len; i < ta_len + len; ++i)
5088 {
5089 if (ta_buf[i] == '\n' || ta_buf[i] == '\b')
5090 msg_putchar(ta_buf[i]);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005091 else if (has_mbyte)
5092 {
5093 int l = (*mb_ptr2len)(ta_buf + i);
5094
5095 msg_outtrans_len(ta_buf + i, l);
5096 i += l - 1;
5097 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005098 else
5099 msg_outtrans_len(ta_buf + i, 1);
5100 }
5101 windgoto(msg_row, msg_col);
5102 out_flush();
5103
5104 ta_len += len;
5105
5106 /*
5107 * Write the characters to the child, unless EOF has been
5108 * typed for pipes. Write one character at a time, to
5109 * avoid losing too much typeahead. When writing buffer
5110 * lines, drop the typed characters (only check for
5111 * CTRL-C).
5112 */
5113 if (options & SHELL_WRITE)
5114 ta_len = 0;
5115 else if (g_hChildStd_IN_Wr != NULL)
5116 {
5117 WriteFile(g_hChildStd_IN_Wr, (char*)ta_buf,
5118 1, &len, NULL);
5119 // if we are typing in, we want to keep things reactive
5120 delay = 1;
5121 if (len > 0)
5122 {
5123 ta_len -= len;
5124 mch_memmove(ta_buf, ta_buf + len, ta_len);
5125 }
5126 }
5127 }
5128 }
5129 }
5130
5131 if (ta_len)
5132 ui_inchar_undo(ta_buf, ta_len);
5133
5134 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
5135 {
Bram Moolenaar2eba1822011-08-27 15:10:04 +02005136 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005137 break;
5138 }
5139
5140 ++noread_cnt;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02005141 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005142
Bram Moolenaar0f873732019-12-05 20:28:46 +01005143 // We start waiting for a very short time and then increase it, so
5144 // that we respond quickly when the process is quick, and don't
5145 // consume too much overhead when it's slow.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005146 if (delay < 50)
5147 delay += 10;
5148 }
5149
Bram Moolenaar0f873732019-12-05 20:28:46 +01005150 // Close the pipe
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005151 CloseHandle(g_hChildStd_OUT_Rd);
5152 if (g_hChildStd_IN_Wr != NULL)
5153 CloseHandle(g_hChildStd_IN_Wr);
5154
5155 WaitForSingleObject(pi.hProcess, INFINITE);
5156
Bram Moolenaar0f873732019-12-05 20:28:46 +01005157 // Get the command exit code
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005158 GetExitCodeProcess(pi.hProcess, &ret);
5159
5160 if (options & SHELL_READ)
5161 {
5162 if (ga.ga_len > 0)
5163 {
5164 append_ga_line(&ga);
Bram Moolenaar0f873732019-12-05 20:28:46 +01005165 // remember that the NL was missing
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005166 curbuf->b_no_eol_lnum = curwin->w_cursor.lnum;
5167 }
5168 else
5169 curbuf->b_no_eol_lnum = 0;
5170 ga_clear(&ga);
5171 }
5172
Bram Moolenaar0f873732019-12-05 20:28:46 +01005173 // Close the handles to the subprocess, so that it goes away
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005174 CloseHandle(pi.hThread);
5175 CloseHandle(pi.hProcess);
5176
5177 return ret;
5178}
5179
5180 static int
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005181mch_system_g(char *cmd, int options)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005182{
Bram Moolenaar0f873732019-12-05 20:28:46 +01005183 // if we can pipe and the shelltemp option is off
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005184 if (!p_stmp)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005185 return mch_system_piped(cmd, options);
5186 else
5187 return mch_system_classic(cmd, options);
5188}
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005189#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005190
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005191#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01005192 static int
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02005193mch_system_c(char *cmd, int options UNUSED)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01005194{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005195 int ret;
5196 WCHAR *wcmd;
Bram Moolenaar2efc44b2019-10-05 12:09:32 +02005197 char_u *buf;
5198 size_t len;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005199
Bram Moolenaar2efc44b2019-10-05 12:09:32 +02005200 // If the command starts and ends with double quotes, enclose the command
5201 // in parentheses.
5202 len = STRLEN(cmd);
5203 if (len >= 2 && cmd[0] == '"' && cmd[len - 1] == '"')
5204 {
5205 len += 3;
5206 buf = alloc(len);
5207 if (buf == NULL)
5208 return -1;
5209 vim_snprintf((char *)buf, len, "(%s)", cmd);
5210 wcmd = enc_to_utf16(buf, NULL);
5211 free(buf);
5212 }
5213 else
5214 wcmd = enc_to_utf16((char_u *)cmd, NULL);
5215
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005216 if (wcmd == NULL)
5217 return -1;
5218
5219 ret = _wsystem(wcmd);
5220 vim_free(wcmd);
5221 return ret;
Bram Moolenaar910cffb2013-12-11 17:58:35 +01005222}
Bram Moolenaar071d4272004-06-13 20:20:40 +00005223
5224#endif
5225
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005226 static int
5227mch_system(char *cmd, int options)
5228{
5229#ifdef VIMDLL
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02005230 if (gui.in_use || gui.starting)
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005231 return mch_system_g(cmd, options);
5232 else
5233 return mch_system_c(cmd, options);
5234#elif defined(FEAT_GUI_MSWIN)
5235 return mch_system_g(cmd, options);
5236#else
5237 return mch_system_c(cmd, options);
5238#endif
5239}
5240
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005241#if defined(FEAT_GUI) && defined(FEAT_TERMINAL)
5242/*
5243 * Use a terminal window to run a shell command in.
5244 */
5245 static int
5246mch_call_shell_terminal(
5247 char_u *cmd,
Bram Moolenaar0f873732019-12-05 20:28:46 +01005248 int options UNUSED) // SHELL_*, see vim.h
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005249{
5250 jobopt_T opt;
5251 char_u *newcmd = NULL;
5252 typval_T argvar[2];
5253 long_u cmdlen;
5254 int retval = -1;
5255 buf_T *buf;
Bram Moolenaarf9c38832018-06-19 19:59:20 +02005256 job_T *job;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005257 aco_save_T aco;
Bram Moolenaar0f873732019-12-05 20:28:46 +01005258 oparg_T oa; // operator arguments
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005259
Bram Moolenaar42f652f2018-03-19 21:44:37 +01005260 if (cmd == NULL)
5261 cmdlen = STRLEN(p_sh) + 1;
5262 else
5263 cmdlen = STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10;
Bram Moolenaar18a4ba22019-05-24 19:39:03 +02005264 newcmd = alloc(cmdlen);
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005265 if (newcmd == NULL)
5266 return 255;
Bram Moolenaar42f652f2018-03-19 21:44:37 +01005267 if (cmd == NULL)
5268 {
5269 STRCPY(newcmd, p_sh);
5270 ch_log(NULL, "starting terminal to run a shell");
5271 }
5272 else
5273 {
5274 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s", p_sh, p_shcf, cmd);
5275 ch_log(NULL, "starting terminal for system command '%s'", cmd);
5276 }
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005277
5278 init_job_options(&opt);
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005279
5280 argvar[0].v_type = VAR_STRING;
5281 argvar[0].vval.v_string = newcmd;
5282 argvar[1].v_type = VAR_UNKNOWN;
5283 buf = term_start(argvar, NULL, &opt, TERM_START_SYSTEM);
Bram Moolenaar81c3c89a2018-03-20 11:41:44 +01005284 if (buf == NULL)
Bram Moolenaar9029b912019-03-21 19:58:00 +01005285 {
5286 vim_free(newcmd);
Bram Moolenaar81c3c89a2018-03-20 11:41:44 +01005287 return 255;
Bram Moolenaar9029b912019-03-21 19:58:00 +01005288 }
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005289
Bram Moolenaarf9c38832018-06-19 19:59:20 +02005290 job = term_getjob(buf->b_term);
5291 ++job->jv_refcount;
5292
Bram Moolenaar0f873732019-12-05 20:28:46 +01005293 // Find a window to make "buf" curbuf.
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005294 aucmd_prepbuf(&aco, buf);
Bram Moolenaare76062c2022-11-28 18:51:43 +00005295 if (curbuf == buf)
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005296 {
Bram Moolenaare76062c2022-11-28 18:51:43 +00005297 // Only do this when a window was found for "buf".
5298 clear_oparg(&oa);
5299 while (term_use_loop())
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005300 {
Bram Moolenaare76062c2022-11-28 18:51:43 +00005301 if (oa.op_type == OP_NOP && oa.regname == NUL && !VIsual_active)
5302 {
5303 // If terminal_loop() returns OK we got a key that is handled
5304 // in Normal model. We don't do redrawing anyway.
5305 if (terminal_loop(TRUE) == OK)
5306 normal_cmd(&oa, TRUE);
5307 }
5308 else
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005309 normal_cmd(&oa, TRUE);
5310 }
Bram Moolenaare76062c2022-11-28 18:51:43 +00005311 retval = job->jv_exitval;
5312 ch_log(NULL, "system command finished");
5313
5314 job_unref(job);
5315
5316 // restore curwin/curbuf and a few other things
5317 aucmd_restbuf(&aco);
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005318 }
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005319
5320 wait_return(TRUE);
5321 do_buffer(DOBUF_WIPE, DOBUF_FIRST, FORWARD, buf->b_fnum, TRUE);
5322
5323 vim_free(newcmd);
5324 return retval;
5325}
5326#endif
5327
Bram Moolenaar071d4272004-06-13 20:20:40 +00005328/*
5329 * Either execute a command by calling the shell or start a new shell
5330 */
5331 int
5332mch_call_shell(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005333 char_u *cmd,
Bram Moolenaar0f873732019-12-05 20:28:46 +01005334 int options) // SHELL_*, see vim.h
Bram Moolenaar071d4272004-06-13 20:20:40 +00005335{
5336 int x = 0;
5337 int tmode = cur_tmode;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005338 WCHAR szShellTitle[512];
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02005339
Bram Moolenaar4c5678f2022-11-30 18:12:19 +00005340#ifdef FEAT_EVAL
Bram Moolenaarc9a9a0a2022-04-12 15:09:23 +01005341 ch_log(NULL, "executing shell command: %s", cmd);
5342#endif
Bram Moolenaar0f873732019-12-05 20:28:46 +01005343 // Change the title to reflect that we are in a subshell.
K.Takataeeec2542021-06-02 13:28:16 +02005344 if (GetConsoleTitleW(szShellTitle, ARRAY_LENGTH(szShellTitle) - 4) > 0)
Bram Moolenaar1df52d72014-10-15 22:50:10 +02005345 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005346 if (cmd == NULL)
5347 wcscat(szShellTitle, L" :sh");
5348 else
Bram Moolenaar1df52d72014-10-15 22:50:10 +02005349 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005350 WCHAR *wn = enc_to_utf16((char_u *)cmd, NULL);
Bram Moolenaar1df52d72014-10-15 22:50:10 +02005351
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005352 if (wn != NULL)
5353 {
5354 wcscat(szShellTitle, L" - !");
5355 if ((wcslen(szShellTitle) + wcslen(wn) <
K.Takataeeec2542021-06-02 13:28:16 +02005356 ARRAY_LENGTH(szShellTitle)))
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005357 wcscat(szShellTitle, wn);
5358 SetConsoleTitleW(szShellTitle);
5359 vim_free(wn);
Bram Moolenaar1df52d72014-10-15 22:50:10 +02005360 }
5361 }
5362 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005363
5364 out_flush();
5365
5366#ifdef MCH_WRITE_DUMP
5367 if (fdDump)
5368 {
5369 fprintf(fdDump, "mch_call_shell(\"%s\", %d)\n", cmd, options);
5370 fflush(fdDump);
5371 }
5372#endif
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005373#if defined(FEAT_GUI) && defined(FEAT_TERMINAL)
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02005374 // TODO: make the terminal window work with input or output redirected.
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005375 if (
5376# ifdef VIMDLL
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02005377 gui.in_use &&
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005378# endif
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02005379 vim_strchr(p_go, GO_TERMINAL) != NULL
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005380 && (options & (SHELL_FILTER|SHELL_DOOUT|SHELL_WRITE|SHELL_READ)) == 0)
5381 {
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02005382 char_u *cmdbase = cmd;
5383
Bram Moolenaar4d5c1262019-09-20 17:20:02 +02005384 if (cmdbase != NULL)
5385 // Skip a leading quote and (.
5386 while (*cmdbase == '"' || *cmdbase == '(')
5387 ++cmdbase;
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02005388
5389 // Check the command does not begin with "start "
Bram Moolenaar36e7a822019-11-13 21:49:24 +01005390 if (cmdbase == NULL || STRNICMP(cmdbase, "start", 5) != 0
5391 || !VIM_ISWHITE(cmdbase[5]))
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02005392 {
5393 // Use a terminal window to run the command in.
5394 x = mch_call_shell_terminal(cmd, options);
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02005395 resettitle();
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02005396 return x;
5397 }
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005398 }
5399#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005400
5401 /*
5402 * Catch all deadly signals while running the external command, because a
5403 * CTRL-C, Ctrl-Break or illegal instruction might otherwise kill us.
5404 */
5405 signal(SIGINT, SIG_IGN);
5406#if defined(__GNUC__) && !defined(__MINGW32__)
5407 signal(SIGKILL, SIG_IGN);
5408#else
5409 signal(SIGBREAK, SIG_IGN);
5410#endif
5411 signal(SIGILL, SIG_IGN);
5412 signal(SIGFPE, SIG_IGN);
5413 signal(SIGSEGV, SIG_IGN);
5414 signal(SIGTERM, SIG_IGN);
5415 signal(SIGABRT, SIG_IGN);
5416
5417 if (options & SHELL_COOKED)
Bram Moolenaar0f873732019-12-05 20:28:46 +01005418 settmode(TMODE_COOK); // set to normal mode
Bram Moolenaar071d4272004-06-13 20:20:40 +00005419
5420 if (cmd == NULL)
5421 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01005422 x = mch_system((char *)p_sh, options);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005423 }
5424 else
5425 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005426 // we use "command" or "cmd" to start the shell; slow but easy
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005427 char_u *newcmd = NULL;
5428 char_u *cmdbase = cmd;
5429 long_u cmdlen;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005430
Bram Moolenaar0f873732019-12-05 20:28:46 +01005431 // Skip a leading ", ( and "(.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005432 if (*cmdbase == '"' )
5433 ++cmdbase;
5434 if (*cmdbase == '(')
5435 ++cmdbase;
5436
Bram Moolenaar1c465442017-03-12 20:10:05 +01005437 if ((STRNICMP(cmdbase, "start", 5) == 0) && VIM_ISWHITE(cmdbase[5]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005438 {
5439 STARTUPINFO si;
5440 PROCESS_INFORMATION pi;
5441 DWORD flags = CREATE_NEW_CONSOLE;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01005442 INT n_show_cmd = SW_SHOWNORMAL;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005443 char_u *p;
5444
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01005445 ZeroMemory(&si, sizeof(si));
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005446 si.cb = sizeof(si);
5447 si.lpReserved = NULL;
5448 si.lpDesktop = NULL;
5449 si.lpTitle = NULL;
5450 si.dwFlags = 0;
5451 si.cbReserved2 = 0;
5452 si.lpReserved2 = NULL;
5453
5454 cmdbase = skipwhite(cmdbase + 5);
5455 if ((STRNICMP(cmdbase, "/min", 4) == 0)
Bram Moolenaar1c465442017-03-12 20:10:05 +01005456 && VIM_ISWHITE(cmdbase[4]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005457 {
5458 cmdbase = skipwhite(cmdbase + 4);
5459 si.dwFlags = STARTF_USESHOWWINDOW;
5460 si.wShowWindow = SW_SHOWMINNOACTIVE;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01005461 n_show_cmd = SW_SHOWMINNOACTIVE;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005462 }
5463 else if ((STRNICMP(cmdbase, "/b", 2) == 0)
Bram Moolenaar1c465442017-03-12 20:10:05 +01005464 && VIM_ISWHITE(cmdbase[2]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005465 {
5466 cmdbase = skipwhite(cmdbase + 2);
5467 flags = CREATE_NO_WINDOW;
5468 si.dwFlags = STARTF_USESTDHANDLES;
5469 si.hStdInput = CreateFile("\\\\.\\NUL", // File name
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005470 GENERIC_READ, // Access flags
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005471 0, // Share flags
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005472 NULL, // Security att.
5473 OPEN_EXISTING, // Open flags
5474 FILE_ATTRIBUTE_NORMAL, // File att.
5475 NULL); // Temp file
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005476 si.hStdOutput = si.hStdInput;
5477 si.hStdError = si.hStdInput;
5478 }
5479
Bram Moolenaar0f873732019-12-05 20:28:46 +01005480 // Remove a trailing ", ) and )" if they have a match
5481 // at the start of the command.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005482 if (cmdbase > cmd)
5483 {
5484 p = cmdbase + STRLEN(cmdbase);
5485 if (p > cmdbase && p[-1] == '"' && *cmd == '"')
5486 *--p = NUL;
5487 if (p > cmdbase && p[-1] == ')'
5488 && (*cmd =='(' || cmd[1] == '('))
5489 *--p = NUL;
5490 }
5491
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005492 newcmd = cmdbase;
5493 unescape_shellxquote(cmdbase, p_sxe);
5494
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005495 /*
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005496 * If creating new console, arguments are passed to the
5497 * 'cmd.exe' as-is. If it's not, arguments are not treated
5498 * correctly for current 'cmd.exe'. So unescape characters in
5499 * shellxescape except '|' for avoiding to be treated as
5500 * argument to them. Pass the arguments to sub-shell.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005501 */
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005502 if (flags != CREATE_NEW_CONSOLE)
5503 {
5504 char_u *subcmd;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01005505 char_u *cmd_shell = mch_getenv("COMSPEC");
5506
5507 if (cmd_shell == NULL || *cmd_shell == NUL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01005508 cmd_shell = (char_u *)default_shell();
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005509
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01005510 subcmd = vim_strsave_escaped_ext(cmdbase,
5511 (char_u *)"|", '^', FALSE);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005512 if (subcmd != NULL)
5513 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005514 // make "cmd.exe /c arguments"
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005515 cmdlen = STRLEN(cmd_shell) + STRLEN(subcmd) + 5;
Bram Moolenaar18a4ba22019-05-24 19:39:03 +02005516 newcmd = alloc(cmdlen);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005517 if (newcmd != NULL)
5518 vim_snprintf((char *)newcmd, cmdlen, "%s /c %s",
Bram Moolenaaree7d1002012-02-22 15:34:08 +01005519 cmd_shell, subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005520 else
5521 newcmd = cmdbase;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01005522 vim_free(subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005523 }
5524 }
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005525
5526 /*
5527 * Now, start the command as a process, so that it doesn't
5528 * inherit our handles which causes unpleasant dangling swap
5529 * files if we exit before the spawned process
5530 */
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005531 if (vim_create_process((char *)newcmd, FALSE, flags,
5532 &si, &pi, NULL, NULL))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005533 x = 0;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01005534 else if (vim_shell_execute((char *)newcmd, n_show_cmd)
5535 > (HINSTANCE)32)
5536 x = 0;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005537 else
5538 {
5539 x = -1;
Bram Moolenaar4f974752019-02-17 17:44:42 +01005540#ifdef FEAT_GUI_MSWIN
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005541# ifdef VIMDLL
5542 if (gui.in_use)
5543# endif
Bram Moolenaarac78dd42022-01-02 19:25:26 +00005544 emsg(_(e_command_not_found));
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005545#endif
5546 }
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005547
5548 if (newcmd != cmdbase)
5549 vim_free(newcmd);
5550
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01005551 if (si.dwFlags == STARTF_USESTDHANDLES && si.hStdInput != NULL)
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005552 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005553 // Close the handle to \\.\NUL created above.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005554 CloseHandle(si.hStdInput);
5555 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01005556 // Close the handles to the subprocess, so that it goes away
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005557 CloseHandle(pi.hThread);
5558 CloseHandle(pi.hProcess);
5559 }
5560 else
5561 {
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005562 cmdlen =
Bram Moolenaar4f974752019-02-17 17:44:42 +01005563#ifdef FEAT_GUI_MSWIN
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02005564 ((gui.in_use || gui.starting) ?
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005565 (!s_dont_use_vimrun && p_stmp ?
5566 STRLEN(vimrun_path) : STRLEN(p_sh) + STRLEN(p_shcf))
5567 : 0) +
Bram Moolenaar071d4272004-06-13 20:20:40 +00005568#endif
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005569 STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10;
Bram Moolenaar0fde2902008-03-16 13:54:13 +00005570
Bram Moolenaar18a4ba22019-05-24 19:39:03 +02005571 newcmd = alloc(cmdlen);
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005572 if (newcmd != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005573 {
Bram Moolenaar4f974752019-02-17 17:44:42 +01005574#if defined(FEAT_GUI_MSWIN)
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005575 if (
5576# ifdef VIMDLL
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02005577 (gui.in_use || gui.starting) &&
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005578# endif
5579 need_vimrun_warning)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005580 {
Bram Moolenaar63e43442016-11-19 17:28:44 +01005581 char *msg = _("VIMRUN.EXE not found in your $PATH.\n"
5582 "External commands will not pause after completion.\n"
5583 "See :help win32-vimrun for more information.");
5584 char *title = _("Vim Warning");
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005585 WCHAR *wmsg = enc_to_utf16((char_u *)msg, NULL);
5586 WCHAR *wtitle = enc_to_utf16((char_u *)title, NULL);
Bram Moolenaar63e43442016-11-19 17:28:44 +01005587
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005588 if (wmsg != NULL && wtitle != NULL)
5589 MessageBoxW(NULL, wmsg, wtitle, MB_ICONWARNING);
5590 vim_free(wmsg);
5591 vim_free(wtitle);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005592 need_vimrun_warning = FALSE;
5593 }
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005594 if (
5595# ifdef VIMDLL
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02005596 (gui.in_use || gui.starting) &&
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005597# endif
5598 !s_dont_use_vimrun && p_stmp)
Bram Moolenaarfcc4d922019-05-24 13:32:36 +02005599 // Use vimrun to execute the command. It opens a console
5600 // window, which can be closed without killing Vim.
Bram Moolenaarcc448b32010-07-14 16:52:17 +02005601 vim_snprintf((char *)newcmd, cmdlen, "%s%s%s %s %s",
Bram Moolenaar071d4272004-06-13 20:20:40 +00005602 vimrun_path,
5603 (msg_silent != 0 || (options & SHELL_DOOUT))
5604 ? "-s " : "",
5605 p_sh, p_shcf, cmd);
Bram Moolenaarfcc4d922019-05-24 13:32:36 +02005606 else if (
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005607# ifdef VIMDLL
Bram Moolenaarfcc4d922019-05-24 13:32:36 +02005608 (gui.in_use || gui.starting) &&
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005609# endif
Bram Moolenaar0e6bfb92019-07-31 20:53:56 +02005610 s_dont_use_vimrun && STRCMP(p_shcf, "/c") == 0)
Bram Moolenaarfcc4d922019-05-24 13:32:36 +02005611 // workaround for the case that "vimrun" does not exist
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005612 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s %s %s",
5613 p_sh, p_shcf, p_sh, p_shcf, cmd);
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005614 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00005615#endif
Bram Moolenaarcc448b32010-07-14 16:52:17 +02005616 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s",
Bram Moolenaar0fde2902008-03-16 13:54:13 +00005617 p_sh, p_shcf, cmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005618 x = mch_system((char *)newcmd, options);
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005619 vim_free(newcmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005620 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005621 }
5622 }
5623
5624 if (tmode == TMODE_RAW)
Bram Moolenaar3b1f18f2020-05-16 23:15:08 +02005625 {
5626 // The shell may have messed with the mode, always set it.
5627 cur_tmode = TMODE_UNKNOWN;
Bram Moolenaar0f873732019-12-05 20:28:46 +01005628 settmode(TMODE_RAW); // set to raw mode
Bram Moolenaar3b1f18f2020-05-16 23:15:08 +02005629 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005630
Bram Moolenaar0f873732019-12-05 20:28:46 +01005631 // Print the return value, unless "vimrun" was used.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005632 if (x != 0 && !(options & SHELL_SILENT) && !emsg_silent
Bram Moolenaar4f974752019-02-17 17:44:42 +01005633#if defined(FEAT_GUI_MSWIN)
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02005634 && ((gui.in_use || gui.starting) ?
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005635 ((options & SHELL_DOOUT) || s_dont_use_vimrun || !p_stmp) : 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005636#endif
5637 )
5638 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005639 smsg(_("shell returned %d"), x);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005640 msg_putchar('\n');
5641 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005642 resettitle();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005643
5644 signal(SIGINT, SIG_DFL);
5645#if defined(__GNUC__) && !defined(__MINGW32__)
5646 signal(SIGKILL, SIG_DFL);
5647#else
5648 signal(SIGBREAK, SIG_DFL);
5649#endif
5650 signal(SIGILL, SIG_DFL);
5651 signal(SIGFPE, SIG_DFL);
5652 signal(SIGSEGV, SIG_DFL);
5653 signal(SIGTERM, SIG_DFL);
5654 signal(SIGABRT, SIG_DFL);
5655
5656 return x;
5657}
5658
Bram Moolenaar509ce2a2016-03-11 22:52:15 +01005659#if defined(FEAT_JOB_CHANNEL) || defined(PROTO)
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005660 static HANDLE
5661job_io_file_open(
Bram Moolenaar972c3b82017-01-12 21:44:49 +01005662 char_u *fname,
5663 DWORD dwDesiredAccess,
5664 DWORD dwShareMode,
5665 LPSECURITY_ATTRIBUTES lpSecurityAttributes,
5666 DWORD dwCreationDisposition,
5667 DWORD dwFlagsAndAttributes)
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005668{
5669 HANDLE h;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005670 WCHAR *wn;
Bram Moolenaara12a1612019-01-24 16:39:02 +01005671
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005672 wn = enc_to_utf16(fname, NULL);
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005673 if (wn == NULL)
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005674 return INVALID_HANDLE_VALUE;
5675
5676 h = CreateFileW(wn, dwDesiredAccess, dwShareMode,
5677 lpSecurityAttributes, dwCreationDisposition,
5678 dwFlagsAndAttributes, NULL);
5679 vim_free(wn);
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005680 return h;
5681}
5682
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005683/*
5684 * Turn the dictionary "env" into a NUL separated list that can be used as the
5685 * environment argument of vim_create_process().
5686 */
Bram Moolenaarba6febd2017-10-30 21:56:23 +01005687 void
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005688win32_build_env(dict_T *env, garray_T *gap, int is_terminal)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005689{
5690 hashitem_T *hi;
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005691 long_u todo = env != NULL ? env->dv_hashtab.ht_used : 0;
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005692 LPVOID base = GetEnvironmentStringsW();
5693
Bram Moolenaar0f873732019-12-05 20:28:46 +01005694 // for last \0
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005695 if (ga_grow(gap, 1) == FAIL)
5696 return;
5697
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005698 if (env != NULL)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005699 {
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005700 for (hi = env->dv_hashtab.ht_array; todo > 0; ++hi)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005701 {
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005702 if (!HASHITEM_EMPTY(hi))
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005703 {
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005704 typval_T *item = &dict_lookup(hi)->di_tv;
5705 WCHAR *wkey = enc_to_utf16((char_u *)hi->hi_key, NULL);
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005706 WCHAR *wval = enc_to_utf16(tv_get_string(item), NULL);
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005707 --todo;
5708 if (wkey != NULL && wval != NULL)
5709 {
5710 size_t n;
5711 size_t lkey = wcslen(wkey);
5712 size_t lval = wcslen(wval);
Bram Moolenaar60104f12017-08-14 23:25:04 +02005713
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005714 if (ga_grow(gap, (int)(lkey + lval + 2)) != OK)
5715 continue;
5716 for (n = 0; n < lkey; n++)
5717 *((WCHAR*)gap->ga_data + gap->ga_len++) = wkey[n];
5718 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'=';
5719 for (n = 0; n < lval; n++)
5720 *((WCHAR*)gap->ga_data + gap->ga_len++) = wval[n];
5721 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5722 }
Bram Moolenaarbdace832019-03-02 10:13:42 +01005723 vim_free(wkey);
5724 vim_free(wval);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005725 }
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005726 }
5727 }
5728
Bram Moolenaar355757a2020-02-10 22:06:32 +01005729 if (base)
5730 {
5731 WCHAR *p = (WCHAR*) base;
5732
5733 // for last \0
5734 if (ga_grow(gap, 1) == FAIL)
5735 return;
5736
5737 while (*p != 0 || *(p + 1) != 0)
5738 {
5739 if (ga_grow(gap, 1) == OK)
5740 *((WCHAR*)gap->ga_data + gap->ga_len++) = *p;
5741 p++;
5742 }
5743 FreeEnvironmentStrings(base);
5744 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5745 }
5746
Bram Moolenaar493359e2018-06-12 20:25:52 +02005747# if defined(FEAT_CLIENTSERVER) || defined(FEAT_TERMINAL)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005748 {
Bram Moolenaar493359e2018-06-12 20:25:52 +02005749# ifdef FEAT_CLIENTSERVER
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005750 char_u *servername = get_vim_var_str(VV_SEND_SERVER);
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005751 size_t servername_len = STRLEN(servername);
Bram Moolenaar493359e2018-06-12 20:25:52 +02005752# endif
5753# ifdef FEAT_TERMINAL
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005754 char_u *version = get_vim_var_str(VV_VERSION);
5755 size_t version_len = STRLEN(version);
Bram Moolenaar493359e2018-06-12 20:25:52 +02005756# endif
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005757 // size of "VIM_SERVERNAME=" and value,
5758 // plus "VIM_TERMINAL=" and value,
5759 // plus two terminating NULs
5760 size_t n = 0
Bram Moolenaar493359e2018-06-12 20:25:52 +02005761# ifdef FEAT_CLIENTSERVER
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005762 + 15 + servername_len
Bram Moolenaar493359e2018-06-12 20:25:52 +02005763# endif
5764# ifdef FEAT_TERMINAL
5765 + 13 + version_len + 2
5766# endif
5767 ;
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005768
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005769 if (ga_grow(gap, (int)n) == OK)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005770 {
Bram Moolenaar493359e2018-06-12 20:25:52 +02005771# ifdef FEAT_CLIENTSERVER
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005772 for (n = 0; n < 15; n++)
5773 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5774 (WCHAR)"VIM_SERVERNAME="[n];
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005775 for (n = 0; n < servername_len; n++)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005776 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5777 (WCHAR)servername[n];
5778 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
Bram Moolenaar493359e2018-06-12 20:25:52 +02005779# endif
5780# ifdef FEAT_TERMINAL
5781 if (is_terminal)
5782 {
5783 for (n = 0; n < 13; n++)
5784 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5785 (WCHAR)"VIM_TERMINAL="[n];
5786 for (n = 0; n < version_len; n++)
5787 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5788 (WCHAR)version[n];
5789 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5790 }
5791# endif
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005792 }
5793 }
Bram Moolenaar79c6b512018-06-12 21:11:12 +02005794# endif
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005795}
5796
Bram Moolenaarb091f302019-01-19 14:37:00 +01005797/*
5798 * Create a pair of pipes.
5799 * Return TRUE for success, FALSE for failure.
5800 */
5801 static BOOL
5802create_pipe_pair(HANDLE handles[2])
5803{
5804 static LONG s;
5805 char name[64];
5806 SECURITY_ATTRIBUTES sa;
5807
5808 sprintf(name, "\\\\?\\pipe\\vim-%08lx-%08lx",
5809 GetCurrentProcessId(),
5810 InterlockedIncrement(&s));
5811
5812 // Create named pipe. Max size of named pipe is 65535.
5813 handles[1] = CreateNamedPipe(
5814 name,
5815 PIPE_ACCESS_OUTBOUND | FILE_FLAG_OVERLAPPED,
5816 PIPE_TYPE_BYTE | PIPE_NOWAIT,
Bram Moolenaar24058382019-01-24 23:11:49 +01005817 1, MAX_NAMED_PIPE_SIZE, 0, 0, NULL);
Bram Moolenaarb091f302019-01-19 14:37:00 +01005818
5819 if (handles[1] == INVALID_HANDLE_VALUE)
5820 return FALSE;
5821
5822 sa.nLength = sizeof(sa);
5823 sa.bInheritHandle = TRUE;
5824 sa.lpSecurityDescriptor = NULL;
5825
5826 handles[0] = CreateFile(name,
5827 FILE_GENERIC_READ,
5828 FILE_SHARE_READ, &sa,
5829 OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
5830
5831 if (handles[0] == INVALID_HANDLE_VALUE)
5832 {
Bram Moolenaar6982f422019-02-16 16:48:01 +01005833 CloseHandle(handles[1]);
Bram Moolenaarb091f302019-01-19 14:37:00 +01005834 return FALSE;
5835 }
5836
5837 return TRUE;
5838}
5839
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005840 void
Bram Moolenaar5a1feb82017-07-22 18:04:08 +02005841mch_job_start(char *cmd, job_T *job, jobopt_T *options)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005842{
5843 STARTUPINFO si;
5844 PROCESS_INFORMATION pi;
Bram Moolenaar14207f42016-10-27 21:13:10 +02005845 HANDLE jo;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005846 SECURITY_ATTRIBUTES saAttr;
5847 channel_T *channel = NULL;
Bram Moolenaard8070362016-02-15 21:56:54 +01005848 HANDLE ifd[2];
5849 HANDLE ofd[2];
5850 HANDLE efd[2];
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005851 garray_T ga;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005852
5853 int use_null_for_in = options->jo_io[PART_IN] == JIO_NULL;
5854 int use_null_for_out = options->jo_io[PART_OUT] == JIO_NULL;
5855 int use_null_for_err = options->jo_io[PART_ERR] == JIO_NULL;
5856 int use_file_for_in = options->jo_io[PART_IN] == JIO_FILE;
5857 int use_file_for_out = options->jo_io[PART_OUT] == JIO_FILE;
5858 int use_file_for_err = options->jo_io[PART_ERR] == JIO_FILE;
5859 int use_out_for_err = options->jo_io[PART_ERR] == JIO_OUT;
5860
5861 if (use_out_for_err && use_null_for_out)
5862 use_null_for_err = TRUE;
Bram Moolenaard8070362016-02-15 21:56:54 +01005863
5864 ifd[0] = INVALID_HANDLE_VALUE;
5865 ifd[1] = INVALID_HANDLE_VALUE;
5866 ofd[0] = INVALID_HANDLE_VALUE;
5867 ofd[1] = INVALID_HANDLE_VALUE;
5868 efd[0] = INVALID_HANDLE_VALUE;
5869 efd[1] = INVALID_HANDLE_VALUE;
Bram Moolenaar04935fb2022-01-08 16:19:22 +00005870 ga_init2(&ga, sizeof(wchar_t), 500);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005871
Bram Moolenaar14207f42016-10-27 21:13:10 +02005872 jo = CreateJobObject(NULL, NULL);
5873 if (jo == NULL)
5874 {
5875 job->jv_status = JOB_FAILED;
5876 goto failed;
5877 }
5878
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005879 if (options->jo_env != NULL)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005880 win32_build_env(options->jo_env, &ga, FALSE);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005881
Bram Moolenaar76467df2016-02-12 19:30:26 +01005882 ZeroMemory(&pi, sizeof(pi));
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005883 ZeroMemory(&si, sizeof(si));
5884 si.cb = sizeof(si);
Bram Moolenaard8070362016-02-15 21:56:54 +01005885 si.dwFlags |= STARTF_USESHOWWINDOW;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005886 si.wShowWindow = SW_HIDE;
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005887
Bram Moolenaard8070362016-02-15 21:56:54 +01005888 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
5889 saAttr.bInheritHandle = TRUE;
5890 saAttr.lpSecurityDescriptor = NULL;
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005891
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005892 if (use_file_for_in)
5893 {
5894 char_u *fname = options->jo_io_name[PART_IN];
5895
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005896 ifd[0] = job_io_file_open(fname, GENERIC_READ,
5897 FILE_SHARE_READ | FILE_SHARE_WRITE,
5898 &saAttr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL);
5899 if (ifd[0] == INVALID_HANDLE_VALUE)
Bram Moolenaar94d01912016-03-08 13:48:51 +01005900 {
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00005901 semsg(_(e_cant_open_file_str), fname);
Bram Moolenaar94d01912016-03-08 13:48:51 +01005902 goto failed;
5903 }
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005904 }
Bram Moolenaarb091f302019-01-19 14:37:00 +01005905 else if (!use_null_for_in
5906 && (!create_pipe_pair(ifd)
5907 || !SetHandleInformation(ifd[1], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005908 goto failed;
5909
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005910 if (use_file_for_out)
5911 {
5912 char_u *fname = options->jo_io_name[PART_OUT];
5913
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005914 ofd[1] = job_io_file_open(fname, GENERIC_WRITE,
5915 FILE_SHARE_READ | FILE_SHARE_WRITE,
5916 &saAttr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL);
5917 if (ofd[1] == INVALID_HANDLE_VALUE)
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005918 {
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00005919 semsg(_(e_cant_open_file_str), fname);
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005920 goto failed;
5921 }
5922 }
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005923 else if (!use_null_for_out &&
5924 (!CreatePipe(&ofd[0], &ofd[1], &saAttr, 0)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005925 || !SetHandleInformation(ofd[0], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005926 goto failed;
5927
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005928 if (use_file_for_err)
5929 {
5930 char_u *fname = options->jo_io_name[PART_ERR];
5931
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005932 efd[1] = job_io_file_open(fname, GENERIC_WRITE,
5933 FILE_SHARE_READ | FILE_SHARE_WRITE,
5934 &saAttr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL);
5935 if (efd[1] == INVALID_HANDLE_VALUE)
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005936 {
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00005937 semsg(_(e_cant_open_file_str), fname);
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005938 goto failed;
5939 }
5940 }
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005941 else if (!use_out_for_err && !use_null_for_err &&
5942 (!CreatePipe(&efd[0], &efd[1], &saAttr, 0)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005943 || !SetHandleInformation(efd[0], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaard8070362016-02-15 21:56:54 +01005944 goto failed;
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005945
Bram Moolenaard8070362016-02-15 21:56:54 +01005946 si.dwFlags |= STARTF_USESTDHANDLES;
5947 si.hStdInput = ifd[0];
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005948 si.hStdOutput = ofd[1];
5949 si.hStdError = use_out_for_err ? ofd[1] : efd[1];
5950
5951 if (!use_null_for_in || !use_null_for_out || !use_null_for_err)
5952 {
Bram Moolenaarde279892016-03-11 22:19:44 +01005953 if (options->jo_set & JO_CHANNEL)
5954 {
5955 channel = options->jo_channel;
5956 if (channel != NULL)
5957 ++channel->ch_refcount;
5958 }
5959 else
5960 channel = add_channel();
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005961 if (channel == NULL)
5962 goto failed;
5963 }
Bram Moolenaard8070362016-02-15 21:56:54 +01005964
5965 if (!vim_create_process(cmd, TRUE,
Bram Moolenaar14207f42016-10-27 21:13:10 +02005966 CREATE_SUSPENDED |
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005967 CREATE_DEFAULT_ERROR_MODE |
5968 CREATE_NEW_PROCESS_GROUP |
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005969 CREATE_UNICODE_ENVIRONMENT |
Bram Moolenaar76467df2016-02-12 19:30:26 +01005970 CREATE_NEW_CONSOLE,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005971 &si, &pi,
5972 ga.ga_data,
5973 (char *)options->jo_cwd))
Bram Moolenaar76467df2016-02-12 19:30:26 +01005974 {
Bram Moolenaar14207f42016-10-27 21:13:10 +02005975 CloseHandle(jo);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005976 job->jv_status = JOB_FAILED;
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005977 goto failed;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005978 }
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005979
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005980 ga_clear(&ga);
5981
Bram Moolenaar14207f42016-10-27 21:13:10 +02005982 if (!AssignProcessToJobObject(jo, pi.hProcess))
5983 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005984 // if failing, switch the way to terminate
5985 // process with TerminateProcess.
Bram Moolenaar14207f42016-10-27 21:13:10 +02005986 CloseHandle(jo);
5987 jo = NULL;
5988 }
5989 ResumeThread(pi.hThread);
Bram Moolenaar75578a32016-03-10 16:33:31 +01005990 CloseHandle(pi.hThread);
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005991 job->jv_proc_info = pi;
Bram Moolenaar14207f42016-10-27 21:13:10 +02005992 job->jv_job_object = jo;
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005993 job->jv_status = JOB_STARTED;
5994
Bram Moolenaar641ad6c2016-09-01 18:32:11 +02005995 CloseHandle(ifd[0]);
5996 CloseHandle(ofd[1]);
5997 if (!use_out_for_err && !use_null_for_err)
Bram Moolenaarc25558b2016-03-03 21:02:23 +01005998 CloseHandle(efd[1]);
Bram Moolenaard8070362016-02-15 21:56:54 +01005999
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01006000 job->jv_channel = channel;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01006001 if (channel != NULL)
6002 {
6003 channel_set_pipes(channel,
6004 use_file_for_in || use_null_for_in
6005 ? INVALID_FD : (sock_T)ifd[1],
6006 use_file_for_out || use_null_for_out
6007 ? INVALID_FD : (sock_T)ofd[0],
6008 use_out_for_err || use_file_for_err || use_null_for_err
6009 ? INVALID_FD : (sock_T)efd[0]);
6010 channel_set_job(channel, job, options);
Bram Moolenaard5d3d302016-03-09 20:54:51 +01006011 }
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01006012 return;
6013
6014failed:
Bram Moolenaard8070362016-02-15 21:56:54 +01006015 CloseHandle(ifd[0]);
6016 CloseHandle(ofd[0]);
6017 CloseHandle(efd[0]);
6018 CloseHandle(ifd[1]);
6019 CloseHandle(ofd[1]);
6020 CloseHandle(efd[1]);
Bram Moolenaarde279892016-03-11 22:19:44 +01006021 channel_unref(channel);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02006022 ga_clear(&ga);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01006023}
6024
6025 char *
6026mch_job_status(job_T *job)
6027{
6028 DWORD dwExitCode = 0;
6029
Bram Moolenaar76467df2016-02-12 19:30:26 +01006030 if (!GetExitCodeProcess(job->jv_proc_info.hProcess, &dwExitCode)
6031 || dwExitCode != STILL_ACTIVE)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01006032 {
Bram Moolenaareab089d2016-02-21 19:32:02 +01006033 job->jv_exitval = (int)dwExitCode;
Bram Moolenaar7df915d2016-11-17 17:25:32 +01006034 if (job->jv_status < JOB_ENDED)
Bram Moolenaar97792de2016-10-15 18:36:49 +02006035 {
6036 ch_log(job->jv_channel, "Job ended");
6037 job->jv_status = JOB_ENDED;
6038 }
Bram Moolenaar942d6b22016-02-07 19:57:16 +01006039 return "dead";
6040 }
6041 return "run";
6042}
6043
Bram Moolenaar97792de2016-10-15 18:36:49 +02006044 job_T *
6045mch_detect_ended_job(job_T *job_list)
6046{
6047 HANDLE jobHandles[MAXIMUM_WAIT_OBJECTS];
6048 job_T *jobArray[MAXIMUM_WAIT_OBJECTS];
6049 job_T *job = job_list;
6050
6051 while (job != NULL)
6052 {
6053 DWORD n;
6054 DWORD result;
6055
6056 for (n = 0; n < MAXIMUM_WAIT_OBJECTS
6057 && job != NULL; job = job->jv_next)
6058 {
6059 if (job->jv_status == JOB_STARTED)
6060 {
6061 jobHandles[n] = job->jv_proc_info.hProcess;
6062 jobArray[n] = job;
6063 ++n;
6064 }
6065 }
6066 if (n == 0)
6067 continue;
6068 result = WaitForMultipleObjects(n, jobHandles, FALSE, 0);
6069 if (result >= WAIT_OBJECT_0 && result < WAIT_OBJECT_0 + n)
6070 {
6071 job_T *wait_job = jobArray[result - WAIT_OBJECT_0];
6072
6073 if (STRCMP(mch_job_status(wait_job), "dead") == 0)
6074 return wait_job;
6075 }
6076 }
6077 return NULL;
6078}
6079
Bram Moolenaarfb630902016-10-29 14:55:00 +02006080 static BOOL
6081terminate_all(HANDLE process, int code)
6082{
6083 PROCESSENTRY32 pe;
6084 HANDLE h = INVALID_HANDLE_VALUE;
6085 DWORD pid = GetProcessId(process);
6086
6087 if (pid != 0)
6088 {
6089 h = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
6090 if (h != INVALID_HANDLE_VALUE)
6091 {
6092 pe.dwSize = sizeof(PROCESSENTRY32);
6093 if (!Process32First(h, &pe))
6094 goto theend;
6095
6096 do
6097 {
6098 if (pe.th32ParentProcessID == pid)
6099 {
6100 HANDLE ph = OpenProcess(
6101 PROCESS_ALL_ACCESS, FALSE, pe.th32ProcessID);
6102 if (ph != NULL)
6103 {
6104 terminate_all(ph, code);
6105 CloseHandle(ph);
6106 }
6107 }
6108 } while (Process32Next(h, &pe));
6109
6110 CloseHandle(h);
6111 }
6112 }
6113
6114theend:
6115 return TerminateProcess(process, code);
6116}
6117
6118/*
6119 * Send a (deadly) signal to "job".
6120 * Return FAIL if it didn't work.
6121 */
Bram Moolenaar942d6b22016-02-07 19:57:16 +01006122 int
Bram Moolenaar2d33e902017-08-11 16:31:54 +02006123mch_signal_job(job_T *job, char_u *how)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01006124{
Bram Moolenaar923d9262016-02-25 20:56:01 +01006125 int ret;
Bram Moolenaar76467df2016-02-12 19:30:26 +01006126
Bram Moolenaar923d9262016-02-25 20:56:01 +01006127 if (STRCMP(how, "term") == 0 || STRCMP(how, "kill") == 0 || *how == NUL)
Bram Moolenaar76467df2016-02-12 19:30:26 +01006128 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006129 // deadly signal
Bram Moolenaar14207f42016-10-27 21:13:10 +02006130 if (job->jv_job_object != NULL)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006131 {
6132 if (job->jv_channel != NULL && job->jv_channel->ch_anonymous_pipe)
6133 job->jv_channel->ch_killing = TRUE;
K.Takata135e1522022-01-29 15:27:58 +00006134 return TerminateJobObject(job->jv_job_object, (UINT)-1) ? OK : FAIL;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006135 }
Bram Moolenaarb3e195c2020-02-10 21:32:19 +01006136 return terminate_all(job->jv_proc_info.hProcess, -1) ? OK : FAIL;
Bram Moolenaar76467df2016-02-12 19:30:26 +01006137 }
6138
6139 if (!AttachConsole(job->jv_proc_info.dwProcessId))
6140 return FAIL;
6141 ret = GenerateConsoleCtrlEvent(
Bram Moolenaar923d9262016-02-25 20:56:01 +01006142 STRCMP(how, "int") == 0 ? CTRL_C_EVENT : CTRL_BREAK_EVENT,
6143 job->jv_proc_info.dwProcessId)
6144 ? OK : FAIL;
Bram Moolenaar76467df2016-02-12 19:30:26 +01006145 FreeConsole();
6146 return ret;
6147}
6148
6149/*
6150 * Clear the data related to "job".
6151 */
6152 void
6153mch_clear_job(job_T *job)
6154{
6155 if (job->jv_status != JOB_FAILED)
6156 {
Bram Moolenaar14207f42016-10-27 21:13:10 +02006157 if (job->jv_job_object != NULL)
6158 CloseHandle(job->jv_job_object);
Bram Moolenaar76467df2016-02-12 19:30:26 +01006159 CloseHandle(job->jv_proc_info.hProcess);
6160 }
Bram Moolenaar942d6b22016-02-07 19:57:16 +01006161}
6162#endif
6163
Bram Moolenaar071d4272004-06-13 20:20:40 +00006164
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006165#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006166
6167/*
6168 * Start termcap mode
6169 */
6170 static void
6171termcap_mode_start(void)
6172{
6173 DWORD cmodein;
6174
6175 if (g_fTermcapMode)
6176 return;
6177
Christopher Plewright1140b512022-11-12 18:46:05 +00006178 // VTP uses alternate screen buffer.
6179 // Switch to a new alternate screen buffer.
Christopher Plewrightc8b126d2022-12-22 13:45:23 +00006180 // But, not if running in a nested terminal
6181 if (use_alternate_screen_buffer)
Bram Moolenaar81ccbf12020-04-15 21:05:30 +02006182 vtp_printf("\033[?1049h");
6183
Bram Moolenaar071d4272004-06-13 20:20:40 +00006184 SaveConsoleBuffer(&g_cbNonTermcap);
6185
6186 if (g_cbTermcap.IsValid)
6187 {
6188 /*
6189 * We've been in termcap mode before. Restore certain screen
6190 * characteristics, including the buffer size and the window
6191 * size. Since we will be redrawing the screen, we don't need
6192 * to restore the actual contents of the buffer.
6193 */
6194 RestoreConsoleBuffer(&g_cbTermcap, FALSE);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006195 reset_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00006196 SetConsoleWindowInfo(g_hConOut, TRUE, &g_cbTermcap.Info.srWindow);
6197 Rows = g_cbTermcap.Info.dwSize.Y;
6198 Columns = g_cbTermcap.Info.dwSize.X;
6199 }
6200 else
6201 {
6202 /*
6203 * This is our first time entering termcap mode. Clear the console
6204 * screen buffer, and resize the buffer to match the current window
6205 * size. We will use this as the size of our editing environment.
6206 */
6207 ClearConsoleBuffer(g_attrCurrent);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006208 set_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00006209 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
6210 }
6211
Bram Moolenaar071d4272004-06-13 20:20:40 +00006212 resettitle();
Bram Moolenaar071d4272004-06-13 20:20:40 +00006213
6214 GetConsoleMode(g_hConIn, &cmodein);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006215 if (g_fMouseActive)
Wez Furlong6ef5ab52021-05-30 19:29:41 +02006216 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006217 cmodein |= ENABLE_MOUSE_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02006218 cmodein &= ~ENABLE_QUICK_EDIT_MODE;
6219 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006220 else
Wez Furlong6ef5ab52021-05-30 19:29:41 +02006221 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006222 cmodein &= ~ENABLE_MOUSE_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02006223 cmodein |= g_cmodein & ENABLE_QUICK_EDIT_MODE;
6224 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006225 cmodein |= ENABLE_WINDOW_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02006226 SetConsoleMode(g_hConIn, cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006227
6228 redraw_later_clear();
6229 g_fTermcapMode = TRUE;
6230}
6231
6232
6233/*
6234 * End termcap mode
6235 */
6236 static void
6237termcap_mode_end(void)
6238{
6239 DWORD cmodein;
6240 ConsoleBuffer *cb;
6241 COORD coord;
6242 DWORD dwDummy;
6243
6244 if (!g_fTermcapMode)
6245 return;
6246
6247 SaveConsoleBuffer(&g_cbTermcap);
6248
6249 GetConsoleMode(g_hConIn, &cmodein);
6250 cmodein &= ~(ENABLE_MOUSE_INPUT | ENABLE_WINDOW_INPUT);
Wez Furlong6ef5ab52021-05-30 19:29:41 +02006251 cmodein |= g_cmodein & ENABLE_QUICK_EDIT_MODE;
6252 SetConsoleMode(g_hConIn, cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006253
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006254# ifdef FEAT_RESTORE_ORIG_SCREEN
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01006255 cb = exiting ? &g_cbOrig : &g_cbNonTermcap;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006256# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00006257 cb = &g_cbNonTermcap;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006258# endif
Bram Moolenaar81ccbf12020-04-15 21:05:30 +02006259 RestoreConsoleBuffer(cb, p_rs);
Bram Moolenaardf543822020-01-30 11:53:59 +01006260 restore_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00006261
Christopher Plewright1140b512022-11-12 18:46:05 +00006262 // VTP uses alternate screen buffer.
6263 // Switch back to main screen buffer.
Christopher Plewrightc8b126d2022-12-22 13:45:23 +00006264 if (exiting && use_alternate_screen_buffer)
Christopher Plewright1140b512022-11-12 18:46:05 +00006265 vtp_printf("\033[?1049l");
6266
6267 if (!USE_WT && (p_rs || exiting))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006268 {
6269 /*
6270 * Clear anything that happens to be on the current line.
6271 */
6272 coord.X = 0;
6273 coord.Y = (SHORT) (p_rs ? cb->Info.dwCursorPosition.Y : (Rows - 1));
Christopher Plewright1140b512022-11-12 18:46:05 +00006274 if (!vtp_working)
6275 FillConsoleOutputCharacter(g_hConOut, ' ',
6276 cb->Info.dwSize.X, coord, &dwDummy);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006277 /*
6278 * The following is just for aesthetics. If we are exiting without
6279 * restoring the screen, then we want to have a prompt string
6280 * appear at the bottom line. However, the command interpreter
6281 * seems to always advance the cursor one line before displaying
6282 * the prompt string, which causes the screen to scroll. To
6283 * counter this, move the cursor up one line before exiting.
6284 */
6285 if (exiting && !p_rs)
6286 coord.Y--;
6287 /*
6288 * Position the cursor at the leftmost column of the desired row.
6289 */
Bram Moolenaar81ccbf12020-04-15 21:05:30 +02006290 SetConsoleCursorPosition(g_hConOut, coord);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006291 }
Christopher Plewright1140b512022-11-12 18:46:05 +00006292 SetConsoleCursorInfo(g_hConOut, &g_cci);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006293 g_fTermcapMode = FALSE;
6294}
Christopher Plewright38804d62022-11-09 23:55:52 +00006295#endif // !FEAT_GUI_MSWIN || VIMDLL
Bram Moolenaar071d4272004-06-13 20:20:40 +00006296
6297
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006298#if defined(FEAT_GUI_MSWIN) && !defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006299 void
6300mch_write(
Bram Moolenaar1266d672017-02-01 13:43:36 +01006301 char_u *s UNUSED,
6302 int len UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006303{
Bram Moolenaar0f873732019-12-05 20:28:46 +01006304 // never used
Bram Moolenaar071d4272004-06-13 20:20:40 +00006305}
6306
6307#else
6308
6309/*
6310 * clear `n' chars, starting from `coord'
6311 */
6312 static void
6313clear_chars(
6314 COORD coord,
6315 DWORD n)
6316{
Christopher Plewright38804d62022-11-09 23:55:52 +00006317 if (!vtp_working)
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006318 {
6319 DWORD dwDummy;
6320
6321 FillConsoleOutputCharacter(g_hConOut, ' ', n, coord, &dwDummy);
6322 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, n, coord,
6323 &dwDummy);
6324 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006325 else
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02006326 {
6327 set_console_color_rgb();
6328 gotoxy(coord.X + 1, coord.Y + 1);
6329 vtp_printf("\033[%dX", n);
6330 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006331}
6332
6333
6334/*
6335 * Clear the screen
6336 */
6337 static void
6338clear_screen(void)
6339{
6340 g_coord.X = g_coord.Y = 0;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006341
Christopher Plewright38804d62022-11-09 23:55:52 +00006342 if (!vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006343 clear_chars(g_coord, Rows * Columns);
6344 else
6345 {
6346 set_console_color_rgb();
6347 gotoxy(1, 1);
6348 vtp_printf("\033[2J");
6349 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006350}
6351
6352
6353/*
6354 * Clear to end of display
6355 */
6356 static void
6357clear_to_end_of_display(void)
6358{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006359 COORD save = g_coord;
6360
Christopher Plewright38804d62022-11-09 23:55:52 +00006361 if (!vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006362 clear_chars(g_coord, (Rows - g_coord.Y - 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006363 * Columns + (Columns - g_coord.X));
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006364 else
6365 {
6366 set_console_color_rgb();
6367 gotoxy(g_coord.X + 1, g_coord.Y + 1);
6368 vtp_printf("\033[0J");
6369
6370 gotoxy(save.X + 1, save.Y + 1);
6371 g_coord = save;
6372 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006373}
6374
6375
6376/*
6377 * Clear to end of line
6378 */
6379 static void
6380clear_to_end_of_line(void)
6381{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006382 COORD save = g_coord;
6383
Christopher Plewright38804d62022-11-09 23:55:52 +00006384 if (!vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006385 clear_chars(g_coord, Columns - g_coord.X);
6386 else
6387 {
6388 set_console_color_rgb();
6389 gotoxy(g_coord.X + 1, g_coord.Y + 1);
6390 vtp_printf("\033[0K");
6391
6392 gotoxy(save.X + 1, save.Y + 1);
6393 g_coord = save;
6394 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006395}
6396
6397
6398/*
6399 * Scroll the scroll region up by `cLines' lines
6400 */
6401 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006402scroll(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006403{
6404 COORD oldcoord = g_coord;
6405
6406 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
6407 delete_lines(cLines);
6408
6409 g_coord = oldcoord;
6410}
6411
6412
6413/*
6414 * Set the scroll region
6415 */
6416 static void
6417set_scroll_region(
6418 unsigned left,
6419 unsigned top,
6420 unsigned right,
6421 unsigned bottom)
6422{
6423 if (left >= right
6424 || top >= bottom
6425 || right > (unsigned) Columns - 1
6426 || bottom > (unsigned) Rows - 1)
6427 return;
6428
6429 g_srScrollRegion.Left = left;
6430 g_srScrollRegion.Top = top;
6431 g_srScrollRegion.Right = right;
6432 g_srScrollRegion.Bottom = bottom;
Bram Moolenaar6982f422019-02-16 16:48:01 +01006433}
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006434
Bram Moolenaar6982f422019-02-16 16:48:01 +01006435 static void
6436set_scroll_region_tb(
6437 unsigned top,
6438 unsigned bottom)
6439{
6440 if (top >= bottom || bottom > (unsigned)Rows - 1)
6441 return;
6442
6443 g_srScrollRegion.Top = top;
6444 g_srScrollRegion.Bottom = bottom;
6445}
6446
6447 static void
6448set_scroll_region_lr(
6449 unsigned left,
6450 unsigned right)
6451{
6452 if (left >= right || right > (unsigned)Columns - 1)
6453 return;
6454
6455 g_srScrollRegion.Left = left;
6456 g_srScrollRegion.Right = right;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006457}
6458
6459
6460/*
6461 * Insert `cLines' lines at the current cursor position
6462 */
6463 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006464insert_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006465{
Bram Moolenaar6982f422019-02-16 16:48:01 +01006466 SMALL_RECT source, clip;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006467 COORD dest;
6468 CHAR_INFO fill;
6469
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006470 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
6471
Bram Moolenaar6982f422019-02-16 16:48:01 +01006472 dest.X = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006473 dest.Y = g_coord.Y + cLines;
6474
Bram Moolenaar6982f422019-02-16 16:48:01 +01006475 source.Left = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006476 source.Top = g_coord.Y;
6477 source.Right = g_srScrollRegion.Right;
6478 source.Bottom = g_srScrollRegion.Bottom - cLines;
6479
Bram Moolenaar6982f422019-02-16 16:48:01 +01006480 clip.Left = g_srScrollRegion.Left;
6481 clip.Top = g_coord.Y;
6482 clip.Right = g_srScrollRegion.Right;
6483 clip.Bottom = g_srScrollRegion.Bottom;
6484
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006485 fill.Char.AsciiChar = ' ';
Christopher Plewright38804d62022-11-09 23:55:52 +00006486 if (!(vtp_working
K.Takata161b6ac2022-11-14 15:31:07 +00006487# ifdef FEAT_TERMGUICOLORS
Christopher Plewright38804d62022-11-09 23:55:52 +00006488 && (p_tgc || t_colors >= 256)
K.Takata161b6ac2022-11-14 15:31:07 +00006489# endif
Christopher Plewright38804d62022-11-09 23:55:52 +00006490 ))
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006491 fill.Attributes = g_attrCurrent;
6492 else
6493 fill.Attributes = g_attrDefault;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006494
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006495 set_console_color_rgb();
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006496
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006497 ScrollConsoleScreenBuffer(g_hConOut, &source, &clip, dest, &fill);
6498
Bram Moolenaar6982f422019-02-16 16:48:01 +01006499 // Here we have to deal with a win32 console flake: If the scroll
6500 // region looks like abc and we scroll c to a and fill with d we get
6501 // cbd... if we scroll block c one line at a time to a, we get cdd...
6502 // vim expects cdd consistently... So we have to deal with that
6503 // here... (this also occurs scrolling the same way in the other
6504 // direction).
Bram Moolenaar071d4272004-06-13 20:20:40 +00006505
6506 if (source.Bottom < dest.Y)
6507 {
6508 COORD coord;
Bram Moolenaar6982f422019-02-16 16:48:01 +01006509 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006510
Bram Moolenaar6982f422019-02-16 16:48:01 +01006511 coord.X = source.Left;
6512 for (i = clip.Top; i < dest.Y; ++i)
6513 {
6514 coord.Y = i;
6515 clear_chars(coord, source.Right - source.Left + 1);
6516 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006517 }
Bram Moolenaar06b7b582020-05-30 17:49:25 +02006518
Christopher Plewright38804d62022-11-09 23:55:52 +00006519 if (vtp_working)
Bram Moolenaar06b7b582020-05-30 17:49:25 +02006520 {
6521 COORD coord;
6522 int i;
6523
6524 coord.X = source.Left;
6525 for (i = source.Top; i < dest.Y; ++i)
6526 {
6527 coord.Y = i;
6528 clear_chars(coord, source.Right - source.Left + 1);
6529 }
6530 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006531}
6532
6533
6534/*
6535 * Delete `cLines' lines at the current cursor position
6536 */
6537 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006538delete_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006539{
Bram Moolenaar6982f422019-02-16 16:48:01 +01006540 SMALL_RECT source, clip;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006541 COORD dest;
6542 CHAR_INFO fill;
6543 int nb;
6544
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006545 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
6546
Bram Moolenaar6982f422019-02-16 16:48:01 +01006547 dest.X = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006548 dest.Y = g_coord.Y;
6549
Bram Moolenaar6982f422019-02-16 16:48:01 +01006550 source.Left = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006551 source.Top = g_coord.Y + cLines;
6552 source.Right = g_srScrollRegion.Right;
6553 source.Bottom = g_srScrollRegion.Bottom;
6554
Bram Moolenaar6982f422019-02-16 16:48:01 +01006555 clip.Left = g_srScrollRegion.Left;
6556 clip.Top = g_coord.Y;
6557 clip.Right = g_srScrollRegion.Right;
6558 clip.Bottom = g_srScrollRegion.Bottom;
6559
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006560 fill.Char.AsciiChar = ' ';
Christopher Plewright38804d62022-11-09 23:55:52 +00006561 if (!vtp_working)
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006562 fill.Attributes = g_attrCurrent;
6563 else
6564 fill.Attributes = g_attrDefault;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006565
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006566 set_console_color_rgb();
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006567
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006568 ScrollConsoleScreenBuffer(g_hConOut, &source, &clip, dest, &fill);
6569
Bram Moolenaar6982f422019-02-16 16:48:01 +01006570 // Here we have to deal with a win32 console flake; See insert_lines()
6571 // above.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006572
6573 nb = dest.Y + (source.Bottom - source.Top) + 1;
6574
6575 if (nb < source.Top)
6576 {
6577 COORD coord;
Bram Moolenaar6982f422019-02-16 16:48:01 +01006578 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006579
Bram Moolenaar6982f422019-02-16 16:48:01 +01006580 coord.X = source.Left;
6581 for (i = nb; i < clip.Bottom; ++i)
6582 {
6583 coord.Y = i;
6584 clear_chars(coord, source.Right - source.Left + 1);
6585 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006586 }
Bram Moolenaar06b7b582020-05-30 17:49:25 +02006587
Christopher Plewright38804d62022-11-09 23:55:52 +00006588 if (vtp_working)
Bram Moolenaar06b7b582020-05-30 17:49:25 +02006589 {
6590 COORD coord;
6591 int i;
6592
6593 coord.X = source.Left;
6594 for (i = nb; i <= source.Bottom; ++i)
6595 {
6596 coord.Y = i;
6597 clear_chars(coord, source.Right - source.Left + 1);
6598 }
6599 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006600}
6601
6602
6603/*
Bram Moolenaar2313b612019-09-27 14:14:32 +02006604 * Set the cursor position to (x,y) (1-based).
Bram Moolenaar071d4272004-06-13 20:20:40 +00006605 */
6606 static void
6607gotoxy(
6608 unsigned x,
6609 unsigned y)
6610{
6611 if (x < 1 || x > (unsigned)Columns || y < 1 || y > (unsigned)Rows)
6612 return;
6613
Christopher Plewright38804d62022-11-09 23:55:52 +00006614 if (!(vtp_working
K.Takata161b6ac2022-11-14 15:31:07 +00006615# ifdef FEAT_TERMGUICOLORS
Christopher Plewright38804d62022-11-09 23:55:52 +00006616 && (p_tgc || t_colors >= 256)
K.Takata161b6ac2022-11-14 15:31:07 +00006617# endif
Christopher Plewright38804d62022-11-09 23:55:52 +00006618 ))
Bram Moolenaar2313b612019-09-27 14:14:32 +02006619 {
Bram Moolenaar82e743c2020-03-26 15:39:53 +01006620 // There are reports of double-width characters not displayed
6621 // correctly. This workaround should fix it, similar to how it's done
6622 // for VTP.
6623 g_coord.X = 0;
6624 SetConsoleCursorPosition(g_hConOut, g_coord);
6625
Bram Moolenaar2313b612019-09-27 14:14:32 +02006626 // external cursor coords are 1-based; internal are 0-based
6627 g_coord.X = x - 1;
6628 g_coord.Y = y - 1;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006629 SetConsoleCursorPosition(g_hConOut, g_coord);
Bram Moolenaar2313b612019-09-27 14:14:32 +02006630 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006631 else
Bram Moolenaar2313b612019-09-27 14:14:32 +02006632 {
6633 // Move the cursor to the left edge of the screen to prevent screen
Bram Moolenaara1299742019-10-10 16:36:00 +02006634 // destruction. Insider build bug. Always enabled because it's cheap
6635 // and avoids mistakes with recognizing the build.
6636 vtp_printf("\033[%d;%dH", g_coord.Y + 1, 1);
Bram Moolenaar2313b612019-09-27 14:14:32 +02006637
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006638 vtp_printf("\033[%d;%dH", y, x);
Bram Moolenaar2313b612019-09-27 14:14:32 +02006639
6640 g_coord.X = x - 1;
6641 g_coord.Y = y - 1;
6642 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006643}
6644
6645
6646/*
6647 * Set the current text attribute = (foreground | background)
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006648 * See ../runtime/doc/os_win32.txt for the numbers.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006649 */
6650 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006651textattr(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006652{
Bram Moolenaar6383b922015-03-24 17:12:19 +01006653 g_attrCurrent = wAttr & 0xff;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006654
6655 SetConsoleTextAttribute(g_hConOut, wAttr);
6656}
6657
6658
6659 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006660textcolor(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006661{
Bram Moolenaar6383b922015-03-24 17:12:19 +01006662 g_attrCurrent = (g_attrCurrent & 0xf0) + (wAttr & 0x0f);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006663
Christopher Plewright38804d62022-11-09 23:55:52 +00006664 if (!vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006665 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
6666 else
6667 vtp_sgr_bulk(wAttr);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006668}
6669
6670
6671 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006672textbackground(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006673{
Bram Moolenaar6383b922015-03-24 17:12:19 +01006674 g_attrCurrent = (g_attrCurrent & 0x0f) + ((wAttr & 0x0f) << 4);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006675
Christopher Plewright38804d62022-11-09 23:55:52 +00006676 if (!vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006677 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
6678 else
6679 vtp_sgr_bulk(wAttr);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006680}
6681
6682
6683/*
6684 * restore the default text attribute (whatever we started with)
6685 */
6686 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006687normvideo(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006688{
Christopher Plewright38804d62022-11-09 23:55:52 +00006689 if (!vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006690 textattr(g_attrDefault);
6691 else
6692 vtp_sgr_bulk(0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006693}
6694
6695
6696static WORD g_attrPreStandout = 0;
6697
6698/*
6699 * Make the text standout, by brightening it
6700 */
6701 static void
6702standout(void)
6703{
6704 g_attrPreStandout = g_attrCurrent;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006705
Bram Moolenaar071d4272004-06-13 20:20:40 +00006706 textattr((WORD) (g_attrCurrent|FOREGROUND_INTENSITY|BACKGROUND_INTENSITY));
6707}
6708
6709
6710/*
6711 * Turn off standout mode
6712 */
6713 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006714standend(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006715{
6716 if (g_attrPreStandout)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006717 textattr(g_attrPreStandout);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006718
6719 g_attrPreStandout = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006720}
6721
6722
6723/*
Bram Moolenaarff1d0d42007-05-10 17:24:16 +00006724 * Set normal fg/bg color, based on T_ME. Called when t_me has been set.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006725 */
6726 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006727mch_set_normal_colors(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006728{
6729 char_u *p;
6730 int n;
6731
6732 cterm_normal_fg_color = (g_attrDefault & 0xf) + 1;
6733 cterm_normal_bg_color = ((g_attrDefault >> 4) & 0xf) + 1;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006734 if (
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006735# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006736 !p_tgc &&
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006737# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006738 T_ME[0] == ESC && T_ME[1] == '|')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006739 {
6740 p = T_ME + 2;
6741 n = getdigits(&p);
6742 if (*p == 'm' && n > 0)
6743 {
6744 cterm_normal_fg_color = (n & 0xf) + 1;
6745 cterm_normal_bg_color = ((n >> 4) & 0xf) + 1;
6746 }
6747 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006748# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006749 cterm_normal_fg_gui_color = INVALCOLOR;
6750 cterm_normal_bg_gui_color = INVALCOLOR;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006751# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006752}
6753
6754
6755/*
6756 * visual bell: flash the screen
6757 */
6758 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006759visual_bell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006760{
6761 COORD coordOrigin = {0, 0};
6762 WORD attrFlash = ~g_attrCurrent & 0xff;
6763
6764 DWORD dwDummy;
Bram Moolenaarc799fe22019-05-28 23:08:19 +02006765 LPWORD oldattrs = ALLOC_MULT(WORD, Rows * Columns);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006766
6767 if (oldattrs == NULL)
6768 return;
6769 ReadConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
6770 coordOrigin, &dwDummy);
6771 FillConsoleOutputAttribute(g_hConOut, attrFlash, Rows * Columns,
6772 coordOrigin, &dwDummy);
6773
Bram Moolenaar0f873732019-12-05 20:28:46 +01006774 Sleep(15); // wait for 15 msec
Christopher Plewright38804d62022-11-09 23:55:52 +00006775 if (!vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006776 WriteConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
Bram Moolenaar071d4272004-06-13 20:20:40 +00006777 coordOrigin, &dwDummy);
6778 vim_free(oldattrs);
6779}
6780
6781
6782/*
6783 * Make the cursor visible or invisible
6784 */
6785 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006786cursor_visible(BOOL fVisible)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006787{
6788 s_cursor_visible = fVisible;
Bram Moolenaar2695de62020-04-17 21:13:01 +02006789
Christopher Plewright38804d62022-11-09 23:55:52 +00006790 if (vtp_working)
Bram Moolenaar2695de62020-04-17 21:13:01 +02006791 vtp_printf("\033[?25%c", fVisible ? 'h' : 'l');
6792
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006793# ifdef MCH_CURSOR_SHAPE
Bram Moolenaar071d4272004-06-13 20:20:40 +00006794 mch_update_cursor();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006795# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006796}
6797
6798
6799/*
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02006800 * Write "cbToWrite" bytes in `pchBuf' to the screen.
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006801 * Returns the number of bytes actually written (at least one).
Bram Moolenaar071d4272004-06-13 20:20:40 +00006802 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006803 static DWORD
Bram Moolenaar071d4272004-06-13 20:20:40 +00006804write_chars(
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006805 char_u *pchBuf,
6806 DWORD cbToWrite)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006807{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006808 COORD coord = g_coord;
6809 DWORD written;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006810 DWORD n, cchwritten;
6811 static DWORD cells;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006812 static WCHAR *unicodebuf = NULL;
6813 static int unibuflen = 0;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006814 static int length;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006815 int cp = enc_utf8 ? CP_UTF8 : enc_codepage;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006816 static WCHAR *utf8spbuf = NULL;
6817 static int utf8splength;
6818 static DWORD utf8spcells;
6819 static WCHAR **utf8usingbuf = &unicodebuf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006820
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006821 if (cbToWrite != 1 || *pchBuf != ' ' || !enc_utf8)
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006822 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006823 utf8usingbuf = &unicodebuf;
6824 do
6825 {
6826 length = MultiByteToWideChar(cp, 0, (LPCSTR)pchBuf, cbToWrite,
6827 unicodebuf, unibuflen);
6828 if (length && length <= unibuflen)
6829 break;
6830 vim_free(unicodebuf);
6831 unicodebuf = length ? LALLOC_MULT(WCHAR, length) : NULL;
6832 unibuflen = unibuflen ? 0 : length;
6833 } while(1);
6834 cells = mb_string2cells(pchBuf, cbToWrite);
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006835 }
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006836 else // cbToWrite == 1 && *pchBuf == ' ' && enc_utf8
6837 {
6838 if (utf8usingbuf != &utf8spbuf)
6839 {
6840 if (utf8spbuf == NULL)
6841 {
6842 cells = mb_string2cells((char_u *)" ", 1);
6843 length = MultiByteToWideChar(CP_UTF8, 0, " ", 1, NULL, 0);
6844 utf8spbuf = LALLOC_MULT(WCHAR, length);
6845 if (utf8spbuf != NULL)
6846 {
6847 MultiByteToWideChar(CP_UTF8, 0, " ", 1, utf8spbuf, length);
6848 utf8usingbuf = &utf8spbuf;
6849 utf8splength = length;
6850 utf8spcells = cells;
6851 }
6852 }
6853 else
6854 {
6855 utf8usingbuf = &utf8spbuf;
6856 length = utf8splength;
6857 cells = utf8spcells;
6858 }
6859 }
6860 }
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006861
Christopher Plewright38804d62022-11-09 23:55:52 +00006862 if (!(vtp_working
K.Takata161b6ac2022-11-14 15:31:07 +00006863# ifdef FEAT_TERMGUICOLORS
Christopher Plewright38804d62022-11-09 23:55:52 +00006864 && (p_tgc || t_colors >= 256)
K.Takata161b6ac2022-11-14 15:31:07 +00006865# endif
Christopher Plewright38804d62022-11-09 23:55:52 +00006866 ))
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006867 {
6868 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, cells,
6869 coord, &written);
6870 // When writing fails or didn't write a single character, pretend one
6871 // character was written, otherwise we get stuck.
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006872 if (WriteConsoleOutputCharacterW(g_hConOut, *utf8usingbuf, length,
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006873 coord, &cchwritten) == 0
6874 || cchwritten == 0 || cchwritten == (DWORD)-1)
6875 cchwritten = 1;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006876 }
6877 else
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006878 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006879 if (WriteConsoleW(g_hConOut, *utf8usingbuf, length, &cchwritten,
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006880 NULL) == 0 || cchwritten == 0)
6881 cchwritten = 1;
6882 }
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006883
K.Takata135e1522022-01-29 15:27:58 +00006884 if (cchwritten == (DWORD)length)
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006885 {
6886 written = cbToWrite;
6887 g_coord.X += (SHORT)cells;
6888 }
6889 else
6890 {
6891 char_u *p = pchBuf;
6892 for (n = 0; n < cchwritten; n++)
6893 MB_CPTR_ADV(p);
6894 written = p - pchBuf;
6895 g_coord.X += (SHORT)mb_string2cells(pchBuf, written);
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006896 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006897
6898 while (g_coord.X > g_srScrollRegion.Right)
6899 {
6900 g_coord.X -= (SHORT) Columns;
6901 if (g_coord.Y < g_srScrollRegion.Bottom)
6902 g_coord.Y++;
6903 }
6904
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006905 // Cursor under VTP is always in the correct position, no need to reset.
Christopher Plewright38804d62022-11-09 23:55:52 +00006906 if (!(vtp_working
K.Takata161b6ac2022-11-14 15:31:07 +00006907# ifdef FEAT_TERMGUICOLORS
Christopher Plewright38804d62022-11-09 23:55:52 +00006908 && (p_tgc || t_colors >= 256)
K.Takata161b6ac2022-11-14 15:31:07 +00006909# endif
Christopher Plewright38804d62022-11-09 23:55:52 +00006910 ))
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006911 gotoxy(g_coord.X + 1, g_coord.Y + 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006912
6913 return written;
6914}
6915
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006916 static char_u *
6917get_seq(
6918 int *args,
6919 int *count,
6920 char_u *head)
6921{
6922 int argc;
6923 char_u *p;
6924
6925 if (head == NULL || *head != '\033')
6926 return NULL;
6927
6928 argc = 0;
6929 p = head;
6930 ++p;
6931 do
6932 {
6933 ++p;
6934 args[argc] = getdigits(&p);
6935 argc += (argc < 15) ? 1 : 0;
6936 } while (*p == ';');
6937 *count = argc;
6938
6939 return p;
6940}
6941
6942 static char_u *
6943get_sgr(
6944 int *args,
6945 int *count,
6946 char_u *head)
6947{
6948 char_u *p = get_seq(args, count, head);
6949
6950 return (p && *p == 'm') ? ++p : NULL;
6951}
6952
6953/*
6954 * Pointer to next if SGR (^[[n;2;*;*;*m), NULL otherwise.
6955 */
6956 static char_u *
6957sgrn2(
6958 char_u *head,
6959 int n)
6960{
6961 int argc;
6962 int args[16];
6963 char_u *p = get_sgr(args, &argc, head);
6964
6965 return p && argc == 5 && args[0] == n && args[1] == 2 ? p : NULL;
6966}
6967
6968/*
6969 * Pointer to next if SGR(^[[nm)<space>ESC, NULL otherwise.
6970 */
6971 static char_u *
6972sgrnc(
6973 char_u *head,
6974 int n)
6975{
6976 int argc;
6977 int args[16];
6978 char_u *p = get_sgr(args, &argc, head);
6979
6980 return p && argc == 1 && args[0] == n && (p = skipwhite(p)) && *p == '\033'
6981 ? p : NULL;
6982}
6983
6984 static char_u *
6985skipblank(char_u *q)
6986{
6987 char_u *p = q;
6988
6989 while (*p == ' ' || *p == '\t' || *p == '\n' || *p == '\r')
6990 ++p;
6991 return p;
6992}
6993
6994/*
6995 * Pointer to the next if any whitespace that may follow SGR is ESC, otherwise
6996 * NULL.
6997 */
6998 static char_u *
6999sgrn2c(
7000 char_u *head,
7001 int n)
7002{
7003 char_u *p = sgrn2(head, n);
7004
7005 return p && *p != NUL && (p = skipblank(p)) && *p == '\033' ? p : NULL;
7006}
7007
7008/*
7009 * If there is only a newline between the sequence immediately following it,
7010 * a pointer to the character following the newline is returned.
7011 * Otherwise NULL.
7012 */
7013 static char_u *
7014sgrn2cn(
7015 char_u *head,
7016 int n)
7017{
7018 char_u *p = sgrn2(head, n);
7019
7020 return p && p[0] == 0x0a && p[1] == '\033' ? ++p : NULL;
7021}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007022
7023/*
7024 * mch_write(): write the output buffer to the screen, translating ESC
7025 * sequences into calls to console output routines.
7026 */
7027 void
7028mch_write(
7029 char_u *s,
7030 int len)
7031{
Bram Moolenaard23f8bd2021-04-21 11:30:48 +02007032 char_u *end = s + len;
7033
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007034# ifdef VIMDLL
7035 if (gui.in_use)
7036 return;
7037# endif
7038
Bram Moolenaar071d4272004-06-13 20:20:40 +00007039 if (!term_console)
7040 {
7041 write(1, s, (unsigned)len);
7042 return;
7043 }
7044
Bram Moolenaar0f873732019-12-05 20:28:46 +01007045 // translate ESC | sequences into faked bios calls
Bram Moolenaar071d4272004-06-13 20:20:40 +00007046 while (len--)
7047 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007048 int prefix = -1;
7049 char_u ch;
7050
7051 // While processing a sequence, on rare occasions it seems that another
7052 // sequence may be inserted asynchronously.
7053 if (len < 0)
7054 {
Bram Moolenaara4d158b2022-08-14 14:17:45 +01007055 redraw_all_later(UPD_CLEAR);
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007056 return;
7057 }
7058
Bram Moolenaard23f8bd2021-04-21 11:30:48 +02007059 while (s + ++prefix < end)
7060 {
7061 ch = s[prefix];
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007062 if (ch <= 0x1e && !(ch != '\n' && ch != '\r' && ch != '\b'
7063 && ch != '\a' && ch != '\033'))
7064 break;
Bram Moolenaard23f8bd2021-04-21 11:30:48 +02007065 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007066
7067 if (p_wd)
7068 {
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02007069 WaitForChar(p_wd, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007070 if (prefix != 0)
7071 prefix = 1;
7072 }
7073
7074 if (prefix != 0)
7075 {
7076 DWORD nWritten;
7077
7078 nWritten = write_chars(s, prefix);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007079# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00007080 if (fdDump)
7081 {
7082 fputc('>', fdDump);
7083 fwrite(s, sizeof(char_u), nWritten, fdDump);
7084 fputs("<\n", fdDump);
7085 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007086# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007087 len -= (nWritten - 1);
7088 s += nWritten;
7089 }
7090 else if (s[0] == '\n')
7091 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007092 // \n, newline: go to the beginning of the next line or scroll
Bram Moolenaar071d4272004-06-13 20:20:40 +00007093 if (g_coord.Y == g_srScrollRegion.Bottom)
7094 {
7095 scroll(1);
7096 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Bottom + 1);
7097 }
7098 else
7099 {
7100 gotoxy(g_srScrollRegion.Left + 1, g_coord.Y + 2);
7101 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007102# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00007103 if (fdDump)
7104 fputs("\\n\n", fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007105# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007106 s++;
7107 }
7108 else if (s[0] == '\r')
7109 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007110 // \r, carriage return: go to beginning of line
Bram Moolenaar071d4272004-06-13 20:20:40 +00007111 gotoxy(g_srScrollRegion.Left+1, g_coord.Y + 1);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007112# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00007113 if (fdDump)
7114 fputs("\\r\n", fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007115# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007116 s++;
7117 }
7118 else if (s[0] == '\b')
7119 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007120 // \b, backspace: move cursor one position left
Bram Moolenaar071d4272004-06-13 20:20:40 +00007121 if (g_coord.X > g_srScrollRegion.Left)
7122 g_coord.X--;
7123 else if (g_coord.Y > g_srScrollRegion.Top)
7124 {
7125 g_coord.X = g_srScrollRegion.Right;
7126 g_coord.Y--;
7127 }
7128 gotoxy(g_coord.X + 1, g_coord.Y + 1);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007129# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00007130 if (fdDump)
7131 fputs("\\b\n", fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007132# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007133 s++;
7134 }
7135 else if (s[0] == '\a')
7136 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007137 // \a, bell
Bram Moolenaar071d4272004-06-13 20:20:40 +00007138 MessageBeep(0xFFFFFFFF);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007139# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00007140 if (fdDump)
7141 fputs("\\a\n", fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007142# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007143 s++;
7144 }
7145 else if (s[0] == ESC && len >= 3-1 && s[1] == '|')
7146 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007147# ifdef MCH_WRITE_DUMP
Bram Moolenaarc0197e22004-09-13 20:26:32 +00007148 char_u *old_s = s;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007149# endif
Bram Moolenaarc0197e22004-09-13 20:26:32 +00007150 char_u *p;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007151 int arg1 = 0, arg2 = 0, argc = 0, args[16];
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007152 char_u *sp;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007153
7154 switch (s[2])
7155 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00007156 case '0': case '1': case '2': case '3': case '4':
7157 case '5': case '6': case '7': case '8': case '9':
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007158 if (*(p = get_seq(args, &argc, s)) != 'm')
7159 goto notsgr;
7160
7161 p = s;
7162
7163 // Handling frequent optional sequences. Output to the screen
7164 // takes too long, so do not output as much as possible.
7165
7166 // If resetFG,FG,BG,<cr>,BG,FG are connected, the preceding
7167 // resetFG,FG,BG are omitted.
7168 if (sgrn2(sgrn2(sgrn2cn(sgrn2(sgrnc(p, 39), 38), 48), 48), 38))
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007169 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007170 p = sgrn2(sgrn2(sgrnc(p, 39), 38), 48);
7171 len = len + 1 - (int)(p - s);
7172 s = p;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007173 break;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007174 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007175
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007176 // If FG,BG,BG,FG of SGR are connected, the first FG can be
7177 // omitted.
7178 if (sgrn2(sgrn2(sgrn2c((sp = sgrn2(p, 38)), 48), 48), 38))
7179 p = sp;
7180
7181 // If FG,BG,FG,BG of SGR are connected, the first FG can be
7182 // omitted.
7183 if (sgrn2(sgrn2(sgrn2c((sp = sgrn2(p, 38)), 48), 38), 48))
7184 p = sp;
7185
7186 // If BG,BG of SGR are connected, the first BG can be omitted.
7187 if (sgrn2((sp = sgrn2(p, 48)), 48))
7188 p = sp;
7189
7190 // If restoreFG and FG are connected, the restoreFG can be
Bram Moolenaar9f1983d2022-05-12 20:35:35 +01007191 // omitted.
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007192 if (sgrn2((sp = sgrnc(p, 39)), 38))
7193 p = sp;
7194
7195 p = get_seq(args, &argc, p);
7196
7197notsgr:
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007198 arg1 = args[0];
7199 arg2 = args[1];
7200 if (*p == 'm')
Bram Moolenaar071d4272004-06-13 20:20:40 +00007201 {
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007202 if (argc == 1 && args[0] == 0)
7203 normvideo();
7204 else if (argc == 1)
7205 {
Christopher Plewright38804d62022-11-09 23:55:52 +00007206 if (vtp_working
7207# ifdef FEAT_TERMGUICOLORS
7208 && (p_tgc || t_colors >= 256)
7209# endif
7210 )
7211 textcolor((WORD)arg1);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007212 else
Christopher Plewright38804d62022-11-09 23:55:52 +00007213 textattr((WORD)arg1);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007214 }
Christopher Plewright38804d62022-11-09 23:55:52 +00007215 else if (vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007216 vtp_sgr_bulks(argc, args);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007217 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007218 else if (argc == 2 && *p == 'H')
Bram Moolenaar071d4272004-06-13 20:20:40 +00007219 {
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007220 gotoxy(arg2, arg1);
7221 }
7222 else if (argc == 2 && *p == 'r')
7223 {
7224 set_scroll_region(0, arg1 - 1, Columns - 1, arg2 - 1);
7225 }
Bram Moolenaar6982f422019-02-16 16:48:01 +01007226 else if (argc == 2 && *p == 'R')
7227 {
7228 set_scroll_region_tb(arg1, arg2);
7229 }
7230 else if (argc == 2 && *p == 'V')
7231 {
7232 set_scroll_region_lr(arg1, arg2);
7233 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007234 else if (argc == 1 && *p == 'A')
7235 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00007236 gotoxy(g_coord.X + 1,
7237 max(g_srScrollRegion.Top, g_coord.Y - arg1) + 1);
7238 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007239 else if (argc == 1 && *p == 'b')
Bram Moolenaar071d4272004-06-13 20:20:40 +00007240 {
7241 textbackground((WORD) arg1);
7242 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007243 else if (argc == 1 && *p == 'C')
7244 {
7245 gotoxy(min(g_srScrollRegion.Right, g_coord.X + arg1) + 1,
7246 g_coord.Y + 1);
7247 }
7248 else if (argc == 1 && *p == 'f')
7249 {
7250 textcolor((WORD) arg1);
7251 }
7252 else if (argc == 1 && *p == 'H')
7253 {
7254 gotoxy(1, arg1);
7255 }
7256 else if (argc == 1 && *p == 'L')
7257 {
7258 insert_lines(arg1);
7259 }
7260 else if (argc == 1 && *p == 'M')
Bram Moolenaar071d4272004-06-13 20:20:40 +00007261 {
7262 delete_lines(arg1);
7263 }
7264
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007265 len -= (int)(p - s);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007266 s = p + 1;
7267 break;
7268
Bram Moolenaar071d4272004-06-13 20:20:40 +00007269 case 'A':
Bram Moolenaar071d4272004-06-13 20:20:40 +00007270 gotoxy(g_coord.X + 1,
7271 max(g_srScrollRegion.Top, g_coord.Y - 1) + 1);
7272 goto got3;
7273
7274 case 'B':
7275 visual_bell();
7276 goto got3;
7277
7278 case 'C':
Bram Moolenaar071d4272004-06-13 20:20:40 +00007279 gotoxy(min(g_srScrollRegion.Right, g_coord.X + 1) + 1,
7280 g_coord.Y + 1);
7281 goto got3;
7282
7283 case 'E':
7284 termcap_mode_end();
7285 goto got3;
7286
7287 case 'F':
7288 standout();
7289 goto got3;
7290
7291 case 'f':
7292 standend();
7293 goto got3;
7294
7295 case 'H':
7296 gotoxy(1, 1);
7297 goto got3;
7298
7299 case 'j':
7300 clear_to_end_of_display();
7301 goto got3;
7302
7303 case 'J':
7304 clear_screen();
7305 goto got3;
7306
7307 case 'K':
7308 clear_to_end_of_line();
7309 goto got3;
7310
7311 case 'L':
7312 insert_lines(1);
7313 goto got3;
7314
7315 case 'M':
7316 delete_lines(1);
7317 goto got3;
7318
7319 case 'S':
7320 termcap_mode_start();
7321 goto got3;
7322
7323 case 'V':
7324 cursor_visible(TRUE);
7325 goto got3;
7326
7327 case 'v':
7328 cursor_visible(FALSE);
7329 goto got3;
7330
7331 got3:
7332 s += 3;
7333 len -= 2;
7334 }
7335
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007336# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00007337 if (fdDump)
7338 {
7339 fputs("ESC | ", fdDump);
7340 fwrite(old_s + 2, sizeof(char_u), s - old_s - 2, fdDump);
7341 fputc('\n', fdDump);
7342 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007343# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007344 }
K.Takatadf5320c2022-09-01 13:20:16 +01007345 else if (s[0] == ESC && len >= 3-1 && s[1] == '[')
7346 {
7347 int l = 2;
7348
7349 if (isdigit(s[l]))
7350 l++;
7351 if (s[l] == ' ' && s[l + 1] == 'q')
7352 {
7353 // DECSCUSR (cursor style) sequences
Christopher Plewright38804d62022-11-09 23:55:52 +00007354 if (vtp_working)
K.Takatadf5320c2022-09-01 13:20:16 +01007355 vtp_printf("%.*s", l + 2, s); // Pass through
7356 s += l + 2;
7357 len -= l + 1;
7358 }
7359 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007360 else
7361 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007362 // Write a single character
Bram Moolenaar071d4272004-06-13 20:20:40 +00007363 DWORD nWritten;
7364
7365 nWritten = write_chars(s, 1);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007366# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00007367 if (fdDump)
7368 {
7369 fputc('>', fdDump);
7370 fwrite(s, sizeof(char_u), nWritten, fdDump);
7371 fputs("<\n", fdDump);
7372 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007373# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007374
7375 len -= (nWritten - 1);
7376 s += nWritten;
7377 }
7378 }
7379
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007380# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00007381 if (fdDump)
7382 fflush(fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007383# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007384}
7385
Bram Moolenaar0f873732019-12-05 20:28:46 +01007386#endif // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00007387
7388
7389/*
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01007390 * Delay for "msec" milliseconds.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007391 */
7392 void
7393mch_delay(
7394 long msec,
Bram Moolenaar0981c872020-08-23 14:28:37 +02007395 int flags UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007396{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007397#if defined(FEAT_GUI_MSWIN) && !defined(VIMDLL)
Bram Moolenaar0f873732019-12-05 20:28:46 +01007398 Sleep((int)msec); // never wait for input
7399#else // Console
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007400# ifdef VIMDLL
7401 if (gui.in_use)
7402 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007403 Sleep((int)msec); // never wait for input
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007404 return;
7405 }
7406# endif
Bram Moolenaar0981c872020-08-23 14:28:37 +02007407 if (flags & MCH_DELAY_IGNOREINPUT)
Bram Moolenaar325b7a22004-07-05 15:58:32 +00007408# ifdef FEAT_MZSCHEME
7409 if (mzthreads_allowed() && p_mzq > 0 && msec > p_mzq)
7410 {
7411 int towait = p_mzq;
7412
Bram Moolenaar0f873732019-12-05 20:28:46 +01007413 // if msec is large enough, wait by portions in p_mzq
Bram Moolenaar325b7a22004-07-05 15:58:32 +00007414 while (msec > 0)
7415 {
7416 mzvim_check_threads();
7417 if (msec < towait)
7418 towait = msec;
7419 Sleep(towait);
7420 msec -= towait;
7421 }
7422 }
7423 else
7424# endif
7425 Sleep((int)msec);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007426 else
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02007427 WaitForChar(msec, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007428#endif
7429}
7430
7431
7432/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01007433 * This version of remove is not scared by a readonly (backup) file.
7434 * This can also remove a symbolic link like Unix.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007435 * Return 0 for success, -1 for failure.
7436 */
7437 int
7438mch_remove(char_u *name)
7439{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007440 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007441 int n;
7442
Bram Moolenaar203258c2016-01-17 22:15:16 +01007443 /*
7444 * On Windows, deleting a directory's symbolic link is done by
7445 * RemoveDirectory(): mch_rmdir. It seems unnatural, but it is fact.
7446 */
7447 if (mch_isdir(name) && mch_is_symbolic_link(name))
7448 return mch_rmdir(name);
7449
Bram Moolenaar12b559e2013-06-12 22:41:37 +02007450 win32_setattrs(name, FILE_ATTRIBUTE_NORMAL);
7451
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007452 wn = enc_to_utf16(name, NULL);
7453 if (wn == NULL)
7454 return -1;
7455
7456 n = DeleteFileW(wn) ? 0 : -1;
7457 vim_free(wn);
7458 return n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007459}
7460
7461
7462/*
Bram Moolenaarb9c31e72016-09-29 15:18:57 +02007463 * Check for an "interrupt signal": CTRL-break or CTRL-C.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007464 */
7465 void
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02007466mch_breakcheck(int force UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007467{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007468#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
7469# ifdef VIMDLL
7470 if (!gui.in_use)
7471# endif
7472 if (g_fCtrlCPressed || g_fCBrkPressed)
7473 {
7474 ctrl_break_was_pressed = g_fCBrkPressed;
7475 g_fCtrlCPressed = g_fCBrkPressed = FALSE;
7476 got_int = TRUE;
7477 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007478#endif
7479}
7480
Bram Moolenaar0f873732019-12-05 20:28:46 +01007481// physical RAM to leave for the OS
Bram Moolenaaree273972016-01-02 21:11:51 +01007482#define WINNT_RESERVE_BYTES (256*1024*1024)
Bram Moolenaaree273972016-01-02 21:11:51 +01007483
7484/*
7485 * How much main memory in KiB that can be used by VIM.
7486 */
Bram Moolenaaree273972016-01-02 21:11:51 +01007487 long_u
Bram Moolenaar1266d672017-02-01 13:43:36 +01007488mch_total_mem(int special UNUSED)
Bram Moolenaaree273972016-01-02 21:11:51 +01007489{
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007490 MEMORYSTATUSEX ms;
7491
Bram Moolenaar0f873732019-12-05 20:28:46 +01007492 // Need to use GlobalMemoryStatusEx() when there is more memory than
7493 // what fits in 32 bits.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007494 ms.dwLength = sizeof(MEMORYSTATUSEX);
7495 GlobalMemoryStatusEx(&ms);
7496 if (ms.ullAvailVirtual < ms.ullTotalPhys)
Bram Moolenaaree273972016-01-02 21:11:51 +01007497 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007498 // Process address space fits in physical RAM, use all of it.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007499 return (long_u)(ms.ullAvailVirtual / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01007500 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007501 if (ms.ullTotalPhys <= WINNT_RESERVE_BYTES)
Bram Moolenaaree273972016-01-02 21:11:51 +01007502 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007503 // Catch old NT box or perverse hardware setup.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007504 return (long_u)((ms.ullTotalPhys / 2) / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01007505 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01007506 // Use physical RAM less reserve for OS + data.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007507 return (long_u)((ms.ullTotalPhys - WINNT_RESERVE_BYTES) / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01007508}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007509
Bram Moolenaar071d4272004-06-13 20:20:40 +00007510/*
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007511 * mch_wrename() works around a bug in rename (aka MoveFile) in
Bram Moolenaar071d4272004-06-13 20:20:40 +00007512 * Windows 95: rename("foo.bar", "foo.bar~") will generate a
7513 * file whose short file name is "FOO.BAR" (its long file name will
7514 * be correct: "foo.bar~"). Because a file can be accessed by
7515 * either its SFN or its LFN, "foo.bar" has effectively been
7516 * renamed to "foo.bar", which is not at all what was wanted. This
7517 * seems to happen only when renaming files with three-character
7518 * extensions by appending a suffix that does not include ".".
7519 * Windows NT gets it right, however, with an SFN of "FOO~1.BAR".
7520 *
7521 * There is another problem, which isn't really a bug but isn't right either:
7522 * When renaming "abcdef~1.txt" to "abcdef~1.txt~", the short name can be
7523 * "abcdef~1.txt" again. This has been reported on Windows NT 4.0 with
7524 * service pack 6. Doesn't seem to happen on Windows 98.
7525 *
7526 * Like rename(), returns 0 upon success, non-zero upon failure.
7527 * Should probably set errno appropriately when errors occur.
7528 */
7529 int
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007530mch_wrename(WCHAR *wold, WCHAR *wnew)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007531{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007532 WCHAR *p;
7533 int i;
7534 WCHAR szTempFile[_MAX_PATH + 1];
7535 WCHAR szNewPath[_MAX_PATH + 1];
Bram Moolenaar071d4272004-06-13 20:20:40 +00007536 HANDLE hf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007537
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007538 // No need to play tricks unless the file name contains a "~" as the
7539 // seventh character.
7540 p = wold;
7541 for (i = 0; wold[i] != NUL; ++i)
7542 if ((wold[i] == '/' || wold[i] == '\\' || wold[i] == ':')
7543 && wold[i + 1] != 0)
7544 p = wold + i + 1;
7545 if ((int)(wold + i - p) < 8 || p[6] != '~')
7546 return (MoveFileW(wold, wnew) == 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007547
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007548 // Get base path of new file name. Undocumented feature: If pszNewFile is
7549 // a directory, no error is returned and pszFilePart will be NULL.
7550 if (GetFullPathNameW(wnew, _MAX_PATH, szNewPath, &p) == 0 || p == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007551 return -1;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007552 *p = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007553
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007554 // Get (and create) a unique temporary file name in directory of new file
7555 if (GetTempFileNameW(szNewPath, L"VIM", 0, szTempFile) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007556 return -2;
7557
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007558 // blow the temp file away
7559 if (!DeleteFileW(szTempFile))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007560 return -3;
7561
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007562 // rename old file to the temp file
7563 if (!MoveFileW(wold, szTempFile))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007564 return -4;
7565
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007566 // now create an empty file called pszOldFile; this prevents the operating
7567 // system using pszOldFile as an alias (SFN) if we're renaming within the
7568 // same directory. For example, we're editing a file called
7569 // filename.asc.txt by its SFN, filena~1.txt. If we rename filena~1.txt
7570 // to filena~1.txt~ (i.e., we're making a backup while writing it), the
7571 // SFN for filena~1.txt~ will be filena~1.txt, by default, which will
7572 // cause all sorts of problems later in buf_write(). So, we create an
7573 // empty file called filena~1.txt and the system will have to find some
7574 // other SFN for filena~1.txt~, such as filena~2.txt
7575 if ((hf = CreateFileW(wold, GENERIC_WRITE, 0, NULL, CREATE_NEW,
Bram Moolenaar071d4272004-06-13 20:20:40 +00007576 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
7577 return -5;
7578 if (!CloseHandle(hf))
7579 return -6;
7580
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007581 // rename the temp file to the new file
7582 if (!MoveFileW(szTempFile, wnew))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007583 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007584 // Renaming failed. Rename the file back to its old name, so that it
7585 // looks like nothing happened.
7586 (void)MoveFileW(szTempFile, wold);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007587 return -7;
7588 }
7589
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007590 // Seems to be left around on Novell filesystems
7591 DeleteFileW(szTempFile);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007592
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007593 // finally, remove the empty old file
7594 if (!DeleteFileW(wold))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007595 return -8;
7596
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007597 return 0;
7598}
7599
7600
7601/*
7602 * Converts the filenames to UTF-16, then call mch_wrename().
7603 * Like rename(), returns 0 upon success, non-zero upon failure.
7604 */
7605 int
7606mch_rename(
7607 const char *pszOldFile,
7608 const char *pszNewFile)
7609{
7610 WCHAR *wold = NULL;
7611 WCHAR *wnew = NULL;
7612 int retval = -1;
7613
7614 wold = enc_to_utf16((char_u *)pszOldFile, NULL);
7615 wnew = enc_to_utf16((char_u *)pszNewFile, NULL);
7616 if (wold != NULL && wnew != NULL)
7617 retval = mch_wrename(wold, wnew);
7618 vim_free(wold);
7619 vim_free(wnew);
7620 return retval;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007621}
7622
7623/*
7624 * Get the default shell for the current hardware platform
7625 */
7626 char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007627default_shell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007628{
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007629 return "cmd.exe";
Bram Moolenaar071d4272004-06-13 20:20:40 +00007630}
7631
7632/*
7633 * mch_access() extends access() to do more detailed check on network drives.
7634 * Returns 0 if file "n" has access rights according to "p", -1 otherwise.
7635 */
7636 int
7637mch_access(char *n, int p)
7638{
7639 HANDLE hFile;
Bram Moolenaar0f873732019-12-05 20:28:46 +01007640 int retval = -1; // default: fail
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007641 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007642
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007643 wn = enc_to_utf16((char_u *)n, NULL);
7644 if (wn == NULL)
7645 return -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007646
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01007647 if (mch_isdir((char_u *)n))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007648 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00007649 WCHAR TempNameW[_MAX_PATH + 16] = L"";
Bram Moolenaar071d4272004-06-13 20:20:40 +00007650
7651 if (p & R_OK)
7652 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007653 // Read check is performed by seeing if we can do a find file on
7654 // the directory for any file.
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007655 int i;
7656 WIN32_FIND_DATAW d;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007657
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007658 for (i = 0; i < _MAX_PATH && wn[i] != 0; ++i)
7659 TempNameW[i] = wn[i];
7660 if (TempNameW[i - 1] != '\\' && TempNameW[i - 1] != '/')
7661 TempNameW[i++] = '\\';
7662 TempNameW[i++] = '*';
7663 TempNameW[i++] = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007664
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007665 hFile = FindFirstFileW(TempNameW, &d);
7666 if (hFile == INVALID_HANDLE_VALUE)
7667 goto getout;
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007668 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00007669 (void)FindClose(hFile);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007670 }
7671
7672 if (p & W_OK)
7673 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007674 // Trying to create a temporary file in the directory should catch
7675 // directories on read-only network shares. However, in
7676 // directories whose ACL allows writes but denies deletes will end
7677 // up keeping the temporary file :-(.
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007678 if (!GetTempFileNameW(wn, L"VIM", 0, TempNameW))
7679 goto getout;
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007680 else
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007681 DeleteFileW(TempNameW);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007682 }
7683 }
7684 else
7685 {
Bram Moolenaar5aa98962018-05-06 17:09:38 +02007686 // Don't consider a file read-only if another process has opened it.
7687 DWORD share_mode = FILE_SHARE_READ | FILE_SHARE_WRITE;
7688
Bram Moolenaar0f873732019-12-05 20:28:46 +01007689 // Trying to open the file for the required access does ACL, read-only
7690 // network share, and file attribute checks.
Bram Moolenaar5aa98962018-05-06 17:09:38 +02007691 DWORD access_mode = ((p & W_OK) ? GENERIC_WRITE : 0)
7692 | ((p & R_OK) ? GENERIC_READ : 0);
7693
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007694 hFile = CreateFileW(wn, access_mode, share_mode,
7695 NULL, OPEN_EXISTING, 0, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007696 if (hFile == INVALID_HANDLE_VALUE)
7697 goto getout;
7698 CloseHandle(hFile);
7699 }
7700
Bram Moolenaar0f873732019-12-05 20:28:46 +01007701 retval = 0; // success
Bram Moolenaar071d4272004-06-13 20:20:40 +00007702getout:
Bram Moolenaar071d4272004-06-13 20:20:40 +00007703 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007704 return retval;
7705}
7706
Bram Moolenaar071d4272004-06-13 20:20:40 +00007707/*
Bram Moolenaar36f692d2008-11-20 16:10:17 +00007708 * Version of open() that may use UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007709 */
7710 int
Bram Moolenaarb6843a02017-08-02 22:07:12 +02007711mch_open(const char *name, int flags, int mode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007712{
7713 WCHAR *wn;
7714 int f;
7715
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007716 wn = enc_to_utf16((char_u *)name, NULL);
7717 if (wn == NULL)
7718 return -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007719
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007720 f = _wopen(wn, flags, mode);
7721 vim_free(wn);
7722 return f;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007723}
7724
7725/*
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007726 * Version of fopen() that uses UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007727 */
7728 FILE *
Bram Moolenaarb6843a02017-08-02 22:07:12 +02007729mch_fopen(const char *name, const char *mode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007730{
7731 WCHAR *wn, *wm;
7732 FILE *f = NULL;
7733
Bram Moolenaara12a1612019-01-24 16:39:02 +01007734#if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0f873732019-12-05 20:28:46 +01007735 // Work around an annoying assertion in the Microsoft debug CRT
7736 // when mode's text/binary setting doesn't match _get_fmode().
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007737 char newMode = mode[strlen(mode) - 1];
7738 int oldMode = 0;
Bram Moolenaar0fde2902008-03-16 13:54:13 +00007739
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007740 _get_fmode(&oldMode);
7741 if (newMode == 't')
7742 _set_fmode(_O_TEXT);
7743 else if (newMode == 'b')
7744 _set_fmode(_O_BINARY);
Bram Moolenaara12a1612019-01-24 16:39:02 +01007745#endif
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007746 wn = enc_to_utf16((char_u *)name, NULL);
7747 wm = enc_to_utf16((char_u *)mode, NULL);
7748 if (wn != NULL && wm != NULL)
7749 f = _wfopen(wn, wm);
7750 vim_free(wn);
7751 vim_free(wm);
Bram Moolenaar0fde2902008-03-16 13:54:13 +00007752
Bram Moolenaara12a1612019-01-24 16:39:02 +01007753#if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007754 _set_fmode(oldMode);
Bram Moolenaara12a1612019-01-24 16:39:02 +01007755#endif
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007756 return f;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007757}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007758
Bram Moolenaar071d4272004-06-13 20:20:40 +00007759/*
7760 * SUB STREAM (aka info stream) handling:
7761 *
Bram Moolenaar8e7d6222020-12-18 19:49:56 +01007762 * NTFS can have sub streams for each file. The normal contents of a file is
7763 * stored in the main stream, and extra contents (author information, title and
7764 * so on) can be stored in a sub stream. After Windows 2000, the user can
7765 * access and store this information in sub streams via an explorer's property
7766 * menu item in the right click menu. This information in sub streams was lost
7767 * when copying only the main stream. Therefore we have to copy sub streams.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007768 *
7769 * Incomplete explanation:
7770 * http://msdn.microsoft.com/library/en-us/dnw2k/html/ntfs5.asp
7771 * More useful info and an example:
7772 * http://www.sysinternals.com/ntw2k/source/misc.shtml#streams
7773 */
7774
7775/*
7776 * Copy info stream data "substream". Read from the file with BackupRead(sh)
7777 * and write to stream "substream" of file "to".
7778 * Errors are ignored.
7779 */
7780 static void
7781copy_substream(HANDLE sh, void *context, WCHAR *to, WCHAR *substream, long len)
7782{
7783 HANDLE hTo;
7784 WCHAR *to_name;
7785
7786 to_name = malloc((wcslen(to) + wcslen(substream) + 1) * sizeof(WCHAR));
7787 wcscpy(to_name, to);
7788 wcscat(to_name, substream);
7789
7790 hTo = CreateFileW(to_name, GENERIC_WRITE, 0, NULL, OPEN_ALWAYS,
7791 FILE_ATTRIBUTE_NORMAL, NULL);
7792 if (hTo != INVALID_HANDLE_VALUE)
7793 {
7794 long done;
7795 DWORD todo;
7796 DWORD readcnt, written;
7797 char buf[4096];
7798
Bram Moolenaar0f873732019-12-05 20:28:46 +01007799 // Copy block of bytes at a time. Abort when something goes wrong.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007800 for (done = 0; done < len; done += written)
7801 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007802 // (size_t) cast for Borland C 5.5
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007803 todo = (DWORD)((size_t)(len - done) > sizeof(buf) ? sizeof(buf)
7804 : (size_t)(len - done));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007805 if (!BackupRead(sh, (LPBYTE)buf, todo, &readcnt,
7806 FALSE, FALSE, context)
7807 || readcnt != todo
7808 || !WriteFile(hTo, buf, todo, &written, NULL)
7809 || written != todo)
7810 break;
7811 }
7812 CloseHandle(hTo);
7813 }
7814
7815 free(to_name);
7816}
7817
7818/*
7819 * Copy info streams from file "from" to file "to".
7820 */
7821 static void
7822copy_infostreams(char_u *from, char_u *to)
7823{
7824 WCHAR *fromw;
7825 WCHAR *tow;
7826 HANDLE sh;
7827 WIN32_STREAM_ID sid;
7828 int headersize;
7829 WCHAR streamname[_MAX_PATH];
7830 DWORD readcount;
7831 void *context = NULL;
7832 DWORD lo, hi;
7833 int len;
7834
Bram Moolenaar0f873732019-12-05 20:28:46 +01007835 // Convert the file names to wide characters.
Bram Moolenaar36f692d2008-11-20 16:10:17 +00007836 fromw = enc_to_utf16(from, NULL);
7837 tow = enc_to_utf16(to, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007838 if (fromw != NULL && tow != NULL)
7839 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007840 // Open the file for reading.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007841 sh = CreateFileW(fromw, GENERIC_READ, FILE_SHARE_READ, NULL,
7842 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
7843 if (sh != INVALID_HANDLE_VALUE)
7844 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007845 // Use BackupRead() to find the info streams. Repeat until we
7846 // have done them all.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007847 for (;;)
7848 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007849 // Get the header to find the length of the stream name. If
7850 // the "readcount" is zero we have done all info streams.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007851 ZeroMemory(&sid, sizeof(WIN32_STREAM_ID));
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007852 headersize = (int)((char *)&sid.cStreamName - (char *)&sid.dwStreamId);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007853 if (!BackupRead(sh, (LPBYTE)&sid, headersize,
7854 &readcount, FALSE, FALSE, &context)
7855 || readcount == 0)
7856 break;
7857
Bram Moolenaar0f873732019-12-05 20:28:46 +01007858 // We only deal with streams that have a name. The normal
7859 // file data appears to be without a name, even though docs
7860 // suggest it is called "::$DATA".
Bram Moolenaar071d4272004-06-13 20:20:40 +00007861 if (sid.dwStreamNameSize > 0)
7862 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007863 // Read the stream name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007864 if (!BackupRead(sh, (LPBYTE)streamname,
7865 sid.dwStreamNameSize,
7866 &readcount, FALSE, FALSE, &context))
7867 break;
7868
Bram Moolenaar0f873732019-12-05 20:28:46 +01007869 // Copy an info stream with a name ":anything:$DATA".
7870 // Skip "::$DATA", it has no stream name (examples suggest
7871 // it might be used for the normal file contents).
7872 // Note that BackupRead() counts bytes, but the name is in
7873 // wide characters.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007874 len = readcount / sizeof(WCHAR);
7875 streamname[len] = 0;
7876 if (len > 7 && wcsicmp(streamname + len - 6,
7877 L":$DATA") == 0)
7878 {
7879 streamname[len - 6] = 0;
7880 copy_substream(sh, &context, tow, streamname,
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00007881 (long)sid.Size.u.LowPart);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007882 }
7883 }
7884
Bram Moolenaar0f873732019-12-05 20:28:46 +01007885 // Advance to the next stream. We might try seeking too far,
7886 // but BackupSeek() doesn't skip over stream borders, thus
7887 // that's OK.
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00007888 (void)BackupSeek(sh, sid.Size.u.LowPart, sid.Size.u.HighPart,
Bram Moolenaar071d4272004-06-13 20:20:40 +00007889 &lo, &hi, &context);
7890 }
7891
Bram Moolenaar0f873732019-12-05 20:28:46 +01007892 // Clear the context.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007893 (void)BackupRead(sh, NULL, 0, &readcount, TRUE, FALSE, &context);
7894
7895 CloseHandle(sh);
7896 }
7897 }
7898 vim_free(fromw);
7899 vim_free(tow);
7900}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007901
7902/*
Bram Moolenaare7bebc42021-02-01 20:50:37 +01007903 * ntdll.dll definitions
7904 */
7905#define FileEaInformation 7
7906#ifndef STATUS_SUCCESS
7907# define STATUS_SUCCESS ((NTSTATUS) 0x00000000L)
7908#endif
7909
7910typedef struct _FILE_FULL_EA_INFORMATION_ {
7911 ULONG NextEntryOffset;
7912 UCHAR Flags;
7913 UCHAR EaNameLength;
7914 USHORT EaValueLength;
7915 CHAR EaName[1];
7916} FILE_FULL_EA_INFORMATION_, *PFILE_FULL_EA_INFORMATION_;
7917
7918typedef struct _FILE_EA_INFORMATION_ {
7919 ULONG EaSize;
7920} FILE_EA_INFORMATION_, *PFILE_EA_INFORMATION_;
7921
Paul Ollis65745772022-06-05 16:55:54 +01007922#ifndef PROTO
Bram Moolenaare7bebc42021-02-01 20:50:37 +01007923typedef NTSTATUS (NTAPI *PfnNtOpenFile)(
7924 PHANDLE FileHandle,
7925 ACCESS_MASK DesiredAccess,
7926 POBJECT_ATTRIBUTES ObjectAttributes,
7927 PIO_STATUS_BLOCK IoStatusBlock,
7928 ULONG ShareAccess,
7929 ULONG OpenOptions);
7930typedef NTSTATUS (NTAPI *PfnNtClose)(
7931 HANDLE Handle);
7932typedef NTSTATUS (NTAPI *PfnNtSetEaFile)(
Bram Moolenaar9f1983d2022-05-12 20:35:35 +01007933 HANDLE FileHandle,
7934 PIO_STATUS_BLOCK IoStatusBlock,
7935 PVOID Buffer,
7936 ULONG Length);
Bram Moolenaare7bebc42021-02-01 20:50:37 +01007937typedef NTSTATUS (NTAPI *PfnNtQueryEaFile)(
7938 HANDLE FileHandle,
7939 PIO_STATUS_BLOCK IoStatusBlock,
7940 PVOID Buffer,
7941 ULONG Length,
7942 BOOLEAN ReturnSingleEntry,
7943 PVOID EaList,
7944 ULONG EaListLength,
7945 PULONG EaIndex,
7946 BOOLEAN RestartScan);
7947typedef NTSTATUS (NTAPI *PfnNtQueryInformationFile)(
Bram Moolenaar9f1983d2022-05-12 20:35:35 +01007948 HANDLE FileHandle,
7949 PIO_STATUS_BLOCK IoStatusBlock,
7950 PVOID FileInformation,
7951 ULONG Length,
Bram Moolenaare7bebc42021-02-01 20:50:37 +01007952 FILE_INFORMATION_CLASS FileInformationClass);
7953typedef VOID (NTAPI *PfnRtlInitUnicodeString)(
7954 PUNICODE_STRING DestinationString,
7955 PCWSTR SourceString);
7956
7957PfnNtOpenFile pNtOpenFile = NULL;
7958PfnNtClose pNtClose = NULL;
7959PfnNtSetEaFile pNtSetEaFile = NULL;
7960PfnNtQueryEaFile pNtQueryEaFile = NULL;
7961PfnNtQueryInformationFile pNtQueryInformationFile = NULL;
7962PfnRtlInitUnicodeString pRtlInitUnicodeString = NULL;
Paul Ollis65745772022-06-05 16:55:54 +01007963#endif
Bram Moolenaare7bebc42021-02-01 20:50:37 +01007964
7965/*
7966 * Load ntdll.dll functions.
7967 */
7968 static BOOL
7969load_ntdll(void)
7970{
7971 static int loaded = -1;
7972
7973 if (loaded == -1)
7974 {
7975 HMODULE hNtdll = GetModuleHandle("ntdll.dll");
7976 if (hNtdll != NULL)
7977 {
7978 pNtOpenFile = (PfnNtOpenFile) GetProcAddress(hNtdll, "NtOpenFile");
7979 pNtClose = (PfnNtClose) GetProcAddress(hNtdll, "NtClose");
7980 pNtSetEaFile = (PfnNtSetEaFile)
7981 GetProcAddress(hNtdll, "NtSetEaFile");
7982 pNtQueryEaFile = (PfnNtQueryEaFile)
7983 GetProcAddress(hNtdll, "NtQueryEaFile");
7984 pNtQueryInformationFile = (PfnNtQueryInformationFile)
7985 GetProcAddress(hNtdll, "NtQueryInformationFile");
7986 pRtlInitUnicodeString = (PfnRtlInitUnicodeString)
7987 GetProcAddress(hNtdll, "RtlInitUnicodeString");
7988 }
7989 if (pNtOpenFile == NULL
7990 || pNtClose == NULL
7991 || pNtSetEaFile == NULL
7992 || pNtQueryEaFile == NULL
7993 || pNtQueryInformationFile == NULL
7994 || pRtlInitUnicodeString == NULL)
7995 loaded = FALSE;
7996 else
7997 loaded = TRUE;
7998 }
7999 return (BOOL) loaded;
8000}
8001
8002/*
8003 * Copy extended attributes (EA) from file "from" to file "to".
8004 */
8005 static void
8006copy_extattr(char_u *from, char_u *to)
8007{
8008 char_u *fromf = NULL;
8009 char_u *tof = NULL;
8010 WCHAR *fromw = NULL;
8011 WCHAR *tow = NULL;
8012 UNICODE_STRING u;
8013 HANDLE h;
8014 OBJECT_ATTRIBUTES oa;
8015 IO_STATUS_BLOCK iosb;
8016 FILE_EA_INFORMATION_ eainfo = {0};
8017 void *ea = NULL;
8018
8019 if (!load_ntdll())
8020 return;
8021
8022 // Convert the file names to the fully qualified object names.
8023 fromf = alloc(STRLEN(from) + 5);
8024 tof = alloc(STRLEN(to) + 5);
8025 if (fromf == NULL || tof == NULL)
8026 goto theend;
8027 STRCPY(fromf, "\\??\\");
8028 STRCAT(fromf, from);
8029 STRCPY(tof, "\\??\\");
8030 STRCAT(tof, to);
8031
8032 // Convert the names to wide characters.
8033 fromw = enc_to_utf16(fromf, NULL);
8034 tow = enc_to_utf16(tof, NULL);
8035 if (fromw == NULL || tow == NULL)
8036 goto theend;
8037
8038 // Get the EA.
8039 pRtlInitUnicodeString(&u, fromw);
8040 InitializeObjectAttributes(&oa, &u, 0, NULL, NULL);
8041 if (pNtOpenFile(&h, FILE_READ_EA, &oa, &iosb, 0,
8042 FILE_NON_DIRECTORY_FILE) != STATUS_SUCCESS)
8043 goto theend;
8044 pNtQueryInformationFile(h, &iosb, &eainfo, sizeof(eainfo),
8045 FileEaInformation);
8046 if (eainfo.EaSize != 0)
8047 {
8048 ea = alloc(eainfo.EaSize);
8049 if (ea != NULL)
8050 {
8051 if (pNtQueryEaFile(h, &iosb, ea, eainfo.EaSize, FALSE,
8052 NULL, 0, NULL, TRUE) != STATUS_SUCCESS)
8053 {
8054 vim_free(ea);
8055 ea = NULL;
8056 }
8057 }
8058 }
8059 pNtClose(h);
8060
8061 // Set the EA.
8062 if (ea != NULL)
8063 {
8064 pRtlInitUnicodeString(&u, tow);
8065 InitializeObjectAttributes(&oa, &u, 0, NULL, NULL);
8066 if (pNtOpenFile(&h, FILE_WRITE_EA, &oa, &iosb, 0,
8067 FILE_NON_DIRECTORY_FILE) != STATUS_SUCCESS)
8068 goto theend;
8069
8070 pNtSetEaFile(h, &iosb, ea, eainfo.EaSize);
8071 pNtClose(h);
8072 }
8073
8074theend:
8075 vim_free(fromf);
8076 vim_free(tof);
8077 vim_free(fromw);
8078 vim_free(tow);
8079 vim_free(ea);
8080}
8081
8082/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00008083 * Copy file attributes from file "from" to file "to".
8084 * For Windows NT and later we copy info streams.
8085 * Always returns zero, errors are ignored.
8086 */
8087 int
8088mch_copy_file_attribute(char_u *from, char_u *to)
8089{
Bram Moolenaar0f873732019-12-05 20:28:46 +01008090 // File streams only work on Windows NT and later.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02008091 copy_infostreams(from, to);
Bram Moolenaare7bebc42021-02-01 20:50:37 +01008092 copy_extattr(from, to);
Bram Moolenaar071d4272004-06-13 20:20:40 +00008093 return 0;
8094}
8095
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008096
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008097/*
K.Takatadc73b4b2021-06-08 18:32:36 +02008098 * The command line arguments in UTF-16
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008099 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00008100static int nArgsW = 0;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008101static LPWSTR *ArglistW = NULL;
8102static int global_argc = 0;
8103static char **global_argv;
8104
Bram Moolenaar0f873732019-12-05 20:28:46 +01008105static int used_file_argc = 0; // last argument in global_argv[] used
8106 // for the argument list.
8107static int *used_file_indexes = NULL; // indexes in global_argv[] for
8108 // command line arguments added to
8109 // the argument list
8110static int used_file_count = 0; // nr of entries in used_file_indexes
8111static int used_file_literal = FALSE; // take file names literally
8112static int used_file_full_path = FALSE; // file name was full path
8113static int used_file_diff_mode = FALSE; // file name was with diff mode
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008114static int used_alist_count = 0;
8115
8116
8117/*
8118 * Get the command line arguments. Unicode version.
8119 * Returns argc. Zero when something fails.
8120 */
8121 int
8122get_cmd_argsW(char ***argvp)
8123{
8124 char **argv = NULL;
8125 int argc = 0;
8126 int i;
8127
Bram Moolenaar14993322014-09-09 12:25:33 +02008128 free_cmd_argsW();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008129 ArglistW = CommandLineToArgvW(GetCommandLineW(), &nArgsW);
8130 if (ArglistW != NULL)
8131 {
8132 argv = malloc((nArgsW + 1) * sizeof(char *));
8133 if (argv != NULL)
8134 {
8135 argc = nArgsW;
8136 argv[argc] = NULL;
8137 for (i = 0; i < argc; ++i)
8138 {
8139 int len;
8140
K.Takatadc73b4b2021-06-08 18:32:36 +02008141 // Convert each Unicode argument to UTF-8.
8142 WideCharToMultiByte_alloc(CP_UTF8, 0,
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00008143 ArglistW[i], (int)wcslen(ArglistW[i]) + 1,
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008144 (LPSTR *)&argv[i], &len, 0, 0);
8145 if (argv[i] == NULL)
8146 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01008147 // Out of memory, clear everything.
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008148 while (i > 0)
8149 free(argv[--i]);
8150 free(argv);
Bram Moolenaar73c61632013-12-07 14:48:10 +01008151 argv = NULL;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008152 argc = 0;
8153 }
8154 }
8155 }
8156 }
8157
8158 global_argc = argc;
8159 global_argv = argv;
8160 if (argc > 0)
Bram Moolenaar14993322014-09-09 12:25:33 +02008161 {
8162 if (used_file_indexes != NULL)
8163 free(used_file_indexes);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008164 used_file_indexes = malloc(argc * sizeof(int));
Bram Moolenaar14993322014-09-09 12:25:33 +02008165 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008166
8167 if (argvp != NULL)
8168 *argvp = argv;
8169 return argc;
8170}
8171
8172 void
8173free_cmd_argsW(void)
8174{
8175 if (ArglistW != NULL)
8176 {
8177 GlobalFree(ArglistW);
8178 ArglistW = NULL;
8179 }
8180}
8181
8182/*
8183 * Remember "name" is an argument that was added to the argument list.
8184 * This avoids that we have to re-parse the argument list when fix_arg_enc()
8185 * is called.
8186 */
8187 void
Bram Moolenaar910f66f2006-04-05 20:41:53 +00008188used_file_arg(char *name, int literal, int full_path, int diff_mode)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008189{
8190 int i;
8191
8192 if (used_file_indexes == NULL)
8193 return;
8194 for (i = used_file_argc + 1; i < global_argc; ++i)
8195 if (STRCMP(global_argv[i], name) == 0)
8196 {
8197 used_file_argc = i;
8198 used_file_indexes[used_file_count++] = i;
8199 break;
8200 }
8201 used_file_literal = literal;
8202 used_file_full_path = full_path;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00008203 used_file_diff_mode = diff_mode;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008204}
8205
8206/*
8207 * Remember the length of the argument list as it was. If it changes then we
8208 * leave it alone when 'encoding' is set.
8209 */
8210 void
8211set_alist_count(void)
8212{
8213 used_alist_count = GARGCOUNT;
8214}
8215
8216/*
8217 * Fix the encoding of the command line arguments. Invoked when 'encoding'
K.Takatadc73b4b2021-06-08 18:32:36 +02008218 * has been changed while starting up. Use the UTF-16 command line arguments
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008219 * and convert them to 'encoding'.
8220 */
8221 void
8222fix_arg_enc(void)
8223{
8224 int i;
8225 int idx;
8226 char_u *str;
Bram Moolenaar86b68352004-12-27 21:59:20 +00008227 int *fnum_list;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008228
Bram Moolenaar0f873732019-12-05 20:28:46 +01008229 // Safety checks:
8230 // - if argument count differs between the wide and non-wide argument
8231 // list, something must be wrong.
8232 // - the file name arguments must have been located.
8233 // - the length of the argument list wasn't changed by the user.
Bram Moolenaard857f0e2005-06-21 22:37:39 +00008234 if (global_argc != nArgsW
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008235 || ArglistW == NULL
8236 || used_file_indexes == NULL
8237 || used_file_count == 0
8238 || used_alist_count != GARGCOUNT)
8239 return;
8240
Bram Moolenaar0f873732019-12-05 20:28:46 +01008241 // Remember the buffer numbers for the arguments.
Bram Moolenaarc799fe22019-05-28 23:08:19 +02008242 fnum_list = ALLOC_MULT(int, GARGCOUNT);
Bram Moolenaar86b68352004-12-27 21:59:20 +00008243 if (fnum_list == NULL)
Bram Moolenaar0f873732019-12-05 20:28:46 +01008244 return; // out of memory
Bram Moolenaar86b68352004-12-27 21:59:20 +00008245 for (i = 0; i < GARGCOUNT; ++i)
8246 fnum_list[i] = GARGLIST[i].ae_fnum;
8247
Bram Moolenaar0f873732019-12-05 20:28:46 +01008248 // Clear the argument list. Make room for the new arguments.
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008249 alist_clear(&global_alist);
8250 if (ga_grow(&global_alist.al_ga, used_file_count) == FAIL)
Bram Moolenaar0f873732019-12-05 20:28:46 +01008251 return; // out of memory
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008252
8253 for (i = 0; i < used_file_count; ++i)
8254 {
8255 idx = used_file_indexes[i];
Bram Moolenaar36f692d2008-11-20 16:10:17 +00008256 str = utf16_to_enc(ArglistW[idx], NULL);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008257 if (str != NULL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00008258 {
Bram Moolenaar39d21e32017-08-05 23:09:31 +02008259 int literal = used_file_literal;
8260
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01008261#ifdef FEAT_DIFF
Bram Moolenaar0f873732019-12-05 20:28:46 +01008262 // When using diff mode may need to concatenate file name to
8263 // directory name. Just like it's done in main().
Bram Moolenaar910f66f2006-04-05 20:41:53 +00008264 if (used_file_diff_mode && mch_isdir(str) && GARGCOUNT > 0
8265 && !mch_isdir(alist_name(&GARGLIST[0])))
8266 {
8267 char_u *r;
8268
8269 r = concat_fnames(str, gettail(alist_name(&GARGLIST[0])), TRUE);
8270 if (r != NULL)
8271 {
8272 vim_free(str);
8273 str = r;
8274 }
8275 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01008276#endif
Bram Moolenaar0f873732019-12-05 20:28:46 +01008277 // Re-use the old buffer by renaming it. When not using literal
8278 // names it's done by alist_expand() below.
Bram Moolenaar86b68352004-12-27 21:59:20 +00008279 if (used_file_literal)
8280 buf_set_name(fnum_list[i], str);
8281
Bram Moolenaar0f873732019-12-05 20:28:46 +01008282 // Check backtick literal. backtick literal is already expanded in
8283 // main.c, so this part add str as literal.
Bram Moolenaar39d21e32017-08-05 23:09:31 +02008284 if (literal == FALSE)
8285 {
Bram Moolenaar116a0f82017-08-07 21:17:57 +02008286 size_t len = STRLEN(str);
8287
Bram Moolenaar39d21e32017-08-05 23:09:31 +02008288 if (len > 2 && *str == '`' && *(str + len - 1) == '`')
8289 literal = TRUE;
8290 }
8291 alist_add(&global_alist, str, literal ? 2 : 0);
Bram Moolenaar86b68352004-12-27 21:59:20 +00008292 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008293 }
8294
8295 if (!used_file_literal)
8296 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01008297 // Now expand wildcards in the arguments.
8298 // Temporarily add '(' and ')' to 'isfname'. These are valid
8299 // filename characters but are excluded from 'isfname' to make
Dominique Pelleaf4a61a2021-12-27 17:21:41 +00008300 // "gf" work on a file name in parentheses (e.g.: see vim.h).
Bram Moolenaar0f873732019-12-05 20:28:46 +01008301 // Also, unset wildignore to not be influenced by this option.
8302 // The arguments specified in command-line should be kept even if
8303 // encoding options were changed.
Christian Brabandtfd916d62021-11-01 22:44:33 +00008304 // Use :legacy so that it also works when in Vim9 script.
8305 do_cmdline_cmd((char_u *)":legacy let g:SaVe_ISF = &isf|set isf+=(,)");
8306 do_cmdline_cmd((char_u *)":legacy let g:SaVe_WIG = &wig|set wig=");
Bram Moolenaar86b68352004-12-27 21:59:20 +00008307 alist_expand(fnum_list, used_alist_count);
Christian Brabandtfd916d62021-11-01 22:44:33 +00008308 do_cmdline_cmd(
8309 (char_u *)":legacy let &isf = g:SaVe_ISF|unlet g:SaVe_ISF");
8310 do_cmdline_cmd(
8311 (char_u *)":legacy let &wig = g:SaVe_WIG|unlet g:SaVe_WIG");
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008312 }
8313
Bram Moolenaar0f873732019-12-05 20:28:46 +01008314 // If wildcard expansion failed, we are editing the first file of the
8315 // arglist and there is no file name: Edit the first argument now.
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008316 if (curwin->w_arg_idx == 0 && curbuf->b_fname == NULL)
8317 {
8318 do_cmdline_cmd((char_u *)":rewind");
Bram Moolenaar05268152021-11-18 18:53:45 +00008319 if (GARGCOUNT == 1 && used_file_full_path
8320 && vim_chdirfile(alist_name(&GARGLIST[0]), "drop") == OK)
8321 last_chdir_reason = "drop";
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008322 }
Bram Moolenaar86b68352004-12-27 21:59:20 +00008323
8324 set_alist_count();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008325}
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01008326
8327 int
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02008328mch_setenv(char *var, char *value, int x UNUSED)
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01008329{
8330 char_u *envbuf;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02008331 WCHAR *p;
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01008332
Bram Moolenaar964b3742019-05-24 18:54:09 +02008333 envbuf = alloc(STRLEN(var) + STRLEN(value) + 2);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01008334 if (envbuf == NULL)
8335 return -1;
8336
8337 sprintf((char *)envbuf, "%s=%s", var, value);
8338
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02008339 p = enc_to_utf16(envbuf, NULL);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01008340
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02008341 vim_free(envbuf);
8342 if (p == NULL)
8343 return -1;
8344 _wputenv(p);
Bram Moolenaara12a1612019-01-24 16:39:02 +01008345#ifdef libintl_wputenv
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02008346 libintl_wputenv(p);
Bram Moolenaara12a1612019-01-24 16:39:02 +01008347#endif
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02008348 // Unlike Un*x systems, we can free the string for _wputenv().
8349 vim_free(p);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01008350
8351 return 0;
8352}
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008353
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008354/*
8355 * Support for 256 colors and 24-bit colors was added in Windows 10
8356 * version 1703 (Creators update).
8357 */
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008358#define VTP_FIRST_SUPPORT_BUILD MAKE_VER(10, 0, 15063)
8359
8360/*
8361 * Support for pseudo-console (ConPTY) was added in windows 10
Bram Moolenaar57da6982019-09-13 22:30:11 +02008362 * version 1809 (October 2018 update).
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008363 */
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01008364#define CONPTY_FIRST_SUPPORT_BUILD MAKE_VER(10, 0, 17763)
Bram Moolenaar57da6982019-09-13 22:30:11 +02008365
8366/*
8367 * ConPTY differences between versions, need different logic.
8368 * version 1903 (May 2019 update).
8369 */
8370#define CONPTY_1903_BUILD MAKE_VER(10, 0, 18362)
8371
8372/*
Bram Moolenaar36e7a822019-11-13 21:49:24 +01008373 * version 1909 (November 2019 update).
8374 */
8375#define CONPTY_1909_BUILD MAKE_VER(10, 0, 18363)
8376
8377/*
Bram Moolenaar7ed8f592020-04-28 20:44:42 +02008378 * Stay ahead of the next update, and when it's done, fix this.
8379 * version ? (2020 update, temporarily use the build number of insider preview)
8380 */
8381#define CONPTY_NEXT_UPDATE_BUILD MAKE_VER(10, 0, 19587)
8382
8383/*
Bram Moolenaar57da6982019-09-13 22:30:11 +02008384 * Confirm until this version. Also the logic changes.
8385 * insider preview.
8386 */
Bram Moolenaar4c063dd2019-10-04 21:29:12 +02008387#define CONPTY_INSIDER_BUILD MAKE_VER(10, 0, 18995)
Bram Moolenaar57da6982019-09-13 22:30:11 +02008388
8389/*
8390 * Not stable now.
8391 */
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01008392#define CONPTY_STABLE_BUILD MAKE_VER(10, 0, 32767) // T.B.D.
Christopher Plewright1140b512022-11-12 18:46:05 +00008393// Notes:
8394// Win 10 22H2 Final is build 19045, it's conpty is widely used.
8395// Strangely, 19045 is newer but is a lower build number than the 2020 insider
8396// preview which had a build 19587. And, not sure how stable that was?
8397// Win Server 2022 (May 10, 2022) is build 20348, its conpty is widely used.
8398// Win 11 starts from build 22000, even though the major version says 10!
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008399
8400 static void
8401vtp_flag_init(void)
8402{
8403 DWORD ver = get_build_number();
Bram Moolenaarafde13b2019-04-28 19:46:49 +02008404#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008405 DWORD mode;
8406 HANDLE out;
8407
Bram Moolenaarafde13b2019-04-28 19:46:49 +02008408# ifdef VIMDLL
8409 if (!gui.in_use)
8410# endif
8411 {
8412 out = GetStdHandle(STD_OUTPUT_HANDLE);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008413
Bram Moolenaarafde13b2019-04-28 19:46:49 +02008414 vtp_working = (ver >= VTP_FIRST_SUPPORT_BUILD) ? 1 : 0;
8415 GetConsoleMode(out, &mode);
8416 mode |= (ENABLE_PROCESSED_OUTPUT | ENABLE_VIRTUAL_TERMINAL_PROCESSING);
8417 if (SetConsoleMode(out, mode) == 0)
8418 vtp_working = 0;
8419 }
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008420#endif
8421
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008422 if (ver >= CONPTY_FIRST_SUPPORT_BUILD)
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01008423 conpty_working = 1;
8424 if (ver >= CONPTY_STABLE_BUILD)
8425 conpty_stable = 1;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008426
Bram Moolenaar57da6982019-09-13 22:30:11 +02008427 if (ver <= CONPTY_INSIDER_BUILD)
8428 conpty_type = 3;
Bram Moolenaar36e7a822019-11-13 21:49:24 +01008429 if (ver <= CONPTY_1909_BUILD)
8430 conpty_type = 2;
Bram Moolenaar57da6982019-09-13 22:30:11 +02008431 if (ver <= CONPTY_1903_BUILD)
8432 conpty_type = 2;
8433 if (ver < CONPTY_FIRST_SUPPORT_BUILD)
8434 conpty_type = 1;
Bram Moolenaar7ed8f592020-04-28 20:44:42 +02008435
8436 if (ver >= CONPTY_NEXT_UPDATE_BUILD)
8437 conpty_fix_type = 1;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008438}
8439
Bram Moolenaarafde13b2019-04-28 19:46:49 +02008440#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL) || defined(PROTO)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008441
8442 static void
8443vtp_init(void)
8444{
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02008445# ifdef FEAT_TERMGUICOLORS
Christopher Plewright38804d62022-11-09 23:55:52 +00008446 if (!vtp_working)
Yasuhiro Matsumotoe42c8da2022-09-01 11:31:45 +01008447 {
Christopher Plewright38804d62022-11-09 23:55:52 +00008448 CONSOLE_SCREEN_BUFFER_INFOEX csbi;
8449 csbi.cbSize = sizeof(csbi);
8450 GetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
8451 save_console_bg_rgb = (guicolor_T)csbi.ColorTable[g_color_index_bg];
8452 save_console_fg_rgb = (guicolor_T)csbi.ColorTable[g_color_index_fg];
8453 store_console_bg_rgb = save_console_bg_rgb;
8454 store_console_fg_rgb = save_console_fg_rgb;
8455
Yasuhiro Matsumotoe42c8da2022-09-01 11:31:45 +01008456 COLORREF bg;
8457 bg = (COLORREF)csbi.ColorTable[g_color_index_bg];
8458 bg = (GetRValue(bg) << 16) | (GetGValue(bg) << 8) | GetBValue(bg);
8459 default_console_color_bg = bg;
Christopher Plewright38804d62022-11-09 23:55:52 +00008460
8461 COLORREF fg;
8462 fg = (COLORREF)csbi.ColorTable[g_color_index_fg];
8463 fg = (GetRValue(fg) << 16) | (GetGValue(fg) << 8) | GetBValue(fg);
8464 default_console_color_fg = fg;
Yasuhiro Matsumotoe42c8da2022-09-01 11:31:45 +01008465 }
Bram Moolenaarc4568ab2018-11-16 16:21:05 +01008466# endif
Christopher Plewrightc8b126d2022-12-22 13:45:23 +00008467 use_alternate_screen_buffer = win10_22H2_or_later && p_rs && vtp_working
Bram Moolenaar9fca1332022-12-22 21:06:41 +00008468 && !mch_getenv("VIM_TERMINAL");
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008469 set_console_color_rgb();
8470}
8471
8472 static void
8473vtp_exit(void)
8474{
Bram Moolenaardf543822020-01-30 11:53:59 +01008475 restore_console_color_rgb();
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008476}
8477
Bram Moolenaar06b7b582020-05-30 17:49:25 +02008478 int
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008479vtp_printf(
8480 char *format,
8481 ...)
8482{
8483 char_u buf[100];
8484 va_list list;
8485 DWORD result;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008486 int len;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008487
8488 va_start(list, format);
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008489 len = vim_vsnprintf((char *)buf, 100, (char *)format, list);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008490 va_end(list);
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008491 WriteConsoleA(g_hConOut, buf, (DWORD)len, &result, NULL);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008492 return (int)result;
8493}
8494
8495 static void
8496vtp_sgr_bulk(
8497 int arg)
8498{
8499 int args[1];
8500
8501 args[0] = arg;
8502 vtp_sgr_bulks(1, args);
8503}
8504
K.Takata6e1d31e2022-02-03 13:05:32 +00008505# define FAST256(x) \
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008506 if ((*p-- = "0123456789"[(n = x % 10)]) \
8507 && x >= 10 && (*p-- = "0123456789"[((m = x % 100) - n) / 10]) \
8508 && x >= 100 && (*p-- = "012"[((x & 0xff) - m) / 100]));
8509
K.Takata6e1d31e2022-02-03 13:05:32 +00008510# define FAST256CASE(x) \
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008511 case x: \
8512 FAST256(newargs[x - 1]);
8513
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008514 static void
8515vtp_sgr_bulks(
8516 int argc,
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008517 int *args)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008518{
K.Takata6e1d31e2022-02-03 13:05:32 +00008519# define MAXSGR 16
8520# define SGRBUFSIZE 2 + 4 * MAXSGR + 1 // '\033[' + SGR + 'm'
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008521 char_u buf[SGRBUFSIZE];
8522 char_u *p;
8523 int in, out;
8524 int newargs[16];
8525 static int sgrfgr = -1, sgrfgg, sgrfgb;
8526 static int sgrbgr = -1, sgrbgg, sgrbgb;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008527
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008528 if (argc == 0)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008529 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008530 sgrfgr = sgrbgr = -1;
K.Takatadf5320c2022-09-01 13:20:16 +01008531 vtp_printf("\033[m");
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008532 return;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008533 }
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008534
8535 in = out = 0;
8536 while (in < argc)
8537 {
8538 int s = args[in];
8539 int copylen = 1;
8540
8541 if (s == 38)
8542 {
8543 if (argc - in >= 5 && args[in + 1] == 2)
8544 {
8545 if (sgrfgr == args[in + 2] && sgrfgg == args[in + 3]
8546 && sgrfgb == args[in + 4])
8547 {
8548 in += 5;
8549 copylen = 0;
8550 }
8551 else
8552 {
8553 sgrfgr = args[in + 2];
8554 sgrfgg = args[in + 3];
8555 sgrfgb = args[in + 4];
8556 copylen = 5;
8557 }
8558 }
8559 else if (argc - in >= 3 && args[in + 1] == 5)
8560 {
8561 sgrfgr = -1;
8562 copylen = 3;
8563 }
8564 }
8565 else if (s == 48)
8566 {
8567 if (argc - in >= 5 && args[in + 1] == 2)
8568 {
8569 if (sgrbgr == args[in + 2] && sgrbgg == args[in + 3]
8570 && sgrbgb == args[in + 4])
8571 {
8572 in += 5;
8573 copylen = 0;
8574 }
8575 else
8576 {
8577 sgrbgr = args[in + 2];
8578 sgrbgg = args[in + 3];
8579 sgrbgb = args[in + 4];
8580 copylen = 5;
8581 }
8582 }
8583 else if (argc - in >= 3 && args[in + 1] == 5)
8584 {
8585 sgrbgr = -1;
8586 copylen = 3;
8587 }
8588 }
8589 else if (30 <= s && s <= 39)
8590 sgrfgr = -1;
8591 else if (90 <= s && s <= 97)
8592 sgrfgr = -1;
8593 else if (40 <= s && s <= 49)
8594 sgrbgr = -1;
8595 else if (100 <= s && s <= 107)
8596 sgrbgr = -1;
8597 else if (s == 0)
8598 sgrfgr = sgrbgr = -1;
8599
8600 while (copylen--)
8601 newargs[out++] = args[in++];
8602 }
8603
8604 p = &buf[sizeof(buf) - 1];
8605 *p-- = 'm';
8606
8607 switch (out)
8608 {
8609 int n, m;
8610 DWORD r;
8611
8612 FAST256CASE(16);
8613 *p-- = ';';
8614 FAST256CASE(15);
8615 *p-- = ';';
8616 FAST256CASE(14);
8617 *p-- = ';';
8618 FAST256CASE(13);
8619 *p-- = ';';
8620 FAST256CASE(12);
8621 *p-- = ';';
8622 FAST256CASE(11);
8623 *p-- = ';';
8624 FAST256CASE(10);
8625 *p-- = ';';
8626 FAST256CASE(9);
8627 *p-- = ';';
8628 FAST256CASE(8);
8629 *p-- = ';';
8630 FAST256CASE(7);
8631 *p-- = ';';
8632 FAST256CASE(6);
8633 *p-- = ';';
8634 FAST256CASE(5);
8635 *p-- = ';';
8636 FAST256CASE(4);
8637 *p-- = ';';
8638 FAST256CASE(3);
8639 *p-- = ';';
8640 FAST256CASE(2);
8641 *p-- = ';';
8642 FAST256CASE(1);
8643 *p-- = '[';
8644 *p = '\033';
8645 WriteConsoleA(g_hConOut, p, (DWORD)(&buf[SGRBUFSIZE] - p), &r, NULL);
8646 default:
8647 break;
8648 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008649}
8650
Bram Moolenaar06b7b582020-05-30 17:49:25 +02008651 static void
8652wt_init(void)
8653{
Christopher Plewright1140b512022-11-12 18:46:05 +00008654 wt_working = mch_getenv("WT_SESSION") != NULL;
Bram Moolenaar06b7b582020-05-30 17:49:25 +02008655}
8656
Bram Moolenaar8a938af2018-05-01 17:30:41 +02008657# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02008658 static int
8659ctermtoxterm(
8660 int cterm)
8661{
Bram Moolenaar9894e392018-05-05 14:29:06 +02008662 char_u r, g, b, idx;
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02008663
8664 cterm_color2rgb(cterm, &r, &g, &b, &idx);
8665 return (((int)r << 16) | ((int)g << 8) | (int)b);
8666}
Bram Moolenaar8a938af2018-05-01 17:30:41 +02008667# endif
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02008668
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008669 static void
8670set_console_color_rgb(void)
8671{
8672# ifdef FEAT_TERMGUICOLORS
K.Takata27b53be2022-09-18 12:25:49 +01008673 CONSOLE_SCREEN_BUFFER_INFOEX csbi;
Bram Moolenaara050b942019-12-02 21:35:31 +01008674 guicolor_T fg, bg;
8675 int ctermfg, ctermbg;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008676
Christopher Plewright38804d62022-11-09 23:55:52 +00008677 if (!vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008678 return;
8679
Bram Moolenaara050b942019-12-02 21:35:31 +01008680 get_default_console_color(&ctermfg, &ctermbg, &fg, &bg);
8681
Christopher Plewright38804d62022-11-09 23:55:52 +00008682 if (p_tgc || t_colors >= 256)
Bram Moolenaar06b7b582020-05-30 17:49:25 +02008683 {
8684 term_fg_rgb_color(fg);
8685 term_bg_rgb_color(bg);
8686 return;
8687 }
8688
Christopher Plewright38804d62022-11-09 23:55:52 +00008689 if (!conpty_working)
8690 {
8691 fg = (GetRValue(fg) << 16) | (GetGValue(fg) << 8) | GetBValue(fg);
8692 bg = (GetRValue(bg) << 16) | (GetGValue(bg) << 8) | GetBValue(bg);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008693
Christopher Plewright38804d62022-11-09 23:55:52 +00008694 csbi.cbSize = sizeof(csbi);
8695 GetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008696
Christopher Plewright38804d62022-11-09 23:55:52 +00008697 csbi.cbSize = sizeof(csbi);
8698 csbi.srWindow.Right += 1;
8699 csbi.srWindow.Bottom += 1;
8700 store_console_bg_rgb = csbi.ColorTable[g_color_index_bg];
8701 store_console_fg_rgb = csbi.ColorTable[g_color_index_fg];
8702 csbi.ColorTable[g_color_index_bg] = (COLORREF)bg;
8703 csbi.ColorTable[g_color_index_fg] = (COLORREF)fg;
8704 SetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
8705 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008706# endif
8707}
8708
Bram Moolenaara050b942019-12-02 21:35:31 +01008709# if defined(FEAT_TERMGUICOLORS) || defined(PROTO)
8710 void
8711get_default_console_color(
8712 int *cterm_fg,
8713 int *cterm_bg,
8714 guicolor_T *gui_fg,
8715 guicolor_T *gui_bg)
8716{
8717 int id;
8718 guicolor_T guifg = INVALCOLOR;
8719 guicolor_T guibg = INVALCOLOR;
8720 int ctermfg = 0;
8721 int ctermbg = 0;
Christopher Plewright38804d62022-11-09 23:55:52 +00008722 int dummynull = 0;
Bram Moolenaara050b942019-12-02 21:35:31 +01008723
8724 id = syn_name2id((char_u *)"Normal");
8725 if (id > 0 && p_tgc)
8726 syn_id2colors(id, &guifg, &guibg);
8727 if (guifg == INVALCOLOR)
8728 {
8729 ctermfg = -1;
8730 if (id > 0)
Christopher Plewright38804d62022-11-09 23:55:52 +00008731 syn_id2cterm_bg(id, &ctermfg, &dummynull);
8732 if (vtp_working)
8733 {
8734 cterm_normal_fg_gui_color = guifg =
8735 ctermfg != -1 ? ctermtoxterm(ctermfg) : INVALCOLOR;
8736 ctermfg = ctermfg < 0 ? 0 : ctermfg;
8737 }
8738 else
8739 {
8740 guifg = ctermfg != -1 ? ctermtoxterm(ctermfg)
Bram Moolenaara050b942019-12-02 21:35:31 +01008741 : default_console_color_fg;
Christopher Plewright38804d62022-11-09 23:55:52 +00008742 cterm_normal_fg_gui_color = guifg;
8743 ctermfg = ctermfg < 0 ? 0 : ctermfg;
8744 }
Bram Moolenaara050b942019-12-02 21:35:31 +01008745 }
8746 if (guibg == INVALCOLOR)
8747 {
8748 ctermbg = -1;
8749 if (id > 0)
Christopher Plewright38804d62022-11-09 23:55:52 +00008750 syn_id2cterm_bg(id, &dummynull, &ctermbg);
8751 if (vtp_working)
Yasuhiro Matsumotoe42c8da2022-09-01 11:31:45 +01008752 {
8753 cterm_normal_bg_gui_color = guibg =
Yasuhiro Matsumotoaa04e1b2022-05-07 14:09:19 +01008754 ctermbg != -1 ? ctermtoxterm(ctermbg) : INVALCOLOR;
Yasuhiro Matsumotoe42c8da2022-09-01 11:31:45 +01008755 if (ctermbg < 0)
8756 ctermbg = 0;
8757 }
K.Takatae53a0d42022-09-05 21:45:11 +01008758 else
8759 {
8760 guibg = ctermbg != -1 ? ctermtoxterm(ctermbg)
8761 : default_console_color_bg;
8762 cterm_normal_bg_gui_color = guibg;
8763 ctermbg = ctermbg < 0 ? 0 : ctermbg;
8764 }
Bram Moolenaara050b942019-12-02 21:35:31 +01008765 }
8766
8767 *cterm_fg = ctermfg;
8768 *cterm_bg = ctermbg;
8769 *gui_fg = guifg;
8770 *gui_bg = guibg;
8771}
8772# endif
8773
Bram Moolenaardf543822020-01-30 11:53:59 +01008774/*
8775 * Set the console colors to the original colors or the last set colors.
8776 */
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008777 static void
8778reset_console_color_rgb(void)
8779{
8780# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008781
Christopher Plewright38804d62022-11-09 23:55:52 +00008782 if (vtp_working)
Bram Moolenaar06b7b582020-05-30 17:49:25 +02008783 return;
8784
Christopher Plewright38804d62022-11-09 23:55:52 +00008785 CONSOLE_SCREEN_BUFFER_INFOEX csbi;
8786
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008787 csbi.cbSize = sizeof(csbi);
K.Takata27b53be2022-09-18 12:25:49 +01008788 GetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008789
8790 csbi.cbSize = sizeof(csbi);
8791 csbi.srWindow.Right += 1;
8792 csbi.srWindow.Bottom += 1;
Bram Moolenaardf543822020-01-30 11:53:59 +01008793 csbi.ColorTable[g_color_index_bg] = (COLORREF)store_console_bg_rgb;
8794 csbi.ColorTable[g_color_index_fg] = (COLORREF)store_console_fg_rgb;
K.Takata27b53be2022-09-18 12:25:49 +01008795 SetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaardf543822020-01-30 11:53:59 +01008796# endif
8797}
8798
8799/*
8800 * Set the console colors to the original colors.
8801 */
8802 static void
8803restore_console_color_rgb(void)
8804{
8805# ifdef FEAT_TERMGUICOLORS
Christopher Plewright38804d62022-11-09 23:55:52 +00008806 if (vtp_working)
8807 return;
8808
K.Takata27b53be2022-09-18 12:25:49 +01008809 CONSOLE_SCREEN_BUFFER_INFOEX csbi;
Bram Moolenaardf543822020-01-30 11:53:59 +01008810
8811 csbi.cbSize = sizeof(csbi);
K.Takata27b53be2022-09-18 12:25:49 +01008812 GetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaardf543822020-01-30 11:53:59 +01008813
8814 csbi.cbSize = sizeof(csbi);
8815 csbi.srWindow.Right += 1;
8816 csbi.srWindow.Bottom += 1;
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02008817 csbi.ColorTable[g_color_index_bg] = (COLORREF)save_console_bg_rgb;
8818 csbi.ColorTable[g_color_index_fg] = (COLORREF)save_console_fg_rgb;
K.Takata27b53be2022-09-18 12:25:49 +01008819 SetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008820# endif
8821}
8822
8823 void
8824control_console_color_rgb(void)
8825{
Christopher Plewright38804d62022-11-09 23:55:52 +00008826 if (vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008827 set_console_color_rgb();
8828 else
8829 reset_console_color_rgb();
8830}
8831
8832 int
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008833use_vtp(void)
8834{
8835 return USE_VTP;
8836}
8837
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02008838 int
8839is_term_win32(void)
8840{
8841 return T_NAME != NULL && STRCMP(T_NAME, "win32") == 0;
8842}
8843
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008844 int
8845has_vtp_working(void)
8846{
8847 return vtp_working;
8848}
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01008849
Bram Moolenaar6902c0e2019-02-16 14:07:37 +01008850#endif
8851
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01008852 int
8853has_conpty_working(void)
8854{
8855 return conpty_working;
8856}
8857
8858 int
Bram Moolenaar57da6982019-09-13 22:30:11 +02008859get_conpty_type(void)
8860{
8861 return conpty_type;
8862}
8863
8864 int
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01008865is_conpty_stable(void)
8866{
8867 return conpty_stable;
8868}
Bram Moolenaar78d21da2019-02-17 15:00:52 +01008869
Bram Moolenaar7ed8f592020-04-28 20:44:42 +02008870 int
8871get_conpty_fix_type(void)
8872{
8873 return conpty_fix_type;
8874}
8875
Bram Moolenaarafde13b2019-04-28 19:46:49 +02008876#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL) || defined(PROTO)
Bram Moolenaar78d21da2019-02-17 15:00:52 +01008877 void
8878resize_console_buf(void)
8879{
8880 CONSOLE_SCREEN_BUFFER_INFO csbi;
8881 COORD coord;
8882 SMALL_RECT newsize;
8883
8884 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
8885 {
8886 coord.X = SRWIDTH(csbi.srWindow);
8887 coord.Y = SRHEIGHT(csbi.srWindow);
8888 SetConsoleScreenBufferSize(g_hConOut, coord);
8889
8890 newsize.Left = 0;
8891 newsize.Top = 0;
8892 newsize.Right = coord.X - 1;
8893 newsize.Bottom = coord.Y - 1;
8894 SetConsoleWindowInfo(g_hConOut, TRUE, &newsize);
8895
8896 SetConsoleScreenBufferSize(g_hConOut, coord);
8897 }
8898}
8899#endif
Martin Tournoij1a3e5742021-07-24 13:57:29 +02008900
8901 char *
8902GetWin32Error(void)
8903{
K.Takatad68b2fc2022-02-12 11:18:37 +00008904 static char *oldmsg = NULL;
Martin Tournoij1a3e5742021-07-24 13:57:29 +02008905 char *msg = NULL;
K.Takatad68b2fc2022-02-12 11:18:37 +00008906
Martin Tournoij1a3e5742021-07-24 13:57:29 +02008907 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER|FORMAT_MESSAGE_FROM_SYSTEM,
8908 NULL, GetLastError(), 0, (LPSTR)&msg, 0, NULL);
K.Takatad68b2fc2022-02-12 11:18:37 +00008909 if (oldmsg != NULL)
8910 LocalFree(oldmsg);
Martin Tournoij1a3e5742021-07-24 13:57:29 +02008911 if (msg != NULL)
8912 {
8913 // remove trailing \r\n
8914 char *pcrlf = strstr(msg, "\r\n");
8915 if (pcrlf != NULL)
8916 *pcrlf = '\0';
K.Takatad68b2fc2022-02-12 11:18:37 +00008917 oldmsg = msg;
Martin Tournoij1a3e5742021-07-24 13:57:29 +02008918 }
8919 return msg;
8920}
Paul Ollis65745772022-06-05 16:55:54 +01008921
8922#if defined(FEAT_RELTIME) || defined(PROTO)
8923static HANDLE timer_handle;
8924static int timer_active = FALSE;
8925
8926/*
8927 * Calls to start_timeout alternate the return value pointer between the two
8928 * entries in timeout_flags. If the previously active timeout is very close to
8929 * expiring when start_timeout() is called then a race condition means that the
8930 * set_flag() function may still be invoked after the previous timer is
8931 * deleted. Ping-ponging between the two flags prevents this causing 'fake'
8932 * timeouts.
8933 */
Bram Moolenaar155f2d12022-06-20 13:38:33 +01008934static sig_atomic_t timeout_flags[2];
8935static int timeout_flag_idx = 0;
8936static sig_atomic_t *timeout_flag = &timeout_flags[0];
Paul Ollis65745772022-06-05 16:55:54 +01008937
8938
8939 static void CALLBACK
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +01008940set_flag(void *param, BOOLEAN unused2 UNUSED)
Paul Ollis65745772022-06-05 16:55:54 +01008941{
8942 int *timeout_flag = (int *)param;
8943
8944 *timeout_flag = TRUE;
8945}
8946
8947/*
8948 * Stop any active timeout.
8949 */
8950 void
8951stop_timeout(void)
8952{
8953 if (timer_active)
8954 {
Christopher Plewright2a46f812022-10-16 19:47:45 +01008955 BOOL ret = DeleteTimerQueueTimer(NULL, timer_handle, NULL);
Paul Ollis65745772022-06-05 16:55:54 +01008956 timer_active = FALSE;
8957 if (!ret && GetLastError() != ERROR_IO_PENDING)
8958 {
8959 semsg(_(e_could_not_clear_timeout_str), GetWin32Error());
8960 }
8961 }
8962 *timeout_flag = FALSE;
8963}
8964
8965/*
8966 * Start the timeout timer.
8967 *
8968 * The period is defined in milliseconds.
8969 *
8970 * The return value is a pointer to a flag that is initialised to 0. If the
8971 * timeout expires, the flag is set to 1. This will only return pointers to
8972 * static memory; i.e. any pointer returned by this function may always be
8973 * safely dereferenced.
8974 *
8975 * This function is not expected to fail, but if it does it still returns a
8976 * valid flag pointer; the flag will remain stuck at zero.
8977 */
Bram Moolenaar155f2d12022-06-20 13:38:33 +01008978 volatile sig_atomic_t *
Paul Ollis65745772022-06-05 16:55:54 +01008979start_timeout(long msec)
8980{
Paul Ollis65745772022-06-05 16:55:54 +01008981 BOOL ret;
8982
Bram Moolenaar1f30caf2022-06-19 14:36:35 +01008983 timeout_flag = &timeout_flags[timeout_flag_idx];
Paul Ollis65745772022-06-05 16:55:54 +01008984
8985 stop_timeout();
8986 ret = CreateTimerQueueTimer(
8987 &timer_handle, NULL, set_flag, timeout_flag,
8988 (DWORD)msec, 0, WT_EXECUTEDEFAULT);
8989 if (!ret)
8990 {
8991 semsg(_(e_could_not_set_timeout_str), GetWin32Error());
8992 }
8993 else
8994 {
Bram Moolenaar1f30caf2022-06-19 14:36:35 +01008995 timeout_flag_idx = (timeout_flag_idx + 1) % 2;
Paul Ollis65745772022-06-05 16:55:54 +01008996 timer_active = TRUE;
8997 *timeout_flag = FALSE;
8998 }
8999 return timeout_flag;
9000}
9001#endif