blob: 3f2b3c3a4ca20d43b38c125e646016a4731d4db0 [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;
Saleem Abdulrasool38bea302023-12-27 18:57:12 +0100159// This is explicitly initialised to work around a LTCG issue on Windows ARM64
160// (at least of 19.39.33321). This pushes this into the `.data` rather than
161// `.bss` which corrects code generation in `write_chars` (#13453).
162static COORD g_coord = {0, 0}; // 0-based, but external coords are 1-based
Bram Moolenaar071d4272004-06-13 20:20:40 +0000163
Bram Moolenaar0f873732019-12-05 20:28:46 +0100164// The attribute of the screen when the editor was started
165static WORD g_attrDefault = 7; // lightgray text on black background
Bram Moolenaar071d4272004-06-13 20:20:40 +0000166static WORD g_attrCurrent;
167
Bram Moolenaar0f873732019-12-05 20:28:46 +0100168static int g_fCBrkPressed = FALSE; // set by ctrl-break interrupt
169static int g_fCtrlCPressed = FALSE; // set when ctrl-C or ctrl-break detected
170static int g_fForceExit = FALSE; // set when forcefully exiting
Bram Moolenaar071d4272004-06-13 20:20:40 +0000171
Bram Moolenaar071d4272004-06-13 20:20:40 +0000172static void scroll(unsigned cLines);
173static void set_scroll_region(unsigned left, unsigned top,
174 unsigned right, unsigned bottom);
Bram Moolenaar6982f422019-02-16 16:48:01 +0100175static void set_scroll_region_tb(unsigned top, unsigned bottom);
176static void set_scroll_region_lr(unsigned left, unsigned right);
177static void insert_lines(unsigned cLines);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000178static void delete_lines(unsigned cLines);
179static void gotoxy(unsigned x, unsigned y);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000180static void standout(void);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000181static int s_cursor_visible = TRUE;
182static int did_create_conin = FALSE;
Christopher Plewright20b795e2022-12-20 20:01:58 +0000183// The 'input_record_buffer' is an internal dynamic fifo queue of MS-Windows
184// console INPUT_RECORD events that are normally read from the console input
185// buffer. This provides an injection point for testing the low-level handling
186// of INPUT_RECORDs.
187typedef struct input_record_buffer_node_S
188{
189 INPUT_RECORD ir;
190 struct input_record_buffer_node_S *next;
191} input_record_buffer_node_T;
192typedef struct input_record_buffer_S
193{
194 input_record_buffer_node_T *head;
195 input_record_buffer_node_T *tail;
196 int length;
197} input_record_buffer_T;
198static input_record_buffer_T input_record_buffer;
Christopher Plewright20b795e2022-12-20 20:01:58 +0000199static int read_input_record_buffer(INPUT_RECORD* irEvents, int nMaxLength);
200static int write_input_record_buffer(INPUT_RECORD* irEvents, int nLength);
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200201#endif
202#ifdef FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +0000203static int s_dont_use_vimrun = TRUE;
204static int need_vimrun_warning = FALSE;
205static char *vimrun_path = "vimrun ";
206#endif
207
Bram Moolenaar12b559e2013-06-12 22:41:37 +0200208static int win32_getattrs(char_u *name);
209static int win32_setattrs(char_u *name, int attrs);
210static int win32_set_archive(char_u *name);
211
Bram Moolenaard9ef1b82019-02-13 19:23:10 +0100212static int conpty_working = 0;
Bram Moolenaar57da6982019-09-13 22:30:11 +0200213static int conpty_type = 0;
Bram Moolenaard9ef1b82019-02-13 19:23:10 +0100214static int conpty_stable = 0;
Bram Moolenaar7ed8f592020-04-28 20:44:42 +0200215static int conpty_fix_type = 0;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100216static void vtp_flag_init();
217
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200218#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar6902c0e2019-02-16 14:07:37 +0100219static int vtp_working = 0;
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100220static void vtp_init();
221static void vtp_exit();
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100222static void vtp_sgr_bulk(int arg);
223static void vtp_sgr_bulks(int argc, int *argv);
224
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200225static int wt_working = 0;
Christopher Plewright1140b512022-11-12 18:46:05 +0000226static void wt_init(void);
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200227
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +0200228static int g_color_index_bg = 0;
229static int g_color_index_fg = 7;
230
231# ifdef FEAT_TERMGUICOLORS
Christopher Plewright38804d62022-11-09 23:55:52 +0000232static guicolor_T save_console_bg_rgb;
233static guicolor_T save_console_fg_rgb;
234static guicolor_T store_console_bg_rgb;
235static guicolor_T store_console_fg_rgb;
Yasuhiro Matsumotoe42c8da2022-09-01 11:31:45 +0100236static int default_console_color_bg = 0x000000; // black
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +0200237static int default_console_color_fg = 0xc0c0c0; // white
Christopher Plewrightf75a2cb2023-01-28 10:28:09 +0000238# define USE_VTP (vtp_working && is_term_win32() \
239 && (p_tgc || t_colors >= 256))
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200240# define USE_WT (wt_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100241# else
242# define USE_VTP 0
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200243# define USE_WT 0
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100244# endif
245
246static void set_console_color_rgb(void);
247static void reset_console_color_rgb(void);
Bram Moolenaardf543822020-01-30 11:53:59 +0100248static void restore_console_color_rgb(void);
Christopher Plewright20b795e2022-12-20 20:01:58 +0000249#endif // !FEAT_GUI_MSWIN || VIMDLL
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100250
Bram Moolenaar0f873732019-12-05 20:28:46 +0100251// This flag is newly created from Windows 10
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100252#ifndef ENABLE_VIRTUAL_TERMINAL_PROCESSING
253# define ENABLE_VIRTUAL_TERMINAL_PROCESSING 0x0004
254#endif
255
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200256#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar0f873732019-12-05 20:28:46 +0100257static int suppress_winsize = 1; // don't fiddle with console
Bram Moolenaar071d4272004-06-13 20:20:40 +0000258#endif
259
K.Takatace3189d2023-02-15 19:13:43 +0000260static WCHAR *exe_pathw = NULL;
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200261
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100262static BOOL win8_or_later = FALSE;
Christopher Plewrightc8b126d2022-12-22 13:45:23 +0000263static BOOL win10_22H2_or_later = FALSE;
Bram Moolenaar9fca1332022-12-22 21:06:41 +0000264#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Christopher Plewrightc8b126d2022-12-22 13:45:23 +0000265static BOOL use_alternate_screen_buffer = FALSE;
Bram Moolenaar9fca1332022-12-22 21:06:41 +0000266#endif
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100267
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100268/*
269 * Get version number including build number
270 */
271typedef BOOL (WINAPI *PfnRtlGetVersion)(LPOSVERSIONINFOW);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100272#define MAKE_VER(major, minor, build) \
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100273 (((major) << 24) | ((minor) << 16) | (build))
274
275 static DWORD
276get_build_number(void)
277{
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +0100278 OSVERSIONINFOW osver;
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100279 HMODULE hNtdll;
280 PfnRtlGetVersion pRtlGetVersion;
281 DWORD ver = MAKE_VER(0, 0, 0);
282
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +0100283 osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFOW);
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100284 hNtdll = GetModuleHandle("ntdll.dll");
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +0000285 if (hNtdll == NULL)
286 return ver;
287
288 pRtlGetVersion =
289 (PfnRtlGetVersion)GetProcAddress(hNtdll, "RtlGetVersion");
290 pRtlGetVersion(&osver);
291 ver = MAKE_VER(min(osver.dwMajorVersion, 255),
292 min(osver.dwMinorVersion, 255),
293 min(osver.dwBuildNumber, 32767));
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100294 return ver;
295}
296
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200297#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200298 static BOOL
299is_ambiwidth_event(
300 INPUT_RECORD *ir)
301{
302 return ir->EventType == KEY_EVENT
303 && ir->Event.KeyEvent.bKeyDown
304 && ir->Event.KeyEvent.wRepeatCount == 1
305 && ir->Event.KeyEvent.wVirtualKeyCode == 0x12
306 && ir->Event.KeyEvent.wVirtualScanCode == 0x38
K.Takata972db232022-02-04 10:45:38 +0000307 && ir->Event.KeyEvent.uChar.UnicodeChar == 0
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200308 && ir->Event.KeyEvent.dwControlKeyState == 2;
309}
310
311 static void
312make_ambiwidth_event(
313 INPUT_RECORD *down,
314 INPUT_RECORD *up)
315{
316 down->Event.KeyEvent.wVirtualKeyCode = 0;
317 down->Event.KeyEvent.wVirtualScanCode = 0;
K.Takata972db232022-02-04 10:45:38 +0000318 down->Event.KeyEvent.uChar.UnicodeChar
319 = up->Event.KeyEvent.uChar.UnicodeChar;
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200320 down->Event.KeyEvent.dwControlKeyState = 0;
321}
322
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100323/*
324 * Version of ReadConsoleInput() that works with IME.
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100325 * Works around problems on Windows 8.
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100326 */
327 static BOOL
328read_console_input(
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100329 HANDLE hInput,
330 INPUT_RECORD *lpBuffer,
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +0100331 int nLength,
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100332 LPDWORD lpEvents)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100333{
334 enum
335 {
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100336 IRSIZE = 10
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100337 };
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100338 static INPUT_RECORD s_irCache[IRSIZE];
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100339 static DWORD s_dwIndex = 0;
340 static DWORD s_dwMax = 0;
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100341 DWORD dwEvents;
Bram Moolenaardd415a62014-02-05 14:02:27 +0100342 int head;
343 int tail;
344 int i;
Bram Moolenaarbc970da2020-04-26 19:00:07 +0200345 static INPUT_RECORD s_irPseudo;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100346
Christopher Plewright20b795e2022-12-20 20:01:58 +0000347 if (s_dwMax == 0 && input_record_buffer.length > 0)
348 {
349 dwEvents = read_input_record_buffer(s_irCache, IRSIZE);
350 s_dwIndex = 0;
351 s_dwMax = dwEvents;
352 }
353
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200354 if (nLength == -2)
355 return (s_dwMax > 0) ? TRUE : FALSE;
356
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100357 if (!win8_or_later)
358 {
359 if (nLength == -1)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200360 return PeekConsoleInputW(hInput, lpBuffer, 1, lpEvents);
361 return ReadConsoleInputW(hInput, lpBuffer, 1, &dwEvents);
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100362 }
363
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100364 if (s_dwMax == 0)
365 {
Christopher Plewright38804d62022-11-09 23:55:52 +0000366 if (!vtp_working && nLength == -1)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200367 return PeekConsoleInputW(hInput, lpBuffer, 1, lpEvents);
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200368 GetNumberOfConsoleInputEvents(hInput, &dwEvents);
369 if (dwEvents == 0 && nLength == -1)
370 return PeekConsoleInputW(hInput, lpBuffer, 1, lpEvents);
371 ReadConsoleInputW(hInput, s_irCache, IRSIZE, &dwEvents);
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100372 s_dwIndex = 0;
373 s_dwMax = dwEvents;
374 if (dwEvents == 0)
375 {
376 *lpEvents = 0;
377 return TRUE;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100378 }
Bram Moolenaardd415a62014-02-05 14:02:27 +0100379
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200380 for (i = s_dwIndex; i < (int)s_dwMax - 1; ++i)
381 if (is_ambiwidth_event(&s_irCache[i]))
382 make_ambiwidth_event(&s_irCache[i], &s_irCache[i + 1]);
383
Bram Moolenaardd415a62014-02-05 14:02:27 +0100384 if (s_dwMax > 1)
385 {
386 head = 0;
387 tail = s_dwMax - 1;
388 while (head != tail)
389 {
390 if (s_irCache[head].EventType == WINDOW_BUFFER_SIZE_EVENT
391 && s_irCache[head + 1].EventType
392 == WINDOW_BUFFER_SIZE_EVENT)
393 {
Bram Moolenaar0f873732019-12-05 20:28:46 +0100394 // Remove duplicate event to avoid flicker.
Bram Moolenaardd415a62014-02-05 14:02:27 +0100395 for (i = head; i < tail; ++i)
396 s_irCache[i] = s_irCache[i + 1];
397 --tail;
398 continue;
399 }
400 head++;
401 }
402 s_dwMax = tail + 1;
403 }
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100404 }
Bram Moolenaardd415a62014-02-05 14:02:27 +0100405
Bram Moolenaarbc970da2020-04-26 19:00:07 +0200406 if (s_irCache[s_dwIndex].EventType == KEY_EVENT)
407 {
408 if (s_irCache[s_dwIndex].Event.KeyEvent.wRepeatCount > 1)
409 {
410 s_irPseudo = s_irCache[s_dwIndex];
411 s_irPseudo.Event.KeyEvent.wRepeatCount = 1;
412 s_irCache[s_dwIndex].Event.KeyEvent.wRepeatCount--;
413 *lpBuffer = s_irPseudo;
414 *lpEvents = 1;
415 return TRUE;
416 }
417 }
418
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100419 *lpBuffer = s_irCache[s_dwIndex];
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200420 if (!(nLength == -1 || nLength == -2) && ++s_dwIndex >= s_dwMax)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100421 s_dwMax = 0;
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100422 *lpEvents = 1;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100423 return TRUE;
424}
425
426/*
427 * Version of PeekConsoleInput() that works with IME.
428 */
429 static BOOL
430peek_console_input(
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100431 HANDLE hInput,
432 INPUT_RECORD *lpBuffer,
Bram Moolenaarbd67aac2019-09-21 23:09:04 +0200433 DWORD nLength UNUSED,
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100434 LPDWORD lpEvents)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100435{
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +0100436 return read_console_input(hInput, lpBuffer, -1, lpEvents);
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100437}
438
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100439# ifdef FEAT_CLIENTSERVER
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200440 static DWORD
441msg_wait_for_multiple_objects(
442 DWORD nCount,
443 LPHANDLE pHandles,
444 BOOL fWaitAll,
445 DWORD dwMilliseconds,
446 DWORD dwWakeMask)
447{
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +0100448 if (read_console_input(NULL, NULL, -2, NULL))
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200449 return WAIT_OBJECT_0;
450 return MsgWaitForMultipleObjects(nCount, pHandles, fWaitAll,
451 dwMilliseconds, dwWakeMask);
452}
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100453# endif
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200454
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100455# ifndef FEAT_CLIENTSERVER
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200456 static DWORD
457wait_for_single_object(
458 HANDLE hHandle,
459 DWORD dwMilliseconds)
460{
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +0100461 if (read_console_input(NULL, NULL, -2, NULL))
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200462 return WAIT_OBJECT_0;
463 return WaitForSingleObject(hHandle, dwMilliseconds);
464}
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100465# endif
Christopher Plewright20b795e2022-12-20 20:01:58 +0000466#endif // !FEAT_GUI_MSWIN || VIMDLL
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200467
K.Takatace3189d2023-02-15 19:13:43 +0000468 void
469mch_get_exe_name(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000470{
Bram Moolenaar0f873732019-12-05 20:28:46 +0100471 // Maximum length of $PATH is more than MAXPATHL. 8191 is often mentioned
K.Takataf741e3e2023-05-15 16:41:40 +0100472 // as the maximum length that works. Add 1 for a NUL byte and 5 for
473 // "PATH=".
474#define MAX_ENV_PATH_LEN (8191 + 1 + 5)
475 WCHAR temp[MAX_ENV_PATH_LEN];
K.Takatace3189d2023-02-15 19:13:43 +0000476 WCHAR buf[MAX_PATH];
477 int updated = FALSE;
478 static int enc_prev = -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000479
K.Takatace3189d2023-02-15 19:13:43 +0000480 if (exe_name == NULL || exe_pathw == NULL || enc_prev != enc_codepage)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000481 {
Bram Moolenaar0f873732019-12-05 20:28:46 +0100482 // store the name of the executable, may be used for $VIM
K.Takatace3189d2023-02-15 19:13:43 +0000483 GetModuleFileNameW(NULL, buf, MAX_PATH);
484 if (*buf != NUL)
485 {
486 if (enc_codepage == -1)
487 enc_codepage = GetACP();
K.Takataf741e3e2023-05-15 16:41:40 +0100488 vim_free(exe_name);
K.Takatace3189d2023-02-15 19:13:43 +0000489 exe_name = utf16_to_enc(buf, NULL);
490 enc_prev = enc_codepage;
491
492 WCHAR *wp = wcsrchr(buf, '\\');
493 if (wp != NULL)
494 *wp = NUL;
K.Takataf741e3e2023-05-15 16:41:40 +0100495 vim_free(exe_pathw);
K.Takatace3189d2023-02-15 19:13:43 +0000496 exe_pathw = _wcsdup(buf);
497 updated = TRUE;
498 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000499 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000500
K.Takatace3189d2023-02-15 19:13:43 +0000501 if (exe_pathw == NULL || !updated)
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +0000502 return;
503
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +0000504 // Append our starting directory to $PATH, so that when doing
505 // "!xxd" it's found in our starting directory. Needed because
506 // SearchPath() also looks there.
K.Takataf741e3e2023-05-15 16:41:40 +0100507 WCHAR *p = _wgetenv(L"PATH");
508 if (p == NULL || wcslen(p) + wcslen(exe_pathw) + 2 + 5 < MAX_ENV_PATH_LEN)
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000509 {
K.Takataf741e3e2023-05-15 16:41:40 +0100510 wcscpy(temp, L"PATH=");
511
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +0000512 if (p == NULL || *p == NUL)
K.Takataf741e3e2023-05-15 16:41:40 +0100513 wcscat(temp, exe_pathw);
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +0000514 else
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000515 {
K.Takataf741e3e2023-05-15 16:41:40 +0100516 wcscat(temp, p);
517
518 // Check if exe_path is already included in $PATH.
519 if (wcsstr(temp, exe_pathw) == NULL)
520 {
521 // Append ';' if $PATH doesn't end with it.
522 size_t len = wcslen(temp);
523 if (temp[len - 1] != L';')
524 wcscat(temp, L";");
525
526 wcscat(temp, exe_pathw);
527 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000528 }
K.Takataf741e3e2023-05-15 16:41:40 +0100529 _wputenv(temp);
530#ifdef libintl_wputenv
531 libintl_wputenv(temp);
532#endif
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000533 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000534}
535
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200536/*
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100537 * Unescape characters in "p" that appear in "escaped".
538 */
539 static void
540unescape_shellxquote(char_u *p, char_u *escaped)
541{
Bram Moolenaar4336cdf2012-02-29 13:58:47 +0100542 int l = (int)STRLEN(p);
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100543 int n;
544
545 while (*p != NUL)
546 {
547 if (*p == '^' && vim_strchr(escaped, p[1]) != NULL)
548 mch_memmove(p, p + 1, l--);
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100549 n = (*mb_ptr2len)(p);
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100550 p += n;
551 l -= n;
552 }
553}
554
555/*
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200556 * Load library "name".
557 */
558 HINSTANCE
K.Takatad68b2fc2022-02-12 11:18:37 +0000559vimLoadLib(const char *name)
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200560{
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200561 HINSTANCE dll = NULL;
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200562
Bram Moolenaar3d0e7a92021-05-01 17:46:03 +0200563 // No need to load any library when registering OLE.
564 if (found_register_arg)
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +0000565 return NULL;
Bram Moolenaar3d0e7a92021-05-01 17:46:03 +0200566
Bram Moolenaar0f873732019-12-05 20:28:46 +0100567 // NOTE: Do not use mch_dirname() and mch_chdir() here, they may call
568 // vimLoadLib() recursively, which causes a stack overflow.
K.Takatace3189d2023-02-15 19:13:43 +0000569 if (exe_pathw == NULL)
K.Takataf741e3e2023-05-15 16:41:40 +0100570 {
K.Takatace3189d2023-02-15 19:13:43 +0000571 mch_get_exe_name();
K.Takataf741e3e2023-05-15 16:41:40 +0100572 if (exe_pathw == NULL)
573 return NULL;
574 }
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +0000575
576 WCHAR old_dirw[MAXPATHL];
577
578 if (GetCurrentDirectoryW(MAXPATHL, old_dirw) == 0)
579 return NULL;
580
581 // Change directory to where the executable is, both to make
582 // sure we find a .dll there and to avoid looking for a .dll
583 // in the current directory.
K.Takatace3189d2023-02-15 19:13:43 +0000584 SetCurrentDirectoryW(exe_pathw);
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +0000585 dll = LoadLibrary(name);
586 SetCurrentDirectoryW(old_dirw);
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200587 return dll;
588}
589
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200590#if defined(VIMDLL) || defined(PROTO)
591/*
592 * Check if the current executable file is for the GUI subsystem.
593 */
594 int
595mch_is_gui_executable(void)
596{
597 PBYTE pImage = (PBYTE)GetModuleHandle(NULL);
598 PIMAGE_DOS_HEADER pDOS = (PIMAGE_DOS_HEADER)pImage;
599 PIMAGE_NT_HEADERS pPE;
600
601 if (pDOS->e_magic != IMAGE_DOS_SIGNATURE)
602 return FALSE;
603 pPE = (PIMAGE_NT_HEADERS)(pImage + pDOS->e_lfanew);
604 if (pPE->Signature != IMAGE_NT_SIGNATURE)
605 return FALSE;
606 if (pPE->OptionalHeader.Subsystem == IMAGE_SUBSYSTEM_WINDOWS_GUI)
607 return TRUE;
608 return FALSE;
609}
610#endif
611
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000612#if defined(DYNAMIC_ICONV) || defined(DYNAMIC_GETTEXT) \
613 || defined(FEAT_PYTHON3) || defined(PROTO)
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100614/*
615 * Get related information about 'funcname' which is imported by 'hInst'.
616 * If 'info' is 0, return the function address.
617 * If 'info' is 1, return the module name which the function is imported from.
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000618 * If 'info' is 2, hook the function with 'ptr', and return the original
619 * function address.
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100620 */
621 static void *
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000622get_imported_func_info(HINSTANCE hInst, const char *funcname, int info,
623 const void *ptr)
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100624{
625 PBYTE pImage = (PBYTE)hInst;
626 PIMAGE_DOS_HEADER pDOS = (PIMAGE_DOS_HEADER)hInst;
627 PIMAGE_NT_HEADERS pPE;
628 PIMAGE_IMPORT_DESCRIPTOR pImpDesc;
Bram Moolenaar0f873732019-12-05 20:28:46 +0100629 PIMAGE_THUNK_DATA pIAT; // Import Address Table
630 PIMAGE_THUNK_DATA pINT; // Import Name Table
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100631 PIMAGE_IMPORT_BY_NAME pImpName;
Ken Takata119fdd92023-10-04 20:05:05 +0200632 DWORD ImpVA;
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100633
634 if (pDOS->e_magic != IMAGE_DOS_SIGNATURE)
635 return NULL;
636 pPE = (PIMAGE_NT_HEADERS)(pImage + pDOS->e_lfanew);
637 if (pPE->Signature != IMAGE_NT_SIGNATURE)
638 return NULL;
Ken Takata119fdd92023-10-04 20:05:05 +0200639
640 ImpVA = pPE->OptionalHeader
641 .DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].VirtualAddress;
642 if (ImpVA == 0)
643 return NULL; // No Import Table
644 pImpDesc = (PIMAGE_IMPORT_DESCRIPTOR)(pImage + ImpVA);
645
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100646 for (; pImpDesc->FirstThunk; ++pImpDesc)
647 {
648 if (!pImpDesc->OriginalFirstThunk)
649 continue;
650 pIAT = (PIMAGE_THUNK_DATA)(pImage + pImpDesc->FirstThunk);
651 pINT = (PIMAGE_THUNK_DATA)(pImage + pImpDesc->OriginalFirstThunk);
652 for (; pIAT->u1.Function; ++pIAT, ++pINT)
653 {
654 if (IMAGE_SNAP_BY_ORDINAL(pINT->u1.Ordinal))
655 continue;
656 pImpName = (PIMAGE_IMPORT_BY_NAME)(pImage
657 + (UINT_PTR)(pINT->u1.AddressOfData));
658 if (strcmp((char *)pImpName->Name, funcname) == 0)
659 {
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000660 void *original;
661 DWORD old, new = PAGE_READWRITE;
662
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100663 switch (info)
664 {
665 case 0:
666 return (void *)pIAT->u1.Function;
667 case 1:
668 return (void *)(pImage + pImpDesc->Name);
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000669 case 2:
670 original = (void *)pIAT->u1.Function;
671 VirtualProtect(&pIAT->u1.Function, sizeof(void *),
672 new, &old);
673 pIAT->u1.Function = (UINT_PTR)ptr;
674 VirtualProtect(&pIAT->u1.Function, sizeof(void *),
675 old, &new);
676 return original;
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100677 default:
678 return NULL;
679 }
680 }
681 }
682 }
683 return NULL;
684}
685
686/*
687 * Get the module handle which 'funcname' in 'hInst' is imported from.
688 */
689 HINSTANCE
690find_imported_module_by_funcname(HINSTANCE hInst, const char *funcname)
691{
692 char *modulename;
693
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000694 modulename = (char *)get_imported_func_info(hInst, funcname, 1, NULL);
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100695 if (modulename != NULL)
696 return GetModuleHandleA(modulename);
697 return NULL;
698}
699
700/*
701 * Get the address of 'funcname' which is imported by 'hInst' DLL.
702 */
703 void *
704get_dll_import_func(HINSTANCE hInst, const char *funcname)
705{
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000706 return get_imported_func_info(hInst, funcname, 0, NULL);
707}
708
709/*
710 * Hook the function named 'funcname' which is imported by 'hInst' DLL,
711 * and return the original function address.
712 */
713 void *
714hook_dll_import_func(HINSTANCE hInst, const char *funcname, const void *hook)
715{
716 return get_imported_func_info(hInst, funcname, 2, hook);
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100717}
718#endif
719
Ken Takata119fdd92023-10-04 20:05:05 +0200720#if defined(FEAT_PYTHON3) || defined(PROTO)
721/*
722 * Check if the specified DLL is a function forwarder.
723 * If yes, return the instance of the forwarded DLL.
724 * If no, return the specified DLL.
725 * If error, return NULL.
726 * This assumes that the DLL forwards all the function to a single DLL.
727 */
728 HINSTANCE
729get_forwarded_dll(HINSTANCE hInst)
730{
731 PBYTE pImage = (PBYTE)hInst;
732 PIMAGE_DOS_HEADER pDOS = (PIMAGE_DOS_HEADER)hInst;
733 PIMAGE_NT_HEADERS pPE;
734 PIMAGE_EXPORT_DIRECTORY pExpDir;
735 DWORD ExpVA;
736 DWORD ExpSize;
737 LPDWORD pFunctionTable;
738
739 if (pDOS->e_magic != IMAGE_DOS_SIGNATURE)
740 return NULL;
741 pPE = (PIMAGE_NT_HEADERS)(pImage + pDOS->e_lfanew);
742 if (pPE->Signature != IMAGE_NT_SIGNATURE)
743 return NULL;
744
745 ExpVA = pPE->OptionalHeader
746 .DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress;
747 ExpSize = pPE->OptionalHeader
748 .DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].Size;
749 if (ExpVA == 0)
750 return hInst; // No Export Directory
751 pExpDir = (PIMAGE_EXPORT_DIRECTORY)(pImage + ExpVA);
752 pFunctionTable = (LPDWORD)(pImage + pExpDir->AddressOfFunctions);
753
754 if (pExpDir->NumberOfNames == 0)
755 return hInst; // No export names.
756
757 // Check only the first entry.
758 if ((pFunctionTable[0] < ExpVA) || (pFunctionTable[0] >= ExpVA + ExpSize))
759 // The first entry is not a function forwarder.
760 return hInst;
761
762 // The first entry is a function forwarder.
763 // The name is represented as "DllName.FunctionName".
764 const char *name = (const char *)(pImage + pFunctionTable[0]);
765 const char *p = strchr(name, '.');
766 if (p == NULL)
767 return hInst;
768
769 // Extract DllName.
770 char buf[MAX_PATH];
771 if (p - name + 1 > sizeof(buf))
772 return NULL;
773 strncpy(buf, name, p - name);
774 buf[p - name] = '\0';
775 return GetModuleHandleA(buf);
776}
777#endif
778
Bram Moolenaar071d4272004-06-13 20:20:40 +0000779#if defined(DYNAMIC_GETTEXT) || defined(PROTO)
780# ifndef GETTEXT_DLL
781# define GETTEXT_DLL "libintl.dll"
Bram Moolenaar7554c542018-10-06 15:03:15 +0200782# define GETTEXT_DLL_ALT1 "libintl-8.dll"
783# define GETTEXT_DLL_ALT2 "intl.dll"
Bram Moolenaar071d4272004-06-13 20:20:40 +0000784# endif
Bram Moolenaar0f873732019-12-05 20:28:46 +0100785// Dummy functions
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000786static char *null_libintl_gettext(const char *);
Bram Moolenaaree695f72016-08-03 22:08:45 +0200787static char *null_libintl_ngettext(const char *, const char *, unsigned long n);
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000788static char *null_libintl_textdomain(const char *);
789static char *null_libintl_bindtextdomain(const char *, const char *);
790static char *null_libintl_bind_textdomain_codeset(const char *, const char *);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100791static int null_libintl_wputenv(const wchar_t *);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000792
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200793static HINSTANCE hLibintlDLL = NULL;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000794char *(*dyn_libintl_gettext)(const char *) = null_libintl_gettext;
Bram Moolenaaree695f72016-08-03 22:08:45 +0200795char *(*dyn_libintl_ngettext)(const char *, const char *, unsigned long n)
796 = null_libintl_ngettext;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000797char *(*dyn_libintl_textdomain)(const char *) = null_libintl_textdomain;
798char *(*dyn_libintl_bindtextdomain)(const char *, const char *)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000799 = null_libintl_bindtextdomain;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000800char *(*dyn_libintl_bind_textdomain_codeset)(const char *, const char *)
801 = null_libintl_bind_textdomain_codeset;
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100802int (*dyn_libintl_wputenv)(const wchar_t *) = null_libintl_wputenv;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000803
804 int
Bram Moolenaar05540972016-01-30 20:31:25 +0100805dyn_libintl_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000806{
807 int i;
808 static struct
809 {
810 char *name;
811 FARPROC *ptr;
812 } libintl_entry[] =
813 {
814 {"gettext", (FARPROC*)&dyn_libintl_gettext},
Bram Moolenaaree695f72016-08-03 22:08:45 +0200815 {"ngettext", (FARPROC*)&dyn_libintl_ngettext},
Bram Moolenaar071d4272004-06-13 20:20:40 +0000816 {"textdomain", (FARPROC*)&dyn_libintl_textdomain},
817 {"bindtextdomain", (FARPROC*)&dyn_libintl_bindtextdomain},
818 {NULL, NULL}
819 };
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100820 HINSTANCE hmsvcrt;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000821
Bram Moolenaar7554c542018-10-06 15:03:15 +0200822 // No need to initialize twice.
823 if (hLibintlDLL != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000824 return 1;
Bram Moolenaar7554c542018-10-06 15:03:15 +0200825 // Load gettext library (libintl.dll and other names).
Bram Moolenaar923e43b2016-01-28 15:07:38 +0100826 hLibintlDLL = vimLoadLib(GETTEXT_DLL);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100827# ifdef GETTEXT_DLL_ALT1
Bram Moolenaar286eacd2016-01-16 18:05:50 +0100828 if (!hLibintlDLL)
Bram Moolenaar7554c542018-10-06 15:03:15 +0200829 hLibintlDLL = vimLoadLib(GETTEXT_DLL_ALT1);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100830# endif
831# ifdef GETTEXT_DLL_ALT2
Bram Moolenaar7554c542018-10-06 15:03:15 +0200832 if (!hLibintlDLL)
833 hLibintlDLL = vimLoadLib(GETTEXT_DLL_ALT2);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100834# endif
Bram Moolenaar938ee832016-01-24 15:36:03 +0100835 if (!hLibintlDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000836 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200837 if (p_verbose > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000838 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200839 verbose_enter();
Bram Moolenaar460ae5d2022-01-01 14:19:49 +0000840 semsg(_(e_could_not_load_library_str_str), GETTEXT_DLL, GetWin32Error());
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200841 verbose_leave();
Bram Moolenaar071d4272004-06-13 20:20:40 +0000842 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200843 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000844 }
845 for (i = 0; libintl_entry[i].name != NULL
846 && libintl_entry[i].ptr != NULL; ++i)
847 {
K.Takata54119102022-02-03 13:33:03 +0000848 if ((*libintl_entry[i].ptr = GetProcAddress(hLibintlDLL,
Bram Moolenaar071d4272004-06-13 20:20:40 +0000849 libintl_entry[i].name)) == NULL)
850 {
851 dyn_libintl_end();
852 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +0000853 {
854 verbose_enter();
Bram Moolenaar460ae5d2022-01-01 14:19:49 +0000855 semsg(_(e_could_not_load_library_function_str), libintl_entry[i].name);
Bram Moolenaara04f10b2005-05-31 22:09:46 +0000856 verbose_leave();
857 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000858 return 0;
859 }
860 }
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000861
Bram Moolenaar0f873732019-12-05 20:28:46 +0100862 // The bind_textdomain_codeset() function is optional.
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +0100863 dyn_libintl_bind_textdomain_codeset = (char *(*)(const char *, const char *))
864 GetProcAddress(hLibintlDLL, "bind_textdomain_codeset");
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000865 if (dyn_libintl_bind_textdomain_codeset == NULL)
866 dyn_libintl_bind_textdomain_codeset =
867 null_libintl_bind_textdomain_codeset;
868
Bram Moolenaar0f873732019-12-05 20:28:46 +0100869 // _wputenv() function for the libintl.dll is optional.
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100870 hmsvcrt = find_imported_module_by_funcname(hLibintlDLL, "getenv");
871 if (hmsvcrt != NULL)
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +0100872 dyn_libintl_wputenv = (int (*)(const wchar_t *))
873 GetProcAddress(hmsvcrt, "_wputenv");
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100874 if (dyn_libintl_wputenv == NULL || dyn_libintl_wputenv == _wputenv)
875 dyn_libintl_wputenv = null_libintl_wputenv;
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100876
Bram Moolenaar071d4272004-06-13 20:20:40 +0000877 return 1;
878}
879
880 void
Bram Moolenaar05540972016-01-30 20:31:25 +0100881dyn_libintl_end(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000882{
883 if (hLibintlDLL)
884 FreeLibrary(hLibintlDLL);
885 hLibintlDLL = NULL;
886 dyn_libintl_gettext = null_libintl_gettext;
Bram Moolenaaree695f72016-08-03 22:08:45 +0200887 dyn_libintl_ngettext = null_libintl_ngettext;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000888 dyn_libintl_textdomain = null_libintl_textdomain;
889 dyn_libintl_bindtextdomain = null_libintl_bindtextdomain;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000890 dyn_libintl_bind_textdomain_codeset = null_libintl_bind_textdomain_codeset;
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100891 dyn_libintl_wputenv = null_libintl_wputenv;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000892}
893
894 static char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000895null_libintl_gettext(const char *msgid)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000896{
897 return (char*)msgid;
898}
899
900 static char *
Bram Moolenaaree695f72016-08-03 22:08:45 +0200901null_libintl_ngettext(
902 const char *msgid,
903 const char *msgid_plural,
904 unsigned long n)
905{
Bram Moolenaarc90f2ae2016-08-04 22:00:15 +0200906 return (char *)(n == 1 ? msgid : msgid_plural);
Bram Moolenaaree695f72016-08-03 22:08:45 +0200907}
908
Bram Moolenaaree695f72016-08-03 22:08:45 +0200909 static char *
Bram Moolenaar1266d672017-02-01 13:43:36 +0100910null_libintl_bindtextdomain(
911 const char *domainname UNUSED,
912 const char *dirname UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000913{
914 return NULL;
915}
916
917 static char *
Bram Moolenaar1266d672017-02-01 13:43:36 +0100918null_libintl_bind_textdomain_codeset(
919 const char *domainname UNUSED,
920 const char *codeset UNUSED)
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000921{
922 return NULL;
923}
924
925 static char *
Bram Moolenaar1266d672017-02-01 13:43:36 +0100926null_libintl_textdomain(const char *domainname UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000927{
928 return NULL;
929}
930
Bram Moolenaare0ab9792017-08-02 23:18:25 +0200931 static int
Bram Moolenaar1266d672017-02-01 13:43:36 +0100932null_libintl_wputenv(const wchar_t *envstring UNUSED)
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100933{
934 return 0;
935}
936
Bram Moolenaar0f873732019-12-05 20:28:46 +0100937#endif // DYNAMIC_GETTEXT
Bram Moolenaar071d4272004-06-13 20:20:40 +0000938
Bram Moolenaar0f873732019-12-05 20:28:46 +0100939// This symbol is not defined in older versions of the SDK or Visual C++
Bram Moolenaar071d4272004-06-13 20:20:40 +0000940
941#ifndef VER_PLATFORM_WIN32_WINDOWS
942# define VER_PLATFORM_WIN32_WINDOWS 1
943#endif
944
Bram Moolenaar071d4272004-06-13 20:20:40 +0000945#ifdef HAVE_ACL
Bram Moolenaar82881492012-11-20 16:53:39 +0100946# ifndef PROTO
947# include <aclapi.h>
948# endif
Bram Moolenaar27515922013-06-29 15:36:26 +0200949# ifndef PROTECTED_DACL_SECURITY_INFORMATION
950# define PROTECTED_DACL_SECURITY_INFORMATION 0x80000000L
951# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000952#endif
953
Bram Moolenaar27515922013-06-29 15:36:26 +0200954#ifdef HAVE_ACL
955/*
956 * Enables or disables the specified privilege.
957 */
958 static BOOL
959win32_enable_privilege(LPTSTR lpszPrivilege, BOOL bEnable)
960{
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100961 BOOL bResult;
962 LUID luid;
963 HANDLE hToken;
964 TOKEN_PRIVILEGES tokenPrivileges;
Bram Moolenaar27515922013-06-29 15:36:26 +0200965
966 if (!OpenProcessToken(GetCurrentProcess(),
967 TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
968 return FALSE;
969
970 if (!LookupPrivilegeValue(NULL, lpszPrivilege, &luid))
971 {
972 CloseHandle(hToken);
973 return FALSE;
974 }
975
Bram Moolenaar45500912014-07-09 20:51:07 +0200976 tokenPrivileges.PrivilegeCount = 1;
Bram Moolenaar27515922013-06-29 15:36:26 +0200977 tokenPrivileges.Privileges[0].Luid = luid;
978 tokenPrivileges.Privileges[0].Attributes = bEnable ?
979 SE_PRIVILEGE_ENABLED : 0;
980
981 bResult = AdjustTokenPrivileges(hToken, FALSE, &tokenPrivileges,
982 sizeof(TOKEN_PRIVILEGES), NULL, NULL);
983
984 CloseHandle(hToken);
985
986 return bResult && GetLastError() == ERROR_SUCCESS;
987}
988#endif
989
Bram Moolenaar29d2f452020-12-04 19:42:52 +0100990#ifdef _MSC_VER
991// Suppress the deprecation warning for using GetVersionEx().
992// It is needed for implementing "windowsversion()".
993# pragma warning(push)
994# pragma warning(disable: 4996)
995#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000996/*
Bram Moolenaar1e1d2e82020-05-18 20:17:02 +0200997 * Set "win8_or_later" and fill in "windowsVersion" if possible.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000998 */
999 void
1000PlatformId(void)
1001{
1002 static int done = FALSE;
1003
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00001004 if (done)
1005 return;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001006
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00001007 OSVERSIONINFO ovi;
1008
1009 ovi.dwOSVersionInfoSize = sizeof(ovi);
1010 GetVersionEx(&ovi);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001011
Bram Moolenaar1e1d2e82020-05-18 20:17:02 +02001012#ifdef FEAT_EVAL
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00001013 vim_snprintf(windowsVersion, sizeof(windowsVersion), "%d.%d",
1014 (int)ovi.dwMajorVersion, (int)ovi.dwMinorVersion);
Bram Moolenaar1e1d2e82020-05-18 20:17:02 +02001015#endif
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00001016 if ((ovi.dwMajorVersion == 6 && ovi.dwMinorVersion >= 2)
1017 || ovi.dwMajorVersion > 6)
1018 win8_or_later = TRUE;
Bram Moolenaarf50eb782014-02-05 13:36:54 +01001019
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00001020 if ((ovi.dwMajorVersion == 10 && ovi.dwBuildNumber >= 19045)
1021 || ovi.dwMajorVersion > 10)
1022 win10_22H2_or_later = TRUE;
Christopher Plewright1140b512022-11-12 18:46:05 +00001023
Bram Moolenaar071d4272004-06-13 20:20:40 +00001024#ifdef HAVE_ACL
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00001025 // Enable privilege for getting or setting SACLs.
1026 win32_enable_privilege(SE_SECURITY_NAME, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001027#endif
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00001028 done = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001029}
Bram Moolenaar29d2f452020-12-04 19:42:52 +01001030#ifdef _MSC_VER
1031# pragma warning(pop)
1032#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001033
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001034#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001035
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001036# define SHIFT (SHIFT_PRESSED)
1037# define CTRL (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED)
1038# define ALT (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED)
1039# define ALT_GR (RIGHT_ALT_PRESSED | LEFT_CTRL_PRESSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001040
1041
Bram Moolenaar0f873732019-12-05 20:28:46 +01001042// When uChar.AsciiChar is 0, then we need to look at wVirtualKeyCode.
1043// We map function keys to their ANSI terminal equivalents, as produced
1044// by ANSI.SYS, for compatibility with the MS-DOS version of Vim. Any
1045// ANSI key with a value >= '\300' is nonstandard, but provided anyway
1046// so that the user can have access to all SHIFT-, CTRL-, and ALT-
1047// combinations of function/arrow/etc keys.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001048
Bram Moolenaard6f676d2005-06-01 21:51:55 +00001049static const struct
Bram Moolenaar071d4272004-06-13 20:20:40 +00001050{
1051 WORD wVirtKey;
1052 BOOL fAnsiKey;
1053 int chAlone;
1054 int chShift;
1055 int chCtrl;
1056 int chAlt;
1057} VirtKeyMap[] =
1058{
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +02001059// Key ANSI alone shift ctrl alt
Bram Moolenaar071d4272004-06-13 20:20:40 +00001060 { VK_ESCAPE,FALSE, ESC, ESC, ESC, ESC, },
1061
1062 { VK_F1, TRUE, ';', 'T', '^', 'h', },
1063 { VK_F2, TRUE, '<', 'U', '_', 'i', },
1064 { VK_F3, TRUE, '=', 'V', '`', 'j', },
1065 { VK_F4, TRUE, '>', 'W', 'a', 'k', },
1066 { VK_F5, TRUE, '?', 'X', 'b', 'l', },
1067 { VK_F6, TRUE, '@', 'Y', 'c', 'm', },
1068 { VK_F7, TRUE, 'A', 'Z', 'd', 'n', },
1069 { VK_F8, TRUE, 'B', '[', 'e', 'o', },
1070 { VK_F9, TRUE, 'C', '\\', 'f', 'p', },
1071 { VK_F10, TRUE, 'D', ']', 'g', 'q', },
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +02001072 { VK_F11, TRUE, '\205', '\207', '\211', '\213', },
1073 { VK_F12, TRUE, '\206', '\210', '\212', '\214', },
Bram Moolenaar071d4272004-06-13 20:20:40 +00001074
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +02001075 { VK_HOME, TRUE, 'G', '\302', 'w', '\303', },
1076 { VK_UP, TRUE, 'H', '\304', '\305', '\306', },
1077 { VK_PRIOR, TRUE, 'I', '\307', '\204', '\310', }, // PgUp
1078 { VK_LEFT, TRUE, 'K', '\311', 's', '\312', },
1079 { VK_RIGHT, TRUE, 'M', '\313', 't', '\314', },
1080 { VK_END, TRUE, 'O', '\315', 'u', '\316', },
1081 { VK_DOWN, TRUE, 'P', '\317', '\320', '\321', },
1082 { VK_NEXT, TRUE, 'Q', '\322', 'v', '\323', }, // PgDn
1083 { VK_INSERT,TRUE, 'R', '\324', '\325', '\326', },
1084 { VK_DELETE,TRUE, 'S', '\327', '\330', '\331', },
Bram Moolenaarb70a47b2019-03-30 22:11:21 +01001085 { VK_BACK, TRUE, 'x', 'y', 'z', '{', }, // Backspace
Bram Moolenaar071d4272004-06-13 20:20:40 +00001086
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +02001087 { VK_SNAPSHOT,TRUE, 0, 0, 0, 'r', }, // PrtScrn
Bram Moolenaar071d4272004-06-13 20:20:40 +00001088
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001089# if 0
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +02001090 // Most people don't have F13-F20, but what the hell...
1091 { VK_F13, TRUE, '\332', '\333', '\334', '\335', },
1092 { VK_F14, TRUE, '\336', '\337', '\340', '\341', },
1093 { VK_F15, TRUE, '\342', '\343', '\344', '\345', },
1094 { VK_F16, TRUE, '\346', '\347', '\350', '\351', },
1095 { VK_F17, TRUE, '\352', '\353', '\354', '\355', },
1096 { VK_F18, TRUE, '\356', '\357', '\360', '\361', },
1097 { VK_F19, TRUE, '\362', '\363', '\364', '\365', },
1098 { VK_F20, TRUE, '\366', '\367', '\370', '\371', },
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001099# endif
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +02001100 { VK_ADD, TRUE, 'N', 'N', 'N', 'N', }, // keyp '+'
1101 { VK_SUBTRACT, TRUE,'J', 'J', 'J', 'J', }, // keyp '-'
1102 // { VK_DIVIDE, TRUE,'N', 'N', 'N', 'N', }, // keyp '/'
1103 { VK_MULTIPLY, TRUE,'7', '7', '7', '7', }, // keyp '*'
Bram Moolenaar071d4272004-06-13 20:20:40 +00001104
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +02001105 { VK_NUMPAD0,TRUE, '\332', '\333', '\334', '\335', },
1106 { VK_NUMPAD1,TRUE, '\336', '\337', '\340', '\341', },
1107 { VK_NUMPAD2,TRUE, '\342', '\343', '\344', '\345', },
1108 { VK_NUMPAD3,TRUE, '\346', '\347', '\350', '\351', },
1109 { VK_NUMPAD4,TRUE, '\352', '\353', '\354', '\355', },
1110 { VK_NUMPAD5,TRUE, '\356', '\357', '\360', '\361', },
1111 { VK_NUMPAD6,TRUE, '\362', '\363', '\364', '\365', },
1112 { VK_NUMPAD7,TRUE, '\366', '\367', '\370', '\371', },
1113 { VK_NUMPAD8,TRUE, '\372', '\373', '\374', '\375', },
1114 // Sorry, out of number space! <negri>
Bram Moolenaarb70a47b2019-03-30 22:11:21 +01001115 { VK_NUMPAD9,TRUE, '\376', '\377', '|', '}', },
Bram Moolenaar071d4272004-06-13 20:20:40 +00001116};
1117
1118
Bram Moolenaar0f873732019-12-05 20:28:46 +01001119/*
1120 * The return code indicates key code size.
1121 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001122 static int
Bram Moolenaar071d4272004-06-13 20:20:40 +00001123win32_kbd_patch_key(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001124 KEY_EVENT_RECORD *pker)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001125{
1126 UINT uMods = pker->dwControlKeyState;
1127 static int s_iIsDead = 0;
1128 static WORD awAnsiCode[2];
1129 static BYTE abKeystate[256];
1130
1131
1132 if (s_iIsDead == 2)
1133 {
K.Takata972db232022-02-04 10:45:38 +00001134 pker->uChar.UnicodeChar = (WCHAR) awAnsiCode[1];
Bram Moolenaar071d4272004-06-13 20:20:40 +00001135 s_iIsDead = 0;
1136 return 1;
1137 }
1138
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001139 // check if it already has a valid unicode character.
Christopher Plewright566f76e2023-01-10 13:43:04 +00001140 if (pker->uChar.UnicodeChar != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001141 return 1;
1142
Bram Moolenaara80faa82020-04-12 19:37:17 +02001143 CLEAR_FIELD(abKeystate);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001144
Bram Moolenaar0f873732019-12-05 20:28:46 +01001145 // Clear any pending dead keys
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001146 ToUnicode(VK_SPACE, MapVirtualKey(VK_SPACE, 0), abKeystate, awAnsiCode, 2, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001147
1148 if (uMods & SHIFT_PRESSED)
1149 abKeystate[VK_SHIFT] = 0x80;
1150 if (uMods & CAPSLOCK_ON)
1151 abKeystate[VK_CAPITAL] = 1;
1152
1153 if ((uMods & ALT_GR) == ALT_GR)
1154 {
1155 abKeystate[VK_CONTROL] = abKeystate[VK_LCONTROL] =
1156 abKeystate[VK_MENU] = abKeystate[VK_RMENU] = 0x80;
1157 }
1158
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001159 s_iIsDead = ToUnicode(pker->wVirtualKeyCode, pker->wVirtualScanCode,
1160 abKeystate, awAnsiCode, 2, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001161
1162 if (s_iIsDead > 0)
K.Takata972db232022-02-04 10:45:38 +00001163 pker->uChar.UnicodeChar = (WCHAR) awAnsiCode[0];
Bram Moolenaar071d4272004-06-13 20:20:40 +00001164
1165 return s_iIsDead;
1166}
1167
Bram Moolenaar071d4272004-06-13 20:20:40 +00001168static BOOL g_fJustGotFocus = FALSE;
1169
1170/*
1171 * Decode a KEY_EVENT into one or two keystrokes
1172 */
1173 static BOOL
1174decode_key_event(
1175 KEY_EVENT_RECORD *pker,
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001176 WCHAR *pch,
1177 WCHAR *pch2,
Bram Moolenaar071d4272004-06-13 20:20:40 +00001178 int *pmodifiers,
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02001179 BOOL fDoPost UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001180{
1181 int i;
1182 const int nModifs = pker->dwControlKeyState & (SHIFT | ALT | CTRL);
1183
1184 *pch = *pch2 = NUL;
1185 g_fJustGotFocus = FALSE;
1186
Bram Moolenaar0f873732019-12-05 20:28:46 +01001187 // ignore key up events
Bram Moolenaar071d4272004-06-13 20:20:40 +00001188 if (!pker->bKeyDown)
1189 return FALSE;
1190
Bram Moolenaar0f873732019-12-05 20:28:46 +01001191 // ignore some keystrokes
Bram Moolenaar071d4272004-06-13 20:20:40 +00001192 switch (pker->wVirtualKeyCode)
1193 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001194 // modifiers
Bram Moolenaar071d4272004-06-13 20:20:40 +00001195 case VK_SHIFT:
1196 case VK_CONTROL:
Bram Moolenaar0f873732019-12-05 20:28:46 +01001197 case VK_MENU: // Alt key
Bram Moolenaar071d4272004-06-13 20:20:40 +00001198 return FALSE;
1199
1200 default:
1201 break;
1202 }
1203
Bram Moolenaar0f873732019-12-05 20:28:46 +01001204 // Shift-TAB
Bram Moolenaar071d4272004-06-13 20:20:40 +00001205 if (pker->wVirtualKeyCode == VK_TAB && (nModifs & SHIFT_PRESSED))
1206 {
1207 *pch = K_NUL;
1208 *pch2 = '\017';
1209 return TRUE;
1210 }
1211
K.Takataeeec2542021-06-02 13:28:16 +02001212 for (i = ARRAY_LENGTH(VirtKeyMap); --i >= 0; )
Bram Moolenaar071d4272004-06-13 20:20:40 +00001213 {
1214 if (VirtKeyMap[i].wVirtKey == pker->wVirtualKeyCode)
1215 {
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001216 *pch = VirtKeyMap[i].chAlone;
1217 if ((nModifs & SHIFT) != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001218 *pch = VirtKeyMap[i].chShift;
1219 else if ((nModifs & CTRL) != 0 && (nModifs & ~CTRL) == 0)
1220 *pch = VirtKeyMap[i].chCtrl;
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001221 else if ((nModifs & ALT) != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001222 *pch = VirtKeyMap[i].chAlt;
1223
1224 if (*pch != 0)
1225 {
1226 if (VirtKeyMap[i].fAnsiKey)
1227 {
1228 *pch2 = *pch;
1229 *pch = K_NUL;
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001230 if (pmodifiers)
1231 {
1232 if (pker->wVirtualKeyCode >= VK_F1
1233 && pker->wVirtualKeyCode <= VK_F12)
1234 {
1235 if ((nModifs & ALT) != 0)
1236 {
1237 *pmodifiers |= MOD_MASK_ALT;
1238 if ((nModifs & SHIFT) == 0)
1239 *pch2 = VirtKeyMap[i].chAlone;
1240 }
1241 if ((nModifs & CTRL) != 0)
1242 {
1243 *pmodifiers |= MOD_MASK_CTRL;
1244 if ((nModifs & SHIFT) == 0)
1245 *pch2 = VirtKeyMap[i].chAlone;
1246 }
1247 }
1248 else if (pker->wVirtualKeyCode >= VK_END
1249 && pker->wVirtualKeyCode <= VK_DOWN)
1250 {
Christopher Plewright566f76e2023-01-10 13:43:04 +00001251 // (0x23 - 0x28): VK_END, VK_HOME,
1252 // VK_LEFT, VK_UP, VK_RIGHT, VK_DOWN
1253
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001254 *pmodifiers = 0;
1255 *pch2 = VirtKeyMap[i].chAlone;
1256 if ((nModifs & SHIFT) != 0
1257 && (nModifs & ~SHIFT) == 0)
1258 {
1259 *pch2 = VirtKeyMap[i].chShift;
1260 }
Christopher Plewright566f76e2023-01-10 13:43:04 +00001261 if ((nModifs & CTRL) != 0
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001262 && (nModifs & ~CTRL) == 0)
1263 {
1264 *pch2 = VirtKeyMap[i].chCtrl;
1265 if (pker->wVirtualKeyCode == VK_UP
1266 || pker->wVirtualKeyCode == VK_DOWN)
1267 {
1268 *pmodifiers |= MOD_MASK_CTRL;
1269 *pch2 = VirtKeyMap[i].chAlone;
1270 }
1271 }
Christopher Plewright566f76e2023-01-10 13:43:04 +00001272 if ((nModifs & SHIFT) != 0
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001273 && (nModifs & CTRL) != 0)
1274 {
1275 *pmodifiers |= MOD_MASK_CTRL;
1276 *pch2 = VirtKeyMap[i].chShift;
1277 }
Christopher Plewright566f76e2023-01-10 13:43:04 +00001278 if ((nModifs & ALT) != 0)
1279 {
1280 *pch2 = VirtKeyMap[i].chAlt;
1281 *pmodifiers |= MOD_MASK_ALT;
1282 if ((nModifs & ~ALT) == 0)
1283 {
1284 *pch2 = VirtKeyMap[i].chAlone;
1285 }
1286 else if ((nModifs & SHIFT) != 0)
1287 {
1288 *pch2 = VirtKeyMap[i].chShift;
1289 }
1290 else if ((nModifs & CTRL) != 0)
1291 {
1292 if (pker->wVirtualKeyCode == VK_UP
1293 || pker->wVirtualKeyCode == VK_DOWN)
1294 {
1295 *pmodifiers |= MOD_MASK_CTRL;
1296 *pch2 = VirtKeyMap[i].chAlone;
1297 }
1298 else
1299 {
1300 *pch2 = VirtKeyMap[i].chCtrl;
1301 }
1302 }
1303 }
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001304 }
1305 else
1306 {
1307 *pch2 = VirtKeyMap[i].chAlone;
1308 if ((nModifs & SHIFT) != 0)
1309 *pmodifiers |= MOD_MASK_SHIFT;
1310 if ((nModifs & CTRL) != 0)
1311 *pmodifiers |= MOD_MASK_CTRL;
1312 if ((nModifs & ALT) != 0)
1313 *pmodifiers |= MOD_MASK_ALT;
1314 }
1315 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001316 }
1317
1318 return TRUE;
1319 }
1320 }
1321 }
1322
1323 i = win32_kbd_patch_key(pker);
1324
1325 if (i < 0)
1326 *pch = NUL;
1327 else
1328 {
K.Takata972db232022-02-04 10:45:38 +00001329 *pch = (i > 0) ? pker->uChar.UnicodeChar : NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001330
1331 if (pmodifiers != NULL)
1332 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001333 // Pass on the ALT key as a modifier, but only when not combined
1334 // with CTRL (which is ALTGR).
Bram Moolenaar071d4272004-06-13 20:20:40 +00001335 if ((nModifs & ALT) != 0 && (nModifs & CTRL) == 0)
1336 *pmodifiers |= MOD_MASK_ALT;
1337
Bram Moolenaar0f873732019-12-05 20:28:46 +01001338 // Pass on SHIFT only for special keys, because we don't know when
1339 // it's already included with the character.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001340 if ((nModifs & SHIFT) != 0 && *pch <= 0x20)
1341 *pmodifiers |= MOD_MASK_SHIFT;
1342
Bram Moolenaar0f873732019-12-05 20:28:46 +01001343 // Pass on CTRL only for non-special keys, because we don't know
1344 // when it's already included with the character. And not when
1345 // combined with ALT (which is ALTGR).
Bram Moolenaar071d4272004-06-13 20:20:40 +00001346 if ((nModifs & CTRL) != 0 && (nModifs & ALT) == 0
1347 && *pch >= 0x20 && *pch < 0x80)
1348 *pmodifiers |= MOD_MASK_CTRL;
1349 }
1350 }
1351
1352 return (*pch != NUL);
1353}
1354
Christopher Plewright20b795e2022-12-20 20:01:58 +00001355# if defined(FEAT_EVAL)
1356 static int
1357encode_key_event(dict_T *args, INPUT_RECORD *ir)
1358{
1359 static int s_dwMods = 0;
1360
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001361 char_u *action = dict_get_string(args, "event", TRUE);
1362 if (action && (STRICMP(action, "keydown") == 0
1363 || STRICMP(action, "keyup") == 0))
Christopher Plewright20b795e2022-12-20 20:01:58 +00001364 {
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001365 BOOL isKeyDown = STRICMP(action, "keydown") == 0;
Christopher Plewright20b795e2022-12-20 20:01:58 +00001366 WORD vkCode = dict_get_number_def(args, "keycode", 0);
1367 if (vkCode <= 0 || vkCode >= 0xFF)
1368 {
1369 semsg(_(e_invalid_argument_nr), (long)vkCode);
1370 return FALSE;
1371 }
1372
1373 ir->EventType = KEY_EVENT;
1374 KEY_EVENT_RECORD ker;
1375 ZeroMemory(&ker, sizeof(ker));
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001376 ker.bKeyDown = isKeyDown;
Christopher Plewright20b795e2022-12-20 20:01:58 +00001377 ker.wRepeatCount = 1;
1378 ker.wVirtualScanCode = 0;
1379 ker.dwControlKeyState = 0;
1380 int mods = (int)dict_get_number(args, "modifiers");
1381 // Encode the win32 console key modifiers from Vim keyboard modifiers.
1382 if (mods)
1383 {
1384 // If "modifiers" is explicitly set in the args, then we reset any
Yegappan Lakshmanan14113fd2023-03-07 17:13:51 +00001385 // remembered modifier key state that may have been set from
1386 // earlier mod-key-down events, even if they are not yet unset by
1387 // earlier mod-key-up events.
Christopher Plewright20b795e2022-12-20 20:01:58 +00001388 s_dwMods = 0;
1389 if (mods & MOD_MASK_SHIFT)
1390 ker.dwControlKeyState |= SHIFT_PRESSED;
1391 if (mods & MOD_MASK_CTRL)
1392 ker.dwControlKeyState |= LEFT_CTRL_PRESSED;
1393 if (mods & MOD_MASK_ALT)
1394 ker.dwControlKeyState |= LEFT_ALT_PRESSED;
1395 }
1396
1397 if (vkCode == VK_LSHIFT || vkCode == VK_RSHIFT || vkCode == VK_SHIFT)
1398 {
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001399 if (isKeyDown)
Christopher Plewright20b795e2022-12-20 20:01:58 +00001400 s_dwMods |= SHIFT_PRESSED;
1401 else
1402 s_dwMods &= ~SHIFT_PRESSED;
1403 }
1404 else if (vkCode == VK_LCONTROL || vkCode == VK_CONTROL)
1405 {
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001406 if (isKeyDown)
Christopher Plewright20b795e2022-12-20 20:01:58 +00001407 s_dwMods |= LEFT_CTRL_PRESSED;
1408 else
1409 s_dwMods &= ~LEFT_CTRL_PRESSED;
1410 }
1411 else if (vkCode == VK_RCONTROL)
1412 {
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001413 if (isKeyDown)
Christopher Plewright20b795e2022-12-20 20:01:58 +00001414 s_dwMods |= RIGHT_CTRL_PRESSED;
1415 else
1416 s_dwMods &= ~RIGHT_CTRL_PRESSED;
1417 }
1418 else if (vkCode == VK_LMENU || vkCode == VK_MENU)
1419 {
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001420 if (isKeyDown)
Christopher Plewright20b795e2022-12-20 20:01:58 +00001421 s_dwMods |= LEFT_ALT_PRESSED;
1422 else
1423 s_dwMods &= ~LEFT_ALT_PRESSED;
1424 }
1425 else if (vkCode == VK_RMENU)
1426 {
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001427 if (isKeyDown)
Christopher Plewright20b795e2022-12-20 20:01:58 +00001428 s_dwMods |= RIGHT_ALT_PRESSED;
1429 else
1430 s_dwMods &= ~RIGHT_ALT_PRESSED;
1431 }
1432 ker.dwControlKeyState |= s_dwMods;
1433 ker.wVirtualKeyCode = vkCode;
Christopher Plewright566f76e2023-01-10 13:43:04 +00001434 ker.uChar.UnicodeChar = 0;
Christopher Plewright20b795e2022-12-20 20:01:58 +00001435 ir->Event.KeyEvent = ker;
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001436 vim_free(action);
Christopher Plewright20b795e2022-12-20 20:01:58 +00001437 }
1438 else
1439 {
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001440 if (action == NULL)
Christopher Plewright20b795e2022-12-20 20:01:58 +00001441 {
1442 semsg(_(e_missing_argument_str), "event");
1443 }
1444 else
1445 {
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001446 semsg(_(e_invalid_value_for_argument_str_str), "event", action);
1447 vim_free(action);
Christopher Plewright20b795e2022-12-20 20:01:58 +00001448 }
1449 return FALSE;
1450 }
1451 return TRUE;
1452}
1453# endif // FEAT_EVAL
1454#endif // !FEAT_GUI_MSWIN || VIMDLL
Bram Moolenaar071d4272004-06-13 20:20:40 +00001455
1456
Bram Moolenaar071d4272004-06-13 20:20:40 +00001457/*
1458 * For the GUI the mouse handling is in gui_w32.c.
1459 */
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001460#if defined(FEAT_GUI_MSWIN) && !defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001461 void
Bram Moolenaar1266d672017-02-01 13:43:36 +01001462mch_setmouse(int on UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001463{
1464}
Christopher Plewright20b795e2022-12-20 20:01:58 +00001465#else // !FEAT_GUI_MSWIN || VIMDLL
Bram Moolenaar0f873732019-12-05 20:28:46 +01001466static int g_fMouseAvail = FALSE; // mouse present
1467static int g_fMouseActive = FALSE; // mouse enabled
1468static int g_nMouseClick = -1; // mouse status
1469static int g_xMouse; // mouse x coordinate
1470static int g_yMouse; // mouse y coordinate
Bram Moolenaar9f1983d2022-05-12 20:35:35 +01001471static DWORD g_cmodein = 0; // Original console input mode
1472static DWORD g_cmodeout = 0; // Original console output mode
Bram Moolenaar071d4272004-06-13 20:20:40 +00001473
1474/*
1475 * Enable or disable mouse input
1476 */
1477 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001478mch_setmouse(int on)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001479{
1480 DWORD cmodein;
1481
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001482# ifdef VIMDLL
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001483 if (gui.in_use)
1484 return;
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001485# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001486 if (!g_fMouseAvail)
1487 return;
1488
1489 g_fMouseActive = on;
1490 GetConsoleMode(g_hConIn, &cmodein);
1491
1492 if (g_fMouseActive)
Wez Furlong6ef5ab52021-05-30 19:29:41 +02001493 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00001494 cmodein |= ENABLE_MOUSE_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02001495 cmodein &= ~ENABLE_QUICK_EDIT_MODE;
1496 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001497 else
Wez Furlong6ef5ab52021-05-30 19:29:41 +02001498 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00001499 cmodein &= ~ENABLE_MOUSE_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02001500 cmodein |= g_cmodein & ENABLE_QUICK_EDIT_MODE;
1501 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001502
Wez Furlong6ef5ab52021-05-30 19:29:41 +02001503 SetConsoleMode(g_hConIn, cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001504}
1505
Bram Moolenaar157d8132018-03-06 17:09:20 +01001506
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001507# if defined(FEAT_BEVAL_TERM) || defined(PROTO)
Bram Moolenaar157d8132018-03-06 17:09:20 +01001508/*
1509 * Called when 'balloonevalterm' changed.
1510 */
1511 void
1512mch_bevalterm_changed(void)
1513{
1514 mch_setmouse(g_fMouseActive);
1515}
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001516# endif
Bram Moolenaar157d8132018-03-06 17:09:20 +01001517
Christopher Plewright2a46f812022-10-16 19:47:45 +01001518/*
1519 * Win32 console mouse scroll event handler.
Christopher Plewright20b795e2022-12-20 20:01:58 +00001520 * Console version of the _OnMouseWheel() function in gui_w32.c
Christopher Plewright2a46f812022-10-16 19:47:45 +01001521 *
1522 * This encodes the mouse scroll direction and keyboard modifiers into
1523 * g_nMouseClick, and the mouse position into g_xMouse and g_yMouse
1524 *
1525 * The direction of the scroll is decoded from two fields of the win32 console
1526 * mouse event record;
Christopher Plewright20b795e2022-12-20 20:01:58 +00001527 * 1. The orientation - vertical or horizontal flag - from dwEventFlags
Christopher Plewright2a46f812022-10-16 19:47:45 +01001528 * 2. The sign - positive or negative (aka delta flag) - from dwButtonState
1529 *
Christopher Plewright20b795e2022-12-20 20:01:58 +00001530 * When scroll orientation is HORIZONTAL
Christopher Plewright2a46f812022-10-16 19:47:45 +01001531 * - If the high word of the dwButtonState member contains a positive
1532 * value, the wheel was rotated to the right.
1533 * - Otherwise, the wheel was rotated to the left.
Christopher Plewright20b795e2022-12-20 20:01:58 +00001534 * When scroll orientation is VERTICAL
Christopher Plewright2a46f812022-10-16 19:47:45 +01001535 * - If the high word of the dwButtonState member contains a positive value,
1536 * the wheel was rotated forward, away from the user.
1537 * - Otherwise, the wheel was rotated backward, toward the user.
1538 */
1539 static void
1540decode_mouse_wheel(MOUSE_EVENT_RECORD *pmer)
1541{
Christopher Plewright2a46f812022-10-16 19:47:45 +01001542 int horizontal = (pmer->dwEventFlags == MOUSE_HWHEELED);
1543 int zDelta = pmer->dwButtonState;
1544
1545 g_xMouse = pmer->dwMousePosition.X;
1546 g_yMouse = pmer->dwMousePosition.Y;
1547
K.Takata161b6ac2022-11-14 15:31:07 +00001548# ifdef FEAT_PROP_POPUP
Christopher Plewright605d02a2022-10-19 11:54:46 +01001549 int lcol = g_xMouse;
1550 int lrow = g_yMouse;
Christopher Plewright38804d62022-11-09 23:55:52 +00001551 win_T *wp = mouse_find_win(&lrow, &lcol, FIND_POPUP);
Christopher Plewright2a46f812022-10-16 19:47:45 +01001552 if (wp != NULL && popup_is_popup(wp))
1553 {
1554 g_nMouseClick = -1;
1555 cmdarg_T cap;
1556 oparg_T oa;
1557 CLEAR_FIELD(cap);
1558 clear_oparg(&oa);
1559 cap.oap = &oa;
1560 if (horizontal)
1561 {
1562 cap.arg = zDelta < 0 ? MSCR_LEFT : MSCR_RIGHT;
1563 cap.cmdchar = zDelta < 0 ? K_MOUSELEFT : K_MOUSERIGHT;
1564 }
1565 else
1566 {
1567 cap.cmdchar = zDelta < 0 ? K_MOUSEUP : K_MOUSEDOWN;
1568 cap.arg = zDelta < 0 ? MSCR_UP : MSCR_DOWN;
1569 }
1570
1571 // Mouse hovers over popup window, scroll it if possible.
1572 mouse_row = wp->w_winrow;
1573 mouse_col = wp->w_wincol;
1574 nv_mousescroll(&cap);
1575 update_screen(0);
1576 setcursor();
1577 out_flush();
1578 return;
1579 }
K.Takata161b6ac2022-11-14 15:31:07 +00001580# endif
Christopher Plewright2a46f812022-10-16 19:47:45 +01001581 mouse_col = g_xMouse;
1582 mouse_row = g_yMouse;
1583
1584 char_u modifiers = 0;
1585 char_u direction = 0;
1586
1587 // Decode the direction into an event that Vim can process
1588 if (horizontal)
1589 direction = zDelta >= 0 ? KE_MOUSELEFT : KE_MOUSERIGHT;
1590 else
1591 direction = zDelta >= 0 ? KE_MOUSEDOWN : KE_MOUSEUP;
1592
dundargocc57b5bc2022-11-02 13:30:51 +00001593 // Decode the win32 console key modifiers into Vim mouse modifiers.
Christopher Plewright2a46f812022-10-16 19:47:45 +01001594 if (pmer->dwControlKeyState & SHIFT_PRESSED)
Christopher Plewright605d02a2022-10-19 11:54:46 +01001595 modifiers |= MOD_MASK_SHIFT; // MOUSE_SHIFT;
Christopher Plewright2a46f812022-10-16 19:47:45 +01001596 if (pmer->dwControlKeyState & (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED))
Christopher Plewright605d02a2022-10-19 11:54:46 +01001597 modifiers |= MOD_MASK_CTRL; // MOUSE_CTRL;
Christopher Plewright2a46f812022-10-16 19:47:45 +01001598 if (pmer->dwControlKeyState & (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED))
1599 modifiers |= MOD_MASK_ALT; // MOUSE_ALT;
1600
1601 // add (bitwise or) the scroll direction and the key modifier chars
1602 // together.
1603 g_nMouseClick = ((direction << 8) | modifiers);
1604
1605 return;
1606}
1607
Bram Moolenaar071d4272004-06-13 20:20:40 +00001608/*
1609 * Decode a MOUSE_EVENT. If it's a valid event, return MOUSE_LEFT,
1610 * MOUSE_MIDDLE, or MOUSE_RIGHT for a click; MOUSE_DRAG for a mouse
1611 * move with a button held down; and MOUSE_RELEASE after a MOUSE_DRAG
1612 * or a MOUSE_LEFT, _MIDDLE, or _RIGHT. We encode the button type,
1613 * the number of clicks, and the Shift/Ctrl/Alt modifiers in g_nMouseClick,
1614 * and we return the mouse position in g_xMouse and g_yMouse.
1615 *
1616 * Every MOUSE_LEFT, _MIDDLE, or _RIGHT will be followed by zero or more
1617 * MOUSE_DRAGs and one MOUSE_RELEASE. MOUSE_RELEASE will be followed only
1618 * by MOUSE_LEFT, _MIDDLE, or _RIGHT.
1619 *
1620 * For multiple clicks, we send, say, MOUSE_LEFT/1 click, MOUSE_RELEASE,
1621 * MOUSE_LEFT/2 clicks, MOUSE_RELEASE, MOUSE_LEFT/3 clicks, MOUSE_RELEASE, ....
1622 *
1623 * Windows will send us MOUSE_MOVED notifications whenever the mouse
1624 * moves, even if it stays within the same character cell. We ignore
1625 * all MOUSE_MOVED messages if the position hasn't really changed, and
1626 * we ignore all MOUSE_MOVED messages where no button is held down (i.e.,
1627 * we're only interested in MOUSE_DRAG).
1628 *
1629 * All of this is complicated by the code that fakes MOUSE_MIDDLE on
1630 * 2-button mouses by pressing the left & right buttons simultaneously.
1631 * In practice, it's almost impossible to click both at the same time,
1632 * so we need to delay a little. Also, we tend not to get MOUSE_RELEASE
1633 * in such cases, if the user is clicking quickly.
1634 */
1635 static BOOL
1636decode_mouse_event(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001637 MOUSE_EVENT_RECORD *pmer)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001638{
1639 static int s_nOldButton = -1;
1640 static int s_nOldMouseClick = -1;
1641 static int s_xOldMouse = -1;
1642 static int s_yOldMouse = -1;
1643 static linenr_T s_old_topline = 0;
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001644# ifdef FEAT_DIFF
Bram Moolenaar071d4272004-06-13 20:20:40 +00001645 static int s_old_topfill = 0;
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001646# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001647 static int s_cClicks = 1;
1648 static BOOL s_fReleased = TRUE;
1649 static DWORD s_dwLastClickTime = 0;
1650 static BOOL s_fNextIsMiddle = FALSE;
1651
Bram Moolenaar0f873732019-12-05 20:28:46 +01001652 static DWORD cButtons = 0; // number of buttons supported
Bram Moolenaar071d4272004-06-13 20:20:40 +00001653
1654 const DWORD LEFT = FROM_LEFT_1ST_BUTTON_PRESSED;
1655 const DWORD MIDDLE = FROM_LEFT_2ND_BUTTON_PRESSED;
1656 const DWORD RIGHT = RIGHTMOST_BUTTON_PRESSED;
1657 const DWORD LEFT_RIGHT = LEFT | RIGHT;
1658
1659 int nButton;
1660
1661 if (cButtons == 0 && !GetNumberOfConsoleMouseButtons(&cButtons))
1662 cButtons = 2;
1663
1664 if (!g_fMouseAvail || !g_fMouseActive)
1665 {
1666 g_nMouseClick = -1;
1667 return FALSE;
1668 }
1669
Bram Moolenaar0f873732019-12-05 20:28:46 +01001670 // get a spurious MOUSE_EVENT immediately after receiving focus; ignore
Bram Moolenaar071d4272004-06-13 20:20:40 +00001671 if (g_fJustGotFocus)
1672 {
1673 g_fJustGotFocus = FALSE;
1674 return FALSE;
1675 }
1676
Christopher Plewright605d02a2022-10-19 11:54:46 +01001677 // If there is an unprocessed mouse click drop this one.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001678 if (g_nMouseClick != -1)
1679 return TRUE;
Christopher Plewright605d02a2022-10-19 11:54:46 +01001680
Christopher Plewright2a46f812022-10-16 19:47:45 +01001681 if (pmer->dwEventFlags == MOUSE_WHEELED
1682 || pmer->dwEventFlags == MOUSE_HWHEELED)
1683 {
1684 decode_mouse_wheel(pmer);
1685 return TRUE; // we now should have a mouse scroll in g_nMouseClick
1686 }
Christopher Plewright605d02a2022-10-19 11:54:46 +01001687
Bram Moolenaar071d4272004-06-13 20:20:40 +00001688 nButton = -1;
1689 g_xMouse = pmer->dwMousePosition.X;
1690 g_yMouse = pmer->dwMousePosition.Y;
1691
1692 if (pmer->dwEventFlags == MOUSE_MOVED)
1693 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001694 // Ignore MOUSE_MOVED events if (x, y) hasn't changed. (We get these
1695 // events even when the mouse moves only within a char cell.)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001696 if (s_xOldMouse == g_xMouse && s_yOldMouse == g_yMouse)
1697 return FALSE;
1698 }
1699
Bram Moolenaar0f873732019-12-05 20:28:46 +01001700 // If no buttons are pressed...
Bram Moolenaar071d4272004-06-13 20:20:40 +00001701 if ((pmer->dwButtonState & ((1 << cButtons) - 1)) == 0)
1702 {
Bram Moolenaar157d8132018-03-06 17:09:20 +01001703 nButton = MOUSE_RELEASE;
1704
Bram Moolenaar0f873732019-12-05 20:28:46 +01001705 // If the last thing returned was MOUSE_RELEASE, ignore this
Bram Moolenaar071d4272004-06-13 20:20:40 +00001706 if (s_fReleased)
Bram Moolenaar157d8132018-03-06 17:09:20 +01001707 {
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001708# ifdef FEAT_BEVAL_TERM
Bram Moolenaar0f873732019-12-05 20:28:46 +01001709 // do return mouse move events when we want them
Bram Moolenaar157d8132018-03-06 17:09:20 +01001710 if (p_bevalterm)
1711 nButton = MOUSE_DRAG;
1712 else
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001713# endif
Bram Moolenaar157d8132018-03-06 17:09:20 +01001714 return FALSE;
1715 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001716
Bram Moolenaar071d4272004-06-13 20:20:40 +00001717 s_fReleased = TRUE;
1718 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01001719 else // one or more buttons pressed
Bram Moolenaar071d4272004-06-13 20:20:40 +00001720 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001721 // on a 2-button mouse, hold down left and right buttons
1722 // simultaneously to get MIDDLE.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001723
1724 if (cButtons == 2 && s_nOldButton != MOUSE_DRAG)
1725 {
1726 DWORD dwLR = (pmer->dwButtonState & LEFT_RIGHT);
1727
Bram Moolenaar0f873732019-12-05 20:28:46 +01001728 // if either left or right button only is pressed, see if the
1729 // next mouse event has both of them pressed
Bram Moolenaar071d4272004-06-13 20:20:40 +00001730 if (dwLR == LEFT || dwLR == RIGHT)
1731 {
1732 for (;;)
1733 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001734 // wait a short time for next input event
Bram Moolenaar071d4272004-06-13 20:20:40 +00001735 if (WaitForSingleObject(g_hConIn, p_mouset / 3)
1736 != WAIT_OBJECT_0)
1737 break;
1738 else
1739 {
1740 DWORD cRecords = 0;
1741 INPUT_RECORD ir;
1742 MOUSE_EVENT_RECORD* pmer2 = &ir.Event.MouseEvent;
1743
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001744 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001745
1746 if (cRecords == 0 || ir.EventType != MOUSE_EVENT
1747 || !(pmer2->dwButtonState & LEFT_RIGHT))
1748 break;
1749 else
1750 {
1751 if (pmer2->dwEventFlags != MOUSE_MOVED)
1752 {
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001753 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001754
1755 return decode_mouse_event(pmer2);
1756 }
1757 else if (s_xOldMouse == pmer2->dwMousePosition.X &&
1758 s_yOldMouse == pmer2->dwMousePosition.Y)
1759 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001760 // throw away spurious mouse move
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001761 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001762
Bram Moolenaar0f873732019-12-05 20:28:46 +01001763 // are there any more mouse events in queue?
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001764 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001765
1766 if (cRecords==0 || ir.EventType != MOUSE_EVENT)
1767 break;
1768 }
1769 else
1770 break;
1771 }
1772 }
1773 }
1774 }
1775 }
1776
1777 if (s_fNextIsMiddle)
1778 {
1779 nButton = (pmer->dwEventFlags == MOUSE_MOVED)
1780 ? MOUSE_DRAG : MOUSE_MIDDLE;
1781 s_fNextIsMiddle = FALSE;
1782 }
1783 else if (cButtons == 2 &&
1784 ((pmer->dwButtonState & LEFT_RIGHT) == LEFT_RIGHT))
1785 {
1786 nButton = MOUSE_MIDDLE;
1787
1788 if (! s_fReleased && pmer->dwEventFlags != MOUSE_MOVED)
1789 {
1790 s_fNextIsMiddle = TRUE;
1791 nButton = MOUSE_RELEASE;
1792 }
1793 }
1794 else if ((pmer->dwButtonState & LEFT) == LEFT)
1795 nButton = MOUSE_LEFT;
1796 else if ((pmer->dwButtonState & MIDDLE) == MIDDLE)
1797 nButton = MOUSE_MIDDLE;
1798 else if ((pmer->dwButtonState & RIGHT) == RIGHT)
1799 nButton = MOUSE_RIGHT;
1800
1801 if (! s_fReleased && ! s_fNextIsMiddle
1802 && nButton != s_nOldButton && s_nOldButton != MOUSE_DRAG)
1803 return FALSE;
1804
1805 s_fReleased = s_fNextIsMiddle;
1806 }
1807
1808 if (pmer->dwEventFlags == 0 || pmer->dwEventFlags == DOUBLE_CLICK)
1809 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001810 // button pressed or released, without mouse moving
Bram Moolenaar071d4272004-06-13 20:20:40 +00001811 if (nButton != -1 && nButton != MOUSE_RELEASE)
1812 {
1813 DWORD dwCurrentTime = GetTickCount();
1814
1815 if (s_xOldMouse != g_xMouse
1816 || s_yOldMouse != g_yMouse
1817 || s_nOldButton != nButton
1818 || s_old_topline != curwin->w_topline
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001819# ifdef FEAT_DIFF
Bram Moolenaar071d4272004-06-13 20:20:40 +00001820 || s_old_topfill != curwin->w_topfill
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001821# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001822 || (int)(dwCurrentTime - s_dwLastClickTime) > p_mouset)
1823 {
1824 s_cClicks = 1;
1825 }
1826 else if (++s_cClicks > 4)
1827 {
1828 s_cClicks = 1;
1829 }
1830
1831 s_dwLastClickTime = dwCurrentTime;
1832 }
1833 }
1834 else if (pmer->dwEventFlags == MOUSE_MOVED)
1835 {
1836 if (nButton != -1 && nButton != MOUSE_RELEASE)
1837 nButton = MOUSE_DRAG;
1838
1839 s_cClicks = 1;
1840 }
1841
1842 if (nButton == -1)
1843 return FALSE;
1844
1845 if (nButton != MOUSE_RELEASE)
1846 s_nOldButton = nButton;
1847
1848 g_nMouseClick = nButton;
1849
1850 if (pmer->dwControlKeyState & SHIFT_PRESSED)
1851 g_nMouseClick |= MOUSE_SHIFT;
1852 if (pmer->dwControlKeyState & (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED))
1853 g_nMouseClick |= MOUSE_CTRL;
1854 if (pmer->dwControlKeyState & (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED))
1855 g_nMouseClick |= MOUSE_ALT;
1856
1857 if (nButton != MOUSE_DRAG && nButton != MOUSE_RELEASE)
1858 SET_NUM_MOUSE_CLICKS(g_nMouseClick, s_cClicks);
1859
Bram Moolenaar0f873732019-12-05 20:28:46 +01001860 // only pass on interesting (i.e., different) mouse events
Bram Moolenaar071d4272004-06-13 20:20:40 +00001861 if (s_xOldMouse == g_xMouse
1862 && s_yOldMouse == g_yMouse
1863 && s_nOldMouseClick == g_nMouseClick)
1864 {
1865 g_nMouseClick = -1;
1866 return FALSE;
1867 }
1868
1869 s_xOldMouse = g_xMouse;
1870 s_yOldMouse = g_yMouse;
1871 s_old_topline = curwin->w_topline;
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001872# ifdef FEAT_DIFF
Bram Moolenaar071d4272004-06-13 20:20:40 +00001873 s_old_topfill = curwin->w_topfill;
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001874# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001875 s_nOldMouseClick = g_nMouseClick;
1876
1877 return TRUE;
1878}
1879
Christopher Plewright20b795e2022-12-20 20:01:58 +00001880# ifdef FEAT_EVAL
1881 static int
1882encode_mouse_event(dict_T *args, INPUT_RECORD *ir)
1883{
1884 int button;
1885 int row;
1886 int col;
1887 int repeated_click;
Bram Moolenaar9b8a3652022-12-20 20:47:28 +00001888 int_u mods = 0;
Christopher Plewright20b795e2022-12-20 20:01:58 +00001889 int move;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001890
Christopher Plewright20b795e2022-12-20 20:01:58 +00001891 if (!dict_has_key(args, "row") || !dict_has_key(args, "col"))
1892 return FALSE;
1893
1894 // Note: "move" is optional, requires fewer arguments
1895 move = (int)dict_get_bool(args, "move", FALSE);
1896 if (!move && (!dict_has_key(args, "button")
1897 || !dict_has_key(args, "multiclick")
1898 || !dict_has_key(args, "modifiers")))
1899 return FALSE;
1900
1901 row = (int)dict_get_number(args, "row") - 1;
1902 col = (int)dict_get_number(args, "col") - 1;
1903
1904 ir->EventType = MOUSE_EVENT;
1905 MOUSE_EVENT_RECORD mer;
1906 ZeroMemory(&mer, sizeof(mer));
1907 mer.dwMousePosition.X = col;
1908 mer.dwMousePosition.Y = row;
1909
1910 if (move)
1911 {
1912 mer.dwButtonState = 0;
1913 mer.dwEventFlags = MOUSE_MOVED;
1914 }
1915 else
1916 {
1917 button = (int)dict_get_number(args, "button");
1918 repeated_click = (int)dict_get_number(args, "multiclick");
1919 mods = (int)dict_get_number(args, "modifiers");
1920 // Reset the scroll values to known values.
1921 // XXX: Remove this when/if the scroll step is made configurable.
1922 mouse_set_hor_scroll_step(6);
1923 mouse_set_vert_scroll_step(3);
1924
1925 switch (button)
1926 {
1927 case MOUSE_LEFT:
1928 mer.dwButtonState = FROM_LEFT_1ST_BUTTON_PRESSED;
1929 mer.dwEventFlags = repeated_click == 1 ? DOUBLE_CLICK : 0;
1930 break;
1931 case MOUSE_MIDDLE:
1932 mer.dwButtonState = FROM_LEFT_2ND_BUTTON_PRESSED;
1933 mer.dwEventFlags = repeated_click == 1 ? DOUBLE_CLICK : 0;
1934 break;
1935 case MOUSE_RIGHT:
1936 mer.dwButtonState = RIGHTMOST_BUTTON_PRESSED;
1937 mer.dwEventFlags = repeated_click == 1 ? DOUBLE_CLICK : 0;
1938 break;
1939 case MOUSE_RELEASE:
1940 // umm? Assume Left Release?
1941 mer.dwEventFlags = 0;
1942
1943 case MOUSE_MOVE:
1944 mer.dwButtonState = 0;
1945 mer.dwEventFlags = MOUSE_MOVED;
1946 break;
1947 case MOUSE_X1:
1948 mer.dwButtonState = FROM_LEFT_3RD_BUTTON_PRESSED;
1949 break;
1950 case MOUSE_X2:
1951 mer.dwButtonState = FROM_LEFT_4TH_BUTTON_PRESSED;
1952 break;
1953 case MOUSE_4: // KE_MOUSEDOWN;
1954 mer.dwButtonState = -1;
1955 mer.dwEventFlags = MOUSE_WHEELED;
1956 break;
1957 case MOUSE_5: // KE_MOUSEUP;
1958 mer.dwButtonState = +1;
1959 mer.dwEventFlags = MOUSE_WHEELED;
1960 break;
1961 case MOUSE_6: // KE_MOUSELEFT;
1962 mer.dwButtonState = -1;
1963 mer.dwEventFlags = MOUSE_HWHEELED;
1964 break;
1965 case MOUSE_7: // KE_MOUSERIGHT;
1966 mer.dwButtonState = +1;
1967 mer.dwEventFlags = MOUSE_HWHEELED;
1968 break;
1969 default:
1970 semsg(_(e_invalid_argument_str), "button");
1971 return FALSE;
1972 }
1973 }
1974
1975 mer.dwControlKeyState = 0;
1976 if (mods != 0)
1977 {
1978 // Encode the win32 console key modifiers from Vim MOUSE modifiers.
1979 if (mods & MOUSE_SHIFT)
1980 mer.dwControlKeyState |= SHIFT_PRESSED;
1981 if (mods & MOUSE_CTRL)
1982 mer.dwControlKeyState |= LEFT_CTRL_PRESSED;
1983 if (mods & MOUSE_ALT)
1984 mer.dwControlKeyState |= LEFT_ALT_PRESSED;
1985 }
1986 ir->Event.MouseEvent = mer;
1987 return TRUE;
1988}
1989# endif // FEAT_EVAL
1990
1991 static int
1992write_input_record_buffer(INPUT_RECORD* irEvents, int nLength)
1993{
1994 int nCount = 0;
1995 while (nCount < nLength)
1996 {
1997 input_record_buffer.length++;
1998 input_record_buffer_node_T *event_node =
1999 malloc(sizeof(input_record_buffer_node_T));
2000 event_node->ir = irEvents[nCount++];
2001 event_node->next = NULL;
2002 if (input_record_buffer.tail == NULL)
2003 {
2004 input_record_buffer.head = event_node;
2005 input_record_buffer.tail = event_node;
2006 }
2007 else
2008 {
2009 input_record_buffer.tail->next = event_node;
2010 input_record_buffer.tail = input_record_buffer.tail->next;
2011 }
2012 }
2013 return nCount;
2014}
2015
2016 static int
2017read_input_record_buffer(INPUT_RECORD* irEvents, int nMaxLength)
2018{
2019 int nCount = 0;
2020 while (nCount < nMaxLength && input_record_buffer.head != NULL)
2021 {
2022 input_record_buffer.length--;
2023 input_record_buffer_node_T *pop_head = input_record_buffer.head;
2024 irEvents[nCount++] = pop_head->ir;
2025 input_record_buffer.head = pop_head->next;
2026 vim_free(pop_head);
2027 if (input_record_buffer.length == 0)
2028 input_record_buffer.tail = NULL;
2029 }
2030 return nCount;
2031}
Christopher Plewright20b795e2022-12-20 20:01:58 +00002032#endif // !FEAT_GUI_MSWIN || VIMDLL
2033
2034#ifdef FEAT_EVAL
2035/*
2036 * The 'test_mswin_event' function is for testing Vim's low-level handling of
2037 * user input events. ie, this manages the encoding of INPUT_RECORD events
2038 * so that we have a way to test how Vim decodes INPUT_RECORD events in Windows
2039 * consoles.
2040 *
2041 * The 'test_mswin_event' function is based on 'test_gui_event'. In fact, when
2042 * the Windows GUI is running, the arguments; 'event' and 'args', are the same.
2043 * So, it acts as an alias for 'test_gui_event' for the Windows GUI.
2044 *
2045 * When the Windows console is running, the arguments; 'event' and 'args', are
2046 * a subset of what 'test_gui_event' handles, ie, only "key" and "mouse"
2047 * events are encoded as INPUT_RECORD events.
2048 *
2049 * Note: INPUT_RECORDs are only used by the Windows console, not the GUI. The
2050 * GUI sends MSG structs instead.
2051 */
2052 int
2053test_mswin_event(char_u *event, dict_T *args)
2054{
2055 int lpEventsWritten = 0;
2056
2057# if defined(VIMDLL) || defined(FEAT_GUI_MSWIN)
2058 if (gui.in_use)
2059 return test_gui_w32_sendevent(event, args);
2060# endif
2061
2062# if defined(VIMDLL) || !defined(FEAT_GUI_MSWIN)
2063
2064// Currently implemented event record types are; KEY_EVENT and MOUSE_EVENT
2065// Potentially could also implement: FOCUS_EVENT and WINDOW_BUFFER_SIZE_EVENT
2066// Maybe also: MENU_EVENT
2067
2068 INPUT_RECORD ir;
2069 BOOL input_encoded = FALSE;
Christopher Plewright7b0afc12022-12-30 16:54:58 +00002070 BOOL execute = FALSE;
Christopher Plewright20b795e2022-12-20 20:01:58 +00002071 if (STRCMP(event, "key") == 0)
Christopher Plewright7b0afc12022-12-30 16:54:58 +00002072 {
2073 execute = dict_get_bool(args, "execute", FALSE);
2074 if (dict_has_key(args, "event"))
2075 input_encoded = encode_key_event(args, &ir);
2076 else if (!execute)
2077 {
2078 semsg(_(e_missing_argument_str), "event");
2079 return FALSE;
2080 }
2081 }
Christopher Plewright20b795e2022-12-20 20:01:58 +00002082 else if (STRCMP(event, "mouse") == 0)
Christopher Plewright7b0afc12022-12-30 16:54:58 +00002083 {
2084 execute = TRUE;
Christopher Plewright20b795e2022-12-20 20:01:58 +00002085 input_encoded = encode_mouse_event(args, &ir);
Christopher Plewright7b0afc12022-12-30 16:54:58 +00002086 }
Christopher Plewright20b795e2022-12-20 20:01:58 +00002087 else
2088 {
2089 semsg(_(e_invalid_value_for_argument_str_str), "event", event);
2090 return FALSE;
2091 }
2092
2093 // Ideally, WriteConsoleInput would be used to inject these low-level
Yegappan Lakshmanan14113fd2023-03-07 17:13:51 +00002094 // events. But, this doesn't work well in the CI test environment. So
Christopher Plewright20b795e2022-12-20 20:01:58 +00002095 // implementing an input_record_buffer instead.
2096 if (input_encoded)
2097 lpEventsWritten = write_input_record_buffer(&ir, 1);
2098
Christopher Plewright7b0afc12022-12-30 16:54:58 +00002099 // Set flags to execute the event, ie. like feedkeys mode X.
2100 if (execute)
2101 {
2102 int save_msg_scroll = msg_scroll;
2103 // Avoid a 1 second delay when the keys start Insert mode.
2104 msg_scroll = FALSE;
2105 ch_log(NULL, "test_mswin_event() executing");
Christopher Plewright20b795e2022-12-20 20:01:58 +00002106 exec_normal(TRUE, TRUE, TRUE);
Christopher Plewright7b0afc12022-12-30 16:54:58 +00002107 msg_scroll |= save_msg_scroll;
2108 }
Christopher Plewright20b795e2022-12-20 20:01:58 +00002109
2110# endif
2111 return lpEventsWritten;
2112}
2113#endif // FEAT_EVAL
Bram Moolenaar071d4272004-06-13 20:20:40 +00002114
2115#ifdef MCH_CURSOR_SHAPE
2116/*
2117 * Set the shape of the cursor.
2118 * 'thickness' can be from 1 (thin) to 99 (block)
2119 */
2120 static void
2121mch_set_cursor_shape(int thickness)
2122{
Christopher Plewright38804d62022-11-09 23:55:52 +00002123 if (vtp_working)
K.Takatadf5320c2022-09-01 13:20:16 +01002124 {
2125 if (*T_CSI == NUL)
2126 {
2127 // If 't_SI' is not set, use the default cursor styles.
2128 if (thickness < 50)
2129 vtp_printf("\033[3 q"); // underline
2130 else
2131 vtp_printf("\033[0 q"); // default
2132 }
2133 }
2134 else
2135 {
2136 CONSOLE_CURSOR_INFO ConsoleCursorInfo;
2137 ConsoleCursorInfo.dwSize = thickness;
2138 ConsoleCursorInfo.bVisible = s_cursor_visible;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002139
K.Takatadf5320c2022-09-01 13:20:16 +01002140 SetConsoleCursorInfo(g_hConOut, &ConsoleCursorInfo);
2141 if (s_cursor_visible)
2142 SetConsoleCursorPosition(g_hConOut, g_coord);
2143 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002144}
2145
2146 void
2147mch_update_cursor(void)
2148{
2149 int idx;
2150 int thickness;
2151
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002152# ifdef VIMDLL
2153 if (gui.in_use)
2154 return;
2155# endif
2156
Bram Moolenaar071d4272004-06-13 20:20:40 +00002157 /*
2158 * How the cursor is drawn depends on the current mode.
2159 */
2160 idx = get_shape_idx(FALSE);
2161
2162 if (shape_table[idx].shape == SHAPE_BLOCK)
Bram Moolenaar0f873732019-12-05 20:28:46 +01002163 thickness = 99; // 100 doesn't work on W95
Bram Moolenaar071d4272004-06-13 20:20:40 +00002164 else
2165 thickness = shape_table[idx].percentage;
2166 mch_set_cursor_shape(thickness);
2167}
2168#endif
2169
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002170#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002171/*
2172 * Handle FOCUS_EVENT.
2173 */
2174 static void
2175handle_focus_event(INPUT_RECORD ir)
2176{
2177 g_fJustGotFocus = ir.Event.FocusEvent.bSetFocus;
2178 ui_focus_change((int)g_fJustGotFocus);
2179}
2180
Bram Moolenaar78d21da2019-02-17 15:00:52 +01002181static void ResizeConBuf(HANDLE hConsole, COORD coordScreen);
2182
Bram Moolenaar071d4272004-06-13 20:20:40 +00002183/*
2184 * Wait until console input from keyboard or mouse is available,
2185 * or the time is up.
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02002186 * When "ignore_input" is TRUE even wait when input is available.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002187 * Return TRUE if something is available FALSE if not.
2188 */
2189 static int
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02002190WaitForChar(long msec, int ignore_input)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002191{
2192 DWORD dwNow = 0, dwEndTime = 0;
2193 INPUT_RECORD ir;
2194 DWORD cRecords;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002195 WCHAR ch, ch2;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002196# ifdef FEAT_TIMERS
Bram Moolenaar40b1b542016-04-20 20:18:23 +02002197 int tb_change_cnt = typebuf.tb_change_cnt;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002198# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002199
2200 if (msec > 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01002201 // Wait until the specified time has elapsed.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002202 dwEndTime = GetTickCount() + msec;
2203 else if (msec < 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01002204 // Wait forever.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002205 dwEndTime = INFINITE;
2206
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01002207 // We need to loop until the end of the time period, because
2208 // we might get multiple unusable mouse events in that time.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002209 for (;;)
2210 {
Bram Moolenaared5a9d62018-09-06 13:14:43 +02002211 // Only process messages when waiting.
2212 if (msec != 0)
2213 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002214# ifdef MESSAGE_QUEUE
Bram Moolenaared5a9d62018-09-06 13:14:43 +02002215 parse_queued_messages();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002216# endif
2217# ifdef FEAT_MZSCHEME
Bram Moolenaared5a9d62018-09-06 13:14:43 +02002218 mzvim_check_threads();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002219# endif
2220# ifdef FEAT_CLIENTSERVER
Bram Moolenaared5a9d62018-09-06 13:14:43 +02002221 serverProcessPendingMessages();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002222# endif
Bram Moolenaared5a9d62018-09-06 13:14:43 +02002223 }
Bram Moolenaarf12d9832016-01-29 21:11:25 +01002224
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02002225 if (g_nMouseClick != -1
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002226# ifdef FEAT_CLIENTSERVER
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02002227 || (!ignore_input && input_available())
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002228# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002229 )
2230 return TRUE;
2231
2232 if (msec > 0)
2233 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01002234 // If the specified wait time has passed, return. Beware that
2235 // GetTickCount() may wrap around (overflow).
Bram Moolenaar071d4272004-06-13 20:20:40 +00002236 dwNow = GetTickCount();
Bram Moolenaarb7512b72013-08-10 12:45:09 +02002237 if ((int)(dwNow - dwEndTime) >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002238 break;
2239 }
2240 if (msec != 0)
2241 {
Bram Moolenaar325b7a22004-07-05 15:58:32 +00002242 DWORD dwWaitTime = dwEndTime - dwNow;
2243
Bram Moolenaarc478ee32020-12-01 21:27:51 +01002244 // Don't wait for more than 11 msec to avoid dropping characters,
2245 // check channel while waiting for input and handle a callback from
2246 // 'balloonexpr'.
2247 if (dwWaitTime > 11)
2248 dwWaitTime = 11;
2249
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002250# ifdef FEAT_MZSCHEME
Bram Moolenaarc478ee32020-12-01 21:27:51 +01002251 if (mzthreads_allowed() && p_mzq > 0 && (long)dwWaitTime > p_mzq)
Bram Moolenaar0f873732019-12-05 20:28:46 +01002252 dwWaitTime = p_mzq; // don't wait longer than 'mzquantum'
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002253# endif
2254# ifdef FEAT_TIMERS
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01002255 // When waiting very briefly don't trigger timers.
2256 if (dwWaitTime > 10)
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01002257 {
2258 long due_time;
2259
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01002260 // Trigger timers and then get the time in msec until the next
2261 // one is due. Wait up to that time.
2262 due_time = check_due_timer();
2263 if (typebuf.tb_change_cnt != tb_change_cnt)
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01002264 {
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01002265 // timer may have used feedkeys().
2266 return FALSE;
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01002267 }
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01002268 if (due_time > 0 && dwWaitTime > (DWORD)due_time)
2269 dwWaitTime = due_time;
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01002270 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002271# endif
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01002272 if (
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002273# ifdef FEAT_CLIENTSERVER
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01002274 // Wait for either an event on the console input or a
2275 // message in the client-server window.
2276 msg_wait_for_multiple_objects(1, &g_hConIn, FALSE,
2277 dwWaitTime, QS_SENDMESSAGE) != WAIT_OBJECT_0
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002278# else
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01002279 wait_for_single_object(g_hConIn, dwWaitTime)
2280 != WAIT_OBJECT_0
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002281# endif
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01002282 )
2283 continue;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002284 }
2285
2286 cRecords = 0;
Bram Moolenaar3a69e112014-01-10 13:51:42 +01002287 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002288
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002289# ifdef FEAT_MBYTE_IME
matveyt4eb19142021-05-20 11:54:10 +02002290 // May have to redraw if the cursor ends up in the wrong place.
2291 // Only when not peeking.
Bram Moolenaar24959102022-05-07 20:01:16 +01002292 if (State == MODE_CMDLINE && msg_row == Rows - 1 && msec != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002293 {
2294 CONSOLE_SCREEN_BUFFER_INFO csbi;
2295
2296 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
2297 {
2298 if (csbi.dwCursorPosition.Y != msg_row)
2299 {
matveyte08795e2021-05-07 15:00:17 +02002300 // The screen is now messed up, must redraw the command
2301 // line and later all the windows.
Bram Moolenaara4d158b2022-08-14 14:17:45 +01002302 redraw_all_later(UPD_CLEAR);
matveyte08795e2021-05-07 15:00:17 +02002303 compute_cmdrow();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002304 redrawcmd();
2305 }
2306 }
2307 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002308# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002309
2310 if (cRecords > 0)
2311 {
2312 if (ir.EventType == KEY_EVENT && ir.Event.KeyEvent.bKeyDown)
2313 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002314# ifdef FEAT_MBYTE_IME
Bram Moolenaar0f873732019-12-05 20:28:46 +01002315 // Windows IME sends two '\n's with only one 'ENTER'. First:
2316 // wVirtualKeyCode == 13. second: wVirtualKeyCode == 0
K.Takata972db232022-02-04 10:45:38 +00002317 if (ir.Event.KeyEvent.uChar.UnicodeChar == 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00002318 && ir.Event.KeyEvent.wVirtualKeyCode == 13)
2319 {
Bram Moolenaar3a69e112014-01-10 13:51:42 +01002320 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002321 continue;
2322 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002323# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002324 if (decode_key_event(&ir.Event.KeyEvent, &ch, &ch2,
2325 NULL, FALSE))
2326 return TRUE;
2327 }
2328
Bram Moolenaar3a69e112014-01-10 13:51:42 +01002329 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002330
2331 if (ir.EventType == FOCUS_EVENT)
2332 handle_focus_event(ir);
2333 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
Bram Moolenaarc33ecb22018-02-11 16:40:45 +01002334 {
Bram Moolenaar78d21da2019-02-17 15:00:52 +01002335 COORD dwSize = ir.Event.WindowBufferSizeEvent.dwSize;
2336
Bram Moolenaar36698e32019-12-11 22:57:40 +01002337 // Only call shell_resized() when the size actually changed to
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002338 // avoid the screen is cleared.
Bram Moolenaar78d21da2019-02-17 15:00:52 +01002339 if (dwSize.X != Columns || dwSize.Y != Rows)
2340 {
2341 CONSOLE_SCREEN_BUFFER_INFO csbi;
2342 GetConsoleScreenBufferInfo(g_hConOut, &csbi);
Bram Moolenaar36698e32019-12-11 22:57:40 +01002343 dwSize.X = csbi.srWindow.Right - csbi.srWindow.Left + 1;
Bram Moolenaar78d21da2019-02-17 15:00:52 +01002344 dwSize.Y = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
Bram Moolenaar36698e32019-12-11 22:57:40 +01002345 if (dwSize.X != Columns || dwSize.Y != Rows)
2346 {
2347 ResizeConBuf(g_hConOut, dwSize);
2348 shell_resized();
2349 }
Bram Moolenaar78d21da2019-02-17 15:00:52 +01002350 }
Bram Moolenaarc33ecb22018-02-11 16:40:45 +01002351 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002352 else if (ir.EventType == MOUSE_EVENT
2353 && decode_mouse_event(&ir.Event.MouseEvent))
2354 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002355 }
2356 else if (msec == 0)
2357 break;
2358 }
2359
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002360# ifdef FEAT_CLIENTSERVER
Bram Moolenaar0f873732019-12-05 20:28:46 +01002361 // Something might have been received while we were waiting.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002362 if (input_available())
2363 return TRUE;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002364# endif
Bram Moolenaarf12d9832016-01-29 21:11:25 +01002365
Bram Moolenaar071d4272004-06-13 20:20:40 +00002366 return FALSE;
2367}
2368
Bram Moolenaar071d4272004-06-13 20:20:40 +00002369/*
2370 * return non-zero if a character is available
2371 */
2372 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002373mch_char_avail(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002374{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002375# ifdef VIMDLL
2376 if (gui.in_use)
2377 return TRUE;
2378# endif
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02002379 return WaitForChar(0L, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002380}
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02002381
2382# if defined(FEAT_TERMINAL) || defined(PROTO)
2383/*
2384 * Check for any pending input or messages.
2385 */
2386 int
2387mch_check_messages(void)
2388{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002389# ifdef VIMDLL
2390 if (gui.in_use)
2391 return TRUE;
2392# endif
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02002393 return WaitForChar(0L, TRUE);
2394}
2395# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002396
2397/*
2398 * Create the console input. Used when reading stdin doesn't work.
2399 */
2400 static void
2401create_conin(void)
2402{
2403 g_hConIn = CreateFile("CONIN$", GENERIC_READ|GENERIC_WRITE,
2404 FILE_SHARE_READ|FILE_SHARE_WRITE,
2405 (LPSECURITY_ATTRIBUTES) NULL,
Bram Moolenaareb3593b2006-04-22 22:33:57 +00002406 OPEN_EXISTING, 0, (HANDLE)NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002407 did_create_conin = TRUE;
2408}
2409
2410/*
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01002411 * Get a keystroke or a mouse event, use a blocking wait.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002412 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002413 static WCHAR
2414tgetch(int *pmodifiers, WCHAR *pch2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002415{
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002416 WCHAR ch;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002417
2418 for (;;)
2419 {
2420 INPUT_RECORD ir;
2421 DWORD cRecords = 0;
2422
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002423# ifdef FEAT_CLIENTSERVER
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02002424 (void)WaitForChar(-1L, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002425 if (input_available())
2426 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002427 if (g_nMouseClick != -1)
2428 return 0;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002429# endif
Bram Moolenaar3a69e112014-01-10 13:51:42 +01002430 if (read_console_input(g_hConIn, &ir, 1, &cRecords) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002431 {
2432 if (did_create_conin)
2433 read_error_exit();
2434 create_conin();
2435 continue;
2436 }
2437
2438 if (ir.EventType == KEY_EVENT)
2439 {
2440 if (decode_key_event(&ir.Event.KeyEvent, &ch, pch2,
2441 pmodifiers, TRUE))
2442 return ch;
2443 }
2444 else if (ir.EventType == FOCUS_EVENT)
2445 handle_focus_event(ir);
2446 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
2447 shell_resized();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002448 else if (ir.EventType == MOUSE_EVENT)
2449 {
2450 if (decode_mouse_event(&ir.Event.MouseEvent))
2451 return 0;
2452 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002453 }
2454}
Bram Moolenaar0f873732019-12-05 20:28:46 +01002455#endif // !FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00002456
2457
2458/*
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02002459 * mch_inchar(): low-level input function.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002460 * Get one or more characters from the keyboard or the mouse.
2461 * If time == 0, do not wait for characters.
2462 * If time == n, wait a short time for characters.
2463 * If time == -1, wait forever for characters.
2464 * Returns the number of characters read into buf.
2465 */
2466 int
2467mch_inchar(
Bram Moolenaar1266d672017-02-01 13:43:36 +01002468 char_u *buf UNUSED,
2469 int maxlen UNUSED,
2470 long time UNUSED,
2471 int tb_change_cnt UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002472{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002473#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002474
2475 int len;
2476 int c;
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01002477# ifdef VIMDLL
2478// Extra space for maximum three CSIs. E.g. U+1B6DB -> 0xF0 0x9B 0x9B 0x9B.
2479# define TYPEAHEADSPACE 6
2480# else
2481# define TYPEAHEADSPACE 0
2482# endif
2483# define TYPEAHEADLEN (20 + TYPEAHEADSPACE)
Bram Moolenaar0f873732019-12-05 20:28:46 +01002484 static char_u typeahead[TYPEAHEADLEN]; // previously typed bytes.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002485 static int typeaheadlen = 0;
2486
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002487# ifdef VIMDLL
2488 if (gui.in_use)
2489 return 0;
2490# endif
2491
Bram Moolenaar0f873732019-12-05 20:28:46 +01002492 // First use any typeahead that was kept because "buf" was too small.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002493 if (typeaheadlen > 0)
2494 goto theend;
2495
Bram Moolenaar071d4272004-06-13 20:20:40 +00002496 if (time >= 0)
2497 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01002498 if (!WaitForChar(time, FALSE)) // no character available
Bram Moolenaar071d4272004-06-13 20:20:40 +00002499 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002500 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01002501 else // time == -1, wait forever
Bram Moolenaar071d4272004-06-13 20:20:40 +00002502 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01002503 mch_set_winsize_now(); // Allow winsize changes from now on
Bram Moolenaar071d4272004-06-13 20:20:40 +00002504
Bram Moolenaar3918c952005-03-15 22:34:55 +00002505 /*
2506 * If there is no character available within 2 seconds (default)
2507 * write the autoscript file to disk. Or cause the CursorHold event
2508 * to be triggered.
2509 */
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02002510 if (!WaitForChar(p_ut, FALSE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002511 {
Bram Moolenaard35f9712005-12-18 22:02:33 +00002512 if (trigger_cursorhold() && maxlen >= 3)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002513 {
Bram Moolenaar3918c952005-03-15 22:34:55 +00002514 buf[0] = K_SPECIAL;
2515 buf[1] = KS_EXTRA;
2516 buf[2] = (int)KE_CURSORHOLD;
2517 return 3;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002518 }
Bram Moolenaar702517d2005-06-27 22:34:07 +00002519 before_blocking();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002520 }
2521 }
2522
2523 /*
2524 * Try to read as many characters as there are, until the buffer is full.
2525 */
2526
Bram Moolenaar0f873732019-12-05 20:28:46 +01002527 // we will get at least one key. Get more if they are available.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002528 g_fCBrkPressed = FALSE;
2529
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002530# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00002531 if (fdDump)
2532 fputc('[', fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002533# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002534
Bram Moolenaar0f873732019-12-05 20:28:46 +01002535 // Keep looping until there is something in the typeahead buffer and more
2536 // to get and still room in the buffer (up to two bytes for a char and
2537 // three bytes for a modifier).
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02002538 while ((typeaheadlen == 0 || WaitForChar(0L, FALSE))
Bram Moolenaar9f1983d2022-05-12 20:35:35 +01002539 && typeaheadlen + 5 + TYPEAHEADSPACE <= TYPEAHEADLEN)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002540 {
2541 if (typebuf_changed(tb_change_cnt))
2542 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01002543 // "buf" may be invalid now if a client put something in the
2544 // typeahead buffer and "buf" is in the typeahead buffer.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002545 typeaheadlen = 0;
2546 break;
2547 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002548 if (g_nMouseClick != -1)
2549 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002550# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00002551 if (fdDump)
2552 fprintf(fdDump, "{%02x @ %d, %d}",
2553 g_nMouseClick, g_xMouse, g_yMouse);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002554# endif
Christopher Plewright2a46f812022-10-16 19:47:45 +01002555 char_u modifiers = ((char_u *)(&g_nMouseClick))[0];
2556 char_u scroll_dir = ((char_u *)(&g_nMouseClick))[1];
2557
2558 if (scroll_dir == KE_MOUSEDOWN
2559 || scroll_dir == KE_MOUSEUP
2560 || scroll_dir == KE_MOUSELEFT
2561 || scroll_dir == KE_MOUSERIGHT)
2562 {
2563 if (modifiers > 0)
2564 {
Christopher Plewright03193062022-11-22 12:58:27 +00002565 // use K_SPECIAL instead of CSI to make mappings work
2566 typeahead[typeaheadlen++] = K_SPECIAL;
Christopher Plewright2a46f812022-10-16 19:47:45 +01002567 typeahead[typeaheadlen++] = KS_MODIFIER;
2568 typeahead[typeaheadlen++] = modifiers;
2569 }
2570 typeahead[typeaheadlen++] = CSI;
2571 typeahead[typeaheadlen++] = KS_EXTRA;
2572 typeahead[typeaheadlen++] = scroll_dir;
Christopher Plewright2a46f812022-10-16 19:47:45 +01002573 }
2574 else
2575 {
2576 typeahead[typeaheadlen++] = ESC + 128;
2577 typeahead[typeaheadlen++] = 'M';
2578 typeahead[typeaheadlen++] = g_nMouseClick;
Christopher Plewright2a46f812022-10-16 19:47:45 +01002579 }
Christopher Plewright36446bb2022-11-23 22:28:08 +00002580
2581 // Pass the pointer coordinates of the mouse event in 2 bytes,
2582 // allowing for > 223 columns. Both for click and scroll events.
2583 // This is the same as what is used for the GUI.
2584 typeahead[typeaheadlen++] = (char_u)(g_xMouse / 128 + ' ' + 1);
2585 typeahead[typeaheadlen++] = (char_u)(g_xMouse % 128 + ' ' + 1);
2586 typeahead[typeaheadlen++] = (char_u)(g_yMouse / 128 + ' ' + 1);
2587 typeahead[typeaheadlen++] = (char_u)(g_yMouse % 128 + ' ' + 1);
2588
2589 g_nMouseClick = -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002590 }
2591 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00002592 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002593 WCHAR ch2 = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002594 int modifiers = 0;
2595
2596 c = tgetch(&modifiers, &ch2);
2597
Christopher Plewrightc8b20492023-01-04 18:06:00 +00002598 c = simplify_key(c, &modifiers);
2599
Christopher Plewright7b0afc12022-12-30 16:54:58 +00002600 // Some chars need adjustment when the Ctrl modifier is used.
2601 ++no_reduce_keys;
2602 c = may_adjust_key_for_ctrl(modifiers, c);
2603 --no_reduce_keys;
2604
2605 // remove the SHIFT modifier for keys where it's already included,
2606 // e.g., '(' and '*'
2607 modifiers = may_remove_shift_modifier(modifiers, c);
2608
Bram Moolenaar071d4272004-06-13 20:20:40 +00002609 if (typebuf_changed(tb_change_cnt))
2610 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01002611 // "buf" may be invalid now if a client put something in the
2612 // typeahead buffer and "buf" is in the typeahead buffer.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002613 typeaheadlen = 0;
2614 break;
2615 }
2616
2617 if (c == Ctrl_C && ctrl_c_interrupts)
2618 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002619# if defined(FEAT_CLIENTSERVER)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002620 trash_input_buf();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002621# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002622 got_int = TRUE;
2623 }
2624
Bram Moolenaar071d4272004-06-13 20:20:40 +00002625 if (g_nMouseClick == -1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002626 {
2627 int n = 1;
2628
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002629 if (ch2 == NUL)
2630 {
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01002631 int i, j;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002632 char_u *p;
2633 WCHAR ch[2];
2634
2635 ch[0] = c;
Bram Moolenaar0f873732019-12-05 20:28:46 +01002636 if (c >= 0xD800 && c <= 0xDBFF) // High surrogate
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002637 {
2638 ch[1] = tgetch(&modifiers, &ch2);
2639 n++;
2640 }
2641 p = utf16_to_enc(ch, &n);
2642 if (p != NULL)
2643 {
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01002644 for (i = 0, j = 0; i < n; i++)
2645 {
2646 typeahead[typeaheadlen + j++] = p[i];
2647# ifdef VIMDLL
2648 if (p[i] == CSI)
2649 {
2650 typeahead[typeaheadlen + j++] = KS_EXTRA;
2651 typeahead[typeaheadlen + j++] = KE_CSI;
2652 }
2653# endif
2654 }
2655 n = j;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002656 vim_free(p);
2657 }
2658 }
2659 else
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01002660 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002661 typeahead[typeaheadlen] = c;
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01002662# ifdef VIMDLL
2663 if (c == CSI)
2664 {
2665 typeahead[typeaheadlen + 1] = KS_EXTRA;
2666 typeahead[typeaheadlen + 2] = KE_CSI;
2667 n = 3;
2668 }
2669# endif
2670 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002671 if (ch2 != NUL)
2672 {
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +02002673 if (c == K_NUL)
Bram Moolenaarfeeb4d02017-12-05 15:14:46 +01002674 {
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +02002675 switch (ch2)
2676 {
2677 case (WCHAR)'\324': // SHIFT+Insert
2678 case (WCHAR)'\325': // CTRL+Insert
2679 case (WCHAR)'\327': // SHIFT+Delete
2680 case (WCHAR)'\330': // CTRL+Delete
2681 typeahead[typeaheadlen + n] = (char_u)ch2;
2682 n++;
2683 break;
2684
2685 default:
2686 typeahead[typeaheadlen + n] = 3;
2687 typeahead[typeaheadlen + n + 1] = (char_u)ch2;
2688 n += 2;
2689 break;
2690 }
Bram Moolenaarfeeb4d02017-12-05 15:14:46 +01002691 }
2692 else
2693 {
2694 typeahead[typeaheadlen + n] = 3;
2695 typeahead[typeaheadlen + n + 1] = (char_u)ch2;
2696 n += 2;
2697 }
Bram Moolenaar45500912014-07-09 20:51:07 +02002698 }
2699
Bram Moolenaar0f873732019-12-05 20:28:46 +01002700 // Use the ALT key to set the 8th bit of the character
2701 // when it's one byte, the 8th bit isn't set yet and not
2702 // using a double-byte encoding (would become a lead
2703 // byte).
Bram Moolenaar071d4272004-06-13 20:20:40 +00002704 if ((modifiers & MOD_MASK_ALT)
2705 && n == 1
2706 && (typeahead[typeaheadlen] & 0x80) == 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00002707 && !enc_dbcs
Bram Moolenaar071d4272004-06-13 20:20:40 +00002708 )
2709 {
Bram Moolenaar85a3e5c2007-11-20 16:22:16 +00002710 n = (*mb_char2bytes)(typeahead[typeaheadlen] | 0x80,
2711 typeahead + typeaheadlen);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002712 modifiers &= ~MOD_MASK_ALT;
2713 }
2714
2715 if (modifiers != 0)
2716 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01002717 // Prepend modifiers to the character.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002718 mch_memmove(typeahead + typeaheadlen + 3,
2719 typeahead + typeaheadlen, n);
2720 typeahead[typeaheadlen++] = K_SPECIAL;
2721 typeahead[typeaheadlen++] = (char_u)KS_MODIFIER;
2722 typeahead[typeaheadlen++] = modifiers;
2723 }
2724
2725 typeaheadlen += n;
2726
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002727# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00002728 if (fdDump)
2729 fputc(c, fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002730# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002731 }
2732 }
2733 }
2734
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002735# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00002736 if (fdDump)
2737 {
2738 fputs("]\n", fdDump);
2739 fflush(fdDump);
2740 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002741# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002742
Bram Moolenaar071d4272004-06-13 20:20:40 +00002743theend:
Bram Moolenaar0f873732019-12-05 20:28:46 +01002744 // Move typeahead to "buf", as much as fits.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002745 len = 0;
2746 while (len < maxlen && typeaheadlen > 0)
2747 {
2748 buf[len++] = typeahead[0];
2749 mch_memmove(typeahead, typeahead + 1, --typeaheadlen);
2750 }
Bram Moolenaar4c5678f2022-11-30 18:12:19 +00002751# ifdef FEAT_EVAL
Bram Moolenaar7ca86fe2020-09-03 19:25:11 +02002752 if (len > 0)
2753 {
2754 buf[len] = NUL;
2755 ch_log(NULL, "raw key input: \"%s\"", buf);
2756 }
K.Takata6e1d31e2022-02-03 13:05:32 +00002757# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002758 return len;
2759
Bram Moolenaar0f873732019-12-05 20:28:46 +01002760#else // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00002761 return 0;
Bram Moolenaar0f873732019-12-05 20:28:46 +01002762#endif // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00002763}
2764
Bram Moolenaar82881492012-11-20 16:53:39 +01002765#ifndef PROTO
2766# ifndef __MINGW32__
Bram Moolenaar0f873732019-12-05 20:28:46 +01002767# include <shellapi.h> // required for FindExecutable()
Bram Moolenaar82881492012-11-20 16:53:39 +01002768# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002769#endif
2770
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002771/*
Bram Moolenaar95da1362020-05-30 18:37:55 +02002772 * Return TRUE if "name" is an executable file, FALSE if not or it doesn't exist.
Bram Moolenaar43663192017-03-05 14:29:12 +01002773 * When returning TRUE and "path" is not NULL save the path and set "*path" to
2774 * the allocated memory.
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00002775 * TODO: Should somehow check if it's really executable.
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002776 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002777 static int
Bram Moolenaar95da1362020-05-30 18:37:55 +02002778executable_file(char *name, char_u **path)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002779{
LemonBoy40fd7e62022-05-05 20:18:16 +01002780 int attrs = win32_getattrs((char_u *)name);
2781
2782 // The file doesn't exist or is a folder.
2783 if (attrs == -1 || (attrs & FILE_ATTRIBUTE_DIRECTORY))
2784 return FALSE;
2785 // Check if the file is an AppExecLink, a special alias used by Windows
2786 // Store for its apps.
2787 if (attrs & FILE_ATTRIBUTE_REPARSE_POINT)
Bram Moolenaar43663192017-03-05 14:29:12 +01002788 {
LemonBoy40fd7e62022-05-05 20:18:16 +01002789 char_u *res = resolve_appexeclink((char_u *)name);
2790 if (res == NULL)
AmberArrf5d0f542023-08-20 20:03:45 +02002791 res = resolve_reparse_point((char_u *)name);
2792 if (res == NULL)
LemonBoy40fd7e62022-05-05 20:18:16 +01002793 return FALSE;
2794 // The path is already absolute.
Bram Moolenaar95da1362020-05-30 18:37:55 +02002795 if (path != NULL)
LemonBoy40fd7e62022-05-05 20:18:16 +01002796 *path = res;
2797 else
2798 vim_free(res);
Bram Moolenaar95da1362020-05-30 18:37:55 +02002799 }
LemonBoy40fd7e62022-05-05 20:18:16 +01002800 else if (path != NULL)
2801 *path = FullName_save((char_u *)name, FALSE);
2802 return TRUE;
Bram Moolenaar95da1362020-05-30 18:37:55 +02002803}
2804
2805/*
2806 * If "use_path" is TRUE: Return TRUE if "name" is in $PATH.
2807 * If "use_path" is FALSE: Return TRUE if "name" exists.
2808 * If "use_pathext" is TRUE search "name" with extensions in $PATHEXT.
2809 * When returning TRUE and "path" is not NULL save the path and set "*path" to
2810 * the allocated memory.
2811 */
2812 static int
2813executable_exists(char *name, char_u **path, int use_path, int use_pathext)
2814{
2815 // WinNT and later can use _MAX_PATH wide characters for a pathname, which
2816 // means that the maximum pathname is _MAX_PATH * 3 bytes when 'enc' is
2817 // UTF-8.
2818 char_u buf[_MAX_PATH * 3];
2819 size_t len = STRLEN(name);
2820 size_t tmplen;
2821 char_u *p, *e, *e2;
2822 char_u *pathbuf = NULL;
2823 char_u *pathext = NULL;
2824 char_u *pathextbuf = NULL;
Mike Williamsa3d1b292021-06-30 20:56:00 +02002825 char_u *shname = NULL;
Bram Moolenaar95da1362020-05-30 18:37:55 +02002826 int noext = FALSE;
2827 int retval = FALSE;
2828
2829 if (len >= sizeof(buf)) // safety check
Bram Moolenaar43663192017-03-05 14:29:12 +01002830 return FALSE;
Bram Moolenaar95da1362020-05-30 18:37:55 +02002831
2832 // Using the name directly when a Unix-shell like 'shell'.
Mike Williamsa3d1b292021-06-30 20:56:00 +02002833 shname = gettail(p_sh);
2834 if (strstr((char *)shname, "sh") != NULL &&
2835 !(strstr((char *)shname, "powershell") != NULL
2836 || strstr((char *)shname, "pwsh") != NULL))
Bram Moolenaar95da1362020-05-30 18:37:55 +02002837 noext = TRUE;
2838
2839 if (use_pathext)
2840 {
2841 pathext = mch_getenv("PATHEXT");
2842 if (pathext == NULL)
2843 pathext = (char_u *)".com;.exe;.bat;.cmd";
2844
2845 if (noext == FALSE)
2846 {
2847 /*
2848 * Loop over all extensions in $PATHEXT.
2849 * Check "name" ends with extension.
2850 */
2851 p = pathext;
2852 while (*p)
2853 {
2854 if (p[0] == ';'
2855 || (p[0] == '.' && (p[1] == NUL || p[1] == ';')))
2856 {
2857 // Skip empty or single ".".
2858 ++p;
2859 continue;
2860 }
2861 e = vim_strchr(p, ';');
2862 if (e == NULL)
2863 e = p + STRLEN(p);
2864 tmplen = e - p;
2865
2866 if (_strnicoll(name + len - tmplen, (char *)p, tmplen) == 0)
2867 {
2868 noext = TRUE;
2869 break;
2870 }
2871
2872 p = e;
2873 }
2874 }
Bram Moolenaar43663192017-03-05 14:29:12 +01002875 }
2876
Dominique Pelleaf4a61a2021-12-27 17:21:41 +00002877 // Prepend single "." to pathext, it means no extension added.
Bram Moolenaar95da1362020-05-30 18:37:55 +02002878 if (pathext == NULL)
2879 pathext = (char_u *)".";
2880 else if (noext == TRUE)
2881 {
2882 if (pathextbuf == NULL)
2883 pathextbuf = alloc(STRLEN(pathext) + 3);
2884 if (pathextbuf == NULL)
2885 {
2886 retval = FALSE;
2887 goto theend;
2888 }
2889 STRCPY(pathextbuf, ".;");
2890 STRCAT(pathextbuf, pathext);
2891 pathext = pathextbuf;
2892 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002893
Bram Moolenaar95da1362020-05-30 18:37:55 +02002894 // Use $PATH when "use_path" is TRUE and "name" is basename.
2895 if (use_path && gettail((char_u *)name) == (char_u *)name)
2896 {
2897 p = mch_getenv("PATH");
2898 if (p != NULL)
2899 {
2900 pathbuf = alloc(STRLEN(p) + 3);
2901 if (pathbuf == NULL)
2902 {
2903 retval = FALSE;
2904 goto theend;
2905 }
Yasuhiro Matsumoto05cf63e2022-05-03 11:02:28 +01002906
2907 if (mch_getenv("NoDefaultCurrentDirectoryInExePath") == NULL)
2908 STRCPY(pathbuf, ".;");
2909 else
2910 *pathbuf = NUL;
Bram Moolenaar95da1362020-05-30 18:37:55 +02002911 STRCAT(pathbuf, p);
2912 }
2913 }
2914
2915 /*
2916 * Walk through all entries in $PATH to check if "name" exists there and
2917 * is an executable file.
2918 */
2919 p = (pathbuf != NULL) ? pathbuf : (char_u *)".";
2920 while (*p)
2921 {
2922 if (*p == ';') // Skip empty entry
2923 {
2924 ++p;
2925 continue;
2926 }
2927 e = vim_strchr(p, ';');
2928 if (e == NULL)
2929 e = p + STRLEN(p);
2930
2931 if (e - p + len + 2 > sizeof(buf))
2932 {
2933 retval = FALSE;
2934 goto theend;
2935 }
2936 // A single "." that means current dir.
2937 if (e - p == 1 && *p == '.')
2938 STRCPY(buf, name);
2939 else
2940 {
2941 vim_strncpy(buf, p, e - p);
2942 add_pathsep(buf);
2943 STRCAT(buf, name);
2944 }
2945 tmplen = STRLEN(buf);
2946
2947 /*
2948 * Loop over all extensions in $PATHEXT.
2949 * Check "name" with extension added.
2950 */
2951 p = pathext;
2952 while (*p)
2953 {
2954 if (*p == ';')
2955 {
2956 // Skip empty entry
2957 ++p;
2958 continue;
2959 }
2960 e2 = vim_strchr(p, (int)';');
2961 if (e2 == NULL)
2962 e2 = p + STRLEN(p);
2963
2964 if (!(p[0] == '.' && (p[1] == NUL || p[1] == ';')))
2965 {
2966 // Not a single "." that means no extension is added.
2967 if (e2 - p + tmplen + 1 > sizeof(buf))
2968 {
2969 retval = FALSE;
2970 goto theend;
2971 }
2972 vim_strncpy(buf + tmplen, p, e2 - p);
2973 }
2974 if (executable_file((char *)buf, path))
2975 {
2976 retval = TRUE;
2977 goto theend;
2978 }
2979
2980 p = e2;
2981 }
2982
2983 p = e;
2984 }
2985
2986theend:
2987 free(pathextbuf);
2988 free(pathbuf);
2989 return retval;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002990}
2991
Bram Moolenaar1eed5322019-02-26 17:03:54 +01002992#if (defined(__MINGW32__) && __MSVCRT_VERSION__ >= 0x800) || \
2993 (defined(_MSC_VER) && _MSC_VER >= 1400)
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002994/*
2995 * Bad parameter handler.
2996 *
2997 * Certain MS CRT functions will intentionally crash when passed invalid
2998 * parameters to highlight possible security holes. Setting this function as
2999 * the bad parameter handler will prevent the crash.
3000 *
3001 * In debug builds the parameters contain CRT information that might help track
3002 * down the source of a problem, but in non-debug builds the arguments are all
3003 * NULL/0. Debug builds will also produce assert dialogs from the CRT, it is
3004 * worth allowing these to make debugging of issues easier.
3005 */
3006 static void
Yegappan Lakshmanana34b4462022-06-11 10:43:26 +01003007bad_param_handler(const wchar_t *expression UNUSED,
3008 const wchar_t *function UNUSED,
3009 const wchar_t *file UNUSED,
3010 unsigned int line UNUSED,
3011 uintptr_t pReserved UNUSED)
Bram Moolenaard32a99a2010-09-21 17:29:23 +02003012{
3013}
3014
3015# define SET_INVALID_PARAM_HANDLER \
3016 ((void)_set_invalid_parameter_handler(bad_param_handler))
3017#else
3018# define SET_INVALID_PARAM_HANDLER
3019#endif
3020
Bram Moolenaar4f974752019-02-17 17:44:42 +01003021#ifdef FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00003022
3023/*
3024 * GUI version of mch_init().
3025 */
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003026 static void
3027mch_init_g(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003028{
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003029# ifndef __MINGW32__
Bram Moolenaar071d4272004-06-13 20:20:40 +00003030 extern int _fmode;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003031# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003032
Bram Moolenaar0f873732019-12-05 20:28:46 +01003033 // Silently handle invalid parameters to CRT functions
Bram Moolenaard32a99a2010-09-21 17:29:23 +02003034 SET_INVALID_PARAM_HANDLER;
3035
Bram Moolenaar0f873732019-12-05 20:28:46 +01003036 // Let critical errors result in a failure, not in a dialog box. Required
3037 // for the timestamp test to work on removed floppies.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003038 SetErrorMode(SEM_FAILCRITICALERRORS);
3039
Bram Moolenaar0f873732019-12-05 20:28:46 +01003040 _fmode = O_BINARY; // we do our own CR-LF translation
Bram Moolenaar071d4272004-06-13 20:20:40 +00003041
Bram Moolenaar0f873732019-12-05 20:28:46 +01003042 // Specify window size. Is there a place to get the default from?
Bram Moolenaar071d4272004-06-13 20:20:40 +00003043 Rows = 25;
3044 Columns = 80;
3045
Bram Moolenaar0f873732019-12-05 20:28:46 +01003046 // Look for 'vimrun'
Bram Moolenaar071d4272004-06-13 20:20:40 +00003047 {
3048 char_u vimrun_location[_MAX_PATH + 4];
3049
Bram Moolenaar0f873732019-12-05 20:28:46 +01003050 // First try in same directory as gvim.exe
Bram Moolenaar071d4272004-06-13 20:20:40 +00003051 STRCPY(vimrun_location, exe_name);
3052 STRCPY(gettail(vimrun_location), "vimrun.exe");
3053 if (mch_getperm(vimrun_location) >= 0)
3054 {
3055 if (*skiptowhite(vimrun_location) != NUL)
3056 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01003057 // Enclose path with white space in double quotes.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003058 mch_memmove(vimrun_location + 1, vimrun_location,
3059 STRLEN(vimrun_location) + 1);
3060 *vimrun_location = '"';
3061 STRCPY(gettail(vimrun_location), "vimrun\" ");
3062 }
3063 else
3064 STRCPY(gettail(vimrun_location), "vimrun ");
3065
3066 vimrun_path = (char *)vim_strsave(vimrun_location);
3067 s_dont_use_vimrun = FALSE;
3068 }
Bram Moolenaar95da1362020-05-30 18:37:55 +02003069 else if (executable_exists("vimrun.exe", NULL, TRUE, FALSE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003070 s_dont_use_vimrun = FALSE;
3071
Bram Moolenaar0f873732019-12-05 20:28:46 +01003072 // Don't give the warning for a missing vimrun.exe right now, but only
3073 // when vimrun was supposed to be used. Don't bother people that do
3074 // not need vimrun.exe.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003075 if (s_dont_use_vimrun)
3076 need_vimrun_warning = TRUE;
3077 }
3078
3079 /*
3080 * If "finstr.exe" doesn't exist, use "grep -n" for 'grepprg'.
3081 * Otherwise the default "findstr /n" is used.
3082 */
Bram Moolenaar95da1362020-05-30 18:37:55 +02003083 if (!executable_exists("findstr.exe", NULL, TRUE, FALSE))
Bram Moolenaar75ab5902022-04-18 15:36:40 +01003084 set_option_value_give_err((char_u *)"grepprg",
3085 0, (char_u *)"grep -n", 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003086
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003087# ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01003088 win_clip_init();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003089# endif
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01003090
3091 vtp_flag_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00003092}
3093
3094
Bram Moolenaar0f873732019-12-05 20:28:46 +01003095#endif // FEAT_GUI_MSWIN
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003096
3097#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003098
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003099# define SRWIDTH(sr) ((sr).Right - (sr).Left + 1)
3100# define SRHEIGHT(sr) ((sr).Bottom - (sr).Top + 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003101
3102/*
3103 * ClearConsoleBuffer()
3104 * Description:
3105 * Clears the entire contents of the console screen buffer, using the
3106 * specified attribute.
3107 * Returns:
3108 * TRUE on success
3109 */
3110 static BOOL
3111ClearConsoleBuffer(WORD wAttribute)
3112{
3113 CONSOLE_SCREEN_BUFFER_INFO csbi;
3114 COORD coord;
3115 DWORD NumCells, dummy;
3116
3117 if (!GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3118 return FALSE;
3119
3120 NumCells = csbi.dwSize.X * csbi.dwSize.Y;
3121 coord.X = 0;
3122 coord.Y = 0;
3123 if (!FillConsoleOutputCharacter(g_hConOut, ' ', NumCells,
3124 coord, &dummy))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003125 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003126 if (!FillConsoleOutputAttribute(g_hConOut, wAttribute, NumCells,
3127 coord, &dummy))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003128 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003129
3130 return TRUE;
3131}
3132
3133/*
3134 * FitConsoleWindow()
3135 * Description:
3136 * Checks if the console window will fit within given buffer dimensions.
3137 * Also, if requested, will shrink the window to fit.
3138 * Returns:
3139 * TRUE on success
3140 */
3141 static BOOL
3142FitConsoleWindow(
3143 COORD dwBufferSize,
3144 BOOL WantAdjust)
3145{
3146 CONSOLE_SCREEN_BUFFER_INFO csbi;
3147 COORD dwWindowSize;
3148 BOOL NeedAdjust = FALSE;
3149
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00003150 if (!GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3151 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003152
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00003153 /*
3154 * A buffer resize will fail if the current console window does
3155 * not lie completely within that buffer. To avoid this, we might
3156 * have to move and possibly shrink the window.
3157 */
3158 if (csbi.srWindow.Right >= dwBufferSize.X)
3159 {
3160 dwWindowSize.X = SRWIDTH(csbi.srWindow);
3161 if (dwWindowSize.X > dwBufferSize.X)
3162 dwWindowSize.X = dwBufferSize.X;
3163 csbi.srWindow.Right = dwBufferSize.X - 1;
3164 csbi.srWindow.Left = dwBufferSize.X - dwWindowSize.X;
3165 NeedAdjust = TRUE;
3166 }
3167 if (csbi.srWindow.Bottom >= dwBufferSize.Y)
3168 {
3169 dwWindowSize.Y = SRHEIGHT(csbi.srWindow);
3170 if (dwWindowSize.Y > dwBufferSize.Y)
3171 dwWindowSize.Y = dwBufferSize.Y;
3172 csbi.srWindow.Bottom = dwBufferSize.Y - 1;
3173 csbi.srWindow.Top = dwBufferSize.Y - dwWindowSize.Y;
3174 NeedAdjust = TRUE;
3175 }
3176 if (NeedAdjust && WantAdjust)
3177 {
3178 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &csbi.srWindow))
3179 return FALSE;
3180 }
3181 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003182}
3183
3184typedef struct ConsoleBufferStruct
3185{
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003186 BOOL IsValid;
3187 CONSOLE_SCREEN_BUFFER_INFO Info;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003188 PCHAR_INFO Buffer;
3189 COORD BufferSize;
Bram Moolenaar444fda22017-08-11 20:37:00 +02003190 PSMALL_RECT Regions;
3191 int NumRegions;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003192} ConsoleBuffer;
3193
3194/*
3195 * SaveConsoleBuffer()
3196 * Description:
3197 * Saves important information about the console buffer, including the
3198 * actual buffer contents. The saved information is suitable for later
3199 * restoration by RestoreConsoleBuffer().
3200 * Returns:
3201 * TRUE if all information was saved; FALSE otherwise
3202 * If FALSE, still sets cb->IsValid if buffer characteristics were saved.
3203 */
3204 static BOOL
3205SaveConsoleBuffer(
3206 ConsoleBuffer *cb)
3207{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003208 DWORD NumCells;
3209 COORD BufferCoord;
3210 SMALL_RECT ReadRegion;
3211 WORD Y, Y_incr;
Bram Moolenaar444fda22017-08-11 20:37:00 +02003212 int i, numregions;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003213
Bram Moolenaar071d4272004-06-13 20:20:40 +00003214 if (cb == NULL)
3215 return FALSE;
3216
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003217 if (!GetConsoleScreenBufferInfo(g_hConOut, &cb->Info))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003218 {
3219 cb->IsValid = FALSE;
3220 return FALSE;
3221 }
3222 cb->IsValid = TRUE;
3223
Christopher Plewright1140b512022-11-12 18:46:05 +00003224 // VTP uses alternate screen buffer.
3225 // No need to save buffer contents for restoration.
Christopher Plewrightc8b126d2022-12-22 13:45:23 +00003226 if (use_alternate_screen_buffer)
Christopher Plewright1140b512022-11-12 18:46:05 +00003227 return TRUE;
3228
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003229 /*
3230 * Allocate a buffer large enough to hold the entire console screen
3231 * buffer. If this ConsoleBuffer structure has already been initialized
3232 * with a buffer of the correct size, then just use that one.
3233 */
3234 if (!cb->IsValid || cb->Buffer == NULL ||
3235 cb->BufferSize.X != cb->Info.dwSize.X ||
3236 cb->BufferSize.Y != cb->Info.dwSize.Y)
3237 {
3238 cb->BufferSize.X = cb->Info.dwSize.X;
3239 cb->BufferSize.Y = cb->Info.dwSize.Y;
3240 NumCells = cb->BufferSize.X * cb->BufferSize.Y;
3241 vim_free(cb->Buffer);
Bram Moolenaarc799fe22019-05-28 23:08:19 +02003242 cb->Buffer = ALLOC_MULT(CHAR_INFO, NumCells);
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003243 if (cb->Buffer == NULL)
3244 return FALSE;
3245 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003246
3247 /*
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003248 * We will now copy the console screen buffer into our buffer.
3249 * ReadConsoleOutput() seems to be limited as far as how much you
3250 * can read at a time. Empirically, this number seems to be about
3251 * 12000 cells (rows * columns). Start at position (0, 0) and copy
3252 * in chunks until it is all copied. The chunks will all have the
3253 * same horizontal characteristics, so initialize them now. The
3254 * height of each chunk will be (12000 / width).
Bram Moolenaar071d4272004-06-13 20:20:40 +00003255 */
Bram Moolenaar61594242015-09-01 20:23:37 +02003256 BufferCoord.X = 0;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003257 ReadRegion.Left = 0;
3258 ReadRegion.Right = cb->Info.dwSize.X - 1;
3259 Y_incr = 12000 / cb->Info.dwSize.X;
Bram Moolenaar444fda22017-08-11 20:37:00 +02003260
3261 numregions = (cb->Info.dwSize.Y + Y_incr - 1) / Y_incr;
3262 if (cb->Regions == NULL || numregions != cb->NumRegions)
3263 {
3264 cb->NumRegions = numregions;
3265 vim_free(cb->Regions);
Bram Moolenaarc799fe22019-05-28 23:08:19 +02003266 cb->Regions = ALLOC_MULT(SMALL_RECT, cb->NumRegions);
Bram Moolenaar444fda22017-08-11 20:37:00 +02003267 if (cb->Regions == NULL)
3268 {
Bram Moolenaard23a8232018-02-10 18:45:26 +01003269 VIM_CLEAR(cb->Buffer);
Bram Moolenaar444fda22017-08-11 20:37:00 +02003270 return FALSE;
3271 }
3272 }
3273
3274 for (i = 0, Y = 0; i < cb->NumRegions; i++, Y += Y_incr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003275 {
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003276 /*
3277 * Read into position (0, Y) in our buffer.
3278 */
3279 BufferCoord.Y = Y;
3280 /*
3281 * Read the region whose top left corner is (0, Y) and whose bottom
3282 * right corner is (width - 1, Y + Y_incr - 1). This should define
3283 * a region of size width by Y_incr. Don't worry if this region is
3284 * too large for the remaining buffer; it will be cropped.
3285 */
3286 ReadRegion.Top = Y;
3287 ReadRegion.Bottom = Y + Y_incr - 1;
Bram Moolenaar0f873732019-12-05 20:28:46 +01003288 if (!ReadConsoleOutputW(g_hConOut, // output handle
3289 cb->Buffer, // our buffer
3290 cb->BufferSize, // dimensions of our buffer
3291 BufferCoord, // offset in our buffer
3292 &ReadRegion)) // region to save
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003293 {
Bram Moolenaard23a8232018-02-10 18:45:26 +01003294 VIM_CLEAR(cb->Buffer);
3295 VIM_CLEAR(cb->Regions);
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003296 return FALSE;
3297 }
Bram Moolenaar444fda22017-08-11 20:37:00 +02003298 cb->Regions[i] = ReadRegion;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003299 }
3300
3301 return TRUE;
3302}
3303
3304/*
3305 * RestoreConsoleBuffer()
3306 * Description:
3307 * Restores important information about the console buffer, including the
3308 * actual buffer contents, if desired. The information to restore is in
3309 * the same format used by SaveConsoleBuffer().
3310 * Returns:
3311 * TRUE on success
3312 */
3313 static BOOL
3314RestoreConsoleBuffer(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003315 ConsoleBuffer *cb,
3316 BOOL RestoreScreen)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003317{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003318 COORD BufferCoord;
3319 SMALL_RECT WriteRegion;
Bram Moolenaar444fda22017-08-11 20:37:00 +02003320 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003321
Christopher Plewright1140b512022-11-12 18:46:05 +00003322 // VTP uses alternate screen buffer.
3323 // No need to restore buffer contents.
Christopher Plewrightc8b126d2022-12-22 13:45:23 +00003324 if (use_alternate_screen_buffer)
Christopher Plewright1140b512022-11-12 18:46:05 +00003325 return TRUE;
3326
Bram Moolenaar071d4272004-06-13 20:20:40 +00003327 if (cb == NULL || !cb->IsValid)
3328 return FALSE;
3329
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003330 /*
3331 * Before restoring the buffer contents, clear the current buffer, and
3332 * restore the cursor position and window information. Doing this now
3333 * prevents old buffer contents from "flashing" onto the screen.
3334 */
3335 if (RestoreScreen)
3336 ClearConsoleBuffer(cb->Info.wAttributes);
3337
3338 FitConsoleWindow(cb->Info.dwSize, TRUE);
3339 if (!SetConsoleScreenBufferSize(g_hConOut, cb->Info.dwSize))
3340 return FALSE;
3341 if (!SetConsoleTextAttribute(g_hConOut, cb->Info.wAttributes))
3342 return FALSE;
3343
3344 if (!RestoreScreen)
3345 {
3346 /*
3347 * No need to restore the screen buffer contents, so we're done.
3348 */
3349 return TRUE;
3350 }
3351
3352 if (!SetConsoleCursorPosition(g_hConOut, cb->Info.dwCursorPosition))
3353 return FALSE;
3354 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &cb->Info.srWindow))
3355 return FALSE;
3356
3357 /*
3358 * Restore the screen buffer contents.
3359 */
3360 if (cb->Buffer != NULL)
3361 {
Bram Moolenaar444fda22017-08-11 20:37:00 +02003362 for (i = 0; i < cb->NumRegions; i++)
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003363 {
Bram Moolenaar444fda22017-08-11 20:37:00 +02003364 BufferCoord.X = cb->Regions[i].Left;
3365 BufferCoord.Y = cb->Regions[i].Top;
3366 WriteRegion = cb->Regions[i];
Bram Moolenaar0f873732019-12-05 20:28:46 +01003367 if (!WriteConsoleOutputW(g_hConOut, // output handle
3368 cb->Buffer, // our buffer
3369 cb->BufferSize, // dimensions of our buffer
3370 BufferCoord, // offset in our buffer
3371 &WriteRegion)) // region to restore
Bram Moolenaar444fda22017-08-11 20:37:00 +02003372 return FALSE;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003373 }
3374 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003375
3376 return TRUE;
3377}
3378
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003379# define FEAT_RESTORE_ORIG_SCREEN
3380# ifdef FEAT_RESTORE_ORIG_SCREEN
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003381static ConsoleBuffer g_cbOrig = { 0 };
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003382# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003383static ConsoleBuffer g_cbNonTermcap = { 0 };
3384static ConsoleBuffer g_cbTermcap = { 0 };
3385
Bram Moolenaar071d4272004-06-13 20:20:40 +00003386char g_szOrigTitle[256] = { 0 };
Bram Moolenaar0f873732019-12-05 20:28:46 +01003387HWND g_hWnd = NULL; // also used in os_mswin.c
Bram Moolenaar071d4272004-06-13 20:20:40 +00003388static HICON g_hOrigIconSmall = NULL;
3389static HICON g_hOrigIcon = NULL;
3390static HICON g_hVimIcon = NULL;
3391static BOOL g_fCanChangeIcon = FALSE;
3392
Bram Moolenaar071d4272004-06-13 20:20:40 +00003393/*
3394 * GetConsoleIcon()
3395 * Description:
3396 * Attempts to retrieve the small icon and/or the big icon currently in
3397 * use by a given window.
3398 * Returns:
3399 * TRUE on success
3400 */
3401 static BOOL
3402GetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003403 HWND hWnd,
3404 HICON *phIconSmall,
3405 HICON *phIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003406{
3407 if (hWnd == NULL)
3408 return FALSE;
3409
3410 if (phIconSmall != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003411 *phIconSmall = (HICON)SendMessage(hWnd, WM_GETICON,
3412 (WPARAM)ICON_SMALL, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003413 if (phIcon != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003414 *phIcon = (HICON)SendMessage(hWnd, WM_GETICON,
3415 (WPARAM)ICON_BIG, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003416 return TRUE;
3417}
3418
3419/*
3420 * SetConsoleIcon()
3421 * Description:
3422 * Attempts to change the small icon and/or the big icon currently in
3423 * use by a given window.
3424 * Returns:
3425 * TRUE on success
3426 */
3427 static BOOL
3428SetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003429 HWND hWnd,
3430 HICON hIconSmall,
3431 HICON hIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003432{
Bram Moolenaar071d4272004-06-13 20:20:40 +00003433 if (hWnd == NULL)
3434 return FALSE;
3435
3436 if (hIconSmall != NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003437 SendMessage(hWnd, WM_SETICON,
3438 (WPARAM)ICON_SMALL, (LPARAM)hIconSmall);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003439 if (hIcon != NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003440 SendMessage(hWnd, WM_SETICON,
3441 (WPARAM)ICON_BIG, (LPARAM) hIcon);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003442 return TRUE;
3443}
3444
3445/*
3446 * SaveConsoleTitleAndIcon()
3447 * Description:
3448 * Saves the current console window title in g_szOrigTitle, for later
3449 * restoration. Also, attempts to obtain a handle to the console window,
3450 * and use it to save the small and big icons currently in use by the
3451 * console window. This is not always possible on some versions of Windows;
3452 * nor is it possible when running Vim remotely using Telnet (since the
3453 * console window the user sees is owned by a remote process).
3454 */
3455 static void
3456SaveConsoleTitleAndIcon(void)
3457{
Bram Moolenaar0f873732019-12-05 20:28:46 +01003458 // Save the original title.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003459 if (!GetConsoleTitle(g_szOrigTitle, sizeof(g_szOrigTitle)))
3460 return;
3461
3462 /*
3463 * Obtain a handle to the console window using GetConsoleWindow() from
3464 * KERNEL32.DLL; we need to handle in order to change the window icon.
3465 * This function only exists on NT-based Windows, starting with Windows
3466 * 2000. On older operating systems, we can't change the window icon
3467 * anyway.
3468 */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003469 g_hWnd = GetConsoleWindow();
Bram Moolenaar071d4272004-06-13 20:20:40 +00003470 if (g_hWnd == NULL)
3471 return;
3472
Bram Moolenaar0f873732019-12-05 20:28:46 +01003473 // Save the original console window icon.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003474 GetConsoleIcon(g_hWnd, &g_hOrigIconSmall, &g_hOrigIcon);
3475 if (g_hOrigIconSmall == NULL || g_hOrigIcon == NULL)
3476 return;
3477
Bram Moolenaar0f873732019-12-05 20:28:46 +01003478 // Extract the first icon contained in the Vim executable.
K.Takata2da11a42022-09-10 13:03:12 +01003479 if (
3480# ifdef FEAT_LIBCALL
3481 mch_icon_load((HANDLE *)&g_hVimIcon) == FAIL ||
3482# endif
3483 g_hVimIcon == NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003484 g_hVimIcon = ExtractIcon(NULL, (LPCSTR)exe_name, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003485 if (g_hVimIcon != NULL)
3486 g_fCanChangeIcon = TRUE;
3487}
Bram Moolenaar071d4272004-06-13 20:20:40 +00003488
3489static int g_fWindInitCalled = FALSE;
3490static int g_fTermcapMode = FALSE;
3491static CONSOLE_CURSOR_INFO g_cci;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003492
3493/*
3494 * non-GUI version of mch_init().
3495 */
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003496 static void
3497mch_init_c(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003498{
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003499# ifndef FEAT_RESTORE_ORIG_SCREEN
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003500 CONSOLE_SCREEN_BUFFER_INFO csbi;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003501# endif
3502# ifndef __MINGW32__
Bram Moolenaar071d4272004-06-13 20:20:40 +00003503 extern int _fmode;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003504# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003505
Bram Moolenaar0f873732019-12-05 20:28:46 +01003506 // Silently handle invalid parameters to CRT functions
Bram Moolenaard32a99a2010-09-21 17:29:23 +02003507 SET_INVALID_PARAM_HANDLER;
3508
Bram Moolenaar0f873732019-12-05 20:28:46 +01003509 // Let critical errors result in a failure, not in a dialog box. Required
3510 // for the timestamp test to work on removed floppies.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003511 SetErrorMode(SEM_FAILCRITICALERRORS);
3512
Bram Moolenaar0f873732019-12-05 20:28:46 +01003513 _fmode = O_BINARY; // we do our own CR-LF translation
Bram Moolenaar071d4272004-06-13 20:20:40 +00003514 out_flush();
3515
Bram Moolenaar0f873732019-12-05 20:28:46 +01003516 // Obtain handles for the standard Console I/O devices
Bram Moolenaar071d4272004-06-13 20:20:40 +00003517 if (read_cmd_fd == 0)
3518 g_hConIn = GetStdHandle(STD_INPUT_HANDLE);
3519 else
3520 create_conin();
3521 g_hConOut = GetStdHandle(STD_OUTPUT_HANDLE);
3522
Christopher Plewright38804d62022-11-09 23:55:52 +00003523 wt_init();
3524 vtp_flag_init();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003525# ifdef FEAT_RESTORE_ORIG_SCREEN
Bram Moolenaar0f873732019-12-05 20:28:46 +01003526 // Save the initial console buffer for later restoration
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003527 SaveConsoleBuffer(&g_cbOrig);
3528 g_attrCurrent = g_attrDefault = g_cbOrig.Info.wAttributes;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003529# else
Bram Moolenaar0f873732019-12-05 20:28:46 +01003530 // Get current text attributes
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003531 GetConsoleScreenBufferInfo(g_hConOut, &csbi);
3532 g_attrCurrent = g_attrDefault = csbi.wAttributes;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003533# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003534 if (cterm_normal_fg_color == 0)
3535 cterm_normal_fg_color = (g_attrCurrent & 0xf) + 1;
3536 if (cterm_normal_bg_color == 0)
3537 cterm_normal_bg_color = ((g_attrCurrent >> 4) & 0xf) + 1;
3538
Bram Moolenaarbdace832019-03-02 10:13:42 +01003539 // Fg and Bg color index number at startup
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02003540 g_color_index_fg = g_attrDefault & 0xf;
3541 g_color_index_bg = (g_attrDefault >> 4) & 0xf;
3542
Bram Moolenaar0f873732019-12-05 20:28:46 +01003543 // set termcap codes to current text attributes
Bram Moolenaar071d4272004-06-13 20:20:40 +00003544 update_tcap(g_attrCurrent);
3545
3546 GetConsoleCursorInfo(g_hConOut, &g_cci);
3547 GetConsoleMode(g_hConIn, &g_cmodein);
3548 GetConsoleMode(g_hConOut, &g_cmodeout);
3549
Bram Moolenaar071d4272004-06-13 20:20:40 +00003550 SaveConsoleTitleAndIcon();
3551 /*
3552 * Set both the small and big icons of the console window to Vim's icon.
3553 * Note that Vim presently only has one size of icon (32x32), but it
3554 * automatically gets scaled down to 16x16 when setting the small icon.
3555 */
3556 if (g_fCanChangeIcon)
3557 SetConsoleIcon(g_hWnd, g_hVimIcon, g_hVimIcon);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003558
3559 ui_get_shellsize();
3560
Christopher Plewrightd343c602023-01-22 18:58:30 +00003561 vtp_init();
Christopher Plewrightf75a2cb2023-01-28 10:28:09 +00003562 // Switch to a new alternate screen buffer.
3563 if (use_alternate_screen_buffer)
3564 vtp_printf("\033[?1049h");
Christopher Plewrightd343c602023-01-22 18:58:30 +00003565
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003566# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00003567 fdDump = fopen("dump", "wt");
3568
3569 if (fdDump)
3570 {
3571 time_t t;
3572
3573 time(&t);
3574 fputs(ctime(&t), fdDump);
3575 fflush(fdDump);
3576 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003577# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003578
3579 g_fWindInitCalled = TRUE;
3580
Bram Moolenaar071d4272004-06-13 20:20:40 +00003581 g_fMouseAvail = GetSystemMetrics(SM_MOUSEPRESENT);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003582
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003583# ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01003584 win_clip_init();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003585# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003586}
3587
3588/*
3589 * non-GUI version of mch_exit().
3590 * Shut down and exit with status `r'
3591 * Careful: mch_exit() may be called before mch_init()!
3592 */
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003593 static void
3594mch_exit_c(int r)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003595{
Bram Moolenaar955f1982017-02-05 15:10:51 +01003596 exiting = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003597
Bram Moolenaarcafafb32018-02-22 21:07:09 +01003598 vtp_exit();
3599
Bram Moolenaar955f1982017-02-05 15:10:51 +01003600 stoptermcap();
Bram Moolenaar071d4272004-06-13 20:20:40 +00003601 if (g_fWindInitCalled)
3602 settmode(TMODE_COOK);
3603
Bram Moolenaar0f873732019-12-05 20:28:46 +01003604 ml_close_all(TRUE); // remove all memfiles
Bram Moolenaar071d4272004-06-13 20:20:40 +00003605
3606 if (g_fWindInitCalled)
3607 {
Bram Moolenaar40385db2018-08-07 22:31:44 +02003608 mch_restore_title(SAVE_RESTORE_BOTH);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003609 /*
3610 * Restore both the small and big icons of the console window to
3611 * what they were at startup. Don't do this when the window is
3612 * closed, Vim would hang here.
3613 */
3614 if (g_fCanChangeIcon && !g_fForceExit)
3615 SetConsoleIcon(g_hWnd, g_hOrigIconSmall, g_hOrigIcon);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003616
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003617# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00003618 if (fdDump)
3619 {
3620 time_t t;
3621
3622 time(&t);
3623 fputs(ctime(&t), fdDump);
3624 fclose(fdDump);
3625 }
3626 fdDump = NULL;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003627# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003628 }
3629
3630 SetConsoleCursorInfo(g_hConOut, &g_cci);
Wez Furlong6ef5ab52021-05-30 19:29:41 +02003631 SetConsoleMode(g_hConIn, g_cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003632 SetConsoleMode(g_hConOut, g_cmodeout);
3633
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003634# ifdef DYNAMIC_GETTEXT
Bram Moolenaar071d4272004-06-13 20:20:40 +00003635 dyn_libintl_end();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003636# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003637
3638 exit(r);
3639}
Bram Moolenaar0f873732019-12-05 20:28:46 +01003640#endif // !FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00003641
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003642 void
3643mch_init(void)
3644{
3645#ifdef VIMDLL
3646 if (gui.starting)
3647 mch_init_g();
3648 else
3649 mch_init_c();
3650#elif defined(FEAT_GUI_MSWIN)
3651 mch_init_g();
3652#else
3653 mch_init_c();
3654#endif
3655}
3656
3657 void
3658mch_exit(int r)
3659{
Bram Moolenaar173d8412020-04-19 14:02:26 +02003660#ifdef FEAT_NETBEANS_INTG
3661 netbeans_send_disconnect();
3662#endif
3663
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003664#ifdef VIMDLL
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02003665 if (gui.in_use || gui.starting)
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003666 mch_exit_g(r);
3667 else
3668 mch_exit_c(r);
3669#elif defined(FEAT_GUI_MSWIN)
3670 mch_exit_g(r);
3671#else
3672 mch_exit_c(r);
3673#endif
3674}
3675
Bram Moolenaar071d4272004-06-13 20:20:40 +00003676/*
3677 * Do we have an interactive window?
3678 */
3679 int
3680mch_check_win(
Bram Moolenaar1266d672017-02-01 13:43:36 +01003681 int argc UNUSED,
3682 char **argv UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003683{
K.Takatace3189d2023-02-15 19:13:43 +00003684 mch_get_exe_name();
Bram Moolenaar071d4272004-06-13 20:20:40 +00003685
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003686#if defined(FEAT_GUI_MSWIN) && !defined(VIMDLL)
Bram Moolenaar0f873732019-12-05 20:28:46 +01003687 return OK; // GUI always has a tty
Bram Moolenaar071d4272004-06-13 20:20:40 +00003688#else
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003689# ifdef VIMDLL
3690 if (gui.in_use)
3691 return OK;
3692# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003693 if (isatty(1))
3694 return OK;
3695 return FAIL;
3696#endif
3697}
3698
Bram Moolenaar65f04f62013-08-30 17:29:16 +02003699/*
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003700 * Set the case of the file name, if it already exists.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003701 * When "len" is > 0, also expand short to long filenames.
3702 */
3703 void
3704fname_case(
3705 char_u *name,
3706 int len)
3707{
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003708 int flen;
3709 WCHAR *p;
3710 WCHAR buf[_MAX_PATH + 1];
Bram Moolenaar071d4272004-06-13 20:20:40 +00003711
Bram Moolenaara3ffd9c2005-07-21 21:03:15 +00003712 flen = (int)STRLEN(name);
Bram Moolenaar65f04f62013-08-30 17:29:16 +02003713 if (flen == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003714 return;
3715
3716 slash_adjust(name);
3717
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003718 p = enc_to_utf16(name, NULL);
3719 if (p == NULL)
Bram Moolenaar65f04f62013-08-30 17:29:16 +02003720 return;
3721
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003722 if (GetLongPathNameW(p, buf, _MAX_PATH))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003723 {
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003724 char_u *q = utf16_to_enc(buf, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003725
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003726 if (q != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003727 {
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003728 if (len > 0 || flen >= (int)STRLEN(q))
3729 vim_strncpy(name, q, (len > 0) ? len - 1 : flen);
3730 vim_free(q);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003731 }
3732 }
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003733 vim_free(p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003734}
3735
3736
3737/*
3738 * Insert user name in s[len].
3739 */
3740 int
3741mch_get_user_name(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003742 char_u *s,
3743 int len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003744{
Bram Moolenaar0f873732019-12-05 20:28:46 +01003745 WCHAR wszUserName[256 + 1]; // UNLEN is 256
K.Takataeeec2542021-06-02 13:28:16 +02003746 DWORD wcch = ARRAY_LENGTH(wszUserName);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003747
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003748 if (GetUserNameW(wszUserName, &wcch))
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003749 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003750 char_u *p = utf16_to_enc(wszUserName, NULL);
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003751
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003752 if (p != NULL)
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003753 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003754 vim_strncpy(s, p, len - 1);
3755 vim_free(p);
3756 return OK;
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003757 }
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003758 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003759 s[0] = NUL;
3760 return FAIL;
3761}
3762
3763
3764/*
3765 * Insert host name in s[len].
3766 */
3767 void
3768mch_get_host_name(
3769 char_u *s,
3770 int len)
3771{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003772 WCHAR wszHostName[256 + 1];
K.Takataeeec2542021-06-02 13:28:16 +02003773 DWORD wcch = ARRAY_LENGTH(wszHostName);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003774
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00003775 if (!GetComputerNameW(wszHostName, &wcch))
3776 return;
Bram Moolenaar2cc87382013-12-11 18:21:45 +01003777
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00003778 char_u *p = utf16_to_enc(wszHostName, NULL);
3779 if (p == NULL)
3780 return;
3781
3782 vim_strncpy(s, p, len - 1);
3783 vim_free(p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003784}
3785
3786
3787/*
3788 * return process ID
3789 */
3790 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003791mch_get_pid(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003792{
3793 return (long)GetCurrentProcessId();
3794}
3795
Bram Moolenaar67cf86b2019-04-28 22:25:38 +02003796/*
3797 * return TRUE if process "pid" is still running
3798 */
3799 int
Bram Moolenaar1b243ea2019-04-28 22:50:40 +02003800mch_process_running(long pid)
Bram Moolenaar67cf86b2019-04-28 22:25:38 +02003801{
3802 HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION, 0, (DWORD)pid);
3803 DWORD status = 0;
3804 int ret = FALSE;
3805
3806 if (hProcess == NULL)
3807 return FALSE; // might not have access
3808 if (GetExitCodeProcess(hProcess, &status) )
3809 ret = status == STILL_ACTIVE;
3810 CloseHandle(hProcess);
3811 return ret;
3812}
Bram Moolenaar071d4272004-06-13 20:20:40 +00003813
3814/*
3815 * Get name of current directory into buffer 'buf' of length 'len' bytes.
3816 * Return OK for success, FAIL for failure.
3817 */
3818 int
3819mch_dirname(
3820 char_u *buf,
3821 int len)
3822{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003823 WCHAR wbuf[_MAX_PATH + 1];
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02003824
Bram Moolenaar071d4272004-06-13 20:20:40 +00003825 /*
3826 * Originally this was:
3827 * return (getcwd(buf, len) != NULL ? OK : FAIL);
3828 * But the Win32s known bug list says that getcwd() doesn't work
3829 * so use the Win32 system call instead. <Negri>
3830 */
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00003831 if (GetCurrentDirectoryW(_MAX_PATH, wbuf) == 0)
3832 return FAIL;
3833
3834 WCHAR wcbuf[_MAX_PATH + 1];
3835 char_u *p = NULL;
3836
3837 if (GetLongPathNameW(wbuf, wcbuf, _MAX_PATH) != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003838 {
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00003839 p = utf16_to_enc(wcbuf, NULL);
3840 if (STRLEN(p) >= (size_t)len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003841 {
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00003842 // long path name is too long, fall back to short one
Yegappan Lakshmanan960dcbd2023-03-07 17:45:11 +00003843 VIM_CLEAR(p);
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003844 }
3845 }
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00003846 if (p == NULL)
3847 p = utf16_to_enc(wbuf, NULL);
3848
3849 if (p == NULL)
3850 return FAIL;
3851
3852 vim_strncpy(buf, p, len - 1);
3853 vim_free(p);
3854 return OK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003855}
3856
3857/*
Bram Moolenaarffa22202013-11-21 12:34:11 +01003858 * Get file permissions for "name".
3859 * Return mode_t or -1 for error.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003860 */
3861 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003862mch_getperm(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003863{
Bram Moolenaar8767f522016-07-01 17:17:39 +02003864 stat_T st;
Bram Moolenaarffa22202013-11-21 12:34:11 +01003865 int n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003866
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003867 n = mch_stat((char *)name, &st);
Bram Moolenaar78cf3f02014-01-10 18:16:07 +01003868 return n == 0 ? (long)(unsigned short)st.st_mode : -1L;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003869}
3870
3871
3872/*
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003873 * Set file permission for "name" to "perm".
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003874 *
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003875 * Return FAIL for failure, OK otherwise.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003876 */
3877 int
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003878mch_setperm(char_u *name, long perm)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003879{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003880 long n;
3881 WCHAR *p;
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003882
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003883 p = enc_to_utf16(name, NULL);
3884 if (p == NULL)
3885 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003886
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003887 n = _wchmod(p, perm);
3888 vim_free(p);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003889 if (n == -1)
3890 return FAIL;
3891
3892 win32_set_archive(name);
3893
3894 return OK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003895}
3896
3897/*
3898 * Set hidden flag for "name".
3899 */
3900 void
3901mch_hide(char_u *name)
3902{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003903 int attrs = win32_getattrs(name);
3904 if (attrs == -1)
3905 return;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003906
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003907 attrs |= FILE_ATTRIBUTE_HIDDEN;
3908 win32_setattrs(name, attrs);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003909}
3910
3911/*
Bram Moolenaar8a52ba72015-11-02 14:45:56 +01003912 * Return TRUE if file "name" exists and is hidden.
3913 */
3914 int
3915mch_ishidden(char_u *name)
3916{
3917 int f = win32_getattrs(name);
3918
3919 if (f == -1)
Bram Moolenaar0f873732019-12-05 20:28:46 +01003920 return FALSE; // file does not exist at all
Bram Moolenaar8a52ba72015-11-02 14:45:56 +01003921
3922 return (f & FILE_ATTRIBUTE_HIDDEN) != 0;
3923}
3924
3925/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003926 * return TRUE if "name" is a directory
3927 * return FALSE if "name" is not a directory or upon error
3928 */
3929 int
3930mch_isdir(char_u *name)
3931{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003932 int f = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003933
3934 if (f == -1)
Bram Moolenaar0f873732019-12-05 20:28:46 +01003935 return FALSE; // file does not exist at all
Bram Moolenaar071d4272004-06-13 20:20:40 +00003936
3937 return (f & FILE_ATTRIBUTE_DIRECTORY) != 0;
3938}
3939
3940/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01003941 * return TRUE if "name" is a directory, NOT a symlink to a directory
3942 * return FALSE if "name" is not a directory
3943 * return FALSE for error
3944 */
3945 int
3946mch_isrealdir(char_u *name)
3947{
3948 return mch_isdir(name) && !mch_is_symbolic_link(name);
3949}
3950
3951/*
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003952 * Create directory "name".
3953 * Return 0 on success, -1 on error.
3954 */
3955 int
3956mch_mkdir(char_u *name)
3957{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003958 WCHAR *p;
3959 int retval;
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003960
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003961 p = enc_to_utf16(name, NULL);
3962 if (p == NULL)
3963 return -1;
3964 retval = _wmkdir(p);
3965 vim_free(p);
3966 return retval;
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003967}
3968
3969/*
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003970 * Delete directory "name".
3971 * Return 0 on success, -1 on error.
3972 */
3973 int
3974mch_rmdir(char_u *name)
3975{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003976 WCHAR *p;
3977 int retval;
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003978
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003979 p = enc_to_utf16(name, NULL);
3980 if (p == NULL)
3981 return -1;
3982 retval = _wrmdir(p);
3983 vim_free(p);
3984 return retval;
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003985}
3986
3987/*
Bram Moolenaar03f48552006-02-28 23:52:23 +00003988 * Return TRUE if file "fname" has more than one link.
3989 */
3990 int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003991mch_is_hard_link(char_u *fname)
Bram Moolenaar03f48552006-02-28 23:52:23 +00003992{
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003993 BY_HANDLE_FILE_INFORMATION info;
3994
3995 return win32_fileinfo(fname, &info) == FILEINFO_OK
3996 && info.nNumberOfLinks > 1;
3997}
3998
3999/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01004000 * Return TRUE if "name" is a symbolic link (or a junction).
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004001 */
4002 int
Bram Moolenaar203258c2016-01-17 22:15:16 +01004003mch_is_symbolic_link(char_u *name)
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004004{
4005 HANDLE hFind;
4006 int res = FALSE;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004007 DWORD fileFlags = 0, reparseTag = 0;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004008 WCHAR *wn;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004009 WIN32_FIND_DATAW findDataW;
4010
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004011 wn = enc_to_utf16(name, NULL);
4012 if (wn == NULL)
4013 return FALSE;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004014
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004015 hFind = FindFirstFileW(wn, &findDataW);
4016 vim_free(wn);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004017 if (hFind != INVALID_HANDLE_VALUE)
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004018 {
4019 fileFlags = findDataW.dwFileAttributes;
4020 reparseTag = findDataW.dwReserved0;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004021 FindClose(hFind);
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004022 }
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004023
4024 if ((fileFlags & FILE_ATTRIBUTE_REPARSE_POINT)
Bram Moolenaar203258c2016-01-17 22:15:16 +01004025 && (reparseTag == IO_REPARSE_TAG_SYMLINK
4026 || reparseTag == IO_REPARSE_TAG_MOUNT_POINT))
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004027 res = TRUE;
4028
4029 return res;
4030}
4031
4032/*
4033 * Return TRUE if file "fname" has more than one link or if it is a symbolic
4034 * link.
4035 */
4036 int
4037mch_is_linked(char_u *fname)
4038{
4039 if (mch_is_hard_link(fname) || mch_is_symbolic_link(fname))
4040 return TRUE;
4041 return FALSE;
4042}
4043
4044/*
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02004045 * Get the by-handle-file-information for "fname".
4046 * Returns FILEINFO_OK when OK.
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004047 * Returns FILEINFO_ENC_FAIL when enc_to_utf16() failed.
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02004048 * Returns FILEINFO_READ_FAIL when CreateFile() failed.
4049 * Returns FILEINFO_INFO_FAIL when GetFileInformationByHandle() failed.
4050 */
4051 int
4052win32_fileinfo(char_u *fname, BY_HANDLE_FILE_INFORMATION *info)
4053{
Bram Moolenaar03f48552006-02-28 23:52:23 +00004054 HANDLE hFile;
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02004055 int res = FILEINFO_READ_FAIL;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004056 WCHAR *wn;
Bram Moolenaar03f48552006-02-28 23:52:23 +00004057
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004058 wn = enc_to_utf16(fname, NULL);
4059 if (wn == NULL)
4060 return FILEINFO_ENC_FAIL;
4061
4062 hFile = CreateFileW(wn, // file name
4063 GENERIC_READ, // access mode
4064 FILE_SHARE_READ | FILE_SHARE_WRITE, // share mode
4065 NULL, // security descriptor
4066 OPEN_EXISTING, // creation disposition
4067 FILE_FLAG_BACKUP_SEMANTICS, // file attributes
4068 NULL); // handle to template file
4069 vim_free(wn);
Bram Moolenaar03f48552006-02-28 23:52:23 +00004070
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00004071 if (hFile == INVALID_HANDLE_VALUE)
4072 return FILEINFO_READ_FAIL;
4073
4074 if (GetFileInformationByHandle(hFile, info) != 0)
4075 res = FILEINFO_OK;
4076 else
4077 res = FILEINFO_INFO_FAIL;
4078 CloseHandle(hFile);
Bram Moolenaar03f48552006-02-28 23:52:23 +00004079
Bram Moolenaar03f48552006-02-28 23:52:23 +00004080 return res;
4081}
4082
4083/*
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004084 * get file attributes for `name'
4085 * -1 : error
4086 * else FILE_ATTRIBUTE_* defined in winnt.h
4087 */
Bram Moolenaarffa22202013-11-21 12:34:11 +01004088 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004089win32_getattrs(char_u *name)
4090{
4091 int attr;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004092 WCHAR *p;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004093
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004094 p = enc_to_utf16(name, NULL);
4095 if (p == NULL)
4096 return INVALID_FILE_ATTRIBUTES;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004097
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004098 attr = GetFileAttributesW(p);
4099 vim_free(p);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004100
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004101 return attr;
4102}
4103
4104/*
4105 * set file attributes for `name' to `attrs'
4106 *
4107 * return -1 for failure, 0 otherwise
4108 */
Bram Moolenaar6dff58f2018-09-30 21:43:26 +02004109 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004110win32_setattrs(char_u *name, int attrs)
4111{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004112 int res;
4113 WCHAR *p;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004114
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004115 p = enc_to_utf16(name, NULL);
4116 if (p == NULL)
4117 return -1;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004118
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004119 res = SetFileAttributesW(p, attrs);
4120 vim_free(p);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004121
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004122 return res ? 0 : -1;
4123}
4124
4125/*
4126 * Set archive flag for "name".
4127 */
Bram Moolenaar6dff58f2018-09-30 21:43:26 +02004128 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004129win32_set_archive(char_u *name)
4130{
4131 int attrs = win32_getattrs(name);
4132 if (attrs == -1)
4133 return -1;
4134
4135 attrs |= FILE_ATTRIBUTE_ARCHIVE;
4136 return win32_setattrs(name, attrs);
4137}
4138
4139/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00004140 * Return TRUE if file or directory "name" is writable (not readonly).
4141 * Strange semantics of Win32: a readonly directory is writable, but you can't
4142 * delete a file. Let's say this means it is writable.
4143 */
4144 int
4145mch_writable(char_u *name)
4146{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004147 int attrs = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004148
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004149 return (attrs != -1 && (!(attrs & FILE_ATTRIBUTE_READONLY)
4150 || (attrs & FILE_ATTRIBUTE_DIRECTORY)));
Bram Moolenaar071d4272004-06-13 20:20:40 +00004151}
4152
Bram Moolenaar071d4272004-06-13 20:20:40 +00004153/*
Bram Moolenaar43663192017-03-05 14:29:12 +01004154 * Return TRUE if "name" can be executed, FALSE if not.
Bram Moolenaar77b77102015-03-21 22:18:41 +01004155 * If "use_path" is FALSE only check if "name" is executable.
Bram Moolenaar43663192017-03-05 14:29:12 +01004156 * When returning TRUE and "path" is not NULL save the path and set "*path" to
4157 * the allocated memory.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004158 */
4159 int
Yegappan Lakshmananebb01bd2022-06-08 15:14:09 +01004160mch_can_exe(char_u *name, char_u **path, int use_path UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004161{
Bram Moolenaar95da1362020-05-30 18:37:55 +02004162 return executable_exists((char *)name, path, TRUE, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004163}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004164
4165/*
4166 * Check what "name" is:
4167 * NODE_NORMAL: file or directory (or doesn't exist)
4168 * NODE_WRITABLE: writable device, socket, fifo, etc.
4169 * NODE_OTHER: non-writable things
4170 */
4171 int
4172mch_nodetype(char_u *name)
4173{
4174 HANDLE hFile;
4175 int type;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004176 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004177
Bram Moolenaar0f873732019-12-05 20:28:46 +01004178 // We can't open a file with a name "\\.\con" or "\\.\prn" and trying to
4179 // read from it later will cause Vim to hang. Thus return NODE_WRITABLE
4180 // here.
Bram Moolenaar043545e2006-10-10 16:44:07 +00004181 if (STRNCMP(name, "\\\\.\\", 4) == 0)
4182 return NODE_WRITABLE;
4183
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004184 wn = enc_to_utf16(name, NULL);
4185 if (wn == NULL)
4186 return NODE_NORMAL;
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004187
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004188 hFile = CreateFileW(wn, // file name
4189 GENERIC_WRITE, // access mode
4190 0, // share mode
4191 NULL, // security descriptor
4192 OPEN_EXISTING, // creation disposition
4193 0, // file attributes
4194 NULL); // handle to template file
4195 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004196 if (hFile == INVALID_HANDLE_VALUE)
4197 return NODE_NORMAL;
4198
4199 type = GetFileType(hFile);
4200 CloseHandle(hFile);
4201 if (type == FILE_TYPE_CHAR)
4202 return NODE_WRITABLE;
4203 if (type == FILE_TYPE_DISK)
4204 return NODE_NORMAL;
4205 return NODE_OTHER;
4206}
4207
4208#ifdef HAVE_ACL
4209struct my_acl
4210{
4211 PSECURITY_DESCRIPTOR pSecurityDescriptor;
4212 PSID pSidOwner;
4213 PSID pSidGroup;
4214 PACL pDacl;
4215 PACL pSacl;
4216};
4217#endif
4218
4219/*
4220 * Return a pointer to the ACL of file "fname" in allocated memory.
4221 * Return NULL if the ACL is not available for whatever reason.
4222 */
4223 vim_acl_T
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004224mch_get_acl(char_u *fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004225{
4226#ifndef HAVE_ACL
4227 return (vim_acl_T)NULL;
4228#else
4229 struct my_acl *p = NULL;
Bram Moolenaar27515922013-06-29 15:36:26 +02004230 DWORD err;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004231
Bram Moolenaarc799fe22019-05-28 23:08:19 +02004232 p = ALLOC_CLEAR_ONE(struct my_acl);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004233 if (p != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004234 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004235 WCHAR *wn;
Bram Moolenaar27515922013-06-29 15:36:26 +02004236
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004237 wn = enc_to_utf16(fname, NULL);
4238 if (wn == NULL)
Bram Moolenaarbbf9f342020-11-10 22:03:40 +01004239 {
4240 vim_free(p);
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004241 return NULL;
Bram Moolenaarbbf9f342020-11-10 22:03:40 +01004242 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004243
4244 // Try to retrieve the entire security descriptor.
4245 err = GetNamedSecurityInfoW(
4246 wn, // Abstract filename
4247 SE_FILE_OBJECT, // File Object
4248 OWNER_SECURITY_INFORMATION |
4249 GROUP_SECURITY_INFORMATION |
4250 DACL_SECURITY_INFORMATION |
4251 SACL_SECURITY_INFORMATION,
4252 &p->pSidOwner, // Ownership information.
4253 &p->pSidGroup, // Group membership.
4254 &p->pDacl, // Discretionary information.
4255 &p->pSacl, // For auditing purposes.
4256 &p->pSecurityDescriptor);
4257 if (err == ERROR_ACCESS_DENIED ||
4258 err == ERROR_PRIVILEGE_NOT_HELD)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004259 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004260 // Retrieve only DACL.
4261 (void)GetNamedSecurityInfoW(
4262 wn,
4263 SE_FILE_OBJECT,
4264 DACL_SECURITY_INFORMATION,
4265 NULL,
4266 NULL,
4267 &p->pDacl,
4268 NULL,
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004269 &p->pSecurityDescriptor);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004270 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004271 if (p->pSecurityDescriptor == NULL)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004272 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004273 mch_free_acl((vim_acl_T)p);
4274 p = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004275 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004276 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004277 }
4278
4279 return (vim_acl_T)p;
4280#endif
4281}
4282
Bram Moolenaar27515922013-06-29 15:36:26 +02004283#ifdef HAVE_ACL
4284/*
4285 * Check if "acl" contains inherited ACE.
4286 */
4287 static BOOL
4288is_acl_inherited(PACL acl)
4289{
4290 DWORD i;
4291 ACL_SIZE_INFORMATION acl_info;
4292 PACCESS_ALLOWED_ACE ace;
4293
4294 acl_info.AceCount = 0;
4295 GetAclInformation(acl, &acl_info, sizeof(acl_info), AclSizeInformation);
4296 for (i = 0; i < acl_info.AceCount; i++)
4297 {
4298 GetAce(acl, i, (LPVOID *)&ace);
4299 if (ace->Header.AceFlags & INHERITED_ACE)
4300 return TRUE;
4301 }
4302 return FALSE;
4303}
4304#endif
4305
Bram Moolenaar071d4272004-06-13 20:20:40 +00004306/*
4307 * Set the ACL of file "fname" to "acl" (unless it's NULL).
4308 * Errors are ignored.
4309 * This must only be called with "acl" equal to what mch_get_acl() returned.
4310 */
4311 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004312mch_set_acl(char_u *fname, vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004313{
4314#ifdef HAVE_ACL
4315 struct my_acl *p = (struct my_acl *)acl;
Bram Moolenaar27515922013-06-29 15:36:26 +02004316 SECURITY_INFORMATION sec_info = 0;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004317 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004318
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004319 if (p == NULL)
4320 return;
4321
4322 wn = enc_to_utf16(fname, NULL);
4323 if (wn == NULL)
4324 return;
4325
4326 // Set security flags
4327 if (p->pSidOwner)
4328 sec_info |= OWNER_SECURITY_INFORMATION;
4329 if (p->pSidGroup)
4330 sec_info |= GROUP_SECURITY_INFORMATION;
4331 if (p->pDacl)
Bram Moolenaar27515922013-06-29 15:36:26 +02004332 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004333 sec_info |= DACL_SECURITY_INFORMATION;
4334 // Do not inherit its parent's DACL.
4335 // If the DACL is inherited, Cygwin permissions would be changed.
4336 if (!is_acl_inherited(p->pDacl))
4337 sec_info |= PROTECTED_DACL_SECURITY_INFORMATION;
Bram Moolenaar27515922013-06-29 15:36:26 +02004338 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004339 if (p->pSacl)
4340 sec_info |= SACL_SECURITY_INFORMATION;
4341
4342 (void)SetNamedSecurityInfoW(
4343 wn, // Abstract filename
4344 SE_FILE_OBJECT, // File Object
4345 sec_info,
4346 p->pSidOwner, // Ownership information.
4347 p->pSidGroup, // Group membership.
4348 p->pDacl, // Discretionary information.
4349 p->pSacl // For auditing purposes.
4350 );
4351 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004352#endif
4353}
4354
4355 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004356mch_free_acl(vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004357{
4358#ifdef HAVE_ACL
4359 struct my_acl *p = (struct my_acl *)acl;
4360
4361 if (p != NULL)
4362 {
4363 LocalFree(p->pSecurityDescriptor); // Free the memory just in case
4364 vim_free(p);
4365 }
4366#endif
4367}
4368
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004369#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004370
4371/*
4372 * handler for ctrl-break, ctrl-c interrupts, and fatal events.
4373 */
4374 static BOOL WINAPI
4375handler_routine(
4376 DWORD dwCtrlType)
4377{
Bram Moolenaar589b1102017-08-12 16:39:05 +02004378 INPUT_RECORD ir;
4379 DWORD out;
4380
Bram Moolenaar071d4272004-06-13 20:20:40 +00004381 switch (dwCtrlType)
4382 {
4383 case CTRL_C_EVENT:
4384 if (ctrl_c_interrupts)
4385 g_fCtrlCPressed = TRUE;
4386 return TRUE;
4387
4388 case CTRL_BREAK_EVENT:
4389 g_fCBrkPressed = TRUE;
Bram Moolenaar589b1102017-08-12 16:39:05 +02004390 ctrl_break_was_pressed = TRUE;
Bram Moolenaar0f873732019-12-05 20:28:46 +01004391 // ReadConsoleInput is blocking, send a key event to continue.
Bram Moolenaar589b1102017-08-12 16:39:05 +02004392 ir.EventType = KEY_EVENT;
4393 ir.Event.KeyEvent.bKeyDown = TRUE;
4394 ir.Event.KeyEvent.wRepeatCount = 1;
4395 ir.Event.KeyEvent.wVirtualKeyCode = VK_CANCEL;
4396 ir.Event.KeyEvent.wVirtualScanCode = 0;
4397 ir.Event.KeyEvent.dwControlKeyState = 0;
4398 ir.Event.KeyEvent.uChar.UnicodeChar = 0;
4399 WriteConsoleInput(g_hConIn, &ir, 1, &out);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004400 return TRUE;
4401
Bram Moolenaar0f873732019-12-05 20:28:46 +01004402 // fatal events: shut down gracefully
Bram Moolenaar071d4272004-06-13 20:20:40 +00004403 case CTRL_CLOSE_EVENT:
4404 case CTRL_LOGOFF_EVENT:
4405 case CTRL_SHUTDOWN_EVENT:
4406 windgoto((int)Rows - 1, 0);
4407 g_fForceExit = TRUE;
4408
Bram Moolenaar0fde2902008-03-16 13:54:13 +00004409 vim_snprintf((char *)IObuff, IOSIZE, _("Vim: Caught %s event\n"),
Bram Moolenaar071d4272004-06-13 20:20:40 +00004410 (dwCtrlType == CTRL_CLOSE_EVENT
4411 ? _("close")
4412 : dwCtrlType == CTRL_LOGOFF_EVENT
4413 ? _("logoff")
4414 : _("shutdown")));
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004415# ifdef DEBUG
Bram Moolenaar071d4272004-06-13 20:20:40 +00004416 OutputDebugString(IObuff);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004417# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004418
Bram Moolenaar0f873732019-12-05 20:28:46 +01004419 preserve_exit(); // output IObuff, preserve files and exit
Bram Moolenaar071d4272004-06-13 20:20:40 +00004420
Bram Moolenaar0f873732019-12-05 20:28:46 +01004421 return TRUE; // not reached
Bram Moolenaar071d4272004-06-13 20:20:40 +00004422
4423 default:
4424 return FALSE;
4425 }
4426}
4427
4428
4429/*
4430 * set the tty in (raw) ? "raw" : "cooked" mode
4431 */
4432 void
Bram Moolenaar26e86442020-05-17 14:06:16 +02004433mch_settmode(tmode_T tmode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004434{
4435 DWORD cmodein;
4436 DWORD cmodeout;
4437 BOOL bEnableHandler;
4438
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004439# ifdef VIMDLL
4440 if (gui.in_use)
4441 return;
4442# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004443 GetConsoleMode(g_hConIn, &cmodein);
4444 GetConsoleMode(g_hConOut, &cmodeout);
4445 if (tmode == TMODE_RAW)
4446 {
4447 cmodein &= ~(ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
4448 ENABLE_ECHO_INPUT);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004449 if (g_fMouseActive)
Wez Furlong6ef5ab52021-05-30 19:29:41 +02004450 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00004451 cmodein |= ENABLE_MOUSE_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02004452 cmodein &= ~ENABLE_QUICK_EDIT_MODE;
4453 }
4454 else
4455 {
4456 cmodein |= g_cmodein & ENABLE_QUICK_EDIT_MODE;
4457 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01004458 cmodeout &= ~(
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004459# ifdef FEAT_TERMGUICOLORS
Bram Moolenaar0f873732019-12-05 20:28:46 +01004460 // Do not turn off the ENABLE_PROCESSED_OUTPUT flag when using
4461 // VTP.
Bram Moolenaarcafafb32018-02-22 21:07:09 +01004462 ((vtp_working) ? 0 : ENABLE_PROCESSED_OUTPUT) |
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004463# else
Bram Moolenaarcafafb32018-02-22 21:07:09 +01004464 ENABLE_PROCESSED_OUTPUT |
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004465# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01004466 ENABLE_WRAP_AT_EOL_OUTPUT);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004467 bEnableHandler = TRUE;
4468 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01004469 else // cooked
Bram Moolenaar071d4272004-06-13 20:20:40 +00004470 {
4471 cmodein |= (ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
4472 ENABLE_ECHO_INPUT);
4473 cmodeout |= (ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
4474 bEnableHandler = FALSE;
4475 }
Wez Furlong6ef5ab52021-05-30 19:29:41 +02004476 SetConsoleMode(g_hConIn, cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004477 SetConsoleMode(g_hConOut, cmodeout);
4478 SetConsoleCtrlHandler(handler_routine, bEnableHandler);
4479
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004480# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00004481 if (fdDump)
4482 {
4483 fprintf(fdDump, "mch_settmode(%s, in = %x, out = %x)\n",
4484 tmode == TMODE_RAW ? "raw" :
4485 tmode == TMODE_COOK ? "cooked" : "normal",
4486 cmodein, cmodeout);
4487 fflush(fdDump);
4488 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004489# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004490}
4491
4492
4493/*
4494 * Get the size of the current window in `Rows' and `Columns'
4495 * Return OK when size could be determined, FAIL otherwise.
4496 */
4497 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004498mch_get_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004499{
4500 CONSOLE_SCREEN_BUFFER_INFO csbi;
4501
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004502# ifdef VIMDLL
4503 if (gui.in_use)
4504 return OK;
4505# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004506 if (!g_fTermcapMode && g_cbTermcap.IsValid)
4507 {
4508 /*
4509 * For some reason, we are trying to get the screen dimensions
4510 * even though we are not in termcap mode. The 'Rows' and 'Columns'
4511 * variables are really intended to mean the size of Vim screen
4512 * while in termcap mode.
4513 */
4514 Rows = g_cbTermcap.Info.dwSize.Y;
4515 Columns = g_cbTermcap.Info.dwSize.X;
4516 }
4517 else if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
4518 {
4519 Rows = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
4520 Columns = csbi.srWindow.Right - csbi.srWindow.Left + 1;
4521 }
4522 else
4523 {
4524 Rows = 25;
4525 Columns = 80;
4526 }
4527 return OK;
4528}
4529
4530/*
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004531 * Resize console buffer to 'COORD'
4532 */
4533 static void
4534ResizeConBuf(
4535 HANDLE hConsole,
4536 COORD coordScreen)
4537{
Christopher Plewrightf75a2cb2023-01-28 10:28:09 +00004538 if (use_alternate_screen_buffer)
4539 return;
4540
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004541 if (!SetConsoleScreenBufferSize(hConsole, coordScreen))
4542 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004543# ifdef MCH_WRITE_DUMP
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004544 if (fdDump)
4545 {
4546 fprintf(fdDump, "SetConsoleScreenBufferSize failed: %lx\n",
4547 GetLastError());
4548 fflush(fdDump);
4549 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004550# endif
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004551 }
4552}
4553
4554/*
4555 * Resize console window size to 'srWindowRect'
4556 */
4557 static void
4558ResizeWindow(
4559 HANDLE hConsole,
4560 SMALL_RECT srWindowRect)
4561{
4562 if (!SetConsoleWindowInfo(hConsole, TRUE, &srWindowRect))
4563 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004564# ifdef MCH_WRITE_DUMP
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004565 if (fdDump)
4566 {
4567 fprintf(fdDump, "SetConsoleWindowInfo failed: %lx\n",
4568 GetLastError());
4569 fflush(fdDump);
4570 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004571# endif
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004572 }
4573}
4574
4575/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00004576 * Set a console window to `xSize' * `ySize'
4577 */
4578 static void
4579ResizeConBufAndWindow(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004580 HANDLE hConsole,
4581 int xSize,
4582 int ySize)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004583{
Bram Moolenaar0f873732019-12-05 20:28:46 +01004584 CONSOLE_SCREEN_BUFFER_INFO csbi; // hold current console buffer info
4585 SMALL_RECT srWindowRect; // hold the new console size
Bram Moolenaar071d4272004-06-13 20:20:40 +00004586 COORD coordScreen;
Bram Moolenaarf49a6922019-07-15 20:37:05 +02004587 COORD cursor;
Bram Moolenaar2551c032018-08-23 22:38:31 +02004588 static int resized = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004589
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004590# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00004591 if (fdDump)
4592 {
4593 fprintf(fdDump, "ResizeConBufAndWindow(%d, %d)\n", xSize, ySize);
4594 fflush(fdDump);
4595 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004596# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004597
Bram Moolenaar0f873732019-12-05 20:28:46 +01004598 // get the largest size we can size the console window to
Bram Moolenaar071d4272004-06-13 20:20:40 +00004599 coordScreen = GetLargestConsoleWindowSize(hConsole);
4600
Bram Moolenaar0f873732019-12-05 20:28:46 +01004601 // define the new console window size and scroll position
Bram Moolenaar071d4272004-06-13 20:20:40 +00004602 srWindowRect.Left = srWindowRect.Top = (SHORT) 0;
4603 srWindowRect.Right = (SHORT) (min(xSize, coordScreen.X) - 1);
4604 srWindowRect.Bottom = (SHORT) (min(ySize, coordScreen.Y) - 1);
4605
4606 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
4607 {
4608 int sx, sy;
4609
4610 sx = csbi.srWindow.Right - csbi.srWindow.Left + 1;
4611 sy = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
4612 if (sy < ySize || sx < xSize)
4613 {
4614 /*
4615 * Increasing number of lines/columns, do buffer first.
4616 * Use the maximal size in x and y direction.
4617 */
4618 if (sy < ySize)
4619 coordScreen.Y = ySize;
4620 else
4621 coordScreen.Y = sy;
4622 if (sx < xSize)
4623 coordScreen.X = xSize;
4624 else
4625 coordScreen.X = sx;
4626 SetConsoleScreenBufferSize(hConsole, coordScreen);
4627 }
4628 }
4629
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004630 // define the new console buffer size
Bram Moolenaar071d4272004-06-13 20:20:40 +00004631 coordScreen.X = xSize;
4632 coordScreen.Y = ySize;
4633
Bram Moolenaar2551c032018-08-23 22:38:31 +02004634 // In the new console call API, only the first time in reverse order
4635 if (!vtp_working || resized)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004636 {
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004637 ResizeWindow(hConsole, srWindowRect);
4638 ResizeConBuf(hConsole, coordScreen);
4639 }
4640 else
4641 {
Bram Moolenaarf49a6922019-07-15 20:37:05 +02004642 // Workaround for a Windows 10 bug
4643 cursor.X = srWindowRect.Left;
4644 cursor.Y = srWindowRect.Top;
4645 SetConsoleCursorPosition(hConsole, cursor);
4646
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004647 ResizeConBuf(hConsole, coordScreen);
4648 ResizeWindow(hConsole, srWindowRect);
Bram Moolenaar2551c032018-08-23 22:38:31 +02004649 resized = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004650 }
4651}
4652
4653
4654/*
4655 * Set the console window to `Rows' * `Columns'
4656 */
4657 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004658mch_set_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004659{
4660 COORD coordScreen;
4661
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004662# ifdef VIMDLL
4663 if (gui.in_use)
4664 return;
4665# endif
Bram Moolenaar0f873732019-12-05 20:28:46 +01004666 // Don't change window size while still starting up
Bram Moolenaar071d4272004-06-13 20:20:40 +00004667 if (suppress_winsize != 0)
4668 {
4669 suppress_winsize = 2;
4670 return;
4671 }
4672
4673 if (term_console)
4674 {
4675 coordScreen = GetLargestConsoleWindowSize(g_hConOut);
4676
Bram Moolenaar0f873732019-12-05 20:28:46 +01004677 // Clamp Rows and Columns to reasonable values
Bram Moolenaar071d4272004-06-13 20:20:40 +00004678 if (Rows > coordScreen.Y)
4679 Rows = coordScreen.Y;
4680 if (Columns > coordScreen.X)
4681 Columns = coordScreen.X;
4682
4683 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
4684 }
4685}
4686
4687/*
4688 * Rows and/or Columns has changed.
4689 */
4690 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004691mch_new_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004692{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004693# ifdef VIMDLL
4694 if (gui.in_use)
4695 return;
4696# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004697 set_scroll_region(0, 0, Columns - 1, Rows - 1);
4698}
4699
4700
4701/*
4702 * Called when started up, to set the winsize that was delayed.
4703 */
4704 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004705mch_set_winsize_now(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004706{
4707 if (suppress_winsize == 2)
4708 {
4709 suppress_winsize = 0;
4710 mch_set_shellsize();
4711 shell_resized();
4712 }
4713 suppress_winsize = 0;
4714}
Bram Moolenaar0f873732019-12-05 20:28:46 +01004715#endif // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00004716
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004717 static BOOL
4718vim_create_process(
Bram Moolenaar36c85b22013-12-12 20:25:44 +01004719 char *cmd,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004720 BOOL inherit_handles,
Bram Moolenaar3f1138e2014-01-05 13:29:26 +01004721 DWORD flags,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004722 STARTUPINFO *si,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004723 PROCESS_INFORMATION *pi,
4724 LPVOID *env,
4725 char *cwd)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004726{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004727 BOOL ret = FALSE;
4728 WCHAR *wcmd, *wcwd = NULL;
4729
4730 wcmd = enc_to_utf16((char_u *)cmd, NULL);
4731 if (wcmd == NULL)
4732 return FALSE;
4733 if (cwd != NULL)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004734 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004735 wcwd = enc_to_utf16((char_u *)cwd, NULL);
4736 if (wcwd == NULL)
4737 goto theend;
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004738 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004739
4740 ret = CreateProcessW(
4741 NULL, // Executable name
4742 wcmd, // Command to execute
4743 NULL, // Process security attributes
4744 NULL, // Thread security attributes
4745 inherit_handles, // Inherit handles
4746 flags, // Creation flags
4747 env, // Environment
4748 wcwd, // Current directory
4749 (LPSTARTUPINFOW)si, // Startup information
4750 pi); // Process information
4751theend:
4752 vim_free(wcmd);
4753 vim_free(wcwd);
4754 return ret;
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004755}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004756
4757
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004758 static HINSTANCE
4759vim_shell_execute(
4760 char *cmd,
4761 INT n_show_cmd)
4762{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004763 HINSTANCE ret;
4764 WCHAR *wcmd;
4765
4766 wcmd = enc_to_utf16((char_u *)cmd, NULL);
4767 if (wcmd == NULL)
4768 return (HINSTANCE) 0;
4769
4770 ret = ShellExecuteW(NULL, NULL, wcmd, NULL, NULL, n_show_cmd);
4771 vim_free(wcmd);
4772 return ret;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004773}
4774
4775
Bram Moolenaar4f974752019-02-17 17:44:42 +01004776#if defined(FEAT_GUI_MSWIN) || defined(PROTO)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004777
4778/*
4779 * Specialised version of system() for Win32 GUI mode.
4780 * This version proceeds as follows:
4781 * 1. Create a console window for use by the subprocess
4782 * 2. Run the subprocess (it gets the allocated console by default)
4783 * 3. Wait for the subprocess to terminate and get its exit code
4784 * 4. Prompt the user to press a key to close the console window
4785 */
4786 static int
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004787mch_system_classic(char *cmd, int options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004788{
4789 STARTUPINFO si;
4790 PROCESS_INFORMATION pi;
4791 DWORD ret = 0;
4792 HWND hwnd = GetFocus();
4793
4794 si.cb = sizeof(si);
4795 si.lpReserved = NULL;
4796 si.lpDesktop = NULL;
4797 si.lpTitle = NULL;
4798 si.dwFlags = STARTF_USESHOWWINDOW;
4799 /*
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004800 * It's nicer to run a filter command in a minimized window.
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01004801 * Don't activate the window to keep focus on Vim.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004802 */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004803 if (options & SHELL_DOOUT)
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01004804 si.wShowWindow = SW_SHOWMINNOACTIVE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004805 else
4806 si.wShowWindow = SW_SHOWNORMAL;
4807 si.cbReserved2 = 0;
4808 si.lpReserved2 = NULL;
4809
Bram Moolenaar0f873732019-12-05 20:28:46 +01004810 // Now, run the command
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004811 vim_create_process(cmd, FALSE,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004812 CREATE_DEFAULT_ERROR_MODE | CREATE_NEW_CONSOLE,
4813 &si, &pi, NULL, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004814
Bram Moolenaar0f873732019-12-05 20:28:46 +01004815 // Wait for the command to terminate before continuing
Bram Moolenaar071d4272004-06-13 20:20:40 +00004816 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004817# ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00004818 int delay = 1;
4819
Bram Moolenaar0f873732019-12-05 20:28:46 +01004820 // Keep updating the window while waiting for the shell to finish.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004821 for (;;)
4822 {
4823 MSG msg;
4824
K.Takatab7057bd2022-01-21 11:37:07 +00004825 if (PeekMessageW(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004826 {
4827 TranslateMessage(&msg);
K.Takatab7057bd2022-01-21 11:37:07 +00004828 DispatchMessageW(&msg);
Bram Moolenaare4195c52012-08-02 12:31:44 +02004829 delay = 1;
4830 continue;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004831 }
4832 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
4833 break;
4834
Bram Moolenaar0f873732019-12-05 20:28:46 +01004835 // We start waiting for a very short time and then increase it, so
4836 // that we respond quickly when the process is quick, and don't
4837 // consume too much overhead when it's slow.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004838 if (delay < 50)
4839 delay += 10;
4840 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004841# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004842 WaitForSingleObject(pi.hProcess, INFINITE);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004843# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004844
Bram Moolenaar0f873732019-12-05 20:28:46 +01004845 // Get the command exit code
Bram Moolenaar071d4272004-06-13 20:20:40 +00004846 GetExitCodeProcess(pi.hProcess, &ret);
4847 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004848
Bram Moolenaar0f873732019-12-05 20:28:46 +01004849 // Close the handles to the subprocess, so that it goes away
Bram Moolenaar071d4272004-06-13 20:20:40 +00004850 CloseHandle(pi.hThread);
4851 CloseHandle(pi.hProcess);
4852
Bram Moolenaar0f873732019-12-05 20:28:46 +01004853 // Try to get input focus back. Doesn't always work though.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004854 PostMessage(hwnd, WM_SETFOCUS, 0, 0);
4855
4856 return ret;
4857}
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004858
4859/*
4860 * Thread launched by the gui to send the current buffer data to the
4861 * process. This way avoid to hang up vim totally if the children
4862 * process take a long time to process the lines.
4863 */
Bram Moolenaar4c38d662016-08-03 20:54:57 +02004864 static unsigned int __stdcall
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004865sub_process_writer(LPVOID param)
4866{
4867 HANDLE g_hChildStd_IN_Wr = param;
4868 linenr_T lnum = curbuf->b_op_start.lnum;
4869 DWORD len = 0;
4870 DWORD l;
4871 char_u *lp = ml_get(lnum);
4872 char_u *s;
4873 int written = 0;
4874
4875 for (;;)
4876 {
4877 l = (DWORD)STRLEN(lp + written);
4878 if (l == 0)
4879 len = 0;
4880 else if (lp[written] == NL)
4881 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004882 // NL -> NUL translation
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004883 WriteFile(g_hChildStd_IN_Wr, "", 1, &len, NULL);
4884 }
4885 else
4886 {
4887 s = vim_strchr(lp + written, NL);
4888 WriteFile(g_hChildStd_IN_Wr, (char *)lp + written,
4889 s == NULL ? l : (DWORD)(s - (lp + written)),
4890 &len, NULL);
4891 }
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +01004892 if (len == l)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004893 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004894 // Finished a line, add a NL, unless this line should not have
4895 // one.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004896 if (lnum != curbuf->b_op_end.lnum
Bram Moolenaar34d72d42015-07-17 14:18:08 +02004897 || (!curbuf->b_p_bin
4898 && curbuf->b_p_fixeol)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004899 || (lnum != curbuf->b_no_eol_lnum
4900 && (lnum != curbuf->b_ml.ml_line_count
4901 || curbuf->b_p_eol)))
4902 {
Bram Moolenaar42335f52018-09-13 15:33:43 +02004903 WriteFile(g_hChildStd_IN_Wr, "\n", 1,
4904 (LPDWORD)&vim_ignored, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004905 }
4906
4907 ++lnum;
4908 if (lnum > curbuf->b_op_end.lnum)
4909 break;
4910
4911 lp = ml_get(lnum);
4912 written = 0;
4913 }
4914 else if (len > 0)
4915 written += len;
4916 }
4917
Bram Moolenaar0f873732019-12-05 20:28:46 +01004918 // finished all the lines, close pipe
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004919 CloseHandle(g_hChildStd_IN_Wr);
Bram Moolenaar86f2cd52016-08-02 21:55:17 +02004920 return 0;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004921}
4922
4923
Bram Moolenaar0f873732019-12-05 20:28:46 +01004924# define BUFLEN 100 // length for buffer, stolen from unix version
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004925
4926/*
4927 * This function read from the children's stdout and write the
4928 * data on screen or in the buffer accordingly.
4929 */
4930 static void
4931dump_pipe(int options,
4932 HANDLE g_hChildStd_OUT_Rd,
4933 garray_T *ga,
4934 char_u buffer[],
4935 DWORD *buffer_off)
4936{
4937 DWORD availableBytes = 0;
4938 DWORD i;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004939 int ret;
4940 DWORD len;
4941 DWORD toRead;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004942
Bram Moolenaar0f873732019-12-05 20:28:46 +01004943 // we query the pipe to see if there is any data to read
4944 // to avoid to perform a blocking read
4945 ret = PeekNamedPipe(g_hChildStd_OUT_Rd, // pipe to query
4946 NULL, // optional buffer
4947 0, // buffer size
4948 NULL, // number of read bytes
4949 &availableBytes, // available bytes total
4950 NULL); // byteLeft
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004951
Bram Moolenaar0f873732019-12-05 20:28:46 +01004952 // We got real data in the pipe, read it
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02004953 while (ret != 0 && availableBytes > 0)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004954 {
Bram Moolenaara12a1612019-01-24 16:39:02 +01004955 toRead = (DWORD)(BUFLEN - *buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004956 toRead = availableBytes < toRead ? availableBytes : toRead;
Bram Moolenaara12a1612019-01-24 16:39:02 +01004957 ReadFile(g_hChildStd_OUT_Rd, buffer + *buffer_off, toRead , &len, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004958
Bram Moolenaar0f873732019-12-05 20:28:46 +01004959 // If we haven't read anything, there is a problem
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004960 if (len == 0)
4961 break;
4962
4963 availableBytes -= len;
4964
4965 if (options & SHELL_READ)
4966 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004967 // Do NUL -> NL translation, append NL separated
4968 // lines to the current buffer.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004969 for (i = 0; i < len; ++i)
4970 {
4971 if (buffer[i] == NL)
4972 append_ga_line(ga);
4973 else if (buffer[i] == NUL)
4974 ga_append(ga, NL);
4975 else
4976 ga_append(ga, buffer[i]);
4977 }
4978 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004979 else if (has_mbyte)
4980 {
4981 int l;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004982 int c;
4983 char_u *p;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004984
4985 len += *buffer_off;
4986 buffer[len] = NUL;
4987
Bram Moolenaar0f873732019-12-05 20:28:46 +01004988 // Check if the last character in buffer[] is
4989 // incomplete, keep these bytes for the next
4990 // round.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004991 for (p = buffer; p < buffer + len; p += l)
4992 {
Bram Moolenaard3c907b2016-08-17 21:32:09 +02004993 l = MB_CPTR2LEN(p);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004994 if (l == 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01004995 l = 1; // NUL byte?
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004996 else if (MB_BYTE2LEN(*p) != l)
4997 break;
4998 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01004999 if (p == buffer) // no complete character
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005000 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005001 // avoid getting stuck at an illegal byte
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005002 if (len >= 12)
5003 ++p;
5004 else
5005 {
5006 *buffer_off = len;
5007 return;
5008 }
5009 }
5010 c = *p;
5011 *p = NUL;
Bram Moolenaar32526b32019-01-19 17:43:09 +01005012 msg_puts((char *)buffer);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005013 if (p < buffer + len)
5014 {
5015 *p = c;
5016 *buffer_off = (DWORD)((buffer + len) - p);
5017 mch_memmove(buffer, p, *buffer_off);
5018 return;
5019 }
5020 *buffer_off = 0;
5021 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005022 else
5023 {
5024 buffer[len] = NUL;
Bram Moolenaar32526b32019-01-19 17:43:09 +01005025 msg_puts((char *)buffer);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005026 }
5027
5028 windgoto(msg_row, msg_col);
5029 cursor_on();
5030 out_flush();
5031 }
5032}
5033
5034/*
5035 * Version of system to use for windows NT > 5.0 (Win2K), use pipe
5036 * for communication and doesn't open any new window.
5037 */
5038 static int
5039mch_system_piped(char *cmd, int options)
5040{
5041 STARTUPINFO si;
5042 PROCESS_INFORMATION pi;
5043 DWORD ret = 0;
5044
5045 HANDLE g_hChildStd_IN_Rd = NULL;
5046 HANDLE g_hChildStd_IN_Wr = NULL;
5047 HANDLE g_hChildStd_OUT_Rd = NULL;
5048 HANDLE g_hChildStd_OUT_Wr = NULL;
5049
Bram Moolenaar0f873732019-12-05 20:28:46 +01005050 char_u buffer[BUFLEN + 1]; // reading buffer + size
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005051 DWORD len;
5052
Bram Moolenaar0f873732019-12-05 20:28:46 +01005053 // buffer used to receive keys
5054 char_u ta_buf[BUFLEN + 1]; // TypeAHead
5055 int ta_len = 0; // valid bytes in ta_buf[]
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005056
5057 DWORD i;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005058 int noread_cnt = 0;
5059 garray_T ga;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005060 int delay = 1;
Bram Moolenaar0f873732019-12-05 20:28:46 +01005061 DWORD buffer_off = 0; // valid bytes in buffer[]
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005062 char *p = NULL;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005063
5064 SECURITY_ATTRIBUTES saAttr;
5065
Bram Moolenaar0f873732019-12-05 20:28:46 +01005066 // Set the bInheritHandle flag so pipe handles are inherited.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005067 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
5068 saAttr.bInheritHandle = TRUE;
5069 saAttr.lpSecurityDescriptor = NULL;
5070
5071 if ( ! CreatePipe(&g_hChildStd_OUT_Rd, &g_hChildStd_OUT_Wr, &saAttr, 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01005072 // Ensure the read handle to the pipe for STDOUT is not inherited.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005073 || ! SetHandleInformation(g_hChildStd_OUT_Rd, HANDLE_FLAG_INHERIT, 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01005074 // Create a pipe for the child process's STDIN.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005075 || ! CreatePipe(&g_hChildStd_IN_Rd, &g_hChildStd_IN_Wr, &saAttr, 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01005076 // Ensure the write handle to the pipe for STDIN is not inherited.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005077 || ! SetHandleInformation(g_hChildStd_IN_Wr, HANDLE_FLAG_INHERIT, 0) )
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005078 {
5079 CloseHandle(g_hChildStd_IN_Rd);
5080 CloseHandle(g_hChildStd_IN_Wr);
5081 CloseHandle(g_hChildStd_OUT_Rd);
5082 CloseHandle(g_hChildStd_OUT_Wr);
Bram Moolenaar32526b32019-01-19 17:43:09 +01005083 msg_puts(_("\nCannot create pipes\n"));
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005084 }
5085
5086 si.cb = sizeof(si);
5087 si.lpReserved = NULL;
5088 si.lpDesktop = NULL;
5089 si.lpTitle = NULL;
5090 si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
5091
Bram Moolenaar0f873732019-12-05 20:28:46 +01005092 // set-up our file redirection
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005093 si.hStdError = g_hChildStd_OUT_Wr;
5094 si.hStdOutput = g_hChildStd_OUT_Wr;
5095 si.hStdInput = g_hChildStd_IN_Rd;
5096 si.wShowWindow = SW_HIDE;
5097 si.cbReserved2 = 0;
5098 si.lpReserved2 = NULL;
5099
5100 if (options & SHELL_READ)
5101 ga_init2(&ga, 1, BUFLEN);
5102
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005103 if (cmd != NULL)
5104 {
5105 p = (char *)vim_strsave((char_u *)cmd);
5106 if (p != NULL)
5107 unescape_shellxquote((char_u *)p, p_sxe);
5108 else
5109 p = cmd;
5110 }
5111
Bram Moolenaar0f873732019-12-05 20:28:46 +01005112 // Now, run the command.
5113 // About "Inherit handles" being TRUE: this command can be litigious,
5114 // handle inheritance was deactivated for pending temp file, but, if we
5115 // deactivate it, the pipes don't work for some reason.
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005116 vim_create_process(p, TRUE, CREATE_DEFAULT_ERROR_MODE,
5117 &si, &pi, NULL, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005118
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005119 if (p != cmd)
5120 vim_free(p);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005121
Bram Moolenaar0f873732019-12-05 20:28:46 +01005122 // Close our unused side of the pipes
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005123 CloseHandle(g_hChildStd_IN_Rd);
5124 CloseHandle(g_hChildStd_OUT_Wr);
5125
5126 if (options & SHELL_WRITE)
5127 {
Bram Moolenaar86f2cd52016-08-02 21:55:17 +02005128 HANDLE thread = (HANDLE)
Bram Moolenaar0f873732019-12-05 20:28:46 +01005129 _beginthreadex(NULL, // security attributes
5130 0, // default stack size
5131 sub_process_writer, // function to be executed
5132 g_hChildStd_IN_Wr, // parameter
5133 0, // creation flag, start immediately
5134 NULL); // we don't care about thread id
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005135 CloseHandle(thread);
5136 g_hChildStd_IN_Wr = NULL;
5137 }
5138
Bram Moolenaar0f873732019-12-05 20:28:46 +01005139 // Keep updating the window while waiting for the shell to finish.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005140 for (;;)
5141 {
5142 MSG msg;
5143
K.Takatab7057bd2022-01-21 11:37:07 +00005144 if (PeekMessageW(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005145 {
5146 TranslateMessage(&msg);
K.Takatab7057bd2022-01-21 11:37:07 +00005147 DispatchMessageW(&msg);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005148 }
5149
Bram Moolenaar0f873732019-12-05 20:28:46 +01005150 // write pipe information in the window
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005151 if ((options & (SHELL_READ|SHELL_WRITE))
5152# ifdef FEAT_GUI
5153 || gui.in_use
5154# endif
5155 )
5156 {
5157 len = 0;
5158 if (!(options & SHELL_EXPAND)
5159 && ((options &
5160 (SHELL_READ|SHELL_WRITE|SHELL_COOKED))
5161 != (SHELL_READ|SHELL_WRITE|SHELL_COOKED)
5162# ifdef FEAT_GUI
5163 || gui.in_use
5164# endif
5165 )
5166 && (ta_len > 0 || noread_cnt > 4))
5167 {
5168 if (ta_len == 0)
5169 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005170 // Get extra characters when we don't have any. Reset the
5171 // counter and timer.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005172 noread_cnt = 0;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005173 len = ui_inchar(ta_buf, BUFLEN, 10L, 0);
5174 }
5175 if (ta_len > 0 || len > 0)
5176 {
5177 /*
5178 * For pipes: Check for CTRL-C: send interrupt signal to
GuyBrush1f13fcc2024-01-14 20:08:40 +01005179 * child.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005180 */
5181 if (len == 1 && cmd != NULL)
5182 {
5183 if (ta_buf[ta_len] == Ctrl_C)
5184 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005185 // Learn what exit code is expected, for
5186 // now put 9 as SIGKILL
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005187 TerminateProcess(pi.hProcess, 9);
5188 }
GuyBrush1f13fcc2024-01-14 20:08:40 +01005189 }
5190
5191 /*
5192 * Check for CTRL-D: EOF, close pipe to child.
5193 * Ctrl_D may be decorated by _OnChar()
5194 */
5195 if ((len == 1 || len == 4 ) && cmd != NULL)
5196 {
5197 if (ta_buf[0] == Ctrl_D
5198 || (ta_buf[0] == CSI
5199 && ta_buf[1] == KS_MODIFIER
5200 && ta_buf[3] == Ctrl_D))
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005201 {
5202 CloseHandle(g_hChildStd_IN_Wr);
5203 g_hChildStd_IN_Wr = NULL;
GuyBrush1f13fcc2024-01-14 20:08:40 +01005204 len = 0;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005205 }
5206 }
5207
Bram Moolenaar2f7e1b82022-10-04 13:17:31 +01005208 len = term_replace_keycodes(ta_buf, ta_len, len);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005209
5210 /*
5211 * For pipes: echo the typed characters. For a pty this
5212 * does not seem to work.
5213 */
5214 for (i = ta_len; i < ta_len + len; ++i)
5215 {
5216 if (ta_buf[i] == '\n' || ta_buf[i] == '\b')
5217 msg_putchar(ta_buf[i]);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005218 else if (has_mbyte)
5219 {
5220 int l = (*mb_ptr2len)(ta_buf + i);
5221
5222 msg_outtrans_len(ta_buf + i, l);
5223 i += l - 1;
5224 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005225 else
5226 msg_outtrans_len(ta_buf + i, 1);
5227 }
5228 windgoto(msg_row, msg_col);
5229 out_flush();
5230
5231 ta_len += len;
5232
5233 /*
5234 * Write the characters to the child, unless EOF has been
5235 * typed for pipes. Write one character at a time, to
5236 * avoid losing too much typeahead. When writing buffer
5237 * lines, drop the typed characters (only check for
5238 * CTRL-C).
5239 */
5240 if (options & SHELL_WRITE)
5241 ta_len = 0;
5242 else if (g_hChildStd_IN_Wr != NULL)
5243 {
5244 WriteFile(g_hChildStd_IN_Wr, (char*)ta_buf,
5245 1, &len, NULL);
5246 // if we are typing in, we want to keep things reactive
5247 delay = 1;
5248 if (len > 0)
5249 {
5250 ta_len -= len;
5251 mch_memmove(ta_buf, ta_buf + len, ta_len);
5252 }
5253 }
5254 }
5255 }
5256 }
5257
5258 if (ta_len)
5259 ui_inchar_undo(ta_buf, ta_len);
5260
5261 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
5262 {
Bram Moolenaar2eba1822011-08-27 15:10:04 +02005263 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005264 break;
5265 }
5266
5267 ++noread_cnt;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02005268 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005269
Bram Moolenaar0f873732019-12-05 20:28:46 +01005270 // We start waiting for a very short time and then increase it, so
5271 // that we respond quickly when the process is quick, and don't
5272 // consume too much overhead when it's slow.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005273 if (delay < 50)
5274 delay += 10;
5275 }
5276
Bram Moolenaar0f873732019-12-05 20:28:46 +01005277 // Close the pipe
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005278 CloseHandle(g_hChildStd_OUT_Rd);
5279 if (g_hChildStd_IN_Wr != NULL)
5280 CloseHandle(g_hChildStd_IN_Wr);
5281
5282 WaitForSingleObject(pi.hProcess, INFINITE);
5283
Bram Moolenaar0f873732019-12-05 20:28:46 +01005284 // Get the command exit code
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005285 GetExitCodeProcess(pi.hProcess, &ret);
5286
5287 if (options & SHELL_READ)
5288 {
5289 if (ga.ga_len > 0)
5290 {
5291 append_ga_line(&ga);
Bram Moolenaar0f873732019-12-05 20:28:46 +01005292 // remember that the NL was missing
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005293 curbuf->b_no_eol_lnum = curwin->w_cursor.lnum;
5294 }
5295 else
5296 curbuf->b_no_eol_lnum = 0;
5297 ga_clear(&ga);
5298 }
5299
Bram Moolenaar0f873732019-12-05 20:28:46 +01005300 // Close the handles to the subprocess, so that it goes away
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005301 CloseHandle(pi.hThread);
5302 CloseHandle(pi.hProcess);
5303
5304 return ret;
5305}
5306
5307 static int
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005308mch_system_g(char *cmd, int options)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005309{
Bram Moolenaar0f873732019-12-05 20:28:46 +01005310 // if we can pipe and the shelltemp option is off
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005311 if (!p_stmp)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005312 return mch_system_piped(cmd, options);
5313 else
5314 return mch_system_classic(cmd, options);
5315}
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005316#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005317
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005318#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01005319 static int
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02005320mch_system_c(char *cmd, int options UNUSED)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01005321{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005322 int ret;
5323 WCHAR *wcmd;
Bram Moolenaar2efc44b2019-10-05 12:09:32 +02005324 char_u *buf;
5325 size_t len;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005326
Bram Moolenaar2efc44b2019-10-05 12:09:32 +02005327 // If the command starts and ends with double quotes, enclose the command
5328 // in parentheses.
5329 len = STRLEN(cmd);
5330 if (len >= 2 && cmd[0] == '"' && cmd[len - 1] == '"')
5331 {
5332 len += 3;
5333 buf = alloc(len);
5334 if (buf == NULL)
5335 return -1;
5336 vim_snprintf((char *)buf, len, "(%s)", cmd);
5337 wcmd = enc_to_utf16(buf, NULL);
5338 free(buf);
5339 }
5340 else
5341 wcmd = enc_to_utf16((char_u *)cmd, NULL);
5342
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005343 if (wcmd == NULL)
5344 return -1;
5345
5346 ret = _wsystem(wcmd);
5347 vim_free(wcmd);
5348 return ret;
Bram Moolenaar910cffb2013-12-11 17:58:35 +01005349}
Bram Moolenaar071d4272004-06-13 20:20:40 +00005350
5351#endif
5352
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005353 static int
5354mch_system(char *cmd, int options)
5355{
5356#ifdef VIMDLL
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02005357 if (gui.in_use || gui.starting)
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005358 return mch_system_g(cmd, options);
5359 else
5360 return mch_system_c(cmd, options);
5361#elif defined(FEAT_GUI_MSWIN)
5362 return mch_system_g(cmd, options);
5363#else
5364 return mch_system_c(cmd, options);
5365#endif
5366}
5367
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005368#if defined(FEAT_GUI) && defined(FEAT_TERMINAL)
5369/*
5370 * Use a terminal window to run a shell command in.
5371 */
5372 static int
5373mch_call_shell_terminal(
5374 char_u *cmd,
Bram Moolenaar0f873732019-12-05 20:28:46 +01005375 int options UNUSED) // SHELL_*, see vim.h
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005376{
5377 jobopt_T opt;
5378 char_u *newcmd = NULL;
5379 typval_T argvar[2];
5380 long_u cmdlen;
5381 int retval = -1;
5382 buf_T *buf;
Bram Moolenaarf9c38832018-06-19 19:59:20 +02005383 job_T *job;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005384 aco_save_T aco;
Bram Moolenaar0f873732019-12-05 20:28:46 +01005385 oparg_T oa; // operator arguments
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005386
Bram Moolenaar42f652f2018-03-19 21:44:37 +01005387 if (cmd == NULL)
5388 cmdlen = STRLEN(p_sh) + 1;
5389 else
5390 cmdlen = STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10;
Bram Moolenaar18a4ba22019-05-24 19:39:03 +02005391 newcmd = alloc(cmdlen);
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005392 if (newcmd == NULL)
5393 return 255;
Bram Moolenaar42f652f2018-03-19 21:44:37 +01005394 if (cmd == NULL)
5395 {
5396 STRCPY(newcmd, p_sh);
5397 ch_log(NULL, "starting terminal to run a shell");
5398 }
5399 else
5400 {
5401 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s", p_sh, p_shcf, cmd);
5402 ch_log(NULL, "starting terminal for system command '%s'", cmd);
5403 }
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005404
5405 init_job_options(&opt);
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005406
5407 argvar[0].v_type = VAR_STRING;
5408 argvar[0].vval.v_string = newcmd;
5409 argvar[1].v_type = VAR_UNKNOWN;
5410 buf = term_start(argvar, NULL, &opt, TERM_START_SYSTEM);
Bram Moolenaar81c3c89a2018-03-20 11:41:44 +01005411 if (buf == NULL)
Bram Moolenaar9029b912019-03-21 19:58:00 +01005412 {
5413 vim_free(newcmd);
Bram Moolenaar81c3c89a2018-03-20 11:41:44 +01005414 return 255;
Bram Moolenaar9029b912019-03-21 19:58:00 +01005415 }
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005416
Bram Moolenaarf9c38832018-06-19 19:59:20 +02005417 job = term_getjob(buf->b_term);
5418 ++job->jv_refcount;
5419
Bram Moolenaar0f873732019-12-05 20:28:46 +01005420 // Find a window to make "buf" curbuf.
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005421 aucmd_prepbuf(&aco, buf);
Bram Moolenaare76062c2022-11-28 18:51:43 +00005422 if (curbuf == buf)
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005423 {
Bram Moolenaare76062c2022-11-28 18:51:43 +00005424 // Only do this when a window was found for "buf".
5425 clear_oparg(&oa);
5426 while (term_use_loop())
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005427 {
Bram Moolenaare76062c2022-11-28 18:51:43 +00005428 if (oa.op_type == OP_NOP && oa.regname == NUL && !VIsual_active)
5429 {
5430 // If terminal_loop() returns OK we got a key that is handled
5431 // in Normal model. We don't do redrawing anyway.
5432 if (terminal_loop(TRUE) == OK)
5433 normal_cmd(&oa, TRUE);
5434 }
5435 else
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005436 normal_cmd(&oa, TRUE);
5437 }
Bram Moolenaare76062c2022-11-28 18:51:43 +00005438 retval = job->jv_exitval;
5439 ch_log(NULL, "system command finished");
5440
5441 job_unref(job);
5442
5443 // restore curwin/curbuf and a few other things
5444 aucmd_restbuf(&aco);
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005445 }
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005446
5447 wait_return(TRUE);
5448 do_buffer(DOBUF_WIPE, DOBUF_FIRST, FORWARD, buf->b_fnum, TRUE);
5449
5450 vim_free(newcmd);
5451 return retval;
5452}
5453#endif
5454
Bram Moolenaar071d4272004-06-13 20:20:40 +00005455/*
5456 * Either execute a command by calling the shell or start a new shell
5457 */
5458 int
5459mch_call_shell(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005460 char_u *cmd,
Bram Moolenaar0f873732019-12-05 20:28:46 +01005461 int options) // SHELL_*, see vim.h
Bram Moolenaar071d4272004-06-13 20:20:40 +00005462{
5463 int x = 0;
5464 int tmode = cur_tmode;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005465 WCHAR szShellTitle[512];
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02005466
Bram Moolenaar4c5678f2022-11-30 18:12:19 +00005467#ifdef FEAT_EVAL
Bram Moolenaarc9a9a0a2022-04-12 15:09:23 +01005468 ch_log(NULL, "executing shell command: %s", cmd);
5469#endif
Bram Moolenaar0f873732019-12-05 20:28:46 +01005470 // Change the title to reflect that we are in a subshell.
K.Takataeeec2542021-06-02 13:28:16 +02005471 if (GetConsoleTitleW(szShellTitle, ARRAY_LENGTH(szShellTitle) - 4) > 0)
Bram Moolenaar1df52d72014-10-15 22:50:10 +02005472 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005473 if (cmd == NULL)
5474 wcscat(szShellTitle, L" :sh");
5475 else
Bram Moolenaar1df52d72014-10-15 22:50:10 +02005476 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005477 WCHAR *wn = enc_to_utf16((char_u *)cmd, NULL);
Bram Moolenaar1df52d72014-10-15 22:50:10 +02005478
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005479 if (wn != NULL)
5480 {
5481 wcscat(szShellTitle, L" - !");
5482 if ((wcslen(szShellTitle) + wcslen(wn) <
K.Takataeeec2542021-06-02 13:28:16 +02005483 ARRAY_LENGTH(szShellTitle)))
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005484 wcscat(szShellTitle, wn);
5485 SetConsoleTitleW(szShellTitle);
5486 vim_free(wn);
Bram Moolenaar1df52d72014-10-15 22:50:10 +02005487 }
5488 }
5489 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005490
5491 out_flush();
5492
5493#ifdef MCH_WRITE_DUMP
5494 if (fdDump)
5495 {
5496 fprintf(fdDump, "mch_call_shell(\"%s\", %d)\n", cmd, options);
5497 fflush(fdDump);
5498 }
5499#endif
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005500#if defined(FEAT_GUI) && defined(FEAT_TERMINAL)
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02005501 // TODO: make the terminal window work with input or output redirected.
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005502 if (
5503# ifdef VIMDLL
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02005504 gui.in_use &&
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005505# endif
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02005506 vim_strchr(p_go, GO_TERMINAL) != NULL
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005507 && (options & (SHELL_FILTER|SHELL_DOOUT|SHELL_WRITE|SHELL_READ)) == 0)
5508 {
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02005509 char_u *cmdbase = cmd;
5510
Bram Moolenaar4d5c1262019-09-20 17:20:02 +02005511 if (cmdbase != NULL)
5512 // Skip a leading quote and (.
5513 while (*cmdbase == '"' || *cmdbase == '(')
5514 ++cmdbase;
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02005515
5516 // Check the command does not begin with "start "
Bram Moolenaar36e7a822019-11-13 21:49:24 +01005517 if (cmdbase == NULL || STRNICMP(cmdbase, "start", 5) != 0
5518 || !VIM_ISWHITE(cmdbase[5]))
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02005519 {
5520 // Use a terminal window to run the command in.
5521 x = mch_call_shell_terminal(cmd, options);
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02005522 resettitle();
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02005523 return x;
5524 }
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005525 }
5526#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005527
5528 /*
5529 * Catch all deadly signals while running the external command, because a
5530 * CTRL-C, Ctrl-Break or illegal instruction might otherwise kill us.
5531 */
ichizok378447f2023-05-11 22:25:42 +01005532 mch_signal(SIGINT, SIG_IGN);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005533#if defined(__GNUC__) && !defined(__MINGW32__)
ichizok378447f2023-05-11 22:25:42 +01005534 mch_signal(SIGKILL, SIG_IGN);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005535#else
ichizok378447f2023-05-11 22:25:42 +01005536 mch_signal(SIGBREAK, SIG_IGN);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005537#endif
ichizok378447f2023-05-11 22:25:42 +01005538 mch_signal(SIGILL, SIG_IGN);
5539 mch_signal(SIGFPE, SIG_IGN);
5540 mch_signal(SIGSEGV, SIG_IGN);
5541 mch_signal(SIGTERM, SIG_IGN);
5542 mch_signal(SIGABRT, SIG_IGN);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005543
5544 if (options & SHELL_COOKED)
Bram Moolenaar0f873732019-12-05 20:28:46 +01005545 settmode(TMODE_COOK); // set to normal mode
Bram Moolenaar071d4272004-06-13 20:20:40 +00005546
5547 if (cmd == NULL)
5548 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01005549 x = mch_system((char *)p_sh, options);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005550 }
5551 else
5552 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005553 // we use "command" or "cmd" to start the shell; slow but easy
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005554 char_u *newcmd = NULL;
5555 char_u *cmdbase = cmd;
5556 long_u cmdlen;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005557
Bram Moolenaar0f873732019-12-05 20:28:46 +01005558 // Skip a leading ", ( and "(.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005559 if (*cmdbase == '"' )
5560 ++cmdbase;
5561 if (*cmdbase == '(')
5562 ++cmdbase;
5563
Bram Moolenaar1c465442017-03-12 20:10:05 +01005564 if ((STRNICMP(cmdbase, "start", 5) == 0) && VIM_ISWHITE(cmdbase[5]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005565 {
5566 STARTUPINFO si;
5567 PROCESS_INFORMATION pi;
5568 DWORD flags = CREATE_NEW_CONSOLE;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01005569 INT n_show_cmd = SW_SHOWNORMAL;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005570 char_u *p;
5571
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01005572 ZeroMemory(&si, sizeof(si));
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005573 si.cb = sizeof(si);
5574 si.lpReserved = NULL;
5575 si.lpDesktop = NULL;
5576 si.lpTitle = NULL;
5577 si.dwFlags = 0;
5578 si.cbReserved2 = 0;
5579 si.lpReserved2 = NULL;
5580
5581 cmdbase = skipwhite(cmdbase + 5);
5582 if ((STRNICMP(cmdbase, "/min", 4) == 0)
Bram Moolenaar1c465442017-03-12 20:10:05 +01005583 && VIM_ISWHITE(cmdbase[4]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005584 {
5585 cmdbase = skipwhite(cmdbase + 4);
5586 si.dwFlags = STARTF_USESHOWWINDOW;
5587 si.wShowWindow = SW_SHOWMINNOACTIVE;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01005588 n_show_cmd = SW_SHOWMINNOACTIVE;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005589 }
5590 else if ((STRNICMP(cmdbase, "/b", 2) == 0)
Bram Moolenaar1c465442017-03-12 20:10:05 +01005591 && VIM_ISWHITE(cmdbase[2]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005592 {
5593 cmdbase = skipwhite(cmdbase + 2);
5594 flags = CREATE_NO_WINDOW;
5595 si.dwFlags = STARTF_USESTDHANDLES;
5596 si.hStdInput = CreateFile("\\\\.\\NUL", // File name
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005597 GENERIC_READ, // Access flags
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005598 0, // Share flags
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005599 NULL, // Security att.
5600 OPEN_EXISTING, // Open flags
5601 FILE_ATTRIBUTE_NORMAL, // File att.
5602 NULL); // Temp file
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005603 si.hStdOutput = si.hStdInput;
5604 si.hStdError = si.hStdInput;
5605 }
5606
Bram Moolenaar0f873732019-12-05 20:28:46 +01005607 // Remove a trailing ", ) and )" if they have a match
5608 // at the start of the command.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005609 if (cmdbase > cmd)
5610 {
5611 p = cmdbase + STRLEN(cmdbase);
5612 if (p > cmdbase && p[-1] == '"' && *cmd == '"')
5613 *--p = NUL;
5614 if (p > cmdbase && p[-1] == ')'
5615 && (*cmd =='(' || cmd[1] == '('))
5616 *--p = NUL;
5617 }
5618
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005619 newcmd = cmdbase;
5620 unescape_shellxquote(cmdbase, p_sxe);
5621
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005622 /*
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005623 * If creating new console, arguments are passed to the
5624 * 'cmd.exe' as-is. If it's not, arguments are not treated
5625 * correctly for current 'cmd.exe'. So unescape characters in
5626 * shellxescape except '|' for avoiding to be treated as
5627 * argument to them. Pass the arguments to sub-shell.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005628 */
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005629 if (flags != CREATE_NEW_CONSOLE)
5630 {
5631 char_u *subcmd;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01005632 char_u *cmd_shell = mch_getenv("COMSPEC");
5633
5634 if (cmd_shell == NULL || *cmd_shell == NUL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01005635 cmd_shell = (char_u *)default_shell();
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005636
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01005637 subcmd = vim_strsave_escaped_ext(cmdbase,
5638 (char_u *)"|", '^', FALSE);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005639 if (subcmd != NULL)
5640 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005641 // make "cmd.exe /c arguments"
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005642 cmdlen = STRLEN(cmd_shell) + STRLEN(subcmd) + 5;
Bram Moolenaar18a4ba22019-05-24 19:39:03 +02005643 newcmd = alloc(cmdlen);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005644 if (newcmd != NULL)
5645 vim_snprintf((char *)newcmd, cmdlen, "%s /c %s",
Bram Moolenaaree7d1002012-02-22 15:34:08 +01005646 cmd_shell, subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005647 else
5648 newcmd = cmdbase;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01005649 vim_free(subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005650 }
5651 }
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005652
5653 /*
5654 * Now, start the command as a process, so that it doesn't
5655 * inherit our handles which causes unpleasant dangling swap
5656 * files if we exit before the spawned process
5657 */
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005658 if (vim_create_process((char *)newcmd, FALSE, flags,
5659 &si, &pi, NULL, NULL))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005660 x = 0;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01005661 else if (vim_shell_execute((char *)newcmd, n_show_cmd)
5662 > (HINSTANCE)32)
5663 x = 0;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005664 else
5665 {
5666 x = -1;
Bram Moolenaar4f974752019-02-17 17:44:42 +01005667#ifdef FEAT_GUI_MSWIN
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005668# ifdef VIMDLL
5669 if (gui.in_use)
5670# endif
Bram Moolenaarac78dd42022-01-02 19:25:26 +00005671 emsg(_(e_command_not_found));
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005672#endif
5673 }
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005674
5675 if (newcmd != cmdbase)
5676 vim_free(newcmd);
5677
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01005678 if (si.dwFlags == STARTF_USESTDHANDLES && si.hStdInput != NULL)
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005679 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005680 // Close the handle to \\.\NUL created above.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005681 CloseHandle(si.hStdInput);
5682 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01005683 // Close the handles to the subprocess, so that it goes away
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005684 CloseHandle(pi.hThread);
5685 CloseHandle(pi.hProcess);
5686 }
5687 else
5688 {
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005689 cmdlen =
Bram Moolenaar4f974752019-02-17 17:44:42 +01005690#ifdef FEAT_GUI_MSWIN
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02005691 ((gui.in_use || gui.starting) ?
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005692 (!s_dont_use_vimrun && p_stmp ?
5693 STRLEN(vimrun_path) : STRLEN(p_sh) + STRLEN(p_shcf))
5694 : 0) +
Bram Moolenaar071d4272004-06-13 20:20:40 +00005695#endif
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005696 STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10;
Bram Moolenaar0fde2902008-03-16 13:54:13 +00005697
Bram Moolenaar18a4ba22019-05-24 19:39:03 +02005698 newcmd = alloc(cmdlen);
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005699 if (newcmd != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005700 {
Bram Moolenaar4f974752019-02-17 17:44:42 +01005701#if defined(FEAT_GUI_MSWIN)
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005702 if (
5703# ifdef VIMDLL
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02005704 (gui.in_use || gui.starting) &&
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005705# endif
5706 need_vimrun_warning)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005707 {
Bram Moolenaar63e43442016-11-19 17:28:44 +01005708 char *msg = _("VIMRUN.EXE not found in your $PATH.\n"
5709 "External commands will not pause after completion.\n"
5710 "See :help win32-vimrun for more information.");
5711 char *title = _("Vim Warning");
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005712 WCHAR *wmsg = enc_to_utf16((char_u *)msg, NULL);
5713 WCHAR *wtitle = enc_to_utf16((char_u *)title, NULL);
Bram Moolenaar63e43442016-11-19 17:28:44 +01005714
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005715 if (wmsg != NULL && wtitle != NULL)
5716 MessageBoxW(NULL, wmsg, wtitle, MB_ICONWARNING);
5717 vim_free(wmsg);
5718 vim_free(wtitle);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005719 need_vimrun_warning = FALSE;
5720 }
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005721 if (
5722# ifdef VIMDLL
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02005723 (gui.in_use || gui.starting) &&
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005724# endif
5725 !s_dont_use_vimrun && p_stmp)
Bram Moolenaarfcc4d922019-05-24 13:32:36 +02005726 // Use vimrun to execute the command. It opens a console
5727 // window, which can be closed without killing Vim.
Bram Moolenaarcc448b32010-07-14 16:52:17 +02005728 vim_snprintf((char *)newcmd, cmdlen, "%s%s%s %s %s",
Bram Moolenaar071d4272004-06-13 20:20:40 +00005729 vimrun_path,
5730 (msg_silent != 0 || (options & SHELL_DOOUT))
5731 ? "-s " : "",
5732 p_sh, p_shcf, cmd);
Bram Moolenaarfcc4d922019-05-24 13:32:36 +02005733 else if (
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005734# ifdef VIMDLL
Bram Moolenaarfcc4d922019-05-24 13:32:36 +02005735 (gui.in_use || gui.starting) &&
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005736# endif
Bram Moolenaar0e6bfb92019-07-31 20:53:56 +02005737 s_dont_use_vimrun && STRCMP(p_shcf, "/c") == 0)
Bram Moolenaarfcc4d922019-05-24 13:32:36 +02005738 // workaround for the case that "vimrun" does not exist
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005739 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s %s %s",
5740 p_sh, p_shcf, p_sh, p_shcf, cmd);
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005741 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00005742#endif
Bram Moolenaarcc448b32010-07-14 16:52:17 +02005743 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s",
Bram Moolenaar0fde2902008-03-16 13:54:13 +00005744 p_sh, p_shcf, cmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005745 x = mch_system((char *)newcmd, options);
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005746 vim_free(newcmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005747 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005748 }
5749 }
5750
5751 if (tmode == TMODE_RAW)
Bram Moolenaar3b1f18f2020-05-16 23:15:08 +02005752 {
5753 // The shell may have messed with the mode, always set it.
5754 cur_tmode = TMODE_UNKNOWN;
Bram Moolenaar0f873732019-12-05 20:28:46 +01005755 settmode(TMODE_RAW); // set to raw mode
Bram Moolenaar3b1f18f2020-05-16 23:15:08 +02005756 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005757
Bram Moolenaar0f873732019-12-05 20:28:46 +01005758 // Print the return value, unless "vimrun" was used.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005759 if (x != 0 && !(options & SHELL_SILENT) && !emsg_silent
Bram Moolenaar4f974752019-02-17 17:44:42 +01005760#if defined(FEAT_GUI_MSWIN)
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02005761 && ((gui.in_use || gui.starting) ?
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005762 ((options & SHELL_DOOUT) || s_dont_use_vimrun || !p_stmp) : 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005763#endif
5764 )
5765 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005766 smsg(_("shell returned %d"), x);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005767 msg_putchar('\n');
5768 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005769 resettitle();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005770
ichizok378447f2023-05-11 22:25:42 +01005771 mch_signal(SIGINT, SIG_DFL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005772#if defined(__GNUC__) && !defined(__MINGW32__)
ichizok378447f2023-05-11 22:25:42 +01005773 mch_signal(SIGKILL, SIG_DFL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005774#else
ichizok378447f2023-05-11 22:25:42 +01005775 mch_signal(SIGBREAK, SIG_DFL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005776#endif
ichizok378447f2023-05-11 22:25:42 +01005777 mch_signal(SIGILL, SIG_DFL);
5778 mch_signal(SIGFPE, SIG_DFL);
5779 mch_signal(SIGSEGV, SIG_DFL);
5780 mch_signal(SIGTERM, SIG_DFL);
5781 mch_signal(SIGABRT, SIG_DFL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005782
5783 return x;
5784}
5785
Bram Moolenaar509ce2a2016-03-11 22:52:15 +01005786#if defined(FEAT_JOB_CHANNEL) || defined(PROTO)
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005787 static HANDLE
5788job_io_file_open(
Bram Moolenaar972c3b82017-01-12 21:44:49 +01005789 char_u *fname,
5790 DWORD dwDesiredAccess,
5791 DWORD dwShareMode,
5792 LPSECURITY_ATTRIBUTES lpSecurityAttributes,
5793 DWORD dwCreationDisposition,
5794 DWORD dwFlagsAndAttributes)
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005795{
5796 HANDLE h;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005797 WCHAR *wn;
Bram Moolenaara12a1612019-01-24 16:39:02 +01005798
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005799 wn = enc_to_utf16(fname, NULL);
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005800 if (wn == NULL)
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005801 return INVALID_HANDLE_VALUE;
5802
5803 h = CreateFileW(wn, dwDesiredAccess, dwShareMode,
5804 lpSecurityAttributes, dwCreationDisposition,
5805 dwFlagsAndAttributes, NULL);
5806 vim_free(wn);
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005807 return h;
5808}
5809
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005810/*
5811 * Turn the dictionary "env" into a NUL separated list that can be used as the
5812 * environment argument of vim_create_process().
5813 */
Bram Moolenaarba6febd2017-10-30 21:56:23 +01005814 void
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005815win32_build_env(dict_T *env, garray_T *gap, int is_terminal)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005816{
5817 hashitem_T *hi;
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005818 long_u todo = env != NULL ? env->dv_hashtab.ht_used : 0;
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005819 LPVOID base = GetEnvironmentStringsW();
5820
Bram Moolenaar0f873732019-12-05 20:28:46 +01005821 // for last \0
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005822 if (ga_grow(gap, 1) == FAIL)
5823 return;
5824
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005825 if (env != NULL)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005826 {
Yegappan Lakshmanan14113fd2023-03-07 17:13:51 +00005827 FOR_ALL_HASHTAB_ITEMS(&env->dv_hashtab, hi, todo)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005828 {
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005829 if (!HASHITEM_EMPTY(hi))
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005830 {
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005831 typval_T *item = &dict_lookup(hi)->di_tv;
5832 WCHAR *wkey = enc_to_utf16((char_u *)hi->hi_key, NULL);
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005833 WCHAR *wval = enc_to_utf16(tv_get_string(item), NULL);
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005834 --todo;
5835 if (wkey != NULL && wval != NULL)
5836 {
5837 size_t n;
5838 size_t lkey = wcslen(wkey);
5839 size_t lval = wcslen(wval);
Bram Moolenaar60104f12017-08-14 23:25:04 +02005840
Yegappan Lakshmananfadc02a2023-01-27 21:03:12 +00005841 if (ga_grow(gap, (int)(lkey + lval + 2)) == FAIL)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005842 continue;
5843 for (n = 0; n < lkey; n++)
5844 *((WCHAR*)gap->ga_data + gap->ga_len++) = wkey[n];
5845 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'=';
5846 for (n = 0; n < lval; n++)
5847 *((WCHAR*)gap->ga_data + gap->ga_len++) = wval[n];
5848 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5849 }
Bram Moolenaarbdace832019-03-02 10:13:42 +01005850 vim_free(wkey);
5851 vim_free(wval);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005852 }
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005853 }
5854 }
5855
Bram Moolenaar355757a2020-02-10 22:06:32 +01005856 if (base)
5857 {
5858 WCHAR *p = (WCHAR*) base;
5859
5860 // for last \0
5861 if (ga_grow(gap, 1) == FAIL)
5862 return;
5863
5864 while (*p != 0 || *(p + 1) != 0)
5865 {
5866 if (ga_grow(gap, 1) == OK)
5867 *((WCHAR*)gap->ga_data + gap->ga_len++) = *p;
5868 p++;
5869 }
Ken Takataad29f6a2023-09-16 13:56:02 +02005870 FreeEnvironmentStringsW(base);
Bram Moolenaar355757a2020-02-10 22:06:32 +01005871 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5872 }
5873
Bram Moolenaar493359e2018-06-12 20:25:52 +02005874# if defined(FEAT_CLIENTSERVER) || defined(FEAT_TERMINAL)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005875 {
Bram Moolenaar493359e2018-06-12 20:25:52 +02005876# ifdef FEAT_CLIENTSERVER
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005877 char_u *servername = get_vim_var_str(VV_SEND_SERVER);
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005878 size_t servername_len = STRLEN(servername);
Bram Moolenaar493359e2018-06-12 20:25:52 +02005879# endif
5880# ifdef FEAT_TERMINAL
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005881 char_u *version = get_vim_var_str(VV_VERSION);
5882 size_t version_len = STRLEN(version);
Bram Moolenaar493359e2018-06-12 20:25:52 +02005883# endif
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005884 // size of "VIM_SERVERNAME=" and value,
5885 // plus "VIM_TERMINAL=" and value,
5886 // plus two terminating NULs
5887 size_t n = 0
Bram Moolenaar493359e2018-06-12 20:25:52 +02005888# ifdef FEAT_CLIENTSERVER
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005889 + 15 + servername_len
Bram Moolenaar493359e2018-06-12 20:25:52 +02005890# endif
5891# ifdef FEAT_TERMINAL
5892 + 13 + version_len + 2
5893# endif
5894 ;
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005895
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005896 if (ga_grow(gap, (int)n) == OK)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005897 {
Bram Moolenaar493359e2018-06-12 20:25:52 +02005898# ifdef FEAT_CLIENTSERVER
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005899 for (n = 0; n < 15; n++)
5900 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5901 (WCHAR)"VIM_SERVERNAME="[n];
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005902 for (n = 0; n < servername_len; n++)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005903 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5904 (WCHAR)servername[n];
5905 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
Bram Moolenaar493359e2018-06-12 20:25:52 +02005906# endif
5907# ifdef FEAT_TERMINAL
5908 if (is_terminal)
5909 {
5910 for (n = 0; n < 13; n++)
5911 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5912 (WCHAR)"VIM_TERMINAL="[n];
5913 for (n = 0; n < version_len; n++)
5914 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5915 (WCHAR)version[n];
5916 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5917 }
5918# endif
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005919 }
5920 }
Bram Moolenaar79c6b512018-06-12 21:11:12 +02005921# endif
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005922}
5923
Bram Moolenaarb091f302019-01-19 14:37:00 +01005924/*
5925 * Create a pair of pipes.
5926 * Return TRUE for success, FALSE for failure.
5927 */
5928 static BOOL
5929create_pipe_pair(HANDLE handles[2])
5930{
5931 static LONG s;
5932 char name[64];
5933 SECURITY_ATTRIBUTES sa;
5934
5935 sprintf(name, "\\\\?\\pipe\\vim-%08lx-%08lx",
5936 GetCurrentProcessId(),
5937 InterlockedIncrement(&s));
5938
5939 // Create named pipe. Max size of named pipe is 65535.
5940 handles[1] = CreateNamedPipe(
5941 name,
5942 PIPE_ACCESS_OUTBOUND | FILE_FLAG_OVERLAPPED,
5943 PIPE_TYPE_BYTE | PIPE_NOWAIT,
Bram Moolenaar24058382019-01-24 23:11:49 +01005944 1, MAX_NAMED_PIPE_SIZE, 0, 0, NULL);
Bram Moolenaarb091f302019-01-19 14:37:00 +01005945
5946 if (handles[1] == INVALID_HANDLE_VALUE)
5947 return FALSE;
5948
5949 sa.nLength = sizeof(sa);
5950 sa.bInheritHandle = TRUE;
5951 sa.lpSecurityDescriptor = NULL;
5952
5953 handles[0] = CreateFile(name,
5954 FILE_GENERIC_READ,
5955 FILE_SHARE_READ, &sa,
5956 OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
5957
5958 if (handles[0] == INVALID_HANDLE_VALUE)
5959 {
Bram Moolenaar6982f422019-02-16 16:48:01 +01005960 CloseHandle(handles[1]);
Bram Moolenaarb091f302019-01-19 14:37:00 +01005961 return FALSE;
5962 }
5963
5964 return TRUE;
5965}
5966
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005967 void
Bram Moolenaar5a1feb82017-07-22 18:04:08 +02005968mch_job_start(char *cmd, job_T *job, jobopt_T *options)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005969{
5970 STARTUPINFO si;
5971 PROCESS_INFORMATION pi;
Bram Moolenaar14207f42016-10-27 21:13:10 +02005972 HANDLE jo;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005973 SECURITY_ATTRIBUTES saAttr;
5974 channel_T *channel = NULL;
Bram Moolenaard8070362016-02-15 21:56:54 +01005975 HANDLE ifd[2];
5976 HANDLE ofd[2];
5977 HANDLE efd[2];
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005978 garray_T ga;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005979
5980 int use_null_for_in = options->jo_io[PART_IN] == JIO_NULL;
5981 int use_null_for_out = options->jo_io[PART_OUT] == JIO_NULL;
5982 int use_null_for_err = options->jo_io[PART_ERR] == JIO_NULL;
5983 int use_file_for_in = options->jo_io[PART_IN] == JIO_FILE;
5984 int use_file_for_out = options->jo_io[PART_OUT] == JIO_FILE;
5985 int use_file_for_err = options->jo_io[PART_ERR] == JIO_FILE;
5986 int use_out_for_err = options->jo_io[PART_ERR] == JIO_OUT;
5987
5988 if (use_out_for_err && use_null_for_out)
5989 use_null_for_err = TRUE;
Bram Moolenaard8070362016-02-15 21:56:54 +01005990
5991 ifd[0] = INVALID_HANDLE_VALUE;
5992 ifd[1] = INVALID_HANDLE_VALUE;
5993 ofd[0] = INVALID_HANDLE_VALUE;
5994 ofd[1] = INVALID_HANDLE_VALUE;
5995 efd[0] = INVALID_HANDLE_VALUE;
5996 efd[1] = INVALID_HANDLE_VALUE;
Bram Moolenaar04935fb2022-01-08 16:19:22 +00005997 ga_init2(&ga, sizeof(wchar_t), 500);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005998
Bram Moolenaar14207f42016-10-27 21:13:10 +02005999 jo = CreateJobObject(NULL, NULL);
6000 if (jo == NULL)
6001 {
6002 job->jv_status = JOB_FAILED;
6003 goto failed;
6004 }
6005
Bram Moolenaar05aafed2017-08-11 19:12:11 +02006006 if (options->jo_env != NULL)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01006007 win32_build_env(options->jo_env, &ga, FALSE);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02006008
Bram Moolenaar76467df2016-02-12 19:30:26 +01006009 ZeroMemory(&pi, sizeof(pi));
Bram Moolenaar942d6b22016-02-07 19:57:16 +01006010 ZeroMemory(&si, sizeof(si));
6011 si.cb = sizeof(si);
Bram Moolenaard8070362016-02-15 21:56:54 +01006012 si.dwFlags |= STARTF_USESHOWWINDOW;
Bram Moolenaar76467df2016-02-12 19:30:26 +01006013 si.wShowWindow = SW_HIDE;
Bram Moolenaar942d6b22016-02-07 19:57:16 +01006014
Bram Moolenaard8070362016-02-15 21:56:54 +01006015 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
6016 saAttr.bInheritHandle = TRUE;
6017 saAttr.lpSecurityDescriptor = NULL;
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01006018
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01006019 if (use_file_for_in)
6020 {
6021 char_u *fname = options->jo_io_name[PART_IN];
6022
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01006023 ifd[0] = job_io_file_open(fname, GENERIC_READ,
6024 FILE_SHARE_READ | FILE_SHARE_WRITE,
6025 &saAttr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL);
6026 if (ifd[0] == INVALID_HANDLE_VALUE)
Bram Moolenaar94d01912016-03-08 13:48:51 +01006027 {
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00006028 semsg(_(e_cant_open_file_str), fname);
Bram Moolenaar94d01912016-03-08 13:48:51 +01006029 goto failed;
6030 }
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01006031 }
Bram Moolenaarb091f302019-01-19 14:37:00 +01006032 else if (!use_null_for_in
6033 && (!create_pipe_pair(ifd)
6034 || !SetHandleInformation(ifd[1], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01006035 goto failed;
6036
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01006037 if (use_file_for_out)
6038 {
6039 char_u *fname = options->jo_io_name[PART_OUT];
6040
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01006041 ofd[1] = job_io_file_open(fname, GENERIC_WRITE,
6042 FILE_SHARE_READ | FILE_SHARE_WRITE,
6043 &saAttr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL);
6044 if (ofd[1] == INVALID_HANDLE_VALUE)
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01006045 {
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00006046 semsg(_(e_cant_open_file_str), fname);
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01006047 goto failed;
6048 }
6049 }
Bram Moolenaard5d3d302016-03-09 20:54:51 +01006050 else if (!use_null_for_out &&
6051 (!CreatePipe(&ofd[0], &ofd[1], &saAttr, 0)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006052 || !SetHandleInformation(ofd[0], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01006053 goto failed;
6054
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01006055 if (use_file_for_err)
6056 {
6057 char_u *fname = options->jo_io_name[PART_ERR];
6058
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01006059 efd[1] = job_io_file_open(fname, GENERIC_WRITE,
6060 FILE_SHARE_READ | FILE_SHARE_WRITE,
6061 &saAttr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL);
6062 if (efd[1] == INVALID_HANDLE_VALUE)
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01006063 {
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00006064 semsg(_(e_cant_open_file_str), fname);
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01006065 goto failed;
6066 }
6067 }
Bram Moolenaard5d3d302016-03-09 20:54:51 +01006068 else if (!use_out_for_err && !use_null_for_err &&
6069 (!CreatePipe(&efd[0], &efd[1], &saAttr, 0)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006070 || !SetHandleInformation(efd[0], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaard8070362016-02-15 21:56:54 +01006071 goto failed;
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01006072
Bram Moolenaard8070362016-02-15 21:56:54 +01006073 si.dwFlags |= STARTF_USESTDHANDLES;
6074 si.hStdInput = ifd[0];
Bram Moolenaard5d3d302016-03-09 20:54:51 +01006075 si.hStdOutput = ofd[1];
6076 si.hStdError = use_out_for_err ? ofd[1] : efd[1];
6077
6078 if (!use_null_for_in || !use_null_for_out || !use_null_for_err)
6079 {
Bram Moolenaarde279892016-03-11 22:19:44 +01006080 if (options->jo_set & JO_CHANNEL)
6081 {
6082 channel = options->jo_channel;
6083 if (channel != NULL)
6084 ++channel->ch_refcount;
6085 }
6086 else
6087 channel = add_channel();
Bram Moolenaard5d3d302016-03-09 20:54:51 +01006088 if (channel == NULL)
6089 goto failed;
6090 }
Bram Moolenaard8070362016-02-15 21:56:54 +01006091
6092 if (!vim_create_process(cmd, TRUE,
Bram Moolenaar14207f42016-10-27 21:13:10 +02006093 CREATE_SUSPENDED |
Bram Moolenaar942d6b22016-02-07 19:57:16 +01006094 CREATE_DEFAULT_ERROR_MODE |
6095 CREATE_NEW_PROCESS_GROUP |
Bram Moolenaar05aafed2017-08-11 19:12:11 +02006096 CREATE_UNICODE_ENVIRONMENT |
Bram Moolenaar76467df2016-02-12 19:30:26 +01006097 CREATE_NEW_CONSOLE,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02006098 &si, &pi,
6099 ga.ga_data,
6100 (char *)options->jo_cwd))
Bram Moolenaar76467df2016-02-12 19:30:26 +01006101 {
Bram Moolenaar14207f42016-10-27 21:13:10 +02006102 CloseHandle(jo);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01006103 job->jv_status = JOB_FAILED;
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01006104 goto failed;
Bram Moolenaar76467df2016-02-12 19:30:26 +01006105 }
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01006106
Bram Moolenaar05aafed2017-08-11 19:12:11 +02006107 ga_clear(&ga);
6108
Bram Moolenaar14207f42016-10-27 21:13:10 +02006109 if (!AssignProcessToJobObject(jo, pi.hProcess))
6110 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006111 // if failing, switch the way to terminate
6112 // process with TerminateProcess.
Bram Moolenaar14207f42016-10-27 21:13:10 +02006113 CloseHandle(jo);
6114 jo = NULL;
6115 }
6116 ResumeThread(pi.hThread);
Bram Moolenaar75578a32016-03-10 16:33:31 +01006117 CloseHandle(pi.hThread);
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01006118 job->jv_proc_info = pi;
Bram Moolenaar14207f42016-10-27 21:13:10 +02006119 job->jv_job_object = jo;
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01006120 job->jv_status = JOB_STARTED;
6121
Bram Moolenaar641ad6c2016-09-01 18:32:11 +02006122 CloseHandle(ifd[0]);
6123 CloseHandle(ofd[1]);
6124 if (!use_out_for_err && !use_null_for_err)
Bram Moolenaarc25558b2016-03-03 21:02:23 +01006125 CloseHandle(efd[1]);
Bram Moolenaard8070362016-02-15 21:56:54 +01006126
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01006127 job->jv_channel = channel;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01006128 if (channel != NULL)
6129 {
6130 channel_set_pipes(channel,
6131 use_file_for_in || use_null_for_in
6132 ? INVALID_FD : (sock_T)ifd[1],
6133 use_file_for_out || use_null_for_out
6134 ? INVALID_FD : (sock_T)ofd[0],
6135 use_out_for_err || use_file_for_err || use_null_for_err
6136 ? INVALID_FD : (sock_T)efd[0]);
6137 channel_set_job(channel, job, options);
Bram Moolenaard5d3d302016-03-09 20:54:51 +01006138 }
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01006139 return;
6140
6141failed:
Bram Moolenaard8070362016-02-15 21:56:54 +01006142 CloseHandle(ifd[0]);
6143 CloseHandle(ofd[0]);
6144 CloseHandle(efd[0]);
6145 CloseHandle(ifd[1]);
6146 CloseHandle(ofd[1]);
6147 CloseHandle(efd[1]);
Bram Moolenaarde279892016-03-11 22:19:44 +01006148 channel_unref(channel);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02006149 ga_clear(&ga);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01006150}
6151
6152 char *
6153mch_job_status(job_T *job)
6154{
6155 DWORD dwExitCode = 0;
6156
Bram Moolenaar76467df2016-02-12 19:30:26 +01006157 if (!GetExitCodeProcess(job->jv_proc_info.hProcess, &dwExitCode)
6158 || dwExitCode != STILL_ACTIVE)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01006159 {
Bram Moolenaareab089d2016-02-21 19:32:02 +01006160 job->jv_exitval = (int)dwExitCode;
Bram Moolenaar7df915d2016-11-17 17:25:32 +01006161 if (job->jv_status < JOB_ENDED)
Bram Moolenaar97792de2016-10-15 18:36:49 +02006162 {
6163 ch_log(job->jv_channel, "Job ended");
6164 job->jv_status = JOB_ENDED;
6165 }
Bram Moolenaar942d6b22016-02-07 19:57:16 +01006166 return "dead";
6167 }
6168 return "run";
6169}
6170
Bram Moolenaar97792de2016-10-15 18:36:49 +02006171 job_T *
6172mch_detect_ended_job(job_T *job_list)
6173{
6174 HANDLE jobHandles[MAXIMUM_WAIT_OBJECTS];
6175 job_T *jobArray[MAXIMUM_WAIT_OBJECTS];
6176 job_T *job = job_list;
6177
6178 while (job != NULL)
6179 {
6180 DWORD n;
6181 DWORD result;
6182
6183 for (n = 0; n < MAXIMUM_WAIT_OBJECTS
6184 && job != NULL; job = job->jv_next)
6185 {
6186 if (job->jv_status == JOB_STARTED)
6187 {
6188 jobHandles[n] = job->jv_proc_info.hProcess;
6189 jobArray[n] = job;
6190 ++n;
6191 }
6192 }
6193 if (n == 0)
6194 continue;
6195 result = WaitForMultipleObjects(n, jobHandles, FALSE, 0);
6196 if (result >= WAIT_OBJECT_0 && result < WAIT_OBJECT_0 + n)
6197 {
6198 job_T *wait_job = jobArray[result - WAIT_OBJECT_0];
6199
6200 if (STRCMP(mch_job_status(wait_job), "dead") == 0)
6201 return wait_job;
6202 }
6203 }
6204 return NULL;
6205}
6206
Bram Moolenaarfb630902016-10-29 14:55:00 +02006207 static BOOL
6208terminate_all(HANDLE process, int code)
6209{
6210 PROCESSENTRY32 pe;
6211 HANDLE h = INVALID_HANDLE_VALUE;
6212 DWORD pid = GetProcessId(process);
6213
6214 if (pid != 0)
6215 {
6216 h = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
6217 if (h != INVALID_HANDLE_VALUE)
6218 {
6219 pe.dwSize = sizeof(PROCESSENTRY32);
6220 if (!Process32First(h, &pe))
6221 goto theend;
6222
6223 do
6224 {
6225 if (pe.th32ParentProcessID == pid)
6226 {
6227 HANDLE ph = OpenProcess(
6228 PROCESS_ALL_ACCESS, FALSE, pe.th32ProcessID);
6229 if (ph != NULL)
6230 {
6231 terminate_all(ph, code);
6232 CloseHandle(ph);
6233 }
6234 }
6235 } while (Process32Next(h, &pe));
6236
6237 CloseHandle(h);
6238 }
6239 }
6240
6241theend:
6242 return TerminateProcess(process, code);
6243}
6244
6245/*
6246 * Send a (deadly) signal to "job".
6247 * Return FAIL if it didn't work.
6248 */
Bram Moolenaar942d6b22016-02-07 19:57:16 +01006249 int
Bram Moolenaar2d33e902017-08-11 16:31:54 +02006250mch_signal_job(job_T *job, char_u *how)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01006251{
Bram Moolenaar923d9262016-02-25 20:56:01 +01006252 int ret;
Bram Moolenaar76467df2016-02-12 19:30:26 +01006253
Bram Moolenaar923d9262016-02-25 20:56:01 +01006254 if (STRCMP(how, "term") == 0 || STRCMP(how, "kill") == 0 || *how == NUL)
Bram Moolenaar76467df2016-02-12 19:30:26 +01006255 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006256 // deadly signal
Bram Moolenaar14207f42016-10-27 21:13:10 +02006257 if (job->jv_job_object != NULL)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006258 {
6259 if (job->jv_channel != NULL && job->jv_channel->ch_anonymous_pipe)
6260 job->jv_channel->ch_killing = TRUE;
K.Takata135e1522022-01-29 15:27:58 +00006261 return TerminateJobObject(job->jv_job_object, (UINT)-1) ? OK : FAIL;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006262 }
Bram Moolenaarb3e195c2020-02-10 21:32:19 +01006263 return terminate_all(job->jv_proc_info.hProcess, -1) ? OK : FAIL;
Bram Moolenaar76467df2016-02-12 19:30:26 +01006264 }
6265
6266 if (!AttachConsole(job->jv_proc_info.dwProcessId))
6267 return FAIL;
6268 ret = GenerateConsoleCtrlEvent(
Bram Moolenaar923d9262016-02-25 20:56:01 +01006269 STRCMP(how, "int") == 0 ? CTRL_C_EVENT : CTRL_BREAK_EVENT,
6270 job->jv_proc_info.dwProcessId)
6271 ? OK : FAIL;
Bram Moolenaar76467df2016-02-12 19:30:26 +01006272 FreeConsole();
6273 return ret;
6274}
6275
6276/*
6277 * Clear the data related to "job".
6278 */
6279 void
6280mch_clear_job(job_T *job)
6281{
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00006282 if (job->jv_status == JOB_FAILED)
6283 return;
6284
6285 if (job->jv_job_object != NULL)
6286 CloseHandle(job->jv_job_object);
6287 CloseHandle(job->jv_proc_info.hProcess);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01006288}
6289#endif
6290
Bram Moolenaar071d4272004-06-13 20:20:40 +00006291
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006292#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006293
6294/*
6295 * Start termcap mode
6296 */
6297 static void
6298termcap_mode_start(void)
6299{
6300 DWORD cmodein;
6301
6302 if (g_fTermcapMode)
6303 return;
6304
6305 SaveConsoleBuffer(&g_cbNonTermcap);
6306
6307 if (g_cbTermcap.IsValid)
6308 {
6309 /*
6310 * We've been in termcap mode before. Restore certain screen
6311 * characteristics, including the buffer size and the window
6312 * size. Since we will be redrawing the screen, we don't need
6313 * to restore the actual contents of the buffer.
6314 */
6315 RestoreConsoleBuffer(&g_cbTermcap, FALSE);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006316 reset_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00006317 SetConsoleWindowInfo(g_hConOut, TRUE, &g_cbTermcap.Info.srWindow);
6318 Rows = g_cbTermcap.Info.dwSize.Y;
6319 Columns = g_cbTermcap.Info.dwSize.X;
6320 }
6321 else
6322 {
6323 /*
6324 * This is our first time entering termcap mode. Clear the console
6325 * screen buffer, and resize the buffer to match the current window
6326 * size. We will use this as the size of our editing environment.
6327 */
6328 ClearConsoleBuffer(g_attrCurrent);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006329 set_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00006330 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
6331 }
6332
Bram Moolenaar071d4272004-06-13 20:20:40 +00006333 resettitle();
Bram Moolenaar071d4272004-06-13 20:20:40 +00006334
6335 GetConsoleMode(g_hConIn, &cmodein);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006336 if (g_fMouseActive)
Wez Furlong6ef5ab52021-05-30 19:29:41 +02006337 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006338 cmodein |= ENABLE_MOUSE_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02006339 cmodein &= ~ENABLE_QUICK_EDIT_MODE;
6340 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006341 else
Wez Furlong6ef5ab52021-05-30 19:29:41 +02006342 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006343 cmodein &= ~ENABLE_MOUSE_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02006344 cmodein |= g_cmodein & ENABLE_QUICK_EDIT_MODE;
6345 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006346 cmodein |= ENABLE_WINDOW_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02006347 SetConsoleMode(g_hConIn, cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006348
6349 redraw_later_clear();
6350 g_fTermcapMode = TRUE;
6351}
6352
6353
6354/*
6355 * End termcap mode
6356 */
6357 static void
6358termcap_mode_end(void)
6359{
6360 DWORD cmodein;
6361 ConsoleBuffer *cb;
6362 COORD coord;
6363 DWORD dwDummy;
6364
6365 if (!g_fTermcapMode)
6366 return;
6367
6368 SaveConsoleBuffer(&g_cbTermcap);
6369
6370 GetConsoleMode(g_hConIn, &cmodein);
6371 cmodein &= ~(ENABLE_MOUSE_INPUT | ENABLE_WINDOW_INPUT);
Wez Furlong6ef5ab52021-05-30 19:29:41 +02006372 cmodein |= g_cmodein & ENABLE_QUICK_EDIT_MODE;
6373 SetConsoleMode(g_hConIn, cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006374
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006375# ifdef FEAT_RESTORE_ORIG_SCREEN
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01006376 cb = exiting ? &g_cbOrig : &g_cbNonTermcap;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006377# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00006378 cb = &g_cbNonTermcap;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006379# endif
Bram Moolenaar81ccbf12020-04-15 21:05:30 +02006380 RestoreConsoleBuffer(cb, p_rs);
Bram Moolenaardf543822020-01-30 11:53:59 +01006381 restore_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00006382
Christopher Plewright1140b512022-11-12 18:46:05 +00006383 // Switch back to main screen buffer.
Christopher Plewrightc8b126d2022-12-22 13:45:23 +00006384 if (exiting && use_alternate_screen_buffer)
Christopher Plewright1140b512022-11-12 18:46:05 +00006385 vtp_printf("\033[?1049l");
6386
6387 if (!USE_WT && (p_rs || exiting))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006388 {
6389 /*
6390 * Clear anything that happens to be on the current line.
6391 */
6392 coord.X = 0;
6393 coord.Y = (SHORT) (p_rs ? cb->Info.dwCursorPosition.Y : (Rows - 1));
Christopher Plewrightf75a2cb2023-01-28 10:28:09 +00006394 FillConsoleOutputCharacter(g_hConOut, ' ',
6395 cb->Info.dwSize.X, coord, &dwDummy);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006396 /*
6397 * The following is just for aesthetics. If we are exiting without
6398 * restoring the screen, then we want to have a prompt string
6399 * appear at the bottom line. However, the command interpreter
6400 * seems to always advance the cursor one line before displaying
6401 * the prompt string, which causes the screen to scroll. To
6402 * counter this, move the cursor up one line before exiting.
6403 */
6404 if (exiting && !p_rs)
6405 coord.Y--;
6406 /*
6407 * Position the cursor at the leftmost column of the desired row.
6408 */
Bram Moolenaar81ccbf12020-04-15 21:05:30 +02006409 SetConsoleCursorPosition(g_hConOut, coord);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006410 }
Christopher Plewright1140b512022-11-12 18:46:05 +00006411 SetConsoleCursorInfo(g_hConOut, &g_cci);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006412 g_fTermcapMode = FALSE;
6413}
Christopher Plewright38804d62022-11-09 23:55:52 +00006414#endif // !FEAT_GUI_MSWIN || VIMDLL
Bram Moolenaar071d4272004-06-13 20:20:40 +00006415
6416
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006417#if defined(FEAT_GUI_MSWIN) && !defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006418 void
6419mch_write(
Bram Moolenaar1266d672017-02-01 13:43:36 +01006420 char_u *s UNUSED,
6421 int len UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006422{
Bram Moolenaar0f873732019-12-05 20:28:46 +01006423 // never used
Bram Moolenaar071d4272004-06-13 20:20:40 +00006424}
6425
6426#else
6427
6428/*
6429 * clear `n' chars, starting from `coord'
6430 */
6431 static void
6432clear_chars(
6433 COORD coord,
6434 DWORD n)
6435{
Christopher Plewright38804d62022-11-09 23:55:52 +00006436 if (!vtp_working)
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006437 {
6438 DWORD dwDummy;
6439
6440 FillConsoleOutputCharacter(g_hConOut, ' ', n, coord, &dwDummy);
6441 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, n, coord,
6442 &dwDummy);
6443 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006444 else
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02006445 {
6446 set_console_color_rgb();
6447 gotoxy(coord.X + 1, coord.Y + 1);
6448 vtp_printf("\033[%dX", n);
6449 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006450}
6451
6452
6453/*
6454 * Clear the screen
6455 */
6456 static void
6457clear_screen(void)
6458{
6459 g_coord.X = g_coord.Y = 0;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006460
Christopher Plewright38804d62022-11-09 23:55:52 +00006461 if (!vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006462 clear_chars(g_coord, Rows * Columns);
6463 else
6464 {
6465 set_console_color_rgb();
6466 gotoxy(1, 1);
6467 vtp_printf("\033[2J");
6468 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006469}
6470
6471
6472/*
6473 * Clear to end of display
6474 */
6475 static void
6476clear_to_end_of_display(void)
6477{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006478 COORD save = g_coord;
6479
Christopher Plewright38804d62022-11-09 23:55:52 +00006480 if (!vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006481 clear_chars(g_coord, (Rows - g_coord.Y - 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006482 * Columns + (Columns - g_coord.X));
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006483 else
6484 {
6485 set_console_color_rgb();
6486 gotoxy(g_coord.X + 1, g_coord.Y + 1);
6487 vtp_printf("\033[0J");
6488
6489 gotoxy(save.X + 1, save.Y + 1);
6490 g_coord = save;
6491 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006492}
6493
6494
6495/*
6496 * Clear to end of line
6497 */
6498 static void
6499clear_to_end_of_line(void)
6500{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006501 COORD save = g_coord;
6502
Christopher Plewright38804d62022-11-09 23:55:52 +00006503 if (!vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006504 clear_chars(g_coord, Columns - g_coord.X);
6505 else
6506 {
6507 set_console_color_rgb();
6508 gotoxy(g_coord.X + 1, g_coord.Y + 1);
6509 vtp_printf("\033[0K");
6510
6511 gotoxy(save.X + 1, save.Y + 1);
6512 g_coord = save;
6513 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006514}
6515
6516
6517/*
6518 * Scroll the scroll region up by `cLines' lines
6519 */
6520 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006521scroll(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006522{
6523 COORD oldcoord = g_coord;
6524
6525 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
6526 delete_lines(cLines);
6527
6528 g_coord = oldcoord;
6529}
6530
6531
6532/*
6533 * Set the scroll region
6534 */
6535 static void
6536set_scroll_region(
6537 unsigned left,
6538 unsigned top,
6539 unsigned right,
6540 unsigned bottom)
6541{
6542 if (left >= right
6543 || top >= bottom
6544 || right > (unsigned) Columns - 1
6545 || bottom > (unsigned) Rows - 1)
6546 return;
6547
6548 g_srScrollRegion.Left = left;
6549 g_srScrollRegion.Top = top;
6550 g_srScrollRegion.Right = right;
6551 g_srScrollRegion.Bottom = bottom;
Bram Moolenaar6982f422019-02-16 16:48:01 +01006552}
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006553
Bram Moolenaar6982f422019-02-16 16:48:01 +01006554 static void
6555set_scroll_region_tb(
6556 unsigned top,
6557 unsigned bottom)
6558{
6559 if (top >= bottom || bottom > (unsigned)Rows - 1)
6560 return;
6561
6562 g_srScrollRegion.Top = top;
6563 g_srScrollRegion.Bottom = bottom;
6564}
6565
6566 static void
6567set_scroll_region_lr(
6568 unsigned left,
6569 unsigned right)
6570{
6571 if (left >= right || right > (unsigned)Columns - 1)
6572 return;
6573
6574 g_srScrollRegion.Left = left;
6575 g_srScrollRegion.Right = right;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006576}
6577
6578
6579/*
6580 * Insert `cLines' lines at the current cursor position
6581 */
6582 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006583insert_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006584{
Bram Moolenaar6982f422019-02-16 16:48:01 +01006585 SMALL_RECT source, clip;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006586 COORD dest;
6587 CHAR_INFO fill;
6588
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006589 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
6590
Bram Moolenaar6982f422019-02-16 16:48:01 +01006591 dest.X = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006592 dest.Y = g_coord.Y + cLines;
6593
Bram Moolenaar6982f422019-02-16 16:48:01 +01006594 source.Left = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006595 source.Top = g_coord.Y;
6596 source.Right = g_srScrollRegion.Right;
6597 source.Bottom = g_srScrollRegion.Bottom - cLines;
6598
Bram Moolenaar6982f422019-02-16 16:48:01 +01006599 clip.Left = g_srScrollRegion.Left;
6600 clip.Top = g_coord.Y;
6601 clip.Right = g_srScrollRegion.Right;
6602 clip.Bottom = g_srScrollRegion.Bottom;
6603
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006604 fill.Char.AsciiChar = ' ';
Christopher Plewrightf75a2cb2023-01-28 10:28:09 +00006605 if (!USE_VTP)
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006606 fill.Attributes = g_attrCurrent;
6607 else
6608 fill.Attributes = g_attrDefault;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006609
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006610 set_console_color_rgb();
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006611
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006612 ScrollConsoleScreenBuffer(g_hConOut, &source, &clip, dest, &fill);
6613
Bram Moolenaar6982f422019-02-16 16:48:01 +01006614 // Here we have to deal with a win32 console flake: If the scroll
6615 // region looks like abc and we scroll c to a and fill with d we get
6616 // cbd... if we scroll block c one line at a time to a, we get cdd...
6617 // vim expects cdd consistently... So we have to deal with that
6618 // here... (this also occurs scrolling the same way in the other
6619 // direction).
Bram Moolenaar071d4272004-06-13 20:20:40 +00006620
6621 if (source.Bottom < dest.Y)
6622 {
6623 COORD coord;
Bram Moolenaar6982f422019-02-16 16:48:01 +01006624 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006625
Bram Moolenaar6982f422019-02-16 16:48:01 +01006626 coord.X = source.Left;
6627 for (i = clip.Top; i < dest.Y; ++i)
6628 {
6629 coord.Y = i;
6630 clear_chars(coord, source.Right - source.Left + 1);
6631 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006632 }
Bram Moolenaar06b7b582020-05-30 17:49:25 +02006633
Christopher Plewright38804d62022-11-09 23:55:52 +00006634 if (vtp_working)
Bram Moolenaar06b7b582020-05-30 17:49:25 +02006635 {
6636 COORD coord;
6637 int i;
6638
6639 coord.X = source.Left;
6640 for (i = source.Top; i < dest.Y; ++i)
6641 {
6642 coord.Y = i;
6643 clear_chars(coord, source.Right - source.Left + 1);
6644 }
6645 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006646}
6647
6648
6649/*
6650 * Delete `cLines' lines at the current cursor position
6651 */
6652 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006653delete_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006654{
Bram Moolenaar6982f422019-02-16 16:48:01 +01006655 SMALL_RECT source, clip;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006656 COORD dest;
6657 CHAR_INFO fill;
6658 int nb;
6659
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006660 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
6661
Bram Moolenaar6982f422019-02-16 16:48:01 +01006662 dest.X = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006663 dest.Y = g_coord.Y;
6664
Bram Moolenaar6982f422019-02-16 16:48:01 +01006665 source.Left = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006666 source.Top = g_coord.Y + cLines;
6667 source.Right = g_srScrollRegion.Right;
6668 source.Bottom = g_srScrollRegion.Bottom;
6669
Bram Moolenaar6982f422019-02-16 16:48:01 +01006670 clip.Left = g_srScrollRegion.Left;
6671 clip.Top = g_coord.Y;
6672 clip.Right = g_srScrollRegion.Right;
6673 clip.Bottom = g_srScrollRegion.Bottom;
6674
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006675 fill.Char.AsciiChar = ' ';
Christopher Plewright38804d62022-11-09 23:55:52 +00006676 if (!vtp_working)
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006677 fill.Attributes = g_attrCurrent;
6678 else
6679 fill.Attributes = g_attrDefault;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006680
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006681 set_console_color_rgb();
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006682
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006683 ScrollConsoleScreenBuffer(g_hConOut, &source, &clip, dest, &fill);
6684
Bram Moolenaar6982f422019-02-16 16:48:01 +01006685 // Here we have to deal with a win32 console flake; See insert_lines()
6686 // above.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006687
6688 nb = dest.Y + (source.Bottom - source.Top) + 1;
6689
6690 if (nb < source.Top)
6691 {
6692 COORD coord;
Bram Moolenaar6982f422019-02-16 16:48:01 +01006693 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006694
Bram Moolenaar6982f422019-02-16 16:48:01 +01006695 coord.X = source.Left;
6696 for (i = nb; i < clip.Bottom; ++i)
6697 {
6698 coord.Y = i;
6699 clear_chars(coord, source.Right - source.Left + 1);
6700 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006701 }
Bram Moolenaar06b7b582020-05-30 17:49:25 +02006702
Christopher Plewright38804d62022-11-09 23:55:52 +00006703 if (vtp_working)
Bram Moolenaar06b7b582020-05-30 17:49:25 +02006704 {
6705 COORD coord;
6706 int i;
6707
6708 coord.X = source.Left;
6709 for (i = nb; i <= source.Bottom; ++i)
6710 {
6711 coord.Y = i;
6712 clear_chars(coord, source.Right - source.Left + 1);
6713 }
6714 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006715}
6716
6717
6718/*
Bram Moolenaar2313b612019-09-27 14:14:32 +02006719 * Set the cursor position to (x,y) (1-based).
Bram Moolenaar071d4272004-06-13 20:20:40 +00006720 */
6721 static void
6722gotoxy(
6723 unsigned x,
6724 unsigned y)
6725{
6726 if (x < 1 || x > (unsigned)Columns || y < 1 || y > (unsigned)Rows)
6727 return;
6728
Christopher Plewrightf75a2cb2023-01-28 10:28:09 +00006729 if (!USE_VTP)
Bram Moolenaar2313b612019-09-27 14:14:32 +02006730 {
Bram Moolenaar82e743c2020-03-26 15:39:53 +01006731 // There are reports of double-width characters not displayed
6732 // correctly. This workaround should fix it, similar to how it's done
6733 // for VTP.
6734 g_coord.X = 0;
6735 SetConsoleCursorPosition(g_hConOut, g_coord);
6736
Bram Moolenaar2313b612019-09-27 14:14:32 +02006737 // external cursor coords are 1-based; internal are 0-based
6738 g_coord.X = x - 1;
6739 g_coord.Y = y - 1;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006740 SetConsoleCursorPosition(g_hConOut, g_coord);
Bram Moolenaar2313b612019-09-27 14:14:32 +02006741 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006742 else
Bram Moolenaar2313b612019-09-27 14:14:32 +02006743 {
6744 // Move the cursor to the left edge of the screen to prevent screen
Bram Moolenaara1299742019-10-10 16:36:00 +02006745 // destruction. Insider build bug. Always enabled because it's cheap
6746 // and avoids mistakes with recognizing the build.
6747 vtp_printf("\033[%d;%dH", g_coord.Y + 1, 1);
Bram Moolenaar2313b612019-09-27 14:14:32 +02006748
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006749 vtp_printf("\033[%d;%dH", y, x);
Bram Moolenaar2313b612019-09-27 14:14:32 +02006750
6751 g_coord.X = x - 1;
6752 g_coord.Y = y - 1;
6753 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006754}
6755
6756
6757/*
6758 * Set the current text attribute = (foreground | background)
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006759 * See ../runtime/doc/os_win32.txt for the numbers.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006760 */
6761 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006762textattr(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006763{
Bram Moolenaar6383b922015-03-24 17:12:19 +01006764 g_attrCurrent = wAttr & 0xff;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006765
6766 SetConsoleTextAttribute(g_hConOut, wAttr);
6767}
6768
6769
6770 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006771textcolor(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006772{
Bram Moolenaar6383b922015-03-24 17:12:19 +01006773 g_attrCurrent = (g_attrCurrent & 0xf0) + (wAttr & 0x0f);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006774
Christopher Plewright38804d62022-11-09 23:55:52 +00006775 if (!vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006776 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
6777 else
6778 vtp_sgr_bulk(wAttr);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006779}
6780
6781
6782 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006783textbackground(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006784{
Bram Moolenaar6383b922015-03-24 17:12:19 +01006785 g_attrCurrent = (g_attrCurrent & 0x0f) + ((wAttr & 0x0f) << 4);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006786
Christopher Plewright38804d62022-11-09 23:55:52 +00006787 if (!vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006788 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
6789 else
6790 vtp_sgr_bulk(wAttr);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006791}
6792
6793
6794/*
6795 * restore the default text attribute (whatever we started with)
6796 */
6797 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006798normvideo(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006799{
Christopher Plewright38804d62022-11-09 23:55:52 +00006800 if (!vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006801 textattr(g_attrDefault);
6802 else
6803 vtp_sgr_bulk(0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006804}
6805
6806
6807static WORD g_attrPreStandout = 0;
6808
6809/*
6810 * Make the text standout, by brightening it
6811 */
6812 static void
6813standout(void)
6814{
6815 g_attrPreStandout = g_attrCurrent;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006816
Bram Moolenaar071d4272004-06-13 20:20:40 +00006817 textattr((WORD) (g_attrCurrent|FOREGROUND_INTENSITY|BACKGROUND_INTENSITY));
6818}
6819
6820
6821/*
6822 * Turn off standout mode
6823 */
6824 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006825standend(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006826{
6827 if (g_attrPreStandout)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006828 textattr(g_attrPreStandout);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006829
6830 g_attrPreStandout = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006831}
6832
6833
6834/*
Bram Moolenaarff1d0d42007-05-10 17:24:16 +00006835 * Set normal fg/bg color, based on T_ME. Called when t_me has been set.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006836 */
6837 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006838mch_set_normal_colors(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006839{
6840 char_u *p;
6841 int n;
6842
6843 cterm_normal_fg_color = (g_attrDefault & 0xf) + 1;
6844 cterm_normal_bg_color = ((g_attrDefault >> 4) & 0xf) + 1;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006845 if (
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006846# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006847 !p_tgc &&
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006848# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006849 T_ME[0] == ESC && T_ME[1] == '|')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006850 {
6851 p = T_ME + 2;
6852 n = getdigits(&p);
6853 if (*p == 'm' && n > 0)
6854 {
6855 cterm_normal_fg_color = (n & 0xf) + 1;
6856 cterm_normal_bg_color = ((n >> 4) & 0xf) + 1;
6857 }
6858 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006859# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006860 cterm_normal_fg_gui_color = INVALCOLOR;
6861 cterm_normal_bg_gui_color = INVALCOLOR;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006862# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006863}
6864
6865
6866/*
6867 * visual bell: flash the screen
6868 */
6869 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006870visual_bell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006871{
6872 COORD coordOrigin = {0, 0};
6873 WORD attrFlash = ~g_attrCurrent & 0xff;
6874
6875 DWORD dwDummy;
Christopher Plewrightdc7179f2023-01-23 12:33:23 +00006876 LPWORD oldattrs = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006877
Christopher Plewrightdc7179f2023-01-23 12:33:23 +00006878# ifdef FEAT_TERMGUICOLORS
6879 if (!(p_tgc || t_colors >= 256))
6880# endif
6881 {
6882 oldattrs = ALLOC_MULT(WORD, Rows * Columns);
6883 if (oldattrs == NULL)
6884 return;
6885 ReadConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
Bram Moolenaar071d4272004-06-13 20:20:40 +00006886 coordOrigin, &dwDummy);
Christopher Plewrightdc7179f2023-01-23 12:33:23 +00006887 }
6888
Bram Moolenaar071d4272004-06-13 20:20:40 +00006889 FillConsoleOutputAttribute(g_hConOut, attrFlash, Rows * Columns,
6890 coordOrigin, &dwDummy);
6891
Bram Moolenaar0f873732019-12-05 20:28:46 +01006892 Sleep(15); // wait for 15 msec
Christopher Plewrightdc7179f2023-01-23 12:33:23 +00006893
6894 if (oldattrs != NULL)
6895 {
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006896 WriteConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
Bram Moolenaar071d4272004-06-13 20:20:40 +00006897 coordOrigin, &dwDummy);
Christopher Plewrightdc7179f2023-01-23 12:33:23 +00006898 vim_free(oldattrs);
6899 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006900}
6901
6902
6903/*
6904 * Make the cursor visible or invisible
6905 */
6906 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006907cursor_visible(BOOL fVisible)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006908{
6909 s_cursor_visible = fVisible;
Bram Moolenaar2695de62020-04-17 21:13:01 +02006910
Christopher Plewright38804d62022-11-09 23:55:52 +00006911 if (vtp_working)
Bram Moolenaar2695de62020-04-17 21:13:01 +02006912 vtp_printf("\033[?25%c", fVisible ? 'h' : 'l');
6913
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006914# ifdef MCH_CURSOR_SHAPE
Bram Moolenaar071d4272004-06-13 20:20:40 +00006915 mch_update_cursor();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006916# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006917}
6918
6919
6920/*
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02006921 * Write "cbToWrite" bytes in `pchBuf' to the screen.
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006922 * Returns the number of bytes actually written (at least one).
Bram Moolenaar071d4272004-06-13 20:20:40 +00006923 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006924 static DWORD
Bram Moolenaar071d4272004-06-13 20:20:40 +00006925write_chars(
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006926 char_u *pchBuf,
6927 DWORD cbToWrite)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006928{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006929 COORD coord = g_coord;
6930 DWORD written;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006931 DWORD n, cchwritten;
6932 static DWORD cells;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006933 static WCHAR *unicodebuf = NULL;
6934 static int unibuflen = 0;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006935 static int length;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006936 int cp = enc_utf8 ? CP_UTF8 : enc_codepage;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006937 static WCHAR *utf8spbuf = NULL;
6938 static int utf8splength;
6939 static DWORD utf8spcells;
6940 static WCHAR **utf8usingbuf = &unicodebuf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006941
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006942 if (cbToWrite != 1 || *pchBuf != ' ' || !enc_utf8)
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006943 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006944 utf8usingbuf = &unicodebuf;
6945 do
6946 {
6947 length = MultiByteToWideChar(cp, 0, (LPCSTR)pchBuf, cbToWrite,
6948 unicodebuf, unibuflen);
6949 if (length && length <= unibuflen)
6950 break;
6951 vim_free(unicodebuf);
6952 unicodebuf = length ? LALLOC_MULT(WCHAR, length) : NULL;
6953 unibuflen = unibuflen ? 0 : length;
Bram Moolenaarc9471b12023-05-09 15:00:00 +01006954 } while (TRUE);
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006955 cells = mb_string2cells(pchBuf, cbToWrite);
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006956 }
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006957 else // cbToWrite == 1 && *pchBuf == ' ' && enc_utf8
6958 {
6959 if (utf8usingbuf != &utf8spbuf)
6960 {
6961 if (utf8spbuf == NULL)
6962 {
6963 cells = mb_string2cells((char_u *)" ", 1);
6964 length = MultiByteToWideChar(CP_UTF8, 0, " ", 1, NULL, 0);
6965 utf8spbuf = LALLOC_MULT(WCHAR, length);
6966 if (utf8spbuf != NULL)
6967 {
6968 MultiByteToWideChar(CP_UTF8, 0, " ", 1, utf8spbuf, length);
6969 utf8usingbuf = &utf8spbuf;
6970 utf8splength = length;
6971 utf8spcells = cells;
6972 }
6973 }
6974 else
6975 {
6976 utf8usingbuf = &utf8spbuf;
6977 length = utf8splength;
6978 cells = utf8spcells;
6979 }
6980 }
6981 }
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006982
Christopher Plewrightf75a2cb2023-01-28 10:28:09 +00006983 if (!USE_VTP)
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006984 {
6985 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, cells,
6986 coord, &written);
6987 // When writing fails or didn't write a single character, pretend one
6988 // character was written, otherwise we get stuck.
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006989 if (WriteConsoleOutputCharacterW(g_hConOut, *utf8usingbuf, length,
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006990 coord, &cchwritten) == 0
6991 || cchwritten == 0 || cchwritten == (DWORD)-1)
6992 cchwritten = 1;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006993 }
6994 else
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006995 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006996 if (WriteConsoleW(g_hConOut, *utf8usingbuf, length, &cchwritten,
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006997 NULL) == 0 || cchwritten == 0)
6998 cchwritten = 1;
6999 }
Bram Moolenaarac360bf2015-09-01 20:31:20 +02007000
K.Takata135e1522022-01-29 15:27:58 +00007001 if (cchwritten == (DWORD)length)
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007002 {
7003 written = cbToWrite;
7004 g_coord.X += (SHORT)cells;
7005 }
7006 else
7007 {
7008 char_u *p = pchBuf;
7009 for (n = 0; n < cchwritten; n++)
7010 MB_CPTR_ADV(p);
7011 written = p - pchBuf;
7012 g_coord.X += (SHORT)mb_string2cells(pchBuf, written);
Bram Moolenaarac360bf2015-09-01 20:31:20 +02007013 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007014
7015 while (g_coord.X > g_srScrollRegion.Right)
7016 {
7017 g_coord.X -= (SHORT) Columns;
7018 if (g_coord.Y < g_srScrollRegion.Bottom)
7019 g_coord.Y++;
7020 }
7021
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007022 // Cursor under VTP is always in the correct position, no need to reset.
Christopher Plewrightf75a2cb2023-01-28 10:28:09 +00007023 if (!USE_VTP)
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007024 gotoxy(g_coord.X + 1, g_coord.Y + 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007025
7026 return written;
7027}
7028
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007029 static char_u *
7030get_seq(
7031 int *args,
7032 int *count,
7033 char_u *head)
7034{
7035 int argc;
7036 char_u *p;
7037
7038 if (head == NULL || *head != '\033')
7039 return NULL;
7040
7041 argc = 0;
7042 p = head;
7043 ++p;
7044 do
7045 {
7046 ++p;
7047 args[argc] = getdigits(&p);
7048 argc += (argc < 15) ? 1 : 0;
7049 } while (*p == ';');
7050 *count = argc;
7051
7052 return p;
7053}
7054
7055 static char_u *
7056get_sgr(
7057 int *args,
7058 int *count,
7059 char_u *head)
7060{
7061 char_u *p = get_seq(args, count, head);
7062
7063 return (p && *p == 'm') ? ++p : NULL;
7064}
7065
7066/*
7067 * Pointer to next if SGR (^[[n;2;*;*;*m), NULL otherwise.
7068 */
7069 static char_u *
7070sgrn2(
7071 char_u *head,
7072 int n)
7073{
7074 int argc;
7075 int args[16];
7076 char_u *p = get_sgr(args, &argc, head);
7077
7078 return p && argc == 5 && args[0] == n && args[1] == 2 ? p : NULL;
7079}
7080
7081/*
7082 * Pointer to next if SGR(^[[nm)<space>ESC, NULL otherwise.
7083 */
7084 static char_u *
7085sgrnc(
7086 char_u *head,
7087 int n)
7088{
7089 int argc;
7090 int args[16];
7091 char_u *p = get_sgr(args, &argc, head);
7092
7093 return p && argc == 1 && args[0] == n && (p = skipwhite(p)) && *p == '\033'
7094 ? p : NULL;
7095}
7096
7097 static char_u *
7098skipblank(char_u *q)
7099{
7100 char_u *p = q;
7101
7102 while (*p == ' ' || *p == '\t' || *p == '\n' || *p == '\r')
7103 ++p;
7104 return p;
7105}
7106
7107/*
7108 * Pointer to the next if any whitespace that may follow SGR is ESC, otherwise
7109 * NULL.
7110 */
7111 static char_u *
7112sgrn2c(
7113 char_u *head,
7114 int n)
7115{
7116 char_u *p = sgrn2(head, n);
7117
7118 return p && *p != NUL && (p = skipblank(p)) && *p == '\033' ? p : NULL;
7119}
7120
7121/*
7122 * If there is only a newline between the sequence immediately following it,
7123 * a pointer to the character following the newline is returned.
7124 * Otherwise NULL.
7125 */
7126 static char_u *
7127sgrn2cn(
7128 char_u *head,
7129 int n)
7130{
7131 char_u *p = sgrn2(head, n);
7132
7133 return p && p[0] == 0x0a && p[1] == '\033' ? ++p : NULL;
7134}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007135
7136/*
7137 * mch_write(): write the output buffer to the screen, translating ESC
7138 * sequences into calls to console output routines.
7139 */
7140 void
7141mch_write(
7142 char_u *s,
7143 int len)
7144{
Bram Moolenaard23f8bd2021-04-21 11:30:48 +02007145 char_u *end = s + len;
7146
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007147# ifdef VIMDLL
7148 if (gui.in_use)
7149 return;
7150# endif
7151
Bram Moolenaar071d4272004-06-13 20:20:40 +00007152 if (!term_console)
7153 {
7154 write(1, s, (unsigned)len);
7155 return;
7156 }
7157
Bram Moolenaar0f873732019-12-05 20:28:46 +01007158 // translate ESC | sequences into faked bios calls
Bram Moolenaar071d4272004-06-13 20:20:40 +00007159 while (len--)
7160 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007161 int prefix = -1;
7162 char_u ch;
7163
7164 // While processing a sequence, on rare occasions it seems that another
7165 // sequence may be inserted asynchronously.
7166 if (len < 0)
7167 {
Bram Moolenaara4d158b2022-08-14 14:17:45 +01007168 redraw_all_later(UPD_CLEAR);
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007169 return;
7170 }
7171
Bram Moolenaard23f8bd2021-04-21 11:30:48 +02007172 while (s + ++prefix < end)
7173 {
7174 ch = s[prefix];
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007175 if (ch <= 0x1e && !(ch != '\n' && ch != '\r' && ch != '\b'
7176 && ch != '\a' && ch != '\033'))
7177 break;
Bram Moolenaard23f8bd2021-04-21 11:30:48 +02007178 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007179
7180 if (p_wd)
7181 {
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02007182 WaitForChar(p_wd, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007183 if (prefix != 0)
7184 prefix = 1;
7185 }
7186
7187 if (prefix != 0)
7188 {
7189 DWORD nWritten;
7190
7191 nWritten = write_chars(s, prefix);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007192# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00007193 if (fdDump)
7194 {
7195 fputc('>', fdDump);
7196 fwrite(s, sizeof(char_u), nWritten, fdDump);
7197 fputs("<\n", fdDump);
7198 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007199# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007200 len -= (nWritten - 1);
7201 s += nWritten;
7202 }
7203 else if (s[0] == '\n')
7204 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007205 // \n, newline: go to the beginning of the next line or scroll
Bram Moolenaar071d4272004-06-13 20:20:40 +00007206 if (g_coord.Y == g_srScrollRegion.Bottom)
7207 {
7208 scroll(1);
7209 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Bottom + 1);
7210 }
7211 else
7212 {
7213 gotoxy(g_srScrollRegion.Left + 1, g_coord.Y + 2);
7214 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007215# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00007216 if (fdDump)
7217 fputs("\\n\n", fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007218# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007219 s++;
7220 }
7221 else if (s[0] == '\r')
7222 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007223 // \r, carriage return: go to beginning of line
Bram Moolenaar071d4272004-06-13 20:20:40 +00007224 gotoxy(g_srScrollRegion.Left+1, g_coord.Y + 1);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007225# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00007226 if (fdDump)
7227 fputs("\\r\n", fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007228# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007229 s++;
7230 }
7231 else if (s[0] == '\b')
7232 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007233 // \b, backspace: move cursor one position left
Bram Moolenaar071d4272004-06-13 20:20:40 +00007234 if (g_coord.X > g_srScrollRegion.Left)
7235 g_coord.X--;
7236 else if (g_coord.Y > g_srScrollRegion.Top)
7237 {
7238 g_coord.X = g_srScrollRegion.Right;
7239 g_coord.Y--;
7240 }
7241 gotoxy(g_coord.X + 1, g_coord.Y + 1);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007242# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00007243 if (fdDump)
7244 fputs("\\b\n", fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007245# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007246 s++;
7247 }
7248 else if (s[0] == '\a')
7249 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007250 // \a, bell
Bram Moolenaar071d4272004-06-13 20:20:40 +00007251 MessageBeep(0xFFFFFFFF);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007252# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00007253 if (fdDump)
7254 fputs("\\a\n", fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007255# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007256 s++;
7257 }
7258 else if (s[0] == ESC && len >= 3-1 && s[1] == '|')
7259 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007260# ifdef MCH_WRITE_DUMP
Bram Moolenaarc0197e22004-09-13 20:26:32 +00007261 char_u *old_s = s;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007262# endif
Bram Moolenaarc0197e22004-09-13 20:26:32 +00007263 char_u *p;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007264 int arg1 = 0, arg2 = 0, argc = 0, args[16];
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007265 char_u *sp;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007266
7267 switch (s[2])
7268 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00007269 case '0': case '1': case '2': case '3': case '4':
7270 case '5': case '6': case '7': case '8': case '9':
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007271 if (*(p = get_seq(args, &argc, s)) != 'm')
7272 goto notsgr;
7273
7274 p = s;
7275
7276 // Handling frequent optional sequences. Output to the screen
7277 // takes too long, so do not output as much as possible.
7278
7279 // If resetFG,FG,BG,<cr>,BG,FG are connected, the preceding
7280 // resetFG,FG,BG are omitted.
7281 if (sgrn2(sgrn2(sgrn2cn(sgrn2(sgrnc(p, 39), 38), 48), 48), 38))
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007282 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007283 p = sgrn2(sgrn2(sgrnc(p, 39), 38), 48);
7284 len = len + 1 - (int)(p - s);
7285 s = p;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007286 break;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007287 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007288
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007289 // If FG,BG,BG,FG of SGR are connected, the first FG can be
7290 // omitted.
7291 if (sgrn2(sgrn2(sgrn2c((sp = sgrn2(p, 38)), 48), 48), 38))
7292 p = sp;
7293
7294 // If FG,BG,FG,BG of SGR are connected, the first FG can be
7295 // omitted.
7296 if (sgrn2(sgrn2(sgrn2c((sp = sgrn2(p, 38)), 48), 38), 48))
7297 p = sp;
7298
7299 // If BG,BG of SGR are connected, the first BG can be omitted.
7300 if (sgrn2((sp = sgrn2(p, 48)), 48))
7301 p = sp;
7302
7303 // If restoreFG and FG are connected, the restoreFG can be
Bram Moolenaar9f1983d2022-05-12 20:35:35 +01007304 // omitted.
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007305 if (sgrn2((sp = sgrnc(p, 39)), 38))
7306 p = sp;
7307
7308 p = get_seq(args, &argc, p);
7309
7310notsgr:
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007311 arg1 = args[0];
7312 arg2 = args[1];
7313 if (*p == 'm')
Bram Moolenaar071d4272004-06-13 20:20:40 +00007314 {
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007315 if (argc == 1 && args[0] == 0)
7316 normvideo();
7317 else if (argc == 1)
7318 {
Christopher Plewrightf75a2cb2023-01-28 10:28:09 +00007319 if (USE_VTP)
Christopher Plewright38804d62022-11-09 23:55:52 +00007320 textcolor((WORD)arg1);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007321 else
Christopher Plewright38804d62022-11-09 23:55:52 +00007322 textattr((WORD)arg1);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007323 }
Christopher Plewright38804d62022-11-09 23:55:52 +00007324 else if (vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007325 vtp_sgr_bulks(argc, args);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007326 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007327 else if (argc == 2 && *p == 'H')
Bram Moolenaar071d4272004-06-13 20:20:40 +00007328 {
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007329 gotoxy(arg2, arg1);
7330 }
7331 else if (argc == 2 && *p == 'r')
7332 {
7333 set_scroll_region(0, arg1 - 1, Columns - 1, arg2 - 1);
7334 }
Bram Moolenaar6982f422019-02-16 16:48:01 +01007335 else if (argc == 2 && *p == 'R')
7336 {
7337 set_scroll_region_tb(arg1, arg2);
7338 }
7339 else if (argc == 2 && *p == 'V')
7340 {
7341 set_scroll_region_lr(arg1, arg2);
7342 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007343 else if (argc == 1 && *p == 'A')
7344 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00007345 gotoxy(g_coord.X + 1,
7346 max(g_srScrollRegion.Top, g_coord.Y - arg1) + 1);
7347 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007348 else if (argc == 1 && *p == 'b')
Bram Moolenaar071d4272004-06-13 20:20:40 +00007349 {
7350 textbackground((WORD) arg1);
7351 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007352 else if (argc == 1 && *p == 'C')
7353 {
7354 gotoxy(min(g_srScrollRegion.Right, g_coord.X + arg1) + 1,
7355 g_coord.Y + 1);
7356 }
7357 else if (argc == 1 && *p == 'f')
7358 {
7359 textcolor((WORD) arg1);
7360 }
7361 else if (argc == 1 && *p == 'H')
7362 {
7363 gotoxy(1, arg1);
7364 }
7365 else if (argc == 1 && *p == 'L')
7366 {
7367 insert_lines(arg1);
7368 }
7369 else if (argc == 1 && *p == 'M')
Bram Moolenaar071d4272004-06-13 20:20:40 +00007370 {
7371 delete_lines(arg1);
7372 }
7373
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007374 len -= (int)(p - s);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007375 s = p + 1;
7376 break;
7377
Bram Moolenaar071d4272004-06-13 20:20:40 +00007378 case 'A':
Bram Moolenaar071d4272004-06-13 20:20:40 +00007379 gotoxy(g_coord.X + 1,
7380 max(g_srScrollRegion.Top, g_coord.Y - 1) + 1);
7381 goto got3;
7382
7383 case 'B':
7384 visual_bell();
7385 goto got3;
7386
7387 case 'C':
Bram Moolenaar071d4272004-06-13 20:20:40 +00007388 gotoxy(min(g_srScrollRegion.Right, g_coord.X + 1) + 1,
7389 g_coord.Y + 1);
7390 goto got3;
7391
7392 case 'E':
7393 termcap_mode_end();
7394 goto got3;
7395
7396 case 'F':
7397 standout();
7398 goto got3;
7399
7400 case 'f':
7401 standend();
7402 goto got3;
7403
7404 case 'H':
7405 gotoxy(1, 1);
7406 goto got3;
7407
7408 case 'j':
7409 clear_to_end_of_display();
7410 goto got3;
7411
7412 case 'J':
7413 clear_screen();
7414 goto got3;
7415
7416 case 'K':
7417 clear_to_end_of_line();
7418 goto got3;
7419
7420 case 'L':
7421 insert_lines(1);
7422 goto got3;
7423
7424 case 'M':
7425 delete_lines(1);
7426 goto got3;
7427
7428 case 'S':
7429 termcap_mode_start();
7430 goto got3;
7431
7432 case 'V':
7433 cursor_visible(TRUE);
7434 goto got3;
7435
7436 case 'v':
7437 cursor_visible(FALSE);
7438 goto got3;
7439
7440 got3:
7441 s += 3;
7442 len -= 2;
7443 }
7444
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007445# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00007446 if (fdDump)
7447 {
7448 fputs("ESC | ", fdDump);
7449 fwrite(old_s + 2, sizeof(char_u), s - old_s - 2, fdDump);
7450 fputc('\n', fdDump);
7451 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007452# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007453 }
K.Takatadf5320c2022-09-01 13:20:16 +01007454 else if (s[0] == ESC && len >= 3-1 && s[1] == '[')
7455 {
7456 int l = 2;
7457
Keith Thompson184f71c2024-01-04 21:19:04 +01007458 if (SAFE_isdigit(s[l]))
K.Takatadf5320c2022-09-01 13:20:16 +01007459 l++;
7460 if (s[l] == ' ' && s[l + 1] == 'q')
7461 {
7462 // DECSCUSR (cursor style) sequences
Christopher Plewright38804d62022-11-09 23:55:52 +00007463 if (vtp_working)
K.Takatadf5320c2022-09-01 13:20:16 +01007464 vtp_printf("%.*s", l + 2, s); // Pass through
7465 s += l + 2;
7466 len -= l + 1;
7467 }
7468 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007469 else
7470 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007471 // Write a single character
Bram Moolenaar071d4272004-06-13 20:20:40 +00007472 DWORD nWritten;
7473
7474 nWritten = write_chars(s, 1);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007475# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00007476 if (fdDump)
7477 {
7478 fputc('>', fdDump);
7479 fwrite(s, sizeof(char_u), nWritten, fdDump);
7480 fputs("<\n", fdDump);
7481 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007482# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007483
7484 len -= (nWritten - 1);
7485 s += nWritten;
7486 }
7487 }
7488
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007489# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00007490 if (fdDump)
7491 fflush(fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007492# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007493}
7494
Bram Moolenaar0f873732019-12-05 20:28:46 +01007495#endif // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00007496
7497
7498/*
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01007499 * Delay for "msec" milliseconds.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007500 */
7501 void
7502mch_delay(
7503 long msec,
Bram Moolenaar0981c872020-08-23 14:28:37 +02007504 int flags UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007505{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007506#if defined(FEAT_GUI_MSWIN) && !defined(VIMDLL)
Bram Moolenaar0f873732019-12-05 20:28:46 +01007507 Sleep((int)msec); // never wait for input
7508#else // Console
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007509# ifdef VIMDLL
7510 if (gui.in_use)
7511 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007512 Sleep((int)msec); // never wait for input
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007513 return;
7514 }
7515# endif
Bram Moolenaar0981c872020-08-23 14:28:37 +02007516 if (flags & MCH_DELAY_IGNOREINPUT)
Bram Moolenaar325b7a22004-07-05 15:58:32 +00007517# ifdef FEAT_MZSCHEME
7518 if (mzthreads_allowed() && p_mzq > 0 && msec > p_mzq)
7519 {
7520 int towait = p_mzq;
7521
Bram Moolenaar0f873732019-12-05 20:28:46 +01007522 // if msec is large enough, wait by portions in p_mzq
Bram Moolenaar325b7a22004-07-05 15:58:32 +00007523 while (msec > 0)
7524 {
7525 mzvim_check_threads();
7526 if (msec < towait)
7527 towait = msec;
7528 Sleep(towait);
7529 msec -= towait;
7530 }
7531 }
7532 else
7533# endif
7534 Sleep((int)msec);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007535 else
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02007536 WaitForChar(msec, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007537#endif
7538}
7539
7540
7541/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01007542 * This version of remove is not scared by a readonly (backup) file.
7543 * This can also remove a symbolic link like Unix.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007544 * Return 0 for success, -1 for failure.
7545 */
7546 int
7547mch_remove(char_u *name)
7548{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007549 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007550 int n;
7551
Bram Moolenaar203258c2016-01-17 22:15:16 +01007552 /*
7553 * On Windows, deleting a directory's symbolic link is done by
7554 * RemoveDirectory(): mch_rmdir. It seems unnatural, but it is fact.
7555 */
7556 if (mch_isdir(name) && mch_is_symbolic_link(name))
7557 return mch_rmdir(name);
7558
Bram Moolenaar12b559e2013-06-12 22:41:37 +02007559 win32_setattrs(name, FILE_ATTRIBUTE_NORMAL);
7560
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007561 wn = enc_to_utf16(name, NULL);
7562 if (wn == NULL)
7563 return -1;
7564
7565 n = DeleteFileW(wn) ? 0 : -1;
7566 vim_free(wn);
7567 return n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007568}
7569
7570
7571/*
Bram Moolenaarb9c31e72016-09-29 15:18:57 +02007572 * Check for an "interrupt signal": CTRL-break or CTRL-C.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007573 */
7574 void
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02007575mch_breakcheck(int force UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007576{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007577#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
7578# ifdef VIMDLL
7579 if (!gui.in_use)
7580# endif
7581 if (g_fCtrlCPressed || g_fCBrkPressed)
7582 {
7583 ctrl_break_was_pressed = g_fCBrkPressed;
7584 g_fCtrlCPressed = g_fCBrkPressed = FALSE;
7585 got_int = TRUE;
7586 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007587#endif
7588}
7589
Bram Moolenaar0f873732019-12-05 20:28:46 +01007590// physical RAM to leave for the OS
Bram Moolenaaree273972016-01-02 21:11:51 +01007591#define WINNT_RESERVE_BYTES (256*1024*1024)
Bram Moolenaaree273972016-01-02 21:11:51 +01007592
7593/*
7594 * How much main memory in KiB that can be used by VIM.
7595 */
Bram Moolenaaree273972016-01-02 21:11:51 +01007596 long_u
Bram Moolenaar1266d672017-02-01 13:43:36 +01007597mch_total_mem(int special UNUSED)
Bram Moolenaaree273972016-01-02 21:11:51 +01007598{
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007599 MEMORYSTATUSEX ms;
7600
Bram Moolenaar0f873732019-12-05 20:28:46 +01007601 // Need to use GlobalMemoryStatusEx() when there is more memory than
7602 // what fits in 32 bits.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007603 ms.dwLength = sizeof(MEMORYSTATUSEX);
7604 GlobalMemoryStatusEx(&ms);
7605 if (ms.ullAvailVirtual < ms.ullTotalPhys)
Bram Moolenaaree273972016-01-02 21:11:51 +01007606 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007607 // Process address space fits in physical RAM, use all of it.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007608 return (long_u)(ms.ullAvailVirtual / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01007609 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007610 if (ms.ullTotalPhys <= WINNT_RESERVE_BYTES)
Bram Moolenaaree273972016-01-02 21:11:51 +01007611 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007612 // Catch old NT box or perverse hardware setup.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007613 return (long_u)((ms.ullTotalPhys / 2) / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01007614 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01007615 // Use physical RAM less reserve for OS + data.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007616 return (long_u)((ms.ullTotalPhys - WINNT_RESERVE_BYTES) / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01007617}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007618
Bram Moolenaar071d4272004-06-13 20:20:40 +00007619/*
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007620 * mch_wrename() works around a bug in rename (aka MoveFile) in
Bram Moolenaar071d4272004-06-13 20:20:40 +00007621 * Windows 95: rename("foo.bar", "foo.bar~") will generate a
7622 * file whose short file name is "FOO.BAR" (its long file name will
7623 * be correct: "foo.bar~"). Because a file can be accessed by
7624 * either its SFN or its LFN, "foo.bar" has effectively been
7625 * renamed to "foo.bar", which is not at all what was wanted. This
7626 * seems to happen only when renaming files with three-character
7627 * extensions by appending a suffix that does not include ".".
7628 * Windows NT gets it right, however, with an SFN of "FOO~1.BAR".
7629 *
7630 * There is another problem, which isn't really a bug but isn't right either:
7631 * When renaming "abcdef~1.txt" to "abcdef~1.txt~", the short name can be
7632 * "abcdef~1.txt" again. This has been reported on Windows NT 4.0 with
7633 * service pack 6. Doesn't seem to happen on Windows 98.
7634 *
7635 * Like rename(), returns 0 upon success, non-zero upon failure.
7636 * Should probably set errno appropriately when errors occur.
7637 */
7638 int
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007639mch_wrename(WCHAR *wold, WCHAR *wnew)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007640{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007641 WCHAR *p;
7642 int i;
7643 WCHAR szTempFile[_MAX_PATH + 1];
7644 WCHAR szNewPath[_MAX_PATH + 1];
Bram Moolenaar071d4272004-06-13 20:20:40 +00007645 HANDLE hf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007646
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007647 // No need to play tricks unless the file name contains a "~" as the
7648 // seventh character.
7649 p = wold;
7650 for (i = 0; wold[i] != NUL; ++i)
7651 if ((wold[i] == '/' || wold[i] == '\\' || wold[i] == ':')
7652 && wold[i + 1] != 0)
7653 p = wold + i + 1;
7654 if ((int)(wold + i - p) < 8 || p[6] != '~')
7655 return (MoveFileW(wold, wnew) == 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007656
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007657 // Get base path of new file name. Undocumented feature: If pszNewFile is
7658 // a directory, no error is returned and pszFilePart will be NULL.
7659 if (GetFullPathNameW(wnew, _MAX_PATH, szNewPath, &p) == 0 || p == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007660 return -1;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007661 *p = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007662
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007663 // Get (and create) a unique temporary file name in directory of new file
7664 if (GetTempFileNameW(szNewPath, L"VIM", 0, szTempFile) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007665 return -2;
7666
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007667 // blow the temp file away
7668 if (!DeleteFileW(szTempFile))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007669 return -3;
7670
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007671 // rename old file to the temp file
7672 if (!MoveFileW(wold, szTempFile))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007673 return -4;
7674
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007675 // now create an empty file called pszOldFile; this prevents the operating
7676 // system using pszOldFile as an alias (SFN) if we're renaming within the
7677 // same directory. For example, we're editing a file called
7678 // filename.asc.txt by its SFN, filena~1.txt. If we rename filena~1.txt
7679 // to filena~1.txt~ (i.e., we're making a backup while writing it), the
7680 // SFN for filena~1.txt~ will be filena~1.txt, by default, which will
7681 // cause all sorts of problems later in buf_write(). So, we create an
7682 // empty file called filena~1.txt and the system will have to find some
7683 // other SFN for filena~1.txt~, such as filena~2.txt
7684 if ((hf = CreateFileW(wold, GENERIC_WRITE, 0, NULL, CREATE_NEW,
Bram Moolenaar071d4272004-06-13 20:20:40 +00007685 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
7686 return -5;
7687 if (!CloseHandle(hf))
7688 return -6;
7689
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007690 // rename the temp file to the new file
7691 if (!MoveFileW(szTempFile, wnew))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007692 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007693 // Renaming failed. Rename the file back to its old name, so that it
7694 // looks like nothing happened.
7695 (void)MoveFileW(szTempFile, wold);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007696 return -7;
7697 }
7698
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007699 // Seems to be left around on Novell filesystems
7700 DeleteFileW(szTempFile);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007701
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007702 // finally, remove the empty old file
7703 if (!DeleteFileW(wold))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007704 return -8;
7705
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007706 return 0;
7707}
7708
7709
7710/*
7711 * Converts the filenames to UTF-16, then call mch_wrename().
7712 * Like rename(), returns 0 upon success, non-zero upon failure.
7713 */
7714 int
7715mch_rename(
7716 const char *pszOldFile,
7717 const char *pszNewFile)
7718{
7719 WCHAR *wold = NULL;
7720 WCHAR *wnew = NULL;
7721 int retval = -1;
7722
7723 wold = enc_to_utf16((char_u *)pszOldFile, NULL);
7724 wnew = enc_to_utf16((char_u *)pszNewFile, NULL);
7725 if (wold != NULL && wnew != NULL)
7726 retval = mch_wrename(wold, wnew);
7727 vim_free(wold);
7728 vim_free(wnew);
7729 return retval;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007730}
7731
7732/*
7733 * Get the default shell for the current hardware platform
7734 */
7735 char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007736default_shell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007737{
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007738 return "cmd.exe";
Bram Moolenaar071d4272004-06-13 20:20:40 +00007739}
7740
7741/*
7742 * mch_access() extends access() to do more detailed check on network drives.
7743 * Returns 0 if file "n" has access rights according to "p", -1 otherwise.
7744 */
7745 int
7746mch_access(char *n, int p)
7747{
7748 HANDLE hFile;
Bram Moolenaar0f873732019-12-05 20:28:46 +01007749 int retval = -1; // default: fail
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007750 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007751
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007752 wn = enc_to_utf16((char_u *)n, NULL);
7753 if (wn == NULL)
7754 return -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007755
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01007756 if (mch_isdir((char_u *)n))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007757 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00007758 WCHAR TempNameW[_MAX_PATH + 16] = L"";
Bram Moolenaar071d4272004-06-13 20:20:40 +00007759
7760 if (p & R_OK)
7761 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007762 // Read check is performed by seeing if we can do a find file on
7763 // the directory for any file.
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007764 int i;
7765 WIN32_FIND_DATAW d;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007766
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007767 for (i = 0; i < _MAX_PATH && wn[i] != 0; ++i)
7768 TempNameW[i] = wn[i];
7769 if (TempNameW[i - 1] != '\\' && TempNameW[i - 1] != '/')
7770 TempNameW[i++] = '\\';
7771 TempNameW[i++] = '*';
7772 TempNameW[i++] = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007773
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007774 hFile = FindFirstFileW(TempNameW, &d);
7775 if (hFile == INVALID_HANDLE_VALUE)
7776 goto getout;
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007777 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00007778 (void)FindClose(hFile);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007779 }
7780
7781 if (p & W_OK)
7782 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007783 // Trying to create a temporary file in the directory should catch
7784 // directories on read-only network shares. However, in
7785 // directories whose ACL allows writes but denies deletes will end
7786 // up keeping the temporary file :-(.
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007787 if (!GetTempFileNameW(wn, L"VIM", 0, TempNameW))
7788 goto getout;
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007789 else
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007790 DeleteFileW(TempNameW);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007791 }
7792 }
7793 else
7794 {
Bram Moolenaar5aa98962018-05-06 17:09:38 +02007795 // Don't consider a file read-only if another process has opened it.
7796 DWORD share_mode = FILE_SHARE_READ | FILE_SHARE_WRITE;
7797
Bram Moolenaar0f873732019-12-05 20:28:46 +01007798 // Trying to open the file for the required access does ACL, read-only
7799 // network share, and file attribute checks.
Bram Moolenaar5aa98962018-05-06 17:09:38 +02007800 DWORD access_mode = ((p & W_OK) ? GENERIC_WRITE : 0)
7801 | ((p & R_OK) ? GENERIC_READ : 0);
7802
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007803 hFile = CreateFileW(wn, access_mode, share_mode,
7804 NULL, OPEN_EXISTING, 0, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007805 if (hFile == INVALID_HANDLE_VALUE)
7806 goto getout;
7807 CloseHandle(hFile);
7808 }
7809
Bram Moolenaar0f873732019-12-05 20:28:46 +01007810 retval = 0; // success
Bram Moolenaar071d4272004-06-13 20:20:40 +00007811getout:
Bram Moolenaar071d4272004-06-13 20:20:40 +00007812 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007813 return retval;
7814}
7815
Bram Moolenaar071d4272004-06-13 20:20:40 +00007816/*
Bram Moolenaar36f692d2008-11-20 16:10:17 +00007817 * Version of open() that may use UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007818 */
7819 int
Bram Moolenaarb6843a02017-08-02 22:07:12 +02007820mch_open(const char *name, int flags, int mode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007821{
7822 WCHAR *wn;
7823 int f;
7824
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007825 wn = enc_to_utf16((char_u *)name, NULL);
7826 if (wn == NULL)
7827 return -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007828
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007829 f = _wopen(wn, flags, mode);
7830 vim_free(wn);
7831 return f;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007832}
7833
7834/*
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007835 * Version of fopen() that uses UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007836 */
7837 FILE *
Bram Moolenaarb6843a02017-08-02 22:07:12 +02007838mch_fopen(const char *name, const char *mode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007839{
7840 WCHAR *wn, *wm;
7841 FILE *f = NULL;
7842
Bram Moolenaara12a1612019-01-24 16:39:02 +01007843#if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0f873732019-12-05 20:28:46 +01007844 // Work around an annoying assertion in the Microsoft debug CRT
7845 // when mode's text/binary setting doesn't match _get_fmode().
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007846 char newMode = mode[strlen(mode) - 1];
7847 int oldMode = 0;
Bram Moolenaar0fde2902008-03-16 13:54:13 +00007848
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007849 _get_fmode(&oldMode);
7850 if (newMode == 't')
7851 _set_fmode(_O_TEXT);
7852 else if (newMode == 'b')
7853 _set_fmode(_O_BINARY);
Bram Moolenaara12a1612019-01-24 16:39:02 +01007854#endif
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007855 wn = enc_to_utf16((char_u *)name, NULL);
7856 wm = enc_to_utf16((char_u *)mode, NULL);
7857 if (wn != NULL && wm != NULL)
7858 f = _wfopen(wn, wm);
7859 vim_free(wn);
7860 vim_free(wm);
Bram Moolenaar0fde2902008-03-16 13:54:13 +00007861
Bram Moolenaara12a1612019-01-24 16:39:02 +01007862#if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007863 _set_fmode(oldMode);
Bram Moolenaara12a1612019-01-24 16:39:02 +01007864#endif
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007865 return f;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007866}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007867
Bram Moolenaar071d4272004-06-13 20:20:40 +00007868/*
7869 * SUB STREAM (aka info stream) handling:
7870 *
Bram Moolenaar8e7d6222020-12-18 19:49:56 +01007871 * NTFS can have sub streams for each file. The normal contents of a file is
7872 * stored in the main stream, and extra contents (author information, title and
7873 * so on) can be stored in a sub stream. After Windows 2000, the user can
7874 * access and store this information in sub streams via an explorer's property
7875 * menu item in the right click menu. This information in sub streams was lost
7876 * when copying only the main stream. Therefore we have to copy sub streams.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007877 *
7878 * Incomplete explanation:
7879 * http://msdn.microsoft.com/library/en-us/dnw2k/html/ntfs5.asp
7880 * More useful info and an example:
7881 * http://www.sysinternals.com/ntw2k/source/misc.shtml#streams
7882 */
7883
7884/*
7885 * Copy info stream data "substream". Read from the file with BackupRead(sh)
7886 * and write to stream "substream" of file "to".
7887 * Errors are ignored.
7888 */
7889 static void
7890copy_substream(HANDLE sh, void *context, WCHAR *to, WCHAR *substream, long len)
7891{
7892 HANDLE hTo;
7893 WCHAR *to_name;
7894
7895 to_name = malloc((wcslen(to) + wcslen(substream) + 1) * sizeof(WCHAR));
7896 wcscpy(to_name, to);
7897 wcscat(to_name, substream);
7898
7899 hTo = CreateFileW(to_name, GENERIC_WRITE, 0, NULL, OPEN_ALWAYS,
7900 FILE_ATTRIBUTE_NORMAL, NULL);
7901 if (hTo != INVALID_HANDLE_VALUE)
7902 {
7903 long done;
7904 DWORD todo;
7905 DWORD readcnt, written;
7906 char buf[4096];
7907
Bram Moolenaar0f873732019-12-05 20:28:46 +01007908 // Copy block of bytes at a time. Abort when something goes wrong.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007909 for (done = 0; done < len; done += written)
7910 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007911 // (size_t) cast for Borland C 5.5
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007912 todo = (DWORD)((size_t)(len - done) > sizeof(buf) ? sizeof(buf)
7913 : (size_t)(len - done));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007914 if (!BackupRead(sh, (LPBYTE)buf, todo, &readcnt,
7915 FALSE, FALSE, context)
7916 || readcnt != todo
7917 || !WriteFile(hTo, buf, todo, &written, NULL)
7918 || written != todo)
7919 break;
7920 }
7921 CloseHandle(hTo);
7922 }
7923
7924 free(to_name);
7925}
7926
7927/*
7928 * Copy info streams from file "from" to file "to".
7929 */
7930 static void
7931copy_infostreams(char_u *from, char_u *to)
7932{
7933 WCHAR *fromw;
7934 WCHAR *tow;
7935 HANDLE sh;
7936 WIN32_STREAM_ID sid;
7937 int headersize;
7938 WCHAR streamname[_MAX_PATH];
7939 DWORD readcount;
7940 void *context = NULL;
7941 DWORD lo, hi;
7942 int len;
7943
Bram Moolenaar0f873732019-12-05 20:28:46 +01007944 // Convert the file names to wide characters.
Bram Moolenaar36f692d2008-11-20 16:10:17 +00007945 fromw = enc_to_utf16(from, NULL);
7946 tow = enc_to_utf16(to, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007947 if (fromw != NULL && tow != NULL)
7948 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007949 // Open the file for reading.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007950 sh = CreateFileW(fromw, GENERIC_READ, FILE_SHARE_READ, NULL,
7951 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
7952 if (sh != INVALID_HANDLE_VALUE)
7953 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007954 // Use BackupRead() to find the info streams. Repeat until we
7955 // have done them all.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007956 for (;;)
7957 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007958 // Get the header to find the length of the stream name. If
7959 // the "readcount" is zero we have done all info streams.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007960 ZeroMemory(&sid, sizeof(WIN32_STREAM_ID));
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007961 headersize = (int)((char *)&sid.cStreamName - (char *)&sid.dwStreamId);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007962 if (!BackupRead(sh, (LPBYTE)&sid, headersize,
7963 &readcount, FALSE, FALSE, &context)
7964 || readcount == 0)
7965 break;
7966
Bram Moolenaar0f873732019-12-05 20:28:46 +01007967 // We only deal with streams that have a name. The normal
7968 // file data appears to be without a name, even though docs
7969 // suggest it is called "::$DATA".
Bram Moolenaar071d4272004-06-13 20:20:40 +00007970 if (sid.dwStreamNameSize > 0)
7971 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007972 // Read the stream name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007973 if (!BackupRead(sh, (LPBYTE)streamname,
7974 sid.dwStreamNameSize,
7975 &readcount, FALSE, FALSE, &context))
7976 break;
7977
Bram Moolenaar0f873732019-12-05 20:28:46 +01007978 // Copy an info stream with a name ":anything:$DATA".
7979 // Skip "::$DATA", it has no stream name (examples suggest
7980 // it might be used for the normal file contents).
7981 // Note that BackupRead() counts bytes, but the name is in
7982 // wide characters.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007983 len = readcount / sizeof(WCHAR);
7984 streamname[len] = 0;
7985 if (len > 7 && wcsicmp(streamname + len - 6,
7986 L":$DATA") == 0)
7987 {
7988 streamname[len - 6] = 0;
7989 copy_substream(sh, &context, tow, streamname,
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00007990 (long)sid.Size.u.LowPart);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007991 }
7992 }
7993
Bram Moolenaar0f873732019-12-05 20:28:46 +01007994 // Advance to the next stream. We might try seeking too far,
7995 // but BackupSeek() doesn't skip over stream borders, thus
7996 // that's OK.
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00007997 (void)BackupSeek(sh, sid.Size.u.LowPart, sid.Size.u.HighPart,
Bram Moolenaar071d4272004-06-13 20:20:40 +00007998 &lo, &hi, &context);
7999 }
8000
Bram Moolenaar0f873732019-12-05 20:28:46 +01008001 // Clear the context.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008002 (void)BackupRead(sh, NULL, 0, &readcount, TRUE, FALSE, &context);
8003
8004 CloseHandle(sh);
8005 }
8006 }
8007 vim_free(fromw);
8008 vim_free(tow);
8009}
Bram Moolenaar071d4272004-06-13 20:20:40 +00008010
8011/*
Bram Moolenaare7bebc42021-02-01 20:50:37 +01008012 * ntdll.dll definitions
8013 */
8014#define FileEaInformation 7
8015#ifndef STATUS_SUCCESS
8016# define STATUS_SUCCESS ((NTSTATUS) 0x00000000L)
8017#endif
8018
8019typedef struct _FILE_FULL_EA_INFORMATION_ {
8020 ULONG NextEntryOffset;
8021 UCHAR Flags;
8022 UCHAR EaNameLength;
8023 USHORT EaValueLength;
8024 CHAR EaName[1];
8025} FILE_FULL_EA_INFORMATION_, *PFILE_FULL_EA_INFORMATION_;
8026
8027typedef struct _FILE_EA_INFORMATION_ {
8028 ULONG EaSize;
8029} FILE_EA_INFORMATION_, *PFILE_EA_INFORMATION_;
8030
Paul Ollis65745772022-06-05 16:55:54 +01008031#ifndef PROTO
Bram Moolenaare7bebc42021-02-01 20:50:37 +01008032typedef NTSTATUS (NTAPI *PfnNtOpenFile)(
8033 PHANDLE FileHandle,
8034 ACCESS_MASK DesiredAccess,
8035 POBJECT_ATTRIBUTES ObjectAttributes,
8036 PIO_STATUS_BLOCK IoStatusBlock,
8037 ULONG ShareAccess,
8038 ULONG OpenOptions);
8039typedef NTSTATUS (NTAPI *PfnNtClose)(
8040 HANDLE Handle);
8041typedef NTSTATUS (NTAPI *PfnNtSetEaFile)(
Bram Moolenaar9f1983d2022-05-12 20:35:35 +01008042 HANDLE FileHandle,
8043 PIO_STATUS_BLOCK IoStatusBlock,
8044 PVOID Buffer,
8045 ULONG Length);
Bram Moolenaare7bebc42021-02-01 20:50:37 +01008046typedef NTSTATUS (NTAPI *PfnNtQueryEaFile)(
8047 HANDLE FileHandle,
8048 PIO_STATUS_BLOCK IoStatusBlock,
8049 PVOID Buffer,
8050 ULONG Length,
8051 BOOLEAN ReturnSingleEntry,
8052 PVOID EaList,
8053 ULONG EaListLength,
8054 PULONG EaIndex,
8055 BOOLEAN RestartScan);
8056typedef NTSTATUS (NTAPI *PfnNtQueryInformationFile)(
Bram Moolenaar9f1983d2022-05-12 20:35:35 +01008057 HANDLE FileHandle,
8058 PIO_STATUS_BLOCK IoStatusBlock,
8059 PVOID FileInformation,
8060 ULONG Length,
Bram Moolenaare7bebc42021-02-01 20:50:37 +01008061 FILE_INFORMATION_CLASS FileInformationClass);
8062typedef VOID (NTAPI *PfnRtlInitUnicodeString)(
8063 PUNICODE_STRING DestinationString,
8064 PCWSTR SourceString);
8065
8066PfnNtOpenFile pNtOpenFile = NULL;
8067PfnNtClose pNtClose = NULL;
8068PfnNtSetEaFile pNtSetEaFile = NULL;
8069PfnNtQueryEaFile pNtQueryEaFile = NULL;
8070PfnNtQueryInformationFile pNtQueryInformationFile = NULL;
8071PfnRtlInitUnicodeString pRtlInitUnicodeString = NULL;
Paul Ollis65745772022-06-05 16:55:54 +01008072#endif
Bram Moolenaare7bebc42021-02-01 20:50:37 +01008073
8074/*
8075 * Load ntdll.dll functions.
8076 */
8077 static BOOL
8078load_ntdll(void)
8079{
8080 static int loaded = -1;
8081
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00008082 if (loaded != -1)
8083 return (BOOL) loaded;
8084
8085 HMODULE hNtdll = GetModuleHandle("ntdll.dll");
8086 if (hNtdll != NULL)
Bram Moolenaare7bebc42021-02-01 20:50:37 +01008087 {
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00008088 pNtOpenFile = (PfnNtOpenFile) GetProcAddress(hNtdll, "NtOpenFile");
8089 pNtClose = (PfnNtClose) GetProcAddress(hNtdll, "NtClose");
8090 pNtSetEaFile = (PfnNtSetEaFile)
8091 GetProcAddress(hNtdll, "NtSetEaFile");
8092 pNtQueryEaFile = (PfnNtQueryEaFile)
8093 GetProcAddress(hNtdll, "NtQueryEaFile");
8094 pNtQueryInformationFile = (PfnNtQueryInformationFile)
8095 GetProcAddress(hNtdll, "NtQueryInformationFile");
8096 pRtlInitUnicodeString = (PfnRtlInitUnicodeString)
8097 GetProcAddress(hNtdll, "RtlInitUnicodeString");
Bram Moolenaare7bebc42021-02-01 20:50:37 +01008098 }
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00008099 if (pNtOpenFile == NULL
8100 || pNtClose == NULL
8101 || pNtSetEaFile == NULL
8102 || pNtQueryEaFile == NULL
8103 || pNtQueryInformationFile == NULL
8104 || pRtlInitUnicodeString == NULL)
8105 loaded = FALSE;
8106 else
8107 loaded = TRUE;
Bram Moolenaare7bebc42021-02-01 20:50:37 +01008108 return (BOOL) loaded;
8109}
8110
8111/*
8112 * Copy extended attributes (EA) from file "from" to file "to".
8113 */
8114 static void
8115copy_extattr(char_u *from, char_u *to)
8116{
8117 char_u *fromf = NULL;
8118 char_u *tof = NULL;
8119 WCHAR *fromw = NULL;
8120 WCHAR *tow = NULL;
8121 UNICODE_STRING u;
8122 HANDLE h;
8123 OBJECT_ATTRIBUTES oa;
8124 IO_STATUS_BLOCK iosb;
8125 FILE_EA_INFORMATION_ eainfo = {0};
8126 void *ea = NULL;
8127
8128 if (!load_ntdll())
8129 return;
8130
8131 // Convert the file names to the fully qualified object names.
8132 fromf = alloc(STRLEN(from) + 5);
8133 tof = alloc(STRLEN(to) + 5);
8134 if (fromf == NULL || tof == NULL)
8135 goto theend;
8136 STRCPY(fromf, "\\??\\");
8137 STRCAT(fromf, from);
8138 STRCPY(tof, "\\??\\");
8139 STRCAT(tof, to);
8140
8141 // Convert the names to wide characters.
8142 fromw = enc_to_utf16(fromf, NULL);
8143 tow = enc_to_utf16(tof, NULL);
8144 if (fromw == NULL || tow == NULL)
8145 goto theend;
8146
8147 // Get the EA.
8148 pRtlInitUnicodeString(&u, fromw);
8149 InitializeObjectAttributes(&oa, &u, 0, NULL, NULL);
8150 if (pNtOpenFile(&h, FILE_READ_EA, &oa, &iosb, 0,
8151 FILE_NON_DIRECTORY_FILE) != STATUS_SUCCESS)
8152 goto theend;
8153 pNtQueryInformationFile(h, &iosb, &eainfo, sizeof(eainfo),
8154 FileEaInformation);
8155 if (eainfo.EaSize != 0)
8156 {
8157 ea = alloc(eainfo.EaSize);
8158 if (ea != NULL)
8159 {
8160 if (pNtQueryEaFile(h, &iosb, ea, eainfo.EaSize, FALSE,
8161 NULL, 0, NULL, TRUE) != STATUS_SUCCESS)
8162 {
Yegappan Lakshmanan960dcbd2023-03-07 17:45:11 +00008163 VIM_CLEAR(ea);
Bram Moolenaare7bebc42021-02-01 20:50:37 +01008164 }
8165 }
8166 }
8167 pNtClose(h);
8168
8169 // Set the EA.
8170 if (ea != NULL)
8171 {
8172 pRtlInitUnicodeString(&u, tow);
8173 InitializeObjectAttributes(&oa, &u, 0, NULL, NULL);
8174 if (pNtOpenFile(&h, FILE_WRITE_EA, &oa, &iosb, 0,
8175 FILE_NON_DIRECTORY_FILE) != STATUS_SUCCESS)
8176 goto theend;
8177
8178 pNtSetEaFile(h, &iosb, ea, eainfo.EaSize);
8179 pNtClose(h);
8180 }
8181
8182theend:
8183 vim_free(fromf);
8184 vim_free(tof);
8185 vim_free(fromw);
8186 vim_free(tow);
8187 vim_free(ea);
8188}
8189
8190/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00008191 * Copy file attributes from file "from" to file "to".
8192 * For Windows NT and later we copy info streams.
8193 * Always returns zero, errors are ignored.
8194 */
8195 int
8196mch_copy_file_attribute(char_u *from, char_u *to)
8197{
Bram Moolenaar0f873732019-12-05 20:28:46 +01008198 // File streams only work on Windows NT and later.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02008199 copy_infostreams(from, to);
Bram Moolenaare7bebc42021-02-01 20:50:37 +01008200 copy_extattr(from, to);
Bram Moolenaar071d4272004-06-13 20:20:40 +00008201 return 0;
8202}
8203
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008204
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008205/*
K.Takatadc73b4b2021-06-08 18:32:36 +02008206 * The command line arguments in UTF-16
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008207 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00008208static int nArgsW = 0;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008209static LPWSTR *ArglistW = NULL;
8210static int global_argc = 0;
8211static char **global_argv;
8212
Bram Moolenaar0f873732019-12-05 20:28:46 +01008213static int used_file_argc = 0; // last argument in global_argv[] used
8214 // for the argument list.
8215static int *used_file_indexes = NULL; // indexes in global_argv[] for
8216 // command line arguments added to
8217 // the argument list
8218static int used_file_count = 0; // nr of entries in used_file_indexes
8219static int used_file_literal = FALSE; // take file names literally
8220static int used_file_full_path = FALSE; // file name was full path
8221static int used_file_diff_mode = FALSE; // file name was with diff mode
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008222static int used_alist_count = 0;
8223
8224
8225/*
8226 * Get the command line arguments. Unicode version.
8227 * Returns argc. Zero when something fails.
8228 */
8229 int
8230get_cmd_argsW(char ***argvp)
8231{
8232 char **argv = NULL;
8233 int argc = 0;
8234 int i;
8235
Bram Moolenaar14993322014-09-09 12:25:33 +02008236 free_cmd_argsW();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008237 ArglistW = CommandLineToArgvW(GetCommandLineW(), &nArgsW);
8238 if (ArglistW != NULL)
8239 {
8240 argv = malloc((nArgsW + 1) * sizeof(char *));
8241 if (argv != NULL)
8242 {
8243 argc = nArgsW;
8244 argv[argc] = NULL;
8245 for (i = 0; i < argc; ++i)
8246 {
8247 int len;
8248
K.Takatadc73b4b2021-06-08 18:32:36 +02008249 // Convert each Unicode argument to UTF-8.
8250 WideCharToMultiByte_alloc(CP_UTF8, 0,
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00008251 ArglistW[i], (int)wcslen(ArglistW[i]) + 1,
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008252 (LPSTR *)&argv[i], &len, 0, 0);
8253 if (argv[i] == NULL)
8254 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01008255 // Out of memory, clear everything.
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008256 while (i > 0)
8257 free(argv[--i]);
8258 free(argv);
Bram Moolenaar73c61632013-12-07 14:48:10 +01008259 argv = NULL;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008260 argc = 0;
8261 }
8262 }
8263 }
8264 }
8265
8266 global_argc = argc;
8267 global_argv = argv;
8268 if (argc > 0)
Bram Moolenaar14993322014-09-09 12:25:33 +02008269 {
8270 if (used_file_indexes != NULL)
8271 free(used_file_indexes);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008272 used_file_indexes = malloc(argc * sizeof(int));
Bram Moolenaar14993322014-09-09 12:25:33 +02008273 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008274
8275 if (argvp != NULL)
8276 *argvp = argv;
8277 return argc;
8278}
8279
8280 void
8281free_cmd_argsW(void)
8282{
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00008283 if (ArglistW == NULL)
8284 return;
8285
8286 GlobalFree(ArglistW);
8287 ArglistW = NULL;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008288}
8289
8290/*
8291 * Remember "name" is an argument that was added to the argument list.
8292 * This avoids that we have to re-parse the argument list when fix_arg_enc()
8293 * is called.
8294 */
8295 void
Bram Moolenaar910f66f2006-04-05 20:41:53 +00008296used_file_arg(char *name, int literal, int full_path, int diff_mode)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008297{
8298 int i;
8299
8300 if (used_file_indexes == NULL)
8301 return;
8302 for (i = used_file_argc + 1; i < global_argc; ++i)
8303 if (STRCMP(global_argv[i], name) == 0)
8304 {
8305 used_file_argc = i;
8306 used_file_indexes[used_file_count++] = i;
8307 break;
8308 }
8309 used_file_literal = literal;
8310 used_file_full_path = full_path;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00008311 used_file_diff_mode = diff_mode;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008312}
8313
8314/*
8315 * Remember the length of the argument list as it was. If it changes then we
8316 * leave it alone when 'encoding' is set.
8317 */
8318 void
8319set_alist_count(void)
8320{
8321 used_alist_count = GARGCOUNT;
8322}
8323
8324/*
8325 * Fix the encoding of the command line arguments. Invoked when 'encoding'
K.Takatadc73b4b2021-06-08 18:32:36 +02008326 * has been changed while starting up. Use the UTF-16 command line arguments
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008327 * and convert them to 'encoding'.
8328 */
8329 void
8330fix_arg_enc(void)
8331{
8332 int i;
8333 int idx;
8334 char_u *str;
Bram Moolenaar86b68352004-12-27 21:59:20 +00008335 int *fnum_list;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008336
Bram Moolenaar0f873732019-12-05 20:28:46 +01008337 // Safety checks:
8338 // - if argument count differs between the wide and non-wide argument
8339 // list, something must be wrong.
8340 // - the file name arguments must have been located.
8341 // - the length of the argument list wasn't changed by the user.
Bram Moolenaard857f0e2005-06-21 22:37:39 +00008342 if (global_argc != nArgsW
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008343 || ArglistW == NULL
8344 || used_file_indexes == NULL
8345 || used_file_count == 0
8346 || used_alist_count != GARGCOUNT)
8347 return;
8348
Bram Moolenaar0f873732019-12-05 20:28:46 +01008349 // Remember the buffer numbers for the arguments.
Bram Moolenaarc799fe22019-05-28 23:08:19 +02008350 fnum_list = ALLOC_MULT(int, GARGCOUNT);
Bram Moolenaar86b68352004-12-27 21:59:20 +00008351 if (fnum_list == NULL)
Bram Moolenaar0f873732019-12-05 20:28:46 +01008352 return; // out of memory
Bram Moolenaar86b68352004-12-27 21:59:20 +00008353 for (i = 0; i < GARGCOUNT; ++i)
8354 fnum_list[i] = GARGLIST[i].ae_fnum;
8355
Bram Moolenaar0f873732019-12-05 20:28:46 +01008356 // Clear the argument list. Make room for the new arguments.
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008357 alist_clear(&global_alist);
8358 if (ga_grow(&global_alist.al_ga, used_file_count) == FAIL)
Bram Moolenaar0f873732019-12-05 20:28:46 +01008359 return; // out of memory
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008360
8361 for (i = 0; i < used_file_count; ++i)
8362 {
8363 idx = used_file_indexes[i];
Bram Moolenaar36f692d2008-11-20 16:10:17 +00008364 str = utf16_to_enc(ArglistW[idx], NULL);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008365 if (str != NULL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00008366 {
Bram Moolenaar39d21e32017-08-05 23:09:31 +02008367 int literal = used_file_literal;
8368
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01008369#ifdef FEAT_DIFF
Bram Moolenaar0f873732019-12-05 20:28:46 +01008370 // When using diff mode may need to concatenate file name to
8371 // directory name. Just like it's done in main().
Bram Moolenaar910f66f2006-04-05 20:41:53 +00008372 if (used_file_diff_mode && mch_isdir(str) && GARGCOUNT > 0
8373 && !mch_isdir(alist_name(&GARGLIST[0])))
8374 {
8375 char_u *r;
8376
8377 r = concat_fnames(str, gettail(alist_name(&GARGLIST[0])), TRUE);
8378 if (r != NULL)
8379 {
8380 vim_free(str);
8381 str = r;
8382 }
8383 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01008384#endif
Bram Moolenaar0f873732019-12-05 20:28:46 +01008385 // Re-use the old buffer by renaming it. When not using literal
8386 // names it's done by alist_expand() below.
Bram Moolenaar86b68352004-12-27 21:59:20 +00008387 if (used_file_literal)
8388 buf_set_name(fnum_list[i], str);
8389
Bram Moolenaar0f873732019-12-05 20:28:46 +01008390 // Check backtick literal. backtick literal is already expanded in
8391 // main.c, so this part add str as literal.
Bram Moolenaar39d21e32017-08-05 23:09:31 +02008392 if (literal == FALSE)
8393 {
Bram Moolenaar116a0f82017-08-07 21:17:57 +02008394 size_t len = STRLEN(str);
8395
Bram Moolenaar39d21e32017-08-05 23:09:31 +02008396 if (len > 2 && *str == '`' && *(str + len - 1) == '`')
8397 literal = TRUE;
8398 }
8399 alist_add(&global_alist, str, literal ? 2 : 0);
Bram Moolenaar86b68352004-12-27 21:59:20 +00008400 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008401 }
8402
8403 if (!used_file_literal)
8404 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01008405 // Now expand wildcards in the arguments.
8406 // Temporarily add '(' and ')' to 'isfname'. These are valid
8407 // filename characters but are excluded from 'isfname' to make
Dominique Pelleaf4a61a2021-12-27 17:21:41 +00008408 // "gf" work on a file name in parentheses (e.g.: see vim.h).
Bram Moolenaar0f873732019-12-05 20:28:46 +01008409 // Also, unset wildignore to not be influenced by this option.
8410 // The arguments specified in command-line should be kept even if
8411 // encoding options were changed.
Christian Brabandtfd916d62021-11-01 22:44:33 +00008412 // Use :legacy so that it also works when in Vim9 script.
8413 do_cmdline_cmd((char_u *)":legacy let g:SaVe_ISF = &isf|set isf+=(,)");
8414 do_cmdline_cmd((char_u *)":legacy let g:SaVe_WIG = &wig|set wig=");
Bram Moolenaar86b68352004-12-27 21:59:20 +00008415 alist_expand(fnum_list, used_alist_count);
Christian Brabandtfd916d62021-11-01 22:44:33 +00008416 do_cmdline_cmd(
8417 (char_u *)":legacy let &isf = g:SaVe_ISF|unlet g:SaVe_ISF");
8418 do_cmdline_cmd(
8419 (char_u *)":legacy let &wig = g:SaVe_WIG|unlet g:SaVe_WIG");
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008420 }
8421
Bram Moolenaar0f873732019-12-05 20:28:46 +01008422 // If wildcard expansion failed, we are editing the first file of the
8423 // arglist and there is no file name: Edit the first argument now.
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008424 if (curwin->w_arg_idx == 0 && curbuf->b_fname == NULL)
8425 {
8426 do_cmdline_cmd((char_u *)":rewind");
Bram Moolenaar05268152021-11-18 18:53:45 +00008427 if (GARGCOUNT == 1 && used_file_full_path
8428 && vim_chdirfile(alist_name(&GARGLIST[0]), "drop") == OK)
8429 last_chdir_reason = "drop";
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008430 }
Bram Moolenaar86b68352004-12-27 21:59:20 +00008431
8432 set_alist_count();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008433}
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01008434
8435 int
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02008436mch_setenv(char *var, char *value, int x UNUSED)
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01008437{
8438 char_u *envbuf;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02008439 WCHAR *p;
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01008440
Bram Moolenaar964b3742019-05-24 18:54:09 +02008441 envbuf = alloc(STRLEN(var) + STRLEN(value) + 2);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01008442 if (envbuf == NULL)
8443 return -1;
8444
8445 sprintf((char *)envbuf, "%s=%s", var, value);
8446
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02008447 p = enc_to_utf16(envbuf, NULL);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01008448
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02008449 vim_free(envbuf);
8450 if (p == NULL)
8451 return -1;
8452 _wputenv(p);
Bram Moolenaara12a1612019-01-24 16:39:02 +01008453#ifdef libintl_wputenv
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02008454 libintl_wputenv(p);
Bram Moolenaara12a1612019-01-24 16:39:02 +01008455#endif
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02008456 // Unlike Un*x systems, we can free the string for _wputenv().
8457 vim_free(p);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01008458
8459 return 0;
8460}
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008461
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008462/*
8463 * Support for 256 colors and 24-bit colors was added in Windows 10
8464 * version 1703 (Creators update).
8465 */
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008466#define VTP_FIRST_SUPPORT_BUILD MAKE_VER(10, 0, 15063)
8467
8468/*
8469 * Support for pseudo-console (ConPTY) was added in windows 10
Bram Moolenaar57da6982019-09-13 22:30:11 +02008470 * version 1809 (October 2018 update).
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008471 */
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01008472#define CONPTY_FIRST_SUPPORT_BUILD MAKE_VER(10, 0, 17763)
Bram Moolenaar57da6982019-09-13 22:30:11 +02008473
8474/*
8475 * ConPTY differences between versions, need different logic.
8476 * version 1903 (May 2019 update).
8477 */
8478#define CONPTY_1903_BUILD MAKE_VER(10, 0, 18362)
8479
8480/*
Bram Moolenaar36e7a822019-11-13 21:49:24 +01008481 * version 1909 (November 2019 update).
8482 */
8483#define CONPTY_1909_BUILD MAKE_VER(10, 0, 18363)
8484
8485/*
Bram Moolenaar7ed8f592020-04-28 20:44:42 +02008486 * Stay ahead of the next update, and when it's done, fix this.
8487 * version ? (2020 update, temporarily use the build number of insider preview)
8488 */
8489#define CONPTY_NEXT_UPDATE_BUILD MAKE_VER(10, 0, 19587)
8490
8491/*
Bram Moolenaar57da6982019-09-13 22:30:11 +02008492 * Confirm until this version. Also the logic changes.
8493 * insider preview.
8494 */
Bram Moolenaar4c063dd2019-10-04 21:29:12 +02008495#define CONPTY_INSIDER_BUILD MAKE_VER(10, 0, 18995)
Bram Moolenaar57da6982019-09-13 22:30:11 +02008496
8497/*
8498 * Not stable now.
8499 */
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01008500#define CONPTY_STABLE_BUILD MAKE_VER(10, 0, 32767) // T.B.D.
Christopher Plewright1140b512022-11-12 18:46:05 +00008501// Notes:
8502// Win 10 22H2 Final is build 19045, it's conpty is widely used.
8503// Strangely, 19045 is newer but is a lower build number than the 2020 insider
8504// preview which had a build 19587. And, not sure how stable that was?
8505// Win Server 2022 (May 10, 2022) is build 20348, its conpty is widely used.
8506// Win 11 starts from build 22000, even though the major version says 10!
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008507
8508 static void
8509vtp_flag_init(void)
8510{
8511 DWORD ver = get_build_number();
Bram Moolenaarafde13b2019-04-28 19:46:49 +02008512#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008513 DWORD mode;
8514 HANDLE out;
8515
Bram Moolenaarafde13b2019-04-28 19:46:49 +02008516# ifdef VIMDLL
8517 if (!gui.in_use)
8518# endif
8519 {
8520 out = GetStdHandle(STD_OUTPUT_HANDLE);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008521
Bram Moolenaarafde13b2019-04-28 19:46:49 +02008522 vtp_working = (ver >= VTP_FIRST_SUPPORT_BUILD) ? 1 : 0;
8523 GetConsoleMode(out, &mode);
8524 mode |= (ENABLE_PROCESSED_OUTPUT | ENABLE_VIRTUAL_TERMINAL_PROCESSING);
8525 if (SetConsoleMode(out, mode) == 0)
8526 vtp_working = 0;
Christopher Plewrightf75a2cb2023-01-28 10:28:09 +00008527
8528 // VTP uses alternate screen buffer.
8529 // But, not if running in a nested terminal
8530 use_alternate_screen_buffer = win10_22H2_or_later && p_rs && vtp_working
8531 && !mch_getenv("VIM_TERMINAL");
Bram Moolenaarafde13b2019-04-28 19:46:49 +02008532 }
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008533#endif
8534
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008535 if (ver >= CONPTY_FIRST_SUPPORT_BUILD)
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01008536 conpty_working = 1;
8537 if (ver >= CONPTY_STABLE_BUILD)
8538 conpty_stable = 1;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008539
Bram Moolenaar57da6982019-09-13 22:30:11 +02008540 if (ver <= CONPTY_INSIDER_BUILD)
8541 conpty_type = 3;
Bram Moolenaar36e7a822019-11-13 21:49:24 +01008542 if (ver <= CONPTY_1909_BUILD)
8543 conpty_type = 2;
Bram Moolenaar57da6982019-09-13 22:30:11 +02008544 if (ver <= CONPTY_1903_BUILD)
8545 conpty_type = 2;
8546 if (ver < CONPTY_FIRST_SUPPORT_BUILD)
8547 conpty_type = 1;
Bram Moolenaar7ed8f592020-04-28 20:44:42 +02008548
8549 if (ver >= CONPTY_NEXT_UPDATE_BUILD)
8550 conpty_fix_type = 1;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008551}
8552
Bram Moolenaarafde13b2019-04-28 19:46:49 +02008553#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL) || defined(PROTO)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008554
8555 static void
8556vtp_init(void)
8557{
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02008558# ifdef FEAT_TERMGUICOLORS
Christopher Plewrightd343c602023-01-22 18:58:30 +00008559 CONSOLE_SCREEN_BUFFER_INFOEX csbi;
8560 csbi.cbSize = sizeof(csbi);
8561 GetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
8562 save_console_bg_rgb = (guicolor_T)csbi.ColorTable[g_color_index_bg];
8563 save_console_fg_rgb = (guicolor_T)csbi.ColorTable[g_color_index_fg];
8564 store_console_bg_rgb = save_console_bg_rgb;
8565 store_console_fg_rgb = save_console_fg_rgb;
Christopher Plewright38804d62022-11-09 23:55:52 +00008566
Christopher Plewrightd343c602023-01-22 18:58:30 +00008567 COLORREF bg;
8568 bg = (COLORREF)csbi.ColorTable[g_color_index_bg];
8569 bg = (GetRValue(bg) << 16) | (GetGValue(bg) << 8) | GetBValue(bg);
8570 default_console_color_bg = bg;
Christopher Plewright38804d62022-11-09 23:55:52 +00008571
Christopher Plewrightd343c602023-01-22 18:58:30 +00008572 COLORREF fg;
8573 fg = (COLORREF)csbi.ColorTable[g_color_index_fg];
8574 fg = (GetRValue(fg) << 16) | (GetGValue(fg) << 8) | GetBValue(fg);
8575 default_console_color_fg = fg;
Bram Moolenaarc4568ab2018-11-16 16:21:05 +01008576# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008577 set_console_color_rgb();
8578}
8579
8580 static void
8581vtp_exit(void)
8582{
Bram Moolenaardf543822020-01-30 11:53:59 +01008583 restore_console_color_rgb();
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008584}
8585
Bram Moolenaar06b7b582020-05-30 17:49:25 +02008586 int
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008587vtp_printf(
8588 char *format,
8589 ...)
8590{
8591 char_u buf[100];
8592 va_list list;
8593 DWORD result;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008594 int len;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008595
Nir Lichtman6cd2d1d2023-11-11 11:27:41 +01008596 if (silent_mode)
8597 return 0;
8598
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008599 va_start(list, format);
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008600 len = vim_vsnprintf((char *)buf, 100, (char *)format, list);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008601 va_end(list);
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008602 WriteConsoleA(g_hConOut, buf, (DWORD)len, &result, NULL);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008603 return (int)result;
8604}
8605
8606 static void
8607vtp_sgr_bulk(
8608 int arg)
8609{
8610 int args[1];
8611
8612 args[0] = arg;
8613 vtp_sgr_bulks(1, args);
8614}
8615
K.Takata6e1d31e2022-02-03 13:05:32 +00008616# define FAST256(x) \
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008617 if ((*p-- = "0123456789"[(n = x % 10)]) \
8618 && x >= 10 && (*p-- = "0123456789"[((m = x % 100) - n) / 10]) \
8619 && x >= 100 && (*p-- = "012"[((x & 0xff) - m) / 100]));
8620
K.Takata6e1d31e2022-02-03 13:05:32 +00008621# define FAST256CASE(x) \
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008622 case x: \
8623 FAST256(newargs[x - 1]);
8624
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008625 static void
8626vtp_sgr_bulks(
8627 int argc,
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008628 int *args)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008629{
K.Takata6e1d31e2022-02-03 13:05:32 +00008630# define MAXSGR 16
8631# define SGRBUFSIZE 2 + 4 * MAXSGR + 1 // '\033[' + SGR + 'm'
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008632 char_u buf[SGRBUFSIZE];
8633 char_u *p;
8634 int in, out;
8635 int newargs[16];
8636 static int sgrfgr = -1, sgrfgg, sgrfgb;
8637 static int sgrbgr = -1, sgrbgg, sgrbgb;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008638
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008639 if (argc == 0)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008640 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008641 sgrfgr = sgrbgr = -1;
K.Takatadf5320c2022-09-01 13:20:16 +01008642 vtp_printf("\033[m");
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008643 return;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008644 }
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008645
8646 in = out = 0;
8647 while (in < argc)
8648 {
8649 int s = args[in];
8650 int copylen = 1;
8651
8652 if (s == 38)
8653 {
8654 if (argc - in >= 5 && args[in + 1] == 2)
8655 {
8656 if (sgrfgr == args[in + 2] && sgrfgg == args[in + 3]
8657 && sgrfgb == args[in + 4])
8658 {
8659 in += 5;
8660 copylen = 0;
8661 }
8662 else
8663 {
8664 sgrfgr = args[in + 2];
8665 sgrfgg = args[in + 3];
8666 sgrfgb = args[in + 4];
8667 copylen = 5;
8668 }
8669 }
8670 else if (argc - in >= 3 && args[in + 1] == 5)
8671 {
8672 sgrfgr = -1;
8673 copylen = 3;
8674 }
8675 }
8676 else if (s == 48)
8677 {
8678 if (argc - in >= 5 && args[in + 1] == 2)
8679 {
8680 if (sgrbgr == args[in + 2] && sgrbgg == args[in + 3]
8681 && sgrbgb == args[in + 4])
8682 {
8683 in += 5;
8684 copylen = 0;
8685 }
8686 else
8687 {
8688 sgrbgr = args[in + 2];
8689 sgrbgg = args[in + 3];
8690 sgrbgb = args[in + 4];
8691 copylen = 5;
8692 }
8693 }
8694 else if (argc - in >= 3 && args[in + 1] == 5)
8695 {
8696 sgrbgr = -1;
8697 copylen = 3;
8698 }
8699 }
8700 else if (30 <= s && s <= 39)
8701 sgrfgr = -1;
8702 else if (90 <= s && s <= 97)
8703 sgrfgr = -1;
8704 else if (40 <= s && s <= 49)
8705 sgrbgr = -1;
8706 else if (100 <= s && s <= 107)
8707 sgrbgr = -1;
8708 else if (s == 0)
8709 sgrfgr = sgrbgr = -1;
8710
8711 while (copylen--)
8712 newargs[out++] = args[in++];
8713 }
8714
8715 p = &buf[sizeof(buf) - 1];
8716 *p-- = 'm';
8717
8718 switch (out)
8719 {
8720 int n, m;
8721 DWORD r;
8722
8723 FAST256CASE(16);
8724 *p-- = ';';
8725 FAST256CASE(15);
8726 *p-- = ';';
8727 FAST256CASE(14);
8728 *p-- = ';';
8729 FAST256CASE(13);
8730 *p-- = ';';
8731 FAST256CASE(12);
8732 *p-- = ';';
8733 FAST256CASE(11);
8734 *p-- = ';';
8735 FAST256CASE(10);
8736 *p-- = ';';
8737 FAST256CASE(9);
8738 *p-- = ';';
8739 FAST256CASE(8);
8740 *p-- = ';';
8741 FAST256CASE(7);
8742 *p-- = ';';
8743 FAST256CASE(6);
8744 *p-- = ';';
8745 FAST256CASE(5);
8746 *p-- = ';';
8747 FAST256CASE(4);
8748 *p-- = ';';
8749 FAST256CASE(3);
8750 *p-- = ';';
8751 FAST256CASE(2);
8752 *p-- = ';';
8753 FAST256CASE(1);
8754 *p-- = '[';
8755 *p = '\033';
8756 WriteConsoleA(g_hConOut, p, (DWORD)(&buf[SGRBUFSIZE] - p), &r, NULL);
8757 default:
8758 break;
8759 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008760}
8761
Bram Moolenaar06b7b582020-05-30 17:49:25 +02008762 static void
8763wt_init(void)
8764{
Christopher Plewright1140b512022-11-12 18:46:05 +00008765 wt_working = mch_getenv("WT_SESSION") != NULL;
Bram Moolenaar06b7b582020-05-30 17:49:25 +02008766}
8767
Bram Moolenaar8a938af2018-05-01 17:30:41 +02008768# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02008769 static int
8770ctermtoxterm(
8771 int cterm)
8772{
Bram Moolenaar9894e392018-05-05 14:29:06 +02008773 char_u r, g, b, idx;
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02008774
8775 cterm_color2rgb(cterm, &r, &g, &b, &idx);
8776 return (((int)r << 16) | ((int)g << 8) | (int)b);
8777}
Bram Moolenaar8a938af2018-05-01 17:30:41 +02008778# endif
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02008779
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008780 static void
8781set_console_color_rgb(void)
8782{
8783# ifdef FEAT_TERMGUICOLORS
K.Takata27b53be2022-09-18 12:25:49 +01008784 CONSOLE_SCREEN_BUFFER_INFOEX csbi;
Bram Moolenaara050b942019-12-02 21:35:31 +01008785 guicolor_T fg, bg;
8786 int ctermfg, ctermbg;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008787
Christopher Plewright38804d62022-11-09 23:55:52 +00008788 if (!vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008789 return;
8790
Bram Moolenaara050b942019-12-02 21:35:31 +01008791 get_default_console_color(&ctermfg, &ctermbg, &fg, &bg);
8792
Christopher Plewright38804d62022-11-09 23:55:52 +00008793 if (p_tgc || t_colors >= 256)
Bram Moolenaar06b7b582020-05-30 17:49:25 +02008794 {
8795 term_fg_rgb_color(fg);
8796 term_bg_rgb_color(bg);
8797 return;
8798 }
8799
Christopher Plewrightf75a2cb2023-01-28 10:28:09 +00008800 if (use_alternate_screen_buffer)
8801 return;
8802
Christopher Plewrightd343c602023-01-22 18:58:30 +00008803 fg = (GetRValue(fg) << 16) | (GetGValue(fg) << 8) | GetBValue(fg);
8804 bg = (GetRValue(bg) << 16) | (GetGValue(bg) << 8) | GetBValue(bg);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008805
Christopher Plewrightd343c602023-01-22 18:58:30 +00008806 csbi.cbSize = sizeof(csbi);
8807 GetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008808
Christopher Plewrightd343c602023-01-22 18:58:30 +00008809 csbi.cbSize = sizeof(csbi);
8810 csbi.srWindow.Right += 1;
8811 csbi.srWindow.Bottom += 1;
8812 store_console_bg_rgb = csbi.ColorTable[g_color_index_bg];
8813 store_console_fg_rgb = csbi.ColorTable[g_color_index_fg];
8814 csbi.ColorTable[g_color_index_bg] = (COLORREF)bg;
8815 csbi.ColorTable[g_color_index_fg] = (COLORREF)fg;
8816 SetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008817# endif
8818}
8819
Bram Moolenaara050b942019-12-02 21:35:31 +01008820# if defined(FEAT_TERMGUICOLORS) || defined(PROTO)
8821 void
8822get_default_console_color(
8823 int *cterm_fg,
8824 int *cterm_bg,
8825 guicolor_T *gui_fg,
8826 guicolor_T *gui_bg)
8827{
8828 int id;
8829 guicolor_T guifg = INVALCOLOR;
8830 guicolor_T guibg = INVALCOLOR;
8831 int ctermfg = 0;
8832 int ctermbg = 0;
Christopher Plewright38804d62022-11-09 23:55:52 +00008833 int dummynull = 0;
Bram Moolenaara050b942019-12-02 21:35:31 +01008834
8835 id = syn_name2id((char_u *)"Normal");
8836 if (id > 0 && p_tgc)
8837 syn_id2colors(id, &guifg, &guibg);
8838 if (guifg == INVALCOLOR)
8839 {
8840 ctermfg = -1;
8841 if (id > 0)
Christopher Plewright38804d62022-11-09 23:55:52 +00008842 syn_id2cterm_bg(id, &ctermfg, &dummynull);
Christopher Plewrightd343c602023-01-22 18:58:30 +00008843 if (ctermfg != -1)
8844 guifg = ctermtoxterm(ctermfg);
Christopher Plewright38804d62022-11-09 23:55:52 +00008845 else
Christopher Plewrightd343c602023-01-22 18:58:30 +00008846 guifg = USE_WT ? INVALCOLOR : default_console_color_fg;
8847 cterm_normal_fg_gui_color = guifg;
8848 ctermfg = ctermfg < 0 ? 0 : ctermfg;
Bram Moolenaara050b942019-12-02 21:35:31 +01008849 }
8850 if (guibg == INVALCOLOR)
8851 {
8852 ctermbg = -1;
8853 if (id > 0)
Christopher Plewright38804d62022-11-09 23:55:52 +00008854 syn_id2cterm_bg(id, &dummynull, &ctermbg);
Christopher Plewrightd343c602023-01-22 18:58:30 +00008855 if (ctermbg != -1)
8856 guibg = ctermtoxterm(ctermbg);
K.Takatae53a0d42022-09-05 21:45:11 +01008857 else
Christopher Plewrightd343c602023-01-22 18:58:30 +00008858 guibg = USE_WT ? INVALCOLOR : default_console_color_bg;
8859 cterm_normal_bg_gui_color = guibg;
8860 ctermbg = ctermbg < 0 ? 0 : ctermbg;
Bram Moolenaara050b942019-12-02 21:35:31 +01008861 }
8862
8863 *cterm_fg = ctermfg;
8864 *cterm_bg = ctermbg;
8865 *gui_fg = guifg;
8866 *gui_bg = guibg;
8867}
8868# endif
8869
Bram Moolenaardf543822020-01-30 11:53:59 +01008870/*
8871 * Set the console colors to the original colors or the last set colors.
8872 */
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008873 static void
8874reset_console_color_rgb(void)
8875{
8876# ifdef FEAT_TERMGUICOLORS
Christopher Plewrightf75a2cb2023-01-28 10:28:09 +00008877 if (use_alternate_screen_buffer)
8878 return;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008879
Christopher Plewright38804d62022-11-09 23:55:52 +00008880 CONSOLE_SCREEN_BUFFER_INFOEX csbi;
8881
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008882 csbi.cbSize = sizeof(csbi);
K.Takata27b53be2022-09-18 12:25:49 +01008883 GetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008884
8885 csbi.cbSize = sizeof(csbi);
8886 csbi.srWindow.Right += 1;
8887 csbi.srWindow.Bottom += 1;
Bram Moolenaardf543822020-01-30 11:53:59 +01008888 csbi.ColorTable[g_color_index_bg] = (COLORREF)store_console_bg_rgb;
8889 csbi.ColorTable[g_color_index_fg] = (COLORREF)store_console_fg_rgb;
K.Takata27b53be2022-09-18 12:25:49 +01008890 SetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaardf543822020-01-30 11:53:59 +01008891# endif
8892}
8893
8894/*
8895 * Set the console colors to the original colors.
8896 */
8897 static void
8898restore_console_color_rgb(void)
8899{
8900# ifdef FEAT_TERMGUICOLORS
Christopher Plewrightf75a2cb2023-01-28 10:28:09 +00008901 if (use_alternate_screen_buffer)
8902 return;
Christopher Plewright38804d62022-11-09 23:55:52 +00008903
K.Takata27b53be2022-09-18 12:25:49 +01008904 CONSOLE_SCREEN_BUFFER_INFOEX csbi;
Bram Moolenaardf543822020-01-30 11:53:59 +01008905
8906 csbi.cbSize = sizeof(csbi);
K.Takata27b53be2022-09-18 12:25:49 +01008907 GetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaardf543822020-01-30 11:53:59 +01008908
8909 csbi.cbSize = sizeof(csbi);
8910 csbi.srWindow.Right += 1;
8911 csbi.srWindow.Bottom += 1;
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02008912 csbi.ColorTable[g_color_index_bg] = (COLORREF)save_console_bg_rgb;
8913 csbi.ColorTable[g_color_index_fg] = (COLORREF)save_console_fg_rgb;
K.Takata27b53be2022-09-18 12:25:49 +01008914 SetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008915# endif
8916}
8917
8918 void
8919control_console_color_rgb(void)
8920{
Christopher Plewright38804d62022-11-09 23:55:52 +00008921 if (vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008922 set_console_color_rgb();
8923 else
8924 reset_console_color_rgb();
8925}
8926
8927 int
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008928use_vtp(void)
8929{
8930 return USE_VTP;
8931}
8932
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02008933 int
8934is_term_win32(void)
8935{
8936 return T_NAME != NULL && STRCMP(T_NAME, "win32") == 0;
8937}
8938
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008939 int
8940has_vtp_working(void)
8941{
8942 return vtp_working;
8943}
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01008944
Bram Moolenaar6902c0e2019-02-16 14:07:37 +01008945#endif
8946
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01008947 int
8948has_conpty_working(void)
8949{
8950 return conpty_working;
8951}
8952
8953 int
Bram Moolenaar57da6982019-09-13 22:30:11 +02008954get_conpty_type(void)
8955{
8956 return conpty_type;
8957}
8958
8959 int
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01008960is_conpty_stable(void)
8961{
8962 return conpty_stable;
8963}
Bram Moolenaar78d21da2019-02-17 15:00:52 +01008964
Bram Moolenaar7ed8f592020-04-28 20:44:42 +02008965 int
8966get_conpty_fix_type(void)
8967{
8968 return conpty_fix_type;
8969}
8970
Bram Moolenaarafde13b2019-04-28 19:46:49 +02008971#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL) || defined(PROTO)
Bram Moolenaar78d21da2019-02-17 15:00:52 +01008972 void
8973resize_console_buf(void)
8974{
Christopher Plewrightf75a2cb2023-01-28 10:28:09 +00008975 if (use_alternate_screen_buffer)
8976 return;
8977
Bram Moolenaar78d21da2019-02-17 15:00:52 +01008978 CONSOLE_SCREEN_BUFFER_INFO csbi;
8979 COORD coord;
8980 SMALL_RECT newsize;
8981
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00008982 if (!GetConsoleScreenBufferInfo(g_hConOut, &csbi))
8983 return;
Bram Moolenaar78d21da2019-02-17 15:00:52 +01008984
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00008985 coord.X = SRWIDTH(csbi.srWindow);
8986 coord.Y = SRHEIGHT(csbi.srWindow);
8987 SetConsoleScreenBufferSize(g_hConOut, coord);
Bram Moolenaar78d21da2019-02-17 15:00:52 +01008988
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00008989 newsize.Left = 0;
8990 newsize.Top = 0;
8991 newsize.Right = coord.X - 1;
8992 newsize.Bottom = coord.Y - 1;
8993 SetConsoleWindowInfo(g_hConOut, TRUE, &newsize);
8994
8995 SetConsoleScreenBufferSize(g_hConOut, coord);
Bram Moolenaar78d21da2019-02-17 15:00:52 +01008996}
8997#endif
Martin Tournoij1a3e5742021-07-24 13:57:29 +02008998
8999 char *
9000GetWin32Error(void)
9001{
K.Takatad68b2fc2022-02-12 11:18:37 +00009002 static char *oldmsg = NULL;
Martin Tournoij1a3e5742021-07-24 13:57:29 +02009003 char *msg = NULL;
K.Takatad68b2fc2022-02-12 11:18:37 +00009004
Martin Tournoij1a3e5742021-07-24 13:57:29 +02009005 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER|FORMAT_MESSAGE_FROM_SYSTEM,
9006 NULL, GetLastError(), 0, (LPSTR)&msg, 0, NULL);
K.Takatad68b2fc2022-02-12 11:18:37 +00009007 if (oldmsg != NULL)
9008 LocalFree(oldmsg);
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00009009 if (msg == NULL)
9010 return NULL;
9011
9012 // remove trailing \r\n
9013 char *pcrlf = strstr(msg, "\r\n");
9014 if (pcrlf != NULL)
9015 *pcrlf = '\0';
9016 oldmsg = msg;
Martin Tournoij1a3e5742021-07-24 13:57:29 +02009017 return msg;
9018}
Paul Ollis65745772022-06-05 16:55:54 +01009019
9020#if defined(FEAT_RELTIME) || defined(PROTO)
9021static HANDLE timer_handle;
9022static int timer_active = FALSE;
9023
9024/*
9025 * Calls to start_timeout alternate the return value pointer between the two
9026 * entries in timeout_flags. If the previously active timeout is very close to
9027 * expiring when start_timeout() is called then a race condition means that the
9028 * set_flag() function may still be invoked after the previous timer is
9029 * deleted. Ping-ponging between the two flags prevents this causing 'fake'
9030 * timeouts.
9031 */
Bram Moolenaar155f2d12022-06-20 13:38:33 +01009032static sig_atomic_t timeout_flags[2];
9033static int timeout_flag_idx = 0;
9034static sig_atomic_t *timeout_flag = &timeout_flags[0];
Paul Ollis65745772022-06-05 16:55:54 +01009035
9036
9037 static void CALLBACK
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +01009038set_flag(void *param, BOOLEAN unused2 UNUSED)
Paul Ollis65745772022-06-05 16:55:54 +01009039{
9040 int *timeout_flag = (int *)param;
9041
9042 *timeout_flag = TRUE;
9043}
9044
9045/*
9046 * Stop any active timeout.
9047 */
9048 void
9049stop_timeout(void)
9050{
9051 if (timer_active)
9052 {
Christopher Plewright2a46f812022-10-16 19:47:45 +01009053 BOOL ret = DeleteTimerQueueTimer(NULL, timer_handle, NULL);
Paul Ollis65745772022-06-05 16:55:54 +01009054 timer_active = FALSE;
9055 if (!ret && GetLastError() != ERROR_IO_PENDING)
9056 {
9057 semsg(_(e_could_not_clear_timeout_str), GetWin32Error());
9058 }
9059 }
9060 *timeout_flag = FALSE;
9061}
9062
9063/*
9064 * Start the timeout timer.
9065 *
9066 * The period is defined in milliseconds.
9067 *
9068 * The return value is a pointer to a flag that is initialised to 0. If the
9069 * timeout expires, the flag is set to 1. This will only return pointers to
9070 * static memory; i.e. any pointer returned by this function may always be
9071 * safely dereferenced.
9072 *
9073 * This function is not expected to fail, but if it does it still returns a
9074 * valid flag pointer; the flag will remain stuck at zero.
9075 */
Bram Moolenaar155f2d12022-06-20 13:38:33 +01009076 volatile sig_atomic_t *
Paul Ollis65745772022-06-05 16:55:54 +01009077start_timeout(long msec)
9078{
Paul Ollis65745772022-06-05 16:55:54 +01009079 BOOL ret;
9080
Bram Moolenaar1f30caf2022-06-19 14:36:35 +01009081 timeout_flag = &timeout_flags[timeout_flag_idx];
Paul Ollis65745772022-06-05 16:55:54 +01009082
9083 stop_timeout();
9084 ret = CreateTimerQueueTimer(
9085 &timer_handle, NULL, set_flag, timeout_flag,
9086 (DWORD)msec, 0, WT_EXECUTEDEFAULT);
9087 if (!ret)
9088 {
9089 semsg(_(e_could_not_set_timeout_str), GetWin32Error());
9090 }
9091 else
9092 {
Bram Moolenaar1f30caf2022-06-19 14:36:35 +01009093 timeout_flag_idx = (timeout_flag_idx + 1) % 2;
Paul Ollis65745772022-06-05 16:55:54 +01009094 timer_active = TRUE;
9095 *timeout_flag = FALSE;
9096 }
9097 return timeout_flag;
9098}
9099#endif