blob: a9d48633d06a7c062b69cd31bf1bba9f009c0f79 [file] [log] [blame]
Bram Moolenaaredf3f972016-08-29 22:49:24 +02001/* vi:set ts=8 sts=4 sw=4 noet:
Bram Moolenaar071d4272004-06-13 20:20:40 +00002 *
3 * VIM - Vi IMproved by Bram Moolenaar
4 *
5 * Do ":help uganda" in Vim to read copying and usage conditions.
6 * Do ":help credits" in Vim to see a list of people who contributed.
7 * See README.txt for an overview of the Vim source code.
8 */
9/*
10 * os_win32.c
11 *
12 * Used for both the console version and the Win32 GUI. A lot of code is for
Bram Moolenaar4f974752019-02-17 17:44:42 +010013 * the console version only, so there is a lot of "#ifndef FEAT_GUI_MSWIN".
Bram Moolenaar071d4272004-06-13 20:20:40 +000014 *
15 * Win32 (Windows NT and Windows 95) system-dependent routines.
16 * Portions lifted from the Win32 SDK samples, the MSDOS-dependent code,
17 * NetHack 3.1.3, GNU Emacs 19.30, and Vile 5.5.
18 *
19 * George V. Reilly <george@reilly.org> wrote most of this.
20 * Roger Knobbe <rogerk@wonderware.com> did the initial port of Vim 3.0.
21 */
22
Bram Moolenaar071d4272004-06-13 20:20:40 +000023#include "vim.h"
24
Bram Moolenaar325b7a22004-07-05 15:58:32 +000025#ifdef FEAT_MZSCHEME
26# include "if_mzsch.h"
27#endif
28
Bram Moolenaar071d4272004-06-13 20:20:40 +000029#include <sys/types.h>
Bram Moolenaar071d4272004-06-13 20:20:40 +000030#include <signal.h>
31#include <limits.h>
Bram Moolenaar82881492012-11-20 16:53:39 +010032
Bram Moolenaar0f873732019-12-05 20:28:46 +010033// cproto fails on missing include files
Bram Moolenaar82881492012-11-20 16:53:39 +010034#ifndef PROTO
35# include <process.h>
Bram Moolenaare7bebc42021-02-01 20:50:37 +010036# include <winternl.h>
Bram Moolenaar82881492012-11-20 16:53:39 +010037#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +000038
39#undef chdir
40#ifdef __GNUC__
41# ifndef __MINGW32__
42# include <dirent.h>
43# endif
44#else
45# include <direct.h>
46#endif
47
Bram Moolenaar82881492012-11-20 16:53:39 +010048#ifndef PROTO
Bram Moolenaar651fca82021-11-29 20:39:38 +000049# if !defined(FEAT_GUI_MSWIN)
Bram Moolenaar82881492012-11-20 16:53:39 +010050# include <shellapi.h>
51# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +000052#endif
53
Bram Moolenaarfb630902016-10-29 14:55:00 +020054#ifdef FEAT_JOB_CHANNEL
55# include <tlhelp32.h>
56#endif
57
Bram Moolenaar071d4272004-06-13 20:20:40 +000058#ifdef __MINGW32__
59# ifndef FROM_LEFT_1ST_BUTTON_PRESSED
60# define FROM_LEFT_1ST_BUTTON_PRESSED 0x0001
61# endif
62# ifndef RIGHTMOST_BUTTON_PRESSED
63# define RIGHTMOST_BUTTON_PRESSED 0x0002
64# endif
65# ifndef FROM_LEFT_2ND_BUTTON_PRESSED
66# define FROM_LEFT_2ND_BUTTON_PRESSED 0x0004
67# endif
68# ifndef FROM_LEFT_3RD_BUTTON_PRESSED
69# define FROM_LEFT_3RD_BUTTON_PRESSED 0x0008
70# endif
71# ifndef FROM_LEFT_4TH_BUTTON_PRESSED
72# define FROM_LEFT_4TH_BUTTON_PRESSED 0x0010
73# endif
74
75/*
76 * EventFlags
77 */
78# ifndef MOUSE_MOVED
79# define MOUSE_MOVED 0x0001
80# endif
81# ifndef DOUBLE_CLICK
82# define DOUBLE_CLICK 0x0002
83# endif
84#endif
85
Bram Moolenaar0f873732019-12-05 20:28:46 +010086// Record all output and all keyboard & mouse input
87// #define MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +000088
89#ifdef MCH_WRITE_DUMP
90FILE* fdDump = NULL;
91#endif
92
93/*
94 * When generating prototypes for Win32 on Unix, these lines make the syntax
95 * errors disappear. They do not need to be correct.
96 */
97#ifdef PROTO
Bram Moolenaar912bc4a2019-12-01 18:58:11 +010098# define WINAPI
Bram Moolenaar071d4272004-06-13 20:20:40 +000099typedef char * LPCSTR;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000100typedef char * LPWSTR;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000101typedef int ACCESS_MASK;
102typedef int BOOL;
Paul Ollis65745772022-06-05 16:55:54 +0100103typedef int BOOLEAN;
104typedef int CALLBACK;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000105typedef int COLORREF;
106typedef int CONSOLE_CURSOR_INFO;
107typedef int COORD;
108typedef int DWORD;
109typedef int HANDLE;
Bram Moolenaaref269542016-01-19 13:22:12 +0100110typedef int LPHANDLE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000111typedef int HDC;
112typedef int HFONT;
113typedef int HICON;
114typedef int HINSTANCE;
115typedef int HWND;
116typedef int INPUT_RECORD;
Bram Moolenaare0ab9792017-08-02 23:18:25 +0200117typedef int INT;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000118typedef int KEY_EVENT_RECORD;
119typedef int LOGFONT;
120typedef int LPBOOL;
121typedef int LPCTSTR;
122typedef int LPDWORD;
123typedef int LPSTR;
124typedef int LPTSTR;
125typedef int LPVOID;
126typedef int MOUSE_EVENT_RECORD;
127typedef int PACL;
128typedef int PDWORD;
129typedef int PHANDLE;
130typedef int PRINTDLG;
131typedef int PSECURITY_DESCRIPTOR;
132typedef int PSID;
133typedef int SECURITY_INFORMATION;
134typedef int SHORT;
135typedef int SMALL_RECT;
136typedef int TEXTMETRIC;
137typedef int TOKEN_INFORMATION_CLASS;
138typedef int TRUSTEE;
139typedef int WORD;
140typedef int WCHAR;
141typedef void VOID;
Bram Moolenaar82881492012-11-20 16:53:39 +0100142typedef int BY_HANDLE_FILE_INFORMATION;
Bram Moolenaar32ac8cd2013-07-03 18:49:17 +0200143typedef int SE_OBJECT_TYPE;
144typedef int PSNSECINFO;
145typedef int PSNSECINFOW;
Bram Moolenaarb8e0bdb2014-11-12 16:10:48 +0100146typedef int STARTUPINFO;
147typedef int PROCESS_INFORMATION;
Bram Moolenaard90b6c02016-08-28 18:10:45 +0200148typedef int LPSECURITY_ATTRIBUTES;
Bram Moolenaar0f873732019-12-05 20:28:46 +0100149# define __stdcall // empty
Bram Moolenaar071d4272004-06-13 20:20:40 +0000150#endif
151
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200152#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar0f873732019-12-05 20:28:46 +0100153// Win32 Console handles for input and output
Bram Moolenaar071d4272004-06-13 20:20:40 +0000154static HANDLE g_hConIn = INVALID_HANDLE_VALUE;
155static HANDLE g_hConOut = INVALID_HANDLE_VALUE;
156
Bram Moolenaar0f873732019-12-05 20:28:46 +0100157// Win32 Screen buffer,coordinate,console I/O information
Bram Moolenaar071d4272004-06-13 20:20:40 +0000158static SMALL_RECT g_srScrollRegion;
Bram Moolenaar0f873732019-12-05 20:28:46 +0100159static COORD g_coord; // 0-based, but external coords are 1-based
Bram Moolenaar071d4272004-06-13 20:20:40 +0000160
Bram Moolenaar0f873732019-12-05 20:28:46 +0100161// The attribute of the screen when the editor was started
162static WORD g_attrDefault = 7; // lightgray text on black background
Bram Moolenaar071d4272004-06-13 20:20:40 +0000163static WORD g_attrCurrent;
164
Bram Moolenaar0f873732019-12-05 20:28:46 +0100165static int g_fCBrkPressed = FALSE; // set by ctrl-break interrupt
166static int g_fCtrlCPressed = FALSE; // set when ctrl-C or ctrl-break detected
167static int g_fForceExit = FALSE; // set when forcefully exiting
Bram Moolenaar071d4272004-06-13 20:20:40 +0000168
Bram Moolenaar071d4272004-06-13 20:20:40 +0000169static void scroll(unsigned cLines);
170static void set_scroll_region(unsigned left, unsigned top,
171 unsigned right, unsigned bottom);
Bram Moolenaar6982f422019-02-16 16:48:01 +0100172static void set_scroll_region_tb(unsigned top, unsigned bottom);
173static void set_scroll_region_lr(unsigned left, unsigned right);
174static void insert_lines(unsigned cLines);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000175static void delete_lines(unsigned cLines);
176static void gotoxy(unsigned x, unsigned y);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000177static void standout(void);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000178static int s_cursor_visible = TRUE;
179static int did_create_conin = FALSE;
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200180#endif
181#ifdef FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +0000182static int s_dont_use_vimrun = TRUE;
183static int need_vimrun_warning = FALSE;
184static char *vimrun_path = "vimrun ";
185#endif
186
Bram Moolenaar12b559e2013-06-12 22:41:37 +0200187static int win32_getattrs(char_u *name);
188static int win32_setattrs(char_u *name, int attrs);
189static int win32_set_archive(char_u *name);
190
Bram Moolenaard9ef1b82019-02-13 19:23:10 +0100191static int conpty_working = 0;
Bram Moolenaar57da6982019-09-13 22:30:11 +0200192static int conpty_type = 0;
Bram Moolenaard9ef1b82019-02-13 19:23:10 +0100193static int conpty_stable = 0;
Bram Moolenaar7ed8f592020-04-28 20:44:42 +0200194static int conpty_fix_type = 0;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100195static void vtp_flag_init();
196
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200197#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar6902c0e2019-02-16 14:07:37 +0100198static int vtp_working = 0;
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100199static void vtp_init();
200static void vtp_exit();
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100201static void vtp_sgr_bulk(int arg);
202static void vtp_sgr_bulks(int argc, int *argv);
203
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200204static int wt_working = 0;
205static void wt_init();
206
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +0200207static int g_color_index_bg = 0;
208static int g_color_index_fg = 7;
209
210# ifdef FEAT_TERMGUICOLORS
Christopher Plewright38804d62022-11-09 23:55:52 +0000211static guicolor_T save_console_bg_rgb;
212static guicolor_T save_console_fg_rgb;
213static guicolor_T store_console_bg_rgb;
214static guicolor_T store_console_fg_rgb;
Yasuhiro Matsumotoe42c8da2022-09-01 11:31:45 +0100215static int default_console_color_bg = 0x000000; // black
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +0200216static int default_console_color_fg = 0xc0c0c0; // white
Christopher Plewright38804d62022-11-09 23:55:52 +0000217# define USE_VTP (vtp_working && is_term_win32())
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200218# define USE_WT (wt_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100219# else
220# define USE_VTP 0
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200221# define USE_WT 0
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100222# endif
223
224static void set_console_color_rgb(void);
225static void reset_console_color_rgb(void);
Bram Moolenaardf543822020-01-30 11:53:59 +0100226static void restore_console_color_rgb(void);
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100227#endif
228
Bram Moolenaar0f873732019-12-05 20:28:46 +0100229// This flag is newly created from Windows 10
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100230#ifndef ENABLE_VIRTUAL_TERMINAL_PROCESSING
231# define ENABLE_VIRTUAL_TERMINAL_PROCESSING 0x0004
232#endif
233
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200234#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar0f873732019-12-05 20:28:46 +0100235static int suppress_winsize = 1; // don't fiddle with console
Bram Moolenaar071d4272004-06-13 20:20:40 +0000236#endif
237
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200238static char_u *exe_path = NULL;
239
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100240static BOOL win8_or_later = FALSE;
241
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100242/*
243 * Get version number including build number
244 */
245typedef BOOL (WINAPI *PfnRtlGetVersion)(LPOSVERSIONINFOW);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100246#define MAKE_VER(major, minor, build) \
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100247 (((major) << 24) | ((minor) << 16) | (build))
248
249 static DWORD
250get_build_number(void)
251{
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +0100252 OSVERSIONINFOW osver;
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100253 HMODULE hNtdll;
254 PfnRtlGetVersion pRtlGetVersion;
255 DWORD ver = MAKE_VER(0, 0, 0);
256
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +0100257 osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFOW);
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100258 hNtdll = GetModuleHandle("ntdll.dll");
259 if (hNtdll != NULL)
260 {
261 pRtlGetVersion =
262 (PfnRtlGetVersion)GetProcAddress(hNtdll, "RtlGetVersion");
263 pRtlGetVersion(&osver);
264 ver = MAKE_VER(min(osver.dwMajorVersion, 255),
265 min(osver.dwMinorVersion, 255),
266 min(osver.dwBuildNumber, 32767));
267 }
268 return ver;
269}
270
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200271#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200272 static BOOL
273is_ambiwidth_event(
274 INPUT_RECORD *ir)
275{
276 return ir->EventType == KEY_EVENT
277 && ir->Event.KeyEvent.bKeyDown
278 && ir->Event.KeyEvent.wRepeatCount == 1
279 && ir->Event.KeyEvent.wVirtualKeyCode == 0x12
280 && ir->Event.KeyEvent.wVirtualScanCode == 0x38
K.Takata972db232022-02-04 10:45:38 +0000281 && ir->Event.KeyEvent.uChar.UnicodeChar == 0
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200282 && ir->Event.KeyEvent.dwControlKeyState == 2;
283}
284
285 static void
286make_ambiwidth_event(
287 INPUT_RECORD *down,
288 INPUT_RECORD *up)
289{
290 down->Event.KeyEvent.wVirtualKeyCode = 0;
291 down->Event.KeyEvent.wVirtualScanCode = 0;
K.Takata972db232022-02-04 10:45:38 +0000292 down->Event.KeyEvent.uChar.UnicodeChar
293 = up->Event.KeyEvent.uChar.UnicodeChar;
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200294 down->Event.KeyEvent.dwControlKeyState = 0;
295}
296
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100297/*
298 * Version of ReadConsoleInput() that works with IME.
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100299 * Works around problems on Windows 8.
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100300 */
301 static BOOL
302read_console_input(
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100303 HANDLE hInput,
304 INPUT_RECORD *lpBuffer,
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +0100305 int nLength,
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100306 LPDWORD lpEvents)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100307{
308 enum
309 {
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100310 IRSIZE = 10
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100311 };
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100312 static INPUT_RECORD s_irCache[IRSIZE];
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100313 static DWORD s_dwIndex = 0;
314 static DWORD s_dwMax = 0;
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100315 DWORD dwEvents;
Bram Moolenaardd415a62014-02-05 14:02:27 +0100316 int head;
317 int tail;
318 int i;
Bram Moolenaarbc970da2020-04-26 19:00:07 +0200319 static INPUT_RECORD s_irPseudo;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100320
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200321 if (nLength == -2)
322 return (s_dwMax > 0) ? TRUE : FALSE;
323
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100324 if (!win8_or_later)
325 {
326 if (nLength == -1)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200327 return PeekConsoleInputW(hInput, lpBuffer, 1, lpEvents);
328 return ReadConsoleInputW(hInput, lpBuffer, 1, &dwEvents);
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100329 }
330
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100331 if (s_dwMax == 0)
332 {
Christopher Plewright38804d62022-11-09 23:55:52 +0000333 if (!vtp_working && nLength == -1)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200334 return PeekConsoleInputW(hInput, lpBuffer, 1, lpEvents);
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200335 GetNumberOfConsoleInputEvents(hInput, &dwEvents);
336 if (dwEvents == 0 && nLength == -1)
337 return PeekConsoleInputW(hInput, lpBuffer, 1, lpEvents);
338 ReadConsoleInputW(hInput, s_irCache, IRSIZE, &dwEvents);
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100339 s_dwIndex = 0;
340 s_dwMax = dwEvents;
341 if (dwEvents == 0)
342 {
343 *lpEvents = 0;
344 return TRUE;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100345 }
Bram Moolenaardd415a62014-02-05 14:02:27 +0100346
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200347 for (i = s_dwIndex; i < (int)s_dwMax - 1; ++i)
348 if (is_ambiwidth_event(&s_irCache[i]))
349 make_ambiwidth_event(&s_irCache[i], &s_irCache[i + 1]);
350
Bram Moolenaardd415a62014-02-05 14:02:27 +0100351 if (s_dwMax > 1)
352 {
353 head = 0;
354 tail = s_dwMax - 1;
355 while (head != tail)
356 {
357 if (s_irCache[head].EventType == WINDOW_BUFFER_SIZE_EVENT
358 && s_irCache[head + 1].EventType
359 == WINDOW_BUFFER_SIZE_EVENT)
360 {
Bram Moolenaar0f873732019-12-05 20:28:46 +0100361 // Remove duplicate event to avoid flicker.
Bram Moolenaardd415a62014-02-05 14:02:27 +0100362 for (i = head; i < tail; ++i)
363 s_irCache[i] = s_irCache[i + 1];
364 --tail;
365 continue;
366 }
367 head++;
368 }
369 s_dwMax = tail + 1;
370 }
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100371 }
Bram Moolenaardd415a62014-02-05 14:02:27 +0100372
Bram Moolenaarbc970da2020-04-26 19:00:07 +0200373 if (s_irCache[s_dwIndex].EventType == KEY_EVENT)
374 {
375 if (s_irCache[s_dwIndex].Event.KeyEvent.wRepeatCount > 1)
376 {
377 s_irPseudo = s_irCache[s_dwIndex];
378 s_irPseudo.Event.KeyEvent.wRepeatCount = 1;
379 s_irCache[s_dwIndex].Event.KeyEvent.wRepeatCount--;
380 *lpBuffer = s_irPseudo;
381 *lpEvents = 1;
382 return TRUE;
383 }
384 }
385
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100386 *lpBuffer = s_irCache[s_dwIndex];
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200387 if (!(nLength == -1 || nLength == -2) && ++s_dwIndex >= s_dwMax)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100388 s_dwMax = 0;
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100389 *lpEvents = 1;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100390 return TRUE;
391}
392
393/*
394 * Version of PeekConsoleInput() that works with IME.
395 */
396 static BOOL
397peek_console_input(
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100398 HANDLE hInput,
399 INPUT_RECORD *lpBuffer,
Bram Moolenaarbd67aac2019-09-21 23:09:04 +0200400 DWORD nLength UNUSED,
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100401 LPDWORD lpEvents)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100402{
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +0100403 return read_console_input(hInput, lpBuffer, -1, lpEvents);
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100404}
405
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100406# ifdef FEAT_CLIENTSERVER
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200407 static DWORD
408msg_wait_for_multiple_objects(
409 DWORD nCount,
410 LPHANDLE pHandles,
411 BOOL fWaitAll,
412 DWORD dwMilliseconds,
413 DWORD dwWakeMask)
414{
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +0100415 if (read_console_input(NULL, NULL, -2, NULL))
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200416 return WAIT_OBJECT_0;
417 return MsgWaitForMultipleObjects(nCount, pHandles, fWaitAll,
418 dwMilliseconds, dwWakeMask);
419}
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100420# endif
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200421
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100422# ifndef FEAT_CLIENTSERVER
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200423 static DWORD
424wait_for_single_object(
425 HANDLE hHandle,
426 DWORD dwMilliseconds)
427{
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +0100428 if (read_console_input(NULL, NULL, -2, NULL))
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200429 return WAIT_OBJECT_0;
430 return WaitForSingleObject(hHandle, dwMilliseconds);
431}
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100432# endif
433#endif
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200434
Bram Moolenaar071d4272004-06-13 20:20:40 +0000435 static void
436get_exe_name(void)
437{
Bram Moolenaar0f873732019-12-05 20:28:46 +0100438 // Maximum length of $PATH is more than MAXPATHL. 8191 is often mentioned
439 // as the maximum length that works (plus a NUL byte).
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100440#define MAX_ENV_PATH_LEN 8192
441 char temp[MAX_ENV_PATH_LEN];
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200442 char_u *p;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000443
444 if (exe_name == NULL)
445 {
Bram Moolenaar0f873732019-12-05 20:28:46 +0100446 // store the name of the executable, may be used for $VIM
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100447 GetModuleFileName(NULL, temp, MAX_ENV_PATH_LEN - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000448 if (*temp != NUL)
449 exe_name = FullName_save((char_u *)temp, FALSE);
450 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000451
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200452 if (exe_path == NULL && exe_name != NULL)
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000453 {
Bram Moolenaar71ccd032020-06-12 22:59:11 +0200454 exe_path = vim_strnsave(exe_name, gettail_sep(exe_name) - exe_name);
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200455 if (exe_path != NULL)
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000456 {
Bram Moolenaar0f873732019-12-05 20:28:46 +0100457 // Append our starting directory to $PATH, so that when doing
458 // "!xxd" it's found in our starting directory. Needed because
459 // SearchPath() also looks there.
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200460 p = mch_getenv("PATH");
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100461 if (p == NULL
462 || STRLEN(p) + STRLEN(exe_path) + 2 < MAX_ENV_PATH_LEN)
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200463 {
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100464 if (p == NULL || *p == NUL)
465 temp[0] = NUL;
466 else
467 {
468 STRCPY(temp, p);
469 STRCAT(temp, ";");
470 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200471 STRCAT(temp, exe_path);
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +0100472 vim_setenv((char_u *)"PATH", (char_u *)temp);
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200473 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000474 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000475 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000476}
477
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200478/*
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100479 * Unescape characters in "p" that appear in "escaped".
480 */
481 static void
482unescape_shellxquote(char_u *p, char_u *escaped)
483{
Bram Moolenaar4336cdf2012-02-29 13:58:47 +0100484 int l = (int)STRLEN(p);
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100485 int n;
486
487 while (*p != NUL)
488 {
489 if (*p == '^' && vim_strchr(escaped, p[1]) != NULL)
490 mch_memmove(p, p + 1, l--);
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100491 n = (*mb_ptr2len)(p);
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100492 p += n;
493 l -= n;
494 }
495}
496
497/*
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200498 * Load library "name".
499 */
500 HINSTANCE
K.Takatad68b2fc2022-02-12 11:18:37 +0000501vimLoadLib(const char *name)
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200502{
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200503 HINSTANCE dll = NULL;
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200504
Bram Moolenaar3d0e7a92021-05-01 17:46:03 +0200505 // No need to load any library when registering OLE.
506 if (found_register_arg)
507 return dll;
508
Bram Moolenaar0f873732019-12-05 20:28:46 +0100509 // NOTE: Do not use mch_dirname() and mch_chdir() here, they may call
510 // vimLoadLib() recursively, which causes a stack overflow.
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200511 if (exe_path == NULL)
512 get_exe_name();
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200513 if (exe_path != NULL)
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200514 {
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200515 WCHAR old_dirw[MAXPATHL];
516
517 if (GetCurrentDirectoryW(MAXPATHL, old_dirw) != 0)
518 {
Bram Moolenaar0f873732019-12-05 20:28:46 +0100519 // Change directory to where the executable is, both to make
520 // sure we find a .dll there and to avoid looking for a .dll
521 // in the current directory.
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +0100522 SetCurrentDirectory((LPCSTR)exe_path);
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200523 dll = LoadLibrary(name);
524 SetCurrentDirectoryW(old_dirw);
525 return dll;
526 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200527 }
528 return dll;
529}
530
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200531#if defined(VIMDLL) || defined(PROTO)
532/*
533 * Check if the current executable file is for the GUI subsystem.
534 */
535 int
536mch_is_gui_executable(void)
537{
538 PBYTE pImage = (PBYTE)GetModuleHandle(NULL);
539 PIMAGE_DOS_HEADER pDOS = (PIMAGE_DOS_HEADER)pImage;
540 PIMAGE_NT_HEADERS pPE;
541
542 if (pDOS->e_magic != IMAGE_DOS_SIGNATURE)
543 return FALSE;
544 pPE = (PIMAGE_NT_HEADERS)(pImage + pDOS->e_lfanew);
545 if (pPE->Signature != IMAGE_NT_SIGNATURE)
546 return FALSE;
547 if (pPE->OptionalHeader.Subsystem == IMAGE_SUBSYSTEM_WINDOWS_GUI)
548 return TRUE;
549 return FALSE;
550}
551#endif
552
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000553#if defined(DYNAMIC_ICONV) || defined(DYNAMIC_GETTEXT) \
554 || defined(FEAT_PYTHON3) || defined(PROTO)
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100555/*
556 * Get related information about 'funcname' which is imported by 'hInst'.
557 * If 'info' is 0, return the function address.
558 * If 'info' is 1, return the module name which the function is imported from.
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000559 * If 'info' is 2, hook the function with 'ptr', and return the original
560 * function address.
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100561 */
562 static void *
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000563get_imported_func_info(HINSTANCE hInst, const char *funcname, int info,
564 const void *ptr)
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100565{
566 PBYTE pImage = (PBYTE)hInst;
567 PIMAGE_DOS_HEADER pDOS = (PIMAGE_DOS_HEADER)hInst;
568 PIMAGE_NT_HEADERS pPE;
569 PIMAGE_IMPORT_DESCRIPTOR pImpDesc;
Bram Moolenaar0f873732019-12-05 20:28:46 +0100570 PIMAGE_THUNK_DATA pIAT; // Import Address Table
571 PIMAGE_THUNK_DATA pINT; // Import Name Table
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100572 PIMAGE_IMPORT_BY_NAME pImpName;
573
574 if (pDOS->e_magic != IMAGE_DOS_SIGNATURE)
575 return NULL;
576 pPE = (PIMAGE_NT_HEADERS)(pImage + pDOS->e_lfanew);
577 if (pPE->Signature != IMAGE_NT_SIGNATURE)
578 return NULL;
579 pImpDesc = (PIMAGE_IMPORT_DESCRIPTOR)(pImage
580 + pPE->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT]
581 .VirtualAddress);
582 for (; pImpDesc->FirstThunk; ++pImpDesc)
583 {
584 if (!pImpDesc->OriginalFirstThunk)
585 continue;
586 pIAT = (PIMAGE_THUNK_DATA)(pImage + pImpDesc->FirstThunk);
587 pINT = (PIMAGE_THUNK_DATA)(pImage + pImpDesc->OriginalFirstThunk);
588 for (; pIAT->u1.Function; ++pIAT, ++pINT)
589 {
590 if (IMAGE_SNAP_BY_ORDINAL(pINT->u1.Ordinal))
591 continue;
592 pImpName = (PIMAGE_IMPORT_BY_NAME)(pImage
593 + (UINT_PTR)(pINT->u1.AddressOfData));
594 if (strcmp((char *)pImpName->Name, funcname) == 0)
595 {
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000596 void *original;
597 DWORD old, new = PAGE_READWRITE;
598
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100599 switch (info)
600 {
601 case 0:
602 return (void *)pIAT->u1.Function;
603 case 1:
604 return (void *)(pImage + pImpDesc->Name);
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000605 case 2:
606 original = (void *)pIAT->u1.Function;
607 VirtualProtect(&pIAT->u1.Function, sizeof(void *),
608 new, &old);
609 pIAT->u1.Function = (UINT_PTR)ptr;
610 VirtualProtect(&pIAT->u1.Function, sizeof(void *),
611 old, &new);
612 return original;
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100613 default:
614 return NULL;
615 }
616 }
617 }
618 }
619 return NULL;
620}
621
622/*
623 * Get the module handle which 'funcname' in 'hInst' is imported from.
624 */
625 HINSTANCE
626find_imported_module_by_funcname(HINSTANCE hInst, const char *funcname)
627{
628 char *modulename;
629
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000630 modulename = (char *)get_imported_func_info(hInst, funcname, 1, NULL);
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100631 if (modulename != NULL)
632 return GetModuleHandleA(modulename);
633 return NULL;
634}
635
636/*
637 * Get the address of 'funcname' which is imported by 'hInst' DLL.
638 */
639 void *
640get_dll_import_func(HINSTANCE hInst, const char *funcname)
641{
Bram Moolenaar63ff72a2022-02-07 13:54:01 +0000642 return get_imported_func_info(hInst, funcname, 0, NULL);
643}
644
645/*
646 * Hook the function named 'funcname' which is imported by 'hInst' DLL,
647 * and return the original function address.
648 */
649 void *
650hook_dll_import_func(HINSTANCE hInst, const char *funcname, const void *hook)
651{
652 return get_imported_func_info(hInst, funcname, 2, hook);
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100653}
654#endif
655
Bram Moolenaar071d4272004-06-13 20:20:40 +0000656#if defined(DYNAMIC_GETTEXT) || defined(PROTO)
657# ifndef GETTEXT_DLL
658# define GETTEXT_DLL "libintl.dll"
Bram Moolenaar7554c542018-10-06 15:03:15 +0200659# define GETTEXT_DLL_ALT1 "libintl-8.dll"
660# define GETTEXT_DLL_ALT2 "intl.dll"
Bram Moolenaar071d4272004-06-13 20:20:40 +0000661# endif
Bram Moolenaar0f873732019-12-05 20:28:46 +0100662// Dummy functions
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000663static char *null_libintl_gettext(const char *);
Bram Moolenaaree695f72016-08-03 22:08:45 +0200664static char *null_libintl_ngettext(const char *, const char *, unsigned long n);
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000665static char *null_libintl_textdomain(const char *);
666static char *null_libintl_bindtextdomain(const char *, const char *);
667static char *null_libintl_bind_textdomain_codeset(const char *, const char *);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100668static int null_libintl_wputenv(const wchar_t *);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000669
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200670static HINSTANCE hLibintlDLL = NULL;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000671char *(*dyn_libintl_gettext)(const char *) = null_libintl_gettext;
Bram Moolenaaree695f72016-08-03 22:08:45 +0200672char *(*dyn_libintl_ngettext)(const char *, const char *, unsigned long n)
673 = null_libintl_ngettext;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000674char *(*dyn_libintl_textdomain)(const char *) = null_libintl_textdomain;
675char *(*dyn_libintl_bindtextdomain)(const char *, const char *)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000676 = null_libintl_bindtextdomain;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000677char *(*dyn_libintl_bind_textdomain_codeset)(const char *, const char *)
678 = null_libintl_bind_textdomain_codeset;
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100679int (*dyn_libintl_wputenv)(const wchar_t *) = null_libintl_wputenv;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000680
681 int
Bram Moolenaar05540972016-01-30 20:31:25 +0100682dyn_libintl_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000683{
684 int i;
685 static struct
686 {
687 char *name;
688 FARPROC *ptr;
689 } libintl_entry[] =
690 {
691 {"gettext", (FARPROC*)&dyn_libintl_gettext},
Bram Moolenaaree695f72016-08-03 22:08:45 +0200692 {"ngettext", (FARPROC*)&dyn_libintl_ngettext},
Bram Moolenaar071d4272004-06-13 20:20:40 +0000693 {"textdomain", (FARPROC*)&dyn_libintl_textdomain},
694 {"bindtextdomain", (FARPROC*)&dyn_libintl_bindtextdomain},
695 {NULL, NULL}
696 };
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100697 HINSTANCE hmsvcrt;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000698
Bram Moolenaar7554c542018-10-06 15:03:15 +0200699 // No need to initialize twice.
700 if (hLibintlDLL != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000701 return 1;
Bram Moolenaar7554c542018-10-06 15:03:15 +0200702 // Load gettext library (libintl.dll and other names).
Bram Moolenaar923e43b2016-01-28 15:07:38 +0100703 hLibintlDLL = vimLoadLib(GETTEXT_DLL);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100704# ifdef GETTEXT_DLL_ALT1
Bram Moolenaar286eacd2016-01-16 18:05:50 +0100705 if (!hLibintlDLL)
Bram Moolenaar7554c542018-10-06 15:03:15 +0200706 hLibintlDLL = vimLoadLib(GETTEXT_DLL_ALT1);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100707# endif
708# ifdef GETTEXT_DLL_ALT2
Bram Moolenaar7554c542018-10-06 15:03:15 +0200709 if (!hLibintlDLL)
710 hLibintlDLL = vimLoadLib(GETTEXT_DLL_ALT2);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100711# endif
Bram Moolenaar938ee832016-01-24 15:36:03 +0100712 if (!hLibintlDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000713 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200714 if (p_verbose > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000715 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200716 verbose_enter();
Bram Moolenaar460ae5d2022-01-01 14:19:49 +0000717 semsg(_(e_could_not_load_library_str_str), GETTEXT_DLL, GetWin32Error());
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200718 verbose_leave();
Bram Moolenaar071d4272004-06-13 20:20:40 +0000719 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200720 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000721 }
722 for (i = 0; libintl_entry[i].name != NULL
723 && libintl_entry[i].ptr != NULL; ++i)
724 {
K.Takata54119102022-02-03 13:33:03 +0000725 if ((*libintl_entry[i].ptr = GetProcAddress(hLibintlDLL,
Bram Moolenaar071d4272004-06-13 20:20:40 +0000726 libintl_entry[i].name)) == NULL)
727 {
728 dyn_libintl_end();
729 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +0000730 {
731 verbose_enter();
Bram Moolenaar460ae5d2022-01-01 14:19:49 +0000732 semsg(_(e_could_not_load_library_function_str), libintl_entry[i].name);
Bram Moolenaara04f10b2005-05-31 22:09:46 +0000733 verbose_leave();
734 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000735 return 0;
736 }
737 }
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000738
Bram Moolenaar0f873732019-12-05 20:28:46 +0100739 // The bind_textdomain_codeset() function is optional.
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +0100740 dyn_libintl_bind_textdomain_codeset = (char *(*)(const char *, const char *))
741 GetProcAddress(hLibintlDLL, "bind_textdomain_codeset");
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000742 if (dyn_libintl_bind_textdomain_codeset == NULL)
743 dyn_libintl_bind_textdomain_codeset =
744 null_libintl_bind_textdomain_codeset;
745
Bram Moolenaar0f873732019-12-05 20:28:46 +0100746 // _wputenv() function for the libintl.dll is optional.
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100747 hmsvcrt = find_imported_module_by_funcname(hLibintlDLL, "getenv");
748 if (hmsvcrt != NULL)
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +0100749 dyn_libintl_wputenv = (int (*)(const wchar_t *))
750 GetProcAddress(hmsvcrt, "_wputenv");
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100751 if (dyn_libintl_wputenv == NULL || dyn_libintl_wputenv == _wputenv)
752 dyn_libintl_wputenv = null_libintl_wputenv;
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100753
Bram Moolenaar071d4272004-06-13 20:20:40 +0000754 return 1;
755}
756
757 void
Bram Moolenaar05540972016-01-30 20:31:25 +0100758dyn_libintl_end(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000759{
760 if (hLibintlDLL)
761 FreeLibrary(hLibintlDLL);
762 hLibintlDLL = NULL;
763 dyn_libintl_gettext = null_libintl_gettext;
Bram Moolenaaree695f72016-08-03 22:08:45 +0200764 dyn_libintl_ngettext = null_libintl_ngettext;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000765 dyn_libintl_textdomain = null_libintl_textdomain;
766 dyn_libintl_bindtextdomain = null_libintl_bindtextdomain;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000767 dyn_libintl_bind_textdomain_codeset = null_libintl_bind_textdomain_codeset;
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100768 dyn_libintl_wputenv = null_libintl_wputenv;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000769}
770
771 static char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000772null_libintl_gettext(const char *msgid)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000773{
774 return (char*)msgid;
775}
776
777 static char *
Bram Moolenaaree695f72016-08-03 22:08:45 +0200778null_libintl_ngettext(
779 const char *msgid,
780 const char *msgid_plural,
781 unsigned long n)
782{
Bram Moolenaarc90f2ae2016-08-04 22:00:15 +0200783 return (char *)(n == 1 ? msgid : msgid_plural);
Bram Moolenaaree695f72016-08-03 22:08:45 +0200784}
785
Bram Moolenaaree695f72016-08-03 22:08:45 +0200786 static char *
Bram Moolenaar1266d672017-02-01 13:43:36 +0100787null_libintl_bindtextdomain(
788 const char *domainname UNUSED,
789 const char *dirname UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000790{
791 return NULL;
792}
793
794 static char *
Bram Moolenaar1266d672017-02-01 13:43:36 +0100795null_libintl_bind_textdomain_codeset(
796 const char *domainname UNUSED,
797 const char *codeset UNUSED)
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000798{
799 return NULL;
800}
801
802 static char *
Bram Moolenaar1266d672017-02-01 13:43:36 +0100803null_libintl_textdomain(const char *domainname UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000804{
805 return NULL;
806}
807
Bram Moolenaare0ab9792017-08-02 23:18:25 +0200808 static int
Bram Moolenaar1266d672017-02-01 13:43:36 +0100809null_libintl_wputenv(const wchar_t *envstring UNUSED)
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100810{
811 return 0;
812}
813
Bram Moolenaar0f873732019-12-05 20:28:46 +0100814#endif // DYNAMIC_GETTEXT
Bram Moolenaar071d4272004-06-13 20:20:40 +0000815
Bram Moolenaar0f873732019-12-05 20:28:46 +0100816// This symbol is not defined in older versions of the SDK or Visual C++
Bram Moolenaar071d4272004-06-13 20:20:40 +0000817
818#ifndef VER_PLATFORM_WIN32_WINDOWS
819# define VER_PLATFORM_WIN32_WINDOWS 1
820#endif
821
Bram Moolenaar071d4272004-06-13 20:20:40 +0000822#ifdef HAVE_ACL
Bram Moolenaar82881492012-11-20 16:53:39 +0100823# ifndef PROTO
824# include <aclapi.h>
825# endif
Bram Moolenaar27515922013-06-29 15:36:26 +0200826# ifndef PROTECTED_DACL_SECURITY_INFORMATION
827# define PROTECTED_DACL_SECURITY_INFORMATION 0x80000000L
828# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000829#endif
830
Bram Moolenaar27515922013-06-29 15:36:26 +0200831#ifdef HAVE_ACL
832/*
833 * Enables or disables the specified privilege.
834 */
835 static BOOL
836win32_enable_privilege(LPTSTR lpszPrivilege, BOOL bEnable)
837{
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100838 BOOL bResult;
839 LUID luid;
840 HANDLE hToken;
841 TOKEN_PRIVILEGES tokenPrivileges;
Bram Moolenaar27515922013-06-29 15:36:26 +0200842
843 if (!OpenProcessToken(GetCurrentProcess(),
844 TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
845 return FALSE;
846
847 if (!LookupPrivilegeValue(NULL, lpszPrivilege, &luid))
848 {
849 CloseHandle(hToken);
850 return FALSE;
851 }
852
Bram Moolenaar45500912014-07-09 20:51:07 +0200853 tokenPrivileges.PrivilegeCount = 1;
Bram Moolenaar27515922013-06-29 15:36:26 +0200854 tokenPrivileges.Privileges[0].Luid = luid;
855 tokenPrivileges.Privileges[0].Attributes = bEnable ?
856 SE_PRIVILEGE_ENABLED : 0;
857
858 bResult = AdjustTokenPrivileges(hToken, FALSE, &tokenPrivileges,
859 sizeof(TOKEN_PRIVILEGES), NULL, NULL);
860
861 CloseHandle(hToken);
862
863 return bResult && GetLastError() == ERROR_SUCCESS;
864}
865#endif
866
Bram Moolenaar29d2f452020-12-04 19:42:52 +0100867#ifdef _MSC_VER
868// Suppress the deprecation warning for using GetVersionEx().
869// It is needed for implementing "windowsversion()".
870# pragma warning(push)
871# pragma warning(disable: 4996)
872#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000873/*
Bram Moolenaar1e1d2e82020-05-18 20:17:02 +0200874 * Set "win8_or_later" and fill in "windowsVersion" if possible.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000875 */
876 void
877PlatformId(void)
878{
879 static int done = FALSE;
880
881 if (!done)
882 {
883 OSVERSIONINFO ovi;
884
885 ovi.dwOSVersionInfoSize = sizeof(ovi);
886 GetVersionEx(&ovi);
887
Bram Moolenaar1e1d2e82020-05-18 20:17:02 +0200888#ifdef FEAT_EVAL
Bram Moolenaar0c1e3742019-12-27 13:49:24 +0100889 vim_snprintf(windowsVersion, sizeof(windowsVersion), "%d.%d",
890 (int)ovi.dwMajorVersion, (int)ovi.dwMinorVersion);
Bram Moolenaar1e1d2e82020-05-18 20:17:02 +0200891#endif
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100892 if ((ovi.dwMajorVersion == 6 && ovi.dwMinorVersion >= 2)
893 || ovi.dwMajorVersion > 6)
894 win8_or_later = TRUE;
895
Bram Moolenaar071d4272004-06-13 20:20:40 +0000896#ifdef HAVE_ACL
Bram Moolenaar0f873732019-12-05 20:28:46 +0100897 // Enable privilege for getting or setting SACLs.
Bram Moolenaarcea912a2016-10-12 14:20:24 +0200898 win32_enable_privilege(SE_SECURITY_NAME, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000899#endif
900 done = TRUE;
901 }
902}
Bram Moolenaar29d2f452020-12-04 19:42:52 +0100903#ifdef _MSC_VER
904# pragma warning(pop)
905#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000906
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200907#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000908
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100909# define SHIFT (SHIFT_PRESSED)
910# define CTRL (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED)
911# define ALT (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED)
912# define ALT_GR (RIGHT_ALT_PRESSED | LEFT_CTRL_PRESSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000913
914
Bram Moolenaar0f873732019-12-05 20:28:46 +0100915// When uChar.AsciiChar is 0, then we need to look at wVirtualKeyCode.
916// We map function keys to their ANSI terminal equivalents, as produced
917// by ANSI.SYS, for compatibility with the MS-DOS version of Vim. Any
918// ANSI key with a value >= '\300' is nonstandard, but provided anyway
919// so that the user can have access to all SHIFT-, CTRL-, and ALT-
920// combinations of function/arrow/etc keys.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000921
Bram Moolenaard6f676d2005-06-01 21:51:55 +0000922static const struct
Bram Moolenaar071d4272004-06-13 20:20:40 +0000923{
924 WORD wVirtKey;
925 BOOL fAnsiKey;
926 int chAlone;
927 int chShift;
928 int chCtrl;
929 int chAlt;
930} VirtKeyMap[] =
931{
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200932// Key ANSI alone shift ctrl alt
Bram Moolenaar071d4272004-06-13 20:20:40 +0000933 { VK_ESCAPE,FALSE, ESC, ESC, ESC, ESC, },
934
935 { VK_F1, TRUE, ';', 'T', '^', 'h', },
936 { VK_F2, TRUE, '<', 'U', '_', 'i', },
937 { VK_F3, TRUE, '=', 'V', '`', 'j', },
938 { VK_F4, TRUE, '>', 'W', 'a', 'k', },
939 { VK_F5, TRUE, '?', 'X', 'b', 'l', },
940 { VK_F6, TRUE, '@', 'Y', 'c', 'm', },
941 { VK_F7, TRUE, 'A', 'Z', 'd', 'n', },
942 { VK_F8, TRUE, 'B', '[', 'e', 'o', },
943 { VK_F9, TRUE, 'C', '\\', 'f', 'p', },
944 { VK_F10, TRUE, 'D', ']', 'g', 'q', },
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200945 { VK_F11, TRUE, '\205', '\207', '\211', '\213', },
946 { VK_F12, TRUE, '\206', '\210', '\212', '\214', },
Bram Moolenaar071d4272004-06-13 20:20:40 +0000947
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200948 { VK_HOME, TRUE, 'G', '\302', 'w', '\303', },
949 { VK_UP, TRUE, 'H', '\304', '\305', '\306', },
950 { VK_PRIOR, TRUE, 'I', '\307', '\204', '\310', }, // PgUp
951 { VK_LEFT, TRUE, 'K', '\311', 's', '\312', },
952 { VK_RIGHT, TRUE, 'M', '\313', 't', '\314', },
953 { VK_END, TRUE, 'O', '\315', 'u', '\316', },
954 { VK_DOWN, TRUE, 'P', '\317', '\320', '\321', },
955 { VK_NEXT, TRUE, 'Q', '\322', 'v', '\323', }, // PgDn
956 { VK_INSERT,TRUE, 'R', '\324', '\325', '\326', },
957 { VK_DELETE,TRUE, 'S', '\327', '\330', '\331', },
Bram Moolenaarb70a47b2019-03-30 22:11:21 +0100958 { VK_BACK, TRUE, 'x', 'y', 'z', '{', }, // Backspace
Bram Moolenaar071d4272004-06-13 20:20:40 +0000959
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200960 { VK_SNAPSHOT,TRUE, 0, 0, 0, 'r', }, // PrtScrn
Bram Moolenaar071d4272004-06-13 20:20:40 +0000961
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100962# if 0
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200963 // Most people don't have F13-F20, but what the hell...
964 { VK_F13, TRUE, '\332', '\333', '\334', '\335', },
965 { VK_F14, TRUE, '\336', '\337', '\340', '\341', },
966 { VK_F15, TRUE, '\342', '\343', '\344', '\345', },
967 { VK_F16, TRUE, '\346', '\347', '\350', '\351', },
968 { VK_F17, TRUE, '\352', '\353', '\354', '\355', },
969 { VK_F18, TRUE, '\356', '\357', '\360', '\361', },
970 { VK_F19, TRUE, '\362', '\363', '\364', '\365', },
971 { VK_F20, TRUE, '\366', '\367', '\370', '\371', },
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100972# endif
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200973 { VK_ADD, TRUE, 'N', 'N', 'N', 'N', }, // keyp '+'
974 { VK_SUBTRACT, TRUE,'J', 'J', 'J', 'J', }, // keyp '-'
975 // { VK_DIVIDE, TRUE,'N', 'N', 'N', 'N', }, // keyp '/'
976 { VK_MULTIPLY, TRUE,'7', '7', '7', '7', }, // keyp '*'
Bram Moolenaar071d4272004-06-13 20:20:40 +0000977
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200978 { VK_NUMPAD0,TRUE, '\332', '\333', '\334', '\335', },
979 { VK_NUMPAD1,TRUE, '\336', '\337', '\340', '\341', },
980 { VK_NUMPAD2,TRUE, '\342', '\343', '\344', '\345', },
981 { VK_NUMPAD3,TRUE, '\346', '\347', '\350', '\351', },
982 { VK_NUMPAD4,TRUE, '\352', '\353', '\354', '\355', },
983 { VK_NUMPAD5,TRUE, '\356', '\357', '\360', '\361', },
984 { VK_NUMPAD6,TRUE, '\362', '\363', '\364', '\365', },
985 { VK_NUMPAD7,TRUE, '\366', '\367', '\370', '\371', },
986 { VK_NUMPAD8,TRUE, '\372', '\373', '\374', '\375', },
987 // Sorry, out of number space! <negri>
Bram Moolenaarb70a47b2019-03-30 22:11:21 +0100988 { VK_NUMPAD9,TRUE, '\376', '\377', '|', '}', },
Bram Moolenaar071d4272004-06-13 20:20:40 +0000989};
990
991
Bram Moolenaar0f873732019-12-05 20:28:46 +0100992/*
993 * The return code indicates key code size.
994 */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000995 static int
Bram Moolenaar071d4272004-06-13 20:20:40 +0000996win32_kbd_patch_key(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000997 KEY_EVENT_RECORD *pker)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000998{
999 UINT uMods = pker->dwControlKeyState;
1000 static int s_iIsDead = 0;
1001 static WORD awAnsiCode[2];
1002 static BYTE abKeystate[256];
1003
1004
1005 if (s_iIsDead == 2)
1006 {
K.Takata972db232022-02-04 10:45:38 +00001007 pker->uChar.UnicodeChar = (WCHAR) awAnsiCode[1];
Bram Moolenaar071d4272004-06-13 20:20:40 +00001008 s_iIsDead = 0;
1009 return 1;
1010 }
1011
K.Takata972db232022-02-04 10:45:38 +00001012 if (pker->uChar.UnicodeChar != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001013 return 1;
1014
Bram Moolenaara80faa82020-04-12 19:37:17 +02001015 CLEAR_FIELD(abKeystate);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001016
Bram Moolenaar0f873732019-12-05 20:28:46 +01001017 // Clear any pending dead keys
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001018 ToUnicode(VK_SPACE, MapVirtualKey(VK_SPACE, 0), abKeystate, awAnsiCode, 2, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001019
1020 if (uMods & SHIFT_PRESSED)
1021 abKeystate[VK_SHIFT] = 0x80;
1022 if (uMods & CAPSLOCK_ON)
1023 abKeystate[VK_CAPITAL] = 1;
1024
1025 if ((uMods & ALT_GR) == ALT_GR)
1026 {
1027 abKeystate[VK_CONTROL] = abKeystate[VK_LCONTROL] =
1028 abKeystate[VK_MENU] = abKeystate[VK_RMENU] = 0x80;
1029 }
1030
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001031 s_iIsDead = ToUnicode(pker->wVirtualKeyCode, pker->wVirtualScanCode,
1032 abKeystate, awAnsiCode, 2, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001033
1034 if (s_iIsDead > 0)
K.Takata972db232022-02-04 10:45:38 +00001035 pker->uChar.UnicodeChar = (WCHAR) awAnsiCode[0];
Bram Moolenaar071d4272004-06-13 20:20:40 +00001036
1037 return s_iIsDead;
1038}
1039
Bram Moolenaar071d4272004-06-13 20:20:40 +00001040static BOOL g_fJustGotFocus = FALSE;
1041
1042/*
1043 * Decode a KEY_EVENT into one or two keystrokes
1044 */
1045 static BOOL
1046decode_key_event(
1047 KEY_EVENT_RECORD *pker,
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001048 WCHAR *pch,
1049 WCHAR *pch2,
Bram Moolenaar071d4272004-06-13 20:20:40 +00001050 int *pmodifiers,
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02001051 BOOL fDoPost UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001052{
1053 int i;
1054 const int nModifs = pker->dwControlKeyState & (SHIFT | ALT | CTRL);
1055
1056 *pch = *pch2 = NUL;
1057 g_fJustGotFocus = FALSE;
1058
Bram Moolenaar0f873732019-12-05 20:28:46 +01001059 // ignore key up events
Bram Moolenaar071d4272004-06-13 20:20:40 +00001060 if (!pker->bKeyDown)
1061 return FALSE;
1062
Bram Moolenaar0f873732019-12-05 20:28:46 +01001063 // ignore some keystrokes
Bram Moolenaar071d4272004-06-13 20:20:40 +00001064 switch (pker->wVirtualKeyCode)
1065 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001066 // modifiers
Bram Moolenaar071d4272004-06-13 20:20:40 +00001067 case VK_SHIFT:
1068 case VK_CONTROL:
Bram Moolenaar0f873732019-12-05 20:28:46 +01001069 case VK_MENU: // Alt key
Bram Moolenaar071d4272004-06-13 20:20:40 +00001070 return FALSE;
1071
1072 default:
1073 break;
1074 }
1075
Bram Moolenaar0f873732019-12-05 20:28:46 +01001076 // special cases
K.Takata972db232022-02-04 10:45:38 +00001077 if ((nModifs & CTRL) != 0 && (nModifs & ~CTRL) == 0
1078 && pker->uChar.UnicodeChar == NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001079 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001080 // Ctrl-6 is Ctrl-^
Bram Moolenaar071d4272004-06-13 20:20:40 +00001081 if (pker->wVirtualKeyCode == '6')
1082 {
1083 *pch = Ctrl_HAT;
1084 return TRUE;
1085 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01001086 // Ctrl-2 is Ctrl-@
Bram Moolenaar071d4272004-06-13 20:20:40 +00001087 else if (pker->wVirtualKeyCode == '2')
1088 {
1089 *pch = NUL;
1090 return TRUE;
1091 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01001092 // Ctrl-- is Ctrl-_
Bram Moolenaar071d4272004-06-13 20:20:40 +00001093 else if (pker->wVirtualKeyCode == 0xBD)
1094 {
1095 *pch = Ctrl__;
1096 return TRUE;
1097 }
1098 }
1099
Bram Moolenaar0f873732019-12-05 20:28:46 +01001100 // Shift-TAB
Bram Moolenaar071d4272004-06-13 20:20:40 +00001101 if (pker->wVirtualKeyCode == VK_TAB && (nModifs & SHIFT_PRESSED))
1102 {
1103 *pch = K_NUL;
1104 *pch2 = '\017';
1105 return TRUE;
1106 }
1107
K.Takataeeec2542021-06-02 13:28:16 +02001108 for (i = ARRAY_LENGTH(VirtKeyMap); --i >= 0; )
Bram Moolenaar071d4272004-06-13 20:20:40 +00001109 {
1110 if (VirtKeyMap[i].wVirtKey == pker->wVirtualKeyCode)
1111 {
1112 if (nModifs == 0)
1113 *pch = VirtKeyMap[i].chAlone;
1114 else if ((nModifs & SHIFT) != 0 && (nModifs & ~SHIFT) == 0)
1115 *pch = VirtKeyMap[i].chShift;
1116 else if ((nModifs & CTRL) != 0 && (nModifs & ~CTRL) == 0)
1117 *pch = VirtKeyMap[i].chCtrl;
1118 else if ((nModifs & ALT) != 0 && (nModifs & ~ALT) == 0)
1119 *pch = VirtKeyMap[i].chAlt;
1120
1121 if (*pch != 0)
1122 {
1123 if (VirtKeyMap[i].fAnsiKey)
1124 {
1125 *pch2 = *pch;
1126 *pch = K_NUL;
1127 }
1128
1129 return TRUE;
1130 }
1131 }
1132 }
1133
1134 i = win32_kbd_patch_key(pker);
1135
1136 if (i < 0)
1137 *pch = NUL;
1138 else
1139 {
K.Takata972db232022-02-04 10:45:38 +00001140 *pch = (i > 0) ? pker->uChar.UnicodeChar : NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001141
1142 if (pmodifiers != NULL)
1143 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001144 // Pass on the ALT key as a modifier, but only when not combined
1145 // with CTRL (which is ALTGR).
Bram Moolenaar071d4272004-06-13 20:20:40 +00001146 if ((nModifs & ALT) != 0 && (nModifs & CTRL) == 0)
1147 *pmodifiers |= MOD_MASK_ALT;
1148
Bram Moolenaar0f873732019-12-05 20:28:46 +01001149 // Pass on SHIFT only for special keys, because we don't know when
1150 // it's already included with the character.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001151 if ((nModifs & SHIFT) != 0 && *pch <= 0x20)
1152 *pmodifiers |= MOD_MASK_SHIFT;
1153
Bram Moolenaar0f873732019-12-05 20:28:46 +01001154 // Pass on CTRL only for non-special keys, because we don't know
1155 // when it's already included with the character. And not when
1156 // combined with ALT (which is ALTGR).
Bram Moolenaar071d4272004-06-13 20:20:40 +00001157 if ((nModifs & CTRL) != 0 && (nModifs & ALT) == 0
1158 && *pch >= 0x20 && *pch < 0x80)
1159 *pmodifiers |= MOD_MASK_CTRL;
1160 }
1161 }
1162
1163 return (*pch != NUL);
1164}
1165
Bram Moolenaar0f873732019-12-05 20:28:46 +01001166#endif // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00001167
1168
Bram Moolenaar071d4272004-06-13 20:20:40 +00001169/*
1170 * For the GUI the mouse handling is in gui_w32.c.
1171 */
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001172#if defined(FEAT_GUI_MSWIN) && !defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001173 void
Bram Moolenaar1266d672017-02-01 13:43:36 +01001174mch_setmouse(int on UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001175{
1176}
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001177#else
Bram Moolenaar0f873732019-12-05 20:28:46 +01001178static int g_fMouseAvail = FALSE; // mouse present
1179static int g_fMouseActive = FALSE; // mouse enabled
1180static int g_nMouseClick = -1; // mouse status
1181static int g_xMouse; // mouse x coordinate
1182static int g_yMouse; // mouse y coordinate
Bram Moolenaar9f1983d2022-05-12 20:35:35 +01001183static DWORD g_cmodein = 0; // Original console input mode
1184static DWORD g_cmodeout = 0; // Original console output mode
Bram Moolenaar071d4272004-06-13 20:20:40 +00001185
1186/*
1187 * Enable or disable mouse input
1188 */
1189 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001190mch_setmouse(int on)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001191{
1192 DWORD cmodein;
1193
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001194# ifdef VIMDLL
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001195 if (gui.in_use)
1196 return;
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001197# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001198 if (!g_fMouseAvail)
1199 return;
1200
1201 g_fMouseActive = on;
1202 GetConsoleMode(g_hConIn, &cmodein);
1203
1204 if (g_fMouseActive)
Wez Furlong6ef5ab52021-05-30 19:29:41 +02001205 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00001206 cmodein |= ENABLE_MOUSE_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02001207 cmodein &= ~ENABLE_QUICK_EDIT_MODE;
1208 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001209 else
Wez Furlong6ef5ab52021-05-30 19:29:41 +02001210 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00001211 cmodein &= ~ENABLE_MOUSE_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02001212 cmodein |= g_cmodein & ENABLE_QUICK_EDIT_MODE;
1213 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001214
Wez Furlong6ef5ab52021-05-30 19:29:41 +02001215 SetConsoleMode(g_hConIn, cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001216}
1217
Bram Moolenaar157d8132018-03-06 17:09:20 +01001218
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001219# if defined(FEAT_BEVAL_TERM) || defined(PROTO)
Bram Moolenaar157d8132018-03-06 17:09:20 +01001220/*
1221 * Called when 'balloonevalterm' changed.
1222 */
1223 void
1224mch_bevalterm_changed(void)
1225{
1226 mch_setmouse(g_fMouseActive);
1227}
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001228# endif
Bram Moolenaar157d8132018-03-06 17:09:20 +01001229
Christopher Plewright2a46f812022-10-16 19:47:45 +01001230/*
1231 * Win32 console mouse scroll event handler.
1232 * Loosely based on the _OnMouseWheel() function in gui_w32.c
1233 *
1234 * This encodes the mouse scroll direction and keyboard modifiers into
1235 * g_nMouseClick, and the mouse position into g_xMouse and g_yMouse
1236 *
1237 * The direction of the scroll is decoded from two fields of the win32 console
1238 * mouse event record;
1239 * 1. The axis - vertical or horizontal flag - from dwEventFlags, and
1240 * 2. The sign - positive or negative (aka delta flag) - from dwButtonState
1241 *
1242 * When scroll axis is HORIZONTAL
1243 * - If the high word of the dwButtonState member contains a positive
1244 * value, the wheel was rotated to the right.
1245 * - Otherwise, the wheel was rotated to the left.
1246 * When scroll axis is VERTICAL
1247 * - If the high word of the dwButtonState member contains a positive value,
1248 * the wheel was rotated forward, away from the user.
1249 * - Otherwise, the wheel was rotated backward, toward the user.
1250 */
1251 static void
1252decode_mouse_wheel(MOUSE_EVENT_RECORD *pmer)
1253{
Christopher Plewright2a46f812022-10-16 19:47:45 +01001254 int horizontal = (pmer->dwEventFlags == MOUSE_HWHEELED);
1255 int zDelta = pmer->dwButtonState;
1256
1257 g_xMouse = pmer->dwMousePosition.X;
1258 g_yMouse = pmer->dwMousePosition.Y;
1259
1260#ifdef FEAT_PROP_POPUP
Christopher Plewright605d02a2022-10-19 11:54:46 +01001261 int lcol = g_xMouse;
1262 int lrow = g_yMouse;
Christopher Plewright38804d62022-11-09 23:55:52 +00001263 win_T *wp = mouse_find_win(&lrow, &lcol, FIND_POPUP);
Christopher Plewright2a46f812022-10-16 19:47:45 +01001264 if (wp != NULL && popup_is_popup(wp))
1265 {
1266 g_nMouseClick = -1;
1267 cmdarg_T cap;
1268 oparg_T oa;
1269 CLEAR_FIELD(cap);
1270 clear_oparg(&oa);
1271 cap.oap = &oa;
1272 if (horizontal)
1273 {
1274 cap.arg = zDelta < 0 ? MSCR_LEFT : MSCR_RIGHT;
1275 cap.cmdchar = zDelta < 0 ? K_MOUSELEFT : K_MOUSERIGHT;
1276 }
1277 else
1278 {
1279 cap.cmdchar = zDelta < 0 ? K_MOUSEUP : K_MOUSEDOWN;
1280 cap.arg = zDelta < 0 ? MSCR_UP : MSCR_DOWN;
1281 }
1282
1283 // Mouse hovers over popup window, scroll it if possible.
1284 mouse_row = wp->w_winrow;
1285 mouse_col = wp->w_wincol;
1286 nv_mousescroll(&cap);
1287 update_screen(0);
1288 setcursor();
1289 out_flush();
1290 return;
1291 }
1292#endif
1293 mouse_col = g_xMouse;
1294 mouse_row = g_yMouse;
1295
1296 char_u modifiers = 0;
1297 char_u direction = 0;
1298
1299 // Decode the direction into an event that Vim can process
1300 if (horizontal)
1301 direction = zDelta >= 0 ? KE_MOUSELEFT : KE_MOUSERIGHT;
1302 else
1303 direction = zDelta >= 0 ? KE_MOUSEDOWN : KE_MOUSEUP;
1304
dundargocc57b5bc2022-11-02 13:30:51 +00001305 // Decode the win32 console key modifiers into Vim mouse modifiers.
Christopher Plewright2a46f812022-10-16 19:47:45 +01001306 if (pmer->dwControlKeyState & SHIFT_PRESSED)
Christopher Plewright605d02a2022-10-19 11:54:46 +01001307 modifiers |= MOD_MASK_SHIFT; // MOUSE_SHIFT;
Christopher Plewright2a46f812022-10-16 19:47:45 +01001308 if (pmer->dwControlKeyState & (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED))
Christopher Plewright605d02a2022-10-19 11:54:46 +01001309 modifiers |= MOD_MASK_CTRL; // MOUSE_CTRL;
Christopher Plewright2a46f812022-10-16 19:47:45 +01001310 if (pmer->dwControlKeyState & (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED))
1311 modifiers |= MOD_MASK_ALT; // MOUSE_ALT;
1312
1313 // add (bitwise or) the scroll direction and the key modifier chars
1314 // together.
1315 g_nMouseClick = ((direction << 8) | modifiers);
1316
1317 return;
1318}
1319
Bram Moolenaar071d4272004-06-13 20:20:40 +00001320/*
1321 * Decode a MOUSE_EVENT. If it's a valid event, return MOUSE_LEFT,
1322 * MOUSE_MIDDLE, or MOUSE_RIGHT for a click; MOUSE_DRAG for a mouse
1323 * move with a button held down; and MOUSE_RELEASE after a MOUSE_DRAG
1324 * or a MOUSE_LEFT, _MIDDLE, or _RIGHT. We encode the button type,
1325 * the number of clicks, and the Shift/Ctrl/Alt modifiers in g_nMouseClick,
1326 * and we return the mouse position in g_xMouse and g_yMouse.
1327 *
1328 * Every MOUSE_LEFT, _MIDDLE, or _RIGHT will be followed by zero or more
1329 * MOUSE_DRAGs and one MOUSE_RELEASE. MOUSE_RELEASE will be followed only
1330 * by MOUSE_LEFT, _MIDDLE, or _RIGHT.
1331 *
1332 * For multiple clicks, we send, say, MOUSE_LEFT/1 click, MOUSE_RELEASE,
1333 * MOUSE_LEFT/2 clicks, MOUSE_RELEASE, MOUSE_LEFT/3 clicks, MOUSE_RELEASE, ....
1334 *
1335 * Windows will send us MOUSE_MOVED notifications whenever the mouse
1336 * moves, even if it stays within the same character cell. We ignore
1337 * all MOUSE_MOVED messages if the position hasn't really changed, and
1338 * we ignore all MOUSE_MOVED messages where no button is held down (i.e.,
1339 * we're only interested in MOUSE_DRAG).
1340 *
1341 * All of this is complicated by the code that fakes MOUSE_MIDDLE on
1342 * 2-button mouses by pressing the left & right buttons simultaneously.
1343 * In practice, it's almost impossible to click both at the same time,
1344 * so we need to delay a little. Also, we tend not to get MOUSE_RELEASE
1345 * in such cases, if the user is clicking quickly.
1346 */
1347 static BOOL
1348decode_mouse_event(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001349 MOUSE_EVENT_RECORD *pmer)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001350{
1351 static int s_nOldButton = -1;
1352 static int s_nOldMouseClick = -1;
1353 static int s_xOldMouse = -1;
1354 static int s_yOldMouse = -1;
1355 static linenr_T s_old_topline = 0;
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001356# ifdef FEAT_DIFF
Bram Moolenaar071d4272004-06-13 20:20:40 +00001357 static int s_old_topfill = 0;
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001358# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001359 static int s_cClicks = 1;
1360 static BOOL s_fReleased = TRUE;
1361 static DWORD s_dwLastClickTime = 0;
1362 static BOOL s_fNextIsMiddle = FALSE;
1363
Bram Moolenaar0f873732019-12-05 20:28:46 +01001364 static DWORD cButtons = 0; // number of buttons supported
Bram Moolenaar071d4272004-06-13 20:20:40 +00001365
1366 const DWORD LEFT = FROM_LEFT_1ST_BUTTON_PRESSED;
1367 const DWORD MIDDLE = FROM_LEFT_2ND_BUTTON_PRESSED;
1368 const DWORD RIGHT = RIGHTMOST_BUTTON_PRESSED;
1369 const DWORD LEFT_RIGHT = LEFT | RIGHT;
1370
1371 int nButton;
1372
1373 if (cButtons == 0 && !GetNumberOfConsoleMouseButtons(&cButtons))
1374 cButtons = 2;
1375
1376 if (!g_fMouseAvail || !g_fMouseActive)
1377 {
1378 g_nMouseClick = -1;
1379 return FALSE;
1380 }
1381
Bram Moolenaar0f873732019-12-05 20:28:46 +01001382 // get a spurious MOUSE_EVENT immediately after receiving focus; ignore
Bram Moolenaar071d4272004-06-13 20:20:40 +00001383 if (g_fJustGotFocus)
1384 {
1385 g_fJustGotFocus = FALSE;
1386 return FALSE;
1387 }
1388
Christopher Plewright605d02a2022-10-19 11:54:46 +01001389 // If there is an unprocessed mouse click drop this one.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001390 if (g_nMouseClick != -1)
1391 return TRUE;
Christopher Plewright605d02a2022-10-19 11:54:46 +01001392
Christopher Plewright2a46f812022-10-16 19:47:45 +01001393 if (pmer->dwEventFlags == MOUSE_WHEELED
1394 || pmer->dwEventFlags == MOUSE_HWHEELED)
1395 {
1396 decode_mouse_wheel(pmer);
1397 return TRUE; // we now should have a mouse scroll in g_nMouseClick
1398 }
Christopher Plewright605d02a2022-10-19 11:54:46 +01001399
Bram Moolenaar071d4272004-06-13 20:20:40 +00001400 nButton = -1;
1401 g_xMouse = pmer->dwMousePosition.X;
1402 g_yMouse = pmer->dwMousePosition.Y;
1403
1404 if (pmer->dwEventFlags == MOUSE_MOVED)
1405 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001406 // Ignore MOUSE_MOVED events if (x, y) hasn't changed. (We get these
1407 // events even when the mouse moves only within a char cell.)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001408 if (s_xOldMouse == g_xMouse && s_yOldMouse == g_yMouse)
1409 return FALSE;
1410 }
1411
Bram Moolenaar0f873732019-12-05 20:28:46 +01001412 // If no buttons are pressed...
Bram Moolenaar071d4272004-06-13 20:20:40 +00001413 if ((pmer->dwButtonState & ((1 << cButtons) - 1)) == 0)
1414 {
Bram Moolenaar157d8132018-03-06 17:09:20 +01001415 nButton = MOUSE_RELEASE;
1416
Bram Moolenaar0f873732019-12-05 20:28:46 +01001417 // If the last thing returned was MOUSE_RELEASE, ignore this
Bram Moolenaar071d4272004-06-13 20:20:40 +00001418 if (s_fReleased)
Bram Moolenaar157d8132018-03-06 17:09:20 +01001419 {
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001420# ifdef FEAT_BEVAL_TERM
Bram Moolenaar0f873732019-12-05 20:28:46 +01001421 // do return mouse move events when we want them
Bram Moolenaar157d8132018-03-06 17:09:20 +01001422 if (p_bevalterm)
1423 nButton = MOUSE_DRAG;
1424 else
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001425# endif
Bram Moolenaar157d8132018-03-06 17:09:20 +01001426 return FALSE;
1427 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001428
Bram Moolenaar071d4272004-06-13 20:20:40 +00001429 s_fReleased = TRUE;
1430 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01001431 else // one or more buttons pressed
Bram Moolenaar071d4272004-06-13 20:20:40 +00001432 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001433 // on a 2-button mouse, hold down left and right buttons
1434 // simultaneously to get MIDDLE.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001435
1436 if (cButtons == 2 && s_nOldButton != MOUSE_DRAG)
1437 {
1438 DWORD dwLR = (pmer->dwButtonState & LEFT_RIGHT);
1439
Bram Moolenaar0f873732019-12-05 20:28:46 +01001440 // if either left or right button only is pressed, see if the
1441 // next mouse event has both of them pressed
Bram Moolenaar071d4272004-06-13 20:20:40 +00001442 if (dwLR == LEFT || dwLR == RIGHT)
1443 {
1444 for (;;)
1445 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001446 // wait a short time for next input event
Bram Moolenaar071d4272004-06-13 20:20:40 +00001447 if (WaitForSingleObject(g_hConIn, p_mouset / 3)
1448 != WAIT_OBJECT_0)
1449 break;
1450 else
1451 {
1452 DWORD cRecords = 0;
1453 INPUT_RECORD ir;
1454 MOUSE_EVENT_RECORD* pmer2 = &ir.Event.MouseEvent;
1455
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001456 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001457
1458 if (cRecords == 0 || ir.EventType != MOUSE_EVENT
1459 || !(pmer2->dwButtonState & LEFT_RIGHT))
1460 break;
1461 else
1462 {
1463 if (pmer2->dwEventFlags != MOUSE_MOVED)
1464 {
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001465 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001466
1467 return decode_mouse_event(pmer2);
1468 }
1469 else if (s_xOldMouse == pmer2->dwMousePosition.X &&
1470 s_yOldMouse == pmer2->dwMousePosition.Y)
1471 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001472 // throw away spurious mouse move
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001473 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001474
Bram Moolenaar0f873732019-12-05 20:28:46 +01001475 // are there any more mouse events in queue?
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001476 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001477
1478 if (cRecords==0 || ir.EventType != MOUSE_EVENT)
1479 break;
1480 }
1481 else
1482 break;
1483 }
1484 }
1485 }
1486 }
1487 }
1488
1489 if (s_fNextIsMiddle)
1490 {
1491 nButton = (pmer->dwEventFlags == MOUSE_MOVED)
1492 ? MOUSE_DRAG : MOUSE_MIDDLE;
1493 s_fNextIsMiddle = FALSE;
1494 }
1495 else if (cButtons == 2 &&
1496 ((pmer->dwButtonState & LEFT_RIGHT) == LEFT_RIGHT))
1497 {
1498 nButton = MOUSE_MIDDLE;
1499
1500 if (! s_fReleased && pmer->dwEventFlags != MOUSE_MOVED)
1501 {
1502 s_fNextIsMiddle = TRUE;
1503 nButton = MOUSE_RELEASE;
1504 }
1505 }
1506 else if ((pmer->dwButtonState & LEFT) == LEFT)
1507 nButton = MOUSE_LEFT;
1508 else if ((pmer->dwButtonState & MIDDLE) == MIDDLE)
1509 nButton = MOUSE_MIDDLE;
1510 else if ((pmer->dwButtonState & RIGHT) == RIGHT)
1511 nButton = MOUSE_RIGHT;
1512
1513 if (! s_fReleased && ! s_fNextIsMiddle
1514 && nButton != s_nOldButton && s_nOldButton != MOUSE_DRAG)
1515 return FALSE;
1516
1517 s_fReleased = s_fNextIsMiddle;
1518 }
1519
1520 if (pmer->dwEventFlags == 0 || pmer->dwEventFlags == DOUBLE_CLICK)
1521 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001522 // button pressed or released, without mouse moving
Bram Moolenaar071d4272004-06-13 20:20:40 +00001523 if (nButton != -1 && nButton != MOUSE_RELEASE)
1524 {
1525 DWORD dwCurrentTime = GetTickCount();
1526
1527 if (s_xOldMouse != g_xMouse
1528 || s_yOldMouse != g_yMouse
1529 || s_nOldButton != nButton
1530 || s_old_topline != curwin->w_topline
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001531# ifdef FEAT_DIFF
Bram Moolenaar071d4272004-06-13 20:20:40 +00001532 || s_old_topfill != curwin->w_topfill
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001533# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001534 || (int)(dwCurrentTime - s_dwLastClickTime) > p_mouset)
1535 {
1536 s_cClicks = 1;
1537 }
1538 else if (++s_cClicks > 4)
1539 {
1540 s_cClicks = 1;
1541 }
1542
1543 s_dwLastClickTime = dwCurrentTime;
1544 }
1545 }
1546 else if (pmer->dwEventFlags == MOUSE_MOVED)
1547 {
1548 if (nButton != -1 && nButton != MOUSE_RELEASE)
1549 nButton = MOUSE_DRAG;
1550
1551 s_cClicks = 1;
1552 }
1553
1554 if (nButton == -1)
1555 return FALSE;
1556
1557 if (nButton != MOUSE_RELEASE)
1558 s_nOldButton = nButton;
1559
1560 g_nMouseClick = nButton;
1561
1562 if (pmer->dwControlKeyState & SHIFT_PRESSED)
1563 g_nMouseClick |= MOUSE_SHIFT;
1564 if (pmer->dwControlKeyState & (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED))
1565 g_nMouseClick |= MOUSE_CTRL;
1566 if (pmer->dwControlKeyState & (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED))
1567 g_nMouseClick |= MOUSE_ALT;
1568
1569 if (nButton != MOUSE_DRAG && nButton != MOUSE_RELEASE)
1570 SET_NUM_MOUSE_CLICKS(g_nMouseClick, s_cClicks);
1571
Bram Moolenaar0f873732019-12-05 20:28:46 +01001572 // only pass on interesting (i.e., different) mouse events
Bram Moolenaar071d4272004-06-13 20:20:40 +00001573 if (s_xOldMouse == g_xMouse
1574 && s_yOldMouse == g_yMouse
1575 && s_nOldMouseClick == g_nMouseClick)
1576 {
1577 g_nMouseClick = -1;
1578 return FALSE;
1579 }
1580
1581 s_xOldMouse = g_xMouse;
1582 s_yOldMouse = g_yMouse;
1583 s_old_topline = curwin->w_topline;
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001584# ifdef FEAT_DIFF
Bram Moolenaar071d4272004-06-13 20:20:40 +00001585 s_old_topfill = curwin->w_topfill;
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001586# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001587 s_nOldMouseClick = g_nMouseClick;
1588
1589 return TRUE;
1590}
1591
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001592#endif // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00001593
1594
1595#ifdef MCH_CURSOR_SHAPE
1596/*
1597 * Set the shape of the cursor.
1598 * 'thickness' can be from 1 (thin) to 99 (block)
1599 */
1600 static void
1601mch_set_cursor_shape(int thickness)
1602{
Christopher Plewright38804d62022-11-09 23:55:52 +00001603 if (vtp_working)
K.Takatadf5320c2022-09-01 13:20:16 +01001604 {
1605 if (*T_CSI == NUL)
1606 {
1607 // If 't_SI' is not set, use the default cursor styles.
1608 if (thickness < 50)
1609 vtp_printf("\033[3 q"); // underline
1610 else
1611 vtp_printf("\033[0 q"); // default
1612 }
1613 }
1614 else
1615 {
1616 CONSOLE_CURSOR_INFO ConsoleCursorInfo;
1617 ConsoleCursorInfo.dwSize = thickness;
1618 ConsoleCursorInfo.bVisible = s_cursor_visible;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001619
K.Takatadf5320c2022-09-01 13:20:16 +01001620 SetConsoleCursorInfo(g_hConOut, &ConsoleCursorInfo);
1621 if (s_cursor_visible)
1622 SetConsoleCursorPosition(g_hConOut, g_coord);
1623 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001624}
1625
1626 void
1627mch_update_cursor(void)
1628{
1629 int idx;
1630 int thickness;
1631
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001632# ifdef VIMDLL
1633 if (gui.in_use)
1634 return;
1635# endif
1636
Bram Moolenaar071d4272004-06-13 20:20:40 +00001637 /*
1638 * How the cursor is drawn depends on the current mode.
1639 */
1640 idx = get_shape_idx(FALSE);
1641
1642 if (shape_table[idx].shape == SHAPE_BLOCK)
Bram Moolenaar0f873732019-12-05 20:28:46 +01001643 thickness = 99; // 100 doesn't work on W95
Bram Moolenaar071d4272004-06-13 20:20:40 +00001644 else
1645 thickness = shape_table[idx].percentage;
1646 mch_set_cursor_shape(thickness);
1647}
1648#endif
1649
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001650#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001651/*
1652 * Handle FOCUS_EVENT.
1653 */
1654 static void
1655handle_focus_event(INPUT_RECORD ir)
1656{
1657 g_fJustGotFocus = ir.Event.FocusEvent.bSetFocus;
1658 ui_focus_change((int)g_fJustGotFocus);
1659}
1660
Bram Moolenaar78d21da2019-02-17 15:00:52 +01001661static void ResizeConBuf(HANDLE hConsole, COORD coordScreen);
1662
Bram Moolenaar071d4272004-06-13 20:20:40 +00001663/*
1664 * Wait until console input from keyboard or mouse is available,
1665 * or the time is up.
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001666 * When "ignore_input" is TRUE even wait when input is available.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001667 * Return TRUE if something is available FALSE if not.
1668 */
1669 static int
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001670WaitForChar(long msec, int ignore_input)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001671{
1672 DWORD dwNow = 0, dwEndTime = 0;
1673 INPUT_RECORD ir;
1674 DWORD cRecords;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001675 WCHAR ch, ch2;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001676# ifdef FEAT_TIMERS
Bram Moolenaar40b1b542016-04-20 20:18:23 +02001677 int tb_change_cnt = typebuf.tb_change_cnt;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001678# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001679
1680 if (msec > 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01001681 // Wait until the specified time has elapsed.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001682 dwEndTime = GetTickCount() + msec;
1683 else if (msec < 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01001684 // Wait forever.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001685 dwEndTime = INFINITE;
1686
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01001687 // We need to loop until the end of the time period, because
1688 // we might get multiple unusable mouse events in that time.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001689 for (;;)
1690 {
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001691 // Only process messages when waiting.
1692 if (msec != 0)
1693 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001694# ifdef MESSAGE_QUEUE
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001695 parse_queued_messages();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001696# endif
1697# ifdef FEAT_MZSCHEME
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001698 mzvim_check_threads();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001699# endif
1700# ifdef FEAT_CLIENTSERVER
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001701 serverProcessPendingMessages();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001702# endif
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001703 }
Bram Moolenaarf12d9832016-01-29 21:11:25 +01001704
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001705 if (g_nMouseClick != -1
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001706# ifdef FEAT_CLIENTSERVER
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001707 || (!ignore_input && input_available())
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001708# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001709 )
1710 return TRUE;
1711
1712 if (msec > 0)
1713 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001714 // If the specified wait time has passed, return. Beware that
1715 // GetTickCount() may wrap around (overflow).
Bram Moolenaar071d4272004-06-13 20:20:40 +00001716 dwNow = GetTickCount();
Bram Moolenaarb7512b72013-08-10 12:45:09 +02001717 if ((int)(dwNow - dwEndTime) >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001718 break;
1719 }
1720 if (msec != 0)
1721 {
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001722 DWORD dwWaitTime = dwEndTime - dwNow;
1723
Bram Moolenaarc478ee32020-12-01 21:27:51 +01001724 // Don't wait for more than 11 msec to avoid dropping characters,
1725 // check channel while waiting for input and handle a callback from
1726 // 'balloonexpr'.
1727 if (dwWaitTime > 11)
1728 dwWaitTime = 11;
1729
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001730# ifdef FEAT_MZSCHEME
Bram Moolenaarc478ee32020-12-01 21:27:51 +01001731 if (mzthreads_allowed() && p_mzq > 0 && (long)dwWaitTime > p_mzq)
Bram Moolenaar0f873732019-12-05 20:28:46 +01001732 dwWaitTime = p_mzq; // don't wait longer than 'mzquantum'
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001733# endif
1734# ifdef FEAT_TIMERS
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001735 // When waiting very briefly don't trigger timers.
1736 if (dwWaitTime > 10)
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001737 {
1738 long due_time;
1739
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001740 // Trigger timers and then get the time in msec until the next
1741 // one is due. Wait up to that time.
1742 due_time = check_due_timer();
1743 if (typebuf.tb_change_cnt != tb_change_cnt)
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001744 {
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001745 // timer may have used feedkeys().
1746 return FALSE;
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001747 }
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001748 if (due_time > 0 && dwWaitTime > (DWORD)due_time)
1749 dwWaitTime = due_time;
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001750 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001751# endif
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001752 if (
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001753# ifdef FEAT_CLIENTSERVER
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001754 // Wait for either an event on the console input or a
1755 // message in the client-server window.
1756 msg_wait_for_multiple_objects(1, &g_hConIn, FALSE,
1757 dwWaitTime, QS_SENDMESSAGE) != WAIT_OBJECT_0
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001758# else
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001759 wait_for_single_object(g_hConIn, dwWaitTime)
1760 != WAIT_OBJECT_0
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001761# endif
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001762 )
1763 continue;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001764 }
1765
1766 cRecords = 0;
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001767 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001768
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001769# ifdef FEAT_MBYTE_IME
matveyt4eb19142021-05-20 11:54:10 +02001770 // May have to redraw if the cursor ends up in the wrong place.
1771 // Only when not peeking.
Bram Moolenaar24959102022-05-07 20:01:16 +01001772 if (State == MODE_CMDLINE && msg_row == Rows - 1 && msec != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001773 {
1774 CONSOLE_SCREEN_BUFFER_INFO csbi;
1775
1776 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
1777 {
1778 if (csbi.dwCursorPosition.Y != msg_row)
1779 {
matveyte08795e2021-05-07 15:00:17 +02001780 // The screen is now messed up, must redraw the command
1781 // line and later all the windows.
Bram Moolenaara4d158b2022-08-14 14:17:45 +01001782 redraw_all_later(UPD_CLEAR);
matveyte08795e2021-05-07 15:00:17 +02001783 compute_cmdrow();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001784 redrawcmd();
1785 }
1786 }
1787 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001788# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001789
1790 if (cRecords > 0)
1791 {
1792 if (ir.EventType == KEY_EVENT && ir.Event.KeyEvent.bKeyDown)
1793 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001794# ifdef FEAT_MBYTE_IME
Bram Moolenaar0f873732019-12-05 20:28:46 +01001795 // Windows IME sends two '\n's with only one 'ENTER'. First:
1796 // wVirtualKeyCode == 13. second: wVirtualKeyCode == 0
K.Takata972db232022-02-04 10:45:38 +00001797 if (ir.Event.KeyEvent.uChar.UnicodeChar == 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00001798 && ir.Event.KeyEvent.wVirtualKeyCode == 13)
1799 {
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001800 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001801 continue;
1802 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001803# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001804 if (decode_key_event(&ir.Event.KeyEvent, &ch, &ch2,
1805 NULL, FALSE))
1806 return TRUE;
1807 }
1808
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001809 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001810
1811 if (ir.EventType == FOCUS_EVENT)
1812 handle_focus_event(ir);
1813 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
Bram Moolenaarc33ecb22018-02-11 16:40:45 +01001814 {
Bram Moolenaar78d21da2019-02-17 15:00:52 +01001815 COORD dwSize = ir.Event.WindowBufferSizeEvent.dwSize;
1816
Bram Moolenaar36698e32019-12-11 22:57:40 +01001817 // Only call shell_resized() when the size actually changed to
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001818 // avoid the screen is cleared.
Bram Moolenaar78d21da2019-02-17 15:00:52 +01001819 if (dwSize.X != Columns || dwSize.Y != Rows)
1820 {
1821 CONSOLE_SCREEN_BUFFER_INFO csbi;
1822 GetConsoleScreenBufferInfo(g_hConOut, &csbi);
Bram Moolenaar36698e32019-12-11 22:57:40 +01001823 dwSize.X = csbi.srWindow.Right - csbi.srWindow.Left + 1;
Bram Moolenaar78d21da2019-02-17 15:00:52 +01001824 dwSize.Y = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
Bram Moolenaar36698e32019-12-11 22:57:40 +01001825 if (dwSize.X != Columns || dwSize.Y != Rows)
1826 {
1827 ResizeConBuf(g_hConOut, dwSize);
1828 shell_resized();
1829 }
Bram Moolenaar78d21da2019-02-17 15:00:52 +01001830 }
Bram Moolenaarc33ecb22018-02-11 16:40:45 +01001831 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001832 else if (ir.EventType == MOUSE_EVENT
1833 && decode_mouse_event(&ir.Event.MouseEvent))
1834 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001835 }
1836 else if (msec == 0)
1837 break;
1838 }
1839
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001840# ifdef FEAT_CLIENTSERVER
Bram Moolenaar0f873732019-12-05 20:28:46 +01001841 // Something might have been received while we were waiting.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001842 if (input_available())
1843 return TRUE;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001844# endif
Bram Moolenaarf12d9832016-01-29 21:11:25 +01001845
Bram Moolenaar071d4272004-06-13 20:20:40 +00001846 return FALSE;
1847}
1848
Bram Moolenaar071d4272004-06-13 20:20:40 +00001849/*
1850 * return non-zero if a character is available
1851 */
1852 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001853mch_char_avail(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001854{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001855# ifdef VIMDLL
1856 if (gui.in_use)
1857 return TRUE;
1858# endif
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001859 return WaitForChar(0L, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001860}
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001861
1862# if defined(FEAT_TERMINAL) || defined(PROTO)
1863/*
1864 * Check for any pending input or messages.
1865 */
1866 int
1867mch_check_messages(void)
1868{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001869# ifdef VIMDLL
1870 if (gui.in_use)
1871 return TRUE;
1872# endif
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001873 return WaitForChar(0L, TRUE);
1874}
1875# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001876
1877/*
1878 * Create the console input. Used when reading stdin doesn't work.
1879 */
1880 static void
1881create_conin(void)
1882{
1883 g_hConIn = CreateFile("CONIN$", GENERIC_READ|GENERIC_WRITE,
1884 FILE_SHARE_READ|FILE_SHARE_WRITE,
1885 (LPSECURITY_ATTRIBUTES) NULL,
Bram Moolenaareb3593b2006-04-22 22:33:57 +00001886 OPEN_EXISTING, 0, (HANDLE)NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001887 did_create_conin = TRUE;
1888}
1889
1890/*
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001891 * Get a keystroke or a mouse event, use a blocking wait.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001892 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001893 static WCHAR
1894tgetch(int *pmodifiers, WCHAR *pch2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001895{
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001896 WCHAR ch;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001897
1898 for (;;)
1899 {
1900 INPUT_RECORD ir;
1901 DWORD cRecords = 0;
1902
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001903# ifdef FEAT_CLIENTSERVER
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001904 (void)WaitForChar(-1L, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001905 if (input_available())
1906 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001907 if (g_nMouseClick != -1)
1908 return 0;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001909# endif
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001910 if (read_console_input(g_hConIn, &ir, 1, &cRecords) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001911 {
1912 if (did_create_conin)
1913 read_error_exit();
1914 create_conin();
1915 continue;
1916 }
1917
1918 if (ir.EventType == KEY_EVENT)
1919 {
1920 if (decode_key_event(&ir.Event.KeyEvent, &ch, pch2,
1921 pmodifiers, TRUE))
1922 return ch;
1923 }
1924 else if (ir.EventType == FOCUS_EVENT)
1925 handle_focus_event(ir);
1926 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
1927 shell_resized();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001928 else if (ir.EventType == MOUSE_EVENT)
1929 {
1930 if (decode_mouse_event(&ir.Event.MouseEvent))
1931 return 0;
1932 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001933 }
1934}
Bram Moolenaar0f873732019-12-05 20:28:46 +01001935#endif // !FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00001936
1937
1938/*
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02001939 * mch_inchar(): low-level input function.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001940 * Get one or more characters from the keyboard or the mouse.
1941 * If time == 0, do not wait for characters.
1942 * If time == n, wait a short time for characters.
1943 * If time == -1, wait forever for characters.
1944 * Returns the number of characters read into buf.
1945 */
1946 int
1947mch_inchar(
Bram Moolenaar1266d672017-02-01 13:43:36 +01001948 char_u *buf UNUSED,
1949 int maxlen UNUSED,
1950 long time UNUSED,
1951 int tb_change_cnt UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001952{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001953#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001954
1955 int len;
1956 int c;
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01001957# ifdef VIMDLL
1958// Extra space for maximum three CSIs. E.g. U+1B6DB -> 0xF0 0x9B 0x9B 0x9B.
1959# define TYPEAHEADSPACE 6
1960# else
1961# define TYPEAHEADSPACE 0
1962# endif
1963# define TYPEAHEADLEN (20 + TYPEAHEADSPACE)
Bram Moolenaar0f873732019-12-05 20:28:46 +01001964 static char_u typeahead[TYPEAHEADLEN]; // previously typed bytes.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001965 static int typeaheadlen = 0;
1966
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001967# ifdef VIMDLL
1968 if (gui.in_use)
1969 return 0;
1970# endif
1971
Bram Moolenaar0f873732019-12-05 20:28:46 +01001972 // First use any typeahead that was kept because "buf" was too small.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001973 if (typeaheadlen > 0)
1974 goto theend;
1975
Bram Moolenaar071d4272004-06-13 20:20:40 +00001976 if (time >= 0)
1977 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001978 if (!WaitForChar(time, FALSE)) // no character available
Bram Moolenaar071d4272004-06-13 20:20:40 +00001979 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001980 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01001981 else // time == -1, wait forever
Bram Moolenaar071d4272004-06-13 20:20:40 +00001982 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001983 mch_set_winsize_now(); // Allow winsize changes from now on
Bram Moolenaar071d4272004-06-13 20:20:40 +00001984
Bram Moolenaar3918c952005-03-15 22:34:55 +00001985 /*
1986 * If there is no character available within 2 seconds (default)
1987 * write the autoscript file to disk. Or cause the CursorHold event
1988 * to be triggered.
1989 */
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001990 if (!WaitForChar(p_ut, FALSE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001991 {
Bram Moolenaard35f9712005-12-18 22:02:33 +00001992 if (trigger_cursorhold() && maxlen >= 3)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001993 {
Bram Moolenaar3918c952005-03-15 22:34:55 +00001994 buf[0] = K_SPECIAL;
1995 buf[1] = KS_EXTRA;
1996 buf[2] = (int)KE_CURSORHOLD;
1997 return 3;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001998 }
Bram Moolenaar702517d2005-06-27 22:34:07 +00001999 before_blocking();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002000 }
2001 }
2002
2003 /*
2004 * Try to read as many characters as there are, until the buffer is full.
2005 */
2006
Bram Moolenaar0f873732019-12-05 20:28:46 +01002007 // we will get at least one key. Get more if they are available.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002008 g_fCBrkPressed = FALSE;
2009
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002010# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00002011 if (fdDump)
2012 fputc('[', fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002013# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002014
Bram Moolenaar0f873732019-12-05 20:28:46 +01002015 // Keep looping until there is something in the typeahead buffer and more
2016 // to get and still room in the buffer (up to two bytes for a char and
2017 // three bytes for a modifier).
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02002018 while ((typeaheadlen == 0 || WaitForChar(0L, FALSE))
Bram Moolenaar9f1983d2022-05-12 20:35:35 +01002019 && typeaheadlen + 5 + TYPEAHEADSPACE <= TYPEAHEADLEN)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002020 {
2021 if (typebuf_changed(tb_change_cnt))
2022 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01002023 // "buf" may be invalid now if a client put something in the
2024 // typeahead buffer and "buf" is in the typeahead buffer.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002025 typeaheadlen = 0;
2026 break;
2027 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002028 if (g_nMouseClick != -1)
2029 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002030# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00002031 if (fdDump)
2032 fprintf(fdDump, "{%02x @ %d, %d}",
2033 g_nMouseClick, g_xMouse, g_yMouse);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002034# endif
Christopher Plewright2a46f812022-10-16 19:47:45 +01002035 char_u modifiers = ((char_u *)(&g_nMouseClick))[0];
2036 char_u scroll_dir = ((char_u *)(&g_nMouseClick))[1];
2037
2038 if (scroll_dir == KE_MOUSEDOWN
2039 || scroll_dir == KE_MOUSEUP
2040 || scroll_dir == KE_MOUSELEFT
2041 || scroll_dir == KE_MOUSERIGHT)
2042 {
2043 if (modifiers > 0)
2044 {
2045 typeahead[typeaheadlen++] = CSI;
2046 typeahead[typeaheadlen++] = KS_MODIFIER;
2047 typeahead[typeaheadlen++] = modifiers;
2048 }
2049 typeahead[typeaheadlen++] = CSI;
2050 typeahead[typeaheadlen++] = KS_EXTRA;
2051 typeahead[typeaheadlen++] = scroll_dir;
2052 g_nMouseClick = -1;
2053 }
2054 else
2055 {
2056 typeahead[typeaheadlen++] = ESC + 128;
2057 typeahead[typeaheadlen++] = 'M';
2058 typeahead[typeaheadlen++] = g_nMouseClick;
2059 typeahead[typeaheadlen++] = g_xMouse + '!';
2060 typeahead[typeaheadlen++] = g_yMouse + '!';
2061 g_nMouseClick = -1;
2062 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002063 }
2064 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00002065 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002066 WCHAR ch2 = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002067 int modifiers = 0;
2068
2069 c = tgetch(&modifiers, &ch2);
2070
2071 if (typebuf_changed(tb_change_cnt))
2072 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01002073 // "buf" may be invalid now if a client put something in the
2074 // typeahead buffer and "buf" is in the typeahead buffer.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002075 typeaheadlen = 0;
2076 break;
2077 }
2078
2079 if (c == Ctrl_C && ctrl_c_interrupts)
2080 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002081# if defined(FEAT_CLIENTSERVER)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002082 trash_input_buf();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002083# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002084 got_int = TRUE;
2085 }
2086
Bram Moolenaar071d4272004-06-13 20:20:40 +00002087 if (g_nMouseClick == -1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002088 {
2089 int n = 1;
2090
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002091 if (ch2 == NUL)
2092 {
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01002093 int i, j;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002094 char_u *p;
2095 WCHAR ch[2];
2096
2097 ch[0] = c;
Bram Moolenaar0f873732019-12-05 20:28:46 +01002098 if (c >= 0xD800 && c <= 0xDBFF) // High surrogate
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002099 {
2100 ch[1] = tgetch(&modifiers, &ch2);
2101 n++;
2102 }
2103 p = utf16_to_enc(ch, &n);
2104 if (p != NULL)
2105 {
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01002106 for (i = 0, j = 0; i < n; i++)
2107 {
2108 typeahead[typeaheadlen + j++] = p[i];
2109# ifdef VIMDLL
2110 if (p[i] == CSI)
2111 {
2112 typeahead[typeaheadlen + j++] = KS_EXTRA;
2113 typeahead[typeaheadlen + j++] = KE_CSI;
2114 }
2115# endif
2116 }
2117 n = j;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002118 vim_free(p);
2119 }
2120 }
2121 else
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01002122 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02002123 typeahead[typeaheadlen] = c;
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01002124# ifdef VIMDLL
2125 if (c == CSI)
2126 {
2127 typeahead[typeaheadlen + 1] = KS_EXTRA;
2128 typeahead[typeaheadlen + 2] = KE_CSI;
2129 n = 3;
2130 }
2131# endif
2132 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002133 if (ch2 != NUL)
2134 {
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +02002135 if (c == K_NUL)
Bram Moolenaarfeeb4d02017-12-05 15:14:46 +01002136 {
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +02002137 switch (ch2)
2138 {
2139 case (WCHAR)'\324': // SHIFT+Insert
2140 case (WCHAR)'\325': // CTRL+Insert
2141 case (WCHAR)'\327': // SHIFT+Delete
2142 case (WCHAR)'\330': // CTRL+Delete
2143 typeahead[typeaheadlen + n] = (char_u)ch2;
2144 n++;
2145 break;
2146
2147 default:
2148 typeahead[typeaheadlen + n] = 3;
2149 typeahead[typeaheadlen + n + 1] = (char_u)ch2;
2150 n += 2;
2151 break;
2152 }
Bram Moolenaarfeeb4d02017-12-05 15:14:46 +01002153 }
2154 else
2155 {
2156 typeahead[typeaheadlen + n] = 3;
2157 typeahead[typeaheadlen + n + 1] = (char_u)ch2;
2158 n += 2;
2159 }
Bram Moolenaar45500912014-07-09 20:51:07 +02002160 }
2161
Bram Moolenaar0f873732019-12-05 20:28:46 +01002162 // Use the ALT key to set the 8th bit of the character
2163 // when it's one byte, the 8th bit isn't set yet and not
2164 // using a double-byte encoding (would become a lead
2165 // byte).
Bram Moolenaar071d4272004-06-13 20:20:40 +00002166 if ((modifiers & MOD_MASK_ALT)
2167 && n == 1
2168 && (typeahead[typeaheadlen] & 0x80) == 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00002169 && !enc_dbcs
Bram Moolenaar071d4272004-06-13 20:20:40 +00002170 )
2171 {
Bram Moolenaar85a3e5c2007-11-20 16:22:16 +00002172 n = (*mb_char2bytes)(typeahead[typeaheadlen] | 0x80,
2173 typeahead + typeaheadlen);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002174 modifiers &= ~MOD_MASK_ALT;
2175 }
2176
2177 if (modifiers != 0)
2178 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01002179 // Prepend modifiers to the character.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002180 mch_memmove(typeahead + typeaheadlen + 3,
2181 typeahead + typeaheadlen, n);
2182 typeahead[typeaheadlen++] = K_SPECIAL;
2183 typeahead[typeaheadlen++] = (char_u)KS_MODIFIER;
2184 typeahead[typeaheadlen++] = modifiers;
2185 }
2186
2187 typeaheadlen += n;
2188
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002189# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00002190 if (fdDump)
2191 fputc(c, fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002192# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002193 }
2194 }
2195 }
2196
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002197# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00002198 if (fdDump)
2199 {
2200 fputs("]\n", fdDump);
2201 fflush(fdDump);
2202 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002203# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002204
Bram Moolenaar071d4272004-06-13 20:20:40 +00002205theend:
Bram Moolenaar0f873732019-12-05 20:28:46 +01002206 // Move typeahead to "buf", as much as fits.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002207 len = 0;
2208 while (len < maxlen && typeaheadlen > 0)
2209 {
2210 buf[len++] = typeahead[0];
2211 mch_memmove(typeahead, typeahead + 1, --typeaheadlen);
2212 }
K.Takata6e1d31e2022-02-03 13:05:32 +00002213# ifdef FEAT_JOB_CHANNEL
Bram Moolenaar7ca86fe2020-09-03 19:25:11 +02002214 if (len > 0)
2215 {
2216 buf[len] = NUL;
2217 ch_log(NULL, "raw key input: \"%s\"", buf);
2218 }
K.Takata6e1d31e2022-02-03 13:05:32 +00002219# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002220 return len;
2221
Bram Moolenaar0f873732019-12-05 20:28:46 +01002222#else // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00002223 return 0;
Bram Moolenaar0f873732019-12-05 20:28:46 +01002224#endif // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00002225}
2226
Bram Moolenaar82881492012-11-20 16:53:39 +01002227#ifndef PROTO
2228# ifndef __MINGW32__
Bram Moolenaar0f873732019-12-05 20:28:46 +01002229# include <shellapi.h> // required for FindExecutable()
Bram Moolenaar82881492012-11-20 16:53:39 +01002230# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002231#endif
2232
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002233/*
Bram Moolenaar95da1362020-05-30 18:37:55 +02002234 * Return TRUE if "name" is an executable file, FALSE if not or it doesn't exist.
Bram Moolenaar43663192017-03-05 14:29:12 +01002235 * When returning TRUE and "path" is not NULL save the path and set "*path" to
2236 * the allocated memory.
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00002237 * TODO: Should somehow check if it's really executable.
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002238 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002239 static int
Bram Moolenaar95da1362020-05-30 18:37:55 +02002240executable_file(char *name, char_u **path)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002241{
LemonBoy40fd7e62022-05-05 20:18:16 +01002242 int attrs = win32_getattrs((char_u *)name);
2243
2244 // The file doesn't exist or is a folder.
2245 if (attrs == -1 || (attrs & FILE_ATTRIBUTE_DIRECTORY))
2246 return FALSE;
2247 // Check if the file is an AppExecLink, a special alias used by Windows
2248 // Store for its apps.
2249 if (attrs & FILE_ATTRIBUTE_REPARSE_POINT)
Bram Moolenaar43663192017-03-05 14:29:12 +01002250 {
LemonBoy40fd7e62022-05-05 20:18:16 +01002251 char_u *res = resolve_appexeclink((char_u *)name);
2252 if (res == NULL)
2253 return FALSE;
2254 // The path is already absolute.
Bram Moolenaar95da1362020-05-30 18:37:55 +02002255 if (path != NULL)
LemonBoy40fd7e62022-05-05 20:18:16 +01002256 *path = res;
2257 else
2258 vim_free(res);
Bram Moolenaar95da1362020-05-30 18:37:55 +02002259 }
LemonBoy40fd7e62022-05-05 20:18:16 +01002260 else if (path != NULL)
2261 *path = FullName_save((char_u *)name, FALSE);
2262 return TRUE;
Bram Moolenaar95da1362020-05-30 18:37:55 +02002263}
2264
2265/*
2266 * If "use_path" is TRUE: Return TRUE if "name" is in $PATH.
2267 * If "use_path" is FALSE: Return TRUE if "name" exists.
2268 * If "use_pathext" is TRUE search "name" with extensions in $PATHEXT.
2269 * When returning TRUE and "path" is not NULL save the path and set "*path" to
2270 * the allocated memory.
2271 */
2272 static int
2273executable_exists(char *name, char_u **path, int use_path, int use_pathext)
2274{
2275 // WinNT and later can use _MAX_PATH wide characters for a pathname, which
2276 // means that the maximum pathname is _MAX_PATH * 3 bytes when 'enc' is
2277 // UTF-8.
2278 char_u buf[_MAX_PATH * 3];
2279 size_t len = STRLEN(name);
2280 size_t tmplen;
2281 char_u *p, *e, *e2;
2282 char_u *pathbuf = NULL;
2283 char_u *pathext = NULL;
2284 char_u *pathextbuf = NULL;
Mike Williamsa3d1b292021-06-30 20:56:00 +02002285 char_u *shname = NULL;
Bram Moolenaar95da1362020-05-30 18:37:55 +02002286 int noext = FALSE;
2287 int retval = FALSE;
2288
2289 if (len >= sizeof(buf)) // safety check
Bram Moolenaar43663192017-03-05 14:29:12 +01002290 return FALSE;
Bram Moolenaar95da1362020-05-30 18:37:55 +02002291
2292 // Using the name directly when a Unix-shell like 'shell'.
Mike Williamsa3d1b292021-06-30 20:56:00 +02002293 shname = gettail(p_sh);
2294 if (strstr((char *)shname, "sh") != NULL &&
2295 !(strstr((char *)shname, "powershell") != NULL
2296 || strstr((char *)shname, "pwsh") != NULL))
Bram Moolenaar95da1362020-05-30 18:37:55 +02002297 noext = TRUE;
2298
2299 if (use_pathext)
2300 {
2301 pathext = mch_getenv("PATHEXT");
2302 if (pathext == NULL)
2303 pathext = (char_u *)".com;.exe;.bat;.cmd";
2304
2305 if (noext == FALSE)
2306 {
2307 /*
2308 * Loop over all extensions in $PATHEXT.
2309 * Check "name" ends with extension.
2310 */
2311 p = pathext;
2312 while (*p)
2313 {
2314 if (p[0] == ';'
2315 || (p[0] == '.' && (p[1] == NUL || p[1] == ';')))
2316 {
2317 // Skip empty or single ".".
2318 ++p;
2319 continue;
2320 }
2321 e = vim_strchr(p, ';');
2322 if (e == NULL)
2323 e = p + STRLEN(p);
2324 tmplen = e - p;
2325
2326 if (_strnicoll(name + len - tmplen, (char *)p, tmplen) == 0)
2327 {
2328 noext = TRUE;
2329 break;
2330 }
2331
2332 p = e;
2333 }
2334 }
Bram Moolenaar43663192017-03-05 14:29:12 +01002335 }
2336
Dominique Pelleaf4a61a2021-12-27 17:21:41 +00002337 // Prepend single "." to pathext, it means no extension added.
Bram Moolenaar95da1362020-05-30 18:37:55 +02002338 if (pathext == NULL)
2339 pathext = (char_u *)".";
2340 else if (noext == TRUE)
2341 {
2342 if (pathextbuf == NULL)
2343 pathextbuf = alloc(STRLEN(pathext) + 3);
2344 if (pathextbuf == NULL)
2345 {
2346 retval = FALSE;
2347 goto theend;
2348 }
2349 STRCPY(pathextbuf, ".;");
2350 STRCAT(pathextbuf, pathext);
2351 pathext = pathextbuf;
2352 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002353
Bram Moolenaar95da1362020-05-30 18:37:55 +02002354 // Use $PATH when "use_path" is TRUE and "name" is basename.
2355 if (use_path && gettail((char_u *)name) == (char_u *)name)
2356 {
2357 p = mch_getenv("PATH");
2358 if (p != NULL)
2359 {
2360 pathbuf = alloc(STRLEN(p) + 3);
2361 if (pathbuf == NULL)
2362 {
2363 retval = FALSE;
2364 goto theend;
2365 }
Yasuhiro Matsumoto05cf63e2022-05-03 11:02:28 +01002366
2367 if (mch_getenv("NoDefaultCurrentDirectoryInExePath") == NULL)
2368 STRCPY(pathbuf, ".;");
2369 else
2370 *pathbuf = NUL;
Bram Moolenaar95da1362020-05-30 18:37:55 +02002371 STRCAT(pathbuf, p);
2372 }
2373 }
2374
2375 /*
2376 * Walk through all entries in $PATH to check if "name" exists there and
2377 * is an executable file.
2378 */
2379 p = (pathbuf != NULL) ? pathbuf : (char_u *)".";
2380 while (*p)
2381 {
2382 if (*p == ';') // Skip empty entry
2383 {
2384 ++p;
2385 continue;
2386 }
2387 e = vim_strchr(p, ';');
2388 if (e == NULL)
2389 e = p + STRLEN(p);
2390
2391 if (e - p + len + 2 > sizeof(buf))
2392 {
2393 retval = FALSE;
2394 goto theend;
2395 }
2396 // A single "." that means current dir.
2397 if (e - p == 1 && *p == '.')
2398 STRCPY(buf, name);
2399 else
2400 {
2401 vim_strncpy(buf, p, e - p);
2402 add_pathsep(buf);
2403 STRCAT(buf, name);
2404 }
2405 tmplen = STRLEN(buf);
2406
2407 /*
2408 * Loop over all extensions in $PATHEXT.
2409 * Check "name" with extension added.
2410 */
2411 p = pathext;
2412 while (*p)
2413 {
2414 if (*p == ';')
2415 {
2416 // Skip empty entry
2417 ++p;
2418 continue;
2419 }
2420 e2 = vim_strchr(p, (int)';');
2421 if (e2 == NULL)
2422 e2 = p + STRLEN(p);
2423
2424 if (!(p[0] == '.' && (p[1] == NUL || p[1] == ';')))
2425 {
2426 // Not a single "." that means no extension is added.
2427 if (e2 - p + tmplen + 1 > sizeof(buf))
2428 {
2429 retval = FALSE;
2430 goto theend;
2431 }
2432 vim_strncpy(buf + tmplen, p, e2 - p);
2433 }
2434 if (executable_file((char *)buf, path))
2435 {
2436 retval = TRUE;
2437 goto theend;
2438 }
2439
2440 p = e2;
2441 }
2442
2443 p = e;
2444 }
2445
2446theend:
2447 free(pathextbuf);
2448 free(pathbuf);
2449 return retval;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002450}
2451
Bram Moolenaar1eed5322019-02-26 17:03:54 +01002452#if (defined(__MINGW32__) && __MSVCRT_VERSION__ >= 0x800) || \
2453 (defined(_MSC_VER) && _MSC_VER >= 1400)
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002454/*
2455 * Bad parameter handler.
2456 *
2457 * Certain MS CRT functions will intentionally crash when passed invalid
2458 * parameters to highlight possible security holes. Setting this function as
2459 * the bad parameter handler will prevent the crash.
2460 *
2461 * In debug builds the parameters contain CRT information that might help track
2462 * down the source of a problem, but in non-debug builds the arguments are all
2463 * NULL/0. Debug builds will also produce assert dialogs from the CRT, it is
2464 * worth allowing these to make debugging of issues easier.
2465 */
2466 static void
Yegappan Lakshmanana34b4462022-06-11 10:43:26 +01002467bad_param_handler(const wchar_t *expression UNUSED,
2468 const wchar_t *function UNUSED,
2469 const wchar_t *file UNUSED,
2470 unsigned int line UNUSED,
2471 uintptr_t pReserved UNUSED)
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002472{
2473}
2474
2475# define SET_INVALID_PARAM_HANDLER \
2476 ((void)_set_invalid_parameter_handler(bad_param_handler))
2477#else
2478# define SET_INVALID_PARAM_HANDLER
2479#endif
2480
Bram Moolenaar4f974752019-02-17 17:44:42 +01002481#ifdef FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00002482
2483/*
2484 * GUI version of mch_init().
2485 */
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002486 static void
2487mch_init_g(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002488{
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002489# ifndef __MINGW32__
Bram Moolenaar071d4272004-06-13 20:20:40 +00002490 extern int _fmode;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002491# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002492
Bram Moolenaar0f873732019-12-05 20:28:46 +01002493 // Silently handle invalid parameters to CRT functions
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002494 SET_INVALID_PARAM_HANDLER;
2495
Bram Moolenaar0f873732019-12-05 20:28:46 +01002496 // Let critical errors result in a failure, not in a dialog box. Required
2497 // for the timestamp test to work on removed floppies.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002498 SetErrorMode(SEM_FAILCRITICALERRORS);
2499
Bram Moolenaar0f873732019-12-05 20:28:46 +01002500 _fmode = O_BINARY; // we do our own CR-LF translation
Bram Moolenaar071d4272004-06-13 20:20:40 +00002501
Bram Moolenaar0f873732019-12-05 20:28:46 +01002502 // Specify window size. Is there a place to get the default from?
Bram Moolenaar071d4272004-06-13 20:20:40 +00002503 Rows = 25;
2504 Columns = 80;
2505
Bram Moolenaar0f873732019-12-05 20:28:46 +01002506 // Look for 'vimrun'
Bram Moolenaar071d4272004-06-13 20:20:40 +00002507 {
2508 char_u vimrun_location[_MAX_PATH + 4];
2509
Bram Moolenaar0f873732019-12-05 20:28:46 +01002510 // First try in same directory as gvim.exe
Bram Moolenaar071d4272004-06-13 20:20:40 +00002511 STRCPY(vimrun_location, exe_name);
2512 STRCPY(gettail(vimrun_location), "vimrun.exe");
2513 if (mch_getperm(vimrun_location) >= 0)
2514 {
2515 if (*skiptowhite(vimrun_location) != NUL)
2516 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01002517 // Enclose path with white space in double quotes.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002518 mch_memmove(vimrun_location + 1, vimrun_location,
2519 STRLEN(vimrun_location) + 1);
2520 *vimrun_location = '"';
2521 STRCPY(gettail(vimrun_location), "vimrun\" ");
2522 }
2523 else
2524 STRCPY(gettail(vimrun_location), "vimrun ");
2525
2526 vimrun_path = (char *)vim_strsave(vimrun_location);
2527 s_dont_use_vimrun = FALSE;
2528 }
Bram Moolenaar95da1362020-05-30 18:37:55 +02002529 else if (executable_exists("vimrun.exe", NULL, TRUE, FALSE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002530 s_dont_use_vimrun = FALSE;
2531
Bram Moolenaar0f873732019-12-05 20:28:46 +01002532 // Don't give the warning for a missing vimrun.exe right now, but only
2533 // when vimrun was supposed to be used. Don't bother people that do
2534 // not need vimrun.exe.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002535 if (s_dont_use_vimrun)
2536 need_vimrun_warning = TRUE;
2537 }
2538
2539 /*
2540 * If "finstr.exe" doesn't exist, use "grep -n" for 'grepprg'.
2541 * Otherwise the default "findstr /n" is used.
2542 */
Bram Moolenaar95da1362020-05-30 18:37:55 +02002543 if (!executable_exists("findstr.exe", NULL, TRUE, FALSE))
Bram Moolenaar75ab5902022-04-18 15:36:40 +01002544 set_option_value_give_err((char_u *)"grepprg",
2545 0, (char_u *)"grep -n", 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002546
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002547# ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01002548 win_clip_init();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002549# endif
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01002550
2551 vtp_flag_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002552}
2553
2554
Bram Moolenaar0f873732019-12-05 20:28:46 +01002555#endif // FEAT_GUI_MSWIN
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002556
2557#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002558
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002559# define SRWIDTH(sr) ((sr).Right - (sr).Left + 1)
2560# define SRHEIGHT(sr) ((sr).Bottom - (sr).Top + 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002561
2562/*
2563 * ClearConsoleBuffer()
2564 * Description:
2565 * Clears the entire contents of the console screen buffer, using the
2566 * specified attribute.
2567 * Returns:
2568 * TRUE on success
2569 */
2570 static BOOL
2571ClearConsoleBuffer(WORD wAttribute)
2572{
2573 CONSOLE_SCREEN_BUFFER_INFO csbi;
2574 COORD coord;
2575 DWORD NumCells, dummy;
2576
2577 if (!GetConsoleScreenBufferInfo(g_hConOut, &csbi))
2578 return FALSE;
2579
2580 NumCells = csbi.dwSize.X * csbi.dwSize.Y;
2581 coord.X = 0;
2582 coord.Y = 0;
2583 if (!FillConsoleOutputCharacter(g_hConOut, ' ', NumCells,
2584 coord, &dummy))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002585 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002586 if (!FillConsoleOutputAttribute(g_hConOut, wAttribute, NumCells,
2587 coord, &dummy))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002588 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002589
2590 return TRUE;
2591}
2592
2593/*
2594 * FitConsoleWindow()
2595 * Description:
2596 * Checks if the console window will fit within given buffer dimensions.
2597 * Also, if requested, will shrink the window to fit.
2598 * Returns:
2599 * TRUE on success
2600 */
2601 static BOOL
2602FitConsoleWindow(
2603 COORD dwBufferSize,
2604 BOOL WantAdjust)
2605{
2606 CONSOLE_SCREEN_BUFFER_INFO csbi;
2607 COORD dwWindowSize;
2608 BOOL NeedAdjust = FALSE;
2609
2610 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
2611 {
2612 /*
2613 * A buffer resize will fail if the current console window does
2614 * not lie completely within that buffer. To avoid this, we might
2615 * have to move and possibly shrink the window.
2616 */
2617 if (csbi.srWindow.Right >= dwBufferSize.X)
2618 {
2619 dwWindowSize.X = SRWIDTH(csbi.srWindow);
2620 if (dwWindowSize.X > dwBufferSize.X)
2621 dwWindowSize.X = dwBufferSize.X;
2622 csbi.srWindow.Right = dwBufferSize.X - 1;
2623 csbi.srWindow.Left = dwBufferSize.X - dwWindowSize.X;
2624 NeedAdjust = TRUE;
2625 }
2626 if (csbi.srWindow.Bottom >= dwBufferSize.Y)
2627 {
2628 dwWindowSize.Y = SRHEIGHT(csbi.srWindow);
2629 if (dwWindowSize.Y > dwBufferSize.Y)
2630 dwWindowSize.Y = dwBufferSize.Y;
2631 csbi.srWindow.Bottom = dwBufferSize.Y - 1;
2632 csbi.srWindow.Top = dwBufferSize.Y - dwWindowSize.Y;
2633 NeedAdjust = TRUE;
2634 }
2635 if (NeedAdjust && WantAdjust)
2636 {
2637 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &csbi.srWindow))
2638 return FALSE;
2639 }
2640 return TRUE;
2641 }
2642
2643 return FALSE;
2644}
2645
2646typedef struct ConsoleBufferStruct
2647{
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002648 BOOL IsValid;
2649 CONSOLE_SCREEN_BUFFER_INFO Info;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002650 PCHAR_INFO Buffer;
2651 COORD BufferSize;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002652 PSMALL_RECT Regions;
2653 int NumRegions;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002654} ConsoleBuffer;
2655
2656/*
2657 * SaveConsoleBuffer()
2658 * Description:
2659 * Saves important information about the console buffer, including the
2660 * actual buffer contents. The saved information is suitable for later
2661 * restoration by RestoreConsoleBuffer().
2662 * Returns:
2663 * TRUE if all information was saved; FALSE otherwise
2664 * If FALSE, still sets cb->IsValid if buffer characteristics were saved.
2665 */
2666 static BOOL
2667SaveConsoleBuffer(
2668 ConsoleBuffer *cb)
2669{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002670 DWORD NumCells;
2671 COORD BufferCoord;
2672 SMALL_RECT ReadRegion;
2673 WORD Y, Y_incr;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002674 int i, numregions;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002675
Bram Moolenaar071d4272004-06-13 20:20:40 +00002676 if (cb == NULL)
2677 return FALSE;
2678
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002679 if (!GetConsoleScreenBufferInfo(g_hConOut, &cb->Info))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002680 {
2681 cb->IsValid = FALSE;
2682 return FALSE;
2683 }
2684 cb->IsValid = TRUE;
2685
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002686 /*
2687 * Allocate a buffer large enough to hold the entire console screen
2688 * buffer. If this ConsoleBuffer structure has already been initialized
2689 * with a buffer of the correct size, then just use that one.
2690 */
2691 if (!cb->IsValid || cb->Buffer == NULL ||
2692 cb->BufferSize.X != cb->Info.dwSize.X ||
2693 cb->BufferSize.Y != cb->Info.dwSize.Y)
2694 {
2695 cb->BufferSize.X = cb->Info.dwSize.X;
2696 cb->BufferSize.Y = cb->Info.dwSize.Y;
2697 NumCells = cb->BufferSize.X * cb->BufferSize.Y;
2698 vim_free(cb->Buffer);
Bram Moolenaarc799fe22019-05-28 23:08:19 +02002699 cb->Buffer = ALLOC_MULT(CHAR_INFO, NumCells);
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002700 if (cb->Buffer == NULL)
2701 return FALSE;
2702 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002703
2704 /*
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002705 * We will now copy the console screen buffer into our buffer.
2706 * ReadConsoleOutput() seems to be limited as far as how much you
2707 * can read at a time. Empirically, this number seems to be about
2708 * 12000 cells (rows * columns). Start at position (0, 0) and copy
2709 * in chunks until it is all copied. The chunks will all have the
2710 * same horizontal characteristics, so initialize them now. The
2711 * height of each chunk will be (12000 / width).
Bram Moolenaar071d4272004-06-13 20:20:40 +00002712 */
Bram Moolenaar61594242015-09-01 20:23:37 +02002713 BufferCoord.X = 0;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002714 ReadRegion.Left = 0;
2715 ReadRegion.Right = cb->Info.dwSize.X - 1;
2716 Y_incr = 12000 / cb->Info.dwSize.X;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002717
2718 numregions = (cb->Info.dwSize.Y + Y_incr - 1) / Y_incr;
2719 if (cb->Regions == NULL || numregions != cb->NumRegions)
2720 {
2721 cb->NumRegions = numregions;
2722 vim_free(cb->Regions);
Bram Moolenaarc799fe22019-05-28 23:08:19 +02002723 cb->Regions = ALLOC_MULT(SMALL_RECT, cb->NumRegions);
Bram Moolenaar444fda22017-08-11 20:37:00 +02002724 if (cb->Regions == NULL)
2725 {
Bram Moolenaard23a8232018-02-10 18:45:26 +01002726 VIM_CLEAR(cb->Buffer);
Bram Moolenaar444fda22017-08-11 20:37:00 +02002727 return FALSE;
2728 }
2729 }
2730
2731 for (i = 0, Y = 0; i < cb->NumRegions; i++, Y += Y_incr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002732 {
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002733 /*
2734 * Read into position (0, Y) in our buffer.
2735 */
2736 BufferCoord.Y = Y;
2737 /*
2738 * Read the region whose top left corner is (0, Y) and whose bottom
2739 * right corner is (width - 1, Y + Y_incr - 1). This should define
2740 * a region of size width by Y_incr. Don't worry if this region is
2741 * too large for the remaining buffer; it will be cropped.
2742 */
2743 ReadRegion.Top = Y;
2744 ReadRegion.Bottom = Y + Y_incr - 1;
Bram Moolenaar0f873732019-12-05 20:28:46 +01002745 if (!ReadConsoleOutputW(g_hConOut, // output handle
2746 cb->Buffer, // our buffer
2747 cb->BufferSize, // dimensions of our buffer
2748 BufferCoord, // offset in our buffer
2749 &ReadRegion)) // region to save
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002750 {
Bram Moolenaard23a8232018-02-10 18:45:26 +01002751 VIM_CLEAR(cb->Buffer);
2752 VIM_CLEAR(cb->Regions);
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002753 return FALSE;
2754 }
Bram Moolenaar444fda22017-08-11 20:37:00 +02002755 cb->Regions[i] = ReadRegion;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002756 }
2757
2758 return TRUE;
2759}
2760
2761/*
2762 * RestoreConsoleBuffer()
2763 * Description:
2764 * Restores important information about the console buffer, including the
2765 * actual buffer contents, if desired. The information to restore is in
2766 * the same format used by SaveConsoleBuffer().
2767 * Returns:
2768 * TRUE on success
2769 */
2770 static BOOL
2771RestoreConsoleBuffer(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002772 ConsoleBuffer *cb,
2773 BOOL RestoreScreen)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002774{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002775 COORD BufferCoord;
2776 SMALL_RECT WriteRegion;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002777 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002778
2779 if (cb == NULL || !cb->IsValid)
2780 return FALSE;
2781
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002782 /*
2783 * Before restoring the buffer contents, clear the current buffer, and
2784 * restore the cursor position and window information. Doing this now
2785 * prevents old buffer contents from "flashing" onto the screen.
2786 */
2787 if (RestoreScreen)
2788 ClearConsoleBuffer(cb->Info.wAttributes);
2789
2790 FitConsoleWindow(cb->Info.dwSize, TRUE);
2791 if (!SetConsoleScreenBufferSize(g_hConOut, cb->Info.dwSize))
2792 return FALSE;
2793 if (!SetConsoleTextAttribute(g_hConOut, cb->Info.wAttributes))
2794 return FALSE;
2795
2796 if (!RestoreScreen)
2797 {
2798 /*
2799 * No need to restore the screen buffer contents, so we're done.
2800 */
2801 return TRUE;
2802 }
2803
2804 if (!SetConsoleCursorPosition(g_hConOut, cb->Info.dwCursorPosition))
2805 return FALSE;
2806 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &cb->Info.srWindow))
2807 return FALSE;
2808
2809 /*
2810 * Restore the screen buffer contents.
2811 */
2812 if (cb->Buffer != NULL)
2813 {
Bram Moolenaar444fda22017-08-11 20:37:00 +02002814 for (i = 0; i < cb->NumRegions; i++)
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002815 {
Bram Moolenaar444fda22017-08-11 20:37:00 +02002816 BufferCoord.X = cb->Regions[i].Left;
2817 BufferCoord.Y = cb->Regions[i].Top;
2818 WriteRegion = cb->Regions[i];
Bram Moolenaar0f873732019-12-05 20:28:46 +01002819 if (!WriteConsoleOutputW(g_hConOut, // output handle
2820 cb->Buffer, // our buffer
2821 cb->BufferSize, // dimensions of our buffer
2822 BufferCoord, // offset in our buffer
2823 &WriteRegion)) // region to restore
Bram Moolenaar444fda22017-08-11 20:37:00 +02002824 return FALSE;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002825 }
2826 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002827
2828 return TRUE;
2829}
2830
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002831# define FEAT_RESTORE_ORIG_SCREEN
2832# ifdef FEAT_RESTORE_ORIG_SCREEN
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002833static ConsoleBuffer g_cbOrig = { 0 };
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002834# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002835static ConsoleBuffer g_cbNonTermcap = { 0 };
2836static ConsoleBuffer g_cbTermcap = { 0 };
2837
Bram Moolenaar071d4272004-06-13 20:20:40 +00002838char g_szOrigTitle[256] = { 0 };
Bram Moolenaar0f873732019-12-05 20:28:46 +01002839HWND g_hWnd = NULL; // also used in os_mswin.c
Bram Moolenaar071d4272004-06-13 20:20:40 +00002840static HICON g_hOrigIconSmall = NULL;
2841static HICON g_hOrigIcon = NULL;
2842static HICON g_hVimIcon = NULL;
2843static BOOL g_fCanChangeIcon = FALSE;
2844
Bram Moolenaar071d4272004-06-13 20:20:40 +00002845/*
2846 * GetConsoleIcon()
2847 * Description:
2848 * Attempts to retrieve the small icon and/or the big icon currently in
2849 * use by a given window.
2850 * Returns:
2851 * TRUE on success
2852 */
2853 static BOOL
2854GetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002855 HWND hWnd,
2856 HICON *phIconSmall,
2857 HICON *phIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002858{
2859 if (hWnd == NULL)
2860 return FALSE;
2861
2862 if (phIconSmall != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002863 *phIconSmall = (HICON)SendMessage(hWnd, WM_GETICON,
2864 (WPARAM)ICON_SMALL, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002865 if (phIcon != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002866 *phIcon = (HICON)SendMessage(hWnd, WM_GETICON,
2867 (WPARAM)ICON_BIG, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002868 return TRUE;
2869}
2870
2871/*
2872 * SetConsoleIcon()
2873 * Description:
2874 * Attempts to change the small icon and/or the big icon currently in
2875 * use by a given window.
2876 * Returns:
2877 * TRUE on success
2878 */
2879 static BOOL
2880SetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002881 HWND hWnd,
2882 HICON hIconSmall,
2883 HICON hIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002884{
Bram Moolenaar071d4272004-06-13 20:20:40 +00002885 if (hWnd == NULL)
2886 return FALSE;
2887
2888 if (hIconSmall != NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002889 SendMessage(hWnd, WM_SETICON,
2890 (WPARAM)ICON_SMALL, (LPARAM)hIconSmall);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002891 if (hIcon != NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002892 SendMessage(hWnd, WM_SETICON,
2893 (WPARAM)ICON_BIG, (LPARAM) hIcon);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002894 return TRUE;
2895}
2896
2897/*
2898 * SaveConsoleTitleAndIcon()
2899 * Description:
2900 * Saves the current console window title in g_szOrigTitle, for later
2901 * restoration. Also, attempts to obtain a handle to the console window,
2902 * and use it to save the small and big icons currently in use by the
2903 * console window. This is not always possible on some versions of Windows;
2904 * nor is it possible when running Vim remotely using Telnet (since the
2905 * console window the user sees is owned by a remote process).
2906 */
2907 static void
2908SaveConsoleTitleAndIcon(void)
2909{
Bram Moolenaar0f873732019-12-05 20:28:46 +01002910 // Save the original title.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002911 if (!GetConsoleTitle(g_szOrigTitle, sizeof(g_szOrigTitle)))
2912 return;
2913
2914 /*
2915 * Obtain a handle to the console window using GetConsoleWindow() from
2916 * KERNEL32.DLL; we need to handle in order to change the window icon.
2917 * This function only exists on NT-based Windows, starting with Windows
2918 * 2000. On older operating systems, we can't change the window icon
2919 * anyway.
2920 */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02002921 g_hWnd = GetConsoleWindow();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002922 if (g_hWnd == NULL)
2923 return;
2924
Bram Moolenaar0f873732019-12-05 20:28:46 +01002925 // Save the original console window icon.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002926 GetConsoleIcon(g_hWnd, &g_hOrigIconSmall, &g_hOrigIcon);
2927 if (g_hOrigIconSmall == NULL || g_hOrigIcon == NULL)
2928 return;
2929
Bram Moolenaar0f873732019-12-05 20:28:46 +01002930 // Extract the first icon contained in the Vim executable.
K.Takata2da11a42022-09-10 13:03:12 +01002931 if (
2932# ifdef FEAT_LIBCALL
2933 mch_icon_load((HANDLE *)&g_hVimIcon) == FAIL ||
2934# endif
2935 g_hVimIcon == NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002936 g_hVimIcon = ExtractIcon(NULL, (LPCSTR)exe_name, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002937 if (g_hVimIcon != NULL)
2938 g_fCanChangeIcon = TRUE;
2939}
Bram Moolenaar071d4272004-06-13 20:20:40 +00002940
2941static int g_fWindInitCalled = FALSE;
2942static int g_fTermcapMode = FALSE;
2943static CONSOLE_CURSOR_INFO g_cci;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002944
2945/*
2946 * non-GUI version of mch_init().
2947 */
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002948 static void
2949mch_init_c(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002950{
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002951# ifndef FEAT_RESTORE_ORIG_SCREEN
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002952 CONSOLE_SCREEN_BUFFER_INFO csbi;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002953# endif
2954# ifndef __MINGW32__
Bram Moolenaar071d4272004-06-13 20:20:40 +00002955 extern int _fmode;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002956# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002957
Bram Moolenaar0f873732019-12-05 20:28:46 +01002958 // Silently handle invalid parameters to CRT functions
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002959 SET_INVALID_PARAM_HANDLER;
2960
Bram Moolenaar0f873732019-12-05 20:28:46 +01002961 // Let critical errors result in a failure, not in a dialog box. Required
2962 // for the timestamp test to work on removed floppies.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002963 SetErrorMode(SEM_FAILCRITICALERRORS);
2964
Bram Moolenaar0f873732019-12-05 20:28:46 +01002965 _fmode = O_BINARY; // we do our own CR-LF translation
Bram Moolenaar071d4272004-06-13 20:20:40 +00002966 out_flush();
2967
Bram Moolenaar0f873732019-12-05 20:28:46 +01002968 // Obtain handles for the standard Console I/O devices
Bram Moolenaar071d4272004-06-13 20:20:40 +00002969 if (read_cmd_fd == 0)
2970 g_hConIn = GetStdHandle(STD_INPUT_HANDLE);
2971 else
2972 create_conin();
2973 g_hConOut = GetStdHandle(STD_OUTPUT_HANDLE);
2974
Christopher Plewright38804d62022-11-09 23:55:52 +00002975 wt_init();
2976 vtp_flag_init();
2977 vtp_init();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002978# ifdef FEAT_RESTORE_ORIG_SCREEN
Bram Moolenaar0f873732019-12-05 20:28:46 +01002979 // Save the initial console buffer for later restoration
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002980 SaveConsoleBuffer(&g_cbOrig);
2981 g_attrCurrent = g_attrDefault = g_cbOrig.Info.wAttributes;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002982# else
Bram Moolenaar0f873732019-12-05 20:28:46 +01002983 // Get current text attributes
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002984 GetConsoleScreenBufferInfo(g_hConOut, &csbi);
2985 g_attrCurrent = g_attrDefault = csbi.wAttributes;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002986# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002987 if (cterm_normal_fg_color == 0)
2988 cterm_normal_fg_color = (g_attrCurrent & 0xf) + 1;
2989 if (cterm_normal_bg_color == 0)
2990 cterm_normal_bg_color = ((g_attrCurrent >> 4) & 0xf) + 1;
2991
Bram Moolenaarbdace832019-03-02 10:13:42 +01002992 // Fg and Bg color index number at startup
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02002993 g_color_index_fg = g_attrDefault & 0xf;
2994 g_color_index_bg = (g_attrDefault >> 4) & 0xf;
2995
Bram Moolenaar0f873732019-12-05 20:28:46 +01002996 // set termcap codes to current text attributes
Bram Moolenaar071d4272004-06-13 20:20:40 +00002997 update_tcap(g_attrCurrent);
2998
2999 GetConsoleCursorInfo(g_hConOut, &g_cci);
3000 GetConsoleMode(g_hConIn, &g_cmodein);
3001 GetConsoleMode(g_hConOut, &g_cmodeout);
3002
Bram Moolenaar071d4272004-06-13 20:20:40 +00003003 SaveConsoleTitleAndIcon();
3004 /*
3005 * Set both the small and big icons of the console window to Vim's icon.
3006 * Note that Vim presently only has one size of icon (32x32), but it
3007 * automatically gets scaled down to 16x16 when setting the small icon.
3008 */
3009 if (g_fCanChangeIcon)
3010 SetConsoleIcon(g_hWnd, g_hVimIcon, g_hVimIcon);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003011
3012 ui_get_shellsize();
3013
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003014# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00003015 fdDump = fopen("dump", "wt");
3016
3017 if (fdDump)
3018 {
3019 time_t t;
3020
3021 time(&t);
3022 fputs(ctime(&t), fdDump);
3023 fflush(fdDump);
3024 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003025# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003026
3027 g_fWindInitCalled = TRUE;
3028
Bram Moolenaar071d4272004-06-13 20:20:40 +00003029 g_fMouseAvail = GetSystemMetrics(SM_MOUSEPRESENT);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003030
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003031# ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01003032 win_clip_init();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003033# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003034}
3035
3036/*
3037 * non-GUI version of mch_exit().
3038 * Shut down and exit with status `r'
3039 * Careful: mch_exit() may be called before mch_init()!
3040 */
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003041 static void
3042mch_exit_c(int r)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003043{
Bram Moolenaar955f1982017-02-05 15:10:51 +01003044 exiting = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003045
Bram Moolenaarcafafb32018-02-22 21:07:09 +01003046 vtp_exit();
3047
Bram Moolenaar955f1982017-02-05 15:10:51 +01003048 stoptermcap();
Bram Moolenaar071d4272004-06-13 20:20:40 +00003049 if (g_fWindInitCalled)
3050 settmode(TMODE_COOK);
3051
Bram Moolenaar0f873732019-12-05 20:28:46 +01003052 ml_close_all(TRUE); // remove all memfiles
Bram Moolenaar071d4272004-06-13 20:20:40 +00003053
3054 if (g_fWindInitCalled)
3055 {
Bram Moolenaar40385db2018-08-07 22:31:44 +02003056 mch_restore_title(SAVE_RESTORE_BOTH);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003057 /*
3058 * Restore both the small and big icons of the console window to
3059 * what they were at startup. Don't do this when the window is
3060 * closed, Vim would hang here.
3061 */
3062 if (g_fCanChangeIcon && !g_fForceExit)
3063 SetConsoleIcon(g_hWnd, g_hOrigIconSmall, g_hOrigIcon);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003064
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003065# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00003066 if (fdDump)
3067 {
3068 time_t t;
3069
3070 time(&t);
3071 fputs(ctime(&t), fdDump);
3072 fclose(fdDump);
3073 }
3074 fdDump = NULL;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003075# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003076 }
3077
3078 SetConsoleCursorInfo(g_hConOut, &g_cci);
Wez Furlong6ef5ab52021-05-30 19:29:41 +02003079 SetConsoleMode(g_hConIn, g_cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003080 SetConsoleMode(g_hConOut, g_cmodeout);
3081
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003082# ifdef DYNAMIC_GETTEXT
Bram Moolenaar071d4272004-06-13 20:20:40 +00003083 dyn_libintl_end();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003084# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003085
3086 exit(r);
3087}
Bram Moolenaar0f873732019-12-05 20:28:46 +01003088#endif // !FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00003089
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003090 void
3091mch_init(void)
3092{
3093#ifdef VIMDLL
3094 if (gui.starting)
3095 mch_init_g();
3096 else
3097 mch_init_c();
3098#elif defined(FEAT_GUI_MSWIN)
3099 mch_init_g();
3100#else
3101 mch_init_c();
3102#endif
3103}
3104
3105 void
3106mch_exit(int r)
3107{
Bram Moolenaar173d8412020-04-19 14:02:26 +02003108#ifdef FEAT_NETBEANS_INTG
3109 netbeans_send_disconnect();
3110#endif
3111
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003112#ifdef VIMDLL
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02003113 if (gui.in_use || gui.starting)
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003114 mch_exit_g(r);
3115 else
3116 mch_exit_c(r);
3117#elif defined(FEAT_GUI_MSWIN)
3118 mch_exit_g(r);
3119#else
3120 mch_exit_c(r);
3121#endif
3122}
3123
Bram Moolenaar071d4272004-06-13 20:20:40 +00003124/*
3125 * Do we have an interactive window?
3126 */
3127 int
3128mch_check_win(
Bram Moolenaar1266d672017-02-01 13:43:36 +01003129 int argc UNUSED,
3130 char **argv UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003131{
3132 get_exe_name();
3133
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003134#if defined(FEAT_GUI_MSWIN) && !defined(VIMDLL)
Bram Moolenaar0f873732019-12-05 20:28:46 +01003135 return OK; // GUI always has a tty
Bram Moolenaar071d4272004-06-13 20:20:40 +00003136#else
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003137# ifdef VIMDLL
3138 if (gui.in_use)
3139 return OK;
3140# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003141 if (isatty(1))
3142 return OK;
3143 return FAIL;
3144#endif
3145}
3146
Bram Moolenaar65f04f62013-08-30 17:29:16 +02003147/*
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003148 * Set the case of the file name, if it already exists.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003149 * When "len" is > 0, also expand short to long filenames.
3150 */
3151 void
3152fname_case(
3153 char_u *name,
3154 int len)
3155{
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003156 int flen;
3157 WCHAR *p;
3158 WCHAR buf[_MAX_PATH + 1];
Bram Moolenaar071d4272004-06-13 20:20:40 +00003159
Bram Moolenaara3ffd9c2005-07-21 21:03:15 +00003160 flen = (int)STRLEN(name);
Bram Moolenaar65f04f62013-08-30 17:29:16 +02003161 if (flen == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003162 return;
3163
3164 slash_adjust(name);
3165
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003166 p = enc_to_utf16(name, NULL);
3167 if (p == NULL)
Bram Moolenaar65f04f62013-08-30 17:29:16 +02003168 return;
3169
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003170 if (GetLongPathNameW(p, buf, _MAX_PATH))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003171 {
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003172 char_u *q = utf16_to_enc(buf, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003173
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003174 if (q != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003175 {
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003176 if (len > 0 || flen >= (int)STRLEN(q))
3177 vim_strncpy(name, q, (len > 0) ? len - 1 : flen);
3178 vim_free(q);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003179 }
3180 }
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003181 vim_free(p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003182}
3183
3184
3185/*
3186 * Insert user name in s[len].
3187 */
3188 int
3189mch_get_user_name(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003190 char_u *s,
3191 int len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003192{
Bram Moolenaar0f873732019-12-05 20:28:46 +01003193 WCHAR wszUserName[256 + 1]; // UNLEN is 256
K.Takataeeec2542021-06-02 13:28:16 +02003194 DWORD wcch = ARRAY_LENGTH(wszUserName);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003195
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003196 if (GetUserNameW(wszUserName, &wcch))
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003197 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003198 char_u *p = utf16_to_enc(wszUserName, NULL);
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003199
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003200 if (p != NULL)
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003201 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003202 vim_strncpy(s, p, len - 1);
3203 vim_free(p);
3204 return OK;
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003205 }
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003206 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003207 s[0] = NUL;
3208 return FAIL;
3209}
3210
3211
3212/*
3213 * Insert host name in s[len].
3214 */
3215 void
3216mch_get_host_name(
3217 char_u *s,
3218 int len)
3219{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003220 WCHAR wszHostName[256 + 1];
K.Takataeeec2542021-06-02 13:28:16 +02003221 DWORD wcch = ARRAY_LENGTH(wszHostName);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003222
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003223 if (GetComputerNameW(wszHostName, &wcch))
Bram Moolenaar2cc87382013-12-11 18:21:45 +01003224 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003225 char_u *p = utf16_to_enc(wszHostName, NULL);
Bram Moolenaar2cc87382013-12-11 18:21:45 +01003226
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003227 if (p != NULL)
Bram Moolenaar2cc87382013-12-11 18:21:45 +01003228 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003229 vim_strncpy(s, p, len - 1);
3230 vim_free(p);
3231 return;
Bram Moolenaar2cc87382013-12-11 18:21:45 +01003232 }
Bram Moolenaar2cc87382013-12-11 18:21:45 +01003233 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003234}
3235
3236
3237/*
3238 * return process ID
3239 */
3240 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003241mch_get_pid(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003242{
3243 return (long)GetCurrentProcessId();
3244}
3245
Bram Moolenaar67cf86b2019-04-28 22:25:38 +02003246/*
3247 * return TRUE if process "pid" is still running
3248 */
3249 int
Bram Moolenaar1b243ea2019-04-28 22:50:40 +02003250mch_process_running(long pid)
Bram Moolenaar67cf86b2019-04-28 22:25:38 +02003251{
3252 HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION, 0, (DWORD)pid);
3253 DWORD status = 0;
3254 int ret = FALSE;
3255
3256 if (hProcess == NULL)
3257 return FALSE; // might not have access
3258 if (GetExitCodeProcess(hProcess, &status) )
3259 ret = status == STILL_ACTIVE;
3260 CloseHandle(hProcess);
3261 return ret;
3262}
Bram Moolenaar071d4272004-06-13 20:20:40 +00003263
3264/*
3265 * Get name of current directory into buffer 'buf' of length 'len' bytes.
3266 * Return OK for success, FAIL for failure.
3267 */
3268 int
3269mch_dirname(
3270 char_u *buf,
3271 int len)
3272{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003273 WCHAR wbuf[_MAX_PATH + 1];
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02003274
Bram Moolenaar071d4272004-06-13 20:20:40 +00003275 /*
3276 * Originally this was:
3277 * return (getcwd(buf, len) != NULL ? OK : FAIL);
3278 * But the Win32s known bug list says that getcwd() doesn't work
3279 * so use the Win32 system call instead. <Negri>
3280 */
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003281 if (GetCurrentDirectoryW(_MAX_PATH, wbuf) != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003282 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003283 WCHAR wcbuf[_MAX_PATH + 1];
3284 char_u *p = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003285
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003286 if (GetLongPathNameW(wbuf, wcbuf, _MAX_PATH) != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003287 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003288 p = utf16_to_enc(wcbuf, NULL);
3289 if (STRLEN(p) >= (size_t)len)
Bram Moolenaarcea1f9e2018-08-19 14:38:42 +02003290 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003291 // long path name is too long, fall back to short one
Bram Moolenaar071d4272004-06-13 20:20:40 +00003292 vim_free(p);
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003293 p = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003294 }
3295 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003296 if (p == NULL)
3297 p = utf16_to_enc(wbuf, NULL);
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02003298
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003299 if (p != NULL)
3300 {
3301 vim_strncpy(buf, p, len - 1);
3302 vim_free(p);
3303 return OK;
3304 }
3305 }
3306 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003307}
3308
3309/*
Bram Moolenaarffa22202013-11-21 12:34:11 +01003310 * Get file permissions for "name".
3311 * Return mode_t or -1 for error.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003312 */
3313 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003314mch_getperm(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003315{
Bram Moolenaar8767f522016-07-01 17:17:39 +02003316 stat_T st;
Bram Moolenaarffa22202013-11-21 12:34:11 +01003317 int n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003318
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003319 n = mch_stat((char *)name, &st);
Bram Moolenaar78cf3f02014-01-10 18:16:07 +01003320 return n == 0 ? (long)(unsigned short)st.st_mode : -1L;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003321}
3322
3323
3324/*
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003325 * Set file permission for "name" to "perm".
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003326 *
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003327 * Return FAIL for failure, OK otherwise.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003328 */
3329 int
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003330mch_setperm(char_u *name, long perm)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003331{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003332 long n;
3333 WCHAR *p;
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003334
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003335 p = enc_to_utf16(name, NULL);
3336 if (p == NULL)
3337 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003338
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003339 n = _wchmod(p, perm);
3340 vim_free(p);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003341 if (n == -1)
3342 return FAIL;
3343
3344 win32_set_archive(name);
3345
3346 return OK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003347}
3348
3349/*
3350 * Set hidden flag for "name".
3351 */
3352 void
3353mch_hide(char_u *name)
3354{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003355 int attrs = win32_getattrs(name);
3356 if (attrs == -1)
3357 return;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003358
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003359 attrs |= FILE_ATTRIBUTE_HIDDEN;
3360 win32_setattrs(name, attrs);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003361}
3362
3363/*
Bram Moolenaar8a52ba72015-11-02 14:45:56 +01003364 * Return TRUE if file "name" exists and is hidden.
3365 */
3366 int
3367mch_ishidden(char_u *name)
3368{
3369 int f = win32_getattrs(name);
3370
3371 if (f == -1)
Bram Moolenaar0f873732019-12-05 20:28:46 +01003372 return FALSE; // file does not exist at all
Bram Moolenaar8a52ba72015-11-02 14:45:56 +01003373
3374 return (f & FILE_ATTRIBUTE_HIDDEN) != 0;
3375}
3376
3377/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003378 * return TRUE if "name" is a directory
3379 * return FALSE if "name" is not a directory or upon error
3380 */
3381 int
3382mch_isdir(char_u *name)
3383{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003384 int f = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003385
3386 if (f == -1)
Bram Moolenaar0f873732019-12-05 20:28:46 +01003387 return FALSE; // file does not exist at all
Bram Moolenaar071d4272004-06-13 20:20:40 +00003388
3389 return (f & FILE_ATTRIBUTE_DIRECTORY) != 0;
3390}
3391
3392/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01003393 * return TRUE if "name" is a directory, NOT a symlink to a directory
3394 * return FALSE if "name" is not a directory
3395 * return FALSE for error
3396 */
3397 int
3398mch_isrealdir(char_u *name)
3399{
3400 return mch_isdir(name) && !mch_is_symbolic_link(name);
3401}
3402
3403/*
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003404 * Create directory "name".
3405 * Return 0 on success, -1 on error.
3406 */
3407 int
3408mch_mkdir(char_u *name)
3409{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003410 WCHAR *p;
3411 int retval;
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003412
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003413 p = enc_to_utf16(name, NULL);
3414 if (p == NULL)
3415 return -1;
3416 retval = _wmkdir(p);
3417 vim_free(p);
3418 return retval;
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003419}
3420
3421/*
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003422 * Delete directory "name".
3423 * Return 0 on success, -1 on error.
3424 */
3425 int
3426mch_rmdir(char_u *name)
3427{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003428 WCHAR *p;
3429 int retval;
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003430
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003431 p = enc_to_utf16(name, NULL);
3432 if (p == NULL)
3433 return -1;
3434 retval = _wrmdir(p);
3435 vim_free(p);
3436 return retval;
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003437}
3438
3439/*
Bram Moolenaar03f48552006-02-28 23:52:23 +00003440 * Return TRUE if file "fname" has more than one link.
3441 */
3442 int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003443mch_is_hard_link(char_u *fname)
Bram Moolenaar03f48552006-02-28 23:52:23 +00003444{
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003445 BY_HANDLE_FILE_INFORMATION info;
3446
3447 return win32_fileinfo(fname, &info) == FILEINFO_OK
3448 && info.nNumberOfLinks > 1;
3449}
3450
3451/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01003452 * Return TRUE if "name" is a symbolic link (or a junction).
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003453 */
3454 int
Bram Moolenaar203258c2016-01-17 22:15:16 +01003455mch_is_symbolic_link(char_u *name)
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003456{
3457 HANDLE hFind;
3458 int res = FALSE;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003459 DWORD fileFlags = 0, reparseTag = 0;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003460 WCHAR *wn;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003461 WIN32_FIND_DATAW findDataW;
3462
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003463 wn = enc_to_utf16(name, NULL);
3464 if (wn == NULL)
3465 return FALSE;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003466
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003467 hFind = FindFirstFileW(wn, &findDataW);
3468 vim_free(wn);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003469 if (hFind != INVALID_HANDLE_VALUE)
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003470 {
3471 fileFlags = findDataW.dwFileAttributes;
3472 reparseTag = findDataW.dwReserved0;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003473 FindClose(hFind);
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003474 }
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003475
3476 if ((fileFlags & FILE_ATTRIBUTE_REPARSE_POINT)
Bram Moolenaar203258c2016-01-17 22:15:16 +01003477 && (reparseTag == IO_REPARSE_TAG_SYMLINK
3478 || reparseTag == IO_REPARSE_TAG_MOUNT_POINT))
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003479 res = TRUE;
3480
3481 return res;
3482}
3483
3484/*
3485 * Return TRUE if file "fname" has more than one link or if it is a symbolic
3486 * link.
3487 */
3488 int
3489mch_is_linked(char_u *fname)
3490{
3491 if (mch_is_hard_link(fname) || mch_is_symbolic_link(fname))
3492 return TRUE;
3493 return FALSE;
3494}
3495
3496/*
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003497 * Get the by-handle-file-information for "fname".
3498 * Returns FILEINFO_OK when OK.
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003499 * Returns FILEINFO_ENC_FAIL when enc_to_utf16() failed.
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003500 * Returns FILEINFO_READ_FAIL when CreateFile() failed.
3501 * Returns FILEINFO_INFO_FAIL when GetFileInformationByHandle() failed.
3502 */
3503 int
3504win32_fileinfo(char_u *fname, BY_HANDLE_FILE_INFORMATION *info)
3505{
Bram Moolenaar03f48552006-02-28 23:52:23 +00003506 HANDLE hFile;
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003507 int res = FILEINFO_READ_FAIL;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003508 WCHAR *wn;
Bram Moolenaar03f48552006-02-28 23:52:23 +00003509
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003510 wn = enc_to_utf16(fname, NULL);
3511 if (wn == NULL)
3512 return FILEINFO_ENC_FAIL;
3513
3514 hFile = CreateFileW(wn, // file name
3515 GENERIC_READ, // access mode
3516 FILE_SHARE_READ | FILE_SHARE_WRITE, // share mode
3517 NULL, // security descriptor
3518 OPEN_EXISTING, // creation disposition
3519 FILE_FLAG_BACKUP_SEMANTICS, // file attributes
3520 NULL); // handle to template file
3521 vim_free(wn);
Bram Moolenaar03f48552006-02-28 23:52:23 +00003522
3523 if (hFile != INVALID_HANDLE_VALUE)
3524 {
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003525 if (GetFileInformationByHandle(hFile, info) != 0)
3526 res = FILEINFO_OK;
3527 else
3528 res = FILEINFO_INFO_FAIL;
Bram Moolenaar03f48552006-02-28 23:52:23 +00003529 CloseHandle(hFile);
3530 }
3531
Bram Moolenaar03f48552006-02-28 23:52:23 +00003532 return res;
3533}
3534
3535/*
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003536 * get file attributes for `name'
3537 * -1 : error
3538 * else FILE_ATTRIBUTE_* defined in winnt.h
3539 */
Bram Moolenaarffa22202013-11-21 12:34:11 +01003540 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003541win32_getattrs(char_u *name)
3542{
3543 int attr;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003544 WCHAR *p;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003545
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003546 p = enc_to_utf16(name, NULL);
3547 if (p == NULL)
3548 return INVALID_FILE_ATTRIBUTES;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003549
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003550 attr = GetFileAttributesW(p);
3551 vim_free(p);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003552
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003553 return attr;
3554}
3555
3556/*
3557 * set file attributes for `name' to `attrs'
3558 *
3559 * return -1 for failure, 0 otherwise
3560 */
Bram Moolenaar6dff58f2018-09-30 21:43:26 +02003561 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003562win32_setattrs(char_u *name, int attrs)
3563{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003564 int res;
3565 WCHAR *p;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003566
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003567 p = enc_to_utf16(name, NULL);
3568 if (p == NULL)
3569 return -1;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003570
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003571 res = SetFileAttributesW(p, attrs);
3572 vim_free(p);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003573
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003574 return res ? 0 : -1;
3575}
3576
3577/*
3578 * Set archive flag for "name".
3579 */
Bram Moolenaar6dff58f2018-09-30 21:43:26 +02003580 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003581win32_set_archive(char_u *name)
3582{
3583 int attrs = win32_getattrs(name);
3584 if (attrs == -1)
3585 return -1;
3586
3587 attrs |= FILE_ATTRIBUTE_ARCHIVE;
3588 return win32_setattrs(name, attrs);
3589}
3590
3591/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003592 * Return TRUE if file or directory "name" is writable (not readonly).
3593 * Strange semantics of Win32: a readonly directory is writable, but you can't
3594 * delete a file. Let's say this means it is writable.
3595 */
3596 int
3597mch_writable(char_u *name)
3598{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003599 int attrs = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003600
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003601 return (attrs != -1 && (!(attrs & FILE_ATTRIBUTE_READONLY)
3602 || (attrs & FILE_ATTRIBUTE_DIRECTORY)));
Bram Moolenaar071d4272004-06-13 20:20:40 +00003603}
3604
Bram Moolenaar071d4272004-06-13 20:20:40 +00003605/*
Bram Moolenaar43663192017-03-05 14:29:12 +01003606 * Return TRUE if "name" can be executed, FALSE if not.
Bram Moolenaar77b77102015-03-21 22:18:41 +01003607 * If "use_path" is FALSE only check if "name" is executable.
Bram Moolenaar43663192017-03-05 14:29:12 +01003608 * When returning TRUE and "path" is not NULL save the path and set "*path" to
3609 * the allocated memory.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003610 */
3611 int
Yegappan Lakshmananebb01bd2022-06-08 15:14:09 +01003612mch_can_exe(char_u *name, char_u **path, int use_path UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003613{
Bram Moolenaar95da1362020-05-30 18:37:55 +02003614 return executable_exists((char *)name, path, TRUE, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003615}
Bram Moolenaar071d4272004-06-13 20:20:40 +00003616
3617/*
3618 * Check what "name" is:
3619 * NODE_NORMAL: file or directory (or doesn't exist)
3620 * NODE_WRITABLE: writable device, socket, fifo, etc.
3621 * NODE_OTHER: non-writable things
3622 */
3623 int
3624mch_nodetype(char_u *name)
3625{
3626 HANDLE hFile;
3627 int type;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003628 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003629
Bram Moolenaar0f873732019-12-05 20:28:46 +01003630 // We can't open a file with a name "\\.\con" or "\\.\prn" and trying to
3631 // read from it later will cause Vim to hang. Thus return NODE_WRITABLE
3632 // here.
Bram Moolenaar043545e2006-10-10 16:44:07 +00003633 if (STRNCMP(name, "\\\\.\\", 4) == 0)
3634 return NODE_WRITABLE;
3635
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003636 wn = enc_to_utf16(name, NULL);
3637 if (wn == NULL)
3638 return NODE_NORMAL;
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003639
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003640 hFile = CreateFileW(wn, // file name
3641 GENERIC_WRITE, // access mode
3642 0, // share mode
3643 NULL, // security descriptor
3644 OPEN_EXISTING, // creation disposition
3645 0, // file attributes
3646 NULL); // handle to template file
3647 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003648 if (hFile == INVALID_HANDLE_VALUE)
3649 return NODE_NORMAL;
3650
3651 type = GetFileType(hFile);
3652 CloseHandle(hFile);
3653 if (type == FILE_TYPE_CHAR)
3654 return NODE_WRITABLE;
3655 if (type == FILE_TYPE_DISK)
3656 return NODE_NORMAL;
3657 return NODE_OTHER;
3658}
3659
3660#ifdef HAVE_ACL
3661struct my_acl
3662{
3663 PSECURITY_DESCRIPTOR pSecurityDescriptor;
3664 PSID pSidOwner;
3665 PSID pSidGroup;
3666 PACL pDacl;
3667 PACL pSacl;
3668};
3669#endif
3670
3671/*
3672 * Return a pointer to the ACL of file "fname" in allocated memory.
3673 * Return NULL if the ACL is not available for whatever reason.
3674 */
3675 vim_acl_T
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003676mch_get_acl(char_u *fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003677{
3678#ifndef HAVE_ACL
3679 return (vim_acl_T)NULL;
3680#else
3681 struct my_acl *p = NULL;
Bram Moolenaar27515922013-06-29 15:36:26 +02003682 DWORD err;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003683
Bram Moolenaarc799fe22019-05-28 23:08:19 +02003684 p = ALLOC_CLEAR_ONE(struct my_acl);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003685 if (p != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003686 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003687 WCHAR *wn;
Bram Moolenaar27515922013-06-29 15:36:26 +02003688
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003689 wn = enc_to_utf16(fname, NULL);
3690 if (wn == NULL)
Bram Moolenaarbbf9f342020-11-10 22:03:40 +01003691 {
3692 vim_free(p);
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003693 return NULL;
Bram Moolenaarbbf9f342020-11-10 22:03:40 +01003694 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003695
3696 // Try to retrieve the entire security descriptor.
3697 err = GetNamedSecurityInfoW(
3698 wn, // Abstract filename
3699 SE_FILE_OBJECT, // File Object
3700 OWNER_SECURITY_INFORMATION |
3701 GROUP_SECURITY_INFORMATION |
3702 DACL_SECURITY_INFORMATION |
3703 SACL_SECURITY_INFORMATION,
3704 &p->pSidOwner, // Ownership information.
3705 &p->pSidGroup, // Group membership.
3706 &p->pDacl, // Discretionary information.
3707 &p->pSacl, // For auditing purposes.
3708 &p->pSecurityDescriptor);
3709 if (err == ERROR_ACCESS_DENIED ||
3710 err == ERROR_PRIVILEGE_NOT_HELD)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003711 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003712 // Retrieve only DACL.
3713 (void)GetNamedSecurityInfoW(
3714 wn,
3715 SE_FILE_OBJECT,
3716 DACL_SECURITY_INFORMATION,
3717 NULL,
3718 NULL,
3719 &p->pDacl,
3720 NULL,
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003721 &p->pSecurityDescriptor);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003722 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003723 if (p->pSecurityDescriptor == NULL)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003724 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003725 mch_free_acl((vim_acl_T)p);
3726 p = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003727 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003728 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003729 }
3730
3731 return (vim_acl_T)p;
3732#endif
3733}
3734
Bram Moolenaar27515922013-06-29 15:36:26 +02003735#ifdef HAVE_ACL
3736/*
3737 * Check if "acl" contains inherited ACE.
3738 */
3739 static BOOL
3740is_acl_inherited(PACL acl)
3741{
3742 DWORD i;
3743 ACL_SIZE_INFORMATION acl_info;
3744 PACCESS_ALLOWED_ACE ace;
3745
3746 acl_info.AceCount = 0;
3747 GetAclInformation(acl, &acl_info, sizeof(acl_info), AclSizeInformation);
3748 for (i = 0; i < acl_info.AceCount; i++)
3749 {
3750 GetAce(acl, i, (LPVOID *)&ace);
3751 if (ace->Header.AceFlags & INHERITED_ACE)
3752 return TRUE;
3753 }
3754 return FALSE;
3755}
3756#endif
3757
Bram Moolenaar071d4272004-06-13 20:20:40 +00003758/*
3759 * Set the ACL of file "fname" to "acl" (unless it's NULL).
3760 * Errors are ignored.
3761 * This must only be called with "acl" equal to what mch_get_acl() returned.
3762 */
3763 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003764mch_set_acl(char_u *fname, vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003765{
3766#ifdef HAVE_ACL
3767 struct my_acl *p = (struct my_acl *)acl;
Bram Moolenaar27515922013-06-29 15:36:26 +02003768 SECURITY_INFORMATION sec_info = 0;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003769 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003770
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003771 if (p == NULL)
3772 return;
3773
3774 wn = enc_to_utf16(fname, NULL);
3775 if (wn == NULL)
3776 return;
3777
3778 // Set security flags
3779 if (p->pSidOwner)
3780 sec_info |= OWNER_SECURITY_INFORMATION;
3781 if (p->pSidGroup)
3782 sec_info |= GROUP_SECURITY_INFORMATION;
3783 if (p->pDacl)
Bram Moolenaar27515922013-06-29 15:36:26 +02003784 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003785 sec_info |= DACL_SECURITY_INFORMATION;
3786 // Do not inherit its parent's DACL.
3787 // If the DACL is inherited, Cygwin permissions would be changed.
3788 if (!is_acl_inherited(p->pDacl))
3789 sec_info |= PROTECTED_DACL_SECURITY_INFORMATION;
Bram Moolenaar27515922013-06-29 15:36:26 +02003790 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003791 if (p->pSacl)
3792 sec_info |= SACL_SECURITY_INFORMATION;
3793
3794 (void)SetNamedSecurityInfoW(
3795 wn, // Abstract filename
3796 SE_FILE_OBJECT, // File Object
3797 sec_info,
3798 p->pSidOwner, // Ownership information.
3799 p->pSidGroup, // Group membership.
3800 p->pDacl, // Discretionary information.
3801 p->pSacl // For auditing purposes.
3802 );
3803 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003804#endif
3805}
3806
3807 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003808mch_free_acl(vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003809{
3810#ifdef HAVE_ACL
3811 struct my_acl *p = (struct my_acl *)acl;
3812
3813 if (p != NULL)
3814 {
3815 LocalFree(p->pSecurityDescriptor); // Free the memory just in case
3816 vim_free(p);
3817 }
3818#endif
3819}
3820
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003821#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003822
3823/*
3824 * handler for ctrl-break, ctrl-c interrupts, and fatal events.
3825 */
3826 static BOOL WINAPI
3827handler_routine(
3828 DWORD dwCtrlType)
3829{
Bram Moolenaar589b1102017-08-12 16:39:05 +02003830 INPUT_RECORD ir;
3831 DWORD out;
3832
Bram Moolenaar071d4272004-06-13 20:20:40 +00003833 switch (dwCtrlType)
3834 {
3835 case CTRL_C_EVENT:
3836 if (ctrl_c_interrupts)
3837 g_fCtrlCPressed = TRUE;
3838 return TRUE;
3839
3840 case CTRL_BREAK_EVENT:
3841 g_fCBrkPressed = TRUE;
Bram Moolenaar589b1102017-08-12 16:39:05 +02003842 ctrl_break_was_pressed = TRUE;
Bram Moolenaar0f873732019-12-05 20:28:46 +01003843 // ReadConsoleInput is blocking, send a key event to continue.
Bram Moolenaar589b1102017-08-12 16:39:05 +02003844 ir.EventType = KEY_EVENT;
3845 ir.Event.KeyEvent.bKeyDown = TRUE;
3846 ir.Event.KeyEvent.wRepeatCount = 1;
3847 ir.Event.KeyEvent.wVirtualKeyCode = VK_CANCEL;
3848 ir.Event.KeyEvent.wVirtualScanCode = 0;
3849 ir.Event.KeyEvent.dwControlKeyState = 0;
3850 ir.Event.KeyEvent.uChar.UnicodeChar = 0;
3851 WriteConsoleInput(g_hConIn, &ir, 1, &out);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003852 return TRUE;
3853
Bram Moolenaar0f873732019-12-05 20:28:46 +01003854 // fatal events: shut down gracefully
Bram Moolenaar071d4272004-06-13 20:20:40 +00003855 case CTRL_CLOSE_EVENT:
3856 case CTRL_LOGOFF_EVENT:
3857 case CTRL_SHUTDOWN_EVENT:
3858 windgoto((int)Rows - 1, 0);
3859 g_fForceExit = TRUE;
3860
Bram Moolenaar0fde2902008-03-16 13:54:13 +00003861 vim_snprintf((char *)IObuff, IOSIZE, _("Vim: Caught %s event\n"),
Bram Moolenaar071d4272004-06-13 20:20:40 +00003862 (dwCtrlType == CTRL_CLOSE_EVENT
3863 ? _("close")
3864 : dwCtrlType == CTRL_LOGOFF_EVENT
3865 ? _("logoff")
3866 : _("shutdown")));
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003867# ifdef DEBUG
Bram Moolenaar071d4272004-06-13 20:20:40 +00003868 OutputDebugString(IObuff);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003869# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003870
Bram Moolenaar0f873732019-12-05 20:28:46 +01003871 preserve_exit(); // output IObuff, preserve files and exit
Bram Moolenaar071d4272004-06-13 20:20:40 +00003872
Bram Moolenaar0f873732019-12-05 20:28:46 +01003873 return TRUE; // not reached
Bram Moolenaar071d4272004-06-13 20:20:40 +00003874
3875 default:
3876 return FALSE;
3877 }
3878}
3879
3880
3881/*
3882 * set the tty in (raw) ? "raw" : "cooked" mode
3883 */
3884 void
Bram Moolenaar26e86442020-05-17 14:06:16 +02003885mch_settmode(tmode_T tmode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003886{
3887 DWORD cmodein;
3888 DWORD cmodeout;
3889 BOOL bEnableHandler;
3890
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003891# ifdef VIMDLL
3892 if (gui.in_use)
3893 return;
3894# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003895 GetConsoleMode(g_hConIn, &cmodein);
3896 GetConsoleMode(g_hConOut, &cmodeout);
3897 if (tmode == TMODE_RAW)
3898 {
3899 cmodein &= ~(ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
3900 ENABLE_ECHO_INPUT);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003901 if (g_fMouseActive)
Wez Furlong6ef5ab52021-05-30 19:29:41 +02003902 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00003903 cmodein |= ENABLE_MOUSE_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02003904 cmodein &= ~ENABLE_QUICK_EDIT_MODE;
3905 }
3906 else
3907 {
3908 cmodein |= g_cmodein & ENABLE_QUICK_EDIT_MODE;
3909 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01003910 cmodeout &= ~(
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003911# ifdef FEAT_TERMGUICOLORS
Bram Moolenaar0f873732019-12-05 20:28:46 +01003912 // Do not turn off the ENABLE_PROCESSED_OUTPUT flag when using
3913 // VTP.
Bram Moolenaarcafafb32018-02-22 21:07:09 +01003914 ((vtp_working) ? 0 : ENABLE_PROCESSED_OUTPUT) |
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003915# else
Bram Moolenaarcafafb32018-02-22 21:07:09 +01003916 ENABLE_PROCESSED_OUTPUT |
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003917# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01003918 ENABLE_WRAP_AT_EOL_OUTPUT);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003919 bEnableHandler = TRUE;
3920 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01003921 else // cooked
Bram Moolenaar071d4272004-06-13 20:20:40 +00003922 {
3923 cmodein |= (ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
3924 ENABLE_ECHO_INPUT);
3925 cmodeout |= (ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
3926 bEnableHandler = FALSE;
3927 }
Wez Furlong6ef5ab52021-05-30 19:29:41 +02003928 SetConsoleMode(g_hConIn, cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003929 SetConsoleMode(g_hConOut, cmodeout);
3930 SetConsoleCtrlHandler(handler_routine, bEnableHandler);
3931
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003932# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00003933 if (fdDump)
3934 {
3935 fprintf(fdDump, "mch_settmode(%s, in = %x, out = %x)\n",
3936 tmode == TMODE_RAW ? "raw" :
3937 tmode == TMODE_COOK ? "cooked" : "normal",
3938 cmodein, cmodeout);
3939 fflush(fdDump);
3940 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003941# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003942}
3943
3944
3945/*
3946 * Get the size of the current window in `Rows' and `Columns'
3947 * Return OK when size could be determined, FAIL otherwise.
3948 */
3949 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003950mch_get_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003951{
3952 CONSOLE_SCREEN_BUFFER_INFO csbi;
3953
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003954# ifdef VIMDLL
3955 if (gui.in_use)
3956 return OK;
3957# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003958 if (!g_fTermcapMode && g_cbTermcap.IsValid)
3959 {
3960 /*
3961 * For some reason, we are trying to get the screen dimensions
3962 * even though we are not in termcap mode. The 'Rows' and 'Columns'
3963 * variables are really intended to mean the size of Vim screen
3964 * while in termcap mode.
3965 */
3966 Rows = g_cbTermcap.Info.dwSize.Y;
3967 Columns = g_cbTermcap.Info.dwSize.X;
3968 }
3969 else if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3970 {
3971 Rows = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
3972 Columns = csbi.srWindow.Right - csbi.srWindow.Left + 1;
3973 }
3974 else
3975 {
3976 Rows = 25;
3977 Columns = 80;
3978 }
3979 return OK;
3980}
3981
3982/*
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02003983 * Resize console buffer to 'COORD'
3984 */
3985 static void
3986ResizeConBuf(
3987 HANDLE hConsole,
3988 COORD coordScreen)
3989{
3990 if (!SetConsoleScreenBufferSize(hConsole, coordScreen))
3991 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003992# ifdef MCH_WRITE_DUMP
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02003993 if (fdDump)
3994 {
3995 fprintf(fdDump, "SetConsoleScreenBufferSize failed: %lx\n",
3996 GetLastError());
3997 fflush(fdDump);
3998 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003999# endif
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004000 }
4001}
4002
4003/*
4004 * Resize console window size to 'srWindowRect'
4005 */
4006 static void
4007ResizeWindow(
4008 HANDLE hConsole,
4009 SMALL_RECT srWindowRect)
4010{
4011 if (!SetConsoleWindowInfo(hConsole, TRUE, &srWindowRect))
4012 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004013# ifdef MCH_WRITE_DUMP
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004014 if (fdDump)
4015 {
4016 fprintf(fdDump, "SetConsoleWindowInfo failed: %lx\n",
4017 GetLastError());
4018 fflush(fdDump);
4019 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004020# endif
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004021 }
4022}
4023
4024/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00004025 * Set a console window to `xSize' * `ySize'
4026 */
4027 static void
4028ResizeConBufAndWindow(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004029 HANDLE hConsole,
4030 int xSize,
4031 int ySize)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004032{
Bram Moolenaar0f873732019-12-05 20:28:46 +01004033 CONSOLE_SCREEN_BUFFER_INFO csbi; // hold current console buffer info
4034 SMALL_RECT srWindowRect; // hold the new console size
Bram Moolenaar071d4272004-06-13 20:20:40 +00004035 COORD coordScreen;
Bram Moolenaarf49a6922019-07-15 20:37:05 +02004036 COORD cursor;
Bram Moolenaar2551c032018-08-23 22:38:31 +02004037 static int resized = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004038
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004039# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00004040 if (fdDump)
4041 {
4042 fprintf(fdDump, "ResizeConBufAndWindow(%d, %d)\n", xSize, ySize);
4043 fflush(fdDump);
4044 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004045# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004046
Bram Moolenaar0f873732019-12-05 20:28:46 +01004047 // get the largest size we can size the console window to
Bram Moolenaar071d4272004-06-13 20:20:40 +00004048 coordScreen = GetLargestConsoleWindowSize(hConsole);
4049
Bram Moolenaar0f873732019-12-05 20:28:46 +01004050 // define the new console window size and scroll position
Bram Moolenaar071d4272004-06-13 20:20:40 +00004051 srWindowRect.Left = srWindowRect.Top = (SHORT) 0;
4052 srWindowRect.Right = (SHORT) (min(xSize, coordScreen.X) - 1);
4053 srWindowRect.Bottom = (SHORT) (min(ySize, coordScreen.Y) - 1);
4054
4055 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
4056 {
4057 int sx, sy;
4058
4059 sx = csbi.srWindow.Right - csbi.srWindow.Left + 1;
4060 sy = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
4061 if (sy < ySize || sx < xSize)
4062 {
4063 /*
4064 * Increasing number of lines/columns, do buffer first.
4065 * Use the maximal size in x and y direction.
4066 */
4067 if (sy < ySize)
4068 coordScreen.Y = ySize;
4069 else
4070 coordScreen.Y = sy;
4071 if (sx < xSize)
4072 coordScreen.X = xSize;
4073 else
4074 coordScreen.X = sx;
4075 SetConsoleScreenBufferSize(hConsole, coordScreen);
4076 }
4077 }
4078
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004079 // define the new console buffer size
Bram Moolenaar071d4272004-06-13 20:20:40 +00004080 coordScreen.X = xSize;
4081 coordScreen.Y = ySize;
4082
Bram Moolenaar2551c032018-08-23 22:38:31 +02004083 // In the new console call API, only the first time in reverse order
4084 if (!vtp_working || resized)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004085 {
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004086 ResizeWindow(hConsole, srWindowRect);
4087 ResizeConBuf(hConsole, coordScreen);
4088 }
4089 else
4090 {
Bram Moolenaarf49a6922019-07-15 20:37:05 +02004091 // Workaround for a Windows 10 bug
4092 cursor.X = srWindowRect.Left;
4093 cursor.Y = srWindowRect.Top;
4094 SetConsoleCursorPosition(hConsole, cursor);
4095
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004096 ResizeConBuf(hConsole, coordScreen);
4097 ResizeWindow(hConsole, srWindowRect);
Bram Moolenaar2551c032018-08-23 22:38:31 +02004098 resized = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004099 }
4100}
4101
4102
4103/*
4104 * Set the console window to `Rows' * `Columns'
4105 */
4106 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004107mch_set_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004108{
4109 COORD coordScreen;
4110
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004111# ifdef VIMDLL
4112 if (gui.in_use)
4113 return;
4114# endif
Bram Moolenaar0f873732019-12-05 20:28:46 +01004115 // Don't change window size while still starting up
Bram Moolenaar071d4272004-06-13 20:20:40 +00004116 if (suppress_winsize != 0)
4117 {
4118 suppress_winsize = 2;
4119 return;
4120 }
4121
4122 if (term_console)
4123 {
4124 coordScreen = GetLargestConsoleWindowSize(g_hConOut);
4125
Bram Moolenaar0f873732019-12-05 20:28:46 +01004126 // Clamp Rows and Columns to reasonable values
Bram Moolenaar071d4272004-06-13 20:20:40 +00004127 if (Rows > coordScreen.Y)
4128 Rows = coordScreen.Y;
4129 if (Columns > coordScreen.X)
4130 Columns = coordScreen.X;
4131
4132 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
4133 }
4134}
4135
4136/*
4137 * Rows and/or Columns has changed.
4138 */
4139 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004140mch_new_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004141{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004142# ifdef VIMDLL
4143 if (gui.in_use)
4144 return;
4145# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004146 set_scroll_region(0, 0, Columns - 1, Rows - 1);
4147}
4148
4149
4150/*
4151 * Called when started up, to set the winsize that was delayed.
4152 */
4153 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004154mch_set_winsize_now(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004155{
4156 if (suppress_winsize == 2)
4157 {
4158 suppress_winsize = 0;
4159 mch_set_shellsize();
4160 shell_resized();
4161 }
4162 suppress_winsize = 0;
4163}
Bram Moolenaar0f873732019-12-05 20:28:46 +01004164#endif // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00004165
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004166 static BOOL
4167vim_create_process(
Bram Moolenaar36c85b22013-12-12 20:25:44 +01004168 char *cmd,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004169 BOOL inherit_handles,
Bram Moolenaar3f1138e2014-01-05 13:29:26 +01004170 DWORD flags,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004171 STARTUPINFO *si,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004172 PROCESS_INFORMATION *pi,
4173 LPVOID *env,
4174 char *cwd)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004175{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004176 BOOL ret = FALSE;
4177 WCHAR *wcmd, *wcwd = NULL;
4178
4179 wcmd = enc_to_utf16((char_u *)cmd, NULL);
4180 if (wcmd == NULL)
4181 return FALSE;
4182 if (cwd != NULL)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004183 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004184 wcwd = enc_to_utf16((char_u *)cwd, NULL);
4185 if (wcwd == NULL)
4186 goto theend;
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004187 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004188
4189 ret = CreateProcessW(
4190 NULL, // Executable name
4191 wcmd, // Command to execute
4192 NULL, // Process security attributes
4193 NULL, // Thread security attributes
4194 inherit_handles, // Inherit handles
4195 flags, // Creation flags
4196 env, // Environment
4197 wcwd, // Current directory
4198 (LPSTARTUPINFOW)si, // Startup information
4199 pi); // Process information
4200theend:
4201 vim_free(wcmd);
4202 vim_free(wcwd);
4203 return ret;
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004204}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004205
4206
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004207 static HINSTANCE
4208vim_shell_execute(
4209 char *cmd,
4210 INT n_show_cmd)
4211{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004212 HINSTANCE ret;
4213 WCHAR *wcmd;
4214
4215 wcmd = enc_to_utf16((char_u *)cmd, NULL);
4216 if (wcmd == NULL)
4217 return (HINSTANCE) 0;
4218
4219 ret = ShellExecuteW(NULL, NULL, wcmd, NULL, NULL, n_show_cmd);
4220 vim_free(wcmd);
4221 return ret;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004222}
4223
4224
Bram Moolenaar4f974752019-02-17 17:44:42 +01004225#if defined(FEAT_GUI_MSWIN) || defined(PROTO)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004226
4227/*
4228 * Specialised version of system() for Win32 GUI mode.
4229 * This version proceeds as follows:
4230 * 1. Create a console window for use by the subprocess
4231 * 2. Run the subprocess (it gets the allocated console by default)
4232 * 3. Wait for the subprocess to terminate and get its exit code
4233 * 4. Prompt the user to press a key to close the console window
4234 */
4235 static int
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004236mch_system_classic(char *cmd, int options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004237{
4238 STARTUPINFO si;
4239 PROCESS_INFORMATION pi;
4240 DWORD ret = 0;
4241 HWND hwnd = GetFocus();
4242
4243 si.cb = sizeof(si);
4244 si.lpReserved = NULL;
4245 si.lpDesktop = NULL;
4246 si.lpTitle = NULL;
4247 si.dwFlags = STARTF_USESHOWWINDOW;
4248 /*
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004249 * It's nicer to run a filter command in a minimized window.
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01004250 * Don't activate the window to keep focus on Vim.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004251 */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004252 if (options & SHELL_DOOUT)
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01004253 si.wShowWindow = SW_SHOWMINNOACTIVE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004254 else
4255 si.wShowWindow = SW_SHOWNORMAL;
4256 si.cbReserved2 = 0;
4257 si.lpReserved2 = NULL;
4258
Bram Moolenaar0f873732019-12-05 20:28:46 +01004259 // Now, run the command
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004260 vim_create_process(cmd, FALSE,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004261 CREATE_DEFAULT_ERROR_MODE | CREATE_NEW_CONSOLE,
4262 &si, &pi, NULL, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004263
Bram Moolenaar0f873732019-12-05 20:28:46 +01004264 // Wait for the command to terminate before continuing
Bram Moolenaar071d4272004-06-13 20:20:40 +00004265 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004266# ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00004267 int delay = 1;
4268
Bram Moolenaar0f873732019-12-05 20:28:46 +01004269 // Keep updating the window while waiting for the shell to finish.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004270 for (;;)
4271 {
4272 MSG msg;
4273
K.Takatab7057bd2022-01-21 11:37:07 +00004274 if (PeekMessageW(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004275 {
4276 TranslateMessage(&msg);
K.Takatab7057bd2022-01-21 11:37:07 +00004277 DispatchMessageW(&msg);
Bram Moolenaare4195c52012-08-02 12:31:44 +02004278 delay = 1;
4279 continue;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004280 }
4281 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
4282 break;
4283
Bram Moolenaar0f873732019-12-05 20:28:46 +01004284 // We start waiting for a very short time and then increase it, so
4285 // that we respond quickly when the process is quick, and don't
4286 // consume too much overhead when it's slow.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004287 if (delay < 50)
4288 delay += 10;
4289 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004290# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004291 WaitForSingleObject(pi.hProcess, INFINITE);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004292# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004293
Bram Moolenaar0f873732019-12-05 20:28:46 +01004294 // Get the command exit code
Bram Moolenaar071d4272004-06-13 20:20:40 +00004295 GetExitCodeProcess(pi.hProcess, &ret);
4296 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004297
Bram Moolenaar0f873732019-12-05 20:28:46 +01004298 // Close the handles to the subprocess, so that it goes away
Bram Moolenaar071d4272004-06-13 20:20:40 +00004299 CloseHandle(pi.hThread);
4300 CloseHandle(pi.hProcess);
4301
Bram Moolenaar0f873732019-12-05 20:28:46 +01004302 // Try to get input focus back. Doesn't always work though.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004303 PostMessage(hwnd, WM_SETFOCUS, 0, 0);
4304
4305 return ret;
4306}
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004307
4308/*
4309 * Thread launched by the gui to send the current buffer data to the
4310 * process. This way avoid to hang up vim totally if the children
4311 * process take a long time to process the lines.
4312 */
Bram Moolenaar4c38d662016-08-03 20:54:57 +02004313 static unsigned int __stdcall
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004314sub_process_writer(LPVOID param)
4315{
4316 HANDLE g_hChildStd_IN_Wr = param;
4317 linenr_T lnum = curbuf->b_op_start.lnum;
4318 DWORD len = 0;
4319 DWORD l;
4320 char_u *lp = ml_get(lnum);
4321 char_u *s;
4322 int written = 0;
4323
4324 for (;;)
4325 {
4326 l = (DWORD)STRLEN(lp + written);
4327 if (l == 0)
4328 len = 0;
4329 else if (lp[written] == NL)
4330 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004331 // NL -> NUL translation
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004332 WriteFile(g_hChildStd_IN_Wr, "", 1, &len, NULL);
4333 }
4334 else
4335 {
4336 s = vim_strchr(lp + written, NL);
4337 WriteFile(g_hChildStd_IN_Wr, (char *)lp + written,
4338 s == NULL ? l : (DWORD)(s - (lp + written)),
4339 &len, NULL);
4340 }
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +01004341 if (len == l)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004342 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004343 // Finished a line, add a NL, unless this line should not have
4344 // one.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004345 if (lnum != curbuf->b_op_end.lnum
Bram Moolenaar34d72d42015-07-17 14:18:08 +02004346 || (!curbuf->b_p_bin
4347 && curbuf->b_p_fixeol)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004348 || (lnum != curbuf->b_no_eol_lnum
4349 && (lnum != curbuf->b_ml.ml_line_count
4350 || curbuf->b_p_eol)))
4351 {
Bram Moolenaar42335f52018-09-13 15:33:43 +02004352 WriteFile(g_hChildStd_IN_Wr, "\n", 1,
4353 (LPDWORD)&vim_ignored, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004354 }
4355
4356 ++lnum;
4357 if (lnum > curbuf->b_op_end.lnum)
4358 break;
4359
4360 lp = ml_get(lnum);
4361 written = 0;
4362 }
4363 else if (len > 0)
4364 written += len;
4365 }
4366
Bram Moolenaar0f873732019-12-05 20:28:46 +01004367 // finished all the lines, close pipe
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004368 CloseHandle(g_hChildStd_IN_Wr);
Bram Moolenaar86f2cd52016-08-02 21:55:17 +02004369 return 0;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004370}
4371
4372
Bram Moolenaar0f873732019-12-05 20:28:46 +01004373# define BUFLEN 100 // length for buffer, stolen from unix version
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004374
4375/*
4376 * This function read from the children's stdout and write the
4377 * data on screen or in the buffer accordingly.
4378 */
4379 static void
4380dump_pipe(int options,
4381 HANDLE g_hChildStd_OUT_Rd,
4382 garray_T *ga,
4383 char_u buffer[],
4384 DWORD *buffer_off)
4385{
4386 DWORD availableBytes = 0;
4387 DWORD i;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004388 int ret;
4389 DWORD len;
4390 DWORD toRead;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004391
Bram Moolenaar0f873732019-12-05 20:28:46 +01004392 // we query the pipe to see if there is any data to read
4393 // to avoid to perform a blocking read
4394 ret = PeekNamedPipe(g_hChildStd_OUT_Rd, // pipe to query
4395 NULL, // optional buffer
4396 0, // buffer size
4397 NULL, // number of read bytes
4398 &availableBytes, // available bytes total
4399 NULL); // byteLeft
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004400
Bram Moolenaar0f873732019-12-05 20:28:46 +01004401 // We got real data in the pipe, read it
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02004402 while (ret != 0 && availableBytes > 0)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004403 {
Bram Moolenaara12a1612019-01-24 16:39:02 +01004404 toRead = (DWORD)(BUFLEN - *buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004405 toRead = availableBytes < toRead ? availableBytes : toRead;
Bram Moolenaara12a1612019-01-24 16:39:02 +01004406 ReadFile(g_hChildStd_OUT_Rd, buffer + *buffer_off, toRead , &len, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004407
Bram Moolenaar0f873732019-12-05 20:28:46 +01004408 // If we haven't read anything, there is a problem
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004409 if (len == 0)
4410 break;
4411
4412 availableBytes -= len;
4413
4414 if (options & SHELL_READ)
4415 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004416 // Do NUL -> NL translation, append NL separated
4417 // lines to the current buffer.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004418 for (i = 0; i < len; ++i)
4419 {
4420 if (buffer[i] == NL)
4421 append_ga_line(ga);
4422 else if (buffer[i] == NUL)
4423 ga_append(ga, NL);
4424 else
4425 ga_append(ga, buffer[i]);
4426 }
4427 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004428 else if (has_mbyte)
4429 {
4430 int l;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004431 int c;
4432 char_u *p;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004433
4434 len += *buffer_off;
4435 buffer[len] = NUL;
4436
Bram Moolenaar0f873732019-12-05 20:28:46 +01004437 // Check if the last character in buffer[] is
4438 // incomplete, keep these bytes for the next
4439 // round.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004440 for (p = buffer; p < buffer + len; p += l)
4441 {
Bram Moolenaard3c907b2016-08-17 21:32:09 +02004442 l = MB_CPTR2LEN(p);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004443 if (l == 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01004444 l = 1; // NUL byte?
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004445 else if (MB_BYTE2LEN(*p) != l)
4446 break;
4447 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01004448 if (p == buffer) // no complete character
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004449 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004450 // avoid getting stuck at an illegal byte
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004451 if (len >= 12)
4452 ++p;
4453 else
4454 {
4455 *buffer_off = len;
4456 return;
4457 }
4458 }
4459 c = *p;
4460 *p = NUL;
Bram Moolenaar32526b32019-01-19 17:43:09 +01004461 msg_puts((char *)buffer);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004462 if (p < buffer + len)
4463 {
4464 *p = c;
4465 *buffer_off = (DWORD)((buffer + len) - p);
4466 mch_memmove(buffer, p, *buffer_off);
4467 return;
4468 }
4469 *buffer_off = 0;
4470 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004471 else
4472 {
4473 buffer[len] = NUL;
Bram Moolenaar32526b32019-01-19 17:43:09 +01004474 msg_puts((char *)buffer);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004475 }
4476
4477 windgoto(msg_row, msg_col);
4478 cursor_on();
4479 out_flush();
4480 }
4481}
4482
4483/*
4484 * Version of system to use for windows NT > 5.0 (Win2K), use pipe
4485 * for communication and doesn't open any new window.
4486 */
4487 static int
4488mch_system_piped(char *cmd, int options)
4489{
4490 STARTUPINFO si;
4491 PROCESS_INFORMATION pi;
4492 DWORD ret = 0;
4493
4494 HANDLE g_hChildStd_IN_Rd = NULL;
4495 HANDLE g_hChildStd_IN_Wr = NULL;
4496 HANDLE g_hChildStd_OUT_Rd = NULL;
4497 HANDLE g_hChildStd_OUT_Wr = NULL;
4498
Bram Moolenaar0f873732019-12-05 20:28:46 +01004499 char_u buffer[BUFLEN + 1]; // reading buffer + size
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004500 DWORD len;
4501
Bram Moolenaar0f873732019-12-05 20:28:46 +01004502 // buffer used to receive keys
4503 char_u ta_buf[BUFLEN + 1]; // TypeAHead
4504 int ta_len = 0; // valid bytes in ta_buf[]
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004505
4506 DWORD i;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004507 int noread_cnt = 0;
4508 garray_T ga;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004509 int delay = 1;
Bram Moolenaar0f873732019-12-05 20:28:46 +01004510 DWORD buffer_off = 0; // valid bytes in buffer[]
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004511 char *p = NULL;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004512
4513 SECURITY_ATTRIBUTES saAttr;
4514
Bram Moolenaar0f873732019-12-05 20:28:46 +01004515 // Set the bInheritHandle flag so pipe handles are inherited.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004516 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
4517 saAttr.bInheritHandle = TRUE;
4518 saAttr.lpSecurityDescriptor = NULL;
4519
4520 if ( ! CreatePipe(&g_hChildStd_OUT_Rd, &g_hChildStd_OUT_Wr, &saAttr, 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01004521 // Ensure the read handle to the pipe for STDOUT is not inherited.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004522 || ! SetHandleInformation(g_hChildStd_OUT_Rd, HANDLE_FLAG_INHERIT, 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01004523 // Create a pipe for the child process's STDIN.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004524 || ! CreatePipe(&g_hChildStd_IN_Rd, &g_hChildStd_IN_Wr, &saAttr, 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01004525 // Ensure the write handle to the pipe for STDIN is not inherited.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004526 || ! SetHandleInformation(g_hChildStd_IN_Wr, HANDLE_FLAG_INHERIT, 0) )
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004527 {
4528 CloseHandle(g_hChildStd_IN_Rd);
4529 CloseHandle(g_hChildStd_IN_Wr);
4530 CloseHandle(g_hChildStd_OUT_Rd);
4531 CloseHandle(g_hChildStd_OUT_Wr);
Bram Moolenaar32526b32019-01-19 17:43:09 +01004532 msg_puts(_("\nCannot create pipes\n"));
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004533 }
4534
4535 si.cb = sizeof(si);
4536 si.lpReserved = NULL;
4537 si.lpDesktop = NULL;
4538 si.lpTitle = NULL;
4539 si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
4540
Bram Moolenaar0f873732019-12-05 20:28:46 +01004541 // set-up our file redirection
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004542 si.hStdError = g_hChildStd_OUT_Wr;
4543 si.hStdOutput = g_hChildStd_OUT_Wr;
4544 si.hStdInput = g_hChildStd_IN_Rd;
4545 si.wShowWindow = SW_HIDE;
4546 si.cbReserved2 = 0;
4547 si.lpReserved2 = NULL;
4548
4549 if (options & SHELL_READ)
4550 ga_init2(&ga, 1, BUFLEN);
4551
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004552 if (cmd != NULL)
4553 {
4554 p = (char *)vim_strsave((char_u *)cmd);
4555 if (p != NULL)
4556 unescape_shellxquote((char_u *)p, p_sxe);
4557 else
4558 p = cmd;
4559 }
4560
Bram Moolenaar0f873732019-12-05 20:28:46 +01004561 // Now, run the command.
4562 // About "Inherit handles" being TRUE: this command can be litigious,
4563 // handle inheritance was deactivated for pending temp file, but, if we
4564 // deactivate it, the pipes don't work for some reason.
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004565 vim_create_process(p, TRUE, CREATE_DEFAULT_ERROR_MODE,
4566 &si, &pi, NULL, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004567
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004568 if (p != cmd)
4569 vim_free(p);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004570
Bram Moolenaar0f873732019-12-05 20:28:46 +01004571 // Close our unused side of the pipes
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004572 CloseHandle(g_hChildStd_IN_Rd);
4573 CloseHandle(g_hChildStd_OUT_Wr);
4574
4575 if (options & SHELL_WRITE)
4576 {
Bram Moolenaar86f2cd52016-08-02 21:55:17 +02004577 HANDLE thread = (HANDLE)
Bram Moolenaar0f873732019-12-05 20:28:46 +01004578 _beginthreadex(NULL, // security attributes
4579 0, // default stack size
4580 sub_process_writer, // function to be executed
4581 g_hChildStd_IN_Wr, // parameter
4582 0, // creation flag, start immediately
4583 NULL); // we don't care about thread id
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004584 CloseHandle(thread);
4585 g_hChildStd_IN_Wr = NULL;
4586 }
4587
Bram Moolenaar0f873732019-12-05 20:28:46 +01004588 // Keep updating the window while waiting for the shell to finish.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004589 for (;;)
4590 {
4591 MSG msg;
4592
K.Takatab7057bd2022-01-21 11:37:07 +00004593 if (PeekMessageW(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004594 {
4595 TranslateMessage(&msg);
K.Takatab7057bd2022-01-21 11:37:07 +00004596 DispatchMessageW(&msg);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004597 }
4598
Bram Moolenaar0f873732019-12-05 20:28:46 +01004599 // write pipe information in the window
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004600 if ((options & (SHELL_READ|SHELL_WRITE))
4601# ifdef FEAT_GUI
4602 || gui.in_use
4603# endif
4604 )
4605 {
4606 len = 0;
4607 if (!(options & SHELL_EXPAND)
4608 && ((options &
4609 (SHELL_READ|SHELL_WRITE|SHELL_COOKED))
4610 != (SHELL_READ|SHELL_WRITE|SHELL_COOKED)
4611# ifdef FEAT_GUI
4612 || gui.in_use
4613# endif
4614 )
4615 && (ta_len > 0 || noread_cnt > 4))
4616 {
4617 if (ta_len == 0)
4618 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004619 // Get extra characters when we don't have any. Reset the
4620 // counter and timer.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004621 noread_cnt = 0;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004622 len = ui_inchar(ta_buf, BUFLEN, 10L, 0);
4623 }
4624 if (ta_len > 0 || len > 0)
4625 {
4626 /*
4627 * For pipes: Check for CTRL-C: send interrupt signal to
4628 * child. Check for CTRL-D: EOF, close pipe to child.
4629 */
4630 if (len == 1 && cmd != NULL)
4631 {
4632 if (ta_buf[ta_len] == Ctrl_C)
4633 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004634 // Learn what exit code is expected, for
4635 // now put 9 as SIGKILL
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004636 TerminateProcess(pi.hProcess, 9);
4637 }
4638 if (ta_buf[ta_len] == Ctrl_D)
4639 {
4640 CloseHandle(g_hChildStd_IN_Wr);
4641 g_hChildStd_IN_Wr = NULL;
4642 }
4643 }
4644
Bram Moolenaar2f7e1b82022-10-04 13:17:31 +01004645 len = term_replace_keycodes(ta_buf, ta_len, len);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004646
4647 /*
4648 * For pipes: echo the typed characters. For a pty this
4649 * does not seem to work.
4650 */
4651 for (i = ta_len; i < ta_len + len; ++i)
4652 {
4653 if (ta_buf[i] == '\n' || ta_buf[i] == '\b')
4654 msg_putchar(ta_buf[i]);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004655 else if (has_mbyte)
4656 {
4657 int l = (*mb_ptr2len)(ta_buf + i);
4658
4659 msg_outtrans_len(ta_buf + i, l);
4660 i += l - 1;
4661 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004662 else
4663 msg_outtrans_len(ta_buf + i, 1);
4664 }
4665 windgoto(msg_row, msg_col);
4666 out_flush();
4667
4668 ta_len += len;
4669
4670 /*
4671 * Write the characters to the child, unless EOF has been
4672 * typed for pipes. Write one character at a time, to
4673 * avoid losing too much typeahead. When writing buffer
4674 * lines, drop the typed characters (only check for
4675 * CTRL-C).
4676 */
4677 if (options & SHELL_WRITE)
4678 ta_len = 0;
4679 else if (g_hChildStd_IN_Wr != NULL)
4680 {
4681 WriteFile(g_hChildStd_IN_Wr, (char*)ta_buf,
4682 1, &len, NULL);
4683 // if we are typing in, we want to keep things reactive
4684 delay = 1;
4685 if (len > 0)
4686 {
4687 ta_len -= len;
4688 mch_memmove(ta_buf, ta_buf + len, ta_len);
4689 }
4690 }
4691 }
4692 }
4693 }
4694
4695 if (ta_len)
4696 ui_inchar_undo(ta_buf, ta_len);
4697
4698 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
4699 {
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004700 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004701 break;
4702 }
4703
4704 ++noread_cnt;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004705 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004706
Bram Moolenaar0f873732019-12-05 20:28:46 +01004707 // We start waiting for a very short time and then increase it, so
4708 // that we respond quickly when the process is quick, and don't
4709 // consume too much overhead when it's slow.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004710 if (delay < 50)
4711 delay += 10;
4712 }
4713
Bram Moolenaar0f873732019-12-05 20:28:46 +01004714 // Close the pipe
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004715 CloseHandle(g_hChildStd_OUT_Rd);
4716 if (g_hChildStd_IN_Wr != NULL)
4717 CloseHandle(g_hChildStd_IN_Wr);
4718
4719 WaitForSingleObject(pi.hProcess, INFINITE);
4720
Bram Moolenaar0f873732019-12-05 20:28:46 +01004721 // Get the command exit code
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004722 GetExitCodeProcess(pi.hProcess, &ret);
4723
4724 if (options & SHELL_READ)
4725 {
4726 if (ga.ga_len > 0)
4727 {
4728 append_ga_line(&ga);
Bram Moolenaar0f873732019-12-05 20:28:46 +01004729 // remember that the NL was missing
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004730 curbuf->b_no_eol_lnum = curwin->w_cursor.lnum;
4731 }
4732 else
4733 curbuf->b_no_eol_lnum = 0;
4734 ga_clear(&ga);
4735 }
4736
Bram Moolenaar0f873732019-12-05 20:28:46 +01004737 // Close the handles to the subprocess, so that it goes away
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004738 CloseHandle(pi.hThread);
4739 CloseHandle(pi.hProcess);
4740
4741 return ret;
4742}
4743
4744 static int
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004745mch_system_g(char *cmd, int options)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004746{
Bram Moolenaar0f873732019-12-05 20:28:46 +01004747 // if we can pipe and the shelltemp option is off
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004748 if (!p_stmp)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004749 return mch_system_piped(cmd, options);
4750 else
4751 return mch_system_classic(cmd, options);
4752}
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004753#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004754
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004755#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004756 static int
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02004757mch_system_c(char *cmd, int options UNUSED)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004758{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004759 int ret;
4760 WCHAR *wcmd;
Bram Moolenaar2efc44b2019-10-05 12:09:32 +02004761 char_u *buf;
4762 size_t len;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004763
Bram Moolenaar2efc44b2019-10-05 12:09:32 +02004764 // If the command starts and ends with double quotes, enclose the command
4765 // in parentheses.
4766 len = STRLEN(cmd);
4767 if (len >= 2 && cmd[0] == '"' && cmd[len - 1] == '"')
4768 {
4769 len += 3;
4770 buf = alloc(len);
4771 if (buf == NULL)
4772 return -1;
4773 vim_snprintf((char *)buf, len, "(%s)", cmd);
4774 wcmd = enc_to_utf16(buf, NULL);
4775 free(buf);
4776 }
4777 else
4778 wcmd = enc_to_utf16((char_u *)cmd, NULL);
4779
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004780 if (wcmd == NULL)
4781 return -1;
4782
4783 ret = _wsystem(wcmd);
4784 vim_free(wcmd);
4785 return ret;
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004786}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004787
4788#endif
4789
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004790 static int
4791mch_system(char *cmd, int options)
4792{
4793#ifdef VIMDLL
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02004794 if (gui.in_use || gui.starting)
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004795 return mch_system_g(cmd, options);
4796 else
4797 return mch_system_c(cmd, options);
4798#elif defined(FEAT_GUI_MSWIN)
4799 return mch_system_g(cmd, options);
4800#else
4801 return mch_system_c(cmd, options);
4802#endif
4803}
4804
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004805#if defined(FEAT_GUI) && defined(FEAT_TERMINAL)
4806/*
4807 * Use a terminal window to run a shell command in.
4808 */
4809 static int
4810mch_call_shell_terminal(
4811 char_u *cmd,
Bram Moolenaar0f873732019-12-05 20:28:46 +01004812 int options UNUSED) // SHELL_*, see vim.h
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004813{
4814 jobopt_T opt;
4815 char_u *newcmd = NULL;
4816 typval_T argvar[2];
4817 long_u cmdlen;
4818 int retval = -1;
4819 buf_T *buf;
Bram Moolenaarf9c38832018-06-19 19:59:20 +02004820 job_T *job;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004821 aco_save_T aco;
Bram Moolenaar0f873732019-12-05 20:28:46 +01004822 oparg_T oa; // operator arguments
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004823
Bram Moolenaar42f652f2018-03-19 21:44:37 +01004824 if (cmd == NULL)
4825 cmdlen = STRLEN(p_sh) + 1;
4826 else
4827 cmdlen = STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10;
Bram Moolenaar18a4ba22019-05-24 19:39:03 +02004828 newcmd = alloc(cmdlen);
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004829 if (newcmd == NULL)
4830 return 255;
Bram Moolenaar42f652f2018-03-19 21:44:37 +01004831 if (cmd == NULL)
4832 {
4833 STRCPY(newcmd, p_sh);
4834 ch_log(NULL, "starting terminal to run a shell");
4835 }
4836 else
4837 {
4838 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s", p_sh, p_shcf, cmd);
4839 ch_log(NULL, "starting terminal for system command '%s'", cmd);
4840 }
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004841
4842 init_job_options(&opt);
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004843
4844 argvar[0].v_type = VAR_STRING;
4845 argvar[0].vval.v_string = newcmd;
4846 argvar[1].v_type = VAR_UNKNOWN;
4847 buf = term_start(argvar, NULL, &opt, TERM_START_SYSTEM);
Bram Moolenaar81c3c89a2018-03-20 11:41:44 +01004848 if (buf == NULL)
Bram Moolenaar9029b912019-03-21 19:58:00 +01004849 {
4850 vim_free(newcmd);
Bram Moolenaar81c3c89a2018-03-20 11:41:44 +01004851 return 255;
Bram Moolenaar9029b912019-03-21 19:58:00 +01004852 }
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004853
Bram Moolenaarf9c38832018-06-19 19:59:20 +02004854 job = term_getjob(buf->b_term);
4855 ++job->jv_refcount;
4856
Bram Moolenaar0f873732019-12-05 20:28:46 +01004857 // Find a window to make "buf" curbuf.
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004858 aucmd_prepbuf(&aco, buf);
4859
4860 clear_oparg(&oa);
4861 while (term_use_loop())
4862 {
4863 if (oa.op_type == OP_NOP && oa.regname == NUL && !VIsual_active)
4864 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004865 // If terminal_loop() returns OK we got a key that is handled
4866 // in Normal model. We don't do redrawing anyway.
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004867 if (terminal_loop(TRUE) == OK)
4868 normal_cmd(&oa, TRUE);
4869 }
4870 else
4871 normal_cmd(&oa, TRUE);
4872 }
Bram Moolenaarf9c38832018-06-19 19:59:20 +02004873 retval = job->jv_exitval;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004874 ch_log(NULL, "system command finished");
4875
Bram Moolenaarf9c38832018-06-19 19:59:20 +02004876 job_unref(job);
4877
Bram Moolenaar0f873732019-12-05 20:28:46 +01004878 // restore curwin/curbuf and a few other things
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004879 aucmd_restbuf(&aco);
4880
4881 wait_return(TRUE);
4882 do_buffer(DOBUF_WIPE, DOBUF_FIRST, FORWARD, buf->b_fnum, TRUE);
4883
4884 vim_free(newcmd);
4885 return retval;
4886}
4887#endif
4888
Bram Moolenaar071d4272004-06-13 20:20:40 +00004889/*
4890 * Either execute a command by calling the shell or start a new shell
4891 */
4892 int
4893mch_call_shell(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004894 char_u *cmd,
Bram Moolenaar0f873732019-12-05 20:28:46 +01004895 int options) // SHELL_*, see vim.h
Bram Moolenaar071d4272004-06-13 20:20:40 +00004896{
4897 int x = 0;
4898 int tmode = cur_tmode;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004899 WCHAR szShellTitle[512];
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004900
Bram Moolenaarc9a9a0a2022-04-12 15:09:23 +01004901#ifdef FEAT_JOB_CHANNEL
4902 ch_log(NULL, "executing shell command: %s", cmd);
4903#endif
Bram Moolenaar0f873732019-12-05 20:28:46 +01004904 // Change the title to reflect that we are in a subshell.
K.Takataeeec2542021-06-02 13:28:16 +02004905 if (GetConsoleTitleW(szShellTitle, ARRAY_LENGTH(szShellTitle) - 4) > 0)
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004906 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004907 if (cmd == NULL)
4908 wcscat(szShellTitle, L" :sh");
4909 else
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004910 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004911 WCHAR *wn = enc_to_utf16((char_u *)cmd, NULL);
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004912
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004913 if (wn != NULL)
4914 {
4915 wcscat(szShellTitle, L" - !");
4916 if ((wcslen(szShellTitle) + wcslen(wn) <
K.Takataeeec2542021-06-02 13:28:16 +02004917 ARRAY_LENGTH(szShellTitle)))
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004918 wcscat(szShellTitle, wn);
4919 SetConsoleTitleW(szShellTitle);
4920 vim_free(wn);
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004921 }
4922 }
4923 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004924
4925 out_flush();
4926
4927#ifdef MCH_WRITE_DUMP
4928 if (fdDump)
4929 {
4930 fprintf(fdDump, "mch_call_shell(\"%s\", %d)\n", cmd, options);
4931 fflush(fdDump);
4932 }
4933#endif
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004934#if defined(FEAT_GUI) && defined(FEAT_TERMINAL)
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004935 // TODO: make the terminal window work with input or output redirected.
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004936 if (
4937# ifdef VIMDLL
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004938 gui.in_use &&
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004939# endif
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004940 vim_strchr(p_go, GO_TERMINAL) != NULL
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004941 && (options & (SHELL_FILTER|SHELL_DOOUT|SHELL_WRITE|SHELL_READ)) == 0)
4942 {
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004943 char_u *cmdbase = cmd;
4944
Bram Moolenaar4d5c1262019-09-20 17:20:02 +02004945 if (cmdbase != NULL)
4946 // Skip a leading quote and (.
4947 while (*cmdbase == '"' || *cmdbase == '(')
4948 ++cmdbase;
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004949
4950 // Check the command does not begin with "start "
Bram Moolenaar36e7a822019-11-13 21:49:24 +01004951 if (cmdbase == NULL || STRNICMP(cmdbase, "start", 5) != 0
4952 || !VIM_ISWHITE(cmdbase[5]))
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004953 {
4954 // Use a terminal window to run the command in.
4955 x = mch_call_shell_terminal(cmd, options);
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004956 resettitle();
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004957 return x;
4958 }
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004959 }
4960#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004961
4962 /*
4963 * Catch all deadly signals while running the external command, because a
4964 * CTRL-C, Ctrl-Break or illegal instruction might otherwise kill us.
4965 */
4966 signal(SIGINT, SIG_IGN);
4967#if defined(__GNUC__) && !defined(__MINGW32__)
4968 signal(SIGKILL, SIG_IGN);
4969#else
4970 signal(SIGBREAK, SIG_IGN);
4971#endif
4972 signal(SIGILL, SIG_IGN);
4973 signal(SIGFPE, SIG_IGN);
4974 signal(SIGSEGV, SIG_IGN);
4975 signal(SIGTERM, SIG_IGN);
4976 signal(SIGABRT, SIG_IGN);
4977
4978 if (options & SHELL_COOKED)
Bram Moolenaar0f873732019-12-05 20:28:46 +01004979 settmode(TMODE_COOK); // set to normal mode
Bram Moolenaar071d4272004-06-13 20:20:40 +00004980
4981 if (cmd == NULL)
4982 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004983 x = mch_system((char *)p_sh, options);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004984 }
4985 else
4986 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004987 // we use "command" or "cmd" to start the shell; slow but easy
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004988 char_u *newcmd = NULL;
4989 char_u *cmdbase = cmd;
4990 long_u cmdlen;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004991
Bram Moolenaar0f873732019-12-05 20:28:46 +01004992 // Skip a leading ", ( and "(.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004993 if (*cmdbase == '"' )
4994 ++cmdbase;
4995 if (*cmdbase == '(')
4996 ++cmdbase;
4997
Bram Moolenaar1c465442017-03-12 20:10:05 +01004998 if ((STRNICMP(cmdbase, "start", 5) == 0) && VIM_ISWHITE(cmdbase[5]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004999 {
5000 STARTUPINFO si;
5001 PROCESS_INFORMATION pi;
5002 DWORD flags = CREATE_NEW_CONSOLE;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01005003 INT n_show_cmd = SW_SHOWNORMAL;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005004 char_u *p;
5005
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01005006 ZeroMemory(&si, sizeof(si));
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005007 si.cb = sizeof(si);
5008 si.lpReserved = NULL;
5009 si.lpDesktop = NULL;
5010 si.lpTitle = NULL;
5011 si.dwFlags = 0;
5012 si.cbReserved2 = 0;
5013 si.lpReserved2 = NULL;
5014
5015 cmdbase = skipwhite(cmdbase + 5);
5016 if ((STRNICMP(cmdbase, "/min", 4) == 0)
Bram Moolenaar1c465442017-03-12 20:10:05 +01005017 && VIM_ISWHITE(cmdbase[4]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005018 {
5019 cmdbase = skipwhite(cmdbase + 4);
5020 si.dwFlags = STARTF_USESHOWWINDOW;
5021 si.wShowWindow = SW_SHOWMINNOACTIVE;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01005022 n_show_cmd = SW_SHOWMINNOACTIVE;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005023 }
5024 else if ((STRNICMP(cmdbase, "/b", 2) == 0)
Bram Moolenaar1c465442017-03-12 20:10:05 +01005025 && VIM_ISWHITE(cmdbase[2]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005026 {
5027 cmdbase = skipwhite(cmdbase + 2);
5028 flags = CREATE_NO_WINDOW;
5029 si.dwFlags = STARTF_USESTDHANDLES;
5030 si.hStdInput = CreateFile("\\\\.\\NUL", // File name
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005031 GENERIC_READ, // Access flags
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005032 0, // Share flags
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005033 NULL, // Security att.
5034 OPEN_EXISTING, // Open flags
5035 FILE_ATTRIBUTE_NORMAL, // File att.
5036 NULL); // Temp file
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005037 si.hStdOutput = si.hStdInput;
5038 si.hStdError = si.hStdInput;
5039 }
5040
Bram Moolenaar0f873732019-12-05 20:28:46 +01005041 // Remove a trailing ", ) and )" if they have a match
5042 // at the start of the command.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005043 if (cmdbase > cmd)
5044 {
5045 p = cmdbase + STRLEN(cmdbase);
5046 if (p > cmdbase && p[-1] == '"' && *cmd == '"')
5047 *--p = NUL;
5048 if (p > cmdbase && p[-1] == ')'
5049 && (*cmd =='(' || cmd[1] == '('))
5050 *--p = NUL;
5051 }
5052
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005053 newcmd = cmdbase;
5054 unescape_shellxquote(cmdbase, p_sxe);
5055
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005056 /*
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005057 * If creating new console, arguments are passed to the
5058 * 'cmd.exe' as-is. If it's not, arguments are not treated
5059 * correctly for current 'cmd.exe'. So unescape characters in
5060 * shellxescape except '|' for avoiding to be treated as
5061 * argument to them. Pass the arguments to sub-shell.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005062 */
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005063 if (flags != CREATE_NEW_CONSOLE)
5064 {
5065 char_u *subcmd;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01005066 char_u *cmd_shell = mch_getenv("COMSPEC");
5067
5068 if (cmd_shell == NULL || *cmd_shell == NUL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01005069 cmd_shell = (char_u *)default_shell();
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005070
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01005071 subcmd = vim_strsave_escaped_ext(cmdbase,
5072 (char_u *)"|", '^', FALSE);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005073 if (subcmd != NULL)
5074 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005075 // make "cmd.exe /c arguments"
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005076 cmdlen = STRLEN(cmd_shell) + STRLEN(subcmd) + 5;
Bram Moolenaar18a4ba22019-05-24 19:39:03 +02005077 newcmd = alloc(cmdlen);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005078 if (newcmd != NULL)
5079 vim_snprintf((char *)newcmd, cmdlen, "%s /c %s",
Bram Moolenaaree7d1002012-02-22 15:34:08 +01005080 cmd_shell, subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005081 else
5082 newcmd = cmdbase;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01005083 vim_free(subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005084 }
5085 }
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005086
5087 /*
5088 * Now, start the command as a process, so that it doesn't
5089 * inherit our handles which causes unpleasant dangling swap
5090 * files if we exit before the spawned process
5091 */
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005092 if (vim_create_process((char *)newcmd, FALSE, flags,
5093 &si, &pi, NULL, NULL))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005094 x = 0;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01005095 else if (vim_shell_execute((char *)newcmd, n_show_cmd)
5096 > (HINSTANCE)32)
5097 x = 0;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005098 else
5099 {
5100 x = -1;
Bram Moolenaar4f974752019-02-17 17:44:42 +01005101#ifdef FEAT_GUI_MSWIN
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005102# ifdef VIMDLL
5103 if (gui.in_use)
5104# endif
Bram Moolenaarac78dd42022-01-02 19:25:26 +00005105 emsg(_(e_command_not_found));
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005106#endif
5107 }
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005108
5109 if (newcmd != cmdbase)
5110 vim_free(newcmd);
5111
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01005112 if (si.dwFlags == STARTF_USESTDHANDLES && si.hStdInput != NULL)
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005113 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005114 // Close the handle to \\.\NUL created above.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005115 CloseHandle(si.hStdInput);
5116 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01005117 // Close the handles to the subprocess, so that it goes away
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005118 CloseHandle(pi.hThread);
5119 CloseHandle(pi.hProcess);
5120 }
5121 else
5122 {
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005123 cmdlen =
Bram Moolenaar4f974752019-02-17 17:44:42 +01005124#ifdef FEAT_GUI_MSWIN
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02005125 ((gui.in_use || gui.starting) ?
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005126 (!s_dont_use_vimrun && p_stmp ?
5127 STRLEN(vimrun_path) : STRLEN(p_sh) + STRLEN(p_shcf))
5128 : 0) +
Bram Moolenaar071d4272004-06-13 20:20:40 +00005129#endif
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005130 STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10;
Bram Moolenaar0fde2902008-03-16 13:54:13 +00005131
Bram Moolenaar18a4ba22019-05-24 19:39:03 +02005132 newcmd = alloc(cmdlen);
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005133 if (newcmd != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005134 {
Bram Moolenaar4f974752019-02-17 17:44:42 +01005135#if defined(FEAT_GUI_MSWIN)
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005136 if (
5137# ifdef VIMDLL
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02005138 (gui.in_use || gui.starting) &&
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005139# endif
5140 need_vimrun_warning)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005141 {
Bram Moolenaar63e43442016-11-19 17:28:44 +01005142 char *msg = _("VIMRUN.EXE not found in your $PATH.\n"
5143 "External commands will not pause after completion.\n"
5144 "See :help win32-vimrun for more information.");
5145 char *title = _("Vim Warning");
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005146 WCHAR *wmsg = enc_to_utf16((char_u *)msg, NULL);
5147 WCHAR *wtitle = enc_to_utf16((char_u *)title, NULL);
Bram Moolenaar63e43442016-11-19 17:28:44 +01005148
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005149 if (wmsg != NULL && wtitle != NULL)
5150 MessageBoxW(NULL, wmsg, wtitle, MB_ICONWARNING);
5151 vim_free(wmsg);
5152 vim_free(wtitle);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005153 need_vimrun_warning = FALSE;
5154 }
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005155 if (
5156# ifdef VIMDLL
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02005157 (gui.in_use || gui.starting) &&
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005158# endif
5159 !s_dont_use_vimrun && p_stmp)
Bram Moolenaarfcc4d922019-05-24 13:32:36 +02005160 // Use vimrun to execute the command. It opens a console
5161 // window, which can be closed without killing Vim.
Bram Moolenaarcc448b32010-07-14 16:52:17 +02005162 vim_snprintf((char *)newcmd, cmdlen, "%s%s%s %s %s",
Bram Moolenaar071d4272004-06-13 20:20:40 +00005163 vimrun_path,
5164 (msg_silent != 0 || (options & SHELL_DOOUT))
5165 ? "-s " : "",
5166 p_sh, p_shcf, cmd);
Bram Moolenaarfcc4d922019-05-24 13:32:36 +02005167 else if (
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005168# ifdef VIMDLL
Bram Moolenaarfcc4d922019-05-24 13:32:36 +02005169 (gui.in_use || gui.starting) &&
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005170# endif
Bram Moolenaar0e6bfb92019-07-31 20:53:56 +02005171 s_dont_use_vimrun && STRCMP(p_shcf, "/c") == 0)
Bram Moolenaarfcc4d922019-05-24 13:32:36 +02005172 // workaround for the case that "vimrun" does not exist
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005173 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s %s %s",
5174 p_sh, p_shcf, p_sh, p_shcf, cmd);
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005175 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00005176#endif
Bram Moolenaarcc448b32010-07-14 16:52:17 +02005177 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s",
Bram Moolenaar0fde2902008-03-16 13:54:13 +00005178 p_sh, p_shcf, cmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005179 x = mch_system((char *)newcmd, options);
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005180 vim_free(newcmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005181 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005182 }
5183 }
5184
5185 if (tmode == TMODE_RAW)
Bram Moolenaar3b1f18f2020-05-16 23:15:08 +02005186 {
5187 // The shell may have messed with the mode, always set it.
5188 cur_tmode = TMODE_UNKNOWN;
Bram Moolenaar0f873732019-12-05 20:28:46 +01005189 settmode(TMODE_RAW); // set to raw mode
Bram Moolenaar3b1f18f2020-05-16 23:15:08 +02005190 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005191
Bram Moolenaar0f873732019-12-05 20:28:46 +01005192 // Print the return value, unless "vimrun" was used.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005193 if (x != 0 && !(options & SHELL_SILENT) && !emsg_silent
Bram Moolenaar4f974752019-02-17 17:44:42 +01005194#if defined(FEAT_GUI_MSWIN)
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02005195 && ((gui.in_use || gui.starting) ?
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005196 ((options & SHELL_DOOUT) || s_dont_use_vimrun || !p_stmp) : 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005197#endif
5198 )
5199 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005200 smsg(_("shell returned %d"), x);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005201 msg_putchar('\n');
5202 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005203 resettitle();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005204
5205 signal(SIGINT, SIG_DFL);
5206#if defined(__GNUC__) && !defined(__MINGW32__)
5207 signal(SIGKILL, SIG_DFL);
5208#else
5209 signal(SIGBREAK, SIG_DFL);
5210#endif
5211 signal(SIGILL, SIG_DFL);
5212 signal(SIGFPE, SIG_DFL);
5213 signal(SIGSEGV, SIG_DFL);
5214 signal(SIGTERM, SIG_DFL);
5215 signal(SIGABRT, SIG_DFL);
5216
5217 return x;
5218}
5219
Bram Moolenaar509ce2a2016-03-11 22:52:15 +01005220#if defined(FEAT_JOB_CHANNEL) || defined(PROTO)
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005221 static HANDLE
5222job_io_file_open(
Bram Moolenaar972c3b82017-01-12 21:44:49 +01005223 char_u *fname,
5224 DWORD dwDesiredAccess,
5225 DWORD dwShareMode,
5226 LPSECURITY_ATTRIBUTES lpSecurityAttributes,
5227 DWORD dwCreationDisposition,
5228 DWORD dwFlagsAndAttributes)
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005229{
5230 HANDLE h;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005231 WCHAR *wn;
Bram Moolenaara12a1612019-01-24 16:39:02 +01005232
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005233 wn = enc_to_utf16(fname, NULL);
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005234 if (wn == NULL)
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005235 return INVALID_HANDLE_VALUE;
5236
5237 h = CreateFileW(wn, dwDesiredAccess, dwShareMode,
5238 lpSecurityAttributes, dwCreationDisposition,
5239 dwFlagsAndAttributes, NULL);
5240 vim_free(wn);
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005241 return h;
5242}
5243
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005244/*
5245 * Turn the dictionary "env" into a NUL separated list that can be used as the
5246 * environment argument of vim_create_process().
5247 */
Bram Moolenaarba6febd2017-10-30 21:56:23 +01005248 void
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005249win32_build_env(dict_T *env, garray_T *gap, int is_terminal)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005250{
5251 hashitem_T *hi;
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005252 long_u todo = env != NULL ? env->dv_hashtab.ht_used : 0;
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005253 LPVOID base = GetEnvironmentStringsW();
5254
Bram Moolenaar0f873732019-12-05 20:28:46 +01005255 // for last \0
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005256 if (ga_grow(gap, 1) == FAIL)
5257 return;
5258
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005259 if (env != NULL)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005260 {
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005261 for (hi = env->dv_hashtab.ht_array; todo > 0; ++hi)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005262 {
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005263 if (!HASHITEM_EMPTY(hi))
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005264 {
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005265 typval_T *item = &dict_lookup(hi)->di_tv;
5266 WCHAR *wkey = enc_to_utf16((char_u *)hi->hi_key, NULL);
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005267 WCHAR *wval = enc_to_utf16(tv_get_string(item), NULL);
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005268 --todo;
5269 if (wkey != NULL && wval != NULL)
5270 {
5271 size_t n;
5272 size_t lkey = wcslen(wkey);
5273 size_t lval = wcslen(wval);
Bram Moolenaar60104f12017-08-14 23:25:04 +02005274
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005275 if (ga_grow(gap, (int)(lkey + lval + 2)) != OK)
5276 continue;
5277 for (n = 0; n < lkey; n++)
5278 *((WCHAR*)gap->ga_data + gap->ga_len++) = wkey[n];
5279 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'=';
5280 for (n = 0; n < lval; n++)
5281 *((WCHAR*)gap->ga_data + gap->ga_len++) = wval[n];
5282 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5283 }
Bram Moolenaarbdace832019-03-02 10:13:42 +01005284 vim_free(wkey);
5285 vim_free(wval);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005286 }
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005287 }
5288 }
5289
Bram Moolenaar355757a2020-02-10 22:06:32 +01005290 if (base)
5291 {
5292 WCHAR *p = (WCHAR*) base;
5293
5294 // for last \0
5295 if (ga_grow(gap, 1) == FAIL)
5296 return;
5297
5298 while (*p != 0 || *(p + 1) != 0)
5299 {
5300 if (ga_grow(gap, 1) == OK)
5301 *((WCHAR*)gap->ga_data + gap->ga_len++) = *p;
5302 p++;
5303 }
5304 FreeEnvironmentStrings(base);
5305 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5306 }
5307
Bram Moolenaar493359e2018-06-12 20:25:52 +02005308# if defined(FEAT_CLIENTSERVER) || defined(FEAT_TERMINAL)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005309 {
Bram Moolenaar493359e2018-06-12 20:25:52 +02005310# ifdef FEAT_CLIENTSERVER
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005311 char_u *servername = get_vim_var_str(VV_SEND_SERVER);
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005312 size_t servername_len = STRLEN(servername);
Bram Moolenaar493359e2018-06-12 20:25:52 +02005313# endif
5314# ifdef FEAT_TERMINAL
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005315 char_u *version = get_vim_var_str(VV_VERSION);
5316 size_t version_len = STRLEN(version);
Bram Moolenaar493359e2018-06-12 20:25:52 +02005317# endif
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005318 // size of "VIM_SERVERNAME=" and value,
5319 // plus "VIM_TERMINAL=" and value,
5320 // plus two terminating NULs
5321 size_t n = 0
Bram Moolenaar493359e2018-06-12 20:25:52 +02005322# ifdef FEAT_CLIENTSERVER
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005323 + 15 + servername_len
Bram Moolenaar493359e2018-06-12 20:25:52 +02005324# endif
5325# ifdef FEAT_TERMINAL
5326 + 13 + version_len + 2
5327# endif
5328 ;
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005329
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005330 if (ga_grow(gap, (int)n) == OK)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005331 {
Bram Moolenaar493359e2018-06-12 20:25:52 +02005332# ifdef FEAT_CLIENTSERVER
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005333 for (n = 0; n < 15; n++)
5334 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5335 (WCHAR)"VIM_SERVERNAME="[n];
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005336 for (n = 0; n < servername_len; n++)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005337 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5338 (WCHAR)servername[n];
5339 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
Bram Moolenaar493359e2018-06-12 20:25:52 +02005340# endif
5341# ifdef FEAT_TERMINAL
5342 if (is_terminal)
5343 {
5344 for (n = 0; n < 13; n++)
5345 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5346 (WCHAR)"VIM_TERMINAL="[n];
5347 for (n = 0; n < version_len; n++)
5348 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5349 (WCHAR)version[n];
5350 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5351 }
5352# endif
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005353 }
5354 }
Bram Moolenaar79c6b512018-06-12 21:11:12 +02005355# endif
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005356}
5357
Bram Moolenaarb091f302019-01-19 14:37:00 +01005358/*
5359 * Create a pair of pipes.
5360 * Return TRUE for success, FALSE for failure.
5361 */
5362 static BOOL
5363create_pipe_pair(HANDLE handles[2])
5364{
5365 static LONG s;
5366 char name[64];
5367 SECURITY_ATTRIBUTES sa;
5368
5369 sprintf(name, "\\\\?\\pipe\\vim-%08lx-%08lx",
5370 GetCurrentProcessId(),
5371 InterlockedIncrement(&s));
5372
5373 // Create named pipe. Max size of named pipe is 65535.
5374 handles[1] = CreateNamedPipe(
5375 name,
5376 PIPE_ACCESS_OUTBOUND | FILE_FLAG_OVERLAPPED,
5377 PIPE_TYPE_BYTE | PIPE_NOWAIT,
Bram Moolenaar24058382019-01-24 23:11:49 +01005378 1, MAX_NAMED_PIPE_SIZE, 0, 0, NULL);
Bram Moolenaarb091f302019-01-19 14:37:00 +01005379
5380 if (handles[1] == INVALID_HANDLE_VALUE)
5381 return FALSE;
5382
5383 sa.nLength = sizeof(sa);
5384 sa.bInheritHandle = TRUE;
5385 sa.lpSecurityDescriptor = NULL;
5386
5387 handles[0] = CreateFile(name,
5388 FILE_GENERIC_READ,
5389 FILE_SHARE_READ, &sa,
5390 OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
5391
5392 if (handles[0] == INVALID_HANDLE_VALUE)
5393 {
Bram Moolenaar6982f422019-02-16 16:48:01 +01005394 CloseHandle(handles[1]);
Bram Moolenaarb091f302019-01-19 14:37:00 +01005395 return FALSE;
5396 }
5397
5398 return TRUE;
5399}
5400
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005401 void
Bram Moolenaar5a1feb82017-07-22 18:04:08 +02005402mch_job_start(char *cmd, job_T *job, jobopt_T *options)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005403{
5404 STARTUPINFO si;
5405 PROCESS_INFORMATION pi;
Bram Moolenaar14207f42016-10-27 21:13:10 +02005406 HANDLE jo;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005407 SECURITY_ATTRIBUTES saAttr;
5408 channel_T *channel = NULL;
Bram Moolenaard8070362016-02-15 21:56:54 +01005409 HANDLE ifd[2];
5410 HANDLE ofd[2];
5411 HANDLE efd[2];
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005412 garray_T ga;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005413
5414 int use_null_for_in = options->jo_io[PART_IN] == JIO_NULL;
5415 int use_null_for_out = options->jo_io[PART_OUT] == JIO_NULL;
5416 int use_null_for_err = options->jo_io[PART_ERR] == JIO_NULL;
5417 int use_file_for_in = options->jo_io[PART_IN] == JIO_FILE;
5418 int use_file_for_out = options->jo_io[PART_OUT] == JIO_FILE;
5419 int use_file_for_err = options->jo_io[PART_ERR] == JIO_FILE;
5420 int use_out_for_err = options->jo_io[PART_ERR] == JIO_OUT;
5421
5422 if (use_out_for_err && use_null_for_out)
5423 use_null_for_err = TRUE;
Bram Moolenaard8070362016-02-15 21:56:54 +01005424
5425 ifd[0] = INVALID_HANDLE_VALUE;
5426 ifd[1] = INVALID_HANDLE_VALUE;
5427 ofd[0] = INVALID_HANDLE_VALUE;
5428 ofd[1] = INVALID_HANDLE_VALUE;
5429 efd[0] = INVALID_HANDLE_VALUE;
5430 efd[1] = INVALID_HANDLE_VALUE;
Bram Moolenaar04935fb2022-01-08 16:19:22 +00005431 ga_init2(&ga, sizeof(wchar_t), 500);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005432
Bram Moolenaar14207f42016-10-27 21:13:10 +02005433 jo = CreateJobObject(NULL, NULL);
5434 if (jo == NULL)
5435 {
5436 job->jv_status = JOB_FAILED;
5437 goto failed;
5438 }
5439
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005440 if (options->jo_env != NULL)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005441 win32_build_env(options->jo_env, &ga, FALSE);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005442
Bram Moolenaar76467df2016-02-12 19:30:26 +01005443 ZeroMemory(&pi, sizeof(pi));
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005444 ZeroMemory(&si, sizeof(si));
5445 si.cb = sizeof(si);
Bram Moolenaard8070362016-02-15 21:56:54 +01005446 si.dwFlags |= STARTF_USESHOWWINDOW;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005447 si.wShowWindow = SW_HIDE;
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005448
Bram Moolenaard8070362016-02-15 21:56:54 +01005449 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
5450 saAttr.bInheritHandle = TRUE;
5451 saAttr.lpSecurityDescriptor = NULL;
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005452
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005453 if (use_file_for_in)
5454 {
5455 char_u *fname = options->jo_io_name[PART_IN];
5456
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005457 ifd[0] = job_io_file_open(fname, GENERIC_READ,
5458 FILE_SHARE_READ | FILE_SHARE_WRITE,
5459 &saAttr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL);
5460 if (ifd[0] == INVALID_HANDLE_VALUE)
Bram Moolenaar94d01912016-03-08 13:48:51 +01005461 {
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00005462 semsg(_(e_cant_open_file_str), fname);
Bram Moolenaar94d01912016-03-08 13:48:51 +01005463 goto failed;
5464 }
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005465 }
Bram Moolenaarb091f302019-01-19 14:37:00 +01005466 else if (!use_null_for_in
5467 && (!create_pipe_pair(ifd)
5468 || !SetHandleInformation(ifd[1], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005469 goto failed;
5470
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005471 if (use_file_for_out)
5472 {
5473 char_u *fname = options->jo_io_name[PART_OUT];
5474
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005475 ofd[1] = job_io_file_open(fname, GENERIC_WRITE,
5476 FILE_SHARE_READ | FILE_SHARE_WRITE,
5477 &saAttr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL);
5478 if (ofd[1] == INVALID_HANDLE_VALUE)
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005479 {
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00005480 semsg(_(e_cant_open_file_str), fname);
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005481 goto failed;
5482 }
5483 }
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005484 else if (!use_null_for_out &&
5485 (!CreatePipe(&ofd[0], &ofd[1], &saAttr, 0)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005486 || !SetHandleInformation(ofd[0], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005487 goto failed;
5488
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005489 if (use_file_for_err)
5490 {
5491 char_u *fname = options->jo_io_name[PART_ERR];
5492
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005493 efd[1] = job_io_file_open(fname, GENERIC_WRITE,
5494 FILE_SHARE_READ | FILE_SHARE_WRITE,
5495 &saAttr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL);
5496 if (efd[1] == INVALID_HANDLE_VALUE)
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005497 {
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00005498 semsg(_(e_cant_open_file_str), fname);
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005499 goto failed;
5500 }
5501 }
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005502 else if (!use_out_for_err && !use_null_for_err &&
5503 (!CreatePipe(&efd[0], &efd[1], &saAttr, 0)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005504 || !SetHandleInformation(efd[0], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaard8070362016-02-15 21:56:54 +01005505 goto failed;
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005506
Bram Moolenaard8070362016-02-15 21:56:54 +01005507 si.dwFlags |= STARTF_USESTDHANDLES;
5508 si.hStdInput = ifd[0];
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005509 si.hStdOutput = ofd[1];
5510 si.hStdError = use_out_for_err ? ofd[1] : efd[1];
5511
5512 if (!use_null_for_in || !use_null_for_out || !use_null_for_err)
5513 {
Bram Moolenaarde279892016-03-11 22:19:44 +01005514 if (options->jo_set & JO_CHANNEL)
5515 {
5516 channel = options->jo_channel;
5517 if (channel != NULL)
5518 ++channel->ch_refcount;
5519 }
5520 else
5521 channel = add_channel();
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005522 if (channel == NULL)
5523 goto failed;
5524 }
Bram Moolenaard8070362016-02-15 21:56:54 +01005525
5526 if (!vim_create_process(cmd, TRUE,
Bram Moolenaar14207f42016-10-27 21:13:10 +02005527 CREATE_SUSPENDED |
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005528 CREATE_DEFAULT_ERROR_MODE |
5529 CREATE_NEW_PROCESS_GROUP |
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005530 CREATE_UNICODE_ENVIRONMENT |
Bram Moolenaar76467df2016-02-12 19:30:26 +01005531 CREATE_NEW_CONSOLE,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005532 &si, &pi,
5533 ga.ga_data,
5534 (char *)options->jo_cwd))
Bram Moolenaar76467df2016-02-12 19:30:26 +01005535 {
Bram Moolenaar14207f42016-10-27 21:13:10 +02005536 CloseHandle(jo);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005537 job->jv_status = JOB_FAILED;
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005538 goto failed;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005539 }
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005540
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005541 ga_clear(&ga);
5542
Bram Moolenaar14207f42016-10-27 21:13:10 +02005543 if (!AssignProcessToJobObject(jo, pi.hProcess))
5544 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005545 // if failing, switch the way to terminate
5546 // process with TerminateProcess.
Bram Moolenaar14207f42016-10-27 21:13:10 +02005547 CloseHandle(jo);
5548 jo = NULL;
5549 }
5550 ResumeThread(pi.hThread);
Bram Moolenaar75578a32016-03-10 16:33:31 +01005551 CloseHandle(pi.hThread);
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005552 job->jv_proc_info = pi;
Bram Moolenaar14207f42016-10-27 21:13:10 +02005553 job->jv_job_object = jo;
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005554 job->jv_status = JOB_STARTED;
5555
Bram Moolenaar641ad6c2016-09-01 18:32:11 +02005556 CloseHandle(ifd[0]);
5557 CloseHandle(ofd[1]);
5558 if (!use_out_for_err && !use_null_for_err)
Bram Moolenaarc25558b2016-03-03 21:02:23 +01005559 CloseHandle(efd[1]);
Bram Moolenaard8070362016-02-15 21:56:54 +01005560
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005561 job->jv_channel = channel;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005562 if (channel != NULL)
5563 {
5564 channel_set_pipes(channel,
5565 use_file_for_in || use_null_for_in
5566 ? INVALID_FD : (sock_T)ifd[1],
5567 use_file_for_out || use_null_for_out
5568 ? INVALID_FD : (sock_T)ofd[0],
5569 use_out_for_err || use_file_for_err || use_null_for_err
5570 ? INVALID_FD : (sock_T)efd[0]);
5571 channel_set_job(channel, job, options);
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005572 }
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005573 return;
5574
5575failed:
Bram Moolenaard8070362016-02-15 21:56:54 +01005576 CloseHandle(ifd[0]);
5577 CloseHandle(ofd[0]);
5578 CloseHandle(efd[0]);
5579 CloseHandle(ifd[1]);
5580 CloseHandle(ofd[1]);
5581 CloseHandle(efd[1]);
Bram Moolenaarde279892016-03-11 22:19:44 +01005582 channel_unref(channel);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005583 ga_clear(&ga);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005584}
5585
5586 char *
5587mch_job_status(job_T *job)
5588{
5589 DWORD dwExitCode = 0;
5590
Bram Moolenaar76467df2016-02-12 19:30:26 +01005591 if (!GetExitCodeProcess(job->jv_proc_info.hProcess, &dwExitCode)
5592 || dwExitCode != STILL_ACTIVE)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005593 {
Bram Moolenaareab089d2016-02-21 19:32:02 +01005594 job->jv_exitval = (int)dwExitCode;
Bram Moolenaar7df915d2016-11-17 17:25:32 +01005595 if (job->jv_status < JOB_ENDED)
Bram Moolenaar97792de2016-10-15 18:36:49 +02005596 {
5597 ch_log(job->jv_channel, "Job ended");
5598 job->jv_status = JOB_ENDED;
5599 }
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005600 return "dead";
5601 }
5602 return "run";
5603}
5604
Bram Moolenaar97792de2016-10-15 18:36:49 +02005605 job_T *
5606mch_detect_ended_job(job_T *job_list)
5607{
5608 HANDLE jobHandles[MAXIMUM_WAIT_OBJECTS];
5609 job_T *jobArray[MAXIMUM_WAIT_OBJECTS];
5610 job_T *job = job_list;
5611
5612 while (job != NULL)
5613 {
5614 DWORD n;
5615 DWORD result;
5616
5617 for (n = 0; n < MAXIMUM_WAIT_OBJECTS
5618 && job != NULL; job = job->jv_next)
5619 {
5620 if (job->jv_status == JOB_STARTED)
5621 {
5622 jobHandles[n] = job->jv_proc_info.hProcess;
5623 jobArray[n] = job;
5624 ++n;
5625 }
5626 }
5627 if (n == 0)
5628 continue;
5629 result = WaitForMultipleObjects(n, jobHandles, FALSE, 0);
5630 if (result >= WAIT_OBJECT_0 && result < WAIT_OBJECT_0 + n)
5631 {
5632 job_T *wait_job = jobArray[result - WAIT_OBJECT_0];
5633
5634 if (STRCMP(mch_job_status(wait_job), "dead") == 0)
5635 return wait_job;
5636 }
5637 }
5638 return NULL;
5639}
5640
Bram Moolenaarfb630902016-10-29 14:55:00 +02005641 static BOOL
5642terminate_all(HANDLE process, int code)
5643{
5644 PROCESSENTRY32 pe;
5645 HANDLE h = INVALID_HANDLE_VALUE;
5646 DWORD pid = GetProcessId(process);
5647
5648 if (pid != 0)
5649 {
5650 h = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
5651 if (h != INVALID_HANDLE_VALUE)
5652 {
5653 pe.dwSize = sizeof(PROCESSENTRY32);
5654 if (!Process32First(h, &pe))
5655 goto theend;
5656
5657 do
5658 {
5659 if (pe.th32ParentProcessID == pid)
5660 {
5661 HANDLE ph = OpenProcess(
5662 PROCESS_ALL_ACCESS, FALSE, pe.th32ProcessID);
5663 if (ph != NULL)
5664 {
5665 terminate_all(ph, code);
5666 CloseHandle(ph);
5667 }
5668 }
5669 } while (Process32Next(h, &pe));
5670
5671 CloseHandle(h);
5672 }
5673 }
5674
5675theend:
5676 return TerminateProcess(process, code);
5677}
5678
5679/*
5680 * Send a (deadly) signal to "job".
5681 * Return FAIL if it didn't work.
5682 */
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005683 int
Bram Moolenaar2d33e902017-08-11 16:31:54 +02005684mch_signal_job(job_T *job, char_u *how)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005685{
Bram Moolenaar923d9262016-02-25 20:56:01 +01005686 int ret;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005687
Bram Moolenaar923d9262016-02-25 20:56:01 +01005688 if (STRCMP(how, "term") == 0 || STRCMP(how, "kill") == 0 || *how == NUL)
Bram Moolenaar76467df2016-02-12 19:30:26 +01005689 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005690 // deadly signal
Bram Moolenaar14207f42016-10-27 21:13:10 +02005691 if (job->jv_job_object != NULL)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005692 {
5693 if (job->jv_channel != NULL && job->jv_channel->ch_anonymous_pipe)
5694 job->jv_channel->ch_killing = TRUE;
K.Takata135e1522022-01-29 15:27:58 +00005695 return TerminateJobObject(job->jv_job_object, (UINT)-1) ? OK : FAIL;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005696 }
Bram Moolenaarb3e195c2020-02-10 21:32:19 +01005697 return terminate_all(job->jv_proc_info.hProcess, -1) ? OK : FAIL;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005698 }
5699
5700 if (!AttachConsole(job->jv_proc_info.dwProcessId))
5701 return FAIL;
5702 ret = GenerateConsoleCtrlEvent(
Bram Moolenaar923d9262016-02-25 20:56:01 +01005703 STRCMP(how, "int") == 0 ? CTRL_C_EVENT : CTRL_BREAK_EVENT,
5704 job->jv_proc_info.dwProcessId)
5705 ? OK : FAIL;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005706 FreeConsole();
5707 return ret;
5708}
5709
5710/*
5711 * Clear the data related to "job".
5712 */
5713 void
5714mch_clear_job(job_T *job)
5715{
5716 if (job->jv_status != JOB_FAILED)
5717 {
Bram Moolenaar14207f42016-10-27 21:13:10 +02005718 if (job->jv_job_object != NULL)
5719 CloseHandle(job->jv_job_object);
Bram Moolenaar76467df2016-02-12 19:30:26 +01005720 CloseHandle(job->jv_proc_info.hProcess);
5721 }
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005722}
5723#endif
5724
Bram Moolenaar071d4272004-06-13 20:20:40 +00005725
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005726#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005727
5728/*
5729 * Start termcap mode
5730 */
5731 static void
5732termcap_mode_start(void)
5733{
5734 DWORD cmodein;
5735
5736 if (g_fTermcapMode)
5737 return;
5738
Bram Moolenaar81ccbf12020-04-15 21:05:30 +02005739 if (!p_rs && USE_VTP)
5740 vtp_printf("\033[?1049h");
5741
Bram Moolenaar071d4272004-06-13 20:20:40 +00005742 SaveConsoleBuffer(&g_cbNonTermcap);
5743
5744 if (g_cbTermcap.IsValid)
5745 {
5746 /*
5747 * We've been in termcap mode before. Restore certain screen
5748 * characteristics, including the buffer size and the window
5749 * size. Since we will be redrawing the screen, we don't need
5750 * to restore the actual contents of the buffer.
5751 */
5752 RestoreConsoleBuffer(&g_cbTermcap, FALSE);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005753 reset_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005754 SetConsoleWindowInfo(g_hConOut, TRUE, &g_cbTermcap.Info.srWindow);
5755 Rows = g_cbTermcap.Info.dwSize.Y;
5756 Columns = g_cbTermcap.Info.dwSize.X;
5757 }
5758 else
5759 {
5760 /*
5761 * This is our first time entering termcap mode. Clear the console
5762 * screen buffer, and resize the buffer to match the current window
5763 * size. We will use this as the size of our editing environment.
5764 */
5765 ClearConsoleBuffer(g_attrCurrent);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005766 set_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005767 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
5768 }
5769
Bram Moolenaar071d4272004-06-13 20:20:40 +00005770 resettitle();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005771
5772 GetConsoleMode(g_hConIn, &cmodein);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005773 if (g_fMouseActive)
Wez Furlong6ef5ab52021-05-30 19:29:41 +02005774 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00005775 cmodein |= ENABLE_MOUSE_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02005776 cmodein &= ~ENABLE_QUICK_EDIT_MODE;
5777 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005778 else
Wez Furlong6ef5ab52021-05-30 19:29:41 +02005779 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00005780 cmodein &= ~ENABLE_MOUSE_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02005781 cmodein |= g_cmodein & ENABLE_QUICK_EDIT_MODE;
5782 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005783 cmodein |= ENABLE_WINDOW_INPUT;
Wez Furlong6ef5ab52021-05-30 19:29:41 +02005784 SetConsoleMode(g_hConIn, cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005785
5786 redraw_later_clear();
5787 g_fTermcapMode = TRUE;
5788}
5789
5790
5791/*
5792 * End termcap mode
5793 */
5794 static void
5795termcap_mode_end(void)
5796{
5797 DWORD cmodein;
5798 ConsoleBuffer *cb;
5799 COORD coord;
5800 DWORD dwDummy;
5801
5802 if (!g_fTermcapMode)
5803 return;
5804
5805 SaveConsoleBuffer(&g_cbTermcap);
5806
5807 GetConsoleMode(g_hConIn, &cmodein);
5808 cmodein &= ~(ENABLE_MOUSE_INPUT | ENABLE_WINDOW_INPUT);
Wez Furlong6ef5ab52021-05-30 19:29:41 +02005809 cmodein |= g_cmodein & ENABLE_QUICK_EDIT_MODE;
5810 SetConsoleMode(g_hConIn, cmodein | ENABLE_EXTENDED_FLAGS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005811
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01005812# ifdef FEAT_RESTORE_ORIG_SCREEN
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01005813 cb = exiting ? &g_cbOrig : &g_cbNonTermcap;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01005814# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00005815 cb = &g_cbNonTermcap;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01005816# endif
Bram Moolenaar81ccbf12020-04-15 21:05:30 +02005817 RestoreConsoleBuffer(cb, p_rs);
Bram Moolenaardf543822020-01-30 11:53:59 +01005818 restore_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005819 SetConsoleCursorInfo(g_hConOut, &g_cci);
5820
5821 if (p_rs || exiting)
5822 {
5823 /*
5824 * Clear anything that happens to be on the current line.
5825 */
5826 coord.X = 0;
5827 coord.Y = (SHORT) (p_rs ? cb->Info.dwCursorPosition.Y : (Rows - 1));
5828 FillConsoleOutputCharacter(g_hConOut, ' ',
5829 cb->Info.dwSize.X, coord, &dwDummy);
5830 /*
5831 * The following is just for aesthetics. If we are exiting without
5832 * restoring the screen, then we want to have a prompt string
5833 * appear at the bottom line. However, the command interpreter
5834 * seems to always advance the cursor one line before displaying
5835 * the prompt string, which causes the screen to scroll. To
5836 * counter this, move the cursor up one line before exiting.
5837 */
5838 if (exiting && !p_rs)
5839 coord.Y--;
5840 /*
5841 * Position the cursor at the leftmost column of the desired row.
5842 */
Bram Moolenaar81ccbf12020-04-15 21:05:30 +02005843 SetConsoleCursorPosition(g_hConOut, coord);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005844 }
5845
Bram Moolenaar81ccbf12020-04-15 21:05:30 +02005846 if (!p_rs && USE_VTP)
Bram Moolenaar0afdcf82020-04-01 18:29:10 +02005847 vtp_printf("\033[?1049l");
5848
Bram Moolenaar071d4272004-06-13 20:20:40 +00005849 g_fTermcapMode = FALSE;
5850}
Christopher Plewright38804d62022-11-09 23:55:52 +00005851#endif // !FEAT_GUI_MSWIN || VIMDLL
Bram Moolenaar071d4272004-06-13 20:20:40 +00005852
5853
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005854#if defined(FEAT_GUI_MSWIN) && !defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005855 void
5856mch_write(
Bram Moolenaar1266d672017-02-01 13:43:36 +01005857 char_u *s UNUSED,
5858 int len UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005859{
Bram Moolenaar0f873732019-12-05 20:28:46 +01005860 // never used
Bram Moolenaar071d4272004-06-13 20:20:40 +00005861}
5862
5863#else
5864
5865/*
5866 * clear `n' chars, starting from `coord'
5867 */
5868 static void
5869clear_chars(
5870 COORD coord,
5871 DWORD n)
5872{
Christopher Plewright38804d62022-11-09 23:55:52 +00005873 if (!vtp_working)
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02005874 {
5875 DWORD dwDummy;
5876
5877 FillConsoleOutputCharacter(g_hConOut, ' ', n, coord, &dwDummy);
5878 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, n, coord,
5879 &dwDummy);
5880 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005881 else
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02005882 {
5883 set_console_color_rgb();
5884 gotoxy(coord.X + 1, coord.Y + 1);
5885 vtp_printf("\033[%dX", n);
5886 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005887}
5888
5889
5890/*
5891 * Clear the screen
5892 */
5893 static void
5894clear_screen(void)
5895{
5896 g_coord.X = g_coord.Y = 0;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005897
Christopher Plewright38804d62022-11-09 23:55:52 +00005898 if (!vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005899 clear_chars(g_coord, Rows * Columns);
5900 else
5901 {
5902 set_console_color_rgb();
5903 gotoxy(1, 1);
5904 vtp_printf("\033[2J");
5905 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005906}
5907
5908
5909/*
5910 * Clear to end of display
5911 */
5912 static void
5913clear_to_end_of_display(void)
5914{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005915 COORD save = g_coord;
5916
Christopher Plewright38804d62022-11-09 23:55:52 +00005917 if (!vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005918 clear_chars(g_coord, (Rows - g_coord.Y - 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005919 * Columns + (Columns - g_coord.X));
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005920 else
5921 {
5922 set_console_color_rgb();
5923 gotoxy(g_coord.X + 1, g_coord.Y + 1);
5924 vtp_printf("\033[0J");
5925
5926 gotoxy(save.X + 1, save.Y + 1);
5927 g_coord = save;
5928 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005929}
5930
5931
5932/*
5933 * Clear to end of line
5934 */
5935 static void
5936clear_to_end_of_line(void)
5937{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005938 COORD save = g_coord;
5939
Christopher Plewright38804d62022-11-09 23:55:52 +00005940 if (!vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005941 clear_chars(g_coord, Columns - g_coord.X);
5942 else
5943 {
5944 set_console_color_rgb();
5945 gotoxy(g_coord.X + 1, g_coord.Y + 1);
5946 vtp_printf("\033[0K");
5947
5948 gotoxy(save.X + 1, save.Y + 1);
5949 g_coord = save;
5950 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005951}
5952
5953
5954/*
5955 * Scroll the scroll region up by `cLines' lines
5956 */
5957 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005958scroll(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005959{
5960 COORD oldcoord = g_coord;
5961
5962 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
5963 delete_lines(cLines);
5964
5965 g_coord = oldcoord;
5966}
5967
5968
5969/*
5970 * Set the scroll region
5971 */
5972 static void
5973set_scroll_region(
5974 unsigned left,
5975 unsigned top,
5976 unsigned right,
5977 unsigned bottom)
5978{
5979 if (left >= right
5980 || top >= bottom
5981 || right > (unsigned) Columns - 1
5982 || bottom > (unsigned) Rows - 1)
5983 return;
5984
5985 g_srScrollRegion.Left = left;
5986 g_srScrollRegion.Top = top;
5987 g_srScrollRegion.Right = right;
5988 g_srScrollRegion.Bottom = bottom;
Bram Moolenaar6982f422019-02-16 16:48:01 +01005989}
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005990
Bram Moolenaar6982f422019-02-16 16:48:01 +01005991 static void
5992set_scroll_region_tb(
5993 unsigned top,
5994 unsigned bottom)
5995{
5996 if (top >= bottom || bottom > (unsigned)Rows - 1)
5997 return;
5998
5999 g_srScrollRegion.Top = top;
6000 g_srScrollRegion.Bottom = bottom;
6001}
6002
6003 static void
6004set_scroll_region_lr(
6005 unsigned left,
6006 unsigned right)
6007{
6008 if (left >= right || right > (unsigned)Columns - 1)
6009 return;
6010
6011 g_srScrollRegion.Left = left;
6012 g_srScrollRegion.Right = right;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006013}
6014
6015
6016/*
6017 * Insert `cLines' lines at the current cursor position
6018 */
6019 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006020insert_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006021{
Bram Moolenaar6982f422019-02-16 16:48:01 +01006022 SMALL_RECT source, clip;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006023 COORD dest;
6024 CHAR_INFO fill;
6025
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006026 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
6027
Bram Moolenaar6982f422019-02-16 16:48:01 +01006028 dest.X = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006029 dest.Y = g_coord.Y + cLines;
6030
Bram Moolenaar6982f422019-02-16 16:48:01 +01006031 source.Left = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006032 source.Top = g_coord.Y;
6033 source.Right = g_srScrollRegion.Right;
6034 source.Bottom = g_srScrollRegion.Bottom - cLines;
6035
Bram Moolenaar6982f422019-02-16 16:48:01 +01006036 clip.Left = g_srScrollRegion.Left;
6037 clip.Top = g_coord.Y;
6038 clip.Right = g_srScrollRegion.Right;
6039 clip.Bottom = g_srScrollRegion.Bottom;
6040
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006041 fill.Char.AsciiChar = ' ';
Christopher Plewright38804d62022-11-09 23:55:52 +00006042 if (!(vtp_working
6043#ifdef FEAT_TERMGUICOLORS
6044 && (p_tgc || t_colors >= 256)
6045#endif
6046 ))
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006047 fill.Attributes = g_attrCurrent;
6048 else
6049 fill.Attributes = g_attrDefault;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006050
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006051 set_console_color_rgb();
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006052
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006053 ScrollConsoleScreenBuffer(g_hConOut, &source, &clip, dest, &fill);
6054
Bram Moolenaar6982f422019-02-16 16:48:01 +01006055 // Here we have to deal with a win32 console flake: If the scroll
6056 // region looks like abc and we scroll c to a and fill with d we get
6057 // cbd... if we scroll block c one line at a time to a, we get cdd...
6058 // vim expects cdd consistently... So we have to deal with that
6059 // here... (this also occurs scrolling the same way in the other
6060 // direction).
Bram Moolenaar071d4272004-06-13 20:20:40 +00006061
6062 if (source.Bottom < dest.Y)
6063 {
6064 COORD coord;
Bram Moolenaar6982f422019-02-16 16:48:01 +01006065 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006066
Bram Moolenaar6982f422019-02-16 16:48:01 +01006067 coord.X = source.Left;
6068 for (i = clip.Top; i < dest.Y; ++i)
6069 {
6070 coord.Y = i;
6071 clear_chars(coord, source.Right - source.Left + 1);
6072 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006073 }
Bram Moolenaar06b7b582020-05-30 17:49:25 +02006074
Christopher Plewright38804d62022-11-09 23:55:52 +00006075 if (vtp_working)
Bram Moolenaar06b7b582020-05-30 17:49:25 +02006076 {
6077 COORD coord;
6078 int i;
6079
6080 coord.X = source.Left;
6081 for (i = source.Top; i < dest.Y; ++i)
6082 {
6083 coord.Y = i;
6084 clear_chars(coord, source.Right - source.Left + 1);
6085 }
6086 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006087}
6088
6089
6090/*
6091 * Delete `cLines' lines at the current cursor position
6092 */
6093 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006094delete_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006095{
Bram Moolenaar6982f422019-02-16 16:48:01 +01006096 SMALL_RECT source, clip;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006097 COORD dest;
6098 CHAR_INFO fill;
6099 int nb;
6100
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006101 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
6102
Bram Moolenaar6982f422019-02-16 16:48:01 +01006103 dest.X = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006104 dest.Y = g_coord.Y;
6105
Bram Moolenaar6982f422019-02-16 16:48:01 +01006106 source.Left = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006107 source.Top = g_coord.Y + cLines;
6108 source.Right = g_srScrollRegion.Right;
6109 source.Bottom = g_srScrollRegion.Bottom;
6110
Bram Moolenaar6982f422019-02-16 16:48:01 +01006111 clip.Left = g_srScrollRegion.Left;
6112 clip.Top = g_coord.Y;
6113 clip.Right = g_srScrollRegion.Right;
6114 clip.Bottom = g_srScrollRegion.Bottom;
6115
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006116 fill.Char.AsciiChar = ' ';
Christopher Plewright38804d62022-11-09 23:55:52 +00006117 if (!vtp_working)
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006118 fill.Attributes = g_attrCurrent;
6119 else
6120 fill.Attributes = g_attrDefault;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006121
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006122 set_console_color_rgb();
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006123
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01006124 ScrollConsoleScreenBuffer(g_hConOut, &source, &clip, dest, &fill);
6125
Bram Moolenaar6982f422019-02-16 16:48:01 +01006126 // Here we have to deal with a win32 console flake; See insert_lines()
6127 // above.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006128
6129 nb = dest.Y + (source.Bottom - source.Top) + 1;
6130
6131 if (nb < source.Top)
6132 {
6133 COORD coord;
Bram Moolenaar6982f422019-02-16 16:48:01 +01006134 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006135
Bram Moolenaar6982f422019-02-16 16:48:01 +01006136 coord.X = source.Left;
6137 for (i = nb; i < clip.Bottom; ++i)
6138 {
6139 coord.Y = i;
6140 clear_chars(coord, source.Right - source.Left + 1);
6141 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006142 }
Bram Moolenaar06b7b582020-05-30 17:49:25 +02006143
Christopher Plewright38804d62022-11-09 23:55:52 +00006144 if (vtp_working)
Bram Moolenaar06b7b582020-05-30 17:49:25 +02006145 {
6146 COORD coord;
6147 int i;
6148
6149 coord.X = source.Left;
6150 for (i = nb; i <= source.Bottom; ++i)
6151 {
6152 coord.Y = i;
6153 clear_chars(coord, source.Right - source.Left + 1);
6154 }
6155 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006156}
6157
6158
6159/*
Bram Moolenaar2313b612019-09-27 14:14:32 +02006160 * Set the cursor position to (x,y) (1-based).
Bram Moolenaar071d4272004-06-13 20:20:40 +00006161 */
6162 static void
6163gotoxy(
6164 unsigned x,
6165 unsigned y)
6166{
6167 if (x < 1 || x > (unsigned)Columns || y < 1 || y > (unsigned)Rows)
6168 return;
6169
Christopher Plewright38804d62022-11-09 23:55:52 +00006170 if (!(vtp_working
6171#ifdef FEAT_TERMGUICOLORS
6172 && (p_tgc || t_colors >= 256)
6173#endif
6174 ))
Bram Moolenaar2313b612019-09-27 14:14:32 +02006175 {
Bram Moolenaar82e743c2020-03-26 15:39:53 +01006176 // There are reports of double-width characters not displayed
6177 // correctly. This workaround should fix it, similar to how it's done
6178 // for VTP.
6179 g_coord.X = 0;
6180 SetConsoleCursorPosition(g_hConOut, g_coord);
6181
Bram Moolenaar2313b612019-09-27 14:14:32 +02006182 // external cursor coords are 1-based; internal are 0-based
6183 g_coord.X = x - 1;
6184 g_coord.Y = y - 1;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006185 SetConsoleCursorPosition(g_hConOut, g_coord);
Bram Moolenaar2313b612019-09-27 14:14:32 +02006186 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006187 else
Bram Moolenaar2313b612019-09-27 14:14:32 +02006188 {
6189 // Move the cursor to the left edge of the screen to prevent screen
Bram Moolenaara1299742019-10-10 16:36:00 +02006190 // destruction. Insider build bug. Always enabled because it's cheap
6191 // and avoids mistakes with recognizing the build.
6192 vtp_printf("\033[%d;%dH", g_coord.Y + 1, 1);
Bram Moolenaar2313b612019-09-27 14:14:32 +02006193
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006194 vtp_printf("\033[%d;%dH", y, x);
Bram Moolenaar2313b612019-09-27 14:14:32 +02006195
6196 g_coord.X = x - 1;
6197 g_coord.Y = y - 1;
6198 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006199}
6200
6201
6202/*
6203 * Set the current text attribute = (foreground | background)
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006204 * See ../runtime/doc/os_win32.txt for the numbers.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006205 */
6206 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006207textattr(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006208{
Bram Moolenaar6383b922015-03-24 17:12:19 +01006209 g_attrCurrent = wAttr & 0xff;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006210
6211 SetConsoleTextAttribute(g_hConOut, wAttr);
6212}
6213
6214
6215 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006216textcolor(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006217{
Bram Moolenaar6383b922015-03-24 17:12:19 +01006218 g_attrCurrent = (g_attrCurrent & 0xf0) + (wAttr & 0x0f);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006219
Christopher Plewright38804d62022-11-09 23:55:52 +00006220 if (!vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006221 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
6222 else
6223 vtp_sgr_bulk(wAttr);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006224}
6225
6226
6227 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006228textbackground(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006229{
Bram Moolenaar6383b922015-03-24 17:12:19 +01006230 g_attrCurrent = (g_attrCurrent & 0x0f) + ((wAttr & 0x0f) << 4);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006231
Christopher Plewright38804d62022-11-09 23:55:52 +00006232 if (!vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006233 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
6234 else
6235 vtp_sgr_bulk(wAttr);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006236}
6237
6238
6239/*
6240 * restore the default text attribute (whatever we started with)
6241 */
6242 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006243normvideo(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006244{
Christopher Plewright38804d62022-11-09 23:55:52 +00006245 if (!vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006246 textattr(g_attrDefault);
6247 else
6248 vtp_sgr_bulk(0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006249}
6250
6251
6252static WORD g_attrPreStandout = 0;
6253
6254/*
6255 * Make the text standout, by brightening it
6256 */
6257 static void
6258standout(void)
6259{
6260 g_attrPreStandout = g_attrCurrent;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006261
Bram Moolenaar071d4272004-06-13 20:20:40 +00006262 textattr((WORD) (g_attrCurrent|FOREGROUND_INTENSITY|BACKGROUND_INTENSITY));
6263}
6264
6265
6266/*
6267 * Turn off standout mode
6268 */
6269 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006270standend(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006271{
6272 if (g_attrPreStandout)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006273 textattr(g_attrPreStandout);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006274
6275 g_attrPreStandout = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006276}
6277
6278
6279/*
Bram Moolenaarff1d0d42007-05-10 17:24:16 +00006280 * Set normal fg/bg color, based on T_ME. Called when t_me has been set.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006281 */
6282 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006283mch_set_normal_colors(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006284{
6285 char_u *p;
6286 int n;
6287
6288 cterm_normal_fg_color = (g_attrDefault & 0xf) + 1;
6289 cterm_normal_bg_color = ((g_attrDefault >> 4) & 0xf) + 1;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006290 if (
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006291# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006292 !p_tgc &&
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006293# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006294 T_ME[0] == ESC && T_ME[1] == '|')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006295 {
6296 p = T_ME + 2;
6297 n = getdigits(&p);
6298 if (*p == 'm' && n > 0)
6299 {
6300 cterm_normal_fg_color = (n & 0xf) + 1;
6301 cterm_normal_bg_color = ((n >> 4) & 0xf) + 1;
6302 }
6303 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006304# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006305 cterm_normal_fg_gui_color = INVALCOLOR;
6306 cterm_normal_bg_gui_color = INVALCOLOR;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006307# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006308}
6309
6310
6311/*
6312 * visual bell: flash the screen
6313 */
6314 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006315visual_bell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006316{
6317 COORD coordOrigin = {0, 0};
6318 WORD attrFlash = ~g_attrCurrent & 0xff;
6319
6320 DWORD dwDummy;
Bram Moolenaarc799fe22019-05-28 23:08:19 +02006321 LPWORD oldattrs = ALLOC_MULT(WORD, Rows * Columns);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006322
6323 if (oldattrs == NULL)
6324 return;
6325 ReadConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
6326 coordOrigin, &dwDummy);
6327 FillConsoleOutputAttribute(g_hConOut, attrFlash, Rows * Columns,
6328 coordOrigin, &dwDummy);
6329
Bram Moolenaar0f873732019-12-05 20:28:46 +01006330 Sleep(15); // wait for 15 msec
Christopher Plewright38804d62022-11-09 23:55:52 +00006331 if (!vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006332 WriteConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
Bram Moolenaar071d4272004-06-13 20:20:40 +00006333 coordOrigin, &dwDummy);
6334 vim_free(oldattrs);
6335}
6336
6337
6338/*
6339 * Make the cursor visible or invisible
6340 */
6341 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006342cursor_visible(BOOL fVisible)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006343{
6344 s_cursor_visible = fVisible;
Bram Moolenaar2695de62020-04-17 21:13:01 +02006345
Christopher Plewright38804d62022-11-09 23:55:52 +00006346 if (vtp_working)
Bram Moolenaar2695de62020-04-17 21:13:01 +02006347 vtp_printf("\033[?25%c", fVisible ? 'h' : 'l');
6348
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006349# ifdef MCH_CURSOR_SHAPE
Bram Moolenaar071d4272004-06-13 20:20:40 +00006350 mch_update_cursor();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006351# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006352}
6353
6354
6355/*
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02006356 * Write "cbToWrite" bytes in `pchBuf' to the screen.
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006357 * Returns the number of bytes actually written (at least one).
Bram Moolenaar071d4272004-06-13 20:20:40 +00006358 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006359 static DWORD
Bram Moolenaar071d4272004-06-13 20:20:40 +00006360write_chars(
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006361 char_u *pchBuf,
6362 DWORD cbToWrite)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006363{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006364 COORD coord = g_coord;
6365 DWORD written;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006366 DWORD n, cchwritten;
6367 static DWORD cells;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006368 static WCHAR *unicodebuf = NULL;
6369 static int unibuflen = 0;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006370 static int length;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006371 int cp = enc_utf8 ? CP_UTF8 : enc_codepage;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006372 static WCHAR *utf8spbuf = NULL;
6373 static int utf8splength;
6374 static DWORD utf8spcells;
6375 static WCHAR **utf8usingbuf = &unicodebuf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006376
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006377 if (cbToWrite != 1 || *pchBuf != ' ' || !enc_utf8)
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006378 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006379 utf8usingbuf = &unicodebuf;
6380 do
6381 {
6382 length = MultiByteToWideChar(cp, 0, (LPCSTR)pchBuf, cbToWrite,
6383 unicodebuf, unibuflen);
6384 if (length && length <= unibuflen)
6385 break;
6386 vim_free(unicodebuf);
6387 unicodebuf = length ? LALLOC_MULT(WCHAR, length) : NULL;
6388 unibuflen = unibuflen ? 0 : length;
6389 } while(1);
6390 cells = mb_string2cells(pchBuf, cbToWrite);
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006391 }
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006392 else // cbToWrite == 1 && *pchBuf == ' ' && enc_utf8
6393 {
6394 if (utf8usingbuf != &utf8spbuf)
6395 {
6396 if (utf8spbuf == NULL)
6397 {
6398 cells = mb_string2cells((char_u *)" ", 1);
6399 length = MultiByteToWideChar(CP_UTF8, 0, " ", 1, NULL, 0);
6400 utf8spbuf = LALLOC_MULT(WCHAR, length);
6401 if (utf8spbuf != NULL)
6402 {
6403 MultiByteToWideChar(CP_UTF8, 0, " ", 1, utf8spbuf, length);
6404 utf8usingbuf = &utf8spbuf;
6405 utf8splength = length;
6406 utf8spcells = cells;
6407 }
6408 }
6409 else
6410 {
6411 utf8usingbuf = &utf8spbuf;
6412 length = utf8splength;
6413 cells = utf8spcells;
6414 }
6415 }
6416 }
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006417
Christopher Plewright38804d62022-11-09 23:55:52 +00006418 if (!(vtp_working
6419#ifdef FEAT_TERMGUICOLORS
6420 && (p_tgc || t_colors >= 256)
6421#endif
6422 ))
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006423 {
6424 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, cells,
6425 coord, &written);
6426 // When writing fails or didn't write a single character, pretend one
6427 // character was written, otherwise we get stuck.
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006428 if (WriteConsoleOutputCharacterW(g_hConOut, *utf8usingbuf, length,
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006429 coord, &cchwritten) == 0
6430 || cchwritten == 0 || cchwritten == (DWORD)-1)
6431 cchwritten = 1;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006432 }
6433 else
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006434 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006435 if (WriteConsoleW(g_hConOut, *utf8usingbuf, length, &cchwritten,
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006436 NULL) == 0 || cchwritten == 0)
6437 cchwritten = 1;
6438 }
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006439
K.Takata135e1522022-01-29 15:27:58 +00006440 if (cchwritten == (DWORD)length)
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006441 {
6442 written = cbToWrite;
6443 g_coord.X += (SHORT)cells;
6444 }
6445 else
6446 {
6447 char_u *p = pchBuf;
6448 for (n = 0; n < cchwritten; n++)
6449 MB_CPTR_ADV(p);
6450 written = p - pchBuf;
6451 g_coord.X += (SHORT)mb_string2cells(pchBuf, written);
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006452 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006453
6454 while (g_coord.X > g_srScrollRegion.Right)
6455 {
6456 g_coord.X -= (SHORT) Columns;
6457 if (g_coord.Y < g_srScrollRegion.Bottom)
6458 g_coord.Y++;
6459 }
6460
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006461 // Cursor under VTP is always in the correct position, no need to reset.
Christopher Plewright38804d62022-11-09 23:55:52 +00006462 if (!(vtp_working
6463#ifdef FEAT_TERMGUICOLORS
6464 && (p_tgc || t_colors >= 256)
6465#endif
6466 ))
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006467 gotoxy(g_coord.X + 1, g_coord.Y + 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006468
6469 return written;
6470}
6471
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006472 static char_u *
6473get_seq(
6474 int *args,
6475 int *count,
6476 char_u *head)
6477{
6478 int argc;
6479 char_u *p;
6480
6481 if (head == NULL || *head != '\033')
6482 return NULL;
6483
6484 argc = 0;
6485 p = head;
6486 ++p;
6487 do
6488 {
6489 ++p;
6490 args[argc] = getdigits(&p);
6491 argc += (argc < 15) ? 1 : 0;
6492 } while (*p == ';');
6493 *count = argc;
6494
6495 return p;
6496}
6497
6498 static char_u *
6499get_sgr(
6500 int *args,
6501 int *count,
6502 char_u *head)
6503{
6504 char_u *p = get_seq(args, count, head);
6505
6506 return (p && *p == 'm') ? ++p : NULL;
6507}
6508
6509/*
6510 * Pointer to next if SGR (^[[n;2;*;*;*m), NULL otherwise.
6511 */
6512 static char_u *
6513sgrn2(
6514 char_u *head,
6515 int n)
6516{
6517 int argc;
6518 int args[16];
6519 char_u *p = get_sgr(args, &argc, head);
6520
6521 return p && argc == 5 && args[0] == n && args[1] == 2 ? p : NULL;
6522}
6523
6524/*
6525 * Pointer to next if SGR(^[[nm)<space>ESC, NULL otherwise.
6526 */
6527 static char_u *
6528sgrnc(
6529 char_u *head,
6530 int n)
6531{
6532 int argc;
6533 int args[16];
6534 char_u *p = get_sgr(args, &argc, head);
6535
6536 return p && argc == 1 && args[0] == n && (p = skipwhite(p)) && *p == '\033'
6537 ? p : NULL;
6538}
6539
6540 static char_u *
6541skipblank(char_u *q)
6542{
6543 char_u *p = q;
6544
6545 while (*p == ' ' || *p == '\t' || *p == '\n' || *p == '\r')
6546 ++p;
6547 return p;
6548}
6549
6550/*
6551 * Pointer to the next if any whitespace that may follow SGR is ESC, otherwise
6552 * NULL.
6553 */
6554 static char_u *
6555sgrn2c(
6556 char_u *head,
6557 int n)
6558{
6559 char_u *p = sgrn2(head, n);
6560
6561 return p && *p != NUL && (p = skipblank(p)) && *p == '\033' ? p : NULL;
6562}
6563
6564/*
6565 * If there is only a newline between the sequence immediately following it,
6566 * a pointer to the character following the newline is returned.
6567 * Otherwise NULL.
6568 */
6569 static char_u *
6570sgrn2cn(
6571 char_u *head,
6572 int n)
6573{
6574 char_u *p = sgrn2(head, n);
6575
6576 return p && p[0] == 0x0a && p[1] == '\033' ? ++p : NULL;
6577}
Bram Moolenaar071d4272004-06-13 20:20:40 +00006578
6579/*
6580 * mch_write(): write the output buffer to the screen, translating ESC
6581 * sequences into calls to console output routines.
6582 */
6583 void
6584mch_write(
6585 char_u *s,
6586 int len)
6587{
Bram Moolenaard23f8bd2021-04-21 11:30:48 +02006588 char_u *end = s + len;
6589
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006590# ifdef VIMDLL
6591 if (gui.in_use)
6592 return;
6593# endif
6594
Bram Moolenaar071d4272004-06-13 20:20:40 +00006595 if (!term_console)
6596 {
6597 write(1, s, (unsigned)len);
6598 return;
6599 }
6600
Bram Moolenaar0f873732019-12-05 20:28:46 +01006601 // translate ESC | sequences into faked bios calls
Bram Moolenaar071d4272004-06-13 20:20:40 +00006602 while (len--)
6603 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006604 int prefix = -1;
6605 char_u ch;
6606
6607 // While processing a sequence, on rare occasions it seems that another
6608 // sequence may be inserted asynchronously.
6609 if (len < 0)
6610 {
Bram Moolenaara4d158b2022-08-14 14:17:45 +01006611 redraw_all_later(UPD_CLEAR);
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006612 return;
6613 }
6614
Bram Moolenaard23f8bd2021-04-21 11:30:48 +02006615 while (s + ++prefix < end)
6616 {
6617 ch = s[prefix];
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006618 if (ch <= 0x1e && !(ch != '\n' && ch != '\r' && ch != '\b'
6619 && ch != '\a' && ch != '\033'))
6620 break;
Bram Moolenaard23f8bd2021-04-21 11:30:48 +02006621 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006622
6623 if (p_wd)
6624 {
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02006625 WaitForChar(p_wd, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006626 if (prefix != 0)
6627 prefix = 1;
6628 }
6629
6630 if (prefix != 0)
6631 {
6632 DWORD nWritten;
6633
6634 nWritten = write_chars(s, prefix);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006635# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006636 if (fdDump)
6637 {
6638 fputc('>', fdDump);
6639 fwrite(s, sizeof(char_u), nWritten, fdDump);
6640 fputs("<\n", fdDump);
6641 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006642# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006643 len -= (nWritten - 1);
6644 s += nWritten;
6645 }
6646 else if (s[0] == '\n')
6647 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006648 // \n, newline: go to the beginning of the next line or scroll
Bram Moolenaar071d4272004-06-13 20:20:40 +00006649 if (g_coord.Y == g_srScrollRegion.Bottom)
6650 {
6651 scroll(1);
6652 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Bottom + 1);
6653 }
6654 else
6655 {
6656 gotoxy(g_srScrollRegion.Left + 1, g_coord.Y + 2);
6657 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006658# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006659 if (fdDump)
6660 fputs("\\n\n", fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006661# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006662 s++;
6663 }
6664 else if (s[0] == '\r')
6665 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006666 // \r, carriage return: go to beginning of line
Bram Moolenaar071d4272004-06-13 20:20:40 +00006667 gotoxy(g_srScrollRegion.Left+1, g_coord.Y + 1);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006668# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006669 if (fdDump)
6670 fputs("\\r\n", fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006671# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006672 s++;
6673 }
6674 else if (s[0] == '\b')
6675 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006676 // \b, backspace: move cursor one position left
Bram Moolenaar071d4272004-06-13 20:20:40 +00006677 if (g_coord.X > g_srScrollRegion.Left)
6678 g_coord.X--;
6679 else if (g_coord.Y > g_srScrollRegion.Top)
6680 {
6681 g_coord.X = g_srScrollRegion.Right;
6682 g_coord.Y--;
6683 }
6684 gotoxy(g_coord.X + 1, g_coord.Y + 1);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006685# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006686 if (fdDump)
6687 fputs("\\b\n", fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006688# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006689 s++;
6690 }
6691 else if (s[0] == '\a')
6692 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006693 // \a, bell
Bram Moolenaar071d4272004-06-13 20:20:40 +00006694 MessageBeep(0xFFFFFFFF);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006695# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006696 if (fdDump)
6697 fputs("\\a\n", fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006698# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006699 s++;
6700 }
6701 else if (s[0] == ESC && len >= 3-1 && s[1] == '|')
6702 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006703# ifdef MCH_WRITE_DUMP
Bram Moolenaarc0197e22004-09-13 20:26:32 +00006704 char_u *old_s = s;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006705# endif
Bram Moolenaarc0197e22004-09-13 20:26:32 +00006706 char_u *p;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006707 int arg1 = 0, arg2 = 0, argc = 0, args[16];
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006708 char_u *sp;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006709
6710 switch (s[2])
6711 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006712 case '0': case '1': case '2': case '3': case '4':
6713 case '5': case '6': case '7': case '8': case '9':
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006714 if (*(p = get_seq(args, &argc, s)) != 'm')
6715 goto notsgr;
6716
6717 p = s;
6718
6719 // Handling frequent optional sequences. Output to the screen
6720 // takes too long, so do not output as much as possible.
6721
6722 // If resetFG,FG,BG,<cr>,BG,FG are connected, the preceding
6723 // resetFG,FG,BG are omitted.
6724 if (sgrn2(sgrn2(sgrn2cn(sgrn2(sgrnc(p, 39), 38), 48), 48), 38))
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006725 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006726 p = sgrn2(sgrn2(sgrnc(p, 39), 38), 48);
6727 len = len + 1 - (int)(p - s);
6728 s = p;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006729 break;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006730 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006731
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006732 // If FG,BG,BG,FG of SGR are connected, the first FG can be
6733 // omitted.
6734 if (sgrn2(sgrn2(sgrn2c((sp = sgrn2(p, 38)), 48), 48), 38))
6735 p = sp;
6736
6737 // If FG,BG,FG,BG of SGR are connected, the first FG can be
6738 // omitted.
6739 if (sgrn2(sgrn2(sgrn2c((sp = sgrn2(p, 38)), 48), 38), 48))
6740 p = sp;
6741
6742 // If BG,BG of SGR are connected, the first BG can be omitted.
6743 if (sgrn2((sp = sgrn2(p, 48)), 48))
6744 p = sp;
6745
6746 // If restoreFG and FG are connected, the restoreFG can be
Bram Moolenaar9f1983d2022-05-12 20:35:35 +01006747 // omitted.
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006748 if (sgrn2((sp = sgrnc(p, 39)), 38))
6749 p = sp;
6750
6751 p = get_seq(args, &argc, p);
6752
6753notsgr:
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006754 arg1 = args[0];
6755 arg2 = args[1];
6756 if (*p == 'm')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006757 {
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006758 if (argc == 1 && args[0] == 0)
6759 normvideo();
6760 else if (argc == 1)
6761 {
Christopher Plewright38804d62022-11-09 23:55:52 +00006762 if (vtp_working
6763# ifdef FEAT_TERMGUICOLORS
6764 && (p_tgc || t_colors >= 256)
6765# endif
6766 )
6767 textcolor((WORD)arg1);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006768 else
Christopher Plewright38804d62022-11-09 23:55:52 +00006769 textattr((WORD)arg1);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006770 }
Christopher Plewright38804d62022-11-09 23:55:52 +00006771 else if (vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006772 vtp_sgr_bulks(argc, args);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006773 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006774 else if (argc == 2 && *p == 'H')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006775 {
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006776 gotoxy(arg2, arg1);
6777 }
6778 else if (argc == 2 && *p == 'r')
6779 {
6780 set_scroll_region(0, arg1 - 1, Columns - 1, arg2 - 1);
6781 }
Bram Moolenaar6982f422019-02-16 16:48:01 +01006782 else if (argc == 2 && *p == 'R')
6783 {
6784 set_scroll_region_tb(arg1, arg2);
6785 }
6786 else if (argc == 2 && *p == 'V')
6787 {
6788 set_scroll_region_lr(arg1, arg2);
6789 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006790 else if (argc == 1 && *p == 'A')
6791 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006792 gotoxy(g_coord.X + 1,
6793 max(g_srScrollRegion.Top, g_coord.Y - arg1) + 1);
6794 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006795 else if (argc == 1 && *p == 'b')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006796 {
6797 textbackground((WORD) arg1);
6798 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006799 else if (argc == 1 && *p == 'C')
6800 {
6801 gotoxy(min(g_srScrollRegion.Right, g_coord.X + arg1) + 1,
6802 g_coord.Y + 1);
6803 }
6804 else if (argc == 1 && *p == 'f')
6805 {
6806 textcolor((WORD) arg1);
6807 }
6808 else if (argc == 1 && *p == 'H')
6809 {
6810 gotoxy(1, arg1);
6811 }
6812 else if (argc == 1 && *p == 'L')
6813 {
6814 insert_lines(arg1);
6815 }
6816 else if (argc == 1 && *p == 'M')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006817 {
6818 delete_lines(arg1);
6819 }
6820
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006821 len -= (int)(p - s);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006822 s = p + 1;
6823 break;
6824
Bram Moolenaar071d4272004-06-13 20:20:40 +00006825 case 'A':
Bram Moolenaar071d4272004-06-13 20:20:40 +00006826 gotoxy(g_coord.X + 1,
6827 max(g_srScrollRegion.Top, g_coord.Y - 1) + 1);
6828 goto got3;
6829
6830 case 'B':
6831 visual_bell();
6832 goto got3;
6833
6834 case 'C':
Bram Moolenaar071d4272004-06-13 20:20:40 +00006835 gotoxy(min(g_srScrollRegion.Right, g_coord.X + 1) + 1,
6836 g_coord.Y + 1);
6837 goto got3;
6838
6839 case 'E':
6840 termcap_mode_end();
6841 goto got3;
6842
6843 case 'F':
6844 standout();
6845 goto got3;
6846
6847 case 'f':
6848 standend();
6849 goto got3;
6850
6851 case 'H':
6852 gotoxy(1, 1);
6853 goto got3;
6854
6855 case 'j':
6856 clear_to_end_of_display();
6857 goto got3;
6858
6859 case 'J':
6860 clear_screen();
6861 goto got3;
6862
6863 case 'K':
6864 clear_to_end_of_line();
6865 goto got3;
6866
6867 case 'L':
6868 insert_lines(1);
6869 goto got3;
6870
6871 case 'M':
6872 delete_lines(1);
6873 goto got3;
6874
6875 case 'S':
6876 termcap_mode_start();
6877 goto got3;
6878
6879 case 'V':
6880 cursor_visible(TRUE);
6881 goto got3;
6882
6883 case 'v':
6884 cursor_visible(FALSE);
6885 goto got3;
6886
6887 got3:
6888 s += 3;
6889 len -= 2;
6890 }
6891
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006892# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006893 if (fdDump)
6894 {
6895 fputs("ESC | ", fdDump);
6896 fwrite(old_s + 2, sizeof(char_u), s - old_s - 2, fdDump);
6897 fputc('\n', fdDump);
6898 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006899# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006900 }
K.Takatadf5320c2022-09-01 13:20:16 +01006901 else if (s[0] == ESC && len >= 3-1 && s[1] == '[')
6902 {
6903 int l = 2;
6904
6905 if (isdigit(s[l]))
6906 l++;
6907 if (s[l] == ' ' && s[l + 1] == 'q')
6908 {
6909 // DECSCUSR (cursor style) sequences
Christopher Plewright38804d62022-11-09 23:55:52 +00006910 if (vtp_working)
K.Takatadf5320c2022-09-01 13:20:16 +01006911 vtp_printf("%.*s", l + 2, s); // Pass through
6912 s += l + 2;
6913 len -= l + 1;
6914 }
6915 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006916 else
6917 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006918 // Write a single character
Bram Moolenaar071d4272004-06-13 20:20:40 +00006919 DWORD nWritten;
6920
6921 nWritten = write_chars(s, 1);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006922# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006923 if (fdDump)
6924 {
6925 fputc('>', fdDump);
6926 fwrite(s, sizeof(char_u), nWritten, fdDump);
6927 fputs("<\n", fdDump);
6928 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006929# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006930
6931 len -= (nWritten - 1);
6932 s += nWritten;
6933 }
6934 }
6935
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006936# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006937 if (fdDump)
6938 fflush(fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006939# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006940}
6941
Bram Moolenaar0f873732019-12-05 20:28:46 +01006942#endif // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00006943
6944
6945/*
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01006946 * Delay for "msec" milliseconds.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006947 */
6948 void
6949mch_delay(
6950 long msec,
Bram Moolenaar0981c872020-08-23 14:28:37 +02006951 int flags UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006952{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006953#if defined(FEAT_GUI_MSWIN) && !defined(VIMDLL)
Bram Moolenaar0f873732019-12-05 20:28:46 +01006954 Sleep((int)msec); // never wait for input
6955#else // Console
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006956# ifdef VIMDLL
6957 if (gui.in_use)
6958 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006959 Sleep((int)msec); // never wait for input
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006960 return;
6961 }
6962# endif
Bram Moolenaar0981c872020-08-23 14:28:37 +02006963 if (flags & MCH_DELAY_IGNOREINPUT)
Bram Moolenaar325b7a22004-07-05 15:58:32 +00006964# ifdef FEAT_MZSCHEME
6965 if (mzthreads_allowed() && p_mzq > 0 && msec > p_mzq)
6966 {
6967 int towait = p_mzq;
6968
Bram Moolenaar0f873732019-12-05 20:28:46 +01006969 // if msec is large enough, wait by portions in p_mzq
Bram Moolenaar325b7a22004-07-05 15:58:32 +00006970 while (msec > 0)
6971 {
6972 mzvim_check_threads();
6973 if (msec < towait)
6974 towait = msec;
6975 Sleep(towait);
6976 msec -= towait;
6977 }
6978 }
6979 else
6980# endif
6981 Sleep((int)msec);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006982 else
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02006983 WaitForChar(msec, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006984#endif
6985}
6986
6987
6988/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01006989 * This version of remove is not scared by a readonly (backup) file.
6990 * This can also remove a symbolic link like Unix.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006991 * Return 0 for success, -1 for failure.
6992 */
6993 int
6994mch_remove(char_u *name)
6995{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006996 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006997 int n;
6998
Bram Moolenaar203258c2016-01-17 22:15:16 +01006999 /*
7000 * On Windows, deleting a directory's symbolic link is done by
7001 * RemoveDirectory(): mch_rmdir. It seems unnatural, but it is fact.
7002 */
7003 if (mch_isdir(name) && mch_is_symbolic_link(name))
7004 return mch_rmdir(name);
7005
Bram Moolenaar12b559e2013-06-12 22:41:37 +02007006 win32_setattrs(name, FILE_ATTRIBUTE_NORMAL);
7007
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007008 wn = enc_to_utf16(name, NULL);
7009 if (wn == NULL)
7010 return -1;
7011
7012 n = DeleteFileW(wn) ? 0 : -1;
7013 vim_free(wn);
7014 return n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007015}
7016
7017
7018/*
Bram Moolenaarb9c31e72016-09-29 15:18:57 +02007019 * Check for an "interrupt signal": CTRL-break or CTRL-C.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007020 */
7021 void
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02007022mch_breakcheck(int force UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007023{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007024#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
7025# ifdef VIMDLL
7026 if (!gui.in_use)
7027# endif
7028 if (g_fCtrlCPressed || g_fCBrkPressed)
7029 {
7030 ctrl_break_was_pressed = g_fCBrkPressed;
7031 g_fCtrlCPressed = g_fCBrkPressed = FALSE;
7032 got_int = TRUE;
7033 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007034#endif
7035}
7036
Bram Moolenaar0f873732019-12-05 20:28:46 +01007037// physical RAM to leave for the OS
Bram Moolenaaree273972016-01-02 21:11:51 +01007038#define WINNT_RESERVE_BYTES (256*1024*1024)
Bram Moolenaaree273972016-01-02 21:11:51 +01007039
7040/*
7041 * How much main memory in KiB that can be used by VIM.
7042 */
Bram Moolenaaree273972016-01-02 21:11:51 +01007043 long_u
Bram Moolenaar1266d672017-02-01 13:43:36 +01007044mch_total_mem(int special UNUSED)
Bram Moolenaaree273972016-01-02 21:11:51 +01007045{
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007046 MEMORYSTATUSEX ms;
7047
Bram Moolenaar0f873732019-12-05 20:28:46 +01007048 // Need to use GlobalMemoryStatusEx() when there is more memory than
7049 // what fits in 32 bits.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007050 ms.dwLength = sizeof(MEMORYSTATUSEX);
7051 GlobalMemoryStatusEx(&ms);
7052 if (ms.ullAvailVirtual < ms.ullTotalPhys)
Bram Moolenaaree273972016-01-02 21:11:51 +01007053 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007054 // Process address space fits in physical RAM, use all of it.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007055 return (long_u)(ms.ullAvailVirtual / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01007056 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007057 if (ms.ullTotalPhys <= WINNT_RESERVE_BYTES)
Bram Moolenaaree273972016-01-02 21:11:51 +01007058 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007059 // Catch old NT box or perverse hardware setup.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007060 return (long_u)((ms.ullTotalPhys / 2) / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01007061 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01007062 // Use physical RAM less reserve for OS + data.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007063 return (long_u)((ms.ullTotalPhys - WINNT_RESERVE_BYTES) / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01007064}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007065
Bram Moolenaar071d4272004-06-13 20:20:40 +00007066/*
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007067 * mch_wrename() works around a bug in rename (aka MoveFile) in
Bram Moolenaar071d4272004-06-13 20:20:40 +00007068 * Windows 95: rename("foo.bar", "foo.bar~") will generate a
7069 * file whose short file name is "FOO.BAR" (its long file name will
7070 * be correct: "foo.bar~"). Because a file can be accessed by
7071 * either its SFN or its LFN, "foo.bar" has effectively been
7072 * renamed to "foo.bar", which is not at all what was wanted. This
7073 * seems to happen only when renaming files with three-character
7074 * extensions by appending a suffix that does not include ".".
7075 * Windows NT gets it right, however, with an SFN of "FOO~1.BAR".
7076 *
7077 * There is another problem, which isn't really a bug but isn't right either:
7078 * When renaming "abcdef~1.txt" to "abcdef~1.txt~", the short name can be
7079 * "abcdef~1.txt" again. This has been reported on Windows NT 4.0 with
7080 * service pack 6. Doesn't seem to happen on Windows 98.
7081 *
7082 * Like rename(), returns 0 upon success, non-zero upon failure.
7083 * Should probably set errno appropriately when errors occur.
7084 */
7085 int
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007086mch_wrename(WCHAR *wold, WCHAR *wnew)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007087{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007088 WCHAR *p;
7089 int i;
7090 WCHAR szTempFile[_MAX_PATH + 1];
7091 WCHAR szNewPath[_MAX_PATH + 1];
Bram Moolenaar071d4272004-06-13 20:20:40 +00007092 HANDLE hf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007093
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007094 // No need to play tricks unless the file name contains a "~" as the
7095 // seventh character.
7096 p = wold;
7097 for (i = 0; wold[i] != NUL; ++i)
7098 if ((wold[i] == '/' || wold[i] == '\\' || wold[i] == ':')
7099 && wold[i + 1] != 0)
7100 p = wold + i + 1;
7101 if ((int)(wold + i - p) < 8 || p[6] != '~')
7102 return (MoveFileW(wold, wnew) == 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007103
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007104 // Get base path of new file name. Undocumented feature: If pszNewFile is
7105 // a directory, no error is returned and pszFilePart will be NULL.
7106 if (GetFullPathNameW(wnew, _MAX_PATH, szNewPath, &p) == 0 || p == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007107 return -1;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007108 *p = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007109
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007110 // Get (and create) a unique temporary file name in directory of new file
7111 if (GetTempFileNameW(szNewPath, L"VIM", 0, szTempFile) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007112 return -2;
7113
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007114 // blow the temp file away
7115 if (!DeleteFileW(szTempFile))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007116 return -3;
7117
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007118 // rename old file to the temp file
7119 if (!MoveFileW(wold, szTempFile))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007120 return -4;
7121
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007122 // now create an empty file called pszOldFile; this prevents the operating
7123 // system using pszOldFile as an alias (SFN) if we're renaming within the
7124 // same directory. For example, we're editing a file called
7125 // filename.asc.txt by its SFN, filena~1.txt. If we rename filena~1.txt
7126 // to filena~1.txt~ (i.e., we're making a backup while writing it), the
7127 // SFN for filena~1.txt~ will be filena~1.txt, by default, which will
7128 // cause all sorts of problems later in buf_write(). So, we create an
7129 // empty file called filena~1.txt and the system will have to find some
7130 // other SFN for filena~1.txt~, such as filena~2.txt
7131 if ((hf = CreateFileW(wold, GENERIC_WRITE, 0, NULL, CREATE_NEW,
Bram Moolenaar071d4272004-06-13 20:20:40 +00007132 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
7133 return -5;
7134 if (!CloseHandle(hf))
7135 return -6;
7136
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007137 // rename the temp file to the new file
7138 if (!MoveFileW(szTempFile, wnew))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007139 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007140 // Renaming failed. Rename the file back to its old name, so that it
7141 // looks like nothing happened.
7142 (void)MoveFileW(szTempFile, wold);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007143 return -7;
7144 }
7145
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007146 // Seems to be left around on Novell filesystems
7147 DeleteFileW(szTempFile);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007148
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007149 // finally, remove the empty old file
7150 if (!DeleteFileW(wold))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007151 return -8;
7152
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007153 return 0;
7154}
7155
7156
7157/*
7158 * Converts the filenames to UTF-16, then call mch_wrename().
7159 * Like rename(), returns 0 upon success, non-zero upon failure.
7160 */
7161 int
7162mch_rename(
7163 const char *pszOldFile,
7164 const char *pszNewFile)
7165{
7166 WCHAR *wold = NULL;
7167 WCHAR *wnew = NULL;
7168 int retval = -1;
7169
7170 wold = enc_to_utf16((char_u *)pszOldFile, NULL);
7171 wnew = enc_to_utf16((char_u *)pszNewFile, NULL);
7172 if (wold != NULL && wnew != NULL)
7173 retval = mch_wrename(wold, wnew);
7174 vim_free(wold);
7175 vim_free(wnew);
7176 return retval;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007177}
7178
7179/*
7180 * Get the default shell for the current hardware platform
7181 */
7182 char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007183default_shell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007184{
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007185 return "cmd.exe";
Bram Moolenaar071d4272004-06-13 20:20:40 +00007186}
7187
7188/*
7189 * mch_access() extends access() to do more detailed check on network drives.
7190 * Returns 0 if file "n" has access rights according to "p", -1 otherwise.
7191 */
7192 int
7193mch_access(char *n, int p)
7194{
7195 HANDLE hFile;
Bram Moolenaar0f873732019-12-05 20:28:46 +01007196 int retval = -1; // default: fail
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007197 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007198
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007199 wn = enc_to_utf16((char_u *)n, NULL);
7200 if (wn == NULL)
7201 return -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007202
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01007203 if (mch_isdir((char_u *)n))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007204 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00007205 WCHAR TempNameW[_MAX_PATH + 16] = L"";
Bram Moolenaar071d4272004-06-13 20:20:40 +00007206
7207 if (p & R_OK)
7208 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007209 // Read check is performed by seeing if we can do a find file on
7210 // the directory for any file.
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007211 int i;
7212 WIN32_FIND_DATAW d;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007213
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007214 for (i = 0; i < _MAX_PATH && wn[i] != 0; ++i)
7215 TempNameW[i] = wn[i];
7216 if (TempNameW[i - 1] != '\\' && TempNameW[i - 1] != '/')
7217 TempNameW[i++] = '\\';
7218 TempNameW[i++] = '*';
7219 TempNameW[i++] = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007220
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007221 hFile = FindFirstFileW(TempNameW, &d);
7222 if (hFile == INVALID_HANDLE_VALUE)
7223 goto getout;
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007224 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00007225 (void)FindClose(hFile);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007226 }
7227
7228 if (p & W_OK)
7229 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007230 // Trying to create a temporary file in the directory should catch
7231 // directories on read-only network shares. However, in
7232 // directories whose ACL allows writes but denies deletes will end
7233 // up keeping the temporary file :-(.
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007234 if (!GetTempFileNameW(wn, L"VIM", 0, TempNameW))
7235 goto getout;
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007236 else
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007237 DeleteFileW(TempNameW);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007238 }
7239 }
7240 else
7241 {
Bram Moolenaar5aa98962018-05-06 17:09:38 +02007242 // Don't consider a file read-only if another process has opened it.
7243 DWORD share_mode = FILE_SHARE_READ | FILE_SHARE_WRITE;
7244
Bram Moolenaar0f873732019-12-05 20:28:46 +01007245 // Trying to open the file for the required access does ACL, read-only
7246 // network share, and file attribute checks.
Bram Moolenaar5aa98962018-05-06 17:09:38 +02007247 DWORD access_mode = ((p & W_OK) ? GENERIC_WRITE : 0)
7248 | ((p & R_OK) ? GENERIC_READ : 0);
7249
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007250 hFile = CreateFileW(wn, access_mode, share_mode,
7251 NULL, OPEN_EXISTING, 0, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007252 if (hFile == INVALID_HANDLE_VALUE)
7253 goto getout;
7254 CloseHandle(hFile);
7255 }
7256
Bram Moolenaar0f873732019-12-05 20:28:46 +01007257 retval = 0; // success
Bram Moolenaar071d4272004-06-13 20:20:40 +00007258getout:
Bram Moolenaar071d4272004-06-13 20:20:40 +00007259 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007260 return retval;
7261}
7262
Bram Moolenaar071d4272004-06-13 20:20:40 +00007263/*
Bram Moolenaar36f692d2008-11-20 16:10:17 +00007264 * Version of open() that may use UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007265 */
7266 int
Bram Moolenaarb6843a02017-08-02 22:07:12 +02007267mch_open(const char *name, int flags, int mode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007268{
7269 WCHAR *wn;
7270 int f;
7271
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007272 wn = enc_to_utf16((char_u *)name, NULL);
7273 if (wn == NULL)
7274 return -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007275
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007276 f = _wopen(wn, flags, mode);
7277 vim_free(wn);
7278 return f;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007279}
7280
7281/*
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007282 * Version of fopen() that uses UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007283 */
7284 FILE *
Bram Moolenaarb6843a02017-08-02 22:07:12 +02007285mch_fopen(const char *name, const char *mode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007286{
7287 WCHAR *wn, *wm;
7288 FILE *f = NULL;
7289
Bram Moolenaara12a1612019-01-24 16:39:02 +01007290#if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0f873732019-12-05 20:28:46 +01007291 // Work around an annoying assertion in the Microsoft debug CRT
7292 // when mode's text/binary setting doesn't match _get_fmode().
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007293 char newMode = mode[strlen(mode) - 1];
7294 int oldMode = 0;
Bram Moolenaar0fde2902008-03-16 13:54:13 +00007295
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007296 _get_fmode(&oldMode);
7297 if (newMode == 't')
7298 _set_fmode(_O_TEXT);
7299 else if (newMode == 'b')
7300 _set_fmode(_O_BINARY);
Bram Moolenaara12a1612019-01-24 16:39:02 +01007301#endif
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007302 wn = enc_to_utf16((char_u *)name, NULL);
7303 wm = enc_to_utf16((char_u *)mode, NULL);
7304 if (wn != NULL && wm != NULL)
7305 f = _wfopen(wn, wm);
7306 vim_free(wn);
7307 vim_free(wm);
Bram Moolenaar0fde2902008-03-16 13:54:13 +00007308
Bram Moolenaara12a1612019-01-24 16:39:02 +01007309#if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007310 _set_fmode(oldMode);
Bram Moolenaara12a1612019-01-24 16:39:02 +01007311#endif
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007312 return f;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007313}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007314
Bram Moolenaar071d4272004-06-13 20:20:40 +00007315/*
7316 * SUB STREAM (aka info stream) handling:
7317 *
Bram Moolenaar8e7d6222020-12-18 19:49:56 +01007318 * NTFS can have sub streams for each file. The normal contents of a file is
7319 * stored in the main stream, and extra contents (author information, title and
7320 * so on) can be stored in a sub stream. After Windows 2000, the user can
7321 * access and store this information in sub streams via an explorer's property
7322 * menu item in the right click menu. This information in sub streams was lost
7323 * when copying only the main stream. Therefore we have to copy sub streams.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007324 *
7325 * Incomplete explanation:
7326 * http://msdn.microsoft.com/library/en-us/dnw2k/html/ntfs5.asp
7327 * More useful info and an example:
7328 * http://www.sysinternals.com/ntw2k/source/misc.shtml#streams
7329 */
7330
7331/*
7332 * Copy info stream data "substream". Read from the file with BackupRead(sh)
7333 * and write to stream "substream" of file "to".
7334 * Errors are ignored.
7335 */
7336 static void
7337copy_substream(HANDLE sh, void *context, WCHAR *to, WCHAR *substream, long len)
7338{
7339 HANDLE hTo;
7340 WCHAR *to_name;
7341
7342 to_name = malloc((wcslen(to) + wcslen(substream) + 1) * sizeof(WCHAR));
7343 wcscpy(to_name, to);
7344 wcscat(to_name, substream);
7345
7346 hTo = CreateFileW(to_name, GENERIC_WRITE, 0, NULL, OPEN_ALWAYS,
7347 FILE_ATTRIBUTE_NORMAL, NULL);
7348 if (hTo != INVALID_HANDLE_VALUE)
7349 {
7350 long done;
7351 DWORD todo;
7352 DWORD readcnt, written;
7353 char buf[4096];
7354
Bram Moolenaar0f873732019-12-05 20:28:46 +01007355 // Copy block of bytes at a time. Abort when something goes wrong.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007356 for (done = 0; done < len; done += written)
7357 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007358 // (size_t) cast for Borland C 5.5
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007359 todo = (DWORD)((size_t)(len - done) > sizeof(buf) ? sizeof(buf)
7360 : (size_t)(len - done));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007361 if (!BackupRead(sh, (LPBYTE)buf, todo, &readcnt,
7362 FALSE, FALSE, context)
7363 || readcnt != todo
7364 || !WriteFile(hTo, buf, todo, &written, NULL)
7365 || written != todo)
7366 break;
7367 }
7368 CloseHandle(hTo);
7369 }
7370
7371 free(to_name);
7372}
7373
7374/*
7375 * Copy info streams from file "from" to file "to".
7376 */
7377 static void
7378copy_infostreams(char_u *from, char_u *to)
7379{
7380 WCHAR *fromw;
7381 WCHAR *tow;
7382 HANDLE sh;
7383 WIN32_STREAM_ID sid;
7384 int headersize;
7385 WCHAR streamname[_MAX_PATH];
7386 DWORD readcount;
7387 void *context = NULL;
7388 DWORD lo, hi;
7389 int len;
7390
Bram Moolenaar0f873732019-12-05 20:28:46 +01007391 // Convert the file names to wide characters.
Bram Moolenaar36f692d2008-11-20 16:10:17 +00007392 fromw = enc_to_utf16(from, NULL);
7393 tow = enc_to_utf16(to, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007394 if (fromw != NULL && tow != NULL)
7395 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007396 // Open the file for reading.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007397 sh = CreateFileW(fromw, GENERIC_READ, FILE_SHARE_READ, NULL,
7398 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
7399 if (sh != INVALID_HANDLE_VALUE)
7400 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007401 // Use BackupRead() to find the info streams. Repeat until we
7402 // have done them all.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007403 for (;;)
7404 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007405 // Get the header to find the length of the stream name. If
7406 // the "readcount" is zero we have done all info streams.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007407 ZeroMemory(&sid, sizeof(WIN32_STREAM_ID));
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007408 headersize = (int)((char *)&sid.cStreamName - (char *)&sid.dwStreamId);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007409 if (!BackupRead(sh, (LPBYTE)&sid, headersize,
7410 &readcount, FALSE, FALSE, &context)
7411 || readcount == 0)
7412 break;
7413
Bram Moolenaar0f873732019-12-05 20:28:46 +01007414 // We only deal with streams that have a name. The normal
7415 // file data appears to be without a name, even though docs
7416 // suggest it is called "::$DATA".
Bram Moolenaar071d4272004-06-13 20:20:40 +00007417 if (sid.dwStreamNameSize > 0)
7418 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007419 // Read the stream name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007420 if (!BackupRead(sh, (LPBYTE)streamname,
7421 sid.dwStreamNameSize,
7422 &readcount, FALSE, FALSE, &context))
7423 break;
7424
Bram Moolenaar0f873732019-12-05 20:28:46 +01007425 // Copy an info stream with a name ":anything:$DATA".
7426 // Skip "::$DATA", it has no stream name (examples suggest
7427 // it might be used for the normal file contents).
7428 // Note that BackupRead() counts bytes, but the name is in
7429 // wide characters.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007430 len = readcount / sizeof(WCHAR);
7431 streamname[len] = 0;
7432 if (len > 7 && wcsicmp(streamname + len - 6,
7433 L":$DATA") == 0)
7434 {
7435 streamname[len - 6] = 0;
7436 copy_substream(sh, &context, tow, streamname,
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00007437 (long)sid.Size.u.LowPart);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007438 }
7439 }
7440
Bram Moolenaar0f873732019-12-05 20:28:46 +01007441 // Advance to the next stream. We might try seeking too far,
7442 // but BackupSeek() doesn't skip over stream borders, thus
7443 // that's OK.
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00007444 (void)BackupSeek(sh, sid.Size.u.LowPart, sid.Size.u.HighPart,
Bram Moolenaar071d4272004-06-13 20:20:40 +00007445 &lo, &hi, &context);
7446 }
7447
Bram Moolenaar0f873732019-12-05 20:28:46 +01007448 // Clear the context.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007449 (void)BackupRead(sh, NULL, 0, &readcount, TRUE, FALSE, &context);
7450
7451 CloseHandle(sh);
7452 }
7453 }
7454 vim_free(fromw);
7455 vim_free(tow);
7456}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007457
7458/*
Bram Moolenaare7bebc42021-02-01 20:50:37 +01007459 * ntdll.dll definitions
7460 */
7461#define FileEaInformation 7
7462#ifndef STATUS_SUCCESS
7463# define STATUS_SUCCESS ((NTSTATUS) 0x00000000L)
7464#endif
7465
7466typedef struct _FILE_FULL_EA_INFORMATION_ {
7467 ULONG NextEntryOffset;
7468 UCHAR Flags;
7469 UCHAR EaNameLength;
7470 USHORT EaValueLength;
7471 CHAR EaName[1];
7472} FILE_FULL_EA_INFORMATION_, *PFILE_FULL_EA_INFORMATION_;
7473
7474typedef struct _FILE_EA_INFORMATION_ {
7475 ULONG EaSize;
7476} FILE_EA_INFORMATION_, *PFILE_EA_INFORMATION_;
7477
Paul Ollis65745772022-06-05 16:55:54 +01007478#ifndef PROTO
Bram Moolenaare7bebc42021-02-01 20:50:37 +01007479typedef NTSTATUS (NTAPI *PfnNtOpenFile)(
7480 PHANDLE FileHandle,
7481 ACCESS_MASK DesiredAccess,
7482 POBJECT_ATTRIBUTES ObjectAttributes,
7483 PIO_STATUS_BLOCK IoStatusBlock,
7484 ULONG ShareAccess,
7485 ULONG OpenOptions);
7486typedef NTSTATUS (NTAPI *PfnNtClose)(
7487 HANDLE Handle);
7488typedef NTSTATUS (NTAPI *PfnNtSetEaFile)(
Bram Moolenaar9f1983d2022-05-12 20:35:35 +01007489 HANDLE FileHandle,
7490 PIO_STATUS_BLOCK IoStatusBlock,
7491 PVOID Buffer,
7492 ULONG Length);
Bram Moolenaare7bebc42021-02-01 20:50:37 +01007493typedef NTSTATUS (NTAPI *PfnNtQueryEaFile)(
7494 HANDLE FileHandle,
7495 PIO_STATUS_BLOCK IoStatusBlock,
7496 PVOID Buffer,
7497 ULONG Length,
7498 BOOLEAN ReturnSingleEntry,
7499 PVOID EaList,
7500 ULONG EaListLength,
7501 PULONG EaIndex,
7502 BOOLEAN RestartScan);
7503typedef NTSTATUS (NTAPI *PfnNtQueryInformationFile)(
Bram Moolenaar9f1983d2022-05-12 20:35:35 +01007504 HANDLE FileHandle,
7505 PIO_STATUS_BLOCK IoStatusBlock,
7506 PVOID FileInformation,
7507 ULONG Length,
Bram Moolenaare7bebc42021-02-01 20:50:37 +01007508 FILE_INFORMATION_CLASS FileInformationClass);
7509typedef VOID (NTAPI *PfnRtlInitUnicodeString)(
7510 PUNICODE_STRING DestinationString,
7511 PCWSTR SourceString);
7512
7513PfnNtOpenFile pNtOpenFile = NULL;
7514PfnNtClose pNtClose = NULL;
7515PfnNtSetEaFile pNtSetEaFile = NULL;
7516PfnNtQueryEaFile pNtQueryEaFile = NULL;
7517PfnNtQueryInformationFile pNtQueryInformationFile = NULL;
7518PfnRtlInitUnicodeString pRtlInitUnicodeString = NULL;
Paul Ollis65745772022-06-05 16:55:54 +01007519#endif
Bram Moolenaare7bebc42021-02-01 20:50:37 +01007520
7521/*
7522 * Load ntdll.dll functions.
7523 */
7524 static BOOL
7525load_ntdll(void)
7526{
7527 static int loaded = -1;
7528
7529 if (loaded == -1)
7530 {
7531 HMODULE hNtdll = GetModuleHandle("ntdll.dll");
7532 if (hNtdll != NULL)
7533 {
7534 pNtOpenFile = (PfnNtOpenFile) GetProcAddress(hNtdll, "NtOpenFile");
7535 pNtClose = (PfnNtClose) GetProcAddress(hNtdll, "NtClose");
7536 pNtSetEaFile = (PfnNtSetEaFile)
7537 GetProcAddress(hNtdll, "NtSetEaFile");
7538 pNtQueryEaFile = (PfnNtQueryEaFile)
7539 GetProcAddress(hNtdll, "NtQueryEaFile");
7540 pNtQueryInformationFile = (PfnNtQueryInformationFile)
7541 GetProcAddress(hNtdll, "NtQueryInformationFile");
7542 pRtlInitUnicodeString = (PfnRtlInitUnicodeString)
7543 GetProcAddress(hNtdll, "RtlInitUnicodeString");
7544 }
7545 if (pNtOpenFile == NULL
7546 || pNtClose == NULL
7547 || pNtSetEaFile == NULL
7548 || pNtQueryEaFile == NULL
7549 || pNtQueryInformationFile == NULL
7550 || pRtlInitUnicodeString == NULL)
7551 loaded = FALSE;
7552 else
7553 loaded = TRUE;
7554 }
7555 return (BOOL) loaded;
7556}
7557
7558/*
7559 * Copy extended attributes (EA) from file "from" to file "to".
7560 */
7561 static void
7562copy_extattr(char_u *from, char_u *to)
7563{
7564 char_u *fromf = NULL;
7565 char_u *tof = NULL;
7566 WCHAR *fromw = NULL;
7567 WCHAR *tow = NULL;
7568 UNICODE_STRING u;
7569 HANDLE h;
7570 OBJECT_ATTRIBUTES oa;
7571 IO_STATUS_BLOCK iosb;
7572 FILE_EA_INFORMATION_ eainfo = {0};
7573 void *ea = NULL;
7574
7575 if (!load_ntdll())
7576 return;
7577
7578 // Convert the file names to the fully qualified object names.
7579 fromf = alloc(STRLEN(from) + 5);
7580 tof = alloc(STRLEN(to) + 5);
7581 if (fromf == NULL || tof == NULL)
7582 goto theend;
7583 STRCPY(fromf, "\\??\\");
7584 STRCAT(fromf, from);
7585 STRCPY(tof, "\\??\\");
7586 STRCAT(tof, to);
7587
7588 // Convert the names to wide characters.
7589 fromw = enc_to_utf16(fromf, NULL);
7590 tow = enc_to_utf16(tof, NULL);
7591 if (fromw == NULL || tow == NULL)
7592 goto theend;
7593
7594 // Get the EA.
7595 pRtlInitUnicodeString(&u, fromw);
7596 InitializeObjectAttributes(&oa, &u, 0, NULL, NULL);
7597 if (pNtOpenFile(&h, FILE_READ_EA, &oa, &iosb, 0,
7598 FILE_NON_DIRECTORY_FILE) != STATUS_SUCCESS)
7599 goto theend;
7600 pNtQueryInformationFile(h, &iosb, &eainfo, sizeof(eainfo),
7601 FileEaInformation);
7602 if (eainfo.EaSize != 0)
7603 {
7604 ea = alloc(eainfo.EaSize);
7605 if (ea != NULL)
7606 {
7607 if (pNtQueryEaFile(h, &iosb, ea, eainfo.EaSize, FALSE,
7608 NULL, 0, NULL, TRUE) != STATUS_SUCCESS)
7609 {
7610 vim_free(ea);
7611 ea = NULL;
7612 }
7613 }
7614 }
7615 pNtClose(h);
7616
7617 // Set the EA.
7618 if (ea != NULL)
7619 {
7620 pRtlInitUnicodeString(&u, tow);
7621 InitializeObjectAttributes(&oa, &u, 0, NULL, NULL);
7622 if (pNtOpenFile(&h, FILE_WRITE_EA, &oa, &iosb, 0,
7623 FILE_NON_DIRECTORY_FILE) != STATUS_SUCCESS)
7624 goto theend;
7625
7626 pNtSetEaFile(h, &iosb, ea, eainfo.EaSize);
7627 pNtClose(h);
7628 }
7629
7630theend:
7631 vim_free(fromf);
7632 vim_free(tof);
7633 vim_free(fromw);
7634 vim_free(tow);
7635 vim_free(ea);
7636}
7637
7638/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00007639 * Copy file attributes from file "from" to file "to".
7640 * For Windows NT and later we copy info streams.
7641 * Always returns zero, errors are ignored.
7642 */
7643 int
7644mch_copy_file_attribute(char_u *from, char_u *to)
7645{
Bram Moolenaar0f873732019-12-05 20:28:46 +01007646 // File streams only work on Windows NT and later.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007647 copy_infostreams(from, to);
Bram Moolenaare7bebc42021-02-01 20:50:37 +01007648 copy_extattr(from, to);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007649 return 0;
7650}
7651
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007652
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007653/*
K.Takatadc73b4b2021-06-08 18:32:36 +02007654 * The command line arguments in UTF-16
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007655 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00007656static int nArgsW = 0;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007657static LPWSTR *ArglistW = NULL;
7658static int global_argc = 0;
7659static char **global_argv;
7660
Bram Moolenaar0f873732019-12-05 20:28:46 +01007661static int used_file_argc = 0; // last argument in global_argv[] used
7662 // for the argument list.
7663static int *used_file_indexes = NULL; // indexes in global_argv[] for
7664 // command line arguments added to
7665 // the argument list
7666static int used_file_count = 0; // nr of entries in used_file_indexes
7667static int used_file_literal = FALSE; // take file names literally
7668static int used_file_full_path = FALSE; // file name was full path
7669static int used_file_diff_mode = FALSE; // file name was with diff mode
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007670static int used_alist_count = 0;
7671
7672
7673/*
7674 * Get the command line arguments. Unicode version.
7675 * Returns argc. Zero when something fails.
7676 */
7677 int
7678get_cmd_argsW(char ***argvp)
7679{
7680 char **argv = NULL;
7681 int argc = 0;
7682 int i;
7683
Bram Moolenaar14993322014-09-09 12:25:33 +02007684 free_cmd_argsW();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007685 ArglistW = CommandLineToArgvW(GetCommandLineW(), &nArgsW);
7686 if (ArglistW != NULL)
7687 {
7688 argv = malloc((nArgsW + 1) * sizeof(char *));
7689 if (argv != NULL)
7690 {
7691 argc = nArgsW;
7692 argv[argc] = NULL;
7693 for (i = 0; i < argc; ++i)
7694 {
7695 int len;
7696
K.Takatadc73b4b2021-06-08 18:32:36 +02007697 // Convert each Unicode argument to UTF-8.
7698 WideCharToMultiByte_alloc(CP_UTF8, 0,
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007699 ArglistW[i], (int)wcslen(ArglistW[i]) + 1,
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007700 (LPSTR *)&argv[i], &len, 0, 0);
7701 if (argv[i] == NULL)
7702 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007703 // Out of memory, clear everything.
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007704 while (i > 0)
7705 free(argv[--i]);
7706 free(argv);
Bram Moolenaar73c61632013-12-07 14:48:10 +01007707 argv = NULL;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007708 argc = 0;
7709 }
7710 }
7711 }
7712 }
7713
7714 global_argc = argc;
7715 global_argv = argv;
7716 if (argc > 0)
Bram Moolenaar14993322014-09-09 12:25:33 +02007717 {
7718 if (used_file_indexes != NULL)
7719 free(used_file_indexes);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007720 used_file_indexes = malloc(argc * sizeof(int));
Bram Moolenaar14993322014-09-09 12:25:33 +02007721 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007722
7723 if (argvp != NULL)
7724 *argvp = argv;
7725 return argc;
7726}
7727
7728 void
7729free_cmd_argsW(void)
7730{
7731 if (ArglistW != NULL)
7732 {
7733 GlobalFree(ArglistW);
7734 ArglistW = NULL;
7735 }
7736}
7737
7738/*
7739 * Remember "name" is an argument that was added to the argument list.
7740 * This avoids that we have to re-parse the argument list when fix_arg_enc()
7741 * is called.
7742 */
7743 void
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007744used_file_arg(char *name, int literal, int full_path, int diff_mode)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007745{
7746 int i;
7747
7748 if (used_file_indexes == NULL)
7749 return;
7750 for (i = used_file_argc + 1; i < global_argc; ++i)
7751 if (STRCMP(global_argv[i], name) == 0)
7752 {
7753 used_file_argc = i;
7754 used_file_indexes[used_file_count++] = i;
7755 break;
7756 }
7757 used_file_literal = literal;
7758 used_file_full_path = full_path;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007759 used_file_diff_mode = diff_mode;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007760}
7761
7762/*
7763 * Remember the length of the argument list as it was. If it changes then we
7764 * leave it alone when 'encoding' is set.
7765 */
7766 void
7767set_alist_count(void)
7768{
7769 used_alist_count = GARGCOUNT;
7770}
7771
7772/*
7773 * Fix the encoding of the command line arguments. Invoked when 'encoding'
K.Takatadc73b4b2021-06-08 18:32:36 +02007774 * has been changed while starting up. Use the UTF-16 command line arguments
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007775 * and convert them to 'encoding'.
7776 */
7777 void
7778fix_arg_enc(void)
7779{
7780 int i;
7781 int idx;
7782 char_u *str;
Bram Moolenaar86b68352004-12-27 21:59:20 +00007783 int *fnum_list;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007784
Bram Moolenaar0f873732019-12-05 20:28:46 +01007785 // Safety checks:
7786 // - if argument count differs between the wide and non-wide argument
7787 // list, something must be wrong.
7788 // - the file name arguments must have been located.
7789 // - the length of the argument list wasn't changed by the user.
Bram Moolenaard857f0e2005-06-21 22:37:39 +00007790 if (global_argc != nArgsW
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007791 || ArglistW == NULL
7792 || used_file_indexes == NULL
7793 || used_file_count == 0
7794 || used_alist_count != GARGCOUNT)
7795 return;
7796
Bram Moolenaar0f873732019-12-05 20:28:46 +01007797 // Remember the buffer numbers for the arguments.
Bram Moolenaarc799fe22019-05-28 23:08:19 +02007798 fnum_list = ALLOC_MULT(int, GARGCOUNT);
Bram Moolenaar86b68352004-12-27 21:59:20 +00007799 if (fnum_list == NULL)
Bram Moolenaar0f873732019-12-05 20:28:46 +01007800 return; // out of memory
Bram Moolenaar86b68352004-12-27 21:59:20 +00007801 for (i = 0; i < GARGCOUNT; ++i)
7802 fnum_list[i] = GARGLIST[i].ae_fnum;
7803
Bram Moolenaar0f873732019-12-05 20:28:46 +01007804 // Clear the argument list. Make room for the new arguments.
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007805 alist_clear(&global_alist);
7806 if (ga_grow(&global_alist.al_ga, used_file_count) == FAIL)
Bram Moolenaar0f873732019-12-05 20:28:46 +01007807 return; // out of memory
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007808
7809 for (i = 0; i < used_file_count; ++i)
7810 {
7811 idx = used_file_indexes[i];
Bram Moolenaar36f692d2008-11-20 16:10:17 +00007812 str = utf16_to_enc(ArglistW[idx], NULL);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007813 if (str != NULL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00007814 {
Bram Moolenaar39d21e32017-08-05 23:09:31 +02007815 int literal = used_file_literal;
7816
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007817#ifdef FEAT_DIFF
Bram Moolenaar0f873732019-12-05 20:28:46 +01007818 // When using diff mode may need to concatenate file name to
7819 // directory name. Just like it's done in main().
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007820 if (used_file_diff_mode && mch_isdir(str) && GARGCOUNT > 0
7821 && !mch_isdir(alist_name(&GARGLIST[0])))
7822 {
7823 char_u *r;
7824
7825 r = concat_fnames(str, gettail(alist_name(&GARGLIST[0])), TRUE);
7826 if (r != NULL)
7827 {
7828 vim_free(str);
7829 str = r;
7830 }
7831 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007832#endif
Bram Moolenaar0f873732019-12-05 20:28:46 +01007833 // Re-use the old buffer by renaming it. When not using literal
7834 // names it's done by alist_expand() below.
Bram Moolenaar86b68352004-12-27 21:59:20 +00007835 if (used_file_literal)
7836 buf_set_name(fnum_list[i], str);
7837
Bram Moolenaar0f873732019-12-05 20:28:46 +01007838 // Check backtick literal. backtick literal is already expanded in
7839 // main.c, so this part add str as literal.
Bram Moolenaar39d21e32017-08-05 23:09:31 +02007840 if (literal == FALSE)
7841 {
Bram Moolenaar116a0f82017-08-07 21:17:57 +02007842 size_t len = STRLEN(str);
7843
Bram Moolenaar39d21e32017-08-05 23:09:31 +02007844 if (len > 2 && *str == '`' && *(str + len - 1) == '`')
7845 literal = TRUE;
7846 }
7847 alist_add(&global_alist, str, literal ? 2 : 0);
Bram Moolenaar86b68352004-12-27 21:59:20 +00007848 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007849 }
7850
7851 if (!used_file_literal)
7852 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007853 // Now expand wildcards in the arguments.
7854 // Temporarily add '(' and ')' to 'isfname'. These are valid
7855 // filename characters but are excluded from 'isfname' to make
Dominique Pelleaf4a61a2021-12-27 17:21:41 +00007856 // "gf" work on a file name in parentheses (e.g.: see vim.h).
Bram Moolenaar0f873732019-12-05 20:28:46 +01007857 // Also, unset wildignore to not be influenced by this option.
7858 // The arguments specified in command-line should be kept even if
7859 // encoding options were changed.
Christian Brabandtfd916d62021-11-01 22:44:33 +00007860 // Use :legacy so that it also works when in Vim9 script.
7861 do_cmdline_cmd((char_u *)":legacy let g:SaVe_ISF = &isf|set isf+=(,)");
7862 do_cmdline_cmd((char_u *)":legacy let g:SaVe_WIG = &wig|set wig=");
Bram Moolenaar86b68352004-12-27 21:59:20 +00007863 alist_expand(fnum_list, used_alist_count);
Christian Brabandtfd916d62021-11-01 22:44:33 +00007864 do_cmdline_cmd(
7865 (char_u *)":legacy let &isf = g:SaVe_ISF|unlet g:SaVe_ISF");
7866 do_cmdline_cmd(
7867 (char_u *)":legacy let &wig = g:SaVe_WIG|unlet g:SaVe_WIG");
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007868 }
7869
Bram Moolenaar0f873732019-12-05 20:28:46 +01007870 // If wildcard expansion failed, we are editing the first file of the
7871 // arglist and there is no file name: Edit the first argument now.
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007872 if (curwin->w_arg_idx == 0 && curbuf->b_fname == NULL)
7873 {
7874 do_cmdline_cmd((char_u *)":rewind");
Bram Moolenaar05268152021-11-18 18:53:45 +00007875 if (GARGCOUNT == 1 && used_file_full_path
7876 && vim_chdirfile(alist_name(&GARGLIST[0]), "drop") == OK)
7877 last_chdir_reason = "drop";
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007878 }
Bram Moolenaar86b68352004-12-27 21:59:20 +00007879
7880 set_alist_count();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007881}
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007882
7883 int
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02007884mch_setenv(char *var, char *value, int x UNUSED)
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007885{
7886 char_u *envbuf;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007887 WCHAR *p;
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007888
Bram Moolenaar964b3742019-05-24 18:54:09 +02007889 envbuf = alloc(STRLEN(var) + STRLEN(value) + 2);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007890 if (envbuf == NULL)
7891 return -1;
7892
7893 sprintf((char *)envbuf, "%s=%s", var, value);
7894
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007895 p = enc_to_utf16(envbuf, NULL);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007896
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007897 vim_free(envbuf);
7898 if (p == NULL)
7899 return -1;
7900 _wputenv(p);
Bram Moolenaara12a1612019-01-24 16:39:02 +01007901#ifdef libintl_wputenv
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007902 libintl_wputenv(p);
Bram Moolenaara12a1612019-01-24 16:39:02 +01007903#endif
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007904 // Unlike Un*x systems, we can free the string for _wputenv().
7905 vim_free(p);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007906
7907 return 0;
7908}
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007909
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007910/*
7911 * Support for 256 colors and 24-bit colors was added in Windows 10
7912 * version 1703 (Creators update).
7913 */
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007914#define VTP_FIRST_SUPPORT_BUILD MAKE_VER(10, 0, 15063)
7915
7916/*
7917 * Support for pseudo-console (ConPTY) was added in windows 10
Bram Moolenaar57da6982019-09-13 22:30:11 +02007918 * version 1809 (October 2018 update).
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007919 */
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01007920#define CONPTY_FIRST_SUPPORT_BUILD MAKE_VER(10, 0, 17763)
Bram Moolenaar57da6982019-09-13 22:30:11 +02007921
7922/*
7923 * ConPTY differences between versions, need different logic.
7924 * version 1903 (May 2019 update).
7925 */
7926#define CONPTY_1903_BUILD MAKE_VER(10, 0, 18362)
7927
7928/*
Bram Moolenaar36e7a822019-11-13 21:49:24 +01007929 * version 1909 (November 2019 update).
7930 */
7931#define CONPTY_1909_BUILD MAKE_VER(10, 0, 18363)
7932
7933/*
Bram Moolenaar7ed8f592020-04-28 20:44:42 +02007934 * Stay ahead of the next update, and when it's done, fix this.
7935 * version ? (2020 update, temporarily use the build number of insider preview)
7936 */
7937#define CONPTY_NEXT_UPDATE_BUILD MAKE_VER(10, 0, 19587)
7938
7939/*
Bram Moolenaar57da6982019-09-13 22:30:11 +02007940 * Confirm until this version. Also the logic changes.
7941 * insider preview.
7942 */
Bram Moolenaar4c063dd2019-10-04 21:29:12 +02007943#define CONPTY_INSIDER_BUILD MAKE_VER(10, 0, 18995)
Bram Moolenaar57da6982019-09-13 22:30:11 +02007944
7945/*
7946 * Not stable now.
7947 */
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01007948#define CONPTY_STABLE_BUILD MAKE_VER(10, 0, 32767) // T.B.D.
Christopher Plewright38804d62022-11-09 23:55:52 +00007949// Note: Windows 11 (build >= 22000 means Windows 11, even though the major
7950// version says 10!)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007951
7952 static void
7953vtp_flag_init(void)
7954{
7955 DWORD ver = get_build_number();
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007956#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007957 DWORD mode;
7958 HANDLE out;
7959
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007960# ifdef VIMDLL
7961 if (!gui.in_use)
7962# endif
7963 {
7964 out = GetStdHandle(STD_OUTPUT_HANDLE);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007965
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007966 vtp_working = (ver >= VTP_FIRST_SUPPORT_BUILD) ? 1 : 0;
7967 GetConsoleMode(out, &mode);
7968 mode |= (ENABLE_PROCESSED_OUTPUT | ENABLE_VIRTUAL_TERMINAL_PROCESSING);
7969 if (SetConsoleMode(out, mode) == 0)
7970 vtp_working = 0;
7971 }
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007972#endif
7973
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007974 if (ver >= CONPTY_FIRST_SUPPORT_BUILD)
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01007975 conpty_working = 1;
7976 if (ver >= CONPTY_STABLE_BUILD)
7977 conpty_stable = 1;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007978
Bram Moolenaar57da6982019-09-13 22:30:11 +02007979 if (ver <= CONPTY_INSIDER_BUILD)
7980 conpty_type = 3;
Bram Moolenaar36e7a822019-11-13 21:49:24 +01007981 if (ver <= CONPTY_1909_BUILD)
7982 conpty_type = 2;
Bram Moolenaar57da6982019-09-13 22:30:11 +02007983 if (ver <= CONPTY_1903_BUILD)
7984 conpty_type = 2;
7985 if (ver < CONPTY_FIRST_SUPPORT_BUILD)
7986 conpty_type = 1;
Bram Moolenaar7ed8f592020-04-28 20:44:42 +02007987
7988 if (ver >= CONPTY_NEXT_UPDATE_BUILD)
7989 conpty_fix_type = 1;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007990}
7991
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007992#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL) || defined(PROTO)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007993
7994 static void
7995vtp_init(void)
7996{
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007997# ifdef FEAT_TERMGUICOLORS
Christopher Plewright38804d62022-11-09 23:55:52 +00007998 if (!vtp_working)
Yasuhiro Matsumotoe42c8da2022-09-01 11:31:45 +01007999 {
Christopher Plewright38804d62022-11-09 23:55:52 +00008000 CONSOLE_SCREEN_BUFFER_INFOEX csbi;
8001 csbi.cbSize = sizeof(csbi);
8002 GetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
8003 save_console_bg_rgb = (guicolor_T)csbi.ColorTable[g_color_index_bg];
8004 save_console_fg_rgb = (guicolor_T)csbi.ColorTable[g_color_index_fg];
8005 store_console_bg_rgb = save_console_bg_rgb;
8006 store_console_fg_rgb = save_console_fg_rgb;
8007
Yasuhiro Matsumotoe42c8da2022-09-01 11:31:45 +01008008 COLORREF bg;
8009 bg = (COLORREF)csbi.ColorTable[g_color_index_bg];
8010 bg = (GetRValue(bg) << 16) | (GetGValue(bg) << 8) | GetBValue(bg);
8011 default_console_color_bg = bg;
Christopher Plewright38804d62022-11-09 23:55:52 +00008012
8013 COLORREF fg;
8014 fg = (COLORREF)csbi.ColorTable[g_color_index_fg];
8015 fg = (GetRValue(fg) << 16) | (GetGValue(fg) << 8) | GetBValue(fg);
8016 default_console_color_fg = fg;
Yasuhiro Matsumotoe42c8da2022-09-01 11:31:45 +01008017 }
Bram Moolenaarc4568ab2018-11-16 16:21:05 +01008018# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008019
8020 set_console_color_rgb();
8021}
8022
8023 static void
8024vtp_exit(void)
8025{
Bram Moolenaardf543822020-01-30 11:53:59 +01008026 restore_console_color_rgb();
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008027}
8028
Bram Moolenaar06b7b582020-05-30 17:49:25 +02008029 int
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008030vtp_printf(
8031 char *format,
8032 ...)
8033{
8034 char_u buf[100];
8035 va_list list;
8036 DWORD result;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008037 int len;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008038
8039 va_start(list, format);
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008040 len = vim_vsnprintf((char *)buf, 100, (char *)format, list);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008041 va_end(list);
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008042 WriteConsoleA(g_hConOut, buf, (DWORD)len, &result, NULL);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008043 return (int)result;
8044}
8045
8046 static void
8047vtp_sgr_bulk(
8048 int arg)
8049{
8050 int args[1];
8051
8052 args[0] = arg;
8053 vtp_sgr_bulks(1, args);
8054}
8055
K.Takata6e1d31e2022-02-03 13:05:32 +00008056# define FAST256(x) \
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008057 if ((*p-- = "0123456789"[(n = x % 10)]) \
8058 && x >= 10 && (*p-- = "0123456789"[((m = x % 100) - n) / 10]) \
8059 && x >= 100 && (*p-- = "012"[((x & 0xff) - m) / 100]));
8060
K.Takata6e1d31e2022-02-03 13:05:32 +00008061# define FAST256CASE(x) \
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008062 case x: \
8063 FAST256(newargs[x - 1]);
8064
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008065 static void
8066vtp_sgr_bulks(
8067 int argc,
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008068 int *args)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008069{
K.Takata6e1d31e2022-02-03 13:05:32 +00008070# define MAXSGR 16
8071# define SGRBUFSIZE 2 + 4 * MAXSGR + 1 // '\033[' + SGR + 'm'
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008072 char_u buf[SGRBUFSIZE];
8073 char_u *p;
8074 int in, out;
8075 int newargs[16];
8076 static int sgrfgr = -1, sgrfgg, sgrfgb;
8077 static int sgrbgr = -1, sgrbgg, sgrbgb;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008078
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008079 if (argc == 0)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008080 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008081 sgrfgr = sgrbgr = -1;
K.Takatadf5320c2022-09-01 13:20:16 +01008082 vtp_printf("\033[m");
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008083 return;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008084 }
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02008085
8086 in = out = 0;
8087 while (in < argc)
8088 {
8089 int s = args[in];
8090 int copylen = 1;
8091
8092 if (s == 38)
8093 {
8094 if (argc - in >= 5 && args[in + 1] == 2)
8095 {
8096 if (sgrfgr == args[in + 2] && sgrfgg == args[in + 3]
8097 && sgrfgb == args[in + 4])
8098 {
8099 in += 5;
8100 copylen = 0;
8101 }
8102 else
8103 {
8104 sgrfgr = args[in + 2];
8105 sgrfgg = args[in + 3];
8106 sgrfgb = args[in + 4];
8107 copylen = 5;
8108 }
8109 }
8110 else if (argc - in >= 3 && args[in + 1] == 5)
8111 {
8112 sgrfgr = -1;
8113 copylen = 3;
8114 }
8115 }
8116 else if (s == 48)
8117 {
8118 if (argc - in >= 5 && args[in + 1] == 2)
8119 {
8120 if (sgrbgr == args[in + 2] && sgrbgg == args[in + 3]
8121 && sgrbgb == args[in + 4])
8122 {
8123 in += 5;
8124 copylen = 0;
8125 }
8126 else
8127 {
8128 sgrbgr = args[in + 2];
8129 sgrbgg = args[in + 3];
8130 sgrbgb = args[in + 4];
8131 copylen = 5;
8132 }
8133 }
8134 else if (argc - in >= 3 && args[in + 1] == 5)
8135 {
8136 sgrbgr = -1;
8137 copylen = 3;
8138 }
8139 }
8140 else if (30 <= s && s <= 39)
8141 sgrfgr = -1;
8142 else if (90 <= s && s <= 97)
8143 sgrfgr = -1;
8144 else if (40 <= s && s <= 49)
8145 sgrbgr = -1;
8146 else if (100 <= s && s <= 107)
8147 sgrbgr = -1;
8148 else if (s == 0)
8149 sgrfgr = sgrbgr = -1;
8150
8151 while (copylen--)
8152 newargs[out++] = args[in++];
8153 }
8154
8155 p = &buf[sizeof(buf) - 1];
8156 *p-- = 'm';
8157
8158 switch (out)
8159 {
8160 int n, m;
8161 DWORD r;
8162
8163 FAST256CASE(16);
8164 *p-- = ';';
8165 FAST256CASE(15);
8166 *p-- = ';';
8167 FAST256CASE(14);
8168 *p-- = ';';
8169 FAST256CASE(13);
8170 *p-- = ';';
8171 FAST256CASE(12);
8172 *p-- = ';';
8173 FAST256CASE(11);
8174 *p-- = ';';
8175 FAST256CASE(10);
8176 *p-- = ';';
8177 FAST256CASE(9);
8178 *p-- = ';';
8179 FAST256CASE(8);
8180 *p-- = ';';
8181 FAST256CASE(7);
8182 *p-- = ';';
8183 FAST256CASE(6);
8184 *p-- = ';';
8185 FAST256CASE(5);
8186 *p-- = ';';
8187 FAST256CASE(4);
8188 *p-- = ';';
8189 FAST256CASE(3);
8190 *p-- = ';';
8191 FAST256CASE(2);
8192 *p-- = ';';
8193 FAST256CASE(1);
8194 *p-- = '[';
8195 *p = '\033';
8196 WriteConsoleA(g_hConOut, p, (DWORD)(&buf[SGRBUFSIZE] - p), &r, NULL);
8197 default:
8198 break;
8199 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008200}
8201
Bram Moolenaar06b7b582020-05-30 17:49:25 +02008202 static void
8203wt_init(void)
8204{
8205 wt_working = (mch_getenv("WT_SESSION") != NULL);
8206}
8207
8208 int
8209use_wt(void)
8210{
8211 return USE_WT;
8212}
8213
Bram Moolenaar8a938af2018-05-01 17:30:41 +02008214# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02008215 static int
8216ctermtoxterm(
8217 int cterm)
8218{
Bram Moolenaar9894e392018-05-05 14:29:06 +02008219 char_u r, g, b, idx;
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02008220
8221 cterm_color2rgb(cterm, &r, &g, &b, &idx);
8222 return (((int)r << 16) | ((int)g << 8) | (int)b);
8223}
Bram Moolenaar8a938af2018-05-01 17:30:41 +02008224# endif
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02008225
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008226 static void
8227set_console_color_rgb(void)
8228{
8229# ifdef FEAT_TERMGUICOLORS
K.Takata27b53be2022-09-18 12:25:49 +01008230 CONSOLE_SCREEN_BUFFER_INFOEX csbi;
Bram Moolenaara050b942019-12-02 21:35:31 +01008231 guicolor_T fg, bg;
8232 int ctermfg, ctermbg;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008233
Christopher Plewright38804d62022-11-09 23:55:52 +00008234 if (!vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008235 return;
8236
Bram Moolenaara050b942019-12-02 21:35:31 +01008237 get_default_console_color(&ctermfg, &ctermbg, &fg, &bg);
8238
Christopher Plewright38804d62022-11-09 23:55:52 +00008239 if (p_tgc || t_colors >= 256)
Bram Moolenaar06b7b582020-05-30 17:49:25 +02008240 {
8241 term_fg_rgb_color(fg);
8242 term_bg_rgb_color(bg);
8243 return;
8244 }
8245
Christopher Plewright38804d62022-11-09 23:55:52 +00008246 if (!conpty_working)
8247 {
8248 fg = (GetRValue(fg) << 16) | (GetGValue(fg) << 8) | GetBValue(fg);
8249 bg = (GetRValue(bg) << 16) | (GetGValue(bg) << 8) | GetBValue(bg);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008250
Christopher Plewright38804d62022-11-09 23:55:52 +00008251 csbi.cbSize = sizeof(csbi);
8252 GetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008253
Christopher Plewright38804d62022-11-09 23:55:52 +00008254 csbi.cbSize = sizeof(csbi);
8255 csbi.srWindow.Right += 1;
8256 csbi.srWindow.Bottom += 1;
8257 store_console_bg_rgb = csbi.ColorTable[g_color_index_bg];
8258 store_console_fg_rgb = csbi.ColorTable[g_color_index_fg];
8259 csbi.ColorTable[g_color_index_bg] = (COLORREF)bg;
8260 csbi.ColorTable[g_color_index_fg] = (COLORREF)fg;
8261 SetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
8262 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008263# endif
8264}
8265
Bram Moolenaara050b942019-12-02 21:35:31 +01008266# if defined(FEAT_TERMGUICOLORS) || defined(PROTO)
8267 void
8268get_default_console_color(
8269 int *cterm_fg,
8270 int *cterm_bg,
8271 guicolor_T *gui_fg,
8272 guicolor_T *gui_bg)
8273{
8274 int id;
8275 guicolor_T guifg = INVALCOLOR;
8276 guicolor_T guibg = INVALCOLOR;
8277 int ctermfg = 0;
8278 int ctermbg = 0;
Christopher Plewright38804d62022-11-09 23:55:52 +00008279 int dummynull = 0;
Bram Moolenaara050b942019-12-02 21:35:31 +01008280
8281 id = syn_name2id((char_u *)"Normal");
8282 if (id > 0 && p_tgc)
8283 syn_id2colors(id, &guifg, &guibg);
8284 if (guifg == INVALCOLOR)
8285 {
8286 ctermfg = -1;
8287 if (id > 0)
Christopher Plewright38804d62022-11-09 23:55:52 +00008288 syn_id2cterm_bg(id, &ctermfg, &dummynull);
8289 if (vtp_working)
8290 {
8291 cterm_normal_fg_gui_color = guifg =
8292 ctermfg != -1 ? ctermtoxterm(ctermfg) : INVALCOLOR;
8293 ctermfg = ctermfg < 0 ? 0 : ctermfg;
8294 }
8295 else
8296 {
8297 guifg = ctermfg != -1 ? ctermtoxterm(ctermfg)
Bram Moolenaara050b942019-12-02 21:35:31 +01008298 : default_console_color_fg;
Christopher Plewright38804d62022-11-09 23:55:52 +00008299 cterm_normal_fg_gui_color = guifg;
8300 ctermfg = ctermfg < 0 ? 0 : ctermfg;
8301 }
Bram Moolenaara050b942019-12-02 21:35:31 +01008302 }
8303 if (guibg == INVALCOLOR)
8304 {
8305 ctermbg = -1;
8306 if (id > 0)
Christopher Plewright38804d62022-11-09 23:55:52 +00008307 syn_id2cterm_bg(id, &dummynull, &ctermbg);
8308 if (vtp_working)
Yasuhiro Matsumotoe42c8da2022-09-01 11:31:45 +01008309 {
8310 cterm_normal_bg_gui_color = guibg =
Yasuhiro Matsumotoaa04e1b2022-05-07 14:09:19 +01008311 ctermbg != -1 ? ctermtoxterm(ctermbg) : INVALCOLOR;
Yasuhiro Matsumotoe42c8da2022-09-01 11:31:45 +01008312 if (ctermbg < 0)
8313 ctermbg = 0;
8314 }
K.Takatae53a0d42022-09-05 21:45:11 +01008315 else
8316 {
8317 guibg = ctermbg != -1 ? ctermtoxterm(ctermbg)
8318 : default_console_color_bg;
8319 cterm_normal_bg_gui_color = guibg;
8320 ctermbg = ctermbg < 0 ? 0 : ctermbg;
8321 }
Bram Moolenaara050b942019-12-02 21:35:31 +01008322 }
8323
8324 *cterm_fg = ctermfg;
8325 *cterm_bg = ctermbg;
8326 *gui_fg = guifg;
8327 *gui_bg = guibg;
8328}
8329# endif
8330
Bram Moolenaardf543822020-01-30 11:53:59 +01008331/*
8332 * Set the console colors to the original colors or the last set colors.
8333 */
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008334 static void
8335reset_console_color_rgb(void)
8336{
8337# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008338
Christopher Plewright38804d62022-11-09 23:55:52 +00008339 if (vtp_working)
Bram Moolenaar06b7b582020-05-30 17:49:25 +02008340 return;
8341
Christopher Plewright38804d62022-11-09 23:55:52 +00008342 CONSOLE_SCREEN_BUFFER_INFOEX csbi;
8343
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008344 csbi.cbSize = sizeof(csbi);
K.Takata27b53be2022-09-18 12:25:49 +01008345 GetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008346
8347 csbi.cbSize = sizeof(csbi);
8348 csbi.srWindow.Right += 1;
8349 csbi.srWindow.Bottom += 1;
Bram Moolenaardf543822020-01-30 11:53:59 +01008350 csbi.ColorTable[g_color_index_bg] = (COLORREF)store_console_bg_rgb;
8351 csbi.ColorTable[g_color_index_fg] = (COLORREF)store_console_fg_rgb;
K.Takata27b53be2022-09-18 12:25:49 +01008352 SetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaardf543822020-01-30 11:53:59 +01008353# endif
8354}
8355
8356/*
8357 * Set the console colors to the original colors.
8358 */
8359 static void
8360restore_console_color_rgb(void)
8361{
8362# ifdef FEAT_TERMGUICOLORS
Christopher Plewright38804d62022-11-09 23:55:52 +00008363 if (vtp_working)
8364 return;
8365
K.Takata27b53be2022-09-18 12:25:49 +01008366 CONSOLE_SCREEN_BUFFER_INFOEX csbi;
Bram Moolenaardf543822020-01-30 11:53:59 +01008367
8368 csbi.cbSize = sizeof(csbi);
K.Takata27b53be2022-09-18 12:25:49 +01008369 GetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaardf543822020-01-30 11:53:59 +01008370
8371 csbi.cbSize = sizeof(csbi);
8372 csbi.srWindow.Right += 1;
8373 csbi.srWindow.Bottom += 1;
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02008374 csbi.ColorTable[g_color_index_bg] = (COLORREF)save_console_bg_rgb;
8375 csbi.ColorTable[g_color_index_fg] = (COLORREF)save_console_fg_rgb;
K.Takata27b53be2022-09-18 12:25:49 +01008376 SetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008377# endif
8378}
8379
8380 void
8381control_console_color_rgb(void)
8382{
Christopher Plewright38804d62022-11-09 23:55:52 +00008383 if (vtp_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008384 set_console_color_rgb();
8385 else
8386 reset_console_color_rgb();
8387}
8388
8389 int
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008390use_vtp(void)
8391{
8392 return USE_VTP;
8393}
8394
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02008395 int
8396is_term_win32(void)
8397{
8398 return T_NAME != NULL && STRCMP(T_NAME, "win32") == 0;
8399}
8400
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008401 int
8402has_vtp_working(void)
8403{
8404 return vtp_working;
8405}
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01008406
Bram Moolenaar6902c0e2019-02-16 14:07:37 +01008407#endif
8408
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01008409 int
8410has_conpty_working(void)
8411{
8412 return conpty_working;
8413}
8414
8415 int
Bram Moolenaar57da6982019-09-13 22:30:11 +02008416get_conpty_type(void)
8417{
8418 return conpty_type;
8419}
8420
8421 int
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01008422is_conpty_stable(void)
8423{
8424 return conpty_stable;
8425}
Bram Moolenaar78d21da2019-02-17 15:00:52 +01008426
Bram Moolenaar7ed8f592020-04-28 20:44:42 +02008427 int
8428get_conpty_fix_type(void)
8429{
8430 return conpty_fix_type;
8431}
8432
Bram Moolenaarafde13b2019-04-28 19:46:49 +02008433#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL) || defined(PROTO)
Bram Moolenaar78d21da2019-02-17 15:00:52 +01008434 void
8435resize_console_buf(void)
8436{
8437 CONSOLE_SCREEN_BUFFER_INFO csbi;
8438 COORD coord;
8439 SMALL_RECT newsize;
8440
8441 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
8442 {
8443 coord.X = SRWIDTH(csbi.srWindow);
8444 coord.Y = SRHEIGHT(csbi.srWindow);
8445 SetConsoleScreenBufferSize(g_hConOut, coord);
8446
8447 newsize.Left = 0;
8448 newsize.Top = 0;
8449 newsize.Right = coord.X - 1;
8450 newsize.Bottom = coord.Y - 1;
8451 SetConsoleWindowInfo(g_hConOut, TRUE, &newsize);
8452
8453 SetConsoleScreenBufferSize(g_hConOut, coord);
8454 }
8455}
8456#endif
Martin Tournoij1a3e5742021-07-24 13:57:29 +02008457
8458 char *
8459GetWin32Error(void)
8460{
K.Takatad68b2fc2022-02-12 11:18:37 +00008461 static char *oldmsg = NULL;
Martin Tournoij1a3e5742021-07-24 13:57:29 +02008462 char *msg = NULL;
K.Takatad68b2fc2022-02-12 11:18:37 +00008463
Martin Tournoij1a3e5742021-07-24 13:57:29 +02008464 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER|FORMAT_MESSAGE_FROM_SYSTEM,
8465 NULL, GetLastError(), 0, (LPSTR)&msg, 0, NULL);
K.Takatad68b2fc2022-02-12 11:18:37 +00008466 if (oldmsg != NULL)
8467 LocalFree(oldmsg);
Martin Tournoij1a3e5742021-07-24 13:57:29 +02008468 if (msg != NULL)
8469 {
8470 // remove trailing \r\n
8471 char *pcrlf = strstr(msg, "\r\n");
8472 if (pcrlf != NULL)
8473 *pcrlf = '\0';
K.Takatad68b2fc2022-02-12 11:18:37 +00008474 oldmsg = msg;
Martin Tournoij1a3e5742021-07-24 13:57:29 +02008475 }
8476 return msg;
8477}
Paul Ollis65745772022-06-05 16:55:54 +01008478
8479#if defined(FEAT_RELTIME) || defined(PROTO)
8480static HANDLE timer_handle;
8481static int timer_active = FALSE;
8482
8483/*
8484 * Calls to start_timeout alternate the return value pointer between the two
8485 * entries in timeout_flags. If the previously active timeout is very close to
8486 * expiring when start_timeout() is called then a race condition means that the
8487 * set_flag() function may still be invoked after the previous timer is
8488 * deleted. Ping-ponging between the two flags prevents this causing 'fake'
8489 * timeouts.
8490 */
Bram Moolenaar155f2d12022-06-20 13:38:33 +01008491static sig_atomic_t timeout_flags[2];
8492static int timeout_flag_idx = 0;
8493static sig_atomic_t *timeout_flag = &timeout_flags[0];
Paul Ollis65745772022-06-05 16:55:54 +01008494
8495
8496 static void CALLBACK
Bram Moolenaar35d7a2f2022-06-09 20:53:54 +01008497set_flag(void *param, BOOLEAN unused2 UNUSED)
Paul Ollis65745772022-06-05 16:55:54 +01008498{
8499 int *timeout_flag = (int *)param;
8500
8501 *timeout_flag = TRUE;
8502}
8503
8504/*
8505 * Stop any active timeout.
8506 */
8507 void
8508stop_timeout(void)
8509{
8510 if (timer_active)
8511 {
Christopher Plewright2a46f812022-10-16 19:47:45 +01008512 BOOL ret = DeleteTimerQueueTimer(NULL, timer_handle, NULL);
Paul Ollis65745772022-06-05 16:55:54 +01008513 timer_active = FALSE;
8514 if (!ret && GetLastError() != ERROR_IO_PENDING)
8515 {
8516 semsg(_(e_could_not_clear_timeout_str), GetWin32Error());
8517 }
8518 }
8519 *timeout_flag = FALSE;
8520}
8521
8522/*
8523 * Start the timeout timer.
8524 *
8525 * The period is defined in milliseconds.
8526 *
8527 * The return value is a pointer to a flag that is initialised to 0. If the
8528 * timeout expires, the flag is set to 1. This will only return pointers to
8529 * static memory; i.e. any pointer returned by this function may always be
8530 * safely dereferenced.
8531 *
8532 * This function is not expected to fail, but if it does it still returns a
8533 * valid flag pointer; the flag will remain stuck at zero.
8534 */
Bram Moolenaar155f2d12022-06-20 13:38:33 +01008535 volatile sig_atomic_t *
Paul Ollis65745772022-06-05 16:55:54 +01008536start_timeout(long msec)
8537{
Paul Ollis65745772022-06-05 16:55:54 +01008538 BOOL ret;
8539
Bram Moolenaar1f30caf2022-06-19 14:36:35 +01008540 timeout_flag = &timeout_flags[timeout_flag_idx];
Paul Ollis65745772022-06-05 16:55:54 +01008541
8542 stop_timeout();
8543 ret = CreateTimerQueueTimer(
8544 &timer_handle, NULL, set_flag, timeout_flag,
8545 (DWORD)msec, 0, WT_EXECUTEDEFAULT);
8546 if (!ret)
8547 {
8548 semsg(_(e_could_not_set_timeout_str), GetWin32Error());
8549 }
8550 else
8551 {
Bram Moolenaar1f30caf2022-06-19 14:36:35 +01008552 timeout_flag_idx = (timeout_flag_idx + 1) % 2;
Paul Ollis65745772022-06-05 16:55:54 +01008553 timer_active = TRUE;
8554 *timeout_flag = FALSE;
8555 }
8556 return timeout_flag;
8557}
8558#endif