blob: eeb3b47166364cf97de34a4ee50326258b7c8a2d [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 Moolenaar071d4272004-06-13 20:20:40 +000037# include <direct.h>
Bram Moolenaar071d4272004-06-13 20:20:40 +000038
Bram Moolenaar651fca82021-11-29 20:39:38 +000039# if !defined(FEAT_GUI_MSWIN)
Bram Moolenaar82881492012-11-20 16:53:39 +010040# include <shellapi.h>
41# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +000042
K.Takata56f587b2024-06-19 19:56:03 +020043# ifdef FEAT_JOB_CHANNEL
44# include <tlhelp32.h>
Bram Moolenaar071d4272004-06-13 20:20:40 +000045# endif
46#endif
47
Bram Moolenaar0f873732019-12-05 20:28:46 +010048// Record all output and all keyboard & mouse input
49// #define MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +000050
51#ifdef MCH_WRITE_DUMP
52FILE* fdDump = NULL;
53#endif
54
55/*
56 * When generating prototypes for Win32 on Unix, these lines make the syntax
57 * errors disappear. They do not need to be correct.
58 */
59#ifdef PROTO
Bram Moolenaar912bc4a2019-12-01 18:58:11 +010060# define WINAPI
Bram Moolenaar071d4272004-06-13 20:20:40 +000061typedef char * LPCSTR;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +000062typedef char * LPWSTR;
Bram Moolenaar071d4272004-06-13 20:20:40 +000063typedef int ACCESS_MASK;
64typedef int BOOL;
Paul Ollis65745772022-06-05 16:55:54 +010065typedef int BOOLEAN;
66typedef int CALLBACK;
Bram Moolenaar071d4272004-06-13 20:20:40 +000067typedef int COLORREF;
68typedef int CONSOLE_CURSOR_INFO;
69typedef int COORD;
70typedef int DWORD;
71typedef int HANDLE;
Bram Moolenaaref269542016-01-19 13:22:12 +010072typedef int LPHANDLE;
Bram Moolenaar071d4272004-06-13 20:20:40 +000073typedef int HDC;
74typedef int HFONT;
75typedef int HICON;
76typedef int HINSTANCE;
77typedef int HWND;
78typedef int INPUT_RECORD;
Bram Moolenaare0ab9792017-08-02 23:18:25 +020079typedef int INT;
Bram Moolenaar071d4272004-06-13 20:20:40 +000080typedef int KEY_EVENT_RECORD;
81typedef int LOGFONT;
82typedef int LPBOOL;
83typedef int LPCTSTR;
84typedef int LPDWORD;
85typedef int LPSTR;
86typedef int LPTSTR;
87typedef int LPVOID;
88typedef int MOUSE_EVENT_RECORD;
89typedef int PACL;
90typedef int PDWORD;
91typedef int PHANDLE;
92typedef int PRINTDLG;
93typedef int PSECURITY_DESCRIPTOR;
94typedef int PSID;
95typedef int SECURITY_INFORMATION;
96typedef int SHORT;
97typedef int SMALL_RECT;
98typedef int TEXTMETRIC;
99typedef int TOKEN_INFORMATION_CLASS;
100typedef int TRUSTEE;
101typedef int WORD;
102typedef int WCHAR;
103typedef void VOID;
Bram Moolenaar82881492012-11-20 16:53:39 +0100104typedef int BY_HANDLE_FILE_INFORMATION;
Bram Moolenaar32ac8cd2013-07-03 18:49:17 +0200105typedef int SE_OBJECT_TYPE;
106typedef int PSNSECINFO;
107typedef int PSNSECINFOW;
Bram Moolenaarb8e0bdb2014-11-12 16:10:48 +0100108typedef int STARTUPINFO;
109typedef int PROCESS_INFORMATION;
Bram Moolenaard90b6c02016-08-28 18:10:45 +0200110typedef int LPSECURITY_ATTRIBUTES;
Bram Moolenaar0f873732019-12-05 20:28:46 +0100111# define __stdcall // empty
Bram Moolenaar071d4272004-06-13 20:20:40 +0000112#endif
113
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200114#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar0f873732019-12-05 20:28:46 +0100115// Win32 Console handles for input and output
Bram Moolenaar071d4272004-06-13 20:20:40 +0000116static HANDLE g_hConIn = INVALID_HANDLE_VALUE;
117static HANDLE g_hConOut = INVALID_HANDLE_VALUE;
118
Bram Moolenaar0f873732019-12-05 20:28:46 +0100119// Win32 Screen buffer,coordinate,console I/O information
Bram Moolenaar071d4272004-06-13 20:20:40 +0000120static SMALL_RECT g_srScrollRegion;
Saleem Abdulrasool38bea302023-12-27 18:57:12 +0100121// This is explicitly initialised to work around a LTCG issue on Windows ARM64
122// (at least of 19.39.33321). This pushes this into the `.data` rather than
123// `.bss` which corrects code generation in `write_chars` (#13453).
124static COORD g_coord = {0, 0}; // 0-based, but external coords are 1-based
Bram Moolenaar071d4272004-06-13 20:20:40 +0000125
Bram Moolenaar0f873732019-12-05 20:28:46 +0100126// The attribute of the screen when the editor was started
127static WORD g_attrDefault = 7; // lightgray text on black background
Bram Moolenaar071d4272004-06-13 20:20:40 +0000128static WORD g_attrCurrent;
129
Bram Moolenaar0f873732019-12-05 20:28:46 +0100130static int g_fCBrkPressed = FALSE; // set by ctrl-break interrupt
131static int g_fCtrlCPressed = FALSE; // set when ctrl-C or ctrl-break detected
132static int g_fForceExit = FALSE; // set when forcefully exiting
Bram Moolenaar071d4272004-06-13 20:20:40 +0000133
Bram Moolenaar071d4272004-06-13 20:20:40 +0000134static void scroll(unsigned cLines);
135static void set_scroll_region(unsigned left, unsigned top,
136 unsigned right, unsigned bottom);
Bram Moolenaar6982f422019-02-16 16:48:01 +0100137static void set_scroll_region_tb(unsigned top, unsigned bottom);
138static void set_scroll_region_lr(unsigned left, unsigned right);
139static void insert_lines(unsigned cLines);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000140static void delete_lines(unsigned cLines);
141static void gotoxy(unsigned x, unsigned y);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000142static void standout(void);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000143static int s_cursor_visible = TRUE;
144static int did_create_conin = FALSE;
Christopher Plewright20b795e2022-12-20 20:01:58 +0000145// The 'input_record_buffer' is an internal dynamic fifo queue of MS-Windows
146// console INPUT_RECORD events that are normally read from the console input
147// buffer. This provides an injection point for testing the low-level handling
148// of INPUT_RECORDs.
149typedef struct input_record_buffer_node_S
150{
151 INPUT_RECORD ir;
152 struct input_record_buffer_node_S *next;
153} input_record_buffer_node_T;
154typedef struct input_record_buffer_S
155{
156 input_record_buffer_node_T *head;
157 input_record_buffer_node_T *tail;
158 int length;
159} input_record_buffer_T;
160static input_record_buffer_T input_record_buffer;
Christopher Plewright20b795e2022-12-20 20:01:58 +0000161static int read_input_record_buffer(INPUT_RECORD* irEvents, int nMaxLength);
162static int write_input_record_buffer(INPUT_RECORD* irEvents, int nLength);
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200163#endif
164#ifdef FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +0000165static int s_dont_use_vimrun = TRUE;
166static int need_vimrun_warning = FALSE;
167static char *vimrun_path = "vimrun ";
168#endif
169
Bram Moolenaar12b559e2013-06-12 22:41:37 +0200170static int win32_getattrs(char_u *name);
171static int win32_setattrs(char_u *name, int attrs);
172static int win32_set_archive(char_u *name);
173
Bram Moolenaard9ef1b82019-02-13 19:23:10 +0100174static int conpty_working = 0;
Bram Moolenaar57da6982019-09-13 22:30:11 +0200175static int conpty_type = 0;
Bram Moolenaard9ef1b82019-02-13 19:23:10 +0100176static int conpty_stable = 0;
Bram Moolenaar7ed8f592020-04-28 20:44:42 +0200177static int conpty_fix_type = 0;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100178static void vtp_flag_init();
179
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200180#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar6902c0e2019-02-16 14:07:37 +0100181static int vtp_working = 0;
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100182static void vtp_init();
183static void vtp_exit();
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100184static void vtp_sgr_bulk(int arg);
185static void vtp_sgr_bulks(int argc, int *argv);
186
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200187static int wt_working = 0;
Christopher Plewright1140b512022-11-12 18:46:05 +0000188static void wt_init(void);
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200189
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +0200190static int g_color_index_bg = 0;
191static int g_color_index_fg = 7;
192
193# ifdef FEAT_TERMGUICOLORS
Christopher Plewright38804d62022-11-09 23:55:52 +0000194static guicolor_T save_console_bg_rgb;
195static guicolor_T save_console_fg_rgb;
196static guicolor_T store_console_bg_rgb;
197static guicolor_T store_console_fg_rgb;
Yasuhiro Matsumotoe42c8da2022-09-01 11:31:45 +0100198static int default_console_color_bg = 0x000000; // black
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +0200199static int default_console_color_fg = 0xc0c0c0; // white
Christopher Plewrightf75a2cb2023-01-28 10:28:09 +0000200# define USE_VTP (vtp_working && is_term_win32() \
201 && (p_tgc || t_colors >= 256))
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200202# define USE_WT (wt_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100203# else
204# define USE_VTP 0
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200205# define USE_WT 0
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100206# endif
207
208static void set_console_color_rgb(void);
209static void reset_console_color_rgb(void);
Bram Moolenaardf543822020-01-30 11:53:59 +0100210static void restore_console_color_rgb(void);
Christopher Plewright20b795e2022-12-20 20:01:58 +0000211#endif // !FEAT_GUI_MSWIN || VIMDLL
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100212
Bram Moolenaar0f873732019-12-05 20:28:46 +0100213// This flag is newly created from Windows 10
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100214#ifndef ENABLE_VIRTUAL_TERMINAL_PROCESSING
215# define ENABLE_VIRTUAL_TERMINAL_PROCESSING 0x0004
216#endif
217
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200218#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar0f873732019-12-05 20:28:46 +0100219static int suppress_winsize = 1; // don't fiddle with console
Bram Moolenaar071d4272004-06-13 20:20:40 +0000220#endif
221
K.Takatace3189d2023-02-15 19:13:43 +0000222static WCHAR *exe_pathw = NULL;
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200223
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100224static BOOL win8_or_later = FALSE;
Christopher Plewrightc8b126d2022-12-22 13:45:23 +0000225static BOOL win10_22H2_or_later = FALSE;
Bram Moolenaar9fca1332022-12-22 21:06:41 +0000226#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Christopher Plewrightc8b126d2022-12-22 13:45:23 +0000227static BOOL use_alternate_screen_buffer = FALSE;
Bram Moolenaar9fca1332022-12-22 21:06:41 +0000228#endif
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100229
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100230/*
231 * Get version number including build number
232 */
233typedef BOOL (WINAPI *PfnRtlGetVersion)(LPOSVERSIONINFOW);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100234#define MAKE_VER(major, minor, build) \
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100235 (((major) << 24) | ((minor) << 16) | (build))
236
237 static DWORD
238get_build_number(void)
239{
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +0100240 OSVERSIONINFOW osver;
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100241 HMODULE hNtdll;
242 PfnRtlGetVersion pRtlGetVersion;
243 DWORD ver = MAKE_VER(0, 0, 0);
244
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +0100245 osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFOW);
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100246 hNtdll = GetModuleHandle("ntdll.dll");
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +0000247 if (hNtdll == NULL)
248 return ver;
249
250 pRtlGetVersion =
251 (PfnRtlGetVersion)GetProcAddress(hNtdll, "RtlGetVersion");
252 pRtlGetVersion(&osver);
253 ver = MAKE_VER(min(osver.dwMajorVersion, 255),
254 min(osver.dwMinorVersion, 255),
255 min(osver.dwBuildNumber, 32767));
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100256 return ver;
257}
258
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200259#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200260 static BOOL
261is_ambiwidth_event(
262 INPUT_RECORD *ir)
263{
264 return ir->EventType == KEY_EVENT
265 && ir->Event.KeyEvent.bKeyDown
266 && ir->Event.KeyEvent.wRepeatCount == 1
267 && ir->Event.KeyEvent.wVirtualKeyCode == 0x12
268 && ir->Event.KeyEvent.wVirtualScanCode == 0x38
K.Takata972db232022-02-04 10:45:38 +0000269 && ir->Event.KeyEvent.uChar.UnicodeChar == 0
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200270 && ir->Event.KeyEvent.dwControlKeyState == 2;
271}
272
273 static void
274make_ambiwidth_event(
275 INPUT_RECORD *down,
276 INPUT_RECORD *up)
277{
278 down->Event.KeyEvent.wVirtualKeyCode = 0;
279 down->Event.KeyEvent.wVirtualScanCode = 0;
K.Takata972db232022-02-04 10:45:38 +0000280 down->Event.KeyEvent.uChar.UnicodeChar
281 = up->Event.KeyEvent.uChar.UnicodeChar;
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200282 down->Event.KeyEvent.dwControlKeyState = 0;
283}
284
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100285/*
286 * Version of ReadConsoleInput() that works with IME.
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100287 * Works around problems on Windows 8.
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100288 */
289 static BOOL
290read_console_input(
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100291 HANDLE hInput,
292 INPUT_RECORD *lpBuffer,
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +0100293 int nLength,
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100294 LPDWORD lpEvents)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100295{
296 enum
297 {
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100298 IRSIZE = 10
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100299 };
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100300 static INPUT_RECORD s_irCache[IRSIZE];
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100301 static DWORD s_dwIndex = 0;
302 static DWORD s_dwMax = 0;
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100303 DWORD dwEvents;
Bram Moolenaardd415a62014-02-05 14:02:27 +0100304 int head;
305 int tail;
306 int i;
Bram Moolenaarbc970da2020-04-26 19:00:07 +0200307 static INPUT_RECORD s_irPseudo;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100308
Christopher Plewright20b795e2022-12-20 20:01:58 +0000309 if (s_dwMax == 0 && input_record_buffer.length > 0)
310 {
311 dwEvents = read_input_record_buffer(s_irCache, IRSIZE);
312 s_dwIndex = 0;
313 s_dwMax = dwEvents;
314 }
315
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200316 if (nLength == -2)
317 return (s_dwMax > 0) ? TRUE : FALSE;
318
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100319 if (!win8_or_later)
320 {
321 if (nLength == -1)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200322 return PeekConsoleInputW(hInput, lpBuffer, 1, lpEvents);
323 return ReadConsoleInputW(hInput, lpBuffer, 1, &dwEvents);
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100324 }
325
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100326 if (s_dwMax == 0)
327 {
Christopher Plewright38804d62022-11-09 23:55:52 +0000328 if (!vtp_working && nLength == -1)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200329 return PeekConsoleInputW(hInput, lpBuffer, 1, lpEvents);
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200330 GetNumberOfConsoleInputEvents(hInput, &dwEvents);
331 if (dwEvents == 0 && nLength == -1)
332 return PeekConsoleInputW(hInput, lpBuffer, 1, lpEvents);
333 ReadConsoleInputW(hInput, s_irCache, IRSIZE, &dwEvents);
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100334 s_dwIndex = 0;
335 s_dwMax = dwEvents;
336 if (dwEvents == 0)
337 {
338 *lpEvents = 0;
339 return TRUE;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100340 }
Bram Moolenaardd415a62014-02-05 14:02:27 +0100341
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200342 for (i = s_dwIndex; i < (int)s_dwMax - 1; ++i)
343 if (is_ambiwidth_event(&s_irCache[i]))
344 make_ambiwidth_event(&s_irCache[i], &s_irCache[i + 1]);
345
Bram Moolenaardd415a62014-02-05 14:02:27 +0100346 if (s_dwMax > 1)
347 {
348 head = 0;
349 tail = s_dwMax - 1;
350 while (head != tail)
351 {
352 if (s_irCache[head].EventType == WINDOW_BUFFER_SIZE_EVENT
353 && s_irCache[head + 1].EventType
354 == WINDOW_BUFFER_SIZE_EVENT)
355 {
Bram Moolenaar0f873732019-12-05 20:28:46 +0100356 // Remove duplicate event to avoid flicker.
Bram Moolenaardd415a62014-02-05 14:02:27 +0100357 for (i = head; i < tail; ++i)
358 s_irCache[i] = s_irCache[i + 1];
359 --tail;
360 continue;
361 }
362 head++;
363 }
364 s_dwMax = tail + 1;
365 }
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100366 }
Bram Moolenaardd415a62014-02-05 14:02:27 +0100367
Bram Moolenaarbc970da2020-04-26 19:00:07 +0200368 if (s_irCache[s_dwIndex].EventType == KEY_EVENT)
369 {
370 if (s_irCache[s_dwIndex].Event.KeyEvent.wRepeatCount > 1)
371 {
372 s_irPseudo = s_irCache[s_dwIndex];
373 s_irPseudo.Event.KeyEvent.wRepeatCount = 1;
374 s_irCache[s_dwIndex].Event.KeyEvent.wRepeatCount--;
375 *lpBuffer = s_irPseudo;
376 *lpEvents = 1;
377 return TRUE;
378 }
379 }
380
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100381 *lpBuffer = s_irCache[s_dwIndex];
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200382 if (!(nLength == -1 || nLength == -2) && ++s_dwIndex >= s_dwMax)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100383 s_dwMax = 0;
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100384 *lpEvents = 1;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100385 return TRUE;
386}
387
388/*
389 * Version of PeekConsoleInput() that works with IME.
390 */
391 static BOOL
392peek_console_input(
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100393 HANDLE hInput,
394 INPUT_RECORD *lpBuffer,
Bram Moolenaarbd67aac2019-09-21 23:09:04 +0200395 DWORD nLength UNUSED,
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100396 LPDWORD lpEvents)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100397{
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +0100398 return read_console_input(hInput, lpBuffer, -1, lpEvents);
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100399}
400
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100401# ifdef FEAT_CLIENTSERVER
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200402 static DWORD
403msg_wait_for_multiple_objects(
404 DWORD nCount,
405 LPHANDLE pHandles,
406 BOOL fWaitAll,
407 DWORD dwMilliseconds,
408 DWORD dwWakeMask)
409{
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +0100410 if (read_console_input(NULL, NULL, -2, NULL))
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200411 return WAIT_OBJECT_0;
412 return MsgWaitForMultipleObjects(nCount, pHandles, fWaitAll,
413 dwMilliseconds, dwWakeMask);
414}
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100415# endif
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200416
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100417# ifndef FEAT_CLIENTSERVER
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200418 static DWORD
419wait_for_single_object(
420 HANDLE hHandle,
421 DWORD dwMilliseconds)
422{
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +0100423 if (read_console_input(NULL, NULL, -2, NULL))
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200424 return WAIT_OBJECT_0;
425 return WaitForSingleObject(hHandle, dwMilliseconds);
426}
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100427# endif
Christopher Plewright20b795e2022-12-20 20:01:58 +0000428#endif // !FEAT_GUI_MSWIN || VIMDLL
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200429
K.Takatace3189d2023-02-15 19:13:43 +0000430 void
431mch_get_exe_name(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000432{
Bram Moolenaar0f873732019-12-05 20:28:46 +0100433 // Maximum length of $PATH is more than MAXPATHL. 8191 is often mentioned
K.Takataf741e3e2023-05-15 16:41:40 +0100434 // as the maximum length that works. Add 1 for a NUL byte and 5 for
435 // "PATH=".
436#define MAX_ENV_PATH_LEN (8191 + 1 + 5)
437 WCHAR temp[MAX_ENV_PATH_LEN];
K.Takatace3189d2023-02-15 19:13:43 +0000438 WCHAR buf[MAX_PATH];
439 int updated = FALSE;
440 static int enc_prev = -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000441
K.Takatace3189d2023-02-15 19:13:43 +0000442 if (exe_name == NULL || exe_pathw == NULL || enc_prev != enc_codepage)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000443 {
Bram Moolenaar0f873732019-12-05 20:28:46 +0100444 // store the name of the executable, may be used for $VIM
K.Takatace3189d2023-02-15 19:13:43 +0000445 GetModuleFileNameW(NULL, buf, MAX_PATH);
446 if (*buf != NUL)
447 {
448 if (enc_codepage == -1)
449 enc_codepage = GetACP();
K.Takataf741e3e2023-05-15 16:41:40 +0100450 vim_free(exe_name);
K.Takatace3189d2023-02-15 19:13:43 +0000451 exe_name = utf16_to_enc(buf, NULL);
452 enc_prev = enc_codepage;
453
454 WCHAR *wp = wcsrchr(buf, '\\');
455 if (wp != NULL)
456 *wp = NUL;
K.Takataf741e3e2023-05-15 16:41:40 +0100457 vim_free(exe_pathw);
K.Takatace3189d2023-02-15 19:13:43 +0000458 exe_pathw = _wcsdup(buf);
459 updated = TRUE;
460 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000461 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000462
K.Takatace3189d2023-02-15 19:13:43 +0000463 if (exe_pathw == NULL || !updated)
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +0000464 return;
465
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +0000466 // Append our starting directory to $PATH, so that when doing
467 // "!xxd" it's found in our starting directory. Needed because
468 // SearchPath() also looks there.
K.Takataf741e3e2023-05-15 16:41:40 +0100469 WCHAR *p = _wgetenv(L"PATH");
470 if (p == NULL || wcslen(p) + wcslen(exe_pathw) + 2 + 5 < MAX_ENV_PATH_LEN)
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000471 {
K.Takataf741e3e2023-05-15 16:41:40 +0100472 wcscpy(temp, L"PATH=");
473
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +0000474 if (p == NULL || *p == NUL)
K.Takataf741e3e2023-05-15 16:41:40 +0100475 wcscat(temp, exe_pathw);
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +0000476 else
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000477 {
K.Takataf741e3e2023-05-15 16:41:40 +0100478 wcscat(temp, p);
479
480 // Check if exe_path is already included in $PATH.
481 if (wcsstr(temp, exe_pathw) == NULL)
482 {
483 // Append ';' if $PATH doesn't end with it.
484 size_t len = wcslen(temp);
485 if (temp[len - 1] != L';')
486 wcscat(temp, L";");
487
488 wcscat(temp, exe_pathw);
489 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000490 }
K.Takataf741e3e2023-05-15 16:41:40 +0100491 _wputenv(temp);
492#ifdef libintl_wputenv
493 libintl_wputenv(temp);
494#endif
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000495 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000496}
497
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200498/*
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100499 * Unescape characters in "p" that appear in "escaped".
500 */
501 static void
502unescape_shellxquote(char_u *p, char_u *escaped)
503{
Bram Moolenaar4336cdf2012-02-29 13:58:47 +0100504 int l = (int)STRLEN(p);
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100505 int n;
506
507 while (*p != NUL)
508 {
509 if (*p == '^' && vim_strchr(escaped, p[1]) != NULL)
510 mch_memmove(p, p + 1, l--);
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100511 n = (*mb_ptr2len)(p);
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100512 p += n;
513 l -= n;
514 }
515}
516
517/*
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200518 * Load library "name".
519 */
520 HINSTANCE
K.Takatad68b2fc2022-02-12 11:18:37 +0000521vimLoadLib(const char *name)
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200522{
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200523 HINSTANCE dll = NULL;
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200524
Bram Moolenaar3d0e7a92021-05-01 17:46:03 +0200525 // No need to load any library when registering OLE.
526 if (found_register_arg)
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +0000527 return NULL;
Bram Moolenaar3d0e7a92021-05-01 17:46:03 +0200528
Bram Moolenaar0f873732019-12-05 20:28:46 +0100529 // NOTE: Do not use mch_dirname() and mch_chdir() here, they may call
530 // vimLoadLib() recursively, which causes a stack overflow.
K.Takatace3189d2023-02-15 19:13:43 +0000531 if (exe_pathw == NULL)
K.Takataf741e3e2023-05-15 16:41:40 +0100532 {
K.Takatace3189d2023-02-15 19:13:43 +0000533 mch_get_exe_name();
K.Takataf741e3e2023-05-15 16:41:40 +0100534 if (exe_pathw == NULL)
535 return NULL;
536 }
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +0000537
538 WCHAR old_dirw[MAXPATHL];
539
540 if (GetCurrentDirectoryW(MAXPATHL, old_dirw) == 0)
541 return NULL;
542
543 // Change directory to where the executable is, both to make
544 // sure we find a .dll there and to avoid looking for a .dll
545 // in the current directory.
K.Takatace3189d2023-02-15 19:13:43 +0000546 SetCurrentDirectoryW(exe_pathw);
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +0000547 dll = LoadLibrary(name);
548 SetCurrentDirectoryW(old_dirw);
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200549 return dll;
550}
551
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200552#if defined(VIMDLL) || defined(PROTO)
553/*
554 * Check if the current executable file is for the GUI subsystem.
555 */
556 int
557mch_is_gui_executable(void)
558{
559 PBYTE pImage = (PBYTE)GetModuleHandle(NULL);
560 PIMAGE_DOS_HEADER pDOS = (PIMAGE_DOS_HEADER)pImage;
561 PIMAGE_NT_HEADERS pPE;
562
563 if (pDOS->e_magic != IMAGE_DOS_SIGNATURE)
564 return FALSE;
565 pPE = (PIMAGE_NT_HEADERS)(pImage + pDOS->e_lfanew);
566 if (pPE->Signature != IMAGE_NT_SIGNATURE)
567 return FALSE;
568 if (pPE->OptionalHeader.Subsystem == IMAGE_SUBSYSTEM_WINDOWS_GUI)
569 return TRUE;
570 return FALSE;
571}
572#endif
573
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000574#if defined(DYNAMIC_ICONV) || defined(DYNAMIC_GETTEXT) \
575 || defined(FEAT_PYTHON3) || defined(PROTO)
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100576/*
577 * Get related information about 'funcname' which is imported by 'hInst'.
578 * If 'info' is 0, return the function address.
579 * If 'info' is 1, return the module name which the function is imported from.
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000580 * If 'info' is 2, hook the function with 'ptr', and return the original
581 * function address.
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100582 */
583 static void *
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000584get_imported_func_info(HINSTANCE hInst, const char *funcname, int info,
585 const void *ptr)
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100586{
587 PBYTE pImage = (PBYTE)hInst;
588 PIMAGE_DOS_HEADER pDOS = (PIMAGE_DOS_HEADER)hInst;
589 PIMAGE_NT_HEADERS pPE;
590 PIMAGE_IMPORT_DESCRIPTOR pImpDesc;
Bram Moolenaar0f873732019-12-05 20:28:46 +0100591 PIMAGE_THUNK_DATA pIAT; // Import Address Table
592 PIMAGE_THUNK_DATA pINT; // Import Name Table
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100593 PIMAGE_IMPORT_BY_NAME pImpName;
Ken Takata119fdd92023-10-04 20:05:05 +0200594 DWORD ImpVA;
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100595
596 if (pDOS->e_magic != IMAGE_DOS_SIGNATURE)
597 return NULL;
598 pPE = (PIMAGE_NT_HEADERS)(pImage + pDOS->e_lfanew);
599 if (pPE->Signature != IMAGE_NT_SIGNATURE)
600 return NULL;
Ken Takata119fdd92023-10-04 20:05:05 +0200601
602 ImpVA = pPE->OptionalHeader
603 .DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].VirtualAddress;
604 if (ImpVA == 0)
605 return NULL; // No Import Table
606 pImpDesc = (PIMAGE_IMPORT_DESCRIPTOR)(pImage + ImpVA);
607
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100608 for (; pImpDesc->FirstThunk; ++pImpDesc)
609 {
610 if (!pImpDesc->OriginalFirstThunk)
611 continue;
612 pIAT = (PIMAGE_THUNK_DATA)(pImage + pImpDesc->FirstThunk);
613 pINT = (PIMAGE_THUNK_DATA)(pImage + pImpDesc->OriginalFirstThunk);
614 for (; pIAT->u1.Function; ++pIAT, ++pINT)
615 {
616 if (IMAGE_SNAP_BY_ORDINAL(pINT->u1.Ordinal))
617 continue;
618 pImpName = (PIMAGE_IMPORT_BY_NAME)(pImage
619 + (UINT_PTR)(pINT->u1.AddressOfData));
620 if (strcmp((char *)pImpName->Name, funcname) == 0)
621 {
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000622 void *original;
623 DWORD old, new = PAGE_READWRITE;
624
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100625 switch (info)
626 {
627 case 0:
628 return (void *)pIAT->u1.Function;
629 case 1:
630 return (void *)(pImage + pImpDesc->Name);
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000631 case 2:
632 original = (void *)pIAT->u1.Function;
633 VirtualProtect(&pIAT->u1.Function, sizeof(void *),
634 new, &old);
635 pIAT->u1.Function = (UINT_PTR)ptr;
636 VirtualProtect(&pIAT->u1.Function, sizeof(void *),
637 old, &new);
638 return original;
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100639 default:
640 return NULL;
641 }
642 }
643 }
644 }
645 return NULL;
646}
647
648/*
649 * Get the module handle which 'funcname' in 'hInst' is imported from.
650 */
651 HINSTANCE
652find_imported_module_by_funcname(HINSTANCE hInst, const char *funcname)
653{
654 char *modulename;
655
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000656 modulename = (char *)get_imported_func_info(hInst, funcname, 1, NULL);
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100657 if (modulename != NULL)
658 return GetModuleHandleA(modulename);
659 return NULL;
660}
661
662/*
663 * Get the address of 'funcname' which is imported by 'hInst' DLL.
664 */
665 void *
666get_dll_import_func(HINSTANCE hInst, const char *funcname)
667{
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000668 return get_imported_func_info(hInst, funcname, 0, NULL);
669}
670
671/*
672 * Hook the function named 'funcname' which is imported by 'hInst' DLL,
673 * and return the original function address.
674 */
675 void *
676hook_dll_import_func(HINSTANCE hInst, const char *funcname, const void *hook)
677{
678 return get_imported_func_info(hInst, funcname, 2, hook);
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100679}
680#endif
681
Ken Takata119fdd92023-10-04 20:05:05 +0200682#if defined(FEAT_PYTHON3) || defined(PROTO)
683/*
684 * Check if the specified DLL is a function forwarder.
685 * If yes, return the instance of the forwarded DLL.
686 * If no, return the specified DLL.
687 * If error, return NULL.
688 * This assumes that the DLL forwards all the function to a single DLL.
689 */
690 HINSTANCE
691get_forwarded_dll(HINSTANCE hInst)
692{
693 PBYTE pImage = (PBYTE)hInst;
694 PIMAGE_DOS_HEADER pDOS = (PIMAGE_DOS_HEADER)hInst;
695 PIMAGE_NT_HEADERS pPE;
696 PIMAGE_EXPORT_DIRECTORY pExpDir;
697 DWORD ExpVA;
698 DWORD ExpSize;
699 LPDWORD pFunctionTable;
700
701 if (pDOS->e_magic != IMAGE_DOS_SIGNATURE)
702 return NULL;
703 pPE = (PIMAGE_NT_HEADERS)(pImage + pDOS->e_lfanew);
704 if (pPE->Signature != IMAGE_NT_SIGNATURE)
705 return NULL;
706
707 ExpVA = pPE->OptionalHeader
708 .DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress;
709 ExpSize = pPE->OptionalHeader
710 .DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].Size;
711 if (ExpVA == 0)
712 return hInst; // No Export Directory
713 pExpDir = (PIMAGE_EXPORT_DIRECTORY)(pImage + ExpVA);
714 pFunctionTable = (LPDWORD)(pImage + pExpDir->AddressOfFunctions);
715
716 if (pExpDir->NumberOfNames == 0)
717 return hInst; // No export names.
718
719 // Check only the first entry.
720 if ((pFunctionTable[0] < ExpVA) || (pFunctionTable[0] >= ExpVA + ExpSize))
721 // The first entry is not a function forwarder.
722 return hInst;
723
724 // The first entry is a function forwarder.
725 // The name is represented as "DllName.FunctionName".
726 const char *name = (const char *)(pImage + pFunctionTable[0]);
727 const char *p = strchr(name, '.');
728 if (p == NULL)
729 return hInst;
730
731 // Extract DllName.
732 char buf[MAX_PATH];
733 if (p - name + 1 > sizeof(buf))
734 return NULL;
735 strncpy(buf, name, p - name);
736 buf[p - name] = '\0';
737 return GetModuleHandleA(buf);
738}
739#endif
740
Bram Moolenaar071d4272004-06-13 20:20:40 +0000741#if defined(DYNAMIC_GETTEXT) || defined(PROTO)
742# ifndef GETTEXT_DLL
743# define GETTEXT_DLL "libintl.dll"
Bram Moolenaar7554c542018-10-06 15:03:15 +0200744# define GETTEXT_DLL_ALT1 "libintl-8.dll"
745# define GETTEXT_DLL_ALT2 "intl.dll"
Bram Moolenaar071d4272004-06-13 20:20:40 +0000746# endif
Bram Moolenaar0f873732019-12-05 20:28:46 +0100747// Dummy functions
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000748static char *null_libintl_gettext(const char *);
Bram Moolenaaree695f72016-08-03 22:08:45 +0200749static char *null_libintl_ngettext(const char *, const char *, unsigned long n);
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000750static char *null_libintl_textdomain(const char *);
751static char *null_libintl_bindtextdomain(const char *, const char *);
752static char *null_libintl_bind_textdomain_codeset(const char *, const char *);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100753static int null_libintl_wputenv(const wchar_t *);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000754
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200755static HINSTANCE hLibintlDLL = NULL;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000756char *(*dyn_libintl_gettext)(const char *) = null_libintl_gettext;
Bram Moolenaaree695f72016-08-03 22:08:45 +0200757char *(*dyn_libintl_ngettext)(const char *, const char *, unsigned long n)
758 = null_libintl_ngettext;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000759char *(*dyn_libintl_textdomain)(const char *) = null_libintl_textdomain;
760char *(*dyn_libintl_bindtextdomain)(const char *, const char *)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000761 = null_libintl_bindtextdomain;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000762char *(*dyn_libintl_bind_textdomain_codeset)(const char *, const char *)
763 = null_libintl_bind_textdomain_codeset;
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100764int (*dyn_libintl_wputenv)(const wchar_t *) = null_libintl_wputenv;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000765
766 int
Bram Moolenaar05540972016-01-30 20:31:25 +0100767dyn_libintl_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000768{
769 int i;
770 static struct
771 {
772 char *name;
773 FARPROC *ptr;
774 } libintl_entry[] =
775 {
776 {"gettext", (FARPROC*)&dyn_libintl_gettext},
Bram Moolenaaree695f72016-08-03 22:08:45 +0200777 {"ngettext", (FARPROC*)&dyn_libintl_ngettext},
Bram Moolenaar071d4272004-06-13 20:20:40 +0000778 {"textdomain", (FARPROC*)&dyn_libintl_textdomain},
779 {"bindtextdomain", (FARPROC*)&dyn_libintl_bindtextdomain},
780 {NULL, NULL}
781 };
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100782 HINSTANCE hmsvcrt;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000783
Bram Moolenaar7554c542018-10-06 15:03:15 +0200784 // No need to initialize twice.
785 if (hLibintlDLL != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000786 return 1;
Bram Moolenaar7554c542018-10-06 15:03:15 +0200787 // Load gettext library (libintl.dll and other names).
Bram Moolenaar923e43b2016-01-28 15:07:38 +0100788 hLibintlDLL = vimLoadLib(GETTEXT_DLL);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100789# ifdef GETTEXT_DLL_ALT1
Bram Moolenaar286eacd2016-01-16 18:05:50 +0100790 if (!hLibintlDLL)
Bram Moolenaar7554c542018-10-06 15:03:15 +0200791 hLibintlDLL = vimLoadLib(GETTEXT_DLL_ALT1);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100792# endif
793# ifdef GETTEXT_DLL_ALT2
Bram Moolenaar7554c542018-10-06 15:03:15 +0200794 if (!hLibintlDLL)
795 hLibintlDLL = vimLoadLib(GETTEXT_DLL_ALT2);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100796# endif
Bram Moolenaar938ee832016-01-24 15:36:03 +0100797 if (!hLibintlDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000798 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200799 if (p_verbose > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000800 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200801 verbose_enter();
Bram Moolenaar460ae5d2022-01-01 14:19:49 +0000802 semsg(_(e_could_not_load_library_str_str), GETTEXT_DLL, GetWin32Error());
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200803 verbose_leave();
Bram Moolenaar071d4272004-06-13 20:20:40 +0000804 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200805 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000806 }
807 for (i = 0; libintl_entry[i].name != NULL
808 && libintl_entry[i].ptr != NULL; ++i)
809 {
K.Takata54119102022-02-03 13:33:03 +0000810 if ((*libintl_entry[i].ptr = GetProcAddress(hLibintlDLL,
Bram Moolenaar071d4272004-06-13 20:20:40 +0000811 libintl_entry[i].name)) == NULL)
812 {
813 dyn_libintl_end();
814 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +0000815 {
816 verbose_enter();
Bram Moolenaar460ae5d2022-01-01 14:19:49 +0000817 semsg(_(e_could_not_load_library_function_str), libintl_entry[i].name);
Bram Moolenaara04f10b2005-05-31 22:09:46 +0000818 verbose_leave();
819 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000820 return 0;
821 }
822 }
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000823
Bram Moolenaar0f873732019-12-05 20:28:46 +0100824 // The bind_textdomain_codeset() function is optional.
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +0100825 dyn_libintl_bind_textdomain_codeset = (char *(*)(const char *, const char *))
826 GetProcAddress(hLibintlDLL, "bind_textdomain_codeset");
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000827 if (dyn_libintl_bind_textdomain_codeset == NULL)
828 dyn_libintl_bind_textdomain_codeset =
829 null_libintl_bind_textdomain_codeset;
830
Bram Moolenaar0f873732019-12-05 20:28:46 +0100831 // _wputenv() function for the libintl.dll is optional.
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100832 hmsvcrt = find_imported_module_by_funcname(hLibintlDLL, "getenv");
833 if (hmsvcrt != NULL)
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +0100834 dyn_libintl_wputenv = (int (*)(const wchar_t *))
835 GetProcAddress(hmsvcrt, "_wputenv");
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100836 if (dyn_libintl_wputenv == NULL || dyn_libintl_wputenv == _wputenv)
837 dyn_libintl_wputenv = null_libintl_wputenv;
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100838
Bram Moolenaar071d4272004-06-13 20:20:40 +0000839 return 1;
840}
841
842 void
Bram Moolenaar05540972016-01-30 20:31:25 +0100843dyn_libintl_end(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000844{
845 if (hLibintlDLL)
846 FreeLibrary(hLibintlDLL);
847 hLibintlDLL = NULL;
848 dyn_libintl_gettext = null_libintl_gettext;
Bram Moolenaaree695f72016-08-03 22:08:45 +0200849 dyn_libintl_ngettext = null_libintl_ngettext;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000850 dyn_libintl_textdomain = null_libintl_textdomain;
851 dyn_libintl_bindtextdomain = null_libintl_bindtextdomain;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000852 dyn_libintl_bind_textdomain_codeset = null_libintl_bind_textdomain_codeset;
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100853 dyn_libintl_wputenv = null_libintl_wputenv;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000854}
855
856 static char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000857null_libintl_gettext(const char *msgid)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000858{
859 return (char*)msgid;
860}
861
862 static char *
Bram Moolenaaree695f72016-08-03 22:08:45 +0200863null_libintl_ngettext(
864 const char *msgid,
865 const char *msgid_plural,
866 unsigned long n)
867{
Bram Moolenaarc90f2ae2016-08-04 22:00:15 +0200868 return (char *)(n == 1 ? msgid : msgid_plural);
Bram Moolenaaree695f72016-08-03 22:08:45 +0200869}
870
Bram Moolenaaree695f72016-08-03 22:08:45 +0200871 static char *
Bram Moolenaar1266d672017-02-01 13:43:36 +0100872null_libintl_bindtextdomain(
873 const char *domainname UNUSED,
874 const char *dirname UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000875{
876 return NULL;
877}
878
879 static char *
Bram Moolenaar1266d672017-02-01 13:43:36 +0100880null_libintl_bind_textdomain_codeset(
881 const char *domainname UNUSED,
882 const char *codeset UNUSED)
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000883{
884 return NULL;
885}
886
887 static char *
Bram Moolenaar1266d672017-02-01 13:43:36 +0100888null_libintl_textdomain(const char *domainname UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000889{
890 return NULL;
891}
892
Bram Moolenaare0ab9792017-08-02 23:18:25 +0200893 static int
Bram Moolenaar1266d672017-02-01 13:43:36 +0100894null_libintl_wputenv(const wchar_t *envstring UNUSED)
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100895{
896 return 0;
897}
898
Bram Moolenaar0f873732019-12-05 20:28:46 +0100899#endif // DYNAMIC_GETTEXT
Bram Moolenaar071d4272004-06-13 20:20:40 +0000900
Bram Moolenaar0f873732019-12-05 20:28:46 +0100901// This symbol is not defined in older versions of the SDK or Visual C++
Bram Moolenaar071d4272004-06-13 20:20:40 +0000902
903#ifndef VER_PLATFORM_WIN32_WINDOWS
904# define VER_PLATFORM_WIN32_WINDOWS 1
905#endif
906
Bram Moolenaar071d4272004-06-13 20:20:40 +0000907#ifdef HAVE_ACL
Bram Moolenaar82881492012-11-20 16:53:39 +0100908# ifndef PROTO
909# include <aclapi.h>
910# endif
Bram Moolenaar27515922013-06-29 15:36:26 +0200911# ifndef PROTECTED_DACL_SECURITY_INFORMATION
912# define PROTECTED_DACL_SECURITY_INFORMATION 0x80000000L
913# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000914#endif
915
Bram Moolenaar27515922013-06-29 15:36:26 +0200916#ifdef HAVE_ACL
917/*
918 * Enables or disables the specified privilege.
919 */
920 static BOOL
921win32_enable_privilege(LPTSTR lpszPrivilege, BOOL bEnable)
922{
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100923 BOOL bResult;
924 LUID luid;
925 HANDLE hToken;
926 TOKEN_PRIVILEGES tokenPrivileges;
Bram Moolenaar27515922013-06-29 15:36:26 +0200927
928 if (!OpenProcessToken(GetCurrentProcess(),
929 TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
930 return FALSE;
931
932 if (!LookupPrivilegeValue(NULL, lpszPrivilege, &luid))
933 {
934 CloseHandle(hToken);
935 return FALSE;
936 }
937
Bram Moolenaar45500912014-07-09 20:51:07 +0200938 tokenPrivileges.PrivilegeCount = 1;
Bram Moolenaar27515922013-06-29 15:36:26 +0200939 tokenPrivileges.Privileges[0].Luid = luid;
940 tokenPrivileges.Privileges[0].Attributes = bEnable ?
941 SE_PRIVILEGE_ENABLED : 0;
942
943 bResult = AdjustTokenPrivileges(hToken, FALSE, &tokenPrivileges,
944 sizeof(TOKEN_PRIVILEGES), NULL, NULL);
945
946 CloseHandle(hToken);
947
948 return bResult && GetLastError() == ERROR_SUCCESS;
949}
950#endif
951
Bram Moolenaar29d2f452020-12-04 19:42:52 +0100952#ifdef _MSC_VER
953// Suppress the deprecation warning for using GetVersionEx().
954// It is needed for implementing "windowsversion()".
955# pragma warning(push)
956# pragma warning(disable: 4996)
957#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000958/*
Bram Moolenaar1e1d2e82020-05-18 20:17:02 +0200959 * Set "win8_or_later" and fill in "windowsVersion" if possible.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000960 */
961 void
962PlatformId(void)
963{
964 static int done = FALSE;
965
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +0000966 if (done)
967 return;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000968
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +0000969 OSVERSIONINFO ovi;
970
971 ovi.dwOSVersionInfoSize = sizeof(ovi);
972 GetVersionEx(&ovi);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000973
Bram Moolenaar1e1d2e82020-05-18 20:17:02 +0200974#ifdef FEAT_EVAL
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +0000975 vim_snprintf(windowsVersion, sizeof(windowsVersion), "%d.%d",
976 (int)ovi.dwMajorVersion, (int)ovi.dwMinorVersion);
Bram Moolenaar1e1d2e82020-05-18 20:17:02 +0200977#endif
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +0000978 if ((ovi.dwMajorVersion == 6 && ovi.dwMinorVersion >= 2)
979 || ovi.dwMajorVersion > 6)
980 win8_or_later = TRUE;
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100981
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +0000982 if ((ovi.dwMajorVersion == 10 && ovi.dwBuildNumber >= 19045)
983 || ovi.dwMajorVersion > 10)
984 win10_22H2_or_later = TRUE;
Christopher Plewright1140b512022-11-12 18:46:05 +0000985
Bram Moolenaar071d4272004-06-13 20:20:40 +0000986#ifdef HAVE_ACL
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +0000987 // Enable privilege for getting or setting SACLs.
988 win32_enable_privilege(SE_SECURITY_NAME, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000989#endif
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +0000990 done = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000991}
Bram Moolenaar29d2f452020-12-04 19:42:52 +0100992#ifdef _MSC_VER
993# pragma warning(pop)
994#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000995
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200996#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000997
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100998# define SHIFT (SHIFT_PRESSED)
999# define CTRL (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED)
1000# define ALT (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED)
1001# define ALT_GR (RIGHT_ALT_PRESSED | LEFT_CTRL_PRESSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001002
1003
Bram Moolenaar0f873732019-12-05 20:28:46 +01001004// When uChar.AsciiChar is 0, then we need to look at wVirtualKeyCode.
1005// We map function keys to their ANSI terminal equivalents, as produced
1006// by ANSI.SYS, for compatibility with the MS-DOS version of Vim. Any
1007// ANSI key with a value >= '\300' is nonstandard, but provided anyway
1008// so that the user can have access to all SHIFT-, CTRL-, and ALT-
1009// combinations of function/arrow/etc keys.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001010
Bram Moolenaard6f676d2005-06-01 21:51:55 +00001011static const struct
Bram Moolenaar071d4272004-06-13 20:20:40 +00001012{
1013 WORD wVirtKey;
1014 BOOL fAnsiKey;
1015 int chAlone;
1016 int chShift;
1017 int chCtrl;
1018 int chAlt;
1019} VirtKeyMap[] =
1020{
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +02001021// Key ANSI alone shift ctrl alt
Bram Moolenaar071d4272004-06-13 20:20:40 +00001022 { VK_ESCAPE,FALSE, ESC, ESC, ESC, ESC, },
1023
1024 { VK_F1, TRUE, ';', 'T', '^', 'h', },
1025 { VK_F2, TRUE, '<', 'U', '_', 'i', },
1026 { VK_F3, TRUE, '=', 'V', '`', 'j', },
1027 { VK_F4, TRUE, '>', 'W', 'a', 'k', },
1028 { VK_F5, TRUE, '?', 'X', 'b', 'l', },
1029 { VK_F6, TRUE, '@', 'Y', 'c', 'm', },
1030 { VK_F7, TRUE, 'A', 'Z', 'd', 'n', },
1031 { VK_F8, TRUE, 'B', '[', 'e', 'o', },
1032 { VK_F9, TRUE, 'C', '\\', 'f', 'p', },
1033 { VK_F10, TRUE, 'D', ']', 'g', 'q', },
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +02001034 { VK_F11, TRUE, '\205', '\207', '\211', '\213', },
1035 { VK_F12, TRUE, '\206', '\210', '\212', '\214', },
Bram Moolenaar071d4272004-06-13 20:20:40 +00001036
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +02001037 { VK_HOME, TRUE, 'G', '\302', 'w', '\303', },
1038 { VK_UP, TRUE, 'H', '\304', '\305', '\306', },
1039 { VK_PRIOR, TRUE, 'I', '\307', '\204', '\310', }, // PgUp
1040 { VK_LEFT, TRUE, 'K', '\311', 's', '\312', },
1041 { VK_RIGHT, TRUE, 'M', '\313', 't', '\314', },
1042 { VK_END, TRUE, 'O', '\315', 'u', '\316', },
1043 { VK_DOWN, TRUE, 'P', '\317', '\320', '\321', },
1044 { VK_NEXT, TRUE, 'Q', '\322', 'v', '\323', }, // PgDn
1045 { VK_INSERT,TRUE, 'R', '\324', '\325', '\326', },
1046 { VK_DELETE,TRUE, 'S', '\327', '\330', '\331', },
Bram Moolenaarb70a47b2019-03-30 22:11:21 +01001047 { VK_BACK, TRUE, 'x', 'y', 'z', '{', }, // Backspace
Bram Moolenaar071d4272004-06-13 20:20:40 +00001048
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +02001049 { VK_SNAPSHOT,TRUE, 0, 0, 0, 'r', }, // PrtScrn
Bram Moolenaar071d4272004-06-13 20:20:40 +00001050
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001051# if 0
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +02001052 // Most people don't have F13-F20, but what the hell...
1053 { VK_F13, TRUE, '\332', '\333', '\334', '\335', },
1054 { VK_F14, TRUE, '\336', '\337', '\340', '\341', },
1055 { VK_F15, TRUE, '\342', '\343', '\344', '\345', },
1056 { VK_F16, TRUE, '\346', '\347', '\350', '\351', },
1057 { VK_F17, TRUE, '\352', '\353', '\354', '\355', },
1058 { VK_F18, TRUE, '\356', '\357', '\360', '\361', },
1059 { VK_F19, TRUE, '\362', '\363', '\364', '\365', },
1060 { VK_F20, TRUE, '\366', '\367', '\370', '\371', },
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001061# endif
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +02001062 { VK_ADD, TRUE, 'N', 'N', 'N', 'N', }, // keyp '+'
1063 { VK_SUBTRACT, TRUE,'J', 'J', 'J', 'J', }, // keyp '-'
1064 // { VK_DIVIDE, TRUE,'N', 'N', 'N', 'N', }, // keyp '/'
1065 { VK_MULTIPLY, TRUE,'7', '7', '7', '7', }, // keyp '*'
Bram Moolenaar071d4272004-06-13 20:20:40 +00001066
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +02001067 { VK_NUMPAD0,TRUE, '\332', '\333', '\334', '\335', },
1068 { VK_NUMPAD1,TRUE, '\336', '\337', '\340', '\341', },
1069 { VK_NUMPAD2,TRUE, '\342', '\343', '\344', '\345', },
1070 { VK_NUMPAD3,TRUE, '\346', '\347', '\350', '\351', },
1071 { VK_NUMPAD4,TRUE, '\352', '\353', '\354', '\355', },
1072 { VK_NUMPAD5,TRUE, '\356', '\357', '\360', '\361', },
1073 { VK_NUMPAD6,TRUE, '\362', '\363', '\364', '\365', },
1074 { VK_NUMPAD7,TRUE, '\366', '\367', '\370', '\371', },
1075 { VK_NUMPAD8,TRUE, '\372', '\373', '\374', '\375', },
1076 // Sorry, out of number space! <negri>
Bram Moolenaarb70a47b2019-03-30 22:11:21 +01001077 { VK_NUMPAD9,TRUE, '\376', '\377', '|', '}', },
Bram Moolenaar071d4272004-06-13 20:20:40 +00001078};
1079
1080
Bram Moolenaar0f873732019-12-05 20:28:46 +01001081/*
1082 * The return code indicates key code size.
1083 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001084 static int
Bram Moolenaar071d4272004-06-13 20:20:40 +00001085win32_kbd_patch_key(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001086 KEY_EVENT_RECORD *pker)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001087{
1088 UINT uMods = pker->dwControlKeyState;
1089 static int s_iIsDead = 0;
1090 static WORD awAnsiCode[2];
1091 static BYTE abKeystate[256];
1092
1093
1094 if (s_iIsDead == 2)
1095 {
K.Takata972db232022-02-04 10:45:38 +00001096 pker->uChar.UnicodeChar = (WCHAR) awAnsiCode[1];
Bram Moolenaar071d4272004-06-13 20:20:40 +00001097 s_iIsDead = 0;
1098 return 1;
1099 }
1100
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001101 // check if it already has a valid unicode character.
Christopher Plewright566f76e2023-01-10 13:43:04 +00001102 if (pker->uChar.UnicodeChar != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001103 return 1;
1104
Bram Moolenaara80faa82020-04-12 19:37:17 +02001105 CLEAR_FIELD(abKeystate);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001106
Bram Moolenaar0f873732019-12-05 20:28:46 +01001107 // Clear any pending dead keys
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001108 ToUnicode(VK_SPACE, MapVirtualKey(VK_SPACE, 0), abKeystate, awAnsiCode, 2, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001109
1110 if (uMods & SHIFT_PRESSED)
1111 abKeystate[VK_SHIFT] = 0x80;
1112 if (uMods & CAPSLOCK_ON)
1113 abKeystate[VK_CAPITAL] = 1;
1114
1115 if ((uMods & ALT_GR) == ALT_GR)
1116 {
1117 abKeystate[VK_CONTROL] = abKeystate[VK_LCONTROL] =
1118 abKeystate[VK_MENU] = abKeystate[VK_RMENU] = 0x80;
1119 }
1120
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001121 s_iIsDead = ToUnicode(pker->wVirtualKeyCode, pker->wVirtualScanCode,
1122 abKeystate, awAnsiCode, 2, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001123
1124 if (s_iIsDead > 0)
K.Takata972db232022-02-04 10:45:38 +00001125 pker->uChar.UnicodeChar = (WCHAR) awAnsiCode[0];
Bram Moolenaar071d4272004-06-13 20:20:40 +00001126
1127 return s_iIsDead;
1128}
1129
Bram Moolenaar071d4272004-06-13 20:20:40 +00001130static BOOL g_fJustGotFocus = FALSE;
1131
1132/*
1133 * Decode a KEY_EVENT into one or two keystrokes
1134 */
1135 static BOOL
1136decode_key_event(
1137 KEY_EVENT_RECORD *pker,
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001138 WCHAR *pch,
1139 WCHAR *pch2,
Bram Moolenaar071d4272004-06-13 20:20:40 +00001140 int *pmodifiers,
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02001141 BOOL fDoPost UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001142{
1143 int i;
1144 const int nModifs = pker->dwControlKeyState & (SHIFT | ALT | CTRL);
1145
1146 *pch = *pch2 = NUL;
1147 g_fJustGotFocus = FALSE;
1148
Bram Moolenaar0f873732019-12-05 20:28:46 +01001149 // ignore key up events
Bram Moolenaar071d4272004-06-13 20:20:40 +00001150 if (!pker->bKeyDown)
1151 return FALSE;
1152
Bram Moolenaar0f873732019-12-05 20:28:46 +01001153 // ignore some keystrokes
Bram Moolenaar071d4272004-06-13 20:20:40 +00001154 switch (pker->wVirtualKeyCode)
1155 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001156 // modifiers
Bram Moolenaar071d4272004-06-13 20:20:40 +00001157 case VK_SHIFT:
1158 case VK_CONTROL:
Bram Moolenaar0f873732019-12-05 20:28:46 +01001159 case VK_MENU: // Alt key
Bram Moolenaar071d4272004-06-13 20:20:40 +00001160 return FALSE;
1161
1162 default:
1163 break;
1164 }
1165
Bram Moolenaar0f873732019-12-05 20:28:46 +01001166 // Shift-TAB
Bram Moolenaar071d4272004-06-13 20:20:40 +00001167 if (pker->wVirtualKeyCode == VK_TAB && (nModifs & SHIFT_PRESSED))
1168 {
1169 *pch = K_NUL;
1170 *pch2 = '\017';
1171 return TRUE;
1172 }
1173
K.Takataeeec2542021-06-02 13:28:16 +02001174 for (i = ARRAY_LENGTH(VirtKeyMap); --i >= 0; )
Bram Moolenaar071d4272004-06-13 20:20:40 +00001175 {
1176 if (VirtKeyMap[i].wVirtKey == pker->wVirtualKeyCode)
1177 {
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001178 *pch = VirtKeyMap[i].chAlone;
1179 if ((nModifs & SHIFT) != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001180 *pch = VirtKeyMap[i].chShift;
1181 else if ((nModifs & CTRL) != 0 && (nModifs & ~CTRL) == 0)
1182 *pch = VirtKeyMap[i].chCtrl;
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001183 else if ((nModifs & ALT) != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001184 *pch = VirtKeyMap[i].chAlt;
1185
1186 if (*pch != 0)
1187 {
1188 if (VirtKeyMap[i].fAnsiKey)
1189 {
1190 *pch2 = *pch;
1191 *pch = K_NUL;
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001192 if (pmodifiers)
1193 {
1194 if (pker->wVirtualKeyCode >= VK_F1
1195 && pker->wVirtualKeyCode <= VK_F12)
1196 {
1197 if ((nModifs & ALT) != 0)
1198 {
1199 *pmodifiers |= MOD_MASK_ALT;
1200 if ((nModifs & SHIFT) == 0)
1201 *pch2 = VirtKeyMap[i].chAlone;
1202 }
1203 if ((nModifs & CTRL) != 0)
1204 {
1205 *pmodifiers |= MOD_MASK_CTRL;
1206 if ((nModifs & SHIFT) == 0)
1207 *pch2 = VirtKeyMap[i].chAlone;
1208 }
1209 }
1210 else if (pker->wVirtualKeyCode >= VK_END
1211 && pker->wVirtualKeyCode <= VK_DOWN)
1212 {
Christopher Plewright566f76e2023-01-10 13:43:04 +00001213 // (0x23 - 0x28): VK_END, VK_HOME,
1214 // VK_LEFT, VK_UP, VK_RIGHT, VK_DOWN
1215
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001216 *pmodifiers = 0;
1217 *pch2 = VirtKeyMap[i].chAlone;
1218 if ((nModifs & SHIFT) != 0
1219 && (nModifs & ~SHIFT) == 0)
1220 {
1221 *pch2 = VirtKeyMap[i].chShift;
1222 }
Christopher Plewright566f76e2023-01-10 13:43:04 +00001223 if ((nModifs & CTRL) != 0
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001224 && (nModifs & ~CTRL) == 0)
1225 {
1226 *pch2 = VirtKeyMap[i].chCtrl;
1227 if (pker->wVirtualKeyCode == VK_UP
1228 || pker->wVirtualKeyCode == VK_DOWN)
1229 {
1230 *pmodifiers |= MOD_MASK_CTRL;
1231 *pch2 = VirtKeyMap[i].chAlone;
1232 }
1233 }
Christopher Plewright566f76e2023-01-10 13:43:04 +00001234 if ((nModifs & SHIFT) != 0
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001235 && (nModifs & CTRL) != 0)
1236 {
1237 *pmodifiers |= MOD_MASK_CTRL;
1238 *pch2 = VirtKeyMap[i].chShift;
1239 }
Christopher Plewright566f76e2023-01-10 13:43:04 +00001240 if ((nModifs & ALT) != 0)
1241 {
1242 *pch2 = VirtKeyMap[i].chAlt;
1243 *pmodifiers |= MOD_MASK_ALT;
1244 if ((nModifs & ~ALT) == 0)
1245 {
1246 *pch2 = VirtKeyMap[i].chAlone;
1247 }
1248 else if ((nModifs & SHIFT) != 0)
1249 {
1250 *pch2 = VirtKeyMap[i].chShift;
1251 }
1252 else if ((nModifs & CTRL) != 0)
1253 {
1254 if (pker->wVirtualKeyCode == VK_UP
1255 || pker->wVirtualKeyCode == VK_DOWN)
1256 {
1257 *pmodifiers |= MOD_MASK_CTRL;
1258 *pch2 = VirtKeyMap[i].chAlone;
1259 }
1260 else
1261 {
1262 *pch2 = VirtKeyMap[i].chCtrl;
1263 }
1264 }
1265 }
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001266 }
1267 else
1268 {
1269 *pch2 = VirtKeyMap[i].chAlone;
1270 if ((nModifs & SHIFT) != 0)
1271 *pmodifiers |= MOD_MASK_SHIFT;
1272 if ((nModifs & CTRL) != 0)
1273 *pmodifiers |= MOD_MASK_CTRL;
1274 if ((nModifs & ALT) != 0)
1275 *pmodifiers |= MOD_MASK_ALT;
1276 }
1277 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001278 }
1279
1280 return TRUE;
1281 }
1282 }
1283 }
1284
1285 i = win32_kbd_patch_key(pker);
1286
1287 if (i < 0)
1288 *pch = NUL;
1289 else
1290 {
K.Takata972db232022-02-04 10:45:38 +00001291 *pch = (i > 0) ? pker->uChar.UnicodeChar : NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001292
1293 if (pmodifiers != NULL)
1294 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001295 // Pass on the ALT key as a modifier, but only when not combined
1296 // with CTRL (which is ALTGR).
Bram Moolenaar071d4272004-06-13 20:20:40 +00001297 if ((nModifs & ALT) != 0 && (nModifs & CTRL) == 0)
1298 *pmodifiers |= MOD_MASK_ALT;
1299
Bram Moolenaar0f873732019-12-05 20:28:46 +01001300 // Pass on SHIFT only for special keys, because we don't know when
1301 // it's already included with the character.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001302 if ((nModifs & SHIFT) != 0 && *pch <= 0x20)
1303 *pmodifiers |= MOD_MASK_SHIFT;
1304
Bram Moolenaar0f873732019-12-05 20:28:46 +01001305 // Pass on CTRL only for non-special keys, because we don't know
1306 // when it's already included with the character. And not when
1307 // combined with ALT (which is ALTGR).
Bram Moolenaar071d4272004-06-13 20:20:40 +00001308 if ((nModifs & CTRL) != 0 && (nModifs & ALT) == 0
1309 && *pch >= 0x20 && *pch < 0x80)
1310 *pmodifiers |= MOD_MASK_CTRL;
1311 }
1312 }
1313
1314 return (*pch != NUL);
1315}
1316
Christopher Plewright20b795e2022-12-20 20:01:58 +00001317# if defined(FEAT_EVAL)
1318 static int
1319encode_key_event(dict_T *args, INPUT_RECORD *ir)
1320{
1321 static int s_dwMods = 0;
1322
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001323 char_u *action = dict_get_string(args, "event", TRUE);
1324 if (action && (STRICMP(action, "keydown") == 0
1325 || STRICMP(action, "keyup") == 0))
Christopher Plewright20b795e2022-12-20 20:01:58 +00001326 {
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001327 BOOL isKeyDown = STRICMP(action, "keydown") == 0;
Christopher Plewright20b795e2022-12-20 20:01:58 +00001328 WORD vkCode = dict_get_number_def(args, "keycode", 0);
1329 if (vkCode <= 0 || vkCode >= 0xFF)
1330 {
1331 semsg(_(e_invalid_argument_nr), (long)vkCode);
1332 return FALSE;
1333 }
1334
1335 ir->EventType = KEY_EVENT;
1336 KEY_EVENT_RECORD ker;
1337 ZeroMemory(&ker, sizeof(ker));
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001338 ker.bKeyDown = isKeyDown;
Christopher Plewright20b795e2022-12-20 20:01:58 +00001339 ker.wRepeatCount = 1;
1340 ker.wVirtualScanCode = 0;
1341 ker.dwControlKeyState = 0;
1342 int mods = (int)dict_get_number(args, "modifiers");
1343 // Encode the win32 console key modifiers from Vim keyboard modifiers.
1344 if (mods)
1345 {
1346 // If "modifiers" is explicitly set in the args, then we reset any
Yegappan Lakshmanan14113fd2023-03-07 17:13:51 +00001347 // remembered modifier key state that may have been set from
1348 // earlier mod-key-down events, even if they are not yet unset by
1349 // earlier mod-key-up events.
Christopher Plewright20b795e2022-12-20 20:01:58 +00001350 s_dwMods = 0;
1351 if (mods & MOD_MASK_SHIFT)
1352 ker.dwControlKeyState |= SHIFT_PRESSED;
1353 if (mods & MOD_MASK_CTRL)
1354 ker.dwControlKeyState |= LEFT_CTRL_PRESSED;
1355 if (mods & MOD_MASK_ALT)
1356 ker.dwControlKeyState |= LEFT_ALT_PRESSED;
1357 }
1358
1359 if (vkCode == VK_LSHIFT || vkCode == VK_RSHIFT || vkCode == VK_SHIFT)
1360 {
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001361 if (isKeyDown)
Christopher Plewright20b795e2022-12-20 20:01:58 +00001362 s_dwMods |= SHIFT_PRESSED;
1363 else
1364 s_dwMods &= ~SHIFT_PRESSED;
1365 }
1366 else if (vkCode == VK_LCONTROL || vkCode == VK_CONTROL)
1367 {
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001368 if (isKeyDown)
Christopher Plewright20b795e2022-12-20 20:01:58 +00001369 s_dwMods |= LEFT_CTRL_PRESSED;
1370 else
1371 s_dwMods &= ~LEFT_CTRL_PRESSED;
1372 }
1373 else if (vkCode == VK_RCONTROL)
1374 {
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001375 if (isKeyDown)
Christopher Plewright20b795e2022-12-20 20:01:58 +00001376 s_dwMods |= RIGHT_CTRL_PRESSED;
1377 else
1378 s_dwMods &= ~RIGHT_CTRL_PRESSED;
1379 }
1380 else if (vkCode == VK_LMENU || vkCode == VK_MENU)
1381 {
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001382 if (isKeyDown)
Christopher Plewright20b795e2022-12-20 20:01:58 +00001383 s_dwMods |= LEFT_ALT_PRESSED;
1384 else
1385 s_dwMods &= ~LEFT_ALT_PRESSED;
1386 }
1387 else if (vkCode == VK_RMENU)
1388 {
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001389 if (isKeyDown)
Christopher Plewright20b795e2022-12-20 20:01:58 +00001390 s_dwMods |= RIGHT_ALT_PRESSED;
1391 else
1392 s_dwMods &= ~RIGHT_ALT_PRESSED;
1393 }
1394 ker.dwControlKeyState |= s_dwMods;
1395 ker.wVirtualKeyCode = vkCode;
Christopher Plewright566f76e2023-01-10 13:43:04 +00001396 ker.uChar.UnicodeChar = 0;
Christopher Plewright20b795e2022-12-20 20:01:58 +00001397 ir->Event.KeyEvent = ker;
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001398 vim_free(action);
Christopher Plewright20b795e2022-12-20 20:01:58 +00001399 }
1400 else
1401 {
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001402 if (action == NULL)
Christopher Plewright20b795e2022-12-20 20:01:58 +00001403 {
1404 semsg(_(e_missing_argument_str), "event");
1405 }
1406 else
1407 {
Christopher Plewrightc8b20492023-01-04 18:06:00 +00001408 semsg(_(e_invalid_value_for_argument_str_str), "event", action);
1409 vim_free(action);
Christopher Plewright20b795e2022-12-20 20:01:58 +00001410 }
1411 return FALSE;
1412 }
1413 return TRUE;
1414}
1415# endif // FEAT_EVAL
1416#endif // !FEAT_GUI_MSWIN || VIMDLL
Bram Moolenaar071d4272004-06-13 20:20:40 +00001417
1418
Bram Moolenaar071d4272004-06-13 20:20:40 +00001419/*
1420 * For the GUI the mouse handling is in gui_w32.c.
1421 */
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001422#if defined(FEAT_GUI_MSWIN) && !defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001423 void
Bram Moolenaar1266d672017-02-01 13:43:36 +01001424mch_setmouse(int on UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001425{
1426}
Christopher Plewright20b795e2022-12-20 20:01:58 +00001427#else // !FEAT_GUI_MSWIN || VIMDLL
Bram Moolenaar0f873732019-12-05 20:28:46 +01001428static int g_fMouseAvail = FALSE; // mouse present
1429static int g_fMouseActive = FALSE; // mouse enabled
1430static int g_nMouseClick = -1; // mouse status
1431static int g_xMouse; // mouse x coordinate
1432static int g_yMouse; // mouse y coordinate
Bram Moolenaar9f1983d2022-05-12 20:35:35 +01001433static DWORD g_cmodein = 0; // Original console input mode
1434static DWORD g_cmodeout = 0; // Original console output mode
Bram Moolenaar071d4272004-06-13 20:20:40 +00001435
1436/*
1437 * Enable or disable mouse input
1438 */
1439 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001440mch_setmouse(int on)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001441{
1442 DWORD cmodein;
1443
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001444# ifdef VIMDLL
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001445 if (gui.in_use)
1446 return;
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001447# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001448 if (!g_fMouseAvail)
1449 return;
1450
1451 g_fMouseActive = on;
1452 GetConsoleMode(g_hConIn, &cmodein);
1453
1454 if (g_fMouseActive)
Wez Furlong6ef5ab52021-05-30 19:29:41 +02001455 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00001456 cmodein |= ENABLE_MOUSE_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02001457 cmodein &= ~ENABLE_QUICK_EDIT_MODE;
1458 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001459 else
Wez Furlong6ef5ab52021-05-30 19:29:41 +02001460 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00001461 cmodein &= ~ENABLE_MOUSE_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02001462 cmodein |= g_cmodein & ENABLE_QUICK_EDIT_MODE;
1463 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001464
Wez Furlong6ef5ab52021-05-30 19:29:41 +02001465 SetConsoleMode(g_hConIn, cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001466}
1467
Bram Moolenaar157d8132018-03-06 17:09:20 +01001468
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001469# if defined(FEAT_BEVAL_TERM) || defined(PROTO)
Bram Moolenaar157d8132018-03-06 17:09:20 +01001470/*
1471 * Called when 'balloonevalterm' changed.
1472 */
1473 void
1474mch_bevalterm_changed(void)
1475{
1476 mch_setmouse(g_fMouseActive);
1477}
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001478# endif
Bram Moolenaar157d8132018-03-06 17:09:20 +01001479
Christopher Plewright2a46f812022-10-16 19:47:45 +01001480/*
1481 * Win32 console mouse scroll event handler.
Christopher Plewright20b795e2022-12-20 20:01:58 +00001482 * Console version of the _OnMouseWheel() function in gui_w32.c
Christopher Plewright2a46f812022-10-16 19:47:45 +01001483 *
1484 * This encodes the mouse scroll direction and keyboard modifiers into
1485 * g_nMouseClick, and the mouse position into g_xMouse and g_yMouse
1486 *
1487 * The direction of the scroll is decoded from two fields of the win32 console
1488 * mouse event record;
Christopher Plewright20b795e2022-12-20 20:01:58 +00001489 * 1. The orientation - vertical or horizontal flag - from dwEventFlags
Christopher Plewright2a46f812022-10-16 19:47:45 +01001490 * 2. The sign - positive or negative (aka delta flag) - from dwButtonState
1491 *
Christopher Plewright20b795e2022-12-20 20:01:58 +00001492 * When scroll orientation is HORIZONTAL
Christopher Plewright2a46f812022-10-16 19:47:45 +01001493 * - If the high word of the dwButtonState member contains a positive
1494 * value, the wheel was rotated to the right.
1495 * - Otherwise, the wheel was rotated to the left.
Christopher Plewright20b795e2022-12-20 20:01:58 +00001496 * When scroll orientation is VERTICAL
Christopher Plewright2a46f812022-10-16 19:47:45 +01001497 * - If the high word of the dwButtonState member contains a positive value,
1498 * the wheel was rotated forward, away from the user.
1499 * - Otherwise, the wheel was rotated backward, toward the user.
1500 */
1501 static void
1502decode_mouse_wheel(MOUSE_EVENT_RECORD *pmer)
1503{
Christopher Plewright2a46f812022-10-16 19:47:45 +01001504 int horizontal = (pmer->dwEventFlags == MOUSE_HWHEELED);
1505 int zDelta = pmer->dwButtonState;
1506
1507 g_xMouse = pmer->dwMousePosition.X;
1508 g_yMouse = pmer->dwMousePosition.Y;
1509
K.Takata161b6ac2022-11-14 15:31:07 +00001510# ifdef FEAT_PROP_POPUP
Christopher Plewright605d02a2022-10-19 11:54:46 +01001511 int lcol = g_xMouse;
1512 int lrow = g_yMouse;
Christopher Plewright38804d62022-11-09 23:55:52 +00001513 win_T *wp = mouse_find_win(&lrow, &lcol, FIND_POPUP);
Christopher Plewright2a46f812022-10-16 19:47:45 +01001514 if (wp != NULL && popup_is_popup(wp))
1515 {
1516 g_nMouseClick = -1;
1517 cmdarg_T cap;
1518 oparg_T oa;
1519 CLEAR_FIELD(cap);
1520 clear_oparg(&oa);
1521 cap.oap = &oa;
1522 if (horizontal)
1523 {
1524 cap.arg = zDelta < 0 ? MSCR_LEFT : MSCR_RIGHT;
1525 cap.cmdchar = zDelta < 0 ? K_MOUSELEFT : K_MOUSERIGHT;
1526 }
1527 else
1528 {
1529 cap.cmdchar = zDelta < 0 ? K_MOUSEUP : K_MOUSEDOWN;
1530 cap.arg = zDelta < 0 ? MSCR_UP : MSCR_DOWN;
1531 }
1532
1533 // Mouse hovers over popup window, scroll it if possible.
1534 mouse_row = wp->w_winrow;
1535 mouse_col = wp->w_wincol;
1536 nv_mousescroll(&cap);
1537 update_screen(0);
1538 setcursor();
1539 out_flush();
1540 return;
1541 }
K.Takata161b6ac2022-11-14 15:31:07 +00001542# endif
Christopher Plewright2a46f812022-10-16 19:47:45 +01001543 mouse_col = g_xMouse;
1544 mouse_row = g_yMouse;
1545
1546 char_u modifiers = 0;
1547 char_u direction = 0;
1548
1549 // Decode the direction into an event that Vim can process
1550 if (horizontal)
1551 direction = zDelta >= 0 ? KE_MOUSELEFT : KE_MOUSERIGHT;
1552 else
1553 direction = zDelta >= 0 ? KE_MOUSEDOWN : KE_MOUSEUP;
1554
dundargocc57b5bc2022-11-02 13:30:51 +00001555 // Decode the win32 console key modifiers into Vim mouse modifiers.
Christopher Plewright2a46f812022-10-16 19:47:45 +01001556 if (pmer->dwControlKeyState & SHIFT_PRESSED)
Christopher Plewright605d02a2022-10-19 11:54:46 +01001557 modifiers |= MOD_MASK_SHIFT; // MOUSE_SHIFT;
Christopher Plewright2a46f812022-10-16 19:47:45 +01001558 if (pmer->dwControlKeyState & (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED))
Christopher Plewright605d02a2022-10-19 11:54:46 +01001559 modifiers |= MOD_MASK_CTRL; // MOUSE_CTRL;
Christopher Plewright2a46f812022-10-16 19:47:45 +01001560 if (pmer->dwControlKeyState & (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED))
1561 modifiers |= MOD_MASK_ALT; // MOUSE_ALT;
1562
1563 // add (bitwise or) the scroll direction and the key modifier chars
1564 // together.
1565 g_nMouseClick = ((direction << 8) | modifiers);
1566
1567 return;
1568}
1569
Bram Moolenaar071d4272004-06-13 20:20:40 +00001570/*
1571 * Decode a MOUSE_EVENT. If it's a valid event, return MOUSE_LEFT,
1572 * MOUSE_MIDDLE, or MOUSE_RIGHT for a click; MOUSE_DRAG for a mouse
1573 * move with a button held down; and MOUSE_RELEASE after a MOUSE_DRAG
1574 * or a MOUSE_LEFT, _MIDDLE, or _RIGHT. We encode the button type,
1575 * the number of clicks, and the Shift/Ctrl/Alt modifiers in g_nMouseClick,
1576 * and we return the mouse position in g_xMouse and g_yMouse.
1577 *
1578 * Every MOUSE_LEFT, _MIDDLE, or _RIGHT will be followed by zero or more
1579 * MOUSE_DRAGs and one MOUSE_RELEASE. MOUSE_RELEASE will be followed only
1580 * by MOUSE_LEFT, _MIDDLE, or _RIGHT.
1581 *
1582 * For multiple clicks, we send, say, MOUSE_LEFT/1 click, MOUSE_RELEASE,
1583 * MOUSE_LEFT/2 clicks, MOUSE_RELEASE, MOUSE_LEFT/3 clicks, MOUSE_RELEASE, ....
1584 *
1585 * Windows will send us MOUSE_MOVED notifications whenever the mouse
1586 * moves, even if it stays within the same character cell. We ignore
1587 * all MOUSE_MOVED messages if the position hasn't really changed, and
1588 * we ignore all MOUSE_MOVED messages where no button is held down (i.e.,
1589 * we're only interested in MOUSE_DRAG).
1590 *
1591 * All of this is complicated by the code that fakes MOUSE_MIDDLE on
1592 * 2-button mouses by pressing the left & right buttons simultaneously.
1593 * In practice, it's almost impossible to click both at the same time,
1594 * so we need to delay a little. Also, we tend not to get MOUSE_RELEASE
1595 * in such cases, if the user is clicking quickly.
1596 */
1597 static BOOL
1598decode_mouse_event(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001599 MOUSE_EVENT_RECORD *pmer)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001600{
1601 static int s_nOldButton = -1;
1602 static int s_nOldMouseClick = -1;
1603 static int s_xOldMouse = -1;
1604 static int s_yOldMouse = -1;
1605 static linenr_T s_old_topline = 0;
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001606# ifdef FEAT_DIFF
Bram Moolenaar071d4272004-06-13 20:20:40 +00001607 static int s_old_topfill = 0;
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001608# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001609 static int s_cClicks = 1;
1610 static BOOL s_fReleased = TRUE;
1611 static DWORD s_dwLastClickTime = 0;
1612 static BOOL s_fNextIsMiddle = FALSE;
1613
Bram Moolenaar0f873732019-12-05 20:28:46 +01001614 static DWORD cButtons = 0; // number of buttons supported
Bram Moolenaar071d4272004-06-13 20:20:40 +00001615
1616 const DWORD LEFT = FROM_LEFT_1ST_BUTTON_PRESSED;
1617 const DWORD MIDDLE = FROM_LEFT_2ND_BUTTON_PRESSED;
1618 const DWORD RIGHT = RIGHTMOST_BUTTON_PRESSED;
1619 const DWORD LEFT_RIGHT = LEFT | RIGHT;
1620
1621 int nButton;
1622
1623 if (cButtons == 0 && !GetNumberOfConsoleMouseButtons(&cButtons))
1624 cButtons = 2;
1625
1626 if (!g_fMouseAvail || !g_fMouseActive)
1627 {
1628 g_nMouseClick = -1;
1629 return FALSE;
1630 }
1631
Bram Moolenaar0f873732019-12-05 20:28:46 +01001632 // get a spurious MOUSE_EVENT immediately after receiving focus; ignore
Bram Moolenaar071d4272004-06-13 20:20:40 +00001633 if (g_fJustGotFocus)
1634 {
1635 g_fJustGotFocus = FALSE;
1636 return FALSE;
1637 }
1638
Christopher Plewright605d02a2022-10-19 11:54:46 +01001639 // If there is an unprocessed mouse click drop this one.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001640 if (g_nMouseClick != -1)
1641 return TRUE;
Christopher Plewright605d02a2022-10-19 11:54:46 +01001642
Christopher Plewright2a46f812022-10-16 19:47:45 +01001643 if (pmer->dwEventFlags == MOUSE_WHEELED
1644 || pmer->dwEventFlags == MOUSE_HWHEELED)
1645 {
1646 decode_mouse_wheel(pmer);
1647 return TRUE; // we now should have a mouse scroll in g_nMouseClick
1648 }
Christopher Plewright605d02a2022-10-19 11:54:46 +01001649
Bram Moolenaar071d4272004-06-13 20:20:40 +00001650 nButton = -1;
1651 g_xMouse = pmer->dwMousePosition.X;
1652 g_yMouse = pmer->dwMousePosition.Y;
1653
1654 if (pmer->dwEventFlags == MOUSE_MOVED)
1655 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001656 // Ignore MOUSE_MOVED events if (x, y) hasn't changed. (We get these
1657 // events even when the mouse moves only within a char cell.)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001658 if (s_xOldMouse == g_xMouse && s_yOldMouse == g_yMouse)
1659 return FALSE;
1660 }
1661
Bram Moolenaar0f873732019-12-05 20:28:46 +01001662 // If no buttons are pressed...
Bram Moolenaar071d4272004-06-13 20:20:40 +00001663 if ((pmer->dwButtonState & ((1 << cButtons) - 1)) == 0)
1664 {
Bram Moolenaar157d8132018-03-06 17:09:20 +01001665 nButton = MOUSE_RELEASE;
1666
Bram Moolenaar0f873732019-12-05 20:28:46 +01001667 // If the last thing returned was MOUSE_RELEASE, ignore this
Bram Moolenaar071d4272004-06-13 20:20:40 +00001668 if (s_fReleased)
Bram Moolenaar157d8132018-03-06 17:09:20 +01001669 {
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001670# ifdef FEAT_BEVAL_TERM
Bram Moolenaar0f873732019-12-05 20:28:46 +01001671 // do return mouse move events when we want them
Bram Moolenaar157d8132018-03-06 17:09:20 +01001672 if (p_bevalterm)
1673 nButton = MOUSE_DRAG;
1674 else
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001675# endif
Bram Moolenaar157d8132018-03-06 17:09:20 +01001676 return FALSE;
1677 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001678
Bram Moolenaar071d4272004-06-13 20:20:40 +00001679 s_fReleased = TRUE;
1680 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01001681 else // one or more buttons pressed
Bram Moolenaar071d4272004-06-13 20:20:40 +00001682 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001683 // on a 2-button mouse, hold down left and right buttons
1684 // simultaneously to get MIDDLE.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001685
1686 if (cButtons == 2 && s_nOldButton != MOUSE_DRAG)
1687 {
1688 DWORD dwLR = (pmer->dwButtonState & LEFT_RIGHT);
1689
Bram Moolenaar0f873732019-12-05 20:28:46 +01001690 // if either left or right button only is pressed, see if the
1691 // next mouse event has both of them pressed
Bram Moolenaar071d4272004-06-13 20:20:40 +00001692 if (dwLR == LEFT || dwLR == RIGHT)
1693 {
1694 for (;;)
1695 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001696 // wait a short time for next input event
Bram Moolenaar071d4272004-06-13 20:20:40 +00001697 if (WaitForSingleObject(g_hConIn, p_mouset / 3)
1698 != WAIT_OBJECT_0)
1699 break;
1700 else
1701 {
1702 DWORD cRecords = 0;
1703 INPUT_RECORD ir;
1704 MOUSE_EVENT_RECORD* pmer2 = &ir.Event.MouseEvent;
1705
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001706 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001707
1708 if (cRecords == 0 || ir.EventType != MOUSE_EVENT
1709 || !(pmer2->dwButtonState & LEFT_RIGHT))
1710 break;
1711 else
1712 {
1713 if (pmer2->dwEventFlags != MOUSE_MOVED)
1714 {
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001715 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001716
1717 return decode_mouse_event(pmer2);
1718 }
1719 else if (s_xOldMouse == pmer2->dwMousePosition.X &&
1720 s_yOldMouse == pmer2->dwMousePosition.Y)
1721 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001722 // throw away spurious mouse move
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001723 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001724
Bram Moolenaar0f873732019-12-05 20:28:46 +01001725 // are there any more mouse events in queue?
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001726 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001727
1728 if (cRecords==0 || ir.EventType != MOUSE_EVENT)
1729 break;
1730 }
1731 else
1732 break;
1733 }
1734 }
1735 }
1736 }
1737 }
1738
1739 if (s_fNextIsMiddle)
1740 {
1741 nButton = (pmer->dwEventFlags == MOUSE_MOVED)
1742 ? MOUSE_DRAG : MOUSE_MIDDLE;
1743 s_fNextIsMiddle = FALSE;
1744 }
1745 else if (cButtons == 2 &&
1746 ((pmer->dwButtonState & LEFT_RIGHT) == LEFT_RIGHT))
1747 {
1748 nButton = MOUSE_MIDDLE;
1749
1750 if (! s_fReleased && pmer->dwEventFlags != MOUSE_MOVED)
1751 {
1752 s_fNextIsMiddle = TRUE;
1753 nButton = MOUSE_RELEASE;
1754 }
1755 }
1756 else if ((pmer->dwButtonState & LEFT) == LEFT)
1757 nButton = MOUSE_LEFT;
1758 else if ((pmer->dwButtonState & MIDDLE) == MIDDLE)
1759 nButton = MOUSE_MIDDLE;
1760 else if ((pmer->dwButtonState & RIGHT) == RIGHT)
1761 nButton = MOUSE_RIGHT;
1762
1763 if (! s_fReleased && ! s_fNextIsMiddle
1764 && nButton != s_nOldButton && s_nOldButton != MOUSE_DRAG)
1765 return FALSE;
1766
1767 s_fReleased = s_fNextIsMiddle;
1768 }
1769
1770 if (pmer->dwEventFlags == 0 || pmer->dwEventFlags == DOUBLE_CLICK)
1771 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001772 // button pressed or released, without mouse moving
Bram Moolenaar071d4272004-06-13 20:20:40 +00001773 if (nButton != -1 && nButton != MOUSE_RELEASE)
1774 {
1775 DWORD dwCurrentTime = GetTickCount();
1776
1777 if (s_xOldMouse != g_xMouse
1778 || s_yOldMouse != g_yMouse
1779 || s_nOldButton != nButton
1780 || s_old_topline != curwin->w_topline
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001781# ifdef FEAT_DIFF
Bram Moolenaar071d4272004-06-13 20:20:40 +00001782 || s_old_topfill != curwin->w_topfill
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001783# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001784 || (int)(dwCurrentTime - s_dwLastClickTime) > p_mouset)
1785 {
1786 s_cClicks = 1;
1787 }
1788 else if (++s_cClicks > 4)
1789 {
1790 s_cClicks = 1;
1791 }
1792
1793 s_dwLastClickTime = dwCurrentTime;
1794 }
1795 }
1796 else if (pmer->dwEventFlags == MOUSE_MOVED)
1797 {
1798 if (nButton != -1 && nButton != MOUSE_RELEASE)
1799 nButton = MOUSE_DRAG;
1800
1801 s_cClicks = 1;
1802 }
1803
1804 if (nButton == -1)
1805 return FALSE;
1806
1807 if (nButton != MOUSE_RELEASE)
1808 s_nOldButton = nButton;
1809
1810 g_nMouseClick = nButton;
1811
1812 if (pmer->dwControlKeyState & SHIFT_PRESSED)
1813 g_nMouseClick |= MOUSE_SHIFT;
1814 if (pmer->dwControlKeyState & (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED))
1815 g_nMouseClick |= MOUSE_CTRL;
1816 if (pmer->dwControlKeyState & (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED))
1817 g_nMouseClick |= MOUSE_ALT;
1818
1819 if (nButton != MOUSE_DRAG && nButton != MOUSE_RELEASE)
1820 SET_NUM_MOUSE_CLICKS(g_nMouseClick, s_cClicks);
1821
Bram Moolenaar0f873732019-12-05 20:28:46 +01001822 // only pass on interesting (i.e., different) mouse events
Bram Moolenaar071d4272004-06-13 20:20:40 +00001823 if (s_xOldMouse == g_xMouse
1824 && s_yOldMouse == g_yMouse
1825 && s_nOldMouseClick == g_nMouseClick)
1826 {
1827 g_nMouseClick = -1;
1828 return FALSE;
1829 }
1830
1831 s_xOldMouse = g_xMouse;
1832 s_yOldMouse = g_yMouse;
1833 s_old_topline = curwin->w_topline;
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001834# ifdef FEAT_DIFF
Bram Moolenaar071d4272004-06-13 20:20:40 +00001835 s_old_topfill = curwin->w_topfill;
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001836# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001837 s_nOldMouseClick = g_nMouseClick;
1838
1839 return TRUE;
1840}
1841
Christopher Plewright20b795e2022-12-20 20:01:58 +00001842# ifdef FEAT_EVAL
1843 static int
1844encode_mouse_event(dict_T *args, INPUT_RECORD *ir)
1845{
1846 int button;
1847 int row;
1848 int col;
1849 int repeated_click;
Bram Moolenaar9b8a3652022-12-20 20:47:28 +00001850 int_u mods = 0;
Christopher Plewright20b795e2022-12-20 20:01:58 +00001851 int move;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001852
Christopher Plewright20b795e2022-12-20 20:01:58 +00001853 if (!dict_has_key(args, "row") || !dict_has_key(args, "col"))
1854 return FALSE;
1855
1856 // Note: "move" is optional, requires fewer arguments
1857 move = (int)dict_get_bool(args, "move", FALSE);
1858 if (!move && (!dict_has_key(args, "button")
1859 || !dict_has_key(args, "multiclick")
1860 || !dict_has_key(args, "modifiers")))
1861 return FALSE;
1862
1863 row = (int)dict_get_number(args, "row") - 1;
1864 col = (int)dict_get_number(args, "col") - 1;
1865
1866 ir->EventType = MOUSE_EVENT;
1867 MOUSE_EVENT_RECORD mer;
1868 ZeroMemory(&mer, sizeof(mer));
1869 mer.dwMousePosition.X = col;
1870 mer.dwMousePosition.Y = row;
1871
1872 if (move)
1873 {
1874 mer.dwButtonState = 0;
1875 mer.dwEventFlags = MOUSE_MOVED;
1876 }
1877 else
1878 {
1879 button = (int)dict_get_number(args, "button");
1880 repeated_click = (int)dict_get_number(args, "multiclick");
1881 mods = (int)dict_get_number(args, "modifiers");
1882 // Reset the scroll values to known values.
1883 // XXX: Remove this when/if the scroll step is made configurable.
1884 mouse_set_hor_scroll_step(6);
1885 mouse_set_vert_scroll_step(3);
1886
1887 switch (button)
1888 {
1889 case MOUSE_LEFT:
1890 mer.dwButtonState = FROM_LEFT_1ST_BUTTON_PRESSED;
1891 mer.dwEventFlags = repeated_click == 1 ? DOUBLE_CLICK : 0;
1892 break;
1893 case MOUSE_MIDDLE:
1894 mer.dwButtonState = FROM_LEFT_2ND_BUTTON_PRESSED;
1895 mer.dwEventFlags = repeated_click == 1 ? DOUBLE_CLICK : 0;
1896 break;
1897 case MOUSE_RIGHT:
1898 mer.dwButtonState = RIGHTMOST_BUTTON_PRESSED;
1899 mer.dwEventFlags = repeated_click == 1 ? DOUBLE_CLICK : 0;
1900 break;
1901 case MOUSE_RELEASE:
1902 // umm? Assume Left Release?
1903 mer.dwEventFlags = 0;
1904
1905 case MOUSE_MOVE:
1906 mer.dwButtonState = 0;
1907 mer.dwEventFlags = MOUSE_MOVED;
1908 break;
1909 case MOUSE_X1:
1910 mer.dwButtonState = FROM_LEFT_3RD_BUTTON_PRESSED;
1911 break;
1912 case MOUSE_X2:
1913 mer.dwButtonState = FROM_LEFT_4TH_BUTTON_PRESSED;
1914 break;
1915 case MOUSE_4: // KE_MOUSEDOWN;
1916 mer.dwButtonState = -1;
1917 mer.dwEventFlags = MOUSE_WHEELED;
1918 break;
1919 case MOUSE_5: // KE_MOUSEUP;
1920 mer.dwButtonState = +1;
1921 mer.dwEventFlags = MOUSE_WHEELED;
1922 break;
1923 case MOUSE_6: // KE_MOUSELEFT;
1924 mer.dwButtonState = -1;
1925 mer.dwEventFlags = MOUSE_HWHEELED;
1926 break;
1927 case MOUSE_7: // KE_MOUSERIGHT;
1928 mer.dwButtonState = +1;
1929 mer.dwEventFlags = MOUSE_HWHEELED;
1930 break;
1931 default:
1932 semsg(_(e_invalid_argument_str), "button");
1933 return FALSE;
1934 }
1935 }
1936
1937 mer.dwControlKeyState = 0;
1938 if (mods != 0)
1939 {
1940 // Encode the win32 console key modifiers from Vim MOUSE modifiers.
1941 if (mods & MOUSE_SHIFT)
1942 mer.dwControlKeyState |= SHIFT_PRESSED;
1943 if (mods & MOUSE_CTRL)
1944 mer.dwControlKeyState |= LEFT_CTRL_PRESSED;
1945 if (mods & MOUSE_ALT)
1946 mer.dwControlKeyState |= LEFT_ALT_PRESSED;
1947 }
1948 ir->Event.MouseEvent = mer;
1949 return TRUE;
1950}
1951# endif // FEAT_EVAL
1952
1953 static int
1954write_input_record_buffer(INPUT_RECORD* irEvents, int nLength)
1955{
1956 int nCount = 0;
1957 while (nCount < nLength)
1958 {
1959 input_record_buffer.length++;
1960 input_record_buffer_node_T *event_node =
1961 malloc(sizeof(input_record_buffer_node_T));
1962 event_node->ir = irEvents[nCount++];
1963 event_node->next = NULL;
1964 if (input_record_buffer.tail == NULL)
1965 {
1966 input_record_buffer.head = event_node;
1967 input_record_buffer.tail = event_node;
1968 }
1969 else
1970 {
1971 input_record_buffer.tail->next = event_node;
1972 input_record_buffer.tail = input_record_buffer.tail->next;
1973 }
1974 }
1975 return nCount;
1976}
1977
1978 static int
1979read_input_record_buffer(INPUT_RECORD* irEvents, int nMaxLength)
1980{
1981 int nCount = 0;
1982 while (nCount < nMaxLength && input_record_buffer.head != NULL)
1983 {
1984 input_record_buffer.length--;
1985 input_record_buffer_node_T *pop_head = input_record_buffer.head;
1986 irEvents[nCount++] = pop_head->ir;
1987 input_record_buffer.head = pop_head->next;
1988 vim_free(pop_head);
1989 if (input_record_buffer.length == 0)
1990 input_record_buffer.tail = NULL;
1991 }
1992 return nCount;
1993}
Christopher Plewright20b795e2022-12-20 20:01:58 +00001994#endif // !FEAT_GUI_MSWIN || VIMDLL
1995
1996#ifdef FEAT_EVAL
1997/*
1998 * The 'test_mswin_event' function is for testing Vim's low-level handling of
1999 * user input events. ie, this manages the encoding of INPUT_RECORD events
2000 * so that we have a way to test how Vim decodes INPUT_RECORD events in Windows
2001 * consoles.
2002 *
2003 * The 'test_mswin_event' function is based on 'test_gui_event'. In fact, when
2004 * the Windows GUI is running, the arguments; 'event' and 'args', are the same.
2005 * So, it acts as an alias for 'test_gui_event' for the Windows GUI.
2006 *
2007 * When the Windows console is running, the arguments; 'event' and 'args', are
2008 * a subset of what 'test_gui_event' handles, ie, only "key" and "mouse"
2009 * events are encoded as INPUT_RECORD events.
2010 *
2011 * Note: INPUT_RECORDs are only used by the Windows console, not the GUI. The
2012 * GUI sends MSG structs instead.
2013 */
2014 int
2015test_mswin_event(char_u *event, dict_T *args)
2016{
2017 int lpEventsWritten = 0;
2018
2019# if defined(VIMDLL) || defined(FEAT_GUI_MSWIN)
2020 if (gui.in_use)
2021 return test_gui_w32_sendevent(event, args);
2022# endif
2023
2024# if defined(VIMDLL) || !defined(FEAT_GUI_MSWIN)
2025
2026// Currently implemented event record types are; KEY_EVENT and MOUSE_EVENT
2027// Potentially could also implement: FOCUS_EVENT and WINDOW_BUFFER_SIZE_EVENT
2028// Maybe also: MENU_EVENT
2029
2030 INPUT_RECORD ir;
2031 BOOL input_encoded = FALSE;
Christopher Plewright7b0afc12022-12-30 16:54:58 +00002032 BOOL execute = FALSE;
Christopher Plewright20b795e2022-12-20 20:01:58 +00002033 if (STRCMP(event, "key") == 0)
Christopher Plewright7b0afc12022-12-30 16:54:58 +00002034 {
2035 execute = dict_get_bool(args, "execute", FALSE);
2036 if (dict_has_key(args, "event"))
2037 input_encoded = encode_key_event(args, &ir);
2038 else if (!execute)
2039 {
2040 semsg(_(e_missing_argument_str), "event");
2041 return FALSE;
2042 }
2043 }
Christopher Plewright20b795e2022-12-20 20:01:58 +00002044 else if (STRCMP(event, "mouse") == 0)
Christopher Plewright7b0afc12022-12-30 16:54:58 +00002045 {
2046 execute = TRUE;
Christopher Plewright20b795e2022-12-20 20:01:58 +00002047 input_encoded = encode_mouse_event(args, &ir);
Christopher Plewright7b0afc12022-12-30 16:54:58 +00002048 }
Christopher Plewright20b795e2022-12-20 20:01:58 +00002049 else
2050 {
2051 semsg(_(e_invalid_value_for_argument_str_str), "event", event);
2052 return FALSE;
2053 }
2054
2055 // Ideally, WriteConsoleInput would be used to inject these low-level
Yegappan Lakshmanan14113fd2023-03-07 17:13:51 +00002056 // events. But, this doesn't work well in the CI test environment. So
Christopher Plewright20b795e2022-12-20 20:01:58 +00002057 // implementing an input_record_buffer instead.
2058 if (input_encoded)
2059 lpEventsWritten = write_input_record_buffer(&ir, 1);
2060
Christopher Plewright7b0afc12022-12-30 16:54:58 +00002061 // Set flags to execute the event, ie. like feedkeys mode X.
2062 if (execute)
2063 {
2064 int save_msg_scroll = msg_scroll;
2065 // Avoid a 1 second delay when the keys start Insert mode.
2066 msg_scroll = FALSE;
2067 ch_log(NULL, "test_mswin_event() executing");
Christopher Plewright20b795e2022-12-20 20:01:58 +00002068 exec_normal(TRUE, TRUE, TRUE);
Christopher Plewright7b0afc12022-12-30 16:54:58 +00002069 msg_scroll |= save_msg_scroll;
2070 }
Christopher Plewright20b795e2022-12-20 20:01:58 +00002071
2072# endif
2073 return lpEventsWritten;
2074}
2075#endif // FEAT_EVAL
Bram Moolenaar071d4272004-06-13 20:20:40 +00002076
2077#ifdef MCH_CURSOR_SHAPE
2078/*
2079 * Set the shape of the cursor.
2080 * 'thickness' can be from 1 (thin) to 99 (block)
2081 */
2082 static void
2083mch_set_cursor_shape(int thickness)
2084{
Christopher Plewright38804d62022-11-09 23:55:52 +00002085 if (vtp_working)
K.Takatadf5320c2022-09-01 13:20:16 +01002086 {
2087 if (*T_CSI == NUL)
2088 {
2089 // If 't_SI' is not set, use the default cursor styles.
2090 if (thickness < 50)
2091 vtp_printf("\033[3 q"); // underline
2092 else
2093 vtp_printf("\033[0 q"); // default
2094 }
2095 }
2096 else
2097 {
2098 CONSOLE_CURSOR_INFO ConsoleCursorInfo;
2099 ConsoleCursorInfo.dwSize = thickness;
2100 ConsoleCursorInfo.bVisible = s_cursor_visible;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002101
K.Takatadf5320c2022-09-01 13:20:16 +01002102 SetConsoleCursorInfo(g_hConOut, &ConsoleCursorInfo);
2103 if (s_cursor_visible)
2104 SetConsoleCursorPosition(g_hConOut, g_coord);
2105 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002106}
2107
2108 void
2109mch_update_cursor(void)
2110{
2111 int idx;
2112 int thickness;
2113
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002114# ifdef VIMDLL
2115 if (gui.in_use)
2116 return;
2117# endif
2118
Bram Moolenaar071d4272004-06-13 20:20:40 +00002119 /*
2120 * How the cursor is drawn depends on the current mode.
2121 */
2122 idx = get_shape_idx(FALSE);
2123
2124 if (shape_table[idx].shape == SHAPE_BLOCK)
Bram Moolenaar0f873732019-12-05 20:28:46 +01002125 thickness = 99; // 100 doesn't work on W95
Bram Moolenaar071d4272004-06-13 20:20:40 +00002126 else
2127 thickness = shape_table[idx].percentage;
2128 mch_set_cursor_shape(thickness);
2129}
2130#endif
2131
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002132#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002133/*
2134 * Handle FOCUS_EVENT.
2135 */
2136 static void
2137handle_focus_event(INPUT_RECORD ir)
2138{
2139 g_fJustGotFocus = ir.Event.FocusEvent.bSetFocus;
2140 ui_focus_change((int)g_fJustGotFocus);
2141}
2142
Bram Moolenaar78d21da2019-02-17 15:00:52 +01002143static void ResizeConBuf(HANDLE hConsole, COORD coordScreen);
2144
Bram Moolenaar071d4272004-06-13 20:20:40 +00002145/*
2146 * Wait until console input from keyboard or mouse is available,
2147 * or the time is up.
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02002148 * When "ignore_input" is TRUE even wait when input is available.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002149 * Return TRUE if something is available FALSE if not.
2150 */
2151 static int
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02002152WaitForChar(long msec, int ignore_input)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002153{
2154 DWORD dwNow = 0, dwEndTime = 0;
2155 INPUT_RECORD ir;
2156 DWORD cRecords;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002157 WCHAR ch, ch2;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002158# ifdef FEAT_TIMERS
Bram Moolenaar40b1b542016-04-20 20:18:23 +02002159 int tb_change_cnt = typebuf.tb_change_cnt;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002160# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002161
2162 if (msec > 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01002163 // Wait until the specified time has elapsed.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002164 dwEndTime = GetTickCount() + msec;
2165 else if (msec < 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01002166 // Wait forever.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002167 dwEndTime = INFINITE;
2168
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01002169 // We need to loop until the end of the time period, because
2170 // we might get multiple unusable mouse events in that time.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002171 for (;;)
2172 {
Bram Moolenaared5a9d62018-09-06 13:14:43 +02002173 // Only process messages when waiting.
2174 if (msec != 0)
2175 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002176# ifdef MESSAGE_QUEUE
Bram Moolenaared5a9d62018-09-06 13:14:43 +02002177 parse_queued_messages();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002178# endif
2179# ifdef FEAT_MZSCHEME
Bram Moolenaared5a9d62018-09-06 13:14:43 +02002180 mzvim_check_threads();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002181# endif
2182# ifdef FEAT_CLIENTSERVER
Bram Moolenaared5a9d62018-09-06 13:14:43 +02002183 serverProcessPendingMessages();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002184# endif
Bram Moolenaared5a9d62018-09-06 13:14:43 +02002185 }
Bram Moolenaarf12d9832016-01-29 21:11:25 +01002186
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02002187 if (g_nMouseClick != -1
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002188# ifdef FEAT_CLIENTSERVER
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02002189 || (!ignore_input && input_available())
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002190# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002191 )
2192 return TRUE;
2193
2194 if (msec > 0)
2195 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01002196 // If the specified wait time has passed, return. Beware that
2197 // GetTickCount() may wrap around (overflow).
Bram Moolenaar071d4272004-06-13 20:20:40 +00002198 dwNow = GetTickCount();
Bram Moolenaarb7512b72013-08-10 12:45:09 +02002199 if ((int)(dwNow - dwEndTime) >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002200 break;
2201 }
2202 if (msec != 0)
2203 {
Bram Moolenaar325b7a22004-07-05 15:58:32 +00002204 DWORD dwWaitTime = dwEndTime - dwNow;
2205
Bram Moolenaarc478ee32020-12-01 21:27:51 +01002206 // Don't wait for more than 11 msec to avoid dropping characters,
2207 // check channel while waiting for input and handle a callback from
2208 // 'balloonexpr'.
2209 if (dwWaitTime > 11)
2210 dwWaitTime = 11;
2211
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002212# ifdef FEAT_MZSCHEME
Bram Moolenaarc478ee32020-12-01 21:27:51 +01002213 if (mzthreads_allowed() && p_mzq > 0 && (long)dwWaitTime > p_mzq)
Bram Moolenaar0f873732019-12-05 20:28:46 +01002214 dwWaitTime = p_mzq; // don't wait longer than 'mzquantum'
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002215# endif
2216# ifdef FEAT_TIMERS
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01002217 // When waiting very briefly don't trigger timers.
2218 if (dwWaitTime > 10)
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01002219 {
2220 long due_time;
2221
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01002222 // Trigger timers and then get the time in msec until the next
2223 // one is due. Wait up to that time.
2224 due_time = check_due_timer();
2225 if (typebuf.tb_change_cnt != tb_change_cnt)
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01002226 {
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01002227 // timer may have used feedkeys().
2228 return FALSE;
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01002229 }
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01002230 if (due_time > 0 && dwWaitTime > (DWORD)due_time)
2231 dwWaitTime = due_time;
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01002232 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002233# endif
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01002234 if (
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002235# ifdef FEAT_CLIENTSERVER
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01002236 // Wait for either an event on the console input or a
2237 // message in the client-server window.
2238 msg_wait_for_multiple_objects(1, &g_hConIn, FALSE,
2239 dwWaitTime, QS_SENDMESSAGE) != WAIT_OBJECT_0
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002240# else
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01002241 wait_for_single_object(g_hConIn, dwWaitTime)
2242 != WAIT_OBJECT_0
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002243# endif
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01002244 )
2245 continue;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002246 }
2247
2248 cRecords = 0;
Bram Moolenaar3a69e112014-01-10 13:51:42 +01002249 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002250
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002251# ifdef FEAT_MBYTE_IME
matveyt4eb19142021-05-20 11:54:10 +02002252 // May have to redraw if the cursor ends up in the wrong place.
2253 // Only when not peeking.
Bram Moolenaar24959102022-05-07 20:01:16 +01002254 if (State == MODE_CMDLINE && msg_row == Rows - 1 && msec != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002255 {
2256 CONSOLE_SCREEN_BUFFER_INFO csbi;
2257
2258 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
2259 {
2260 if (csbi.dwCursorPosition.Y != msg_row)
2261 {
matveyte08795e2021-05-07 15:00:17 +02002262 // The screen is now messed up, must redraw the command
2263 // line and later all the windows.
Bram Moolenaara4d158b2022-08-14 14:17:45 +01002264 redraw_all_later(UPD_CLEAR);
matveyte08795e2021-05-07 15:00:17 +02002265 compute_cmdrow();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002266 redrawcmd();
2267 }
2268 }
2269 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002270# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002271
2272 if (cRecords > 0)
2273 {
2274 if (ir.EventType == KEY_EVENT && ir.Event.KeyEvent.bKeyDown)
2275 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002276# ifdef FEAT_MBYTE_IME
Bram Moolenaar0f873732019-12-05 20:28:46 +01002277 // Windows IME sends two '\n's with only one 'ENTER'. First:
2278 // wVirtualKeyCode == 13. second: wVirtualKeyCode == 0
K.Takata972db232022-02-04 10:45:38 +00002279 if (ir.Event.KeyEvent.uChar.UnicodeChar == 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00002280 && ir.Event.KeyEvent.wVirtualKeyCode == 13)
2281 {
Bram Moolenaar3a69e112014-01-10 13:51:42 +01002282 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002283 continue;
2284 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002285# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002286 if (decode_key_event(&ir.Event.KeyEvent, &ch, &ch2,
2287 NULL, FALSE))
2288 return TRUE;
2289 }
2290
Bram Moolenaar3a69e112014-01-10 13:51:42 +01002291 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002292
2293 if (ir.EventType == FOCUS_EVENT)
2294 handle_focus_event(ir);
2295 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
Bram Moolenaarc33ecb22018-02-11 16:40:45 +01002296 {
Bram Moolenaar78d21da2019-02-17 15:00:52 +01002297 COORD dwSize = ir.Event.WindowBufferSizeEvent.dwSize;
2298
Bram Moolenaar36698e32019-12-11 22:57:40 +01002299 // Only call shell_resized() when the size actually changed to
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002300 // avoid the screen is cleared.
Bram Moolenaar78d21da2019-02-17 15:00:52 +01002301 if (dwSize.X != Columns || dwSize.Y != Rows)
2302 {
2303 CONSOLE_SCREEN_BUFFER_INFO csbi;
2304 GetConsoleScreenBufferInfo(g_hConOut, &csbi);
Bram Moolenaar36698e32019-12-11 22:57:40 +01002305 dwSize.X = csbi.srWindow.Right - csbi.srWindow.Left + 1;
Bram Moolenaar78d21da2019-02-17 15:00:52 +01002306 dwSize.Y = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
Bram Moolenaar36698e32019-12-11 22:57:40 +01002307 if (dwSize.X != Columns || dwSize.Y != Rows)
2308 {
2309 ResizeConBuf(g_hConOut, dwSize);
2310 shell_resized();
2311 }
Bram Moolenaar78d21da2019-02-17 15:00:52 +01002312 }
Bram Moolenaarc33ecb22018-02-11 16:40:45 +01002313 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002314 else if (ir.EventType == MOUSE_EVENT
2315 && decode_mouse_event(&ir.Event.MouseEvent))
2316 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002317 }
2318 else if (msec == 0)
2319 break;
2320 }
2321
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002322# ifdef FEAT_CLIENTSERVER
Bram Moolenaar0f873732019-12-05 20:28:46 +01002323 // Something might have been received while we were waiting.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002324 if (input_available())
2325 return TRUE;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002326# endif
Bram Moolenaarf12d9832016-01-29 21:11:25 +01002327
Bram Moolenaar071d4272004-06-13 20:20:40 +00002328 return FALSE;
2329}
2330
Bram Moolenaar071d4272004-06-13 20:20:40 +00002331/*
2332 * return non-zero if a character is available
2333 */
2334 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002335mch_char_avail(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002336{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002337# ifdef VIMDLL
2338 if (gui.in_use)
2339 return TRUE;
2340# endif
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02002341 return WaitForChar(0L, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002342}
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02002343
2344# if defined(FEAT_TERMINAL) || defined(PROTO)
2345/*
2346 * Check for any pending input or messages.
2347 */
2348 int
2349mch_check_messages(void)
2350{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002351# ifdef VIMDLL
2352 if (gui.in_use)
2353 return TRUE;
2354# endif
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02002355 return WaitForChar(0L, TRUE);
2356}
2357# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002358
2359/*
2360 * Create the console input. Used when reading stdin doesn't work.
2361 */
2362 static void
2363create_conin(void)
2364{
2365 g_hConIn = CreateFile("CONIN$", GENERIC_READ|GENERIC_WRITE,
2366 FILE_SHARE_READ|FILE_SHARE_WRITE,
2367 (LPSECURITY_ATTRIBUTES) NULL,
Bram Moolenaareb3593b2006-04-22 22:33:57 +00002368 OPEN_EXISTING, 0, (HANDLE)NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002369 did_create_conin = TRUE;
2370}
2371
2372/*
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01002373 * Get a keystroke or a mouse event, use a blocking wait.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002374 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002375 static WCHAR
2376tgetch(int *pmodifiers, WCHAR *pch2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002377{
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002378 WCHAR ch;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002379
2380 for (;;)
2381 {
2382 INPUT_RECORD ir;
2383 DWORD cRecords = 0;
2384
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002385# ifdef FEAT_CLIENTSERVER
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02002386 (void)WaitForChar(-1L, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002387 if (input_available())
2388 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002389 if (g_nMouseClick != -1)
2390 return 0;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002391# endif
Bram Moolenaar3a69e112014-01-10 13:51:42 +01002392 if (read_console_input(g_hConIn, &ir, 1, &cRecords) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002393 {
2394 if (did_create_conin)
2395 read_error_exit();
2396 create_conin();
2397 continue;
2398 }
2399
2400 if (ir.EventType == KEY_EVENT)
2401 {
2402 if (decode_key_event(&ir.Event.KeyEvent, &ch, pch2,
2403 pmodifiers, TRUE))
2404 return ch;
2405 }
2406 else if (ir.EventType == FOCUS_EVENT)
2407 handle_focus_event(ir);
2408 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
2409 shell_resized();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002410 else if (ir.EventType == MOUSE_EVENT)
2411 {
2412 if (decode_mouse_event(&ir.Event.MouseEvent))
2413 return 0;
2414 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002415 }
2416}
Bram Moolenaar0f873732019-12-05 20:28:46 +01002417#endif // !FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00002418
2419
2420/*
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02002421 * mch_inchar(): low-level input function.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002422 * Get one or more characters from the keyboard or the mouse.
2423 * If time == 0, do not wait for characters.
2424 * If time == n, wait a short time for characters.
2425 * If time == -1, wait forever for characters.
2426 * Returns the number of characters read into buf.
2427 */
2428 int
2429mch_inchar(
Bram Moolenaar1266d672017-02-01 13:43:36 +01002430 char_u *buf UNUSED,
2431 int maxlen UNUSED,
2432 long time UNUSED,
2433 int tb_change_cnt UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002434{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002435#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002436
2437 int len;
2438 int c;
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01002439# ifdef VIMDLL
2440// Extra space for maximum three CSIs. E.g. U+1B6DB -> 0xF0 0x9B 0x9B 0x9B.
2441# define TYPEAHEADSPACE 6
2442# else
2443# define TYPEAHEADSPACE 0
2444# endif
2445# define TYPEAHEADLEN (20 + TYPEAHEADSPACE)
Bram Moolenaar0f873732019-12-05 20:28:46 +01002446 static char_u typeahead[TYPEAHEADLEN]; // previously typed bytes.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002447 static int typeaheadlen = 0;
2448
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002449# ifdef VIMDLL
2450 if (gui.in_use)
2451 return 0;
2452# endif
2453
Bram Moolenaar0f873732019-12-05 20:28:46 +01002454 // First use any typeahead that was kept because "buf" was too small.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002455 if (typeaheadlen > 0)
2456 goto theend;
2457
Bram Moolenaar071d4272004-06-13 20:20:40 +00002458 if (time >= 0)
2459 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01002460 if (!WaitForChar(time, FALSE)) // no character available
Bram Moolenaar071d4272004-06-13 20:20:40 +00002461 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002462 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01002463 else // time == -1, wait forever
Bram Moolenaar071d4272004-06-13 20:20:40 +00002464 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01002465 mch_set_winsize_now(); // Allow winsize changes from now on
Bram Moolenaar071d4272004-06-13 20:20:40 +00002466
Bram Moolenaar3918c952005-03-15 22:34:55 +00002467 /*
2468 * If there is no character available within 2 seconds (default)
2469 * write the autoscript file to disk. Or cause the CursorHold event
2470 * to be triggered.
2471 */
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02002472 if (!WaitForChar(p_ut, FALSE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002473 {
Bram Moolenaard35f9712005-12-18 22:02:33 +00002474 if (trigger_cursorhold() && maxlen >= 3)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002475 {
Bram Moolenaar3918c952005-03-15 22:34:55 +00002476 buf[0] = K_SPECIAL;
2477 buf[1] = KS_EXTRA;
2478 buf[2] = (int)KE_CURSORHOLD;
2479 return 3;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002480 }
Bram Moolenaar702517d2005-06-27 22:34:07 +00002481 before_blocking();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002482 }
2483 }
2484
2485 /*
2486 * Try to read as many characters as there are, until the buffer is full.
2487 */
2488
Bram Moolenaar0f873732019-12-05 20:28:46 +01002489 // we will get at least one key. Get more if they are available.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002490 g_fCBrkPressed = FALSE;
2491
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002492# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00002493 if (fdDump)
2494 fputc('[', fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002495# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002496
Bram Moolenaar0f873732019-12-05 20:28:46 +01002497 // Keep looping until there is something in the typeahead buffer and more
2498 // to get and still room in the buffer (up to two bytes for a char and
2499 // three bytes for a modifier).
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02002500 while ((typeaheadlen == 0 || WaitForChar(0L, FALSE))
Bram Moolenaar9f1983d2022-05-12 20:35:35 +01002501 && typeaheadlen + 5 + TYPEAHEADSPACE <= TYPEAHEADLEN)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002502 {
2503 if (typebuf_changed(tb_change_cnt))
2504 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01002505 // "buf" may be invalid now if a client put something in the
2506 // typeahead buffer and "buf" is in the typeahead buffer.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002507 typeaheadlen = 0;
2508 break;
2509 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002510 if (g_nMouseClick != -1)
2511 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002512# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00002513 if (fdDump)
2514 fprintf(fdDump, "{%02x @ %d, %d}",
2515 g_nMouseClick, g_xMouse, g_yMouse);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002516# endif
Christopher Plewright2a46f812022-10-16 19:47:45 +01002517 char_u modifiers = ((char_u *)(&g_nMouseClick))[0];
2518 char_u scroll_dir = ((char_u *)(&g_nMouseClick))[1];
2519
2520 if (scroll_dir == KE_MOUSEDOWN
2521 || scroll_dir == KE_MOUSEUP
2522 || scroll_dir == KE_MOUSELEFT
2523 || scroll_dir == KE_MOUSERIGHT)
2524 {
2525 if (modifiers > 0)
2526 {
Christopher Plewright03193062022-11-22 12:58:27 +00002527 // use K_SPECIAL instead of CSI to make mappings work
2528 typeahead[typeaheadlen++] = K_SPECIAL;
Christopher Plewright2a46f812022-10-16 19:47:45 +01002529 typeahead[typeaheadlen++] = KS_MODIFIER;
2530 typeahead[typeaheadlen++] = modifiers;
2531 }
2532 typeahead[typeaheadlen++] = CSI;
2533 typeahead[typeaheadlen++] = KS_EXTRA;
2534 typeahead[typeaheadlen++] = scroll_dir;
Christopher Plewright2a46f812022-10-16 19:47:45 +01002535 }
2536 else
2537 {
2538 typeahead[typeaheadlen++] = ESC + 128;
2539 typeahead[typeaheadlen++] = 'M';
2540 typeahead[typeaheadlen++] = g_nMouseClick;
Christopher Plewright2a46f812022-10-16 19:47:45 +01002541 }
Christopher Plewright36446bb2022-11-23 22:28:08 +00002542
2543 // Pass the pointer coordinates of the mouse event in 2 bytes,
2544 // allowing for > 223 columns. Both for click and scroll events.
2545 // This is the same as what is used for the GUI.
2546 typeahead[typeaheadlen++] = (char_u)(g_xMouse / 128 + ' ' + 1);
2547 typeahead[typeaheadlen++] = (char_u)(g_xMouse % 128 + ' ' + 1);
2548 typeahead[typeaheadlen++] = (char_u)(g_yMouse / 128 + ' ' + 1);
2549 typeahead[typeaheadlen++] = (char_u)(g_yMouse % 128 + ' ' + 1);
2550
2551 g_nMouseClick = -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002552 }
2553 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00002554 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002555 WCHAR ch2 = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002556 int modifiers = 0;
2557
2558 c = tgetch(&modifiers, &ch2);
2559
Christopher Plewrightc8b20492023-01-04 18:06:00 +00002560 c = simplify_key(c, &modifiers);
2561
Christopher Plewright7b0afc12022-12-30 16:54:58 +00002562 // Some chars need adjustment when the Ctrl modifier is used.
2563 ++no_reduce_keys;
2564 c = may_adjust_key_for_ctrl(modifiers, c);
2565 --no_reduce_keys;
2566
2567 // remove the SHIFT modifier for keys where it's already included,
2568 // e.g., '(' and '*'
2569 modifiers = may_remove_shift_modifier(modifiers, c);
2570
Bram Moolenaar071d4272004-06-13 20:20:40 +00002571 if (typebuf_changed(tb_change_cnt))
2572 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01002573 // "buf" may be invalid now if a client put something in the
2574 // typeahead buffer and "buf" is in the typeahead buffer.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002575 typeaheadlen = 0;
2576 break;
2577 }
2578
2579 if (c == Ctrl_C && ctrl_c_interrupts)
2580 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002581# if defined(FEAT_CLIENTSERVER)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002582 trash_input_buf();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002583# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002584 got_int = TRUE;
2585 }
2586
Bram Moolenaar071d4272004-06-13 20:20:40 +00002587 if (g_nMouseClick == -1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002588 {
2589 int n = 1;
2590
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002591 if (ch2 == NUL)
2592 {
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01002593 int i, j;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002594 char_u *p;
2595 WCHAR ch[2];
2596
2597 ch[0] = c;
Bram Moolenaar0f873732019-12-05 20:28:46 +01002598 if (c >= 0xD800 && c <= 0xDBFF) // High surrogate
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002599 {
2600 ch[1] = tgetch(&modifiers, &ch2);
2601 n++;
2602 }
2603 p = utf16_to_enc(ch, &n);
2604 if (p != NULL)
2605 {
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01002606 for (i = 0, j = 0; i < n; i++)
2607 {
2608 typeahead[typeaheadlen + j++] = p[i];
2609# ifdef VIMDLL
2610 if (p[i] == CSI)
2611 {
2612 typeahead[typeaheadlen + j++] = KS_EXTRA;
2613 typeahead[typeaheadlen + j++] = KE_CSI;
2614 }
2615# endif
2616 }
2617 n = j;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002618 vim_free(p);
2619 }
2620 }
2621 else
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01002622 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002623 typeahead[typeaheadlen] = c;
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01002624# ifdef VIMDLL
2625 if (c == CSI)
2626 {
2627 typeahead[typeaheadlen + 1] = KS_EXTRA;
2628 typeahead[typeaheadlen + 2] = KE_CSI;
2629 n = 3;
2630 }
2631# endif
2632 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002633 if (ch2 != NUL)
2634 {
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +02002635 if (c == K_NUL)
Bram Moolenaarfeeb4d02017-12-05 15:14:46 +01002636 {
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +02002637 switch (ch2)
2638 {
2639 case (WCHAR)'\324': // SHIFT+Insert
2640 case (WCHAR)'\325': // CTRL+Insert
2641 case (WCHAR)'\327': // SHIFT+Delete
2642 case (WCHAR)'\330': // CTRL+Delete
2643 typeahead[typeaheadlen + n] = (char_u)ch2;
2644 n++;
2645 break;
2646
2647 default:
2648 typeahead[typeaheadlen + n] = 3;
2649 typeahead[typeaheadlen + n + 1] = (char_u)ch2;
2650 n += 2;
2651 break;
2652 }
Bram Moolenaarfeeb4d02017-12-05 15:14:46 +01002653 }
2654 else
2655 {
2656 typeahead[typeaheadlen + n] = 3;
2657 typeahead[typeaheadlen + n + 1] = (char_u)ch2;
2658 n += 2;
2659 }
Bram Moolenaar45500912014-07-09 20:51:07 +02002660 }
2661
Bram Moolenaar0f873732019-12-05 20:28:46 +01002662 // Use the ALT key to set the 8th bit of the character
2663 // when it's one byte, the 8th bit isn't set yet and not
2664 // using a double-byte encoding (would become a lead
2665 // byte).
Bram Moolenaar071d4272004-06-13 20:20:40 +00002666 if ((modifiers & MOD_MASK_ALT)
2667 && n == 1
2668 && (typeahead[typeaheadlen] & 0x80) == 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00002669 && !enc_dbcs
Bram Moolenaar071d4272004-06-13 20:20:40 +00002670 )
2671 {
Bram Moolenaar85a3e5c2007-11-20 16:22:16 +00002672 n = (*mb_char2bytes)(typeahead[typeaheadlen] | 0x80,
2673 typeahead + typeaheadlen);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002674 modifiers &= ~MOD_MASK_ALT;
2675 }
2676
2677 if (modifiers != 0)
2678 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01002679 // Prepend modifiers to the character.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002680 mch_memmove(typeahead + typeaheadlen + 3,
2681 typeahead + typeaheadlen, n);
2682 typeahead[typeaheadlen++] = K_SPECIAL;
2683 typeahead[typeaheadlen++] = (char_u)KS_MODIFIER;
2684 typeahead[typeaheadlen++] = modifiers;
2685 }
2686
2687 typeaheadlen += n;
2688
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002689# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00002690 if (fdDump)
2691 fputc(c, fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002692# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002693 }
2694 }
2695 }
2696
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002697# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00002698 if (fdDump)
2699 {
2700 fputs("]\n", fdDump);
2701 fflush(fdDump);
2702 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002703# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002704
Bram Moolenaar071d4272004-06-13 20:20:40 +00002705theend:
Bram Moolenaar0f873732019-12-05 20:28:46 +01002706 // Move typeahead to "buf", as much as fits.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002707 len = 0;
2708 while (len < maxlen && typeaheadlen > 0)
2709 {
2710 buf[len++] = typeahead[0];
2711 mch_memmove(typeahead, typeahead + 1, --typeaheadlen);
2712 }
Bram Moolenaar4c5678f2022-11-30 18:12:19 +00002713# ifdef FEAT_EVAL
Bram Moolenaar7ca86fe2020-09-03 19:25:11 +02002714 if (len > 0)
2715 {
2716 buf[len] = NUL;
2717 ch_log(NULL, "raw key input: \"%s\"", buf);
2718 }
K.Takata6e1d31e2022-02-03 13:05:32 +00002719# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002720 return len;
2721
Bram Moolenaar0f873732019-12-05 20:28:46 +01002722#else // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00002723 return 0;
Bram Moolenaar0f873732019-12-05 20:28:46 +01002724#endif // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00002725}
2726
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002727/*
Bram Moolenaar95da1362020-05-30 18:37:55 +02002728 * Return TRUE if "name" is an executable file, FALSE if not or it doesn't exist.
Bram Moolenaar43663192017-03-05 14:29:12 +01002729 * When returning TRUE and "path" is not NULL save the path and set "*path" to
2730 * the allocated memory.
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00002731 * TODO: Should somehow check if it's really executable.
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002732 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002733 static int
Bram Moolenaar95da1362020-05-30 18:37:55 +02002734executable_file(char *name, char_u **path)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002735{
LemonBoy40fd7e62022-05-05 20:18:16 +01002736 int attrs = win32_getattrs((char_u *)name);
2737
2738 // The file doesn't exist or is a folder.
2739 if (attrs == -1 || (attrs & FILE_ATTRIBUTE_DIRECTORY))
2740 return FALSE;
2741 // Check if the file is an AppExecLink, a special alias used by Windows
2742 // Store for its apps.
2743 if (attrs & FILE_ATTRIBUTE_REPARSE_POINT)
Bram Moolenaar43663192017-03-05 14:29:12 +01002744 {
LemonBoy40fd7e62022-05-05 20:18:16 +01002745 char_u *res = resolve_appexeclink((char_u *)name);
2746 if (res == NULL)
AmberArrf5d0f542023-08-20 20:03:45 +02002747 res = resolve_reparse_point((char_u *)name);
2748 if (res == NULL)
LemonBoy40fd7e62022-05-05 20:18:16 +01002749 return FALSE;
2750 // The path is already absolute.
Bram Moolenaar95da1362020-05-30 18:37:55 +02002751 if (path != NULL)
LemonBoy40fd7e62022-05-05 20:18:16 +01002752 *path = res;
2753 else
2754 vim_free(res);
Bram Moolenaar95da1362020-05-30 18:37:55 +02002755 }
LemonBoy40fd7e62022-05-05 20:18:16 +01002756 else if (path != NULL)
2757 *path = FullName_save((char_u *)name, FALSE);
2758 return TRUE;
Bram Moolenaar95da1362020-05-30 18:37:55 +02002759}
2760
2761/*
2762 * If "use_path" is TRUE: Return TRUE if "name" is in $PATH.
2763 * If "use_path" is FALSE: Return TRUE if "name" exists.
2764 * If "use_pathext" is TRUE search "name" with extensions in $PATHEXT.
2765 * When returning TRUE and "path" is not NULL save the path and set "*path" to
2766 * the allocated memory.
2767 */
2768 static int
2769executable_exists(char *name, char_u **path, int use_path, int use_pathext)
2770{
2771 // WinNT and later can use _MAX_PATH wide characters for a pathname, which
2772 // means that the maximum pathname is _MAX_PATH * 3 bytes when 'enc' is
2773 // UTF-8.
2774 char_u buf[_MAX_PATH * 3];
2775 size_t len = STRLEN(name);
2776 size_t tmplen;
2777 char_u *p, *e, *e2;
2778 char_u *pathbuf = NULL;
2779 char_u *pathext = NULL;
2780 char_u *pathextbuf = NULL;
Mike Williamsa3d1b292021-06-30 20:56:00 +02002781 char_u *shname = NULL;
Bram Moolenaar95da1362020-05-30 18:37:55 +02002782 int noext = FALSE;
2783 int retval = FALSE;
2784
2785 if (len >= sizeof(buf)) // safety check
Bram Moolenaar43663192017-03-05 14:29:12 +01002786 return FALSE;
Bram Moolenaar95da1362020-05-30 18:37:55 +02002787
2788 // Using the name directly when a Unix-shell like 'shell'.
Mike Williamsa3d1b292021-06-30 20:56:00 +02002789 shname = gettail(p_sh);
2790 if (strstr((char *)shname, "sh") != NULL &&
2791 !(strstr((char *)shname, "powershell") != NULL
2792 || strstr((char *)shname, "pwsh") != NULL))
Bram Moolenaar95da1362020-05-30 18:37:55 +02002793 noext = TRUE;
2794
2795 if (use_pathext)
2796 {
2797 pathext = mch_getenv("PATHEXT");
2798 if (pathext == NULL)
2799 pathext = (char_u *)".com;.exe;.bat;.cmd";
2800
2801 if (noext == FALSE)
2802 {
2803 /*
2804 * Loop over all extensions in $PATHEXT.
2805 * Check "name" ends with extension.
2806 */
2807 p = pathext;
2808 while (*p)
2809 {
2810 if (p[0] == ';'
2811 || (p[0] == '.' && (p[1] == NUL || p[1] == ';')))
2812 {
2813 // Skip empty or single ".".
2814 ++p;
2815 continue;
2816 }
2817 e = vim_strchr(p, ';');
2818 if (e == NULL)
2819 e = p + STRLEN(p);
2820 tmplen = e - p;
2821
2822 if (_strnicoll(name + len - tmplen, (char *)p, tmplen) == 0)
2823 {
2824 noext = TRUE;
2825 break;
2826 }
2827
2828 p = e;
2829 }
2830 }
Bram Moolenaar43663192017-03-05 14:29:12 +01002831 }
2832
Dominique Pelleaf4a61a2021-12-27 17:21:41 +00002833 // Prepend single "." to pathext, it means no extension added.
Bram Moolenaar95da1362020-05-30 18:37:55 +02002834 if (pathext == NULL)
2835 pathext = (char_u *)".";
2836 else if (noext == TRUE)
2837 {
2838 if (pathextbuf == NULL)
2839 pathextbuf = alloc(STRLEN(pathext) + 3);
2840 if (pathextbuf == NULL)
2841 {
2842 retval = FALSE;
2843 goto theend;
2844 }
2845 STRCPY(pathextbuf, ".;");
2846 STRCAT(pathextbuf, pathext);
2847 pathext = pathextbuf;
2848 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002849
Bram Moolenaar95da1362020-05-30 18:37:55 +02002850 // Use $PATH when "use_path" is TRUE and "name" is basename.
2851 if (use_path && gettail((char_u *)name) == (char_u *)name)
2852 {
2853 p = mch_getenv("PATH");
2854 if (p != NULL)
2855 {
2856 pathbuf = alloc(STRLEN(p) + 3);
2857 if (pathbuf == NULL)
2858 {
2859 retval = FALSE;
2860 goto theend;
2861 }
Yasuhiro Matsumoto05cf63e2022-05-03 11:02:28 +01002862
2863 if (mch_getenv("NoDefaultCurrentDirectoryInExePath") == NULL)
2864 STRCPY(pathbuf, ".;");
2865 else
2866 *pathbuf = NUL;
Bram Moolenaar95da1362020-05-30 18:37:55 +02002867 STRCAT(pathbuf, p);
2868 }
2869 }
2870
2871 /*
2872 * Walk through all entries in $PATH to check if "name" exists there and
2873 * is an executable file.
2874 */
2875 p = (pathbuf != NULL) ? pathbuf : (char_u *)".";
2876 while (*p)
2877 {
2878 if (*p == ';') // Skip empty entry
2879 {
2880 ++p;
2881 continue;
2882 }
2883 e = vim_strchr(p, ';');
2884 if (e == NULL)
2885 e = p + STRLEN(p);
2886
2887 if (e - p + len + 2 > sizeof(buf))
2888 {
2889 retval = FALSE;
2890 goto theend;
2891 }
2892 // A single "." that means current dir.
2893 if (e - p == 1 && *p == '.')
2894 STRCPY(buf, name);
2895 else
2896 {
2897 vim_strncpy(buf, p, e - p);
2898 add_pathsep(buf);
2899 STRCAT(buf, name);
2900 }
2901 tmplen = STRLEN(buf);
2902
2903 /*
2904 * Loop over all extensions in $PATHEXT.
2905 * Check "name" with extension added.
2906 */
2907 p = pathext;
2908 while (*p)
2909 {
2910 if (*p == ';')
2911 {
2912 // Skip empty entry
2913 ++p;
2914 continue;
2915 }
2916 e2 = vim_strchr(p, (int)';');
2917 if (e2 == NULL)
2918 e2 = p + STRLEN(p);
2919
2920 if (!(p[0] == '.' && (p[1] == NUL || p[1] == ';')))
2921 {
2922 // Not a single "." that means no extension is added.
2923 if (e2 - p + tmplen + 1 > sizeof(buf))
2924 {
2925 retval = FALSE;
2926 goto theend;
2927 }
2928 vim_strncpy(buf + tmplen, p, e2 - p);
2929 }
2930 if (executable_file((char *)buf, path))
2931 {
2932 retval = TRUE;
2933 goto theend;
2934 }
2935
2936 p = e2;
2937 }
2938
2939 p = e;
2940 }
2941
2942theend:
2943 free(pathextbuf);
2944 free(pathbuf);
2945 return retval;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002946}
2947
Bram Moolenaar1eed5322019-02-26 17:03:54 +01002948#if (defined(__MINGW32__) && __MSVCRT_VERSION__ >= 0x800) || \
2949 (defined(_MSC_VER) && _MSC_VER >= 1400)
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002950/*
2951 * Bad parameter handler.
2952 *
2953 * Certain MS CRT functions will intentionally crash when passed invalid
2954 * parameters to highlight possible security holes. Setting this function as
2955 * the bad parameter handler will prevent the crash.
2956 *
2957 * In debug builds the parameters contain CRT information that might help track
2958 * down the source of a problem, but in non-debug builds the arguments are all
2959 * NULL/0. Debug builds will also produce assert dialogs from the CRT, it is
2960 * worth allowing these to make debugging of issues easier.
2961 */
2962 static void
Yegappan Lakshmanana34b4462022-06-11 10:43:26 +01002963bad_param_handler(const wchar_t *expression UNUSED,
2964 const wchar_t *function UNUSED,
2965 const wchar_t *file UNUSED,
2966 unsigned int line UNUSED,
2967 uintptr_t pReserved UNUSED)
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002968{
2969}
2970
2971# define SET_INVALID_PARAM_HANDLER \
2972 ((void)_set_invalid_parameter_handler(bad_param_handler))
2973#else
2974# define SET_INVALID_PARAM_HANDLER
2975#endif
2976
Bram Moolenaar4f974752019-02-17 17:44:42 +01002977#ifdef FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00002978
2979/*
2980 * GUI version of mch_init().
2981 */
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002982 static void
2983mch_init_g(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002984{
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002985# ifndef __MINGW32__
Bram Moolenaar071d4272004-06-13 20:20:40 +00002986 extern int _fmode;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002987# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002988
Bram Moolenaar0f873732019-12-05 20:28:46 +01002989 // Silently handle invalid parameters to CRT functions
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002990 SET_INVALID_PARAM_HANDLER;
2991
Bram Moolenaar0f873732019-12-05 20:28:46 +01002992 // Let critical errors result in a failure, not in a dialog box. Required
2993 // for the timestamp test to work on removed floppies.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002994 SetErrorMode(SEM_FAILCRITICALERRORS);
2995
Bram Moolenaar0f873732019-12-05 20:28:46 +01002996 _fmode = O_BINARY; // we do our own CR-LF translation
Bram Moolenaar071d4272004-06-13 20:20:40 +00002997
Bram Moolenaar0f873732019-12-05 20:28:46 +01002998 // Specify window size. Is there a place to get the default from?
Bram Moolenaar071d4272004-06-13 20:20:40 +00002999 Rows = 25;
3000 Columns = 80;
3001
Bram Moolenaar0f873732019-12-05 20:28:46 +01003002 // Look for 'vimrun'
Bram Moolenaar071d4272004-06-13 20:20:40 +00003003 {
3004 char_u vimrun_location[_MAX_PATH + 4];
3005
Bram Moolenaar0f873732019-12-05 20:28:46 +01003006 // First try in same directory as gvim.exe
Bram Moolenaar071d4272004-06-13 20:20:40 +00003007 STRCPY(vimrun_location, exe_name);
3008 STRCPY(gettail(vimrun_location), "vimrun.exe");
3009 if (mch_getperm(vimrun_location) >= 0)
3010 {
3011 if (*skiptowhite(vimrun_location) != NUL)
3012 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01003013 // Enclose path with white space in double quotes.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003014 mch_memmove(vimrun_location + 1, vimrun_location,
3015 STRLEN(vimrun_location) + 1);
3016 *vimrun_location = '"';
3017 STRCPY(gettail(vimrun_location), "vimrun\" ");
3018 }
3019 else
3020 STRCPY(gettail(vimrun_location), "vimrun ");
3021
3022 vimrun_path = (char *)vim_strsave(vimrun_location);
3023 s_dont_use_vimrun = FALSE;
3024 }
Bram Moolenaar95da1362020-05-30 18:37:55 +02003025 else if (executable_exists("vimrun.exe", NULL, TRUE, FALSE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003026 s_dont_use_vimrun = FALSE;
3027
Bram Moolenaar0f873732019-12-05 20:28:46 +01003028 // Don't give the warning for a missing vimrun.exe right now, but only
3029 // when vimrun was supposed to be used. Don't bother people that do
3030 // not need vimrun.exe.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003031 if (s_dont_use_vimrun)
3032 need_vimrun_warning = TRUE;
3033 }
3034
3035 /*
3036 * If "finstr.exe" doesn't exist, use "grep -n" for 'grepprg'.
3037 * Otherwise the default "findstr /n" is used.
3038 */
Bram Moolenaar95da1362020-05-30 18:37:55 +02003039 if (!executable_exists("findstr.exe", NULL, TRUE, FALSE))
Bram Moolenaar75ab5902022-04-18 15:36:40 +01003040 set_option_value_give_err((char_u *)"grepprg",
3041 0, (char_u *)"grep -n", 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003042
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003043# ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01003044 win_clip_init();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003045# endif
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01003046
3047 vtp_flag_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00003048}
3049
3050
Bram Moolenaar0f873732019-12-05 20:28:46 +01003051#endif // FEAT_GUI_MSWIN
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003052
3053#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003054
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003055# define SRWIDTH(sr) ((sr).Right - (sr).Left + 1)
3056# define SRHEIGHT(sr) ((sr).Bottom - (sr).Top + 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003057
3058/*
3059 * ClearConsoleBuffer()
3060 * Description:
3061 * Clears the entire contents of the console screen buffer, using the
3062 * specified attribute.
3063 * Returns:
3064 * TRUE on success
3065 */
3066 static BOOL
3067ClearConsoleBuffer(WORD wAttribute)
3068{
3069 CONSOLE_SCREEN_BUFFER_INFO csbi;
3070 COORD coord;
3071 DWORD NumCells, dummy;
3072
3073 if (!GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3074 return FALSE;
3075
3076 NumCells = csbi.dwSize.X * csbi.dwSize.Y;
3077 coord.X = 0;
3078 coord.Y = 0;
3079 if (!FillConsoleOutputCharacter(g_hConOut, ' ', NumCells,
3080 coord, &dummy))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003081 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003082 if (!FillConsoleOutputAttribute(g_hConOut, wAttribute, NumCells,
3083 coord, &dummy))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003084 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003085
3086 return TRUE;
3087}
3088
3089/*
3090 * FitConsoleWindow()
3091 * Description:
3092 * Checks if the console window will fit within given buffer dimensions.
3093 * Also, if requested, will shrink the window to fit.
3094 * Returns:
3095 * TRUE on success
3096 */
3097 static BOOL
3098FitConsoleWindow(
3099 COORD dwBufferSize,
3100 BOOL WantAdjust)
3101{
3102 CONSOLE_SCREEN_BUFFER_INFO csbi;
3103 COORD dwWindowSize;
3104 BOOL NeedAdjust = FALSE;
3105
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00003106 if (!GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3107 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003108
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00003109 /*
3110 * A buffer resize will fail if the current console window does
3111 * not lie completely within that buffer. To avoid this, we might
3112 * have to move and possibly shrink the window.
3113 */
3114 if (csbi.srWindow.Right >= dwBufferSize.X)
3115 {
3116 dwWindowSize.X = SRWIDTH(csbi.srWindow);
3117 if (dwWindowSize.X > dwBufferSize.X)
3118 dwWindowSize.X = dwBufferSize.X;
3119 csbi.srWindow.Right = dwBufferSize.X - 1;
3120 csbi.srWindow.Left = dwBufferSize.X - dwWindowSize.X;
3121 NeedAdjust = TRUE;
3122 }
3123 if (csbi.srWindow.Bottom >= dwBufferSize.Y)
3124 {
3125 dwWindowSize.Y = SRHEIGHT(csbi.srWindow);
3126 if (dwWindowSize.Y > dwBufferSize.Y)
3127 dwWindowSize.Y = dwBufferSize.Y;
3128 csbi.srWindow.Bottom = dwBufferSize.Y - 1;
3129 csbi.srWindow.Top = dwBufferSize.Y - dwWindowSize.Y;
3130 NeedAdjust = TRUE;
3131 }
3132 if (NeedAdjust && WantAdjust)
3133 {
3134 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &csbi.srWindow))
3135 return FALSE;
3136 }
3137 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003138}
3139
3140typedef struct ConsoleBufferStruct
3141{
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003142 BOOL IsValid;
3143 CONSOLE_SCREEN_BUFFER_INFO Info;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003144 PCHAR_INFO Buffer;
3145 COORD BufferSize;
Bram Moolenaar444fda22017-08-11 20:37:00 +02003146 PSMALL_RECT Regions;
3147 int NumRegions;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003148} ConsoleBuffer;
3149
3150/*
3151 * SaveConsoleBuffer()
3152 * Description:
3153 * Saves important information about the console buffer, including the
3154 * actual buffer contents. The saved information is suitable for later
3155 * restoration by RestoreConsoleBuffer().
3156 * Returns:
3157 * TRUE if all information was saved; FALSE otherwise
3158 * If FALSE, still sets cb->IsValid if buffer characteristics were saved.
3159 */
3160 static BOOL
3161SaveConsoleBuffer(
3162 ConsoleBuffer *cb)
3163{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003164 DWORD NumCells;
3165 COORD BufferCoord;
3166 SMALL_RECT ReadRegion;
3167 WORD Y, Y_incr;
Bram Moolenaar444fda22017-08-11 20:37:00 +02003168 int i, numregions;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003169
Bram Moolenaar071d4272004-06-13 20:20:40 +00003170 if (cb == NULL)
3171 return FALSE;
3172
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003173 if (!GetConsoleScreenBufferInfo(g_hConOut, &cb->Info))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003174 {
3175 cb->IsValid = FALSE;
3176 return FALSE;
3177 }
3178 cb->IsValid = TRUE;
3179
Christopher Plewright1140b512022-11-12 18:46:05 +00003180 // VTP uses alternate screen buffer.
3181 // No need to save buffer contents for restoration.
Christopher Plewrightc8b126d2022-12-22 13:45:23 +00003182 if (use_alternate_screen_buffer)
Christopher Plewright1140b512022-11-12 18:46:05 +00003183 return TRUE;
3184
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003185 /*
3186 * Allocate a buffer large enough to hold the entire console screen
3187 * buffer. If this ConsoleBuffer structure has already been initialized
3188 * with a buffer of the correct size, then just use that one.
3189 */
3190 if (!cb->IsValid || cb->Buffer == NULL ||
3191 cb->BufferSize.X != cb->Info.dwSize.X ||
3192 cb->BufferSize.Y != cb->Info.dwSize.Y)
3193 {
3194 cb->BufferSize.X = cb->Info.dwSize.X;
3195 cb->BufferSize.Y = cb->Info.dwSize.Y;
3196 NumCells = cb->BufferSize.X * cb->BufferSize.Y;
3197 vim_free(cb->Buffer);
Bram Moolenaarc799fe22019-05-28 23:08:19 +02003198 cb->Buffer = ALLOC_MULT(CHAR_INFO, NumCells);
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003199 if (cb->Buffer == NULL)
3200 return FALSE;
3201 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003202
3203 /*
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003204 * We will now copy the console screen buffer into our buffer.
3205 * ReadConsoleOutput() seems to be limited as far as how much you
3206 * can read at a time. Empirically, this number seems to be about
3207 * 12000 cells (rows * columns). Start at position (0, 0) and copy
3208 * in chunks until it is all copied. The chunks will all have the
3209 * same horizontal characteristics, so initialize them now. The
3210 * height of each chunk will be (12000 / width).
Bram Moolenaar071d4272004-06-13 20:20:40 +00003211 */
Bram Moolenaar61594242015-09-01 20:23:37 +02003212 BufferCoord.X = 0;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003213 ReadRegion.Left = 0;
3214 ReadRegion.Right = cb->Info.dwSize.X - 1;
3215 Y_incr = 12000 / cb->Info.dwSize.X;
Bram Moolenaar444fda22017-08-11 20:37:00 +02003216
3217 numregions = (cb->Info.dwSize.Y + Y_incr - 1) / Y_incr;
3218 if (cb->Regions == NULL || numregions != cb->NumRegions)
3219 {
3220 cb->NumRegions = numregions;
3221 vim_free(cb->Regions);
Bram Moolenaarc799fe22019-05-28 23:08:19 +02003222 cb->Regions = ALLOC_MULT(SMALL_RECT, cb->NumRegions);
Bram Moolenaar444fda22017-08-11 20:37:00 +02003223 if (cb->Regions == NULL)
3224 {
Bram Moolenaard23a8232018-02-10 18:45:26 +01003225 VIM_CLEAR(cb->Buffer);
Bram Moolenaar444fda22017-08-11 20:37:00 +02003226 return FALSE;
3227 }
3228 }
3229
3230 for (i = 0, Y = 0; i < cb->NumRegions; i++, Y += Y_incr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003231 {
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003232 /*
3233 * Read into position (0, Y) in our buffer.
3234 */
3235 BufferCoord.Y = Y;
3236 /*
3237 * Read the region whose top left corner is (0, Y) and whose bottom
3238 * right corner is (width - 1, Y + Y_incr - 1). This should define
3239 * a region of size width by Y_incr. Don't worry if this region is
3240 * too large for the remaining buffer; it will be cropped.
3241 */
3242 ReadRegion.Top = Y;
3243 ReadRegion.Bottom = Y + Y_incr - 1;
Bram Moolenaar0f873732019-12-05 20:28:46 +01003244 if (!ReadConsoleOutputW(g_hConOut, // output handle
3245 cb->Buffer, // our buffer
3246 cb->BufferSize, // dimensions of our buffer
3247 BufferCoord, // offset in our buffer
3248 &ReadRegion)) // region to save
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003249 {
Bram Moolenaard23a8232018-02-10 18:45:26 +01003250 VIM_CLEAR(cb->Buffer);
3251 VIM_CLEAR(cb->Regions);
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003252 return FALSE;
3253 }
Bram Moolenaar444fda22017-08-11 20:37:00 +02003254 cb->Regions[i] = ReadRegion;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003255 }
3256
3257 return TRUE;
3258}
3259
3260/*
3261 * RestoreConsoleBuffer()
3262 * Description:
3263 * Restores important information about the console buffer, including the
3264 * actual buffer contents, if desired. The information to restore is in
3265 * the same format used by SaveConsoleBuffer().
3266 * Returns:
3267 * TRUE on success
3268 */
3269 static BOOL
3270RestoreConsoleBuffer(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003271 ConsoleBuffer *cb,
3272 BOOL RestoreScreen)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003273{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003274 COORD BufferCoord;
3275 SMALL_RECT WriteRegion;
Bram Moolenaar444fda22017-08-11 20:37:00 +02003276 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003277
Christopher Plewright1140b512022-11-12 18:46:05 +00003278 // VTP uses alternate screen buffer.
3279 // No need to restore buffer contents.
Christopher Plewrightc8b126d2022-12-22 13:45:23 +00003280 if (use_alternate_screen_buffer)
Christopher Plewright1140b512022-11-12 18:46:05 +00003281 return TRUE;
3282
Bram Moolenaar071d4272004-06-13 20:20:40 +00003283 if (cb == NULL || !cb->IsValid)
3284 return FALSE;
3285
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003286 /*
3287 * Before restoring the buffer contents, clear the current buffer, and
3288 * restore the cursor position and window information. Doing this now
3289 * prevents old buffer contents from "flashing" onto the screen.
3290 */
3291 if (RestoreScreen)
3292 ClearConsoleBuffer(cb->Info.wAttributes);
3293
3294 FitConsoleWindow(cb->Info.dwSize, TRUE);
3295 if (!SetConsoleScreenBufferSize(g_hConOut, cb->Info.dwSize))
3296 return FALSE;
3297 if (!SetConsoleTextAttribute(g_hConOut, cb->Info.wAttributes))
3298 return FALSE;
3299
3300 if (!RestoreScreen)
3301 {
3302 /*
3303 * No need to restore the screen buffer contents, so we're done.
3304 */
3305 return TRUE;
3306 }
3307
3308 if (!SetConsoleCursorPosition(g_hConOut, cb->Info.dwCursorPosition))
3309 return FALSE;
3310 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &cb->Info.srWindow))
3311 return FALSE;
3312
3313 /*
3314 * Restore the screen buffer contents.
3315 */
3316 if (cb->Buffer != NULL)
3317 {
Bram Moolenaar444fda22017-08-11 20:37:00 +02003318 for (i = 0; i < cb->NumRegions; i++)
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003319 {
Bram Moolenaar444fda22017-08-11 20:37:00 +02003320 BufferCoord.X = cb->Regions[i].Left;
3321 BufferCoord.Y = cb->Regions[i].Top;
3322 WriteRegion = cb->Regions[i];
Bram Moolenaar0f873732019-12-05 20:28:46 +01003323 if (!WriteConsoleOutputW(g_hConOut, // output handle
3324 cb->Buffer, // our buffer
3325 cb->BufferSize, // dimensions of our buffer
3326 BufferCoord, // offset in our buffer
3327 &WriteRegion)) // region to restore
Bram Moolenaar444fda22017-08-11 20:37:00 +02003328 return FALSE;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003329 }
3330 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003331
3332 return TRUE;
3333}
3334
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003335# define FEAT_RESTORE_ORIG_SCREEN
3336# ifdef FEAT_RESTORE_ORIG_SCREEN
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003337static ConsoleBuffer g_cbOrig = { 0 };
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003338# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003339static ConsoleBuffer g_cbNonTermcap = { 0 };
3340static ConsoleBuffer g_cbTermcap = { 0 };
3341
Bram Moolenaar071d4272004-06-13 20:20:40 +00003342char g_szOrigTitle[256] = { 0 };
Bram Moolenaar0f873732019-12-05 20:28:46 +01003343HWND g_hWnd = NULL; // also used in os_mswin.c
Bram Moolenaar071d4272004-06-13 20:20:40 +00003344static HICON g_hOrigIconSmall = NULL;
3345static HICON g_hOrigIcon = NULL;
3346static HICON g_hVimIcon = NULL;
3347static BOOL g_fCanChangeIcon = FALSE;
3348
Bram Moolenaar071d4272004-06-13 20:20:40 +00003349/*
3350 * GetConsoleIcon()
3351 * Description:
3352 * Attempts to retrieve the small icon and/or the big icon currently in
3353 * use by a given window.
3354 * Returns:
3355 * TRUE on success
3356 */
3357 static BOOL
3358GetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003359 HWND hWnd,
3360 HICON *phIconSmall,
3361 HICON *phIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003362{
3363 if (hWnd == NULL)
3364 return FALSE;
3365
3366 if (phIconSmall != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003367 *phIconSmall = (HICON)SendMessage(hWnd, WM_GETICON,
3368 (WPARAM)ICON_SMALL, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003369 if (phIcon != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003370 *phIcon = (HICON)SendMessage(hWnd, WM_GETICON,
3371 (WPARAM)ICON_BIG, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003372 return TRUE;
3373}
3374
3375/*
3376 * SetConsoleIcon()
3377 * Description:
3378 * Attempts to change the small icon and/or the big icon currently in
3379 * use by a given window.
3380 * Returns:
3381 * TRUE on success
3382 */
3383 static BOOL
3384SetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003385 HWND hWnd,
3386 HICON hIconSmall,
3387 HICON hIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003388{
Bram Moolenaar071d4272004-06-13 20:20:40 +00003389 if (hWnd == NULL)
3390 return FALSE;
3391
3392 if (hIconSmall != NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003393 SendMessage(hWnd, WM_SETICON,
3394 (WPARAM)ICON_SMALL, (LPARAM)hIconSmall);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003395 if (hIcon != NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003396 SendMessage(hWnd, WM_SETICON,
3397 (WPARAM)ICON_BIG, (LPARAM) hIcon);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003398 return TRUE;
3399}
3400
3401/*
3402 * SaveConsoleTitleAndIcon()
3403 * Description:
3404 * Saves the current console window title in g_szOrigTitle, for later
3405 * restoration. Also, attempts to obtain a handle to the console window,
3406 * and use it to save the small and big icons currently in use by the
3407 * console window. This is not always possible on some versions of Windows;
3408 * nor is it possible when running Vim remotely using Telnet (since the
3409 * console window the user sees is owned by a remote process).
3410 */
3411 static void
3412SaveConsoleTitleAndIcon(void)
3413{
Bram Moolenaar0f873732019-12-05 20:28:46 +01003414 // Save the original title.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003415 if (!GetConsoleTitle(g_szOrigTitle, sizeof(g_szOrigTitle)))
3416 return;
3417
3418 /*
3419 * Obtain a handle to the console window using GetConsoleWindow() from
3420 * KERNEL32.DLL; we need to handle in order to change the window icon.
3421 * This function only exists on NT-based Windows, starting with Windows
3422 * 2000. On older operating systems, we can't change the window icon
3423 * anyway.
3424 */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003425 g_hWnd = GetConsoleWindow();
Bram Moolenaar071d4272004-06-13 20:20:40 +00003426 if (g_hWnd == NULL)
3427 return;
3428
Bram Moolenaar0f873732019-12-05 20:28:46 +01003429 // Save the original console window icon.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003430 GetConsoleIcon(g_hWnd, &g_hOrigIconSmall, &g_hOrigIcon);
3431 if (g_hOrigIconSmall == NULL || g_hOrigIcon == NULL)
3432 return;
3433
Bram Moolenaar0f873732019-12-05 20:28:46 +01003434 // Extract the first icon contained in the Vim executable.
K.Takata2da11a42022-09-10 13:03:12 +01003435 if (
3436# ifdef FEAT_LIBCALL
3437 mch_icon_load((HANDLE *)&g_hVimIcon) == FAIL ||
3438# endif
3439 g_hVimIcon == NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003440 g_hVimIcon = ExtractIcon(NULL, (LPCSTR)exe_name, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003441 if (g_hVimIcon != NULL)
3442 g_fCanChangeIcon = TRUE;
3443}
Bram Moolenaar071d4272004-06-13 20:20:40 +00003444
3445static int g_fWindInitCalled = FALSE;
3446static int g_fTermcapMode = FALSE;
3447static CONSOLE_CURSOR_INFO g_cci;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003448
3449/*
3450 * non-GUI version of mch_init().
3451 */
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003452 static void
3453mch_init_c(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003454{
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003455# ifndef FEAT_RESTORE_ORIG_SCREEN
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003456 CONSOLE_SCREEN_BUFFER_INFO csbi;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003457# endif
3458# ifndef __MINGW32__
Bram Moolenaar071d4272004-06-13 20:20:40 +00003459 extern int _fmode;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003460# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003461
Bram Moolenaar0f873732019-12-05 20:28:46 +01003462 // Silently handle invalid parameters to CRT functions
Bram Moolenaard32a99a2010-09-21 17:29:23 +02003463 SET_INVALID_PARAM_HANDLER;
3464
Bram Moolenaar0f873732019-12-05 20:28:46 +01003465 // Let critical errors result in a failure, not in a dialog box. Required
3466 // for the timestamp test to work on removed floppies.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003467 SetErrorMode(SEM_FAILCRITICALERRORS);
3468
Bram Moolenaar0f873732019-12-05 20:28:46 +01003469 _fmode = O_BINARY; // we do our own CR-LF translation
Bram Moolenaar071d4272004-06-13 20:20:40 +00003470 out_flush();
3471
Bram Moolenaar0f873732019-12-05 20:28:46 +01003472 // Obtain handles for the standard Console I/O devices
Bram Moolenaar071d4272004-06-13 20:20:40 +00003473 if (read_cmd_fd == 0)
3474 g_hConIn = GetStdHandle(STD_INPUT_HANDLE);
3475 else
3476 create_conin();
3477 g_hConOut = GetStdHandle(STD_OUTPUT_HANDLE);
3478
Christopher Plewright38804d62022-11-09 23:55:52 +00003479 wt_init();
3480 vtp_flag_init();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003481# ifdef FEAT_RESTORE_ORIG_SCREEN
Bram Moolenaar0f873732019-12-05 20:28:46 +01003482 // Save the initial console buffer for later restoration
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003483 SaveConsoleBuffer(&g_cbOrig);
3484 g_attrCurrent = g_attrDefault = g_cbOrig.Info.wAttributes;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003485# else
Bram Moolenaar0f873732019-12-05 20:28:46 +01003486 // Get current text attributes
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01003487 GetConsoleScreenBufferInfo(g_hConOut, &csbi);
3488 g_attrCurrent = g_attrDefault = csbi.wAttributes;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003489# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003490 if (cterm_normal_fg_color == 0)
3491 cterm_normal_fg_color = (g_attrCurrent & 0xf) + 1;
3492 if (cterm_normal_bg_color == 0)
3493 cterm_normal_bg_color = ((g_attrCurrent >> 4) & 0xf) + 1;
3494
Bram Moolenaarbdace832019-03-02 10:13:42 +01003495 // Fg and Bg color index number at startup
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02003496 g_color_index_fg = g_attrDefault & 0xf;
3497 g_color_index_bg = (g_attrDefault >> 4) & 0xf;
3498
Bram Moolenaar0f873732019-12-05 20:28:46 +01003499 // set termcap codes to current text attributes
Bram Moolenaar071d4272004-06-13 20:20:40 +00003500 update_tcap(g_attrCurrent);
3501
3502 GetConsoleCursorInfo(g_hConOut, &g_cci);
3503 GetConsoleMode(g_hConIn, &g_cmodein);
3504 GetConsoleMode(g_hConOut, &g_cmodeout);
3505
Bram Moolenaar071d4272004-06-13 20:20:40 +00003506 SaveConsoleTitleAndIcon();
3507 /*
3508 * Set both the small and big icons of the console window to Vim's icon.
3509 * Note that Vim presently only has one size of icon (32x32), but it
3510 * automatically gets scaled down to 16x16 when setting the small icon.
3511 */
3512 if (g_fCanChangeIcon)
3513 SetConsoleIcon(g_hWnd, g_hVimIcon, g_hVimIcon);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003514
3515 ui_get_shellsize();
3516
Christopher Plewrightd343c602023-01-22 18:58:30 +00003517 vtp_init();
Christopher Plewrightf75a2cb2023-01-28 10:28:09 +00003518 // Switch to a new alternate screen buffer.
3519 if (use_alternate_screen_buffer)
3520 vtp_printf("\033[?1049h");
Christopher Plewrightd343c602023-01-22 18:58:30 +00003521
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003522# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00003523 fdDump = fopen("dump", "wt");
3524
3525 if (fdDump)
3526 {
3527 time_t t;
3528
3529 time(&t);
3530 fputs(ctime(&t), fdDump);
3531 fflush(fdDump);
3532 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003533# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003534
3535 g_fWindInitCalled = TRUE;
3536
Bram Moolenaar071d4272004-06-13 20:20:40 +00003537 g_fMouseAvail = GetSystemMetrics(SM_MOUSEPRESENT);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003538
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003539# ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01003540 win_clip_init();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003541# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003542}
3543
3544/*
3545 * non-GUI version of mch_exit().
3546 * Shut down and exit with status `r'
3547 * Careful: mch_exit() may be called before mch_init()!
3548 */
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003549 static void
3550mch_exit_c(int r)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003551{
Bram Moolenaar955f1982017-02-05 15:10:51 +01003552 exiting = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003553
Bram Moolenaarcafafb32018-02-22 21:07:09 +01003554 vtp_exit();
3555
Bram Moolenaar955f1982017-02-05 15:10:51 +01003556 stoptermcap();
Bram Moolenaar071d4272004-06-13 20:20:40 +00003557 if (g_fWindInitCalled)
3558 settmode(TMODE_COOK);
3559
Bram Moolenaar0f873732019-12-05 20:28:46 +01003560 ml_close_all(TRUE); // remove all memfiles
Bram Moolenaar071d4272004-06-13 20:20:40 +00003561
3562 if (g_fWindInitCalled)
3563 {
Bram Moolenaar40385db2018-08-07 22:31:44 +02003564 mch_restore_title(SAVE_RESTORE_BOTH);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003565 /*
3566 * Restore both the small and big icons of the console window to
3567 * what they were at startup. Don't do this when the window is
3568 * closed, Vim would hang here.
3569 */
3570 if (g_fCanChangeIcon && !g_fForceExit)
3571 SetConsoleIcon(g_hWnd, g_hOrigIconSmall, g_hOrigIcon);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003572
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003573# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00003574 if (fdDump)
3575 {
3576 time_t t;
3577
3578 time(&t);
3579 fputs(ctime(&t), fdDump);
3580 fclose(fdDump);
3581 }
3582 fdDump = NULL;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003583# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003584 }
3585
3586 SetConsoleCursorInfo(g_hConOut, &g_cci);
Wez Furlong6ef5ab52021-05-30 19:29:41 +02003587 SetConsoleMode(g_hConIn, g_cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003588 SetConsoleMode(g_hConOut, g_cmodeout);
3589
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003590# ifdef DYNAMIC_GETTEXT
Bram Moolenaar071d4272004-06-13 20:20:40 +00003591 dyn_libintl_end();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003592# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003593
3594 exit(r);
3595}
Bram Moolenaar0f873732019-12-05 20:28:46 +01003596#endif // !FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00003597
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003598 void
3599mch_init(void)
3600{
3601#ifdef VIMDLL
3602 if (gui.starting)
3603 mch_init_g();
3604 else
3605 mch_init_c();
3606#elif defined(FEAT_GUI_MSWIN)
3607 mch_init_g();
3608#else
3609 mch_init_c();
3610#endif
3611}
3612
3613 void
3614mch_exit(int r)
3615{
Bram Moolenaar173d8412020-04-19 14:02:26 +02003616#ifdef FEAT_NETBEANS_INTG
3617 netbeans_send_disconnect();
3618#endif
3619
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003620#ifdef VIMDLL
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02003621 if (gui.in_use || gui.starting)
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003622 mch_exit_g(r);
3623 else
3624 mch_exit_c(r);
3625#elif defined(FEAT_GUI_MSWIN)
3626 mch_exit_g(r);
3627#else
3628 mch_exit_c(r);
3629#endif
3630}
3631
Bram Moolenaar071d4272004-06-13 20:20:40 +00003632/*
3633 * Do we have an interactive window?
3634 */
3635 int
3636mch_check_win(
Bram Moolenaar1266d672017-02-01 13:43:36 +01003637 int argc UNUSED,
3638 char **argv UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003639{
K.Takatace3189d2023-02-15 19:13:43 +00003640 mch_get_exe_name();
Bram Moolenaar071d4272004-06-13 20:20:40 +00003641
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003642#if defined(FEAT_GUI_MSWIN) && !defined(VIMDLL)
Bram Moolenaar0f873732019-12-05 20:28:46 +01003643 return OK; // GUI always has a tty
Bram Moolenaar071d4272004-06-13 20:20:40 +00003644#else
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003645# ifdef VIMDLL
3646 if (gui.in_use)
3647 return OK;
3648# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003649 if (isatty(1))
3650 return OK;
3651 return FAIL;
3652#endif
3653}
3654
Bram Moolenaar65f04f62013-08-30 17:29:16 +02003655/*
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003656 * Set the case of the file name, if it already exists.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003657 * When "len" is > 0, also expand short to long filenames.
3658 */
3659 void
3660fname_case(
3661 char_u *name,
3662 int len)
3663{
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003664 int flen;
3665 WCHAR *p;
3666 WCHAR buf[_MAX_PATH + 1];
Bram Moolenaar071d4272004-06-13 20:20:40 +00003667
Bram Moolenaara3ffd9c2005-07-21 21:03:15 +00003668 flen = (int)STRLEN(name);
Bram Moolenaar65f04f62013-08-30 17:29:16 +02003669 if (flen == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003670 return;
3671
3672 slash_adjust(name);
3673
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003674 p = enc_to_utf16(name, NULL);
3675 if (p == NULL)
Bram Moolenaar65f04f62013-08-30 17:29:16 +02003676 return;
3677
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003678 if (GetLongPathNameW(p, buf, _MAX_PATH))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003679 {
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003680 char_u *q = utf16_to_enc(buf, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003681
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003682 if (q != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003683 {
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003684 if (len > 0 || flen >= (int)STRLEN(q))
3685 vim_strncpy(name, q, (len > 0) ? len - 1 : flen);
3686 vim_free(q);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003687 }
3688 }
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003689 vim_free(p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003690}
3691
3692
3693/*
3694 * Insert user name in s[len].
3695 */
3696 int
3697mch_get_user_name(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003698 char_u *s,
3699 int len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003700{
Bram Moolenaar0f873732019-12-05 20:28:46 +01003701 WCHAR wszUserName[256 + 1]; // UNLEN is 256
K.Takataeeec2542021-06-02 13:28:16 +02003702 DWORD wcch = ARRAY_LENGTH(wszUserName);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003703
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003704 if (GetUserNameW(wszUserName, &wcch))
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003705 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003706 char_u *p = utf16_to_enc(wszUserName, NULL);
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003707
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003708 if (p != NULL)
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003709 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003710 vim_strncpy(s, p, len - 1);
3711 vim_free(p);
3712 return OK;
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003713 }
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003714 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003715 s[0] = NUL;
3716 return FAIL;
3717}
3718
3719
3720/*
3721 * Insert host name in s[len].
3722 */
3723 void
3724mch_get_host_name(
3725 char_u *s,
3726 int len)
3727{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003728 WCHAR wszHostName[256 + 1];
K.Takataeeec2542021-06-02 13:28:16 +02003729 DWORD wcch = ARRAY_LENGTH(wszHostName);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003730
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00003731 if (!GetComputerNameW(wszHostName, &wcch))
3732 return;
Bram Moolenaar2cc87382013-12-11 18:21:45 +01003733
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00003734 char_u *p = utf16_to_enc(wszHostName, NULL);
3735 if (p == NULL)
3736 return;
3737
3738 vim_strncpy(s, p, len - 1);
3739 vim_free(p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003740}
3741
3742
3743/*
3744 * return process ID
3745 */
3746 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003747mch_get_pid(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003748{
3749 return (long)GetCurrentProcessId();
3750}
3751
Bram Moolenaar67cf86b2019-04-28 22:25:38 +02003752/*
3753 * return TRUE if process "pid" is still running
3754 */
3755 int
Bram Moolenaar1b243ea2019-04-28 22:50:40 +02003756mch_process_running(long pid)
Bram Moolenaar67cf86b2019-04-28 22:25:38 +02003757{
3758 HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION, 0, (DWORD)pid);
3759 DWORD status = 0;
3760 int ret = FALSE;
3761
3762 if (hProcess == NULL)
3763 return FALSE; // might not have access
3764 if (GetExitCodeProcess(hProcess, &status) )
3765 ret = status == STILL_ACTIVE;
3766 CloseHandle(hProcess);
3767 return ret;
3768}
Bram Moolenaar071d4272004-06-13 20:20:40 +00003769
3770/*
3771 * Get name of current directory into buffer 'buf' of length 'len' bytes.
3772 * Return OK for success, FAIL for failure.
3773 */
3774 int
3775mch_dirname(
3776 char_u *buf,
3777 int len)
3778{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003779 WCHAR wbuf[_MAX_PATH + 1];
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02003780
Bram Moolenaar071d4272004-06-13 20:20:40 +00003781 /*
3782 * Originally this was:
3783 * return (getcwd(buf, len) != NULL ? OK : FAIL);
3784 * But the Win32s known bug list says that getcwd() doesn't work
3785 * so use the Win32 system call instead. <Negri>
3786 */
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00003787 if (GetCurrentDirectoryW(_MAX_PATH, wbuf) == 0)
3788 return FAIL;
3789
3790 WCHAR wcbuf[_MAX_PATH + 1];
3791 char_u *p = NULL;
3792
3793 if (GetLongPathNameW(wbuf, wcbuf, _MAX_PATH) != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003794 {
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00003795 p = utf16_to_enc(wcbuf, NULL);
3796 if (STRLEN(p) >= (size_t)len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003797 {
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00003798 // long path name is too long, fall back to short one
Yegappan Lakshmanan960dcbd2023-03-07 17:45:11 +00003799 VIM_CLEAR(p);
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003800 }
3801 }
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00003802 if (p == NULL)
3803 p = utf16_to_enc(wbuf, NULL);
3804
3805 if (p == NULL)
3806 return FAIL;
3807
3808 vim_strncpy(buf, p, len - 1);
3809 vim_free(p);
3810 return OK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003811}
3812
3813/*
Bram Moolenaarffa22202013-11-21 12:34:11 +01003814 * Get file permissions for "name".
3815 * Return mode_t or -1 for error.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003816 */
3817 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003818mch_getperm(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003819{
Bram Moolenaar8767f522016-07-01 17:17:39 +02003820 stat_T st;
Bram Moolenaarffa22202013-11-21 12:34:11 +01003821 int n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003822
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003823 n = mch_stat((char *)name, &st);
Bram Moolenaar78cf3f02014-01-10 18:16:07 +01003824 return n == 0 ? (long)(unsigned short)st.st_mode : -1L;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003825}
3826
3827
3828/*
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003829 * Set file permission for "name" to "perm".
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003830 *
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003831 * Return FAIL for failure, OK otherwise.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003832 */
3833 int
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003834mch_setperm(char_u *name, long perm)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003835{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003836 long n;
3837 WCHAR *p;
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003838
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003839 p = enc_to_utf16(name, NULL);
3840 if (p == NULL)
3841 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003842
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003843 n = _wchmod(p, perm);
3844 vim_free(p);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003845 if (n == -1)
3846 return FAIL;
3847
3848 win32_set_archive(name);
3849
3850 return OK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003851}
3852
3853/*
3854 * Set hidden flag for "name".
3855 */
3856 void
3857mch_hide(char_u *name)
3858{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003859 int attrs = win32_getattrs(name);
3860 if (attrs == -1)
3861 return;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003862
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003863 attrs |= FILE_ATTRIBUTE_HIDDEN;
3864 win32_setattrs(name, attrs);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003865}
3866
3867/*
Bram Moolenaar8a52ba72015-11-02 14:45:56 +01003868 * Return TRUE if file "name" exists and is hidden.
3869 */
3870 int
3871mch_ishidden(char_u *name)
3872{
3873 int f = win32_getattrs(name);
3874
3875 if (f == -1)
Bram Moolenaar0f873732019-12-05 20:28:46 +01003876 return FALSE; // file does not exist at all
Bram Moolenaar8a52ba72015-11-02 14:45:56 +01003877
3878 return (f & FILE_ATTRIBUTE_HIDDEN) != 0;
3879}
3880
3881/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003882 * return TRUE if "name" is a directory
3883 * return FALSE if "name" is not a directory or upon error
3884 */
3885 int
3886mch_isdir(char_u *name)
3887{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003888 int f = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003889
3890 if (f == -1)
Bram Moolenaar0f873732019-12-05 20:28:46 +01003891 return FALSE; // file does not exist at all
Bram Moolenaar071d4272004-06-13 20:20:40 +00003892
3893 return (f & FILE_ATTRIBUTE_DIRECTORY) != 0;
3894}
3895
3896/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01003897 * return TRUE if "name" is a directory, NOT a symlink to a directory
3898 * return FALSE if "name" is not a directory
3899 * return FALSE for error
3900 */
3901 int
3902mch_isrealdir(char_u *name)
3903{
3904 return mch_isdir(name) && !mch_is_symbolic_link(name);
3905}
3906
3907/*
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003908 * Create directory "name".
3909 * Return 0 on success, -1 on error.
3910 */
3911 int
3912mch_mkdir(char_u *name)
3913{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003914 WCHAR *p;
3915 int retval;
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003916
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003917 p = enc_to_utf16(name, NULL);
3918 if (p == NULL)
3919 return -1;
3920 retval = _wmkdir(p);
3921 vim_free(p);
3922 return retval;
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003923}
3924
3925/*
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003926 * Delete directory "name".
3927 * Return 0 on success, -1 on error.
3928 */
3929 int
3930mch_rmdir(char_u *name)
3931{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003932 WCHAR *p;
3933 int retval;
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003934
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003935 p = enc_to_utf16(name, NULL);
3936 if (p == NULL)
3937 return -1;
3938 retval = _wrmdir(p);
3939 vim_free(p);
3940 return retval;
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003941}
3942
3943/*
Bram Moolenaar03f48552006-02-28 23:52:23 +00003944 * Return TRUE if file "fname" has more than one link.
3945 */
3946 int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003947mch_is_hard_link(char_u *fname)
Bram Moolenaar03f48552006-02-28 23:52:23 +00003948{
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003949 BY_HANDLE_FILE_INFORMATION info;
3950
3951 return win32_fileinfo(fname, &info) == FILEINFO_OK
3952 && info.nNumberOfLinks > 1;
3953}
3954
3955/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01003956 * Return TRUE if "name" is a symbolic link (or a junction).
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003957 */
3958 int
Bram Moolenaar203258c2016-01-17 22:15:16 +01003959mch_is_symbolic_link(char_u *name)
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003960{
3961 HANDLE hFind;
3962 int res = FALSE;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003963 DWORD fileFlags = 0, reparseTag = 0;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003964 WCHAR *wn;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003965 WIN32_FIND_DATAW findDataW;
3966
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003967 wn = enc_to_utf16(name, NULL);
3968 if (wn == NULL)
3969 return FALSE;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003970
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003971 hFind = FindFirstFileW(wn, &findDataW);
3972 vim_free(wn);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003973 if (hFind != INVALID_HANDLE_VALUE)
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003974 {
3975 fileFlags = findDataW.dwFileAttributes;
3976 reparseTag = findDataW.dwReserved0;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003977 FindClose(hFind);
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003978 }
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003979
3980 if ((fileFlags & FILE_ATTRIBUTE_REPARSE_POINT)
Bram Moolenaar203258c2016-01-17 22:15:16 +01003981 && (reparseTag == IO_REPARSE_TAG_SYMLINK
3982 || reparseTag == IO_REPARSE_TAG_MOUNT_POINT))
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003983 res = TRUE;
3984
3985 return res;
3986}
3987
3988/*
3989 * Return TRUE if file "fname" has more than one link or if it is a symbolic
3990 * link.
3991 */
3992 int
3993mch_is_linked(char_u *fname)
3994{
3995 if (mch_is_hard_link(fname) || mch_is_symbolic_link(fname))
3996 return TRUE;
3997 return FALSE;
3998}
3999
4000/*
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02004001 * Get the by-handle-file-information for "fname".
4002 * Returns FILEINFO_OK when OK.
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004003 * Returns FILEINFO_ENC_FAIL when enc_to_utf16() failed.
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02004004 * Returns FILEINFO_READ_FAIL when CreateFile() failed.
4005 * Returns FILEINFO_INFO_FAIL when GetFileInformationByHandle() failed.
4006 */
4007 int
4008win32_fileinfo(char_u *fname, BY_HANDLE_FILE_INFORMATION *info)
4009{
Bram Moolenaar03f48552006-02-28 23:52:23 +00004010 HANDLE hFile;
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02004011 int res = FILEINFO_READ_FAIL;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004012 WCHAR *wn;
Bram Moolenaar03f48552006-02-28 23:52:23 +00004013
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004014 wn = enc_to_utf16(fname, NULL);
4015 if (wn == NULL)
4016 return FILEINFO_ENC_FAIL;
4017
4018 hFile = CreateFileW(wn, // file name
4019 GENERIC_READ, // access mode
4020 FILE_SHARE_READ | FILE_SHARE_WRITE, // share mode
4021 NULL, // security descriptor
4022 OPEN_EXISTING, // creation disposition
4023 FILE_FLAG_BACKUP_SEMANTICS, // file attributes
4024 NULL); // handle to template file
4025 vim_free(wn);
Bram Moolenaar03f48552006-02-28 23:52:23 +00004026
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00004027 if (hFile == INVALID_HANDLE_VALUE)
4028 return FILEINFO_READ_FAIL;
4029
4030 if (GetFileInformationByHandle(hFile, info) != 0)
4031 res = FILEINFO_OK;
4032 else
4033 res = FILEINFO_INFO_FAIL;
4034 CloseHandle(hFile);
Bram Moolenaar03f48552006-02-28 23:52:23 +00004035
Bram Moolenaar03f48552006-02-28 23:52:23 +00004036 return res;
4037}
4038
4039/*
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004040 * get file attributes for `name'
4041 * -1 : error
4042 * else FILE_ATTRIBUTE_* defined in winnt.h
4043 */
Bram Moolenaarffa22202013-11-21 12:34:11 +01004044 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004045win32_getattrs(char_u *name)
4046{
4047 int attr;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004048 WCHAR *p;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004049
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004050 p = enc_to_utf16(name, NULL);
4051 if (p == NULL)
4052 return INVALID_FILE_ATTRIBUTES;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004053
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004054 attr = GetFileAttributesW(p);
4055 vim_free(p);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004056
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004057 return attr;
4058}
4059
4060/*
4061 * set file attributes for `name' to `attrs'
4062 *
4063 * return -1 for failure, 0 otherwise
4064 */
Bram Moolenaar6dff58f2018-09-30 21:43:26 +02004065 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004066win32_setattrs(char_u *name, int attrs)
4067{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004068 int res;
4069 WCHAR *p;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004070
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004071 p = enc_to_utf16(name, NULL);
4072 if (p == NULL)
4073 return -1;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004074
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004075 res = SetFileAttributesW(p, attrs);
4076 vim_free(p);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004077
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004078 return res ? 0 : -1;
4079}
4080
4081/*
4082 * Set archive flag for "name".
4083 */
Bram Moolenaar6dff58f2018-09-30 21:43:26 +02004084 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004085win32_set_archive(char_u *name)
4086{
4087 int attrs = win32_getattrs(name);
4088 if (attrs == -1)
4089 return -1;
4090
4091 attrs |= FILE_ATTRIBUTE_ARCHIVE;
4092 return win32_setattrs(name, attrs);
4093}
4094
4095/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00004096 * Return TRUE if file or directory "name" is writable (not readonly).
4097 * Strange semantics of Win32: a readonly directory is writable, but you can't
4098 * delete a file. Let's say this means it is writable.
4099 */
4100 int
4101mch_writable(char_u *name)
4102{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004103 int attrs = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004104
Bram Moolenaar12b559e2013-06-12 22:41:37 +02004105 return (attrs != -1 && (!(attrs & FILE_ATTRIBUTE_READONLY)
4106 || (attrs & FILE_ATTRIBUTE_DIRECTORY)));
Bram Moolenaar071d4272004-06-13 20:20:40 +00004107}
4108
Bram Moolenaar071d4272004-06-13 20:20:40 +00004109/*
Bram Moolenaar43663192017-03-05 14:29:12 +01004110 * Return TRUE if "name" can be executed, FALSE if not.
Bram Moolenaar77b77102015-03-21 22:18:41 +01004111 * If "use_path" is FALSE only check if "name" is executable.
Bram Moolenaar43663192017-03-05 14:29:12 +01004112 * When returning TRUE and "path" is not NULL save the path and set "*path" to
4113 * the allocated memory.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004114 */
4115 int
Yegappan Lakshmananebb01bd2022-06-08 15:14:09 +01004116mch_can_exe(char_u *name, char_u **path, int use_path UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004117{
Bram Moolenaar95da1362020-05-30 18:37:55 +02004118 return executable_exists((char *)name, path, TRUE, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004119}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004120
4121/*
4122 * Check what "name" is:
4123 * NODE_NORMAL: file or directory (or doesn't exist)
4124 * NODE_WRITABLE: writable device, socket, fifo, etc.
4125 * NODE_OTHER: non-writable things
4126 */
4127 int
4128mch_nodetype(char_u *name)
4129{
4130 HANDLE hFile;
4131 int type;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004132 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004133
Bram Moolenaar0f873732019-12-05 20:28:46 +01004134 // We can't open a file with a name "\\.\con" or "\\.\prn" and trying to
4135 // read from it later will cause Vim to hang. Thus return NODE_WRITABLE
4136 // here.
Bram Moolenaar043545e2006-10-10 16:44:07 +00004137 if (STRNCMP(name, "\\\\.\\", 4) == 0)
4138 return NODE_WRITABLE;
4139
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004140 wn = enc_to_utf16(name, NULL);
4141 if (wn == NULL)
4142 return NODE_NORMAL;
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004143
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004144 hFile = CreateFileW(wn, // file name
4145 GENERIC_WRITE, // access mode
4146 0, // share mode
4147 NULL, // security descriptor
4148 OPEN_EXISTING, // creation disposition
4149 0, // file attributes
4150 NULL); // handle to template file
4151 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004152 if (hFile == INVALID_HANDLE_VALUE)
4153 return NODE_NORMAL;
4154
4155 type = GetFileType(hFile);
4156 CloseHandle(hFile);
4157 if (type == FILE_TYPE_CHAR)
4158 return NODE_WRITABLE;
4159 if (type == FILE_TYPE_DISK)
4160 return NODE_NORMAL;
4161 return NODE_OTHER;
4162}
4163
4164#ifdef HAVE_ACL
4165struct my_acl
4166{
4167 PSECURITY_DESCRIPTOR pSecurityDescriptor;
4168 PSID pSidOwner;
4169 PSID pSidGroup;
4170 PACL pDacl;
4171 PACL pSacl;
4172};
4173#endif
4174
4175/*
4176 * Return a pointer to the ACL of file "fname" in allocated memory.
4177 * Return NULL if the ACL is not available for whatever reason.
4178 */
4179 vim_acl_T
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004180mch_get_acl(char_u *fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004181{
4182#ifndef HAVE_ACL
4183 return (vim_acl_T)NULL;
4184#else
4185 struct my_acl *p = NULL;
Bram Moolenaar27515922013-06-29 15:36:26 +02004186 DWORD err;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004187
Bram Moolenaarc799fe22019-05-28 23:08:19 +02004188 p = ALLOC_CLEAR_ONE(struct my_acl);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004189 if (p != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004190 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004191 WCHAR *wn;
Bram Moolenaar27515922013-06-29 15:36:26 +02004192
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004193 wn = enc_to_utf16(fname, NULL);
4194 if (wn == NULL)
Bram Moolenaarbbf9f342020-11-10 22:03:40 +01004195 {
4196 vim_free(p);
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004197 return NULL;
Bram Moolenaarbbf9f342020-11-10 22:03:40 +01004198 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004199
4200 // Try to retrieve the entire security descriptor.
4201 err = GetNamedSecurityInfoW(
4202 wn, // Abstract filename
4203 SE_FILE_OBJECT, // File Object
4204 OWNER_SECURITY_INFORMATION |
4205 GROUP_SECURITY_INFORMATION |
4206 DACL_SECURITY_INFORMATION |
4207 SACL_SECURITY_INFORMATION,
4208 &p->pSidOwner, // Ownership information.
4209 &p->pSidGroup, // Group membership.
4210 &p->pDacl, // Discretionary information.
4211 &p->pSacl, // For auditing purposes.
4212 &p->pSecurityDescriptor);
4213 if (err == ERROR_ACCESS_DENIED ||
4214 err == ERROR_PRIVILEGE_NOT_HELD)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004215 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004216 // Retrieve only DACL.
4217 (void)GetNamedSecurityInfoW(
4218 wn,
4219 SE_FILE_OBJECT,
4220 DACL_SECURITY_INFORMATION,
4221 NULL,
4222 NULL,
4223 &p->pDacl,
4224 NULL,
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004225 &p->pSecurityDescriptor);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004226 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004227 if (p->pSecurityDescriptor == NULL)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004228 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004229 mch_free_acl((vim_acl_T)p);
4230 p = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004231 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004232 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004233 }
4234
4235 return (vim_acl_T)p;
4236#endif
4237}
4238
Bram Moolenaar27515922013-06-29 15:36:26 +02004239#ifdef HAVE_ACL
4240/*
4241 * Check if "acl" contains inherited ACE.
4242 */
4243 static BOOL
4244is_acl_inherited(PACL acl)
4245{
4246 DWORD i;
4247 ACL_SIZE_INFORMATION acl_info;
4248 PACCESS_ALLOWED_ACE ace;
4249
4250 acl_info.AceCount = 0;
4251 GetAclInformation(acl, &acl_info, sizeof(acl_info), AclSizeInformation);
4252 for (i = 0; i < acl_info.AceCount; i++)
4253 {
4254 GetAce(acl, i, (LPVOID *)&ace);
4255 if (ace->Header.AceFlags & INHERITED_ACE)
4256 return TRUE;
4257 }
4258 return FALSE;
4259}
4260#endif
4261
Bram Moolenaar071d4272004-06-13 20:20:40 +00004262/*
4263 * Set the ACL of file "fname" to "acl" (unless it's NULL).
4264 * Errors are ignored.
4265 * This must only be called with "acl" equal to what mch_get_acl() returned.
4266 */
4267 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004268mch_set_acl(char_u *fname, vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004269{
4270#ifdef HAVE_ACL
4271 struct my_acl *p = (struct my_acl *)acl;
Bram Moolenaar27515922013-06-29 15:36:26 +02004272 SECURITY_INFORMATION sec_info = 0;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004273 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004274
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004275 if (p == NULL)
4276 return;
4277
4278 wn = enc_to_utf16(fname, NULL);
4279 if (wn == NULL)
4280 return;
4281
4282 // Set security flags
4283 if (p->pSidOwner)
4284 sec_info |= OWNER_SECURITY_INFORMATION;
4285 if (p->pSidGroup)
4286 sec_info |= GROUP_SECURITY_INFORMATION;
4287 if (p->pDacl)
Bram Moolenaar27515922013-06-29 15:36:26 +02004288 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004289 sec_info |= DACL_SECURITY_INFORMATION;
4290 // Do not inherit its parent's DACL.
4291 // If the DACL is inherited, Cygwin permissions would be changed.
4292 if (!is_acl_inherited(p->pDacl))
4293 sec_info |= PROTECTED_DACL_SECURITY_INFORMATION;
Bram Moolenaar27515922013-06-29 15:36:26 +02004294 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004295 if (p->pSacl)
4296 sec_info |= SACL_SECURITY_INFORMATION;
4297
4298 (void)SetNamedSecurityInfoW(
4299 wn, // Abstract filename
4300 SE_FILE_OBJECT, // File Object
4301 sec_info,
4302 p->pSidOwner, // Ownership information.
4303 p->pSidGroup, // Group membership.
4304 p->pDacl, // Discretionary information.
4305 p->pSacl // For auditing purposes.
4306 );
4307 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004308#endif
4309}
4310
4311 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004312mch_free_acl(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;
4316
4317 if (p != NULL)
4318 {
4319 LocalFree(p->pSecurityDescriptor); // Free the memory just in case
4320 vim_free(p);
4321 }
4322#endif
4323}
4324
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004325#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004326
4327/*
4328 * handler for ctrl-break, ctrl-c interrupts, and fatal events.
4329 */
4330 static BOOL WINAPI
4331handler_routine(
4332 DWORD dwCtrlType)
4333{
Bram Moolenaar589b1102017-08-12 16:39:05 +02004334 INPUT_RECORD ir;
4335 DWORD out;
4336
Bram Moolenaar071d4272004-06-13 20:20:40 +00004337 switch (dwCtrlType)
4338 {
4339 case CTRL_C_EVENT:
4340 if (ctrl_c_interrupts)
4341 g_fCtrlCPressed = TRUE;
4342 return TRUE;
4343
4344 case CTRL_BREAK_EVENT:
4345 g_fCBrkPressed = TRUE;
Bram Moolenaar589b1102017-08-12 16:39:05 +02004346 ctrl_break_was_pressed = TRUE;
Bram Moolenaar0f873732019-12-05 20:28:46 +01004347 // ReadConsoleInput is blocking, send a key event to continue.
Bram Moolenaar589b1102017-08-12 16:39:05 +02004348 ir.EventType = KEY_EVENT;
4349 ir.Event.KeyEvent.bKeyDown = TRUE;
4350 ir.Event.KeyEvent.wRepeatCount = 1;
4351 ir.Event.KeyEvent.wVirtualKeyCode = VK_CANCEL;
4352 ir.Event.KeyEvent.wVirtualScanCode = 0;
4353 ir.Event.KeyEvent.dwControlKeyState = 0;
4354 ir.Event.KeyEvent.uChar.UnicodeChar = 0;
4355 WriteConsoleInput(g_hConIn, &ir, 1, &out);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004356 return TRUE;
4357
Bram Moolenaar0f873732019-12-05 20:28:46 +01004358 // fatal events: shut down gracefully
Bram Moolenaar071d4272004-06-13 20:20:40 +00004359 case CTRL_CLOSE_EVENT:
4360 case CTRL_LOGOFF_EVENT:
4361 case CTRL_SHUTDOWN_EVENT:
4362 windgoto((int)Rows - 1, 0);
4363 g_fForceExit = TRUE;
4364
Bram Moolenaar0fde2902008-03-16 13:54:13 +00004365 vim_snprintf((char *)IObuff, IOSIZE, _("Vim: Caught %s event\n"),
Bram Moolenaar071d4272004-06-13 20:20:40 +00004366 (dwCtrlType == CTRL_CLOSE_EVENT
4367 ? _("close")
4368 : dwCtrlType == CTRL_LOGOFF_EVENT
4369 ? _("logoff")
4370 : _("shutdown")));
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004371# ifdef DEBUG
Bram Moolenaar071d4272004-06-13 20:20:40 +00004372 OutputDebugString(IObuff);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004373# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004374
Bram Moolenaar0f873732019-12-05 20:28:46 +01004375 preserve_exit(); // output IObuff, preserve files and exit
Bram Moolenaar071d4272004-06-13 20:20:40 +00004376
Bram Moolenaar0f873732019-12-05 20:28:46 +01004377 return TRUE; // not reached
Bram Moolenaar071d4272004-06-13 20:20:40 +00004378
4379 default:
4380 return FALSE;
4381 }
4382}
4383
4384
4385/*
4386 * set the tty in (raw) ? "raw" : "cooked" mode
4387 */
4388 void
Bram Moolenaar26e86442020-05-17 14:06:16 +02004389mch_settmode(tmode_T tmode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004390{
4391 DWORD cmodein;
4392 DWORD cmodeout;
4393 BOOL bEnableHandler;
4394
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004395# ifdef VIMDLL
4396 if (gui.in_use)
4397 return;
4398# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004399 GetConsoleMode(g_hConIn, &cmodein);
4400 GetConsoleMode(g_hConOut, &cmodeout);
4401 if (tmode == TMODE_RAW)
4402 {
4403 cmodein &= ~(ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
4404 ENABLE_ECHO_INPUT);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004405 if (g_fMouseActive)
Wez Furlong6ef5ab52021-05-30 19:29:41 +02004406 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00004407 cmodein |= ENABLE_MOUSE_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02004408 cmodein &= ~ENABLE_QUICK_EDIT_MODE;
4409 }
4410 else
4411 {
4412 cmodein |= g_cmodein & ENABLE_QUICK_EDIT_MODE;
4413 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01004414 cmodeout &= ~(
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004415# ifdef FEAT_TERMGUICOLORS
Bram Moolenaar0f873732019-12-05 20:28:46 +01004416 // Do not turn off the ENABLE_PROCESSED_OUTPUT flag when using
4417 // VTP.
Bram Moolenaarcafafb32018-02-22 21:07:09 +01004418 ((vtp_working) ? 0 : ENABLE_PROCESSED_OUTPUT) |
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004419# else
Bram Moolenaarcafafb32018-02-22 21:07:09 +01004420 ENABLE_PROCESSED_OUTPUT |
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004421# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01004422 ENABLE_WRAP_AT_EOL_OUTPUT);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004423 bEnableHandler = TRUE;
4424 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01004425 else // cooked
Bram Moolenaar071d4272004-06-13 20:20:40 +00004426 {
4427 cmodein |= (ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
4428 ENABLE_ECHO_INPUT);
4429 cmodeout |= (ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
4430 bEnableHandler = FALSE;
4431 }
Wez Furlong6ef5ab52021-05-30 19:29:41 +02004432 SetConsoleMode(g_hConIn, cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004433 SetConsoleMode(g_hConOut, cmodeout);
4434 SetConsoleCtrlHandler(handler_routine, bEnableHandler);
4435
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004436# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00004437 if (fdDump)
4438 {
4439 fprintf(fdDump, "mch_settmode(%s, in = %x, out = %x)\n",
4440 tmode == TMODE_RAW ? "raw" :
4441 tmode == TMODE_COOK ? "cooked" : "normal",
4442 cmodein, cmodeout);
4443 fflush(fdDump);
4444 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004445# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004446}
4447
4448
4449/*
4450 * Get the size of the current window in `Rows' and `Columns'
4451 * Return OK when size could be determined, FAIL otherwise.
4452 */
4453 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004454mch_get_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004455{
4456 CONSOLE_SCREEN_BUFFER_INFO csbi;
4457
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004458# ifdef VIMDLL
4459 if (gui.in_use)
4460 return OK;
4461# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004462 if (!g_fTermcapMode && g_cbTermcap.IsValid)
4463 {
4464 /*
4465 * For some reason, we are trying to get the screen dimensions
4466 * even though we are not in termcap mode. The 'Rows' and 'Columns'
4467 * variables are really intended to mean the size of Vim screen
4468 * while in termcap mode.
4469 */
4470 Rows = g_cbTermcap.Info.dwSize.Y;
4471 Columns = g_cbTermcap.Info.dwSize.X;
4472 }
4473 else if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
4474 {
4475 Rows = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
4476 Columns = csbi.srWindow.Right - csbi.srWindow.Left + 1;
4477 }
4478 else
4479 {
4480 Rows = 25;
4481 Columns = 80;
4482 }
4483 return OK;
4484}
4485
4486/*
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004487 * Resize console buffer to 'COORD'
4488 */
4489 static void
4490ResizeConBuf(
4491 HANDLE hConsole,
4492 COORD coordScreen)
4493{
Christopher Plewrightf75a2cb2023-01-28 10:28:09 +00004494 if (use_alternate_screen_buffer)
4495 return;
4496
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004497 if (!SetConsoleScreenBufferSize(hConsole, coordScreen))
4498 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004499# ifdef MCH_WRITE_DUMP
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004500 if (fdDump)
4501 {
4502 fprintf(fdDump, "SetConsoleScreenBufferSize failed: %lx\n",
4503 GetLastError());
4504 fflush(fdDump);
4505 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004506# endif
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004507 }
4508}
4509
4510/*
4511 * Resize console window size to 'srWindowRect'
4512 */
4513 static void
4514ResizeWindow(
4515 HANDLE hConsole,
4516 SMALL_RECT srWindowRect)
4517{
4518 if (!SetConsoleWindowInfo(hConsole, TRUE, &srWindowRect))
4519 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004520# ifdef MCH_WRITE_DUMP
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004521 if (fdDump)
4522 {
4523 fprintf(fdDump, "SetConsoleWindowInfo failed: %lx\n",
4524 GetLastError());
4525 fflush(fdDump);
4526 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004527# endif
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004528 }
4529}
4530
4531/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00004532 * Set a console window to `xSize' * `ySize'
4533 */
4534 static void
4535ResizeConBufAndWindow(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004536 HANDLE hConsole,
4537 int xSize,
4538 int ySize)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004539{
Bram Moolenaar0f873732019-12-05 20:28:46 +01004540 CONSOLE_SCREEN_BUFFER_INFO csbi; // hold current console buffer info
4541 SMALL_RECT srWindowRect; // hold the new console size
Bram Moolenaar071d4272004-06-13 20:20:40 +00004542 COORD coordScreen;
Bram Moolenaarf49a6922019-07-15 20:37:05 +02004543 COORD cursor;
Bram Moolenaar2551c032018-08-23 22:38:31 +02004544 static int resized = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004545
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004546# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00004547 if (fdDump)
4548 {
4549 fprintf(fdDump, "ResizeConBufAndWindow(%d, %d)\n", xSize, ySize);
4550 fflush(fdDump);
4551 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004552# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004553
Bram Moolenaar0f873732019-12-05 20:28:46 +01004554 // get the largest size we can size the console window to
Bram Moolenaar071d4272004-06-13 20:20:40 +00004555 coordScreen = GetLargestConsoleWindowSize(hConsole);
4556
Bram Moolenaar0f873732019-12-05 20:28:46 +01004557 // define the new console window size and scroll position
Bram Moolenaar071d4272004-06-13 20:20:40 +00004558 srWindowRect.Left = srWindowRect.Top = (SHORT) 0;
4559 srWindowRect.Right = (SHORT) (min(xSize, coordScreen.X) - 1);
4560 srWindowRect.Bottom = (SHORT) (min(ySize, coordScreen.Y) - 1);
4561
4562 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
4563 {
4564 int sx, sy;
4565
4566 sx = csbi.srWindow.Right - csbi.srWindow.Left + 1;
4567 sy = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
4568 if (sy < ySize || sx < xSize)
4569 {
4570 /*
4571 * Increasing number of lines/columns, do buffer first.
4572 * Use the maximal size in x and y direction.
4573 */
4574 if (sy < ySize)
4575 coordScreen.Y = ySize;
4576 else
4577 coordScreen.Y = sy;
4578 if (sx < xSize)
4579 coordScreen.X = xSize;
4580 else
4581 coordScreen.X = sx;
4582 SetConsoleScreenBufferSize(hConsole, coordScreen);
4583 }
4584 }
4585
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004586 // define the new console buffer size
Bram Moolenaar071d4272004-06-13 20:20:40 +00004587 coordScreen.X = xSize;
4588 coordScreen.Y = ySize;
4589
Bram Moolenaar2551c032018-08-23 22:38:31 +02004590 // In the new console call API, only the first time in reverse order
4591 if (!vtp_working || resized)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004592 {
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004593 ResizeWindow(hConsole, srWindowRect);
4594 ResizeConBuf(hConsole, coordScreen);
4595 }
4596 else
4597 {
Bram Moolenaarf49a6922019-07-15 20:37:05 +02004598 // Workaround for a Windows 10 bug
4599 cursor.X = srWindowRect.Left;
4600 cursor.Y = srWindowRect.Top;
4601 SetConsoleCursorPosition(hConsole, cursor);
4602
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004603 ResizeConBuf(hConsole, coordScreen);
4604 ResizeWindow(hConsole, srWindowRect);
Bram Moolenaar2551c032018-08-23 22:38:31 +02004605 resized = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004606 }
4607}
4608
4609
4610/*
4611 * Set the console window to `Rows' * `Columns'
4612 */
4613 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004614mch_set_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004615{
4616 COORD coordScreen;
4617
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004618# ifdef VIMDLL
4619 if (gui.in_use)
4620 return;
4621# endif
Bram Moolenaar0f873732019-12-05 20:28:46 +01004622 // Don't change window size while still starting up
Bram Moolenaar071d4272004-06-13 20:20:40 +00004623 if (suppress_winsize != 0)
4624 {
4625 suppress_winsize = 2;
4626 return;
4627 }
4628
4629 if (term_console)
4630 {
4631 coordScreen = GetLargestConsoleWindowSize(g_hConOut);
4632
Bram Moolenaar0f873732019-12-05 20:28:46 +01004633 // Clamp Rows and Columns to reasonable values
Bram Moolenaar071d4272004-06-13 20:20:40 +00004634 if (Rows > coordScreen.Y)
4635 Rows = coordScreen.Y;
4636 if (Columns > coordScreen.X)
4637 Columns = coordScreen.X;
4638
4639 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
4640 }
4641}
4642
4643/*
4644 * Rows and/or Columns has changed.
4645 */
4646 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004647mch_new_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004648{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004649# ifdef VIMDLL
4650 if (gui.in_use)
4651 return;
4652# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004653 set_scroll_region(0, 0, Columns - 1, Rows - 1);
4654}
4655
4656
4657/*
4658 * Called when started up, to set the winsize that was delayed.
4659 */
4660 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004661mch_set_winsize_now(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004662{
4663 if (suppress_winsize == 2)
4664 {
4665 suppress_winsize = 0;
4666 mch_set_shellsize();
4667 shell_resized();
4668 }
4669 suppress_winsize = 0;
4670}
Bram Moolenaar0f873732019-12-05 20:28:46 +01004671#endif // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00004672
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004673 static BOOL
4674vim_create_process(
Bram Moolenaar36c85b22013-12-12 20:25:44 +01004675 char *cmd,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004676 BOOL inherit_handles,
Bram Moolenaar3f1138e2014-01-05 13:29:26 +01004677 DWORD flags,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004678 STARTUPINFO *si,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004679 PROCESS_INFORMATION *pi,
4680 LPVOID *env,
4681 char *cwd)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004682{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004683 BOOL ret = FALSE;
4684 WCHAR *wcmd, *wcwd = NULL;
4685
4686 wcmd = enc_to_utf16((char_u *)cmd, NULL);
4687 if (wcmd == NULL)
4688 return FALSE;
4689 if (cwd != NULL)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004690 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004691 wcwd = enc_to_utf16((char_u *)cwd, NULL);
4692 if (wcwd == NULL)
4693 goto theend;
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004694 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004695
4696 ret = CreateProcessW(
4697 NULL, // Executable name
4698 wcmd, // Command to execute
4699 NULL, // Process security attributes
4700 NULL, // Thread security attributes
4701 inherit_handles, // Inherit handles
4702 flags, // Creation flags
4703 env, // Environment
4704 wcwd, // Current directory
4705 (LPSTARTUPINFOW)si, // Startup information
4706 pi); // Process information
4707theend:
4708 vim_free(wcmd);
4709 vim_free(wcwd);
4710 return ret;
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004711}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004712
4713
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004714 static HINSTANCE
4715vim_shell_execute(
4716 char *cmd,
4717 INT n_show_cmd)
4718{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004719 HINSTANCE ret;
4720 WCHAR *wcmd;
4721
4722 wcmd = enc_to_utf16((char_u *)cmd, NULL);
4723 if (wcmd == NULL)
4724 return (HINSTANCE) 0;
4725
4726 ret = ShellExecuteW(NULL, NULL, wcmd, NULL, NULL, n_show_cmd);
4727 vim_free(wcmd);
4728 return ret;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004729}
4730
4731
Bram Moolenaar4f974752019-02-17 17:44:42 +01004732#if defined(FEAT_GUI_MSWIN) || defined(PROTO)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004733
4734/*
4735 * Specialised version of system() for Win32 GUI mode.
4736 * This version proceeds as follows:
4737 * 1. Create a console window for use by the subprocess
4738 * 2. Run the subprocess (it gets the allocated console by default)
4739 * 3. Wait for the subprocess to terminate and get its exit code
4740 * 4. Prompt the user to press a key to close the console window
4741 */
4742 static int
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004743mch_system_classic(char *cmd, int options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004744{
4745 STARTUPINFO si;
4746 PROCESS_INFORMATION pi;
4747 DWORD ret = 0;
4748 HWND hwnd = GetFocus();
4749
4750 si.cb = sizeof(si);
4751 si.lpReserved = NULL;
4752 si.lpDesktop = NULL;
4753 si.lpTitle = NULL;
4754 si.dwFlags = STARTF_USESHOWWINDOW;
4755 /*
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004756 * It's nicer to run a filter command in a minimized window.
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01004757 * Don't activate the window to keep focus on Vim.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004758 */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004759 if (options & SHELL_DOOUT)
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01004760 si.wShowWindow = SW_SHOWMINNOACTIVE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004761 else
4762 si.wShowWindow = SW_SHOWNORMAL;
4763 si.cbReserved2 = 0;
4764 si.lpReserved2 = NULL;
4765
Bram Moolenaar0f873732019-12-05 20:28:46 +01004766 // Now, run the command
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004767 vim_create_process(cmd, FALSE,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004768 CREATE_DEFAULT_ERROR_MODE | CREATE_NEW_CONSOLE,
4769 &si, &pi, NULL, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004770
Bram Moolenaar0f873732019-12-05 20:28:46 +01004771 // Wait for the command to terminate before continuing
Bram Moolenaar071d4272004-06-13 20:20:40 +00004772 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004773# ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00004774 int delay = 1;
4775
Bram Moolenaar0f873732019-12-05 20:28:46 +01004776 // Keep updating the window while waiting for the shell to finish.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004777 for (;;)
4778 {
4779 MSG msg;
4780
K.Takatab7057bd2022-01-21 11:37:07 +00004781 if (PeekMessageW(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004782 {
4783 TranslateMessage(&msg);
K.Takatab7057bd2022-01-21 11:37:07 +00004784 DispatchMessageW(&msg);
Bram Moolenaare4195c52012-08-02 12:31:44 +02004785 delay = 1;
4786 continue;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004787 }
4788 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
4789 break;
4790
Bram Moolenaar0f873732019-12-05 20:28:46 +01004791 // We start waiting for a very short time and then increase it, so
4792 // that we respond quickly when the process is quick, and don't
4793 // consume too much overhead when it's slow.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004794 if (delay < 50)
4795 delay += 10;
4796 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004797# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004798 WaitForSingleObject(pi.hProcess, INFINITE);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004799# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004800
Bram Moolenaar0f873732019-12-05 20:28:46 +01004801 // Get the command exit code
Bram Moolenaar071d4272004-06-13 20:20:40 +00004802 GetExitCodeProcess(pi.hProcess, &ret);
4803 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004804
Bram Moolenaar0f873732019-12-05 20:28:46 +01004805 // Close the handles to the subprocess, so that it goes away
Bram Moolenaar071d4272004-06-13 20:20:40 +00004806 CloseHandle(pi.hThread);
4807 CloseHandle(pi.hProcess);
4808
Bram Moolenaar0f873732019-12-05 20:28:46 +01004809 // Try to get input focus back. Doesn't always work though.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004810 PostMessage(hwnd, WM_SETFOCUS, 0, 0);
4811
4812 return ret;
4813}
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004814
4815/*
4816 * Thread launched by the gui to send the current buffer data to the
4817 * process. This way avoid to hang up vim totally if the children
4818 * process take a long time to process the lines.
4819 */
Bram Moolenaar4c38d662016-08-03 20:54:57 +02004820 static unsigned int __stdcall
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004821sub_process_writer(LPVOID param)
4822{
4823 HANDLE g_hChildStd_IN_Wr = param;
4824 linenr_T lnum = curbuf->b_op_start.lnum;
4825 DWORD len = 0;
4826 DWORD l;
4827 char_u *lp = ml_get(lnum);
4828 char_u *s;
4829 int written = 0;
4830
4831 for (;;)
4832 {
4833 l = (DWORD)STRLEN(lp + written);
4834 if (l == 0)
4835 len = 0;
4836 else if (lp[written] == NL)
4837 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004838 // NL -> NUL translation
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004839 WriteFile(g_hChildStd_IN_Wr, "", 1, &len, NULL);
4840 }
4841 else
4842 {
4843 s = vim_strchr(lp + written, NL);
4844 WriteFile(g_hChildStd_IN_Wr, (char *)lp + written,
4845 s == NULL ? l : (DWORD)(s - (lp + written)),
4846 &len, NULL);
4847 }
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +01004848 if (len == l)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004849 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004850 // Finished a line, add a NL, unless this line should not have
4851 // one.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004852 if (lnum != curbuf->b_op_end.lnum
Bram Moolenaar34d72d42015-07-17 14:18:08 +02004853 || (!curbuf->b_p_bin
4854 && curbuf->b_p_fixeol)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004855 || (lnum != curbuf->b_no_eol_lnum
4856 && (lnum != curbuf->b_ml.ml_line_count
4857 || curbuf->b_p_eol)))
4858 {
Bram Moolenaar42335f52018-09-13 15:33:43 +02004859 WriteFile(g_hChildStd_IN_Wr, "\n", 1,
4860 (LPDWORD)&vim_ignored, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004861 }
4862
4863 ++lnum;
4864 if (lnum > curbuf->b_op_end.lnum)
4865 break;
4866
4867 lp = ml_get(lnum);
4868 written = 0;
4869 }
4870 else if (len > 0)
4871 written += len;
4872 }
4873
Bram Moolenaar0f873732019-12-05 20:28:46 +01004874 // finished all the lines, close pipe
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004875 CloseHandle(g_hChildStd_IN_Wr);
Bram Moolenaar86f2cd52016-08-02 21:55:17 +02004876 return 0;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004877}
4878
4879
Bram Moolenaar0f873732019-12-05 20:28:46 +01004880# define BUFLEN 100 // length for buffer, stolen from unix version
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004881
4882/*
4883 * This function read from the children's stdout and write the
4884 * data on screen or in the buffer accordingly.
4885 */
4886 static void
4887dump_pipe(int options,
4888 HANDLE g_hChildStd_OUT_Rd,
4889 garray_T *ga,
4890 char_u buffer[],
4891 DWORD *buffer_off)
4892{
4893 DWORD availableBytes = 0;
4894 DWORD i;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004895 int ret;
4896 DWORD len;
4897 DWORD toRead;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004898
Bram Moolenaar0f873732019-12-05 20:28:46 +01004899 // we query the pipe to see if there is any data to read
4900 // to avoid to perform a blocking read
4901 ret = PeekNamedPipe(g_hChildStd_OUT_Rd, // pipe to query
4902 NULL, // optional buffer
4903 0, // buffer size
4904 NULL, // number of read bytes
4905 &availableBytes, // available bytes total
4906 NULL); // byteLeft
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004907
Bram Moolenaar0f873732019-12-05 20:28:46 +01004908 // We got real data in the pipe, read it
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02004909 while (ret != 0 && availableBytes > 0)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004910 {
Bram Moolenaara12a1612019-01-24 16:39:02 +01004911 toRead = (DWORD)(BUFLEN - *buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004912 toRead = availableBytes < toRead ? availableBytes : toRead;
Bram Moolenaara12a1612019-01-24 16:39:02 +01004913 ReadFile(g_hChildStd_OUT_Rd, buffer + *buffer_off, toRead , &len, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004914
Bram Moolenaar0f873732019-12-05 20:28:46 +01004915 // If we haven't read anything, there is a problem
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004916 if (len == 0)
4917 break;
4918
4919 availableBytes -= len;
4920
4921 if (options & SHELL_READ)
4922 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004923 // Do NUL -> NL translation, append NL separated
4924 // lines to the current buffer.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004925 for (i = 0; i < len; ++i)
4926 {
4927 if (buffer[i] == NL)
4928 append_ga_line(ga);
4929 else if (buffer[i] == NUL)
4930 ga_append(ga, NL);
4931 else
4932 ga_append(ga, buffer[i]);
4933 }
4934 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004935 else if (has_mbyte)
4936 {
4937 int l;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004938 int c;
4939 char_u *p;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004940
4941 len += *buffer_off;
4942 buffer[len] = NUL;
4943
Bram Moolenaar0f873732019-12-05 20:28:46 +01004944 // Check if the last character in buffer[] is
4945 // incomplete, keep these bytes for the next
4946 // round.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004947 for (p = buffer; p < buffer + len; p += l)
4948 {
Bram Moolenaard3c907b2016-08-17 21:32:09 +02004949 l = MB_CPTR2LEN(p);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004950 if (l == 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01004951 l = 1; // NUL byte?
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004952 else if (MB_BYTE2LEN(*p) != l)
4953 break;
4954 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01004955 if (p == buffer) // no complete character
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004956 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004957 // avoid getting stuck at an illegal byte
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004958 if (len >= 12)
4959 ++p;
4960 else
4961 {
4962 *buffer_off = len;
4963 return;
4964 }
4965 }
4966 c = *p;
4967 *p = NUL;
Bram Moolenaar32526b32019-01-19 17:43:09 +01004968 msg_puts((char *)buffer);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004969 if (p < buffer + len)
4970 {
4971 *p = c;
4972 *buffer_off = (DWORD)((buffer + len) - p);
4973 mch_memmove(buffer, p, *buffer_off);
4974 return;
4975 }
4976 *buffer_off = 0;
4977 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004978 else
4979 {
4980 buffer[len] = NUL;
Bram Moolenaar32526b32019-01-19 17:43:09 +01004981 msg_puts((char *)buffer);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004982 }
4983
4984 windgoto(msg_row, msg_col);
4985 cursor_on();
4986 out_flush();
4987 }
4988}
4989
4990/*
4991 * Version of system to use for windows NT > 5.0 (Win2K), use pipe
4992 * for communication and doesn't open any new window.
4993 */
4994 static int
4995mch_system_piped(char *cmd, int options)
4996{
4997 STARTUPINFO si;
4998 PROCESS_INFORMATION pi;
4999 DWORD ret = 0;
5000
5001 HANDLE g_hChildStd_IN_Rd = NULL;
5002 HANDLE g_hChildStd_IN_Wr = NULL;
5003 HANDLE g_hChildStd_OUT_Rd = NULL;
5004 HANDLE g_hChildStd_OUT_Wr = NULL;
5005
Bram Moolenaar0f873732019-12-05 20:28:46 +01005006 char_u buffer[BUFLEN + 1]; // reading buffer + size
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005007 DWORD len;
5008
Bram Moolenaar0f873732019-12-05 20:28:46 +01005009 // buffer used to receive keys
5010 char_u ta_buf[BUFLEN + 1]; // TypeAHead
5011 int ta_len = 0; // valid bytes in ta_buf[]
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005012
5013 DWORD i;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005014 int noread_cnt = 0;
5015 garray_T ga;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005016 int delay = 1;
Bram Moolenaar0f873732019-12-05 20:28:46 +01005017 DWORD buffer_off = 0; // valid bytes in buffer[]
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005018 char *p = NULL;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005019
5020 SECURITY_ATTRIBUTES saAttr;
5021
Bram Moolenaar0f873732019-12-05 20:28:46 +01005022 // Set the bInheritHandle flag so pipe handles are inherited.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005023 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
5024 saAttr.bInheritHandle = TRUE;
5025 saAttr.lpSecurityDescriptor = NULL;
5026
5027 if ( ! CreatePipe(&g_hChildStd_OUT_Rd, &g_hChildStd_OUT_Wr, &saAttr, 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01005028 // Ensure the read handle to the pipe for STDOUT is not inherited.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005029 || ! SetHandleInformation(g_hChildStd_OUT_Rd, HANDLE_FLAG_INHERIT, 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01005030 // Create a pipe for the child process's STDIN.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005031 || ! CreatePipe(&g_hChildStd_IN_Rd, &g_hChildStd_IN_Wr, &saAttr, 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01005032 // Ensure the write handle to the pipe for STDIN is not inherited.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005033 || ! SetHandleInformation(g_hChildStd_IN_Wr, HANDLE_FLAG_INHERIT, 0) )
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005034 {
5035 CloseHandle(g_hChildStd_IN_Rd);
5036 CloseHandle(g_hChildStd_IN_Wr);
5037 CloseHandle(g_hChildStd_OUT_Rd);
5038 CloseHandle(g_hChildStd_OUT_Wr);
Bram Moolenaar32526b32019-01-19 17:43:09 +01005039 msg_puts(_("\nCannot create pipes\n"));
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005040 }
5041
5042 si.cb = sizeof(si);
5043 si.lpReserved = NULL;
5044 si.lpDesktop = NULL;
5045 si.lpTitle = NULL;
5046 si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
5047
Bram Moolenaar0f873732019-12-05 20:28:46 +01005048 // set-up our file redirection
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005049 si.hStdError = g_hChildStd_OUT_Wr;
5050 si.hStdOutput = g_hChildStd_OUT_Wr;
5051 si.hStdInput = g_hChildStd_IN_Rd;
5052 si.wShowWindow = SW_HIDE;
5053 si.cbReserved2 = 0;
5054 si.lpReserved2 = NULL;
5055
5056 if (options & SHELL_READ)
5057 ga_init2(&ga, 1, BUFLEN);
5058
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005059 if (cmd != NULL)
5060 {
5061 p = (char *)vim_strsave((char_u *)cmd);
5062 if (p != NULL)
5063 unescape_shellxquote((char_u *)p, p_sxe);
5064 else
5065 p = cmd;
5066 }
5067
Bram Moolenaar0f873732019-12-05 20:28:46 +01005068 // Now, run the command.
5069 // About "Inherit handles" being TRUE: this command can be litigious,
5070 // handle inheritance was deactivated for pending temp file, but, if we
5071 // deactivate it, the pipes don't work for some reason.
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005072 vim_create_process(p, TRUE, CREATE_DEFAULT_ERROR_MODE,
5073 &si, &pi, NULL, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005074
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005075 if (p != cmd)
5076 vim_free(p);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005077
Bram Moolenaar0f873732019-12-05 20:28:46 +01005078 // Close our unused side of the pipes
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005079 CloseHandle(g_hChildStd_IN_Rd);
5080 CloseHandle(g_hChildStd_OUT_Wr);
5081
5082 if (options & SHELL_WRITE)
5083 {
Bram Moolenaar86f2cd52016-08-02 21:55:17 +02005084 HANDLE thread = (HANDLE)
Bram Moolenaar0f873732019-12-05 20:28:46 +01005085 _beginthreadex(NULL, // security attributes
5086 0, // default stack size
5087 sub_process_writer, // function to be executed
5088 g_hChildStd_IN_Wr, // parameter
5089 0, // creation flag, start immediately
5090 NULL); // we don't care about thread id
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005091 CloseHandle(thread);
5092 g_hChildStd_IN_Wr = NULL;
5093 }
5094
Bram Moolenaar0f873732019-12-05 20:28:46 +01005095 // Keep updating the window while waiting for the shell to finish.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005096 for (;;)
5097 {
5098 MSG msg;
5099
K.Takatab7057bd2022-01-21 11:37:07 +00005100 if (PeekMessageW(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005101 {
5102 TranslateMessage(&msg);
K.Takatab7057bd2022-01-21 11:37:07 +00005103 DispatchMessageW(&msg);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005104 }
5105
Bram Moolenaar0f873732019-12-05 20:28:46 +01005106 // write pipe information in the window
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005107 if ((options & (SHELL_READ|SHELL_WRITE))
5108# ifdef FEAT_GUI
5109 || gui.in_use
5110# endif
5111 )
5112 {
5113 len = 0;
GuyBrush52ecc762024-02-21 20:16:38 +01005114 if (((options &
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005115 (SHELL_READ|SHELL_WRITE|SHELL_COOKED))
5116 != (SHELL_READ|SHELL_WRITE|SHELL_COOKED)
5117# ifdef FEAT_GUI
5118 || gui.in_use
5119# endif
5120 )
5121 && (ta_len > 0 || noread_cnt > 4))
5122 {
5123 if (ta_len == 0)
5124 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005125 // Get extra characters when we don't have any. Reset the
5126 // counter and timer.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005127 noread_cnt = 0;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005128 len = ui_inchar(ta_buf, BUFLEN, 10L, 0);
5129 }
5130 if (ta_len > 0 || len > 0)
5131 {
5132 /*
5133 * For pipes: Check for CTRL-C: send interrupt signal to
GuyBrush1f13fcc2024-01-14 20:08:40 +01005134 * child.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005135 */
5136 if (len == 1 && cmd != NULL)
5137 {
5138 if (ta_buf[ta_len] == Ctrl_C)
5139 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005140 // Learn what exit code is expected, for
5141 // now put 9 as SIGKILL
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005142 TerminateProcess(pi.hProcess, 9);
5143 }
GuyBrush1f13fcc2024-01-14 20:08:40 +01005144 }
5145
5146 /*
5147 * Check for CTRL-D: EOF, close pipe to child.
5148 * Ctrl_D may be decorated by _OnChar()
5149 */
5150 if ((len == 1 || len == 4 ) && cmd != NULL)
5151 {
5152 if (ta_buf[0] == Ctrl_D
5153 || (ta_buf[0] == CSI
5154 && ta_buf[1] == KS_MODIFIER
5155 && ta_buf[3] == Ctrl_D))
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005156 {
5157 CloseHandle(g_hChildStd_IN_Wr);
5158 g_hChildStd_IN_Wr = NULL;
GuyBrush1f13fcc2024-01-14 20:08:40 +01005159 len = 0;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005160 }
5161 }
5162
Bram Moolenaar2f7e1b82022-10-04 13:17:31 +01005163 len = term_replace_keycodes(ta_buf, ta_len, len);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005164
5165 /*
5166 * For pipes: echo the typed characters. For a pty this
5167 * does not seem to work.
5168 */
5169 for (i = ta_len; i < ta_len + len; ++i)
5170 {
5171 if (ta_buf[i] == '\n' || ta_buf[i] == '\b')
5172 msg_putchar(ta_buf[i]);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005173 else if (has_mbyte)
5174 {
5175 int l = (*mb_ptr2len)(ta_buf + i);
5176
5177 msg_outtrans_len(ta_buf + i, l);
5178 i += l - 1;
5179 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005180 else
5181 msg_outtrans_len(ta_buf + i, 1);
5182 }
5183 windgoto(msg_row, msg_col);
5184 out_flush();
5185
5186 ta_len += len;
5187
5188 /*
5189 * Write the characters to the child, unless EOF has been
5190 * typed for pipes. Write one character at a time, to
5191 * avoid losing too much typeahead. When writing buffer
5192 * lines, drop the typed characters (only check for
5193 * CTRL-C).
5194 */
5195 if (options & SHELL_WRITE)
5196 ta_len = 0;
5197 else if (g_hChildStd_IN_Wr != NULL)
5198 {
5199 WriteFile(g_hChildStd_IN_Wr, (char*)ta_buf,
5200 1, &len, NULL);
5201 // if we are typing in, we want to keep things reactive
5202 delay = 1;
5203 if (len > 0)
5204 {
5205 ta_len -= len;
5206 mch_memmove(ta_buf, ta_buf + len, ta_len);
5207 }
5208 }
5209 }
5210 }
5211 }
5212
5213 if (ta_len)
5214 ui_inchar_undo(ta_buf, ta_len);
5215
5216 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
5217 {
Bram Moolenaar2eba1822011-08-27 15:10:04 +02005218 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005219 break;
5220 }
5221
5222 ++noread_cnt;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02005223 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005224
Bram Moolenaar0f873732019-12-05 20:28:46 +01005225 // We start waiting for a very short time and then increase it, so
5226 // that we respond quickly when the process is quick, and don't
5227 // consume too much overhead when it's slow.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005228 if (delay < 50)
5229 delay += 10;
5230 }
5231
Bram Moolenaar0f873732019-12-05 20:28:46 +01005232 // Close the pipe
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005233 CloseHandle(g_hChildStd_OUT_Rd);
5234 if (g_hChildStd_IN_Wr != NULL)
5235 CloseHandle(g_hChildStd_IN_Wr);
5236
5237 WaitForSingleObject(pi.hProcess, INFINITE);
5238
Bram Moolenaar0f873732019-12-05 20:28:46 +01005239 // Get the command exit code
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005240 GetExitCodeProcess(pi.hProcess, &ret);
5241
5242 if (options & SHELL_READ)
5243 {
5244 if (ga.ga_len > 0)
5245 {
5246 append_ga_line(&ga);
Bram Moolenaar0f873732019-12-05 20:28:46 +01005247 // remember that the NL was missing
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005248 curbuf->b_no_eol_lnum = curwin->w_cursor.lnum;
5249 }
5250 else
5251 curbuf->b_no_eol_lnum = 0;
5252 ga_clear(&ga);
5253 }
5254
Bram Moolenaar0f873732019-12-05 20:28:46 +01005255 // Close the handles to the subprocess, so that it goes away
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005256 CloseHandle(pi.hThread);
5257 CloseHandle(pi.hProcess);
5258
5259 return ret;
5260}
5261
5262 static int
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005263mch_system_g(char *cmd, int options)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005264{
Bram Moolenaar0f873732019-12-05 20:28:46 +01005265 // if we can pipe and the shelltemp option is off
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005266 if (!p_stmp)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005267 return mch_system_piped(cmd, options);
5268 else
5269 return mch_system_classic(cmd, options);
5270}
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005271#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005272
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005273#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01005274 static int
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02005275mch_system_c(char *cmd, int options UNUSED)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01005276{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005277 int ret;
5278 WCHAR *wcmd;
Bram Moolenaar2efc44b2019-10-05 12:09:32 +02005279 char_u *buf;
5280 size_t len;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005281
Bram Moolenaar2efc44b2019-10-05 12:09:32 +02005282 // If the command starts and ends with double quotes, enclose the command
5283 // in parentheses.
5284 len = STRLEN(cmd);
5285 if (len >= 2 && cmd[0] == '"' && cmd[len - 1] == '"')
5286 {
5287 len += 3;
5288 buf = alloc(len);
5289 if (buf == NULL)
5290 return -1;
5291 vim_snprintf((char *)buf, len, "(%s)", cmd);
5292 wcmd = enc_to_utf16(buf, NULL);
5293 free(buf);
5294 }
5295 else
5296 wcmd = enc_to_utf16((char_u *)cmd, NULL);
5297
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005298 if (wcmd == NULL)
5299 return -1;
5300
5301 ret = _wsystem(wcmd);
5302 vim_free(wcmd);
5303 return ret;
Bram Moolenaar910cffb2013-12-11 17:58:35 +01005304}
Bram Moolenaar071d4272004-06-13 20:20:40 +00005305
5306#endif
5307
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005308 static int
5309mch_system(char *cmd, int options)
5310{
5311#ifdef VIMDLL
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02005312 if (gui.in_use || gui.starting)
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005313 return mch_system_g(cmd, options);
5314 else
5315 return mch_system_c(cmd, options);
5316#elif defined(FEAT_GUI_MSWIN)
5317 return mch_system_g(cmd, options);
5318#else
5319 return mch_system_c(cmd, options);
5320#endif
5321}
5322
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005323#if defined(FEAT_GUI) && defined(FEAT_TERMINAL)
5324/*
5325 * Use a terminal window to run a shell command in.
5326 */
5327 static int
5328mch_call_shell_terminal(
5329 char_u *cmd,
Bram Moolenaar0f873732019-12-05 20:28:46 +01005330 int options UNUSED) // SHELL_*, see vim.h
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005331{
5332 jobopt_T opt;
5333 char_u *newcmd = NULL;
5334 typval_T argvar[2];
5335 long_u cmdlen;
5336 int retval = -1;
5337 buf_T *buf;
Bram Moolenaarf9c38832018-06-19 19:59:20 +02005338 job_T *job;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005339 aco_save_T aco;
Bram Moolenaar0f873732019-12-05 20:28:46 +01005340 oparg_T oa; // operator arguments
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005341
Bram Moolenaar42f652f2018-03-19 21:44:37 +01005342 if (cmd == NULL)
5343 cmdlen = STRLEN(p_sh) + 1;
5344 else
5345 cmdlen = STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10;
Bram Moolenaar18a4ba22019-05-24 19:39:03 +02005346 newcmd = alloc(cmdlen);
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005347 if (newcmd == NULL)
5348 return 255;
Bram Moolenaar42f652f2018-03-19 21:44:37 +01005349 if (cmd == NULL)
5350 {
5351 STRCPY(newcmd, p_sh);
5352 ch_log(NULL, "starting terminal to run a shell");
5353 }
5354 else
5355 {
5356 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s", p_sh, p_shcf, cmd);
5357 ch_log(NULL, "starting terminal for system command '%s'", cmd);
5358 }
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005359
5360 init_job_options(&opt);
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005361
5362 argvar[0].v_type = VAR_STRING;
5363 argvar[0].vval.v_string = newcmd;
5364 argvar[1].v_type = VAR_UNKNOWN;
5365 buf = term_start(argvar, NULL, &opt, TERM_START_SYSTEM);
Bram Moolenaar81c3c89a2018-03-20 11:41:44 +01005366 if (buf == NULL)
Bram Moolenaar9029b912019-03-21 19:58:00 +01005367 {
5368 vim_free(newcmd);
Bram Moolenaar81c3c89a2018-03-20 11:41:44 +01005369 return 255;
Bram Moolenaar9029b912019-03-21 19:58:00 +01005370 }
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005371
Bram Moolenaarf9c38832018-06-19 19:59:20 +02005372 job = term_getjob(buf->b_term);
5373 ++job->jv_refcount;
5374
Bram Moolenaar0f873732019-12-05 20:28:46 +01005375 // Find a window to make "buf" curbuf.
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005376 aucmd_prepbuf(&aco, buf);
Bram Moolenaare76062c2022-11-28 18:51:43 +00005377 if (curbuf == buf)
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005378 {
Bram Moolenaare76062c2022-11-28 18:51:43 +00005379 // Only do this when a window was found for "buf".
5380 clear_oparg(&oa);
5381 while (term_use_loop())
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005382 {
Bram Moolenaare76062c2022-11-28 18:51:43 +00005383 if (oa.op_type == OP_NOP && oa.regname == NUL && !VIsual_active)
5384 {
5385 // If terminal_loop() returns OK we got a key that is handled
5386 // in Normal model. We don't do redrawing anyway.
5387 if (terminal_loop(TRUE) == OK)
5388 normal_cmd(&oa, TRUE);
5389 }
5390 else
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005391 normal_cmd(&oa, TRUE);
5392 }
Bram Moolenaare76062c2022-11-28 18:51:43 +00005393 retval = job->jv_exitval;
5394 ch_log(NULL, "system command finished");
5395
5396 job_unref(job);
5397
5398 // restore curwin/curbuf and a few other things
5399 aucmd_restbuf(&aco);
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005400 }
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005401
5402 wait_return(TRUE);
5403 do_buffer(DOBUF_WIPE, DOBUF_FIRST, FORWARD, buf->b_fnum, TRUE);
5404
5405 vim_free(newcmd);
5406 return retval;
5407}
5408#endif
5409
Bram Moolenaar071d4272004-06-13 20:20:40 +00005410/*
5411 * Either execute a command by calling the shell or start a new shell
5412 */
5413 int
5414mch_call_shell(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005415 char_u *cmd,
Bram Moolenaar0f873732019-12-05 20:28:46 +01005416 int options) // SHELL_*, see vim.h
Bram Moolenaar071d4272004-06-13 20:20:40 +00005417{
5418 int x = 0;
5419 int tmode = cur_tmode;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005420 WCHAR szShellTitle[512];
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02005421
Bram Moolenaar4c5678f2022-11-30 18:12:19 +00005422#ifdef FEAT_EVAL
Bram Moolenaarc9a9a0a2022-04-12 15:09:23 +01005423 ch_log(NULL, "executing shell command: %s", cmd);
5424#endif
Bram Moolenaar0f873732019-12-05 20:28:46 +01005425 // Change the title to reflect that we are in a subshell.
K.Takataeeec2542021-06-02 13:28:16 +02005426 if (GetConsoleTitleW(szShellTitle, ARRAY_LENGTH(szShellTitle) - 4) > 0)
Bram Moolenaar1df52d72014-10-15 22:50:10 +02005427 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005428 if (cmd == NULL)
5429 wcscat(szShellTitle, L" :sh");
5430 else
Bram Moolenaar1df52d72014-10-15 22:50:10 +02005431 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005432 WCHAR *wn = enc_to_utf16((char_u *)cmd, NULL);
Bram Moolenaar1df52d72014-10-15 22:50:10 +02005433
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005434 if (wn != NULL)
5435 {
5436 wcscat(szShellTitle, L" - !");
5437 if ((wcslen(szShellTitle) + wcslen(wn) <
K.Takataeeec2542021-06-02 13:28:16 +02005438 ARRAY_LENGTH(szShellTitle)))
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005439 wcscat(szShellTitle, wn);
5440 SetConsoleTitleW(szShellTitle);
5441 vim_free(wn);
Bram Moolenaar1df52d72014-10-15 22:50:10 +02005442 }
5443 }
5444 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005445
5446 out_flush();
5447
5448#ifdef MCH_WRITE_DUMP
5449 if (fdDump)
5450 {
5451 fprintf(fdDump, "mch_call_shell(\"%s\", %d)\n", cmd, options);
5452 fflush(fdDump);
5453 }
5454#endif
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005455#if defined(FEAT_GUI) && defined(FEAT_TERMINAL)
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02005456 // TODO: make the terminal window work with input or output redirected.
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005457 if (
5458# ifdef VIMDLL
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02005459 gui.in_use &&
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005460# endif
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02005461 vim_strchr(p_go, GO_TERMINAL) != NULL
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005462 && (options & (SHELL_FILTER|SHELL_DOOUT|SHELL_WRITE|SHELL_READ)) == 0)
5463 {
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02005464 char_u *cmdbase = cmd;
5465
Bram Moolenaar4d5c1262019-09-20 17:20:02 +02005466 if (cmdbase != NULL)
5467 // Skip a leading quote and (.
5468 while (*cmdbase == '"' || *cmdbase == '(')
5469 ++cmdbase;
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02005470
5471 // Check the command does not begin with "start "
Bram Moolenaar36e7a822019-11-13 21:49:24 +01005472 if (cmdbase == NULL || STRNICMP(cmdbase, "start", 5) != 0
5473 || !VIM_ISWHITE(cmdbase[5]))
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02005474 {
5475 // Use a terminal window to run the command in.
5476 x = mch_call_shell_terminal(cmd, options);
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02005477 resettitle();
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02005478 return x;
5479 }
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005480 }
5481#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005482
5483 /*
5484 * Catch all deadly signals while running the external command, because a
5485 * CTRL-C, Ctrl-Break or illegal instruction might otherwise kill us.
5486 */
ichizok378447f2023-05-11 22:25:42 +01005487 mch_signal(SIGINT, SIG_IGN);
ichizok378447f2023-05-11 22:25:42 +01005488 mch_signal(SIGBREAK, SIG_IGN);
ichizok378447f2023-05-11 22:25:42 +01005489 mch_signal(SIGILL, SIG_IGN);
5490 mch_signal(SIGFPE, SIG_IGN);
5491 mch_signal(SIGSEGV, SIG_IGN);
5492 mch_signal(SIGTERM, SIG_IGN);
5493 mch_signal(SIGABRT, SIG_IGN);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005494
5495 if (options & SHELL_COOKED)
Bram Moolenaar0f873732019-12-05 20:28:46 +01005496 settmode(TMODE_COOK); // set to normal mode
Bram Moolenaar071d4272004-06-13 20:20:40 +00005497
5498 if (cmd == NULL)
5499 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01005500 x = mch_system((char *)p_sh, options);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005501 }
5502 else
5503 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005504 // we use "command" or "cmd" to start the shell; slow but easy
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005505 char_u *newcmd = NULL;
5506 char_u *cmdbase = cmd;
5507 long_u cmdlen;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005508
Bram Moolenaar0f873732019-12-05 20:28:46 +01005509 // Skip a leading ", ( and "(.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005510 if (*cmdbase == '"' )
5511 ++cmdbase;
5512 if (*cmdbase == '(')
5513 ++cmdbase;
5514
Bram Moolenaar1c465442017-03-12 20:10:05 +01005515 if ((STRNICMP(cmdbase, "start", 5) == 0) && VIM_ISWHITE(cmdbase[5]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005516 {
5517 STARTUPINFO si;
5518 PROCESS_INFORMATION pi;
5519 DWORD flags = CREATE_NEW_CONSOLE;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01005520 INT n_show_cmd = SW_SHOWNORMAL;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005521 char_u *p;
5522
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01005523 ZeroMemory(&si, sizeof(si));
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005524 si.cb = sizeof(si);
5525 si.lpReserved = NULL;
5526 si.lpDesktop = NULL;
5527 si.lpTitle = NULL;
5528 si.dwFlags = 0;
5529 si.cbReserved2 = 0;
5530 si.lpReserved2 = NULL;
5531
5532 cmdbase = skipwhite(cmdbase + 5);
5533 if ((STRNICMP(cmdbase, "/min", 4) == 0)
Bram Moolenaar1c465442017-03-12 20:10:05 +01005534 && VIM_ISWHITE(cmdbase[4]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005535 {
5536 cmdbase = skipwhite(cmdbase + 4);
5537 si.dwFlags = STARTF_USESHOWWINDOW;
5538 si.wShowWindow = SW_SHOWMINNOACTIVE;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01005539 n_show_cmd = SW_SHOWMINNOACTIVE;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005540 }
5541 else if ((STRNICMP(cmdbase, "/b", 2) == 0)
Bram Moolenaar1c465442017-03-12 20:10:05 +01005542 && VIM_ISWHITE(cmdbase[2]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005543 {
5544 cmdbase = skipwhite(cmdbase + 2);
5545 flags = CREATE_NO_WINDOW;
5546 si.dwFlags = STARTF_USESTDHANDLES;
5547 si.hStdInput = CreateFile("\\\\.\\NUL", // File name
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005548 GENERIC_READ, // Access flags
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005549 0, // Share flags
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005550 NULL, // Security att.
5551 OPEN_EXISTING, // Open flags
5552 FILE_ATTRIBUTE_NORMAL, // File att.
5553 NULL); // Temp file
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005554 si.hStdOutput = si.hStdInput;
5555 si.hStdError = si.hStdInput;
5556 }
5557
Bram Moolenaar0f873732019-12-05 20:28:46 +01005558 // Remove a trailing ", ) and )" if they have a match
5559 // at the start of the command.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005560 if (cmdbase > cmd)
5561 {
5562 p = cmdbase + STRLEN(cmdbase);
5563 if (p > cmdbase && p[-1] == '"' && *cmd == '"')
5564 *--p = NUL;
5565 if (p > cmdbase && p[-1] == ')'
5566 && (*cmd =='(' || cmd[1] == '('))
5567 *--p = NUL;
5568 }
5569
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005570 newcmd = cmdbase;
5571 unescape_shellxquote(cmdbase, p_sxe);
5572
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005573 /*
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005574 * If creating new console, arguments are passed to the
5575 * 'cmd.exe' as-is. If it's not, arguments are not treated
5576 * correctly for current 'cmd.exe'. So unescape characters in
5577 * shellxescape except '|' for avoiding to be treated as
5578 * argument to them. Pass the arguments to sub-shell.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005579 */
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005580 if (flags != CREATE_NEW_CONSOLE)
5581 {
5582 char_u *subcmd;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01005583 char_u *cmd_shell = mch_getenv("COMSPEC");
5584
5585 if (cmd_shell == NULL || *cmd_shell == NUL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01005586 cmd_shell = (char_u *)default_shell();
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005587
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01005588 subcmd = vim_strsave_escaped_ext(cmdbase,
5589 (char_u *)"|", '^', FALSE);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005590 if (subcmd != NULL)
5591 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005592 // make "cmd.exe /c arguments"
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005593 cmdlen = STRLEN(cmd_shell) + STRLEN(subcmd) + 5;
Bram Moolenaar18a4ba22019-05-24 19:39:03 +02005594 newcmd = alloc(cmdlen);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005595 if (newcmd != NULL)
5596 vim_snprintf((char *)newcmd, cmdlen, "%s /c %s",
Bram Moolenaaree7d1002012-02-22 15:34:08 +01005597 cmd_shell, subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005598 else
5599 newcmd = cmdbase;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01005600 vim_free(subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005601 }
5602 }
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005603
5604 /*
5605 * Now, start the command as a process, so that it doesn't
5606 * inherit our handles which causes unpleasant dangling swap
5607 * files if we exit before the spawned process
5608 */
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005609 if (vim_create_process((char *)newcmd, FALSE, flags,
5610 &si, &pi, NULL, NULL))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005611 x = 0;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01005612 else if (vim_shell_execute((char *)newcmd, n_show_cmd)
5613 > (HINSTANCE)32)
5614 x = 0;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005615 else
5616 {
5617 x = -1;
Bram Moolenaar4f974752019-02-17 17:44:42 +01005618#ifdef FEAT_GUI_MSWIN
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005619# ifdef VIMDLL
5620 if (gui.in_use)
5621# endif
Bram Moolenaarac78dd42022-01-02 19:25:26 +00005622 emsg(_(e_command_not_found));
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005623#endif
5624 }
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005625
5626 if (newcmd != cmdbase)
5627 vim_free(newcmd);
5628
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01005629 if (si.dwFlags == STARTF_USESTDHANDLES && si.hStdInput != NULL)
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005630 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005631 // Close the handle to \\.\NUL created above.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005632 CloseHandle(si.hStdInput);
5633 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01005634 // Close the handles to the subprocess, so that it goes away
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005635 CloseHandle(pi.hThread);
5636 CloseHandle(pi.hProcess);
5637 }
5638 else
5639 {
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005640 cmdlen =
Bram Moolenaar4f974752019-02-17 17:44:42 +01005641#ifdef FEAT_GUI_MSWIN
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02005642 ((gui.in_use || gui.starting) ?
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005643 (!s_dont_use_vimrun && p_stmp ?
5644 STRLEN(vimrun_path) : STRLEN(p_sh) + STRLEN(p_shcf))
5645 : 0) +
Bram Moolenaar071d4272004-06-13 20:20:40 +00005646#endif
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005647 STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10;
Bram Moolenaar0fde2902008-03-16 13:54:13 +00005648
Bram Moolenaar18a4ba22019-05-24 19:39:03 +02005649 newcmd = alloc(cmdlen);
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005650 if (newcmd != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005651 {
Bram Moolenaar4f974752019-02-17 17:44:42 +01005652#if defined(FEAT_GUI_MSWIN)
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005653 if (
5654# ifdef VIMDLL
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02005655 (gui.in_use || gui.starting) &&
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005656# endif
5657 need_vimrun_warning)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005658 {
Bram Moolenaar63e43442016-11-19 17:28:44 +01005659 char *msg = _("VIMRUN.EXE not found in your $PATH.\n"
5660 "External commands will not pause after completion.\n"
5661 "See :help win32-vimrun for more information.");
5662 char *title = _("Vim Warning");
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005663 WCHAR *wmsg = enc_to_utf16((char_u *)msg, NULL);
5664 WCHAR *wtitle = enc_to_utf16((char_u *)title, NULL);
Bram Moolenaar63e43442016-11-19 17:28:44 +01005665
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005666 if (wmsg != NULL && wtitle != NULL)
5667 MessageBoxW(NULL, wmsg, wtitle, MB_ICONWARNING);
5668 vim_free(wmsg);
5669 vim_free(wtitle);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005670 need_vimrun_warning = FALSE;
5671 }
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005672 if (
5673# ifdef VIMDLL
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02005674 (gui.in_use || gui.starting) &&
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005675# endif
5676 !s_dont_use_vimrun && p_stmp)
Bram Moolenaarfcc4d922019-05-24 13:32:36 +02005677 // Use vimrun to execute the command. It opens a console
5678 // window, which can be closed without killing Vim.
Bram Moolenaarcc448b32010-07-14 16:52:17 +02005679 vim_snprintf((char *)newcmd, cmdlen, "%s%s%s %s %s",
Bram Moolenaar071d4272004-06-13 20:20:40 +00005680 vimrun_path,
5681 (msg_silent != 0 || (options & SHELL_DOOUT))
5682 ? "-s " : "",
5683 p_sh, p_shcf, cmd);
Bram Moolenaarfcc4d922019-05-24 13:32:36 +02005684 else if (
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005685# ifdef VIMDLL
Bram Moolenaarfcc4d922019-05-24 13:32:36 +02005686 (gui.in_use || gui.starting) &&
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005687# endif
Bram Moolenaar0e6bfb92019-07-31 20:53:56 +02005688 s_dont_use_vimrun && STRCMP(p_shcf, "/c") == 0)
Bram Moolenaarfcc4d922019-05-24 13:32:36 +02005689 // workaround for the case that "vimrun" does not exist
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005690 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s %s %s",
5691 p_sh, p_shcf, p_sh, p_shcf, cmd);
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005692 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00005693#endif
Bram Moolenaarcc448b32010-07-14 16:52:17 +02005694 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s",
Bram Moolenaar0fde2902008-03-16 13:54:13 +00005695 p_sh, p_shcf, cmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005696 x = mch_system((char *)newcmd, options);
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005697 vim_free(newcmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005698 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005699 }
5700 }
5701
5702 if (tmode == TMODE_RAW)
Bram Moolenaar3b1f18f2020-05-16 23:15:08 +02005703 {
5704 // The shell may have messed with the mode, always set it.
5705 cur_tmode = TMODE_UNKNOWN;
Bram Moolenaar0f873732019-12-05 20:28:46 +01005706 settmode(TMODE_RAW); // set to raw mode
Bram Moolenaar3b1f18f2020-05-16 23:15:08 +02005707 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005708
Bram Moolenaar0f873732019-12-05 20:28:46 +01005709 // Print the return value, unless "vimrun" was used.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005710 if (x != 0 && !(options & SHELL_SILENT) && !emsg_silent
Bram Moolenaar4f974752019-02-17 17:44:42 +01005711#if defined(FEAT_GUI_MSWIN)
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02005712 && ((gui.in_use || gui.starting) ?
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005713 ((options & SHELL_DOOUT) || s_dont_use_vimrun || !p_stmp) : 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005714#endif
5715 )
5716 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005717 smsg(_("shell returned %d"), x);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005718 msg_putchar('\n');
5719 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005720 resettitle();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005721
ichizok378447f2023-05-11 22:25:42 +01005722 mch_signal(SIGINT, SIG_DFL);
ichizok378447f2023-05-11 22:25:42 +01005723 mch_signal(SIGBREAK, SIG_DFL);
ichizok378447f2023-05-11 22:25:42 +01005724 mch_signal(SIGILL, SIG_DFL);
5725 mch_signal(SIGFPE, SIG_DFL);
5726 mch_signal(SIGSEGV, SIG_DFL);
5727 mch_signal(SIGTERM, SIG_DFL);
5728 mch_signal(SIGABRT, SIG_DFL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005729
5730 return x;
5731}
5732
Bram Moolenaar509ce2a2016-03-11 22:52:15 +01005733#if defined(FEAT_JOB_CHANNEL) || defined(PROTO)
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005734 static HANDLE
5735job_io_file_open(
Bram Moolenaar972c3b82017-01-12 21:44:49 +01005736 char_u *fname,
5737 DWORD dwDesiredAccess,
5738 DWORD dwShareMode,
5739 LPSECURITY_ATTRIBUTES lpSecurityAttributes,
5740 DWORD dwCreationDisposition,
5741 DWORD dwFlagsAndAttributes)
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005742{
5743 HANDLE h;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005744 WCHAR *wn;
Bram Moolenaara12a1612019-01-24 16:39:02 +01005745
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005746 wn = enc_to_utf16(fname, NULL);
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005747 if (wn == NULL)
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005748 return INVALID_HANDLE_VALUE;
5749
5750 h = CreateFileW(wn, dwDesiredAccess, dwShareMode,
5751 lpSecurityAttributes, dwCreationDisposition,
5752 dwFlagsAndAttributes, NULL);
5753 vim_free(wn);
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005754 return h;
5755}
5756
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005757/*
5758 * Turn the dictionary "env" into a NUL separated list that can be used as the
5759 * environment argument of vim_create_process().
5760 */
Bram Moolenaarba6febd2017-10-30 21:56:23 +01005761 void
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005762win32_build_env(dict_T *env, garray_T *gap, int is_terminal)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005763{
5764 hashitem_T *hi;
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005765 long_u todo = env != NULL ? env->dv_hashtab.ht_used : 0;
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005766 LPVOID base = GetEnvironmentStringsW();
5767
Bram Moolenaar0f873732019-12-05 20:28:46 +01005768 // for last \0
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005769 if (ga_grow(gap, 1) == FAIL)
5770 return;
5771
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005772 if (env != NULL)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005773 {
Yegappan Lakshmanan14113fd2023-03-07 17:13:51 +00005774 FOR_ALL_HASHTAB_ITEMS(&env->dv_hashtab, hi, todo)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005775 {
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005776 if (!HASHITEM_EMPTY(hi))
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005777 {
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005778 typval_T *item = &dict_lookup(hi)->di_tv;
5779 WCHAR *wkey = enc_to_utf16((char_u *)hi->hi_key, NULL);
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005780 WCHAR *wval = enc_to_utf16(tv_get_string(item), NULL);
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005781 --todo;
5782 if (wkey != NULL && wval != NULL)
5783 {
5784 size_t n;
5785 size_t lkey = wcslen(wkey);
5786 size_t lval = wcslen(wval);
Bram Moolenaar60104f12017-08-14 23:25:04 +02005787
Yegappan Lakshmananfadc02a2023-01-27 21:03:12 +00005788 if (ga_grow(gap, (int)(lkey + lval + 2)) == FAIL)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005789 continue;
5790 for (n = 0; n < lkey; n++)
5791 *((WCHAR*)gap->ga_data + gap->ga_len++) = wkey[n];
5792 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'=';
5793 for (n = 0; n < lval; n++)
5794 *((WCHAR*)gap->ga_data + gap->ga_len++) = wval[n];
5795 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5796 }
Bram Moolenaarbdace832019-03-02 10:13:42 +01005797 vim_free(wkey);
5798 vim_free(wval);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005799 }
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005800 }
5801 }
5802
Bram Moolenaar355757a2020-02-10 22:06:32 +01005803 if (base)
5804 {
5805 WCHAR *p = (WCHAR*) base;
5806
5807 // for last \0
5808 if (ga_grow(gap, 1) == FAIL)
5809 return;
5810
5811 while (*p != 0 || *(p + 1) != 0)
5812 {
5813 if (ga_grow(gap, 1) == OK)
5814 *((WCHAR*)gap->ga_data + gap->ga_len++) = *p;
5815 p++;
5816 }
Ken Takataad29f6a2023-09-16 13:56:02 +02005817 FreeEnvironmentStringsW(base);
Bram Moolenaar355757a2020-02-10 22:06:32 +01005818 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5819 }
5820
Bram Moolenaar493359e2018-06-12 20:25:52 +02005821# if defined(FEAT_CLIENTSERVER) || defined(FEAT_TERMINAL)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005822 {
Bram Moolenaar493359e2018-06-12 20:25:52 +02005823# ifdef FEAT_CLIENTSERVER
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005824 char_u *servername = get_vim_var_str(VV_SEND_SERVER);
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005825 size_t servername_len = STRLEN(servername);
Bram Moolenaar493359e2018-06-12 20:25:52 +02005826# endif
5827# ifdef FEAT_TERMINAL
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005828 char_u *version = get_vim_var_str(VV_VERSION);
5829 size_t version_len = STRLEN(version);
Bram Moolenaar493359e2018-06-12 20:25:52 +02005830# endif
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005831 // size of "VIM_SERVERNAME=" and value,
5832 // plus "VIM_TERMINAL=" and value,
5833 // plus two terminating NULs
5834 size_t n = 0
Bram Moolenaar493359e2018-06-12 20:25:52 +02005835# ifdef FEAT_CLIENTSERVER
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005836 + 15 + servername_len
Bram Moolenaar493359e2018-06-12 20:25:52 +02005837# endif
5838# ifdef FEAT_TERMINAL
5839 + 13 + version_len + 2
5840# endif
5841 ;
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005842
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005843 if (ga_grow(gap, (int)n) == OK)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005844 {
Bram Moolenaar493359e2018-06-12 20:25:52 +02005845# ifdef FEAT_CLIENTSERVER
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005846 for (n = 0; n < 15; n++)
5847 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5848 (WCHAR)"VIM_SERVERNAME="[n];
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005849 for (n = 0; n < servername_len; n++)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005850 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5851 (WCHAR)servername[n];
5852 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
Bram Moolenaar493359e2018-06-12 20:25:52 +02005853# endif
5854# ifdef FEAT_TERMINAL
5855 if (is_terminal)
5856 {
5857 for (n = 0; n < 13; n++)
5858 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5859 (WCHAR)"VIM_TERMINAL="[n];
5860 for (n = 0; n < version_len; n++)
5861 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5862 (WCHAR)version[n];
5863 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5864 }
5865# endif
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005866 }
5867 }
Bram Moolenaar79c6b512018-06-12 21:11:12 +02005868# endif
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005869}
5870
Bram Moolenaarb091f302019-01-19 14:37:00 +01005871/*
5872 * Create a pair of pipes.
5873 * Return TRUE for success, FALSE for failure.
5874 */
5875 static BOOL
5876create_pipe_pair(HANDLE handles[2])
5877{
5878 static LONG s;
5879 char name[64];
5880 SECURITY_ATTRIBUTES sa;
5881
5882 sprintf(name, "\\\\?\\pipe\\vim-%08lx-%08lx",
5883 GetCurrentProcessId(),
5884 InterlockedIncrement(&s));
5885
5886 // Create named pipe. Max size of named pipe is 65535.
5887 handles[1] = CreateNamedPipe(
5888 name,
5889 PIPE_ACCESS_OUTBOUND | FILE_FLAG_OVERLAPPED,
5890 PIPE_TYPE_BYTE | PIPE_NOWAIT,
Bram Moolenaar24058382019-01-24 23:11:49 +01005891 1, MAX_NAMED_PIPE_SIZE, 0, 0, NULL);
Bram Moolenaarb091f302019-01-19 14:37:00 +01005892
5893 if (handles[1] == INVALID_HANDLE_VALUE)
5894 return FALSE;
5895
5896 sa.nLength = sizeof(sa);
5897 sa.bInheritHandle = TRUE;
5898 sa.lpSecurityDescriptor = NULL;
5899
5900 handles[0] = CreateFile(name,
5901 FILE_GENERIC_READ,
5902 FILE_SHARE_READ, &sa,
5903 OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
5904
5905 if (handles[0] == INVALID_HANDLE_VALUE)
5906 {
Bram Moolenaar6982f422019-02-16 16:48:01 +01005907 CloseHandle(handles[1]);
Bram Moolenaarb091f302019-01-19 14:37:00 +01005908 return FALSE;
5909 }
5910
5911 return TRUE;
5912}
5913
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005914 void
Bram Moolenaar5a1feb82017-07-22 18:04:08 +02005915mch_job_start(char *cmd, job_T *job, jobopt_T *options)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005916{
5917 STARTUPINFO si;
5918 PROCESS_INFORMATION pi;
Bram Moolenaar14207f42016-10-27 21:13:10 +02005919 HANDLE jo;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005920 SECURITY_ATTRIBUTES saAttr;
5921 channel_T *channel = NULL;
Bram Moolenaard8070362016-02-15 21:56:54 +01005922 HANDLE ifd[2];
5923 HANDLE ofd[2];
5924 HANDLE efd[2];
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005925 garray_T ga;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005926
5927 int use_null_for_in = options->jo_io[PART_IN] == JIO_NULL;
5928 int use_null_for_out = options->jo_io[PART_OUT] == JIO_NULL;
5929 int use_null_for_err = options->jo_io[PART_ERR] == JIO_NULL;
5930 int use_file_for_in = options->jo_io[PART_IN] == JIO_FILE;
5931 int use_file_for_out = options->jo_io[PART_OUT] == JIO_FILE;
5932 int use_file_for_err = options->jo_io[PART_ERR] == JIO_FILE;
5933 int use_out_for_err = options->jo_io[PART_ERR] == JIO_OUT;
5934
5935 if (use_out_for_err && use_null_for_out)
5936 use_null_for_err = TRUE;
Bram Moolenaard8070362016-02-15 21:56:54 +01005937
5938 ifd[0] = INVALID_HANDLE_VALUE;
5939 ifd[1] = INVALID_HANDLE_VALUE;
5940 ofd[0] = INVALID_HANDLE_VALUE;
5941 ofd[1] = INVALID_HANDLE_VALUE;
5942 efd[0] = INVALID_HANDLE_VALUE;
5943 efd[1] = INVALID_HANDLE_VALUE;
Bram Moolenaar04935fb2022-01-08 16:19:22 +00005944 ga_init2(&ga, sizeof(wchar_t), 500);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005945
Bram Moolenaar14207f42016-10-27 21:13:10 +02005946 jo = CreateJobObject(NULL, NULL);
5947 if (jo == NULL)
5948 {
5949 job->jv_status = JOB_FAILED;
5950 goto failed;
5951 }
5952
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005953 if (options->jo_env != NULL)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005954 win32_build_env(options->jo_env, &ga, FALSE);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005955
Bram Moolenaar76467df2016-02-12 19:30:26 +01005956 ZeroMemory(&pi, sizeof(pi));
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005957 ZeroMemory(&si, sizeof(si));
5958 si.cb = sizeof(si);
Bram Moolenaard8070362016-02-15 21:56:54 +01005959 si.dwFlags |= STARTF_USESHOWWINDOW;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005960 si.wShowWindow = SW_HIDE;
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005961
Bram Moolenaard8070362016-02-15 21:56:54 +01005962 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
5963 saAttr.bInheritHandle = TRUE;
5964 saAttr.lpSecurityDescriptor = NULL;
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005965
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005966 if (use_file_for_in)
5967 {
5968 char_u *fname = options->jo_io_name[PART_IN];
5969
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005970 ifd[0] = job_io_file_open(fname, GENERIC_READ,
5971 FILE_SHARE_READ | FILE_SHARE_WRITE,
5972 &saAttr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL);
5973 if (ifd[0] == INVALID_HANDLE_VALUE)
Bram Moolenaar94d01912016-03-08 13:48:51 +01005974 {
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00005975 semsg(_(e_cant_open_file_str), fname);
Bram Moolenaar94d01912016-03-08 13:48:51 +01005976 goto failed;
5977 }
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005978 }
Bram Moolenaarb091f302019-01-19 14:37:00 +01005979 else if (!use_null_for_in
5980 && (!create_pipe_pair(ifd)
5981 || !SetHandleInformation(ifd[1], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005982 goto failed;
5983
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005984 if (use_file_for_out)
5985 {
5986 char_u *fname = options->jo_io_name[PART_OUT];
5987
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005988 ofd[1] = job_io_file_open(fname, GENERIC_WRITE,
5989 FILE_SHARE_READ | FILE_SHARE_WRITE,
5990 &saAttr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL);
5991 if (ofd[1] == INVALID_HANDLE_VALUE)
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005992 {
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00005993 semsg(_(e_cant_open_file_str), fname);
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005994 goto failed;
5995 }
5996 }
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005997 else if (!use_null_for_out &&
5998 (!CreatePipe(&ofd[0], &ofd[1], &saAttr, 0)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005999 || !SetHandleInformation(ofd[0], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01006000 goto failed;
6001
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01006002 if (use_file_for_err)
6003 {
6004 char_u *fname = options->jo_io_name[PART_ERR];
6005
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01006006 efd[1] = job_io_file_open(fname, GENERIC_WRITE,
6007 FILE_SHARE_READ | FILE_SHARE_WRITE,
6008 &saAttr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL);
6009 if (efd[1] == INVALID_HANDLE_VALUE)
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01006010 {
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00006011 semsg(_(e_cant_open_file_str), fname);
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01006012 goto failed;
6013 }
6014 }
Bram Moolenaard5d3d302016-03-09 20:54:51 +01006015 else if (!use_out_for_err && !use_null_for_err &&
6016 (!CreatePipe(&efd[0], &efd[1], &saAttr, 0)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006017 || !SetHandleInformation(efd[0], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaard8070362016-02-15 21:56:54 +01006018 goto failed;
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01006019
Bram Moolenaard8070362016-02-15 21:56:54 +01006020 si.dwFlags |= STARTF_USESTDHANDLES;
6021 si.hStdInput = ifd[0];
Bram Moolenaard5d3d302016-03-09 20:54:51 +01006022 si.hStdOutput = ofd[1];
6023 si.hStdError = use_out_for_err ? ofd[1] : efd[1];
6024
6025 if (!use_null_for_in || !use_null_for_out || !use_null_for_err)
6026 {
Bram Moolenaarde279892016-03-11 22:19:44 +01006027 if (options->jo_set & JO_CHANNEL)
6028 {
6029 channel = options->jo_channel;
6030 if (channel != NULL)
6031 ++channel->ch_refcount;
6032 }
6033 else
6034 channel = add_channel();
Bram Moolenaard5d3d302016-03-09 20:54:51 +01006035 if (channel == NULL)
6036 goto failed;
6037 }
Bram Moolenaard8070362016-02-15 21:56:54 +01006038
6039 if (!vim_create_process(cmd, TRUE,
Bram Moolenaar14207f42016-10-27 21:13:10 +02006040 CREATE_SUSPENDED |
Bram Moolenaar942d6b22016-02-07 19:57:16 +01006041 CREATE_DEFAULT_ERROR_MODE |
6042 CREATE_NEW_PROCESS_GROUP |
Bram Moolenaar05aafed2017-08-11 19:12:11 +02006043 CREATE_UNICODE_ENVIRONMENT |
Bram Moolenaar76467df2016-02-12 19:30:26 +01006044 CREATE_NEW_CONSOLE,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02006045 &si, &pi,
6046 ga.ga_data,
6047 (char *)options->jo_cwd))
Bram Moolenaar76467df2016-02-12 19:30:26 +01006048 {
Bram Moolenaar14207f42016-10-27 21:13:10 +02006049 CloseHandle(jo);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01006050 job->jv_status = JOB_FAILED;
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01006051 goto failed;
Bram Moolenaar76467df2016-02-12 19:30:26 +01006052 }
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01006053
Bram Moolenaar05aafed2017-08-11 19:12:11 +02006054 ga_clear(&ga);
6055
Bram Moolenaar14207f42016-10-27 21:13:10 +02006056 if (!AssignProcessToJobObject(jo, pi.hProcess))
6057 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006058 // if failing, switch the way to terminate
6059 // process with TerminateProcess.
Bram Moolenaar14207f42016-10-27 21:13:10 +02006060 CloseHandle(jo);
6061 jo = NULL;
6062 }
6063 ResumeThread(pi.hThread);
Bram Moolenaar75578a32016-03-10 16:33:31 +01006064 CloseHandle(pi.hThread);
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01006065 job->jv_proc_info = pi;
Bram Moolenaar14207f42016-10-27 21:13:10 +02006066 job->jv_job_object = jo;
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01006067 job->jv_status = JOB_STARTED;
6068
Bram Moolenaar641ad6c2016-09-01 18:32:11 +02006069 CloseHandle(ifd[0]);
6070 CloseHandle(ofd[1]);
6071 if (!use_out_for_err && !use_null_for_err)
Bram Moolenaarc25558b2016-03-03 21:02:23 +01006072 CloseHandle(efd[1]);
Bram Moolenaard8070362016-02-15 21:56:54 +01006073
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01006074 job->jv_channel = channel;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01006075 if (channel != NULL)
6076 {
6077 channel_set_pipes(channel,
6078 use_file_for_in || use_null_for_in
6079 ? INVALID_FD : (sock_T)ifd[1],
6080 use_file_for_out || use_null_for_out
6081 ? INVALID_FD : (sock_T)ofd[0],
6082 use_out_for_err || use_file_for_err || use_null_for_err
6083 ? INVALID_FD : (sock_T)efd[0]);
6084 channel_set_job(channel, job, options);
Bram Moolenaard5d3d302016-03-09 20:54:51 +01006085 }
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01006086 return;
6087
6088failed:
Bram Moolenaard8070362016-02-15 21:56:54 +01006089 CloseHandle(ifd[0]);
6090 CloseHandle(ofd[0]);
6091 CloseHandle(efd[0]);
6092 CloseHandle(ifd[1]);
6093 CloseHandle(ofd[1]);
6094 CloseHandle(efd[1]);
Bram Moolenaarde279892016-03-11 22:19:44 +01006095 channel_unref(channel);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02006096 ga_clear(&ga);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01006097}
6098
6099 char *
6100mch_job_status(job_T *job)
6101{
6102 DWORD dwExitCode = 0;
6103
Bram Moolenaar76467df2016-02-12 19:30:26 +01006104 if (!GetExitCodeProcess(job->jv_proc_info.hProcess, &dwExitCode)
6105 || dwExitCode != STILL_ACTIVE)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01006106 {
Bram Moolenaareab089d2016-02-21 19:32:02 +01006107 job->jv_exitval = (int)dwExitCode;
Bram Moolenaar7df915d2016-11-17 17:25:32 +01006108 if (job->jv_status < JOB_ENDED)
Bram Moolenaar97792de2016-10-15 18:36:49 +02006109 {
6110 ch_log(job->jv_channel, "Job ended");
6111 job->jv_status = JOB_ENDED;
6112 }
Bram Moolenaar942d6b22016-02-07 19:57:16 +01006113 return "dead";
6114 }
6115 return "run";
6116}
6117
Bram Moolenaar97792de2016-10-15 18:36:49 +02006118 job_T *
6119mch_detect_ended_job(job_T *job_list)
6120{
6121 HANDLE jobHandles[MAXIMUM_WAIT_OBJECTS];
6122 job_T *jobArray[MAXIMUM_WAIT_OBJECTS];
6123 job_T *job = job_list;
6124
6125 while (job != NULL)
6126 {
6127 DWORD n;
6128 DWORD result;
6129
6130 for (n = 0; n < MAXIMUM_WAIT_OBJECTS
6131 && job != NULL; job = job->jv_next)
6132 {
6133 if (job->jv_status == JOB_STARTED)
6134 {
6135 jobHandles[n] = job->jv_proc_info.hProcess;
6136 jobArray[n] = job;
6137 ++n;
6138 }
6139 }
6140 if (n == 0)
6141 continue;
6142 result = WaitForMultipleObjects(n, jobHandles, FALSE, 0);
6143 if (result >= WAIT_OBJECT_0 && result < WAIT_OBJECT_0 + n)
6144 {
6145 job_T *wait_job = jobArray[result - WAIT_OBJECT_0];
6146
6147 if (STRCMP(mch_job_status(wait_job), "dead") == 0)
6148 return wait_job;
6149 }
6150 }
6151 return NULL;
6152}
6153
Bram Moolenaarfb630902016-10-29 14:55:00 +02006154 static BOOL
6155terminate_all(HANDLE process, int code)
6156{
6157 PROCESSENTRY32 pe;
6158 HANDLE h = INVALID_HANDLE_VALUE;
6159 DWORD pid = GetProcessId(process);
6160
6161 if (pid != 0)
6162 {
6163 h = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
6164 if (h != INVALID_HANDLE_VALUE)
6165 {
6166 pe.dwSize = sizeof(PROCESSENTRY32);
6167 if (!Process32First(h, &pe))
6168 goto theend;
6169
6170 do
6171 {
6172 if (pe.th32ParentProcessID == pid)
6173 {
6174 HANDLE ph = OpenProcess(
6175 PROCESS_ALL_ACCESS, FALSE, pe.th32ProcessID);
6176 if (ph != NULL)
6177 {
6178 terminate_all(ph, code);
6179 CloseHandle(ph);
6180 }
6181 }
6182 } while (Process32Next(h, &pe));
6183
6184 CloseHandle(h);
6185 }
6186 }
6187
6188theend:
6189 return TerminateProcess(process, code);
6190}
6191
6192/*
6193 * Send a (deadly) signal to "job".
6194 * Return FAIL if it didn't work.
6195 */
Bram Moolenaar942d6b22016-02-07 19:57:16 +01006196 int
Bram Moolenaar2d33e902017-08-11 16:31:54 +02006197mch_signal_job(job_T *job, char_u *how)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01006198{
Bram Moolenaar923d9262016-02-25 20:56:01 +01006199 int ret;
Bram Moolenaar76467df2016-02-12 19:30:26 +01006200
Bram Moolenaar923d9262016-02-25 20:56:01 +01006201 if (STRCMP(how, "term") == 0 || STRCMP(how, "kill") == 0 || *how == NUL)
Bram Moolenaar76467df2016-02-12 19:30:26 +01006202 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006203 // deadly signal
Bram Moolenaar14207f42016-10-27 21:13:10 +02006204 if (job->jv_job_object != NULL)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006205 {
6206 if (job->jv_channel != NULL && job->jv_channel->ch_anonymous_pipe)
6207 job->jv_channel->ch_killing = TRUE;
K.Takata135e1522022-01-29 15:27:58 +00006208 return TerminateJobObject(job->jv_job_object, (UINT)-1) ? OK : FAIL;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006209 }
Bram Moolenaarb3e195c2020-02-10 21:32:19 +01006210 return terminate_all(job->jv_proc_info.hProcess, -1) ? OK : FAIL;
Bram Moolenaar76467df2016-02-12 19:30:26 +01006211 }
6212
6213 if (!AttachConsole(job->jv_proc_info.dwProcessId))
6214 return FAIL;
6215 ret = GenerateConsoleCtrlEvent(
Bram Moolenaar923d9262016-02-25 20:56:01 +01006216 STRCMP(how, "int") == 0 ? CTRL_C_EVENT : CTRL_BREAK_EVENT,
6217 job->jv_proc_info.dwProcessId)
6218 ? OK : FAIL;
Bram Moolenaar76467df2016-02-12 19:30:26 +01006219 FreeConsole();
6220 return ret;
6221}
6222
6223/*
6224 * Clear the data related to "job".
6225 */
6226 void
6227mch_clear_job(job_T *job)
6228{
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00006229 if (job->jv_status == JOB_FAILED)
6230 return;
6231
6232 if (job->jv_job_object != NULL)
6233 CloseHandle(job->jv_job_object);
6234 CloseHandle(job->jv_proc_info.hProcess);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01006235}
6236#endif
6237
Bram Moolenaar071d4272004-06-13 20:20:40 +00006238
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006239#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006240
6241/*
6242 * Start termcap mode
6243 */
6244 static void
6245termcap_mode_start(void)
6246{
6247 DWORD cmodein;
6248
6249 if (g_fTermcapMode)
6250 return;
6251
6252 SaveConsoleBuffer(&g_cbNonTermcap);
6253
6254 if (g_cbTermcap.IsValid)
6255 {
6256 /*
6257 * We've been in termcap mode before. Restore certain screen
6258 * characteristics, including the buffer size and the window
6259 * size. Since we will be redrawing the screen, we don't need
6260 * to restore the actual contents of the buffer.
6261 */
6262 RestoreConsoleBuffer(&g_cbTermcap, FALSE);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006263 reset_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00006264 SetConsoleWindowInfo(g_hConOut, TRUE, &g_cbTermcap.Info.srWindow);
6265 Rows = g_cbTermcap.Info.dwSize.Y;
6266 Columns = g_cbTermcap.Info.dwSize.X;
6267 }
6268 else
6269 {
6270 /*
6271 * This is our first time entering termcap mode. Clear the console
6272 * screen buffer, and resize the buffer to match the current window
6273 * size. We will use this as the size of our editing environment.
6274 */
6275 ClearConsoleBuffer(g_attrCurrent);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006276 set_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00006277 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
6278 }
6279
Bram Moolenaar071d4272004-06-13 20:20:40 +00006280 resettitle();
Bram Moolenaar071d4272004-06-13 20:20:40 +00006281
6282 GetConsoleMode(g_hConIn, &cmodein);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006283 if (g_fMouseActive)
Wez Furlong6ef5ab52021-05-30 19:29:41 +02006284 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006285 cmodein |= ENABLE_MOUSE_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02006286 cmodein &= ~ENABLE_QUICK_EDIT_MODE;
6287 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006288 else
Wez Furlong6ef5ab52021-05-30 19:29:41 +02006289 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006290 cmodein &= ~ENABLE_MOUSE_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02006291 cmodein |= g_cmodein & ENABLE_QUICK_EDIT_MODE;
6292 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006293 cmodein |= ENABLE_WINDOW_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02006294 SetConsoleMode(g_hConIn, cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006295
6296 redraw_later_clear();
6297 g_fTermcapMode = TRUE;
6298}
6299
6300
6301/*
6302 * End termcap mode
6303 */
6304 static void
6305termcap_mode_end(void)
6306{
6307 DWORD cmodein;
6308 ConsoleBuffer *cb;
6309 COORD coord;
6310 DWORD dwDummy;
6311
6312 if (!g_fTermcapMode)
6313 return;
6314
6315 SaveConsoleBuffer(&g_cbTermcap);
6316
6317 GetConsoleMode(g_hConIn, &cmodein);
6318 cmodein &= ~(ENABLE_MOUSE_INPUT | ENABLE_WINDOW_INPUT);
Wez Furlong6ef5ab52021-05-30 19:29:41 +02006319 cmodein |= g_cmodein & ENABLE_QUICK_EDIT_MODE;
6320 SetConsoleMode(g_hConIn, cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006321
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006322# ifdef FEAT_RESTORE_ORIG_SCREEN
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01006323 cb = exiting ? &g_cbOrig : &g_cbNonTermcap;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006324# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00006325 cb = &g_cbNonTermcap;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006326# endif
Bram Moolenaar81ccbf12020-04-15 21:05:30 +02006327 RestoreConsoleBuffer(cb, p_rs);
Bram Moolenaardf543822020-01-30 11:53:59 +01006328 restore_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00006329
Christopher Plewright1140b512022-11-12 18:46:05 +00006330 // Switch back to main screen buffer.
Christopher Plewrightc8b126d2022-12-22 13:45:23 +00006331 if (exiting && use_alternate_screen_buffer)
Christopher Plewright1140b512022-11-12 18:46:05 +00006332 vtp_printf("\033[?1049l");
6333
6334 if (!USE_WT && (p_rs || exiting))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006335 {
6336 /*
6337 * Clear anything that happens to be on the current line.
6338 */
6339 coord.X = 0;
6340 coord.Y = (SHORT) (p_rs ? cb->Info.dwCursorPosition.Y : (Rows - 1));
Christopher Plewrightf75a2cb2023-01-28 10:28:09 +00006341 FillConsoleOutputCharacter(g_hConOut, ' ',
6342 cb->Info.dwSize.X, coord, &dwDummy);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006343 /*
6344 * The following is just for aesthetics. If we are exiting without
6345 * restoring the screen, then we want to have a prompt string
6346 * appear at the bottom line. However, the command interpreter
6347 * seems to always advance the cursor one line before displaying
6348 * the prompt string, which causes the screen to scroll. To
6349 * counter this, move the cursor up one line before exiting.
6350 */
6351 if (exiting && !p_rs)
6352 coord.Y--;
6353 /*
6354 * Position the cursor at the leftmost column of the desired row.
6355 */
Bram Moolenaar81ccbf12020-04-15 21:05:30 +02006356 SetConsoleCursorPosition(g_hConOut, coord);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006357 }
Christopher Plewright1140b512022-11-12 18:46:05 +00006358 SetConsoleCursorInfo(g_hConOut, &g_cci);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006359 g_fTermcapMode = FALSE;
6360}
Christopher Plewright38804d62022-11-09 23:55:52 +00006361#endif // !FEAT_GUI_MSWIN || VIMDLL
Bram Moolenaar071d4272004-06-13 20:20:40 +00006362
6363
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006364#if defined(FEAT_GUI_MSWIN) && !defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006365 void
6366mch_write(
Bram Moolenaar1266d672017-02-01 13:43:36 +01006367 char_u *s UNUSED,
6368 int len UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006369{
Bram Moolenaar0f873732019-12-05 20:28:46 +01006370 // never used
Bram Moolenaar071d4272004-06-13 20:20:40 +00006371}
6372
6373#else
6374
6375/*
6376 * clear `n' chars, starting from `coord'
6377 */
6378 static void
6379clear_chars(
6380 COORD coord,
6381 DWORD n)
6382{
Christopher Plewright38804d62022-11-09 23:55:52 +00006383 if (!vtp_working)
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006384 {
6385 DWORD dwDummy;
6386
6387 FillConsoleOutputCharacter(g_hConOut, ' ', n, coord, &dwDummy);
6388 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, n, coord,
6389 &dwDummy);
6390 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006391 else
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02006392 {
6393 set_console_color_rgb();
6394 gotoxy(coord.X + 1, coord.Y + 1);
6395 vtp_printf("\033[%dX", n);
6396 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006397}
6398
6399
6400/*
6401 * Clear the screen
6402 */
6403 static void
6404clear_screen(void)
6405{
6406 g_coord.X = g_coord.Y = 0;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006407
Christopher Plewright38804d62022-11-09 23:55:52 +00006408 if (!vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006409 clear_chars(g_coord, Rows * Columns);
6410 else
6411 {
6412 set_console_color_rgb();
6413 gotoxy(1, 1);
6414 vtp_printf("\033[2J");
6415 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006416}
6417
6418
6419/*
6420 * Clear to end of display
6421 */
6422 static void
6423clear_to_end_of_display(void)
6424{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006425 COORD save = g_coord;
6426
Christopher Plewright38804d62022-11-09 23:55:52 +00006427 if (!vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006428 clear_chars(g_coord, (Rows - g_coord.Y - 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006429 * Columns + (Columns - g_coord.X));
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006430 else
6431 {
6432 set_console_color_rgb();
6433 gotoxy(g_coord.X + 1, g_coord.Y + 1);
6434 vtp_printf("\033[0J");
6435
6436 gotoxy(save.X + 1, save.Y + 1);
6437 g_coord = save;
6438 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006439}
6440
6441
6442/*
6443 * Clear to end of line
6444 */
6445 static void
6446clear_to_end_of_line(void)
6447{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006448 COORD save = g_coord;
6449
Christopher Plewright38804d62022-11-09 23:55:52 +00006450 if (!vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006451 clear_chars(g_coord, Columns - g_coord.X);
6452 else
6453 {
6454 set_console_color_rgb();
6455 gotoxy(g_coord.X + 1, g_coord.Y + 1);
6456 vtp_printf("\033[0K");
6457
6458 gotoxy(save.X + 1, save.Y + 1);
6459 g_coord = save;
6460 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006461}
6462
6463
6464/*
6465 * Scroll the scroll region up by `cLines' lines
6466 */
6467 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006468scroll(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006469{
6470 COORD oldcoord = g_coord;
6471
6472 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
6473 delete_lines(cLines);
6474
6475 g_coord = oldcoord;
6476}
6477
6478
6479/*
6480 * Set the scroll region
6481 */
6482 static void
6483set_scroll_region(
6484 unsigned left,
6485 unsigned top,
6486 unsigned right,
6487 unsigned bottom)
6488{
6489 if (left >= right
6490 || top >= bottom
6491 || right > (unsigned) Columns - 1
6492 || bottom > (unsigned) Rows - 1)
6493 return;
6494
6495 g_srScrollRegion.Left = left;
6496 g_srScrollRegion.Top = top;
6497 g_srScrollRegion.Right = right;
6498 g_srScrollRegion.Bottom = bottom;
Bram Moolenaar6982f422019-02-16 16:48:01 +01006499}
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006500
Bram Moolenaar6982f422019-02-16 16:48:01 +01006501 static void
6502set_scroll_region_tb(
6503 unsigned top,
6504 unsigned bottom)
6505{
6506 if (top >= bottom || bottom > (unsigned)Rows - 1)
6507 return;
6508
6509 g_srScrollRegion.Top = top;
6510 g_srScrollRegion.Bottom = bottom;
6511}
6512
6513 static void
6514set_scroll_region_lr(
6515 unsigned left,
6516 unsigned right)
6517{
6518 if (left >= right || right > (unsigned)Columns - 1)
6519 return;
6520
6521 g_srScrollRegion.Left = left;
6522 g_srScrollRegion.Right = right;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006523}
6524
6525
6526/*
6527 * Insert `cLines' lines at the current cursor position
6528 */
6529 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006530insert_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006531{
Bram Moolenaar6982f422019-02-16 16:48:01 +01006532 SMALL_RECT source, clip;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006533 COORD dest;
6534 CHAR_INFO fill;
6535
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006536 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
6537
Bram Moolenaar6982f422019-02-16 16:48:01 +01006538 dest.X = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006539 dest.Y = g_coord.Y + cLines;
6540
Bram Moolenaar6982f422019-02-16 16:48:01 +01006541 source.Left = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006542 source.Top = g_coord.Y;
6543 source.Right = g_srScrollRegion.Right;
6544 source.Bottom = g_srScrollRegion.Bottom - cLines;
6545
Bram Moolenaar6982f422019-02-16 16:48:01 +01006546 clip.Left = g_srScrollRegion.Left;
6547 clip.Top = g_coord.Y;
6548 clip.Right = g_srScrollRegion.Right;
6549 clip.Bottom = g_srScrollRegion.Bottom;
6550
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006551 fill.Char.AsciiChar = ' ';
Christopher Plewrightf75a2cb2023-01-28 10:28:09 +00006552 if (!USE_VTP)
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006553 fill.Attributes = g_attrCurrent;
6554 else
6555 fill.Attributes = g_attrDefault;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006556
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006557 set_console_color_rgb();
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006558
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006559 ScrollConsoleScreenBuffer(g_hConOut, &source, &clip, dest, &fill);
6560
Bram Moolenaar6982f422019-02-16 16:48:01 +01006561 // Here we have to deal with a win32 console flake: If the scroll
6562 // region looks like abc and we scroll c to a and fill with d we get
6563 // cbd... if we scroll block c one line at a time to a, we get cdd...
6564 // vim expects cdd consistently... So we have to deal with that
6565 // here... (this also occurs scrolling the same way in the other
6566 // direction).
Bram Moolenaar071d4272004-06-13 20:20:40 +00006567
6568 if (source.Bottom < dest.Y)
6569 {
6570 COORD coord;
Bram Moolenaar6982f422019-02-16 16:48:01 +01006571 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006572
Bram Moolenaar6982f422019-02-16 16:48:01 +01006573 coord.X = source.Left;
6574 for (i = clip.Top; i < dest.Y; ++i)
6575 {
6576 coord.Y = i;
6577 clear_chars(coord, source.Right - source.Left + 1);
6578 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006579 }
Bram Moolenaar06b7b582020-05-30 17:49:25 +02006580
Christopher Plewright38804d62022-11-09 23:55:52 +00006581 if (vtp_working)
Bram Moolenaar06b7b582020-05-30 17:49:25 +02006582 {
6583 COORD coord;
6584 int i;
6585
6586 coord.X = source.Left;
6587 for (i = source.Top; i < dest.Y; ++i)
6588 {
6589 coord.Y = i;
6590 clear_chars(coord, source.Right - source.Left + 1);
6591 }
6592 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006593}
6594
6595
6596/*
6597 * Delete `cLines' lines at the current cursor position
6598 */
6599 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006600delete_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006601{
Bram Moolenaar6982f422019-02-16 16:48:01 +01006602 SMALL_RECT source, clip;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006603 COORD dest;
6604 CHAR_INFO fill;
6605 int nb;
6606
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006607 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
6608
Bram Moolenaar6982f422019-02-16 16:48:01 +01006609 dest.X = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006610 dest.Y = g_coord.Y;
6611
Bram Moolenaar6982f422019-02-16 16:48:01 +01006612 source.Left = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006613 source.Top = g_coord.Y + cLines;
6614 source.Right = g_srScrollRegion.Right;
6615 source.Bottom = g_srScrollRegion.Bottom;
6616
Bram Moolenaar6982f422019-02-16 16:48:01 +01006617 clip.Left = g_srScrollRegion.Left;
6618 clip.Top = g_coord.Y;
6619 clip.Right = g_srScrollRegion.Right;
6620 clip.Bottom = g_srScrollRegion.Bottom;
6621
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006622 fill.Char.AsciiChar = ' ';
Christopher Plewright38804d62022-11-09 23:55:52 +00006623 if (!vtp_working)
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006624 fill.Attributes = g_attrCurrent;
6625 else
6626 fill.Attributes = g_attrDefault;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006627
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006628 set_console_color_rgb();
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006629
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006630 ScrollConsoleScreenBuffer(g_hConOut, &source, &clip, dest, &fill);
6631
Bram Moolenaar6982f422019-02-16 16:48:01 +01006632 // Here we have to deal with a win32 console flake; See insert_lines()
6633 // above.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006634
6635 nb = dest.Y + (source.Bottom - source.Top) + 1;
6636
6637 if (nb < source.Top)
6638 {
6639 COORD coord;
Bram Moolenaar6982f422019-02-16 16:48:01 +01006640 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006641
Bram Moolenaar6982f422019-02-16 16:48:01 +01006642 coord.X = source.Left;
6643 for (i = nb; i < clip.Bottom; ++i)
6644 {
6645 coord.Y = i;
6646 clear_chars(coord, source.Right - source.Left + 1);
6647 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006648 }
Bram Moolenaar06b7b582020-05-30 17:49:25 +02006649
Christopher Plewright38804d62022-11-09 23:55:52 +00006650 if (vtp_working)
Bram Moolenaar06b7b582020-05-30 17:49:25 +02006651 {
6652 COORD coord;
6653 int i;
6654
6655 coord.X = source.Left;
6656 for (i = nb; i <= source.Bottom; ++i)
6657 {
6658 coord.Y = i;
6659 clear_chars(coord, source.Right - source.Left + 1);
6660 }
6661 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006662}
6663
6664
6665/*
Bram Moolenaar2313b612019-09-27 14:14:32 +02006666 * Set the cursor position to (x,y) (1-based).
Bram Moolenaar071d4272004-06-13 20:20:40 +00006667 */
6668 static void
6669gotoxy(
6670 unsigned x,
6671 unsigned y)
6672{
6673 if (x < 1 || x > (unsigned)Columns || y < 1 || y > (unsigned)Rows)
6674 return;
6675
Christopher Plewrightf75a2cb2023-01-28 10:28:09 +00006676 if (!USE_VTP)
Bram Moolenaar2313b612019-09-27 14:14:32 +02006677 {
Bram Moolenaar82e743c2020-03-26 15:39:53 +01006678 // There are reports of double-width characters not displayed
6679 // correctly. This workaround should fix it, similar to how it's done
6680 // for VTP.
6681 g_coord.X = 0;
6682 SetConsoleCursorPosition(g_hConOut, g_coord);
6683
Bram Moolenaar2313b612019-09-27 14:14:32 +02006684 // external cursor coords are 1-based; internal are 0-based
6685 g_coord.X = x - 1;
6686 g_coord.Y = y - 1;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006687 SetConsoleCursorPosition(g_hConOut, g_coord);
Bram Moolenaar2313b612019-09-27 14:14:32 +02006688 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006689 else
Bram Moolenaar2313b612019-09-27 14:14:32 +02006690 {
6691 // Move the cursor to the left edge of the screen to prevent screen
Bram Moolenaara1299742019-10-10 16:36:00 +02006692 // destruction. Insider build bug. Always enabled because it's cheap
6693 // and avoids mistakes with recognizing the build.
6694 vtp_printf("\033[%d;%dH", g_coord.Y + 1, 1);
Bram Moolenaar2313b612019-09-27 14:14:32 +02006695
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006696 vtp_printf("\033[%d;%dH", y, x);
Bram Moolenaar2313b612019-09-27 14:14:32 +02006697
6698 g_coord.X = x - 1;
6699 g_coord.Y = y - 1;
6700 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006701}
6702
6703
6704/*
6705 * Set the current text attribute = (foreground | background)
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006706 * See ../runtime/doc/os_win32.txt for the numbers.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006707 */
6708 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006709textattr(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006710{
Bram Moolenaar6383b922015-03-24 17:12:19 +01006711 g_attrCurrent = wAttr & 0xff;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006712
6713 SetConsoleTextAttribute(g_hConOut, wAttr);
6714}
6715
6716
6717 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006718textcolor(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006719{
Bram Moolenaar6383b922015-03-24 17:12:19 +01006720 g_attrCurrent = (g_attrCurrent & 0xf0) + (wAttr & 0x0f);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006721
Christopher Plewright38804d62022-11-09 23:55:52 +00006722 if (!vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006723 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
6724 else
6725 vtp_sgr_bulk(wAttr);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006726}
6727
6728
6729 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006730textbackground(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006731{
Bram Moolenaar6383b922015-03-24 17:12:19 +01006732 g_attrCurrent = (g_attrCurrent & 0x0f) + ((wAttr & 0x0f) << 4);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006733
Christopher Plewright38804d62022-11-09 23:55:52 +00006734 if (!vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006735 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
6736 else
6737 vtp_sgr_bulk(wAttr);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006738}
6739
6740
6741/*
6742 * restore the default text attribute (whatever we started with)
6743 */
6744 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006745normvideo(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006746{
Christopher Plewright38804d62022-11-09 23:55:52 +00006747 if (!vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006748 textattr(g_attrDefault);
6749 else
6750 vtp_sgr_bulk(0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006751}
6752
6753
6754static WORD g_attrPreStandout = 0;
6755
6756/*
6757 * Make the text standout, by brightening it
6758 */
6759 static void
6760standout(void)
6761{
6762 g_attrPreStandout = g_attrCurrent;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006763
Bram Moolenaar071d4272004-06-13 20:20:40 +00006764 textattr((WORD) (g_attrCurrent|FOREGROUND_INTENSITY|BACKGROUND_INTENSITY));
6765}
6766
6767
6768/*
6769 * Turn off standout mode
6770 */
6771 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006772standend(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006773{
6774 if (g_attrPreStandout)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006775 textattr(g_attrPreStandout);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006776
6777 g_attrPreStandout = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006778}
6779
6780
6781/*
Bram Moolenaarff1d0d42007-05-10 17:24:16 +00006782 * Set normal fg/bg color, based on T_ME. Called when t_me has been set.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006783 */
6784 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006785mch_set_normal_colors(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006786{
6787 char_u *p;
6788 int n;
6789
6790 cterm_normal_fg_color = (g_attrDefault & 0xf) + 1;
6791 cterm_normal_bg_color = ((g_attrDefault >> 4) & 0xf) + 1;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006792 if (
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006793# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006794 !p_tgc &&
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006795# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006796 T_ME[0] == ESC && T_ME[1] == '|')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006797 {
6798 p = T_ME + 2;
6799 n = getdigits(&p);
6800 if (*p == 'm' && n > 0)
6801 {
6802 cterm_normal_fg_color = (n & 0xf) + 1;
6803 cterm_normal_bg_color = ((n >> 4) & 0xf) + 1;
6804 }
6805 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006806# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006807 cterm_normal_fg_gui_color = INVALCOLOR;
6808 cterm_normal_bg_gui_color = INVALCOLOR;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006809# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006810}
6811
6812
6813/*
6814 * visual bell: flash the screen
6815 */
6816 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006817visual_bell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006818{
6819 COORD coordOrigin = {0, 0};
6820 WORD attrFlash = ~g_attrCurrent & 0xff;
6821
6822 DWORD dwDummy;
Christopher Plewrightdc7179f2023-01-23 12:33:23 +00006823 LPWORD oldattrs = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006824
Christopher Plewrightdc7179f2023-01-23 12:33:23 +00006825# ifdef FEAT_TERMGUICOLORS
6826 if (!(p_tgc || t_colors >= 256))
6827# endif
6828 {
6829 oldattrs = ALLOC_MULT(WORD, Rows * Columns);
6830 if (oldattrs == NULL)
6831 return;
6832 ReadConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
Bram Moolenaar071d4272004-06-13 20:20:40 +00006833 coordOrigin, &dwDummy);
Christopher Plewrightdc7179f2023-01-23 12:33:23 +00006834 }
6835
Bram Moolenaar071d4272004-06-13 20:20:40 +00006836 FillConsoleOutputAttribute(g_hConOut, attrFlash, Rows * Columns,
6837 coordOrigin, &dwDummy);
6838
Bram Moolenaar0f873732019-12-05 20:28:46 +01006839 Sleep(15); // wait for 15 msec
Christopher Plewrightdc7179f2023-01-23 12:33:23 +00006840
6841 if (oldattrs != NULL)
6842 {
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006843 WriteConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
Bram Moolenaar071d4272004-06-13 20:20:40 +00006844 coordOrigin, &dwDummy);
Christopher Plewrightdc7179f2023-01-23 12:33:23 +00006845 vim_free(oldattrs);
6846 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006847}
6848
6849
6850/*
6851 * Make the cursor visible or invisible
6852 */
6853 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006854cursor_visible(BOOL fVisible)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006855{
6856 s_cursor_visible = fVisible;
Bram Moolenaar2695de62020-04-17 21:13:01 +02006857
Christopher Plewright38804d62022-11-09 23:55:52 +00006858 if (vtp_working)
Bram Moolenaar2695de62020-04-17 21:13:01 +02006859 vtp_printf("\033[?25%c", fVisible ? 'h' : 'l');
6860
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006861# ifdef MCH_CURSOR_SHAPE
Bram Moolenaar071d4272004-06-13 20:20:40 +00006862 mch_update_cursor();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006863# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006864}
6865
6866
6867/*
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02006868 * Write "cbToWrite" bytes in `pchBuf' to the screen.
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006869 * Returns the number of bytes actually written (at least one).
Bram Moolenaar071d4272004-06-13 20:20:40 +00006870 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006871 static DWORD
Bram Moolenaar071d4272004-06-13 20:20:40 +00006872write_chars(
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006873 char_u *pchBuf,
6874 DWORD cbToWrite)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006875{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006876 COORD coord = g_coord;
6877 DWORD written;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006878 DWORD n, cchwritten;
6879 static DWORD cells;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006880 static WCHAR *unicodebuf = NULL;
6881 static int unibuflen = 0;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006882 static int length;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006883 int cp = enc_utf8 ? CP_UTF8 : enc_codepage;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006884 static WCHAR *utf8spbuf = NULL;
6885 static int utf8splength;
6886 static DWORD utf8spcells;
6887 static WCHAR **utf8usingbuf = &unicodebuf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006888
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006889 if (cbToWrite != 1 || *pchBuf != ' ' || !enc_utf8)
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006890 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006891 utf8usingbuf = &unicodebuf;
6892 do
6893 {
6894 length = MultiByteToWideChar(cp, 0, (LPCSTR)pchBuf, cbToWrite,
6895 unicodebuf, unibuflen);
6896 if (length && length <= unibuflen)
6897 break;
6898 vim_free(unicodebuf);
6899 unicodebuf = length ? LALLOC_MULT(WCHAR, length) : NULL;
6900 unibuflen = unibuflen ? 0 : length;
Bram Moolenaarc9471b12023-05-09 15:00:00 +01006901 } while (TRUE);
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006902 cells = mb_string2cells(pchBuf, cbToWrite);
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006903 }
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006904 else // cbToWrite == 1 && *pchBuf == ' ' && enc_utf8
6905 {
6906 if (utf8usingbuf != &utf8spbuf)
6907 {
6908 if (utf8spbuf == NULL)
6909 {
6910 cells = mb_string2cells((char_u *)" ", 1);
6911 length = MultiByteToWideChar(CP_UTF8, 0, " ", 1, NULL, 0);
6912 utf8spbuf = LALLOC_MULT(WCHAR, length);
6913 if (utf8spbuf != NULL)
6914 {
6915 MultiByteToWideChar(CP_UTF8, 0, " ", 1, utf8spbuf, length);
6916 utf8usingbuf = &utf8spbuf;
6917 utf8splength = length;
6918 utf8spcells = cells;
6919 }
6920 }
6921 else
6922 {
6923 utf8usingbuf = &utf8spbuf;
6924 length = utf8splength;
6925 cells = utf8spcells;
6926 }
6927 }
6928 }
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006929
Christopher Plewrightf75a2cb2023-01-28 10:28:09 +00006930 if (!USE_VTP)
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006931 {
6932 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, cells,
6933 coord, &written);
6934 // When writing fails or didn't write a single character, pretend one
6935 // character was written, otherwise we get stuck.
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006936 if (WriteConsoleOutputCharacterW(g_hConOut, *utf8usingbuf, length,
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006937 coord, &cchwritten) == 0
6938 || cchwritten == 0 || cchwritten == (DWORD)-1)
6939 cchwritten = 1;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006940 }
6941 else
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006942 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006943 if (WriteConsoleW(g_hConOut, *utf8usingbuf, length, &cchwritten,
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006944 NULL) == 0 || cchwritten == 0)
6945 cchwritten = 1;
6946 }
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006947
K.Takata135e1522022-01-29 15:27:58 +00006948 if (cchwritten == (DWORD)length)
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006949 {
6950 written = cbToWrite;
6951 g_coord.X += (SHORT)cells;
6952 }
6953 else
6954 {
6955 char_u *p = pchBuf;
6956 for (n = 0; n < cchwritten; n++)
6957 MB_CPTR_ADV(p);
6958 written = p - pchBuf;
6959 g_coord.X += (SHORT)mb_string2cells(pchBuf, written);
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006960 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006961
6962 while (g_coord.X > g_srScrollRegion.Right)
6963 {
6964 g_coord.X -= (SHORT) Columns;
6965 if (g_coord.Y < g_srScrollRegion.Bottom)
6966 g_coord.Y++;
6967 }
6968
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006969 // Cursor under VTP is always in the correct position, no need to reset.
Christopher Plewrightf75a2cb2023-01-28 10:28:09 +00006970 if (!USE_VTP)
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006971 gotoxy(g_coord.X + 1, g_coord.Y + 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006972
6973 return written;
6974}
6975
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006976 static char_u *
6977get_seq(
6978 int *args,
6979 int *count,
6980 char_u *head)
6981{
6982 int argc;
6983 char_u *p;
6984
6985 if (head == NULL || *head != '\033')
6986 return NULL;
6987
6988 argc = 0;
6989 p = head;
6990 ++p;
6991 do
6992 {
6993 ++p;
6994 args[argc] = getdigits(&p);
6995 argc += (argc < 15) ? 1 : 0;
6996 } while (*p == ';');
6997 *count = argc;
6998
6999 return p;
7000}
7001
7002 static char_u *
7003get_sgr(
7004 int *args,
7005 int *count,
7006 char_u *head)
7007{
7008 char_u *p = get_seq(args, count, head);
7009
7010 return (p && *p == 'm') ? ++p : NULL;
7011}
7012
7013/*
7014 * Pointer to next if SGR (^[[n;2;*;*;*m), NULL otherwise.
7015 */
7016 static char_u *
7017sgrn2(
7018 char_u *head,
7019 int n)
7020{
7021 int argc;
7022 int args[16];
7023 char_u *p = get_sgr(args, &argc, head);
7024
7025 return p && argc == 5 && args[0] == n && args[1] == 2 ? p : NULL;
7026}
7027
7028/*
7029 * Pointer to next if SGR(^[[nm)<space>ESC, NULL otherwise.
7030 */
7031 static char_u *
7032sgrnc(
7033 char_u *head,
7034 int n)
7035{
7036 int argc;
7037 int args[16];
7038 char_u *p = get_sgr(args, &argc, head);
7039
7040 return p && argc == 1 && args[0] == n && (p = skipwhite(p)) && *p == '\033'
7041 ? p : NULL;
7042}
7043
7044 static char_u *
7045skipblank(char_u *q)
7046{
7047 char_u *p = q;
7048
7049 while (*p == ' ' || *p == '\t' || *p == '\n' || *p == '\r')
7050 ++p;
7051 return p;
7052}
7053
7054/*
7055 * Pointer to the next if any whitespace that may follow SGR is ESC, otherwise
7056 * NULL.
7057 */
7058 static char_u *
7059sgrn2c(
7060 char_u *head,
7061 int n)
7062{
7063 char_u *p = sgrn2(head, n);
7064
7065 return p && *p != NUL && (p = skipblank(p)) && *p == '\033' ? p : NULL;
7066}
7067
7068/*
7069 * If there is only a newline between the sequence immediately following it,
7070 * a pointer to the character following the newline is returned.
7071 * Otherwise NULL.
7072 */
7073 static char_u *
7074sgrn2cn(
7075 char_u *head,
7076 int n)
7077{
7078 char_u *p = sgrn2(head, n);
7079
7080 return p && p[0] == 0x0a && p[1] == '\033' ? ++p : NULL;
7081}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007082
7083/*
7084 * mch_write(): write the output buffer to the screen, translating ESC
7085 * sequences into calls to console output routines.
7086 */
7087 void
7088mch_write(
7089 char_u *s,
7090 int len)
7091{
Bram Moolenaard23f8bd2021-04-21 11:30:48 +02007092 char_u *end = s + len;
7093
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007094# ifdef VIMDLL
7095 if (gui.in_use)
7096 return;
7097# endif
7098
Bram Moolenaar071d4272004-06-13 20:20:40 +00007099 if (!term_console)
7100 {
7101 write(1, s, (unsigned)len);
7102 return;
7103 }
7104
Bram Moolenaar0f873732019-12-05 20:28:46 +01007105 // translate ESC | sequences into faked bios calls
Bram Moolenaar071d4272004-06-13 20:20:40 +00007106 while (len--)
7107 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007108 int prefix = -1;
7109 char_u ch;
7110
7111 // While processing a sequence, on rare occasions it seems that another
7112 // sequence may be inserted asynchronously.
7113 if (len < 0)
7114 {
Bram Moolenaara4d158b2022-08-14 14:17:45 +01007115 redraw_all_later(UPD_CLEAR);
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007116 return;
7117 }
7118
Bram Moolenaard23f8bd2021-04-21 11:30:48 +02007119 while (s + ++prefix < end)
7120 {
7121 ch = s[prefix];
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007122 if (ch <= 0x1e && !(ch != '\n' && ch != '\r' && ch != '\b'
7123 && ch != '\a' && ch != '\033'))
7124 break;
Bram Moolenaard23f8bd2021-04-21 11:30:48 +02007125 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007126
7127 if (p_wd)
7128 {
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02007129 WaitForChar(p_wd, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007130 if (prefix != 0)
7131 prefix = 1;
7132 }
7133
7134 if (prefix != 0)
7135 {
7136 DWORD nWritten;
7137
7138 nWritten = write_chars(s, prefix);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007139# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00007140 if (fdDump)
7141 {
7142 fputc('>', fdDump);
7143 fwrite(s, sizeof(char_u), nWritten, fdDump);
7144 fputs("<\n", fdDump);
7145 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007146# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007147 len -= (nWritten - 1);
7148 s += nWritten;
7149 }
7150 else if (s[0] == '\n')
7151 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007152 // \n, newline: go to the beginning of the next line or scroll
Bram Moolenaar071d4272004-06-13 20:20:40 +00007153 if (g_coord.Y == g_srScrollRegion.Bottom)
7154 {
7155 scroll(1);
7156 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Bottom + 1);
7157 }
7158 else
7159 {
7160 gotoxy(g_srScrollRegion.Left + 1, g_coord.Y + 2);
7161 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007162# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00007163 if (fdDump)
7164 fputs("\\n\n", fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007165# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007166 s++;
7167 }
7168 else if (s[0] == '\r')
7169 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007170 // \r, carriage return: go to beginning of line
Bram Moolenaar071d4272004-06-13 20:20:40 +00007171 gotoxy(g_srScrollRegion.Left+1, g_coord.Y + 1);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007172# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00007173 if (fdDump)
7174 fputs("\\r\n", fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007175# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007176 s++;
7177 }
7178 else if (s[0] == '\b')
7179 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007180 // \b, backspace: move cursor one position left
Bram Moolenaar071d4272004-06-13 20:20:40 +00007181 if (g_coord.X > g_srScrollRegion.Left)
7182 g_coord.X--;
7183 else if (g_coord.Y > g_srScrollRegion.Top)
7184 {
7185 g_coord.X = g_srScrollRegion.Right;
7186 g_coord.Y--;
7187 }
7188 gotoxy(g_coord.X + 1, g_coord.Y + 1);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007189# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00007190 if (fdDump)
7191 fputs("\\b\n", fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007192# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007193 s++;
7194 }
7195 else if (s[0] == '\a')
7196 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007197 // \a, bell
Bram Moolenaar071d4272004-06-13 20:20:40 +00007198 MessageBeep(0xFFFFFFFF);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007199# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00007200 if (fdDump)
7201 fputs("\\a\n", fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007202# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007203 s++;
7204 }
7205 else if (s[0] == ESC && len >= 3-1 && s[1] == '|')
7206 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007207# ifdef MCH_WRITE_DUMP
Bram Moolenaarc0197e22004-09-13 20:26:32 +00007208 char_u *old_s = s;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007209# endif
Bram Moolenaarc0197e22004-09-13 20:26:32 +00007210 char_u *p;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007211 int arg1 = 0, arg2 = 0, argc = 0, args[16];
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007212 char_u *sp;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007213
7214 switch (s[2])
7215 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00007216 case '0': case '1': case '2': case '3': case '4':
7217 case '5': case '6': case '7': case '8': case '9':
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007218 if (*(p = get_seq(args, &argc, s)) != 'm')
7219 goto notsgr;
7220
7221 p = s;
7222
7223 // Handling frequent optional sequences. Output to the screen
7224 // takes too long, so do not output as much as possible.
7225
7226 // If resetFG,FG,BG,<cr>,BG,FG are connected, the preceding
7227 // resetFG,FG,BG are omitted.
7228 if (sgrn2(sgrn2(sgrn2cn(sgrn2(sgrnc(p, 39), 38), 48), 48), 38))
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007229 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007230 p = sgrn2(sgrn2(sgrnc(p, 39), 38), 48);
7231 len = len + 1 - (int)(p - s);
7232 s = p;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007233 break;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007234 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007235
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007236 // If FG,BG,BG,FG of SGR are connected, the first FG can be
7237 // omitted.
7238 if (sgrn2(sgrn2(sgrn2c((sp = sgrn2(p, 38)), 48), 48), 38))
7239 p = sp;
7240
7241 // If FG,BG,FG,BG of SGR are connected, the first FG can be
7242 // omitted.
7243 if (sgrn2(sgrn2(sgrn2c((sp = sgrn2(p, 38)), 48), 38), 48))
7244 p = sp;
7245
7246 // If BG,BG of SGR are connected, the first BG can be omitted.
7247 if (sgrn2((sp = sgrn2(p, 48)), 48))
7248 p = sp;
7249
7250 // If restoreFG and FG are connected, the restoreFG can be
Bram Moolenaar9f1983d2022-05-12 20:35:35 +01007251 // omitted.
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007252 if (sgrn2((sp = sgrnc(p, 39)), 38))
7253 p = sp;
7254
7255 p = get_seq(args, &argc, p);
7256
7257notsgr:
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007258 arg1 = args[0];
7259 arg2 = args[1];
7260 if (*p == 'm')
Bram Moolenaar071d4272004-06-13 20:20:40 +00007261 {
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007262 if (argc == 1 && args[0] == 0)
7263 normvideo();
7264 else if (argc == 1)
7265 {
Christopher Plewrightf75a2cb2023-01-28 10:28:09 +00007266 if (USE_VTP)
Christopher Plewright38804d62022-11-09 23:55:52 +00007267 textcolor((WORD)arg1);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007268 else
Christopher Plewright38804d62022-11-09 23:55:52 +00007269 textattr((WORD)arg1);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007270 }
Christopher Plewright38804d62022-11-09 23:55:52 +00007271 else if (vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007272 vtp_sgr_bulks(argc, args);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007273 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007274 else if (argc == 2 && *p == 'H')
Bram Moolenaar071d4272004-06-13 20:20:40 +00007275 {
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007276 gotoxy(arg2, arg1);
7277 }
7278 else if (argc == 2 && *p == 'r')
7279 {
7280 set_scroll_region(0, arg1 - 1, Columns - 1, arg2 - 1);
7281 }
Bram Moolenaar6982f422019-02-16 16:48:01 +01007282 else if (argc == 2 && *p == 'R')
7283 {
7284 set_scroll_region_tb(arg1, arg2);
7285 }
7286 else if (argc == 2 && *p == 'V')
7287 {
7288 set_scroll_region_lr(arg1, arg2);
7289 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007290 else if (argc == 1 && *p == 'A')
7291 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00007292 gotoxy(g_coord.X + 1,
7293 max(g_srScrollRegion.Top, g_coord.Y - arg1) + 1);
7294 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007295 else if (argc == 1 && *p == 'b')
Bram Moolenaar071d4272004-06-13 20:20:40 +00007296 {
7297 textbackground((WORD) arg1);
7298 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007299 else if (argc == 1 && *p == 'C')
7300 {
7301 gotoxy(min(g_srScrollRegion.Right, g_coord.X + arg1) + 1,
7302 g_coord.Y + 1);
7303 }
7304 else if (argc == 1 && *p == 'f')
7305 {
7306 textcolor((WORD) arg1);
7307 }
7308 else if (argc == 1 && *p == 'H')
7309 {
7310 gotoxy(1, arg1);
7311 }
7312 else if (argc == 1 && *p == 'L')
7313 {
7314 insert_lines(arg1);
7315 }
7316 else if (argc == 1 && *p == 'M')
Bram Moolenaar071d4272004-06-13 20:20:40 +00007317 {
7318 delete_lines(arg1);
7319 }
7320
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007321 len -= (int)(p - s);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007322 s = p + 1;
7323 break;
7324
Bram Moolenaar071d4272004-06-13 20:20:40 +00007325 case 'A':
Bram Moolenaar071d4272004-06-13 20:20:40 +00007326 gotoxy(g_coord.X + 1,
7327 max(g_srScrollRegion.Top, g_coord.Y - 1) + 1);
7328 goto got3;
7329
7330 case 'B':
7331 visual_bell();
7332 goto got3;
7333
7334 case 'C':
Bram Moolenaar071d4272004-06-13 20:20:40 +00007335 gotoxy(min(g_srScrollRegion.Right, g_coord.X + 1) + 1,
7336 g_coord.Y + 1);
7337 goto got3;
7338
7339 case 'E':
7340 termcap_mode_end();
7341 goto got3;
7342
7343 case 'F':
7344 standout();
7345 goto got3;
7346
7347 case 'f':
7348 standend();
7349 goto got3;
7350
7351 case 'H':
7352 gotoxy(1, 1);
7353 goto got3;
7354
7355 case 'j':
7356 clear_to_end_of_display();
7357 goto got3;
7358
7359 case 'J':
7360 clear_screen();
7361 goto got3;
7362
7363 case 'K':
7364 clear_to_end_of_line();
7365 goto got3;
7366
7367 case 'L':
7368 insert_lines(1);
7369 goto got3;
7370
7371 case 'M':
7372 delete_lines(1);
7373 goto got3;
7374
7375 case 'S':
7376 termcap_mode_start();
7377 goto got3;
7378
7379 case 'V':
7380 cursor_visible(TRUE);
7381 goto got3;
7382
7383 case 'v':
7384 cursor_visible(FALSE);
7385 goto got3;
7386
7387 got3:
7388 s += 3;
7389 len -= 2;
7390 }
7391
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007392# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00007393 if (fdDump)
7394 {
7395 fputs("ESC | ", fdDump);
7396 fwrite(old_s + 2, sizeof(char_u), s - old_s - 2, fdDump);
7397 fputc('\n', fdDump);
7398 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007399# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007400 }
K.Takatadf5320c2022-09-01 13:20:16 +01007401 else if (s[0] == ESC && len >= 3-1 && s[1] == '[')
7402 {
7403 int l = 2;
7404
Keith Thompson184f71c2024-01-04 21:19:04 +01007405 if (SAFE_isdigit(s[l]))
K.Takatadf5320c2022-09-01 13:20:16 +01007406 l++;
7407 if (s[l] == ' ' && s[l + 1] == 'q')
7408 {
7409 // DECSCUSR (cursor style) sequences
Christopher Plewright38804d62022-11-09 23:55:52 +00007410 if (vtp_working)
K.Takatadf5320c2022-09-01 13:20:16 +01007411 vtp_printf("%.*s", l + 2, s); // Pass through
7412 s += l + 2;
7413 len -= l + 1;
7414 }
7415 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007416 else
7417 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007418 // Write a single character
Bram Moolenaar071d4272004-06-13 20:20:40 +00007419 DWORD nWritten;
7420
7421 nWritten = write_chars(s, 1);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007422# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00007423 if (fdDump)
7424 {
7425 fputc('>', fdDump);
7426 fwrite(s, sizeof(char_u), nWritten, fdDump);
7427 fputs("<\n", fdDump);
7428 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007429# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007430
7431 len -= (nWritten - 1);
7432 s += nWritten;
7433 }
7434 }
7435
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007436# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00007437 if (fdDump)
7438 fflush(fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007439# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007440}
7441
Bram Moolenaar0f873732019-12-05 20:28:46 +01007442#endif // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00007443
7444
7445/*
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01007446 * Delay for "msec" milliseconds.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007447 */
7448 void
7449mch_delay(
7450 long msec,
Bram Moolenaar0981c872020-08-23 14:28:37 +02007451 int flags UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007452{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007453#if defined(FEAT_GUI_MSWIN) && !defined(VIMDLL)
Bram Moolenaar0f873732019-12-05 20:28:46 +01007454 Sleep((int)msec); // never wait for input
7455#else // Console
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007456# ifdef VIMDLL
7457 if (gui.in_use)
7458 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007459 Sleep((int)msec); // never wait for input
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007460 return;
7461 }
7462# endif
Bram Moolenaar0981c872020-08-23 14:28:37 +02007463 if (flags & MCH_DELAY_IGNOREINPUT)
Bram Moolenaar325b7a22004-07-05 15:58:32 +00007464# ifdef FEAT_MZSCHEME
7465 if (mzthreads_allowed() && p_mzq > 0 && msec > p_mzq)
7466 {
7467 int towait = p_mzq;
7468
Bram Moolenaar0f873732019-12-05 20:28:46 +01007469 // if msec is large enough, wait by portions in p_mzq
Bram Moolenaar325b7a22004-07-05 15:58:32 +00007470 while (msec > 0)
7471 {
7472 mzvim_check_threads();
7473 if (msec < towait)
7474 towait = msec;
7475 Sleep(towait);
7476 msec -= towait;
7477 }
7478 }
7479 else
7480# endif
7481 Sleep((int)msec);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007482 else
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02007483 WaitForChar(msec, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007484#endif
7485}
7486
7487
7488/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01007489 * This version of remove is not scared by a readonly (backup) file.
7490 * This can also remove a symbolic link like Unix.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007491 * Return 0 for success, -1 for failure.
7492 */
7493 int
7494mch_remove(char_u *name)
7495{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007496 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007497 int n;
7498
Bram Moolenaar203258c2016-01-17 22:15:16 +01007499 /*
7500 * On Windows, deleting a directory's symbolic link is done by
7501 * RemoveDirectory(): mch_rmdir. It seems unnatural, but it is fact.
7502 */
7503 if (mch_isdir(name) && mch_is_symbolic_link(name))
7504 return mch_rmdir(name);
7505
Bram Moolenaar12b559e2013-06-12 22:41:37 +02007506 win32_setattrs(name, FILE_ATTRIBUTE_NORMAL);
7507
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007508 wn = enc_to_utf16(name, NULL);
7509 if (wn == NULL)
7510 return -1;
7511
7512 n = DeleteFileW(wn) ? 0 : -1;
7513 vim_free(wn);
7514 return n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007515}
7516
7517
7518/*
Bram Moolenaarb9c31e72016-09-29 15:18:57 +02007519 * Check for an "interrupt signal": CTRL-break or CTRL-C.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007520 */
7521 void
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02007522mch_breakcheck(int force UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007523{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007524#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
7525# ifdef VIMDLL
7526 if (!gui.in_use)
7527# endif
7528 if (g_fCtrlCPressed || g_fCBrkPressed)
7529 {
7530 ctrl_break_was_pressed = g_fCBrkPressed;
7531 g_fCtrlCPressed = g_fCBrkPressed = FALSE;
7532 got_int = TRUE;
7533 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007534#endif
7535}
7536
Bram Moolenaar0f873732019-12-05 20:28:46 +01007537// physical RAM to leave for the OS
Bram Moolenaaree273972016-01-02 21:11:51 +01007538#define WINNT_RESERVE_BYTES (256*1024*1024)
Bram Moolenaaree273972016-01-02 21:11:51 +01007539
7540/*
7541 * How much main memory in KiB that can be used by VIM.
7542 */
Bram Moolenaaree273972016-01-02 21:11:51 +01007543 long_u
Bram Moolenaar1266d672017-02-01 13:43:36 +01007544mch_total_mem(int special UNUSED)
Bram Moolenaaree273972016-01-02 21:11:51 +01007545{
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007546 MEMORYSTATUSEX ms;
7547
Bram Moolenaar0f873732019-12-05 20:28:46 +01007548 // Need to use GlobalMemoryStatusEx() when there is more memory than
7549 // what fits in 32 bits.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007550 ms.dwLength = sizeof(MEMORYSTATUSEX);
7551 GlobalMemoryStatusEx(&ms);
7552 if (ms.ullAvailVirtual < ms.ullTotalPhys)
Bram Moolenaaree273972016-01-02 21:11:51 +01007553 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007554 // Process address space fits in physical RAM, use all of it.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007555 return (long_u)(ms.ullAvailVirtual / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01007556 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007557 if (ms.ullTotalPhys <= WINNT_RESERVE_BYTES)
Bram Moolenaaree273972016-01-02 21:11:51 +01007558 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007559 // Catch old NT box or perverse hardware setup.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007560 return (long_u)((ms.ullTotalPhys / 2) / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01007561 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01007562 // Use physical RAM less reserve for OS + data.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007563 return (long_u)((ms.ullTotalPhys - WINNT_RESERVE_BYTES) / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01007564}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007565
Bram Moolenaar071d4272004-06-13 20:20:40 +00007566/*
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007567 * mch_wrename() works around a bug in rename (aka MoveFile) in
Bram Moolenaar071d4272004-06-13 20:20:40 +00007568 * Windows 95: rename("foo.bar", "foo.bar~") will generate a
7569 * file whose short file name is "FOO.BAR" (its long file name will
7570 * be correct: "foo.bar~"). Because a file can be accessed by
7571 * either its SFN or its LFN, "foo.bar" has effectively been
7572 * renamed to "foo.bar", which is not at all what was wanted. This
7573 * seems to happen only when renaming files with three-character
7574 * extensions by appending a suffix that does not include ".".
7575 * Windows NT gets it right, however, with an SFN of "FOO~1.BAR".
7576 *
7577 * There is another problem, which isn't really a bug but isn't right either:
7578 * When renaming "abcdef~1.txt" to "abcdef~1.txt~", the short name can be
7579 * "abcdef~1.txt" again. This has been reported on Windows NT 4.0 with
7580 * service pack 6. Doesn't seem to happen on Windows 98.
7581 *
7582 * Like rename(), returns 0 upon success, non-zero upon failure.
7583 * Should probably set errno appropriately when errors occur.
7584 */
7585 int
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007586mch_wrename(WCHAR *wold, WCHAR *wnew)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007587{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007588 WCHAR *p;
7589 int i;
7590 WCHAR szTempFile[_MAX_PATH + 1];
7591 WCHAR szNewPath[_MAX_PATH + 1];
Bram Moolenaar071d4272004-06-13 20:20:40 +00007592 HANDLE hf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007593
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007594 // No need to play tricks unless the file name contains a "~" as the
7595 // seventh character.
7596 p = wold;
7597 for (i = 0; wold[i] != NUL; ++i)
7598 if ((wold[i] == '/' || wold[i] == '\\' || wold[i] == ':')
7599 && wold[i + 1] != 0)
7600 p = wold + i + 1;
7601 if ((int)(wold + i - p) < 8 || p[6] != '~')
7602 return (MoveFileW(wold, wnew) == 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007603
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007604 // Get base path of new file name. Undocumented feature: If pszNewFile is
7605 // a directory, no error is returned and pszFilePart will be NULL.
7606 if (GetFullPathNameW(wnew, _MAX_PATH, szNewPath, &p) == 0 || p == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007607 return -1;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007608 *p = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007609
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007610 // Get (and create) a unique temporary file name in directory of new file
7611 if (GetTempFileNameW(szNewPath, L"VIM", 0, szTempFile) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007612 return -2;
7613
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007614 // blow the temp file away
7615 if (!DeleteFileW(szTempFile))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007616 return -3;
7617
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007618 // rename old file to the temp file
7619 if (!MoveFileW(wold, szTempFile))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007620 return -4;
7621
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007622 // now create an empty file called pszOldFile; this prevents the operating
7623 // system using pszOldFile as an alias (SFN) if we're renaming within the
7624 // same directory. For example, we're editing a file called
7625 // filename.asc.txt by its SFN, filena~1.txt. If we rename filena~1.txt
7626 // to filena~1.txt~ (i.e., we're making a backup while writing it), the
7627 // SFN for filena~1.txt~ will be filena~1.txt, by default, which will
7628 // cause all sorts of problems later in buf_write(). So, we create an
7629 // empty file called filena~1.txt and the system will have to find some
7630 // other SFN for filena~1.txt~, such as filena~2.txt
7631 if ((hf = CreateFileW(wold, GENERIC_WRITE, 0, NULL, CREATE_NEW,
Bram Moolenaar071d4272004-06-13 20:20:40 +00007632 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
7633 return -5;
7634 if (!CloseHandle(hf))
7635 return -6;
7636
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007637 // rename the temp file to the new file
7638 if (!MoveFileW(szTempFile, wnew))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007639 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007640 // Renaming failed. Rename the file back to its old name, so that it
7641 // looks like nothing happened.
7642 (void)MoveFileW(szTempFile, wold);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007643 return -7;
7644 }
7645
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007646 // Seems to be left around on Novell filesystems
7647 DeleteFileW(szTempFile);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007648
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007649 // finally, remove the empty old file
7650 if (!DeleteFileW(wold))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007651 return -8;
7652
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007653 return 0;
7654}
7655
7656
7657/*
7658 * Converts the filenames to UTF-16, then call mch_wrename().
7659 * Like rename(), returns 0 upon success, non-zero upon failure.
7660 */
7661 int
7662mch_rename(
7663 const char *pszOldFile,
7664 const char *pszNewFile)
7665{
7666 WCHAR *wold = NULL;
7667 WCHAR *wnew = NULL;
7668 int retval = -1;
7669
7670 wold = enc_to_utf16((char_u *)pszOldFile, NULL);
7671 wnew = enc_to_utf16((char_u *)pszNewFile, NULL);
7672 if (wold != NULL && wnew != NULL)
7673 retval = mch_wrename(wold, wnew);
7674 vim_free(wold);
7675 vim_free(wnew);
7676 return retval;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007677}
7678
7679/*
7680 * Get the default shell for the current hardware platform
7681 */
7682 char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007683default_shell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007684{
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007685 return "cmd.exe";
Bram Moolenaar071d4272004-06-13 20:20:40 +00007686}
7687
7688/*
7689 * mch_access() extends access() to do more detailed check on network drives.
7690 * Returns 0 if file "n" has access rights according to "p", -1 otherwise.
7691 */
7692 int
7693mch_access(char *n, int p)
7694{
7695 HANDLE hFile;
Bram Moolenaar0f873732019-12-05 20:28:46 +01007696 int retval = -1; // default: fail
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007697 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007698
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007699 wn = enc_to_utf16((char_u *)n, NULL);
7700 if (wn == NULL)
7701 return -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007702
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01007703 if (mch_isdir((char_u *)n))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007704 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00007705 WCHAR TempNameW[_MAX_PATH + 16] = L"";
Bram Moolenaar071d4272004-06-13 20:20:40 +00007706
7707 if (p & R_OK)
7708 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007709 // Read check is performed by seeing if we can do a find file on
7710 // the directory for any file.
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007711 int i;
7712 WIN32_FIND_DATAW d;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007713
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007714 for (i = 0; i < _MAX_PATH && wn[i] != 0; ++i)
7715 TempNameW[i] = wn[i];
7716 if (TempNameW[i - 1] != '\\' && TempNameW[i - 1] != '/')
7717 TempNameW[i++] = '\\';
7718 TempNameW[i++] = '*';
7719 TempNameW[i++] = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007720
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007721 hFile = FindFirstFileW(TempNameW, &d);
7722 if (hFile == INVALID_HANDLE_VALUE)
7723 goto getout;
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007724 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00007725 (void)FindClose(hFile);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007726 }
7727
7728 if (p & W_OK)
7729 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007730 // Trying to create a temporary file in the directory should catch
7731 // directories on read-only network shares. However, in
7732 // directories whose ACL allows writes but denies deletes will end
7733 // up keeping the temporary file :-(.
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007734 if (!GetTempFileNameW(wn, L"VIM", 0, TempNameW))
7735 goto getout;
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007736 else
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007737 DeleteFileW(TempNameW);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007738 }
7739 }
7740 else
7741 {
Bram Moolenaar5aa98962018-05-06 17:09:38 +02007742 // Don't consider a file read-only if another process has opened it.
7743 DWORD share_mode = FILE_SHARE_READ | FILE_SHARE_WRITE;
7744
Bram Moolenaar0f873732019-12-05 20:28:46 +01007745 // Trying to open the file for the required access does ACL, read-only
7746 // network share, and file attribute checks.
Bram Moolenaar5aa98962018-05-06 17:09:38 +02007747 DWORD access_mode = ((p & W_OK) ? GENERIC_WRITE : 0)
7748 | ((p & R_OK) ? GENERIC_READ : 0);
7749
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007750 hFile = CreateFileW(wn, access_mode, share_mode,
7751 NULL, OPEN_EXISTING, 0, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007752 if (hFile == INVALID_HANDLE_VALUE)
7753 goto getout;
7754 CloseHandle(hFile);
7755 }
7756
Bram Moolenaar0f873732019-12-05 20:28:46 +01007757 retval = 0; // success
Bram Moolenaar071d4272004-06-13 20:20:40 +00007758getout:
Bram Moolenaar071d4272004-06-13 20:20:40 +00007759 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007760 return retval;
7761}
7762
Bram Moolenaar071d4272004-06-13 20:20:40 +00007763/*
Bram Moolenaar36f692d2008-11-20 16:10:17 +00007764 * Version of open() that may use UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007765 */
7766 int
Bram Moolenaarb6843a02017-08-02 22:07:12 +02007767mch_open(const char *name, int flags, int mode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007768{
7769 WCHAR *wn;
7770 int f;
7771
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007772 wn = enc_to_utf16((char_u *)name, NULL);
7773 if (wn == NULL)
7774 return -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007775
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007776 f = _wopen(wn, flags, mode);
7777 vim_free(wn);
7778 return f;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007779}
7780
7781/*
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007782 * Version of fopen() that uses UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007783 */
7784 FILE *
Bram Moolenaarb6843a02017-08-02 22:07:12 +02007785mch_fopen(const char *name, const char *mode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007786{
7787 WCHAR *wn, *wm;
7788 FILE *f = NULL;
7789
Bram Moolenaara12a1612019-01-24 16:39:02 +01007790#if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0f873732019-12-05 20:28:46 +01007791 // Work around an annoying assertion in the Microsoft debug CRT
7792 // when mode's text/binary setting doesn't match _get_fmode().
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007793 char newMode = mode[strlen(mode) - 1];
7794 int oldMode = 0;
Bram Moolenaar0fde2902008-03-16 13:54:13 +00007795
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007796 _get_fmode(&oldMode);
7797 if (newMode == 't')
7798 _set_fmode(_O_TEXT);
7799 else if (newMode == 'b')
7800 _set_fmode(_O_BINARY);
Bram Moolenaara12a1612019-01-24 16:39:02 +01007801#endif
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007802 wn = enc_to_utf16((char_u *)name, NULL);
7803 wm = enc_to_utf16((char_u *)mode, NULL);
7804 if (wn != NULL && wm != NULL)
7805 f = _wfopen(wn, wm);
7806 vim_free(wn);
7807 vim_free(wm);
Bram Moolenaar0fde2902008-03-16 13:54:13 +00007808
Bram Moolenaara12a1612019-01-24 16:39:02 +01007809#if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007810 _set_fmode(oldMode);
Bram Moolenaara12a1612019-01-24 16:39:02 +01007811#endif
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007812 return f;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007813}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007814
Bram Moolenaar071d4272004-06-13 20:20:40 +00007815/*
7816 * SUB STREAM (aka info stream) handling:
7817 *
Bram Moolenaar8e7d6222020-12-18 19:49:56 +01007818 * NTFS can have sub streams for each file. The normal contents of a file is
7819 * stored in the main stream, and extra contents (author information, title and
7820 * so on) can be stored in a sub stream. After Windows 2000, the user can
7821 * access and store this information in sub streams via an explorer's property
7822 * menu item in the right click menu. This information in sub streams was lost
7823 * when copying only the main stream. Therefore we have to copy sub streams.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007824 *
7825 * Incomplete explanation:
7826 * http://msdn.microsoft.com/library/en-us/dnw2k/html/ntfs5.asp
7827 * More useful info and an example:
7828 * http://www.sysinternals.com/ntw2k/source/misc.shtml#streams
7829 */
7830
7831/*
7832 * Copy info stream data "substream". Read from the file with BackupRead(sh)
7833 * and write to stream "substream" of file "to".
7834 * Errors are ignored.
7835 */
7836 static void
7837copy_substream(HANDLE sh, void *context, WCHAR *to, WCHAR *substream, long len)
7838{
7839 HANDLE hTo;
7840 WCHAR *to_name;
7841
7842 to_name = malloc((wcslen(to) + wcslen(substream) + 1) * sizeof(WCHAR));
7843 wcscpy(to_name, to);
7844 wcscat(to_name, substream);
7845
7846 hTo = CreateFileW(to_name, GENERIC_WRITE, 0, NULL, OPEN_ALWAYS,
7847 FILE_ATTRIBUTE_NORMAL, NULL);
7848 if (hTo != INVALID_HANDLE_VALUE)
7849 {
7850 long done;
7851 DWORD todo;
7852 DWORD readcnt, written;
7853 char buf[4096];
7854
Bram Moolenaar0f873732019-12-05 20:28:46 +01007855 // Copy block of bytes at a time. Abort when something goes wrong.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007856 for (done = 0; done < len; done += written)
7857 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007858 // (size_t) cast for Borland C 5.5
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007859 todo = (DWORD)((size_t)(len - done) > sizeof(buf) ? sizeof(buf)
7860 : (size_t)(len - done));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007861 if (!BackupRead(sh, (LPBYTE)buf, todo, &readcnt,
7862 FALSE, FALSE, context)
7863 || readcnt != todo
7864 || !WriteFile(hTo, buf, todo, &written, NULL)
7865 || written != todo)
7866 break;
7867 }
7868 CloseHandle(hTo);
7869 }
7870
7871 free(to_name);
7872}
7873
7874/*
7875 * Copy info streams from file "from" to file "to".
7876 */
7877 static void
7878copy_infostreams(char_u *from, char_u *to)
7879{
7880 WCHAR *fromw;
7881 WCHAR *tow;
7882 HANDLE sh;
7883 WIN32_STREAM_ID sid;
7884 int headersize;
7885 WCHAR streamname[_MAX_PATH];
7886 DWORD readcount;
7887 void *context = NULL;
7888 DWORD lo, hi;
7889 int len;
7890
Bram Moolenaar0f873732019-12-05 20:28:46 +01007891 // Convert the file names to wide characters.
Bram Moolenaar36f692d2008-11-20 16:10:17 +00007892 fromw = enc_to_utf16(from, NULL);
7893 tow = enc_to_utf16(to, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007894 if (fromw != NULL && tow != NULL)
7895 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007896 // Open the file for reading.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007897 sh = CreateFileW(fromw, GENERIC_READ, FILE_SHARE_READ, NULL,
7898 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
7899 if (sh != INVALID_HANDLE_VALUE)
7900 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007901 // Use BackupRead() to find the info streams. Repeat until we
7902 // have done them all.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007903 for (;;)
7904 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007905 // Get the header to find the length of the stream name. If
7906 // the "readcount" is zero we have done all info streams.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007907 ZeroMemory(&sid, sizeof(WIN32_STREAM_ID));
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007908 headersize = (int)((char *)&sid.cStreamName - (char *)&sid.dwStreamId);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007909 if (!BackupRead(sh, (LPBYTE)&sid, headersize,
7910 &readcount, FALSE, FALSE, &context)
7911 || readcount == 0)
7912 break;
7913
Bram Moolenaar0f873732019-12-05 20:28:46 +01007914 // We only deal with streams that have a name. The normal
7915 // file data appears to be without a name, even though docs
7916 // suggest it is called "::$DATA".
Bram Moolenaar071d4272004-06-13 20:20:40 +00007917 if (sid.dwStreamNameSize > 0)
7918 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007919 // Read the stream name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007920 if (!BackupRead(sh, (LPBYTE)streamname,
7921 sid.dwStreamNameSize,
7922 &readcount, FALSE, FALSE, &context))
7923 break;
7924
Bram Moolenaar0f873732019-12-05 20:28:46 +01007925 // Copy an info stream with a name ":anything:$DATA".
7926 // Skip "::$DATA", it has no stream name (examples suggest
7927 // it might be used for the normal file contents).
7928 // Note that BackupRead() counts bytes, but the name is in
7929 // wide characters.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007930 len = readcount / sizeof(WCHAR);
7931 streamname[len] = 0;
7932 if (len > 7 && wcsicmp(streamname + len - 6,
7933 L":$DATA") == 0)
7934 {
7935 streamname[len - 6] = 0;
7936 copy_substream(sh, &context, tow, streamname,
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00007937 (long)sid.Size.u.LowPart);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007938 }
7939 }
7940
Bram Moolenaar0f873732019-12-05 20:28:46 +01007941 // Advance to the next stream. We might try seeking too far,
7942 // but BackupSeek() doesn't skip over stream borders, thus
7943 // that's OK.
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00007944 (void)BackupSeek(sh, sid.Size.u.LowPart, sid.Size.u.HighPart,
Bram Moolenaar071d4272004-06-13 20:20:40 +00007945 &lo, &hi, &context);
7946 }
7947
Bram Moolenaar0f873732019-12-05 20:28:46 +01007948 // Clear the context.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007949 (void)BackupRead(sh, NULL, 0, &readcount, TRUE, FALSE, &context);
7950
7951 CloseHandle(sh);
7952 }
7953 }
7954 vim_free(fromw);
7955 vim_free(tow);
7956}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007957
7958/*
Bram Moolenaare7bebc42021-02-01 20:50:37 +01007959 * ntdll.dll definitions
7960 */
7961#define FileEaInformation 7
7962#ifndef STATUS_SUCCESS
7963# define STATUS_SUCCESS ((NTSTATUS) 0x00000000L)
7964#endif
7965
7966typedef struct _FILE_FULL_EA_INFORMATION_ {
7967 ULONG NextEntryOffset;
7968 UCHAR Flags;
7969 UCHAR EaNameLength;
7970 USHORT EaValueLength;
7971 CHAR EaName[1];
7972} FILE_FULL_EA_INFORMATION_, *PFILE_FULL_EA_INFORMATION_;
7973
7974typedef struct _FILE_EA_INFORMATION_ {
7975 ULONG EaSize;
7976} FILE_EA_INFORMATION_, *PFILE_EA_INFORMATION_;
7977
Paul Ollis65745772022-06-05 16:55:54 +01007978#ifndef PROTO
Bram Moolenaare7bebc42021-02-01 20:50:37 +01007979typedef NTSTATUS (NTAPI *PfnNtOpenFile)(
7980 PHANDLE FileHandle,
7981 ACCESS_MASK DesiredAccess,
7982 POBJECT_ATTRIBUTES ObjectAttributes,
7983 PIO_STATUS_BLOCK IoStatusBlock,
7984 ULONG ShareAccess,
7985 ULONG OpenOptions);
7986typedef NTSTATUS (NTAPI *PfnNtClose)(
7987 HANDLE Handle);
7988typedef NTSTATUS (NTAPI *PfnNtSetEaFile)(
Bram Moolenaar9f1983d2022-05-12 20:35:35 +01007989 HANDLE FileHandle,
7990 PIO_STATUS_BLOCK IoStatusBlock,
7991 PVOID Buffer,
7992 ULONG Length);
Bram Moolenaare7bebc42021-02-01 20:50:37 +01007993typedef NTSTATUS (NTAPI *PfnNtQueryEaFile)(
7994 HANDLE FileHandle,
7995 PIO_STATUS_BLOCK IoStatusBlock,
7996 PVOID Buffer,
7997 ULONG Length,
7998 BOOLEAN ReturnSingleEntry,
7999 PVOID EaList,
8000 ULONG EaListLength,
8001 PULONG EaIndex,
8002 BOOLEAN RestartScan);
8003typedef NTSTATUS (NTAPI *PfnNtQueryInformationFile)(
Bram Moolenaar9f1983d2022-05-12 20:35:35 +01008004 HANDLE FileHandle,
8005 PIO_STATUS_BLOCK IoStatusBlock,
8006 PVOID FileInformation,
8007 ULONG Length,
Bram Moolenaare7bebc42021-02-01 20:50:37 +01008008 FILE_INFORMATION_CLASS FileInformationClass);
8009typedef VOID (NTAPI *PfnRtlInitUnicodeString)(
8010 PUNICODE_STRING DestinationString,
8011 PCWSTR SourceString);
8012
8013PfnNtOpenFile pNtOpenFile = NULL;
8014PfnNtClose pNtClose = NULL;
8015PfnNtSetEaFile pNtSetEaFile = NULL;
8016PfnNtQueryEaFile pNtQueryEaFile = NULL;
8017PfnNtQueryInformationFile pNtQueryInformationFile = NULL;
8018PfnRtlInitUnicodeString pRtlInitUnicodeString = NULL;
Paul Ollis65745772022-06-05 16:55:54 +01008019#endif
Bram Moolenaare7bebc42021-02-01 20:50:37 +01008020
8021/*
8022 * Load ntdll.dll functions.
8023 */
8024 static BOOL
8025load_ntdll(void)
8026{
8027 static int loaded = -1;
8028
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00008029 if (loaded != -1)
8030 return (BOOL) loaded;
8031
8032 HMODULE hNtdll = GetModuleHandle("ntdll.dll");
8033 if (hNtdll != NULL)
Bram Moolenaare7bebc42021-02-01 20:50:37 +01008034 {
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00008035 pNtOpenFile = (PfnNtOpenFile) GetProcAddress(hNtdll, "NtOpenFile");
8036 pNtClose = (PfnNtClose) GetProcAddress(hNtdll, "NtClose");
8037 pNtSetEaFile = (PfnNtSetEaFile)
8038 GetProcAddress(hNtdll, "NtSetEaFile");
8039 pNtQueryEaFile = (PfnNtQueryEaFile)
8040 GetProcAddress(hNtdll, "NtQueryEaFile");
8041 pNtQueryInformationFile = (PfnNtQueryInformationFile)
8042 GetProcAddress(hNtdll, "NtQueryInformationFile");
8043 pRtlInitUnicodeString = (PfnRtlInitUnicodeString)
8044 GetProcAddress(hNtdll, "RtlInitUnicodeString");
Bram Moolenaare7bebc42021-02-01 20:50:37 +01008045 }
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00008046 if (pNtOpenFile == NULL
8047 || pNtClose == NULL
8048 || pNtSetEaFile == NULL
8049 || pNtQueryEaFile == NULL
8050 || pNtQueryInformationFile == NULL
8051 || pRtlInitUnicodeString == NULL)
8052 loaded = FALSE;
8053 else
8054 loaded = TRUE;
Bram Moolenaare7bebc42021-02-01 20:50:37 +01008055 return (BOOL) loaded;
8056}
8057
8058/*
8059 * Copy extended attributes (EA) from file "from" to file "to".
8060 */
8061 static void
8062copy_extattr(char_u *from, char_u *to)
8063{
8064 char_u *fromf = NULL;
8065 char_u *tof = NULL;
8066 WCHAR *fromw = NULL;
8067 WCHAR *tow = NULL;
8068 UNICODE_STRING u;
8069 HANDLE h;
8070 OBJECT_ATTRIBUTES oa;
8071 IO_STATUS_BLOCK iosb;
8072 FILE_EA_INFORMATION_ eainfo = {0};
8073 void *ea = NULL;
8074
8075 if (!load_ntdll())
8076 return;
8077
8078 // Convert the file names to the fully qualified object names.
8079 fromf = alloc(STRLEN(from) + 5);
8080 tof = alloc(STRLEN(to) + 5);
8081 if (fromf == NULL || tof == NULL)
8082 goto theend;
8083 STRCPY(fromf, "\\??\\");
8084 STRCAT(fromf, from);
8085 STRCPY(tof, "\\??\\");
8086 STRCAT(tof, to);
8087
8088 // Convert the names to wide characters.
8089 fromw = enc_to_utf16(fromf, NULL);
8090 tow = enc_to_utf16(tof, NULL);
8091 if (fromw == NULL || tow == NULL)
8092 goto theend;
8093
8094 // Get the EA.
8095 pRtlInitUnicodeString(&u, fromw);
8096 InitializeObjectAttributes(&oa, &u, 0, NULL, NULL);
8097 if (pNtOpenFile(&h, FILE_READ_EA, &oa, &iosb, 0,
8098 FILE_NON_DIRECTORY_FILE) != STATUS_SUCCESS)
8099 goto theend;
8100 pNtQueryInformationFile(h, &iosb, &eainfo, sizeof(eainfo),
8101 FileEaInformation);
8102 if (eainfo.EaSize != 0)
8103 {
8104 ea = alloc(eainfo.EaSize);
8105 if (ea != NULL)
8106 {
8107 if (pNtQueryEaFile(h, &iosb, ea, eainfo.EaSize, FALSE,
8108 NULL, 0, NULL, TRUE) != STATUS_SUCCESS)
8109 {
Yegappan Lakshmanan960dcbd2023-03-07 17:45:11 +00008110 VIM_CLEAR(ea);
Bram Moolenaare7bebc42021-02-01 20:50:37 +01008111 }
8112 }
8113 }
8114 pNtClose(h);
8115
8116 // Set the EA.
8117 if (ea != NULL)
8118 {
8119 pRtlInitUnicodeString(&u, tow);
8120 InitializeObjectAttributes(&oa, &u, 0, NULL, NULL);
8121 if (pNtOpenFile(&h, FILE_WRITE_EA, &oa, &iosb, 0,
8122 FILE_NON_DIRECTORY_FILE) != STATUS_SUCCESS)
8123 goto theend;
8124
8125 pNtSetEaFile(h, &iosb, ea, eainfo.EaSize);
8126 pNtClose(h);
8127 }
8128
8129theend:
8130 vim_free(fromf);
8131 vim_free(tof);
8132 vim_free(fromw);
8133 vim_free(tow);
8134 vim_free(ea);
8135}
8136
8137/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00008138 * Copy file attributes from file "from" to file "to".
8139 * For Windows NT and later we copy info streams.
8140 * Always returns zero, errors are ignored.
8141 */
8142 int
8143mch_copy_file_attribute(char_u *from, char_u *to)
8144{
Bram Moolenaar0f873732019-12-05 20:28:46 +01008145 // File streams only work on Windows NT and later.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02008146 copy_infostreams(from, to);
Bram Moolenaare7bebc42021-02-01 20:50:37 +01008147 copy_extattr(from, to);
Bram Moolenaar071d4272004-06-13 20:20:40 +00008148 return 0;
8149}
8150
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008151
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008152/*
K.Takatadc73b4b2021-06-08 18:32:36 +02008153 * The command line arguments in UTF-16
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008154 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00008155static int nArgsW = 0;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008156static LPWSTR *ArglistW = NULL;
8157static int global_argc = 0;
8158static char **global_argv;
8159
Bram Moolenaar0f873732019-12-05 20:28:46 +01008160static int used_file_argc = 0; // last argument in global_argv[] used
8161 // for the argument list.
8162static int *used_file_indexes = NULL; // indexes in global_argv[] for
8163 // command line arguments added to
8164 // the argument list
8165static int used_file_count = 0; // nr of entries in used_file_indexes
8166static int used_file_literal = FALSE; // take file names literally
8167static int used_file_full_path = FALSE; // file name was full path
8168static int used_file_diff_mode = FALSE; // file name was with diff mode
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008169static int used_alist_count = 0;
8170
8171
8172/*
8173 * Get the command line arguments. Unicode version.
8174 * Returns argc. Zero when something fails.
8175 */
8176 int
8177get_cmd_argsW(char ***argvp)
8178{
8179 char **argv = NULL;
8180 int argc = 0;
8181 int i;
8182
Bram Moolenaar14993322014-09-09 12:25:33 +02008183 free_cmd_argsW();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008184 ArglistW = CommandLineToArgvW(GetCommandLineW(), &nArgsW);
8185 if (ArglistW != NULL)
8186 {
8187 argv = malloc((nArgsW + 1) * sizeof(char *));
8188 if (argv != NULL)
8189 {
8190 argc = nArgsW;
8191 argv[argc] = NULL;
8192 for (i = 0; i < argc; ++i)
8193 {
8194 int len;
8195
K.Takatadc73b4b2021-06-08 18:32:36 +02008196 // Convert each Unicode argument to UTF-8.
8197 WideCharToMultiByte_alloc(CP_UTF8, 0,
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00008198 ArglistW[i], (int)wcslen(ArglistW[i]) + 1,
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008199 (LPSTR *)&argv[i], &len, 0, 0);
8200 if (argv[i] == NULL)
8201 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01008202 // Out of memory, clear everything.
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008203 while (i > 0)
8204 free(argv[--i]);
8205 free(argv);
Bram Moolenaar73c61632013-12-07 14:48:10 +01008206 argv = NULL;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008207 argc = 0;
8208 }
8209 }
8210 }
8211 }
8212
8213 global_argc = argc;
8214 global_argv = argv;
8215 if (argc > 0)
Bram Moolenaar14993322014-09-09 12:25:33 +02008216 {
8217 if (used_file_indexes != NULL)
8218 free(used_file_indexes);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008219 used_file_indexes = malloc(argc * sizeof(int));
Bram Moolenaar14993322014-09-09 12:25:33 +02008220 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008221
8222 if (argvp != NULL)
8223 *argvp = argv;
8224 return argc;
8225}
8226
8227 void
8228free_cmd_argsW(void)
8229{
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00008230 if (ArglistW == NULL)
8231 return;
8232
8233 GlobalFree(ArglistW);
8234 ArglistW = NULL;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008235}
8236
8237/*
8238 * Remember "name" is an argument that was added to the argument list.
8239 * This avoids that we have to re-parse the argument list when fix_arg_enc()
8240 * is called.
8241 */
8242 void
Bram Moolenaar910f66f2006-04-05 20:41:53 +00008243used_file_arg(char *name, int literal, int full_path, int diff_mode)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008244{
8245 int i;
8246
8247 if (used_file_indexes == NULL)
8248 return;
8249 for (i = used_file_argc + 1; i < global_argc; ++i)
8250 if (STRCMP(global_argv[i], name) == 0)
8251 {
8252 used_file_argc = i;
8253 used_file_indexes[used_file_count++] = i;
8254 break;
8255 }
8256 used_file_literal = literal;
8257 used_file_full_path = full_path;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00008258 used_file_diff_mode = diff_mode;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008259}
8260
8261/*
8262 * Remember the length of the argument list as it was. If it changes then we
8263 * leave it alone when 'encoding' is set.
8264 */
8265 void
8266set_alist_count(void)
8267{
8268 used_alist_count = GARGCOUNT;
8269}
8270
8271/*
8272 * Fix the encoding of the command line arguments. Invoked when 'encoding'
K.Takatadc73b4b2021-06-08 18:32:36 +02008273 * has been changed while starting up. Use the UTF-16 command line arguments
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008274 * and convert them to 'encoding'.
8275 */
8276 void
8277fix_arg_enc(void)
8278{
8279 int i;
8280 int idx;
8281 char_u *str;
Bram Moolenaar86b68352004-12-27 21:59:20 +00008282 int *fnum_list;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008283
Bram Moolenaar0f873732019-12-05 20:28:46 +01008284 // Safety checks:
8285 // - if argument count differs between the wide and non-wide argument
8286 // list, something must be wrong.
8287 // - the file name arguments must have been located.
8288 // - the length of the argument list wasn't changed by the user.
Bram Moolenaard857f0e2005-06-21 22:37:39 +00008289 if (global_argc != nArgsW
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008290 || ArglistW == NULL
8291 || used_file_indexes == NULL
8292 || used_file_count == 0
8293 || used_alist_count != GARGCOUNT)
8294 return;
8295
Bram Moolenaar0f873732019-12-05 20:28:46 +01008296 // Remember the buffer numbers for the arguments.
Bram Moolenaarc799fe22019-05-28 23:08:19 +02008297 fnum_list = ALLOC_MULT(int, GARGCOUNT);
Bram Moolenaar86b68352004-12-27 21:59:20 +00008298 if (fnum_list == NULL)
Bram Moolenaar0f873732019-12-05 20:28:46 +01008299 return; // out of memory
Bram Moolenaar86b68352004-12-27 21:59:20 +00008300 for (i = 0; i < GARGCOUNT; ++i)
8301 fnum_list[i] = GARGLIST[i].ae_fnum;
8302
Bram Moolenaar0f873732019-12-05 20:28:46 +01008303 // Clear the argument list. Make room for the new arguments.
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008304 alist_clear(&global_alist);
8305 if (ga_grow(&global_alist.al_ga, used_file_count) == FAIL)
Bram Moolenaar0f873732019-12-05 20:28:46 +01008306 return; // out of memory
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008307
8308 for (i = 0; i < used_file_count; ++i)
8309 {
8310 idx = used_file_indexes[i];
Bram Moolenaar36f692d2008-11-20 16:10:17 +00008311 str = utf16_to_enc(ArglistW[idx], NULL);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008312 if (str != NULL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00008313 {
Bram Moolenaar39d21e32017-08-05 23:09:31 +02008314 int literal = used_file_literal;
8315
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01008316#ifdef FEAT_DIFF
Bram Moolenaar0f873732019-12-05 20:28:46 +01008317 // When using diff mode may need to concatenate file name to
8318 // directory name. Just like it's done in main().
Bram Moolenaar910f66f2006-04-05 20:41:53 +00008319 if (used_file_diff_mode && mch_isdir(str) && GARGCOUNT > 0
8320 && !mch_isdir(alist_name(&GARGLIST[0])))
8321 {
8322 char_u *r;
8323
8324 r = concat_fnames(str, gettail(alist_name(&GARGLIST[0])), TRUE);
8325 if (r != NULL)
8326 {
8327 vim_free(str);
8328 str = r;
8329 }
8330 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01008331#endif
Bram Moolenaar0f873732019-12-05 20:28:46 +01008332 // Re-use the old buffer by renaming it. When not using literal
8333 // names it's done by alist_expand() below.
Bram Moolenaar86b68352004-12-27 21:59:20 +00008334 if (used_file_literal)
8335 buf_set_name(fnum_list[i], str);
8336
Bram Moolenaar0f873732019-12-05 20:28:46 +01008337 // Check backtick literal. backtick literal is already expanded in
8338 // main.c, so this part add str as literal.
Bram Moolenaar39d21e32017-08-05 23:09:31 +02008339 if (literal == FALSE)
8340 {
Bram Moolenaar116a0f82017-08-07 21:17:57 +02008341 size_t len = STRLEN(str);
8342
Bram Moolenaar39d21e32017-08-05 23:09:31 +02008343 if (len > 2 && *str == '`' && *(str + len - 1) == '`')
8344 literal = TRUE;
8345 }
8346 alist_add(&global_alist, str, literal ? 2 : 0);
Bram Moolenaar86b68352004-12-27 21:59:20 +00008347 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008348 }
8349
8350 if (!used_file_literal)
8351 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01008352 // Now expand wildcards in the arguments.
8353 // Temporarily add '(' and ')' to 'isfname'. These are valid
8354 // filename characters but are excluded from 'isfname' to make
Dominique Pelleaf4a61a2021-12-27 17:21:41 +00008355 // "gf" work on a file name in parentheses (e.g.: see vim.h).
Bram Moolenaar0f873732019-12-05 20:28:46 +01008356 // Also, unset wildignore to not be influenced by this option.
8357 // The arguments specified in command-line should be kept even if
8358 // encoding options were changed.
Christian Brabandtfd916d62021-11-01 22:44:33 +00008359 // Use :legacy so that it also works when in Vim9 script.
8360 do_cmdline_cmd((char_u *)":legacy let g:SaVe_ISF = &isf|set isf+=(,)");
8361 do_cmdline_cmd((char_u *)":legacy let g:SaVe_WIG = &wig|set wig=");
Bram Moolenaar86b68352004-12-27 21:59:20 +00008362 alist_expand(fnum_list, used_alist_count);
Christian Brabandtfd916d62021-11-01 22:44:33 +00008363 do_cmdline_cmd(
8364 (char_u *)":legacy let &isf = g:SaVe_ISF|unlet g:SaVe_ISF");
8365 do_cmdline_cmd(
8366 (char_u *)":legacy let &wig = g:SaVe_WIG|unlet g:SaVe_WIG");
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008367 }
8368
Bram Moolenaar0f873732019-12-05 20:28:46 +01008369 // If wildcard expansion failed, we are editing the first file of the
8370 // arglist and there is no file name: Edit the first argument now.
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008371 if (curwin->w_arg_idx == 0 && curbuf->b_fname == NULL)
8372 {
8373 do_cmdline_cmd((char_u *)":rewind");
Bram Moolenaar05268152021-11-18 18:53:45 +00008374 if (GARGCOUNT == 1 && used_file_full_path
8375 && vim_chdirfile(alist_name(&GARGLIST[0]), "drop") == OK)
8376 last_chdir_reason = "drop";
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008377 }
Bram Moolenaar86b68352004-12-27 21:59:20 +00008378
8379 set_alist_count();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00008380}
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01008381
8382 int
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02008383mch_setenv(char *var, char *value, int x UNUSED)
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01008384{
8385 char_u *envbuf;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02008386 WCHAR *p;
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01008387
Bram Moolenaar964b3742019-05-24 18:54:09 +02008388 envbuf = alloc(STRLEN(var) + STRLEN(value) + 2);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01008389 if (envbuf == NULL)
8390 return -1;
8391
8392 sprintf((char *)envbuf, "%s=%s", var, value);
8393
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02008394 p = enc_to_utf16(envbuf, NULL);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01008395
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02008396 vim_free(envbuf);
8397 if (p == NULL)
8398 return -1;
8399 _wputenv(p);
Bram Moolenaara12a1612019-01-24 16:39:02 +01008400#ifdef libintl_wputenv
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02008401 libintl_wputenv(p);
Bram Moolenaara12a1612019-01-24 16:39:02 +01008402#endif
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02008403 // Unlike Un*x systems, we can free the string for _wputenv().
8404 vim_free(p);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01008405
8406 return 0;
8407}
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008408
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008409/*
8410 * Support for 256 colors and 24-bit colors was added in Windows 10
8411 * version 1703 (Creators update).
8412 */
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008413#define VTP_FIRST_SUPPORT_BUILD MAKE_VER(10, 0, 15063)
8414
8415/*
8416 * Support for pseudo-console (ConPTY) was added in windows 10
Bram Moolenaar57da6982019-09-13 22:30:11 +02008417 * version 1809 (October 2018 update).
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008418 */
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01008419#define CONPTY_FIRST_SUPPORT_BUILD MAKE_VER(10, 0, 17763)
Bram Moolenaar57da6982019-09-13 22:30:11 +02008420
8421/*
8422 * ConPTY differences between versions, need different logic.
8423 * version 1903 (May 2019 update).
8424 */
8425#define CONPTY_1903_BUILD MAKE_VER(10, 0, 18362)
8426
8427/*
Bram Moolenaar36e7a822019-11-13 21:49:24 +01008428 * version 1909 (November 2019 update).
8429 */
8430#define CONPTY_1909_BUILD MAKE_VER(10, 0, 18363)
8431
8432/*
Bram Moolenaar7ed8f592020-04-28 20:44:42 +02008433 * Stay ahead of the next update, and when it's done, fix this.
8434 * version ? (2020 update, temporarily use the build number of insider preview)
8435 */
8436#define CONPTY_NEXT_UPDATE_BUILD MAKE_VER(10, 0, 19587)
8437
8438/*
Bram Moolenaar57da6982019-09-13 22:30:11 +02008439 * Confirm until this version. Also the logic changes.
8440 * insider preview.
8441 */
Bram Moolenaar4c063dd2019-10-04 21:29:12 +02008442#define CONPTY_INSIDER_BUILD MAKE_VER(10, 0, 18995)
Bram Moolenaar57da6982019-09-13 22:30:11 +02008443
8444/*
8445 * Not stable now.
8446 */
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01008447#define CONPTY_STABLE_BUILD MAKE_VER(10, 0, 32767) // T.B.D.
Christopher Plewright1140b512022-11-12 18:46:05 +00008448// Notes:
8449// Win 10 22H2 Final is build 19045, it's conpty is widely used.
8450// Strangely, 19045 is newer but is a lower build number than the 2020 insider
8451// preview which had a build 19587. And, not sure how stable that was?
8452// Win Server 2022 (May 10, 2022) is build 20348, its conpty is widely used.
8453// Win 11 starts from build 22000, even though the major version says 10!
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008454
8455 static void
8456vtp_flag_init(void)
8457{
8458 DWORD ver = get_build_number();
Bram Moolenaarafde13b2019-04-28 19:46:49 +02008459#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008460 DWORD mode;
8461 HANDLE out;
8462
Bram Moolenaarafde13b2019-04-28 19:46:49 +02008463# ifdef VIMDLL
8464 if (!gui.in_use)
8465# endif
8466 {
8467 out = GetStdHandle(STD_OUTPUT_HANDLE);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008468
Bram Moolenaarafde13b2019-04-28 19:46:49 +02008469 vtp_working = (ver >= VTP_FIRST_SUPPORT_BUILD) ? 1 : 0;
8470 GetConsoleMode(out, &mode);
8471 mode |= (ENABLE_PROCESSED_OUTPUT | ENABLE_VIRTUAL_TERMINAL_PROCESSING);
8472 if (SetConsoleMode(out, mode) == 0)
8473 vtp_working = 0;
Christopher Plewrightf75a2cb2023-01-28 10:28:09 +00008474
8475 // VTP uses alternate screen buffer.
8476 // But, not if running in a nested terminal
8477 use_alternate_screen_buffer = win10_22H2_or_later && p_rs && vtp_working
8478 && !mch_getenv("VIM_TERMINAL");
Bram Moolenaarafde13b2019-04-28 19:46:49 +02008479 }
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008480#endif
8481
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008482 if (ver >= CONPTY_FIRST_SUPPORT_BUILD)
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01008483 conpty_working = 1;
8484 if (ver >= CONPTY_STABLE_BUILD)
8485 conpty_stable = 1;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008486
Bram Moolenaar57da6982019-09-13 22:30:11 +02008487 if (ver <= CONPTY_INSIDER_BUILD)
8488 conpty_type = 3;
Bram Moolenaar36e7a822019-11-13 21:49:24 +01008489 if (ver <= CONPTY_1909_BUILD)
8490 conpty_type = 2;
Bram Moolenaar57da6982019-09-13 22:30:11 +02008491 if (ver <= CONPTY_1903_BUILD)
8492 conpty_type = 2;
8493 if (ver < CONPTY_FIRST_SUPPORT_BUILD)
8494 conpty_type = 1;
Bram Moolenaar7ed8f592020-04-28 20:44:42 +02008495
8496 if (ver >= CONPTY_NEXT_UPDATE_BUILD)
8497 conpty_fix_type = 1;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008498}
8499
Bram Moolenaarafde13b2019-04-28 19:46:49 +02008500#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL) || defined(PROTO)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008501
8502 static void
8503vtp_init(void)
8504{
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02008505# ifdef FEAT_TERMGUICOLORS
Christopher Plewrightd343c602023-01-22 18:58:30 +00008506 CONSOLE_SCREEN_BUFFER_INFOEX csbi;
8507 csbi.cbSize = sizeof(csbi);
8508 GetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
8509 save_console_bg_rgb = (guicolor_T)csbi.ColorTable[g_color_index_bg];
8510 save_console_fg_rgb = (guicolor_T)csbi.ColorTable[g_color_index_fg];
8511 store_console_bg_rgb = save_console_bg_rgb;
8512 store_console_fg_rgb = save_console_fg_rgb;
Christopher Plewright38804d62022-11-09 23:55:52 +00008513
Christopher Plewrightd343c602023-01-22 18:58:30 +00008514 COLORREF bg;
8515 bg = (COLORREF)csbi.ColorTable[g_color_index_bg];
8516 bg = (GetRValue(bg) << 16) | (GetGValue(bg) << 8) | GetBValue(bg);
8517 default_console_color_bg = bg;
Christopher Plewright38804d62022-11-09 23:55:52 +00008518
Christopher Plewrightd343c602023-01-22 18:58:30 +00008519 COLORREF fg;
8520 fg = (COLORREF)csbi.ColorTable[g_color_index_fg];
8521 fg = (GetRValue(fg) << 16) | (GetGValue(fg) << 8) | GetBValue(fg);
8522 default_console_color_fg = fg;
Bram Moolenaarc4568ab2018-11-16 16:21:05 +01008523# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008524 set_console_color_rgb();
8525}
8526
8527 static void
8528vtp_exit(void)
8529{
Bram Moolenaardf543822020-01-30 11:53:59 +01008530 restore_console_color_rgb();
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008531}
8532
Bram Moolenaar06b7b582020-05-30 17:49:25 +02008533 int
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008534vtp_printf(
8535 char *format,
8536 ...)
8537{
8538 char_u buf[100];
8539 va_list list;
8540 DWORD result;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008541 int len;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008542
Nir Lichtman6cd2d1d2023-11-11 11:27:41 +01008543 if (silent_mode)
8544 return 0;
8545
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008546 va_start(list, format);
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008547 len = vim_vsnprintf((char *)buf, 100, (char *)format, list);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008548 va_end(list);
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008549 WriteConsoleA(g_hConOut, buf, (DWORD)len, &result, NULL);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008550 return (int)result;
8551}
8552
8553 static void
8554vtp_sgr_bulk(
8555 int arg)
8556{
8557 int args[1];
8558
8559 args[0] = arg;
8560 vtp_sgr_bulks(1, args);
8561}
8562
K.Takata6e1d31e2022-02-03 13:05:32 +00008563# define FAST256(x) \
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008564 if ((*p-- = "0123456789"[(n = x % 10)]) \
8565 && x >= 10 && (*p-- = "0123456789"[((m = x % 100) - n) / 10]) \
8566 && x >= 100 && (*p-- = "012"[((x & 0xff) - m) / 100]));
8567
K.Takata6e1d31e2022-02-03 13:05:32 +00008568# define FAST256CASE(x) \
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008569 case x: \
8570 FAST256(newargs[x - 1]);
8571
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008572 static void
8573vtp_sgr_bulks(
8574 int argc,
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008575 int *args)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008576{
K.Takata6e1d31e2022-02-03 13:05:32 +00008577# define MAXSGR 16
8578# define SGRBUFSIZE 2 + 4 * MAXSGR + 1 // '\033[' + SGR + 'm'
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008579 char_u buf[SGRBUFSIZE];
8580 char_u *p;
8581 int in, out;
8582 int newargs[16];
8583 static int sgrfgr = -1, sgrfgg, sgrfgb;
8584 static int sgrbgr = -1, sgrbgg, sgrbgb;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008585
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008586 if (argc == 0)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008587 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008588 sgrfgr = sgrbgr = -1;
K.Takatadf5320c2022-09-01 13:20:16 +01008589 vtp_printf("\033[m");
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008590 return;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008591 }
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008592
8593 in = out = 0;
8594 while (in < argc)
8595 {
8596 int s = args[in];
8597 int copylen = 1;
8598
8599 if (s == 38)
8600 {
8601 if (argc - in >= 5 && args[in + 1] == 2)
8602 {
8603 if (sgrfgr == args[in + 2] && sgrfgg == args[in + 3]
8604 && sgrfgb == args[in + 4])
8605 {
8606 in += 5;
8607 copylen = 0;
8608 }
8609 else
8610 {
8611 sgrfgr = args[in + 2];
8612 sgrfgg = args[in + 3];
8613 sgrfgb = args[in + 4];
8614 copylen = 5;
8615 }
8616 }
8617 else if (argc - in >= 3 && args[in + 1] == 5)
8618 {
8619 sgrfgr = -1;
8620 copylen = 3;
8621 }
8622 }
8623 else if (s == 48)
8624 {
8625 if (argc - in >= 5 && args[in + 1] == 2)
8626 {
8627 if (sgrbgr == args[in + 2] && sgrbgg == args[in + 3]
8628 && sgrbgb == args[in + 4])
8629 {
8630 in += 5;
8631 copylen = 0;
8632 }
8633 else
8634 {
8635 sgrbgr = args[in + 2];
8636 sgrbgg = args[in + 3];
8637 sgrbgb = args[in + 4];
8638 copylen = 5;
8639 }
8640 }
8641 else if (argc - in >= 3 && args[in + 1] == 5)
8642 {
8643 sgrbgr = -1;
8644 copylen = 3;
8645 }
8646 }
8647 else if (30 <= s && s <= 39)
8648 sgrfgr = -1;
8649 else if (90 <= s && s <= 97)
8650 sgrfgr = -1;
8651 else if (40 <= s && s <= 49)
8652 sgrbgr = -1;
8653 else if (100 <= s && s <= 107)
8654 sgrbgr = -1;
8655 else if (s == 0)
8656 sgrfgr = sgrbgr = -1;
8657
8658 while (copylen--)
8659 newargs[out++] = args[in++];
8660 }
8661
8662 p = &buf[sizeof(buf) - 1];
8663 *p-- = 'm';
8664
8665 switch (out)
8666 {
8667 int n, m;
8668 DWORD r;
8669
8670 FAST256CASE(16);
8671 *p-- = ';';
8672 FAST256CASE(15);
8673 *p-- = ';';
8674 FAST256CASE(14);
8675 *p-- = ';';
8676 FAST256CASE(13);
8677 *p-- = ';';
8678 FAST256CASE(12);
8679 *p-- = ';';
8680 FAST256CASE(11);
8681 *p-- = ';';
8682 FAST256CASE(10);
8683 *p-- = ';';
8684 FAST256CASE(9);
8685 *p-- = ';';
8686 FAST256CASE(8);
8687 *p-- = ';';
8688 FAST256CASE(7);
8689 *p-- = ';';
8690 FAST256CASE(6);
8691 *p-- = ';';
8692 FAST256CASE(5);
8693 *p-- = ';';
8694 FAST256CASE(4);
8695 *p-- = ';';
8696 FAST256CASE(3);
8697 *p-- = ';';
8698 FAST256CASE(2);
8699 *p-- = ';';
8700 FAST256CASE(1);
8701 *p-- = '[';
8702 *p = '\033';
8703 WriteConsoleA(g_hConOut, p, (DWORD)(&buf[SGRBUFSIZE] - p), &r, NULL);
8704 default:
8705 break;
8706 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008707}
8708
Bram Moolenaar06b7b582020-05-30 17:49:25 +02008709 static void
8710wt_init(void)
8711{
Christopher Plewright1140b512022-11-12 18:46:05 +00008712 wt_working = mch_getenv("WT_SESSION") != NULL;
Bram Moolenaar06b7b582020-05-30 17:49:25 +02008713}
8714
Bram Moolenaar8a938af2018-05-01 17:30:41 +02008715# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02008716 static int
8717ctermtoxterm(
8718 int cterm)
8719{
Bram Moolenaar9894e392018-05-05 14:29:06 +02008720 char_u r, g, b, idx;
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02008721
8722 cterm_color2rgb(cterm, &r, &g, &b, &idx);
8723 return (((int)r << 16) | ((int)g << 8) | (int)b);
8724}
Bram Moolenaar8a938af2018-05-01 17:30:41 +02008725# endif
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02008726
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008727 static void
8728set_console_color_rgb(void)
8729{
8730# ifdef FEAT_TERMGUICOLORS
K.Takata27b53be2022-09-18 12:25:49 +01008731 CONSOLE_SCREEN_BUFFER_INFOEX csbi;
Bram Moolenaara050b942019-12-02 21:35:31 +01008732 guicolor_T fg, bg;
8733 int ctermfg, ctermbg;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008734
Christopher Plewright38804d62022-11-09 23:55:52 +00008735 if (!vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008736 return;
8737
Bram Moolenaara050b942019-12-02 21:35:31 +01008738 get_default_console_color(&ctermfg, &ctermbg, &fg, &bg);
8739
Christopher Plewright38804d62022-11-09 23:55:52 +00008740 if (p_tgc || t_colors >= 256)
Bram Moolenaar06b7b582020-05-30 17:49:25 +02008741 {
8742 term_fg_rgb_color(fg);
8743 term_bg_rgb_color(bg);
8744 return;
8745 }
8746
Christopher Plewrightf75a2cb2023-01-28 10:28:09 +00008747 if (use_alternate_screen_buffer)
8748 return;
8749
Christopher Plewrightd343c602023-01-22 18:58:30 +00008750 fg = (GetRValue(fg) << 16) | (GetGValue(fg) << 8) | GetBValue(fg);
8751 bg = (GetRValue(bg) << 16) | (GetGValue(bg) << 8) | GetBValue(bg);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008752
Christopher Plewrightd343c602023-01-22 18:58:30 +00008753 csbi.cbSize = sizeof(csbi);
8754 GetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008755
Christopher Plewrightd343c602023-01-22 18:58:30 +00008756 csbi.cbSize = sizeof(csbi);
8757 csbi.srWindow.Right += 1;
8758 csbi.srWindow.Bottom += 1;
8759 store_console_bg_rgb = csbi.ColorTable[g_color_index_bg];
8760 store_console_fg_rgb = csbi.ColorTable[g_color_index_fg];
8761 csbi.ColorTable[g_color_index_bg] = (COLORREF)bg;
8762 csbi.ColorTable[g_color_index_fg] = (COLORREF)fg;
8763 SetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008764# endif
8765}
8766
Bram Moolenaara050b942019-12-02 21:35:31 +01008767# if defined(FEAT_TERMGUICOLORS) || defined(PROTO)
8768 void
8769get_default_console_color(
8770 int *cterm_fg,
8771 int *cterm_bg,
8772 guicolor_T *gui_fg,
8773 guicolor_T *gui_bg)
8774{
8775 int id;
8776 guicolor_T guifg = INVALCOLOR;
8777 guicolor_T guibg = INVALCOLOR;
8778 int ctermfg = 0;
8779 int ctermbg = 0;
Christopher Plewright38804d62022-11-09 23:55:52 +00008780 int dummynull = 0;
Bram Moolenaara050b942019-12-02 21:35:31 +01008781
8782 id = syn_name2id((char_u *)"Normal");
8783 if (id > 0 && p_tgc)
8784 syn_id2colors(id, &guifg, &guibg);
8785 if (guifg == INVALCOLOR)
8786 {
8787 ctermfg = -1;
8788 if (id > 0)
Christopher Plewright38804d62022-11-09 23:55:52 +00008789 syn_id2cterm_bg(id, &ctermfg, &dummynull);
Christopher Plewrightd343c602023-01-22 18:58:30 +00008790 if (ctermfg != -1)
8791 guifg = ctermtoxterm(ctermfg);
Christopher Plewright38804d62022-11-09 23:55:52 +00008792 else
Christopher Plewrightd343c602023-01-22 18:58:30 +00008793 guifg = USE_WT ? INVALCOLOR : default_console_color_fg;
8794 cterm_normal_fg_gui_color = guifg;
8795 ctermfg = ctermfg < 0 ? 0 : ctermfg;
Bram Moolenaara050b942019-12-02 21:35:31 +01008796 }
8797 if (guibg == INVALCOLOR)
8798 {
8799 ctermbg = -1;
8800 if (id > 0)
Christopher Plewright38804d62022-11-09 23:55:52 +00008801 syn_id2cterm_bg(id, &dummynull, &ctermbg);
Christopher Plewrightd343c602023-01-22 18:58:30 +00008802 if (ctermbg != -1)
8803 guibg = ctermtoxterm(ctermbg);
K.Takatae53a0d42022-09-05 21:45:11 +01008804 else
Christopher Plewrightd343c602023-01-22 18:58:30 +00008805 guibg = USE_WT ? INVALCOLOR : default_console_color_bg;
8806 cterm_normal_bg_gui_color = guibg;
8807 ctermbg = ctermbg < 0 ? 0 : ctermbg;
Bram Moolenaara050b942019-12-02 21:35:31 +01008808 }
8809
8810 *cterm_fg = ctermfg;
8811 *cterm_bg = ctermbg;
8812 *gui_fg = guifg;
8813 *gui_bg = guibg;
8814}
8815# endif
8816
Bram Moolenaardf543822020-01-30 11:53:59 +01008817/*
8818 * Set the console colors to the original colors or the last set colors.
8819 */
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008820 static void
8821reset_console_color_rgb(void)
8822{
8823# ifdef FEAT_TERMGUICOLORS
Christopher Plewrightf75a2cb2023-01-28 10:28:09 +00008824 if (use_alternate_screen_buffer)
8825 return;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008826
Christopher Plewright38804d62022-11-09 23:55:52 +00008827 CONSOLE_SCREEN_BUFFER_INFOEX csbi;
8828
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008829 csbi.cbSize = sizeof(csbi);
K.Takata27b53be2022-09-18 12:25:49 +01008830 GetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008831
8832 csbi.cbSize = sizeof(csbi);
8833 csbi.srWindow.Right += 1;
8834 csbi.srWindow.Bottom += 1;
Bram Moolenaardf543822020-01-30 11:53:59 +01008835 csbi.ColorTable[g_color_index_bg] = (COLORREF)store_console_bg_rgb;
8836 csbi.ColorTable[g_color_index_fg] = (COLORREF)store_console_fg_rgb;
K.Takata27b53be2022-09-18 12:25:49 +01008837 SetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaardf543822020-01-30 11:53:59 +01008838# endif
8839}
8840
8841/*
8842 * Set the console colors to the original colors.
8843 */
8844 static void
8845restore_console_color_rgb(void)
8846{
8847# ifdef FEAT_TERMGUICOLORS
Christopher Plewrightf75a2cb2023-01-28 10:28:09 +00008848 if (use_alternate_screen_buffer)
8849 return;
Christopher Plewright38804d62022-11-09 23:55:52 +00008850
K.Takata27b53be2022-09-18 12:25:49 +01008851 CONSOLE_SCREEN_BUFFER_INFOEX csbi;
Bram Moolenaardf543822020-01-30 11:53:59 +01008852
8853 csbi.cbSize = sizeof(csbi);
K.Takata27b53be2022-09-18 12:25:49 +01008854 GetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaardf543822020-01-30 11:53:59 +01008855
8856 csbi.cbSize = sizeof(csbi);
8857 csbi.srWindow.Right += 1;
8858 csbi.srWindow.Bottom += 1;
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02008859 csbi.ColorTable[g_color_index_bg] = (COLORREF)save_console_bg_rgb;
8860 csbi.ColorTable[g_color_index_fg] = (COLORREF)save_console_fg_rgb;
K.Takata27b53be2022-09-18 12:25:49 +01008861 SetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008862# endif
8863}
8864
8865 void
8866control_console_color_rgb(void)
8867{
Christopher Plewright38804d62022-11-09 23:55:52 +00008868 if (vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008869 set_console_color_rgb();
8870 else
8871 reset_console_color_rgb();
8872}
8873
8874 int
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008875use_vtp(void)
8876{
8877 return USE_VTP;
8878}
8879
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02008880 int
8881is_term_win32(void)
8882{
8883 return T_NAME != NULL && STRCMP(T_NAME, "win32") == 0;
8884}
8885
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008886 int
8887has_vtp_working(void)
8888{
8889 return vtp_working;
8890}
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01008891
Bram Moolenaar6902c0e2019-02-16 14:07:37 +01008892#endif
8893
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01008894 int
8895has_conpty_working(void)
8896{
8897 return conpty_working;
8898}
8899
8900 int
Bram Moolenaar57da6982019-09-13 22:30:11 +02008901get_conpty_type(void)
8902{
8903 return conpty_type;
8904}
8905
8906 int
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01008907is_conpty_stable(void)
8908{
8909 return conpty_stable;
8910}
Bram Moolenaar78d21da2019-02-17 15:00:52 +01008911
Bram Moolenaar7ed8f592020-04-28 20:44:42 +02008912 int
8913get_conpty_fix_type(void)
8914{
8915 return conpty_fix_type;
8916}
8917
Bram Moolenaarafde13b2019-04-28 19:46:49 +02008918#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL) || defined(PROTO)
Bram Moolenaar78d21da2019-02-17 15:00:52 +01008919 void
8920resize_console_buf(void)
8921{
Christopher Plewrightf75a2cb2023-01-28 10:28:09 +00008922 if (use_alternate_screen_buffer)
8923 return;
8924
Bram Moolenaar78d21da2019-02-17 15:00:52 +01008925 CONSOLE_SCREEN_BUFFER_INFO csbi;
8926 COORD coord;
8927 SMALL_RECT newsize;
8928
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00008929 if (!GetConsoleScreenBufferInfo(g_hConOut, &csbi))
8930 return;
Bram Moolenaar78d21da2019-02-17 15:00:52 +01008931
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00008932 coord.X = SRWIDTH(csbi.srWindow);
8933 coord.Y = SRHEIGHT(csbi.srWindow);
8934 SetConsoleScreenBufferSize(g_hConOut, coord);
Bram Moolenaar78d21da2019-02-17 15:00:52 +01008935
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00008936 newsize.Left = 0;
8937 newsize.Top = 0;
8938 newsize.Right = coord.X - 1;
8939 newsize.Bottom = coord.Y - 1;
8940 SetConsoleWindowInfo(g_hConOut, TRUE, &newsize);
8941
8942 SetConsoleScreenBufferSize(g_hConOut, coord);
Bram Moolenaar78d21da2019-02-17 15:00:52 +01008943}
8944#endif
Martin Tournoij1a3e5742021-07-24 13:57:29 +02008945
8946 char *
8947GetWin32Error(void)
8948{
K.Takatad68b2fc2022-02-12 11:18:37 +00008949 static char *oldmsg = NULL;
Martin Tournoij1a3e5742021-07-24 13:57:29 +02008950 char *msg = NULL;
K.Takatad68b2fc2022-02-12 11:18:37 +00008951
Martin Tournoij1a3e5742021-07-24 13:57:29 +02008952 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER|FORMAT_MESSAGE_FROM_SYSTEM,
8953 NULL, GetLastError(), 0, (LPSTR)&msg, 0, NULL);
K.Takatad68b2fc2022-02-12 11:18:37 +00008954 if (oldmsg != NULL)
8955 LocalFree(oldmsg);
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00008956 if (msg == NULL)
8957 return NULL;
8958
8959 // remove trailing \r\n
8960 char *pcrlf = strstr(msg, "\r\n");
8961 if (pcrlf != NULL)
8962 *pcrlf = '\0';
8963 oldmsg = msg;
Martin Tournoij1a3e5742021-07-24 13:57:29 +02008964 return msg;
8965}
Paul Ollis65745772022-06-05 16:55:54 +01008966
8967#if defined(FEAT_RELTIME) || defined(PROTO)
8968static HANDLE timer_handle;
8969static int timer_active = FALSE;
8970
8971/*
8972 * Calls to start_timeout alternate the return value pointer between the two
8973 * entries in timeout_flags. If the previously active timeout is very close to
8974 * expiring when start_timeout() is called then a race condition means that the
8975 * set_flag() function may still be invoked after the previous timer is
8976 * deleted. Ping-ponging between the two flags prevents this causing 'fake'
8977 * timeouts.
8978 */
Bram Moolenaar155f2d12022-06-20 13:38:33 +01008979static sig_atomic_t timeout_flags[2];
8980static int timeout_flag_idx = 0;
8981static sig_atomic_t *timeout_flag = &timeout_flags[0];
Paul Ollis65745772022-06-05 16:55:54 +01008982
8983
8984 static void CALLBACK
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +01008985set_flag(void *param, BOOLEAN unused2 UNUSED)
Paul Ollis65745772022-06-05 16:55:54 +01008986{
8987 int *timeout_flag = (int *)param;
8988
8989 *timeout_flag = TRUE;
8990}
8991
8992/*
8993 * Stop any active timeout.
8994 */
8995 void
8996stop_timeout(void)
8997{
8998 if (timer_active)
8999 {
Christopher Plewright2a46f812022-10-16 19:47:45 +01009000 BOOL ret = DeleteTimerQueueTimer(NULL, timer_handle, NULL);
Paul Ollis65745772022-06-05 16:55:54 +01009001 timer_active = FALSE;
9002 if (!ret && GetLastError() != ERROR_IO_PENDING)
9003 {
9004 semsg(_(e_could_not_clear_timeout_str), GetWin32Error());
9005 }
9006 }
9007 *timeout_flag = FALSE;
9008}
9009
9010/*
9011 * Start the timeout timer.
9012 *
9013 * The period is defined in milliseconds.
9014 *
9015 * The return value is a pointer to a flag that is initialised to 0. If the
9016 * timeout expires, the flag is set to 1. This will only return pointers to
9017 * static memory; i.e. any pointer returned by this function may always be
9018 * safely dereferenced.
9019 *
9020 * This function is not expected to fail, but if it does it still returns a
9021 * valid flag pointer; the flag will remain stuck at zero.
9022 */
Bram Moolenaar155f2d12022-06-20 13:38:33 +01009023 volatile sig_atomic_t *
Paul Ollis65745772022-06-05 16:55:54 +01009024start_timeout(long msec)
9025{
Paul Ollis65745772022-06-05 16:55:54 +01009026 BOOL ret;
9027
Bram Moolenaar1f30caf2022-06-19 14:36:35 +01009028 timeout_flag = &timeout_flags[timeout_flag_idx];
Paul Ollis65745772022-06-05 16:55:54 +01009029
9030 stop_timeout();
9031 ret = CreateTimerQueueTimer(
9032 &timer_handle, NULL, set_flag, timeout_flag,
9033 (DWORD)msec, 0, WT_EXECUTEDEFAULT);
9034 if (!ret)
9035 {
9036 semsg(_(e_could_not_set_timeout_str), GetWin32Error());
9037 }
9038 else
9039 {
Bram Moolenaar1f30caf2022-06-19 14:36:35 +01009040 timeout_flag_idx = (timeout_flag_idx + 1) % 2;
Paul Ollis65745772022-06-05 16:55:54 +01009041 timer_active = TRUE;
9042 *timeout_flag = FALSE;
9043 }
9044 return timeout_flag;
9045}
9046#endif