blob: 9c942c4f7e9183a36e9e3297c1dfd40ab72e2f2a [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.
Christopher Plewright566f76e2023-01-10 13:43:04 +00001046 if (pker->uChar.UnicodeChar != 0)
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 {
Christopher Plewright566f76e2023-01-10 13:43:04 +00001157 // (0x23 - 0x28): VK_END, VK_HOME,
1158 // VK_LEFT, VK_UP, VK_RIGHT, VK_DOWN
1159
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001160 *pmodifiers = 0;
1161 *pch2 = VirtKeyMap[i].chAlone;
1162 if ((nModifs & SHIFT) != 0
1163 && (nModifs & ~SHIFT) == 0)
1164 {
1165 *pch2 = VirtKeyMap[i].chShift;
1166 }
Christopher Plewright566f76e2023-01-10 13:43:04 +00001167 if ((nModifs & CTRL) != 0
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001168 && (nModifs & ~CTRL) == 0)
1169 {
1170 *pch2 = VirtKeyMap[i].chCtrl;
1171 if (pker->wVirtualKeyCode == VK_UP
1172 || pker->wVirtualKeyCode == VK_DOWN)
1173 {
1174 *pmodifiers |= MOD_MASK_CTRL;
1175 *pch2 = VirtKeyMap[i].chAlone;
1176 }
1177 }
Christopher Plewright566f76e2023-01-10 13:43:04 +00001178 if ((nModifs & SHIFT) != 0
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001179 && (nModifs & CTRL) != 0)
1180 {
1181 *pmodifiers |= MOD_MASK_CTRL;
1182 *pch2 = VirtKeyMap[i].chShift;
1183 }
Christopher Plewright566f76e2023-01-10 13:43:04 +00001184 if ((nModifs & ALT) != 0)
1185 {
1186 *pch2 = VirtKeyMap[i].chAlt;
1187 *pmodifiers |= MOD_MASK_ALT;
1188 if ((nModifs & ~ALT) == 0)
1189 {
1190 *pch2 = VirtKeyMap[i].chAlone;
1191 }
1192 else if ((nModifs & SHIFT) != 0)
1193 {
1194 *pch2 = VirtKeyMap[i].chShift;
1195 }
1196 else if ((nModifs & CTRL) != 0)
1197 {
1198 if (pker->wVirtualKeyCode == VK_UP
1199 || pker->wVirtualKeyCode == VK_DOWN)
1200 {
1201 *pmodifiers |= MOD_MASK_CTRL;
1202 *pch2 = VirtKeyMap[i].chAlone;
1203 }
1204 else
1205 {
1206 *pch2 = VirtKeyMap[i].chCtrl;
1207 }
1208 }
1209 }
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001210 }
1211 else
1212 {
1213 *pch2 = VirtKeyMap[i].chAlone;
1214 if ((nModifs & SHIFT) != 0)
1215 *pmodifiers |= MOD_MASK_SHIFT;
1216 if ((nModifs & CTRL) != 0)
1217 *pmodifiers |= MOD_MASK_CTRL;
1218 if ((nModifs & ALT) != 0)
1219 *pmodifiers |= MOD_MASK_ALT;
1220 }
1221 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001222 }
1223
1224 return TRUE;
1225 }
1226 }
1227 }
1228
1229 i = win32_kbd_patch_key(pker);
1230
1231 if (i < 0)
1232 *pch = NUL;
1233 else
1234 {
K.Takata972db232022-02-04 10:45:38 +00001235 *pch = (i > 0) ? pker->uChar.UnicodeChar : NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001236
1237 if (pmodifiers != NULL)
1238 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001239 // Pass on the ALT key as a modifier, but only when not combined
1240 // with CTRL (which is ALTGR).
Bram Moolenaar071d4272004-06-13 20:20:40 +00001241 if ((nModifs & ALT) != 0 && (nModifs & CTRL) == 0)
1242 *pmodifiers |= MOD_MASK_ALT;
1243
Bram Moolenaar0f873732019-12-05 20:28:46 +01001244 // Pass on SHIFT only for special keys, because we don't know when
1245 // it's already included with the character.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001246 if ((nModifs & SHIFT) != 0 && *pch <= 0x20)
1247 *pmodifiers |= MOD_MASK_SHIFT;
1248
Bram Moolenaar0f873732019-12-05 20:28:46 +01001249 // Pass on CTRL only for non-special keys, because we don't know
1250 // when it's already included with the character. And not when
1251 // combined with ALT (which is ALTGR).
Bram Moolenaar071d4272004-06-13 20:20:40 +00001252 if ((nModifs & CTRL) != 0 && (nModifs & ALT) == 0
1253 && *pch >= 0x20 && *pch < 0x80)
1254 *pmodifiers |= MOD_MASK_CTRL;
1255 }
1256 }
1257
1258 return (*pch != NUL);
1259}
1260
Christopher Plewright20b795e2022-12-20 20:01:58 +00001261# if defined(FEAT_EVAL)
1262 static int
1263encode_key_event(dict_T *args, INPUT_RECORD *ir)
1264{
1265 static int s_dwMods = 0;
1266
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001267 char_u *action = dict_get_string(args, "event", TRUE);
1268 if (action && (STRICMP(action, "keydown") == 0
1269 || STRICMP(action, "keyup") == 0))
Christopher Plewright20b795e2022-12-20 20:01:58 +00001270 {
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001271 BOOL isKeyDown = STRICMP(action, "keydown") == 0;
Christopher Plewright20b795e2022-12-20 20:01:58 +00001272 WORD vkCode = dict_get_number_def(args, "keycode", 0);
1273 if (vkCode <= 0 || vkCode >= 0xFF)
1274 {
1275 semsg(_(e_invalid_argument_nr), (long)vkCode);
1276 return FALSE;
1277 }
1278
1279 ir->EventType = KEY_EVENT;
1280 KEY_EVENT_RECORD ker;
1281 ZeroMemory(&ker, sizeof(ker));
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001282 ker.bKeyDown = isKeyDown;
Christopher Plewright20b795e2022-12-20 20:01:58 +00001283 ker.wRepeatCount = 1;
1284 ker.wVirtualScanCode = 0;
1285 ker.dwControlKeyState = 0;
1286 int mods = (int)dict_get_number(args, "modifiers");
1287 // Encode the win32 console key modifiers from Vim keyboard modifiers.
1288 if (mods)
1289 {
1290 // If "modifiers" is explicitly set in the args, then we reset any
1291 // remembered modifer key state that may have been set from earlier
1292 // mod-key-down events, even if they are not yet unset by earlier
1293 // mod-key-up events.
1294 s_dwMods = 0;
1295 if (mods & MOD_MASK_SHIFT)
1296 ker.dwControlKeyState |= SHIFT_PRESSED;
1297 if (mods & MOD_MASK_CTRL)
1298 ker.dwControlKeyState |= LEFT_CTRL_PRESSED;
1299 if (mods & MOD_MASK_ALT)
1300 ker.dwControlKeyState |= LEFT_ALT_PRESSED;
1301 }
1302
1303 if (vkCode == VK_LSHIFT || vkCode == VK_RSHIFT || vkCode == VK_SHIFT)
1304 {
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001305 if (isKeyDown)
Christopher Plewright20b795e2022-12-20 20:01:58 +00001306 s_dwMods |= SHIFT_PRESSED;
1307 else
1308 s_dwMods &= ~SHIFT_PRESSED;
1309 }
1310 else if (vkCode == VK_LCONTROL || vkCode == VK_CONTROL)
1311 {
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001312 if (isKeyDown)
Christopher Plewright20b795e2022-12-20 20:01:58 +00001313 s_dwMods |= LEFT_CTRL_PRESSED;
1314 else
1315 s_dwMods &= ~LEFT_CTRL_PRESSED;
1316 }
1317 else if (vkCode == VK_RCONTROL)
1318 {
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001319 if (isKeyDown)
Christopher Plewright20b795e2022-12-20 20:01:58 +00001320 s_dwMods |= RIGHT_CTRL_PRESSED;
1321 else
1322 s_dwMods &= ~RIGHT_CTRL_PRESSED;
1323 }
1324 else if (vkCode == VK_LMENU || vkCode == VK_MENU)
1325 {
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001326 if (isKeyDown)
Christopher Plewright20b795e2022-12-20 20:01:58 +00001327 s_dwMods |= LEFT_ALT_PRESSED;
1328 else
1329 s_dwMods &= ~LEFT_ALT_PRESSED;
1330 }
1331 else if (vkCode == VK_RMENU)
1332 {
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001333 if (isKeyDown)
Christopher Plewright20b795e2022-12-20 20:01:58 +00001334 s_dwMods |= RIGHT_ALT_PRESSED;
1335 else
1336 s_dwMods &= ~RIGHT_ALT_PRESSED;
1337 }
1338 ker.dwControlKeyState |= s_dwMods;
1339 ker.wVirtualKeyCode = vkCode;
Christopher Plewright566f76e2023-01-10 13:43:04 +00001340 ker.uChar.UnicodeChar = 0;
Christopher Plewright20b795e2022-12-20 20:01:58 +00001341 ir->Event.KeyEvent = ker;
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001342 vim_free(action);
Christopher Plewright20b795e2022-12-20 20:01:58 +00001343 }
1344 else
1345 {
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001346 if (action == NULL)
Christopher Plewright20b795e2022-12-20 20:01:58 +00001347 {
1348 semsg(_(e_missing_argument_str), "event");
1349 }
1350 else
1351 {
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001352 semsg(_(e_invalid_value_for_argument_str_str), "event", action);
1353 vim_free(action);
Christopher Plewright20b795e2022-12-20 20:01:58 +00001354 }
1355 return FALSE;
1356 }
1357 return TRUE;
1358}
1359# endif // FEAT_EVAL
1360#endif // !FEAT_GUI_MSWIN || VIMDLL
Bram Moolenaar071d4272004-06-13 20:20:40 +00001361
1362
Bram Moolenaar071d4272004-06-13 20:20:40 +00001363/*
1364 * For the GUI the mouse handling is in gui_w32.c.
1365 */
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001366#if defined(FEAT_GUI_MSWIN) && !defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001367 void
Bram Moolenaar1266d672017-02-01 13:43:36 +01001368mch_setmouse(int on UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001369{
1370}
Christopher Plewright20b795e2022-12-20 20:01:58 +00001371#else // !FEAT_GUI_MSWIN || VIMDLL
Bram Moolenaar0f873732019-12-05 20:28:46 +01001372static int g_fMouseAvail = FALSE; // mouse present
1373static int g_fMouseActive = FALSE; // mouse enabled
1374static int g_nMouseClick = -1; // mouse status
1375static int g_xMouse; // mouse x coordinate
1376static int g_yMouse; // mouse y coordinate
Bram Moolenaar9f1983d2022-05-12 20:35:35 +01001377static DWORD g_cmodein = 0; // Original console input mode
1378static DWORD g_cmodeout = 0; // Original console output mode
Bram Moolenaar071d4272004-06-13 20:20:40 +00001379
1380/*
1381 * Enable or disable mouse input
1382 */
1383 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001384mch_setmouse(int on)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001385{
1386 DWORD cmodein;
1387
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001388# ifdef VIMDLL
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001389 if (gui.in_use)
1390 return;
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001391# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001392 if (!g_fMouseAvail)
1393 return;
1394
1395 g_fMouseActive = on;
1396 GetConsoleMode(g_hConIn, &cmodein);
1397
1398 if (g_fMouseActive)
Wez Furlong6ef5ab52021-05-30 19:29:41 +02001399 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00001400 cmodein |= ENABLE_MOUSE_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02001401 cmodein &= ~ENABLE_QUICK_EDIT_MODE;
1402 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001403 else
Wez Furlong6ef5ab52021-05-30 19:29:41 +02001404 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00001405 cmodein &= ~ENABLE_MOUSE_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02001406 cmodein |= g_cmodein & ENABLE_QUICK_EDIT_MODE;
1407 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001408
Wez Furlong6ef5ab52021-05-30 19:29:41 +02001409 SetConsoleMode(g_hConIn, cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001410}
1411
Bram Moolenaar157d8132018-03-06 17:09:20 +01001412
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001413# if defined(FEAT_BEVAL_TERM) || defined(PROTO)
Bram Moolenaar157d8132018-03-06 17:09:20 +01001414/*
1415 * Called when 'balloonevalterm' changed.
1416 */
1417 void
1418mch_bevalterm_changed(void)
1419{
1420 mch_setmouse(g_fMouseActive);
1421}
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001422# endif
Bram Moolenaar157d8132018-03-06 17:09:20 +01001423
Christopher Plewright2a46f812022-10-16 19:47:45 +01001424/*
1425 * Win32 console mouse scroll event handler.
Christopher Plewright20b795e2022-12-20 20:01:58 +00001426 * Console version of the _OnMouseWheel() function in gui_w32.c
Christopher Plewright2a46f812022-10-16 19:47:45 +01001427 *
1428 * This encodes the mouse scroll direction and keyboard modifiers into
1429 * g_nMouseClick, and the mouse position into g_xMouse and g_yMouse
1430 *
1431 * The direction of the scroll is decoded from two fields of the win32 console
1432 * mouse event record;
Christopher Plewright20b795e2022-12-20 20:01:58 +00001433 * 1. The orientation - vertical or horizontal flag - from dwEventFlags
Christopher Plewright2a46f812022-10-16 19:47:45 +01001434 * 2. The sign - positive or negative (aka delta flag) - from dwButtonState
1435 *
Christopher Plewright20b795e2022-12-20 20:01:58 +00001436 * When scroll orientation is HORIZONTAL
Christopher Plewright2a46f812022-10-16 19:47:45 +01001437 * - If the high word of the dwButtonState member contains a positive
1438 * value, the wheel was rotated to the right.
1439 * - Otherwise, the wheel was rotated to the left.
Christopher Plewright20b795e2022-12-20 20:01:58 +00001440 * When scroll orientation is VERTICAL
Christopher Plewright2a46f812022-10-16 19:47:45 +01001441 * - If the high word of the dwButtonState member contains a positive value,
1442 * the wheel was rotated forward, away from the user.
1443 * - Otherwise, the wheel was rotated backward, toward the user.
1444 */
1445 static void
1446decode_mouse_wheel(MOUSE_EVENT_RECORD *pmer)
1447{
Christopher Plewright2a46f812022-10-16 19:47:45 +01001448 int horizontal = (pmer->dwEventFlags == MOUSE_HWHEELED);
1449 int zDelta = pmer->dwButtonState;
1450
1451 g_xMouse = pmer->dwMousePosition.X;
1452 g_yMouse = pmer->dwMousePosition.Y;
1453
K.Takata161b6ac2022-11-14 15:31:07 +00001454# ifdef FEAT_PROP_POPUP
Christopher Plewright605d02a2022-10-19 11:54:46 +01001455 int lcol = g_xMouse;
1456 int lrow = g_yMouse;
Christopher Plewright38804d62022-11-09 23:55:52 +00001457 win_T *wp = mouse_find_win(&lrow, &lcol, FIND_POPUP);
Christopher Plewright2a46f812022-10-16 19:47:45 +01001458 if (wp != NULL && popup_is_popup(wp))
1459 {
1460 g_nMouseClick = -1;
1461 cmdarg_T cap;
1462 oparg_T oa;
1463 CLEAR_FIELD(cap);
1464 clear_oparg(&oa);
1465 cap.oap = &oa;
1466 if (horizontal)
1467 {
1468 cap.arg = zDelta < 0 ? MSCR_LEFT : MSCR_RIGHT;
1469 cap.cmdchar = zDelta < 0 ? K_MOUSELEFT : K_MOUSERIGHT;
1470 }
1471 else
1472 {
1473 cap.cmdchar = zDelta < 0 ? K_MOUSEUP : K_MOUSEDOWN;
1474 cap.arg = zDelta < 0 ? MSCR_UP : MSCR_DOWN;
1475 }
1476
1477 // Mouse hovers over popup window, scroll it if possible.
1478 mouse_row = wp->w_winrow;
1479 mouse_col = wp->w_wincol;
1480 nv_mousescroll(&cap);
1481 update_screen(0);
1482 setcursor();
1483 out_flush();
1484 return;
1485 }
K.Takata161b6ac2022-11-14 15:31:07 +00001486# endif
Christopher Plewright2a46f812022-10-16 19:47:45 +01001487 mouse_col = g_xMouse;
1488 mouse_row = g_yMouse;
1489
1490 char_u modifiers = 0;
1491 char_u direction = 0;
1492
1493 // Decode the direction into an event that Vim can process
1494 if (horizontal)
1495 direction = zDelta >= 0 ? KE_MOUSELEFT : KE_MOUSERIGHT;
1496 else
1497 direction = zDelta >= 0 ? KE_MOUSEDOWN : KE_MOUSEUP;
1498
dundargocc57b5bc2022-11-02 13:30:51 +00001499 // Decode the win32 console key modifiers into Vim mouse modifiers.
Christopher Plewright2a46f812022-10-16 19:47:45 +01001500 if (pmer->dwControlKeyState & SHIFT_PRESSED)
Christopher Plewright605d02a2022-10-19 11:54:46 +01001501 modifiers |= MOD_MASK_SHIFT; // MOUSE_SHIFT;
Christopher Plewright2a46f812022-10-16 19:47:45 +01001502 if (pmer->dwControlKeyState & (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED))
Christopher Plewright605d02a2022-10-19 11:54:46 +01001503 modifiers |= MOD_MASK_CTRL; // MOUSE_CTRL;
Christopher Plewright2a46f812022-10-16 19:47:45 +01001504 if (pmer->dwControlKeyState & (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED))
1505 modifiers |= MOD_MASK_ALT; // MOUSE_ALT;
1506
1507 // add (bitwise or) the scroll direction and the key modifier chars
1508 // together.
1509 g_nMouseClick = ((direction << 8) | modifiers);
1510
1511 return;
1512}
1513
Bram Moolenaar071d4272004-06-13 20:20:40 +00001514/*
1515 * Decode a MOUSE_EVENT. If it's a valid event, return MOUSE_LEFT,
1516 * MOUSE_MIDDLE, or MOUSE_RIGHT for a click; MOUSE_DRAG for a mouse
1517 * move with a button held down; and MOUSE_RELEASE after a MOUSE_DRAG
1518 * or a MOUSE_LEFT, _MIDDLE, or _RIGHT. We encode the button type,
1519 * the number of clicks, and the Shift/Ctrl/Alt modifiers in g_nMouseClick,
1520 * and we return the mouse position in g_xMouse and g_yMouse.
1521 *
1522 * Every MOUSE_LEFT, _MIDDLE, or _RIGHT will be followed by zero or more
1523 * MOUSE_DRAGs and one MOUSE_RELEASE. MOUSE_RELEASE will be followed only
1524 * by MOUSE_LEFT, _MIDDLE, or _RIGHT.
1525 *
1526 * For multiple clicks, we send, say, MOUSE_LEFT/1 click, MOUSE_RELEASE,
1527 * MOUSE_LEFT/2 clicks, MOUSE_RELEASE, MOUSE_LEFT/3 clicks, MOUSE_RELEASE, ....
1528 *
1529 * Windows will send us MOUSE_MOVED notifications whenever the mouse
1530 * moves, even if it stays within the same character cell. We ignore
1531 * all MOUSE_MOVED messages if the position hasn't really changed, and
1532 * we ignore all MOUSE_MOVED messages where no button is held down (i.e.,
1533 * we're only interested in MOUSE_DRAG).
1534 *
1535 * All of this is complicated by the code that fakes MOUSE_MIDDLE on
1536 * 2-button mouses by pressing the left & right buttons simultaneously.
1537 * In practice, it's almost impossible to click both at the same time,
1538 * so we need to delay a little. Also, we tend not to get MOUSE_RELEASE
1539 * in such cases, if the user is clicking quickly.
1540 */
1541 static BOOL
1542decode_mouse_event(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001543 MOUSE_EVENT_RECORD *pmer)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001544{
1545 static int s_nOldButton = -1;
1546 static int s_nOldMouseClick = -1;
1547 static int s_xOldMouse = -1;
1548 static int s_yOldMouse = -1;
1549 static linenr_T s_old_topline = 0;
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001550# ifdef FEAT_DIFF
Bram Moolenaar071d4272004-06-13 20:20:40 +00001551 static int s_old_topfill = 0;
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001552# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001553 static int s_cClicks = 1;
1554 static BOOL s_fReleased = TRUE;
1555 static DWORD s_dwLastClickTime = 0;
1556 static BOOL s_fNextIsMiddle = FALSE;
1557
Bram Moolenaar0f873732019-12-05 20:28:46 +01001558 static DWORD cButtons = 0; // number of buttons supported
Bram Moolenaar071d4272004-06-13 20:20:40 +00001559
1560 const DWORD LEFT = FROM_LEFT_1ST_BUTTON_PRESSED;
1561 const DWORD MIDDLE = FROM_LEFT_2ND_BUTTON_PRESSED;
1562 const DWORD RIGHT = RIGHTMOST_BUTTON_PRESSED;
1563 const DWORD LEFT_RIGHT = LEFT | RIGHT;
1564
1565 int nButton;
1566
1567 if (cButtons == 0 && !GetNumberOfConsoleMouseButtons(&cButtons))
1568 cButtons = 2;
1569
1570 if (!g_fMouseAvail || !g_fMouseActive)
1571 {
1572 g_nMouseClick = -1;
1573 return FALSE;
1574 }
1575
Bram Moolenaar0f873732019-12-05 20:28:46 +01001576 // get a spurious MOUSE_EVENT immediately after receiving focus; ignore
Bram Moolenaar071d4272004-06-13 20:20:40 +00001577 if (g_fJustGotFocus)
1578 {
1579 g_fJustGotFocus = FALSE;
1580 return FALSE;
1581 }
1582
Christopher Plewright605d02a2022-10-19 11:54:46 +01001583 // If there is an unprocessed mouse click drop this one.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001584 if (g_nMouseClick != -1)
1585 return TRUE;
Christopher Plewright605d02a2022-10-19 11:54:46 +01001586
Christopher Plewright2a46f812022-10-16 19:47:45 +01001587 if (pmer->dwEventFlags == MOUSE_WHEELED
1588 || pmer->dwEventFlags == MOUSE_HWHEELED)
1589 {
1590 decode_mouse_wheel(pmer);
1591 return TRUE; // we now should have a mouse scroll in g_nMouseClick
1592 }
Christopher Plewright605d02a2022-10-19 11:54:46 +01001593
Bram Moolenaar071d4272004-06-13 20:20:40 +00001594 nButton = -1;
1595 g_xMouse = pmer->dwMousePosition.X;
1596 g_yMouse = pmer->dwMousePosition.Y;
1597
1598 if (pmer->dwEventFlags == MOUSE_MOVED)
1599 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001600 // Ignore MOUSE_MOVED events if (x, y) hasn't changed. (We get these
1601 // events even when the mouse moves only within a char cell.)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001602 if (s_xOldMouse == g_xMouse && s_yOldMouse == g_yMouse)
1603 return FALSE;
1604 }
1605
Bram Moolenaar0f873732019-12-05 20:28:46 +01001606 // If no buttons are pressed...
Bram Moolenaar071d4272004-06-13 20:20:40 +00001607 if ((pmer->dwButtonState & ((1 << cButtons) - 1)) == 0)
1608 {
Bram Moolenaar157d8132018-03-06 17:09:20 +01001609 nButton = MOUSE_RELEASE;
1610
Bram Moolenaar0f873732019-12-05 20:28:46 +01001611 // If the last thing returned was MOUSE_RELEASE, ignore this
Bram Moolenaar071d4272004-06-13 20:20:40 +00001612 if (s_fReleased)
Bram Moolenaar157d8132018-03-06 17:09:20 +01001613 {
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001614# ifdef FEAT_BEVAL_TERM
Bram Moolenaar0f873732019-12-05 20:28:46 +01001615 // do return mouse move events when we want them
Bram Moolenaar157d8132018-03-06 17:09:20 +01001616 if (p_bevalterm)
1617 nButton = MOUSE_DRAG;
1618 else
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001619# endif
Bram Moolenaar157d8132018-03-06 17:09:20 +01001620 return FALSE;
1621 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001622
Bram Moolenaar071d4272004-06-13 20:20:40 +00001623 s_fReleased = TRUE;
1624 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01001625 else // one or more buttons pressed
Bram Moolenaar071d4272004-06-13 20:20:40 +00001626 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001627 // on a 2-button mouse, hold down left and right buttons
1628 // simultaneously to get MIDDLE.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001629
1630 if (cButtons == 2 && s_nOldButton != MOUSE_DRAG)
1631 {
1632 DWORD dwLR = (pmer->dwButtonState & LEFT_RIGHT);
1633
Bram Moolenaar0f873732019-12-05 20:28:46 +01001634 // if either left or right button only is pressed, see if the
1635 // next mouse event has both of them pressed
Bram Moolenaar071d4272004-06-13 20:20:40 +00001636 if (dwLR == LEFT || dwLR == RIGHT)
1637 {
1638 for (;;)
1639 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001640 // wait a short time for next input event
Bram Moolenaar071d4272004-06-13 20:20:40 +00001641 if (WaitForSingleObject(g_hConIn, p_mouset / 3)
1642 != WAIT_OBJECT_0)
1643 break;
1644 else
1645 {
1646 DWORD cRecords = 0;
1647 INPUT_RECORD ir;
1648 MOUSE_EVENT_RECORD* pmer2 = &ir.Event.MouseEvent;
1649
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001650 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001651
1652 if (cRecords == 0 || ir.EventType != MOUSE_EVENT
1653 || !(pmer2->dwButtonState & LEFT_RIGHT))
1654 break;
1655 else
1656 {
1657 if (pmer2->dwEventFlags != MOUSE_MOVED)
1658 {
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001659 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001660
1661 return decode_mouse_event(pmer2);
1662 }
1663 else if (s_xOldMouse == pmer2->dwMousePosition.X &&
1664 s_yOldMouse == pmer2->dwMousePosition.Y)
1665 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001666 // throw away spurious mouse move
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001667 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001668
Bram Moolenaar0f873732019-12-05 20:28:46 +01001669 // are there any more mouse events in queue?
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001670 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001671
1672 if (cRecords==0 || ir.EventType != MOUSE_EVENT)
1673 break;
1674 }
1675 else
1676 break;
1677 }
1678 }
1679 }
1680 }
1681 }
1682
1683 if (s_fNextIsMiddle)
1684 {
1685 nButton = (pmer->dwEventFlags == MOUSE_MOVED)
1686 ? MOUSE_DRAG : MOUSE_MIDDLE;
1687 s_fNextIsMiddle = FALSE;
1688 }
1689 else if (cButtons == 2 &&
1690 ((pmer->dwButtonState & LEFT_RIGHT) == LEFT_RIGHT))
1691 {
1692 nButton = MOUSE_MIDDLE;
1693
1694 if (! s_fReleased && pmer->dwEventFlags != MOUSE_MOVED)
1695 {
1696 s_fNextIsMiddle = TRUE;
1697 nButton = MOUSE_RELEASE;
1698 }
1699 }
1700 else if ((pmer->dwButtonState & LEFT) == LEFT)
1701 nButton = MOUSE_LEFT;
1702 else if ((pmer->dwButtonState & MIDDLE) == MIDDLE)
1703 nButton = MOUSE_MIDDLE;
1704 else if ((pmer->dwButtonState & RIGHT) == RIGHT)
1705 nButton = MOUSE_RIGHT;
1706
1707 if (! s_fReleased && ! s_fNextIsMiddle
1708 && nButton != s_nOldButton && s_nOldButton != MOUSE_DRAG)
1709 return FALSE;
1710
1711 s_fReleased = s_fNextIsMiddle;
1712 }
1713
1714 if (pmer->dwEventFlags == 0 || pmer->dwEventFlags == DOUBLE_CLICK)
1715 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001716 // button pressed or released, without mouse moving
Bram Moolenaar071d4272004-06-13 20:20:40 +00001717 if (nButton != -1 && nButton != MOUSE_RELEASE)
1718 {
1719 DWORD dwCurrentTime = GetTickCount();
1720
1721 if (s_xOldMouse != g_xMouse
1722 || s_yOldMouse != g_yMouse
1723 || s_nOldButton != nButton
1724 || s_old_topline != curwin->w_topline
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001725# ifdef FEAT_DIFF
Bram Moolenaar071d4272004-06-13 20:20:40 +00001726 || s_old_topfill != curwin->w_topfill
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001727# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001728 || (int)(dwCurrentTime - s_dwLastClickTime) > p_mouset)
1729 {
1730 s_cClicks = 1;
1731 }
1732 else if (++s_cClicks > 4)
1733 {
1734 s_cClicks = 1;
1735 }
1736
1737 s_dwLastClickTime = dwCurrentTime;
1738 }
1739 }
1740 else if (pmer->dwEventFlags == MOUSE_MOVED)
1741 {
1742 if (nButton != -1 && nButton != MOUSE_RELEASE)
1743 nButton = MOUSE_DRAG;
1744
1745 s_cClicks = 1;
1746 }
1747
1748 if (nButton == -1)
1749 return FALSE;
1750
1751 if (nButton != MOUSE_RELEASE)
1752 s_nOldButton = nButton;
1753
1754 g_nMouseClick = nButton;
1755
1756 if (pmer->dwControlKeyState & SHIFT_PRESSED)
1757 g_nMouseClick |= MOUSE_SHIFT;
1758 if (pmer->dwControlKeyState & (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED))
1759 g_nMouseClick |= MOUSE_CTRL;
1760 if (pmer->dwControlKeyState & (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED))
1761 g_nMouseClick |= MOUSE_ALT;
1762
1763 if (nButton != MOUSE_DRAG && nButton != MOUSE_RELEASE)
1764 SET_NUM_MOUSE_CLICKS(g_nMouseClick, s_cClicks);
1765
Bram Moolenaar0f873732019-12-05 20:28:46 +01001766 // only pass on interesting (i.e., different) mouse events
Bram Moolenaar071d4272004-06-13 20:20:40 +00001767 if (s_xOldMouse == g_xMouse
1768 && s_yOldMouse == g_yMouse
1769 && s_nOldMouseClick == g_nMouseClick)
1770 {
1771 g_nMouseClick = -1;
1772 return FALSE;
1773 }
1774
1775 s_xOldMouse = g_xMouse;
1776 s_yOldMouse = g_yMouse;
1777 s_old_topline = curwin->w_topline;
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001778# ifdef FEAT_DIFF
Bram Moolenaar071d4272004-06-13 20:20:40 +00001779 s_old_topfill = curwin->w_topfill;
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001780# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001781 s_nOldMouseClick = g_nMouseClick;
1782
1783 return TRUE;
1784}
1785
Christopher Plewright20b795e2022-12-20 20:01:58 +00001786# ifdef FEAT_EVAL
1787 static int
1788encode_mouse_event(dict_T *args, INPUT_RECORD *ir)
1789{
1790 int button;
1791 int row;
1792 int col;
1793 int repeated_click;
Bram Moolenaar9b8a3652022-12-20 20:47:28 +00001794 int_u mods = 0;
Christopher Plewright20b795e2022-12-20 20:01:58 +00001795 int move;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001796
Christopher Plewright20b795e2022-12-20 20:01:58 +00001797 if (!dict_has_key(args, "row") || !dict_has_key(args, "col"))
1798 return FALSE;
1799
1800 // Note: "move" is optional, requires fewer arguments
1801 move = (int)dict_get_bool(args, "move", FALSE);
1802 if (!move && (!dict_has_key(args, "button")
1803 || !dict_has_key(args, "multiclick")
1804 || !dict_has_key(args, "modifiers")))
1805 return FALSE;
1806
1807 row = (int)dict_get_number(args, "row") - 1;
1808 col = (int)dict_get_number(args, "col") - 1;
1809
1810 ir->EventType = MOUSE_EVENT;
1811 MOUSE_EVENT_RECORD mer;
1812 ZeroMemory(&mer, sizeof(mer));
1813 mer.dwMousePosition.X = col;
1814 mer.dwMousePosition.Y = row;
1815
1816 if (move)
1817 {
1818 mer.dwButtonState = 0;
1819 mer.dwEventFlags = MOUSE_MOVED;
1820 }
1821 else
1822 {
1823 button = (int)dict_get_number(args, "button");
1824 repeated_click = (int)dict_get_number(args, "multiclick");
1825 mods = (int)dict_get_number(args, "modifiers");
1826 // Reset the scroll values to known values.
1827 // XXX: Remove this when/if the scroll step is made configurable.
1828 mouse_set_hor_scroll_step(6);
1829 mouse_set_vert_scroll_step(3);
1830
1831 switch (button)
1832 {
1833 case MOUSE_LEFT:
1834 mer.dwButtonState = FROM_LEFT_1ST_BUTTON_PRESSED;
1835 mer.dwEventFlags = repeated_click == 1 ? DOUBLE_CLICK : 0;
1836 break;
1837 case MOUSE_MIDDLE:
1838 mer.dwButtonState = FROM_LEFT_2ND_BUTTON_PRESSED;
1839 mer.dwEventFlags = repeated_click == 1 ? DOUBLE_CLICK : 0;
1840 break;
1841 case MOUSE_RIGHT:
1842 mer.dwButtonState = RIGHTMOST_BUTTON_PRESSED;
1843 mer.dwEventFlags = repeated_click == 1 ? DOUBLE_CLICK : 0;
1844 break;
1845 case MOUSE_RELEASE:
1846 // umm? Assume Left Release?
1847 mer.dwEventFlags = 0;
1848
1849 case MOUSE_MOVE:
1850 mer.dwButtonState = 0;
1851 mer.dwEventFlags = MOUSE_MOVED;
1852 break;
1853 case MOUSE_X1:
1854 mer.dwButtonState = FROM_LEFT_3RD_BUTTON_PRESSED;
1855 break;
1856 case MOUSE_X2:
1857 mer.dwButtonState = FROM_LEFT_4TH_BUTTON_PRESSED;
1858 break;
1859 case MOUSE_4: // KE_MOUSEDOWN;
1860 mer.dwButtonState = -1;
1861 mer.dwEventFlags = MOUSE_WHEELED;
1862 break;
1863 case MOUSE_5: // KE_MOUSEUP;
1864 mer.dwButtonState = +1;
1865 mer.dwEventFlags = MOUSE_WHEELED;
1866 break;
1867 case MOUSE_6: // KE_MOUSELEFT;
1868 mer.dwButtonState = -1;
1869 mer.dwEventFlags = MOUSE_HWHEELED;
1870 break;
1871 case MOUSE_7: // KE_MOUSERIGHT;
1872 mer.dwButtonState = +1;
1873 mer.dwEventFlags = MOUSE_HWHEELED;
1874 break;
1875 default:
1876 semsg(_(e_invalid_argument_str), "button");
1877 return FALSE;
1878 }
1879 }
1880
1881 mer.dwControlKeyState = 0;
1882 if (mods != 0)
1883 {
1884 // Encode the win32 console key modifiers from Vim MOUSE modifiers.
1885 if (mods & MOUSE_SHIFT)
1886 mer.dwControlKeyState |= SHIFT_PRESSED;
1887 if (mods & MOUSE_CTRL)
1888 mer.dwControlKeyState |= LEFT_CTRL_PRESSED;
1889 if (mods & MOUSE_ALT)
1890 mer.dwControlKeyState |= LEFT_ALT_PRESSED;
1891 }
1892 ir->Event.MouseEvent = mer;
1893 return TRUE;
1894}
1895# endif // FEAT_EVAL
1896
1897 static int
1898write_input_record_buffer(INPUT_RECORD* irEvents, int nLength)
1899{
1900 int nCount = 0;
1901 while (nCount < nLength)
1902 {
1903 input_record_buffer.length++;
1904 input_record_buffer_node_T *event_node =
1905 malloc(sizeof(input_record_buffer_node_T));
1906 event_node->ir = irEvents[nCount++];
1907 event_node->next = NULL;
1908 if (input_record_buffer.tail == NULL)
1909 {
1910 input_record_buffer.head = event_node;
1911 input_record_buffer.tail = event_node;
1912 }
1913 else
1914 {
1915 input_record_buffer.tail->next = event_node;
1916 input_record_buffer.tail = input_record_buffer.tail->next;
1917 }
1918 }
1919 return nCount;
1920}
1921
1922 static int
1923read_input_record_buffer(INPUT_RECORD* irEvents, int nMaxLength)
1924{
1925 int nCount = 0;
1926 while (nCount < nMaxLength && input_record_buffer.head != NULL)
1927 {
1928 input_record_buffer.length--;
1929 input_record_buffer_node_T *pop_head = input_record_buffer.head;
1930 irEvents[nCount++] = pop_head->ir;
1931 input_record_buffer.head = pop_head->next;
1932 vim_free(pop_head);
1933 if (input_record_buffer.length == 0)
1934 input_record_buffer.tail = NULL;
1935 }
1936 return nCount;
1937}
Christopher Plewright20b795e2022-12-20 20:01:58 +00001938#endif // !FEAT_GUI_MSWIN || VIMDLL
1939
1940#ifdef FEAT_EVAL
1941/*
1942 * The 'test_mswin_event' function is for testing Vim's low-level handling of
1943 * user input events. ie, this manages the encoding of INPUT_RECORD events
1944 * so that we have a way to test how Vim decodes INPUT_RECORD events in Windows
1945 * consoles.
1946 *
1947 * The 'test_mswin_event' function is based on 'test_gui_event'. In fact, when
1948 * the Windows GUI is running, the arguments; 'event' and 'args', are the same.
1949 * So, it acts as an alias for 'test_gui_event' for the Windows GUI.
1950 *
1951 * When the Windows console is running, the arguments; 'event' and 'args', are
1952 * a subset of what 'test_gui_event' handles, ie, only "key" and "mouse"
1953 * events are encoded as INPUT_RECORD events.
1954 *
1955 * Note: INPUT_RECORDs are only used by the Windows console, not the GUI. The
1956 * GUI sends MSG structs instead.
1957 */
1958 int
1959test_mswin_event(char_u *event, dict_T *args)
1960{
1961 int lpEventsWritten = 0;
1962
1963# if defined(VIMDLL) || defined(FEAT_GUI_MSWIN)
1964 if (gui.in_use)
1965 return test_gui_w32_sendevent(event, args);
1966# endif
1967
1968# if defined(VIMDLL) || !defined(FEAT_GUI_MSWIN)
1969
1970// Currently implemented event record types are; KEY_EVENT and MOUSE_EVENT
1971// Potentially could also implement: FOCUS_EVENT and WINDOW_BUFFER_SIZE_EVENT
1972// Maybe also: MENU_EVENT
1973
1974 INPUT_RECORD ir;
1975 BOOL input_encoded = FALSE;
Christopher Plewright7b0afc12022-12-30 16:54:58 +00001976 BOOL execute = FALSE;
Christopher Plewright20b795e2022-12-20 20:01:58 +00001977 if (STRCMP(event, "key") == 0)
Christopher Plewright7b0afc12022-12-30 16:54:58 +00001978 {
1979 execute = dict_get_bool(args, "execute", FALSE);
1980 if (dict_has_key(args, "event"))
1981 input_encoded = encode_key_event(args, &ir);
1982 else if (!execute)
1983 {
1984 semsg(_(e_missing_argument_str), "event");
1985 return FALSE;
1986 }
1987 }
Christopher Plewright20b795e2022-12-20 20:01:58 +00001988 else if (STRCMP(event, "mouse") == 0)
Christopher Plewright7b0afc12022-12-30 16:54:58 +00001989 {
1990 execute = TRUE;
Christopher Plewright20b795e2022-12-20 20:01:58 +00001991 input_encoded = encode_mouse_event(args, &ir);
Christopher Plewright7b0afc12022-12-30 16:54:58 +00001992 }
Christopher Plewright20b795e2022-12-20 20:01:58 +00001993 else
1994 {
1995 semsg(_(e_invalid_value_for_argument_str_str), "event", event);
1996 return FALSE;
1997 }
1998
1999 // Ideally, WriteConsoleInput would be used to inject these low-level
2000 // events. But, this doesnt work well in the CI test environment. So
2001 // implementing an input_record_buffer instead.
2002 if (input_encoded)
2003 lpEventsWritten = write_input_record_buffer(&ir, 1);
2004
Christopher Plewright7b0afc12022-12-30 16:54:58 +00002005 // Set flags to execute the event, ie. like feedkeys mode X.
2006 if (execute)
2007 {
2008 int save_msg_scroll = msg_scroll;
2009 // Avoid a 1 second delay when the keys start Insert mode.
2010 msg_scroll = FALSE;
2011 ch_log(NULL, "test_mswin_event() executing");
Christopher Plewright20b795e2022-12-20 20:01:58 +00002012 exec_normal(TRUE, TRUE, TRUE);
Christopher Plewright7b0afc12022-12-30 16:54:58 +00002013 msg_scroll |= save_msg_scroll;
2014 }
Christopher Plewright20b795e2022-12-20 20:01:58 +00002015
2016# endif
2017 return lpEventsWritten;
2018}
2019#endif // FEAT_EVAL
Bram Moolenaar071d4272004-06-13 20:20:40 +00002020
2021#ifdef MCH_CURSOR_SHAPE
2022/*
2023 * Set the shape of the cursor.
2024 * 'thickness' can be from 1 (thin) to 99 (block)
2025 */
2026 static void
2027mch_set_cursor_shape(int thickness)
2028{
Christopher Plewright38804d62022-11-09 23:55:52 +00002029 if (vtp_working)
K.Takatadf5320c2022-09-01 13:20:16 +01002030 {
2031 if (*T_CSI == NUL)
2032 {
2033 // If 't_SI' is not set, use the default cursor styles.
2034 if (thickness < 50)
2035 vtp_printf("\033[3 q"); // underline
2036 else
2037 vtp_printf("\033[0 q"); // default
2038 }
2039 }
2040 else
2041 {
2042 CONSOLE_CURSOR_INFO ConsoleCursorInfo;
2043 ConsoleCursorInfo.dwSize = thickness;
2044 ConsoleCursorInfo.bVisible = s_cursor_visible;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002045
K.Takatadf5320c2022-09-01 13:20:16 +01002046 SetConsoleCursorInfo(g_hConOut, &ConsoleCursorInfo);
2047 if (s_cursor_visible)
2048 SetConsoleCursorPosition(g_hConOut, g_coord);
2049 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002050}
2051
2052 void
2053mch_update_cursor(void)
2054{
2055 int idx;
2056 int thickness;
2057
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002058# ifdef VIMDLL
2059 if (gui.in_use)
2060 return;
2061# endif
2062
Bram Moolenaar071d4272004-06-13 20:20:40 +00002063 /*
2064 * How the cursor is drawn depends on the current mode.
2065 */
2066 idx = get_shape_idx(FALSE);
2067
2068 if (shape_table[idx].shape == SHAPE_BLOCK)
Bram Moolenaar0f873732019-12-05 20:28:46 +01002069 thickness = 99; // 100 doesn't work on W95
Bram Moolenaar071d4272004-06-13 20:20:40 +00002070 else
2071 thickness = shape_table[idx].percentage;
2072 mch_set_cursor_shape(thickness);
2073}
2074#endif
2075
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002076#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002077/*
2078 * Handle FOCUS_EVENT.
2079 */
2080 static void
2081handle_focus_event(INPUT_RECORD ir)
2082{
2083 g_fJustGotFocus = ir.Event.FocusEvent.bSetFocus;
2084 ui_focus_change((int)g_fJustGotFocus);
2085}
2086
Bram Moolenaar78d21da2019-02-17 15:00:52 +01002087static void ResizeConBuf(HANDLE hConsole, COORD coordScreen);
2088
Bram Moolenaar071d4272004-06-13 20:20:40 +00002089/*
2090 * Wait until console input from keyboard or mouse is available,
2091 * or the time is up.
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02002092 * When "ignore_input" is TRUE even wait when input is available.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002093 * Return TRUE if something is available FALSE if not.
2094 */
2095 static int
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02002096WaitForChar(long msec, int ignore_input)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002097{
2098 DWORD dwNow = 0, dwEndTime = 0;
2099 INPUT_RECORD ir;
2100 DWORD cRecords;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002101 WCHAR ch, ch2;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002102# ifdef FEAT_TIMERS
Bram Moolenaar40b1b542016-04-20 20:18:23 +02002103 int tb_change_cnt = typebuf.tb_change_cnt;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002104# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002105
2106 if (msec > 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01002107 // Wait until the specified time has elapsed.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002108 dwEndTime = GetTickCount() + msec;
2109 else if (msec < 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01002110 // Wait forever.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002111 dwEndTime = INFINITE;
2112
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01002113 // We need to loop until the end of the time period, because
2114 // we might get multiple unusable mouse events in that time.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002115 for (;;)
2116 {
Bram Moolenaared5a9d62018-09-06 13:14:43 +02002117 // Only process messages when waiting.
2118 if (msec != 0)
2119 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002120# ifdef MESSAGE_QUEUE
Bram Moolenaared5a9d62018-09-06 13:14:43 +02002121 parse_queued_messages();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002122# endif
2123# ifdef FEAT_MZSCHEME
Bram Moolenaared5a9d62018-09-06 13:14:43 +02002124 mzvim_check_threads();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002125# endif
2126# ifdef FEAT_CLIENTSERVER
Bram Moolenaared5a9d62018-09-06 13:14:43 +02002127 serverProcessPendingMessages();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002128# endif
Bram Moolenaared5a9d62018-09-06 13:14:43 +02002129 }
Bram Moolenaarf12d9832016-01-29 21:11:25 +01002130
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02002131 if (g_nMouseClick != -1
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002132# ifdef FEAT_CLIENTSERVER
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02002133 || (!ignore_input && input_available())
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002134# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002135 )
2136 return TRUE;
2137
2138 if (msec > 0)
2139 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01002140 // If the specified wait time has passed, return. Beware that
2141 // GetTickCount() may wrap around (overflow).
Bram Moolenaar071d4272004-06-13 20:20:40 +00002142 dwNow = GetTickCount();
Bram Moolenaarb7512b72013-08-10 12:45:09 +02002143 if ((int)(dwNow - dwEndTime) >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002144 break;
2145 }
2146 if (msec != 0)
2147 {
Bram Moolenaar325b7a22004-07-05 15:58:32 +00002148 DWORD dwWaitTime = dwEndTime - dwNow;
2149
Bram Moolenaarc478ee32020-12-01 21:27:51 +01002150 // Don't wait for more than 11 msec to avoid dropping characters,
2151 // check channel while waiting for input and handle a callback from
2152 // 'balloonexpr'.
2153 if (dwWaitTime > 11)
2154 dwWaitTime = 11;
2155
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002156# ifdef FEAT_MZSCHEME
Bram Moolenaarc478ee32020-12-01 21:27:51 +01002157 if (mzthreads_allowed() && p_mzq > 0 && (long)dwWaitTime > p_mzq)
Bram Moolenaar0f873732019-12-05 20:28:46 +01002158 dwWaitTime = p_mzq; // don't wait longer than 'mzquantum'
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002159# endif
2160# ifdef FEAT_TIMERS
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01002161 // When waiting very briefly don't trigger timers.
2162 if (dwWaitTime > 10)
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01002163 {
2164 long due_time;
2165
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01002166 // Trigger timers and then get the time in msec until the next
2167 // one is due. Wait up to that time.
2168 due_time = check_due_timer();
2169 if (typebuf.tb_change_cnt != tb_change_cnt)
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01002170 {
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01002171 // timer may have used feedkeys().
2172 return FALSE;
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01002173 }
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01002174 if (due_time > 0 && dwWaitTime > (DWORD)due_time)
2175 dwWaitTime = due_time;
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01002176 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002177# endif
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01002178 if (
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002179# ifdef FEAT_CLIENTSERVER
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01002180 // Wait for either an event on the console input or a
2181 // message in the client-server window.
2182 msg_wait_for_multiple_objects(1, &g_hConIn, FALSE,
2183 dwWaitTime, QS_SENDMESSAGE) != WAIT_OBJECT_0
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002184# else
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01002185 wait_for_single_object(g_hConIn, dwWaitTime)
2186 != WAIT_OBJECT_0
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002187# endif
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01002188 )
2189 continue;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002190 }
2191
2192 cRecords = 0;
Bram Moolenaar3a69e112014-01-10 13:51:42 +01002193 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002194
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002195# ifdef FEAT_MBYTE_IME
matveyt4eb19142021-05-20 11:54:10 +02002196 // May have to redraw if the cursor ends up in the wrong place.
2197 // Only when not peeking.
Bram Moolenaar24959102022-05-07 20:01:16 +01002198 if (State == MODE_CMDLINE && msg_row == Rows - 1 && msec != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002199 {
2200 CONSOLE_SCREEN_BUFFER_INFO csbi;
2201
2202 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
2203 {
2204 if (csbi.dwCursorPosition.Y != msg_row)
2205 {
matveyte08795e2021-05-07 15:00:17 +02002206 // The screen is now messed up, must redraw the command
2207 // line and later all the windows.
Bram Moolenaara4d158b2022-08-14 14:17:45 +01002208 redraw_all_later(UPD_CLEAR);
matveyte08795e2021-05-07 15:00:17 +02002209 compute_cmdrow();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002210 redrawcmd();
2211 }
2212 }
2213 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002214# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002215
2216 if (cRecords > 0)
2217 {
2218 if (ir.EventType == KEY_EVENT && ir.Event.KeyEvent.bKeyDown)
2219 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002220# ifdef FEAT_MBYTE_IME
Bram Moolenaar0f873732019-12-05 20:28:46 +01002221 // Windows IME sends two '\n's with only one 'ENTER'. First:
2222 // wVirtualKeyCode == 13. second: wVirtualKeyCode == 0
K.Takata972db232022-02-04 10:45:38 +00002223 if (ir.Event.KeyEvent.uChar.UnicodeChar == 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00002224 && ir.Event.KeyEvent.wVirtualKeyCode == 13)
2225 {
Bram Moolenaar3a69e112014-01-10 13:51:42 +01002226 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002227 continue;
2228 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002229# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002230 if (decode_key_event(&ir.Event.KeyEvent, &ch, &ch2,
2231 NULL, FALSE))
2232 return TRUE;
2233 }
2234
Bram Moolenaar3a69e112014-01-10 13:51:42 +01002235 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002236
2237 if (ir.EventType == FOCUS_EVENT)
2238 handle_focus_event(ir);
2239 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
Bram Moolenaarc33ecb22018-02-11 16:40:45 +01002240 {
Bram Moolenaar78d21da2019-02-17 15:00:52 +01002241 COORD dwSize = ir.Event.WindowBufferSizeEvent.dwSize;
2242
Bram Moolenaar36698e32019-12-11 22:57:40 +01002243 // Only call shell_resized() when the size actually changed to
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002244 // avoid the screen is cleared.
Bram Moolenaar78d21da2019-02-17 15:00:52 +01002245 if (dwSize.X != Columns || dwSize.Y != Rows)
2246 {
2247 CONSOLE_SCREEN_BUFFER_INFO csbi;
2248 GetConsoleScreenBufferInfo(g_hConOut, &csbi);
Bram Moolenaar36698e32019-12-11 22:57:40 +01002249 dwSize.X = csbi.srWindow.Right - csbi.srWindow.Left + 1;
Bram Moolenaar78d21da2019-02-17 15:00:52 +01002250 dwSize.Y = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
Bram Moolenaar36698e32019-12-11 22:57:40 +01002251 if (dwSize.X != Columns || dwSize.Y != Rows)
2252 {
2253 ResizeConBuf(g_hConOut, dwSize);
2254 shell_resized();
2255 }
Bram Moolenaar78d21da2019-02-17 15:00:52 +01002256 }
Bram Moolenaarc33ecb22018-02-11 16:40:45 +01002257 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002258 else if (ir.EventType == MOUSE_EVENT
2259 && decode_mouse_event(&ir.Event.MouseEvent))
2260 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002261 }
2262 else if (msec == 0)
2263 break;
2264 }
2265
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002266# ifdef FEAT_CLIENTSERVER
Bram Moolenaar0f873732019-12-05 20:28:46 +01002267 // Something might have been received while we were waiting.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002268 if (input_available())
2269 return TRUE;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002270# endif
Bram Moolenaarf12d9832016-01-29 21:11:25 +01002271
Bram Moolenaar071d4272004-06-13 20:20:40 +00002272 return FALSE;
2273}
2274
Bram Moolenaar071d4272004-06-13 20:20:40 +00002275/*
2276 * return non-zero if a character is available
2277 */
2278 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002279mch_char_avail(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002280{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002281# ifdef VIMDLL
2282 if (gui.in_use)
2283 return TRUE;
2284# endif
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02002285 return WaitForChar(0L, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002286}
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02002287
2288# if defined(FEAT_TERMINAL) || defined(PROTO)
2289/*
2290 * Check for any pending input or messages.
2291 */
2292 int
2293mch_check_messages(void)
2294{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002295# ifdef VIMDLL
2296 if (gui.in_use)
2297 return TRUE;
2298# endif
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02002299 return WaitForChar(0L, TRUE);
2300}
2301# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002302
2303/*
2304 * Create the console input. Used when reading stdin doesn't work.
2305 */
2306 static void
2307create_conin(void)
2308{
2309 g_hConIn = CreateFile("CONIN$", GENERIC_READ|GENERIC_WRITE,
2310 FILE_SHARE_READ|FILE_SHARE_WRITE,
2311 (LPSECURITY_ATTRIBUTES) NULL,
Bram Moolenaareb3593b2006-04-22 22:33:57 +00002312 OPEN_EXISTING, 0, (HANDLE)NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002313 did_create_conin = TRUE;
2314}
2315
2316/*
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01002317 * Get a keystroke or a mouse event, use a blocking wait.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002318 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002319 static WCHAR
2320tgetch(int *pmodifiers, WCHAR *pch2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002321{
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002322 WCHAR ch;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002323
2324 for (;;)
2325 {
2326 INPUT_RECORD ir;
2327 DWORD cRecords = 0;
2328
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002329# ifdef FEAT_CLIENTSERVER
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02002330 (void)WaitForChar(-1L, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002331 if (input_available())
2332 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002333 if (g_nMouseClick != -1)
2334 return 0;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002335# endif
Bram Moolenaar3a69e112014-01-10 13:51:42 +01002336 if (read_console_input(g_hConIn, &ir, 1, &cRecords) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002337 {
2338 if (did_create_conin)
2339 read_error_exit();
2340 create_conin();
2341 continue;
2342 }
2343
2344 if (ir.EventType == KEY_EVENT)
2345 {
2346 if (decode_key_event(&ir.Event.KeyEvent, &ch, pch2,
2347 pmodifiers, TRUE))
2348 return ch;
2349 }
2350 else if (ir.EventType == FOCUS_EVENT)
2351 handle_focus_event(ir);
2352 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
2353 shell_resized();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002354 else if (ir.EventType == MOUSE_EVENT)
2355 {
2356 if (decode_mouse_event(&ir.Event.MouseEvent))
2357 return 0;
2358 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002359 }
2360}
Bram Moolenaar0f873732019-12-05 20:28:46 +01002361#endif // !FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00002362
2363
2364/*
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02002365 * mch_inchar(): low-level input function.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002366 * Get one or more characters from the keyboard or the mouse.
2367 * If time == 0, do not wait for characters.
2368 * If time == n, wait a short time for characters.
2369 * If time == -1, wait forever for characters.
2370 * Returns the number of characters read into buf.
2371 */
2372 int
2373mch_inchar(
Bram Moolenaar1266d672017-02-01 13:43:36 +01002374 char_u *buf UNUSED,
2375 int maxlen UNUSED,
2376 long time UNUSED,
2377 int tb_change_cnt UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002378{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002379#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002380
2381 int len;
2382 int c;
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01002383# ifdef VIMDLL
2384// Extra space for maximum three CSIs. E.g. U+1B6DB -> 0xF0 0x9B 0x9B 0x9B.
2385# define TYPEAHEADSPACE 6
2386# else
2387# define TYPEAHEADSPACE 0
2388# endif
2389# define TYPEAHEADLEN (20 + TYPEAHEADSPACE)
Bram Moolenaar0f873732019-12-05 20:28:46 +01002390 static char_u typeahead[TYPEAHEADLEN]; // previously typed bytes.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002391 static int typeaheadlen = 0;
2392
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002393# ifdef VIMDLL
2394 if (gui.in_use)
2395 return 0;
2396# endif
2397
Bram Moolenaar0f873732019-12-05 20:28:46 +01002398 // First use any typeahead that was kept because "buf" was too small.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002399 if (typeaheadlen > 0)
2400 goto theend;
2401
Bram Moolenaar071d4272004-06-13 20:20:40 +00002402 if (time >= 0)
2403 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01002404 if (!WaitForChar(time, FALSE)) // no character available
Bram Moolenaar071d4272004-06-13 20:20:40 +00002405 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002406 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01002407 else // time == -1, wait forever
Bram Moolenaar071d4272004-06-13 20:20:40 +00002408 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01002409 mch_set_winsize_now(); // Allow winsize changes from now on
Bram Moolenaar071d4272004-06-13 20:20:40 +00002410
Bram Moolenaar3918c952005-03-15 22:34:55 +00002411 /*
2412 * If there is no character available within 2 seconds (default)
2413 * write the autoscript file to disk. Or cause the CursorHold event
2414 * to be triggered.
2415 */
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02002416 if (!WaitForChar(p_ut, FALSE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002417 {
Bram Moolenaard35f9712005-12-18 22:02:33 +00002418 if (trigger_cursorhold() && maxlen >= 3)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002419 {
Bram Moolenaar3918c952005-03-15 22:34:55 +00002420 buf[0] = K_SPECIAL;
2421 buf[1] = KS_EXTRA;
2422 buf[2] = (int)KE_CURSORHOLD;
2423 return 3;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002424 }
Bram Moolenaar702517d2005-06-27 22:34:07 +00002425 before_blocking();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002426 }
2427 }
2428
2429 /*
2430 * Try to read as many characters as there are, until the buffer is full.
2431 */
2432
Bram Moolenaar0f873732019-12-05 20:28:46 +01002433 // we will get at least one key. Get more if they are available.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002434 g_fCBrkPressed = FALSE;
2435
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002436# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00002437 if (fdDump)
2438 fputc('[', fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002439# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002440
Bram Moolenaar0f873732019-12-05 20:28:46 +01002441 // Keep looping until there is something in the typeahead buffer and more
2442 // to get and still room in the buffer (up to two bytes for a char and
2443 // three bytes for a modifier).
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02002444 while ((typeaheadlen == 0 || WaitForChar(0L, FALSE))
Bram Moolenaar9f1983d2022-05-12 20:35:35 +01002445 && typeaheadlen + 5 + TYPEAHEADSPACE <= TYPEAHEADLEN)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002446 {
2447 if (typebuf_changed(tb_change_cnt))
2448 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01002449 // "buf" may be invalid now if a client put something in the
2450 // typeahead buffer and "buf" is in the typeahead buffer.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002451 typeaheadlen = 0;
2452 break;
2453 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002454 if (g_nMouseClick != -1)
2455 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002456# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00002457 if (fdDump)
2458 fprintf(fdDump, "{%02x @ %d, %d}",
2459 g_nMouseClick, g_xMouse, g_yMouse);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002460# endif
Christopher Plewright2a46f812022-10-16 19:47:45 +01002461 char_u modifiers = ((char_u *)(&g_nMouseClick))[0];
2462 char_u scroll_dir = ((char_u *)(&g_nMouseClick))[1];
2463
2464 if (scroll_dir == KE_MOUSEDOWN
2465 || scroll_dir == KE_MOUSEUP
2466 || scroll_dir == KE_MOUSELEFT
2467 || scroll_dir == KE_MOUSERIGHT)
2468 {
2469 if (modifiers > 0)
2470 {
Christopher Plewright03193062022-11-22 12:58:27 +00002471 // use K_SPECIAL instead of CSI to make mappings work
2472 typeahead[typeaheadlen++] = K_SPECIAL;
Christopher Plewright2a46f812022-10-16 19:47:45 +01002473 typeahead[typeaheadlen++] = KS_MODIFIER;
2474 typeahead[typeaheadlen++] = modifiers;
2475 }
2476 typeahead[typeaheadlen++] = CSI;
2477 typeahead[typeaheadlen++] = KS_EXTRA;
2478 typeahead[typeaheadlen++] = scroll_dir;
Christopher Plewright2a46f812022-10-16 19:47:45 +01002479 }
2480 else
2481 {
2482 typeahead[typeaheadlen++] = ESC + 128;
2483 typeahead[typeaheadlen++] = 'M';
2484 typeahead[typeaheadlen++] = g_nMouseClick;
Christopher Plewright2a46f812022-10-16 19:47:45 +01002485 }
Christopher Plewright36446bb2022-11-23 22:28:08 +00002486
2487 // Pass the pointer coordinates of the mouse event in 2 bytes,
2488 // allowing for > 223 columns. Both for click and scroll events.
2489 // This is the same as what is used for the GUI.
2490 typeahead[typeaheadlen++] = (char_u)(g_xMouse / 128 + ' ' + 1);
2491 typeahead[typeaheadlen++] = (char_u)(g_xMouse % 128 + ' ' + 1);
2492 typeahead[typeaheadlen++] = (char_u)(g_yMouse / 128 + ' ' + 1);
2493 typeahead[typeaheadlen++] = (char_u)(g_yMouse % 128 + ' ' + 1);
2494
2495 g_nMouseClick = -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002496 }
2497 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00002498 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002499 WCHAR ch2 = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002500 int modifiers = 0;
2501
2502 c = tgetch(&modifiers, &ch2);
2503
Christopher Plewrightc8b20492023-01-04 18:06:00 +00002504 c = simplify_key(c, &modifiers);
2505
Christopher Plewright7b0afc12022-12-30 16:54:58 +00002506 // Some chars need adjustment when the Ctrl modifier is used.
2507 ++no_reduce_keys;
2508 c = may_adjust_key_for_ctrl(modifiers, c);
2509 --no_reduce_keys;
2510
2511 // remove the SHIFT modifier for keys where it's already included,
2512 // e.g., '(' and '*'
2513 modifiers = may_remove_shift_modifier(modifiers, c);
2514
Bram Moolenaar071d4272004-06-13 20:20:40 +00002515 if (typebuf_changed(tb_change_cnt))
2516 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01002517 // "buf" may be invalid now if a client put something in the
2518 // typeahead buffer and "buf" is in the typeahead buffer.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002519 typeaheadlen = 0;
2520 break;
2521 }
2522
2523 if (c == Ctrl_C && ctrl_c_interrupts)
2524 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002525# if defined(FEAT_CLIENTSERVER)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002526 trash_input_buf();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002527# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002528 got_int = TRUE;
2529 }
2530
Bram Moolenaar071d4272004-06-13 20:20:40 +00002531 if (g_nMouseClick == -1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002532 {
2533 int n = 1;
2534
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002535 if (ch2 == NUL)
2536 {
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01002537 int i, j;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002538 char_u *p;
2539 WCHAR ch[2];
2540
2541 ch[0] = c;
Bram Moolenaar0f873732019-12-05 20:28:46 +01002542 if (c >= 0xD800 && c <= 0xDBFF) // High surrogate
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002543 {
2544 ch[1] = tgetch(&modifiers, &ch2);
2545 n++;
2546 }
2547 p = utf16_to_enc(ch, &n);
2548 if (p != NULL)
2549 {
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01002550 for (i = 0, j = 0; i < n; i++)
2551 {
2552 typeahead[typeaheadlen + j++] = p[i];
2553# ifdef VIMDLL
2554 if (p[i] == CSI)
2555 {
2556 typeahead[typeaheadlen + j++] = KS_EXTRA;
2557 typeahead[typeaheadlen + j++] = KE_CSI;
2558 }
2559# endif
2560 }
2561 n = j;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002562 vim_free(p);
2563 }
2564 }
2565 else
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01002566 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002567 typeahead[typeaheadlen] = c;
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01002568# ifdef VIMDLL
2569 if (c == CSI)
2570 {
2571 typeahead[typeaheadlen + 1] = KS_EXTRA;
2572 typeahead[typeaheadlen + 2] = KE_CSI;
2573 n = 3;
2574 }
2575# endif
2576 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002577 if (ch2 != NUL)
2578 {
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +02002579 if (c == K_NUL)
Bram Moolenaarfeeb4d02017-12-05 15:14:46 +01002580 {
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +02002581 switch (ch2)
2582 {
2583 case (WCHAR)'\324': // SHIFT+Insert
2584 case (WCHAR)'\325': // CTRL+Insert
2585 case (WCHAR)'\327': // SHIFT+Delete
2586 case (WCHAR)'\330': // CTRL+Delete
2587 typeahead[typeaheadlen + n] = (char_u)ch2;
2588 n++;
2589 break;
2590
2591 default:
2592 typeahead[typeaheadlen + n] = 3;
2593 typeahead[typeaheadlen + n + 1] = (char_u)ch2;
2594 n += 2;
2595 break;
2596 }
Bram Moolenaarfeeb4d02017-12-05 15:14:46 +01002597 }
2598 else
2599 {
2600 typeahead[typeaheadlen + n] = 3;
2601 typeahead[typeaheadlen + n + 1] = (char_u)ch2;
2602 n += 2;
2603 }
Bram Moolenaar45500912014-07-09 20:51:07 +02002604 }
2605
Bram Moolenaar0f873732019-12-05 20:28:46 +01002606 // Use the ALT key to set the 8th bit of the character
2607 // when it's one byte, the 8th bit isn't set yet and not
2608 // using a double-byte encoding (would become a lead
2609 // byte).
Bram Moolenaar071d4272004-06-13 20:20:40 +00002610 if ((modifiers & MOD_MASK_ALT)
2611 && n == 1
2612 && (typeahead[typeaheadlen] & 0x80) == 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00002613 && !enc_dbcs
Bram Moolenaar071d4272004-06-13 20:20:40 +00002614 )
2615 {
Bram Moolenaar85a3e5c2007-11-20 16:22:16 +00002616 n = (*mb_char2bytes)(typeahead[typeaheadlen] | 0x80,
2617 typeahead + typeaheadlen);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002618 modifiers &= ~MOD_MASK_ALT;
2619 }
2620
2621 if (modifiers != 0)
2622 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01002623 // Prepend modifiers to the character.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002624 mch_memmove(typeahead + typeaheadlen + 3,
2625 typeahead + typeaheadlen, n);
2626 typeahead[typeaheadlen++] = K_SPECIAL;
2627 typeahead[typeaheadlen++] = (char_u)KS_MODIFIER;
2628 typeahead[typeaheadlen++] = modifiers;
2629 }
2630
2631 typeaheadlen += n;
2632
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002633# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00002634 if (fdDump)
2635 fputc(c, fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002636# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002637 }
2638 }
2639 }
2640
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002641# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00002642 if (fdDump)
2643 {
2644 fputs("]\n", fdDump);
2645 fflush(fdDump);
2646 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002647# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002648
Bram Moolenaar071d4272004-06-13 20:20:40 +00002649theend:
Bram Moolenaar0f873732019-12-05 20:28:46 +01002650 // Move typeahead to "buf", as much as fits.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002651 len = 0;
2652 while (len < maxlen && typeaheadlen > 0)
2653 {
2654 buf[len++] = typeahead[0];
2655 mch_memmove(typeahead, typeahead + 1, --typeaheadlen);
2656 }
Bram Moolenaar4c5678f2022-11-30 18:12:19 +00002657# ifdef FEAT_EVAL
Bram Moolenaar7ca86fe2020-09-03 19:25:11 +02002658 if (len > 0)
2659 {
2660 buf[len] = NUL;
2661 ch_log(NULL, "raw key input: \"%s\"", buf);
2662 }
K.Takata6e1d31e2022-02-03 13:05:32 +00002663# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002664 return len;
2665
Bram Moolenaar0f873732019-12-05 20:28:46 +01002666#else // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00002667 return 0;
Bram Moolenaar0f873732019-12-05 20:28:46 +01002668#endif // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00002669}
2670
Bram Moolenaar82881492012-11-20 16:53:39 +01002671#ifndef PROTO
2672# ifndef __MINGW32__
Bram Moolenaar0f873732019-12-05 20:28:46 +01002673# include <shellapi.h> // required for FindExecutable()
Bram Moolenaar82881492012-11-20 16:53:39 +01002674# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002675#endif
2676
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002677/*
Bram Moolenaar95da1362020-05-30 18:37:55 +02002678 * Return TRUE if "name" is an executable file, FALSE if not or it doesn't exist.
Bram Moolenaar43663192017-03-05 14:29:12 +01002679 * When returning TRUE and "path" is not NULL save the path and set "*path" to
2680 * the allocated memory.
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00002681 * TODO: Should somehow check if it's really executable.
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002682 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002683 static int
Bram Moolenaar95da1362020-05-30 18:37:55 +02002684executable_file(char *name, char_u **path)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002685{
LemonBoy40fd7e62022-05-05 20:18:16 +01002686 int attrs = win32_getattrs((char_u *)name);
2687
2688 // The file doesn't exist or is a folder.
2689 if (attrs == -1 || (attrs & FILE_ATTRIBUTE_DIRECTORY))
2690 return FALSE;
2691 // Check if the file is an AppExecLink, a special alias used by Windows
2692 // Store for its apps.
2693 if (attrs & FILE_ATTRIBUTE_REPARSE_POINT)
Bram Moolenaar43663192017-03-05 14:29:12 +01002694 {
LemonBoy40fd7e62022-05-05 20:18:16 +01002695 char_u *res = resolve_appexeclink((char_u *)name);
2696 if (res == NULL)
2697 return FALSE;
2698 // The path is already absolute.
Bram Moolenaar95da1362020-05-30 18:37:55 +02002699 if (path != NULL)
LemonBoy40fd7e62022-05-05 20:18:16 +01002700 *path = res;
2701 else
2702 vim_free(res);
Bram Moolenaar95da1362020-05-30 18:37:55 +02002703 }
LemonBoy40fd7e62022-05-05 20:18:16 +01002704 else if (path != NULL)
2705 *path = FullName_save((char_u *)name, FALSE);
2706 return TRUE;
Bram Moolenaar95da1362020-05-30 18:37:55 +02002707}
2708
2709/*
2710 * If "use_path" is TRUE: Return TRUE if "name" is in $PATH.
2711 * If "use_path" is FALSE: Return TRUE if "name" exists.
2712 * If "use_pathext" is TRUE search "name" with extensions in $PATHEXT.
2713 * When returning TRUE and "path" is not NULL save the path and set "*path" to
2714 * the allocated memory.
2715 */
2716 static int
2717executable_exists(char *name, char_u **path, int use_path, int use_pathext)
2718{
2719 // WinNT and later can use _MAX_PATH wide characters for a pathname, which
2720 // means that the maximum pathname is _MAX_PATH * 3 bytes when 'enc' is
2721 // UTF-8.
2722 char_u buf[_MAX_PATH * 3];
2723 size_t len = STRLEN(name);
2724 size_t tmplen;
2725 char_u *p, *e, *e2;
2726 char_u *pathbuf = NULL;
2727 char_u *pathext = NULL;
2728 char_u *pathextbuf = NULL;
Mike Williamsa3d1b292021-06-30 20:56:00 +02002729 char_u *shname = NULL;
Bram Moolenaar95da1362020-05-30 18:37:55 +02002730 int noext = FALSE;
2731 int retval = FALSE;
2732
2733 if (len >= sizeof(buf)) // safety check
Bram Moolenaar43663192017-03-05 14:29:12 +01002734 return FALSE;
Bram Moolenaar95da1362020-05-30 18:37:55 +02002735
2736 // Using the name directly when a Unix-shell like 'shell'.
Mike Williamsa3d1b292021-06-30 20:56:00 +02002737 shname = gettail(p_sh);
2738 if (strstr((char *)shname, "sh") != NULL &&
2739 !(strstr((char *)shname, "powershell") != NULL
2740 || strstr((char *)shname, "pwsh") != NULL))
Bram Moolenaar95da1362020-05-30 18:37:55 +02002741 noext = TRUE;
2742
2743 if (use_pathext)
2744 {
2745 pathext = mch_getenv("PATHEXT");
2746 if (pathext == NULL)
2747 pathext = (char_u *)".com;.exe;.bat;.cmd";
2748
2749 if (noext == FALSE)
2750 {
2751 /*
2752 * Loop over all extensions in $PATHEXT.
2753 * Check "name" ends with extension.
2754 */
2755 p = pathext;
2756 while (*p)
2757 {
2758 if (p[0] == ';'
2759 || (p[0] == '.' && (p[1] == NUL || p[1] == ';')))
2760 {
2761 // Skip empty or single ".".
2762 ++p;
2763 continue;
2764 }
2765 e = vim_strchr(p, ';');
2766 if (e == NULL)
2767 e = p + STRLEN(p);
2768 tmplen = e - p;
2769
2770 if (_strnicoll(name + len - tmplen, (char *)p, tmplen) == 0)
2771 {
2772 noext = TRUE;
2773 break;
2774 }
2775
2776 p = e;
2777 }
2778 }
Bram Moolenaar43663192017-03-05 14:29:12 +01002779 }
2780
Dominique Pelleaf4a61a2021-12-27 17:21:41 +00002781 // Prepend single "." to pathext, it means no extension added.
Bram Moolenaar95da1362020-05-30 18:37:55 +02002782 if (pathext == NULL)
2783 pathext = (char_u *)".";
2784 else if (noext == TRUE)
2785 {
2786 if (pathextbuf == NULL)
2787 pathextbuf = alloc(STRLEN(pathext) + 3);
2788 if (pathextbuf == NULL)
2789 {
2790 retval = FALSE;
2791 goto theend;
2792 }
2793 STRCPY(pathextbuf, ".;");
2794 STRCAT(pathextbuf, pathext);
2795 pathext = pathextbuf;
2796 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002797
Bram Moolenaar95da1362020-05-30 18:37:55 +02002798 // Use $PATH when "use_path" is TRUE and "name" is basename.
2799 if (use_path && gettail((char_u *)name) == (char_u *)name)
2800 {
2801 p = mch_getenv("PATH");
2802 if (p != NULL)
2803 {
2804 pathbuf = alloc(STRLEN(p) + 3);
2805 if (pathbuf == NULL)
2806 {
2807 retval = FALSE;
2808 goto theend;
2809 }
Yasuhiro Matsumoto05cf63e2022-05-03 11:02:28 +01002810
2811 if (mch_getenv("NoDefaultCurrentDirectoryInExePath") == NULL)
2812 STRCPY(pathbuf, ".;");
2813 else
2814 *pathbuf = NUL;
Bram Moolenaar95da1362020-05-30 18:37:55 +02002815 STRCAT(pathbuf, p);
2816 }
2817 }
2818
2819 /*
2820 * Walk through all entries in $PATH to check if "name" exists there and
2821 * is an executable file.
2822 */
2823 p = (pathbuf != NULL) ? pathbuf : (char_u *)".";
2824 while (*p)
2825 {
2826 if (*p == ';') // Skip empty entry
2827 {
2828 ++p;
2829 continue;
2830 }
2831 e = vim_strchr(p, ';');
2832 if (e == NULL)
2833 e = p + STRLEN(p);
2834
2835 if (e - p + len + 2 > sizeof(buf))
2836 {
2837 retval = FALSE;
2838 goto theend;
2839 }
2840 // A single "." that means current dir.
2841 if (e - p == 1 && *p == '.')
2842 STRCPY(buf, name);
2843 else
2844 {
2845 vim_strncpy(buf, p, e - p);
2846 add_pathsep(buf);
2847 STRCAT(buf, name);
2848 }
2849 tmplen = STRLEN(buf);
2850
2851 /*
2852 * Loop over all extensions in $PATHEXT.
2853 * Check "name" with extension added.
2854 */
2855 p = pathext;
2856 while (*p)
2857 {
2858 if (*p == ';')
2859 {
2860 // Skip empty entry
2861 ++p;
2862 continue;
2863 }
2864 e2 = vim_strchr(p, (int)';');
2865 if (e2 == NULL)
2866 e2 = p + STRLEN(p);
2867
2868 if (!(p[0] == '.' && (p[1] == NUL || p[1] == ';')))
2869 {
2870 // Not a single "." that means no extension is added.
2871 if (e2 - p + tmplen + 1 > sizeof(buf))
2872 {
2873 retval = FALSE;
2874 goto theend;
2875 }
2876 vim_strncpy(buf + tmplen, p, e2 - p);
2877 }
2878 if (executable_file((char *)buf, path))
2879 {
2880 retval = TRUE;
2881 goto theend;
2882 }
2883
2884 p = e2;
2885 }
2886
2887 p = e;
2888 }
2889
2890theend:
2891 free(pathextbuf);
2892 free(pathbuf);
2893 return retval;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002894}
2895
Bram Moolenaar1eed5322019-02-26 17:03:54 +01002896#if (defined(__MINGW32__) && __MSVCRT_VERSION__ >= 0x800) || \
2897 (defined(_MSC_VER) && _MSC_VER >= 1400)
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002898/*
2899 * Bad parameter handler.
2900 *
2901 * Certain MS CRT functions will intentionally crash when passed invalid
2902 * parameters to highlight possible security holes. Setting this function as
2903 * the bad parameter handler will prevent the crash.
2904 *
2905 * In debug builds the parameters contain CRT information that might help track
2906 * down the source of a problem, but in non-debug builds the arguments are all
2907 * NULL/0. Debug builds will also produce assert dialogs from the CRT, it is
2908 * worth allowing these to make debugging of issues easier.
2909 */
2910 static void
Yegappan Lakshmanana34b4462022-06-11 10:43:26 +01002911bad_param_handler(const wchar_t *expression UNUSED,
2912 const wchar_t *function UNUSED,
2913 const wchar_t *file UNUSED,
2914 unsigned int line UNUSED,
2915 uintptr_t pReserved UNUSED)
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002916{
2917}
2918
2919# define SET_INVALID_PARAM_HANDLER \
2920 ((void)_set_invalid_parameter_handler(bad_param_handler))
2921#else
2922# define SET_INVALID_PARAM_HANDLER
2923#endif
2924
Bram Moolenaar4f974752019-02-17 17:44:42 +01002925#ifdef FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00002926
2927/*
2928 * GUI version of mch_init().
2929 */
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002930 static void
2931mch_init_g(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002932{
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002933# ifndef __MINGW32__
Bram Moolenaar071d4272004-06-13 20:20:40 +00002934 extern int _fmode;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002935# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002936
Bram Moolenaar0f873732019-12-05 20:28:46 +01002937 // Silently handle invalid parameters to CRT functions
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002938 SET_INVALID_PARAM_HANDLER;
2939
Bram Moolenaar0f873732019-12-05 20:28:46 +01002940 // Let critical errors result in a failure, not in a dialog box. Required
2941 // for the timestamp test to work on removed floppies.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002942 SetErrorMode(SEM_FAILCRITICALERRORS);
2943
Bram Moolenaar0f873732019-12-05 20:28:46 +01002944 _fmode = O_BINARY; // we do our own CR-LF translation
Bram Moolenaar071d4272004-06-13 20:20:40 +00002945
Bram Moolenaar0f873732019-12-05 20:28:46 +01002946 // Specify window size. Is there a place to get the default from?
Bram Moolenaar071d4272004-06-13 20:20:40 +00002947 Rows = 25;
2948 Columns = 80;
2949
Bram Moolenaar0f873732019-12-05 20:28:46 +01002950 // Look for 'vimrun'
Bram Moolenaar071d4272004-06-13 20:20:40 +00002951 {
2952 char_u vimrun_location[_MAX_PATH + 4];
2953
Bram Moolenaar0f873732019-12-05 20:28:46 +01002954 // First try in same directory as gvim.exe
Bram Moolenaar071d4272004-06-13 20:20:40 +00002955 STRCPY(vimrun_location, exe_name);
2956 STRCPY(gettail(vimrun_location), "vimrun.exe");
2957 if (mch_getperm(vimrun_location) >= 0)
2958 {
2959 if (*skiptowhite(vimrun_location) != NUL)
2960 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01002961 // Enclose path with white space in double quotes.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002962 mch_memmove(vimrun_location + 1, vimrun_location,
2963 STRLEN(vimrun_location) + 1);
2964 *vimrun_location = '"';
2965 STRCPY(gettail(vimrun_location), "vimrun\" ");
2966 }
2967 else
2968 STRCPY(gettail(vimrun_location), "vimrun ");
2969
2970 vimrun_path = (char *)vim_strsave(vimrun_location);
2971 s_dont_use_vimrun = FALSE;
2972 }
Bram Moolenaar95da1362020-05-30 18:37:55 +02002973 else if (executable_exists("vimrun.exe", NULL, TRUE, FALSE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002974 s_dont_use_vimrun = FALSE;
2975
Bram Moolenaar0f873732019-12-05 20:28:46 +01002976 // Don't give the warning for a missing vimrun.exe right now, but only
2977 // when vimrun was supposed to be used. Don't bother people that do
2978 // not need vimrun.exe.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002979 if (s_dont_use_vimrun)
2980 need_vimrun_warning = TRUE;
2981 }
2982
2983 /*
2984 * If "finstr.exe" doesn't exist, use "grep -n" for 'grepprg'.
2985 * Otherwise the default "findstr /n" is used.
2986 */
Bram Moolenaar95da1362020-05-30 18:37:55 +02002987 if (!executable_exists("findstr.exe", NULL, TRUE, FALSE))
Bram Moolenaar75ab5902022-04-18 15:36:40 +01002988 set_option_value_give_err((char_u *)"grepprg",
2989 0, (char_u *)"grep -n", 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002990
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002991# ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01002992 win_clip_init();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002993# endif
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01002994
2995 vtp_flag_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002996}
2997
2998
Bram Moolenaar0f873732019-12-05 20:28:46 +01002999#endif // FEAT_GUI_MSWIN
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003000
3001#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003002
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003003# define SRWIDTH(sr) ((sr).Right - (sr).Left + 1)
3004# define SRHEIGHT(sr) ((sr).Bottom - (sr).Top + 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003005
3006/*
3007 * ClearConsoleBuffer()
3008 * Description:
3009 * Clears the entire contents of the console screen buffer, using the
3010 * specified attribute.
3011 * Returns:
3012 * TRUE on success
3013 */
3014 static BOOL
3015ClearConsoleBuffer(WORD wAttribute)
3016{
3017 CONSOLE_SCREEN_BUFFER_INFO csbi;
3018 COORD coord;
3019 DWORD NumCells, dummy;
3020
3021 if (!GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3022 return FALSE;
3023
3024 NumCells = csbi.dwSize.X * csbi.dwSize.Y;
3025 coord.X = 0;
3026 coord.Y = 0;
3027 if (!FillConsoleOutputCharacter(g_hConOut, ' ', NumCells,
3028 coord, &dummy))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003029 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003030 if (!FillConsoleOutputAttribute(g_hConOut, wAttribute, NumCells,
3031 coord, &dummy))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003032 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003033
3034 return TRUE;
3035}
3036
3037/*
3038 * FitConsoleWindow()
3039 * Description:
3040 * Checks if the console window will fit within given buffer dimensions.
3041 * Also, if requested, will shrink the window to fit.
3042 * Returns:
3043 * TRUE on success
3044 */
3045 static BOOL
3046FitConsoleWindow(
3047 COORD dwBufferSize,
3048 BOOL WantAdjust)
3049{
3050 CONSOLE_SCREEN_BUFFER_INFO csbi;
3051 COORD dwWindowSize;
3052 BOOL NeedAdjust = FALSE;
3053
3054 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3055 {
3056 /*
3057 * A buffer resize will fail if the current console window does
3058 * not lie completely within that buffer. To avoid this, we might
3059 * have to move and possibly shrink the window.
3060 */
3061 if (csbi.srWindow.Right >= dwBufferSize.X)
3062 {
3063 dwWindowSize.X = SRWIDTH(csbi.srWindow);
3064 if (dwWindowSize.X > dwBufferSize.X)
3065 dwWindowSize.X = dwBufferSize.X;
3066 csbi.srWindow.Right = dwBufferSize.X - 1;
3067 csbi.srWindow.Left = dwBufferSize.X - dwWindowSize.X;
3068 NeedAdjust = TRUE;
3069 }
3070 if (csbi.srWindow.Bottom >= dwBufferSize.Y)
3071 {
3072 dwWindowSize.Y = SRHEIGHT(csbi.srWindow);
3073 if (dwWindowSize.Y > dwBufferSize.Y)
3074 dwWindowSize.Y = dwBufferSize.Y;
3075 csbi.srWindow.Bottom = dwBufferSize.Y - 1;
3076 csbi.srWindow.Top = dwBufferSize.Y - dwWindowSize.Y;
3077 NeedAdjust = TRUE;
3078 }
3079 if (NeedAdjust && WantAdjust)
3080 {
3081 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &csbi.srWindow))
3082 return FALSE;
3083 }
3084 return TRUE;
3085 }
3086
3087 return FALSE;
3088}
3089
3090typedef struct ConsoleBufferStruct
3091{
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003092 BOOL IsValid;
3093 CONSOLE_SCREEN_BUFFER_INFO Info;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003094 PCHAR_INFO Buffer;
3095 COORD BufferSize;
Bram Moolenaar444fda22017-08-11 20:37:00 +02003096 PSMALL_RECT Regions;
3097 int NumRegions;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003098} ConsoleBuffer;
3099
3100/*
3101 * SaveConsoleBuffer()
3102 * Description:
3103 * Saves important information about the console buffer, including the
3104 * actual buffer contents. The saved information is suitable for later
3105 * restoration by RestoreConsoleBuffer().
3106 * Returns:
3107 * TRUE if all information was saved; FALSE otherwise
3108 * If FALSE, still sets cb->IsValid if buffer characteristics were saved.
3109 */
3110 static BOOL
3111SaveConsoleBuffer(
3112 ConsoleBuffer *cb)
3113{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003114 DWORD NumCells;
3115 COORD BufferCoord;
3116 SMALL_RECT ReadRegion;
3117 WORD Y, Y_incr;
Bram Moolenaar444fda22017-08-11 20:37:00 +02003118 int i, numregions;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003119
Bram Moolenaar071d4272004-06-13 20:20:40 +00003120 if (cb == NULL)
3121 return FALSE;
3122
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003123 if (!GetConsoleScreenBufferInfo(g_hConOut, &cb->Info))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003124 {
3125 cb->IsValid = FALSE;
3126 return FALSE;
3127 }
3128 cb->IsValid = TRUE;
3129
Christopher Plewright1140b512022-11-12 18:46:05 +00003130 // VTP uses alternate screen buffer.
3131 // No need to save buffer contents for restoration.
Christopher Plewrightc8b126d2022-12-22 13:45:23 +00003132 if (use_alternate_screen_buffer)
Christopher Plewright1140b512022-11-12 18:46:05 +00003133 return TRUE;
3134
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003135 /*
3136 * Allocate a buffer large enough to hold the entire console screen
3137 * buffer. If this ConsoleBuffer structure has already been initialized
3138 * with a buffer of the correct size, then just use that one.
3139 */
3140 if (!cb->IsValid || cb->Buffer == NULL ||
3141 cb->BufferSize.X != cb->Info.dwSize.X ||
3142 cb->BufferSize.Y != cb->Info.dwSize.Y)
3143 {
3144 cb->BufferSize.X = cb->Info.dwSize.X;
3145 cb->BufferSize.Y = cb->Info.dwSize.Y;
3146 NumCells = cb->BufferSize.X * cb->BufferSize.Y;
3147 vim_free(cb->Buffer);
Bram Moolenaarc799fe22019-05-28 23:08:19 +02003148 cb->Buffer = ALLOC_MULT(CHAR_INFO, NumCells);
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003149 if (cb->Buffer == NULL)
3150 return FALSE;
3151 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003152
3153 /*
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003154 * We will now copy the console screen buffer into our buffer.
3155 * ReadConsoleOutput() seems to be limited as far as how much you
3156 * can read at a time. Empirically, this number seems to be about
3157 * 12000 cells (rows * columns). Start at position (0, 0) and copy
3158 * in chunks until it is all copied. The chunks will all have the
3159 * same horizontal characteristics, so initialize them now. The
3160 * height of each chunk will be (12000 / width).
Bram Moolenaar071d4272004-06-13 20:20:40 +00003161 */
Bram Moolenaar61594242015-09-01 20:23:37 +02003162 BufferCoord.X = 0;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003163 ReadRegion.Left = 0;
3164 ReadRegion.Right = cb->Info.dwSize.X - 1;
3165 Y_incr = 12000 / cb->Info.dwSize.X;
Bram Moolenaar444fda22017-08-11 20:37:00 +02003166
3167 numregions = (cb->Info.dwSize.Y + Y_incr - 1) / Y_incr;
3168 if (cb->Regions == NULL || numregions != cb->NumRegions)
3169 {
3170 cb->NumRegions = numregions;
3171 vim_free(cb->Regions);
Bram Moolenaarc799fe22019-05-28 23:08:19 +02003172 cb->Regions = ALLOC_MULT(SMALL_RECT, cb->NumRegions);
Bram Moolenaar444fda22017-08-11 20:37:00 +02003173 if (cb->Regions == NULL)
3174 {
Bram Moolenaard23a8232018-02-10 18:45:26 +01003175 VIM_CLEAR(cb->Buffer);
Bram Moolenaar444fda22017-08-11 20:37:00 +02003176 return FALSE;
3177 }
3178 }
3179
3180 for (i = 0, Y = 0; i < cb->NumRegions; i++, Y += Y_incr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003181 {
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003182 /*
3183 * Read into position (0, Y) in our buffer.
3184 */
3185 BufferCoord.Y = Y;
3186 /*
3187 * Read the region whose top left corner is (0, Y) and whose bottom
3188 * right corner is (width - 1, Y + Y_incr - 1). This should define
3189 * a region of size width by Y_incr. Don't worry if this region is
3190 * too large for the remaining buffer; it will be cropped.
3191 */
3192 ReadRegion.Top = Y;
3193 ReadRegion.Bottom = Y + Y_incr - 1;
Bram Moolenaar0f873732019-12-05 20:28:46 +01003194 if (!ReadConsoleOutputW(g_hConOut, // output handle
3195 cb->Buffer, // our buffer
3196 cb->BufferSize, // dimensions of our buffer
3197 BufferCoord, // offset in our buffer
3198 &ReadRegion)) // region to save
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003199 {
Bram Moolenaard23a8232018-02-10 18:45:26 +01003200 VIM_CLEAR(cb->Buffer);
3201 VIM_CLEAR(cb->Regions);
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003202 return FALSE;
3203 }
Bram Moolenaar444fda22017-08-11 20:37:00 +02003204 cb->Regions[i] = ReadRegion;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003205 }
3206
3207 return TRUE;
3208}
3209
3210/*
3211 * RestoreConsoleBuffer()
3212 * Description:
3213 * Restores important information about the console buffer, including the
3214 * actual buffer contents, if desired. The information to restore is in
3215 * the same format used by SaveConsoleBuffer().
3216 * Returns:
3217 * TRUE on success
3218 */
3219 static BOOL
3220RestoreConsoleBuffer(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003221 ConsoleBuffer *cb,
3222 BOOL RestoreScreen)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003223{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003224 COORD BufferCoord;
3225 SMALL_RECT WriteRegion;
Bram Moolenaar444fda22017-08-11 20:37:00 +02003226 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003227
Christopher Plewright1140b512022-11-12 18:46:05 +00003228 // VTP uses alternate screen buffer.
3229 // No need to restore buffer contents.
Christopher Plewrightc8b126d2022-12-22 13:45:23 +00003230 if (use_alternate_screen_buffer)
Christopher Plewright1140b512022-11-12 18:46:05 +00003231 return TRUE;
3232
Bram Moolenaar071d4272004-06-13 20:20:40 +00003233 if (cb == NULL || !cb->IsValid)
3234 return FALSE;
3235
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003236 /*
3237 * Before restoring the buffer contents, clear the current buffer, and
3238 * restore the cursor position and window information. Doing this now
3239 * prevents old buffer contents from "flashing" onto the screen.
3240 */
3241 if (RestoreScreen)
3242 ClearConsoleBuffer(cb->Info.wAttributes);
3243
3244 FitConsoleWindow(cb->Info.dwSize, TRUE);
3245 if (!SetConsoleScreenBufferSize(g_hConOut, cb->Info.dwSize))
3246 return FALSE;
3247 if (!SetConsoleTextAttribute(g_hConOut, cb->Info.wAttributes))
3248 return FALSE;
3249
3250 if (!RestoreScreen)
3251 {
3252 /*
3253 * No need to restore the screen buffer contents, so we're done.
3254 */
3255 return TRUE;
3256 }
3257
3258 if (!SetConsoleCursorPosition(g_hConOut, cb->Info.dwCursorPosition))
3259 return FALSE;
3260 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &cb->Info.srWindow))
3261 return FALSE;
3262
3263 /*
3264 * Restore the screen buffer contents.
3265 */
3266 if (cb->Buffer != NULL)
3267 {
Bram Moolenaar444fda22017-08-11 20:37:00 +02003268 for (i = 0; i < cb->NumRegions; i++)
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003269 {
Bram Moolenaar444fda22017-08-11 20:37:00 +02003270 BufferCoord.X = cb->Regions[i].Left;
3271 BufferCoord.Y = cb->Regions[i].Top;
3272 WriteRegion = cb->Regions[i];
Bram Moolenaar0f873732019-12-05 20:28:46 +01003273 if (!WriteConsoleOutputW(g_hConOut, // output handle
3274 cb->Buffer, // our buffer
3275 cb->BufferSize, // dimensions of our buffer
3276 BufferCoord, // offset in our buffer
3277 &WriteRegion)) // region to restore
Bram Moolenaar444fda22017-08-11 20:37:00 +02003278 return FALSE;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003279 }
3280 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003281
3282 return TRUE;
3283}
3284
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003285# define FEAT_RESTORE_ORIG_SCREEN
3286# ifdef FEAT_RESTORE_ORIG_SCREEN
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003287static ConsoleBuffer g_cbOrig = { 0 };
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003288# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003289static ConsoleBuffer g_cbNonTermcap = { 0 };
3290static ConsoleBuffer g_cbTermcap = { 0 };
3291
Bram Moolenaar071d4272004-06-13 20:20:40 +00003292char g_szOrigTitle[256] = { 0 };
Bram Moolenaar0f873732019-12-05 20:28:46 +01003293HWND g_hWnd = NULL; // also used in os_mswin.c
Bram Moolenaar071d4272004-06-13 20:20:40 +00003294static HICON g_hOrigIconSmall = NULL;
3295static HICON g_hOrigIcon = NULL;
3296static HICON g_hVimIcon = NULL;
3297static BOOL g_fCanChangeIcon = FALSE;
3298
Bram Moolenaar071d4272004-06-13 20:20:40 +00003299/*
3300 * GetConsoleIcon()
3301 * Description:
3302 * Attempts to retrieve the small icon and/or the big icon currently in
3303 * use by a given window.
3304 * Returns:
3305 * TRUE on success
3306 */
3307 static BOOL
3308GetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003309 HWND hWnd,
3310 HICON *phIconSmall,
3311 HICON *phIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003312{
3313 if (hWnd == NULL)
3314 return FALSE;
3315
3316 if (phIconSmall != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003317 *phIconSmall = (HICON)SendMessage(hWnd, WM_GETICON,
3318 (WPARAM)ICON_SMALL, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003319 if (phIcon != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003320 *phIcon = (HICON)SendMessage(hWnd, WM_GETICON,
3321 (WPARAM)ICON_BIG, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003322 return TRUE;
3323}
3324
3325/*
3326 * SetConsoleIcon()
3327 * Description:
3328 * Attempts to change the small icon and/or the big icon currently in
3329 * use by a given window.
3330 * Returns:
3331 * TRUE on success
3332 */
3333 static BOOL
3334SetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003335 HWND hWnd,
3336 HICON hIconSmall,
3337 HICON hIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003338{
Bram Moolenaar071d4272004-06-13 20:20:40 +00003339 if (hWnd == NULL)
3340 return FALSE;
3341
3342 if (hIconSmall != NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003343 SendMessage(hWnd, WM_SETICON,
3344 (WPARAM)ICON_SMALL, (LPARAM)hIconSmall);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003345 if (hIcon != NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003346 SendMessage(hWnd, WM_SETICON,
3347 (WPARAM)ICON_BIG, (LPARAM) hIcon);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003348 return TRUE;
3349}
3350
3351/*
3352 * SaveConsoleTitleAndIcon()
3353 * Description:
3354 * Saves the current console window title in g_szOrigTitle, for later
3355 * restoration. Also, attempts to obtain a handle to the console window,
3356 * and use it to save the small and big icons currently in use by the
3357 * console window. This is not always possible on some versions of Windows;
3358 * nor is it possible when running Vim remotely using Telnet (since the
3359 * console window the user sees is owned by a remote process).
3360 */
3361 static void
3362SaveConsoleTitleAndIcon(void)
3363{
Bram Moolenaar0f873732019-12-05 20:28:46 +01003364 // Save the original title.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003365 if (!GetConsoleTitle(g_szOrigTitle, sizeof(g_szOrigTitle)))
3366 return;
3367
3368 /*
3369 * Obtain a handle to the console window using GetConsoleWindow() from
3370 * KERNEL32.DLL; we need to handle in order to change the window icon.
3371 * This function only exists on NT-based Windows, starting with Windows
3372 * 2000. On older operating systems, we can't change the window icon
3373 * anyway.
3374 */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003375 g_hWnd = GetConsoleWindow();
Bram Moolenaar071d4272004-06-13 20:20:40 +00003376 if (g_hWnd == NULL)
3377 return;
3378
Bram Moolenaar0f873732019-12-05 20:28:46 +01003379 // Save the original console window icon.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003380 GetConsoleIcon(g_hWnd, &g_hOrigIconSmall, &g_hOrigIcon);
3381 if (g_hOrigIconSmall == NULL || g_hOrigIcon == NULL)
3382 return;
3383
Bram Moolenaar0f873732019-12-05 20:28:46 +01003384 // Extract the first icon contained in the Vim executable.
K.Takata2da11a42022-09-10 13:03:12 +01003385 if (
3386# ifdef FEAT_LIBCALL
3387 mch_icon_load((HANDLE *)&g_hVimIcon) == FAIL ||
3388# endif
3389 g_hVimIcon == NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003390 g_hVimIcon = ExtractIcon(NULL, (LPCSTR)exe_name, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003391 if (g_hVimIcon != NULL)
3392 g_fCanChangeIcon = TRUE;
3393}
Bram Moolenaar071d4272004-06-13 20:20:40 +00003394
3395static int g_fWindInitCalled = FALSE;
3396static int g_fTermcapMode = FALSE;
3397static CONSOLE_CURSOR_INFO g_cci;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003398
3399/*
3400 * non-GUI version of mch_init().
3401 */
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003402 static void
3403mch_init_c(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003404{
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003405# ifndef FEAT_RESTORE_ORIG_SCREEN
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003406 CONSOLE_SCREEN_BUFFER_INFO csbi;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003407# endif
3408# ifndef __MINGW32__
Bram Moolenaar071d4272004-06-13 20:20:40 +00003409 extern int _fmode;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003410# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003411
Bram Moolenaar0f873732019-12-05 20:28:46 +01003412 // Silently handle invalid parameters to CRT functions
Bram Moolenaard32a99a2010-09-21 17:29:23 +02003413 SET_INVALID_PARAM_HANDLER;
3414
Bram Moolenaar0f873732019-12-05 20:28:46 +01003415 // Let critical errors result in a failure, not in a dialog box. Required
3416 // for the timestamp test to work on removed floppies.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003417 SetErrorMode(SEM_FAILCRITICALERRORS);
3418
Bram Moolenaar0f873732019-12-05 20:28:46 +01003419 _fmode = O_BINARY; // we do our own CR-LF translation
Bram Moolenaar071d4272004-06-13 20:20:40 +00003420 out_flush();
3421
Bram Moolenaar0f873732019-12-05 20:28:46 +01003422 // Obtain handles for the standard Console I/O devices
Bram Moolenaar071d4272004-06-13 20:20:40 +00003423 if (read_cmd_fd == 0)
3424 g_hConIn = GetStdHandle(STD_INPUT_HANDLE);
3425 else
3426 create_conin();
3427 g_hConOut = GetStdHandle(STD_OUTPUT_HANDLE);
3428
Christopher Plewright38804d62022-11-09 23:55:52 +00003429 wt_init();
3430 vtp_flag_init();
3431 vtp_init();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003432# ifdef FEAT_RESTORE_ORIG_SCREEN
Bram Moolenaar0f873732019-12-05 20:28:46 +01003433 // Save the initial console buffer for later restoration
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003434 SaveConsoleBuffer(&g_cbOrig);
3435 g_attrCurrent = g_attrDefault = g_cbOrig.Info.wAttributes;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003436# else
Bram Moolenaar0f873732019-12-05 20:28:46 +01003437 // Get current text attributes
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003438 GetConsoleScreenBufferInfo(g_hConOut, &csbi);
3439 g_attrCurrent = g_attrDefault = csbi.wAttributes;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003440# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003441 if (cterm_normal_fg_color == 0)
3442 cterm_normal_fg_color = (g_attrCurrent & 0xf) + 1;
3443 if (cterm_normal_bg_color == 0)
3444 cterm_normal_bg_color = ((g_attrCurrent >> 4) & 0xf) + 1;
3445
Bram Moolenaarbdace832019-03-02 10:13:42 +01003446 // Fg and Bg color index number at startup
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02003447 g_color_index_fg = g_attrDefault & 0xf;
3448 g_color_index_bg = (g_attrDefault >> 4) & 0xf;
3449
Bram Moolenaar0f873732019-12-05 20:28:46 +01003450 // set termcap codes to current text attributes
Bram Moolenaar071d4272004-06-13 20:20:40 +00003451 update_tcap(g_attrCurrent);
3452
3453 GetConsoleCursorInfo(g_hConOut, &g_cci);
3454 GetConsoleMode(g_hConIn, &g_cmodein);
3455 GetConsoleMode(g_hConOut, &g_cmodeout);
3456
Bram Moolenaar071d4272004-06-13 20:20:40 +00003457 SaveConsoleTitleAndIcon();
3458 /*
3459 * Set both the small and big icons of the console window to Vim's icon.
3460 * Note that Vim presently only has one size of icon (32x32), but it
3461 * automatically gets scaled down to 16x16 when setting the small icon.
3462 */
3463 if (g_fCanChangeIcon)
3464 SetConsoleIcon(g_hWnd, g_hVimIcon, g_hVimIcon);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003465
3466 ui_get_shellsize();
3467
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003468# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00003469 fdDump = fopen("dump", "wt");
3470
3471 if (fdDump)
3472 {
3473 time_t t;
3474
3475 time(&t);
3476 fputs(ctime(&t), fdDump);
3477 fflush(fdDump);
3478 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003479# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003480
3481 g_fWindInitCalled = TRUE;
3482
Bram Moolenaar071d4272004-06-13 20:20:40 +00003483 g_fMouseAvail = GetSystemMetrics(SM_MOUSEPRESENT);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003484
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003485# ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01003486 win_clip_init();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003487# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003488}
3489
3490/*
3491 * non-GUI version of mch_exit().
3492 * Shut down and exit with status `r'
3493 * Careful: mch_exit() may be called before mch_init()!
3494 */
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003495 static void
3496mch_exit_c(int r)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003497{
Bram Moolenaar955f1982017-02-05 15:10:51 +01003498 exiting = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003499
Bram Moolenaarcafafb32018-02-22 21:07:09 +01003500 vtp_exit();
3501
Bram Moolenaar955f1982017-02-05 15:10:51 +01003502 stoptermcap();
Bram Moolenaar071d4272004-06-13 20:20:40 +00003503 if (g_fWindInitCalled)
3504 settmode(TMODE_COOK);
3505
Bram Moolenaar0f873732019-12-05 20:28:46 +01003506 ml_close_all(TRUE); // remove all memfiles
Bram Moolenaar071d4272004-06-13 20:20:40 +00003507
3508 if (g_fWindInitCalled)
3509 {
Bram Moolenaar40385db2018-08-07 22:31:44 +02003510 mch_restore_title(SAVE_RESTORE_BOTH);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003511 /*
3512 * Restore both the small and big icons of the console window to
3513 * what they were at startup. Don't do this when the window is
3514 * closed, Vim would hang here.
3515 */
3516 if (g_fCanChangeIcon && !g_fForceExit)
3517 SetConsoleIcon(g_hWnd, g_hOrigIconSmall, g_hOrigIcon);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003518
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003519# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00003520 if (fdDump)
3521 {
3522 time_t t;
3523
3524 time(&t);
3525 fputs(ctime(&t), fdDump);
3526 fclose(fdDump);
3527 }
3528 fdDump = NULL;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003529# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003530 }
3531
3532 SetConsoleCursorInfo(g_hConOut, &g_cci);
Wez Furlong6ef5ab52021-05-30 19:29:41 +02003533 SetConsoleMode(g_hConIn, g_cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003534 SetConsoleMode(g_hConOut, g_cmodeout);
3535
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003536# ifdef DYNAMIC_GETTEXT
Bram Moolenaar071d4272004-06-13 20:20:40 +00003537 dyn_libintl_end();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003538# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003539
3540 exit(r);
3541}
Bram Moolenaar0f873732019-12-05 20:28:46 +01003542#endif // !FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00003543
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003544 void
3545mch_init(void)
3546{
3547#ifdef VIMDLL
3548 if (gui.starting)
3549 mch_init_g();
3550 else
3551 mch_init_c();
3552#elif defined(FEAT_GUI_MSWIN)
3553 mch_init_g();
3554#else
3555 mch_init_c();
3556#endif
3557}
3558
3559 void
3560mch_exit(int r)
3561{
Bram Moolenaar173d8412020-04-19 14:02:26 +02003562#ifdef FEAT_NETBEANS_INTG
3563 netbeans_send_disconnect();
3564#endif
3565
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003566#ifdef VIMDLL
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02003567 if (gui.in_use || gui.starting)
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003568 mch_exit_g(r);
3569 else
3570 mch_exit_c(r);
3571#elif defined(FEAT_GUI_MSWIN)
3572 mch_exit_g(r);
3573#else
3574 mch_exit_c(r);
3575#endif
3576}
3577
Bram Moolenaar071d4272004-06-13 20:20:40 +00003578/*
3579 * Do we have an interactive window?
3580 */
3581 int
3582mch_check_win(
Bram Moolenaar1266d672017-02-01 13:43:36 +01003583 int argc UNUSED,
3584 char **argv UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003585{
3586 get_exe_name();
3587
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003588#if defined(FEAT_GUI_MSWIN) && !defined(VIMDLL)
Bram Moolenaar0f873732019-12-05 20:28:46 +01003589 return OK; // GUI always has a tty
Bram Moolenaar071d4272004-06-13 20:20:40 +00003590#else
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003591# ifdef VIMDLL
3592 if (gui.in_use)
3593 return OK;
3594# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003595 if (isatty(1))
3596 return OK;
3597 return FAIL;
3598#endif
3599}
3600
Bram Moolenaar65f04f62013-08-30 17:29:16 +02003601/*
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003602 * Set the case of the file name, if it already exists.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003603 * When "len" is > 0, also expand short to long filenames.
3604 */
3605 void
3606fname_case(
3607 char_u *name,
3608 int len)
3609{
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003610 int flen;
3611 WCHAR *p;
3612 WCHAR buf[_MAX_PATH + 1];
Bram Moolenaar071d4272004-06-13 20:20:40 +00003613
Bram Moolenaara3ffd9c2005-07-21 21:03:15 +00003614 flen = (int)STRLEN(name);
Bram Moolenaar65f04f62013-08-30 17:29:16 +02003615 if (flen == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003616 return;
3617
3618 slash_adjust(name);
3619
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003620 p = enc_to_utf16(name, NULL);
3621 if (p == NULL)
Bram Moolenaar65f04f62013-08-30 17:29:16 +02003622 return;
3623
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003624 if (GetLongPathNameW(p, buf, _MAX_PATH))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003625 {
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003626 char_u *q = utf16_to_enc(buf, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003627
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003628 if (q != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003629 {
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003630 if (len > 0 || flen >= (int)STRLEN(q))
3631 vim_strncpy(name, q, (len > 0) ? len - 1 : flen);
3632 vim_free(q);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003633 }
3634 }
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003635 vim_free(p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003636}
3637
3638
3639/*
3640 * Insert user name in s[len].
3641 */
3642 int
3643mch_get_user_name(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003644 char_u *s,
3645 int len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003646{
Bram Moolenaar0f873732019-12-05 20:28:46 +01003647 WCHAR wszUserName[256 + 1]; // UNLEN is 256
K.Takataeeec2542021-06-02 13:28:16 +02003648 DWORD wcch = ARRAY_LENGTH(wszUserName);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003649
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003650 if (GetUserNameW(wszUserName, &wcch))
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003651 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003652 char_u *p = utf16_to_enc(wszUserName, NULL);
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003653
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003654 if (p != NULL)
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003655 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003656 vim_strncpy(s, p, len - 1);
3657 vim_free(p);
3658 return OK;
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003659 }
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003660 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003661 s[0] = NUL;
3662 return FAIL;
3663}
3664
3665
3666/*
3667 * Insert host name in s[len].
3668 */
3669 void
3670mch_get_host_name(
3671 char_u *s,
3672 int len)
3673{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003674 WCHAR wszHostName[256 + 1];
K.Takataeeec2542021-06-02 13:28:16 +02003675 DWORD wcch = ARRAY_LENGTH(wszHostName);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003676
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003677 if (GetComputerNameW(wszHostName, &wcch))
Bram Moolenaar2cc87382013-12-11 18:21:45 +01003678 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003679 char_u *p = utf16_to_enc(wszHostName, NULL);
Bram Moolenaar2cc87382013-12-11 18:21:45 +01003680
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003681 if (p != NULL)
Bram Moolenaar2cc87382013-12-11 18:21:45 +01003682 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003683 vim_strncpy(s, p, len - 1);
3684 vim_free(p);
3685 return;
Bram Moolenaar2cc87382013-12-11 18:21:45 +01003686 }
Bram Moolenaar2cc87382013-12-11 18:21:45 +01003687 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003688}
3689
3690
3691/*
3692 * return process ID
3693 */
3694 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003695mch_get_pid(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003696{
3697 return (long)GetCurrentProcessId();
3698}
3699
Bram Moolenaar67cf86b2019-04-28 22:25:38 +02003700/*
3701 * return TRUE if process "pid" is still running
3702 */
3703 int
Bram Moolenaar1b243ea2019-04-28 22:50:40 +02003704mch_process_running(long pid)
Bram Moolenaar67cf86b2019-04-28 22:25:38 +02003705{
3706 HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION, 0, (DWORD)pid);
3707 DWORD status = 0;
3708 int ret = FALSE;
3709
3710 if (hProcess == NULL)
3711 return FALSE; // might not have access
3712 if (GetExitCodeProcess(hProcess, &status) )
3713 ret = status == STILL_ACTIVE;
3714 CloseHandle(hProcess);
3715 return ret;
3716}
Bram Moolenaar071d4272004-06-13 20:20:40 +00003717
3718/*
3719 * Get name of current directory into buffer 'buf' of length 'len' bytes.
3720 * Return OK for success, FAIL for failure.
3721 */
3722 int
3723mch_dirname(
3724 char_u *buf,
3725 int len)
3726{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003727 WCHAR wbuf[_MAX_PATH + 1];
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02003728
Bram Moolenaar071d4272004-06-13 20:20:40 +00003729 /*
3730 * Originally this was:
3731 * return (getcwd(buf, len) != NULL ? OK : FAIL);
3732 * But the Win32s known bug list says that getcwd() doesn't work
3733 * so use the Win32 system call instead. <Negri>
3734 */
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003735 if (GetCurrentDirectoryW(_MAX_PATH, wbuf) != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003736 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003737 WCHAR wcbuf[_MAX_PATH + 1];
3738 char_u *p = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003739
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003740 if (GetLongPathNameW(wbuf, wcbuf, _MAX_PATH) != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003741 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003742 p = utf16_to_enc(wcbuf, NULL);
3743 if (STRLEN(p) >= (size_t)len)
Bram Moolenaarcea1f9e2018-08-19 14:38:42 +02003744 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003745 // long path name is too long, fall back to short one
Bram Moolenaar071d4272004-06-13 20:20:40 +00003746 vim_free(p);
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003747 p = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003748 }
3749 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003750 if (p == NULL)
3751 p = utf16_to_enc(wbuf, NULL);
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02003752
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003753 if (p != NULL)
3754 {
3755 vim_strncpy(buf, p, len - 1);
3756 vim_free(p);
3757 return OK;
3758 }
3759 }
3760 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003761}
3762
3763/*
Bram Moolenaarffa22202013-11-21 12:34:11 +01003764 * Get file permissions for "name".
3765 * Return mode_t or -1 for error.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003766 */
3767 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003768mch_getperm(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003769{
Bram Moolenaar8767f522016-07-01 17:17:39 +02003770 stat_T st;
Bram Moolenaarffa22202013-11-21 12:34:11 +01003771 int n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003772
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003773 n = mch_stat((char *)name, &st);
Bram Moolenaar78cf3f02014-01-10 18:16:07 +01003774 return n == 0 ? (long)(unsigned short)st.st_mode : -1L;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003775}
3776
3777
3778/*
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003779 * Set file permission for "name" to "perm".
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003780 *
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003781 * Return FAIL for failure, OK otherwise.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003782 */
3783 int
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003784mch_setperm(char_u *name, long perm)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003785{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003786 long n;
3787 WCHAR *p;
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003788
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003789 p = enc_to_utf16(name, NULL);
3790 if (p == NULL)
3791 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003792
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003793 n = _wchmod(p, perm);
3794 vim_free(p);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003795 if (n == -1)
3796 return FAIL;
3797
3798 win32_set_archive(name);
3799
3800 return OK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003801}
3802
3803/*
3804 * Set hidden flag for "name".
3805 */
3806 void
3807mch_hide(char_u *name)
3808{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003809 int attrs = win32_getattrs(name);
3810 if (attrs == -1)
3811 return;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003812
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003813 attrs |= FILE_ATTRIBUTE_HIDDEN;
3814 win32_setattrs(name, attrs);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003815}
3816
3817/*
Bram Moolenaar8a52ba72015-11-02 14:45:56 +01003818 * Return TRUE if file "name" exists and is hidden.
3819 */
3820 int
3821mch_ishidden(char_u *name)
3822{
3823 int f = win32_getattrs(name);
3824
3825 if (f == -1)
Bram Moolenaar0f873732019-12-05 20:28:46 +01003826 return FALSE; // file does not exist at all
Bram Moolenaar8a52ba72015-11-02 14:45:56 +01003827
3828 return (f & FILE_ATTRIBUTE_HIDDEN) != 0;
3829}
3830
3831/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003832 * return TRUE if "name" is a directory
3833 * return FALSE if "name" is not a directory or upon error
3834 */
3835 int
3836mch_isdir(char_u *name)
3837{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003838 int f = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003839
3840 if (f == -1)
Bram Moolenaar0f873732019-12-05 20:28:46 +01003841 return FALSE; // file does not exist at all
Bram Moolenaar071d4272004-06-13 20:20:40 +00003842
3843 return (f & FILE_ATTRIBUTE_DIRECTORY) != 0;
3844}
3845
3846/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01003847 * return TRUE if "name" is a directory, NOT a symlink to a directory
3848 * return FALSE if "name" is not a directory
3849 * return FALSE for error
3850 */
3851 int
3852mch_isrealdir(char_u *name)
3853{
3854 return mch_isdir(name) && !mch_is_symbolic_link(name);
3855}
3856
3857/*
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003858 * Create directory "name".
3859 * Return 0 on success, -1 on error.
3860 */
3861 int
3862mch_mkdir(char_u *name)
3863{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003864 WCHAR *p;
3865 int retval;
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003866
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003867 p = enc_to_utf16(name, NULL);
3868 if (p == NULL)
3869 return -1;
3870 retval = _wmkdir(p);
3871 vim_free(p);
3872 return retval;
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003873}
3874
3875/*
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003876 * Delete directory "name".
3877 * Return 0 on success, -1 on error.
3878 */
3879 int
3880mch_rmdir(char_u *name)
3881{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003882 WCHAR *p;
3883 int retval;
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003884
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003885 p = enc_to_utf16(name, NULL);
3886 if (p == NULL)
3887 return -1;
3888 retval = _wrmdir(p);
3889 vim_free(p);
3890 return retval;
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003891}
3892
3893/*
Bram Moolenaar03f48552006-02-28 23:52:23 +00003894 * Return TRUE if file "fname" has more than one link.
3895 */
3896 int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003897mch_is_hard_link(char_u *fname)
Bram Moolenaar03f48552006-02-28 23:52:23 +00003898{
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003899 BY_HANDLE_FILE_INFORMATION info;
3900
3901 return win32_fileinfo(fname, &info) == FILEINFO_OK
3902 && info.nNumberOfLinks > 1;
3903}
3904
3905/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01003906 * Return TRUE if "name" is a symbolic link (or a junction).
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003907 */
3908 int
Bram Moolenaar203258c2016-01-17 22:15:16 +01003909mch_is_symbolic_link(char_u *name)
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003910{
3911 HANDLE hFind;
3912 int res = FALSE;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003913 DWORD fileFlags = 0, reparseTag = 0;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003914 WCHAR *wn;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003915 WIN32_FIND_DATAW findDataW;
3916
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003917 wn = enc_to_utf16(name, NULL);
3918 if (wn == NULL)
3919 return FALSE;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003920
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003921 hFind = FindFirstFileW(wn, &findDataW);
3922 vim_free(wn);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003923 if (hFind != INVALID_HANDLE_VALUE)
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003924 {
3925 fileFlags = findDataW.dwFileAttributes;
3926 reparseTag = findDataW.dwReserved0;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003927 FindClose(hFind);
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003928 }
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003929
3930 if ((fileFlags & FILE_ATTRIBUTE_REPARSE_POINT)
Bram Moolenaar203258c2016-01-17 22:15:16 +01003931 && (reparseTag == IO_REPARSE_TAG_SYMLINK
3932 || reparseTag == IO_REPARSE_TAG_MOUNT_POINT))
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003933 res = TRUE;
3934
3935 return res;
3936}
3937
3938/*
3939 * Return TRUE if file "fname" has more than one link or if it is a symbolic
3940 * link.
3941 */
3942 int
3943mch_is_linked(char_u *fname)
3944{
3945 if (mch_is_hard_link(fname) || mch_is_symbolic_link(fname))
3946 return TRUE;
3947 return FALSE;
3948}
3949
3950/*
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003951 * Get the by-handle-file-information for "fname".
3952 * Returns FILEINFO_OK when OK.
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003953 * Returns FILEINFO_ENC_FAIL when enc_to_utf16() failed.
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003954 * Returns FILEINFO_READ_FAIL when CreateFile() failed.
3955 * Returns FILEINFO_INFO_FAIL when GetFileInformationByHandle() failed.
3956 */
3957 int
3958win32_fileinfo(char_u *fname, BY_HANDLE_FILE_INFORMATION *info)
3959{
Bram Moolenaar03f48552006-02-28 23:52:23 +00003960 HANDLE hFile;
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003961 int res = FILEINFO_READ_FAIL;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003962 WCHAR *wn;
Bram Moolenaar03f48552006-02-28 23:52:23 +00003963
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003964 wn = enc_to_utf16(fname, NULL);
3965 if (wn == NULL)
3966 return FILEINFO_ENC_FAIL;
3967
3968 hFile = CreateFileW(wn, // file name
3969 GENERIC_READ, // access mode
3970 FILE_SHARE_READ | FILE_SHARE_WRITE, // share mode
3971 NULL, // security descriptor
3972 OPEN_EXISTING, // creation disposition
3973 FILE_FLAG_BACKUP_SEMANTICS, // file attributes
3974 NULL); // handle to template file
3975 vim_free(wn);
Bram Moolenaar03f48552006-02-28 23:52:23 +00003976
3977 if (hFile != INVALID_HANDLE_VALUE)
3978 {
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003979 if (GetFileInformationByHandle(hFile, info) != 0)
3980 res = FILEINFO_OK;
3981 else
3982 res = FILEINFO_INFO_FAIL;
Bram Moolenaar03f48552006-02-28 23:52:23 +00003983 CloseHandle(hFile);
3984 }
3985
Bram Moolenaar03f48552006-02-28 23:52:23 +00003986 return res;
3987}
3988
3989/*
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003990 * get file attributes for `name'
3991 * -1 : error
3992 * else FILE_ATTRIBUTE_* defined in winnt.h
3993 */
Bram Moolenaarffa22202013-11-21 12:34:11 +01003994 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003995win32_getattrs(char_u *name)
3996{
3997 int attr;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003998 WCHAR *p;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003999
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004000 p = enc_to_utf16(name, NULL);
4001 if (p == NULL)
4002 return INVALID_FILE_ATTRIBUTES;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004003
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004004 attr = GetFileAttributesW(p);
4005 vim_free(p);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004006
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004007 return attr;
4008}
4009
4010/*
4011 * set file attributes for `name' to `attrs'
4012 *
4013 * return -1 for failure, 0 otherwise
4014 */
Bram Moolenaar6dff58f2018-09-30 21:43:26 +02004015 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004016win32_setattrs(char_u *name, int attrs)
4017{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004018 int res;
4019 WCHAR *p;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004020
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004021 p = enc_to_utf16(name, NULL);
4022 if (p == NULL)
4023 return -1;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004024
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004025 res = SetFileAttributesW(p, attrs);
4026 vim_free(p);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004027
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004028 return res ? 0 : -1;
4029}
4030
4031/*
4032 * Set archive flag for "name".
4033 */
Bram Moolenaar6dff58f2018-09-30 21:43:26 +02004034 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004035win32_set_archive(char_u *name)
4036{
4037 int attrs = win32_getattrs(name);
4038 if (attrs == -1)
4039 return -1;
4040
4041 attrs |= FILE_ATTRIBUTE_ARCHIVE;
4042 return win32_setattrs(name, attrs);
4043}
4044
4045/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00004046 * Return TRUE if file or directory "name" is writable (not readonly).
4047 * Strange semantics of Win32: a readonly directory is writable, but you can't
4048 * delete a file. Let's say this means it is writable.
4049 */
4050 int
4051mch_writable(char_u *name)
4052{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004053 int attrs = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004054
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004055 return (attrs != -1 && (!(attrs & FILE_ATTRIBUTE_READONLY)
4056 || (attrs & FILE_ATTRIBUTE_DIRECTORY)));
Bram Moolenaar071d4272004-06-13 20:20:40 +00004057}
4058
Bram Moolenaar071d4272004-06-13 20:20:40 +00004059/*
Bram Moolenaar43663192017-03-05 14:29:12 +01004060 * Return TRUE if "name" can be executed, FALSE if not.
Bram Moolenaar77b77102015-03-21 22:18:41 +01004061 * If "use_path" is FALSE only check if "name" is executable.
Bram Moolenaar43663192017-03-05 14:29:12 +01004062 * When returning TRUE and "path" is not NULL save the path and set "*path" to
4063 * the allocated memory.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004064 */
4065 int
Yegappan Lakshmananebb01bd2022-06-08 15:14:09 +01004066mch_can_exe(char_u *name, char_u **path, int use_path UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004067{
Bram Moolenaar95da1362020-05-30 18:37:55 +02004068 return executable_exists((char *)name, path, TRUE, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004069}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004070
4071/*
4072 * Check what "name" is:
4073 * NODE_NORMAL: file or directory (or doesn't exist)
4074 * NODE_WRITABLE: writable device, socket, fifo, etc.
4075 * NODE_OTHER: non-writable things
4076 */
4077 int
4078mch_nodetype(char_u *name)
4079{
4080 HANDLE hFile;
4081 int type;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004082 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004083
Bram Moolenaar0f873732019-12-05 20:28:46 +01004084 // We can't open a file with a name "\\.\con" or "\\.\prn" and trying to
4085 // read from it later will cause Vim to hang. Thus return NODE_WRITABLE
4086 // here.
Bram Moolenaar043545e2006-10-10 16:44:07 +00004087 if (STRNCMP(name, "\\\\.\\", 4) == 0)
4088 return NODE_WRITABLE;
4089
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004090 wn = enc_to_utf16(name, NULL);
4091 if (wn == NULL)
4092 return NODE_NORMAL;
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004093
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004094 hFile = CreateFileW(wn, // file name
4095 GENERIC_WRITE, // access mode
4096 0, // share mode
4097 NULL, // security descriptor
4098 OPEN_EXISTING, // creation disposition
4099 0, // file attributes
4100 NULL); // handle to template file
4101 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004102 if (hFile == INVALID_HANDLE_VALUE)
4103 return NODE_NORMAL;
4104
4105 type = GetFileType(hFile);
4106 CloseHandle(hFile);
4107 if (type == FILE_TYPE_CHAR)
4108 return NODE_WRITABLE;
4109 if (type == FILE_TYPE_DISK)
4110 return NODE_NORMAL;
4111 return NODE_OTHER;
4112}
4113
4114#ifdef HAVE_ACL
4115struct my_acl
4116{
4117 PSECURITY_DESCRIPTOR pSecurityDescriptor;
4118 PSID pSidOwner;
4119 PSID pSidGroup;
4120 PACL pDacl;
4121 PACL pSacl;
4122};
4123#endif
4124
4125/*
4126 * Return a pointer to the ACL of file "fname" in allocated memory.
4127 * Return NULL if the ACL is not available for whatever reason.
4128 */
4129 vim_acl_T
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004130mch_get_acl(char_u *fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004131{
4132#ifndef HAVE_ACL
4133 return (vim_acl_T)NULL;
4134#else
4135 struct my_acl *p = NULL;
Bram Moolenaar27515922013-06-29 15:36:26 +02004136 DWORD err;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004137
Bram Moolenaarc799fe22019-05-28 23:08:19 +02004138 p = ALLOC_CLEAR_ONE(struct my_acl);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004139 if (p != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004140 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004141 WCHAR *wn;
Bram Moolenaar27515922013-06-29 15:36:26 +02004142
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004143 wn = enc_to_utf16(fname, NULL);
4144 if (wn == NULL)
Bram Moolenaarbbf9f342020-11-10 22:03:40 +01004145 {
4146 vim_free(p);
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004147 return NULL;
Bram Moolenaarbbf9f342020-11-10 22:03:40 +01004148 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004149
4150 // Try to retrieve the entire security descriptor.
4151 err = GetNamedSecurityInfoW(
4152 wn, // Abstract filename
4153 SE_FILE_OBJECT, // File Object
4154 OWNER_SECURITY_INFORMATION |
4155 GROUP_SECURITY_INFORMATION |
4156 DACL_SECURITY_INFORMATION |
4157 SACL_SECURITY_INFORMATION,
4158 &p->pSidOwner, // Ownership information.
4159 &p->pSidGroup, // Group membership.
4160 &p->pDacl, // Discretionary information.
4161 &p->pSacl, // For auditing purposes.
4162 &p->pSecurityDescriptor);
4163 if (err == ERROR_ACCESS_DENIED ||
4164 err == ERROR_PRIVILEGE_NOT_HELD)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004165 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004166 // Retrieve only DACL.
4167 (void)GetNamedSecurityInfoW(
4168 wn,
4169 SE_FILE_OBJECT,
4170 DACL_SECURITY_INFORMATION,
4171 NULL,
4172 NULL,
4173 &p->pDacl,
4174 NULL,
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004175 &p->pSecurityDescriptor);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004176 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004177 if (p->pSecurityDescriptor == NULL)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004178 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004179 mch_free_acl((vim_acl_T)p);
4180 p = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004181 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004182 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004183 }
4184
4185 return (vim_acl_T)p;
4186#endif
4187}
4188
Bram Moolenaar27515922013-06-29 15:36:26 +02004189#ifdef HAVE_ACL
4190/*
4191 * Check if "acl" contains inherited ACE.
4192 */
4193 static BOOL
4194is_acl_inherited(PACL acl)
4195{
4196 DWORD i;
4197 ACL_SIZE_INFORMATION acl_info;
4198 PACCESS_ALLOWED_ACE ace;
4199
4200 acl_info.AceCount = 0;
4201 GetAclInformation(acl, &acl_info, sizeof(acl_info), AclSizeInformation);
4202 for (i = 0; i < acl_info.AceCount; i++)
4203 {
4204 GetAce(acl, i, (LPVOID *)&ace);
4205 if (ace->Header.AceFlags & INHERITED_ACE)
4206 return TRUE;
4207 }
4208 return FALSE;
4209}
4210#endif
4211
Bram Moolenaar071d4272004-06-13 20:20:40 +00004212/*
4213 * Set the ACL of file "fname" to "acl" (unless it's NULL).
4214 * Errors are ignored.
4215 * This must only be called with "acl" equal to what mch_get_acl() returned.
4216 */
4217 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004218mch_set_acl(char_u *fname, vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004219{
4220#ifdef HAVE_ACL
4221 struct my_acl *p = (struct my_acl *)acl;
Bram Moolenaar27515922013-06-29 15:36:26 +02004222 SECURITY_INFORMATION sec_info = 0;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004223 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004224
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004225 if (p == NULL)
4226 return;
4227
4228 wn = enc_to_utf16(fname, NULL);
4229 if (wn == NULL)
4230 return;
4231
4232 // Set security flags
4233 if (p->pSidOwner)
4234 sec_info |= OWNER_SECURITY_INFORMATION;
4235 if (p->pSidGroup)
4236 sec_info |= GROUP_SECURITY_INFORMATION;
4237 if (p->pDacl)
Bram Moolenaar27515922013-06-29 15:36:26 +02004238 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004239 sec_info |= DACL_SECURITY_INFORMATION;
4240 // Do not inherit its parent's DACL.
4241 // If the DACL is inherited, Cygwin permissions would be changed.
4242 if (!is_acl_inherited(p->pDacl))
4243 sec_info |= PROTECTED_DACL_SECURITY_INFORMATION;
Bram Moolenaar27515922013-06-29 15:36:26 +02004244 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004245 if (p->pSacl)
4246 sec_info |= SACL_SECURITY_INFORMATION;
4247
4248 (void)SetNamedSecurityInfoW(
4249 wn, // Abstract filename
4250 SE_FILE_OBJECT, // File Object
4251 sec_info,
4252 p->pSidOwner, // Ownership information.
4253 p->pSidGroup, // Group membership.
4254 p->pDacl, // Discretionary information.
4255 p->pSacl // For auditing purposes.
4256 );
4257 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004258#endif
4259}
4260
4261 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004262mch_free_acl(vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004263{
4264#ifdef HAVE_ACL
4265 struct my_acl *p = (struct my_acl *)acl;
4266
4267 if (p != NULL)
4268 {
4269 LocalFree(p->pSecurityDescriptor); // Free the memory just in case
4270 vim_free(p);
4271 }
4272#endif
4273}
4274
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004275#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004276
4277/*
4278 * handler for ctrl-break, ctrl-c interrupts, and fatal events.
4279 */
4280 static BOOL WINAPI
4281handler_routine(
4282 DWORD dwCtrlType)
4283{
Bram Moolenaar589b1102017-08-12 16:39:05 +02004284 INPUT_RECORD ir;
4285 DWORD out;
4286
Bram Moolenaar071d4272004-06-13 20:20:40 +00004287 switch (dwCtrlType)
4288 {
4289 case CTRL_C_EVENT:
4290 if (ctrl_c_interrupts)
4291 g_fCtrlCPressed = TRUE;
4292 return TRUE;
4293
4294 case CTRL_BREAK_EVENT:
4295 g_fCBrkPressed = TRUE;
Bram Moolenaar589b1102017-08-12 16:39:05 +02004296 ctrl_break_was_pressed = TRUE;
Bram Moolenaar0f873732019-12-05 20:28:46 +01004297 // ReadConsoleInput is blocking, send a key event to continue.
Bram Moolenaar589b1102017-08-12 16:39:05 +02004298 ir.EventType = KEY_EVENT;
4299 ir.Event.KeyEvent.bKeyDown = TRUE;
4300 ir.Event.KeyEvent.wRepeatCount = 1;
4301 ir.Event.KeyEvent.wVirtualKeyCode = VK_CANCEL;
4302 ir.Event.KeyEvent.wVirtualScanCode = 0;
4303 ir.Event.KeyEvent.dwControlKeyState = 0;
4304 ir.Event.KeyEvent.uChar.UnicodeChar = 0;
4305 WriteConsoleInput(g_hConIn, &ir, 1, &out);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004306 return TRUE;
4307
Bram Moolenaar0f873732019-12-05 20:28:46 +01004308 // fatal events: shut down gracefully
Bram Moolenaar071d4272004-06-13 20:20:40 +00004309 case CTRL_CLOSE_EVENT:
4310 case CTRL_LOGOFF_EVENT:
4311 case CTRL_SHUTDOWN_EVENT:
4312 windgoto((int)Rows - 1, 0);
4313 g_fForceExit = TRUE;
4314
Bram Moolenaar0fde2902008-03-16 13:54:13 +00004315 vim_snprintf((char *)IObuff, IOSIZE, _("Vim: Caught %s event\n"),
Bram Moolenaar071d4272004-06-13 20:20:40 +00004316 (dwCtrlType == CTRL_CLOSE_EVENT
4317 ? _("close")
4318 : dwCtrlType == CTRL_LOGOFF_EVENT
4319 ? _("logoff")
4320 : _("shutdown")));
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004321# ifdef DEBUG
Bram Moolenaar071d4272004-06-13 20:20:40 +00004322 OutputDebugString(IObuff);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004323# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004324
Bram Moolenaar0f873732019-12-05 20:28:46 +01004325 preserve_exit(); // output IObuff, preserve files and exit
Bram Moolenaar071d4272004-06-13 20:20:40 +00004326
Bram Moolenaar0f873732019-12-05 20:28:46 +01004327 return TRUE; // not reached
Bram Moolenaar071d4272004-06-13 20:20:40 +00004328
4329 default:
4330 return FALSE;
4331 }
4332}
4333
4334
4335/*
4336 * set the tty in (raw) ? "raw" : "cooked" mode
4337 */
4338 void
Bram Moolenaar26e86442020-05-17 14:06:16 +02004339mch_settmode(tmode_T tmode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004340{
4341 DWORD cmodein;
4342 DWORD cmodeout;
4343 BOOL bEnableHandler;
4344
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004345# ifdef VIMDLL
4346 if (gui.in_use)
4347 return;
4348# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004349 GetConsoleMode(g_hConIn, &cmodein);
4350 GetConsoleMode(g_hConOut, &cmodeout);
4351 if (tmode == TMODE_RAW)
4352 {
4353 cmodein &= ~(ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
4354 ENABLE_ECHO_INPUT);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004355 if (g_fMouseActive)
Wez Furlong6ef5ab52021-05-30 19:29:41 +02004356 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00004357 cmodein |= ENABLE_MOUSE_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02004358 cmodein &= ~ENABLE_QUICK_EDIT_MODE;
4359 }
4360 else
4361 {
4362 cmodein |= g_cmodein & ENABLE_QUICK_EDIT_MODE;
4363 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01004364 cmodeout &= ~(
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004365# ifdef FEAT_TERMGUICOLORS
Bram Moolenaar0f873732019-12-05 20:28:46 +01004366 // Do not turn off the ENABLE_PROCESSED_OUTPUT flag when using
4367 // VTP.
Bram Moolenaarcafafb32018-02-22 21:07:09 +01004368 ((vtp_working) ? 0 : ENABLE_PROCESSED_OUTPUT) |
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004369# else
Bram Moolenaarcafafb32018-02-22 21:07:09 +01004370 ENABLE_PROCESSED_OUTPUT |
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004371# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01004372 ENABLE_WRAP_AT_EOL_OUTPUT);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004373 bEnableHandler = TRUE;
4374 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01004375 else // cooked
Bram Moolenaar071d4272004-06-13 20:20:40 +00004376 {
4377 cmodein |= (ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
4378 ENABLE_ECHO_INPUT);
4379 cmodeout |= (ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
4380 bEnableHandler = FALSE;
4381 }
Wez Furlong6ef5ab52021-05-30 19:29:41 +02004382 SetConsoleMode(g_hConIn, cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004383 SetConsoleMode(g_hConOut, cmodeout);
4384 SetConsoleCtrlHandler(handler_routine, bEnableHandler);
4385
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004386# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00004387 if (fdDump)
4388 {
4389 fprintf(fdDump, "mch_settmode(%s, in = %x, out = %x)\n",
4390 tmode == TMODE_RAW ? "raw" :
4391 tmode == TMODE_COOK ? "cooked" : "normal",
4392 cmodein, cmodeout);
4393 fflush(fdDump);
4394 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004395# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004396}
4397
4398
4399/*
4400 * Get the size of the current window in `Rows' and `Columns'
4401 * Return OK when size could be determined, FAIL otherwise.
4402 */
4403 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004404mch_get_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004405{
4406 CONSOLE_SCREEN_BUFFER_INFO csbi;
4407
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004408# ifdef VIMDLL
4409 if (gui.in_use)
4410 return OK;
4411# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004412 if (!g_fTermcapMode && g_cbTermcap.IsValid)
4413 {
4414 /*
4415 * For some reason, we are trying to get the screen dimensions
4416 * even though we are not in termcap mode. The 'Rows' and 'Columns'
4417 * variables are really intended to mean the size of Vim screen
4418 * while in termcap mode.
4419 */
4420 Rows = g_cbTermcap.Info.dwSize.Y;
4421 Columns = g_cbTermcap.Info.dwSize.X;
4422 }
4423 else if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
4424 {
4425 Rows = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
4426 Columns = csbi.srWindow.Right - csbi.srWindow.Left + 1;
4427 }
4428 else
4429 {
4430 Rows = 25;
4431 Columns = 80;
4432 }
4433 return OK;
4434}
4435
4436/*
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004437 * Resize console buffer to 'COORD'
4438 */
4439 static void
4440ResizeConBuf(
4441 HANDLE hConsole,
4442 COORD coordScreen)
4443{
4444 if (!SetConsoleScreenBufferSize(hConsole, coordScreen))
4445 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004446# ifdef MCH_WRITE_DUMP
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004447 if (fdDump)
4448 {
4449 fprintf(fdDump, "SetConsoleScreenBufferSize failed: %lx\n",
4450 GetLastError());
4451 fflush(fdDump);
4452 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004453# endif
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004454 }
4455}
4456
4457/*
4458 * Resize console window size to 'srWindowRect'
4459 */
4460 static void
4461ResizeWindow(
4462 HANDLE hConsole,
4463 SMALL_RECT srWindowRect)
4464{
4465 if (!SetConsoleWindowInfo(hConsole, TRUE, &srWindowRect))
4466 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004467# ifdef MCH_WRITE_DUMP
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004468 if (fdDump)
4469 {
4470 fprintf(fdDump, "SetConsoleWindowInfo failed: %lx\n",
4471 GetLastError());
4472 fflush(fdDump);
4473 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004474# endif
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004475 }
4476}
4477
4478/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00004479 * Set a console window to `xSize' * `ySize'
4480 */
4481 static void
4482ResizeConBufAndWindow(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004483 HANDLE hConsole,
4484 int xSize,
4485 int ySize)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004486{
Bram Moolenaar0f873732019-12-05 20:28:46 +01004487 CONSOLE_SCREEN_BUFFER_INFO csbi; // hold current console buffer info
4488 SMALL_RECT srWindowRect; // hold the new console size
Bram Moolenaar071d4272004-06-13 20:20:40 +00004489 COORD coordScreen;
Bram Moolenaarf49a6922019-07-15 20:37:05 +02004490 COORD cursor;
Bram Moolenaar2551c032018-08-23 22:38:31 +02004491 static int resized = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004492
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004493# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00004494 if (fdDump)
4495 {
4496 fprintf(fdDump, "ResizeConBufAndWindow(%d, %d)\n", xSize, ySize);
4497 fflush(fdDump);
4498 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004499# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004500
Bram Moolenaar0f873732019-12-05 20:28:46 +01004501 // get the largest size we can size the console window to
Bram Moolenaar071d4272004-06-13 20:20:40 +00004502 coordScreen = GetLargestConsoleWindowSize(hConsole);
4503
Bram Moolenaar0f873732019-12-05 20:28:46 +01004504 // define the new console window size and scroll position
Bram Moolenaar071d4272004-06-13 20:20:40 +00004505 srWindowRect.Left = srWindowRect.Top = (SHORT) 0;
4506 srWindowRect.Right = (SHORT) (min(xSize, coordScreen.X) - 1);
4507 srWindowRect.Bottom = (SHORT) (min(ySize, coordScreen.Y) - 1);
4508
4509 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
4510 {
4511 int sx, sy;
4512
4513 sx = csbi.srWindow.Right - csbi.srWindow.Left + 1;
4514 sy = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
4515 if (sy < ySize || sx < xSize)
4516 {
4517 /*
4518 * Increasing number of lines/columns, do buffer first.
4519 * Use the maximal size in x and y direction.
4520 */
4521 if (sy < ySize)
4522 coordScreen.Y = ySize;
4523 else
4524 coordScreen.Y = sy;
4525 if (sx < xSize)
4526 coordScreen.X = xSize;
4527 else
4528 coordScreen.X = sx;
4529 SetConsoleScreenBufferSize(hConsole, coordScreen);
4530 }
4531 }
4532
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004533 // define the new console buffer size
Bram Moolenaar071d4272004-06-13 20:20:40 +00004534 coordScreen.X = xSize;
4535 coordScreen.Y = ySize;
4536
Bram Moolenaar2551c032018-08-23 22:38:31 +02004537 // In the new console call API, only the first time in reverse order
4538 if (!vtp_working || resized)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004539 {
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004540 ResizeWindow(hConsole, srWindowRect);
4541 ResizeConBuf(hConsole, coordScreen);
4542 }
4543 else
4544 {
Bram Moolenaarf49a6922019-07-15 20:37:05 +02004545 // Workaround for a Windows 10 bug
4546 cursor.X = srWindowRect.Left;
4547 cursor.Y = srWindowRect.Top;
4548 SetConsoleCursorPosition(hConsole, cursor);
4549
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004550 ResizeConBuf(hConsole, coordScreen);
4551 ResizeWindow(hConsole, srWindowRect);
Bram Moolenaar2551c032018-08-23 22:38:31 +02004552 resized = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004553 }
4554}
4555
4556
4557/*
4558 * Set the console window to `Rows' * `Columns'
4559 */
4560 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004561mch_set_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004562{
4563 COORD coordScreen;
4564
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004565# ifdef VIMDLL
4566 if (gui.in_use)
4567 return;
4568# endif
Bram Moolenaar0f873732019-12-05 20:28:46 +01004569 // Don't change window size while still starting up
Bram Moolenaar071d4272004-06-13 20:20:40 +00004570 if (suppress_winsize != 0)
4571 {
4572 suppress_winsize = 2;
4573 return;
4574 }
4575
4576 if (term_console)
4577 {
4578 coordScreen = GetLargestConsoleWindowSize(g_hConOut);
4579
Bram Moolenaar0f873732019-12-05 20:28:46 +01004580 // Clamp Rows and Columns to reasonable values
Bram Moolenaar071d4272004-06-13 20:20:40 +00004581 if (Rows > coordScreen.Y)
4582 Rows = coordScreen.Y;
4583 if (Columns > coordScreen.X)
4584 Columns = coordScreen.X;
4585
4586 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
4587 }
4588}
4589
4590/*
4591 * Rows and/or Columns has changed.
4592 */
4593 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004594mch_new_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004595{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004596# ifdef VIMDLL
4597 if (gui.in_use)
4598 return;
4599# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004600 set_scroll_region(0, 0, Columns - 1, Rows - 1);
4601}
4602
4603
4604/*
4605 * Called when started up, to set the winsize that was delayed.
4606 */
4607 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004608mch_set_winsize_now(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004609{
4610 if (suppress_winsize == 2)
4611 {
4612 suppress_winsize = 0;
4613 mch_set_shellsize();
4614 shell_resized();
4615 }
4616 suppress_winsize = 0;
4617}
Bram Moolenaar0f873732019-12-05 20:28:46 +01004618#endif // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00004619
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004620 static BOOL
4621vim_create_process(
Bram Moolenaar36c85b22013-12-12 20:25:44 +01004622 char *cmd,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004623 BOOL inherit_handles,
Bram Moolenaar3f1138e2014-01-05 13:29:26 +01004624 DWORD flags,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004625 STARTUPINFO *si,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004626 PROCESS_INFORMATION *pi,
4627 LPVOID *env,
4628 char *cwd)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004629{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004630 BOOL ret = FALSE;
4631 WCHAR *wcmd, *wcwd = NULL;
4632
4633 wcmd = enc_to_utf16((char_u *)cmd, NULL);
4634 if (wcmd == NULL)
4635 return FALSE;
4636 if (cwd != NULL)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004637 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004638 wcwd = enc_to_utf16((char_u *)cwd, NULL);
4639 if (wcwd == NULL)
4640 goto theend;
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004641 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004642
4643 ret = CreateProcessW(
4644 NULL, // Executable name
4645 wcmd, // Command to execute
4646 NULL, // Process security attributes
4647 NULL, // Thread security attributes
4648 inherit_handles, // Inherit handles
4649 flags, // Creation flags
4650 env, // Environment
4651 wcwd, // Current directory
4652 (LPSTARTUPINFOW)si, // Startup information
4653 pi); // Process information
4654theend:
4655 vim_free(wcmd);
4656 vim_free(wcwd);
4657 return ret;
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004658}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004659
4660
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004661 static HINSTANCE
4662vim_shell_execute(
4663 char *cmd,
4664 INT n_show_cmd)
4665{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004666 HINSTANCE ret;
4667 WCHAR *wcmd;
4668
4669 wcmd = enc_to_utf16((char_u *)cmd, NULL);
4670 if (wcmd == NULL)
4671 return (HINSTANCE) 0;
4672
4673 ret = ShellExecuteW(NULL, NULL, wcmd, NULL, NULL, n_show_cmd);
4674 vim_free(wcmd);
4675 return ret;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004676}
4677
4678
Bram Moolenaar4f974752019-02-17 17:44:42 +01004679#if defined(FEAT_GUI_MSWIN) || defined(PROTO)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004680
4681/*
4682 * Specialised version of system() for Win32 GUI mode.
4683 * This version proceeds as follows:
4684 * 1. Create a console window for use by the subprocess
4685 * 2. Run the subprocess (it gets the allocated console by default)
4686 * 3. Wait for the subprocess to terminate and get its exit code
4687 * 4. Prompt the user to press a key to close the console window
4688 */
4689 static int
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004690mch_system_classic(char *cmd, int options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004691{
4692 STARTUPINFO si;
4693 PROCESS_INFORMATION pi;
4694 DWORD ret = 0;
4695 HWND hwnd = GetFocus();
4696
4697 si.cb = sizeof(si);
4698 si.lpReserved = NULL;
4699 si.lpDesktop = NULL;
4700 si.lpTitle = NULL;
4701 si.dwFlags = STARTF_USESHOWWINDOW;
4702 /*
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004703 * It's nicer to run a filter command in a minimized window.
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01004704 * Don't activate the window to keep focus on Vim.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004705 */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004706 if (options & SHELL_DOOUT)
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01004707 si.wShowWindow = SW_SHOWMINNOACTIVE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004708 else
4709 si.wShowWindow = SW_SHOWNORMAL;
4710 si.cbReserved2 = 0;
4711 si.lpReserved2 = NULL;
4712
Bram Moolenaar0f873732019-12-05 20:28:46 +01004713 // Now, run the command
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004714 vim_create_process(cmd, FALSE,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004715 CREATE_DEFAULT_ERROR_MODE | CREATE_NEW_CONSOLE,
4716 &si, &pi, NULL, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004717
Bram Moolenaar0f873732019-12-05 20:28:46 +01004718 // Wait for the command to terminate before continuing
Bram Moolenaar071d4272004-06-13 20:20:40 +00004719 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004720# ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00004721 int delay = 1;
4722
Bram Moolenaar0f873732019-12-05 20:28:46 +01004723 // Keep updating the window while waiting for the shell to finish.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004724 for (;;)
4725 {
4726 MSG msg;
4727
K.Takatab7057bd2022-01-21 11:37:07 +00004728 if (PeekMessageW(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004729 {
4730 TranslateMessage(&msg);
K.Takatab7057bd2022-01-21 11:37:07 +00004731 DispatchMessageW(&msg);
Bram Moolenaare4195c52012-08-02 12:31:44 +02004732 delay = 1;
4733 continue;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004734 }
4735 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
4736 break;
4737
Bram Moolenaar0f873732019-12-05 20:28:46 +01004738 // We start waiting for a very short time and then increase it, so
4739 // that we respond quickly when the process is quick, and don't
4740 // consume too much overhead when it's slow.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004741 if (delay < 50)
4742 delay += 10;
4743 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004744# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004745 WaitForSingleObject(pi.hProcess, INFINITE);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004746# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004747
Bram Moolenaar0f873732019-12-05 20:28:46 +01004748 // Get the command exit code
Bram Moolenaar071d4272004-06-13 20:20:40 +00004749 GetExitCodeProcess(pi.hProcess, &ret);
4750 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004751
Bram Moolenaar0f873732019-12-05 20:28:46 +01004752 // Close the handles to the subprocess, so that it goes away
Bram Moolenaar071d4272004-06-13 20:20:40 +00004753 CloseHandle(pi.hThread);
4754 CloseHandle(pi.hProcess);
4755
Bram Moolenaar0f873732019-12-05 20:28:46 +01004756 // Try to get input focus back. Doesn't always work though.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004757 PostMessage(hwnd, WM_SETFOCUS, 0, 0);
4758
4759 return ret;
4760}
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004761
4762/*
4763 * Thread launched by the gui to send the current buffer data to the
4764 * process. This way avoid to hang up vim totally if the children
4765 * process take a long time to process the lines.
4766 */
Bram Moolenaar4c38d662016-08-03 20:54:57 +02004767 static unsigned int __stdcall
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004768sub_process_writer(LPVOID param)
4769{
4770 HANDLE g_hChildStd_IN_Wr = param;
4771 linenr_T lnum = curbuf->b_op_start.lnum;
4772 DWORD len = 0;
4773 DWORD l;
4774 char_u *lp = ml_get(lnum);
4775 char_u *s;
4776 int written = 0;
4777
4778 for (;;)
4779 {
4780 l = (DWORD)STRLEN(lp + written);
4781 if (l == 0)
4782 len = 0;
4783 else if (lp[written] == NL)
4784 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004785 // NL -> NUL translation
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004786 WriteFile(g_hChildStd_IN_Wr, "", 1, &len, NULL);
4787 }
4788 else
4789 {
4790 s = vim_strchr(lp + written, NL);
4791 WriteFile(g_hChildStd_IN_Wr, (char *)lp + written,
4792 s == NULL ? l : (DWORD)(s - (lp + written)),
4793 &len, NULL);
4794 }
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +01004795 if (len == l)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004796 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004797 // Finished a line, add a NL, unless this line should not have
4798 // one.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004799 if (lnum != curbuf->b_op_end.lnum
Bram Moolenaar34d72d42015-07-17 14:18:08 +02004800 || (!curbuf->b_p_bin
4801 && curbuf->b_p_fixeol)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004802 || (lnum != curbuf->b_no_eol_lnum
4803 && (lnum != curbuf->b_ml.ml_line_count
4804 || curbuf->b_p_eol)))
4805 {
Bram Moolenaar42335f52018-09-13 15:33:43 +02004806 WriteFile(g_hChildStd_IN_Wr, "\n", 1,
4807 (LPDWORD)&vim_ignored, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004808 }
4809
4810 ++lnum;
4811 if (lnum > curbuf->b_op_end.lnum)
4812 break;
4813
4814 lp = ml_get(lnum);
4815 written = 0;
4816 }
4817 else if (len > 0)
4818 written += len;
4819 }
4820
Bram Moolenaar0f873732019-12-05 20:28:46 +01004821 // finished all the lines, close pipe
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004822 CloseHandle(g_hChildStd_IN_Wr);
Bram Moolenaar86f2cd52016-08-02 21:55:17 +02004823 return 0;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004824}
4825
4826
Bram Moolenaar0f873732019-12-05 20:28:46 +01004827# define BUFLEN 100 // length for buffer, stolen from unix version
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004828
4829/*
4830 * This function read from the children's stdout and write the
4831 * data on screen or in the buffer accordingly.
4832 */
4833 static void
4834dump_pipe(int options,
4835 HANDLE g_hChildStd_OUT_Rd,
4836 garray_T *ga,
4837 char_u buffer[],
4838 DWORD *buffer_off)
4839{
4840 DWORD availableBytes = 0;
4841 DWORD i;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004842 int ret;
4843 DWORD len;
4844 DWORD toRead;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004845
Bram Moolenaar0f873732019-12-05 20:28:46 +01004846 // we query the pipe to see if there is any data to read
4847 // to avoid to perform a blocking read
4848 ret = PeekNamedPipe(g_hChildStd_OUT_Rd, // pipe to query
4849 NULL, // optional buffer
4850 0, // buffer size
4851 NULL, // number of read bytes
4852 &availableBytes, // available bytes total
4853 NULL); // byteLeft
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004854
Bram Moolenaar0f873732019-12-05 20:28:46 +01004855 // We got real data in the pipe, read it
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02004856 while (ret != 0 && availableBytes > 0)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004857 {
Bram Moolenaara12a1612019-01-24 16:39:02 +01004858 toRead = (DWORD)(BUFLEN - *buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004859 toRead = availableBytes < toRead ? availableBytes : toRead;
Bram Moolenaara12a1612019-01-24 16:39:02 +01004860 ReadFile(g_hChildStd_OUT_Rd, buffer + *buffer_off, toRead , &len, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004861
Bram Moolenaar0f873732019-12-05 20:28:46 +01004862 // If we haven't read anything, there is a problem
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004863 if (len == 0)
4864 break;
4865
4866 availableBytes -= len;
4867
4868 if (options & SHELL_READ)
4869 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004870 // Do NUL -> NL translation, append NL separated
4871 // lines to the current buffer.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004872 for (i = 0; i < len; ++i)
4873 {
4874 if (buffer[i] == NL)
4875 append_ga_line(ga);
4876 else if (buffer[i] == NUL)
4877 ga_append(ga, NL);
4878 else
4879 ga_append(ga, buffer[i]);
4880 }
4881 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004882 else if (has_mbyte)
4883 {
4884 int l;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004885 int c;
4886 char_u *p;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004887
4888 len += *buffer_off;
4889 buffer[len] = NUL;
4890
Bram Moolenaar0f873732019-12-05 20:28:46 +01004891 // Check if the last character in buffer[] is
4892 // incomplete, keep these bytes for the next
4893 // round.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004894 for (p = buffer; p < buffer + len; p += l)
4895 {
Bram Moolenaard3c907b2016-08-17 21:32:09 +02004896 l = MB_CPTR2LEN(p);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004897 if (l == 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01004898 l = 1; // NUL byte?
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004899 else if (MB_BYTE2LEN(*p) != l)
4900 break;
4901 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01004902 if (p == buffer) // no complete character
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004903 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004904 // avoid getting stuck at an illegal byte
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004905 if (len >= 12)
4906 ++p;
4907 else
4908 {
4909 *buffer_off = len;
4910 return;
4911 }
4912 }
4913 c = *p;
4914 *p = NUL;
Bram Moolenaar32526b32019-01-19 17:43:09 +01004915 msg_puts((char *)buffer);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004916 if (p < buffer + len)
4917 {
4918 *p = c;
4919 *buffer_off = (DWORD)((buffer + len) - p);
4920 mch_memmove(buffer, p, *buffer_off);
4921 return;
4922 }
4923 *buffer_off = 0;
4924 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004925 else
4926 {
4927 buffer[len] = NUL;
Bram Moolenaar32526b32019-01-19 17:43:09 +01004928 msg_puts((char *)buffer);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004929 }
4930
4931 windgoto(msg_row, msg_col);
4932 cursor_on();
4933 out_flush();
4934 }
4935}
4936
4937/*
4938 * Version of system to use for windows NT > 5.0 (Win2K), use pipe
4939 * for communication and doesn't open any new window.
4940 */
4941 static int
4942mch_system_piped(char *cmd, int options)
4943{
4944 STARTUPINFO si;
4945 PROCESS_INFORMATION pi;
4946 DWORD ret = 0;
4947
4948 HANDLE g_hChildStd_IN_Rd = NULL;
4949 HANDLE g_hChildStd_IN_Wr = NULL;
4950 HANDLE g_hChildStd_OUT_Rd = NULL;
4951 HANDLE g_hChildStd_OUT_Wr = NULL;
4952
Bram Moolenaar0f873732019-12-05 20:28:46 +01004953 char_u buffer[BUFLEN + 1]; // reading buffer + size
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004954 DWORD len;
4955
Bram Moolenaar0f873732019-12-05 20:28:46 +01004956 // buffer used to receive keys
4957 char_u ta_buf[BUFLEN + 1]; // TypeAHead
4958 int ta_len = 0; // valid bytes in ta_buf[]
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004959
4960 DWORD i;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004961 int noread_cnt = 0;
4962 garray_T ga;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004963 int delay = 1;
Bram Moolenaar0f873732019-12-05 20:28:46 +01004964 DWORD buffer_off = 0; // valid bytes in buffer[]
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004965 char *p = NULL;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004966
4967 SECURITY_ATTRIBUTES saAttr;
4968
Bram Moolenaar0f873732019-12-05 20:28:46 +01004969 // Set the bInheritHandle flag so pipe handles are inherited.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004970 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
4971 saAttr.bInheritHandle = TRUE;
4972 saAttr.lpSecurityDescriptor = NULL;
4973
4974 if ( ! CreatePipe(&g_hChildStd_OUT_Rd, &g_hChildStd_OUT_Wr, &saAttr, 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01004975 // Ensure the read handle to the pipe for STDOUT is not inherited.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004976 || ! SetHandleInformation(g_hChildStd_OUT_Rd, HANDLE_FLAG_INHERIT, 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01004977 // Create a pipe for the child process's STDIN.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004978 || ! CreatePipe(&g_hChildStd_IN_Rd, &g_hChildStd_IN_Wr, &saAttr, 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01004979 // Ensure the write handle to the pipe for STDIN is not inherited.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004980 || ! SetHandleInformation(g_hChildStd_IN_Wr, HANDLE_FLAG_INHERIT, 0) )
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004981 {
4982 CloseHandle(g_hChildStd_IN_Rd);
4983 CloseHandle(g_hChildStd_IN_Wr);
4984 CloseHandle(g_hChildStd_OUT_Rd);
4985 CloseHandle(g_hChildStd_OUT_Wr);
Bram Moolenaar32526b32019-01-19 17:43:09 +01004986 msg_puts(_("\nCannot create pipes\n"));
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004987 }
4988
4989 si.cb = sizeof(si);
4990 si.lpReserved = NULL;
4991 si.lpDesktop = NULL;
4992 si.lpTitle = NULL;
4993 si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
4994
Bram Moolenaar0f873732019-12-05 20:28:46 +01004995 // set-up our file redirection
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004996 si.hStdError = g_hChildStd_OUT_Wr;
4997 si.hStdOutput = g_hChildStd_OUT_Wr;
4998 si.hStdInput = g_hChildStd_IN_Rd;
4999 si.wShowWindow = SW_HIDE;
5000 si.cbReserved2 = 0;
5001 si.lpReserved2 = NULL;
5002
5003 if (options & SHELL_READ)
5004 ga_init2(&ga, 1, BUFLEN);
5005
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005006 if (cmd != NULL)
5007 {
5008 p = (char *)vim_strsave((char_u *)cmd);
5009 if (p != NULL)
5010 unescape_shellxquote((char_u *)p, p_sxe);
5011 else
5012 p = cmd;
5013 }
5014
Bram Moolenaar0f873732019-12-05 20:28:46 +01005015 // Now, run the command.
5016 // About "Inherit handles" being TRUE: this command can be litigious,
5017 // handle inheritance was deactivated for pending temp file, but, if we
5018 // deactivate it, the pipes don't work for some reason.
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005019 vim_create_process(p, TRUE, CREATE_DEFAULT_ERROR_MODE,
5020 &si, &pi, NULL, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005021
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005022 if (p != cmd)
5023 vim_free(p);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005024
Bram Moolenaar0f873732019-12-05 20:28:46 +01005025 // Close our unused side of the pipes
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005026 CloseHandle(g_hChildStd_IN_Rd);
5027 CloseHandle(g_hChildStd_OUT_Wr);
5028
5029 if (options & SHELL_WRITE)
5030 {
Bram Moolenaar86f2cd52016-08-02 21:55:17 +02005031 HANDLE thread = (HANDLE)
Bram Moolenaar0f873732019-12-05 20:28:46 +01005032 _beginthreadex(NULL, // security attributes
5033 0, // default stack size
5034 sub_process_writer, // function to be executed
5035 g_hChildStd_IN_Wr, // parameter
5036 0, // creation flag, start immediately
5037 NULL); // we don't care about thread id
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005038 CloseHandle(thread);
5039 g_hChildStd_IN_Wr = NULL;
5040 }
5041
Bram Moolenaar0f873732019-12-05 20:28:46 +01005042 // Keep updating the window while waiting for the shell to finish.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005043 for (;;)
5044 {
5045 MSG msg;
5046
K.Takatab7057bd2022-01-21 11:37:07 +00005047 if (PeekMessageW(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005048 {
5049 TranslateMessage(&msg);
K.Takatab7057bd2022-01-21 11:37:07 +00005050 DispatchMessageW(&msg);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005051 }
5052
Bram Moolenaar0f873732019-12-05 20:28:46 +01005053 // write pipe information in the window
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005054 if ((options & (SHELL_READ|SHELL_WRITE))
5055# ifdef FEAT_GUI
5056 || gui.in_use
5057# endif
5058 )
5059 {
5060 len = 0;
5061 if (!(options & SHELL_EXPAND)
5062 && ((options &
5063 (SHELL_READ|SHELL_WRITE|SHELL_COOKED))
5064 != (SHELL_READ|SHELL_WRITE|SHELL_COOKED)
5065# ifdef FEAT_GUI
5066 || gui.in_use
5067# endif
5068 )
5069 && (ta_len > 0 || noread_cnt > 4))
5070 {
5071 if (ta_len == 0)
5072 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005073 // Get extra characters when we don't have any. Reset the
5074 // counter and timer.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005075 noread_cnt = 0;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005076 len = ui_inchar(ta_buf, BUFLEN, 10L, 0);
5077 }
5078 if (ta_len > 0 || len > 0)
5079 {
5080 /*
5081 * For pipes: Check for CTRL-C: send interrupt signal to
5082 * child. Check for CTRL-D: EOF, close pipe to child.
5083 */
5084 if (len == 1 && cmd != NULL)
5085 {
5086 if (ta_buf[ta_len] == Ctrl_C)
5087 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005088 // Learn what exit code is expected, for
5089 // now put 9 as SIGKILL
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005090 TerminateProcess(pi.hProcess, 9);
5091 }
5092 if (ta_buf[ta_len] == Ctrl_D)
5093 {
5094 CloseHandle(g_hChildStd_IN_Wr);
5095 g_hChildStd_IN_Wr = NULL;
5096 }
5097 }
5098
Bram Moolenaar2f7e1b82022-10-04 13:17:31 +01005099 len = term_replace_keycodes(ta_buf, ta_len, len);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005100
5101 /*
5102 * For pipes: echo the typed characters. For a pty this
5103 * does not seem to work.
5104 */
5105 for (i = ta_len; i < ta_len + len; ++i)
5106 {
5107 if (ta_buf[i] == '\n' || ta_buf[i] == '\b')
5108 msg_putchar(ta_buf[i]);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005109 else if (has_mbyte)
5110 {
5111 int l = (*mb_ptr2len)(ta_buf + i);
5112
5113 msg_outtrans_len(ta_buf + i, l);
5114 i += l - 1;
5115 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005116 else
5117 msg_outtrans_len(ta_buf + i, 1);
5118 }
5119 windgoto(msg_row, msg_col);
5120 out_flush();
5121
5122 ta_len += len;
5123
5124 /*
5125 * Write the characters to the child, unless EOF has been
5126 * typed for pipes. Write one character at a time, to
5127 * avoid losing too much typeahead. When writing buffer
5128 * lines, drop the typed characters (only check for
5129 * CTRL-C).
5130 */
5131 if (options & SHELL_WRITE)
5132 ta_len = 0;
5133 else if (g_hChildStd_IN_Wr != NULL)
5134 {
5135 WriteFile(g_hChildStd_IN_Wr, (char*)ta_buf,
5136 1, &len, NULL);
5137 // if we are typing in, we want to keep things reactive
5138 delay = 1;
5139 if (len > 0)
5140 {
5141 ta_len -= len;
5142 mch_memmove(ta_buf, ta_buf + len, ta_len);
5143 }
5144 }
5145 }
5146 }
5147 }
5148
5149 if (ta_len)
5150 ui_inchar_undo(ta_buf, ta_len);
5151
5152 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
5153 {
Bram Moolenaar2eba1822011-08-27 15:10:04 +02005154 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005155 break;
5156 }
5157
5158 ++noread_cnt;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02005159 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005160
Bram Moolenaar0f873732019-12-05 20:28:46 +01005161 // We start waiting for a very short time and then increase it, so
5162 // that we respond quickly when the process is quick, and don't
5163 // consume too much overhead when it's slow.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005164 if (delay < 50)
5165 delay += 10;
5166 }
5167
Bram Moolenaar0f873732019-12-05 20:28:46 +01005168 // Close the pipe
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005169 CloseHandle(g_hChildStd_OUT_Rd);
5170 if (g_hChildStd_IN_Wr != NULL)
5171 CloseHandle(g_hChildStd_IN_Wr);
5172
5173 WaitForSingleObject(pi.hProcess, INFINITE);
5174
Bram Moolenaar0f873732019-12-05 20:28:46 +01005175 // Get the command exit code
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005176 GetExitCodeProcess(pi.hProcess, &ret);
5177
5178 if (options & SHELL_READ)
5179 {
5180 if (ga.ga_len > 0)
5181 {
5182 append_ga_line(&ga);
Bram Moolenaar0f873732019-12-05 20:28:46 +01005183 // remember that the NL was missing
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005184 curbuf->b_no_eol_lnum = curwin->w_cursor.lnum;
5185 }
5186 else
5187 curbuf->b_no_eol_lnum = 0;
5188 ga_clear(&ga);
5189 }
5190
Bram Moolenaar0f873732019-12-05 20:28:46 +01005191 // Close the handles to the subprocess, so that it goes away
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005192 CloseHandle(pi.hThread);
5193 CloseHandle(pi.hProcess);
5194
5195 return ret;
5196}
5197
5198 static int
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005199mch_system_g(char *cmd, int options)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005200{
Bram Moolenaar0f873732019-12-05 20:28:46 +01005201 // if we can pipe and the shelltemp option is off
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005202 if (!p_stmp)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005203 return mch_system_piped(cmd, options);
5204 else
5205 return mch_system_classic(cmd, options);
5206}
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005207#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005208
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005209#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01005210 static int
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02005211mch_system_c(char *cmd, int options UNUSED)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01005212{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005213 int ret;
5214 WCHAR *wcmd;
Bram Moolenaar2efc44b2019-10-05 12:09:32 +02005215 char_u *buf;
5216 size_t len;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005217
Bram Moolenaar2efc44b2019-10-05 12:09:32 +02005218 // If the command starts and ends with double quotes, enclose the command
5219 // in parentheses.
5220 len = STRLEN(cmd);
5221 if (len >= 2 && cmd[0] == '"' && cmd[len - 1] == '"')
5222 {
5223 len += 3;
5224 buf = alloc(len);
5225 if (buf == NULL)
5226 return -1;
5227 vim_snprintf((char *)buf, len, "(%s)", cmd);
5228 wcmd = enc_to_utf16(buf, NULL);
5229 free(buf);
5230 }
5231 else
5232 wcmd = enc_to_utf16((char_u *)cmd, NULL);
5233
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005234 if (wcmd == NULL)
5235 return -1;
5236
5237 ret = _wsystem(wcmd);
5238 vim_free(wcmd);
5239 return ret;
Bram Moolenaar910cffb2013-12-11 17:58:35 +01005240}
Bram Moolenaar071d4272004-06-13 20:20:40 +00005241
5242#endif
5243
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005244 static int
5245mch_system(char *cmd, int options)
5246{
5247#ifdef VIMDLL
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02005248 if (gui.in_use || gui.starting)
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005249 return mch_system_g(cmd, options);
5250 else
5251 return mch_system_c(cmd, options);
5252#elif defined(FEAT_GUI_MSWIN)
5253 return mch_system_g(cmd, options);
5254#else
5255 return mch_system_c(cmd, options);
5256#endif
5257}
5258
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005259#if defined(FEAT_GUI) && defined(FEAT_TERMINAL)
5260/*
5261 * Use a terminal window to run a shell command in.
5262 */
5263 static int
5264mch_call_shell_terminal(
5265 char_u *cmd,
Bram Moolenaar0f873732019-12-05 20:28:46 +01005266 int options UNUSED) // SHELL_*, see vim.h
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005267{
5268 jobopt_T opt;
5269 char_u *newcmd = NULL;
5270 typval_T argvar[2];
5271 long_u cmdlen;
5272 int retval = -1;
5273 buf_T *buf;
Bram Moolenaarf9c38832018-06-19 19:59:20 +02005274 job_T *job;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005275 aco_save_T aco;
Bram Moolenaar0f873732019-12-05 20:28:46 +01005276 oparg_T oa; // operator arguments
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005277
Bram Moolenaar42f652f2018-03-19 21:44:37 +01005278 if (cmd == NULL)
5279 cmdlen = STRLEN(p_sh) + 1;
5280 else
5281 cmdlen = STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10;
Bram Moolenaar18a4ba22019-05-24 19:39:03 +02005282 newcmd = alloc(cmdlen);
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005283 if (newcmd == NULL)
5284 return 255;
Bram Moolenaar42f652f2018-03-19 21:44:37 +01005285 if (cmd == NULL)
5286 {
5287 STRCPY(newcmd, p_sh);
5288 ch_log(NULL, "starting terminal to run a shell");
5289 }
5290 else
5291 {
5292 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s", p_sh, p_shcf, cmd);
5293 ch_log(NULL, "starting terminal for system command '%s'", cmd);
5294 }
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005295
5296 init_job_options(&opt);
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005297
5298 argvar[0].v_type = VAR_STRING;
5299 argvar[0].vval.v_string = newcmd;
5300 argvar[1].v_type = VAR_UNKNOWN;
5301 buf = term_start(argvar, NULL, &opt, TERM_START_SYSTEM);
Bram Moolenaar81c3c89a2018-03-20 11:41:44 +01005302 if (buf == NULL)
Bram Moolenaar9029b912019-03-21 19:58:00 +01005303 {
5304 vim_free(newcmd);
Bram Moolenaar81c3c89a2018-03-20 11:41:44 +01005305 return 255;
Bram Moolenaar9029b912019-03-21 19:58:00 +01005306 }
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005307
Bram Moolenaarf9c38832018-06-19 19:59:20 +02005308 job = term_getjob(buf->b_term);
5309 ++job->jv_refcount;
5310
Bram Moolenaar0f873732019-12-05 20:28:46 +01005311 // Find a window to make "buf" curbuf.
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005312 aucmd_prepbuf(&aco, buf);
Bram Moolenaare76062c2022-11-28 18:51:43 +00005313 if (curbuf == buf)
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005314 {
Bram Moolenaare76062c2022-11-28 18:51:43 +00005315 // Only do this when a window was found for "buf".
5316 clear_oparg(&oa);
5317 while (term_use_loop())
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005318 {
Bram Moolenaare76062c2022-11-28 18:51:43 +00005319 if (oa.op_type == OP_NOP && oa.regname == NUL && !VIsual_active)
5320 {
5321 // If terminal_loop() returns OK we got a key that is handled
5322 // in Normal model. We don't do redrawing anyway.
5323 if (terminal_loop(TRUE) == OK)
5324 normal_cmd(&oa, TRUE);
5325 }
5326 else
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005327 normal_cmd(&oa, TRUE);
5328 }
Bram Moolenaare76062c2022-11-28 18:51:43 +00005329 retval = job->jv_exitval;
5330 ch_log(NULL, "system command finished");
5331
5332 job_unref(job);
5333
5334 // restore curwin/curbuf and a few other things
5335 aucmd_restbuf(&aco);
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005336 }
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005337
5338 wait_return(TRUE);
5339 do_buffer(DOBUF_WIPE, DOBUF_FIRST, FORWARD, buf->b_fnum, TRUE);
5340
5341 vim_free(newcmd);
5342 return retval;
5343}
5344#endif
5345
Bram Moolenaar071d4272004-06-13 20:20:40 +00005346/*
5347 * Either execute a command by calling the shell or start a new shell
5348 */
5349 int
5350mch_call_shell(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005351 char_u *cmd,
Bram Moolenaar0f873732019-12-05 20:28:46 +01005352 int options) // SHELL_*, see vim.h
Bram Moolenaar071d4272004-06-13 20:20:40 +00005353{
5354 int x = 0;
5355 int tmode = cur_tmode;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005356 WCHAR szShellTitle[512];
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02005357
Bram Moolenaar4c5678f2022-11-30 18:12:19 +00005358#ifdef FEAT_EVAL
Bram Moolenaarc9a9a0a2022-04-12 15:09:23 +01005359 ch_log(NULL, "executing shell command: %s", cmd);
5360#endif
Bram Moolenaar0f873732019-12-05 20:28:46 +01005361 // Change the title to reflect that we are in a subshell.
K.Takataeeec2542021-06-02 13:28:16 +02005362 if (GetConsoleTitleW(szShellTitle, ARRAY_LENGTH(szShellTitle) - 4) > 0)
Bram Moolenaar1df52d72014-10-15 22:50:10 +02005363 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005364 if (cmd == NULL)
5365 wcscat(szShellTitle, L" :sh");
5366 else
Bram Moolenaar1df52d72014-10-15 22:50:10 +02005367 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005368 WCHAR *wn = enc_to_utf16((char_u *)cmd, NULL);
Bram Moolenaar1df52d72014-10-15 22:50:10 +02005369
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005370 if (wn != NULL)
5371 {
5372 wcscat(szShellTitle, L" - !");
5373 if ((wcslen(szShellTitle) + wcslen(wn) <
K.Takataeeec2542021-06-02 13:28:16 +02005374 ARRAY_LENGTH(szShellTitle)))
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005375 wcscat(szShellTitle, wn);
5376 SetConsoleTitleW(szShellTitle);
5377 vim_free(wn);
Bram Moolenaar1df52d72014-10-15 22:50:10 +02005378 }
5379 }
5380 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005381
5382 out_flush();
5383
5384#ifdef MCH_WRITE_DUMP
5385 if (fdDump)
5386 {
5387 fprintf(fdDump, "mch_call_shell(\"%s\", %d)\n", cmd, options);
5388 fflush(fdDump);
5389 }
5390#endif
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005391#if defined(FEAT_GUI) && defined(FEAT_TERMINAL)
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02005392 // TODO: make the terminal window work with input or output redirected.
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005393 if (
5394# ifdef VIMDLL
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02005395 gui.in_use &&
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005396# endif
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02005397 vim_strchr(p_go, GO_TERMINAL) != NULL
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005398 && (options & (SHELL_FILTER|SHELL_DOOUT|SHELL_WRITE|SHELL_READ)) == 0)
5399 {
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02005400 char_u *cmdbase = cmd;
5401
Bram Moolenaar4d5c1262019-09-20 17:20:02 +02005402 if (cmdbase != NULL)
5403 // Skip a leading quote and (.
5404 while (*cmdbase == '"' || *cmdbase == '(')
5405 ++cmdbase;
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02005406
5407 // Check the command does not begin with "start "
Bram Moolenaar36e7a822019-11-13 21:49:24 +01005408 if (cmdbase == NULL || STRNICMP(cmdbase, "start", 5) != 0
5409 || !VIM_ISWHITE(cmdbase[5]))
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02005410 {
5411 // Use a terminal window to run the command in.
5412 x = mch_call_shell_terminal(cmd, options);
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02005413 resettitle();
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02005414 return x;
5415 }
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005416 }
5417#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005418
5419 /*
5420 * Catch all deadly signals while running the external command, because a
5421 * CTRL-C, Ctrl-Break or illegal instruction might otherwise kill us.
5422 */
5423 signal(SIGINT, SIG_IGN);
5424#if defined(__GNUC__) && !defined(__MINGW32__)
5425 signal(SIGKILL, SIG_IGN);
5426#else
5427 signal(SIGBREAK, SIG_IGN);
5428#endif
5429 signal(SIGILL, SIG_IGN);
5430 signal(SIGFPE, SIG_IGN);
5431 signal(SIGSEGV, SIG_IGN);
5432 signal(SIGTERM, SIG_IGN);
5433 signal(SIGABRT, SIG_IGN);
5434
5435 if (options & SHELL_COOKED)
Bram Moolenaar0f873732019-12-05 20:28:46 +01005436 settmode(TMODE_COOK); // set to normal mode
Bram Moolenaar071d4272004-06-13 20:20:40 +00005437
5438 if (cmd == NULL)
5439 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01005440 x = mch_system((char *)p_sh, options);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005441 }
5442 else
5443 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005444 // we use "command" or "cmd" to start the shell; slow but easy
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005445 char_u *newcmd = NULL;
5446 char_u *cmdbase = cmd;
5447 long_u cmdlen;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005448
Bram Moolenaar0f873732019-12-05 20:28:46 +01005449 // Skip a leading ", ( and "(.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005450 if (*cmdbase == '"' )
5451 ++cmdbase;
5452 if (*cmdbase == '(')
5453 ++cmdbase;
5454
Bram Moolenaar1c465442017-03-12 20:10:05 +01005455 if ((STRNICMP(cmdbase, "start", 5) == 0) && VIM_ISWHITE(cmdbase[5]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005456 {
5457 STARTUPINFO si;
5458 PROCESS_INFORMATION pi;
5459 DWORD flags = CREATE_NEW_CONSOLE;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01005460 INT n_show_cmd = SW_SHOWNORMAL;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005461 char_u *p;
5462
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01005463 ZeroMemory(&si, sizeof(si));
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005464 si.cb = sizeof(si);
5465 si.lpReserved = NULL;
5466 si.lpDesktop = NULL;
5467 si.lpTitle = NULL;
5468 si.dwFlags = 0;
5469 si.cbReserved2 = 0;
5470 si.lpReserved2 = NULL;
5471
5472 cmdbase = skipwhite(cmdbase + 5);
5473 if ((STRNICMP(cmdbase, "/min", 4) == 0)
Bram Moolenaar1c465442017-03-12 20:10:05 +01005474 && VIM_ISWHITE(cmdbase[4]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005475 {
5476 cmdbase = skipwhite(cmdbase + 4);
5477 si.dwFlags = STARTF_USESHOWWINDOW;
5478 si.wShowWindow = SW_SHOWMINNOACTIVE;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01005479 n_show_cmd = SW_SHOWMINNOACTIVE;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005480 }
5481 else if ((STRNICMP(cmdbase, "/b", 2) == 0)
Bram Moolenaar1c465442017-03-12 20:10:05 +01005482 && VIM_ISWHITE(cmdbase[2]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005483 {
5484 cmdbase = skipwhite(cmdbase + 2);
5485 flags = CREATE_NO_WINDOW;
5486 si.dwFlags = STARTF_USESTDHANDLES;
5487 si.hStdInput = CreateFile("\\\\.\\NUL", // File name
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005488 GENERIC_READ, // Access flags
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005489 0, // Share flags
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005490 NULL, // Security att.
5491 OPEN_EXISTING, // Open flags
5492 FILE_ATTRIBUTE_NORMAL, // File att.
5493 NULL); // Temp file
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005494 si.hStdOutput = si.hStdInput;
5495 si.hStdError = si.hStdInput;
5496 }
5497
Bram Moolenaar0f873732019-12-05 20:28:46 +01005498 // Remove a trailing ", ) and )" if they have a match
5499 // at the start of the command.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005500 if (cmdbase > cmd)
5501 {
5502 p = cmdbase + STRLEN(cmdbase);
5503 if (p > cmdbase && p[-1] == '"' && *cmd == '"')
5504 *--p = NUL;
5505 if (p > cmdbase && p[-1] == ')'
5506 && (*cmd =='(' || cmd[1] == '('))
5507 *--p = NUL;
5508 }
5509
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005510 newcmd = cmdbase;
5511 unescape_shellxquote(cmdbase, p_sxe);
5512
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005513 /*
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005514 * If creating new console, arguments are passed to the
5515 * 'cmd.exe' as-is. If it's not, arguments are not treated
5516 * correctly for current 'cmd.exe'. So unescape characters in
5517 * shellxescape except '|' for avoiding to be treated as
5518 * argument to them. Pass the arguments to sub-shell.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005519 */
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005520 if (flags != CREATE_NEW_CONSOLE)
5521 {
5522 char_u *subcmd;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01005523 char_u *cmd_shell = mch_getenv("COMSPEC");
5524
5525 if (cmd_shell == NULL || *cmd_shell == NUL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01005526 cmd_shell = (char_u *)default_shell();
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005527
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01005528 subcmd = vim_strsave_escaped_ext(cmdbase,
5529 (char_u *)"|", '^', FALSE);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005530 if (subcmd != NULL)
5531 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005532 // make "cmd.exe /c arguments"
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005533 cmdlen = STRLEN(cmd_shell) + STRLEN(subcmd) + 5;
Bram Moolenaar18a4ba22019-05-24 19:39:03 +02005534 newcmd = alloc(cmdlen);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005535 if (newcmd != NULL)
5536 vim_snprintf((char *)newcmd, cmdlen, "%s /c %s",
Bram Moolenaaree7d1002012-02-22 15:34:08 +01005537 cmd_shell, subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005538 else
5539 newcmd = cmdbase;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01005540 vim_free(subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005541 }
5542 }
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005543
5544 /*
5545 * Now, start the command as a process, so that it doesn't
5546 * inherit our handles which causes unpleasant dangling swap
5547 * files if we exit before the spawned process
5548 */
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005549 if (vim_create_process((char *)newcmd, FALSE, flags,
5550 &si, &pi, NULL, NULL))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005551 x = 0;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01005552 else if (vim_shell_execute((char *)newcmd, n_show_cmd)
5553 > (HINSTANCE)32)
5554 x = 0;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005555 else
5556 {
5557 x = -1;
Bram Moolenaar4f974752019-02-17 17:44:42 +01005558#ifdef FEAT_GUI_MSWIN
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005559# ifdef VIMDLL
5560 if (gui.in_use)
5561# endif
Bram Moolenaarac78dd42022-01-02 19:25:26 +00005562 emsg(_(e_command_not_found));
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005563#endif
5564 }
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005565
5566 if (newcmd != cmdbase)
5567 vim_free(newcmd);
5568
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01005569 if (si.dwFlags == STARTF_USESTDHANDLES && si.hStdInput != NULL)
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005570 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005571 // Close the handle to \\.\NUL created above.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005572 CloseHandle(si.hStdInput);
5573 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01005574 // Close the handles to the subprocess, so that it goes away
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005575 CloseHandle(pi.hThread);
5576 CloseHandle(pi.hProcess);
5577 }
5578 else
5579 {
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005580 cmdlen =
Bram Moolenaar4f974752019-02-17 17:44:42 +01005581#ifdef FEAT_GUI_MSWIN
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02005582 ((gui.in_use || gui.starting) ?
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005583 (!s_dont_use_vimrun && p_stmp ?
5584 STRLEN(vimrun_path) : STRLEN(p_sh) + STRLEN(p_shcf))
5585 : 0) +
Bram Moolenaar071d4272004-06-13 20:20:40 +00005586#endif
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005587 STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10;
Bram Moolenaar0fde2902008-03-16 13:54:13 +00005588
Bram Moolenaar18a4ba22019-05-24 19:39:03 +02005589 newcmd = alloc(cmdlen);
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005590 if (newcmd != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005591 {
Bram Moolenaar4f974752019-02-17 17:44:42 +01005592#if defined(FEAT_GUI_MSWIN)
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005593 if (
5594# ifdef VIMDLL
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02005595 (gui.in_use || gui.starting) &&
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005596# endif
5597 need_vimrun_warning)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005598 {
Bram Moolenaar63e43442016-11-19 17:28:44 +01005599 char *msg = _("VIMRUN.EXE not found in your $PATH.\n"
5600 "External commands will not pause after completion.\n"
5601 "See :help win32-vimrun for more information.");
5602 char *title = _("Vim Warning");
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005603 WCHAR *wmsg = enc_to_utf16((char_u *)msg, NULL);
5604 WCHAR *wtitle = enc_to_utf16((char_u *)title, NULL);
Bram Moolenaar63e43442016-11-19 17:28:44 +01005605
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005606 if (wmsg != NULL && wtitle != NULL)
5607 MessageBoxW(NULL, wmsg, wtitle, MB_ICONWARNING);
5608 vim_free(wmsg);
5609 vim_free(wtitle);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005610 need_vimrun_warning = FALSE;
5611 }
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005612 if (
5613# ifdef VIMDLL
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02005614 (gui.in_use || gui.starting) &&
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005615# endif
5616 !s_dont_use_vimrun && p_stmp)
Bram Moolenaarfcc4d922019-05-24 13:32:36 +02005617 // Use vimrun to execute the command. It opens a console
5618 // window, which can be closed without killing Vim.
Bram Moolenaarcc448b32010-07-14 16:52:17 +02005619 vim_snprintf((char *)newcmd, cmdlen, "%s%s%s %s %s",
Bram Moolenaar071d4272004-06-13 20:20:40 +00005620 vimrun_path,
5621 (msg_silent != 0 || (options & SHELL_DOOUT))
5622 ? "-s " : "",
5623 p_sh, p_shcf, cmd);
Bram Moolenaarfcc4d922019-05-24 13:32:36 +02005624 else if (
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005625# ifdef VIMDLL
Bram Moolenaarfcc4d922019-05-24 13:32:36 +02005626 (gui.in_use || gui.starting) &&
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005627# endif
Bram Moolenaar0e6bfb92019-07-31 20:53:56 +02005628 s_dont_use_vimrun && STRCMP(p_shcf, "/c") == 0)
Bram Moolenaarfcc4d922019-05-24 13:32:36 +02005629 // workaround for the case that "vimrun" does not exist
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005630 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s %s %s",
5631 p_sh, p_shcf, p_sh, p_shcf, cmd);
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005632 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00005633#endif
Bram Moolenaarcc448b32010-07-14 16:52:17 +02005634 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s",
Bram Moolenaar0fde2902008-03-16 13:54:13 +00005635 p_sh, p_shcf, cmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005636 x = mch_system((char *)newcmd, options);
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005637 vim_free(newcmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005638 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005639 }
5640 }
5641
5642 if (tmode == TMODE_RAW)
Bram Moolenaar3b1f18f2020-05-16 23:15:08 +02005643 {
5644 // The shell may have messed with the mode, always set it.
5645 cur_tmode = TMODE_UNKNOWN;
Bram Moolenaar0f873732019-12-05 20:28:46 +01005646 settmode(TMODE_RAW); // set to raw mode
Bram Moolenaar3b1f18f2020-05-16 23:15:08 +02005647 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005648
Bram Moolenaar0f873732019-12-05 20:28:46 +01005649 // Print the return value, unless "vimrun" was used.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005650 if (x != 0 && !(options & SHELL_SILENT) && !emsg_silent
Bram Moolenaar4f974752019-02-17 17:44:42 +01005651#if defined(FEAT_GUI_MSWIN)
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02005652 && ((gui.in_use || gui.starting) ?
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005653 ((options & SHELL_DOOUT) || s_dont_use_vimrun || !p_stmp) : 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005654#endif
5655 )
5656 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005657 smsg(_("shell returned %d"), x);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005658 msg_putchar('\n');
5659 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005660 resettitle();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005661
5662 signal(SIGINT, SIG_DFL);
5663#if defined(__GNUC__) && !defined(__MINGW32__)
5664 signal(SIGKILL, SIG_DFL);
5665#else
5666 signal(SIGBREAK, SIG_DFL);
5667#endif
5668 signal(SIGILL, SIG_DFL);
5669 signal(SIGFPE, SIG_DFL);
5670 signal(SIGSEGV, SIG_DFL);
5671 signal(SIGTERM, SIG_DFL);
5672 signal(SIGABRT, SIG_DFL);
5673
5674 return x;
5675}
5676
Bram Moolenaar509ce2a2016-03-11 22:52:15 +01005677#if defined(FEAT_JOB_CHANNEL) || defined(PROTO)
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005678 static HANDLE
5679job_io_file_open(
Bram Moolenaar972c3b82017-01-12 21:44:49 +01005680 char_u *fname,
5681 DWORD dwDesiredAccess,
5682 DWORD dwShareMode,
5683 LPSECURITY_ATTRIBUTES lpSecurityAttributes,
5684 DWORD dwCreationDisposition,
5685 DWORD dwFlagsAndAttributes)
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005686{
5687 HANDLE h;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005688 WCHAR *wn;
Bram Moolenaara12a1612019-01-24 16:39:02 +01005689
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005690 wn = enc_to_utf16(fname, NULL);
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005691 if (wn == NULL)
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005692 return INVALID_HANDLE_VALUE;
5693
5694 h = CreateFileW(wn, dwDesiredAccess, dwShareMode,
5695 lpSecurityAttributes, dwCreationDisposition,
5696 dwFlagsAndAttributes, NULL);
5697 vim_free(wn);
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005698 return h;
5699}
5700
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005701/*
5702 * Turn the dictionary "env" into a NUL separated list that can be used as the
5703 * environment argument of vim_create_process().
5704 */
Bram Moolenaarba6febd2017-10-30 21:56:23 +01005705 void
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005706win32_build_env(dict_T *env, garray_T *gap, int is_terminal)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005707{
5708 hashitem_T *hi;
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005709 long_u todo = env != NULL ? env->dv_hashtab.ht_used : 0;
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005710 LPVOID base = GetEnvironmentStringsW();
5711
Bram Moolenaar0f873732019-12-05 20:28:46 +01005712 // for last \0
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005713 if (ga_grow(gap, 1) == FAIL)
5714 return;
5715
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005716 if (env != NULL)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005717 {
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005718 for (hi = env->dv_hashtab.ht_array; todo > 0; ++hi)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005719 {
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005720 if (!HASHITEM_EMPTY(hi))
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005721 {
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005722 typval_T *item = &dict_lookup(hi)->di_tv;
5723 WCHAR *wkey = enc_to_utf16((char_u *)hi->hi_key, NULL);
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005724 WCHAR *wval = enc_to_utf16(tv_get_string(item), NULL);
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005725 --todo;
5726 if (wkey != NULL && wval != NULL)
5727 {
5728 size_t n;
5729 size_t lkey = wcslen(wkey);
5730 size_t lval = wcslen(wval);
Bram Moolenaar60104f12017-08-14 23:25:04 +02005731
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005732 if (ga_grow(gap, (int)(lkey + lval + 2)) != OK)
5733 continue;
5734 for (n = 0; n < lkey; n++)
5735 *((WCHAR*)gap->ga_data + gap->ga_len++) = wkey[n];
5736 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'=';
5737 for (n = 0; n < lval; n++)
5738 *((WCHAR*)gap->ga_data + gap->ga_len++) = wval[n];
5739 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5740 }
Bram Moolenaarbdace832019-03-02 10:13:42 +01005741 vim_free(wkey);
5742 vim_free(wval);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005743 }
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005744 }
5745 }
5746
Bram Moolenaar355757a2020-02-10 22:06:32 +01005747 if (base)
5748 {
5749 WCHAR *p = (WCHAR*) base;
5750
5751 // for last \0
5752 if (ga_grow(gap, 1) == FAIL)
5753 return;
5754
5755 while (*p != 0 || *(p + 1) != 0)
5756 {
5757 if (ga_grow(gap, 1) == OK)
5758 *((WCHAR*)gap->ga_data + gap->ga_len++) = *p;
5759 p++;
5760 }
5761 FreeEnvironmentStrings(base);
5762 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5763 }
5764
Bram Moolenaar493359e2018-06-12 20:25:52 +02005765# if defined(FEAT_CLIENTSERVER) || defined(FEAT_TERMINAL)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005766 {
Bram Moolenaar493359e2018-06-12 20:25:52 +02005767# ifdef FEAT_CLIENTSERVER
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005768 char_u *servername = get_vim_var_str(VV_SEND_SERVER);
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005769 size_t servername_len = STRLEN(servername);
Bram Moolenaar493359e2018-06-12 20:25:52 +02005770# endif
5771# ifdef FEAT_TERMINAL
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005772 char_u *version = get_vim_var_str(VV_VERSION);
5773 size_t version_len = STRLEN(version);
Bram Moolenaar493359e2018-06-12 20:25:52 +02005774# endif
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005775 // size of "VIM_SERVERNAME=" and value,
5776 // plus "VIM_TERMINAL=" and value,
5777 // plus two terminating NULs
5778 size_t n = 0
Bram Moolenaar493359e2018-06-12 20:25:52 +02005779# ifdef FEAT_CLIENTSERVER
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005780 + 15 + servername_len
Bram Moolenaar493359e2018-06-12 20:25:52 +02005781# endif
5782# ifdef FEAT_TERMINAL
5783 + 13 + version_len + 2
5784# endif
5785 ;
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005786
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005787 if (ga_grow(gap, (int)n) == OK)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005788 {
Bram Moolenaar493359e2018-06-12 20:25:52 +02005789# ifdef FEAT_CLIENTSERVER
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005790 for (n = 0; n < 15; n++)
5791 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5792 (WCHAR)"VIM_SERVERNAME="[n];
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005793 for (n = 0; n < servername_len; n++)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005794 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5795 (WCHAR)servername[n];
5796 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
Bram Moolenaar493359e2018-06-12 20:25:52 +02005797# endif
5798# ifdef FEAT_TERMINAL
5799 if (is_terminal)
5800 {
5801 for (n = 0; n < 13; n++)
5802 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5803 (WCHAR)"VIM_TERMINAL="[n];
5804 for (n = 0; n < version_len; n++)
5805 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5806 (WCHAR)version[n];
5807 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5808 }
5809# endif
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005810 }
5811 }
Bram Moolenaar79c6b512018-06-12 21:11:12 +02005812# endif
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005813}
5814
Bram Moolenaarb091f302019-01-19 14:37:00 +01005815/*
5816 * Create a pair of pipes.
5817 * Return TRUE for success, FALSE for failure.
5818 */
5819 static BOOL
5820create_pipe_pair(HANDLE handles[2])
5821{
5822 static LONG s;
5823 char name[64];
5824 SECURITY_ATTRIBUTES sa;
5825
5826 sprintf(name, "\\\\?\\pipe\\vim-%08lx-%08lx",
5827 GetCurrentProcessId(),
5828 InterlockedIncrement(&s));
5829
5830 // Create named pipe. Max size of named pipe is 65535.
5831 handles[1] = CreateNamedPipe(
5832 name,
5833 PIPE_ACCESS_OUTBOUND | FILE_FLAG_OVERLAPPED,
5834 PIPE_TYPE_BYTE | PIPE_NOWAIT,
Bram Moolenaar24058382019-01-24 23:11:49 +01005835 1, MAX_NAMED_PIPE_SIZE, 0, 0, NULL);
Bram Moolenaarb091f302019-01-19 14:37:00 +01005836
5837 if (handles[1] == INVALID_HANDLE_VALUE)
5838 return FALSE;
5839
5840 sa.nLength = sizeof(sa);
5841 sa.bInheritHandle = TRUE;
5842 sa.lpSecurityDescriptor = NULL;
5843
5844 handles[0] = CreateFile(name,
5845 FILE_GENERIC_READ,
5846 FILE_SHARE_READ, &sa,
5847 OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
5848
5849 if (handles[0] == INVALID_HANDLE_VALUE)
5850 {
Bram Moolenaar6982f422019-02-16 16:48:01 +01005851 CloseHandle(handles[1]);
Bram Moolenaarb091f302019-01-19 14:37:00 +01005852 return FALSE;
5853 }
5854
5855 return TRUE;
5856}
5857
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005858 void
Bram Moolenaar5a1feb82017-07-22 18:04:08 +02005859mch_job_start(char *cmd, job_T *job, jobopt_T *options)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005860{
5861 STARTUPINFO si;
5862 PROCESS_INFORMATION pi;
Bram Moolenaar14207f42016-10-27 21:13:10 +02005863 HANDLE jo;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005864 SECURITY_ATTRIBUTES saAttr;
5865 channel_T *channel = NULL;
Bram Moolenaard8070362016-02-15 21:56:54 +01005866 HANDLE ifd[2];
5867 HANDLE ofd[2];
5868 HANDLE efd[2];
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005869 garray_T ga;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005870
5871 int use_null_for_in = options->jo_io[PART_IN] == JIO_NULL;
5872 int use_null_for_out = options->jo_io[PART_OUT] == JIO_NULL;
5873 int use_null_for_err = options->jo_io[PART_ERR] == JIO_NULL;
5874 int use_file_for_in = options->jo_io[PART_IN] == JIO_FILE;
5875 int use_file_for_out = options->jo_io[PART_OUT] == JIO_FILE;
5876 int use_file_for_err = options->jo_io[PART_ERR] == JIO_FILE;
5877 int use_out_for_err = options->jo_io[PART_ERR] == JIO_OUT;
5878
5879 if (use_out_for_err && use_null_for_out)
5880 use_null_for_err = TRUE;
Bram Moolenaard8070362016-02-15 21:56:54 +01005881
5882 ifd[0] = INVALID_HANDLE_VALUE;
5883 ifd[1] = INVALID_HANDLE_VALUE;
5884 ofd[0] = INVALID_HANDLE_VALUE;
5885 ofd[1] = INVALID_HANDLE_VALUE;
5886 efd[0] = INVALID_HANDLE_VALUE;
5887 efd[1] = INVALID_HANDLE_VALUE;
Bram Moolenaar04935fb2022-01-08 16:19:22 +00005888 ga_init2(&ga, sizeof(wchar_t), 500);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005889
Bram Moolenaar14207f42016-10-27 21:13:10 +02005890 jo = CreateJobObject(NULL, NULL);
5891 if (jo == NULL)
5892 {
5893 job->jv_status = JOB_FAILED;
5894 goto failed;
5895 }
5896
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005897 if (options->jo_env != NULL)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005898 win32_build_env(options->jo_env, &ga, FALSE);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005899
Bram Moolenaar76467df2016-02-12 19:30:26 +01005900 ZeroMemory(&pi, sizeof(pi));
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005901 ZeroMemory(&si, sizeof(si));
5902 si.cb = sizeof(si);
Bram Moolenaard8070362016-02-15 21:56:54 +01005903 si.dwFlags |= STARTF_USESHOWWINDOW;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005904 si.wShowWindow = SW_HIDE;
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005905
Bram Moolenaard8070362016-02-15 21:56:54 +01005906 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
5907 saAttr.bInheritHandle = TRUE;
5908 saAttr.lpSecurityDescriptor = NULL;
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005909
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005910 if (use_file_for_in)
5911 {
5912 char_u *fname = options->jo_io_name[PART_IN];
5913
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005914 ifd[0] = job_io_file_open(fname, GENERIC_READ,
5915 FILE_SHARE_READ | FILE_SHARE_WRITE,
5916 &saAttr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL);
5917 if (ifd[0] == INVALID_HANDLE_VALUE)
Bram Moolenaar94d01912016-03-08 13:48:51 +01005918 {
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00005919 semsg(_(e_cant_open_file_str), fname);
Bram Moolenaar94d01912016-03-08 13:48:51 +01005920 goto failed;
5921 }
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005922 }
Bram Moolenaarb091f302019-01-19 14:37:00 +01005923 else if (!use_null_for_in
5924 && (!create_pipe_pair(ifd)
5925 || !SetHandleInformation(ifd[1], 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_out)
5929 {
5930 char_u *fname = options->jo_io_name[PART_OUT];
5931
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005932 ofd[1] = job_io_file_open(fname, GENERIC_WRITE,
5933 FILE_SHARE_READ | FILE_SHARE_WRITE,
5934 &saAttr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL);
5935 if (ofd[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_null_for_out &&
5942 (!CreatePipe(&ofd[0], &ofd[1], &saAttr, 0)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005943 || !SetHandleInformation(ofd[0], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005944 goto failed;
5945
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005946 if (use_file_for_err)
5947 {
5948 char_u *fname = options->jo_io_name[PART_ERR];
5949
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005950 efd[1] = job_io_file_open(fname, GENERIC_WRITE,
5951 FILE_SHARE_READ | FILE_SHARE_WRITE,
5952 &saAttr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL);
5953 if (efd[1] == INVALID_HANDLE_VALUE)
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005954 {
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00005955 semsg(_(e_cant_open_file_str), fname);
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005956 goto failed;
5957 }
5958 }
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005959 else if (!use_out_for_err && !use_null_for_err &&
5960 (!CreatePipe(&efd[0], &efd[1], &saAttr, 0)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005961 || !SetHandleInformation(efd[0], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaard8070362016-02-15 21:56:54 +01005962 goto failed;
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005963
Bram Moolenaard8070362016-02-15 21:56:54 +01005964 si.dwFlags |= STARTF_USESTDHANDLES;
5965 si.hStdInput = ifd[0];
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005966 si.hStdOutput = ofd[1];
5967 si.hStdError = use_out_for_err ? ofd[1] : efd[1];
5968
5969 if (!use_null_for_in || !use_null_for_out || !use_null_for_err)
5970 {
Bram Moolenaarde279892016-03-11 22:19:44 +01005971 if (options->jo_set & JO_CHANNEL)
5972 {
5973 channel = options->jo_channel;
5974 if (channel != NULL)
5975 ++channel->ch_refcount;
5976 }
5977 else
5978 channel = add_channel();
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005979 if (channel == NULL)
5980 goto failed;
5981 }
Bram Moolenaard8070362016-02-15 21:56:54 +01005982
5983 if (!vim_create_process(cmd, TRUE,
Bram Moolenaar14207f42016-10-27 21:13:10 +02005984 CREATE_SUSPENDED |
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005985 CREATE_DEFAULT_ERROR_MODE |
5986 CREATE_NEW_PROCESS_GROUP |
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005987 CREATE_UNICODE_ENVIRONMENT |
Bram Moolenaar76467df2016-02-12 19:30:26 +01005988 CREATE_NEW_CONSOLE,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005989 &si, &pi,
5990 ga.ga_data,
5991 (char *)options->jo_cwd))
Bram Moolenaar76467df2016-02-12 19:30:26 +01005992 {
Bram Moolenaar14207f42016-10-27 21:13:10 +02005993 CloseHandle(jo);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005994 job->jv_status = JOB_FAILED;
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005995 goto failed;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005996 }
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005997
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005998 ga_clear(&ga);
5999
Bram Moolenaar14207f42016-10-27 21:13:10 +02006000 if (!AssignProcessToJobObject(jo, pi.hProcess))
6001 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006002 // if failing, switch the way to terminate
6003 // process with TerminateProcess.
Bram Moolenaar14207f42016-10-27 21:13:10 +02006004 CloseHandle(jo);
6005 jo = NULL;
6006 }
6007 ResumeThread(pi.hThread);
Bram Moolenaar75578a32016-03-10 16:33:31 +01006008 CloseHandle(pi.hThread);
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01006009 job->jv_proc_info = pi;
Bram Moolenaar14207f42016-10-27 21:13:10 +02006010 job->jv_job_object = jo;
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01006011 job->jv_status = JOB_STARTED;
6012
Bram Moolenaar641ad6c2016-09-01 18:32:11 +02006013 CloseHandle(ifd[0]);
6014 CloseHandle(ofd[1]);
6015 if (!use_out_for_err && !use_null_for_err)
Bram Moolenaarc25558b2016-03-03 21:02:23 +01006016 CloseHandle(efd[1]);
Bram Moolenaard8070362016-02-15 21:56:54 +01006017
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01006018 job->jv_channel = channel;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01006019 if (channel != NULL)
6020 {
6021 channel_set_pipes(channel,
6022 use_file_for_in || use_null_for_in
6023 ? INVALID_FD : (sock_T)ifd[1],
6024 use_file_for_out || use_null_for_out
6025 ? INVALID_FD : (sock_T)ofd[0],
6026 use_out_for_err || use_file_for_err || use_null_for_err
6027 ? INVALID_FD : (sock_T)efd[0]);
6028 channel_set_job(channel, job, options);
Bram Moolenaard5d3d302016-03-09 20:54:51 +01006029 }
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01006030 return;
6031
6032failed:
Bram Moolenaard8070362016-02-15 21:56:54 +01006033 CloseHandle(ifd[0]);
6034 CloseHandle(ofd[0]);
6035 CloseHandle(efd[0]);
6036 CloseHandle(ifd[1]);
6037 CloseHandle(ofd[1]);
6038 CloseHandle(efd[1]);
Bram Moolenaarde279892016-03-11 22:19:44 +01006039 channel_unref(channel);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02006040 ga_clear(&ga);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01006041}
6042
6043 char *
6044mch_job_status(job_T *job)
6045{
6046 DWORD dwExitCode = 0;
6047
Bram Moolenaar76467df2016-02-12 19:30:26 +01006048 if (!GetExitCodeProcess(job->jv_proc_info.hProcess, &dwExitCode)
6049 || dwExitCode != STILL_ACTIVE)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01006050 {
Bram Moolenaareab089d2016-02-21 19:32:02 +01006051 job->jv_exitval = (int)dwExitCode;
Bram Moolenaar7df915d2016-11-17 17:25:32 +01006052 if (job->jv_status < JOB_ENDED)
Bram Moolenaar97792de2016-10-15 18:36:49 +02006053 {
6054 ch_log(job->jv_channel, "Job ended");
6055 job->jv_status = JOB_ENDED;
6056 }
Bram Moolenaar942d6b22016-02-07 19:57:16 +01006057 return "dead";
6058 }
6059 return "run";
6060}
6061
Bram Moolenaar97792de2016-10-15 18:36:49 +02006062 job_T *
6063mch_detect_ended_job(job_T *job_list)
6064{
6065 HANDLE jobHandles[MAXIMUM_WAIT_OBJECTS];
6066 job_T *jobArray[MAXIMUM_WAIT_OBJECTS];
6067 job_T *job = job_list;
6068
6069 while (job != NULL)
6070 {
6071 DWORD n;
6072 DWORD result;
6073
6074 for (n = 0; n < MAXIMUM_WAIT_OBJECTS
6075 && job != NULL; job = job->jv_next)
6076 {
6077 if (job->jv_status == JOB_STARTED)
6078 {
6079 jobHandles[n] = job->jv_proc_info.hProcess;
6080 jobArray[n] = job;
6081 ++n;
6082 }
6083 }
6084 if (n == 0)
6085 continue;
6086 result = WaitForMultipleObjects(n, jobHandles, FALSE, 0);
6087 if (result >= WAIT_OBJECT_0 && result < WAIT_OBJECT_0 + n)
6088 {
6089 job_T *wait_job = jobArray[result - WAIT_OBJECT_0];
6090
6091 if (STRCMP(mch_job_status(wait_job), "dead") == 0)
6092 return wait_job;
6093 }
6094 }
6095 return NULL;
6096}
6097
Bram Moolenaarfb630902016-10-29 14:55:00 +02006098 static BOOL
6099terminate_all(HANDLE process, int code)
6100{
6101 PROCESSENTRY32 pe;
6102 HANDLE h = INVALID_HANDLE_VALUE;
6103 DWORD pid = GetProcessId(process);
6104
6105 if (pid != 0)
6106 {
6107 h = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
6108 if (h != INVALID_HANDLE_VALUE)
6109 {
6110 pe.dwSize = sizeof(PROCESSENTRY32);
6111 if (!Process32First(h, &pe))
6112 goto theend;
6113
6114 do
6115 {
6116 if (pe.th32ParentProcessID == pid)
6117 {
6118 HANDLE ph = OpenProcess(
6119 PROCESS_ALL_ACCESS, FALSE, pe.th32ProcessID);
6120 if (ph != NULL)
6121 {
6122 terminate_all(ph, code);
6123 CloseHandle(ph);
6124 }
6125 }
6126 } while (Process32Next(h, &pe));
6127
6128 CloseHandle(h);
6129 }
6130 }
6131
6132theend:
6133 return TerminateProcess(process, code);
6134}
6135
6136/*
6137 * Send a (deadly) signal to "job".
6138 * Return FAIL if it didn't work.
6139 */
Bram Moolenaar942d6b22016-02-07 19:57:16 +01006140 int
Bram Moolenaar2d33e902017-08-11 16:31:54 +02006141mch_signal_job(job_T *job, char_u *how)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01006142{
Bram Moolenaar923d9262016-02-25 20:56:01 +01006143 int ret;
Bram Moolenaar76467df2016-02-12 19:30:26 +01006144
Bram Moolenaar923d9262016-02-25 20:56:01 +01006145 if (STRCMP(how, "term") == 0 || STRCMP(how, "kill") == 0 || *how == NUL)
Bram Moolenaar76467df2016-02-12 19:30:26 +01006146 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006147 // deadly signal
Bram Moolenaar14207f42016-10-27 21:13:10 +02006148 if (job->jv_job_object != NULL)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006149 {
6150 if (job->jv_channel != NULL && job->jv_channel->ch_anonymous_pipe)
6151 job->jv_channel->ch_killing = TRUE;
K.Takata135e1522022-01-29 15:27:58 +00006152 return TerminateJobObject(job->jv_job_object, (UINT)-1) ? OK : FAIL;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006153 }
Bram Moolenaarb3e195c2020-02-10 21:32:19 +01006154 return terminate_all(job->jv_proc_info.hProcess, -1) ? OK : FAIL;
Bram Moolenaar76467df2016-02-12 19:30:26 +01006155 }
6156
6157 if (!AttachConsole(job->jv_proc_info.dwProcessId))
6158 return FAIL;
6159 ret = GenerateConsoleCtrlEvent(
Bram Moolenaar923d9262016-02-25 20:56:01 +01006160 STRCMP(how, "int") == 0 ? CTRL_C_EVENT : CTRL_BREAK_EVENT,
6161 job->jv_proc_info.dwProcessId)
6162 ? OK : FAIL;
Bram Moolenaar76467df2016-02-12 19:30:26 +01006163 FreeConsole();
6164 return ret;
6165}
6166
6167/*
6168 * Clear the data related to "job".
6169 */
6170 void
6171mch_clear_job(job_T *job)
6172{
6173 if (job->jv_status != JOB_FAILED)
6174 {
Bram Moolenaar14207f42016-10-27 21:13:10 +02006175 if (job->jv_job_object != NULL)
6176 CloseHandle(job->jv_job_object);
Bram Moolenaar76467df2016-02-12 19:30:26 +01006177 CloseHandle(job->jv_proc_info.hProcess);
6178 }
Bram Moolenaar942d6b22016-02-07 19:57:16 +01006179}
6180#endif
6181
Bram Moolenaar071d4272004-06-13 20:20:40 +00006182
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006183#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006184
6185/*
6186 * Start termcap mode
6187 */
6188 static void
6189termcap_mode_start(void)
6190{
6191 DWORD cmodein;
6192
6193 if (g_fTermcapMode)
6194 return;
6195
Christopher Plewright1140b512022-11-12 18:46:05 +00006196 // VTP uses alternate screen buffer.
6197 // Switch to a new alternate screen buffer.
Christopher Plewrightc8b126d2022-12-22 13:45:23 +00006198 // But, not if running in a nested terminal
6199 if (use_alternate_screen_buffer)
Bram Moolenaar81ccbf12020-04-15 21:05:30 +02006200 vtp_printf("\033[?1049h");
6201
Bram Moolenaar071d4272004-06-13 20:20:40 +00006202 SaveConsoleBuffer(&g_cbNonTermcap);
6203
6204 if (g_cbTermcap.IsValid)
6205 {
6206 /*
6207 * We've been in termcap mode before. Restore certain screen
6208 * characteristics, including the buffer size and the window
6209 * size. Since we will be redrawing the screen, we don't need
6210 * to restore the actual contents of the buffer.
6211 */
6212 RestoreConsoleBuffer(&g_cbTermcap, FALSE);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006213 reset_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00006214 SetConsoleWindowInfo(g_hConOut, TRUE, &g_cbTermcap.Info.srWindow);
6215 Rows = g_cbTermcap.Info.dwSize.Y;
6216 Columns = g_cbTermcap.Info.dwSize.X;
6217 }
6218 else
6219 {
6220 /*
6221 * This is our first time entering termcap mode. Clear the console
6222 * screen buffer, and resize the buffer to match the current window
6223 * size. We will use this as the size of our editing environment.
6224 */
6225 ClearConsoleBuffer(g_attrCurrent);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006226 set_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00006227 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
6228 }
6229
Bram Moolenaar071d4272004-06-13 20:20:40 +00006230 resettitle();
Bram Moolenaar071d4272004-06-13 20:20:40 +00006231
6232 GetConsoleMode(g_hConIn, &cmodein);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006233 if (g_fMouseActive)
Wez Furlong6ef5ab52021-05-30 19:29:41 +02006234 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006235 cmodein |= ENABLE_MOUSE_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02006236 cmodein &= ~ENABLE_QUICK_EDIT_MODE;
6237 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006238 else
Wez Furlong6ef5ab52021-05-30 19:29:41 +02006239 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006240 cmodein &= ~ENABLE_MOUSE_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02006241 cmodein |= g_cmodein & ENABLE_QUICK_EDIT_MODE;
6242 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006243 cmodein |= ENABLE_WINDOW_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02006244 SetConsoleMode(g_hConIn, cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006245
6246 redraw_later_clear();
6247 g_fTermcapMode = TRUE;
6248}
6249
6250
6251/*
6252 * End termcap mode
6253 */
6254 static void
6255termcap_mode_end(void)
6256{
6257 DWORD cmodein;
6258 ConsoleBuffer *cb;
6259 COORD coord;
6260 DWORD dwDummy;
6261
6262 if (!g_fTermcapMode)
6263 return;
6264
6265 SaveConsoleBuffer(&g_cbTermcap);
6266
6267 GetConsoleMode(g_hConIn, &cmodein);
6268 cmodein &= ~(ENABLE_MOUSE_INPUT | ENABLE_WINDOW_INPUT);
Wez Furlong6ef5ab52021-05-30 19:29:41 +02006269 cmodein |= g_cmodein & ENABLE_QUICK_EDIT_MODE;
6270 SetConsoleMode(g_hConIn, cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006271
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006272# ifdef FEAT_RESTORE_ORIG_SCREEN
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01006273 cb = exiting ? &g_cbOrig : &g_cbNonTermcap;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006274# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00006275 cb = &g_cbNonTermcap;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006276# endif
Bram Moolenaar81ccbf12020-04-15 21:05:30 +02006277 RestoreConsoleBuffer(cb, p_rs);
Bram Moolenaardf543822020-01-30 11:53:59 +01006278 restore_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00006279
Christopher Plewright1140b512022-11-12 18:46:05 +00006280 // VTP uses alternate screen buffer.
6281 // Switch back to main screen buffer.
Christopher Plewrightc8b126d2022-12-22 13:45:23 +00006282 if (exiting && use_alternate_screen_buffer)
Christopher Plewright1140b512022-11-12 18:46:05 +00006283 vtp_printf("\033[?1049l");
6284
6285 if (!USE_WT && (p_rs || exiting))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006286 {
6287 /*
6288 * Clear anything that happens to be on the current line.
6289 */
6290 coord.X = 0;
6291 coord.Y = (SHORT) (p_rs ? cb->Info.dwCursorPosition.Y : (Rows - 1));
Christopher Plewright1140b512022-11-12 18:46:05 +00006292 if (!vtp_working)
6293 FillConsoleOutputCharacter(g_hConOut, ' ',
6294 cb->Info.dwSize.X, coord, &dwDummy);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006295 /*
6296 * The following is just for aesthetics. If we are exiting without
6297 * restoring the screen, then we want to have a prompt string
6298 * appear at the bottom line. However, the command interpreter
6299 * seems to always advance the cursor one line before displaying
6300 * the prompt string, which causes the screen to scroll. To
6301 * counter this, move the cursor up one line before exiting.
6302 */
6303 if (exiting && !p_rs)
6304 coord.Y--;
6305 /*
6306 * Position the cursor at the leftmost column of the desired row.
6307 */
Bram Moolenaar81ccbf12020-04-15 21:05:30 +02006308 SetConsoleCursorPosition(g_hConOut, coord);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006309 }
Christopher Plewright1140b512022-11-12 18:46:05 +00006310 SetConsoleCursorInfo(g_hConOut, &g_cci);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006311 g_fTermcapMode = FALSE;
6312}
Christopher Plewright38804d62022-11-09 23:55:52 +00006313#endif // !FEAT_GUI_MSWIN || VIMDLL
Bram Moolenaar071d4272004-06-13 20:20:40 +00006314
6315
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006316#if defined(FEAT_GUI_MSWIN) && !defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006317 void
6318mch_write(
Bram Moolenaar1266d672017-02-01 13:43:36 +01006319 char_u *s UNUSED,
6320 int len UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006321{
Bram Moolenaar0f873732019-12-05 20:28:46 +01006322 // never used
Bram Moolenaar071d4272004-06-13 20:20:40 +00006323}
6324
6325#else
6326
6327/*
6328 * clear `n' chars, starting from `coord'
6329 */
6330 static void
6331clear_chars(
6332 COORD coord,
6333 DWORD n)
6334{
Christopher Plewright38804d62022-11-09 23:55:52 +00006335 if (!vtp_working)
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006336 {
6337 DWORD dwDummy;
6338
6339 FillConsoleOutputCharacter(g_hConOut, ' ', n, coord, &dwDummy);
6340 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, n, coord,
6341 &dwDummy);
6342 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006343 else
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02006344 {
6345 set_console_color_rgb();
6346 gotoxy(coord.X + 1, coord.Y + 1);
6347 vtp_printf("\033[%dX", n);
6348 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006349}
6350
6351
6352/*
6353 * Clear the screen
6354 */
6355 static void
6356clear_screen(void)
6357{
6358 g_coord.X = g_coord.Y = 0;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006359
Christopher Plewright38804d62022-11-09 23:55:52 +00006360 if (!vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006361 clear_chars(g_coord, Rows * Columns);
6362 else
6363 {
6364 set_console_color_rgb();
6365 gotoxy(1, 1);
6366 vtp_printf("\033[2J");
6367 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006368}
6369
6370
6371/*
6372 * Clear to end of display
6373 */
6374 static void
6375clear_to_end_of_display(void)
6376{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006377 COORD save = g_coord;
6378
Christopher Plewright38804d62022-11-09 23:55:52 +00006379 if (!vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006380 clear_chars(g_coord, (Rows - g_coord.Y - 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006381 * Columns + (Columns - g_coord.X));
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006382 else
6383 {
6384 set_console_color_rgb();
6385 gotoxy(g_coord.X + 1, g_coord.Y + 1);
6386 vtp_printf("\033[0J");
6387
6388 gotoxy(save.X + 1, save.Y + 1);
6389 g_coord = save;
6390 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006391}
6392
6393
6394/*
6395 * Clear to end of line
6396 */
6397 static void
6398clear_to_end_of_line(void)
6399{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006400 COORD save = g_coord;
6401
Christopher Plewright38804d62022-11-09 23:55:52 +00006402 if (!vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006403 clear_chars(g_coord, Columns - g_coord.X);
6404 else
6405 {
6406 set_console_color_rgb();
6407 gotoxy(g_coord.X + 1, g_coord.Y + 1);
6408 vtp_printf("\033[0K");
6409
6410 gotoxy(save.X + 1, save.Y + 1);
6411 g_coord = save;
6412 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006413}
6414
6415
6416/*
6417 * Scroll the scroll region up by `cLines' lines
6418 */
6419 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006420scroll(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006421{
6422 COORD oldcoord = g_coord;
6423
6424 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
6425 delete_lines(cLines);
6426
6427 g_coord = oldcoord;
6428}
6429
6430
6431/*
6432 * Set the scroll region
6433 */
6434 static void
6435set_scroll_region(
6436 unsigned left,
6437 unsigned top,
6438 unsigned right,
6439 unsigned bottom)
6440{
6441 if (left >= right
6442 || top >= bottom
6443 || right > (unsigned) Columns - 1
6444 || bottom > (unsigned) Rows - 1)
6445 return;
6446
6447 g_srScrollRegion.Left = left;
6448 g_srScrollRegion.Top = top;
6449 g_srScrollRegion.Right = right;
6450 g_srScrollRegion.Bottom = bottom;
Bram Moolenaar6982f422019-02-16 16:48:01 +01006451}
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006452
Bram Moolenaar6982f422019-02-16 16:48:01 +01006453 static void
6454set_scroll_region_tb(
6455 unsigned top,
6456 unsigned bottom)
6457{
6458 if (top >= bottom || bottom > (unsigned)Rows - 1)
6459 return;
6460
6461 g_srScrollRegion.Top = top;
6462 g_srScrollRegion.Bottom = bottom;
6463}
6464
6465 static void
6466set_scroll_region_lr(
6467 unsigned left,
6468 unsigned right)
6469{
6470 if (left >= right || right > (unsigned)Columns - 1)
6471 return;
6472
6473 g_srScrollRegion.Left = left;
6474 g_srScrollRegion.Right = right;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006475}
6476
6477
6478/*
6479 * Insert `cLines' lines at the current cursor position
6480 */
6481 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006482insert_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006483{
Bram Moolenaar6982f422019-02-16 16:48:01 +01006484 SMALL_RECT source, clip;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006485 COORD dest;
6486 CHAR_INFO fill;
6487
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006488 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
6489
Bram Moolenaar6982f422019-02-16 16:48:01 +01006490 dest.X = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006491 dest.Y = g_coord.Y + cLines;
6492
Bram Moolenaar6982f422019-02-16 16:48:01 +01006493 source.Left = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006494 source.Top = g_coord.Y;
6495 source.Right = g_srScrollRegion.Right;
6496 source.Bottom = g_srScrollRegion.Bottom - cLines;
6497
Bram Moolenaar6982f422019-02-16 16:48:01 +01006498 clip.Left = g_srScrollRegion.Left;
6499 clip.Top = g_coord.Y;
6500 clip.Right = g_srScrollRegion.Right;
6501 clip.Bottom = g_srScrollRegion.Bottom;
6502
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006503 fill.Char.AsciiChar = ' ';
Christopher Plewright38804d62022-11-09 23:55:52 +00006504 if (!(vtp_working
K.Takata161b6ac2022-11-14 15:31:07 +00006505# ifdef FEAT_TERMGUICOLORS
Christopher Plewright38804d62022-11-09 23:55:52 +00006506 && (p_tgc || t_colors >= 256)
K.Takata161b6ac2022-11-14 15:31:07 +00006507# endif
Christopher Plewright38804d62022-11-09 23:55:52 +00006508 ))
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006509 fill.Attributes = g_attrCurrent;
6510 else
6511 fill.Attributes = g_attrDefault;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006512
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006513 set_console_color_rgb();
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006514
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006515 ScrollConsoleScreenBuffer(g_hConOut, &source, &clip, dest, &fill);
6516
Bram Moolenaar6982f422019-02-16 16:48:01 +01006517 // Here we have to deal with a win32 console flake: If the scroll
6518 // region looks like abc and we scroll c to a and fill with d we get
6519 // cbd... if we scroll block c one line at a time to a, we get cdd...
6520 // vim expects cdd consistently... So we have to deal with that
6521 // here... (this also occurs scrolling the same way in the other
6522 // direction).
Bram Moolenaar071d4272004-06-13 20:20:40 +00006523
6524 if (source.Bottom < dest.Y)
6525 {
6526 COORD coord;
Bram Moolenaar6982f422019-02-16 16:48:01 +01006527 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006528
Bram Moolenaar6982f422019-02-16 16:48:01 +01006529 coord.X = source.Left;
6530 for (i = clip.Top; i < dest.Y; ++i)
6531 {
6532 coord.Y = i;
6533 clear_chars(coord, source.Right - source.Left + 1);
6534 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006535 }
Bram Moolenaar06b7b582020-05-30 17:49:25 +02006536
Christopher Plewright38804d62022-11-09 23:55:52 +00006537 if (vtp_working)
Bram Moolenaar06b7b582020-05-30 17:49:25 +02006538 {
6539 COORD coord;
6540 int i;
6541
6542 coord.X = source.Left;
6543 for (i = source.Top; i < dest.Y; ++i)
6544 {
6545 coord.Y = i;
6546 clear_chars(coord, source.Right - source.Left + 1);
6547 }
6548 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006549}
6550
6551
6552/*
6553 * Delete `cLines' lines at the current cursor position
6554 */
6555 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006556delete_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006557{
Bram Moolenaar6982f422019-02-16 16:48:01 +01006558 SMALL_RECT source, clip;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006559 COORD dest;
6560 CHAR_INFO fill;
6561 int nb;
6562
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006563 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
6564
Bram Moolenaar6982f422019-02-16 16:48:01 +01006565 dest.X = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006566 dest.Y = g_coord.Y;
6567
Bram Moolenaar6982f422019-02-16 16:48:01 +01006568 source.Left = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006569 source.Top = g_coord.Y + cLines;
6570 source.Right = g_srScrollRegion.Right;
6571 source.Bottom = g_srScrollRegion.Bottom;
6572
Bram Moolenaar6982f422019-02-16 16:48:01 +01006573 clip.Left = g_srScrollRegion.Left;
6574 clip.Top = g_coord.Y;
6575 clip.Right = g_srScrollRegion.Right;
6576 clip.Bottom = g_srScrollRegion.Bottom;
6577
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006578 fill.Char.AsciiChar = ' ';
Christopher Plewright38804d62022-11-09 23:55:52 +00006579 if (!vtp_working)
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006580 fill.Attributes = g_attrCurrent;
6581 else
6582 fill.Attributes = g_attrDefault;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006583
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006584 set_console_color_rgb();
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006585
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006586 ScrollConsoleScreenBuffer(g_hConOut, &source, &clip, dest, &fill);
6587
Bram Moolenaar6982f422019-02-16 16:48:01 +01006588 // Here we have to deal with a win32 console flake; See insert_lines()
6589 // above.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006590
6591 nb = dest.Y + (source.Bottom - source.Top) + 1;
6592
6593 if (nb < source.Top)
6594 {
6595 COORD coord;
Bram Moolenaar6982f422019-02-16 16:48:01 +01006596 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006597
Bram Moolenaar6982f422019-02-16 16:48:01 +01006598 coord.X = source.Left;
6599 for (i = nb; i < clip.Bottom; ++i)
6600 {
6601 coord.Y = i;
6602 clear_chars(coord, source.Right - source.Left + 1);
6603 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006604 }
Bram Moolenaar06b7b582020-05-30 17:49:25 +02006605
Christopher Plewright38804d62022-11-09 23:55:52 +00006606 if (vtp_working)
Bram Moolenaar06b7b582020-05-30 17:49:25 +02006607 {
6608 COORD coord;
6609 int i;
6610
6611 coord.X = source.Left;
6612 for (i = nb; i <= source.Bottom; ++i)
6613 {
6614 coord.Y = i;
6615 clear_chars(coord, source.Right - source.Left + 1);
6616 }
6617 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006618}
6619
6620
6621/*
Bram Moolenaar2313b612019-09-27 14:14:32 +02006622 * Set the cursor position to (x,y) (1-based).
Bram Moolenaar071d4272004-06-13 20:20:40 +00006623 */
6624 static void
6625gotoxy(
6626 unsigned x,
6627 unsigned y)
6628{
6629 if (x < 1 || x > (unsigned)Columns || y < 1 || y > (unsigned)Rows)
6630 return;
6631
Christopher Plewright38804d62022-11-09 23:55:52 +00006632 if (!(vtp_working
K.Takata161b6ac2022-11-14 15:31:07 +00006633# ifdef FEAT_TERMGUICOLORS
Christopher Plewright38804d62022-11-09 23:55:52 +00006634 && (p_tgc || t_colors >= 256)
K.Takata161b6ac2022-11-14 15:31:07 +00006635# endif
Christopher Plewright38804d62022-11-09 23:55:52 +00006636 ))
Bram Moolenaar2313b612019-09-27 14:14:32 +02006637 {
Bram Moolenaar82e743c2020-03-26 15:39:53 +01006638 // There are reports of double-width characters not displayed
6639 // correctly. This workaround should fix it, similar to how it's done
6640 // for VTP.
6641 g_coord.X = 0;
6642 SetConsoleCursorPosition(g_hConOut, g_coord);
6643
Bram Moolenaar2313b612019-09-27 14:14:32 +02006644 // external cursor coords are 1-based; internal are 0-based
6645 g_coord.X = x - 1;
6646 g_coord.Y = y - 1;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006647 SetConsoleCursorPosition(g_hConOut, g_coord);
Bram Moolenaar2313b612019-09-27 14:14:32 +02006648 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006649 else
Bram Moolenaar2313b612019-09-27 14:14:32 +02006650 {
6651 // Move the cursor to the left edge of the screen to prevent screen
Bram Moolenaara1299742019-10-10 16:36:00 +02006652 // destruction. Insider build bug. Always enabled because it's cheap
6653 // and avoids mistakes with recognizing the build.
6654 vtp_printf("\033[%d;%dH", g_coord.Y + 1, 1);
Bram Moolenaar2313b612019-09-27 14:14:32 +02006655
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006656 vtp_printf("\033[%d;%dH", y, x);
Bram Moolenaar2313b612019-09-27 14:14:32 +02006657
6658 g_coord.X = x - 1;
6659 g_coord.Y = y - 1;
6660 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006661}
6662
6663
6664/*
6665 * Set the current text attribute = (foreground | background)
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006666 * See ../runtime/doc/os_win32.txt for the numbers.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006667 */
6668 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006669textattr(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006670{
Bram Moolenaar6383b922015-03-24 17:12:19 +01006671 g_attrCurrent = wAttr & 0xff;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006672
6673 SetConsoleTextAttribute(g_hConOut, wAttr);
6674}
6675
6676
6677 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006678textcolor(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006679{
Bram Moolenaar6383b922015-03-24 17:12:19 +01006680 g_attrCurrent = (g_attrCurrent & 0xf0) + (wAttr & 0x0f);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006681
Christopher Plewright38804d62022-11-09 23:55:52 +00006682 if (!vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006683 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
6684 else
6685 vtp_sgr_bulk(wAttr);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006686}
6687
6688
6689 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006690textbackground(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006691{
Bram Moolenaar6383b922015-03-24 17:12:19 +01006692 g_attrCurrent = (g_attrCurrent & 0x0f) + ((wAttr & 0x0f) << 4);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006693
Christopher Plewright38804d62022-11-09 23:55:52 +00006694 if (!vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006695 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
6696 else
6697 vtp_sgr_bulk(wAttr);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006698}
6699
6700
6701/*
6702 * restore the default text attribute (whatever we started with)
6703 */
6704 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006705normvideo(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006706{
Christopher Plewright38804d62022-11-09 23:55:52 +00006707 if (!vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006708 textattr(g_attrDefault);
6709 else
6710 vtp_sgr_bulk(0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006711}
6712
6713
6714static WORD g_attrPreStandout = 0;
6715
6716/*
6717 * Make the text standout, by brightening it
6718 */
6719 static void
6720standout(void)
6721{
6722 g_attrPreStandout = g_attrCurrent;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006723
Bram Moolenaar071d4272004-06-13 20:20:40 +00006724 textattr((WORD) (g_attrCurrent|FOREGROUND_INTENSITY|BACKGROUND_INTENSITY));
6725}
6726
6727
6728/*
6729 * Turn off standout mode
6730 */
6731 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006732standend(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006733{
6734 if (g_attrPreStandout)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006735 textattr(g_attrPreStandout);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006736
6737 g_attrPreStandout = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006738}
6739
6740
6741/*
Bram Moolenaarff1d0d42007-05-10 17:24:16 +00006742 * Set normal fg/bg color, based on T_ME. Called when t_me has been set.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006743 */
6744 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006745mch_set_normal_colors(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006746{
6747 char_u *p;
6748 int n;
6749
6750 cterm_normal_fg_color = (g_attrDefault & 0xf) + 1;
6751 cterm_normal_bg_color = ((g_attrDefault >> 4) & 0xf) + 1;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006752 if (
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006753# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006754 !p_tgc &&
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006755# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006756 T_ME[0] == ESC && T_ME[1] == '|')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006757 {
6758 p = T_ME + 2;
6759 n = getdigits(&p);
6760 if (*p == 'm' && n > 0)
6761 {
6762 cterm_normal_fg_color = (n & 0xf) + 1;
6763 cterm_normal_bg_color = ((n >> 4) & 0xf) + 1;
6764 }
6765 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006766# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006767 cterm_normal_fg_gui_color = INVALCOLOR;
6768 cterm_normal_bg_gui_color = INVALCOLOR;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006769# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006770}
6771
6772
6773/*
6774 * visual bell: flash the screen
6775 */
6776 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006777visual_bell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006778{
6779 COORD coordOrigin = {0, 0};
6780 WORD attrFlash = ~g_attrCurrent & 0xff;
6781
6782 DWORD dwDummy;
Bram Moolenaarc799fe22019-05-28 23:08:19 +02006783 LPWORD oldattrs = ALLOC_MULT(WORD, Rows * Columns);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006784
6785 if (oldattrs == NULL)
6786 return;
6787 ReadConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
6788 coordOrigin, &dwDummy);
6789 FillConsoleOutputAttribute(g_hConOut, attrFlash, Rows * Columns,
6790 coordOrigin, &dwDummy);
6791
Bram Moolenaar0f873732019-12-05 20:28:46 +01006792 Sleep(15); // wait for 15 msec
Christopher Plewright38804d62022-11-09 23:55:52 +00006793 if (!vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006794 WriteConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
Bram Moolenaar071d4272004-06-13 20:20:40 +00006795 coordOrigin, &dwDummy);
6796 vim_free(oldattrs);
6797}
6798
6799
6800/*
6801 * Make the cursor visible or invisible
6802 */
6803 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006804cursor_visible(BOOL fVisible)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006805{
6806 s_cursor_visible = fVisible;
Bram Moolenaar2695de62020-04-17 21:13:01 +02006807
Christopher Plewright38804d62022-11-09 23:55:52 +00006808 if (vtp_working)
Bram Moolenaar2695de62020-04-17 21:13:01 +02006809 vtp_printf("\033[?25%c", fVisible ? 'h' : 'l');
6810
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006811# ifdef MCH_CURSOR_SHAPE
Bram Moolenaar071d4272004-06-13 20:20:40 +00006812 mch_update_cursor();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006813# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006814}
6815
6816
6817/*
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02006818 * Write "cbToWrite" bytes in `pchBuf' to the screen.
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006819 * Returns the number of bytes actually written (at least one).
Bram Moolenaar071d4272004-06-13 20:20:40 +00006820 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006821 static DWORD
Bram Moolenaar071d4272004-06-13 20:20:40 +00006822write_chars(
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006823 char_u *pchBuf,
6824 DWORD cbToWrite)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006825{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006826 COORD coord = g_coord;
6827 DWORD written;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006828 DWORD n, cchwritten;
6829 static DWORD cells;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006830 static WCHAR *unicodebuf = NULL;
6831 static int unibuflen = 0;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006832 static int length;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006833 int cp = enc_utf8 ? CP_UTF8 : enc_codepage;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006834 static WCHAR *utf8spbuf = NULL;
6835 static int utf8splength;
6836 static DWORD utf8spcells;
6837 static WCHAR **utf8usingbuf = &unicodebuf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006838
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006839 if (cbToWrite != 1 || *pchBuf != ' ' || !enc_utf8)
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006840 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006841 utf8usingbuf = &unicodebuf;
6842 do
6843 {
6844 length = MultiByteToWideChar(cp, 0, (LPCSTR)pchBuf, cbToWrite,
6845 unicodebuf, unibuflen);
6846 if (length && length <= unibuflen)
6847 break;
6848 vim_free(unicodebuf);
6849 unicodebuf = length ? LALLOC_MULT(WCHAR, length) : NULL;
6850 unibuflen = unibuflen ? 0 : length;
6851 } while(1);
6852 cells = mb_string2cells(pchBuf, cbToWrite);
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006853 }
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006854 else // cbToWrite == 1 && *pchBuf == ' ' && enc_utf8
6855 {
6856 if (utf8usingbuf != &utf8spbuf)
6857 {
6858 if (utf8spbuf == NULL)
6859 {
6860 cells = mb_string2cells((char_u *)" ", 1);
6861 length = MultiByteToWideChar(CP_UTF8, 0, " ", 1, NULL, 0);
6862 utf8spbuf = LALLOC_MULT(WCHAR, length);
6863 if (utf8spbuf != NULL)
6864 {
6865 MultiByteToWideChar(CP_UTF8, 0, " ", 1, utf8spbuf, length);
6866 utf8usingbuf = &utf8spbuf;
6867 utf8splength = length;
6868 utf8spcells = cells;
6869 }
6870 }
6871 else
6872 {
6873 utf8usingbuf = &utf8spbuf;
6874 length = utf8splength;
6875 cells = utf8spcells;
6876 }
6877 }
6878 }
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006879
Christopher Plewright38804d62022-11-09 23:55:52 +00006880 if (!(vtp_working
K.Takata161b6ac2022-11-14 15:31:07 +00006881# ifdef FEAT_TERMGUICOLORS
Christopher Plewright38804d62022-11-09 23:55:52 +00006882 && (p_tgc || t_colors >= 256)
K.Takata161b6ac2022-11-14 15:31:07 +00006883# endif
Christopher Plewright38804d62022-11-09 23:55:52 +00006884 ))
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006885 {
6886 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, cells,
6887 coord, &written);
6888 // When writing fails or didn't write a single character, pretend one
6889 // character was written, otherwise we get stuck.
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006890 if (WriteConsoleOutputCharacterW(g_hConOut, *utf8usingbuf, length,
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006891 coord, &cchwritten) == 0
6892 || cchwritten == 0 || cchwritten == (DWORD)-1)
6893 cchwritten = 1;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006894 }
6895 else
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006896 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006897 if (WriteConsoleW(g_hConOut, *utf8usingbuf, length, &cchwritten,
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006898 NULL) == 0 || cchwritten == 0)
6899 cchwritten = 1;
6900 }
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006901
K.Takata135e1522022-01-29 15:27:58 +00006902 if (cchwritten == (DWORD)length)
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006903 {
6904 written = cbToWrite;
6905 g_coord.X += (SHORT)cells;
6906 }
6907 else
6908 {
6909 char_u *p = pchBuf;
6910 for (n = 0; n < cchwritten; n++)
6911 MB_CPTR_ADV(p);
6912 written = p - pchBuf;
6913 g_coord.X += (SHORT)mb_string2cells(pchBuf, written);
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006914 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006915
6916 while (g_coord.X > g_srScrollRegion.Right)
6917 {
6918 g_coord.X -= (SHORT) Columns;
6919 if (g_coord.Y < g_srScrollRegion.Bottom)
6920 g_coord.Y++;
6921 }
6922
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006923 // Cursor under VTP is always in the correct position, no need to reset.
Christopher Plewright38804d62022-11-09 23:55:52 +00006924 if (!(vtp_working
K.Takata161b6ac2022-11-14 15:31:07 +00006925# ifdef FEAT_TERMGUICOLORS
Christopher Plewright38804d62022-11-09 23:55:52 +00006926 && (p_tgc || t_colors >= 256)
K.Takata161b6ac2022-11-14 15:31:07 +00006927# endif
Christopher Plewright38804d62022-11-09 23:55:52 +00006928 ))
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006929 gotoxy(g_coord.X + 1, g_coord.Y + 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006930
6931 return written;
6932}
6933
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006934 static char_u *
6935get_seq(
6936 int *args,
6937 int *count,
6938 char_u *head)
6939{
6940 int argc;
6941 char_u *p;
6942
6943 if (head == NULL || *head != '\033')
6944 return NULL;
6945
6946 argc = 0;
6947 p = head;
6948 ++p;
6949 do
6950 {
6951 ++p;
6952 args[argc] = getdigits(&p);
6953 argc += (argc < 15) ? 1 : 0;
6954 } while (*p == ';');
6955 *count = argc;
6956
6957 return p;
6958}
6959
6960 static char_u *
6961get_sgr(
6962 int *args,
6963 int *count,
6964 char_u *head)
6965{
6966 char_u *p = get_seq(args, count, head);
6967
6968 return (p && *p == 'm') ? ++p : NULL;
6969}
6970
6971/*
6972 * Pointer to next if SGR (^[[n;2;*;*;*m), NULL otherwise.
6973 */
6974 static char_u *
6975sgrn2(
6976 char_u *head,
6977 int n)
6978{
6979 int argc;
6980 int args[16];
6981 char_u *p = get_sgr(args, &argc, head);
6982
6983 return p && argc == 5 && args[0] == n && args[1] == 2 ? p : NULL;
6984}
6985
6986/*
6987 * Pointer to next if SGR(^[[nm)<space>ESC, NULL otherwise.
6988 */
6989 static char_u *
6990sgrnc(
6991 char_u *head,
6992 int n)
6993{
6994 int argc;
6995 int args[16];
6996 char_u *p = get_sgr(args, &argc, head);
6997
6998 return p && argc == 1 && args[0] == n && (p = skipwhite(p)) && *p == '\033'
6999 ? p : NULL;
7000}
7001
7002 static char_u *
7003skipblank(char_u *q)
7004{
7005 char_u *p = q;
7006
7007 while (*p == ' ' || *p == '\t' || *p == '\n' || *p == '\r')
7008 ++p;
7009 return p;
7010}
7011
7012/*
7013 * Pointer to the next if any whitespace that may follow SGR is ESC, otherwise
7014 * NULL.
7015 */
7016 static char_u *
7017sgrn2c(
7018 char_u *head,
7019 int n)
7020{
7021 char_u *p = sgrn2(head, n);
7022
7023 return p && *p != NUL && (p = skipblank(p)) && *p == '\033' ? p : NULL;
7024}
7025
7026/*
7027 * If there is only a newline between the sequence immediately following it,
7028 * a pointer to the character following the newline is returned.
7029 * Otherwise NULL.
7030 */
7031 static char_u *
7032sgrn2cn(
7033 char_u *head,
7034 int n)
7035{
7036 char_u *p = sgrn2(head, n);
7037
7038 return p && p[0] == 0x0a && p[1] == '\033' ? ++p : NULL;
7039}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007040
7041/*
7042 * mch_write(): write the output buffer to the screen, translating ESC
7043 * sequences into calls to console output routines.
7044 */
7045 void
7046mch_write(
7047 char_u *s,
7048 int len)
7049{
Bram Moolenaard23f8bd2021-04-21 11:30:48 +02007050 char_u *end = s + len;
7051
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007052# ifdef VIMDLL
7053 if (gui.in_use)
7054 return;
7055# endif
7056
Bram Moolenaar071d4272004-06-13 20:20:40 +00007057 if (!term_console)
7058 {
7059 write(1, s, (unsigned)len);
7060 return;
7061 }
7062
Bram Moolenaar0f873732019-12-05 20:28:46 +01007063 // translate ESC | sequences into faked bios calls
Bram Moolenaar071d4272004-06-13 20:20:40 +00007064 while (len--)
7065 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007066 int prefix = -1;
7067 char_u ch;
7068
7069 // While processing a sequence, on rare occasions it seems that another
7070 // sequence may be inserted asynchronously.
7071 if (len < 0)
7072 {
Bram Moolenaara4d158b2022-08-14 14:17:45 +01007073 redraw_all_later(UPD_CLEAR);
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007074 return;
7075 }
7076
Bram Moolenaard23f8bd2021-04-21 11:30:48 +02007077 while (s + ++prefix < end)
7078 {
7079 ch = s[prefix];
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007080 if (ch <= 0x1e && !(ch != '\n' && ch != '\r' && ch != '\b'
7081 && ch != '\a' && ch != '\033'))
7082 break;
Bram Moolenaard23f8bd2021-04-21 11:30:48 +02007083 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007084
7085 if (p_wd)
7086 {
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02007087 WaitForChar(p_wd, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007088 if (prefix != 0)
7089 prefix = 1;
7090 }
7091
7092 if (prefix != 0)
7093 {
7094 DWORD nWritten;
7095
7096 nWritten = write_chars(s, prefix);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007097# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00007098 if (fdDump)
7099 {
7100 fputc('>', fdDump);
7101 fwrite(s, sizeof(char_u), nWritten, fdDump);
7102 fputs("<\n", fdDump);
7103 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007104# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007105 len -= (nWritten - 1);
7106 s += nWritten;
7107 }
7108 else if (s[0] == '\n')
7109 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007110 // \n, newline: go to the beginning of the next line or scroll
Bram Moolenaar071d4272004-06-13 20:20:40 +00007111 if (g_coord.Y == g_srScrollRegion.Bottom)
7112 {
7113 scroll(1);
7114 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Bottom + 1);
7115 }
7116 else
7117 {
7118 gotoxy(g_srScrollRegion.Left + 1, g_coord.Y + 2);
7119 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007120# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00007121 if (fdDump)
7122 fputs("\\n\n", fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007123# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007124 s++;
7125 }
7126 else if (s[0] == '\r')
7127 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007128 // \r, carriage return: go to beginning of line
Bram Moolenaar071d4272004-06-13 20:20:40 +00007129 gotoxy(g_srScrollRegion.Left+1, g_coord.Y + 1);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007130# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00007131 if (fdDump)
7132 fputs("\\r\n", fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007133# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007134 s++;
7135 }
7136 else if (s[0] == '\b')
7137 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007138 // \b, backspace: move cursor one position left
Bram Moolenaar071d4272004-06-13 20:20:40 +00007139 if (g_coord.X > g_srScrollRegion.Left)
7140 g_coord.X--;
7141 else if (g_coord.Y > g_srScrollRegion.Top)
7142 {
7143 g_coord.X = g_srScrollRegion.Right;
7144 g_coord.Y--;
7145 }
7146 gotoxy(g_coord.X + 1, g_coord.Y + 1);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007147# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00007148 if (fdDump)
7149 fputs("\\b\n", fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007150# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007151 s++;
7152 }
7153 else if (s[0] == '\a')
7154 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007155 // \a, bell
Bram Moolenaar071d4272004-06-13 20:20:40 +00007156 MessageBeep(0xFFFFFFFF);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007157# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00007158 if (fdDump)
7159 fputs("\\a\n", fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007160# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007161 s++;
7162 }
7163 else if (s[0] == ESC && len >= 3-1 && s[1] == '|')
7164 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007165# ifdef MCH_WRITE_DUMP
Bram Moolenaarc0197e22004-09-13 20:26:32 +00007166 char_u *old_s = s;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007167# endif
Bram Moolenaarc0197e22004-09-13 20:26:32 +00007168 char_u *p;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007169 int arg1 = 0, arg2 = 0, argc = 0, args[16];
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007170 char_u *sp;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007171
7172 switch (s[2])
7173 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00007174 case '0': case '1': case '2': case '3': case '4':
7175 case '5': case '6': case '7': case '8': case '9':
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007176 if (*(p = get_seq(args, &argc, s)) != 'm')
7177 goto notsgr;
7178
7179 p = s;
7180
7181 // Handling frequent optional sequences. Output to the screen
7182 // takes too long, so do not output as much as possible.
7183
7184 // If resetFG,FG,BG,<cr>,BG,FG are connected, the preceding
7185 // resetFG,FG,BG are omitted.
7186 if (sgrn2(sgrn2(sgrn2cn(sgrn2(sgrnc(p, 39), 38), 48), 48), 38))
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007187 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007188 p = sgrn2(sgrn2(sgrnc(p, 39), 38), 48);
7189 len = len + 1 - (int)(p - s);
7190 s = p;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007191 break;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007192 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007193
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007194 // If FG,BG,BG,FG of SGR are connected, the first FG can be
7195 // omitted.
7196 if (sgrn2(sgrn2(sgrn2c((sp = sgrn2(p, 38)), 48), 48), 38))
7197 p = sp;
7198
7199 // If FG,BG,FG,BG of SGR are connected, the first FG can be
7200 // omitted.
7201 if (sgrn2(sgrn2(sgrn2c((sp = sgrn2(p, 38)), 48), 38), 48))
7202 p = sp;
7203
7204 // If BG,BG of SGR are connected, the first BG can be omitted.
7205 if (sgrn2((sp = sgrn2(p, 48)), 48))
7206 p = sp;
7207
7208 // If restoreFG and FG are connected, the restoreFG can be
Bram Moolenaar9f1983d2022-05-12 20:35:35 +01007209 // omitted.
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007210 if (sgrn2((sp = sgrnc(p, 39)), 38))
7211 p = sp;
7212
7213 p = get_seq(args, &argc, p);
7214
7215notsgr:
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007216 arg1 = args[0];
7217 arg2 = args[1];
7218 if (*p == 'm')
Bram Moolenaar071d4272004-06-13 20:20:40 +00007219 {
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007220 if (argc == 1 && args[0] == 0)
7221 normvideo();
7222 else if (argc == 1)
7223 {
Christopher Plewright38804d62022-11-09 23:55:52 +00007224 if (vtp_working
7225# ifdef FEAT_TERMGUICOLORS
7226 && (p_tgc || t_colors >= 256)
7227# endif
7228 )
7229 textcolor((WORD)arg1);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007230 else
Christopher Plewright38804d62022-11-09 23:55:52 +00007231 textattr((WORD)arg1);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007232 }
Christopher Plewright38804d62022-11-09 23:55:52 +00007233 else if (vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007234 vtp_sgr_bulks(argc, args);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007235 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007236 else if (argc == 2 && *p == 'H')
Bram Moolenaar071d4272004-06-13 20:20:40 +00007237 {
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007238 gotoxy(arg2, arg1);
7239 }
7240 else if (argc == 2 && *p == 'r')
7241 {
7242 set_scroll_region(0, arg1 - 1, Columns - 1, arg2 - 1);
7243 }
Bram Moolenaar6982f422019-02-16 16:48:01 +01007244 else if (argc == 2 && *p == 'R')
7245 {
7246 set_scroll_region_tb(arg1, arg2);
7247 }
7248 else if (argc == 2 && *p == 'V')
7249 {
7250 set_scroll_region_lr(arg1, arg2);
7251 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007252 else if (argc == 1 && *p == 'A')
7253 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00007254 gotoxy(g_coord.X + 1,
7255 max(g_srScrollRegion.Top, g_coord.Y - arg1) + 1);
7256 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007257 else if (argc == 1 && *p == 'b')
Bram Moolenaar071d4272004-06-13 20:20:40 +00007258 {
7259 textbackground((WORD) arg1);
7260 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007261 else if (argc == 1 && *p == 'C')
7262 {
7263 gotoxy(min(g_srScrollRegion.Right, g_coord.X + arg1) + 1,
7264 g_coord.Y + 1);
7265 }
7266 else if (argc == 1 && *p == 'f')
7267 {
7268 textcolor((WORD) arg1);
7269 }
7270 else if (argc == 1 && *p == 'H')
7271 {
7272 gotoxy(1, arg1);
7273 }
7274 else if (argc == 1 && *p == 'L')
7275 {
7276 insert_lines(arg1);
7277 }
7278 else if (argc == 1 && *p == 'M')
Bram Moolenaar071d4272004-06-13 20:20:40 +00007279 {
7280 delete_lines(arg1);
7281 }
7282
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007283 len -= (int)(p - s);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007284 s = p + 1;
7285 break;
7286
Bram Moolenaar071d4272004-06-13 20:20:40 +00007287 case 'A':
Bram Moolenaar071d4272004-06-13 20:20:40 +00007288 gotoxy(g_coord.X + 1,
7289 max(g_srScrollRegion.Top, g_coord.Y - 1) + 1);
7290 goto got3;
7291
7292 case 'B':
7293 visual_bell();
7294 goto got3;
7295
7296 case 'C':
Bram Moolenaar071d4272004-06-13 20:20:40 +00007297 gotoxy(min(g_srScrollRegion.Right, g_coord.X + 1) + 1,
7298 g_coord.Y + 1);
7299 goto got3;
7300
7301 case 'E':
7302 termcap_mode_end();
7303 goto got3;
7304
7305 case 'F':
7306 standout();
7307 goto got3;
7308
7309 case 'f':
7310 standend();
7311 goto got3;
7312
7313 case 'H':
7314 gotoxy(1, 1);
7315 goto got3;
7316
7317 case 'j':
7318 clear_to_end_of_display();
7319 goto got3;
7320
7321 case 'J':
7322 clear_screen();
7323 goto got3;
7324
7325 case 'K':
7326 clear_to_end_of_line();
7327 goto got3;
7328
7329 case 'L':
7330 insert_lines(1);
7331 goto got3;
7332
7333 case 'M':
7334 delete_lines(1);
7335 goto got3;
7336
7337 case 'S':
7338 termcap_mode_start();
7339 goto got3;
7340
7341 case 'V':
7342 cursor_visible(TRUE);
7343 goto got3;
7344
7345 case 'v':
7346 cursor_visible(FALSE);
7347 goto got3;
7348
7349 got3:
7350 s += 3;
7351 len -= 2;
7352 }
7353
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007354# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00007355 if (fdDump)
7356 {
7357 fputs("ESC | ", fdDump);
7358 fwrite(old_s + 2, sizeof(char_u), s - old_s - 2, fdDump);
7359 fputc('\n', fdDump);
7360 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007361# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007362 }
K.Takatadf5320c2022-09-01 13:20:16 +01007363 else if (s[0] == ESC && len >= 3-1 && s[1] == '[')
7364 {
7365 int l = 2;
7366
7367 if (isdigit(s[l]))
7368 l++;
7369 if (s[l] == ' ' && s[l + 1] == 'q')
7370 {
7371 // DECSCUSR (cursor style) sequences
Christopher Plewright38804d62022-11-09 23:55:52 +00007372 if (vtp_working)
K.Takatadf5320c2022-09-01 13:20:16 +01007373 vtp_printf("%.*s", l + 2, s); // Pass through
7374 s += l + 2;
7375 len -= l + 1;
7376 }
7377 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007378 else
7379 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007380 // Write a single character
Bram Moolenaar071d4272004-06-13 20:20:40 +00007381 DWORD nWritten;
7382
7383 nWritten = write_chars(s, 1);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007384# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00007385 if (fdDump)
7386 {
7387 fputc('>', fdDump);
7388 fwrite(s, sizeof(char_u), nWritten, fdDump);
7389 fputs("<\n", fdDump);
7390 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007391# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007392
7393 len -= (nWritten - 1);
7394 s += nWritten;
7395 }
7396 }
7397
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007398# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00007399 if (fdDump)
7400 fflush(fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007401# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007402}
7403
Bram Moolenaar0f873732019-12-05 20:28:46 +01007404#endif // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00007405
7406
7407/*
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01007408 * Delay for "msec" milliseconds.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007409 */
7410 void
7411mch_delay(
7412 long msec,
Bram Moolenaar0981c872020-08-23 14:28:37 +02007413 int flags UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007414{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007415#if defined(FEAT_GUI_MSWIN) && !defined(VIMDLL)
Bram Moolenaar0f873732019-12-05 20:28:46 +01007416 Sleep((int)msec); // never wait for input
7417#else // Console
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007418# ifdef VIMDLL
7419 if (gui.in_use)
7420 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007421 Sleep((int)msec); // never wait for input
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007422 return;
7423 }
7424# endif
Bram Moolenaar0981c872020-08-23 14:28:37 +02007425 if (flags & MCH_DELAY_IGNOREINPUT)
Bram Moolenaar325b7a22004-07-05 15:58:32 +00007426# ifdef FEAT_MZSCHEME
7427 if (mzthreads_allowed() && p_mzq > 0 && msec > p_mzq)
7428 {
7429 int towait = p_mzq;
7430
Bram Moolenaar0f873732019-12-05 20:28:46 +01007431 // if msec is large enough, wait by portions in p_mzq
Bram Moolenaar325b7a22004-07-05 15:58:32 +00007432 while (msec > 0)
7433 {
7434 mzvim_check_threads();
7435 if (msec < towait)
7436 towait = msec;
7437 Sleep(towait);
7438 msec -= towait;
7439 }
7440 }
7441 else
7442# endif
7443 Sleep((int)msec);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007444 else
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02007445 WaitForChar(msec, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007446#endif
7447}
7448
7449
7450/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01007451 * This version of remove is not scared by a readonly (backup) file.
7452 * This can also remove a symbolic link like Unix.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007453 * Return 0 for success, -1 for failure.
7454 */
7455 int
7456mch_remove(char_u *name)
7457{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007458 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007459 int n;
7460
Bram Moolenaar203258c2016-01-17 22:15:16 +01007461 /*
7462 * On Windows, deleting a directory's symbolic link is done by
7463 * RemoveDirectory(): mch_rmdir. It seems unnatural, but it is fact.
7464 */
7465 if (mch_isdir(name) && mch_is_symbolic_link(name))
7466 return mch_rmdir(name);
7467
Bram Moolenaar12b559e2013-06-12 22:41:37 +02007468 win32_setattrs(name, FILE_ATTRIBUTE_NORMAL);
7469
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007470 wn = enc_to_utf16(name, NULL);
7471 if (wn == NULL)
7472 return -1;
7473
7474 n = DeleteFileW(wn) ? 0 : -1;
7475 vim_free(wn);
7476 return n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007477}
7478
7479
7480/*
Bram Moolenaarb9c31e72016-09-29 15:18:57 +02007481 * Check for an "interrupt signal": CTRL-break or CTRL-C.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007482 */
7483 void
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02007484mch_breakcheck(int force UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007485{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007486#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
7487# ifdef VIMDLL
7488 if (!gui.in_use)
7489# endif
7490 if (g_fCtrlCPressed || g_fCBrkPressed)
7491 {
7492 ctrl_break_was_pressed = g_fCBrkPressed;
7493 g_fCtrlCPressed = g_fCBrkPressed = FALSE;
7494 got_int = TRUE;
7495 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007496#endif
7497}
7498
Bram Moolenaar0f873732019-12-05 20:28:46 +01007499// physical RAM to leave for the OS
Bram Moolenaaree273972016-01-02 21:11:51 +01007500#define WINNT_RESERVE_BYTES (256*1024*1024)
Bram Moolenaaree273972016-01-02 21:11:51 +01007501
7502/*
7503 * How much main memory in KiB that can be used by VIM.
7504 */
Bram Moolenaaree273972016-01-02 21:11:51 +01007505 long_u
Bram Moolenaar1266d672017-02-01 13:43:36 +01007506mch_total_mem(int special UNUSED)
Bram Moolenaaree273972016-01-02 21:11:51 +01007507{
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007508 MEMORYSTATUSEX ms;
7509
Bram Moolenaar0f873732019-12-05 20:28:46 +01007510 // Need to use GlobalMemoryStatusEx() when there is more memory than
7511 // what fits in 32 bits.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007512 ms.dwLength = sizeof(MEMORYSTATUSEX);
7513 GlobalMemoryStatusEx(&ms);
7514 if (ms.ullAvailVirtual < ms.ullTotalPhys)
Bram Moolenaaree273972016-01-02 21:11:51 +01007515 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007516 // Process address space fits in physical RAM, use all of it.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007517 return (long_u)(ms.ullAvailVirtual / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01007518 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007519 if (ms.ullTotalPhys <= WINNT_RESERVE_BYTES)
Bram Moolenaaree273972016-01-02 21:11:51 +01007520 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007521 // Catch old NT box or perverse hardware setup.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007522 return (long_u)((ms.ullTotalPhys / 2) / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01007523 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01007524 // Use physical RAM less reserve for OS + data.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007525 return (long_u)((ms.ullTotalPhys - WINNT_RESERVE_BYTES) / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01007526}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007527
Bram Moolenaar071d4272004-06-13 20:20:40 +00007528/*
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007529 * mch_wrename() works around a bug in rename (aka MoveFile) in
Bram Moolenaar071d4272004-06-13 20:20:40 +00007530 * Windows 95: rename("foo.bar", "foo.bar~") will generate a
7531 * file whose short file name is "FOO.BAR" (its long file name will
7532 * be correct: "foo.bar~"). Because a file can be accessed by
7533 * either its SFN or its LFN, "foo.bar" has effectively been
7534 * renamed to "foo.bar", which is not at all what was wanted. This
7535 * seems to happen only when renaming files with three-character
7536 * extensions by appending a suffix that does not include ".".
7537 * Windows NT gets it right, however, with an SFN of "FOO~1.BAR".
7538 *
7539 * There is another problem, which isn't really a bug but isn't right either:
7540 * When renaming "abcdef~1.txt" to "abcdef~1.txt~", the short name can be
7541 * "abcdef~1.txt" again. This has been reported on Windows NT 4.0 with
7542 * service pack 6. Doesn't seem to happen on Windows 98.
7543 *
7544 * Like rename(), returns 0 upon success, non-zero upon failure.
7545 * Should probably set errno appropriately when errors occur.
7546 */
7547 int
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007548mch_wrename(WCHAR *wold, WCHAR *wnew)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007549{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007550 WCHAR *p;
7551 int i;
7552 WCHAR szTempFile[_MAX_PATH + 1];
7553 WCHAR szNewPath[_MAX_PATH + 1];
Bram Moolenaar071d4272004-06-13 20:20:40 +00007554 HANDLE hf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007555
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007556 // No need to play tricks unless the file name contains a "~" as the
7557 // seventh character.
7558 p = wold;
7559 for (i = 0; wold[i] != NUL; ++i)
7560 if ((wold[i] == '/' || wold[i] == '\\' || wold[i] == ':')
7561 && wold[i + 1] != 0)
7562 p = wold + i + 1;
7563 if ((int)(wold + i - p) < 8 || p[6] != '~')
7564 return (MoveFileW(wold, wnew) == 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007565
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007566 // Get base path of new file name. Undocumented feature: If pszNewFile is
7567 // a directory, no error is returned and pszFilePart will be NULL.
7568 if (GetFullPathNameW(wnew, _MAX_PATH, szNewPath, &p) == 0 || p == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007569 return -1;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007570 *p = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007571
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007572 // Get (and create) a unique temporary file name in directory of new file
7573 if (GetTempFileNameW(szNewPath, L"VIM", 0, szTempFile) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007574 return -2;
7575
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007576 // blow the temp file away
7577 if (!DeleteFileW(szTempFile))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007578 return -3;
7579
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007580 // rename old file to the temp file
7581 if (!MoveFileW(wold, szTempFile))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007582 return -4;
7583
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007584 // now create an empty file called pszOldFile; this prevents the operating
7585 // system using pszOldFile as an alias (SFN) if we're renaming within the
7586 // same directory. For example, we're editing a file called
7587 // filename.asc.txt by its SFN, filena~1.txt. If we rename filena~1.txt
7588 // to filena~1.txt~ (i.e., we're making a backup while writing it), the
7589 // SFN for filena~1.txt~ will be filena~1.txt, by default, which will
7590 // cause all sorts of problems later in buf_write(). So, we create an
7591 // empty file called filena~1.txt and the system will have to find some
7592 // other SFN for filena~1.txt~, such as filena~2.txt
7593 if ((hf = CreateFileW(wold, GENERIC_WRITE, 0, NULL, CREATE_NEW,
Bram Moolenaar071d4272004-06-13 20:20:40 +00007594 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
7595 return -5;
7596 if (!CloseHandle(hf))
7597 return -6;
7598
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007599 // rename the temp file to the new file
7600 if (!MoveFileW(szTempFile, wnew))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007601 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007602 // Renaming failed. Rename the file back to its old name, so that it
7603 // looks like nothing happened.
7604 (void)MoveFileW(szTempFile, wold);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007605 return -7;
7606 }
7607
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007608 // Seems to be left around on Novell filesystems
7609 DeleteFileW(szTempFile);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007610
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007611 // finally, remove the empty old file
7612 if (!DeleteFileW(wold))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007613 return -8;
7614
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007615 return 0;
7616}
7617
7618
7619/*
7620 * Converts the filenames to UTF-16, then call mch_wrename().
7621 * Like rename(), returns 0 upon success, non-zero upon failure.
7622 */
7623 int
7624mch_rename(
7625 const char *pszOldFile,
7626 const char *pszNewFile)
7627{
7628 WCHAR *wold = NULL;
7629 WCHAR *wnew = NULL;
7630 int retval = -1;
7631
7632 wold = enc_to_utf16((char_u *)pszOldFile, NULL);
7633 wnew = enc_to_utf16((char_u *)pszNewFile, NULL);
7634 if (wold != NULL && wnew != NULL)
7635 retval = mch_wrename(wold, wnew);
7636 vim_free(wold);
7637 vim_free(wnew);
7638 return retval;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007639}
7640
7641/*
7642 * Get the default shell for the current hardware platform
7643 */
7644 char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007645default_shell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007646{
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007647 return "cmd.exe";
Bram Moolenaar071d4272004-06-13 20:20:40 +00007648}
7649
7650/*
7651 * mch_access() extends access() to do more detailed check on network drives.
7652 * Returns 0 if file "n" has access rights according to "p", -1 otherwise.
7653 */
7654 int
7655mch_access(char *n, int p)
7656{
7657 HANDLE hFile;
Bram Moolenaar0f873732019-12-05 20:28:46 +01007658 int retval = -1; // default: fail
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007659 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007660
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007661 wn = enc_to_utf16((char_u *)n, NULL);
7662 if (wn == NULL)
7663 return -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007664
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01007665 if (mch_isdir((char_u *)n))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007666 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00007667 WCHAR TempNameW[_MAX_PATH + 16] = L"";
Bram Moolenaar071d4272004-06-13 20:20:40 +00007668
7669 if (p & R_OK)
7670 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007671 // Read check is performed by seeing if we can do a find file on
7672 // the directory for any file.
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007673 int i;
7674 WIN32_FIND_DATAW d;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007675
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007676 for (i = 0; i < _MAX_PATH && wn[i] != 0; ++i)
7677 TempNameW[i] = wn[i];
7678 if (TempNameW[i - 1] != '\\' && TempNameW[i - 1] != '/')
7679 TempNameW[i++] = '\\';
7680 TempNameW[i++] = '*';
7681 TempNameW[i++] = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007682
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007683 hFile = FindFirstFileW(TempNameW, &d);
7684 if (hFile == INVALID_HANDLE_VALUE)
7685 goto getout;
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007686 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00007687 (void)FindClose(hFile);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007688 }
7689
7690 if (p & W_OK)
7691 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007692 // Trying to create a temporary file in the directory should catch
7693 // directories on read-only network shares. However, in
7694 // directories whose ACL allows writes but denies deletes will end
7695 // up keeping the temporary file :-(.
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007696 if (!GetTempFileNameW(wn, L"VIM", 0, TempNameW))
7697 goto getout;
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007698 else
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007699 DeleteFileW(TempNameW);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007700 }
7701 }
7702 else
7703 {
Bram Moolenaar5aa98962018-05-06 17:09:38 +02007704 // Don't consider a file read-only if another process has opened it.
7705 DWORD share_mode = FILE_SHARE_READ | FILE_SHARE_WRITE;
7706
Bram Moolenaar0f873732019-12-05 20:28:46 +01007707 // Trying to open the file for the required access does ACL, read-only
7708 // network share, and file attribute checks.
Bram Moolenaar5aa98962018-05-06 17:09:38 +02007709 DWORD access_mode = ((p & W_OK) ? GENERIC_WRITE : 0)
7710 | ((p & R_OK) ? GENERIC_READ : 0);
7711
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007712 hFile = CreateFileW(wn, access_mode, share_mode,
7713 NULL, OPEN_EXISTING, 0, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007714 if (hFile == INVALID_HANDLE_VALUE)
7715 goto getout;
7716 CloseHandle(hFile);
7717 }
7718
Bram Moolenaar0f873732019-12-05 20:28:46 +01007719 retval = 0; // success
Bram Moolenaar071d4272004-06-13 20:20:40 +00007720getout:
Bram Moolenaar071d4272004-06-13 20:20:40 +00007721 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007722 return retval;
7723}
7724
Bram Moolenaar071d4272004-06-13 20:20:40 +00007725/*
Bram Moolenaar36f692d2008-11-20 16:10:17 +00007726 * Version of open() that may use UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007727 */
7728 int
Bram Moolenaarb6843a02017-08-02 22:07:12 +02007729mch_open(const char *name, int flags, int mode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007730{
7731 WCHAR *wn;
7732 int f;
7733
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007734 wn = enc_to_utf16((char_u *)name, NULL);
7735 if (wn == NULL)
7736 return -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007737
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007738 f = _wopen(wn, flags, mode);
7739 vim_free(wn);
7740 return f;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007741}
7742
7743/*
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007744 * Version of fopen() that uses UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007745 */
7746 FILE *
Bram Moolenaarb6843a02017-08-02 22:07:12 +02007747mch_fopen(const char *name, const char *mode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007748{
7749 WCHAR *wn, *wm;
7750 FILE *f = NULL;
7751
Bram Moolenaara12a1612019-01-24 16:39:02 +01007752#if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0f873732019-12-05 20:28:46 +01007753 // Work around an annoying assertion in the Microsoft debug CRT
7754 // when mode's text/binary setting doesn't match _get_fmode().
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007755 char newMode = mode[strlen(mode) - 1];
7756 int oldMode = 0;
Bram Moolenaar0fde2902008-03-16 13:54:13 +00007757
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007758 _get_fmode(&oldMode);
7759 if (newMode == 't')
7760 _set_fmode(_O_TEXT);
7761 else if (newMode == 'b')
7762 _set_fmode(_O_BINARY);
Bram Moolenaara12a1612019-01-24 16:39:02 +01007763#endif
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007764 wn = enc_to_utf16((char_u *)name, NULL);
7765 wm = enc_to_utf16((char_u *)mode, NULL);
7766 if (wn != NULL && wm != NULL)
7767 f = _wfopen(wn, wm);
7768 vim_free(wn);
7769 vim_free(wm);
Bram Moolenaar0fde2902008-03-16 13:54:13 +00007770
Bram Moolenaara12a1612019-01-24 16:39:02 +01007771#if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007772 _set_fmode(oldMode);
Bram Moolenaara12a1612019-01-24 16:39:02 +01007773#endif
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007774 return f;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007775}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007776
Bram Moolenaar071d4272004-06-13 20:20:40 +00007777/*
7778 * SUB STREAM (aka info stream) handling:
7779 *
Bram Moolenaar8e7d6222020-12-18 19:49:56 +01007780 * NTFS can have sub streams for each file. The normal contents of a file is
7781 * stored in the main stream, and extra contents (author information, title and
7782 * so on) can be stored in a sub stream. After Windows 2000, the user can
7783 * access and store this information in sub streams via an explorer's property
7784 * menu item in the right click menu. This information in sub streams was lost
7785 * when copying only the main stream. Therefore we have to copy sub streams.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007786 *
7787 * Incomplete explanation:
7788 * http://msdn.microsoft.com/library/en-us/dnw2k/html/ntfs5.asp
7789 * More useful info and an example:
7790 * http://www.sysinternals.com/ntw2k/source/misc.shtml#streams
7791 */
7792
7793/*
7794 * Copy info stream data "substream". Read from the file with BackupRead(sh)
7795 * and write to stream "substream" of file "to".
7796 * Errors are ignored.
7797 */
7798 static void
7799copy_substream(HANDLE sh, void *context, WCHAR *to, WCHAR *substream, long len)
7800{
7801 HANDLE hTo;
7802 WCHAR *to_name;
7803
7804 to_name = malloc((wcslen(to) + wcslen(substream) + 1) * sizeof(WCHAR));
7805 wcscpy(to_name, to);
7806 wcscat(to_name, substream);
7807
7808 hTo = CreateFileW(to_name, GENERIC_WRITE, 0, NULL, OPEN_ALWAYS,
7809 FILE_ATTRIBUTE_NORMAL, NULL);
7810 if (hTo != INVALID_HANDLE_VALUE)
7811 {
7812 long done;
7813 DWORD todo;
7814 DWORD readcnt, written;
7815 char buf[4096];
7816
Bram Moolenaar0f873732019-12-05 20:28:46 +01007817 // Copy block of bytes at a time. Abort when something goes wrong.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007818 for (done = 0; done < len; done += written)
7819 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007820 // (size_t) cast for Borland C 5.5
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007821 todo = (DWORD)((size_t)(len - done) > sizeof(buf) ? sizeof(buf)
7822 : (size_t)(len - done));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007823 if (!BackupRead(sh, (LPBYTE)buf, todo, &readcnt,
7824 FALSE, FALSE, context)
7825 || readcnt != todo
7826 || !WriteFile(hTo, buf, todo, &written, NULL)
7827 || written != todo)
7828 break;
7829 }
7830 CloseHandle(hTo);
7831 }
7832
7833 free(to_name);
7834}
7835
7836/*
7837 * Copy info streams from file "from" to file "to".
7838 */
7839 static void
7840copy_infostreams(char_u *from, char_u *to)
7841{
7842 WCHAR *fromw;
7843 WCHAR *tow;
7844 HANDLE sh;
7845 WIN32_STREAM_ID sid;
7846 int headersize;
7847 WCHAR streamname[_MAX_PATH];
7848 DWORD readcount;
7849 void *context = NULL;
7850 DWORD lo, hi;
7851 int len;
7852
Bram Moolenaar0f873732019-12-05 20:28:46 +01007853 // Convert the file names to wide characters.
Bram Moolenaar36f692d2008-11-20 16:10:17 +00007854 fromw = enc_to_utf16(from, NULL);
7855 tow = enc_to_utf16(to, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007856 if (fromw != NULL && tow != NULL)
7857 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007858 // Open the file for reading.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007859 sh = CreateFileW(fromw, GENERIC_READ, FILE_SHARE_READ, NULL,
7860 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
7861 if (sh != INVALID_HANDLE_VALUE)
7862 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007863 // Use BackupRead() to find the info streams. Repeat until we
7864 // have done them all.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007865 for (;;)
7866 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007867 // Get the header to find the length of the stream name. If
7868 // the "readcount" is zero we have done all info streams.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007869 ZeroMemory(&sid, sizeof(WIN32_STREAM_ID));
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007870 headersize = (int)((char *)&sid.cStreamName - (char *)&sid.dwStreamId);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007871 if (!BackupRead(sh, (LPBYTE)&sid, headersize,
7872 &readcount, FALSE, FALSE, &context)
7873 || readcount == 0)
7874 break;
7875
Bram Moolenaar0f873732019-12-05 20:28:46 +01007876 // We only deal with streams that have a name. The normal
7877 // file data appears to be without a name, even though docs
7878 // suggest it is called "::$DATA".
Bram Moolenaar071d4272004-06-13 20:20:40 +00007879 if (sid.dwStreamNameSize > 0)
7880 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007881 // Read the stream name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007882 if (!BackupRead(sh, (LPBYTE)streamname,
7883 sid.dwStreamNameSize,
7884 &readcount, FALSE, FALSE, &context))
7885 break;
7886
Bram Moolenaar0f873732019-12-05 20:28:46 +01007887 // Copy an info stream with a name ":anything:$DATA".
7888 // Skip "::$DATA", it has no stream name (examples suggest
7889 // it might be used for the normal file contents).
7890 // Note that BackupRead() counts bytes, but the name is in
7891 // wide characters.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007892 len = readcount / sizeof(WCHAR);
7893 streamname[len] = 0;
7894 if (len > 7 && wcsicmp(streamname + len - 6,
7895 L":$DATA") == 0)
7896 {
7897 streamname[len - 6] = 0;
7898 copy_substream(sh, &context, tow, streamname,
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00007899 (long)sid.Size.u.LowPart);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007900 }
7901 }
7902
Bram Moolenaar0f873732019-12-05 20:28:46 +01007903 // Advance to the next stream. We might try seeking too far,
7904 // but BackupSeek() doesn't skip over stream borders, thus
7905 // that's OK.
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00007906 (void)BackupSeek(sh, sid.Size.u.LowPart, sid.Size.u.HighPart,
Bram Moolenaar071d4272004-06-13 20:20:40 +00007907 &lo, &hi, &context);
7908 }
7909
Bram Moolenaar0f873732019-12-05 20:28:46 +01007910 // Clear the context.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007911 (void)BackupRead(sh, NULL, 0, &readcount, TRUE, FALSE, &context);
7912
7913 CloseHandle(sh);
7914 }
7915 }
7916 vim_free(fromw);
7917 vim_free(tow);
7918}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007919
7920/*
Bram Moolenaare7bebc42021-02-01 20:50:37 +01007921 * ntdll.dll definitions
7922 */
7923#define FileEaInformation 7
7924#ifndef STATUS_SUCCESS
7925# define STATUS_SUCCESS ((NTSTATUS) 0x00000000L)
7926#endif
7927
7928typedef struct _FILE_FULL_EA_INFORMATION_ {
7929 ULONG NextEntryOffset;
7930 UCHAR Flags;
7931 UCHAR EaNameLength;
7932 USHORT EaValueLength;
7933 CHAR EaName[1];
7934} FILE_FULL_EA_INFORMATION_, *PFILE_FULL_EA_INFORMATION_;
7935
7936typedef struct _FILE_EA_INFORMATION_ {
7937 ULONG EaSize;
7938} FILE_EA_INFORMATION_, *PFILE_EA_INFORMATION_;
7939
Paul Ollis65745772022-06-05 16:55:54 +01007940#ifndef PROTO
Bram Moolenaare7bebc42021-02-01 20:50:37 +01007941typedef NTSTATUS (NTAPI *PfnNtOpenFile)(
7942 PHANDLE FileHandle,
7943 ACCESS_MASK DesiredAccess,
7944 POBJECT_ATTRIBUTES ObjectAttributes,
7945 PIO_STATUS_BLOCK IoStatusBlock,
7946 ULONG ShareAccess,
7947 ULONG OpenOptions);
7948typedef NTSTATUS (NTAPI *PfnNtClose)(
7949 HANDLE Handle);
7950typedef NTSTATUS (NTAPI *PfnNtSetEaFile)(
Bram Moolenaar9f1983d2022-05-12 20:35:35 +01007951 HANDLE FileHandle,
7952 PIO_STATUS_BLOCK IoStatusBlock,
7953 PVOID Buffer,
7954 ULONG Length);
Bram Moolenaare7bebc42021-02-01 20:50:37 +01007955typedef NTSTATUS (NTAPI *PfnNtQueryEaFile)(
7956 HANDLE FileHandle,
7957 PIO_STATUS_BLOCK IoStatusBlock,
7958 PVOID Buffer,
7959 ULONG Length,
7960 BOOLEAN ReturnSingleEntry,
7961 PVOID EaList,
7962 ULONG EaListLength,
7963 PULONG EaIndex,
7964 BOOLEAN RestartScan);
7965typedef NTSTATUS (NTAPI *PfnNtQueryInformationFile)(
Bram Moolenaar9f1983d2022-05-12 20:35:35 +01007966 HANDLE FileHandle,
7967 PIO_STATUS_BLOCK IoStatusBlock,
7968 PVOID FileInformation,
7969 ULONG Length,
Bram Moolenaare7bebc42021-02-01 20:50:37 +01007970 FILE_INFORMATION_CLASS FileInformationClass);
7971typedef VOID (NTAPI *PfnRtlInitUnicodeString)(
7972 PUNICODE_STRING DestinationString,
7973 PCWSTR SourceString);
7974
7975PfnNtOpenFile pNtOpenFile = NULL;
7976PfnNtClose pNtClose = NULL;
7977PfnNtSetEaFile pNtSetEaFile = NULL;
7978PfnNtQueryEaFile pNtQueryEaFile = NULL;
7979PfnNtQueryInformationFile pNtQueryInformationFile = NULL;
7980PfnRtlInitUnicodeString pRtlInitUnicodeString = NULL;
Paul Ollis65745772022-06-05 16:55:54 +01007981#endif
Bram Moolenaare7bebc42021-02-01 20:50:37 +01007982
7983/*
7984 * Load ntdll.dll functions.
7985 */
7986 static BOOL
7987load_ntdll(void)
7988{
7989 static int loaded = -1;
7990
7991 if (loaded == -1)
7992 {
7993 HMODULE hNtdll = GetModuleHandle("ntdll.dll");
7994 if (hNtdll != NULL)
7995 {
7996 pNtOpenFile = (PfnNtOpenFile) GetProcAddress(hNtdll, "NtOpenFile");
7997 pNtClose = (PfnNtClose) GetProcAddress(hNtdll, "NtClose");
7998 pNtSetEaFile = (PfnNtSetEaFile)
7999 GetProcAddress(hNtdll, "NtSetEaFile");
8000 pNtQueryEaFile = (PfnNtQueryEaFile)
8001 GetProcAddress(hNtdll, "NtQueryEaFile");
8002 pNtQueryInformationFile = (PfnNtQueryInformationFile)
8003 GetProcAddress(hNtdll, "NtQueryInformationFile");
8004 pRtlInitUnicodeString = (PfnRtlInitUnicodeString)
8005 GetProcAddress(hNtdll, "RtlInitUnicodeString");
8006 }
8007 if (pNtOpenFile == NULL
8008 || pNtClose == NULL
8009 || pNtSetEaFile == NULL
8010 || pNtQueryEaFile == NULL
8011 || pNtQueryInformationFile == NULL
8012 || pRtlInitUnicodeString == NULL)
8013 loaded = FALSE;
8014 else
8015 loaded = TRUE;
8016 }
8017 return (BOOL) loaded;
8018}
8019
8020/*
8021 * Copy extended attributes (EA) from file "from" to file "to".
8022 */
8023 static void
8024copy_extattr(char_u *from, char_u *to)
8025{
8026 char_u *fromf = NULL;
8027 char_u *tof = NULL;
8028 WCHAR *fromw = NULL;
8029 WCHAR *tow = NULL;
8030 UNICODE_STRING u;
8031 HANDLE h;
8032 OBJECT_ATTRIBUTES oa;
8033 IO_STATUS_BLOCK iosb;
8034 FILE_EA_INFORMATION_ eainfo = {0};
8035 void *ea = NULL;
8036
8037 if (!load_ntdll())
8038 return;
8039
8040 // Convert the file names to the fully qualified object names.
8041 fromf = alloc(STRLEN(from) + 5);
8042 tof = alloc(STRLEN(to) + 5);
8043 if (fromf == NULL || tof == NULL)
8044 goto theend;
8045 STRCPY(fromf, "\\??\\");
8046 STRCAT(fromf, from);
8047 STRCPY(tof, "\\??\\");
8048 STRCAT(tof, to);
8049
8050 // Convert the names to wide characters.
8051 fromw = enc_to_utf16(fromf, NULL);
8052 tow = enc_to_utf16(tof, NULL);
8053 if (fromw == NULL || tow == NULL)
8054 goto theend;
8055
8056 // Get the EA.
8057 pRtlInitUnicodeString(&u, fromw);
8058 InitializeObjectAttributes(&oa, &u, 0, NULL, NULL);
8059 if (pNtOpenFile(&h, FILE_READ_EA, &oa, &iosb, 0,
8060 FILE_NON_DIRECTORY_FILE) != STATUS_SUCCESS)
8061 goto theend;
8062 pNtQueryInformationFile(h, &iosb, &eainfo, sizeof(eainfo),
8063 FileEaInformation);
8064 if (eainfo.EaSize != 0)
8065 {
8066 ea = alloc(eainfo.EaSize);
8067 if (ea != NULL)
8068 {
8069 if (pNtQueryEaFile(h, &iosb, ea, eainfo.EaSize, FALSE,
8070 NULL, 0, NULL, TRUE) != STATUS_SUCCESS)
8071 {
8072 vim_free(ea);
8073 ea = NULL;
8074 }
8075 }
8076 }
8077 pNtClose(h);
8078
8079 // Set the EA.
8080 if (ea != NULL)
8081 {
8082 pRtlInitUnicodeString(&u, tow);
8083 InitializeObjectAttributes(&oa, &u, 0, NULL, NULL);
8084 if (pNtOpenFile(&h, FILE_WRITE_EA, &oa, &iosb, 0,
8085 FILE_NON_DIRECTORY_FILE) != STATUS_SUCCESS)
8086 goto theend;
8087
8088 pNtSetEaFile(h, &iosb, ea, eainfo.EaSize);
8089 pNtClose(h);
8090 }
8091
8092theend:
8093 vim_free(fromf);
8094 vim_free(tof);
8095 vim_free(fromw);
8096 vim_free(tow);
8097 vim_free(ea);
8098}
8099
8100/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00008101 * Copy file attributes from file "from" to file "to".
8102 * For Windows NT and later we copy info streams.
8103 * Always returns zero, errors are ignored.
8104 */
8105 int
8106mch_copy_file_attribute(char_u *from, char_u *to)
8107{
Bram Moolenaar0f873732019-12-05 20:28:46 +01008108 // File streams only work on Windows NT and later.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02008109 copy_infostreams(from, to);
Bram Moolenaare7bebc42021-02-01 20:50:37 +01008110 copy_extattr(from, to);
Bram Moolenaar071d4272004-06-13 20:20:40 +00008111 return 0;
8112}
8113
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008114
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008115/*
K.Takatadc73b4b2021-06-08 18:32:36 +02008116 * The command line arguments in UTF-16
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008117 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00008118static int nArgsW = 0;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008119static LPWSTR *ArglistW = NULL;
8120static int global_argc = 0;
8121static char **global_argv;
8122
Bram Moolenaar0f873732019-12-05 20:28:46 +01008123static int used_file_argc = 0; // last argument in global_argv[] used
8124 // for the argument list.
8125static int *used_file_indexes = NULL; // indexes in global_argv[] for
8126 // command line arguments added to
8127 // the argument list
8128static int used_file_count = 0; // nr of entries in used_file_indexes
8129static int used_file_literal = FALSE; // take file names literally
8130static int used_file_full_path = FALSE; // file name was full path
8131static int used_file_diff_mode = FALSE; // file name was with diff mode
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008132static int used_alist_count = 0;
8133
8134
8135/*
8136 * Get the command line arguments. Unicode version.
8137 * Returns argc. Zero when something fails.
8138 */
8139 int
8140get_cmd_argsW(char ***argvp)
8141{
8142 char **argv = NULL;
8143 int argc = 0;
8144 int i;
8145
Bram Moolenaar14993322014-09-09 12:25:33 +02008146 free_cmd_argsW();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008147 ArglistW = CommandLineToArgvW(GetCommandLineW(), &nArgsW);
8148 if (ArglistW != NULL)
8149 {
8150 argv = malloc((nArgsW + 1) * sizeof(char *));
8151 if (argv != NULL)
8152 {
8153 argc = nArgsW;
8154 argv[argc] = NULL;
8155 for (i = 0; i < argc; ++i)
8156 {
8157 int len;
8158
K.Takatadc73b4b2021-06-08 18:32:36 +02008159 // Convert each Unicode argument to UTF-8.
8160 WideCharToMultiByte_alloc(CP_UTF8, 0,
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00008161 ArglistW[i], (int)wcslen(ArglistW[i]) + 1,
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008162 (LPSTR *)&argv[i], &len, 0, 0);
8163 if (argv[i] == NULL)
8164 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01008165 // Out of memory, clear everything.
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008166 while (i > 0)
8167 free(argv[--i]);
8168 free(argv);
Bram Moolenaar73c61632013-12-07 14:48:10 +01008169 argv = NULL;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008170 argc = 0;
8171 }
8172 }
8173 }
8174 }
8175
8176 global_argc = argc;
8177 global_argv = argv;
8178 if (argc > 0)
Bram Moolenaar14993322014-09-09 12:25:33 +02008179 {
8180 if (used_file_indexes != NULL)
8181 free(used_file_indexes);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008182 used_file_indexes = malloc(argc * sizeof(int));
Bram Moolenaar14993322014-09-09 12:25:33 +02008183 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008184
8185 if (argvp != NULL)
8186 *argvp = argv;
8187 return argc;
8188}
8189
8190 void
8191free_cmd_argsW(void)
8192{
8193 if (ArglistW != NULL)
8194 {
8195 GlobalFree(ArglistW);
8196 ArglistW = NULL;
8197 }
8198}
8199
8200/*
8201 * Remember "name" is an argument that was added to the argument list.
8202 * This avoids that we have to re-parse the argument list when fix_arg_enc()
8203 * is called.
8204 */
8205 void
Bram Moolenaar910f66f2006-04-05 20:41:53 +00008206used_file_arg(char *name, int literal, int full_path, int diff_mode)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008207{
8208 int i;
8209
8210 if (used_file_indexes == NULL)
8211 return;
8212 for (i = used_file_argc + 1; i < global_argc; ++i)
8213 if (STRCMP(global_argv[i], name) == 0)
8214 {
8215 used_file_argc = i;
8216 used_file_indexes[used_file_count++] = i;
8217 break;
8218 }
8219 used_file_literal = literal;
8220 used_file_full_path = full_path;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00008221 used_file_diff_mode = diff_mode;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008222}
8223
8224/*
8225 * Remember the length of the argument list as it was. If it changes then we
8226 * leave it alone when 'encoding' is set.
8227 */
8228 void
8229set_alist_count(void)
8230{
8231 used_alist_count = GARGCOUNT;
8232}
8233
8234/*
8235 * Fix the encoding of the command line arguments. Invoked when 'encoding'
K.Takatadc73b4b2021-06-08 18:32:36 +02008236 * has been changed while starting up. Use the UTF-16 command line arguments
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008237 * and convert them to 'encoding'.
8238 */
8239 void
8240fix_arg_enc(void)
8241{
8242 int i;
8243 int idx;
8244 char_u *str;
Bram Moolenaar86b68352004-12-27 21:59:20 +00008245 int *fnum_list;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008246
Bram Moolenaar0f873732019-12-05 20:28:46 +01008247 // Safety checks:
8248 // - if argument count differs between the wide and non-wide argument
8249 // list, something must be wrong.
8250 // - the file name arguments must have been located.
8251 // - the length of the argument list wasn't changed by the user.
Bram Moolenaard857f0e2005-06-21 22:37:39 +00008252 if (global_argc != nArgsW
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008253 || ArglistW == NULL
8254 || used_file_indexes == NULL
8255 || used_file_count == 0
8256 || used_alist_count != GARGCOUNT)
8257 return;
8258
Bram Moolenaar0f873732019-12-05 20:28:46 +01008259 // Remember the buffer numbers for the arguments.
Bram Moolenaarc799fe22019-05-28 23:08:19 +02008260 fnum_list = ALLOC_MULT(int, GARGCOUNT);
Bram Moolenaar86b68352004-12-27 21:59:20 +00008261 if (fnum_list == NULL)
Bram Moolenaar0f873732019-12-05 20:28:46 +01008262 return; // out of memory
Bram Moolenaar86b68352004-12-27 21:59:20 +00008263 for (i = 0; i < GARGCOUNT; ++i)
8264 fnum_list[i] = GARGLIST[i].ae_fnum;
8265
Bram Moolenaar0f873732019-12-05 20:28:46 +01008266 // Clear the argument list. Make room for the new arguments.
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008267 alist_clear(&global_alist);
8268 if (ga_grow(&global_alist.al_ga, used_file_count) == FAIL)
Bram Moolenaar0f873732019-12-05 20:28:46 +01008269 return; // out of memory
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008270
8271 for (i = 0; i < used_file_count; ++i)
8272 {
8273 idx = used_file_indexes[i];
Bram Moolenaar36f692d2008-11-20 16:10:17 +00008274 str = utf16_to_enc(ArglistW[idx], NULL);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008275 if (str != NULL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00008276 {
Bram Moolenaar39d21e32017-08-05 23:09:31 +02008277 int literal = used_file_literal;
8278
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01008279#ifdef FEAT_DIFF
Bram Moolenaar0f873732019-12-05 20:28:46 +01008280 // When using diff mode may need to concatenate file name to
8281 // directory name. Just like it's done in main().
Bram Moolenaar910f66f2006-04-05 20:41:53 +00008282 if (used_file_diff_mode && mch_isdir(str) && GARGCOUNT > 0
8283 && !mch_isdir(alist_name(&GARGLIST[0])))
8284 {
8285 char_u *r;
8286
8287 r = concat_fnames(str, gettail(alist_name(&GARGLIST[0])), TRUE);
8288 if (r != NULL)
8289 {
8290 vim_free(str);
8291 str = r;
8292 }
8293 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01008294#endif
Bram Moolenaar0f873732019-12-05 20:28:46 +01008295 // Re-use the old buffer by renaming it. When not using literal
8296 // names it's done by alist_expand() below.
Bram Moolenaar86b68352004-12-27 21:59:20 +00008297 if (used_file_literal)
8298 buf_set_name(fnum_list[i], str);
8299
Bram Moolenaar0f873732019-12-05 20:28:46 +01008300 // Check backtick literal. backtick literal is already expanded in
8301 // main.c, so this part add str as literal.
Bram Moolenaar39d21e32017-08-05 23:09:31 +02008302 if (literal == FALSE)
8303 {
Bram Moolenaar116a0f82017-08-07 21:17:57 +02008304 size_t len = STRLEN(str);
8305
Bram Moolenaar39d21e32017-08-05 23:09:31 +02008306 if (len > 2 && *str == '`' && *(str + len - 1) == '`')
8307 literal = TRUE;
8308 }
8309 alist_add(&global_alist, str, literal ? 2 : 0);
Bram Moolenaar86b68352004-12-27 21:59:20 +00008310 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008311 }
8312
8313 if (!used_file_literal)
8314 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01008315 // Now expand wildcards in the arguments.
8316 // Temporarily add '(' and ')' to 'isfname'. These are valid
8317 // filename characters but are excluded from 'isfname' to make
Dominique Pelleaf4a61a2021-12-27 17:21:41 +00008318 // "gf" work on a file name in parentheses (e.g.: see vim.h).
Bram Moolenaar0f873732019-12-05 20:28:46 +01008319 // Also, unset wildignore to not be influenced by this option.
8320 // The arguments specified in command-line should be kept even if
8321 // encoding options were changed.
Christian Brabandtfd916d62021-11-01 22:44:33 +00008322 // Use :legacy so that it also works when in Vim9 script.
8323 do_cmdline_cmd((char_u *)":legacy let g:SaVe_ISF = &isf|set isf+=(,)");
8324 do_cmdline_cmd((char_u *)":legacy let g:SaVe_WIG = &wig|set wig=");
Bram Moolenaar86b68352004-12-27 21:59:20 +00008325 alist_expand(fnum_list, used_alist_count);
Christian Brabandtfd916d62021-11-01 22:44:33 +00008326 do_cmdline_cmd(
8327 (char_u *)":legacy let &isf = g:SaVe_ISF|unlet g:SaVe_ISF");
8328 do_cmdline_cmd(
8329 (char_u *)":legacy let &wig = g:SaVe_WIG|unlet g:SaVe_WIG");
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008330 }
8331
Bram Moolenaar0f873732019-12-05 20:28:46 +01008332 // If wildcard expansion failed, we are editing the first file of the
8333 // arglist and there is no file name: Edit the first argument now.
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008334 if (curwin->w_arg_idx == 0 && curbuf->b_fname == NULL)
8335 {
8336 do_cmdline_cmd((char_u *)":rewind");
Bram Moolenaar05268152021-11-18 18:53:45 +00008337 if (GARGCOUNT == 1 && used_file_full_path
8338 && vim_chdirfile(alist_name(&GARGLIST[0]), "drop") == OK)
8339 last_chdir_reason = "drop";
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008340 }
Bram Moolenaar86b68352004-12-27 21:59:20 +00008341
8342 set_alist_count();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008343}
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01008344
8345 int
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02008346mch_setenv(char *var, char *value, int x UNUSED)
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01008347{
8348 char_u *envbuf;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02008349 WCHAR *p;
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01008350
Bram Moolenaar964b3742019-05-24 18:54:09 +02008351 envbuf = alloc(STRLEN(var) + STRLEN(value) + 2);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01008352 if (envbuf == NULL)
8353 return -1;
8354
8355 sprintf((char *)envbuf, "%s=%s", var, value);
8356
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02008357 p = enc_to_utf16(envbuf, NULL);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01008358
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02008359 vim_free(envbuf);
8360 if (p == NULL)
8361 return -1;
8362 _wputenv(p);
Bram Moolenaara12a1612019-01-24 16:39:02 +01008363#ifdef libintl_wputenv
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02008364 libintl_wputenv(p);
Bram Moolenaara12a1612019-01-24 16:39:02 +01008365#endif
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02008366 // Unlike Un*x systems, we can free the string for _wputenv().
8367 vim_free(p);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01008368
8369 return 0;
8370}
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008371
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008372/*
8373 * Support for 256 colors and 24-bit colors was added in Windows 10
8374 * version 1703 (Creators update).
8375 */
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008376#define VTP_FIRST_SUPPORT_BUILD MAKE_VER(10, 0, 15063)
8377
8378/*
8379 * Support for pseudo-console (ConPTY) was added in windows 10
Bram Moolenaar57da6982019-09-13 22:30:11 +02008380 * version 1809 (October 2018 update).
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008381 */
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01008382#define CONPTY_FIRST_SUPPORT_BUILD MAKE_VER(10, 0, 17763)
Bram Moolenaar57da6982019-09-13 22:30:11 +02008383
8384/*
8385 * ConPTY differences between versions, need different logic.
8386 * version 1903 (May 2019 update).
8387 */
8388#define CONPTY_1903_BUILD MAKE_VER(10, 0, 18362)
8389
8390/*
Bram Moolenaar36e7a822019-11-13 21:49:24 +01008391 * version 1909 (November 2019 update).
8392 */
8393#define CONPTY_1909_BUILD MAKE_VER(10, 0, 18363)
8394
8395/*
Bram Moolenaar7ed8f592020-04-28 20:44:42 +02008396 * Stay ahead of the next update, and when it's done, fix this.
8397 * version ? (2020 update, temporarily use the build number of insider preview)
8398 */
8399#define CONPTY_NEXT_UPDATE_BUILD MAKE_VER(10, 0, 19587)
8400
8401/*
Bram Moolenaar57da6982019-09-13 22:30:11 +02008402 * Confirm until this version. Also the logic changes.
8403 * insider preview.
8404 */
Bram Moolenaar4c063dd2019-10-04 21:29:12 +02008405#define CONPTY_INSIDER_BUILD MAKE_VER(10, 0, 18995)
Bram Moolenaar57da6982019-09-13 22:30:11 +02008406
8407/*
8408 * Not stable now.
8409 */
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01008410#define CONPTY_STABLE_BUILD MAKE_VER(10, 0, 32767) // T.B.D.
Christopher Plewright1140b512022-11-12 18:46:05 +00008411// Notes:
8412// Win 10 22H2 Final is build 19045, it's conpty is widely used.
8413// Strangely, 19045 is newer but is a lower build number than the 2020 insider
8414// preview which had a build 19587. And, not sure how stable that was?
8415// Win Server 2022 (May 10, 2022) is build 20348, its conpty is widely used.
8416// Win 11 starts from build 22000, even though the major version says 10!
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008417
8418 static void
8419vtp_flag_init(void)
8420{
8421 DWORD ver = get_build_number();
Bram Moolenaarafde13b2019-04-28 19:46:49 +02008422#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008423 DWORD mode;
8424 HANDLE out;
8425
Bram Moolenaarafde13b2019-04-28 19:46:49 +02008426# ifdef VIMDLL
8427 if (!gui.in_use)
8428# endif
8429 {
8430 out = GetStdHandle(STD_OUTPUT_HANDLE);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008431
Bram Moolenaarafde13b2019-04-28 19:46:49 +02008432 vtp_working = (ver >= VTP_FIRST_SUPPORT_BUILD) ? 1 : 0;
8433 GetConsoleMode(out, &mode);
8434 mode |= (ENABLE_PROCESSED_OUTPUT | ENABLE_VIRTUAL_TERMINAL_PROCESSING);
8435 if (SetConsoleMode(out, mode) == 0)
8436 vtp_working = 0;
8437 }
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008438#endif
8439
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008440 if (ver >= CONPTY_FIRST_SUPPORT_BUILD)
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01008441 conpty_working = 1;
8442 if (ver >= CONPTY_STABLE_BUILD)
8443 conpty_stable = 1;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008444
Bram Moolenaar57da6982019-09-13 22:30:11 +02008445 if (ver <= CONPTY_INSIDER_BUILD)
8446 conpty_type = 3;
Bram Moolenaar36e7a822019-11-13 21:49:24 +01008447 if (ver <= CONPTY_1909_BUILD)
8448 conpty_type = 2;
Bram Moolenaar57da6982019-09-13 22:30:11 +02008449 if (ver <= CONPTY_1903_BUILD)
8450 conpty_type = 2;
8451 if (ver < CONPTY_FIRST_SUPPORT_BUILD)
8452 conpty_type = 1;
Bram Moolenaar7ed8f592020-04-28 20:44:42 +02008453
8454 if (ver >= CONPTY_NEXT_UPDATE_BUILD)
8455 conpty_fix_type = 1;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008456}
8457
Bram Moolenaarafde13b2019-04-28 19:46:49 +02008458#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL) || defined(PROTO)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008459
8460 static void
8461vtp_init(void)
8462{
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02008463# ifdef FEAT_TERMGUICOLORS
Christopher Plewright38804d62022-11-09 23:55:52 +00008464 if (!vtp_working)
Yasuhiro Matsumotoe42c8da2022-09-01 11:31:45 +01008465 {
Christopher Plewright38804d62022-11-09 23:55:52 +00008466 CONSOLE_SCREEN_BUFFER_INFOEX csbi;
8467 csbi.cbSize = sizeof(csbi);
8468 GetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
8469 save_console_bg_rgb = (guicolor_T)csbi.ColorTable[g_color_index_bg];
8470 save_console_fg_rgb = (guicolor_T)csbi.ColorTable[g_color_index_fg];
8471 store_console_bg_rgb = save_console_bg_rgb;
8472 store_console_fg_rgb = save_console_fg_rgb;
8473
Yasuhiro Matsumotoe42c8da2022-09-01 11:31:45 +01008474 COLORREF bg;
8475 bg = (COLORREF)csbi.ColorTable[g_color_index_bg];
8476 bg = (GetRValue(bg) << 16) | (GetGValue(bg) << 8) | GetBValue(bg);
8477 default_console_color_bg = bg;
Christopher Plewright38804d62022-11-09 23:55:52 +00008478
8479 COLORREF fg;
8480 fg = (COLORREF)csbi.ColorTable[g_color_index_fg];
8481 fg = (GetRValue(fg) << 16) | (GetGValue(fg) << 8) | GetBValue(fg);
8482 default_console_color_fg = fg;
Yasuhiro Matsumotoe42c8da2022-09-01 11:31:45 +01008483 }
Bram Moolenaarc4568ab2018-11-16 16:21:05 +01008484# endif
Christopher Plewrightc8b126d2022-12-22 13:45:23 +00008485 use_alternate_screen_buffer = win10_22H2_or_later && p_rs && vtp_working
Bram Moolenaar9fca1332022-12-22 21:06:41 +00008486 && !mch_getenv("VIM_TERMINAL");
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008487 set_console_color_rgb();
8488}
8489
8490 static void
8491vtp_exit(void)
8492{
Bram Moolenaardf543822020-01-30 11:53:59 +01008493 restore_console_color_rgb();
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008494}
8495
Bram Moolenaar06b7b582020-05-30 17:49:25 +02008496 int
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008497vtp_printf(
8498 char *format,
8499 ...)
8500{
8501 char_u buf[100];
8502 va_list list;
8503 DWORD result;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008504 int len;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008505
8506 va_start(list, format);
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008507 len = vim_vsnprintf((char *)buf, 100, (char *)format, list);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008508 va_end(list);
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008509 WriteConsoleA(g_hConOut, buf, (DWORD)len, &result, NULL);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008510 return (int)result;
8511}
8512
8513 static void
8514vtp_sgr_bulk(
8515 int arg)
8516{
8517 int args[1];
8518
8519 args[0] = arg;
8520 vtp_sgr_bulks(1, args);
8521}
8522
K.Takata6e1d31e2022-02-03 13:05:32 +00008523# define FAST256(x) \
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008524 if ((*p-- = "0123456789"[(n = x % 10)]) \
8525 && x >= 10 && (*p-- = "0123456789"[((m = x % 100) - n) / 10]) \
8526 && x >= 100 && (*p-- = "012"[((x & 0xff) - m) / 100]));
8527
K.Takata6e1d31e2022-02-03 13:05:32 +00008528# define FAST256CASE(x) \
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008529 case x: \
8530 FAST256(newargs[x - 1]);
8531
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008532 static void
8533vtp_sgr_bulks(
8534 int argc,
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008535 int *args)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008536{
K.Takata6e1d31e2022-02-03 13:05:32 +00008537# define MAXSGR 16
8538# define SGRBUFSIZE 2 + 4 * MAXSGR + 1 // '\033[' + SGR + 'm'
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008539 char_u buf[SGRBUFSIZE];
8540 char_u *p;
8541 int in, out;
8542 int newargs[16];
8543 static int sgrfgr = -1, sgrfgg, sgrfgb;
8544 static int sgrbgr = -1, sgrbgg, sgrbgb;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008545
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008546 if (argc == 0)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008547 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008548 sgrfgr = sgrbgr = -1;
K.Takatadf5320c2022-09-01 13:20:16 +01008549 vtp_printf("\033[m");
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008550 return;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008551 }
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008552
8553 in = out = 0;
8554 while (in < argc)
8555 {
8556 int s = args[in];
8557 int copylen = 1;
8558
8559 if (s == 38)
8560 {
8561 if (argc - in >= 5 && args[in + 1] == 2)
8562 {
8563 if (sgrfgr == args[in + 2] && sgrfgg == args[in + 3]
8564 && sgrfgb == args[in + 4])
8565 {
8566 in += 5;
8567 copylen = 0;
8568 }
8569 else
8570 {
8571 sgrfgr = args[in + 2];
8572 sgrfgg = args[in + 3];
8573 sgrfgb = args[in + 4];
8574 copylen = 5;
8575 }
8576 }
8577 else if (argc - in >= 3 && args[in + 1] == 5)
8578 {
8579 sgrfgr = -1;
8580 copylen = 3;
8581 }
8582 }
8583 else if (s == 48)
8584 {
8585 if (argc - in >= 5 && args[in + 1] == 2)
8586 {
8587 if (sgrbgr == args[in + 2] && sgrbgg == args[in + 3]
8588 && sgrbgb == args[in + 4])
8589 {
8590 in += 5;
8591 copylen = 0;
8592 }
8593 else
8594 {
8595 sgrbgr = args[in + 2];
8596 sgrbgg = args[in + 3];
8597 sgrbgb = args[in + 4];
8598 copylen = 5;
8599 }
8600 }
8601 else if (argc - in >= 3 && args[in + 1] == 5)
8602 {
8603 sgrbgr = -1;
8604 copylen = 3;
8605 }
8606 }
8607 else if (30 <= s && s <= 39)
8608 sgrfgr = -1;
8609 else if (90 <= s && s <= 97)
8610 sgrfgr = -1;
8611 else if (40 <= s && s <= 49)
8612 sgrbgr = -1;
8613 else if (100 <= s && s <= 107)
8614 sgrbgr = -1;
8615 else if (s == 0)
8616 sgrfgr = sgrbgr = -1;
8617
8618 while (copylen--)
8619 newargs[out++] = args[in++];
8620 }
8621
8622 p = &buf[sizeof(buf) - 1];
8623 *p-- = 'm';
8624
8625 switch (out)
8626 {
8627 int n, m;
8628 DWORD r;
8629
8630 FAST256CASE(16);
8631 *p-- = ';';
8632 FAST256CASE(15);
8633 *p-- = ';';
8634 FAST256CASE(14);
8635 *p-- = ';';
8636 FAST256CASE(13);
8637 *p-- = ';';
8638 FAST256CASE(12);
8639 *p-- = ';';
8640 FAST256CASE(11);
8641 *p-- = ';';
8642 FAST256CASE(10);
8643 *p-- = ';';
8644 FAST256CASE(9);
8645 *p-- = ';';
8646 FAST256CASE(8);
8647 *p-- = ';';
8648 FAST256CASE(7);
8649 *p-- = ';';
8650 FAST256CASE(6);
8651 *p-- = ';';
8652 FAST256CASE(5);
8653 *p-- = ';';
8654 FAST256CASE(4);
8655 *p-- = ';';
8656 FAST256CASE(3);
8657 *p-- = ';';
8658 FAST256CASE(2);
8659 *p-- = ';';
8660 FAST256CASE(1);
8661 *p-- = '[';
8662 *p = '\033';
8663 WriteConsoleA(g_hConOut, p, (DWORD)(&buf[SGRBUFSIZE] - p), &r, NULL);
8664 default:
8665 break;
8666 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008667}
8668
Bram Moolenaar06b7b582020-05-30 17:49:25 +02008669 static void
8670wt_init(void)
8671{
Christopher Plewright1140b512022-11-12 18:46:05 +00008672 wt_working = mch_getenv("WT_SESSION") != NULL;
Bram Moolenaar06b7b582020-05-30 17:49:25 +02008673}
8674
Bram Moolenaar8a938af2018-05-01 17:30:41 +02008675# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02008676 static int
8677ctermtoxterm(
8678 int cterm)
8679{
Bram Moolenaar9894e392018-05-05 14:29:06 +02008680 char_u r, g, b, idx;
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02008681
8682 cterm_color2rgb(cterm, &r, &g, &b, &idx);
8683 return (((int)r << 16) | ((int)g << 8) | (int)b);
8684}
Bram Moolenaar8a938af2018-05-01 17:30:41 +02008685# endif
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02008686
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008687 static void
8688set_console_color_rgb(void)
8689{
8690# ifdef FEAT_TERMGUICOLORS
K.Takata27b53be2022-09-18 12:25:49 +01008691 CONSOLE_SCREEN_BUFFER_INFOEX csbi;
Bram Moolenaara050b942019-12-02 21:35:31 +01008692 guicolor_T fg, bg;
8693 int ctermfg, ctermbg;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008694
Christopher Plewright38804d62022-11-09 23:55:52 +00008695 if (!vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008696 return;
8697
Bram Moolenaara050b942019-12-02 21:35:31 +01008698 get_default_console_color(&ctermfg, &ctermbg, &fg, &bg);
8699
Christopher Plewright38804d62022-11-09 23:55:52 +00008700 if (p_tgc || t_colors >= 256)
Bram Moolenaar06b7b582020-05-30 17:49:25 +02008701 {
8702 term_fg_rgb_color(fg);
8703 term_bg_rgb_color(bg);
8704 return;
8705 }
8706
Christopher Plewright38804d62022-11-09 23:55:52 +00008707 if (!conpty_working)
8708 {
8709 fg = (GetRValue(fg) << 16) | (GetGValue(fg) << 8) | GetBValue(fg);
8710 bg = (GetRValue(bg) << 16) | (GetGValue(bg) << 8) | GetBValue(bg);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008711
Christopher Plewright38804d62022-11-09 23:55:52 +00008712 csbi.cbSize = sizeof(csbi);
8713 GetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008714
Christopher Plewright38804d62022-11-09 23:55:52 +00008715 csbi.cbSize = sizeof(csbi);
8716 csbi.srWindow.Right += 1;
8717 csbi.srWindow.Bottom += 1;
8718 store_console_bg_rgb = csbi.ColorTable[g_color_index_bg];
8719 store_console_fg_rgb = csbi.ColorTable[g_color_index_fg];
8720 csbi.ColorTable[g_color_index_bg] = (COLORREF)bg;
8721 csbi.ColorTable[g_color_index_fg] = (COLORREF)fg;
8722 SetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
8723 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008724# endif
8725}
8726
Bram Moolenaara050b942019-12-02 21:35:31 +01008727# if defined(FEAT_TERMGUICOLORS) || defined(PROTO)
8728 void
8729get_default_console_color(
8730 int *cterm_fg,
8731 int *cterm_bg,
8732 guicolor_T *gui_fg,
8733 guicolor_T *gui_bg)
8734{
8735 int id;
8736 guicolor_T guifg = INVALCOLOR;
8737 guicolor_T guibg = INVALCOLOR;
8738 int ctermfg = 0;
8739 int ctermbg = 0;
Christopher Plewright38804d62022-11-09 23:55:52 +00008740 int dummynull = 0;
Bram Moolenaara050b942019-12-02 21:35:31 +01008741
8742 id = syn_name2id((char_u *)"Normal");
8743 if (id > 0 && p_tgc)
8744 syn_id2colors(id, &guifg, &guibg);
8745 if (guifg == INVALCOLOR)
8746 {
8747 ctermfg = -1;
8748 if (id > 0)
Christopher Plewright38804d62022-11-09 23:55:52 +00008749 syn_id2cterm_bg(id, &ctermfg, &dummynull);
8750 if (vtp_working)
8751 {
8752 cterm_normal_fg_gui_color = guifg =
8753 ctermfg != -1 ? ctermtoxterm(ctermfg) : INVALCOLOR;
8754 ctermfg = ctermfg < 0 ? 0 : ctermfg;
8755 }
8756 else
8757 {
8758 guifg = ctermfg != -1 ? ctermtoxterm(ctermfg)
Bram Moolenaara050b942019-12-02 21:35:31 +01008759 : default_console_color_fg;
Christopher Plewright38804d62022-11-09 23:55:52 +00008760 cterm_normal_fg_gui_color = guifg;
8761 ctermfg = ctermfg < 0 ? 0 : ctermfg;
8762 }
Bram Moolenaara050b942019-12-02 21:35:31 +01008763 }
8764 if (guibg == INVALCOLOR)
8765 {
8766 ctermbg = -1;
8767 if (id > 0)
Christopher Plewright38804d62022-11-09 23:55:52 +00008768 syn_id2cterm_bg(id, &dummynull, &ctermbg);
8769 if (vtp_working)
Yasuhiro Matsumotoe42c8da2022-09-01 11:31:45 +01008770 {
8771 cterm_normal_bg_gui_color = guibg =
Yasuhiro Matsumotoaa04e1b2022-05-07 14:09:19 +01008772 ctermbg != -1 ? ctermtoxterm(ctermbg) : INVALCOLOR;
Yasuhiro Matsumotoe42c8da2022-09-01 11:31:45 +01008773 if (ctermbg < 0)
8774 ctermbg = 0;
8775 }
K.Takatae53a0d42022-09-05 21:45:11 +01008776 else
8777 {
8778 guibg = ctermbg != -1 ? ctermtoxterm(ctermbg)
8779 : default_console_color_bg;
8780 cterm_normal_bg_gui_color = guibg;
8781 ctermbg = ctermbg < 0 ? 0 : ctermbg;
8782 }
Bram Moolenaara050b942019-12-02 21:35:31 +01008783 }
8784
8785 *cterm_fg = ctermfg;
8786 *cterm_bg = ctermbg;
8787 *gui_fg = guifg;
8788 *gui_bg = guibg;
8789}
8790# endif
8791
Bram Moolenaardf543822020-01-30 11:53:59 +01008792/*
8793 * Set the console colors to the original colors or the last set colors.
8794 */
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008795 static void
8796reset_console_color_rgb(void)
8797{
8798# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008799
Christopher Plewright38804d62022-11-09 23:55:52 +00008800 if (vtp_working)
Bram Moolenaar06b7b582020-05-30 17:49:25 +02008801 return;
8802
Christopher Plewright38804d62022-11-09 23:55:52 +00008803 CONSOLE_SCREEN_BUFFER_INFOEX csbi;
8804
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008805 csbi.cbSize = sizeof(csbi);
K.Takata27b53be2022-09-18 12:25:49 +01008806 GetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008807
8808 csbi.cbSize = sizeof(csbi);
8809 csbi.srWindow.Right += 1;
8810 csbi.srWindow.Bottom += 1;
Bram Moolenaardf543822020-01-30 11:53:59 +01008811 csbi.ColorTable[g_color_index_bg] = (COLORREF)store_console_bg_rgb;
8812 csbi.ColorTable[g_color_index_fg] = (COLORREF)store_console_fg_rgb;
K.Takata27b53be2022-09-18 12:25:49 +01008813 SetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaardf543822020-01-30 11:53:59 +01008814# endif
8815}
8816
8817/*
8818 * Set the console colors to the original colors.
8819 */
8820 static void
8821restore_console_color_rgb(void)
8822{
8823# ifdef FEAT_TERMGUICOLORS
Christopher Plewright38804d62022-11-09 23:55:52 +00008824 if (vtp_working)
8825 return;
8826
K.Takata27b53be2022-09-18 12:25:49 +01008827 CONSOLE_SCREEN_BUFFER_INFOEX csbi;
Bram Moolenaardf543822020-01-30 11:53:59 +01008828
8829 csbi.cbSize = sizeof(csbi);
K.Takata27b53be2022-09-18 12:25:49 +01008830 GetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaardf543822020-01-30 11:53:59 +01008831
8832 csbi.cbSize = sizeof(csbi);
8833 csbi.srWindow.Right += 1;
8834 csbi.srWindow.Bottom += 1;
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02008835 csbi.ColorTable[g_color_index_bg] = (COLORREF)save_console_bg_rgb;
8836 csbi.ColorTable[g_color_index_fg] = (COLORREF)save_console_fg_rgb;
K.Takata27b53be2022-09-18 12:25:49 +01008837 SetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008838# endif
8839}
8840
8841 void
8842control_console_color_rgb(void)
8843{
Christopher Plewright38804d62022-11-09 23:55:52 +00008844 if (vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008845 set_console_color_rgb();
8846 else
8847 reset_console_color_rgb();
8848}
8849
8850 int
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008851use_vtp(void)
8852{
8853 return USE_VTP;
8854}
8855
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02008856 int
8857is_term_win32(void)
8858{
8859 return T_NAME != NULL && STRCMP(T_NAME, "win32") == 0;
8860}
8861
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008862 int
8863has_vtp_working(void)
8864{
8865 return vtp_working;
8866}
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01008867
Bram Moolenaar6902c0e2019-02-16 14:07:37 +01008868#endif
8869
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01008870 int
8871has_conpty_working(void)
8872{
8873 return conpty_working;
8874}
8875
8876 int
Bram Moolenaar57da6982019-09-13 22:30:11 +02008877get_conpty_type(void)
8878{
8879 return conpty_type;
8880}
8881
8882 int
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01008883is_conpty_stable(void)
8884{
8885 return conpty_stable;
8886}
Bram Moolenaar78d21da2019-02-17 15:00:52 +01008887
Bram Moolenaar7ed8f592020-04-28 20:44:42 +02008888 int
8889get_conpty_fix_type(void)
8890{
8891 return conpty_fix_type;
8892}
8893
Bram Moolenaarafde13b2019-04-28 19:46:49 +02008894#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL) || defined(PROTO)
Bram Moolenaar78d21da2019-02-17 15:00:52 +01008895 void
8896resize_console_buf(void)
8897{
8898 CONSOLE_SCREEN_BUFFER_INFO csbi;
8899 COORD coord;
8900 SMALL_RECT newsize;
8901
8902 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
8903 {
8904 coord.X = SRWIDTH(csbi.srWindow);
8905 coord.Y = SRHEIGHT(csbi.srWindow);
8906 SetConsoleScreenBufferSize(g_hConOut, coord);
8907
8908 newsize.Left = 0;
8909 newsize.Top = 0;
8910 newsize.Right = coord.X - 1;
8911 newsize.Bottom = coord.Y - 1;
8912 SetConsoleWindowInfo(g_hConOut, TRUE, &newsize);
8913
8914 SetConsoleScreenBufferSize(g_hConOut, coord);
8915 }
8916}
8917#endif
Martin Tournoij1a3e5742021-07-24 13:57:29 +02008918
8919 char *
8920GetWin32Error(void)
8921{
K.Takatad68b2fc2022-02-12 11:18:37 +00008922 static char *oldmsg = NULL;
Martin Tournoij1a3e5742021-07-24 13:57:29 +02008923 char *msg = NULL;
K.Takatad68b2fc2022-02-12 11:18:37 +00008924
Martin Tournoij1a3e5742021-07-24 13:57:29 +02008925 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER|FORMAT_MESSAGE_FROM_SYSTEM,
8926 NULL, GetLastError(), 0, (LPSTR)&msg, 0, NULL);
K.Takatad68b2fc2022-02-12 11:18:37 +00008927 if (oldmsg != NULL)
8928 LocalFree(oldmsg);
Martin Tournoij1a3e5742021-07-24 13:57:29 +02008929 if (msg != NULL)
8930 {
8931 // remove trailing \r\n
8932 char *pcrlf = strstr(msg, "\r\n");
8933 if (pcrlf != NULL)
8934 *pcrlf = '\0';
K.Takatad68b2fc2022-02-12 11:18:37 +00008935 oldmsg = msg;
Martin Tournoij1a3e5742021-07-24 13:57:29 +02008936 }
8937 return msg;
8938}
Paul Ollis65745772022-06-05 16:55:54 +01008939
8940#if defined(FEAT_RELTIME) || defined(PROTO)
8941static HANDLE timer_handle;
8942static int timer_active = FALSE;
8943
8944/*
8945 * Calls to start_timeout alternate the return value pointer between the two
8946 * entries in timeout_flags. If the previously active timeout is very close to
8947 * expiring when start_timeout() is called then a race condition means that the
8948 * set_flag() function may still be invoked after the previous timer is
8949 * deleted. Ping-ponging between the two flags prevents this causing 'fake'
8950 * timeouts.
8951 */
Bram Moolenaar155f2d12022-06-20 13:38:33 +01008952static sig_atomic_t timeout_flags[2];
8953static int timeout_flag_idx = 0;
8954static sig_atomic_t *timeout_flag = &timeout_flags[0];
Paul Ollis65745772022-06-05 16:55:54 +01008955
8956
8957 static void CALLBACK
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +01008958set_flag(void *param, BOOLEAN unused2 UNUSED)
Paul Ollis65745772022-06-05 16:55:54 +01008959{
8960 int *timeout_flag = (int *)param;
8961
8962 *timeout_flag = TRUE;
8963}
8964
8965/*
8966 * Stop any active timeout.
8967 */
8968 void
8969stop_timeout(void)
8970{
8971 if (timer_active)
8972 {
Christopher Plewright2a46f812022-10-16 19:47:45 +01008973 BOOL ret = DeleteTimerQueueTimer(NULL, timer_handle, NULL);
Paul Ollis65745772022-06-05 16:55:54 +01008974 timer_active = FALSE;
8975 if (!ret && GetLastError() != ERROR_IO_PENDING)
8976 {
8977 semsg(_(e_could_not_clear_timeout_str), GetWin32Error());
8978 }
8979 }
8980 *timeout_flag = FALSE;
8981}
8982
8983/*
8984 * Start the timeout timer.
8985 *
8986 * The period is defined in milliseconds.
8987 *
8988 * The return value is a pointer to a flag that is initialised to 0. If the
8989 * timeout expires, the flag is set to 1. This will only return pointers to
8990 * static memory; i.e. any pointer returned by this function may always be
8991 * safely dereferenced.
8992 *
8993 * This function is not expected to fail, but if it does it still returns a
8994 * valid flag pointer; the flag will remain stuck at zero.
8995 */
Bram Moolenaar155f2d12022-06-20 13:38:33 +01008996 volatile sig_atomic_t *
Paul Ollis65745772022-06-05 16:55:54 +01008997start_timeout(long msec)
8998{
Paul Ollis65745772022-06-05 16:55:54 +01008999 BOOL ret;
9000
Bram Moolenaar1f30caf2022-06-19 14:36:35 +01009001 timeout_flag = &timeout_flags[timeout_flag_idx];
Paul Ollis65745772022-06-05 16:55:54 +01009002
9003 stop_timeout();
9004 ret = CreateTimerQueueTimer(
9005 &timer_handle, NULL, set_flag, timeout_flag,
9006 (DWORD)msec, 0, WT_EXECUTEDEFAULT);
9007 if (!ret)
9008 {
9009 semsg(_(e_could_not_set_timeout_str), GetWin32Error());
9010 }
9011 else
9012 {
Bram Moolenaar1f30caf2022-06-19 14:36:35 +01009013 timeout_flag_idx = (timeout_flag_idx + 1) % 2;
Paul Ollis65745772022-06-05 16:55:54 +01009014 timer_active = TRUE;
9015 *timeout_flag = FALSE;
9016 }
9017 return timeout_flag;
9018}
9019#endif