blob: 9947150cdfba98b6717886449a01f895a684f55c [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;
GuyBrush52ecc762024-02-21 20:16:38 +01005158 if (((options &
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005159 (SHELL_READ|SHELL_WRITE|SHELL_COOKED))
5160 != (SHELL_READ|SHELL_WRITE|SHELL_COOKED)
5161# ifdef FEAT_GUI
5162 || gui.in_use
5163# endif
5164 )
5165 && (ta_len > 0 || noread_cnt > 4))
5166 {
5167 if (ta_len == 0)
5168 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005169 // Get extra characters when we don't have any. Reset the
5170 // counter and timer.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005171 noread_cnt = 0;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005172 len = ui_inchar(ta_buf, BUFLEN, 10L, 0);
5173 }
5174 if (ta_len > 0 || len > 0)
5175 {
5176 /*
5177 * For pipes: Check for CTRL-C: send interrupt signal to
GuyBrush1f13fcc2024-01-14 20:08:40 +01005178 * child.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005179 */
5180 if (len == 1 && cmd != NULL)
5181 {
5182 if (ta_buf[ta_len] == Ctrl_C)
5183 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005184 // Learn what exit code is expected, for
5185 // now put 9 as SIGKILL
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005186 TerminateProcess(pi.hProcess, 9);
5187 }
GuyBrush1f13fcc2024-01-14 20:08:40 +01005188 }
5189
5190 /*
5191 * Check for CTRL-D: EOF, close pipe to child.
5192 * Ctrl_D may be decorated by _OnChar()
5193 */
5194 if ((len == 1 || len == 4 ) && cmd != NULL)
5195 {
5196 if (ta_buf[0] == Ctrl_D
5197 || (ta_buf[0] == CSI
5198 && ta_buf[1] == KS_MODIFIER
5199 && ta_buf[3] == Ctrl_D))
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005200 {
5201 CloseHandle(g_hChildStd_IN_Wr);
5202 g_hChildStd_IN_Wr = NULL;
GuyBrush1f13fcc2024-01-14 20:08:40 +01005203 len = 0;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005204 }
5205 }
5206
Bram Moolenaar2f7e1b82022-10-04 13:17:31 +01005207 len = term_replace_keycodes(ta_buf, ta_len, len);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005208
5209 /*
5210 * For pipes: echo the typed characters. For a pty this
5211 * does not seem to work.
5212 */
5213 for (i = ta_len; i < ta_len + len; ++i)
5214 {
5215 if (ta_buf[i] == '\n' || ta_buf[i] == '\b')
5216 msg_putchar(ta_buf[i]);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005217 else if (has_mbyte)
5218 {
5219 int l = (*mb_ptr2len)(ta_buf + i);
5220
5221 msg_outtrans_len(ta_buf + i, l);
5222 i += l - 1;
5223 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005224 else
5225 msg_outtrans_len(ta_buf + i, 1);
5226 }
5227 windgoto(msg_row, msg_col);
5228 out_flush();
5229
5230 ta_len += len;
5231
5232 /*
5233 * Write the characters to the child, unless EOF has been
5234 * typed for pipes. Write one character at a time, to
5235 * avoid losing too much typeahead. When writing buffer
5236 * lines, drop the typed characters (only check for
5237 * CTRL-C).
5238 */
5239 if (options & SHELL_WRITE)
5240 ta_len = 0;
5241 else if (g_hChildStd_IN_Wr != NULL)
5242 {
5243 WriteFile(g_hChildStd_IN_Wr, (char*)ta_buf,
5244 1, &len, NULL);
5245 // if we are typing in, we want to keep things reactive
5246 delay = 1;
5247 if (len > 0)
5248 {
5249 ta_len -= len;
5250 mch_memmove(ta_buf, ta_buf + len, ta_len);
5251 }
5252 }
5253 }
5254 }
5255 }
5256
5257 if (ta_len)
5258 ui_inchar_undo(ta_buf, ta_len);
5259
5260 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
5261 {
Bram Moolenaar2eba1822011-08-27 15:10:04 +02005262 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005263 break;
5264 }
5265
5266 ++noread_cnt;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02005267 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005268
Bram Moolenaar0f873732019-12-05 20:28:46 +01005269 // We start waiting for a very short time and then increase it, so
5270 // that we respond quickly when the process is quick, and don't
5271 // consume too much overhead when it's slow.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005272 if (delay < 50)
5273 delay += 10;
5274 }
5275
Bram Moolenaar0f873732019-12-05 20:28:46 +01005276 // Close the pipe
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005277 CloseHandle(g_hChildStd_OUT_Rd);
5278 if (g_hChildStd_IN_Wr != NULL)
5279 CloseHandle(g_hChildStd_IN_Wr);
5280
5281 WaitForSingleObject(pi.hProcess, INFINITE);
5282
Bram Moolenaar0f873732019-12-05 20:28:46 +01005283 // Get the command exit code
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005284 GetExitCodeProcess(pi.hProcess, &ret);
5285
5286 if (options & SHELL_READ)
5287 {
5288 if (ga.ga_len > 0)
5289 {
5290 append_ga_line(&ga);
Bram Moolenaar0f873732019-12-05 20:28:46 +01005291 // remember that the NL was missing
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005292 curbuf->b_no_eol_lnum = curwin->w_cursor.lnum;
5293 }
5294 else
5295 curbuf->b_no_eol_lnum = 0;
5296 ga_clear(&ga);
5297 }
5298
Bram Moolenaar0f873732019-12-05 20:28:46 +01005299 // Close the handles to the subprocess, so that it goes away
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005300 CloseHandle(pi.hThread);
5301 CloseHandle(pi.hProcess);
5302
5303 return ret;
5304}
5305
5306 static int
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005307mch_system_g(char *cmd, int options)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005308{
Bram Moolenaar0f873732019-12-05 20:28:46 +01005309 // if we can pipe and the shelltemp option is off
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005310 if (!p_stmp)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005311 return mch_system_piped(cmd, options);
5312 else
5313 return mch_system_classic(cmd, options);
5314}
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005315#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005316
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005317#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01005318 static int
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02005319mch_system_c(char *cmd, int options UNUSED)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01005320{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005321 int ret;
5322 WCHAR *wcmd;
Bram Moolenaar2efc44b2019-10-05 12:09:32 +02005323 char_u *buf;
5324 size_t len;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005325
Bram Moolenaar2efc44b2019-10-05 12:09:32 +02005326 // If the command starts and ends with double quotes, enclose the command
5327 // in parentheses.
5328 len = STRLEN(cmd);
5329 if (len >= 2 && cmd[0] == '"' && cmd[len - 1] == '"')
5330 {
5331 len += 3;
5332 buf = alloc(len);
5333 if (buf == NULL)
5334 return -1;
5335 vim_snprintf((char *)buf, len, "(%s)", cmd);
5336 wcmd = enc_to_utf16(buf, NULL);
5337 free(buf);
5338 }
5339 else
5340 wcmd = enc_to_utf16((char_u *)cmd, NULL);
5341
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005342 if (wcmd == NULL)
5343 return -1;
5344
5345 ret = _wsystem(wcmd);
5346 vim_free(wcmd);
5347 return ret;
Bram Moolenaar910cffb2013-12-11 17:58:35 +01005348}
Bram Moolenaar071d4272004-06-13 20:20:40 +00005349
5350#endif
5351
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005352 static int
5353mch_system(char *cmd, int options)
5354{
5355#ifdef VIMDLL
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02005356 if (gui.in_use || gui.starting)
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005357 return mch_system_g(cmd, options);
5358 else
5359 return mch_system_c(cmd, options);
5360#elif defined(FEAT_GUI_MSWIN)
5361 return mch_system_g(cmd, options);
5362#else
5363 return mch_system_c(cmd, options);
5364#endif
5365}
5366
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005367#if defined(FEAT_GUI) && defined(FEAT_TERMINAL)
5368/*
5369 * Use a terminal window to run a shell command in.
5370 */
5371 static int
5372mch_call_shell_terminal(
5373 char_u *cmd,
Bram Moolenaar0f873732019-12-05 20:28:46 +01005374 int options UNUSED) // SHELL_*, see vim.h
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005375{
5376 jobopt_T opt;
5377 char_u *newcmd = NULL;
5378 typval_T argvar[2];
5379 long_u cmdlen;
5380 int retval = -1;
5381 buf_T *buf;
Bram Moolenaarf9c38832018-06-19 19:59:20 +02005382 job_T *job;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005383 aco_save_T aco;
Bram Moolenaar0f873732019-12-05 20:28:46 +01005384 oparg_T oa; // operator arguments
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005385
Bram Moolenaar42f652f2018-03-19 21:44:37 +01005386 if (cmd == NULL)
5387 cmdlen = STRLEN(p_sh) + 1;
5388 else
5389 cmdlen = STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10;
Bram Moolenaar18a4ba22019-05-24 19:39:03 +02005390 newcmd = alloc(cmdlen);
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005391 if (newcmd == NULL)
5392 return 255;
Bram Moolenaar42f652f2018-03-19 21:44:37 +01005393 if (cmd == NULL)
5394 {
5395 STRCPY(newcmd, p_sh);
5396 ch_log(NULL, "starting terminal to run a shell");
5397 }
5398 else
5399 {
5400 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s", p_sh, p_shcf, cmd);
5401 ch_log(NULL, "starting terminal for system command '%s'", cmd);
5402 }
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005403
5404 init_job_options(&opt);
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005405
5406 argvar[0].v_type = VAR_STRING;
5407 argvar[0].vval.v_string = newcmd;
5408 argvar[1].v_type = VAR_UNKNOWN;
5409 buf = term_start(argvar, NULL, &opt, TERM_START_SYSTEM);
Bram Moolenaar81c3c89a2018-03-20 11:41:44 +01005410 if (buf == NULL)
Bram Moolenaar9029b912019-03-21 19:58:00 +01005411 {
5412 vim_free(newcmd);
Bram Moolenaar81c3c89a2018-03-20 11:41:44 +01005413 return 255;
Bram Moolenaar9029b912019-03-21 19:58:00 +01005414 }
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005415
Bram Moolenaarf9c38832018-06-19 19:59:20 +02005416 job = term_getjob(buf->b_term);
5417 ++job->jv_refcount;
5418
Bram Moolenaar0f873732019-12-05 20:28:46 +01005419 // Find a window to make "buf" curbuf.
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005420 aucmd_prepbuf(&aco, buf);
Bram Moolenaare76062c2022-11-28 18:51:43 +00005421 if (curbuf == buf)
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005422 {
Bram Moolenaare76062c2022-11-28 18:51:43 +00005423 // Only do this when a window was found for "buf".
5424 clear_oparg(&oa);
5425 while (term_use_loop())
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005426 {
Bram Moolenaare76062c2022-11-28 18:51:43 +00005427 if (oa.op_type == OP_NOP && oa.regname == NUL && !VIsual_active)
5428 {
5429 // If terminal_loop() returns OK we got a key that is handled
5430 // in Normal model. We don't do redrawing anyway.
5431 if (terminal_loop(TRUE) == OK)
5432 normal_cmd(&oa, TRUE);
5433 }
5434 else
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005435 normal_cmd(&oa, TRUE);
5436 }
Bram Moolenaare76062c2022-11-28 18:51:43 +00005437 retval = job->jv_exitval;
5438 ch_log(NULL, "system command finished");
5439
5440 job_unref(job);
5441
5442 // restore curwin/curbuf and a few other things
5443 aucmd_restbuf(&aco);
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005444 }
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005445
5446 wait_return(TRUE);
5447 do_buffer(DOBUF_WIPE, DOBUF_FIRST, FORWARD, buf->b_fnum, TRUE);
5448
5449 vim_free(newcmd);
5450 return retval;
5451}
5452#endif
5453
Bram Moolenaar071d4272004-06-13 20:20:40 +00005454/*
5455 * Either execute a command by calling the shell or start a new shell
5456 */
5457 int
5458mch_call_shell(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005459 char_u *cmd,
Bram Moolenaar0f873732019-12-05 20:28:46 +01005460 int options) // SHELL_*, see vim.h
Bram Moolenaar071d4272004-06-13 20:20:40 +00005461{
5462 int x = 0;
5463 int tmode = cur_tmode;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005464 WCHAR szShellTitle[512];
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02005465
Bram Moolenaar4c5678f2022-11-30 18:12:19 +00005466#ifdef FEAT_EVAL
Bram Moolenaarc9a9a0a2022-04-12 15:09:23 +01005467 ch_log(NULL, "executing shell command: %s", cmd);
5468#endif
Bram Moolenaar0f873732019-12-05 20:28:46 +01005469 // Change the title to reflect that we are in a subshell.
K.Takataeeec2542021-06-02 13:28:16 +02005470 if (GetConsoleTitleW(szShellTitle, ARRAY_LENGTH(szShellTitle) - 4) > 0)
Bram Moolenaar1df52d72014-10-15 22:50:10 +02005471 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005472 if (cmd == NULL)
5473 wcscat(szShellTitle, L" :sh");
5474 else
Bram Moolenaar1df52d72014-10-15 22:50:10 +02005475 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005476 WCHAR *wn = enc_to_utf16((char_u *)cmd, NULL);
Bram Moolenaar1df52d72014-10-15 22:50:10 +02005477
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005478 if (wn != NULL)
5479 {
5480 wcscat(szShellTitle, L" - !");
5481 if ((wcslen(szShellTitle) + wcslen(wn) <
K.Takataeeec2542021-06-02 13:28:16 +02005482 ARRAY_LENGTH(szShellTitle)))
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005483 wcscat(szShellTitle, wn);
5484 SetConsoleTitleW(szShellTitle);
5485 vim_free(wn);
Bram Moolenaar1df52d72014-10-15 22:50:10 +02005486 }
5487 }
5488 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005489
5490 out_flush();
5491
5492#ifdef MCH_WRITE_DUMP
5493 if (fdDump)
5494 {
5495 fprintf(fdDump, "mch_call_shell(\"%s\", %d)\n", cmd, options);
5496 fflush(fdDump);
5497 }
5498#endif
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005499#if defined(FEAT_GUI) && defined(FEAT_TERMINAL)
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02005500 // TODO: make the terminal window work with input or output redirected.
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005501 if (
5502# ifdef VIMDLL
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02005503 gui.in_use &&
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005504# endif
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02005505 vim_strchr(p_go, GO_TERMINAL) != NULL
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005506 && (options & (SHELL_FILTER|SHELL_DOOUT|SHELL_WRITE|SHELL_READ)) == 0)
5507 {
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02005508 char_u *cmdbase = cmd;
5509
Bram Moolenaar4d5c1262019-09-20 17:20:02 +02005510 if (cmdbase != NULL)
5511 // Skip a leading quote and (.
5512 while (*cmdbase == '"' || *cmdbase == '(')
5513 ++cmdbase;
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02005514
5515 // Check the command does not begin with "start "
Bram Moolenaar36e7a822019-11-13 21:49:24 +01005516 if (cmdbase == NULL || STRNICMP(cmdbase, "start", 5) != 0
5517 || !VIM_ISWHITE(cmdbase[5]))
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02005518 {
5519 // Use a terminal window to run the command in.
5520 x = mch_call_shell_terminal(cmd, options);
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02005521 resettitle();
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02005522 return x;
5523 }
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005524 }
5525#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005526
5527 /*
5528 * Catch all deadly signals while running the external command, because a
5529 * CTRL-C, Ctrl-Break or illegal instruction might otherwise kill us.
5530 */
ichizok378447f2023-05-11 22:25:42 +01005531 mch_signal(SIGINT, SIG_IGN);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005532#if defined(__GNUC__) && !defined(__MINGW32__)
ichizok378447f2023-05-11 22:25:42 +01005533 mch_signal(SIGKILL, SIG_IGN);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005534#else
ichizok378447f2023-05-11 22:25:42 +01005535 mch_signal(SIGBREAK, SIG_IGN);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005536#endif
ichizok378447f2023-05-11 22:25:42 +01005537 mch_signal(SIGILL, SIG_IGN);
5538 mch_signal(SIGFPE, SIG_IGN);
5539 mch_signal(SIGSEGV, SIG_IGN);
5540 mch_signal(SIGTERM, SIG_IGN);
5541 mch_signal(SIGABRT, SIG_IGN);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005542
5543 if (options & SHELL_COOKED)
Bram Moolenaar0f873732019-12-05 20:28:46 +01005544 settmode(TMODE_COOK); // set to normal mode
Bram Moolenaar071d4272004-06-13 20:20:40 +00005545
5546 if (cmd == NULL)
5547 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01005548 x = mch_system((char *)p_sh, options);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005549 }
5550 else
5551 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005552 // we use "command" or "cmd" to start the shell; slow but easy
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005553 char_u *newcmd = NULL;
5554 char_u *cmdbase = cmd;
5555 long_u cmdlen;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005556
Bram Moolenaar0f873732019-12-05 20:28:46 +01005557 // Skip a leading ", ( and "(.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005558 if (*cmdbase == '"' )
5559 ++cmdbase;
5560 if (*cmdbase == '(')
5561 ++cmdbase;
5562
Bram Moolenaar1c465442017-03-12 20:10:05 +01005563 if ((STRNICMP(cmdbase, "start", 5) == 0) && VIM_ISWHITE(cmdbase[5]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005564 {
5565 STARTUPINFO si;
5566 PROCESS_INFORMATION pi;
5567 DWORD flags = CREATE_NEW_CONSOLE;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01005568 INT n_show_cmd = SW_SHOWNORMAL;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005569 char_u *p;
5570
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01005571 ZeroMemory(&si, sizeof(si));
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005572 si.cb = sizeof(si);
5573 si.lpReserved = NULL;
5574 si.lpDesktop = NULL;
5575 si.lpTitle = NULL;
5576 si.dwFlags = 0;
5577 si.cbReserved2 = 0;
5578 si.lpReserved2 = NULL;
5579
5580 cmdbase = skipwhite(cmdbase + 5);
5581 if ((STRNICMP(cmdbase, "/min", 4) == 0)
Bram Moolenaar1c465442017-03-12 20:10:05 +01005582 && VIM_ISWHITE(cmdbase[4]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005583 {
5584 cmdbase = skipwhite(cmdbase + 4);
5585 si.dwFlags = STARTF_USESHOWWINDOW;
5586 si.wShowWindow = SW_SHOWMINNOACTIVE;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01005587 n_show_cmd = SW_SHOWMINNOACTIVE;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005588 }
5589 else if ((STRNICMP(cmdbase, "/b", 2) == 0)
Bram Moolenaar1c465442017-03-12 20:10:05 +01005590 && VIM_ISWHITE(cmdbase[2]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005591 {
5592 cmdbase = skipwhite(cmdbase + 2);
5593 flags = CREATE_NO_WINDOW;
5594 si.dwFlags = STARTF_USESTDHANDLES;
5595 si.hStdInput = CreateFile("\\\\.\\NUL", // File name
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005596 GENERIC_READ, // Access flags
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005597 0, // Share flags
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005598 NULL, // Security att.
5599 OPEN_EXISTING, // Open flags
5600 FILE_ATTRIBUTE_NORMAL, // File att.
5601 NULL); // Temp file
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005602 si.hStdOutput = si.hStdInput;
5603 si.hStdError = si.hStdInput;
5604 }
5605
Bram Moolenaar0f873732019-12-05 20:28:46 +01005606 // Remove a trailing ", ) and )" if they have a match
5607 // at the start of the command.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005608 if (cmdbase > cmd)
5609 {
5610 p = cmdbase + STRLEN(cmdbase);
5611 if (p > cmdbase && p[-1] == '"' && *cmd == '"')
5612 *--p = NUL;
5613 if (p > cmdbase && p[-1] == ')'
5614 && (*cmd =='(' || cmd[1] == '('))
5615 *--p = NUL;
5616 }
5617
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005618 newcmd = cmdbase;
5619 unescape_shellxquote(cmdbase, p_sxe);
5620
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005621 /*
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005622 * If creating new console, arguments are passed to the
5623 * 'cmd.exe' as-is. If it's not, arguments are not treated
5624 * correctly for current 'cmd.exe'. So unescape characters in
5625 * shellxescape except '|' for avoiding to be treated as
5626 * argument to them. Pass the arguments to sub-shell.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005627 */
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005628 if (flags != CREATE_NEW_CONSOLE)
5629 {
5630 char_u *subcmd;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01005631 char_u *cmd_shell = mch_getenv("COMSPEC");
5632
5633 if (cmd_shell == NULL || *cmd_shell == NUL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01005634 cmd_shell = (char_u *)default_shell();
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005635
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01005636 subcmd = vim_strsave_escaped_ext(cmdbase,
5637 (char_u *)"|", '^', FALSE);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005638 if (subcmd != NULL)
5639 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005640 // make "cmd.exe /c arguments"
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005641 cmdlen = STRLEN(cmd_shell) + STRLEN(subcmd) + 5;
Bram Moolenaar18a4ba22019-05-24 19:39:03 +02005642 newcmd = alloc(cmdlen);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005643 if (newcmd != NULL)
5644 vim_snprintf((char *)newcmd, cmdlen, "%s /c %s",
Bram Moolenaaree7d1002012-02-22 15:34:08 +01005645 cmd_shell, subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005646 else
5647 newcmd = cmdbase;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01005648 vim_free(subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005649 }
5650 }
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005651
5652 /*
5653 * Now, start the command as a process, so that it doesn't
5654 * inherit our handles which causes unpleasant dangling swap
5655 * files if we exit before the spawned process
5656 */
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005657 if (vim_create_process((char *)newcmd, FALSE, flags,
5658 &si, &pi, NULL, NULL))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005659 x = 0;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01005660 else if (vim_shell_execute((char *)newcmd, n_show_cmd)
5661 > (HINSTANCE)32)
5662 x = 0;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005663 else
5664 {
5665 x = -1;
Bram Moolenaar4f974752019-02-17 17:44:42 +01005666#ifdef FEAT_GUI_MSWIN
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005667# ifdef VIMDLL
5668 if (gui.in_use)
5669# endif
Bram Moolenaarac78dd42022-01-02 19:25:26 +00005670 emsg(_(e_command_not_found));
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005671#endif
5672 }
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005673
5674 if (newcmd != cmdbase)
5675 vim_free(newcmd);
5676
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01005677 if (si.dwFlags == STARTF_USESTDHANDLES && si.hStdInput != NULL)
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005678 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005679 // Close the handle to \\.\NUL created above.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005680 CloseHandle(si.hStdInput);
5681 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01005682 // Close the handles to the subprocess, so that it goes away
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005683 CloseHandle(pi.hThread);
5684 CloseHandle(pi.hProcess);
5685 }
5686 else
5687 {
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005688 cmdlen =
Bram Moolenaar4f974752019-02-17 17:44:42 +01005689#ifdef FEAT_GUI_MSWIN
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02005690 ((gui.in_use || gui.starting) ?
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005691 (!s_dont_use_vimrun && p_stmp ?
5692 STRLEN(vimrun_path) : STRLEN(p_sh) + STRLEN(p_shcf))
5693 : 0) +
Bram Moolenaar071d4272004-06-13 20:20:40 +00005694#endif
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005695 STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10;
Bram Moolenaar0fde2902008-03-16 13:54:13 +00005696
Bram Moolenaar18a4ba22019-05-24 19:39:03 +02005697 newcmd = alloc(cmdlen);
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005698 if (newcmd != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005699 {
Bram Moolenaar4f974752019-02-17 17:44:42 +01005700#if defined(FEAT_GUI_MSWIN)
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005701 if (
5702# ifdef VIMDLL
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02005703 (gui.in_use || gui.starting) &&
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005704# endif
5705 need_vimrun_warning)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005706 {
Bram Moolenaar63e43442016-11-19 17:28:44 +01005707 char *msg = _("VIMRUN.EXE not found in your $PATH.\n"
5708 "External commands will not pause after completion.\n"
5709 "See :help win32-vimrun for more information.");
5710 char *title = _("Vim Warning");
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005711 WCHAR *wmsg = enc_to_utf16((char_u *)msg, NULL);
5712 WCHAR *wtitle = enc_to_utf16((char_u *)title, NULL);
Bram Moolenaar63e43442016-11-19 17:28:44 +01005713
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005714 if (wmsg != NULL && wtitle != NULL)
5715 MessageBoxW(NULL, wmsg, wtitle, MB_ICONWARNING);
5716 vim_free(wmsg);
5717 vim_free(wtitle);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005718 need_vimrun_warning = FALSE;
5719 }
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005720 if (
5721# ifdef VIMDLL
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02005722 (gui.in_use || gui.starting) &&
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005723# endif
5724 !s_dont_use_vimrun && p_stmp)
Bram Moolenaarfcc4d922019-05-24 13:32:36 +02005725 // Use vimrun to execute the command. It opens a console
5726 // window, which can be closed without killing Vim.
Bram Moolenaarcc448b32010-07-14 16:52:17 +02005727 vim_snprintf((char *)newcmd, cmdlen, "%s%s%s %s %s",
Bram Moolenaar071d4272004-06-13 20:20:40 +00005728 vimrun_path,
5729 (msg_silent != 0 || (options & SHELL_DOOUT))
5730 ? "-s " : "",
5731 p_sh, p_shcf, cmd);
Bram Moolenaarfcc4d922019-05-24 13:32:36 +02005732 else if (
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005733# ifdef VIMDLL
Bram Moolenaarfcc4d922019-05-24 13:32:36 +02005734 (gui.in_use || gui.starting) &&
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005735# endif
Bram Moolenaar0e6bfb92019-07-31 20:53:56 +02005736 s_dont_use_vimrun && STRCMP(p_shcf, "/c") == 0)
Bram Moolenaarfcc4d922019-05-24 13:32:36 +02005737 // workaround for the case that "vimrun" does not exist
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005738 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s %s %s",
5739 p_sh, p_shcf, p_sh, p_shcf, cmd);
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005740 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00005741#endif
Bram Moolenaarcc448b32010-07-14 16:52:17 +02005742 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s",
Bram Moolenaar0fde2902008-03-16 13:54:13 +00005743 p_sh, p_shcf, cmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005744 x = mch_system((char *)newcmd, options);
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005745 vim_free(newcmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005746 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005747 }
5748 }
5749
5750 if (tmode == TMODE_RAW)
Bram Moolenaar3b1f18f2020-05-16 23:15:08 +02005751 {
5752 // The shell may have messed with the mode, always set it.
5753 cur_tmode = TMODE_UNKNOWN;
Bram Moolenaar0f873732019-12-05 20:28:46 +01005754 settmode(TMODE_RAW); // set to raw mode
Bram Moolenaar3b1f18f2020-05-16 23:15:08 +02005755 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005756
Bram Moolenaar0f873732019-12-05 20:28:46 +01005757 // Print the return value, unless "vimrun" was used.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005758 if (x != 0 && !(options & SHELL_SILENT) && !emsg_silent
Bram Moolenaar4f974752019-02-17 17:44:42 +01005759#if defined(FEAT_GUI_MSWIN)
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02005760 && ((gui.in_use || gui.starting) ?
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005761 ((options & SHELL_DOOUT) || s_dont_use_vimrun || !p_stmp) : 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005762#endif
5763 )
5764 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005765 smsg(_("shell returned %d"), x);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005766 msg_putchar('\n');
5767 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005768 resettitle();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005769
ichizok378447f2023-05-11 22:25:42 +01005770 mch_signal(SIGINT, SIG_DFL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005771#if defined(__GNUC__) && !defined(__MINGW32__)
ichizok378447f2023-05-11 22:25:42 +01005772 mch_signal(SIGKILL, SIG_DFL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005773#else
ichizok378447f2023-05-11 22:25:42 +01005774 mch_signal(SIGBREAK, SIG_DFL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005775#endif
ichizok378447f2023-05-11 22:25:42 +01005776 mch_signal(SIGILL, SIG_DFL);
5777 mch_signal(SIGFPE, SIG_DFL);
5778 mch_signal(SIGSEGV, SIG_DFL);
5779 mch_signal(SIGTERM, SIG_DFL);
5780 mch_signal(SIGABRT, SIG_DFL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005781
5782 return x;
5783}
5784
Bram Moolenaar509ce2a2016-03-11 22:52:15 +01005785#if defined(FEAT_JOB_CHANNEL) || defined(PROTO)
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005786 static HANDLE
5787job_io_file_open(
Bram Moolenaar972c3b82017-01-12 21:44:49 +01005788 char_u *fname,
5789 DWORD dwDesiredAccess,
5790 DWORD dwShareMode,
5791 LPSECURITY_ATTRIBUTES lpSecurityAttributes,
5792 DWORD dwCreationDisposition,
5793 DWORD dwFlagsAndAttributes)
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005794{
5795 HANDLE h;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005796 WCHAR *wn;
Bram Moolenaara12a1612019-01-24 16:39:02 +01005797
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005798 wn = enc_to_utf16(fname, NULL);
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005799 if (wn == NULL)
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005800 return INVALID_HANDLE_VALUE;
5801
5802 h = CreateFileW(wn, dwDesiredAccess, dwShareMode,
5803 lpSecurityAttributes, dwCreationDisposition,
5804 dwFlagsAndAttributes, NULL);
5805 vim_free(wn);
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005806 return h;
5807}
5808
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005809/*
5810 * Turn the dictionary "env" into a NUL separated list that can be used as the
5811 * environment argument of vim_create_process().
5812 */
Bram Moolenaarba6febd2017-10-30 21:56:23 +01005813 void
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005814win32_build_env(dict_T *env, garray_T *gap, int is_terminal)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005815{
5816 hashitem_T *hi;
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005817 long_u todo = env != NULL ? env->dv_hashtab.ht_used : 0;
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005818 LPVOID base = GetEnvironmentStringsW();
5819
Bram Moolenaar0f873732019-12-05 20:28:46 +01005820 // for last \0
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005821 if (ga_grow(gap, 1) == FAIL)
5822 return;
5823
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005824 if (env != NULL)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005825 {
Yegappan Lakshmanan14113fd2023-03-07 17:13:51 +00005826 FOR_ALL_HASHTAB_ITEMS(&env->dv_hashtab, hi, todo)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005827 {
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005828 if (!HASHITEM_EMPTY(hi))
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005829 {
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005830 typval_T *item = &dict_lookup(hi)->di_tv;
5831 WCHAR *wkey = enc_to_utf16((char_u *)hi->hi_key, NULL);
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005832 WCHAR *wval = enc_to_utf16(tv_get_string(item), NULL);
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005833 --todo;
5834 if (wkey != NULL && wval != NULL)
5835 {
5836 size_t n;
5837 size_t lkey = wcslen(wkey);
5838 size_t lval = wcslen(wval);
Bram Moolenaar60104f12017-08-14 23:25:04 +02005839
Yegappan Lakshmananfadc02a2023-01-27 21:03:12 +00005840 if (ga_grow(gap, (int)(lkey + lval + 2)) == FAIL)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005841 continue;
5842 for (n = 0; n < lkey; n++)
5843 *((WCHAR*)gap->ga_data + gap->ga_len++) = wkey[n];
5844 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'=';
5845 for (n = 0; n < lval; n++)
5846 *((WCHAR*)gap->ga_data + gap->ga_len++) = wval[n];
5847 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5848 }
Bram Moolenaarbdace832019-03-02 10:13:42 +01005849 vim_free(wkey);
5850 vim_free(wval);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005851 }
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005852 }
5853 }
5854
Bram Moolenaar355757a2020-02-10 22:06:32 +01005855 if (base)
5856 {
5857 WCHAR *p = (WCHAR*) base;
5858
5859 // for last \0
5860 if (ga_grow(gap, 1) == FAIL)
5861 return;
5862
5863 while (*p != 0 || *(p + 1) != 0)
5864 {
5865 if (ga_grow(gap, 1) == OK)
5866 *((WCHAR*)gap->ga_data + gap->ga_len++) = *p;
5867 p++;
5868 }
Ken Takataad29f6a2023-09-16 13:56:02 +02005869 FreeEnvironmentStringsW(base);
Bram Moolenaar355757a2020-02-10 22:06:32 +01005870 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5871 }
5872
Bram Moolenaar493359e2018-06-12 20:25:52 +02005873# if defined(FEAT_CLIENTSERVER) || defined(FEAT_TERMINAL)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005874 {
Bram Moolenaar493359e2018-06-12 20:25:52 +02005875# ifdef FEAT_CLIENTSERVER
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005876 char_u *servername = get_vim_var_str(VV_SEND_SERVER);
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005877 size_t servername_len = STRLEN(servername);
Bram Moolenaar493359e2018-06-12 20:25:52 +02005878# endif
5879# ifdef FEAT_TERMINAL
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005880 char_u *version = get_vim_var_str(VV_VERSION);
5881 size_t version_len = STRLEN(version);
Bram Moolenaar493359e2018-06-12 20:25:52 +02005882# endif
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005883 // size of "VIM_SERVERNAME=" and value,
5884 // plus "VIM_TERMINAL=" and value,
5885 // plus two terminating NULs
5886 size_t n = 0
Bram Moolenaar493359e2018-06-12 20:25:52 +02005887# ifdef FEAT_CLIENTSERVER
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005888 + 15 + servername_len
Bram Moolenaar493359e2018-06-12 20:25:52 +02005889# endif
5890# ifdef FEAT_TERMINAL
5891 + 13 + version_len + 2
5892# endif
5893 ;
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005894
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005895 if (ga_grow(gap, (int)n) == OK)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005896 {
Bram Moolenaar493359e2018-06-12 20:25:52 +02005897# ifdef FEAT_CLIENTSERVER
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005898 for (n = 0; n < 15; n++)
5899 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5900 (WCHAR)"VIM_SERVERNAME="[n];
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005901 for (n = 0; n < servername_len; n++)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005902 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5903 (WCHAR)servername[n];
5904 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
Bram Moolenaar493359e2018-06-12 20:25:52 +02005905# endif
5906# ifdef FEAT_TERMINAL
5907 if (is_terminal)
5908 {
5909 for (n = 0; n < 13; n++)
5910 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5911 (WCHAR)"VIM_TERMINAL="[n];
5912 for (n = 0; n < version_len; n++)
5913 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5914 (WCHAR)version[n];
5915 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5916 }
5917# endif
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005918 }
5919 }
Bram Moolenaar79c6b512018-06-12 21:11:12 +02005920# endif
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005921}
5922
Bram Moolenaarb091f302019-01-19 14:37:00 +01005923/*
5924 * Create a pair of pipes.
5925 * Return TRUE for success, FALSE for failure.
5926 */
5927 static BOOL
5928create_pipe_pair(HANDLE handles[2])
5929{
5930 static LONG s;
5931 char name[64];
5932 SECURITY_ATTRIBUTES sa;
5933
5934 sprintf(name, "\\\\?\\pipe\\vim-%08lx-%08lx",
5935 GetCurrentProcessId(),
5936 InterlockedIncrement(&s));
5937
5938 // Create named pipe. Max size of named pipe is 65535.
5939 handles[1] = CreateNamedPipe(
5940 name,
5941 PIPE_ACCESS_OUTBOUND | FILE_FLAG_OVERLAPPED,
5942 PIPE_TYPE_BYTE | PIPE_NOWAIT,
Bram Moolenaar24058382019-01-24 23:11:49 +01005943 1, MAX_NAMED_PIPE_SIZE, 0, 0, NULL);
Bram Moolenaarb091f302019-01-19 14:37:00 +01005944
5945 if (handles[1] == INVALID_HANDLE_VALUE)
5946 return FALSE;
5947
5948 sa.nLength = sizeof(sa);
5949 sa.bInheritHandle = TRUE;
5950 sa.lpSecurityDescriptor = NULL;
5951
5952 handles[0] = CreateFile(name,
5953 FILE_GENERIC_READ,
5954 FILE_SHARE_READ, &sa,
5955 OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
5956
5957 if (handles[0] == INVALID_HANDLE_VALUE)
5958 {
Bram Moolenaar6982f422019-02-16 16:48:01 +01005959 CloseHandle(handles[1]);
Bram Moolenaarb091f302019-01-19 14:37:00 +01005960 return FALSE;
5961 }
5962
5963 return TRUE;
5964}
5965
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005966 void
Bram Moolenaar5a1feb82017-07-22 18:04:08 +02005967mch_job_start(char *cmd, job_T *job, jobopt_T *options)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005968{
5969 STARTUPINFO si;
5970 PROCESS_INFORMATION pi;
Bram Moolenaar14207f42016-10-27 21:13:10 +02005971 HANDLE jo;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005972 SECURITY_ATTRIBUTES saAttr;
5973 channel_T *channel = NULL;
Bram Moolenaard8070362016-02-15 21:56:54 +01005974 HANDLE ifd[2];
5975 HANDLE ofd[2];
5976 HANDLE efd[2];
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005977 garray_T ga;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005978
5979 int use_null_for_in = options->jo_io[PART_IN] == JIO_NULL;
5980 int use_null_for_out = options->jo_io[PART_OUT] == JIO_NULL;
5981 int use_null_for_err = options->jo_io[PART_ERR] == JIO_NULL;
5982 int use_file_for_in = options->jo_io[PART_IN] == JIO_FILE;
5983 int use_file_for_out = options->jo_io[PART_OUT] == JIO_FILE;
5984 int use_file_for_err = options->jo_io[PART_ERR] == JIO_FILE;
5985 int use_out_for_err = options->jo_io[PART_ERR] == JIO_OUT;
5986
5987 if (use_out_for_err && use_null_for_out)
5988 use_null_for_err = TRUE;
Bram Moolenaard8070362016-02-15 21:56:54 +01005989
5990 ifd[0] = INVALID_HANDLE_VALUE;
5991 ifd[1] = INVALID_HANDLE_VALUE;
5992 ofd[0] = INVALID_HANDLE_VALUE;
5993 ofd[1] = INVALID_HANDLE_VALUE;
5994 efd[0] = INVALID_HANDLE_VALUE;
5995 efd[1] = INVALID_HANDLE_VALUE;
Bram Moolenaar04935fb2022-01-08 16:19:22 +00005996 ga_init2(&ga, sizeof(wchar_t), 500);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005997
Bram Moolenaar14207f42016-10-27 21:13:10 +02005998 jo = CreateJobObject(NULL, NULL);
5999 if (jo == NULL)
6000 {
6001 job->jv_status = JOB_FAILED;
6002 goto failed;
6003 }
6004
Bram Moolenaar05aafed2017-08-11 19:12:11 +02006005 if (options->jo_env != NULL)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01006006 win32_build_env(options->jo_env, &ga, FALSE);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02006007
Bram Moolenaar76467df2016-02-12 19:30:26 +01006008 ZeroMemory(&pi, sizeof(pi));
Bram Moolenaar942d6b22016-02-07 19:57:16 +01006009 ZeroMemory(&si, sizeof(si));
6010 si.cb = sizeof(si);
Bram Moolenaard8070362016-02-15 21:56:54 +01006011 si.dwFlags |= STARTF_USESHOWWINDOW;
Bram Moolenaar76467df2016-02-12 19:30:26 +01006012 si.wShowWindow = SW_HIDE;
Bram Moolenaar942d6b22016-02-07 19:57:16 +01006013
Bram Moolenaard8070362016-02-15 21:56:54 +01006014 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
6015 saAttr.bInheritHandle = TRUE;
6016 saAttr.lpSecurityDescriptor = NULL;
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01006017
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01006018 if (use_file_for_in)
6019 {
6020 char_u *fname = options->jo_io_name[PART_IN];
6021
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01006022 ifd[0] = job_io_file_open(fname, GENERIC_READ,
6023 FILE_SHARE_READ | FILE_SHARE_WRITE,
6024 &saAttr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL);
6025 if (ifd[0] == INVALID_HANDLE_VALUE)
Bram Moolenaar94d01912016-03-08 13:48:51 +01006026 {
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00006027 semsg(_(e_cant_open_file_str), fname);
Bram Moolenaar94d01912016-03-08 13:48:51 +01006028 goto failed;
6029 }
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01006030 }
Bram Moolenaarb091f302019-01-19 14:37:00 +01006031 else if (!use_null_for_in
6032 && (!create_pipe_pair(ifd)
6033 || !SetHandleInformation(ifd[1], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01006034 goto failed;
6035
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01006036 if (use_file_for_out)
6037 {
6038 char_u *fname = options->jo_io_name[PART_OUT];
6039
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01006040 ofd[1] = job_io_file_open(fname, GENERIC_WRITE,
6041 FILE_SHARE_READ | FILE_SHARE_WRITE,
6042 &saAttr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL);
6043 if (ofd[1] == INVALID_HANDLE_VALUE)
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01006044 {
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00006045 semsg(_(e_cant_open_file_str), fname);
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01006046 goto failed;
6047 }
6048 }
Bram Moolenaard5d3d302016-03-09 20:54:51 +01006049 else if (!use_null_for_out &&
6050 (!CreatePipe(&ofd[0], &ofd[1], &saAttr, 0)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006051 || !SetHandleInformation(ofd[0], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01006052 goto failed;
6053
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01006054 if (use_file_for_err)
6055 {
6056 char_u *fname = options->jo_io_name[PART_ERR];
6057
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01006058 efd[1] = job_io_file_open(fname, GENERIC_WRITE,
6059 FILE_SHARE_READ | FILE_SHARE_WRITE,
6060 &saAttr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL);
6061 if (efd[1] == INVALID_HANDLE_VALUE)
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01006062 {
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00006063 semsg(_(e_cant_open_file_str), fname);
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01006064 goto failed;
6065 }
6066 }
Bram Moolenaard5d3d302016-03-09 20:54:51 +01006067 else if (!use_out_for_err && !use_null_for_err &&
6068 (!CreatePipe(&efd[0], &efd[1], &saAttr, 0)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006069 || !SetHandleInformation(efd[0], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaard8070362016-02-15 21:56:54 +01006070 goto failed;
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01006071
Bram Moolenaard8070362016-02-15 21:56:54 +01006072 si.dwFlags |= STARTF_USESTDHANDLES;
6073 si.hStdInput = ifd[0];
Bram Moolenaard5d3d302016-03-09 20:54:51 +01006074 si.hStdOutput = ofd[1];
6075 si.hStdError = use_out_for_err ? ofd[1] : efd[1];
6076
6077 if (!use_null_for_in || !use_null_for_out || !use_null_for_err)
6078 {
Bram Moolenaarde279892016-03-11 22:19:44 +01006079 if (options->jo_set & JO_CHANNEL)
6080 {
6081 channel = options->jo_channel;
6082 if (channel != NULL)
6083 ++channel->ch_refcount;
6084 }
6085 else
6086 channel = add_channel();
Bram Moolenaard5d3d302016-03-09 20:54:51 +01006087 if (channel == NULL)
6088 goto failed;
6089 }
Bram Moolenaard8070362016-02-15 21:56:54 +01006090
6091 if (!vim_create_process(cmd, TRUE,
Bram Moolenaar14207f42016-10-27 21:13:10 +02006092 CREATE_SUSPENDED |
Bram Moolenaar942d6b22016-02-07 19:57:16 +01006093 CREATE_DEFAULT_ERROR_MODE |
6094 CREATE_NEW_PROCESS_GROUP |
Bram Moolenaar05aafed2017-08-11 19:12:11 +02006095 CREATE_UNICODE_ENVIRONMENT |
Bram Moolenaar76467df2016-02-12 19:30:26 +01006096 CREATE_NEW_CONSOLE,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02006097 &si, &pi,
6098 ga.ga_data,
6099 (char *)options->jo_cwd))
Bram Moolenaar76467df2016-02-12 19:30:26 +01006100 {
Bram Moolenaar14207f42016-10-27 21:13:10 +02006101 CloseHandle(jo);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01006102 job->jv_status = JOB_FAILED;
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01006103 goto failed;
Bram Moolenaar76467df2016-02-12 19:30:26 +01006104 }
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01006105
Bram Moolenaar05aafed2017-08-11 19:12:11 +02006106 ga_clear(&ga);
6107
Bram Moolenaar14207f42016-10-27 21:13:10 +02006108 if (!AssignProcessToJobObject(jo, pi.hProcess))
6109 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006110 // if failing, switch the way to terminate
6111 // process with TerminateProcess.
Bram Moolenaar14207f42016-10-27 21:13:10 +02006112 CloseHandle(jo);
6113 jo = NULL;
6114 }
6115 ResumeThread(pi.hThread);
Bram Moolenaar75578a32016-03-10 16:33:31 +01006116 CloseHandle(pi.hThread);
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01006117 job->jv_proc_info = pi;
Bram Moolenaar14207f42016-10-27 21:13:10 +02006118 job->jv_job_object = jo;
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01006119 job->jv_status = JOB_STARTED;
6120
Bram Moolenaar641ad6c2016-09-01 18:32:11 +02006121 CloseHandle(ifd[0]);
6122 CloseHandle(ofd[1]);
6123 if (!use_out_for_err && !use_null_for_err)
Bram Moolenaarc25558b2016-03-03 21:02:23 +01006124 CloseHandle(efd[1]);
Bram Moolenaard8070362016-02-15 21:56:54 +01006125
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01006126 job->jv_channel = channel;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01006127 if (channel != NULL)
6128 {
6129 channel_set_pipes(channel,
6130 use_file_for_in || use_null_for_in
6131 ? INVALID_FD : (sock_T)ifd[1],
6132 use_file_for_out || use_null_for_out
6133 ? INVALID_FD : (sock_T)ofd[0],
6134 use_out_for_err || use_file_for_err || use_null_for_err
6135 ? INVALID_FD : (sock_T)efd[0]);
6136 channel_set_job(channel, job, options);
Bram Moolenaard5d3d302016-03-09 20:54:51 +01006137 }
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01006138 return;
6139
6140failed:
Bram Moolenaard8070362016-02-15 21:56:54 +01006141 CloseHandle(ifd[0]);
6142 CloseHandle(ofd[0]);
6143 CloseHandle(efd[0]);
6144 CloseHandle(ifd[1]);
6145 CloseHandle(ofd[1]);
6146 CloseHandle(efd[1]);
Bram Moolenaarde279892016-03-11 22:19:44 +01006147 channel_unref(channel);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02006148 ga_clear(&ga);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01006149}
6150
6151 char *
6152mch_job_status(job_T *job)
6153{
6154 DWORD dwExitCode = 0;
6155
Bram Moolenaar76467df2016-02-12 19:30:26 +01006156 if (!GetExitCodeProcess(job->jv_proc_info.hProcess, &dwExitCode)
6157 || dwExitCode != STILL_ACTIVE)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01006158 {
Bram Moolenaareab089d2016-02-21 19:32:02 +01006159 job->jv_exitval = (int)dwExitCode;
Bram Moolenaar7df915d2016-11-17 17:25:32 +01006160 if (job->jv_status < JOB_ENDED)
Bram Moolenaar97792de2016-10-15 18:36:49 +02006161 {
6162 ch_log(job->jv_channel, "Job ended");
6163 job->jv_status = JOB_ENDED;
6164 }
Bram Moolenaar942d6b22016-02-07 19:57:16 +01006165 return "dead";
6166 }
6167 return "run";
6168}
6169
Bram Moolenaar97792de2016-10-15 18:36:49 +02006170 job_T *
6171mch_detect_ended_job(job_T *job_list)
6172{
6173 HANDLE jobHandles[MAXIMUM_WAIT_OBJECTS];
6174 job_T *jobArray[MAXIMUM_WAIT_OBJECTS];
6175 job_T *job = job_list;
6176
6177 while (job != NULL)
6178 {
6179 DWORD n;
6180 DWORD result;
6181
6182 for (n = 0; n < MAXIMUM_WAIT_OBJECTS
6183 && job != NULL; job = job->jv_next)
6184 {
6185 if (job->jv_status == JOB_STARTED)
6186 {
6187 jobHandles[n] = job->jv_proc_info.hProcess;
6188 jobArray[n] = job;
6189 ++n;
6190 }
6191 }
6192 if (n == 0)
6193 continue;
6194 result = WaitForMultipleObjects(n, jobHandles, FALSE, 0);
6195 if (result >= WAIT_OBJECT_0 && result < WAIT_OBJECT_0 + n)
6196 {
6197 job_T *wait_job = jobArray[result - WAIT_OBJECT_0];
6198
6199 if (STRCMP(mch_job_status(wait_job), "dead") == 0)
6200 return wait_job;
6201 }
6202 }
6203 return NULL;
6204}
6205
Bram Moolenaarfb630902016-10-29 14:55:00 +02006206 static BOOL
6207terminate_all(HANDLE process, int code)
6208{
6209 PROCESSENTRY32 pe;
6210 HANDLE h = INVALID_HANDLE_VALUE;
6211 DWORD pid = GetProcessId(process);
6212
6213 if (pid != 0)
6214 {
6215 h = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
6216 if (h != INVALID_HANDLE_VALUE)
6217 {
6218 pe.dwSize = sizeof(PROCESSENTRY32);
6219 if (!Process32First(h, &pe))
6220 goto theend;
6221
6222 do
6223 {
6224 if (pe.th32ParentProcessID == pid)
6225 {
6226 HANDLE ph = OpenProcess(
6227 PROCESS_ALL_ACCESS, FALSE, pe.th32ProcessID);
6228 if (ph != NULL)
6229 {
6230 terminate_all(ph, code);
6231 CloseHandle(ph);
6232 }
6233 }
6234 } while (Process32Next(h, &pe));
6235
6236 CloseHandle(h);
6237 }
6238 }
6239
6240theend:
6241 return TerminateProcess(process, code);
6242}
6243
6244/*
6245 * Send a (deadly) signal to "job".
6246 * Return FAIL if it didn't work.
6247 */
Bram Moolenaar942d6b22016-02-07 19:57:16 +01006248 int
Bram Moolenaar2d33e902017-08-11 16:31:54 +02006249mch_signal_job(job_T *job, char_u *how)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01006250{
Bram Moolenaar923d9262016-02-25 20:56:01 +01006251 int ret;
Bram Moolenaar76467df2016-02-12 19:30:26 +01006252
Bram Moolenaar923d9262016-02-25 20:56:01 +01006253 if (STRCMP(how, "term") == 0 || STRCMP(how, "kill") == 0 || *how == NUL)
Bram Moolenaar76467df2016-02-12 19:30:26 +01006254 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006255 // deadly signal
Bram Moolenaar14207f42016-10-27 21:13:10 +02006256 if (job->jv_job_object != NULL)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006257 {
6258 if (job->jv_channel != NULL && job->jv_channel->ch_anonymous_pipe)
6259 job->jv_channel->ch_killing = TRUE;
K.Takata135e1522022-01-29 15:27:58 +00006260 return TerminateJobObject(job->jv_job_object, (UINT)-1) ? OK : FAIL;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006261 }
Bram Moolenaarb3e195c2020-02-10 21:32:19 +01006262 return terminate_all(job->jv_proc_info.hProcess, -1) ? OK : FAIL;
Bram Moolenaar76467df2016-02-12 19:30:26 +01006263 }
6264
6265 if (!AttachConsole(job->jv_proc_info.dwProcessId))
6266 return FAIL;
6267 ret = GenerateConsoleCtrlEvent(
Bram Moolenaar923d9262016-02-25 20:56:01 +01006268 STRCMP(how, "int") == 0 ? CTRL_C_EVENT : CTRL_BREAK_EVENT,
6269 job->jv_proc_info.dwProcessId)
6270 ? OK : FAIL;
Bram Moolenaar76467df2016-02-12 19:30:26 +01006271 FreeConsole();
6272 return ret;
6273}
6274
6275/*
6276 * Clear the data related to "job".
6277 */
6278 void
6279mch_clear_job(job_T *job)
6280{
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00006281 if (job->jv_status == JOB_FAILED)
6282 return;
6283
6284 if (job->jv_job_object != NULL)
6285 CloseHandle(job->jv_job_object);
6286 CloseHandle(job->jv_proc_info.hProcess);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01006287}
6288#endif
6289
Bram Moolenaar071d4272004-06-13 20:20:40 +00006290
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006291#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006292
6293/*
6294 * Start termcap mode
6295 */
6296 static void
6297termcap_mode_start(void)
6298{
6299 DWORD cmodein;
6300
6301 if (g_fTermcapMode)
6302 return;
6303
6304 SaveConsoleBuffer(&g_cbNonTermcap);
6305
6306 if (g_cbTermcap.IsValid)
6307 {
6308 /*
6309 * We've been in termcap mode before. Restore certain screen
6310 * characteristics, including the buffer size and the window
6311 * size. Since we will be redrawing the screen, we don't need
6312 * to restore the actual contents of the buffer.
6313 */
6314 RestoreConsoleBuffer(&g_cbTermcap, FALSE);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006315 reset_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00006316 SetConsoleWindowInfo(g_hConOut, TRUE, &g_cbTermcap.Info.srWindow);
6317 Rows = g_cbTermcap.Info.dwSize.Y;
6318 Columns = g_cbTermcap.Info.dwSize.X;
6319 }
6320 else
6321 {
6322 /*
6323 * This is our first time entering termcap mode. Clear the console
6324 * screen buffer, and resize the buffer to match the current window
6325 * size. We will use this as the size of our editing environment.
6326 */
6327 ClearConsoleBuffer(g_attrCurrent);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006328 set_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00006329 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
6330 }
6331
Bram Moolenaar071d4272004-06-13 20:20:40 +00006332 resettitle();
Bram Moolenaar071d4272004-06-13 20:20:40 +00006333
6334 GetConsoleMode(g_hConIn, &cmodein);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006335 if (g_fMouseActive)
Wez Furlong6ef5ab52021-05-30 19:29:41 +02006336 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006337 cmodein |= ENABLE_MOUSE_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02006338 cmodein &= ~ENABLE_QUICK_EDIT_MODE;
6339 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006340 else
Wez Furlong6ef5ab52021-05-30 19:29:41 +02006341 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006342 cmodein &= ~ENABLE_MOUSE_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02006343 cmodein |= g_cmodein & ENABLE_QUICK_EDIT_MODE;
6344 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006345 cmodein |= ENABLE_WINDOW_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02006346 SetConsoleMode(g_hConIn, cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006347
6348 redraw_later_clear();
6349 g_fTermcapMode = TRUE;
6350}
6351
6352
6353/*
6354 * End termcap mode
6355 */
6356 static void
6357termcap_mode_end(void)
6358{
6359 DWORD cmodein;
6360 ConsoleBuffer *cb;
6361 COORD coord;
6362 DWORD dwDummy;
6363
6364 if (!g_fTermcapMode)
6365 return;
6366
6367 SaveConsoleBuffer(&g_cbTermcap);
6368
6369 GetConsoleMode(g_hConIn, &cmodein);
6370 cmodein &= ~(ENABLE_MOUSE_INPUT | ENABLE_WINDOW_INPUT);
Wez Furlong6ef5ab52021-05-30 19:29:41 +02006371 cmodein |= g_cmodein & ENABLE_QUICK_EDIT_MODE;
6372 SetConsoleMode(g_hConIn, cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006373
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006374# ifdef FEAT_RESTORE_ORIG_SCREEN
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01006375 cb = exiting ? &g_cbOrig : &g_cbNonTermcap;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006376# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00006377 cb = &g_cbNonTermcap;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006378# endif
Bram Moolenaar81ccbf12020-04-15 21:05:30 +02006379 RestoreConsoleBuffer(cb, p_rs);
Bram Moolenaardf543822020-01-30 11:53:59 +01006380 restore_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00006381
Christopher Plewright1140b512022-11-12 18:46:05 +00006382 // Switch back to main screen buffer.
Christopher Plewrightc8b126d2022-12-22 13:45:23 +00006383 if (exiting && use_alternate_screen_buffer)
Christopher Plewright1140b512022-11-12 18:46:05 +00006384 vtp_printf("\033[?1049l");
6385
6386 if (!USE_WT && (p_rs || exiting))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006387 {
6388 /*
6389 * Clear anything that happens to be on the current line.
6390 */
6391 coord.X = 0;
6392 coord.Y = (SHORT) (p_rs ? cb->Info.dwCursorPosition.Y : (Rows - 1));
Christopher Plewrightf75a2cb2023-01-28 10:28:09 +00006393 FillConsoleOutputCharacter(g_hConOut, ' ',
6394 cb->Info.dwSize.X, coord, &dwDummy);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006395 /*
6396 * The following is just for aesthetics. If we are exiting without
6397 * restoring the screen, then we want to have a prompt string
6398 * appear at the bottom line. However, the command interpreter
6399 * seems to always advance the cursor one line before displaying
6400 * the prompt string, which causes the screen to scroll. To
6401 * counter this, move the cursor up one line before exiting.
6402 */
6403 if (exiting && !p_rs)
6404 coord.Y--;
6405 /*
6406 * Position the cursor at the leftmost column of the desired row.
6407 */
Bram Moolenaar81ccbf12020-04-15 21:05:30 +02006408 SetConsoleCursorPosition(g_hConOut, coord);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006409 }
Christopher Plewright1140b512022-11-12 18:46:05 +00006410 SetConsoleCursorInfo(g_hConOut, &g_cci);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006411 g_fTermcapMode = FALSE;
6412}
Christopher Plewright38804d62022-11-09 23:55:52 +00006413#endif // !FEAT_GUI_MSWIN || VIMDLL
Bram Moolenaar071d4272004-06-13 20:20:40 +00006414
6415
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006416#if defined(FEAT_GUI_MSWIN) && !defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006417 void
6418mch_write(
Bram Moolenaar1266d672017-02-01 13:43:36 +01006419 char_u *s UNUSED,
6420 int len UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006421{
Bram Moolenaar0f873732019-12-05 20:28:46 +01006422 // never used
Bram Moolenaar071d4272004-06-13 20:20:40 +00006423}
6424
6425#else
6426
6427/*
6428 * clear `n' chars, starting from `coord'
6429 */
6430 static void
6431clear_chars(
6432 COORD coord,
6433 DWORD n)
6434{
Christopher Plewright38804d62022-11-09 23:55:52 +00006435 if (!vtp_working)
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006436 {
6437 DWORD dwDummy;
6438
6439 FillConsoleOutputCharacter(g_hConOut, ' ', n, coord, &dwDummy);
6440 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, n, coord,
6441 &dwDummy);
6442 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006443 else
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02006444 {
6445 set_console_color_rgb();
6446 gotoxy(coord.X + 1, coord.Y + 1);
6447 vtp_printf("\033[%dX", n);
6448 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006449}
6450
6451
6452/*
6453 * Clear the screen
6454 */
6455 static void
6456clear_screen(void)
6457{
6458 g_coord.X = g_coord.Y = 0;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006459
Christopher Plewright38804d62022-11-09 23:55:52 +00006460 if (!vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006461 clear_chars(g_coord, Rows * Columns);
6462 else
6463 {
6464 set_console_color_rgb();
6465 gotoxy(1, 1);
6466 vtp_printf("\033[2J");
6467 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006468}
6469
6470
6471/*
6472 * Clear to end of display
6473 */
6474 static void
6475clear_to_end_of_display(void)
6476{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006477 COORD save = g_coord;
6478
Christopher Plewright38804d62022-11-09 23:55:52 +00006479 if (!vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006480 clear_chars(g_coord, (Rows - g_coord.Y - 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006481 * Columns + (Columns - g_coord.X));
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006482 else
6483 {
6484 set_console_color_rgb();
6485 gotoxy(g_coord.X + 1, g_coord.Y + 1);
6486 vtp_printf("\033[0J");
6487
6488 gotoxy(save.X + 1, save.Y + 1);
6489 g_coord = save;
6490 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006491}
6492
6493
6494/*
6495 * Clear to end of line
6496 */
6497 static void
6498clear_to_end_of_line(void)
6499{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006500 COORD save = g_coord;
6501
Christopher Plewright38804d62022-11-09 23:55:52 +00006502 if (!vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006503 clear_chars(g_coord, Columns - g_coord.X);
6504 else
6505 {
6506 set_console_color_rgb();
6507 gotoxy(g_coord.X + 1, g_coord.Y + 1);
6508 vtp_printf("\033[0K");
6509
6510 gotoxy(save.X + 1, save.Y + 1);
6511 g_coord = save;
6512 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006513}
6514
6515
6516/*
6517 * Scroll the scroll region up by `cLines' lines
6518 */
6519 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006520scroll(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006521{
6522 COORD oldcoord = g_coord;
6523
6524 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
6525 delete_lines(cLines);
6526
6527 g_coord = oldcoord;
6528}
6529
6530
6531/*
6532 * Set the scroll region
6533 */
6534 static void
6535set_scroll_region(
6536 unsigned left,
6537 unsigned top,
6538 unsigned right,
6539 unsigned bottom)
6540{
6541 if (left >= right
6542 || top >= bottom
6543 || right > (unsigned) Columns - 1
6544 || bottom > (unsigned) Rows - 1)
6545 return;
6546
6547 g_srScrollRegion.Left = left;
6548 g_srScrollRegion.Top = top;
6549 g_srScrollRegion.Right = right;
6550 g_srScrollRegion.Bottom = bottom;
Bram Moolenaar6982f422019-02-16 16:48:01 +01006551}
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006552
Bram Moolenaar6982f422019-02-16 16:48:01 +01006553 static void
6554set_scroll_region_tb(
6555 unsigned top,
6556 unsigned bottom)
6557{
6558 if (top >= bottom || bottom > (unsigned)Rows - 1)
6559 return;
6560
6561 g_srScrollRegion.Top = top;
6562 g_srScrollRegion.Bottom = bottom;
6563}
6564
6565 static void
6566set_scroll_region_lr(
6567 unsigned left,
6568 unsigned right)
6569{
6570 if (left >= right || right > (unsigned)Columns - 1)
6571 return;
6572
6573 g_srScrollRegion.Left = left;
6574 g_srScrollRegion.Right = right;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006575}
6576
6577
6578/*
6579 * Insert `cLines' lines at the current cursor position
6580 */
6581 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006582insert_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006583{
Bram Moolenaar6982f422019-02-16 16:48:01 +01006584 SMALL_RECT source, clip;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006585 COORD dest;
6586 CHAR_INFO fill;
6587
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006588 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
6589
Bram Moolenaar6982f422019-02-16 16:48:01 +01006590 dest.X = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006591 dest.Y = g_coord.Y + cLines;
6592
Bram Moolenaar6982f422019-02-16 16:48:01 +01006593 source.Left = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006594 source.Top = g_coord.Y;
6595 source.Right = g_srScrollRegion.Right;
6596 source.Bottom = g_srScrollRegion.Bottom - cLines;
6597
Bram Moolenaar6982f422019-02-16 16:48:01 +01006598 clip.Left = g_srScrollRegion.Left;
6599 clip.Top = g_coord.Y;
6600 clip.Right = g_srScrollRegion.Right;
6601 clip.Bottom = g_srScrollRegion.Bottom;
6602
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006603 fill.Char.AsciiChar = ' ';
Christopher Plewrightf75a2cb2023-01-28 10:28:09 +00006604 if (!USE_VTP)
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006605 fill.Attributes = g_attrCurrent;
6606 else
6607 fill.Attributes = g_attrDefault;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006608
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006609 set_console_color_rgb();
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006610
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006611 ScrollConsoleScreenBuffer(g_hConOut, &source, &clip, dest, &fill);
6612
Bram Moolenaar6982f422019-02-16 16:48:01 +01006613 // Here we have to deal with a win32 console flake: If the scroll
6614 // region looks like abc and we scroll c to a and fill with d we get
6615 // cbd... if we scroll block c one line at a time to a, we get cdd...
6616 // vim expects cdd consistently... So we have to deal with that
6617 // here... (this also occurs scrolling the same way in the other
6618 // direction).
Bram Moolenaar071d4272004-06-13 20:20:40 +00006619
6620 if (source.Bottom < dest.Y)
6621 {
6622 COORD coord;
Bram Moolenaar6982f422019-02-16 16:48:01 +01006623 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006624
Bram Moolenaar6982f422019-02-16 16:48:01 +01006625 coord.X = source.Left;
6626 for (i = clip.Top; i < dest.Y; ++i)
6627 {
6628 coord.Y = i;
6629 clear_chars(coord, source.Right - source.Left + 1);
6630 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006631 }
Bram Moolenaar06b7b582020-05-30 17:49:25 +02006632
Christopher Plewright38804d62022-11-09 23:55:52 +00006633 if (vtp_working)
Bram Moolenaar06b7b582020-05-30 17:49:25 +02006634 {
6635 COORD coord;
6636 int i;
6637
6638 coord.X = source.Left;
6639 for (i = source.Top; i < dest.Y; ++i)
6640 {
6641 coord.Y = i;
6642 clear_chars(coord, source.Right - source.Left + 1);
6643 }
6644 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006645}
6646
6647
6648/*
6649 * Delete `cLines' lines at the current cursor position
6650 */
6651 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006652delete_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006653{
Bram Moolenaar6982f422019-02-16 16:48:01 +01006654 SMALL_RECT source, clip;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006655 COORD dest;
6656 CHAR_INFO fill;
6657 int nb;
6658
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006659 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
6660
Bram Moolenaar6982f422019-02-16 16:48:01 +01006661 dest.X = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006662 dest.Y = g_coord.Y;
6663
Bram Moolenaar6982f422019-02-16 16:48:01 +01006664 source.Left = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006665 source.Top = g_coord.Y + cLines;
6666 source.Right = g_srScrollRegion.Right;
6667 source.Bottom = g_srScrollRegion.Bottom;
6668
Bram Moolenaar6982f422019-02-16 16:48:01 +01006669 clip.Left = g_srScrollRegion.Left;
6670 clip.Top = g_coord.Y;
6671 clip.Right = g_srScrollRegion.Right;
6672 clip.Bottom = g_srScrollRegion.Bottom;
6673
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006674 fill.Char.AsciiChar = ' ';
Christopher Plewright38804d62022-11-09 23:55:52 +00006675 if (!vtp_working)
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006676 fill.Attributes = g_attrCurrent;
6677 else
6678 fill.Attributes = g_attrDefault;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006679
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006680 set_console_color_rgb();
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006681
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006682 ScrollConsoleScreenBuffer(g_hConOut, &source, &clip, dest, &fill);
6683
Bram Moolenaar6982f422019-02-16 16:48:01 +01006684 // Here we have to deal with a win32 console flake; See insert_lines()
6685 // above.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006686
6687 nb = dest.Y + (source.Bottom - source.Top) + 1;
6688
6689 if (nb < source.Top)
6690 {
6691 COORD coord;
Bram Moolenaar6982f422019-02-16 16:48:01 +01006692 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006693
Bram Moolenaar6982f422019-02-16 16:48:01 +01006694 coord.X = source.Left;
6695 for (i = nb; i < clip.Bottom; ++i)
6696 {
6697 coord.Y = i;
6698 clear_chars(coord, source.Right - source.Left + 1);
6699 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006700 }
Bram Moolenaar06b7b582020-05-30 17:49:25 +02006701
Christopher Plewright38804d62022-11-09 23:55:52 +00006702 if (vtp_working)
Bram Moolenaar06b7b582020-05-30 17:49:25 +02006703 {
6704 COORD coord;
6705 int i;
6706
6707 coord.X = source.Left;
6708 for (i = nb; i <= source.Bottom; ++i)
6709 {
6710 coord.Y = i;
6711 clear_chars(coord, source.Right - source.Left + 1);
6712 }
6713 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006714}
6715
6716
6717/*
Bram Moolenaar2313b612019-09-27 14:14:32 +02006718 * Set the cursor position to (x,y) (1-based).
Bram Moolenaar071d4272004-06-13 20:20:40 +00006719 */
6720 static void
6721gotoxy(
6722 unsigned x,
6723 unsigned y)
6724{
6725 if (x < 1 || x > (unsigned)Columns || y < 1 || y > (unsigned)Rows)
6726 return;
6727
Christopher Plewrightf75a2cb2023-01-28 10:28:09 +00006728 if (!USE_VTP)
Bram Moolenaar2313b612019-09-27 14:14:32 +02006729 {
Bram Moolenaar82e743c2020-03-26 15:39:53 +01006730 // There are reports of double-width characters not displayed
6731 // correctly. This workaround should fix it, similar to how it's done
6732 // for VTP.
6733 g_coord.X = 0;
6734 SetConsoleCursorPosition(g_hConOut, g_coord);
6735
Bram Moolenaar2313b612019-09-27 14:14:32 +02006736 // external cursor coords are 1-based; internal are 0-based
6737 g_coord.X = x - 1;
6738 g_coord.Y = y - 1;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006739 SetConsoleCursorPosition(g_hConOut, g_coord);
Bram Moolenaar2313b612019-09-27 14:14:32 +02006740 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006741 else
Bram Moolenaar2313b612019-09-27 14:14:32 +02006742 {
6743 // Move the cursor to the left edge of the screen to prevent screen
Bram Moolenaara1299742019-10-10 16:36:00 +02006744 // destruction. Insider build bug. Always enabled because it's cheap
6745 // and avoids mistakes with recognizing the build.
6746 vtp_printf("\033[%d;%dH", g_coord.Y + 1, 1);
Bram Moolenaar2313b612019-09-27 14:14:32 +02006747
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006748 vtp_printf("\033[%d;%dH", y, x);
Bram Moolenaar2313b612019-09-27 14:14:32 +02006749
6750 g_coord.X = x - 1;
6751 g_coord.Y = y - 1;
6752 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006753}
6754
6755
6756/*
6757 * Set the current text attribute = (foreground | background)
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006758 * See ../runtime/doc/os_win32.txt for the numbers.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006759 */
6760 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006761textattr(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006762{
Bram Moolenaar6383b922015-03-24 17:12:19 +01006763 g_attrCurrent = wAttr & 0xff;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006764
6765 SetConsoleTextAttribute(g_hConOut, wAttr);
6766}
6767
6768
6769 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006770textcolor(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006771{
Bram Moolenaar6383b922015-03-24 17:12:19 +01006772 g_attrCurrent = (g_attrCurrent & 0xf0) + (wAttr & 0x0f);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006773
Christopher Plewright38804d62022-11-09 23:55:52 +00006774 if (!vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006775 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
6776 else
6777 vtp_sgr_bulk(wAttr);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006778}
6779
6780
6781 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006782textbackground(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006783{
Bram Moolenaar6383b922015-03-24 17:12:19 +01006784 g_attrCurrent = (g_attrCurrent & 0x0f) + ((wAttr & 0x0f) << 4);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006785
Christopher Plewright38804d62022-11-09 23:55:52 +00006786 if (!vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006787 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
6788 else
6789 vtp_sgr_bulk(wAttr);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006790}
6791
6792
6793/*
6794 * restore the default text attribute (whatever we started with)
6795 */
6796 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006797normvideo(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006798{
Christopher Plewright38804d62022-11-09 23:55:52 +00006799 if (!vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006800 textattr(g_attrDefault);
6801 else
6802 vtp_sgr_bulk(0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006803}
6804
6805
6806static WORD g_attrPreStandout = 0;
6807
6808/*
6809 * Make the text standout, by brightening it
6810 */
6811 static void
6812standout(void)
6813{
6814 g_attrPreStandout = g_attrCurrent;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006815
Bram Moolenaar071d4272004-06-13 20:20:40 +00006816 textattr((WORD) (g_attrCurrent|FOREGROUND_INTENSITY|BACKGROUND_INTENSITY));
6817}
6818
6819
6820/*
6821 * Turn off standout mode
6822 */
6823 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006824standend(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006825{
6826 if (g_attrPreStandout)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006827 textattr(g_attrPreStandout);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006828
6829 g_attrPreStandout = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006830}
6831
6832
6833/*
Bram Moolenaarff1d0d42007-05-10 17:24:16 +00006834 * Set normal fg/bg color, based on T_ME. Called when t_me has been set.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006835 */
6836 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006837mch_set_normal_colors(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006838{
6839 char_u *p;
6840 int n;
6841
6842 cterm_normal_fg_color = (g_attrDefault & 0xf) + 1;
6843 cterm_normal_bg_color = ((g_attrDefault >> 4) & 0xf) + 1;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006844 if (
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006845# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006846 !p_tgc &&
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006847# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006848 T_ME[0] == ESC && T_ME[1] == '|')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006849 {
6850 p = T_ME + 2;
6851 n = getdigits(&p);
6852 if (*p == 'm' && n > 0)
6853 {
6854 cterm_normal_fg_color = (n & 0xf) + 1;
6855 cterm_normal_bg_color = ((n >> 4) & 0xf) + 1;
6856 }
6857 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006858# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006859 cterm_normal_fg_gui_color = INVALCOLOR;
6860 cterm_normal_bg_gui_color = INVALCOLOR;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006861# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006862}
6863
6864
6865/*
6866 * visual bell: flash the screen
6867 */
6868 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006869visual_bell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006870{
6871 COORD coordOrigin = {0, 0};
6872 WORD attrFlash = ~g_attrCurrent & 0xff;
6873
6874 DWORD dwDummy;
Christopher Plewrightdc7179f2023-01-23 12:33:23 +00006875 LPWORD oldattrs = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006876
Christopher Plewrightdc7179f2023-01-23 12:33:23 +00006877# ifdef FEAT_TERMGUICOLORS
6878 if (!(p_tgc || t_colors >= 256))
6879# endif
6880 {
6881 oldattrs = ALLOC_MULT(WORD, Rows * Columns);
6882 if (oldattrs == NULL)
6883 return;
6884 ReadConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
Bram Moolenaar071d4272004-06-13 20:20:40 +00006885 coordOrigin, &dwDummy);
Christopher Plewrightdc7179f2023-01-23 12:33:23 +00006886 }
6887
Bram Moolenaar071d4272004-06-13 20:20:40 +00006888 FillConsoleOutputAttribute(g_hConOut, attrFlash, Rows * Columns,
6889 coordOrigin, &dwDummy);
6890
Bram Moolenaar0f873732019-12-05 20:28:46 +01006891 Sleep(15); // wait for 15 msec
Christopher Plewrightdc7179f2023-01-23 12:33:23 +00006892
6893 if (oldattrs != NULL)
6894 {
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006895 WriteConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
Bram Moolenaar071d4272004-06-13 20:20:40 +00006896 coordOrigin, &dwDummy);
Christopher Plewrightdc7179f2023-01-23 12:33:23 +00006897 vim_free(oldattrs);
6898 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006899}
6900
6901
6902/*
6903 * Make the cursor visible or invisible
6904 */
6905 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006906cursor_visible(BOOL fVisible)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006907{
6908 s_cursor_visible = fVisible;
Bram Moolenaar2695de62020-04-17 21:13:01 +02006909
Christopher Plewright38804d62022-11-09 23:55:52 +00006910 if (vtp_working)
Bram Moolenaar2695de62020-04-17 21:13:01 +02006911 vtp_printf("\033[?25%c", fVisible ? 'h' : 'l');
6912
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006913# ifdef MCH_CURSOR_SHAPE
Bram Moolenaar071d4272004-06-13 20:20:40 +00006914 mch_update_cursor();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006915# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006916}
6917
6918
6919/*
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02006920 * Write "cbToWrite" bytes in `pchBuf' to the screen.
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006921 * Returns the number of bytes actually written (at least one).
Bram Moolenaar071d4272004-06-13 20:20:40 +00006922 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006923 static DWORD
Bram Moolenaar071d4272004-06-13 20:20:40 +00006924write_chars(
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006925 char_u *pchBuf,
6926 DWORD cbToWrite)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006927{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006928 COORD coord = g_coord;
6929 DWORD written;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006930 DWORD n, cchwritten;
6931 static DWORD cells;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006932 static WCHAR *unicodebuf = NULL;
6933 static int unibuflen = 0;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006934 static int length;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006935 int cp = enc_utf8 ? CP_UTF8 : enc_codepage;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006936 static WCHAR *utf8spbuf = NULL;
6937 static int utf8splength;
6938 static DWORD utf8spcells;
6939 static WCHAR **utf8usingbuf = &unicodebuf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006940
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006941 if (cbToWrite != 1 || *pchBuf != ' ' || !enc_utf8)
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006942 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006943 utf8usingbuf = &unicodebuf;
6944 do
6945 {
6946 length = MultiByteToWideChar(cp, 0, (LPCSTR)pchBuf, cbToWrite,
6947 unicodebuf, unibuflen);
6948 if (length && length <= unibuflen)
6949 break;
6950 vim_free(unicodebuf);
6951 unicodebuf = length ? LALLOC_MULT(WCHAR, length) : NULL;
6952 unibuflen = unibuflen ? 0 : length;
Bram Moolenaarc9471b12023-05-09 15:00:00 +01006953 } while (TRUE);
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006954 cells = mb_string2cells(pchBuf, cbToWrite);
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006955 }
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006956 else // cbToWrite == 1 && *pchBuf == ' ' && enc_utf8
6957 {
6958 if (utf8usingbuf != &utf8spbuf)
6959 {
6960 if (utf8spbuf == NULL)
6961 {
6962 cells = mb_string2cells((char_u *)" ", 1);
6963 length = MultiByteToWideChar(CP_UTF8, 0, " ", 1, NULL, 0);
6964 utf8spbuf = LALLOC_MULT(WCHAR, length);
6965 if (utf8spbuf != NULL)
6966 {
6967 MultiByteToWideChar(CP_UTF8, 0, " ", 1, utf8spbuf, length);
6968 utf8usingbuf = &utf8spbuf;
6969 utf8splength = length;
6970 utf8spcells = cells;
6971 }
6972 }
6973 else
6974 {
6975 utf8usingbuf = &utf8spbuf;
6976 length = utf8splength;
6977 cells = utf8spcells;
6978 }
6979 }
6980 }
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006981
Christopher Plewrightf75a2cb2023-01-28 10:28:09 +00006982 if (!USE_VTP)
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006983 {
6984 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, cells,
6985 coord, &written);
6986 // When writing fails or didn't write a single character, pretend one
6987 // character was written, otherwise we get stuck.
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006988 if (WriteConsoleOutputCharacterW(g_hConOut, *utf8usingbuf, length,
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006989 coord, &cchwritten) == 0
6990 || cchwritten == 0 || cchwritten == (DWORD)-1)
6991 cchwritten = 1;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006992 }
6993 else
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006994 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006995 if (WriteConsoleW(g_hConOut, *utf8usingbuf, length, &cchwritten,
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006996 NULL) == 0 || cchwritten == 0)
6997 cchwritten = 1;
6998 }
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006999
K.Takata135e1522022-01-29 15:27:58 +00007000 if (cchwritten == (DWORD)length)
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007001 {
7002 written = cbToWrite;
7003 g_coord.X += (SHORT)cells;
7004 }
7005 else
7006 {
7007 char_u *p = pchBuf;
7008 for (n = 0; n < cchwritten; n++)
7009 MB_CPTR_ADV(p);
7010 written = p - pchBuf;
7011 g_coord.X += (SHORT)mb_string2cells(pchBuf, written);
Bram Moolenaarac360bf2015-09-01 20:31:20 +02007012 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007013
7014 while (g_coord.X > g_srScrollRegion.Right)
7015 {
7016 g_coord.X -= (SHORT) Columns;
7017 if (g_coord.Y < g_srScrollRegion.Bottom)
7018 g_coord.Y++;
7019 }
7020
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007021 // Cursor under VTP is always in the correct position, no need to reset.
Christopher Plewrightf75a2cb2023-01-28 10:28:09 +00007022 if (!USE_VTP)
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007023 gotoxy(g_coord.X + 1, g_coord.Y + 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007024
7025 return written;
7026}
7027
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007028 static char_u *
7029get_seq(
7030 int *args,
7031 int *count,
7032 char_u *head)
7033{
7034 int argc;
7035 char_u *p;
7036
7037 if (head == NULL || *head != '\033')
7038 return NULL;
7039
7040 argc = 0;
7041 p = head;
7042 ++p;
7043 do
7044 {
7045 ++p;
7046 args[argc] = getdigits(&p);
7047 argc += (argc < 15) ? 1 : 0;
7048 } while (*p == ';');
7049 *count = argc;
7050
7051 return p;
7052}
7053
7054 static char_u *
7055get_sgr(
7056 int *args,
7057 int *count,
7058 char_u *head)
7059{
7060 char_u *p = get_seq(args, count, head);
7061
7062 return (p && *p == 'm') ? ++p : NULL;
7063}
7064
7065/*
7066 * Pointer to next if SGR (^[[n;2;*;*;*m), NULL otherwise.
7067 */
7068 static char_u *
7069sgrn2(
7070 char_u *head,
7071 int n)
7072{
7073 int argc;
7074 int args[16];
7075 char_u *p = get_sgr(args, &argc, head);
7076
7077 return p && argc == 5 && args[0] == n && args[1] == 2 ? p : NULL;
7078}
7079
7080/*
7081 * Pointer to next if SGR(^[[nm)<space>ESC, NULL otherwise.
7082 */
7083 static char_u *
7084sgrnc(
7085 char_u *head,
7086 int n)
7087{
7088 int argc;
7089 int args[16];
7090 char_u *p = get_sgr(args, &argc, head);
7091
7092 return p && argc == 1 && args[0] == n && (p = skipwhite(p)) && *p == '\033'
7093 ? p : NULL;
7094}
7095
7096 static char_u *
7097skipblank(char_u *q)
7098{
7099 char_u *p = q;
7100
7101 while (*p == ' ' || *p == '\t' || *p == '\n' || *p == '\r')
7102 ++p;
7103 return p;
7104}
7105
7106/*
7107 * Pointer to the next if any whitespace that may follow SGR is ESC, otherwise
7108 * NULL.
7109 */
7110 static char_u *
7111sgrn2c(
7112 char_u *head,
7113 int n)
7114{
7115 char_u *p = sgrn2(head, n);
7116
7117 return p && *p != NUL && (p = skipblank(p)) && *p == '\033' ? p : NULL;
7118}
7119
7120/*
7121 * If there is only a newline between the sequence immediately following it,
7122 * a pointer to the character following the newline is returned.
7123 * Otherwise NULL.
7124 */
7125 static char_u *
7126sgrn2cn(
7127 char_u *head,
7128 int n)
7129{
7130 char_u *p = sgrn2(head, n);
7131
7132 return p && p[0] == 0x0a && p[1] == '\033' ? ++p : NULL;
7133}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007134
7135/*
7136 * mch_write(): write the output buffer to the screen, translating ESC
7137 * sequences into calls to console output routines.
7138 */
7139 void
7140mch_write(
7141 char_u *s,
7142 int len)
7143{
Bram Moolenaard23f8bd2021-04-21 11:30:48 +02007144 char_u *end = s + len;
7145
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007146# ifdef VIMDLL
7147 if (gui.in_use)
7148 return;
7149# endif
7150
Bram Moolenaar071d4272004-06-13 20:20:40 +00007151 if (!term_console)
7152 {
7153 write(1, s, (unsigned)len);
7154 return;
7155 }
7156
Bram Moolenaar0f873732019-12-05 20:28:46 +01007157 // translate ESC | sequences into faked bios calls
Bram Moolenaar071d4272004-06-13 20:20:40 +00007158 while (len--)
7159 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007160 int prefix = -1;
7161 char_u ch;
7162
7163 // While processing a sequence, on rare occasions it seems that another
7164 // sequence may be inserted asynchronously.
7165 if (len < 0)
7166 {
Bram Moolenaara4d158b2022-08-14 14:17:45 +01007167 redraw_all_later(UPD_CLEAR);
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007168 return;
7169 }
7170
Bram Moolenaard23f8bd2021-04-21 11:30:48 +02007171 while (s + ++prefix < end)
7172 {
7173 ch = s[prefix];
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007174 if (ch <= 0x1e && !(ch != '\n' && ch != '\r' && ch != '\b'
7175 && ch != '\a' && ch != '\033'))
7176 break;
Bram Moolenaard23f8bd2021-04-21 11:30:48 +02007177 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007178
7179 if (p_wd)
7180 {
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02007181 WaitForChar(p_wd, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007182 if (prefix != 0)
7183 prefix = 1;
7184 }
7185
7186 if (prefix != 0)
7187 {
7188 DWORD nWritten;
7189
7190 nWritten = write_chars(s, prefix);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007191# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00007192 if (fdDump)
7193 {
7194 fputc('>', fdDump);
7195 fwrite(s, sizeof(char_u), nWritten, fdDump);
7196 fputs("<\n", fdDump);
7197 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007198# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007199 len -= (nWritten - 1);
7200 s += nWritten;
7201 }
7202 else if (s[0] == '\n')
7203 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007204 // \n, newline: go to the beginning of the next line or scroll
Bram Moolenaar071d4272004-06-13 20:20:40 +00007205 if (g_coord.Y == g_srScrollRegion.Bottom)
7206 {
7207 scroll(1);
7208 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Bottom + 1);
7209 }
7210 else
7211 {
7212 gotoxy(g_srScrollRegion.Left + 1, g_coord.Y + 2);
7213 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007214# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00007215 if (fdDump)
7216 fputs("\\n\n", fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007217# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007218 s++;
7219 }
7220 else if (s[0] == '\r')
7221 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007222 // \r, carriage return: go to beginning of line
Bram Moolenaar071d4272004-06-13 20:20:40 +00007223 gotoxy(g_srScrollRegion.Left+1, g_coord.Y + 1);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007224# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00007225 if (fdDump)
7226 fputs("\\r\n", fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007227# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007228 s++;
7229 }
7230 else if (s[0] == '\b')
7231 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007232 // \b, backspace: move cursor one position left
Bram Moolenaar071d4272004-06-13 20:20:40 +00007233 if (g_coord.X > g_srScrollRegion.Left)
7234 g_coord.X--;
7235 else if (g_coord.Y > g_srScrollRegion.Top)
7236 {
7237 g_coord.X = g_srScrollRegion.Right;
7238 g_coord.Y--;
7239 }
7240 gotoxy(g_coord.X + 1, g_coord.Y + 1);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007241# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00007242 if (fdDump)
7243 fputs("\\b\n", fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007244# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007245 s++;
7246 }
7247 else if (s[0] == '\a')
7248 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007249 // \a, bell
Bram Moolenaar071d4272004-06-13 20:20:40 +00007250 MessageBeep(0xFFFFFFFF);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007251# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00007252 if (fdDump)
7253 fputs("\\a\n", fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007254# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007255 s++;
7256 }
7257 else if (s[0] == ESC && len >= 3-1 && s[1] == '|')
7258 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007259# ifdef MCH_WRITE_DUMP
Bram Moolenaarc0197e22004-09-13 20:26:32 +00007260 char_u *old_s = s;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007261# endif
Bram Moolenaarc0197e22004-09-13 20:26:32 +00007262 char_u *p;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007263 int arg1 = 0, arg2 = 0, argc = 0, args[16];
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007264 char_u *sp;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007265
7266 switch (s[2])
7267 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00007268 case '0': case '1': case '2': case '3': case '4':
7269 case '5': case '6': case '7': case '8': case '9':
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007270 if (*(p = get_seq(args, &argc, s)) != 'm')
7271 goto notsgr;
7272
7273 p = s;
7274
7275 // Handling frequent optional sequences. Output to the screen
7276 // takes too long, so do not output as much as possible.
7277
7278 // If resetFG,FG,BG,<cr>,BG,FG are connected, the preceding
7279 // resetFG,FG,BG are omitted.
7280 if (sgrn2(sgrn2(sgrn2cn(sgrn2(sgrnc(p, 39), 38), 48), 48), 38))
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007281 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007282 p = sgrn2(sgrn2(sgrnc(p, 39), 38), 48);
7283 len = len + 1 - (int)(p - s);
7284 s = p;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007285 break;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007286 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007287
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007288 // If FG,BG,BG,FG of SGR are connected, the first FG can be
7289 // omitted.
7290 if (sgrn2(sgrn2(sgrn2c((sp = sgrn2(p, 38)), 48), 48), 38))
7291 p = sp;
7292
7293 // If FG,BG,FG,BG of SGR are connected, the first FG can be
7294 // omitted.
7295 if (sgrn2(sgrn2(sgrn2c((sp = sgrn2(p, 38)), 48), 38), 48))
7296 p = sp;
7297
7298 // If BG,BG of SGR are connected, the first BG can be omitted.
7299 if (sgrn2((sp = sgrn2(p, 48)), 48))
7300 p = sp;
7301
7302 // If restoreFG and FG are connected, the restoreFG can be
Bram Moolenaar9f1983d2022-05-12 20:35:35 +01007303 // omitted.
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007304 if (sgrn2((sp = sgrnc(p, 39)), 38))
7305 p = sp;
7306
7307 p = get_seq(args, &argc, p);
7308
7309notsgr:
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007310 arg1 = args[0];
7311 arg2 = args[1];
7312 if (*p == 'm')
Bram Moolenaar071d4272004-06-13 20:20:40 +00007313 {
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007314 if (argc == 1 && args[0] == 0)
7315 normvideo();
7316 else if (argc == 1)
7317 {
Christopher Plewrightf75a2cb2023-01-28 10:28:09 +00007318 if (USE_VTP)
Christopher Plewright38804d62022-11-09 23:55:52 +00007319 textcolor((WORD)arg1);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007320 else
Christopher Plewright38804d62022-11-09 23:55:52 +00007321 textattr((WORD)arg1);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007322 }
Christopher Plewright38804d62022-11-09 23:55:52 +00007323 else if (vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007324 vtp_sgr_bulks(argc, args);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007325 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007326 else if (argc == 2 && *p == 'H')
Bram Moolenaar071d4272004-06-13 20:20:40 +00007327 {
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007328 gotoxy(arg2, arg1);
7329 }
7330 else if (argc == 2 && *p == 'r')
7331 {
7332 set_scroll_region(0, arg1 - 1, Columns - 1, arg2 - 1);
7333 }
Bram Moolenaar6982f422019-02-16 16:48:01 +01007334 else if (argc == 2 && *p == 'R')
7335 {
7336 set_scroll_region_tb(arg1, arg2);
7337 }
7338 else if (argc == 2 && *p == 'V')
7339 {
7340 set_scroll_region_lr(arg1, arg2);
7341 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007342 else if (argc == 1 && *p == 'A')
7343 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00007344 gotoxy(g_coord.X + 1,
7345 max(g_srScrollRegion.Top, g_coord.Y - arg1) + 1);
7346 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007347 else if (argc == 1 && *p == 'b')
Bram Moolenaar071d4272004-06-13 20:20:40 +00007348 {
7349 textbackground((WORD) arg1);
7350 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007351 else if (argc == 1 && *p == 'C')
7352 {
7353 gotoxy(min(g_srScrollRegion.Right, g_coord.X + arg1) + 1,
7354 g_coord.Y + 1);
7355 }
7356 else if (argc == 1 && *p == 'f')
7357 {
7358 textcolor((WORD) arg1);
7359 }
7360 else if (argc == 1 && *p == 'H')
7361 {
7362 gotoxy(1, arg1);
7363 }
7364 else if (argc == 1 && *p == 'L')
7365 {
7366 insert_lines(arg1);
7367 }
7368 else if (argc == 1 && *p == 'M')
Bram Moolenaar071d4272004-06-13 20:20:40 +00007369 {
7370 delete_lines(arg1);
7371 }
7372
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007373 len -= (int)(p - s);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007374 s = p + 1;
7375 break;
7376
Bram Moolenaar071d4272004-06-13 20:20:40 +00007377 case 'A':
Bram Moolenaar071d4272004-06-13 20:20:40 +00007378 gotoxy(g_coord.X + 1,
7379 max(g_srScrollRegion.Top, g_coord.Y - 1) + 1);
7380 goto got3;
7381
7382 case 'B':
7383 visual_bell();
7384 goto got3;
7385
7386 case 'C':
Bram Moolenaar071d4272004-06-13 20:20:40 +00007387 gotoxy(min(g_srScrollRegion.Right, g_coord.X + 1) + 1,
7388 g_coord.Y + 1);
7389 goto got3;
7390
7391 case 'E':
7392 termcap_mode_end();
7393 goto got3;
7394
7395 case 'F':
7396 standout();
7397 goto got3;
7398
7399 case 'f':
7400 standend();
7401 goto got3;
7402
7403 case 'H':
7404 gotoxy(1, 1);
7405 goto got3;
7406
7407 case 'j':
7408 clear_to_end_of_display();
7409 goto got3;
7410
7411 case 'J':
7412 clear_screen();
7413 goto got3;
7414
7415 case 'K':
7416 clear_to_end_of_line();
7417 goto got3;
7418
7419 case 'L':
7420 insert_lines(1);
7421 goto got3;
7422
7423 case 'M':
7424 delete_lines(1);
7425 goto got3;
7426
7427 case 'S':
7428 termcap_mode_start();
7429 goto got3;
7430
7431 case 'V':
7432 cursor_visible(TRUE);
7433 goto got3;
7434
7435 case 'v':
7436 cursor_visible(FALSE);
7437 goto got3;
7438
7439 got3:
7440 s += 3;
7441 len -= 2;
7442 }
7443
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007444# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00007445 if (fdDump)
7446 {
7447 fputs("ESC | ", fdDump);
7448 fwrite(old_s + 2, sizeof(char_u), s - old_s - 2, fdDump);
7449 fputc('\n', fdDump);
7450 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007451# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007452 }
K.Takatadf5320c2022-09-01 13:20:16 +01007453 else if (s[0] == ESC && len >= 3-1 && s[1] == '[')
7454 {
7455 int l = 2;
7456
Keith Thompson184f71c2024-01-04 21:19:04 +01007457 if (SAFE_isdigit(s[l]))
K.Takatadf5320c2022-09-01 13:20:16 +01007458 l++;
7459 if (s[l] == ' ' && s[l + 1] == 'q')
7460 {
7461 // DECSCUSR (cursor style) sequences
Christopher Plewright38804d62022-11-09 23:55:52 +00007462 if (vtp_working)
K.Takatadf5320c2022-09-01 13:20:16 +01007463 vtp_printf("%.*s", l + 2, s); // Pass through
7464 s += l + 2;
7465 len -= l + 1;
7466 }
7467 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007468 else
7469 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007470 // Write a single character
Bram Moolenaar071d4272004-06-13 20:20:40 +00007471 DWORD nWritten;
7472
7473 nWritten = write_chars(s, 1);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007474# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00007475 if (fdDump)
7476 {
7477 fputc('>', fdDump);
7478 fwrite(s, sizeof(char_u), nWritten, fdDump);
7479 fputs("<\n", fdDump);
7480 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007481# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007482
7483 len -= (nWritten - 1);
7484 s += nWritten;
7485 }
7486 }
7487
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007488# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00007489 if (fdDump)
7490 fflush(fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007491# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007492}
7493
Bram Moolenaar0f873732019-12-05 20:28:46 +01007494#endif // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00007495
7496
7497/*
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01007498 * Delay for "msec" milliseconds.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007499 */
7500 void
7501mch_delay(
7502 long msec,
Bram Moolenaar0981c872020-08-23 14:28:37 +02007503 int flags UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007504{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007505#if defined(FEAT_GUI_MSWIN) && !defined(VIMDLL)
Bram Moolenaar0f873732019-12-05 20:28:46 +01007506 Sleep((int)msec); // never wait for input
7507#else // Console
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007508# ifdef VIMDLL
7509 if (gui.in_use)
7510 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007511 Sleep((int)msec); // never wait for input
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007512 return;
7513 }
7514# endif
Bram Moolenaar0981c872020-08-23 14:28:37 +02007515 if (flags & MCH_DELAY_IGNOREINPUT)
Bram Moolenaar325b7a22004-07-05 15:58:32 +00007516# ifdef FEAT_MZSCHEME
7517 if (mzthreads_allowed() && p_mzq > 0 && msec > p_mzq)
7518 {
7519 int towait = p_mzq;
7520
Bram Moolenaar0f873732019-12-05 20:28:46 +01007521 // if msec is large enough, wait by portions in p_mzq
Bram Moolenaar325b7a22004-07-05 15:58:32 +00007522 while (msec > 0)
7523 {
7524 mzvim_check_threads();
7525 if (msec < towait)
7526 towait = msec;
7527 Sleep(towait);
7528 msec -= towait;
7529 }
7530 }
7531 else
7532# endif
7533 Sleep((int)msec);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007534 else
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02007535 WaitForChar(msec, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007536#endif
7537}
7538
7539
7540/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01007541 * This version of remove is not scared by a readonly (backup) file.
7542 * This can also remove a symbolic link like Unix.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007543 * Return 0 for success, -1 for failure.
7544 */
7545 int
7546mch_remove(char_u *name)
7547{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007548 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007549 int n;
7550
Bram Moolenaar203258c2016-01-17 22:15:16 +01007551 /*
7552 * On Windows, deleting a directory's symbolic link is done by
7553 * RemoveDirectory(): mch_rmdir. It seems unnatural, but it is fact.
7554 */
7555 if (mch_isdir(name) && mch_is_symbolic_link(name))
7556 return mch_rmdir(name);
7557
Bram Moolenaar12b559e2013-06-12 22:41:37 +02007558 win32_setattrs(name, FILE_ATTRIBUTE_NORMAL);
7559
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007560 wn = enc_to_utf16(name, NULL);
7561 if (wn == NULL)
7562 return -1;
7563
7564 n = DeleteFileW(wn) ? 0 : -1;
7565 vim_free(wn);
7566 return n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007567}
7568
7569
7570/*
Bram Moolenaarb9c31e72016-09-29 15:18:57 +02007571 * Check for an "interrupt signal": CTRL-break or CTRL-C.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007572 */
7573 void
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02007574mch_breakcheck(int force UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007575{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007576#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
7577# ifdef VIMDLL
7578 if (!gui.in_use)
7579# endif
7580 if (g_fCtrlCPressed || g_fCBrkPressed)
7581 {
7582 ctrl_break_was_pressed = g_fCBrkPressed;
7583 g_fCtrlCPressed = g_fCBrkPressed = FALSE;
7584 got_int = TRUE;
7585 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007586#endif
7587}
7588
Bram Moolenaar0f873732019-12-05 20:28:46 +01007589// physical RAM to leave for the OS
Bram Moolenaaree273972016-01-02 21:11:51 +01007590#define WINNT_RESERVE_BYTES (256*1024*1024)
Bram Moolenaaree273972016-01-02 21:11:51 +01007591
7592/*
7593 * How much main memory in KiB that can be used by VIM.
7594 */
Bram Moolenaaree273972016-01-02 21:11:51 +01007595 long_u
Bram Moolenaar1266d672017-02-01 13:43:36 +01007596mch_total_mem(int special UNUSED)
Bram Moolenaaree273972016-01-02 21:11:51 +01007597{
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007598 MEMORYSTATUSEX ms;
7599
Bram Moolenaar0f873732019-12-05 20:28:46 +01007600 // Need to use GlobalMemoryStatusEx() when there is more memory than
7601 // what fits in 32 bits.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007602 ms.dwLength = sizeof(MEMORYSTATUSEX);
7603 GlobalMemoryStatusEx(&ms);
7604 if (ms.ullAvailVirtual < ms.ullTotalPhys)
Bram Moolenaaree273972016-01-02 21:11:51 +01007605 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007606 // Process address space fits in physical RAM, use all of it.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007607 return (long_u)(ms.ullAvailVirtual / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01007608 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007609 if (ms.ullTotalPhys <= WINNT_RESERVE_BYTES)
Bram Moolenaaree273972016-01-02 21:11:51 +01007610 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007611 // Catch old NT box or perverse hardware setup.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007612 return (long_u)((ms.ullTotalPhys / 2) / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01007613 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01007614 // Use physical RAM less reserve for OS + data.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007615 return (long_u)((ms.ullTotalPhys - WINNT_RESERVE_BYTES) / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01007616}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007617
Bram Moolenaar071d4272004-06-13 20:20:40 +00007618/*
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007619 * mch_wrename() works around a bug in rename (aka MoveFile) in
Bram Moolenaar071d4272004-06-13 20:20:40 +00007620 * Windows 95: rename("foo.bar", "foo.bar~") will generate a
7621 * file whose short file name is "FOO.BAR" (its long file name will
7622 * be correct: "foo.bar~"). Because a file can be accessed by
7623 * either its SFN or its LFN, "foo.bar" has effectively been
7624 * renamed to "foo.bar", which is not at all what was wanted. This
7625 * seems to happen only when renaming files with three-character
7626 * extensions by appending a suffix that does not include ".".
7627 * Windows NT gets it right, however, with an SFN of "FOO~1.BAR".
7628 *
7629 * There is another problem, which isn't really a bug but isn't right either:
7630 * When renaming "abcdef~1.txt" to "abcdef~1.txt~", the short name can be
7631 * "abcdef~1.txt" again. This has been reported on Windows NT 4.0 with
7632 * service pack 6. Doesn't seem to happen on Windows 98.
7633 *
7634 * Like rename(), returns 0 upon success, non-zero upon failure.
7635 * Should probably set errno appropriately when errors occur.
7636 */
7637 int
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007638mch_wrename(WCHAR *wold, WCHAR *wnew)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007639{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007640 WCHAR *p;
7641 int i;
7642 WCHAR szTempFile[_MAX_PATH + 1];
7643 WCHAR szNewPath[_MAX_PATH + 1];
Bram Moolenaar071d4272004-06-13 20:20:40 +00007644 HANDLE hf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007645
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007646 // No need to play tricks unless the file name contains a "~" as the
7647 // seventh character.
7648 p = wold;
7649 for (i = 0; wold[i] != NUL; ++i)
7650 if ((wold[i] == '/' || wold[i] == '\\' || wold[i] == ':')
7651 && wold[i + 1] != 0)
7652 p = wold + i + 1;
7653 if ((int)(wold + i - p) < 8 || p[6] != '~')
7654 return (MoveFileW(wold, wnew) == 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007655
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007656 // Get base path of new file name. Undocumented feature: If pszNewFile is
7657 // a directory, no error is returned and pszFilePart will be NULL.
7658 if (GetFullPathNameW(wnew, _MAX_PATH, szNewPath, &p) == 0 || p == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007659 return -1;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007660 *p = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007661
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007662 // Get (and create) a unique temporary file name in directory of new file
7663 if (GetTempFileNameW(szNewPath, L"VIM", 0, szTempFile) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007664 return -2;
7665
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007666 // blow the temp file away
7667 if (!DeleteFileW(szTempFile))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007668 return -3;
7669
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007670 // rename old file to the temp file
7671 if (!MoveFileW(wold, szTempFile))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007672 return -4;
7673
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007674 // now create an empty file called pszOldFile; this prevents the operating
7675 // system using pszOldFile as an alias (SFN) if we're renaming within the
7676 // same directory. For example, we're editing a file called
7677 // filename.asc.txt by its SFN, filena~1.txt. If we rename filena~1.txt
7678 // to filena~1.txt~ (i.e., we're making a backup while writing it), the
7679 // SFN for filena~1.txt~ will be filena~1.txt, by default, which will
7680 // cause all sorts of problems later in buf_write(). So, we create an
7681 // empty file called filena~1.txt and the system will have to find some
7682 // other SFN for filena~1.txt~, such as filena~2.txt
7683 if ((hf = CreateFileW(wold, GENERIC_WRITE, 0, NULL, CREATE_NEW,
Bram Moolenaar071d4272004-06-13 20:20:40 +00007684 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
7685 return -5;
7686 if (!CloseHandle(hf))
7687 return -6;
7688
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007689 // rename the temp file to the new file
7690 if (!MoveFileW(szTempFile, wnew))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007691 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007692 // Renaming failed. Rename the file back to its old name, so that it
7693 // looks like nothing happened.
7694 (void)MoveFileW(szTempFile, wold);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007695 return -7;
7696 }
7697
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007698 // Seems to be left around on Novell filesystems
7699 DeleteFileW(szTempFile);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007700
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007701 // finally, remove the empty old file
7702 if (!DeleteFileW(wold))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007703 return -8;
7704
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007705 return 0;
7706}
7707
7708
7709/*
7710 * Converts the filenames to UTF-16, then call mch_wrename().
7711 * Like rename(), returns 0 upon success, non-zero upon failure.
7712 */
7713 int
7714mch_rename(
7715 const char *pszOldFile,
7716 const char *pszNewFile)
7717{
7718 WCHAR *wold = NULL;
7719 WCHAR *wnew = NULL;
7720 int retval = -1;
7721
7722 wold = enc_to_utf16((char_u *)pszOldFile, NULL);
7723 wnew = enc_to_utf16((char_u *)pszNewFile, NULL);
7724 if (wold != NULL && wnew != NULL)
7725 retval = mch_wrename(wold, wnew);
7726 vim_free(wold);
7727 vim_free(wnew);
7728 return retval;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007729}
7730
7731/*
7732 * Get the default shell for the current hardware platform
7733 */
7734 char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007735default_shell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007736{
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007737 return "cmd.exe";
Bram Moolenaar071d4272004-06-13 20:20:40 +00007738}
7739
7740/*
7741 * mch_access() extends access() to do more detailed check on network drives.
7742 * Returns 0 if file "n" has access rights according to "p", -1 otherwise.
7743 */
7744 int
7745mch_access(char *n, int p)
7746{
7747 HANDLE hFile;
Bram Moolenaar0f873732019-12-05 20:28:46 +01007748 int retval = -1; // default: fail
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007749 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007750
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007751 wn = enc_to_utf16((char_u *)n, NULL);
7752 if (wn == NULL)
7753 return -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007754
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01007755 if (mch_isdir((char_u *)n))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007756 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00007757 WCHAR TempNameW[_MAX_PATH + 16] = L"";
Bram Moolenaar071d4272004-06-13 20:20:40 +00007758
7759 if (p & R_OK)
7760 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007761 // Read check is performed by seeing if we can do a find file on
7762 // the directory for any file.
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007763 int i;
7764 WIN32_FIND_DATAW d;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007765
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007766 for (i = 0; i < _MAX_PATH && wn[i] != 0; ++i)
7767 TempNameW[i] = wn[i];
7768 if (TempNameW[i - 1] != '\\' && TempNameW[i - 1] != '/')
7769 TempNameW[i++] = '\\';
7770 TempNameW[i++] = '*';
7771 TempNameW[i++] = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007772
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007773 hFile = FindFirstFileW(TempNameW, &d);
7774 if (hFile == INVALID_HANDLE_VALUE)
7775 goto getout;
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007776 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00007777 (void)FindClose(hFile);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007778 }
7779
7780 if (p & W_OK)
7781 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007782 // Trying to create a temporary file in the directory should catch
7783 // directories on read-only network shares. However, in
7784 // directories whose ACL allows writes but denies deletes will end
7785 // up keeping the temporary file :-(.
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007786 if (!GetTempFileNameW(wn, L"VIM", 0, TempNameW))
7787 goto getout;
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007788 else
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007789 DeleteFileW(TempNameW);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007790 }
7791 }
7792 else
7793 {
Bram Moolenaar5aa98962018-05-06 17:09:38 +02007794 // Don't consider a file read-only if another process has opened it.
7795 DWORD share_mode = FILE_SHARE_READ | FILE_SHARE_WRITE;
7796
Bram Moolenaar0f873732019-12-05 20:28:46 +01007797 // Trying to open the file for the required access does ACL, read-only
7798 // network share, and file attribute checks.
Bram Moolenaar5aa98962018-05-06 17:09:38 +02007799 DWORD access_mode = ((p & W_OK) ? GENERIC_WRITE : 0)
7800 | ((p & R_OK) ? GENERIC_READ : 0);
7801
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007802 hFile = CreateFileW(wn, access_mode, share_mode,
7803 NULL, OPEN_EXISTING, 0, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007804 if (hFile == INVALID_HANDLE_VALUE)
7805 goto getout;
7806 CloseHandle(hFile);
7807 }
7808
Bram Moolenaar0f873732019-12-05 20:28:46 +01007809 retval = 0; // success
Bram Moolenaar071d4272004-06-13 20:20:40 +00007810getout:
Bram Moolenaar071d4272004-06-13 20:20:40 +00007811 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007812 return retval;
7813}
7814
Bram Moolenaar071d4272004-06-13 20:20:40 +00007815/*
Bram Moolenaar36f692d2008-11-20 16:10:17 +00007816 * Version of open() that may use UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007817 */
7818 int
Bram Moolenaarb6843a02017-08-02 22:07:12 +02007819mch_open(const char *name, int flags, int mode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007820{
7821 WCHAR *wn;
7822 int f;
7823
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007824 wn = enc_to_utf16((char_u *)name, NULL);
7825 if (wn == NULL)
7826 return -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007827
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007828 f = _wopen(wn, flags, mode);
7829 vim_free(wn);
7830 return f;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007831}
7832
7833/*
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007834 * Version of fopen() that uses UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007835 */
7836 FILE *
Bram Moolenaarb6843a02017-08-02 22:07:12 +02007837mch_fopen(const char *name, const char *mode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007838{
7839 WCHAR *wn, *wm;
7840 FILE *f = NULL;
7841
Bram Moolenaara12a1612019-01-24 16:39:02 +01007842#if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0f873732019-12-05 20:28:46 +01007843 // Work around an annoying assertion in the Microsoft debug CRT
7844 // when mode's text/binary setting doesn't match _get_fmode().
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007845 char newMode = mode[strlen(mode) - 1];
7846 int oldMode = 0;
Bram Moolenaar0fde2902008-03-16 13:54:13 +00007847
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007848 _get_fmode(&oldMode);
7849 if (newMode == 't')
7850 _set_fmode(_O_TEXT);
7851 else if (newMode == 'b')
7852 _set_fmode(_O_BINARY);
Bram Moolenaara12a1612019-01-24 16:39:02 +01007853#endif
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007854 wn = enc_to_utf16((char_u *)name, NULL);
7855 wm = enc_to_utf16((char_u *)mode, NULL);
7856 if (wn != NULL && wm != NULL)
7857 f = _wfopen(wn, wm);
7858 vim_free(wn);
7859 vim_free(wm);
Bram Moolenaar0fde2902008-03-16 13:54:13 +00007860
Bram Moolenaara12a1612019-01-24 16:39:02 +01007861#if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007862 _set_fmode(oldMode);
Bram Moolenaara12a1612019-01-24 16:39:02 +01007863#endif
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007864 return f;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007865}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007866
Bram Moolenaar071d4272004-06-13 20:20:40 +00007867/*
7868 * SUB STREAM (aka info stream) handling:
7869 *
Bram Moolenaar8e7d6222020-12-18 19:49:56 +01007870 * NTFS can have sub streams for each file. The normal contents of a file is
7871 * stored in the main stream, and extra contents (author information, title and
7872 * so on) can be stored in a sub stream. After Windows 2000, the user can
7873 * access and store this information in sub streams via an explorer's property
7874 * menu item in the right click menu. This information in sub streams was lost
7875 * when copying only the main stream. Therefore we have to copy sub streams.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007876 *
7877 * Incomplete explanation:
7878 * http://msdn.microsoft.com/library/en-us/dnw2k/html/ntfs5.asp
7879 * More useful info and an example:
7880 * http://www.sysinternals.com/ntw2k/source/misc.shtml#streams
7881 */
7882
7883/*
7884 * Copy info stream data "substream". Read from the file with BackupRead(sh)
7885 * and write to stream "substream" of file "to".
7886 * Errors are ignored.
7887 */
7888 static void
7889copy_substream(HANDLE sh, void *context, WCHAR *to, WCHAR *substream, long len)
7890{
7891 HANDLE hTo;
7892 WCHAR *to_name;
7893
7894 to_name = malloc((wcslen(to) + wcslen(substream) + 1) * sizeof(WCHAR));
7895 wcscpy(to_name, to);
7896 wcscat(to_name, substream);
7897
7898 hTo = CreateFileW(to_name, GENERIC_WRITE, 0, NULL, OPEN_ALWAYS,
7899 FILE_ATTRIBUTE_NORMAL, NULL);
7900 if (hTo != INVALID_HANDLE_VALUE)
7901 {
7902 long done;
7903 DWORD todo;
7904 DWORD readcnt, written;
7905 char buf[4096];
7906
Bram Moolenaar0f873732019-12-05 20:28:46 +01007907 // Copy block of bytes at a time. Abort when something goes wrong.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007908 for (done = 0; done < len; done += written)
7909 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007910 // (size_t) cast for Borland C 5.5
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007911 todo = (DWORD)((size_t)(len - done) > sizeof(buf) ? sizeof(buf)
7912 : (size_t)(len - done));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007913 if (!BackupRead(sh, (LPBYTE)buf, todo, &readcnt,
7914 FALSE, FALSE, context)
7915 || readcnt != todo
7916 || !WriteFile(hTo, buf, todo, &written, NULL)
7917 || written != todo)
7918 break;
7919 }
7920 CloseHandle(hTo);
7921 }
7922
7923 free(to_name);
7924}
7925
7926/*
7927 * Copy info streams from file "from" to file "to".
7928 */
7929 static void
7930copy_infostreams(char_u *from, char_u *to)
7931{
7932 WCHAR *fromw;
7933 WCHAR *tow;
7934 HANDLE sh;
7935 WIN32_STREAM_ID sid;
7936 int headersize;
7937 WCHAR streamname[_MAX_PATH];
7938 DWORD readcount;
7939 void *context = NULL;
7940 DWORD lo, hi;
7941 int len;
7942
Bram Moolenaar0f873732019-12-05 20:28:46 +01007943 // Convert the file names to wide characters.
Bram Moolenaar36f692d2008-11-20 16:10:17 +00007944 fromw = enc_to_utf16(from, NULL);
7945 tow = enc_to_utf16(to, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007946 if (fromw != NULL && tow != NULL)
7947 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007948 // Open the file for reading.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007949 sh = CreateFileW(fromw, GENERIC_READ, FILE_SHARE_READ, NULL,
7950 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
7951 if (sh != INVALID_HANDLE_VALUE)
7952 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007953 // Use BackupRead() to find the info streams. Repeat until we
7954 // have done them all.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007955 for (;;)
7956 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007957 // Get the header to find the length of the stream name. If
7958 // the "readcount" is zero we have done all info streams.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007959 ZeroMemory(&sid, sizeof(WIN32_STREAM_ID));
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007960 headersize = (int)((char *)&sid.cStreamName - (char *)&sid.dwStreamId);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007961 if (!BackupRead(sh, (LPBYTE)&sid, headersize,
7962 &readcount, FALSE, FALSE, &context)
7963 || readcount == 0)
7964 break;
7965
Bram Moolenaar0f873732019-12-05 20:28:46 +01007966 // We only deal with streams that have a name. The normal
7967 // file data appears to be without a name, even though docs
7968 // suggest it is called "::$DATA".
Bram Moolenaar071d4272004-06-13 20:20:40 +00007969 if (sid.dwStreamNameSize > 0)
7970 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007971 // Read the stream name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007972 if (!BackupRead(sh, (LPBYTE)streamname,
7973 sid.dwStreamNameSize,
7974 &readcount, FALSE, FALSE, &context))
7975 break;
7976
Bram Moolenaar0f873732019-12-05 20:28:46 +01007977 // Copy an info stream with a name ":anything:$DATA".
7978 // Skip "::$DATA", it has no stream name (examples suggest
7979 // it might be used for the normal file contents).
7980 // Note that BackupRead() counts bytes, but the name is in
7981 // wide characters.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007982 len = readcount / sizeof(WCHAR);
7983 streamname[len] = 0;
7984 if (len > 7 && wcsicmp(streamname + len - 6,
7985 L":$DATA") == 0)
7986 {
7987 streamname[len - 6] = 0;
7988 copy_substream(sh, &context, tow, streamname,
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00007989 (long)sid.Size.u.LowPart);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007990 }
7991 }
7992
Bram Moolenaar0f873732019-12-05 20:28:46 +01007993 // Advance to the next stream. We might try seeking too far,
7994 // but BackupSeek() doesn't skip over stream borders, thus
7995 // that's OK.
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00007996 (void)BackupSeek(sh, sid.Size.u.LowPart, sid.Size.u.HighPart,
Bram Moolenaar071d4272004-06-13 20:20:40 +00007997 &lo, &hi, &context);
7998 }
7999
Bram Moolenaar0f873732019-12-05 20:28:46 +01008000 // Clear the context.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008001 (void)BackupRead(sh, NULL, 0, &readcount, TRUE, FALSE, &context);
8002
8003 CloseHandle(sh);
8004 }
8005 }
8006 vim_free(fromw);
8007 vim_free(tow);
8008}
Bram Moolenaar071d4272004-06-13 20:20:40 +00008009
8010/*
Bram Moolenaare7bebc42021-02-01 20:50:37 +01008011 * ntdll.dll definitions
8012 */
8013#define FileEaInformation 7
8014#ifndef STATUS_SUCCESS
8015# define STATUS_SUCCESS ((NTSTATUS) 0x00000000L)
8016#endif
8017
8018typedef struct _FILE_FULL_EA_INFORMATION_ {
8019 ULONG NextEntryOffset;
8020 UCHAR Flags;
8021 UCHAR EaNameLength;
8022 USHORT EaValueLength;
8023 CHAR EaName[1];
8024} FILE_FULL_EA_INFORMATION_, *PFILE_FULL_EA_INFORMATION_;
8025
8026typedef struct _FILE_EA_INFORMATION_ {
8027 ULONG EaSize;
8028} FILE_EA_INFORMATION_, *PFILE_EA_INFORMATION_;
8029
Paul Ollis65745772022-06-05 16:55:54 +01008030#ifndef PROTO
Bram Moolenaare7bebc42021-02-01 20:50:37 +01008031typedef NTSTATUS (NTAPI *PfnNtOpenFile)(
8032 PHANDLE FileHandle,
8033 ACCESS_MASK DesiredAccess,
8034 POBJECT_ATTRIBUTES ObjectAttributes,
8035 PIO_STATUS_BLOCK IoStatusBlock,
8036 ULONG ShareAccess,
8037 ULONG OpenOptions);
8038typedef NTSTATUS (NTAPI *PfnNtClose)(
8039 HANDLE Handle);
8040typedef NTSTATUS (NTAPI *PfnNtSetEaFile)(
Bram Moolenaar9f1983d2022-05-12 20:35:35 +01008041 HANDLE FileHandle,
8042 PIO_STATUS_BLOCK IoStatusBlock,
8043 PVOID Buffer,
8044 ULONG Length);
Bram Moolenaare7bebc42021-02-01 20:50:37 +01008045typedef NTSTATUS (NTAPI *PfnNtQueryEaFile)(
8046 HANDLE FileHandle,
8047 PIO_STATUS_BLOCK IoStatusBlock,
8048 PVOID Buffer,
8049 ULONG Length,
8050 BOOLEAN ReturnSingleEntry,
8051 PVOID EaList,
8052 ULONG EaListLength,
8053 PULONG EaIndex,
8054 BOOLEAN RestartScan);
8055typedef NTSTATUS (NTAPI *PfnNtQueryInformationFile)(
Bram Moolenaar9f1983d2022-05-12 20:35:35 +01008056 HANDLE FileHandle,
8057 PIO_STATUS_BLOCK IoStatusBlock,
8058 PVOID FileInformation,
8059 ULONG Length,
Bram Moolenaare7bebc42021-02-01 20:50:37 +01008060 FILE_INFORMATION_CLASS FileInformationClass);
8061typedef VOID (NTAPI *PfnRtlInitUnicodeString)(
8062 PUNICODE_STRING DestinationString,
8063 PCWSTR SourceString);
8064
8065PfnNtOpenFile pNtOpenFile = NULL;
8066PfnNtClose pNtClose = NULL;
8067PfnNtSetEaFile pNtSetEaFile = NULL;
8068PfnNtQueryEaFile pNtQueryEaFile = NULL;
8069PfnNtQueryInformationFile pNtQueryInformationFile = NULL;
8070PfnRtlInitUnicodeString pRtlInitUnicodeString = NULL;
Paul Ollis65745772022-06-05 16:55:54 +01008071#endif
Bram Moolenaare7bebc42021-02-01 20:50:37 +01008072
8073/*
8074 * Load ntdll.dll functions.
8075 */
8076 static BOOL
8077load_ntdll(void)
8078{
8079 static int loaded = -1;
8080
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00008081 if (loaded != -1)
8082 return (BOOL) loaded;
8083
8084 HMODULE hNtdll = GetModuleHandle("ntdll.dll");
8085 if (hNtdll != NULL)
Bram Moolenaare7bebc42021-02-01 20:50:37 +01008086 {
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00008087 pNtOpenFile = (PfnNtOpenFile) GetProcAddress(hNtdll, "NtOpenFile");
8088 pNtClose = (PfnNtClose) GetProcAddress(hNtdll, "NtClose");
8089 pNtSetEaFile = (PfnNtSetEaFile)
8090 GetProcAddress(hNtdll, "NtSetEaFile");
8091 pNtQueryEaFile = (PfnNtQueryEaFile)
8092 GetProcAddress(hNtdll, "NtQueryEaFile");
8093 pNtQueryInformationFile = (PfnNtQueryInformationFile)
8094 GetProcAddress(hNtdll, "NtQueryInformationFile");
8095 pRtlInitUnicodeString = (PfnRtlInitUnicodeString)
8096 GetProcAddress(hNtdll, "RtlInitUnicodeString");
Bram Moolenaare7bebc42021-02-01 20:50:37 +01008097 }
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00008098 if (pNtOpenFile == NULL
8099 || pNtClose == NULL
8100 || pNtSetEaFile == NULL
8101 || pNtQueryEaFile == NULL
8102 || pNtQueryInformationFile == NULL
8103 || pRtlInitUnicodeString == NULL)
8104 loaded = FALSE;
8105 else
8106 loaded = TRUE;
Bram Moolenaare7bebc42021-02-01 20:50:37 +01008107 return (BOOL) loaded;
8108}
8109
8110/*
8111 * Copy extended attributes (EA) from file "from" to file "to".
8112 */
8113 static void
8114copy_extattr(char_u *from, char_u *to)
8115{
8116 char_u *fromf = NULL;
8117 char_u *tof = NULL;
8118 WCHAR *fromw = NULL;
8119 WCHAR *tow = NULL;
8120 UNICODE_STRING u;
8121 HANDLE h;
8122 OBJECT_ATTRIBUTES oa;
8123 IO_STATUS_BLOCK iosb;
8124 FILE_EA_INFORMATION_ eainfo = {0};
8125 void *ea = NULL;
8126
8127 if (!load_ntdll())
8128 return;
8129
8130 // Convert the file names to the fully qualified object names.
8131 fromf = alloc(STRLEN(from) + 5);
8132 tof = alloc(STRLEN(to) + 5);
8133 if (fromf == NULL || tof == NULL)
8134 goto theend;
8135 STRCPY(fromf, "\\??\\");
8136 STRCAT(fromf, from);
8137 STRCPY(tof, "\\??\\");
8138 STRCAT(tof, to);
8139
8140 // Convert the names to wide characters.
8141 fromw = enc_to_utf16(fromf, NULL);
8142 tow = enc_to_utf16(tof, NULL);
8143 if (fromw == NULL || tow == NULL)
8144 goto theend;
8145
8146 // Get the EA.
8147 pRtlInitUnicodeString(&u, fromw);
8148 InitializeObjectAttributes(&oa, &u, 0, NULL, NULL);
8149 if (pNtOpenFile(&h, FILE_READ_EA, &oa, &iosb, 0,
8150 FILE_NON_DIRECTORY_FILE) != STATUS_SUCCESS)
8151 goto theend;
8152 pNtQueryInformationFile(h, &iosb, &eainfo, sizeof(eainfo),
8153 FileEaInformation);
8154 if (eainfo.EaSize != 0)
8155 {
8156 ea = alloc(eainfo.EaSize);
8157 if (ea != NULL)
8158 {
8159 if (pNtQueryEaFile(h, &iosb, ea, eainfo.EaSize, FALSE,
8160 NULL, 0, NULL, TRUE) != STATUS_SUCCESS)
8161 {
Yegappan Lakshmanan960dcbd2023-03-07 17:45:11 +00008162 VIM_CLEAR(ea);
Bram Moolenaare7bebc42021-02-01 20:50:37 +01008163 }
8164 }
8165 }
8166 pNtClose(h);
8167
8168 // Set the EA.
8169 if (ea != NULL)
8170 {
8171 pRtlInitUnicodeString(&u, tow);
8172 InitializeObjectAttributes(&oa, &u, 0, NULL, NULL);
8173 if (pNtOpenFile(&h, FILE_WRITE_EA, &oa, &iosb, 0,
8174 FILE_NON_DIRECTORY_FILE) != STATUS_SUCCESS)
8175 goto theend;
8176
8177 pNtSetEaFile(h, &iosb, ea, eainfo.EaSize);
8178 pNtClose(h);
8179 }
8180
8181theend:
8182 vim_free(fromf);
8183 vim_free(tof);
8184 vim_free(fromw);
8185 vim_free(tow);
8186 vim_free(ea);
8187}
8188
8189/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00008190 * Copy file attributes from file "from" to file "to".
8191 * For Windows NT and later we copy info streams.
8192 * Always returns zero, errors are ignored.
8193 */
8194 int
8195mch_copy_file_attribute(char_u *from, char_u *to)
8196{
Bram Moolenaar0f873732019-12-05 20:28:46 +01008197 // File streams only work on Windows NT and later.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02008198 copy_infostreams(from, to);
Bram Moolenaare7bebc42021-02-01 20:50:37 +01008199 copy_extattr(from, to);
Bram Moolenaar071d4272004-06-13 20:20:40 +00008200 return 0;
8201}
8202
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008203
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008204/*
K.Takatadc73b4b2021-06-08 18:32:36 +02008205 * The command line arguments in UTF-16
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008206 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00008207static int nArgsW = 0;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008208static LPWSTR *ArglistW = NULL;
8209static int global_argc = 0;
8210static char **global_argv;
8211
Bram Moolenaar0f873732019-12-05 20:28:46 +01008212static int used_file_argc = 0; // last argument in global_argv[] used
8213 // for the argument list.
8214static int *used_file_indexes = NULL; // indexes in global_argv[] for
8215 // command line arguments added to
8216 // the argument list
8217static int used_file_count = 0; // nr of entries in used_file_indexes
8218static int used_file_literal = FALSE; // take file names literally
8219static int used_file_full_path = FALSE; // file name was full path
8220static int used_file_diff_mode = FALSE; // file name was with diff mode
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008221static int used_alist_count = 0;
8222
8223
8224/*
8225 * Get the command line arguments. Unicode version.
8226 * Returns argc. Zero when something fails.
8227 */
8228 int
8229get_cmd_argsW(char ***argvp)
8230{
8231 char **argv = NULL;
8232 int argc = 0;
8233 int i;
8234
Bram Moolenaar14993322014-09-09 12:25:33 +02008235 free_cmd_argsW();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008236 ArglistW = CommandLineToArgvW(GetCommandLineW(), &nArgsW);
8237 if (ArglistW != NULL)
8238 {
8239 argv = malloc((nArgsW + 1) * sizeof(char *));
8240 if (argv != NULL)
8241 {
8242 argc = nArgsW;
8243 argv[argc] = NULL;
8244 for (i = 0; i < argc; ++i)
8245 {
8246 int len;
8247
K.Takatadc73b4b2021-06-08 18:32:36 +02008248 // Convert each Unicode argument to UTF-8.
8249 WideCharToMultiByte_alloc(CP_UTF8, 0,
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00008250 ArglistW[i], (int)wcslen(ArglistW[i]) + 1,
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008251 (LPSTR *)&argv[i], &len, 0, 0);
8252 if (argv[i] == NULL)
8253 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01008254 // Out of memory, clear everything.
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008255 while (i > 0)
8256 free(argv[--i]);
8257 free(argv);
Bram Moolenaar73c61632013-12-07 14:48:10 +01008258 argv = NULL;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008259 argc = 0;
8260 }
8261 }
8262 }
8263 }
8264
8265 global_argc = argc;
8266 global_argv = argv;
8267 if (argc > 0)
Bram Moolenaar14993322014-09-09 12:25:33 +02008268 {
8269 if (used_file_indexes != NULL)
8270 free(used_file_indexes);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008271 used_file_indexes = malloc(argc * sizeof(int));
Bram Moolenaar14993322014-09-09 12:25:33 +02008272 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008273
8274 if (argvp != NULL)
8275 *argvp = argv;
8276 return argc;
8277}
8278
8279 void
8280free_cmd_argsW(void)
8281{
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00008282 if (ArglistW == NULL)
8283 return;
8284
8285 GlobalFree(ArglistW);
8286 ArglistW = NULL;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008287}
8288
8289/*
8290 * Remember "name" is an argument that was added to the argument list.
8291 * This avoids that we have to re-parse the argument list when fix_arg_enc()
8292 * is called.
8293 */
8294 void
Bram Moolenaar910f66f2006-04-05 20:41:53 +00008295used_file_arg(char *name, int literal, int full_path, int diff_mode)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008296{
8297 int i;
8298
8299 if (used_file_indexes == NULL)
8300 return;
8301 for (i = used_file_argc + 1; i < global_argc; ++i)
8302 if (STRCMP(global_argv[i], name) == 0)
8303 {
8304 used_file_argc = i;
8305 used_file_indexes[used_file_count++] = i;
8306 break;
8307 }
8308 used_file_literal = literal;
8309 used_file_full_path = full_path;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00008310 used_file_diff_mode = diff_mode;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008311}
8312
8313/*
8314 * Remember the length of the argument list as it was. If it changes then we
8315 * leave it alone when 'encoding' is set.
8316 */
8317 void
8318set_alist_count(void)
8319{
8320 used_alist_count = GARGCOUNT;
8321}
8322
8323/*
8324 * Fix the encoding of the command line arguments. Invoked when 'encoding'
K.Takatadc73b4b2021-06-08 18:32:36 +02008325 * has been changed while starting up. Use the UTF-16 command line arguments
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008326 * and convert them to 'encoding'.
8327 */
8328 void
8329fix_arg_enc(void)
8330{
8331 int i;
8332 int idx;
8333 char_u *str;
Bram Moolenaar86b68352004-12-27 21:59:20 +00008334 int *fnum_list;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008335
Bram Moolenaar0f873732019-12-05 20:28:46 +01008336 // Safety checks:
8337 // - if argument count differs between the wide and non-wide argument
8338 // list, something must be wrong.
8339 // - the file name arguments must have been located.
8340 // - the length of the argument list wasn't changed by the user.
Bram Moolenaard857f0e2005-06-21 22:37:39 +00008341 if (global_argc != nArgsW
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008342 || ArglistW == NULL
8343 || used_file_indexes == NULL
8344 || used_file_count == 0
8345 || used_alist_count != GARGCOUNT)
8346 return;
8347
Bram Moolenaar0f873732019-12-05 20:28:46 +01008348 // Remember the buffer numbers for the arguments.
Bram Moolenaarc799fe22019-05-28 23:08:19 +02008349 fnum_list = ALLOC_MULT(int, GARGCOUNT);
Bram Moolenaar86b68352004-12-27 21:59:20 +00008350 if (fnum_list == NULL)
Bram Moolenaar0f873732019-12-05 20:28:46 +01008351 return; // out of memory
Bram Moolenaar86b68352004-12-27 21:59:20 +00008352 for (i = 0; i < GARGCOUNT; ++i)
8353 fnum_list[i] = GARGLIST[i].ae_fnum;
8354
Bram Moolenaar0f873732019-12-05 20:28:46 +01008355 // Clear the argument list. Make room for the new arguments.
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008356 alist_clear(&global_alist);
8357 if (ga_grow(&global_alist.al_ga, used_file_count) == FAIL)
Bram Moolenaar0f873732019-12-05 20:28:46 +01008358 return; // out of memory
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008359
8360 for (i = 0; i < used_file_count; ++i)
8361 {
8362 idx = used_file_indexes[i];
Bram Moolenaar36f692d2008-11-20 16:10:17 +00008363 str = utf16_to_enc(ArglistW[idx], NULL);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008364 if (str != NULL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00008365 {
Bram Moolenaar39d21e32017-08-05 23:09:31 +02008366 int literal = used_file_literal;
8367
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01008368#ifdef FEAT_DIFF
Bram Moolenaar0f873732019-12-05 20:28:46 +01008369 // When using diff mode may need to concatenate file name to
8370 // directory name. Just like it's done in main().
Bram Moolenaar910f66f2006-04-05 20:41:53 +00008371 if (used_file_diff_mode && mch_isdir(str) && GARGCOUNT > 0
8372 && !mch_isdir(alist_name(&GARGLIST[0])))
8373 {
8374 char_u *r;
8375
8376 r = concat_fnames(str, gettail(alist_name(&GARGLIST[0])), TRUE);
8377 if (r != NULL)
8378 {
8379 vim_free(str);
8380 str = r;
8381 }
8382 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01008383#endif
Bram Moolenaar0f873732019-12-05 20:28:46 +01008384 // Re-use the old buffer by renaming it. When not using literal
8385 // names it's done by alist_expand() below.
Bram Moolenaar86b68352004-12-27 21:59:20 +00008386 if (used_file_literal)
8387 buf_set_name(fnum_list[i], str);
8388
Bram Moolenaar0f873732019-12-05 20:28:46 +01008389 // Check backtick literal. backtick literal is already expanded in
8390 // main.c, so this part add str as literal.
Bram Moolenaar39d21e32017-08-05 23:09:31 +02008391 if (literal == FALSE)
8392 {
Bram Moolenaar116a0f82017-08-07 21:17:57 +02008393 size_t len = STRLEN(str);
8394
Bram Moolenaar39d21e32017-08-05 23:09:31 +02008395 if (len > 2 && *str == '`' && *(str + len - 1) == '`')
8396 literal = TRUE;
8397 }
8398 alist_add(&global_alist, str, literal ? 2 : 0);
Bram Moolenaar86b68352004-12-27 21:59:20 +00008399 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008400 }
8401
8402 if (!used_file_literal)
8403 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01008404 // Now expand wildcards in the arguments.
8405 // Temporarily add '(' and ')' to 'isfname'. These are valid
8406 // filename characters but are excluded from 'isfname' to make
Dominique Pelleaf4a61a2021-12-27 17:21:41 +00008407 // "gf" work on a file name in parentheses (e.g.: see vim.h).
Bram Moolenaar0f873732019-12-05 20:28:46 +01008408 // Also, unset wildignore to not be influenced by this option.
8409 // The arguments specified in command-line should be kept even if
8410 // encoding options were changed.
Christian Brabandtfd916d62021-11-01 22:44:33 +00008411 // Use :legacy so that it also works when in Vim9 script.
8412 do_cmdline_cmd((char_u *)":legacy let g:SaVe_ISF = &isf|set isf+=(,)");
8413 do_cmdline_cmd((char_u *)":legacy let g:SaVe_WIG = &wig|set wig=");
Bram Moolenaar86b68352004-12-27 21:59:20 +00008414 alist_expand(fnum_list, used_alist_count);
Christian Brabandtfd916d62021-11-01 22:44:33 +00008415 do_cmdline_cmd(
8416 (char_u *)":legacy let &isf = g:SaVe_ISF|unlet g:SaVe_ISF");
8417 do_cmdline_cmd(
8418 (char_u *)":legacy let &wig = g:SaVe_WIG|unlet g:SaVe_WIG");
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008419 }
8420
Bram Moolenaar0f873732019-12-05 20:28:46 +01008421 // If wildcard expansion failed, we are editing the first file of the
8422 // arglist and there is no file name: Edit the first argument now.
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008423 if (curwin->w_arg_idx == 0 && curbuf->b_fname == NULL)
8424 {
8425 do_cmdline_cmd((char_u *)":rewind");
Bram Moolenaar05268152021-11-18 18:53:45 +00008426 if (GARGCOUNT == 1 && used_file_full_path
8427 && vim_chdirfile(alist_name(&GARGLIST[0]), "drop") == OK)
8428 last_chdir_reason = "drop";
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008429 }
Bram Moolenaar86b68352004-12-27 21:59:20 +00008430
8431 set_alist_count();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008432}
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01008433
8434 int
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02008435mch_setenv(char *var, char *value, int x UNUSED)
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01008436{
8437 char_u *envbuf;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02008438 WCHAR *p;
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01008439
Bram Moolenaar964b3742019-05-24 18:54:09 +02008440 envbuf = alloc(STRLEN(var) + STRLEN(value) + 2);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01008441 if (envbuf == NULL)
8442 return -1;
8443
8444 sprintf((char *)envbuf, "%s=%s", var, value);
8445
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02008446 p = enc_to_utf16(envbuf, NULL);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01008447
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02008448 vim_free(envbuf);
8449 if (p == NULL)
8450 return -1;
8451 _wputenv(p);
Bram Moolenaara12a1612019-01-24 16:39:02 +01008452#ifdef libintl_wputenv
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02008453 libintl_wputenv(p);
Bram Moolenaara12a1612019-01-24 16:39:02 +01008454#endif
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02008455 // Unlike Un*x systems, we can free the string for _wputenv().
8456 vim_free(p);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01008457
8458 return 0;
8459}
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008460
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008461/*
8462 * Support for 256 colors and 24-bit colors was added in Windows 10
8463 * version 1703 (Creators update).
8464 */
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008465#define VTP_FIRST_SUPPORT_BUILD MAKE_VER(10, 0, 15063)
8466
8467/*
8468 * Support for pseudo-console (ConPTY) was added in windows 10
Bram Moolenaar57da6982019-09-13 22:30:11 +02008469 * version 1809 (October 2018 update).
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008470 */
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01008471#define CONPTY_FIRST_SUPPORT_BUILD MAKE_VER(10, 0, 17763)
Bram Moolenaar57da6982019-09-13 22:30:11 +02008472
8473/*
8474 * ConPTY differences between versions, need different logic.
8475 * version 1903 (May 2019 update).
8476 */
8477#define CONPTY_1903_BUILD MAKE_VER(10, 0, 18362)
8478
8479/*
Bram Moolenaar36e7a822019-11-13 21:49:24 +01008480 * version 1909 (November 2019 update).
8481 */
8482#define CONPTY_1909_BUILD MAKE_VER(10, 0, 18363)
8483
8484/*
Bram Moolenaar7ed8f592020-04-28 20:44:42 +02008485 * Stay ahead of the next update, and when it's done, fix this.
8486 * version ? (2020 update, temporarily use the build number of insider preview)
8487 */
8488#define CONPTY_NEXT_UPDATE_BUILD MAKE_VER(10, 0, 19587)
8489
8490/*
Bram Moolenaar57da6982019-09-13 22:30:11 +02008491 * Confirm until this version. Also the logic changes.
8492 * insider preview.
8493 */
Bram Moolenaar4c063dd2019-10-04 21:29:12 +02008494#define CONPTY_INSIDER_BUILD MAKE_VER(10, 0, 18995)
Bram Moolenaar57da6982019-09-13 22:30:11 +02008495
8496/*
8497 * Not stable now.
8498 */
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01008499#define CONPTY_STABLE_BUILD MAKE_VER(10, 0, 32767) // T.B.D.
Christopher Plewright1140b512022-11-12 18:46:05 +00008500// Notes:
8501// Win 10 22H2 Final is build 19045, it's conpty is widely used.
8502// Strangely, 19045 is newer but is a lower build number than the 2020 insider
8503// preview which had a build 19587. And, not sure how stable that was?
8504// Win Server 2022 (May 10, 2022) is build 20348, its conpty is widely used.
8505// Win 11 starts from build 22000, even though the major version says 10!
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008506
8507 static void
8508vtp_flag_init(void)
8509{
8510 DWORD ver = get_build_number();
Bram Moolenaarafde13b2019-04-28 19:46:49 +02008511#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008512 DWORD mode;
8513 HANDLE out;
8514
Bram Moolenaarafde13b2019-04-28 19:46:49 +02008515# ifdef VIMDLL
8516 if (!gui.in_use)
8517# endif
8518 {
8519 out = GetStdHandle(STD_OUTPUT_HANDLE);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008520
Bram Moolenaarafde13b2019-04-28 19:46:49 +02008521 vtp_working = (ver >= VTP_FIRST_SUPPORT_BUILD) ? 1 : 0;
8522 GetConsoleMode(out, &mode);
8523 mode |= (ENABLE_PROCESSED_OUTPUT | ENABLE_VIRTUAL_TERMINAL_PROCESSING);
8524 if (SetConsoleMode(out, mode) == 0)
8525 vtp_working = 0;
Christopher Plewrightf75a2cb2023-01-28 10:28:09 +00008526
8527 // VTP uses alternate screen buffer.
8528 // But, not if running in a nested terminal
8529 use_alternate_screen_buffer = win10_22H2_or_later && p_rs && vtp_working
8530 && !mch_getenv("VIM_TERMINAL");
Bram Moolenaarafde13b2019-04-28 19:46:49 +02008531 }
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008532#endif
8533
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008534 if (ver >= CONPTY_FIRST_SUPPORT_BUILD)
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01008535 conpty_working = 1;
8536 if (ver >= CONPTY_STABLE_BUILD)
8537 conpty_stable = 1;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008538
Bram Moolenaar57da6982019-09-13 22:30:11 +02008539 if (ver <= CONPTY_INSIDER_BUILD)
8540 conpty_type = 3;
Bram Moolenaar36e7a822019-11-13 21:49:24 +01008541 if (ver <= CONPTY_1909_BUILD)
8542 conpty_type = 2;
Bram Moolenaar57da6982019-09-13 22:30:11 +02008543 if (ver <= CONPTY_1903_BUILD)
8544 conpty_type = 2;
8545 if (ver < CONPTY_FIRST_SUPPORT_BUILD)
8546 conpty_type = 1;
Bram Moolenaar7ed8f592020-04-28 20:44:42 +02008547
8548 if (ver >= CONPTY_NEXT_UPDATE_BUILD)
8549 conpty_fix_type = 1;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008550}
8551
Bram Moolenaarafde13b2019-04-28 19:46:49 +02008552#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL) || defined(PROTO)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008553
8554 static void
8555vtp_init(void)
8556{
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02008557# ifdef FEAT_TERMGUICOLORS
Christopher Plewrightd343c602023-01-22 18:58:30 +00008558 CONSOLE_SCREEN_BUFFER_INFOEX csbi;
8559 csbi.cbSize = sizeof(csbi);
8560 GetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
8561 save_console_bg_rgb = (guicolor_T)csbi.ColorTable[g_color_index_bg];
8562 save_console_fg_rgb = (guicolor_T)csbi.ColorTable[g_color_index_fg];
8563 store_console_bg_rgb = save_console_bg_rgb;
8564 store_console_fg_rgb = save_console_fg_rgb;
Christopher Plewright38804d62022-11-09 23:55:52 +00008565
Christopher Plewrightd343c602023-01-22 18:58:30 +00008566 COLORREF bg;
8567 bg = (COLORREF)csbi.ColorTable[g_color_index_bg];
8568 bg = (GetRValue(bg) << 16) | (GetGValue(bg) << 8) | GetBValue(bg);
8569 default_console_color_bg = bg;
Christopher Plewright38804d62022-11-09 23:55:52 +00008570
Christopher Plewrightd343c602023-01-22 18:58:30 +00008571 COLORREF fg;
8572 fg = (COLORREF)csbi.ColorTable[g_color_index_fg];
8573 fg = (GetRValue(fg) << 16) | (GetGValue(fg) << 8) | GetBValue(fg);
8574 default_console_color_fg = fg;
Bram Moolenaarc4568ab2018-11-16 16:21:05 +01008575# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008576 set_console_color_rgb();
8577}
8578
8579 static void
8580vtp_exit(void)
8581{
Bram Moolenaardf543822020-01-30 11:53:59 +01008582 restore_console_color_rgb();
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008583}
8584
Bram Moolenaar06b7b582020-05-30 17:49:25 +02008585 int
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008586vtp_printf(
8587 char *format,
8588 ...)
8589{
8590 char_u buf[100];
8591 va_list list;
8592 DWORD result;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008593 int len;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008594
Nir Lichtman6cd2d1d2023-11-11 11:27:41 +01008595 if (silent_mode)
8596 return 0;
8597
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008598 va_start(list, format);
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008599 len = vim_vsnprintf((char *)buf, 100, (char *)format, list);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008600 va_end(list);
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008601 WriteConsoleA(g_hConOut, buf, (DWORD)len, &result, NULL);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008602 return (int)result;
8603}
8604
8605 static void
8606vtp_sgr_bulk(
8607 int arg)
8608{
8609 int args[1];
8610
8611 args[0] = arg;
8612 vtp_sgr_bulks(1, args);
8613}
8614
K.Takata6e1d31e2022-02-03 13:05:32 +00008615# define FAST256(x) \
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008616 if ((*p-- = "0123456789"[(n = x % 10)]) \
8617 && x >= 10 && (*p-- = "0123456789"[((m = x % 100) - n) / 10]) \
8618 && x >= 100 && (*p-- = "012"[((x & 0xff) - m) / 100]));
8619
K.Takata6e1d31e2022-02-03 13:05:32 +00008620# define FAST256CASE(x) \
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008621 case x: \
8622 FAST256(newargs[x - 1]);
8623
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008624 static void
8625vtp_sgr_bulks(
8626 int argc,
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008627 int *args)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008628{
K.Takata6e1d31e2022-02-03 13:05:32 +00008629# define MAXSGR 16
8630# define SGRBUFSIZE 2 + 4 * MAXSGR + 1 // '\033[' + SGR + 'm'
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008631 char_u buf[SGRBUFSIZE];
8632 char_u *p;
8633 int in, out;
8634 int newargs[16];
8635 static int sgrfgr = -1, sgrfgg, sgrfgb;
8636 static int sgrbgr = -1, sgrbgg, sgrbgb;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008637
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008638 if (argc == 0)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008639 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008640 sgrfgr = sgrbgr = -1;
K.Takatadf5320c2022-09-01 13:20:16 +01008641 vtp_printf("\033[m");
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008642 return;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008643 }
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008644
8645 in = out = 0;
8646 while (in < argc)
8647 {
8648 int s = args[in];
8649 int copylen = 1;
8650
8651 if (s == 38)
8652 {
8653 if (argc - in >= 5 && args[in + 1] == 2)
8654 {
8655 if (sgrfgr == args[in + 2] && sgrfgg == args[in + 3]
8656 && sgrfgb == args[in + 4])
8657 {
8658 in += 5;
8659 copylen = 0;
8660 }
8661 else
8662 {
8663 sgrfgr = args[in + 2];
8664 sgrfgg = args[in + 3];
8665 sgrfgb = args[in + 4];
8666 copylen = 5;
8667 }
8668 }
8669 else if (argc - in >= 3 && args[in + 1] == 5)
8670 {
8671 sgrfgr = -1;
8672 copylen = 3;
8673 }
8674 }
8675 else if (s == 48)
8676 {
8677 if (argc - in >= 5 && args[in + 1] == 2)
8678 {
8679 if (sgrbgr == args[in + 2] && sgrbgg == args[in + 3]
8680 && sgrbgb == args[in + 4])
8681 {
8682 in += 5;
8683 copylen = 0;
8684 }
8685 else
8686 {
8687 sgrbgr = args[in + 2];
8688 sgrbgg = args[in + 3];
8689 sgrbgb = args[in + 4];
8690 copylen = 5;
8691 }
8692 }
8693 else if (argc - in >= 3 && args[in + 1] == 5)
8694 {
8695 sgrbgr = -1;
8696 copylen = 3;
8697 }
8698 }
8699 else if (30 <= s && s <= 39)
8700 sgrfgr = -1;
8701 else if (90 <= s && s <= 97)
8702 sgrfgr = -1;
8703 else if (40 <= s && s <= 49)
8704 sgrbgr = -1;
8705 else if (100 <= s && s <= 107)
8706 sgrbgr = -1;
8707 else if (s == 0)
8708 sgrfgr = sgrbgr = -1;
8709
8710 while (copylen--)
8711 newargs[out++] = args[in++];
8712 }
8713
8714 p = &buf[sizeof(buf) - 1];
8715 *p-- = 'm';
8716
8717 switch (out)
8718 {
8719 int n, m;
8720 DWORD r;
8721
8722 FAST256CASE(16);
8723 *p-- = ';';
8724 FAST256CASE(15);
8725 *p-- = ';';
8726 FAST256CASE(14);
8727 *p-- = ';';
8728 FAST256CASE(13);
8729 *p-- = ';';
8730 FAST256CASE(12);
8731 *p-- = ';';
8732 FAST256CASE(11);
8733 *p-- = ';';
8734 FAST256CASE(10);
8735 *p-- = ';';
8736 FAST256CASE(9);
8737 *p-- = ';';
8738 FAST256CASE(8);
8739 *p-- = ';';
8740 FAST256CASE(7);
8741 *p-- = ';';
8742 FAST256CASE(6);
8743 *p-- = ';';
8744 FAST256CASE(5);
8745 *p-- = ';';
8746 FAST256CASE(4);
8747 *p-- = ';';
8748 FAST256CASE(3);
8749 *p-- = ';';
8750 FAST256CASE(2);
8751 *p-- = ';';
8752 FAST256CASE(1);
8753 *p-- = '[';
8754 *p = '\033';
8755 WriteConsoleA(g_hConOut, p, (DWORD)(&buf[SGRBUFSIZE] - p), &r, NULL);
8756 default:
8757 break;
8758 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008759}
8760
Bram Moolenaar06b7b582020-05-30 17:49:25 +02008761 static void
8762wt_init(void)
8763{
Christopher Plewright1140b512022-11-12 18:46:05 +00008764 wt_working = mch_getenv("WT_SESSION") != NULL;
Bram Moolenaar06b7b582020-05-30 17:49:25 +02008765}
8766
Bram Moolenaar8a938af2018-05-01 17:30:41 +02008767# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02008768 static int
8769ctermtoxterm(
8770 int cterm)
8771{
Bram Moolenaar9894e392018-05-05 14:29:06 +02008772 char_u r, g, b, idx;
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02008773
8774 cterm_color2rgb(cterm, &r, &g, &b, &idx);
8775 return (((int)r << 16) | ((int)g << 8) | (int)b);
8776}
Bram Moolenaar8a938af2018-05-01 17:30:41 +02008777# endif
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02008778
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008779 static void
8780set_console_color_rgb(void)
8781{
8782# ifdef FEAT_TERMGUICOLORS
K.Takata27b53be2022-09-18 12:25:49 +01008783 CONSOLE_SCREEN_BUFFER_INFOEX csbi;
Bram Moolenaara050b942019-12-02 21:35:31 +01008784 guicolor_T fg, bg;
8785 int ctermfg, ctermbg;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008786
Christopher Plewright38804d62022-11-09 23:55:52 +00008787 if (!vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008788 return;
8789
Bram Moolenaara050b942019-12-02 21:35:31 +01008790 get_default_console_color(&ctermfg, &ctermbg, &fg, &bg);
8791
Christopher Plewright38804d62022-11-09 23:55:52 +00008792 if (p_tgc || t_colors >= 256)
Bram Moolenaar06b7b582020-05-30 17:49:25 +02008793 {
8794 term_fg_rgb_color(fg);
8795 term_bg_rgb_color(bg);
8796 return;
8797 }
8798
Christopher Plewrightf75a2cb2023-01-28 10:28:09 +00008799 if (use_alternate_screen_buffer)
8800 return;
8801
Christopher Plewrightd343c602023-01-22 18:58:30 +00008802 fg = (GetRValue(fg) << 16) | (GetGValue(fg) << 8) | GetBValue(fg);
8803 bg = (GetRValue(bg) << 16) | (GetGValue(bg) << 8) | GetBValue(bg);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008804
Christopher Plewrightd343c602023-01-22 18:58:30 +00008805 csbi.cbSize = sizeof(csbi);
8806 GetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008807
Christopher Plewrightd343c602023-01-22 18:58:30 +00008808 csbi.cbSize = sizeof(csbi);
8809 csbi.srWindow.Right += 1;
8810 csbi.srWindow.Bottom += 1;
8811 store_console_bg_rgb = csbi.ColorTable[g_color_index_bg];
8812 store_console_fg_rgb = csbi.ColorTable[g_color_index_fg];
8813 csbi.ColorTable[g_color_index_bg] = (COLORREF)bg;
8814 csbi.ColorTable[g_color_index_fg] = (COLORREF)fg;
8815 SetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008816# endif
8817}
8818
Bram Moolenaara050b942019-12-02 21:35:31 +01008819# if defined(FEAT_TERMGUICOLORS) || defined(PROTO)
8820 void
8821get_default_console_color(
8822 int *cterm_fg,
8823 int *cterm_bg,
8824 guicolor_T *gui_fg,
8825 guicolor_T *gui_bg)
8826{
8827 int id;
8828 guicolor_T guifg = INVALCOLOR;
8829 guicolor_T guibg = INVALCOLOR;
8830 int ctermfg = 0;
8831 int ctermbg = 0;
Christopher Plewright38804d62022-11-09 23:55:52 +00008832 int dummynull = 0;
Bram Moolenaara050b942019-12-02 21:35:31 +01008833
8834 id = syn_name2id((char_u *)"Normal");
8835 if (id > 0 && p_tgc)
8836 syn_id2colors(id, &guifg, &guibg);
8837 if (guifg == INVALCOLOR)
8838 {
8839 ctermfg = -1;
8840 if (id > 0)
Christopher Plewright38804d62022-11-09 23:55:52 +00008841 syn_id2cterm_bg(id, &ctermfg, &dummynull);
Christopher Plewrightd343c602023-01-22 18:58:30 +00008842 if (ctermfg != -1)
8843 guifg = ctermtoxterm(ctermfg);
Christopher Plewright38804d62022-11-09 23:55:52 +00008844 else
Christopher Plewrightd343c602023-01-22 18:58:30 +00008845 guifg = USE_WT ? INVALCOLOR : default_console_color_fg;
8846 cterm_normal_fg_gui_color = guifg;
8847 ctermfg = ctermfg < 0 ? 0 : ctermfg;
Bram Moolenaara050b942019-12-02 21:35:31 +01008848 }
8849 if (guibg == INVALCOLOR)
8850 {
8851 ctermbg = -1;
8852 if (id > 0)
Christopher Plewright38804d62022-11-09 23:55:52 +00008853 syn_id2cterm_bg(id, &dummynull, &ctermbg);
Christopher Plewrightd343c602023-01-22 18:58:30 +00008854 if (ctermbg != -1)
8855 guibg = ctermtoxterm(ctermbg);
K.Takatae53a0d42022-09-05 21:45:11 +01008856 else
Christopher Plewrightd343c602023-01-22 18:58:30 +00008857 guibg = USE_WT ? INVALCOLOR : default_console_color_bg;
8858 cterm_normal_bg_gui_color = guibg;
8859 ctermbg = ctermbg < 0 ? 0 : ctermbg;
Bram Moolenaara050b942019-12-02 21:35:31 +01008860 }
8861
8862 *cterm_fg = ctermfg;
8863 *cterm_bg = ctermbg;
8864 *gui_fg = guifg;
8865 *gui_bg = guibg;
8866}
8867# endif
8868
Bram Moolenaardf543822020-01-30 11:53:59 +01008869/*
8870 * Set the console colors to the original colors or the last set colors.
8871 */
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008872 static void
8873reset_console_color_rgb(void)
8874{
8875# ifdef FEAT_TERMGUICOLORS
Christopher Plewrightf75a2cb2023-01-28 10:28:09 +00008876 if (use_alternate_screen_buffer)
8877 return;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008878
Christopher Plewright38804d62022-11-09 23:55:52 +00008879 CONSOLE_SCREEN_BUFFER_INFOEX csbi;
8880
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008881 csbi.cbSize = sizeof(csbi);
K.Takata27b53be2022-09-18 12:25:49 +01008882 GetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008883
8884 csbi.cbSize = sizeof(csbi);
8885 csbi.srWindow.Right += 1;
8886 csbi.srWindow.Bottom += 1;
Bram Moolenaardf543822020-01-30 11:53:59 +01008887 csbi.ColorTable[g_color_index_bg] = (COLORREF)store_console_bg_rgb;
8888 csbi.ColorTable[g_color_index_fg] = (COLORREF)store_console_fg_rgb;
K.Takata27b53be2022-09-18 12:25:49 +01008889 SetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaardf543822020-01-30 11:53:59 +01008890# endif
8891}
8892
8893/*
8894 * Set the console colors to the original colors.
8895 */
8896 static void
8897restore_console_color_rgb(void)
8898{
8899# ifdef FEAT_TERMGUICOLORS
Christopher Plewrightf75a2cb2023-01-28 10:28:09 +00008900 if (use_alternate_screen_buffer)
8901 return;
Christopher Plewright38804d62022-11-09 23:55:52 +00008902
K.Takata27b53be2022-09-18 12:25:49 +01008903 CONSOLE_SCREEN_BUFFER_INFOEX csbi;
Bram Moolenaardf543822020-01-30 11:53:59 +01008904
8905 csbi.cbSize = sizeof(csbi);
K.Takata27b53be2022-09-18 12:25:49 +01008906 GetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaardf543822020-01-30 11:53:59 +01008907
8908 csbi.cbSize = sizeof(csbi);
8909 csbi.srWindow.Right += 1;
8910 csbi.srWindow.Bottom += 1;
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02008911 csbi.ColorTable[g_color_index_bg] = (COLORREF)save_console_bg_rgb;
8912 csbi.ColorTable[g_color_index_fg] = (COLORREF)save_console_fg_rgb;
K.Takata27b53be2022-09-18 12:25:49 +01008913 SetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008914# endif
8915}
8916
8917 void
8918control_console_color_rgb(void)
8919{
Christopher Plewright38804d62022-11-09 23:55:52 +00008920 if (vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008921 set_console_color_rgb();
8922 else
8923 reset_console_color_rgb();
8924}
8925
8926 int
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008927use_vtp(void)
8928{
8929 return USE_VTP;
8930}
8931
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02008932 int
8933is_term_win32(void)
8934{
8935 return T_NAME != NULL && STRCMP(T_NAME, "win32") == 0;
8936}
8937
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008938 int
8939has_vtp_working(void)
8940{
8941 return vtp_working;
8942}
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01008943
Bram Moolenaar6902c0e2019-02-16 14:07:37 +01008944#endif
8945
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01008946 int
8947has_conpty_working(void)
8948{
8949 return conpty_working;
8950}
8951
8952 int
Bram Moolenaar57da6982019-09-13 22:30:11 +02008953get_conpty_type(void)
8954{
8955 return conpty_type;
8956}
8957
8958 int
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01008959is_conpty_stable(void)
8960{
8961 return conpty_stable;
8962}
Bram Moolenaar78d21da2019-02-17 15:00:52 +01008963
Bram Moolenaar7ed8f592020-04-28 20:44:42 +02008964 int
8965get_conpty_fix_type(void)
8966{
8967 return conpty_fix_type;
8968}
8969
Bram Moolenaarafde13b2019-04-28 19:46:49 +02008970#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL) || defined(PROTO)
Bram Moolenaar78d21da2019-02-17 15:00:52 +01008971 void
8972resize_console_buf(void)
8973{
Christopher Plewrightf75a2cb2023-01-28 10:28:09 +00008974 if (use_alternate_screen_buffer)
8975 return;
8976
Bram Moolenaar78d21da2019-02-17 15:00:52 +01008977 CONSOLE_SCREEN_BUFFER_INFO csbi;
8978 COORD coord;
8979 SMALL_RECT newsize;
8980
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00008981 if (!GetConsoleScreenBufferInfo(g_hConOut, &csbi))
8982 return;
Bram Moolenaar78d21da2019-02-17 15:00:52 +01008983
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00008984 coord.X = SRWIDTH(csbi.srWindow);
8985 coord.Y = SRHEIGHT(csbi.srWindow);
8986 SetConsoleScreenBufferSize(g_hConOut, coord);
Bram Moolenaar78d21da2019-02-17 15:00:52 +01008987
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00008988 newsize.Left = 0;
8989 newsize.Top = 0;
8990 newsize.Right = coord.X - 1;
8991 newsize.Bottom = coord.Y - 1;
8992 SetConsoleWindowInfo(g_hConOut, TRUE, &newsize);
8993
8994 SetConsoleScreenBufferSize(g_hConOut, coord);
Bram Moolenaar78d21da2019-02-17 15:00:52 +01008995}
8996#endif
Martin Tournoij1a3e5742021-07-24 13:57:29 +02008997
8998 char *
8999GetWin32Error(void)
9000{
K.Takatad68b2fc2022-02-12 11:18:37 +00009001 static char *oldmsg = NULL;
Martin Tournoij1a3e5742021-07-24 13:57:29 +02009002 char *msg = NULL;
K.Takatad68b2fc2022-02-12 11:18:37 +00009003
Martin Tournoij1a3e5742021-07-24 13:57:29 +02009004 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER|FORMAT_MESSAGE_FROM_SYSTEM,
9005 NULL, GetLastError(), 0, (LPSTR)&msg, 0, NULL);
K.Takatad68b2fc2022-02-12 11:18:37 +00009006 if (oldmsg != NULL)
9007 LocalFree(oldmsg);
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00009008 if (msg == NULL)
9009 return NULL;
9010
9011 // remove trailing \r\n
9012 char *pcrlf = strstr(msg, "\r\n");
9013 if (pcrlf != NULL)
9014 *pcrlf = '\0';
9015 oldmsg = msg;
Martin Tournoij1a3e5742021-07-24 13:57:29 +02009016 return msg;
9017}
Paul Ollis65745772022-06-05 16:55:54 +01009018
9019#if defined(FEAT_RELTIME) || defined(PROTO)
9020static HANDLE timer_handle;
9021static int timer_active = FALSE;
9022
9023/*
9024 * Calls to start_timeout alternate the return value pointer between the two
9025 * entries in timeout_flags. If the previously active timeout is very close to
9026 * expiring when start_timeout() is called then a race condition means that the
9027 * set_flag() function may still be invoked after the previous timer is
9028 * deleted. Ping-ponging between the two flags prevents this causing 'fake'
9029 * timeouts.
9030 */
Bram Moolenaar155f2d12022-06-20 13:38:33 +01009031static sig_atomic_t timeout_flags[2];
9032static int timeout_flag_idx = 0;
9033static sig_atomic_t *timeout_flag = &timeout_flags[0];
Paul Ollis65745772022-06-05 16:55:54 +01009034
9035
9036 static void CALLBACK
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +01009037set_flag(void *param, BOOLEAN unused2 UNUSED)
Paul Ollis65745772022-06-05 16:55:54 +01009038{
9039 int *timeout_flag = (int *)param;
9040
9041 *timeout_flag = TRUE;
9042}
9043
9044/*
9045 * Stop any active timeout.
9046 */
9047 void
9048stop_timeout(void)
9049{
9050 if (timer_active)
9051 {
Christopher Plewright2a46f812022-10-16 19:47:45 +01009052 BOOL ret = DeleteTimerQueueTimer(NULL, timer_handle, NULL);
Paul Ollis65745772022-06-05 16:55:54 +01009053 timer_active = FALSE;
9054 if (!ret && GetLastError() != ERROR_IO_PENDING)
9055 {
9056 semsg(_(e_could_not_clear_timeout_str), GetWin32Error());
9057 }
9058 }
9059 *timeout_flag = FALSE;
9060}
9061
9062/*
9063 * Start the timeout timer.
9064 *
9065 * The period is defined in milliseconds.
9066 *
9067 * The return value is a pointer to a flag that is initialised to 0. If the
9068 * timeout expires, the flag is set to 1. This will only return pointers to
9069 * static memory; i.e. any pointer returned by this function may always be
9070 * safely dereferenced.
9071 *
9072 * This function is not expected to fail, but if it does it still returns a
9073 * valid flag pointer; the flag will remain stuck at zero.
9074 */
Bram Moolenaar155f2d12022-06-20 13:38:33 +01009075 volatile sig_atomic_t *
Paul Ollis65745772022-06-05 16:55:54 +01009076start_timeout(long msec)
9077{
Paul Ollis65745772022-06-05 16:55:54 +01009078 BOOL ret;
9079
Bram Moolenaar1f30caf2022-06-19 14:36:35 +01009080 timeout_flag = &timeout_flags[timeout_flag_idx];
Paul Ollis65745772022-06-05 16:55:54 +01009081
9082 stop_timeout();
9083 ret = CreateTimerQueueTimer(
9084 &timer_handle, NULL, set_flag, timeout_flag,
9085 (DWORD)msec, 0, WT_EXECUTEDEFAULT);
9086 if (!ret)
9087 {
9088 semsg(_(e_could_not_set_timeout_str), GetWin32Error());
9089 }
9090 else
9091 {
Bram Moolenaar1f30caf2022-06-19 14:36:35 +01009092 timeout_flag_idx = (timeout_flag_idx + 1) % 2;
Paul Ollis65745772022-06-05 16:55:54 +01009093 timer_active = TRUE;
9094 *timeout_flag = FALSE;
9095 }
9096 return timeout_flag;
9097}
9098#endif